diff --git a/CHANGELOG.md b/CHANGELOG.md index 23c1f347..863d7ed6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +* **Insert › New Symbol…** (Ctrl+F8, #655): creates a new, empty graphic, movie clip or button + symbol in the Library (optionally inside a folder) and opens it for editing without placing an + instance on the stage. Also available from the Library panel's New Symbol button and as + `library.new_symbol`. * **Flash 8 to CS4 `.fla` files open** (backlog P-039, ADR 0120, #163; by rcoenen, #478 and #481): the binary `.fla` of the Flash 8 to CS4 era, which AniCraft used to refuse, now opens like an Animate file, untitled, so Save asks for a new `.anicraft` name. diff --git a/crates/engine/src/access.rs b/crates/engine/src/access.rs index 7715d43e..e6e2d217 100644 --- a/crates/engine/src/access.rs +++ b/crates/engine/src/access.rs @@ -403,6 +403,7 @@ pub const NOT_FILES: &[&str] = &[ "text.path", "text.release_path", "library.items", + "library.new_symbol", "library.new_folder", "library.rename", "library.move", diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index 9d9b8567..a0f5f1a5 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -8,7 +8,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::library::{MAX_FOLDER_DEPTH, MAX_FOLDERS}; -use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryFolder, LibraryItem, Paint, SoundId, SymbolId, SymbolKind, Timeline}; +use anicraft_doc::{BitmapId, ElementKind, FolderId, Layer, LayerId, LibraryEntry, LibraryFolder, LibraryItem, Paint, SoundId, Symbol, SymbolId, SymbolKind, Timeline}; use serde_json::{Value, json}; use std::collections::HashSet; use std::sync::Arc; @@ -17,6 +17,15 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("library.items", "List Library", "", None, "{} every folder (id, name, parent, path) and item (symbol | bitmap | sound id, kind, name, folder, path, uses, unused) in Library order; `uses` counts instances, bitmap fills and keyframe sounds once per keyframe", false, items as crate::RunFn), + c( + "library.new_symbol", + "New Symbol…", + "Insert", + Some("Ctrl+F8"), + "{name? (default: the next free “Symbol n”), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level), edit?: bool (default: true: open the new symbol for editing)} → {id, name, kind}: creates an empty symbol in the Library without placing it on the stage", + true, + new_symbol, + ), c("library.new_folder", "New Folder", "", None, "{name? (default: the next free “Folder n”), parent?: folder id} → {folder, name}; names are unique within a folder (case aside) and can't hold “/”", true, new_folder), c("library.rename", "Rename", "", None, "{symbol | bitmap | sound | folder: id, name} renames a Library item or folder; the name must be free in its folder (case aside) and can't hold “/”", true, rename), c("library.move", "Move to Folder", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..], to: folder id | null (the top level)} moves items and folders (with what they hold) into a folder; a folder can't go inside itself, and a name the folder already has stops the move", true, move_to), @@ -175,6 +184,27 @@ fn items(s: &mut Session, _: &Value) -> Result { Ok(json!({"folders": folders, "items": items, "unused": unused.len()})) } +fn new_symbol(s: &mut Session, p: &Value) -> Result { + let folder = opt_folder(s, p, "folder")?; + let kind = opt_str(p, "kind")?.map(kind_of).transpose()?.unwrap_or(SymbolKind::Graphic); + let edit = opt_bool(p, "edit")?.unwrap_or(true); + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(folder, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.numbered_name(folder, "Symbol", s.doc.library.len() + 1), + }; + let id = SymbolId(s.doc.alloc_id()); + let layer = Layer::new(LayerId(s.doc.alloc_id()), "Layer 1"); + let sym = Symbol { id, name: name.clone(), kind, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(layer)] } }; + s.doc.library.push(Arc::new(sym)); + if folder.is_some() { + s.doc.place_entry(LibraryEntry::Item(LibraryItem::Symbol(id)), folder); + } + if edit { + crate::editing::edit(s, &json!({"symbol": id.0}))?; + } + Ok(json!({"id": id.0, "name": name, "kind": kind_key(kind)})) +} + fn new_folder(s: &mut Session, p: &Value) -> Result { let parent = opt_folder(s, p, "parent")?; if s.doc.library_tree.folders.len() >= MAX_FOLDERS { diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs index 318b460d..9699bf30 100644 --- a/crates/engine/src/library_tests.rs +++ b/crates/engine/src/library_tests.rs @@ -268,6 +268,57 @@ fn convert_to_symbol_picks_a_free_name() { assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken"); } +#[test] +fn new_symbol_creates_an_empty_symbol_enters_it_and_undoes_in_one_step() { + let mut s = Session::default(); + let before_lib = s.doc.library.len(); + let before_stage = s.elements_on(s.layer).len(); + // Explicit name and kind; edit defaults to true and enters the new empty symbol. + let v = run(&mut s, "library.new_symbol", json!({"name": "Hero", "kind": "movie_clip"})); + let id = SymbolId(v["id"].as_u64().unwrap()); + assert_eq!((v["name"].as_str(), v["kind"].as_str()), (Some("Hero"), Some("movie_clip"))); + assert_eq!(s.doc.library.len(), before_lib + 1); + assert_eq!(s.editing_symbol(), Some(id), "edit defaults to true"); + let sym = s.doc.symbol(id).expect("in the Library"); + assert_eq!(sym.kind, anicraft_doc::SymbolKind::MovieClip); + assert_eq!(sym.timeline.layers.len(), 1); + assert_eq!(sym.timeline.layers[0].keyframes.len(), 1); + assert!(sym.timeline.layers[0].keyframes[0].elements.is_empty(), "the new symbol starts empty"); + assert_eq!(instances(&s, id.0), 0, "nothing is placed on the stage"); + // Undo removes the symbol and leaves symbol editing in one step. + s.undo().unwrap(); + assert_eq!(s.doc.library.len(), before_lib); + assert!(s.doc.symbol(id).is_none()); + assert_eq!(s.editing_symbol(), None); + assert_eq!(s.elements_on(s.layer).len(), before_stage); + // Redo brings it back and re-enters it. + s.redo().unwrap(); + assert!(s.doc.symbol(id).is_some()); + assert_eq!(s.editing_symbol(), Some(id)); + run(&mut s, "symbol.exit", json!({"all": true})); + // Default name picks a free "Symbol N" that differs from existing names; edit: false stays on stage. + let a = run(&mut s, "library.new_symbol", json!({"edit": false})); + let b = run(&mut s, "library.new_symbol", json!({"edit": false, "kind": "button"})); + assert_eq!(s.editing_symbol(), None, "edit: false does not enter the symbol"); + assert_ne!(a["name"], b["name"]); + assert_eq!(a["kind"], "graphic"); + assert_eq!(b["kind"], "button"); + // Folder placement works and duplicates are checked per folder (case aside). + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Cast"}))); + let in_folder = run(&mut s, "library.new_symbol", json!({"name": "Hero", "folder": f, "edit": false})); + assert_eq!(path(&s, in_folder["id"].as_u64().unwrap()), "Cast/Hero"); + // Refusals: duplicate name (case-insensitive), empty/whitespace, slash, unknown kind, missing folder. + let lib_before_err = s.doc.library.len(); + assert!(err(&mut s, "library.new_symbol", json!({"name": "hero"})).contains("already has")); + assert!(err(&mut s, "library.new_symbol", json!({"name": "HERO", "folder": f})).contains("already has")); + assert!(err(&mut s, "library.new_symbol", json!({"name": ""})).contains("empty")); + assert!(err(&mut s, "library.new_symbol", json!({"name": " "})).contains("empty")); + assert!(err(&mut s, "library.new_symbol", json!({"name": "a/b"})).contains("/")); + assert!(err(&mut s, "library.new_symbol", json!({"kind": "sprite"})).contains("unknown symbol type")); + assert!(err(&mut s, "library.new_symbol", json!({"folder": 999_999})).contains("no folder")); + assert_eq!(s.doc.library.len(), lib_before_err, "refused calls add nothing"); +} + #[test] fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() { let mut s = Session::default(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 933cac2c..66e07b4a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1859,6 +1859,7 @@ fn animate_default_keys_map_to_the_same_commands() { ("Shift+,", "timeline.first_frame"), ("Shift+.", "timeline.last_frame"), ("F8", "modify.convert_to_symbol"), + ("Ctrl+F8", "library.new_symbol"), ("Ctrl+Enter", "control.test_movie"), ("Ctrl+B", "modify.break_apart"), ("Ctrl+Shift+Z", "modify.remove_transform"), diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 38d391ac..5c8491b2 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 406 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 407 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. @@ -153,6 +153,8 @@ This page is generated from the command registry, so it always matches the versi Parameters: `{} (a camera layer on top of the scene, at rest: it sees the stage as it is; nothing happens if there is one)` - **New Scene** `scene.new` · changes the document Parameters: `{name?}` +- **New Symbol…** `library.new_symbol` · **Ctrl+F8** (macOS **⌘F8**) · changes the document + Parameters: `{name? (default: the next free “Symbol n”), kind?: graphic|movie_clip|button (default: graphic), folder?: Library folder id (default: the top level), edit?: bool (default: true: open the new symbol for editing)} → {id, name, kind}: creates an empty symbol in the Library without placing it on the stage` ## Modify diff --git a/docs/guide/reference/shortcuts.md b/docs/guide/reference/shortcuts.md index 0f2d96c3..3bd9ac11 100644 --- a/docs/guide/reference/shortcuts.md +++ b/docs/guide/reference/shortcuts.md @@ -129,6 +129,7 @@ This page is generated from the editor's shortcut map, so it always matches the | Timeline › Keyframe | F6 | F6 | | Timeline › Blank Keyframe | F7 | F7 | | Timeline › Clear Keyframe | Shift+F6 | ⇧F6 | +| New Symbol… | Ctrl+F8 | ⌘F8 | ## Modify diff --git a/docs/guide/symbols-and-library.md b/docs/guide/symbols-and-library.md index 58727bd8..8b202ce6 100644 --- a/docs/guide/symbols-and-library.md +++ b/docs/guide/symbols-and-library.md @@ -45,6 +45,18 @@ layers, the symbol keeps those layers inside it, and the instance goes on the to Names are unique within a folder: if the name is taken, the dialog shows the name the symbol will get instead. The next time, the dialog offers the type and folder you used last. +To start from an empty symbol and draw inside it: + +1. Choose **Insert › New Symbol…** (**Ctrl+F8**), or click the **+** (**New Symbol**) button + under the Library list. +2. Type a **Name**, choose a **Type** (Graphic, Movie clip or Button), and choose the Library + **Folder** it goes into. +3. Press **OK**. + +The new symbol is added to the Library with one empty layer and opens straight into symbol +editing so you can draw its artwork right away, without placing an instance on the stage. +Names must be unique within a folder (capitals aside). + You can also make symbols by importing (see [Importing into the Library](#importing-into-the-library)). ## Editing a symbol in place diff --git a/docs/parity.md b/docs/parity.md index 4a5b5c91..6e05bc14 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -33,7 +33,7 @@ AniCraft is an independent, open-source project, and is not affiliated with or e | Drawing model | 16 | 3 | 4 | 0 | | Colour | 8 | 1 | 2 | 2 | | Text | 8 | 5 | 5 | 2 | -| Symbols and Library | 13 | 3 | 4 | 0 | +| Symbols and Library | 14 | 3 | 3 | 0 | | Timeline | 16 | 2 | 9 | 0 | | Tweens and the Motion Editor | 12 | 2 | 4 | 0 | | Bones and rigging | 8 | 2 | 3 | 0 | @@ -49,7 +49,7 @@ AniCraft is an independent, open-source project, and is not affiliated with or e | Accessibility | 4 | 2 | 1 | 0 | | Preferences and shortcuts | 6 | 2 | 0 | 1 | | Automation | 4 | 2 | 1 | 1 | -| **All** | **198** | **53** | **70** | **27** | +| **All** | **199** | **53** | **69** | **27** | The counts are of the rows below, so they weigh a small feature like a large one. The backlog, not this table, says what matters most. @@ -209,7 +209,7 @@ not this table, says what matters most. |---|---|---| | Graphic, movie clip and button symbols | **done** | [symbols](guide/symbols-and-library.md). | | Convert to Symbol, with name, type, folder | **done** | Missing: the registration point grid in the dialog (P-021). | -| New Symbol (empty, Ctrl+F8) | **missing** | P-021. | +| New Symbol (empty, Ctrl+F8) | **done** | Insert › New Symbol… (`library.new_symbol`, [#655](https://github.com/storytold/anicraft/issues/655)), and the Library panel's New Symbol button. | | Edit in place, edit symbols, the path back | **done** | [ADR 0045](adr/0045-raw-points-and-raw-shapes-inside-symbols.md). A rotated instance opens upright. | | Graphic looping: loop, play once, single frame, first frame | **done** | Reverse loop modes import from Animate files†. | | Swap Symbol, Duplicate Symbol | **done** | | diff --git a/src/app.rs b/src/app.rs index fec96a4e..860da9a4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -405,6 +405,8 @@ pub struct App { pub prompt: Option, /// The Convert to Symbol dialog, and what it chose last (ADR 0053). pub convert: Option, + /// The Create New Symbol dialog (Ctrl+F8, #655). + pub new_symbol: Option, /// The Layer Properties dialog while it is open (ADR 0061). pub layer_props: Option, /// Open the timeline's Frame View menu on the next frame (screenshots, the audit). @@ -841,6 +843,7 @@ impl App { left_out_said: false, prompt: None, convert: None, + new_symbol: None, layer_props: None, tl_frame_view_open: false, tl_header_spill: 0.0, @@ -3502,7 +3505,7 @@ impl App { /// Any modal (prompt, confirmation, close guard) is open: global shortcuts pause. pub fn modal_open(&self) -> bool { - self.prompt.is_some() || self.convert.is_some() || self.shape_dialog.is_some() || self.trace.is_some() || self.doc_settings.is_some() || self.audio_keys.is_some() || self.confirm.is_some() || self.tabs.asking() || self.plugin_dialog.is_some() || self.templates.save.is_some() || self.video_import.is_some() + self.prompt.is_some() || self.convert.is_some() || self.new_symbol.is_some() || self.shape_dialog.is_some() || self.trace.is_some() || self.doc_settings.is_some() || self.audio_keys.is_some() || self.confirm.is_some() || self.tabs.asking() || self.plugin_dialog.is_some() || self.templates.save.is_some() || self.video_import.is_some() } /// The single entry point for user-initiated commands: asks first when the engine says the @@ -3927,6 +3930,11 @@ impl App { crate::convert_symbol::open(self); return; } + if id == "library.new_symbol" { + // Empty symbol in the Library, opened for editing (#655). + crate::new_symbol::open(self); + return; + } // A picture copied in another app (a paint program, a screenshot) is what Paste means // when it is the newest thing copied (#263). if matches!(id, "edit.paste" | "edit.paste_in_place") && self.paste_from_system() { @@ -4997,6 +5005,7 @@ impl App { crate::drop::frame(self, &ctx); self.prompt_window(&ctx); crate::convert_symbol::window(self, &ctx); + crate::new_symbol::window(self, &ctx); crate::shape_dialogs::window(self, &ctx); crate::trace_dialog::window(self, &ctx); crate::doc_settings::window(self, &ctx); diff --git a/src/context_help.rs b/src/context_help.rs index d4c0d6d3..5503052f 100644 --- a/src/context_help.rs +++ b/src/context_help.rs @@ -66,6 +66,7 @@ pub enum Dialog { FindReplace, BrushLibrary, ConvertSymbol, + NewSymbol, ShapeEdges, TraceBitmap, LayerProperties, @@ -90,7 +91,7 @@ pub enum Dialog { } impl Dialog { - pub const ALL: [Dialog; 31] = [ + pub const ALL: [Dialog; 32] = [ Dialog::Preferences, Dialog::Shortcuts, Dialog::Licenses, @@ -101,6 +102,7 @@ impl Dialog { Dialog::FindReplace, Dialog::BrushLibrary, Dialog::ConvertSymbol, + Dialog::NewSymbol, Dialog::ShapeEdges, Dialog::TraceBitmap, Dialog::LayerProperties, @@ -137,6 +139,7 @@ impl Dialog { Dialog::FindReplace => "find_replace", Dialog::BrushLibrary => "brush_library", Dialog::ConvertSymbol => "convert_symbol", + Dialog::NewSymbol => "new_symbol", Dialog::ShapeEdges => "shape_edges", Dialog::TraceBitmap => "trace_bitmap", Dialog::LayerProperties => "layer_props", @@ -168,7 +171,7 @@ impl Dialog { Dialog::PublishProgress => "exporting-and-publish.md#publish", Dialog::FindReplace => "workspace.md#find-and-replace", Dialog::BrushLibrary => "drawing.md#the-brush", - Dialog::ConvertSymbol => "symbols-and-library.md#making-a-symbol", + Dialog::ConvertSymbol | Dialog::NewSymbol => "symbols-and-library.md#making-a-symbol", Dialog::ShapeEdges => "drawing.md#lines-to-fills-expanding-and-softening-fills", Dialog::TraceBitmap => "images-and-sound.md#trace-bitmap", Dialog::LayerProperties => "timeline.md#layer-properties", @@ -231,6 +234,7 @@ pub const COMMAND_TOPICS: &[(&str, &str)] = &[ ("instance.", "symbols-and-library.md#instance-properties"), ("layer.", "timeline.md#layers"), ("library.", "symbols-and-library.md#the-library-panel"), + ("library.new_symbol", "symbols-and-library.md#making-a-symbol"), ("macro.", "saved-commands.md#saving-steps-as-a-command"), ("modify.", "drawing.md#transforming-artwork"), ("modify.convert_to_bitmap", "images-and-sound.md#convert-to-bitmap"), @@ -356,6 +360,9 @@ pub fn subject(app: &App, ctx: &egui::Context, pointer: bool) -> Subject { if app.convert.is_some() { return Subject::Dialog(Dialog::ConvertSymbol); } + if app.new_symbol.is_some() { + return Subject::Dialog(Dialog::NewSymbol); + } // Expand Fill and Soften Fill Edges (ADR 0109). if app.shape_dialog.is_some() { return Subject::Dialog(Dialog::ShapeEdges); diff --git a/src/dialogs.rs b/src/dialogs.rs index 0d989dbd..97430e06 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -211,7 +211,7 @@ impl Entry { /// Commands the palette can run without extra input (everything optional, or prompted). fn runnable(c: &CommandSpec) -> bool { - if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.import_video" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "file.export_svg_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install" | "data.import_table" | "data.bind") { + if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.import_video" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "file.export_svg_sequence" | "modify.convert_to_symbol" | "library.new_symbol" | "layer.rename" | "scene.rename" | "plugin.install" | "data.import_table" | "data.bind") { return true; } let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}'); diff --git a/src/library.rs b/src/library.rs index da4fb563..ef5d1a36 100644 --- a/src/library.rs +++ b/src/library.rs @@ -367,14 +367,25 @@ fn drag_ghost(app: &App, ctx: &egui::Context) { painter.galley(at, galley, color(Type::Body)); } -/// A new folder in the selected row's folder (or the selected folder), opened, selected and -/// ready to be named. -fn new_folder(app: &mut App) { - let parent = match app.library.sel.as_slice() { +/// The folder a new item or folder goes into: the selected folder, or the selected item's folder. +fn target_folder(app: &App) -> Option { + match app.library.sel.as_slice() { [LibraryEntry::Folder(f)] => Some(*f), [one] => app.s.doc.parent_of(*one), _ => None, - }; + } +} + +/// Opens the Create New Symbol dialog targeting the selected folder (or the top level). +fn new_symbol(app: &mut App) { + let parent = target_folder(app); + crate::new_symbol::open_in(app, parent); +} + +/// A new folder in the selected row's folder (or the selected folder), opened, selected and +/// ready to be named. +fn new_folder(app: &mut App) { + let parent = target_folder(app); if let Some(p) = parent { app.library.expanded.insert(p); } @@ -410,9 +421,14 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) { if doc.library_items().next().is_none() && doc.library_tree.folders.is_empty() { let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default(); ui.label(text(Type::Caption, tr!("No symbols, images or sounds yet. Select artwork and press {convert} to make a symbol, or import an image or a sound with {import}.", convert = key("modify.convert_to_symbol"), import = key("file.import")))); - if ui.button(tr!("New Folder")).clicked() { - new_folder(app); - } + ui.horizontal(|ui| { + if ui.button(tr!("New Symbol…")).clicked() { + crate::new_symbol::open(app); + } + if ui.button(tr!("New Folder")).clicked() { + new_folder(app); + } + }); return; } toolbar(app, ui); @@ -631,6 +647,11 @@ fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet, + pub error: Option, + /// The name field takes the keyboard on the first frame. + focus: bool, +} + +const KINDS: [SymbolKind; 3] = [SymbolKind::Graphic, SymbolKind::MovieClip, SymbolKind::Button]; + +/// Opens the dialog at the top level of the Library with the next free "Symbol n". +pub fn open(app: &mut App) { + open_in(app, None); +} + +/// Opens the dialog targeting `folder`, prefilled with the next free "Symbol n" there. +pub fn open_in(app: &mut App, folder: Option) { + app.playing = false; + let folder = folder.filter(|f| app.s.doc.folder(*f).is_some()); + let name = app.s.doc.numbered_name(folder, "Symbol", app.s.doc.library.len() + 1); // i18n-exempt: a new symbol's default name is document text, as the engine gives it + app.new_symbol = Some(NewSymbolDialog { name, kind: SymbolKind::Graphic, folder, error: None, focus: true }); +} + +fn kind_key(k: SymbolKind) -> &'static str { + match k { + SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => "movie_clip", + SymbolKind::Button => "button", + } +} + +fn folder_label(doc: &Document, folder: Option) -> String { + match folder { + Some(f) => doc.entry_path(LibraryEntry::Folder(f)), + None => tr!("Library (top level)").to_string(), + } +} + +pub fn window(app: &mut App, ctx: &egui::Context) { + let Some(d) = &mut app.new_symbol else { return }; + let doc = &app.s.doc; + if d.folder.is_some_and(|f| doc.folder(f).is_none()) { + d.folder = None; + } + let mut folders: Vec<(FolderId, String)> = doc.library_tree.folders.iter().map(|f| (f.id, doc.entry_path(LibraryEntry::Folder(f.id)))).collect(); + folders.sort_by_key(|(_, p)| p.to_lowercase()); + let (mut submit, mut cancel) = (false, false); + let title = tr!("Create New Symbol"); + let shown = crate::windows::new(ctx, title).id(egui::Id::unique("new_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| { + ui.set_min_width(360.0); + form_row(ui, FORM_LABEL_DOCK, tr!("Name"), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Name")); + if d.focus { + crate::theme::focus_selected(ui, &r, &d.name); + d.focus = false; + } + if r.changed() { + d.error = None; + } + if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + submit = true; + } + }); + form_row(ui, FORM_LABEL_DOCK, tr!("Type"), |ui| { + egui::ComboBox::from_id_salt("new_symbol_kind") + .width(200.0) + .selected_text(crate::panels::symbol_kind_label(d.kind)) + .show_ui(ui, |ui| { + for k in KINDS { + if ui.selectable_label(d.kind == k, crate::panels::symbol_kind_label(k)).clicked() { + d.kind = k; + } + } + }) + .response + .set_name(tr!("Type")); + }); + form_row(ui, FORM_LABEL_DOCK, tr!("Folder"), |ui| { + egui::ComboBox::from_id_salt("new_symbol_folder") + .width(200.0) + .selected_text(folder_label(doc, d.folder)) + .show_ui(ui, |ui| { + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + if ui.selectable_label(d.folder.is_none(), tr!("Library (top level)")).clicked() { + d.folder = None; + d.error = None; + } + for (f, path) in &folders { + if ui.selectable_label(d.folder == Some(*f), path.as_str()).clicked() { + d.folder = Some(*f); + d.error = None; + } + } + }); + }) + .response + .on_hover_text(tr!("The Library folder the new symbol goes into")) + .set_name(tr!("Folder")); + }); + if let Some(err) = &d.error { + ui.label(text(Type::Caption, err).color(T.error)); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + if ui.button(tr!("OK")).clicked() { + submit = true; + } + if ui.button(tr!("Cancel")).clicked() { + cancel = true; + } + }); + }); + crate::a11y::name_title_bar(&shown, title); + if !egui::Popup::is_any_open(ctx) { + if !cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) { + cancel = true; + } else if !submit && !cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) { + submit = true; + } + } + if submit { + accept(app); + } else if cancel { + app.new_symbol = None; + } +} + +/// OK: runs `library.new_symbol` and closes the dialog on success; on refusal keeps it open with +/// the error shown. +fn accept(app: &mut App) { + let Some((name, kind, folder)) = app.new_symbol.as_ref().map(|d| (d.name.clone(), d.kind, d.folder)) else { return }; + let params = json!({"name": name, "kind": kind_key(kind), "folder": folder.map(|f| f.0), "edit": true}); + if let Some(v) = app.run("library.new_symbol", params) { + app.new_symbol = None; + if let Some(f) = folder { + app.library.expanded.extend(app.s.doc.folder_chain(f)); + } + if let Some(id) = v["id"].as_u64() { + let item = LibraryItem::Symbol(SymbolId(id)); + app.library_sel = Some(item); + app.library.sel = vec![LibraryEntry::Item(item)]; + } + let created = v["name"].as_str().unwrap_or(""); + app.status_ok(tr!("Created symbol “{name}” — {undo} to undo", name = created, undo = app.undo_key())); + } else if let Some(d) = app.new_symbol.as_mut() { + d.error = app.status.as_ref().map(|s| s.text.clone()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::sample; + + fn app(ctx: &egui::Context) -> App { + App::with_context(ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png"))) + } + + #[test] + fn menu_and_shortcut_open_the_dialog_and_ok_creates_the_symbol() { + let spec = anicraft_engine::find_command("library.new_symbol").expect("command registered"); + assert_eq!((spec.menu, spec.shortcut), ("Insert", Some("Ctrl+F8"))); + + let ctx = egui::Context::default(); + let mut app = app(&ctx); + let before = app.s.doc.library.len(); + // Ctrl+F8 opens the dialog. + let mut input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), + events: vec![egui::Event::Key { key: Key::F8, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }], + ..Default::default() + }; + let mut out = ctx.run_ui(input.clone(), |ui| app.frame(ui)); + out.textures_delta.clear(); + let d = app.new_symbol.as_ref().expect("Ctrl+F8 opens the dialog"); + assert!(app.modal_open()); + assert_eq!(d.kind, SymbolKind::Graphic); + assert!(d.name.starts_with("Symbol ")); + + // Escape closes it without changing the document. + input.events = vec![egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]; + let mut out = ctx.run_ui(input, |ui| window(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.new_symbol.is_none()); + assert_eq!(app.s.doc.library.len(), before); + + // Menu action opens it; an invalid name is refused and keeps the dialog open with an error. + app.invoke("library.new_symbol"); + if let Some(d) = app.new_symbol.as_mut() { + d.name = " ".into(); + } + accept(&mut app); + assert!(app.new_symbol.as_ref().is_some_and(|d| d.error.is_some())); + assert_eq!(app.s.doc.library.len(), before); + + // OK with a valid name and type creates the empty symbol and enters it. + if let Some(d) = app.new_symbol.as_mut() { + d.name = "Hero".into(); + d.kind = SymbolKind::Button; + } + accept(&mut app); + assert!(app.new_symbol.is_none()); + assert_eq!(app.s.doc.library.len(), before + 1); + let sym = app.s.doc.library.iter().find(|s| s.name == "Hero").expect("created"); + assert_eq!(sym.kind, SymbolKind::Button); + assert_eq!(app.s.editing_symbol(), Some(sym.id)); + } +}