Merge main into fix/browser-place-distinct-sources-w4

This commit is contained in:
dotCooCoo committed 2026-11-27 04:13:37 -08:00
commit 57dc20b171
16 files changed
+992 -63

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:
+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()));
+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"));
}
}
+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]);
}
}
+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")
}
+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();
+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]
+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();
+54 -5
View File
@@ -259,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.
@@ -269,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 {
@@ -337,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}`"))?;
@@ -376,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)
}
@@ -3293,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"]}));
+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,
+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());