2bc41aeb8602
tests.rs
use serde_json::json;
use vectorcraft_engine::Session;
use super::*;
/// Filled target circles drawn by one headless frame of the panel.
fn filled_targets(app: &mut VectorcraftApp, ctx: &egui::Context) -> usize {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Circle(cs) if cs.radius == 3.2 && cs.fill != Color32::TRANSPARENT)).count()
}
/// A generated `<Kind>` name is translated where painted; an unnamed text object's text never
/// is, even when it reads like one.
#[test]
fn only_generated_names_are_translated() {
let zh = crate::i18n::Lang::from_code("zh-hant").unwrap();
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let rect = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
let text = run(&mut app, "text.create", json!({"x": 10, "y": 40, "text": "<Path>"}))["id"].as_u64().unwrap();
let doc = &app.session.active().unwrap().doc;
let names = |id: u64| {
let n = doc.node(NodeId(id)).unwrap();
(n.display_name(), painted_name(n, &n.display_name(), zh))
};
assert_eq!(names(text), ("<Path>".to_string(), "<Path>".to_string()));
let (stored, painted) = names(rect);
let inner = stored.trim_start_matches('<').trim_end_matches('>');
assert_eq!(painted, format!("<{}>", crate::i18n::tr(zh, inner)));
}
#[test]
fn target_circle_fills_for_non_default_transparency() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let id = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
run(&mut app, "select.set", json!({ "ids": [id] }));
let ctx = egui::Context::default();
assert_eq!(filled_targets(&mut app, &ctx), 0);
run(&mut app, "transparency.set", json!({"blend": "multiply"}));
assert_eq!(filled_targets(&mut app, &ctx), 1, "a Multiply object");
run(&mut app, "transparency.set", json!({"blend": "normal", "knockout": true}));
assert_eq!(filled_targets(&mut app, &ctx), 1, "a knockout group");
run(&mut app, "transparency.set", json!({"knockout": false}));
run(&mut app, "appearance.addStroke", json!({}));
assert_eq!(filled_targets(&mut app, &ctx), 1, "two strokes");
}
#[test]
fn a_layer_clipping_mask_underlines_its_clipping_path() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 25, "y": 25, "width": 50, "height": 50}));
run(&mut app, "select.none", json!({}));
let ctx = egui::Context::default();
let text = Tokens::get(&ctx).text;
// Line segments in the text colour: the underlines.
let underlines = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::LineSegment { stroke, .. } if stroke.color == text)).count()
};
assert_eq!(underlines(&mut app), 0);
assert_eq!(run(&mut app, "layer.clippingMask.toggle", json!({}))["clip"], true);
assert_eq!(underlines(&mut app), 1);
run(&mut app, "layer.clippingMask.toggle", json!({}));
assert_eq!(underlines(&mut app), 0);
}
/// One headless frame of the panel with `events` (Alt held when `alt`): the centres of the
/// target circles, top row first, and the text-coloured line segments (underlines) drawn.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, alt: bool) -> (Vec<egui::Pos2>, usize) {
let mut events = events;
events.insert(0, egui::Event::ModifiersChanged(egui::Modifiers { alt, ..Default::default() }));
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let text = Tokens::get(ctx).text;
let mut circles = vec![];
let mut lines = 0;
for c in &out.shapes {
match &c.shape {
egui::Shape::Circle(cs) if cs.radius == 5.0 => circles.push(cs.center),
egui::Shape::LineSegment { stroke, .. } if stroke.color == text => lines += 1,
_ => {}
}
}
circles.sort_by(|a, b| a.y.total_cmp(&b.y));
(circles, lines)
}
fn button(pos: egui::Pos2, pressed: bool) -> egui::Event {
button_by(pos, pressed, egui::PointerButton::Primary)
}
/// `pointer` pressed (or released) at `pos`.
fn button_by(pos: egui::Pos2, pressed: bool, pointer: egui::PointerButton) -> egui::Event {
egui::Event::PointerButton { pos, button: pointer, pressed, modifiers: Default::default() }
}
/// Drag from `a` to `b` over a few frames (Alt held when `alt`).
fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, a: egui::Pos2, b: egui::Pos2, alt: bool) {
drag_by(app, ctx, a, b, alt, egui::PointerButton::Primary);
}
/// Drag from `a` to `b` with `pointer` over a few frames (Alt held when `alt`). Returns whether a
/// drag-and-drop payload was held over `b` before the release.
fn drag_by(app: &mut VectorcraftApp, ctx: &egui::Context, a: egui::Pos2, b: egui::Pos2, alt: bool, pointer: egui::PointerButton) -> bool {
frame(app, ctx, vec![egui::Event::PointerMoved(a)], alt);
frame(app, ctx, vec![button_by(a, true, pointer)], alt);
frame(app, ctx, vec![egui::Event::PointerMoved(a + vec2(0.0, 6.0))], alt);
frame(app, ctx, vec![egui::Event::PointerMoved(b)], alt);
let held = egui::DragAndDrop::has_any_payload(ctx);
frame(app, ctx, vec![button_by(b, false, pointer)], alt);
frame(app, ctx, vec![], alt);
held
}
#[test]
fn alt_clicking_an_eye_or_lock_toggles_the_other_layers() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "layer.new", json!({}));
run(&mut app, "layer.new", json!({}));
let ctx = egui::Context::default();
// Rows top first: Layers 3, 2, 1.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
let state =
|app: &VectorcraftApp| -> Vec<(bool, bool)> { app.session.active().unwrap().doc.layers.iter().map(|l| (l.visible, l.locked)).collect() };
let click = |app: &mut VectorcraftApp, at: egui::Pos2, alt: bool| {
frame(app, &ctx, vec![egui::Event::PointerMoved(at)], alt);
frame(app, &ctx, vec![button(at, true)], alt);
frame(app, &ctx, vec![button(at, false)], alt);
};
let (eye, lock) = (egui::pos2(12.0, circles[1].y), egui::pos2(37.0, circles[1].y));
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = undo(&app);
// Alt-click Layer 2's eye: Layers 1 and 3 hide in one step; again, they show.
click(&mut app, eye, true);
assert_eq!(state(&app), [(false, false), (true, false), (false, false)]);
assert_eq!(undo(&app), before + 1);
click(&mut app, eye, true);
assert_eq!(state(&app), [(true, false); 3]);
// Alt-click its lock: the others lock; again, every layer unlocks.
click(&mut app, lock, true);
assert_eq!(state(&app), [(true, true), (true, false), (true, true)]);
assert_eq!(app.session.active().unwrap().history.undo.last().map(|u| u.label.as_str()), Some("Lock Others"));
// A plain click still toggles only that layer.
click(&mut app, eye, false);
assert_eq!(state(&app), [(true, true), (false, false), (true, true)]);
click(&mut app, lock, true);
assert_eq!(state(&app), [(true, false), (false, false), (true, false)]);
// A sublayer's row stands for its top-level layer: the other layers hide.
click(&mut app, eye, false);
let layer2 = app.session.active().unwrap().doc.layers[1].id.0;
let sub = run(&mut app, "layer.newSublayer", json!({"parent": layer2}));
// Rows: Layer 3, Layer 2, its sublayer, Layer 1.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4);
click(&mut app, egui::pos2(12.0, circles[2].y), true);
assert_eq!(state(&app), [(false, false), (true, false), (false, false)]);
let doc = &app.session.active().unwrap().doc;
assert!(doc.node(NodeId(sub["id"].as_u64().unwrap())).unwrap().visible);
}
#[test]
fn ctrl_alt_clicking_an_eye_switches_the_other_layers_between_outline_and_preview() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "layer.new", json!({}));
run(&mut app, "layer.new", json!({}));
let ctx = egui::Context::default();
// Rows top first: Layers 3, 2, 1.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
// Each layer bottom first: (visible, preview).
let state = |app: &VectorcraftApp| -> Vec<(bool, bool)> {
let doc = &app.session.active().unwrap().doc;
doc.layers.iter().map(|l| (l.visible, !matches!(l.kind, NodeKind::Layer { preview: false, .. }))).collect()
};
let last = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.last().map(|u| u.label.clone());
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let eye = |i: usize| egui::pos2(12.0, circles[i].y);
let ctrl_alt = egui::Modifiers { alt: true, command: true, ..Default::default() };
let before = undo(&app);
// Ctrl/Cmd+Alt-click Layer 1's eye: Layers 2 and 3 go to Outline in one step, and stay visible.
click_with(&mut app, &ctx, eye(2), ctrl_alt);
assert_eq!(state(&app), [(true, true), (true, false), (true, false)]);
assert_eq!(undo(&app), before + 1);
assert_eq!(last(&app).as_deref(), Some("Outline Others"));
// Again: every layer previews, in one step.
click_with(&mut app, &ctx, eye(2), ctrl_alt);
assert_eq!(state(&app), [(true, true); 3]);
assert_eq!(undo(&app), before + 2);
assert_eq!(last(&app).as_deref(), Some("Preview All Layers"));
// On a layer in Outline whose others preview: the others go to Outline and it previews.
click_with(&mut app, &ctx, eye(0), egui::Modifiers::COMMAND);
assert_eq!(state(&app), [(true, true), (true, true), (true, false)]);
click_with(&mut app, &ctx, eye(0), ctrl_alt);
assert_eq!(state(&app), [(true, false), (true, false), (true, true)]);
}
/// A document with two rectangles on one layer → (app, layer, [bottom, top]).
fn two_rects() -> (VectorcraftApp, NodeId, [NodeId; 2]) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
let b = run(&mut app, "shape.rectangle", json!({"x": 60, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
run(&mut app, "select.none", json!({}));
let layer = app.session.active().unwrap().doc.layers[0].id;
(app, layer, [NodeId(a), NodeId(b)])
}
/// The painted names one headless frame of the panel draws italic.
fn italic_names(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
fn collect(shape: &egui::Shape, names: &mut Vec<String>) {
match shape {
egui::Shape::Text(t) => {
if t.galley.job.sections.iter().any(|s| s.format.italics) {
names.push(t.galley.text().to_string());
}
}
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, names)),
_ => {}
}
}
let mut names = Vec::new();
out.shapes.iter().for_each(|c| collect(&c.shape, &mut names));
names
}
/// A layer whose Layer Options › Print is off has its name italic in the panel (#5739), as the
/// reference application shows it; a printing layer's name stays upright, and unticking Print again
/// makes it upright.
#[test]
fn a_layer_that_does_not_print_has_its_name_italic() {
let (mut app, layer, _) = two_rects();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
assert!(!italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "a printing layer's name is upright");
app.session.execute("layer.setProps", &json!({"ids": [layer.0], "printable": false})).unwrap();
assert!(italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "Print off: its name is italic");
app.session.execute("layer.setProps", &json!({"ids": [layer.0], "printable": true})).unwrap();
assert!(!italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "Print on again: upright again");
}
#[test]
fn closing_a_document_releases_only_its_layer_thumbnails() {
let (mut app, _, _) = two_rects();
let ctx = egui::Context::default();
let first = app.session.active().unwrap().uid;
frame(&mut app, &ctx, vec![], false);
assert!(THUMBS.with(|c| c.borrow().cached(first)));
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let second = app.session.active().unwrap().uid;
frame(&mut app, &ctx, vec![], false);
assert!(THUMBS.with(|c| c.borrow().cached(second)));
// Close the first document the way File › Close does (Don't Save), with no panel drawn after.
assert_eq!(app.run("file.close", json!({"index": 0})).unwrap(), json!({"pending": crate::unsaved::KIND}));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
crate::dialogs::confirm(&mut app).unwrap();
assert!(app.session.documents().iter().all(|d| d.uid != first), "the first document closed");
THUMBS.with(|c| {
let thumbs = c.borrow();
assert!(!thumbs.cached(first), "closed document textures are released");
assert!(thumbs.cached(second), "open document textures stay cached");
});
}
/// From now on each reading of this thread's render budget clock is `ms` later than the one before.
/// A render reads it before and after, so each row thumbnail rendered takes `ms` of the budget.
fn clock_steps(ms: f64) {
let mut now = 0.0;
THUMBS.with(|c| {
c.borrow_mut().clock = Some(Box::new(move || {
now += ms;
now
}))
});
}
/// Rendering on the UI thread stops for the pass once the thumbnails rendered in it took the
/// budget, and the rest render in the next passes.
#[test]
fn row_thumbnails_past_the_render_budget_wait_for_the_next_pass() {
let (mut app, _, _) = two_rects();
let ctx = egui::Context::default();
let renders = || THUMBS.with(|c| c.borrow().renders);
// Each render takes 5 ms: after two renders the pass has used 10 ms, past the 8 ms budget.
clock_steps(5.0);
let mut per_pass = vec![];
for _ in 0..4 {
let before = renders();
frame(&mut app, &ctx, vec![], false);
per_pass.push(renders() - before);
}
assert_eq!(per_pass, [2, 1, 0, 0], "the layer's and two objects' thumbnails, two in the first pass");
}
#[test]
fn row_thumbnails_wait_for_the_end_of_a_drag() {
let (mut app, _, _) = two_rects();
app.session.execute("select.all", &json!({})).unwrap();
let ctx = egui::Context::default();
let renders = || THUMBS.with(|c| c.borrow().renders);
// Renders take no time, so every row's thumbnail fits in a pass however busy the machine is.
clock_steps(0.0);
frame(&mut app, &ctx, vec![], false);
let first = renders();
assert!(first >= 1, "the rows' thumbnails render at once");
frame(&mut app, &ctx, vec![], false);
assert_eq!(renders(), first, "and stay");
// A move drag: the layer (and the moved objects) change on every preview.
app.session.begin_interaction("Move").unwrap();
for i in 1..=10 {
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, i, 0]})).unwrap();
frame(&mut app, &ctx, vec![], false);
}
assert_eq!(renders(), first, "nothing renders while the drag goes on");
app.session.commit_interaction().unwrap();
for _ in 0..12 {
frame(&mut app, &ctx, vec![], false);
}
assert!(renders() > first, "the changed rows render after it");
let after = renders();
frame(&mut app, &ctx, vec![], false);
assert_eq!(renders(), after, "once");
}
#[test]
fn the_row_thumbnails_follow_the_document_shown_and_none_once_it_closes() {
let (mut app, _, _) = two_rects();
let ctx = egui::Context::default();
let showing = || THUMBS.with(|c| c.borrow().showing);
frame(&mut app, &ctx, vec![], false);
let first = app.session.active().map(|st| st.uid);
assert_eq!(showing(), first);
// With no thumbnails drawn, the panel still tells which document it shows.
let p = &mut app.ui.layers_panel;
(p.thumb_layers, p.thumb_groups, p.thumb_objects) = (false, false, false);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap();
frame(&mut app, &ctx, vec![], false);
let second = app.session.active().map(|st| st.uid);
assert_ne!(second, first);
assert_eq!(showing(), second, "the new document's rows are drawn");
for _ in 0..2 {
app.session.execute("file.close", &json!({"index": 0})).unwrap();
}
frame(&mut app, &ctx, vec![], false);
assert_eq!(showing(), None, "no document is shown once both close");
// The Links panel alone does the same.
let links = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::links::show(app, ui));
out.textures_delta.clear();
};
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
links(&mut app);
assert_eq!(showing(), app.session.active().map(|st| st.uid));
app.session.execute("file.close", &json!({"index": 0})).unwrap();
links(&mut app);
assert_eq!(showing(), None, "the Links panel shows no document");
}
#[test]
fn clicking_a_target_circle_targets_the_layer() {
let (mut app, layer, [a, b]) = two_rects();
let ctx = egui::Context::default();
// Rows top down: the layer, the top rectangle, the bottom one.
let (c, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(c.len(), 3);
for e in [egui::Event::PointerMoved(c[0]), button(c[0], true), button(c[0], false)] {
frame(&mut app, &ctx, vec![e], false);
}
let st = app.session.active().unwrap();
assert_eq!(st.selection.target, Some(layer));
assert_eq!(st.selection.objects, vec![a, b]);
assert_eq!(super::super::appearance::object_label(&app), "Layer", "the Appearance panel lists the layer");
app.session.execute("transparency.set", &json!({"opacity": 25})).unwrap();
assert!((app.session.active().unwrap().doc.node(layer).unwrap().opacity - 0.25).abs() < 1e-6);
// The layer's circle is filled now; clicking an object's circle targets that object.
assert_eq!(filled_targets(&mut app, &ctx), 1);
for e in [egui::Event::PointerMoved(c[2]), button(c[2], true), button(c[2], false)] {
frame(&mut app, &ctx, vec![e], false);
}
let st = app.session.active().unwrap();
assert_eq!((st.selection.target, st.selection.objects.clone()), (Some(a), vec![a]));
// Shift-clicking another object's circle adds it to the selection (#901), and again takes
// it out; nothing is targeted meanwhile.
click_with(&mut app, &ctx, c[1], egui::Modifiers::SHIFT);
let st = app.session.active().unwrap();
assert_eq!((st.selection.target, st.selection.objects.clone()), (None, vec![a, b]));
click_with(&mut app, &ctx, c[1], egui::Modifiers::SHIFT);
assert_eq!(app.session.active().unwrap().selection.objects, vec![a]);
}
/// The rows whose target circle shows as targeted (its inner ring drawn), as indexes into the
/// circles [`frame`] returns.
fn targeted_rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<usize> {
let (circles, _) = frame(app, ctx, vec![], false);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let rings: Vec<egui::Pos2> = out
.shapes
.iter()
.filter(|c| matches!(&c.shape, egui::Shape::Circle(cs) if cs.radius == 2.8))
.map(|c| c.shape.visual_bounding_rect().center())
.collect();
circles.iter().enumerate().filter(|(_, c)| rings.iter().any(|r| r.distance(**c) < 0.5)).map(|(i, _)| i).collect()
}
/// A layer added to the selection from its target circle shows as targeted, as an object added
/// the same way does (#8646): with nothing targeted, a layer's circle shows its inner ring while
/// all of its visible, unlocked art is selected, and not while only part of it is.
#[test]
fn a_layer_added_from_its_target_circle_shows_as_targeted() {
let (mut app, [layer, sub, g, b, a, c]) = nested();
let ctx = egui::Context::default();
// Rows top down, as `rows_at_every_depth_are_clickable` lists them.
let ids = [layer, sub, g, b, a, c];
let row = |id: NodeId| ids.iter().position(|r| *r == id).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), ids.len());
// c, then the sublayer added: its art (the group and a) is selected, nothing is targeted.
app.session.execute("layer.target", &json!({"id": c.0})).unwrap();
app.session.execute("layer.target", &json!({"id": sub.0, "add": true})).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.selection.target, None);
let mut want = vec![row(sub), row(g), row(a), row(c), row(layer)];
want.sort();
// The top layer's art is all selected too, so it shows as targeted; b, inside the selected
// group, is not selected itself.
assert_eq!(targeted_rows(&mut app, &ctx), want);
assert!(!targeted_rows(&mut app, &ctx).contains(&row(b)));
// With only part of the sublayer's art selected, neither layer shows as targeted.
app.session.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
let mut want = vec![row(a), row(c)];
want.sort();
assert_eq!(targeted_rows(&mut app, &ctx), want);
}
#[test]
fn dragging_a_target_circle_moves_or_copies_the_appearance() {
let (mut app, layer, [a, b]) = two_rects();
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
let ctx = egui::Context::default();
let (c, _) = frame(&mut app, &ctx, vec![], false);
let opacity = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().opacity;
// Alt-drag the bottom rectangle's circle onto the top one's: both have it.
drag(&mut app, &ctx, c[2], c[1], true);
assert!((opacity(&app, b) - 0.3).abs() < 1e-6 && (opacity(&app, a) - 0.3).abs() < 1e-6);
// A plain drag onto the layer's circle moves it there.
drag(&mut app, &ctx, c[1], c[0], false);
assert!((opacity(&app, layer) - 0.3).abs() < 1e-6 && opacity(&app, b) == 1.0);
}
/// A target circle dropped on the trash reduces that item's own appearance to its topmost visible
/// fill and stroke in one undo step, and deletes nothing; dropped again, it changes nothing and
/// adds no undo step. A layer keeps only the rows it had, and its art is left as it is.
#[test]
fn dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance() {
let (mut app, layer, [a, _]) = two_rects();
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
// [Fill green, Stroke, Fill red, Stroke 5 pt], with an effect on the object.
run(&mut app, "appearance.addFill", json!({"ids": [a.0]}));
run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 0, "color": "#00ff00"}));
run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 2, "color": "#ff0000"}));
run(&mut app, "appearance.addStroke", json!({"ids": [a.0]}));
run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 3, "weight": 5}));
run(&mut app, "effect.apply", json!({"ids": [a.0], "effect": "stylize.dropShadow", "item": null}));
let ctx = egui::Context::default();
let (c, _) = frame(&mut app, &ctx, vec![], false);
let trash = trash_pos(&mut app, &ctx);
let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone();
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let (original, count, before) = (node(&app, a), app.session.active().unwrap().doc.node_count(), undo(&app));
// The bottom rectangle's circle (rows: the layer, the top rectangle, the bottom one).
drag(&mut app, &ctx, c[2], trash, false);
let n = node(&app, a);
assert!(n.appearance.is_basic(), "{:?}", n.appearance);
assert_eq!(n.appearance.items.len(), 2);
assert_eq!(n.appearance.fill().unwrap().paint.color().unwrap().to_hex(), "#ff0000");
assert_eq!(n.appearance.stroke().unwrap().width, 5.0);
assert_eq!((app.session.active().unwrap().doc.node_count(), undo(&app)), (count, before + 1));
// Dropped again, nothing changes and no undo step is made.
drag(&mut app, &ctx, c[2], trash, false);
assert_eq!((node(&app, a), undo(&app)), (n, before + 1));
run(&mut app, "edit.undo", json!({}));
assert_eq!(node(&app, a), original, "one undo step restores the whole stack");
// The layer's own fill stays and its effect goes; the art on it keeps its appearance.
run(&mut app, "appearance.addFill", json!({"ids": [layer.0]}));
run(&mut app, "effect.apply", json!({"ids": [layer.0], "effect": "stylize.dropShadow", "item": null}));
drag(&mut app, &ctx, c[0], trash, false);
let l = node(&app, layer);
assert_eq!((l.appearance.items.len(), l.appearance.effects.len()), (1, 0), "{:?}", l.appearance);
assert!(l.appearance.fill().is_some());
assert_eq!(node(&app, a), original);
}
/// The trash button: the bottom bar's rightmost button.
fn trash_pos(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::Pos2 {
bar_buttons(app, ctx)[0]
}
#[test]
fn dragging_rows_onto_the_trash_deletes_them() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({})).unwrap();
let ctx = egui::Context::default();
// Rows top first: Layer 2, Layer 1. Grab Layer 2 by its name, left of its target circle.
let (c, _) = frame(&mut app, &ctx, vec![], false);
let top = app.session.active().unwrap().doc.layers[1].id;
let trash = trash_pos(&mut app, &ctx);
drag(&mut app, &ctx, c[0] - vec2(100.0, 0.0), trash, false);
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layers.len(), 1);
assert!(doc.node(top).is_none());
}
/// The message of the confirmation open now, if one is.
fn asked(app: &VectorcraftApp) -> Option<String> {
app.ui.dialog.as_ref().filter(|d| d.kind == crate::dialogs::confirm::KIND).map(|d| d.str("message"))
}
/// The trash, the Delete key and rows dropped on the trash ask before deleting a layer that holds
/// art, hidden and locked art included: Cancel keeps it, and OK deletes the rows it asked about in
/// one undo step, even after another row was highlighted.
#[test]
fn deleting_a_layer_that_holds_art_asks_first() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut app, "select.none", json!({}));
run(&mut app, "layer.setProps", json!({"ids": [rect.0], "visible": false, "locked": true}));
let art = app.session.active().unwrap().doc.layers[0].id;
run(&mut app, "layer.new", json!({}));
let there = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(art).is_some();
let ctx = egui::Context::default();
// Rows top first: Layer 2, Layer 1, its rectangle.
let (c, _) = frame(&mut app, &ctx, vec![], false);
let name = |i: usize| egui::pos2(150.0, c[i].y);
let question = Some("Delete this layer and its artwork?".to_string());
click_with(&mut app, &ctx, name(1), egui::Modifiers::NONE);
let trash = trash_pos(&mut app, &ctx);
click_with(&mut app, &ctx, trash, egui::Modifiers::NONE);
assert_eq!(asked(&app), question, "the trash asks");
assert!(there(&app), "nothing is deleted before OK");
crate::dialogs::cancel(&mut app);
assert!(app.ui.dialog.is_none() && there(&app), "Cancel keeps the layer");
click_with(&mut app, &ctx, name(1), egui::Modifiers::NONE);
let del = egui::Event::Key { key: egui::Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
frame(&mut app, &ctx, vec![del], false);
assert_eq!(asked(&app), question, "Delete asks");
assert!(there(&app));
crate::dialogs::cancel(&mut app);
let undo = app.session.active().unwrap().history.undo.len();
drag(&mut app, &ctx, c[1] - vec2(100.0, 0.0), trash, false);
assert_eq!(asked(&app), question, "a drop on the trash asks");
assert!(there(&app));
// Highlighting Layer 2 now leaves OK deleting the row that was dropped.
click_with(&mut app, &ctx, name(0), egui::Modifiers::NONE);
crate::dialogs::confirm(&mut app).unwrap();
let st = app.session.active().unwrap();
assert!(app.ui.dialog.is_none() && st.doc.node(art).is_none() && st.doc.node(rect).is_none());
assert_eq!((st.doc.layers.len(), st.history.undo.len()), (1, undo + 1), "one undo step");
run(&mut app, "edit.undo", json!({}));
assert!(there(&app));
}
/// The panel menu's Delete Selection (`ui.layerDelete`) asks once for several rows when one of
/// them is a layer with art, art in a sublayer included; an empty layer, a layer with only a
/// guide, and objects alone go at once, and `layer.delete` itself never asks.
#[test]
fn delete_selection_asks_only_for_layers_with_art() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let bottom = app.session.active().unwrap().doc.layers[0].id.0;
let loose = id(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})));
let outer = id(run(&mut app, "layer.new", json!({})));
let sub = id(run(&mut app, "layer.newSublayer", json!({})));
let nested = id(run(&mut app, "shape.ellipse", json!({"x": 50, "y": 50, "width": 20, "height": 20})));
run(&mut app, "select.none", json!({}));
let empty = id(run(&mut app, "layer.new", json!({"top": true})));
let guided = id(run(&mut app, "layer.new", json!({"top": true})));
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50, "layer": guided}));
run(&mut app, "select.none", json!({}));
let exists = |app: &VectorcraftApp, id: u64| app.session.active().unwrap().doc.node(NodeId(id)).is_some();
for (rows, what) in [(json!([empty]), "an empty layer"), (json!([guided]), "a layer with only a guide"), (json!([loose]), "an object")] {
app.run("ui.layerDelete", json!({ "ids": rows })).unwrap();
assert!(app.ui.dialog.is_none(), "{what} goes at once");
assert!(!exists(&app, rows[0].as_u64().unwrap()), "{what} is deleted");
}
run(&mut app, "edit.undo", json!({}));
// Art in a sublayer counts; the highlighted rows are the default, and a mixed selection asks once.
run(&mut app, "layer.highlight", json!({"ids": [outer, loose]}));
app.run("ui.layerDelete", json!({})).unwrap();
assert_eq!(asked(&app).as_deref(), Some("Delete the selected items and their artwork?"));
assert!(exists(&app, nested) && exists(&app, loose));
crate::dialogs::confirm(&mut app).unwrap();
assert!(!exists(&app, outer) && !exists(&app, sub) && !exists(&app, nested) && !exists(&app, loose));
assert!(app.ui.dialog.is_none(), "asked once");
// A sublayer with art asks as a layer does.
run(&mut app, "edit.undo", json!({}));
app.run("ui.layerDelete", json!({ "id": sub })).unwrap();
assert_eq!(asked(&app).as_deref(), Some("Delete this layer and its artwork?"));
crate::dialogs::cancel(&mut app);
// Scripts deleting with layer.delete are not asked.
app.run("layer.delete", json!({ "ids": [outer] })).unwrap();
assert!(app.ui.dialog.is_none() && !exists(&app, outer));
assert!(exists(&app, bottom));
}
/// Rows `layer.delete` refuses are refused without a question, and OK deletes nothing once another
/// document is active.
#[test]
fn delete_selection_refusals_and_a_document_change() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
let only = app.session.active().unwrap().doc.layers[0].id.0;
let e = app.run("ui.layerDelete", json!({ "ids": [only] })).unwrap_err();
assert!(e.contains("at least one layer") && app.ui.dialog.is_none(), "{e}");
for bad in [json!({"ids": [999_999]}), json!({"id": "x"}), json!({"ids": 3}), json!({"confirmed": "yes"}), json!({"doc": -1})] {
assert!(app.run("ui.layerDelete", bad.clone()).is_err() && app.ui.dialog.is_none(), "{bad}");
}
let art = run(&mut app, "layer.new", json!({}))["id"].as_u64().unwrap();
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
app.run("ui.layerDelete", json!({ "ids": [art] })).unwrap();
assert!(asked(&app).is_some());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let e = crate::dialogs::confirm(&mut app).unwrap_err();
assert!(e.contains("nothing was deleted"), "{e}");
let first = &app.session.documents()[0].doc;
assert!(first.node(NodeId(art)).is_some(), "the first document keeps the layer");
}
#[test]
fn renaming_a_layer_commits_on_enter_and_escape_cancels() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let layer = app.session.doc().unwrap().doc.layers[0].id;
let name = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].display_name();
let ctx = egui::Context::default();
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let select_all = egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };
// What a double-click on the row does: the name field opens with the name.
let open = |app: &mut VectorcraftApp| {
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("layers-rename"), (layer.0, name(app))));
frame(app, &ctx, vec![], false);
frame(app, &ctx, vec![], false);
};
open(&mut app);
frame(&mut app, &ctx, vec![select_all.clone(), egui::Event::Text("Sky".into())], false);
frame(&mut app, &ctx, vec![key(egui::Key::Enter)], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(name(&app), "Sky", "Enter keeps the new name");
assert!(ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("layers-rename"))).is_none(), "and closes the field");
open(&mut app);
frame(&mut app, &ctx, vec![select_all, egui::Event::Text("Ground".into())], false);
frame(&mut app, &ctx, vec![key(egui::Key::Escape)], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(name(&app), "Sky", "Escape cancels");
}
/// Shift+Enter in the name field renames the layer and keeps the field open, the new name
/// selected; Enter then renames it again and closes the field.
#[test]
fn shift_enter_renames_a_layer_and_keeps_the_field_open() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let layer = app.session.doc().unwrap().doc.layers[0].id;
let name = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].display_name();
let ctx = egui::Context::default();
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
let field = rename_id().with("field");
ctx.data_mut(|d| d.insert_temp(rename_id(), (layer.0, name(&app))));
frame(&mut app, &ctx, vec![], false);
frame(&mut app, &ctx, vec![], false);
frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text("Sky".into())], false);
frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::SHIFT)], false);
assert_eq!(name(&app), "Sky", "Shift+Enter applies the name");
assert!(ctx.memory(|m| m.has_focus(field)), "the field keeps the focus");
assert!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).is_some(), "and stays open");
frame(&mut app, &ctx, vec![], false);
let selected = egui::TextEdit::load_state(&ctx, field).and_then(|st| st.cursor.char_range()).map(|r| r.as_sorted_char_range());
assert_eq!(selected.map(|r| (r.start.0, r.end.0)), Some((0, 3)), "the name shown is selected");
frame(&mut app, &ctx, vec![egui::Event::Text("Sea".into())], false);
frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(name(&app), "Sea", "typing replaced it, and Enter applies that");
assert!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).is_none(), "and closes the field");
}
/// Rename (`ui.rename`, F2) opens the name field on the selected object's row, as a
/// double-click on the name does: Enter renames it in one undo step.
#[test]
fn rename_opens_the_name_field_of_the_selected_object() {
let (mut app, _, [a, _]) = two_rects();
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
let name = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(a).unwrap().display_name();
let before = name(&app);
app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let opened = app.run("ui.rename", json!({})).unwrap();
assert_eq!(opened, json!({"id": a.0, "name": before}));
assert_eq!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())), Some((a.0, before.clone())), "the field opens on its row");
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
frame(&mut app, &ctx, vec![], false);
frame(&mut app, &ctx, vec![], false);
assert!(ctx.memory(|m| m.has_focus(rename_id().with("field"))), "with the keyboard");
frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text("Sun".into())], false);
frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(name(&app), "Sun");
app.session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(name(&app), before, "one undo step");
}
/// Rename (`ui.rename`) has no default key (F2 is Cut's alternate on Windows and Linux): it is listed in Keyboard Shortcuts,
/// where a key can be assigned to it.
#[test]
fn rename_has_no_default_key() {
use crate::shortcut_editor::{command_for_key, default_command_shortcut};
crate::shortcut_editor::sync(&crate::state::UiState::default());
assert_eq!(default_command_shortcut("ui.rename"), None);
assert_ne!(command_for_key("F2"), Some("ui.rename"));
let (mut app, _, _) = two_rects();
let listed = app.run("shortcuts.list", json!({"query": "ui.rename"})).unwrap();
let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| r["label"].clone()).collect();
assert_eq!(rows, [json!("Rename")], "Keyboard Shortcuts lists it");
}
/// Without a selection Rename names the current layer; it refuses several objects and a row the
/// panel doesn't list, and opens nothing then.
#[test]
fn rename_names_the_current_layer_and_refuses_several_or_hidden_rows() {
let (mut app, layer, [a, b]) = two_rects();
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
let open = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).map(|r| r.0);
assert_eq!(app.run("ui.rename", json!({})).unwrap()["id"], json!(layer.0), "nothing selected: the current layer");
ctx.data_mut(|d| d.remove::<(u64, String)>(rename_id()));
app.session.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
assert!(app.run("ui.rename", json!({})).is_err(), "two objects");
assert_eq!(open(&ctx), None);
app.ui.layers_panel.layers_only = true;
assert!(app.run("ui.rename", json!({"id": a.0})).is_err(), "Show Layers Only lists no object rows");
assert_eq!(open(&ctx), None);
assert!(app.run("ui.rename", json!({"id": 999_999})).is_err(), "no such object");
assert_eq!(app.run("ui.rename", json!({"id": layer.0})).unwrap()["id"], json!(layer.0));
assert_eq!(open(&ctx), Some(layer.0));
}
#[test]
fn an_open_rename_does_not_follow_into_another_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let layer = app.session.doc().unwrap().doc.layers[0].id;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![], false);
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("layers-rename"), (layer.0, "Renamed in the first".to_string())));
frame(&mut app, &ctx, vec![], false);
// A second document, whose first layer has the same node id, comes to the front.
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert_eq!(app.session.doc().unwrap().doc.layers[0].id, layer);
let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
frame(&mut app, &ctx, vec![], false);
frame(&mut app, &ctx, vec![enter], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(app.session.doc().unwrap().doc.layers[0].display_name(), "Layer 1");
assert!(ctx.data(|d| d.get_temp::<(u64, String)>(egui::Id::unique("layers-rename"))).is_none());
}
#[test]
fn masks_underline_dashed_and_mask_editing_lists_only_the_mask() {
let (mut app, _, [a, _]) = two_rects();
let ctx = egui::Context::default();
let (_, before) = frame(&mut app, &ctx, vec![], false);
app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
app.session.execute("transparency.makeOpacityMask", &json!({})).unwrap();
// Editing the new (empty) mask: one row, `<Opacity Mask>`.
let (c, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(c.len(), 1);
let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], show);
assert!(texts.iter().any(|(t, _)| t == "<Opacity Mask>"), "{texts:?}");
app.session.execute("transparency.stopEditingOpacityMask", &json!({})).unwrap();
let (c, after) = frame(&mut app, &ctx, vec![], false);
assert_eq!(c.len(), 3);
assert!(after > before + 1, "a dashed underline: {before} → {after}");
}
// ---- isolation mode ----
/// The object rows [`list_rows`] lists for the active document, top down, with their depths.
fn listed_ids(app: &VectorcraftApp) -> Vec<(NodeId, usize)> {
let st = app.session.active().unwrap();
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default());
rows.iter().filter(|r| r.guide.is_none() && !r.spine).map(|r| (r.node.id, r.depth)).collect()
}
/// In isolation mode the panel lists only the isolated sublayer, group or object, as the top row
/// with the open rows inside it; the other layers and groups are listed again when it ends.
#[test]
fn isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again() {
let (mut app, [layer, sub, g, b, a, c]) = nested();
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
let top = NodeId(run(&mut app, "layer.new", json!({"top": true, "name": "Top"}))["id"].as_u64().unwrap());
let all = vec![(top, 0), (layer, 0), (sub, 1), (g, 2), (b, 3), (a, 2), (c, 1)];
assert_eq!(listed_ids(&app), all);
run(&mut app, "object.isolate", json!({"id": g.0}));
assert_eq!(listed_ids(&app), [(g, 0), (b, 1)], "the group and its art");
run(&mut app, "object.exitIsolation", json!({}));
assert_eq!(listed_ids(&app), all, "every layer again");
run(&mut app, "object.isolate", json!({"id": sub.0}));
assert_eq!(listed_ids(&app), [(sub, 0), (g, 1), (b, 2), (a, 1)], "the sublayer and its art");
// Isolating an object inside lists that object alone.
run(&mut app, "object.isolate", json!({"id": a.0}));
assert_eq!(listed_ids(&app), [(a, 0)]);
run(&mut app, "object.exitIsolation", json!({}));
assert_eq!(listed_ids(&app), all);
// A closed isolated group lists its own row alone, and an isolated object that is gone leaves
// every layer listed.
run(&mut app, "object.isolate", json!({"id": g.0}));
app.session.active_mut().unwrap().layers_open.set(g, false);
assert_eq!(listed_ids(&app), [(g, 0)]);
app.session.active_mut().unwrap().isolation = Some(NodeId(999_999));
assert_eq!(listed_ids(&app), [(top, 0), (layer, 0), (sub, 1), (g, 2), (a, 2), (c, 1)]);
}
/// Entering isolation mode opens the isolated row and leaving it lists every row again; a drop
/// beside the isolated row or into the empty space under it moves nothing out of the isolated art.
#[test]
fn isolation_opens_the_isolated_row_and_keeps_drops_inside_it() {
let (mut app, [layer, sub, g, _, a, _]) = nested();
let ctx = egui::Context::default();
let parent = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.parent_of(id);
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
app.session.active_mut().unwrap().layers_open.set(sub, false);
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
// Rows: Sub, g, b, a.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4, "the sublayer's row opens");
// Rectangle a onto the upper edge of the sublayer's row: not above it, outside the sublayer.
let primary = egui::PointerButton::Primary;
let dragged = drag_by(&mut app, &ctx, egui::pos2(150.0, circles[3].y), egui::pos2(150.0, circles[0].y - ROW_MEDIUM * 0.4), false, primary);
assert!(dragged, "the drag started");
assert_eq!(parent(&app, a), Some(sub));
// The sublayer into the empty space under the rows: it stays in Layer 1.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4);
let dragged = drag_by(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::pos2(150.0, circles[3].y + 3.0 * ROW_MEDIUM), false, primary);
assert!(dragged, "the drag started");
assert_eq!(parent(&app, sub), Some(layer));
// Rectangle a onto the middle of the group's row: into it.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let at = |app: &VectorcraftApp, id: NodeId| circles[listed_ids(app).iter().position(|(n, _)| *n == id).unwrap()];
let (from, to) = (at(&app, a), at(&app, g));
drag(&mut app, &ctx, egui::pos2(150.0, from.y), egui::pos2(150.0, to.y), false);
assert_eq!(parent(&app, a), Some(g));
app.session.execute("object.exitIsolation", &json!({"all": true})).unwrap();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6, "every row again");
}
/// In isolation mode the rows outside the isolated art are no longer highlighted, so Delete and the
/// trash in the panel act only on rows it lists.
#[test]
fn isolation_drops_highlights_outside_the_isolated_art() {
let (mut app, [_, sub, _, b, _, c]) = nested();
let ctx = egui::Context::default();
app.session.execute("layer.highlight", &json!({"ids": [c.0, b.0], "mode": "set"})).unwrap();
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
frame(&mut app, &ctx, vec![], false);
assert_eq!(rows_of(&app), [b], "the rectangle on Layer 1, outside the sublayer, is let go");
}
/// In isolation mode Rename and the rows opened around a located object stay inside the isolated
/// row: an object outside it has no row to rename, and opens no rows.
#[test]
fn isolation_keeps_rename_and_locate_to_the_rows_listed() {
let (mut app, [layer, sub, g, b, _, c]) = nested();
let ctx = egui::Context::default();
app.ui_ctx = Some(ctx.clone());
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
let err = app.run("ui.rename", json!({"id": c.0})).unwrap_err();
assert!(err.contains("the object is outside the isolated group"), "{err}");
assert_eq!(app.run("ui.rename", json!({"id": b.0})).unwrap()["id"], json!(b.0));
{
let st = app.session.active().unwrap();
let listed = |id| listed_when_opened(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default(), id);
assert_eq!([layer, sub, g, b, c].map(listed), [false, true, true, true, false]);
}
let st = app.session.active_mut().unwrap();
st.layers_open.set(layer, false);
st.layers_open.set(g, false);
let doc = st.doc.clone();
open_around(&mut app, &doc, &[c]);
open_around(&mut app, &doc, &[b]);
let open = &app.session.active().unwrap().layers_open;
assert!(open.contains(g), "the group inside the sublayer opens");
assert!(!open.contains(layer), "the layer around the sublayer stays closed");
}
/// In isolation mode, with no row highlighted, Delete Selection and the trash do not delete the
/// current layer when it is outside the isolated art, where the panel does not list it.
#[test]
fn isolation_keeps_delete_to_the_rows_listed() {
let (mut app, [layer, sub, g, b, a, c]) = nested();
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
// A row left highlighted outside the isolated group before the panel shows again.
let st = app.session.active_mut().unwrap();
st.layer_rows = vec![c];
let current = st.current_layer().unwrap();
assert!([layer, sub].contains(¤t), "the current layer holds the isolated group");
let err = app.run("ui.layerDelete", json!({})).unwrap_err();
assert!(err.contains("the object is outside the isolated group"), "{err}");
let doc = &app.session.active().unwrap().doc;
assert!([layer, sub, g, b, a, c].iter().all(|id| doc.node(*id).is_some()), "nothing was deleted");
app.session.active_mut().unwrap().layer_rows = vec![b];
app.run("ui.layerDelete", json!({})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert!(doc.node(b).is_none(), "a highlighted row inside the isolated group is deleted");
assert!(doc.node(a).is_some() && doc.node(c).is_some());
}
/// In isolation mode New Layer and New Sublayer are off, and `ui.newLayer` is an error, while the
/// layer they make would be outside the isolated art; a sublayer of an isolated sublayer is listed.
#[test]
fn isolation_keeps_new_layers_to_the_rows_listed() {
let (mut app, [_, sub, g, ..]) = nested();
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
let st = app.session.active().unwrap();
assert_eq!([(false, false), (true, false), (false, true)].map(|(s, t)| new_layer_unlisted(st, s, t)), [true; 3]);
for p in [json!({}), json!({"sublayer": true})] {
let err = app.run("ui.newLayer", p).unwrap_err();
assert!(err.contains("exit isolation mode first"), "{err}");
}
assert!(app.ui.dialog.is_none());
app.session.execute("object.exitIsolation", &json!({})).unwrap();
app.session.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
let st = app.session.active().unwrap();
assert!(new_layer_unlisted(st, false, false), "a new layer would go beside the isolated sublayer");
assert!(!new_layer_unlisted(st, true, false), "a new sublayer goes inside it");
app.run("ui.newLayer", json!({"sublayer": true})).unwrap();
assert!(app.ui.dialog.is_some());
// Exit Isolation Mode on the sublayer isolates its layer, beside which a new layer would go.
app.session.execute("object.exitIsolation", &json!({})).unwrap();
assert!(new_layer_unlisted(app.session.active().unwrap(), false, true));
app.session.execute("object.exitIsolation", &json!({})).unwrap();
assert!(!new_layer_unlisted(app.session.active().unwrap(), false, true));
}
/// With Show Layers Only on, an isolated group or object is still listed as the top row, without
/// the art inside it, and its row can be renamed.
#[test]
fn isolation_with_show_layers_only_lists_the_isolated_group_or_object() {
let (mut app, [_, sub, g, _, a, _]) = nested();
let opts = PanelOptions { layers_only: true, ..Default::default() };
let listed = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
list_rows(&st.doc, st.isolation, &st.layers_open, &opts, "", &Filter::default()).iter().map(|r| r.node.id).collect::<Vec<_>>()
};
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(listed(&app), [g], "the group's row, without its art");
let st = app.session.active().unwrap();
assert!(listed_when_opened(&st.doc, st.isolation, &st.layers_open, &opts, "", &Filter::default(), g));
app.session.execute("object.isolate", &json!({"id": a.0})).unwrap();
assert_eq!(listed(&app), [a]);
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
assert_eq!(listed(&app), [sub], "a sublayer with no sublayers inside lists itself alone");
}
/// Click the item of the Layers panel menu whose text ends with `label`.
fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
let draw = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| menu(app, ui));
out.textures_delta.clear();
out.shapes.iter().find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().ends_with(label) => Some(t.visual_bounding_rect()),
_ => None,
})
};
let Some(r) = draw(app, vec![]) else { panic!("no menu item {label}") };
for e in [egui::Event::PointerMoved(r.center()), button(r.center(), true), button(r.center(), false)] {
draw(app, vec![e]);
}
}
/// In isolation mode the panel menu's Duplicate Selection copies only the rows the panel lists, Hide
/// Others is off, and with a group isolated so is Locate Layer, whose layer row is not listed.
#[test]
fn isolation_keeps_the_panel_menu_to_the_rows_listed() {
let (mut app, [layer, sub, g, b, _, c]) = nested();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let top = NodeId(app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap()["id"].as_u64().unwrap());
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
// A row left highlighted outside the sublayer before the panel shows again.
app.session.active_mut().unwrap().layer_rows = vec![c, b];
click_menu_item(&mut app, &ctx, "Duplicate Selection");
let count = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().children().unwrap().len();
assert_eq!(count(&app, layer), 2, "rectangle c, outside the sublayer, is not copied");
assert_eq!(count(&app, g), 2, "rectangle b is copied");
click_menu_item(&mut app, &ctx, "Hide Others");
assert!(app.session.active().unwrap().doc.node(top).unwrap().visible, "the layer outside the isolated art still shows");
app.ui.layers_panel.layers_only = true;
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
app.session.active_mut().unwrap().layer_rows = vec![];
click_menu_item(&mut app, &ctx, "Locate Layer");
assert!(rows_of(&app).is_empty(), "the sublayer holding the group is not highlighted");
}
/// OK in Delete Selection's question deletes nothing when isolation mode started while it asked and
/// a row it asked about is outside the isolated art, and rows given outside it, as rows dropped on
/// the trash are, are not deleted either.
#[test]
fn isolation_keeps_a_confirmed_delete_to_the_rows_listed() {
let (mut app, [_, sub, g, _, a, c]) = nested();
let uid = app.session.active().unwrap().uid;
app.session.active_mut().unwrap().layer_rows = vec![sub];
assert!(app.run("ui.layerDelete", json!({})).unwrap().is_null(), "it asks first");
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
let ok = json!({"ids": [sub.0], "doc": uid, "confirmed": true});
let err = app.run("ui.layerDelete", ok.clone()).unwrap_err();
assert!(err.contains("the object is outside the isolated group"), "{err}");
assert!(app.session.active().unwrap().doc.node(sub).is_some(), "nothing was deleted");
let err = app.run("ui.layerDelete", json!({"ids": [c.0]})).unwrap_err();
assert!(err.contains("the object is outside the isolated group"), "{err}");
assert!(app.session.active().unwrap().doc.node(c).is_some(), "the rectangle outside the group stays");
// OK with no rows given deletes the highlighted rows the panel lists, inside the sublayer.
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
app.session.active_mut().unwrap().layer_rows = vec![a, c];
app.run("ui.layerDelete", json!({"doc": uid, "confirmed": true})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert!(doc.node(a).is_none() && doc.node(c).is_some(), "only the row inside the sublayer is deleted");
app.session.execute("object.exitIsolation", &json!({"all": true})).unwrap();
app.run("ui.layerDelete", ok).unwrap();
assert!(app.session.active().unwrap().doc.node(sub).is_none());
}
/// A document first shown in isolation mode opens its isolated row, also when the panel showed
/// another document last; shown again with its isolation mode unchanged, it opens nothing.
#[test]
fn isolation_opens_the_isolated_row_of_each_document() {
let (mut app, [_, _, g, ..]) = nested();
let ctx = egui::Context::default();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
frame(&mut app, &ctx, vec![], false);
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
app.session.active_mut().unwrap().layers_open.set(g, false);
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
frame(&mut app, &ctx, vec![], false);
assert!(app.session.active().unwrap().layers_open.contains(g), "the isolated group's row opens");
app.session.active_mut().unwrap().layers_open.set(g, false);
app.session.execute("document.activate", &json!({"index": 1})).unwrap();
frame(&mut app, &ctx, vec![], false);
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
frame(&mut app, &ctx, vec![], false);
assert!(!app.session.active().unwrap().layers_open.contains(g), "a row closed in isolation mode stays closed");
}
/// In isolation mode an Alt-drag of the isolated row onto itself shows no place to drop and copies
/// nothing, and a guide dragged since before isolation mode began goes to no layer outside the
/// isolated art.
#[test]
fn isolation_keeps_drops_on_the_isolated_row_inside_it() {
let (mut app, [layer, sub, g, ..]) = nested();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap();
let ctx = egui::Context::default();
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
// Rows: Sub, g, b, a.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4);
let nodes = |app: &VectorcraftApp| {
let mut n = 0;
app.session.active().unwrap().doc.walk(|_| n += 1);
n
};
let before = nodes(&app);
// The boxes drawn around a row that would take the drop, in one frame with Alt held.
let boxes = |app: &mut VectorcraftApp, e: egui::Event| {
let events = vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT), e];
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let accent = Tokens::get(&ctx).accent;
out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(r) if r.stroke.width == 2.0 && r.stroke.color == accent)).count()
};
let (from, to) = (egui::pos2(150.0, circles[0].y - 6.0), egui::pos2(150.0, circles[0].y + 2.0));
boxes(&mut app, egui::Event::PointerMoved(from));
boxes(&mut app, button(from, true));
boxes(&mut app, egui::Event::PointerMoved(from + vec2(0.0, 6.0)));
let shown = boxes(&mut app, egui::Event::PointerMoved(to)) + boxes(&mut app, egui::Event::PointerMoved(to + vec2(1.0, 0.0)));
assert!(egui::DragAndDrop::has_any_payload(&ctx), "the drag started");
assert_eq!(shown, 0, "no box around the isolated row");
boxes(&mut app, button(to, false));
frame(&mut app, &ctx, vec![], false);
assert_eq!(nodes(&app), before, "nothing was copied");
app.session.execute("object.exitIsolation", &json!({"all": true})).unwrap();
// Rows: Layer 1, its guide (no target circle), Sub, g, b, a, c.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
let guide_row = egui::pos2(150.0, (circles[0].y + circles[1].y) / 2.0);
click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE);
frame(&mut app, &ctx, vec![button(guide_row, true)], false);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(guide_row + vec2(0.0, 6.0))], false);
// Over the group's row the guide would go to the sublayer holding it.
let over = egui::pos2(150.0, circles[2].y);
let shown = boxes(&mut app, egui::Event::PointerMoved(over)) + boxes(&mut app, egui::Event::PointerMoved(over + vec2(1.0, 0.0)));
assert!(shown > 0, "a box around the group's row");
app.session.execute("object.isolate", &json!({"id": g.0})).unwrap();
// Rows: g, b.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let over = egui::pos2(150.0, circles[0].y);
let shown = boxes(&mut app, egui::Event::PointerMoved(over)) + boxes(&mut app, egui::Event::PointerMoved(over + vec2(1.0, 0.0)));
assert!(egui::DragAndDrop::has_any_payload(&ctx), "the guide is still dragged");
assert_eq!(shown, 0, "no box around the isolated group's row, outside which its sublayer is");
frame(&mut app, &ctx, vec![button(over, false)], false);
frame(&mut app, &ctx, vec![], false);
assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].layer, Some(layer), "the guide stays on Layer 1");
}
/// In isolation mode Alt-clicking or Ctrl/Cmd+Alt-clicking an eye, or Alt-clicking a lock, changes
/// no layer outside the isolated art.
#[test]
fn isolation_keeps_alt_clicks_on_eyes_and_locks_inside_it() {
let (mut app, [_, sub, ..]) = nested();
let top = NodeId(app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap()["id"].as_u64().unwrap());
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let click = |app: &mut VectorcraftApp, at: egui::Pos2, mods: egui::Modifiers| click_with(app, &ctx, at, mods);
let (eye, lock) = (egui::pos2(12.0, circles[0].y), egui::pos2(37.0, circles[0].y));
click(&mut app, eye, egui::Modifiers::ALT);
click(&mut app, eye, egui::Modifiers::ALT | egui::Modifiers::COMMAND);
click(&mut app, lock, egui::Modifiers::ALT);
let st = app.session.active().unwrap();
let t = st.doc.node(top).unwrap();
assert!(t.visible && !t.locked && !matches!(t.kind, NodeKind::Layer { preview: false, .. }), "the layer outside the isolated art is unchanged");
}
// ---- rows at every depth (layers, sublayers, groups, objects) ----
/// Layer 1 holding rectangle `c` and a sublayer holding rectangle `a` and a group of
/// rectangle `b`, every row open, nothing selected → (app, [layer, sub, g, b, a, c]): the rows
/// top down.
fn nested() -> (VectorcraftApp, [NodeId; 6]) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
run(&mut app, "file.new", json!({"width": 400, "height": 400}));
let layer = app.session.active().unwrap().doc.layers[0].id;
let c = id(run(&mut app, "shape.rectangle", json!({"x": 300, "y": 0, "width": 20, "height": 20})));
let sub = id(run(&mut app, "layer.newSublayer", json!({"name": "Sub"})));
let a = id(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})));
let b = id(run(&mut app, "shape.rectangle", json!({"x": 100, "y": 0, "width": 20, "height": 20})));
run(&mut app, "select.set", json!({"ids": [b.0]}));
let g = id(run(&mut app, "object.group", json!({})));
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
(app, [layer, sub, g, b, a, c])
}
/// Press and release at `at` with `mods` held, over three frames.
fn click_with(app: &mut VectorcraftApp, ctx: &egui::Context, at: egui::Pos2, mods: egui::Modifiers) {
for e in [egui::Event::PointerMoved(at), button(at, true), button(at, false)] {
let mut out = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(mods), e], ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
}
}
fn rows_of(app: &VectorcraftApp) -> Vec<NodeId> {
app.session.active().unwrap().highlighted_rows()
}
#[test]
fn rows_at_every_depth_are_clickable() {
let (mut app, [layer, sub, g, b, a, c]) = nested();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6, "a row for the layer, the sublayer, the group, both rectangles in it and the one on the layer");
let name = |i: usize| egui::pos2(150.0, circles[i].y);
for (i, row, current) in [(1, sub, sub), (2, g, sub), (3, b, sub), (4, a, sub), (5, c, layer), (0, layer, layer)] {
click_with(&mut app, &ctx, name(i), egui::Modifiers::NONE);
let st = app.session.active().unwrap();
assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![row], Some(current)), "row {i}");
}
// New art goes into the current sublayer once its row is clicked.
click_with(&mut app, &ctx, name(1), egui::Modifiers::NONE);
let n = app.session.execute("shape.ellipse", &json!({"x": 0, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
assert_eq!(app.session.active().unwrap().doc.parent_of(NodeId(n)), Some(sub));
app.session.execute("edit.undo", &json!({})).unwrap();
// Shift-click highlights the range down to the row; Ctrl/Cmd-click toggles one.
click_with(&mut app, &ctx, name(4), egui::Modifiers::SHIFT);
assert_eq!(rows_of(&app), vec![sub, g, b, a]);
click_with(&mut app, &ctx, name(2), egui::Modifiers::COMMAND);
assert_eq!(rows_of(&app), vec![sub, b, a]);
click_with(&mut app, &ctx, name(5), egui::Modifiers::COMMAND);
assert_eq!(rows_of(&app), vec![sub, b, a, c]);
// Delete with the panel's keyboard: the highlighted rows go once OK answers the question the
// sublayer's art asks.
let del = egui::Event::Key { key: egui::Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
frame(&mut app, &ctx, vec![del], false);
crate::dialogs::confirm(&mut app).unwrap();
let d = &app.session.active().unwrap().doc;
assert!(d.node(sub).is_none() && d.node(c).is_none());
assert_eq!(d.layers.len(), 1);
}
/// A layer's ruler guides are rows in it, above its art: a click selects the guide, a drag onto
/// another layer's row moves it there, and a guide on a locked layer is left alone.
#[test]
fn guide_rows_select_and_move_their_guides() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
run(&mut app, "select.none", json!({}));
let second = NodeId(run(&mut app, "layer.new", json!({}))["id"].as_u64().unwrap());
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
// Rows top down: Layer 2, Layer 1, its guide (no target circle), the rectangle.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
let guide_row = egui::pos2(150.0, (circles[1].y + circles[2].y) / 2.0);
let guides = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides)
};
click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE);
assert_eq!(guides(&app), [0], "its row selects it");
// Dragged onto Layer 2's row, it goes on Layer 2, in one undo step.
let undo = app.session.active().unwrap().history.undo.len();
drag(&mut app, &ctx, guide_row, egui::pos2(150.0, circles[0].y), false);
let st = app.session.active().unwrap();
assert_eq!((st.doc.ruler_guides()[0].layer, st.history.undo.len()), (Some(second), undo + 1));
// Now under Layer 2: locked, its row neither selects nor drags it.
run(&mut app, "layer.setProps", json!({"ids": [second.0], "locked": true}));
assert!(guides(&app).is_empty(), "deselected with its layer locked");
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let guide_row = egui::pos2(150.0, (circles[0].y + circles[1].y) / 2.0);
click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE);
assert!(guides(&app).is_empty());
drag(&mut app, &ctx, guide_row, egui::pos2(150.0, circles[2].y), false);
assert_eq!(app.session.active().unwrap().doc.ruler_guides()[0].layer, Some(second));
}
/// A guide row's eye and lock hide and lock that guide alone, each click one undo step: a hidden
/// guide neither shows nor stays selected and its row dims, a locked one shows but can't be
/// selected. They work while the guide's layer is hidden, and a drag down the eye column passes
/// the guide row like any other.
#[test]
fn guide_rows_have_their_own_eye_and_lock() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
// Rows top down: Layer 1, its guide (no target circle), the rectangle.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
let y = (circles[0].y + circles[1].y) / 2.0;
let (name, eye, lock) = (egui::pos2(150.0, y), egui::pos2(12.0, y), egui::pos2(37.0, y));
let st = app.session.active().unwrap();
let (layer, guide) = (st.doc.layers[0].id, st.doc.ruler_guides()[0].id.unwrap());
let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone();
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.guides.clone();
let shown_and_editable = |app: &VectorcraftApp| {
let d = &app.session.active().unwrap().doc;
let g = d.ruler_guide(guide).unwrap();
(d.guide_shown(&g), d.guide_editable(&g))
};
let dimmed = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default());
rows.iter().find(|r| r.guide.is_some()).unwrap().dim
};
click_with(&mut app, &ctx, name, egui::Modifiers::NONE);
assert_eq!(selected(&app), [guide]);
// The eye hides the guide alone, in one step, and deselects it.
let before = undo(&app);
click_with(&mut app, &ctx, eye, egui::Modifiers::NONE);
assert!(!node(&app, guide).visible && node(&app, layer).visible && node(&app, rect).visible);
assert_eq!((undo(&app), shown_and_editable(&app), dimmed(&app)), (before + 1, (false, false), true));
assert!(selected(&app).is_empty(), "a hidden guide can't stay selected");
click_with(&mut app, &ctx, name, egui::Modifiers::NONE);
assert!(selected(&app).is_empty(), "its row doesn't select a hidden guide");
click_with(&mut app, &ctx, eye, egui::Modifiers::NONE);
assert_eq!((node(&app, guide).visible, shown_and_editable(&app), dimmed(&app)), (true, (true, true), false));
// The lock locks it alone: it still shows, and its row no longer selects it.
click_with(&mut app, &ctx, lock, egui::Modifiers::NONE);
assert!(node(&app, guide).locked && !node(&app, layer).locked);
assert_eq!((undo(&app), shown_and_editable(&app), dimmed(&app)), (before + 3, (true, false), false));
click_with(&mut app, &ctx, name, egui::Modifiers::NONE);
assert!(selected(&app).is_empty(), "its row doesn't select a locked guide");
run(&mut app, "edit.undo", json!({}));
assert!(!node(&app, guide).locked);
run(&mut app, "edit.redo", json!({}));
assert!(node(&app, guide).locked);
click_with(&mut app, &ctx, lock, egui::Modifiers::NONE);
assert_eq!(shown_and_editable(&app), (true, true));
// With its layer hidden, the guide's own eye still changes the guide, which shows again with
// the layer only when its own eye is on.
run(&mut app, "layer.setProps", json!({"ids": [layer.0], "visible": false}));
click_with(&mut app, &ctx, eye, egui::Modifiers::NONE);
assert!(!node(&app, guide).visible);
run(&mut app, "layer.setProps", json!({"ids": [layer.0], "visible": true}));
assert_eq!(shown_and_editable(&app), (false, false));
click_with(&mut app, &ctx, eye, egui::Modifiers::NONE);
assert_eq!(shown_and_editable(&app), (true, true));
// A drag down the eye column from the guide row to the rectangle hides both, in one step.
let before = undo(&app);
let below = egui::pos2(12.0, circles[1].y);
let steps = [
vec![egui::Event::PointerMoved(eye)],
vec![button(eye, true)],
vec![egui::Event::PointerMoved(eye + vec2(0.0, 6.0))],
vec![egui::Event::PointerMoved(below)],
vec![button(below, false)],
vec![],
];
for e in steps {
frame(&mut app, &ctx, e, false);
}
assert!(!node(&app, guide).visible && !node(&app, rect).visible && node(&app, layer).visible);
assert_eq!(undo(&app), before + 1, "one undo step");
assert!(!app.session.in_interaction());
run(&mut app, "edit.undo", json!({}));
assert!(node(&app, guide).visible && node(&app, rect).visible);
// Alt-click on the guide's eye or lock acts on the other layers, as on any row in its layer.
run(&mut app, "layer.new", json!({}));
let other = app.session.active().unwrap().doc.layers.iter().map(|l| l.id).find(|l| *l != layer).unwrap();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3, "the new layer, Layer 1 and the rectangle");
let y = (circles[1].y + circles[2].y) / 2.0;
click_with(&mut app, &ctx, egui::pos2(12.0, y), egui::Modifiers::ALT);
assert!(!node(&app, other).visible && node(&app, layer).visible && node(&app, guide).visible);
click_with(&mut app, &ctx, egui::pos2(37.0, y), egui::Modifiers::ALT);
assert!(node(&app, other).locked && !node(&app, layer).locked && !node(&app, guide).locked);
}
/// A guide row dropped on the trash deletes its guide, in one undo step; with no row highlighted
/// the trash deletes the guide its row selected; and a click on a guide row lets go of the
/// highlighted rows, so Delete goes to Edit › Clear, which deletes the guide and not the layer.
#[test]
fn guide_rows_are_deleted_with_the_trash_and_delete() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
for pos in [50, 80] {
run(&mut app, "guide.add", json!({"vertical": true, "pos": pos}));
}
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
// Rows top down: Layer 1, the 80 pt guide, the 50 pt guide, the rectangle.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
let h = (circles[1].y - circles[0].y) / 3.0;
let (row_80, row_50) = (egui::pos2(150.0, circles[0].y + h), egui::pos2(150.0, circles[0].y + 2.0 * h));
let positions = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().iter().map(|g| g.pos).collect::<Vec<_>>();
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let kept = |app: &VectorcraftApp| {
let d = &app.session.active().unwrap().doc;
d.layers.len() == 1 && d.node(rect).is_some()
};
let trash = trash_pos(&mut app, &ctx);
let before = undo(&app);
drag(&mut app, &ctx, row_80, trash, false);
assert_eq!((positions(&app), undo(&app)), (vec![50.0], before + 1));
assert!(kept(&app));
run(&mut app, "edit.undo", json!({}));
assert_eq!(positions(&app).len(), 2);
// The trash, with the guide selected through its row and no row highlighted.
click_with(&mut app, &ctx, row_50, egui::Modifiers::NONE);
assert!(app.session.active().unwrap().highlighted_rows().is_empty());
click_with(&mut app, &ctx, trash, egui::Modifiers::NONE);
assert_eq!(positions(&app), [80.0]);
assert!(kept(&app) && app.ui.dialog.is_none());
run(&mut app, "edit.undo", json!({}));
// Layer 1 highlighted, then the guide's row clicked: the panel lets Delete go.
let layer = app.session.active().unwrap().doc.layers[0].id;
click_with(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::Modifiers::NONE);
assert_eq!(app.session.active().unwrap().highlighted_rows(), [layer]);
click_with(&mut app, &ctx, row_80, egui::Modifiers::NONE);
assert!(app.session.active().unwrap().highlighted_rows().is_empty());
let del = egui::Event::Key { key: egui::Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
frame(&mut app, &ctx, vec![del], false);
assert!(kept(&app) && app.ui.dialog.is_none() && !crate::panels::rows_take_delete(&ctx));
assert_eq!(positions(&app).len(), 2);
app.run("edit.clear", json!({})).unwrap();
assert_eq!(positions(&app), [50.0]);
assert!(kept(&app));
}
/// A plain click on another row lets go of the guide a guide row selected, keeping the selected
/// art, so a guide can be dropped without Ctrl/Cmd-clicking its own row (#7340); a Ctrl/Cmd click
/// on a row adds to the pick and keeps it.
#[test]
fn a_plain_row_click_lets_go_of_the_selected_guide() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let rect = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
// Rows top down: Layer 1, its guide (no target circle), the rectangle.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
let guide_row = egui::pos2(150.0, (circles[0].y + circles[1].y) / 2.0);
let rect_row = egui::pos2(150.0, circles[1].y);
let guides = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides)
};
let art = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.clone();
// Guide, then the rectangle's row: the guide is let go and the rectangle's row highlighted.
click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE);
assert_eq!(guides(&app), [0]);
click_with(&mut app, &ctx, rect_row, egui::Modifiers::NONE);
assert!(guides(&app).is_empty(), "a plain row click drops the guide");
assert_eq!(app.session.active().unwrap().highlighted_rows(), [rect]);
// Art and a guide selected together: a plain row click drops only the guide.
run(&mut app, "select.all", json!({}));
click_with(&mut app, &ctx, guide_row, egui::Modifiers::SHIFT);
assert_eq!((guides(&app), art(&app)), (vec![0], vec![rect]));
click_with(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::Modifiers::NONE);
assert!(guides(&app).is_empty());
assert_eq!(art(&app), [rect], "the selected art stays");
// A Ctrl/Cmd click on a row adds that row to the highlight and keeps the guide.
click_with(&mut app, &ctx, guide_row, egui::Modifiers::NONE);
click_with(&mut app, &ctx, rect_row, egui::Modifiers::COMMAND);
assert_eq!(guides(&app), [0], "a Ctrl/Cmd row click keeps the guide");
}
/// The selection squares drawn: (big ones on rows whose object is selected, small ones on rows
/// holding selected art).
fn squares(app: &mut VectorcraftApp, ctx: &egui::Context) -> (usize, usize) {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let size = |w: f32| {
out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(r) if (r.rect.width() - w).abs() < 0.01 && (r.rect.height() - w).abs() < 0.01 && r.fill != Color32::TRANSPARENT)).count()
};
(size(7.0), size(4.0))
}
#[test]
fn selection_squares_show_and_select_a_rows_art() {
let (mut app, [layer, sub, g, b, a, c]) = nested();
let ctx = egui::Context::default();
assert_eq!(squares(&mut app, &ctx), (0, 0));
app.session.execute("select.set", &json!({"ids": [g.0]})).unwrap();
assert_eq!(squares(&mut app, &ctx), (1, 2), "the group's square, and small ones on the sublayer and the layer");
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let square = |i: usize| circles[i] + vec2(TARGET_X - SQUARE_X, 0.0);
let sel = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.clone();
click_with(&mut app, &ctx, square(4), egui::Modifiers::NONE);
assert_eq!(sel(&app), vec![a]);
click_with(&mut app, &ctx, square(5), egui::Modifiers::SHIFT);
assert_eq!(sel(&app), vec![a, c]);
click_with(&mut app, &ctx, square(1), egui::Modifiers::NONE);
assert_eq!(sel(&app), vec![a, g], "a sublayer's square selects its art");
click_with(&mut app, &ctx, square(0), egui::Modifiers::NONE);
assert_eq!(sel(&app), vec![c, a, g], "a layer's, its sublayers' too");
let _ = (layer, sub, b);
}
/// Alt-click on a layer's or sublayer's name makes it current, as a plain click does, and selects
/// its art, as its selection square does. On another row, beside the name or with Shift or Ctrl/Cmd
/// held too, it is the click without Alt.
#[test]
fn alt_clicking_a_layer_name_selects_its_art() {
let (mut app, [layer, sub, g, _, a, c]) = nested();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
// The rows' names start right of the thumbnail; the sublayer's row is one level deeper.
let name = |i: usize, depth: f32| egui::pos2(2.0 * COLUMN + 2.0 + 6.0 + depth * INDENT + 16.0 + 30.0, circles[i].y);
let state = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
(st.selection.objects.clone(), st.highlighted_rows(), st.current_layer())
};
click_with(&mut app, &ctx, name(1, 1.0), egui::Modifiers::ALT);
assert_eq!(state(&app), (vec![a, g], vec![sub], Some(sub)), "the sublayer's art");
click_with(&mut app, &ctx, name(0, 0.0), egui::Modifiers::ALT);
assert_eq!(state(&app), (vec![c, a, g], vec![layer], Some(layer)), "the layer's, its sublayer's too");
app.session.execute("select.none", &json!({})).unwrap();
// A group's row, the space right of a layer's name, Alt+Shift and Ctrl/Cmd+Alt select nothing.
click_with(&mut app, &ctx, name(2, 2.0), egui::Modifiers::ALT);
assert_eq!(state(&app), (vec![], vec![g], Some(sub)), "a group's row");
click_with(&mut app, &ctx, circles[0] - vec2(40.0, 0.0), egui::Modifiers::ALT);
assert_eq!(state(&app), (vec![], vec![layer], Some(layer)), "beside the name");
click_with(&mut app, &ctx, name(1, 1.0), egui::Modifiers::ALT | egui::Modifiers::SHIFT);
assert_eq!(state(&app).0, vec![], "Alt+Shift");
click_with(&mut app, &ctx, name(0, 0.0), egui::Modifiers::ALT | egui::Modifiers::COMMAND);
assert_eq!(state(&app).0, vec![], "Ctrl/Cmd+Alt");
}
/// Alt-click right of a one-letter layer name, inside the wider rename target, selects nothing.
#[test]
fn alt_clicking_beside_a_short_layer_name_selects_nothing() {
let (mut app, [_, sub, ..]) = nested();
app.session.execute("layer.setProps", &json!({"ids": [sub.0], "name": "I"})).unwrap();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
// The sublayer's name area starts here; "I" ends about 5 points in, the rename target 20 points in.
let name_left = 2.0 * COLUMN + 2.0 + 6.0 + INDENT + 40.0;
click_with(&mut app, &ctx, egui::pos2(name_left + 14.0, circles[1].y), egui::Modifiers::ALT);
let st = app.session.active().unwrap();
assert_eq!((st.selection.objects.clone(), st.current_layer()), (vec![], Some(sub)));
}
#[test]
fn eye_and_lock_toggle_nested_rows_and_drag_down_the_column() {
let (mut app, [_, sub, g, b, a, _]) = nested();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let (eye, lock) = (|i: usize| egui::pos2(12.0, circles[i].y), |i: usize| egui::pos2(37.0, circles[i].y));
let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone();
click_with(&mut app, &ctx, eye(3), egui::Modifiers::NONE);
assert!(!node(&app, b).visible, "an object in a group in a sublayer hides");
click_with(&mut app, &ctx, eye(3), egui::Modifiers::NONE);
click_with(&mut app, &ctx, lock(2), egui::Modifiers::NONE);
assert!(node(&app, g).locked, "a group locks");
click_with(&mut app, &ctx, lock(2), egui::Modifiers::NONE);
// Ctrl/Cmd-click a layer's eye: Outline, and back.
click_with(&mut app, &ctx, eye(1), egui::Modifiers::COMMAND);
assert!(matches!(node(&app, sub).kind, NodeKind::Layer { preview: false, .. }));
click_with(&mut app, &ctx, eye(1), egui::Modifiers::COMMAND);
assert!(matches!(node(&app, sub).kind, NodeKind::Layer { preview: true, .. }));
// Drag down the eye column from the group to the rectangle below: all three hide, one step.
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = undo(&app);
let steps = [
vec![egui::Event::PointerMoved(eye(2))],
vec![button(eye(2), true)],
vec![egui::Event::PointerMoved(eye(2) + vec2(0.0, 6.0))],
vec![egui::Event::PointerMoved(eye(3))],
vec![egui::Event::PointerMoved(eye(4))],
vec![button(eye(4), false)],
vec![],
];
for e in steps {
frame(&mut app, &ctx, e, false);
}
assert!(!node(&app, g).visible && !node(&app, b).visible && !node(&app, a).visible);
assert!(node(&app, sub).visible, "rows it didn't pass stay");
assert_eq!(undo(&app), before + 1, "one undo step");
assert!(!app.session.in_interaction());
app.session.execute("edit.undo", &json!({})).unwrap();
assert!(node(&app, g).visible && node(&app, b).visible && node(&app, a).visible);
}
#[test]
fn triangles_open_and_close_rows_and_alt_does_everything_inside() {
let (mut app, [layer, sub, ..]) = nested();
let ctx = egui::Context::default();
let count = |app: &mut VectorcraftApp| frame(app, &ctx, vec![], false).0.len();
assert_eq!(count(&mut app), 6);
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let triangle = |depth: f32, y: f32| egui::pos2(2.0 * COLUMN + 8.0 + depth * INDENT + 7.0, y);
// Close the sublayer: its group, the group's rectangle and its own rectangle go.
click_with(&mut app, &ctx, triangle(1.0, circles[1].y), egui::Modifiers::NONE);
assert_eq!(count(&mut app), 3);
// Alt-click the layer's: everything inside closes, and opens again.
click_with(&mut app, &ctx, triangle(0.0, circles[0].y), egui::Modifiers::ALT);
assert_eq!(count(&mut app), 1);
click_with(&mut app, &ctx, triangle(0.0, circles[0].y), egui::Modifiers::ALT);
assert_eq!(count(&mut app), 6);
// Show Layers Only (Panel Options).
app.ui.layers_panel.layers_only = true;
assert_eq!(count(&mut app), 2);
app.ui.layers_panel = PanelOptions { row_size: ROW_LARGE, ..Default::default() };
let (c, _) = frame(&mut app, &ctx, vec![], false);
assert!((c[1].y - c[0].y - ROW_LARGE).abs() < 0.5, "large rows");
let _ = (layer, sub);
}
// ---- Search All and the Filter ----
/// Layer 1 holding a path, a rectangle, type reading "Sky line", a group of an ellipse with an
/// effect, a compound path, a guide, an embedded and a linked image and a ruler guide, and on top
/// a sublayer "Sub" holding a hidden path named "Sky" and a locked path; only Layer 1 open and
/// nothing selected → (app, the rows' ids by name).
fn kinds() -> (VectorcraftApp, HashMap<&'static str, NodeId>) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
let star = |app: &mut VectorcraftApp, x: u32| id(run(app, "shape.star", json!({"cx": x, "cy": 50, "radius1": 20, "radius2": 10})));
run(&mut app, "file.new", json!({"width": 400, "height": 400}));
let mut ids = HashMap::from([("layer", app.session.active().unwrap().doc.layers[0].id)]);
ids.insert("path", star(&mut app, 50));
ids.insert("rect", id(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 100, "width": 20, "height": 20}))));
ids.insert("text", id(run(&mut app, "text.create", json!({"x": 10, "y": 200, "text": "Sky line"}))));
let ellipse = id(run(&mut app, "shape.ellipse", json!({"x": 100, "y": 100, "width": 20, "height": 20})));
run(&mut app, "effect.apply", json!({"effect": "distort.twist", "ids": [ellipse.0]}));
run(&mut app, "select.set", json!({"ids": [ellipse.0]}));
ids.insert("group", id(run(&mut app, "object.group", json!({}))));
ids.insert("ellipse", ellipse);
let parts = [star(&mut app, 150), star(&mut app, 160)];
run(&mut app, "select.set", json!({"ids": [parts[0].0, parts[1].0]}));
ids.insert("compound", id(run(&mut app, "object.compoundPath.make", json!({}))));
let guide = id(run(&mut app, "shape.arc", json!({"x1": 0, "y1": 300, "x2": 50, "y2": 350})));
run(&mut app, "select.set", json!({"ids": [guide.0]}));
run(&mut app, "view.guides.make", json!({}));
ids.insert("guide", guide);
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
let mut png = vec![];
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 40, 40, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let placed = |app: &mut VectorcraftApp, p: serde_json::Value| NodeId(run(app, "file.place", p)["ids"][0].as_u64().unwrap());
ids.insert("embedded", placed(&mut app, json!({"name": "pic.png", "dataBase64": vectorcraft_format::base64_encode(&png)})));
// One file for every test that calls this, written by the first.
static LINKED: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
let file = LINKED.get_or_init(|| {
let file = vectorcraft_testkit::temp_dir("layers-filter").join("linked.png");
std::fs::write(&file, &png).unwrap();
file
});
ids.insert("linked", placed(&mut app, json!({"path": file.to_string_lossy()})));
ids.insert("sub", id(run(&mut app, "layer.newSublayer", json!({"name": "Sub"}))));
let hidden = star(&mut app, 250);
run(&mut app, "layer.setProps", json!({"ids": [hidden.0], "name": "Sky", "visible": false}));
let locked = star(&mut app, 300);
run(&mut app, "layer.setProps", json!({"ids": [locked.0], "locked": true}));
ids.extend([("hidden", hidden), ("locked", locked)]);
run(&mut app, "select.none", json!({}));
(app, ids)
}
/// The rows [`list_rows`] lists for `query` and `filter`, by their names in `ids` ("ruler guide"
/// for a guide's row).
fn listed(app: &VectorcraftApp, ids: &HashMap<&'static str, NodeId>, query: &str, filter: &Filter) -> Vec<&'static str> {
let st = app.session.active().unwrap();
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), query, filter);
let name = |r: &Row| match r.guide {
Some(_) => "ruler guide",
None => ids.iter().find(|(_, id)| **id == r.node.id).map_or("?", |(name, _)| *name),
};
rows.iter().map(name).collect()
}
fn only(k: ObjectKind) -> Filter {
Filter { objects: vec![k], layers: vec![] }
}
/// Each object kind keeps exactly the rows of that kind, with the rows holding them, open or
/// closed.
#[test]
fn each_object_kind_keeps_its_rows_and_the_rows_holding_them() {
let (app, ids) = kinds();
for (k, want) in [
(ObjectKind::Paths, vec!["layer", "sub", "locked", "hidden", "compound", "path"]),
(ObjectKind::Shapes, vec!["layer", "group", "ellipse", "rect"]),
(ObjectKind::Text, vec!["layer", "text"]),
(ObjectKind::Images, vec!["layer", "linked", "embedded"]),
(ObjectKind::Effects, vec!["layer", "group", "ellipse"]),
(ObjectKind::Groups, vec!["layer", "group"]),
(ObjectKind::LinkedFiles, vec!["layer", "linked"]),
(ObjectKind::Guides, vec!["layer", "ruler guide", "guide"]),
] {
assert_eq!(listed(&app, &ids, "", &only(k)), want, "{k:?}");
}
}
/// By Layer keeps the rows that are locked or hidden themselves: in a hidden, locked sublayer a
/// row stays only for its own lock or eye. Two choices in a section take either; a choice in
/// each section takes rows that are both.
#[test]
fn row_states_keep_locked_or_hidden_rows_and_combine_with_kinds() {
let (mut app, ids) = kinds();
let f = |objects: Vec<ObjectKind>, layers: Vec<RowState>| Filter { objects, layers };
assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Hidden])), ["layer", "sub", "hidden"]);
assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Locked])), ["layer", "sub", "locked"]);
assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Locked, RowState::Hidden])), ["layer", "sub", "locked", "hidden"]);
assert_eq!(listed(&app, &ids, "", &f(vec![ObjectKind::Text, ObjectKind::Images], vec![])), ["layer", "linked", "embedded", "text"]);
assert_eq!(listed(&app, &ids, "", &f(vec![ObjectKind::Paths], vec![RowState::Hidden])), ["layer", "sub", "hidden"]);
assert!(listed(&app, &ids, "", &f(vec![ObjectKind::Shapes], vec![RowState::Hidden])).is_empty());
// Once Sub is hidden and locked, the rows in it stay only for their own lock or eye.
app.session.execute("layer.setProps", &json!({"ids": [ids["sub"].0], "visible": false, "locked": true})).unwrap();
assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Hidden])), ["layer", "sub", "hidden"]);
assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Locked])), ["layer", "sub", "locked"]);
}
/// The filter and the search combine: a row stays when its name holds the text and the filter
/// keeps it, or when it holds such a row.
#[test]
fn the_filter_combines_with_the_search() {
let (app, ids) = kinds();
assert_eq!(listed(&app, &ids, "sky", &Filter::default()), ["layer", "sub", "hidden", "text"]);
assert_eq!(listed(&app, &ids, "sky", &only(ObjectKind::Text)), ["layer", "text"]);
assert_eq!(listed(&app, &ids, "sky", &Filter { objects: vec![], layers: vec![RowState::Hidden] }), ["layer", "sub", "hidden"]);
assert!(listed(&app, &ids, "sky", &only(ObjectKind::Groups)).is_empty());
}
/// (target circles, lit 24 pt buttons) one frame of the panel draws.
fn circles_and_lit_buttons(app: &mut VectorcraftApp, ctx: &egui::Context) -> (usize, usize) {
let lit = Tokens::get(ctx).tool_active;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let circles = out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Circle(cs) if cs.radius == 5.0)).count();
let buttons =
out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(r) if r.fill == lit && (r.rect.width() - 24.0).abs() < 0.01)).count();
(circles, buttons)
}
/// `ui.layersFilter` has the panel list its rows again at once and lights the Filter button
/// while a filter is on; clearing it lists every row again. The document, its open rows and the
/// selection stay as they were.
#[test]
fn the_panel_lists_its_rows_again_when_the_filter_changes() {
let (mut app, ids) = kinds();
app.session.execute("select.set", &json!({"ids": [ids["rect"].0]})).unwrap();
let ctx = egui::Context::default();
let before = circles_and_lit_buttons(&mut app, &ctx);
assert_eq!(before.1, 0, "the Filter button is not lit");
let st = app.session.active().unwrap();
let (revision, open) = (st.revision, st.layers_open.generation());
let r = app.run("ui.layersFilter", json!({"objects": ["text"]})).unwrap();
assert_eq!(r, json!({"objects": ["text"], "layers": []}));
assert_eq!(circles_and_lit_buttons(&mut app, &ctx), (2, 1), "Layer 1 and the type; the button is lit");
app.run("ui.layersFilter", json!({"layers": ["hidden"]})).unwrap();
assert_eq!(circles_and_lit_buttons(&mut app, &ctx), (0, 1), "no type is hidden");
app.run("ui.layersFilter", json!({"objects": [], "layers": []})).unwrap();
assert_eq!(circles_and_lit_buttons(&mut app, &ctx), before, "every row again");
let st = app.session.active().unwrap();
assert_eq!((st.revision, st.layers_open.generation(), st.selection.objects.clone()), (revision, open, vec![ids["rect"]]));
}
/// Clicks in the Filter button's popup tick a kind and a state, and a second click clears the
/// kind, while the popup stays open; Clear All turns the filter off.
#[test]
fn the_filter_popup_ticks_kinds_and_states_and_clear_all_turns_the_filter_off() {
let (mut app, _) = kinds();
let ctx = egui::Context::default();
// The Filter button: the 24 pt square lit while a filter is on.
app.run("ui.layersFilter", json!({"layers": ["locked"]})).unwrap();
let lit = Tokens::get(&ctx).tool_active;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let filter = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Rect(r) if r.fill == lit && (r.rect.width() - 24.0).abs() < 0.01 => Some(r.rect.center()),
_ => None,
})
.unwrap();
app.run("ui.layersFilter", json!({"layers": []})).unwrap();
click_with(&mut app, &ctx, filter, egui::Modifiers::NONE);
// Where the popup draws `label` (after a frame for it to settle).
let at = |app: &mut VectorcraftApp, label: &str| {
super::super::tests_appearance::frame_events(&ctx, app, vec![], show);
let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], show);
texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} not in {texts:?}"))
};
let text = at(&mut app, "Text");
click_with(&mut app, &ctx, text, egui::Modifiers::NONE);
assert_eq!(app.ui.layers_filter, Filter { objects: vec![ObjectKind::Text], layers: vec![] });
let hidden = at(&mut app, "Hidden");
click_with(&mut app, &ctx, hidden, egui::Modifiers::NONE);
assert_eq!(app.ui.layers_filter, Filter { objects: vec![ObjectKind::Text], layers: vec![RowState::Hidden] });
click_with(&mut app, &ctx, text, egui::Modifiers::NONE);
assert_eq!(app.ui.layers_filter, Filter { objects: vec![], layers: vec![RowState::Hidden] }, "a second click takes it out");
let clear = at(&mut app, "Clear All");
click_with(&mut app, &ctx, clear, egui::Modifiers::NONE);
assert!(!app.ui.layers_filter.is_on());
}
/// `ui.layersFilter` reads its lists by name in the popup's order, keeps a list it is not given,
/// and changes nothing when a list holds anything else.
#[test]
fn the_filter_command_reads_its_lists_by_name() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let r = app.run("ui.layersFilter", json!({"objects": ["guides", "paths", "paths"], "layers": ["hidden"]})).unwrap();
assert_eq!(r, json!({"objects": ["paths", "guides"], "layers": ["hidden"]}));
let r = app.run("ui.layersFilter", json!({"layers": []})).unwrap();
assert_eq!(r, json!({"objects": ["paths", "guides"], "layers": []}));
for bad in [json!({"objects": ["paths", "layers"]}), json!({"objects": "paths"}), json!({"objects": [], "layers": ["visible"]})] {
let e = app.run("ui.layersFilter", bad.clone()).unwrap_err();
let key = if bad["layers"].is_null() { "objects" } else { "layers" };
assert!(e.starts_with(&format!("`{key}` must be an array of these names: ")), "{bad}: {e}");
}
assert_eq!(app.run("ui.layersFilter", json!({})).unwrap(), json!({"objects": ["paths", "guides"], "layers": []}), "unchanged");
}
#[test]
fn dragging_a_layer_into_the_empty_space_under_the_rows_moves_it_to_the_bottom() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({"top": true})).unwrap();
let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [bottom, top] = ids(&app)[..] else { panic!("two layers") };
let ctx = egui::Context::default();
// Rows: the top layer, the bottom layer, then empty space.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
drag(&mut app, &ctx, egui::pos2(150.0, circles[0].y), egui::pos2(150.0, circles[1].y + 3.0 * ROW_MEDIUM), false);
assert_eq!(ids(&app), vec![top, bottom], "the top layer is now the bottom one");
}
/// #8237: with Alt, the top layer dropped on the top edge of its own row copies above itself, and
/// the bottom layer dropped in the empty space under the list copies below itself. Without Alt,
/// neither drop changes anything.
#[test]
fn alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({"top": true})).unwrap();
let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [bottom, top] = ids(&app)[..] else { panic!("two layers") };
let ctx = egui::Context::default();
// Rows: the top layer, the bottom layer, then empty space.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
let row = |y: f32| egui::pos2(150.0, y);
let top_edge = |y: f32| egui::pos2(150.0, y - ROW_MEDIUM * 0.4);
let under = |y: f32| egui::pos2(150.0, y + 3.0 * ROW_MEDIUM);
drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), false);
drag(&mut app, &ctx, row(circles[1].y), under(circles[1].y), false);
assert_eq!(ids(&app), vec![bottom, top], "moved onto their own places, nothing changes");
drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), true);
let after = ids(&app);
assert_eq!((after.len(), &after[..2]), (3, &[bottom, top][..]), "a copy above the top layer");
// Rows: the copy, the top layer, the bottom layer, then empty space.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
drag(&mut app, &ctx, row(circles[2].y), under(circles[2].y), true);
let after = ids(&app);
assert_eq!((after.len(), after[1]), (4, bottom), "a copy below the bottom layer");
}
/// #8237: a document's only layer, Alt-dragged up onto its own row or down into the empty space,
/// is copied above or below itself.
#[test]
fn a_lone_layer_alt_dragged_up_or_down_is_copied() {
for (up, at) in [(true, 0), (false, 1)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [only] = ids(&app)[..] else { panic!("one layer") };
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 1);
let y = circles[0].y;
let to = if up { y - ROW_MEDIUM * 0.4 } else { y + 3.0 * ROW_MEDIUM };
drag(&mut app, &ctx, egui::pos2(150.0, y), egui::pos2(150.0, to), true);
let after = ids(&app);
assert_eq!((after.len(), after[at]), (2, only), "up: {up}");
}
}
#[test]
fn dragging_rows_moves_them_into_other_layers_and_alt_copies() {
let (mut app, [layer, sub, g, _, a, c]) = nested();
let ctx = egui::Context::default();
let l2 = NodeId(app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap()["id"].as_u64().unwrap());
// Rows: Top, Layer 1, Sub, g, b, a, c.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 7);
let name = |i: usize| egui::pos2(150.0, circles[i].y);
let parent = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.parent_of(id);
// Rectangle a onto the middle of the Top layer's row: into it.
drag(&mut app, &ctx, name(5), name(0), false);
assert_eq!(parent(&app, a), Some(l2));
// Rows: Top, a, Layer 1, Sub, g, b, c. The sublayer onto the upper edge of Layer 1's row:
// above it, a top-level layer now.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 7);
drag(&mut app, &ctx, egui::pos2(150.0, circles[3].y), egui::pos2(150.0, circles[2].y - ROW_MEDIUM * 0.4), false);
assert_eq!(parent(&app, sub), None);
let d = &app.session.active().unwrap().doc;
assert_eq!(d.layers.iter().map(|l| l.id).collect::<Vec<_>>(), vec![layer, sub, l2]);
// Rows: Top, a, Sub, g, b, Layer 1, c. Alt-drag the group into Layer 1: a copy goes there,
// the group stays.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let count = app.session.active().unwrap().doc.node_count();
drag(&mut app, &ctx, egui::pos2(150.0, circles[3].y), egui::pos2(150.0, circles[5].y), true);
assert_eq!(parent(&app, g), Some(sub));
assert_eq!(app.session.active().unwrap().doc.node_count(), count + 2, "the group and its rectangle, copied");
let _ = (layer, c);
}
/// One headless frame of the panel with `events` (Alt held when `alt`) → the cursor it asks for,
/// and the cursor bitmap it hands the OS, if any.
fn cursor_frame(
app: &mut VectorcraftApp,
ctx: &egui::Context,
events: Vec<egui::Event>,
alt: bool,
) -> (egui::CursorIcon, Option<egui::CustomCursorImage>) {
let mut events = events;
events.insert(0, egui::Event::ModifiersChanged(egui::Modifiers { alt, ..Default::default() }));
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
(out.platform_output.cursor_icon, out.platform_output.cursor_image)
}
/// #8217: a row dragged over the list shows the copy cursor while Alt is held, as the drop then
/// copies, and the grabbing hand otherwise, following Alt as it goes down and up mid-drag. The copy
/// cursor is the panels' add cursor (#8241): where the window shows glyphs as OS cursors (Windows,
/// X11, which have no system copy cursor winit can show), the white arrow with a plus.
#[test]
fn alt_shows_the_copy_cursor_while_rows_are_dragged() {
let (mut app, _) = nested();
let ctx = egui::Context::default();
// Rows: Layer 1, Sub, g, b, a, c.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
let (from, to) = (egui::pos2(150.0, circles[2].y), egui::pos2(150.0, circles[5].y));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)], false);
frame(&mut app, &ctx, vec![button(from, true)], false);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + vec2(0.0, 6.0))], false);
let glyph = crate::cursors::add_cursor_is_a_glyph(&app).then(|| app.canvas.cursors.get(vectorcraft_tools::Cursor::GroupSelection, 1.0)).flatten();
assert_eq!(cursor_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)], false), (egui::CursorIcon::Grabbing, None), "a move");
assert_eq!(cursor_frame(&mut app, &ctx, vec![], true), (egui::CursorIcon::Copy, glyph), "Alt held: the drop copies");
assert_eq!(cursor_frame(&mut app, &ctx, vec![], false), (egui::CursorIcon::Grabbing, None), "Alt let go: a move again");
cursor_frame(&mut app, &ctx, vec![button(to, false)], false);
assert_ne!(cursor_frame(&mut app, &ctx, vec![], true).0, egui::CursorIcon::Copy, "no drag, no copy cursor");
}
/// The selected-art square copies with Alt as rows do; off the list (the trash, New Layer) Alt
/// copies nothing, and guide rows keep their own cursor.
#[test]
fn drag_cursor_shows_a_copy_only_where_the_drop_copies() {
let (copy, grabbing) = (Some(egui::CursorIcon::Copy), Some(egui::CursorIcon::Grabbing));
for drag in [LayersDrag::Rows(vec![NodeId(1)]), LayersDrag::Art] {
assert_eq!(super::drag_cursor(&drag, true, true), copy);
assert_eq!(super::drag_cursor(&drag, false, true), grabbing);
assert_eq!(super::drag_cursor(&drag, true, false), grabbing, "off the list");
}
assert_eq!(super::drag_cursor(&LayersDrag::Guides(vec![0]), true, true), None);
}
/// An Intertwine group's row takes a dragged row inside it, as a group's does, and the object
/// becomes a member; a row that can't be intertwined gets no inside box and goes beside it.
#[test]
fn dragging_a_row_into_an_intertwine_adds_a_member() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
let rect = |app: &mut VectorcraftApp, x: f64| {
NodeId(run(app, "shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap())
};
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
let (a, b) = (rect(&mut app, 0.0), rect(&mut app, 10.0));
run(&mut app, "select.set", json!({"ids": [a.0, b.0]}));
let g = NodeId(run(&mut app, "object.intertwine.make", json!({}))["id"].as_u64().unwrap());
let (d, e) = (rect(&mut app, 100.0), rect(&mut app, 110.0));
run(&mut app, "select.set", json!({"ids": [d.0, e.0]}));
let g2 = NodeId(run(&mut app, "object.intertwine.make", json!({}))["id"].as_u64().unwrap());
let c = rect(&mut app, 50.0);
run(&mut app, "select.none", json!({}));
let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone();
let ids = |nodes: Option<&Vec<Arc<Node>>>| nodes.map(|c| c.iter().map(|n| n.id).collect::<Vec<_>>()).unwrap_or_default();
let layer = doc(&app).layers[0].id;
let ctx = egui::Context::default();
// Rows: Layer 1, c, the second Intertwine group, the first.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4);
// c onto the middle of the first Intertwine group's row: into it, on top.
drag(&mut app, &ctx, egui::pos2(150.0, circles[1].y), egui::pos2(150.0, circles[3].y + 3.0), false);
assert_eq!(ids(doc(&app).node(g).and_then(Node::children)), [a, b, c]);
// Rows: Layer 1, the second Intertwine group, the first (open on its moved row), c, b, a. The
// second just below the middle of the first's row: no nested Intertwine groups, so the row has
// no inside box and it goes below the group, beside it.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
drag(&mut app, &ctx, egui::pos2(150.0, circles[1].y), egui::pos2(150.0, circles[2].y + 3.0), false);
let now = doc(&app);
assert_eq!(ids(now.node(layer).and_then(Node::children)), [g2, g]);
assert_eq!(ids(now.node(g2).and_then(Node::children)), [d, e]);
assert_eq!(ids(now.node(g).and_then(Node::children)), [a, b, c]);
// Rows: Layer 1, the first (open), c, b, a, the second. Held over member b's row, the second
// shows no line or box, as it can't go beside a member either; over the first's own row it
// shows the line below it.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 6);
let accent = Tokens::get(&ctx).accent;
let from = egui::pos2(150.0, circles[5].y);
let marks_over = |app: &mut VectorcraftApp, to: egui::Pos2| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from)], false);
frame(app, &ctx, vec![button(from, true)], false);
frame(app, &ctx, vec![egui::Event::PointerMoved(from + vec2(0.0, 6.0))], false);
frame(app, &ctx, vec![egui::Event::PointerMoved(to)], false);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let marks = out
.shapes
.iter()
.filter(|c| match &c.shape {
egui::Shape::LineSegment { stroke, .. } => stroke.color == accent,
egui::Shape::Rect(r) => r.stroke.color == accent,
_ => false,
})
.count();
frame(app, &ctx, vec![egui::Event::PointerMoved(from)], false);
frame(app, &ctx, vec![button(from, false)], false);
frame(app, &ctx, vec![], false);
marks
};
let beside_member = marks_over(&mut app, egui::pos2(150.0, circles[3].y + 3.0));
let beside_group = marks_over(&mut app, egui::pos2(150.0, circles[1].y + 3.0));
assert_eq!(beside_group, beside_member + 1);
assert_eq!(ids(doc(&app).node(g).and_then(Node::children)), [a, b, c]);
}
/// One headless frame of the panel on a short screen (300 × 260) with `events` (Alt held when
/// `alt`): for every row name painted inside the list's view, its center, and the view.
fn short_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, alt: bool) -> (HashMap<String, egui::Pos2>, egui::Rect) {
timed_short_frame(app, ctx, events, alt, 1.0 / 60.0)
}
/// [`short_frame`] for a frame that comes `dt` seconds after the one before it.
fn timed_short_frame(
app: &mut VectorcraftApp,
ctx: &egui::Context,
events: Vec<egui::Event>,
alt: bool,
dt: f32,
) -> (HashMap<String, egui::Pos2>, egui::Rect) {
let mut events = events;
events.insert(0, egui::Event::ModifiersChanged(egui::Modifiers { alt, ..Default::default() }));
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 260.0));
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), predicted_dt: dt, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
// The rows' eye column dividers are drawn clipped to the list's view.
let border = Tokens::get(ctx).input_border;
let view = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::LineSegment { stroke, .. } if stroke.color == border && c.clip_rect.height() < screen.height() => Some(c.clip_rect),
_ => None,
})
.unwrap_or(egui::Rect::NOTHING);
let mut names = HashMap::new();
for c in &out.shapes {
if let egui::Shape::Text(t) = &c.shape
&& t.galley.text().starts_with("Layer ")
&& view.contains_rect(c.clip_rect)
{
let center = t.pos + t.galley.size() / 2.0;
if c.clip_rect.contains(center) {
names.insert(t.galley.text().to_string(), center);
}
}
}
(names, view)
}
/// A document of 30 empty layers named `Layer 1` (the bottom one) to `Layer 30` (the top one):
/// more rows than [`short_frame`]'s list shows.
fn thirty_layers() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
for i in 2..=30 {
app.session.execute("layer.new", &json!({"top": true, "name": format!("Layer {i}")})).unwrap();
}
app
}
/// The layers' names, bottom first.
fn layer_names(app: &VectorcraftApp) -> Vec<String> {
app.session.active().unwrap().doc.layers.iter().map(|l| l.display_name()).collect()
}
/// Hold the button still at `at` (a row is held) until `name`'s row is fully in view; → its center.
fn hold_until(app: &mut VectorcraftApp, ctx: &egui::Context, at: egui::Pos2, name: &str, alt: bool) -> Option<egui::Pos2> {
short_frame(app, ctx, vec![egui::Event::PointerMoved(at)], alt);
for _ in 0..500 {
let (names, view) = short_frame(app, ctx, vec![], alt);
if let Some(&c) = names.get(name)
&& c.y - ROW_MEDIUM / 2.0 >= view.top()
&& c.y + ROW_MEDIUM / 2.0 <= view.bottom()
{
return Some(c);
}
}
None
}
#[test]
fn rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view() {
let mut app = thirty_layers();
let ctx = egui::Context::default();
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let (names, view) = short_frame(&mut app, &ctx, vec![], false);
assert!(names.contains_key("Layer 30") && !names.contains_key("Layer 1"), "the list overflows: {names:?}");
let before = (undo(&app), layer_names(&app));
// Layer 30 held still just above the list's bottom edge: the list scrolls down to Layer 1.
let grab = names["Layer 30"];
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], false);
short_frame(&mut app, &ctx, vec![button(grab, true)], false);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab + vec2(0.0, 6.0))], false);
let edge = egui::pos2(grab.x, view.bottom() - 3.0);
let target = hold_until(&mut app, &ctx, edge, "Layer 1", false).expect("Layer 1 scrolled into view while the row was held");
assert_eq!((undo(&app), layer_names(&app)), before, "scrolling alone changes nothing");
// Dropped on the upper edge of Layer 1's row: above it.
let drop = target - vec2(0.0, ROW_MEDIUM * 0.4);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)], false);
short_frame(&mut app, &ctx, vec![button(drop, false)], false);
let names = layer_names(&app);
assert_eq!(&names[..2], ["Layer 1", "Layer 30"], "{names:?}");
assert_eq!(undo(&app), before.0 + 1);
// Released, the list stays where it is with the pointer in the top band.
let (rows, _) = short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(drop.x, view.top() + 3.0))], false);
for _ in 0..10 {
assert_eq!(short_frame(&mut app, &ctx, vec![], false).0, rows, "no scrolling after the release");
}
// Layer 2, Alt-dragged to the top edge: the list scrolls back up, and dropped on the lower edge
// of Layer 29's row a copy goes below it.
let grab = rows["Layer 2"];
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], true);
short_frame(&mut app, &ctx, vec![button(grab, true)], true);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab - vec2(0.0, 6.0))], true);
let (_, view) = short_frame(&mut app, &ctx, vec![], true);
let target = hold_until(&mut app, &ctx, egui::pos2(grab.x, view.top() + 3.0), "Layer 29", true).expect("Layer 29 scrolled into view");
let drop = target + vec2(0.0, ROW_MEDIUM * 0.4);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)], true);
short_frame(&mut app, &ctx, vec![button(drop, false)], true);
let names = layer_names(&app);
assert_eq!(names.len(), 31);
assert_eq!((names[28].as_str(), names[30].as_str()), ("Layer 28", "Layer 29"), "{names:?}");
assert!(names[29].starts_with("Layer 2"), "the copy, below Layer 29: {names:?}");
assert_eq!(names[2], "Layer 2", "the original stays");
}
#[test]
fn a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate() {
// Layer 30 held just above the list's bottom edge for half a second, drawn in `frames` frames,
// then moved beside the list, where the scrolling stops: → where the rows in view came to rest.
let held = |frames: u16| {
let mut app = thirty_layers();
let ctx = egui::Context::default();
let (names, view) = short_frame(&mut app, &ctx, vec![], false);
let grab = names["Layer 30"];
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], false);
short_frame(&mut app, &ctx, vec![button(grab, true)], false);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab + vec2(0.0, 6.0))], false);
let dt = 0.5 / f32::from(frames);
timed_short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(grab.x, view.bottom() - 3.0))], false, dt);
for _ in 1..frames {
timed_short_frame(&mut app, &ctx, vec![], false, dt);
}
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(view.right() + 2.0, view.bottom() - 3.0))], false);
let mut rows = HashMap::new();
for _ in 0..120 {
rows = short_frame(&mut app, &ctx, vec![], false).0;
}
// (Layer 30's dimmed copy follows the pointer.)
rows.remove("Layer 30");
rows
};
let (at_30, at_120) = (held(15), held(60));
assert!(!at_30.contains_key("Layer 29") && !at_30.is_empty(), "the list scrolled: {at_30:?}");
assert_eq!(at_30.len(), at_120.len(), "{at_30:?} {at_120:?}");
for (name, a) in &at_30 {
let b = at_120.get(name).unwrap_or_else(|| panic!("{name} is in view at 30 frames a second only: {at_120:?}"));
assert!((a.y - b.y).abs() < 2.0, "{name}: {a:?} at 30 frames a second, {b:?} at 120");
}
}
#[test]
fn the_list_scrolls_only_for_rows_held_over_it() {
let mut app = thirty_layers();
let ctx = egui::Context::default();
let (rows, view) = short_frame(&mut app, &ctx, vec![], false);
// The pointer in the bottom band with no button down: nothing scrolls.
let edge = egui::pos2(150.0, view.bottom() - 3.0);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)], false);
for _ in 0..20 {
assert_eq!(short_frame(&mut app, &ctx, vec![], false).0, rows, "hovering scrolls nothing");
}
// A row held in the bottom band beside the list (right of its view): nothing scrolls, and
// the release there moves nothing.
let before = layer_names(&app);
let grab = rows["Layer 30"];
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)], false);
short_frame(&mut app, &ctx, vec![button(grab, true)], false);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab + vec2(0.0, 6.0))], false);
let beside = egui::pos2(view.right() + 2.0, view.bottom() - 3.0);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(beside)], false);
// (Layer 30's dimmed copy follows the pointer, so another row is compared.)
assert!(rows.contains_key("Layer 27"));
for _ in 0..20 {
assert_eq!(short_frame(&mut app, &ctx, vec![], false).0.get("Layer 27"), rows.get("Layer 27"), "held beside the list");
}
short_frame(&mut app, &ctx, vec![button(beside, false)], false);
short_frame(&mut app, &ctx, vec![], false);
assert_eq!(layer_names(&app), before);
// The eye column dragged down into the band: a column drag, which scrolls nothing.
let eye = egui::pos2(12.0, grab.y);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(eye)], false);
short_frame(&mut app, &ctx, vec![button(eye, true)], false);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(eye + vec2(0.0, 6.0))], false);
short_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(egui::pos2(12.0, view.bottom() - 3.0))], false);
for _ in 0..20 {
assert_eq!(short_frame(&mut app, &ctx, vec![], false).0, rows, "a column drag");
}
short_frame(&mut app, &ctx, vec![button(egui::pos2(12.0, view.bottom() - 3.0), false)], false);
}
/// The centres of the bottom bar's buttons, right to left from under the right end of its top
/// divider: Delete, New Layer, New Sublayer, Make/Release Clipping Mask, Locate Object.
fn bar_buttons(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<egui::Pos2> {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let divider = Tokens::get(ctx).divider;
let corner = out
.shapes
.iter()
.rev()
.find_map(|c| match &c.shape {
egui::Shape::LineSegment { points, stroke } if stroke.color == divider => Some(points[1]),
_ => None,
})
.unwrap();
let step = 24.0 + ctx.global_style().spacing.item_spacing.x;
(0..5).map(|k| corner + vec2(-12.0 - k as f32 * step, 15.0)).collect()
}
/// How many texts reading `s` the frame after `events` paints.
fn texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, s: &str) -> usize {
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == s)).count()
}
/// Drag the row at `a` to `b` and drop it there. Returns how many times its `name` was painted
/// while it hung over `b`.
fn drag_row(app: &mut VectorcraftApp, ctx: &egui::Context, a: egui::Pos2, b: egui::Pos2, name: &str) -> usize {
frame(app, ctx, vec![egui::Event::PointerMoved(a)], false);
frame(app, ctx, vec![button(a, true)], false);
frame(app, ctx, vec![egui::Event::PointerMoved(a + vec2(0.0, 6.0))], false);
let shown = texts(app, ctx, vec![egui::Event::PointerMoved(b)], name);
frame(app, ctx, vec![button(b, false)], false);
frame(app, ctx, vec![], false);
shown
}
#[test]
fn dropping_rows_on_new_layer_duplicates_them() {
let (mut app, first, _) = two_rects();
let second = app.session.execute("layer.new", &json!({"name": "Top"})).unwrap()["id"].as_u64().map(NodeId).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let layers = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
// Rows top down: Top, Layer 1 (expanded: its two rectangles).
let (c, _) = frame(&mut app, &ctx, vec![], false);
let buttons = bar_buttons(&mut app, &ctx);
// Layer 1 dropped on New Layer: a copy of it right above it.
let shown = drag_row(&mut app, &ctx, egui::pos2(150.0, c[1].y), buttons[1], "Layer 1");
assert_eq!(shown, 2, "the row and its ghost under the pointer");
let after = layers(&app);
assert_eq!(after.len(), 3);
assert_eq!((after[0], after[2]), (first, second));
assert_eq!(app.session.active().unwrap().doc.node(after[1]).unwrap().children().map(Vec::len), Some(2));
assert_eq!(texts(&mut app, &ctx, vec![], "Layer 1"), 1, "the ghost is gone after the drop");
// One undo step takes the copy away.
app.session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layers(&app), vec![first, second]);
// The other bottom-bar buttons are no drop targets.
drag_row(&mut app, &ctx, egui::pos2(150.0, c[0].y), buttons[2], "Top");
assert_eq!(layers(&app), vec![first, second]);
}
/// Cmd+Alt+L is New Layer Options… by default. On Windows and Linux the key is Ctrl+Alt+L, and on
/// macOS it is Option+Command+L. Cmd+L is still New Layer. No other command, tool or panel has
/// Cmd+Alt+L by default.
#[test]
fn cmd_alt_l_is_new_layer_options() {
use crate::shortcut_editor::{command_for_key, default_command_shortcut};
assert_eq!(default_command_shortcut("ui.newLayer"), Some("Cmd+Alt+L"));
assert_eq!(command_for_key("Cmd+Alt+L"), Some("ui.newLayer"));
assert_eq!(command_for_key("Cmd+L"), Some("layer.new"));
let chord = crate::shortcuts::parse("Cmd+Alt+L").expect("parses");
assert_eq!((chord.modifiers, chord.logical_key), (egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::L));
let shown = crate::menus::pretty_shortcut("Cmd+Alt+L");
assert_eq!(shown, if cfg!(target_os = "macos") { "⌥⌘L" } else { "Ctrl+Alt+L" });
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let listed = app.run("shortcuts.list", json!({"query": "ui.newLayer"})).unwrap();
let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| (r["label"].clone(), r["default"].clone())).collect();
assert_eq!(rows, [(json!("New Layer Options…"), json!("Cmd+Alt+L"))], "Keyboard Shortcuts lists it");
assert_eq!(app.run("shortcuts.conflicts", json!({})).unwrap(), json!([]), "no other default has the key");
}
/// Cmd+Alt+L, pressed through the shortcut handler, opens Layer Options for a new layer as an
/// Alt-click on the panel's New Layer button does, and no layer is added until OK. OK adds the
/// layer above the current layer, as after the Alt-click, and Cancel adds none. Cmd+L still adds
/// a layer without the dialog.
#[test]
fn cmd_alt_l_opens_new_layer_options_as_alt_clicking_new_layer_does() {
fn press(app: &mut VectorcraftApp, modifiers: egui::Modifiers) {
let ctx = egui::Context::default();
let ev = egui::Event::Key { key: egui::Key::L, physical_key: None, pressed: true, repeat: false, modifiers };
let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx()));
out.textures_delta.clear();
}
/// Layer 1 with two rectangles under a layer named Top, with Layer 1 current.
fn two_layers() -> VectorcraftApp {
let (mut app, first, _) = two_rects();
app.session.execute("layer.new", &json!({"name": "Top"})).unwrap();
app.session.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
app
}
let names = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.display_name()).collect::<Vec<_>>();
let dialog = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| (d.kind.clone(), d.fields.clone()));
let mut keyed = two_layers();
press(&mut keyed, egui::Modifiers::COMMAND | egui::Modifiers::ALT);
let mut clicked = two_layers();
let ctx = egui::Context::default();
let new_layer = bar_buttons(&mut clicked, &ctx)[1];
click_with(&mut clicked, &ctx, new_layer, egui::Modifiers::ALT);
let opened = dialog(&keyed).expect("the key opens a dialog");
assert_eq!((opened.0.as_str(), opened.1.get("mode")), ("layerOptions", Some(&json!("new"))));
assert_eq!(dialog(&clicked), Some(opened), "the key opens what the Alt-click opens");
assert_eq!(names(&keyed), ["Layer 1", "Top"], "no layer is added until OK");
for app in [&mut keyed, &mut clicked] {
crate::dialogs::confirm(app).unwrap();
}
assert_eq!(names(&keyed), ["Layer 1", "Layer 3", "Top"]);
assert_eq!(names(&clicked), names(&keyed));
// Cancel adds no layer.
press(&mut keyed, egui::Modifiers::COMMAND | egui::Modifiers::ALT);
assert!(keyed.ui.dialog.is_some());
crate::dialogs::cancel(&mut keyed);
assert!(keyed.ui.dialog.is_none());
assert_eq!(names(&keyed), ["Layer 1", "Layer 3", "Top"]);
press(&mut keyed, egui::Modifiers::COMMAND);
assert!(keyed.ui.dialog.is_none(), "Cmd+L opens no dialog");
assert_eq!(names(&keyed).len(), 4);
}
/// Ctrl/Cmd+Alt-click on the New Layer button adds a layer directly below the current layer, and
/// on the New Sublayer button a sublayer under the current layer's contents, without a dialog and
/// in one undo step each. A plain click still adds the layer above the current layer and the
/// sublayer on top, and an Alt-click still opens Layer Options.
#[test]
fn cmd_alt_click_puts_a_new_layer_below_and_a_new_sublayer_at_the_bottom() {
let (mut app, first, [a, b]) = two_rects();
app.session.execute("layer.new", &json!({"name": "Top"})).unwrap();
app.session.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
let ctx = egui::Context::default();
let names = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.display_name()).collect::<Vec<_>>();
let undos = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let cmd_alt = egui::Modifiers::COMMAND | egui::Modifiers::ALT;
// Clicks the bottom bar's button `k` (1: New Layer, 2: New Sublayer) with `mods` held.
let click = |app: &mut VectorcraftApp, k: usize, mods: egui::Modifiers| {
let at = bar_buttons(app, &ctx)[k];
click_with(app, &ctx, at, mods);
};
let before = undos(&app);
click(&mut app, 1, cmd_alt);
assert!(app.ui.dialog.is_none(), "no dialog");
assert_eq!(names(&app), ["Layer 3", "Layer 1", "Top"]);
assert_eq!(undos(&app), before + 1);
app.session.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
click(&mut app, 2, cmd_alt);
assert!(app.ui.dialog.is_none(), "no dialog");
let d = &app.session.active().unwrap().doc;
let kids: Vec<NodeId> = d.node(first).unwrap().children().unwrap().iter().map(|n| n.id).collect();
assert_eq!(kids.len(), 3);
assert!(d.node(kids[0]).is_some_and(Node::is_layer), "the sublayer is under the rectangles");
assert_eq!(kids[1..], [a, b]);
assert_eq!(undos(&app), before + 2);
// A plain click: above the current layer, and the sublayer on top.
app.session.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
click(&mut app, 2, egui::Modifiers::NONE);
let d = &app.session.active().unwrap().doc;
assert!(d.node(first).unwrap().children().unwrap().last().is_some_and(|n| n.is_layer()), "a plain click puts it on top");
app.session.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
click(&mut app, 1, egui::Modifiers::NONE);
assert_eq!(names(&app), ["Layer 3", "Layer 1", "Layer 6", "Top"]);
click(&mut app, 1, egui::Modifiers::ALT);
assert!(app.ui.dialog.is_some(), "Alt-click opens Layer Options");
}
#[test]
fn the_selected_art_square_drags_the_selection_to_another_layer() {
let (mut app, [_, sub, g, _, a, c]) = nested();
let ctx = egui::Context::default();
app.session.execute("select.set", &json!({"ids": [a.0, g.0]})).unwrap();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let square = |i: usize| circles[i] + vec2(TARGET_X - SQUARE_X, 0.0);
// From the sublayer's (small) square onto Layer 1's row.
drag(&mut app, &ctx, square(1), egui::pos2(150.0, circles[0].y), false);
let d = &app.session.active().unwrap().doc;
assert_eq!(d.node(d.layers[0].id).unwrap().children().unwrap().iter().map(|n| n.id).collect::<Vec<_>>(), vec![c, sub, a, g]);
assert_eq!(app.session.active().unwrap().selection.objects.len(), 2, "still selected");
}
/// The undo steps of the active document.
fn undo_len(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
/// Drags from `a` to `b` with the secondary and then the middle button, each of which must carry
/// nothing and leave the document and its undo steps as they were (`state` reads what the drag
/// would change); then the same drag with the primary button, which must change `state`.
fn only_the_primary_button_drags<S: PartialEq + std::fmt::Debug>(
app: &mut VectorcraftApp,
ctx: &egui::Context,
(a, b): (egui::Pos2, egui::Pos2),
state: impl Fn(&VectorcraftApp) -> S,
what: &str,
) {
let (before, undo) = (state(app), undo_len(app));
for pointer in [egui::PointerButton::Secondary, egui::PointerButton::Middle] {
let held = drag_by(app, ctx, a, b, false, pointer);
assert!(!held, "{what}: a {pointer:?} drag carries nothing");
assert_eq!(state(app), before, "{what}: a {pointer:?} drag changes nothing");
assert_eq!(undo_len(app), undo, "{what}: a {pointer:?} drag records no undo step");
}
drag_by(app, ctx, a, b, false, egui::PointerButton::Primary);
assert_ne!(state(app), before, "{what}: the primary button drags");
}
/// Only the primary button drags in the panel: a drag with the secondary or middle button moves no
/// row, guide or selected art, hides or locks no row and moves no appearance, and records no undo
/// step. The secondary button still opens a row's menu.
#[test]
fn only_the_primary_button_drags_rows_guides_art_columns_and_appearances() {
let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone();
let rows = |app: &mut VectorcraftApp, ctx: &egui::Context| frame(app, ctx, vec![], false).0;
// A row, onto the middle of another layer's row.
let (mut app, [.., a, _]) = nested();
app.session.execute("layer.new", &json!({"top": true, "name": "Top"})).unwrap();
let ctx = egui::Context::default();
let c = rows(&mut app, &ctx);
let parent = |app: &VectorcraftApp| app.session.active().unwrap().doc.parent_of(a);
only_the_primary_button_drags(&mut app, &ctx, (egui::pos2(150.0, c[5].y), egui::pos2(150.0, c[0].y)), parent, "a row");
// A guide row, onto another layer's row.
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
run(&mut app, "select.none", json!({}));
run(&mut app, "layer.new", json!({}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
let c = rows(&mut app, &ctx);
let guide_row = egui::pos2(150.0, (c[1].y + c[2].y) / 2.0);
let layer = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides()[0].layer;
only_the_primary_button_drags(&mut app, &ctx, (guide_row, egui::pos2(150.0, c[0].y)), layer, "a guide row");
// The selected-art square, onto the layer's row.
let (mut app, [_, _, g, _, a, _]) = nested();
app.session.execute("select.set", &json!({"ids": [a.0, g.0]})).unwrap();
let ctx = egui::Context::default();
let c = rows(&mut app, &ctx);
let kids = |app: &VectorcraftApp| {
let d = &app.session.active().unwrap().doc;
d.node(d.layers[0].id).unwrap().children().unwrap().iter().map(|n| n.id).collect::<Vec<_>>()
};
let square = c[1] + vec2(TARGET_X - SQUARE_X, 0.0);
only_the_primary_button_drags(&mut app, &ctx, (square, egui::pos2(150.0, c[0].y)), kids, "the selected-art square");
// Down the eye and the lock columns, from the group's row to a rectangle's.
for (x, what) in [(12.0, "the eye column"), (37.0, "the lock column")] {
let (mut app, [_, _, g, b, a, _]) = nested();
let ctx = egui::Context::default();
let c = rows(&mut app, &ctx);
let marks = move |app: &VectorcraftApp| [g, b, a].map(|id| (node(app, id).visible, node(app, id).locked));
only_the_primary_button_drags(&mut app, &ctx, (egui::pos2(x, c[2].y), egui::pos2(x, c[4].y)), marks, what);
}
// A target circle, onto another row's circle.
let (mut app, _, [a, b]) = two_rects();
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
let ctx = egui::Context::default();
let c = rows(&mut app, &ctx);
let opacities = move |app: &VectorcraftApp| [a, b].map(|id| node(app, id).opacity);
only_the_primary_button_drags(&mut app, &ctx, (c[2], c[1]), opacities, "a target circle");
// A secondary click on a row opens its menu.
let (mut app, _, _) = two_rects();
let ctx = egui::Context::default();
let c = frame(&mut app, &ctx, vec![], false).0;
let at = egui::pos2(150.0, c[0].y);
let right = egui::PointerButton::Secondary;
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
assert_eq!(texts(&mut app, &ctx, vec![], "Collect for Export"), 1, "the row menu is open");
}
#[test]
fn the_panel_menu_lists_every_operation() {
let (mut app, _) = nested();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let texts = super::super::tests_appearance::frame_events(&ctx, &mut app, vec![], menu);
for label in [
"New Layer…",
"New Sublayer…",
"Duplicate Selection",
"Delete Selection",
"Options for Selection…",
"Make/Release Clipping Mask",
"Enter Isolation Mode",
"Locate Object",
"Save Selection",
"Merge Selected",
"Flatten Artwork",
"Collect in New Layer",
"Collect for Export",
"Release to Layers (Sequence)",
"Release to Layers (Build)",
"Reverse Order",
"Template",
"Show All Layers",
"Preview All Layers",
"Unlock All Layers",
"Paste Remembers Layers",
"Panel Options…",
] {
assert!(texts.iter().any(|(t, _)| t.trim() == label), "{label} missing from {texts:?}");
}
}
/// With Show Layers Only on, Locate Object becomes Locate Layer in the panel menu and a row's
/// menu, and the bottom bar's Locate button highlights the sublayer holding the selected art,
/// opening the layer around it. Off, the button highlights the art's own row.
#[test]
fn with_show_layers_only_locate_object_becomes_locate_layer() {
let (mut app, [layer, sub, _, b, _, _]) = nested();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let shown = |app: &mut VectorcraftApp, events: Vec<egui::Event>, f: fn(&mut VectorcraftApp, &mut egui::Ui)| {
super::super::tests_appearance::frame_events(&ctx, app, events, f).into_iter().map(|(t, _)| t.trim().to_string()).collect::<Vec<_>>()
};
let has = |texts: &[String], s: &str| texts.iter().any(|t| t == s);
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let off = shown(&mut app, vec![], menu);
assert!(has(&off, "Locate Object") && !has(&off, "Locate Layer"), "{off:?}");
let locate = |app: &mut VectorcraftApp| {
let at = bar_buttons(app, &ctx)[4];
click_with(app, &ctx, at, egui::Modifiers::NONE);
};
locate(&mut app);
assert_eq!(rows_of(&app), vec![b], "off: the art's own row");
app.ui.layers_panel.layers_only = true;
let on = shown(&mut app, vec![], menu);
assert!(has(&on, "Locate Layer") && !has(&on, "Locate Object"), "{on:?}");
app.session.active_mut().unwrap().layers_open.set(layer, false);
shown(&mut app, vec![], show);
locate(&mut app);
assert_eq!(rows_of(&app), vec![sub], "on: the sublayer holding the art");
shown(&mut app, vec![], show);
assert!(app.session.active().unwrap().layers_open.contains(layer), "the layer around the sublayer opens");
assert!(has(&shown(&mut app, vec![], show), "Sub"), "the sublayer's row shows");
// A row's menu says Locate Layer too.
let c = frame(&mut app, &ctx, vec![], false).0;
let at = egui::pos2(150.0, c[0].y);
let right = egui::PointerButton::Secondary;
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let row_menu = shown(&mut app, vec![], show);
assert!(has(&row_menu, "Locate Layer") && !has(&row_menu, "Locate Object"), "{row_menu:?}");
}
/// Locate Layer or Locate Object run again on the row it already highlighted reveals that row
/// again: the layers around it that were closed since open, once per Locate.
#[test]
fn a_repeated_locate_reveals_the_row_it_already_highlighted() {
let (mut app, [layer, sub, g, b, _, _]) = nested();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let draw = |app: &mut VectorcraftApp| {
super::super::tests_appearance::frame_events(&ctx, app, vec![], show).into_iter().map(|(t, _)| t.trim().to_string()).collect::<Vec<_>>()
};
let open = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().layers_open.contains(id);
let close = |app: &mut VectorcraftApp, ids: &[NodeId]| {
for id in ids {
app.session.active_mut().unwrap().layers_open.set(*id, false);
}
};
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
// Locate Layer: the sublayer stays highlighted while its layer is closed, and Locate Layer again opens it.
app.ui.layers_panel.layers_only = true;
app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap();
draw(&mut app);
assert_eq!(rows_of(&app), vec![sub]);
close(&mut app, &[layer]);
assert!(!draw(&mut app).iter().any(|t| t == "Sub"), "the closed layer hides the sublayer");
app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap();
assert!(draw(&mut app).iter().any(|t| t == "Sub"), "the sublayer's row shows again");
assert!(open(&app, layer), "the layer around the sublayer opens again");
assert_eq!(rows_of(&app), vec![sub]);
// Once per Locate: a later frame leaves a layer closed after that alone.
close(&mut app, &[layer]);
draw(&mut app);
assert!(!open(&app, layer), "a frame without a Locate opens nothing");
// Locate Object: the same for the object's row inside a closed sublayer and group.
app.ui.layers_panel.layers_only = false;
app.session.execute("layer.locate", &json!({})).unwrap();
draw(&mut app);
assert_eq!(rows_of(&app), vec![b]);
close(&mut app, &[sub, g]);
draw(&mut app);
app.session.execute("layer.locate", &json!({})).unwrap();
draw(&mut app);
assert!(open(&app, layer) && open(&app, sub) && open(&app, g), "the layers and group around the object open again");
assert_eq!(rows_of(&app), vec![b]);
}
/// ≡ › Save Selection lists the saved selections: choosing one recalls it, Update Selection
/// makes it hold the selected objects, and Save Selection… opens the name dialog.
#[test]
fn the_save_selection_submenu_recalls_updates_and_saves_selections() {
let (mut app, _, [a, b]) = two_rects();
app.run("select.set", json!({"ids": [a.0]})).unwrap();
app.run("select.save", json!({"name": "Left"})).unwrap();
app.run("select.set", json!({"ids": [b.0]})).unwrap();
app.run("select.save", json!({"name": "Right"})).unwrap();
app.run("select.none", json!({})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| super::super::tests_appearance::frame_events(&ctx, app, events, menu);
// Opens the submenu (when closed) and clicks the item labeled `label` in it.
let choose = |app: &mut VectorcraftApp, label: &str| {
let at = |texts: &[(String, egui::Rect)], label: &str| texts.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center());
let mut texts = frame(app, vec![]);
if at(&texts, label).is_none() {
let sub = at(&texts, "Save Selection").expect("the Save Selection submenu");
for e in [egui::Event::PointerMoved(sub), button(sub, true), button(sub, false)] {
frame(app, vec![e]);
}
texts = frame(app, vec![]);
}
let item = at(&texts, label).unwrap_or_else(|| panic!("{label} missing from {texts:?}"));
for e in [egui::Event::PointerMoved(item), button(item, true), button(item, false)] {
frame(app, vec![e]);
}
};
let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.clone();
choose(&mut app, "Left");
assert_eq!(selected(&app), vec![a], "choosing a name recalls it");
app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap();
choose(&mut app, "Update Selection");
let saved = app.session.active().unwrap().doc.saved_selections.clone();
assert_eq!(saved.iter().map(|s| (s.name.as_str(), s.objects.len())).collect::<Vec<_>>(), vec![("Left", 2), ("Right", 1)]);
assert!(app.ui.dialog.is_none());
choose(&mut app, "Save Selection…");
let d = app.ui.dialog.clone().expect("Save Selection dialog");
assert_eq!((d.str("__command"), d.str("name")), ("select.save".into(), "Selection 1".into()));
}
/// With the dock collapsed, Layers shows in a floating flyout: its rows work there too.
#[test]
fn rows_work_in_the_floating_flyout() {
let (mut app, [_, sub, ..]) = nested();
app.ui.dock_collapsed = true;
app.ui.open_panel = Some("layers".into());
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.05;
let input = egui::RawInput { time: Some(time), events, screen_rect: Some(screen), ..Default::default() };
let mut out = ctx.run_ui(input, |ui| crate::panel_docking::show(app, ui));
out.textures_delta.clear();
let mut c: Vec<egui::Pos2> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Circle(cs) if cs.radius == 5.0 => Some(cs.center),
_ => None,
})
.collect();
c.sort_by(|a, b| a.y.total_cmp(&b.y));
c
};
for _ in 0..3 {
frame(&mut app, vec![]);
}
let circles = frame(&mut app, vec![]);
assert_eq!(circles.len(), 6, "every row shows in the flyout");
assert!(circles.iter().all(|c| screen.contains(*c)));
let at = circles[1] - vec2(120.0, 0.0);
frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]);
frame(&mut app, vec![button(at, false)]);
frame(&mut app, vec![]);
assert_eq!(rows_of(&app), vec![sub]);
assert_eq!(app.session.active().unwrap().current_layer(), Some(sub));
}
// ---- Locate Selected Objects (Panel Options) ----
/// A layer of `n` groups of one path each, with only the layer open, as a document opens →
/// (app, layer, the paths in stacking order, so the first is in the bottom row). The path in
/// group `i` is named `Path {i}`.
fn groups_of_one(n: usize) -> (VectorcraftApp, NodeId, Vec<NodeId>) {
use vectorcraft_doc::Appearance;
use vectorcraft_geom::{Rect, shapes};
let mut d = Document::new(1000.0, 1000.0);
let mut groups = vec![];
let mut paths = vec![];
for i in 0..n {
let r = Rect::new(0.0, i as f64, 1.0, i as f64 + 1.0);
let mut path = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default());
path.name = Some(format!("Path {i}"));
paths.push(path.id);
groups.push(Arc::new(Node::group(d.alloc_id(), vec![Arc::new(path)])));
}
*Arc::make_mut(&mut d.layers[0]).children_mut().unwrap() = groups;
let layer = d.layers[0].id;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.add_document(d, None);
(app, layer, paths)
}
/// One frame of the panel in a 300 × 800 window, one second after the previous frame: the
/// centers of the target circles, top row first, and whether `name` is drawn.
fn tall_frame(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) -> (Vec<egui::Pos2>, bool) {
let time = ctx.input(|i| i.time) + 1.0;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 800.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == name));
let mut circles: Vec<egui::Pos2> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Circle(cs) if cs.radius == 5.0 => Some(cs.center),
_ => None,
})
.collect();
circles.sort_by(|a, b| a.y.total_cmp(&b.y));
(circles, found)
}
/// Without Locate Selected Objects (the default), an object selected outside the panel leaves
/// the open rows and the scroll position as they were.
#[test]
fn without_the_option_a_selection_leaves_the_rows_and_the_scroll_as_they_were() {
let (mut app, layer, paths) = groups_of_one(500);
let ctx = egui::Context::default();
let (before, _) = tall_frame(&mut app, &ctx, "");
// The bottom row's path: out of view, in a closed group.
app.session.execute("select.set", &json!({"ids": [paths[0].0]})).unwrap();
for _ in 0..4 {
let (circles, found) = tall_frame(&mut app, &ctx, "Path 0");
assert!(!found);
assert_eq!(circles, before, "nothing opens or scrolls");
}
let st = app.session.active().unwrap();
let group = st.doc.parent_of(paths[0]).unwrap();
assert!(st.layers_open.contains(layer) && !st.layers_open.contains(group));
}
/// With Locate Selected Objects on, an object selected outside the panel is located as Locate
/// Object locates it: the layer and the group around it open and its row is scrolled into
/// view. The highlighted row stays as it was.
#[test]
fn with_the_option_a_selected_object_is_opened_and_scrolled_into_view() {
let (mut app, layer, paths) = groups_of_one(500);
app.ui.layers_panel.locate_selected = true;
let ctx = egui::Context::default();
let top = app.session.active().unwrap().doc.parent_of(paths[499]).unwrap();
app.session.execute("layer.highlight", &json!({"ids": [top.0]})).unwrap();
tall_frame(&mut app, &ctx, "");
expand(&mut app, &json!({"ids": [layer.0], "open": false})).unwrap();
assert_eq!(tall_frame(&mut app, &ctx, "").0.len(), 1, "only the layer's row");
app.session.execute("select.set", &json!({"ids": [paths[0].0]})).unwrap();
let found = (0..4).any(|_| tall_frame(&mut app, &ctx, "Path 0").1);
let st = app.session.active().unwrap();
let group = st.doc.parent_of(paths[0]).unwrap();
assert!(st.layers_open.contains(layer) && st.layers_open.contains(group), "the layer and the group open");
assert!(found, "the row is scrolled into view");
assert_eq!(st.highlighted_rows(), [top], "the highlighted row stays");
}
/// With Locate Selected Objects on, the panel's own clicks locate nothing: a Shift-click
/// highlights the rows down to the one it clicks, and Shift-clicking selection squares selects
/// art in a closed sublayer without opening it. An object then selected outside the panel is
/// located, and the highlighted rows stay.
#[test]
fn with_the_option_the_panels_own_clicks_locate_nothing() {
let (mut app, [layer, sub, g, b, _, c]) = nested();
app.ui.layers_panel.locate_selected = true;
expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap();
let ctx = egui::Context::default();
// Rows top down: Layer 1, Sub (closed), c.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
let name = |i: usize| egui::pos2(150.0, circles[i].y);
let square = |i: usize| circles[i] + vec2(TARGET_X - SQUARE_X, 0.0);
click_with(&mut app, &ctx, name(0), egui::Modifiers::NONE);
click_with(&mut app, &ctx, name(2), egui::Modifiers::SHIFT);
assert_eq!(rows_of(&app), [layer, sub, c], "both rows clicked and the one between them");
click_with(&mut app, &ctx, square(2), egui::Modifiers::SHIFT);
click_with(&mut app, &ctx, square(1), egui::Modifiers::SHIFT);
let st = app.session.active().unwrap();
assert!(st.selection.objects.len() >= 3 && st.selection.objects.contains(&c), "c and Sub's art are selected");
let (after, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(after, circles, "no row opens and nothing scrolls");
assert_eq!(rows_of(&app), [layer, sub, c]);
// Selected outside the panel: b's sublayer and group open, and the rows stay highlighted.
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 6);
assert_eq!(rows_of(&app), [layer, sub, c]);
}
/// With Locate Selected Objects on, a selection the panel menu changes is not located: Delete
/// Selection deletes the highlighted object, and the object left selected stays in its closed
/// sublayer and group.
#[test]
fn with_the_option_the_panel_menu_locates_nothing() {
let (mut app, [_, sub, g, b, _, c]) = nested();
app.ui.layers_panel.locate_selected = true;
app.session.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
frame(&mut app, &ctx, vec![], false);
expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap();
app.session.execute("layer.highlight", &json!({"ids": [c.0]})).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "Layer 1, Sub (closed) and c");
let menu_frame = |app: &mut VectorcraftApp, events| super::super::tests_appearance::frame_events(&ctx, app, events, menu);
let at = menu_frame(&mut app, vec![]).iter().find(|(t, _)| t.trim() == "Delete Selection").map(|(_, r)| r.center()).unwrap();
for e in [egui::Event::PointerMoved(at), button(at, true), button(at, false)] {
menu_frame(&mut app, vec![e]);
}
assert_eq!(app.session.active().unwrap().selection.objects, [b], "c is deleted and b stays selected");
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 2, "Sub stays closed");
}
/// With Locate Selected Objects on, a saved selection recalled from the panel menu's Save
/// Selection submenu is not located: the recalled object stays in its closed sublayer and group.
#[test]
fn with_the_option_a_selection_recalled_from_the_panel_menu_is_not_located() {
let (mut app, [_, sub, g, b, _, c]) = nested();
app.ui.layers_panel.locate_selected = true;
app.run("select.set", json!({"ids": [b.0]})).unwrap();
app.run("select.save", json!({"name": "Kept"})).unwrap();
app.run("select.set", json!({"ids": [c.0]})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
frame(&mut app, &ctx, vec![], false);
expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "Layer 1, Sub (closed) and c");
let menu_frame = |app: &mut VectorcraftApp, events| super::super::tests_appearance::frame_events(&ctx, app, events, menu);
let at = |texts: &[(String, egui::Rect)], label: &str| texts.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center());
let sub_menu = at(&menu_frame(&mut app, vec![]), "Save Selection").expect("the Save Selection submenu");
for e in [egui::Event::PointerMoved(sub_menu), button(sub_menu, true), button(sub_menu, false)] {
menu_frame(&mut app, vec![e]);
}
let item = at(&menu_frame(&mut app, vec![]), "Kept").expect("the saved selection's item");
for e in [egui::Event::PointerMoved(item), button(item, true), button(item, false)] {
menu_frame(&mut app, vec![e]);
}
assert_eq!(app.session.active().unwrap().selection.objects, [b], "the saved selection is recalled");
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "Sub stays closed");
}
/// With Locate Selected Objects on, the object selected in a document that becomes active is
/// not located; an object selected after that is. Neither document has highlighted rows, so
/// the switch reveals no row of its own.
#[test]
fn with_the_option_a_document_becoming_active_locates_nothing() {
let (mut app, [_, sub, g, b, a, _]) = nested();
app.ui.layers_panel.locate_selected = true;
app.session.execute("layer.highlight", &json!({"ids": []})).unwrap();
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![], false);
expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
frame(&mut app, &ctx, vec![], false);
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "b's sublayer and group stay closed");
app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 5, "a's sublayer opens");
}
/// With Locate Selected Objects on, the copies an Alt-drag selects are located once the drag
/// ends, not while it lasts.
#[test]
fn with_the_option_a_selection_made_during_a_drag_is_located_when_it_ends() {
let (mut app, [_, sub, g, b, ..]) = nested();
app.ui.layers_panel.locate_selected = true;
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![], false);
expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap();
app.session.begin_interaction("Move").unwrap();
for i in 1..=3 {
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, i * 10, 0], "copy": true})).unwrap();
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "nothing opens while the drag lasts");
}
app.session.commit_interaction().unwrap();
let st = app.session.active().unwrap();
let copy = st.selection.objects.last().copied().unwrap();
assert!(copy != b && st.doc.parent_of(copy) == Some(g), "the copy is selected, in b's group");
assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 7, "Sub and the group open on the copy's row");
}
/// With Locate Selected Objects on, art selected outside the panel in another layer is
/// located: the selection makes that layer the active one, and the panel scrolls to the art's
/// row, not to the layer's row.
#[test]
fn with_the_option_the_located_object_is_revealed_instead_of_its_active_layer() {
let (mut app, layer, paths) = groups_of_one(500);
app.ui.layers_panel.locate_selected = true;
app.session.execute("layer.new", &json!({})).unwrap();
assert_ne!(app.session.active().unwrap().current_layer(), Some(layer));
let ctx = egui::Context::default();
tall_frame(&mut app, &ctx, "");
app.session.execute("select.set", &json!({"ids": [paths[0].0]})).unwrap();
assert_eq!(app.session.active().unwrap().current_layer(), Some(layer), "the path's layer is the active one");
let found = (0..4).any(|_| tall_frame(&mut app, &ctx, "Path 0").1);
let st = app.session.active().unwrap();
let group = st.doc.parent_of(paths[0]).unwrap();
assert!(st.layers_open.contains(group), "the group opens");
assert!(found, "the path's row is scrolled into view");
}
/// With Locate Selected Objects and Show Layers Only on, art selected outside the panel has no
/// row, so the panel scrolls to the row of the layer that the selection makes the active one.
#[test]
fn with_the_option_and_show_layers_only_the_active_layer_is_revealed() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.ui.layers_panel.locate_selected = true;
app.ui.layers_panel.layers_only = true;
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let rect = |app: &mut VectorcraftApp| run(app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5}))["id"].as_u64().unwrap();
let bottom = rect(&mut app);
for _ in 0..59 {
run(&mut app, "layer.new", json!({}));
rect(&mut app);
}
run(&mut app, "select.none", json!({}));
let doc = app.session.active().unwrap().doc.clone();
let name = doc.node(doc.layer_of(NodeId(bottom)).unwrap()).unwrap().display_name();
let ctx = egui::Context::default();
assert!(!(0..4).any(|_| tall_frame(&mut app, &ctx, &name).1), "the bottom layer's row is out of view");
run(&mut app, "select.set", json!({"ids": [bottom]}));
assert!((0..4).any(|_| tall_frame(&mut app, &ctx, &name).1), "the active layer's row is scrolled into view");
}
/// With Locate Selected Objects on, art selected outside the panel that Show Layers Only or the
/// filter leaves without a row opens nothing, so its group stays closed once the panel lists
/// every row again. Art the filter keeps has its group opened.
#[test]
fn with_the_option_art_the_panel_does_not_list_opens_nothing() {
let (mut app, _, paths) = groups_of_one(500);
app.ui.layers_panel.locate_selected = true;
let ctx = egui::Context::default();
let open = |app: &VectorcraftApp, i: usize| {
let st = app.session.active().unwrap();
st.layers_open.contains(st.doc.parent_of(paths[i]).unwrap())
};
let locate = |app: &mut VectorcraftApp, i: usize| {
app.session.execute("select.set", &json!({"ids": [paths[i].0]})).unwrap();
for _ in 0..4 {
tall_frame(app, &ctx, "");
}
};
tall_frame(&mut app, &ctx, "");
app.ui.layers_panel.layers_only = true;
locate(&mut app, 0);
app.ui.layers_panel.layers_only = false;
tall_frame(&mut app, &ctx, "");
assert!(!open(&app, 0), "Show Layers Only: the group stays closed");
app.ui.layers_filter = Filter { objects: vec![ObjectKind::Text], layers: vec![] };
locate(&mut app, 1);
assert!(!open(&app, 1), "a filter that leaves the path out: the group stays closed");
app.ui.layers_filter = Filter { objects: vec![ObjectKind::Paths], layers: vec![] };
locate(&mut app, 2);
assert!(open(&app, 2), "a filter that keeps the path: the group opens");
}
/// A layer of 2,000 groups of 10 paths with every row open: one frame lays out only the rows
/// in view, and a row highlighted far below them is scrolled to.
#[test]
fn only_the_rows_in_view_are_laid_out() {
use vectorcraft_doc::Appearance;
use vectorcraft_geom::{Rect, shapes};
let mut d = Document::new(1000.0, 1000.0);
let mut groups = vec![];
let mut needle = None;
for g in 0..2000 {
let kids = (0..10)
.map(|k| {
let r = Rect::new(k as f64, g as f64 * 0.1, k as f64 + 1.0, g as f64 * 0.1 + 1.0);
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default());
if g == 0 && k == 0 {
n.name = Some("Needle".into());
needle = Some(n.id);
}
Arc::new(n)
})
.collect();
groups.push(Arc::new(Node::group(d.alloc_id(), kids)));
}
*Arc::make_mut(&mut d.layers[0]).children_mut().unwrap() = groups;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.add_document(d, None);
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
// (shapes drawn, whether the needle's name is among them); a second passes per frame, so
// scrolling ends.
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 1.0;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 800.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == "Needle"));
(out.shapes.len(), found)
};
let (shapes, found) = frame(&mut app);
// 22,001 rows; about 30 fit.
assert!(shapes < 1000 && !found, "{shapes} shapes");
let needle = needle.unwrap();
app.session.execute("layer.highlight", &json!({"ids": [needle.0], "mode": "set"})).unwrap();
let found = (0..4).any(|_| frame(&mut app).1);
assert_eq!(app.session.active().unwrap().highlighted_rows(), [needle]);
assert!(found, "the highlighted row is scrolled into view");
}
/// Selecting art on the canvas scrolls its layer (now the active one) into view, but not away
/// from a row highlighted in the panel.
#[test]
fn a_canvas_selection_reveals_its_active_layer() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let mut rects = vec![run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5}))["id"].as_u64().unwrap()];
for _ in 0..59 {
run(&mut app, "layer.new", json!({}));
rects.push(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5}))["id"].as_u64().unwrap());
}
run(&mut app, "select.none", json!({}));
let doc = app.session.active().unwrap().doc.clone();
let name = |id: u64| doc.node(doc.layer_of(NodeId(id)).unwrap()).unwrap().display_name();
let (bottom, top) = (name(rects[0]), name(rects[59]));
let ctx = egui::Context::default();
let mut time = 0.0;
// Whether a row with this name is drawn after a few frames.
let mut shown = |app: &mut VectorcraftApp, s: &str| {
let mut found = false;
for _ in 0..4 {
time += 1.0;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == s));
}
found
};
assert!(shown(&mut app, &top) && !shown(&mut app, &bottom));
run(&mut app, "select.set", json!({"ids": [rects[0]]}));
assert_eq!(app.session.active().unwrap().current_layer(), doc.layer_of(NodeId(rects[0])));
assert!(shown(&mut app, &bottom), "the active layer is scrolled into view");
// A row highlighted in the panel stays in view when the active layer changes.
let top_layer = doc.layer_of(NodeId(rects[59])).unwrap();
run(&mut app, "layer.highlight", json!({"ids": [top_layer.0], "mode": "set"}));
assert!(shown(&mut app, &top));
app.session.active_mut().unwrap().active_layer = doc.layer_of(NodeId(rects[0]));
assert!(shown(&mut app, &top) && !shown(&mut app, &bottom), "the highlighted row keeps the view");
}
/// #4820: an open blend lists its spine below its key objects, and a click on the spine's row
/// selects the blend (whose spine Direct Selection edits); a locked blend's spine row selects
/// nothing, and searching leaves the row out.
#[test]
fn a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 300, "height": 200}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap();
let b = run(&mut app, "shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap();
run(&mut app, "select.set", json!({"ids": [a, b]}));
let blend = NodeId(run(&mut app, "object.blend.make", json!({}))["id"].as_u64().unwrap());
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
let st = app.session.active().unwrap();
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default());
let kinds: Vec<(u64, bool)> = rows.iter().map(|r| (r.node.id.0, r.spine)).collect();
assert_eq!(kinds[1..], [(blend.0, false), (b, false), (a, false), (blend.0, true)], "the spine row comes last in the blend");
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "rect", &Filter::default());
assert!(!rows.iter().any(|r| r.spine), "no spine row while searching");
// Rows top down: the layer, the blend, both keys (with target circles), then the spine.
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 4);
let spine_row = egui::pos2(150.0, circles[3].y + (circles[3].y - circles[2].y));
let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.to_vec();
click_with(&mut app, &ctx, spine_row, egui::Modifiers::NONE);
assert_eq!(selected(&app), [blend], "its row selects the blend");
click_with(&mut app, &ctx, spine_row, egui::Modifiers::SHIFT);
assert!(selected(&app).is_empty(), "Shift-click takes it out again");
run(&mut app, "layer.setProps", json!({"ids": [blend.0], "locked": true}));
click_with(&mut app, &ctx, spine_row, egui::Modifiers::NONE);
assert!(selected(&app).is_empty(), "a locked blend's spine can't be selected");
}
/// A ruler guide node gets no object row, and a layer that holds only one has no rows to open.
#[test]
fn ruler_guide_nodes_get_no_object_row() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let rect = NodeId(app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
expand(&mut app, &json!({})).unwrap();
let st = app.session.active_mut().unwrap();
let doc = Arc::make_mut(&mut st.doc);
let (first, second) = (doc.layers[0].id, doc.add_layer(Some("Guides only")));
for l in [first, second] {
let g = Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: true, pos: 20.0, artboard: None });
doc.insert(Some(l), usize::MAX, g).unwrap();
}
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default());
let ids: Vec<NodeId> = rows.iter().filter(|r| r.guide.is_none()).map(|r| r.node.id).collect();
assert_eq!(ids, [second, first, rect]);
// Each guide is a guide row of its layer instead.
let guide_rows: Vec<NodeId> = rows.iter().filter(|r| r.guide.is_some()).map(|r| r.node.id).collect();
assert_eq!(guide_rows, [first], "the open layer lists its guide");
assert!(rows[0].opens, "a layer with only a ruler guide opens to its guide row");
}
/// A layer lists its guide rows by `guide.list` index, the highest first, whatever the order of
/// the guide nodes in the layer (`guide.setLayer` puts a moved guide at the top of its new layer).
#[test]
fn guide_rows_list_by_index_whatever_the_node_order() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
for pos in [10, 20, 30] {
app.session.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
}
let st = app.session.active_mut().unwrap();
let doc = Arc::make_mut(&mut st.doc);
let layer = doc.layers[0].id;
// The guide of index 0 moves to the top of the layer's guides.
let first = doc.ruler_guides()[0].id.unwrap();
doc.move_node(first, Some(layer), usize::MAX).unwrap();
let kids: Vec<NodeId> = doc.layers[0].children().unwrap().iter().map(|c| c.id).collect();
assert_eq!(kids.last(), Some(&first));
let rows = list_rows(&st.doc, st.isolation, &st.layers_open, &PanelOptions::default(), "", &Filter::default());
let indexes: Vec<usize> = rows.iter().filter_map(|r| r.guide).collect();
assert_eq!(indexes, [2, 1, 0]);
}
#[test]
fn guide_row_highlight_stays_selected_without_hover() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = NodeId(app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
app.session.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
app.session.execute("select.none", &json!({})).unwrap();
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2); // Layer, rectangle; guide has no target circle.
let guide = egui::pos2(150.0, (circles[0].y + circles[1].y) / 2.0);
let ordinary = egui::pos2(150.0, circles[1].y);
let highlighted_at = |app: &mut VectorcraftApp, at: egui::Pos2| {
// Clear hover so a hover rectangle cannot satisfy selected-fill proof.
let mut out = ctx.run_ui(egui::RawInput { events: vec![egui::Event::PointerGone], ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let selected = Tokens::get(&ctx).row_selected;
out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Rect(r) if r.fill == selected && r.rect.contains(at) && r.rect.width() > 200.0))
};
assert!(!highlighted_at(&mut app, guide), "an unselected guide is not highlighted");
click_with(&mut app, &ctx, guide, egui::Modifiers::NONE);
assert_eq!(vectorcraft_engine::cmd::guide_indexes(&app.session.active().unwrap().doc, &app.session.active().unwrap().selection.guides), [0]);
assert!(highlighted_at(&mut app, guide), "selected guide has the ordinary row fill without hover");
click_with(&mut app, &ctx, ordinary, egui::Modifiers::NONE);
assert_eq!(app.session.active().unwrap().highlighted_rows(), [rect]);
assert!(highlighted_at(&mut app, ordinary), "ordinary row painting remains intact");
}
/// Right-clicking a row that is not highlighted selects it.
#[test]
fn context_menu_right_click_selects_unselected_row() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({})).unwrap();
app.session.execute("layer.highlight", &json!({"ids": [], "mode": "set"})).unwrap();
let ctx = egui::Context::default();
// Rows top-first: Layer 2, Layer 1. Neither is highlighted.
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
assert!(rows_of(&app).is_empty());
// Secondary-click Layer 1's row (bottom row).
let pos = circles[1] - vec2(100.0, 0.0); // name area
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos)], false);
frame(&mut app, &ctx, vec![button_by(pos, true, egui::PointerButton::Secondary)], false);
frame(&mut app, &ctx, vec![button_by(pos, false, egui::PointerButton::Secondary)], false);
// The row is now highlighted.
let highlighted = rows_of(&app);
let layer1 = app.session.active().unwrap().doc.layers[0].id;
assert!(highlighted.contains(&layer1), "right-click selected the unselected row");
assert!(crate::panels::has_row_keys(&ctx, super::ROW_KEYS), "secondary click claims row keys");
}
/// Right-clicking a row that IS highlighted preserves the multiselection.
#[test]
fn context_menu_right_click_preserves_multiselection() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({})).unwrap();
app.session.execute("layer.new", &json!({})).unwrap();
let doc = &app.session.active().unwrap().doc;
let ids: Vec<u64> = doc.layers.iter().map(|l| l.id.0).collect();
// Highlight all 3 layers.
app.session.execute("layer.highlight", &json!({"ids": ids, "mode": "set"})).unwrap();
let ctx = egui::Context::default();
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 3);
// Secondary-click the middle row.
let pos = circles[1] - vec2(100.0, 0.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos)], false);
frame(&mut app, &ctx, vec![button_by(pos, true, egui::PointerButton::Secondary)], false);
frame(&mut app, &ctx, vec![button_by(pos, false, egui::PointerButton::Secondary)], false);
// All 3 must still be highlighted.
assert_eq!(rows_of(&app).len(), 3, "multiselection preserved after right-click on a highlighted row");
}
/// layer.delete removes the specified layer.
#[test]
fn context_menu_delete_dispatches_layer_delete() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let layer2_id = app.session.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
let before = app.session.active().unwrap().doc.layers.len();
// Dispatch layer.delete with explicit ids (what the context menu item does).
app.session.execute("layer.delete", &json!({"ids": [layer2_id]})).unwrap();
let after = app.session.active().unwrap().doc.layers.len();
assert_eq!(after, before - 1, "layer.delete removes the layer");
}
/// layer.duplicate adds a copy.
#[test]
fn context_menu_duplicate_dispatches_layer_duplicate() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let layer_id = app.session.active().unwrap().doc.layers[0].id.0;
let before_layers = app.session.active().unwrap().doc.layers.len();
let before_undo = app.session.active().unwrap().history.undo.len();
app.session.execute("layer.duplicate", &json!({"ids": [layer_id]})).unwrap();
let after = &app.session.active().unwrap();
assert_eq!(after.doc.layers.len(), before_layers + 1, "layer.duplicate adds a layer");
assert_eq!(after.history.undo.len(), before_undo + 1, "one undo step");
}
/// layer.locate locates a specified object id without requiring a prior canvas selection.
#[test]
fn context_menu_locate_object_locates_by_id() {
let (mut app, _, [a, _]) = two_rects();
app.session.execute("select.none", &json!({})).unwrap();
assert!(app.session.active().unwrap().selection.objects.is_empty());
// Context menu passes the node's id directly to layer.locate.
let result = app.session.execute("layer.locate", &json!({"id": a.0}));
assert!(result.is_ok(), "layer.locate with id succeeds without selection: {:?}", result.err());
assert_eq!(app.session.active().unwrap().highlighted_rows(), vec![a]);
}
/// In a 1-layer document, the Delete action in the context menu is disabled when targeting that layer.
#[test]
fn context_menu_delete_disabled_when_every_layer_targeted() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layers.len(), 1);
let layer_id = doc.layers[0].id;
// Targeting every layer disables delete.
let listed: std::collections::HashSet<NodeId> = [layer_id].into_iter().collect();
let del_enabled = !doc.layers.iter().all(|l| listed.contains(&l.id));
assert!(!del_enabled, "Delete must be disabled when every layer is targeted");
// Add a second layer: delete is now enabled for one layer.
app.session.execute("layer.new", &json!({})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layers.len(), 2);
let del_enabled = !doc.layers.iter().all(|l| listed.contains(&l.id));
assert!(del_enabled, "Delete is enabled when at least one layer remains");
}
/// Others actions (Hide Others / Lock Others) retain all multiselected layers.
#[test]
fn context_menu_others_actions_preserve_multiselected_layers() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("layer.new", &json!({})).unwrap();
app.session.execute("layer.new", &json!({})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layers.len(), 3);
let l1 = doc.layers[0].id.0;
let l2 = doc.layers[1].id.0;
// Hide Others with multiselection [l1, l2] hides only l3.
let (hide_cmd, hide_params, hide_enabled) = super::rows::multi_others_action(doc, &[l1, l2], true);
assert_eq!(hide_cmd, "layer.hideOthers");
assert!(hide_enabled);
assert_eq!(hide_params["ids"], json!([l1, l2]));
// Lock Others with multiselection [l1, l2] locks only l3.
let (lock_cmd, lock_params, lock_enabled) = super::rows::multi_others_action(doc, &[l1, l2], false);
assert_eq!(lock_cmd, "layer.lockOthers");
assert!(lock_enabled);
assert_eq!(lock_params["ids"], json!([l1, l2]));
}
/// Context menu Others action resolves an object row to its holding top-level layer.
#[test]
fn context_menu_others_actions_object_row_resolves_to_holding_layer() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
// Layer 1 (current) holding a rectangle.
let rect = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let rect_id = rect["id"].as_u64().unwrap();
// Create Layer 2 and hide it.
let l2 = app.session.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
app.session.execute("layer.setProps", &json!({"ids": [l2], "visible": false})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layers.len(), 2);
// Right-clicking the object in Layer 1: Layer 1 is visible, Layer 2 is hidden.
// There are no other visible layers, so the action should be Show All Layers, enabled.
let (hide_cmd, _hide_params, hide_enabled) = super::rows::multi_others_action(doc, &[rect_id], true);
assert_eq!(hide_cmd, "layer.showAll");
assert!(hide_enabled, "Show All Layers is enabled because Layer 2 is hidden");
// Now make Layer 2 visible, but lock it.
app.session.execute("layer.setProps", &json!({"ids": [l2], "visible": true, "locked": true})).unwrap();
let doc = &app.session.active().unwrap().doc;
// Right-clicking the object in Layer 1: Layer 1 is unlocked, Layer 2 is locked.
// There are no other unlocked layers, so the action should be Unlock All Layers, enabled.
let (lock_cmd, _lock_params, lock_enabled) = super::rows::multi_others_action(doc, &[rect_id], false);
assert_eq!(lock_cmd, "layer.unlockAll");
assert!(lock_enabled, "Unlock All Layers is enabled because Layer 2 is locked");
}
/// Context menu Show/Unlock All Layers are enabled when sublayers are hidden or locked.
#[test]
fn context_menu_others_actions_sublayer_state_enables_all_commands() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let doc = &app.session.active().unwrap().doc;
assert_eq!(doc.layers.len(), 1);
let l1 = doc.layers[0].id.0;
// Create a sublayer in Layer 1.
let sub = app.session.execute("layer.newSublayer", &json!({"parent": l1})).unwrap()["id"].as_u64().unwrap();
// Case 1: Sublayer is hidden while top layer is visible.
app.session.execute("layer.setProps", &json!({"ids": [sub], "visible": false})).unwrap();
let doc = &app.session.active().unwrap().doc;
let (hide_cmd, _, hide_enabled) = super::rows::multi_others_action(doc, &[l1], true);
assert_eq!(hide_cmd, "layer.showAll");
assert!(hide_enabled, "hidden sublayer enables Show All Layers");
// Case 2: Sublayer is visible, but locked while top layer is unlocked.
app.session.execute("layer.setProps", &json!({"ids": [sub], "visible": true, "locked": true})).unwrap();
let doc = &app.session.active().unwrap().doc;
let (lock_cmd, _, lock_enabled) = super::rows::multi_others_action(doc, &[l1], false);
assert_eq!(lock_cmd, "layer.unlockAll");
assert!(lock_enabled, "locked sublayer enables Unlock All Layers");
}
/// Right-clicking a guide row presents specialized context menu actions:
/// Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show.
#[test]
fn context_menu_on_guide_row_presents_specialized_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.set", &json!({"ids": [rect]})).unwrap();
app.session.execute("view.guides.make", &json!({})).unwrap();
let doc = &app.session.active().unwrap().doc;
let layer = doc.layers[0].id;
assert!(doc.node(NodeId(rect)).unwrap().is_guide(), "node was made a guide");
app.session.active_mut().unwrap().layers_open.set(layer, true);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2, "Layer 1 row and guide row");
// Secondary-click the guide row (bottom row)
let at = egui::pos2(150.0, circles[1].y);
let right = egui::PointerButton::Secondary;
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
// Capture the open context menu shapes
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let labels: Vec<String> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some(t.galley.text().trim().to_string()),
_ => None,
})
.collect();
assert!(labels.iter().any(|s| s == "Release Guide"), "Release Guide present in {labels:?}");
assert!(labels.iter().any(|s| s == "Duplicate"), "Duplicate present in {labels:?}");
assert!(labels.iter().any(|s| s == "Delete Guide"), "Delete Guide present in {labels:?}");
assert!(labels.iter().any(|s| s == "Lock"), "Lock present in {labels:?}");
assert!(labels.iter().any(|s| s == "Hide"), "Hide present in {labels:?}");
}
/// Clicking "Release Guide" dispatches the command and converts the guide to a path in one undo step.
#[test]
fn context_menu_release_guide_dispatches_and_is_one_undo_step() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.set", &json!({"ids": [rect]})).unwrap();
app.session.execute("view.guides.make", &json!({})).unwrap();
let layer = app.session.active().unwrap().doc.layers[0].id;
app.session.active_mut().unwrap().layers_open.set(layer, true);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
// Secondary-click the guide row
let at = egui::pos2(150.0, circles[1].y);
let right = egui::PointerButton::Secondary;
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
// Find "Release Guide" position
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let release_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Release Guide" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Release Guide text position");
let undo_before = app.session.active().unwrap().history.undo.len();
click_with(&mut app, &ctx, release_pos, egui::Modifiers::NONE);
// Verify it is no longer a guide
let node = app.session.active().unwrap().doc.node(NodeId(rect)).unwrap();
assert!(!node.is_guide(), "node is now a regular path, not a guide");
let undo_after = app.session.active().unwrap().history.undo.len();
assert_eq!(undo_after, undo_before + 1, "exactly one undo step added");
// Undo restores the guide
app.session.execute("edit.undo", &json!({})).unwrap();
let node = app.session.active().unwrap().doc.node(NodeId(rect)).unwrap();
assert!(node.is_guide(), "undo restores guide status");
}
/// Clicking "Duplicate" and "Delete Guide" in a guide row's context menu dispatches duplicate and delete.
#[test]
fn context_menu_guide_row_duplicate_and_delete() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.set", &json!({"ids": [rect]})).unwrap();
app.session.execute("view.guides.make", &json!({})).unwrap();
let layer = app.session.active().unwrap().doc.layers[0].id;
app.session.active_mut().unwrap().layers_open.set(layer, true);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let (circles, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles.len(), 2);
// 1. Right-click guide row and click "Duplicate"
let at = egui::pos2(150.0, circles[1].y);
let right = egui::PointerButton::Secondary;
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let dup_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Duplicate" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Duplicate text position");
click_with(&mut app, &ctx, dup_pos, egui::Modifiers::NONE);
// Document now has 2 guides
let (circles2, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles2.len(), 3, "Layer and 2 guide rows");
// 2. Right-click the second guide row and click "Delete Guide"
let at2 = egui::pos2(150.0, circles2[2].y);
for e in [egui::Event::PointerMoved(at2), button_by(at2, true, right), button_by(at2, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let del_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Delete Guide" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Delete Guide text position");
click_with(&mut app, &ctx, del_pos, egui::Modifiers::NONE);
let (circles3, _) = frame(&mut app, &ctx, vec![], false);
assert_eq!(circles3.len(), 2, "Back to layer and 1 guide row");
}
/// Clicking "Lock"/"Unlock" and "Hide"/"Show" in a guide row's context menu toggles locked and visible.
#[test]
fn context_menu_guide_row_lock_and_hide() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.set", &json!({"ids": [rect]})).unwrap();
app.session.execute("view.guides.make", &json!({})).unwrap();
let layer = app.session.active().unwrap().doc.layers[0].id;
app.session.active_mut().unwrap().layers_open.set(layer, true);
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let (circles, _) = frame(&mut app, &ctx, vec![], false);
let at = egui::pos2(150.0, circles[1].y);
let right = egui::PointerButton::Secondary;
// 1. Right-click -> menu shows "Lock" -> click "Lock"
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let lock_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Lock" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Lock text position");
click_with(&mut app, &ctx, lock_pos, egui::Modifiers::NONE);
assert!(app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().locked, "guide is locked");
// 2. Right-click -> menu now shows "Unlock" -> click "Unlock"
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let unlock_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Unlock" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Unlock text position");
click_with(&mut app, &ctx, unlock_pos, egui::Modifiers::NONE);
assert!(!app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().locked, "guide is unlocked");
// 3. Right-click -> menu shows "Hide" -> click "Hide"
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let hide_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Hide" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Hide text position");
click_with(&mut app, &ctx, hide_pos, egui::Modifiers::NONE);
assert!(!app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().visible, "guide is hidden");
// 4. Right-click -> menu shows "Show" -> click "Show"
for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] {
frame(&mut app, &ctx, vec![e], false);
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
let show_pos = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().trim() == "Show" => Some(t.pos + egui::vec2(10.0, 5.0)),
_ => None,
})
.expect("Show text position");
click_with(&mut app, &ctx, show_pos, egui::Modifiers::NONE);
assert!(app.session.active().unwrap().doc.node(NodeId(rect)).unwrap().visible, "guide is visible again");
}
/// One headless frame of the panel in a 300 × 600 window, returning every drawn text and its rect.
fn frame_texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(300.0, 600.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
out.textures_delta.clear();
let mut texts = vec![];
for s in out.shapes {
if let egui::epaint::Shape::Text(t) = s.shape {
texts.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2())));
}
}
texts
}
/// Click `button` at `pos` (pressed in one frame, released in the next) and return the texts drawn
/// on the frame after release.
fn click_menu_at(app: &mut VectorcraftApp, ctx: &egui::Context, pos: egui::Pos2, button: egui::PointerButton) -> Vec<(String, egui::Rect)> {
let ev = |pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() };
frame_texts(app, ctx, vec![egui::Event::PointerMoved(pos), ev(true)]);
frame_texts(app, ctx, vec![ev(false)]);
frame_texts(app, ctx, vec![])
}
/// The menu item labels in `texts` (which start with `" "`), ordered from top to bottom.
fn menu_entries(texts: &[(String, egui::Rect)]) -> Vec<String> {
let mut entries: Vec<_> = texts.iter().filter(|(t, _)| t.starts_with(" ")).map(|(t, r)| (t.trim().to_string(), r.top())).collect();
entries.sort_by(|a, b| a.1.total_cmp(&b.1));
entries.into_iter().map(|(t, _)| t).collect()
}
fn text_rect(texts: &[(String, egui::Rect)], name: &str) -> egui::Rect {
texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} not in {texts:?}"))
}
/// Right-clicking a ruler guide row selects the guide (or keeps a multi-guide selection), opens its
/// context menu (Hide/Show, Lock/Unlock, Release Guides, Delete, Locate Object), and each item
/// dispatches its command with Undo/Redo registration (#8592).
#[test]
fn guide_row_context_menu_selects_and_runs_guide_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
run(&mut app, "guide.add", json!({"vertical": false, "pos": 80}));
run(&mut app, "select.none", json!({}));
let layer = app.session.active().unwrap().doc.layers[0].id;
run(&mut app, "layer.highlight", json!({"ids": [layer.0], "mode": "set"}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let texts = frame_texts(&mut app, &ctx, vec![]);
let h_guide_pos = text_rect(&texts, "<Horizontal Guide>").center();
let v_guide_pos = text_rect(&texts, "<Vertical Guide>").center();
let selected_guides = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides)
};
// Right-clicking an unselected guide row selects it, clears highlighted rows, and opens the menu.
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
assert_eq!(selected_guides(&app), [0], "right-click selects the guide");
assert!(rows_of(&app).is_empty(), "highlighted rows cleared when selecting a guide");
assert_eq!(menu_entries(&menu), ["Hide", "Lock", "Release Guides", "Delete", "Locate Object"]);
// Hide toggles the guide's visibility off in one undo step; right-clicking again shows "Show".
let guide_node = app.session.active().unwrap().doc.ruler_guides()[0].id.unwrap();
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Hide").center(), egui::PointerButton::Primary);
assert!(!app.session.active().unwrap().doc.node(guide_node).unwrap().visible);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
assert_eq!(menu_entries(&menu), ["Show", "Lock", "Release Guides", "Delete", "Locate Object"]);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Show").center(), egui::PointerButton::Primary);
assert!(app.session.active().unwrap().doc.node(guide_node).unwrap().visible);
// Lock toggles the guide's lock on in one undo step; right-clicking again shows "Unlock".
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Lock").center(), egui::PointerButton::Primary);
assert!(app.session.active().unwrap().doc.node(guide_node).unwrap().locked);
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
assert_eq!(menu_entries(&menu), ["Hide", "Unlock", "Release Guides", "Delete", "Locate Object"]);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Unlock").center(), egui::PointerButton::Primary);
assert!(!app.session.active().unwrap().doc.node(guide_node).unwrap().locked);
// Locate Object locates the guide's holding layer.
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Locate Object").center(), egui::PointerButton::Primary);
assert_eq!(rows_of(&app), vec![layer]);
// Multi-guide selection is preserved when right-clicking an already-selected guide row.
run(&mut app, "guide.select", json!({"indexes": [0, 1]}));
let _menu = click_menu_at(&mut app, &ctx, h_guide_pos, egui::PointerButton::Secondary);
assert_eq!(selected_guides(&app), [0, 1], "right-click on selected guide preserves multi-guide selection");
// Release Guides on a single guide converts it into a path in one undo step; Undo brings it back.
run(&mut app, "guide.select", json!({"indexes": [0]}));
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Release Guides").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "one guide released to a path");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
run(&mut app, "edit.undo", json!({}));
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 2, "Undo restores the released guide");
// Delete removes the guide in one undo step; Undo restores it.
let texts = frame_texts(&mut app, &ctx, vec![]);
let v_guide_pos = text_rect(&texts, "<Vertical Guide>").center();
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Delete").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "Delete removes the guide");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
run(&mut app, "edit.undo", json!({}));
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 2, "Undo restores the deleted guide");
}
/// Right-clicking a blend spine row selects the blend, opens its context menu (Select, Blend
/// Options…, Reverse Spine, Reverse Front to Back, Expand, Release, Locate Object), and each item
/// dispatches its command with Undo/Redo registration (#8592).
#[test]
fn spine_row_context_menu_selects_blend_and_runs_blend_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 300, "height": 200}));
let a = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
let b = NodeId(run(&mut app, "shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut app, "select.set", json!({"ids": [a.0, b.0]}));
let blend = NodeId(run(&mut app, "object.blend.make", json!({}))["id"].as_u64().unwrap());
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let spine_rect = |texts: &[(String, egui::Rect)]| {
texts
.iter()
.filter(|(t, _)| t == "<Path>")
.max_by(|x, y| x.1.top().total_cmp(&y.1.top()))
.map(|(_, r)| *r)
.unwrap_or_else(|| panic!("spine <Path> not in {texts:?}"))
};
let texts = frame_texts(&mut app, &ctx, vec![]);
let spine_pos = spine_rect(&texts).center();
let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.to_vec();
// Right-clicking the unselected spine row selects the blend and opens the context menu.
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
assert_eq!(selected(&app), [blend], "right-clicking the spine row selects the blend");
assert_eq!(menu_entries(&menu), ["Select", "Blend Options…", "Reverse Spine", "Reverse Front to Back", "Expand", "Release", "Locate Object"]);
// Blend Options… opens the Blend Options dialog.
click_menu_at(&mut app, &ctx, text_rect(&menu, " Blend Options…").center(), egui::PointerButton::Primary);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("blendOptions"));
crate::dialogs::cancel(&mut app);
// Reverse Spine reverses the key positions along the spine in one undo step.
let key_x = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0;
let a_x_before = key_x(&app, a);
let b_x_before = key_x(&app, b);
let undo_before = app.session.active().unwrap().history.undo.len();
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Reverse Spine").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
assert!((key_x(&app, a) - b_x_before).abs() < 1e-6 && (key_x(&app, b) - a_x_before).abs() < 1e-6);
// Reverse Front to Back reverses the key stacking order in one undo step.
let key_ids = |app: &VectorcraftApp| -> Vec<NodeId> {
app.session.active().unwrap().doc.node(blend).unwrap().children().unwrap().iter().map(|c| c.id).collect()
};
assert_eq!(key_ids(&app), [a, b]);
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Reverse Front to Back").center(), egui::PointerButton::Primary);
assert_eq!(key_ids(&app), [b, a]);
// Locate Object highlights the blend row.
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Locate Object").center(), egui::PointerButton::Primary);
assert_eq!(rows_of(&app), vec![blend]);
// Expand replaces the blend with a group in one undo step; Undo brings the blend back.
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Expand").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Group { .. }));
run(&mut app, "edit.undo", json!({}));
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Blend { .. }));
// Release releases the blend into its keys and spine path in one undo step; Undo restores it.
expand(&mut app, &json!({})).unwrap();
let texts = frame_texts(&mut app, &ctx, vec![]);
let spine_pos = spine_rect(&texts).center();
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Release").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
assert!(app.session.active().unwrap().doc.node(blend).is_none(), "blend released into keys and spine path");
run(&mut app, "edit.undo", json!({}));
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Blend { .. }));
}
No file is open. Choose one in the tree, or press Ctrl+O (⌘O on a Mac) to find one by name.
Syntax highlighting could not load. The unmodified read-only text remains available above.