Merge main into feat/script-grants-list

This commit is contained in:
dotCooCoo committed 2026-11-22 16:23:51 -08:00
commit 10383f53f3
139 files changed
+5398 -1686

No files matched your search

Generated
+7 -3
View File
@@ -1251,7 +1251,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
source = "git+https://github.com/storytold/craft-libs?rev=c56fbd8271a42ffcc82b07c8f31d714e345fdcd9#c56fbd8271a42ffcc82b07c8f31d714e345fdcd9"
dependencies = [
"encoding_rs",
"image",
@@ -1342,7 +1342,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
dependencies = [
"fax",
"hayro-ccitt",
@@ -2634,7 +2634,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -6901,6 +6901,7 @@ dependencies = [
"cfb",
"chrono",
"craft-cdr",
"craft-codepage",
"craft-docpath",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
"craft-jxl",
@@ -7060,6 +7061,7 @@ dependencies = [
name = "vectorcraft-metafile"
version = "0.24.1"
dependencies = [
"craft-codepage",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
"craft-metafile",
"image",
@@ -7200,6 +7202,7 @@ dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)",
"craft-mime",
"craft-svg",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"data-url",
"flate2",
"image",
@@ -7251,6 +7254,7 @@ dependencies = [
"icu_segmenter",
"kurbo 0.13.1",
"log",
"serde_json",
"skrifa 0.47.0",
"subsetter",
"unicode-bidi",
+4 -3
View File
@@ -38,16 +38,17 @@ craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7b
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "c56fbd8271a42ffcc82b07c8f31d714e345fdcd9" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -192,7 +193,7 @@ codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
+3
View File
@@ -225,3 +225,6 @@ sync_github_name = true
real_name = "Hassan Nawaz Khan"
display_name = "Hassan Nawaz Khan"
sync_github_name = false
[people.Terra854]
display_name = "Terra854"
+8 -5
View File
@@ -880,7 +880,7 @@ fn image_and_fill_doc(fill: Paint) -> Document {
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))),
]
});
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
d
}
@@ -974,7 +974,10 @@ fn images_can_be_left_out_with_their_files() {
assert_eq!(out.setting_notes, [IMAGES_OFF]);
// An image that can't be decoded is not read when images are left out.
let mut broken = d.clone();
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
broken.images.insert(
"raster-1".into(),
ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None, file_font: Default::default() },
);
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
@@ -1379,7 +1382,7 @@ fn images_link_png_or_jpeg_files() {
};
vec![Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
});
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
let out = export(&d, &opts(&d)).unwrap();
let e = entities(&out);
assert_eq!(kind(&e[0]), "IMAGE");
@@ -1422,7 +1425,7 @@ fn images_without_pixels_are_left_out_with_one_note() {
})
.collect()
});
d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None });
d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None, file_font: Default::default() });
let out = export(&d, &opts(&d)).unwrap();
assert!(entities(&out).is_empty() && out.images.is_empty());
assert_eq!(out.warnings, ["an image has no pixels and was left out"]);
@@ -1583,7 +1586,7 @@ fn drawings_doc() -> Document {
});
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
d
}
+7 -1
View File
@@ -551,13 +551,19 @@ impl Document {
}
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]).
/// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). A
/// node that is or holds a dimension (a pasted one) sets [`Document::dimensions`].
pub fn insert(&mut self, parent: Option<NodeId>, index: usize, node: Node) -> Result<NodeId, DocError> {
fn holds_dimension(n: &Node) -> bool {
n.extras().dimension.is_some() || n.children().into_iter().flatten().any(|c| holds_dimension(c))
}
let id = node.id;
self.check_ruler_guide_place(&node, parent)?;
let dimension = !self.dimensions && holds_dimension(&node);
let ch = self.children_mut(parent)?;
let i = Node::insert_index(ch, index, &node);
ch.insert(i, Arc::new(node));
self.dimensions |= dimension;
Ok(id)
}
+231 -16
View File
@@ -115,6 +115,36 @@ pub fn set_image_paint(f: ImagePaint) {
let _ = IMAGE_PAINT.set(f);
}
/// Adds the geometry and raster effects of a symbol instance's active fill and stroke to the fills
/// and strokes that paint in the art it is given, the instance's art in the symbol's coordinates,
/// as the canvas adds them to the art it draws. Every object keeps its place in the art, so the
/// child indices of [`symbol_part_at`] still lead to it. Effects are evaluated above this crate, so
/// the engine registers one with [`set_instance_row_art`].
pub type InstanceRowArt = fn(Option<&Document>, &Node, &mut Node);
static INSTANCE_ROW_ART: OnceLock<InstanceRowArt> = OnceLock::new();
/// Register how a symbol instance's art takes the effects of the instance's fill and stroke, for
/// Direct Selection's parts (the first registration stays).
pub fn set_instance_row_art(f: InstanceRowArt) {
// Already set: the same engine, registered by another session.
let _ = INSTANCE_ROW_ART.set(f);
}
/// Does a symbol instance's active fill or stroke carry a visible geometry effect, which the art it
/// places takes on each of its fills and strokes ([`set_instance_row_art`])? Effects are classified
/// above this crate, so the engine registers one with [`set_instance_reshapes`].
pub type InstanceReshapes = fn(&Node) -> bool;
static INSTANCE_RESHAPES: OnceLock<InstanceReshapes> = OnceLock::new();
/// Register how Direct Selection tells whether a symbol instance's fill or stroke effects reshape
/// its art (the first registration stays).
pub fn set_instance_reshapes(f: InstanceReshapes) {
// Already set: the same engine, registered by another session.
let _ = INSTANCE_RESHAPES.set(f);
}
/// The shapes that [`ImagePaint`] gives for one object.
type Painted = Vec<(BezPath, FillRule, AppearanceItem)>;
@@ -1575,12 +1605,67 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
/// stroke along its shape, a fill inside it except with Selection by Path Only.
fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
painted_hit(&image_paint(Some(symbols.document()), n), p, opt)
}
/// What a click at `p` hits among `painted`, the shapes [`image_paint`] gives, as [`hit_painted`]
/// tests them.
fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option<HitKind> {
painted.iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
}
/// Is `n` a symbol instance whose active fill or stroke has a visible geometry effect, which
/// reshapes the art it draws ([`set_instance_reshapes`])? This holds whatever that art is, clip
/// groups and type included. Callers ask [`own_effects_art`] first, which takes an instance whose
/// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow)
/// is tested here. Never with `outline`, where the canvas draws no effects, nor while a
/// [`DrawnOff`] guard lives, nor while nothing is registered.
fn reshapes_instance_art(n: &Node, outline: bool) -> bool {
!outline
&& !DRAWN_OFF.get()
&& matches!(n.kind, NodeKind::SymbolInstance { .. })
&& n.appearance.items.iter().any(|i| !i.effects().is_empty())
&& INSTANCE_RESHAPES.get().is_some_and(|f| f(n))
}
/// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what
/// testing or outlining it takes from the [`ArtWalk`] limit.
fn walk_size(n: &Node) -> u64 {
u64::try_from(n.count_with_masks()).unwrap_or(u64::MAX)
}
/// The art that symbol instance `n` draws with a visible effect of its own, the effects of its
/// fills and strokes and those of its symbol's art all applied, or that type `n` draws with the
/// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]).
/// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or
/// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect
/// changes what it draws. Evaluating the art is work that walking it does not count, so the art
/// takes its objects from the [`ArtWalk`] limit of the click or outline under way, and the walk of
/// it takes them again. Once the limit is used up, the result is `Some` of an empty group, which
/// hits and outlines nothing, and no more art is evaluated.
fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option<Node> {
let has = match n.kind {
NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible),
NodeKind::Text(_) => has_own_effects(n),
_ => false,
};
if outline || DRAWN_OFF.get() || !has || DRAWN_ART.get().is_none() {
return None;
}
let nothing = || Some(Node::group(n.id, vec![]));
if ArtWalk::used_up() {
return nothing();
}
let art = DRAWN_ART.get()?(symbols, n)?;
if !ArtWalk::take(walk_size(&art)) {
return nothing();
}
Some(art)
}
/// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path
/// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and
/// type on a path's path, drawn through `n`'s perspective projection if it has one.
@@ -1690,6 +1775,41 @@ impl<'a> InstanceArt<'a> {
Some(Self { art, map, xf: *xf, boxes })
}
/// [`Self::of`] with the effects of the instance's active fill and stroke added to the fills and
/// strokes in the art ([`set_instance_row_art`]), so that each object of it is tested and
/// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects.
fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option<Self> {
let mut art = Self::of(doc, inst)?;
#[cfg(test)]
ARTS_WALKED.with(|c| c.set(c.get() + 1));
if !outline && let Some(f) = INSTANCE_ROW_ART.get() {
f(Some(doc), inst, &mut art.art);
}
Some(art)
}
/// [`Self::drawn`] for symbol instance `inst` in the art of another instance, outside Outline.
/// Copying the art and adding the effects to it is work that walking it does not count, so the
/// art takes as many objects as placing it makes ([`Self::size`]) from the [`ArtWalk`] limit of
/// the click or outline under way before it is copied, as the marquee takes the art it places,
/// and the walk of it takes its objects again. `None` once fewer are left.
fn nested(doc: &'a Document, inst: &Node) -> Option<Self> {
if ArtWalk::used_up() {
return None;
}
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let boxes = doc.symbol_boxes().quick();
let source = boxes.symbol_art(symbol)?;
let size = match boxes.slice_map(symbol, *xf) {
Some(m) => m.most_placed_with(source, &boxes),
None => walk_size(source),
};
if !ArtWalk::take(size) {
return None;
}
Self::drawn(doc, inst, false)
}
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
@@ -1751,15 +1871,18 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
/// no editable object of its art is under `p`.
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. Elsewhere each
/// object is tested where the geometry effects of the instance's active fill and stroke draw it
/// ([`InstanceArt::drawn`]), and not where its own shape no longer paints. Live objects in the art
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
/// symbol instance or no editable object of its art is under `p`.
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
let _walk = ArtWalk::open();
let art = InstanceArt::of(doc, inst)?;
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
let art = InstanceArt::drawn(doc, inst, outline)?;
let symbols = doc.kept_symbol_boxes();
let mut path = vec![];
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
find.find(&art.art, &mut path, None, outline).map(|_| path)
}
@@ -1772,14 +1895,35 @@ struct FindPart<'a> {
/// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws
/// them, and clipping paths are not picked by their outline.
whole_instance: bool,
/// For [`symbol_part_at`] and [`drawn_instance_hit`]: the art carries the effects of the
/// instance's active fill and stroke ([`InstanceArt::drawn`]).
drawn: bool,
}
impl FindPart<'_> {
/// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each
/// object it visits inside `n` from the [`ArtWalk`] limit.
/// object it visits inside `n` from the [`ArtWalk`] limit. In drawn art, a symbol instance with
/// geometry effects of its own, and type whose own effects or fill and stroke effects (its own,
/// or those the outer instance adds) reshape it, are hit only where the art they draw is
/// ([`own_effects_art`]), and an instance whose fill or stroke has geometry effects that reshape
/// its art (its own, or those the outer instance passes on) only where its art is drawn with
/// them ([`drawn_instance_hit`]); not anywhere in their bounds. With Type Object Selection by
/// Path Only ([`HitOptions::type_path_only`]), type is still picked by its type path.
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
let placed = self.art.place(n, whole)?;
let _charged = ArtWalk::charge();
// Type Object Selection by Path Only picks type by its type path, whatever its effects draw.
let type_path = opt.type_path_only && matches!(placed.kind, NodeKind::Text(_));
if self.drawn && !type_path {
if let Some(art) = own_effects_art(&placed, self.symbols, opt.outline) {
let _off = DrawnOff::set();
let _art_only = ArtOnly::set();
return hit_any(&art, self.p, opt, self.symbols);
}
if reshapes_instance_art(&placed, opt.outline) {
return drawn_instance_hit(&placed, self.p, opt, self.symbols);
}
}
hit_any(&placed, self.p, opt, self.symbols)
}
@@ -1858,7 +2002,26 @@ fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes)
ARTS_WALKED.with(|c| c.set(c.get() + 1));
let opt = HitOptions { clip_outlines: false, ..opt };
let _art_only = ArtOnly::set();
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: false }.find(&art.art, &mut vec![], None, false)
}
/// What a click at `p` hits of symbol instance `n`, an object of another instance's drawn art,
/// where the canvas draws `n`'s art with the geometry effects of `n`'s active fill and stroke
/// ([`InstanceArt::drawn`]): each object of that art where it is drawn, paths, images and type
/// alike, and not anywhere in `n`'s box. Locked and template objects of the art count, as in
/// [`instance_art_hit`]. `None` for an instance of a missing symbol, of a symbol that holds an
/// instance of itself or nests too deep ([`SymbolBoxes::art`]), of art past the 9-slice object
/// limit ([`InstanceArt::of`]), and once the click has visited as many objects of symbol art as
/// [`ArtWalk`] allows.
fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
if symbols.art(symbol).is_none() || ArtWalk::used_up() {
return None;
}
let art = InstanceArt::nested(symbols.document(), n)?;
let opt = HitOptions { clip_outlines: false, ..opt };
let _art_only = ArtOnly::set();
FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false)
}
thread_local! {
@@ -2008,15 +2171,21 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
/// the object leave no region.
/// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's
/// active fill and stroke, as [`symbol_part_at`] does. Outlining visits at most as many objects of
/// symbol art as one click does ([`ArtWalk`]), the art of the instances nested in the part included,
/// and leaves out what is past that limit.
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
let art = InstanceArt::of(doc, inst)?;
let part = crate::symbol_overrides::part(&art.art, path)?;
let _walk = ArtWalk::open();
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
let art = InstanceArt::drawn(doc, inst, outline)?;
let part = crate::symbol_overrides::part(&art.art, path)?;
let symbols = doc.kept_symbol_boxes();
let mut out = BezPath::new();
let mut limit = None;
let mut whole = None;
let mut n = &art.art;
let mut mask = false;
for &i in path {
let children = n.children()?;
whole = art.whole(n, whole);
@@ -2028,9 +2197,12 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], op
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
limit = within;
}
mask = i == 0 && n.clips();
n = children.get(usize::try_from(i).ok()?)?;
}
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
// A clipping path is picked by its own geometry ([`FindPart::find`]), and outlined so.
let placed = art.place(part, whole)?;
plain(mask, || outline_within(&placed, &symbols, limit, outline, &mut out));
Some(out)
}
@@ -2052,9 +2224,42 @@ fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Optio
}
}
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. A path
/// or compound path whose geometry effects reshape it is outlined as the art they draw
/// ([`drawn_art`]), a symbol instance with geometry effects of its own and type whose effects
/// reshape it as the art they draw ([`own_effects_art`]), and a symbol instance whose fill or
/// stroke effects reshape its art as that art drawn with them ([`InstanceArt::drawn`]), as
/// [`FindPart`] tests them, except with `outline` and while a [`DrawnOff`] guard lives. Each object
/// visited takes one object of the [`ArtWalk`] limit, and nothing more is outlined once the limit
/// is used up. A hidden object and what it holds are not outlined, as [`FindPart`] passes over them.
fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
use vectorcraft_geom::kurbo::Shape;
if !n.visible || !ArtWalk::take(1) {
return;
}
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& let Some(art) = drawn_art(symbols, n, outline)
{
let _off = DrawnOff::set();
art.iter().for_each(|a| outline_within(a, symbols, limit, outline, out));
return;
}
if let Some(art) = own_effects_art(n, symbols, outline) {
let _off = DrawnOff::set();
outline_within(&art, symbols, limit, outline, out);
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& reshapes_instance_art(n, outline)
{
if symbols.art(symbol).is_some()
&& let Some(art) = InstanceArt::nested(symbols.document(), n)
&& let Some(placed) = art.place(&art.art, None)
{
outline_within(&placed, symbols, limit, outline, out);
}
return;
}
if let Some(pd) = n.path_data() {
match limit {
Some(r) => push_cut(out, &pd.to_bezpath(), r),
@@ -2066,16 +2271,26 @@ fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPat
{
out.extend(b.to_path(0.1));
}
// An image is also outlined where its own fills and strokes paint with their effects, as
// [`hit_leaf`] picks it there ([`image_paint`]).
if !outline && matches!(n.kind, NodeKind::Image(_)) {
for (bp, ..) in image_paint(Some(symbols.document()), n).iter() {
match limit {
Some(r) => push_cut(out, bp, r),
None => out.extend(bp.iter()),
}
}
}
let Some(children) = n.children() else { return };
let outline = outline || previews_off(n);
if n.clips()
&& let Some((first, rest)) = children.split_first()
{
let Some(inner) = limit_within(first, limit, outline) else { return };
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
rest.iter().for_each(|c| outline_within(c, symbols, inner, outline, out));
return;
}
children.iter().for_each(|c| outline_within(c, limit, outline, out));
children.iter().for_each(|c| outline_within(c, symbols, limit, outline, out));
}
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
+116 -3
View File
@@ -1324,11 +1324,11 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
assert_eq!(evaluated(), before + 2);
}
/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to
/// (320, 20); nothing for anything else.
/// For instances of the symbols whose names start with "Painted", a fill that paints the square
/// from (300, 0) to (320, 20); nothing for anything else.
fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => {
NodeKind::SymbolInstance { symbol, .. } if symbol.starts_with("Painted") => {
let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath();
vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))]
}
@@ -3067,6 +3067,119 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li
assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths");
}
/// Whether a symbol instance's fill or stroke effects reshape its art, for these tests: when
/// [`painted_far_away`] gives it shapes.
fn reshapes_when_painted(n: &Node) -> bool {
!painted_far_away(None, n).is_empty()
}
/// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect:
/// [`reshapes_when_painted`] holds for it when the name starts with "Painted", so a part pick and a
/// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]).
fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc<Node> {
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
n.appearance = Appearance::default_art().into();
let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true };
n.appearance.items[0].effects_mut().push(offset);
Arc::new(n)
}
/// Five levels of symbols: "Painted 0" is a 1 pt square, and each level above holds 8 instances
/// of the level below whose fills have a geometry effect. Returns the id of an instance of
/// "Painted 4" on the layer.
fn painted_chain(d: &mut Document) -> NodeId {
let l = d.layers[0].id;
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted 0".into(), art: Arc::new(dot) });
for level in 1..5 {
let members = (0..8).map(|_| painted_instance_of(d, &format!("Painted {}", level - 1))).collect();
group_symbol(d, &format!("Painted {level}"), members);
}
let inst = instance_of(d, "Painted 4");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
id
}
/// The outline of a part of a dynamic symbol's instance visits at most the art walk's limit of
/// objects, though the part is an instance whose art, drawn with its fill's effects, nests
/// instances 3 levels deep, 8 at each level. Within the limit every square is outlined.
#[test]
fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() {
set_image_paint(painted_far_away);
set_instance_reshapes(reshapes_when_painted);
let mut d = Document::new(600.0, 400.0);
let id = painted_chain(&mut d);
let n = d.node(id).unwrap();
let squares = |o: &BezPath| o.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count();
// Part [0] is an instance of "Painted 3": 8 × 8 × 8 squares.
assert_eq!(squares(&symbol_part_outline(&d, n, &[0]).unwrap()), 512, "within the limit");
let (outline, _, arts) = with_art_limit(100, || symbol_part_outline(&d, n, &[0]).unwrap());
assert!(squares(&outline) < 100, "{} squares outlined", squares(&outline));
assert!(arts < 100, "{arts} instances' art walked");
}
/// A part pick in a dynamic symbol's instance visits at most the art walk's limit of objects of
/// nested instances whose art, drawn with their fills' effects, is walked: in a chain of nested
/// instances, and in instances whose clip groups the click misses, where only the clip group
/// itself is tested. A click on the clipped art of a nested instance is still found.
#[test]
fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() {
set_image_paint(painted_far_away);
set_instance_reshapes(reshapes_when_painted);
let mut d = Document::new(600.0, 400.0);
let id = painted_chain(&mut d);
let opt = HitOptions::default();
let (hit, _, arts) = with_art_limit(100, || symbol_part_at(&d, d.node(id).unwrap(), Point::new(150.0, 50.0), opt));
assert_eq!(hit, None);
assert!(arts <= 40, "chain: {arts} instances' art walked");
// 30 instances of a clip group whose 10 pt clipping path holds 40 squares: 42 objects each.
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default());
let mut members = vec![Arc::new(mask)];
members.extend((0..40).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))));
let mut clip = Node::group(d.alloc_id(), members);
clip.set_clips(true);
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted clip".into(), art: Arc::new(clip) });
let members = (0..30).map(|_| painted_instance_of(&mut d, "Painted clip")).collect();
group_symbol(&mut d, "Clips", members);
let inst = instance_of(&mut d, "Clips");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
let n = d.node(id).unwrap();
let (hit, _, arts) = with_art_limit(300, || symbol_part_at(&d, n, Point::new(150.0, 50.0), opt));
assert_eq!(hit, None);
assert!(arts <= 8, "clip groups: {arts} instances' art walked");
assert_eq!(with_art_limit(300, || symbol_part_at(&d, n, Point::new(2.0, 2.0), opt)).0, Some(vec![29]), "the clipped art");
}
/// The outline of a part of a dynamic symbol's instance leaves out the hidden objects in the art of
/// an instance nested in the part whose fill's effects reshape it, as a part pick passes over them.
#[test]
fn a_parts_outline_leaves_out_hidden_art_of_nested_reshaped_symbol_instances() {
use vectorcraft_geom::kurbo::Shape;
set_image_paint(painted_far_away);
set_instance_reshapes(reshapes_when_painted);
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
let shown = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
let mut hidden = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art());
hidden.visible = false;
group_symbol(&mut d, "Painted hidden", vec![Arc::new(shown), Arc::new(hidden)]);
let member = painted_instance_of(&mut d, "Painted hidden");
group_symbol(&mut d, "Hides", vec![member]);
let inst = instance_of(&mut d, "Hides");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
let n = d.node(id).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(55.0, 55.0), HitOptions::default()), None, "the hidden square is not picked");
let outline = symbol_part_outline(&d, n, &[0]).unwrap();
let squares = outline.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count();
assert_eq!(squares, 1, "only the shown square is outlined");
assert!(outline.bounding_box().x1 <= 1.0, "the outline reaches {:?}", outline.bounding_box());
}
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
/// canvas draws nothing of it. At the art's natural size the same art is picked.
+4 -4
View File
@@ -134,10 +134,10 @@ pub use text::GlyphForm;
pub use text::PATH_LEAD_MAX;
pub use text::WarichuAlign;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
VerticalAlign, WrapShape,
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FILE_FONT_MIME, FileFont, FileFontFace, FileFonts,
FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection,
ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind,
TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
};
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
pub use trace::TraceView;
+1 -1
View File
@@ -130,7 +130,7 @@ pub fn hash_reader_within(r: impl std::io::Read, max: u64) -> std::io::Result<(S
impl ImageBlob {
/// A blob of encoded image `bytes` of type `mime`, without a preview.
pub fn new(mime: impl Into<String>, bytes: Vec<u8>) -> Self {
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None }
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None, file_font: Default::default() }
}
/// This blob with a preview of at most [`PROXY_SIZE`] pixels a side (PNG), when the image is
+4 -1
View File
@@ -461,7 +461,7 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
doc.layers.clear();
doc.swatches.clear();
let mime = if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { "image/png" };
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None });
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None, file_font: Default::default() });
let xf = Affine::scale_non_uniform(frame.width() / w as f64, frame.height() / h as f64);
let im = ImageObject { key: "preview".into(), width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
let art = Node::new(art_id(), NodeKind::Group { children: vec![Arc::new(Node::new(art_id(), NodeKind::Image(Box::new(im))))], clip: false });
@@ -519,6 +519,9 @@ fn rename(n: &mut Node, prefix: &str) {
paint(&mut r.style.fill);
paint(&mut r.style.stroke);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| *key = format!("{prefix}{key}"));
}
}
NodeKind::Image(im) => {
im.key = format!("{prefix}{}", im.key);
+31 -2
View File
@@ -154,8 +154,9 @@ pub struct Symbol {
pub dynamic: bool,
}
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects, and the fonts files carried for
/// type ([`crate::FileFonts`], MIME [`crate::FILE_FONT_MIME`]), which save and travel the same way.
#[derive(Serialize, Deserialize)]
pub struct ImageBlob {
pub mime: String,
#[serde(skip)]
@@ -164,4 +165,32 @@ pub struct ImageBlob {
/// linked images show this blob, and what `bytes` hold while the linked file can't be read.
#[serde(skip)]
pub proxy: Option<Arc<Vec<u8>>>,
/// Runtime ownership of an admitted font face. Image resources (including undo and clipboard
/// copies) own it; cached text nodes carry only weak references.
#[serde(skip)]
pub file_font: std::sync::Mutex<Option<Arc<dyn crate::FileFontFace>>>,
}
impl std::fmt::Debug for ImageBlob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ImageBlob").field("mime", &self.mime).field("bytes", &self.bytes).field("proxy", &self.proxy).finish()
}
}
impl Clone for ImageBlob {
fn clone(&self) -> Self {
let mut owner = self.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if owner.as_ref().is_some_and(|face| {
self.mime != crate::FILE_FONT_MIME || (!std::ptr::eq(face.bytes(), self.bytes.as_slice()) && face.bytes() != self.bytes.as_slice())
}) {
*owner = None;
}
Self { mime: self.mime.clone(), bytes: self.bytes.clone(), proxy: self.proxy.clone(), file_font: std::sync::Mutex::new(owner.clone()) }
}
}
impl PartialEq for ImageBlob {
fn eq(&self, other: &Self) -> bool {
self.mime == other.mime && self.bytes == other.bytes && self.proxy == other.proxy
}
}
+6
View File
@@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
mod area;
mod char_style;
mod composite;
mod file_fonts;
mod kinsoku_set;
mod object;
mod para_style;
@@ -26,6 +27,7 @@ pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
};
pub use file_fonts::{FILE_FONT_MIME, FileFont, FileFontFace, FileFonts, MAX_FILE_FONTS, text_hash};
pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets;
pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet};
pub use para_style::{
@@ -131,6 +133,10 @@ pub struct TextObject {
/// file saves the count only when it is not 0.
#[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")]
pub list_count: u32,
/// The fonts the file this type came from carried for fonts that aren't available here,
/// which draw it until its text is edited ([`FileFonts`]); `None` for other type.
#[serde(default, rename = "fileFonts", skip_serializing_if = "Option::is_none")]
pub file_fonts: Option<Box<FileFonts>>,
/// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame
/// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0,
/// and the file saves them only when not empty. A file's longer list opens with the first 8.
+4
View File
@@ -7,6 +7,9 @@ pub struct CharStyle {
pub font_family: String,
#[serde(default = "regular")]
pub font_style: String,
/// Internal layout selection from a validated file-font binding, never read from a file.
#[serde(skip)]
pub file_font_id: Option<u32>,
/// Which installed version of the font (its version string) when several versions of the
/// family and style are installed and the text was set in one the family and style alone
/// wouldn't pick (an imported file's type matched to it); None = the one they pick.
@@ -656,6 +659,7 @@ impl Default for CharStyle {
Self {
font_family: "Source Sans 3".into(),
font_style: "Regular".into(),
file_font_id: None,
font_version: None,
font_axes: std::collections::BTreeMap::new(),
size: 12.0,
+105
View File
@@ -0,0 +1,105 @@
use std::sync::Arc;
use serde::{Deserialize, Serialize};
/// The MIME type of a font a file carried ([`FileFonts`]), kept among the document's image blobs
/// ([`crate::Document::images`]).
pub const FILE_FONT_MIME: &str = "font/ttf";
/// The most fonts of [`FileFonts`] that draw one type object (a file's list may be longer: the rest
/// are left out).
pub const MAX_FILE_FONTS: usize = 64;
/// The fonts a file carried for type whose fonts aren't available here (a PDF's embedded fonts),
/// kept with the document among its image blobs ([`crate::Document::images`], MIME
/// [`FILE_FONT_MIME`]). A file embeds its fonts so that readers see its text in its own fonts
/// rather than substitutes (Acrobat Help, PDF fonts,
/// <https://helpx.adobe.com/acrobat/using/pdf-fonts.html>); editing text in a font that isn't
/// installed sets it in a substitute (Acrobat Help, Edit text in PDFs,
/// <https://helpx.adobe.com/acrobat/using/edit-text-pdfs1.html>). So the type is drawn in these,
/// as the file drew it, while its text is the one the file had and a font it names isn't
/// available: once its text is edited (or that font is installed) it takes the font it names, or
/// its substitute. Its runs keep naming the file's fonts, so they stay listed as missing.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileFonts {
/// The font kept for each family and style the runs name.
pub fonts: Vec<FileFont>,
/// The text as the file had it ([`text_hash`] of the plain text).
pub text: u64,
/// Validated runtime resources; serialized keys alone never authorize a font lookup.
#[serde(skip)]
resources: Vec<(String, u32, std::sync::Weak<dyn FileFontFace>)>,
}
impl FileFonts {
/// `fonts` for type whose text is `text`.
pub fn new(fonts: Vec<FileFont>, text: &str) -> Self {
Self { fonts, text: text_hash([text]), resources: vec![] }
}
/// The runtime face bound to this reference by its owning document.
pub fn face(&self, key: &str) -> Option<Arc<dyn FileFontFace>> {
self.resources.iter().find(|(k, _, _)| k == key).and_then(|(_, _, face)| face.upgrade())
}
/// Replace validated bindings, returning whether their runtime identity changed.
pub fn bind(&mut self, resources: Vec<(String, Arc<dyn FileFontFace>)>) -> bool {
let changed = self.resources.len() != resources.len()
|| self.resources.iter().zip(&resources).any(|((a, id, _), (b, face))| a != b || *id != face.id());
self.resources = resources.into_iter().map(|(key, face)| (key, face.id(), Arc::downgrade(&face))).collect();
changed
}
/// Remap serialized and validated runtime resource keys together when art changes namespaces.
/// The callback applies the same mapping to each occurrence of an original key.
pub fn map_keys(&mut self, mut map: impl FnMut(&mut String)) {
for font in &mut self.fonts {
map(&mut font.key);
}
for (key, _, _) in &mut self.resources {
map(key);
}
}
}
impl PartialEq for FileFonts {
fn eq(&self, other: &Self) -> bool {
self.fonts == other.fonts
&& self.text == other.text
&& self.resources.len() == other.resources.len()
&& self.resources.iter().zip(&other.resources).all(|((a, aid, _), (b, bid, _))| a == b && aid == bid)
}
}
/// A runtime file-font resource owned by image blobs, undo snapshots and clipboard resources.
/// The text engine implements this interface without making the document depend on it.
pub trait FileFontFace: Send + Sync {
fn id(&self) -> u32;
fn bytes(&self) -> &[u8];
}
impl std::fmt::Debug for dyn FileFontFace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FileFontFace").field("id", &self.id()).finish()
}
}
/// One font of [`FileFonts`]: the family and style type names it by, and its blob.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileFont {
pub family: String,
pub style: String,
/// The font's blob among the document's image blobs.
pub key: String,
}
/// A hash of the text `parts` make one after another (64-bit FNV-1a of its UTF-8 bytes): the same
/// on every machine and in every version, as a saved [`FileFonts::text`] needs.
pub fn text_hash<'a>(parts: impl IntoIterator<Item = &'a str>) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in parts.into_iter().flat_map(str::bytes) {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
+13
View File
@@ -1,5 +1,6 @@
use super::area::{AreaOptions, PathAlign, PathEffect};
use super::char_style::CharStyle;
use super::file_fonts::{FileFont, MAX_FILE_FONTS, text_hash};
use super::para_style::{JustificationOptions, ParaStyle};
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
use super::tabs_lists::{ListCounts, ParaList};
@@ -126,6 +127,7 @@ impl TextObject {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -144,6 +146,17 @@ impl TextObject {
pub fn plain_text(&self) -> String {
self.runs.iter().map(|r| r.text.as_str()).collect()
}
/// The fonts the file this type came from carried ([`FileFonts`]) while its text is still the
/// file's (at most [`MAX_FILE_FONTS`]); none once it was edited, and for other type.
pub fn file_fonts_in_use(&self) -> &[FileFont] {
match self.file_fonts.as_deref() {
Some(f) if f.text == text_hash(self.runs.iter().map(|r| r.text.as_str())) => {
f.fonts.get(..f.fonts.len().min(MAX_FILE_FONTS)).unwrap_or_default()
}
_ => &[],
}
}
/// Does layout stack some of this type's characters as warichu ([`CharStyle::warichu`])? Not
/// on a path, which sets them as they are. Exports that write live text write such type as
/// outlines, as they do ruby: their text can't place the stacked lines.
+27
View File
@@ -801,3 +801,30 @@ fn auto_alignment_saves_readable_by_older_builds() {
// Files from before the flag keep their alignment.
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
}
#[test]
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
use super::file_fonts::*;
use super::*;
// The hash is the same everywhere and in every version (saved files carry it).
assert_eq!(text_hash([""]), 0xcbf2_9ce4_8422_2325);
assert_eq!(text_hash(["Ham", "burg"]), text_hash(["Hamburg"]));
assert_ne!(text_hash(["Hamburg"]), text_hash(["Hamburh"]));
let font = FileFont { family: "Source Serif 9".into(), style: "Regular".into(), key: "k".into() };
let mut t = TextObject::point(Point::ZERO, "Ham", CharStyle::default());
t.runs.push(TextRun::new("burg", CharStyle::default()));
assert!(t.file_fonts_in_use().is_empty());
t.file_fonts = Some(Box::new(FileFonts::new(vec![font.clone()], "Hamburg")));
assert_eq!(t.file_fonts_in_use(), std::slice::from_ref(&font));
// Saved and read back.
let json = serde_json::to_string(&t).unwrap();
assert!(json.contains(r#""fileFonts":{"fonts":[{"family":"Source Serif 9","style":"Regular","key":"k"}]"#), "{json}");
assert_eq!(serde_json::from_str::<TextObject>(&json).unwrap(), t);
// Edited: none.
t.runs[1].text.push('s');
assert!(t.file_fonts_in_use().is_empty());
// A file's list past the cap: the first ones.
t.runs[1].text.pop();
t.file_fonts.as_mut().unwrap().fonts = vec![font; MAX_FILE_FONTS + 5];
assert_eq!(t.file_fonts_in_use().len(), MAX_FILE_FONTS);
}
+3 -3
View File
@@ -89,9 +89,9 @@ pub use raster::{
without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
has_gradient_copies, has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies,
has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+23 -5
View File
@@ -388,11 +388,23 @@ fn row_effects_of(fx: &[Effect]) -> Vec<Effect> {
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
/// instance in the art takes them.
pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
add_instance_rows(doc, n, art, true);
}
/// [`add_instance_row_effects`] for Direct Selection's parts of a symbol instance's art: live
/// objects (blends, envelopes, repeats) are left as they are, without the effects, so that every
/// object keeps its place in the art and the child indices that pick a part still lead to it.
pub fn add_instance_row_effects_to_parts(doc: Option<&Document>, n: &Node, art: &mut Node) {
add_instance_rows(doc, n, art, false);
}
/// [`add_instance_row_effects`], evaluating live objects in the art only with `live`.
fn add_instance_rows(doc: Option<&Document>, n: &Node, art: &mut Node, live: bool) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
if !fill.is_empty() || !stroke.is_empty() {
add_row_effects(doc, symbol, art, &fill, &stroke);
add_row_effects(doc, symbol, art, &fill, &stroke, live);
}
}
@@ -413,8 +425,9 @@ fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet<String
}
/// [`add_instance_row_effects`] of `fill` and `stroke` to `n` and the art in it, the art of an
/// instance of the symbol named `outer`.
fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) {
/// instance of the symbol named `outer`. Without `live`, live objects are left as they are
/// ([`add_instance_row_effects_to_parts`]).
fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect], live: bool) {
match &n.kind {
NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return,
NodeKind::SymbolInstance { symbol, .. } => {
@@ -425,7 +438,12 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef
}
return;
}
_ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n),
_ if vectorcraft_doc::live::is_live(n) => {
if !live {
return;
}
*n = evaluated(doc, n);
}
_ => {}
}
let takes = |i: &AppearanceItem| {
@@ -445,7 +463,7 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef
let clips = n.clips();
for (i, c) in n.children_mut().into_iter().flatten().enumerate() {
if !(clips && i == 0) {
add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke);
add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke, live);
}
}
}
+1
View File
@@ -19,6 +19,7 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"]
heif = ["dep:heic-rs", "dep:rayon"]
[dependencies]
craft-codepage = { workspace = true }
# Which paths stored in documents may be opened.
craft-docpath = { workspace = true }
craft-proof = { workspace = true }
@@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() {
#[test]
fn color_mask_refuses_previews_and_images_too_large() {
let preview = std::sync::Arc::new(framed());
let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
let (mut s, id) =
linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string();
assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}");
assert_eq!(mask_of(doc(&s), id), None);
+6 -1
View File
@@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
let preview = Arc::new(bytes);
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
let missing = place_linked(
&mut s,
"missing",
ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() },
(12, 10),
);
let before = (image_of(&s, missing), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
+17 -2
View File
@@ -159,6 +159,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The fonts its file carried travel with it, as images do.
for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) {
f(Ref::Name(Res::Image, &ff.key));
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
@@ -807,6 +811,9 @@ impl Relink {
if relaid {
refresh_bounds(t);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| self.name(Res::Image, key));
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
@@ -1134,6 +1141,8 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// File-font resources refused while binding pasted type.
pub warnings: Vec<String>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
@@ -1158,13 +1167,18 @@ impl Imported {
}
}
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
if !self.warnings.contains(&note) {
self.warnings.push(note);
}
}
}
}
@@ -1462,6 +1476,7 @@ impl Clipboard {
&& out.relink.colors.is_empty()
&& out.relink.kinsoku.is_empty()
&& used.styles.is_empty());
out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d));
Ok(out)
}
+6 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Dimensions",
[],
None,
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}",
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}",
has_doc,
update
),
@@ -159,6 +159,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
return Err(error("Select dimensions to update"));
}
let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None };
let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None };
// Every dimension is checked before anything changes, and an update that changes none of
// them records no undo step.
let mut next = Vec::with_capacity(ids.len());
@@ -178,6 +179,10 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
}
dim.offset = distance(p, dim.offset)?;
dim.resolve(doc).map_err(error)?;
if let Some(at) = at {
dim.place(at);
dim.resolve(doc).map_err(error)?;
}
if dim != old {
next.push((*id, dim));
}
+2 -2
View File
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
has_selection,
smooth_region
),
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes",
has_doc,
join_scrub
),
+13 -84
View File
@@ -1,9 +1,10 @@
use vectorcraft_pathops::addons::pathtools as pt;
use vectorcraft_pathops::start_nearest;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad,
json, number_or, po,
};
// ---------- Smooth ----------
@@ -323,84 +324,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
out.into_vec()
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
/// instead of at a new one split in beside it.
const START_SNAP: f64 = 1e-3;
/// Distance (points) within which two points of a smoothed closed path count as equally near its
/// old start.
const START_TIE: f64 = 1e-6;
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
/// when there is none.
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
let mut best: Option<(f64, usize, f64)> = None;
for j in 0..orig.anchors.len() {
let hit = orig.segment(j).nearest(p, 1e-9);
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
best = Some((hit.distance_sq, j, hit.t));
}
}
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
}
/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new
/// anchor split into the segment there, which leaves the outline as it is. Of points equally near
/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used,
/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point,
/// is returned as it is.
fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
let n = sp.anchors.len();
if !sp.closed || n < 2 {
return sp;
}
// (distance, place along `orig` once a tie needs it, segment of `sp`, parameter)
type Best = (f64, Option<(usize, f64)>, usize, f64);
let mut best: Option<Best> = None;
for i in 0..n {
let c = sp.segment(i);
let hit = c.nearest(start, 1e-9);
if !hit.distance_sq.is_finite() || !hit.t.is_finite() {
continue;
}
let d = hit.distance_sq.sqrt();
match &mut best {
None => best = Some((d, None, i, hit.t)),
Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => {
let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt)));
let place = place_along(orig, c.eval(hit.t));
if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) {
best = Some((d, Some(place), i, hit.t));
}
}
Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)),
Some(_) => {}
}
}
let Some((_, _, i, t)) = best else { return sp };
let c = sp.segment(i);
let at = c.eval(t);
let first = if at.distance(c.p0) <= START_SNAP {
i
} else if at.distance(c.p3) <= START_SNAP {
(i + 1) % n
} else {
let mid = if sp.segment_is_line(i) {
Anchor::corner(at)
} else {
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
sp.anchors[i].h_out = l.p1;
sp.anchors[(i + 1) % n].h_in = r.p2;
Anchor::with_handles(at, l.p2, r.p1)
};
sp.anchors.insert(i + 1, mid);
i + 1
};
sp.anchors.rotate_left(first);
sp
}
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
@@ -759,8 +682,12 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.smoothRegion";
let pts = points_param(p, "points", C)?;
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
let tol = number_or(p, "fidelity", 2.5, C)?;
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
if !(lo..=hi).contains(&tol) {
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
}
let sigma = radius * SMOOTH_SPREAD;
let st = s.doc()?;
let mut plan = vec![];
@@ -908,7 +835,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol:
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.joinScrub";
let pts = points_param(p, "points", C)?;
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
let st = s.doc()?;
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
@@ -1035,6 +962,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use vectorcraft_pathops::START_SNAP;
use super::*;
/// A closed ring of four smooth anchors round (100, 100) with radius 50.
+3 -2
View File
@@ -1552,7 +1552,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
// Converted colors are compared with the document's resources, as another document's are
// (`Clipboard::import_into`); its images are still the document's own.
let imported = clip.import_into(d, choices, same_doc)?;
let mut imported = clip.import_into(d, choices, same_doc)?;
// Draw Inside: the clip group of the object drawn into, made on the first paste.
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
let artboards: Vec<usize> = boards
@@ -1570,7 +1570,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let mut c = d.reid(n);
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
imported.apply(&mut c, d);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
// A cross-document drag carries the graphic's appearance with it,
@@ -1698,6 +1698,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
"added": imported.added,
"merged": imported.merged,
"renamed": imported.renamed,
"warnings": imported.warnings,
}))
}
+49 -10
View File
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance outside template layers in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
can_expand,
expand_appearance
),
@@ -1616,33 +1616,72 @@ fn expanded_node(
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does
/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the
/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). A symbol's
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
let mut symbols = vec![];
let mut drawn = vec![];
let mut holds = false;
n.walk(&mut |c| {
if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() {
drawn.push(c);
}
if !in_art && !expandable(c) {
return;
}
holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin));
holds |= has_own_plugin_effect(c);
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
symbols.push(symbol.clone());
}
});
holds
|| drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen))
|| (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new()))
|| symbols.into_iter().any(|name| {
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
})
}
/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke?
fn has_own_plugin_effect(n: &Node) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin))
}
/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect
/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or
/// a group around it, is hidden. A group or layer that paints something and whose raster effects
/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers
/// in it make no images of their own; one that paints nothing makes no image, and its members
/// expand on their own.
fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] };
if !fx.is_empty() {
if draws_plugin_effect(d, n, seen) {
return true;
}
if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() {
return false;
}
}
n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen))
}
/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places,
/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object
/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does
/// with templates skipped. `seen` holds the symbols already looked into.
fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
if has_own_plugin_effect(n) {
return true;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.clone())
&& d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen))
{
return true;
}
let drawn =
|c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. });
n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen))
}
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let roots = edit_targets(s, p, "effect.expandAppearance")?;
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
+1 -1
View File
@@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::native_file;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
+17 -8
View File
@@ -193,8 +193,11 @@ fn restore_or_import(
let mut fallback = None;
if let Some((intact, bytes)) = editing {
let native = if intact { bytes() } else { None };
match native.and_then(|b| native_file(&b).ok()) {
Some((doc, _, warnings)) => return Ok((doc, warnings, true)),
match native.and_then(|b| decode_native_file(&b).ok()) {
Some((mut doc, _, mut warnings)) => {
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
return Ok((doc, warnings, true));
}
None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }),
}
}
@@ -205,9 +208,9 @@ fn restore_or_import(
Ok((doc, warnings, false))
}
/// A native file's document and details, the colour profiles it carries installed where missing
/// (with a warning for each that can't be used).
pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
/// Decode a native file and install its colour profiles, preserving profile and depth warnings.
/// The caller must assemble any external resources and bind file fonts before layout.
pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
let f = vectorcraft_format::load_file(bytes).map_err(err)?;
let mut warnings = super::native::install_profiles(f.profiles);
warnings.extend(f.depth_notes);
@@ -424,7 +427,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
})?
}
"vectorcraft" | "template" => {
let (d, info, warnings) = native_file(bytes)?;
let (mut d, info, mut warnings) = decode_native_file(bytes)?;
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d));
native_pdf_compatible = Some(info.pdf_compatible);
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
(d, warnings, false)
@@ -688,7 +692,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
let update_links = s.prefs.update_links == "automatically";
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
let p = s.prefs.with_pdf_font_choice(p);
open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?)
}
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
@@ -860,7 +865,11 @@ impl ReadFile {
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut self.loaded.doc);
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
if !self.loaded.warnings.contains(&note) {
self.loaded.warnings.push(note);
}
}
}
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
+21 -2
View File
@@ -47,6 +47,10 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs
/// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in
/// imported PDFs for opens and places that give none).
pub embedded_fonts: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
@@ -74,6 +78,7 @@ impl Default for LoadOptions {
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
embedded_fonts: true,
native: true,
link_pages: false,
}
@@ -84,7 +89,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -135,6 +140,10 @@ impl LoadOptions {
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?,
};
Ok(Self {
pages,
crop,
@@ -148,6 +157,7 @@ impl LoadOptions {
dxf,
editing_data,
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
link_pages,
@@ -177,6 +187,7 @@ impl LoadOptions {
text_as: self.text_as,
layers: self.layers,
uncalibrated_rgb: editor_document,
embedded_fonts: self.embedded_fonts,
..Default::default()
})
}
@@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene
/// The import options of [`page_document`].
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
ImportOptions {
pages: Some(vec![page]),
crop: o.crop,
password: o.password.clone(),
text_as: o.text_as,
layers: false,
embedded_fonts: o.embedded_fonts,
..Default::default()
}
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_pdf::TextAs;
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
use super::*;
@@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() {
#[test]
fn load_options_read_text_and_layers() {
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false));
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap();
assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false));
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
let d = LoadOptions::default();
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true));
let n = LoadOptions { native: false, ..Default::default() };
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
}
@@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap();
assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted");
}
/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a
/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's).
fn carried_font_pdf(content: &str, height: f64) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
widths.join(" "),
n + 1
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file], None)
}
/// The glyphs of the active document's type (document space origins) and how many come from fonts
/// files carried.
fn glyphs(s: &Session) -> (Vec<kurbo::Point>, usize) {
let db = vectorcraft_text::FontDb::global();
let (mut at, mut carried) = (vec![], 0);
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
at.push(t.xf * g.origin);
carried += usize::from(db.is_file_font(g.font_id));
}
}
});
(at, carried)
}
/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited:
/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited,
/// it takes the substitute, which exports then name.
#[test]
fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() {
let mut s = Session::new();
let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let family = fonts[0]["family"].as_str().unwrap().to_string();
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}");
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}");
let (at, carried) = glyphs(&s);
assert_eq!((at.len(), carried), (11, 11), "every glyph the file's");
let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family);
assert!(!warned(&mut s), "drawn as the file draws it: not substituted");
// Saved and opened again: the same.
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
assert_eq!(glyphs(&s), (at.clone(), carried));
// Edited: the substitute, which exports name, and the font still missing.
let mut id = None;
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
id = Some(n.id);
}
});
let id = id.unwrap();
let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone();
assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted");
s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap();
assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font");
assert!(warned(&mut s), "edited: substituted");
let findings = preflight(&mut s);
assert!(
findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont"
&& f["name"].as_str().is_some_and(|n| n.contains(&family))
&& f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))),
"preflight identifies the substituted text owner: {findings}"
);
assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family));
// Undone: the file's look again.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s), (at, carried));
assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font");
}
#[test]
fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() {
let db = vectorcraft_text::FontDb::global();
let serif = db.face("Source Serif 4", "Regular").unwrap();
let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap();
let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em();
assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute");
let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET";
let bytes = carried_font_pdf(content, 200.0);
let mut reference = Session::new();
open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap();
let want = glyph_ink(&reference, false);
assert_eq!(want.len(), 3);
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
let compare = |s: &Session| {
let mut areas = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area");
assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3);
areas += 1;
}
});
assert_eq!(areas, 1);
let got = glyph_ink(s, false);
assert_eq!(got.len(), want.len());
for (got, want) in got.iter().zip(&want) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{got:?} is {off} pt from {want:?}");
}
};
compare(&s);
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap();
compare(&s);
}
fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject};
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() };
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap());
let mut doc = Document::new(100.0, 100.0);
doc.images.insert("chosen".into(), blob.clone());
let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() });
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
(doc, blob, id)
}
/// No machine fonts are needed: the two native documents own different synthetic glyphs under
/// the same key. Paste must relink its own bytes, including after closing the source tab.
#[test]
fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Native Owned File Font Regression";
let open_native = |s: &mut Session, doc: &Document| {
let bytes = vectorcraft_format::save_file(doc);
s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap()
};
let face_of = |s: &Session, id| {
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0];
FontDb::global().face_by_id(g.font_id).unwrap()
};
let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0);
let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0);
let mut s = Session::new();
open_native(&mut s, &a);
let a_index = s.active_index().unwrap();
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
open_native(&mut s, &b);
let b_index = s.active_index().unwrap();
let carried = face_of(&s, b_id).id();
assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice());
s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
assert!(s.close_document(b_index));
assert!(s.set_active(a_index));
let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}");
assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen"));
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
assert_eq!(face_of(&s, id).id(), carried);
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] {
let svg = options["format"] == "svg";
let exported = s.execute("document.serialize", &options).unwrap();
if svg {
let text = exported["text"].as_str().unwrap();
assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded");
} else {
let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
}
// SVG may warn that the same CSS description cannot distinguish these two x glyphs.
assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}");
}
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
let mut unowned = b.clone();
unowned.images.clear();
let report = open_native(&mut s, &unowned);
assert!(report["warnings"].to_string().contains(FAMILY));
assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font");
}
/// Place owns its carried font even after the decoded source is dropped, whether the destination
/// reuses an equal unbound blob or renames a key occupied by another font.
#[test]
fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Placed Owned Font Regression";
let (source, expected, _) = owned_font_document(FAMILY, 200.0);
let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source));
for same_bytes in [true, false] {
let mut host = Document::new(100.0, 100.0);
let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 };
host.images.insert("chosen".into(), blob);
let mut s = Session::new();
s.add_document(host, None);
let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap();
assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}");
let check = |s: &Session| {
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font");
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice());
drawn += 1;
}
}
});
assert_eq!(drawn, 1);
};
check(&s);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s).1, 0);
s.execute("edit.redo", &json!({})).unwrap();
check(&s);
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
check(&s);
}
}
fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::Affine;
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument};
let (source, expected, _) = owned_font_document(family, 200.0);
let bytes = vectorcraft_format::save_file(&source);
let blob = ImageBlob::new("application/json", bytes);
let key = format!("placed-font-{}", blob.content_key());
let mut host = Document::new(100.0, 100.0);
host.images.insert("chosen".into(), owned_font_document(family, 800.0).1);
host.images.insert(key.clone(), blob);
let placed = PlacedDocument {
key,
link: LinkInfo::new("/font-placement-regression.vectorcraft"),
bounding: false,
page_box: Default::default(),
width: 100.0,
height: 100.0,
xf: Affine::IDENTITY,
placement: Default::default(),
};
let id = host.alloc_id();
host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap();
(host, expected, id)
}
/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind
/// text to the host's unrelated font under the same key when reopened.
#[test]
fn placed_carried_fonts_survive_break_link_and_older_version_save() {
use vectorcraft_text::FontDb;
for break_link in [true, false] {
let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" };
let (host, expected, id) = linked_owned_font_document(family);
let mut s = Session::new();
s.add_document(host, None);
if break_link {
let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
assert_eq!(glyphs(&s).1, 1);
}
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id));
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}");
drawn += 1;
}
}
});
assert_eq!(drawn, 1, "{family}");
assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source");
}
}
/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode.
fn two_glyphs_for_one_character_pdf(content: &str) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>",
widths.join(" "),
n + 1,
n + 3
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None)
}
/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines.
fn glyph_ink(s: &Session, across: bool) -> Vec<kurbo::Rect> {
use kurbo::Shape;
let db = vectorcraft_text::FontDb::global();
let mut lines: [Option<kurbo::Rect>; 3] = [None; 3];
let mut add = |path: &kurbo::BezPath| {
let els = path.elements();
let mut start = 0;
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
let line = if across {
usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0)
} else {
usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0)
};
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
start = end;
}
};
s.doc().unwrap().doc.walk(|n| match &n.kind {
NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))),
NodeKind::Path { path, .. } => add(&path.to_bezpath()),
_ => {}
});
lines.into_iter().flatten().collect()
}
/// Two different glyphs of a carried font for one character can't both go into the font kept with
/// the document, which has one glyph per character, so the line with the other glyph is outlines.
/// Opened, saved in the native format and opened again, each glyph is still the one the file draws,
/// where it draws it: the same page opened as outlines is the reference.
#[test]
fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() {
let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET";
assert_carried_glyph_roundtrip(content, false);
}
#[test]
fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() {
let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET";
assert_carried_glyph_roundtrip(content, true);
}
fn assert_carried_glyph_roundtrip(content: &str, across: bool) {
let bytes = two_glyphs_for_one_character_pdf(content);
let mut reference_session = Session::new();
open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap();
let reference = glyph_ink(&reference_session, across);
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}");
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
assert!(
live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3,
"some glyphs stay type, the other is outlines: {:?}",
live_texts(&s)
);
let close = |s: &Session, what: &str| {
let got = glyph_ink(s, across);
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
for (got, want) in got.iter().zip(&reference) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
}
};
close(&s, "opened");
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
close(&s, "saved and reopened");
}
@@ -405,9 +405,9 @@ fn zipped_and_32_bit_layers_read() {
/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman.
#[test]
fn names_without_a_unicode_name_read_as_mac_roman() {
let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({}));
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}");
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}");
}
#[test]
+29 -9
View File
@@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts_of(d, art, false)
}
/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font
/// their file carried ([`in_file_fonts`]).
fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
if let NodeKind::Text(t) = &n.kind {
fonts.extend(t.runs.iter().flat_map(run_fonts));
let file = if drawn { in_file_fonts(t) } else { vec![] };
fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts));
}
};
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
@@ -659,21 +666,25 @@ impl<'a> Printed<'a> {
}
}
match &n.kind {
NodeKind::Text(_) => {
NodeKind::Text(t) => {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
let file = in_file_fonts(t);
for r in runs {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
// Drawn in a font its file carried: printed as the file drew it.
if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
@@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
/// families that aren't available (their type is drawn in the fallback font, not the font it
/// names) or styles that its family doesn't have (the closest style is drawn).
/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a
/// font its file carried isn't substituted.
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
substitution_warning_of(used_fonts(d))
substitution_warning_of(fonts_of(d, &[], true))
}
/// The families and styles of the runs of `t` drawn in a font its file carried
/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute,
/// though the font they name isn't available.
fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> {
let faces = vectorcraft_text::FontDb::global().file_faces(t);
t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect()
}
/// [`substitution_warning`] for type set in `fonts`.
+1 -1
View File
@@ -563,7 +563,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
_ => img.blob.mime.clone(),
};
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview });
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() });
}
let mut warnings = vec![];
match previews.len() {
+2 -1
View File
@@ -960,10 +960,11 @@ impl Session {
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
// The color profiles the file carries are installed where missing, as opening it installs
// them, so the new document's assigned profiles draw and are saved with it.
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
// Linked images in its symbols, patterns and brushes are read from their files, as placing
// a document reads them.
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
Ok(Some(ReadProfile { doc, file, warnings }))
}
}
+11 -2
View File
@@ -373,16 +373,25 @@ impl DocState {
}
}
/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick?
fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool {
t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET)
}
impl Session {
/// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)?
pub(crate) fn lent_by_bucket(&self) -> bool {
self.lender.as_deref().is_some_and(works_for_bucket)
}
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
/// sample its click takes before it switches back to the bucket.
pub fn bucket_paints(&self) -> bool {
let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket()
}
/// The tool the active tool's armed one-shot pick switches back to after its click
+2 -5
View File
@@ -199,14 +199,11 @@ pub fn specs() -> Vec<CommandSpec> {
// ---------- helpers ----------
/// Number param that also accepts strings like `"10 pt"`.
/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`).
pub(crate) fn num_param(p: &Value, key: &str) -> Option<f64> {
match p.get(key)? {
Value::Number(n) => n.as_f64(),
Value::String(s) => {
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
t.parse().ok()
}
Value::String(s) => whole_number(s),
_ => None,
}
.filter(|v: &f64| v.is_finite())
+1 -1
View File
@@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
};
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
}
/// Place the file `read` holds in the active document.
+16
View File
@@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
paint_refs(&mut r.style.fill, f);
paint_refs(&mut r.style.stroke, f);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| f(Ref::Image(key)));
}
}
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
@@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
dst.images.insert(new.to_string(), blob.clone());
}
}
// Equal font bytes can reuse an existing image entry whose runtime lease is still empty.
// Transfer the validated source lease too: cached text nodes hold only weak references.
for (old, (new, copy)) in &images {
if *copy {
continue;
}
let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue };
let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue };
let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) {
*target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
}
}
for (old, new) in copies(&symbols) {
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
def.name = new.to_string();
+5 -2
View File
@@ -333,7 +333,7 @@ fn read_source(
}
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let Some(blob) = out.images.get(&p.key) else { continue };
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
Some(bytes) => {
out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() });
out.images.insert(
p.key.clone(),
ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() },
);
}
None => {
previews.insert(p.key);
+2 -2
View File
@@ -651,8 +651,8 @@ mod tests {
let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}"));
assert_eq!(text_of(&s), "café€ 😀 end“q”");
assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character");
let mac = read(r"{\rtf1\mac \'8e\'a5}");
assert_eq!(text_of(&mac), "é•", "Mac Roman");
let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}");
assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman");
}
#[test]
+2 -15
View File
@@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
/// Byte `b` of Mac Roman.
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
const HIGH: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', //
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', //
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', //
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', //
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', //
'\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
match b {
0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
_ => char::from(b),
}
craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b)
}
/// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says:
@@ -344,7 +331,7 @@ mod tests {
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}");
}
/// The other character sets decode by their Encoding Standard decoders: the platform matters
+1
View File
@@ -396,6 +396,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool),
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
p!(
"updateLinks",
+4 -2
View File
@@ -1458,7 +1458,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A frame whose first paragraph continues from the frame before draws it without the
// paragraph's first-line indent and list marker.
super::threads::mark_continued(&mut doc);
@@ -1473,7 +1473,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
};
match read {
Ok(data) => {
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if r.proxy {
blob.proxy = Some(blob.bytes.clone());
@@ -1510,6 +1510,8 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let links_from = meta.path.clone().or_else(|| meta.links_from.clone());
let base = super::links::LinkBase::file(links_from.as_deref());
let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
// Bind only after the copy's external resources and linked files have been restored.
warnings.extend(Session::refresh_text_bounds(&mut doc));
let index = s.add_document(doc, meta.path.clone());
let st = s.doc_mut()?;
st.recovered = true;
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
has_selected_path,
retype
)]
+28
View File
@@ -1385,6 +1385,34 @@ fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() {
assert_eq!(r["texts"], json!(["oo"]), "{r}");
}
#[test]
fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_type() {
// An even-odd compound paints the same whichever way its contours run, so an o's counter may
// run the same way as its outer contour: neither the part as it is nor all its contours turned
// is the glyph. Filled by the nonzero rule, the same contours paint the o's counter, and the
// compound stays an outline.
for turned in [1usize, 2] {
let mut s = session();
let c = one_compound(&mut s, "do");
// One path per contour: the d's two, then the o's two.
let paths = children_of(&s, c);
assert_eq!(paths.len(), 4, "a d and an o are two contours each");
let p = paths[paths.len() - turned];
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(p)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&data.to_bezpath().reverse_subpaths());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter");
s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
}
}
#[test]
fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let mut s = session();
+23 -13
View File
@@ -11,8 +11,8 @@ use super::menucmds::whole_or;
use super::stroke::StrokeChange;
use super::typecmd::refresh_bounds;
use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index,
number_or, object_param, point_param, str_param, switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection,
index, number_or, object_param, str_param, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area / Path Type",
[],
None,
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
has_doc,
create_in_path
),
@@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option<usize> {
/// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result<usize> {
Ok(offset_given(p, k, cmd)?.unwrap_or(default))
}
/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_given(p: &Value, k: &str, cmd: &str) -> Result<Option<usize>> {
match p.get(k) {
None | Some(Value::Null) => Ok(default),
Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)),
None | Some(Value::Null) => Ok(None),
Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))),
}
}
@@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?),
};
let insert = str_param(p, "insert").unwrap_or("").to_string();
let insert = text_param(p, "insert", C)?.unwrap_or("").to_string();
let clear = clear_param(s, p, id, C)?;
let caret = s.edit("Typing", |d, _| {
for other in &clear {
@@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve
/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error
/// when there is no character there, it is an inline graphic, or its font is not available.
fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range<usize>, std::sync::Arc<vectorcraft_text::FontFace>)> {
check_numbers(p, &["start"], c)?;
let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let mut at = 0;
for run in &t.runs {
let end = at + run.text.len();
@@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.touchType";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
check_numbers(p, &["start"], C)?;
let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation"));
}
@@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.createInPath";
let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?;
let on_path = match str_param(p, "mode").unwrap_or("area") {
let on_path = match text_param(p, "mode", C)?.unwrap_or("area") {
"area" => false,
"onPath" | "path" => true,
o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))),
@@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["vertical", "placeholder"], C)?;
super::color_param(p, "color", C)?;
let style = super::create::new_type_style(s, p, C)?;
let text = str_param(p, "text").unwrap_or("").to_string();
let start = match point_param(p, "at") {
let text = text_param(p, "text", C)?.unwrap_or("").to_string();
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?),
};
let start = match at {
Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0),
_ => 0.0,
};
@@ -1842,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -2150,6 +2159,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
system_layout: t.system_layout,
fractional_widths: t.fractional_widths,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
+2 -2
View File
@@ -13,7 +13,7 @@ use super::edit::selected_roots;
use super::pathops::{length_given, number_given, shape_node};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or,
object_param, ok, str_param, switch_or, targets, text_param,
object_param, ok, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: i
}
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let ids = text_targets(s, p, "text.setText")?;
// The text the type already has is no undo step.
edit_if_nodes_changed(s, "Typing", &ids, |d| {
+3 -2
View File
@@ -75,8 +75,9 @@ pub struct Session {
/// back as it was at the release ([`Session::pointer`]).
pub(crate) lender: Option<Box<dyn Tool>>,
/// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
/// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
/// colors the bucket paints with ([`Session::bucket_paints`]).
/// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent
/// is deactivated as it goes back: their paint commands change the colors the bucket paints
/// with ([`Session::bucket_paints`]).
pub(crate) back_to_bucket: bool,
/// Pointer and key input that came while the tool computed an edit on another thread, each with
/// its number and view, made in order once the edit is applied.
+16
View File
@@ -281,6 +281,10 @@ pub struct Prefs {
pub recovery_off_for_complex: bool,
pub recent_files_count: u32,
pub low_res_proxy_eps: bool,
/// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
/// fallback font with the missing-font warning (#4568).
pub pdf_import_embedded_fonts: bool,
pub anti_aliased_bitmaps: bool,
pub update_links: String,
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
@@ -446,6 +450,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
impl Prefs {
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) {
return p.clone();
}
let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) };
out["embeddedFonts"] = serde_json::json!(false);
out
}
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
/// checked against the range, so a value outside it is brought inside, and one that is not a
/// number gives the default.
@@ -592,6 +607,7 @@ impl Default for Prefs {
recovery_off_for_complex: false,
recent_files_count: 20,
low_res_proxy_eps: false,
pdf_import_embedded_fonts: true,
anti_aliased_bitmaps: false,
update_links: s("askWhenModified"),
pdf_text_as: s("text"),
+10 -1
View File
@@ -24,6 +24,10 @@ impl Session {
});
// Clicks find an image's own fills and strokes where their effects draw them.
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
// Direct Selection picks and outlines the parts of a dynamic symbol's instance where the
// effects of the instance's fill and stroke draw them.
vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts);
vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry);
// Clicks inside a clip group fall in the region its clipping path's effects give it.
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
// Clicks and marquees find paths, compound paths, groups and layers where their geometry
@@ -289,7 +293,9 @@ impl Session {
/// what is fitted to type's bounds (an envelope warping it) would come out differently. That
/// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too,
/// not only in the layers (#1738).
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec<String> {
// The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]).
let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc);
// Inline graphics in text take their size from their symbols' art (not saved either).
doc.resolve_inline_art();
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
@@ -299,6 +305,7 @@ impl Session {
// The symbols' type is measured now: the inline graphics showing those symbols take their
// art's measured size, a symbol's type before the type that shows that symbol inline.
doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame);
warnings
}
/// Measure the type in open document `index` that `stale` picks (in its trees as
@@ -340,6 +347,8 @@ impl Session {
// (importers and the native reader have seen to theirs already, with a warning).
doc.limit_depth();
cmd::compositefonts::filter_loaded(&mut doc);
// Importers report binding failures; programmatic additions still need owned resources.
let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc);
// Inline graphics in text take their size from their symbols' art (not saved).
doc.resolve_inline_art();
// Ruler guides a reader left in the saved list become nodes on their layers.
+28
View File
@@ -3493,6 +3493,34 @@ fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_clic
assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample");
}
/// A Cmd-drag of a corner widget with the Live Paint Bucket that is cut short by choosing the
/// bucket again (the Selection tool it lent cancels the drag as it goes back) leaves the bucket's
/// colors as they were, with New Art Has Basic Appearance off: the selected object's appearance
/// does not replace them.
#[test]
fn live_paint_bucket_keeps_its_colors_when_a_lent_drag_is_cut_short() {
let v = ViewInfo::default();
let mut s = session();
let rect = rect(&mut s, 300.0, 300.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.select_tool("livePaintBucket", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let fill = s.paint.fill.clone();
let st = s.doc().unwrap();
let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show");
let at = w.visible().next().expect("a widget");
let cmd = Mods { cmd: true, ..Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 8.0, at.y + 8.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection", "the bucket lent the Selection tool for the drag");
assert!(s.in_interaction(), "the corner widget drag is in progress");
s.select_tool("livePaintBucket", v).unwrap();
assert_eq!(s.tool_id(), "livePaintBucket");
assert_eq!(s.paint.fill, fill, "the bucket's fill stays");
}
/// A gradient stop selected on the selection's gradient is not selected once the Live Paint
/// Bucket is active (its proxies show the default paint), and one selected on the bucket's
/// gradient is not selected once another tool is chosen.
+3 -3
View File
@@ -481,7 +481,7 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
fn a_colorized_missing_link_placeholder_is_not_flattened() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -502,7 +502,7 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() {
fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -523,7 +523,7 @@ fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.edit("Colorize", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
+60
View File
@@ -3335,6 +3335,66 @@ fn path_eraser_width_outside_its_range_is_refused() {
}
}
/// `path.smoothRegion` refuses a `radius` outside 0.001 to 1000 pt and a `fidelity` outside the
/// Smooth tool's tolerance range, and `path.joinScrub` a `tolerance` outside 0.001 to 1000 pt: the
/// document, the selection and the undo history do not change. The ends of each range are taken,
/// and null is read as the key left out, which smooths or joins in one undo step.
#[test]
fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() {
let mut s = session();
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": if i % 2 == 0 { 200.0 } else { 203.0 }})).collect();
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let drag = json!({"points": [[90, 200], [200, 200], [310, 200]]});
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
let reaches = [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)];
let fidelities = [json!(0), json!(-1), json!(lo / 2.0), json!(hi * 1.01), json!(1e300)];
let refused = reaches
.iter()
.map(|x| ("radius", x, "`radius` must be from 0.001 to 1000".to_string()))
.chain(fidelities.iter().map(|x| ("fidelity", x, format!("`fidelity` must be from {lo} to {hi} pt"))));
for (key, x, want) in refused {
let sel = s.doc().unwrap().selection.clone();
refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({ key: x })), &want);
assert_eq!(s.doc().unwrap().selection, sel, "{key} {x} changed the selection");
}
for extra in [json!({"radius": 0.001}), json!({"radius": 1000}), json!({"fidelity": lo}), json!({"fidelity": hi})] {
let undo = undo_steps(&s);
s.execute("path.smoothRegion", &with(&drag, extra.clone())).unwrap_or_else(|e| panic!("{extra}: {e}"));
while undo_steps(&s) > undo {
s.execute("edit.undo", &json!({})).unwrap();
}
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
}
let before = path(&s, id);
let undo = undo_steps(&s);
s.execute("path.smoothRegion", &with(&drag, json!({"radius": null, "fidelity": null}))).unwrap();
assert!(path(&s, id) != before, "the default radius and fidelity smoothed nothing");
assert_eq!(undo_steps(&s), undo + 1);
let mut s = session();
line(&mut s, 100.0, 100.0, 200.0, 100.0);
line(&mut s, 205.0, 100.0, 300.0, 150.0);
s.execute("select.none", &json!({})).unwrap();
let scrub = json!({"points": [[202, 90], [202, 110]]});
for x in &reaches {
refuses_with(&mut s, "path.joinScrub", &with(&scrub, json!({"tolerance": x})), "`tolerance` must be from 0.001 to 1000");
assert_eq!(paths(&s).len(), 2, "tolerance {x}");
}
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 0.001}))).unwrap();
assert_eq!(paths(&s).len(), 2, "0.001 pt reaches neither end");
let undo = undo_steps(&s);
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 1000}))).unwrap();
while undo_steps(&s) > undo {
s.execute("edit.undo", &json!({})).unwrap();
}
s.execute("select.none", &json!({})).unwrap();
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": null}))).unwrap();
assert_eq!(paths(&s).len(), 1, "the default tolerance joined nothing");
assert_eq!(undo_steps(&s), undo + 1);
}
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
/// nothing; null is read as the key left out.
+180
View File
@@ -587,6 +587,186 @@ fn direct_selection_paints_one_object_of_one_dynamic_instance() {
assert_eq!(pixel(&s, 80, 30), BLUE);
}
/// Instance `inst` with a new fill (`fill`) or stroke row without paint whose effect is `effect`
/// with `params`.
fn row_effect(s: &mut Session, inst: NodeId, fill: bool, effect: &str, params: Value) {
s.execute(if fill { "appearance.addFill" } else { "appearance.addStroke" }, &json!({"ids": [inst.0]})).unwrap();
let row = node(s, inst).appearance.items.len() - 1;
s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": row, "none": true})).unwrap();
s.execute("effect.apply", &json!({"ids": [inst.0], "item": row, "effect": effect, "params": params})).unwrap();
}
/// The object of `inst`'s art that Direct Selection picks at (`x`, `y`) with `opt`.
fn part_at(s: &Session, inst: NodeId, (x, y): (f64, f64), opt: vectorcraft_doc::hit::HitOptions) -> Option<Vec<u32>> {
let doc = &s.doc().unwrap().doc;
vectorcraft_doc::hit::symbol_part_at(doc, doc.node(inst).unwrap(), vectorcraft_geom::Point::new(x, y), opt)
}
/// The box of the outline of the object at `path` in `inst`'s art, as Direct Selection draws it.
fn part_outline_box(s: &Session, inst: NodeId, path: &[u32]) -> Rect {
use vectorcraft_geom::kurbo::Shape;
let doc = &s.doc().unwrap().doc;
let outline = vectorcraft_doc::hit::symbol_part_outline_in_view(doc, doc.node(inst).unwrap(), path, Default::default()).unwrap();
outline.bounding_box()
}
/// A geometry effect on a dynamic instance's fill or stroke moves where the objects of its art
/// are drawn: Direct Selection picks an object where it is drawn, not where its own shape no longer
/// paints, and outlines it there; Outline view still takes the plain shapes.
#[test]
fn direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let inst = pair(&mut s, "dynamic");
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
// The squares are drawn at x 110..150 and 160..200.
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the first square where it is drawn");
assert_eq!(part_at(&s, inst, (180.0, 30.0), opt), Some(vec![1]), "the second square where it is drawn");
assert_eq!(part_at(&s, inst, (80.0, 30.0), opt), None, "where the second square's own shape no longer paints");
assert_eq!(part_at(&s, inst, (60.5, 30.0), opt), None, "the plain edge of the second square");
assert_eq!(part_at(&s, inst, (60.5, 30.0), HitOptions { outline: true, ..opt }), Some(vec![1]), "Outline view draws the plain shapes");
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 110.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline follows the moved square: {b:?}");
direct(&mut s, (130.0, 30.0), (130.0, 30.0), Mods::default());
let sel = s.doc().unwrap().selection.clone();
assert_eq!(sel.objects, [inst]);
assert_eq!(sel.symbol_part, Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![0] }), "a press on the drawn square picks it");
// A stroke effect: Offset Path moves the first square's stroke out to x = 0.
let mut s = session();
let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0));
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#00ff00"})).unwrap();
let inst = id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, false, "path.offsetPath", json!({"offset": 10}));
assert_eq!(part_at(&s, inst, (0.5, 30.0), opt), Some(vec![0]), "the moved stroke");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), Some(vec![0]), "the fill keeps its shape");
let b = part_outline_box(&s, inst, &[0]);
assert!(b.x0 < 1.0 && b.x1 > 59.0, "the outline takes in the moved stroke: {b:?}");
// A symbol instance in the art takes the effect too: it is picked and outlined where its art is
// drawn, not in its box. The fill effect moves its square; its image has no fill and stays.
let mut s = session();
let a = square(&mut s, 10.0);
place_image(&mut s);
let img = top(&s);
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0, img.0]})).unwrap());
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance's square where it is drawn");
assert_eq!(part_at(&s, inst, (65.0, 35.0), opt), Some(vec![0]), "the nested instance's image");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box");
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 50.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline takes in the moved square and the image: {b:?}");
// A nested instance with a geometry effect of its own is picked where both effects draw it.
let mut s = session();
let a = square(&mut s, 10.0);
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap());
s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "distort.transform", "params": {"moveV": 30}})).unwrap();
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
assert_eq!(part_at(&s, inst, (130.0, 60.0), opt), Some(vec![0]), "the nested square moved by both effects");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box");
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 110.0).abs() < 0.5 && (b.y0 - 40.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "the outline follows both effects: {b:?}");
// Type with a fill of its own in the art is picked and outlined where the fill effect draws its
// glyphs, not in its own bounds.
let mut s = session();
let t = id(&s.execute("text.create", &json!({"x": 10, "y": 45, "size": 40, "text": "I"})).unwrap());
s.execute("appearance.addFill", &json!({"ids": [t.0]})).unwrap();
let plain = {
let doc = &s.doc().unwrap().doc;
doc.node(t).unwrap().geometric_bounds().unwrap()
};
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [t.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
// The type's own color still paints the glyph in place; the new fill paints it 100 pt right.
let drawn = part_outline_box(&s, inst, &[0]);
assert!(drawn.x1 > plain.x1 + 90.0 && drawn.x1 < plain.x1 + 101.0, "the outline takes in the moved glyph: {drawn:?}, plain {plain:?}");
let glyph = drawn.x1 - 100.0 - drawn.x0;
let (x, y) = (drawn.x1 - glyph / 2.0, (drawn.y0 + drawn.y1) / 2.0);
assert_eq!(part_at(&s, inst, (x, y), opt), Some(vec![0]), "the type where the fill effect draws its glyph");
assert_eq!(part_at(&s, inst, (plain.x0 + 1.0, plain.y0 + 1.0), opt), None, "the type's own bounds, off its glyph");
let by_path = HitOptions { type_path_only: true, ..opt };
assert_eq!(part_at(&s, inst, (plain.x1 - 1.5, 45.0), by_path), Some(vec![0]), "Type Object Selection by Path Only takes the baseline");
// A nested instance whose own effect adds only pixels (a drop shadow) is still picked where the
// outer fill effect draws its art.
let mut s = session();
let a = square(&mut s, 10.0);
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap());
s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "stylize.dropShadow"})).unwrap();
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the shadowed nested square where it is drawn");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the shadowed nested instance's own box");
// An image whose fill has Convert to Shape is picked and outlined where the instance's fill
// effect moves that shape.
let mut s = session();
place_image(&mut s);
let img = top(&s);
let frame = node(&s, img).geometric_bounds().unwrap();
s.execute("appearance.addFill", &json!({"ids": [img.0]})).unwrap();
s.execute("paint.setFill", &json!({"ids": [img.0], "color": "#00ff00", "item": 0})).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "convertToShape.rectangle", "item": 0})).unwrap();
let b = square(&mut s, 200.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [img.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
let c = frame.center();
assert_eq!(part_at(&s, inst, (c.x + 100.0, c.y), opt), Some(vec![0]), "the image where its fill is drawn");
let o = part_outline_box(&s, inst, &[0]);
assert!(o.x1 > frame.x1 + 99.0, "the outline takes in the moved fill: {o:?}, frame {frame:?}");
}
/// A clipping path in a dynamic symbol's art with a geometry effect of its own is picked by its
/// own geometry, and Direct Selection outlines that geometry, not the shape the effect draws.
#[test]
fn a_picked_clipping_path_is_outlined_by_its_own_geometry() {
let mut s = session();
let content = square(&mut s, 20.0);
let clip = square(&mut s, 10.0);
s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap();
s.execute("effect.apply", &json!({"ids": [clip.0], "effect": "path.offsetPath", "params": {"offset": 10}})).unwrap();
let group = top(&s);
assert!(node(&s, group).clips());
let inst = id(&s.execute("symbol.new", &json!({"name": "Clip", "ids": [group.0], "type": "dynamic"})).unwrap());
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}");
}
/// A symbol instance in a dynamic symbol's art whose own art is a clip group takes the instance's
/// fill effect on the clip group's members, which the canvas draws moved: Direct Selection picks it
/// where its member is drawn, not where the member's own shape is, and outlines it there.
#[test]
fn a_nested_instance_of_a_clip_group_is_picked_where_the_fill_effect_draws_its_art() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let content = square(&mut s, 10.0);
let clip = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 60})).unwrap());
s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap();
let group = top(&s);
assert!(node(&s, group).clips());
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [group.0]})).unwrap());
let b = square(&mut s, 160.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
// The member is drawn at x 110..150, inside the clipping path.
assert_eq!(pixel(&s, 130, 30), BLUE, "the canvas draws the member moved");
assert_ne!(pixel(&s, 30, 30), BLUE, "and not in its own place");
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance where its member is drawn");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the member's own place");
let o = part_outline_box(&s, inst, &[0]);
assert!((o.x0 - 110.0).abs() < 0.5 && (o.x1 - 150.0).abs() < 0.5, "the outline follows the moved member: {o:?}");
}
#[test]
fn a_drag_of_a_picked_object_moves_nothing_and_says_why() {
let mut s = session();
+9 -2
View File
@@ -1019,8 +1019,15 @@ fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_n
im.link.as_mut().unwrap().path = logo_ai.clone();
im.link.as_mut().unwrap().relative = None;
let key = im.key.clone();
d.images
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
d.images.insert(
key,
vectorcraft_doc::ImageBlob {
mime: "application/postscript".into(),
bytes: std::sync::Arc::new(eps.to_vec()),
proxy: None,
file_font: Default::default(),
},
);
Ok(())
})
.unwrap();
+6
View File
@@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() {
assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set);
let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap();
assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}");
for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] {
let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap();
assert_eq!(r["precision"], json!(want), "{given}");
}
s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap();
for bad in [
json!({"precision": 0}),
json!({"precision": 11}),
json!({"precision": "x"}),
json!({"precision": "1abc"}),
json!({"precision": "0.5 extra"}),
json!({"precision": -1}),
json!({"removeRedundantPoints": "yes"}),
json!({"removeUnpainted": 1}),
+4 -1
View File
@@ -999,7 +999,10 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.edit("Brush", |d, _| {
d.images.insert("k".into(), vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert(
"k".into(),
vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() },
);
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 2,
+20
View File
@@ -2979,6 +2979,26 @@ fn snap_to_glyph_options_read_set_and_reset() {
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
}
/// File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default)
/// reaches Open and Place as the `embeddedFonts` choice, unless a call gives its own (#4568).
#[test]
fn the_embedded_fonts_preference_reaches_the_import_options() {
use crate::cmd::fileio::LoadOptions;
let mut s = Session::new();
assert!(s.prefs.pdf_import_embedded_fonts, "on by default");
let on = s.prefs.with_pdf_font_choice(&json!({}));
assert!(LoadOptions::from_params("x", &on).unwrap().embedded_fonts);
s.execute("prefs.set", &json!({"key": "pdfImportEmbeddedFonts", "value": false})).unwrap();
let off = s.prefs.with_pdf_font_choice(&json!({"page": 2}));
assert_eq!(off["page"], 2, "the call's own params stay");
assert!(!LoadOptions::from_params("x", &off).unwrap().embedded_fonts);
assert!(!LoadOptions::from_params("x", &s.prefs.with_pdf_font_choice(&Value::Null)).unwrap().embedded_fonts);
// A call that says so wins over the preference.
let own = s.prefs.with_pdf_font_choice(&json!({"embeddedFonts": true}));
assert!(LoadOptions::from_params("x", &own).unwrap().embedded_fonts);
assert!(LoadOptions::from_params("x", &json!({"embeddedFonts": "yes"})).is_err());
}
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
/// values change nothing, preferences saved without the group read it as all on, and resetting the
+71
View File
@@ -69,6 +69,77 @@ fn native_recovery_copies_leave_out_the_pdf() {
assert_eq!(vectorcraft_format::load(&bytes).unwrap().node_count(), s.doc().unwrap().doc.node_count());
}
const RECOVERY_FONT_FAMILY: &str = "Recovery Carried Font Regression";
const RECOVERY_FONT_BYTES: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
fn carried_font_copy() -> (Arc<MemoryStore>, vectorcraft_doc::NodeId) {
use vectorcraft_doc::{CharStyle, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind, TextObject};
let (mut s, store) = session();
let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.images.insert("recovered-font".into(), ImageBlob::new(FILE_FONT_MIME, RECOVERY_FONT_BYTES.to_vec()));
// An uninstalled family ensures the fixture must be read from the recovered resource.
let style = CharStyle { font_family: RECOVERY_FONT_FAMILY.into(), size: 20.0, ..Default::default() };
let mut text = TextObject::point(kurbo::Point::new(10.0, 40.0), "x", style);
text.file_fonts = Some(Box::new(FileFonts::new(
vec![FileFont { family: RECOVERY_FONT_FAMILY.into(), style: "Regular".into(), key: "recovered-font".into() }],
"x",
)));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
let saved = s.execute("file.recovery.save", &json!({})).unwrap();
let file = saved["saved"][0]["file"].as_str().unwrap();
let lean = vectorcraft_format::load(&store.read(&format!("{file}.vectorcraft")).unwrap()).unwrap();
assert!(lean.images.is_empty(), "the font travels in the recovery store, not the document entry");
drop(s);
(store, id)
}
#[test]
fn recovered_carried_fonts_bind_after_their_resources_are_restored() {
use vectorcraft_doc::NodeKind;
use vectorcraft_text::FontDb;
let (store, id) = carried_font_copy();
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
assert!(reply["restored"][0]["warnings"].as_array().unwrap().is_empty(), "{reply}");
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.images["recovered-font"].bytes.as_slice(), RECOVERY_FONT_BYTES);
let NodeKind::Text(text) = &doc.node(id).unwrap().kind else { panic!("text") };
let db = FontDb::global();
let laid = vectorcraft_text::layout(db, text);
assert_eq!(laid.glyphs.len(), 1);
let face = db.face_by_id(laid.glyphs[0].font_id).unwrap();
assert_eq!(face.file_data(), RECOVERY_FONT_BYTES, "layout uses the recovered font's exact bytes");
}
#[test]
fn recovered_missing_or_corrupt_carried_fonts_report_the_actual_refusal() {
for missing in [true, false] {
let (store, id) = carried_font_copy();
let blob = store.list().unwrap().into_iter().find(|name| name.ends_with(".blob")).unwrap();
if missing {
store.remove(&blob).unwrap();
} else {
store.write(&blob, b"not a font").unwrap();
}
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
let warnings = reply["restored"][0]["warnings"].as_array().unwrap();
assert!(
warnings.iter().any(|note| note.as_str().is_some_and(|note| note.contains(RECOVERY_FONT_FAMILY) && note.contains("substitute"))),
"missing={missing}: {reply}"
);
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
assert!(vectorcraft_text::FontDb::global().file_faces(text).is_empty(), "missing={missing}");
}
}
#[test]
fn restored_recovery_copies_keep_the_original_pdf_preference() {
let dir = crate::tests_links::Folder::new("recovered-pdf-preference");
+67 -14
View File
@@ -122,34 +122,87 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
}
/// The points of a closed 80-gon of radius 100 round (300, 300), starting at (400, 300).
fn eighty_gon() -> Vec<(f64, f64)> {
(0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect()
}
/// On a closed 80-gon, a run from anchor 70 through the start point to anchor 10 simplifies as one
/// run: anchor 0 goes, anchors 11–69 stay exactly as they were (the path now starts at anchor 10),
/// anchors 10 and 70 stay where they were with their outer handles, and the path stays closed.
/// run: anchor 0 goes, and the path starts at a new anchor where the refitted run passes nearest
/// it; anchors 11–69 stay exactly as they were, anchors 10 and 70 stay where they were with their
/// outer handles, the path stays closed, and the refitted run stays direct-selected.
#[test]
fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() {
let mut s = session();
let pts: Vec<(f64, f64)> =
(0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect();
let id = polyline(&mut s, &pts, true);
let id = polyline(&mut s, &eighty_gon(), true);
let original = path_of(&s, id).subpaths[0].clone();
select_anchors(&mut s, id, &[(70, 79), (0, 10)]);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
let sp = path_of(&s, id).subpaths[0].clone();
assert!(sp.closed);
assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len());
assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run");
assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
for i in 0..60 {
assert_eq!(sp.segment(i), original.segment(10 + i));
}
let moved = sp.anchors[0].p.distance(original.anchors[0].p);
assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt");
let n = sp.anchors.len();
assert!(worst_offset(&original, (70..80).chain(0..10), &sp, 60..n) <= 1.0 + 1e-6);
let sel: BTreeSet<_> = std::iter::once((0, 0)).chain((60..n).map(|i| (0, i))).collect();
let k = sp.anchors.iter().position(|a| a.p == original.anchors[10].p).unwrap();
let mut turned = sp.clone();
turned.anchors.rotate_left(k);
assert_eq!(turned.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
assert_eq!((turned.anchors[0].p, turned.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
assert_eq!((turned.anchors[60].p, turned.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
for i in 0..60 {
assert_eq!(turned.segment(i), original.segment(10 + i));
}
assert!(worst_offset(&original, (70..80).chain(0..10), &turned, 60..n) <= 1.0 + 1e-6);
let sel: BTreeSet<_> = (0..=k).chain(k + 60..n).map(|i| (0, i)).collect();
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
}
/// Smooth of a direct-selected run across the start of a closed 80-gon starts the path near where it
/// started too, with fewer anchors.
#[test]
fn smoothing_a_run_across_the_start_keeps_the_start() {
let mut s = session();
let id = polyline(&mut s, &eighty_gon(), true);
let original = path_of(&s, id).subpaths[0].clone();
select_anchors(&mut s, id, &[(70, 79), (0, 10)]);
s.execute("object.path.smooth", &json!({"level": 50})).unwrap();
let sp = path_of(&s, id).subpaths[0].clone();
assert!(sp.closed && sp.anchors.len() < 80, "{}", sp.anchors.len());
let moved = sp.anchors[0].p.distance(original.anchors[0].p);
assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", sp.anchors[0].p);
}
/// A dashed closed path keeps its start, where its dashes begin, through Simplify and through
/// Smooth: a loop of radius 50 round (300, 300) with a needle out to (550, 300), starting on the far
/// side of the loop at (250, 300). Its stroke stays as it was, and each command is one undo step.
#[test]
fn a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth() {
let mut s = session();
let at = |deg: f64| (300.0 + 50.0 * deg.to_radians().cos(), 300.0 + 50.0 * deg.to_radians().sin());
let pts: Vec<(f64, f64)> =
(0..=20).map(|i| at(180.0 + 8.95 * f64::from(i))).chain([(550.0, 300.0)]).chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))).collect();
let id = polyline(&mut s, &pts, true);
s.execute("stroke.set", &json!({"ids": [id.0], "weight": 2, "dash": [10, 5]})).unwrap();
let stroke = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
let style = stroke(&s);
let original = path_of(&s, id).subpaths[0].clone();
// (command, params, how far the start may move: Simplify's tolerance, or Smooth's smoothing and tolerance)
let commands = [("object.path.simplify", json!({"tolerance": 1}), 1.0 + 1e-9), ("object.path.smooth", json!({"level": 50}), 5.0)];
for (command, params, limit) in commands {
let steps = undo_len(&s);
s.execute(command, &params).unwrap();
assert_eq!(undo_len(&s), steps + 1, "{command}");
let sp = path_of(&s, id).subpaths[0].clone();
assert!(sp.closed && sp.anchors.len() < original.anchors.len(), "{command}: {}", sp.anchors.len());
let moved = sp.anchors[0].p.distance(original.anchors[0].p);
assert!(moved <= limit, "{command}: the start moved {moved} pt, to {:?}", sp.anchors[0].p);
assert_eq!(stroke(&s), style, "{command}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path_of(&s, id).subpaths[0], original, "{command}");
}
}
/// Segments picked with the Direct Selection tool simplify the same way, and stay picked as
/// segments.
#[test]
+42
View File
@@ -671,6 +671,48 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() {
s.execute("text.setPathHandle", &handle(Value::Null)).unwrap();
}
/// Range edits, Set Text, area and on-path type and the glyph commands refuse a param of the wrong
/// type with an error naming the param, and leave the document and the undo history as they were:
/// text that is not a string, a byte offset that is fractional or negative, and a point that is not
/// two numbers. Null counts as a param left out, which keeps its default.
#[test]
fn text_edits_refuse_a_param_of_the_wrong_type() {
use crate::tests::not_refused;
let mut s = session();
let id = text(&mut s, "abc");
let frame = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 100, "height": 50})).unwrap()["id"].clone();
let line = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 400}, {"x": 400, "y": 400}]})).unwrap()["id"].clone();
let string = |k: &str| format!("`{k}` must be a string");
let whole = "`start` must be a whole number".to_string();
let point = "`at` must be a point: [x, y]".to_string();
let calls: Vec<(String, Value, String)> = [
("text.editRange", json!({"id": id.0, "start": 0, "end": 1, "insert": 5}), string("insert")),
("text.editRange", json!({"id": id.0, "start": 0, "end": 3, "insert": ["x"]}), string("insert")),
("text.setText", json!({"ids": [id.0], "text": true}), string("text")),
("text.createInPath", json!({"path": frame, "mode": 1}), string("mode")),
("text.createInPath", json!({"path": frame, "text": true}), string("text")),
("text.createInPath", json!({"path": line, "mode": "onPath", "text": "a", "at": [1, "y"]}), point.clone()),
("text.createInPath", json!({"path": line, "mode": "onPath", "at": [100]}), point.clone()),
("text.createInPath", json!({"path": frame, "text": "a", "at": "start"}), point),
("text.touchType", json!({"id": id.0, "start": 1.5, "dy": 2}), whole.clone()),
("text.touchType", json!({"id": id.0, "start": -1, "dy": 2}), whole.clone()),
("text.glyphAlternates", json!({"id": id.0, "start": 1.5}), whole.clone()),
("text.setGlyphAlternate", json!({"id": id.0, "start": -1, "gid": null}), whole),
]
.into_iter()
.map(|(cmd, p, msg)| (cmd.to_string(), p, msg))
.collect();
let wrong = not_refused(&mut s, &calls);
assert!(wrong.is_empty(), "not refused: {wrong:#?}");
// Null keeps each default: nothing inserted, area type with no text, no start point.
s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 1, "insert": null})).unwrap();
assert_eq!(obj(&s, id).plain_text(), "bc");
let r = s.execute("text.createInPath", &json!({"path": frame, "mode": null, "text": null, "at": null})).unwrap();
let t = obj(&s, NodeId(r["id"].as_u64().unwrap()));
assert!(matches!(t.kind, TextKind::Area { .. }) && t.plain_text().is_empty(), "{:?}", t.kind);
s.execute("text.createInPath", &json!({"path": line, "mode": "onPath", "text": "a", "at": [100, 400]})).unwrap();
}
/// Where each glyph of type object `id` is drawn from (its origin in font units), document space.
fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> {
let t = obj(s, id);
+20 -8
View File
@@ -1,7 +1,7 @@
//! Hosting the active tool: pointer/key events → actions → commands.
use serde_json::{Map, Value};
use vectorcraft_doc::Selection;
use vectorcraft_doc::{NodeId, Selection};
use vectorcraft_geom::Point;
use vectorcraft_tools::distort::perspective::widget::WidgetPlace;
use vectorcraft_tools::draw2::FEEDBACK;
@@ -319,6 +319,7 @@ impl Session {
/// Pen goes on drawing its path), less the work the gesture ended as a command would: a
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
let lent_by_bucket = self.lent_by_bucket();
let Some(lender) = self.lender.take() else { return Ok(()) };
// The points the lent tool left picked go back to the tool it was lent to when that tool
// picks mesh points, none when it unpicked them all (#8090). Group Selection and the
@@ -328,7 +329,12 @@ impl Session {
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|p| lender.options().get("meshPoints") != Some(p));
// The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint
// Bucket's when the bucket lent it ([`Session::bucket_paints`]).
let outer_bucket = self.back_to_bucket;
self.back_to_bucket |= lent_by_bucket;
let r = self.deactivate_tool(view);
self.back_to_bucket = outer_bucket;
self.keep_tool_settings();
self.tool = lender;
if let Some(points) = mesh_points {
@@ -1755,7 +1761,7 @@ impl Session {
(st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields)
};
let (overlays, transform_box) = if self.preview(cmd, p).is_ok() {
let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default();
let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default();
let (objects, color) = self
.active()
.map(|st| (st.selection.objects.clone(), st.selection.objects.first().map(|id| st.doc.layer_color(*id))))
@@ -1796,11 +1802,17 @@ const FEEDBACK_MAX_POINTS: usize = 100_000;
/// The outlines of every selected object, a group's members each with their own, or the selection's
/// bounds when the outlines' points and the objects evaluated to make them come to more than
/// [`FEEDBACK_MAX_POINTS`].
fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec<Overlay> {
let nodes = selection.objects.iter().filter_map(|&id| doc.node(id));
let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS).unwrap_or_else(|| {
doc.bounds_of(&selection.objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect()
});
/// [`FEEDBACK_MAX_POINTS`]. A `dimension.update` preview (`cmd`, `p`) that names its dimensions,
/// as the Dimension tool sends for a dimension it drags, outlines those dimensions instead.
fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection, cmd: &str, p: &Value) -> Vec<Overlay> {
let named: Vec<NodeId> = if cmd == "dimension.update" {
p.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect()
} else {
vec![]
};
let objects = if named.is_empty() { &selection.objects } else { &named };
let nodes = objects.iter().filter_map(|&id| doc.node(id));
let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS)
.unwrap_or_else(|| doc.bounds_of(objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect());
outlines.into_iter().map(|path| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false }).collect()
}
+322
View File
@@ -2119,6 +2119,328 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() {
assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0)));
}
/// A drag with the Dimension tool from a dimension already drawn moves its line as far across as
/// the pointer moved, keeps what it measures and its link to the art, and is one undo step. A
/// click on its line does not move it, and neither does Escape during the drag.
#[test]
fn dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line() {
let plain = ViewInfo::default();
let pt = vectorcraft_geom::Point::new;
let (mut s, first) = level_start(plain);
let (count, label) = (s.doc().unwrap().doc.node_count(), text(&s, first));
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
}
};
// Dragged up and to the side: the line goes up as far as the pointer, and stays over the
// points it measures.
drag(&mut s, (150.0, 170.0), (180.0, 130.0));
assert!(!s.in_interaction());
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(100.0, 200.0), pt(200.0, 200.0)));
assert_eq!((s.doc().unwrap().doc.node_count(), text(&s, first)), (count, label));
// One undo step puts it back.
run(&mut s, "edit.undo", json!({}));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
run(&mut s, "edit.redo", json!({}));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
// Still linked: moving the art moves its points, and the line keeps its distance from them.
let art = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
run(&mut s, "select.set", json!({"ids":[art]}));
run(&mut s, "object.move", json!({"dx":0,"dy":10}));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 140.0), pt(200.0, 140.0)));
run(&mut s, "object.move", json!({"dx":0,"dy":-10}));
run(&mut s, "select.none", json!({}));
run(&mut s, "dimension.update", json!({"ids":[first],"at":[150,170]}));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
// A click on the line picks a point there and leaves the dimension where it is.
linear_click(&mut s, plain, 150.0, 170.0);
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
// Escape during the drag leaves it where it was.
ev(&mut s, PointerKind::Down, 150.0, 170.0);
ev(&mut s, PointerKind::Drag, 150.0, 120.0);
assert!(s.in_interaction());
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
ev(&mut s, PointerKind::Up, 150.0, 120.0);
assert!(!s.in_interaction());
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
// A locked dimension is not moved: the drag from its line drags out nothing either.
run(&mut s, "select.set", json!({"ids":[first]}));
run(&mut s, "object.lock", json!({}));
drag(&mut s, (150.0, 170.0), (150.0, 130.0));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
assert_eq!(s.doc().unwrap().doc.node_count(), count);
}
/// A dimension moved with the Dimension tool lands on the level of a parallel dimension line
/// within the Smart Guides snapping tolerance, and its own line before the drag is not a level.
#[test]
fn a_dimension_moved_beside_another_lands_on_its_level() {
let plain = ViewInfo::default();
let pt = vectorcraft_geom::Point::new;
let (mut s, first) = level_start(plain);
linear_click(&mut s, plain, 200.0, 200.0);
linear_click(&mut s, plain, 300.0, 200.0);
linear_click(&mut s, plain, 250.0, 150.0);
let second = s.doc().unwrap().selection.objects[0].0;
run(&mut s, "select.none", json!({}));
assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 150.0), pt(300.0, 150.0)));
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
}
};
// 3.5 points off its own level, with no other level there: where the pointer puts it.
drag(&mut s, (150.0, 170.0), (150.0, 166.5));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 166.5), pt(200.0, 166.5)));
// 2.5 points below the first line's new level: on it.
drag(&mut s, (250.0, 150.0), (250.0, 169.0));
assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 166.5), pt(300.0, 166.5)));
}
/// `dimension.update` with `at` puts a linear dimension's line, an angular dimension's arc or a
/// radius line through the point, and keeps what each measures; a bad `at` changes nothing.
#[test]
fn dimension_update_at_moves_the_line_through_the_point() {
let mut s = session();
let line = edge(&mut s);
let linear = dim(&mut s, line);
let label = text(&s, linear);
run(&mut s, "dimension.update", json!({"ids":[linear],"at":[130,50]}));
let d = recipe(&s, linear);
assert!((d.line_ends().0.y - 50.0).abs() < 1e-9 && (d.line_ends().1.y - 50.0).abs() < 1e-9, "{:?}", d.line_ends());
assert_eq!(text(&s, linear), label);
let angular = run(&mut s, "dimension.create", json!({"mode":"angular","a":[100,0],"vertex":[0,0],"b":[0,100]}))["id"].as_u64().unwrap();
run(&mut s, "dimension.update", json!({"ids":[angular],"at":[60,0]}));
assert!((recipe(&s, angular).offset - 60.0).abs() < 1e-9);
let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap();
let radius = run(&mut s, "dimension.create", json!({"mode":"radius","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap();
run(&mut s, "dimension.update", json!({"ids":[radius],"at":[172,400]}));
let d = recipe(&s, radius);
assert!(d.b.distance(vectorcraft_geom::Point::new(172.0, 244.0)) < 1e-6, "turned toward the point: {:?}", d.b);
assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays");
let before = recipe(&s, linear);
for bad in [json!([1]), json!("x"), json!([0, 1e12])] {
assert!(s.execute("dimension.update", &json!({"ids":[linear],"at":bad})).is_err(), "{bad}");
assert_eq!(recipe(&s, linear), before);
}
}
/// A dimension dragged with the Dimension tool follows the part grabbed: a diameter grabbed on its
/// far half turns that half toward the pointer, and an angular arc grabbed away from its middle
/// grows by as much as the pointer moved away from the vertex.
#[test]
fn a_dragged_dimension_follows_the_part_grabbed() {
let plain = ViewInfo::default();
let mut s = session();
let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap();
let diameter = run(&mut s, "dimension.create", json!({"mode":"diameter","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap();
run(&mut s, "dimension.update", json!({"ids":[diameter],"at":[244,172]}));
let angular =
run(&mut s, "dimension.create", json!({"mode":"angular","a":[500,400],"vertex":[400,400],"b":[400,500],"offset":60}))["id"].as_u64().unwrap();
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
}
};
// Grabbed left of the center and dragged up: the left half goes up, the right half down.
drag(&mut s, (120.0, 172.0), (120.0, 152.0));
let d = recipe(&s, diameter);
assert!(d.b.y > 172.0 + 1.0, "the half not grabbed turns away from the pointer: {:?}", d.b);
assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays");
// Grabbed at the center: it turns toward the pointer.
drag(&mut s, (172.0, 172.0), (172.0, 100.0));
assert!(recipe(&s, diameter).b.distance(vectorcraft_geom::Point::new(172.0, 100.0)) < 1e-6, "{:?}", recipe(&s, diameter).b);
// Grabbed 10° from the arc's start and dragged 20 points straight away from the vertex.
let (sin, cos) = 10f64.to_radians().sin_cos();
drag(&mut s, (400.0 + 60.0 * cos, 400.0 + 60.0 * sin), (400.0 + 80.0 * cos, 400.0 + 80.0 * sin));
assert!((recipe(&s, angular).offset - 80.0).abs() < 1e-6, "the arc's radius: {}", recipe(&s, angular).offset);
}
/// The Dimension tool takes a drag only from a dimension the canvas hits: one painted wider than
/// the reach is taken by its stroke, while one outside isolation mode, around an isolated part of
/// it, clipped away where the press is or drawn elsewhere by a geometry effect stays put. With
/// Real-time Drawing off the dimension being dragged is outlined.
#[test]
fn a_dimension_is_dragged_only_where_the_canvas_hits_it() {
use vectorcraft_engine::tools::Overlay;
let plain = ViewInfo::default();
let pt = vectorcraft_geom::Point::new;
let at_170 = (pt(100.0, 170.0), pt(200.0, 170.0));
let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| {
for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] {
s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap();
}
};
// A 30-point line: a press 13 points from its middle is on its stroke.
let (mut s, first) = level_start(plain);
run(&mut s, "dimension.update", json!({"ids":[first],"options":{"lineWeight":30}}));
drag(&mut s, (115.0, 183.0), (115.0, 143.0));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
// Outside the isolated group: not moved.
let (mut s, first) = level_start(plain);
let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":50,"width":50,"height":50}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids":[rect]}));
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
run(&mut s, "object.isolate", json!({"id": group}));
run(&mut s, "select.none", json!({}));
drag(&mut s, (150.0, 170.0), (150.0, 130.0));
assert_eq!(recipe(&s, first).line_ends(), at_170);
// In a clipping mask that leaves its right half out: not taken there, taken on its left half.
let (mut s, first) = level_start(plain);
let mask = run(&mut s, "shape.rectangle", json!({"x":90,"y":140,"width":50,"height":90}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids":[first, mask]}));
run(&mut s, "object.clippingMask.make", json!({}));
run(&mut s, "select.none", json!({}));
let count = s.doc().unwrap().doc.node_count();
drag(&mut s, (180.0, 170.0), (180.0, 130.0));
assert_eq!((recipe(&s, first).line_ends(), s.doc().unwrap().doc.node_count()), (at_170, count));
// That press picked a point, as a click there does: Escape drops it.
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
drag(&mut s, (120.0, 170.0), (120.0, 130.0));
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
// In a group whose Transform effect draws it 50 points lower: not taken where it is drawn.
let (mut s, first) = level_start(plain);
run(&mut s, "select.set", json!({"ids":[first]}));
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[group],"params":{"moveV":50}}));
run(&mut s, "select.none", json!({}));
drag(&mut s, (150.0, 220.0), (150.0, 260.0));
assert_eq!(recipe(&s, first).line_ends(), at_170);
// In Outline view the canvas draws no effects: taken where its recipe puts it.
s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap();
let outline = ViewInfo { outline: true, ..plain };
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] {
s.pointer(&PointerEvent::new(kind, 150.0, y), outline).unwrap();
}
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
// A Transform effect on its parts draws them 50 points lower: not taken where they are drawn.
let (mut s, first) = level_start(plain);
let parts: Vec<u64> = s.doc().unwrap().doc.node(NodeId(first)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect();
run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":parts,"params":{"moveV":50}}));
run(&mut s, "select.none", json!({}));
drag(&mut s, (150.0, 220.0), (150.0, 260.0));
assert_eq!(recipe(&s, first).line_ends(), at_170);
// With one of its parts isolated, the dimension around it is outside the editing scope.
let (mut s, first) = level_start(plain);
let part = {
let doc = &s.doc().unwrap().doc;
let parts = doc.node(NodeId(first)).unwrap().children().unwrap();
// The dimension line, which the press below lands on.
let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x0 < 150.0 && r.x1 > 150.0 && r.y0 < 171.0 && r.y1 > 169.0));
line.unwrap().id.0
};
run(&mut s, "object.isolate", json!({"id": part}));
run(&mut s, "select.none", json!({}));
drag(&mut s, (150.0, 170.0), (150.0, 130.0));
assert_eq!(recipe(&s, first).line_ends(), at_170);
// Real-time Drawing off: the dimension is outlined where the drag puts it, and other selected
// art, which the drag does not move, is not.
let (mut s, first) = level_start(plain);
let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":400,"width":50,"height":50}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids":[first, rect]}));
run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": false}));
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 110.0)] {
s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
}
let boxes: Vec<vectorcraft_geom::Rect> = s
.overlays(plain)
.into_iter()
.filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(&path)) } else { None })
.collect();
assert!(boxes.iter().any(|r| r.y0 < 111.0 && r.y1 > 109.0 && r.width() >= 99.0), "the dragged dimension is outlined at its new place");
assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}");
}
/// A geometry effect on a part of a dimension other than the one pressed keeps the Dimension tool
/// from dragging it, and the effect stays on that part.
#[test]
fn a_geometry_effect_on_another_part_keeps_the_dimension_in_place() {
let plain = ViewInfo::default();
let pt = vectorcraft_geom::Point::new;
let (mut s, first) = level_start(plain);
let extension = {
let doc = &s.doc().unwrap().doc;
let parts = doc.node(NodeId(first)).unwrap().children().unwrap();
// The extension line at x = 100, which the press below on the dimension line misses.
let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x1 < 101.0 && r.height() > 10.0));
line.unwrap().id.0
};
run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[extension],"params":{"moveH":-60}}));
run(&mut s, "select.none", json!({}));
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] {
s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
}
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
let kept = s.doc().unwrap().doc.node(NodeId(extension)).is_some_and(|n| !n.appearance.effects.is_empty());
assert!(kept, "the extension line keeps its effect");
}
/// In isolation mode, art outside the isolated group does not take a press on a dimension inside
/// it: the drag moves the dimension.
#[test]
fn art_outside_isolation_does_not_take_the_press_on_a_dimension() {
let plain = ViewInfo::default();
let pt = vectorcraft_geom::Point::new;
let (mut s, first) = level_start(plain);
// A line across the dimension line, outside the group isolated below. The press, a point below
// the dimension line, is nearer to it than to the dimension line.
run(&mut s, "path.create", json!({"d": "M150 100 L150 250"}));
run(&mut s, "select.set", json!({"ids":[first]}));
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
run(&mut s, "object.isolate", json!({"id": group}));
run(&mut s, "select.none", json!({}));
for (kind, y) in [(PointerKind::Move, 171.0), (PointerKind::Down, 171.0), (PointerKind::Drag, 131.0), (PointerKind::Up, 131.0)] {
s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
}
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
}
/// A dimension pasted into a document that had none is dragged with the Dimension tool like one
/// drawn there.
#[test]
fn a_dimension_pasted_into_another_document_is_dragged() {
let plain = ViewInfo::default();
let (mut s, first) = level_start(plain);
run(&mut s, "select.set", json!({"ids":[first]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 612, "height": 792}));
run(&mut s, "edit.paste", json!({}));
let pasted = s.doc().unwrap().selection.objects[0].0;
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let (a, b) = recipe(&s, pasted).line_ends();
let mid = a.midpoint(b);
for (kind, y) in [(PointerKind::Move, mid.y), (PointerKind::Down, mid.y), (PointerKind::Drag, mid.y - 40.0), (PointerKind::Up, mid.y - 40.0)] {
s.pointer(&PointerEvent::new(kind, mid.x, y), plain).unwrap();
}
let (a2, b2) = recipe(&s, pasted).line_ends();
assert!((a2.y - (a.y - 40.0)).abs() < 1e-6 && (b2.y - (b.y - 40.0)).abs() < 1e-6, "{:?} → {:?}", (a, b), (a2, b2));
}
/// A file that holds a dimension but was saved without the document's dimension flag (as one saved
/// after a dimension was pasted into a document that had none) opens with its dimension dragged
/// by the Dimension tool.
#[test]
fn a_dimension_in_a_file_saved_without_the_flag_is_dragged() {
let plain = ViewInfo::default();
let pt = vectorcraft_geom::Point::new;
let (s, first) = level_start(plain);
let mut doc = s.doc().unwrap().doc.as_ref().clone();
doc.dimensions = false;
let mut reopened = Session::new();
reopened.add_document(vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(), None);
reopened.select_tool("dimension", plain).unwrap();
for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] {
reopened.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap();
}
assert_eq!(recipe(&reopened, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0)));
}
/// A second dimension of the same two points as a dimension already drawn lands on its level too.
/// Off every level, a pointer moved in small steps while it is placed puts the line at each step,
/// with no pull from the preview of the dimension itself.
+128
View File
@@ -506,6 +506,134 @@ fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() {
refused(&mut s, &json!(outer));
}
/// In Safe Mode, a hidden plain instance draws nothing in the image a group's raster effect makes,
/// so its symbol art's plug-in effect doesn't stop Expand Appearance of the group; shown, it does.
#[test]
fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_image_leaves_out() {
let _f = fresh();
let mut s = Session::new();
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.hid", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.hid"})).unwrap();
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
let hide = |s: &mut Session, id: u64| {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(vectorcraft_engine::doc::NodeId(id)).unwrap().visible = false;
};
let expand = |s: &mut Session, group: u64| {
safe_mode::set_active(Some(safe_mode::Source::Flag));
let r = s.execute("effect.expandAppearance", &json!({"ids": [group]}));
safe_mode::set_active(None);
r
};
// A blurred group of a visible rectangle and an instance, then one of a visible rectangle and a
// group around an instance; the instance, or the group around it, is shown and then hidden.
for wrap in [false, true] {
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone();
let mut hidden = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone();
if wrap {
hidden = s.execute("object.group", &json!({"ids": [hidden]})).unwrap()["id"].clone();
}
let group = s.execute("object.group", &json!({"ids": [rect, hidden]})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap();
let (hidden, group) = (hidden.as_u64().unwrap(), group.as_u64().unwrap());
let err = expand(&mut s, group).unwrap_err().to_string();
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
hide(&mut s, hidden);
expand(&mut s, group).unwrap();
}
// Expansion still makes the image of a hidden blurred group, or of one in a hidden group, so
// a shown instance in it still stops it.
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 20})).unwrap()["id"].clone();
let blurred = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [blurred], "params": {"radius": 2}})).unwrap();
let parent = s.execute("object.group", &json!({"ids": [blurred]})).unwrap()["id"].as_u64().unwrap();
hide(&mut s, parent);
let err = expand(&mut s, parent).unwrap_err().to_string();
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
let blurred = blurred.as_u64().unwrap();
hide(&mut s, blurred);
let err = expand(&mut s, blurred).unwrap_err().to_string();
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
}
/// In Safe Mode, the image a layer's raster effect makes leaves out a template sublayer, so the symbol
/// art of a plain instance in it doesn't stop Expand Appearance of the layer; in a plain sublayer, it does.
#[test]
fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_layer_image_leaves_out() {
let _f = fresh();
let mut s = Session::new();
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.tpl", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.tpl"})).unwrap();
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setCurrent", &json!({"id": layer})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap();
let instance = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].as_u64().unwrap();
let sub = s.execute("layer.newSublayer", &json!({"parent": layer})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.move", &json!({"ids": [instance], "target": sub})).unwrap();
s.execute("layer.target", &json!({"id": layer})).unwrap();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [layer], "item": null, "params": {"radius": 2}})).unwrap();
let blurred = |s: &Session| s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(layer)).unwrap().appearance.effects.len();
assert_eq!(blurred(&s), 1, "the layer has its own Gaussian Blur");
let expand = |s: &mut Session| {
s.execute("layer.target", &json!({"id": layer})).unwrap();
safe_mode::set_active(Some(safe_mode::Source::Flag));
let r = s.execute("effect.expandAppearance", &json!({}));
safe_mode::set_active(None);
r
};
let err = expand(&mut s).unwrap_err().to_string();
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
s.execute("layer.setProps", &json!({"id": sub, "template": true})).unwrap();
expand(&mut s).unwrap();
}
/// In Safe Mode, a group whose Gaussian Blur makes it one image leaves out a hidden blurred group in
/// it, which makes no image of its own, so the symbol art of a plain instance there doesn't stop
/// Expand Appearance. Under a Drop Shadow, whose members expand on their own, the hidden group still
/// makes its image, so it does.
#[test]
fn expand_appearance_in_safe_mode_skips_a_hidden_blurred_group_that_a_blurred_group_image_leaves_out() {
let _f = fresh();
let mut s = Session::new();
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.nest", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.nest"})).unwrap();
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
let expand = |s: &mut Session, group: u64| {
safe_mode::set_active(Some(safe_mode::Source::Flag));
let r = s.execute("effect.expandAppearance", &json!({"ids": [group]}));
safe_mode::set_active(None);
r
};
for (outer, allowed) in [("blur.gaussian", true), ("stylize.dropShadow", false)] {
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone();
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone();
let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [inner], "params": {"radius": 2}})).unwrap();
let group = s.execute("object.group", &json!({"ids": [rect, inner]})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": outer, "ids": [group]})).unwrap();
let inner = vectorcraft_engine::doc::NodeId(inner.as_u64().unwrap());
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inner).unwrap().visible = false;
let r = expand(&mut s, group);
if allowed {
r.unwrap();
// The blurred group became its image: the hidden group in it was not expanded on its own.
assert!(s.doc().unwrap().doc.node(inner).is_none(), "the hidden group went into the image");
} else {
let err = r.unwrap_err().to_string();
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{outer}: {err}");
}
}
}
/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only
/// when an effect of the series group draws that art with the group.
#[test]
+2 -2
View File
@@ -662,7 +662,7 @@ impl<'a> Reader<'a> {
};
// The placeholder is all the document has of the file: what a missing link shows.
let bytes = Arc::new(png);
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() };
let key = linked_key(&blob, &path);
self.doc.images.entry(key.clone()).or_insert(blob);
self.warn(LINKED_PLACEHOLDERS);
@@ -905,7 +905,7 @@ impl<'a> Reader<'a> {
}
// The preview is all the document has of the file: what a missing link shows.
let bytes = Arc::new(png);
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() };
let key = linked_key(&blob, &path);
let fresh = !self.doc.images.contains_key(&key);
self.doc.images.entry(key.clone()).or_insert(blob);
+6 -1
View File
@@ -586,7 +586,7 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize
let mut doc = f.document;
for (k, img) in f.images {
let bytes = bytes_of(&img).ok_or_else(|| FormatError::BadImage(k.clone()))?;
let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None };
let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if img.proxy {
blob.proxy = Some(blob.bytes.clone());
@@ -637,6 +637,11 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize
// Untrusted: the type's sizes, leading, baseline shifts and scales, its indents and paragraph
// spacing, and its tab stops, each within its range (after the depth limit: the walk recurses).
doc.keep_type_values_in_range();
// Untrusted, and unset in a file saved after a dimension was pasted into a document that had
// none: the flag is set when some object is a dimension (after the depth limit too).
let mut dimensions = false;
doc.walk(|n| dimensions |= n.extras().dimension.is_some());
doc.dimensions = dimensions;
// Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too).
doc.fix_ruby();
// Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite).
+3 -1
View File
@@ -57,7 +57,9 @@ fn include_linked_files_keeps_the_files_bytes() {
// Only the preview loaded (the file was never found): the preview is all there is to write.
let mut missing = linked_doc();
let preview = Arc::new(vec![9, 9]);
missing.images.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
missing
.images
.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let out = save_with(&missing, &SaveOptions { include_linked: true, ..SaveOptions::default() }).unwrap();
assert_eq!(json_of(&out)["images"]["k"]["proxy"], true);
}
+3 -2
View File
@@ -3,19 +3,20 @@ name = "vectorcraft-metafile"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
[lints]
workspace = true
[dependencies]
craft-codepage = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
vectorcraft-effects = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-text = { workspace = true }
craft-metafile = { workspace = true }
craft-metafile = { workspace = true, features = ["write"] }
kurbo = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
+1 -15
View File
@@ -1,4 +1,4 @@
//! Little-endian values: the buffer both writers build records in.
//! Little-endian values for hand-built import fixtures.
/// Bytes being written.
#[derive(Default)]
@@ -20,9 +20,6 @@ impl Out {
pub fn i32(&mut self, v: i32) {
self.0.extend_from_slice(&v.to_le_bytes());
}
pub fn f32(&mut self, v: f32) {
self.0.extend_from_slice(&v.to_le_bytes());
}
pub fn bytes(&mut self, b: &[u8]) {
self.0.extend_from_slice(b);
}
@@ -32,15 +29,4 @@ impl Out {
self.0.push(0);
}
}
/// Overwrite the `u32` at `at` (a size or count known only later).
pub fn set_u32(&mut self, at: usize, v: u32) {
if let Some(b) = self.0.get_mut(at..at + 4) {
b.copy_from_slice(&v.to_le_bytes());
}
}
pub fn set_i32(&mut self, at: usize, v: i32) {
if let Some(b) = self.0.get_mut(at..at + 4) {
b.copy_from_slice(&v.to_le_bytes());
}
}
}
+45 -93
View File
@@ -1,6 +1,6 @@
//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source).
//! App bitmap sizing, read budgets, and raster conversion for imported pictures.
use craft_metafile::write::Image;
use vectorcraft_doc::resample::{Resample, resized};
/// Most pixels along a side of an image the writers store (larger ones are scaled down).
@@ -16,8 +16,6 @@ pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28;
/// What [`charge`] says of a bitmap past what is left of the file's budget.
pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may";
const BI_RGB: u32 = 0;
/// Pixels with straight (not premultiplied) alpha, row by row from the top.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Rgba {
@@ -26,30 +24,25 @@ pub(crate) struct Rgba {
pub pixels: Vec<u8>,
}
/// `img`, scaled down to what a metafile stores when it is larger.
pub(crate) fn fitted(img: image::RgbaImage) -> Image {
let (w, h) = img.dimensions();
let side = f64::from(w.max(h)) / f64::from(MAX_SIDE);
let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64;
let k = side.max(area.sqrt());
let img = if k > 1.0 {
let nw = ((f64::from(w) / k).floor() as u32).max(1);
let nh = ((f64::from(h) / k).floor() as u32).max(1);
let how = Resample::Filter(image::imageops::FilterType::Triangle);
resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8()
} else {
img
};
let (width, height) = img.dimensions();
Image { width, height, rgba: img.into_raw() }
}
impl Rgba {
/// `img`, scaled down to what a metafile stores when it is larger.
pub fn fitted(img: image::RgbaImage) -> Self {
let (w, h) = img.dimensions();
let side = f64::from(w.max(h)) / f64::from(MAX_SIDE);
let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64;
let k = side.max(area.sqrt());
let img = if k > 1.0 {
let nw = ((f64::from(w) / k).floor() as u32).max(1);
let nh = ((f64::from(h) / k).floor() as u32).max(1);
let how = Resample::Filter(image::imageops::FilterType::Triangle);
resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8()
} else {
img
};
let (width, height) = img.dimensions();
Self { width, height, pixels: img.into_raw() }
}
/// Every pixel fully opaque?
pub fn opaque(&self) -> bool {
self.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)
}
/// As PNG bytes.
pub fn to_png(&self) -> Result<Vec<u8>, String> {
let img = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.pixels.clone())
@@ -58,63 +51,6 @@ impl Rgba {
}
}
/// A BITMAPINFOHEADER of a bottom-up, uncompressed `width` × `height` bitmap of `bits` per pixel.
fn header(width: u32, height: u32, bits: u16, size: usize) -> Vec<u8> {
let mut h = crate::bytes::Out::default();
h.u32(40);
h.i32(i32::try_from(width).unwrap_or(i32::MAX));
h.i32(i32::try_from(height).unwrap_or(i32::MAX));
h.u16(1);
h.u16(bits);
h.u32(BI_RGB);
h.u32(u32::try_from(size).unwrap_or(0));
// 2835 pixels a metre: 72 ppi (the size on the page comes from the record).
h.i32(2835);
h.i32(2835);
h.u32(0);
h.u32(0);
h.0
}
/// The bytes of a row of `width` pixels of `bits` each, padded to 4 bytes.
fn stride(width: u32, bits: u32) -> Option<usize> {
let row_bits = u64::from(width).checked_mul(u64::from(bits))?;
usize::try_from(row_bits.div_ceil(32) * 4).ok()
}
/// `img` at `opacity`, composited over white, as a 24-bit DIB → (header, bits).
pub(crate) fn rgb24(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
let row = stride(img.width, 24).unwrap_or(0);
let mut bits = vec![0u8; row * img.height as usize];
let over = |c: u8, a: u32| ((u32::from(c) * a + 255 * (255 - a) + 127) / 255) as u8;
for (y, src) in img.pixels.chunks_exact((img.width as usize * 4).max(1)).enumerate() {
// Bottom-up: the first stored row is the image's last.
let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue };
let Some(dst) = bits.get_mut(at..at + img.width as usize * 3) else { continue };
for (d, p) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<4>().0) {
let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32;
d.copy_from_slice(&[over(p[2], a), over(p[1], a), over(p[0], a)]);
}
}
(header(img.width, img.height, 24, bits.len()), bits)
}
/// `img` at `opacity` as a 32-bit DIB of premultiplied BGRA → (header, bits).
pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
let row = img.width as usize * 4;
let mut bits = vec![0u8; row * img.height as usize];
for (y, src) in img.pixels.chunks_exact(row.max(1)).enumerate() {
let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue };
let Some(dst) = bits.get_mut(at..at + row) else { continue };
for (d, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) {
let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32;
let pre = |c: u8| ((u32::from(c) * a + 127) / 255) as u8;
d.copy_from_slice(&[pre(p[2]), pre(p[1]), pre(p[0]), a as u8]);
}
}
(header(img.width, img.height, 32, bits.len()), bits)
}
/// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded.
pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
let n = u64::from(w) * u64::from(h);
@@ -126,10 +62,10 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
mod tests {
use super::*;
fn sample() -> Rgba {
fn sample() -> Image {
// 3 × 2: red, green, blue / half-transparent black, transparent, white.
let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255];
Rgba { width: 3, height: 2, pixels }
Image { width: 3, height: 2, rgba: pixels }
}
#[test]
@@ -144,7 +80,14 @@ mod tests {
#[test]
fn rgb24_is_bottom_up_bgr_over_white() {
let (bmi, bits) = rgb24(&sample(), 1.0);
// WMF's shared writer emits a StretchDIB record: 28 bytes of parameters and
// record framing precede BITMAPINFOHEADER, then the bottom-up rows.
let image = std::sync::Arc::new(sample());
let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity: 1.0 };
let bytes = craft_metafile::write::wmf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0)).unwrap().bytes;
let records = crate::tests::wmf_records(&bytes);
let (_, record) = records.iter().find(|(kind, _)| *kind == 0x0f43).unwrap();
let (bmi, bits) = (&record[28..68], &record[68..]);
assert_eq!(bmi.len(), 40);
assert_eq!(&bmi[14..16], &[24, 0], "24 bits a pixel");
// Rows of 9 bytes padded to 12, the last row first: half-transparent black over white is
@@ -154,19 +97,28 @@ mod tests {
#[test]
fn bgra32_is_premultiplied() {
let (bmi, bits) = bgra32(&sample(), 1.0);
assert_eq!(&bmi[14..16], &[32, 0]);
let pixels = |opacity| {
let image = std::sync::Arc::new(sample());
let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity };
let bytes = craft_metafile::write::emf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0), "VectorCraft", "").unwrap();
let records = crate::tests::emf_records(&bytes);
let (_, record) = records.iter().find(|(kind, _)| *kind == 114).unwrap();
let (bmi, bits) = (&record[108..148], &record[148..]);
assert_eq!(&bmi[14..16], &[32, 0]);
bits.to_vec()
};
let bits = pixels(1.0);
assert_eq!(&bits[..12], &[0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]);
assert_eq!(&bits[12..16], &[0, 0, 255, 255], "red, as BGRA");
// At half opacity.
let (_, half) = bgra32(&sample(), 0.5);
let half = pixels(0.5);
assert_eq!(&half[12..16], &[0, 0, 128, 128]);
}
#[test]
fn large_images_are_scaled_to_fit() {
let img = image::RgbaImage::new(MAX_SIDE * 2, 4);
let f = Rgba::fitted(img);
let f = fitted(img);
assert_eq!((f.width, f.height), (MAX_SIDE, 2));
}
@@ -176,10 +128,10 @@ mod tests {
fn large_images_keep_their_color_beside_clear_pixels() {
let img =
image::RgbaImage::from_fn(MAX_SIDE * 2, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) });
let f = Rgba::fitted(img);
let f = fitted(img);
assert_eq!((f.width, f.height), (MAX_SIDE, 2));
let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8;
for p in f.pixels.as_chunks::<4>().0 {
for p in f.rgba.as_chunks::<4>().0 {
assert!(p[3] > 0 && [200, 30, 30].iter().zip(p).all(|(&want, &c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}");
}
}
-503
View File
@@ -1,503 +0,0 @@
//! The EMF writer: an EMR_HEADER whose frame is the region in 0.01 mm, then the drawing in device
//! units of 0.01 mm (the reference device has 100 pixels a millimetre) and an EMR_EOF.
//!
//! Each fill and stroke is a path bracket (move-to, poly-line-to and poly-Bézier-to runs, close
//! figure) filled with a solid brush or stroked with a geometric pen; brushes and pens are made
//! when the colour or pen changes and deleted when replaced. Clips are path clips inside a saved
//! DC; images are StretchDIBits (opaque) or AlphaBlend (with transparency) under a world transform
//! that places their pixels.
use kurbo::PathEl;
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect};
use crate::bytes::Out;
use crate::dib::{self, Rgba};
use crate::scene::{Op, Pen};
// Record types (MS-EMF 2.1.1).
pub(crate) const HEADER: u32 = 1;
pub(crate) const POLYBEZIERTO: u32 = 5;
pub(crate) const POLYLINETO: u32 = 6;
pub(crate) const EOF: u32 = 14;
pub(crate) const SETBKMODE: u32 = 18;
pub(crate) const SETPOLYFILLMODE: u32 = 19;
pub(crate) const MOVETOEX: u32 = 27;
pub(crate) const SAVEDC: u32 = 33;
pub(crate) const RESTOREDC: u32 = 34;
pub(crate) const SETWORLDTRANSFORM: u32 = 35;
pub(crate) const MODIFYWORLDTRANSFORM: u32 = 36;
pub(crate) const SELECTOBJECT: u32 = 37;
pub(crate) const CREATEBRUSHINDIRECT: u32 = 39;
pub(crate) const DELETEOBJECT: u32 = 40;
pub(crate) const SETMITERLIMIT: u32 = 58;
pub(crate) const BEGINPATH: u32 = 59;
pub(crate) const ENDPATH: u32 = 60;
pub(crate) const CLOSEFIGURE: u32 = 61;
pub(crate) const FILLPATH: u32 = 62;
pub(crate) const STROKEPATH: u32 = 64;
pub(crate) const SELECTCLIPPATH: u32 = 67;
pub(crate) const STRETCHDIBITS: u32 = 81;
pub(crate) const EXTCREATEPEN: u32 = 95;
pub(crate) const ALPHABLEND: u32 = 114;
/// The `" EMF"` signature in the header.
pub(crate) const SIGNATURE: u32 = 0x464D_4520;
/// Stock objects (selected to release ours before deleting them).
const WHITE_BRUSH: u32 = 0x8000_0000;
const NULL_PEN: u32 = 0x8000_0008;
/// Our two object slots (0 is reserved).
const BRUSH: u32 = 1;
const PEN: u32 = 2;
pub(crate) const PS_GEOMETRIC: u32 = 0x0001_0000;
pub(crate) const PS_USERSTYLE: u32 = 7;
pub(crate) const PS_ENDCAP_SQUARE: u32 = 0x100;
pub(crate) const PS_ENDCAP_FLAT: u32 = 0x200;
pub(crate) const PS_JOIN_BEVEL: u32 = 0x1000;
pub(crate) const PS_JOIN_MITER: u32 = 0x2000;
/// Raster operation: copy the source.
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
/// Device units (0.01 mm) per point.
pub(crate) const UNITS_PER_PT: f64 = 2540.0 / 72.0;
/// Longest dash pattern a geometric pen takes (longer ones are drawn as separate dashes).
const MAX_STYLE: usize = 16;
/// Header size with both extensions.
const HEADER_SIZE: usize = 108;
/// Coordinates are kept within this (far beyond any page).
const MAX_COORD: f64 = 1e9;
/// Does `bytes` start with an EMF header?
pub(crate) fn is_emf(bytes: &[u8]) -> bool {
let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
u32_at(0) == Some(HEADER) && u32_at(40) == Some(SIGNATURE)
}
/// A COLORREF (0x00bbggrr).
pub(crate) fn colorref(rgb: [u8; 3]) -> u32 {
u32::from_le_bytes([rgb[0], rgb[1], rgb[2], 0])
}
/// What a pen object is made of, to tell when the next stroke needs another.
#[derive(Clone, PartialEq)]
struct PenKey {
style: u32,
width: u32,
color: u32,
entries: Vec<u32>,
}
/// A device-space bounding box (inclusive).
type Bounds = [i32; 4];
fn union(a: Option<Bounds>, b: Bounds) -> Bounds {
match a {
None => b,
Some(a) => [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])],
}
}
struct Writer {
out: Out,
records: u32,
/// Document → device units.
to_dev: Affine,
/// The frame in device units: what the region clip lets through.
frame: Bounds,
/// Everything drawn, in device units.
bounds: Option<Bounds>,
brush: Option<u32>,
pen: Option<PenKey>,
fill_mode: Option<u32>,
miter: Option<u32>,
}
/// Write `ops` as an EMF of `region` (document space), described as `title`.
pub(crate) fn write(ops: &[Op], region: Rect, title: &str) -> Vec<u8> {
let k = UNITS_PER_PT;
let frame = [0, 0, (region.width() * k).round() as i32, (region.height() * k).round() as i32];
let mut w = Writer {
out: Out::default(),
records: 0,
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
frame,
bounds: None,
brush: None,
pen: None,
fill_mode: None,
miter: None,
};
w.header(title);
// Dash gaps and hatches show what is below.
w.record(SETBKMODE, |o| o.u32(1));
for op in ops {
w.op(op);
}
w.release();
w.record(EOF, |o| {
o.u32(0);
o.u32(16);
o.u32(20);
});
w.finish()
}
impl Writer {
/// Append one record: its type, size and `body`, padded to 4 bytes.
fn record(&mut self, kind: u32, body: impl FnOnce(&mut Out)) {
let start = self.out.len();
self.out.u32(kind);
self.out.u32(0);
body(&mut self.out);
self.out.pad(4);
let size = u32::try_from(self.out.len() - start).unwrap_or(u32::MAX);
self.out.set_u32(start + 4, size);
self.records += 1;
}
fn header(&mut self, title: &str) {
let desc: Vec<u16> =
"VectorCraft".encode_utf16().chain([0]).chain(title.chars().take(200).collect::<String>().encode_utf16()).chain([0, 0]).collect();
let f = self.frame;
// The reference device: 100 pixels a millimetre, as large as the frame.
let mm = [(f[2] / 100).max(1) + 1, (f[3] / 100).max(1) + 1];
self.record(HEADER, |o| {
// Bounds, patched in `finish`.
o.bytes(&[0; 16]);
for v in f {
o.i32(v);
}
o.u32(SIGNATURE);
o.u32(0x0001_0000);
// Bytes, records and handles, patched in `finish`.
o.u32(0);
o.u32(0);
o.u16(3);
o.u16(0);
o.u32(desc.len() as u32);
o.u32(HEADER_SIZE as u32);
o.u32(0);
o.i32(mm[0] * 100);
o.i32(mm[1] * 100);
o.i32(mm[0]);
o.i32(mm[1]);
// No pixel format, not OpenGL; the device in micrometres.
o.u32(0);
o.u32(0);
o.u32(0);
o.u32(mm[0] as u32 * 1000);
o.u32(mm[1] as u32 * 1000);
for c in &desc {
o.u16(*c);
}
});
}
/// Patch the header's bounds, size and record count.
fn finish(mut self) -> Vec<u8> {
let b = self.bounds.map(|b| [b[0].max(self.frame[0]), b[1].max(self.frame[1]), b[2].min(self.frame[2]), b[3].min(self.frame[3])]);
// An empty picture has bounds (0, 0, -1, -1).
let b = b.filter(|b| b[0] <= b[2] && b[1] <= b[3]).unwrap_or([0, 0, -1, -1]);
for (i, v) in b.iter().enumerate() {
self.out.set_i32(8 + 4 * i, *v);
}
let size = u32::try_from(self.out.len()).unwrap_or(u32::MAX);
self.out.set_u32(48, size);
self.out.set_u32(52, self.records);
self.out.0
}
fn dev(&self, p: Point) -> [i32; 2] {
let q = self.to_dev * p;
let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_COORD, MAX_COORD) as i32 } else { 0 };
[c(q.x), c(q.y)]
}
fn grow(&mut self, b: Bounds) {
self.bounds = Some(union(self.bounds, b));
}
fn op(&mut self, op: &Op) {
match op {
Op::Fill { path, rule, rgb } => {
self.fill_mode(*rule);
self.brush(*rgb);
if let Some(b) = self.path(path) {
self.grow(b);
self.record(FILLPATH, |o| b.iter().for_each(|v| o.i32(*v)));
}
}
Op::Stroke { path, pen } => {
let dashed;
let path = if self.pen(pen) {
path
} else {
dashed = crate::scene::dashed(path, pen.dash.as_ref());
&dashed
};
if let Some(b) = self.path(path) {
let half = (pen.width * UNITS_PER_PT / 2.0).ceil() as i32;
let b = [b[0] - half, b[1] - half, b[2] + half, b[3] + half];
self.grow(b);
self.record(STROKEPATH, |o| b.iter().for_each(|v| o.i32(*v)));
}
}
Op::Image { image, xf, opacity } => self.image(image, *xf, *opacity),
Op::Clip { path, rule } => {
self.release();
self.record(SAVEDC, |_| {});
self.fill_mode(*rule);
if self.path(path).is_some() {
// RGN_AND: inside the clip already set.
self.record(SELECTCLIPPATH, |o| o.u32(1));
}
}
Op::Unclip => {
self.release();
self.record(RESTOREDC, |o| o.i32(-1));
// The DC's fill mode and miter limit are back to what they were at the save.
self.fill_mode = None;
self.miter = None;
}
}
}
fn fill_mode(&mut self, rule: FillRule) {
// ALTERNATE (even-odd) or WINDING (non-zero).
let mode = if rule == FillRule::EvenOdd { 1 } else { 2 };
if self.fill_mode != Some(mode) {
self.record(SETPOLYFILLMODE, |o| o.u32(mode));
self.fill_mode = Some(mode);
}
}
/// Select a solid brush of `rgb`, made when the colour changes.
fn brush(&mut self, rgb: [u8; 3]) {
let color = colorref(rgb);
if self.brush == Some(color) {
return;
}
self.drop_brush();
self.record(CREATEBRUSHINDIRECT, |o| {
o.u32(BRUSH);
// BS_SOLID, the colour, no hatch.
o.u32(0);
o.u32(color);
o.u32(0);
});
self.record(SELECTOBJECT, |o| o.u32(BRUSH));
self.brush = Some(color);
}
fn drop_brush(&mut self) {
if self.brush.take().is_some() {
self.record(SELECTOBJECT, |o| o.u32(WHITE_BRUSH));
self.record(DELETEOBJECT, |o| o.u32(BRUSH));
}
}
fn drop_pen(&mut self) {
if self.pen.take().is_some() {
self.record(SELECTOBJECT, |o| o.u32(NULL_PEN));
self.record(DELETEOBJECT, |o| o.u32(PEN));
}
}
/// Release our objects (before a DC is saved or restored, which would bring back deleted ones).
fn release(&mut self) {
self.drop_brush();
self.drop_pen();
}
/// Select a geometric pen for `p`, made when it changes. False when `p`'s dashes must be
/// drawn as separate lines (the pen selected is solid): a pen's dashes start at the path's
/// start, every entry at least a unit long, 16 entries at most.
fn pen(&mut self, p: &Pen) -> bool {
let k = UNITS_PER_PT;
let entries: Option<Vec<u32>> = p.dash.as_ref().map(|d| {
let mut v: Vec<f64> = d.pattern.clone();
if v.len() % 2 == 1 {
v.extend_from_within(..);
}
v.iter().map(|x| (x * k).round().clamp(0.0, f64::from(u32::MAX)) as u32).collect()
});
let native = match (&entries, &p.dash) {
(Some(e), Some(d)) => d.offset.abs() < 1e-9 && e.len() <= MAX_STYLE && e.iter().all(|x| *x >= 1),
_ => true,
};
let entries = if native { entries.unwrap_or_default() } else { vec![] };
let cap = match p.cap {
LineCap::Butt => PS_ENDCAP_FLAT,
LineCap::Round => 0,
LineCap::Square => PS_ENDCAP_SQUARE,
};
let join = match p.join {
LineJoin::Miter => PS_JOIN_MITER,
LineJoin::Round => 0,
LineJoin::Bevel => PS_JOIN_BEVEL,
};
let style = PS_GEOMETRIC | cap | join | if entries.is_empty() { 0 } else { PS_USERSTYLE };
let key = PenKey { style, width: (p.width * k).round().clamp(1.0, 1e9) as u32, color: colorref(p.rgb), entries };
if p.join == LineJoin::Miter {
let m = p.miter.round().clamp(1.0, 1000.0) as u32;
if self.miter != Some(m) {
self.record(SETMITERLIMIT, |o| o.u32(m));
self.miter = Some(m);
}
}
if self.pen.as_ref() != Some(&key) {
self.drop_pen();
let n = key.entries.len() as u32;
self.record(EXTCREATEPEN, |o| {
o.u32(PEN);
// No pattern bitmap: its offsets point past the record, its sizes are 0.
let end = 52 + 4 * n;
o.u32(end);
o.u32(0);
o.u32(end);
o.u32(0);
o.u32(key.style);
o.u32(key.width);
// BS_SOLID, the colour, no hatch.
o.u32(0);
o.u32(key.color);
o.u32(0);
o.u32(n);
key.entries.iter().for_each(|e| o.u32(*e));
});
self.record(SELECTOBJECT, |o| o.u32(PEN));
self.pen = Some(key);
}
native
}
/// `bp` as a path bracket → its device bounds (`None`: nothing to draw).
fn path(&mut self, bp: &BezPath) -> Option<Bounds> {
if !bp.elements().iter().any(|e| !matches!(e, PathEl::MoveTo(_) | PathEl::ClosePath)) {
return None;
}
self.record(BEGINPATH, |_| {});
let mut bounds: Option<Bounds> = None;
let mut run: Vec<[i32; 2]> = vec![];
let mut curves = false;
let mut last = Point::ZERO;
let mut start = Point::ZERO;
for el in bp.elements() {
let (pts, is_curve): (Vec<Point>, bool) = match *el {
PathEl::MoveTo(p) => {
self.flush_run(&mut run, curves);
let d = self.dev(p);
bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]]));
self.record(MOVETOEX, |o| d.iter().for_each(|v| o.i32(*v)));
(last, start) = (p, p);
continue;
}
PathEl::ClosePath => {
self.flush_run(&mut run, curves);
self.record(CLOSEFIGURE, |_| {});
last = start;
continue;
}
PathEl::LineTo(p) => (vec![p], false),
PathEl::QuadTo(c, p) => (vec![last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0), p], true),
PathEl::CurveTo(a, b, p) => (vec![a, b, p], true),
};
if is_curve != curves {
self.flush_run(&mut run, curves);
curves = is_curve;
}
for p in &pts {
let d = self.dev(*p);
bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]]));
run.push(d);
}
last = pts.last().copied().unwrap_or(last);
}
self.flush_run(&mut run, curves);
self.record(ENDPATH, |_| {});
bounds
}
/// Write the points of a run of lines or curves, then empty it.
fn flush_run(&mut self, run: &mut Vec<[i32; 2]>, curves: bool) {
if run.is_empty() {
return;
}
let pts = std::mem::take(run);
let b = pts.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]);
self.record(if curves { POLYBEZIERTO } else { POLYLINETO }, |o| {
b.iter().for_each(|v| o.i32(*v));
o.u32(pts.len() as u32);
for p in &pts {
o.i32(p[0]);
o.i32(p[1]);
}
});
}
/// An image placed by `xf` (its pixels → document): StretchDIBits when opaque, else AlphaBlend,
/// drawn at its pixel size under a world transform.
fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) {
if img.width == 0 || img.height == 0 || opacity <= 0.0 {
return;
}
let m = self.to_dev * xf;
if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 {
return;
}
let (w, h) = (f64::from(img.width), f64::from(img.height));
let corners = [Point::ZERO, Point::new(w, 0.0), Point::new(0.0, h), Point::new(w, h)].map(|p| self.dev(xf * p));
let b = corners.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]);
self.grow(b);
let [a, bb, c, d, e, f] = m.as_coeffs();
self.record(SETWORLDTRANSFORM, |o| [a, bb, c, d, e, f].iter().for_each(|v| o.f32(*v as f32)));
let (iw, ih) = (img.width as i32, img.height as i32);
if img.opaque() && opacity >= 0.998 {
let (bmi, bits) = dib::rgb24(img, 1.0);
self.record(STRETCHDIBITS, |o| {
b.iter().for_each(|v| o.i32(*v));
// Destination and source rectangles.
[0, 0, 0, 0, iw, ih].iter().for_each(|v| o.i32(*v));
o.u32(80);
o.u32(bmi.len() as u32);
o.u32(80 + bmi.len() as u32);
o.u32(bits.len() as u32);
// DIB_RGB_COLORS, SRCCOPY, the destination size.
o.u32(0);
o.u32(SRCCOPY);
o.i32(iw);
o.i32(ih);
o.bytes(&bmi);
o.bytes(&bits);
});
} else {
let (bmi, bits) = dib::bgra32(img, opacity);
self.record(ALPHABLEND, |o| {
b.iter().for_each(|v| o.i32(*v));
[0, 0, iw, ih].iter().for_each(|v| o.i32(*v));
// AC_SRC_OVER, no flags, constant alpha 255, AC_SRC_ALPHA (per-pixel alpha).
o.bytes(&[0, 0, 255, 1]);
o.i32(0);
o.i32(0);
// The source's own transform: identity.
[1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v));
o.u32(0);
o.u32(0);
o.u32(108);
o.u32(bmi.len() as u32);
o.u32(108 + bmi.len() as u32);
o.u32(bits.len() as u32);
o.i32(iw);
o.i32(ih);
o.bytes(&bmi);
o.bytes(&bits);
});
}
// MWT_IDENTITY: back to drawing in device units.
self.record(MODIFYWORLDTRANSFORM, |o| {
[1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v));
o.u32(1);
});
}
}
+94
View File
@@ -0,0 +1,94 @@
//! Translate VectorCraft's drawing operations to the shared metafile writers.
use craft_metafile::{
Cap, Join,
write::{self, Dash, Op, Pen},
};
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{FillRule, Rect};
use crate::{Kind, scene};
pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str, warnings: &mut Vec<String>) -> Result<Vec<u8>, String> {
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
let invalid = || "the export region is empty".to_string();
match kind {
Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid),
Kind::Wmf => {
let out = write::wmf(&ops, region).ok_or_else(invalid)?;
for (lost, warning) in [
(out.translucent_images, "WMF has no transparency: images are written over white"),
(out.turned_images, "WMF can't rotate or skew images: they are written upright, filling their bounds"),
(out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"),
(out.oversized_images, "WMF images with a side over 32,767 pixels were left out"),
] {
if lost && !warnings.iter().any(|w| w == warning) {
warnings.push(warning.to_string());
}
}
Ok(out.bytes)
}
}
}
fn convert(op: scene::Op, kind: Kind) -> Op {
match op {
scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb },
scene::Op::Stroke { mut path, pen } => {
let dash = pen.dash.and_then(|dash| {
let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset };
if kind == Kind::Emf && native.emf_pen_draws() {
Some(native)
} else {
// Keep VectorCraft's own dash placement for strokes that cannot use an
// EMF native pen, including adjusted dashes around corners in WMF.
if let Some(dashed) = vectorcraft_effects::stroke::dash(&path, &dash) {
path = dashed.path;
}
None
}
});
let cap = match pen.cap {
LineCap::Butt => Cap::Flat,
LineCap::Round => Cap::Round,
LineCap::Square => Cap::Square,
};
let join = match pen.join {
LineJoin::Miter => Join::Miter,
LineJoin::Round => Join::Round,
LineJoin::Bevel => Join::Bevel,
};
Op::Stroke { path, pen: Pen { rgb: pen.rgb, width: pen.width, cap, join, miter: pen.miter, dash } }
}
scene::Op::Image { image, xf, opacity } => Op::Image { image, xf, opacity },
scene::Op::Clip { path, rule } => Op::Clip { path, even_odd: rule == FillRule::EvenOdd },
scene::Op::Unclip => Op::Unclip,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nonnative_metafile_pens_keep_vectorcraft_corner_alignment() {
let mut path = kurbo::BezPath::new();
path.move_to((7.0, 8.0));
path.line_to((42.0, 8.0));
path.line_to((42.0, 45.0));
path.line_to((7.0, 45.0));
path.close_path();
let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true };
let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None };
let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() };
let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path;
let region = Rect::new(0.0, 0.0, 50.0, 50.0);
for kind in [Kind::Emf, Kind::Wmf] {
let actual = write(vec![scene::Op::Stroke { path: path.clone(), pen: with_dash.clone() }], region, kind, "", &mut Vec::new()).unwrap();
let already_dashed =
write(vec![scene::Op::Stroke { path: segments.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap();
let unsplit = write(vec![scene::Op::Stroke { path: path.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap();
assert_eq!(actual, already_dashed, "the wire writer must receive the app-aligned segments: {kind:?}");
assert_ne!(actual, unsplit, "the fixture must distinguish a lost dash pattern: {kind:?}");
}
}
}
+1 -14
View File
@@ -206,20 +206,7 @@ fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] {
/// Byte `b` of Mac Roman.
fn mac_roman(b: u8) -> char {
const HIGH: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', //
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', //
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', //
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', //
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', //
'\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
match b {
0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
_ => char::from(b),
}
craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b)
}
/// The family name of a classic Macintosh font number.
+8 -42
View File
@@ -44,9 +44,11 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect,
use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane};
use crate::dib::Rgba;
use crate::wmf::PLACEABLE_KEY;
use crate::{Imported, Kind};
// The placeable header is interpreted here for VectorCraft’s logical-unit policy.
const PLACEABLE_KEY: u32 = 0x9AC6_CDD7;
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
const TOO_MANY: &str = "objects past the most one file may hold were left out";
@@ -1162,46 +1164,6 @@ fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) ->
Some(out)
}
/// Does the file stop before its end-of-file record?
fn ends_early(bytes: &[u8], kind: Kind) -> bool {
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let mut at = match kind {
Kind::Emf => 0,
Kind::Wmf => {
let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 };
let Some(words) = u16_at(start + 2) else { return true };
start + usize::from(words) * 2
}
};
loop {
let size = match kind {
Kind::Emf => {
let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true };
if kind == 14 {
return false;
}
// Records are a multiple of 4 bytes long; reading stops at one that isn't.
if !size.is_multiple_of(4) {
return true;
}
size as usize
}
Kind::Wmf => {
let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true };
if function == 0 {
return false;
}
(words as usize).saturating_mul(2)
}
};
if size < 6 {
return true;
}
at = at.saturating_add(size);
}
}
/// Read an EMF or WMF file.
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
@@ -1212,7 +1174,11 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
})?;
let k = unit(bytes, kind);
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k);
if ends_early(bytes, kind) {
let wire_kind = match kind {
Kind::Emf => craft_metafile::Kind::Emf,
Kind::Wmf => craft_metafile::Kind::Wmf,
};
if craft_metafile::ends_early(bytes, wire_kind) {
m.warn(ENDS_EARLY);
}
if pic.truncated {
+10 -22
View File
@@ -22,18 +22,14 @@
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
//! document.
//!
//! - `bytes`: little-endian writing.
//! - `dib`: device-independent bitmaps for the writers.
//! - `scene`: the document walk both writers share.
//! - `emf`, `wmf`: the writers.
//! - `import`: the readers.
//! The app walks its document and maps its drawing operations to the shared writers.
#[cfg(test)]
mod bytes;
mod dib;
mod emf;
mod encode;
mod import;
mod scene;
mod wmf;
use vectorcraft_doc::Document;
use vectorcraft_geom::Rect;
@@ -59,13 +55,10 @@ impl Kind {
/// The metafile format `bytes` start like, if any.
pub fn sniff(bytes: &[u8]) -> Option<Kind> {
if emf::is_emf(bytes) {
Some(Kind::Emf)
} else if wmf::is_wmf(bytes) {
Some(Kind::Wmf)
} else {
None
}
craft_metafile::sniff(bytes).map(|kind| match kind {
craft_metafile::Kind::Emf => Kind::Emf,
craft_metafile::Kind::Wmf => Kind::Wmf,
})
}
/// A written metafile.
@@ -109,18 +102,13 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Ve
let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false };
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers);
let doc = baked.as_ref().unwrap_or(doc);
let outputs = regions
regions
.into_iter()
.map(|r| {
let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run();
let bytes = match kind {
Kind::Emf => emf::write(&ops, r, doc.info_title()),
Kind::Wmf => wmf::write(&ops, r, &mut warnings),
};
Output { bytes, warnings }
encode::write(ops, r, kind, doc.info_title(), &mut warnings).map(|bytes| Output { bytes, warnings })
})
.collect();
Ok(outputs)
.collect()
}
/// A metafile read into a document.
+9 -14
View File
@@ -14,7 +14,7 @@ use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, LineCap, Line
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape};
use crate::dib::Rgba;
use craft_metafile::write::Image;
/// How deep symbols, brush art and pattern tiles may nest in one another (deeper art is left out).
const MAX_NEST: u32 = 8;
@@ -73,7 +73,7 @@ pub(crate) enum Op {
/// An image: its pixel space (0..w, 0..h) maps into the document by `xf`; its alpha times
/// `opacity`.
Image {
image: Arc<Rgba>,
image: Arc<Image>,
xf: Affine,
opacity: f32,
},
@@ -104,11 +104,6 @@ fn first_solid(n: &Node) -> Option<vectorcraft_color::Color> {
own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c)))
}
/// `bp` cut into its dashes (as it is when `dash` draws none), for pens that can't draw them.
pub(crate) fn dashed(bp: &BezPath, dash: Option<&Dash>) -> BezPath {
dash.and_then(|d| stroke::dash(bp, d)).map_or_else(|| bp.clone(), |d| d.path)
}
fn q(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
@@ -124,7 +119,7 @@ pub(crate) struct Scene<'a> {
ops: Vec<Op>,
warnings: Vec<String>,
/// Decoded images by key (`None`: can't be decoded, left out).
images: HashMap<String, Option<Arc<Rgba>>>,
images: HashMap<String, Option<Arc<Image>>>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// The opacity of the containers around the current object.
opacity: f32,
@@ -456,7 +451,7 @@ impl<'a> Scene<'a> {
})
.collect()
};
let image = Rgba { width: u32::from(cols), height: u32::from(rows), pixels };
let image = Image { width: u32::from(cols), height: u32::from(rows), rgba: pixels };
let xf =
Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width() / f64::from(cols), area.height() / f64::from(rows));
self.ops.push(Op::Clip { path: bp.clone(), rule });
@@ -518,7 +513,7 @@ impl<'a> Scene<'a> {
/// Image `im`'s pixels (scaled down to what a metafile stores), `None` with a warning when it
/// has none or can't be decoded.
fn decoded(&mut self, im: &ImageObject) -> Option<Arc<Rgba>> {
fn decoded(&mut self, im: &ImageObject) -> Option<Arc<Image>> {
let key = im.key.as_str();
if let Some(i) = self.images.get(key) {
return i.clone();
@@ -527,7 +522,7 @@ impl<'a> Scene<'a> {
let img = blob
.and_then(|b| craft_image_codecs::decode(&b.bytes).ok())
.and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8()))
.map(Rgba::fitted)
.map(crate::dib::fitted)
.filter(|i| i.width > 0 && i.height > 0)
.map(Arc::new);
if img.is_none() {
@@ -541,7 +536,7 @@ impl<'a> Scene<'a> {
/// The pixels of `img`, drawn by `xf`, that `clip` (a box in the document) shows, with one pixel
/// more on each side: the part and its top left pixel. The whole image when `xf` cannot be
/// inverted; `None` when `clip` shows none of it.
fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> {
fn cropped(img: &Image, xf: Affine, clip: Rect) -> Option<(Image, u32, u32)> {
if xf.determinant().abs() < 1e-12 || !xf.determinant().is_finite() {
return Some((img.clone(), 0, 0));
}
@@ -564,9 +559,9 @@ fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> {
let mut pixels = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4);
for y in y0..y1 {
let start = y as usize * row + x0 as usize * 4;
pixels.extend_from_slice(img.pixels.get(start..start + (x1 - x0) as usize * 4)?);
pixels.extend_from_slice(img.rgba.get(start..start + (x1 - x0) as usize * 4)?);
}
Some((Rgba { width: x1 - x0, height: y1 - y0, pixels }, x0, y0))
Some((Image { width: x1 - x0, height: y1 - y0, rgba: pixels }, x0, y0))
}
/// Do the instances of `def` stay apart? A grid or brick tiling places its tiles side by side, so
+9 -13
View File
@@ -342,7 +342,7 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() {
})
.collect();
let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run();
let parts: Vec<(&crate::dib::Rgba, Affine)> = ops
let parts: Vec<(&craft_metafile::write::Image, Affine)> = ops
.iter()
.filter_map(|o| match o {
crate::scene::Op::Image { image, xf, .. } => Some((&**image, *xf)),
@@ -355,12 +355,12 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() {
assert!(stored * 4 < 64 * 64 * parts.len() as u64, "{stored} pixels in {} pieces", parts.len());
for ((part, xf), full) in parts.iter().zip(&whole) {
// The part's first pixel names where it starts in the image.
let (x0, y0) = (f64::from(part.pixels[0] / 4), f64::from(part.pixels[1] / 4));
let (x0, y0) = (f64::from(part.rgba[0] / 4), f64::from(part.rgba[1] / 4));
let want = *full * Affine::translate((x0, y0));
assert!(xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{xf:?} against {want:?}");
// Each row runs on from that pixel.
let last = (part.width as usize - 1) * 4;
assert_eq!(f64::from(part.pixels[last] / 4), x0 + f64::from(part.width - 1));
assert_eq!(f64::from(part.rgba[last] / 4), x0 + f64::from(part.width - 1));
}
}
@@ -394,7 +394,7 @@ fn ruby_is_written_with_its_type() {
let reading = contours(&lay.ruby);
assert!(reading >= 3, "the reading has ink: {reading}");
let doc = |ruby: bool| doc_with(100.0, 100.0, vec![Node::new(NodeId(0), NodeKind::Text(Box::new(typed(ruby))))]);
let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), crate::emf::MOVETOEX);
let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), 27 /* EMR_MOVETOEX */);
assert_eq!(moves(&doc(true)), moves(&doc(false)) + reading, "the reading's contours are written");
assert!(wmf(&doc(true)).bytes.len() > wmf(&doc(false)).bytes.len(), "WMF writes the reading too");
}
@@ -411,7 +411,6 @@ fn wmf_placeable_header_checksum_and_record_sizes() {
assert_eq!(u16_at(b, 14), 1440);
let xor = (0..10).fold(0u16, |a, i| a ^ u16_at(b, 2 * i));
assert_eq!(u16_at(b, 20), xor, "the checksum");
assert_eq!(crate::wmf::checksum(&b[..20]), xor);
// The WMF header: a memory metafile of 9 words, its size in words, the largest record.
assert_eq!([u16_at(b, 22), u16_at(b, 24), u16_at(b, 26)], [1, 9, 0x0300]);
assert_eq!(u32_at(b, 28) as usize * 2, b.len() - 22);
@@ -431,12 +430,12 @@ fn wmf_placeable_header_checksum_and_record_sizes() {
#[test]
fn wmf_sizes_fit_sixteen_bits() {
assert_eq!(crate::wmf::units_per_inch(612.0, 792.0), 1440);
let inch = crate::wmf::units_per_inch(3000.0, 1000.0);
assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0);
let ordinary = wmf(&doc_with(612.0, 792.0, Vec::new())).bytes;
assert_eq!(u16_at(&ordinary, 14), 1440);
let d = doc_with(3000.0, 1000.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 3000.0, 1000.0)), red(), Paint::None, 0.0)]);
let b = wmf(&d).bytes;
assert_eq!(u16_at(&b, 14), inch);
let inch = u16_at(&b, 14);
assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0);
assert!(u16_at(&b, 10) <= 32767);
}
@@ -483,10 +482,7 @@ fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers);
let doc = baked.as_ref().unwrap_or(doc);
let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run();
let bytes = match kind {
Kind::Emf => crate::emf::write(&ops, r, doc.info_title()),
Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings),
};
let bytes = crate::encode::write(ops, r, kind, doc.info_title(), &mut warnings)?;
Ok(Output { bytes, warnings })
}
+1 -1
View File
@@ -314,7 +314,7 @@ fn hand_wmf(w: i16, h: i16, records: &[(u16, Vec<u8>)]) -> Vec<u8> {
}
o.u16(1440);
o.u32(0);
let sum = crate::wmf::checksum(&o.0);
let sum = o.0.as_chunks::<2>().0.iter().fold(0, |acc, pair| acc ^ u16::from_le_bytes(*pair));
o.u16(sum);
o.bytes(&[1, 0, 9, 0, 0, 3]);
o.bytes(&[0; 12]);
+10 -4
View File
@@ -236,17 +236,23 @@ fn patterns_fill_with_their_average_color() {
#[test]
fn text_comes_in_as_point_type_in_the_named_font() {
let name = [be(&[9, 300]), vec![6], b"Geneva".to_vec()].concat();
let name = [be(&[9, 300]), vec![6], b"Gen\x8Eva".to_vec()].concat();
let bytes = v2(
[0, 0, 100, 200],
&[(0x2C, name), (0x03, be(&[300])), (0x0D, be(&[18])), (0x04, vec![1]), (0x28, [be(&[50, 10]), vec![4], b"Caf\x8E".to_vec()].concat())],
&[
(0x2C, name),
(0x03, be(&[300])),
(0x0D, be(&[18])),
(0x04, vec![1]),
(0x28, [be(&[50, 10]), vec![8], b"Caf\x8E\xCA\xDB\xDE\xF0".to_vec()].concat()),
],
);
let p = import_pict(&bytes).unwrap();
let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect();
let NodeKind::Text(t) = &texts[0].kind else { panic!("text") };
assert_eq!(t.plain_text(), "Café");
assert_eq!(t.plain_text(), "Café\u{a0}€fi\u{f8ff}");
let st = &t.runs[0].style;
assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Geneva", "Bold", 18.0));
assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Genéva", "Bold", 18.0));
// The text location is the baseline's start.
assert_eq!(t.xf.translation(), Point::new(10.0, 50.0).to_vec2());
}
-441
View File
@@ -1,441 +0,0 @@
//! The WMF writer: a placeable header (the picture's size and logical units an inch, with its
//! checksum), the WMF header, then the drawing in 16-bit logical units with an anisotropic window
//! the size of the picture, and the end-of-file record.
//!
//! Curves are flattened into polygons (fills) and polylines (strokes, with pens of the stroke's
//! width, caps and joins; dashes as separate lines). Objects take the lowest free slot of the
//! object table, as players number them: slots 0 and 1 hold a null pen and a null brush, our pen
//! and brush come after and are deleted when replaced. Images are StretchDIB records of 24-bit
//! bitmaps composited over white.
use kurbo::PathEl;
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect};
use crate::bytes::Out;
use crate::dib::{self, Rgba};
use crate::emf::{PS_ENDCAP_FLAT, PS_ENDCAP_SQUARE, PS_JOIN_BEVEL, PS_JOIN_MITER, SRCCOPY, colorref};
use crate::scene::{Op, Pen};
/// The key a placeable header starts with.
pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7;
// Record functions (MS-WMF 2.1.1.1).
pub(crate) const EOF: u16 = 0x0000;
pub(crate) const SETBKMODE: u16 = 0x0102;
pub(crate) const SETMAPMODE: u16 = 0x0103;
pub(crate) const SETPOLYFILLMODE: u16 = 0x0106;
pub(crate) const SETWINDOWORG: u16 = 0x020B;
pub(crate) const SETWINDOWEXT: u16 = 0x020C;
pub(crate) const SELECTOBJECT: u16 = 0x012D;
pub(crate) const DELETEOBJECT: u16 = 0x01F0;
pub(crate) const CREATEPENINDIRECT: u16 = 0x02FA;
pub(crate) const CREATEBRUSHINDIRECT: u16 = 0x02FC;
pub(crate) const POLYGON: u16 = 0x0324;
pub(crate) const POLYLINE: u16 = 0x0325;
pub(crate) const POLYPOLYGON: u16 = 0x0538;
pub(crate) const STRETCHDIB: u16 = 0x0F43;
/// Most logical units an inch (twips, what office apps use).
const MAX_INCH: f64 = 1440.0;
/// The largest 16-bit coordinate.
const MAX_I16: f64 = 32767.0;
/// Most points a polygon or polyline record holds (its count is 16-bit).
const MAX_POINTS: usize = 32767;
/// Curves are flattened to within this many logical units.
const FLATNESS: f64 = 0.25;
/// The null pen's and the null brush's slots.
const NULL_PEN: u16 = 0;
const NULL_BRUSH: u16 = 1;
const TRANSLUCENT_IMAGES: &str = "WMF has no transparency: images are written over white";
const TURNED_IMAGES: &str = "WMF can't rotate or skew images: they are written upright, filling their bounds";
/// Does `bytes` start like a WMF (placeable, or a plain memory or disk metafile header)?
pub(crate) fn is_wmf(bytes: &[u8]) -> bool {
let u16_at = |at: usize| bytes.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let placeable = bytes.get(..4).is_some_and(|b| b == PLACEABLE_KEY.to_le_bytes());
placeable || (matches!(u16_at(0), Some(1 | 2)) && u16_at(2) == Some(9) && matches!(u16_at(4), Some(0x0100 | 0x0300)))
}
/// The logical units an inch for a picture `w` × `h` points: the most, up to 1440, that keep its
/// size within 16 bits.
pub(crate) fn units_per_inch(w: f64, h: f64) -> u16 {
let side_in = w.max(h) / 72.0;
let fit = if side_in > 0.0 { (MAX_I16 / side_in).floor() } else { MAX_INCH };
fit.clamp(1.0, MAX_INCH) as u16
}
/// The XOR of the first ten 16-bit words of a placeable header.
pub(crate) fn checksum(header: &[u8]) -> u16 {
header.as_chunks::<2>().0.iter().take(10).fold(0, |acc, w| acc ^ u16::from_le_bytes(*w))
}
/// `bp` flattened to within `tol`: each subpath's points and whether it closes.
fn flatten(bp: &BezPath, tol: f64) -> Vec<(Vec<Point>, bool)> {
let mut out: Vec<(Vec<Point>, bool)> = vec![];
let mut cur: Vec<Point> = vec![];
vectorcraft_geom::flatten(bp.iter(), tol, |el| match el {
PathEl::MoveTo(p) => {
if cur.len() > 1 {
out.push((std::mem::take(&mut cur), false));
}
cur = vec![p];
}
PathEl::LineTo(p) => cur.push(p),
PathEl::ClosePath => {
if cur.len() > 1 {
out.push((std::mem::take(&mut cur), true));
}
cur.clear();
}
_ => {}
});
if cur.len() > 1 {
out.push((cur, false));
}
out
}
/// What a pen object is made of.
#[derive(Clone, Copy, PartialEq)]
struct PenKey {
style: u16,
width: i16,
color: u32,
}
struct Writer {
/// The records after the headers.
out: Out,
max_record: u32,
to_dev: Affine,
/// Logical units per point.
k: f64,
/// Which object slots are taken.
slots: Vec<bool>,
brush: Option<(u16, u32)>,
pen: Option<(u16, PenKey)>,
sel_pen: u16,
sel_brush: u16,
fill_mode: Option<u16>,
}
/// Write `ops` (curves flattened, no clips) as a placeable WMF of `region` (document space).
pub(crate) fn write(ops: &[Op], region: Rect, warnings: &mut Vec<String>) -> Vec<u8> {
let inch = units_per_inch(region.width(), region.height());
let k = f64::from(inch) / 72.0;
let size = |v: f64| (v * k).round().clamp(1.0, MAX_I16) as i16;
let (w, h) = (size(region.width()), size(region.height()));
let mut wr = Writer {
out: Out::default(),
max_record: 0,
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
k,
slots: vec![],
brush: None,
pen: None,
sel_pen: NULL_PEN,
sel_brush: NULL_BRUSH,
fill_mode: None,
};
// MM_ANISOTROPIC, a window the size of the picture, transparent background.
wr.record(SETMAPMODE, |o| o.u16(8));
wr.record(SETWINDOWORG, |o| {
o.i16(0);
o.i16(0);
});
wr.record(SETWINDOWEXT, |o| {
o.i16(h);
o.i16(w);
});
wr.record(SETBKMODE, |o| o.u16(1));
// The null pen and brush (slots 0 and 1), selected while ours change.
wr.alloc();
wr.record(CREATEPENINDIRECT, |o| {
o.u16(5);
o.i16(0);
o.i16(0);
o.u32(0);
});
wr.alloc();
wr.record(CREATEBRUSHINDIRECT, |o| {
o.u16(1);
o.u32(0);
o.u16(0);
});
wr.select(NULL_PEN);
wr.select(NULL_BRUSH);
let mut translucent = false;
let mut turned = false;
for op in ops {
match op {
Op::Fill { path, rule, rgb } => wr.fill(path, *rule, *rgb),
Op::Stroke { path, pen } => wr.stroke(path, pen),
Op::Image { image, xf, opacity } => {
translucent |= !image.opaque() || *opacity < 0.998;
turned |= !wr.image(image, *xf, *opacity);
}
// The scene gives formats without clipping none.
Op::Clip { .. } | Op::Unclip => {}
}
}
if let Some((slot, _)) = wr.brush.take() {
wr.select(NULL_BRUSH);
wr.delete(slot);
}
if let Some((slot, _)) = wr.pen.take() {
wr.select(NULL_PEN);
wr.delete(slot);
}
wr.record(EOF, |_| {});
for (on, w) in [(translucent, TRANSLUCENT_IMAGES), (turned, TURNED_IMAGES)] {
if on && !warnings.iter().any(|x| x == w) {
warnings.push(w.to_string());
}
}
wr.finish(w, h, inch)
}
impl Writer {
/// Append one record: its size in 16-bit words, its function and `body`.
fn record(&mut self, function: u16, body: impl FnOnce(&mut Out)) {
let start = self.out.len();
self.out.u32(0);
self.out.u16(function);
body(&mut self.out);
self.out.pad(2);
let words = u32::try_from((self.out.len() - start) / 2).unwrap_or(u32::MAX);
self.out.set_u32(start, words);
self.max_record = self.max_record.max(words);
}
/// The placeable header, the WMF header, then the records.
fn finish(self, w: i16, h: i16, inch: u16) -> Vec<u8> {
let mut o = Out::default();
o.u32(PLACEABLE_KEY);
o.u16(0);
for v in [0, 0, w, h] {
o.i16(v);
}
o.u16(inch);
o.u32(0);
let sum = checksum(&o.0);
o.u16(sum);
// A memory metafile, 9 words of header, version 3.
o.u16(1);
o.u16(9);
o.u16(0x0300);
o.u32(u32::try_from((18 + self.out.len()) / 2).unwrap_or(u32::MAX));
o.u16(u16::try_from(self.slots.len()).unwrap_or(u16::MAX));
o.u32(self.max_record);
o.u16(0);
o.bytes(&self.out.0);
o.0
}
/// The lowest free object slot, taken.
fn alloc(&mut self) -> u16 {
let i = match self.slots.iter().position(|t| !t) {
Some(i) => i,
None => {
self.slots.push(false);
self.slots.len() - 1
}
};
if let Some(s) = self.slots.get_mut(i) {
*s = true;
}
u16::try_from(i).unwrap_or(u16::MAX)
}
fn select(&mut self, slot: u16) {
self.record(SELECTOBJECT, |o| o.u16(slot));
}
fn delete(&mut self, slot: u16) {
self.record(DELETEOBJECT, |o| o.u16(slot));
if let Some(s) = self.slots.get_mut(usize::from(slot)) {
*s = false;
}
}
fn dev(&self, p: Point) -> [i16; 2] {
let q = self.to_dev * p;
let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_I16, MAX_I16) as i16 } else { 0 };
[c(q.x), c(q.y)]
}
/// The device points of `pts`, repeats dropped, thinned to what one record holds.
fn points(&self, pts: &[Point]) -> Vec<[i16; 2]> {
let mut v: Vec<[i16; 2]> = vec![];
for p in pts {
let d = self.dev(*p);
if v.last() != Some(&d) {
v.push(d);
}
}
if v.len() > MAX_POINTS {
let step = v.len().div_ceil(MAX_POINTS - 1);
let last = v.last().copied();
v = v.into_iter().step_by(step).collect();
v.extend(last);
}
v
}
fn select_pen(&mut self, slot: u16) {
if self.sel_pen != slot {
self.select(slot);
self.sel_pen = slot;
}
}
fn select_brush(&mut self, slot: u16) {
if self.sel_brush != slot {
self.select(slot);
self.sel_brush = slot;
}
}
fn use_brush(&mut self, rgb: [u8; 3]) {
let color = colorref(rgb);
let slot = match self.brush {
Some((slot, c)) if c == color => slot,
old => {
if let Some((slot, _)) = old {
self.select_brush(NULL_BRUSH);
self.delete(slot);
}
let slot = self.alloc();
self.record(CREATEBRUSHINDIRECT, |o| {
o.u16(0);
o.u32(color);
o.u16(0);
});
self.brush = Some((slot, color));
slot
}
};
self.select_brush(slot);
}
fn use_pen(&mut self, p: &Pen) {
let cap = match p.cap {
LineCap::Butt => PS_ENDCAP_FLAT,
LineCap::Round => 0,
LineCap::Square => PS_ENDCAP_SQUARE,
};
let join = match p.join {
LineJoin::Miter => PS_JOIN_MITER,
LineJoin::Round => 0,
LineJoin::Bevel => PS_JOIN_BEVEL,
};
let key = PenKey { style: (cap | join) as u16, width: (p.width * self.k).round().clamp(1.0, MAX_I16) as i16, color: colorref(p.rgb) };
let slot = match self.pen {
Some((slot, k)) if k == key => slot,
old => {
if let Some((slot, _)) = old {
self.select_pen(NULL_PEN);
self.delete(slot);
}
let slot = self.alloc();
self.record(CREATEPENINDIRECT, |o| {
o.u16(key.style);
o.i16(key.width);
o.i16(0);
o.u32(key.color);
});
self.pen = Some((slot, key));
slot
}
};
self.select_pen(slot);
}
fn fill(&mut self, bp: &BezPath, rule: FillRule, rgb: [u8; 3]) {
let polys: Vec<Vec<[i16; 2]>> = flatten(bp, FLATNESS / self.k).iter().map(|(p, _)| self.points(p)).filter(|p| p.len() > 2).collect();
if polys.is_empty() {
return;
}
// ALTERNATE (even-odd) or WINDING (non-zero).
let mode = if rule == FillRule::EvenOdd { 1 } else { 2 };
if self.fill_mode != Some(mode) {
self.record(SETPOLYFILLMODE, |o| o.u16(mode));
self.fill_mode = Some(mode);
}
self.use_brush(rgb);
self.select_pen(NULL_PEN);
for chunk in polys.chunks(usize::from(u16::MAX)) {
self.record(POLYPOLYGON, |o| {
o.u16(chunk.len() as u16);
chunk.iter().for_each(|p| o.u16(p.len() as u16));
for p in chunk.iter().flatten() {
o.i16(p[0]);
o.i16(p[1]);
}
});
}
}
fn stroke(&mut self, bp: &BezPath, pen: &Pen) {
let path = crate::scene::dashed(bp, pen.dash.as_ref());
let lines: Vec<(Vec<[i16; 2]>, bool)> =
flatten(&path, FLATNESS / self.k).iter().map(|(p, closed)| (self.points(p), *closed)).filter(|(p, _)| p.len() > 1).collect();
if lines.is_empty() {
return;
}
self.use_pen(pen);
self.select_brush(NULL_BRUSH);
for (pts, closed) in lines {
// A closed subpath is a polygon (with the null brush, its outline), so it joins at
// its start.
self.record(if closed { POLYGON } else { POLYLINE }, |o| {
o.i16(pts.len() as i16);
for p in &pts {
o.i16(p[0]);
o.i16(p[1]);
}
});
}
}
/// An image placed by `xf`, upright: false when `xf` rotates or skews it (then it fills its
/// bounds).
fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) -> bool {
if img.width == 0 || img.height == 0 || opacity <= 0.0 {
return true;
}
let m = self.to_dev * xf;
if !m.as_coeffs().iter().all(|v| v.is_finite()) {
return true;
}
let [a, b, c, d, e, f] = m.as_coeffs();
let (w, h) = (f64::from(img.width), f64::from(img.height));
let upright = b.abs() < 1e-9 && c.abs() < 1e-9;
let (x, y, dw, dh) = if upright {
(e, f, a * w, d * h)
} else {
let r = m.transform_rect_bbox(Rect::new(0.0, 0.0, w, h));
(r.x0, r.y0, r.width(), r.height())
};
let s = |v: f64| v.round().clamp(-MAX_I16, MAX_I16) as i16;
let (bmi, bits) = dib::rgb24(img, opacity);
self.record(STRETCHDIB, |o| {
o.u32(SRCCOPY);
// DIB_RGB_COLORS; the source and destination rectangles, last field first.
o.u16(0);
o.i16(img.height as i16);
o.i16(img.width as i16);
o.i16(0);
o.i16(0);
o.i16(s(dh));
o.i16(s(dw));
o.i16(s(y));
o.i16(s(x));
o.bytes(&bmi);
o.bytes(&bits);
});
upright
}
}
+267 -10
View File
@@ -1,7 +1,8 @@
//! Object → Path commands: Simplify, Smooth, Remove redundant points, Add Anchor Points, Average,
//! Join, Split Into Grid.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ops::Range;
use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2};
use vectorcraft_geom::path::measured_arclen;
@@ -97,7 +98,10 @@ fn turn_deg(a: &Seg, b: &Seg) -> f64 {
d.acos().to_degrees()
}
/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold.
/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. A closed
/// subpath starts where it did: at its first anchor when the refit keeps an anchor there, otherwise
/// at a new anchor split into the refit at its point nearest there when the refit still has fewer
/// anchors than the subpath with that one, and otherwise at the refit's anchor nearest there.
pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData {
let mut out = Vec::new();
for sp in &path.subpaths {
@@ -108,15 +112,151 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData {
PathData::new(out)
}
/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath
/// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the
/// point farthest from its start, or in three when two still give that. When three parts still give
/// no area, straight lines follow the subpath within the tolerance, and without straight lines it
/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit
/// starts where the subpath started ([`keep_start`]).
fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option<SubPath> {
refit_subpath(sp, opts).map(|fit| {
let n = fit.anchors.len();
keep_start(fit, sp, 0..n).0
})
}
/// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`]
/// starts at that anchor instead of at a new one split in beside it.
pub const START_SNAP: f64 = 1e-3;
/// Distance (points) within which two points of a closed path count as equally near its old start.
const START_TIE: f64 = 1e-6;
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
/// when there is none.
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
#[cfg(test)]
tests::count_places();
let mut best: Option<(f64, usize, f64)> = None;
for j in 0..orig.anchors.len() {
let hit = orig.segment(j).nearest(p, 1e-9);
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
best = Some((hit.distance_sq, j, hit.t));
}
}
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
}
/// Of the candidates (distance, point, value), the value of the nearest, with a finite distance:
/// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from
/// its first anchor, then the first given. Each distinct point is placed along `orig` once.
fn earliest_nearest<T>(candidates: impl IntoIterator<Item = (f64, Point, T)>, orig: &SubPath) -> Option<T> {
// (distance, place along `orig` once a tie needs it, point, value)
type Best<T> = (f64, Option<(usize, f64)>, Point, T);
let mut best: Option<Best<T>> = None;
// Places along `orig` by the bits of the point, so many ties at one point search `orig` once.
let mut placed: HashMap<[u64; 2], (usize, f64)> = HashMap::new();
let mut place = |p: Point| *placed.entry([p.x.to_bits(), p.y.to_bits()]).or_insert_with(|| place_along(orig, p));
for (d, p, x) in candidates {
if !d.is_finite() {
continue;
}
match &mut best {
None => best = Some((d, None, p, x)),
Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => {
let held = *bplace.get_or_insert_with(|| place(*bp));
let at = place(p);
if at.0 < held.0 || (at.0 == held.0 && at.1 < held.1) {
best = Some((d, Some(at), p, x));
}
}
Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)),
Some(_) => {}
}
}
best.map(|(.., x)| x)
}
/// The closed `sp` started at the point on it nearest `start`: at an anchor within [`START_SNAP`] of
/// `start` when it has one, even where a segment crosses the path there, otherwise at the anchor at
/// that point or at a new anchor split into the segment there, which leaves the outline as it is. Of
/// points equally near `start`, the one earliest along `orig` (the path before it was refitted) from
/// its first anchor is used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest
/// point, is returned as it is.
pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
let n = sp.anchors.len();
start_near(sp, start, orig, true, 0..n).0
}
/// [`start_nearest`] on the segments `within` alone, splitting a segment only when `split` is set;
/// otherwise, when no anchor lies at the nearest point, the path starts at the anchor of those
/// segments nearest `start`, with the same tie rule. → (the path, the segment split when one was,
/// where the new start was before the anchors turned).
fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within: Range<usize>) -> (SubPath, Option<usize>, usize) {
let n = sp.anchors.len();
if !sp.closed || n < 2 {
return (sp, None, 0);
}
let within = within.start.min(n)..within.end.min(n);
// The anchors of the segments `within`: each one's first, and the last one's end.
let anchors = || (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j));
// An anchor within [`START_SNAP`] of `start` starts the path, before any segment through there.
let snapped = if within.is_empty() { None } else { earliest_nearest(anchors().filter(|(d, ..)| *d <= START_SNAP), orig) };
if let Some(first) = snapped {
sp.anchors.rotate_left(first);
return (sp, None, first);
}
let hits = within.clone().map(|i| {
let c = sp.segment(i);
let hit = c.nearest(start, 1e-9);
let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN };
(d, c.eval(hit.t), (i, hit.t))
});
let Some((i, t)) = earliest_nearest(hits, orig) else { return (sp, None, 0) };
let c = sp.segment(i);
let at = c.eval(t);
let (first, cut) = if at.distance(c.p0) <= START_SNAP {
(i, None)
} else if at.distance(c.p3) <= START_SNAP {
((i + 1) % n, None)
} else if split {
let mid = if sp.segment_is_line(i) {
Anchor::corner(at)
} else {
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
sp.anchors[i].h_out = l.p1;
sp.anchors[(i + 1) % n].h_in = r.p2;
Anchor::with_handles(at, l.p2, r.p1)
};
sp.anchors.insert(i + 1, mid);
(i + 1, Some(i))
} else {
(earliest_nearest(anchors(), orig).unwrap_or(0), None)
};
sp.anchors.rotate_left(first);
(sp, cut, first)
}
/// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at
/// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has
/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]),
/// looking only at the segments `within`. An open `orig` keeps `fit` as it is.
fn keep_start(fit: SubPath, orig: &SubPath, within: Range<usize>) -> (SubPath, Option<usize>, usize) {
match orig.anchors.first() {
Some(a) if orig.closed => {
let split = fit.anchors.len() + 1 < orig.anchors.len();
start_near(fit, a.p, orig, split, within)
}
_ => (fit, None, 0),
}
}
/// [`simplify_subpath`] before the start is put back: a closed subpath whose refit is one segment,
/// or lines that enclose no area, is refitted in two parts, cut at the point farthest from its
/// start, or in three when two still give that. When three parts still give no area, straight lines
/// follow the subpath within the tolerance, and without straight lines it
/// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose
/// an area, it stays as it is, or with straight lines follows the lines between samples of each
/// curved segment when the limits leave room for lines within the tolerance; one that is all in line
/// keeps the refit.
fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option<SubPath> {
fn refit_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option<SubPath> {
let mut segs = subpath_segs(sp);
let n = segs.len();
if n == 0 || sp.closed && n < 2 {
@@ -694,7 +834,9 @@ pub struct SimplifiedPart {
/// two end anchors, which stay where they are with their handles on the side away from the run.
/// The other segments and anchors stay exactly as they are. A subpath whose every segment is in
/// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more
/// segments than it had is left as it is (except with Convert to Straight Lines).
/// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath
/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]), on the run that held its
/// first anchor when that anchor goes.
pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart {
let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts };
let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new());
@@ -733,6 +875,7 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP
let mut anchors = vec![sp.anchors[start]];
let mut kept = vec![(start, 0)];
let mut runs = vec![];
let mut start_run = None;
let mut k = 0;
while k < n {
let j = (start + k) % n;
@@ -765,7 +908,12 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP
}
// The run's segments, from its first anchor on: a run back to the walk's start ends with
// the closing segment, the last index.
runs.extend(first..first + if keep_original { run.len() } else { fitted.len() });
let segs = first..first + if keep_original { run.len() } else { fitted.len() };
if sp.closed && (k + 1..k + len).any(|i| (start + i) % m == 0) {
// The run that held the old first anchor.
start_run = Some(segs.clone());
}
runs.extend(segs);
let end_seg = fitted.last().filter(|_| !keep_original);
if sp.closed && k + len == n {
// The run ends where the walk started.
@@ -782,7 +930,20 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP
}
k += len;
}
(SubPath::new(anchors, sp.closed), runs, kept)
// A closed subpath starts where it did: the walk already starts at its first anchor when that
// stays, and otherwise the run that held it starts the path ([`keep_start`] on that run's
// segments alone, so no other segment changes), with the runs and anchors kept renumbered.
let Some(within) = start_run else { return (SubPath::new(anchors, sp.closed), runs, kept) };
let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp, within);
let len = out.anchors.len();
if (cut, first) == (None, 0) || len == 0 {
return (out, runs, kept);
}
let turned = |i: usize| (i + len - first) % len;
let after_cut = |i: usize| i + usize::from(cut.is_some_and(|c| i > c));
let runs = runs.into_iter().flat_map(|s| if cut == Some(s) { vec![s, s + 1] } else { vec![after_cut(s)] }).map(turned).collect();
let kept = kept.into_iter().map(|(old, new)| (old, turned(after_cut(new)))).collect();
(out, runs, kept)
}
/// `a` with its out (`out`) or in handle at `h` and the other as it is: still smooth when it was
@@ -1402,6 +1563,102 @@ mod tests {
MOVES.set(MOVES.get() + n);
}
std::thread_local! {
/// Calls of [`place_along`], each a search of every segment of the path before the refit.
static PLACES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub(super) fn count_places() {
PLACES.set(PLACES.get() + 1);
}
/// A refitted run across the start of a closed path that crosses itself at its start keeps the
/// start on the run: the unselected segment through the old start is not split.
#[test]
fn a_run_across_the_start_keeps_the_start_on_the_run() {
let pts = [
(0.0, 0.0),
(10.0, 0.3),
(20.0, -0.3),
(30.0, 0.3),
(40.0, 0.6),
(40.0, 50.0),
(0.0, 50.0),
(0.0, -50.0),
(-40.0, -50.0),
(-40.0, 0.6),
(-30.0, 0.3),
(-20.0, -0.3),
(-10.0, 0.3),
];
let sp = SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true);
let path = PathData::new(vec![sp]);
let picked: BTreeSet<(usize, usize)> = [9, 10, 11, 12, 0, 1, 2, 3].into_iter().map(|s| (0, s)).collect();
let out = simplify_part(&path, &picked, &SimplifyOptions { tolerance: 1.0, ..SimplifyOptions::default() });
let got = &out.path.subpaths[0];
let n = got.anchors.len();
assert!(n < pts.len(), "{n} anchors");
let (top, bottom) = (Point::new(0.0, 50.0), Point::new(0.0, -50.0));
assert!(
(0..n).any(|i| got.anchors[i].p == top && got.anchors[(i + 1) % n].p == bottom),
"the segment through the old start was split: {:?}",
got.anchors.iter().map(|a| a.p).collect::<Vec<_>>()
);
assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p);
}
/// A closed polyline from its start at (0, 0) up to (0, 10) whose diagonal from (-20, -20) to
/// (20, 20) crosses it at that start, with two anchors on the diagonal that a refit drops.
fn crossing_at_start() -> SubPath {
let pts = [(0, 0), (0, 10), (40, 10), (40, -20), (-20, -20), (-10, -10), (10, 10), (20, 20), (20, 30), (-10, 30), (-10, 0)];
SubPath::polyline(&pts.map(|(x, y)| Point::new(f64::from(x), f64::from(y))), true)
}
/// A refitted run that keeps an anchor at the old start of a closed path starts the path at that
/// anchor, though a segment of the run that crosses the path there comes first in the run.
#[test]
fn a_run_that_keeps_the_start_anchor_starts_there() {
let path = PathData::new(vec![crossing_at_start()]);
let picked: BTreeSet<(usize, usize)> = [0, 4, 5, 6, 7, 8, 9, 10].into_iter().map(|s| (0, s)).collect();
let opts = SimplifyOptions { tolerance: 0.01, corner_angle_deg: 1.0, straight_lines: true, ..SimplifyOptions::default() };
let got = &simplify_part(&path, &picked, &opts).path.subpaths[0];
let ps: Vec<Point> = got.anchors.iter().map(|a| a.p).collect();
assert_eq!(ps.len(), 9, "{ps:?}");
assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}");
assert_eq!(ps.iter().filter(|&&p| p == Point::ZERO).count(), 1, "{ps:?}");
}
/// The whole closed path refitted keeps its start anchor first when a segment of the refit
/// crosses the path there.
#[test]
fn a_refit_that_keeps_the_start_anchor_starts_there() {
let sp = crossing_at_start();
let mut fit = sp.clone();
fit.anchors.retain(|a| ![Point::new(-10.0, -10.0), Point::new(10.0, 10.0)].contains(&a.p));
fit.anchors.rotate_left(4);
let n = fit.anchors.len();
let (got, cut, _) = keep_start(fit, &sp, 0..n);
let ps: Vec<Point> = got.anchors.iter().map(|a| a.p).collect();
assert_eq!(cut, None, "{ps:?}");
assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}");
}
/// Candidates tied at one point are placed along the old path once, not once each, and the first
/// given still wins the tie.
#[test]
fn tied_candidates_at_one_point_are_placed_once() {
let orig = SubPath::new(
vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0)), Anchor::corner(Point::new(100.0, 100.0))],
true,
);
let candidates = (0..1000).map(|i| (0.0, Point::new(0.0, 0.0), i));
PLACES.set(0);
let got = earliest_nearest(candidates, &orig);
let places = PLACES.get();
assert_eq!(got, Some(0));
assert_eq!(places, 1, "searches of the old path for 1000 candidates at one point");
}
/// A subpath of `n` anchors from `seed`: corners, smooth points and points with one handle.
fn random_subpath(seed: &mut u64, n: usize, closed: bool) -> SubPath {
let mut rnd = || {
+3 -3
View File
@@ -22,9 +22,9 @@ pub use boolean::{
try_unite_all_with, unite_all, unite_all_with,
};
pub use edit::{
AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join,
remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level,
smooth_options, split_into_grid,
AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, START_SNAP, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average,
join, remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth,
smooth_level, smooth_options, split_into_grid, start_nearest,
};
pub use fit::{fit_cubics, fit_cubics_through};
pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path};
+68
View File
@@ -742,6 +742,74 @@ fn smooth_level_0_keeps_a_closed_paths_start_corner_within_tolerance() {
assert!(moved <= limit, "level 0 moved the path by {moved} pt, more than {limit} pt: {:?}", s.subpaths[0].anchors[0]);
}
/// Twice the area `sp` encloses, from 16 points along each segment: positive when it runs
/// counterclockwise in y-up terms.
fn signed_area(sp: &SubPath) -> f64 {
let pts: Vec<Point> = (0..sp.segment_count()).flat_map(|i| (0..16).map(move |k| sp.segment(i).eval(f64::from(k) / 16.0))).collect();
(0..pts.len()).map(|i| pts[i].to_vec2().cross(pts[(i + 1) % pts.len()].to_vec2())).sum()
}
/// A D of 41 corner points round (0, 0): the arc of radius 100 from (100, 0) up to (0, 100), the
/// straight side down to (0, -100), and the arc back. It starts in the middle of its arc, and its
/// first corner is at the top.
fn d_shape() -> SubPath {
let at = |deg: f64| Point::new(100.0 * deg.to_radians().cos(), 100.0 * deg.to_radians().sin());
let pts: Vec<Point> = (0..=20).map(|i| at(4.5 * f64::from(i))).chain((0..20).map(|i| at(-90.0 + 4.5 * f64::from(i)))).collect();
SubPath::polyline(&pts, true)
}
/// Object › Path › Simplify starts a closed path where it started, though the refit runs from the
/// first corner: on the D, the refit starts within the tolerance of the old start, runs the same way
/// round, and has fewer anchors.
#[test]
fn simplify_keeps_a_closed_paths_start() {
let sp = d_shape();
let path = PathData::single(sp.clone());
let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, ..Default::default() });
let out = &s.subpaths[0];
assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}");
let moved = out.anchors[0].p.distance(sp.anchors[0].p);
assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt, to {:?}", out.anchors[0].p);
assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays");
assert!(one_way_distance(&path, &s).max(one_way_distance(&s, &path)) <= 1.0 + 1e-6);
}
/// Object › Path › Smooth starts a closed path near where it started, though the refit runs from the
/// point where the path turns back: a round loop of radius 50 with a needle out to (250, 0), which
/// starts on the far side of the loop at (-50, 0).
#[test]
fn smooth_keeps_a_closed_paths_start() {
let at = |deg: f64| Point::new(50.0 * deg.to_radians().cos(), 50.0 * deg.to_radians().sin());
let pts: Vec<Point> = (0..=20)
.map(|i| at(180.0 + 8.95 * f64::from(i)))
.chain([Point::new(250.0, 0.0)])
.chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i))))
.collect();
let sp = SubPath::polyline(&pts, true);
let path = PathData::single(sp.clone());
let s = smooth_level(&path, SMOOTH_AUTO_LEVEL);
let out = &s.subpaths[0];
assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}");
let moved = out.anchors[0].p.distance(sp.anchors[0].p);
assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", out.anchors[0].p);
assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays");
}
/// A refit with only one anchor fewer than the closed path gets no anchor split in to keep its
/// start: it starts at its anchor nearest the old start. A rectangle with a straight point at
/// (30, 0) simplifies to its four corners, starting at (0, 0).
#[test]
fn simplify_starts_at_the_nearest_anchor_rather_than_add_one_back() {
let pts = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y));
let path = PathData::single(SubPath::polyline(&pts, true));
let want = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(|(x, y)| Point::new(x, y));
for straight_lines in [false, true] {
let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, straight_lines, ..Default::default() });
let got: Vec<Point> = s.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(got, want, "straight_lines {straight_lines}");
}
}
#[test]
fn remove_redundant_collinear_and_curve() {
let p = PathData::single(SubPath::polyline(
+72 -6
View File
@@ -13,6 +13,8 @@ use super::{
PathData, PathDrawMode, Pattern, PatternDef, Placement, Rect, Scan, Shape, SoftMask, StrokeProps, TextAs, TextLine, TextOverprint, TilingPattern,
Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient,
};
use crate::import_fonts::program_facts;
use vectorcraft_text::{FileFontInfo, FileGlyph};
/// The most lines of type kept for a text-showing operator's stroke pass ([`Builder::park_text`]):
/// beyond them the oldest is finished, and strokes over its glyphs come in as type of their own.
@@ -51,6 +53,12 @@ fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool {
}
impl<'p> Builder<'p> {
/// Draw type in the fonts the file embeds (the default) or not ([`crate::ImportOptions::embedded_fonts`]).
pub(super) fn with_embedded_fonts(mut self, on: bool) -> Self {
self.embedded_fonts = on;
self
}
pub(super) fn new(next: u64, colors: Colors<'p>, text_as: TextAs, route: bool) -> Self {
Self {
colors,
@@ -67,6 +75,7 @@ impl<'p> Builder<'p> {
held: vec![],
lost: None,
text_as,
embedded_fonts: true,
actual: Default::default(),
images: HashMap::new(),
image_keys: HashMap::new(),
@@ -80,6 +89,8 @@ impl<'p> Builder<'p> {
font_names: HashMap::new(),
families: None,
missing_fonts: vec![],
file_glyphs: crate::import_fonts::FileFontGlyphs::default(),
file_fonts: HashMap::new(),
cid_text: HashMap::new(),
font_chars: HashMap::new(),
matched: HashMap::new(),
@@ -782,11 +793,15 @@ impl<'p> Builder<'p> {
/// it was kept as them ([`Self::end_text`]).
fn end_line(&mut self, mut line: TextLine, glyphs: Vec<GlyphRun>) -> bool {
let held = std::mem::take(&mut line.held);
let (line_conflict, line_type3) = (line.file_conflict, line.has_type3);
// Type the file names itself (ActualText) is in reading order as it stands.
let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3;
let mut outlined = false;
if let Some((t, opacity, facts)) = line.finish() {
if checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink) {
// A line with a glyph the file's font can't keep (another glyph for the same character)
// is kept as outlines too, so each glyph draws as the file does.
let conflict = line_conflict && !glyphs.is_empty() && !line_type3;
if conflict || (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)) {
outlined = true;
if self.mask.is_some() {
self.flush_glyphs();
@@ -1461,10 +1476,8 @@ impl<'p> Builder<'p> {
// vector's vx (from the font's `W2`, else half its width from `W` or `DW`) to the left of
// the column's centre (ISO 32000-1 §9.7.4.3); vertical type centres each glyph on the
// column. Half an em only for a full-width glyph (#722).
let top = upright.then(|| {
let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph));
m * kurbo::Point::new(vx, 880.0)
});
let vx = upright.then(|| self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph)));
let top = vx.map(|vx| m * kurbo::Point::new(vx, 880.0));
// A horizontal line is gathered in visual order and put back in logical order as a whole:
// a ligature's characters (lam-alef, lam-lam-heh) go in visual order too (#6072).
let text = if top.is_none() { visual_glyph_text(text) } else { text };
@@ -1507,8 +1520,31 @@ impl<'p> Builder<'p> {
place(&mut line);
self.text = Some(line);
}
let outline = o.outline();
// A font the file carries for a family that isn't available: the glyph goes into the font
// kept with the document, which draws the line as the file does ([`crate::import_fonts`]).
if let Some(font) = self.file_font(key, o, &look) {
if let Some(line) = &mut self.text {
line.file_font = true;
}
let mut chars = text.chars();
if let (Some(ch), None) = (chars.next(), chars.next()) {
// A glyph set vertically has no horizontal width: its column's, twice its centre.
let advance = match vx {
Some(vx) => 2.0 * vx,
None => width.map_or(500.0, f64::from),
};
if self.file_glyphs.wants(font, ch) {
self.file_glyphs.add(font, FileGlyph { ch, outline: outline.clone(), advance });
} else if self.file_glyphs.conflicts(font, ch, &outline, advance)
&& let Some(line) = &mut self.text
{
line.file_conflict = true;
}
}
}
// Its ink: a stroke the file draws as outlines of the glyphs is told by it.
let mut ink = o.outline();
let mut ink = outline;
if top.is_none() {
self.keep_glyph(o, m, drawn, opacity, scale, overprint);
}
@@ -1520,6 +1556,36 @@ impl<'p> Builder<'p> {
}
true
}
/// The font among the glyphs gathered for fonts kept with the document that glyphs of font
/// `key` (drawn with `look`) go into: when the file carries the font's program, no installed
/// face has its PostScript name, and its family and style aren't available as named. Decided
/// once per font.
fn file_font(&mut self, key: u128, o: &craft_pdf::interpret::font::OutlineGlyph, look: &Look) -> Option<usize> {
if let Some(f) = self.file_fonts.get(&key) {
return *f;
}
// Not the interpreter's stand-in for a font the file doesn't carry.
let carried = self.embedded_fonts && self.fonts.get(&key).is_some_and(|f| f.embedded) && o.font_data().is_none_or(|d| d.embedded);
let installed = self.font_names.get(&key).is_some_and(|i| i.face.is_some());
let available =
|| vectorcraft_text::FontDb::global().resolve(&look.family, &look.style).is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact);
let font = (carried && !installed && !look.family.trim().is_empty() && !available()).then(|| {
let data = o.font_data();
let (fs_type, metrics) = data.as_ref().map_or((None, None), |d| program_facts(d.data.as_ref().as_ref(), d.index));
let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.and_then(|d| d.postscript_name)).unwrap_or_default();
// A subset's six-letter tag.
let postscript = match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(),
_ => name,
};
let (ascent, descent) = metrics.unwrap_or_default();
let info = || FileFontInfo { family: look.family.clone(), style: look.style.clone(), postscript, ascent, descent, fs_type };
self.file_glyphs.font(&look.family, &look.style, info)
});
self.file_fonts.insert(key, font);
font
}
}
/// Glyph `o` placed by `m` and drawn with `drawn` as the outline it is kept as
+34 -5
View File
@@ -5,6 +5,7 @@ use super::{
ImportReport, InterpreterCache, InterpreterSettings, InterpreterWarning, LayerColor, MAX_NESTING, Mutex, Node, NodeKind, Ocgs, Ordering, Paint,
PdfError, Rect, Shape, Swatch, all_on, contains, hides_forms, scan_page, white_cover,
};
use crate::import_text::keep_file_fonts;
/// Mixed into an image's cache key when it is read white inside an alpha soft mask.
pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa;
@@ -242,6 +243,32 @@ pub fn imports_of(bytes: &[u8]) -> usize {
IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0)
}
/// The notes on the fonts the file draws with that aren't available: type in a font the file
/// carries keeps its look until it is edited; the rest shows in the fallback font.
fn warn_missing_fonts(b: &mut Builder, doc: &Document) {
let mut bound = std::collections::HashSet::new();
doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for font in t.file_fonts_in_use() {
if t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some() {
bound.insert(font.family.clone());
}
}
}
});
let (carried, missing): (Vec<String>, Vec<String>) = std::mem::take(&mut b.missing_fonts).into_iter().partition(|family| bound.contains(family));
if !carried.is_empty() {
b.warn(&format!(
"fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): {}",
carried.join(", ")
));
}
if !missing.is_empty() {
let list = missing.join(", ");
b.warn(&format!("fonts that aren't available show in the fallback font until they are: {list}"));
}
}
/// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]).
fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator<Item = &'p craft_pdf::syntax::page::Page<'d>>) -> [f64; 4] {
pages.fold([0.0; 4], |widest, page| {
@@ -278,7 +305,7 @@ fn read_opened(
doc.artboards.clear();
doc.layers.clear();
let taken: Vec<String> = doc.swatches_iter().map(|s| s.name.clone()).chain(doc.swatch_groups.iter().map(|g| g.name.clone())).collect();
let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route);
let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route).with_embedded_fonts(opts.embedded_fonts);
// The art of a group that is off (drawn as `all_on` turned it on) or doesn't print mustn't
// show or print on its page's layer.
b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print);
@@ -437,6 +464,9 @@ fn read_opened(
// The groups' layers stack as the pages mark them (the art outside them stays where it was
// drawn): a group that first paints on a later page doesn't go on top of the others.
stack_groups(&mut slots, &order);
// The fonts the file carries for families that aren't available, kept with the document: the
// type set in them is drawn in them and spaced from the file's own widths.
let kept = std::mem::take(&mut b.file_glyphs).keep(&mut b.images);
for (n, slot) in slots.into_iter().enumerate() {
let mut layer = match slot {
Slot::Page(l) => *l,
@@ -447,6 +477,7 @@ fn read_opened(
},
};
if let Some(art) = layer.children_mut() {
keep_file_fonts(art, &b.lines, &kept, &b.images);
crate::import_lines::rebuild(art, &b.lines);
}
doc.layers.push(Arc::new(layer));
@@ -474,10 +505,7 @@ fn read_opened(
if b.colors.mixed {
b.warn("colours mixing several inks (DeviceN) were imported as RGB");
}
if !b.missing_fonts.is_empty() {
let list = b.missing_fonts.join(", ");
b.warn(&format!("fonts that aren't available show in the fallback font until they are: {list}"));
}
warn_missing_fonts(&mut b, &doc);
// Before anything walks the tree by recursion (`fix_next_id` does): nested clips can be deeper
// than the stack goes.
let mut depth_notes = vec![];
@@ -486,6 +514,7 @@ fn read_opened(
doc.reserve_ids(b.next);
let mut warnings = b.warnings;
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
if let Ok(v) = sink.lock() {
for w in v.iter() {
if !warnings.contains(w) {
+8
View File
@@ -3,6 +3,7 @@ use super::{
Affine, Arc, BezPath, BlendMode, Colors, Dash, Families, FillRule, FontNames, FunctionBudget, HashMap, HashSet, ImageBlob, LineCap, LineFacts,
LineJoin, LumaData, MaskSpec, Node, NodeId, Paint, PathEl, PatternDef, Rect, Scan, StrokeLayer, StrokeProps, TextAs, TextLine, TypeStroke,
};
use crate::import_fonts::FileFontGlyphs;
/// Decoded RGBA pixels, width, height and hayro's scale factors.
pub(super) type Decoded = (Vec<u8>, u32, u32, (f32, f32));
@@ -127,6 +128,8 @@ pub(super) struct Builder<'p> {
/// anything else drawn ([`Builder::flush_text`]).
pub(super) lost: Option<crate::import_text::LostFills>,
pub(super) text_as: TextAs,
/// Fonts the file embeds are kept (ImportOptions::embedded_fonts).
pub(super) embedded_fonts: bool,
pub(super) actual: super::actual_text::ActualText,
pub(super) images: HashMap<String, ImageBlob>,
pub(super) image_keys: HashMap<u128, (String, u32, u32)>,
@@ -150,6 +153,11 @@ pub(super) struct Builder<'p> {
pub(super) font_names: HashMap<u128, FontInfo>,
pub(super) families: Option<Families>,
pub(super) missing_fonts: Vec<String>,
/// The glyphs drawn in fonts the file carries for families that aren't available, for the
/// fonts kept with the document ([`crate::import_fonts`]).
pub(super) file_glyphs: FileFontGlyphs,
/// Font (cache key) → its font among `file_glyphs`; `None`: its type takes the font it names.
pub(super) file_fonts: HashMap<u128, Option<usize>>,
/// Font (cache key) → its characters by glyph, for CID-keyed fonts embedded without a
/// ToUnicode map.
pub(super) cid_text: HashMap<u128, Option<Arc<CidText>>>,
+162
View File
@@ -0,0 +1,162 @@
//! The fonts a PDF carries (embeds) for type whose fonts aren't available here: the glyphs it draws
//! in each, gathered as its pages are read, become one font per family and style, kept with the
//! document ([`vectorcraft_doc::FileFonts`]), that draws that type as the file did until its text
//! is edited. A file embeds its fonts so that it shows in them wherever it is read (Acrobat Help,
//! PDF fonts, <https://helpx.adobe.com/acrobat/using/pdf-fonts.html>).
//!
//! Each glyph comes as the interpreter draws it (an outline in thousandths of an em, whatever the
//! font program: Type 1, CFF or TrueType, simple or CID-keyed) with the width the file gives it, for
//! the character the file says it shows (its `ToUnicode` map, or what the import reads from the
//! font program). The first glyph of each character is kept; a line using a different glyph for
//! that character is imported as outlines instead.
use std::collections::HashMap;
use kurbo::BezPath;
use vectorcraft_doc::{FILE_FONT_MIME, ImageBlob};
use vectorcraft_text::{FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font};
/// The most glyphs gathered from one file, in all its fonts (an outline is some hundreds of bytes;
/// a CJK document uses a few thousand characters).
const MAX_GLYPHS: usize = 200_000;
/// The licence flags (OS/2 `fsType`) of `a` and `b` that allow less: a restricted font beats one
/// that may be embedded whole, which beats one that may be embedded as a subset. A font without
/// flags reads as print and preview (4), as a font built from it does.
fn stricter(a: Option<u16>, b: Option<u16>) -> Option<u16> {
use vectorcraft_text::embed::Embedding;
let rank = |f: Option<u16>| match Embedding::from_fs_type(f.unwrap_or(4)) {
Embedding::Subset => 0,
Embedding::Whole => 1,
Embedding::Forbidden => 2,
};
if rank(b) > rank(a) { b } else { a }
}
/// The glyphs gathered so far.
#[derive(Default)]
pub(crate) struct FileFontGlyphs {
fonts: Vec<Gathered>,
/// Each font (family and style) by its index in `fonts`.
index: HashMap<(String, String), usize>,
/// Glyphs gathered, in all.
count: usize,
}
/// The glyphs of one family and style.
struct Gathered {
family: String,
style: String,
info: FileFontInfo,
glyphs: Vec<FileGlyph>,
/// Each character's glyph, by its index in `glyphs`.
chars: HashMap<char, usize>,
}
impl FileFontGlyphs {
/// The font of `family` and `style` (made with `info` the first time): its index.
pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize {
if let Some(&i) = self.index.get(&(family.to_string(), style.to_string())) {
// Two programs of one family and style share one font here: it takes the stricter
// of their licence flags, so a restricted one's glyphs never read as permitted.
if let Some(g) = self.fonts.get_mut(i) {
g.info.fs_type = stricter(g.info.fs_type, info().fs_type);
}
return i;
}
let i = self.fonts.len();
self.fonts.push(Gathered { family: family.to_string(), style: style.to_string(), info: info(), glyphs: vec![], chars: HashMap::new() });
self.index.insert((family.to_string(), style.to_string()), i);
i
}
/// Does font `font` still want a glyph for `ch` (none gathered yet, and room for it)?
pub fn wants(&self, font: usize, ch: char) -> bool {
self.count < MAX_GLYPHS && self.fonts.get(font).is_some_and(|f| f.glyphs.len() < MAX_FILE_GLYPHS && !f.chars.contains_key(&ch))
}
/// Does font `font` hold a glyph for `ch` that differs from `outline` or `advance`? A font keeps
/// one glyph per character, so a file's other glyph for it (a stylistic alternate that maps to
/// the same character) can't go into it: the line it is on is kept as outlines instead.
pub fn conflicts(&self, font: usize, ch: char, outline: &BezPath, advance: f64) -> bool {
self.fonts
.get(font)
.and_then(|f| f.chars.get(&ch).and_then(|&i| f.glyphs.get(i)))
.is_some_and(|g| g.outline != *outline || g.advance != advance)
}
/// Gather `glyph` for font `font`.
pub fn add(&mut self, font: usize, glyph: FileGlyph) {
if !self.wants(font, glyph.ch) {
return;
}
if let Some(f) = self.fonts.get_mut(font) {
f.chars.insert(glyph.ch, f.glyphs.len());
f.glyphs.push(glyph);
self.count += 1;
}
}
/// The fonts built from gathered glyphs, stored under their content keys. Only text that
/// actually references one admits a runtime face, before it is respaced.
pub fn keep(self, images: &mut HashMap<String, ImageBlob>) -> HashMap<(String, String), String> {
let mut kept = HashMap::new();
for f in self.fonts {
let Some(bytes) = build_file_font(&f.info, &f.glyphs) else { continue };
let blob = ImageBlob::new(FILE_FONT_MIME, bytes);
let base = blob.content_key();
let mut key = base.clone();
let mut suffix = 1;
while images.get(&key).is_some_and(|held| held != &blob) {
key = format!("{base}-{suffix}");
suffix += 1;
}
images.entry(key.clone()).or_insert(blob);
kept.insert((f.family, f.style), key);
}
kept
}
}
/// What a font program the file embeds (`data`, a TrueType or OpenType file, or a bare CFF font)
/// says of the font's licence (OS/2 `fsType`) and its ascent and descent (thousandths of an em).
pub(crate) fn program_facts(data: &[u8], index: u32) -> (Option<u16>, Option<(f64, f64)>) {
use skrifa::MetadataProvider;
use skrifa::raw::TableProvider;
let Ok(f) = skrifa::FontRef::from_index(data, index) else { return (None, None) };
let fs_type = f.os2().ok().map(|o| o.fs_type());
let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default());
let k = 1000.0 / f64::from(m.units_per_em.max(1));
let (ascent, descent) = (f64::from(m.ascent) * k, f64::from(m.descent) * k);
let metrics = (ascent.is_finite() && descent.is_finite() && ascent > 0.0 && descent <= 0.0).then_some((ascent, descent));
(fs_type, metrics)
}
#[cfg(test)]
mod tests {
use super::*;
/// Two programs of one family and style are one font here, and its flags are the stricter
/// of theirs whichever came first (CodeRabbit, #4569).
#[test]
fn two_programs_of_one_font_keep_the_stricter_licence() {
for (first, second, want) in [
(Some(4), Some(2), Some(2)),
(Some(2), Some(4), Some(2)),
(None, Some(0x0200), Some(0x0200)),
(Some(4), Some(0x0108), Some(0x0108)),
(Some(0x0108), Some(2), Some(2)),
(Some(8), Some(4), Some(8)),
(None, None, None),
] {
let mut g = FileFontGlyphs::default();
let info = |fs_type| {
move || FileFontInfo { family: "F".into(), style: "R".into(), postscript: "F-R".into(), ascent: 800.0, descent: -200.0, fs_type }
};
let a = g.font("F", "R", info(first));
let b = g.font("F", "R", info(second));
assert_eq!(a, b);
assert_eq!(g.fonts[a].info.fs_type, want, "{first:?} then {second:?}");
}
}
}
+26 -2
View File
@@ -7,14 +7,14 @@
//! - area type comes as a line of point type per line, each wrapped line ending in a space. Lines
//! in a row sharing a left edge, font, size and leading (and paragraph spacing) are one area
//! type object again, aligned left or justified, where laying its text out in the frame breaks
//! it where the file does: else, as where its font isn't installed, they stay lines.
//! it where the file does; otherwise they stay lines. Carried fonts are used for this check.
use std::collections::HashMap;
use std::sync::Arc;
use kurbo::{Point, Rect, Shape};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::{AppearanceItem, CharStyle, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
use vectorcraft_doc::{AppearanceItem, CharStyle, FileFont, FileFonts, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
use vectorcraft_geom::shapes;
use crate::import_text::{LineFacts, median};
@@ -258,6 +258,30 @@ fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, wi
}
let mut t = (*first).clone();
t.runs = runs;
// The fonts the file carries that draw the lines draw them as one object too.
let mut fonts: Vec<FileFont> = vec![];
for f in texts.iter().flat_map(|(t, _)| t.file_fonts_in_use()) {
if !fonts.contains(f) {
fonts.push(f.clone());
}
}
t.file_fonts = (!fonts.is_empty()).then(|| {
let resources = fonts
.iter()
.take(vectorcraft_doc::text::MAX_FILE_FONTS)
.filter_map(|font| {
texts
.iter()
.find_map(|(line, _)| {
line.file_fonts_in_use().iter().any(|f| f.key == font.key).then(|| line.file_fonts.as_ref()?.face(&font.key)).flatten()
})
.map(|face| (font.key.clone(), face))
})
.collect();
let mut kept = FileFonts::new(fonts, &t.plain_text());
kept.bind(resources);
Box::new(kept)
});
t.para.justify = justify;
t.para.space_before = b.space;
let last = b.ys.last().copied()?;
+166 -88
View File
@@ -4,16 +4,19 @@
//! baseline, text rise, is baseline shift). Each glyph stays where the file drew it: the kerning
//! and tracking the type takes put it there (#722). Fonts are named from the file's base font name (its
//! subset prefix dropped, the family matched against the fonts available); a font that isn't
//! available keeps its name, and the text shows in the fallback font until it is.
//! available keeps its name. Where the file carries that font, its glyphs make a font kept with the
//! document ([`crate::import_fonts`]) that draws the type as the file did until its text is
//! edited ([`keep_file_fonts`]); otherwise the text shows in the fallback font until it is.
//!
//! Glyphs each turned a little further along a curve (type set on a path: apps write each glyph
//! with its own placement) make one type-on-a-path object, its path through the glyphs' baseline.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, LineCap, LineJoin, Node, ParaDirection, TextKind, TextObject, TextRun};
use vectorcraft_doc::{CharStyle, FileFont, FileFonts, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, TextKind, TextObject, TextRun};
use vectorcraft_text::TextLayout;
/// One glyph's placement: its baseline origin, advance direction, size and horizontal scale.
@@ -268,8 +271,13 @@ pub(crate) struct TextLine {
/// The strokes of its glyphs' outlines drawn between them, one per glyph with ink so far
/// (written right after the line).
pub held: Vec<Node>,
/// A glyph of the line is drawn in a font the file carries for a family that isn't available
/// ([`keep_file_fonts`]).
pub file_font: bool,
/// Whether this line holds Type 3 font glyphs.
pub has_type3: bool,
/// A glyph of the line differs from the one its font keeps for the same character ([`crate::import_fonts::FileFontGlyphs::conflicts`]).
pub file_conflict: bool,
}
/// Where the file put a glyph: the glyph's index in the line, and its advance in the file's font
@@ -368,6 +376,9 @@ pub(crate) struct LineFacts {
/// Horizontal point type: how long the file set it, from its first glyph's origin to the end
/// of its last glyph that isn't a space (points, along the baseline).
pub length: f64,
/// Set in a font the file carries for a family that isn't available: what its spacing is
/// measured from, to measure it again once that font is kept ([`keep_file_fonts`]).
pub respace: Option<Box<Spacing>>,
}
/// The most a glyph on a curve turns from the one before it (about 20°).
@@ -401,7 +412,9 @@ impl TextLine {
drawn_spaces: vec![],
drawn_space: None,
held: vec![],
file_font: false,
has_type3: false,
file_conflict: false,
}
}
@@ -1014,79 +1027,163 @@ impl TextLine {
let angle = self.at.dir.atan2();
// The glyphs' tops lean along the baseline (+x), up being -y in the type's own space.
t.xf = Affine::translate(self.at.origin.to_vec2()) * Affine::rotate(angle) * Affine::skew(-self.at.slant, 0.0);
let db = vectorcraft_text::FontDb::global();
// Each glyph where the file put it (#722): the kerning (the font's, or none) and tracking
// (one value for the line, or each character its own) that place them there.
let placed = (self.upright.is_none() && t.para.direction.is_none())
.then(|| place_each(&t, &self.slots, &self.baseline, path.as_ref(), self.at, self.at.size))
.flatten()
.map(|(runs, laid)| {
t.runs = runs;
laid.bounds
});
if let Some(path) = path {
// Evenly spaced type keeps its length along the path: the path runs through the
// glyphs' origins, one curve each, to the end of the last glyph, and tracking makes up
// the difference from the advances.
if placed.is_none() {
let length: f64 = path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum();
let laid = vectorcraft_text::layout(db, &t);
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
let size = self.at.size;
if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size, spacing_em(&t, size));
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
}
}
t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None };
t.xf = Affine::IDENTITY;
t.cached_bounds = Some(vectorcraft_text::layout(db, &t).bounds);
return Some((t, self.opacity, facts));
}
let (start, along) = match self.upright {
// How far along the line the file put each glyph: along the path through them (one curve
// each), or along the baseline from the line's origin.
let along: Vec<f64> = match &path {
Some(bp) => std::iter::once(0.0)
.chain(bp.segments().scan(0.0, |d, seg| {
*d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3);
Some(*d)
}))
.take(self.baseline.len())
.collect(),
None => self.baseline.iter().map(|p| (*p - self.at.origin).dot(self.at.dir)).collect(),
};
// Evenly spaced type on a path keeps its length along the path: the path runs through the
// glyphs' origins, one curve each, to the end of the last glyph.
let path_length =
path.as_ref().map(|path| path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum());
let start = match self.upright {
// Vertical point type (a column, or a single upright glyph) is anchored at the top
// centre of its first em box.
Some(u) => {
Some(u) if path.is_none() => {
t.vertical = true;
t.xf = Affine::translate(u.top.to_vec2()) * Affine::rotate(angle);
(self.at.origin, -self.at.up())
-self.at.up()
}
_ => (self.at.origin, self.at.dir),
_ => self.at.dir,
};
// Tracking that makes the line as long as in the file: the PDF placed each glyph, the
// layout sets them by their advances. Spread over the gaps between characters (tracking
// follows each character, the last one's past the end of the line). A horizontal line is
// measured to its last glyph that isn't a space: the spaces after it were dropped.
let length = (if t.vertical { self.next } else { self.visible } - start).dot(along);
if !t.vertical {
// A horizontal line is measured to its last glyph that isn't a space (the spaces after it
// were dropped), a column to the end of its last glyph.
let length = (if t.vertical { self.next } else { self.visible } - self.at.origin).dot(start);
if path.is_none() && !t.vertical {
facts.length = length;
}
// Placed glyph by glyph: laid out so already.
if let Some(bounds) = placed {
t.cached_bounds = Some(bounds);
return Some((t, self.opacity, facts));
if let Some(path) = &path {
t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(path), start: 0.0, end: None };
t.xf = Affine::IDENTITY;
}
let laid = vectorcraft_text::layout(db, &t);
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
let size = self.at.size;
let mut bounds = laid.bounds;
if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
// The spaces read from gaps or drawn between glyphs keep their own place only in text
// left in the file's order.
let total: usize = t.runs.iter().map(|r| r.text.len()).sum();
let gaps: Vec<(usize, f64)> = if t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] };
let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size, spacing_em(&t, size));
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
// Tracked: laid out again for its bounds.
bounds = vectorcraft_text::layout(db, &t).bounds;
// The spaces read from gaps or drawn between glyphs keep their own place only in a line
// left in the file's order (not along a path).
let total: usize = t.runs.iter().map(|r| r.text.len()).sum();
let gaps: Vec<(usize, f64)> =
if path.is_none() && t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] };
let s = Spacing {
runs: t.runs.clone(),
slots: std::mem::take(&mut self.slots),
// Glyph by glyph only in horizontal type in the file's order.
along: (self.upright.is_none() && t.para.direction.is_none()).then_some(along),
slant: if path.is_some() { 0.0 } else { self.at.slant },
size: self.at.size,
length: path_length.unwrap_or(length),
gaps,
};
space_line(&mut t, &s);
// Set in a font the file carries for a family that isn't available: spaced again once that
// font is kept with the document ([`keep_file_fonts`]).
if self.file_font {
facts.respace = Some(Box::new(s));
}
t.cached_bounds = Some(bounds);
Some((t, self.opacity, facts))
}
}
/// What a line's spacing is measured from: where the file put its glyphs. Kept with a line set in
/// a font the file carries for a family that isn't available ([`LineFacts::respace`]), to be
/// measured again against that font once it is kept with the document ([`keep_file_fonts`]).
#[derive(Clone, Debug)]
pub(crate) struct Spacing {
/// The line's runs, unspaced.
runs: Vec<TextRun>,
/// Where the file put each character ([`TextLine::slots`]).
slots: Vec<Option<Slot>>,
/// How far along the line (or its path) the file put each glyph (points); `None` when the
/// glyphs aren't placed one by one (vertical type, type in visual order).
along: Option<Vec<f64>>,
/// The type's slant ([`Placement::slant`]; 0 on a path).
slant: f64,
size: f64,
/// How long the file set the line (points): along its path, to the end of a column, or to
/// the last glyph of a horizontal line that isn't a space.
length: f64,
/// The spaces read from gaps or drawn between glyphs: byte offset, width (points).
gaps: Vec<(usize, f64)>,
}
/// Space `t` (whose runs are `s`'s, unspaced) as the file did ([`Spacing`]): each glyph where the
/// file put it (#722) with the kerning (the font's, or none) and tracking (one value for the line,
/// or each character its own) that place them there ([`place_each`]); else tracking that makes
/// the line as long as in the file (the PDF placed each glyph, the layout sets them by their
/// advances), spread over the gaps between characters (tracking follows each character, the last
/// one's past the end of the line). Its bounds are laid out too.
fn space_line(t: &mut TextObject, s: &Spacing) {
let db = vectorcraft_text::FontDb::global();
t.runs = s.runs.clone();
let on_path = !matches!(t.kind, TextKind::Point);
// Measured as point type: type on a path stops at the path's end, which tracking moves.
let point = |t: &TextObject| TextObject { kind: TextKind::Point, ..t.clone() };
let placed = s.along.as_ref().and_then(|along| place_each(&point(t), &s.slots, along, s.slant, s.size));
if let Some((runs, laid)) = placed {
t.runs = runs;
t.cached_bounds = Some(if on_path { vectorcraft_text::layout(db, t).bounds } else { laid.bounds });
return;
}
let laid = vectorcraft_text::layout(db, &point(t));
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
let mut bounds = (!on_path).then_some(laid.bounds);
if chars > 1 && s.length.is_finite() && (s.length - natural).abs() > s.size * 0.01 {
let (tracking, spaces) = spacing(&laid, &s.gaps, s.length - natural, chars, s.size, spacing_em(t, s.size));
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
// Tracked: laid out again for its bounds.
bounds = None;
}
t.cached_bounds = Some(bounds.unwrap_or_else(|| vectorcraft_text::layout(db, t).bounds));
}
/// The type among `nodes` (and in their groups) set in fonts the file carries for families that
/// aren't available, now kept with the document as `kept` (family and style → the font's blob):
/// drawn in them while its text is the file's ([`vectorcraft_doc::FileFonts`]), and spaced again
/// from where the file put each glyph, measured against the file's own widths (not the stand-in's,
/// which differ, #3756).
pub(crate) fn keep_file_fonts(
nodes: &mut [Arc<Node>],
lines: &HashMap<NodeId, LineFacts>,
kept: &HashMap<(String, String), String>,
images: &HashMap<String, vectorcraft_doc::ImageBlob>,
) {
if kept.is_empty() {
return;
}
for n in nodes.iter_mut() {
if n.children().is_some_and(|c| !c.is_empty())
&& let Some(children) = Arc::make_mut(n).children_mut()
{
keep_file_fonts(children, lines, kept, images);
}
let Some(s) = lines.get(&n.id).and_then(|f| f.respace.as_deref()) else { continue };
let mut fonts: Vec<FileFont> = vec![];
for r in &s.runs {
let (family, style) = (&r.style.font_family, &r.style.font_style);
if let Some(key) = kept.get(&(family.clone(), style.clone()))
&& !fonts.iter().any(|f| f.family == *family && f.style == *style)
{
fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() });
}
}
if fonts.is_empty() {
continue;
}
if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind {
let text: String = s.runs.iter().map(|r| r.text.as_str()).collect();
t.file_fonts = Some(Box::new(FileFonts::new(fonts, &text)));
// A blob reference is not ownership until its actual document resource is bound.
vectorcraft_text::FontDb::global().bind_file_fonts(t, |key| images.get(key));
space_line(t, s);
}
}
}
/// Where along the line (points) layout `laid` puts each character at a byte offset of `chars`
/// (in order), and its advance: `None` for one inside another's cluster. Text in the file's order
/// (left to right).
@@ -1142,21 +1239,14 @@ fn restyled(t: &TextObject, kern: Option<f64>, own: &[f64]) -> Vec<TextRun> {
/// file's widths (not the font's advances, which may be a hair off them) and kept on course where
/// the differences add up ([`on_course`]).
///
/// The file put the glyph of each character with a [`Slot`] at `baseline` (one origin per glyph),
/// measured along `path` (type on a path: one curve per glyph) or along `line`'s baseline from its
/// origin, where a character shifted off it by its baseline shift draws that shift times `line`'s
/// slant further along (the type's skew leans it so, as the file's text rise did). `None` when the
/// font laid out isn't the file's (its advances differ from the file's): spacing measured against
/// a stand-in's widths would keep the stand-in's differences once the font is installed; or when
/// the glyphs can't be placed so (the layout joins characters the file drew apart).
fn place_each(
t: &TextObject,
slots: &[Option<Slot>],
baseline: &[Point],
path: Option<&BezPath>,
line: Placement,
size: f64,
) -> Option<(Vec<TextRun>, TextLayout)> {
/// The file put the glyph of each character with a [`Slot`] `along` the line (points from its
/// origin, or along its path), where a character shifted off the baseline by its baseline shift
/// draws that shift times `slant` further along (the type's skew leans it so, as the file's text
/// rise did). `None` when the font laid out isn't the file's (its advances differ from the file's):
/// spacing measured against a stand-in's widths would keep the stand-in's differences once the
/// font is installed; or when the glyphs can't be placed so (the layout joins characters the file
/// drew apart).
fn place_each(t: &TextObject, slots: &[Option<Slot>], along: &[f64], slant: f64, size: f64) -> Option<(Vec<TextRun>, TextLayout)> {
let chars: Vec<usize> = t
.runs
.iter()
@@ -1170,20 +1260,8 @@ fn place_each(
if chars.len() < 2 || chars.len() != slots.len() || t.runs.iter().any(|r| r.inline.is_some()) {
return None;
}
// How far along the line the file put each glyph.
let along: Vec<f64> = match path {
Some(bp) => std::iter::once(0.0)
.chain(bp.segments().scan(0.0, |d, seg| {
*d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3);
Some(*d)
}))
.take(baseline.len())
.collect(),
None => baseline.iter().map(|p| (*p - line.origin).dot(line.dir)).collect(),
};
// Each character's baseline shift, which the type's slant draws `slant` times as far along.
let shifts: Vec<f64> = t.runs.iter().flat_map(|r| r.text.chars().map(move |_| r.style.baseline_shift)).collect();
let slant = if path.is_some() { 0.0 } else { line.slant };
// Each character's target: where the file put it, if it put it anywhere.
let target: Vec<Option<(f64, Option<f64>)>> =
slots.iter().zip(&shifts).map(|(s, shift)| s.and_then(|s| Some((*along.get(s.glyph)? - slant * shift, s.advance)))).collect();
+6
View File
@@ -51,6 +51,7 @@ mod forms;
mod images;
mod import;
mod import_color;
mod import_fonts;
mod import_image;
mod import_lines;
mod import_mask;
@@ -151,6 +152,10 @@ pub struct ImportOptions {
/// The file is an editor's own document (`.ai`): RGB in its `ICCBased` spaces keeps its numbers
/// (see `Colors::uncalibrated_rgb`). Off for PDFs, whose profiles stand.
pub uncalibrated_rgb: bool,
/// Type in a font the file embeds and this machine lacks is drawn in glyphs built from the
/// file's own, kept with the document (default); off, it is set in the fallback font, with the
/// missing-font warning, as before.
pub embedded_fonts: bool,
}
impl Default for ImportOptions {
@@ -164,6 +169,7 @@ impl Default for ImportOptions {
text_as: TextAs::default(),
layers: true,
uncalibrated_rgb: false,
embedded_fonts: true,
}
}
}
+1
View File
@@ -20,6 +20,7 @@ mod dashalign;
mod diamond;
mod editing;
mod encrypt;
mod file_fonts;
mod file_info;
mod focal;
mod fx;
+2 -2
View File
@@ -1547,7 +1547,7 @@ fn gray_freeform_points_are_written_as_black_ink_in_a_cmyk_document() {
#[test]
fn press_quality_writes_an_rgb_image_in_a_cmyk_document_as_cmyk() {
let rgb = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([(x * 60) as u8, (y * 60) as u8, 128]));
let blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None };
let blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None, file_font: Default::default() };
let d = image_doc(blob, 4, 4);
let press = builtin_presets().into_iter().find(|p| p.name == "Press Quality").unwrap().settings;
assert_eq!(press.output.conversion, ColorConversion::PreserveNumbers);
@@ -1569,7 +1569,7 @@ fn press_quality_writes_cmyk_in_an_rgb_document_too() {
let ink = [0u8, 102, 255, 0];
let tiff = ImageBlob::cmyk_tiff(&Inks::new(4, 4, flat(ink, 16)).unwrap()).unwrap();
let rgb = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([(x * 60) as u8, (y * 60) as u8, 128]));
let png_blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None };
let png_blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None, file_font: Default::default() };
for (what, blob) in [("CMYK image", tiff), ("RGB image", png_blob)] {
let mut d = image_doc(blob, 4, 4);
d.color_mode = ColorMode::Rgb;
+4 -2
View File
@@ -343,7 +343,8 @@ fn separations_colorize_masked_pixels_whose_own_pixels_are_a_preview() {
let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 };
let mut d = doc(ColorMode::Cmyk, Some(spot));
let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
d.images
.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let img =
craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255])
.unwrap();
@@ -379,7 +380,8 @@ fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() {
let placeholder = || {
let mut d = doc(ColorMode::Cmyk, None);
let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
d.images
.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
d
};
let plain = placeholder();
+276
View File
@@ -0,0 +1,276 @@
//! Type in a font the PDF carries for a family that isn't installed keeps the file's glyphs and
//! their places until its text is edited ([`vectorcraft_doc::FileFonts`]): drawn as it is in the
//! same PDF whose font is installed, saved and read back so, and in the substitute once edited.
use craft_pdf::write::backend as krilla;
use krilla::geom::Point as KPoint;
use krilla::page::PageSettings;
use krilla::text::{Font, GlyphId, KrillaGlyph, TextDirection};
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject};
use vectorcraft_text::{FontDb, FontMatch};
use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif};
use crate::*;
/// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes.
const LINES: &[(f32, f32, f32, &str)] =
&[(20.0, 40.0, 24.0, "AVATAR Toyota"), (20.0, 80.0, 11.0, "Wavy quartz jumps over 12 lazy dogs."), (20.0, 120.0, 30.0, "Ky Wo")];
/// A line set glyph by glyph, each 2 pt further on than its advance (as `Tc` or `TJ` set it).
const SPACED: (f32, f32, f32, &str) = (20.0, 160.0, 14.0, "Spaced out");
/// A page of [`LINES`] and [`SPACED`] in `font` (Source Serif 4 or a renamed copy), written as
/// writers write type: a subset of the font embedded as a CID-keyed TrueType font (Identity-H) with
/// a ToUnicode map.
fn page_pdf(font: Vec<u8>) -> Vec<u8> {
let mut pdf = krilla::Document::new();
let mut page = pdf.start_page_with(PageSettings::from_wh(400.0, 200.0).unwrap());
let mut s = page.surface();
let kfont = Font::new(font.into(), 0).unwrap();
for &(x, y, size, text) in LINES {
s.draw_text(KPoint::from_xy(x, y), kfont.clone(), size, text, false, TextDirection::Auto);
}
let face = FontDb::global().face("Source Serif 4", "Regular").unwrap();
let (x, y, size, text) = SPACED;
let glyphs: Vec<KrillaGlyph> = text
.char_indices()
.map(|(i, c)| {
let g = face.glyph_for(c);
let advance = face.advance(g) / face.units_per_em() + 2.0 / f64::from(size);
KrillaGlyph::new(GlyphId::new(g), advance as f32, 0.0, 0.0, 0.0, i..i + c.len_utf8(), None)
})
.collect();
s.draw_glyphs(KPoint::from_xy(x, y), &glyphs, kfont, text, size, false);
s.finish();
page.finish();
pdf.finish().unwrap()
}
fn import(bytes: &[u8]) -> ImportReport {
import_with_report(bytes, &ImportOptions::default()).unwrap()
}
/// A drawn line: its text, and its glyphs' origins and ink boxes (document space).
type DrawnLine = (String, Vec<(Point, Option<Rect>)>);
/// Each line `db` lays the type of `d` out in ([`DrawnLine`]), sorted by text.
fn drawn(db: &FontDb, d: &Document) -> Vec<DrawnLine> {
let mut out = vec![];
for t in texts(d) {
let lay = vectorcraft_text::layout(db, &t);
let plain = t.plain_text();
for (i, line) in lay.lines.iter().enumerate() {
let glyphs = lay
.glyphs
.iter()
.filter(|g| g.line == i)
.map(|g| {
let ink = (!g.outline.elements().is_empty()).then(|| (t.xf * g.outline.clone()).bounding_box());
(t.xf * g.origin, ink)
})
.collect();
out.push((plain[line.start..line.end].trim().to_string(), glyphs));
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// The largest distance between the glyphs of `a` and `b`, line by line (their texts the same).
fn farthest(a: &[DrawnLine], b: &[DrawnLine]) -> f64 {
assert_eq!(a.iter().map(|l| &l.0).collect::<Vec<_>>(), b.iter().map(|l| &l.0).collect::<Vec<_>>(), "the same lines");
let mut far: f64 = 0.0;
for ((text, ga), (_, gb)) in a.iter().zip(b) {
assert_eq!(ga.len(), gb.len(), "{text}");
for ((pa, ia), (pb, ib)) in ga.iter().zip(gb) {
far = far.max((*pa - *pb).hypot());
match (ia, ib) {
(Some(ia), Some(ib)) => {
far = far.max((ia.x0 - ib.x0).abs().max((ia.x1 - ib.x1).abs()).max((ia.y0 - ib.y0).abs()).max((ia.y1 - ib.y1).abs()))
}
(None, None) => {}
_ => panic!("{text}: ink on one side only"),
}
}
}
far
}
fn text_of<'a>(d: &'a [TextObject], text: &str) -> &'a TextObject {
d.iter()
.find(|t| t.plain_text() == text)
.unwrap_or_else(|| panic!("no `{text}` among {:?}", d.iter().map(TextObject::plain_text).collect::<Vec<_>>()))
}
#[test]
fn type_in_a_font_the_file_carries_keeps_its_glyphs_and_places() {
let db = FontDb::global();
let installed = import(&page_pdf(SOURCE_SERIF.to_vec()));
let carried = import(&page_pdf(uninstalled_serif()));
let t = texts(&carried.document);
assert_eq!(t.len(), LINES.len() + 1, "a line stays a line: {:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
// Named by the file's font, which stays missing (Find Font and the Missing Fonts dialog list it).
let st = text_of(&t, "AVATAR Toyota").first_style();
assert_eq!(st.font_family, "Source Serif 9");
assert_eq!(db.resolve(&st.font_family, &st.font_style).map(|(_, m)| m), Some(FontMatch::Missing));
// Drawn as the same file whose font is installed: the file's glyphs, where the file put them.
let far = farthest(&drawn(db, &carried.document), &drawn(db, &installed.document));
assert!(far < 0.02, "glyphs {far} pt off the installed font's");
// Every glyph from the font the file carries, which the document keeps.
for t in &t {
let lay = vectorcraft_text::layout(db, t);
assert!(lay.glyphs.iter().all(|g| db.is_file_font(g.font_id)), "{}", t.plain_text());
let key = &t.file_fonts.as_ref().unwrap().fonts[0].key;
assert_eq!(carried.document.images[key].mime, FILE_FONT_MIME);
}
assert_eq!(carried.document.images.values().filter(|b| b.mime == FILE_FONT_MIME).count(), 1, "one font for the family and style");
// Where the file put them: the ink is the file's own glyphs' (read as outlines).
let as_outlines = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap();
let ink = drawn(db, &carried.document).iter().flat_map(|(_, g)| g.iter().filter_map(|(_, i)| *i)).reduce(|a, b| a.union(b)).unwrap();
let file = outlines(&as_outlines.document).bounding_box();
let off = (ink.x0 - file.x0).abs().max((ink.x1 - file.x1).abs()).max((ink.y0 - file.y0).abs()).max((ink.y1 - file.y1).abs());
assert!(off < 0.05, "{ink:?} vs the file's {file:?}");
// Spacing measured from the file's widths, as with the font installed (not a stand-in's, #3756).
let tracking = |d: &Document| text_of(&texts(d), "Spaced out").first_style().tracking;
assert!(
(tracking(&carried.document) - tracking(&installed.document)).abs() < 1.0,
"{} vs {}",
tracking(&carried.document),
tracking(&installed.document)
);
assert!(carried.warnings.iter().any(|w| w.contains("Source Serif 9") && w.contains("until their text is edited")), "{:?}", carried.warnings);
}
#[test]
fn edited_type_takes_the_substitute_and_unedited_type_keeps_the_files_font() {
let db = FontDb::global();
let carried = import(&page_pdf(uninstalled_serif()));
let t = text_of(&texts(&carried.document), "AVATAR Toyota").clone();
let from_file = |t: &TextObject| vectorcraft_text::layout(db, t).glyphs.iter().filter(|g| db.is_file_font(g.font_id)).count();
assert_eq!(from_file(&t), vectorcraft_text::layout(db, &t).glyphs.len(), "every glyph");
// Moved or resized, the text is the file's: still its font.
let mut moved = t.clone();
moved.xf = kurbo::Affine::translate((40.0, 10.0)) * moved.xf;
for r in &mut moved.runs {
r.style.size *= 2.0;
}
assert!(from_file(&moved) > 0);
// Edited: the substitute (the run still names the missing font).
let mut edited = t.clone();
edited.runs[0].text.insert(0, 'Z');
assert!(edited.file_fonts_in_use().is_empty());
assert_eq!(from_file(&edited), 0);
assert_eq!(edited.first_style().font_family, "Source Serif 9");
// Undone, the file's again.
edited.runs[0].text.remove(0);
assert_eq!(from_file(&edited), from_file(&t));
}
#[test]
fn a_font_that_is_installed_keeps_drawing_its_type() {
// With the family installed nothing is kept: the type is set in the installed font as before.
let installed = import(&page_pdf(SOURCE_SERIF.to_vec()));
assert!(!installed.document.images.values().any(|b| b.mime == FILE_FONT_MIME));
assert!(texts(&installed.document).iter().all(|t| t.file_fonts.is_none()));
}
/// `ImportOptions::embedded_fonts` on (the default): type in an embedded font the machine lacks
/// carries the file's glyphs (a font blob kept with the document) and the text keeps naming the
/// file's font.
#[test]
fn embedded_fonts_on_keeps_the_files_glyphs() {
let r = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { embedded_fonts: true, ..Default::default() }).unwrap();
assert!(r.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "a font kept with the document");
assert!(texts(&r.document).iter().any(|t| t.file_fonts.is_some()), "its type draws in the file's font");
}
/// Off (Preferences › File Handling › Use fonts embedded in imported PDFs): import behaves as it
/// did without the feature: no font is kept, the type is set in the fallback font and the missing
/// font is warned about.
#[test]
fn embedded_fonts_off_sets_type_in_the_fallback_font_with_the_warning() {
let r = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { embedded_fonts: false, ..Default::default() }).unwrap();
assert!(!r.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font kept");
assert!(texts(&r.document).iter().all(|t| t.file_fonts.is_none()), "no type draws in a file font");
assert!(r.warnings.iter().any(|w| w.contains("Source Serif 9")), "the missing font is named: {:?}", r.warnings);
let st = texts(&r.document)[0].first_style().clone();
assert_eq!(st.font_family, "Source Serif 9", "the text still names the file's font");
}
/// A page with the glyph of `a`, then of `b`, then of `a` again, each on its own line and each
/// named `a` by the ToUnicode map: two different glyphs of the embedded font for one character.
fn two_glyphs_pdf() -> Vec<u8> {
let face = FontDb::global().face("Source Serif 4", "Regular").unwrap();
let mut pdf = krilla::Document::new();
let mut page = pdf.start_page_with(PageSettings::from_wh(400.0, 200.0).unwrap());
let mut s = page.surface();
let font = Font::new(uninstalled_serif().into(), 0).unwrap();
// Glyph `from` standing for the character "a", on its own line at y.
let mut draw = |y: f32, from: char| {
let g = KrillaGlyph::new(GlyphId::new(face.glyph_for(from)), 0.5, 0.0, 0.0, 0.0, 0..1, None);
s.draw_glyphs(KPoint::from_xy(20.0, y), &[g], font.clone(), "a", 30.0, false);
};
draw(40.0, 'a');
draw(100.0, 'b');
draw(160.0, 'a');
s.finish();
page.finish();
pdf.finish().unwrap()
}
/// The ink box of the glyph on each of the page's three lines (set at 40, 100 and 160 pt from the
/// top) as `d` draws it: type laid out by `db` and outline paths, which an import may merge into
/// one path for the page, so their subpaths are told apart by the line they lie on.
fn glyph_ink(db: &FontDb, d: &Document) -> Vec<Rect> {
let mut lines: [Option<Rect>; 3] = [None; 3];
let mut add = |path: &kurbo::BezPath| {
let mut start = 0;
let els = path.elements();
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
let line = usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0);
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
start = end;
}
};
for t in texts(d) {
for g in vectorcraft_text::layout(db, &t).glyphs {
add(&(t.xf * g.outline.clone()));
}
}
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Path { path, .. } = &n.kind {
add(&path.to_bezpath());
}
});
lines.into_iter().flatten().collect()
}
/// Two different glyphs of the embedded font that map to one character (a normal and an alternate
/// `a`, here the glyphs of `a` and `b` both named `a` by the ToUnicode map) can't both go into the
/// font kept with the document, which has one glyph per character: the line with the other glyph is
/// kept as outlines. Each glyph is the one the file draws, where it draws it: the outlines of the same page
/// imported as outlines are the reference (the save and reopen half is `two_glyphs_for_one_character_survive_a_native_save_and_reopen` in the engine).
#[test]
fn two_glyphs_for_one_character_both_survive_import() {
let db = FontDb::global();
let bytes = two_glyphs_pdf();
let reference = glyph_ink(db, &import_with_report(&bytes, &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap().document);
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "and the first and third are the same glyph: {reference:?}");
let imported = import(&bytes).document;
let text: Vec<String> = texts(&imported).iter().map(|t| t.plain_text()).collect();
assert!(text.iter().any(|t| t == "a"), "the glyphs the font keeps stay live type: {text:?}");
assert!(text.len() < 3, "the line with the other glyph is not live type: {text:?}");
let close = |got: &[Rect], what: &str| {
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
for (got, want) in got.iter().zip(&reference) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
}
};
close(&glyph_ink(db, &imported), "imported");
}
+4 -4
View File
@@ -10,7 +10,7 @@ use vectorcraft_doc::{Document, NodeKind, TextObject};
use crate::*;
const SOURCE_SANS: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf");
const SOURCE_SERIF: &[u8] = include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf");
pub(crate) const SOURCE_SERIF: &[u8] = include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf");
/// A 300 × 200 pt page with `lines` of (x, y from the top, size, text) in Source Sans 3, and the
/// same rotated 90° when `rotated`.
@@ -33,7 +33,7 @@ pub(crate) fn text_pdf(lines: &[(f32, f32, f32, &str)], rotated: bool) -> Vec<u8
pdf.finish().unwrap()
}
fn texts(d: &Document) -> Vec<TextObject> {
pub(crate) fn texts(d: &Document) -> Vec<TextObject> {
let mut v = vec![];
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
@@ -294,7 +294,7 @@ fn uninstalled_font() -> Vec<u8> {
/// Source Serif 4 renamed `SourceSerif9-Regular`, family Source Serif 9: a serif font that isn't
/// installed (the fallback font, Source Sans 3, is a sans).
fn uninstalled_serif() -> Vec<u8> {
pub(crate) fn uninstalled_serif() -> Vec<u8> {
renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif9"), ("Source Serif 4", "Source Serif 9")])
}
@@ -310,7 +310,7 @@ fn one_line_pdf(font: Vec<u8>, text: &str) -> Vec<u8> {
}
/// The outlines text imported as (`textAs: outlines`), as one path.
fn outlines(d: &Document) -> kurbo::BezPath {
pub(crate) fn outlines(d: &Document) -> kurbo::BezPath {
let mut all = kurbo::BezPath::new();
d.walk(|n| {
if let NodeKind::Path { path, .. } = &n.kind {
+1 -1
View File
@@ -284,7 +284,7 @@ fn colorize_dims_with_the_grays() {
fn a_colorized_missing_link_placeholder_draws_in_its_own_colors() {
let proxy = |bytes: Vec<u8>| {
let bytes = std::sync::Arc::new(bytes);
ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }
ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }
};
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let sharp = RenderOptions { smooth_images: false, ..Default::default() };
+49
View File
@@ -75,6 +75,55 @@ fn type_redraws_when_its_font_becomes_available() {
assert_eq!(after, Renderer::new().render(&d, 300, 150, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it");
}
/// Same serialized text and node ids are not the same glyph geometry when each document owns
/// different file-font bytes. Both fonts are bound before either render, so generation is steady.
#[test]
fn file_font_geometry_is_scoped_to_owned_resources_not_serialized_keys() {
use vectorcraft_doc::{FILE_FONT_MIME, FileFont, FileFonts, ImageBlob};
use vectorcraft_text::{FileFontInfo, FileGlyph, FontDb, build_file_font};
let _adding = adding_fonts();
let make = |width| {
const FAMILY: &str = "Rendered Owned File Font Regression";
let info = FileFontInfo { family: FAMILY.into(), style: "Regular".into(), ..Default::default() };
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
let mut doc = Document::new(100.0, 100.0);
doc.images.insert("chosen".into(), ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap()));
let style = CharStyle { size: 60.0, font_family: FAMILY.into(), ..Default::default() };
let mut t = TextObject::point(Point::new(10.0, 70.0), "x", style);
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: FAMILY.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
let id = doc.alloc_id();
let layer = doc.layers[0].id;
doc.insert(Some(layer), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
assert!(FontDb::global().bind_document_file_fonts(&mut doc).is_empty());
doc
};
let (a, b) = (make(200.0), make(800.0));
let renderer = with_fonts_unchanged(|| {
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let mut reused = Renderer::new();
let first = reused.render(&a, 100, 100, Affine::IDENTITY, &opts).pixels;
let second = reused.render(&b, 100, 100, Affine::IDENTITY, &opts).pixels;
let fresh = Renderer::new().render(&b, 100, 100, Affine::IDENTITY, &opts).pixels;
assert_ne!(first, second, "B must draw its own wider glyph");
assert_eq!(second, fresh, "a renderer must not reuse A's glyph geometry for B");
reused
});
let mut faces = vec![];
for doc in [&a, &b] {
doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
faces.extend(FontDb::global().file_faces(t).into_iter().flatten().map(|face| Arc::downgrade(&face)));
}
});
}
assert_eq!(faces.len(), 2);
drop(a);
drop(b);
assert!(!renderer.texts.is_empty(), "the idle renderer still holds its old text nodes");
assert!(faces.iter().all(|face| face.upgrade().is_none()), "geometry-cache nodes must not pin document font allowance");
}
/// Type with raster effects redraws in a font that becomes available: its drop shadow and its
/// blurred content are made again.
#[test]
+8 -4
View File
@@ -166,18 +166,22 @@ pub(crate) fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeo
_ => spans.push((run, start, end)),
}
};
// Per run: is its family missing, and the face its glyphs should come from.
// Per run: is its family missing, and the face its glyphs should come from. A run drawn in a
// font its file carried isn't substituted: its glyphs come from that font.
let file = db.file_faces(t);
let faces: Vec<(bool, Option<u32>)> = t
.runs
.iter()
.map(|r| match db.resolve(&r.style.font_family, &r.style.font_style) {
.enumerate()
.map(|(i, r)| match (file.get(i).and_then(Option::as_ref), db.resolve(&r.style.font_family, &r.style.font_style)) {
(Some(f), _) => (false, Some(f.id())),
// The version the type names, when it's installed (see `FontDb::face_version`), at its
// Variable Font settings (see `FontDb::style_face`).
Some((f, m)) => {
(None, Some((f, m))) => {
let face = db.style_face(&r.style).unwrap_or(f);
(m == vectorcraft_text::FontMatch::Missing, Some(face.id()))
}
None => (true, None),
(None, None) => (true, None),
})
.collect();
let (mut substituted_fonts, mut substituted_glyphs, mut alternate_candidates) = (BezPath::new(), BezPath::new(), vec![]);
+1
View File
@@ -10,6 +10,7 @@ workspace = true
[dependencies]
craft-svg = { workspace = true }
craft-xml = { workspace = true }
craft-mime = { workspace = true }
# Which paths stored in documents may be opened.
craft-docpath = { workspace = true }
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more