diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 5871d07126..cc00d06a3d 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -171,7 +171,7 @@ mod tests { (TYPE, &["editing"]), (&["puppetWarp"], &["pins", "selected"]), // With nothing queued, `current` (0) is no file's index either. - (&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]), + (&["place"], &["count", "total", "current", "sourceIndex", "name", "width", "height", "names"]), ]; let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); // Tools that `create` makes and the catalog doesn't list. diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 84f6ee1bad..454b1128ac 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -32,6 +32,8 @@ struct Entry { #[derive(Default)] pub struct PlaceTool { entries: Vec, + /// How many files the last load held, before any was placed or discarded. + total: usize, current: usize, /// The tool to return to when the last file is placed or discarded. prev: Option, @@ -67,6 +69,7 @@ impl PlaceTool { } if self.entries.is_empty() { self.current = 0; + self.total = 0; return vec![Action::SwitchTool(self.prev.clone().unwrap_or_else(|| "selection".into()))]; } self.current %= self.entries.len(); @@ -153,11 +156,13 @@ impl Tool for PlaceTool { Cursor::Crosshair } - /// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data). + /// `{count, total, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data); + /// `total` is how many files the load held. fn options(&self) -> Value { let e = self.entry(); json!({ "count": self.entries.len(), + "total": self.total, "current": self.current, "sourceIndex": e.map(|e| e.source_index), "name": e.map(|e| &e.name), @@ -187,6 +192,7 @@ impl Tool for PlaceTool { }) }) .collect(); + self.total = entries.len(); self.entries = entries; self.current = 0; self.drag = None; @@ -233,6 +239,7 @@ impl Tool for PlaceTool { /// Switching tools discards what the cursor holds. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.entries.clear(); + self.total = 0; self.drag = None; vec![] } @@ -399,6 +406,30 @@ mod tests { assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]); } + #[test] + fn the_total_is_the_size_of_the_load_until_the_cursor_empties() { + let (d, _) = doc_with_rect(); + let (s, p) = (Default::default(), paint()); + let c = cx(&d, &s, &p); + let counts = |t: &PlaceTool| (t.options()["count"].clone(), t.options()["total"].clone()); + let mut t = loaded(3); + assert_eq!(counts(&t), (json!(3), json!(3))); + t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); + t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); + assert_eq!(counts(&t), (json!(2), json!(3)), "a placed file leaves the total"); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(counts(&t), (json!(1), json!(3)), "a discarded file leaves the total"); + // A new load replaces the total, and an empty cursor has none. + let mut t = loaded(3); + t.set_option("queue", &json!({"entries": [{"params": {"path": "g.png"}, "name": "g.png", "width": 4.0, "height": 2.0}]})); + assert_eq!(counts(&t), (json!(1), json!(1))); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(counts(&t), (json!(0), json!(0))); + let mut t = loaded(2); + t.deactivate(&c); + assert_eq!(counts(&t), (json!(0), json!(0))); + } + #[test] fn source_indices_survive_removal_in_cursor_requests() { let (d, _) = doc_with_rect(); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index ef40ffefe4..5ac45da71d 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -25,8 +25,8 @@ const TIP: PartKey = PartKey::new("tip"); const CHIP: f32 = 5.0; const CHIP_RIM: f32 = 6.0; const CHIP_RING: f32 = 8.0; -/// Where the Selection tool's rule badge sits from the pointer, in points. -const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0); +/// Where the Selection tool's rule badge and the loaded place cursor's file sit from the pointer, in points. +pub(super) const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0); /// Shows `overlays` (the session's list, read after the tool host ran) over `extra` (the thread and gap overlays), /// on the canvas of `space`. The extras lie under the tool's own marks. diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index c7d13cc96c..4edaa65945 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -866,7 +866,8 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too response } -/// The session's overlays, then the text threads and Live Paint gaps under them, shown over the picture. +/// The session's overlays, then the text threads and Live Paint gaps under them, shown over the picture, and the +/// loaded place cursor's file over them. fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_info: ViewInfo) { let Some(space) = pass.space else { return }; let revolve = crate::dialogs::three_d::gizmo_shown(app); @@ -892,6 +893,18 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in } } super::overlays::show(app, ui, &space, &list, &extra); + // The loaded place cursor shows its current file and the files left beside the pointer, while the canvas has the + // pointer and no view tool is held. A press that began on the canvas keeps `hover_doc` while it is dragged off it, + // so the pointer must also be over the canvas. + if app.session.tool_id() == "place" + && app.ui.screen_mode < 3 + && app.hover_doc.is_some() + && !view_tool_held(app) + && let Some(at) = ui.input(|i| i.pointer.hover_pos()) + && space.view.rect.contains(at) + { + crate::place::cursor_overlay(app, ui, at, space.view.rect, super::overlays::BADGE_OFFSET); + } } /// Whether the canvas has a tool gesture in progress. Only the current window's body is live: panes and the other diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 4cf1bdb3d4..ce5b6672ea 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -111,6 +111,9 @@ pub struct PlaceState { /// [`ASKED`]), with the automation roots the cursor was loaded in: its OK, pressed outside any /// roots, places the file within them. Cleared when the cursor is loaded again. asked: Option<(u64, std::sync::Arc)>, + /// The size the loaded cursor's thumbnail and count took when last shown, which places them on the side of the + /// pointer where they fit ([`cursor_overlay`]). + cursor_size: Vec2, } /// The `file.place` param that ties an import options dialog's OK to the click of the place cursor @@ -838,35 +841,66 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) { .collect(); } -/// The loaded place cursor at `at` in the overlay layer `ui`: the current file's thumbnail with the -/// number of files loaded. A thumbnail is named by its place in the cursor's list, which -/// [`show_thumbnails`] replaces only together with a new load number. -pub fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos2) { +/// The loaded place cursor beside the pointer at `pointer`, `offset` from it, over `ui` (the canvas +/// `canvas`): the current file's thumbnail and, for a load of more than one file, the files left of +/// the load (`remaining/total`, `1/3` for the last of three). An empty cursor shows nothing. A +/// thumbnail is named by its place in the cursor's list, which [`show_thumbnails`] replaces only +/// together with a new load number. +pub(crate) fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, pointer: egui::Pos2, canvas: egui::Rect, offset: Vec2) { + let size = app.place.cursor_size; + let shown = show_cursor(app, ui, beside(pointer, offset, size, canvas)).unwrap_or(Vec2::ZERO); + // The first frame of a new size placed it by the old one. + if shown != size { + app.place.cursor_size = shown; + ui.ctx().request_repaint(); + } +} + +/// Where a box of `size` goes beside the pointer at `pointer` in `canvas`: `offset` below and to its +/// right, on an axis where that passes the canvas's edge `offset` above or to its left instead, and +/// inside the canvas where it fits on neither side. +fn beside(pointer: egui::Pos2, offset: Vec2, size: Vec2, canvas: egui::Rect) -> egui::Pos2 { + let axis = |at: f32, offset: f32, len: f32, min: f32, max: f32| { + let after = at + offset; + let start = if after + len > max { at - offset - len } else { after }; + start.min(max - len).max(min) + }; + egui::pos2(axis(pointer.x, offset.x, size.x, canvas.min.x, canvas.max.x), axis(pointer.y, offset.y, size.y, canvas.min.y, canvas.max.y)) +} + +/// [`cursor_overlay`]'s thumbnail and count with their top-left corner at `at`, and the size they +/// took; `None` for an empty cursor. +fn show_cursor(app: &VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos2) -> Option { let opts = app.session.tool_options(); let count = opts["count"].as_u64().unwrap_or(0); + if count == 0 { + return None; + } + let total = opts["total"].as_u64().unwrap_or(count).max(count); let name = opts["name"].as_str().unwrap_or_default(); let found = (app.place.queue_load == app.session.place_queue_loads()).then(|| app.place.cursor_thumbnail(&opts)).flatten(); let revision = Revision::new(app.place.queue_load); - let room = egui::Rect::from_min_max(at, ui.max_rect().max.max(at)); - ui.scope_builder(egui::UiBuilder::new().max_rect(room), |ui| { - match found { - Some((key, image)) => { - let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX); - let [w, h] = image.size; - Picture::new(name.to_string(), key as u64, &|| image.clone()) - .revision(revision) - .aspect(ThumbAspect::new(side(w), side(h))) - .extent(PictureSize::Thumb(ThumbSize::Medium)) - .show(ui); - } - None => { - Text::new(name.to_string()).shade(Shade::Muted).show(ui); - } + let room = egui::Rect::from_min_max(at, ui.clip_rect().max.max(at)); + // A child `Ui`: the overlay takes no room in the canvas's layout. + let ui = &mut ui.new_child(egui::UiBuilder::new().id_salt("place-cursor").max_rect(room)); + match found { + Some((key, image)) => { + let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX); + let [w, h] = image.size; + Picture::new(name.to_string(), key as u64, &|| image.clone()) + .revision(revision) + .aspect(ThumbAspect::new(side(w), side(h))) + .extent(PictureSize::Thumb(ThumbSize::Medium)) + .show(ui); } - if count > 1 { - Badge::count(u32::try_from(count).unwrap_or(u32::MAX)).show(ui); + None => { + Text::new(name.to_string()).shade(Shade::Muted).show(ui); } - }); + } + if total > 1 { + Badge::new(format!("{count}/{total}")).show(ui); + } + Some(ui.min_rect().size()) } // ---------- drops ---------- diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index ed1c1a3ae5..45bb099d8d 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -414,6 +414,97 @@ fn an_automated_place_queue_keeps_same_named_file_bytes_in_order() { } } +/// The loaded place cursor shows its current file's thumbnail beside the pointer on the canvas and, for a load of +/// several files, the files left of the load: `3/3`, `2/3` once one is placed, `1/3` once another is discarded. A load +/// of one file shows no count, and nothing shows off the canvas or once the cursor is empty. +#[test] +fn the_loaded_place_cursor_shows_its_file_and_the_files_left_beside_the_pointer() { + let mut app = app(); + let ctx = window(&app); + ctx.enable_accesskit(); + let canvas = laid_out(&mut app, &ctx); + let pointer = canvas.center(); + let load = |app: &mut VectorcraftApp, names: &[&str]| { + let data = vectorcraft_format::base64_encode(&png(8, 5, 72.0)); + let files: Vec = names.iter().map(|name| json!({"name": name, "dataBase64": data})).collect(); + app.run("file.place.queue", json!({"link": false, "files": files})).unwrap(); + }; + // The thumbnails named `name` and the counts (`n/m`) shown on the canvas in one frame with the pointer at `at`. + let shown = |app: &mut VectorcraftApp, at: Option, name: &str| -> (Vec, Vec<(String, egui::Rect)>) { + let event = at.map_or(egui::Event::PointerGone, egui::Event::PointerMoved); + let out = crate::testing::app_frame(app, &ctx, raw_input(vec![event], vec![], vec![])); + let nodes: Vec<(String, egui::accesskit::Role, egui::Rect)> = out + .platform_output + .accesskit_update + .iter() + .flat_map(|u| u.nodes.iter()) + .filter_map(|(_, n)| { + let b = n.bounds()?; + let rect = egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)); + let label = n.label()?.to_string(); + canvas.intersects(rect).then_some((label, n.role(), rect)) + }) + .collect(); + let thumbs = nodes.iter().filter(|(l, role, _)| l == name && *role == egui::accesskit::Role::Image).map(|n| n.2).collect(); + let is_count = + |l: &str| l.split_once('/').is_some_and(|(a, b)| [a, b].iter().all(|s| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit()))); + let counts = nodes.into_iter().filter(|(l, ..)| is_count(l)).map(|(l, _, r)| (l, r)).collect(); + (thumbs, counts) + }; + // Beside the pointer: below and to the right of it, inside the canvas, the count under the thumbnail. + let beside = |thumbs: &[egui::Rect], counts: &[(String, egui::Rect)], want: Option<&str>| { + assert_eq!(thumbs.len(), 1, "one thumbnail: {thumbs:?}"); + let thumb = thumbs[0]; + assert!(thumb.min.x >= pointer.x && thumb.min.y >= pointer.y && canvas.contains_rect(thumb), "{thumb:?} beside {pointer:?} in {canvas:?}"); + match want { + Some(want) => { + assert_eq!(counts.iter().map(|c| c.0.as_str()).collect::>(), [want]); + let count = counts[0].1; + assert!(count.min.y >= thumb.max.y && canvas.contains_rect(count), "{count:?} under {thumb:?}"); + } + None => assert!(counts.is_empty(), "{counts:?}"), + } + }; + + load(&mut app, &["first.png", "second.png", "third.png"]); + let (thumbs, counts) = shown(&mut app, Some(pointer), "first.png"); + beside(&thumbs, &counts, Some("3/3")); + // At the canvas's bottom-right corner they go above and to the left of the pointer, inside the canvas. + let corner = canvas.max - vec2(1.0, 1.0); + let (thumbs, counts) = shown(&mut app, Some(corner), "first.png"); + assert_eq!((thumbs.len(), counts.len()), (1, 1), "{thumbs:?} {counts:?}"); + let both = thumbs[0].union(counts[0].1); + assert!(canvas.contains_rect(both) && both.max.x < corner.x && both.max.y < corner.y, "{both:?} beside {corner:?} in {canvas:?}"); + // Off the canvas the cursor shows nothing. + let (thumbs, counts) = shown(&mut app, None, "first.png"); + assert!(thumbs.is_empty() && counts.is_empty(), "{thumbs:?} {counts:?}"); + click(&mut app); + let (thumbs, counts) = shown(&mut app, Some(pointer), "second.png"); + beside(&thumbs, &counts, Some("2/3")); + tool_key(&mut app, vectorcraft_tools::ToolKey::Escape); + let (thumbs, counts) = shown(&mut app, Some(pointer), "third.png"); + beside(&thumbs, &counts, Some("1/3")); + click(&mut app); + assert_ne!(app.session.tool_id(), "place", "the last file placed ends the cursor"); + let (thumbs, counts) = shown(&mut app, Some(pointer), "third.png"); + assert!(thumbs.is_empty() && counts.is_empty(), "{thumbs:?} {counts:?}"); + + // One file: its thumbnail, no count. + load(&mut app, &["only.png"]); + let (thumbs, counts) = shown(&mut app, Some(pointer), "only.png"); + beside(&thumbs, &counts, None); + + // A press on the canvas dragged across it keeps the thumbnail, and dragged off the canvas shows nothing. + let press = egui::Event::PointerButton { pos: pointer, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }; + crate::testing::app_frame(&mut app, &ctx, raw_input(vec![egui::Event::PointerMoved(pointer), press], vec![], vec![])); + let (thumbs, _) = shown(&mut app, Some(pointer + vec2(10.0, 10.0)), "only.png"); + assert_eq!(thumbs.len(), 1, "dragged on the canvas: {thumbs:?}"); + let outside = egui::pos2(pointer.x, canvas.min.y - 4.0); + assert!(outside.y > 0.0, "{canvas:?} leaves room above it"); + let (thumbs, counts) = shown(&mut app, Some(outside), "only.png"); + assert!(thumbs.is_empty() && counts.is_empty(), "dragged off the canvas: {thumbs:?} {counts:?}"); +} + /// A tiny SVG document. const SVG: &str = r#""#; diff --git a/docs/mcp.md b/docs/mcp.md index 718c5c367c..d1ab78340f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12026,7 +12026,8 @@ Placement does not trim composite font or character set names as `type.composite effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and `press_key` (Left/Right/Up/Down cycle, Escape discards the current file). The place tool's state includes a -read-only `sourceIndex`: the current file's zero-based position in the original load, or null when empty. +read-only `sourceIndex`: the current file's zero-based position in the original load, or null when empty, and a +read-only `total`: how many files the load held (0 when empty), which the app's cursor shows as `count/total`. It stays with that file when other files are placed or discarded; `current` indexes the remaining files. In the app, same-named files also keep their own queued size and password requirement. Choosing another PDF page after a cursor click places that page at its own size; a drag keeps the chosen box.