Verify distinct browser Place sources on current main

This commit is contained in:
dotCooCoo committed 2026-11-26 21:47:06 -08:00
commit 28292e6a02
4 files changed
+148 -18

No files matched your search

+26 -2
View File
@@ -12,6 +12,8 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool
/// 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,
@@ -141,12 +143,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 +166,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())?,
@@ -359,4 +364,23 @@ 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_and_never_enter_place_params() {
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", "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);
}
}
+24 -12
View File
@@ -87,7 +87,7 @@ 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<u8>)>,
/// The loaded cursor's thumbnails by file name.
thumbs: Vec<(String, Thumb)>,
@@ -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<egui::ColorImage>,
}
@@ -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<Value> {
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))
}
@@ -773,11 +784,12 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) {
.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();
}
@@ -789,15 +801,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))
+94 -3
View File
@@ -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::<Vec<_>>(),
["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#"<svg xmlns="http://www.w3.org/2000/svg" width="50" height="40"><path d="M5 5 L45 5 L30 30 Z"/></svg>"#;
+4 -1
View File
@@ -9919,7 +9919,10 @@ 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.
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