diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 7086c7f92e..94da32aa01 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -1224,9 +1224,16 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to let reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view).unwrap(); let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") }; assert_eq!(p["rect"], json!([10.0, 10.0, 40.0, 20.0])); + assert_eq!(p[vectorcraft_tools::place::SOURCE_INDEX], 0); + assert_eq!(p[vectorcraft_tools::place::CLICK], true); assert!(top_children(&s).is_empty(), "the frontend places it"); assert_eq!(s.tool_options()["names"], json!(["b.png"]), "the cursor goes on to the next file"); - s.execute("file.place", p).unwrap(); + // The frontend consumes the private source identity before placing the file. + let mut p = p.clone(); + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + p.as_object_mut().unwrap().remove(key); + } + s.execute("file.place", &p).unwrap(); // Left out: the second each document was made in. let doc = |s: &Session| { let mut d = (*s.doc().unwrap().doc).clone(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f417bcaf03..bc9e2aa0c6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1918,7 +1918,12 @@ impl Session { // The place cursor's file, placed by the frontend that asked for it. Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)), // The place cursor's file, read within the roots of whoever loaded the cursor. - Action::Exec(cmd, p) if cmd == "file.place" => { + Action::Exec(cmd, mut p) if cmd == "file.place" => { + if let Some(params) = p.as_object_mut() { + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + params.remove(key); + } + } let roots = self.place_queue_roots.clone(); if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) { ui.push(UiRequest::Status(w.to_string())); diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index dd26fa28f0..5871d07126 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", "name", "width", "height", "names"]), + (&["place"], &["count", "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 813ec99429..84f6ee1bad 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -9,9 +9,18 @@ use vectorcraft_geom::{Point, Rect}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +/// Private cursor metadata: the original queue entry for a placement request. The frontend +/// consumes it before opening import options; the engine removes it before direct placement. +pub const SOURCE_INDEX: &str = "__placeSourceIndex"; + +/// Whether a cursor placement was a click under the pointer tolerance, rather than a drag. +pub const CLICK: &str = "__placeCursorClick"; + /// One loaded file. #[derive(Clone, Debug, PartialEq)] struct Entry { + /// Its position in the original load, retained when other entries are discarded. + source_index: usize, /// `file.place` params (the file and its options). params: Value, name: String, @@ -93,9 +102,12 @@ impl Tool for PlaceTool { let Some((a, _)) = self.drag.take() else { return vec![] }; let (Some(r), Some(e)) = (self.target(a, ev.pos, cx.tol(3.0)), self.entry()) else { return vec![] }; let mut p = e.params.clone(); + p[SOURCE_INDEX] = json!(e.source_index); + let clicked = (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0); + p[CLICK] = json!(clicked); p["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); // A Shift-click (not a drag) asks for the file's import options before placing it. - if ev.mods.shift && (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0) { + if ev.mods.shift && clicked { p["showImportOptions"] = json!(true); } let mut acts = vec![Action::Exec("file.place".into(), p)]; @@ -141,12 +153,13 @@ impl Tool for PlaceTool { Cursor::Crosshair } - /// `{count, current, name, width, height, names}`: what the cursor holds (no file data). + /// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data). fn options(&self) -> Value { let e = self.entry(); json!({ "count": self.entries.len(), "current": self.current, + "sourceIndex": e.map(|e| e.source_index), "name": e.map(|e| &e.name), "width": e.map(|e| e.width), "height": e.map(|e| e.height), @@ -163,8 +176,10 @@ impl Tool for PlaceTool { .as_array() .into_iter() .flatten() - .filter_map(|e| { + .enumerate() + .filter_map(|(source_index, e)| { Some(Entry { + source_index, params: e.get("params").filter(|p| p.is_object())?.clone(), name: e["name"].as_str().unwrap_or_default().to_string(), width: e["width"].as_f64().filter(|v| v.is_finite())?, @@ -277,14 +292,26 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0)); - assert_eq!(acts, vec![Action::Exec("file.place".into(), json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0]}))]); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0]}) + )] + ); // A drag up and to the left grows the box from the press point, aspect kept. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0)); let c_marquee_only = ToolContext { measurement_labels: false, ..c }; assert_eq!(t.overlays(&c_marquee_only), vec![Overlay::Marquee(Rect::new(20.0, 60.0, 100.0, 100.0))]); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); assert_eq!(t.options()["count"], 1); // Placing the last file returns to the previous tool. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); @@ -302,18 +329,30 @@ mod tests { let mut t = loaded(3); t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0).with_mods(shift)); - let asked = json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); + let asked = json!({"path": "f0.png", "__placeSourceIndex": 0, "__placeCursorClick": true, "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true}); assert_eq!(acts, vec![Action::Exec("file.place".into(), asked)]); assert_eq!(t.options()["names"], json!(["f1.png", "f2.png"]), "the cursor goes on to the next file"); // A Shift-drag places at the dragged size, as a drag does. t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0).with_mods(shift)); t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0).with_mods(shift)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f1.png", "__placeSourceIndex": 1, "__placeCursorClick": false, "rect": [20.0, 60.0, 80.0, 40.0]}) + ) + ); // Shift released before the button: a plain click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); - assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f2.png", "rect": [0.0, 0.0, 40.0, 20.0]}))); + assert_eq!( + acts[0], + Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + ) + ); assert_eq!(acts.last(), Some(&Action::SwitchTool("pen".into()))); // An empty cursor places nothing on a Shift-click. t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift)); @@ -359,4 +398,29 @@ mod tests { t.key(&c, ToolKey::Escape, Mods::default()); assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]); } + + #[test] + fn source_indices_survive_removal_in_cursor_requests() { + let (d, _) = doc_with_rect(); + let (s, p) = (Default::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = loaded(3); + t.key(&c, ToolKey::Right, Mods::default()); + assert_eq!(t.options()["sourceIndex"], 1); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!((t.options()["current"].clone(), t.options()["sourceIndex"].clone()), (json!(1), json!(2))); + t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); + let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); + assert_eq!( + acts, + vec![Action::Exec( + "file.place".into(), + json!({"path": "f2.png", "__placeSourceIndex": 2, "__placeCursorClick": true, "rect": [0.0, 0.0, 40.0, 20.0]}) + )] + ); + assert_eq!(t.options()["sourceIndex"], 0); + assert!(t.check_option("sourceIndex", &json!(0)).is_err(), "the source identity is read only"); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(t.options()["sourceIndex"], Value::Null); + } } diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 7a42d96f9f..62ce0b2e58 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -358,12 +358,21 @@ fn a_pick_places_with_the_importer_and_params_given() { let picker = scripted(&mut app); let ctx = crate::testing::ui_context(); let with = json!({"importer": "plugin.test.ui.placepick", "params": {"density": 7}, "showImportOptions": false}); + let picked_files = |app: &VectorcraftApp| { + let mut files = fields(app)["files"].clone(); + for file in files.as_array_mut().unwrap() { + let source = file.as_object_mut().unwrap().remove("__pickedSource").expect("browser files keep their source identity"); + let token = source.as_str().unwrap(); + assert!(app.place.picked.iter().any(|(key, bytes)| key == token && bytes == b"?")); + } + files + }; // The web: the picker answers with the files' contents. app.run("file.place", with.clone()).unwrap(); picker.answer_contents(&[("a.svg", b"?")]); poll(&mut app, &ctx); - assert_eq!(fields(&app)["files"], json!([{"name": "a.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + assert_eq!(picked_files(&app), json!([{"name": "a.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); let steps = app.session.active().unwrap().history.undo.len(); try_confirm(&mut app).unwrap(); assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status); @@ -383,7 +392,7 @@ fn a_pick_places_with_the_importer_and_params_given() { app.run("file.place", json!({})).unwrap(); picker.answer_contents(&[("c.svg", b"?")]); poll(&mut app, &ctx); - assert_eq!(fields(&app)["files"], json!([{"name": "c.svg"}])); + assert_eq!(picked_files(&app), json!([{"name": "c.svg"}])); cancel(&mut app); // Two picks open at once: each one's files keep that pick's importer and parameters, also when @@ -392,11 +401,11 @@ fn a_pick_places_with_the_importer_and_params_given() { app.run("file.place", json!({})).unwrap(); picker.answer_contents(&[("e.svg", b"?")]); poll(&mut app, &ctx); - assert_eq!(fields(&app)["files"], json!([{"name": "e.svg"}])); + assert_eq!(picked_files(&app), json!([{"name": "e.svg"}])); cancel(&mut app); picker.answer_contents(&[("d.svg", b"?")]); poll(&mut app, &ctx); - assert_eq!(fields(&app)["files"], json!([{"name": "d.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + assert_eq!(picked_files(&app), json!([{"name": "d.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); try_confirm(&mut app).unwrap(); assert_eq!(placed_group(&app).as_deref(), Some("d.svg"), "{}", app.ui.status); diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 97d17b6810..3ee2b402dc 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -87,9 +87,9 @@ pub fn is_document(name: &str) -> bool { /// The app's Place state (not saved with the preferences). #[derive(Default)] pub struct PlaceState { - /// Web: the bytes of the files picked for the Place dialog, by name. + /// Web: the bytes of the files picked for the Place dialog, by selection token. pub(crate) picked: Vec<(String, Vec)>, - /// The loaded cursor's thumbnails by file name. + /// The loaded cursor's thumbnails by original queue entry, with names for display. thumbs: Vec<(String, Thumb)>, /// The Control bar's `image.info`, for (document uid, revision, image id). info: Option<((u64, u64, u64), Value)>, @@ -99,10 +99,10 @@ pub struct PlaceState { /// The files of the loaded place cursor ask for their import options when clicked or dragged /// (the Place dialog loaded it with Show Import Options on). queue_asks: bool, - /// The loaded cursor's files by name, with the size a click places them at. - queue_sizes: Vec<(String, f64, f64)>, - /// The names of the loaded cursor's encrypted PDF files, which ask for their password. - queue_locked: Vec, + /// The size a click places each original queue entry at, including entries without a size. + queue_sizes: Vec>, + /// Whether each original queue entry is an encrypted PDF, which asks for its password. + queue_locked: Vec, /// The engine's count of cursor loads ([`vectorcraft_engine::Session::place_queue_loads`]) when /// `queue_asks`, `queue_sizes` and `queue_locked` were set: a later load (`tool.setOption`, a /// script) clears them. @@ -142,6 +142,7 @@ const SET_ASIDE: &str = "__placeCursorOptions"; /// A place cursor thumbnail, decoded when the cursor is loaded. struct Thumb { + source_index: usize, image: std::sync::Arc, } @@ -177,6 +178,13 @@ impl PlaceState { pub(crate) fn thumbnails(&self) -> Vec<&str> { self.thumbs.iter().map(|(n, _)| n.as_str()).collect() } + + /// The current entry's thumbnail, even after earlier entries with the same name are removed. + pub(crate) fn cursor_thumbnail(&self, options: &Value) -> Option<(usize, &egui::ColorImage)> { + let source_index = usize::try_from(options["sourceIndex"].as_u64()?).ok()?; + let (_, thumb) = self.thumbs.iter().find(|(_, thumb)| thumb.source_index == source_index)?; + Some((source_index, thumb.image.as_ref())) + } } /// Run engine command `id` itself (past the UI's handling of the same id); an error shows in the @@ -348,14 +356,15 @@ fn pick(app: &mut VectorcraftApp, p: &Value) -> Value { paths.into_iter().map(|path| with_importer(json!({ "path": path.to_string_lossy() }), &with)).collect() } Picked::Contents(files) => { - // The next Place dialog replaces the previous selection, including its source bytes. + // A replacement selection owns a new set of source bytes. app.place.picked.clear(); files .into_iter() .map(|(name, bytes)| { - app.place.picked.retain(|(n, _)| *n != name); - let entry = with_importer(json!({ "name": name }), &with); - app.place.picked.push((name, bytes)); + static SOURCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let source = SOURCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed).to_string(); + let entry = with_importer(json!({ "name": name, "__pickedSource": source }), &with); + app.place.picked.push((source, bytes)); entry }) .collect() @@ -478,7 +487,9 @@ fn source(app: &VectorcraftApp, file: &Value) -> Option { return Some(with_importer(json!({ "path": path }), file)); } let name = file.get("name").and_then(Value::as_str)?; - let bytes = app.place.picked.iter().find(|(n, _)| n == name).map(|(_, b)| b)?; + // The selection token is UI bookkeeping; only the original name and bytes reach the engine. + let source = file.get("__pickedSource").and_then(Value::as_str).unwrap_or(name); + let bytes = app.place.picked.iter().find(|(n, _)| n == source).map(|(_, b)| b)?; Some(with_importer(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), file)) } @@ -665,12 +676,18 @@ pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) { // at the keyboard: an agent's queue reaches no file it wasn't given. let roots = app.session.place_queue_roots(); forget_older_queue(app); + let locked = is_locked(app, p); + // A Shift-click asks for the file's import options whatever the cursor was loaded with. + let shift_click = p.get("showImportOptions") == Some(&Value::Bool(true)); + let ask = app.place.queue_asks || locked || shift_click; + let mut p = if ask { clicked_at_full_size(app, p) } else { p.clone() }; + if let Some(params) = p.as_object_mut() { + for key in [vectorcraft_tools::place::SOURCE_INDEX, vectorcraft_tools::place::CLICK] { + params.remove(key); + } + } vectorcraft_engine::file_access::confine(roots.as_ref(), || { - let locked = is_locked(app, p); - // A Shift-click asks for the file's import options whatever the cursor was loaded with. - let shift_click = p.get("showImportOptions") == Some(&Value::Bool(true)); - if app.place.queue_asks || locked || shift_click { - let mut p = clicked_at_full_size(app, p); + if ask { if shift_click { set_aside_import_options(&mut p); } else if !app.place.queue_asks { @@ -689,7 +706,6 @@ pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) { let _ = place_file(app, &p, Read::ForUser { dropped: false }); } else { // An embedded PDF takes the `pdfTextAs` preference, as one placed from the Place dialog. - let mut p = p.clone(); crate::dialogs::import_pdf::place_with_preferred_text_as(app, &mut p); if crate::placing::available(app) { if let Err(e) = crate::placing::start(app, &p, false) { @@ -735,27 +751,34 @@ fn forget_older_queue(app: &mut VectorcraftApp) { /// Does `p` (a cursor click's `file.place` params) name a file the cursor holds as an encrypted PDF? fn is_locked(app: &VectorcraftApp, p: &Value) -> bool { - let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name); - name.is_some_and(|n| app.place.queue_locked.contains(&n)) + source_index(p).and_then(|index| app.place.queue_locked.get(index)).copied().unwrap_or(false) +} + +fn source_index(p: &Value) -> Option { + usize::try_from(p.get(vectorcraft_tools::place::SOURCE_INDEX)?.as_u64()?).ok() } /// The params of a cursor click (`rect` at the file's queued size) on a PDF or DXF file, whose /// import options may change its size (another page, another scale): placed as its options place /// it at the click (`at`, the center of the box the click gave), as File › Place of that one file -/// places it, instead of fitted into the box of the first page or the default scale. A drag keeps -/// its `rect`; one to exactly the queued size gives the same `rect` as a click, and is taken as one. +/// places it, instead of fitted into the box of the first page or the default scale. The cursor +/// marks clicks explicitly: a deliberate drag keeps its `rect`, even at exactly the queued size. fn clicked_at_full_size(app: &VectorcraftApp, p: &Value) -> Value { let mut p = p.clone(); + if p.get(vectorcraft_tools::place::CLICK) != Some(&Value::Bool(true)) { + return p; + } let Some(name) = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name) else { return p }; if !matches!(fileio::extension(&name).as_str(), "pdf" | "ai" | "ait" | "dxf") { return p; } let r: Vec = p.get("rect").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); let [x, y, w, h] = r[..] else { return p }; - // Files of the same name in the cursor must all have that size: the place tool's request names - // the file, not its place in the cursor. - let mut same_name = app.place.queue_sizes.iter().filter(|(n, ..)| *n == name).peekable(); - let queued = same_name.peek().is_some() && same_name.all(|(_, qw, qh)| (qw - w).abs() < 1e-6 && (qh - h).abs() < 1e-6); + let queued = source_index(&p) + .and_then(|index| app.place.queue_sizes.get(index)) + .copied() + .flatten() + .is_some_and(|(qw, qh)| (qw - w).abs() < 1e-6 && (qh - h).abs() < 1e-6); if queued && let Some(o) = p.as_object_mut() { o.remove("rect"); o.insert("at".into(), json!([x + w / 2.0, y + h / 2.0])); @@ -769,28 +792,18 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) { app.place.queue_load = app.session.place_queue_loads(); app.place.queue_asks = asks; app.place.asked = None; - app.place.queue_sizes = r["files"] - .as_array() - .into_iter() - .flatten() - .filter_map(|f| Some((f["name"].as_str()?.to_string(), f["width"].as_f64()?, f["height"].as_f64()?))) - .collect(); - app.place.queue_locked = r["files"] - .as_array() - .into_iter() - .flatten() - .filter(|f| f["needsPassword"] == true) - .filter_map(|f| Some(f["name"].as_str()?.to_string())) - .collect(); + app.place.queue_sizes = r["files"].as_array().into_iter().flatten().map(|f| Some((f["width"].as_f64()?, f["height"].as_f64()?))).collect(); + app.place.queue_locked = r["files"].as_array().into_iter().flatten().map(|f| f["needsPassword"] == true).collect(); app.place.thumbs = r["files"] .as_array() .into_iter() .flatten() - .filter_map(|f| { + .enumerate() + .filter_map(|(source_index, f)| { let png = vectorcraft_format::base64_decode(f["thumbnailBase64"].as_str()?)?; let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png).ok()?; let color = egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &img.to_rgba8()); - Some((f["name"].as_str()?.to_string(), Thumb { image: std::sync::Arc::new(color) })) + Some((f["name"].as_str()?.to_string(), Thumb { source_index, image: std::sync::Arc::new(color) })) }) .collect(); } @@ -802,15 +815,15 @@ pub fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos let opts = app.session.tool_options(); let count = opts["count"].as_u64().unwrap_or(0); let name = opts["name"].as_str().unwrap_or_default(); - let found = app.place.thumbs.iter().enumerate().find(|(_, (n, _))| n == name); + 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, (_, thumb))) => { + Some((key, image)) => { let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX); - let [w, h] = thumb.image.size; - Picture::new(name.to_string(), key as u64, &|| (*thumb.image).clone()) + 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)) @@ -1285,3 +1298,21 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool } true } + +#[cfg(test)] +mod source_identity_tests { + use super::*; + + #[test] + fn same_named_pdf_sources_keep_independent_password_requirements() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let pages = [PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f")]; + let files = + [None, Some("pw")].map(|password| json!({"name": "same.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf(&pages, password))})); + app.run("file.new", json!({})).unwrap(); + app.run("file.place.queue", json!({"files": files, "link": false})).unwrap(); + assert!(!is_locked(&app, &json!({"name": "same.pdf", "__placeSourceIndex": 0}))); + assert!(is_locked(&app, &json!({"name": "same.pdf", "__placeSourceIndex": 1}))); + } +} diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 55612417c1..ed1c1a3ae5 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -134,11 +134,12 @@ fn cancelling_browser_place_releases_the_picked_file_buffers() { crate::file_asks::poll(&mut app); assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); assert_eq!(app.place.picked.len(), 1); + let source = app.place.picked[0].0.clone(); // Cancelling a replacement file picker leaves the existing Place selection usable. app.run("file.place", json!({})).unwrap(); picker.cancel(); crate::file_asks::poll(&mut app); - assert_eq!(app.place.picked[0].0, name); + assert_eq!(app.place.picked[0].0, source); dismiss(&mut app); crate::place::pump(&mut app, &ctx); assert!(app.place.picked.is_empty(), "a cancelled Place selection no longer owns file bytes"); @@ -210,7 +211,7 @@ fn an_old_place_ok_cannot_consume_a_newer_dialogs_browser_bytes() { assert_eq!(app.ui.status, "new selection", "the retired OK reports no stale error"); assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); assert_eq!(app.place.picked.len(), 1); - assert_eq!(app.place.picked[0].0, "new.png"); + assert_eq!(app.place.picked[0].1.as_slice(), bytes.as_slice()); assert!(app.session.active().unwrap().doc.layers[0].children().unwrap().is_empty()); answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); assert!(app.place.picked.is_empty()); @@ -234,7 +235,7 @@ fn an_old_place_cancellation_keeps_a_newer_dialogs_browser_bytes() { crate::place::pump(&mut app, &ctx); assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); assert_eq!(app.place.picked.len(), 1, "the replacement owns only its own source bytes"); - assert_eq!(app.place.picked[0].0, "new.png"); + assert_eq!(app.place.picked[0].1.as_slice(), bytes.as_slice()); answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); assert!(app.place.picked.is_empty(), "confirmation transfers the bytes out of the dialog cache"); assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1, "the newer file still places"); @@ -323,6 +324,96 @@ fn selected_image(app: &VectorcraftApp) -> vectorcraft_doc::Node { n } +/// Browser file names are labels, not unique source identities. Both the bytes and the cursor +/// thumbnail must follow each selection through cycling, placement and discarding another file. +#[test] +fn browser_place_keeps_same_named_files_and_their_cursor_thumbnails_distinct() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let (a, b) = (png(8, 5, 72.0), png(3, 2, 72.0)); + let load = |app: &mut VectorcraftApp| { + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.png", &a), ("same.png", &b)]); + poll(app, &ctx); + assert_eq!( + fields(app)["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect::>(), + ["same.png", "same.png"] + ); + answer(app, &[("link", json!(false)), ("showImportOptions", json!(false))]); + assert_eq!(app.session.tool_options()["count"], 2); + }; + let thumbnail = |app: &VectorcraftApp| { + let options = app.session.tool_options(); + let (source, image) = app.place.cursor_thumbnail(&options).expect("the selected entry has its own thumbnail"); + (source, image.size) + }; + let placed = |app: &VectorcraftApp, size| { + let node = selected_image(app); + assert_eq!(node.name.as_deref(), Some("same.png")); + let NodeKind::Image(image) = node.kind else { panic!("Place selects the raster just placed") }; + assert_eq!((image.width, image.height), size); + }; + load(&mut app); + let first = thumbnail(&app); + tool_key(&mut app, vectorcraft_tools::ToolKey::Right); + let second = thumbnail(&app); + assert_eq!((first.0, second.0), (0, 1)); + assert_ne!(first.1, second.1, "the distinct image proportions have distinct thumbnails"); + tool_key(&mut app, vectorcraft_tools::ToolKey::Left); + click(&mut app); + placed(&app, (8, 5)); + assert_eq!(thumbnail(&app), second, "removing the first entry must not shift the thumbnail identity"); + click(&mut app); + placed(&app, (3, 2)); + + load(&mut app); + tool_key(&mut app, vectorcraft_tools::ToolKey::Escape); + assert_eq!(thumbnail(&app), second, "discarding the first entry preserves the second thumbnail"); + click(&mut app); + placed(&app, (3, 2)); +} + +/// Each browser selection places its own bytes, in selection order, with its original name. +#[test] +fn browser_place_keeps_same_named_file_bytes_in_order() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let (a, b) = (png(8, 5, 72.0), png(3, 2, 72.0)); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.png", &a), ("same.png", &b)]); + poll(&mut app, &ctx); + answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); + for size in [(8, 5), (3, 2)] { + click(&mut app); + let node = selected_image(&app); + assert_eq!(node.name.as_deref(), Some("same.png")); + let NodeKind::Image(image) = node.kind else { panic!("Place selects the raster just placed") }; + assert_eq!((image.width, image.height), size); + } +} + +/// Automation already supplies each file's bytes directly; the same names retain their order too. +#[test] +fn an_automated_place_queue_keeps_same_named_file_bytes_in_order() { + let mut app = app(); + let (a, b) = (png(8, 5, 72.0), png(3, 2, 72.0)); + app.run( + "file.place.queue", + json!({"link": false, "files": [ + {"name": "same.png", "dataBase64": vectorcraft_format::base64_encode(&a)}, + {"name": "same.png", "dataBase64": vectorcraft_format::base64_encode(&b)} + ]}), + ) + .unwrap(); + for size in [(8, 5), (3, 2)] { + click(&mut app); + let NodeKind::Image(image) = selected_image(&app).kind else { panic!("Place selects the raster just placed") }; + assert_eq!((image.width, image.height), size); + } +} + /// A tiny SVG document. const SVG: &str = r#""#; @@ -1233,6 +1324,71 @@ fn two_pages() -> [PdfPage; 2] { [PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), PdfPage::new(300.0, 100.0, "1 0 0 rg 0 0 30 30 re f")] } +/// Same-named PDFs keep their own click size when their page options change it. +#[test] +fn browser_place_same_named_pdfs_keep_each_click_at_full_size() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let first = pdf(&two_pages(), None); + let second = pdf(&[PdfPage::new(200.0, 100.0, "0 g 0 0 20 10 re f"), PdfPage::new(400.0, 100.0, "0 g 0 0 40 10 re f")], None); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.pdf", &first), ("same.pdf", &second)]); + poll(&mut app, &ctx); + answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(true))]); + for (width, center) in [(300.0, 60.0), (400.0, 110.0)] { + click(&mut app); + assert_eq!(dialog_kind(&app).as_deref(), Some(PDF_IMPORT)); + answer(&mut app, &[("page", json!(2))]); + let st = app.session.active().unwrap(); + let bounds = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap(); + assert_eq!((bounds.width().round(), bounds.center()), (width, vectorcraft_geom::Point::new(center, 60.0))); + } +} + +/// A deliberate drag keeps its box even when it equals that source's queued dimensions. +#[test] +fn browser_place_same_named_pdfs_keep_an_exact_size_drag_box() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let first = pdf(&two_pages(), None); + let second = pdf(&[PdfPage::new(200.0, 100.0, "0 g 0 0 20 10 re f"), PdfPage::new(400.0, 100.0, "0 g 0 0 40 10 re f")], None); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.pdf", &first), ("same.pdf", &second)]); + poll(&mut app, &ctx); + answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(true))]); + cursor_gesture(&mut app, vectorcraft_tools::Mods::default(), (110.0, 110.0)); + assert_eq!(dialog_kind(&app).as_deref(), Some(PDF_IMPORT)); + answer(&mut app, &[("page", json!(2))]); + let st = app.session.active().unwrap(); + let bounds = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap(); + assert_eq!((bounds.width().round(), bounds.center()), (100.0, vectorcraft_geom::Point::new(60.0, 60.0))); +} + +/// A locked PDF must not make a same-named unlocked PDF discard its deliberate drag size. +#[test] +fn browser_place_same_named_pdfs_keep_password_checks_separate() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let first = pdf(&two_pages(), None); + let locked = pdf(&two_pages(), Some("pw")); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.pdf", &first), ("same.pdf", &locked)]); + poll(&mut app, &ctx); + answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); + // The unlocked file's 100-by-100 drag is deliberate. It is not the locked file's click. + cursor_gesture(&mut app, vectorcraft_tools::Mods::default(), (110.0, 110.0)); + assert_eq!(dialog_kind(&app), None); + assert_eq!(selected_width(&app).round(), 100.0); + click(&mut app); + assert!(dialog_kind(&app).is_some(), "the other source still asks for its password"); + answer(&mut app, &[("password", json!("pw"))]); + assert_eq!(dialog_kind(&app), None); + assert_eq!(selected_width(&app).round(), 100.0); +} + #[test] fn show_import_options_is_a_place_option_saved_with_the_preferences() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 90856c6736..995e339213 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9928,7 +9928,12 @@ its allocation limit. Importing individual layers with `layers: true` retains it `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and 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 cursor keeps an encrypted PDF, `.ai` +`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. +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. +The cursor keeps an encrypted PDF, `.ai` or `.ait` file that it cannot read without the password, at 612 × 792 pt (VectorCraft's own size) with `needsPassword: true` and no thumbnail; in the app a click or drag on it asks for the password, and headless it places nothing. `file.place`, `file.place.queue` and