mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
Merge main into fix/test-lint-port-review-fixes
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
//! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"`
|
||||
//! the objects inside them (see `appearance`).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -115,7 +116,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Move Effect",
|
||||
[],
|
||||
None,
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
has_doc,
|
||||
move_effect
|
||||
),
|
||||
@@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Can the Appearance panel reorder shared effects on the exact subjects it displays?
|
||||
/// A generated graph design or a selection normalized to different objects has no matching row.
|
||||
pub fn can_reorder_selected_effects(&self) -> bool {
|
||||
let Ok(st) = self.doc() else { return false };
|
||||
let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false };
|
||||
let selected: HashSet<_> = st.selection.subjects().iter().copied().collect();
|
||||
roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the
|
||||
/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing.
|
||||
fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option<Vec<Option<usize>>> {
|
||||
let mut seen = HashSet::with_capacity(ids.len());
|
||||
let mut appearances: Vec<&vectorcraft_doc::Appearance> =
|
||||
ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::<Option<_>>()?;
|
||||
let first = *appearances.get(anchor)?;
|
||||
if source == ItemTarget::Top {
|
||||
return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]);
|
||||
}
|
||||
let item = source.effects_item(first, "effect.move").ok()??;
|
||||
appearances.swap(0, anchor);
|
||||
let shared = SharedStack::of(&appearances);
|
||||
let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::<Option<Vec<_>>>()?;
|
||||
slots.swap(0, anchor);
|
||||
Some(slots)
|
||||
}
|
||||
|
||||
/// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s.
|
||||
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.move";
|
||||
@@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let roots = edit_targets(s, p, C)?;
|
||||
// Where an aligned effect would go in each of several different stacks isn't one place.
|
||||
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) {
|
||||
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
|
||||
}
|
||||
let reference = design_reference(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) {
|
||||
// An omitted item and a numbered item can use different anchors and still name the same row.
|
||||
let shared = (!copy && reference.is_none())
|
||||
.then(|| {
|
||||
shared_reorder_slots(d, &roots, src, src.anchor(s, &roots))
|
||||
.filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source))
|
||||
})
|
||||
.flatten();
|
||||
Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Where the effect landed in each object it moved in, in the order of `ids`.
|
||||
let mut landed = vec![];
|
||||
let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| {
|
||||
let mut done = vec![];
|
||||
for id in &roots {
|
||||
for (k, id) in roots.iter().enumerate() {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?);
|
||||
let (si, di) = match &slots {
|
||||
Some(slots) => (slots[k], slots[k]),
|
||||
None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?),
|
||||
};
|
||||
let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue };
|
||||
// Taken out from the top down, so the lower positions stay valid; put back in order.
|
||||
let mut taken: Vec<Effect> = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect();
|
||||
|
||||
@@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() {
|
||||
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() {
|
||||
let mut s = session();
|
||||
let (a, b) = reversed_pair(&mut s);
|
||||
for (id, item) in [(a, 1), (b, 2)] {
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect}));
|
||||
}
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [b.0, a.0]}));
|
||||
let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone());
|
||||
let before = appearances(&s);
|
||||
for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] {
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
|
||||
let moved = run(&mut s, "effect.move", params);
|
||||
assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor");
|
||||
assert_eq!(moved["index"], json!(0));
|
||||
for (appearance, item) in appearances(&s).iter().zip([1, 2]) {
|
||||
let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(ids, ["distort.roughen", "distort.twist"]);
|
||||
assert!(appearance.effects_at(Some(0)).unwrap().is_empty());
|
||||
}
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(appearances(&s), before);
|
||||
}
|
||||
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
|
||||
for destination in [0, 2] {
|
||||
assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err());
|
||||
assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list");
|
||||
}
|
||||
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"}));
|
||||
let before = appearances(&s);
|
||||
assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err());
|
||||
assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row");
|
||||
}
|
||||
|
||||
/// `effect.move`'s reply names where the effect landed in the object whose row the active item is
|
||||
/// (the first selected object), also when that object paints above the others.
|
||||
#[test]
|
||||
|
||||
@@ -409,11 +409,14 @@ impl Session {
|
||||
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
|
||||
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd
|
||||
/// press armed ([`Self::behind_armed`]).
|
||||
/// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press
|
||||
/// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown
|
||||
/// direction handle to mirror the opposite handle.
|
||||
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
|
||||
let id = self.lent_tool(self.tool.id(), mods)?;
|
||||
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
|
||||
(!behind).then_some(id)
|
||||
let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods));
|
||||
(!behind && !kept).then_some(id)
|
||||
}
|
||||
|
||||
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
|
||||
|
||||
@@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let end = Point::new(180.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Down, end, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let p = anchor(&s, id).p;
|
||||
let shifted = Mods { shift: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let raw = Point::new(180.0, 150.0);
|
||||
pointer(&mut s, PointerKind::Drag, raw, shifted);
|
||||
assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, raw, shifted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
// A second object widens the selection's bounding box so its top-middle handle lands on the
|
||||
// curve's outgoing handle end at (180, 100).
|
||||
let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]}));
|
||||
let boxed = ViewInfo { show_bbox: true, ..view() };
|
||||
let end = Point::new(180.0, 100.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let a = anchor(&s, id);
|
||||
let both = Mods { alt: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle");
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
assert_eq!(anchor(&s, id), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
|
||||
let mut s = session();
|
||||
@@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
|
||||
assert_content(&s, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() {
|
||||
let mut s = session();
|
||||
let id = blend(&mut s);
|
||||
let (a, keys, _) = blend_state(&s, id);
|
||||
pointer(&mut s, PointerKind::Down, a.h_out, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
let (after, after_keys, _) = blend_state(&s, id);
|
||||
near(after.p, a.p);
|
||||
assert_mirrored(after, q, AnchorKind::Smooth);
|
||||
assert_eq!(after_keys, keys, "the key objects did not move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() {
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0));
|
||||
}
|
||||
|
||||
/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone
|
||||
/// and mirrors its opposite handle; the other picked handle stays where it is.
|
||||
#[test]
|
||||
fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let a = anchor(&s, id, 1);
|
||||
near(a.h_out, Point::new(180.0, 160.0));
|
||||
near(a.h_in, Point::new(20.0, 40.0));
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without
|
||||
/// Cmd/Ctrl then moves both.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during
|
||||
/// one.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() {
|
||||
for escape in [false, true] {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift);
|
||||
if escape {
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
}
|
||||
pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift);
|
||||
let x = if escape { 180.0 } else { 220.0 };
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both
|
||||
/// picked.
|
||||
#[test]
|
||||
fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd);
|
||||
near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag
|
||||
/// then moves only the handle pressed.
|
||||
#[test]
|
||||
|
||||
+89
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape};
|
||||
use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape};
|
||||
|
||||
use crate::path::{FillRule, PathData};
|
||||
|
||||
@@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> {
|
||||
|
||||
/// Distance from `p` to the nearest point on the path outline.
|
||||
pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 {
|
||||
path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt()
|
||||
path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt()
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of the path's stroke of width `width`?
|
||||
pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool {
|
||||
let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol);
|
||||
quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol
|
||||
let radius = width / 2.0 + tol;
|
||||
if !path.bounding_box().inflate(radius, radius).contains(p) {
|
||||
return false;
|
||||
}
|
||||
if !radius.is_finite() {
|
||||
return distance_to_outline(path, p) <= radius;
|
||||
}
|
||||
|
||||
// Keep candidates whose squared distance could underflow near a zero radius.
|
||||
let search_radius = radius.max(f64::MIN_POSITIVE.sqrt());
|
||||
path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius)
|
||||
}
|
||||
|
||||
// A Bézier stays inside the bounds of its control points. A line projection is
|
||||
// already cheap, so only check the bounds before running a curve solver.
|
||||
fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool {
|
||||
let bounds = match segment {
|
||||
PathSeg::Line(_) => return false,
|
||||
PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2),
|
||||
PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3),
|
||||
};
|
||||
outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1)
|
||||
}
|
||||
|
||||
fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool {
|
||||
// Leave room for rounding in the curve evaluation and the distance comparison.
|
||||
let scale = p.abs().max(low.abs()).max(high.abs()).max(radius);
|
||||
let padded = radius + 8.0 * f64::EPSILON * scale;
|
||||
p < low - padded || p > high + padded
|
||||
}
|
||||
|
||||
fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 {
|
||||
#[cfg(test)]
|
||||
OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1));
|
||||
segment.nearest(p, 1e-9).distance_sq
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static OUTLINE_NEAREST_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for
|
||||
@@ -185,6 +223,53 @@ mod tests {
|
||||
assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_hit_skips_distant_curves_without_changing_results() {
|
||||
let mut path = BezPath::new();
|
||||
for i in 0..96 {
|
||||
let x = f64::from(i) * 16.0;
|
||||
path.move_to((x, 0.0));
|
||||
path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0));
|
||||
}
|
||||
path.move_to((512.0, 0.0));
|
||||
path.quad_to((513.0, 4.0), (514.0, 0.0));
|
||||
|
||||
for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] {
|
||||
assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit);
|
||||
assert!(path.bounding_box().contains(point));
|
||||
OUTLINE_NEAREST_CALLS.with(|count| count.set(0));
|
||||
assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit);
|
||||
assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls);
|
||||
}
|
||||
|
||||
assert_stroke_hits_at_cutoff();
|
||||
}
|
||||
|
||||
fn assert_stroke_hits_at_cutoff() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.line_to((0.0, 0.0));
|
||||
path.quad_to((4.0, 8.0), (8.0, 0.0));
|
||||
path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0));
|
||||
path.close_path();
|
||||
path.move_to((2.0, -3.0));
|
||||
path.line_to((2.0, -3.0));
|
||||
|
||||
for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] {
|
||||
let transformed = transform * path.clone();
|
||||
for x in -2..23 {
|
||||
for y in -5..9 {
|
||||
let point = transform * Point::new(f64::from(x), f64::from(y));
|
||||
let distance = distance_to_outline(&transformed, point);
|
||||
for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] {
|
||||
let inside = transformed.bounding_box().inflate(radius, radius).contains(point);
|
||||
assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evenodd_hole() {
|
||||
let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf};
|
||||
use super::{
|
||||
Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind,
|
||||
@@ -19,6 +21,37 @@ fn brushed(b: Option<Rect>, reach: f64) -> Option<Rect> {
|
||||
if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b }
|
||||
}
|
||||
|
||||
/// Can the patch shade its own outline without folding across it? The differences of adjacent
|
||||
/// tensor control points bound each directional derivative in a convex cone. If every pair of
|
||||
/// derivatives has the same strict orientation, averaging them along any segment keeps them
|
||||
/// independent, so distinct parameter points cannot map to the same point.
|
||||
fn unfolded_patch(points: [(f32, f32); 12]) -> bool {
|
||||
let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y)));
|
||||
let top = [p[0], p[11], p[10], p[9]];
|
||||
let bottom = [p[3], p[4], p[5], p[6]];
|
||||
let left = [p[0], p[1], p[2], p[3]];
|
||||
let right = [p[9], p[8], p[7], p[6]];
|
||||
// Raise the linear blending terms of the Coons surface to cubic degree in each direction.
|
||||
let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| {
|
||||
let v = row as f64 / 3.0;
|
||||
std::array::from_fn(|col| {
|
||||
let u = col as f64 / 3.0;
|
||||
let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v;
|
||||
top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear
|
||||
})
|
||||
});
|
||||
let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col]));
|
||||
let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col]));
|
||||
let orientation = du[0][0].cross(dv[0][0]).signum();
|
||||
du.into_iter().flatten().all(|u| {
|
||||
dv.iter().flatten().all(|v| {
|
||||
let cross = u.cross(*v) * orientation;
|
||||
// Keep near-parallel directions on the existing clipped path through PDF quantization.
|
||||
cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// The objects this thread has measured for the walk and for the links (tests).
|
||||
@@ -542,7 +575,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1,
|
||||
/// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1,
|
||||
/// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and
|
||||
/// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads
|
||||
/// instead banded, left seams between them, and made files with many meshes very large.
|
||||
@@ -560,7 +593,6 @@ impl Exporter<'_> {
|
||||
if !writable(s, Affine::IDENTITY, bounds) {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false };
|
||||
let page: Vec<vectorcraft_color::Color> = m.points.iter().map(|p| self.page_color(&p.color)).collect();
|
||||
let mixed = page.windows(2).any(|w| w[0].model() != w[1].model());
|
||||
let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. }));
|
||||
@@ -584,6 +616,14 @@ impl Exporter<'_> {
|
||||
patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] });
|
||||
}
|
||||
}
|
||||
// An unfolded single patch shades its own outline. Filling that exact outline makes some
|
||||
// readers antialias it twice and leave seams where patches touch. Keep the outline for
|
||||
// folded geometry and for meshes with more than one patch, which can overlap themselves.
|
||||
let bounds_path = match patches.as_slice() {
|
||||
[patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false };
|
||||
let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false };
|
||||
s.set_stroke(None);
|
||||
s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero }));
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
//! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small
|
||||
//! flat-coloured paths that band, show seams and make the file large.
|
||||
|
||||
use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction};
|
||||
use craft::pdf::syntax::object::{Name, Object};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, MeshAppearance};
|
||||
use vectorcraft_doc::{ColorMode, Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
use vectorcraft_testkit::raster::{assert_similar, render_artboard};
|
||||
|
||||
use super::import_fidelity::stream;
|
||||
use crate::*;
|
||||
|
||||
/// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured
|
||||
@@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) {
|
||||
(meshes, paths)
|
||||
}
|
||||
|
||||
fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document {
|
||||
use std::fmt::Write as _;
|
||||
let mut data = String::new();
|
||||
for boundary in boundaries {
|
||||
data.push_str("00"); // Every patch supplies all its vertices.
|
||||
for (x, y) in boundary {
|
||||
write!(data, "{x:02X}{y:02X}").unwrap();
|
||||
}
|
||||
data.push_str(&"28465A".repeat(4));
|
||||
}
|
||||
data.push('>');
|
||||
let shading = stream(
|
||||
"/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \
|
||||
/Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode",
|
||||
&data,
|
||||
);
|
||||
let page = PdfPage {
|
||||
resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)),
|
||||
..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q")
|
||||
};
|
||||
let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap();
|
||||
assert_eq!(kinds(&imported).0, boundaries.len());
|
||||
imported
|
||||
}
|
||||
|
||||
fn has_curved_outline(bytes: &[u8]) -> bool {
|
||||
let output = crate::pages::open(bytes, None).unwrap();
|
||||
let pages = output.pages();
|
||||
let has_curve = |content: &[u8]| {
|
||||
let mut ops = TypedIter::new(content);
|
||||
while let Some(op) = ops.next() {
|
||||
if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
};
|
||||
if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) {
|
||||
return true;
|
||||
}
|
||||
output.objects().into_iter().any(|object| match object {
|
||||
Object::Stream(form) if form.dict().get::<Name<'_>>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => {
|
||||
has_curve(&form.decoded().unwrap())
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() {
|
||||
// The same cubic, in opposite directions, is the two patches' inner edge.
|
||||
let imported = import_patches(&[
|
||||
[(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)],
|
||||
[(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)],
|
||||
]);
|
||||
let bytes = export(&imported, &PdfOptions::default()).unwrap();
|
||||
assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself");
|
||||
let reimported = import(&bytes).unwrap();
|
||||
assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings");
|
||||
assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folded_pdf_mesh_still_uses_its_outline() {
|
||||
let imported =
|
||||
import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]);
|
||||
let bytes = export(&imported, &PdfOptions::default()).unwrap();
|
||||
assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() {
|
||||
let d = doc(rgb, 1.0);
|
||||
|
||||
+56
-11
@@ -110,6 +110,8 @@ struct HandlePress {
|
||||
moved: bool,
|
||||
/// The picked handles when the press began.
|
||||
picked: PickedHandles,
|
||||
/// A mirroring Cmd/Ctrl press on one of several picked handles: they stay picked after its drag.
|
||||
keeps_picks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -1046,6 +1048,33 @@ impl Tool for DirectSelectionTool {
|
||||
self.lent_cmd = value.as_bool().unwrap_or(false);
|
||||
}
|
||||
}
|
||||
/// A Cmd/Ctrl press without Alt on the end of a shown direction handle (a path's, type on a
|
||||
/// path's or a selected blend spine anchor's) stays with Direct Selection, so the drag mirrors
|
||||
/// the opposite handle ([`DirectSelectionTool::mirrors`]). A press on a handle of the bounding
|
||||
/// box the lent Selection tool shows still goes to that tool, and so does a press anywhere else,
|
||||
/// including one that a press of the tool gives to something it checks before the handles (a
|
||||
/// corner widget, a bracket of type on a path, a gradient mesh point).
|
||||
fn keeps_cmd_press(&self, cx: &ToolContext, p: Point, mods: Mods) -> bool {
|
||||
if self.group || mods.alt || crate::select::bbox_handle_at(cx, p) {
|
||||
return false;
|
||||
}
|
||||
let point = cx.point_tol();
|
||||
// The order of the checks is the order `pointer` tries them in on a press.
|
||||
let ev = PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods);
|
||||
if CornerDrag::hit(cx, &ev, true).is_some_and(|c| !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))) {
|
||||
return false;
|
||||
}
|
||||
if !over_path_type_anchor(cx, p) && BracketDrag::hit_any(cx, &ev).is_some() {
|
||||
return false;
|
||||
}
|
||||
if self.spine.filter(|(id, _)| cx.selection.contains(*id)).and_then(|sel| hit_spine_handle(cx, sel, p, point)).is_some() {
|
||||
return true;
|
||||
}
|
||||
if self.mesh.hit(cx, &cx.selection.objects, p).is_some() {
|
||||
return false;
|
||||
}
|
||||
hit_handle(cx, p, point).is_some()
|
||||
}
|
||||
/// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh
|
||||
/// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved
|
||||
/// goes back and the tool waits for the next press (#1743).
|
||||
@@ -1087,13 +1116,16 @@ impl Tool for DirectSelectionTool {
|
||||
self.mesh.cancel();
|
||||
// The frame anchors or handles a cancelled drag held stay selected.
|
||||
let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty();
|
||||
let handles = matches!(self.state, State::Handles { .. });
|
||||
let kept = self.handle_press.take().filter(|press| press.keeps_picks && matches!(self.state, State::Handle { .. }));
|
||||
let handles = matches!(self.state, State::Handles { .. }) || kept.is_some();
|
||||
if let Some(press) = kept {
|
||||
self.handles = press.picked;
|
||||
}
|
||||
self.state = State::Idle;
|
||||
self.guides.clear();
|
||||
(self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None);
|
||||
self.last_location = None;
|
||||
(self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None);
|
||||
self.handle_press = None;
|
||||
match (frame, handles) {
|
||||
(true, _) => vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())],
|
||||
(_, true) => vec![Action::Cancel, Action::Notify(HANDLES_PICKED.into())],
|
||||
@@ -1896,9 +1928,11 @@ impl DirectSelectionTool {
|
||||
self.state = State::Handle { id, si, ai, out, drag: Some(drag) };
|
||||
vec![Action::Preview("path.setHandle".into(), params)]
|
||||
}
|
||||
/// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift on one of two or
|
||||
/// more picked handles (`picks`, as they were before the press), a drag moves them all; any
|
||||
/// other press drags that handle alone, as before handles could be picked.
|
||||
/// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring
|
||||
/// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were
|
||||
/// before the press), a drag moves them all; any other press drags that handle alone, as before
|
||||
/// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles
|
||||
/// stay picked after such a Cmd/Ctrl or Cmd/Ctrl+Shift drag of one of them.
|
||||
fn press_handle(
|
||||
&mut self,
|
||||
cx: &ToolContext,
|
||||
@@ -1931,8 +1965,11 @@ impl DirectSelectionTool {
|
||||
};
|
||||
let handle = (id, (si, ai, out));
|
||||
let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1));
|
||||
let several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::<usize>() > 1;
|
||||
let begin = if several {
|
||||
let one_of_several = on && picks.values().map(BTreeSet::len).sum::<usize>() > 1;
|
||||
let among_several = one_of_several && !ev.mods.shift;
|
||||
// A mirroring drag keeps the picks with Shift held too.
|
||||
let keeps_picks = one_of_several && self.mirrors(ev);
|
||||
let begin = if among_several && !keeps_picks {
|
||||
let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect();
|
||||
self.state = State::Handles { handle, from, start: p, items, began: false };
|
||||
self.handles = picks.clone();
|
||||
@@ -1942,7 +1979,7 @@ impl DirectSelectionTool {
|
||||
self.state = State::Handle { id, si, ai, out, drag };
|
||||
vec![Action::Begin("Reshape".into())]
|
||||
};
|
||||
self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks });
|
||||
self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks, keeps_picks });
|
||||
begin
|
||||
}
|
||||
/// The release of a press on one of several picked handles: a drag commits, and the picked
|
||||
@@ -1957,10 +1994,18 @@ impl DirectSelectionTool {
|
||||
self.handles = BTreeMap::from([(handle.0, BTreeSet::from([handle.1]))]);
|
||||
vec![Action::Notify(HANDLES_PICKED.into())]
|
||||
}
|
||||
/// After the release of a press on a handle that did not drag: a click picks the handle alone,
|
||||
/// and a Shift-click adds it to the picked handles or takes it away.
|
||||
/// After the release of a press on a handle: a click picks the handle alone, and a Shift-click
|
||||
/// adds it to the picked handles or takes it away. A mirroring drag of one of several picked
|
||||
/// handles leaves them all picked.
|
||||
fn pick_clicked_handle(&mut self) -> Option<Action> {
|
||||
let press = self.handle_press.take().filter(|press| !press.moved)?;
|
||||
let press = self.handle_press.take()?;
|
||||
if press.moved {
|
||||
if !press.keeps_picks {
|
||||
return None;
|
||||
}
|
||||
self.handles = press.picked;
|
||||
return Some(Action::Notify(HANDLES_PICKED.into()));
|
||||
}
|
||||
let (id, h) = press.handle;
|
||||
let mut picked = if press.shift { press.picked } else { BTreeMap::new() };
|
||||
let set = picked.entry(id).or_default();
|
||||
|
||||
@@ -279,6 +279,12 @@ pub trait Tool: Send {
|
||||
fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option<NodeId> {
|
||||
None
|
||||
}
|
||||
/// Does a press at `p` with Cmd/Ctrl and `mods` held stay with the tool, instead of going to
|
||||
/// the selection tool the session lends for Cmd/Ctrl? Direct Selection keeps a press on a shown
|
||||
/// direction handle, where Cmd/Ctrl mirrors the opposite handle.
|
||||
fn keeps_cmd_press(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> bool {
|
||||
false
|
||||
}
|
||||
/// What the Info panel shows for the tool as it is now: the drag in progress (a move of the
|
||||
/// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear
|
||||
/// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show.
|
||||
|
||||
@@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator;
|
||||
use craft::ui::list::{CommandHighlight, ThumbRows};
|
||||
use craft::ui::menu::{MenuTitleLook, MenuTitlePad};
|
||||
use craft::ui::patterns::form_dialogs::PresetCardLook;
|
||||
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey};
|
||||
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
use craft::ui::runtime::toast::{self, Toast};
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
@@ -771,7 +771,7 @@ impl VectorcraftApp {
|
||||
let mut control_bar_place = chrome::control_bar_place(&self.ui);
|
||||
// PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9).
|
||||
let window_title = chrome::window_title(self);
|
||||
let shown = AppShell::new(WindowKey::main())
|
||||
let shell = AppShell::new(WindowKey::main())
|
||||
.title_bar_if(true, |_| None, chrome::app_bar)
|
||||
.options_bar(
|
||||
self.ui.control_bar,
|
||||
@@ -801,8 +801,11 @@ impl VectorcraftApp {
|
||||
.body(|ui, cx, app: &mut VectorcraftApp| {
|
||||
panel_docking::show(app, ui, cx.shell().is_some_and(|shell| shell.panels_hidden()));
|
||||
crate::place::window_files(app, ui);
|
||||
})
|
||||
.show(ui, self);
|
||||
});
|
||||
// The shell shows the window's dialogs under these words. Temporary: removed once the craft-libs pin includes
|
||||
// storytold/craft-libs#4891 (`dialogs::print::title_words`).
|
||||
let words = dialogs::print::title_words(self).map(WordsOverride::Overlay);
|
||||
let shown = with_env(ui, |env| env.words = words, |ui| shell.show(ui, self));
|
||||
chrome::set_control_bar_place(&mut self.ui, control_bar_place);
|
||||
if shown.screen_mode != given {
|
||||
self.ui.follow_screen_mode(shown.screen_mode);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use craft::behavior::{ColumnWidth, IconId};
|
||||
use craft::i18n::WordSet as _;
|
||||
use craft::ui::buttons::{Link, LinkLook};
|
||||
use craft::ui::contract::{Bind, Gap, Pad, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Stack};
|
||||
use craft::ui::runtime::env::{Env, Overrides, with_env};
|
||||
use craft::ui::runtime::env::{Env, Overrides, WordRows, WordsOverride, with_env};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
|
||||
use craft::ui::shell::{RecentFile, ShellWords, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
|
||||
use craft::ui::style::{SurfaceKind, TypeRole};
|
||||
|
||||
use super::{Ui, VectorcraftApp, json};
|
||||
@@ -45,9 +46,14 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
}
|
||||
let mut pressed = None;
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
// Production's community links read in the accent alone, with no underline.
|
||||
let plain_links = |overrides: &mut Overrides| {
|
||||
let words = recent_words(app.ui_language());
|
||||
// Production's community links read in the accent alone, with no underline, and the recent files are headed
|
||||
// "Recent Files".
|
||||
let set_env = |overrides: &mut Overrides| {
|
||||
overrides.values.set(LinkLook::Plain);
|
||||
if let Some(words) = words {
|
||||
overrides.words = Some(WordsOverride::Overlay(words));
|
||||
}
|
||||
};
|
||||
// Learn follows the presets, which stand right under New and Open as in production 0.24.1.
|
||||
let start = StartScreen::new(Bind::bound(&mut app.ui.home_view), Bind::bound(&mut app.ui.home_sort), &recent)
|
||||
@@ -62,7 +68,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
.links(&links)
|
||||
.links_title(tl!("Community"))
|
||||
.section(StartPlace::AfterSections, |ui, _| learn(ui, &mut pressed));
|
||||
let out = with_env(&mut child, plain_links, |ui| start.show(ui));
|
||||
let out = with_env(&mut child, set_env, |ui| start.show(ui));
|
||||
for action in out.actions {
|
||||
run_action(app, action);
|
||||
}
|
||||
@@ -73,6 +79,17 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// VectorCraft's heading for the Home screen's recent files, "Recent Files", over the framework's "Recent". Outside
|
||||
/// English, a language whose catalog does not translate it keeps the framework's translation.
|
||||
// Workaround for craft-libs#4890: once the craft-libs pin includes it, the start screen's `recent_title` heads the
|
||||
// list, and this word row is removed.
|
||||
fn recent_words(lang: crate::i18n::Lang) -> Option<WordRows> {
|
||||
const ENGLISH: &str = "Recent Files";
|
||||
let shown = crate::i18n::tr(lang, ENGLISH);
|
||||
let word = ShellWords::word("startScreen.recent")?;
|
||||
(lang == crate::i18n::Lang::EN || shown != ENGLISH).then(|| WordRows::new().row(word, shown))
|
||||
}
|
||||
|
||||
/// What the start screen's user did. A command that fails says why in the status bar (#6160).
|
||||
fn run_action(app: &mut VectorcraftApp, action: StartAction) {
|
||||
fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) {
|
||||
|
||||
@@ -33,7 +33,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKi
|
||||
use craft::ui::patterns::presets::{NamedPresetEvent, PresetError, PresetRow};
|
||||
use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook};
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind};
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind, WordRows};
|
||||
use craft::ui::shell::WindowDialogs;
|
||||
use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -518,6 +518,15 @@ pub(super) fn settings(fields: &DialogFields) -> Value {
|
||||
Value::Object(nested(p))
|
||||
}
|
||||
|
||||
/// The words that title File › Print "Print" while the Print dialog is open in Print mode, for the window's shell to
|
||||
/// show its dialogs under. The framework titles a dialog in sections "Print Settings". Temporary: this is removed, and
|
||||
/// the dialog is titled with `HostedPrint::title`, once the craft-libs pin includes storytold/craft-libs#4891.
|
||||
pub(crate) fn title_words(app: &VectorcraftApp) -> Option<WordRows> {
|
||||
app.print_dialog.open.as_ref().filter(|open| open.mode == PrintMode::Print)?;
|
||||
let title = craft::i18n::Word::keyed("printDialog.title", "Print Settings");
|
||||
Some(WordRows::new().row(title, tl!("Print")))
|
||||
}
|
||||
|
||||
/// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was
|
||||
/// dragged to, the presets and OK.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
@@ -143,6 +143,42 @@ fn pages(pdf: &[u8]) -> usize {
|
||||
vectorcraft_pdf::info(pdf, None).unwrap().pages.len()
|
||||
}
|
||||
|
||||
/// The texts the whole window paints, with where each is drawn, once the open dialog has faded in (each frame is a
|
||||
/// quarter second on).
|
||||
fn window_texts(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> {
|
||||
let ctx = ctx(app);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0));
|
||||
let mut texts = vec![];
|
||||
for k in 0..4 {
|
||||
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
|
||||
let out = crate::testing::app_frame(app, &ctx, raw);
|
||||
texts = crate::tests_labels::text_shapes(&out)
|
||||
.into_iter()
|
||||
.map(|(t, transform)| (t.galley.text().to_string(), transform * t.galley.rect.translate(t.pos.to_vec2())))
|
||||
.collect();
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_print_dialog_is_titled_print_and_the_preset_editor_keeps_its_title() {
|
||||
let (mut printing, _) = app();
|
||||
printing.run("file.print", json!({})).unwrap();
|
||||
let texts = window_texts(&mut printing);
|
||||
let painted = |texts: &[(String, egui::Rect)], text: &str| texts.iter().filter(|(t, _)| t == text).map(|(_, r)| *r).collect::<Vec<_>>();
|
||||
assert!(painted(&texts, "Print Settings").is_empty(), "the Print dialog is not titled Print Settings: {texts:?}");
|
||||
let preset_row = painted(&texts, "Print Preset");
|
||||
let preset_row = preset_row.first().expect("the Print Preset row is shown");
|
||||
// The title sits above the dialog's first row; the Print button sits below it.
|
||||
assert!(painted(&texts, "Print").iter().any(|title| title.bottom() <= preset_row.top()), "the dialog is titled Print: {texts:?}");
|
||||
|
||||
// The preset editor keeps the framework's title.
|
||||
let (mut editing, _) = app();
|
||||
editing.run("ui.printPresetDialog", json!({"preset": vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET})).unwrap();
|
||||
let texts = window_texts(&mut editing);
|
||||
assert!(!painted(&texts, "Print Settings").is_empty(), "the preset editor is titled Print Settings: {texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_sends_every_page_to_the_chosen_printer_and_keeps_the_settings() {
|
||||
let (mut app, jobs) = app();
|
||||
|
||||
@@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let pass = pass.into_inner();
|
||||
if let Some(list) = shown.inner {
|
||||
let opener = list.response.clone();
|
||||
apply_list(app, node.as_deref(), &order, selection, list);
|
||||
apply_list(app, node.as_deref(), &order, mix, selection, list);
|
||||
if let (Some(key), Some(n)) = (app.ui.appearance_panel.menu, node.as_deref()) {
|
||||
row_menu(app, ui, &opener, n, key);
|
||||
}
|
||||
@@ -530,8 +530,7 @@ fn object_row_label(app: &VectorcraftApp, summary: Option<&Summary>, mixed: bool
|
||||
}
|
||||
}
|
||||
|
||||
/// The list over `rows` (`order` their keys), bound to `selection`. A mixed selection's rows don't
|
||||
/// drag: where one would go in each of the different stacks isn't one place.
|
||||
/// The list over `rows` (`order` their keys), bound to `selection`.
|
||||
fn show_list(
|
||||
ui: &mut Ui,
|
||||
cx: &RowCx<'_>,
|
||||
@@ -555,10 +554,11 @@ fn show_list(
|
||||
.deletable(true)
|
||||
.selection(Bind::bound(selection))
|
||||
.can_drag(|key: &RowKey| key.drags());
|
||||
if let Some(n) = cx.node.filter(|_| cx.mix.is_none()) {
|
||||
if let Some(n) = cx.node {
|
||||
let mix = cx.mix;
|
||||
list = list
|
||||
.reorder(ReorderRule::new().copy_with(CopyKeys::Alt).into_groups())
|
||||
.accepts(move |drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize| accepts(n, order, drag, over, insert, copy));
|
||||
.accepts(move |drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize| accepts(n, order, mix, drag, over, insert, copy));
|
||||
}
|
||||
list.show_items(ui, rows, &mut |key, item| build_row(cx, *key, item))
|
||||
}
|
||||
@@ -569,6 +569,7 @@ fn apply_list(
|
||||
app: &mut VectorcraftApp,
|
||||
node: Option<&Node>,
|
||||
order: &[RowKey],
|
||||
mix: Option<&Mixed>,
|
||||
selection: Selection<RowKey>,
|
||||
list: CollectionResponse<RowKey, RowEvent>,
|
||||
) {
|
||||
@@ -610,7 +611,7 @@ fn apply_list(
|
||||
delete_selected(app, node, sel).ok();
|
||||
}
|
||||
if let Some(mv) = moved {
|
||||
reorder(app, n, order, &mv);
|
||||
reorder(app, n, order, mix, &mv);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1192,7 +1193,14 @@ fn mixed(app: &VectorcraftApp) -> Option<Mixed> {
|
||||
}
|
||||
let aps: Vec<&vectorcraft_doc::Appearance> = nodes.iter().map(|n| &*n.appearance).collect();
|
||||
let fills_differ = rest.iter().any(|n| n.appearance.fill_paint() != first.appearance.fill_paint());
|
||||
Some(Mixed { shared: vectorcraft_doc::appearance::SharedStack::of(&aps), transparency, fills_differ })
|
||||
let object_effects_match = rest.iter().all(|n| n.appearance.effects == first.appearance.effects);
|
||||
Some(Mixed {
|
||||
shared: vectorcraft_doc::appearance::SharedStack::of(&aps),
|
||||
transparency,
|
||||
fills_differ,
|
||||
object_effects_match,
|
||||
effect_targets_match: app.session.can_reorder_selected_effects(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A mixed selection as the panel lists it ([`mixed`]).
|
||||
@@ -1203,6 +1211,10 @@ struct Mixed {
|
||||
transparency: bool,
|
||||
/// Their topmost fills differ: the object row shows no fill chip.
|
||||
fills_differ: bool,
|
||||
/// All objects have the same complete, ordered object effect list.
|
||||
object_effects_match: bool,
|
||||
/// The command edits the same subjects whose rows the panel shows.
|
||||
effect_targets_match: bool,
|
||||
}
|
||||
|
||||
/// The selection's [`object_label`] and [`mixed`] summary for the active document as of one
|
||||
@@ -1673,17 +1685,40 @@ fn delete_selected(app: &mut VectorcraftApp, node: Option<&Node>, sel: Sel) -> R
|
||||
/// Whether the rows of `drag` may land before position `insert` of `order` (`over`: the row under
|
||||
/// the pointer, which takes them when it holds rows): a drop that moves or copies them
|
||||
/// ([`reorder_command`]).
|
||||
fn accepts(n: &Node, order: &[RowKey], drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize, copy: bool) -> bool {
|
||||
fn accepts(n: &Node, order: &[RowKey], mix: Option<&Mixed>, drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize, copy: bool) -> bool {
|
||||
let before = order.get(..insert).map_or(0, |rows| rows.iter().filter(|key| drag.keys.contains(key)).count());
|
||||
let mv = ReorderMove::new(drag.grabbed, drag.keys.clone(), insert.saturating_sub(before), copy);
|
||||
let into = over.copied().filter(|key| key.has_children()).map(|key| mv.clone().in_group(Some(key)));
|
||||
reorder_command(n, order, &mv).is_some() || into.is_some_and(|mv| reorder_command(n, order, &mv).is_some())
|
||||
reorder_for_selection(n, order, mix, &mv).is_some() || into.is_some_and(|mv| reorder_for_selection(n, order, mix, &mv).is_some())
|
||||
}
|
||||
|
||||
/// A mixed selection has an unambiguous destination only within a list that all its objects share.
|
||||
fn reorder_for_selection(n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove<RowKey>) -> Option<(&'static str, Value)> {
|
||||
let (cmd, params) = reorder_command(n, order, mv)?;
|
||||
let Some(mix) = mix else { return Some((cmd, params)) };
|
||||
let (item, _) = mv.key.effect()?;
|
||||
let shared = item.map_or(mix.object_effects_match, |i| mix.shared.has_item(i));
|
||||
(cmd == "effect.move" && !mv.copy && mix.effect_targets_match && shared && params["fromItem"] == params["toItem"]).then_some((cmd, params))
|
||||
}
|
||||
|
||||
/// Runs the reorder `mv` of the rows `order` of `n` and picks the moved rows (the copies), the
|
||||
/// grabbed one the lead; a moved Contents row keeps its selection.
|
||||
fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mv: &ReorderMove<RowKey>) {
|
||||
let Some((cmd, params)) = reorder_command(n, order, mv) else { return };
|
||||
fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove<RowKey>) {
|
||||
let Some((cmd, mut params)) = reorder_for_selection(n, order, mix, mv) else { return };
|
||||
if mix.is_some() {
|
||||
if let Some((Some(item), _)) = mv.key.effect() {
|
||||
// The panel shows the first selected object's rows. The engine's implicit active
|
||||
// item uses that same anchor, even when another target paints first.
|
||||
if app.session.appearance_item() != Some(item) && app.run("appearance.setActiveItem", json!({"index": item})).is_err() {
|
||||
return;
|
||||
}
|
||||
if let Some(fields) = params.as_object_mut() {
|
||||
fields.remove("fromItem");
|
||||
fields.remove("toItem");
|
||||
}
|
||||
}
|
||||
params = aligned(app, params);
|
||||
}
|
||||
let Ok(result) = app.run(cmd, params.clone()) else { return };
|
||||
let Some((kind, grabbed)) = mv.key.sel().rows() else { return };
|
||||
let mut set: Vec<usize> = mv.keys.iter().filter_map(|key| key.sel().rows().map(|(_, k)| k)).collect();
|
||||
@@ -1808,6 +1843,20 @@ fn items_move(
|
||||
Some(("appearance.moveItem", params))
|
||||
}
|
||||
|
||||
/// An edge between rows in an expanded fill or stroke can report that item as its parent.
|
||||
/// A drop immediately after the item header still means append to its effects.
|
||||
fn item_effect_gap(remaining: &[RowKey], gap: usize, item: usize) -> Option<usize> {
|
||||
let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied();
|
||||
if above == Some(RowKey::Item(item)) {
|
||||
return None;
|
||||
}
|
||||
let index = |key: Option<RowKey>| match key {
|
||||
Some(RowKey::ItemEffect(row, index)) if row == item => Some(index),
|
||||
_ => None,
|
||||
};
|
||||
index(remaining.get(gap).copied()).or_else(|| index(above).map(|at| at + 1))
|
||||
}
|
||||
|
||||
/// The effects `set` (ascending) of list `from_item` moved or copied to `gap` of `remaining`.
|
||||
fn effects_move(
|
||||
n: &Node,
|
||||
@@ -1818,7 +1867,11 @@ fn effects_move(
|
||||
mv: &ReorderMove<RowKey>,
|
||||
) -> Option<(&'static str, Value)> {
|
||||
let (item, pos) = match mv.parent {
|
||||
Some(RowKey::Item(i)) => (Some(i), n.appearance.effects_at(Some(i))?.len()),
|
||||
Some(RowKey::Item(i)) => {
|
||||
let end = n.appearance.effects_at(Some(i))?.len();
|
||||
let pos = if from_item == Some(i) && !mv.copy { item_effect_gap(remaining, gap, i).unwrap_or(end) } else { end };
|
||||
(Some(i), pos)
|
||||
}
|
||||
Some(key) => key.effect()?,
|
||||
None => {
|
||||
let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied();
|
||||
|
||||
@@ -353,6 +353,8 @@ fn drops_pick_the_command() {
|
||||
(mv(&[item(1)], 3, false, None), None),
|
||||
(mv(&[item(1)], 3, false, Some(ItemEffect(1, 0))), None),
|
||||
(mv(&[ItemEffect(1, 0)], 5, false, None), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))),
|
||||
(mv(&[ItemEffect(1, 1)], 4, false, Some(item(1))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 1, "copy": false}))),
|
||||
(mv(&[ItemEffect(1, 0)], 3, false, Some(item(1))), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))),
|
||||
(mv(&[ItemEffect(1, 0)], 4, false, None), None),
|
||||
(mv(&[ItemEffect(1, 1)], 5, true, Some(item(0))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 0, "copy": true}))),
|
||||
(mv(&[ItemEffect(1, 1)], 7, false, None), effects(json!({"from": 1, "fromItem": 1, "to": 1, "toItem": null, "copy": false}))),
|
||||
@@ -362,8 +364,8 @@ fn drops_pick_the_command() {
|
||||
assert_eq!(reorder_command(&path, &order, &moved), want, "{moved:?}");
|
||||
}
|
||||
let drag = |keys: &[RowKey]| ListDrag::new(egui::Id::NULL, keys.to_vec(), keys[0]);
|
||||
assert!(accepts(&path, &order, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row");
|
||||
assert!(!accepts(&path, &order, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is");
|
||||
assert!(accepts(&path, &order, None, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row");
|
||||
assert!(!accepts(&path, &order, None, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is");
|
||||
|
||||
// A group listed top-down S3, FA*, Contents, S1*, F0 (paint order F0 S1 FA S3, Contents above
|
||||
// two), FA and S1 dragged together.
|
||||
@@ -419,7 +421,7 @@ fn drops_pick_the_command() {
|
||||
] {
|
||||
assert_eq!(reorder_command(&group, &order, &moved), want, "{moved:?}");
|
||||
}
|
||||
assert!(!accepts(&group, &order, &drag(&[Contents]), Some(&Contents), 3, false), "where it is");
|
||||
assert!(!accepts(&group, &order, None, &drag(&[Contents]), Some(&Contents), 3, false), "where it is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -604,6 +606,74 @@ fn a_mixed_selection_lists_what_its_objects_share() {
|
||||
assert!(panel.shows("Mixed Objects"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_selection_reorders_its_identical_object_effect_lists() {
|
||||
let mut app = app_with_a_selected_rectangle();
|
||||
let a = node(&app).id;
|
||||
let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [b], "color": "#ff0000"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a.0, b]})).unwrap();
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
app.run("effect.apply", json!({"effect": effect, "item": null})).unwrap();
|
||||
}
|
||||
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
|
||||
let order = |app: &VectorcraftApp| {
|
||||
[a, NodeId(b)]
|
||||
.map(|id| app.session.active().unwrap().doc.node(id).unwrap().appearance.effects.iter().map(|e| e.id.clone()).collect::<Vec<_>>())
|
||||
};
|
||||
let before = order(&app);
|
||||
let undo = steps(&app);
|
||||
let mut panel = Panel::new(app, show);
|
||||
assert!(panel.shows("Mixed Appearances"));
|
||||
let drag = |panel: &mut Panel| {
|
||||
let from = crate::panels::tests_appearance::row_spot(panel, &effect_row_label("distort.roughen"));
|
||||
let above = panel.rect(&effect_row_label("distort.twist"));
|
||||
panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE);
|
||||
};
|
||||
drag(&mut panel);
|
||||
{
|
||||
let mut app = panel.app();
|
||||
assert_eq!(order(&app), [vec!["distort.roughen", "distort.twist"], vec!["distort.roughen", "distort.twist"]]);
|
||||
assert_eq!(steps(&app), undo + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(order(&app), before);
|
||||
app.run("effect.apply", json!({"ids": [b], "effect": "stylize.feather", "item": null})).unwrap();
|
||||
}
|
||||
let before = order(&panel.app());
|
||||
drag(&mut panel);
|
||||
assert_eq!(order(&panel.app()), before, "a common prefix does not make both lists reorderable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_selection_reorders_shared_stroke_effects_at_different_item_indices() {
|
||||
let mut app = app_with_a_selected_rectangle();
|
||||
let a = node(&app).id;
|
||||
let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [b]})).unwrap();
|
||||
app.run("appearance.addFill", json!({})).unwrap();
|
||||
app.run("appearance.moveItem", json!({"from": 2, "to": 0})).unwrap();
|
||||
app.run("appearance.setItem", json!({"index": 0, "color": "#ff0000"})).unwrap();
|
||||
for (id, item) in [(a.0, 1), (b, 2)] {
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
app.run("effect.apply", json!({"ids": [id], "item": item, "effect": effect})).unwrap();
|
||||
}
|
||||
}
|
||||
app.run("select.set", json!({"ids": [b, a.0]})).unwrap();
|
||||
app.ui.appearance_panel.open.insert(RowKey::Item(2));
|
||||
|
||||
let mut panel = Panel::new(app, show);
|
||||
let from = crate::panels::tests_appearance::row_spot(&mut panel, &effect_row_label("distort.roughen"));
|
||||
let above = panel.rect(&effect_row_label("distort.twist"));
|
||||
panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE);
|
||||
let app = panel.app();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
for (id, item) in [(a, 1), (NodeId(b), 2)] {
|
||||
let effects = doc.node(id).unwrap().appearance.effects_at(Some(item)).unwrap();
|
||||
assert_eq!(effects.iter().map(|effect| effect.id.as_str()).collect::<Vec<_>>(), ["distort.roughen", "distort.twist"]);
|
||||
}
|
||||
assert_eq!(app.ui.appearance_panel.selection.lead, Some(RowKey::ItemEffect(2, 0)));
|
||||
}
|
||||
|
||||
/// The [`summary`] the canvas cache holds for the active document, checked field by field against
|
||||
/// what [`object_label`] and [`mixed`] work out from scratch.
|
||||
fn fresh_summary(app: &mut VectorcraftApp) -> Arc<Summary> {
|
||||
|
||||
@@ -7,15 +7,17 @@
|
||||
//! list stays after the selection changes, so choosing a font in it sets that font on the live text
|
||||
//! selected then, as the font menus do. The sample field sets the text the samples show, and the
|
||||
//! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`,
|
||||
//! `retype.preview` and `retype.reset` do the same.
|
||||
//! `retype.preview` and `retype.reset` do the same. A font's menu (a secondary click on its row, or
|
||||
//! Shift+F10 on the focused row) selects the row and holds Apply Font, which sets that font as a
|
||||
//! click does, then the panel menu's sample sizes and Reset Retype Panel.
|
||||
|
||||
use craft::behavior::{EditEvent, Mixed, keyed};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::{Button, Link};
|
||||
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _};
|
||||
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize};
|
||||
use craft::ui::menu::PanelRow;
|
||||
use craft::ui::menu::{Menu, MenuItem, PanelRow};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::commands::{CommandState, CommandStates};
|
||||
use craft::ui::style::Variant;
|
||||
@@ -50,7 +52,7 @@ const SIZES: [(Size, &str, ThumbSize); 3] =
|
||||
[(Size::Small, "small", ThumbSize::Small), (Size::Medium, "medium", ThumbSize::Medium), (Size::Large, "large", ThumbSize::Large)];
|
||||
|
||||
/// One font in the list.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Found {
|
||||
pub family: String,
|
||||
pub style: String,
|
||||
@@ -114,21 +116,47 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let on_white = app.session.prefs.font_samples_on_white;
|
||||
let indexed: Vec<(usize, &Found)> = view.fonts.iter().enumerate().collect();
|
||||
let source = keyed(&indexed, |(at, _)| *at);
|
||||
// A click activates a row, so the same row chosen again sets its font again.
|
||||
let list = List::<usize>::new(tl!("Matching fonts")).select(SelectMode::Single).activate(ActivateOn::Click).show_items(
|
||||
ui,
|
||||
&source,
|
||||
&mut |key, _| {
|
||||
// The rows are keyed by place, so a list with other fonts, or another document, is another
|
||||
// list: a row's menu closes rather than act on the font that took its place.
|
||||
let document = app.session.active().map(|st| st.uid);
|
||||
// A click activates a row, so the same row chosen again sets its font again. A secondary
|
||||
// click selects its row and asks for the row's menu; it does not activate the row.
|
||||
let list = List::<usize>::new(tl!("Matching fonts"))
|
||||
.id(ui.scope_id().with(("matching-fonts", document, &view.fonts)))
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.row_menu()
|
||||
.show_items(ui, &source, &mut |key, _| {
|
||||
let (family, style) = indexed.get(*key).map_or(("", ""), |(_, f)| (f.family.as_str(), f.style.as_str()));
|
||||
ListRow::new(format!("{family} {style}")).thumb_aspect(size, ThumbAspect::new(8, 1), move |cx: &ContentPainterCx, rect: Rect| {
|
||||
crate::font_menu::paint_family_sample(cx, rect, family, style, sample, on_white);
|
||||
})
|
||||
},
|
||||
);
|
||||
let chosen = list.events.iter().find_map(|e| match e {
|
||||
});
|
||||
let mut chosen = list.events.iter().find_map(|e| match e {
|
||||
CollectionEvent::Activate(at) => view.fonts.get(*at),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(request) = list.menu
|
||||
&& let Some(f) = view.fonts.get(request.key)
|
||||
{
|
||||
// Apply Font is off while choosing the font would set it on nothing.
|
||||
let live = live_text_selected(app);
|
||||
Menu::context(format!("{} {}", f.family, f.style), &list.response).show(ui, |ui, _| {
|
||||
if MenuItem::new(tl!("Apply Font")).enabled(live).show(ui).ran {
|
||||
chosen = Some(f);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
for (size, name, _) in SIZES {
|
||||
if MenuItem::new(size_label(size)).check(view.size == size).show(ui).ran {
|
||||
run = Some(("retype.preview", json!({ "size": name })));
|
||||
}
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
if MenuItem::new(tl!("Reset Retype Panel")).show(ui).ran {
|
||||
run = Some(("retype.reset", json!({})));
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(f) = chosen
|
||||
&& live_text_selected(app)
|
||||
{
|
||||
|
||||
@@ -232,3 +232,125 @@ fn choosing_a_listed_font_sets_it_on_the_selected_live_text() {
|
||||
click(&mut app, &ctx, "Source Serif 4 Regular");
|
||||
assert!(app.session.active().unwrap().doc == before);
|
||||
}
|
||||
|
||||
/// Live text in Source Sans 3, selected, and a list of two fonts → the app and the text's id.
|
||||
fn listed_with_live_text() -> (VectorcraftApp, u64) {
|
||||
let mut app = app();
|
||||
let font = |family: &str, style: &str| super::Found { family: family.into(), style: style.into(), matched: 1 };
|
||||
app.ui.retype.searched = true;
|
||||
app.ui.retype.fonts = vec![font("Source Sans 3", "Bold"), font("Source Serif 4", "Regular")];
|
||||
let t = app.session.execute("text.create", &json!({"x": 10, "y": 300, "text": "live", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
|
||||
select(&mut app, &[t]);
|
||||
(app, t)
|
||||
}
|
||||
|
||||
fn family_of(app: &VectorcraftApp, id: u64) -> String {
|
||||
let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
text.first_style().font_family.clone()
|
||||
}
|
||||
|
||||
fn undo_len(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
const SERIF: &str = "Source Serif 4 Regular";
|
||||
const SANS: &str = "Source Sans 3 Bold";
|
||||
|
||||
#[test]
|
||||
fn a_fonts_menu_selects_its_row_without_setting_the_font() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, t) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let undo = undo_len(&panel.app());
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(panel.menu_item_enabled("Apply Font"), "live text is selected");
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "the secondary click sets no font");
|
||||
assert_eq!(undo_len(&panel.app()), undo);
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
assert!(panel.selected(SERIF), "the row the menu opened on is selected");
|
||||
assert!(!panel.selected(SANS));
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step() {
|
||||
let (app, t) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let undo = undo_len(&panel.app());
|
||||
// A menu opened on another row first, then closed: the menu acts on the row it opened on last.
|
||||
panel.secondary_click(SANS);
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
panel.secondary_click(SERIF);
|
||||
panel.click_menu_item("Apply Font");
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Serif 4", "the font of the row the menu opened on");
|
||||
assert_eq!(undo_len(&panel.app()), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_font_is_off_without_live_text() {
|
||||
let (mut app, t) = listed_with_live_text();
|
||||
select(&mut app, &[]);
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(!panel.menu_item_enabled("Apply Font"));
|
||||
assert!(panel.menu_item_enabled("Reset Retype Panel"), "the panel's own items stay on");
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "text that is not selected keeps its font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_menu_sets_the_sample_size_and_resets_the_panel() {
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, _) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let before = panel.app().ui.retype.size;
|
||||
let (other, label) = if before == Size::Large { (Size::Small, "Small") } else { (Size::Large, "Large") };
|
||||
panel.secondary_click(SERIF);
|
||||
panel.click_role(label, Role::MENU_ITEM_CHECK_BOX);
|
||||
assert_eq!(panel.app().ui.retype.size, other, "the size changed to the one chosen");
|
||||
panel.secondary_click(SERIF);
|
||||
assert_eq!(panel.toggled(label), Some(Mixed::Same(true)), "the size chosen is checked");
|
||||
panel.click_menu_item("Reset Retype Panel");
|
||||
assert!(!panel.app().ui.retype.searched, "the list is cleared");
|
||||
assert_eq!(panel.app().ui.retype.size, other, "the size stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_opens_the_fonts_menu_and_escape_returns_focus() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, t) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.focus(SERIF);
|
||||
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
|
||||
panel.frame();
|
||||
assert!(panel.menu_item_enabled("Apply Font"));
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
assert!(panel.focused(SERIF));
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "opening and closing the menu sets no font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_menu_closes_when_the_list_or_the_document_changes() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, _) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
// Another search puts another font in the row's place.
|
||||
panel.app().ui.retype.fonts.reverse();
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
}
|
||||
|
||||
@@ -164,6 +164,27 @@ fn home_lists_recent_files_and_a_click_opens_one() {
|
||||
assert!(!app.ui.status.is_empty(), "a file that can't be opened says so");
|
||||
}
|
||||
|
||||
/// The Home screen heads its recent files "Recent Files", in the interface language where the catalog translates it.
|
||||
#[test]
|
||||
fn home_heads_the_recent_files_recent_files() {
|
||||
use crate::i18n::LangExt as _;
|
||||
let shown = |lang: &str| {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
app.session.prefs.interface_language = lang.into();
|
||||
app.ui.recent_files = vec![std::env::temp_dir().join("vectorcraft-home-heading").join("Drawing.svg").to_string_lossy().into_owned()];
|
||||
home_screen(app)
|
||||
};
|
||||
let home = shown("en");
|
||||
assert!(home.shows("Recent Files"), "the recent files are headed Recent Files");
|
||||
assert!(!home.shows("Recent"), "not Recent alone");
|
||||
let home = shown("de");
|
||||
let de = crate::i18n::Lang::from_code("de").expect("German is registered");
|
||||
let german = crate::i18n::tr(de, "Recent Files");
|
||||
// Without a German row for Recent Files, the framework's heading stays.
|
||||
let heading = if german == "Recent Files" { crate::i18n::tr_id(de, "startScreen.recent", "Recent") } else { german };
|
||||
assert!(home.shows(heading), "German shows {heading}");
|
||||
}
|
||||
|
||||
/// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A
|
||||
/// tutorial shows the Learn panel at its steps and no document is opened; the Quick skill guide
|
||||
/// shows its list of skills.
|
||||
|
||||
@@ -510,6 +510,11 @@ impl Panel {
|
||||
self.fixture.tree().focused_key() == self.look(name).node
|
||||
}
|
||||
|
||||
/// Whether the row or item named `name` reports itself selected.
|
||||
pub(crate) fn selected(&self, name: &str) -> bool {
|
||||
self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
+5
-2
File diff suppressed because one or more lines are too long
+2
-1
@@ -7129,7 +7129,8 @@ act on several fills/strokes at once, and `appearance.showAllHidden` makes every
|
||||
visible again. In remote mode, `effect.dialog {effect, index, item}` opens an applied effect's dialog prefilled
|
||||
(`ui.dialog.confirm` runs `effect.setParams`); see the control protocol for the "already applied" question.
|
||||
`effect.move` rejects a `copy` value that is not a boolean, and every command that takes `aligned` rejects an `aligned`
|
||||
value that is not a boolean.
|
||||
value that is not a boolean. With `aligned: true`, objects with different appearances can reorder effects within an
|
||||
identical object effect list or within a shared fill or stroke. Copies and moves between lists require equal appearances.
|
||||
|
||||
Effect dialogs use the targeted object, group, or layer shown in Appearance. The Transform dialog previews valid
|
||||
numbers as they are typed, including Copies, distances with units, and rotation. With Preview off, changes apply
|
||||
|
||||
+4
-3
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user