Merge main into fix/cjk-settings-opening-text-selection

This commit is contained in:
dotCooCoo committed 2026-11-27 05:58:35 -08:00
commit 63c6dbfd66
54 files changed
+2936 -217

No files matched your search

+2
View File
@@ -496,6 +496,7 @@ fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
let neighbor_art = d.alloc_id();
@@ -523,6 +524,7 @@ fn artboard_for_bounds_edge_cases_and_tie_breaks() {
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
+7 -2
View File
@@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"];
const EXPORT: &str = "type.compositeFonts.export";
/// The largest file Import reads, in bytes.
const MAX_FILE_BYTES: usize = 4 << 20;
pub const MAX_FILE_BYTES: usize = 4 << 20;
/// The keys a part may give.
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
@@ -349,7 +349,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
let too_large = || bad(C, "the file is larger than 4 MB");
let bytes = match given {
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
(None, Some(text), None) => text.as_bytes().to_vec(),
(None, Some(text), None) => {
if text.len() > MAX_FILE_BYTES {
return Err(too_large());
}
text.as_bytes().to_vec()
}
(None, None, Some(b64)) => {
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
return Err(too_large());
@@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history.
#[test]
fn import_file_byte_boundaries_preserve_the_document_on_refusal() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap();
let before = steps(&s);
let large = " ".repeat(super::MAX_FILE_BYTES + 1);
for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] {
let error = s.execute("type.compositeFonts.import", &params).unwrap_err();
assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}");
assert_eq!(names(&s), ["Existing"]);
assert_eq!(steps(&s), before);
}
let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string();
exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len()));
let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap();
assert_eq!(imported["fonts"][0]["name"], "Imported");
assert_eq!(names(&s), ["Existing"]);
assert_eq!(steps(&s), before);
}
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
+77 -2
View File
@@ -3,6 +3,7 @@
//! circles selected; Keep Originals), which previews on the canvas and runs
//! `addon.pathtools.bridge` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::UnitKind;
use serde_json::{Value, json};
@@ -50,7 +51,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
("many", FieldValue::Bool(many)),
]);
let lengths = general_lengths(app);
dialogs::open(app, &SPEC, fields, move |_| {
dialogs::open(app, &SPEC, fields, move |fields| {
let rows = vec![
Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)),
Param::number("gap", tl!("Gap:"), GAP, 1.0, 2)
@@ -67,7 +68,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.enabled_when("many", FieldValue::Bool(true)),
Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)),
];
ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields))
})
}
@@ -83,6 +84,80 @@ mod tests {
app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
}
fn bridge_app(xs: &[f64]) -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect();
app.run("select.set", json!({"ids": ids})).unwrap();
app
}
fn geometry(app: &VectorcraftApp) -> Vec<vectorcraft_doc::NodeKind> {
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect()
}
fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) {
panel.click(label);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.frame();
}
#[test]
fn real_bridge_controls_change_the_preview_and_confirmed_geometry() {
use crate::tests::panel_harness::Panel;
let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs);
let before = panel.app().session.doc().unwrap().history.undo.len();
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance");
panel.click("Keep Originals");
type_number(&mut panel, "Radius", "150");
let id = dialog_id(&panel.app());
assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0));
let mut expected = bridge_app(&[100.0, 124.0]);
expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap();
assert_eq!(geometry(&panel.app()), geometry(&expected));
assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge");
panel.click("Constant Gap");
type_number(&mut panel, "Gap", "6");
let params = read(&panel.app(), id, super::params);
assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true}));
let mut expected = bridge_app(&[100.0, 124.0]);
expected.session.execute(super::COMMAND, &params).unwrap();
let preview = geometry(&panel.app());
assert_eq!(preview, geometry(&expected));
panel.click("OK");
panel.frame();
assert_eq!(geometry(&panel.app()), preview);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1);
assert!(!panel.app().any_dialog_open());
}
#[test]
fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() {
use crate::tests::panel_harness::Panel;
let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs);
let original = geometry(&panel.app());
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
assert!(panel.enabled("Reach"));
type_number(&mut panel, "Reach", "5");
let id = dialog_id(&panel.app());
let params = read(&panel.app(), id, super::params);
assert_eq!(params["reach"], 5.0);
let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]);
expected.session.execute(super::COMMAND, &params).unwrap();
assert_eq!(geometry(&panel.app()), geometry(&expected));
panel.click("Cancel");
panel.frame();
assert_eq!(geometry(&panel.app()), original);
}
#[test]
fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
+92 -2
View File
@@ -1,6 +1,7 @@
//! Divide into Dashes in the interface: its dialog (dash and gap lengths, Fit to Corners and Ends,
//! Remove Gaps), which previews on the canvas and runs `addon.pathtools.divideDashes` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
@@ -36,7 +37,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
("removeGaps", FieldValue::Bool(true)),
]);
let lengths = general_lengths(app);
dialogs::open(app, &SPEC, fields, move |_| {
dialogs::open(app, &SPEC, fields, move |fields| {
let rows = vec![
Param::number("dash", tl!("Dash:"), 10.0, 1.0, 2).length(lengths).bounds(Some(*DASHES.start()), Some(*DASHES.end())),
Param::number("gap", tl!("Gap:"), 0.0, 1.0, 2).length(lengths).bounds(Some(*GAPS.start()), Some(*GAPS.end())),
@@ -45,6 +46,95 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// PLAN: assumed `Param::enabled_above(key, threshold)` (pl.F4, forms-w1)
Param::new("removeGaps", tl!("Remove Gaps"), ParamKind::bool(true)).enabled_above("gap", 0.0),
];
ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).values(Bind::bound(fields)).previews(true)
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::addons::dialogs::tests::{dialog_id, open_item, read};
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let path = app.run("path.create", json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]})).unwrap();
app.run("select.set", json!({"ids": [path["id"]]})).unwrap();
app
}
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
crate::dialogs::host::pump(app, ui.ctx());
}
fn spans(app: &VectorcraftApp) -> Vec<(f64, f64)> {
app.session.active().unwrap().doc.layers[0]
.children()
.unwrap()
.iter()
.map(|node| {
let bounds = node.geometric_bounds().unwrap();
(bounds.x0, bounds.x1)
})
.collect()
}
/// Real input controls the preview and approval; Cancel restores the undivided path.
#[test]
fn keyboard_and_toggle_edits_control_dashes_preview_cancel_and_ok() {
let mut expected = app();
expected.run(COMMAND, json!({"dash": 30, "gap": 10, "fit": true, "removeGaps": false})).unwrap();
let expected = spans(&expected);
assert!(expected.len() > 1);
for cancel in [true, false] {
let app = app();
let original = app.session.active().unwrap().doc.clone();
let selection = app.session.active().unwrap().selection.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, draw);
panel.room(egui::vec2(800.0, 600.0));
open_item(&mut panel.app(), "Path Precision Tools", "Divide into Dashes…");
panel.frame();
panel.click_role("Preview", Role::CHECK_BOX);
let id = dialog_id(&panel.app());
for (label, key, text, value) in [("Dash", "dash", "30 pt", 30.0), ("Gap", "gap", "10 pt", 10.0)] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(read(&panel.app(), id, |fields| fields.number(key)), Some(value));
}
panel.click_role("Fit to Corners and Ends", Role::CHECK_BOX);
panel.click_role("Remove Gaps", Role::CHECK_BOX);
assert_eq!(read(&panel.app(), id, |fields| fields.bool("fit")), Some(true));
assert_eq!(read(&panel.app(), id, |fields| fields.bool("removeGaps")), Some(false));
panel.click_role("Preview", Role::CHECK_BOX);
let preview = spans(&panel.app());
assert_eq!(preview.len(), expected.len());
assert!(preview.iter().zip(&expected).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6));
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.click(if cancel { "Cancel" } else { "OK" });
assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty()));
assert!(!panel.app().session.in_interaction());
if cancel {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!(state.doc, original);
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
} else {
assert_eq!(spans(&panel.app()), preview);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
}
}
}
@@ -2,6 +2,7 @@
//! circle to draw, or all), which previews the circles on the canvas and runs
//! `addon.pathtools.tangentCircle` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
@@ -71,7 +72,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.enabled_when("twoShapes", FieldValue::Bool(true)),
Param::new("circle", tl!("Circle:"), ParamKind::choice(options, Some("0".into()))),
];
ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true)
})
}
@@ -87,6 +88,97 @@ mod tests {
app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
}
#[test]
fn actual_radius_and_circle_edits_control_preview_cancel_and_ok() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let a = circle(&mut app, 100.0, 100.0, 10.0);
let b = circle(&mut app, 130.0, 100.0, 10.0);
app.run("select.set", json!({"ids": [a, b]})).unwrap();
app
}
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
crate::dialogs::host::pump(app, ui.ctx());
}
fn previewing(app: &VectorcraftApp) -> bool {
let id = dialog_id(app);
app.dialogs().unwrap().with(|host| host.get_by_id::<HostedParamDialog>(id).unwrap().is_previewing())
}
fn count(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().doc.layers[0].children().unwrap().len()
}
fn last_bounds(app: &VectorcraftApp) -> vectorcraft_geom::Rect {
app.session.active().unwrap().doc.layers[0].children().unwrap().last().unwrap().geometric_bounds().unwrap()
}
let mut expected = app();
expected.run(super::COMMAND, json!({"radius": 20, "circle": 2})).unwrap();
let expected = last_bounds(&expected);
for cancel in [true, false] {
let app = app();
let original = app.session.active().unwrap().doc.clone();
let selection = app.session.active().unwrap().selection.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, draw);
panel.room(egui::vec2(800.0, 600.0));
crate::addons::dialogs::tests::open_item(&mut panel.app(), "Path Precision Tools", "Tangent Circle…");
panel.frame();
let id = dialog_id(&panel.app());
assert!(previewing(&panel.app()), "the hosted dialog starts with Preview on");
assert_eq!(count(&panel.app()), 10);
panel.click_role("Preview", Role::CHECK_BOX);
assert!(!previewing(&panel.app()));
assert_eq!(panel.app().session.active().unwrap().doc, original);
panel.click_role("Radius", Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("20 pt");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(read(&panel.app(), id, |fields| fields.number("radius")), Some(20.0));
assert_eq!(count(&panel.app()), 2, "editing with Preview off keeps the originals");
panel.click_role("Preview", Role::CHECK_BOX);
assert!(previewing(&panel.app()));
assert_eq!(count(&panel.app()), 8);
assert_eq!(read(&panel.app(), id, |fields| fields.int("found")), Some(6));
panel.click("Circle");
panel.click("2");
assert_eq!(read(&panel.app(), id, |fields| fields.text("circle").map(str::to_owned)), Some("2".into()));
assert_eq!(count(&panel.app()), 3);
let actual = last_bounds(&panel.app());
assert!((actual.x0 - expected.x0).abs() < 1e-6 && (actual.y0 - expected.y0).abs() < 1e-6);
assert!((actual.x1 - expected.x1).abs() < 1e-6 && (actual.y1 - expected.y1).abs() < 1e-6);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.click(if cancel { "Cancel" } else { "OK" });
assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty()));
assert!(!panel.app().session.in_interaction());
if cancel {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!(state.doc, original);
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
} else {
assert_eq!(count(&panel.app()), 3);
assert_eq!(last_bounds(&panel.app()), actual);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
}
}
#[test]
fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
+1 -4
View File
@@ -200,10 +200,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut
});
let relations: Vec<Entry<String>> = RELATIONS.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect();
Field::new(label(tl!("Select:"))).show(ui, |ui, _| {
let picked = Select::new(label(tl!("Select:")), Bind::given(fields.relation.clone()), &relations).show(ui).value().cloned();
if let Some(relation) = picked {
fields.relation = relation;
}
Select::new(label(tl!("Select:")), Bind::bound(&mut fields.relation), &relations).show(ui);
});
}
@@ -290,10 +290,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) {
TextField::search(label(tl!("Search images")), Bind::bound(&mut fields.search)).show(ui);
let shows: Vec<Entry<String>> = SHOW.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect();
Field::new(label(tl!("Show:"))).show(ui, |ui, _| {
let picked = Select::new(label(tl!("Show:")), Bind::given(fields.show.clone()), &shows).show(ui).value().cloned();
if let Some(show) = picked {
fields.show = show;
}
Select::new(label(tl!("Show:")), Bind::bound(&mut fields.show), &shows).show(ui);
});
let visible = shown(rows, &fields.search, &fields.show, &Env::of(ui).folder());
let lines: Vec<Line> = visible
@@ -95,6 +95,43 @@ fn selected(app: &VectorcraftApp) -> Vec<u64> {
ids
}
#[test]
fn canceling_a_keyboard_show_filter_restores_all_rows_before_selecting() {
use craft::ui::contract::Role;
let dir = Folder::new("cancel-show-filter");
let (app, river, harbour, stamp) = app(&dir);
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Show", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "linked");
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "all");
for name in ["river.png", "harbour.png", "stamp.png"] {
assert!(panel.shows(name), "canceling the filter restores {name}");
}
panel.click_role("All", Role::BUTTON);
panel.click_role("Zoom to Selection", Role::CHECK_BOX);
panel.click("Select");
let mut want = vec![river, harbour, stamp];
want.sort_unstable();
assert_eq!(selected(&panel.app()), want);
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Show", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "linked");
assert!(panel.shows("river.png"));
assert!(!panel.shows("harbour.png") && !panel.shows("stamp.png"));
panel.click("Cancel");
assert_eq!(selected(&panel.app()), want);
}
#[test]
fn the_message_says_what_was_selected_and_what_was_left_out() {
assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images");
+35
View File
@@ -39,6 +39,41 @@ fn names(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn canceling_a_keyboard_relation_choice_restores_the_original_selection_rule() {
use craft::ui::contract::Role;
let mut app = new_app();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
let edge = app.run("shape.rectangle", json!({"x": 90, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.none", json!({})).unwrap();
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Select", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "inside");
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "overlap");
panel.click("OK");
let mut actual = panel.app().session.active().unwrap().selection.objects.clone();
let mut expected = vec![vectorcraft_doc::NodeId(inside), vectorcraft_doc::NodeId(edge)];
actual.sort_unstable();
expected.sort_unstable();
assert_eq!(actual, expected);
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Select", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "inside");
panel.click("OK");
assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]);
}
/// A 100 × 100 document with a Banner artboard at x 150, an object in each artboard, and nothing selected.
fn banner() -> (VectorcraftApp, u64) {
let mut app = new_app();
+2 -1
View File
@@ -3,6 +3,7 @@
//! and runs `addon.type.textTweaker` on OK.
use craft::menu::Node;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::UnitKind;
use serde_json::{Value, json};
@@ -116,7 +117,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.enabled_when("shape", FieldValue::Text("random".into())),
Param::new("skipSpaces", tl!("Skip Spaces"), ParamKind::bool(true)),
]);
ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).values(Bind::bound(fields)).previews(true)
})
}
+79 -1
View File
@@ -6,13 +6,91 @@ use crate::addons::dialogs::tests::{dialog_id, frame, open_item, read, set};
/// A window's app with one type object, selected.
fn app() -> VectorcraftApp {
app_with_text("abc")
}
fn app_with_text(text: &str) -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap();
let id = app.run("text.create", json!({"x": 40, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app
}
/// The real form controls the same text changes as the command, including attribute-dependent
/// defaults, random seed and whether a space is included. Cancel restores the original text.
#[test]
fn keyboard_and_choice_edits_reach_text_tweaker_preview_and_approval() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
fn text(app: &VectorcraftApp) -> vectorcraft_doc::TextObject {
let state = app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
match &node.kind {
vectorcraft_doc::NodeKind::Text(text) => (**text).clone(),
_ => panic!("selected object is not text"),
}
}
fn type_number(panel: &mut Panel, label: &str, input: &str) {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
let params = json!({"attribute": "rotation", "from": 10.0, "to": 40.0, "shape": "random", "seed": 42, "skipSpaces": false});
let mut expected = app_with_text("a b");
expected.run(super::COMMAND, params.clone()).unwrap();
let expected = text(&expected);
for cancel in [true, false] {
let app = app_with_text("a b");
let original = app.session.active().unwrap().doc.clone();
let selection = app.session.active().unwrap().selection.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
open_item(&mut panel.app(), "Type Tools", "Text Tweaker…");
panel.frame();
let id = dialog_id(&panel.app());
assert!(panel.app().dialogs().unwrap().with(|host| host.get_by_id::<HostedParamDialog>(id).unwrap().is_previewing()));
panel.click_role("Preview", Role::CHECK_BOX);
assert_eq!(panel.app().session.active().unwrap().doc, original);
panel.click("Attribute");
panel.click("Character Rotation");
assert_eq!(read(&panel.app(), id, |fields| (fields.number("from"), fields.number("to"))), (Some(0.0), Some(30.0)));
type_number(&mut panel, "From", "10");
type_number(&mut panel, "To", "40");
panel.click("Shape");
panel.click("Random");
assert!(panel.enabled("Seed"));
type_number(&mut panel, "Seed", "42");
panel.click_role("Skip Spaces", Role::CHECK_BOX);
assert_eq!(read(&panel.app(), id, super::params), params);
assert_eq!(panel.app().session.active().unwrap().doc, original, "Preview off leaves the text unchanged");
panel.click_role("Preview", Role::CHECK_BOX);
assert_eq!(text(&panel.app()), expected, "the real controls reach the same text formatting as automation");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.click(if cancel { "Cancel" } else { "OK" });
assert!(!panel.app().any_dialog_open());
assert!(!panel.app().session.in_interaction());
if cancel {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!(state.doc, original);
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
} else {
assert_eq!(text(&panel.app()), expected);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
}
}
#[test]
fn another_attribute_starts_from_its_own_values() {
let mut app = app();
+48 -2
View File
@@ -82,9 +82,14 @@ fn start(app: &mut VectorcraftApp) -> Result<SpellingWalk, String> {
/// Open Check Spelling on the active document's type.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let w = start(app)?;
let items = items_of(app, &w)?;
let mut w = start(app)?;
let dialogs = app.dialogs().ok_or("no window")?;
let all_layers = dialogs.with(|host| host.get::<CheckSpellingDialog>().is_none_or(CheckSpellingDialog::all_layers_checked));
if !all_layers {
w.layer = w.shown.as_ref().map(|word| word.0);
advance(app, &mut w, None, 1)?;
}
let items = items_of(app, &w)?;
dialogs.with(|host| match host.get_mut::<CheckSpellingDialog>() {
Some(d) => d.restart(items),
None => {
@@ -971,6 +976,47 @@ mod tests {
assert_eq!(plain(&app, b), "fixed y");
}
#[test]
fn reopening_keeps_the_unchecked_all_layers_scope_for_change_all() {
use crate::tests::panel_harness::Panel;
use craft::ui::dialog::StackDialog as _;
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
super::pump(app, ui.ctx());
}
let _dictionary = crate::testing::custom_dictionary();
let mut app = app();
let first = text(&mut app, 50.0, WORD_A);
app.run("layer.new", json!({"name": "Other text"})).unwrap();
let second = text(&mut app, 100.0, WORD_A);
app.run("select.none", json!({})).unwrap();
let mut panel = Panel::new(app, draw);
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
let checked = shown(&panel.app()).0;
let other = if checked == first { second } else { first };
panel.click("Check All Layers");
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
{
let app = panel.app();
let ctx = panel.ctx();
app.dialogs().unwrap().with(|host| {
let dialog = host.get::<super::CheckSpellingDialog>().unwrap();
assert!(!dialog.all_layers_checked(), "reopening preserves the chosen scope");
let id = dialog.id();
host.set_json_field(ctx, id, "changeTo", json!("fixed")).unwrap();
});
}
panel.click("Change All");
assert_eq!(plain(&panel.app(), checked), "fixed");
assert_eq!(plain(&panel.app(), other), WORD_A, "the unchecked scope leaves the other layer's text alone");
}
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
+23 -14
View File
@@ -43,15 +43,23 @@ pub(crate) enum Target {
/// The stroke proxy.
Stroke,
/// The background colour of this artboard.
Artboard { document: u64, index: usize },
Artboard { document: u64, reverts: u64, index: usize },
/// A colour row `key` of the open dialog `parent`.
Answer { parent: DialogId, key: String },
}
impl Target {
fn in_active_document(&self, app: &VectorcraftApp) -> bool {
let Self::Artboard { document, .. } = self else { return true };
app.session.active().is_some_and(|st| st.uid == *document)
self.document_problem(app).is_none()
}
fn document_problem(&self, app: &VectorcraftApp) -> Option<&'static str> {
let Self::Artboard { document, reverts, .. } = self else { return None };
match app.session.active() {
Some(st) if st.uid == *document && st.reverts == *reverts => None,
Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")),
_ => Some(tl!("The active document changed while the Color Picker was open")),
}
}
}
@@ -160,14 +168,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let found = index.and_then(|i| {
let st = app.session.active()?;
let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE);
Some((st.uid, i, color))
Some((st.uid, st.reverts, i, color))
});
Some(found.ok_or("no such artboard")?)
}
};
let color = match (p.get("color"), artboard) {
(Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?,
(None, Some((_, _, c))) => c,
(None, Some((_, _, _, c))) => c,
(None, None) => proxy_color(app, stroke),
};
let dialogs = app.dialogs().ok_or("no window")?;
@@ -195,18 +203,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
dialog = dialog.kept(model_values(&color));
}
// The host replaces a picker only for the same document and artboard.
if let Some((document, index, _)) = artboard {
if let Some((document, _, index, _)) = artboard {
dialog = dialog.instance((document, index));
}
let id = dialogs.with(|h| h.open(dialog));
// A picker the open replaced leaves its preview behind: end it.
let before = app.color_dialogs.pickers.len();
app.color_dialogs.pickers.retain(|o| o.id != id);
if app.color_dialogs.pickers.len() != before {
let _ = app.session.cancel_interaction();
if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) {
let retired = app.color_dialogs.pickers.remove(at);
if retired.target.in_active_document(app) {
let _ = app.session.cancel_interaction();
}
}
let target = match artboard {
Some((document, index, _)) => Target::Artboard { document, index },
Some((document, reverts, index, _)) => Target::Artboard { document, reverts, index },
None if stroke => Target::Stroke,
None => Target::Fill,
};
@@ -284,10 +293,10 @@ fn finish(
open: &mut Open,
result: Option<DialogResult<craft::color_ui::ui::ColorPickerResult>>,
) {
// Switching documents rolls back the source preview. Do not settle it against the new drawing.
if !open.target.in_active_document(app) {
// Switching or restoring a drawing ends the preview belonging to its old contents.
if let Some(reason) = open.target.document_problem(app) {
if matches!(result, Some(DialogResult::Ok(_))) {
app.status("The active document changed while the Color Picker was open");
app.status(reason);
}
return;
}
@@ -287,3 +287,44 @@ fn sampler_above_the_field_previews_and_cancel_restores_the_original() {
cancel(&mut app, &ctx);
assert_eq!(fill_hex(&app), original);
}
#[test]
fn the_artboard_picker_leaves_restored_artboards_unchanged() {
for accept in [true, false] {
let (mut app, ctx) = app();
app.run("artboard.new", json!({})).unwrap();
app.run("artboard.setProps", json!({"index": 1, "color": "#123456"})).unwrap();
let dir = vectorcraft_testkit::TempDir::new("artboard-picker-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("artboard.setProps", json!({"index": 1, "color": "#ff0000"})).unwrap();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#abcdef");
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = artboard_color(&app);
assert_eq!(restored.map(|c| c.to_hex()).as_deref(), Some("#123456"));
let steps = undo_len(&app);
frame(&mut app, &ctx);
assert_eq!(artboard_color(&app), restored);
assert!(!app.session.in_interaction());
if accept {
ok(&mut app, &ctx);
assert!(app.ui.status.contains("document was reverted"));
} else {
app.begin_interaction("New drawing edit").unwrap();
cancel(&mut app, &ctx);
assert!(app.session.in_interaction());
app.session.cancel_interaction().unwrap();
}
assert_eq!(artboard_color(&app), restored);
assert_eq!(undo_len(&app), steps);
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#abcdef");
ok(&mut app, &ctx);
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef"));
}
}
+73 -2
View File
@@ -88,8 +88,10 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
let token = Arc::new(());
let dialog = {
let (key, heading, opening) = (command.to_string(), heading_label(label), params.clone());
HostedParamDialog::command(&ctx, command, fields, move |_: &mut DialogFields| {
ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)).previews(previews)
HostedParamDialog::command(&ctx, command, fields, move |fields| {
ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting))
.previews(previews)
.values(craft::ui::contract::Bind::bound(fields))
})
// The Preview box starts off, as production's dialogs did (#5360).
.preview_off()
@@ -590,6 +592,75 @@ mod tests {
crate::panels::pattern_options::repeat_fields(app).unwrap()["cols"].as_u64().unwrap()
}
#[test]
fn hosted_commands_keep_actual_keyboard_edits_until_ok() {
use egui::accesskit::Role;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let type_and_accept = |app: &mut VectorcraftApp, command: &str, name: &str, role: Role, value: &str, preview: bool| {
let ctx = app.ui_ctx.clone().unwrap();
let time = std::cell::Cell::new(0.0);
let frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
ctx.enable_accesskit();
time.set(time.get() + 0.1);
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time.get()), screen_rect: Some(viewport), ..Default::default() })
};
let locate = |app: &mut VectorcraftApp, label: &str, role: Role| {
frame(app, vec![]);
let nodes = frame(app, vec![]).platform_output.accesskit_update.unwrap().nodes;
let node = nodes
.iter()
.map(|(_, node)| node)
.find(|node| {
node.role() == role
&& (node.label() == Some(label)
|| node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label))))
})
.unwrap_or_else(|| panic!("{command}: missing {role:?} {label}"));
let b = node.bounds().unwrap();
let at = pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5);
assert!(viewport.contains(at), "{command}: {label} is reachable");
at
};
let click = |app: &mut VectorcraftApp, at: Pos2| {
frame(app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
};
frame(app, vec![]);
assert_eq!(ctx.content_rect(), viewport);
crate::menus::invoke(app, command, json!({}));
let id = id_of(app);
if preview {
let toggle = locate(app, "Preview", Role::CheckBox);
click(app, toggle);
assert!(app.session.in_interaction(), "{command}: pointer turns Preview on");
}
let at = locate(app, name, role);
click(app, at);
frame(app, vec![Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]);
frame(app, vec![Event::Text(value.to_owned())]);
frame(app, vec![Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
frame(app, vec![]);
let live_columns = preview.then(|| cols(app));
let ok = locate(app, "OK", Role::Button);
click(app, ok);
frame(app, vec![]);
assert!(app.dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).is_none()), "{command}: OK closes the dialog");
live_columns
};
let (mut repeat, _) = prepared("object.repeat.options");
let preview = type_and_accept(&mut repeat, "object.repeat.options", "Columns", Role::SpinButton, "5", true);
let (mut selection, _) = prepared("select.save");
type_and_accept(&mut selection, "select.save", "Name", Role::TextInput, "Typed selection", false);
let saved = &selection.session.active().unwrap().doc.saved_selections;
assert_eq!((preview, cols(&repeat), saved.last().map(|s| s.name.as_str())), (Some(5), 5, Some("Typed selection")));
}
#[test]
fn area_type_options_choices_match_the_params_doc() {
let doc = vectorcraft_engine::find_command("text.areaOptions").unwrap().params;
+15 -9
View File
@@ -57,7 +57,7 @@ use egui::{Context, Ui};
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{COMPOSITE_BASELINE, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CustomCharSet};
use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes};
use vectorcraft_engine::cmd::compositefonts::{EXTS, MAX_FILE_BYTES, file_bytes};
use vectorcraft_text::FontDb;
use crate::VectorcraftApp;
@@ -137,7 +137,7 @@ enum PartEdit {
/// [`COMMAND`] and answers whether the dialog may close.
pub struct CompositeFontsDialog {
/// The document whose fonts the draft edits.
document: u64,
document: (u64, u64),
fonts: Vec<CompositeFont>,
/// The index of the font picked.
selected: usize,
@@ -172,7 +172,7 @@ pub struct CompositeFontsDialog {
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?;
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
let dialog = CompositeFontsDialog::new(document.uid, document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app));
let dialog = CompositeFontsDialog::new((document.uid, document.reverts), document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app));
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -244,7 +244,7 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> {
impl CompositeFontsDialog {
/// The dialog over `fonts`, the first picked.
fn new(document: u64, fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
fn new(document: (u64, u64), fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
let mut sample = Map::new();
sample::defaults(&mut sample);
CompositeFontsDialog {
@@ -862,11 +862,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
}) else {
return;
};
if let Some((document, fonts)) = held {
let answer = if app.session.active().is_some_and(|active| active.uid == document) {
app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from)
} else {
Err(Label::from(tl!("Composite Fonts can only change the document where it was opened.").to_owned()))
if let Some(((document, reverts), fonts)) = held {
let answer = match app.session.active().filter(|active| active.uid == document) {
Some(active) if active.reverts == reverts => app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from),
Some(_) => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))),
None => Err(Label::from(tl!("Composite Fonts can only change the document where it was opened."))),
};
with_dialog(app, |d| d.held.answer(answer));
}
@@ -899,6 +899,12 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>
/// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…).
fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result<Value, String> {
// Refuse the browser's raw file before open_params allocates its base64 representation.
if let Picked::Contents(files) = picked
&& files.first().is_some_and(|(_, bytes)| bytes.len() > MAX_FILE_BYTES)
{
return Err(vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string());
}
let Some(mut params) = open_params(picked) else { return Ok(Value::Null) };
let browser_name = params.remove("name");
let name = picked
@@ -127,6 +127,42 @@ fn load_and_replace_accept_a_browser_picked_file() {
}
}
/// Load and Replace refuse an oversized browser file while preserving both the draft and artwork;
/// a later valid file still reaches that same draft.
#[test]
fn oversized_browser_composite_font_files_leave_the_draft_unchanged() {
for command in [PresetCommands::Load, PresetCommands::Replace] {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Draft".into()));
let dialogs = app.dialogs().unwrap();
ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear();
let before = dialog(&mut app, |d| d.fonts.clone());
let bytes = file_bytes(&before).unwrap();
let step = steps(&app);
let large = vec![b' '; MAX_FILE_BYTES + 1];
request(&mut app, command, None);
picker.answer_contents(&[("large.vccomposite", &large)]);
poll(&mut app, &ctx);
assert_eq!(
app.ui.status,
vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string()
);
assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before);
assert!(names(&app).is_empty());
assert_eq!(steps(&app), step);
request(&mut app, command, None);
picker.answer_contents(&[("valid.vccomposite", &bytes)]);
poll(&mut app, &ctx);
assert!(app.ui.status.contains("valid.vccomposite"), "{}", app.ui.status);
assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before);
assert!(names(&app).is_empty());
assert_eq!(steps(&app), step);
}
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
@@ -575,3 +611,33 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() {
assert!(p.shows(name), "{name} is drawn");
}
}
#[test]
fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() {
let mut app = app();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Saved Font".into()));
ok(&mut app).unwrap();
let dir = vectorcraft_testkit::TempDir::new("composite-fonts-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Unsaved Font".into()));
ok(&mut app).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Stale Draft Font".into()));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored_step = steps(&app);
assert_eq!(names(&app), ["Saved Font"]);
assert_eq!(ok(&mut app), Err("The document was reverted. Reopen this dialog to continue.".into()));
assert_eq!(names(&app), ["Saved Font"]);
assert_eq!(steps(&app), restored_step);
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Fresh Font".into()));
ok(&mut app).unwrap();
assert_eq!(names(&app), ["Saved Font", "Fresh Font"]);
}
+40 -1
View File
@@ -9,6 +9,7 @@
use std::collections::BTreeSet;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
use serde_json::{Value, json};
@@ -65,7 +66,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let lengths = general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(fields.text("radii") == Some("relative"), lengths));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
dialog(fields.text("radii") == Some("relative"), lengths).values(Bind::bound(fields))
});
open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
}
@@ -341,4 +344,40 @@ mod tests {
app.run("edit.undo", json!({})).unwrap();
assert!(!lc(&app).0, "undo brings back absolute radii");
}
#[test]
fn a_live_radius_edit_applies_to_the_corners_that_opened_the_dialog() {
use craft::ui::testing::Fixture;
use std::cell::RefCell;
use std::rc::Rc;
let (app, id) = app();
let app = Rc::new(RefCell::new(app));
let shown = app.clone();
let mut fixture = Fixture::new(move |ui| {
let mut app = shown.borrow_mut();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.run(ui));
super::super::host::pump(&mut app, ui.ctx());
});
fixture.room(egui::vec2(880.0, 720.0));
let undo = {
let mut app = app.borrow_mut();
app.ui_ctx = Some(fixture.ctx().clone());
app.run("ui.corners", json!({"id": id, "corners": [1, 3]})).unwrap();
app.session.active().unwrap().history.undo.len()
};
fixture.settle();
let radius = fixture.by_label("Radius:").or_else(|| fixture.by_label("Radius")).expect("the Corners radius field");
fixture.click(&radius).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("12").key(egui::Key::Tab, egui::Modifiers::NONE).settle();
let ok = fixture.by_label("OK").expect("the Corners confirmation button");
fixture.click(&ok).settle();
let mut app = app.borrow_mut();
assert_eq!(corners(&app, id).0, [0.0, 12.0, 0.0, 12.0], "OK applies the typed radius only to the opening corners");
assert!(!is_open(&app));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(corners(&app, id).0, [0.0; 4]);
}
}
+68 -3
View File
@@ -103,15 +103,22 @@ pub(crate) fn effect_params(cx: &EffectCx, fields: &DialogFields) -> Vec<Param>
}
}
/// One row per default of an effect without a builder: the JSON type of the default decides the
/// kind, and the rows follow the effect's parameter documentation.
/// One row per default of a built-in effect without a builder: the JSON type of the default decides
/// the kind, labels use the UI language, and the rows follow the effect's parameter documentation.
pub(super) fn generic(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
let id = cx.id.as_str();
let Some(info) = vectorcraft_effects::effect_info(id) else { return Vec::new() };
let relative = fields.contains("relative") && effect_rows::is_relative(fields);
let mut defaults: Vec<(&String, &Value)> = info.defaults.as_object().into_iter().flatten().collect();
defaults.sort_by_key(|(key, _)| doc_rank(info.params, key));
defaults.into_iter().filter_map(|(key, default)| generic_row(cx, key, default, relative)).collect()
defaults
.into_iter()
.filter_map(|(key, default)| {
let mut row = generic_row(cx, key, default, relative)?;
row.label = tl!(row.label.as_str()).to_owned().into();
Some(row)
})
.collect()
}
/// One row per stored value of an effect that has no rows of its own (a plug-in no longer
@@ -294,3 +301,61 @@ pub(super) fn doc_rank(doc: &str, key: &str) -> usize {
.find(|at| starts(*at) && doc.get(at + key.len()..).is_some_and(|rest| rest.starts_with(':') || rest.starts_with("?:")))
.unwrap_or(usize::MAX)
}
#[cfg(test)]
mod tests {
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
#[test]
fn gallery_cutout_setting_uses_its_localized_label() {
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut shown_labels = Vec::new();
for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.prefs.interface_language = language.to_owned();
let lang = app.ui_language();
let ctx = app.ui_ctx.clone().unwrap();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
ctx.enable_accesskit();
time += 0.1;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(viewport), ..Default::default() })
};
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let square = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
frame(&mut app, vec![]);
assert_eq!(ctx.content_rect(), viewport);
app.run("ui.effectGalleryDialog", json!({})).unwrap();
frame(&mut app, vec![]);
let nodes = frame(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes;
let filter = crate::i18n::effect_name(lang, "artistic.cutout").unwrap();
let bounds = nodes.iter().filter(|(_, node)| node.label() == Some(filter.as_str())).find_map(|(_, node)| node.bounds()).unwrap();
let at = pos2((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5);
assert!(viewport.contains(at), "{language}: Cutout is reachable");
frame(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(&mut app, vec![]);
let output = frame(&mut app, vec![]);
let state = app.session.active().unwrap();
let affected = &state.doc.node(NodeId(square)).unwrap().appearance.effects;
assert_eq!(affected.first().map(|effect| effect.id.as_str()), Some("artistic.cutout"), "{language}: Cutout is previewed");
let nodes = output.platform_output.accesskit_update.unwrap().nodes;
let found = [expected, "Levels"].into_iter().find(|label| {
nodes
.iter()
.any(|(_, node)| node.label() == Some(*label) && node.bounds().is_some_and(|b| viewport.contains(pos2(b.x0 as f32, b.y0 as f32))))
});
eprintln!("{language}: expected {expected:?}, found {found:?}");
shown_labels.push(found);
}
assert_eq!(shown_labels, [Some("Levels"), Some("Stufen"), Some("レベル数")]);
}
}
+109 -1
View File
@@ -197,7 +197,7 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String,
let fields = fields_of(&params(kind, &DialogFields::new()), &values);
let dialog = HostedParamDialog::command(&ctx, kind, fields, move |fields| {
let reset = fields.bool("reset").unwrap_or(false);
ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope)
ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope).values(Bind::bound(fields))
});
let generation = OPENED.fetch_add(1, Ordering::Relaxed);
let cancel = Box::new(move |app: &mut VectorcraftApp| {
@@ -453,6 +453,114 @@ mod tests {
app.effect_dialogs.envelope.as_ref().map(|open| open.id).expect("an open envelope dialog")
}
fn type_count(panel: &mut crate::tests::panel_harness::Panel, name: &str, text: &str) {
panel.click(name);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.frame();
}
#[test]
fn real_warp_choice_radio_and_slider_edits_reach_the_preview_and_ok() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let (app, _) = app_with_rect();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
let before = panel.app().session.doc().unwrap().history.undo.len();
crate::menus::invoke(&mut panel.app(), MAKE_WARP, json!({}));
panel.frame();
let opening_bounds = envelope(&panel.app()).1.geometric_bounds();
panel.click_role("Style", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
panel.click("Vertical");
panel.click_role("Bend", Role::SLIDER);
panel.key(egui::Key::ArrowLeft, egui::Modifiers::NONE);
panel.frame();
let id = dialog(&panel.app());
let fields = json_fields(&panel.app(), id);
assert_ne!(fields["style"], "arc");
assert_ne!(fields["bend"], 50.0);
let preview = envelope(&panel.app()).1;
let NodeKind::Envelope { ref kind, .. } = preview.kind else { panic!("an envelope preview") };
let EnvelopeKind::Warp { style, bend, horizontal, .. } = &**kind else { panic!("a warp") };
assert_eq!(style.as_str(), fields["style"].as_str().unwrap());
assert_eq!(*bend, fields["bend"].as_f64().unwrap());
assert!(!*horizontal);
let bounds = preview.geometric_bounds();
assert_ne!(bounds, opening_bounds, "the nondefault warp changes the preview geometry");
panel.click("OK");
panel.frame();
panel.frame();
assert!(open_ids(&panel.app()).is_empty());
assert_eq!(envelope(&panel.app()).1.geometric_bounds(), bounds);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1);
}
#[test]
fn real_mesh_counts_and_reset_maintain_shape_edits_reach_the_model() {
use crate::tests::panel_harness::Panel;
let (app, _) = app_with_rect();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({}));
type_count(&mut panel, "Rows", "2");
type_count(&mut panel, "Columns", "3");
assert!(
matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 2, cols: 3, .. }))
);
panel.click("OK");
panel.frame();
panel.frame();
let confirmed = envelope(&panel.app()).1;
crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({}));
panel.frame();
assert!(panel.shows("Maintain Envelope Shape"));
panel.click("Maintain Envelope Shape");
type_count(&mut panel, "Rows", "1");
let id = dialog(&panel.app());
assert_eq!(json_fields(&panel.app(), id)["maintainShape"], false);
assert!(
matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 1, cols: 3, .. }))
);
panel.click("Cancel");
panel.frame();
assert_eq!(envelope(&panel.app()).1, confirmed);
}
#[test]
fn real_options_controls_enable_dependents_and_confirm_defaults_without_preview() {
use crate::tests::panel_harness::Panel;
let (mut app, _) = app_with_rect();
app.run(OPTIONS_CMD, json!({"distortAppearance": false, "distortLinearGradients": false})).unwrap();
let initial = app.session.execute("object.envelope.info", &json!({})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({}));
panel.frame();
assert!(!panel.enabled("Distort Linear Gradients"));
panel.click("Distort Appearance");
assert!(panel.enabled("Distort Linear Gradients"));
panel.click("Distort Linear Gradients");
panel.click("Anti-Alias");
assert!(!panel.app().session.in_interaction(), "defaults have no artwork preview");
panel.click("OK");
panel.frame();
panel.frame();
let info = panel.app().session.execute("object.envelope.info", &json!({})).unwrap();
assert_eq!(info["distortAppearance"], true);
assert_eq!(info["distortLinearGradients"], true);
assert_eq!(info["antiAlias"].as_bool(), initial["antiAlias"].as_bool().map(|on| !on));
crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({}));
panel.frame();
panel.click("Anti-Alias");
panel.click("Cancel");
panel.frame();
assert_eq!(panel.app().session.execute("object.envelope.info", &json!({})).unwrap(), info);
}
#[test]
fn warp_dialog_previews_and_ok_keeps_one_step() {
let (mut app, rect) = app_with_rect();
+73 -2
View File
@@ -10,7 +10,7 @@
//! `object.expand.info`), `__canGradient` (Expand Gradient To applies) and `__canSteps` (it
//! applies and makes objects). What only the art of symbol instances holds needs Object on.
use craft::ui::contract::SaveKey;
use craft::ui::contract::{Bind, SaveKey};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::memory::Lifetime;
use serde_json::{Value, json};
@@ -152,7 +152,7 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result<HostedParamDialog, S
let rows = rows();
Ok(HostedParamDialog::new(ctx, KIND, fields, move |fields| {
refresh(info, fields);
ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run)
ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run).values(Bind::bound(fields))
}))
}
@@ -233,6 +233,77 @@ mod tests {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()))
}
#[test]
fn actual_fill_and_stroke_choices_leave_those_paints_unexpanded() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
gradient_rectangle(&mut app);
app.run("paint.setStroke", json!({"color": "#000000"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
panel.app().run("ui.expandDialog", json!({})).unwrap();
panel.click_role("Fill", Role::CHECK_BOX);
panel.click_role("Stroke", Role::CHECK_BOX);
let edited = fields(&panel.app());
assert_eq!((edited.bool("fill"), edited.bool("stroke")), (Some(false), Some(false)));
assert_eq!(edited.bool("__canGradient"), Some(false));
assert!(!panel.enabled("Gradient Mesh"));
assert!(!panel.enabled("Objects"));
panel.click("OK");
assert!(!is_open(&panel.app()));
let app = panel.app();
let state = app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
assert!(matches!(node.kind, NodeKind::Path { .. }), "the object remains one path");
assert!(matches!(node.appearance.fill_paint(), vectorcraft_color::Paint::Gradient(_)), "unticked Fill keeps its gradient");
assert!(!node.appearance.stroke_paint().is_none(), "unticked Stroke keeps its stroke");
assert_eq!(state.history.undo.len(), undo + 1);
}
#[test]
fn actual_gradient_controls_apply_and_remember_the_typed_object_count() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
gradient_rectangle(&mut app);
let original = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
panel.app().run("ui.expandDialog", json!({})).unwrap();
panel.click_role("Gradient Mesh", Role::RADIO_BUTTON);
assert_eq!(fields(&panel.app()).text("gradient"), Some("mesh"));
assert!(!panel.enabled("Objects"));
let specify = if panel.shows("Specify") { "Specify" } else { "Specify:" };
panel.click_role(specify, Role::RADIO_BUTTON);
assert!(panel.enabled("Objects"));
panel.click_role("Objects", Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("4");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(fields(&panel.app()).number("steps"), Some(4.0));
panel.click("OK");
assert!(!is_open(&panel.app()));
{
let app = panel.app();
let state = app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
let NodeKind::Group { children, clip: true } = &node.kind else { panic!("a gradient clip group") };
assert_eq!(children.iter().filter(|child| matches!(child.kind, NodeKind::Path { clipping: false, .. })).count(), 4);
assert_eq!(state.history.undo.len(), undo + 1);
}
panel.app().run("edit.undo", json!({})).unwrap();
panel.app().run("ui.expandDialog", json!({})).unwrap();
panel.frame();
assert_eq!(fields(&panel.app()).number("steps"), Some(4.0), "a successful real edit is remembered");
panel.click("Cancel");
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
fn ctx(app: &VectorcraftApp) -> egui::Context {
app.ui_ctx.clone().expect("the test context")
}
+2 -2
View File
@@ -52,7 +52,7 @@ pub(crate) enum Export {
/// Save for Office Documents.
Office,
/// Text Export Options.
Text,
Text { source: Option<text_export::SelectionSource> },
/// The options a save or open asks for before it goes on, for `action`.
Save {
/// The action the options belong to.
@@ -161,7 +161,7 @@ fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Resu
Export::Dxf => dxf_options::confirm(app, open, fields),
Export::Hpgl { .. } => hpgl_options::confirm(app, open, fields),
Export::Office => office_export::confirm(app, open, fields),
Export::Text => text_export::confirm(app, open, fields),
Export::Text { source } => text_export::confirm(app, open, source.as_ref(), fields),
Export::Save { .. } => save_options::confirm(app, open, fields),
}
}
+71 -3
View File
@@ -175,12 +175,13 @@ pub(crate) fn custom_dialog(ctx: &egui::Context, parent: &HostedPdfExport, job:
as_written(&mut o, parent.settings().advanced.overprint);
let mut fields = option_fields(&o);
fields.set(KEPT_OVERPRINTS, kept);
HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |_| {
HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |fields| {
ParamDialog::new(
CUSTOM_KEY,
tl!("Custom Transparency Flattener Options"),
option_params(&FIXED, tl!("PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept.")),
)
.values(Bind::bound(fields))
})
}
@@ -213,8 +214,8 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field
/// Open Flatten Transparency for the selection with the default preset.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |_| {
ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).previews(true)
let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| {
ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true)
})
// Flattening complex art is slow: the preview waits until it is turned on.
.preview_off();
@@ -450,4 +451,71 @@ mod tests {
create(&mut app, &ctx, id, params, "High Resolution");
assert_eq!(app.session.prefs.flattener_presets.len(), 1);
}
#[test]
fn flattened_art_resolution_keeps_a_live_keyboard_edit() {
assert_live_resolution(false);
}
#[test]
fn pdf_flattener_resolution_keeps_a_live_keyboard_edit() {
assert_live_resolution(true);
}
fn assert_live_resolution(custom: bool) {
use craft::ui::testing::Fixture;
use std::cell::RefCell;
use std::rc::Rc;
let app = Rc::new(RefCell::new(scene()));
let shown = app.clone();
let mut fixture = Fixture::new(move |ui| {
let mut app = shown.borrow_mut();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.run(ui));
super::super::host::pump(&mut app, ui.ctx());
});
fixture.room(egui::vec2(880.0, 720.0));
let ctx = fixture.ctx().clone();
let document = app.borrow().session.active().unwrap().uid;
let mut job = SavePdfJob {
document,
path: None,
save_mode: None,
flattener: Some(FlattenOptions { line_art_ppi: 611.0, ..FlattenOptions::default() }),
selection: false,
};
let parent = HostedPdfExport::new(vectorcraft_pdf::APP, vectorcraft_pdf::PdfSettings::default());
let id = {
let mut app = app.borrow_mut();
app.ui_ctx = Some(ctx.clone());
if custom {
let dialog = custom_dialog(&ctx, &parent, &job, &[]);
app.dialogs().unwrap().with(|host| host.open(dialog))
} else {
open(&mut app).unwrap();
app.flatten_dialog.open.as_ref().unwrap().id
}
};
fixture.settle();
let field = fixture
.by_label("Line Art and Text Resolution")
.or_else(|| fixture.by_label("Line Art and Text Resolution:"))
.expect("the hosted resolution field");
if custom {
let fields = app.borrow().dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone());
assert_eq!(fields.number("lineArtPpi"), Some(611.0), "the PDF dialog opens with the job's own resolution");
}
fixture.click(&field).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("399").key(egui::Key::Tab, egui::Modifiers::NONE).settle();
let app = app.borrow();
let fields = app.dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone());
assert_eq!(fields.number("lineArtPpi"), Some(399.0), "the hosted form keeps its keyboard edit");
if custom {
apply_custom(&mut job, &parent, &fields, &[]).unwrap();
assert_eq!(job.flattener.unwrap().line_art_ppi, 399.0);
} else {
let params = command_params(&option_params(&[], ""), &fields, &[]).unwrap();
assert_eq!(params["lineArtPpi"], 399.0);
}
}
}
+278 -12
View File
@@ -102,11 +102,63 @@ impl TargetKey {
}
}
/// A Color mode command from the popover's menu that has not been seen to finish.
struct OwnMode {
/// The document's history step when it ran.
from: (u64, u64),
/// The mode it picked.
mode: ColorPanelMode,
/// The Color panel showed `mode` at an earlier pass with no new history step.
shown: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum OwnModeNow {
/// No command is pending.
None,
/// The command has not been seen to finish.
Waiting,
/// The command made the new history step: the changed paint is the popover's own edit.
Edited,
/// The command finished without a history step.
Unchanged,
}
impl OwnMode {
/// What the command has done by this pass, with the document at history `step` and the Color panel showing
/// `shown_mode`. The first new history step after it is its own edit. Once the panel shows the picked mode, one
/// more pass with no new step means it changed nothing.
fn now(&mut self, step: Option<(u64, u64)>, shown_mode: ColorPanelMode) -> OwnModeNow {
if step != Some(self.from) {
return OwnModeNow::Edited;
}
if shown_mode != self.mode {
return OwnModeNow::Waiting;
}
if std::mem::replace(&mut self.shown, true) { OwnModeNow::Unchanged } else { OwnModeNow::Waiting }
}
}
/// The gradient in that slot as the popover last saw it, including any live edits it applied.
#[derive(Clone)]
struct TargetOwner {
key: TargetKey,
paints: Arc<TargetPaints>,
/// The history step when the popover took `paints`.
step: Option<(u64, u64)>,
/// The document's count of Undo and Redo steps as of the popover's last pass.
restores: Option<u64>,
/// The paints the popover owned before its own later edits, newest last, each with the history step it was
/// current at and the stop or point it edited then, so that Undo and Redo of those edits keep it open on the
/// same stop or point.
earlier: Vec<Earlier>,
}
#[derive(Clone)]
struct Earlier {
step: Option<(u64, u64)>,
key: TargetKey,
paints: Arc<TargetPaints>,
}
struct TargetPaints {
@@ -115,10 +167,49 @@ struct TargetPaints {
}
impl TargetOwner {
/// The most earlier paints kept.
const EARLIER: usize = 32;
fn new(key: TargetKey, paints: Arc<TargetPaints>, step: Option<(u64, u64)>, restores: Option<u64>) -> Self {
Self { key, paints, step, restores, earlier: Vec::new() }
}
fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool {
self.key.matches(app, target)
&& self.paints.shown == *target.paint()
&& app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|paints| paints == self.paints.edited)
self.key.matches(app, target) && self.owns(app, target, &self.paints)
}
/// The earlier owned paint and stop or point that the target shows now after Undo or Redo of one of the popover's
/// own edits. A stop selected after Undo that is not the one that paint belonged to matches nothing, and so does
/// an earlier paint set again by anything other than Undo or Redo.
fn owned_earlier(&self, app: &VectorcraftApp, target: &Target, restores: Option<u64>) -> Option<TargetKey> {
if restores == self.restores {
return None;
}
self.earlier.iter().rev().find(|e| e.key.matches(app, target) && self.owns(app, target, &e.paints)).map(|e| e.key.clone())
}
fn owns(&self, app: &VectorcraftApp, target: &Target, paints: &TargetPaints) -> bool {
paints.shown == *target.paint() && app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|now| now == paints.edited)
}
/// The popover now owns `paints`, taken at history step `step`; the paints it owned until now are kept as earlier
/// ones, with `was`, the stop or point they belonged to.
fn adopt(&mut self, paints: Arc<TargetPaints>, was: TargetKey, step: Option<(u64, u64)>) {
let old = std::mem::replace(&mut self.paints, paints);
let old_step = std::mem::replace(&mut self.step, step);
self.earlier.retain(|e| !Arc::ptr_eq(&e.paints, &old));
// Undo and Redo return only to the first or the last paints of one history step. The samples of a live drag
// between them replace each other, so a long drag does not push out the paints before it.
if let [.., before, last] = self.earlier.as_slice()
&& before.step == old_step
&& last.step == old_step
{
self.earlier.pop();
}
self.earlier.push(Earlier { step: old_step, key: was, paints: old });
if self.earlier.len() > Self::EARLIER {
self.earlier.remove(0);
}
}
}
@@ -237,6 +328,8 @@ struct Filed {
panels: Vec<ColorPanelOutput>,
/// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command.
mode: Option<ColorPanelMode>,
/// The mode whose row of the popover's Color mode menu ran its command this pass.
mode_command: Option<ColorPanelMode>,
}
/// The gradient stop popover.
@@ -253,6 +346,9 @@ pub(crate) struct GradientStopPopover {
/// The fields set from outside, applied at confirm.
set: PopoverFields,
filed: Filed,
/// A command the popover's Color mode menu ran, which runs outside `pump`: the document's history step when it
/// ran, the mode it picked, and whether the Color panel already showed that mode at an earlier pass.
own_mode: Option<OwnMode>,
}
impl GradientStopPopover {
@@ -266,6 +362,7 @@ impl GradientStopPopover {
feed: None,
set: PopoverFields::default(),
filed: Filed::default(),
own_mode: None,
}
}
@@ -360,7 +457,9 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true);
}
if *tab == Tab::Color {
outside |= mode_menu(ui, &feed.shown, panel.mode);
let (closed, picked) = mode_menu(ui, &feed.shown, panel.mode);
outside |= closed;
filed.mode_command = picked.or(filed.mode_command);
}
});
match *tab {
@@ -389,8 +488,9 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
}
/// The Color panel's existing five mode commands. Native menu ownership keeps its parent popover
/// open on a pick and gives the child the first Escape, including rows outside the parent bounds.
fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) -> bool {
/// open on a pick and gives the child the first Escape, including rows outside the parent bounds. Returns whether
/// an outside press closed the menu, and the mode whose row ran its command.
fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) -> (bool, Option<ColorPanelMode>) {
let words = Env::of(ui).words::<ColorPanelWords>();
let label = match shown {
ColorPanelShown::Mode(mode) => mode.label(&words),
@@ -398,13 +498,16 @@ fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) ->
_ => fallback.label(&words),
};
let button = Button::new(label).popup(PopupKind::Menu).show(ui);
let mut picked = None;
let menu = Menu::new(tl!("Color mode")).opened_by(&button, Trigger::Click).show(ui, |ui, _| {
for mode in ColorPanelMode::FILL_STROKE {
MenuItem::command(mode.command()).show(ui);
if MenuItem::command(mode.command()).show(ui).ran {
picked = Some(mode);
}
}
});
// The child absorbs an outside press before its parent sees it. Close both for that event only.
menu.output.closed == Some(CloseReason::Outside)
(menu.output.closed == Some(CloseReason::Outside), picked)
}
/// Document swatches as tiles: a pick gives the stop (or point) that colour.
@@ -514,8 +617,10 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) {
let Some(key) = TargetKey::of(app, &target) else { return };
let Ok(edited) = app.session.gradient_edit_paints(!key.fill) else { return };
let paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited });
let step = app.session.active().map(|st| st.history.step());
let restores = app.session.active().map(|st| st.history_restores);
dialogs.with(|host| {
host.open(GradientStopPopover::new(anchor, TargetOwner { key, paints }));
host.open(GradientStopPopover::new(anchor, TargetOwner::new(key, paints, step, restores)));
});
refresh(app, &ctx, dialog_id(KIND), &target);
}
@@ -538,13 +643,40 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
Some(_) => return,
None => {}
}
let Some(mut owner) = dialogs.with(|host| host.get_by_id::<GradientStopPopover>(id).map(|popover| popover.target.clone())) else {
let step = app.session.active().map(|st| st.history.step());
let restores = app.session.active().map(|st| st.history_restores);
let shown_mode = app.ui.color_panel.mode;
let Some((mut owner, own_mode)) = dialogs.with(|host| {
host.get_mut_by_id::<GradientStopPopover>(id).map(|popover| {
if let Some(mode) = popover.filed.mode_command.take() {
popover.own_mode = step.map(|from| OwnMode { from, mode, shown: false });
}
let own = popover.own_mode.as_mut().map_or(OwnModeNow::None, |pending| pending.now(step, shown_mode));
if own != OwnModeNow::Waiting {
popover.own_mode = None;
}
(popover.target.clone(), own == OwnModeNow::Edited)
})
}) else {
return;
};
let Some(target) = selected(app).filter(|target| owner.matches(app, target)) else {
let accepted = selected(app).and_then(|target| {
if owner.matches(app, &target) || (own_mode && owner.key.matches(app, &target)) {
Some((target, None))
} else {
owner.owned_earlier(app, &target, restores).map(|key| (target, Some(key)))
}
});
let Some((target, earlier)) = accepted else {
dialogs.with(|host| host.cancel_by_id(ctx, id));
return;
};
// The stop or point the paints owned until now belong to, before Undo or Redo or this pass's edits move it.
let owned_key = owner.key.clone();
if let Some(key) = earlier {
owner.key = key;
}
owner.restores = restores;
let filed = dialogs.with(|host| host.get_mut_by_id::<GradientStopPopover>(id).map(GradientStopPopover::take_filed)).unwrap_or_default();
if filed.fields != PopoverFields::default() {
apply(app, &target, &filed.fields);
@@ -581,7 +713,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
};
// The popover can continue with the paints resulting from its own edits in this pass.
if owner.paints.shown != *target.paint() || owner.paints.edited != edited {
owner.paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited });
let step = app.session.active().map(|st| st.history.step());
owner.adopt(Arc::new(TargetPaints { shown: target.paint().clone(), edited }), owned_key, step);
}
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) {
@@ -805,6 +938,139 @@ mod tests {
assert!(!is_open(&app));
}
#[test]
fn a_mode_command_that_changes_nothing_stops_counting_as_its_own_edit() {
let (from, other) = ((3, 0), ColorPanelMode::FILL_STROKE[0]);
let picked = ColorPanelMode::FILL_STROKE[1];
let mut pending = OwnMode { from, mode: picked, shown: false };
assert!(OwnModeNow::Waiting == pending.now(Some(from), other), "the command has not run yet");
assert!(OwnModeNow::Waiting == pending.now(Some(from), picked), "the panel shows the mode; one more pass");
assert!(OwnModeNow::Unchanged == pending.now(Some(from), picked), "no history step followed: nothing changed");
let mut pending = OwnMode { from, mode: picked, shown: false };
assert!(OwnModeNow::Edited == pending.now(Some((4, 0)), picked), "the first new step is the command's own");
}
#[test]
fn undo_after_a_stop_crosses_its_neighbor_does_not_edit_the_neighbor() {
let mut app = app();
open_at(&mut app, 0, Anchor::Screen(egui::pos2(200.0, 200.0)));
assert!(is_open(&app));
let ctx = ctx(&app);
let edit = |app: &VectorcraftApp, fields: PopoverFields| {
app.dialogs().unwrap().with(|host| host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields = fields);
};
edit(&app, PopoverFields { location: Some(75.0), ..PopoverFields::default() });
host::pump(&mut app, &ctx);
assert_eq!(app.session.selected_stop(), Some(1), "the stop crossed its neighbor");
app.run("edit.undo", json!({})).unwrap();
host::pump(&mut app, &ctx);
if is_open(&app) {
edit(&app, PopoverFields { opacity: Some(25.0), ..PopoverFields::default() });
host::pump(&mut app, &ctx);
let stops = stops(&app);
assert!(stops[0].opacity < 1.0, "the edit reaches the stop the popover opened on");
assert_eq!(stops[1].opacity, 1.0, "the neighbor is left alone");
}
}
#[test]
fn redo_after_a_stop_crosses_its_neighbor_does_not_reopen_on_the_neighbor() {
let mut app = app();
open_at(&mut app, 0, Anchor::Screen(egui::pos2(200.0, 200.0)));
let ctx = ctx(&app);
app.dialogs().unwrap().with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields.location = Some(75.0);
});
host::pump(&mut app, &ctx);
assert_eq!(app.session.selected_stop(), Some(1), "the stop crossed its neighbor");
app.run("edit.undo", json!({})).unwrap();
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
host::pump(&mut app, &ctx);
assert!(is_open(&app), "Undo returns to the paint it owned on stop 0");
app.run("edit.redo", json!({})).unwrap();
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
host::pump(&mut app, &ctx);
assert!(!is_open(&app), "after Redo, stop 0 is the neighbor");
}
#[test]
fn its_earlier_paint_set_again_from_elsewhere_closes_the_popover() {
let mut app = app();
open_popover(&mut app);
let ctx = ctx(&app);
let queue = |app: &VectorcraftApp, opacity: f64| {
app.dialogs().unwrap().with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(opacity);
});
};
queue(&app, 25.0);
host::pump(&mut app, &ctx);
assert!(is_open(&app) && stops(&app)[1].opacity < 1.0, "the live edit applied");
// The fixture's gradient again, set without Undo.
let stops_json = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}]);
app.run("paint.setFill", json!({"gradient": {"stops": stops_json, "start": [100, 150], "end": [200, 150]}})).unwrap();
assert_eq!(app.session.selected_stop(), Some(1));
queue(&app, 50.0);
host::pump(&mut app, &ctx);
assert!(!is_open(&app), "a gradient from elsewhere closes it, even one it owned before");
assert_eq!(stops(&app)[1].opacity, 1.0, "the pending edit is discarded");
}
#[test]
fn undo_after_a_long_live_drag_keeps_the_popover_open() {
let mut app = app();
open_popover(&mut app);
let ctx = ctx(&app);
let dialogs = app.dialogs().unwrap();
let gesture = GestureId::new(1);
let pick = |hex: &str| PickedColor::rgb(Srgba::from_hex(hex).unwrap());
let before = pick("#00ff00");
let original = stops(&app)[1].color.to_hex();
let samples = (0..2 * TargetOwner::EARLIER).map(|i| EditEvent::update(gesture, pick(&format!("#{:02x}0000", 40 + i))));
for edit in samples.chain([EditEvent::commit(gesture, Mixed::Same(before), pick("#0000ff"))]) {
let mut edit = Some(edit);
ctx.run_ui(Default::default(), |ui| {
let Some(edit) = edit.take() else { return };
let mut state = ColorPanelState::default();
let mut output = ColorPanel::new(Bind::bound(&mut state), [before.color; 2]).show(ui);
output.edits.push((PanelTarget::Foreground, edit));
dialogs.with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.panels.push(output);
});
})
.textures_delta
.clear();
host::pump(&mut app, &ctx);
}
assert_eq!(stops(&app)[1].color.to_hex(), "#0000ff");
app.run("edit.undo", json!({})).unwrap();
host::pump(&mut app, &ctx);
assert_eq!(stops(&app)[1].color.to_hex(), original, "Undo returns to the paint before the drag");
assert!(is_open(&app), "the paint before the drag is still the popover's own");
}
#[test]
fn undo_of_its_own_edit_keeps_the_popover_open() {
let mut app = app();
open_popover(&mut app);
app.dialogs().unwrap().with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0);
});
let ctx = ctx(&app);
host::pump(&mut app, &ctx);
assert!(stops(&app)[1].opacity < 1.0, "the live edit applied");
app.run("edit.undo", json!({})).unwrap();
host::pump(&mut app, &ctx);
assert_eq!(stops(&app)[1].opacity, 1.0);
assert!(is_open(&app), "Undo returns to a paint the popover owned");
app.run("edit.redo", json!({})).unwrap();
host::pump(&mut app, &ctx);
assert!(is_open(&app), "Redo returns to a paint the popover owned");
replace_gradient(&mut app);
host::pump(&mut app, &ctx);
assert!(!is_open(&app), "a gradient from elsewhere still closes it");
}
#[test]
fn discards_edits_when_only_a_secondary_selected_gradient_is_replaced() {
let mut app = app();
+149 -8
View File
@@ -44,6 +44,7 @@ pub(crate) type Cancel = Box<dyn FnOnce(&mut VectorcraftApp)>;
type Drain = Box<dyn FnMut(&mut VectorcraftApp) -> Option<bool>>;
struct Record {
id: DialogId,
drain: Drain,
cancel: Option<Cancel>,
}
@@ -52,20 +53,39 @@ struct Record {
#[derive(Default)]
pub(crate) struct Held(Vec<Record>);
fn drain<D: HoldsOk>(id: DialogId, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain {
impl Held {
fn reopened(&self, id: DialogId) -> bool {
self.0.iter().any(|record| record.id == id)
}
}
fn drain<D: HoldsOk>(id: DialogId, serial: u64, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain {
Box::new(move |app| {
// Without a window nothing can answer: the dialog counts as cancelled so its rollback runs.
let Some(host) = app.dialogs() else { return Some(true) };
match host.with(|h| h.open_serial(id)) {
None => return host.with(|h| h.take_by_id::<D>(id)).map(|r| matches!(r, DialogResult::Cancel)),
Some(open) if open != serial => return Some(false),
Some(_) => {}
}
if let Some(answer) = host.with(|h| h.get_mut_by_id::<D>(id).and_then(D::take_ok)) {
// The host's lock is released while `ok` runs: it may open dialogs.
let verdict = ok(app, &answer).map_err(Into::into);
// A callback can reopen the same key. Its old verdict cannot answer that opening.
if app.held.reopened(id) {
return Some(false);
}
host.with(|h| {
if let Some(d) = h.get_mut_by_id::<D>(id) {
if h.open_serial(id) == Some(serial)
&& let Some(d) = h.get_mut_by_id::<D>(id)
{
d.answer_ok(verdict);
}
});
}
host.with(|h| h.take_by_id::<D>(id)).map(|r| matches!(r, DialogResult::Cancel))
// A replace-by-open can leave the retired opening's Cancel under the same dialog ID.
// A live opening has no final result for this record yet.
None
})
}
@@ -88,11 +108,16 @@ pub(crate) fn open_held_with<D: HoldsOk>(
) -> Option<DialogId> {
let host = app.dialogs()?;
let dialog = dialog.held_ok();
let id = host.with(|h| match options.parent {
Some(parent) => h.open_child(dialog, parent),
None => h.open(dialog),
});
app.held.0.push(Record { drain: drain::<D>(id, ok), cancel: options.cancel });
let (id, serial) = host.with(|h| {
let id = match options.parent {
Some(parent) => h.open_child(dialog, parent),
None => h.open(dialog),
};
h.open_serial(id).map(|serial| (id, serial))
})?;
// A host key can be reopened before the previous result has been pumped.
app.held.0.retain(|record| record.id != id);
app.held.0.push(Record { id, drain: drain::<D>(id, serial, ok), cancel: options.cancel });
Some(id)
}
@@ -226,6 +251,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
// A drain's `ok` may open held dialogs: those join the records that stay.
let mut kept = Vec::new();
for mut record in std::mem::take(&mut app.held.0) {
if app.held.reopened(record.id) {
continue;
}
match (record.drain)(app) {
None => kept.push(record),
Some(true) => {
@@ -236,6 +264,119 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
Some(false) => {}
}
}
kept.retain(|record| !app.held.reopened(record.id));
kept.append(&mut app.held.0);
app.held.0 = kept;
}
#[cfg(test)]
mod opening_tests {
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::dialog::HeldOk;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog};
use vectorcraft_engine::Session;
use super::*;
const KEY: &str = "testHeldOpening";
fn app() -> (VectorcraftApp, egui::Context) {
let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let ctx = app.ui_ctx.clone().unwrap();
(app, ctx)
}
fn dialog(ctx: &egui::Context) -> HostedParamDialog {
HostedParamDialog::new(ctx, KEY, DialogFields::new(), |_| ParamDialog::new(KEY, "Test dialog", vec![]))
}
#[test]
fn held_ok_uses_the_replacement_openings_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
let retired = Rc::new(RefCell::new(Vec::new()));
let before = retired.clone();
let first = open_held(&mut app, dialog(&ctx), move |_, _| {
before.borrow_mut().push("old");
Ok(())
})
.unwrap();
assert!(host.with(|h| h.cancel_by_id(&ctx, first)));
let answers = retired.clone();
let fresh = open_held(&mut app, dialog(&ctx), move |_, _| {
answers.borrow_mut().push("new");
Ok(())
})
.unwrap();
assert_eq!(first, fresh);
assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh)));
assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Waiting));
pump(&mut app, &ctx);
assert_eq!(*retired.borrow(), ["new"]);
assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted));
}
#[test]
fn pumping_a_replacement_before_ok_keeps_its_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
open_held(&mut app, dialog(&ctx), |_, _| panic!("the retired opening cannot answer")).unwrap();
let accepted = Rc::new(RefCell::new(Vec::new()));
let seen = accepted.clone();
let fresh = open_held(&mut app, dialog(&ctx), move |_, _| {
seen.borrow_mut().push("new");
Ok(())
})
.unwrap();
pump(&mut app, &ctx);
assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh)));
pump(&mut app, &ctx);
assert_eq!(*accepted.borrow(), ["new"]);
assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted));
}
#[test]
fn cancelling_a_replacement_runs_only_its_cancel_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
let cancelled = Rc::new(RefCell::new(Vec::new()));
for flag in ["old", "new"] {
let log = cancelled.clone();
open_held_with(
&mut app,
dialog(&ctx),
|_, _| Ok(()),
HeldOptions { parent: None, cancel: Some(Box::new(move |_| log.borrow_mut().push(flag))) },
)
.unwrap();
}
assert!(host.with(|h| h.cancel_by_id(&ctx, craft::ui::dialog::dialog_id(KEY))));
pump(&mut app, &ctx);
assert_eq!(*cancelled.borrow(), ["new"]);
}
#[test]
fn an_old_verdict_does_not_answer_a_replacement_opened_by_its_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
let replacement_ctx = ctx.clone();
let id = open_held(&mut app, dialog(&ctx), move |app, _| {
let id = open_held(app, dialog(&replacement_ctx), |_, _| Ok(())).unwrap();
let host = app.dialogs().unwrap();
assert!(!host.with(|h| h.confirm_by_id(&replacement_ctx, id)));
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting));
Err("old verdict".into())
})
.unwrap();
assert!(!host.with(|h| h.confirm_by_id(&ctx, id)));
pump(&mut app, &ctx);
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting));
pump(&mut app, &ctx);
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted));
}
}
+145 -1
View File
@@ -9,6 +9,7 @@
//! (letters, 1..15), `hyphenLimit` (hyphens, 0..25, 0: no limit), `hyphenationZone` (pt) and
//! `hyphenateCapitalized`, as `text.setFormat` takes them.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
// PLAN: assumed paths of `UnitKind` and `LengthUnits`
use craft::ui::runtime::env::{LengthUnits, UnitKind};
@@ -78,7 +79,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let initial = fields.clone();
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let lengths = crate::canvas::rulers::general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)).values(Bind::bound(fields))
});
super::host::open_held(app, dialog, move |app, result| {
let mut p = params(&result.fields, &initial);
if p.is_empty() {
@@ -140,6 +143,147 @@ mod tests {
}
}
/// Actual focused Hyphenation edits keep the hosted draft and apply to both selected paragraphs.
#[test]
fn hyphenation_keeps_focused_edits_until_cancel_or_ok() {
use craft::automation::{ControlRequest, Reply};
use egui::accesskit::{Node, Role, TreeUpdate};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
fn control(tree: &TreeUpdate, source: &str, role: Role, scope: Option<Rect>) -> Rect {
fn plain(s: &str) -> &str {
s.trim_end().trim_end_matches([':', ':']).trim_end()
}
fn bounds(node: &Node) -> Option<Rect> {
let b = node.bounds()?;
Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))
}
let expected = crate::i18n::t(source);
tree.nodes
.iter()
.map(|(_, n)| n)
.filter(|n| n.role() == role && n.label().is_some_and(|label| plain(label) == plain(expected)))
.filter_map(bounds)
.find(|rect| scope.is_none_or(|scope| scope.contains(rect.center())))
.unwrap_or_else(|| panic!("missing {role:?} {expected:?} in {scope:?}"))
}
fn draft(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
let ui = crate::control::inspect(app, ctx);
ui["dialogs"].as_array().unwrap().iter().find(|dialog| dialog["key"] == KIND).expect("open Hyphenation dialog")["fields"].clone()
}
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut failures = Vec::new();
for lang in ["en", "de", "fr", "ja"] {
for answer in ["Cancel", "OK", "ui.dialog.confirm"] {
let (mut app, id) = app();
app.session.prefs.interface_language = lang.into();
app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2, "start": 5, "end": 5})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
time += 0.1;
let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() };
crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap()
};
let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate| {
for _ in 0..5 {
frame(app, vec![]);
}
frame(app, vec![])
};
let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, pos| {
frame(app, vec![Event::PointerMoved(pos)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
};
let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, key, modifiers| {
for pressed in [true, false] {
frame(
app,
vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }],
);
}
};
let original = paras(&app, id);
let undo = app.session.active().unwrap().history.undo.len();
settle(&mut app, &mut frame);
let apply = answer != "Cancel";
app.run("ui.hyphenation", json!({})).unwrap();
let tree = settle(&mut app, &mut frame);
let modal = control(&tree, "Hyphenation", Role::Dialog, None);
let count = control(&tree, "Words Longer Than:", Role::SpinButton, Some(modal));
let enabled = control(&tree, "Hyphenation", Role::CheckBox, Some(modal));
let footer = control(&tree, if apply { "OK" } else { "Cancel" }, Role::Button, Some(modal));
assert!(screen.expand(0.5).contains_rect(modal));
for bounds in [count, enabled, footer] {
assert!(bounds.is_positive() && modal.expand(0.5).contains_rect(bounds), "{lang}: {bounds:?} outside {modal:?}");
}
let before = driver::fields(&app);
assert_eq!(before.number("wordsLongerThan"), Some(5.0));
assert_eq!(before.bool("hyphenate"), Some(false));
assert!(before.is_mixed("afterFirst"));
click(&mut app, &mut frame, count.center());
press(&mut app, &mut frame, Key::A, Modifiers::COMMAND);
frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("8".into())]);
press(&mut app, &mut frame, Key::Tab, Modifiers::NONE);
settle(&mut app, &mut frame);
let typed = draft(&app, &ctx)["wordsLongerThan"].as_f64();
click(&mut app, &mut frame, enabled.center());
let inspected = draft(&app, &ctx);
let kept = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenate"].as_bool());
eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after typing {typed:?}, after checkbox {kept:?}");
if typed != Some(8.0) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") {
failures.push(format!("{lang} {answer}: {typed:?}, {kept:?}"));
}
assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open");
if answer == "ui.dialog.confirm" {
let (request, _) = ControlRequest::new(answer, json!({}));
match crate::control::handle(&mut app, &ctx, &request) {
Reply::Done(reply) => assert_eq!(reply["ok"], true, "{reply}"),
_ => panic!("confirmation should reply immediately"),
}
} else {
click(&mut app, &mut frame, footer.center());
}
settle(&mut app, &mut frame);
assert!(!driver::is_open(&app), "{lang}: footer closed the dialog");
let actual = paras(&app, id);
let undo_delta = app.session.active().unwrap().history.undo.len() - undo;
eprintln!(
"{lang}, {answer}: committed counts {}/{}, hyphenation {}/{}, after first {}/{}, undo {undo_delta}",
actual.0.hyphenation.words_longer_than,
actual.1.hyphenation.words_longer_than,
actual.0.hyphenate,
actual.1.hyphenate,
actual.0.hyphenation.after_first,
actual.1.hyphenation.after_first
);
if apply {
let mut expected = original.clone();
for p in [&mut expected.0, &mut expected.1] {
p.hyphenation.words_longer_than = 8;
p.hyphenate = true;
}
if actual != expected || undo_delta != 1 {
failures.push(format!(
"{lang} {answer}: left {:?} and {:?}, undo delta {undo_delta}",
actual.0.hyphenation, actual.1.hyphenation
));
}
} else {
assert_eq!(actual, original, "{lang}: Cancel discards both edits");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
assert!(failures.is_empty(), "Hyphenation lost physical edits: {failures:?}");
}
/// `ui.hyphenation` opens the dialog on the selected type; OK sets the paragraphs' hyphenation
/// options in one undo step.
#[test]
+50 -4
View File
@@ -6,6 +6,7 @@
use std::sync::Arc;
use craft::ui::contract::Bind;
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::UnitKind;
@@ -86,7 +87,7 @@ fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
fields.set("colors", clamped);
}
}
ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).previews(true)
ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).values(Bind::bound(fields)).previews(true)
}
/// Open the dialog with the defaults of `edit.colors.toIndexed`.
@@ -187,16 +188,24 @@ fn params(fields: &DialogFields) -> Value {
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{panel_harness::Panel, picks::dialogs};
use craft::ui::contract::Role;
use std::collections::BTreeSet;
use vectorcraft_engine::Session;
fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId {
add_raster_row(app, &[[200, 30, 90, 255], [20, 40, 220, 255]])
}
fn add_raster_row(app: &mut VectorcraftApp, rgba: &[[u8; 4]]) -> vectorcraft_doc::NodeId {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let width = u32::try_from(rgba.len()).unwrap();
let img = craft_image_codecs::Image::from_raw(
2,
width,
1,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
vec![200, 30, 90, 255, 20, 40, 220, 255],
rgba.as_flattened().to_vec(),
)
.unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
@@ -206,7 +215,7 @@ mod tests {
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 2,
width,
height: 1,
xf: Default::default(),
link: None,
@@ -226,6 +235,43 @@ mod tests {
&st.doc.images[&im.key]
}
#[test]
fn indexed_color_form_edits_update_the_preview_and_confirmation() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let id = add_raster_row(&mut app, &[[200, 30, 90, 255], [20, 40, 220, 255], [220, 240, 70, 255]]);
let original = palette(&app, id).rgba().unwrap().2;
let undo = app.session.doc().unwrap().history.undo.len();
let mut panel = Panel::new(app, dialogs);
let black_and_white = |panel: &mut Panel| {
panel.click_role("Reduction", Role::COMBO_BOX);
panel.click("Black & White");
panel.click_role("Dither", Role::COMBO_BOX);
panel.click("No Dither");
};
panel.app().run("ui.indexedColorDialog", json!({})).unwrap();
panel.frame();
panel.click_at(panel.rect_role("Colors", Role::SPIN_BUTTON).center());
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("2");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
let preview = palette(&panel.app(), id).rgba().unwrap().2;
assert_eq!(preview.as_chunks::<4>().0.iter().collect::<BTreeSet<_>>().len(), 2);
black_and_white(&mut panel);
let preview = palette(&panel.app(), id).rgba().unwrap().2;
assert_eq!(preview, [0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, 255]);
panel.click("Cancel");
assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, original);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo);
panel.app().run("ui.indexedColorDialog", json!({})).unwrap();
black_and_white(&mut panel);
panel.click("OK");
assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, preview);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
+17 -10
View File
@@ -55,7 +55,8 @@ fn categories() -> [(&'static str, &'static str); 4] {
/// What OK files for the pump: the document the dialog opened on, the names of its sets then, and the sets.
#[derive(Clone)]
struct Request {
doc: Option<u64>,
doc: u64,
reverts: u64,
opened: Vec<String>,
sets: Value,
}
@@ -63,8 +64,9 @@ struct Request {
/// The Kinsoku Shori Settings dialog on the host.
pub(crate) struct KinsokuDialog {
id: DialogId,
/// The uid of the document the dialog opened on, which OK sets the sets of.
doc: Option<u64>,
/// The drawing and its saved-content generation when the dialog opened.
doc: u64,
reverts: u64,
/// The names of that document's sets when the dialog opened: OK keeps the sets the document gained
/// since, after the dialog's own, and New's suggestion skips these names.
opened: Vec<String>,
@@ -84,7 +86,7 @@ pub(crate) struct KinsokuDialog {
/// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let dialog = KinsokuDialog::new(st.uid, st.doc.kinsoku_sets.iter());
let dialog = KinsokuDialog::new(st.uid, st.reverts, st.doc.kinsoku_sets.iter());
app.dialogs().ok_or("no window")?.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -176,10 +178,11 @@ fn text_of(field: &str, value: &Value) -> Result<String, String> {
}
impl KinsokuDialog {
fn new<'a>(doc: u64, document_sets: impl Iterator<Item = &'a KinsokuSet> + Clone) -> Self {
fn new<'a>(doc: u64, reverts: u64, document_sets: impl Iterator<Item = &'a KinsokuSet> + Clone) -> Self {
let mut d = KinsokuDialog {
id: dialog_id(COMMAND),
doc: Some(doc),
doc,
reverts,
opened: document_sets.clone().map(|k| k.name.clone()).collect(),
sets: Value::Array(document_sets.map(listed).collect()),
selected: 0,
@@ -340,7 +343,7 @@ impl KinsokuDialog {
}
self.commit();
self.problem = None;
self.held.file(Request { doc: self.doc, opened: self.opened.clone(), sets: self.sets.clone() });
self.held.file(Request { doc: self.doc, reverts: self.reverts, opened: self.opened.clone(), sets: self.sets.clone() });
}
/// The answer OK filed, once.
@@ -517,7 +520,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
let Some(host) = app.dialogs() else { return };
let Some(request) = host.with(|h| h.get_mut::<KinsokuDialog>().and_then(KinsokuDialog::take_ok)) else { return };
let answer = apply(app, &request);
let gone = answer.is_err() && !app.session.documents().iter().any(|d| Some(d.uid) == request.doc);
let gone = answer.is_err() && !app.session.documents().iter().any(|d| d.uid == request.doc);
// The command ran outside the host's lock, which a dialog's own methods take.
host.with(|h| {
if let Some(d) = h.get_mut::<KinsokuDialog>() {
@@ -530,8 +533,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
}
fn apply(app: &mut VectorcraftApp, request: &Request) -> Result<(), String> {
if app.session.active().map(|st| st.uid) != request.doc {
let index = app.session.documents().iter().position(|d| Some(d.uid) == request.doc).ok_or("that document is no longer open")?;
let (index, document) =
app.session.documents().iter().enumerate().find(|(_, st)| st.uid == request.doc).ok_or("that document is no longer open")?;
if document.reverts != request.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
if app.session.active().is_none_or(|st| st.uid != request.doc) {
app.run("document.activate", json!({ "index": index }))?;
}
// A `sets` that is not a list of sets goes to the command as it is, which refuses it.
@@ -226,6 +226,47 @@ fn ok_sets_the_document_the_dialog_opened_on() {
assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty()));
}
#[test]
fn old_ok_keeps_restored_kinsoku_rules_and_the_current_tab() {
let mut app = app();
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゝ"}]})).unwrap();
let file = std::env::temp_dir().join(format!("vectorcraft-kinsoku-revert-{}.vectorcraft", std::process::id()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap();
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゞ"}]})).unwrap();
open(&mut app).unwrap();
set(&app, "cannotStart", json!("ー"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert_eq!(doc_sets(&app)[0].cannot_start, ['ゝ']);
let undo = steps(&app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let other = app.session.active().unwrap().uid;
assert_ne!(uid, other);
pump(&mut app);
let restored = app.session.documents().iter().find(|st| st.uid == uid).unwrap();
assert_eq!(restored.doc.kinsoku_sets[0].cannot_start, ['ゝ'], "an old OK must keep the saved line-breaking rule");
assert_eq!(restored.history.undo.len(), undo);
assert_eq!(app.session.active().unwrap().uid, other, "a stale OK does not activate the original tab");
assert!(is_open(&app));
dialog(&app, |d| assert_eq!(d.problem.as_deref(), Some("The document was reverted. Reopen this dialog to continue.")));
cancel(&app);
assert!(app.session.set_active(0));
open(&mut app).unwrap();
set(&app, "cannotStart", json!("ー"));
pump(&mut app);
assert!(!is_open(&app));
assert_eq!(doc_sets(&app)[0].cannot_start, ['ー'], "a fresh draft can edit the restored rule");
}
/// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a
/// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the
/// dialog open and leaves the document's sets as they are, and New refuses to start from it.
+53 -9
View File
@@ -52,15 +52,15 @@ pub(super) static SPEC: OptionSpec = OptionSpec {
pub(crate) struct Open {
/// The dialog the preview belongs to.
pub id: DialogId,
/// The document that owns the preview interaction.
document: u64,
/// The drawing and loaded contents that own the preview interaction.
document: (u64, u64),
/// The preview the options run as.
pub preview: LivePreview,
}
impl Open {
fn cancel(self, app: &mut VectorcraftApp) {
if app.session.active().is_some_and(|active| active.uid == self.document) {
if app.session.active().is_some_and(|active| (active.uid, active.reverts) == self.document) {
self.preview.cancel(app);
}
}
@@ -69,7 +69,7 @@ impl Open {
/// Open Gap Options on the selected Live Paint groups, filled in from the first one's options.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let active = app.session.active().ok_or("select a Live Paint group")?;
let document = active.uid;
let (document, reverts) = (active.uid, active.reverts);
let groups: Vec<u64> = active
.selection
.objects
@@ -87,13 +87,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields =
[("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))];
let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value)));
option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document })).ok_or("no window")?;
option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document, "reverts": reverts })).ok_or("no window")?;
Ok(Value::Null)
}
fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<u64> {
let document = extra["document"].as_u64()?;
app.session.active().filter(|active| active.uid == document).map(|_| document)
fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<(u64, u64)> {
let document = (extra["document"].as_u64()?, extra["reverts"].as_u64()?);
app.session.active().filter(|active| (active.uid, active.reverts) == document).map(|_| document)
}
/// `livePaint.gapOptions` parameters from the values and the groups in `extra`.
@@ -128,7 +128,13 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) {
/// OK: keep the previewed options as one undo step; with no preview running they run as one.
fn run(app: &mut VectorcraftApp, values: &Map<String, Value>, extra: &Value) -> Result<Value, String> {
let document = original_document(app, extra).ok_or_else(|| tl!(WRONG_DOCUMENT).to_owned())?;
let document = original_document(app, extra).ok_or_else(|| {
if app.session.active().is_some_and(|active| extra["document"].as_u64() == Some(active.uid)) {
tl!("The document was reverted. Reopen this dialog to continue.").to_owned()
} else {
tl!(WRONG_DOCUMENT).to_owned()
}
})?;
let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview);
preview.commit(app, CMD, params(values, extra))
}
@@ -338,6 +344,44 @@ mod tests {
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn gap_preview_and_ok_do_not_edit_live_paint_restored_by_revert() {
let mut app = app();
let dir = vectorcraft_testkit::TempDir::new("live-paint-gap-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let group = gapped_group(&mut app);
let saved = options(&app, group);
app.run("file.saveAs", json!({"path": dir.join("Live Paint.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 140, "y": 140, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(&app, "detect", json!(true)).unwrap();
set(&app, "preview", json!(true)).unwrap();
pump_all(&mut app);
assert!(options(&app, group).detect);
let source = app.session.active().unwrap();
let (uid, reverts) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let current = app.session.active().unwrap();
assert_eq!((current.uid, current.reverts), (uid, reverts + 1));
let undo = current.history.undo.len();
pump_all(&mut app);
assert_eq!(options(&app, group), saved);
assert!(overlays(&app).is_empty());
assert!(!press_ok(&mut app));
assert_eq!(options(&app, group), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
cancel(&mut app);
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(&app, "detect", json!(true)).unwrap();
assert!(press_ok(&mut app));
assert!(options(&app, group).detect);
}
#[test]
fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() {
let mut app = app();
+35 -2
View File
@@ -18,7 +18,7 @@ pub const KIND: &str = "newColorGroup";
/// art is selected and no swatches are.
pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let document = st.uid;
let (document, reverts) = (st.uid, st.reverts);
let art = !st.selection.is_empty();
let mut fields = DialogFields::new();
fields.set("name", st.doc.free_swatch_name("Color Group"));
@@ -38,8 +38,11 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, St
];
let dialog = hosted(&ctx, KIND, tl!("New Color Group"), fields, rows, false);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
if !app.session.active().is_some_and(|active| active.uid == document) {
let Some(source) = app.session.active().filter(|active| active.uid == document) else {
return Err(tl!("Create this color group in the document that opened the dialog.").to_owned());
};
if source.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
app.run("swatch.newGroup", params(&answer.fields, &swatches)).map(|_| ())
};
@@ -65,6 +68,36 @@ mod tests {
use super::*;
#[test]
fn a_color_group_draft_cannot_change_the_drawing_restored_by_revert() {
for swatches in [vec!["Saved Ink".to_owned()], Vec::new()] {
let dir = vectorcraft_testkit::TempDir::new("new-color-group-revert");
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [id], "color": "#123456"})).unwrap();
app.run("swatch.new", json!({"name": "Saved Ink", "color": "#446688"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("Saved.vectorcraft")})).unwrap();
app.run("paint.setFill", json!({"ids": [id], "color": "#abcdef"})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let before = app.session.active().unwrap();
let (uid, reverts) = (before.uid, before.reverts);
open(&mut app, swatches).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let loaded = app.session.active().unwrap();
assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1));
let (saved, undo) = (loaded.doc.clone(), loaded.history.undo.len());
let refused = crate::dialogs::tests_export::try_confirm(&mut app);
let current = app.session.active().unwrap();
assert_eq!(current.doc, saved);
assert_eq!(current.history.undo.len(), undo);
assert_eq!(refused.unwrap_err(), "The document was reverted. Reopen this dialog to continue.");
}
}
#[test]
fn color_group_does_not_convert_the_other_drawings_artwork() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
@@ -5,6 +5,7 @@
//! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`),
//! `anchorPoint` (bool) and `gridlineIntersection` (bool).
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
use vectorcraft_tools::distort::perspective::widget::WidgetCorner;
@@ -31,8 +32,8 @@ fn params() -> Vec<Param> {
]
}
fn build(_fields: &mut DialogFields) -> ParamDialog<'_> {
ParamDialog::new(KIND, tl!("Perspective Grid Options"), params())
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
ParamDialog::new(KIND, tl!("Perspective Grid Options"), params()).values(Bind::bound(fields))
}
/// Open the dialog with the current options.
@@ -51,3 +52,39 @@ pub fn open(app: &mut VectorcraftApp) {
app.status("no window".to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{panel_harness::Panel, picks::dialogs};
use craft::ui::contract::Role;
use vectorcraft_engine::Session;
fn open_options(panel: &mut Panel) {
panel.app().run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap();
panel.frame();
}
#[test]
fn perspective_grid_options_show_and_apply_widget_preferences() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.prefs.perspective_widget.position = WidgetCorner::BottomRight;
let mut panel = Panel::new(app, dialogs);
open_options(&mut panel);
assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Bottom Right"));
panel.click_role("Widget Position", Role::COMBO_BOX);
panel.click("Top Right");
panel.click("Intersection of Gridlines");
panel.click("OK");
let saved = panel.app().session.prefs.perspective_widget;
assert_eq!(saved.position, WidgetCorner::TopRight);
assert!(!saved.gridline_intersection);
open_options(&mut panel);
assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Top Right"));
panel.click("Show Active Plane Widget");
panel.click("Cancel");
assert_eq!(panel.app().session.prefs.perspective_widget, saved);
}
}
@@ -16,6 +16,7 @@ use crate::VectorcraftApp;
use crate::dialogs::tool_options::reference_param;
const KEY: &str = "placementOptions";
const OPENING: &str = "__opening";
const CMD: &str = "links.placementOptions";
/// (value, label) of each Preserve choice.
const PRESERVE: [(&str, &str); 5] = [
@@ -43,16 +44,18 @@ fn params() -> Vec<Param> {
/// Open the dialog on the placement options of images `ids` (default: the selected ones).
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let source_document = app.session.active().map(|document| document.uid);
let active = app.session.active().ok_or("no document open")?;
let source = (active.uid, active.reverts);
let ids = p.get("ids").cloned().unwrap_or(Value::Null);
let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?;
let placement = &r["placement"];
let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE);
let fields = DialogFields::from_pairs([
let mut fields = DialogFields::from_pairs([
("preserve", FieldValue::Text(placement["preserve"].as_str().unwrap_or("transforms").to_owned())),
("align", FieldValue::Int(align as i64)),
("clip", FieldValue::Bool(placement["clip"].as_bool().unwrap_or(false))),
]);
fields.set(OPENING, FieldValue::Json(json!({"uid": source.0, "reverts": source.1, "ids": ids})));
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KEY, fields, |fields| {
ParamDialog::new(KEY, tl!("Placement Options"), params())
@@ -60,13 +63,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
.footer_note(tl!("Applies when the linked file is relinked or updated."))
})
.held_ok();
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
if app.session.active().map(|document| document.uid) != source_document {
return Err(tl!("Placement Options can only change the document where it was opened.").to_owned());
}
crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| {
let f = &result.fields;
let Some(FieldValue::Json(opening)) = f.get(OPENING) else { return Err("the Placement Options target is missing".into()) };
let Some(active) = app.session.active().filter(|document| Some(document.uid) == opening["uid"].as_u64()) else {
return Err(tl!("Placement Options can only change the document where it was opened.").to_owned());
};
if Some(active.reverts) != opening["reverts"].as_u64() {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]);
let params = json!({ "ids": ids, "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
app.run(CMD, params).map(|_| ())
})
.ok_or("no window")?;
@@ -125,4 +132,40 @@ mod tests {
assert_eq!(placement["preserve"], json!("fit"));
assert_eq!(steps, starting.1 + 1);
}
#[test]
fn held_placement_options_do_not_edit_a_link_restored_by_file_revert() {
let dir = vectorcraft_testkit::TempDir::new("placement-options-revert");
let path = dir.join("linked.png");
let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap();
std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let link = app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap();
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
let placement = |app: &mut VectorcraftApp| app.run(CMD, json!({"ids": [link]})).unwrap()["placement"].clone();
let original = placement(&mut app);
app.run(CMD, json!({"ids": [link], "preserve": "fill"})).unwrap();
open(&mut app, &json!({"ids": [link]})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let dialog = dialog_id(KEY);
let host = app.dialogs().unwrap();
host.with(|h| {
h.set_json_field(&ctx, dialog, "preserve", json!("fit")).unwrap();
assert!(!h.confirm_by_id(&ctx, dialog));
});
app.run("file.revert", json!({"confirmed": true})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(placement(&mut app), original);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_))));
host.with(|h| h.cancel_by_id(&ctx, dialog));
open(&mut app, &json!({"ids": [link]})).unwrap();
crate::tests::picks::answer_dialog(&mut app, dialog, &[("preserve", json!("fit"))], true);
assert_eq!(placement(&mut app)["preserve"], "fit");
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn stored(app: &VectorcraftApp, name: &str) -> Value {
fn detail(app: &VectorcraftApp, name: &str) -> Vec<Detail> {
let builtin = name == DEFAULT_PRESET;
let title = if builtin { tl!(DEFAULT_PRESET).to_string() } else { name.to_string() };
let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]))];
let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", tl!(DEFAULT_PRESET))]))];
let settings = app.session.prefs.print_presets.iter().find(|p| p.name == name).map(|p| &p.settings);
let mut changed = settings.map(|s| changes(s, &Default::default())).unwrap_or_default();
changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0);
+8 -10
View File
@@ -62,9 +62,8 @@ pub(crate) struct PasteAsk {
params: Value,
/// The models whose profiles differ, as `clipboard.profileMismatch` lists them.
mismatches: Vec<Value>,
/// The uid of the document the question was asked in: a paste that runs at once pastes nothing
/// once another document is active.
doc: Option<u64>,
/// The drawing and content generation the question was asked in.
drawing: Option<(u64, u64)>,
/// The chain of a deferred paste (one that waits for its clipboard), which placing answers.
deferred: Option<u64>,
}
@@ -271,8 +270,8 @@ fn open_paste(app: &mut VectorcraftApp, command: &str, params: &Value, mismatche
crate::placing::cancel_swatch_paste(app);
}
let dialog = paste_dialog(&ctx, &mismatches);
let doc = app.session.active().map(|st| st.uid);
app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, doc, deferred: None });
let drawing = app.session.active().map(|st| (st.uid, st.reverts));
app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, drawing, deferred: None });
dialogs.with(|h| h.open(dialog));
Some(Ok(json!({ "dialog": PASTE_KIND })))
}
@@ -389,12 +388,11 @@ fn pump_paste(app: &mut VectorcraftApp) {
}
}
/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another
/// document has become the active one since a paste that runs at once asked, it pastes nothing. When
/// the profiles that paste or drop would bring have changed since it asked (the clipboard, the
/// dragged objects' document or the destination's profile changed), it asks again about the new ones.
/// OK: run the paste with the choice; any Swatch Conflict question comes next. An immediate paste
/// is canceled if its drawing is inactive or reverted. When the profiles it would bring have changed
/// since it asked (the clipboard, dragged objects or destination changed), it asks about the new ones.
fn paste_confirm(app: &mut VectorcraftApp, ask: PasteAsk, choice: Value) -> Result<Value, String> {
if ask.deferred.is_none() && ask.doc != app.session.active().map(|st| st.uid) {
if ask.deferred.is_none() && ask.drawing != app.session.active().map(|st| (st.uid, st.reverts)) {
return Ok(json!({}));
}
let params = with_choice(&ask.params, choice);
@@ -320,6 +320,31 @@ fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) {
app.run("document.activate", json!({ "index": asked_in })).unwrap();
}
/// The destination still has a mismatch after reopening the saved contents. Its old approval is retired.
fn paste_asked_before_its_drawing_is_reverted(app: &mut VectorcraftApp) {
let dir = vectorcraft_testkit::TempDir::new("immediate-profile-mismatch-revert");
let path = dir.join("destination.vectorcraft");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.rectangle", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap();
assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND }));
let before = app.session.active().unwrap();
let (uid, reverts) = (before.uid, before.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
assert!(app.pending_paste.is_some(), "the old question is still waiting");
let saved = restored.doc.clone();
let undo = restored.history.undo.len();
answer_ok(app, paste_id_open());
let after = app.session.active().unwrap();
assert!(after.doc == saved, "the old profile approval must leave the restored drawing intact");
assert_eq!(after.history.undo.len(), undo);
assert!(app.pending_paste.is_none());
}
/// A drag of the art of the document assigned Display P3 into the active one asks as Paste does:
/// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while
/// the question is open, OK drops nothing and asks again about the new profile. `count` counts the
@@ -467,6 +492,7 @@ fn opening_and_pasting_ask_about_profiles() {
// Cancel pastes nothing; with the box off nothing asks.
paste_canceled(&mut app, count);
paste_asked_before_another_document_is_active(&mut app);
paste_asked_before_its_drawing_is_reverted(&mut app);
drop_asks_as_paste_does(&mut app, count);
let before = count(&app);
app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap();
+71 -10
View File
@@ -123,7 +123,6 @@ use std::sync::{Arc, Weak};
use craft::behavior::edit_history::{EditHistory, Step};
use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed};
use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorPanelMode, DiscRadius, patch_at};
use craft::host::PickRequest;
use craft::theme::variant::Tone;
use craft::theme::{ModelValues, Rgba, Srgba};
use craft::ui::buttons::{IconButton, ToggleButton};
@@ -260,6 +259,7 @@ pub(crate) struct Open {
/// The dialog on the window's host.
pub id: DialogId,
document: u64,
reverts: u64,
/// The preview the pump runs and OK commits.
pub preview: LivePreview,
/// The selection snapshot identifies the interaction that ran the preview.
@@ -270,14 +270,17 @@ impl Open {
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
(state.uid, state.reverts) == (self.document, self.reverts)
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn problem(&self, app: &VectorcraftApp) -> Option<&'static str> {
if app.session.active().is_none_or(|state| state.uid != self.document) {
Some("Return to the document where Recolor Artwork opened.")
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else {
return Some("Return to the document where Recolor Artwork opened.");
};
if state.reverts != self.reverts {
Some("The document was reverted. Reopen this dialog to continue.")
} else if app.session.in_interaction() && !self.owns_preview(app) {
Some("Finish the active edit before applying Recolor Artwork.")
} else {
@@ -338,7 +341,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
// A Recolor Artwork still open is replaced: its preview goes before the group's colours are read.
cancel_open(app);
let st = app.session.active().ok_or("no document open")?;
let document = st.uid;
let (document, reverts) = (st.uid, st.reverts);
let group_colors: Option<Vec<Color>> = match group {
Some(g) => {
let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?;
@@ -377,7 +380,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let dialog = RecolorDialog::new(app, d);
let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() };
let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?;
app.color_dialogs.recolor = Some(Open { id, document, preview: LivePreview::default(), preview_selection: None });
app.color_dialogs.recolor = Some(Open { id, document, reverts, preview: LivePreview::default(), preview_selection: None });
Ok(Value::Null)
}
@@ -1632,11 +1635,9 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) {
/// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and
/// limit to it.
fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) {
let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts));
// A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked.
crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| {
let Some(path) = picked.first_path() else { return Ok(Value::Null) };
let r = app.run("swatch.library.load", json!({ "path": path }))?;
let _ = crate::panels::library_panel::pick_library_file(app, None, builtin_open_filters().collect(), move |app, source| {
let r = app.run("swatch.library.load", source)?;
let library = r["library"].clone();
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
@@ -3208,6 +3209,21 @@ mod tests {
(rc, opening, other)
}
#[test]
fn other_library_accepts_browser_contents_and_selects_the_loaded_library() {
let (mut rc, _, _) = two_red_drawings();
let picker = crate::tests::picks::scripted(&mut rc.app());
rc.settled().click_label("Other Library…").frame();
assert_eq!(picker.requests().len(), 1);
let bytes = b"GIMP Palette\nName: Recolor Browser Palette\n#\n255 0 0\tRecolor Red\n";
picker.answer_contents(&[("Recolor Browser Palette.gpl", bytes)]);
crate::file_asks::poll(&mut rc.app());
rc.frame();
let selected = rc.fields().str("limitTo");
assert!(!selected.is_empty(), "Other Library selects the imported library");
assert!(swatchlib::limit_palette(&rc.app().session, &selected).is_some());
}
#[test]
fn recolor_preview_does_not_change_the_other_drawings_art() {
let (mut rc, opening, other) = two_red_drawings();
@@ -3281,6 +3297,51 @@ mod tests {
assert!(group_hex(&rc.app(), "Shared").is_none());
}
#[test]
fn recolor_after_file_revert_does_not_restart_the_discarded_preview() {
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let mut app = app(120);
let shape = square(&mut app, 10.0, "#ff0000");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-recolor-revert-{}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
square(&mut app, 60.0, "#0000ff");
app.run("select.set", json!({"ids": [shape]})).unwrap();
let mut rc = opened(app, json!({}));
rc.set("method", json!(Method::Exact.id())).unwrap();
rc.frame();
rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap();
rc.frame();
assert_eq!(fill_hex(&rc, shape), "#00ff00", "the original preview is active");
{
let mut app = rc.app();
let state = app.session.active().unwrap();
let (uid, reverts) = (state.uid, state.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
assert!(state.doc.node(vectorcraft_doc::NodeId(shape)).is_some());
app.run("select.set", json!({"ids": [shape]})).unwrap();
}
assert_eq!(fill_hex(&rc, shape), "#ff0000");
let history = undo_len(&rc.app());
rc.frame();
assert_eq!(fill_hex(&rc, shape), "#ff0000", "an open preview must leave the saved red fill alone");
assert!(!rc.app().session.in_interaction());
assert!(rc.confirm().is_err() && rc.is_open(), "the old draft cannot be applied");
assert_eq!(fill_hex(&rc, shape), "#ff0000");
assert_eq!(undo_len(&rc.app()), history);
}
#[test]
fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() {
let rc = opened(app(100), json!({"colors": ["#ff8000"]}));
+61 -3
View File
@@ -36,7 +36,8 @@ fn document_name(app: &VectorcraftApp) -> Option<String> {
/// Open the dialog for `library`: `extra` rows sit under the Name row. `names` are the items selected in the
/// panel.
pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec<String>, extra: Vec<Param>) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let state = app.session.active().ok_or("no document open")?;
let document = (state.uid, state.reverts);
let name = document_name(app).ok_or("no document open")?;
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let Library { key, title, cmd, only, ext, has_user_dir } = library;
@@ -68,9 +69,12 @@ pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec<String
let owner = egui::Id::unique((key, "opening-drawing"));
ctx.data_mut(|data| data.insert_temp(owner, document));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
let document = ctx.data(|data| data.get_temp::<u64>(owner));
if app.session.active().is_none_or(|st| Some(st.uid) != document) {
let document = ctx.data(|data| data.get_temp::<(u64, u64)>(owner));
let Some(state) = app.session.active().filter(|st| document.is_some_and(|(uid, _)| st.uid == uid)) else {
return Err(tl!("Return to the original drawing to save its library").into());
};
if document.is_some_and(|(_, reverts)| state.reverts != reverts) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
save(app, cmd, ext, result)
};
@@ -155,4 +159,58 @@ mod tests {
assert_eq!(output.len(), 1);
assert!(output[0].0.contains("Other Marks"));
}
#[test]
fn an_old_save_library_approval_cannot_export_definitions_restored_by_revert() {
let (mut app, written) = tests_export::app(1);
app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string())));
let output = written.clone();
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
if path.ends_with(".vectorcraft") {
std::fs::write(path, bytes).map_err(|error| error.to_string())
} else {
output.borrow_mut().push((path.to_string(), bytes.to_vec()));
Ok(())
}
}));
let id = app.session.active().unwrap().selection.objects[0];
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
app.run("graphicStyle.new", json!({"name": "Mark", "id": id.0})).unwrap();
let saved_fill = app.session.active().unwrap().doc.graphic_style("Mark").unwrap().appearance.fill_paint();
let temp = vectorcraft_testkit::TempDir::new("save-library-revert");
let file = temp.join("library-source.vectorcraft");
app.run("file.saveAs", json!({"path": file})).unwrap();
assert!(file.is_file());
let state = app.session.active().unwrap();
let (uid, reverts) = (state.uid, state.reverts);
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
app.run("graphicStyle.redefine", json!({"name": "Mark", "id": id.0})).unwrap();
assert_ne!(app.session.active().unwrap().doc.graphic_style("Mark").unwrap().appearance.fill_paint(), saved_fill);
super::super::save_style_library::open(&mut app, vec!["Mark".into()]).unwrap();
tests_export::set(&mut app, "saveTo", json!("file"));
tests_export::set(&mut app, "selectedOnly", json!(true));
tests_export::set(&mut app, "name", json!("Draft Marks"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
assert_eq!(state.doc.graphic_style("Mark").unwrap().appearance.fill_paint(), saved_fill);
let undo = state.history.undo.len();
assert!(tests_export::try_confirm(&mut app).is_err(), "old approval must not export the restored library");
assert!(written.borrow().is_empty(), "no output is written for the retired draft");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(tests_export::fields(&app)["name"], "Draft Marks", "refusal preserves the user's draft");
tests_export::cancel(&mut app);
super::super::save_style_library::open(&mut app, vec!["Mark".into()]).unwrap();
tests_export::set(&mut app, "saveTo", json!("file"));
tests_export::set(&mut app, "selectedOnly", json!(true));
tests_export::set(&mut app, "name", json!("Restored Marks"));
tests_export::try_confirm(&mut app).unwrap();
let output = written.borrow();
assert_eq!(output.len(), 1);
let text = std::str::from_utf8(&output[0].1).unwrap();
let library = vectorcraft_doc::style_libs::read(text, "Restored Marks").unwrap();
assert_eq!(library.style("Mark").unwrap().appearance.fill_paint(), saved_fill, "fresh approval exports the restored definition");
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ const WRONG_DOCUMENT: &str = "Return to the original drawing to save the PDF or
/// What the Save PDF dialog was opened for; the preset editor has none.
pub(crate) struct SavePdfJob {
/// The drawing this job reads and writes.
document: u64,
pub(crate) document: u64,
/// The file the PDF goes to; none: the write asks.
pub(crate) path: Option<String>,
/// The save command (`file.saveAs`, `file.saveCopy`) this PDF finishes; none: a plain PDF copy.
+13 -11
View File
@@ -56,7 +56,7 @@ const CHOICES: [(Choice, &str, &str); 2] = [
];
/// The question about the swatches a paste brings that the document names differently. Its answer is the value
/// [`take`] hands the paste: `command`, `params` (with `swatchConflict`), `deferred`, `asked` and `doc`.
/// [`take`] hands the paste: `command`, `params` (with `swatchConflict`), `deferred`, `asked` and `drawing`.
struct SwatchConflictDialog {
id: DialogId,
/// The conflicts as `clipboard.conflicts` lists them: `[{name, document, clipboard, spot}]`.
@@ -70,15 +70,15 @@ struct SwatchConflictDialog {
/// The paste command and its parameters.
command: String,
params: Value,
/// The uid of the document the question is about.
doc: Option<u64>,
/// The drawing and content generation the question is about.
drawing: Option<(u64, u64)>,
/// The deferred paste waiting on the answer ([`defer`]).
deferred: Option<u64>,
open: bool,
}
impl SwatchConflictDialog {
fn new(conflicts: Vec<Value>, command: &str, params: &Value, doc: Option<u64>) -> Self {
fn new(conflicts: Vec<Value>, command: &str, params: &Value, drawing: Option<(u64, u64)>) -> Self {
SwatchConflictDialog {
id: dialog_id(KIND),
conflicts,
@@ -88,7 +88,7 @@ impl SwatchConflictDialog {
choices: Map::new(),
command: command.to_owned(),
params: Some(params).filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})),
doc,
drawing,
deferred: None,
open: true,
}
@@ -115,7 +115,7 @@ impl SwatchConflictDialog {
}
let mut params = self.params.clone();
params["swatchConflict"] = Value::Object(self.choices.clone());
Some(json!({"command": self.command, "params": params, "deferred": self.deferred, "asked": self.conflicts, "doc": self.doc}))
Some(json!({"command": self.command, "params": params, "deferred": self.deferred, "asked": self.conflicts, "drawing": self.drawing}))
}
}
@@ -221,7 +221,8 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option<Re
return None;
}
let conflicts = found(app, command, params).filter(|a| !a.is_empty())?;
let dialog = SwatchConflictDialog::new(conflicts, command, params, app.session.active().map(|doc| doc.uid));
let drawing = app.session.active().map(|doc| (doc.uid, doc.reverts));
let dialog = SwatchConflictDialog::new(conflicts, command, params, drawing);
let Some(host) = app.dialogs() else { return Some(Err(NO_WINDOW.into())) };
host.with(|h| h.open(dialog));
Some(Ok(json!({ "dialog": KIND })))
@@ -233,14 +234,15 @@ pub(crate) fn id(app: &VectorcraftApp) -> Option<DialogId> {
app.dialogs()?.with(|h| h.get_by_id::<SwatchConflictDialog>(id).map(|_| id))
}
/// What the question `id` answered this pass. A question about another document than the active one, with no
/// deferred paste to go back to, answers Cancel.
/// What the question `id` answered this pass. An immediate question whose drawing is inactive or
/// reverted answers Cancel. Placing checks deferred answers against their original drawing.
pub(crate) fn take(app: &VectorcraftApp, id: DialogId) -> Taken {
let Some(host) = app.dialogs() else { return Taken::Open };
match host.with(|h| h.take_by_id::<SwatchConflictDialog>(id)) {
Some(Answer::Ok(value)) => {
let elsewhere = value["deferred"].is_null() && value["doc"].as_u64() != app.session.active().map(|doc| doc.uid);
if elsewhere { Taken::Cancelled } else { Taken::Answered(value) }
let drawing = app.session.active().map(|doc| (doc.uid, doc.reverts));
let retired = value["deferred"].is_null() && value["drawing"] != json!(drawing);
if retired { Taken::Cancelled } else { Taken::Answered(value) }
}
Some(_) => Taken::Cancelled,
None => Taken::Open,
+74 -1
View File
@@ -107,7 +107,9 @@ fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option<Stri
let selection = edit.is_none().then(|| st.selection.objects.iter().copied().collect::<HashSet<_>>());
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let name = fields.text("name").unwrap_or_default().to_string();
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name)));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name)).values(Bind::bound(fields))
});
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> {
let Some(active) = app.session.active().filter(|st| st.uid == document) else {
return Err(tl!("This symbol belongs to the document that opened the dialog.").into());
@@ -214,6 +216,77 @@ mod document_tests {
use super::*;
use crate::tests::picks::answer_dialog;
#[test]
fn keyboard_and_pointer_edits_reach_new_and_existing_symbol_options() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
super::super::host::pump(app, ui.ctx());
}
for editing in [false, true] {
let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap();
if editing {
app.run("symbol.new", json!({"name": "Badge", "type": "static", "alignToPixelGrid": true})).unwrap();
}
let mut panel = Panel::new(app, draw);
panel.room(egui::vec2(800.0, 800.0));
if editing {
open_edit(&mut panel.app(), Some("Badge")).unwrap();
} else {
open(&mut panel.app(), false).unwrap();
}
panel.frame();
let undo = panel.app().session.active().unwrap().history.undo.len();
assert_eq!(
panel.toggled("Align to Pixel Grid"),
Some(craft::behavior::Mixed::Same(editing)),
"the options open with the symbol's current pixel-alignment setting"
);
panel.click_role("Name", Role::TEXT_INPUT);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("Keyboard badge");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["name"], "Keyboard badge");
assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["type"], if editing { "static" } else { "dynamic" });
panel.click_role(if editing { "Dynamic Symbol" } else { "Static Symbol" }, Role::RADIO_BUTTON);
assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["type"], if editing { "dynamic" } else { "static" });
panel.click_role("Align to Pixel Grid", Role::CHECK_BOX);
panel.click_role("Enable Guides for 9-Slice Scaling", Role::CHECK_BOX);
for (label, key, input, value) in [
("Left", "sliceLeft", "10", 10.0),
("Top", "sliceTop", "20", 20.0),
("Right", "sliceRight", "30", 30.0),
("Bottom", "sliceBottom", "40", 40.0),
] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))[key], value);
}
panel.click("OK");
assert!(!super::super::tests_warp::open_ids(&panel.app()).contains(&dialog_id(KIND)));
let app = panel.app();
let state = app.session.active().unwrap();
let symbol = state.doc.symbols.iter().find(|symbol| symbol.name == "Keyboard badge").unwrap();
assert_eq!(symbol.dynamic, editing);
assert_eq!(state.doc.symbol_pixel_aligned("Keyboard badge"), !editing);
assert_eq!(
state.doc.symbol_nine_slice("Keyboard badge"),
Some(vectorcraft_doc::SymbolNineSlice { left: 0.1, top: 0.2, right: 0.3, bottom: 0.4 })
);
assert_eq!(state.doc.symbols.len(), 1);
assert_eq!(state.history.undo.len(), undo + 1);
}
}
#[test]
fn editing_symbol_options_does_not_rename_another_drawings_symbol() {
let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default()));
@@ -119,6 +119,88 @@ fn the_manager_adds_edits_and_deletes_presets_through_the_editor() {
assert!(!is_open(&app), "Close");
}
#[test]
fn print_presets_difference_caption_uses_the_visible_default_name() {
use egui::accesskit::{Node, NodeId, Role};
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
fn modal_nodes(out: &[(NodeId, Node)]) -> Vec<&Node> {
let modal = out.iter().find(|(_, node)| node.role() == Role::Dialog).expect("Print Presets dialog").0;
let by_id: std::collections::HashMap<_, _> = out.iter().map(|(id, node)| (*id, node)).collect();
let mut pending = vec![modal];
let mut nodes = Vec::new();
while let Some(id) = pending.pop() {
let Some(node) = by_id.get(&id) else { continue };
nodes.push(*node);
pending.extend_from_slice(node.children());
}
nodes
}
let mut failures = Vec::new();
let name = "Épreuve — Δοκιμή";
for lang in ["en", "fr", "el"] {
for height in [500.0, 800.0] {
let mut app = new_app(Default::default());
app.session.prefs.interface_language = lang.into();
app.run("print.presets.save", json!({"name": name, "settings": {"copies": 2}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
ctx.enable_accesskit();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, height));
let mut time = 0.0;
let mut draw = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
draw(&mut app, vec![]);
app.run("ui.printPresetsDialog", json!({})).unwrap();
for _ in 0..6 {
draw(&mut app, vec![]);
}
let default_label = crate::i18n::t(DEFAULT_PRESET);
if lang != "en" {
assert_ne!(default_label, DEFAULT_PRESET, "the tested locale has its own Default name");
}
let expected = crate::i18n::fmt(crate::i18n::t("Differences from {preset}:"), &[("preset", default_label)]);
let stock = crate::i18n::fmt(crate::i18n::t("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]);
let frame = draw(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes;
let nodes = modal_nodes(&frame);
let row = |label| {
nodes
.iter()
.find(|node| matches!(node.role(), Role::ListItem | Role::ListBoxOption) && node.label() == Some(label))
.unwrap_or_else(|| panic!("{lang} at 800 by {height}: missing preset row {label:?}"))
};
assert_eq!(row(default_label).is_selected(), Some(true));
let bounds = row(name).bounds().unwrap();
let click = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
assert!(screen.contains(click));
if !nodes.iter().any(|node| node.label() == Some(expected.as_str())) {
failures.push(format!(
"{lang} at 800 by {height}, Default: expected {expected:?}, English name present: {}",
nodes.iter().any(|node| node.label() == Some(stock.as_str()))
));
}
draw(&mut app, vec![Event::PointerMoved(click)]);
for pressed in [true, false] {
draw(&mut app, vec![Event::PointerButton { pos: click, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
draw(&mut app, vec![]);
assert_eq!(fields(&app)["selected"], name);
let frame = draw(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes;
let nodes = modal_nodes(&frame);
if !nodes.iter().any(|node| node.label() == Some(expected.as_str())) {
failures.push(format!(
"{lang} at 800 by {height}, saved preset: expected {expected:?}, English name present: {}",
nodes.iter().any(|node| node.label() == Some(stock.as_str()))
));
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
#[test]
fn presets_files_import_and_export() {
let dir = std::env::temp_dir().join(format!("vc-printpresets-ui-{}", std::process::id()));
+64 -3
View File
@@ -6,6 +6,7 @@ use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::Label;
use serde_json::Value;
use vectorcraft_doc::NodeId;
use super::export_host::{self, After, Export, Open, options};
use super::form;
@@ -32,11 +33,28 @@ fn params(can_select: bool) -> Vec<Param> {
]
}
/// The drawing and selected objects a Selection Only export started with.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct SelectionSource {
drawing: (u64, u64),
objects: Vec<NodeId>,
}
impl SelectionSource {
fn of(app: &VectorcraftApp) -> Option<Self> {
let state = app.session.active()?;
let mut objects = state.selection.objects.clone();
objects.sort_unstable();
Some(Self { drawing: (state.uid, state.reverts), objects })
}
}
/// Open the options for exporting the document's text to `path`; `selection` when Export Selection opened them.
pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(), String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Export Selection keeps Selection Only on.
let can_select = !selection && app.session.active().is_some_and(|st| !st.selection.objects.is_empty());
let source = SelectionSource::of(app);
let can_select = !selection && source.as_ref().is_some_and(|source| !source.objects.is_empty());
// The platform's own line endings by default.
let eol = if cfg!(windows) { LINE_ENDINGS[1] } else { LINE_ENDINGS[0] };
let mut fields = DialogFields::from_pairs([("format", "txt"), ("path", path), ("encoding", ENCODINGS[0]), ("lineEndings", eol)]);
@@ -44,12 +62,15 @@ pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(),
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Text Export Options"), params(can_select)).values(Bind::bound(fields)).ok_label(Label::from("Export"))
});
export_host::open(app, Export::Text, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into())
export_host::open(app, Export::Text { source }, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into())
}
/// Write the text file (the command runs first, so a bad option keeps the dialog open). Opened by
/// Export Selection, it writes `document.exportSelection`'s text.
pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result<After, String> {
pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, source: Option<&SelectionSource>, fields: &DialogFields) -> Result<After, String> {
if (open.selection || fields.bool("selectionOnly") == Some(true)) && SelectionSource::of(app).as_ref() != source {
return Err(tl!("Select the original artwork to export it, or reopen Text Export Options.").into());
}
let mut params = Value::Object(form::json_of(&params(true), fields));
let id = if open.selection {
if let Some(o) = params.as_object_mut() {
@@ -62,3 +83,43 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel
io::save_command_output(app, id, "txt", params, |_, _| Ok(Value::Null))?;
Ok(None)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::super::tests_export::{app_saving, frame, kind, set, try_confirm};
#[test]
fn selection_only_text_export_stays_on_the_opening_artwork() {
for export_selection in [true, false] {
let (mut app, written) = app_saving(1, |_| "/output/selection.txt".into());
let first = app.run("text.create", json!({"x": 5, "y": 10, "text": "First text"})).unwrap()["id"].clone();
let second = app.run("text.create", json!({"x": 5, "y": 25, "text": "Second text"})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [first]})).unwrap();
if export_selection {
app.run("document.exportSelection", json!({})).unwrap();
frame(&mut app);
} else {
app.run("file.exportAs", json!({"format": "txt"})).unwrap();
try_confirm(&mut app).unwrap();
set(&mut app, "selectionOnly", json!(true));
}
assert_eq!(kind(&app).as_deref(), Some("txtOptions"));
app.run("select.set", json!({"ids": [second]})).unwrap();
let why = try_confirm(&mut app).expect_err("the original selection is required");
assert!(why.contains("original artwork"));
assert_eq!(kind(&app).as_deref(), Some("txtOptions"));
assert!(written.borrow().is_empty());
app.run("select.set", json!({"ids": [first]})).unwrap();
try_confirm(&mut app).unwrap();
let output = written.borrow();
assert_eq!(output.len(), 1);
let contents = std::str::from_utf8(&output[0].1).unwrap();
assert!(contents.contains("First text"));
assert!(!contents.contains("Second text"));
}
}
}
+59 -1
View File
@@ -10,6 +10,7 @@
//! already says, and its Name field renames the row. The data set dialogs stay open when OK
//! fails, keeping what was typed.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::Label;
use serde_json::{Value, json};
@@ -127,7 +128,7 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
let build_id = command.clone();
let dialog = HostedParamDialog::new(&ctx, KEY, fields, move |fields| {
let rows = params(&vars, &build_id, fields);
ParamDialog::command(KEY, Label::from(title.clone()), rows)
ParamDialog::command(KEY, Label::from(title.clone()), rows).values(Bind::bound(fields))
});
crate::dialogs::host::open_held(app, dialog, move |app, result| ok(app, document, &command, result));
true
@@ -583,4 +584,61 @@ mod tests {
ok(&mut app);
assert_eq!((kind_of(&app, "Flag"), kind_of(&app, "Badge")), (Some(VariableKind::Visibility), None));
}
fn type_in(panel: &mut crate::tests::panel_harness::Panel, label: &str, value: &str) {
panel.click_role(label, craft::ui::contract::Role::TEXT_INPUT);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(value);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
#[test]
fn the_typed_variable_name_renames_the_opening_variable() {
use crate::tests::panel_harness::Panel;
let mut panel = Panel::new(app_with_variables(), crate::tests::picks::dialogs);
assert!(open(&mut panel.app(), "variable.rename", Some("Badge")));
panel.frame();
type_in(&mut panel, "Name", "Logo");
panel.click("OK");
panel.frame();
let app = panel.app();
assert_eq!(kind_of(&app, "Logo"), Some(VariableKind::Visibility), "the typed name applies to the highlighted variable");
assert_eq!(kind_of(&app, "Badge"), None);
assert_eq!(kind_of(&app, "Title"), Some(VariableKind::Text));
}
#[test]
fn real_data_set_edits_keep_the_opening_row_and_preserve_cancel() {
use crate::tests::panel_harness::Panel;
use craft::behavior::Mixed;
use craft::ui::contract::Role;
let mut app = app_with_variables();
app.run("dataset.new", json!({"name": "First", "values": {"Title": "Unchanged", "Badge": true}})).unwrap();
app.run("dataset.new", json!({"name": "Second", "values": {"Title": "Original", "Badge": false}})).unwrap();
app.run("dataset.select", json!({"name": "Second"})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
assert!(open(&mut panel.app(), "dataset.set", None));
panel.frame();
assert_eq!(panel.value_role("Title", Role::TEXT_INPUT).as_deref(), Some("Original"), "the editor displays the active row's text");
assert_eq!(panel.toggled("Badge"), Some(Mixed::Same(false)));
type_in(&mut panel, "Title", "Approved");
panel.click_role("Badge", Role::CHECK_BOX);
panel.click("OK");
panel.frame();
let accepted = panel.app().run("dataset.list", json!({})).unwrap();
assert_eq!(accepted["datasets"][0]["values"]["Title"], json!({"text": "Unchanged"}));
assert_eq!(accepted["datasets"][1]["values"]["Title"], json!({"text": "Approved"}));
assert_eq!(accepted["datasets"][1]["values"]["Badge"], json!({"visible": true}));
assert!(open(&mut panel.app(), "dataset.set", None));
panel.frame();
type_in(&mut panel, "Title", "Discarded");
panel.click("Cancel");
panel.frame();
assert_eq!(panel.app().run("dataset.list", json!({})).unwrap(), accepted);
}
}
+56 -1
View File
@@ -789,7 +789,17 @@ fn takes_drop(mixed: (bool, bool), well: Well, drag: &PanelDrag) -> bool {
/// Paints the fill (the primary well) or the stroke with the paint `drag` carries.
fn drop_paint(app: &mut VectorcraftApp, well: Well, drag: &PanelDrag) {
if let Some(params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) {
let destination = app.session.active().map(|st| st.uid);
if let PanelDrag::Paint { paint, rows: Some(rows), .. } = drag
&& !rows.unlinked_process_color
&& destination.is_some_and(|uid| uid != rows.document)
&& paint.color().is_some()
&& !paint.is_registration()
{
app.status(tl!("A linked color swatch can only be applied in its own document."));
return;
}
if let Some(params) = drag.paint_drop_params(destination) {
let cmd = if well == Well::Primary { "paint.setFill" } else { "paint.setStroke" };
app.run(cmd, params).ok();
}
@@ -1111,6 +1121,51 @@ mod tests {
assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination);
}
#[test]
fn proxy_linked_swatches_stay_in_their_source_drawing() {
use crate::panel_drag::SwatchRows;
let name = "Shared Swatch";
for spot in [false, true] {
for (different_drawing, collision) in [(false, false), (true, false), (true, true)] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap();
let source = app.session.active().unwrap();
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows =
SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false };
let drag = PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None };
if different_drawing {
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
}
if collision {
app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).unwrap();
}
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
app.run("paint.setStroke", json!({"color": "#ffff00"})).unwrap();
let initial = current_paints(&app);
let target = app.session.active().unwrap();
let palette = target.doc.swatch(name).map(|swatch| swatch.paint.clone());
let initial_undo = target.history.undo.len();
drop_paint(&mut app, Well::Primary, &drag);
drop_paint(&mut app, Well::Secondary, &drag);
let target = app.session.active().unwrap();
assert_eq!(target.doc.swatch(name).map(|swatch| swatch.paint.clone()), palette);
if different_drawing {
assert_eq!(current_paints(&app), initial, "spot={spot}, collision={collision}");
assert_eq!(target.history.undo.len(), initial_undo);
assert_eq!(app.ui.status, tl!("A linked color swatch can only be applied in its own document."));
} else {
let linked = target.doc.tint_paint(name, 1.0).unwrap();
assert_eq!(current_paints(&app), (linked.clone(), linked));
}
}
}
}
#[test]
fn paint_params_roundtrip_shapes() {
assert_eq!(paint_params(&Paint::None), json!({"none": true}));
+38 -10
View File
@@ -80,6 +80,9 @@ fn color_group<'a>(app: &VectorcraftApp, params: &'a Value) -> Option<&'a str> {
rows::known_group(&rows::swatch_groups(app), params)
}
/// An object's open document, content generation and node id.
type ObjectKey = (u64, u64, NodeId);
/// Panel state: the preset name, the current parameters, the view and the last result's counts.
#[derive(Clone, Debug, Default)]
pub(crate) struct TraceUi {
@@ -93,13 +96,13 @@ pub(crate) struct TraceUi {
/// The selected Image Trace object's stored settings last adopted (so edits in progress
/// aren't overwritten until the object changes).
synced: Value,
/// The document and object `synced` came from.
object: Option<(u64, NodeId)>,
/// The document contents and object `synced` came from.
object: Option<ObjectKey>,
/// Preview was off at the panel's last frame.
preview_off: bool,
/// The settings that wait for objects no longer selected, by document and object: the preset,
/// The settings that wait for objects no longer selected, by document contents and object: the preset,
/// the parameters, and the object's stored settings they were changed from.
drafts: std::collections::HashMap<(u64, NodeId), (String, Value, Value)>,
drafts: std::collections::HashMap<ObjectKey, (String, Value, Value)>,
}
/// The Image Trace panel's run-only state: what it shows, and the view settings of its preset picker.
@@ -184,6 +187,8 @@ pub(crate) fn is_trace(n: &Node) -> bool {
/// object (wherever it is in the selection).
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Target {
/// Present even with nothing selected, so Revert can retire that document's old drafts.
document: Option<(u64, u64)>,
/// The active document's uid and the object Trace acts on.
object: Option<(u64, NodeId)>,
/// The object is an Image Trace object.
@@ -195,6 +200,14 @@ pub(crate) struct Target {
any_trace: bool,
}
impl Target {
fn object_key(&self) -> Option<ObjectKey> {
let (uid, node) = self.object?;
let (_, reverts) = self.document?;
Some((uid, reverts, node))
}
}
/// Whether any selected object is an Image Trace object.
fn any_trace_selected(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace)))
@@ -204,13 +217,15 @@ fn any_trace_selected(app: &VectorcraftApp) -> bool {
/// first selected non-traceable object's metadata. Release and Expand keep their own selection scope.
fn find_target(app: &VectorcraftApp) -> Target {
let Some(st) = app.session.active() else { return Target::default() };
let document = Some((st.uid, st.reverts));
let any_trace = any_trace_selected(app);
let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null)
.ok()
.and_then(|id| st.doc.node(id))
.or_else(|| first_node(app).filter(|n| !is_trace(n) && !matches!(n.kind, NodeKind::Image(_))));
let Some(n) = node else { return Target { any_trace, ..Target::default() } };
let Some(n) = node else { return Target { document, any_trace, ..Target::default() } };
Target {
document,
object: Some((st.uid, n.id)),
is_trace: is_trace(n),
is_image: matches!(n.kind, NodeKind::Image(_)),
@@ -482,7 +497,7 @@ pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) {
let mut st = std::mem::take(&mut app.ui.image_trace_panel.shown);
follow_preset_changes(app, &mut st, &list.presets);
let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect();
sync_with_object(&mut st, t.stored.clone(), Some((s.doc, s.target)), &list.presets, &changes);
sync_with_object(&mut st, &t, &list.presets, &changes);
st.params["ignoreColor"] = json!(color);
st.preset = "Custom".into();
let preview = app.ui.image_trace_preview;
@@ -624,10 +639,11 @@ fn trace(app: &mut VectorcraftApp, st: &mut TraceUi) {
/// the next panel frame must still be recognized as a change, even when it returns to the previous
/// settings.
fn adopt(st: &mut TraceUi, target: &Target, r: &Value) {
discard_retired_drafts(st, target.document);
st.info = Some((r["paths"].as_u64().unwrap_or(0), r["anchors"].as_u64().unwrap_or(0), r["colors"].as_u64().unwrap_or(0)));
if let Some(stored) = &target.stored {
st.synced = stored.clone();
st.object = target.object;
st.object = target.object_key();
}
}
@@ -678,10 +694,22 @@ fn listed_preset(name: &str, params: &Value, all: &[Preset], changes: &[&TracePr
found.map_or_else(|| "Custom".into(), |p| p.0.clone())
}
/// Bring the panel's settings `st` in line with the selected object `object`, whose trace settings are `stored`,
/// Drop only drafts for content that Revert replaced in the active document.
fn discard_retired_drafts(st: &mut TraceUi, document: Option<(u64, u64)>) {
let Some((uid, reverts)) = document else { return };
st.drafts.retain(|(doc, generation, _), _| *doc != uid || *generation == reverts);
if st.object.is_some_and(|(doc, generation, _)| doc == uid && generation != reverts) {
st.object = None;
st.synced = Value::Null;
}
}
/// Bring the panel's settings `st` in line with the selected object's stored settings,
/// with the presets `all` and the saved preset changes `changes` of this session (oldest first); whether the object
/// came back with the settings that waited for it.
fn sync_with_object(st: &mut TraceUi, stored: Option<Value>, object: Option<(u64, NodeId)>, all: &[Preset], changes: &[&TracePresetChange]) -> bool {
fn sync_with_object(st: &mut TraceUi, target: &Target, all: &[Preset], changes: &[&TracePresetChange]) -> bool {
discard_retired_drafts(st, target.document);
let (stored, object) = (target.stored.clone(), target.object_key());
let same = |a: &Value, b: &Value| a["preset"] == b["preset"] && a["params"] == b["params"];
let mut restored = false;
// Another object: the settings that wait for the one left are kept until it is selected again,
@@ -796,7 +824,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
follow_preset_changes(app, &mut st, &list.presets);
let restored = {
let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect();
sync_with_object(&mut st, t.stored.clone(), t.object, &list.presets, &changes)
sync_with_object(&mut st, &t, &list.presets, &changes)
};
let preview = app.ui.image_trace_preview;
let mut actions = (false, false, false);
+62 -4
View File
@@ -99,6 +99,60 @@ fn traced_app_with_ink(ink: u8) -> VectorcraftApp {
app
}
/// Revert reloads the saved file even when its trace has the same node id and stored settings.
/// A preview-off draft belongs to the discarded source pixels, not the reloaded object.
#[test]
fn native_file_revert_discards_pending_settings_for_reused_trace_ids() {
for frame_without_selection in [false, true] {
let mut app = traced_app_with_ink(0);
let old = find_target(&app);
let id = old.object.unwrap().1;
let old_source = source_image(app.session.active().unwrap().doc.node(id).unwrap()).unwrap().key.clone();
let dir = vectorcraft_testkit::TempDir::new("trace-native-revert");
let path = dir.join("saved.vectorcraft");
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("object.move", json!({"ids": [id.0], "dx": 1, "dy": 0})).unwrap();
// Another saved copy supplies different pixels with the same trace identity and settings.
let mut saved = traced_app_with_ink(100);
let restored = find_target(&saved);
assert_eq!(restored.object.unwrap().1, id);
assert_eq!(old.stored.as_ref().unwrap()["params"], restored.stored.as_ref().unwrap()["params"]);
saved.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
saved.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
let mut panel = panel_over(app);
panel.click("Preview");
panel.click("Strokes");
assert!(!panel.app().ui.image_trace_preview);
assert_eq!(shown(&panel).params["strokes"], json!(true));
assert_eq!(param(&panel.app(), "strokes"), Some(json!(false)), "the changed setting remains a panel draft");
let uid = panel.app().session.active().unwrap().uid;
let reverts = panel.app().session.active().unwrap().reverts;
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
{
let app = panel.app();
let st = app.session.active().unwrap();
assert_eq!(st.uid, uid);
assert_eq!(st.reverts, reverts + 1, "the native Revert replaced the drawing contents");
assert!(st.selection.objects.is_empty());
assert_ne!(source_image(st.doc.node(id).unwrap()).unwrap().key, old_source, "Revert read the other saved pixels");
}
if frame_without_selection {
panel.frame();
}
select(&mut panel, id);
assert_eq!(shown(&panel).params, restored.stored.unwrap()["params"], "the saved trace's own settings are adopted");
assert!(shown(&panel).drafts.is_empty(), "the discarded source's draft is gone");
let before = undo(&panel.app());
panel.click("Preview");
assert_eq!(param(&panel.app(), "strokes"), Some(json!(false)));
assert_eq!(undo(&panel.app()), before, "Preview must not apply the discarded source's draft");
}
}
fn scroll_settings(panel: &mut Panel, dy: f32) {
panel.scroll_at(egui::pos2(30.0, 30.0), dy);
panel.advance(1.0);
@@ -403,7 +457,8 @@ fn settings_that_wait_are_dropped_when_their_object_changed_since() {
// A's settings as they were when the change was made, other than its settings now.
{
let mut app = panel.app();
let key = (app.session.active().unwrap().uid, a);
let doc = app.session.active().unwrap();
let key = (doc.uid, doc.reverts, a);
let draft = app.ui.image_trace_panel.shown.drafts.get_mut(&key).expect("the change waits for A");
assert_eq!(draft.1["strokes"], json!(true));
draft.2["params"]["threshold"] = json!(1);
@@ -1163,7 +1218,7 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() {
assert_eq!(param(&app, "strokes"), Some(json!(true)));
let st = &app.ui.image_trace_panel.shown;
assert!(st.info.is_some(), "its counts show");
assert_eq!(st.object, find_target(&app).object);
assert_eq!(st.object, find_target(&app).object_key());
assert!(st.drafts.is_empty(), "nothing waits for the object it replaced");
app.ui.image_trace_preview = true;
}
@@ -1192,9 +1247,11 @@ fn target_node_sorting_everything(app: &VectorcraftApp) -> Option<Node> {
/// [`Target`] from [`target_node_sorting_everything`] and a scan of the whole selection for Image
/// Trace objects, as the panel read them on every frame before.
fn target_sorting_everything(app: &VectorcraftApp) -> Target {
let document = app.session.active().map(|st| (st.uid, st.reverts));
let any_trace = app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace)));
let Some(n) = target_node_sorting_everything(app) else { return Target { any_trace, ..Target::default() } };
let Some(n) = target_node_sorting_everything(app) else { return Target { document, any_trace, ..Target::default() } };
Target {
document,
object: app.session.active().map(|st| (st.uid, n.id)),
is_trace: is_trace(&n),
is_image: matches!(n.kind, NodeKind::Image(_)),
@@ -1347,7 +1404,8 @@ fn the_target_lookup_obeys_canonical_roots_and_explicit_id_validation() {
for (parent, child) in [("clip", "clipped"), ("outer", "deep")] {
select_as_is(&mut app, &[ids[parent], ids[child]]);
let uid = app.session.active().unwrap().uid;
let expected = Target { object: Some((uid, ids[parent])), ..Default::default() };
let document = app.session.active().map(|st| (st.uid, st.reverts));
let expected = Target { document, object: Some((uid, ids[parent])), ..Default::default() };
assert_eq!(find_target(&app), expected, "the selected {parent} supplies metadata, not its pruned image");
assert_eq!(*target(&mut app), expected);
assert_eq!(*target(&mut app), expected, "the canonical result is also cached");
+19 -33
View File
@@ -24,11 +24,9 @@ use craft::ui::style::DataColor;
use craft::ui::text::{LinkMode, LinkedFields};
use craft::ui::text::{NumberField, NumberOutput, NumberPick, StepArrows};
use egui::{Rect, Ui, pos2};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, ArrowAlign, Arrowhead, Dash, Document, Node, StrokeLayer, Unit, WidthProfile};
use vectorcraft_doc::{Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, StrokeAlign, StrokeLayer, Unit, WidthProfile};
use vectorcraft_engine::inspect::StrokeMixed;
use super::{Live, character, current_stroke, live_run, stroke_mixed};
@@ -171,11 +169,6 @@ pub(crate) fn shown_weight(app: &VectorcraftApp, st: Option<&StrokeLayer>, mixed
(!mixed.weight).then(|| st.map_or(app.session.paint.stroke_width, |s| s.width))
}
/// A document enum as the editor's enum of the same name: both serialise as the same camelCase word.
fn convert<A: Serialize, B: DeserializeOwned + Default>(a: A) -> B {
serde_json::to_value(a).ok().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default()
}
/// The style the stroke editor shows for `st` (the defaults without a stroke). Dashes count document units, so the
/// pattern is the stroke's own numbers.
pub(crate) fn style_of(st: Option<&StrokeLayer>) -> draw::StrokeStyle {
@@ -185,9 +178,21 @@ pub(crate) fn style_of(st: Option<&StrokeLayer>) -> draw::StrokeStyle {
s.dash.as_ref().map_or((vec![], 0.0, false), |d| (d.pattern.iter().map(|v| *v as f32).collect(), d.offset, d.align_corners));
draw::StrokeStyle {
width: s.width as f32,
align: convert(s.align),
cap: convert(s.cap),
join: convert(s.join),
align: match s.align {
StrokeAlign::Center => draw::StrokeAlign::Center,
StrokeAlign::Inside => draw::StrokeAlign::Inside,
StrokeAlign::Outside => draw::StrokeAlign::Outside,
},
cap: match s.cap {
LineCap::Butt => draw::LineCap::Butt,
LineCap::Round => draw::LineCap::Round,
LineCap::Square => draw::LineCap::Square,
},
join: match s.join {
LineJoin::Miter => draw::LineJoin::Miter,
LineJoin::Round => draw::LineJoin::Round,
LineJoin::Bevel => draw::LineJoin::Bevel,
},
miter_limit: s.miter_limit as f32,
dashes,
dash_offset: offset as f32,
@@ -212,13 +217,12 @@ fn num(v: f32) -> f64 {
/// The `stroke.set` params of an edit of `field` that turned `old` into `new`: only what the field changes, so
/// each selected stroke keeps its other options (its dash offset and alignment included).
pub(crate) fn params_of(old: &draw::StrokeStyle, new: &draw::StrokeStyle, field: StrokeField) -> Value {
let word = |v: &dyn erased::Word| v.word();
let dash = if new.dashes.is_empty() { Value::Null } else { json!(new.dashes.iter().map(|v| num(*v)).collect::<Vec<_>>()) };
let corners = new.dash_align == draw::DashAlign::Corners;
match field {
StrokeField::Align => json!({"align": word(&new.align)}),
StrokeField::Cap => json!({"cap": word(&new.cap)}),
StrokeField::Join => json!({"join": word(&new.join)}),
StrokeField::Align => json!({"align": new.align}),
StrokeField::Cap => json!({"cap": new.cap}),
StrokeField::Join => json!({"join": new.join}),
StrokeField::MiterLimit => json!({"miterLimit": num(new.miter_limit)}),
StrokeField::Dashed => json!({"dash": dash, "alignDashes": corners}),
StrokeField::Dash(_) => json!({"dash": dash}),
@@ -231,24 +235,6 @@ pub(crate) fn params_of(old: &draw::StrokeStyle, new: &draw::StrokeStyle, field:
}
}
/// The word `stroke.set` reads for an editor enum.
mod erased {
use serde::Serialize;
use serde_json::Value;
/// An enum that serialises as its camelCase word.
pub trait Word {
/// The word.
fn word(&self) -> Value;
}
impl<T: Serialize> Word for T {
fn word(&self) -> Value {
serde_json::to_value(self).unwrap_or(Value::Null)
}
}
}
/// Sends an editor edit of `field` (`old` to `new`) to the strokes. Turning dashes off remembers the pattern; turning
/// them on brings back the remembered one, or 12 pt dashes fitted to corners.
fn apply_style(app: &mut VectorcraftApp, old: &draw::StrokeStyle, mut new: draw::StrokeStyle, field: StrokeField) {
@@ -13,6 +13,101 @@ use crate::tests::panel_harness::{Panel, ROOM};
type Show = fn(&mut VectorcraftApp, &mut Ui);
#[test]
fn stroke_style_choices_cross_the_editor_bridge_in_both_directions() {
use craft::draw::ui::stroke::{self as draw, StrokeField};
use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign};
let mut app = app_with_rect();
run(&mut app, "paint.setStroke", json!({"color": "#222222"}));
let mut document = current_stroke(&app).unwrap();
let rows = [
(LineCap::Butt, draw::LineCap::Butt, "butt"),
(LineCap::Round, draw::LineCap::Round, "round"),
(LineCap::Square, draw::LineCap::Square, "square"),
];
for (choice, shown, keyword) in rows {
document.cap = choice;
let style = stroke::style_of(Some(&document));
assert_eq!(style.cap, shown);
let params = stroke::params_of(&draw::StrokeStyle::default(), &style, StrokeField::Cap);
run(&mut app, "stroke.set", params.clone());
assert_eq!(params, json!({"cap": keyword}));
assert_eq!(current_stroke(&app).unwrap().cap, choice);
}
let rows = [
(LineJoin::Miter, draw::LineJoin::Miter, "miter"),
(LineJoin::Round, draw::LineJoin::Round, "round"),
(LineJoin::Bevel, draw::LineJoin::Bevel, "bevel"),
];
for (choice, shown, keyword) in rows {
document.join = choice;
let style = stroke::style_of(Some(&document));
assert_eq!(style.join, shown);
let params = stroke::params_of(&draw::StrokeStyle::default(), &style, StrokeField::Join);
run(&mut app, "stroke.set", params.clone());
assert_eq!(params, json!({"join": keyword}));
assert_eq!(current_stroke(&app).unwrap().join, choice);
}
let rows = [
(StrokeAlign::Center, draw::StrokeAlign::Center, "center"),
(StrokeAlign::Inside, draw::StrokeAlign::Inside, "inside"),
(StrokeAlign::Outside, draw::StrokeAlign::Outside, "outside"),
];
for (choice, shown, keyword) in rows {
document.align = choice;
let style = stroke::style_of(Some(&document));
assert_eq!(style.align, shown);
let params = stroke::params_of(&draw::StrokeStyle::default(), &style, StrokeField::Align);
run(&mut app, "stroke.set", params.clone());
assert_eq!(params, json!({"align": keyword}));
assert_eq!(current_stroke(&app).unwrap().align, choice);
}
}
#[test]
fn compact_stroke_miter_limit_only_applies_to_miter_joins() {
use craft::ui::contract::Role;
use egui::{Key, Pos2, Rect};
use vectorcraft_doc::LineJoin;
for (join, width) in [("round", crate::panel_docking::PANEL_MIN_WIDTH), ("bevel", 320.0)] {
let mut app = app_with_rect();
app.session.prefs.interface_language = "en".into();
run(&mut app, "paint.setStroke", json!({"color": "#222222"}));
run(&mut app, "stroke.set", json!({"join": join, "miterLimit": 4}));
let original = current_stroke(&app).unwrap();
let room = egui::vec2(width, 500.0);
let mut panel = Panel::new(app, stroke::show);
panel.room(room).frame();
let baseline = panel.app().session.active().unwrap().history.undo.len();
let edit = |panel: &mut Panel| {
let field = panel.rect_role("Miter limit", Role::SPIN_BUTTON);
assert!(Rect::from_min_size(Pos2::ZERO, room).contains_rect(field));
let value = panel.app().host.i18n().unwrap().format().number(8.5, 1);
panel.click_at(field.center());
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(&value);
panel.key(Key::Enter, Modifiers::NONE);
};
edit(&mut panel);
assert_eq!(current_stroke(&panel.app()).unwrap(), original);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), baseline);
panel.click("Miter");
let miter = current_stroke(&panel.app()).unwrap();
assert_eq!(miter.join, LineJoin::Miter);
edit(&mut panel);
let mut expected = miter.clone();
expected.miter_limit = 8.5;
assert_eq!(current_stroke(&panel.app()).unwrap(), expected);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), baseline + 2);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(current_stroke(&panel.app()).unwrap(), miter);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(current_stroke(&panel.app()).unwrap(), original);
}
}
#[test]
fn weights_and_dashes_show_in_the_stroke_unit_everywhere() {
let mut app = app_with_rect();
+29 -13
View File
@@ -343,16 +343,23 @@ fn pick(app: &mut VectorcraftApp, p: &Value) -> Value {
// The web answers with the files' contents instead of paths.
crate::file_asks::ask(app, request, Owner::Document, move |app, picked| {
let files = match picked {
Picked::Paths(paths) => paths.into_iter().map(|path| with_importer(json!({ "path": path.to_string_lossy() }), &with)).collect(),
Picked::Contents(files) => files
.into_iter()
.map(|(name, bytes)| {
app.place.picked.retain(|(n, _)| *n != name);
let entry = with_importer(json!({ "name": name }), &with);
app.place.picked.push((name, bytes));
entry
})
.collect(),
Picked::Paths(paths) => {
app.place.picked.clear();
paths.into_iter().map(|path| with_importer(json!({ "path": path.to_string_lossy() }), &with)).collect()
}
Picked::Contents(files) => {
// The next Place dialog replaces the previous selection, including its source bytes.
app.place.picked.clear();
files
.into_iter()
.map(|(name, bytes)| {
app.place.picked.retain(|(n, _)| *n != name);
let entry = with_importer(json!({ "name": name }), &with);
app.place.picked.push((name, bytes));
entry
})
.collect()
}
// Only an open's answers carry files.
_ => return Ok(Value::Null),
};
@@ -398,20 +405,29 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
use crate::dialogs::place::PlaceDialog;
use craft::ui::dialog::DialogResult;
let Some(dialogs) = app.dialogs() else { return };
let (reading, answer) = dialogs.with(|host| {
let (reading, answer, current_open) = dialogs.with(|host| {
let reading = host.get_mut::<PlaceDialog>().is_some_and(|d| fill_lines(app, &d.files, &mut d.info));
(reading, host.take::<PlaceDialog>())
let answer = host.take::<PlaceDialog>();
(reading, answer, host.is_open::<PlaceDialog>())
});
if reading {
ctx.request_repaint_after(std::time::Duration::from_millis(100));
}
// Place answers only after closing. Replacing an open Place leaves its Cancel while the new
// dialog is open; that retired selection must not clear the current selection's cache.
if current_open {
return;
}
match answer {
Some(DialogResult::Ok((files, options))) => {
if let Err(e) = confirm(app, files, options) {
app.status(e);
}
}
Some(_) => app.place.reading_lines = None,
Some(_) => {
app.place.reading_lines = None;
app.place.picked.clear();
}
None => {}
}
}
+93 -4
View File
@@ -1276,11 +1276,22 @@ fn with_set_at(app: &mut VectorcraftApp, path: &str, then: SetReader) -> Result<
if crate::dialogs::shortcut_import::is_kys(path) {
return crate::dialogs::shortcut_import::command(app, &json!({ "path": path }));
}
let read = app.services.read.as_ref().ok_or("no file reader")?;
let bytes = read(path)?;
let bytes = match (&app.services.read_head, &app.services.read) {
(Some(read), _) => read(path, (craft::keymap::MAX_EXPORT_BYTES + 1).max(vectorcraft_engine::cmd::shortcutset::READ_LIMIT))?,
(None, Some(read)) => read(path)?,
_ => return Err("no file reader".into()),
};
then(app, path, &bytes)
}
/// Bound the original JSON file before parsing or serializing its normalized form.
fn shortcut_json(bytes: &[u8]) -> Result<Value, String> {
if bytes.len() > craft::keymap::MAX_EXPORT_BYTES {
return Err(craft::keymap::ProfileError::TooLarge.to_string());
}
serde_json::from_slice(bytes).map_err(|e| e.to_string())
}
/// The dialog's Import…: a set another app saved as text opens its review; a JSON set waits for
/// the dialog's next pass, which loads it.
fn import_into_dialog(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) -> Result<Value, String> {
@@ -1290,7 +1301,7 @@ fn import_into_dialog(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) -> Res
if crate::dialogs::shortcut_import::is_text_set(name, bytes) {
return crate::dialogs::shortcut_import::open(app, name, bytes);
}
let v: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
let v = shortcut_json(bytes)?;
let text = keymap_json(&v)?;
if let Some(open) = app.shortcuts_dialog.as_mut() {
open.pending_import = Some(text);
@@ -1658,7 +1669,7 @@ fn import_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) -> Result<Va
if crate::dialogs::shortcut_import::is_text_set(name, bytes) {
return crate::dialogs::shortcut_import::open(app, name, bytes);
}
let v: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
let v = shortcut_json(bytes)?;
import_set(app, &v)
}
@@ -1763,6 +1774,84 @@ mod tests {
written
}
fn imported_json() -> Vec<u8> {
br#"{"format":"vectorcraft-shortcuts","version":1,"set":"Studio","overrides":{}}"#.to_vec()
}
/// A valid set padded past the shared file limit must not become acceptable after JSON
/// normalization. The real dialog's browser pick leaves its draft and saved preferences alone.
#[test]
fn the_shortcut_dialog_refuses_oversized_browser_json_before_normalization() {
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::testing::{Fixture, Room};
let (mut app, _) = app();
open(&mut app);
let prefs = serde_json::to_value(&app.session.prefs).unwrap();
let overrides = app.shortcut_overrides.clone();
let saved = app.ui.shortcut_sets.clone();
let app = Rc::new(RefCell::new(app));
let shown = Rc::clone(&app);
let mut fixture = Fixture::new(move |ui| show(&mut shown.borrow_mut(), ui));
fixture.in_room(Room::Window);
app.borrow_mut().ui_ctx = Some(fixture.ctx().clone());
let picker = crate::tests::picks::scripted(&mut app.borrow_mut());
fixture.settle();
let import = fixture.by_label("Import…").expect("the shortcut dialog's Import button");
fixture.click(&import).settle();
assert_eq!(picker.requests().len(), 1);
let mut large = imported_json();
large.resize(craft::keymap::MAX_EXPORT_BYTES + 1, b' ');
picker.answer_contents(&[("Studio.json", &large)]);
crate::file_asks::poll(&mut app.borrow_mut());
{
let app = app.borrow();
assert!(app.ui.status.contains("shortcut set file too large"), "{}", app.ui.status);
let draft = app.shortcuts_dialog.as_ref().unwrap();
assert!(draft.pending_import.is_none());
assert_eq!(app.shortcut_overrides, overrides);
assert_eq!(serde_json::to_value(&app.ui.shortcut_sets).unwrap(), serde_json::to_value(&saved).unwrap());
assert_eq!(serde_json::to_value(&app.session.prefs).unwrap(), prefs);
}
fixture.settle();
let import = fixture.by_label("Import…").unwrap();
fixture.click(&import).settle();
picker.answer_contents(&[("Studio.json", &imported_json())]);
crate::file_asks::poll(&mut app.borrow_mut());
assert!(app.borrow().shortcuts_dialog.as_ref().unwrap().pending_import.is_some(), "a small set still reaches the draft");
}
/// Direct automation uses the same raw-file bound and a bounded native read when available.
#[test]
fn shortcut_import_refuses_oversized_native_json_and_accepts_small_json() {
let (mut app, _) = app();
let prefs = serde_json::to_value(&app.session.prefs).unwrap();
let saved = serde_json::to_value(&app.ui.shortcut_sets).unwrap();
let requested = std::rc::Rc::new(std::cell::Cell::new(0));
let seen = requested.clone();
app.services.read = Some(Box::new(|_| panic!("a bounded reader is available")));
app.services.read_head = Some(Box::new(move |path, cap| {
seen.set(cap);
let mut bytes = imported_json();
if path == "/large.json" {
bytes.resize(cap, b' ');
} else if path == "/limit.json" {
bytes.resize(craft::keymap::MAX_EXPORT_BYTES, b' ');
}
Ok(bytes)
}));
let error = app.run("shortcuts.import", json!({"path": "/large.json"})).unwrap_err();
assert_eq!(error, "shortcut set file too large");
assert_eq!(requested.get(), (craft::keymap::MAX_EXPORT_BYTES + 1).max(vectorcraft_engine::cmd::shortcutset::READ_LIMIT));
assert_eq!(serde_json::to_value(&app.session.prefs).unwrap(), prefs);
assert_eq!(serde_json::to_value(&app.ui.shortcut_sets).unwrap(), saved);
let result = app.run("shortcuts.import", json!({"path": "/small.json"})).unwrap();
assert_eq!(result["set"], "Studio");
assert!(app.run("shortcuts.import", json!({"path": "/limit.json"})).is_ok(), "the exact byte limit is allowed");
}
/// A plug-in installed while the menus are walked doesn't leave a snapshot under the revision
/// read before the walk: the keymap built for that revision would then lack the plug-in's row.
#[test]
+32
View File
@@ -144,6 +144,38 @@ fn ok_pastes_nothing_after_another_document_became_active() {
assert!(objects(&app).is_empty(), "the document it asked in pastes nothing");
}
#[test]
fn immediate_swatch_conflict_pastes_nothing_after_destination_revert() {
let mut app = conflicting();
let dir = vectorcraft_testkit::TempDir::new("immediate-swatch-conflict-revert");
let path = dir.join("destination.vectorcraft");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
run(&mut app, "file.saveAs", json!({"path": path.to_string_lossy()}));
rect(&mut app);
assert_eq!(run(&mut app, "edit.paste", json!({"profileMismatch": "preserveNumbers"}))["dialog"], dialogs::swatch_conflict::KIND);
let id = question(&app);
host::set(&app, id, "choice", json!("add"));
host::set(&app, id, "applyToAll", json!(true));
let before = app.session.active().unwrap();
let (uid, reverts) = (before.uid, before.reverts);
run(&mut app, "file.revert", json!({"confirmed": true}));
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
assert!(objects(&app).is_empty());
assert_eq!(question(&app), id, "the old question is still waiting");
let saved = restored.doc.clone();
let undo = restored.history.undo.len();
assert!(host::confirm(&app, id));
host::frame(&mut app);
let after = app.session.active().unwrap();
assert!(after.doc == saved, "the old swatch approval must leave the restored drawing intact");
assert_eq!(after.history.undo.len(), undo);
assert!(dialogs::swatch_conflict::id(&app).is_none());
}
#[test]
fn paste_goes_to_the_centre_of_the_view() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+119
View File
@@ -121,6 +121,125 @@ fn dismiss(app: &mut VectorcraftApp) {
}
}
#[test]
fn cancelling_browser_place_releases_the_picked_file_buffers() {
let mut app = app();
let picker = scripted(&mut app);
let ctx = window(&app);
let bytes = png(6, 4, 72.0);
let undo = app.session.active().unwrap().history.undo.len();
for name in ["first.png", "second.png"] {
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[(name, &bytes)]);
crate::file_asks::poll(&mut app);
assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND));
assert_eq!(app.place.picked.len(), 1);
// Cancelling a replacement file picker leaves the existing Place selection usable.
app.run("file.place", json!({})).unwrap();
picker.cancel();
crate::file_asks::poll(&mut app);
assert_eq!(app.place.picked[0].0, name);
dismiss(&mut app);
crate::place::pump(&mut app, &ctx);
assert!(app.place.picked.is_empty(), "a cancelled Place selection no longer owns file bytes");
assert!(app.session.active().unwrap().doc.layers[0].children().unwrap().is_empty());
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
#[test]
fn a_finished_replacement_places_only_its_own_browser_file_before_the_next_pump() {
for old_ok in [false, true] {
let mut app = app();
let picker = scripted(&mut app);
let ctx = window(&app);
let old = png(6, 4, 72.0);
let new = png(8, 5, 72.0);
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("same.png", &old)]);
crate::file_asks::poll(&mut app);
let id = open_dialogs(&app).pop().unwrap().id;
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
if old_ok {
assert!(host.confirm_by_id(&ctx, id));
} else {
assert!(host.cancel_by_id(&ctx, id));
}
});
// Both openings finish before the application takes a Place result.
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("same.png", &new)]);
crate::file_asks::poll(&mut app);
let id = open_dialogs(&app).pop().unwrap().id;
dialogs.with(|host| {
host.set_json_field(&ctx, id, "link", json!(false)).unwrap();
host.set_json_field(&ctx, id, "showImportOptions", json!(false)).unwrap();
assert!(host.confirm_by_id(&ctx, id));
});
crate::place::pump(&mut app, &ctx);
assert!(app.place.picked.is_empty());
assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1);
let image = selected_image(&app);
assert!(matches!(&image.kind, NodeKind::Image(im) if (im.width, im.height) == (8, 5)));
let status = app.ui.status.clone();
let undo = app.session.active().unwrap().history.undo.len();
crate::place::pump(&mut app, &ctx);
assert_eq!(app.ui.status, status, "no earlier result remains to report an error");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
#[test]
fn an_old_place_ok_cannot_consume_a_newer_dialogs_browser_bytes() {
let mut app = app();
let picker = scripted(&mut app);
let ctx = window(&app);
let bytes = png(6, 4, 72.0);
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("old.png", &bytes)]);
crate::file_asks::poll(&mut app);
let id = open_dialogs(&app).pop().unwrap().id;
assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "Place closes when its answer is filed");
assert_ne!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND));
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("new.png", &bytes)]);
crate::file_asks::poll(&mut app);
app.ui.status = "new selection".into();
crate::place::pump(&mut app, &ctx);
assert_eq!(app.ui.status, "new selection", "the retired OK reports no stale error");
assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND));
assert_eq!(app.place.picked.len(), 1);
assert_eq!(app.place.picked[0].0, "new.png");
assert!(app.session.active().unwrap().doc.layers[0].children().unwrap().is_empty());
answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]);
assert!(app.place.picked.is_empty());
assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
#[test]
fn an_old_place_cancellation_keeps_a_newer_dialogs_browser_bytes() {
let mut app = app();
let picker = scripted(&mut app);
let ctx = window(&app);
let bytes = png(6, 4, 72.0);
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("old.png", &bytes)]);
crate::file_asks::poll(&mut app);
dismiss(&mut app);
// Open the replacement before the application pump consumes the previous cancellation.
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("new.png", &bytes)]);
crate::file_asks::poll(&mut app);
crate::place::pump(&mut app, &ctx);
assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND));
assert_eq!(app.place.picked.len(), 1, "the replacement owns only its own source bytes");
assert_eq!(app.place.picked[0].0, "new.png");
answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]);
assert!(app.place.picked.is_empty(), "confirmation transfers the bytes out of the dialog cache");
assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1, "the newer file still places");
}
#[derive(Debug)]
struct Dropped(std::path::PathBuf);