Merge main into fix/properties-corner-commit

This commit is contained in:
dotCooCoo committed 2026-11-27 05:50:13 -08:00
commit 807cd1c879
98 files changed
+5171 -411

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:
+1
View File
@@ -97,6 +97,7 @@ mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES;
mod swatch;
pub mod swatchlib;
pub(crate) mod symboledit;
+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(),
+16 -8
View File
@@ -8,6 +8,8 @@
//! editing one adds a copy to the document under the default's name, and from then on that copy is
//! the filter of that name. Deleting the copy lists the default again.
use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, Document, SvgFilter};
use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter};
@@ -17,7 +19,7 @@ use super::fileio::{absolute_path, read_file_head};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param};
/// The largest SVG file Import SVG Filter reads.
const MAX_IMPORT_BYTES: usize = 16 << 20;
pub const MAX_IMPORT_BYTES: usize = 16 << 20;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -53,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import SVG Filter…",
[],
None,
"{path?|svg?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
"{path?|svg?|dataBase64?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters), SVG text or base64-encoded file bytes to the document's SVG filters, as one undo step; file bytes keep their UTF-8, BOM-marked UTF-16 or declared ISO 8859-1 encoding. A filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
has_doc,
import
),
@@ -197,13 +199,19 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
}
/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`.
fn import_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) {
/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. Inline SVG borrows its UTF-8 bytes.
fn import_bytes<'a>(p: &'a Value, cmd: &str) -> Result<Cow<'a, [u8]>> {
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?, text_param(p, "dataBase64", cmd)?) {
// One byte past the cap is enough to refuse the file below.
(Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?,
(None, Some(svg)) => svg.as_bytes().to_vec(),
_ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")),
(Some(path), _, _) => Cow::Owned(read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?),
(None, Some(svg), _) => Cow::Borrowed(svg.as_bytes()),
(None, None, Some(encoded)) => {
if vectorcraft_format::base64_decoded_len(encoded) > MAX_IMPORT_BYTES as u64 {
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
}
Cow::Owned(vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))?)
}
_ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")),
};
if bytes.len() > MAX_IMPORT_BYTES {
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
+33
View File
@@ -34,6 +34,39 @@ fn names(s: &mut Session) -> Vec<String> {
const BLUR: &str = r#"<filter id="Soft"><feGaussianBlur stdDeviation="2"/></filter>"#;
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
#[test]
fn byte_import_keeps_svg_encodings_and_uses_one_undo_step() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><filter id="café"><feOffset dx="3"/></filter></svg>"#;
let utf16: Vec<u8> = [0xff, 0xfe].into_iter().chain(svg.encode_utf16().flat_map(u16::to_le_bytes)).collect();
let latin1: Vec<u8> = format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>{svg}").chars().map(|c| c as u8).collect();
for bytes in [svg.as_bytes().to_vec(), utf16, latin1] {
let mut s = session();
let out = run(&mut s, "svgFilter.import", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)}));
assert_eq!(out["added"], json!(["café"]));
assert_eq!(names(&mut s), ["café"]);
assert_eq!(steps(&s), 1);
run(&mut s, "edit.undo", json!({}));
assert!(names(&mut s).is_empty());
}
}
#[test]
fn byte_import_refuses_invalid_oversized_and_compressed_files_without_an_edit() {
let mut s = session();
assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": "!"})).contains("dataBase64"));
assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": 3})).contains("must be a string"));
let mut inline = "é".repeat(8 << 20);
inline.push(' ');
assert!(err(&mut s, "svgFilter.import", json!({"svg": inline})).contains("larger than 16777216 bytes"));
assert!(names(&mut s).is_empty());
assert_eq!(steps(&s), 0);
for bytes in [vec![0xff], vec![b' '; (16 << 20) + 1], vectorcraft_svg::compress("<svg/>")] {
assert!(s.execute("svgFilter.import", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).is_err());
assert!(names(&mut s).is_empty());
assert_eq!(steps(&s), 0);
}
}
#[test]
fn filters_are_defined_edited_and_deleted_in_one_undo_step_each() {
let mut s = session();
+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();
+9 -2
View File
@@ -353,7 +353,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
}
Payload::Style(_) => Ok(()),
Payload::Panel(drag @ PanelDrag::Paint { params, paint, .. }) if !params.is_null() => {
Payload::Panel(drag @ PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => {
if let Some(color) = paint.color()
&& crate::panels::proxy_cmd(app, false) == "paint.setFill"
&& let Some((id, points)) = selected_mesh_drop(app, at, zoom)
@@ -362,7 +362,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
return run(app, "object.mesh.setPointColor", params);
}
let Some(hit) = hit() else { return Ok(()) };
let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) else { return Ok(()) };
let destination = app.session.active().map(|st| st.uid);
if rows.as_ref().is_some_and(|rows| !rows.unlinked_process_color && destination.is_some_and(|uid| uid != rows.document))
&& paint.color().is_some()
&& !paint.is_registration()
{
return Err(tl!("A linked color swatch can only be applied in its own document.").into());
}
let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) };
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
+57
View File
@@ -331,6 +331,63 @@ fn a_swatch_drag_keeps_its_color_after_next_document() {
assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source);
}
#[test]
fn linked_swatch_drops_stay_in_their_source_document() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::runtime::drag;
use egui::{Key, Modifiers};
for spot in [false, true] {
for (different_drawing, same_name) in [(false, false), (true, false), (true, true)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let name = "Shared Swatch";
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap();
if different_drawing {
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
}
if same_name {
app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).unwrap();
}
let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
let destination = app.session.active().unwrap().uid;
if different_drawing {
app.run("window.previousDocument", json!({})).unwrap();
}
let mut panel = Panel::new(app, |app, ui| {
app.sync_views();
ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| {
crate::panels::swatches::show(app, ui);
});
canvas::show(app, ui);
});
let label = "Shared Swatch, #ff0000";
let from = panel.rect(label).center();
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
panel.drag_hold_role(label, Role::LIST_ITEM, to - from);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the Swatches row starts a paint drag");
if different_drawing {
panel.key(Key::F6, Modifiers::COMMAND);
}
assert_eq!(panel.app().session.active().unwrap().uid, destination);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the drag stays active");
panel.release();
let app = panel.app();
let doc = &app.session.active().unwrap().doc;
let fill = doc.node(target).unwrap().appearance.fill_paint();
if different_drawing {
assert_eq!(fill, Paint::solid(Color::rgb8(0, 255, 0)), "the destination fill stays unchanged");
assert_eq!(app.ui.status, "A linked color swatch can only be applied in its own document.");
assert_eq!(doc.swatch(name).and_then(|s| s.paint.color()), same_name.then_some(Color::rgb8(0, 0, 255)));
} else {
assert_eq!(fill, doc.tint_paint(name, 1.0).unwrap(), "the fill remains linked to its swatch");
}
}
}
}
#[test]
fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() {
use vectorcraft_doc::GradientMesh;
+10 -2
View File
@@ -9,6 +9,7 @@ use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::menu::Menu;
use craft::ui::pickers::{Select, SelectLook};
use craft::ui::runtime::env::Env;
use craft::ui::style::TypeRole;
use craft::ui::text::ZoomField;
@@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
let busy = busy_labels(app);
let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false);
let mut invalid_zoom = None;
// The readouts end the bar, the pointer's position and then the timings; a narrow bar leaves out the timings
// first, then the position, before the message.
let readouts = |ui: &mut Ui, _: &mut BodyCx<'_>| {
@@ -73,8 +75,11 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui));
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) {
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print));
if let Some(zoom) = zoom.inner {
if let Some(view) = zoom.view.committed() {
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print));
}
invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui)));
}
Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| {
// Entries are keyed by index: an angle is not a hashable value.
@@ -156,6 +161,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
if let Some(message) = invalid_zoom {
app.status(message);
}
}
/// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first
+7 -3
View File
@@ -164,7 +164,7 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, Strin
/// with the values it opened with. OK reaches [`ok`] once the dialog's own rows accept it.
fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Option<&[&str]>) -> Result<Value, String> {
let source = app.session.active().ok_or("no document open")?;
let document = source.uid;
let (document, reverts) = (source.uid, source.reverts);
let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default();
let object = object_keys.is_some();
let ctx = app.ui_ctx.clone().ok_or("no window")?;
@@ -195,8 +195,12 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
.held_ok();
app.ui.brush_options = Some(
host::open_held(app, dialog, move |app, result: &ParamResult| {
if !object && app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to edit its brush").into());
match app.session.active().filter(|st| st.uid == document) {
Some(source) if source.reverts != reverts => {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()),
_ => {}
}
ok(app, result)
})
@@ -135,7 +135,7 @@ pub(crate) struct BulletsDialog {
/// The preview from the opening drawing and the interaction that owns its undo snapshot.
pub(crate) struct Preview {
document: u64,
document: (u64, u64),
live: LivePreview,
selection: Option<Weak<ArtworkSelection>>,
}
@@ -144,13 +144,13 @@ impl Preview {
fn owns_interaction(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
(state.uid, state.reverts) == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return };
let Some(state) = app.session.active().filter(|state| (state.uid, state.reverts) == self.document) else { return };
if !self.owns_interaction(app) {
self.live = LivePreview::default();
self.selection = None;
@@ -175,8 +175,11 @@ impl Preview {
}
return Ok(());
}
if app.session.active().is_none_or(|state| state.uid != self.document) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document.0) else {
return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned());
};
if state.reverts != self.document.1 {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if app.session.in_interaction() && !self.owns_interaction(app) {
return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned());
@@ -211,7 +214,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?),
};
crate::panels::character::text_style(app).ok_or("select some type first")?;
let document = app.session.active().ok_or("no document")?.uid;
let active = app.session.active().ok_or("no document")?;
let document = (active.uid, active.reverts);
// A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own.
if let Some(old) = app.bullets_preview.take() {
old.cancel(app);
@@ -617,7 +621,7 @@ impl StackDialog for BulletsDialog {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some(host) = app.dialogs() else { return };
let Some(mut preview) = app.bullets_preview.take() else { return };
let active_document = app.session.active().is_some_and(|state| state.uid == preview.document);
let active_document = app.session.active().is_some_and(|state| (state.uid, state.reverts) == preview.document);
let lengths = crate::canvas::general_lengths(app);
let Some((fields, answer)) = host.with(|h| {
h.get_mut::<BulletsDialog>().map(|d| {
@@ -804,6 +808,36 @@ mod tests {
assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic)));
}
#[test]
fn bullets_preview_and_ok_leave_restored_paragraphs_unchanged() {
let (mut app, id) = app();
let dir = vectorcraft_testkit::TempDir::new("bullets-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 saved = paras(&app, id);
app.run("file.saveAs", json!({"path": dir.join("Paragraphs.vectorcraft")})).unwrap();
app.run("text.setFormat", json!({"ids": [id], "leftIndent": 19})).unwrap();
let drawing = app.session.active().unwrap();
let (uid, reverts) = (drawing.uid, drawing.reverts);
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
frame(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
let undo = restored.history.undo.len();
frame(&mut app);
assert_eq!(paras(&app, id), saved);
assert!(!app.session.in_interaction());
press_ok(&mut app);
assert!(with_dialog(&app, |dialog| matches!(dialog.held.state(), Some(HeldOk::Refused(_)))));
assert_eq!(paras(&app, id), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
#[test]
fn bullets_cancel_keeps_the_other_drawings_pending_edit() {
let (mut app, id) = app();
+124 -14
View File
@@ -4,7 +4,7 @@
//! and the pump that runs each action against the document.
//!
//! The walk's state:
//! - `doc`: uid of the document it started on; another active document ends it
//! - `doc` and `reverts`: the drawing contents it started on; switching or reverting ends it
//! - `ids`: object IDs checked (None: entire document; Some(empty): nothing)
//! - `layer`: the one object checked while the dialog's Check All Layers is off
//! - `skipped`: `(node_id, start, word)` skipped by Ignore, which Change All leaves alone
@@ -43,6 +43,8 @@ type Word = (u64, usize, usize, String, String);
pub(crate) struct SpellingWalk {
/// Uid of the document the walk started on.
doc: u64,
/// File Revert generation of the document the walk started on.
reverts: u64,
/// The selected objects; None is the whole document, which Some(empty) is not.
ids: Option<Vec<u64>>,
/// The one object checked while Check All Layers is off.
@@ -66,23 +68,28 @@ fn start(app: &mut VectorcraftApp) -> Result<SpellingWalk, String> {
if app.session.active().is_none() {
return Err("no document".into());
}
let (doc, ids) = {
let (doc, reverts, ids) = {
let st = app.session.doc().map_err(|e| e.to_string())?;
// The selection (groups too: the check goes through the type inside them), or, with
// nothing selected, every visible, unlocked type object (the check's default).
let selected: Vec<u64> = st.selection.objects.iter().map(|n| n.0).collect();
(st.uid, (!selected.is_empty()).then_some(selected))
(st.uid, st.reverts, (!selected.is_empty()).then_some(selected))
};
let mut w = SpellingWalk { doc, ids, ..Default::default() };
let mut w = SpellingWalk { doc, reverts, ids, ..Default::default() };
advance(app, &mut w, None, 1)?;
Ok(w)
}
/// 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 => {
@@ -109,7 +116,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
return;
}
if check_doc_uid(app, &w).is_err() {
if check_opening_drawing(app, &w).is_err() {
dialogs.with(|host| host.cancel::<CheckSpellingDialog>(ctx));
return;
}
@@ -417,17 +424,17 @@ fn shown_word(app: &VectorcraftApp, w: &SpellingWalk) -> Option<(u64, usize, usi
Some((*id, *start, *end, still_there))
}
/// Fails when the active document is not the one the walk started on.
fn check_doc_uid(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> {
if app.session.active().map(|st| st.uid) != Some(w.doc) {
return Err("the document was switched".into());
/// Fails when the active drawing's contents are not the ones the walk started on.
fn check_opening_drawing(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> {
if !app.session.active().is_some_and(|st| st.uid == w.doc && st.reverts == w.reverts) {
return Err("the document was switched or reverted".into());
}
Ok(())
}
/// The word shown, when the walk is still going and on the walk's document.
fn shown_text(app: &VectorcraftApp, w: &SpellingWalk) -> Result<Option<String>, String> {
check_doc_uid(app, w)?;
check_opening_drawing(app, w)?;
Ok(w.shown.as_ref().map(|s| s.3.clone()))
}
@@ -969,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();
@@ -1112,13 +1160,75 @@ mod tests {
begin(&mut app);
// PLAN: the pump's close-on-switch needs the window host fixture of the hosted-dialog
// tests; this drives the guard the pump calls (`check_doc_uid`) through the walk's steps.
// tests; this drives the guard the pump calls (`check_opening_drawing`) through the walk's steps.
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let mut w = app.spelling.take().unwrap();
assert!(super::check_doc_uid(&app, &w).is_err());
assert!(super::check_opening_drawing(&app, &w).is_err());
assert!(super::ignore(&mut app, &mut w).is_err(), "no step runs on another document");
}
#[test]
fn queued_spelling_changes_leave_reverted_text_unchanged() {
use crate::tests::panel_harness::Panel;
use craft::ui::dialog::StackDialog as _;
// The host files the real button's action; the test decides when the app consumes it.
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
}
let _dictionary = crate::testing::custom_dictionary();
for button in ["Change", "Change All"] {
let mut app = app();
let saved = format!("{WORD_A} saved");
let id = text(&mut app, 50.0, &saved);
app.run("select.none", json!({})).unwrap();
app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string())));
app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|error| error.to_string())));
let dir = vectorcraft_testkit::TempDir::new("spelling-revert");
app.run("file.saveAs", json!({"path": dir.join("Spelling.vectorcraft")})).unwrap();
let state = app.session.active().unwrap();
let (uid, reverts) = (state.uid, state.reverts);
app.run("text.editRange", json!({"id": id, "start": saved.len(), "end": saved.len(), "insert": " draft"})).unwrap();
let mut panel = Panel::new(app, draw);
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
let ctx = panel.ctx().clone();
let set_replacement = |app: &VectorcraftApp| {
app.dialogs().unwrap().with(|host| {
let dialog = host.get::<super::CheckSpellingDialog>().unwrap().id();
host.set_json_field(&ctx, dialog, "changeTo", json!("fixed")).unwrap();
});
};
set_replacement(&panel.app());
panel.click(button);
assert_eq!(plain(&panel.app(), id), format!("{saved} draft"), "the action is still queued");
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
let undo = {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
assert_eq!(plain(&app, id), saved, "the same word and local ID were reloaded from the native file");
state.history.undo.len()
};
super::pump(&mut panel.app(), &ctx);
assert_eq!(plain(&panel.app(), id), saved, "{button} from the old walk must not edit restored text");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
assert!(panel.app().spelling.is_none(), "the reverted walk is retired");
assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::<super::CheckSpellingDialog>()));
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
set_replacement(&panel.app());
panel.click(button);
super::pump(&mut panel.app(), &ctx);
assert_eq!(plain(&panel.app(), id), "fixed saved", "a fresh check can still change the restored text");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
}
}
#[test]
fn check_spelling_ignores_uneditable_text() {
let _dictionary = crate::testing::custom_dictionary();
+8 -8
View File
@@ -160,7 +160,7 @@ fn slot(dialogs: &mut ColorDialogs) -> &mut Option<Open> {
/// Open the dialog with every channel at 0, adjusting fills and strokes.
pub fn open(app: &mut VectorcraftApp) {
ADJUST.open(app);
Adjust { label: tl!(ADJUST.label), ..ADJUST }.open(app);
}
/// Previews the open dialog; one line of `dialogs::host::pump`.
@@ -217,22 +217,22 @@ fn track(key: &str, x: f32) -> Srgba {
fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response {
super::form::stacked(ui, fields, |ui, fields| {
for (key, label) in mode(fields).channels {
percent_row(ui, fields, key, label, |x| track(key, x));
percent_row(ui, fields, key, tl!(label), |x| track(key, x));
}
})
}
fn rows() -> Vec<Param> {
let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(m.label))).collect();
let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(tl!(m.label)))).collect();
let with_model = MODES.iter().map(|m| m.id).filter(|id| *id != GLOBAL);
vec![
Param::new("mode", "Color Mode", ParamKind::choice(modes, Some("rgb".to_owned()))),
Param::new("convert", "Convert", ParamKind::bool(false)).enabled_when_in("mode", with_model),
Param::read_only_text("note", "", "Shifts the tints of global and spot colors; other colors stay.").visible_when("mode", GLOBAL),
Param::new("mode", tl!("Color Mode"), ParamKind::choice(modes, Some("rgb".to_owned()))),
Param::new("convert", tl!("Convert"), ParamKind::bool(false)).enabled_when_in("mode", with_model),
Param::read_only_text("note", "", tl!("Shifts the tints of global and spot colors; other colors stay.")).visible_when("mode", GLOBAL),
Param::custom("channels", "Channels", channels).companions(channel_keys()),
Param::section("Adjust Options"),
Param::new("fill", "Fill", ParamKind::bool(true)),
Param::new("stroke", "Stroke", ParamKind::bool(true)),
Param::new("fill", tl!("Fill"), ParamKind::bool(true)),
Param::new("stroke", tl!("Stroke"), ParamKind::bool(true)),
]
}
@@ -3,7 +3,7 @@
//! as they are.
//!
//! Fields: `name`. The group being renamed (its name, its place in the list of color groups, the names of
//! its swatches and the uid of its document when the dialog opened) is kept by the dialog's OK.
//! its swatches and the document's identity and revert generation at opening) is kept by the dialog's OK.
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult};
use serde_json::{Value, json};
@@ -16,8 +16,9 @@ pub const KIND: &str = "colorGroupOptions";
/// A color group as the dialog found it: what tells it apart from the others, since color groups carry nothing else.
struct Identity {
/// The uid of the document the dialog opened on.
/// The document and its saved-content generation when the dialog opened.
doc: u64,
reverts: u64,
/// The group's place in the document's list of color groups.
at: usize,
/// The group's name.
@@ -40,14 +41,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let at = st.doc.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| format!("no colour group `{group}`"))?;
let g = &st.doc.swatch_groups[at];
let identity = Identity { doc: st.uid, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() };
let identity =
Identity { doc: st.uid, reverts: st.reverts, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() };
let mut fields = DialogFields::new();
fields.set("name", g.name.as_str());
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let rows = vec![Param::new("name", field_label(tl!("Name:")), ParamKind::text(""))];
let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
// Another document or group: it closes as Cancel does and renames nothing.
// A different document, a revert, or a different group closes the draft without renaming.
if !same_group(app, &identity) {
return Ok(());
}
@@ -60,9 +62,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
/// Whether the dialog's group is still in its document, at the place in the list, under the name
/// and with the swatches it opened with, and that document is the active one.
/// and with the swatches it opened with, and the document is still active and has not been reverted.
fn same_group(app: &VectorcraftApp, identity: &Identity) -> bool {
let Some(st) = app.session.active().filter(|st| st.uid == identity.doc) else { return false };
let Some(st) = app.session.active().filter(|st| st.uid == identity.doc && st.reverts == identity.reverts) else { return false };
st.doc
.swatch_groups
.get(identity.at)
@@ -101,6 +103,42 @@ mod tests {
app.session.active().unwrap().history.undo.len()
}
#[test]
fn an_old_rename_draft_keeps_the_color_group_restored_by_revert() {
let (ctx, mut app) = app();
let dir = vectorcraft_testkit::TempDir::new("color-group-options-revert");
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": dir.join("colors.vectorcraft")})).unwrap();
let color = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatch("Bright Red").unwrap().paint.color();
let saved_color = color(&app);
let saved_groups = groups(&app);
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("swatch.edit", json!({"name": "Bright Red", "color": "#1784ca"})).unwrap();
assert_ne!(color(&app), saved_color);
app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap();
let id = dialog_id(KIND);
app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "name", json!("Old palette draft"))).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
assert_eq!(color(&app), saved_color);
assert_eq!(groups(&app), saved_groups);
let undo = undo_len(&app);
crate::tests::picks::answer_dialog(&mut app, id, &[], true);
assert_eq!(groups(&app), saved_groups, "old Color Group Options must leave the restored group named Brights");
assert_eq!(color(&app), saved_color);
assert_eq!(undo_len(&app), undo);
app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap();
ok(&mut app, &ctx, "Restored palette");
assert!(groups(&app).iter().any(|name| name == "Restored palette"));
assert_eq!(undo_len(&app), undo + 1);
}
/// Whether the dialog is still open.
fn is_open(app: &VectorcraftApp) -> bool {
app.dialogs().unwrap().with(|h| h.get_by_id::<craft::ui::patterns::form_dialogs::HostedParamDialog>(dialog_id(KIND)).is_some())
+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),
}
}
+146 -8
View File
@@ -55,10 +55,12 @@ type Info = Map<String, Value>;
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?;
let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?;
let document = app.session.active().ok_or("no document")?.uid;
let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| {
if !app.session.active().is_some_and(|active| active.uid == *document) {
return Err(tl!("File Info can only change the document it was opened for.").to_owned());
let source = app.session.active().ok_or("no document")?;
let document = (source.uid, source.reverts);
let ok = |app: &mut VectorcraftApp, ((uid, generation), fields): &((u64, u64), Info)| {
let source = app.session.active().filter(|st| st.uid == *uid).ok_or(tl!("File Info can only change the document it was opened for."))?;
if source.reverts != *generation {
return Err(tl!("Reopen File Info after reverting the drawing").into());
}
app.run("file.info", Value::Object(fields.clone())).map(|_| ())
};
@@ -113,6 +115,8 @@ enum Request {
SaveTo(PathBuf),
/// A browser picker returned a template larger than the import limit.
TemplateTooLarge,
/// Download the current draft as a template, without requiring a filesystem path.
Download,
/// Merge the template `source` into the fields as `mode` says.
Import { source: Info, mode: &'static str },
}
@@ -136,6 +140,7 @@ enum Chosen {
#[derive(Default)]
struct Templates {
can_save: bool,
web_save: bool,
can_open: bool,
has_folder: bool,
/// The metadata templates folder, where the save pick starts, once listed.
@@ -221,6 +226,7 @@ impl Templates {
}
});
match chosen {
Some(Chosen::Pick(Pick::Save)) if self.web_save => self.requests.push(Request::Download),
Some(Chosen::Pick(kind)) => self.pick(cx, kind, title),
Some(Chosen::Template(file)) => wait_for_template(import, file),
Some(Chosen::Folder) => self.requests.push(Request::Folder),
@@ -232,7 +238,7 @@ impl Templates {
/// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app.
pub(crate) struct FileInfoDialog {
id: DialogId,
document: u64,
document: (u64, u64),
open: bool,
/// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]).
hold: bool,
@@ -248,7 +254,7 @@ pub(crate) struct FileInfoDialog {
}
impl FileInfoDialog {
fn new(document: u64, value: Info) -> Self {
fn new(document: (u64, u64), value: Info) -> Self {
FileInfoDialog {
id: dialog_id(KEY),
document,
@@ -390,7 +396,7 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option<bool> {
}
impl HoldsOk for FileInfoDialog {
type Answer = (u64, Info);
type Answer = ((u64, u64), Info);
fn held_ok(mut self) -> Self {
self.hold = true;
@@ -567,6 +573,26 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res
save(app).map(|_| ())
}
/// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft.
fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> {
let title = text_of(&fields, "title");
let stem = vectorcraft_engine::cmd::library::file_stem_for(if title.trim().is_empty() { "Metadata" } else { &title });
let name = format!("{stem}.{XMP_EXT}");
let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?;
let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec();
let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]);
file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| {
match picked {
Picked::Downloaded(name) => app.status(format!("Saved {name}")),
Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())),
Picked::Failed(error) => return Err(error),
_ => {}
}
Ok(Value::Null)
});
Ok(())
}
/// Merge the template `source` names into the dialog's fields as `mode` says.
fn import(app: &mut VectorcraftApp, d: &mut FileInfoDialog, source: Info, mode: &str) -> Result<(), String> {
let mut p = Value::Object(source);
@@ -587,10 +613,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
// PLAN: fl.A9 lists no `file_info::pump`; the Templates menu needs the session, so hub-w2 adds this line to `dialogs::host::pump`.
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KEY);
let (can_save, can_open, has_folder) = (file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app));
let web_save = app.ui_ctx.as_ref().and_then(Host::try_of_ctx).is_some_and(|host| host.files().browser_saves());
let (can_save, can_open, has_folder) =
(web_save || file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app));
let requests = dialogs.with(|host| {
host.get_mut_by_id::<FileInfoDialog>(id).map(|d| {
d.templates.can_save = can_save;
d.templates.web_save = web_save;
d.templates.can_open = can_open;
d.templates.has_folder = has_folder;
d.take_requests()
@@ -614,6 +643,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
None => Ok(()),
},
Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()),
Request::Download => match dialogs.with(|host| host.get_by_id::<FileInfoDialog>(id).map(FileInfoDialog::filed_fields)) {
Some(fields) => download_template(app, fields),
None => Ok(()),
},
Request::Import { source, mode } => {
dialogs.with(|host| host.get_mut_by_id::<FileInfoDialog>(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(()))
}
@@ -652,6 +685,42 @@ mod tests {
app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog_id(KEY), field, value))
}
#[test]
fn stale_file_info_cannot_replace_metadata_restored_by_revert() {
let mut app = windowed();
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 dir = vectorcraft_testkit::TempDir::new("file-info-metadata-revert");
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("file.info", json!({"title": "Saved Title"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("metadata.vectorcraft")})).unwrap();
let saved = &app.session.active().unwrap().doc;
let (saved_title, saved_metadata) = (saved.info_title().to_owned(), saved.metadata.clone());
app.run("file.info", json!({"title": "Unsaved Title"})).unwrap();
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "title", json!("Old Draft")).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reverted = app.session.active().unwrap();
assert_eq!(reverted.uid, uid);
assert_ne!(reverted.reverts, generation);
assert_eq!(reverted.doc.info_title(), saved_title);
assert_eq!(reverted.doc.metadata, saved_metadata);
let undo = reverted.history.undo.len();
crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[], true);
let reverted = app.session.active().unwrap();
assert_eq!(reverted.doc.info_title(), saved_title);
assert_eq!(reverted.doc.metadata, saved_metadata);
assert_eq!(reverted.history.undo.len(), undo);
assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog_id(KEY))), Some(HeldOk::Refused(_))));
app.run("ui.fileInfoDialog", json!({})).unwrap();
crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[("title", json!("Fresh Title"))], true);
assert_eq!(app.run("file.info", json!({})).unwrap()["title"], json!("Fresh Title"));
}
/// Presses OK: the dialog files its fields, and the frames after it run the app's OK and close an accepted dialog
/// (a second OK would file a refused answer again). Whether it closed.
fn press_ok(app: &mut VectorcraftApp) -> bool {
@@ -662,6 +731,75 @@ mod tests {
app.dialogs().unwrap().with(|host| host.held_state(dialog_id(KEY)))
}
#[test]
fn browser_template_saves_export_the_draft_and_preserve_it_on_cancel_or_failure() {
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use craft::host::{Picked, ScriptedFiles};
use craft::ui::testing::{Fixture, Room};
let mut app = windowed();
let files = Arc::new(ScriptedFiles::held().in_browser());
crate::tests::picks::install_files(&mut app, files.clone());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let original = app.session.active().unwrap().doc.metadata.clone();
let app = Rc::new(RefCell::new(app));
let shown = Rc::clone(&app);
let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui));
fixture.in_room(Room::Window);
let ctx = fixture.ctx().clone();
{
let mut app = app.borrow_mut();
app.ui_ctx = Some(ctx.clone());
craft::host::Host::clone(&app.host).install(&ctx);
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "title", json!("Draft Template")).unwrap();
set(&app, "author", json!("Ada")).unwrap();
set(&app, PENDING, json!("print")).unwrap();
}
fixture.settle();
let draft = with_dialog(&app.borrow(), |d| d.filed_fields()).unwrap();
for answer in [
Picked::Saved { path: "draft.xmp".into(), file_type: None },
Picked::Downloaded("draft.xmp".into()),
Picked::Cancelled,
Picked::Failed("download refused".into()),
] {
let before = files.requests().len();
let menu = fixture.by_label("Templates").expect("the Templates menu");
fixture.click(&menu).settle();
let save = fixture.by_label("Save Metadata Template…").expect("browser hosts can save the draft");
fixture.click(&save).settle();
assert_eq!(files.requests().len(), before + 1, "one save per action");
let request = files.requests().pop().unwrap();
assert_eq!(request.kind, craft::host::PickKind::Save);
assert!(request.file_name.as_deref().is_some_and(|name| name.ends_with(".xmp")));
app.borrow_mut().ui.status = "before the answer".into();
assert!(files.answer(answer.clone()).is_some());
crate::file_asks::poll(&mut app.borrow_mut());
fixture.settle();
let app = app.borrow();
match answer {
Picked::Cancelled => assert_eq!(app.ui.status, "before the answer"),
Picked::Failed(_) => assert_eq!(app.ui.status, "download refused"),
_ => assert!(app.ui.status.starts_with("Saved ")),
}
assert_eq!(with_dialog(&app, |d| d.filed_fields()).unwrap(), draft);
let document = app.session.active().unwrap();
assert_eq!(document.doc.metadata, original);
assert!(document.history.undo.is_empty());
assert!(document.path.is_none(), "saving a template does not save the drawing");
}
let xmp = files.file(Path::new("draft.xmp")).expect("the service received the XMP bytes");
let template = vectorcraft_pdf::read_template(&xmp).expect("the saved draft is a metadata template");
assert_eq!(template.title.as_deref(), Some("Draft Template"));
assert_eq!(template.author.as_deref(), Some("Ada"));
assert_eq!(template.keywords, Some(vec!["print".into()]));
}
#[test]
fn file_info_draws_and_ok_is_one_undo_step() {
let mut app = windowed();
+34 -3
View File
@@ -42,7 +42,7 @@ pub(crate) struct Open {
/// The hosted dialog.
id: DialogId,
opening: Arc<()>,
document: Option<u64>,
document: Option<(u64, u64)>,
/// Where a click opened it, to draw a flare there on OK.
click: Option<Point>,
/// The selected flares (ids) and the settings the dialog opened with, to change them on OK.
@@ -55,7 +55,7 @@ const PREVIEW_LABEL: &str = "Flare";
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
self.preview.is_none() || app.session.active().map(|st| st.uid) == self.document
self.preview.is_none() || app.session.active().map(|st| (st.uid, st.reverts)) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
@@ -132,7 +132,7 @@ pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone())
});
let document = app.session.active().map(|st| st.uid);
let document = app.session.active().map(|st| (st.uid, st.reverts));
match open_held_with(app, dialog, ok, held) {
Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }),
None => app.status("no window"),
@@ -301,6 +301,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let open = app.object_dialogs.flare.as_ref().ok_or("the Flare Tool Options dialog is gone")?;
if !open.on_original_drawing(app) {
if app.session.active().map(|st| st.uid) == open.document.map(|(uid, _)| uid) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
return Err(tl!("Return to the original drawing to place or edit the flare").into());
}
if open.preview.is_some() && other_preview(app) {
@@ -544,4 +547,32 @@ mod tests {
let parts = flare_parts(&app);
assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (10, true), "{parts:?}");
}
#[test]
fn a_pending_flare_does_not_draw_on_restored_art() {
let mut app = app();
let dir = vectorcraft_testkit::TempDir::new("flare-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("shape.ellipse", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len();
open(&mut app, Some(Point::new(100.0, 110.0)));
pump(&mut app);
assert_eq!(count(&app), 2, "the original art and the flare preview");
app.run("file.revert", json!({"confirmed": true})).unwrap();
pump(&mut app);
assert_eq!(count(&app), 0, "the old preview leaves the restored art alone");
let options = app.session.tool_options_of("flare");
press_ok(&mut app);
assert_eq!(count(&app), 0, "the old approval leaves the restored art alone");
assert_eq!(app.session.tool_options_of("flare"), options);
assert!(app.object_dialogs.flare.is_some());
press_cancel(&mut app);
open(&mut app, Some(Point::new(100.0, 110.0)));
press_ok(&mut app);
assert_eq!(count(&app), 1);
}
}
+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);
}
}
}
+321 -11
View File
@@ -16,17 +16,21 @@
use std::sync::Arc;
use craft::behavior::IconId;
use craft::color_ui::ui::{ColorPanel, ColorPanelLayout, ColorPanelOutput, ColorPanelShown, ColorPanelState, DropperButton, SwatchPalette};
use craft::color_ui::ui::{
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, SwatchPalette,
};
use craft::theme::Srgba;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::Segmented;
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, Entry, PopupKind, Show as _, ShowContainer as _, Trigger};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::notices::Notice;
use craft::ui::popover::Popover;
use craft::ui::runtime::env::{Label, UnitKind};
use craft::ui::runtime::env::{Env, Label, UnitKind};
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::text::NumberField;
use egui::{Pos2, Ui, vec2};
@@ -98,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 {
@@ -111,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);
}
}
}
@@ -231,6 +326,10 @@ struct Filed {
swatch: Option<(String, Color)>,
eyedropper: bool,
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.
@@ -247,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 {
@@ -260,6 +362,7 @@ impl GradientStopPopover {
feed: None,
set: PopoverFields::default(),
filed: Filed::default(),
own_mode: None,
}
}
@@ -286,6 +389,9 @@ impl StackDialog for GradientStopPopover {
.at_point(*at)
.close_on_enter(true)
.show(ui, |ui, _| body(ui, feed, tab, panel, filed));
if shown.inner == Some(true) {
return Some(DialogResult::Cancel);
}
match shown.output.closed {
Some(CloseReason::Enter) => self.confirm(ui.ctx()).map(DialogResult::Ok),
Some(_) => Some(DialogResult::Cancel),
@@ -336,7 +442,8 @@ impl StackDialog for GradientStopPopover {
/// The popover's body: the tabs and the eyedropper, the Color panel or the swatches, then opacity and location (a
/// point: spread). What the user edits is filed in `filed`.
fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) {
fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) -> bool {
let mut outside = false;
Stack::new().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let tabs = [
@@ -349,16 +456,25 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned();
filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true);
}
if *tab == Tab::Color {
let (closed, picked) = mode_menu(ui, &feed.shown, panel.mode);
outside |= closed;
filed.mode_command = picked.or(filed.mode_command);
}
});
match *tab {
// The Color panel edits the selected stop (or point) of the active gradient.
Tab::Color => {
let before = panel.mode;
filed.panels.push(
ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2])
.layout(ColorPanelLayout::FillStroke)
.shown(feed.shown.clone())
.show(ui),
);
if panel.mode != before {
filed.mode = Some(panel.mode);
}
}
Tab::Swatches => swatches(ui, feed, filed),
}
@@ -368,6 +484,30 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
*amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount);
});
});
outside
}
/// 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. 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),
ColorPanelShown::Tint(_) => words.tint.clone(),
_ => 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 {
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), picked)
}
/// Document swatches as tiles: a pick gives the stop (or point) that colour.
@@ -454,6 +594,9 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) {
(popover.at, popover.feed) = (at, Some(feed));
popover.panel = app.ui.color_panel;
// This panel edits the active stop/point, never the other paint behind the proxy.
popover.panel.background = false;
}
});
}
@@ -474,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);
}
@@ -498,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);
@@ -525,6 +697,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
// PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision).
crate::panels::color::apply_output(app, output);
}
if let Some(mode) = filed.mode {
let target = crate::panels::color::target_now(app);
crate::panels::color::set_mode(app, &target, mode);
}
if filed.eyedropper {
dialogs.with(|host| host.cancel_by_id(ctx, id));
crate::panels::gradient::stop_eyedropper(app);
@@ -537,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) {
@@ -761,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();
+88 -21
View File
@@ -51,6 +51,7 @@ use crate::file_asks::{self, Owner};
/// The dialog kind of Graph Data, the key of its dialog on the host.
pub const KIND: &str = "graphData";
const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet.";
const REVERTED_DOCUMENT: &str = "Reopen Graph Data after reverting the drawing.";
/// The sheet's size: a row of labels over a graph's categories, a column of labels before its
/// series; the least rows it shows.
@@ -71,13 +72,11 @@ const ROW_H: f32 = 19.0;
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The query fails without a graph selected, with the engine's own message.
let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?;
let document = app.session.active().ok_or("no document open")?.uid;
let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id)));
let scatter = graph.is_some_and(|(st, id)| {
st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter)
});
let id = graph.map(|(_, id)| id.0);
let dialog = GraphDataDialog::new(grid_from_data(&v), document, id, scatter, can_import(app));
let st = app.session.active().ok_or("no document open")?;
let graph = st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id));
let scatter = graph
.is_some_and(|id| st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter));
let dialog = GraphDataDialog::new(grid_from_data(&v), st.uid, st.reverts, graph.map(|id| id.0), scatter, can_import(app));
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
@@ -437,6 +436,7 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result<V
/// What the window asked of the app since the last [`pump`].
struct Asks {
document: u64,
reverts: u64,
graph: Option<u64>,
import_owner: Arc<()>,
apply: Option<Sheet>,
@@ -448,26 +448,29 @@ struct Asks {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let can = can_import(app);
let active = app.session.active().map(|doc| doc.uid);
let active = app.session.active().map(|doc| (doc.uid, doc.reverts));
let asked = dialogs.with(|host| {
host.get_mut::<GraphDataDialog>().map(|d| {
d.can_import = can;
if active == Some(d.document) {
if active == Some((d.document, d.reverts)) {
d.held.clear_refusal();
}
d.take_asks()
})
});
let Some(Asks { document, graph, import_owner, apply: filed, actions }) = asked else { return };
let same_document = active == Some(document);
let Some(Asks { document, reverts, graph, import_owner, apply: filed, actions }) = asked else { return };
let refusal = match active {
Some((uid, current_reverts)) if uid == document => (current_reverts != reverts).then_some(tl!(REVERTED_DOCUMENT)),
_ => Some(tl!(WRONG_DOCUMENT)),
};
if let Some(sheet) = filed {
let answer = if same_document {
let answer = if let Some(reason) = refusal {
Err(Label::from(reason))
} else {
if let Err(e) = apply(app, &sheet, graph) {
app.status(e);
}
Ok(())
} else {
Err(Label::from(tl!(WRONG_DOCUMENT)))
};
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|dialog| dialog.applied(answer)));
}
@@ -489,13 +492,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
move |app, picked| import(app, &owner, picked),
);
}
Action::Revert if !same_document => app.status(tl!(WRONG_DOCUMENT).to_owned()),
Action::Revert => match graph_grid(app, graph) {
Ok(grid) => {
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|d| d.replace(grid)));
Action::Revert => {
if let Some(reason) = refusal {
app.status(reason.to_owned());
} else {
match graph_grid(app, graph) {
Ok(grid) => {
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|d| d.replace(grid)));
}
Err(e) => app.status(e),
}
}
Err(e) => app.status(e),
},
}
}
}
}
@@ -675,6 +683,7 @@ pub(crate) struct GraphDataDialog {
state: GridState,
entry: Entry,
document: u64,
reverts: u64,
/// The graph the sheet opened on.
graph: Option<u64>,
scatter: bool,
@@ -687,7 +696,7 @@ pub(crate) struct GraphDataDialog {
impl GraphDataDialog {
/// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph.
fn new(grid: Grid, document: u64, graph: Option<u64>, scatter: bool, can_import: bool) -> Self {
fn new(grid: Grid, document: u64, reverts: u64, graph: Option<u64>, scatter: bool, can_import: bool) -> Self {
let sheet = Sheet { grid, ..Sheet::default() };
let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0);
let mut entry = Entry { text: String::new(), at: (0, 1) };
@@ -699,6 +708,7 @@ impl GraphDataDialog {
state,
entry,
document,
reverts,
graph,
scatter,
can_import,
@@ -712,6 +722,7 @@ impl GraphDataDialog {
fn take_asks(&mut self) -> Asks {
Asks {
document: self.document,
reverts: self.reverts,
graph: self.graph,
import_owner: self.import_owner.clone(),
apply: self.held.take(),
@@ -922,6 +933,62 @@ mod tests {
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected);
}
fn stale_sheet_after_file_revert(test: &str) -> (VectorcraftApp, u64, Value) {
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let (mut app, id) = app_with(",Original\nQ1,1", "column");
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-graph-data-revert-{}-{test}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
let saved = data(&mut app, id);
app.run("graph.setData", json!({"id": id, "series": ["Unsaved"], "categories": ["Q2"], "rows": [[3.0]]})).unwrap();
assert_ne!(data(&mut app, id), saved);
app.run("select.set", json!({"ids": [id]})).unwrap();
open(&mut app).unwrap();
set_field(&app, "grid", json!([["", "Draft"], ["Q2", "9"]])).unwrap();
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));
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(data(&mut app, id), saved, "the restored graph uses the same ID");
(app, id, saved)
}
#[test]
fn graph_data_after_file_revert_cannot_apply_the_old_draft() {
let (mut app, id, saved) = stale_sheet_after_file_revert("apply");
let undo = app.session.active().unwrap().history.undo.len();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_))));
app.run("select.set", json!({"ids": [id]})).unwrap();
open(&mut app).unwrap();
set_field(&app, "grid", json!([["", "Fresh"], ["Q3", "7"]])).unwrap();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id)["rows"], json!([[7.0]]));
}
#[test]
fn graph_data_after_file_revert_keeps_the_old_sheet_on_worksheet_revert() {
let (mut app, id, saved) = stale_sheet_after_file_revert("worksheet");
let draft = read(&app, |dialog| dialog.sheet.grid.clone());
edit(&app, |dialog| dialog.actions.push(Action::Revert));
pump(&mut app, &crate::testing::ui_context());
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft);
assert_eq!(data(&mut app, id), saved);
}
/// The app with the window drawn each frame as the shell draws it.
// PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself.
fn harness(app: VectorcraftApp) -> Harness {
+61 -9
View File
@@ -252,8 +252,11 @@ pub(crate) enum Answer {
impl Answer {
/// Runs the command; the refusal is its error.
fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> {
if !target.in_active_document(app) {
let Some(active) = app.session.active().filter(|active| active.uid == target.document.0) else {
return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog.")));
};
if active.reverts != target.document.1 {
return Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue.")));
}
let design = |d: &Option<DesignKey>| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) });
let (command, mut params) = match self {
@@ -281,21 +284,18 @@ impl Answer {
/// The graph and picked series the Column or Marker form opened for.
#[derive(Clone)]
struct GraphTarget {
document: u64,
document: (u64, u64),
graph: u64,
series: Vec<usize>,
}
impl GraphTarget {
fn selected(app: &VectorcraftApp) -> Result<Self, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let active = app.session.active().ok_or("no document open")?;
let document = (active.uid, active.reverts);
let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?;
Ok(Self { document, graph: selected.id.0, series: selected.series })
}
fn in_active_document(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|active| active.uid == self.document)
}
}
/// A loaded library's document, for the thumbnails of its designs.
@@ -409,7 +409,7 @@ pub(crate) struct GraphDesignDialog {
struct Work {
actions: Vec<Action>,
answer: Option<(Answer, GraphTarget)>,
document: Option<u64>,
document: Option<(u64, u64)>,
}
impl GraphDesignDialog {
@@ -854,7 +854,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
let answered = work.answer.map(|(answer, target)| answer.run(app, &target));
let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| active.uid == document));
let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| (active.uid, active.reverts) == document));
let lists = if same_document { Lists::read(app).ok() } else { None };
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<GraphDesignDialog>() {
@@ -956,6 +956,58 @@ mod tests {
}
}
fn a_graph_design_draft_after_file_revert(graph_kind: &str, command: &str) {
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let (mut app, ctx) = app_with_design();
select_graph(&mut app, graph_kind);
let graph = app.session.active().unwrap().selection.objects[0].0;
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-graph-design-revert-{}-{graph_kind}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [graph]})).unwrap();
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
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));
app.run("select.set", json!({"ids": [graph]})).unwrap();
let selected_design = |app: &mut VectorcraftApp| app.session.execute(command, &json!({"id": graph})).unwrap()["design"].clone();
assert_eq!(selected_design(&mut app), Value::Null);
let undo = app.session.active().unwrap().history.undo.len();
app.dialogs().unwrap().with(|host| host.confirm::<GraphDesignDialog>(&ctx));
super::pump(&mut app, &ctx);
assert_eq!(selected_design(&mut app), Value::Null, "the stale draft must leave the restored graph's design alone");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(&app)["selected"], "New Design", "the refused answer still shows the draft");
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
ok(&mut app, &ctx);
assert_eq!(selected_design(&mut app), "New Design", "a fresh draft applies to the restored graph");
}
#[test]
fn graph_column_draft_after_file_revert_leaves_the_restored_columns_alone() {
a_graph_design_draft_after_file_revert("column", "graph.column");
}
#[test]
fn graph_marker_draft_after_file_revert_leaves_the_restored_markers_alone() {
a_graph_design_draft_after_file_revert("line", "graph.marker");
}
#[test]
fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() {
for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] {
@@ -7,7 +7,8 @@
//! OK, not by a field, so a name another style has refuses the OK and keeps the dialog open.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::host;
@@ -15,8 +16,10 @@ use crate::VectorcraftApp;
/// The dialog kind of Graphic Style Options.
pub const KIND: &str = "graphicStyleOptions";
const OPENING: &str = "__opening";
/// What OK does with the name.
#[derive(Deserialize, Serialize)]
enum Target {
/// Name the style made from the selection.
New,
@@ -40,15 +43,24 @@ impl Target {
/// Open the dialog with `name` in its field; OK runs `target`.
fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let active = app.session.active().ok_or("no document open")?;
let mut fields = DialogFields::from_pairs([("name", name.clone())]);
fields.set(OPENING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts, "target": target})));
let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))];
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| {
let dialog = HostedParamDialog::command(&ctx, KIND, fields, move |fields| {
ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields))
});
// An `Err` (a name another style has) keeps the dialog open with the reason.
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
if !app.session.active().is_some_and(|active| active.uid == document) {
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let Some(FieldValue::Json(opening)) = result.fields.get(OPENING) else { return Err("the graphic style target is missing".into()) };
let document = opening["uid"].as_u64().ok_or("the graphic style target is missing")?;
let target = Target::deserialize(&opening["target"]).map_err(|e| e.to_string())?;
let active = app.session.active();
if active.is_some_and(|active| active.uid == document && Some(active.reverts) != opening["reverts"].as_u64()) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if !active.is_some_and(|active| active.uid == document) {
return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned());
}
target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ())
@@ -164,4 +176,45 @@ mod tests {
accept(&mut app, id);
assert!(names(&app).iter().any(|name| name == "Source style"));
}
#[test]
fn graphic_style_options_leave_restored_definitions_alone() {
for action in ["rename", "merge", "new"] {
let mut app = app();
let art = app.session.active().unwrap().selection.objects[0];
app.run("graphicStyle.new", json!({"name": "First"})).unwrap();
app.run("paint.setFill", json!({"ids": [art.0], "color": "#abcdef"})).unwrap();
app.run("graphicStyle.new", json!({"name": "Second"})).unwrap();
let saved = names(&app);
let dir = vectorcraft_testkit::TempDir::new("graphic-style-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("object.move", json!({"ids": [art.0], "dx": 10, "dy": 0})).unwrap();
let open_action = |app: &mut VectorcraftApp| match action {
"rename" => open(app, Some("First")),
"merge" => open_merge(app, vec!["First".into(), "Second".into()]),
_ => open(app, None),
};
open_action(&mut app).unwrap();
let id = options(&app);
set(&app, id, "name", json!("Draft Style"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [art.0]})).unwrap();
let steps = app.session.active().unwrap().history.undo.len();
accept(&mut app, id);
assert_eq!(names(&app), saved, "{action}");
assert_eq!(app.session.active().unwrap().history.undo.len(), steps);
assert_eq!(options(&app), id);
let ctx = app.ui_ctx.clone().unwrap();
app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id));
open_action(&mut app).unwrap();
let id = options(&app);
set(&app, id, "name", json!("Current Style"));
accept(&mut app, id);
assert!(names(&app).iter().any(|name| name == "Current Style"), "{action}");
}
}
}
+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]
+97 -10
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;
@@ -25,13 +26,22 @@ const PREVIEW_LABEL: &str = "Convert to Indexed Color";
pub(crate) struct Open {
document: u64,
reverts: u64,
opening: Arc<()>,
preview: LivePreview,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.uid == self.document)
self.check_drawing(app).is_ok()
}
fn check_drawing(&self, app: &VectorcraftApp) -> Result<(), &'static str> {
let st = app.session.active().filter(|st| st.uid == self.document).ok_or(tl!("Return to the original drawing to convert its images"))?;
if st.reverts != self.reverts {
return Err(tl!("Reopen Convert to Indexed Color after reverting the drawing"));
}
Ok(())
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
@@ -77,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`.
@@ -86,7 +96,7 @@ pub fn open(app: &mut VectorcraftApp) {
app.status("no window".to_string());
return;
};
let Some(document) = app.session.active().map(|st| st.uid) else {
let Some((document, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else {
app.status(tl!("Open a drawing to convert its images"));
return;
};
@@ -98,9 +108,7 @@ pub fn open(app: &mut VectorcraftApp) {
let cancelled = Arc::clone(&opening);
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let open = app.object_dialogs.indexed.as_ref().ok_or("the Indexed Color dialog is gone")?;
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to convert its images").into());
}
open.check_drawing(app)?;
if other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
@@ -123,7 +131,7 @@ pub fn open(app: &mut VectorcraftApp) {
}
});
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_some() {
app.object_dialogs.indexed = Some(Open { document, opening, preview: LivePreview::default() });
app.object_dialogs.indexed = Some(Open { document, reverts, opening, preview: LivePreview::default() });
} else {
app.status("no window".to_string());
}
@@ -180,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();
@@ -199,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,
@@ -219,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()));
@@ -265,4 +318,38 @@ mod tests {
crate::dialogs::host::pump(&mut app, &ctx);
assert!(palette(&app, source).indexed_png());
}
#[test]
fn indexed_color_preview_and_ok_leave_reloaded_pixels_unchanged() {
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())));
let dir = vectorcraft_testkit::TempDir::new("indexed-color-image-revert");
let image = add_raster(&mut app);
app.run("file.saveAs", json!({"path": dir.join("raster.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [image.0]})).unwrap();
open(&mut app);
let st = app.session.active().unwrap();
let version = (st.uid, st.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.uid, version.0);
assert_ne!(st.reverts, version.1);
let undo = st.history.undo.len();
app.run("select.set", json!({"ids": [image.0]})).unwrap();
let before = palette(&app, image).rgba().unwrap().2;
let id = dialog_id(KIND);
crate::tests::picks::answer_dialog(
&mut app,
id,
&[("reduction", json!("blackWhite")), ("dither", json!("none")), ("preview", json!(true))],
false,
);
assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old Preview leaves the saved pixels in place");
crate::tests::picks::answer_dialog(&mut app, id, &[("preview", json!(false))], true);
assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old OK leaves the saved pixels in place");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
+41 -5
View File
@@ -38,7 +38,7 @@ pub(crate) struct Open {
/// The dialog on the host.
pub id: DialogId,
/// The drawing that owns the text IDs and the preview.
document: u64,
document: (u64, u64),
/// The preview on the canvas.
pub preview: LivePreview,
/// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on.
@@ -52,7 +52,7 @@ pub(crate) struct Open {
impl Open {
fn in_opening_document(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.uid == self.document)
app.session.active().is_some_and(|st| (st.uid, st.reverts) == self.document)
}
}
@@ -118,7 +118,8 @@ fn form(fields: &mut DialogFields) -> ParamDialog<'_> {
/// Open Justification on the paragraph attributes the Paragraph panel shows.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
let document = app.session.active().ok_or("no document open")?.uid;
let active = app.session.active().ok_or("no document open")?;
let document = (active.uid, active.reverts);
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
let mut story = None;
@@ -148,8 +149,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let id = super::host::open_held(app, dialog, |app, result| {
let Some(open) = app.justification.take() else { return Ok(()) };
if !open.in_opening_document(app) {
let message = if app.session.active().is_some_and(|st| st.uid == open.document.0) {
tl!("The document was reverted. Reopen this dialog to continue.")
} else {
tl!("This dialog was opened in a different document.")
};
app.justification = Some(open);
return Err(tl!("This dialog was opened in a different document.").to_owned());
return Err(message.to_owned());
}
let p = params(app, &result.fields, &open);
if !changes(&p) {
@@ -215,7 +221,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.justification.take() else { return };
let shown =
app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
// A document switch ends that document's preview. The active drawing may have started a different one.
// A document switch or revert ends the opening preview. The active drawing may have started a different one.
if !open.in_opening_document(app) {
if shown.is_some() {
open.preview = LivePreview::default();
@@ -604,4 +610,34 @@ mod tests {
assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0);
assert!(app.session.in_interaction());
}
#[test]
fn justification_does_not_preview_or_apply_after_revert() {
let (mut app, id) = app();
let dir = vectorcraft_testkit::TempDir::new("justification-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("text.setFormat", json!({"ids": [id], "autoLeading": 145})).unwrap();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
driver::set(&mut app, "preview", json!(true));
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
let dialog = craft::ui::dialog::dialog_id(KIND);
crate::tests::picks::answer_dialog(&mut app, dialog, &[], true);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(craft::ui::dialog::HeldOk::Refused(_))));
driver::cancel(&mut app);
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
driver::ok(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
}
}
+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();
+33 -2
View File
@@ -25,7 +25,7 @@ const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern"
/// It starts on Art when there is art, and it starts on Calligraphic otherwise.
pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> 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 = match &ids {
Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()),
None => !st.selection.is_empty(),
@@ -38,8 +38,11 @@ pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, Strin
let dialog =
HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), rows.clone()).values(Bind::bound(f))).held_ok();
host::open_held(app, dialog, move |app, answer| {
if app.session.active().is_none_or(|st| st.uid != document) {
let Some(source) = app.session.active().filter(|st| st.uid == document) else {
return Err(tl!("Return to the original drawing to make the brush").into());
};
if source.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
confirm(app, &answer.fields, ids.clone())
})
@@ -182,6 +185,34 @@ mod tests {
assert_eq!(open_fields(&app).text("__type"), Some("scatter"));
}
#[test]
fn the_type_chooser_and_brush_options_require_a_new_opening_after_revert() {
for in_options in [false, true] {
let dir = vectorcraft_testkit::TempDir::new("new-brush-revert");
let mut app = app();
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 saved = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone();
app.run("file.saveAs", json!({"path": dir.join("Saved.vectorcraft")})).unwrap();
app.run("shape.ellipse", json!({"x": 10, "y": 60, "width": 60, "height": 40})).unwrap();
app.run("ui.newBrush", json!({})).unwrap();
if in_options {
press_ok(&mut app, json!({"type": "art"}));
assert_eq!(open_fields(&app).text("__type"), Some("art"));
}
let source = app.session.active().unwrap();
let (uid, reverts) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [saved]})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
let before = (library(&mut app), undo_steps(&app));
let error = super::super::tests_export::try_confirm(&mut app).expect_err("an old brush approval is refused");
assert_eq!(error, "The document was reverted. Reopen this dialog to continue.");
assert_eq!((library(&mut app), undo_steps(&app)), before);
}
}
/// The new brush takes the art its Brush Options opened with: changing or clearing the
/// selection while the dialog is open does not change the art, and OK still makes the brush.
#[test]
+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()));
@@ -58,3 +58,143 @@ pub fn open(app: &mut VectorcraftApp) -> Value {
}
json!({ "dialog": KIND })
}
/// The compact tool options expose translated Pivot corners and accept actual edits.
#[cfg(test)]
#[test]
fn compact_objects_on_path_options_pivot_rotate_reset_and_save() {
use egui::accesskit::{Node, Role, TreeUpdate};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
use vectorcraft_engine::Session;
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)))
}
fn plain_label(label: &str) -> &str {
label.trim_end().trim_end_matches([':', ':']).trim_end()
}
const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"];
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut untranslated = Vec::new();
for lang in ["en", "de", "fr", "ja"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.prefs.interface_language = lang.into();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("tool.setOption", json!({"tool": TOOL, "values": {"pivot": 1,"rotate": 17}})).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 draft = |app: &VectorcraftApp| {
app.dialogs()
.unwrap()
.with(|host| host.get::<HostedParamDialog>().map(|d| (d.fields().int("pivot").unwrap(), d.fields().number("rotate").unwrap())))
};
let actual = |app: &VectorcraftApp| {
let options = app.session.tool_options_of(TOOL);
(options["pivot"].as_i64().unwrap(), options["rotate"].as_f64().unwrap())
};
settle(&mut app, &mut frame);
for save in [false, true] {
assert_eq!(app.run("tool.options", json!({"tool": TOOL})).unwrap()["dialog"], KIND);
let tree = settle(&mut app, &mut frame);
let by_name = |role, label: &str| {
tree.nodes
.iter()
.find(|(_, n)| {
n.role() == role
&& n.label().is_some_and(|actual| {
plain_label(actual) == plain_label(label)
|| (role == Role::RadioGroup && plain_label(actual) == plain_label(crate::i18n::t("Pivot:")))
})
})
.and_then(|(_, n)| bounds(n))
.unwrap_or_else(|| {
let names: Vec<_> = tree.nodes.iter().filter(|(_, n)| n.role() == role).filter_map(|(_, n)| n.label()).collect();
panic!("{lang}: missing {role:?} {label:?} in {names:?}")
})
};
let title = tool_options::title(TOOL);
let modal = by_name(Role::Dialog, title.as_str());
let picker = by_name(Role::RadioGroup, crate::i18n::t("Reference Point"));
let rotate = by_name(Role::SpinButton, crate::i18n::t("Rotate:"));
let reset = by_name(Role::Button, crate::i18n::t("Reset"));
let footer = by_name(Role::Button, crate::i18n::t(if save { "Save" } else { "Cancel" }));
assert!(screen.expand(0.5).contains_rect(modal), "{lang}: modal {modal:?} off screen");
for rect in [picker, rotate, reset, footer] {
assert!(rect.is_positive() && modal.expand(0.5).contains_rect(rect), "{lang}: {rect:?} outside modal {modal:?}");
}
let mut cells: Vec<_> = tree
.nodes
.iter()
.filter(|(_, n)| n.role() == Role::RadioButton)
.filter_map(|(_, n)| Some((n.label()?, bounds(n)?)))
.filter(|(_, rect)| picker.expand(0.5).contains(rect.center()))
.collect();
cells.sort_by(|(_, a), (_, b)| a.center().y.total_cmp(&b.center().y).then(a.center().x.total_cmp(&b.center().x)));
eprintln!(
"{lang}, save {save}: modal {modal:?}, pivot {picker:?}, cells {cells:?}, Rotate {rotate:?}, Reset {reset:?}, footer {footer:?}"
);
assert_eq!(cells.len(), 9, "{lang}: all Pivot options");
if save {
for ((name, _), legacy) in cells.iter().zip(PIVOT_NAMES) {
let expected = crate::i18n::t(legacy);
if expected != legacy && *name != expected {
untranslated.push(format!("{lang}: {name:?} instead of {expected:?}"));
}
}
}
assert!(cells.iter().all(|(_, cell)| picker.expand(0.5).contains_rect(*cell)), "{lang}: all cells lie in the picker");
assert_eq!(draft(&app), Some((1, 17.0)), "{lang}: opens from saved tool preferences");
click(&mut app, &mut frame, cells[8].1.center());
assert_eq!(draft(&app), Some((8, 17.0)), "{lang}: bottom-right physical pointer");
click(&mut app, &mut frame, rotate.center());
press(&mut app, &mut frame, Key::A, Modifiers::COMMAND);
frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("42".to_owned())]);
press(&mut app, &mut frame, Key::Tab, Modifiers::NONE);
settle(&mut app, &mut frame);
assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: real Rotate keyboard edit");
if !save {
click(&mut app, &mut frame, reset.center());
assert_eq!(draft(&app), Some((4, 0.0)), "{lang}: pointer Reset keeps the dialog open and resets both settings");
}
assert_eq!(actual(&app), (1, 17.0), "{lang}: only a draft before accepting");
click(&mut app, &mut frame, footer.center());
settle(&mut app, &mut frame);
assert_eq!(draft(&app), None, "{lang}: footer closes the dialog");
assert_eq!(actual(&app), if save { (8, 42.0) } else { (1, 17.0) }, "{lang}: footer persistence");
}
app.run("tool.options", json!({"tool": TOOL})).unwrap();
settle(&mut app, &mut frame);
assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: reopened saved values");
press(&mut app, &mut frame, Key::Escape, Modifiers::NONE);
settle(&mut app, &mut frame);
assert_eq!(draft(&app), None, "{lang}: Escape dismisses reopened options");
crate::i18n::set_current(crate::i18n::Lang::EN);
}
assert!(untranslated.is_empty(), "localized Pivot names were lost: {untranslated:?}");
}
+69 -3
View File
@@ -129,6 +129,7 @@ pub(crate) struct Open {
pub(crate) struct SplitOpen {
id: DialogId,
document: u64,
reverts: u64,
preview: LivePreview,
/// An interaction allocates its own selection snapshot, even when the selected objects did not change.
preview_selection: Option<Weak<Selection>>,
@@ -139,12 +140,13 @@ impl SplitOpen {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.reverts == self.reverts
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update_preview(&mut self, app: &mut VectorcraftApp, on: bool, fields: &DialogFields) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return };
let Some(state) = app.session.active().filter(|state| state.uid == self.document && state.reverts == self.reverts) else { return };
if !self.owns_preview(app) {
self.preview = LivePreview::default();
self.preview_selection = None;
@@ -162,8 +164,11 @@ impl SplitOpen {
}
fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> {
if app.session.active().is_none_or(|state| state.uid != self.document) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else {
return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned());
};
if state.reverts != self.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if app.session.in_interaction() && !self.owns_preview(app) {
return Err(tl!("Finish the active edit before applying Split Into Grid.").to_owned());
@@ -512,6 +517,7 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) {
return;
};
let document = state.uid;
let reverts = state.reverts;
let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let lengths = crate::canvas::general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| {
@@ -525,7 +531,7 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) {
old.cancel(app);
}
match open_held(app, dialog, ok) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, preview: LivePreview::default(), preview_selection: None }),
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, reverts, preview: LivePreview::default(), preview_selection: None }),
None => app.status("There is no window to show the dialog in."),
}
}
@@ -618,6 +624,7 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> {
#[cfg(test)]
mod split_tests {
use craft::ui::dialog::HeldOk;
use serde_json::json;
use super::*;
@@ -633,6 +640,65 @@ mod split_tests {
selected_rectangle(app, 150, 90);
}
fn grid_after_file_revert(hold_ok: bool) -> VectorcraftApp {
let mut app = app();
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 folder = vectorcraft_testkit::TempDir::new("split-into-grid-revert");
let path = folder.join("drawing.vectorcraft");
selected_rectangle(&mut app, 112, 62);
let original = app.session.active().unwrap().selection.objects[0];
app.run("file.saveAs", json!({"path": path})).unwrap();
selected_rectangle(&mut app, 50, 30);
app.run("select.set", json!({"ids": [original.0]})).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
open_split(&mut app);
set(&mut app, "columns", json!(3));
set(&mut app, "preview", json!(false));
if hold_ok {
let ctx = app.ui_ctx.clone().unwrap();
let id = app.object_dialogs.split.as_ref().unwrap().id;
assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)));
}
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reloaded = app.session.active().unwrap();
assert_eq!(reloaded.uid, uid);
assert_ne!(reloaded.reverts, generation);
app.run("select.set", json!({"ids": [original.0]})).unwrap();
app
}
#[test]
fn grid_revert_ignores_the_previous_generations_preview() {
let mut app = grid_after_file_revert(false);
let restored = app.session.active().unwrap().doc.clone();
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.active().unwrap().doc == restored, "old grid preview reached the restored drawing");
assert!(!app.session.in_interaction());
}
#[test]
fn grid_revert_ignores_a_held_ok_and_accepts_a_fresh_opening() {
let mut app = grid_after_file_revert(true);
let restored = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let id = app.object_dialogs.split.as_ref().unwrap().id;
frame(&mut app, vec![]);
assert!(app.session.active().unwrap().doc == restored, "old grid OK reached the restored drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
let Some(HeldOk::Refused(message)) = app.dialogs().unwrap().with(|host| host.held_state(id)) else { panic!("expected a held refusal") };
assert_eq!(message.as_str(), "The document was reverted. Reopen this dialog to continue.");
assert!(cancel(&mut app));
open_split(&mut app);
set(&mut app, "columns", json!(3));
assert!(confirm(&mut app));
let active = app.session.active().unwrap();
assert_eq!(active.doc.layers[0].children().unwrap().len(), 6);
assert_eq!(active.history.undo.len(), undo + 1);
}
#[test]
fn split_into_grid_skips_preview_in_the_other_drawing() {
let mut app = app();
+10 -6
View File
@@ -134,7 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res
let dialog = GridDialog::new(
def,
mode,
app.session.active().map(|st| st.uid),
app.session.active().map(|st| (st.uid, st.reverts)),
(general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points),
app.session.perspective_presets(),
app.session.new_perspective_preset_name(),
@@ -172,8 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) -
pub(super) struct GridDialog {
id: DialogId,
mode: GridMode,
/// The document whose grid Define Grid edits.
source_document: Option<u64>,
/// The document and loaded contents whose grid Define Grid edits.
source_document: Option<(u64, u64)>,
draft: GridDraft,
/// The presets the Preset row offers, as the document and the preferences have them.
presets: Vec<GridDefinition>,
@@ -196,7 +196,7 @@ impl GridDialog {
fn new(
def: GridDefinition,
mode: GridMode,
source_document: Option<u64>,
source_document: Option<(u64, u64)>,
(ppi, bare_points): (f64, bool),
presets: Vec<GridDefinition>,
new_name: String,
@@ -527,12 +527,16 @@ enum Next {
Presets(String),
}
fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<u64>, def: &GridDefinition) -> Result<Next, String> {
fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<(u64, u64)>, def: &GridDefinition) -> Result<Next, String> {
let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?;
if *mode == GridMode::Define {
if app.session.active().map(|st| st.uid) != source_document {
let active = app.session.active().map(|st| (st.uid, st.reverts));
if active.map(|(uid, _)| uid) != source_document.map(|(uid, _)| uid) {
return Err(tl!("Define Grid can only change the document where it was opened.").to_owned());
}
if active != source_document {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
app.run("perspective.grid.define", params)?;
return Ok(Next::Close);
}
@@ -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"]}));
+41 -5
View File
@@ -6,7 +6,7 @@
//! Fields: `limitTo` (a library id, `"document"` for the document's swatches, `""` for None), as
//! Recolor Artwork's.
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, ParamResult};
use craft::ui::runtime::env::Label;
use serde_json::{Value, json};
@@ -16,6 +16,7 @@ use crate::VectorcraftApp;
/// The dialog kind of Recolor with Preset.
pub const KIND: &str = "recolorPreset";
const OPENING: &str = "__opening";
/// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on,
/// "" the first library) on the selected art.
@@ -24,7 +25,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if st.selection.is_empty() {
return Err("select artwork to recolor".into());
}
let document = st.uid;
let (document, reverts) = (st.uid, st.reverts);
if p.get("group").is_some_and(|g| !g.is_null()) {
return Err("`group` does not apply to a preset".into());
}
@@ -36,15 +37,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let options = library_choices(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect();
let mut fields = DialogFields::new();
fields.set("limitTo", limit.clone());
fields.set(OPENING, FieldValue::Json(json!({"uid": document, "reverts": reverts, "colors": colors})));
let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))];
let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false);
// Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays.
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
if !app.session.active().is_some_and(|active| active.uid == document) {
let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let Some(FieldValue::Json(opening)) = answer.fields.get(OPENING) else { return Err("the Recolor with Preset target is missing".into()) };
let Some(active) = app.session.active().filter(|active| Some(active.uid) == opening["uid"].as_u64()) else {
return Err(tl!("Open the original drawing to continue with Recolor with Preset.").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 mut p = serde_json::Map::new();
if let Some(n) = colors {
if let Some(n) = opening["colors"].as_u64() {
p.insert("colors".into(), json!(n));
}
if let Some(limit) = answer.fields.text("limitTo").filter(|l| !l.is_empty()) {
@@ -101,4 +107,34 @@ mod tests {
let limit = super::super::recolor::limit_to(&host, dialog_id(super::super::recolor::KIND));
assert_eq!(limit.as_deref(), Some("document"));
}
#[test]
fn an_old_recolor_preset_does_not_open_on_restored_artwork() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
let dir = vectorcraft_testkit::TempDir::new("recolor-preset-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("paint.setFill", json!({"ids": [shape], "color": "#ff0000"})).unwrap();
app.run("select.set", json!({"ids": [shape]})).unwrap();
app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
let id = dialog_id(KIND);
assert!(!host.with(|h| h.confirm_by_id(&ctx, id)));
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [shape]})).unwrap();
super::super::host::pump(&mut app, &ctx);
assert!(app.color_dialogs.recolor.is_none());
assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
host.with(|h| h.cancel_by_id(&ctx, id));
app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap();
assert!(super::super::tests::confirm(&mut app));
assert!(app.color_dialogs.recolor.is_some());
}
}
+2 -2
View File
@@ -46,9 +46,9 @@ fn params(fields: &DialogFields) -> Value {
}
fn rows() -> Vec<Param> {
vec![Param::custom("intensity", "Intensity", |ui, fields, _cx| {
vec![Param::custom("intensity", tl!("Intensity"), |ui, fields, _cx| {
// The rail runs from grey to a fully saturated colour.
percent_row(ui, fields, "intensity", "Intensity", |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85))));
percent_row(ui, fields, "intensity", tl!("Intensity"), |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85))));
ui.response()
})]
}
+19 -13
View File
@@ -42,7 +42,7 @@ const WRONG_DOCUMENT: &str = "Save for Web belongs to the document that opened t
/// What the open dialog's pump keeps between frames: data keyed by its inputs, never UI state.
#[derive(Default)]
pub(crate) struct WebExport {
document: Option<u64>,
document: Option<(u64, u64)>,
opening: Arc<()>,
/// The rendering of the art before optimisation, by [`render_key`].
render: Option<(String, Result<Arc<WebRender>, String>)>,
@@ -186,7 +186,8 @@ fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: O
/// Open on the document's active artboard, keeping the other remembered settings.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let document = app.session.active().ok_or("no document")?.uid;
let active = app.session.active().ok_or("no document")?;
let document = (active.uid, active.reverts);
let host = app.dialogs().ok_or("no window")?;
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Settle a completed opening while its settings and source are still available.
@@ -461,8 +462,13 @@ fn on_dialog<R>(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host
host.with(|h| h.get_mut::<HostedSaveForWeb>().map(f))
}
fn on_original_document(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|active| app.web_export.document == Some(active.uid))
fn document_problem(app: &VectorcraftApp) -> Option<&'static str> {
match (app.web_export.document, app.session.active()) {
(Some((uid, reverts)), Some(active)) if uid == active.uid => {
(reverts != active.reverts).then(|| tl!("The document was reverted. Reopen this dialog to continue."))
}
_ => Some(tl!(WRONG_DOCUMENT)),
}
}
/// Answers the open dialog once per frame: its result when it closed, else its requests.
@@ -479,7 +485,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
_ => {}
}
let Some(asked) = on_dialog(&host, Asked::take) else { return };
if !on_original_document(app) {
if let Some(reason) = document_problem(app) {
let restore = asked.tables.iter().any(|event| matches!(event.edit, ColorTableEdit::Restore));
if restore {
color_table::restore(&mut app.web_export.table);
@@ -494,7 +500,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
update_presets(app, &host, asked.presets, restore);
if requested {
on_dialog(&host, HostedSaveForWeb::cancel_requests);
app.status(tl!(WRONG_DOCUMENT).to_owned());
app.status(reason);
}
return;
}
@@ -595,8 +601,8 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key:
let Some(options) = host.with(|h| h.get_mut_by_id::<HostedSaveForWeb>(parent).map(|d| d.current().clone())) else {
return false;
};
if !on_original_document(app) {
app.status(tl!(WRONG_DOCUMENT).to_owned());
if let Some(reason) = document_problem(app) {
app.status(reason);
return true;
}
let rgb = |c: Srgba| {
@@ -736,11 +742,11 @@ fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id
if !Arc::ptr_eq(&opening, &app.web_export.opening) {
return Ok(Value::Null);
}
if !on_original_document(app) {
if let Some(reason) = document_problem(app) {
if let Some(host) = app.dialogs() {
on_dialog(&host, HostedSaveForWeb::cancel_requests);
}
app.status(tl!(WRONG_DOCUMENT).to_owned());
app.status(reason);
return Ok(Value::Null);
}
match picked.first_path() {
@@ -765,12 +771,12 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) {
/// The dialog closed with Save… or Done: the settings are remembered, and with a path the files are
/// written. Failures show in the status line; the dialog has closed.
fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) {
let wrong_document = result.path.is_some() && !on_original_document(app);
let problem = document_problem(app).filter(|_| result.path.is_some());
let table = std::mem::take(&mut app.web_export.table);
let kept = std::mem::take(&mut app.web_export.kept);
app.web_export = WebExport::default();
if wrong_document {
return app.status(tl!(WRONG_DOCUMENT).to_owned());
if let Some(reason) = problem {
return app.status(reason);
}
let params = settings_of(&result.options, &table, &kept, None);
if let Err(e) = app.run("webExport.settings", params.clone()) {
@@ -355,6 +355,42 @@ fn save_for_web_does_not_write_another_drawing_when_the_picker_returns() {
assert!(dir.join("Untitled-1.png").exists());
}
#[test]
fn save_for_web_requires_a_fresh_approval_after_file_revert() {
let dir = vectorcraft_testkit::TempDir::new("sfw-revert-output");
let source = vectorcraft_testkit::TempDir::new("sfw-revert-drawing");
let (mut app, _) = app(dir.as_ref(), false);
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
let path = source.join("Source.vectorcraft");
app.run("file.saveAs", json!({"path": path})).unwrap();
app.run("shape.rectangle", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
let original = app.session.active().unwrap();
let (uid, reverts) = (original.uid, original.reverts);
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("png24"));
let ctx = app.ui_ctx.clone().unwrap();
let dialog = id(&app);
host(&app).with(|h| h.confirm_by_id(&ctx, dialog));
settle(&mut app);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let current = app.session.active().unwrap();
assert_eq!((current.uid, current.reverts), (uid, reverts + 1));
answer_saves(&mut app);
settle(&mut app);
assert_eq!(std::fs::read_dir(dir.as_ref()).unwrap().count(), 0);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
close(&mut app);
settle(&mut app);
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("png24"));
save(&mut app);
let outputs: Vec<_> = std::fs::read_dir(dir.as_ref()).unwrap().map(|entry| entry.unwrap().path()).collect();
assert_eq!(outputs.len(), 1);
assert!(std::fs::read(&outputs[0]).unwrap().starts_with(b"\x89PNG"));
}
/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes
/// and stays remembered after Done.
#[test]
+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.
@@ -6,6 +6,8 @@
//! Fields: the switches `fiLigatures`, `flLigatures`, `quotes`, `spaces`, `dashes`, `ellipsis` and
//! `fractions`, `scope` (`selection` or `document`) and `report`.
use std::collections::HashSet;
use craft::ui::contract::{Bind, SaveKey};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::Label;
@@ -51,6 +53,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let source = app.session.active().ok_or("no document")?;
let document = source.uid;
let selected = !source.selection.is_empty();
let selection = source.selection.objects.iter().copied().collect::<HashSet<_>>();
let mut params: Vec<Param> = options()
.into_iter()
.map(|(key, _, label)| Param::new(key, label, ParamKind::bool(matches!(key, "quotes" | "dashes" | "ellipsis"))))
@@ -72,10 +75,18 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
ctx.data_mut(|data| data.insert_temp(owner, document));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> {
let document = ctx.data(|data| data.get_temp::<u64>(owner));
if app.session.active().is_none_or(|st| Some(st.uid) != document) {
let Some(active) = app.session.active().filter(|st| Some(st.uid) == document) else {
return Err(tl!("Return to the original drawing to replace its punctuation").into());
};
let params = params_of(result);
if params["scope"] == "selection"
&& (active.selection.is_empty()
|| active.selection.objects.len() != selection.len()
|| active.selection.objects.iter().any(|id| !selection.contains(id)))
{
return Err(tl!("The selected text changed. Restore the selection to continue.").into());
}
let r = app.run(COMMAND, params_of(result))?;
let r = app.run(COMMAND, params)?;
result.remember(&ctx);
if result.fields.bool("report") == Some(true) {
let lines: Vec<String> = options()
@@ -208,4 +219,47 @@ mod tests {
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(plain(&app, source), "a--b");
}
fn selected_text_pair() -> (VectorcraftApp, u64, u64) {
let (mut app, selected) = app_with_text("a--b");
let other = app.run("text.create", json!({"x": 10, "y": 70, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [selected]})).unwrap();
open(&mut app).unwrap();
assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "selection");
(app, selected, other)
}
#[test]
fn selected_text_only_does_not_expand_to_the_document_after_clearing_selection() {
let (mut app, selected, other) = selected_text_pair();
let undo = app.session.active().unwrap().history.undo.len();
app.run("select.none", json!({})).unwrap();
assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "selection");
let answer = super::super::tests_export::try_confirm(&mut app);
assert_eq!([plain(&app, selected), plain(&app, other)], ["a--b", "c--d"], "Selected Text Only must not expand to the document");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into()));
app.run("select.set", json!({"ids": [selected]})).unwrap();
ok(&mut app);
assert_eq!([plain(&app, selected), plain(&app, other)], ["a–b", "c--d"], "retry changes only the original selection");
}
#[test]
fn selected_text_only_refuses_later_art_but_entire_document_still_works() {
let (mut app, selected, other) = selected_text_pair();
app.run("select.set", json!({"ids": [other]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let answer = super::super::tests_export::try_confirm(&mut app);
assert_eq!([plain(&app, selected), plain(&app, other)], ["a--b", "c--d"], "Selected Text Only must not change later artwork");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into()));
set(&app, "scope", json!("document"));
ok(&mut app);
assert_eq!([plain(&app, selected), plain(&app, other)], ["a–b", "c–d"], "an explicit Entire Document still works");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
}
+23 -1
View File
@@ -474,7 +474,10 @@ fn ask_import(app: &mut VectorcraftApp, source: Option<Arc<Opening>>) -> Value {
// The browser answers with the file's contents, not a path.
Picked::Contents(files) => {
let (_, bytes) = files.first().ok_or("cancelled")?;
json!({ "svg": String::from_utf8_lossy(bytes) })
if bytes.len() > vectorcraft_engine::cmd::MAX_SVG_FILTER_IMPORT_BYTES {
return Err("The SVG file is larger than 16 MB".into());
}
json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) })
}
other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }),
};
@@ -499,6 +502,25 @@ mod tests {
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3"/></filter>"#;
#[test]
fn browser_filter_import_keeps_the_picked_file_encoding() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><filter id="café"><feOffset dx="3"/></filter></svg>"#;
let utf16: Vec<u8> = [0xfe, 0xff].into_iter().chain(svg.encode_utf16().flat_map(u16::to_be_bytes)).collect();
let latin1: Vec<u8> = format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>{svg}").chars().map(|c| c as u8).collect();
for bytes in [utf16, latin1] {
let mut app = app();
let picker = scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
open(&mut app, &json!({})).unwrap();
import_file(&mut app).unwrap();
picker.answer_contents(&[("filter.svg", &bytes)]);
poll(&mut app, &ctx);
assert_eq!(app.session.active().unwrap().doc.svg_filters[0].name, "café");
assert_eq!(fields(&app)[SELECTED], "café");
assert_eq!(app.session.active().unwrap().history.undo.len(), 1);
}
}
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
+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,
+46 -8
View File
@@ -48,7 +48,7 @@ pub(crate) struct Open {
/// The held dialog.
pub(crate) id: DialogId,
opening: Arc<()>,
document: u64,
document: (u64, u64),
preview_reset: u64,
/// The name of the swatch being edited.
swatch: String,
@@ -291,7 +291,8 @@ fn stops_of(g: &GradientPaint) -> GradientStops {
/// Opens the held dialog over swatch `swatch`: OK is one `swatch.edit` undo step, Cancel rolls the preview back.
fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Vec<Param>) -> Result<Value, String> {
let document = app.session.active().ok_or("no drawing")?.uid;
let active = app.session.active().ok_or("no drawing")?;
let document = (active.uid, active.reverts);
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true);
if owns_preview(app) {
@@ -301,8 +302,11 @@ fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Ve
let cancelled = Arc::clone(&opening);
let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let open = app.ui.swatch_options.as_ref().ok_or("the Swatch Options dialog is gone")?;
if app.session.active().is_none_or(|st| st.uid != open.document) {
let Some(active) = app.session.active().filter(|st| st.uid == open.document.0) else {
return Err(tl!("Return to the original drawing to edit this swatch").into());
};
if active.reverts != open.document.1 {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
let edited = open.swatch.clone();
// The edit replaces the preview, so the preview is dropped first.
@@ -345,15 +349,17 @@ fn owns_preview(app: &VectorcraftApp) -> bool {
app.ui.swatch_options.as_ref().is_some_and(|open| {
open.last.is_some()
&& open.preview_reset == app.session.tool_resets()
&& app
.session
.active()
.is_some_and(|st| st.uid == open.document && st.interaction.as_ref().is_some_and(|interaction| interaction.label == PREVIEW_LABEL))
&& app.session.active().is_some_and(|st| {
(st.uid, st.reverts) == open.document && st.interaction.as_ref().is_some_and(|interaction| interaction.label == PREVIEW_LABEL)
})
})
}
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| st.uid == open.document)) else { return };
let Some(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| (st.uid, st.reverts) == open.document))
else {
return;
};
let (id, swatch, last) = (open.id, open.swatch.clone(), open.last.clone());
let owns_preview = owns_preview(app);
correct(app, id);
@@ -674,4 +680,36 @@ mod tests {
app.run("edit.undo", json!({})).unwrap();
assert_eq!(swatch(&app, "Sky").0.map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step");
}
#[test]
fn swatch_options_cannot_preview_or_rename_a_restored_swatch() {
let (ctx, mut app) = setup();
app.run("swatch.new", json!({"name": "Editable", "color": "#123456"})).unwrap();
let dir = vectorcraft_testkit::TempDir::new("swatch-options-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("swatch.edit", json!({"name": "Editable", "color": "#654321"})).unwrap();
open(&mut app, "Editable").unwrap();
let name = "Renamed";
set(&app, &ctx, &[("name", json!(name)), ("preview", json!(true))]);
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.active().unwrap().doc.swatch(name).is_some());
app.run("file.revert", json!({"confirmed": true})).unwrap();
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.active().unwrap().doc.swatch(name).is_none());
let color = swatch(&app, "Editable").0.unwrap();
assert_eq!(color.to_hex(), "#123456");
let id = dialog_id(KIND);
crate::tests::picks::answer_dialog(&mut app, id, &[], true);
assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
assert!(app.session.active().unwrap().doc.swatch(name).is_none());
app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
open(&mut app, "Editable").unwrap();
crate::tests::picks::answer_dialog(&mut app, id, &[("name", json!(name))], true);
assert!(app.session.active().unwrap().doc.swatch(name).is_some());
}
}
+23 -14
View File
@@ -2,10 +2,10 @@
//! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand
//! Instances, Delete Instances and Cancel ([`USED`]).
//!
//! The question carries the [`vectorcraft_engine::DocState::uid`] of the document it was asked in and
//! the symbol names. Yes or either Instances button deletes the symbol only while that document is
//! the active one and still has the symbol; an unused symbol that has gained instances since asks
//! the in-use question instead.
//! The question carries the opening document, its revert generation, and the symbol names. Yes or
//! either Instances button deletes the symbol only while that document is active, has not been
//! reverted, and still has the symbol. An unused symbol that has gained instances asks the in-use
//! question instead.
use craft::ui::dialog::{PromptChoice, StandardPrompt};
use serde_json::{Value, json};
@@ -28,6 +28,7 @@ enum Target {
/// whether it is the in-use question.
struct Ask {
doc: u64,
reverts: u64,
target: Target,
used: bool,
}
@@ -42,7 +43,7 @@ crate::dialogs::confirm::wrapped_dialog!(SymbolQuestion, StandardPrompt, KIND);
/// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's
/// button) and asked about otherwise.
pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) {
let Some(uid) = app.session.active().map(|st| st.uid) else { return };
let Some((uid, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return };
match instances(app, uid, name) {
None => {}
Some(0) if now => {
@@ -50,7 +51,7 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) {
app.status(e);
}
}
Some(n) => open(app, Ask { doc: uid, target: Target::One(name.to_string()), used: n > 0 }),
Some(n) => open(app, Ask { doc: uid, reverts, target: Target::One(name.to_string()), used: n > 0 }),
}
}
@@ -58,12 +59,12 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) {
/// ("Delete the selected symbols?", or the singular for one), or at once with `now`. Only those still
/// unused then (`symbol.unused`: brush art, patterns and nested instances count) go, in one undo step.
pub(crate) fn ask_many(app: &mut VectorcraftApp, names: &[String], now: bool) {
let Some(uid) = app.session.active().map(|st| st.uid) else { return };
let Some((uid, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return };
if now {
// An error already went to the status bar.
let _ = delete_unused(app, uid, names);
} else {
open(app, Ask { doc: uid, target: Target::Many(names.to_vec()), used: false });
open(app, Ask { doc: uid, reverts, target: Target::Many(names.to_vec()), used: false });
}
}
@@ -109,12 +110,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
// The host lock is released before any command runs.
let Some(mut answer) = dialogs.with(|host| host.take::<SymbolQuestion>()).and_then(|result| result.ok()) else { return };
let Some(ask) = answer.take_tag::<Ask>() else { return };
let r = match (ask.used, answer.choice) {
(false, PromptChoice::Proceed) => confirm_unused(app, ask),
(true, PromptChoice::Proceed) => confirm_used(app, ask, true),
(true, PromptChoice::Alternate) => confirm_used(app, ask, false),
let expand_instances = match (ask.used, answer.choice) {
(false, PromptChoice::Proceed) => None,
(true, PromptChoice::Proceed) => Some(true),
(true, PromptChoice::Alternate) => Some(false),
_ => return,
};
if app.session.active().is_some_and(|st| st.uid == ask.doc && st.reverts != ask.reverts) {
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
return;
}
let r = match expand_instances {
Some(expand) => confirm_used(app, ask, expand),
None => confirm_unused(app, ask),
};
if let Err(e) = r {
app.status(e);
}
@@ -132,14 +141,14 @@ fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option<u64> {
/// Yes: deletes the symbol, or asks the in-use question when it has gained instances.
fn confirm_unused(app: &mut VectorcraftApp, ask: Ask) -> Result<Value, String> {
let Ask { doc, target, .. } = ask;
let Ask { doc, reverts, target, .. } = ask;
match target {
Target::Many(names) => delete_unused(app, doc, &names),
Target::One(name) => match instances(app, doc, &name) {
None => Ok(Value::Null),
Some(0) => app.run("symbol.delete", json!({ "name": name })),
Some(_) => {
open(app, Ask { doc, target: Target::One(name), used: true });
open(app, Ask { doc, reverts, target: Target::One(name), used: true });
Ok(Value::Null)
}
},
+155 -5
View File
@@ -12,6 +12,8 @@
//! Help:
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html>.
use std::collections::HashSet;
use craft::ui::contract::{Bind, Outcome as _, Show as _};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook};
@@ -100,13 +102,25 @@ fn rows(name: &str) -> Vec<Param> {
/// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one;
/// `opened` are the guides the dialog opened with.
fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option<String>, keep_art: bool, opened: [f64; 4]) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let st = app.session.active().ok_or("no document open")?;
let (document, reverts) = (st.uid, st.reverts);
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> {
if !app.session.active().is_some_and(|active| active.uid == document) {
return Err(tl!("This symbol belongs to the document that opened the dialog.").to_owned());
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());
};
if active.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
if let Some(selection) = &selection
&& (active.selection.objects.len() != selection.len() || active.selection.objects.iter().any(|id| !selection.contains(id)))
{
return Err(tl!("The selected artwork changed. Restore the selection to continue.").into());
}
let f = &result.fields;
let name = f.text("name").unwrap_or_default().trim().to_string();
@@ -195,10 +209,83 @@ fn merge(into: &mut Value, extra: Value) {
#[cfg(test)]
mod document_tests {
use craft::ui::dialog::dialog_id;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
use super::super::tests_warp::{accept, set, windowed};
use super::super::tests_warp::{accept, dismiss, set, windowed};
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() {
@@ -225,4 +312,67 @@ mod document_tests {
accept(&mut app, id);
assert!(app.session.active().unwrap().doc.symbols.iter().any(|symbol| symbol.name == "Source badge"));
}
#[test]
fn new_symbol_does_not_replace_art_selected_after_opening() {
let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let original = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
let other = app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [original]})).unwrap();
open(&mut app, false).unwrap();
let id = dialog_id(KIND);
set(&app, id, "name", json!("Badge"));
app.run("select.set", json!({"ids": [other]})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
answer_dialog(&mut app, id, &[], true);
assert!(app.session.active().unwrap().doc == before, "OK cannot turn the later selection into a symbol");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("select.set", json!({"ids": [original]})).unwrap();
answer_dialog(&mut app, id, &[], true);
let symbols = app.run("symbol.list", json!({})).unwrap();
assert_eq!(symbols["symbols"][0]["name"], "Badge");
assert_eq!(symbols["symbols"][0]["size"], json!([30.0, 30.0]), "the original art becomes the symbol");
assert!(app.session.active().unwrap().doc.node(NodeId(other)).is_some(), "the unrelated rectangle remains");
}
#[test]
fn editing_symbol_options_keeps_the_definition_restored_by_revert() {
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": 0, "y": 0, "width": 30, "height": 30})).unwrap();
app.run("symbol.new", json!({"name": "Badge"})).unwrap();
let file = std::env::temp_dir().join(format!("vectorcraft-symbol-options-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("symbol.options", json!({"name": "Badge", "registration": 0})).unwrap();
open_edit(&mut app, Some("Badge")).unwrap();
let id = dialog_id(KIND);
set(&app, id, "name", json!("Edited badge"));
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!(st.doc.symbol_registration("Badge").0, 4);
let restored = st.doc.clone();
let undo = st.history.undo.len();
answer_dialog(&mut app, id, &[], true);
assert_eq!(app.session.active().unwrap().doc.symbols[0].name, "Badge", "the restored symbol keeps its name");
assert_eq!(app.session.active().unwrap().doc, restored);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
dismiss(&mut app, id);
open_edit(&mut app, Some("Badge")).unwrap();
set(&app, id, "name", json!("New badge"));
accept(&mut app, id);
assert_eq!(app.session.active().unwrap().doc.symbols[0].name, "New badge");
}
}
+40 -3
View File
@@ -39,7 +39,8 @@ fn rows(lengths: LengthUnits) -> Vec<Param> {
/// Open Tate-chu-yoko Settings on the characters the Character panel acts on.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
let document = app.session.active().ok_or("no document")?.uid;
let active = app.session.active().ok_or("no document")?;
let (document, reverts) = (active.uid, active.reverts);
let (up, right) = crate::panels::character::shared_tcy_offsets(app);
let mut fields = DialogFields::new();
for (key, v) in KEYS.into_iter().zip([up, right]) {
@@ -56,8 +57,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if p.is_empty() {
return Ok(());
}
if !app.session.active().is_some_and(|active| active.uid == document) {
return Err(tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned());
let active = app
.session
.active()
.filter(|active| active.uid == document)
.ok_or_else(|| tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned())?;
if active.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
crate::panels::character::run_format(app, Value::Object(p)).map(|_| ())
})
@@ -199,4 +205,35 @@ mod tests {
driver::ok(&mut app);
assert_eq!(offsets(&app, id), [(0.0, 6.0), (0.0, 0.0)]);
}
#[test]
fn tate_chu_yoko_approval_refuses_to_change_restored_text() {
let (mut app, id) = app();
let dir = vectorcraft_testkit::TempDir::new("tate_chu_yoko-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();
let before = offsets(&app, id);
app.run("text.setFormat", json!({"ids": [id], "tcyUpDown": 3})).unwrap();
app.run("ui.tateChuYokoSettings", json!({})).unwrap();
driver::set(&mut app, "tcyUpDown", json!(7));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let dialog = craft::ui::dialog::dialog_id(KIND);
crate::tests::picks::answer_dialog(&mut app, dialog, &[], true);
assert_eq!(offsets(&app, id), before);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(
app.dialogs().unwrap().with(|h| h.held_state(dialog)),
Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted")
));
driver::cancel(&mut app);
app.run("ui.tateChuYokoSettings", json!({})).unwrap();
driver::set(&mut app, "tcyUpDown", json!(7));
driver::ok(&mut app);
assert_eq!(offsets(&app, id)[0].0, 7.0);
}
}
@@ -137,6 +137,39 @@ fn define_grid_applies_only_to_the_document_where_it_opened() {
assert_eq!(grid(&app).right_color.hex(), "#112233");
}
#[test]
fn define_grid_requires_a_fresh_opening_after_native_revert() {
let mut app = app();
let dir = vectorcraft_testkit::TempDir::new("define-grid-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("perspective.grid.define", json!({"rightColor": "#123456"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("Grid.vectorcraft")})).unwrap();
app.run("perspective.grid.define", json!({"rightColor": "#765432"})).unwrap();
let source = app.session.active().unwrap();
let (uid, reverts) = (source.uid, source.reverts);
app.run("ui.perspectiveGridDialog", json!({})).unwrap();
set(&mut app, "rightColor", json!("#abcdef")).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
let undo = restored.history.undo.len();
ok(&mut app);
assert_eq!(grid(&app).right_color.hex(), "#123456");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
let id = dialog_id(super::perspective_grid::KIND);
assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_))));
let ctx = window(&app);
assert!(host(&app, |h| h.cancel_by_id(&ctx, id)));
frame(&mut app);
app.run("ui.perspectiveGridDialog", json!({})).unwrap();
set(&mut app, "rightColor", json!("#abcdef")).unwrap();
ok(&mut app);
assert_eq!(grid(&app).right_color.hex(), "#abcdef");
}
#[test]
fn define_grid_loads_and_saves_presets() {
let mut app = app();
@@ -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"));
}
}
}
+25 -2
View File
@@ -4,10 +4,11 @@
// PLAN: ui-egui reaches the framework through `craft::..`; the crate's Cargo.toml needs the `craft` dependency
// (hub-w1 owns the manifest).
use craft::behavior::Anchor9;
use craft::i18n::Word;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::patterns::form_dialogs::{DialogFields, Param};
use craft::ui::pickers::{ReferencePoint, ReferencePointLook};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env};
use serde_json::{Map, Value, json};
use vectorcraft_doc::Unit;
@@ -30,13 +31,35 @@ pub(crate) fn reference_index(fields: &DialogFields, key: &str) -> usize {
fields.int(key).map_or(0, |n| n.clamp(0, 8) as usize)
}
/// The dialog reference picker's corner labels use the app catalog's existing title-case keys.
fn localized_reference_corners() -> WordRows {
[
(Word::keyed("referencePoint.topLeft", "Top left"), "Top Left"),
(Word::keyed("referencePoint.topRight", "Top right"), "Top Right"),
(Word::keyed("referencePoint.bottomLeft", "Bottom left"), "Bottom Left"),
(Word::keyed("referencePoint.bottomRight", "Bottom right"), "Bottom Right"),
]
.into_iter()
.fold(WordRows::new(), |rows, (word, source)| {
let translated = tl!(source);
if translated == source { rows } else { rows.row(word, translated) }
})
}
/// A row of the nine-point reference picker over the index `key` holds ([`reference_index`]).
pub(crate) fn reference_param(key: &str, label: impl Into<Label>) -> Param {
let name = key.to_owned();
Param::custom(key, label, move |ui, fields, _| {
let shown = reference_index(fields, &name);
let mut anchor = Some(Anchor9::ALL.get(shown).copied().unwrap_or(Anchor9::TopLeft));
let edit = ReferencePoint::new(tl!("Reference Point"), Bind::bound(&mut anchor)).look(ReferencePointLook::Squares).show(ui);
let picker = ReferencePoint::new(tl!("Reference Point"), Bind::bound(&mut anchor)).look(ReferencePointLook::Squares);
let show = |ui: &mut egui::Ui| picker.show(ui);
let words = localized_reference_corners();
let edit = if words.iter().next().is_some() {
with_env(ui, |overrides| overrides.words = Some(WordsOverride::Overlay(words)), show)
} else {
show(ui)
};
if let Some(picked) = Anchor9::ALL.iter().position(|point| Some(*point) == anchor).filter(|at| *at != shown) {
fields.set(name.clone(), picked as i64);
}
+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);
}
}
+40 -3
View File
@@ -69,7 +69,8 @@ fn rows(lengths: LengthUnits) -> Vec<Param> {
/// Open Warichu Settings on the characters the Character panel acts on.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
let document = app.session.active().ok_or("no document")?.uid;
let active = app.session.active().ok_or("no document")?;
let (document, reverts) = (active.uid, active.reverts);
let shared = crate::panels::character::shared_warichu(app);
let mut fields = DialogFields::new();
set_shared(&mut fields, KEYS[0], shared.lines.map(i64::from));
@@ -87,8 +88,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if p.is_empty() {
return Ok(());
}
if !app.session.active().is_some_and(|active| active.uid == document) {
return Err(tl!("Warichu Settings can only change the document where it was opened.").to_owned());
let active = app
.session
.active()
.filter(|active| active.uid == document)
.ok_or_else(|| tl!("Warichu Settings can only change the document where it was opened.").to_owned())?;
if active.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
crate::panels::character::run_format(app, Value::Object(p)).map(|_| ())
})
@@ -335,4 +341,35 @@ mod tests {
driver::ok(&mut app);
assert_eq!(settings(&app, id), [(false, 2, 0.0, 50.0, WarichuAlign::JustifyAll), (false, 2, 0.0, 50.0, WarichuAlign::Auto)]);
}
#[test]
fn warichu_approval_refuses_to_change_restored_text() {
let (mut app, id) = app();
let dir = vectorcraft_testkit::TempDir::new("warichu-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();
let before = settings(&app, id);
app.run("text.setFormat", json!({"ids": [id], "warichuLines": 3})).unwrap();
app.run("ui.warichuSettings", json!({})).unwrap();
driver::set(&mut app, "warichuLines", json!(4));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let dialog = craft::ui::dialog::dialog_id(KIND);
crate::tests::picks::answer_dialog(&mut app, dialog, &[], true);
assert_eq!(settings(&app, id), before);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(
app.dialogs().unwrap().with(|h| h.held_state(dialog)),
Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted")
));
driver::cancel(&mut app);
app.run("ui.warichuSettings", json!({})).unwrap();
driver::set(&mut app, "warichuLines", json!(4));
driver::ok(&mut app);
assert_eq!(settings(&app, id)[0].1, 4);
}
}
+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}));
+1 -1
View File
@@ -402,7 +402,7 @@ fn apply_tint(app: &mut VectorcraftApp, tgt: &Target, tint: &Tint, t: f32, phase
/// Switch the panel to `mode`, converting the colour to its model (a tint becomes a process
/// colour).
fn set_mode(app: &mut VectorcraftApp, tgt: &Target, mode: ColorPanelMode) {
pub(crate) fn set_mode(app: &mut VectorcraftApp, tgt: &Target, mode: ColorPanelMode) {
app.ui.color_panel.mode = mode;
if let Some(c) = tgt.color() {
let conv = convert_to(mode, &c);
+8 -9
View File
@@ -266,8 +266,8 @@ pub(crate) fn reset_to_linear_white_black(app: &mut VectorcraftApp) {
}
/// Save the gradient as a swatch; its stops keep their color models.
fn save_to_swatches(app: &mut VectorcraftApp, g: &GradientPaint) {
app.run("swatch.new", super::swatch_paint_params(&Paint::Gradient(Box::new(g.clone())))).ok();
fn save_to_swatches(app: &mut VectorcraftApp, g: &GradientPaint) -> Result<(), String> {
app.run("swatch.new", super::swatch_paint_params(&Paint::Gradient(Box::new(g.clone())))).map(drop)
}
/// The document's gradient swatches (groups included): name and gradient.
@@ -658,10 +658,10 @@ fn fill_box(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: b
}
}
Divider::horizontal().show(ui);
save = MenuItem::new(tl!("Save to Swatches")).enabled(is_grad).show(ui).ran;
save = MenuItem::new(tl!("Save to Swatches")).enabled(is_grad && crate::menus::enabled(app, "swatch.new")).show(ui).ran;
});
if save {
save_to_swatches(app, g);
if save && let Err(error) = save_to_swatches(app, g) {
app.status(error);
}
if let Some(name) = chosen {
super::apply_click(app, ui, json!({ "swatch": name }));
@@ -903,7 +903,7 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let has = current(app).is_some();
let toggle = |key: &str, show: &str, hide: &str| CommandState::new().title(if part_hidden(app, key) { show } else { hide });
states.set(MENU_OPTIONS, toggle(HIDE_OPTIONS, tl!("Show Options"), tl!("Hide Options")));
states.set(MENU_ADD_TO_SWATCHES, CommandState::new().title(tl!("Add to Swatches")).enabled(has));
states.set(MENU_ADD_TO_SWATCHES, CommandState::new().title(tl!("Add to Swatches")).enabled(has && crate::menus::enabled(app, "swatch.new")));
states.set(MENU_REVERSE, CommandState::new().title(tl!("Reverse Gradient")).enabled(has));
states.set(MENU_RESET, CommandState::new().title(tl!("Reset to White, Black")));
states.set(MENU_PRESETS, toggle(HIDE_PRESETS, tl!("Show Presets"), tl!("Hide Presets")));
@@ -922,9 +922,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option
set_part_hidden(app, key, hide);
}
MENU_ADD_TO_SWATCHES => {
if let Some(g) = current(app) {
save_to_swatches(app, &g);
}
let outcome = current(app).ok_or_else(|| tl!("No gradient to save").to_owned()).and_then(|g| save_to_swatches(app, &g));
return Some(outcome.map(|()| Value::Null));
}
MENU_REVERSE => edit(app, json!({"reverse": true}), Live::Released),
MENU_RESET => set_stops(app, &Gradient::default().stops, None, Live::Released),
+25 -1
View File
@@ -9,6 +9,30 @@ use vectorcraft_engine::Session;
use super::*;
use crate::tests::panel_harness::{Place, Shown, floated};
#[test]
fn add_to_swatches_requires_a_drawing_even_when_the_default_gradient_remains() {
let enabled = |app: &VectorcraftApp| {
let mut states = CommandStates::new();
menu_states(app, &mut states);
states.get(&CommandRef::new(MENU_ADD_TO_SWATCHES)).is_some_and(CommandState::is_enabled)
};
let mut app = app(json!({"gradient": {}}));
app.run("select.none", json!({})).unwrap();
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
assert!(enabled(&app));
app.session.execute("file.close", &json!({"index": 0})).unwrap();
assert!(current(&app).is_some(), "the default gradient remains visible without a drawing");
assert!(!enabled(&app), "there is no drawing to receive a swatch");
assert!(app.run(MENU_ADD_TO_SWATCHES, json!({})).is_err());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("paint.setFill", json!({"gradient": {}})).unwrap();
assert!(enabled(&app));
let before = app.session.active().unwrap().doc.swatches.len();
run(&mut app, MENU_ADD_TO_SWATCHES, &json!({})).unwrap().unwrap();
assert_eq!(app.session.active().unwrap().doc.swatches.len(), before + 1);
}
#[test]
fn dropped_colours_recolour_or_add_an_opaque_stop() {
let mut g = Gradient::default();
@@ -78,7 +102,7 @@ fn a_gradient_saved_as_a_swatch_keeps_its_stops_models_in_a_cmyk_document() {
let g = current(&app).expect("a gradient fill");
let colors = |g: &GradientPaint| g.gradient.stops.iter().map(|s| s.color).collect::<Vec<_>>();
assert_eq!(colors(&g), [Color::rgb8(255, 128, 0), Color::cmyk(0.0, 0.0, 0.0, 1.0)]);
save_to_swatches(&mut app, &g);
save_to_swatches(&mut app, &g).unwrap();
let Some(Paint::Gradient(saved)) = app.session.doc().unwrap().doc.swatches.last().map(|w| w.paint.clone()) else { panic!("a gradient swatch") };
assert_eq!(colors(&saved), colors(&g));
}
+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");
+37
View File
@@ -284,12 +284,49 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let scaling = app.ui_scaling();
app.run("view.setZoom", view_params(edited, region, print, scaling)).ok();
}
if let Some(invalid) = out.invalid_zoom {
app.status(invalid.message(&env));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn navigator_reports_a_malformed_zoom_entry() {
assert_malformed_zoom_entry_reported(show);
}
#[test]
fn status_bar_reports_a_malformed_zoom_entry() {
assert_malformed_zoom_entry_reported(crate::chrome::status_bar);
}
fn assert_malformed_zoom_entry_reported(draw: fn(&mut VectorcraftApp, &mut Ui)) {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.view_mut().unwrap().rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(460.0, 260.0));
app.run("view.setZoom", json!({"zoom": 100})).unwrap();
let mut panel = crate::tests::panel_harness::Panel::new(app, draw);
panel.app().ui.status.clear();
panel.type_into("Zoom", "80..2");
{
let app = panel.app();
assert!((app.view().unwrap().zoom - 0.8).abs() < 1e-9, "applies the valid prefix");
assert!(app.ui.status.contains("Closest value inserted"), "reports the partial entry: {:?}", app.ui.status);
}
panel.app().ui.status.clear();
panel.type_into("Zoom", "200");
{
let app = panel.app();
assert!((app.view().unwrap().zoom - 2.0).abs() < 1e-9, "still accepts a valid entry");
assert!(!app.ui.status.contains("Closest value inserted"), "does not warn for a valid entry");
}
}
/// A centre edit of the shifted view reaches `view.setZoom` as the document point it shows, and
/// an unedited view's centre is shifted by the region's corner.
#[test]
+33 -6
View File
@@ -8,8 +8,9 @@
// PLAN: assumed import paths for the framework items below (behavior::{IconId, Mixed}, keymap::CommandRef,
// text::ui::character, ui::{buttons, choice::Select, controls::Checkbox, menu, popover, runtime::access::PopupKind}).
use craft::behavior::{IconId, Mixed};
use craft::i18n::WordSet as _;
use craft::keymap::CommandRef;
use craft::text::ui::character::{DirectionRow, ParagraphChange, ParagraphControls, ParagraphDirection, ParagraphValues, TextAlign};
use craft::text::ui::character::{DirectionRow, ParagraphChange, ParagraphControls, ParagraphDirection, ParagraphValues, ParagraphWords, TextAlign};
use craft::ui::buttons::{IconButton, PopupMark, ToggleButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger};
@@ -21,6 +22,7 @@ use craft::ui::popover::Popover;
use craft::ui::primitives::{Glyph, IconSpec};
use craft::ui::runtime::access::PopupKind;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::runtime::env::{WordRows, WordsOverride, with_env};
use craft::ui::style::UiTokens;
use egui::{Color32, Painter, Rect, Stroke, Ui, vec2};
use serde_json::{Value, json};
@@ -821,6 +823,30 @@ fn kinsoku_row(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// Maps the toolkit's different English names to the translations already in the app catalogs.
fn localized_control_words() -> WordRows {
[
("paragraph.left", ALIGNMENTS[0].2),
("paragraph.center", ALIGNMENTS[1].2),
("paragraph.right", ALIGNMENTS[2].2),
("paragraph.justifyLeft", ALIGNMENTS[3].2),
("paragraph.justifyCenter", ALIGNMENTS[4].2),
("paragraph.justifyRight", ALIGNMENTS[5].2),
("paragraph.justifyAll", ALIGNMENTS[6].2),
("paragraph.spaceBefore", "Space Before Paragraph"),
("paragraph.spaceAfter", "Space After Paragraph"),
]
.into_iter()
.filter_map(|(id, source)| {
let translated = tl!(source);
if translated == source {
return None;
}
ParagraphWords::word(id).map(|word| (word, translated))
})
.fold(WordRows::new(), |rows, (word, translated)| rows.row(word, translated))
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some((_, para)) = text_style(app) else {
super::empty_state(ui, "pilcrow", tl!("No text selected"), tl!("Select a text object to edit its paragraph attributes."));
@@ -831,11 +857,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// Paragraph direction, with the Middle Eastern (Indic) options.
let direction = if app.session.prefs.show_indic_options { DirectionRow::Explicit } else { DirectionRow::Hidden };
// Indents and paragraph spacing are distances (General); type sizes follow Units ▸ Type.
let out = ParagraphControls::new(tl!("Paragraph"), &shown)
.unit(doc_unit(app.session.general_unit()))
.hyphenate(!hidden)
.direction_row(direction)
.show_with(ui, |ui| lists_row(app, ui));
let controls =
ParagraphControls::new(tl!("Paragraph"), &shown).unit(doc_unit(app.session.general_unit())).hyphenate(!hidden).direction_row(direction);
let words = localized_control_words();
let show = |ui: &mut Ui| controls.show_with(ui, |ui| lists_row(app, ui));
let out =
if words.iter().next().is_some() { with_env(ui, |overrides| overrides.words = Some(WordsOverride::Overlay(words)), show) } else { show(ui) };
for event in &out.edits {
edits::apply_event(app, event, &EditPath::Scope, &mut |app, change, _| apply(app, change));
}
@@ -25,6 +25,120 @@ fn editing_text(text: &str) -> (VectorcraftApp, Value) {
(app, id)
}
/// The minimum-width Paragraph dock keeps translated alignment and spacing controls usable.
#[test]
fn compact_paragraph_dock_keeps_localized_alignment_and_spacing_usable() {
use craft::behavior::dock::{DockEdge, Node, Workspace};
use egui::accesskit::Role;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2};
use std::sync::Arc;
let width = crate::panel_docking::PANEL_MIN_WIDTH;
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0));
let mut untranslated = Vec::new();
for lang in ["en", "de", "fr", "pt-br"] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.prefs.interface_language = lang.into();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id =
app.run("text.create", json!({"x": 20, "y": 50, "text": "First\nSecond", "area": {"width": 180, "height": 100}})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("window.panel", json!({"panel": "paragraph"})).unwrap();
app.run("window.panel.dock", json!({"panel": "paragraph", "column": true})).unwrap();
app.run("window.panel.activate", json!({"panel": "paragraph"})).unwrap();
let ws = &app.ui.dock_workspace;
let mut layout = ws.layout().clone();
let path = layout.dock_path(DockEdge::End).unwrap();
let mut node = layout.root.as_mut().unwrap();
for second_child in path {
let Node::Split { first, second, .. } = node else { panic!("end dock path") };
node = if second_child { second } else { first };
}
let Node::Dock { columns, .. } = node else { panic!("end dock") };
let column = columns.iter_mut().find(|column| column.groups.iter().any(|group| group.panels.iter().any(|p| p == "paragraph"))).unwrap();
assert!(!column.iconic);
column.width = Some(width);
let next = Workspace::from_parts(layout, ws.hidden().to_vec(), ws.floated().to_vec());
Arc::make_mut(&mut app.ui.dock_workspace).replace(next);
let ctx = crate::testing::ui_context();
ctx.enable_accesskit();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, mut events: Vec<Event>, modifiers| {
time += 0.05;
events.insert(0, Event::ModifiersChanged(modifiers));
let input = egui::RawInput { time: Some(time), events, screen_rect: Some(screen), ..Default::default() };
crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes)
};
for _ in 0..7 {
frame(&mut app, Vec::new(), Modifiers::NONE);
}
let nodes = frame(&mut app, Vec::new(), Modifiers::NONE);
let rect =
|node: &egui::accesskit::Node| node.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)));
let title = crate::i18n::t("Paragraph");
let (_, body_node) = nodes.iter().find(|(_, node)| node.role() == Role::TabPanel && node.label() == Some(title)).unwrap();
let body = rect(body_node).unwrap();
assert!((body.width() - width).abs() < 1.0, "{lang}: {body:?}");
let mut descendants = Vec::new();
let mut todo = body_node.children().to_vec();
while let Some(id) = todo.pop() {
let Some((_, node)) = nodes.iter().find(|(key, _)| *key == id) else { continue };
todo.extend(node.children());
if let (Some(label), Some(bounds)) = (node.label(), rect(node)) {
descendants.push((label, node.role(), bounds));
}
}
let mut control = |names: [&str; 2], role: Option<Role>| {
let (label, _, bounds) = descendants
.iter()
.find(|(label, kind, _)| {
role.is_none_or(|expected| *kind == expected) && names.iter().any(|name| *label == *name || *label == crate::i18n::t(name))
})
.unwrap_or_else(|| panic!("{lang}: no {names:?} with role {role:?}"));
assert!(bounds.is_positive() && body.expand(0.5).contains_rect(*bounds), "{lang}: {label} {bounds:?} outside {body:?}");
let expected = crate::i18n::t(names[1]);
if expected != names[1] && *label != expected {
untranslated.push(format!("{lang}: {label:?}, expected {expected:?}"));
}
bounds.center()
};
for names in [
["Left align text", "Align left"],
["Right align text", "Align right"],
["Justify last left", "Justify with last line aligned left"],
["Justify last centered", "Justify with last line aligned center"],
["Justify last right", "Justify with last line aligned right"],
["Justify all", "Justify all lines"],
] {
control(names, None);
}
let center = control(["Center text", "Align center"], None);
let before = control(["Add space before paragraph", "Space Before Paragraph"], Some(Role::SpinButton));
let after = control(["Add space after paragraph", "Space After Paragraph"], Some(Role::SpinButton));
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
let key = |key, modifiers, pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers };
frame(&mut app, vec![Event::PointerMoved(center), button(center, true)], Modifiers::NONE);
frame(&mut app, vec![button(center, false)], Modifiers::NONE);
frame(&mut app, Vec::new(), Modifiers::NONE);
assert_eq!(selected(&app), [Justify::Center], "{lang}: pointer changed alignment");
for (at, input) in [(before, "12"), (after, "18")] {
frame(&mut app, vec![Event::PointerMoved(at), button(at, true)], Modifiers::NONE);
frame(&mut app, vec![button(at, false)], Modifiers::NONE);
frame(&mut app, vec![key(Key::A, Modifiers::COMMAND, true)], Modifiers::COMMAND);
frame(&mut app, vec![key(Key::A, Modifiers::COMMAND, false), Event::Text(input.to_owned())], Modifiers::NONE);
frame(&mut app, vec![key(Key::Enter, Modifiers::NONE, true)], Modifiers::NONE);
frame(&mut app, vec![key(Key::Enter, Modifiers::NONE, false)], Modifiers::NONE);
}
assert_eq!(shared_para_field(&app, |p| p.space_before), Some(12.0), "{lang}: keyboard updated before");
assert_eq!(shared_para_field(&app, |p| p.space_after), Some(18.0), "{lang}: keyboard updated after");
crate::i18n::set_current(crate::i18n::Lang::EN);
}
assert!(untranslated.is_empty(), "lost Paragraph translations: {untranslated:?}");
}
fn select_range(app: &mut VectorcraftApp, start: usize, end: usize) {
app.session.set_tool_option("select", &json!({"start": start, "end": end}));
}
+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) {
@@ -1438,6 +1438,55 @@ fn a_stale_delete_symbol_question_deletes_nothing() {
assert_eq!(art(&app, "Dot"), (1, 0));
}
fn refuses_symbol_approval_after_revert(name: &str, choice: PromptChoice, after_fresh_approval: (usize, usize)) {
let mut app = windowed(leaf_and_dot());
let file = std::env::temp_dir().join(format!("vectorcraft-symbol-delete-{name}-{choice:?}-{}.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 leaf = instance_of(&app, "Leaf").unwrap();
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("symbol.place", json!({"name": "Leaf"})).unwrap();
assert_eq!(art(&app, "Leaf"), (2, 0));
symbol_delete::ask(&mut app, name, false);
assert_eq!(delete_question(&app), Some(name == "Leaf"));
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!(instance_of(&app, "Leaf"), Some(leaf));
assert_eq!(art(&app, "Leaf"), (1, 0));
let undo = st.history.undo.len();
choose(&mut app, choice);
assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "an old approval keeps the restored symbols");
assert_eq!(art(&app, "Leaf"), (1, 0), "the restored instance stays unmodified");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
symbol_delete::ask(&mut app, name, false);
choose(&mut app, choice);
assert!(!symbols(&mut app).iter().any(|symbol| symbol == name));
assert_eq!(art(&app, "Leaf"), after_fresh_approval);
}
#[test]
fn old_delete_symbol_yes_keeps_the_symbol_restored_by_revert() {
refuses_symbol_approval_after_revert("Dot", PromptChoice::Proceed, (1, 0));
}
#[test]
fn old_expand_instances_keeps_the_instance_restored_by_revert() {
refuses_symbol_approval_after_revert("Leaf", PromptChoice::Proceed, (0, 1));
}
#[test]
fn old_delete_instances_keeps_the_instance_restored_by_revert() {
refuses_symbol_approval_after_revert("Leaf", PromptChoice::Alternate, (0, 0));
}
/// The panel menu's Reset Transformation and the Control bar's Reset are enabled only while a
/// selected instance's scale, rotation or shear differs from its symbol's, and give the
/// instance its symbol's again.
@@ -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);
@@ -0,0 +1,418 @@
//! The stop/point popover uses the Color panel's real mode chooser.
// Integration tests may unwrap and panic (AGENTS.md, Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::{Mutex, MutexGuard};
use craft::behavior::OwnerClass;
use craft::color_ui::ui::ColorPanelMode as Mode;
use craft::ui::dialog::dialog_id;
use craft::ui::runtime::env::WindowKey;
use craft::ui::runtime::frame::take_output;
use craft::ui::runtime::overlay;
use craft::ui::shell::{WindowDialogs, embed};
use egui::accesskit::{Node, Role, Toggled};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
use serde_json::{Value, json};
use vectorcraft_color::{GradientPaint, Paint, cms};
use vectorcraft_engine::Session;
use vectorcraft_ui_egui::{VectorcraftApp, i18n};
static UI_STATE: Mutex<()> = Mutex::new(());
const MODES: [&str; 5] = ["Grayscale Slider", "RGB Sliders", "HSB Sliders", "CMYK Sliders", "Web Color Sliders"];
struct GlobalState {
language: i18n::Lang,
colors: cms::ColorSettings,
_lock: MutexGuard<'static, ()>,
}
impl GlobalState {
fn new() -> Self {
let lock = UI_STATE.lock().unwrap_or_else(|e| e.into_inner());
let language = i18n::current();
let colors = cms::active_settings();
i18n::set_current(i18n::Lang::EN);
cms::set_active(&cms::ColorSettings { rgb: cms::SRGB.into(), ..Default::default() }).unwrap();
Self { language, colors, _lock: lock }
}
}
impl Drop for GlobalState {
fn drop(&mut self) {
cms::set_active(&self.colors).unwrap();
i18n::set_current(self.language);
}
}
fn key(key: Key, pressed: bool) -> Event {
Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE }
}
struct Scene {
app: VectorcraftApp,
ctx: egui::Context,
size: egui::Vec2,
time: f64,
freeform: bool,
nodes: Vec<Node>,
}
impl Scene {
/// The app has the native runtime and fonts before its first frame.
fn new(size: egui::Vec2, freeform: bool) -> Self {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("app.language", json!({"lang": "en"})).unwrap();
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 120, "height": 100})).unwrap();
app.run(
"paint.setFill",
json!({"keepModel": true, "gradient": {
"kind": if freeform { "freeform" } else { "linear" },
"stops": [{"offset": 0, "color": "#2468ac"}, {"offset": 1, "color": "#e09020"}]
}}),
)
.unwrap();
app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap();
assert!(app.session.fill_active, "removing the stroke must retain the intended gradient fill proxy");
assert!(matches!(app.session.proxy_paints().0, Paint::Gradient(_)), "the actual active fill, not fallback markers, is a gradient");
app.select_tool("directSelection");
if freeform {
app.run("paint.freeform.selectPoint", json!({"index": 0})).unwrap();
} else {
app.run("gradient.selectStop", json!({"index": 0})).unwrap();
}
app.run("window.panel", json!({"panel": "gradient"})).unwrap();
let ctx = egui::Context::default();
embed::install(&ctx, craft::ui::testing::install_spec(), &vectorcraft_ui_egui::ui_fonts()).unwrap();
app.adopt_context(&ctx);
ctx.enable_accesskit();
Self { app, ctx, size, time: 0.0, freeform, nodes: vec![] }
}
fn frame(&mut self, events: Vec<Event>) {
self.time += 1.0 / 60.0;
// The normal host tick selects the App's language before painting, too.
i18n::set_current(self.app.ui_language());
let mut raw = RawInput {
events,
time: Some(self.time),
focused: true,
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, self.size)),
..Default::default()
};
self.app.raw_input(&self.ctx, &mut raw);
embed::before_input(&self.ctx, |out| self.app.frame_input(out));
let mut output = self.ctx.run_ui(raw, |ui| {
self.app.tick(ui.ctx());
self.app.ui(ui);
});
let _ = self.app.frame_input(take_output(&self.ctx));
self.nodes =
output.platform_output.accesskit_update.as_ref().expect("AccessKit enabled").nodes.iter().map(|(_, node)| node.clone()).collect();
output.textures_delta.clear();
}
fn idle(&mut self, count: usize) {
for _ in 0..count {
self.frame(vec![]);
}
}
fn click_with(&mut self, point: Pos2, modifiers: Modifiers) {
self.frame(vec![Event::ModifiersChanged(modifiers), Event::PointerMoved(point)]);
self.frame(vec![Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers }]);
self.frame(vec![Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers }]);
self.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
}
fn click(&mut self, point: Pos2) {
self.click_with(point, Modifiers::NONE);
}
fn escape(&mut self) {
self.frame(vec![key(Key::Escape, true)]);
self.frame(vec![key(Key::Escape, false)]);
self.idle(2);
}
fn node_rect(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)))
}
fn popover(&self) -> Rect {
self.nodes
.iter()
.find(|n| n.role() == Role::Dialog && n.label() == Some("Gradient stop"))
.and_then(Self::node_rect)
.expect("the actual native stop popover")
}
fn editor_open(&self) -> bool {
WindowDialogs::of(&self.ctx, &WindowKey::main()).with(|host| host.open_dialogs().iter().any(|d| d.id == dialog_id("gradientStop")))
}
fn assert_editor(&self) {
assert!(self.editor_open(), "the real stop/point editor remains open");
}
fn child_open(&self) -> bool {
overlay::top(&self.ctx).and_then(|id| overlay::entry(&self.ctx, id)).is_some_and(|entry| !entry.exiting && entry.keys == OwnerClass::Menu)
}
fn open_stop(&mut self) {
self.idle(8);
let name = if self.freeform { "Edit the point" } else { "Edit the stop" };
let matches: Vec<_> = self.nodes.iter().filter(|node| node.label() == Some(name)).filter_map(Self::node_rect).collect();
assert_eq!(matches.len(), 1, "the actual Gradient panel's color chip {name}");
self.click(matches[0].center());
self.idle(3);
self.assert_editor();
if self.freeform {
assert_eq!(self.app.session.selected_freeform_point(), Some(0));
} else {
assert_eq!(self.app.session.selected_stop(), Some(0));
}
}
fn button(&self, label: &str) -> Rect {
let popover = self.popover();
let matches: Vec<_> = self
.nodes
.iter()
.filter(|node| node.role() == Role::Button && node.label() == Some(label))
.filter_map(Self::node_rect)
.filter(|rect| rect.is_positive() && popover.contains(rect.center()))
.collect();
assert_eq!(matches.len(), 1, "one actual native mode chooser {label:?}");
matches[0]
}
fn open_mode(&mut self, label: &str) {
self.assert_editor();
let button = self.button(label);
assert!(self.popover().contains(button.center()));
self.click(button.center());
self.idle(3);
assert!(self.child_open(), "actual child menu opens");
self.assert_editor();
}
fn mode_rows(&self) -> Vec<(String, bool, Rect)> {
let mut rows: Vec<_> = self
.nodes
.iter()
.filter_map(|node| {
let label = node.label()?;
if !matches!(node.role(), Role::MenuItem | Role::MenuItemRadio | Role::MenuItemCheckBox) || !MODES.contains(&label) {
return None;
}
Some((label.to_owned(), node.toggled() == Some(Toggled::True), Self::node_rect(node)?))
})
.collect();
rows.sort_by(|a, b| a.2.top().total_cmp(&b.2.top()));
rows
}
fn assert_modes(&self, current: Option<&str>) {
let rows = self.mode_rows();
assert_eq!(rows.iter().map(|(label, _, _)| label.as_str()).collect::<Vec<_>>(), MODES);
for (label, checked, rect) in rows {
assert_eq!(checked, current == Some(label.as_str()), "current row: {label}");
assert!(Rect::from_min_size(Pos2::ZERO, self.size).contains(rect.center()));
}
}
fn choose_mode(&mut self, label: &str) -> Rect {
let rows = self.mode_rows();
let rect = rows.iter().find(|(text, _, _)| text == label).expect("actual offered mode").2;
self.click(rect.center());
self.idle(3);
assert!(!self.child_open(), "picking a mode closes only its dropdown");
self.assert_editor();
rect
}
fn gradient(&self) -> GradientPaint {
let Paint::Gradient(g) = self.app.session.proxy_paints().0 else { panic!("gradient fill") };
*g
}
fn snapshot(&self) -> Value {
let state = self.app.session.active().unwrap();
json!({"doc": state.doc.as_ref(), "selection": state.selection,
"undo": state.history.undo.iter().map(|e| json!({"label":e.label,"doc":e.doc.as_ref(),"selection":e.selection.as_ref()})).collect::<Vec<_>>(),
"redo": state.history.redo.iter().map(|e| json!({"label":e.label,"doc":e.doc.as_ref(),"selection":e.selection.as_ref()})).collect::<Vec<_>>(),
"step": state.history.step(), "stop": self.app.session.selected_stop(), "point": self.app.session.selected_freeform_point()})
}
fn geometry(&self) -> Value {
let state = self.app.session.active().unwrap();
json!(state.selection.objects.iter().map(|id| &state.doc.node(*id).unwrap().kind).collect::<Vec<_>>())
}
fn spectrum(&self) -> Rect {
let popover = self.popover();
let found: Vec<_> = self
.nodes
.iter()
// The component and its interactive bar share a name; only the bar carries the mode value.
.filter(|node| node.role() == Role::Group && node.label() == Some("Color Ramp") && node.value() == Some("RGB Sliders"))
.filter_map(Self::node_rect)
.filter(|rect| popover.contains(rect.center()))
.collect();
assert_eq!(found.len(), 1, "the actual native Color panel spectrum");
found[0]
}
}
#[test]
fn gradient_stop_mode_baseline_shift_and_menu_are_display_only() {
let _globals = GlobalState::new();
let mut scene = Scene::new(vec2(960.0, 720.0), false);
scene.open_stop();
let before = scene.snapshot();
let original = scene.gradient();
assert_eq!(original.gradient.stops[0].color.model(), cms::Model::Rgb);
// Retain the existing Shift control through the native panel's local-to-app synchronization.
scene.click_with(scene.spectrum().center(), Modifiers::SHIFT);
scene.idle(3);
assert_eq!(scene.app.ui.color_panel.mode, Mode::HsbSliders);
assert_eq!(scene.snapshot(), before, "Shift cycling changes display, not art/history");
scene.open_mode("HSB Sliders");
scene.assert_modes(Some("HSB Sliders"));
assert_eq!(scene.snapshot(), before, "opening the menu is not an edit");
scene.escape();
assert!(!scene.child_open());
scene.assert_editor();
assert_eq!(scene.snapshot(), before);
scene.open_mode("HSB Sliders");
scene.choose_mode("RGB Sliders");
scene.open_mode("RGB Sliders");
scene.assert_modes(Some("RGB Sliders"));
scene.choose_mode("HSB Sliders");
assert_eq!(scene.gradient(), original);
assert_eq!(scene.snapshot(), before, "RGB/HSB preserve native RGB and one-stop selection");
scene.escape();
assert!(!scene.editor_open(), "after dropdown dismissal the next Escape closes the editor");
assert_eq!(scene.snapshot(), before);
}
#[test]
fn gradient_stop_mode_converts_only_selected_stop_and_unlinks_tint_with_one_undo() {
let _globals = GlobalState::new();
for tint in [false, true] {
let mut scene = Scene::new(vec2(960.0, 720.0), false);
if tint {
scene.app.run("swatch.new", json!({"name":"Ink","color":{"c":0,"m":1,"y":0,"k":0},"spot":true})).unwrap();
scene
.app
.run(
"paint.setFill",
json!({"gradient":{"stops":[
{"offset":0,"swatch":"Ink","tint":50}, {"offset":1,"color":"#e09020"}
]}}),
)
.unwrap();
}
scene.open_stop();
let before = scene.snapshot();
let original = scene.gradient();
let geometry = scene.geometry();
let undo = scene.app.session.active().unwrap().history.undo.len();
if tint {
assert_eq!(original.gradient.stops[0].swatch.as_deref(), Some("Ink"));
assert!((original.gradient.stops[0].tint - 0.5).abs() < 1e-6);
}
scene.open_mode(if tint { "Tint" } else { "RGB Sliders" });
scene.assert_modes(if tint { None } else { Some("RGB Sliders") });
scene.choose_mode("CMYK Sliders");
let converted = scene.gradient();
assert_eq!(converted.gradient.stops[0].color.model(), cms::Model::Cmyk);
assert!(converted.gradient.stops[0].swatch.is_none(), "process mode unlinks a tint");
let mut expected = original.clone();
expected.gradient.stops[0].color = converted.gradient.stops[0].color;
expected.gradient.stops[0].swatch = None;
expected.gradient.stops[0].tint = 1.0;
expected.gradient.stops[0].plates = None;
assert_eq!(converted, expected, "other stops, placement and gradient settings are untouched");
assert_eq!(scene.geometry(), geometry);
assert_eq!(scene.app.session.active().unwrap().history.undo.len(), undo + 1);
scene.app.run("edit.undo", json!({})).unwrap();
assert_eq!(serde_json::to_value(scene.app.session.active().unwrap().doc.as_ref()).unwrap(), before["doc"]);
assert_eq!(scene.gradient(), original);
if !tint {
// Hide Options is the existing compact mixer; its child menu can outgrow the editor.
scene.app.run("ui.colorPanel", json!({"options": false})).unwrap();
scene.idle(3);
scene.open_mode("RGB Sliders");
scene.assert_modes(Some("RGB Sliders"));
let row = scene.mode_rows().into_iter().find(|(label, _, _)| label == "Web Color Sliders").unwrap().2;
let parent = scene.popover();
assert!(!parent.contains(row.center()), "compact editor must expose a real child row outside itself: parent={parent:?}, row={row:?}");
scene.choose_mode("Web Color Sliders");
assert_eq!(scene.app.ui.color_panel.mode, Mode::WebColorSliders);
assert_ne!(
scene.gradient().gradient.stops[0].color,
original.gradient.stops[0].color,
"the original non-web-safe RGB stop is actually converted"
);
assert_eq!(scene.geometry(), geometry);
scene.app.run("edit.undo", json!({})).unwrap();
assert_eq!(serde_json::to_value(scene.app.session.active().unwrap().doc.as_ref()).unwrap(), before["doc"]);
assert_eq!(scene.gradient(), original, "one Undo restores the pre-conversion paint");
}
// A real outside click closes both editor and child, without another edit.
scene.idle(3);
// Undo restores art, while the chosen display mode remains a UI preference.
scene.open_mode(if tint { "Tint" } else { "Web Color Sliders" });
let closed_boundary = scene.snapshot();
let outside = pos2(2.0, scene.size.y - 2.0);
assert!(!scene.popover().contains(outside));
assert!(scene.mode_rows().iter().all(|(_, _, r)| !r.contains(outside)));
scene.click(outside);
scene.idle(3);
assert!(!scene.editor_open());
assert!(!scene.child_open());
assert_eq!(scene.snapshot(), closed_boundary);
}
}
#[test]
fn gradient_stop_mode_freeform_point_uses_the_same_real_menu() {
let _globals = GlobalState::new();
let mut scene = Scene::new(vec2(960.0, 720.0), true);
scene.open_stop();
let before = scene.snapshot();
let original = scene.gradient();
scene.open_mode("RGB Sliders");
scene.assert_modes(Some("RGB Sliders"));
scene.choose_mode("HSB Sliders");
assert_eq!(scene.app.ui.color_panel.mode, Mode::HsbSliders);
assert_eq!(scene.gradient(), original, "display-only point editing keeps every freeform point");
assert_eq!(scene.snapshot(), before);
let (points, _) = scene.app.session.proxy_freeform(false).unwrap();
let undo = scene.app.session.active().unwrap().history.undo.len();
let geometry = scene.geometry();
scene.open_mode("HSB Sliders");
scene.choose_mode("CMYK Sliders");
let (converted, _) = scene.app.session.proxy_freeform(false).unwrap();
assert_eq!(converted.points[0].color.model(), cms::Model::Cmyk);
let mut expected = points;
expected.points[0].color = converted.points[0].color;
assert_eq!(converted, expected, "conversion changes only the selected freeform point's color");
assert_eq!(scene.geometry(), geometry);
assert_eq!(scene.app.session.active().unwrap().history.undo.len(), undo + 1);
scene.app.run("edit.undo", json!({})).unwrap();
assert_eq!(serde_json::to_value(scene.app.session.active().unwrap().doc.as_ref()).unwrap(), before["doc"]);
assert_eq!(scene.gradient(), original, "one Undo restores the complete point paint");
scene.idle(3);
let boundary = scene.snapshot();
scene.open_mode("RGB Sliders");
scene.escape();
scene.assert_editor();
scene.escape();
assert!(!scene.editor_open());
assert_eq!(scene.snapshot(), boundary, "both Escape stages preserve artwork and history");
}
+4 -1
View File
@@ -1,6 +1,6 @@
# Gaps
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as lLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups <g>, or as lLine truncated
> Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged.
@@ -167,6 +167,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall
## G1 Interaction fidelity
- **Done (#7918):** The gradient stop editor’s Color tab offers the Color panel’s five color modes without Shift-clicking the spectrum, sharing its saved mode, conversions and tint unlinking. Mode selection keeps the editor open, with the menu taking Escape first. Evidence: `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs`. Broader G1 scope and estimates unchanged.
- **#7237, request 3 only:** Space during an ordinary path's Direct Selection direction-handle drag moves the owning anchor and both handles, including while Direct Selection is lent from the Pen; releasing Space resumes handle adjustment and the Pen can continue the same path. The separate handle-hover label request remains open. See the Direct Selection checklist and validation evidence in [ui-parity.md](ui-parity.md) and [target-app-parity.md](target-app-parity.md#evidence-what-ships-today-by-area). Scores and estimates unchanged.
macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate.
@@ -1013,6 +1015,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv
| Date | Change | Summary |
|---|---|---|
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12: Document Info › Selection Only (`ui.docInfo.selectionOnly`) counts objects in the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
| 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. |
+3 -2
View File
@@ -1,6 +1,6 @@
# Roadmap: milestones and what's next
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object anLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object anLine truncated
>
> Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865).
@@ -190,7 +190,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
| M0 | Skeleton + vertical slice | ✅ done | — |
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 |
| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 |
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding Line truncated
| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 |
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 |
@@ -247,6 +247,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours
|---|---|---|
| 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. |
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
+4 -2
View File
@@ -2,7 +2,7 @@
Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written.
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and esLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and esLine truncated
>
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
>
@@ -324,7 +324,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de
| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) |
| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged |
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) |
| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) |
| Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` |
| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged |
@@ -2157,6 +2157,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Hue Clockwise and Hue Counterclockwise, VectorCraft's own gradient methods, in the Gradient panel's Method menu and on `paint.editGradient` and `paint.setFill` (`method`: `hue-clockwise`, `hue-counterclockwise`): a linear, radial, conic or diamond gradient's colors mix around the hue wheel, with hue, saturation and brightness each changing evenly from one stop to the next and the hue angle keeping one direction, as the fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do: falling with Hue Clockwise (red, magenta, blue), which is clockwise on the color wheels, and rising with Hue Counterclockwise (red, yellow, green). Hues less than half a color level apart count as one hue, so a color and its tint do not turn the wheel. A gray stop takes the hue of the stop it mixes with, and black its saturation too. The canvas and raster exports draw it through stops on that curve, within half a color level; Reverse Gradient turns the method the other way with the stops, so the ramp keeps its colors. SVG and PDF write it as an RGB image, EPS as a shading in process colors, and a legacy `.ai` file and the `.ai` editing data with the colors between its stops as stops of their own, with a warning.
- Gradient spread, VectorCraft's own setting: Pad, Repeat or Reflect, with a Repeats count of 1 to 100, in the Gradient panel and on `paint.editGradient` and `paint.setFill`; Repeat and Reflect run a linear, radial, conic or diamond gradient's stops that many times along the vector and on past its ends, the Gradient tool marks where the runs meet, and SVG writes and reads `spreadMethod`, CSS writes repeating gradients, PDF writes a conic's sweep shading over one run and the other kinds with their stops repeated across the shape, as EPS, legacy `.ai` and the `.ai` editing data do.
- The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681).
- The stop editor’s Color tab has a compact menu named for the current mode: Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders or Web Color Sliders (#7918). It shares the Color panel’s saved mode and color conversion, including making a linked tint a process color. A mode choice keeps the editor open; Escape closes the menu before the editor, and a click outside both closes the editor. The same controls edit a freeform point. Evidence: `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs`.
Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)).
Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)).
With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke.
@@ -3314,6 +3315,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s
|---|---|---|
| 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. |
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
| 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12: Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. |
+3 -1
View File
@@ -1,6 +1,6 @@
# UI and interaction parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores andLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores andLine truncated
>
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
>
@@ -531,6 +531,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Gradient panel: Method, Classic or Perceptual (30.0) | done | Method menu under the Stroke buttons for linear and radial gradients (`paint.editGradient` `method`); [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html); `panels::gradient` test |
| Gradient panel: Presets (30.0) | done | Presets menu by library (theme) plus Saved: applies a preset to the gradient behind the active proxy, keeping its placement, one undo step; panel menu Save Gradient Preset…, Delete Gradient Preset, Hide/Show Presets (`gradient.presets.*`); `panels::gradient` tests |
| Gradient panel: delete a stop | done | Delete Stop at the right end of the ramp deletes the selected stop, and a stop dragged down off the ramp is deleted on release, never below two stops, one undo step each; [Gradient panel options](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html); `panels::gradient` test |
| Gradient stop editor: Color mode menu | done | Compact current-mode menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion; a choice keeps the editor open, Escape closes the menu first, and clicking outside both dismisses the editor (#7918); `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs` |
| Gradient tool: the annotator's end handle changes the length; Alt-drag changes the length and angle together | done | A plain drag keeps the end on the bar's line, at least 10 px from the start (VectorCraft's own minimum); Alt-drag moves it freely, Shift with Alt at 45° steps; [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); `xform::gradient` tests |
| Workspaces (save, reset, switch); each remembers the layout changes made in it across switches and restarts until Reset <name> | done | `UiState::workspace_changes` |
| Opening a file: after 0.4 s a progress window with the file name, a moving bar (reading counts no steps), how many more files wait, Cancel (Esc: the file doesn't open) and Continue in Background; never over another dialog or progress window | done | #5930; `opening::show`, `file.cancelOpen`, `file.openInBackground`. A save that runs in the background shows the same window, with how many more saves wait; its Cancel (`file.cancelSave`) stops the save before it replaces the file, which stays as it was. A save whose file is already being replaced finishes and is reported as saved, and a save of several files (EPS with Use Artboards) whose first file is in place writes the rest. Its Continue in Background is `file.saveInBackground` (the help page lists each background save's progress with a Cancel button: https://helpx.adobe.com/illustrator/using/saving-artwork.html). A place that takes longer than 0.4 s shows the progress window with Cancel (`placing::show`, `file.cancelPlace`); Close still shows only the status bar's spinner (Close is immediate) |
@@ -644,6 +645,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra
|---|---|---|
| 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. |
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. |