diff --git a/Cargo.toml b/Cargo.toml index 562023b3..5d957ba6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -120,7 +120,7 @@ wasm-bindgen-futures = "0.4" js-sys = "0.3" # In the browser the page's language (navigator.languages) is the system's. sys-locale = { version = "0.3", features = ["js"] } -web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] } +web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] } [build-dependencies] # Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets. diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 196de0bd..4df45cf5 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -222,6 +222,7 @@ pub(crate) mod base64_bytes { } } +pub use base64_bytes::decode as base64_decode; pub use base64_bytes::encode as base64_encode; #[cfg(test)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8e92b3..157e233d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -26,7 +26,7 @@ pub mod sample; pub mod sound; pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; -pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; +pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; pub use easing::Easing; pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; diff --git a/src/a11y.rs b/src/a11y.rs index 6f427639..328710a8 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 3abc78d5..b70802a9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -420,6 +420,12 @@ pub struct App { heard: Option<(usize, u32)>, /// The panel Ctrl+F6 last moved focus to (where the next press continues from). pub last_panel: Option, + /// The start screen, while it is up (ADR 0059). + pub start: Option, + /// Files dragged over and dropped onto the window (ADR 0059). + pub drop: crate::drop::DropState, + /// Recent files' pictures for the start screen. + pub thumbs: crate::recent::Thumbs, } /// How finished this version is, shown next to the version number (docs/release.md). English: @@ -471,6 +477,8 @@ impl App { let _ = anicraft_engine::text::Fonts::get(); }); let mut session = session; + // Open Recent is the session's list, kept in the preferences (ADR 0059). + session.recent = prefs.recent.clone(); // The editor draws as Animate does: merge drawing, until Object Drawing (J) is switched on. session.style.object_drawing = false; let mut app = App { @@ -564,6 +572,9 @@ impl App { audio_clock: false, heard: None, last_panel: None, + start: None, + drop: Default::default(), + thumbs: Default::default(), }; app.apply_prefs(ctx); app.decode_sounds(); @@ -767,6 +778,18 @@ impl App { self.run("scene.select", json!({"scene": last})); } Some("files") => self.show_files = true, + Some("start") => { + // The start screen with sample recent files (one pinned, one missing). + crate::start::open(self); + if self.shot.is_some() { + crate::recent::sample_entries(self); + } + } + Some("drop") => self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Stage)), // i18n-exempt: a sample file name + Some("droplibrary") => { + self.run("library.new_folder", json!({"name": "Backgrounds"})); // i18n-exempt: a sample folder name + self.drop.preview = Some((vec![PathBuf::from("sunset.png")], crate::drop::PreviewAt::Library)); // i18n-exempt: a sample file name + } Some("recovery") => { // Work left behind by a session that didn't close cleanly (sample entries // unless ANICRAFT_RECOVERY_DIR holds real ones). @@ -1479,7 +1502,15 @@ impl App { /// new document resets. `selected` is how many elements were selected before it ran. pub(crate) fn announce(&mut self, id: &str, v: &Value, selected: usize) { match id { - "file.new" | "file.new_sample" | "file.open" => { + "file.new" | "file.new_sample" | "file.open" | "file.open_recent" => { + // The document is here: the start screen has done its job (ADR 0059). + self.start = None; + if id != "file.new" + && id != "file.new_sample" + && let Some(path) = self.s.path.clone().or_else(|| v["imported"].as_str().map(PathBuf::from)) + { + crate::recent::captured_on_open(self, &path); + } self.view.fit = true; self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); @@ -1487,7 +1518,7 @@ impl App { // An imported file: say what came across and what didn't, and that saving // makes a new .anicraft document. Some(r) => self.status_ok(tr!("{report} Save to keep it as an AniCraft document.", report = r)), - None => self.status_ok(if id == "file.open" { tr!("Opened") } else { tr!("New document") }), + None => self.status_ok(if id == "file.open" || id == "file.open_recent" { tr!("Opened") } else { tr!("New document") }), } } "file.recover" => { @@ -1507,6 +1538,10 @@ impl App { self.status_ok(tr!("Discarded the autosaved copy")); } "file.save" | "file.save_as" => { + // The start screen's picture of it (ADR 0059). + if let Some(saved) = v["saved"].as_str() { + crate::recent::capture(self, std::path::Path::new(saved)); + } // In a browser the file goes to the downloads (ADR 0036). let path = v["saved"].as_str().unwrap_or(""); self.status_ok(if platform::WEB { tr!("Saved {path} to your downloads", path = path) } else { tr!("Saved {path}", path = path) }); @@ -1649,6 +1684,11 @@ impl App { } return; } + if matches!(id, "file.open_recent" | "file.recent_list") { + // The recent files with their pictures (the File menu lists them too). + crate::start::open(self); + return; + } if id == "tween.add_hint" { crate::shape_hints::add(self); return; @@ -2150,7 +2190,7 @@ impl App { /// The app icon (`assets/app-icon/`; the PNG carries its rounded corners) as a texture, decoded on /// first use and kept in the context. 128 px stays sharp at 64 pt on a 2× display. -fn app_mark(ctx: &egui::Context) -> egui::TextureHandle { +pub(crate) fn app_mark(ctx: &egui::Context) -> egui::TextureHandle { const PNG: &[u8] = include_bytes!("../assets/app-icon/hicolor/128x128/apps/ai.storyteller.anicraft.png"); let id = egui::Id::new("anicraft-app-mark"); if let Some(tex) = ctx.data(|d| d.get_temp::(id)) { @@ -2237,7 +2277,22 @@ impl App { } let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2)); + crate::drop::begin_frame(self); egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui)); + if self.start.is_some() { + // The start screen takes the workspace's place (ADR 0059); the menus stay. + egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui)); + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| crate::start::show(self, ui)); + } else { + self.workspace(ui); + } + self.windows(&ctx); + } + + /// The editor's panels: tools, stage, timeline, properties and Library. + fn workspace(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2)); egui::Panel::top("edit_bar").exact_size(theme::TARGET + 8.0).frame(bar(T.panel)).show(ui, |ui| panels::edit_bar(self, ui)); egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui)); // Docks start at their usual size, but never take most of a small window or a large @@ -2252,7 +2307,12 @@ impl App { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(T.pasteboard)).show(ui, |ui| stage::show(self, ui)); crate::a11y::name_splitter(&ctx, "properties", tr!("Resize the right-hand panels")); crate::a11y::name_splitter(&ctx, "timeline", tr!("Resize the timeline")); + } + /// Dialogs and floating windows, the close guard and the end-of-frame upkeep. + fn windows(&mut self, ctx: &egui::Context) { + let ctx = ctx.clone(); + crate::drop::frame(self, &ctx); self.prompt_window(&ctx); crate::convert_symbol::window(self, &ctx); self.about_window(&ctx); @@ -2285,6 +2345,8 @@ impl App { // After this frame's edits: start a recovery copy when one is due (off this thread). autosave::tick(self, &ctx); + // Open Recent changed (an open, a save, a pin): into the preferences. + crate::recent::sync(self); // A browser asks before leaving a page with unsaved work (its close guard). platform::set_unsaved(self.s.is_dirty()); diff --git a/src/drop.rs b/src/drop.rs new file mode 100644 index 00000000..d7b94a56 --- /dev/null +++ b/src/drop.rs @@ -0,0 +1,538 @@ +//! Files dropped onto the window from the desktop or a browser (ADR 0059). Documents open (the +//! unsaved-changes guard as with File › Open); drawings, images and sounds dropped on the stage +//! go onto the active layer at the playhead where they were dropped, and dropped on the Library +//! go into it, into the folder under the pointer. While files are dragged over the window a +//! highlight shows where they will land. The routing is `anicraft_engine::cmds_drop::route`; +//! the import is the `file.drop` command, one undo step. +//! +//! Where a drop lands needs the pointer. Browsers report it while dragging (our own `dragover` +//! listener, `web::drag_pos`), but winit 0.30 gives no position with dragged files, and Windows +//! and macOS send no pointer moves during a drag. So a drop waits a moment for the pointer's +//! first move after it (the system sends one as the drag ends); without one it lands at the +//! centre of the view, and says so. + +use crate::app::App; +use crate::theme::{T, Type, color, font}; +use anicraft_engine::cmds_drop::{DropAction, DropKind, DropTarget, kind_of, route}; +use anicraft_engine::doc::FolderId; +use egui::{Pos2, Rect, Stroke, StrokeKind, vec2}; +use serde_json::json; +use std::path::{Path, PathBuf}; + +/// How long a drop waits for the pointer to say where it is, in seconds. +const WAIT_FOR_POINTER: f64 = 0.35; + +/// Where the stage was drawn this frame and how it maps to the edited space. +#[derive(Clone, Copy)] +pub struct StageGeo { + pub canvas: Rect, + pub origin: Pos2, + pub zoom: f32, + /// Previewing through the camera: artwork edits are paused. + pub paused: bool, +} + +impl StageGeo { + pub fn to_stage(self, p: Pos2) -> (f32, f32) { + let z = self.zoom.max(1e-6); + ((p.x - self.origin.x) / z, (p.y - self.origin.y) / z) + } +} + +/// Where a drop at a point lands. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Spot { + /// On the stage, at this point of the edited space. + Stage(f32, f32), + /// On the Library, into this folder (`None`: the top level). + Library(Option), + /// Somewhere else on the window. + Window, + /// The start screen is up: documents open, nothing imports. + Start, + /// The pointer's position isn't known (a drop on the desktop without a pointer move). + Unknown, +} + +/// What a drop does, worked out from its files and where it landed. +#[derive(Debug, Default, PartialEq)] +pub struct Plan { + /// The document to open (the first one dropped). + pub open: Option, + /// Files to import, and where. + pub import: Vec, + pub to: Option, + /// Files left out, each with why (in the interface language). + pub left_out: Vec<(PathBuf, String)>, +} + +/// Why a file can't go there, in the interface language. +fn refusal(kind: DropKind, to: DropTarget, start: bool) -> String { + match kind { + DropKind::Unsupported => tr!("AniCraft opens .anicraft, .fla and .xfl documents, and imports SVG drawings, PNG and JPEG images, and WAV, Ogg and MP3 sounds").into(), + _ if start => tr!("Open or create a document first, then drop drawings, images and sounds on its stage").into(), + DropKind::Drawing if to == DropTarget::Library => tr!("SVG drawings import to the stage: drop it there").into(), + _ => tr!("Drop drawings, images and sounds on the stage to place them, or on the Library to add them").into(), + } +} + +/// What dropping `files` at `spot` does. One document opens (AniCraft has one document +/// window); other files in the same drop are left out then. +pub fn plan(files: &[PathBuf], spot: Spot) -> Plan { + let mut out = Plan::default(); + if let Some(doc) = files.iter().find(|f| kind_of(f) == DropKind::Document) { + out.open = Some(doc.clone()); + for f in files.iter().filter(|f| *f != doc) { + out.left_out.push((f.clone(), tr!("AniCraft opens one document at a time; drop the others on their own").into())); + } + return out; + } + let to = match spot { + Spot::Library(_) => DropTarget::Library, + // Without a position, the stage (at the centre of the view). + Spot::Stage(..) | Spot::Unknown => DropTarget::Stage, + Spot::Window | Spot::Start => DropTarget::Window, + }; + for f in files { + let kind = kind_of(f); + match route(kind, to) { + DropAction::ImportToStage | DropAction::ImportToLibrary => out.import.push(f.clone()), + DropAction::Open => {} + DropAction::Refuse(_) => out.left_out.push((f.clone(), refusal(kind, to, spot == Spot::Start))), + } + } + if !out.import.is_empty() { + out.to = Some(to); + } + out +} + +/// A drop waiting for the pointer (desktop), or for the browser to read the files (web). +struct Waiting { + files: Vec, + since: f64, + /// Browser files still being read, by ticket. + #[cfg(target_arch = "wasm32")] + ticket: Option, +} + +/// The drop state the window keeps between frames. +#[derive(Default)] +pub struct DropState { + /// Where the stage was drawn this frame (set by `stage::show`). + pub stage: Option, + waiting: Option, + /// The pointer moved while files were dragged over the window: its position is current. + tracked: bool, + /// A drag shown without one (screenshots and tests): the files and where they hover. + pub preview: Option<(Vec, PreviewAt)>, + #[cfg(target_arch = "wasm32")] + web_spot: Option, +} + +/// Where a previewed drag hovers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewAt { + Stage, + Library, +} + +/// Where a drop at `p` lands, from this frame's layout. +pub fn spot_at(app: &App, p: Option) -> Spot { + if app.start.is_some() { + return Spot::Start; + } + let Some(p) = p else { return Spot::Unknown }; + if let Some(folder) = app.library.drop_zone.folder_at(p) { + return Spot::Library(folder); + } + match app.drop.stage { + Some(g) if g.canvas.contains(p) => { + let (x, y) = g.to_stage(p); + Spot::Stage(x, y) + } + _ => Spot::Window, + } +} + +/// Before the panels draw: forget last frame's targets (a hidden panel takes nothing). +pub fn begin_frame(app: &mut App) { + app.drop.stage = None; + app.library.drop_zone = Default::default(); +} + +/// The pointer's position over a dragged file, if it is known. +fn drag_pointer(app: &App, ctx: &egui::Context) -> Option { + #[cfg(target_arch = "wasm32")] + { + let _ = app; + let z = ctx.zoom_factor().max(1e-3); + crate::web::drag_pos().map(|(x, y)| egui::pos2(x / z, y / z)) + } + #[cfg(not(target_arch = "wasm32"))] + { + if app.drop.tracked { ctx.input(|i| i.pointer.latest_pos()) } else { None } + } +} + +/// After the panels drew: the highlight while files hover, and what was dropped. +pub fn frame(app: &mut App, ctx: &egui::Context) { + let (hovered, dropped, moved, now) = ctx.input(|i| { + let hovered: Vec = i.raw.hovered_files.iter().map(|h| h.path.clone().unwrap_or_else(|| PathBuf::from(guess_name(&h.mime)))).collect(); + let moved = i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_))); + (hovered, i.raw.dropped_files.clone(), moved, i.time) + }); + if !hovered.is_empty() { + app.drop.tracked |= moved; + let p = drag_pointer(app, ctx); + highlight(app, ctx, &hovered, p); + } else if let Some((files, at)) = app.drop.preview.clone() { + let p = preview_point(app, at); + highlight(app, ctx, &files, p); + } + if !dropped.is_empty() { + let files: Vec = dropped.iter().take(anicraft_engine::cmds_drop::MAX_DROPPED).map(|f| f.path().to_path_buf()).collect(); + if dropped.len() > anicraft_engine::cmds_drop::MAX_DROPPED { + app.status_err(tr!("Drop at most {n} files at once", n = anicraft_engine::cmds_drop::MAX_DROPPED)); + app.drop.tracked = false; + return; + } + app.playing = false; + #[cfg(target_arch = "wasm32")] + { + // The browser said where the drop is; it reads the files' bytes, which arrive later. + let spot = spot_at(app, drag_pointer(app, ctx)); + let handles: Vec = dropped.iter().filter_map(|f| f.web_file().cloned()).collect(); + let ticket = crate::web::read_dropped(handles); + app.drop.web_spot = Some(spot); + app.drop.waiting = Some(Waiting { files, since: now, ticket: Some(ticket) }); + crate::web::clear_drag_pos(); + } + #[cfg(not(target_arch = "wasm32"))] + { + if app.drop.tracked { + let spot = spot_at(app, ctx.input(|i| i.pointer.latest_pos())); + run(app, &files, spot); + } else { + app.drop.waiting = Some(Waiting { files, since: now }); + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + } + app.drop.tracked = false; + return; + } + if hovered.is_empty() { + // A drag that left the window (or was cancelled) starts over. + app.drop.tracked = false; + } + resolve_waiting(app, ctx, moved, now); +} + +#[cfg(not(target_arch = "wasm32"))] +fn resolve_waiting(app: &mut App, ctx: &egui::Context, moved: bool, now: f64) { + let Some(w) = &app.drop.waiting else { return }; + let timed_out = now - w.since > WAIT_FOR_POINTER; + if !moved && !timed_out { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + return; + } + let Some(w) = app.drop.waiting.take() else { return }; + let p = if moved { ctx.input(|i| i.pointer.latest_pos()) } else { None }; + run(app, &w.files, spot_at(app, p)); +} + +#[cfg(target_arch = "wasm32")] +fn resolve_waiting(app: &mut App, _ctx: &egui::Context, _moved: bool, _now: f64) { + let Some((ticket, read)) = crate::web::take_dropped() else { return }; + if app.drop.waiting.as_ref().and_then(|w| w.ticket) != Some(ticket) { + return; + } + let (Some(w), Some(spot)) = (app.drop.waiting.take(), app.drop.web_spot.take()) else { return }; + let _ = WAIT_FOR_POINTER; + let mut files = Vec::new(); + for (name, data) in read { + // Only the name: the browser never says which folder a file came from. + let path = PathBuf::from(&name); + match data.and_then(|d| anicraft_engine::vfs::put(&path, d).map_err(|e| e.to_string())) { + Ok(()) => files.push(path), + Err(e) => app.status_err(tr!("Could not open {name}: {e}", name = name, e = e)), + } + } + let _ = w.files; + if !files.is_empty() { + run(app, &files, spot); + } +} + +/// Carries out a drop. +pub fn run(app: &mut App, files: &[PathBuf], spot: Spot) { + let plan = plan(files, spot); + let names = |list: &[PathBuf]| list.iter().map(|p| crate::recent::display_name(p)).collect::>().join(", "); + if let Some(doc) = &plan.open { + app.start = None; + app.request("file.open", json!({"path": doc.display().to_string()})); + if let Some((_, why)) = plan.left_out.first() { + app.status_ok(tr!("Left out {files}: {why}", files = names(&plan.left_out.iter().map(|(p, _)| p.clone()).collect::>()), why = why)); + } + return; + } + let Some(to) = plan.to else { + // Nothing to import: one message says why. + if let Some((p, why)) = plan.left_out.first() { + app.status_err(tr!("Can't import {file}: {why}", file = crate::recent::display_name(p), why = why)); + } + return; + }; + let paths: Vec = plan.import.iter().map(|p| p.display().to_string()).collect(); + let n = plan.import.len(); + let done = match (to, spot) { + (DropTarget::Library, Spot::Library(folder)) => { + let v = app.run("file.drop", json!({"paths": paths, "to": "library", "folder": folder.map(|f| f.0)})); + if let Some(f) = folder { + app.library.expanded.extend(app.s.doc.folder_chain(f)); + } + v.map(|v| { + // The last file added is the Library's current item. + let last = v["items"].as_array().and_then(|a| a.last()).cloned().unwrap_or_default(); + match (last["bitmap"].as_u64(), last["sound"].as_u64()) { + (Some(b), _) => app.library_sel = Some(anicraft_engine::doc::LibraryItem::Bitmap(anicraft_engine::doc::BitmapId(b))), + (None, Some(snd)) => app.library_sel = Some(anicraft_engine::doc::LibraryItem::Sound(anicraft_engine::doc::SoundId(snd))), + _ => {} + } + match folder.and_then(|f| app.s.doc.folder(f)).map(|f| f.name.clone()) { + Some(name) => trn!("Added {n} file to “{folder}” in the Library", "Added {n} files to “{folder}” in the Library", n, folder = name), + None => trn!("Added {n} file to the Library", "Added {n} files to the Library", n), + } + }) + } + _ => { + let geo = app.drop.stage; + if geo.is_some_and(|g| g.paused) { + app.status_ok(tr!("Previewing through the camera: artwork edits are paused. Turn off View › Preview Through Camera to edit.")); + return; + } + let (centred, (x, y)) = match spot { + Spot::Stage(x, y) => (false, (x, y)), + _ => { + let c = app.view_center_stage(); + let c = match app.s.edit_view() { + Some(v) if v.scale.abs() > 1e-6 => ((c.x - v.origin.x) / v.scale, (c.y - v.origin.y) / v.scale), + _ => (c.x, c.y), + }; + (true, c) + } + }; + let v = app.run("file.drop", json!({"paths": paths, "to": "stage", "x": x, "y": y})); + v.map(|_| { + let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default(); + let (frame, undo) = (app.s.frame + 1, app.undo_key()); + if centred { + trn!("Placed {n} file on {layer} at frame {frame}, in the middle of the view — {undo} to undo", "Placed {n} files on {layer} at frame {frame}, in the middle of the view — {undo} to undo", n, layer = layer, frame = frame, undo = undo) + } else { + trn!("Placed {n} file on {layer} at frame {frame} — {undo} to undo", "Placed {n} files on {layer} at frame {frame} — {undo} to undo", n, layer = layer, frame = frame, undo = undo) + } + }) + } + }; + if let Some(msg) = done { + app.decode_sounds(); + match plan.left_out.first() { + Some((p, why)) => app.status_ok(tr!("{done}. Left out {file}: {why}", done = msg, file = crate::recent::display_name(p), why = why)), + None => app.status_ok(msg), + } + } +} + +/// A name for a file the browser describes only by its type while it is dragged. +fn guess_name(mime: &str) -> &'static str { + match mime { + "image/svg+xml" => "drawing.svg", + "image/png" => "image.png", + "image/jpeg" => "image.jpg", + "audio/wav" | "audio/x-wav" | "audio/wave" => "sound.wav", + "audio/ogg" => "sound.ogg", + "audio/mpeg" | "audio/mp3" => "sound.mp3", + _ => "", + } +} + +/// Where a previewed drag hovers on screen: the stage's middle, or the Library's first folder. +fn preview_point(app: &App, at: PreviewAt) -> Option { + match at { + PreviewAt::Stage => app.drop.stage.map(|g| g.canvas.center() + vec2(-g.canvas.width() * 0.12, -g.canvas.height() * 0.08)), + PreviewAt::Library => app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).map(|(r, _)| r.center()), + } +} + +/// The drop highlight: what lands where, drawn over everything. +fn highlight(app: &App, ctx: &egui::Context, files: &[PathBuf], p: Option) { + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("file_drop"))); + let screen = ctx.content_rect().shrink(3.0); + // Only the names are known while a browser drags (and sometimes not even those). + let known: Vec<&PathBuf> = files.iter().filter(|f| !f.as_os_str().is_empty()).collect(); + let docs: Vec<&&PathBuf> = known.iter().filter(|f| kind_of(f) == DropKind::Document).collect(); + let stroke = Stroke::new(2.0, T.accent); + let label = |at: Pos2, text: String, ok: bool| { + let c = if ok { color(Type::Body) } else { T.error }; + let galley = painter.layout_no_wrap(text, font(Type::Label), c); + let r = Rect::from_min_size(at, vec2(galley.rect.width(), galley.rect.height())).expand(6.0); + // Kept on screen. + let r = r.translate(vec2((screen.right() - r.right()).min(0.0), (screen.bottom() - r.bottom()).min(0.0))); + painter.rect_filled(r, T.rc(), T.panel); + painter.rect_stroke(r, T.rc(), Stroke::new(1.0, if ok { T.accent } else { T.error }), StrokeKind::Inside); + painter.galley(r.min + vec2(6.0, 6.0), galley, c); + }; + if let Some(doc) = docs.first() { + painter.rect_stroke(screen, T.rc(), stroke, StrokeKind::Inside); + let text = if app.s.is_dirty() { tr!("Open {name} (you'll be asked about unsaved changes)", name = crate::recent::display_name(doc)) } else { tr!("Open {name}", name = crate::recent::display_name(doc)) }; + label(screen.center_top() + vec2(-120.0, 12.0), text, true); + return; + } + let spot = spot_at(app, p); + let what = match known.len() { + 0 => tr!("these files").to_string(), + 1 => crate::recent::display_name(known[0]), + n => trn!("{n} file", "{n} files", n), + }; + let fits = |to: DropTarget| known.iter().all(|f| matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary)); + match (spot, p) { + (Spot::Stage(..), Some(p)) => { + if let Some(g) = app.drop.stage { + painter.rect_stroke(g.canvas.shrink(1.0), crate::theme::SQUARE, stroke, StrokeKind::Inside); + } + let r = 8.0; + painter.line_segment([p - vec2(r, 0.0), p + vec2(r, 0.0)], Stroke::new(1.5, T.accent)); + painter.line_segment([p - vec2(0.0, r), p + vec2(0.0, r)], Stroke::new(1.5, T.accent)); + let ok = fits(DropTarget::Stage); + let layer = app.s.active_layer().map(|l| l.name.clone()).unwrap_or_default(); + let text = if ok { tr!("Place {what} on {layer} at frame {frame}", what = what, layer = layer, frame = app.s.frame + 1) } else { refusal(DropKind::Unsupported, DropTarget::Stage, false) }; + label(p + vec2(14.0, 12.0), text, ok); + } + (Spot::Library(folder), Some(p)) => { + let zone = &app.library.drop_zone; + match zone.row_at(p).filter(|_| folder.is_some()) { + Some(row) => { + painter.rect_stroke(row, T.rc(), stroke, StrokeKind::Inside); + } + None => { + if let Some(panel) = zone.panel { + painter.rect_stroke(panel, T.rc(), stroke, StrokeKind::Inside); + } + } + } + let ok = fits(DropTarget::Library); + let text = match (ok, folder.and_then(|f| app.s.doc.folder(f))) { + (true, Some(f)) => tr!("Add {what} to “{folder}”", what = what, folder = f.name), + (true, None) => tr!("Add {what} to the Library", what = what), + (false, _) => match known.iter().find(|f| !fits_one(f, DropTarget::Library)) { + Some(f) => refusal(kind_of(f), DropTarget::Library, false), + None => refusal(DropKind::Unsupported, DropTarget::Library, false), + }, + }; + label(p + vec2(14.0, 12.0), text, ok); + } + (Spot::Unknown, _) => { + // The desktop doesn't say where the pointer is during a drag: say what each place does. + painter.rect_stroke(screen, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + label(screen.center_top() + vec2(-180.0, 12.0), tr!("Drop {what} on the stage to place it, or on the Library to add it", what = what), true); + } + (spot, p) => { + let at = p.unwrap_or(screen.center_top()) + vec2(14.0, 12.0); + label(at, refusal(known.first().map_or(DropKind::Image, |f| kind_of(f)), DropTarget::Window, spot == Spot::Start), false); + } + } +} + +fn fits_one(f: &Path, to: DropTarget) -> bool { + matches!(route(kind_of(f), to), DropAction::ImportToStage | DropAction::ImportToLibrary) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p(s: &str) -> PathBuf { + PathBuf::from(s) + } + + #[test] + fn drops_are_routed_by_type_and_target() { + // A document opens wherever it lands, and only one at a time. + for spot in [Spot::Stage(1.0, 2.0), Spot::Library(None), Spot::Window, Spot::Start, Spot::Unknown] { + let plan = plan(&[p("walk.anicraft"), p("photo.png"), p("old.fla")], spot); + assert_eq!(plan.open, Some(p("walk.anicraft")), "{spot:?}"); + assert!(plan.import.is_empty()); + assert_eq!(plan.left_out.len(), 2); + } + let plan_at = |spot| plan(&[p("a.svg"), p("b.png"), p("c.mp3"), p("d.psd")], spot); + // On the stage: everything AniCraft reads, the rest left out with a reason. + let on_stage = plan_at(Spot::Stage(10.0, 20.0)); + assert_eq!((on_stage.to, on_stage.import.len(), on_stage.left_out.len()), (Some(DropTarget::Stage), 3, 1)); + assert!(on_stage.left_out[0].1.contains("SVG"), "says what AniCraft reads"); + // On the Library: images and sounds; a drawing is pointed to the stage. + let in_library = plan_at(Spot::Library(Some(FolderId(7)))); + assert_eq!((in_library.to, in_library.import.len(), in_library.left_out.len()), (Some(DropTarget::Library), 2, 2)); + assert!(in_library.left_out.iter().any(|(f, why)| f == &p("a.svg") && why.contains("stage"))); + // Elsewhere on the window, or over the start screen: nothing imports. + for spot in [Spot::Window, Spot::Start] { + let plan = plan_at(spot); + assert!(plan.import.is_empty() && plan.to.is_none() && plan.left_out.len() == 4, "{spot:?}"); + } + // No pointer position: the stage, at the middle of the view. + assert_eq!(plan_at(Spot::Unknown).to, Some(DropTarget::Stage)); + // Only unsupported files: nothing to do but say why. + let plan = plan(&[p("notes.txt")], Spot::Stage(0.0, 0.0)); + assert!(plan.to.is_none() && plan.open.is_none() && plan.left_out.len() == 1); + } + + #[test] + fn a_drop_lands_where_the_layout_says() { + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png"))); + app.run("library.new_folder", json!({"name": "Props"})); + let screen = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), ..Default::default() }; + for _ in 0..3 { + let mut out = ctx.run_ui(screen.clone(), |ui| app.frame(ui)); + out.textures_delta.clear(); + } + let geo = app.drop.stage.expect("the stage drew"); + // The middle of the canvas maps into the stage. + match spot_at(&app, Some(geo.canvas.center())) { + Spot::Stage(x, y) => assert!(x.is_finite() && y.is_finite()), + other => panic!("{other:?}"), + } + let (row, folder) = *app.library.drop_zone.rows.iter().find(|(_, f)| f.is_some()).expect("the folder row drew"); + assert_eq!(spot_at(&app, Some(row.center())), Spot::Library(folder)); + assert_eq!(spot_at(&app, Some(egui::pos2(1.0, 1.0))), Spot::Window, "the menu bar takes nothing"); + assert_eq!(spot_at(&app, None), Spot::Unknown); + crate::start::open(&mut app); + assert_eq!(spot_at(&app, Some(geo.canvas.center())), Spot::Start); + } + + #[test] + fn dropped_media_land_on_the_stage_or_in_a_library_folder() { + let dir = std::env::temp_dir().join(format!("anicraft-shell-drop-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("dot.png"); + std::fs::write(&png, anicraft_engine::render::encode_png(2, 2, &[200u8; 16]).unwrap()).unwrap(); + let ctx = egui::Context::default(); + let mut app = App::with_context(&ctx, anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()), Some(PathBuf::from("unused.png"))); + let bitmaps = app.s.doc.bitmaps.len(); + run(&mut app, std::slice::from_ref(&png), Spot::Stage(50.0, 40.0)); + assert_eq!(app.s.doc.bitmaps.len(), bitmaps + 1); + assert_eq!(app.s.selection.len(), 1); + assert!(app.status.as_ref().is_some_and(|s| !s.error), "{:?}", app.status.as_ref().map(|s| &s.text)); + let folder = app.run("library.new_folder", json!({"name": "Props"})).and_then(|v| v["folder"].as_u64()).map(FolderId).unwrap(); + run(&mut app, std::slice::from_ref(&png), Spot::Library(Some(folder))); + assert_eq!(app.s.doc.folder_contents(folder).len(), 1); + assert!(app.library.expanded.contains(&folder), "the folder opens to show it"); + // An unsupported file: one clear message, nothing changes. + let before = app.s.doc.clone(); + run(&mut app, &[dir.join("notes.txt")], Spot::Stage(0.0, 0.0)); + assert!(app.s.doc == before); + assert!(app.status.as_ref().is_some_and(|s| s.error && s.text.contains("notes.txt"))); + // A document over unsaved work asks first. + run(&mut app, &[dir.join("other.anicraft")], Spot::Stage(0.0, 0.0)); + assert!(app.confirm.is_some()); + } +} diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index 02dc4682..937a86a4 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -1,6 +1,9 @@ //! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values. -const SOURCES: [(&str, &str); 20] = [ +const SOURCES: [(&str, &str); 23] = [ + ("drop.rs", include_str!("drop.rs")), + ("recent.rs", include_str!("recent.rs")), + ("start.rs", include_str!("start.rs")), ("actions_panel.rs", include_str!("actions_panel.rs")), ("test_movie.rs", include_str!("test_movie.rs")), ("autosave.rs", include_str!("autosave.rs")), diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 8a29f683..37233515 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] { + for panel in ["start", "sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] { @@ -777,7 +777,7 @@ fn screen_reader_names_are_translated_too() { found.extend(untranslated_names("library item", |a, _| { a.library_sel = a.s.doc.library.first().map(|s| crate::app::LibraryItem::Symbol(s.id)); })); - for panel in ["select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] { + for panel in ["start", "drop", "droplibrary", "select", "motion", "motionspan", "motionpath", "motionedit", "camera", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "filters", "plugins", "actions", "script", "scriptproblems", "testmovie", "testscript", "exporthtml", "envelope"] { found.extend(untranslated_names(panel, |a, _| a.open_panel(Some(panel)))); } assert!(found.is_empty(), "{} screen-reader names not translated in the pseudo-locale:\n{}", found.len(), found.join("\n")); diff --git a/src/library.rs b/src/library.rs index ea2f72e4..da9afdc4 100644 --- a/src/library.rs +++ b/src/library.rs @@ -58,6 +58,33 @@ pub struct LibraryView { list_rect: Option, uses: Option<(StateId, HashMap, HashSet)>, preview: Option, + /// Where files dropped from the desktop land this frame (ADR 0059). + pub drop_zone: DropZone, +} + +/// The Library as a target for files dropped from the desktop (ADR 0059): the panel, and each +/// row with the folder a file dropped on it goes into. Cleared every frame before the panels +/// draw, so a hidden panel takes nothing. +#[derive(Default)] +pub struct DropZone { + pub panel: Option, + pub rows: Vec<(Rect, Option)>, +} + +impl DropZone { + /// The folder a file dropped at `p` goes into (`None` inside: the top level), or `None` + /// outside the panel. + pub fn folder_at(&self, p: Pos2) -> Option> { + if !self.panel.is_some_and(|r| r.contains(p)) { + return None; + } + Some(self.rows.iter().find(|(r, _)| r.contains(p)).and_then(|(_, f)| *f)) + } + + /// The row a drop at `p` lands on (a folder row, or the row inside that folder). + pub fn row_at(&self, p: Pos2) -> Option { + self.rows.iter().find(|(r, _)| r.contains(p)).map(|(r, _)| *r) + } } /// The current item's preview picture, and what it was made from. @@ -558,6 +585,7 @@ fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet Some(f), e => app.s.doc.parent_of(e), }; + app.library.drop_zone.rows.push((r.intersect(ui.clip_rect()), target)); if let Some(payload) = resp.dnd_hover_payload::>() && !payload.contains(&row.entry) { diff --git a/src/main.rs b/src/main.rs index 5f14701b..b83e1287 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,7 @@ mod bone_tool; mod camera_tool; mod convert_symbol; mod dialogs; +mod drop; mod gpu_stage; mod icons; mod keymap; @@ -46,10 +47,12 @@ mod pathtools; mod platform; mod plugins_ui; mod prefs; +mod recent; mod scale_grid; mod sound; mod shape_hints; mod stage; +mod start; mod test_movie; mod theme; mod timeline; @@ -108,11 +111,17 @@ fn run(renderer: eframe::Renderer, file: Option<&Path>, shot: Option, o // `--lang` before the window exists, so its first status line is in that language too. i18n::force(look.lang.as_deref()); let (session, report) = open_session(file); + let file_given = file.map(Path::to_path_buf); eframe::run_native( "AniCraft", options, Box::new(move |cc| { + let starting_fresh = file_given.is_none() && shot.is_none(); let mut a = app::App::new(cc, session, shot); + // No document to open: the start screen, unless it was switched off (ADR 0059). + if starting_fresh && a.prefs.start_screen { + start::open(&mut a); + } a.preview_look(&cc.egui_ctx, look.theme, look.scale); a.open_panel(open.as_deref()); // An imported document says what came across, as opening it from the menu does. @@ -180,7 +189,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu|colour]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/menus.rs b/src/menus.rs index 5eda634a..d5fd6612 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -140,6 +140,13 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option fn registry_items(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &[CommandSpec]) { for spec in cmds.iter().filter(|c| c.menu == top) { item(app, ui, spec); + if spec.id == "file.open" { + // Below Open, as in Animate: the recent files, and the start screen (ADR 0059). + ui.menu_button(tr!("Open Recent"), |ui| crate::recent::menu(app, ui)); + if ui_item(ui, tr!("Start Screen"), "", None) { + crate::start::open(app); + } + } } let mut subs: Vec<&str> = Vec::new(); for c in cmds { diff --git a/src/panels.rs b/src/panels.rs index 7cb27262..817c02e1 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -2095,5 +2095,7 @@ fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) { } fn library(app: &mut App, ui: &mut egui::Ui) { - crate::library::panel(app, ui); + // Where the panel is, for files dropped on it (ADR 0059). + let r = ui.scope(|ui| crate::library::panel(app, ui)).response.rect; + app.library.drop_zone.panel = Some(r); } diff --git a/src/platform.rs b/src/platform.rs index 551fd8a5..b612b7c7 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -167,6 +167,29 @@ pub fn save_settings(json: &str) -> Result<(), String> { } } +/// A recent file's start-screen picture (ADR 0059): `Thumbnails/.png` in the settings +/// folder, or browser storage on the web. `None` when there is none yet. +pub fn load_thumbnail(key: &str) -> Option> { + #[cfg(target_arch = "wasm32")] + return crate::web::storage_get(&format!("anicraft.thumb.{key}")).and_then(|t| anicraft_engine::doc::base64_decode(&t)); + #[cfg(not(target_arch = "wasm32"))] + config_dir().and_then(|d| std::fs::read(d.join("Thumbnails").join(format!("{key}.png"))).ok()) // i18n-exempt: a folder name +} + +/// Keeps a recent file's picture (a small PNG) for the start screen. +pub fn save_thumbnail(key: &str, png: &[u8]) -> Result<(), String> { + #[cfg(target_arch = "wasm32")] + return crate::web::storage_set(&format!("anicraft.thumb.{key}"), &anicraft_engine::doc::base64_encode(png)); + #[cfg(not(target_arch = "wasm32"))] + { + let dir = config_dir().ok_or(tr!("no settings folder on this system"))?.join("Thumbnails"); // i18n-exempt: a folder name + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let (path, tmp) = (dir.join(format!("{key}.png")), dir.join(format!("{key}.png.tmp"))); + std::fs::write(&tmp, png).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &path).map_err(|e| e.to_string()) + } +} + /// Why this build can't run `cmd`, if it can't: a web page can't start ffmpeg or keep files in /// a folder of the computer (ADR 0036). The desktop app runs everything. pub fn unavailable(cmd: &str) -> Option<&'static str> { diff --git a/src/prefs.rs b/src/prefs.rs index 256bdd5a..595e8c48 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -90,6 +90,12 @@ pub struct Prefs { pub autosave_edits: u32, /// Onion skin options (ADR 0047), kept from session to session. pub onion: OnionPrefs, + /// File › Open Recent and the start screen's list (ADR 0059): pinned favourites, then the + /// last 10 documents opened or saved. + #[serde(deserialize_with = "lenient_recent")] + pub recent: anicraft_engine::cmds_recent::RecentFiles, + /// Show the start screen when AniCraft starts without a document to open (ADR 0059). + pub start_screen: bool, } /// Onion skin options that carry over between sessions (ADR 0047). Whether onion skin and Edit @@ -140,10 +146,25 @@ impl Default for Prefs { autosave_secs: 60, autosave_edits: 25, onion: OnionPrefs::default(), + recent: Default::default(), + start_screen: true, } } } +/// The recent files as written, skipping entries that aren't one (a hand-edited file): one bad +/// entry must not reset every preference. +fn lenient_recent<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + use anicraft_engine::cmds_recent::{RecentFile, RecentFiles}; + let v = serde_json::Value::deserialize(d)?; + let list: Vec = match v { + serde_json::Value::Array(a) => a.into_iter().take(1000).collect(), + _ => Vec::new(), + }; + let good: Vec = list.into_iter().filter_map(|x| serde_json::from_value::(x).ok()).collect(); + Ok(serde_json::from_value::(serde_json::to_value(good).unwrap_or_default()).unwrap_or_default()) +} + /// Autosave intervals offered in Preferences: `(seconds, label)`. pub const AUTOSAVE_INTERVALS: [(u32, &str); 5] = [(30, tr_noop!("30 seconds")), (60, tr_noop!("1 minute")), (120, tr_noop!("2 minutes")), (300, tr_noop!("5 minutes")), (600, tr_noop!("10 minutes"))]; pub const AUTOSAVE_SECS_RANGE: std::ops::RangeInclusive = 15..=600; @@ -171,6 +192,7 @@ impl Prefs { self.autosave_edits = self.autosave_edits.min(*AUTOSAVE_EDITS_RANGE.end()); self.onion.before = self.onion.before.min(ONION_REACH_MAX); self.onion.after = self.onion.after.min(ONION_REACH_MAX); + self.recent = std::mem::take(&mut self.recent).sanitized(); self } @@ -273,5 +295,16 @@ mod tests { let p = Prefs::from_json(r#"{"autosave": false, "autosave_secs": 1, "autosave_edits": 99999999}"#); assert!(!p.autosave); assert_eq!((p.autosave_secs, p.autosave_edits), (15, 1000)); + // Older files have no recent files and show the start screen (ADR 0059); a list + // someone edited by hand is cleaned up. + let p = Prefs::from_json(r#"{"ui_scale": 1.25}"#); + assert!(p.recent.is_empty() && p.start_screen); + let p = Prefs::from_json(r#"{"recent": [{"path": "a.anicraft"}, {"path": "a.anicraft"}, {"path": ""}, 7], "start_screen": false}"#); + let paths: Vec<_> = p.recent.entries().iter().map(|e| e.path.display().to_string()).collect(); + assert_eq!(paths, ["a.anicraft"], "bad entries are skipped, the rest kept"); + assert!(!p.start_screen, "and the other preferences with them"); + let p = Prefs::from_json(r#"{"recent": [{"path": "b.anicraft"}, {"path": "a.anicraft", "pinned": true}, {"path": "b.anicraft"}]}"#); + let paths: Vec<_> = p.recent.entries().iter().map(|e| (e.path.display().to_string(), e.pinned)).collect(); + assert_eq!(paths, [("a.anicraft".to_string(), true), ("b.anicraft".to_string(), false)]); } } diff --git a/src/recent.rs b/src/recent.rs new file mode 100644 index 00000000..378748fa --- /dev/null +++ b/src/recent.rs @@ -0,0 +1,193 @@ +//! Recent files in the window (ADR 0059): File › Open Recent, the list kept in the preferences, +//! and the thumbnails the start screen shows. The list itself is the session's +//! (`anicraft_engine::cmds_recent`): `file.open` and `file.save` add to it, the `prefs.recent_*` +//! commands change it, and the window copies it into the preferences whenever it changes. + +use crate::app::App; +use crate::platform; +use crate::theme::{Type, text}; +use anicraft_engine::cmds_recent::{self, RecentFile}; +use serde_json::json; +use std::collections::HashMap; +use std::path::Path; + +/// Thumbnails loaded for the start screen, by thumbnail key (`None`: there is none). +#[derive(Default)] +pub struct Thumbs { + loaded: HashMap>, + /// Pictures made in memory (screenshot runs show sample entries without touching disk). + pub(crate) seeded: HashMap>, +} + +impl Thumbs { + /// The picture of `path`, decoded and uploaded once. + pub fn get(&mut self, ctx: &egui::Context, path: &Path) -> Option { + let key = cmds_recent::thumb_key(path); + if let Some(t) = self.loaded.get(&key) { + return t.clone(); + } + let png = self.seeded.get(&key).cloned().or_else(|| platform::load_thumbnail(&key)); + let tex = png.and_then(|png| anicraft_engine::doc::decode_png(&png)).and_then(|px| { + let (w, h) = (usize::try_from(px.width).ok()?, usize::try_from(px.height).ok()?); + (w > 0 && h > 0 && px.rgba.len() == w * h * 4).then(|| ctx.load_texture(format!("recent-{key}"), egui::ColorImage::from_rgba_unmultiplied([w, h], &px.rgba), egui::TextureOptions::LINEAR)) + }); + self.loaded.insert(key, tex.clone()); + tex + } + + /// Forgets `path`'s picture, so the next look reads the new one. + pub fn invalidate(&mut self, path: &Path) { + self.loaded.remove(&cmds_recent::thumb_key(path)); + } +} + +/// The picture of the open document's first frame, kept for `path` (after a save or an open). +/// Screenshot and test runs keep nothing on disk. +pub fn capture(app: &mut App, path: &Path) { + if app.shot.is_some() { + return; + } + let t = web_time::Instant::now(); + match cmds_recent::thumbnail_png(&app.s.doc) { + Ok(png) => { + if let Err(e) = platform::save_thumbnail(&cmds_recent::thumb_key(path), &png) { + eprintln!("could not keep the thumbnail of {}: {e}", path.display()); + } + app.thumbs.invalidate(path); + } + Err(e) => eprintln!("could not draw the thumbnail of {}: {e}", path.display()), + } + if cfg!(debug_assertions) { + eprintln!("thumbnail of {} in {:.1} ms", path.display(), t.elapsed().as_secs_f64() * 1000.0); + } +} + +/// After a document was opened: a picture if it has none yet (one made on save is kept). +pub fn captured_on_open(app: &mut App, path: &Path) { + if app.shot.is_none() && platform::load_thumbnail(&cmds_recent::thumb_key(path)).is_none() { + capture(app, path); + } +} + +/// Copies the session's list into the preferences when a command changed it, and saves them +/// (not in screenshot or test runs, which never write the user's preferences). +pub fn sync(app: &mut App) { + if app.s.recent == app.prefs.recent { + return; + } + app.prefs.recent = app.s.recent.clone(); + if app.shot.is_none() + && let Err(e) = app.prefs.save() + { + app.status_err(tr!("Could not save preferences: {e}", e = e)); + } +} + +/// The file's name, as the menu and the start screen show it. +pub fn display_name(path: &Path) -> String { + path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()) +} + +/// The name of the folder it is in. +pub fn folder_name(path: &Path) -> String { + path.parent().and_then(Path::file_name).map_or_else(String::new, |n| n.to_string_lossy().into_owned()) +} + +/// The recent files with whether each is still there. +pub fn entries(app: &App) -> Vec<(usize, RecentFile, bool)> { + app.s.recent.entries().iter().enumerate().map(|(i, e)| (i, e.clone(), !cmds_recent::exists(&e.path))).collect() +} + +/// File › Open Recent: pinned favourites, then the last files; a missing file is greyed out +/// with Remove beside it. Every action is a command. +pub fn menu(app: &mut App, ui: &mut egui::Ui) { + ui.set_min_width(320.0); + let list = entries(app); + if list.is_empty() { + ui.label(text(Type::Caption, tr!("No recent files yet. Documents you open or save show here."))); + return; + } + let mut act: Option<(&'static str, serde_json::Value)> = None; + let mut last_pinned = list.first().is_some_and(|(_, e, _)| e.pinned); + if last_pinned { + ui.label(text(Type::Caption, tr!("Pinned"))); + } + for (i, e, missing) in &list { + if last_pinned && !e.pinned { + ui.separator(); + last_pinned = false; + } + let name = display_name(&e.path); + ui.horizontal(|ui| { + let label = if *missing { tr!("{name} (missing)", name = name) } else { name.clone() }; + let r = ui.add_enabled(!*missing, egui::Button::new(label).min_size(egui::vec2(200.0, 0.0))); + let tip = e.path.display().to_string(); + let r = if *missing { r.on_disabled_hover_text(tr!("{path} is no longer there", path = tip)) } else { r.on_hover_text(tip) }; + if r.clicked() { + act = Some(("file.open_recent", json!({"index": i}))); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if *missing { + if ui.small_button(tr!("Remove")).on_hover_text(tr!("Take it off the list")).clicked() { + act = Some(("prefs.recent_remove", json!({"index": i}))); + } + } else if ui.small_button(if e.pinned { tr!("Unpin") } else { tr!("Pin") }).on_hover_text(if e.pinned { tr!("Let it move down the list again") } else { tr!("Keep it at the top of the list") }).clicked() { + act = Some(("prefs.recent_pin", json!({"index": i}))); + } + }); + }); + } + ui.separator(); + if ui.button(tr!("Clear Recent Files")).on_hover_text(tr!("Pinned files stay")).clicked() { + act = Some(("prefs.recent_clear", json!({}))); + } + if let Some((id, params)) = act { + // Opening keeps the menu's promise; pinning and removing keep the menu open. + if id == "file.open_recent" { + ui.close(); + } + open_or_run(app, id, params); + } +} + +/// Runs a recent-files command from a menu or the start screen; opening goes through +/// `request`, so unsaved work asks first. +pub fn open_or_run(app: &mut App, id: &str, params: serde_json::Value) { + if id == "file.open_recent" { + app.request(id, params); + } else if let Some(v) = app.run(id, params) + && id == "prefs.recent_clear" + { + let n = v["removed"].as_u64().unwrap_or(0) as usize; + app.status_ok(trn!("Cleared {n} recent file", "Cleared {n} recent files", n)); + } +} + +/// Sample entries for screenshot and test runs (`--open start`): two documents made from the +/// samples in a scratch folder (one pinned), and one that is missing. Their pictures stay in +/// memory; nothing goes into the settings folder. +pub fn sample_entries(app: &mut App) { + let folder = std::env::temp_dir().join("AniCraft samples"); // i18n-exempt: a folder name + let _ = anicraft_engine::vfs::create_dir_all(&folder); + let docs = [("Bouncing ball.anicraft", Some(anicraft_engine::doc::sample::demo()), true), ("Title card.anicraft", Some(anicraft_engine::doc::sample::interactive()), false), ("Old walk cycle.anicraft", None, false)]; // i18n-exempt: sample file names + let mut list = anicraft_engine::cmds_recent::RecentFiles::default(); + for (name, doc, pinned) in docs.into_iter().rev() { + let path = folder.join(name); + match doc { + Some(doc) => { + if let Ok(png) = cmds_recent::thumbnail_png(&doc) { + app.thumbs.seeded.insert(cmds_recent::thumb_key(&path), png); + } + let _ = anicraft_engine::format::save(&doc, &path); + } + None => { + let _ = anicraft_engine::vfs::remove_file(&path); + } + } + list.add(&path); + if pinned { + let _ = list.pin(&path, true); + } + } + app.s.recent = list; +} diff --git a/src/stage.rs b/src/stage.rs index fb2c2427..583b6e86 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -264,6 +264,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let cam_geo = crate::camera_tool::Geo { origin: st_origin, zoom: st_zoom, stage_rect, preview }; // Library items dragged onto the stage land at the pointer (ADR 0053). crate::library::stage_drop(app, ui, &resp, to_stage, preview); + // Files dropped from the desktop land here too (ADR 0059). + app.drop.stage = Some(crate::drop::StageGeo { canvas, origin, zoom, paused: preview }); // ---- tools ---------------------------------------------------------------------------- diff --git a/src/start.rs b/src/start.rs new file mode 100644 index 00000000..c5cee4af --- /dev/null +++ b/src/start.rs @@ -0,0 +1,315 @@ +//! The start screen (ADR 0059): what AniCraft shows when it starts without a document to open, +//! as Animate's Home screen does. New with stage-size presets (and a custom size), Open, the +//! recent files with their pictures, and the sample animation. It takes the place of the +//! workspace, never sits over it as a dialog: the menus keep working, Esc goes back to the +//! document, and New, Open or a recent file dismisses it once the document is there. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{T, TARGET, Type, color, font, text}; +use egui::{Align2, Rect, Sense, Stroke, StrokeKind, Vec2, WidgetType, pos2, vec2}; +use serde_json::json; + +/// A New preset: its name (English, translated where drawn), stage width and height. +pub struct Preset { + pub name: &'static str, + pub width: u32, + pub height: u32, +} + +/// The sizes artists start from most: video in HD and Full HD, square and vertical social posts. +pub const PRESETS: [Preset; 4] = [ + Preset { name: tr_noop!("HD video"), width: 1280, height: 720 }, + Preset { name: tr_noop!("Full HD video"), width: 1920, height: 1080 }, + Preset { name: tr_noop!("Square post"), width: 1080, height: 1080 }, + Preset { name: tr_noop!("Vertical story"), width: 1080, height: 1920 }, +]; + +/// The frame rates offered for a new document. +pub const RATES: [f32; 5] = [12.0, 24.0, 25.0, 30.0, 60.0]; + +/// What the start screen holds between frames: the custom size being typed. +pub struct StartScreen { + pub width: u32, + pub height: u32, + pub fps: f32, +} + +impl Default for StartScreen { + fn default() -> Self { + let d = anicraft_engine::doc::Stage::default(); + StartScreen { width: d.width, height: d.height, fps: d.fps } + } +} + +/// `file.new`'s params for a size and rate. +pub fn new_params(width: u32, height: u32, fps: f32) -> serde_json::Value { + json!({"width": width, "height": height, "fps": fps}) +} + +/// Shows the start screen (File › Start Screen, and at launch). +pub fn open(app: &mut App) { + app.playing = false; + app.start = Some(StartScreen { fps: app.s.doc.stage.fps, ..StartScreen::default() }); + app.status_ok(tr!("Pick a size to start a new animation, or open one you made. Esc goes back to the document.")); +} + +/// The start screen in the space the workspace normally takes. +pub fn show(app: &mut App, ui: &mut egui::Ui) { + if ui.input(|i| i.key_pressed(egui::Key::Escape)) && !app.modal_open() { + app.start = None; + return; + } + let ctx = ui.ctx().clone(); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let width = ui.available_width().min(1120.0); + let pad = ((ui.available_width() - width) / 2.0).max(24.0); + ui.add_space(28.0); + ui.horizontal(|ui| { + ui.add_space(pad); + ui.vertical(|ui| { + ui.set_width(width - 48.0); + header(app, ui, &ctx); + ui.add_space(20.0); + ui.columns(2, |cols| { + if let [left, right] = cols { + new_column(app, left); + open_column(app, right, &ctx); + } + }); + ui.add_space(16.0); + footer(app, ui); + }); + }); + ui.add_space(28.0); + }); +} + +fn header(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) { + ui.horizontal(|ui| { + ui.add(egui::Image::new((crate::app::app_mark(ctx).id(), vec2(44.0, 44.0)))); + ui.add_space(8.0); + ui.vertical(|ui| { + ui.label(text(Type::Title, "AniCraft")); // i18n-exempt: the product name + ui.label(text(Type::Caption, tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(crate::app::RELEASE_STAGE)))); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let back = ui.add(egui::Button::new(tr!("Back to the document")).shortcut_text(text(Type::Key, "Esc"))); // i18n-exempt: a key name + if back.on_hover_text(tr!("The document that is open stays as it is")).clicked() { + app.start = None; + } + }); + }); +} + +/// A preset tile: the stage's shape drawn to scale, its name and size. +fn tile(ui: &mut egui::Ui, name: &str, w: u32, h: u32) -> egui::Response { + let size = vec2(118.0, 112.0); + let (r, resp) = ui.allocate_exact_size(size, Sense::click()); + let size_text = format!("{w} × {h}"); + a11y::control(ui, &resp, WidgetType::Button, &tr!("New {name}, {size}", name = name, size = size_text), None); + let p = ui.painter(); + let hot = resp.hovered() || resp.has_focus(); + p.rect_filled(r, T.rc(), if hot { T.hover } else { T.panel_alt }); + p.rect_stroke(r, T.rc(), Stroke::new(1.0, if hot { T.accent } else { T.border }), StrokeKind::Inside); + // The stage's aspect, in a 64-point box. + let box_ = Rect::from_center_size(pos2(r.center().x, r.top() + 38.0), vec2(64.0, 52.0)); + let aspect = w.max(1) as f32 / h.max(1) as f32; + let shape = if aspect >= box_.width() / box_.height() { vec2(box_.width(), box_.width() / aspect) } else { vec2(box_.height() * aspect, box_.height()) }; + p.rect_filled(Rect::from_center_size(box_.center(), shape), crate::theme::SQUARE, T.text_faint); + p.text(pos2(r.center().x, r.bottom() - 34.0), Align2::CENTER_CENTER, name, font(Type::Label), color(Type::Body)); + p.text(pos2(r.center().x, r.bottom() - 16.0), Align2::CENTER_CENTER, size_text, font(Type::DataSmall), T.text_dim); + a11y::focus_ring(ui, &resp); + resp +} + +fn new_column(app: &mut App, ui: &mut egui::Ui) { + ui.label(text(Type::Heading, tr!("Create new"))); + ui.add_space(6.0); + let fps = app.start.as_ref().map_or(24.0, |s| s.fps); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(10.0, 10.0); + for p in &PRESETS { + if tile(ui, crate::i18n::t(p.name), p.width, p.height).clicked() { + app.request("file.new", new_params(p.width, p.height, fps)); + } + } + }); + ui.add_space(12.0); + ui.label(text(Type::Label, tr!("Custom size"))); + let Some(st) = app.start.as_mut() else { return }; + let max = anicraft_engine::doc::MAX_STAGE_EDGE; + let mut create = false; + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut st.width).range(1..=max).suffix(" px")).named(tr!("Custom width")); // i18n-exempt: a unit + ui.label(text(Type::Data, "×")); // i18n-exempt: a symbol + ui.add(egui::DragValue::new(&mut st.height).range(1..=max).suffix(" px")).named(tr!("Custom height")); // i18n-exempt: a unit + ui.add_space(8.0); + egui::ComboBox::from_id_salt("start_fps") + .selected_text(text(Type::Data, tr!("{fps} fps", fps = st.fps))) + .show_ui(ui, |ui| { + for r in RATES { + ui.selectable_value(&mut st.fps, r, text(Type::Data, tr!("{fps} fps", fps = r))); + } + }) + .response + .set_name(tr!("Frame rate")); + ui.add_space(8.0); + create = ui.add(egui::Button::new(tr!("Create")).min_size(vec2(0.0, TARGET))).clicked(); + }); + ui.label(text(Type::Caption, tr!("The frame rate is for every new document made here. Change the size later in Modify › Document Settings."))); + let (w, h, f) = (st.width, st.height, st.fps); + if create { + app.request("file.new", new_params(w, h, f)); + } +} + +fn open_column(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context) { + ui.label(text(Type::Heading, tr!("Open"))); + ui.add_space(6.0); + ui.horizontal(|ui| { + if ui.add(egui::Button::new(tr!("Open…")).min_size(vec2(0.0, TARGET))).on_hover_text(tr!("An AniCraft document, or an Animate .fla or .xfl")).clicked() { + app.invoke("file.open"); + } + if ui.add(egui::Button::new(tr!("Sample animation")).min_size(vec2(0.0, TARGET))).on_hover_text(tr!("A short animation to look at and take apart")).clicked() { + app.request("file.new_sample", json!({})); + } + }); + ui.label(text(Type::Caption, tr!("Or drop a document anywhere on this window."))); + ui.add_space(14.0); + ui.label(text(Type::Heading, tr!("Recent"))); + ui.add_space(6.0); + let list = crate::recent::entries(app); + if list.is_empty() { + ui.label(text(Type::Caption, tr!("Documents you open or save show here, with a picture of their first frame."))); + return; + } + let mut act: Option<(&'static str, serde_json::Value)> = None; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(10.0, 10.0); + for (i, e, missing) in &list { + card(app, ui, ctx, *i, e, *missing, &mut act); + } + }); + if let Some((id, params)) = act { + crate::recent::open_or_run(app, id, params); + } +} + +/// A recent file: its picture, name and folder. A click opens it; a missing file is dimmed with +/// Remove; Pin keeps it first. +fn card(app: &mut App, ui: &mut egui::Ui, ctx: &egui::Context, i: usize, e: &anicraft_engine::cmds_recent::RecentFile, missing: bool, act: &mut Option<(&'static str, serde_json::Value)>) { + let thumb = Vec2::new(anicraft_engine::cmds_recent::THUMB_W as f32 * 0.66, anicraft_engine::cmds_recent::THUMB_H as f32 * 0.66); + let name = crate::recent::display_name(&e.path); + ui.vertical(|ui| { + ui.set_width(thumb.x); + let (r, resp) = ui.allocate_exact_size(thumb, if missing { Sense::hover() } else { Sense::click() }); + let label = if missing { tr!("{name}, missing", name = name) } else if e.pinned { tr!("Open {name}, pinned", name = name) } else { tr!("Open {name}", name = name) }; + a11y::control(ui, &resp, WidgetType::Button, &label, None); + let hot = !missing && (resp.hovered() || resp.has_focus()); + let p = ui.painter(); + p.rect_filled(r, T.rc(), T.panel_alt); + match (!missing).then(|| app.thumbs.get(ctx, &e.path)).flatten() { + Some(tex) => { + let s = tex.size_vec2(); + let fit = (r.width() / s.x.max(1.0)).min(r.height() / s.y.max(1.0)); + let img = Rect::from_center_size(r.center(), s * fit); + p.image(tex.id(), img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => icons::paint(p, Rect::from_center_size(r.center(), vec2(28.0, 28.0)), Icon::Image, T.text_faint), + } + p.rect_stroke(r, T.rc(), Stroke::new(if hot { 1.5 } else { 1.0 }, if hot { T.accent } else { T.border }), StrokeKind::Inside); + a11y::focus_ring(ui, &resp); + let tip = e.path.display().to_string(); + let resp = if missing { resp.on_hover_text(tr!("{path} is no longer there", path = tip)) } else { resp.on_hover_text(tip) }; + if resp.clicked() { + *act = Some(("file.open_recent", json!({"index": i}))); + } + let c = if missing { T.text_dim } else { color(Type::Body) }; + ui.add(egui::Label::new(text(Type::Body, name.clone()).color(c)).truncate()); + ui.horizontal(|ui| { + let note = if missing { tr!("Missing").to_string() } else if e.pinned { tr!("Pinned").to_string() } else { crate::recent::folder_name(&e.path) }; + ui.add(egui::Label::new(text(if missing || e.pinned { Type::Caption } else { Type::Path }, note).color(T.text_dim)).truncate()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if missing { + if ui.small_button(tr!("Remove")).on_hover_text(tr!("Take it off the list")).clicked() { + *act = Some(("prefs.recent_remove", json!({"index": i}))); + } + } else if ui.small_button(if e.pinned { tr!("Unpin") } else { tr!("Pin") }).on_hover_text(if e.pinned { tr!("Let it move down the list again") } else { tr!("Keep it at the top of the list") }).clicked() { + *act = Some(("prefs.recent_pin", json!({"index": i}))); + } + }); + }); + }); +} + +fn footer(app: &mut App, ui: &mut egui::Ui) { + ui.separator(); + ui.horizontal(|ui| { + let mut on = app.prefs.start_screen; + if crate::theme::checkbox(ui, &mut on, tr!("Show this screen when AniCraft starts")).changed() { + let mut p = app.prefs.clone(); + p.start_screen = on; + let ctx = ui.ctx().clone(); + app.set_prefs(&ctx, p); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(text(Type::Caption, tr!("File › Start Screen brings it back"))); + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + + fn app() -> (App, egui::Context) { + let ctx = egui::Context::default(); + let app = App::with_context(&ctx, Session::new(anicraft_engine::doc::sample::demo()), Some(std::path::PathBuf::from("unused.png"))); + (app, ctx) + } + + #[test] + fn every_preset_makes_a_document_of_its_size() { + let (mut app, _) = app(); + for p in &PRESETS { + for fps in [24.0, 30.0] { + crate::start::open(&mut app); + app.request("file.new", new_params(p.width, p.height, fps)); + let st = app.s.doc.stage; + assert_eq!((st.width, st.height, st.fps), (p.width, p.height, fps), "{}", p.name); + assert!(app.start.is_none(), "New dismisses the start screen"); + } + } + let names: Vec<(u32, u32)> = PRESETS.iter().map(|p| (p.width, p.height)).collect(); + for want in [(1280, 720), (1920, 1080), (1080, 1080)] { + assert!(names.contains(&want), "{want:?} is a preset"); + } + // A custom size, and one past the limit that the engine refuses (the screen stays). + crate::start::open(&mut app); + app.request("file.new", new_params(640, 480, 12.0)); + assert_eq!((app.s.doc.stage.width, app.s.doc.stage.height, app.s.doc.stage.fps), (640, 480, 12.0)); + crate::start::open(&mut app); + app.request("file.new", new_params(anicraft_engine::doc::MAX_STAGE_EDGE + 1, 10, 24.0)); + assert!(app.start.is_some(), "a refused New leaves the start screen up"); + } + + #[test] + fn over_unsaved_work_new_asks_first_and_esc_goes_back() { + let (mut app, ctx) = app(); + app.run("draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + crate::start::open(&mut app); + app.request("file.new", new_params(1920, 1080, 24.0)); + assert!(app.confirm.is_some(), "unsaved work asks first"); + assert!(app.start.is_some(), "and the start screen waits for the answer"); + app.confirm = None; + // Esc returns to the work, untouched. + let input = egui::RawInput { events: vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + assert!(app.start.is_none()); + assert!(app.s.is_dirty(), "the work is still there"); + } +} diff --git a/src/web.rs b/src/web.rs index e0e248fb..b18c9495 100644 --- a/src/web.rs +++ b/src/web.rs @@ -36,6 +36,9 @@ const PICKER_ID: &str = "anicraft_file_input"; /// Largest file taken from the picker (the engine's own limits are lower for most kinds). const MAX_PICK_BYTES: f64 = 512.0 * 1024.0 * 1024.0; +/// Files read from a drop: each one's name, and its bytes or why the browser couldn't read it. +pub type ReadFiles = Vec<(String, Result, String>)>; + thread_local! { /// Files the picker delivered, waiting for the next frame. static PICKED: RefCell> = const { RefCell::new(Vec::new()) }; @@ -44,6 +47,12 @@ thread_local! { static UNSAVED: Cell = const { Cell::new(false) }; /// Sessions whose tab is still open (they hold their lock); `None` until the browser said. static LIVE: RefCell>> = const { RefCell::new(None) }; + /// Where the pointer is over the canvas while files are dragged (CSS pixels from its + /// top-left corner), ADR 0059: egui is told only that something hovers. + static DRAG_POS: Cell> = const { Cell::new(None) }; + /// Dropped files read so far, by ticket: each file's name and bytes. + static DROPPED: RefCell> = const { RefCell::new(Vec::new()) }; + static TICKET: Cell = const { Cell::new(0) }; } /// Starts the editor on the page's canvas. @@ -75,13 +84,19 @@ async fn run() -> Result<(), String> { // Text needs a face to lay out with, and a page can't see the computer's fonts. anicraft_engine::text::Fonts::register(fonts()); let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + track_drags(&canvas); eframe::WebRunner::new() .start( canvas, eframe::WebOptions::default(), Box::new(move |cc| { CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone())); - Ok(Box::new(crate::app::App::new(cc, session, None))) + let mut app = crate::app::App::new(cc, session, None); + // The start screen, unless it was switched off (ADR 0059). + if app.prefs.start_screen { + crate::start::open(&mut app); + } + Ok(Box::new(app)) }), ) .await @@ -169,6 +184,67 @@ pub fn take_picked() -> Option { }) } +/// Keeps where the pointer is while files are dragged over the canvas (eframe's own listener +/// tells egui only that files hover, ADR 0059). +fn track_drags(canvas: &web_sys::HtmlCanvasElement) { + let target = canvas.clone(); + let on_over = Closure::::new(move |e: web_sys::DragEvent| { + let r = target.get_bounding_client_rect(); + DRAG_POS.with(|p| p.set(Some((e.client_x() as f32 - r.left() as f32, e.client_y() as f32 - r.top() as f32)))); + }); + if canvas.add_event_listener_with_callback("dragover", on_over.as_ref().unchecked_ref()).is_ok() { + on_over.forget(); + } + let on_leave = Closure::::new(|_e: web_sys::DragEvent| DRAG_POS.with(|p| p.set(None))); + if canvas.add_event_listener_with_callback("dragleave", on_leave.as_ref().unchecked_ref()).is_ok() { + on_leave.forget(); + } +} + +/// Where the pointer was over the canvas during the drag, in CSS pixels. +pub fn drag_pos() -> Option<(f32, f32)> { + DRAG_POS.with(Cell::get) +} + +pub fn clear_drag_pos() { + DRAG_POS.with(|p| p.set(None)); +} + +/// Reads dropped files' bytes; they arrive together through [`take_dropped`] with the ticket +/// returned here. +pub fn read_dropped(files: Vec) -> u64 { + let ticket = TICKET.with(|t| { + t.set(t.get().wrapping_add(1)); + t.get() + }); + wasm_bindgen_futures::spawn_local(async move { + let mut out = Vec::with_capacity(files.len()); + for file in files { + let name = file.name(); + let data = if file.size() > MAX_PICK_BYTES { + Err(tr!("it is larger than {size} MB", size = MAX_PICK_BYTES as u64 >> 20)) + } else { + match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await { + Ok(buf) => Ok(js_sys::Uint8Array::new(&buf).to_vec()), + Err(_) => Err(tr!("the browser could not read it").to_string()), + } + }; + out.push((name, data)); + } + DROPPED.with(|d| d.borrow_mut().push((ticket, out))); + repaint(); + }); + ticket +} + +/// The next dropped files the browser finished reading. +pub fn take_dropped() -> Option<(u64, ReadFiles)> { + DROPPED.with(|d| { + let mut d = d.borrow_mut(); + (!d.is_empty()).then(|| d.remove(0)) + }) +} + /// Offers `data` as a download named after `path`'s file name. pub fn download(path: &Path, data: &[u8]) { let name = path.file_name().map_or_else(|| "download".to_string(), |n| n.to_string_lossy().into_owned());