diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 4c491efb6b..9dd1e02b32 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -1,57 +1,102 @@ //! Links panel: every image in the document, linked files with their status (missing, modified) //! and embedded images, as rows with a thumbnail, name, page and status. Clicking a row selects //! its image, Ctrl/Cmd-click adds or removes it, and Shift-click selects the images of the rows -//! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the buttons Relink, -//! Go To, Update and Edit Original act on the selected rows (Relink through its dialog, with the -//! Replace choice: `ui.relinkDialog`); Link Info shows the details of the first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: -//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / -//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, Copy Info (the selected -//! rows' file names to the clipboard: `links.copyInfo`), thumbnail size, Show in Folder and Show DCS Transparency Interactions (a warning on the rows of images placed -//! from DCS files that are transparent or overlap transparent objects). +//! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the footer's buttons +//! Relink, Go To, Update and Edit Original act on the selected rows (Relink through its dialog, +//! with the Replace choice: `ui.relinkDialog`); Link Info shows the details of the first. The +//! panel menu adds Relink to Folder, Find in Folder (Find Linked Files: `ui.findLinksInFolder`), +//! Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / Modified +//! (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, Copy Info (the selected rows' +//! file names to the clipboard: `links.copyInfo`), thumbnail size, Show in Folder and Show DCS +//! Transparency Interactions (a warning on the rows of images placed from DCS files that are +//! transparent or overlap transparent objects). //! //! Images and placed documents in opacity-mask art and in the art of symbols, graph designs and //! patterns are listed after the layers' own, one row each; the canvas can't select them, so a -//! click picks such a row in the panel, and the buttons act on it as on any other. +//! click picks such a row in the panel, and the footer's buttons act on it as on any other. //! //! Everything runs through the `links.*` commands (`links.editOriginal` and `links.reveal` are UI -//! commands: they hand the file to the system). +//! commands: they hand the file to the system) and the panel's own `ui.links.*` commands +//! ([`run`]). -use egui::{Sense, Ui, vec2}; +use std::collections::HashMap; +use std::sync::Arc; + +use craft::behavior::{IconId, Selection, keyed}; +use craft::host::files::{PickKind, PickRequest}; +use craft_keymap::CommandRef; +use craft_ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft_ui::display::{Shade, Text}; +use craft_ui::form::Field; +use craft_ui::list::{List, ListRow, ThumbSize}; +use craft_ui::menu::{Menu, MenuItem, PanelRow}; +use craft_ui::runtime::commands::{CommandState, CommandStates}; +use craft_ui::sections::{FooterAction, FooterBar, Panel, Section}; +use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::NodeId; -use super::{pstate, set_pstate}; -use crate::theme::{self, Tokens}; -use crate::widgets::{self, menu_item}; -use crate::{VectorcraftApp, icons}; +use crate::addons::select::link_status; +use crate::file_asks::{self, Owner}; +use crate::VectorcraftApp; pub const ID: &str = "links"; /// Seconds between two looks at the linked files (they change outside the app). const RECHECK: f64 = 2.0; const SHOW: [(&str, &str); 4] = [("all", "Show All"), ("missing", "Show Missing"), ("modified", "Show Modified"), ("embedded", "Show Embedded")]; const SORT: [(&str, &str); 4] = [("name", "Sort by Name"), ("kind", "Sort by Kind"), ("status", "Sort by Status"), ("size", "Sort by Size")]; -const THUMBS: [(f32, &str); 4] = [(0.0, "No Thumbnails"), (18.0, "Small Thumbnails"), (28.0, "Medium Thumbnails"), (44.0, "Large Thumbnails")]; +const THUMBS: [(&str, ThumbSize, &str); 4] = [ + ("none", ThumbSize::None, "No Thumbnails"), + ("small", ThumbSize::Small, "Small Thumbnails"), + ("medium", ThumbSize::Medium, "Medium Thumbnails"), + ("large", ThumbSize::Large, "Large Thumbnails"), +]; +/// The footer's actions after Show Link Info, in the order the footer lays them out from its end edge. +const FOOTER: [(Act, &str, &str); 5] = [ + (Act::Edit, "pencil", "Edit Original"), + (Act::Update, "rotate-cw", "Update Link"), + (Act::GoTo, "zoom-in", "Go To Link"), + (Act::Relink, "link", "Relink…"), + (Act::BreakLink, "link-2-off", "Break Link"), +]; -/// The panel's options (flyout). +/// The panel's options (panel menu). #[derive(Clone)] -struct Options { - show: &'static str, - sort: Option<&'static str>, - /// Thumbnail side (pt); 0 hides them. - thumb: f32, +pub(super) struct Options { + pub(super) show: &'static str, + pub(super) sort: Option<&'static str>, + pub(super) thumb: ThumbSize, /// The Link Info section is open. - info: bool, + pub(super) info: bool, /// Show DCS Transparency Interactions: rows of DCS images that are transparent or overlap /// transparent objects get a warning. - dcs: bool, + pub(super) dcs: bool, } impl Default for Options { fn default() -> Self { - Self { show: "all", sort: None, thumb: 28.0, info: true, dcs: false } + Self { show: "all", sort: None, thumb: ThumbSize::Medium, info: true, dcs: false } } } +/// The rows outside the layer tree picked in the panel, with the canvas selection +/// ([`canvas_selection`]) they were picked with. +type NestedPicks = Option<((u64, Vec), Vec)>; + +/// What the panel keeps for the session: its options, the rows it last fetched, the request to +/// show an image, the rows picked outside the layer tree, the list's selection (its lead and +/// anchor) and the row whose menu is open. +#[derive(Default)] +pub(crate) struct LinksModel { + pub(super) options: Options, + pub(super) cache: Arc, + /// The (document uid, image) [`show_selected_image`] asks the next draw to reveal. + pub(super) show: Option<(u64, u64)>, + nested: NestedPicks, + selection: Selection, + menu: Option, +} + /// `links.list` and the first selected image's `links.info`, with what they were fetched for. #[derive(Clone, Default)] pub(super) struct Cache { @@ -62,24 +107,31 @@ pub(super) struct Cache { info: Option<(u64, Value)>, /// The objects outside the layer tree, by id: those of the rows, for their thumbnails, and /// those whose opacity masks hold a row's image, for the tooltip. - nested: Vec<(u64, std::sync::Arc)>, + nested: Vec<(u64, Arc)>, } impl Cache { /// Object `id` outside the layer tree, as [`cached`] collected it. - fn nested_node(&self, id: u64) -> Option<&std::sync::Arc> { + pub(super) fn nested_node(&self, id: u64) -> Option<&Arc> { self.nested.binary_search_by_key(&id, |(n, _)| *n).ok().and_then(|i| self.nested.get(i)).map(|(_, n)| n) } } -fn options(ctx: &egui::Context) -> Options { - pstate(ctx, "links-options") -} - -fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { - let mut o = options(ctx); - f(&mut o); - set_pstate(ctx, "links-options", o); +/// What a footer button, a row menu item or a panel menu row does to the selected rows. +#[derive(Clone, Copy, PartialEq)] +enum Act { + Relink, + RelinkToFolder, + FindInFolder, + GoTo, + Update, + Edit, + Reveal, + Embed, + Unembed, + BreakLink, + Placement, + CopyInfo, } /// Show the Links panel on the selected image (the Control bar's Linked File or Embedded label), @@ -87,16 +139,15 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { /// Link Info section opens, and when the panel next draws the list, a Show filter that leaves out /// the image's row goes back to Show All and the list scrolls to the row ([`show`]). The sort, /// thumbnail size and DCS option keep their settings. -pub(crate) fn show_selected_image(app: &mut VectorcraftApp, ctx: &egui::Context) { +pub(crate) fn show_selected_image(app: &mut VectorcraftApp, _ctx: &egui::Context) { let first = selected_images(app).first().copied(); let request = app.session.active().map(|st| st.uid).zip(first); - set_pstate(ctx, "links-scroll-to", request); + let model = &mut app.ui.links; + model.show = request; // The list drawn next is read after this request, so a row a file change has just brought // into the Show filter is there to scroll to. - let mut c: std::sync::Arc = pstate(ctx, "links-cache"); - std::sync::Arc::make_mut(&mut c).at = f64::NEG_INFINITY; - set_pstate(ctx, "links-cache", c); - set_options(ctx, |o| o.info = true); + Arc::make_mut(&mut model.cache).at = f64::NEG_INFINITY; + model.options.info = true; if let Err(e) = crate::panel_docking::reveal_panel(app, ID) { app.status(e); } @@ -105,12 +156,13 @@ pub(crate) fn show_selected_image(app: &mut VectorcraftApp, ctx: &egui::Context) /// The rows to show (cached per document revision, the files looked at again every [`RECHECK`] /// seconds) and the Link Info of the first selected image when the section is open. A frame that /// fetches nothing returns the stored cache without copying it and stores nothing. -fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option> { +fn cached(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option> { + let o = app.ui.links.options.clone(); let st = app.session.active()?; let key = Some((st.uid, st.revision, o.show, o.sort, o.dcs)); - let first = selected_links(app, ctx).first().copied(); + let first = selected_links(app).first().copied(); let now = ctx.input(|i| i.time); - let mut c: std::sync::Arc = pstate(ctx, "links-cache"); + let mut c = Arc::clone(&app.ui.links.cache); let stale = c.key != key || now - c.at > RECHECK; if stale { let same_doc = c.key == key; @@ -138,13 +190,13 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< _ => vec![], } }; - c = std::sync::Arc::new(Cache { key, at: now, list, info: None, nested }); + c = Arc::new(Cache { key, at: now, list, info: None, nested }); } let want = first.filter(|_| o.info); if stale || c.info.as_ref().map(|(id, _)| *id) != want { let info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); - std::sync::Arc::make_mut(&mut c).info = info; - set_pstate(ctx, "links-cache", c.clone()); + Arc::make_mut(&mut c).info = info; + app.ui.links.cache = Arc::clone(&c); } // Files change on disk without a frame of ours: look again later. ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK)); @@ -160,7 +212,7 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< pub(super) fn stored_objects( doc: &vectorcraft_doc::Document, mut want: std::collections::HashSet, -) -> Vec<(u64, std::sync::Arc)> { +) -> Vec<(u64, Arc)> { let mut out = vec![]; collect_stored(doc, &mut want, &mut out); if !want.is_empty() && doc.mounted_art.is_empty() { @@ -177,14 +229,10 @@ pub(super) fn stored_objects( /// Adds the objects of `d` outside the layer tree whose ids are in `want` to `out`, taking their /// ids out of `want`. -fn collect_stored( - d: &vectorcraft_doc::Document, - want: &mut std::collections::HashSet, - out: &mut Vec<(u64, std::sync::Arc)>, -) { +fn collect_stored(d: &vectorcraft_doc::Document, want: &mut std::collections::HashSet, out: &mut Vec<(u64, Arc)>) { d.visit_stored_arcs(|n, place| { if !place.in_layers() && want.remove(&n.id.0) { - out.push((n.id.0, std::sync::Arc::clone(n))); + out.push((n.id.0, Arc::clone(n))); } }); } @@ -209,32 +257,25 @@ fn canvas_selection(app: &VectorcraftApp) -> Option<(u64, Vec)> { app.session.active().map(|st| (st.uid, st.selection.objects.iter().map(|id| id.0).collect())) } -/// The rows outside the layer tree picked in the panel, with the canvas selection -/// ([`canvas_selection`]) they were picked with. -type NestedPicks = Option<((u64, Vec), Vec)>; - /// The rows outside the layer tree picked in the panel, in the active document. A change of the -/// canvas selection, or another document, drops them (the panel looks every frame). -fn nested_picks(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { - let picks: NestedPicks = pstate(ctx, "links-nested"); - let Some((at, ids)) = picks else { return vec![] }; - if Some(&at) == canvas_selection(app).as_ref() { - return ids; +/// canvas selection, or another document, drops them. +fn nested_picks(app: &VectorcraftApp) -> Vec { + match &app.ui.links.nested { + Some((at, ids)) if Some(at) == canvas_selection(app).as_ref() => ids.clone(), + _ => vec![], } - set_pstate::(ctx, "links-nested", None); - vec![] } /// Keep `ids` as the rows picked in the panel, with the canvas selection as it is now. -fn set_nested_picks(app: &VectorcraftApp, ctx: &egui::Context, ids: Vec) { - set_pstate(ctx, "links-nested", canvas_selection(app).map(|at| (at, ids))); +fn set_nested_picks(app: &mut VectorcraftApp, ids: Vec) { + app.ui.links.nested = canvas_selection(app).map(|at| (at, ids)); } /// The ids of the selected rows: the selected images and placed documents, then the rows outside /// the layer tree picked in the panel. -fn selected_links(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { +fn selected_links(app: &VectorcraftApp) -> Vec { let mut ids = selected_images(app); - for id in nested_picks(app, ctx) { + for id in nested_picks(app) { if !ids.contains(&id) { ids.push(id); } @@ -242,13 +283,9 @@ fn selected_links(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { ids } -/// [`selected_links`] with the app's window context, for a command run outside the panel (the -/// selected images and placed documents alone when there is no window). +/// [`selected_links`], for a command run outside the panel. pub(crate) fn selected_rows_of_app(app: &VectorcraftApp) -> Vec { - match app.ui_ctx.clone() { - Some(ctx) => selected_links(app, &ctx), - None => selected_images(app), - } + selected_links(app) } /// The rows of `list` whose image is selected. @@ -265,6 +302,11 @@ fn status_is(r: &Value, status: &str) -> bool { r["status"].as_str() == Some(status) } +/// Does row `r` hold a file that changed, or a preview that Update Link can read again? +fn is_modified(r: &Value) -> bool { + status_is(r, "modified") || (r["preview"] == true && !status_is(r, "missing")) +} + fn report(app: &mut VectorcraftApp, r: Result, done: impl FnOnce(&Value) -> String) { let msg = match r { Ok(v) => done(&v), @@ -298,30 +340,37 @@ pub(crate) fn selected_ids(app: &VectorcraftApp) -> Vec { selected_images(app) } +/// Asks for `request` for the active document and runs `then` with the path picked; a cancelled +/// pick does nothing. +fn ask(app: &mut VectorcraftApp, request: PickRequest, then: impl FnOnce(&mut VectorcraftApp, String) + 'static) { + file_asks::ask(app, request, Owner::Document, move |app, picked| { + if let Some(path) = picked.first_path() { + then(app, path.to_string_lossy().into_owned()); + } + Ok(Value::Null) + }); +} + /// Replace images `ids` with a picked file (Control bar, Properties): it keeps its own aspect /// ratio, fitted inside the old bounds (Placement Options: Fit), whatever their Placement Options /// say. pub(crate) fn replace(app: &mut VectorcraftApp, ids: Vec) { - crate::picks::button(app, move |app| { - let pick = crate::FilePick { filters: crate::FilePick::filters(vectorcraft_engine::cmd::fileio::place_filters()), ..Default::default() }; - let Some(path) = crate::picks::open(app, &pick) else { return }; - let r = app.run("links.relink", json!({ "ids": ids.clone(), "path": path, "preserve": "fit" })); + let request = vectorcraft_engine::cmd::fileio::place_filters().fold(PickRequest::open("links"), |r, (name, exts)| r.filter(name, exts)); + ask(app, request, move |app, path| { + let r = app.run("links.relink", json!({ "ids": ids, "path": path, "preserve": "fit" })); report(app, r, |v| crate::i18n::msg_n(v["relinked"].as_array().map_or(0, Vec::len) as u64, "Replaced {n} image", "Replaced {n} images", &[])); }); } /// Relink images `ids` (none: every missing one) to the files of their names in a picked folder. fn relink_to_folder(app: &mut VectorcraftApp, ids: Vec) { - crate::picks::button(app, move |app| relink_to_picked_folder(app, ids.clone())); -} - -fn relink_to_picked_folder(app: &mut VectorcraftApp, ids: Vec) { - let Some(folder) = crate::picks::folder(app) else { return }; - let ids = Some(ids).filter(|i| !i.is_empty()); - let r = app.run("links.relink", json!({ "ids": ids, "folder": folder })); - report(app, r, |v| { - let missed: Vec<&str> = v["notFound"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); - relinked_status_missed(v["relinked"].as_array().map_or(0, Vec::len), &missed) + ask(app, PickRequest::folder("links"), move |app, folder| { + let ids = Some(ids).filter(|i| !i.is_empty()); + let r = app.run("links.relink", json!({ "ids": ids, "folder": folder })); + report(app, r, |v| { + let missed: Vec<&str> = v["notFound"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + relinked_status_missed(v["relinked"].as_array().map_or(0, Vec::len), &missed) + }); }); } @@ -351,9 +400,7 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) { } return; } - let name = name.to_string(); - crate::picks::button(app, move |app| { - let Some(path) = crate::picks::save(app, &crate::FilePick::named(&name)) else { return }; + ask(app, PickRequest::save("links").file_name(name), move |app, path| { let r = app.run("links.unembed", json!({ "id": id, "path": path })); report(app, r, |v| format!("Unembedded to {}", v["path"].as_str().unwrap_or_default())); }); @@ -365,7 +412,7 @@ pub(crate) fn can_unembed(app: &VectorcraftApp, embedded: usize) -> bool { match embedded { 0 => false, 1 => true, - _ => app.services.download.is_some() || app.services.pick_folder.is_some(), + _ => app.services.download.is_some() || file_asks::can(app, PickKind::Folder), } } @@ -378,15 +425,12 @@ pub(crate) fn unembed_several(app: &mut VectorcraftApp, ids: Vec) { } return; } - crate::picks::button(app, move |app| unembed_to_picked_folder(app, ids.clone())); -} - -fn unembed_to_picked_folder(app: &mut VectorcraftApp, ids: Vec) { - let Some(folder) = crate::picks::folder(app) else { return }; - let r = app.run("links.unembed", json!({ "ids": ids, "folder": folder })); - report(app, r, |v| { - let n = v["unembedded"].as_array().map_or(0, Vec::len); - crate::i18n::msg_n(n as u64, "Unembedded {n} image to {folder}", "Unembedded {n} images to {folder}", &[("folder", &folder)]) + ask(app, PickRequest::folder("links"), move |app, folder| { + let r = app.run("links.unembed", json!({ "ids": ids, "folder": folder })); + report(app, r, |v| { + let n = v["unembedded"].as_array().map_or(0, Vec::len); + crate::i18n::msg_n(n as u64, "Unembedded {n} image to {folder}", "Unembedded {n} images to {folder}", &[("folder", &folder)]) + }); }); } @@ -447,8 +491,7 @@ pub(crate) fn copy_info(app: &mut VectorcraftApp, p: &Value) -> Result = - rows.iter().filter_map(|r| Some((r["id"].as_u64()?, r["name"].as_str().unwrap_or_default()))).collect(); + let by_id: HashMap = rows.iter().filter_map(|r| Some((r["id"].as_u64()?, r["name"].as_str().unwrap_or_default()))).collect(); let mut names = Vec::with_capacity(wanted.len()); for id in &wanted { let name = by_id.get(id).ok_or_else(|| format!("object {} is not an image or a linked file", *id))?; @@ -483,27 +526,6 @@ pub(crate) fn openable_original(path: &str) -> Result<(), String> { Ok(()) } -/// A status badge: missing (red, ?), modified (amber, !), embedded (the image icon). -fn badge(ui: &Ui, r: egui::Rect, status: &str) { - let t = Tokens::get(ui.ctx()); - let c = r.center(); - let p = ui.painter(); - let font = theme::semibold(10.0); - match status { - "missing" => { - p.circle_filled(c, 6.5, t.error); - p.text(c, egui::Align2::CENTER_CENTER, "?", font, egui::Color32::WHITE); - } - "modified" => { - let pts = vec![c + vec2(0.0, -7.0), c + vec2(7.0, 6.0), c + vec2(-7.0, 6.0)]; - p.add(egui::Shape::convex_polygon(pts, t.warning, egui::Stroke::NONE)); - p.text(c + vec2(0.0, 1.5), egui::Align2::CENTER_CENTER, "!", font, egui::Color32::BLACK); - } - "embedded" => icons::paint(ui, "image", egui::Rect::from_center_size(c, vec2(13.0, 13.0)), t.text_dim), - _ => {} - } -} - /// The tooltip of row `r`. A row outside the layer tree also names where it is stored /// (`links.list`'s `owner`): the symbol, graph design, pattern or brush whose art holds it, and the /// object whose opacity mask holds it, by `mask` (that object's name) or else by its id. @@ -549,210 +571,272 @@ fn file_tip(r: &Value) -> String { } } -/// A click on the row of image `id` among the shown `rows`: plain selects the image alone, -/// Ctrl/Cmd adds or removes it, and Shift selects the images of the rows from the last row clicked -/// without Shift in this document to it, or with Ctrl/Cmd adds them to the selection. A -/// Shift-click while that row is not shown, or after the last click was in another document, acts -/// as a click without Shift. Rows outside the layer tree are picked in the panel itself, as the -/// canvas can't select them; a click without Ctrl/Cmd replaces both kinds of selection. -fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64, m: egui::Modifiers) { - let Some(uid) = app.session.active().map(|st| st.uid) else { return }; - let anchor: Option<(u64, u64)> = pstate(ctx, "links-anchor"); - let at = |id: u64| rows.iter().position(|r| r["id"].as_u64() == Some(id)); - let nested = |r: &Value| nested_row(r).then(|| r["id"].as_u64()).flatten(); - let mut picks = if m.command { nested_picks(app, ctx) } else { vec![] }; - if m.shift - && let Some((_, a)) = anchor.filter(|(doc, _)| *doc == uid) - && let (Some(i), Some(j)) = (at(a), at(id)) - { - let range = rows.get(i.min(j)..=i.max(j)).unwrap_or_default(); - let canvas: Vec = range.iter().filter(|r| !nested_row(r)).filter_map(|r| r["id"].as_u64()).collect(); - picks.extend(range.iter().filter_map(nested).filter(|id| !picks.contains(id)).collect::>()); - app.run(if m.command { "select.add" } else { "select.set" }, json!({ "ids": canvas })).ok(); - set_nested_picks(app, ctx, picks); - return; - } - set_pstate(ctx, "links-anchor", Some((uid, id))); - let row = rows.iter().find(|r| r["id"].as_u64() == Some(id)); - if row.is_some_and(nested_row) { - match picks.iter().position(|p| *p == id) { - Some(i) if m.command => { - picks.remove(i); - } - _ => picks.push(id), - } - if !m.command { - app.run("select.set", json!({ "ids": [] })).ok(); - } - set_nested_picks(app, ctx, picks); - return; - } - if m.command { - app.run("select.toggle", json!({ "id": id })).ok(); - } else { - app.run("select.set", json!({ "ids": [id] })).ok(); - } - set_nested_picks(app, ctx, picks); +/// The name of the object whose opacity mask holds row `r`'s image, by the layer tree's index or +/// from the cache: no walk of the stored art each frame. +fn mask_name(app: &VectorcraftApp, doc: &vectorcraft_doc::Document, cache: &Cache, r: &Value) -> Option { + let m = r["owner"]["maskOf"].as_u64()?; + let n = doc.node(NodeId(m)).or_else(|| cache.nested_node(m).map(|n| &**n))?; + Some(super::layers::shown_name(app, n, crate::i18n::current())) } -pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - let mut o = options(ui.ctx()); - super::layers::show_thumbs_of(app.session.active().map(|st| st.uid)); - let Some(mut cache) = cached(app, ui.ctx(), &o) else { - widgets::dim_label(ui, tl!("No document")); - return; +/// The icon of a row's status mark. +fn status_icon(status: &str) -> &'static str { + match status { + "missing" => "circle-help", + "modified" => "triangle-alert", + "embedded" => "image", + _ => "link", + } +} + +/// The rows the list selected, as the canvas selection and the rows picked in the panel: the +/// canvas can't select a row outside the layer tree, and a pick without Ctrl/Cmd replaces both +/// kinds of selection. +fn apply_selection(app: &mut VectorcraftApp, rows: &[Value], items: Vec) { + let outside = |id: &u64| rows.iter().any(|r| r["id"].as_u64() == Some(*id) && nested_row(r)); + let (nested, canvas): (Vec, Vec) = items.into_iter().partition(outside); + app.run("select.set", json!({ "ids": canvas })).ok(); + set_nested_picks(app, nested); +} + +/// What the selected rows allow, for the footer, the row menu and the panel menu alike. +struct Facts<'a> { + rows: Vec<&'a Value>, + /// Some image in the whole document is missing (not only in the selection). + missing_any: bool, +} + +impl<'a> Facts<'a> { + fn of(list: &'a Value, selected: &[u64]) -> Self { + Facts { rows: selected_rows(list, selected), missing_any: list["missing"].as_u64().unwrap_or(0) > 0 } + } + + fn all(&self) -> Vec { + ids(&self.rows, |_| true) + } + + fn linked(&self) -> Vec { + ids(&self.rows, |r| r["linked"] == true) + } + + fn modified(&self) -> Vec { + ids(&self.rows, is_modified) + } + + fn embedded(&self) -> Vec<&'a Value> { + self.rows.iter().copied().filter(|r| status_is(r, "embedded")).collect() + } + + /// The first linked row whose file is there, for Edit Original and Show in Folder. + fn file_row(&self) -> Value { + match ids(&self.rows, |r| r["linked"] == true && !status_is(r, "missing")).first() { + Some(id) => json!({ "id": id }), + None => json!({}), + } + } +} + +/// Is row `r` an object of the layer tree, which Go To can show on the canvas? +fn in_canvas(app: &VectorcraftApp, r: &Value) -> bool { + !nested_row(r) && r["id"].as_u64().is_some_and(|id| app.session.active().is_some_and(|st| st.doc.node(NodeId(id)).is_some())) +} + +/// Whether `act` can run on the selected rows; `row` is the row a menu opened on, which Go To +/// needs on the canvas. +fn can(app: &VectorcraftApp, act: Act, f: &Facts, row: Option<&Value>) -> bool { + let any = !f.rows.is_empty(); + let editable = f.rows.iter().any(|r| r["linked"] == true && !status_is(r, "missing")); + match act { + Act::Relink => any && file_asks::can(app, PickKind::Open), + Act::RelinkToFolder => (any || f.missing_any) && file_asks::can(app, PickKind::Folder), + Act::FindInFolder => (!f.linked().is_empty() || f.missing_any) && file_asks::can(app, PickKind::Folder), + Act::GoTo => row.map_or(f.rows.len() == 1, |r| in_canvas(app, r)), + Act::Update => !f.modified().is_empty(), + Act::Edit | Act::Reveal => editable, + Act::Embed | Act::BreakLink => !f.linked().is_empty(), + Act::Unembed => can_unembed(app, f.embedded().len()), + Act::Placement | Act::CopyInfo => any, + } +} + +/// Runs `act` on the selected rows; `target` is the row a menu opened on, which Go To, Edit +/// Original and Show in Folder use when it is the one they can act on. +fn act(app: &mut VectorcraftApp, act: Act, target: Option) { + let cache = Arc::clone(&app.ui.links.cache); + let selected = selected_links(app); + let f = Facts::of(&cache.list, &selected); + let file_arg = || match target.filter(|id| f.rows.iter().any(|r| r["id"].as_u64() == Some(*id) && r["linked"] == true && !status_is(r, "missing"))) { + Some(id) => json!({ "id": id }), + None => f.file_row(), }; - // The row that `show_selected_image` asks for, used by this draw only and only in the document - // it was asked in. A Show filter that leaves the row out goes back to Show All, decided from the - // rows this frame draws and scrolls through. - let request: Option<(u64, u64)> = pstate(ui.ctx(), "links-scroll-to"); - if request.is_some() { - set_pstate::>(ui.ctx(), "links-scroll-to", None); - } - let uid = app.session.active().map(|st| st.uid); - let scroll_to = request.filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id); - let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id))); - if scroll_to.filter(|id| o.show != "all" && !listed(&cache, *id)).is_some() { - set_options(ui.ctx(), |o| o.show = "all"); - o = options(ui.ctx()); - let Some(all) = cached(app, ui.ctx(), &o) else { return }; - cache = all; - } - let Some(st) = app.session.active() else { return }; - let doc = st.doc.clone(); - let thumbs = super::layers::ThumbSource::of(app, st, &doc); - let mut selected = selected_links(app, ui.ctx()); - let rows: &[Value] = cache.list["links"].as_array().map_or(&[], Vec::as_slice); - let mut clicked: Option<(u64, egui::Modifiers, bool)> = None; - widgets::list_box(ui, |ui| { - ui.set_min_height(110.0); - ui.set_width(ui.available_width()); - if rows.is_empty() { - let detail = if o.show == "all" { - tl!("File › Place… brings in an image, linked or embedded.") - } else { - tl!("Nothing matches the Show filter.") - }; - super::empty_state(ui, "link", tl!("No images"), detail); - return; - } - egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| { - let h = o.thumb.max(16.0) + 6.0; - for r in rows { - let Some(id) = r["id"].as_u64() else { continue }; - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click()); - if scroll_to == Some(id) { - ui.scroll_to_rect(rect, Some(egui::Align::Center)); - } - if !ui.is_rect_visible(rect) { - continue; - } - if selected.contains(&id) { - ui.painter().rect_filled(rect, 0.0, t.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(rect, 0.0, t.hover); - } - let mut x = rect.left() + 6.0; - if o.thumb > 0.0 { - let tr = egui::Rect::from_min_size(egui::pos2(x, rect.center().y - o.thumb / 2.0), vec2(o.thumb, o.thumb)); - ui.painter().rect_filled(tr, 0.0, egui::Color32::WHITE); - let node = - if nested_row(r) { cache.nested_node(id).map(std::sync::Arc::clone) } else { super::layers::node_arc(&doc, NodeId(id)) }; - if let Some(n) = node { - super::layers::real_thumb(ui, &thumbs, &n, tr); - } - ui.painter().rect_stroke(tr, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - x = tr.right() + 6.0; - } - let right = rect.right() - 22.0; - badge( - ui, - egui::Rect::from_center_size(egui::pos2(right + 10.0, rect.center().y), vec2(16.0, 16.0)), - r["status"].as_str().unwrap_or_default(), - ); - let mut text_right = right - 4.0; - if r["dcsTransparency"] == true { - badge(ui, egui::Rect::from_center_size(egui::pos2(text_right - 8.0, rect.center().y), vec2(16.0, 16.0)), "modified"); - text_right -= 20.0; - } - if let Some(page) = r["page"].as_u64() { - let g = ui.painter().layout_no_wrap(format!("{page}"), egui::FontId::proportional(11.5), t.text_dim); - text_right -= g.size().x; - ui.painter().galley(egui::pos2(text_right, rect.center().y - g.size().y / 2.0), g, t.text_dim); - text_right -= 6.0; - } - let name = r["name"].as_str().unwrap_or_default(); - let clip = egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(text_right.max(x), rect.bottom())); - ui.painter().with_clip_rect(clip).text( - egui::pos2(x, rect.center().y), - egui::Align2::LEFT_CENTER, - name, - egui::FontId::proportional(12.5), - t.text, - ); - // The mask's object by the layer tree's index or from the cache: no walk of the - // stored art each frame. - let mask = r["owner"]["maskOf"] - .as_u64() - .and_then(|m| doc.node(NodeId(m)).or_else(|| cache.nested_node(m).map(|n| &**n))) - .map(|n| super::layers::shown_name(app, n, crate::i18n::current())); - let resp = resp.on_hover_text(status_tip(r, mask)); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), selected.contains(&id), name)); - if resp.secondary_clicked() && !selected.contains(&id) { - click(app, ui.ctx(), rows, id, egui::Modifiers::NONE); - selected = selected_links(app, ui.ctx()); - } - resp.context_menu(|ui| { - row_context_menu(app, ui, r, id, &cache.list); - }); - if resp.double_clicked() { - clicked = Some((id, egui::Modifiers::NONE, true)); - } else if resp.clicked() { - clicked = Some((id, ui.input(|i| i.modifiers), false)); - } - } - }); - }); - match clicked { - Some((id, _, true)) => go_to(app, id), - Some((id, m, false)) => click(app, ui.ctx(), rows, id, m), - None => {} - } - if o.info { - let units = app.session.general_unit(); - link_info(ui, cache.info.as_ref().map(|(_, i)| i), units); - } - let sel = selected_rows(&cache.list, &selected); - let modified = ids(&sel, |r| status_is(r, "modified") || r["preview"] == true && !status_is(r, "missing")); - let can_edit = sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")); - let linked = ids(&sel, |r| r["linked"] == true); - widgets::bottom_bar(ui, |ui| { - let info = !o.info; - if widgets::icon_button(ui, if o.info { "chevron-down" } else { "chevron-right" }, tl!("Show Link Info"), false, 24.0).clicked() { - set_options(ui.ctx(), |o| o.info = info); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if widgets::icon_button_enabled(ui, "pencil", tl!("Edit Original"), false, can_edit, 24.0).clicked() { - crate::menus::invoke(app, "links.editOriginal", file_row(&sel)); - } - if widgets::icon_button_enabled(ui, "rotate-cw", tl!("Update Link"), false, !modified.is_empty(), 24.0).clicked() { - let r = app.run("links.update", json!({ "ids": modified })); - report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); - } - if widgets::icon_button_enabled(ui, "zoom-in", tl!("Go To Link"), false, sel.len() == 1, 24.0).clicked() - && let Some(id) = sel.first().and_then(|r| r["id"].as_u64()) - { + match act { + Act::Relink => crate::menus::invoke(app, "ui.relinkDialog", json!({ "ids": f.all() })), + Act::RelinkToFolder => relink_to_folder(app, f.all()), + Act::FindInFolder => crate::menus::invoke(app, "ui.findLinksInFolder", json!({ "ids": f.linked() })), + Act::GoTo => { + if let Some(id) = target.or_else(|| f.all().first().copied()) { go_to(app, id); } - if widgets::icon_button_enabled(ui, "link", tl!("Relink…"), false, !sel.is_empty() && can_pick(app), 24.0).clicked() { - crate::menus::invoke(app, "ui.relinkDialog", json!({ "ids": ids(&sel, |_| true) })); + } + Act::Update => { + let r = app.run("links.update", json!({ "ids": f.modified() })); + report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); + } + Act::Edit => crate::menus::invoke(app, "links.editOriginal", file_arg()), + Act::Reveal => crate::menus::invoke(app, "links.reveal", file_arg()), + Act::Embed => embed_images(app, f.linked()), + Act::BreakLink => break_link(app, f.linked()), + Act::Unembed => match &f.embedded()[..] { + [] => {} + [r] => { + if let Some(id) = r["id"].as_u64() { + unembed(app, id, r["name"].as_str().unwrap_or("Image")); + } } - if widgets::icon_button_enabled(ui, "link-2-off", tl!("Break Link"), false, !linked.is_empty(), 24.0).clicked() { - break_link(app, linked.clone()); + rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), + }, + Act::Placement => crate::menus::invoke(app, "ui.placementOptionsDialog", json!({ "ids": f.all() })), + Act::CopyInfo => crate::menus::invoke(app, "links.copyInfo", json!({ "ids": f.all() })), + } +} + +/// The Links panel: the images as a list with a footer of link actions and the Link Info section. +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(mut cache) = cached(app, ui.ctx()) else { + Panel::new(tl!("Links")).show(ui, |ui, _| { + Text::new(tl!("No document")).shade(Shade::Muted).show(ui); + }); + return; + }; + let uid = app.session.active().map(|st| st.uid); + let reveal = app.ui.links.show.take().filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id); + let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id))); + // A Show filter that leaves the requested row out goes back to Show All. + if reveal.is_some_and(|id| app.ui.links.options.show != "all" && !listed(&cache, id)) { + app.ui.links.options.show = "all"; + let Some(all) = cached(app, ui.ctx()) else { return }; + cache = all; + } + let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return }; + let o = app.ui.links.options.clone(); + let selected = selected_links(app); + let mut selection = std::mem::take(&mut app.ui.links.selection); + selection.items = selected.clone(); + let open_menu = app.ui.links.menu; + let units = app.session.general_unit(); + + let view: &VectorcraftApp = app; + let facts = Facts::of(&cache.list, &selected); + let rows: &[Value] = cache.list["links"].as_array().map_or(&[], Vec::as_slice); + let by_id: HashMap = rows.iter().filter_map(|r| Some((r["id"].as_u64()?, r))).collect(); + let row_ids: Vec = rows.iter().filter_map(|r| r["id"].as_u64()).collect(); + // PLAN: assumed `thumbs::link_thumbnails(&Context)` and `NodeThumbs::new(&Document, lookup)` + // of document-panels-w8; `lookup` gives the objects outside the layer tree. + let thumbs = super::thumbs::link_thumbnails(ui.ctx()); + let nodes = super::thumbs::NodeThumbs::new(&doc, |id| cache.nested_node(id).cloned()); + let (thumbs, nodes) = (&thumbs, &nodes); + let ppp = ui.ctx().pixels_per_point(); + + let mut footer_pick = None; + let (mut activated, mut menu_for, mut row_act) = (None, None, None); + Panel::new(tl!("Links")) + .footer(|ui, _| { + let info = FooterAction::new(IconId::new(if o.info { "chevron-down" } else { "chevron-right" }), tl!("Show Link Info")); + let actions = std::iter::once(info).chain( + FOOTER.iter().map(|(a, icon, label)| FooterAction::new(IconId::new(icon), tl!(label)).enabled(can(view, *a, &facts, None))), + ); + footer_pick = FooterBar::actions(actions).at_start(1).show_footer(ui).picked; + }) + .show(ui, |ui, _| { + let empty = if o.show == "all" { tl!("No images") } else { tl!("Nothing matches the Show filter.") }; + let mut list = List::::new(tl!("Links")).selection(Bind::bound(&mut selection)).empty(empty).row_menu(); + if let Some(id) = reveal { + list = list.reveal(id); + } + let out = list.show_items(ui, &keyed(&row_ids, |id| *id), &mut |id, _| { + let Some(r) = by_id.get(id) else { return ListRow::spacer() }; + let name = r["name"].as_str().unwrap_or_default(); + let tip = status_tip(r, mask_name(view, &doc, &cache, r)); + let node = NodeId(*id); + let mut row = ListRow::new(name.to_string()).thumb(o.thumb, move |cx, rect| { + // PLAN: assumed `state(..).shown()` gives the texture to paint, if ready. + let request = craft_ui::primitives::ThumbRequest::for_cell(rect.width(), ppp); + let shown = thumbs.state(cx.ctx(), nodes, &super::thumbs::NodeThumb { uid: uid.unwrap_or_default(), node }, &request, craft::host::queue::Priority::VISIBLE).shown(); + if let Some(texture) = shown { + let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + cx.painter().image(texture, rect, uv, egui::Color32::WHITE); + } + }); + if let Some(page) = r["page"].as_u64() { + row = row.trailing(page.to_string()); + } + if r["dcsTransparency"] == true { + row = row.trailing_icon(IconId::new("triangle-alert"), tip.clone()); + } + row.trailing_icon(IconId::new(status_icon(r["status"].as_str().unwrap_or_default())), tip) + }); + for event in out.events { + match event { + CollectionEvent::Activate(id) => activated = Some(id), + CollectionEvent::ContextMenu(request) => menu_for = Some(request.key), + _ => {} + } + } + if let Some(r) = menu_for.or(open_menu).and_then(|id| by_id.get(&id).copied()) { + row_act = show_row_menu(ui, &out.response, view, &facts, r); + } + if o.info { + link_info(ui, cache.info.as_ref().map(|(_, i)| i), units); } }); + + app.ui.links.selection = selection; + if app.ui.links.selection.items != selected { + let items = app.ui.links.selection.items.clone(); + apply_selection(app, rows_of(&cache), items); + } + if menu_for.is_some() { + app.ui.links.menu = menu_for; + } + if let Some(id) = activated { + go_to(app, id); + } + match footer_pick { + Some(0) => app.ui.links.options.info = !o.info, + Some(i) => { + if let Some((a, ..)) = FOOTER.get(i - 1) { + act(app, *a, None); + } + } + None => {} + } + if let Some((a, id)) = row_act { + app.ui.links.menu = None; + act(app, a, Some(id)); + } +} + +/// The rows of the cached list. +fn rows_of(cache: &Cache) -> &[Value] { + cache.list["links"].as_array().map_or(&[], Vec::as_slice) +} + +/// The context menu of row `r`, hanging from `opener`: the link actions for the selected rows, +/// and Embed Image or Unembed… by what the row is. Returns the action chosen with the row. +fn show_row_menu(ui: &mut Ui, opener: &egui::Response, app: &VectorcraftApp, f: &Facts, r: &Value) -> Option<(Act, u64)> { + let id = r["id"].as_u64()?; + let last = if status_is(r, "embedded") { (Act::Unembed, "Unembed…") } else { (Act::Embed, "Embed Image") }; + let items = [(Act::Relink, "Relink…"), (Act::GoTo, "Go To Link"), (Act::Update, "Update Link"), (Act::Edit, "Edit Original"), (Act::Reveal, "Show in Folder"), last]; + let shown = Menu::context(tl!("Link"), opener).show(ui, |ui, _| { + let mut ran = None; + for (a, label) in items { + if MenuItem::new(tl!(label)).enabled(can(app, a, f, Some(r))).show(ui).ran { + ran = Some(a); + } + } + ran }); + shown.inner.flatten().map(|a| (a, id)) } /// Break Link (`links.embed`) of `ids`: images keep their files' pixels, placed documents become @@ -794,73 +878,6 @@ fn embed_images(app: &mut VectorcraftApp, ids: Vec) { }); } -/// An item's right-click context menu in the Links panel. -fn row_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, r: &Value, id: u64, list: &Value) { - let selected = selected_links(app, ui.ctx()); - let sel = selected_rows(list, &selected); - let linked = ids(&sel, |r| r["linked"] == true); - let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); - let modified = ids(&sel, |r| status_is(r, "modified") || (r["preview"] == true && !status_is(r, "missing"))); - let can_edit = sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")); - let in_canvas = app.session.active().is_some_and(|st| st.doc.node(NodeId(id)).is_some()) && !nested_row(r); - - if menu_item(ui, tl!("Relink…"), !sel.is_empty() && can_pick(app), false) { - crate::menus::invoke(app, "ui.relinkDialog", json!({ "ids": ids(&sel, |_| true) })); - ui.close(); - } - if menu_item(ui, tl!("Go To Link"), in_canvas, false) { - go_to(app, id); - ui.close(); - } - if menu_item(ui, tl!("Update Link"), !modified.is_empty(), false) { - let r = app.run("links.update", json!({ "ids": modified })); - report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); - ui.close(); - } - if menu_item(ui, tl!("Edit Original"), can_edit, false) { - let file_arg = if r["linked"] == true && !status_is(r, "missing") { json!({ "id": id }) } else { file_row(&sel) }; - crate::menus::invoke(app, "links.editOriginal", file_arg); - ui.close(); - } - if menu_item(ui, tl!("Show in Folder"), can_edit, false) { - let file_arg = if r["linked"] == true && !status_is(r, "missing") { json!({ "id": id }) } else { file_row(&sel) }; - crate::menus::invoke(app, "links.reveal", file_arg); - ui.close(); - } - ui.separator(); - if status_is(r, "embedded") { - if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { - match &embedded[..] { - [r] => { - if let Some(id) = r["id"].as_u64() { - let name = r["name"].as_str().unwrap_or("Image").to_string(); - unembed(app, id, &name); - } - } - rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), - } - ui.close(); - } - } else if menu_item(ui, tl!("Embed Image"), !linked.is_empty(), false) { - embed_images(app, linked); - ui.close(); - } -} - -/// The params of Edit Original and Show in Folder for the selected rows `sel`: the first linked -/// row whose file is there (rows outside the layer tree included), else none (the selection's). -fn file_row(sel: &[&Value]) -> Value { - match ids(sel, |r| r["linked"] == true && !status_is(r, "missing")).first() { - Some(id) => json!({ "id": id }), - None => json!({}), - } -} - -/// Pick-a-file actions need a file dialog (the desktop app). -fn can_pick(app: &VectorcraftApp) -> bool { - app.services.pick_open.is_some() -} - /// Bytes as B, KB or MB. fn size_label(bytes: u64) -> String { match bytes { @@ -876,159 +893,177 @@ pub(crate) fn date_label(ms: u64) -> String { format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC") } -/// The Link Info section: the details of `info` (`links.info`), or a hint. -fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { - widgets::divider(ui); - let Some(i) = info else { - widgets::dim_label(ui, tl!("Select an image to see its Link Info.")); - return; - }; - let pair = |k: &str| { - let n: Vec = i[k].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); - match n[..] { - [x, y] if (x - y).abs() < 0.05 => format!("{x:.0}"), - [x, y] => format!("{x:.0} × {y:.0}"), - _ => String::new(), - } - }; - let row = super::doc_info::row; - row(ui, tl!("Name"), i["fileName"].as_str().or(i["name"].as_str()).unwrap_or_default().into()); - row(ui, tl!("Format"), i["format"].as_str().unwrap_or_default().into()); - row(ui, tl!("Color Space"), i["colorMode"].as_str().unwrap_or_default().into()); - if let Some(l) = i["location"].as_str() { - row(ui, tl!("Location"), l.into()); - } - // A placed document has no resolution: its rows are left out. - for (label, k) in [(tl!("PPI"), "ppi"), (tl!("Effective PPI"), "effectivePpi")] { - if i.get(k).is_some() { - row(ui, label, pair(k)); - } - } - // Pixels, or a placed document's artboard size. - let dims = match (i["pixelWidth"].as_u64(), i["pageWidth"].as_f64(), i["pageHeight"].as_f64()) { - (Some(w), _, _) => format!("{w} × {} px", i["pixelHeight"].as_u64().unwrap_or(0)), - (None, Some(w), Some(h)) => format!("{} × {}", units.format(w), units.format(h)), - _ => String::new(), - }; - row(ui, tl!("Dimensions"), dims); - let scale: Vec = i["scale"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); - if let [x, y] = scale[..] { - row(ui, tl!("Scale"), format!("H: {x:.1}% V: {y:.1}%")); - } - row(ui, tl!("Rotation"), format!("{:.1}°", i["rotation"].as_f64().unwrap_or(0.0))); - if let Some(b) = i["fileSize"].as_u64() { - row(ui, tl!("Size"), size_label(b)); - } - for (k, label) in [("created", tl!("Created")), ("modified", tl!("Modified"))] { - if let Some(ms) = i[k].as_u64() { - row(ui, label, date_label(ms)); - } - } - if let Some(p) = i["page"].as_u64() { - row(ui, tl!("Page"), p.to_string()); - } - let status = match i["status"].as_str().unwrap_or_default() { - "ok" => tl!("Linked"), - "missing" => tl!("Missing"), - "modified" => tl!("Modified"), - _ => tl!("Embedded"), - }; - row(ui, tl!("Status"), status.into()); +/// One line of Link Info: a labelled field whose text is its value. +fn info_row(ui: &mut Ui, label: &str, value: String) { + Field::new(label).value(value.clone()).show(ui, |ui, _| { + Text::new(value).show(ui); + }); } -/// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / +/// The Link Info section: the details of `info` (`links.info`), or a hint. +fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { + Section::fixed(tl!("Link Info")).show(ui, |ui, _| { + let Some(i) = info else { + Text::new(tl!("Select an image to see its Link Info.")).shade(Shade::Muted).show(ui); + return; + }; + let pair = |k: &str| { + let n: Vec = i[k].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); + match n[..] { + [x, y] if (x - y).abs() < 0.05 => format!("{x:.0}"), + [x, y] => format!("{x:.0} × {y:.0}"), + _ => String::new(), + } + }; + info_row(ui, tl!("Name"), i["fileName"].as_str().or(i["name"].as_str()).unwrap_or_default().into()); + info_row(ui, tl!("Format"), i["format"].as_str().unwrap_or_default().into()); + info_row(ui, tl!("Color Space"), i["colorMode"].as_str().unwrap_or_default().into()); + if let Some(l) = i["location"].as_str() { + info_row(ui, tl!("Location"), l.into()); + } + // A placed document has no resolution: its rows are left out. + for (label, k) in [(tl!("PPI"), "ppi"), (tl!("Effective PPI"), "effectivePpi")] { + if i.get(k).is_some() { + info_row(ui, label, pair(k)); + } + } + // Pixels, or a placed document's artboard size. + let dims = match (i["pixelWidth"].as_u64(), i["pageWidth"].as_f64(), i["pageHeight"].as_f64()) { + (Some(w), _, _) => format!("{w} × {} px", i["pixelHeight"].as_u64().unwrap_or(0)), + (None, Some(w), Some(h)) => format!("{} × {}", units.format(w), units.format(h)), + _ => String::new(), + }; + info_row(ui, tl!("Dimensions"), dims); + let scale: Vec = i["scale"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); + if let [x, y] = scale[..] { + info_row(ui, tl!("Scale"), format!("H: {x:.1}% V: {y:.1}%")); + } + info_row(ui, tl!("Rotation"), format!("{:.1}°", i["rotation"].as_f64().unwrap_or(0.0))); + if let Some(b) = i["fileSize"].as_u64() { + info_row(ui, tl!("Size"), size_label(b)); + } + for (k, label) in [("created", tl!("Created")), ("modified", tl!("Modified"))] { + if let Some(ms) = i[k].as_u64() { + info_row(ui, label, date_label(ms)); + } + } + if let Some(p) = i["page"].as_u64() { + info_row(ui, tl!("Page"), p.to_string()); + } + let status = match i["status"].as_str().unwrap_or_default() { + "ok" => tl!("Linked"), + "missing" => tl!("Missing"), + "modified" => tl!("Modified"), + _ => tl!("Embedded"), + }; + info_row(ui, tl!("Status"), status.into()); + }); +} + +/// A command row with the state its panel-menu row shows. +fn entry(app: &VectorcraftApp, f: &Facts, id: &str, params: Value, a: Act) -> (CommandRef, CommandState) { + (CommandRef::with_params(id, params), CommandState::new().enabled(can(app, a, f, None))) +} + +/// A command row that is always enabled and checked or not. +fn option_entry(id: &str, params: Value, checked: bool) -> (CommandRef, CommandState) { + (CommandRef::with_params(id, params), CommandState::new().enabled(true).checked(checked)) +} + +/// The panel menu's command rows with their states, in the groups the menu separates: the link +/// actions, Embed and Placement Options, Show, Sort, Copy Info, and the thumbnail and Link Info +/// options. The Select rows between the second and third group are the add-on's. +fn groups(app: &VectorcraftApp) -> [Vec<(CommandRef, CommandState)>; 6] { + let cache = Arc::clone(&app.ui.links.cache); + let selected = selected_links(app); + let f = Facts::of(&cache.list, &selected); + let o = &app.ui.links.options; + let e = |id: &str, params: Value, a: Act| entry(app, &f, id, params, a); + [ + vec![ + e("ui.relinkDialog", json!({ "ids": f.all() }), Act::Relink), + e("ui.links.relinkToFolder", Value::Null, Act::RelinkToFolder), + e("ui.findLinksInFolder", json!({ "ids": f.linked() }), Act::FindInFolder), + e("ui.links.goTo", Value::Null, Act::GoTo), + e("ui.links.update", Value::Null, Act::Update), + e("links.editOriginal", f.file_row(), Act::Edit), + ], + vec![ + e("ui.links.embed", Value::Null, Act::Embed), + e("ui.links.unembed", Value::Null, Act::Unembed), + e("ui.placementOptionsDialog", json!({ "ids": f.all() }), Act::Placement), + e("links.reveal", f.file_row(), Act::Reveal), + ], + SHOW.iter().map(|(k, _)| option_entry("ui.links.show", json!({ "show": k }), o.show == *k)).collect(), + SORT.iter().map(|(k, _)| option_entry("ui.links.sort", json!({ "sort": k }), o.sort == Some(*k))).collect(), + vec![e("links.copyInfo", json!({ "ids": f.all() }), Act::CopyInfo)], + THUMBS + .iter() + .map(|(k, size, _)| option_entry("ui.links.thumbnails", json!({ "size": k }), o.thumb == *size)) + .chain([option_entry("ui.links.linkInfo", Value::Null, o.info), option_entry("ui.links.dcs", Value::Null, o.dcs)]) + .collect(), + ] +} + +/// The rows of the panel menu: the link commands for the selected rows, Select Linked / Embedded / /// Missing / Modified for the whole document, the Show and Sort options, Copy Info and the /// thumbnail options. -pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let o = options(ui.ctx()); - // The rows the panel shows (the menu opens from it). - let cache = pstate::>(ui.ctx(), "links-cache"); - let list = &cache.list; - let selected = selected_links(app, ui.ctx()); - let sel = selected_rows(list, &selected); - let linked = ids(&sel, |r| r["linked"] == true); - let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); - let any = !sel.is_empty(); - let missing_any = list["missing"].as_u64().unwrap_or(0) > 0; - if menu_item(ui, tl!("Relink…"), any && can_pick(app), false) { - crate::menus::invoke(app, "ui.relinkDialog", json!({ "ids": ids(&sel, |_| true) })); - } - if menu_item(ui, tl!("Relink to Folder…"), (any || missing_any) && app.services.pick_folder.is_some(), false) { - relink_to_folder(app, ids(&sel, |_| true)); - } - if menu_item(ui, tl!("Find in Folder…"), (!linked.is_empty() || missing_any) && app.services.pick_folder.is_some(), false) { - crate::menus::invoke(app, "ui.findLinksInFolder", json!({ "ids": linked })); - } - if menu_item(ui, tl!("Go To Link"), sel.len() == 1, false) - && let Some(id) = sel.first().and_then(|r| r["id"].as_u64()) - { - go_to(app, id); - } - if menu_item(ui, tl!("Update Link"), sel.iter().any(|r| status_is(r, "modified")), false) { - let r = app.run("links.update", json!({ "ids": ids(&sel, |r| status_is(r, "modified")) })); - report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); - } - if menu_item(ui, tl!("Edit Original"), sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")), false) { - crate::menus::invoke(app, "links.editOriginal", file_row(&sel)); - } - ui.separator(); - if menu_item(ui, tl!("Embed Image(s)"), !linked.is_empty(), false) { - embed_images(app, linked); - } - if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { - match &embedded[..] { - [r] => { - if let Some(id) = r["id"].as_u64() { - let name = r["name"].as_str().unwrap_or("Image").to_string(); - unembed(app, id, &name); - } - } - rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), +pub(crate) fn menu_rows(app: &VectorcraftApp) -> Vec { + let mut rows = vec![]; + for (i, group) in groups(app).into_iter().enumerate() { + if i > 0 { + rows.push(PanelRow::Separator); } - } - if menu_item(ui, tl!("Placement Options…"), any, false) { - crate::menus::invoke(app, "ui.placementOptionsDialog", json!({ "ids": ids(&sel, |_| true) })); - } - if menu_item(ui, tl!("Show in Folder"), sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")), false) { - crate::menus::invoke(app, "links.reveal", file_row(&sel)); - } - ui.separator(); - // Select Linked, Embedded, Missing and Modified: every such image in the document, not only - // the rows shown; with Shift, added to the selection. - use crate::addons::select::link_status; - for (i, (status, label, _)) in link_status::STATUSES.iter().enumerate() { - if menu_item(ui, tl!(label), app.ui.link_statuses.has.get(i).copied().unwrap_or(false), false) { - let p = json!({ "status": status }); - let p = if ui.input(|i| i.modifiers.shift) { link_status::with_shift(p) } else { p }; - crate::menus::invoke(app, link_status::COMMAND, p); + if i == 2 { + rows.extend(link_status::rows()); + rows.push(PanelRow::Separator); } + rows.extend(group.into_iter().map(|(command, _)| PanelRow::Command(command))); } - ui.separator(); - for (id, label) in SHOW { - if menu_item(ui, tl!(label), true, o.show == id) { - set_options(ui.ctx(), |o| o.show = id); - } - } - ui.separator(); - for (id, label) in SORT { - if menu_item(ui, tl!(label), true, o.sort == Some(id)) { - set_options(ui.ctx(), |o| o.sort = if o.sort == Some(id) { None } else { Some(id) }); - } - } - ui.separator(); - if menu_item(ui, tl!("Copy Info"), any, false) { - crate::menus::invoke(app, "links.copyInfo", json!({ "ids": ids(&sel, |_| true) })); - } - ui.separator(); - for (px, label) in THUMBS { - if menu_item(ui, tl!(label), true, o.thumb == px) { - set_options(ui.ctx(), |o| o.thumb = px); - } - } - if menu_item(ui, tl!("Show Link Info"), true, o.info) { - set_options(ui.ctx(), |o| o.info = !o.info); - } - if menu_item(ui, tl!("Show DCS Transparency Interactions"), true, o.dcs) { - set_options(ui.ctx(), |o| o.dcs = !o.dcs); - } + rows +} + +/// The enabled and checked states of the panel menu's rows, into the frame's command states. +pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { + for (command, state) in groups(app).into_iter().flatten() { + states.set(command, state); + } + link_status::states(app, states); +} + +/// The option of `names` that `p[key]` names. +fn choose(p: &Value, key: &str, mut names: impl Iterator) -> Result<&'static str, String> { + let given = p.get(key).and_then(Value::as_str).unwrap_or_default(); + names.find(|n| *n == given).ok_or_else(|| format!("`{key}` is not one of the options: {given:?}")) +} + +/// The panel's own commands (`ui.links.*`), for the panel menu's rows and automation; `None` for +/// any other id. +pub(crate) fn run(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { + let acted = |app: &mut VectorcraftApp, a: Act, target: Option| { + act(app, a, target); + Ok(()) + }; + let done = match id { + "ui.links.relinkToFolder" => acted(app, Act::RelinkToFolder, None), + "ui.links.goTo" => acted(app, Act::GoTo, p.get("id").and_then(Value::as_u64)), + "ui.links.update" => acted(app, Act::Update, None), + "ui.links.embed" => acted(app, Act::Embed, None), + "ui.links.unembed" => acted(app, Act::Unembed, None), + "ui.links.show" => choose(p, "show", SHOW.iter().map(|(k, _)| *k)).map(|k| app.ui.links.options.show = k), + // Choosing the chosen sort again clears it. + "ui.links.sort" => choose(p, "sort", SORT.iter().map(|(k, _)| *k)).map(|k| { + let o = &mut app.ui.links.options; + o.sort = if o.sort == Some(k) { None } else { Some(k) }; + }), + "ui.links.thumbnails" => choose(p, "size", THUMBS.iter().map(|(k, ..)| *k)).map(|k| { + if let Some((_, size, _)) = THUMBS.iter().find(|(n, ..)| *n == k) { + app.ui.links.options.thumb = *size; + } + }), + "ui.links.linkInfo" => Ok(app.ui.links.options.info = !app.ui.links.options.info), + "ui.links.dcs" => Ok(app.ui.links.options.dcs = !app.ui.links.options.dcs), + _ => return None, + }; + Some(done.map(|()| Value::Null)) } diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 85a26e557a..117d7d0ffe 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -1,9 +1,12 @@ -//! The Links panel, its flyout, Link Info, Edit Original / Show in Folder, the Placement Options +//! The Links panel, its menu rows, Link Info, Edit Original / Show in Folder, the Placement Options //! dialog and the Properties panel's image section, drawn headless. use std::cell::{Cell, RefCell}; use std::rc::Rc; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use vectorcraft_engine::Session; @@ -84,22 +87,55 @@ fn app(dir: &Folder) -> (VectorcraftApp, u64, u64) { (app, linked, embedded) } -fn panel(app: &mut VectorcraftApp) -> String { - painted_text(app, super::links::show) +type Rig = Harness<'static, VectorcraftApp>; + +/// The Links panel of `app` in a headless window, after two settled frames. +fn rig(app: VectorcraftApp) -> Rig { + let mut h = Harness::builder() + .with_size(vec2(280.0, 500.0)) + .with_accessibility_check(false) + .build_ui_state(|ui, app: &mut VectorcraftApp| super::links::show(app, ui), app); + h.run_steps(2); + h } -/// Click the row named `name` in the panel with `mods` held (frames at `time` and just after: a -/// second apart, two clicks are not a double-click). -fn click_row(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, mods: egui::Modifiers, time: f64) { - let frame = |app: &mut VectorcraftApp, events: Vec, time: f64| { - let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); - super::tests_appearance::frame_raw(ctx, app, egui::RawInput { events, time: Some(time), ..Default::default() }, super::links::show) - }; - let at = super::tests_appearance::text_rect(&frame(app, vec![], time), name).center(); +/// Whether some node of the panel is named `label`. +fn shown(h: &Rig, label: &str) -> bool { + h.query_all_by_label(label).next().is_some() +} + +/// How many nodes of the panel are named `label`. +fn count(h: &Rig, label: &str) -> usize { + h.query_all_by_label(label).count() +} + +/// The list row named `name`, by its access node. +fn row_pos(h: &Rig, name: &str) -> egui::Pos2 { + let node = h.get_all_by_label(name).find(|n| n.accesskit_node().role() == egui::accesskit::Role::ListItem); + node.unwrap_or_else(|| panic!("no row `{name}`")).rect().center() +} + +/// Click the row named `name` with `mods` held. +fn click_row(h: &mut Rig, name: &str, mods: egui::Modifiers) { + let at = row_pos(h, name); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: mods }; - for (i, e) in [egui::Event::PointerMoved(at), button(true), button(false)].into_iter().enumerate() { - frame(app, vec![e], time + 0.01 * (i + 1) as f64); - } + h.event(egui::Event::ModifiersChanged(mods)); + h.event(egui::Event::PointerMoved(at)); + h.event(button(true)); + h.event(button(false)); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(2); +} + +/// Runs the panel command `id` with `params` on the app in `h`, then a frame. +fn command(h: &mut Rig, id: &str, params: serde_json::Value) { + super::links::run(h.state_mut(), id, ¶ms).expect("a panel command").unwrap(); + h.run_steps(2); +} + +/// The menu item named `label` of an open row menu (the footer has buttons of the same names). +fn menu_item<'h>(h: &'h Rig, label: &str) -> egui_kittest::Node<'h> { + h.get_all_by_label(label).find(|n| n.accesskit_node().role() == egui::accesskit::Role::MenuItem).unwrap_or_else(|| panic!("no item `{label}`")) } /// The selected objects' ids, in ascending order. @@ -112,42 +148,14 @@ fn selected(app: &VectorcraftApp) -> Vec { #[test] fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { let dir = Folder::new("panel"); - let (mut app, linked, _) = app(&dir); - let text = panel(&mut app); - assert!(text.contains("linked.png") && text.contains("embedded.png"), "{text}"); + let (app, linked, _) = app(&dir); + let mut h = rig(app); + assert!(shown(&h, "linked.png") && shown(&h, "embedded.png")); // The selection is the embedded image. - assert!(text.contains("Embedded") && text.contains("Effective PPI"), "{text}"); - app.run("select.set", json!({"ids": [linked]})).unwrap(); - let text = panel(&mut app); - assert!(text.contains("Linked") && text.contains("300 × 200 px") && text.contains("Location"), "{text}"); - // The flyout draws with every item. - let menu = painted_text(&mut app, super::links::menu); - for item in [ - "Relink to Folder…", - "Embed Image(s)", - "Placement Options…", - "Show Missing", - "Sort by Status", - "Sort by Size", - "Large Thumbnails", - "Show in Folder", - ] { - assert!(menu.contains(item), "{item}: {menu}"); - } -} - -/// Click the flyout item `name`, checked or not (frames at `time` and just after). -fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, time: f64) { - let frame = |app: &mut VectorcraftApp, events: Vec, time: f64| { - super::tests_appearance::frame_raw(ctx, app, egui::RawInput { events, time: Some(time), ..Default::default() }, super::links::menu) - }; - let texts = frame(app, vec![], time); - let item = texts.iter().find(|(t, _)| t.trim_start_matches('✓').trim() == name); - let at = item.unwrap_or_else(|| panic!("`{name}` not drawn: {texts:?}")).1.center(); - let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - for (i, e) in [egui::Event::PointerMoved(at), button(true), button(false)].into_iter().enumerate() { - frame(app, vec![e], time + 0.01 * (i + 1) as f64); - } + assert!(shown(&h, "Embedded") && shown(&h, "Effective PPI")); + h.state_mut().run("select.set", json!({"ids": [linked]})).unwrap(); + h.run_steps(2); + assert!(shown(&h, "Linked") && shown(&h, "300 × 200 px") && shown(&h, "Location")); } /// Opening the panel on the selected image (the Control bar's Linked File or Embedded label) opens @@ -156,67 +164,28 @@ fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, ti #[test] fn opening_the_panel_on_the_selected_image_shows_its_row_and_link_info() { let dir = Folder::new("show-selected"); - let (mut app, linked, embedded) = app(&dir); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let text = |app: &mut VectorcraftApp, time: f64| { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); - texts.into_iter().map(|(t, _)| t).collect::>().join("\n") - }; - app.run("select.set", json!({"ids": [linked]})).unwrap(); - click_menu_item(&mut app, &ctx, "Show Link Info", 1.0); - click_menu_item(&mut app, &ctx, "Show Embedded", 2.0); - let before = text(&mut app, 3.0); - assert!(!before.contains("linked.png") && !before.contains("Location"), "the filter hides the row, Link Info is closed: {before}"); - app.run("window.panel.close", json!({"panel": super::links::ID})).ok(); - super::links::show_selected_image(&mut app, &ctx); - assert!(crate::panel_docking::visible(&app.ui, super::links::ID), "status: {}", app.ui.status); - let after = text(&mut app, 4.0); - assert!(after.contains("linked.png") && after.contains("embedded.png"), "Show All lists every row: {after}"); - assert!(after.contains("Location") && after.contains("300 × 200 px"), "Link Info shows the linked image: {after}"); + let (app, linked, embedded) = app(&dir); + let mut h = rig(app); + h.state_mut().run("select.set", json!({"ids": [linked]})).unwrap(); + command(&mut h, "ui.links.linkInfo", json!({})); + command(&mut h, "ui.links.show", json!({"show": "embedded"})); + assert!(!shown(&h, "linked.png") && !shown(&h, "Location"), "the filter hides the row, Link Info is closed"); + h.state_mut().run("window.panel.close", json!({"panel": super::links::ID})).ok(); + let ctx = h.ctx.clone(); + super::links::show_selected_image(h.state_mut(), &ctx); + h.run_steps(2); + assert!(crate::panel_docking::visible(h.state(), super::links::ID), "status: {}", h.state().ui.status); + assert!(shown(&h, "linked.png") && shown(&h, "embedded.png"), "Show All lists every row"); + assert!(shown(&h, "Location") && shown(&h, "300 × 200 px"), "Link Info shows the linked image"); // An embedded image under Show Embedded keeps the filter. - app.run("select.set", json!({"ids": [embedded]})).unwrap(); - click_menu_item(&mut app, &ctx, "Show Link Info", 5.0); - click_menu_item(&mut app, &ctx, "Show Embedded", 6.0); - super::links::show_selected_image(&mut app, &ctx); - assert!(crate::panel_docking::visible(&app.ui, super::links::ID), "an open panel stays open"); - let embedded_only = text(&mut app, 7.0); - assert!(embedded_only.contains("embedded.png") && !embedded_only.contains("linked.png"), "Show Embedded stays: {embedded_only}"); - assert!(embedded_only.contains("Effective PPI"), "Link Info shows the embedded image: {embedded_only}"); -} - -/// Opening the panel on the selected image scrolls the list to the image's row when it is out of -/// view. -#[test] -fn opening_the_panel_on_the_selected_image_scrolls_to_its_row() { - let dir = Folder::new("show-selected-scroll"); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - // The panel lists the image placed first last, below the list's view. - let mut first = None; - for i in 0..20 { - let path = dir.file(&format!("img{i:02}.png"), &png(10, 10)); - let id = app.run("file.place", json!({"path": path, "at": [10 + 15 * i, 100]})).unwrap()["ids"][0].as_u64().unwrap(); - first.get_or_insert(id); - } - app.run("select.set", json!({"ids": [first]})).unwrap(); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - // How many times the first image's name is drawn: its row while in view, and Link Info. - let drawn = |app: &mut VectorcraftApp, time: f64| { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); - texts.iter().filter(|(t, _)| t == "img00.png").count() - }; - let before = drawn(&mut app, 1.0); - assert_eq!(drawn(&mut app, 2.0), before, "the list stays at the top"); - super::links::show_selected_image(&mut app, &ctx); - // The list scrolls over the frames after the one that asks. - for time in [3.0, 4.0, 5.0] { - drawn(&mut app, time); - } - assert_eq!(drawn(&mut app, 6.0), before + 1, "the row scrolled into view"); + h.state_mut().run("select.set", json!({"ids": [embedded]})).unwrap(); + command(&mut h, "ui.links.linkInfo", json!({})); + command(&mut h, "ui.links.show", json!({"show": "embedded"})); + super::links::show_selected_image(h.state_mut(), &ctx); + h.run_steps(2); + assert!(crate::panel_docking::visible(h.state(), super::links::ID), "an open panel stays open"); + assert!(shown(&h, "embedded.png") && !shown(&h, "linked.png"), "Show Embedded stays"); + assert!(shown(&h, "Effective PPI"), "Link Info shows the embedded image"); } /// Opening the panel on the selected image draws a list read after the request, so a row that a @@ -224,46 +193,18 @@ fn opening_the_panel_on_the_selected_image_scrolls_to_its_row() { #[test] fn opening_the_panel_on_the_selected_image_reads_the_list_again() { let dir = Folder::new("show-selected-fresh"); - let (mut app, linked, _) = app(&dir); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - // How many times the linked image's name is drawn: its row, and Link Info. - let drawn = |app: &mut VectorcraftApp, time: f64| { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); - texts.iter().filter(|(t, _)| t == "linked.png").count() - }; - app.run("select.set", json!({"ids": [linked]})).unwrap(); - click_menu_item(&mut app, &ctx, "Show Missing", 1.0); - assert_eq!(drawn(&mut app, 2.0), 1, "Link Info only: nothing is missing yet"); + let (app, linked, _) = app(&dir); + let mut h = rig(app); + // How many nodes name the linked image: its row, and Link Info. + h.state_mut().run("select.set", json!({"ids": [linked]})).unwrap(); + command(&mut h, "ui.links.show", json!({"show": "missing"})); + assert_eq!(count(&h, "linked.png"), 1, "Link Info only: nothing is missing yet"); std::fs::remove_file(dir.0.join("linked.png")).unwrap(); // Within the time the panel keeps its list before it looks at the files again. - super::links::show_selected_image(&mut app, &ctx); - assert_eq!(drawn(&mut app, 2.1), 2, "the missing image's row and its Link Info are drawn"); -} - -/// The Show filter is set back to Show All from the rows the panel draws, not from the files as -/// they were when the panel was asked to open: a missing image restored before the list is drawn -/// still gets its row. -#[test] -fn opening_the_panel_on_the_selected_image_decides_the_filter_from_the_drawn_rows() { - let dir = Folder::new("show-selected-drawn"); - let (mut app, linked, _) = app(&dir); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let drawn = |app: &mut VectorcraftApp, time: f64| { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); - texts.iter().filter(|(t, _)| t == "linked.png").count() - }; - app.run("select.set", json!({"ids": [linked]})).unwrap(); - click_menu_item(&mut app, &ctx, "Show Missing", 1.0); - let bytes = std::fs::read(dir.0.join("linked.png")).unwrap(); - std::fs::remove_file(dir.0.join("linked.png")).unwrap(); - super::links::show_selected_image(&mut app, &ctx); - std::fs::write(dir.0.join("linked.png"), bytes).unwrap(); - assert_eq!(drawn(&mut app, 2.0), 2, "the restored image's row and its Link Info are drawn"); - assert_eq!(super::pstate::>(&ctx, "links-scroll-to"), None, "the scroll request is used on the row"); + let ctx = h.ctx.clone(); + super::links::show_selected_image(h.state_mut(), &ctx); + h.run_steps(2); + assert_eq!(count(&h, "linked.png"), 2, "the missing image's row and its Link Info are drawn"); } /// A request to show the selected image applies only in the document it was made in: drawn for @@ -271,21 +212,16 @@ fn opening_the_panel_on_the_selected_image_decides_the_filter_from_the_drawn_row #[test] fn opening_the_panel_on_the_selected_image_leaves_another_document_alone() { let dir = Folder::new("show-selected-other-doc"); - let (mut app, linked, _) = app(&dir); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let text = |app: &mut VectorcraftApp, time: f64| { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); - texts.into_iter().map(|(t, _)| t).collect::>().join("\n") - }; - app.run("select.set", json!({"ids": [linked]})).unwrap(); - click_menu_item(&mut app, &ctx, "Show Missing", 1.0); - super::links::show_selected_image(&mut app, &ctx); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let other = text(&mut app, 2.0); - assert!(other.contains("Nothing matches the Show filter."), "the other document keeps Show Missing: {other}"); - assert_eq!(super::pstate::>(&ctx, "links-scroll-to"), None, "the request is dropped"); + let (app, linked, _) = app(&dir); + let mut h = rig(app); + h.state_mut().run("select.set", json!({"ids": [linked]})).unwrap(); + command(&mut h, "ui.links.show", json!({"show": "missing"})); + let ctx = h.ctx.clone(); + super::links::show_selected_image(h.state_mut(), &ctx); + h.state_mut().run("file.new", json!({"width": 400, "height": 300})).unwrap(); + h.run_steps(2); + assert!(shown(&h, "Nothing matches the Show filter."), "the other document keeps Show Missing"); + assert_eq!(h.state().ui.links.show, None, "the request is dropped"); } /// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the @@ -293,29 +229,30 @@ fn opening_the_panel_on_the_selected_image_leaves_another_document_alone() { #[test] fn frames_that_fetch_nothing_reuse_the_cached_rows() { let dir = Folder::new("cache"); - let (mut app, linked, _) = app(&dir); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let frame = |app: &mut VectorcraftApp, time: f64| { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - let text: Vec = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show).into_iter().map(|(t, _)| t).collect(); - (super::pstate::>(&ctx, "links-cache"), text) - }; - let (first, text) = frame(&mut app, 1.0); - assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); - let (same, text) = frame(&mut app, 1.5); - assert!(std::sync::Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new cache"); - assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); - let (rechecked, _) = frame(&mut app, 3.6); - assert!(!std::sync::Arc::ptr_eq(&same, &rechecked), "the files are looked at again after two seconds"); - app.run("select.set", json!({"ids": [linked]})).unwrap(); - let (picked, text) = frame(&mut app, 3.7); + let (app, linked, _) = app(&dir); + let mut h = rig(app); + let cache = |h: &Rig| std::sync::Arc::clone(&h.state().ui.links.cache); + let now = |h: &Rig| h.ctx.input(|i| i.time); + assert!(shown(&h, "linked.png") && shown(&h, "40 × 20 px")); + let first = cache(&h); + h.step(); + assert!(std::sync::Arc::ptr_eq(&first, &cache(&h)), "a frame that fetches nothing stores no new cache"); + assert!(shown(&h, "linked.png") && shown(&h, "40 × 20 px")); + let start = now(&h); + while now(&h) - start <= 2.1 { + h.step(); + } + let rechecked = cache(&h); + assert!(!std::sync::Arc::ptr_eq(&first, &rechecked), "the files are looked at again after two seconds"); + h.state_mut().run("select.set", json!({"ids": [linked]})).unwrap(); + h.step(); + let picked = cache(&h); assert!(!std::sync::Arc::ptr_eq(&rechecked, &picked), "Link Info follows the first selected image"); - assert!(text.iter().any(|t| t == "300 × 200 px"), "{text:?}"); - app.run("edit.clear", json!({"ids": [linked]})).unwrap(); - let (edited, text) = frame(&mut app, 3.8); - assert!(!std::sync::Arc::ptr_eq(&picked, &edited), "an edit lists the rows again"); - assert!(!text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "embedded.png"), "{text:?}"); + assert!(shown(&h, "300 × 200 px")); + h.state_mut().run("edit.clear", json!({"ids": [linked]})).unwrap(); + h.step(); + assert!(!std::sync::Arc::ptr_eq(&picked, &cache(&h)), "an edit lists the rows again"); + assert!(!shown(&h, "linked.png") && shown(&h, "embedded.png")); } /// Copy Info copies the file names of the selected links, or of `ids` in the order given, one per @@ -324,8 +261,6 @@ fn frames_that_fetch_nothing_reuse_the_cached_rows() { fn copy_info_copies_the_file_names_of_the_links() { let dir = Folder::new("copy-info"); let (mut app, linked, embedded) = app(&dir); - let menu = painted_text(&mut app, super::links::menu); - assert!(menu.contains("Copy Info"), "{menu}"); // The selection is the embedded image: its row's name. assert!(crate::menus::enabled(&app, "links.copyInfo")); let r = app.run("links.copyInfo", json!({})).unwrap(); @@ -354,41 +289,6 @@ fn copy_info_copies_the_file_names_of_the_links() { assert!(app.clipboard_out.is_none()); } -/// Shift-click selects the images of the rows from the last row clicked without Shift; Ctrl/Cmd-click -/// adds or removes one image, and Ctrl/Cmd-Shift-click adds the rows' images to the selection. -#[test] -fn shift_click_selects_a_range_of_links_and_ctrl_click_toggles_one() { - let dir = Folder::new("range"); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - for (i, name) in ["a.png", "b.png", "c.png", "d.png"].into_iter().enumerate() { - let path = dir.file(name, &png(20, 20)); - app.run("file.place", json!({"path": path, "at": [50 + 80 * i, 100]})).unwrap(); - } - let list = app.run("links.list", json!({})).unwrap(); - let rows: Vec<(String, u64)> = - list["links"].as_array().unwrap().iter().map(|r| (r["name"].as_str().unwrap().to_string(), r["id"].as_u64().unwrap())).collect(); - assert_eq!(rows.len(), 4, "{list}"); - let id = |rows_at: &[usize]| { - let mut ids: Vec = rows_at.iter().map(|&i| rows[i].1).collect(); - ids.sort_unstable(); - ids - }; - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - click_row(&mut app, &ctx, &rows[0].0, egui::Modifiers::NONE, 1.0); - assert_eq!(selected(&app), id(&[0])); - click_row(&mut app, &ctx, &rows[2].0, egui::Modifiers::SHIFT, 2.0); - assert_eq!(selected(&app), id(&[0, 1, 2]), "Shift-click selects the rows from the one clicked before"); - click_row(&mut app, &ctx, &rows[1].0, egui::Modifiers::COMMAND, 3.0); - assert_eq!(selected(&app), id(&[0, 2]), "Ctrl/Cmd-click removes one image"); - click_row(&mut app, &ctx, &rows[3].0, egui::Modifiers::SHIFT | egui::Modifiers::COMMAND, 4.0); - assert_eq!(selected(&app), id(&[0, 1, 2, 3]), "Ctrl/Cmd-Shift-click adds the rows from the one clicked before"); - click_row(&mut app, &ctx, &rows[0].0, egui::Modifiers::SHIFT, 5.0); - assert_eq!(selected(&app), id(&[0, 1]), "Shift-click replaces the selection with the rows"); - click_row(&mut app, &ctx, &rows[3].0, egui::Modifiers::NONE, 6.0); - assert_eq!(selected(&app), id(&[3])); -} /// A linked image kept only in a symbol's art has a row of its own: a click picks it in the panel /// (the canvas selection is cleared), Link Info shows it, Ctrl/Cmd-click adds an image in the @@ -408,37 +308,32 @@ fn a_link_inside_a_symbol_is_listed_and_picked_in_the_panel() { let list = app.run("links.list", json!({})).unwrap(); let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == "inside.png").unwrap_or_else(|| panic!("{list}")).clone(); assert_eq!(row["owner"]["kind"], "symbol", "{list}"); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let shown = |app: &mut VectorcraftApp, time: f64| -> Vec { - let raw = egui::RawInput { time: Some(time), ..Default::default() }; - super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show).into_iter().map(|(t, _)| t).collect() - }; - assert!(shown(&mut app, 0.5).iter().any(|t| t == "20 × 20 px"), "Link Info of the selected image in the layers"); - click_row(&mut app, &ctx, "inside.png", egui::Modifiers::NONE, 1.0); - assert!(selected(&app).is_empty(), "the canvas can't select it"); - assert!(shown(&mut app, 1.5).iter().any(|t| t == "30 × 20 px"), "Link Info of the symbol's image"); + let mut h = rig(app); + assert!(shown(&h, "20 × 20 px"), "Link Info of the selected image in the layers"); + click_row(&mut h, "inside.png", egui::Modifiers::NONE); + assert!(selected(h.state()).is_empty(), "the canvas can't select it"); + assert!(shown(&h, "30 × 20 px"), "Link Info of the symbol's image"); // Copy Info without ids copies the row picked in the panel. - app.ui_ctx = Some(ctx.clone()); - assert!(crate::menus::enabled(&app, "links.copyInfo")); - assert_eq!(app.run("links.copyInfo", json!({})).unwrap()["text"], "inside.png"); - assert_eq!(app.clipboard_out.take().as_deref(), Some("inside.png")); - click_row(&mut app, &ctx, "layer.png", egui::Modifiers::COMMAND, 2.0); - assert_eq!(selected(&app), [layer]); + assert!(crate::menus::enabled(h.state(), "links.copyInfo")); + assert_eq!(h.state_mut().run("links.copyInfo", json!({})).unwrap()["text"], "inside.png"); + assert_eq!(h.state_mut().clipboard_out.take().as_deref(), Some("inside.png")); + click_row(&mut h, "layer.png", egui::Modifiers::COMMAND); + assert_eq!(selected(h.state()), [layer]); // Both rows are selected until the canvas selection changes: then the panel's pick goes too. - click_row(&mut app, &ctx, "layer.png", egui::Modifiers::COMMAND, 3.0); - assert!(selected(&app).is_empty()); - assert!(shown(&mut app, 3.5).iter().any(|t| t == "30 × 20 px"), "the symbol's image is still picked"); - app.run("select.set", json!({"ids": [layer]})).unwrap(); - assert!(shown(&mut app, 4.0).iter().any(|t| t == "20 × 20 px")); - app.run("select.set", json!({"ids": []})).unwrap(); - let text = shown(&mut app, 4.5); - assert!(!text.iter().any(|t| t == "30 × 20 px" || t == "20 × 20 px"), "nothing is picked: {text:?}"); + click_row(&mut h, "layer.png", egui::Modifiers::COMMAND); + assert!(selected(h.state()).is_empty()); + assert!(shown(&h, "30 × 20 px"), "the symbol's image is still picked"); + h.state_mut().run("select.set", json!({"ids": [layer]})).unwrap(); + h.run_steps(2); + assert!(shown(&h, "20 × 20 px")); + h.state_mut().run("select.set", json!({"ids": []})).unwrap(); + h.run_steps(2); + assert!(!shown(&h, "30 × 20 px") && !shown(&h, "20 × 20 px"), "nothing is picked"); // Go To clears the selection and says the link has no place on the canvas. - app.run("select.set", json!({"ids": [layer]})).unwrap(); - super::links::go_to(&mut app, row["id"].as_u64().unwrap()); - assert_eq!(app.ui.status, "The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas"); - assert!(selected(&app).is_empty(), "the image in the layers is no longer selected"); + h.state_mut().run("select.set", json!({"ids": [layer]})).unwrap(); + super::links::go_to(h.state_mut(), row["id"].as_u64().unwrap()); + assert_eq!(h.state().ui.status, "The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas"); + assert!(selected(h.state()).is_empty(), "the image in the layers is no longer selected"); } /// The tooltip of a row outside the layer tree says where the image is stored, so two rows of the @@ -487,17 +382,11 @@ fn a_mask_rows_tooltip_names_its_object_inside_a_symbol() { let doc = app.session.active().unwrap().doc.clone(); assert!(doc.node(owner).is_none(), "the masked object is outside the layer tree"); let name = super::layers::shown_name(&app, doc.stored_node(owner).unwrap().0, crate::i18n::current()); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let frame = |app: &mut VectorcraftApp, events: Vec, time: f64| { - super::tests_appearance::frame_raw(&ctx, app, egui::RawInput { events, time: Some(time), ..Default::default() }, super::links::show) - }; - let at = super::tests_appearance::text_rect(&frame(&mut app, vec![], 1.0), "mask.png").center(); - frame(&mut app, vec![egui::Event::PointerMoved(at)], 2.0); - frame(&mut app, vec![], 4.0); - let text: Vec = frame(&mut app, vec![], 4.1).into_iter().map(|(t, _)| t).collect(); - let want = format!("Opacity Mask: {name}"); - assert!(text.iter().any(|t| t.contains(&want)), "{want} in {text:?}"); + let h = rig(app); + let found = h.state().ui.links.cache.nested_node(owner.0).map(|n| super::layers::shown_name(h.state(), n, crate::i18n::current())); + assert_eq!(found.as_deref(), Some(name.as_str()), "the panel collected the masked object with the list"); + let tip = super::links::status_tip(&row, found); + assert!(tip.contains(&format!("Opacity Mask: {name}")), "{tip}"); } /// The row of an image in a stored brush's art finds its object for the thumbnail, though that art @@ -522,12 +411,6 @@ fn a_row_in_a_stored_brushs_art_finds_its_object() { assert!(matches!(found[0].1.kind, vectorcraft_doc::NodeKind::Image(_)), "{:?}", found[0].1.kind); } -#[test] -fn an_empty_document_shows_how_to_add_images() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - assert!(panel(&mut app).contains("No images")); -} #[test] fn edit_original_and_show_in_folder_hand_the_file_to_the_system() { @@ -674,20 +557,19 @@ fn edit_original_opens_image_and_document_files_only() { #[test] fn placement_options_dialog_sets_the_options() { + use crate::tests::picks::{answer_dialog, open_dialogs}; let dir = Folder::new("dialog"); let (mut app, linked, _) = app(&dir); app.run("select.set", json!({"ids": [linked]})).unwrap(); assert!(crate::menus::enabled(&app, "ui.placementOptionsDialog")); app.run("ui.placementOptionsDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.str("preserve"), d.str("align")), ("placementOptions", "bounds".into(), "center".into())); - let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); - assert!(text.contains("Clip to Bounding Box") && text.contains("Preserve"), "{text}"); - let fields = &mut app.ui.dialog.as_mut().unwrap().fields; - fields.insert("preserve".into(), json!("fit")); - fields.insert("align".into(), json!("bottomRight")); - crate::dialogs::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + // PLAN: assumed `placement_options::ALIGN` names the reference points in the order of the + // dialog's `align` index (files-w22). + let align = crate::dialogs::placement_options::ALIGN.iter().position(|a| *a == "bottomRight").unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit")), ("align", json!(align))], true); + assert!(open_dialogs(&app).is_empty(), "OK closes the dialog"); let r = app.run("links.placementOptions", json!({"ids": [linked]})).unwrap(); assert_eq!(r["placement"], json!({"preserve": "fit", "align": "bottomRight", "clip": false})); } @@ -711,21 +593,25 @@ fn unembed_writes_several_images_to_one_picked_folder() { let (mut app, _, embedded) = app(&dir); let c = dir.file("other.png", &png(30, 10)); let other = app.run("file.place", json!({"path": c, "at": [50, 50], "link": false})).unwrap()["ids"][0].as_u64().unwrap(); + use crate::tests::picks::{poll, scripted}; assert!(super::links::can_unembed(&app, 1)); assert!(!super::links::can_unembed(&app, 0)); - assert!(!super::links::can_unembed(&app, 2), "no folder to pick"); let out = dir.0.join("out"); std::fs::create_dir_all(&out).unwrap(); - // No folder picked: nothing written or linked. - app.services.pick_folder = Some(Box::new(|| None)); + // PLAN: assumed `scripted` and `poll` of fl.A20 live in `crate::tests::picks`. + let picker = scripted(&mut app); + let ctx = egui::Context::default(); assert!(super::links::can_unembed(&app, 2)); + // No folder picked: nothing written or linked. super::links::unembed_several(&mut app, vec![embedded, other]); + picker.cancel(); + poll(&mut app, &ctx); assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0); assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["status"], "embedded"); let picked = out.to_string_lossy().into_owned(); - let answer = picked.clone(); - app.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); super::links::unembed_several(&mut app, vec![embedded, other]); + picker.answer(&[picked.as_str()]); + poll(&mut app, &ctx); for (id, name) in [(embedded, "embedded.png"), (other, "other.png")] { let info = app.run("links.info", json!({"id": id})).unwrap(); assert_eq!(info["path"], out.join(name).to_string_lossy().as_ref(), "{info}"); @@ -733,23 +619,8 @@ fn unembed_writes_several_images_to_one_picked_folder() { assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); } -#[test] -fn the_links_menu_items_run_commands() { - let tree = crate::menus::menu_tree(); - let ids = |label: &str| { - let (_, items) = tree.iter().find(|(t, _)| *t == label).unwrap(); - format!("{items:?}") - }; - assert!(ids("Edit").contains("links.editOriginal")); - assert!(ids("Window").contains(super::links::ID)); -} - #[test] fn right_click_context_menu_in_links_panel() { - use egui::vec2; - use egui_kittest::Harness; - use egui_kittest::kittest::{NodeT, Queryable}; - let dir = Folder::new("context-menu"); let (mut app, linked, embedded) = app(&dir); @@ -784,15 +655,15 @@ fn right_click_context_menu_in_links_panel() { right_click(&mut h, "linked.png"); assert_eq!(selected(h.state()), vec![linked], "right-clicking unselected row selects that row first"); - let relink = h.get_by_label(" Relink…"); - let go_to = h.get_by_label(" Go To Link"); - let update = h.get_by_label(" Update Link"); - let edit_orig = h.get_by_label(" Edit Original"); - let show_folder = h.get_by_label(" Show in Folder"); - let embed_img = h.get_by_label(" Embed Image"); + let relink = menu_item(&h, "Relink…"); + let go_to = menu_item(&h, "Go To Link"); + let update = menu_item(&h, "Update Link"); + let edit_orig = menu_item(&h, "Edit Original"); + let show_folder = menu_item(&h, "Show in Folder"); + let embed_img = menu_item(&h, "Embed Image"); - // "Relink…" is disabled because app has no pick_open service by default - assert!(relink.accesskit_node().is_disabled()); + // "Relink…" is enabled because the desktop can ask for a file + assert!(!relink.accesskit_node().is_disabled()); // "Go To Link" is enabled because linked node is in canvas document assert!(!go_to.accesskit_node().is_disabled()); // "Update Link" is disabled because linked file is not modified @@ -818,7 +689,7 @@ fn right_click_context_menu_in_links_panel() { assert_eq!(selected(h.state()), vec![linked, embedded], "right-clicking selected row preserves multi-selection"); // 4. Click "Go To Link" focuses the art on canvas via go_to - let go_to_btn = h.get_by_label(" Go To Link"); + let go_to_btn = menu_item(&h, "Go To Link"); assert!(!go_to_btn.accesskit_node().is_disabled()); go_to_btn.click(); h.run_steps(2); @@ -828,8 +699,8 @@ fn right_click_context_menu_in_links_panel() { // 5. Right-click embedded image: displays "Unembed…" while "Edit Original" and "Show in Folder" are disabled right_click(&mut h, "embedded.png"); assert_eq!(selected(h.state()), vec![embedded]); - let unembed_btn = h.get_by_label(" Unembed…"); + let unembed_btn = menu_item(&h, "Unembed…"); assert!(!unembed_btn.accesskit_node().is_disabled()); - assert!(h.get_by_label(" Edit Original").accesskit_node().is_disabled()); - assert!(h.get_by_label(" Show in Folder").accesskit_node().is_disabled()); + assert!(menu_item(&h, "Edit Original").accesskit_node().is_disabled()); + assert!(menu_item(&h, "Show in Folder").accesskit_node().is_disabled()); }