diff --git a/src/a11y.rs b/src/a11y.rs index 15318b84..6b8f29b5 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"] { + 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"] { 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 5d04f74d..6c788c05 100644 --- a/src/app.rs +++ b/src/app.rs @@ -269,19 +269,7 @@ pub struct Shot { pub const SHOT_FRAMES: u32 = 120; /// The item picked in the Library panel (view state). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LibraryItem { - Symbol(anicraft_engine::doc::SymbolId), - Bitmap(anicraft_engine::doc::BitmapId), - Sound(anicraft_engine::doc::SoundId), -} - -impl LibraryItem { - /// The first item in the Library: its first symbol, else its first bitmap, else sound. - pub fn first(doc: &anicraft_engine::doc::Document) -> Option { - doc.library.first().map(|s| LibraryItem::Symbol(s.id)).or_else(|| doc.bitmaps.first().map(|b| LibraryItem::Bitmap(b.id))).or_else(|| doc.sounds.first().map(|s| LibraryItem::Sound(s.id))) - } -} +pub use anicraft_engine::doc::LibraryItem; pub struct App { pub s: Session, @@ -317,6 +305,8 @@ pub struct App { /// Folders shown closed on the timeline (view state: not saved, not undoable). pub tl_collapsed: HashSet, pub library_sel: Option, + /// The Library panel's folders, selection, sorting, search and preview (ADR 0050). + pub library: crate::library::LibraryView, /// Text being typed on the stage. pub text_edit: Option, /// Font families on this computer, listed once on first need. @@ -460,7 +450,7 @@ impl App { let prefs = if shot_mode { prefs::Prefs::default() } else { prefs::Prefs::load() }; let keymap = keymap::Keymap::new(&prefs.shortcuts); let shortcuts = keymap.table(); - let library_sel = LibraryItem::first(&session.doc); + let library_sel = crate::library::first_item(&session.doc); let (recovery, recovery_err) = autosave::Recovery::start(shot_mode); // Text lays out with the fonts on this computer plus the embedded interface font (so new // text has the same default everywhere). Scan them now, off the UI thread. @@ -500,6 +490,7 @@ impl App { tl_last_layer: None, tl_collapsed: HashSet::new(), library_sel, + library: Default::default(), text_edit: None, font_families: None, star_points: 5, @@ -784,6 +775,22 @@ impl App { self.scan_system_fonts(); } Some("confirm") => self.request("layer.delete", json!({})), + Some(which @ ("library" | "librarymenu")) => { + // Library folders with an item inside, a copy, the item previewed (ADR 0050). + let ball = self.s.doc.library.first().map(|s| s.id); + let folder = self.run("library.new_folder", json!({"name": "Characters"})).and_then(|v| v["folder"].as_u64()); + self.run("library.new_folder", json!({"name": "Props"})); + if let (Some(ball), Some(f)) = (ball, folder) { + self.run("library.duplicate", json!({"symbol": ball.0})); + self.run("library.move", json!({"items": [{"symbol": ball.0}], "to": f})); + self.library.expanded.insert(anicraft_engine::doc::FolderId(f)); + self.library_sel = Some(LibraryItem::Symbol(ball)); + self.library.sel = vec![anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(ball))]; + } + if which == "librarymenu" { + crate::library::select_unused(self); + } + } Some(which @ ("onion" | "onionmenu")) => { // Onion skin ±5 on a frame with frames before and after it, the markers on the // ruler; with its menu open, in outlines (ADR 0047). @@ -1341,7 +1348,7 @@ impl App { if let Some(session) = restored { self.view.fit = true; self.frame_sel = None; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); self.recovery.restored(&session); let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned()); @@ -1358,7 +1365,7 @@ impl App { match id { "file.new" | "file.new_sample" | "file.open" => { self.view.fit = true; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); match v.get("report").and_then(Value::as_str) { // An imported file: say what came across and what didn't, and that saving @@ -1370,7 +1377,7 @@ impl App { "file.recover" => { self.view.fit = true; self.frame_sel = None; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.recovery.restored(v["recovered"].as_str().unwrap_or("")); let name = v["name"].as_str().unwrap_or(tr!("Untitled")); self.status_ok(if v["original_newer"].as_bool() == Some(true) { @@ -1804,6 +1811,7 @@ impl App { crate::widthtool::consume_keys(self, ctx); crate::bone_tool::consume_keys(self, ctx); } + crate::library::consume_keys(self, ctx); let mut fire: Vec<&'static str> = Vec::new(); let mut tool = None; let mut play = false; diff --git a/src/library.rs b/src/library.rs new file mode 100644 index 00000000..02b61972 --- /dev/null +++ b/src/library.rs @@ -0,0 +1,890 @@ +//! The Library panel (ADR 0050): folders, sorting and search, inline rename, drag into and out +//! of folders, multiple selection, an item preview (a symbol's first frame, a bitmap, a +//! sound's waveform with play) and the item's properties. Every change is a `library.*` +//! command; what is sorted, filtered, expanded or selected is view state, kept here. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{T, TARGET, Type, color, font, text, with_type}; +use anicraft_engine::StateId; +use anicraft_engine::cmds_library::entry_json; +use anicraft_engine::doc::library::MAX_FOLDER_DEPTH; +use anicraft_engine::doc::{Document, FolderId, LibraryEntry, LibraryItem, SymbolKind}; +use egui::{Align2, Key, Modifiers, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use serde_json::json; +use std::collections::{HashMap, HashSet}; + +/// How the list is ordered (folders always come first, by name). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sort { + #[default] + Name, + Type, + Uses, + /// When the item came into the Library (ids grow with time). + Added, +} + +impl Sort { + const ALL: [Sort; 4] = [Sort::Name, Sort::Type, Sort::Uses, Sort::Added]; + fn label(self) -> &'static str { + match self { + Sort::Name => tr!("Name"), + Sort::Type => tr!("Type"), + Sort::Uses => tr!("Use count"), + Sort::Added => tr!("Date added"), + } + } +} + +/// What the Library panel shows and holds between frames. +#[derive(Default)] +pub struct LibraryView { + /// The selected rows (items and folders). + pub sel: Vec, + /// Where a Shift-click range starts. + anchor: Option, + pub expanded: HashSet, + pub sort: Sort, + pub descending: bool, + pub filter: String, + /// The row being renamed and the text so far; `true` until the field has taken focus. + pub renaming: Option<(LibraryEntry, String, bool)>, + /// The list was clicked last: F2 and Delete act on it (not on the stage). + pub keys: bool, + /// Where the list was drawn last frame (`None` before the first). + list_rect: Option, + uses: Option<(StateId, HashMap, HashSet)>, + preview: Option, +} + +/// The current item's preview picture, and what it was made from. +struct Preview { + key: (LibraryItem, StateId), + texture: Option, +} + +/// The first item in the Library: its first symbol, else its first bitmap, else sound. +pub fn first_item(doc: &Document) -> Option { + doc.library_items().next() +} + +/// One visible row. +struct Row { + entry: LibraryEntry, + depth: usize, + name: String, + /// What it is, for the tooltip and screen readers (“Movie clip · 24 frames”). + detail: String, + uses: Option, + open: bool, +} + +impl LibraryView { + /// Use counts and unused items, worked out once per document state. + fn counts(&mut self, s: &anicraft_engine::Session) -> (HashMap, HashSet) { + match &self.uses { + Some((st, u, n)) if *st == s.state => (u.clone(), n.clone()), + _ => { + let (u, n): (HashMap, HashSet) = (s.doc.library_uses(), s.doc.unused_items().into_iter().collect()); + self.uses = Some((s.state, u.clone(), n.clone())); + (u, n) + } + } + } + + /// Only one row selected: `e`. + fn select_only(&mut self, e: LibraryEntry) { + self.sel = vec![e]; + self.anchor = Some(e); + } +} + +fn kind_rank(doc: &Document, e: LibraryEntry) -> u8 { + match e { + LibraryEntry::Folder(_) => 0, + LibraryEntry::Item(LibraryItem::Symbol(id)) => match doc.symbol(id).map(|s| s.kind) { + Some(SymbolKind::Graphic) => 1, + Some(SymbolKind::MovieClip) => 2, + _ => 3, + }, + LibraryEntry::Item(LibraryItem::Bitmap(_)) => 4, + LibraryEntry::Item(LibraryItem::Sound(_)) => 5, + } +} + +fn raw_id(e: LibraryEntry) -> u64 { + match e { + LibraryEntry::Item(i) => i.raw(), + LibraryEntry::Folder(f) => f.0, + } +} + +fn detail(doc: &Document, e: LibraryEntry) -> String { + match e { + LibraryEntry::Folder(f) => { + let n = doc.library_children(Some(f)).len(); + trn!("Folder · {n} item", "Folder · {n} items", n) + } + LibraryEntry::Item(LibraryItem::Symbol(id)) => doc.symbol(id).map_or_else(String::new, |s| { + let n = s.timeline.frame_count(); + let frames = trn!("{n} frame", "{n} frames", n); + tr!("{kind} · {frames}", kind = crate::panels::symbol_kind_label(s.kind), frames = frames) + }), + LibraryEntry::Item(LibraryItem::Bitmap(id)) => doc.bitmap(id).map_or_else(String::new, |b| tr!("Bitmap · {width}×{height}", width = b.width, height = b.height)), + LibraryEntry::Item(LibraryItem::Sound(id)) => doc.sound(id).map_or_else(String::new, |x| tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds()))), + } +} + +/// The visible rows: folders (open ones with what they hold), then items, ordered by `sort`. +/// With a search, only matching items show, inside every folder that leads to one. +fn rows(doc: &Document, v: &LibraryView, uses: &HashMap) -> Vec { + let query = v.filter.trim().to_lowercase(); + let matches = |e: LibraryEntry| query.is_empty() || doc.entry_name(e).is_some_and(|n| n.to_lowercase().contains(&query)); + // Folders that lead to a match (searching opens them all). + let mut leads: HashSet = HashSet::new(); + if !query.is_empty() { + for e in doc.library_items().map(LibraryEntry::Item).chain(doc.library_tree.folders.iter().map(|f| LibraryEntry::Folder(f.id))) { + if matches(e) + && let Some(p) = doc.parent_of(e) + { + leads.extend(doc.folder_chain(p)); + } + } + } + let count = |e: LibraryEntry| match e { + LibraryEntry::Item(i) => uses.get(&i).copied().unwrap_or(0), + LibraryEntry::Folder(_) => 0, + }; + let mut out = Vec::new(); + // Depth-first, in order: each level is sorted, then pushed in reverse. + let mut pending: Vec<(LibraryEntry, usize)> = level(doc, v, None, &count).into_iter().rev().map(|e| (e, 0)).collect(); + while let Some((e, depth)) = pending.pop() { + if out.len() > 100_000 { + break; + } + let shown = match e { + LibraryEntry::Folder(f) => query.is_empty() || leads.contains(&f) || matches(e), + LibraryEntry::Item(_) => matches(e), + }; + if !shown { + continue; + } + let open = match e { + LibraryEntry::Folder(f) => (!query.is_empty() && leads.contains(&f)) || (query.is_empty() && v.expanded.contains(&f)), + LibraryEntry::Item(_) => false, + }; + out.push(Row { entry: e, depth, name: doc.entry_name(e).unwrap_or("").to_string(), detail: detail(doc, e), uses: matches!(e, LibraryEntry::Item(_)).then(|| count(e)), open }); + if let LibraryEntry::Folder(f) = e + && open + && depth + 1 < MAX_FOLDER_DEPTH + { + pending.extend(level(doc, v, Some(f), &count).into_iter().rev().map(|c| (c, depth + 1))); + } + } + out +} + +/// What folder `parent` holds, folders first (by name), then items in the chosen order. +fn level(doc: &Document, v: &LibraryView, parent: Option, count: &dyn Fn(LibraryEntry) -> usize) -> Vec { + let mut all = doc.library_children(parent); + let name = |e: &LibraryEntry| doc.entry_name(*e).unwrap_or("").to_lowercase(); + all.sort_by(|a, b| { + let folders = matches!(b, LibraryEntry::Folder(_)).cmp(&matches!(a, LibraryEntry::Folder(_))); + let by = match v.sort { + Sort::Name => std::cmp::Ordering::Equal, + Sort::Type => kind_rank(doc, *a).cmp(&kind_rank(doc, *b)), + Sort::Uses => count(*a).cmp(&count(*b)), + Sort::Added => raw_id(*a).cmp(&raw_id(*b)), + }; + let by = by.then_with(|| name(a).cmp(&name(b))); + folders.then(if v.descending && !matches!(a, LibraryEntry::Folder(_)) { by.reverse() } else { by }) + }); + all +} + +/// F2 renames the selected row and Delete deletes the selection, while the list has the +/// keyboard (it was clicked last). Called before the global shortcuts. +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + let clicked_elsewhere = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !app.library.list_rect.is_some_and(|r| r.contains(p)))); + if clicked_elsewhere { + app.library.keys = false; + } + if !app.library.keys || app.library.renaming.is_some() { + return; + } + let (rename, delete) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::F2), i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace))); + if rename && let [one] = app.library.sel.as_slice() { + let e = *one; + start_rename(app, e); + } + if delete { + delete_selection(app); + } +} + +fn start_rename(app: &mut App, e: LibraryEntry) { + let name = app.s.doc.entry_name(e).unwrap_or("").to_string(); + app.library.renaming = Some((e, name, true)); +} + +fn delete_selection(app: &mut App) { + let items: Vec = app.library.sel.iter().filter(|e| app.s.doc.has_entry(**e)).map(|e| entry_json(*e)).collect(); + if !items.is_empty() { + app.request("library.delete", json!({"items": items})); + } +} + +/// Places an item: a symbol or bitmap at the stage centre, a sound on the active layer's +/// keyframe at the playhead (its span grown to fit). +fn place(app: &mut App, item: LibraryItem) { + match item { + LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), + LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), + LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), + }; +} + +/// 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() { + [LibraryEntry::Folder(f)] => Some(*f), + [one] => app.s.doc.parent_of(*one), + _ => None, + }; + if let Some(p) = parent { + app.library.expanded.insert(p); + } + if let Some(v) = app.run("library.new_folder", json!({"parent": parent.map(|f| f.0)})) + && let Some(id) = v["folder"].as_u64() + { + let e = LibraryEntry::Folder(FolderId(id)); + app.library.select_only(e); + start_rename(app, e); + } +} + +/// Moves `what` into `to` (`None`: the top level), opening the folder so they stay in view. +fn move_into(app: &mut App, what: &[LibraryEntry], to: Option) { + let items: Vec = what.iter().filter(|e| app.s.doc.parent_of(**e) != to && **e != to.map_or(**e, LibraryEntry::Folder)).map(|e| entry_json(*e)).collect(); + if items.is_empty() { + return; + } + if app.run("library.move", json!({"items": items, "to": to.map(|f| f.0)})).is_some() + && let Some(f) = to + { + app.library.expanded.insert(f); + } +} + +pub fn panel(app: &mut App, ui: &mut egui::Ui) { + // Rows that are gone (an undo, a deletion) leave the selection. + let doc = &app.s.doc; + app.library.sel.retain(|e| doc.has_entry(*e)); + if app.library.renaming.as_ref().is_some_and(|(e, _, _)| !doc.has_entry(*e)) { + app.library.renaming = None; + } + 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); + } + return; + } + toolbar(app, ui); + ui.add_space(4.0); + let (uses, unused) = app.library.counts(&app.s); + let list = rows(&app.s.doc, &app.library, &uses); + let total = app.s.doc.library_items().count(); + let summary = if app.library.filter.trim().is_empty() { + trn!("{n} item", "{n} items", total) + } else { + tr!("{shown} of {total}", shown = list.iter().filter(|r| matches!(r.entry, LibraryEntry::Item(_))).count(), total = total) + }; + ui.horizontal(|ui| { + ui.label(text(Type::Caption, summary)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(text(Type::Caption, tr!("Uses")))); + }); + list_ui(app, ui, &list, &unused); + ui.add_space(4.0); + actions_row(app, ui); + ui.add_space(6.0); + preview(app, ui); + properties(app, ui); +} + +/// Search, sort, and the panel's menu. +fn toolbar(app: &mut App, ui: &mut egui::Ui) { + let search = ui.add(egui::TextEdit::singleline(&mut app.library.filter).hint_text(tr!("Search")).desired_width(ui.available_width())); + search.set_name(tr!("Search the Library")); + ui.horizontal(|ui| { + ui.label(text(Type::Label, tr!("Sort"))); + egui::ComboBox::from_id_salt("lib_sort") + .width(110.0) + .selected_text(app.library.sort.label()) + .show_ui(ui, |ui| { + for s in Sort::ALL { + if ui.selectable_label(app.library.sort == s, s.label()).clicked() { + app.library.sort = s; + } + } + }) + .response + .set_name(tr!("Sort by")); + let (icon, tip) = if app.library.descending { (Icon::ChevronDown, tr!("Descending: click for ascending")) } else { (Icon::ChevronUp, tr!("Ascending: click for descending")) }; + if crate::timeline::icon_button(ui, tip, None, icon).clicked() { + app.library.descending = !app.library.descending; + } + let menu = ui.menu_button(tr!("More"), |ui| { + let n_unused = app.library.counts(&app.s).1.len(); + if ui.add_enabled(n_unused > 0, egui::Button::new(tr!("Select Unused Items"))).clicked() { + ui.close(); + select_unused(app); + } + if ui.add_enabled(n_unused > 0, egui::Button::new(tr!("Delete Unused Items…"))).clicked() { + ui.close(); + app.request("library.delete_unused", json!({})); + } + ui.separator(); + if ui.button(tr!("Expand All Folders")).clicked() { + ui.close(); + app.library.expanded = app.s.doc.library_tree.folders.iter().map(|f| f.id).collect(); + } + if ui.button(tr!("Collapse All Folders")).clicked() { + ui.close(); + app.library.expanded.clear(); + } + }); + menu.response.on_hover_text(tr!("Library options")).set_name(tr!("Library options")); + }); +} + +/// Selects every unused item, opening the folders they are in. +pub fn select_unused(app: &mut App) { + let unused = app.s.doc.unused_items(); + for i in &unused { + if let Some(p) = app.s.doc.parent_of(LibraryEntry::Item(*i)) { + app.library.expanded.extend(app.s.doc.folder_chain(p)); + } + } + app.library.sel = unused.iter().map(|i| LibraryEntry::Item(*i)).collect(); + app.library.keys = true; + app.status_ok(trn!("{n} unused item selected", "{n} unused items selected", unused.len())); +} + +fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet) { + let mut toggle: Option = None; + let mut clicked: Option<(LibraryEntry, Modifiers)> = None; + let mut activate: Option = None; + let mut rename: Option = None; + let mut dropped: Option<(Vec, Option)> = None; + let scroll = egui::ScrollArea::vertical().id_salt("lib").max_height(200.0).auto_shrink([false, true]).show(ui, |ui| { + for row in list { + let selected = app.library.sel.contains(&row.entry); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click_and_drag()); + let p = ui.painter(); + if selected || resp.hovered() { + p.rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); + } + if selected { + p.rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); + } + let indent = 6.0 + row.depth as f32 * 14.0; + let chevron = Rect::from_center_size(pos2(r.left() + indent + 6.0, r.center().y), vec2(12.0, 12.0)); + let icon = Rect::from_center_size(pos2(r.left() + indent + 22.0, r.center().y), vec2(14.0, 14.0)); + match row.entry { + LibraryEntry::Folder(_) => { + icons::paint(p, chevron, if row.open { Icon::ChevronDown } else { Icon::ChevronRight }, T.icon); + icons::paint(p, icon.expand(1.0), if row.open { Icon::FolderOpen } else { Icon::Folder }, color(Type::Body)); + } + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + let kind_color = match app.s.doc.symbol(id).map(|s| s.kind) { + Some(SymbolKind::Graphic) | None => T.kind_graphic, + Some(SymbolKind::MovieClip) => T.kind_movie_clip, + Some(SymbolKind::Button) => T.kind_button, + }; + p.rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); + p.circle_filled(icon.center(), 2.5, kind_color); + } + LibraryEntry::Item(LibraryItem::Sound(_)) => icons::paint(p, icon.expand(1.0), Icon::Sound, color(Type::Body)), + LibraryEntry::Item(LibraryItem::Bitmap(_)) => icons::paint(p, icon.expand(1.0), Icon::Image, color(Type::Body)), + } + let name_rect = Rect::from_min_max(pos2(icon.right() + 8.0, r.top()), pos2(r.right() - 40.0, r.bottom())); + let uses_text = row.uses.map(|n| n.to_string()).unwrap_or_default(); + let is_unused = matches!(row.entry, LibraryEntry::Item(i) if unused.contains(&i)); + if let Some(n) = row.uses { + p.text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &uses_text, font(Type::Data), if n == 0 { T.text_faint } else { color(Type::Caption) }); + } + // Renaming: a field over the name; Enter or clicking away keeps it, Esc doesn't. + let editing = app.library.renaming.as_ref().is_some_and(|(e, _, _)| *e == row.entry); + if editing { + let mut commit = None; + if let Some((e, buf, focus)) = &mut app.library.renaming { + let edit = ui.put(name_rect.shrink2(vec2(0.0, 3.0)), egui::TextEdit::singleline(buf).font(font(Type::Body))); + edit.set_name(tr!("Library name")); + if *focus { + edit.request_focus(); + *focus = false; + } + let esc = ui.input(|i| i.key_pressed(Key::Escape)); + if edit.lost_focus() { + commit = Some((*e, buf.clone(), !esc)); + } + } + if let Some((e, name, keep)) = commit { + app.library.renaming = None; + if keep && app.s.doc.entry_name(e) != Some(name.as_str()) { + let mut params = entry_json(e); + params["name"] = json!(name); + app.run("library.rename", params); + } + } + } else { + let c = if is_unused { T.text_dim } else { color(Type::Body) }; + let galley = ui.painter().layout_no_wrap(row.name.clone(), font(Type::Body), c); + let clip = ui.painter().with_clip_rect(name_rect.intersect(ui.clip_rect())); + clip.galley(pos2(name_rect.left(), r.center().y - galley.size().y / 2.0), galley, c); + } + let used_note = match row.uses { + Some(0) => tr!("not used").to_string(), + Some(n) => trn!("used {n} time", "used {n} times", n), + None => String::new(), + }; + let name = if used_note.is_empty() { format!("{} · {}", row.name, row.detail) } else { format!("{} · {} · {}", row.name, row.detail, used_note) }; + a11y::control(ui, &resp, WidgetType::SelectableLabel, &name, Some(selected)); + let resp = resp.on_hover_text(&name); + // Dragging rows: the selection if the row is in it, else just the row. + if resp.drag_started() { + let what = if selected { app.library.sel.clone() } else { vec![row.entry] }; + resp.dnd_set_drag_payload(what); + } + let target = match row.entry { + LibraryEntry::Folder(f) => Some(f), + e => app.s.doc.parent_of(e), + }; + if let Some(payload) = resp.dnd_hover_payload::>() + && !payload.contains(&row.entry) + { + let hl = if let LibraryEntry::Folder(_) = row.entry { r } else { Rect::from_min_size(pos2(r.left(), r.top()), vec2(r.width(), 2.0)) }; + ui.painter().rect_stroke(hl, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + } + if let Some(payload) = resp.dnd_release_payload::>() { + dropped = Some(((*payload).clone(), target)); + } + if let LibraryEntry::Folder(f) = row.entry + && resp.clicked() + && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x < icon.right() + 2.0) + { + toggle = Some(f); + } else if resp.clicked() { + clicked = Some((row.entry, ui.input(|i| i.modifiers))); + } + if resp.double_clicked() { + let on_name = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x >= name_rect.left()); + if on_name { + rename = Some(row.entry); + } else { + activate = Some(row.entry); + } + } + resp.context_menu(|ui| row_menu(app, ui, row.entry)); + } + // Below the rows: dropping there moves to the top level. + let rest = ui.available_rect_before_wrap(); + let (r, resp) = ui.allocate_exact_size(vec2(rest.width(), (rest.height()).max(TARGET)), Sense::click() - Sense::FOCUSABLE); + a11y::surface(ui, &resp, tr!("Library: drop here for the top level")); + if resp.dnd_hover_payload::>().is_some() { + ui.painter().rect_stroke(r, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + } + if let Some(payload) = resp.dnd_release_payload::>() { + dropped = Some(((*payload).clone(), None)); + } + if resp.clicked() { + app.library.sel.clear(); + app.library.keys = true; + } + resp.context_menu(|ui| { + if ui.button(tr!("New Folder")).clicked() { + ui.close(); + app.library.sel.clear(); + new_folder(app); + } + }); + }); + app.library.list_rect = Some(scroll.inner_rect); + if let Some(f) = toggle { + if !app.library.expanded.remove(&f) { + app.library.expanded.insert(f); + } + app.library.select_only(LibraryEntry::Folder(f)); + app.library.keys = true; + } + if let Some((e, m)) = clicked { + app.library.keys = true; + if m.command { + if let Some(i) = app.library.sel.iter().position(|x| *x == e) { + app.library.sel.remove(i); + } else { + app.library.sel.push(e); + } + app.library.anchor = Some(e); + } else if m.shift + && let Some(a) = app.library.anchor + && let (Some(i), Some(j)) = (list.iter().position(|r| r.entry == a), list.iter().position(|r| r.entry == e)) + { + let (lo, hi) = (i.min(j), i.max(j)); + app.library.sel = list.get(lo..=hi).map(|rs| rs.iter().map(|r| r.entry).collect()).unwrap_or_default(); + } else { + app.library.select_only(e); + } + if let LibraryEntry::Item(i) = e { + app.library_sel = Some(i); + } + } + if let Some(e) = rename { + app.library.select_only(e); + start_rename(app, e); + } else if let Some(e) = activate { + match e { + // A symbol opens for editing, as in Animate (ADR 0045); images and sounds are placed. + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + app.run("symbol.edit", json!({"symbol": id.0})); + } + LibraryEntry::Item(i) => place(app, i), + LibraryEntry::Folder(f) => { + if !app.library.expanded.remove(&f) { + app.library.expanded.insert(f); + } + } + } + } + if let Some((what, to)) = dropped { + move_into(app, &what, to); + } +} + +/// A row's right-click menu. +fn row_menu(app: &mut App, ui: &mut egui::Ui, e: LibraryEntry) { + if !app.library.sel.contains(&e) { + app.library.select_only(e); + if let LibraryEntry::Item(i) = e { + app.library_sel = Some(i); + } + } + let many = app.library.sel.len() > 1; + if let LibraryEntry::Item(LibraryItem::Symbol(id)) = e + && !many + { + if ui.button(tr!("Edit Symbol")).clicked() { + ui.close(); + app.run("symbol.edit", json!({"symbol": id.0})); + } + if ui.button(tr!("Duplicate Symbol")).clicked() { + ui.close(); + if let Some(v) = app.run("library.duplicate", json!({"symbol": id.0})) + && let Some(n) = v["symbol"].as_u64() + { + let copy = LibraryEntry::Item(LibraryItem::Symbol(anicraft_engine::doc::SymbolId(n))); + app.library.select_only(copy); + start_rename(app, copy); + } + } + } + if let LibraryEntry::Item(i) = e + && !many + { + let label = if matches!(i, LibraryItem::Sound(_)) { tr!("Place on Timeline") } else { tr!("Place on Stage") }; + if ui.button(label).clicked() { + ui.close(); + place(app, i); + } + } + if !many && ui.button(tr!("Rename")).clicked() { + ui.close(); + start_rename(app, e); + } + if ui.button(tr!("New Folder")).clicked() { + ui.close(); + new_folder(app); + } + let folders: Vec<(FolderId, String)> = app.s.doc.library_tree.folders.iter().map(|f| (f.id, app.s.doc.entry_path(LibraryEntry::Folder(f.id)))).collect(); + ui.menu_button(tr!("Move to"), |ui| { + let what = app.library.sel.clone(); + if ui.button(tr!("Library (top level)")).clicked() { + ui.close(); + move_into(app, &what, None); + } + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (f, path) in &folders { + let inside_moved = what.iter().any(|w| matches!(w, LibraryEntry::Folder(m) if app.s.doc.folder_within(*f, *m))); + if ui.add_enabled(!inside_moved, egui::Button::new(path.as_str())).clicked() { + ui.close(); + move_into(app, &what, Some(*f)); + } + } + }); + }); + ui.separator(); + if ui.button(tr!("Delete")).clicked() { + ui.close(); + delete_selection(app); + } +} + +/// New Folder and Delete, and placing the current item. +fn actions_row(app: &mut App, ui: &mut egui::Ui) { + ui.horizontal(|ui| { + if crate::timeline::icon_button(ui, tr!("New Folder"), None, Icon::FolderPlus).clicked() { + new_folder(app); + } + let can_delete = !app.library.sel.is_empty(); + let del = ui.add_enabled(can_delete, egui::Button::new(tr!("Delete"))).on_hover_text(tr!("Deletes the selected items and folders (Delete)")); + if del.clicked() { + delete_selection(app); + } + let current = app.library_sel.filter(|i| app.s.doc.has_item(*i)); + match current { + Some(LibraryItem::Sound(id)) => { + if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click its icon)")).clicked() { + place(app, LibraryItem::Sound(id)); + } + } + other => { + if ui.add_enabled(other.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre")).clicked() + && let Some(item) = other + { + place(app, item); + } + } + } + }); +} + +/// The current item's settings: a symbol's type and linkage class, a bitmap's smoothing. +fn properties(app: &mut App, ui: &mut egui::Ui) { + let Some(item) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) else { return }; + ui.add_space(6.0); + match item { + LibraryItem::Symbol(id) => { + let Some((kind, linkage)) = app.s.doc.symbol(id).map(|s| (s.kind, s.linkage.clone())) else { return }; + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, tr!("Type"), |ui| { + egui::ComboBox::from_id_salt("lib_symkind") + .width(150.0) + .selected_text(crate::panels::symbol_kind_label(kind)) + .show_ui(ui, |ui| { + for (k, key) in [(SymbolKind::Graphic, "graphic"), (SymbolKind::MovieClip, "movie_clip"), (SymbolKind::Button, "button")] { + if ui.selectable_label(kind == k, crate::panels::symbol_kind_label(k)).clicked() && kind != k { + app.run("symbol.set_kind", json!({"symbol": id.0, "kind": key})); + } + } + }) + .response + .set_name(tr!("Symbol type")); + }); + // The class scripts create it by (ADR 0013 tier 1: kept, not run). + let (class, base) = linkage.map_or((String::new(), String::new()), |l| (l.class, l.base)); + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, tr!("Class"), |ui| { + if let Some(v) = crate::actions_panel::class_field(ui, "lib_symclass", &class, tr!("Linkage class"), tr!("The class scripts create this symbol by (its linkage). Kept with the document; scripts don't run yet")) { + let base = if v.is_empty() { String::new() } else { base.clone() }; + app.run("script.set_class", json!({"symbol": id.0, "class": v, "base": base})); + } + }); + } + LibraryItem::Bitmap(id) => { + let Some(mut on) = app.s.doc.bitmap(id).map(|b| b.smoothing) else { return }; + if crate::theme::checkbox(ui, &mut on, tr!("Allow smoothing")).on_hover_text(tr!("Smooth when scaled or turned; off keeps hard pixel edges, for pixel art")).changed() { + app.run("library.set_smoothing", json!({"bitmap": id.0, "on": on})); + } + } + LibraryItem::Sound(id) => { + if let Some(x) = app.s.doc.sound(id) { + let info = format!("{} · {} Hz · {}", x.format.label(), x.rate, if x.channels > 1 { tr!("Stereo") } else { tr!("Mono") }); + with_type(ui, Type::Data, |ui| ui.label(text(Type::Caption, info))); + } + } + } +} + +// ----- preview -------------------------------------------------------------------------------- + +const PREVIEW_H: f32 = 72.0; + +/// The current item's picture: a symbol's first frame, a bitmap, or a sound's waveform with a +/// play button. +fn preview(app: &mut App, ui: &mut egui::Ui) { + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), PREVIEW_H), Sense::hover()); + ui.painter().rect_filled(r, T.rc(), T.field); + let Some(item) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) else { + ui.painter().text(r.center(), Align2::CENTER_CENTER, tr!("Select an item to preview it"), font(Type::Caption), color(Type::Caption)); + return; + }; + let inner = r.shrink(6.0); + match item { + LibraryItem::Sound(id) => { + waveform(app, ui, inner, id); + let play = Rect::from_min_size(pos2(r.right() - TARGET - 4.0, r.top() + 4.0), vec2(TARGET, TARGET)); + let resp = ui.put(play, egui::Button::new("▶").min_size(vec2(TARGET, TARGET))); + a11y::control(ui, &resp, WidgetType::Button, tr!("Play the sound"), None); + if resp.on_hover_text(tr!("Plays the sound on its own")).clicked() + && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) + { + app.playing = false; + app.sound.preview(dec.pcm.clone()); + if let Some(e) = app.sound.error.take() { + app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); + } + } + } + _ => { + let key = (item, app.s.state); + if app.library.preview.as_ref().is_none_or(|p| p.key != key) { + let texture = picture(ui.ctx(), &app.s.doc, item, inner); + app.library.preview = Some(Preview { key, texture }); + } + if let Some(tex) = app.library.preview.as_ref().and_then(|p| p.texture.as_ref()) { + let size = tex.size_vec2() / ui.ctx().pixels_per_point(); + let fit = (inner.width() / size.x.max(1.0)).min(inner.height() / size.y.max(1.0)).min(1.0); + let at = Rect::from_center_size(inner.center(), size * fit); + ui.painter().image(tex.id(), at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + } + } +} + +/// A texture of `item` fitting `area` (in points): a symbol's first frame rendered by the +/// oracle, or the bitmap, drawn with or without smoothing as it will be on the stage. +fn picture(ctx: &egui::Context, doc: &Document, item: LibraryItem, area: Rect) -> Option { + let ppp = ctx.pixels_per_point().clamp(0.5, 4.0); + let (w, h) = ((area.width() * ppp).round().max(1.0) as u32, (area.height() * ppp).round().max(1.0) as u32); + match item { + LibraryItem::Symbol(id) => { + let dl = symbol_frame(doc, id); + let b = dl.items.iter().filter(|i| !i.guide && i.masks.is_none()).fold(anicraft_engine::geom::Rect::EMPTY, |acc, i| { + let reach = i.stroke.as_ref().map_or(0.0, |s| s.reach()); + acc.union(&i.path.bounds().inflate(reach).transformed(&i.transform)) + }); + if b.is_empty() || !(b.width().is_finite() && b.height().is_finite()) { + return None; + } + let s = ((w as f32 - 4.0) / b.width().max(1e-3)).min((h as f32 - 4.0) / b.height().max(1e-3)).min(4.0 * ppp); + let c = b.center(); + let transform = anicraft_engine::geom::Affine::translate(w as f32 / 2.0, h as f32 / 2.0).mul(&anicraft_engine::geom::Affine::scale(s, s)).mul(&anicraft_engine::geom::Affine::translate(-c.x, -c.y)); + let view = anicraft_engine::render::View { transform, width: w, height: h, background: None }; + let (px, _) = anicraft_engine::render::render(&dl, &view).ok()?; + let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &px.to_premul_rgba8()); + Some(ctx.load_texture("library-preview", image, egui::TextureOptions::LINEAR)) + } + LibraryItem::Bitmap(id) => { + let b = doc.bitmap(id)?; + let px = b.pixels()?; + // At most the area's size in pixels (nearest pixel), so a huge image costs little. + let k = (w as f32 / px.width.max(1) as f32).min(h as f32 / px.height.max(1) as f32).min(1.0); + let (tw, th) = (((px.width as f32 * k).round() as u32).max(1), ((px.height as f32 * k).round() as u32).max(1)); + let mut rgba = Vec::with_capacity((tw * th * 4) as usize); + for y in 0..th { + for x in 0..tw { + let c = px.at((x as f32 / k) as i64, (y as f32 / k) as i64); + rgba.extend(c.iter().map(|v| (v * 255.0 + 0.5) as u8)); + } + } + let image = egui::ColorImage::from_rgba_unmultiplied([tw as usize, th as usize], &rgba); + let options = if b.smoothing { egui::TextureOptions::LINEAR } else { egui::TextureOptions::NEAREST }; + Some(ctx.load_texture("library-preview", image, options)) + } + LibraryItem::Sound(_) => None, + } +} + +/// Symbol `id`'s first frame on its own, its registration point at the origin. +fn symbol_frame(doc: &Document, id: anicraft_engine::doc::SymbolId) -> anicraft_engine::doc::DisplayList { + use anicraft_engine::doc::{Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Scene}; + use std::sync::Arc; + let mut d = doc.clone(); + let mut layer = Layer::new(LayerId(u64::MAX - 1), ""); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = vec![Arc::new(Element { + id: ElementId(u64::MAX - 2), + name: String::new(), + transform: Default::default(), + color: Default::default(), + kind: ElementKind::Symbol { symbol: id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + })]; + } + let mut scene = Scene::new(""); + scene.timeline.layers.push(Arc::new(layer)); + d.scenes = vec![Arc::new(scene)]; + anicraft_engine::doc::evaluate_scene(&d, 0, 0) +} + +/// A sound's waveform across `r`: one line per point column, lowest to highest sample. +fn waveform(app: &App, ui: &egui::Ui, r: Rect, id: anicraft_engine::doc::SoundId) { + let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded_if_ready()) else { + ui.painter().text(r.center(), Align2::CENTER_CENTER, tr!("Reading the sound…"), font(Type::Caption), color(Type::Caption)); + return; + }; + let len = dec.peaks.frames(); + let cols = r.width().floor().max(1.0) as usize; + if len == 0 { + return; + } + let (cy, half) = (r.center().y, r.height() / 2.0); + let stroke = Stroke::new(1.0, T.waveform); + for c in 0..cols { + let a = c * len / cols; + let b = ((c + 1) * len / cols).max(a + 1).min(len); + if let Some((lo, hi)) = dec.peaks.range(a, b) { + let x = r.left() + c as f32 + 0.5; + ui.painter().line_segment([pos2(x, cy - hi.clamp(-1.0, 1.0) * half), pos2(x, cy - lo.clamp(-1.0, 1.0) * half)], stroke); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session() -> (anicraft_engine::Session, u64, u64) { + let mut s = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let ball = s.doc.library.iter().find(|x| x.name == "Ball").map(|x| x.id.0).unwrap(); + let f = s.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap(); + s.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + s.execute("library.move", &json!({"items": [{"symbol": ball}], "to": f})).unwrap(); + (s, ball, f) + } + + fn names(s: &anicraft_engine::Session, v: &mut LibraryView) -> Vec<(usize, String)> { + let (uses, _) = v.counts(s); + rows(&s.doc, v, &uses).into_iter().map(|r| (r.depth, r.name)).collect() + } + + #[test] + fn folders_come_first_and_open_ones_show_what_they_hold() { + let (s, _, f) = session(); + let mut v = LibraryView::default(); + let n = |d: usize, x: &str| (d, x.to_string()); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(0, "Ball copy"), n(0, "Star")]); + v.expanded.insert(FolderId(f)); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Ball copy"), n(0, "Star")]); + // By use count, most used first when descending; folders stay on top. + v.sort = Sort::Uses; + v.descending = true; + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Star"), n(0, "Ball copy")]); + // Date added: the copy is newest. + v.sort = Sort::Added; + v.descending = false; + assert_eq!(names(&s, &mut v)[2..], [n(0, "Star"), n(0, "Ball copy")]); + } + + #[test] + fn a_search_shows_matches_inside_closed_folders() { + let (s, _, _) = session(); + let mut v = LibraryView { filter: "BALL".into(), ..Default::default() }; + let n = |d: usize, x: &str| (d, x.to_string()); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Ball copy")]); + v.filter = "nothing like it".into(); + assert!(names(&s, &mut v).is_empty()); + } +} diff --git a/src/main.rs b/src/main.rs index 37e70968..38f7fe49 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,6 +34,7 @@ mod dialogs; mod gpu_stage; mod icons; mod keymap; +mod library; mod menus; mod motion_editor; mod panels; @@ -176,7 +177,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|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]\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|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|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]\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/panels.rs b/src/panels.rs index 4f65e630..a22c3809 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1,11 +1,11 @@ //! Tools bar, edit bar, status bar, Properties and Library panels. -use crate::app::{App, LibraryItem, Tool}; +use crate::app::{App, Tool}; use crate::icons::{self, Icon}; -use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, font, section, text, to_color32, with_type}; -use anicraft_engine::doc::{ElementKind, Paint, Rgba, SymbolKind, evaluate_layer_elements}; +use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type}; +use anicraft_engine::doc::{ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements}; use crate::a11y::{self, Named}; -use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; // ----- tools -------------------------------------------------------------------------------- @@ -302,7 +302,12 @@ pub fn right(app: &mut App, ui: &mut egui::Ui) { // next one (Align goes with Properties, History with the Library). let split = ui.cursor().top(); let (library_header, _) = crate::theme::section_with_header(ui, "dock_library", Section::Band, tr!("Library"), None, |ui| { - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); + // The Library scrolls on its own, so a short window still reaches every row (History's + // header stays below it). + let room = (ui.available_height() - 48.0).max(120.0); + egui::ScrollArea::vertical().id_salt("library_dock").max_height(room).auto_shrink([false, true]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); + }); }); section(ui, "dock_history", Section::Band, tr!("History"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| history(app, ui)); @@ -439,7 +444,7 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { } /// A symbol type's name, as the Properties panel shows it. -fn symbol_kind_label(kind: SymbolKind) -> &'static str { +pub(crate) fn symbol_kind_label(kind: SymbolKind) -> &'static str { match kind { SymbolKind::Graphic => tr!("Graphic"), SymbolKind::MovieClip => tr!("Movie clip"), @@ -579,6 +584,30 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E .response .set_name(tr!("Symbol type")); }); + // Swap Symbol (ADR 0050): another symbol in this instance's place, keeping its + // transform, colour effect, filters and name. + let current = *symbol; + let mut choices: Vec<(anicraft_engine::doc::SymbolId, String)> = app.s.doc.library.iter().map(|x| (x.id, app.s.doc.entry_path(anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(x.id))))).collect(); + choices.sort_by_key(|(_, p)| p.to_lowercase()); + let name = app.s.doc.symbol(current).map(|x| x.name.clone()).unwrap_or_default(); + row_prose(ui, tr!("Symbol"), |ui| { + ui.label(text(Type::Body, name)); + ui.menu_button(tr!("Swap…"), |ui| { + egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + for (id, path) in &choices { + if ui.selectable_label(*id == current, path.as_str()).clicked() { + ui.close(); + if *id != current { + app.run("element.swap_symbol", json!({"symbol": id.0})); + } + } + } + }); + }) + .response + .on_hover_text(tr!("Show another symbol here, keeping position, colour effect, filters and name")) + .set_name(tr!("Swap Symbol")); + }); // The class scripts know the symbol by (kept, not run; ADR 0013), in documents // that use scripts. let linkage = app.s.doc.symbol(*symbol).and_then(|s| s.linkage.clone()); @@ -1926,124 +1955,5 @@ fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) { } fn library(app: &mut App, ui: &mut egui::Ui) { - let doc = &app.s.doc; - let rows: Vec = doc - .library - .iter() - .map(|sym| LibraryRow { - item: LibraryItem::Symbol(sym.id), - name: sym.name.clone(), - detail: tr!("{kind} · {frames}f", kind = symbol_kind_label(sym.kind), frames = sym.timeline.frame_count()), - kind: Some(sym.kind), - }) - .chain(doc.bitmaps.iter().map(|b| LibraryRow { item: LibraryItem::Bitmap(b.id), name: b.name.clone(), detail: tr!("Bitmap · {width}×{height}", width = b.width, height = b.height), kind: None })) - .chain(doc.sounds.iter().map(|x| LibraryRow { item: LibraryItem::Sound(x.id), name: x.name.clone(), detail: tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds())), kind: None })) - .collect(); - if rows.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")))); - return; - } - ui.label(text(Type::Caption, trn!("{n} item", "{n} items", rows.len()))); - // Sounds go on the active layer's keyframe at the playhead, their span grown to fit. - let place = |app: &mut App, item: LibraryItem| match item { - LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), - LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), - LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), - }; - egui::ScrollArea::vertical().id_salt("lib").max_height(140.0).auto_shrink([false, true]).show(ui, |ui| { - for row in &rows { - let selected = app.library_sel == Some(row.item); - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click()); - if selected || resp.hovered() { - ui.painter().rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); - } - if selected { - ui.painter().rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); - } - let icon = Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(14.0, 14.0)); - match (row.kind, row.item) { - (Some(kind), _) => { - let kind_color = match kind { - SymbolKind::Graphic => T.kind_graphic, - SymbolKind::MovieClip => T.kind_movie_clip, - SymbolKind::Button => T.kind_button, - }; - ui.painter().rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); - ui.painter().circle_filled(icon.center(), 2.5, kind_color); - } - (None, LibraryItem::Sound(_)) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Sound, color(Type::Body)), - (None, _) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Image, color(Type::Body)), - } - ui.painter().text(r.left_center() + vec2(30.0, 0.0), Align2::LEFT_CENTER, &row.name, font(Type::Body), color(Type::Body)); - ui.painter().text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &row.detail, font(Type::Caption), color(Type::Caption)); - a11y::control(ui, &resp, WidgetType::SelectableLabel, &format!("{} · {}", row.name, row.detail), Some(selected)); - if resp.clicked() { - app.library_sel = Some(row.item); - } - // A symbol opens for editing, as in Animate (ADR 0045); images and sounds go on the - // stage. Place on stage (below) places a symbol. - if resp.double_clicked() { - match row.item { - LibraryItem::Symbol(id) => { - app.run("symbol.edit", json!({"symbol": id.0})); - } - other => { - place(app, other); - } - } - } - // Opens it alone, its registration point at the stage's centre (ADR 0045). - if let LibraryItem::Symbol(id) = row.item { - resp.context_menu(|ui| { - if ui.button(tr!("Edit Symbol")).clicked() { - ui.close(); - app.run("symbol.edit", json!({"symbol": id.0})); - } - }); - } - if let LibraryItem::Sound(id) = row.item { - resp.context_menu(|ui| { - if ui.button(tr!("Delete Sound")).clicked() { - ui.close(); - app.request("sound.delete", json!({"sound": id.0})); - } - }); - } - } - }); - ui.add_space(4.0); - let can_place = app.library_sel.filter(|sel| rows.iter().any(|r| r.item == *sel)); - match can_place { - Some(LibraryItem::Sound(id)) => { - ui.horizontal(|ui| { - if ui.button(tr!("Preview")).on_hover_text(tr!("Plays the sound on its own")).clicked() - && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) - { - app.playing = false; - app.sound.preview(dec.pcm.clone()); - if let Some(e) = app.sound.error.take() { - app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); - } - } - if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click it)")).clicked() { - place(app, LibraryItem::Sound(id)); - } - }); - } - _ => { - if ui.add_enabled(can_place.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre (or double-click an item)")).clicked() - && let Some(item) = can_place { - place(app, item); - } - } - } -} - -/// One Library row: a symbol (with its kind), a bitmap or a sound. -struct LibraryRow { - item: LibraryItem, - name: String, - detail: String, - kind: Option, + crate::library::panel(app, ui); }