2bc41aeb8602
tests.rs
use super::super::tests_long_popups::{
PopupWindow, assert_last_row_scrolls_into_view, assert_popup_stays_put, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll,
fx_menu_ends,
};
use super::*;
/// A selected rectangle, for the fill row's swatch picker and the Add Effect button.
fn app_with_a_selected_rectangle() -> VectorcraftApp {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({ "ids": [id] })).unwrap();
app
}
/// The swatch of a fill row at the top of the window, with the size of its click target.
fn swatch_button_at_the_top() -> (impl FnMut(&mut VectorcraftApp, &mut Ui), egui::Vec2) {
let row = Rect::from_min_size(pos2(0.0, 8.0), vec2(400.0, 22.0));
(move |app: &mut VectorcraftApp, ui: &mut Ui| swatch_button(app, ui, row, &Paint::None, Painted::Item(0)), vec2(22.0, 22.0))
}
/// One tile of the swatch picker.
const TILE: egui::Vec2 = vec2(15.5, 15.5);
/// The picker has one tile per swatch: with enough of them it stops inside a short window and
/// scrolls, its rows stay 12 tiles wide, and a click on the last tile paints with the last swatch.
#[test]
fn a_long_swatch_picker_scrolls_inside_a_short_window() {
const HEIGHT: f32 = 200.0;
let mut app = app_with_a_selected_rectangle();
for n in 0..150 {
app.run("swatch.new", json!({"name": format!("Long {n}"), "color": format!("#{:06x}", n + 1)})).unwrap();
}
let doc = &app.session.active().unwrap().doc;
let last_swatch = doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|group| &group.swatches)).last().unwrap().paint.clone();
let (draw, chip) = swatch_button_at_the_top();
let mut window = PopupWindow::new(&mut app, HEIGHT, draw);
window.click(&mut app, window.clickable(chip)[0].center());
let tiles = window.clickable(TILE);
assert!(tiles.len() > 150, "one tile per swatch: {}", tiles.len());
assert_eq!(tiles[11].top(), tiles[0].top(), "12 tiles in a row");
assert!(tiles[12].top() > tiles[0].top(), "the 13th tile starts the next row");
assert!(tiles[tiles.len() - 1].bottom() > HEIGHT, "the picker opens at the top of its list");
window.wheel_down(&mut app, tiles[0].center());
let tiles = window.clickable(TILE);
let last = tiles[tiles.len() - 1];
assert!(last.bottom() <= HEIGHT, "the last tile at {last:?} is inside the window");
window.click(&mut app, last.center());
let node = first_subject(&app).expect("the rectangle");
let (Paint::Solid { color, .. }, Paint::Solid { color: last_color, .. }) = (node.appearance.items[0].paint(), &last_swatch) else {
panic!("solid paints")
};
assert_eq!(color, last_color);
}
/// A picker with few swatches fits its tiles and the wheel does not move them.
#[test]
fn a_short_swatch_picker_does_not_scroll() {
let mut app = app_with_a_selected_rectangle();
let (draw, chip) = swatch_button_at_the_top();
let mut window = PopupWindow::new(&mut app, 900.0, draw);
window.click(&mut app, window.clickable(chip)[0].center());
let tiles = window.clickable(TILE);
assert!(tiles[tiles.len() - 1].bottom() <= 900.0, "every tile is inside the window");
window.wheel_down(&mut app, tiles[0].center());
assert_eq!(window.clickable(TILE), tiles, "a list that fits does not scroll");
}
/// The Add New Effect popup keeps each group's name on one line when its list scrolls: the scroll
/// bar's column widens the popup instead of narrowing the rows.
#[test]
fn the_add_effect_popup_keeps_its_rows_on_one_line_when_it_scrolls() {
let mut groups: Vec<String> = vec![];
for effect in vectorcraft_effects::effect_catalog() {
let group = effect.menu.get(1).copied().unwrap_or("Other").to_string();
if !groups.contains(&group) {
groups.push(group);
}
}
assert_rows_stay_on_one_line(&mut app_with_a_selected_rectangle(), draw_bottom_bar, fx_button, &groups, "Distort & Transform", 120.0);
}
/// The Add New Effect button: the third of the bottom bar's 24 pt buttons.
fn fx_button(window: &PopupWindow) -> egui::Pos2 {
window.clickable(vec2(24.0, 24.0))[2].center()
}
fn draw_bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
let node = first_subject(app);
bottom(app, ui, node.as_deref(), Sel::None);
}
/// The Add New Effect popup has one row per effect group, plug-in groups included.
#[test]
fn the_add_effect_popup_scrolls_inside_a_short_window() {
let (first, last) = fx_menu_ends();
assert_last_row_scrolls_into_view(&mut app_with_a_selected_rectangle(), 150.0, draw_bottom_bar, fx_button, &first, &last);
assert_short_list_does_not_scroll(&mut app_with_a_selected_rectangle(), draw_bottom_bar, fx_button, &first, &last);
}
/// The Add New Effect popup opened from a button `below` pt above the bottom of a window `height`
/// pt tall stays at one place on every frame, inside the window.
fn assert_add_effect_popup_stays_put(height: f32, below: f32) -> Rect {
let (first, _) = fx_menu_ends();
let draw = move |app: &mut VectorcraftApp, ui: &mut Ui| {
ui.add_space((height - below - 24.0).max(0.0));
draw_bottom_bar(app, ui);
};
assert_popup_stays_put(&mut app_with_a_selected_rectangle(), height, draw, fx_button, &first)
}
/// Opened from a button near the bottom of a short window, the Add New Effect popup stays at one
/// place instead of being drawn above and below the button on alternate frames.
#[test]
fn the_add_effect_popup_stays_put_near_the_bottom_of_a_short_window() {
for height in [200.0, 300.0, 400.0, 600.0] {
let row = assert_add_effect_popup_stays_put(height, 8.0);
assert!(row.bottom() < height - 32.0, "in a {height} pt window the popup opens above the button: {row:?}");
}
}
/// Opened from a button near the top of a window, the popup opens below it and stays there.
#[test]
fn the_add_effect_popup_stays_put_below_a_button_near_the_top() {
for height in [200.0, 400.0, 900.0] {
let row = assert_add_effect_popup_stays_put(height, height - 32.0);
assert!(row.top() > 24.0, "in a {height} pt window the popup opens below the button: {row:?}");
}
}
/// Duplicating rows highlights the copies, each right above its original, as the Layers panel
/// does: the active row's copy becomes active, the anchor's copy the anchor.
#[test]
fn a_duplicate_highlights_the_copies_above_the_originals() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({ "ids": [id] })).unwrap();
for _ in 0..3 {
app.run("effect.apply", json!({"effect": "distort.roughen"})).unwrap();
}
let owner = Some(NodeId(id));
let ctx = egui::Context::default();
let duplicate = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let node = first_subject(app);
let sel = current_sel(app, ui.ctx(), node.as_deref());
duplicate_selected(app, ui, node.as_deref(), sel);
});
out.textures_delta.clear();
};
// Effects 0 and 2 highlighted, 2 selected: the list reads copy, 0, 1, copy, 2 (top down), so
// the copies are rows 0 and 3.
app.run("appearance.setActiveItem", json!({ "index": null })).unwrap();
set_pstate(&ctx, "ap-sel", (owner, Sel::Effect(2)));
set_pstate(&ctx, "ap-multi", Highlight { owner, rows: Rows::Effects(None), order: vec![2, 0], anchor: Some(0), active: Some(2) });
duplicate(&mut app);
let h: Highlight = pstate(&ctx, "ap-multi");
assert_eq!((h.order, h.anchor), (vec![3, 0], Some(0)));
assert_eq!(pstate::<(Option<NodeId>, Sel)>(&ctx, "ap-sel").1, Sel::Effect(3));
// [Fill, Stroke] both highlighted, the stroke active: paint order fill, copy, stroke, copy,
// so the copies are 1 and 3 and the stroke's copy is active.
app.run("appearance.setActiveItem", json!({ "index": 1 })).unwrap();
set_pstate(&ctx, "ap-sel", (owner, Sel::Item(1)));
set_pstate(&ctx, "ap-multi", Highlight { owner, rows: Rows::Items, order: vec![1, 0], anchor: Some(1), active: Some(1) });
duplicate(&mut app);
let h: Highlight = pstate(&ctx, "ap-multi");
assert_eq!((h.order, h.anchor), (vec![3, 1], Some(3)));
assert_eq!(app.session.appearance_item(), Some(3));
// A row outside the highlight (dropped on Duplicate): only its copy is highlighted and active.
app.run("appearance.setActiveItem", json!({ "index": null })).unwrap();
set_pstate(&ctx, "ap-sel", (owner, Sel::Effect(0)));
set_pstate(&ctx, "ap-multi", Highlight { owner, rows: Rows::Effects(None), order: vec![0], anchor: Some(0), active: Some(0) });
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let n = first_subject(&app).unwrap();
let sel = current_sel(&app, ui.ctx(), Some(&*n));
app.run("effect.duplicate", json!({"item": null, "indices": [4]})).unwrap();
highlight_copies(&mut app, ui.ctx(), &n, sel, Rows::Effects(None), &[4]);
});
out.textures_delta.clear();
let h: Highlight = pstate(&ctx, "ap-multi");
assert_eq!((h.order, h.anchor), (vec![4], Some(4)));
assert_eq!(pstate::<(Option<NodeId>, Sel)>(&ctx, "ap-sel").1, Sel::Effect(4));
}
/// Removing other fills/strokes keeps a fill/stroke's Opacity row selected, renumbered with its
/// item (so the Transparency panel keeps editing it); removing that item clears the selection.
#[test]
fn removing_items_keeps_a_surviving_item_opacity_row_selected() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({ "ids": [id] })).unwrap();
app.run("appearance.duplicateItem", json!({ "indices": [0] })).unwrap();
let owner = Some(NodeId(id));
let ctx = egui::Context::default();
let remove = |app: &mut VectorcraftApp, k: usize| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let n = first_subject(app).unwrap();
let sel = current_sel(app, ui.ctx(), Some(&*n));
app.run("appearance.removeItem", json!({ "indices": [k] })).unwrap();
highlight_after_removal(app, ui.ctx(), &n, sel, Rows::Items, &[k]);
});
out.textures_delta.clear();
};
app.run("appearance.setActiveItem", json!({ "index": 2 })).unwrap();
set_pstate(&ctx, "ap-sel", (owner, Sel::ItemOpacity(2)));
remove(&mut app, 0);
assert_eq!(pstate::<(Option<NodeId>, Sel)>(&ctx, "ap-sel").1, Sel::ItemOpacity(1));
assert_eq!(app.session.appearance_item(), Some(1));
remove(&mut app, 1);
assert_eq!(pstate::<(Option<NodeId>, Sel)>(&ctx, "ap-sel").1, Sel::None);
assert_eq!(app.session.appearance_item(), None);
}
/// #5742: Delete Selected Item on an Opacity row sets it back to Default (100%, Normal): the
/// object's own, or a fill's, leaving the other untouched. Duplicate stays off for it.
#[test]
fn deleting_an_opacity_row_sets_it_back_to_default() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({ "ids": [id] })).unwrap();
app.run("transparency.set", json!({"item": null, "opacity": 50, "blend": "Multiply"})).unwrap();
app.run("transparency.set", json!({"item": 0, "opacity": 40, "blend": "Screen"})).unwrap();
let owner = Some(NodeId(id));
let ctx = egui::Context::default();
let delete = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let node = first_subject(app);
let sel = current_sel(app, ui.ctx(), node.as_deref());
assert!(sel.deletable() && !sel.editable(), "{sel:?}");
delete_selected(app, ui, node.as_deref(), sel);
});
out.textures_delta.clear();
};
let node = |app: &VectorcraftApp| first_subject(app).unwrap();
// The fill's Opacity row: only the fill goes back to Default.
app.run("appearance.setActiveItem", json!({ "index": 0 })).unwrap();
set_pstate(&ctx, "ap-sel", (owner, Sel::ItemOpacity(0)));
delete(&mut app);
let n = node(&app);
assert_eq!((n.appearance.items[0].opacity(), n.appearance.items[0].blend()), (1.0, BlendMode::Normal));
assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply));
assert_eq!(pstate::<(Option<NodeId>, Sel)>(&ctx, "ap-sel").1, Sel::ItemOpacity(0));
// The object's Opacity row.
app.run("appearance.setActiveItem", json!({ "index": null })).unwrap();
set_pstate(&ctx, "ap-sel", (owner, Sel::Opacity));
delete(&mut app);
let n = node(&app);
assert_eq!(opacity_text(n.opacity, n.blend), "Default");
// One step, so Undo brings the object's opacity back.
app.run("edit.undo", json!({})).unwrap();
assert_eq!(node(&app).opacity, 0.5);
}
#[test]
fn opacity_labels() {
assert_eq!(opacity_text(1.0, BlendMode::Normal), "Default");
assert_eq!(opacity_text(0.5, BlendMode::Normal), "50%");
assert_eq!(opacity_text(0.5, BlendMode::Multiply), "50% Multiply");
}
#[test]
fn labels() {
assert_eq!(param_label("offsetX", true), "Offset X");
assert_eq!(param_label("blur", true), "Blur");
assert!(!effect_label("stylize.dropShadow").contains('…'));
assert_eq!(effect_label("path.outlineObject"), "Outline Object");
assert_eq!(effect_label("x.unknownThing"), "unknownThing");
// Only our own effects are interface labels; a plug-in's name is its own.
assert!(built_in_effect("stylize.dropShadow") && !built_in_effect("plugin.example.glow"));
assert_eq!(shown_effect_label("plugin.example.glow"), effect_label("plugin.example.glow"));
}
/// A Drop Shadow's inline editor has Color and Darkness as radio buttons in its Shade row; a
/// click on Darkness sets the effect's `shade`.
#[test]
fn the_drop_shadow_editor_chooses_color_or_darkness() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "stylize.dropShadow"})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
set_pstate(&ctx, "ap-fx-open-None-0", true);
let mut time = 0.0;
let mut run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.1;
let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out
};
run(&mut app, vec![]);
let out = run(&mut app, vec![]);
// The Shade row's Darkness, below the Darkness value's own row.
fn find(s: &egui::Shape, out: &mut Vec<egui::Pos2>) {
match s {
egui::Shape::Text(t) if t.galley.text() == "Darkness" => out.push(t.visual_bounding_rect().center()),
egui::Shape::Vec(v) => v.iter().for_each(|s| find(s, out)),
_ => {}
}
}
let mut found = vec![];
out.shapes.iter().for_each(|c| find(&c.shape, &mut found));
assert_eq!(found.len(), 2, "{found:?}");
let at = found.into_iter().max_by(|a, b| a.y.total_cmp(&b.y)).unwrap();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for events in [vec![egui::Event::PointerMoved(at)], vec![button(true)], vec![button(false)]] {
run(&mut app, events);
}
let n = app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
assert_eq!(n.appearance.effects[0].params["shade"], json!("darkness"));
}
/// A rectangle with `effect` applied, its inline editor open, after a first frame in `ctx`.
fn editing(effect: &str) -> (VectorcraftApp, egui::Context, NodeId) {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": effect})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
set_pstate(&ctx, "ap-fx-open-None-0", true);
panel_frame(&mut app, &ctx, vec![]);
(app, ctx, NodeId(id))
}
/// One frame of the panel in `ctx` with `events`: the texts drawn and where.
fn panel_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, Rect)> {
fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let time = ctx.input(|i| i.time) + 0.1;
let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v
}
/// Clicks the text `label` drawn in the panel (the last one drawn when there are several).
fn click_text(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
let shown = panel_frame(app, ctx, vec![]);
let at = shown.iter().rev().find(|(s, _)| s == label).unwrap_or_else(|| panic!("no {label:?} in {shown:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for events in [vec![egui::Event::PointerMoved(at)], vec![button(true)], vec![button(false)]] {
panel_frame(app, ctx, events);
}
}
fn shown_texts(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
panel_frame(app, ctx, vec![]).into_iter().map(|(s, _)| s).collect()
}
/// Roughen's Points and Offset Path's Joins are dropdowns with the effect dialog's labels, and
/// a pick sends the dialog's value as one undo step.
#[test]
fn the_effect_editor_picks_choices_from_the_dialogs_dropdowns() {
for (effect, key, shown, pick, value) in
[("distort.roughen", "points", "Smooth", "Corner", "corner"), ("path.offsetPath", "joins", "Miter", "Round", "round")]
{
let (mut app, ctx, id) = editing(effect);
let texts = shown_texts(&mut app, &ctx);
assert!(texts.iter().any(|s| s == shown), "{effect}: {texts:?}");
let undo = app.session.doc().unwrap().history.undo.len();
click_text(&mut app, &ctx, shown);
click_text(&mut app, &ctx, pick);
let st = app.session.doc().unwrap();
assert_eq!(st.doc.node(id).unwrap().appearance.effects[0].params[key], json!(value), "{effect}");
assert_eq!(st.history.undo.len(), undo + 1, "{effect}");
assert!(shown_texts(&mut app, &ctx).iter().any(|s| s == pick), "{effect}");
}
}
/// The editor labels a parameter as the effect dialog does, without the ":".
#[test]
fn the_effect_editor_labels_parameters_as_the_dialog_does() {
for (effect, labels) in [
("pixelate.colorHalftone", &["Max. Radius", "Channel 1", "Channel 4"][..]),
("video.deinterlace", &["Create New Fields by", "Duplication", "Eliminate", "Odd Fields"][..]),
] {
let (mut app, ctx, _) = editing(effect);
let texts = shown_texts(&mut app, &ctx);
for label in labels {
assert!(texts.iter().any(|s| s == label), "{effect}: no {label:?} in {texts:?}");
}
}
}
/// A plug-in's choice is a dropdown of the plug-in's own values, also when the parameter is
/// called `mode` and its value names a blend mode.
#[test]
fn a_plug_in_choice_lists_the_plug_ins_values() {
use vectorcraft_plugins::wat as tpl;
let params = r#"{"mode":{"type":"choice","options":["normal","screen","dots"],"default":"screen"}}"#;
let src = tpl::module(&tpl::manifest("test.ui.inlinechoice", "effect", params), tpl::ECHO, "", 1);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "plugin.test.ui.inlinechoice"})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
set_pstate(&ctx, "ap-fx-open-None-0", true);
panel_frame(&mut app, &ctx, vec![]);
click_text(&mut app, &ctx, "screen");
click_text(&mut app, &ctx, "dots");
let mode = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["mode"].clone();
assert_eq!(mode(&app), json!("dots"));
click_text(&mut app, &ctx, "dots");
click_text(&mut app, &ctx, "screen");
assert_eq!(mode(&app), json!("screen"));
// Once the plug-in is removed, its value shows as it is, not as a blend mode.
app.run("plugin.remove", json!({"id": "test.ui.inlinechoice"})).unwrap();
let texts = shown_texts(&mut app, &ctx);
assert!(texts.iter().any(|s| s == "screen") && !texts.iter().any(|s| s == "Screen"), "{texts:?}");
}
/// A plug-in effect's editor labels its parameters, shows their units and leaves out those whose
/// `visibleWhen` isn't met, as the effect's dialog does, and reads a typed number list the same
/// way.
#[test]
fn a_plug_in_effect_s_editor_follows_its_manifest() {
use vectorcraft_plugins::wat as tpl;
let params = r#"{"outline":{"type":"bool","default":true,"label":"Outline"},
"spacing":{"type":"number","min":0.1,"max":10,"default":1.5,"label":"Spacing","unit":"mm","help":"Distance between the lines."},
"angles":{"type":"numberList","min":0,"max":360,"default":[45,135],"minItems":1,"maxItems":4,"unit":"°"},
"width":{"type":"number","min":0,"max":10,"default":0.5,"label":"Width","unit":"pt","visibleWhen":{"outline":[true]}}}"#;
let src = tpl::module(&tpl::manifest("test.ui.inlinekeys", "effect", params), tpl::ECHO, "", 1);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "plugin.test.ui.inlinekeys"})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
set_pstate(&ctx, "ap-fx-open-None-0", true);
let texts = shown_texts(&mut app, &ctx);
for shown in ["Spacing", "1.5 mm", "Angles", "45, 135", "°", "Width", "0.5 pt"] {
assert!(texts.iter().any(|s| s == shown), "no {shown:?} in {texts:?}");
}
assert!(!texts.iter().any(|s| s == "spacing" || s == "width"), "the labels replace the names: {texts:?}");
// Without the outline, its width isn't shown.
app.run("effect.setParams", json!({"item": null, "index": 0, "params": {"outline": false}})).unwrap();
let texts = shown_texts(&mut app, &ctx);
assert!(!texts.iter().any(|s| s == "Width") && texts.iter().any(|s| s == "Spacing"), "{texts:?}");
// A list typed in the field: separated by a semicolon and a space, and clamped.
click_text(&mut app, &ctx, "45, 135");
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
panel_frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
panel_frame(&mut app, &ctx, vec![egui::Event::Text("10; 400 20".into())]);
panel_frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
panel_frame(&mut app, &ctx, vec![]);
let angles = app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["angles"].clone();
assert_eq!(angles, json!([10.0, 360.0, 20.0]));
app.run("plugin.remove", json!({"id": "test.ui.inlinekeys"})).unwrap();
}
/// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does.
#[test]
fn the_effect_editor_lists_a_loaded_glass_texture() {
let mut png = vec![];
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 120, 150, 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 stored = vectorcraft_engine::cmd::fileio::texture_image(&png).unwrap();
let (mut app, ctx, id) = editing("distort.glass");
app.run("effect.setParams", json!({"item": null, "index": 0, "params": {"texture": "loaded", "textureImage": stored}})).unwrap();
let texts = shown_texts(&mut app, &ctx);
assert!(texts.iter().any(|s| s == "Loaded Texture") && !texts.iter().any(|s| s == "loaded"), "{texts:?}");
click_text(&mut app, &ctx, "Loaded Texture");
click_text(&mut app, &ctx, "Frosted");
let st = app.session.doc().unwrap();
assert_eq!(st.doc.node(id).unwrap().appearance.effects[0].params["texture"], json!("frosted"));
}
/// The choices that their dialogs list in their own bodies are dropdowns with those dialogs'
/// labels too: Revolve's edge, Extrude & Bevel's bevel, Warp's orientation, Rasterize's
/// options and the channel of Levels and Curves. A pick sends the dialog's value as one undo
/// step.
#[test]
fn the_effect_editor_picks_choices_their_own_dialogs_list() {
for (effect, key, shown, pick, value) in [
("threeD.revolve", "edge", "Left", "Right", "right"),
("threeD.extrude", "bevel", "None", "Rounded", "rounded"),
("warp.arc", "orientation", "Horizontal", "Vertical", "vertical"),
("rasterize", "colorModel", "RGB", "Grayscale", "grayscale"),
("rasterize", "background", "Transparent", "White", "white"),
("rasterize", "antiAlias", "Art Optimized", "Type Optimized", "type"),
("adjust.levels", "channel", "RGB", "Red", "red"),
("adjust.curves", "channel", "RGB", "Blue", "blue"),
] {
let (mut app, ctx, id) = editing(effect);
let texts = shown_texts(&mut app, &ctx);
assert!(texts.iter().any(|s| s == shown), "{effect} {key}: {texts:?}");
let undo = app.session.doc().unwrap().history.undo.len();
click_text(&mut app, &ctx, shown);
click_text(&mut app, &ctx, pick);
let st = app.session.doc().unwrap();
assert_eq!(st.doc.node(id).unwrap().appearance.effects[0].params[key], json!(value), "{effect} {key}");
assert_eq!(st.history.undo.len(), undo + 1, "{effect} {key}");
assert!(shown_texts(&mut app, &ctx).iter().any(|s| s == pick), "{effect} {key}");
}
}
/// Those choices read as their dialogs show them in the UI language: in French, the channel's
/// RGB as the "effect" row translates it, and in Spanish, Extrude & Bevel's Rounded as the "3d"
/// row does, not the plain row. Rasterize names the document's color mode.
#[test]
fn the_effect_editor_shows_those_choices_as_their_dialogs_do() {
let fr = crate::i18n::Lang::from_code("fr").unwrap();
crate::i18n::set_current(fr);
let (mut app, ctx, _) = editing("adjust.levels");
let texts = shown_texts(&mut app, &ctx);
let rgb = crate::i18n::tr_ctx(fr, "effect", "RGB");
assert!(texts.iter().any(|s| s == rgb), "{rgb}: {texts:?}");
let es = crate::i18n::Lang::from_code("es").unwrap();
crate::i18n::set_current(es);
let (mut app, ctx, _) = editing("threeD.extrude");
app.run("effect.setParams", json!({"item": null, "index": 0, "params": {"bevel": "rounded"}})).unwrap();
let rounded = crate::i18n::tr_ctx(es, "3d", "Rounded");
assert_ne!(rounded, crate::i18n::tr(es, "Rounded"));
assert!(shown_texts(&mut app, &ctx).iter().any(|s| s == rounded), "{rounded}");
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, ctx, _) = editing("rasterize");
app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
let texts = shown_texts(&mut app, &ctx);
assert!(texts.iter().any(|s| s == "CMYK") && !texts.iter().any(|s| s == "document"), "{texts:?}");
}
#[test]
fn the_effect_editor_lists_earlier_parameters_in_their_current_form() {
// A Scribble saved with one `variation` lists it as its Path Overlap and Spacing variations.
let e = Effect { id: "stylize.scribble".into(), params: json!({"variation": 2, "angle": 270}), visible: true };
let p = editor_params(&e);
assert!(!p.contains_key("variation"), "{p:?}");
assert_eq!((&p["overlapVariation"], &p["spacingVariation"], &p["curvinessVariation"]), (&json!(2), &json!(2), &json!(0.0)));
assert_eq!(p["angle"].as_f64(), Some(-90.0));
// Another effect lists its values over its defaults, as before.
let e = Effect { id: "distort.twist".into(), params: json!({"angle": 270}), visible: true };
assert_eq!(editor_params(&e).get("angle"), Some(&json!(270)));
}
/// A text field of the inline editor keeps what is typed from one frame to the next: a Drop
/// Shadow's color typed a character a frame and confirmed with Enter is set in one undo step.
/// Escape drops what is typed.
#[test]
fn the_effect_editor_keeps_text_typed_across_frames() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "stylize.dropShadow"})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
set_pstate(&ctx, "ap-fx-open-None-0", true);
let mut time = 0.0;
let mut run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.1;
let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out
};
/// Every text drawn, with its center.
fn texts(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let drawn = |out: &egui::FullOutput| {
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v
};
run(&mut app, vec![]);
let shown = drawn(&run(&mut app, vec![]));
let at = shown.iter().find(|(t, _)| t == "#000000").map(|(_, p)| *p);
let Some(at) = at else { panic!("no color field: {shown:?}") };
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
for events in [vec![egui::Event::PointerMoved(at)], vec![button(true)], vec![button(false)]] {
run(&mut app, events);
}
run(&mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
let undo = app.session.active().unwrap().history.undo.len();
for ch in "#ff0000".chars() {
run(&mut app, vec![egui::Event::Text(ch.to_string())]);
}
let shown = drawn(&run(&mut app, vec![]));
assert!(shown.iter().any(|(t, _)| t == "#ff0000"), "the field shows what was typed: {shown:?}");
run(&mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
run(&mut app, vec![]);
let color = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["color"].clone();
assert_eq!(color(&app), json!("#ff0000"));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step");
// Escape drops what is typed.
for events in [vec![button(true)], vec![button(false)]] {
run(&mut app, events);
}
run(&mut app, vec![egui::Event::Text("0".into())]);
let shown = drawn(&run(&mut app, vec![]));
assert!(shown.iter().any(|(t, _)| t.len() == 8 && t.starts_with('#')), "a 0 typed into the color: {shown:?}");
run(&mut app, vec![key(egui::Key::Escape, egui::Modifiers::NONE)]);
run(&mut app, vec![]);
assert_eq!(color(&app), json!("#ff0000"));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
/// Each place a dragged row can be dropped picks the command it runs and its parameters.
#[test]
fn drops_pick_the_command() {
use vectorcraft_doc::{Appearance, FillLayer};
let fx = |id: &str| Effect { id: id.into(), params: Value::Null, visible: true };
let mut n = Node::path(NodeId(1), vectorcraft_geom::PathData::default(), Appearance::default_art());
n.appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None))); // [F, S, F]
n.appearance.items[1].effects_mut().extend([fx("distort.twist"), fx("distort.roughen")]);
n.appearance.effects.push(fx("stylize.dropShadow"));
let slots = [
Slot::Object { top: true },
Slot::Item { index: 2, sub: false },
Slot::Item { index: 1, sub: false },
Slot::Effect(Some(1), 0),
Slot::Effect(Some(1), 1),
Slot::Item { index: 0, sub: false },
Slot::Effect(None, 0),
Slot::Object { top: false },
];
let rows: Vec<(Slot, Rect)> =
slots.iter().enumerate().map(|(i, s)| (*s, Rect::from_min_size(pos2(0.0, i as f32 * ROW), vec2(200.0, ROW)))).collect();
// The upper or lower half of row `i`.
let at = |i: usize, lower: bool| pos2(50.0, i as f32 * ROW + if lower { ROW * 0.75 } else { ROW * 0.25 });
let drop = |what, p, copy| drop_command(&n, &rows, what, p, copy);
// Fill/stroke rows: moves, Alt copies to where it was dropped.
assert_eq!(drop(Dragged::Item(0), at(1, false), false), Some(("appearance.moveItem", json!({"from": 0, "to": 2}))));
assert_eq!(drop(Dragged::Item(0), at(0, false), true), Some(("appearance.duplicateItem", json!({"index": 0, "to": 3}))));
assert_eq!(drop(Dragged::Item(2), at(7, false), true), Some(("appearance.duplicateItem", json!({"index": 2, "to": 0}))));
assert_eq!(drop(Dragged::Item(1), at(3, false), false), None, "onto its own effect");
// Effects: within the list (below the next one), into a fill, out onto the object.
let mv = |from: usize, fi: Value, to: usize, ti: Value, copy: bool| {
Some(("effect.move", json!({"from": from, "fromItem": fi, "to": to, "toItem": ti, "copy": copy})))
};
assert_eq!(drop(Dragged::Effect(Some(1), 0), at(4, true), false), mv(0, json!(1), 1, json!(1), false));
assert_eq!(drop(Dragged::Effect(Some(1), 0), at(3, true), false), None, "dropped on itself");
assert_eq!(drop(Dragged::Effect(Some(1), 1), at(5, false), true), mv(1, json!(1), 0, json!(0), true));
assert_eq!(drop(Dragged::Effect(Some(1), 1), at(7, false), false), mv(1, json!(1), 1, Value::Null, false));
assert_eq!(drop(Dragged::Effect(None, 0), at(3, false), false), mv(0, Value::Null, 0, json!(1), false));
assert_eq!(drop(Dragged::Effect(None, 0), pos2(500.0, 10.0), false), None, "outside the stack");
}
/// Several highlighted rows dropped together (the owner's straddling example): a group listed
/// top-down `S3, FA*, Contents, S1*, F0` (paint order F0 S1 FA S3, Contents above two).
#[test]
fn several_rows_drop_as_one_block() {
use vectorcraft_doc::FillLayer;
let mut n = Node::group(NodeId(1), vec![]);
n.appearance.items = (0..4).map(|_| AppearanceItem::Fill(FillLayer::new(Paint::None))).collect();
n.appearance.set_contents_at(2);
let slots = [
Slot::Object { top: true },
Slot::Item { index: 3, sub: false },
Slot::Item { index: 2, sub: false },
Slot::Contents,
Slot::Item { index: 1, sub: false },
Slot::Item { index: 0, sub: false },
Slot::Object { top: false },
];
let rows: Vec<(Slot, Rect)> =
slots.iter().enumerate().map(|(i, s)| (*s, Rect::from_min_size(pos2(0.0, i as f32 * ROW), vec2(200.0, ROW)))).collect();
let at = |i: usize| pos2(50.0, i as f32 * ROW + ROW / 2.0);
let set = [1, 2];
let drop = |grabbed, i, copy| block_drop_command(&n, &rows, Dragged::Item(grabbed), &set, at(i), copy);
let mv = |to: usize, contents: usize| Some(("appearance.moveItem", json!({"indices": [1, 2], "to": to, "contents": contents})));
// On S3 (FA grabbed, so dropped upwards: above it): FA, S1, S3, Contents, F0.
assert_eq!(drop(2, 1, false), mv(2, 1));
// On the Contents row: grabbed above it, just below; grabbed below it, just above.
assert_eq!(drop(2, 3, false), mv(1, 3));
assert_eq!(drop(1, 3, false), mv(1, 1));
// On the object row: on top, Contents below; under the stack: at the bottom, Contents above.
assert_eq!(drop(2, 0, false), mv(2, 1));
assert_eq!(drop(2, 6, false), mv(0, 3));
// On F0 (below it, on its side of Contents).
assert_eq!(drop(2, 5, false), mv(0, 3));
// On one of its own rows: nothing.
assert_eq!(drop(2, 2, false), None);
assert_eq!(drop(2, 4, true), None);
// Alt: copies as a block, placed the same way; Contents stays between the same rows.
let cp = |to: usize, contents: usize| Some(("appearance.duplicateItem", json!({"indices": [1, 2], "to": to, "contents": contents})));
assert_eq!(drop(2, 0, true), cp(4, 2));
assert_eq!(drop(2, 5, true), cp(0, 4));
assert_eq!(drop(2, 3, true), cp(2, 4));
// Effects of one list: they land together; on one of their own rows nothing happens.
let fx = |id: &str| Effect { id: id.into(), params: Value::Null, visible: true };
let mut p = Node::path(NodeId(2), vectorcraft_geom::PathData::default(), vectorcraft_doc::Appearance::default_art());
p.appearance.effects.extend([fx("a"), fx("b"), fx("c")]);
let fslots = [
Slot::Object { top: true },
Slot::Item { index: 1, sub: false },
Slot::Item { index: 0, sub: false },
Slot::Effect(None, 0),
Slot::Effect(None, 1),
Slot::Effect(None, 2),
];
let frows: Vec<(Slot, Rect)> =
fslots.iter().enumerate().map(|(i, s)| (*s, Rect::from_min_size(pos2(0.0, i as f32 * ROW), vec2(200.0, ROW)))).collect();
let lower = |i: usize| pos2(50.0, i as f32 * ROW + ROW * 0.75);
let fdrop = |i, copy| block_drop_command(&p, &frows, Dragged::Effect(None, 0), &[0, 2], lower(i), copy);
let fmv = |to: usize, to_item: Value, copy: bool| {
Some(("effect.move", json!({"from": [0, 2], "fromItem": null, "to": to, "toItem": to_item, "copy": copy})))
};
assert_eq!(fdrop(4, false), fmv(1, Value::Null, false), "below b: a, c land after it");
assert_eq!(fdrop(1, true), fmv(0, json!(1), true), "into the stroke's list");
assert_eq!(fdrop(3, false), None);
assert_eq!(fdrop(5, false), None);
}
/// One headless frame of the panel: the texts drawn, top to bottom.
fn frame(app: &mut VectorcraftApp) -> Vec<String> {
fn texts(s: &egui::Shape, out: &mut Vec<(f32, String)>) {
match s {
egui::Shape::Text(t) => out.push((t.pos.y, t.galley.text().to_string())),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
out.textures_delta.clear();
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v.sort_by(|a, b| a.0.total_cmp(&b.0));
v.into_iter().map(|(_, t)| t).collect()
}
#[test]
fn groups_show_a_contents_row_and_type_a_characters_row_in_their_slot() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone();
let b = run(&mut app, "shape.rectangle", json!({"x": 30, "y": 0, "width": 20, "height": 20}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
run(&mut app, "object.group", json!({}));
run(&mut app, "appearance.addFill", json!({}));
run(&mut app, "appearance.addStroke", json!({}));
let rows = |t: Vec<String>| t.into_iter().filter(|t| ["Fill:", "Stroke:", "Contents", "Characters"].contains(&t.as_str())).collect::<Vec<_>>();
assert_eq!(rows(frame(&mut app)), ["Stroke:", "Fill:", "Contents"]);
run(&mut app, "appearance.moveItem", json!({"from": "contents", "to": 1}));
assert_eq!(rows(frame(&mut app)), ["Stroke:", "Contents", "Fill:"]);
let t = run(&mut app, "text.create", json!({"x": 0, "y": 60, "text": "Hi"}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [t]}));
assert_eq!(rows(frame(&mut app)), ["Characters"]);
run(&mut app, "appearance.addFill", json!({}));
assert_eq!(rows(frame(&mut app)), ["Fill:", "Characters"]);
}
/// Add New Fill (button, menu or shortcut) with rows selected: the copy of the active row lands
/// right above it and is then the only selected row.
#[test]
fn add_new_fill_selects_the_new_fill_alone() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = NodeId(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
app.run("appearance.addFill", json!({})).unwrap(); // [Fill, Stroke, Fill]
let ctx = egui::Context::default();
let n = app.session.doc().unwrap().doc.node(id).unwrap().clone();
// Rows 1 (the stroke) and 0 Cmd-clicked together, row 0 (clicked last) active.
click_row(&mut app, &ctx, &n, Sel::None, Rows::Items, 1, egui::Modifiers::NONE);
click_row(&mut app, &ctx, &n, Sel::Item(1), Rows::Items, 0, egui::Modifiers::COMMAND);
assert_eq!(selected_items(&ctx, Some(&n), Sel::Item(0)), [0, 1]);
app.run("appearance.addFill", json!({})).unwrap();
let n = app.session.doc().unwrap().doc.node(id).unwrap().clone();
assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke", "fill"]);
let sel = current_sel(&app, &ctx, Some(&n));
assert_eq!(sel, Sel::Item(1));
assert_eq!(selected_items(&ctx, Some(&n), sel), [1]);
}
#[test]
fn images_show_a_contents_row_with_new_fills_and_strokes_below_it() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let rows = |t: Vec<String>| t.into_iter().filter(|t| ["Fill:", "Stroke:", "Contents"].contains(&t.as_str())).collect::<Vec<_>>();
let mut png = vec![];
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 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();
run(&mut app, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
assert_eq!(rows(frame(&mut app)), ["Contents"]);
run(&mut app, "appearance.addStroke", json!({}));
assert_eq!(rows(frame(&mut app)), ["Contents", "Stroke:"]);
}
#[test]
fn drops_move_items_across_the_contents_row_and_the_row_itself() {
use vectorcraft_doc::FillLayer;
// A group [F0 | F1 F2]: the Contents row sits above item 0.
let mut n = Node::group(NodeId(1), vec![]);
n.appearance.items = (0..3).map(|_| AppearanceItem::Fill(FillLayer::new(Paint::None))).collect();
n.appearance.set_contents_at(1);
let slots = [
Slot::Object { top: true },
Slot::Item { index: 2, sub: false },
Slot::Item { index: 1, sub: false },
Slot::Contents,
Slot::Item { index: 0, sub: false },
Slot::Object { top: false },
];
let rows: Vec<(Slot, Rect)> =
slots.iter().enumerate().map(|(i, s)| (*s, Rect::from_min_size(pos2(0.0, i as f32 * ROW), vec2(200.0, ROW)))).collect();
let at = |i: usize| pos2(50.0, i as f32 * ROW + ROW / 2.0);
let drop = |what, i| drop_command(&n, &rows, what, at(i), false);
// Onto the Contents row: from above it lands just below, from below just above.
assert_eq!(drop(Dragged::Item(2), 3), Some(("appearance.moveItem", json!({"from": 2, "to": 1, "contents": 2}))));
assert_eq!(drop(Dragged::Item(0), 3), Some(("appearance.moveItem", json!({"from": 0, "to": 0, "contents": 0}))));
// Onto the object row: above everything; under the stack: below everything.
assert_eq!(drop(Dragged::Item(0), 0), Some(("appearance.moveItem", json!({"from": 0, "to": 2, "contents": 0}))));
assert_eq!(drop(Dragged::Item(2), 5), Some(("appearance.moveItem", json!({"from": 2, "to": 0, "contents": 2}))));
// The row itself: above item 2, below item 0; nowhere new on itself.
assert_eq!(drop(Dragged::Contents, 1), Some(("appearance.moveItem", json!({"from": "contents", "to": 3}))));
assert_eq!(drop(Dragged::Contents, 4), Some(("appearance.moveItem", json!({"from": "contents", "to": 0}))));
assert_eq!(drop(Dragged::Contents, 3), None);
assert_eq!(drop(Dragged::Contents, 2), Some(("appearance.moveItem", json!({"from": "contents", "to": 2}))));
}
#[test]
fn with_nothing_selected_it_lists_what_new_art_gets() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: 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": 20, "height": 20}));
run(&mut app, "appearance.addFill", json!({}));
run(&mut app, "effect.apply", json!({"effect": "stylize.dropShadow"}));
run(&mut app, "transparency.set", json!({"opacity": 50}));
run(&mut app, "graphicStyle.new", json!({"name": "Fancy"}));
run(&mut app, "select.none", json!({}));
let shown = frame(&mut app);
assert!(shown.contains(&"No Selection".to_string()) && shown.contains(&"Opacity: Default".to_string()), "{shown:?}");
// A style clicked with nothing selected: the rows show what the next object gets.
run(&mut app, "graphicStyle.apply", json!({"name": "Fancy"}));
run(&mut app, "stroke.set", json!({"dash": [3, 3]}));
let shown = frame(&mut app);
let rows: Vec<&String> = shown.iter().filter(|t| ["Fill:", "Stroke:"].contains(&t.as_str())).collect();
assert_eq!(rows, ["Fill:", "Stroke:", "Fill:"], "the added fill is on top");
for want in ["No Selection: Fancy".to_string(), effect_label("stylize.dropShadow"), "Opacity: 50%".into(), "Dashed".into()] {
assert!(shown.contains(&want), "{want} in {shown:?}");
}
}
/// Both stroke rows expose named Weight inputs, and the drop-shadow effect names its Blur input and
/// Color radio button.
#[test]
fn inline_stroke_weight_and_effect_fields_are_named() {
use egui_kittest::kittest::Queryable;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
app.run("appearance.addStroke", json!({})).unwrap();
app.run("effect.apply", json!({"effect": "stylize.dropShadow"})).unwrap();
let mut first = true;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(360.0, 760.0)).with_accessibility_check(false).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if std::mem::replace(&mut first, false) {
crate::theme::install_fonts(ui.ctx());
set_pstate(ui.ctx(), "ap-fx-open-None-0", true);
}
show(app, ui);
},
app,
);
h.run_steps(4);
assert_eq!(h.get_all_by_role_and_label(egui::accesskit::Role::TextInput, "Weight:").count(), 2, "both stroke rows are named");
let _ = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Blur");
let _ = h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Color");
}
/// A style that gives the next object two fills and two strokes: each row's swatch and weight
/// field has an id of its own (egui flags a clash with a 🔥 warning drawn over the widgets).
#[test]
fn new_art_rows_of_the_same_kind_have_their_own_widget_ids() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: 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": 20, "height": 20}));
run(&mut app, "appearance.addFill", json!({}));
run(&mut app, "appearance.addStroke", json!({}));
run(&mut app, "graphicStyle.new", json!({"name": "Twice"}));
run(&mut app, "select.none", json!({}));
run(&mut app, "graphicStyle.apply", json!({"name": "Twice"}));
let ctx = egui::Context::default();
ctx.options_mut(|o| o.warn_on_id_clash = true);
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut shown = vec![];
// The second frame: ids from the first are known by then.
for _ in 0..2 {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
out.textures_delta.clear();
shown.clear();
out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown));
}
let rows = shown.iter().filter(|t| ["Fill:", "Stroke:"].contains(&t.as_str())).count();
assert_eq!(rows, 4, "two fills and two strokes: {shown:?}");
let clashes: Vec<&String> = shown.iter().filter(|t| t.contains('🔥')).collect();
assert!(clashes.is_empty(), "{clashes:?}");
}
/// #4174: two circles with different fills and the same stroke, effect and opacity list the
/// object row with their kind, the "Mixed Appearances" note and what they share: the stroke, the
/// Feather and the opacity, not the fills. A path with type names them "Mixed Objects".
#[test]
fn a_mixed_selection_lists_what_its_objects_share() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 300, "height": 200}));
let mut ids = vec![];
for (x, color) in [(0, "#ffff00"), (150, "#ff0000")] {
let id = run(&mut app, "shape.ellipse", json!({"x": x, "y": 50, "width": 100, "height": 100}))["id"].clone();
run(&mut app, "paint.setFill", json!({"ids": [id], "color": color}));
run(&mut app, "appearance.setItem", json!({"ids": [id], "index": 1, "color": "#0000ff", "weight": 11}));
run(&mut app, "effect.apply", json!({"ids": [id], "effect": "stylize.feather", "item": null}));
ids.push(id);
}
run(&mut app, "select.set", json!({"ids": ids}));
let shown = frame(&mut app);
let kind = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(ids[0].as_u64().unwrap())).unwrap().kind_label();
assert_eq!(shown.iter().find(|t| *t != "?").map(String::as_str), Some(kind), "the object row names their kind: {shown:?}");
assert!(shown.iter().any(|t| t == "Mixed Appearances"), "{shown:?}");
assert!(shown.iter().any(|t| t == "Stroke:") && !shown.iter().any(|t| t == "Fill:"), "the stroke, not the fills: {shown:?}");
assert!(shown.iter().any(|t| t.contains("Feather")), "the shared effect: {shown:?}");
assert!(shown.iter().any(|t| t == "Opacity:"), "{shown:?}");
// The object row's chip says the fills differ, like the Properties panel's "?" chip.
assert!(shown.iter().any(|t| t == "?"), "{shown:?}");
// Alike objects list their whole stack, without the note.
run(&mut app, "paint.setFill", json!({"ids": ids, "color": "#ffff00"}));
let shown = frame(&mut app);
assert!(!shown.iter().any(|t| t == "Mixed Appearances") && shown.iter().any(|t| t == "Fill:"), "{shown:?}");
assert!(!shown.iter().any(|t| t == "?"), "{shown:?}");
// A path and type.
let t = run(&mut app, "text.create", json!({"x": 0, "y": 180, "text": "Hi"}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [ids[0].clone(), t]}));
assert_eq!(frame(&mut app).iter().find(|t| *t != "?").map(String::as_str), Some("Mixed Objects"));
}
/// The [`summary`] `ctx` holds for the active document, checked field by field against what
/// [`object_label`] and [`mixed`] work out from scratch.
fn fresh_summary(app: &VectorcraftApp, ctx: &egui::Context) -> Arc<Summary> {
let s = summary(app, ctx).unwrap();
assert_eq!(s.label, object_label(app), "the kind label");
let parts = |m: &Mixed| (m.shared.clone(), m.transparency, m.fills_differ);
assert_eq!(s.mixed(app).map(parts), mixed(app).as_ref().map(parts), "the mixed summary");
s
}
/// The object row's kind and the Mixed Appearances summary are worked out once per document
/// revision and list of subjects: a repaint with nothing changed reuses them, and they follow an
/// edit, Undo and Redo, a selection that changes only in the middle, a target circle and another
/// document at the same revision.
#[test]
fn the_selection_summary_is_reused_until_the_document_or_its_subjects_change() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = egui::Context::default();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let art = |app: &mut VectorcraftApp| -> (Vec<NodeId>, NodeId) {
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let r = (0..3).map(|i| id(app.run("shape.rectangle", json!({"x": i * 30, "y": 0, "width": 20, "height": 20})).unwrap())).collect();
(r, id(app.run("text.create", json!({"x": 0, "y": 100, "text": "Hi"})).unwrap()))
};
let (r, t) = art(&mut app);
app.run("select.set", json!({"ids": r})).unwrap();
let s = fresh_summary(&app, &ctx);
assert!(s.mixed(&app).is_none(), "alike rectangles");
assert!(Arc::ptr_eq(&s, &fresh_summary(&app, &ctx)), "a repaint with nothing changed reuses the summary");
// An edit of the middle object, then Undo and Redo.
app.run("transparency.set", json!({"ids": [r[1]], "opacity": 50})).unwrap();
assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| m.transparency), "the middle one's opacity differs");
app.run("edit.undo", json!({})).unwrap();
assert!(fresh_summary(&app, &ctx).mixed(&app).is_none(), "undone");
app.run("edit.redo", json!({})).unwrap();
assert!(fresh_summary(&app, &ctx).mixed(&app).is_some(), "redone");
// The middle id changes at the same revision, length, first and last id.
app.session.active_mut().unwrap().selection.objects[1] = t;
assert_eq!(fresh_summary(&app, &ctx).label, "Mixed Objects");
// A target circle with the selected objects unchanged, and back.
let layer = app.session.active().unwrap().doc.default_layer().unwrap();
app.session.active_mut().unwrap().selection.target = Some(layer);
assert_eq!(fresh_summary(&app, &ctx).label, "Layer");
app.session.active_mut().unwrap().selection.target = None;
assert_eq!(fresh_summary(&app, &ctx).label, "Mixed Objects");
// Another document with the same ids selected at the same revision, where the first object's
// opacity differs instead.
let revision = app.session.active().unwrap().revision;
assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| !m.transparency));
let (r2, t2) = art(&mut app);
assert_eq!((&r2, t2), (&r, t), "the second document numbers its objects alike");
app.run("transparency.set", json!({"ids": [r[0]], "opacity": 50})).unwrap();
let st = app.session.active_mut().unwrap();
st.selection.objects = vec![r[0], t, r[2]];
st.selection.target = None;
st.revision = revision;
assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| m.transparency), "the second document's own summary");
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(fresh_summary(&app, &ctx).mixed(&app).is_some_and(|m| !m.transparency), "the first document's again");
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
}
/// The milliseconds `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time_ms(f: impl FnOnce()) -> f64 {
let d = match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
};
d.as_secs_f64() * 1000.0
}
/// A document of `n` small rectangles, all selected; with `mixed`, every second one at 50% opacity.
fn many_rectangles(n: usize, mixed: bool) -> VectorcraftApp {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
let r = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap()["id"].as_u64().unwrap();
let mut d = vectorcraft_doc::Document::clone(&app.session.active().unwrap().doc);
let template = d.node(NodeId(r)).unwrap().clone();
let layer = d.layers[0].id;
d.children_mut(Some(layer)).unwrap().clear();
let mut ids = Vec::with_capacity(n);
for i in 0..n {
let mut node = template.clone();
node.id = d.alloc_id();
if mixed && i % 2 == 1 {
node.opacity = 0.5;
}
ids.push(d.insert(Some(layer), usize::MAX, node).unwrap());
}
app.session.add_document(d, None);
app.session.active_mut().unwrap().selection.objects = ids;
app
}
/// Timings of the selection summary the Control bar and the Appearance panel show on each repaint,
/// on 5,000, 20,000 and 200,000 selected rectangles, alike and with every second one's opacity
/// different, in milliseconds per repaint: worked out from scratch (`object_label` for the Control
/// bar, then `mixed` and `object_label` for the panel); through [`summary`], whose first repaint
/// works it out and the rest reuse it; and through [`summary`] with its stored entry removed before
/// every repaint, as when the document or the selection changes each time. They run in turn on the same document,
/// 7 runs each, and the results are checked equal. Ignored by default; it prints the median, fastest and slowest run
/// and sets no bound on them:
/// `cargo test --release -p vectorcraft-ui-egui --lib selection_summary_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn selection_summary_perf() {
const RUNS: usize = 7;
const REPAINTS: usize = 20;
let stats = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
format!("{:.3} ({:.3}-{:.3})", v[v.len() / 2], v[0], v[v.len() - 1])
};
eprintln!("selection_summary_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!(
"selection_summary_perf: {:>8} {:<6} {:>28} {:>28} {:>28}",
"selected", "kind", "from scratch ms (min-max)", "summary ms (min-max)", "summary, changed ms (min-max)"
);
for n in [5_000, 20_000, 200_000] {
for mixed_case in [false, true] {
let app = many_rectangles(n, mixed_case);
let (mut old, mut new, mut changed) = (vec![], vec![], vec![]);
for _ in 0..RUNS {
let mut seen = None;
old.push(
time_ms(|| {
for _ in 0..REPAINTS {
let bar = object_label(&app);
let mix = mixed(&app);
let row = object_label(&app);
seen = Some((bar, row, mix.map(|m| (m.shared, m.transparency, m.fills_differ))));
}
}) / REPAINTS as f64,
);
let ctx = egui::Context::default();
let mut cached = None;
new.push(
time_ms(|| {
for _ in 0..REPAINTS {
let bar = summary(&app, &ctx).map_or("No Selection", |s| s.label);
let s = summary(&app, &ctx).unwrap();
let mix = s.mixed(&app).map(|m| (m.shared.clone(), m.transparency, m.fills_differ));
cached = Some((bar, s.label, mix));
}
}) / REPAINTS as f64,
);
assert_eq!(cached, seen, "{n} {mixed_case}");
let mut fresh = None;
changed.push(
time_ms(|| {
for _ in 0..REPAINTS {
ctx.data_mut(|d| d.remove::<Arc<Summary>>(egui::Id::unique("ap-summary")));
let bar = summary(&app, &ctx).map_or("No Selection", |s| s.label);
let s = summary(&app, &ctx).unwrap();
let mix = s.mixed(&app).map(|m| (m.shared.clone(), m.transparency, m.fills_differ));
fresh = Some((bar, s.label, mix));
}
}) / REPAINTS as f64,
);
assert_eq!(fresh, seen, "{n} {mixed_case}");
}
let kind = if mixed_case { "mixed" } else { "alike" };
eprintln!("selection_summary_perf: {:>8} {:<6} {:>28} {:>28} {:>28}", n, kind, stats(old), stats(new), stats(changed));
}
}
}
/// The panel's subject is the `Arc` the document holds for the selected object, a targeted group
/// or a targeted layer, not a copy of it; nothing with nothing selected.
#[test]
fn first_subject_is_the_node_the_document_holds() {
let mut app = app_with_a_selected_rectangle();
let held = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
super::super::layers::node_arc(&st.doc, st.selection.subjects()[0]).unwrap()
};
assert!(std::sync::Arc::ptr_eq(&first_subject(&app).expect("the rectangle"), &held(&app)), "the selected object");
let group = app.run("object.group", json!({})).unwrap()["id"].clone();
app.run("layer.target", json!({ "id": group })).unwrap();
let n = first_subject(&app).expect("the group");
assert_eq!(n.id.0, group.as_u64().unwrap());
assert!(std::sync::Arc::ptr_eq(&n, &held(&app)), "the targeted group");
let layer = app.session.active().unwrap().doc.layers[0].id;
app.run("layer.target", json!({ "id": layer.0 })).unwrap();
let n = first_subject(&app).expect("the layer");
assert_eq!(n.id, layer);
assert!(std::sync::Arc::ptr_eq(&n, &held(&app)), "the targeted layer");
app.run("select.none", json!({})).unwrap();
assert!(first_subject(&app).is_none(), "nothing selected");
}
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.