Merge main into feat/object-mosaic-dialog

This commit is contained in:
dotCooCoo
2026-11-18 07:31:04 -08:00
31 changed files with 2678 additions and 252 deletions
Generated
+15
View File
@@ -1044,6 +1044,20 @@ name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3"
dependencies = [
"harfrust 0.13.3",
"kurbo 0.13.1",
"skrifa 0.47.0",
"thiserror 2.0.21",
"unicode-bidi",
"unicode-segmentation",
"windows-registry",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -7109,6 +7123,7 @@ dependencies = [
name = "vectorcraft-text"
version = "0.24.1"
dependencies = [
"craft-font-catalog",
"craft-proof",
"harfrust 0.13.3",
"icu_segmenter",
+30
View File
@@ -312,6 +312,36 @@ impl Carry {
}
}
/// Undo the actual maps of already placed gradients. Failure only changes this temporary
/// appearance; callers retain the stored row unchanged when a map cannot be inverted.
pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> {
for step in self.0.iter().rev() {
for item in &mut ap.items {
if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) {
continue;
}
let map = match *step {
CarryStep::Affine { m, .. } => m,
CarryStep::Boxes { from, to } => match item {
AppearanceItem::Fill(_) => crate::reshape::box_map(from, to),
AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)),
},
};
if vectorcraft_doc::node::flattens(map) {
return None;
}
let inverse = map.inverse();
if !inverse.is_finite() {
return None;
}
if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() {
g.transform(inverse);
}
}
}
Some(())
}
pub(crate) fn push(&mut self, more: Carry) {
self.0.extend(more.0);
self.1.extend(more.1);
+79 -25
View File
@@ -846,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
take_held_guides(n, held, out, false, false);
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
/// the members (after a clipping path) or above them, as its contents slot says. Its
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
/// it gives each copy those raster effects ([`copied_container`]).
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
struct PreparedContainer {
m: Node,
guides: Vec<Arc<Node>>,
paint: bool,
carry: crate::Carry,
}
/// The existing container pass up to its own rows becoming art. Keep its carried appearance for
/// rendering, and retain the same Carry for freezing only missing stored placements separately.
fn prepare_container(doc: Option<&Document>, n: &Node) -> Option<PreparedContainer> {
if !is_container(n) {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
return Some(copied_container(doc, n, t));
}
let pathfinder = has_pathfinder(n);
let fx = crate::reshape::geometry_effects(n);
let paint = has_own_paint(n);
@@ -870,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
return None;
}
let mut m = n.clone();
let mut carry = crate::Carry::default();
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
// that replace or copy the art, so do its guides among the art and those in its sublayers and
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
@@ -896,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut m);
}
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes paint the members as a whole: their gradients follow
// the effects as the members' do.
if paint && carry.moves(&m.appearance) {
@@ -905,6 +902,27 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
Some(PreparedContainer { m, guides, paint, carry })
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
/// the members (after a clipping path) or above them, as its contents slot says. Its
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
/// it gives each copy those raster effects ([`copied_container`]).
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
if !is_container(n) {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
return Some(copied_container(doc, n, t));
}
let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?;
if paint {
// A clip group whose clipping type paints strokes is now a group of a clip group and those
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
@@ -931,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
Some(m)
}
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
/// and locked as their containers were.
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
/// The exact pre-copy source shared by rendering and stored gradient placement.
fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec<Arc<Node>>, Node) {
let mut m = n.clone();
let mut guides = vec![];
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
@@ -955,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut source);
}
(m, guides, source)
}
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
/// and locked as their containers were.
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
let (mut m, guides, source) = copied_container_source(doc, n, t);
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
let mut p = source.clone();
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
@@ -988,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
m
}
/// Freeze representable fitted own paints to the box the container pass gives them, retaining
/// every live effect and already explicit placement. Hidden-only containers the pass does not
/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`.
pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option<Appearance> {
if !n.appearance.has_unplaced_gradient() {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
let (_, _, source) = copied_container_source(Some(doc), n, t);
let pinned = pinned_container_appearance(doc, &source)?;
let mut out = (*n.appearance).clone();
out.items = pinned.items;
return Some(out);
}
let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?;
let bounds = m.geometric_bounds()?;
let mut out = (*n.appearance).clone();
let mut changed = false;
for (item, original) in out.items.iter_mut().zip(&n.appearance.items) {
if paints(original)
&& matches!(original.paint(), Paint::Gradient(g) if !g.is_placed())
&& let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry])
{
*item = pinned;
changed = true;
}
}
changed.then_some(out)
}
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
+3 -1
View File
@@ -45,6 +45,7 @@ mod lighting_presets;
mod live;
mod marks;
pub mod pixel;
mod placement;
pub mod preview;
mod raster;
mod reshape;
@@ -75,12 +76,13 @@ pub use bake::{
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
};
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use placement::pinned_gradient_item;
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
without_geometry,
+74
View File
@@ -0,0 +1,74 @@
//! Conservative stored placements for gradients fitted by the existing effects passes.
use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem};
use vectorcraft_geom::Rect;
use crate::Carry;
/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects.
/// `carries` are the actual object and item passes, in rendering order. Only missing placement
/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or
/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted.
pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option<AppearanceItem> {
if gradient(item)?.is_placed() {
return Some(item.clone());
}
if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) {
return None;
}
let resolved = resolve(item, bounds, carries);
if !finite_placement(resolved.items.first()?) {
return None;
}
let mut stored = resolved.clone();
for carry in carries.iter().rev() {
carry.unapply_placed(&mut stored)?;
}
if !finite_placement(stored.items.first()?) {
return None;
}
let candidate = missing_placement(item, stored.items.first()?)?;
let replayed = resolve(&candidate, bounds, carries);
(finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate)
}
fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> {
match item.paint() {
Paint::Gradient(g) => Some(g),
_ => None,
}
}
fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance {
let mut ap = Appearance { items: vec![item.clone()], ..Default::default() };
for carry in carries {
carry.apply(&mut ap);
}
ap.pin_gradients(bounds);
ap
}
fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option<AppearanceItem> {
let original = gradient(item)?;
let placed = gradient(placed)?;
let mut out = item.clone();
let Paint::Gradient(g) = out.paint_mut() else { return None };
if original.geom.is_none() {
g.geom = placed.geom;
}
if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() {
let freeform = placed.freeform.as_ref()?;
match &mut g.freeform {
Some(f) => f.points.clone_from(&freeform.points),
None => g.freeform = Some(freeform.clone()),
}
}
Some(out)
}
fn finite_placement(item: &AppearanceItem) -> bool {
let Some(g) = gradient(item) else { return false };
g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite()))
&& g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite()))
}
+1 -1
View File
@@ -3505,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) {
/// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent
/// on, a move from its center to `to`'s).
fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
let axis = |a0: f64, a1: f64, b0: f64, b1: f64| {
if (a1 - a0).abs() > 1e-12 {
let s = (b1 - b0) / (a1 - a0);
-1
View File
@@ -99,7 +99,6 @@ pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
mod textedit;
mod xmlattrs;
pub use textedit::effective_kerning;
pub mod textstyles;
+1 -1
View File
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
has_doc,
erase_region
),
+32 -4
View File
@@ -345,18 +345,46 @@ pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec<N
out
}
/// Any visible non-None fill, including one below a topmost None.
pub(super) fn has_fill(n: &Node) -> bool {
n.appearance.items.iter().any(|item| item.is_fill() && item.visible() && !item.paint().is_none())
}
/// A visible painted stroke keeps open paths on the existing outline-erasure route.
pub(super) fn has_painted_stroke(n: &Node) -> bool {
n.appearance.items.iter().any(
|item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(stroke) if stroke.visible && !stroke.paint.is_none() && stroke.width > 0.0),
)
}
/// A container stroke that paints this target's open geometry. A clipping container's own
/// paint follows its clipping outline, and a compound shape paints its combined area instead.
/// Neither makes its descendants' implicit fill-closing edges into new stroked edges.
pub(super) fn has_painted_ancestor_stroke(doc: &Document, id: NodeId) -> bool {
doc.ancestry(id)
.unwrap_or_default()
.into_iter()
.rev()
.skip(1)
.filter_map(|id| doc.node(id))
.take_while(|node| !node.clips() && !node.is_compound_shape())
.any(|node| matches!(node.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && has_painted_stroke(node))
}
/// [`target_paths`] for the tools that cut fills, with each target's geometry and fill rule: the
/// members of a compound path whose members are all closed paths give the compound path itself,
/// once, so its fill (holes included) is cut as one shape under its own fill rule.
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect) -> Result<Vec<(NodeId, PathData, FillRule)>> {
let closed_compound = |n: &Node| {
/// With `open_fills`, an open compound with a visible fill and no painted visible stroke does too.
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect, open_fills: bool) -> Result<Vec<(NodeId, PathData, FillRule)>> {
let area_compound = |n: &Node| {
let filled = open_fills && has_fill(n) && !has_painted_stroke(n) && !has_painted_ancestor_stroke(doc, n.id);
matches!(&n.kind, NodeKind::Compound { children, .. }
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed())))
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed() || filled)))
};
let editable = doc.editable();
let mut out: Vec<(NodeId, PathData, FillRule)> = vec![];
for id in target_paths(doc, sel, area) {
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| closed_compound(p) && editable(p.id));
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| area_compound(p) && editable(p.id));
let target = compound.map_or(id, |c| c.id);
if out.iter().any(|t| t.0 == target) {
continue;
+71 -13
View File
@@ -1,10 +1,11 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke,
has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param,
set_geometry, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point,
Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use kurbo::{CubicBez, Line, PathSeg};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
@@ -266,7 +267,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0);
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0))? {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0), false)? {
if !pd.is_closed() {
continue;
}
@@ -340,8 +341,9 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
None => dist_to_polyline(&round, squash * q) <= r,
};
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -353,6 +355,34 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// Whether the target is erased as filled area rather than as an open outline.
fn erase_as_area(doc: &Document, id: NodeId, pd: &PathData) -> bool {
// An unaggregated compound member keeps the outline route: its own appearance does not
// paint it. Eligible fill-only compounds were collected as one parent target above.
let compound_member =
doc.parent_of(id).and_then(|parent| doc.node(parent)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. }));
let filled_open =
!compound_member && !has_painted_ancestor_stroke(doc, id) && doc.node(id).is_some_and(|node| has_fill(node) && !has_painted_stroke(node));
pd.is_closed() || filled_open
}
/// Close only Eraser's temporary fill operand, preserving an open path's straight closing edge.
fn eraser_fill_operand(mut pd: PathData) -> PathData {
for sp in &mut pd.subpaths {
if !sp.closed {
// These endpoint handles are unused by an open path. Closing it must not activate them.
if let Some(first) = sp.anchors.first_mut() {
first.h_in = first.p;
}
if let Some(last) = sp.anchors.last_mut() {
last.h_out = last.p;
}
sp.closed = true;
}
}
pd
}
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
/// height above 0.
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
@@ -369,7 +399,7 @@ fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
}
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
/// all). Closed paths and fill-only open paths lose the rectangle's area; other open paths are cut where they cross its edges.
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
let region =
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
@@ -392,8 +422,9 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
};
let st = s.doc()?;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r, true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -492,8 +523,9 @@ fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Vari
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
let reach = (size + sv) / 2.0;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -510,10 +542,36 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
return Ok(json!({ "ids": [] }));
}
let ids = s.edit(label, |d, sel| {
// Measure every original painting owner before any geometry or appearance changes.
// This includes a Compound above a Path Eraser target and containers above live art.
let owners: std::collections::BTreeSet<_> = plan.iter().flat_map(|(id, _)| d.ancestry(*id).unwrap_or_default()).collect();
let pinned: Vec<_> = owners
.into_iter()
.filter_map(|id| {
let node = d.node(id)?;
if !node.appearance.has_unplaced_gradient() {
return None;
}
vectorcraft_render::pinned_appearance_for_geometry_edit(d, node).map(|appearance| (id, appearance))
})
.collect();
for (id, appearance) in pinned {
if let Some(node) = d.node_mut(id) {
node.appearance = appearance.into();
}
}
let mut all = vec![];
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in plan {
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
let clipping_path = d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(|p| p.clips()));
if clipping_path {
// Keep every clipping contour in its original first child slot. An empty mask
// must also stay there so the clipped artwork cannot become the new mask.
set_geometry(d, id, PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect()))?;
all.push(id);
} else {
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
}
}
cut.finish(d)?;
sel.set(all.iter().copied());
-2
View File
@@ -171,8 +171,6 @@ fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
})?;
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
Ok(doc)
}
@@ -250,7 +250,6 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")),
_ => bad(cmd, format!("the variable library is not well-formed XML: {e}")),
})?;
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else {
return Err(bad(cmd, "the file holds no `variableSets` element"));
};
-55
View File
@@ -1,55 +0,0 @@
//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode.
//!
//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the
//! shared strict reader and remove this second event pass when that dependency is updated.
/// Check names before canonical/local-name rewriting can collapse distinct attributes.
/// The event reader and namespace scope use the same caller-supplied resource caps.
pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> {
use std::collections::BTreeSet;
let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict();
let mut events = opts.events(xml);
let mut bindings: Vec<(String, String)> = Vec::new();
let mut scopes = Vec::new();
while let Some(event) = events.next().map_err(|e| e.to_string())? {
match event {
craft_xml::Event::Start { attrs, .. } => {
scopes.push(bindings.len());
let mut raw = BTreeSet::new();
for (key, value) in &attrs {
if !raw.insert(key.as_str()) {
return Err(format!("duplicate attribute `{key}`"));
}
if let Some(prefix) = key.strip_prefix("xmlns:") {
if bindings.len() >= limits.max_attrs {
return Err("too many in-scope namespace declarations".into());
}
bindings.push((prefix.to_string(), value.clone()));
}
}
let mut expanded = BTreeSet::new();
for (key, _) in &attrs {
if key == "xmlns" || key.starts_with("xmlns:") {
continue;
}
// Default namespaces do not apply to attributes. Preserve undeclared
// prefixes for standalone SVG library fragments, as the importer did.
let name = match key.split_once(':') {
Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local),
Some((prefix, local)) => {
bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local))
}
None => ("", key.as_str()),
};
if !expanded.insert(name) {
return Err(format!("duplicate expanded attribute `{key}`"));
}
}
}
craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)),
_ => {}
}
}
Ok(())
}
File diff suppressed because it is too large Load Diff
+3
View File
@@ -64,10 +64,13 @@ use crate::{Frame, Renderer, blend_mode, fill_rule, paint};
mod bounds;
mod entries;
mod pixels;
mod placement;
mod predicates;
mod raster;
mod renderer;
pub use placement::pinned_appearance_for_geometry_edit;
#[cfg(test)]
pub(crate) use bounds::visual_bounds;
pub(crate) use bounds::{
+94
View File
@@ -0,0 +1,94 @@
//! Stored gradient fits for geometry edits on the renderer's ordinary shape/container paths.
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind};
use vectorcraft_effects::{self as effects, GeomContext};
use vectorcraft_geom::{BezPath, Rect, Shape};
use super::bounds::{apply_carrying, effected_path_carrying, item_effects, node_bezpath};
use super::predicates::has_non_container_art_fx;
use super::renderer::carried;
/// Store the current renderer fit of gradients that can be represented by the existing appearance.
///
/// Alternate materialized art, visible plug-ins, Rasterize and path-coordinate stroke gradients
/// keep their existing fit behavior. An unsupported or non-roundtripping carry also leaves its row
/// unchanged; this neither flattens art nor changes persisted effects. `None` makes no change.
pub fn pinned_appearance_for_geometry_edit(doc: &Document, n: &Node) -> Option<Appearance> {
if !n.appearance.has_unplaced_gradient() || unsupported(n) || has_non_container_art_fx(n) {
return None;
}
// Enclosing geometry effects change the fit outside this node-local pass.
// Without that context, leave the paint fitted rather than storing a false frame.
if doc.ancestry(n.id)?.into_iter().filter(|&id| id != n.id).any(|id| {
doc.node(id).is_some_and(|ancestor| {
matches!(ancestor.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && effects::has_geometry(&ancestor.appearance.effects)
})
}) {
return None;
}
match &n.kind {
NodeKind::Group { .. } | NodeKind::Layer { .. } => effects::pinned_container_appearance(doc, n),
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => pinned_shape(doc, n),
_ => None,
}
}
fn rasterizes(fx: &[Effect]) -> bool {
fx.iter().any(|effect| effect.visible && effect.id == effects::RASTERIZE)
}
fn unsupported(n: &Node) -> bool {
effects::has_plugin_effect(n)
|| rasterizes(&n.appearance.effects)
|| n.appearance.items.iter().any(|item| {
item.visible() && (rasterizes(item.effects()) || matches!(item, AppearanceItem::Stroke(stroke) if stroke.path_gradient().is_some()))
})
}
fn unplaced(item: &AppearanceItem) -> bool {
item.visible() && matches!(item.paint(), Paint::Gradient(gradient) if !gradient.is_placed())
}
fn pinned_shape(doc: &Document, n: &Node) -> Option<Appearance> {
let bp = node_bezpath(n)?;
let (geometry, object_carry) = effected_path_carrying(doc, n, &bp);
if geometry.elements().is_empty() {
return None;
}
// Share the renderer's actual temporary object carry and skipped-effect flags.
let temporary = carried(n, &object_carry);
let paints = temporary.as_deref().unwrap_or(n);
let context = GeomContext { doc: Some(doc), ..GeomContext::of(paints) };
let mut appearance = (*n.appearance).clone();
let mut changed = false;
for (index, original) in n.appearance.items.iter().enumerate().filter(|(_, item)| unplaced(item)) {
// `item` must belong to the same temporary appearance borrowed by `context.item`:
// that lookup uses pointer identity to recover the actual row index/seed.
let item = paints.appearance.items.get(index)?;
let (item_geometry, item_carry) = apply_carrying(item_effects(item), &geometry, &context.item(item));
let bounds = item_bounds(item, &geometry, &item_geometry, &item_carry)?;
if let Some(pinned) = effects::pinned_gradient_item(original, bounds, &[&object_carry, &item_carry]) {
*appearance.items.get_mut(index)? = pinned;
changed = true;
}
}
changed.then_some(appearance)
}
/// The same temporary item carry/skipped flags and `ib` choice as `Renderer::paint_items`.
fn item_bounds(item: &AppearanceItem, geometry: &BezPath, item_geometry: &BezPath, carry: &effects::Carry) -> Option<Rect> {
let mut appearance = Appearance { items: vec![item.clone()], ..Default::default() };
if !carry.is_empty() && matches!(item.paint(), Paint::Gradient(_)) {
carry.apply(&mut appearance);
}
let mut item = appearance.items.pop()?;
if carry.skipped() {
carry.hide_skipped(item.effects_mut());
}
Some(if effects::has_geometry(item_effects(&item)) && !item_geometry.elements().is_empty() {
item_geometry.bounding_box()
} else {
geometry.bounding_box()
})
}
+10 -1
View File
@@ -25,11 +25,20 @@ pub(crate) fn has_fx(n: &Node) -> bool {
/// effect copies it with a gradient or changes its fills and strokes ([`effects::has_transform_art`]),
/// or is it a group or layer with an appearance of its own (see [`Renderer::draw_object_fx`])?
pub(crate) fn has_object_fx(n: &Node) -> bool {
object_fx(n, true)
}
/// The alternate-art dispatches other than a group or layer's own container appearance.
pub(super) fn has_non_container_art_fx(n: &Node) -> bool {
object_fx(n, false)
}
fn object_fx(n: &Node, containers: bool) -> bool {
(effects::needs_outline(n) && (visible(&n.appearance.effects) || n.projection().is_some()))
|| effects::has_item_geometry(n)
|| effects::has_instance_row_raster(n)
|| effects::has_transform_art(n)
|| effects::has_container_appearance(n)
|| (containers && effects::has_container_appearance(n))
|| effects::has_crop_marks(n)
|| effects::addons::halftone::has_halftone(n)
|| effects::has_adjustment(n)
+1 -1
View File
@@ -1029,7 +1029,7 @@ impl Renderer {
/// the Transform effects the geometry pass left out hidden ([`effects::Carry::hide_skipped`]), so
/// its raster effects and those of its fills and strokes stay with its art; `None` when it stays
/// as it is.
fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
pub(super) fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
let moves = carry.moves(&n.appearance);
(moves || carry.skipped()).then(|| {
let mut m = n.clone();
+1
View File
@@ -43,6 +43,7 @@ use lru::FrameCache;
pub use brush_fx::instance_art;
pub use changed::{Changed, changed, placed_area, view_pixels};
pub use effects::stroke::width_outline;
pub use fx::pinned_appearance_for_geometry_edit;
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget};
pub use live::expand_live;
pub use pattern::render_pattern_swatch;
+2
View File
@@ -9,6 +9,8 @@ description = "VectorCraft text: font database, shaping, layout, glyph outlines"
workspace = true
[dependencies]
# The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false }
vectorcraft-geom = { workspace = true }
vectorcraft-doc = { workspace = true }
kurbo = { workspace = true }
+1 -1
View File
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, RwLock};
use kurbo::BezPath;
use skrifa::instance::{Location, LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::outline::OutlinePen;
use skrifa::raw::FileRef;
use skrifa::string::StringId;
use skrifa::{GlyphId, MetadataProvider, Tag};
+19
View File
@@ -53,6 +53,25 @@ impl OutlinePen for FlipPen {
}
}
// Share font decoding while preserving the app's existing y-down geometry and resource budget.
impl craft_font_catalog::GlyphPen for FlipPen {
fn move_to(&mut self, x: f32, y: f32) {
OutlinePen::move_to(self, x, y);
}
fn line_to(&mut self, x: f32, y: f32) {
OutlinePen::line_to(self, x, y);
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
OutlinePen::quad_to(self, x1, y1, x, y);
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
OutlinePen::curve_to(self, x1, y1, x2, y2, x, y);
}
fn close(&mut self) {
OutlinePen::close(self);
}
}
#[cfg(test)]
mod tests {
use super::*;
+90 -8
View File
@@ -10,10 +10,7 @@ use super::names::{norm, norm_chars, script_families};
#[cfg(not(target_arch = "wasm32"))]
use super::scan::{enumerate_faces, font_files};
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
use super::{
Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX,
Ordering, Size,
};
use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering};
/// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads.
const MAX_POSTSCRIPT_FACES: usize = 16;
@@ -655,10 +652,9 @@ impl FontDb {
return p.clone();
}
let mut pen = FlipPen(BezPath::new());
if let Some(f) = face.skrifa()
&& let Some(g) = f.outline_glyphs().get(GlyphId::new(gid))
{
let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);
if let Ok(font) = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) {
// As before, keep the prefix emitted before a malformed glyph reports an error.
let _ = font.draw_to(gid, &mut pen);
}
let p = Arc::new(pen.0);
let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner());
@@ -722,3 +718,89 @@ impl FontDb {
content
}
}
#[cfg(test)]
mod shared_outline_tests {
use super::super::glyph_pen::FlipPen;
use super::*;
use skrifa::instance::Size;
use skrifa::outline::DrawSettings;
use skrifa::{GlyphId, MetadataProvider};
#[test]
fn shared_outlines_match_original_pen_for_variable_instances() {
let db = FontDb::with_font_dirs(vec![]);
let Some(bytes) = crate::test_fonts::variable_font() else { return };
assert!(db.add_font(bytes) > 0);
let face = db.face(crate::test_fonts::VARIABLE_FAMILY, "Bold").expect("named instance is registered");
let f = face.skrifa().expect("font parses");
for ch in ['A', 'V', ' ', 'a'] {
let Some(glyph) = f.charmap().map(ch) else { continue };
let mut old = FlipPen(BezPath::new());
if let Some(outline) = f.outline_glyphs().get(GlyphId::new(glyph.to_u32())) {
// Match the prior production behavior, including a partial path on error.
let _ = outline.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut old);
}
assert_eq!(*db.outline(&face, glyph.to_u32()), old.0, "glyph {ch}");
}
}
// Generated CFF keeps the differential tests independent of installed fonts.
fn cff_font(program: &[u8]) -> Vec<u8> {
let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0];
cff.extend_from_slice(&[0, 1, 4]);
cff.extend_from_slice(&1u32.to_be_bytes());
cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes());
cff.extend_from_slice(program);
let mut builder = write_fonts::FontBuilder::new();
let mut head = vec![0; 54];
head[18..20].copy_from_slice(&1000u16.to_be_bytes());
let mut hhea = vec![0; 36];
hhea[34..36].copy_from_slice(&1u16.to_be_bytes());
for (tag, data) in [(b"head", head), (b"hhea", hhea), (b"hmtx", vec![0, 100, 0, 0]), (b"maxp", vec![0, 0, 0x50, 0, 0, 1]), (b"CFF ", cff)] {
builder.add_raw(write_fonts::types::Tag::new(tag), data);
}
builder.build()
}
#[test]
fn malformed_cff_prefix_matches_original_pen() {
let bytes = cff_font(&[139, 139, 21, 239, 139, 5, 10, 14]);
let gid = 0;
let f = skrifa::FontRef::new(&bytes).unwrap();
let mut old = FlipPen(BezPath::new());
let result = f
.outline_glyphs()
.get(GlyphId::new(gid))
.unwrap()
.draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old);
assert!(result.is_err());
assert!(!old.0.elements().is_empty());
let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
let mut streamed = FlipPen(BezPath::new());
assert!(shared.draw_to(gid, &mut streamed).is_err());
assert_eq!(streamed.0, old.0);
}
#[test]
fn large_valid_outline_matches_original_pen() {
let mut program = vec![139, 139, 21];
for _ in 0..100_001 {
program.extend_from_slice(&[140, 6]);
}
program.push(14);
let bytes = cff_font(&program);
let f = skrifa::FontRef::new(&bytes).unwrap();
let mut old = FlipPen(BezPath::new());
f.outline_glyphs()
.get(GlyphId::new(0))
.unwrap()
.draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old)
.unwrap();
assert!(old.0.elements().len() > 100_000);
let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
let mut streamed = FlipPen(BezPath::new());
shared.draw_to(0, &mut streamed).unwrap();
assert_eq!(streamed.0, old.0);
}
}
+16 -24
View File
@@ -62,30 +62,22 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool {
/// ([`upright_extent`]) as a share of `upright`, the length in font units its own width runs down.
/// Empty for a glyph of one character.
fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: Option<f64>) -> Vec<(usize, f64)> {
use unicode_segmentation::UnicodeSegmentation;
let Some(s) = text.get(g.byte..g.byte + g.len).filter(|_| g.len > 1) else { return Vec::new() };
let starts: Vec<usize> = s.grapheme_indices(true).skip(1).map(|(i, _)| g.byte + i).collect();
if starts.is_empty() {
return Vec::new();
}
let parts = starts.len() + 1;
let from_font = if let Some(length) = upright {
let (cell, top) = upright_extent(g);
g.face
.vertical_ligature_carets(g.gid, starts.len(), top, cell)
.filter(|c| c.len() == starts.len() && length > 0.0)
.map(|c| c.into_iter().map(|d| d / length).collect::<Vec<f64>>())
.filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0))
} else {
let advance = g.face.advance(g.gid);
g.face
.ligature_carets(g.gid, starts.len())
.filter(|c| c.len() == starts.len() && advance > 0.0)
.map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::<Vec<f64>>())
};
let mut at = from_font.unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect());
at.sort_by(f64::total_cmp);
starts.into_iter().zip(at).collect()
craft_font_catalog::ligature_caret_stops(text, g.byte, g.len, |count| {
if let Some(length) = upright {
let (cell, top) = upright_extent(g);
g.face
.vertical_ligature_carets(g.gid, count, top, cell)
.filter(|c| c.len() == count && length > 0.0)
.map(|c| c.into_iter().map(|d| d / length).collect::<Vec<f64>>())
.filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0))
} else {
let advance = g.face.advance(g.gid);
g.face
.ligature_carets(g.gid, count)
.filter(|c| c.len() == count && advance > 0.0)
.map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::<Vec<f64>>())
}
})
}
/// Does glyph `g`, standing upright in vertical type, take a cell of its own down the column? Every
+5 -30
View File
@@ -81,34 +81,9 @@ pub(super) fn visual_order(bidi: Option<&BidiInfo<'_>>, paragraph_start: usize,
return vec![];
}
let levels = bidi.reordered_levels(para, line.start.saturating_sub(paragraph_start)..line.end.saturating_sub(paragraph_start));
// A list marker (length 0) is a cluster of its own.
let mut clusters: Vec<Range<usize>> = Vec::new();
for (i, g) in glyphs.iter().enumerate() {
if i > 0 && glyphs.get(i - 1).is_some_and(|p| p.byte == g.byte && (p.len == 0) == (g.len == 0)) {
if let Some(c) = clusters.last_mut() {
c.end = i + 1;
}
} else {
clusters.push(i..i + 1);
}
}
// A list marker is at the paragraph's level, and at a right-to-left one its tab is drawn
// before (left of) its characters.
let cluster_levels: Vec<_> = clusters
.iter()
.filter_map(|c| glyphs.get(c.start))
.map(|g| if g.len == 0 { g.level } else { levels.get(g.byte.saturating_sub(paragraph_start)).copied().unwrap_or(g.level) })
.collect();
let reversed = |i: usize| glyphs.get(clusters.get(i).map_or(0, |c| c.start)).is_some_and(|g| g.len == 0 && g.level.is_rtl());
unicode_bidi::BidiInfo::reorder_visual(&cluster_levels)
.into_iter()
.filter_map(|i| clusters.get(i).map(|c| (c.clone(), reversed(i))))
.flat_map(|(c, rev)| {
let mut v: Vec<usize> = c.collect();
if rev {
v.reverse();
}
v
})
.collect()
craft_font_catalog::visual_order(
glyphs.iter().map(|g| craft_font_catalog::VisualGlyph { byte: g.byte, len: g.len, level: g.level }),
paragraph_start,
&levels,
)
}
+2 -18
View File
@@ -458,24 +458,8 @@ pub(super) fn break_line(
line_end: &[f64],
fits: Option<&dyn Fn(usize, bool) -> bool>,
) -> (usize, bool) {
// The line ending at `chosen`, once it holds a tab, when it fits as drawn; otherwise the latest
// of the legal `breaks` before it that fits as drawn, measuring at most `checks` of them from
// the latest back and bisecting the earlier ones without a hyphen; the first of them when none
// of those measured fits.
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| -> (usize, bool) {
let Some(fits) = fits.filter(|_| tabbed) else { return chosen };
if fits(chosen.0, chosen.1) {
return chosen;
}
let earlier = breaks.get(breaks.partition_point(|b| b.0 <= i)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default();
if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) {
return b;
}
// Without a hyphen, a line that ends later is drawn no narrower, so those breaks bisect.
let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default();
let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect();
let fitting = plain.partition_point(|b| fits(b.0, b.1));
fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen)
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| {
craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits)
};
// How many breaks a line measures as drawn one by one.
let checks = |back: f64| if back > 0.0 { MAX_DRAWN_CHECKS_STEPPING_BACK } else { MAX_DRAWN_CHECKS };
+35 -57
View File
@@ -8,7 +8,7 @@ use unicode_bidi::Level;
use unicode_script::{Script, UnicodeScript};
use unicode_segmentation::UnicodeSegmentation;
use harfrust::{BufferClusterLevel, Direction, Feature, ShapeOptions, Tag, UnicodeBuffer};
use harfrust::{Direction, Feature, Tag};
use kurbo::Shape;
use skrifa::MetadataProvider;
use skrifa::charmap::Charmap;
@@ -673,7 +673,7 @@ pub(crate) fn shape_runs(
// Split into segments by font coverage (and case, for Small Caps).
let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) };
let mut cache: std::collections::HashMap<&str, Arc<FontFace>> = std::collections::HashMap::new();
let mut script = Script::Common;
let mut boundary = craft_font_catalog::SegmentBoundary::new(primary.id(), level_at(a));
// A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face.
for (i, cluster) in text[a..b].grapheme_indices(true) {
let i = a + i;
@@ -693,20 +693,16 @@ pub(crate) fn shape_runs(
};
let small = small_caps && c.is_lowercase();
let next_script = shaping_script(c);
let strong_script = !matches!(next_script, Script::Common | Script::Inherited);
let script_change = strong_script && script != Script::Common && script != next_script;
let strong_script = (!matches!(next_script, Script::Common | Script::Inherited)).then_some(next_script);
// Combining marks, zero width joiners and non-joiners, and variation selectors stay
// with the character before them.
if (face.id() != seg.face.id() || small != seg.small || level != seg.level || script_change) && !is_mark(c) {
if boundary.advance(face.id(), level, small, strong_script, is_mark(c)) {
if i > seg.range.start {
seg.range.end = i;
shape_segment(text, &range, &seg, feats, out);
}
seg = Segment { range: i..i, face, small, level, ..seg };
}
if strong_script {
script = next_script;
}
}
if b > seg.range.start {
seg.range.end = b;
@@ -1301,10 +1297,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
/// variation selectors.
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
cluster
.chars()
.map(move |c| digits.map(c))
.filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')))
craft_font_catalog::drawable_characters(cluster, move |c| digits.map(c))
}
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
@@ -1316,11 +1309,14 @@ fn in_face(map: Option<&Charmap<'_>>, c: char) -> bool {
/// first fallback face with all of them, so that a letter's marks are shaped with it and attach to
/// it (#4491); when there is none, the face its first character takes on its own.
fn fallback_face(db: &FontDb, primary: &Arc<FontFace>, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc<FontFace> {
let fallback = |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic);
drawn_chars(cluster, digits)
.find_map(|c| fallback(c).filter(|f| drawn_chars(cluster, digits).all(|c| f.covers(c))))
.or_else(|| drawn_chars(cluster, digits).next().filter(|&c| !in_face(pmap, c)).and_then(fallback))
.unwrap_or_else(|| primary.clone())
craft_font_catalog::cluster_face(
cluster,
primary,
|c| digits.map(c),
|c| in_face(pmap, c),
|c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic),
|face, c| face.covers(c),
)
}
/// The script `c` is shaped in: Japanese and Chinese text mixes Han, Hiragana, Katakana and
@@ -1606,46 +1602,28 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
let along_features = with_more(&|s| feats.resolve(s));
// gid, cluster, x and y advance, x and y offset.
let shape = |feats: &[Feature], direction: Direction| {
let mut buf = UnicodeBuffer::new();
for (i, c) in text_seg.char_indices() {
let cl = (range.start + i) as u32;
let c = st.digits.map(c);
if upper {
for u in c.to_uppercase() {
buf.add(u, cl);
}
} else {
buf.add(c, cl);
}
}
buf.set_direction(direction);
buf.guess_segment_properties();
if char_level.get() {
buf.set_cluster_level(BufferClusterLevel::Characters);
}
// The characters' language picks the font's forms for it (`locl`: Turkish keeps fi
// apart and the dot on its i).
if let Some(l) = &language {
buf.set_language(l.clone());
}
// Harfrust keeps this Unicode context for joining/positional shaping, but does not emit
// glyphs for it. This retains context at real style/font segmentation boundaries without
// shaping across those boundaries or claiming cross-style ligatures/mark attachment.
if let Some(pre) = text.get(context.start..range.start) {
buf.set_pre_context(pre);
}
if let Some(post) = text.get(range.end..context.end) {
buf.set_post_context(post);
}
// A buffer whose characters name no script reads as `UNKNOWN`: its plan has none.
let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN);
let plan = face.shape_plan(&shaper, buf.direction(), script, language.as_ref(), feats);
let gb = shaper.shape(buf, ShapeOptions::new().features(feats).plan(Some(&plan)));
gb.glyph_infos()
.iter()
.zip(gb.glyph_positions())
.map(|(info, pos)| (info.glyph_id, info.cluster, pos.x_advance, pos.y_advance, pos.x_offset, pos.y_offset))
.collect::<Vec<_>>()
let input = craft_font_catalog::RunInput {
text: text_seg,
source_start: range.start,
pre_context: text.get(context.start..range.start).unwrap_or_default(),
post_context: text.get(range.end..context.end).unwrap_or_default(),
direction,
language: language.as_ref(),
features: feats,
character_clusters: char_level.get(),
uppercase: upper,
};
craft_font_catalog::shape_run(
&shaper,
&input,
|c| st.digits.map(c),
|shaper, direction, script, language, features| face.shape_plan(shaper, direction, script, language, features),
)
// HarfRust clusters are u32; a run beyond that source offset cannot be represented.
.unwrap_or_default()
.into_iter()
.map(|g| (g.glyph_id, g.cluster, g.x_advance, g.y_advance, g.x_offset, g.y_offset))
.collect::<Vec<_>>()
};
let along = if level.is_rtl() { Direction::RightToLeft } else { Direction::LeftToRight };
*raw = shape(&along_features, along).into_iter().map(|(g, c, xa, _, xo, yo)| (g, c, xa, xo, yo)).collect();
+7 -1
View File
File diff suppressed because one or more lines are too long
+7 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+8 -2
View File
File diff suppressed because one or more lines are too long