Merge remote-tracking branch 'origin/main' into pr-8983

# Conflicts:
#	docs/gaps.md
#	docs/target-app-parity.md
This commit is contained in:
FredApps
2026-11-26 22:58:34 +07:00
41 changed files with 1583 additions and 150 deletions
+1 -2
View File
@@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
let mut ends = vec![0.0];
for ch in 0..3 {
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) {
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
+4 -3
View File
@@ -141,7 +141,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Contrast",
[],
None,
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
always,
contrast
),
@@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
.transpose()
};
let drawing;
// Selected objects that share a color but draw it differently have no one answer.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) {
// Selected objects that share a color but draw it differently have no one answer. While the
// active tool paints with the proxy's color, the selection does not draw it.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) {
let item = s.appearance_item();
// Every painted object inside a selected group counts, as the proxy's color comes from all,
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
+15 -7
View File
@@ -710,6 +710,12 @@ impl Prefs {
}
impl Session {
/// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a
/// reset of every category. A frontend resets the settings it keeps itself in them.
pub fn take_prefs_resets(&mut self) -> Vec<Option<&'static str>> {
std::mem::take(&mut self.prefs_resets)
}
/// Replace the preferences and push the ones with engine-side consumers into open documents
/// and the renderer (grid, history depth, render threads).
pub fn apply_prefs(&mut self, mut p: Prefs) {
@@ -817,7 +823,7 @@ pub fn specs() -> Vec<CommandSpec> {
always,
set
),
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset),
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
cmd!(
query "prefs.export",
@@ -1000,15 +1006,17 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
fn reset(s: &mut Session, p: &Value) -> Result<Value> {
let cat = str_param(p, "category");
if let Some(c) = cat
&& !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c))
{
return Err(bad("prefs.reset", format!("unknown category `{c}`")));
}
let cat = text_param(p, "category", "prefs.reset")?;
let known = |c: &str| {
PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`")))
};
let category = cat.map(known).transpose()?;
let mut next = s.prefs.clone();
next.reset(cat);
s.apply_prefs(next);
if !s.prefs_resets.contains(&category) {
s.prefs_resets.push(category);
}
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
}
+1 -1
View File
@@ -248,7 +248,7 @@ impl History {
/// The document at row `row` of the History panel, `now` being the document now: the rows before
/// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first.
pub(crate) fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
pub fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
let current = self.undo.len();
match row.cmp(&current) {
std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc),
+2
View File
@@ -136,6 +136,8 @@ pub struct Session {
/// Set when a command that draws a shape was journaled outside saved steps
/// ([`Session::take_shape_drawn`]).
shape_drawn: bool,
/// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]).
prefs_resets: Vec<Option<&'static str>>,
/// Set when the active tool panicked (see [`guard`]); reported by the next tool event.
tool_panic: Option<EngineError>,
/// How many times switching or closing documents, or replacing the active one, has started the
+1
View File
@@ -78,6 +78,7 @@ impl Session {
depth: 0,
replaying: false,
shape_drawn: false,
prefs_resets: Vec::new(),
tool_panic: None,
tool_resets: 0,
tool_set_since_reset: false,
+25
View File
@@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() {
assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}");
}
/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the
/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no
/// error.
#[test]
fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap();
let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap());
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
let bucket = s.execute("color.contrast", &json!({})).unwrap();
assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}");
assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}");
// A second selected object drawn at another opacity does not make the answer ambiguous.
s.select_tool("selection", ViewInfo::default()).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
let both = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}");
}
#[test]
fn a_translucent_group_counts_for_the_art_inside_it() {
let mut s = session();
+18
View File
@@ -216,6 +216,24 @@ fn reset_category_and_all() {
assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err());
}
/// `prefs.reset` records each category it reset once, `None` for every category, and a failed
/// reset records nothing.
#[test]
fn prefs_reset_records_the_categories_it_reset() {
let mut s = Session::new();
assert!(s.take_prefs_resets().is_empty());
s.execute("prefs.reset", &json!({"category": "general"})).unwrap();
s.execute("prefs.reset", &json!({"category": "General"})).unwrap();
assert_eq!(s.take_prefs_resets(), vec![Some("General")]);
assert!(s.take_prefs_resets().is_empty(), "taking clears the list");
assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err());
assert!(s.execute("prefs.reset", &json!({"category": 5})).is_err());
assert!(s.take_prefs_resets().is_empty(), "a failed reset records nothing");
s.execute("prefs.reset", &json!({})).unwrap();
s.execute("prefs.reset", &json!({"category": "Type"})).unwrap();
assert_eq!(s.take_prefs_resets(), vec![None, Some("Type")]);
}
/// A rectangle made into a guide path; nothing is selected after.
fn guide_path(s: &mut Session, x: f64) -> NodeId {
let id = square(s, x, 0.0);
+95 -7
View File
@@ -86,6 +86,9 @@ struct Drag {
/// when the Alt state at the release changes what it transforms.
pointer: Point,
shift: bool,
/// The pointer's own movement since the press, before snapping: a snapped press can turn a
/// level drag diagonal, so Scale's Shift-drag uses this to pick an axis (#6324).
moved: Vec2,
last: Affine,
/// The document revision at the press: a press whose document or selection changes before it
/// becomes a drag is dropped, so its reference point is never applied to other objects.
@@ -100,6 +103,16 @@ impl Drag {
}
}
/// The pointer drag [`TransformTool::solve`] turns into a transform.
struct SolveDrag {
start: Point,
p: Point,
/// The pointer's own movement since the press, before snapping (#6324).
moved: Vec2,
shift: bool,
bounds: Rect,
}
/// The first point of a Reflect axis set by a click, waiting for the second point, with the
/// selection and the document revision it was set for.
#[derive(Clone, Debug)]
@@ -222,7 +235,7 @@ impl TransformTool {
/// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the
/// line the pointer draws on the page.
pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) {
let (m, a, b) = self.solve(angle, o, start, p, shift, bounds);
let (m, a, b) = self.solve(angle, o, SolveDrag { start, p, moved: p - start, shift, bounds });
(m, self.label(a, b))
}
@@ -253,7 +266,8 @@ impl TransformTool {
/// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height
/// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as
/// `object.shear` takes it (Shear).
fn solve(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, f64, f64) {
fn solve(&self, angle: f64, o: Point, d: SolveDrag) -> (Affine, f64, f64) {
let SolveDrag { start, p, moved, shift, bounds } = d;
let frame = OrientedBox { angle, rect: Rect::ZERO };
let local = |v: Vec2| frame.to_doc().inverse() * v.to_point();
match self.kind {
@@ -276,7 +290,18 @@ impl TransformTool {
let d1 = local(p - o).to_vec2();
let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 };
let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y));
if shift {
// Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal
// one uniformly (#6324). The pointer's own movement decides, in the box's axes; a
// snapped press can otherwise turn a level drag diagonal. A drag that starts level
// with the reference point on that axis has nothing to scale it by, so it stays uniform.
let moved_local = local(moved).to_vec2();
let axis_angle = moved_local.y.abs().atan2(moved_local.x.abs()).to_degrees();
let along = moved_local.hypot() > 1e-9;
if shift && along && axis_angle <= 22.5 && d0.x.abs() > 1e-6 {
sy = 1.0;
} else if shift && along && axis_angle >= 67.5 && d0.y.abs() > 1e-6 {
sx = 1.0;
} else if shift {
let l2 = d0.hypot2();
let k = if l2 > 1e-12 { d1.dot(d0) / l2 } else { 1.0 };
sx = k;
@@ -380,6 +405,7 @@ impl Tool for TransformTool {
anchors,
pointer: p,
shift: false,
moved: Vec2::ZERO,
last: Affine::IDENTITY,
revision: cx.revision,
});
@@ -406,10 +432,15 @@ impl Tool for TransformTool {
Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) });
out.push(Action::Begin(self.kind.label().into()));
}
let moved = p - d.start;
let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p));
self.hover = guides;
let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds);
(d.last, d.pointer, d.shift) = (m, p, ev.mods.shift);
let (m, a, b) = self.solve(
d.angle_for(ev.mods.alt, ev.backquote),
d.origin,
SolveDrag { start: d.pick, p, moved, shift: ev.mods.shift, bounds: d.bounds },
);
(d.last, d.pointer, d.shift, d.moved) = (m, p, ev.mods.shift, moved);
self.drag = Some(d);
self.measure = Some((p, self.label(a, b)));
self.readout = Some(self.readout_of(m, a, b, d.bounds));
@@ -423,7 +454,12 @@ impl Tool for TransformTool {
// or moves only pattern tiles, and with anchors selected, whether it acts
// along the box or the page.
let m = if d.anchors {
self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0
self.solve(
d.angle_for(ev.mods.alt, ev.backquote),
d.origin,
SolveDrag { start: d.pick, p: d.pointer, moved: d.moved, shift: d.shift, bounds: d.bounds },
)
.0
} else {
d.last
};
@@ -445,7 +481,11 @@ impl Tool for TransformTool {
}
self.drop_axis();
let copy = ev.mods.alt;
let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds);
let (m, _, _) = self.solve(
d.angle_for(copy, ev.backquote),
first,
SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds },
);
vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit]
} else {
// A click sets the reference point; with Alt, it opens the dialog too. With the
@@ -741,6 +781,54 @@ mod tests {
assert!((c[0] - c[3]).abs() < 1e-9 && c[0] > 1.0);
}
/// A Shift-drag along one axis scales along that axis alone, and a diagonal one scales
/// uniformly (#6324): the drag's own direction decides, within 22.5° of an axis.
#[test]
fn scale_shift_follows_the_drag_direction() {
let t = TransformTool::new(TransformKind::Scale);
let o = Point::new(100.0, 100.0);
let scales = |p: Point| {
let c = t.matrix_for(o, Point::new(150.0, 140.0), p, true, Rect::ZERO).0.as_coeffs();
(c[0], c[3])
};
// Sideways, a little off the level: width only.
let (sx, sy) = scales(Point::new(200.0, 145.0));
assert!((sx - 2.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9, "{sx} {sy}");
// Up or down: height only.
let (sx, sy) = scales(Point::new(148.0, 180.0));
assert!((sx - 1.0).abs() < 1e-9 && (sy - 2.0).abs() < 1e-9, "{sx} {sy}");
// Diagonal: both, by the same factor.
let (sx, sy) = scales(Point::new(200.0, 180.0));
assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}");
// A drag that starts straight above (beside) the reference point has no width (height) to
// scale, so a sideways (up or down) Shift-drag from there scales uniformly, as before.
let from = |start: Point, p: Point| {
let c = t.matrix_for(o, start, p, true, Rect::ZERO).0.as_coeffs();
(c[0], c[3])
};
let (sx, sy) = from(Point::new(100.0, 150.0), Point::new(150.0, 160.0));
assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}");
let (sx, sy) = from(Point::new(150.0, 100.0), Point::new(160.0, 150.0));
assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}");
}
/// The axis of a Shift-drag comes from the pointer's own movement: a press near a corner
/// snaps to it, and a level drag from there still scales the width alone.
#[test]
fn scale_shift_axis_follows_the_pointer_not_the_snapped_press() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Default::default() };
let mut t = TransformTool::new(TransformKind::Scale);
t.pointer(&cx, &ev(PointerKind::Down, 198.0, 203.0).with_mods(shift));
let drag = t.pointer(&cx, &ev(PointerKind::Drag, 205.0, 203.0).with_mods(shift));
let c = matrix(drag.last().expect("a preview")).as_coeffs();
assert!((c[0] - 1.1).abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9, "the width alone: {c:?}");
}
#[test]
fn alt_click_opens_dialog_and_alt_release_copies() {
let (d, id) = doc_with_rect();
+3
View File
@@ -544,6 +544,9 @@ impl VectorcraftApp {
if let Some(wait) = crate::panels::actions::tick_playback(self, now) {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
}
// A `prefs.reset` run in this frame outside `Self::run` (a script's, say): the pass that follows draws the
// reset rows.
prefs_dialog::apply_prefs_resets(self);
}
/// The canvas panel's body: the document tabs, then the canvas (a pane for each document while
+3
View File
@@ -77,7 +77,10 @@ impl VectorcraftApp {
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
self.beacon.command(id);
let touch_workspace = self.session.prefs.touch_workspace;
// A `prefs.reset` that ran straight on the session applies before this command can switch workspaces.
crate::prefs_dialog::apply_prefs_resets(self);
let result = self.run_now(id, params);
crate::prefs_dialog::apply_prefs_resets(self);
if id == "prefs.import" && result.is_ok() {
crate::prefs_dialog::imported(self, touch_workspace);
}
+4
View File
@@ -109,6 +109,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) {
app.ui.home = None;
}
// The Home screen and the empty window show no marks: a closed document's text nodes are not kept.
if app.session.active().is_none() {
marks::release_text_marks(app);
}
let full = ui.available_rect_before_wrap();
if crate::menus::home_showing(app) {
// No type editor shows to lose the keys: the marked text stays as typed.
+8 -3
View File
@@ -160,6 +160,13 @@ pub(crate) struct Marks {
artboard_marks: Vec<BezPath>,
}
/// Drops the hidden-character and spelling memos and the text nodes they hold.
pub(crate) fn release_text_marks(app: &mut VectorcraftApp) {
app.canvas.hidden_chars.marks.clear();
app.canvas.spelling = SpellingMarks::default();
app.canvas.text_nodes = TextNodes::default();
}
/// The marks of one canvas pass over `view`. The memos of [`crate::CanvasCache`] are kept while their
/// gate is on and dropped, with the text nodes they hold, when it is off.
pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
@@ -183,9 +190,7 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
let fades = artboards::fades_outside_artboards(app);
let shows_artboards = artboards::shows_artboards(app);
let Some(st) = app.session.active() else {
app.canvas.hidden_chars.marks.clear();
app.canvas.spelling = SpellingMarks::default();
app.canvas.text_nodes = TextNodes::default();
release_text_marks(app);
return m;
};
let key = (st.uid, st.revision);
+26
View File
@@ -122,6 +122,32 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() {
assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept");
}
/// Closing the last document drops the memos' text nodes on the canvas's next frame, whether it
/// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window.
#[test]
fn a_canvas_frame_without_a_document_releases_the_text_nodes() {
let ctx = crate::testing::ui_context();
let frame = |app: &mut VectorcraftApp| {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() };
crate::testing::part_frame(app, &ctx, raw, crate::canvas::show);
};
for home in [true, false] {
let mut app = app();
app.session.execute("prefs.set", &json!({"key": "showHomeScreen", "value": home})).unwrap();
text(&mut app, 20, 60, "one\ttwo qzxv\nthree");
app.ui.view.hidden_chars = true;
app.ui.view.auto_spell_check = true;
frame(&mut app);
assert!(app.canvas.text_nodes.list.is_some() && !app.canvas.hidden_chars.marks.is_empty(), "home {home}: the canvas keeps the memos");
app.session.execute("file.close", &json!({})).unwrap();
assert_eq!(crate::menus::home_showing(&app), home);
frame(&mut app);
assert!(app.canvas.text_nodes.list.is_none(), "home {home}: no list of the closed document's text objects is kept");
assert!(app.canvas.hidden_chars.marks.is_empty(), "home {home}: no hidden-character marks of the closed document are kept");
assert!(app.canvas.spelling.lines.is_empty(), "home {home}: no spelling marks of the closed document are kept");
}
}
/// `paths` small rectangles and three point type objects with hidden characters and words no
/// dictionary knows: the first on the first layer, the second in a group on that layer and the
/// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type
+15
View File
@@ -561,6 +561,21 @@ mod tests {
assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value");
}
/// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size
/// with Relative, a share of the object's size, shows one.
#[test]
fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() {
use craft::ui::runtime::env::UnitKind;
let app = app();
for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] {
let cx = EffectCx::new(&app, effect, false);
let rows = super::super::effect_rows::distort(&cx, &DialogFields::new());
let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit);
assert_eq!(unit(key), Some(None), "{effect} {key}");
assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size");
}
}
/// The lists the dialogs draw hold the values the effect's parameter documentation lists, in
/// its order; Rasterize's Color Model names the document's mode first.
#[test]
+7 -2
View File
@@ -36,7 +36,12 @@ fn data_label(text: &str) -> Label {
/// A whole-number slider row over `0..=100` percent.
fn percent_range(key: &str, label: Label, default: f64) -> Param {
Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent)
count_range(key, label, default).unit(UnitKind::Percent)
}
/// A whole-number slider row over `0..=100` with no unit after the number.
fn count_range(key: &str, label: Label, default: f64) -> Param {
Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0)
}
/// The row of `key` for either unit of a Relative/Absolute pair: a share of the object's size, or a distance in the
@@ -82,7 +87,7 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec<Param> {
pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
let roughen = cx.id == "distort.roughen";
// PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it
let second = if roughen { percent_range("detail", lbl!("Detail:"), 10.0) } else { percent_range("ridges", lbl!("Ridges per segment:"), 4.0) };
let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) };
let points: Vec<(String, Label)> = choices(&cx.id, "points")
.unwrap_or_default()
.iter()
@@ -15,7 +15,10 @@
use std::sync::Arc;
use craft::ui::buttons::Button;
use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, clicked};
use craft::ui::dialog::DialogResult;
use craft::ui::layout_components::Row;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesTab, PropertyRow};
use craft::ui::runtime::env::Label;
use serde_json::{Map, Value, json};
@@ -599,8 +602,6 @@ fn seed_editors(fields: &mut DialogFields) {
}
}
// PLAN: the stop list is a Select over the stops and the buttons are egui buttons: the List and button
// components' signatures are not in the bundle.
/// The Add, Delete Tab and Clear All Tabs buttons, which also keep the editors and the stop they edit in step.
fn tabs_buttons(unit: Unit) -> Param {
Param::custom("tabs", tl!("Tabs"), move |ui, fields, _| {
@@ -608,10 +609,10 @@ fn tabs_buttons(unit: Unit) -> Param {
let (rows, _, _) = tab_rows(fields);
let can_add = new_tab_position(&rows, unit).is_some();
let (mut add, mut delete, mut clear) = (false, false, false);
let line = ui.horizontal(|ui| {
add = ui.add_enabled(can_add, egui::Button::new(tl!("Add"))).clicked();
delete = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Delete Tab"))).clicked();
clear = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Clear All Tabs"))).clicked();
let line = Row::new().show(ui, |ui, _| {
add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui));
delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui));
clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui));
});
if add {
add_tab(fields, unit);
@@ -621,7 +622,7 @@ fn tabs_buttons(unit: Unit) -> Param {
clear_tabs(fields);
}
seed_editors(fields);
line.response
line.output
})
.companions(["__tabSel", "__tabEdited", "__tabShown", "__tabAlign", "__tabPosition", "__tabLeader", "__tabAlignOn"])
}
+45 -33
View File
@@ -5,12 +5,16 @@
// PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and
// runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets).
use craft::ui::contract::{Bind, FieldLabelRole, Show as _, ShowContainer as _, SideLabel};
use craft::behavior::ColumnWidth;
use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft::ui::dialog::DialogId;
use craft::ui::display::Text;
use craft::ui::form::Field;
use craft::ui::layout::GridFit;
use craft::ui::layout_components::Grid;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
use craft::ui::runtime::measure;
use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
use craft::ui::text::{NumberField, NumberOutput};
use craft::ui::value_drag::SliderScale;
@@ -30,6 +34,10 @@ use crate::VectorcraftApp;
/// sends 180° less the threshold: 150° sends `object.path.simplify`'s default of 30°.
pub(crate) const ANGLE_THRESHOLD: f64 = 150.0;
/// Split Into Grid's two columns, each as wide as its fields: the rows on the left, the columns on the right. The
/// grid keeps both columns in a narrow dialog.
const AXES: [ColumnWidth; 2] = [ColumnWidth::Content; 2];
/// Simplify's tolerance when the dialog opens from the menu, in points.
const DEFAULT_TOLERANCE: f64 = 1.0;
@@ -175,7 +183,7 @@ pub(crate) fn split_fields(width: f64, height: f64) -> DialogFields {
fn cell(ui: &mut egui::Ui, label: &'static str, name: String, describes: bool, value: f64, lengths: Option<LengthUnits>) -> Option<f64> {
let role = if describes { FieldLabelRole::Describes } else { FieldLabelRole::Names };
let mut edited = None;
Field::new(label).side(SideLabel::new().role(role)).show(ui, |ui, _| {
Field::new(label).side(SideLabel::new().role(role)).id_salt(name.as_str()).show(ui, |ui, _| {
let bind = Bind::given(Some(value));
let out: NumberOutput = match lengths {
Some(l) => NumberField::length(name.clone(), bind, l).show(ui),
@@ -194,41 +202,45 @@ fn split_grid(ui: &mut egui::Ui, f: &mut DialogFields, lengths: LengthUnits) ->
("rows", tl!("Rows:"), tl!("Height:"), "rowGutter", "totalHeight", 2.0),
("columns", tl!("Columns:"), tl!("Width:"), "columnGutter", "totalWidth", 2.0),
];
egui::Grid::new("split-grid")
.num_columns(2)
.show(ui, |ui| {
for (number, label, _, _, _, default) in axes {
let n = f.number(number).unwrap_or(default);
if let Some(v) = cell(ui, label, label.to_string(), false, n, None) {
f.set(number, v);
}
// The grid can run its body twice in a pass, so the body edits a copy, kept only from the run that takes effect.
let before = f.clone();
let mut edited = None;
let shown = Grid::new(&AXES).fit(GridFit::Fixed).id_salt("split-grid").show(ui, |ui, _| {
let mut f = before.clone();
for (number, label, _, _, _, default) in axes {
let n = f.number(number).unwrap_or(default);
if let Some(v) = cell(ui, label, label.to_string(), false, n, None) {
f.set(number, v);
}
ui.end_row();
for (number, _, label, gutter, total, default) in axes {
let n = f.number(number).unwrap_or(default).max(1.0);
let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0);
let size = (f.number(total).unwrap_or(0.0) - gaps) / n;
if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) {
f.set(total, n * v + gaps);
}
}
for (number, _, label, gutter, total, default) in axes {
let n = f.number(number).unwrap_or(default).max(1.0);
let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0);
let size = (f.number(total).unwrap_or(0.0) - gaps) / n;
if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) {
f.set(total, n * v + gaps);
}
ui.end_row();
for (_, axis, _, gutter, _, _) in axes {
let label = tl!("Gutter:");
if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) {
f.set(gutter, v);
}
}
for (_, axis, _, gutter, _, _) in axes {
let label = tl!("Gutter:");
if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) {
f.set(gutter, v);
}
ui.end_row();
for (_, axis, _, _, total, _) in axes {
let label = tl!("Total:");
if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) {
f.set(total, v);
}
}
for (_, axis, _, _, total, _) in axes {
let label = tl!("Total:");
if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) {
f.set(total, v);
}
ui.end_row();
})
.response
}
if measure::effect(ui.ctx(), "Split Into Grid's fields edit their values") {
edited = Some(f);
}
});
if let Some(edited) = edited {
*f = edited;
}
shown.output
}
/// Split Into Grid's rows: the grid and Add Guides.
+19 -13
View File
@@ -175,8 +175,13 @@ impl Rows<'_> {
self.defaults.get(key).and_then(Value::as_f64).unwrap_or(0.0)
}
fn range(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32, unit: UnitKind) -> Param {
Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).unit(unit).resettable()
fn range(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32, unit: UnitKind) -> Param {
self.plain(key, label, range, decimals).unit(unit)
}
/// A slider over a number shown with no unit after it, such as a count.
fn plain(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32) -> Param {
Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).resettable()
}
fn degrees(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32) -> Param {
@@ -273,7 +278,7 @@ fn object_rows(data: &Data, rows: &Rows, effect: &str, place: Place) -> Vec<Para
out.push(bevel_row(data, effect, place));
out.push(sized(rows.length("bevelWidth", tl!("Width"), (0.0, 1000.0))));
out.push(sized(rows.length("bevelHeight", tl!("Height"), (0.0, 1000.0))));
out.push(sized(rows.range("bevelRepeat", tl!("Repeat"), (1.0, 32.0), 0, UnitKind::Pixels)));
out.push(sized(rows.plain("bevelRepeat", tl!("Repeat"), (1.0, 32.0), 0)));
out.push(sized(rows.percent("bevelSpace", c3("Space"), (0.0, 90.0))));
out.push(sized(rows.flag("bevelInside", tl!("Bevel Inside"))));
out.push(sized(rows.flag("bevelBothSides", tl!("Bevel both sides"))));
@@ -295,15 +300,16 @@ fn bevel_heading() -> Param {
let defaults = bevel_defaults();
let keys: Vec<String> = defaults.keys().cloned().collect();
Param::custom("__bevelHeading", c3("Bevel"), move |ui, fields, _| {
ui.horizontal(|ui| {
ui.label(egui::RichText::new(c3("Bevel")).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if pressed(ui, tl!("Reset"), differs_from(fields, &defaults), None) {
defaults.iter().for_each(|(k, v)| set_value(fields, k, v));
}
});
})
.response
let mut reset = false;
let changed = differs_from(fields, &defaults);
let shown = crate::panels::section(c3("Bevel"))
.id_salt("bevel")
.controls(|ui, _| reset = pressed(ui, tl!("Reset"), changed, None))
.show(ui, |_, _| {});
if reset {
defaults.iter().for_each(|(k, v)| set_value(fields, k, v));
}
shown.output.response
})
.companions(keys)
.full_width()
@@ -413,7 +419,7 @@ fn differs_from(fields: &DialogFields, defaults: &serde_json::Map<String, Value>
/// Revolve's Rotation page: shape, view and the advanced settings.
fn revolve_rows(rows: &Rows, effect: &str, place: Place) -> Vec<Param> {
let mut advanced = vec![rows.range("segments", tl!("Segments"), (8.0, 128.0), 0, UnitKind::Pixels)];
let mut advanced = vec![rows.plain("segments", tl!("Segments"), (8.0, 128.0), 0)];
if place == Place::Dialog {
advanced.push(rows.flag("__showAxis", tl!("Show axis")));
}
@@ -406,6 +406,39 @@ fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() {
assert_eq!(doc(&h), before);
}
/// The Bevel heading is a section named Bevel that holds its Reset, on its own line between Cap and Bevel Shape.
#[test]
fn the_bevel_heading_is_a_section_between_cap_and_bevel_shape() {
use craft::ui::contract::Role;
let mut h = drawn(SQUARE, EXTRUDE);
h.set("__page", json!("object"));
let (cap, reset, shape) = (h.target("Cap").rect, h.target("Reset").rect, h.target("Bevel Shape").rect);
let tree = h.fixture.tree();
let section = h.fixture.by_role(Role::GROUP).into_iter().find(|t| tree.name_of(t.node) == Some("Bevel")).map(|t| t.rect);
assert!(section.is_some_and(|s| s.contains_rect(reset)), "a section named Bevel holds Reset: {section:?} {reset:?}");
assert!(reset.top() >= cap.bottom(), "Reset is below Cap: {cap:?} {reset:?}");
assert!(shape.top() >= reset.bottom(), "Bevel Shape is below Reset: {reset:?} {shape:?}");
h.cancel();
}
/// The bevel's Repeat and Revolve's Segments are counts: their rows show no unit after the number, while Taper, a
/// share, shows its percent sign.
#[test]
fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
use craft::ui::patterns::form_dialogs::DialogFields;
use craft::ui::runtime::env::UnitKind;
let app = VectorcraftApp::new(Session::new(), crate::Services::default());
let unit = |effect: &str, page: &str, key: &str| {
let data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new());
let mut fields = DialogFields::new();
fields.set("__page", FieldValue::Text(page.into()));
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
};
assert_eq!(unit(EXTRUDE, "object", "bevelRepeat"), Some(None));
assert_eq!(unit(REVOLVE, "rotation", "segments"), Some(None));
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
}
#[test]
fn reset_all_keeps_map_art_and_its_options() {
let mut h = drawn(SQUARE, CLASSIC_EXTRUDE);
+3 -2
View File
@@ -374,9 +374,10 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map<String, Value>, mut menu: Optio
let one = rows.len() == 1;
let first = settings_format(&rows);
let shown = Stack::new().show(ui, |ui, _| {
Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
// The buttons end at the right edge; a column too narrow for them puts them on more lines.
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
Text::new(tl!("Formats:")).shade(Shade::Muted).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
for (id, label) in PLATFORMS {
if Button::new(tl!(label)).selected(preset == id).id_salt(id).show(ui).clicked() {
platform = Some(id);
+10 -2
View File
@@ -32,11 +32,12 @@ use std::path::Path;
use craft::host::{PickRequest, Picked};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Outcome as _, Show as _};
use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _};
use craft::ui::dialog::{
DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id,
};
use craft::ui::display::Text;
use craft::ui::layout_components::Stack;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::text::TextField;
use egui::Ui;
@@ -66,6 +67,8 @@ pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a
/// The note the file dialog shows when the person picked more files than a script is given.
const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out";
/// The height of the Script File Access prompt's list of picked files before it scrolls, in points.
const PICKED_LIST_HEIGHT: f32 = 120.0;
/// The warning before a script runs. One type per question, so the host's per-type results never
/// mix the three questions of this area.
@@ -359,7 +362,12 @@ impl StackDialog for ScriptFiles {
}
let rows = |ui: &mut Ui| paths.iter().for_each(|path| drop(Text::new(shown_text(path, false)).show(ui)));
if paths.len() > 1 {
egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, rows);
Stack::new()
.label(tl!("Picked files"))
.scroll(Scroll::vertical())
.room_height(PICKED_LIST_HEIGHT)
.id_salt("script-picked")
.show(ui, |ui, _| rows(ui));
} else {
rows(ui);
}
@@ -1,4 +1,5 @@
//! The Split Into Grid dialog names its row and column fields with their axis, read from the access tree of the window.
//! The Split Into Grid dialog names its row and column fields with their axis and lays them out in two columns, read
//! from the access tree of the window.
use egui::accesskit::Role;
use serde_json::json;
@@ -27,3 +28,24 @@ fn split_into_grid_names_row_and_column_fields_with_context() {
assert!(names.contains(&name), "{name} among the text inputs: {names:?}");
}
}
/// Split Into Grid lays its fields out as a grid: the columns' fields stand right of the rows' fields on the same
/// lines, and Add Guides stands below the last of them.
#[test]
fn split_into_grid_lays_out_its_fields_above_add_guides() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap();
app.run("select.all", json!({})).unwrap();
assert!(super::object_dialogs::open_from_menu(&mut app, "object.path.splitIntoGrid"));
settle(&mut app);
let out = frame(&mut app, vec![]);
let update = out.platform_output.accesskit_update.expect("an accessibility tree");
let rect = |name: &str| {
let node = update.nodes.iter().map(|(_, node)| node).find(|node| node.label() == Some(name));
node.and_then(|node| node.bounds()).unwrap_or_else(|| panic!("{name} has a rect"))
};
let (rows, columns, guides) = (rect("Rows: Total:"), rect("Columns: Total:"), rect("Add Guides"));
assert!(columns.x0 > rows.x1, "the columns' fields stand right of the rows' fields: {rows:?} {columns:?}");
assert!(columns.y0 < rows.y1 && rows.y0 < columns.y1, "the two Total fields share a line: {rows:?} {columns:?}");
assert!(guides.y0 >= rows.y1.max(columns.y1), "Add Guides stands below the grid: {guides:?} {rows:?} {columns:?}");
}
+88 -2
View File
@@ -837,18 +837,25 @@ fn big_tiff_tags(bytes: &[u8]) -> Vec<(u16, u16, u32, u16)> {
}
/// Frames of the app's own window (`app.ui_ctx`, where its dialogs are) with the accessibility
/// tree, input events and a clock; each frame runs the dialog layer's pump after it.
/// tree, input events and a clock; each frame runs the dialog layer's pump after it. The window is
/// 1280 by 900 unless `sized` gives another size.
#[derive(Default)]
pub(super) struct Window {
time: f64,
size: Option<egui::Vec2>,
}
impl Window {
/// A window of `size` instead of the default 1280 by 900.
fn sized(size: egui::Vec2) -> Self {
Self { size: Some(size), ..Self::default() }
}
fn run(&mut self, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> egui::FullOutput {
let ctx = app.ui_ctx.clone().expect("a test app has a window");
ctx.enable_accesskit();
self.time += 0.1;
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, self.size.unwrap_or(egui::vec2(1280.0, 900.0)));
let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() };
// The window's frame with the app's frame input, as the hosts run it: the controls' commands reach the app.
let out = crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui));
@@ -1429,3 +1436,82 @@ fn an_artboard_name_stays_with_its_document() {
assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]);
assert!(log.borrow().is_empty(), "renaming must not export");
}
/// In a window of the default size and in one of the app's least size, every control of the dialog stays between its
/// sides, the format rows stay in the right column, and in the default window the Formats heading's buttons end at
/// the column's right edge.
#[test]
fn the_format_rows_fit_the_right_column_at_the_default_and_least_window_sizes() {
let rows = json!([
{"scale": "1x", "suffix": "", "format": "png"},
{"scale": "2x", "suffix": "@2x-long-suffix", "format": "jpg", "quality": 100},
{"scale": "100w", "format": "pdf"},
]);
// The default window, then the least size the desktop app's window takes.
for (size, default) in [(egui::vec2(1280.0, 900.0), true), (egui::vec2(800.0, 500.0), false)] {
let (mut app, _) = app(2, false);
let mut w = Window::sized(size);
w.run(&mut app, vec![]);
open(&mut app);
set(&mut app, "formats", rows.clone());
w.run(&mut app, vec![]);
let out = w.run(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
let rect = |n: &egui::accesskit::Node| {
n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
};
let find = |label: &str, role: Role| {
nodes
.iter()
.find(|(_, n)| n.label() == Some(label) && n.role() == role)
.and_then(|(_, n)| rect(n))
.unwrap_or_else(|| panic!("no {role:?} {label:?}"))
};
let Some((dialog_id, dialog)) = nodes.iter().find(|(_, n)| n.role() == Role::Dialog) else { panic!("no dialog at {size:?}") };
let dialog = rect(dialog).expect("the dialog's bounds");
// The Export to: section spans the right column.
let column = find("Export to:", Role::Group);
let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect();
let mut under = vec![*dialog_id];
while let Some(id) = under.pop() {
let Some(n) = by_id.get(&id) else { continue };
under.extend(n.children().iter().copied());
if let Some(r) = rect(n) {
assert!(
r.left() >= dialog.left() - 0.5 && r.right() <= dialog.right() + 0.5,
"{:?} {:?} at {r:?} is outside the dialog at {dialog:?} in a {size:?} window",
n.role(),
n.label()
);
}
}
// Each control with how many of it the three rows show.
let format_rows = [
("Formats:", Role::Label, 1),
("iOS", Role::Button, 1),
("Android", Role::Button, 1),
("Format Presets", Role::Button, 1),
("Format Settings", Role::Button, 1),
("Scale", Role::ComboBox, 3),
("Suffix", Role::TextInput, 3),
("Format", Role::ComboBox, 3),
("Remove", Role::Button, 3),
("+ Add Scale", Role::Button, 1),
];
for (label, role, count) in format_rows {
let shown: Vec<_> = nodes.iter().filter(|(_, n)| n.label() == Some(label) && n.role() == role).collect();
assert_eq!(shown.len(), count, "{role:?} {label:?} in a {size:?} window");
for (_, n) in shown {
let r = rect(n).expect("bounds");
assert!(
r.left() >= column.left() - 0.5 && r.right() <= column.right() + 0.5,
"{label} at {r:?} is outside the column at {column:?} in a {size:?} window"
);
}
}
if default {
let gear = find("Format Settings", Role::Button);
assert!((gear.right() - column.right()).abs() <= 0.5, "the gear at {gear:?} ends at the column's edge {column:?}");
}
}
}
+32
View File
@@ -54,6 +54,12 @@ pub(crate) fn reset(app: &mut VectorcraftApp) {
app.original_editor.choice = Choice::default();
}
/// `prefs.reset`: the saved choice goes back to the default, and the next Preferences shows it.
pub(crate) fn reset_saved(app: &mut VectorcraftApp) {
app.ui.original_editor = Choice::default();
reset(app);
}
pub(crate) fn cancel(app: &mut VectorcraftApp) {
open(app);
}
@@ -262,6 +268,32 @@ mod tests {
assert!(app.ui.original_editor.path.is_none());
}
/// `prefs.reset` of every category or of File Handling, alone or as a batch step, resets the
/// saved choice; a reset of another category keeps it.
#[test]
fn prefs_reset_resets_the_saved_choice_with_file_handling() {
let (mut app, picker) = app();
prefs_dialog::cancel(&mut app);
let mine = editor("prefs-reset");
let chosen = |app: &mut VectorcraftApp| {
prefs_dialog::open(app, Some("File Handling"));
choose(app, &picker, Some(&mine)).unwrap();
prefs_dialog::confirm(app).unwrap();
assert!(app.ui.original_editor.path.is_some());
};
chosen(&mut app);
app.run("prefs.reset", json!({"category": "General"})).unwrap();
assert!(app.ui.original_editor.path.is_some(), "General keeps the choice");
app.run("prefs.reset", json!({"category": "File Handling"})).unwrap();
assert!(app.ui.original_editor.path.is_none(), "File Handling resets it");
chosen(&mut app);
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("command.batch", json!({"commands": [{"command": "prefs.reset", "params": {}}]})).unwrap();
assert!(app.ui.original_editor.path.is_none(), "every category, as a batch step");
prefs_dialog::open(&mut app, Some("File Handling"));
assert!(app.original_editor.choice.path.is_none(), "Preferences shows the default");
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn original_editor_routing_and_errors() {
+3 -2
View File
@@ -20,7 +20,7 @@ use std::sync::Arc;
use craft::behavior::{Axis, DockSide, IconId};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, Tracked};
use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked};
use craft::ui::docking::{
ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels,
PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions,
@@ -1202,9 +1202,10 @@ impl PanelSpecs<String> for Specs {
if panel == CANVAS {
return spec.canvas();
}
// A toolbar's column is as wide as its grid's steps; every other panel is at least PANEL_MIN_WIDTH wide.
let spec = match self.grids.iter().find(|(rail, _)| rail == panel) {
Some((_, grid)) => spec.grid(*grid),
None => spec,
None => spec.limits(SizeLimits::at_least(egui::vec2(PANEL_MIN_WIDTH, 0.0))),
};
let icon = crate::state::rail_panel(panel).map(|p| p.2).or_else(|| crate::panels::library_panel::parse(panel).map(|_| "library"));
match icon {
+41
View File
@@ -983,3 +983,44 @@ fn cycle_options_rejects_panels_without_sizes() {
}
assert_eq!(h.layout(), before, "a refusal changes nothing");
}
/// The width of the body of the panel titled `title` as the last frame drew it.
fn body_width(h: &Harness, title: &str) -> f32 {
h.nodes
.iter()
.find(|(_, node)| node.role() == egui::accesskit::Role::TabPanel && node.label() == Some(title))
.and_then(|(_, node)| node.bounds())
.map(|b| (b.x1 - b.x0) as f32)
.unwrap_or_else(|| panic!("{title}'s body is drawn"))
}
/// A floating panel's side dragged in past `PANEL_MIN_WIDTH` stops at the minimum.
#[test]
fn a_floating_panel_resized_past_the_panel_minimum_stops_at_it() {
let mut h = Harness::new();
h.app.run("window.panel.float", json!({"panel": "stroke", "x": 300, "y": 200, "width": 400, "height": 300})).unwrap();
h.frames(3);
let before = body_width(&h, "Stroke");
assert!((before - 400.0).abs() < 1.0, "a float wider than the minimum keeps its width: {before}");
let rect = floating_window(&h.layout(), "stroke").expect("Stroke floats").rect;
// The window's right side is its resize grip; the drag goes 300 pt in, well past the minimum.
let grip = pos2(rect.right() - 1.0, rect.center().y);
h.drag(grip, grip - vec2(300.0, 0.0));
let after = body_width(&h, "Stroke");
assert!(after < before - 1.0, "the drag narrowed the window: {before} to {after}");
assert!(after >= PANEL_MIN_WIDTH - 0.5, "dragged in past the minimum: {after}");
}
/// A docked column saved narrower than `PANEL_MIN_WIDTH` is drawn at the minimum.
#[test]
fn a_docked_column_is_never_narrower_than_the_panel_minimum() {
let mut h = Harness::new();
let mut layout = h.layout();
let columns = end_dock_mut(&mut layout).expect("the default layout has an end dock");
for column in columns.iter_mut().filter(|column| !column.iconic) {
column.width = Some(100.0);
}
h.set_layout(layout);
h.frames(3);
assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties"));
}
+133 -5
View File
@@ -1,8 +1,9 @@
//! Window → Flattener Preview: what flattening the document would touch (`flattener.preview`),
//! highlighted in red over a grey preview of the art. Refresh takes a new snapshot of the
//! document; Highlight picks what shows; Overprints, the preset and the options (Show Options in
//! the panel menu) set how it flattens. The preview is a `PreviewPane`: the wheel and the pane's
//! gestures zoom and pan, and a double click fits.
//! the panel menu) set how it flattens. The preview is a `PreviewPane`: a click zooms in about the
//! point clicked and an Alt-click (Option on macOS) zooms out, a drag pans, Ctrl or Cmd with the
//! wheel zooms, and a double click fits. The zoom row under it zooms from the keyboard.
//!
//! The settings live in `UiState::flattener_preview` (`ui.inspect`); `ui.flattenerPreview` sets
//! them and refreshes. The snapshot, the view and the texture live in [`FlattenerPreviewModel`]
@@ -10,12 +11,13 @@
use std::sync::Arc;
use craft::behavior::CanvasTransform;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Divider, Shade, Text};
use craft::ui::layout_components::Row;
use craft::ui::menu::PanelRow;
use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView};
use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom};
use craft::ui::pickers::Select;
use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates};
use craft::ui::runtime::env::Env;
@@ -258,6 +260,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
/// The preview: the whole snapshot rendered once per [`Key`], grey under a highlight with the
/// highlighted art in the theme's error colour, in a pane that zooms and pans it.
/// A click zooms in 2× about the point clicked and an Alt-click zooms out 2×, within [`fitting_view`]'s range.
fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, h: Highlight, overprints: Overprints) {
let FlattenerPreviewModel { shot, renderer, view, drawn, .. } = &mut app.flattener_preview;
let Some(shot) = shot.as_ref() else { return };
@@ -282,12 +285,46 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32,
// At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit.
let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height());
let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32);
let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view).aspect(ASPECT).show(ui);
if let Some(v) = out.view {
let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view)
.aspect(ASPECT)
.click_centres(false)
.tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit"))
.show(ui);
*view = match out.clicked {
Some(at) => {
let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 };
zoomed_about(&out.shown, at, size, out.response.rect.size(), factor)
}
// The view as drawn, so the zoom row steps from what is on screen while the pane fits.
None => out.view.unwrap_or(out.shown),
};
// The zoom row zooms from the keyboard too.
if let Some(v) = PreviewZoom::new(view).show(ui).view {
*view = v;
}
}
/// `shown` zoomed by `factor` within its zoom range, keeping the point `at` of a picture of `picture` points (from its
/// top-left corner) under the pointer, settled in a well of `well` points. A zoom out to the fit or past it returns
/// to the fitting view.
fn zoomed_about(shown: &PreviewView, at: egui::Pos2, picture: egui::Vec2, well: egui::Vec2, factor: f32) -> PreviewView {
let t = shown.transform;
let fit = PreviewPane::fit_view(picture, well, &shown.range);
let scale = (t.scale * factor).min(*shown.range.end());
let mut next = shown.clone();
if scale <= fit.scale {
next.transform = PreviewPane::settled(fit, picture, well);
next.fit = true;
return next;
}
// Where the point lies from the well's center; the new offset keeps it there at the new zoom.
let about = (at.to_vec2() - picture / 2.0) * t.scale + t.offset;
let offset = about - (about - t.offset) * (scale / t.scale);
next.transform = PreviewPane::settled(CanvasTransform::new(scale, offset), picture, well);
next.fit = false;
next
}
/// `visible` of the snapshot at most `px` pixels: in colour without a highlight, else in grey with
/// the highlighted art in `color`.
fn render(
@@ -446,4 +483,95 @@ mod tests {
let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
assert_eq!(back.flattener_preview, app.ui.flattener_preview);
}
/// The panel in a fixture, and the preview pane's bounds.
fn shown_pane() -> (std::rc::Rc<std::cell::RefCell<VectorcraftApp>>, craft::ui::testing::Fixture, egui::Rect) {
let app = std::rc::Rc::new(std::cell::RefCell::new(app()));
let drawn = std::rc::Rc::clone(&app);
let mut fixture = craft::ui::testing::Fixture::new(move |ui| show(&mut drawn.borrow_mut(), ui));
fixture.settle();
let pane = fixture.by_label("Flattener Preview").unwrap_or_else(|| panic!("no preview pane"));
(app, fixture, pane.rect)
}
/// One click at `at` with `modifiers` held, far enough from the last that the two make no double click.
fn click(fixture: &mut craft::ui::testing::Fixture, at: egui::Pos2, modifiers: egui::Modifiers) {
fixture.advance(2.0).hold(modifiers).click_at(at).hold(egui::Modifiers::NONE).idle(1);
}
fn view(app: &std::rc::Rc<std::cell::RefCell<VectorcraftApp>>) -> PreviewView {
app.borrow().flattener_preview.view.clone()
}
#[test]
fn a_click_zooms_in_about_the_point_and_an_alt_click_zooms_out() {
let (app, mut fixture, well) = shown_pane();
assert!(view(&app).fit);
let at = well.center() + egui::vec2(well.width() * 0.1, well.height() * 0.1);
click(&mut fixture, at, egui::Modifiers::NONE);
let zoomed = view(&app);
assert!(!zoomed.fit, "a click leaves fit");
// 1 is about the fit: the picture is sized to the well.
assert!(zoomed.transform.scale > 1.5, "a click zooms in: {zoomed:?}");
// The point clicked stays under the pointer: off center, the picture moved away from the well's center.
assert!(zoomed.transform.offset.x < 0.0 && zoomed.transform.offset.y < 0.0, "{zoomed:?}");
click(&mut fixture, at, egui::Modifiers::NONE);
let closer = view(&app);
assert!(closer.transform.scale > zoomed.transform.scale * 1.9, "a second click zooms in further");
click(&mut fixture, at, egui::Modifiers::ALT);
let out = view(&app);
assert!((out.transform.scale - zoomed.transform.scale).abs() < 1e-3, "an Alt-click zooms back out: {out:?}");
click(&mut fixture, at, egui::Modifiers::ALT);
assert!(view(&app).fit, "an Alt-click to the fit returns to fit");
}
#[test]
fn a_click_with_alt_latched_by_the_app_zooms_out() {
let mut app = app();
let mut frames = craft::ui::testing::Frames::new();
let mut pane = None;
for _ in 0..60 {
frames.frame(Vec::new(), |ui| show(&mut app, ui));
let tree = frames.tree();
pane = tree
.keys()
.into_iter()
.filter(|key| tree.name_of(*key) == Some("Flattener Preview"))
.filter_map(|key| tree.bounds_of(key))
.max_by(|a, b| a.area().total_cmp(&b.area()));
if pane.is_some() {
break;
}
}
let well = pane.unwrap_or_else(|| panic!("no preview pane"));
let at = well.center();
let primary =
|pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
let click = |frames: &mut craft::ui::testing::Frames, app: &mut VectorcraftApp| {
frames.advance(2.0);
frames.frame(vec![egui::Event::PointerMoved(at), primary(true)], |ui| show(app, ui));
frames.frame(vec![primary(false)], |ui| show(app, ui));
frames.idle(1, |ui| show(app, ui));
};
click(&mut frames, &mut app);
assert!(!app.flattener_preview.view.fit, "a click zooms in");
// Alt held for the user by the app (the Modifier Keys panel), with no Alt key down.
frames.latched(craft::keymap::Mods { alt: true, ..Default::default() });
click(&mut frames, &mut app);
assert!(app.flattener_preview.view.fit, "a click with Alt latched zooms back out to fit");
}
#[test]
fn click_zoom_stays_inside_the_zoom_range() {
let (app, mut fixture, well) = shown_pane();
// Alt-click at fit stays at fit.
click(&mut fixture, well.center(), egui::Modifiers::ALT);
assert!(view(&app).fit, "no zoom below the fit");
for _ in 0..6 {
click(&mut fixture, well.center(), egui::Modifiers::NONE);
}
let most = view(&app);
assert!(most.transform.scale <= *most.range.end(), "no zoom past the range: {most:?}");
assert!(!most.can_zoom_in(), "clicks reach the most zoom: {most:?}");
}
}
+392 -41
View File
@@ -1,9 +1,17 @@
//! History panel: the document's states; click one to go back (or forward) to it.
use std::sync::Arc;
use craft::behavior::{IconId, Selection, SelectionChange, keyed};
use craft::keymap::CommandRef;
use craft::ui::menu::PanelRow;
use craft::ui::patterns::panels::{HistoryEvent, HistoryFooter, HistoryKey, HistoryPanel, HistoryRow};
use craft::ui::contract::{Bind, CollectionEvent, Props as _, ScrollAnchor, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
use craft::ui::display::Divider;
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow, RowInk};
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::patterns::panels::{HistoryKey, HistoryRow};
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::sections::{FooterAction, FooterBar};
use egui::Ui;
use serde_json::{Value, json};
@@ -69,34 +77,168 @@ fn rows(app: &VectorcraftApp) -> Vec<HistoryRow> {
.collect()
}
/// Moves the document to state `target`, stopping at the first step that fails.
fn step_to(app: &mut VectorcraftApp, target: usize) {
let Some(current) = app.session.active().map(|st| st.history.undo.len()) else { return };
let s = steps_to(current, target);
let (cmd, n) = if s < 0 { ("edit.undo", -s) } else { ("edit.redo", s) };
for _ in 0..n {
if app.run(cmd, json!({})).is_err() {
break;
}
}
#[derive(Clone)]
struct ContextState {
document: u64,
snapshot: Arc<vectorcraft_doc::Document>,
}
/// The shared collection supplies row focus, keyboard context requests, scrolling and menu
/// dismissal. The app retains the chosen document snapshot and dispatches its history commands.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(undone) = app.session.active().map(|st| st.history.undo.len()) else {
let state_id = ui.scope_id().with("history-context-state");
let document = app.session.active().map(|st| st.uid);
let mut context = ui.ctx().data(|d| d.get_temp::<ContextState>(state_id));
if context.as_ref().is_some_and(|state| document != Some(state.document)) {
craft::ui::runtime::overlay::close_popups(ui.ctx());
context = None;
}
let Some(st) = app.session.active() else {
ui.ctx().data_mut(|d| d.remove::<ContextState>(state_id));
super::empty_state(ui, "history", tl!("No document"), tl!("Open a document to see its history."));
return;
};
let document = st.uid;
let current = st.history.undo.len();
let rows = rows(app);
// A click on a row moves to its state at once, so the current state is the selected one.
let out = HistoryPanel::new(&rows, Some(HistoryKey::State(undone as u64)))
.footer(HistoryFooter::default().new_document(true))
.can_delete(|_| false)
.show(ui);
for event in out.events {
match event {
HistoryEvent::Select(HistoryKey::State(n)) => step_to(app, n as usize),
HistoryEvent::NewDocument => crate::menus::invoke(app, "edit.newDocumentFromState", json!({})),
_ => {}
let mut selected = Selection::single(HistoryKey::State(current as u64));
let mut new_document = false;
let mut target = None;
let mut action = None;
Stack::new()
.fill()
.footer(|ui, _| {
let out = FooterBar::actions([FooterAction::new(IconId::new("new_file"), tl!("Create New Document from Current State"))]).show_footer(ui);
if !ui.is_sizing_pass() {
new_document |= out.picked.is_some();
}
})
.show(ui, |ui, _| {
let list = List::<HistoryKey>::new(tl!("History"))
.id(ui.scope_id().with(("history-rows", document)))
.select(SelectMode::Single)
.arrows_select(false)
.selection(Bind::bound(&mut selected))
.row_menu()
.sizing(Sizing::Fill)
.scroll_anchor(ScrollAnchor::End);
let out = list.show_items(ui, &keyed(&rows, |row: &HistoryRow| row.key), &mut |_, icx| {
let row = &rows[icx.at];
let mut item = ListRow::new(row.label.clone()).cells(icx.cells()).state(icx.row.clone());
if let Some(icon) = row.icon.clone() {
item = item.icon(icon.into());
}
if row.redo {
item = item.ink(RowInk::Dimmed);
}
item
});
let requested = out.events.iter().find_map(|event| match event {
CollectionEvent::ContextMenu(request) => Some(request.key),
_ => None,
});
if let Some(HistoryKey::State(row)) = requested {
context = app
.session
.active()
.and_then(|st| st.history.state(&st.doc, row as usize))
.cloned()
.map(|snapshot| ContextState { document, snapshot });
} else {
for event in &out.events {
if let CollectionEvent::Activate(HistoryKey::State(row)) = event {
target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned();
}
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(HistoryKey::State(row)) = keys.last()
&& *row as usize != current
{
target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned();
}
}
}
if let Some(state) = context.as_ref() {
let snapshot = state.snapshot.clone();
let can_step = app.session.active().is_some_and(|st| !Arc::ptr_eq(&snapshot, &st.doc));
let shown = Menu::context(tl!("History"), &out.response).show(ui, |ui, _| {
if MenuItem::new(tl!("New Document from State")).enabled(crate::menus::enabled(app, "edit.newDocumentFromState")).show(ui).ran {
action = Some(("edit.newDocumentFromState", snapshot.clone()));
}
if MenuItem::new(tl!("Step to This State")).enabled(can_step).show(ui).ran {
target = Some(snapshot.clone());
}
Divider::horizontal().show(ui);
if MenuItem::new(tl!("Clear History")).enabled(crate::menus::enabled(app, "edit.clearHistory")).show(ui).ran {
action = Some(("edit.clearHistory", snapshot.clone()));
}
});
if shown.output.closed.is_some() || action.is_some() || target.is_some() {
context = None;
}
}
});
ui.ctx().data_mut(|d| {
if let Some(state) = context {
d.insert_temp(state_id, state);
} else {
d.remove::<ContextState>(state_id);
}
});
if let Some((command, snapshot)) = action {
if command == "edit.newDocumentFromState" {
if let Some(row) = resolve_state(app, snapshot, false) {
crate::menus::invoke(app, command, json!({ "index": row }));
}
} else {
crate::menus::invoke(app, command, json!({}));
}
}
if let Some(target) = target {
step_to_state(app, target);
}
if new_document {
crate::menus::invoke(app, "edit.newDocumentFromState", json!({}));
}
}
/// Keep the clicked snapshot while pending edits settle: they can add or trim history rows.
fn resolve_state(app: &mut VectorcraftApp, target: Arc<vectorcraft_doc::Document>, keep_typing: bool) -> Option<usize> {
let requests = app.session.finish_tool_edit();
let failed = requests.is_err();
crate::canvas::apply_requests(app, requests);
if failed {
return None;
}
if keep_typing && let Err(e) = app.keep_typing() {
app.status(e);
return None;
}
let st = app.session.active()?;
let current = st.history.undo.len();
let row = if Arc::ptr_eq(&st.doc, &target) {
Some(current)
} else {
st.history
.undo
.iter()
.position(|h| Arc::ptr_eq(&h.doc, &target))
.or_else(|| st.history.redo.iter().rev().position(|h| Arc::ptr_eq(&h.doc, &target)).map(|i| current + i + 1))
};
if row.is_none() {
app.status(tl!("That history state is no longer available."));
}
row
}
fn step_to_state(app: &mut VectorcraftApp, target: Arc<vectorcraft_doc::Document>) {
let Some(row) = resolve_state(app, target, true) else { return };
let Some(st) = app.session.active() else { return };
let steps = steps_to(st.history.undo.len(), row);
let (cmd, n) = if steps < 0 { ("edit.undo", -steps) } else { ("edit.redo", steps) };
for _ in 0..n {
if let Err(e) = app.run(cmd, json!({})) {
app.status(e);
break;
}
}
}
@@ -142,6 +284,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option
mod tests {
use super::*;
use crate::i18n::LangExt;
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
/// A step named after a style lists the template's translation with the style's name in it as
/// the document holds it, also when the name looks like a template, like a step with a row of
@@ -259,24 +403,9 @@ mod tests {
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
let source = app.session.active().unwrap().doc.clone();
let ctx = crate::testing::ui_context();
ctx.enable_accesskit();
egui_extras::install_image_loaders(&ctx);
let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(240.0, 400.0)));
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let out = crate::testing::part_frame(app, &ctx, egui::RawInput { events, screen_rect: screen, ..Default::default() }, show);
out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default()
};
frame(&mut app, vec![]);
let nodes = frame(&mut app, vec![]);
// PLAN: the button is named by the framework's words ("Create New Document from Current State"); the name is
// matched by the words it holds.
let button = nodes.iter().map(|(_, n)| n).find(|n| n.label().is_some_and(|l| l.contains("New Document"))).expect("the button");
let at = button.bounds().expect("its bounds");
let at = egui::pos2((at.x0 + at.x1) as f32 / 2.0, (at.y0 + at.y1) as f32 / 2.0);
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, vec![egui::Event::PointerMoved(at), press(true)]);
frame(&mut app, vec![press(false)]);
let mut panel = Panel::new(app, show);
panel.click("Create New Document from Current State");
let app = panel.app();
assert_eq!(app.session.documents().len(), 2);
assert_eq!(app.session.active_index(), Some(1), "the new document is the active one");
let st = app.session.active().unwrap();
@@ -284,4 +413,226 @@ mod tests {
assert!(st.is_dirty(), "the new document is unsaved");
assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source), "the source stays at that state");
}
fn history_harness(app: VectorcraftApp) -> Panel {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut panel = Panel::new(app, show);
panel.room(egui::vec2(260.0, 400.0));
panel.frame();
panel
}
fn row_menu_harness(app: VectorcraftApp, row: usize) -> Panel {
let mut panel = history_harness(app);
panel.secondary_click_nth(Role::LIST_ITEM, row);
panel
}
fn focus_previous_state(panel: &mut Panel) {
for _ in 0..4 {
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
if panel.focused_nth(Role::LIST_ITEM, 2) {
break;
}
}
assert!(panel.focused_nth(Role::LIST_ITEM, 2));
panel.key(egui::Key::ArrowUp, egui::Modifiers::NONE);
assert!(panel.focused_nth(Role::LIST_ITEM, 1));
assert_eq!(depth(&panel.app()), (2, 0), "moving focus must not step history");
}
#[test]
fn keyboard_activation_steps_to_the_focused_state() {
let mut h = history_harness(app_with_two_rectangles());
focus_previous_state(&mut h);
h.key(egui::Key::Enter, egui::Modifiers::NONE);
h.frame();
h.frame();
assert_eq!(depth(&h.app()), (1, 1));
assert_eq!(h.app().session.active().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
#[test]
fn switching_documents_dismisses_the_row_menu_without_clearing_either_history() {
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap();
for x in [10, 60] {
app.session.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap();
}
app.session.execute("edit.undo", &json!({})).unwrap();
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
let mut h = row_menu_harness(app, 1);
assert!(h.shows("Clear History"));
h.app().session.execute("document.activate", &json!({"index": 1})).unwrap();
h.frame();
h.frame();
assert!(!h.shows("Clear History"), "the other document must not inherit the popup");
h.app().session.execute("document.activate", &json!({"index": 0})).unwrap();
h.frame();
h.frame();
assert!(!h.shows("Clear History"), "switching back must not revive the popup");
for st in h.app().session.documents() {
assert_eq!((st.history.undo.len(), st.history.redo.len()), (1, 1));
}
}
#[test]
fn keyboard_opens_dismisses_and_activates_the_focused_rows_menu() {
let app = app_with_two_rectangles();
let source = app.session.active().unwrap().doc.clone();
let wanted = app.session.active().unwrap().history.undo[1].doc.clone();
let mut h = history_harness(app);
focus_previous_state(&mut h);
h.key(egui::Key::F10, egui::Modifiers::SHIFT);
h.frame();
h.frame();
assert!(h.focused("New Document from State"));
assert_eq!(depth(&h.app()), (2, 0), "opening does not step");
h.key(egui::Key::Escape, egui::Modifiers::NONE);
h.frame();
h.frame();
assert!(!h.shows("New Document from State"));
assert!(h.focused_nth(Role::LIST_ITEM, 1));
h.key(egui::Key::F10, egui::Modifiers::SHIFT);
h.frame();
h.frame();
h.key(egui::Key::Enter, egui::Modifiers::NONE);
h.frame();
h.frame();
assert_eq!(h.app().session.documents().len(), 2);
assert_eq!(h.app().session.active().unwrap().doc.layers, wanted.layers);
assert!(Arc::ptr_eq(&h.app().session.documents()[0].doc, &source));
assert_eq!(h.app().session.documents()[0].history.undo.len(), 2);
}
#[test]
fn right_clicking_an_earlier_state_opens_its_menu_without_stepping() {
let h = row_menu_harness(app_with_two_rectangles(), 1);
assert!(h.shows("New Document from State"));
assert!(h.shows("Step to This State"));
assert!(h.shows("Clear History"));
assert_eq!(depth(&h.app()), (2, 0));
}
#[test]
fn the_row_menu_makes_a_new_document_from_that_snapshot() {
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
let snapshot = app.session.active().unwrap().doc.clone();
app.session.execute("edit.redo", &json!({})).unwrap();
let source = app.session.active().unwrap().doc.clone();
let mut h = row_menu_harness(app, 1);
h.click_menu_item("New Document from State");
h.frame();
h.frame();
let app = h.app();
assert_eq!(app.session.documents().len(), 2);
assert_eq!(app.session.active_index(), Some(1));
let st = app.session.active().unwrap();
assert_eq!(st.doc.layers, snapshot.layers, "the historic artwork");
assert!(st.is_dirty());
assert_eq!(depth(&app), (0, 0));
assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source));
assert_eq!(app.session.documents()[0].history.undo.len(), 2);
}
#[test]
fn the_row_menu_steps_backward_and_forward_to_the_target() {
for (current, target) in [(2, 0), (0, 2), (1, 1)] {
let mut app = app_with_two_rectangles();
for _ in current..2 {
app.session.execute("edit.undo", &json!({})).unwrap();
}
let mut h = row_menu_harness(app, target);
assert_eq!(h.menu_item_enabled("Step to This State"), current != target);
h.click_menu_item("Step to This State");
h.frame();
h.frame();
assert_eq!(depth(&h.app()), (target, 2 - target));
assert_eq!(h.app().session.active().unwrap().doc.layers[0].children().unwrap().len(), target);
}
}
#[test]
fn the_row_menu_clears_undo_and_redo_without_changing_art() {
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
let source = app.session.active().unwrap().doc.clone();
let mut h = row_menu_harness(app, 0);
h.click_menu_item("Clear History");
h.frame();
h.frame();
assert_eq!(depth(&h.app()), (0, 0));
assert!(std::sync::Arc::ptr_eq(&h.app().session.active().unwrap().doc, &source));
let mut empty = app_with_two_rectangles();
empty.session.execute("edit.clearHistory", &json!({})).unwrap();
let h = row_menu_harness(empty, 0);
assert!(!h.menu_item_enabled("Clear History"));
}
#[test]
fn stepping_settles_typing_and_follows_the_snapshot_when_rows_shift() {
for (limit, row) in [(10, 0), (2, 1)] {
let mut app = app_with_two_rectangles();
app.session.active_mut().unwrap().history.limit = limit;
let st = app.session.active().unwrap();
let wanted = st.history.state(&st.doc, row).unwrap().clone();
app.session.begin_interaction("Typing").unwrap();
app.session.preview("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let mut h = row_menu_harness(app, row);
h.click_menu_item("Step to This State");
h.frame();
h.frame();
let app = h.app();
let st = app.session.active().unwrap();
assert_eq!(st.doc.layers, wanted.layers, "limit {limit}, row {row}");
assert!(st.interaction.is_none());
assert_eq!(st.history.undo.len(), 0);
}
}
#[test]
fn copying_a_state_resolves_pending_tool_edits_without_copying_a_neighbor() {
use vectorcraft_tools::{PointerEvent, PointerKind};
for (row, finishes_while_open) in [(0, false), (1, false), (0, true), (1, true)] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 800, "height": 200})).unwrap();
// A Shape Builder merge over this many segments computes on another thread.
for k in 0..40 {
app.run("shape.rectangle", json!({"x": k * 10, "y": 0, "width": 20, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap();
let st = app.session.active_mut().unwrap();
st.history.limit = 2;
st.history.trim();
let wanted = st.history.state(&st.doc, row).unwrap().clone();
let view = app.view_info();
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Move, 15.0, 10.0), view);
app.session.tool_poll(view, true).unwrap();
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, 15.0, 10.0), view);
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Up, 15.0, 10.0), view);
assert!(app.session.tool_waiting());
let mut h = row_menu_harness(app, row);
if finishes_while_open {
let requests = h.app().session.finish_tool_edit();
crate::canvas::apply_requests(&mut h.app(), requests);
h.frame();
h.frame();
}
h.click_menu_item("New Document from State");
h.frame();
h.frame();
let app = h.app();
assert!(!app.session.tool_waiting());
if row == 0 {
assert_eq!(app.session.documents().len(), 1, "the pruned snapshot must not copy its neighbor");
assert_eq!(app.ui.status, "That history state is no longer available.");
} else {
assert_eq!(app.session.active_index(), Some(1));
assert_eq!(app.session.active().unwrap().doc.layers, wanted.layers, "the retained snapshot moved from row 1 to row 0");
}
}
}
}
+64
View File
@@ -324,5 +324,69 @@ pub(crate) fn imported(app: &mut VectorcraftApp, touch_workspace: bool) {
}
}
/// The default of each UI-only row ([`UI_FIELDS`]), by key. Enable Contextual Task Bar takes the value the current
/// workspace was saved with, so a reset leaves the workspace as it was saved.
fn default_ui_fields(ui: &crate::UiState) -> [(&'static str, bool); 3] {
let first = crate::UiState::default();
let task_bar = crate::workspaces::saved_task_bar(ui);
[("__smartGuides", first.view.smart_guides), ("__snapToGrid", first.view.snap_to_grid), ("__taskBar", task_bar)]
}
/// After `prefs.reset`, alone or as a batch step, of every category or of one: the UI-only rows ([`UI_FIELDS`]) and
/// the Edit Original app of the categories it reset take their defaults too, and an open Preferences window shows
/// the reset values. Returns whether any reset was pending.
pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) -> bool {
let mut w = app.prefs.take();
let any = apply_prefs_resets_to(app, w.as_deref_mut());
if app.prefs.is_none() {
app.prefs = w;
}
any
}
/// [`apply_prefs_resets`] with the open window `w`, which is out of `app` while it draws or applies.
fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindow>) -> bool {
let resets = app.session.take_prefs_resets();
if resets.is_empty() {
return false;
}
let in_reset = |category: &str| resets.iter().any(|r| r.is_none_or(|c| c == category));
for (key, value) in default_ui_fields(&app.ui) {
if !UI_FIELDS.iter().any(|&(k, c, _)| k == key && in_reset(c)) {
continue;
}
match key {
"__smartGuides" => app.ui.view.smart_guides = value,
"__snapToGrid" => app.ui.view.snap_to_grid = value,
_ => app.ui.task_bar = value,
}
// The window shows the reset row, so OK keeps it.
if let Some(w) = w.as_deref_mut() {
w.draft.set(key, &value);
}
}
// And the reset preferences, the groups with a reset of every category; Units ▸ General then leaves the open
// document's units alone on OK.
if let Some(w) = w {
let every = resets.contains(&None);
let prefs = app.session.prefs.to_json();
for (k, v) in prefs.as_object().into_iter().flatten() {
let reset = spec(k).map_or(every && PREF_GROUPS.contains(&k.as_str()), |s| in_reset(s.category));
if reset && w.draft.get::<Value>(k).is_some() {
w.draft.set(k, v);
if k == "unitsGeneral" {
w.reset_units = v.as_str().map(str::to_string);
}
}
}
w.sync_strings();
}
// The Edit Original row shows the app's Edit Original choice.
if spec("editOriginalSystemDefaults").is_some_and(|s| in_reset(s.category)) {
crate::original_editor::reset_saved(app);
}
true
}
#[cfg(test)]
mod tests;
+34 -2
View File
@@ -269,14 +269,25 @@ impl Live<'_> {
page
}
/// Sets every key of the draft to its default, as the answered Reset question does.
/// Sets every key of the draft to its default, the UI-only rows ([`UI_FIELDS`]) included, as the answered
/// Reset question does.
fn reset_all(&mut self) {
let keys: Vec<String> =
Prefs::default().to_json().as_object().into_iter().flatten().map(|(k, _)| k.clone()).filter(|k| super::is_known(k)).collect();
self.w.reset_keys(keys.iter().map(String::as_str));
self.reset_ui_rows(|_| true);
crate::original_editor::reset(self.app);
}
/// Sets the UI-only rows of the categories `reset` names to their defaults.
fn reset_ui_rows(&mut self, reset: impl Fn(&str) -> bool) {
for (key, value) in super::default_ui_fields(&self.app.ui) {
if UI_FIELDS.iter().any(|&(k, c, _)| k == key && reset(c)) {
self.w.draft.set(key, &value);
}
}
}
/// The answers of the dialogs the window opened: the Reset question and the colour picker.
pub(super) fn take_answers(&mut self) {
if let Some(id) = self.w.reset_asked
@@ -388,6 +399,11 @@ impl PreferencesModel for Live<'_> {
fn reset_page(&mut self, page: &str) {
let keys: Vec<&str> = PREF_SPECS.iter().filter(|s| s.category == page).map(|s| s.key).collect();
self.w.reset_keys(keys);
self.reset_ui_rows(|c| c == page);
// The Edit Original row of its page.
if spec("editOriginalSystemDefaults").is_some_and(|s| s.category == page) {
crate::original_editor::reset(self.app);
}
}
fn nested(&mut self, ui: &mut egui::Ui) {
@@ -406,20 +422,33 @@ impl PreferencesDraft for Live<'_> {
}
fn apply(&mut self) -> Result<(), String> {
// A `prefs.reset` run since the last frame shows in the draft before OK reads it.
super::apply_prefs_resets_to(self.app, Some(&mut *self.w));
let values: Map<String, Value> =
self.w.draft.to::<Map<String, Value>>().unwrap_or_default().into_iter().filter(|(k, _)| !k.starts_with("__")).collect();
let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool);
let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u));
// A refused folder, typed or picked, comes back here as the engine's message.
self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?;
// When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the workspace being
// left; otherwise after it, so a return from Touch gives it to the workspace returned to.
let before_switch = touch_ws.is_some() && crate::workspaces::enters_touch(self.app, self.app.touch_screen);
if before_switch && let Some(on) = self.w.draft.get::<bool>("__taskBar") {
self.app.ui.task_bar = on;
}
let was_touch = crate::workspaces::is_current(&self.app.ui, crate::workspaces::TOUCH);
if touch_ws.is_some() {
crate::workspaces::sync_touch_workspace(self.app, self.app.touch_screen);
}
// When OK leaves Touch, the workspace returned to takes the row only when it changed since the window opened or
// last applied; otherwise it keeps its own.
let left_touch = was_touch && !crate::workspaces::is_current(&self.app.ui, crate::workspaces::TOUCH);
let task_bar_row = self.w.draft.get::<bool>("__taskBar").filter(|on| !left_touch || self.w.opened.get::<bool>("__taskBar") != Some(*on));
let flag = |key: &str, now: bool| self.w.draft.get::<bool>(key).unwrap_or(now);
let (smart_guides, snap_to_grid, task_bar) = (
flag("__smartGuides", self.app.ui.view.smart_guides),
flag("__snapToGrid", self.app.ui.view.snap_to_grid),
flag("__taskBar", self.app.ui.task_bar),
if before_switch { self.app.ui.task_bar } else { task_bar_row.unwrap_or(self.app.ui.task_bar) },
);
self.app.ui.view.smart_guides = smart_guides;
self.app.ui.view.snap_to_grid = snap_to_grid;
@@ -427,6 +456,9 @@ impl PreferencesDraft for Live<'_> {
crate::original_editor::commit(self.app);
super::snapshot(self.app);
self.app.prefs_changed = true;
// The row shows the task bar in use: after OK enters Touch, that is Touch's, not the value the workspace left
// took, so a later Apply does not give the workspace left's value to Touch.
self.w.draft.set("__taskBar", &self.app.ui.task_bar);
self.w.opened = self.w.draft.clone();
Ok(())
}
+302
View File
@@ -298,6 +298,291 @@ fn reset_preferences_keeps_an_edit_of_general_units() {
assert_eq!(b.session.prefs.units_general, Prefs::default().units_general);
}
/// Smart Guides, Snap to Grid and Enable Contextual Task Bar, the UI-only rows.
fn ui_rows(a: &VectorcraftApp) -> (bool, bool, bool) {
(a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar)
}
fn set_ui_rows(a: &mut VectorcraftApp, rows: (bool, bool, bool)) {
(a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = rows;
}
/// The Contextual Task Bar workspace `name` was left with.
fn left_task_bar(a: &VectorcraftApp, name: &str) -> bool {
let id = &crate::workspaces::find(&a.ui, name).expect("a workspace").id;
a.ui.workspaces.edited.get(id).expect("left").task_bar
}
/// Reset Preferences returns every UI-only row (Smart Guides, Snap to Grid, Enable Contextual Task Bar) to its
/// default in the draft, the value a new app shows. OK applies them; Cancel keeps the values in use.
#[test]
fn reset_preferences_resets_the_ui_only_rows() {
let default = ui_rows(&app());
let changed = (!default.0, !default.1, !default.2);
let reset_changed = |a: &mut VectorcraftApp| {
set_ui_rows(a, changed);
open(a, Some("General"));
reset_preferences(a, PromptChoice::Proceed);
};
let mut a = app();
reset_changed(&mut a);
assert_eq!(
(field(&a, "__smartGuides"), field(&a, "__snapToGrid"), field(&a, "__taskBar")),
(json!(default.0), json!(default.1), json!(default.2))
);
assert_eq!(ui_rows(&a), changed, "nothing applied before OK");
confirm(&mut a).unwrap();
assert_eq!(ui_rows(&a), default, "OK applies the defaults");
let mut b = app();
reset_changed(&mut b);
cancel(&mut b);
assert!(!is_open(&b));
assert_eq!(ui_rows(&b), changed, "Cancel keeps the values in use");
}
/// A page's own reset also resets the UI-only row of that page, and only that one.
#[test]
fn a_page_reset_resets_the_ui_only_row_of_the_page() {
let mut a = app();
let default = ui_rows(&a);
set_ui_rows(&mut a, (!default.0, !default.1, !default.2));
// The saved Edit Original choice has no setter outside its module; the UI state's saved form sets it.
let chosen = json!({"path": "editor"});
let editor = |a: &VectorcraftApp| serde_json::to_value(&a.ui.original_editor).unwrap_or_default();
a.ui.original_editor = serde_json::from_value(chosen.clone()).unwrap();
let reset_page = |a: &mut VectorcraftApp, page: &str| {
open(a, Some(page));
let mut w = a.prefs.take().expect("Preferences is open");
model::Live { app: &mut *a, w: &mut w }.reset_page(page);
a.prefs = Some(w);
};
reset_page(&mut a, "General");
assert_eq!(field(&a, "__taskBar"), json!(default.2), "General: Enable Contextual Task Bar");
assert_eq!((field(&a, "__smartGuides"), field(&a, "__snapToGrid")), (json!(!default.0), json!(!default.1)), "the other pages' rows");
confirm(&mut a).unwrap();
assert_eq!(editor(&a), chosen, "General keeps the Edit Original choice");
reset_page(&mut a, "File Handling");
confirm(&mut a).unwrap();
assert_eq!(editor(&a)["path"], Value::Null, "File Handling resets the Edit Original choice");
}
/// `prefs.reset` (the Command Palette's Reset Preferences) also returns the UI-only rows to their defaults, as a
/// batch step too; with a category, only that category's rows; with an unknown or malformed category, none.
#[test]
fn prefs_reset_resets_the_ui_only_rows_of_its_category() {
let default = ui_rows(&app());
let changed = (!default.0, !default.1, !default.2);
let mut a = app();
a.run("file.new", json!({"width": 400, "height": 400})).unwrap();
set_ui_rows(&mut a, changed);
a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap();
for bad in [json!("Nowhere"), json!(["General"]), json!(5)] {
assert!(a.run("prefs.reset", json!({"category": bad})).is_err(), "{bad}");
assert_eq!(ui_rows(&a), changed, "{bad}: an unknown or malformed category resets nothing");
assert_eq!(a.session.prefs.keyboard_increment, 7.0, "{bad}: the preferences are kept");
}
a.run("prefs.reset", json!({"category": "general"})).unwrap();
assert_eq!(ui_rows(&a), (changed.0, changed.1, default.2), "General: Enable Contextual Task Bar only");
a.run("command.batch", json!({"commands": [{"command": "prefs.reset", "params": {"category": "Guides & Grid"}}]})).unwrap();
assert_eq!(ui_rows(&a), (changed.0, default.1, default.2), "Guides & Grid, as a batch step: Snap to Grid only");
a.run("prefs.reset", json!({"category": "Smart Guides"})).unwrap();
assert_eq!(ui_rows(&a), default, "Smart Guides: Smart Guides");
set_ui_rows(&mut a, changed);
a.run("prefs.reset", json!({})).unwrap();
assert_eq!(ui_rows(&a), default, "every category");
}
/// A `prefs.reset` run while Preferences is open shows the reset values in the draft, for the categories it reset,
/// so OK keeps the reset; rows of other categories keep the draft's values.
#[test]
fn prefs_reset_while_preferences_is_open_shows_the_reset_values() {
let fresh = app();
let default = ui_rows(&fresh);
let mut a = app();
set_ui_rows(&mut a, (!default.0, !default.1, !default.2));
a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap();
open(&mut a, Some("General"));
a.run("prefs.reset", json!({"category": "General"})).unwrap();
assert_eq!(field(&a, "__taskBar"), json!(default.2), "the window shows the reset row");
assert_eq!(field(&a, "__smartGuides"), json!(!default.0), "a row of another category keeps its value");
confirm(&mut a).unwrap();
assert_eq!(ui_rows(&a), (!default.0, !default.1, default.2), "OK keeps the reset");
assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment, "OK keeps the reset preference");
// Every category, the preference groups included.
let group = fresh.session.prefs.to_json()["pixelSnap"].clone();
let mut changed = group.clone();
let flag = changed.as_object_mut().and_then(|o| o.values_mut().find(|v| v.is_boolean())).expect("a pixelSnap option is a boolean");
*flag = json!(!flag.as_bool().unwrap_or_default());
a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap();
a.run("prefs.set", json!({"key": "pixelSnap", "value": changed})).unwrap();
open(&mut a, Some("General"));
assert_eq!(field(&a, "pixelSnap"), changed);
a.run("prefs.reset", json!({})).unwrap();
confirm(&mut a).unwrap();
assert_eq!(ui_rows(&a), default, "every category");
assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment);
assert_eq!(a.session.prefs.to_json()["pixelSnap"], group, "OK keeps the reset group");
// Run straight on the session, with OK before the next frame.
a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap();
open(&mut a, Some("General"));
a.session.execute("prefs.reset", &json!({"category": "General"})).unwrap();
confirm(&mut a).unwrap();
assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment, "OK keeps a reset outside run");
}
/// Reset Preferences and `prefs.reset` give Enable Contextual Task Bar the value the current workspace was saved
/// with, which for a workspace saved with the bar off differs from the default.
#[test]
fn reset_preferences_gives_the_task_bar_the_workspaces_value() {
let off = crate::workspaces::builtins().into_iter().find(|w| !w.record.task_bar).expect("a workspace saved with the bar off");
let in_workspace = |a: &mut VectorcraftApp| {
crate::workspaces::switch(a, off.name).unwrap();
assert!(!a.ui.task_bar, "{} starts with the bar off", off.name);
a.ui.task_bar = true;
};
let mut a = app();
in_workspace(&mut a);
open(&mut a, Some("General"));
reset_preferences(&mut a, PromptChoice::Proceed);
assert_eq!(field(&a, "__taskBar"), json!(false), "the draft shows the workspace's value");
confirm(&mut a).unwrap();
assert!(!a.ui.task_bar, "OK applies the workspace's value");
let mut b = app();
in_workspace(&mut b);
b.run("prefs.reset", json!({"category": "General"})).unwrap();
assert!(!b.ui.task_bar, "prefs.reset gives the workspace's value");
let mut c = app();
assert!(c.ui.task_bar, "the default workspace starts with the bar on");
c.ui.task_bar = false;
c.run("prefs.reset", json!({})).unwrap();
assert!(c.ui.task_bar, "the default workspace's value");
}
/// On a touch screen, OK after Reset Preferences turns Enable Touch Workspace back on: the reset task bar goes to
/// the workspace left, and Touch keeps its own. With Touch entered automatically while Preferences was open,
/// clearing Enable Touch Workspace gives the row to the workspace returned to.
#[test]
fn ok_sets_the_task_bar_in_the_workspace_outside_touch() {
use crate::workspaces::{TOUCH, is_current, switch, sync_touch_workspace};
let mut a = app();
a.touch_screen = true;
a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap();
switch(&mut a, "Essentials Classic").unwrap();
a.ui.task_bar = true;
open(&mut a, Some("General"));
reset_preferences(&mut a, PromptChoice::Proceed);
assert_eq!(field(&a, "touchWorkspace"), json!(true), "the reset turns it on");
confirm(&mut a).unwrap();
assert!(is_current(&a.ui, TOUCH));
assert!(a.ui.task_bar, "Touch keeps its own task bar");
assert!(!left_task_bar(&a, "Essentials Classic"), "the workspace left takes the reset value");
let mut b = app();
b.run("prefs.set", json!({"key": "touchWorkspace", "value": true})).unwrap();
switch(&mut b, "Essentials Classic").unwrap();
open(&mut b, Some("General"));
b.touch_screen = true;
sync_touch_workspace(&mut b, true);
assert!(is_current(&b.ui, TOUCH));
set_field(&mut b, "touchWorkspace", json!(false)).unwrap();
confirm(&mut b).unwrap();
assert!(is_current(&b.ui, "Essentials Classic"));
assert!(!b.ui.task_bar, "the workspace returned to takes the row");
assert!(left_task_bar(&b, TOUCH), "Touch keeps its own task bar");
}
/// After an Apply that enters Touch, the task bar row shows Touch's task bar: a later Apply that leaves the row
/// unedited keeps it, and an edit or a reset of the row reaches it. Leaving Touch with the row unedited gives the
/// workspace returned to the value it left with.
#[test]
fn apply_after_entering_touch_keeps_touchs_task_bar() {
use crate::workspaces::{TOUCH, is_current, switch};
use craft::ui::patterns::preferences::PreferencesDraft as _;
let apply = |a: &mut VectorcraftApp| {
let mut w = a.prefs.take().expect("Preferences is open");
let r = model::Live { app: &mut *a, w: &mut w }.apply();
a.prefs = Some(w);
r.unwrap();
};
let mut a = app();
a.touch_screen = true;
a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap();
switch(&mut a, "Essentials Classic").unwrap();
a.ui.task_bar = true;
open(&mut a, Some("General"));
reset_preferences(&mut a, PromptChoice::Proceed);
assert_eq!(field(&a, "__taskBar"), json!(false), "the reset row differs from Touch's task bar");
apply(&mut a);
assert!(is_current(&a.ui, TOUCH));
assert!(a.ui.task_bar, "Touch keeps its own task bar");
set_field(&mut a, "keyboardIncrement", json!(9)).unwrap();
apply(&mut a);
assert!(is_current(&a.ui, TOUCH));
assert!(a.ui.task_bar, "an Apply without a task bar edit keeps Touch's task bar");
assert_eq!(field(&a, "__taskBar"), json!(true), "the row shows Touch's task bar");
set_field(&mut a, "__taskBar", json!(false)).unwrap();
apply(&mut a);
assert!(!a.ui.task_bar, "an edit to the row reaches Touch");
// Reset Preferences in Touch gives Touch its saved value, the value the row showed before the edit.
reset_preferences(&mut a, PromptChoice::Proceed);
apply(&mut a);
assert!(is_current(&a.ui, TOUCH));
assert!(a.ui.task_bar, "the reset reaches Touch");
// Leaving Touch with the row unedited: the workspace returned to keeps the value it left with.
set_field(&mut a, "touchWorkspace", json!(false)).unwrap();
apply(&mut a);
assert!(is_current(&a.ui, "Essentials Classic"));
assert!(!a.ui.task_bar, "the workspace returned to keeps its reset value");
}
/// A Touch return marker left over from an earlier automatic switch (Window › Workspace does not clear it) does not
/// change where OK puts the task bar: OK enters Touch from the workspace it leaves, so that workspace takes the row
/// and Touch keeps its own.
#[test]
fn ok_sets_the_task_bar_in_the_workspace_left_with_a_stale_touch_marker() {
use crate::workspaces::{TOUCH, is_current, switch};
let mut a = app();
a.touch_screen = true;
a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap();
a.ui.touch_workspace_restore = Some("Typography".into());
switch(&mut a, "Essentials Classic").unwrap();
a.ui.task_bar = true;
open(&mut a, Some("General"));
reset_preferences(&mut a, PromptChoice::Proceed);
confirm(&mut a).unwrap();
assert!(is_current(&a.ui, TOUCH));
assert!(a.ui.task_bar, "Touch keeps its own task bar");
assert!(!left_task_bar(&a, "Essentials Classic"), "the workspace left takes the reset value");
}
/// A `prefs.reset` run straight on the session, outside `VectorcraftApp::run`, resets the UI-only rows in the next
/// frame, and before the next command switches workspaces.
#[test]
fn prefs_reset_outside_run_resets_the_ui_only_rows_in_the_next_frame() {
let mut a = app();
let default = ui_rows(&a);
set_ui_rows(&mut a, (!default.0, !default.1, !default.2));
a.session.execute("prefs.reset", &json!({})).unwrap();
let ctx = a.ui_ctx.clone().expect("a window context");
crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default());
assert_eq!(ui_rows(&a), default);
// Before the next command switches workspaces: the workspace left keeps the reset value.
let mut b = app();
crate::workspaces::switch(&mut b, "Essentials Classic").unwrap();
b.ui.task_bar = true;
b.session.execute("prefs.reset", &json!({"category": "General"})).unwrap();
b.run("window.workspace", json!({"name": crate::workspaces::ESSENTIALS})).unwrap();
assert!(b.ui.task_bar, "Essentials keeps its own task bar");
assert!(!left_task_bar(&b, "Essentials Classic"), "the workspace left keeps the reset value");
}
#[test]
fn old_pref_files_keep_their_brightness() {
let mut a = app();
@@ -527,6 +812,23 @@ fn prefs_import_of_touch_workspace_switches_the_workspace() {
assert!(crate::workspaces::is_current(&a.ui, "Typography"));
}
/// A `prefs.reset` run straight on the session, then a touch screen that switches to Touch: the workspace left keeps
/// the reset value.
#[test]
fn a_pending_prefs_reset_applies_before_a_touch_switch() {
use crate::workspaces::{TOUCH, is_current, switch, sync_touch_workspace};
let mut a = app();
a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap();
switch(&mut a, "Essentials Classic").unwrap();
a.ui.task_bar = true;
a.session.execute("prefs.reset", &json!({})).unwrap();
assert!(a.session.prefs.touch_workspace, "the reset turns Enable Touch Workspace on");
sync_touch_workspace(&mut a, true);
assert!(is_current(&a.ui, TOUCH));
assert!(a.ui.task_bar, "Touch keeps its own task bar");
assert!(!left_task_bar(&a, "Essentials Classic"), "the workspace left keeps the reset value");
}
/// A folder that no folder can be created in, or that is not there, is refused on OK with the
/// engine's message, and the draft keeps its value.
#[test]
+20
View File
@@ -261,6 +261,21 @@ impl Panel {
/// A right click on the control named `name`.
pub(crate) fn secondary_click(&mut self, name: &str) {
let at = self.find(name).center();
self.secondary_click_at(at);
}
/// Right-clicks the zero-based control of `role`, including rows with identical names.
pub(crate) fn secondary_click_nth(&mut self, role: craft::ui::contract::Role, index: usize) {
self.frame();
let at = self.look_nth(role, index).center();
self.secondary_click_at(at);
}
fn look_nth(&self, role: craft::ui::contract::Role, index: usize) -> Target {
self.fixture.by_role(role).into_iter().nth(index).unwrap_or_else(|| panic!("no {role:?} at {index} in {:?}", self.names()))
}
fn secondary_click_at(&mut self, at: Pos2) {
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
self.frame_with(vec![Event::PointerMoved(at)]);
self.frame_with(vec![button(true)]);
@@ -362,6 +377,11 @@ impl Panel {
pub(crate) fn focused(&self, name: &str) -> bool {
self.fixture.tree().focused_key() == self.look(name).node
}
/// Whether the zero-based control of `role` has focus, including rows with identical names.
pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool {
self.fixture.tree().focused_key() == self.look_nth(role, index).node
}
}
/// Where [`floated`] shows a panel in the app window.
+6 -4
View File
@@ -77,8 +77,8 @@ pub(super) fn open_blocker(app: &VectorcraftApp) {
}
/// One pass of the dialog host with `events`; a key pressed in it is let go in a second pass, as a
/// person lets go of it.
pub(super) fn frame(app: &VectorcraftApp, events: Vec<egui::Event>) {
/// person lets go of it. Returns the last pass's output.
pub(super) fn frame(app: &VectorcraftApp, events: Vec<egui::Event>) -> egui::FullOutput {
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let released: Vec<egui::Event> = events
@@ -92,10 +92,12 @@ pub(super) fn frame(app: &VectorcraftApp, events: Vec<egui::Event>) {
.collect();
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)));
let pressed = !released.is_empty();
let mut last = egui::FullOutput::default();
for events in std::iter::once(events).chain(pressed.then_some(released)) {
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui)));
out.textures_delta.clear();
last = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui)));
last.textures_delta.clear();
}
last
}
pub(super) fn key(k: egui::Key) -> egui::Event {
+36
View File
@@ -505,3 +505,39 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() {
cancel(&mut app, PICKER_KIND);
finish(&mut app);
}
/// With two files picked, the file dialog lists them in a scrolled group named Picked files.
#[test]
fn a_scripts_file_dialog_lists_several_picked_files_in_a_named_group() {
let mut app = app();
app.session.prefs.show_external_script_warning = false;
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap();
script_runs::poll(&mut app);
let given = vec!["/picked/a.txt".to_string(), "/picked/b.txt".to_string()];
script_run::with_host(&app, |host, _| host.get_mut::<ScriptFiles>().map(|d| d.add(given, true, false))).unwrap();
frame(&app, vec![]);
let out = frame(&app, vec![]);
let update = out.platform_output.accesskit_update.expect("an accessibility tree");
let groups: Vec<_> =
update.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Group).filter_map(|(_, node)| node.label()).collect();
assert!(groups.contains(&"Picked files"), "a group named Picked files: {groups:?}");
let nodes: std::collections::HashMap<_, _> = update.nodes.iter().map(|(id, node)| (*id, node)).collect();
let (_, group) = update
.nodes
.iter()
.find(|(_, node)| node.role() == egui::accesskit::Role::Group && node.label() == Some("Picked files"))
.expect("the Picked files group");
let mut texts = Vec::new();
let mut pending = group.children().to_vec();
while let Some(id) = pending.pop() {
if let Some(node) = nodes.get(&id) {
texts.extend(node.label().into_iter().chain(node.value()).map(str::to_owned));
pending.extend_from_slice(node.children());
}
}
for path in ["/picked/a.txt", "/picked/b.txt"] {
assert!(texts.iter().any(|text| text == path), "{path} is inside the Picked files group: {texts:?}");
}
cancel(&mut app, PICKER_KIND);
finish(&mut app);
}
+12
View File
@@ -304,11 +304,23 @@ fn chrome_of(record: &WorkspaceRecord) -> WorkspaceChrome {
chrome
}
/// Whether [`sync_touch_workspace`] with `touch_screen` switches to the Touch workspace.
pub fn enters_touch(app: &VectorcraftApp, touch_screen: bool) -> bool {
app.session.prefs.touch_workspace && touch_screen && !is_current(&app.ui, TOUCH)
}
/// Whether the current workspace was saved with the Contextual Task Bar on.
pub(crate) fn saved_task_bar(ui: &UiState) -> bool {
saved_record(&ui.workspaces, &ui.workspaces.set.current).task_bar
}
/// Preferences › Devices › Enable Touch Workspace (#394): on, a touch screen switches to the Touch
/// workspace; off, or when no touch screen is reported, the workspace before that switch is
/// restored if Touch was entered automatically. Each switch keeps the layout it leaves and brings
/// back the one it returns to as it was left, as Window › Workspace does.
pub fn sync_touch_workspace(app: &mut VectorcraftApp, touch_screen: bool) {
// A pending `prefs.reset` applies to the workspace it was run in.
crate::prefs_dialog::apply_prefs_resets(app);
let auto = app.session.prefs.touch_workspace && touch_screen;
if auto {
if !is_current(&app.ui, TOUCH) {
+11 -2
View File
File diff suppressed because one or more lines are too long
+10
View File
@@ -1222,6 +1222,8 @@ the art below it inside the object, groups and layer around it, the object's row
the background when `against` or `opacity` is given;
inside an object, group or layer that isolates its blending, the modes blend only with the art it holds);
`opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque.
While the active tool paints with the proxy's color (the Live Paint Bucket, the Shape Builder's fill), that color is
drawn the same way, and the selected objects' opacities and blend modes do not apply.
`against` takes a color, or `"below"` (the default, also for `null`): the color VectorCraft draws at the center of the
selection's bounds with the selected objects hidden, as the canvas shows it (locked art, opacity, blend modes and
images included; template layers and guides left out, as exports leave them out; the artboard's white where nothing
@@ -9339,6 +9341,14 @@ Preferences. `prefs.reset` resets the preferences at once, without the question.
{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"unitsGeneral","value":"millimeters"}}}
```
Reset Preferences also sets the dialog's `__smartGuides`, `__snapToGrid` and `__taskBar` fields to their defaults
(`__taskBar` takes the value the current workspace was saved with). A category's own reset sets the field of that
category (Smart Guides, Guides & Grid or General), and File Handling's also resets the app chosen for Edit Original.
`prefs.reset` run while Preferences is open shows the values it reset in the dialog. In the app, `prefs.reset` also resets Smart Guides,
Snap to Grid and Enable Contextual Task Bar when it resets every category or their category (Smart Guides, Guides &
Grid and General), and the app chosen for Edit Original when it resets every category or File Handling. A `category`
left out or `null` resets every category, and one that is not a string is an error.
`prefs.export {path?}` writes the preferences as a JSON file, `{"format": "vectorcraft-preferences", "version": 1,
"prefs": {…}}`, and replies `{path, count}`; without `path` it replies `{data, count}` with the file's text. The file
holds every preference `prefs.list` lists and the `eyedropper`, `perspectiveWidget`, `pathfinder`, `glyphSnap` and
+9 -3
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+7 -2
View File
File diff suppressed because one or more lines are too long