Merge remote-tracking branch 'upstream/main' into HEAD

This commit is contained in:
jayzed80
2026-11-19 06:10:27 +00:00
23 changed files with 1240 additions and 61 deletions
+15
View File
@@ -81,6 +81,21 @@ impl Unit {
Unit::Ha => "H",
}
}
/// Whether this unit is a physical measurement unit (not points or pixels).
pub fn is_physical(self) -> bool {
self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha)
}
/// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG
/// (`mm`, `cm`, `in`, `pc`).
pub fn svg_suffix(self) -> Option<&'static str> {
match self {
Unit::Millimeters => Some("mm"),
Unit::Centimeters => Some("cm"),
Unit::Inches => Some("in"),
Unit::Picas => Some("pc"),
_ => None,
}
}
pub const fn label(self) -> &'static str {
match self {
Unit::Points => "Points",
+45
View File
@@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}");
}
}
/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so
/// that the unit setting survives a save/open round-trip. The engine-level test covers the full
/// stack (file.new → document.setUnits → document.serialize → document.open).
#[test]
fn svg_round_trip_preserves_document_units() {
// (unit name the engine accepts, expected unit after re-import)
let cases: &[(&str, vectorcraft_doc::Unit)] = &[
("millimeters", vectorcraft_doc::Unit::Millimeters),
("centimeters", vectorcraft_doc::Unit::Centimeters),
("inches", vectorcraft_doc::Unit::Inches),
("picas", vectorcraft_doc::Unit::Picas),
// Points and pixels both serialise as bare user-unit numbers, so both import as Pixels.
("pixels", vectorcraft_doc::Unit::Pixels),
];
for (name, expected) in cases {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
s.execute("document.setUnits", &json!({"units": name})).unwrap();
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg_text = r["text"].as_str().unwrap();
match *expected {
vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"),
vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"),
vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"),
vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"),
_ => {}
}
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
let doc_state = s.doc().unwrap();
assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'");
}
// Points serialise without suffix and re-open as Pixels (equivalent in user units).
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
s.execute("document.setUnits", &json!({"units": "points"})).unwrap();
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg_text = r["text"].as_str().unwrap();
assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}");
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels);
}
+15 -1
View File
@@ -123,11 +123,13 @@ impl<'a> Reader<'a> {
}
// A group holding only clipping paths (`q … u <path> W n U … Q`) doesn't clip on its own: `u`/`U` don't save
// the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it.
// In a compound path (`*u u <path> W n … U *U`, possibly nested in other groups) they are the compound
// path's subpaths, as its other grouped paths are: the compound clipping path, their union.
if matches!(kind, Kind::Group)
&& unread.is_empty()
&& !clips.is_empty()
&& clips.len() == kids.len()
&& matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. }))
&& (matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) || self.in_compound())
{
for kid in kids {
if let Some(parent) = self.frames.last_mut() {
@@ -212,6 +214,18 @@ impl<'a> Reader<'a> {
Ok(())
}
/// Is the innermost open frame a compound path (`*u`), or a group in one with only groups between them?
fn in_compound(&self) -> bool {
for f in self.frames.iter().rev() {
match f.kind {
Kind::Group => {}
Kind::Compound => return true,
_ => return false,
}
}
false
}
/// The compound path of `kids`, painted and made transparent as its subpaths say.
fn compound(&mut self, mut kids: Vec<Node>, gs: &GState) -> Option<Node> {
// The compound path's paint is its last path's (a gradient's instance wraps only
+36
View File
@@ -1734,6 +1734,42 @@ fn a_clipping_path_alone_in_a_group_clips_its_clipping_group() {
assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)));
}
/// Clipping paths grouped in a compound path (`*u u <path> W n … U *U`, possibly nested in other groups) are
/// the compound path's subpaths, as its other grouped paths are: the compound clipping path, their union, clips its
/// clipping group, however many there are and wherever in the group it is written.
#[test]
fn clipping_paths_grouped_in_a_compound_path_are_its_subpaths() {
let square = rect_path(0.0, 0.0, 80.0, 80.0);
let (a, b, c) = (rect_path(0.0, 0.0, 10.0, 10.0), rect_path(30.0, 0.0, 40.0, 10.0), rect_path(60.0, 0.0, 70.0, 10.0));
let clip = |p: &str| format!("{p}h\nW\nn\n");
let bodies = [
// One group of them, after the art.
format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}{}{}U\n*U\nQ\n", clip(&a), clip(&b), clip(&c)),
// Groups in a group, and one path straight in the compound path, before the art.
format!("0 Ae\nq\n*u\n0 Ae\nu\n0 Ae\nu\n{}{}U\n0 Ae\nu\n{}U\nU\n*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)),
format!("0 Ae\nq\n*u\n0 Ae\nu\n{}{}U\n{}*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)),
];
for body in &bodies {
let doc = read_ok(&layer(body)).doc;
let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{body}: {:?}", art(&doc)[0].kind) };
assert_eq!(children.len(), 2, "{body}: {children:?}");
let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{body}: {:?}", children[0].kind) };
assert_eq!(subpaths.len(), 3, "{body}: {subpaths:?}");
assert!(subpaths.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: true, .. })), "{body}: {subpaths:?}");
assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{body}");
}
// Hundreds of them, one union: not clipping groups nested past the document's depth limit.
let many = format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}U\n*U\nQ\n", clip(&a).repeat(300));
let doc = read_ok(&layer(&many)).doc;
let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) };
let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) };
assert_eq!(subpaths.len(), 300);
// A group of clipping paths outside a compound path or a clipping group is read as before: a clipping group.
let alone = format!("0 Ae\nu\n{}{}U\n{RED}{square}f\n", clip(&a), clip(&b));
let doc = read_ok(&layer(&alone)).doc;
assert!(matches!(art(&doc)[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", art(&doc)[0].kind);
}
/// #1410: a compound path shows its last path's paint, and paths grouped in it stay its paths.
#[test]
fn compound_path_takes_its_last_paths_paint() {
+27 -1
View File
@@ -1189,6 +1189,12 @@ impl Story {
self.text.len()
}
/// Is frame `frame` of the story point type with nothing but spaces and line ends (its last
/// `\r` left out), which [`Self::node`] doesn't make: it draws nothing.
pub(super) fn blank_point(&self, frame: usize) -> bool {
frame == 0 && matches!(self.frames.first(), Some(FrameKind::Point(_))) && self.is_blank()
}
/// The point frame's matrix (the first frame's, when it is one), else the identity.
fn matrix(&self) -> [f64; 6] {
match self.frames.first() {
@@ -1260,6 +1266,24 @@ impl Story {
/// document), or `None` for type that is mirrored, has no size, or a frame past the first of
/// threaded type (the first frame holds the whole story).
pub(super) fn node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option<Node> {
self.made_node(id, frame, template, to_doc, false)
}
/// For a blank story (nothing but spaces and line ends) in an area frame or on a path, an empty
/// text object with that frame or path, as [`Self::node`] would make it, as VectorCraft's Type
/// tool keeps such an empty frame (#85, #154). Its text is the story's, spaces kept. `None` for
/// any other story or frame.
pub(super) fn blank_frame_node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option<Node> {
self.is_blank().then(|| self.made_node(id, frame, template, to_doc, true)).flatten()
}
/// Is the story's text nothing but spaces and line ends (`\r`, and `\x03`, a line break)?
pub(super) fn is_blank(&self) -> bool {
self.text.chars().all(|c| c.is_whitespace() || c == '\x03')
}
/// [`Self::node`]; with `blank_frame`, a blank story in an area frame or on a path is made too.
fn made_node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine, blank_frame: bool) -> Option<Node> {
let kind = self.frames.get(frame)?;
let threaded = frame > 0;
let (scale, xf, kind) = match kind {
@@ -1301,7 +1325,9 @@ impl Story {
})
.collect()
};
if text.trim().is_empty() && !threaded {
// A blank story isn't made here: the page may still have type for its object. What is left
// of one, an area frame or a path, is made by [`Self::blank_frame_node`].
if text.trim().is_empty() && !threaded && !(blank_frame && !matches!(kind, TextKind::Point)) {
return None;
}
// The text document measures in the art's units too: the document's scale carries its
+102 -11
View File
@@ -531,12 +531,12 @@ pub(super) fn build_weighing(
clip_by_type(&mut layers, &type_clips, &filled);
doc.layers = layers;
made.sort();
let threaded_frames: BTreeSet<NodeId> =
made.chunk_by(|a, b| a.0 == b.0).filter(|thread| thread.len() > 1).flatten().map(|(_, _, id)| *id).collect();
let threads = threads_of(&made);
let threaded_frames: BTreeSet<NodeId> = threads.iter().flat_map(|(_, ids)| ids.iter().copied()).collect();
if !unread.is_empty() {
let Some(frame) = frame.as_ref() else { return Err(unread_error(&unread)) };
let mut copied = BTreeSet::new();
let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &threaded_frames, &mut copied)?;
let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &held_frames(&infos, &stories, &threads), &mut copied)?;
// With the text objects filled, the page art chosen can differ from the first try's: the
// page's type set aside for it, and no other, must be in it.
let all_copied = |o: &Vec<Arc<Node>>| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id));
@@ -545,12 +545,8 @@ pub(super) fn build_weighing(
}
notes.push(format!("{}: they came in as the page's art", kinds.join(", ")));
}
// A story in several frames is threaded type: its frames in order (the first holds the story).
for thread in made.chunk_by(|a, b| a.0 == b.0) {
if thread.len() > 1 {
doc.text_threads.push(thread.iter().map(|(_, _, id)| *id).collect());
}
}
// The frames still threaded: a blank story's frame an unread object left alone isn't.
let threaded_frames = add_threads(&mut doc, threads, &threaded_frames, !unread.is_empty());
// Area type flows around the wrap objects above it before it is compared with the page.
resolve_text_wrap(&mut doc)?;
let bound_text = bound_slots(&doc, &bindings, &xml_ids, VariableKind::Text);
@@ -1485,7 +1481,9 @@ fn slot_content(
) -> Result<(Vec<Content>, bool), String> {
let made = make_slots(infos, stories, template, to_doc, notes);
if let Some(own) = own.filter(|_| readable_all(infos, &made)) {
return Ok((made_only(infos, made, [own, pages[1]], notes), true));
let mut content = made_only(infos, stories, made, [own, pages[1]], notes);
settle_blank_stories(infos, stories, template, to_doc, &mut content, notes);
return Ok((content, true));
}
// The page's type is matched with every text object whose type isn't made, and weighed against
// where every made one draws: that has its limits (the slots of type that looks draw are within
@@ -1494,7 +1492,100 @@ fn slot_content(
if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS {
return Err("it has too many text objects".into());
}
Ok((plan(infos, stories, made, template, to_doc, pages, notes), false))
let mut content = plan(infos, stories, made, template, to_doc, pages, notes);
settle_blank_stories(infos, stories, template, to_doc, &mut content, notes);
Ok((content, false))
}
/// The threads of the text objects `made` (story, frame and id of each, sorted): each story in
/// several frames, with its frames in order (the first holds the story).
fn threads_of(made: &[(u32, usize, NodeId)]) -> Vec<(u32, Vec<NodeId>)> {
made.chunk_by(|a, b| a.0 == b.0)
.filter(|thread| thread.len() > 1)
.map(|thread| (thread[0].0, thread.iter().map(|(_, _, id)| *id).collect()))
.collect()
}
/// The frames of `threads` that an unread object can't take with it: those of a blank story's thread
/// hold no type, so they may go.
fn held_frames(infos: &[SlotInfo], stories: &[Option<Arc<Story>>], threads: &[(u32, Vec<NodeId>)]) -> BTreeSet<NodeId> {
let blank: BTreeSet<u32> =
infos.iter().zip(stories).filter(|(_, s)| s.as_ref().is_some_and(|s| s.is_blank())).filter_map(|(i, _)| i.story).collect();
threads.iter().filter(|(story, _)| !blank.contains(story)).flat_map(|(_, ids)| ids.iter().copied()).collect()
}
/// `threads` as `doc`'s text threads, and the frames of the threads added. With `replaced` (unread
/// objects were replaced by page art), the frames they took with them (`frames` that `doc` no longer
/// has, only a blank story's) are left out, and so is a thread left with one frame.
fn add_threads(doc: &mut Document, threads: Vec<(u32, Vec<NodeId>)>, frames: &BTreeSet<NodeId>, replaced: bool) -> BTreeSet<NodeId> {
let present = replaced.then(|| doc.index_paths(frames.iter().copied()));
let mut threaded = BTreeSet::new();
for (_, mut ids) in threads {
if let Some(present) = &present {
ids.retain(|id| present.contains_key(id));
}
if ids.len() > 1 {
threaded.extend(ids.iter().copied());
doc.text_threads.push(ids);
}
}
threaded
}
/// The slots of blank stories (nothing but spaces and line ends) that neither the text document nor
/// the page fills: blank point type draws nothing and has nothing to keep, so it is left out without
/// a note, as VectorCraft's Type tool discards empty point type (#85, #154); blank area type and
/// type on a path come in as an empty text object with their frame or path, as the Type tool keeps
/// such an empty frame, also where the page's type went to another text object (`Merged`). An empty
/// frame draws nothing, so the page can't show it: it is kept without being weighed against the
/// page (`prune_unseen` would take it out), and so are the later frames of its thread, which the
/// text document makes empty. Type that a look draws is left as it is.
fn settle_blank_stories(
infos: &[SlotInfo],
stories: &[Option<Arc<Story>>],
template: Option<(f64, f64)>,
to_doc: Affine,
content: &mut [Content],
notes: &mut Vec<String>,
) {
// The stories whose first frame came in as an empty frame: their later frames stay with it.
let mut kept = BTreeSet::new();
for ((story, info), c) in stories.iter().zip(infos).zip(content.iter_mut()) {
let Some(story) = story.as_ref().filter(|s| s.is_blank() && info.look.is_none()) else { continue };
let unfilled = match c {
Content::Empty => true,
Content::Page(parts) => parts.is_empty(),
_ => false,
};
if story.blank_point(info.frame) {
if unfilled {
*c = Content::Merged;
}
} else if (unfilled || matches!(c, Content::Merged))
&& let Some((node, region)) = template.and_then(|t| super::plan::blank_frame(info, story, t, to_doc))
{
*c = Content::Made(node, region.filter(|_| info.shown), true);
kept.extend(info.story);
// Its paragraphs' settings are read as made type's are, with the same notes.
for (left_out, note) in [
(story.tabs_left_out(), crate::import::ate::TABS_LEFT_OUT),
(story.kinsoku_sets_left_out(), crate::import::ate::KINSOKU_SETS_LEFT_OUT),
] {
if left_out && !notes.iter().any(|n| n == note) {
notes.push(note.into());
}
}
}
}
for (info, c) in infos.iter().zip(content.iter_mut()) {
if let Content::Made(_, _, seen) = c
&& info.frame > 0
&& info.look.is_none()
&& info.story.is_some_and(|s| kept.contains(&s))
{
*seen = true;
}
}
}
/// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the
+52 -18
View File
@@ -66,17 +66,10 @@ pub(super) fn make_slots(
.map(|(k, info)| {
let t = template?;
let story = stories.get(k)?.as_ref()?;
let mut node = story.node(NodeId(0), info.frame, t, to_doc)?;
let node = story.node(NodeId(0), info.frame, t, to_doc)?;
tabs_left_out |= story.tabs_left_out();
kinsoku_left_out |= story.kinsoku_sets_left_out();
let mut region = story.region(t, to_doc);
// The first line where the file has it, in the text document's frame (that of a
// copied object is its original's, as its lines are).
story.place_first_line(&mut node, info.frame, t, to_doc);
// Area type and type on a path in the object's own frame: the text document's frame
// of a copied object keeps its original's path.
frame_text_from_art(info, &mut node, &mut region);
story.flip_on_path(&mut node, info.frame);
let (mut node, region) = placed(info, story, node, t, to_doc);
if let NodeKind::Text(text) = &mut node.kind
&& story.fit_first_line(text)
{
@@ -109,6 +102,28 @@ pub(super) fn make_slots(
made
}
/// The empty text object a slot of a blank story in an area frame or on a path comes in as, placed
/// as [`make_slots`] places made type: its frame or path, the object's own where it has one
/// ([`Story::blank_frame_node`]). `None` for any other slot.
pub(super) fn blank_frame(info: &SlotInfo, story: &Story, template: (f64, f64), to_doc: Affine) -> Option<Made> {
let node = story.blank_frame_node(NodeId(0), info.frame, template, to_doc)?;
let (node, region) = placed(info, story, node, template, to_doc);
Some((Box::new(node), region))
}
/// `node`, made from `story` for slot `info`, placed where the file has it, with the region it
/// draws in: the first line where the file has it, in the text document's frame (that of a copied
/// object is its original's, as its lines are); area type and type on a path in the object's own
/// frame (the text document's frame of a copied object keeps its original's path); type on a path
/// flipped as its frame keeps it.
fn placed(info: &SlotInfo, story: &Story, mut node: Node, template: (f64, f64), to_doc: Affine) -> (Node, Option<Rect>) {
let mut region = story.region(template, to_doc);
story.place_first_line(&mut node, info.frame, template, to_doc);
frame_text_from_art(info, &mut node, &mut region);
story.flip_on_path(&mut node, info.frame);
(node, region)
}
/// Does the file's text document make the type of every slot that shows (at least one does)? Type
/// that a look draws doesn't count: only the page has it.
pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option<Made>]) -> bool {
@@ -122,7 +137,13 @@ pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option<Made>]) -> bool {
/// that no made type takes, shown or not, is left out with a note in `warn`. Slots that don't show
/// and whose type isn't made take the page's type that doesn't show (`pages`: the page's text
/// objects that show and that don't), by painting order.
pub(super) fn made_only(infos: &[SlotInfo], made: Vec<Option<Made>>, pages: [&[Vec<Arc<Node>>]; 2], warn: &mut Vec<String>) -> Vec<Content> {
pub(super) fn made_only(
infos: &[SlotInfo],
stories: &[Option<Arc<Story>>],
made: Vec<Option<Made>>,
pages: [&[Vec<Arc<Node>>]; 2],
warn: &mut Vec<String>,
) -> Vec<Content> {
let [shown, hidden] = pages;
let mut content = made_content(infos, made);
// The page's type where no made type draws, in the copies that looks draw, is theirs (past
@@ -154,7 +175,7 @@ pub(super) fn made_only(infos: &[SlotInfo], made: Vec<Option<Made>>, pages: [&[V
None => warn.push(PAGE_TYPE_UNCHECKED.into()),
}
drop_look_slots(infos, &mut content);
fill_hidden(infos, &mut content, hidden);
fill_hidden(infos, stories, &mut content, hidden);
content
}
@@ -421,8 +442,10 @@ pub(super) fn plan(
}
fill_look_slots(infos, &mut content, &mut spare);
// What is left of the page goes by painting order into the shown slots the file can't say.
let loose: Vec<usize> =
infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect();
let loose = readable_first(
stories,
infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(),
);
if loose.is_empty() {
// Type of the page that no text object says it owns goes with the nearest text object that has
// type of the page (never into made type); with none, it is left out.
@@ -466,17 +489,28 @@ pub(super) fn plan(
warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into());
}
}
fill_hidden(infos, &mut content, hidden);
fill_hidden(infos, stories, &mut content, hidden);
content
}
/// The slots `open` that are to take the page's type left over, by painting order: those of blank
/// stories (nothing but spaces and line ends) only when no other slot is open, as such a story has
/// no type of its own; the blank ones left out come in empty or not at all (see
/// `settle_blank_stories`).
fn readable_first(stories: &[Option<Arc<Story>>], open: Vec<usize>) -> Vec<usize> {
let blank = |k: &usize| stories.get(*k).and_then(Option::as_ref).is_some_and(|s| s.is_blank());
if open.iter().all(blank) { open } else { open.into_iter().filter(|k| !blank(k)).collect() }
}
/// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't
/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object
/// show and have nothing yet ([`readable_first`]), but for what is the type of made type that doesn't show: a page object
/// with words and at least half of it where such type draws, while the type has all its words left
/// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes.
fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec<Arc<Node>>]) {
let unread: Vec<usize> =
infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect();
fn fill_hidden(infos: &[SlotInfo], stories: &[Option<Arc<Story>>], content: &mut [Content], hidden: &[Vec<Arc<Node>>]) {
let unread = readable_first(
stories,
infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(),
);
if unread.is_empty() {
return;
}
+3 -2
View File
@@ -2,7 +2,7 @@ use super::build::MADE;
use super::{AppearanceItem, Arc, BTreeSet, BlendMode, Document, Node, NodeId, NodeKind, PathData, Point, Rect, ai, slot_of};
/// The notes that say the import left out something the file has (see [`is_loss`]).
pub(super) const TEXT_LEFT_OUT: &str = "text objects on hidden layers or hidden objects couldn't be read, so they are left out";
pub(super) const TEXT_LEFT_OUT: &str = "text objects whose type couldn't be read from the file's text document or its page are left out";
/// The same for a file without a page to take shown type from.
pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn't read from the file's text document yet are left out";
@@ -230,7 +230,8 @@ pub(super) enum Content {
/// Text objects (with the strokes round them) of the page.
Page(Vec<Arc<Node>>),
/// A text object made from the file's text document, where it draws on the document (when it
/// shows), and whether the page has type where it is.
/// shows), and whether it is kept without being weighed against the page: the page has type
/// where it is, or it draws nothing (an empty frame of a blank story).
Made(Box<Node>, Option<Rect>, bool),
/// Nothing the file lets this read.
Empty,
+269 -1
View File
@@ -3830,7 +3830,7 @@ fn type_with_a_frame_it_cant_read_is_left_out_with_a_note() {
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert!(text_of(&r.document.layers[1]).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("1 text objects on hidden layers")), "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("1 text objects whose type couldn't be read")), "{:?}", r.warnings);
assert!(crate::is_loss(r.warnings.iter().find(|w| w.contains("couldn't be read")).unwrap()));
}
@@ -5030,6 +5030,274 @@ fn area_type_keeps_its_area_type_options() {
assert_eq!(texts[2].area, vectorcraft_doc::AreaOptions::default());
}
/// A blank story in an area frame, hidden or shown, comes in as a text object that keeps its frame
/// and draws nothing (its spaces kept), as VectorCraft's Type tool keeps an empty frame (#85, #154).
/// As point type, hidden or shown, it draws nothing and has nothing to keep: it is left out, without
/// a note that something wasn't read.
#[test]
fn blank_stories_keep_their_area_frame_and_leave_point_type_out_quietly() {
let frames = [area_frame(10.0, 50.0, 90.0, 90.0), point_frame(20.0, 20.0), point_frame(30.0, 30.0), area_frame(60.0, 10.0, 90.0, 40.0)];
let stories = [
story("\\r", &[0], "/0 0", "/1 6.0"),
story("\\r", &[1], "/0 0", "/1 6.0"),
story(" \\r", &[2], "/0 0", "/1 6.0"),
story(" \\r", &[3], "/0 0", "/1 6.0"),
];
let doc = document_of(&frames, &stories);
// A shown blank area frame too: it draws nothing, so the page can't show it, and it stays.
let shown = square(10, 10) + &text_object(2) + &text_object(3);
let art = native_with_text(&(layer("Back", true, &shown) + &layer("Spare", false, &(text_object(0) + &text_object(1)))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 1, "{:?}", r.warnings);
assert_eq!(texts[0].plain_text(), "");
let vectorcraft_doc::TextKind::Area { frame } = &texts[0].kind else { panic!("area type: {:?}", texts[0].kind) };
// Art y 50..90 is 10..50 down the 100 pt page.
let b = frame.bounds().unwrap();
assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 10.0).abs() < 1e-6 && (b.x1 - 90.0).abs() < 1e-6 && (b.y1 - 50.0).abs() < 1e-6, "{b:?}");
let shown = text_of(&r.document.layers[0]);
assert_eq!(shown.len(), 1, "{:?}", r.warnings);
assert_eq!(shown[0].plain_text(), " ");
let vectorcraft_doc::TextKind::Area { frame } = &shown[0].kind else { panic!("area type: {:?}", shown[0].kind) };
// Art y 10..40 is 60..90 down the page.
let b = frame.bounds().unwrap();
assert!((b.x0 - 60.0).abs() < 1e-6 && (b.y0 - 60.0).abs() < 1e-6 && (b.x1 - 90.0).abs() < 1e-6 && (b.y1 - 90.0).abs() < 1e-6, "{b:?}");
assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings);
}
/// A blank story whose object the page still draws type for takes the page's type, as before: the
/// empty frame is only for a slot nothing else fills.
#[test]
fn a_blank_area_story_the_page_draws_type_for_takes_the_pages_type() {
let doc = document_of(&[area_frame(10.0, 50.0, 90.0, 90.0)], &[story("\\r", &[0], "/0 0", "/1 6.0")]);
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 20 75 moveto (Hi there) show";
let r = import(&eps(page, &art)).unwrap();
let mut all = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
all.push(t.plain_text());
}
});
assert_eq!(all, ["Hi there".to_string()], "{:?}", r.warnings);
}
/// The text objects of `d`: each one's text and kind, in the layers' order.
fn text_kinds(d: &Document) -> Vec<(String, &'static str)> {
let mut out = vec![];
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
let kind = match t.kind {
vectorcraft_doc::TextKind::Area { .. } => "area",
vectorcraft_doc::TextKind::OnPath { .. } => "path",
_ => "point",
};
out.push((t.plain_text(), kind));
}
});
out
}
/// A blank story threaded through two shown area frames comes in as both frames, empty and still
/// one thread: the later frame the text document makes empty stays with the first.
#[test]
fn a_blank_story_threaded_through_two_shown_frames_keeps_both() {
let frames = [area_frame(10.0, 60.0, 40.0, 80.0), area_frame(50.0, 60.0, 80.0, 80.0)];
let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]);
let art = native_with_text(&layer("Art", true, &(square(10, 10) + &frame_object(0, 0) + &frame_object(0, 1))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
// The thread names only text objects the document has.
assert!(r.document.text_threads.iter().flatten().all(|id| r.document.node(*id).is_some()), "{:?} {:?}", r.document.text_threads, r.warnings);
assert_eq!(text_kinds(&r.document), [("".to_string(), "area"), ("".to_string(), "area")], "{:?}", r.warnings);
let ids: Vec<_> = r.document.layers[0].children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id).collect();
assert_eq!(r.document.text_threads, [ids]);
}
/// A blank story threaded from a hidden frame into a shown one: both frames come in, one thread.
#[test]
fn a_blank_story_threaded_from_a_hidden_frame_into_a_shown_one_keeps_both() {
let frames = [area_frame(10.0, 60.0, 40.0, 80.0), area_frame(50.0, 60.0, 80.0, 80.0)];
let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]);
let art = native_with_text(&(layer("Back", true, &(square(10, 10) + &frame_object(0, 1))) + &layer("Spare", false, &frame_object(0, 0))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert!(r.document.text_threads.iter().flatten().all(|id| r.document.node(*id).is_some()), "{:?} {:?}", r.document.text_threads, r.warnings);
assert_eq!(text_kinds(&r.document), [("".to_string(), "area"), ("".to_string(), "area")], "{:?}", r.warnings);
assert_eq!(r.document.text_threads.len(), 1, "{:?}", r.warnings);
assert_eq!(r.document.text_threads[0].len(), 2, "{:?}", r.warnings);
}
/// An unread group holding a frame of a blank story's thread is replaced by its page art as for
/// any other text object (the frame holds no type): the layers are read, and the thread, left with
/// one frame, isn't one any more.
#[test]
fn unread_group_holding_a_blank_threaded_frame_is_replaced() {
let frames = [
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)),
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)),
];
let text = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]);
for removed in [0, 1] {
let grouped = os1_group(&format!("{}\n{}\nZZ", square(if removed == 0 { 50 } else { 70 }, 10), frame_object(0, removed)));
let other = frame_object(0, 1 - removed);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{other}"))), &text);
let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0);
assert!(read, "removed frame {removed}: {notes:?}");
assert!(doc.text_threads.is_empty(), "removed frame {removed}: {:?} {notes:?}", doc.text_threads);
assert_eq!(text_kinds(&doc), [("".to_string(), "area")], "removed frame {removed}: {notes:?}");
}
}
/// A blank story on a path comes in as empty type on that path.
#[test]
fn a_blank_story_on_a_path_keeps_its_path() {
let (a, b, c) = (canvas(10.0, 70.0), canvas(30.0, 70.0), canvas(50.0, 70.0));
let path = format!(
"<< /0 << /0 [ 0 0 ] /1 << /0 [ {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} ] >> /2 << /0 2 /6 [ 0.5 2.0 ] >> >> >>",
a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1, b.0, b.1, b.0, b.1, c.0, c.1, c.0, c.1
);
let doc = document_of(&[path], &[story("\\r", &[0], "/0 0", "/1 8.0")]);
let art = native_with_text(&layer("Art", true, &(square(10, 10) + &text_object(0))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert_eq!(text_kinds(&r.document), [("".to_string(), "path")], "{:?}", r.warnings);
let mut on_path = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind
&& let vectorcraft_doc::TextKind::OnPath { path, start, end } = &t.kind
{
on_path.push((path.bounds(), *start, *end));
}
});
// The path as `area_type_and_type_on_a_path_come_from_the_text_document` reads it: 40 pt long,
// the type from a quarter of the way along.
let [(Some(b), start, end)] = on_path.as_slice() else { panic!("{on_path:?}") };
assert!((b.width() - 40.0).abs() < 1e-6 && (start - 0.25).abs() < 1e-3 && end.is_none(), "{b:?} {start} {end:?}");
}
/// Where every shown text object's type comes from the text document (the page isn't matched with
/// them), a hidden blank area story still comes in as its empty frame, and blank point type is left
/// out without a note.
#[test]
fn blank_stories_beside_type_the_text_document_makes() {
let frames = [point_frame(20.0, 20.0), area_frame(10.0, 50.0, 90.0, 90.0), point_frame(30.0, 30.0)];
let stories = [story("Hi there\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0"), story("\\r", &[2], "/0 0", "/1 6.0")];
let doc = document_of(&frames, &stories);
let art = native_with_text(
&(layer("Back", true, &(square(10, 10) + &text_object(0))) + &layer("Spare", false, &(text_object(1) + &text_object(2)))),
&doc,
);
// The page draws the square and "Hi there" where the text document sets it.
let page = format!("{}\n0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 20 20 moveto (Hi there) show", page_square(10, 10));
let r = import(&eps(&page, &art)).unwrap();
assert_eq!(text_kinds(&r.document), [("Hi there".to_string(), "point"), ("".to_string(), "area")], "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings);
}
/// Without a page (the editing data alone), a blank area story comes in as its empty frame and
/// blank point type is left out, without the note for type of kinds that aren't read.
#[test]
fn blank_stories_without_a_page() {
let frames = [area_frame(10.0, 50.0, 90.0, 90.0), point_frame(30.0, 30.0)];
let doc = document_of(&frames, &[story("\\r", &[0], "/0 0", "/1 6.0"), story(" \\r", &[1], "/0 0", "/1 6.0")]);
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
assert_eq!(text_kinds(&d), [("".to_string(), "area")], "{notes:?}");
assert!(!notes.iter().any(|w| w.contains("left out")), "{notes:?}");
}
/// The page's spare type goes to a shown text object the text document can't make, not to a blank
/// story beside it, whichever the page paints first: the blank area story comes in as its empty
/// frame. A blank slot takes the page's type only where no other slot is open.
#[test]
fn spare_page_type_goes_to_the_unread_object_not_the_blank_one() {
// Story 0's frame is of a kind this doesn't read, so neither shown object is made: the page's
// one piece of type is spare.
let frames = [point_frame(20.0, 20.0).replace("/2 << /2 [", "/2 << /0 9 /2 ["), area_frame(10.0, 50.0, 90.0, 90.0)];
let doc = document_of(&frames, &[story("Hi there\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0")]);
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 20 20 moveto (Hi there) show";
for (order, body) in [("blank first", text_object(1) + &text_object(0)), ("blank last", text_object(0) + &text_object(1))] {
let art = native_with_text(&layer("Art", true, &body), &doc);
let r = import(&eps(page, &art)).unwrap();
let mut texts = text_kinds(&r.document);
texts.sort();
assert_eq!(texts, [("".to_string(), "area"), ("Hi there".to_string(), "point")], "{order}: {:?}", r.warnings);
}
}
/// Two shown blank area stories and one piece of the page's type that no text object owns: with no
/// other slot open, the blank ones take it by painting order; the one left without type comes in as
/// its empty frame, not dropped as merged type.
#[test]
fn a_blank_area_story_the_spare_page_type_skips_keeps_its_frame() {
let frames = [area_frame(10.0, 50.0, 90.0, 90.0), area_frame(10.0, 5.0, 40.0, 30.0)];
let doc = document_of(&frames, &[story("\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0")]);
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
// Away from both frames, so neither owns it.
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 60 40 moveto (Hi there) show";
let r = import(&eps(page, &art)).unwrap();
let mut texts = text_kinds(&r.document);
texts.sort();
assert_eq!(texts, [("".to_string(), "area"), ("Hi there".to_string(), "point")], "{:?}", r.warnings);
}
/// A warp or an envelope holding the second frame of a blank story threaded from a frame outside
/// it: a thread names only text objects the document has. The warped frame stays type, and the
/// thread stays whole, as for other threaded type, whatever the warp's look draws; the frame in the
/// envelope comes in as the envelope's drawn art, and no thread is left.
#[test]
fn a_warp_or_an_envelope_holding_a_frame_of_a_blank_thread_keeps_its_thread_of_text() {
let frames = [area_frame(10.0, 5.0, 40.0, 30.0), area_frame(20.0, 40.0, 80.0, 70.0)];
let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]);
let envelope = type_envelope_of(0, &arc_keys(0.3), &format!("{}\n", square(30, 50)), "").replace("%_0 /FrameIndex ,", "%_1 /FrameIndex ,");
assert!(envelope.contains("%_1 /FrameIndex ,"));
let warp: String = frame_object(0, 1).lines().map(|l| format!("%_{l}\n")).collect();
let warped = format!("u\n0 1 1 0 1 0 0 Xa\n2 2 m\n9 2 L\n9 9 L\n2 9 L\nf\nU\n9 () XW\n{warp}1 (Warped) XW\n");
let check = |what: &str, d: &Document, notes: &[String]| {
assert!(
d.text_threads.iter().flatten().all(|id| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))),
"{what}: {:?} {notes:?}",
d.text_threads
);
};
let art = native_with_text(&layer("Art", true, &format!("{}\n{}\n{envelope}", square(10, 10), frame_object(0, 0))), &doc);
// The page draws the envelope's drawn art.
let r = import(&eps(&format!("{}\n{}", page_square(10, 10), page_square(30, 50)), &art)).unwrap();
check("envelope, with the page", &r.document, &r.warnings);
assert!(r.document.text_threads.is_empty(), "{:?} {:?}", r.document.text_threads, r.warnings);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
check("envelope, editing data alone", &d, &notes);
assert!(d.text_threads.is_empty(), "{:?} {notes:?}", d.text_threads);
let art = native_with_text(&(warped_style(40.0, WarpOn::Object) + &layer("Art", true, &format!("{}\n{warped}", frame_object(0, 0)))), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
check("warp", &d, &notes);
assert_eq!(d.text_threads.len(), 1, "{notes:?}");
assert!(!notes.iter().any(|w| w.starts_with(crate::import::ai::WARPED_TYPE_DRAWN)), "{notes:?}");
}
/// A blank story's thread whose first frame an unread group takes with it leaves its other frame
/// alone, no longer threaded: in a warp, that frame is weighed against its look as any warped text
/// object is (the look draws a square the empty frame doesn't, so the look takes its place).
#[test]
fn a_blank_frame_an_unread_group_leaves_alone_in_a_warp_is_weighed_as_lone_type() {
let frames = [
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)),
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)),
];
let text = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]);
let grouped = os1_group(&format!("{}\n{}\nZZ", square(50, 10), frame_object(0, 0)));
let own: String = frame_object(0, 1).lines().map(|l| format!("%_{l}\n")).collect();
let warped = format!("u\n0 1 1 0 1 0 0 Xa\n70 10 m\n74 10 L\n74 14 L\n70 14 L\nf\nU\n9 () XW\n{own}1 (Warped) XW\n");
let art = native_with_text(
&(warped_style(40.0, WarpOn::Object) + &layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{warped}"))),
&text,
);
let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0);
assert!(read, "{notes:?}");
assert!(doc.text_threads.is_empty(), "{:?} {notes:?}", doc.text_threads);
assert!(notes.iter().any(|w| w.starts_with(crate::import::ai::WARPED_TYPE_DRAWN)), "{notes:?}");
// The look took the frame's place: no text object is left.
assert!(text_kinds(&doc).is_empty(), "{:?} {notes:?}", text_kinds(&doc));
}
/// A point type frame at the point (`x`, `y`) of the art.
fn point_frame(x: f64, y: f64) -> String {
let (cx, cy) = canvas(x, y);
+22 -3
View File
@@ -78,6 +78,18 @@ fn update_editing_hash(svg: &mut String) {
}
}
/// Format physical dimensions (inches, mm, cm) with enough precision and significant digits
/// that small nonzero sizes do not round to zero or distort relative aspect ratio.
fn physical_num(v: f64) -> String {
if !v.is_finite() || v <= 0.0 {
return "0".into();
}
let leading_zeros = (-v.log10().floor() as i32).max(0);
let decimals = (leading_zeros + 3).clamp(3, 14) as u8;
let s = fmt_num(v, decimals);
if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
}
/// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated
/// ids starting with `id_prefix`.
fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: &str) -> Output {
@@ -183,10 +195,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
root = root.attr("version", "1.2").attr("baseProfile", "tiny");
}
if !opts.responsive {
// Unitless width/height stay in this one branch so #7105 (physical unit suffixes) can rebase here.
root = root.attr("width", &ww).attr("height", &hh);
if let Some(suffix) = doc.units.svg_suffix() {
let w_val = physical_num(doc.units.from_pt(rect.width()));
let h_val = physical_num(doc.units.from_pt(rect.height()));
root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}"));
} else {
root = root.attr("width", &ww).attr("height", &hh);
}
}
root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open();
let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() };
let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() };
root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open();
let mut out = svg.as_str().to_string();
out.push_str(nl);
let css = opts.styling == Styling::InternalCss && !w.classes.is_empty();
+39 -2
View File
@@ -29,7 +29,7 @@
use craft_svg::tree::usvg;
use std::borrow::Cow;
use std::cell::RefCell;
use std::cell::{OnceCell, RefCell};
use std::collections::HashMap;
use std::fmt::Write as _;
use std::ops::{Range, RangeInclusive};
@@ -774,6 +774,10 @@ struct Ctx {
/// no usable one. The styles of a `<use>` instance share it, so each path is found and parsed
/// once however many `<use>` elements show its text.
paths: Rc<RefCell<HashMap<roxmltree::NodeId, Option<Rc<FollowedPath>>>>>,
/// Each element id in the document and the first element in document order that carries it
/// ([`Self::element`]). It is built when the first `<textPath>` names an element, and the
/// styles of a `<use>` instance share it.
ids: Rc<OnceCell<HashMap<Box<str>, roxmltree::NodeId>>>,
}
/// The path a `<textPath>` follows ([`Ctx::text_path`]).
@@ -788,6 +792,11 @@ struct FollowedPath {
thread_local! {
/// How many times [`Ctx::read_text_path`] has read a `<textPath>`'s path on this thread.
static TEXT_PATH_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// How many times [`Ctx::element`] has walked a document's elements on this thread.
static ID_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// When set, [`Ctx::element`] walks the document for each id instead of using the map, so
/// tests can compare the two.
static LINEAR_IDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
impl Ctx {
@@ -802,6 +811,7 @@ impl Ctx {
elems: RefCell::default(),
strong: RefCell::default(),
paths: Rc::default(),
ids: Rc::default(),
};
let root = xml.root_element();
let dim = |a: &str| root.attribute(a).and_then(|v| cx.length(v, DEFAULT_FONT_SIZE, 0.0)).filter(|v| *v > 0.0);
@@ -824,6 +834,7 @@ impl Ctx {
elems: RefCell::default(),
strong: RefCell::default(),
paths: self.paths.clone(),
ids: self.ids.clone(),
}
}
@@ -1219,7 +1230,7 @@ impl Ctx {
Some(d) => BezPath::from_svg(d).ok()?,
None => {
let id = href(tp)?.trim().strip_prefix('#')?;
let el = xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id))?;
let el = self.element(xml, id)?;
let d = match el.tag_name().name() {
"path" => el.attribute("d")?.to_string(),
_ => self.shape_path(el)?,
@@ -1238,6 +1249,32 @@ impl Ctx {
usable.then_some(FollowedPath { path: bp, author_length })
}
/// The first element in document order whose `id` is `id`, as the DOM's `getElementById`
/// finds it (https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid). The first
/// call walks `xml` once to build [`Self::ids`]; later calls look the id up there. `xml` is
/// the document [`Self::new`] read.
fn element<'a, 'i>(&self, xml: &'a roxmltree::Document<'i>, id: &str) -> Option<XNode<'a, 'i>> {
#[cfg(test)]
if LINEAR_IDS.get() {
ID_WALKS.set(ID_WALKS.get() + 1);
return xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id));
}
let ids = self.ids.get_or_init(|| {
#[cfg(test)]
ID_WALKS.set(ID_WALKS.get() + 1);
let mut ids = HashMap::new();
for n in xml.descendants().filter(|n| n.is_element()) {
if let Some(id) = n.attribute("id") {
ids.entry(Box::from(id)).or_insert(n.id());
}
}
ids
});
let el = xml.get_node(*ids.get(id)?)?;
debug_assert_eq!(el.attribute("id"), Some(id), "the id map was built from another document");
Some(el)
}
/// The equivalent path of a basic shape (SVG 2 › Basic Shapes), as path data: what a
/// `<textPath>` that points at it follows. Circles and ellipses start at 3 o'clock and rounded
/// rects at the end of the top-left corner, all running clockwise; lines and polylines follow
+132
View File
@@ -1,4 +1,5 @@
use super::*;
use vectorcraft_doc::Document;
/// The texts [`prepare`] builds from `body` and how many times it read a `<textPath>`'s path.
fn prepared(body: &str) -> (usize, u64, Vec<String>) {
@@ -27,3 +28,134 @@ fn uses_of_a_text_on_a_path_read_the_path_once() {
));
assert_eq!((texts, reads), (51, 1));
}
/// How many times [`prepare`] walked the document's elements to find the element a
/// `<textPath>` names.
fn id_walks(body: &str) -> u64 {
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
let xml = roxmltree::Document::parse(&svg).unwrap();
let before = ID_WALKS.get();
prepare(&svg, &xml, None, 96.0, &mut vec![]);
ID_WALKS.get() - before
}
/// The texts on paths in one file find the elements they name through one walk of the document.
#[test]
fn text_paths_find_their_elements_in_one_walk() {
let paths: String = (0..20).map(|i| format!(r#"<path id="p{i}" d="M0 {i}L150 {i}"/>"#)).collect();
let texts: String = (0..20).map(|i| format!(r##"<text id="t{i}"><textPath href="#p{i}">Path</textPath></text>"##)).collect();
assert_eq!(id_walks(&format!("<defs>{paths}</defs>{texts}")), 1);
// Texts shown only through `<use>` elements share the walk, and a missing id needs no other.
let uses: String = (0..20).map(|i| format!(r##"<use href="#t{i}" font-size="20"/>"##)).collect();
let missing = r##"<text><textPath xlink:href="#none" xmlns:xlink="http://www.w3.org/1999/xlink">Path</textPath></text>"##;
assert_eq!(id_walks(&format!("<defs>{paths}{texts}</defs>{uses}{missing}")), 1);
// A file whose texts name no element is not walked.
assert_eq!(id_walks(r#"<text>Plain</text><text><textPath path="M0 20L150 20">Inline</textPath></text>"#), 0);
assert_eq!(id_walks(r#"<path id="p" d="M0 20L150 20"/><text><textPath href="p">No hash</textPath></text>"#), 0);
}
/// The document and warnings [`crate::import`] gives for `body`, with each `<textPath>`'s
/// element found through the map of ids or, with `linear`, by walking the document for each one.
fn imported(body: &str, linear: bool) -> (Document, Vec<String>) {
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">{body}</svg>"#);
LINEAR_IDS.set(linear);
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
LINEAR_IDS.set(false);
out.unwrap_or_else(|e| panic!("{e}"))
}
/// The text objects of `d`, in paint order.
fn text_objects(d: &Document) -> Vec<TextObject> {
let mut v = vec![];
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
v.push((**t).clone());
}
});
v
}
/// The map of ids finds the element the document walk finds: the first element in document order
/// with the id, whatever it is.
#[test]
fn text_paths_find_the_element_a_document_walk_finds() {
let cases = [
// Several paths, one of them named twice, and shapes.
r##"<defs><path id="a" d="M0 20L150 20"/><path id="b" d="M0 50C50 0 100 100 150 50" pathLength="10"/><path id="a" d="M0 80L150 80"/>
<circle id="c" cx="200" cy="200" r="80"/><rect id="r" x="10" y="10" width="200" height="100" rx="5"/></defs>
<text font-size="12"><textPath href="#a">First</textPath></text>
<text font-size="12"><textPath xlink:href=" #b " startOffset="5">Second</textPath></text>
<text font-size="12"><textPath href="#c" side="right">Circle</textPath></text>
<text font-size="12"><textPath href="#r" startOffset="50%">Rect</textPath></text>"##,
// A missing id, an empty one, and one without a `#`.
r##"<path id="p" d="M0 20L150 20"/><text><textPath href="#none">Missing</textPath></text>
<text><textPath href="#">Empty</textPath></text><text><textPath href="p">Bare</textPath></text>"##,
// The first element with the id has no path; the later path is not used.
r##"<g id="p"><path d="M0 20L150 20"/></g><path id="p" d="M0 80L150 80"/><text><textPath href="#p">Group</textPath></text>"##,
// Ids on texts and groups, one of them named twice.
r##"<g id="g"><text id="t"><textPath href="#t">Self</textPath></text></g><text id="g">Later</text><text><textPath href="#g">Group</textPath></text>"##,
// Uses of texts on paths, and an inline path beside an href.
r##"<defs><path id="p" d="M0 20L150 20"/><text id="t"><textPath href="#p">Used</textPath></text></defs>
<use href="#t" font-size="30"/><use href="#t" y="40"/><text><textPath href="#p" path="M0 90L150 90">Inline</textPath></text>"##,
];
for body in cases {
let map = imported(body, false);
assert_eq!(map, imported(body, true), "{body}");
assert!(!text_objects(&map.0).is_empty(), "{body}");
}
}
/// With two elements of one id, a `<textPath>` follows the first.
#[test]
fn a_text_path_follows_the_first_element_with_its_id() {
let text = r##"<text font-size="12"><textPath href="#p">Path</textPath></text>"##;
let first = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
let only = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="q" d="M0 80L150 80"/>{text}"#), false).0);
let second = text_objects(&imported(&format!(r#"<path id="q" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
assert!(matches!(first[0].kind, TextKind::OnPath { .. }), "{:?}", first[0].kind);
assert_eq!(first, only);
assert_ne!(first, second);
// A first element with no path leaves the text without one.
let (doc, warnings) = imported(&format!(r#"<g id="p"/><path id="p" d="M0 80L150 80"/>{text}"#), false);
assert!(!matches!(text_objects(&doc)[0].kind, TextKind::OnPath { .. }), "{warnings:?}");
}
/// Times importing a file with 20,000 paths and 2,000 texts on paths, finding each `<textPath>`'s
/// element through the map of ids and by walking the document for each one, after checking that
/// the two give the same document. Run it with
/// `cargo test --release -p vectorcraft-svg --lib text_path_lookup_timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand in a release build"]
fn text_path_lookup_timing() {
let mut body = String::new();
for i in 0..20_000 {
let _ = write!(body, r#"<path id="p{i}" d="M0 {}L300 {}"/>"#, i % 400, i % 400);
if i % 10 == 9 {
let k = (i * 7919) % 20_000;
let _ = write!(body, r##"<text font-size="8"><textPath href="#p{k}">L{i}</textPath></text>"##);
}
}
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
let run = |linear: bool| {
LINEAR_IDS.set(linear);
let start = std::time::Instant::now();
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
let took = start.elapsed();
LINEAR_IDS.set(false);
(out.unwrap_or_else(|e| panic!("{e}")), took)
};
let (map, _) = run(false);
let (walk, _) = run(true);
assert_eq!(map, walk);
assert_eq!(text_objects(&map.0).len(), 2_000);
let (mut maps, mut walks) = (vec![], vec![]);
for _ in 0..7 {
walks.push(run(true).1);
maps.push(run(false).1);
}
println!("walk per textPath: {walks:?}");
println!("map of ids: {maps:?}");
walks.sort();
maps.sort();
println!("median: walk {:?}, map {:?}", walks[3], maps[3]);
}
+63 -1
View File
@@ -3,7 +3,7 @@
use vectorcraft_doc::{Document, Node, NodeKind, Unit};
use vectorcraft_geom::Rect;
use vectorcraft_svg::import;
use vectorcraft_svg::{ExportOptions, export, import};
fn art(d: &Document) -> Vec<&Node> {
let mut v = Vec::new();
@@ -130,3 +130,65 @@ fn absolute_lengths_in_a_pixel_document_keep_their_size() {
assert!(close_rect(n.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 720.0 / 25.4)), "{:?}", n.geometric_bounds());
assert!(close(n.appearance.stroke_width(), 2.0));
}
#[test]
fn export_physical_units_writes_unit_suffixes() {
// Millimeters (#864 / G11: avoid 75% scale in external tools like LightBurn, LaserGRBL, Inkscape)
let mut d = Document::new(50.0 * 72.0 / 25.4, 30.0 * 72.0 / 25.4);
d.units = Unit::Millimeters;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"50mm\" height=\"30mm\""), "{s}");
assert!(s.contains("viewBox=\"0 0 141.732 85.039\""), "{s}");
// Inches
let mut d = Document::new(8.5 * 72.0, 11.0 * 72.0);
d.units = Unit::Inches;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"8.5in\" height=\"11in\""), "{s}");
assert!(s.contains("viewBox=\"0 0 612 792\""), "{s}");
// Centimeters
let mut d = Document::new(5.0 * 72.0 / 2.54, 3.0 * 72.0 / 2.54);
d.units = Unit::Centimeters;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"5cm\" height=\"3cm\""), "{s}");
// Picas
let mut d = Document::new(10.0 * 12.0, 20.0 * 12.0);
d.units = Unit::Picas;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"10pc\" height=\"20pc\""), "{s}");
// Points and pixels remain unitless
let mut d = Document::new(100.0, 200.0);
d.units = Unit::Points;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"100\" height=\"200\""), "{s}");
d.units = Unit::Pixels;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"100\" height=\"200\""), "{s}");
// Responsive export omits width and height even with physical units
d.units = Unit::Millimeters;
let s = export(&d, &ExportOptions { responsive: true, ..Default::default() });
assert!(!s.contains("width="), "{s}");
assert!(!s.contains("height="), "{s}");
// Non-zero small dimensions do not round to zero
let mut d = Document::new(0.001 * 72.0 / 25.4, 0.002 * 72.0 / 25.4);
d.units = Unit::Millimeters;
let s = export(&d, &ExportOptions::default());
assert!(s.contains("width=\"0.001mm\" height=\"0.002mm\""), "{s}");
// Extreme small dimension below 8 decimal places preserves non-zero width and viewBox
let mut d = Document::new(1e-9 * 72.0 / 25.4, 1e-9 * 72.0 / 25.4);
d.units = Unit::Millimeters;
let s = export(&d, &ExportOptions::default());
assert!(!s.contains("width=\"0mm\""), "{s}");
assert!(!s.contains("viewBox=\"0 0 0 0\""), "{s}");
// Re-importing preserved physical units
let back = import(&s).unwrap();
assert_eq!(back.units, Unit::Millimeters);
}
+22 -2
View File
@@ -1355,15 +1355,35 @@ fn palette_window_state(modal: bool, popup: bool, active: bool) -> (egui::Window
(level, true)
}
/// How long none of the app's windows has focus before the app counts as inactive. Focus moving
/// between the app's own windows passes through a frame where none has it (a press on a palette's
/// bar takes it from the main window): lowering the palettes then let the window system give the
/// keyboard to another palette in the middle of the press. craft-ui's docking waits as long.
#[cfg(not(target_arch = "wasm32"))]
const AWAY_DELAY: f64 = 0.25;
/// Sends the palette windows of `layout` the level and visibility [`palette_window_state`] gives
/// when they change. craft-ui varies a palette's level through the viewport builder, which egui
/// applies when the window opens and not to one already on screen, so the commands go explicitly to
/// the windows there are. A window that opens while the others are hidden (a panel floated under a
/// dialog, a menu, a flyout or the drawer) opens shown at its palette level, so it gets the commands
/// in its first frame.
/// in its first frame. The app is active until none of its windows has had focus for
/// [`AWAY_DELAY`], counted from the first frame that saw none.
#[cfg(not(target_arch = "wasm32"))]
fn palette_window_levels(ctx: &egui::Context, layout: &Layout<String>, modal: bool, popup: bool) {
let active = ctx.input(|i| i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true)));
let (focused, now) = ctx.input(|i| (i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true)), i.time));
let away_key = area_id().with("palette-levels-away");
let active = if focused {
ctx.data_mut(|d| d.remove::<f64>(away_key));
true
} else {
let since = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(away_key, || now));
let left = AWAY_DELAY - (now - since);
if left > 0.0 {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(left));
}
left > 0.0
};
let key = area_id().with("palette-levels-state");
let state = (modal, popup, active);
let windows: Vec<u64> = layout.floating.iter().map(|window| window.id).collect();
@@ -735,6 +735,40 @@ fn a_palette_window_keeps_out_of_the_way_of_the_main_windows_dialog_and_menus()
assert_ne!(inactive.0, WindowLevel::AlwaysOnTop, "and not above other applications' windows: {:?}", inactive.0);
}
/// Focus moving between the app's own windows passes through a frame where none has it: the
/// palettes keep their level then, or the window system hands the keyboard to another palette in
/// the middle of a press on a palette's bar. They leave the top level once the app has had no
/// focus for a while.
#[test]
fn focus_moving_between_the_apps_windows_leaves_the_palettes_on_top() {
let mut h = Harness::new();
let viewport = h.float("navigator");
h.host.borrow_mut().focus = ViewportId::ROOT;
h.frames(2);
take_palette_commands(&h, viewport);
let nowhere = ViewportId::from_hash_of("no window of the app");
h.host.borrow_mut().focus = nowhere;
h.frames(1);
h.host.borrow_mut().focus = viewport;
h.frames(2);
assert_eq!(take_palette_commands(&h, viewport), (vec![], vec![]), "a frame without focus leaves the palette's level");
// The wait starts again each time focus leaves: a second frame without focus, longer after
// the first than the wait, leaves the level too.
h.frames(6);
h.host.borrow_mut().focus = nowhere;
h.frames(1);
h.host.borrow_mut().focus = ViewportId::ROOT;
h.frames(2);
assert_eq!(take_palette_commands(&h, viewport), (vec![], vec![]), "the wait is counted from when focus last left");
h.host.borrow_mut().focus = nowhere;
h.frames(8);
let (_, levels) = take_palette_commands(&h, viewport);
assert_eq!(levels.last(), Some(&palette_window_state(false, false, false).0), "the app left: the palette leaves the top level");
h.host.borrow_mut().focus = ViewportId::ROOT;
h.frames(2);
assert_eq!(take_palette_commands(&h, viewport).1, [egui::WindowLevel::AlwaysOnTop], "and takes it again when the app is back");
}
/// With a menu of the in-window menu bar open, the palettes take the normal level (still shown):
/// the menu is drawn in the main window, or it would open under them.
#[test]
+111
View File
@@ -177,6 +177,19 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) {
}
out.actions.push(("guide.select".into(), json!({"indexes": [i], "toggle": m.shift || m.command})));
}
if resp.secondary_clicked() {
crate::panels::set_row_keys(ui.ctx(), ROW_KEYS, true);
if editable && !selected {
if !view.rows.is_empty() {
out.actions.push(("layer.highlight".into(), json!({"ids": [], "mode": "set"})));
out.rows_after_click = Some(vec![]);
}
out.actions.push(("guide.select".into(), json!({"indexes": [i]})));
}
}
resp.context_menu(|ui| {
guide_context_menu(ui, view, item, i, out);
});
// Dragged: the selected guides when this is one of them, else this one, to another layer's row.
// Only the primary button drags a guide row, and not while a drag down a column passes it.
if editable && resp.drag_started_by(egui::PointerButton::Primary) && view.column.is_none() {
@@ -194,6 +207,46 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) {
}
}
/// The right-click context menu of ruler guide row `i` (`item`).
fn guide_context_menu(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) {
let Some(g) = view.ruler_guides.get(i) else { return };
let selected = view.guides.contains(&i);
let editable = view.doc.guide_editable(g);
let guides: Vec<usize> = if selected { view.guides.clone() } else { vec![i] };
let node = g.id.and_then(|id| view.doc.node(id));
let guide_nodes: Vec<u64> = if selected {
guides.iter().filter_map(|&idx| view.ruler_guides.get(idx)?.id.map(|id| id.0)).collect()
} else {
node.map(|n| vec![n.id.0]).unwrap_or_default()
};
let visible = node.is_none_or(|n| n.visible);
if widgets::menu_item(ui, if visible { "Hide" } else { "Show" }, !guide_nodes.is_empty(), false) {
out.actions.push(("layer.setProps".into(), json!({ "ids": guide_nodes, "visible": !visible })));
ui.close();
}
let locked = node.is_some_and(|n| n.locked);
if widgets::menu_item(ui, if locked { "Unlock" } else { "Lock" }, !guide_nodes.is_empty(), false) {
out.actions.push(("layer.setProps".into(), json!({ "ids": guide_nodes, "locked": !locked })));
ui.close();
}
ui.separator();
if widgets::menu_item(ui, "Release Guides", editable, false) {
let params = if guides.len() > 1 { json!({}) } else { json!({ "index": i }) };
out.actions.push(("view.guides.release".into(), params));
ui.close();
}
if widgets::menu_item(ui, "Delete", editable, false) {
out.actions.push(("guide.remove".into(), json!({ "indexes": guides })));
ui.close();
}
ui.separator();
let layers_only = view.opts.layers_only;
if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) {
out.actions.push(("layer.locate".into(), json!({ "id": item.node.id.0, "layersOnly": layers_only })));
ui.close();
}
}
/// The row of the spine of blend `item` (#4820): a path mark and `<Path>`, the selection square
/// while the blend is selected. A click selects the blend, whose spine Direct Selection then edits
/// on the canvas; Shift or Cmd adds it to (or takes it from) the selection. The spine of a hidden
@@ -233,6 +286,64 @@ fn spine_row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
let action = if m.shift || m.command { "select.toggle" } else { "select.set" };
out.actions.push((action.into(), json!({"ids": [blend.0]})));
}
if resp.secondary_clicked() {
crate::panels::set_row_keys(ui.ctx(), ROW_KEYS, true);
if editable && !selected {
out.actions.push(("select.set".into(), json!({"ids": [blend.0]})));
}
}
resp.context_menu(|ui| {
spine_context_menu(ui, view, item, out);
});
}
/// The right-click context menu of blend spine row `item`.
fn spine_context_menu(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
let blend = item.node.id;
let selected = view.sel.contains(&blend);
let editable = (view.doc.editable())(blend);
let has_spine = !matches!(&item.node.kind, NodeKind::Blend { spec, .. } if spec.no_spine);
let ensure_selected = |out: &mut Out| {
if !selected {
out.actions.push(("select.set".into(), json!({ "ids": [blend.0] })));
}
};
if widgets::menu_item(ui, "Select", editable, false) {
out.actions.push(("select.set".into(), json!({ "ids": [blend.0] })));
ui.close();
}
if widgets::menu_item(ui, "Blend Options…", editable, false) {
ensure_selected(out);
out.actions.push(("ui.blendOptions".into(), json!({})));
ui.close();
}
ui.separator();
if widgets::menu_item(ui, "Reverse Spine", editable && has_spine, false) {
ensure_selected(out);
out.actions.push(("object.blend.reverseSpine".into(), json!({})));
ui.close();
}
if widgets::menu_item(ui, "Reverse Front to Back", editable, false) {
ensure_selected(out);
out.actions.push(("object.blend.reverseFrontToBack".into(), json!({})));
ui.close();
}
if widgets::menu_item(ui, "Expand", editable, false) {
ensure_selected(out);
out.actions.push(("object.blend.expand".into(), json!({})));
ui.close();
}
if widgets::menu_item(ui, "Release", editable, false) {
ensure_selected(out);
out.actions.push(("object.blend.release".into(), json!({})));
ui.close();
}
ui.separator();
let layers_only = view.opts.layers_only;
if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) {
out.actions.push(("layer.locate".into(), json!({ "id": blend.0, "layersOnly": layers_only })));
ui.close();
}
}
/// Guide rows `guides` dragged over row `r` (`resp`) of layer `layer`: the row lights up, and the
+203
View File
@@ -3006,3 +3006,206 @@ fn context_menu_others_actions_sublayer_state_enables_all_commands() {
assert_eq!(lock_cmd, "layer.unlockAll");
assert!(lock_enabled, "locked sublayer enables Unlock All Layers");
}
/// One headless frame of the panel in a 300 × 600 window, returning every drawn text and its rect.
fn frame_texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(300.0, 600.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
out.textures_delta.clear();
let mut texts = vec![];
for s in out.shapes {
if let egui::epaint::Shape::Text(t) = s.shape {
texts.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2())));
}
}
texts
}
/// Click `button` at `pos` (pressed in one frame, released in the next) and return the texts drawn
/// on the frame after release.
fn click_menu_at(app: &mut VectorcraftApp, ctx: &egui::Context, pos: egui::Pos2, button: egui::PointerButton) -> Vec<(String, egui::Rect)> {
let ev = |pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() };
frame_texts(app, ctx, vec![egui::Event::PointerMoved(pos), ev(true)]);
frame_texts(app, ctx, vec![ev(false)]);
frame_texts(app, ctx, vec![])
}
/// The menu item labels in `texts` (which start with `" "`), ordered from top to bottom.
fn menu_entries(texts: &[(String, egui::Rect)]) -> Vec<String> {
let mut entries: Vec<_> = texts.iter().filter(|(t, _)| t.starts_with(" ")).map(|(t, r)| (t.trim().to_string(), r.top())).collect();
entries.sort_by(|a, b| a.1.total_cmp(&b.1));
entries.into_iter().map(|(t, _)| t).collect()
}
fn text_rect(texts: &[(String, egui::Rect)], name: &str) -> egui::Rect {
texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} not in {texts:?}"))
}
/// Right-clicking a ruler guide row selects the guide (or keeps a multi-guide selection), opens its
/// context menu (Hide/Show, Lock/Unlock, Release Guides, Delete, Locate Object), and each item
/// dispatches its command with Undo/Redo registration (#8592).
#[test]
fn guide_row_context_menu_selects_and_runs_guide_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
run(&mut app, "guide.add", json!({"vertical": false, "pos": 80}));
run(&mut app, "select.none", json!({}));
let layer = app.session.active().unwrap().doc.layers[0].id;
run(&mut app, "layer.highlight", json!({"ids": [layer.0], "mode": "set"}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let texts = frame_texts(&mut app, &ctx, vec![]);
let h_guide_pos = text_rect(&texts, "<Horizontal Guide>").center();
let v_guide_pos = text_rect(&texts, "<Vertical Guide>").center();
let selected_guides = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides)
};
// Right-clicking an unselected guide row selects it, clears highlighted rows, and opens the menu.
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
assert_eq!(selected_guides(&app), [0], "right-click selects the guide");
assert!(rows_of(&app).is_empty(), "highlighted rows cleared when selecting a guide");
assert_eq!(menu_entries(&menu), ["Hide", "Lock", "Release Guides", "Delete", "Locate Object"]);
// Hide toggles the guide's visibility off in one undo step; right-clicking again shows "Show".
let guide_node = app.session.active().unwrap().doc.ruler_guides()[0].id.unwrap();
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Hide").center(), egui::PointerButton::Primary);
assert!(!app.session.active().unwrap().doc.node(guide_node).unwrap().visible);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
assert_eq!(menu_entries(&menu), ["Show", "Lock", "Release Guides", "Delete", "Locate Object"]);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Show").center(), egui::PointerButton::Primary);
assert!(app.session.active().unwrap().doc.node(guide_node).unwrap().visible);
// Lock toggles the guide's lock on in one undo step; right-clicking again shows "Unlock".
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Lock").center(), egui::PointerButton::Primary);
assert!(app.session.active().unwrap().doc.node(guide_node).unwrap().locked);
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
assert_eq!(menu_entries(&menu), ["Hide", "Unlock", "Release Guides", "Delete", "Locate Object"]);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Unlock").center(), egui::PointerButton::Primary);
assert!(!app.session.active().unwrap().doc.node(guide_node).unwrap().locked);
// Locate Object locates the guide's holding layer.
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Locate Object").center(), egui::PointerButton::Primary);
assert_eq!(rows_of(&app), vec![layer]);
// Multi-guide selection is preserved when right-clicking an already-selected guide row.
run(&mut app, "guide.select", json!({"indexes": [0, 1]}));
let _menu = click_menu_at(&mut app, &ctx, h_guide_pos, egui::PointerButton::Secondary);
assert_eq!(selected_guides(&app), [0, 1], "right-click on selected guide preserves multi-guide selection");
// Release Guides on a single guide converts it into a path in one undo step; Undo brings it back.
run(&mut app, "guide.select", json!({"indexes": [0]}));
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Release Guides").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "one guide released to a path");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
run(&mut app, "edit.undo", json!({}));
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 2, "Undo restores the released guide");
// Delete removes the guide in one undo step; Undo restores it.
let texts = frame_texts(&mut app, &ctx, vec![]);
let v_guide_pos = text_rect(&texts, "<Vertical Guide>").center();
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Delete").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "Delete removes the guide");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
run(&mut app, "edit.undo", json!({}));
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 2, "Undo restores the deleted guide");
}
/// Right-clicking a blend spine row selects the blend, opens its context menu (Select, Blend
/// Options…, Reverse Spine, Reverse Front to Back, Expand, Release, Locate Object), and each item
/// dispatches its command with Undo/Redo registration (#8592).
#[test]
fn spine_row_context_menu_selects_blend_and_runs_blend_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 300, "height": 200}));
let a = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
let b = NodeId(run(&mut app, "shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut app, "select.set", json!({"ids": [a.0, b.0]}));
let blend = NodeId(run(&mut app, "object.blend.make", json!({}))["id"].as_u64().unwrap());
run(&mut app, "select.none", json!({}));
expand(&mut app, &json!({})).unwrap();
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
let spine_rect = |texts: &[(String, egui::Rect)]| {
texts
.iter()
.filter(|(t, _)| t == "<Path>")
.max_by(|x, y| x.1.top().total_cmp(&y.1.top()))
.map(|(_, r)| *r)
.unwrap_or_else(|| panic!("spine <Path> not in {texts:?}"))
};
let texts = frame_texts(&mut app, &ctx, vec![]);
let spine_pos = spine_rect(&texts).center();
let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.to_vec();
// Right-clicking the unselected spine row selects the blend and opens the context menu.
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
assert_eq!(selected(&app), [blend], "right-clicking the spine row selects the blend");
assert_eq!(menu_entries(&menu), ["Select", "Blend Options…", "Reverse Spine", "Reverse Front to Back", "Expand", "Release", "Locate Object"]);
// Blend Options… opens the Blend Options dialog.
click_menu_at(&mut app, &ctx, text_rect(&menu, " Blend Options…").center(), egui::PointerButton::Primary);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("blendOptions"));
crate::dialogs::cancel(&mut app);
// Reverse Spine reverses the key positions along the spine in one undo step.
let key_x = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0;
let a_x_before = key_x(&app, a);
let b_x_before = key_x(&app, b);
let undo_before = app.session.active().unwrap().history.undo.len();
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Reverse Spine").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
assert!((key_x(&app, a) - b_x_before).abs() < 1e-6 && (key_x(&app, b) - a_x_before).abs() < 1e-6);
// Reverse Front to Back reverses the key stacking order in one undo step.
let key_ids = |app: &VectorcraftApp| -> Vec<NodeId> {
app.session.active().unwrap().doc.node(blend).unwrap().children().unwrap().iter().map(|c| c.id).collect()
};
assert_eq!(key_ids(&app), [a, b]);
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Reverse Front to Back").center(), egui::PointerButton::Primary);
assert_eq!(key_ids(&app), [b, a]);
// Locate Object highlights the blend row.
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
click_menu_at(&mut app, &ctx, text_rect(&menu, " Locate Object").center(), egui::PointerButton::Primary);
assert_eq!(rows_of(&app), vec![blend]);
// Expand replaces the blend with a group in one undo step; Undo brings the blend back.
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Expand").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Group { .. }));
run(&mut app, "edit.undo", json!({}));
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Blend { .. }));
// Release releases the blend into its keys and spine path in one undo step; Undo restores it.
expand(&mut app, &json!({})).unwrap();
let texts = frame_texts(&mut app, &ctx, vec![]);
let spine_pos = spine_rect(&texts).center();
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
let undo_before = app.session.active().unwrap().history.undo.len();
click_menu_at(&mut app, &ctx, text_rect(&menu, " Release").center(), egui::PointerButton::Primary);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
assert!(app.session.active().unwrap().doc.node(blend).is_none(), "blend released into keys and spine path");
run(&mut app, "edit.undo", json!({}));
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Blend { .. }));
}
+16 -1
View File
@@ -3781,7 +3781,22 @@ mod tests {
let (csv_off, csv_on) = (String::from_utf8_lossy(csv_off), String::from_utf8_lossy(csv_on));
assert!(!csv_off.contains(&hold), "off, the CSV file lists no hold");
assert!(csv_on.contains(&swap[0].shortcut), "on, the CSV file lists it: {}", swap[0].shortcut);
assert_eq!(sheet_off, sheet_off_again, "the sheet is the same each time");
// The writer stamps each file with the clock: its dates and its ID (fixed width), which differ
// between two exports a second apart. The rest of the file is the same each time.
let unstamped = |pdf: &[u8]| {
let mut b: Vec<u8> = pdf.iter().map(|&c| if c.is_ascii_digit() { b'0' } else { c }).collect();
for key in [&b"InstanceID>"[..], b"DocumentID>", b"/ID["] {
let mut at = 0;
while let Some(i) = b[at..].windows(key.len()).position(|w| w == key) {
let start = at + i + key.len();
let end = b[start..].iter().position(|&c| c == b'<' || c == b']').map_or(b.len(), |e| start + e);
b[start..end].fill(b'?');
at = end;
}
}
b
};
assert_eq!(unstamped(sheet_off), unstamped(sheet_off_again), "the sheet is the same each time");
assert_ne!(sheet_off, sheet_on, "on, the sheet lists the hold");
}
File diff suppressed because one or more lines are too long
+9 -5
View File
File diff suppressed because one or more lines are too long
+4 -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
+5 -3
View File
File diff suppressed because one or more lines are too long