diff --git a/CHANGELOG.md b/CHANGELOG.md index e2c82d9b..5d2af938 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +* **An imported Animate file keeps its name** (ADR 0009 note): a `.fla`, `.xfl` or XFL folder + opens with its own name on its tab and in the window title instead of "Untitled", marked as + imported (a dim "Imported" on the tab, "(imported)" in the title, where it came from in the + tooltip). Saving still never writes over it: Save asks for a new name, suggesting an + `.anicraft` of the same name beside the original, and from then on the tab shows that file. + Opening the same Animate file again shows its tab. Save dialogs now open in the suggested + file's folder. + * **Text reads right: mixed directions, and letters from a fallback face** (M5, backlog P-008, ADR 0130). With outside pull requests #39 and #40 by SoldierPePe, whose commits are merged here and rebuilt on styled text. diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 3e58bf1a..4e8a547f 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -184,6 +184,55 @@ fn new_sample(s: &mut Session, p: &Value) -> Result { Ok(json!({"frames": s.frame_count()})) } +/// Where an untitled document came from (ADR 0009), settled when it was imported, so a later +/// change on disk (a package's files moved or removed) never changes what it is called or where +/// Save suggests keeping it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Import { + /// What was opened: the `.fla`, the `.xfl` or the XFL folder. Its name names the document. + pub source: PathBuf, + /// The Animate document itself: the XFL folder, whether it or the `.xfl` in it was opened, + /// or the `.fla`. Two imports of the same package are the same document. + pub package: PathBuf, + /// Where Save first suggests keeping it: an `.anicraft` of the same name beside the + /// package, so `walk.fla` suggests `walk.anicraft` in its folder, and an XFL folder's goes + /// beside the folder, never inside it. + pub save_as: PathBuf, +} + +impl Import { + /// The import of `source`, as the disk has it now. + pub fn of(source: &std::path::Path) -> Import { + let package = import_package(source); + // "." or "walk/sub/.." has no name of its own: resolve it, or the suggestion would land + // inside the package as "animation.anicraft". + let package = match package.file_name() { + Some(_) => package, + None => std::fs::canonicalize(&package).unwrap_or(package), + }; + // A folder's whole name ("walk.v2" stays "walk.v2"); a file's without its extension. + let name = if crate::vfs::is_dir(&package) { package.file_name() } else { package.file_stem() }; + let name = name.map_or_else(|| "animation".to_string(), |n| n.to_string_lossy().into_owned()); + let save_as = package.with_file_name(format!("{name}.anicraft")); + Import { source: source.to_path_buf(), package, save_as } + } +} + +/// The Animate document `path` opens: the XFL folder for the `.xfl` file in one, else `path` +/// itself (a `.fla`, an XFL folder, or any other file). +pub fn import_package(path: &std::path::Path) -> PathBuf { + // A folder named "x.xfl" is a package of its own, not part of the one around it. + let xfl_file = crate::vfs::is_file(path) + && path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xfl")) + && path.parent().is_some_and(|d| crate::vfs::is_file(&d.join("DOMDocument.xml"))); + match path.parent() { + // A bare "walk.xfl" is in the current folder: "." resolves, an empty path doesn't. + Some(folder) if xfl_file && folder.as_os_str().is_empty() => PathBuf::from("."), + Some(folder) if xfl_file => folder.to_path_buf(), + _ => path.to_path_buf(), + } +} + /// Whether `path` is an Animate document: a `.fla` archive, an `.xfl` file or an XFL folder. pub fn is_animate(path: &std::path::Path) -> bool { let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); @@ -195,8 +244,9 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result { let unsaved = opt_bool(p, "unsaved")?.unwrap_or(false); let untitled = opt_bool(p, "untitled")?.unwrap_or(false); if is_animate(&path) { - // Imported, not adopted: the document is untitled, so Save asks for a new .anicraft - // name and never writes over the Animate file. + // Imported, not adopted: the document has no file name, so Save asks for a new + // .anicraft name and never writes over the Animate file. It is still called by the + // Animate file's name, and Save suggests one beside it (ADR 0009). let fla = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("fla")) && crate::vfs::is_file(&path); let imported = if fla { // Through `vfs`, so an archive the browser handed over opens too (ADR 0036). @@ -216,10 +266,11 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result { // as it was in Animate (ADR 0042). let merged = crate::merge::merge_document(&mut doc); s.replace_document(doc, None); + s.imported = Some(Import::of(&path)); // Open Recent reopens the Animate file (ADR 0059). s.recent.add(&path); + // `imported` and `save_as` come with the session's info. let mut info = s.info(); - info["imported"] = json!(path.display().to_string()); info["report"] = json!(report.summary()); info["skipped"] = json!(report.skipped); info["kept"] = json!(report.kept); @@ -247,6 +298,8 @@ fn save(s: &mut Session, p: &Value) -> Result { }; format::save(&s.doc, &path)?; s.path = Some(path.clone()); + // Saved: the document is the .anicraft file now, not the import. + s.imported = None; s.mark_saved(); s.recent.add(&path); Ok(json!({"saved": path.display().to_string()})) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 962fbd71..899f811d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -101,7 +101,7 @@ pub use anicraft_render as render; pub use anicraft_svg as svg; /// Whether a path is an Animate document (`.fla`, `.xfl`, or an XFL folder) that `file.open` /// imports. -pub use cmds_file::is_animate; +pub use cmds_file::{Import, import_package, is_animate}; pub use cmds_modify::{Item as SelectedItem, transform_origins}; #[derive(Debug, thiserror::Error)] @@ -409,6 +409,10 @@ pub struct Session { pub state: StateId, saved_state: Option, pub path: Option, + /// The Animate file (`.fla`, `.xfl` or XFL folder) this untitled document was imported from + /// (ADR 0009). It names the document until it is saved, but is never written to: `path` + /// stays `None`, so Save asks for a new `.anicraft` name. + pub imported: Option, pub style: ToolStyle, /// Whether the rulers, grid and guides show and snap (ADR 0076): the editor's, not the /// document's. @@ -578,6 +582,7 @@ impl Session { state, saved_state: Some(state), path: None, + imported: None, style: ToolStyle::default(), aids: ViewAids::default(), text_style: cmds_text::TextStyle::default(), @@ -1331,6 +1336,10 @@ impl Session { "sounds": sounds, "revision": self.revision, "dirty": self.is_dirty(), + // The Animate file an untitled document came from, and the name Save suggests for + // it (ADR 0009). + "imported": self.imported.as_ref().map(|i| i.source.display().to_string()), + "save_as": self.imported.as_ref().map(|i| i.save_as.display().to_string()), "history": {"undo": self.history.undo_len(), "redo": self.history.redo_len(), "bytes": self.history.bytes(), "evicted": self.history.evicted}, "state": self.state, })) diff --git a/crates/engine/src/web_tests.rs b/crates/engine/src/web_tests.rs index 2d04c05c..61ebc084 100644 --- a/crates/engine/src/web_tests.rs +++ b/crates/engine/src/web_tests.rs @@ -103,3 +103,17 @@ fn imports_read_picked_files() { assert!(err.contains(".fla"), "an XFL folder can't come from a browser: {err}"); }); } + +/// A bare "walk.xfl" stands for the current folder, as a path that resolves, so reopening it +/// finds the tab its import has (ADR 0009). Run on the in-memory store, so the test needs no +/// working directory of its own. +#[test] +fn a_bare_xfl_files_package_is_a_folder_that_resolves() { + in_browser(|| { + vfs::put(Path::new("DOMDocument.xml"), b"".to_vec()).unwrap(); + vfs::put(Path::new("walk.xfl"), b"PROXY".to_vec()).unwrap(); + let package = crate::import_package(Path::new("walk.xfl")); + assert_eq!(package, Path::new("."), "the current folder, not an empty path"); + assert_eq!(crate::import_package(Path::new("walk.fla")), Path::new("walk.fla"), "a file that isn't an XFL proxy is its own package"); + }); +} diff --git a/crates/engine/tests/xfl_corpus.rs b/crates/engine/tests/xfl_corpus.rs index a90384fc..be78e113 100644 --- a/crates/engine/tests/xfl_corpus.rs +++ b/crates/engine/tests/xfl_corpus.rs @@ -373,3 +373,80 @@ fn file_open_names_the_sounds_and_videos_that_did_not_come_across() { let got = s.execute("file.open", &json!({"path": corpus().join("video").display().to_string(), "confirm": true})).unwrap(); assert_eq!(got["named"]["videos AniCraft can't play"], json!(["intro.flv: FLV, On2 VP6, 4.5 s", "gone.mp4: its file is missing, 1.0 s"])); } + +/// ADR 0009: an import is called by the Animate file it came from, while Save still asks for a +/// new name, first suggesting an `.anicraft` of the same name beside the original, whether the +/// XFL folder, the `.xfl` in it or a `.fla` was opened. Saving makes it the `.anicraft` file. +#[test] +fn an_import_keeps_its_animate_name_and_save_suggests_one_beside_it() { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-import-name"); + std::fs::create_dir_all(&dir).unwrap(); + let folder = corpus().join("primitives"); + let fla = dir.join("Walk Cycle.v2.FLA"); + std::fs::write(&fla, pack::pack(&pack::package(&folder), &pack::VARIANTS[0])).unwrap(); + let beside_folder = corpus().join("primitives.anicraft"); + for (opened, suggested) in [(folder.clone(), beside_folder.clone()), (folder.join("primitives.xfl"), beside_folder), (fla.clone(), dir.join("Walk Cycle.v2.anicraft"))] { + let mut s = Session::default(); + let info = s.execute("file.open", &json!({"path": opened.display().to_string()})).unwrap_or_else(|e| panic!("{}: {e}", opened.display())); + assert_eq!(s.imported.as_ref().map(|i| i.source.as_path()), Some(opened.as_path()), "the document is called by what was opened"); + assert!(s.path.is_none(), "{}: still untitled, so Save never writes over the Animate file", opened.display()); + assert!(s.execute("file.save", &json!({})).is_err(), "Save asks for a name"); + assert_eq!(info["imported"], json!(opened.display().to_string())); + assert_eq!(info["save_as"], json!(suggested.display().to_string()), "{}", opened.display()); + assert_eq!(anicraft_engine::Import::of(&opened).save_as, suggested); + assert_eq!(anicraft_engine::import_package(&opened), if opened == fla { fla.clone() } else { folder.clone() }, "the folder and its .xfl are one document"); + // A new document is no longer the import. + let mut t = Session::default(); + t.execute("file.open", &json!({"path": opened.display().to_string()})).unwrap(); + t.execute("file.new", &json!({"confirm": true})).unwrap(); + assert!(t.imported.is_none() && t.info()["imported"].is_null()); + } + // Saved, it is the .anicraft document: the import's name and suggestion are gone. + let mut s = Session::default(); + s.execute("file.open", &json!({"path": fla.display().to_string()})).unwrap(); + let saved = dir.join("Walk Cycle.v2.anicraft"); + s.execute("file.save", &json!({"path": saved.display().to_string(), "confirm": true})).unwrap(); + assert_eq!((s.path.as_deref(), s.imported.as_ref()), (Some(saved.as_path()), None)); + assert!(s.info()["save_as"].is_null()); + assert!(fla.is_file(), "the Animate file is untouched"); +} + +/// An import's name and Save suggestion are settled when it opens (ADR 0009): an XFL package +/// whose files change on disk afterwards still suggests saving beside its folder, not inside it. +#[test] +fn an_imports_save_suggestion_outlives_changes_to_its_package_on_disk() { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-import-settled"); + let folder = root.join("Walk.v2"); + std::fs::create_dir_all(&folder).unwrap(); + for f in ["DOMDocument.xml", "primitives.xfl"] { + std::fs::copy(corpus().join("primitives").join(f), folder.join(f)).unwrap(); + } + let xfl = folder.join("primitives.xfl"); + let mut s = Session::default(); + s.execute("file.open", &json!({"path": xfl.display().to_string()})).unwrap(); + std::fs::remove_file(folder.join("DOMDocument.xml")).unwrap(); + let info = s.info(); + assert_eq!(info["save_as"], json!(root.join("Walk.v2.anicraft").display().to_string()), "still beside the folder"); + assert_eq!(info["imported"], json!(xfl.display().to_string())); + std::fs::remove_dir_all(&root).ok(); +} + +/// A package reached through ".." is named after the folder it resolves to, and a folder named +/// "x.xfl" inside a package is a package of its own (ADR 0009). +#[test] +fn an_imports_package_is_the_folder_itself() { + let primitives = corpus().join("primitives"); + let up = primitives.join("golden").join(".."); + let real = std::fs::canonicalize(&primitives).unwrap(); + let import = anicraft_engine::Import::of(&up); + assert_eq!((import.source.as_path(), import.save_as), (up.as_path(), real.with_file_name("primitives.anicraft")), "beside the folder, not inside it"); + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("xfl-corpus-nested-package"); + let inner = root.join("outer").join("inner.xfl"); + std::fs::create_dir_all(&inner).unwrap(); + for dir in [root.join("outer"), inner.clone()] { + std::fs::copy(primitives.join("DOMDocument.xml"), dir.join("DOMDocument.xml")).unwrap(); + } + assert_eq!(anicraft_engine::import_package(&inner), inner, "a folder is never the .xfl file of the one around it"); + assert_eq!(anicraft_engine::Import::of(&inner).save_as, root.join("outer").join("inner.xfl.anicraft")); + std::fs::remove_dir_all(&root).ok(); +} diff --git a/docs/adr/0009-xfl-import.md b/docs/adr/0009-xfl-import.md index 8804d55e..aaaab0bc 100644 --- a/docs/adr/0009-xfl-import.md +++ b/docs/adr/0009-xfl-import.md @@ -27,6 +27,20 @@ elements) and `LIBRARY/*.xml` (symbols), with shape geometry encoded as edge str palette, the command line and agents all import the same way, and it inherits the unsaved-work confirmation. **An imported document is untitled**: Save asks for a new `.anicraft` name and can never write over the Animate file. + + *Note (2026-11):* untitled is about saving, not naming. An import keeps the name of what + was opened (`walk.fla`, `walk.xfl` or the XFL folder `walk`) on its tab and in the window + title, marked as imported (a dim "Imported" after the tab's name, "(imported)" in the + title, the source's path in the tab's tooltip), so artists see which file they are working + on. `Session::imported` (an `Import`) holds that source; `path` stays `None`, so Save is + still Save As. It first suggests `walk.anicraft` beside the original, and beside an XFL + folder rather than inside it (`file.open` and the session's info report it as `imported` + and `save_as`). The package and the suggestion are settled when the file is imported, so + later changes on disk don't move them. Saving clears the mark: the document is the + `.anicraft` file from then on. Opening the same Animate document again (the XFL folder or + the `.xfl` in it) shows its tab instead of importing it a second time; not in a browser, + where an upload is known only by its name. The same holds for XFL folders, `.fla` archives and older binary `.fla` files, + since they all enter through `file.open`. 5. **Report, don't guess.** Anything not yet mapped (bitmaps, text, sound, masks, motion tweens with property curves, shape tweens, filters, extra scenes) is counted and shown in the status bar after opening ("Imported. Not yet supported: 2 bitmaps, 1 text field."). diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index e2a30284..e91f779d 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -184,7 +184,7 @@ ActionScript 1.0 and 2.0, and scripts placed on instances. See [Interactivity](i ### Files, Test Movie and publishing * AniCraft saves `.anicraft` documents, an open, documented format. It **opens** `.fla`, `.xfl` - and XFL folders, as new, untitled documents, but can't save back to them. See + and XFL folders, as new documents named after the file, but can't save back to them. See [Opening Animate files](opening-animate-files.md). * There is **no SWF** export. For the web, **Export HTML Canvas** writes one page that plays the movie, buttons and scripts in any browser. Video (with your own ffmpeg), GIF, animated PNG and diff --git a/docs/guide/opening-animate-files.md b/docs/guide/opening-animate-files.md index 25489678..943da888 100644 --- a/docs/guide/opening-animate-files.md +++ b/docs/guide/opening-animate-files.md @@ -12,8 +12,8 @@ structure and from observation. On a Mac, read **⌘** wherever this chapter say 1. Choose **File › Open…** (**Ctrl+O**, **⌘O** on macOS). 2. Pick a `.fla` file, or the `.xfl` file inside an XFL folder. -3. AniCraft opens it as a new, untitled document, and the status bar says what came across and - what didn't. +3. AniCraft opens it as a new document named after the file, and the status bar says what came + across and what didn't. Other ways in: @@ -31,9 +31,12 @@ folder can't be opened there. ## Saving: your Animate file is never touched -An opened Animate file comes in **untitled**. When you save, AniCraft asks for a new name and -writes an `.anicraft` document, so the original `.fla` or XFL is never overwritten. The status -bar reminds you: "Save to keep it as an AniCraft document." +An opened Animate file keeps its name on its tab and in the window title, marked +**Imported**, but it has no AniCraft file yet. When you save, AniCraft asks for a new name, +suggesting one beside the original (`walk.fla` suggests `walk.anicraft` in the same folder), +and writes an `.anicraft` document, so the original `.fla` or XFL is never overwritten. The +status bar reminds you: "Save to keep it as an AniCraft document." Once saved, the tab shows +the `.anicraft` name. Hover over an imported tab to see which file it came from. AniCraft doesn't save back to `.fla` or XFL. diff --git a/docs/guide/troubleshooting-and-faq.md b/docs/guide/troubleshooting-and-faq.md index 262de43d..5cfb0635 100644 --- a/docs/guide/troubleshooting-and-faq.md +++ b/docs/guide/troubleshooting-and-faq.md @@ -233,8 +233,9 @@ a report after opening. Motion tweens from Animate files are not imported yet. S ### Can it save back to `.fla`? -No. AniCraft saves its own `.anicraft` format, and an opened Animate file comes in as a new, -untitled document, so saving never overwrites the original. +No. AniCraft saves its own `.anicraft` format. An opened Animate file keeps its name, marked +as imported, but saving always asks for a new `.anicraft` name, so it never overwrites the +original. ### Can it export SWF? diff --git a/src/app.rs b/src/app.rs index 01e1635f..eec22dba 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3958,8 +3958,8 @@ impl App { } let prompt = match id { "file.open" => Some((tr_noop!("Open document"), "path", "animation.anicraft".to_string())), - "file.save" if self.s.path.is_none() => Some((tr_noop!("Save document as"), "path", "animation.anicraft".to_string())), - "file.save_as" => Some((tr_noop!("Save document as"), "path", self.s.path.as_ref().map_or_else(|| "animation.anicraft".to_string(), |p| p.display().to_string()))), + "file.save" if self.s.path.is_none() => Some((tr_noop!("Save document as"), "path", self.save_suggestion())), + "file.save_as" => Some((tr_noop!("Save document as"), "path", self.save_suggestion())), "layer.rename" => Some((tr_noop!("Rename layer"), "name", self.s.active_layer().map_or_else(String::new, |l| l.name.clone()))), "scene.rename" => Some((tr_noop!("Rename scene"), "name", self.s.doc.scenes.get(self.s.scene).map_or_else(String::new, |s| s.name.clone()))), "file.export_png" => Some((tr_noop!("Export frame as PNG"), "path", format!("frame_{:04}.png", self.s.frame + 1))), @@ -4043,6 +4043,16 @@ impl App { self.request(id, json!({})); } + /// The name Save As offers: the document's own file, or for an unsaved import an + /// `.anicraft` of the same name beside the Animate file (ADR 0009), else a placeholder. + pub(crate) fn save_suggestion(&self) -> String { + match (&self.s.path, &self.s.imported) { + (Some(p), _) => p.display().to_string(), + (None, Some(import)) => import.save_as.display().to_string(), + (None, None) => "animation.anicraft".to_string(), + } + } + /// The stage point at the centre of the visible canvas. /// Pastes the system clipboard's picture, when it is newer than what AniCraft copied. /// AniCraft's own Copy leaves a note as text on the system clipboard, so while that note is @@ -4494,8 +4504,7 @@ impl App { } fn update_title(&mut self, ctx: &egui::Context) { - let name = crate::tabs::active_name(self); - let title = format!("AniCraft — {name}{}", if self.s.is_dirty() { " •" } else { "" }); // i18n-exempt: the product name and the file's + let title = crate::tabs::window_title(self); if title != self.title { ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone())); self.title = title; diff --git a/src/platform.rs b/src/platform.rs index 6ceed0d8..329ab203 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -1003,6 +1003,18 @@ pub fn reads_file(cmd: &str) -> bool { matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_video" | "layer.set_video" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import" | "data.import_table" | "macro.run" | "macro.import") } +/// A save dialog's suggestion split into the folder it opens in and the name in its field: a +/// full path ("/art/walk.anicraft", the file the document has or, for an import, beside the +/// Animate file) opens in its folder when that exists; a bare name opens wherever the platform +/// last did. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn split_suggestion(default_name: &str) -> (Option, String) { + let path = std::path::Path::new(default_name); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty() && d.is_dir()).map(std::path::Path::to_path_buf); + let name = path.file_name().map_or_else(|| default_name.to_string(), |n| n.to_string_lossy().into_owned()); + (dir, name) +} + /// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with /// `title` already in the interface language. `None` when cancelled. #[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos")))] @@ -1012,7 +1024,15 @@ pub fn file_dialog(cmd: &str, title: &str, default_name: &str) -> Option d.add_filter(label, exts).pick_file(), "file.export_png_sequence" | "file.export_svg_sequence" => d.pick_folder(), - _ => d.add_filter(label, exts).set_file_name(default_name).save_file(), + _ => { + let (dir, name) = split_suggestion(default_name); + let d = d.add_filter(label, exts).set_file_name(name); + match dir { + Some(dir) => d.set_directory(dir), + None => d, + } + .save_file() + } } } @@ -1053,7 +1073,15 @@ pub fn start_file_dialog(cmd: &str, title: &str, default_name: &str, window: &ef let answer: Answer = match cmd { c if reads_file(c) => Box::pin(d.add_filter(label, exts).pick_file()), "file.export_png_sequence" | "file.export_svg_sequence" => Box::pin(d.pick_folder()), - _ => Box::pin(d.add_filter(label, exts).set_file_name(default_name).save_file()), + _ => { + let (dir, name) = split_suggestion(default_name); + let d = d.add_filter(label, exts).set_file_name(name); + Box::pin(match dir { + Some(dir) => d.set_directory(dir), + None => d, + } + .save_file()) + } }; let _ = sheet_tx.send(answer); } @@ -1246,6 +1274,19 @@ mod tests { assert_eq!(menu_inset(), 0.0); } + /// A save dialog opens in the suggested file's folder with only its name in the field + /// (ADR 0009: an import's `.anicraft` goes beside the Animate file). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_save_suggestion_opens_in_its_folder_with_its_name() { + let dir = std::env::temp_dir(); + let full = dir.join("walk.anicraft"); + assert_eq!(split_suggestion(&full.display().to_string()), (Some(dir.clone()), "walk.anicraft".to_string())); + assert_eq!(split_suggestion("animation.anicraft"), (None, "animation.anicraft".to_string()), "a bare name: the platform picks the folder"); + let gone = dir.join("anicraft-no-such-folder-here").join("walk.anicraft"); + assert_eq!(split_suggestion(&gone.display().to_string()).0, None, "a folder that isn't there is not offered"); + } + #[test] fn the_desktop_runs_every_command() { assert!(anicraft_engine::commands().iter().all(|c| unavailable(c.id).is_none())); diff --git a/src/tabs.rs b/src/tabs.rs index cf3eb365..744a814a 100644 --- a/src/tabs.rs +++ b/src/tabs.rs @@ -119,6 +119,9 @@ pub struct TabInfo { pub name: String, pub dirty: bool, pub path: Option, + /// The Animate file an unsaved import came from (ADR 0009): the tab is named after it and + /// marked "Imported". + pub imported: Option, pub active: bool, } @@ -200,9 +203,13 @@ impl Tabs { } } -/// A document's name on its tab: the file's, or "Untitled" (numbered from the second on). -fn name_of(untitled: u32, path: Option<&Path>) -> String { - match path.and_then(Path::file_name) { +/// A document's name on its tab: the file's, the Animate file's it was imported from (ADR 0009), +/// or "Untitled" (numbered from the second on). +fn name_of(untitled: u32, s: &Session) -> String { + // An import is named after what was opened, or after its folder when that path has no + // name of its own ("walk/sub/.."). + let imported = s.imported.as_ref().and_then(|i| i.source.file_name().or_else(|| i.package.file_name())); + match s.path.as_deref().and_then(Path::file_name).or(imported) { Some(n) => n.to_string_lossy().into_owned(), None if untitled <= 1 => tr!("Untitled").to_string(), None => tr!("Untitled {n}", n = untitled), @@ -219,7 +226,8 @@ fn session(app: &App, i: usize) -> Option<&Session> { pub fn info(app: &App, i: usize) -> Option { let slot = app.tabs.slots.get(i)?; let s = session(app, i)?; - Some(TabInfo { id: slot.id, name: name_of(slot.untitled, s.path.as_deref()), dirty: s.is_dirty(), path: s.path.clone(), active: i == app.tabs.active }) + let imported = if s.path.is_none() { s.imported.as_ref().map(|i| i.source.clone()) } else { None }; + Some(TabInfo { id: slot.id, name: name_of(slot.untitled, s), dirty: s.is_dirty(), path: s.path.clone(), imported, active: i == app.tabs.active }) } /// Every tab, in the bar's order. @@ -232,6 +240,17 @@ pub fn active_name(app: &App) -> String { info(app, app.tabs.active).map_or_else(|| tr!("Untitled").to_string(), |t| t.name) } +/// The window's title for the shown document: its name, marked when it is an unsaved import +/// (ADR 0009), and a dot while it has unsaved changes. +pub fn window_title(app: &App) -> String { + let name = match info(app, app.tabs.active) { + Some(t) if t.imported.is_some() => tr!("{name} (imported)", name = t.name), + Some(t) => t.name, + None => tr!("Untitled").to_string(), + }; + format!("AniCraft — {name}{}", if app.s.is_dirty() { " •" } else { "" }) // i18n-exempt: the product name and the document's +} + /// Whether any open document has unsaved changes. pub fn any_dirty(app: &App) -> bool { (0..app.tabs.len()).any(|i| session(app, i).is_some_and(Session::is_dirty)) @@ -406,7 +425,17 @@ fn already_open(app: &App, id: &str, params: &Value) -> Option { }, _ => return None, }; - (0..app.tabs.len()).find(|i| session(app, *i).and_then(|s| s.path.as_deref()).is_some_and(|p| same_file(p, &path))) + // An unsaved import of the same Animate document counts too, whether its XFL folder or the + // .xfl in it was opened. Not in a browser: an upload is known only by its name there, and + // two different files may share one. + let package = anicraft_engine::import_package(&path); + (0..app.tabs.len()).find(|i| { + session(app, *i).is_some_and(|s| match (&s.path, &s.imported) { + (Some(p), _) => same_file(p, &path), + (None, Some(import)) => !platform::WEB && same_file(&import.package, &package), + (None, None) => false, + }) + }) } /// The shown document is the one the app started with, untouched: what is opened takes its @@ -447,7 +476,7 @@ pub fn open(app: &mut App, id: &str, params: Value) -> Option { let id_new = app.tabs.next_id; app.tabs.next_id += 1; // The lowest number no open document without a file has. - let taken: Vec = (0..app.tabs.len()).filter(|i| session(app, *i).is_some_and(|s| s.path.is_none())).filter_map(|i| app.tabs.slots.get(i).map(|s| s.untitled)).collect(); + let taken: Vec = (0..app.tabs.len()).filter(|i| session(app, *i).is_some_and(|s| s.path.is_none() && s.imported.is_none())).filter_map(|i| app.tabs.slots.get(i).map(|s| s.untitled)).collect(); let untitled = (1..=MAX_TABS as u32 + 1).find(|n| !taken.contains(n)).unwrap_or(1); let parked = Parked { s: Session::new(Document::default()), view: DocView::fresh(app), saver: app.recovery.for_new_document() }; app.tabs.slots.push(Slot { id: id_new, untitled, placeholder: false, parked: Some(Box::new(parked)) }); @@ -685,9 +714,23 @@ fn elided(p: &egui::Painter, name: &str, width: f32) -> std::sync::Arc String { - if t.dirty { tr!("{name}, unsaved changes", name = t.name) } else { t.name.clone() } + match (t.imported.is_some(), t.dirty) { + (true, true) => tr!("{name}, imported, unsaved changes", name = t.name), + (true, false) => tr!("{name}, imported", name = t.name), + (false, true) => tr!("{name}, unsaved changes", name = t.name), + (false, false) => t.name.clone(), + } } +/// The dim "Imported" after an unsaved import's name (ADR 0009). It never shortens: the name +/// gives way first. +fn imported_tag(p: &egui::Painter) -> std::sync::Arc { + p.layout_no_wrap(tr!("Imported").to_string(), font(Type::Caption), T.text_dim) +} + +/// The gap between a name and its "Imported". +const TAG_GAP: f32 = 6.0; + /// The document tabs, above the edit bar: one per open document, with a dot while it has /// unsaved changes and a button to close it. Click shows a document, middle click closes it, /// a drag moves the tab, right-click has Close, Close Others, Close All and where the file is. @@ -696,7 +739,11 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) { let full = ui.max_rect(); let mut acts: Vec = Vec::new(); // How wide each tab is: its name, within limits; all a little narrower when they don't fit. - let natural: Vec = tabs.iter().map(|t| (elided(ui.painter(), &t.name, TAB_MAX).rect.width() + 2.0 * PAD + CLOSE_W + DOT_W).clamp(TAB_MIN, TAB_MAX)).collect(); + let tag_w = imported_tag(ui.painter()).rect.width() + TAG_GAP; + let natural: Vec = tabs + .iter() + .map(|t| (elided(ui.painter(), &t.name, TAB_MAX).rect.width() + if t.imported.is_some() { tag_w } else { 0.0 } + 2.0 * PAD + CLOSE_W + DOT_W).clamp(TAB_MIN, TAB_MAX)) + .collect(); let wanted: f32 = natural.iter().sum(); let shrink = if wanted > full.width() && wanted > 0.0 { (full.width() / wanted).max(TAB_MIN / TAB_MAX) } else { 1.0 }; let widths: Vec = natural.iter().map(|w| (w * shrink).max(TAB_MIN.min(*w))).collect(); @@ -757,9 +804,15 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) { p.circle_filled(pos2(left + 3.5, r.center().y), 3.5, if t.active { T.accent } else { T.text_dim }); left += DOT_W; } - let galley = elided(p, &t.name, close_r.left() - 4.0 - left); + let tag = t.imported.is_some().then(|| imported_tag(p)); + let room = close_r.left() - 4.0 - left - tag.as_ref().map_or(0.0, |g| g.rect.width() + TAG_GAP); + let galley = elided(p, &t.name, room); let cut = galley.elided; + let after = left + galley.rect.width() + TAG_GAP; p.galley_with_override_text_color(pos2(left, r.center().y - galley.rect.height() * 0.5), galley, if t.active { T.text } else { T.text_dim }); + if let Some(g) = tag { + p.galley(pos2(after, r.center().y - g.rect.height() * 0.5), g, T.text_dim); + } // The close button: an ×, brighter under the pointer. if close.hovered() { p.rect_filled(close_r, T.rc(), T.hover); @@ -781,9 +834,10 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) { app.tabs.drag = Some(t.id); acts.push(Act::Show(t.id)); } - let place = match &t.path { - Some(path) => path.display().to_string(), - None => tr!("Not saved yet").to_string(), + let place = match (&t.path, &t.imported) { + (Some(path), _) => path.display().to_string(), + (None, Some(from)) => tr!("Imported from {path}. Saving makes a new AniCraft document; the original is never changed.", path = from.display().to_string()), + (None, None) => tr!("Not saved yet").to_string(), }; let tip = if cut { format!("{}\n{place}", t.name) } else { place }; close.on_hover_text(tr!("Close")); diff --git a/src/tabs_tests.rs b/src/tabs_tests.rs index b997606d..25ad8692 100644 --- a/src/tabs_tests.rs +++ b/src/tabs_tests.rs @@ -84,6 +84,51 @@ fn the_first_document_opened_takes_the_samples_place_and_the_next_gets_a_tab() { assert_eq!(app.tabs.len(), 2); } +/// ADR 0009: an imported Animate file's tab and the window are named after it and marked as +/// imported, while it stays untitled: Save As offers an `.anicraft` beside the original, opening +/// the same file again shows its tab, and once saved it is the `.anicraft` document. +#[test] +fn an_import_is_named_after_its_animate_file_until_it_is_saved() { + let (ctx, mut app) = app(); + let corpus = Path::new(env!("CARGO_MANIFEST_DIR")).join("crates/xfl/tests/corpus"); + let folder = corpus.join("primitives"); + app.request("file.open", json!({"path": folder.display().to_string()})); + settle(&ctx, &mut app); + assert!(app.s.path.is_none(), "still untitled: Save never writes over the Animate file"); + assert_eq!(names(&app), ["primitives"]); + let t = &infos(&app)[0]; + assert_eq!(t.imported.as_deref(), Some(folder.as_path())); + assert_eq!(spoken(t), "primitives, imported"); + assert_eq!(window_title(&app), "AniCraft — primitives (imported)"); + assert_eq!(app.save_suggestion(), corpus.join("primitives.anicraft").display().to_string(), "beside the XFL folder"); + // Reached through "..", it is still named after its folder. + let (_, mut other) = self::app(); + other.request("file.open", json!({"path": folder.join("golden").join("..").display().to_string()})); + assert_eq!(names(&other), ["primitives"]); + // A new document is "Untitled": the import has a name of its own. + app.request("file.new", json!({})); + assert_eq!(names(&app), ["primitives", "Untitled"]); + assert_eq!(window_title(&app), "AniCraft — Untitled"); + // Opening the same Animate file again shows its tab instead of importing it twice, and so + // does the .xfl in its folder: they are one document. + app.request("file.open", json!({"path": folder.display().to_string()})); + assert_eq!((app.tabs.len(), app.tabs.active()), (2, 0)); + app.request("file.new", json!({})); + app.request("file.open", json!({"path": folder.join("primitives.xfl").display().to_string()})); + assert_eq!((app.tabs.len(), app.tabs.active()), (3, 0), "the .xfl shows the folder's tab"); + assert_eq!(names(&app), ["primitives", "Untitled", "Untitled 2"]); + // Saved, it is the .anicraft document, no longer marked. + let dir = std::env::temp_dir().join(format!("anicraft-tabs-import-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let saved = dir.join("primitives.anicraft"); + app.run("file.save", json!({"path": saved.display().to_string(), "confirm": true})); + assert_eq!(names(&app), ["primitives.anicraft", "Untitled", "Untitled 2"]); + assert!(infos(&app)[0].imported.is_none()); + assert_eq!(window_title(&app), "AniCraft — primitives.anicraft"); + assert_eq!(app.save_suggestion(), saved.display().to_string()); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn switching_keeps_each_documents_undo_selection_playhead_and_view() { let (ctx, mut app) = app();