Merge main into fix/direct-select-ctrl-handle-mirror

This commit is contained in:
dotCooCoo committed 2026-12-03 12:59:15 -08:00
commit d1b41542ff
20 files changed
+496 -83

No files matched your search

Generated
+17
View File
@@ -2900,6 +2900,7 @@ dependencies = [
"raw-window-handle",
"smithay-clipboard",
"web-time",
"webbrowser",
"windows-sys 0.61.2",
"winit",
]
@@ -9642,6 +9643,22 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webbrowser"
version = "1.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13b31216ad837f3f4062538be333d8431d37c11832ef86924a3d0ad50defdc2f"
dependencies = [
"jni",
"log",
"ndk-context",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"url",
"web-sys",
]
[[package]]
name = "webpki-root-certs"
version = "1.0.11"
+4 -1
View File
@@ -23,7 +23,10 @@ vectorcraft-text = { workspace = true }
# the update client.
craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] }
craft-nightly = { workspace = true }
eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] }
# `links` makes egui's OpenUrl output (every link the app opens) start the system browser; without it egui-winit only
# logs the request. Remove it when the craft-libs pin includes storytold/craft-libs#5083, which opens links in the
# shared app setup.
eframe = { workspace = true, features = ["clipboard", "default_fonts", "links", "wayland", "x11"] }
egui = { workspace = true }
egui_extras = { workspace = true }
serde_json = { workspace = true }
+174 -1
View File
@@ -21,11 +21,12 @@ use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
use crate::node::{Node, NodeId, NodeKind};
use crate::node::{LiveShape, Node, NodeId, NodeKind};
use crate::text::TextObject;
// =====================================================================================
@@ -1032,6 +1033,9 @@ enum Shape {
/// Paths and compound paths; `members`: the subpath count of each member when both keys are
/// compound paths.
Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec<usize>, Vec<usize>)> },
/// Two live rectangles: each step is a live rectangle whose size, transform and corner radii
/// lie between the keys', so their rounded corners stay circular arcs.
LiveRect(Box<(LiveRectParts, LiveRectParts)>),
/// Text, symbols and images: their transforms interpolate.
Placed,
/// Anything else: a copy of the nearer key moved and scaled into the interpolated box.
@@ -1046,6 +1050,43 @@ pub struct Lerp {
shape: Shape,
}
/// A live rectangle's size, transform, corner kinds and corner radii in document units.
#[derive(Clone, Debug)]
struct LiveRectParts {
w: f64,
h: f64,
radii: [f64; 4],
kinds: [CornerKind; 4],
xf: Affine,
}
/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws.
fn live_rect(s: &LiveShape) -> Option<LiveRectParts> {
let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None };
let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h));
let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative);
let corners = vectorcraft_geom::corners::path_corners(&base);
let mut drawn = [0.0; 4];
for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) {
if let Some(d) = drawn.get_mut(c.index) {
*d = r;
}
}
Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf })
}
/// The parts of `a` and `b` when steps between them can be live rectangles: both are live
/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear
/// left in their transforms, so each step only moves and resizes and its corners stay circular.
fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> {
let (x, y) = (live_rect(a)?, live_rect(b)?);
let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs());
// A rotation or a reflection: unit columns at right angles.
let rigid =
|c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9;
(x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y))
}
/// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has.
fn collapsed(n: &Node, c: Point) -> Node {
let mut x = n.clone();
@@ -1083,6 +1124,12 @@ impl Lerp {
| (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. })
| (NodeKind::Image(_), NodeKind::Image(_))
| (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed,
// A clicked start point asks for anchors to be paired; the path route does that.
(NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. })
if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) =>
{
Shape::LiveRect(Box::new(parts))
}
_ => match (node_path(a), node_path(b)) {
(Some((pa, ra, ma)), Some((pb, rb, mb))) => {
Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) }
@@ -1145,6 +1192,28 @@ impl Lerp {
}
}
}
Shape::LiveRect(parts) => {
let (x, y) = &**parts;
let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs());
let live = LiveShape::Rectangle {
w: lerp_f64(x.w, y.w, t),
h: lerp_f64(x.h, y.h, t),
radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)),
kinds: x.kinds,
radii_relative: false,
xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]),
};
let rule = match &base.kind {
NodeKind::Path { rule, .. } => *rule,
_ => FillRule::default(),
};
let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default());
if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind {
*r = rule;
*l = Some(Box::new(live));
}
n
}
Shape::Placed => {
let mut n = base.clone();
match (&mut n.kind, &a.kind, &b.kind) {
@@ -2321,6 +2390,110 @@ mod tests {
assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0));
}
/// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`.
fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node {
let live =
LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) };
let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default());
if let NodeKind::Path { live: l, .. } = &mut n.kind {
*l = Some(Box::new(live));
}
n
}
/// The step's live radii, after checking that every curve of its outline is a circular arc of
/// that radius about the matching corner center.
fn round_step_radii(step: &Node) -> [f64; 4] {
let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") };
let r = radii[0];
let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default();
let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y));
let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default();
let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count();
assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}");
for seg in path.segments() {
if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg {
for u in [0.0, 0.25, 0.5, 0.75, 1.0] {
let p = c.eval(u);
let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min);
assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}");
}
}
}
*radii
}
/// Steps between live rectangles are live rectangles whose corner radii lie between the keys'.
#[test]
fn steps_between_rounded_rectangles_keep_round_corners() {
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
for r in round_step_radii(&blend.at(0.5)) {
assert!((r - 20.0).abs() < 1e-9, "{r}");
}
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
for t in [0.25, 0.5, 0.75] {
for r in round_step_radii(&blend.at(t)) {
assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}");
}
}
// A radius too large for its rectangle counts as the radius it draws.
let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None));
for r in round_step_radii(&blend.at(0.5)) {
assert!((r - 10.0).abs() < 1e-9, "{r}");
}
// Keys turned differently keep the anchor-by-anchor route.
let mut turned = rounded(300.0, 200.0, 60.0, 30.0);
turned.transform(Affine::rotate(0.5), false);
assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. }));
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
let mut b = rounded(300.0, 100.0, 100.0, 30.0);
a.transform(Affine::rotate(30.0_f64.to_radians()), false);
b.transform(Affine::rotate(390.0_f64.to_radians()), false);
let blend = Lerp::new(&a, &b, (None, None));
assert!(matches!(&blend.shape, Shape::LiveRect(_)));
let step = blend.at(0.5);
let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") };
let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") };
assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]);
for starts in [(Some(0), None), (None, Some(0))] {
assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. }));
}
b.transform(Affine::scale_non_uniform(-1.0, 1.0), false);
assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. }));
for scale in [1.0, 1e-200] {
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
let mut b = rounded(300.0, 100.0, 100.0, 30.0);
a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false);
b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false);
assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. }));
}
// Keys whose corner kinds differ keep the anchor-by-anchor route.
let mut kinds = [CornerKind::Round; 4];
kinds[2] = CornerKind::InvertedRound;
let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) };
let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default());
if let NodeKind::Path { live: l, .. } = &mut inverted.kind {
*l = Some(Box::new(live));
}
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None));
assert!(matches!(blend.shape, Shape::Path { .. }));
// The last step is the inverted key's outline.
assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds()));
// Each step keeps the fill rule of the key it is nearer.
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
if let NodeKind::Path { rule, .. } = &mut a.kind {
*rule = FillRule::EvenOdd;
}
let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
assert!(matches!(&blend.shape, Shape::LiveRect(_)));
let rule = |n: &Node| match &n.kind {
NodeKind::Path { rule, .. } => *rule,
_ => panic!("a path step: {n:?}"),
};
assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd);
assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero);
}
/// A step between two distorted images has its corners between the keys' corners.
#[test]
fn steps_between_distorted_images_have_corners_between_theirs() {
+1 -1
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Blend"],
Some("Cmd+Alt+B"),
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way. A start anchor makes rectangles blend anchor by anchor.), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
has_doc,
blend_make
),
+32
View File
@@ -171,6 +171,38 @@ fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
/// Divide refuses a cutting line with more segments than its planar map takes, instead of
/// dividing the square without the line, and leaves the document and the undo history as they were.
#[test]
fn divide_refuses_cutting_lines_past_the_segment_cap() {
let mut s = session();
let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let cutter = NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap());
// A zigzag across the square with one segment more than the cap, the square's four sides aside.
let segments = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS - 3;
s.edit("zigzag", |d, sel| {
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((-10.0, 40.0));
for i in 1..=segments {
let x = -10.0 + 120.0 * i as f64 / segments as f64;
bp.line_to((x, if i % 2 == 0 { 40.0 } else { 60.0 }));
}
// Unfilled, so the zigzag stays open and cuts.
let n = d.node_mut(cutter).unwrap();
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
sel.set([cutter, base]);
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let undo_len = s.doc().unwrap().history.undo.len();
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(e.contains("select fewer paths"), "{e}");
assert!(s.doc().unwrap().doc == before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
#[test]
fn exclude_makes_compound() {
let mut s = session();
+1 -1
View File
@@ -22,4 +22,4 @@ mod pixels;
pub(crate) use filters::Stream;
#[cfg(test)]
pub(crate) use ops::measured;
pub(crate) use ops::{max_data, measured, with_data_limit};
+7 -7
View File
@@ -1,4 +1,4 @@
use super::ops::MAX_DATA;
use super::ops::max_data;
use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err};
use craft_stream_codecs::CcittParams;
@@ -44,7 +44,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
out.extend(std::iter::repeat_n(b, 257 - usize::from(n)));
}
}
if out.len() > MAX_DATA {
if out.len() > max_data() {
return Err(PsError::Limit("decoded data is too large"));
}
}
@@ -54,7 +54,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
/// zlib data inflated, and how many bytes of `raw` it took.
fn flate(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
let mut z = flate2::Decompress::new(true);
let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(MAX_DATA));
let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(max_data()));
loop {
let before = (z.total_in(), z.total_out());
if out.capacity() - out.len() < 64 * 1024 {
@@ -62,7 +62,7 @@ fn flate(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
}
let input = raw.get(z.total_in() as usize..).unwrap_or_default();
let status = z.decompress_vec(input, &mut out, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?;
if out.len() > MAX_DATA {
if out.len() > max_data() {
return Err(PsError::Limit("decoded data is too large"));
}
match status {
@@ -79,7 +79,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
let mut out = vec![];
let used = lzw_into(raw, &mut |bytes| {
out.extend_from_slice(bytes);
if out.len() > MAX_DATA {
if out.len() > max_data() {
return Err(PsError::Limit("decoded data is too large"));
}
Ok(())
@@ -238,10 +238,10 @@ fn dct(raw: &[u8]) -> Res<(Vec<u8>, usize, u8)> {
/// `EndOfBlock` the rows end at the end-of-block code (EOFB, or RTC in Group 3) regardless of
/// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0.
/// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an
/// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused.
/// `ioerror`. Rows that would take more than [`max_data`] bytes are refused.
fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec<u8>, usize)> {
let row = (settings.columns as usize).div_ceil(8).max(1);
let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX);
let most = u32::try_from(max_data() / row).unwrap_or(u32::MAX);
if !settings.end_of_block && settings.rows > i64::from(most) {
return Err(PsError::Limit("decoded data is too large"));
}
+38 -7
View File
@@ -6,7 +6,38 @@ use super::{
};
/// Most bytes one filter or image reads.
pub(super) const MAX_DATA: usize = 1 << 28;
const MAX_DATA: usize = 1 << 28;
#[cfg(test)]
thread_local! {
/// The most bytes one filter or image reads on this thread ([`MAX_DATA`] unless a test lowered it).
static DATA_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_DATA) };
}
/// The most bytes one filter or image reads: [`MAX_DATA`].
#[cfg(not(test))]
pub(super) const fn max_data() -> usize {
MAX_DATA
}
/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread.
#[cfg(test)]
pub(crate) fn max_data() -> usize {
DATA_LIMIT.get()
}
/// Runs `f` with [`max_data`] set to `limit` on this thread, and restores it afterwards.
#[cfg(test)]
pub(crate) fn with_data_limit<R>(limit: usize, f: impl FnOnce() -> R) -> R {
struct Restore(usize);
impl Drop for Restore {
fn drop(&mut self) {
DATA_LIMIT.set(self.0);
}
}
let _restore = Restore(DATA_LIMIT.replace(limit));
f()
}
/// Decoded bytes the measuring of an image's data left out charges one operation for. A program's
/// budget grows by 64 operations for each byte of it, so the data of one image compressed up to
@@ -410,7 +441,7 @@ impl Interp<'_> {
Stream::Buf { data, pos: 0, rgb }
}
p @ Obj::Array { .. } => {
let raw = self.gather(&p, MAX_DATA)?;
let raw = self.gather(&p, max_data())?;
let (data, _, rgb) = decode(&spec, &raw)?;
self.charge_decoded(data.len())?;
Stream::Buf { data, pos: 0, rgb }
@@ -600,7 +631,7 @@ impl Interp<'_> {
if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") {
return Ok(None);
}
let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) };
let Some(kept) = row.checked_mul(oh).filter(|k| *k <= max_data()) else { return Ok(None) };
self.alloc(kept)?;
// The compressed data: what the filters before the last one decode, or the file itself.
let compressed = if head.is_empty() {
@@ -618,7 +649,7 @@ impl Interp<'_> {
};
let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize);
// Past the image's data and as much again the data is not an image's: it stops there.
let most = row.saturating_mul(s.h).saturating_add(MAX_DATA);
let most = row.saturating_mul(s.h).saturating_add(max_data());
let mut sink = |mut chunk: &[u8]| -> Res {
while !chunk.is_empty() {
let (r, off) = (seen / row.max(1), seen % row.max(1));
@@ -829,7 +860,7 @@ impl Interp<'_> {
let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n));
let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h));
// What is read: an image past the pixel cap is reduced from the samples read.
charged = total.min(MAX_DATA);
charged = total.min(max_data());
self.alloc(charged)?;
let raw = self.source_bytes(&src, charged)?;
by_rows(&raw, (mrow, stencil.h), (drow, image.h))
@@ -838,7 +869,7 @@ impl Interp<'_> {
stencil.bpc = image.bpc;
(stencil.w, stencil.h) = (image.w, image.h);
let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8);
charged = row.saturating_mul(image.h).min(MAX_DATA);
charged = row.saturating_mul(image.h).min(max_data());
self.alloc(charged)?;
let raw = self.source_bytes(&src, charged)?;
by_samples(&raw, image.w, image.h, n, image.bpc)
@@ -1020,7 +1051,7 @@ impl Interp<'_> {
// skipped), while one within the pixel cap whose samples are still too much data
// (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane
// is refused).
let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else {
let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= max_data()) else {
if step > 1 {
return Ok(self.leave_out(&s));
}
+34 -1
View File
@@ -17,6 +17,39 @@ use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err};
/// Most operations one file may run, whatever its length.
const MAX_OPS: u64 = 50_000_000;
#[cfg(test)]
thread_local! {
/// The most operations one file may run on this thread, whatever its length ([`MAX_OPS`] unless
/// a test lowered it).
static OPS_LIMIT: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_OPS) };
}
/// The most operations one file may run, whatever its length: [`MAX_OPS`].
#[cfg(not(test))]
const fn max_ops() -> u64 {
MAX_OPS
}
/// The most operations one file may run, whatever its length: [`OPS_LIMIT`] of this thread.
#[cfg(test)]
pub(crate) fn max_ops() -> u64 {
OPS_LIMIT.get()
}
/// Runs `f` with [`max_ops`] set to `limit` on this thread, and restores it afterwards.
#[cfg(test)]
pub(crate) fn with_ops_limit<R>(limit: u64, f: impl FnOnce() -> R) -> R {
struct Restore(u64);
impl Drop for Restore {
fn drop(&mut self) {
OPS_LIMIT.set(self.0);
}
}
let _restore = Restore(OPS_LIMIT.replace(limit));
f()
}
/// More operations a file may run for each byte of its program: a large file that draws a lot
/// runs proportionally more, and stays bounded by its length.
const OPS_PER_BYTE: u64 = 64;
@@ -228,7 +261,7 @@ impl<'a> Interp<'a> {
resources,
depth: 0,
ops: 0,
max_ops: MAX_OPS.saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)),
max_ops: max_ops().saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)),
allocated: 0,
seed: 1,
saves: vec![],
+9 -4
View File
@@ -7,9 +7,9 @@ use vectorcraft_color::{Color, GradientKind, Paint};
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind};
use vectorcraft_geom::{Point, Rect};
use crate::import::data::measured;
use crate::import::data::{max_data, measured, with_data_limit};
use crate::import::graphics::{GState, Out, tilings_compared};
use crate::import::interp::Interp;
use crate::import::interp::{Interp, max_ops, with_ops_limit};
use crate::import::obj::Obj;
use crate::import::{Dsc, import};
use crate::{EpsOptions, Level, Preview, Raster};
@@ -1282,11 +1282,16 @@ fn read_counting_tilings(body: &str) -> (crate::Imported, u64) {
}
/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and
/// how many decoded bytes the measuring of images' data left out decoded.
/// how many decoded bytes the measuring of images' data left out decoded. The reading thread
/// reads with this thread's data and operation limits ([`with_data_limit`], [`with_ops_limit`]).
fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) {
let (tx, rx) = std::sync::mpsc::channel();
let ps = eps(body);
std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok());
let (data, ops) = (max_data(), max_ops());
std::thread::spawn(move || {
let read = with_ops_limit(ops, || with_data_limit(data, || import(&ps)));
tx.send((read, tilings_compared(), measured())).ok()
});
let (read, compared, measured) =
rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish"));
(read.unwrap(), compared, measured)
+36 -21
View File
@@ -686,11 +686,15 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() {
/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure
/// is called until the data ends; when its first filter decompresses to more than the reader
/// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is
/// measured without keeping it.
/// measured without keeping it. The reader holds 1 MiB here, and each filter's data decompresses
/// to 2 MiB: Flate and LZW data is measured in full (run-length data is measured by its run
/// lengths, without decoding it).
#[test]
fn the_data_of_an_image_too_large_to_hold_is_skipped() {
const LIMIT: usize = 1 << 20;
const DECODED: usize = 2 * LIMIT;
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]);
let zeros = crate::ps::deflate(&vec![0u8; DECODED]);
// Predicted rows aren't decoded a row at a time: such an image is left out.
let mut flate =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
@@ -699,7 +703,7 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
// The same through LZW, which counts the codes up to its end-of-data code.
let mut lzw =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec();
lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true));
lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; DECODED], true));
lzw.extend(format!("\n{after}").as_bytes());
// Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of
// 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in
@@ -707,24 +711,29 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
// run's length and stays off by one.
let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec();
run_length.extend([2, 200, 200, 200]);
run_length.extend([129u8, 200].repeat((300 << 20) / 128));
run_length.extend([129u8, 200].repeat(DECODED / 128));
run_length.push(128);
run_length.extend(format!("\n{after}").as_bytes());
for program in [
format!(
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}"
)
.into_bytes(),
flate,
lzw,
run_length,
for (program, measured) in [
(
format!(
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}"
)
.into_bytes(),
0,
),
(flate, DECODED as u64),
(lzw, DECODED as u64),
(run_length, 0),
] {
let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned();
let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
file.extend(&program);
file.extend(b"\nshowpage\n%%EOF\n");
let r = import(&file).unwrap();
let before = crate::import::data::measured();
let r = crate::import::data::with_data_limit(LIMIT, || import(&file)).unwrap();
assert_eq!(crate::import::data::measured() - before, measured, "{text}");
assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings);
let o = super::tests::objects(&r.document);
assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings);
@@ -733,18 +742,24 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
}
/// Measuring the data of an image too large to hold decompresses it, and that is charged to the
/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed
/// zeros is left out and measured again each time a loop runs the stream from its start, runs out
/// of the budget after it measured the data in full more than once and at most five times.
/// operation budget: a program kept in a reusable stream, whose image over compressed zeros is
/// left out and measured again each time a loop runs the stream from its start, runs out of the
/// budget after it measured the data in full more than once and at most five times. The reader
/// holds 1 MiB here, the zeros decompress to 4 MiB, and the budget a file has whatever its length
/// pays for measuring them twice.
#[test]
fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() {
const LIMIT: usize = 1 << 20;
const DECODED: usize = 4 * LIMIT;
let mut program =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
program.extend(crate::ps::deflate(&vec![0u8; 300 << 20]));
program.extend(crate::ps::deflate(&vec![0u8; DECODED]));
let hex: String = program.iter().map(|b| format!("{b:02x}")).collect();
let measured =
super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"));
assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured");
let body = format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop");
let measured = super::interp::with_ops_limit(DECODED as u64 / 8, || {
crate::import::data::with_data_limit(LIMIT, || super::tests::runs_out_of_budget_measuring(&body))
});
assert!((DECODED as u64 + 1..=5 * DECODED as u64).contains(&measured), "{measured} bytes measured");
}
/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is
+26 -1
View File
@@ -100,8 +100,11 @@ pub struct FontDb {
colours: Mutex<GlyphColours>,
/// The installed fonts: the system font scan's faces, found by any of their names
/// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find
/// never depends on what ran before them.
/// never depends on what ran before them. The bundled faces join it on the first call of
/// [`FontDb::catalog`], so its faces are read through that call.
catalog: Arc<Catalog>,
/// The bundled faces were added to [`Self::catalog`].
bundled_cataloged: std::sync::Once,
/// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces,
/// so no family name, font menu, fallback or PostScript name lookup finds them.
pub(super) file_faces: RwLock<FileFaces>,
@@ -387,6 +390,28 @@ mod race_tests {
}
}
#[cfg(all(test, feature = "bundled-fonts"))]
mod bundled_catalog_tests {
use super::*;
fn bundled_in_catalog(catalog: &Catalog) -> usize {
catalog.faces().iter().filter(|f| f.source == craft::font_catalog::Source::Bundled).count()
}
#[test]
fn the_bundled_fonts_join_the_catalog_when_it_is_first_read() {
let db = FontDb::with_font_dirs(Vec::new());
assert!(!db.read_faces().is_empty(), "the database draws with its bundled faces from the start");
assert_eq!(bundled_in_catalog(&db.catalog), 0, "making the database copies no bundled font into the catalog");
// A lookup that only the catalog answers finds a bundled face.
assert_eq!(db.by_postscript_name("SourceSans3-Bold"), Some(("Source Sans 3".to_string(), "Bold".to_string())));
let added = bundled_in_catalog(&db.catalog);
assert!(added > 0, "the first read of the catalog adds the bundled fonts");
assert!(db.catalog().families().iter().any(|f| f == "Inter"), "font pickers list a bundled family");
assert_eq!(bundled_in_catalog(db.catalog()), added, "later reads add them no second time");
}
}
#[cfg(test)]
mod image_cache_tests {
use super::*;
+1 -1
View File
@@ -31,7 +31,7 @@ impl FontDb {
/// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are
/// never listed. Empty on wasm, which has no installed fonts.
pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded {
let faces = self.catalog.faces();
let faces = self.catalog().faces();
// Each file's creation time once for all its faces (a collection or a variable font's
// named instances share one).
let mut created: HashMap<&Path, Option<SystemTime>> = HashMap::new();
+32 -18
View File
@@ -20,6 +20,14 @@ static NEXT_ID: AtomicU64 = AtomicU64::new(0);
/// [`FontDb::global`].
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
/// The fonts a database starts with: the bundled fonts first, then explicitly supplied craft-fonts
/// faces: Japanese (Mincho first), Arabic, Thai, then remaining faces in manifest order. Existing
/// script fallback priorities stay ahead of the additional families users can now pick by name.
fn bundled_fonts() -> impl Iterator<Item = &'static [u8]> {
let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes);
BUNDLED.iter().copied().chain(craft)
}
impl FontDb {
/// A database holding the bundled fonts, whose system font scan reads `font_dirs` (folders,
/// read with their subfolders, and font files) and nothing else.
@@ -44,15 +52,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
catalog.set_confined_dirs(confined_font_dirs());
let mut faces = Vec::new();
// Bundled fonts first, then explicitly supplied craft-fonts faces: Japanese (Mincho
// first), Arabic, Thai, then remaining faces in manifest order. Existing script fallback
// priorities stay ahead of the additional families users can now pick by name.
let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes);
for data in BUNDLED.iter().copied().chain(craft) {
// Font pickers list the catalog's families: the fonts the app carries are in it as bundled faces.
if let Err(e) = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) {
log::warn!("a bundled font is not in the font catalog: {e}");
}
for data in bundled_fonts() {
for (i, spec) in enumerate_faces(data) {
if let Some(f) = make_face(FontBytes::Static(data), i, spec, None) {
faces.push(Arc::new(f));
@@ -65,6 +65,7 @@ impl FontDb {
images: Mutex::new(GlyphCache::default()),
colours: Mutex::new(GlyphCache::default()),
catalog: Arc::new(catalog),
bundled_cataloged: std::sync::Once::new(),
file_faces: RwLock::new(super::FileFaces::default()),
canonical_cache: Mutex::new(CanonicalNames::new()),
#[cfg(not(target_arch = "wasm32"))]
@@ -119,7 +120,20 @@ impl FontDb {
/// The installed fonts this database finds by name, shared with the framework's font menus and
/// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]).
///
/// The first call adds the bundled fonts to it as [`Source::Bundled`] faces, so font pickers
/// list them. A run that never looks a font up in the catalog, such as exporting a file without
/// type, does not hold the catalog's copies of their bytes.
// The catalog keeps its own copy of the bytes it is given. Adding the bundled fonts on first use
// can go once the catalog takes static bytes without copying them (craft-libs#4888).
pub fn catalog(&self) -> &Arc<Catalog> {
self.bundled_cataloged.call_once(|| {
for data in bundled_fonts() {
if let Err(e) = self.catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) {
log::warn!("a bundled font is not in the font catalog: {e}");
}
}
});
&self.catalog
}
@@ -164,7 +178,7 @@ impl FontDb {
/// [`FontDb::families`], shared: cheap to call every frame.
pub fn family_list(&self) -> Arc<[String]> {
// The catalog's list is the same `Arc` until it rescans (here or in its watch).
let installed = self.catalog.families();
let installed = self.catalog().families();
let mut cache = self.family_cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some((from, list)) = cache.as_ref()
&& Arc::ptr_eq(from, &installed)
@@ -238,7 +252,7 @@ impl FontDb {
}
// An installed family's, from its names in other languages, as a loaded face's is chosen
// (every face of a family has the same names: one is enough).
let native = self.catalog.resolve(&family, "").and_then(|(f, _)| {
let native = self.catalog().resolve(&family, "").and_then(|(f, _)| {
let names: Vec<(Option<String>, String)> = f.localized_families.into_iter().map(|n| (n.language, n.name)).collect();
pick_native_label(&f.family, &names)
});
@@ -256,7 +270,7 @@ impl FontDb {
v.push((f.italic, f.weight, f.style.clone()));
}
}
for f in self.catalog.styles(family) {
for f in self.catalog().styles(family) {
if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&f.style)) {
v.push((f.italic, f.weight, f.style));
}
@@ -282,7 +296,7 @@ impl FontDb {
for f in self.read_faces().iter().filter(|f| f.family.eq_ignore_ascii_case(family)) {
consider(&mut best, f.weight, f.italic, &f.style);
}
for f in self.catalog.styles(family) {
for f in self.catalog().styles(family) {
consider(&mut best, f.weight, f.italic, &f.style);
}
best.map(|(_, style)| style)
@@ -347,7 +361,7 @@ impl FontDb {
/// folders, any other waits for that scan to finish, as every catalog lookup does.
#[cfg(any(test, feature = "test-fonts"))]
pub(crate) fn ensure_catalog(&self) {
let _ = self.catalog.families();
let _ = self.catalog().families();
}
/// Catalog the installed fonts on a background thread, so the first lookup by family name
@@ -370,14 +384,14 @@ impl FontDb {
let _change = self.catalog.is_ready().then(crate::test_fonts::font_change);
// The first scan, or a rescan once it is done (never both at once). The count is of the installed faces: the
// catalog's less the bundled faces no installed file also has.
let cataloged = self.catalog.rescan();
let bundled_only = self.catalog.faces().iter().filter(|f| f.source == Source::Bundled && self.catalog.versions(f).len() == 1).count();
let catalog = self.catalog();
let cataloged = catalog.rescan();
let bundled_only = catalog.faces().iter().filter(|f| f.source == Source::Bundled && catalog.versions(f).len() == 1).count();
let n = cataloged.saturating_sub(bundled_only);
// Files may have been installed since: other versions are looked for again, in the catalog
// the rescan published. A version lookup made during the scan read the previous one.
self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear();
let installed: std::collections::HashSet<PathBuf> =
self.catalog.faces().iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect();
let installed: std::collections::HashSet<PathBuf> = catalog.faces().iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect();
// Faces loaded from a file this scan did not catalog, as a face or a version of one (the font was removed, or its folder
// is no longer read) are dropped with their outlines. A family with no face left and no
// cataloged file leaves the lists, and type set in it resolves to the fallback font. A face
+3 -4
View File
@@ -30,13 +30,12 @@ impl FontDb {
// The catalog first: the first scan takes the faces' lock, which a guard held here would block.
// The bundled faces have no file to read. The catalog lists a bundled face ahead of an
// installed file of the same face, so each face's file is its first installed version.
let cataloged: Vec<(String, String, PathBuf)> = self
.catalog
let catalog = self.catalog();
let cataloged: Vec<(String, String, PathBuf)> = catalog
.faces()
.iter()
.filter_map(|f| {
let path =
self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?;
let path = catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?;
Some((f.family.clone(), f.style.clone(), path))
})
.collect();
+13 -11
View File
@@ -73,7 +73,7 @@ impl FontDb {
}
#[cfg(not(target_arch = "wasm32"))]
{
let faces = self.catalog.styles(family);
let faces = self.catalog().styles(family);
let off = |f: &craft::font_catalog::FaceInfo| (f.italic, (f.weight - 400.0).abs());
let nearest = faces.iter().min_by(|a, b| {
let ((ai, aw), (bi, bw)) = (off(a), off(b));
@@ -89,7 +89,7 @@ impl FontDb {
/// Is `family` an installed family's own name (any ASCII case)?
fn is_installed(&self, family: &str) -> bool {
self.catalog.family(family).is_some_and(|f| f.eq_ignore_ascii_case(family))
self.catalog().family(family).is_some_and(|f| f.eq_ignore_ascii_case(family))
}
/// The family's own name and the style for a name given in a document: any of a family's
@@ -124,7 +124,7 @@ impl FontDb {
self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).filter(|(k, _)| *k == key).map(|(_, a)| a).collect();
// The installed face the name gives: by a family name in its family, by a legacy family
// name with its legacy style, by a full or PostScript name whatever the style.
let installed = self.catalog.resolve(family, style);
let installed = self.catalog().resolve(family, style);
let ns = norm(style);
// A family and style split from a PostScript name by an importer that didn't have the font
// (`Honoka-Mincho` → Honoka, Mincho): once it is installed, the face of that PostScript
@@ -147,7 +147,7 @@ impl FontDb {
if let Some(a) = found.iter().find(|a| a.style.is_none()) {
return (a.family.clone(), style.to_string());
}
if let Some(installed_family) = self.catalog.family(family) {
if let Some(installed_family) = self.catalog().family(family) {
return (installed_family, style.to_string());
}
if let Some(a) = found.iter().find(|a| a.paired.as_ref().is_some_and(|p| *p == ns) || a.paired.is_none()) {
@@ -278,7 +278,7 @@ impl FontDb {
let key = norm(name);
let mut families: Vec<String> = vec![first.family.clone()];
let named = |f: &&FaceInfo| f.postscript_name.as_deref().is_some_and(|p| norm(p) == key);
for f in self.catalog.faces().iter().filter(named) {
for f in self.catalog().faces().iter().filter(named) {
if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|known| known.eq_ignore_ascii_case(&f.family)) {
families.push(f.family.clone());
}
@@ -303,13 +303,14 @@ impl FontDb {
/// The cataloged face of PostScript name `name`: an installed face before a bundled face of another family with the
/// same name, as the installed faces alone answered before the bundled ones were cataloged.
fn cataloged_postscript(&self, name: &str) -> Option<FaceInfo> {
let face = self.catalog.by_postscript_name(name)?;
let catalog = self.catalog();
let face = catalog.by_postscript_name(name)?;
if face.source != Source::Bundled {
return Some(face);
}
let key = norm(name);
let named = |f: &&FaceInfo| f.source != Source::Bundled && f.postscript_name.as_deref().is_some_and(|p| norm(p) == key);
Some(self.catalog.faces().iter().find(named).cloned().unwrap_or(face))
Some(catalog.faces().iter().find(named).cloned().unwrap_or(face))
}
/// Load the files of the installed `family`, every cataloged version of its faces included,
@@ -317,8 +318,9 @@ impl FontDb {
/// thread meanwhile.
#[cfg(not(target_arch = "wasm32"))]
fn load_cataloged(&self, family: &str) -> bool {
let faces = self.catalog.styles(family);
let mut paths: Vec<PathBuf> = faces.iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect();
let catalog = self.catalog();
let faces = catalog.styles(family);
let mut paths: Vec<PathBuf> = faces.iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect();
paths.sort();
paths.dedup();
let files = paths.into_iter().flat_map(|p| font_files(&p).into_iter().map(move |data| (data, Some(p.clone()))));
@@ -403,7 +405,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
fn is_cataloged(&self, family: &str, style: &str) -> bool {
let ns = norm(style);
self.catalog.styles(family).iter().any(|f| norm(&f.style) == ns)
self.catalog().styles(family).iter().any(|f| norm(&f.style) == ns)
}
/// The loaded face with [`FontFace::id`] `id` (the face a laid-out glyph came from), an
@@ -680,7 +682,7 @@ impl FontDb {
}
sys.file_searches += 1;
}
let mut paths: Vec<PathBuf> = self.catalog.faces().iter().filter_map(|f| f.path.clone()).collect();
let mut paths: Vec<PathBuf> = self.catalog().faces().iter().filter_map(|f| f.path.clone()).collect();
paths.sort();
paths.dedup();
for p in paths {
+12 -3
View File
@@ -1317,15 +1317,24 @@ fn window_viewport(app: &VectorcraftApp, panel: &str) -> Option<egui::ViewportId
}
/// Whether the OS window of a floating panel lies at `pos`, a point of the main window: a palette
/// window stays in front of the main window.
/// window stays in front of the main window. A hidden or minimized palette window does not count.
pub(crate) fn os_window_at(app: &VectorcraftApp, ctx: &egui::Context, pos: egui::Pos2) -> bool {
if app.dock_rt.windows.is_empty() {
return false;
}
// Workaround for craft-libs#4739: `WindowHost::viewports_at` still lists palette windows that are minimized, or
// hidden while a dialog or popup shows. Remove these checks when the craft-libs pin includes craft-libs#4739.
if app.any_dialog_open() {
return false;
}
let origin = ctx.input(|i| i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.inner_rect).map(|r| r.min.to_vec2()));
let Some(origin) = origin else { return false };
let under = craft::ui::runtime::windows::WindowHost::of(ctx).viewports_at(pos + origin);
under.iter().any(|viewport| app.dock_rt.windows.iter().any(|(_, shown)| shown == viewport))
let host = craft::ui::runtime::windows::WindowHost::of(ctx);
let under = host.viewports_at(pos + origin);
// Workaround for craft-libs#4739 (see above).
let restored =
|viewport: &egui::ViewportId| host.facts(*viewport).is_some_and(|facts| facts.state != craft::host::target::WindowState::Minimized);
under.iter().filter(|viewport| restored(viewport)).any(|viewport| app.dock_rt.windows.iter().any(|(_, shown)| shown == viewport))
}
/// Brings the OS window of the floating window holding `panel` forward, as it was last drawn.
@@ -28,6 +28,8 @@ struct Window {
/// Whether the window shows on the desktop: the builder's visibility when it opened, then each
/// `Visible` command.
visible: bool,
/// Whether the OS reports the window minimized.
minimized: bool,
frames: usize,
/// The texts its last frame drew, with their rects in the window.
texts: Vec<(String, Rect)>,
@@ -59,6 +61,7 @@ impl Host {
std::iter::once((ViewportId::ROOT, info(ViewportId::ROOT, SCREEN.translate(ORIGIN.to_vec2()))))
.chain(self.windows.iter().map(|(id, w)| {
let mut info = info(*id, w.rect);
info.minimized = Some(w.minimized);
if w.close_requested {
info.events.push(egui::ViewportEvent::Close);
}
@@ -96,6 +99,7 @@ impl Host {
dropped: Vec::new(),
close_requested: false,
visible: builder.visible != Some(false),
minimized: false,
frames: 0,
texts: Vec::new(),
nodes: Vec::new(),
@@ -633,3 +637,47 @@ fn a_window_menu_panel_stays_shown_while_art_is_selected_and_moved() {
);
}
}
/// A floating panel's window over the canvas, with the main window holding the keyboard: the window and the point at
/// its middle, in the main window's points.
fn palette_over_canvas(h: &mut Harness) -> (ViewportId, Pos2) {
let viewport = h.float("graphicStyles");
h.host.borrow_mut().focus = ViewportId::ROOT;
h.frames(2);
let middle = h.host.borrow().windows[&viewport].rect.center() - ORIGIN.to_vec2();
let view = h.app.canvas_view().expect("the canvas was drawn");
assert!(view.rect.contains(middle), "the window lies over the canvas");
assert!(os_window_at(&h.app, &h.ctx, middle), "the shown window covers the canvas under it");
(viewport, middle)
}
/// A minimized palette window leaves the canvas under the place it had uncovered, and covers it again once restored.
#[test]
fn a_minimized_palette_window_does_not_cover_the_canvas() {
let mut h = Harness::new();
let (viewport, middle) = palette_over_canvas(&mut h);
h.host.borrow_mut().windows.get_mut(&viewport).unwrap().minimized = true;
h.frames(2);
assert!(!os_window_at(&h.app, &h.ctx, middle), "a minimized window covers nothing");
h.host.borrow_mut().windows.get_mut(&viewport).unwrap().minimized = false;
h.frames(2);
assert!(os_window_at(&h.app, &h.ctx, middle), "the restored window covers the canvas again");
}
/// While a dialog shows, the palette windows are hidden and leave the canvas uncovered.
#[test]
fn a_hidden_palette_window_does_not_cover_the_canvas() {
let mut h = Harness::new();
let (_, middle) = palette_over_canvas(&mut h);
crate::menus::invoke(&mut h.app, "view.rotate", json!({}));
h.frames(2);
assert!(h.app.any_dialog_open(), "the Rotate View dialog shows");
assert!(!os_window_at(&h.app, &h.ctx, middle), "a palette hidden behind a dialog covers nothing");
let ctx = h.app.ui_ctx.clone().expect("a frame ran");
let id = h.app.dialogs().expect("a window").with(|host| host.open_dialogs().last().map(|d| d.id)).expect("a dialog is open");
assert!(h.app.dialogs().expect("a window").with(|host| host.cancel_by_id(&ctx, id)), "the dialog took the answer");
crate::dialogs::host::pump(&mut h.app, &ctx);
h.frames(2);
assert!(!h.app.any_dialog_open(), "the dialog closed");
assert!(os_window_at(&h.app, &h.ctx, middle), "the palette covers the canvas again once the dialog closes");
}
+7 -1
View File
@@ -17073,7 +17073,13 @@ key holds a gradient or a pattern, the count is the largest distance between the
bounding-box edges divided by their mean width (left and right edges) or height (top and bottom), rounded, less one,
from 1 to 1000. Keys with no width or no height are measured by their other side, keys with neither in points, and
keys without bounds make 1 step. `starts` gives, per object, the anchor of its first subpath the blend starts
from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). With the
from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). Steps
between two live rectangles with the same corner kinds and the same rotation and reflection, and with no scale
or shear left in their transforms, are live rectangles whose width, height and drawn corner radii lie between
the keys', so their rounded corners stay circular arcs. The drawn radius is a key's radius fitted to its sides (a
20 by 10 key that stores a radius of 50 blends with a radius of 5). On a straight spine the steps' positions also
lie between the keys'; on an edited or replaced spine each step sits on the spine. Other path and live-shape pairs use anchor matching. A start anchor given in
`starts` for either key also sends live rectangles through anchor matching; an all-null `starts` does not. With the
Blend tool, `press_key` Escape drops the object clicked first and stops the next click adding to the blend
just made; the document and the selection stay as they are. A blend
among the objects takes the others in as more key objects, keeping its options, name, transparency and whether it
+1
View File
@@ -2136,6 +2136,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A double-click with the Live Paint Selection tool on a face selects it and the faces of its group that no stroked edge parts from it ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)), and on an edge selects it and the edges joined to it end to end that have its stroke paint ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)); Shift-double-click adds them to the selection or removes them from it. A triple-click on a face selects every face of its group with that face's fill, and on an edge every edge of its group that has its stroke paint ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)); hidden faces and edges are left out, and Shift-triple-click adds them to the selection or removes them from it.
When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`.
Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected.
Steps between two live rectangles with the same corner kinds, turned and reflected alike, are live rectangles whose sizes and drawn corner radii lie between the keys', so their rounded corners stay circular arcs (#10707). The drawn radii are the radii after each key's radius is fitted to its sides: a 20 by 10 key that stores a radius of 50 draws and blends with a radius of 5. On a straight spine the steps' positions also lie between the keys'; on an edited or replaced spine each step sits on the spine. A start point clicked on either key, a scale or shear left in a key's transform, and every other pair of paths keep anchor-by-anchor matching. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`.
The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`.
Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`.
The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`.