From a84de561834f97c4b76e185335b2bdc97a1c2503 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 15:31:08 +0100 Subject: [PATCH 01/24] refactor(color): satisfy Clippy pedantic lints --- crates/color/src/lib.rs | 64 +++++++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index e99f8d269..ea58d63ab 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -1,5 +1,5 @@ //! CAD colours: the 256-entry colour index (ACI), 24-bit true colour, and the logical -//! ByLayer / ByBlock values. The index palette is generated from its well-known structure +//! `ByLayer` / `ByBlock` values. The index palette is generated from its well-known structure //! (24 hues × 5 values × 2 saturations, plus primaries and greys), not copied from any file. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -11,12 +11,15 @@ use serde::{Deserialize, Serialize}; pub struct Rgb(pub u8, pub u8, pub u8); impl Rgb { + #[must_use] pub fn to_u32(self) -> u32 { (u32::from(self.0) << 16) | (u32::from(self.1) << 8) | u32::from(self.2) } + #[must_use] pub fn from_u32(v: u32) -> Rgb { Rgb(((v >> 16) & 0xff) as u8, ((v >> 8) & 0xff) as u8, (v & 0xff) as u8) } + #[must_use] pub fn hex(self) -> String { format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2) } @@ -29,6 +32,7 @@ impl Rgb { u32::from_str_radix(s, 16).ok().map(Rgb::from_u32) } /// Relative luminance (0..1) for contrast decisions. + #[must_use] pub fn luma(self) -> f64 { (0.2126 * f64::from(self.0) + 0.7152 * f64::from(self.1) + 0.0722 * f64::from(self.2)) / 255.0 } @@ -48,7 +52,8 @@ pub enum Color { impl Color { pub const WHITE: Color = Color::Index(7); - /// DXF group 62 value: 0 = ByBlock, 256 = ByLayer. + /// DXF group 62 value: 0 = `ByBlock`, 256 = `ByLayer`. + #[must_use] pub fn to_aci(self) -> i16 { match self { Color::ByLayer => 256, @@ -57,14 +62,16 @@ impl Color { Color::True(rgb) => i16::from(nearest_aci(rgb)), } } + #[must_use] pub fn from_aci(v: i16) -> Color { match v { 0 => Color::ByBlock, - 1..=255 => Color::Index(v as u8), + 1..=255 => u8::try_from(v).map_or(Color::ByLayer, Color::Index), _ => Color::ByLayer, } } /// Resolve to RGB given the layer and block colours. + #[must_use] pub fn resolve(self, layer: Color, block: Color) -> Rgb { match self { Color::ByLayer => match layer { @@ -79,7 +86,8 @@ impl Color { Color::True(c) => c, } } - /// Short display name like AutoCAD's Properties palette ("ByLayer", "Red", "Color 34", "255,128,0"). + /// Short display name like `AutoCAD`'s Properties palette ("`ByLayer`", "Red", "Color 34", "255,128,0"). + #[must_use] pub fn name(self) -> String { match self { Color::ByLayer => "ByLayer".into(), @@ -102,7 +110,7 @@ impl Color { let t = s.trim().to_ascii_lowercase(); let named = ["", "red", "yellow", "green", "cyan", "blue", "magenta", "white"]; if let Some(i) = named.iter().position(|n| !n.is_empty() && *n == t) { - return Some(Color::Index(i as u8)); + return u8::try_from(i).ok().map(Color::Index); } match t.as_str() { "bylayer" => return Some(Color::ByLayer), @@ -117,7 +125,7 @@ impl Color { return match i { 0 => Some(Color::ByBlock), 256 => Some(Color::ByLayer), - 1..=255 => Some(Color::Index(i as u8)), + 1..=255 => u8::try_from(i).ok().map(Color::Index), _ => None, }; } @@ -145,11 +153,16 @@ pub fn aci_rgb(i: u8) -> Rgb { PALETTE.get(usize::from(i)).copied().unwrap_or(Rgb(255, 255, 255)) } -/// The palette as a 256-entry table (entry 0 = ByBlock placeholder = black). +/// The palette as a 256-entry table (entry 0 = `ByBlock` placeholder = black). pub static PALETTE: std::sync::LazyLock<[Rgb; 256]> = std::sync::LazyLock::new(build_palette); +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "Palette channels are finite and clamped to the u8 range before conversion." +)] fn build_palette() -> [Rgb; 256] { - let mut p = [Rgb(0, 0, 0); 256]; + let mut palette = [Rgb(0, 0, 0); 256]; let base = [ Rgb(0, 0, 0), Rgb(255, 0, 0), @@ -162,34 +175,35 @@ fn build_palette() -> [Rgb; 256] { Rgb(128, 128, 128), Rgb(192, 192, 192), ]; - for (slot, c) in p.iter_mut().zip(base) { - *slot = c; + for (slot, colour) in palette.iter_mut().zip(base) { + *slot = colour; } let values = [255.0, 204.0, 153.0, 127.0, 76.0]; - for i in 10..250usize { - let hue = (i - 10) / 10; // 0..24, 15° each - let sub = i % 10; - let v: f64 = values.get(sub / 2).copied().unwrap_or(255.0); + for index in 10..250usize { + let hue = (index - 10) / 10; // 0..24, 15° each + let sub = index % 10; + let value: f64 = values.get(sub / 2).copied().unwrap_or(255.0); let half = sub % 2 == 1; - let (r, g, b) = hue_fractions(hue); - let ch = |f: f64| -> u8 { - let f = if half { 0.5 + 0.5 * f } else { f }; - (v * f).floor().clamp(0.0, 255.0) as u8 + let (red, green, blue) = hue_fractions(hue); + let channel = |fraction: f64| -> u8 { + let fraction = if half { 0.5 + 0.5 * fraction } else { fraction }; + (value * fraction).floor().clamp(0.0, 255.0) as u8 }; - if let Some(slot) = p.get_mut(i) { - *slot = Rgb(ch(r), ch(g), ch(b)); + if let Some(slot) = palette.get_mut(index) { + *slot = Rgb(channel(red), channel(green), channel(blue)); } } let greys = [51u8, 91, 132, 173, 214, 255]; - for (k, g) in greys.iter().enumerate() { - if let Some(slot) = p.get_mut(250 + k) { - *slot = Rgb(*g, *g, *g); + for (offset, shade) in greys.iter().enumerate() { + if let Some(slot) = palette.get_mut(250 + offset) { + *slot = Rgb(*shade, *shade, *shade); } } - p + palette } /// Channel fractions for hue step 0..24 (red → yellow → green → cyan → blue → magenta → red). +#[expect(clippy::cast_precision_loss, reason = "Only the four hue offsets 0..=3 are converted; they are exact in f64.")] fn hue_fractions(h: usize) -> (f64, f64, f64) { let seg = h / 4; let t = (h % 4) as f64 / 4.0; @@ -204,6 +218,7 @@ fn hue_fractions(h: usize) -> (f64, f64, f64) { } /// The closest index colour to an RGB value (1..=255). +#[must_use] pub fn nearest_aci(c: Rgb) -> u8 { let mut best = (u32::MAX, 7u8); for i in 1..=255u8 { @@ -220,6 +235,7 @@ pub fn nearest_aci(c: Rgb) -> u8 { /// Display colour of `c` on `background`. Colour 7 (`aci7`) flips to contrast with the /// background, white on dark and black on light (paper), as CAD programs draw it; every other /// colour, including a true-colour or index white or black, keeps its RGB. +#[must_use] pub fn display_rgb(c: Rgb, aci7: bool, background: Rgb) -> Rgb { if !aci7 { c From 2ac6d98dacdb7b899dd03b64ec8294a0c22971fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 18:32:23 +0100 Subject: [PATCH 02/24] refactor(geom): satisfy Clippy pedantic lints --- crates/geom/src/bounds.rs | 21 +++++-- crates/geom/src/curve.rs | 70 +++++++++++++++++++++- crates/geom/src/fillet.rs | 9 +++ crates/geom/src/intersect.rs | 8 +++ crates/geom/src/lib.rs | 13 ++++- crates/geom/src/mat.rs | 20 +++++++ crates/geom/src/nurbs.rs | 84 ++++++++++++++++++++------ crates/geom/src/property_tests.rs | 16 +++-- crates/geom/src/region.rs | 29 ++++++++- crates/geom/src/spline.rs | 41 +++++++++++-- crates/geom/src/spline/tests.rs | 33 +++++++---- crates/geom/src/spline_fit.rs | 97 +++++++++++++++++++++++-------- crates/geom/src/tests.rs | 6 +- crates/geom/src/vec.rs | 29 +++++++++ 14 files changed, 403 insertions(+), 73 deletions(-) diff --git a/crates/geom/src/bounds.rs b/crates/geom/src/bounds.rs index ba5b7175d..ad7f2549f 100644 --- a/crates/geom/src/bounds.rs +++ b/crates/geom/src/bounds.rs @@ -24,6 +24,7 @@ impl Default for Bounds2 { impl Bounds2 { pub const EMPTY: Bounds2 = Bounds2 { min: Vec2 { x: f64::INFINITY, y: f64::INFINITY }, max: Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY } }; + #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Bounds2 { min: a.min(b), max: a.max(b) } } @@ -34,6 +35,7 @@ impl Bounds2 { } b } + #[must_use] pub fn is_empty(&self) -> bool { !(self.min.x <= self.max.x && self.min.y <= self.max.y) } @@ -43,6 +45,7 @@ impl Bounds2 { self.max = self.max.max(p); } } + #[must_use] pub fn union(&self, o: &Bounds2) -> Bounds2 { if o.is_empty() { return *self; @@ -52,12 +55,15 @@ impl Bounds2 { } Bounds2 { min: self.min.min(o.min), max: self.max.max(o.max) } } + #[must_use] pub fn width(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.x, self.max.x) } } + #[must_use] pub fn height(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.y, self.max.y) } } + #[must_use] pub fn center(&self) -> Vec2 { if self.is_empty() { return Vec2::ZERO; @@ -65,26 +71,31 @@ impl Bounds2 { // (max - min) can overflow even when both endpoints and their midpoint // are finite. Halve first when the endpoints have opposite signs. let mid = |a: f64, b: f64| { - if a.is_sign_negative() != b.is_sign_negative() { a * 0.5 + b * 0.5 } else { a + (b - a) * 0.5 } + if a.is_sign_negative() == b.is_sign_negative() { a + (b - a) * 0.5 } else { a * 0.5 + b * 0.5 } }; Vec2::new(mid(self.min.x, self.max.x), mid(self.min.y, self.max.y)) } + #[must_use] pub fn contains(&self, p: Vec2) -> bool { p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y } /// True when `o` lies entirely inside. + #[must_use] pub fn contains_box(&self, o: &Bounds2) -> bool { !o.is_empty() && self.contains(o.min) && self.contains(o.max) } + #[must_use] pub fn intersects(&self, o: &Bounds2) -> bool { !(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y) } + #[must_use] pub fn expand(&self, d: f64) -> Bounds2 { if self.is_empty() { return *self; } Bounds2 { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) } } + #[must_use] pub fn corners(&self) -> [Vec2; 4] { [self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)] } @@ -101,17 +112,17 @@ mod tests { let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0)); assert!(b.center().x.is_finite()); assert!((b.center().x / 1e308 - 1.3).abs() < 1e-12); - assert_eq!(b.center().y, 5.0); + assert_eq!(b.center().y.to_bits(), 5.0_f64.to_bits()); assert_eq!(Bounds2::EMPTY.center(), Vec2::ZERO); } #[test] fn width_and_height_stay_finite_for_opposite_large_coordinates() { let b = Bounds2::new(Vec2::new(-1e308, -1e308), Vec2::new(1e308, 1e308)); - assert_eq!(b.width(), f64::MAX); - assert_eq!(b.height(), f64::MAX); + assert_eq!(b.width().to_bits(), f64::MAX.to_bits()); + assert_eq!(b.height().to_bits(), f64::MAX.to_bits()); let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0)); assert!((b.width() / 1e308 - 0.6).abs() < 1e-12); - assert_eq!(b.height(), 10.0); + assert_eq!(b.height().to_bits(), 10.0_f64.to_bits()); } } diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index 5d0e53f17..ddda27e82 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -10,42 +10,53 @@ pub struct Line { } impl Line { + #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Line { a, b } } + #[must_use] pub fn len(&self) -> f64 { self.a.dist(self.b) } + #[must_use] pub fn dir(&self) -> Vec2 { (self.b - self.a).normalized() } + #[must_use] pub fn mid(&self) -> Vec2 { self.a.mid(self.b) } /// Parameter (0..1 on the segment) of the projection of `p`. + #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let d = self.b - self.a; let l2 = d.len2(); if l2 <= EPS * EPS { 0.0 } else { (p - self.a).dot(d) / l2 } } + #[must_use] pub fn at(&self, t: f64) -> Vec2 { self.a.lerp(self.b, t) } /// Closest point on the segment. + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p).clamp(0.0, 1.0)) } /// Foot of the perpendicular on the infinite line. + #[must_use] pub fn project(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p)) } + #[must_use] pub fn dist(&self, p: Vec2) -> f64 { self.closest(p).dist(p) } /// Signed side: > 0 left of a→b. + #[must_use] pub fn side(&self, p: Vec2) -> f64 { (self.b - self.a).cross(p - self.a) } + #[must_use] pub fn offset(&self, d: f64) -> Line { let n = (self.b - self.a).normalized().perp() * d; Line::new(self.a + n, self.b + n) @@ -62,32 +73,41 @@ pub struct Arc { } impl Arc { + #[must_use] pub fn new(center: Vec2, radius: f64, start: f64, end: f64) -> Self { Arc { center, radius: radius.abs(), start: norm_angle(start), end: norm_angle(end) } } + #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } + #[must_use] pub fn start_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start) } + #[must_use] pub fn end_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.end) } + #[must_use] pub fn mid_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() / 2.0) } + #[must_use] pub fn len(&self) -> f64 { self.radius * self.sweep() } + #[must_use] pub fn contains_angle(&self, a: f64) -> bool { angle_in_sweep(a, self.start, self.end) } /// Point at parameter `t` in 0..1 along the sweep. + #[must_use] pub fn at(&self, t: f64) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() * t) } /// Arc through three points, or `None` when collinear. + #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { let c = Circle::from_3_points(p1, p2, p3)?; let a1 = c.center.angle_to(p1); @@ -97,9 +117,11 @@ impl Arc { if angle_in_sweep(a2, a1, a3) { Some(Arc::new(c.center, c.radius, a1, a3)) } else { Some(Arc::new(c.center, c.radius, a3, a1)) } } /// Arc from start point, center and end point (CCW). + #[must_use] pub fn from_start_center_end(s: Vec2, c: Vec2, e: Vec2) -> Arc { Arc::new(c, s.dist(c), c.angle_to(s), c.angle_to(e)) } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let a = self.center.angle_to(p); if self.contains_angle(a) && p.dist(self.center) > EPS { @@ -110,16 +132,18 @@ impl Arc { if s.dist(p) <= e.dist(p) { s } else { e } } } + #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points([self.start_point(), self.end_point()]); for k in 0..4 { - let a = k as f64 * PI / 2.0; + let a = f64::from(k) * PI / 2.0; if self.contains_angle(a) { b.add(Vec2::polar(self.center, self.radius, a)); } } b } + #[expect(clippy::cast_precision_loss, reason = "arc_segments caps the sample count at 4096, so every sample index is exact as f64.")] pub fn tessellate(&self, tol: f64, out: &mut Vec) { let sweep = self.sweep(); let n = arc_segments(self.radius, sweep, tol); @@ -137,9 +161,11 @@ pub struct Circle { } impl Circle { + #[must_use] pub fn new(center: Vec2, radius: f64) -> Self { Circle { center, radius: radius.abs() } } + #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { // Work in point-relative coordinates. Absolute coordinate squares lose the small // differences between points in drawings far from the origin. @@ -165,13 +191,16 @@ impl Circle { } Some(Circle::new(c, radius)) } + #[must_use] pub fn from_2_points(p1: Vec2, p2: Vec2) -> Circle { Circle::new(p1.mid(p2), p1.dist(p2) / 2.0) } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let d = p - self.center; if d.len() < EPS { self.center + Vec2::X * self.radius } else { self.center + d.normalized() * self.radius } } + #[must_use] pub fn bounds(&self) -> Bounds2 { Bounds2::new(self.center - Vec2::new(self.radius, self.radius), self.center + Vec2::new(self.radius, self.radius)) } @@ -179,6 +208,7 @@ impl Circle { Arc { center: self.center, radius: self.radius, start: 0.0, end: TAU }.tessellate(tol, out); } /// Tangent points from external point `p`. + #[must_use] pub fn tangent_points(&self, p: Vec2) -> Vec { let d = p.dist(self.center); if d <= self.radius + EPS { @@ -192,6 +222,8 @@ impl Circle { /// up to two outer (belt) tangents and two inner (crossed) tangents. Empty for concentric /// circles or when one circle lies inside the other; tangents that touch both circles at the /// same point (circles touching each other) are left out. + #[must_use] + #[expect(clippy::many_single_char_names, reason = "Circle-tangent equations use conventional r/v/d/u/c/h/n/p/q notation.")] pub fn common_tangents(&self, other: &Circle) -> Vec<(Vec2, Vec2)> { let (r1, r2) = (self.radius, other.radius); let v = other.center - self.center; @@ -232,18 +264,23 @@ pub struct Ellipse { } impl Ellipse { + #[must_use] pub fn full(center: Vec2, major: Vec2, ratio: f64) -> Self { Ellipse { center, major, ratio, start: 0.0, end: TAU } } + #[must_use] pub fn is_full(&self) -> bool { (ccw_sweep(self.start, self.end) - TAU).abs() < 1e-9 } + #[must_use] pub fn minor(&self) -> Vec2 { self.major.perp() * self.ratio } + #[must_use] pub fn at_param(&self, t: f64) -> Vec2 { self.center + self.major * t.cos() + self.minor() * t.sin() } + #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } @@ -264,6 +301,7 @@ impl Ellipse { let (start, end) = if u.cross(v) >= 0.0 { (self.start - t0, self.end - t0) } else { (t0 - self.end, t0 - self.start) }; Ellipse { center, major: u, ratio, start: norm_angle(start), end: norm_angle(end) } } + #[expect(clippy::cast_precision_loss, reason = "arc_segments caps the sample count at 4096, so every sample index is exact as f64.")] pub fn tessellate(&self, tol: f64, out: &mut Vec) { let r = self.major.len(); let sweep = self.sweep(); @@ -272,6 +310,7 @@ impl Ellipse { out.push(self.at_param(self.start + sweep * i as f64 / n as f64)); } } + #[must_use] pub fn bounds(&self) -> Bounds2 { // Sampled bounds can cut off the true extrema, especially on a small arc or // a large drawing. The derivative of each coordinate gives two exact @@ -286,6 +325,7 @@ impl Ellipse { bounds } /// Parameter of the point on the ellipse nearest the direction of `p` (approximate). + #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let ma = self.major.len(); if ma < EPS { @@ -298,6 +338,7 @@ impl Ellipse { let mb = ma * self.ratio; norm_angle((y / mb.max(EPS)).atan2(x / ma)) } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let mut pts = Vec::new(); self.tessellate(self.major.len() * 1e-3, &mut pts); @@ -332,6 +373,7 @@ pub enum Segment { } impl Segment { + #[must_use] pub fn start(&self) -> Vec2 { match self { Segment::Line(l) => l.a, @@ -339,6 +381,7 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.end_point(), } } + #[must_use] pub fn end(&self) -> Vec2 { match self { Segment::Line(l) => l.b, @@ -346,24 +389,28 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.start_point(), } } + #[must_use] pub fn len(&self) -> f64 { match self { Segment::Line(l) => l.len(), Segment::Arc { arc, .. } => arc.len(), } } + #[must_use] pub fn mid(&self) -> Vec2 { match self { Segment::Line(l) => l.mid(), Segment::Arc { arc, .. } => arc.mid_point(), } } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { match self { Segment::Line(l) => l.closest(p), Segment::Arc { arc, .. } => arc.closest(p), } } + #[must_use] pub fn bounds(&self) -> Bounds2 { match self { Segment::Line(l) => Bounds2::new(l.a, l.b), @@ -381,12 +428,13 @@ impl Segment { let start = out.len(); arc.tessellate(tol, out); if !ccw && let Some(s) = out.get_mut(start..) { - s.reverse() + s.reverse(); } } } } /// Point at parameter `t` (0..1) in segment direction. + #[must_use] pub fn at(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.at(t), @@ -394,6 +442,7 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.at(1.0 - t), } } + #[must_use] pub fn reversed(&self) -> Segment { match *self { Segment::Line(l) => Segment::Line(Line::new(l.b, l.a)), @@ -401,6 +450,7 @@ impl Segment { } } /// Tangent direction (unit) at parameter t. + #[must_use] pub fn tangent(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.dir(), @@ -412,6 +462,7 @@ impl Segment { } } /// Offset by `d` to the left of travel direction. `None` if an arc collapses. + #[must_use] pub fn offset(&self, d: f64) -> Option { match *self { Segment::Line(l) => Some(Segment::Line(l.offset(d))), @@ -440,15 +491,18 @@ pub struct PolyVertex { } impl PolyVertex { + #[must_use] pub fn new(p: Vec2) -> Self { PolyVertex { p, ..Default::default() } } + #[must_use] pub fn with_bulge(p: Vec2, bulge: f64) -> Self { PolyVertex { p, bulge, ..Default::default() } } } /// Convert a bulge segment to an arc. `None` for a straight (zero-bulge or degenerate) segment. +#[must_use] pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { if bulge.abs() < 1e-12 || !bulge.is_finite() || a.near(b, EPS) { return None; @@ -473,6 +527,7 @@ pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { } /// Bulge for an arc traversed from `a` to `b` with the given sweep (signed: + = CCW). +#[must_use] pub fn arc_to_bulge(signed_sweep: f64) -> f64 { (signed_sweep / 4.0).tan() } @@ -488,10 +543,12 @@ pub struct Polyline { pub const MAX_TESSELLATED_POINTS: usize = 4_000_000; impl Polyline { + #[must_use] pub fn from_points(pts: &[Vec2], closed: bool) -> Self { Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed } } /// The segments, including the closing segment when closed. + #[must_use] pub fn segments(&self) -> Vec { let n = self.vertices.len(); let mut out = Vec::with_capacity(n); @@ -511,6 +568,7 @@ impl Polyline { pub fn len(&self) -> f64 { self.segments().iter().map(Segment::len).sum() } + #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points(self.vertices.iter().map(|v| v.p)); for s in self.segments() { @@ -518,6 +576,7 @@ impl Polyline { } b } + #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { let mut budget = MAX_TESSELLATED_POINTS; self.tessellate_within(tol, &mut budget) @@ -546,6 +605,7 @@ impl Polyline { out } /// Signed area (CCW positive) of a closed polyline including bulge areas. + #[must_use] pub fn area(&self) -> f64 { // Integrate the chords exactly and add the signed circular-segment area // for every bulge. A tessellated shoelace loses precision on large arcs. @@ -573,6 +633,7 @@ impl Polyline { } twice_area / 2.0 } + #[must_use] pub fn closest(&self, p: Vec2) -> Option { let mut best: Option<(f64, Vec2)> = None; for s in self.segments() { @@ -585,11 +646,13 @@ impl Polyline { best.map(|(_, c)| c).or_else(|| self.vertices.first().map(|v| v.p)) } /// True if `p` is inside a closed polyline (even-odd on the tessellation). + #[must_use] pub fn contains(&self, p: Vec2) -> bool { point_in_polygon(&self.tessellate(1e-3), p) } /// Area centroid of the closed polyline, exact with bulges: the chord triangles fanned from the /// first vertex plus each bulge's circular segment, weighted by signed area. `None` at zero area. + #[expect(clippy::many_single_char_names, reason = "Centroid integration uses conventional a/b/c/d/t area and point notation.")] pub fn centroid(&self) -> Option { let origin = self.vertices.first()?.p; let n = self.vertices.len(); @@ -622,11 +685,13 @@ impl Polyline { } /// Area centroid of a closed polygon. `None` at zero area. +#[must_use] pub fn polygon_centroid(pts: &[Vec2]) -> Option { Polyline::from_points(pts, true).centroid() } /// Signed polygon area (CCW positive). +#[must_use] pub fn shoelace(pts: &[Vec2]) -> f64 { let n = pts.len(); if n < 3 { @@ -647,6 +712,7 @@ pub fn shoelace(pts: &[Vec2]) -> f64 { } /// Even-odd point-in-polygon test. +#[must_use] pub fn point_in_polygon(poly: &[Vec2], p: Vec2) -> bool { let n = poly.len(); if n < 3 { diff --git a/crates/geom/src/fillet.rs b/crates/geom/src/fillet.rs index 78e1fc93b..74b06385b 100644 --- a/crates/geom/src/fillet.rs +++ b/crates/geom/src/fillet.rs @@ -49,6 +49,7 @@ struct Range { impl TanCurve { /// Point at parameter `t`. + #[must_use] pub fn point(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.a + (l.b - l.a) * t, @@ -59,6 +60,7 @@ impl TanCurve { } /// First derivative at parameter `t`. + #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.b - l.a, @@ -69,6 +71,7 @@ impl TanCurve { } /// The point at distance `d` along the left normal at `t` (`None` where the curve stops). + #[expect(clippy::many_single_char_names, reason = "The offset equation uses conventional t/d/p/n/q geometric notation.")] fn offset(&self, t: f64, d: f64) -> Option { let p = self.point(t); if d == 0.0 { @@ -125,6 +128,11 @@ impl TanCurve { } /// A sampled offset curve: runs of consecutive (parameter, point) samples. +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Sample counts are capped by MAX_SPLINE_SAMPLES, and c/r/d/i/t/p name the curve, range, offset and sample equations." +)] fn sample(c: &TanCurve, r: &Range, d: f64) -> Vec> { let n = c.sample_count(); let mut runs: Vec> = vec![Vec::new()]; @@ -232,6 +240,7 @@ fn refine(c1: &TanCurve, r1: &Range, d1: f64, c2: &TanCurve, r2: &Range, d2: f64 /// Circles of radius `r` tangent to both curves (`r = 0`: the points where they cross). `near` /// (the pick points) widens the search window for lines. Every distinct solution is returned; /// callers choose one, usually the nearest the picks. +#[must_use] pub fn tangent_circles(c1: &TanCurve, c2: &TanCurve, r: f64, near: &[Vec2]) -> Vec { if !(r.is_finite() && r >= 0.0) { return Vec::new(); diff --git a/crates/geom/src/intersect.rs b/crates/geom/src/intersect.rs index 653cd61c9..4e7714b6e 100644 --- a/crates/geom/src/intersect.rs +++ b/crates/geom/src/intersect.rs @@ -1,6 +1,7 @@ use crate::{Arc, Circle, EPS, Line, Segment, Vec2}; /// Intersection of two infinite lines through (a1,a2) and (b1,b2), with parameters on each. +#[must_use] pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec2, f64, f64)> { let r = a2 - a1; let s = b2 - b1; @@ -14,6 +15,8 @@ pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec } /// Intersection of two finite segments. +#[must_use] +#[expect(clippy::many_single_char_names, reason = "Segment endpoints and parameters use conventional a/b/p/t/u geometric notation.")] pub fn line_line(a: &Line, b: &Line) -> Option { let (p, t, u) = line_line_infinite(a.a, a.b, b.a, b.b)?; let tol = 1e-9; @@ -21,6 +24,8 @@ pub fn line_line(a: &Line, b: &Line) -> Option { } /// Intersections of the infinite line through `l` with a circle. Returns points with line params. +#[must_use] +#[expect(clippy::many_single_char_names, reason = "The line/circle quadratic uses conventional a/d/f/t mathematical notation.")] pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { let d = l.b - l.a; let f = l.a - c.center; @@ -52,6 +57,7 @@ pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { } /// Intersections of two full circles. +#[must_use] pub fn circle_circle(c1: &Circle, c2: &Circle) -> Vec { let delta = c2.center - c1.center; let d = delta.len(); @@ -101,12 +107,14 @@ fn on_arc(a: &Arc, p: Vec2) -> bool { } /// Intersections between two segments (finite). +#[must_use] pub fn intersect_segments(s1: &Segment, s2: &Segment) -> Vec { intersect_segments_ext(s1, s2, false) } /// Intersections; with `extend` true, lines are infinite and arcs are full circles /// (used by TRIM/EXTEND edge mode and apparent intersections). +#[must_use] pub fn intersect_segments_ext(s1: &Segment, s2: &Segment, extend: bool) -> Vec { let tol = 1e-9; match (s1, s2) { diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index d482141fd..40b47d6d5 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,4 +1,4 @@ -//! CADCraft geometry: double-precision 2D/3D math for drafting. +//! `CADCraft` geometry: double-precision 2D/3D math for drafting. //! //! Everything a CAD kernel needs below the document model: vectors and affine transforms, //! bounding boxes, angles, lines, circular arcs (and polyline bulges), ellipses, NURBS splines, @@ -36,6 +36,7 @@ pub const TAU: f64 = std::f64::consts::TAU; pub const PI: f64 = std::f64::consts::PI; /// Normalize an angle to `[0, 2π)`. +#[must_use] pub fn norm_angle(a: f64) -> f64 { if !a.is_finite() { return 0.0; @@ -45,26 +46,36 @@ pub fn norm_angle(a: f64) -> f64 { } /// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`. +#[must_use] pub fn ccw_sweep(start: f64, end: f64) -> f64 { let s = norm_angle(end - start); if s <= EPS { TAU } else { s } } /// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance). +#[must_use] pub fn angle_in_sweep(a: f64, start: f64, end: f64) -> bool { let sweep = ccw_sweep(start, end); let d = norm_angle(a - start); d <= sweep + 1e-12 || (TAU - d) < 1e-12 } +#[must_use] pub fn deg(r: f64) -> f64 { r.to_degrees() } +#[must_use] pub fn rad(d: f64) -> f64 { d.to_radians() } /// Number of segments needed to approximate an arc of `radius` and `sweep` within `tol`. +#[must_use] +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "The segment count is nonnegative and immediately clamped to 1..=4096; float-to-usize saturation handles out-of-range values." +)] pub fn arc_segments(radius: f64, sweep: f64, tol: f64) -> usize { let r = radius.abs(); if !(r.is_finite() && sweep.is_finite()) || r <= EPS { diff --git a/crates/geom/src/mat.rs b/crates/geom/src/mat.rs index 5f28b068d..ec7a2075b 100644 --- a/crates/geom/src/mat.rs +++ b/crates/geom/src/mat.rs @@ -22,24 +22,30 @@ impl Default for Mat3 { impl Mat3 { pub const IDENTITY: Mat3 = Mat3 { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; + #[must_use] pub fn translate(v: Vec2) -> Mat3 { Mat3 { e: v.x, f: v.y, ..Mat3::IDENTITY } } + #[must_use] pub fn scale(sx: f64, sy: f64) -> Mat3 { Mat3 { a: sx, d: sy, ..Mat3::IDENTITY } } + #[must_use] pub fn rotate(angle: f64) -> Mat3 { let (s, c) = angle.sin_cos(); Mat3 { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 } } /// Scale about `base`. + #[must_use] pub fn scale_about(base: Vec2, s: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::scale(s, s)).then_before(Mat3::translate(-base)) } + #[must_use] pub fn rotate_about(base: Vec2, angle: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::rotate(angle)).then_before(Mat3::translate(-base)) } /// Reflection across the line through `p1`, `p2`. + #[must_use] pub fn mirror(p1: Vec2, p2: Vec2) -> Mat3 { let d = (p2 - p1).normalized(); if d == Vec2::ZERO { @@ -50,6 +56,7 @@ impl Mat3 { Mat3::translate(p1).then_before(r).then_before(Mat3::translate(-p1)) } /// `self * o`: apply `o` first, then `self`. + #[must_use] pub fn then_before(self, o: Mat3) -> Mat3 { Mat3 { a: self.a * o.a + self.c * o.b, @@ -61,18 +68,24 @@ impl Mat3 { } } /// Apply `self` first, then `o`. + #[must_use] pub fn then(self, o: Mat3) -> Mat3 { o.then_before(self) } + #[must_use] pub fn apply(&self, p: Vec2) -> Vec2 { Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f) } + #[must_use] pub fn apply_vec(&self, v: Vec2) -> Vec2 { Vec2::new(self.a * v.x + self.c * v.y, self.b * v.x + self.d * v.y) } + #[must_use] pub fn det(&self) -> f64 { self.a * self.d - self.b * self.c } + #[must_use] + #[expect(clippy::many_single_char_names, reason = "Matrix coefficients use the same a–f notation as Mat3 and the affine-transform formula.")] pub fn inverse(&self) -> Option { let det = self.det(); if det.abs() < 1e-300 || !det.is_finite() { @@ -88,13 +101,16 @@ impl Mat3 { Some(Mat3 { a, b, c, d, e, f }) } /// Uniform scale factor (geometric mean of the axis scales). + #[must_use] pub fn scale_factor(&self) -> f64 { self.det().abs().sqrt() } /// Rotation angle of the transformed X axis. + #[must_use] pub fn rotation(&self) -> f64 { crate::norm_angle(self.b.atan2(self.a)) } + #[must_use] pub fn is_mirroring(&self) -> bool { self.det() < 0.0 } @@ -122,6 +138,7 @@ impl Default for Mat4 { impl Mat4 { pub const IDENTITY: Mat4 = Mat4 { m: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] }; + #[must_use] pub fn mul(&self, o: &Mat4) -> Mat4 { let mut r = [[0.0; 4]; 4]; for (i, row) in r.iter_mut().enumerate() { @@ -131,6 +148,7 @@ impl Mat4 { } Mat4 { m: r } } + #[must_use] pub fn apply(&self, p: Vec3) -> Vec3 { let m = &self.m; let w = m[3][0] * p.x + m[3][1] * p.y + m[3][2] * p.z + m[3][3]; @@ -141,10 +159,12 @@ impl Mat4 { (m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3]) / w, ) } + #[must_use] pub fn from_mat3(t: &Mat3) -> Mat4 { Mat4 { m: [[t.a, t.c, 0.0, t.e], [t.b, t.d, 0.0, t.f], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] } } /// The "arbitrary axis algorithm" frame for an extrusion direction (DXF OCS → WCS). + #[must_use] pub fn ocs(normal: Vec3) -> Mat4 { let n = normal.normalized(); if n == Vec3::ZERO || (n.x.abs() < 1e-12 && n.y.abs() < 1e-12 && n.z > 0.0) { diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 04cf933cb..2c8e070f5 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -44,8 +44,9 @@ const GAUSS: [(f64, f64); 5] = [ (0.906_179_845_938_664, 0.236_926_885_056_189_1), ]; +#[expect(clippy::many_single_char_names, reason = "Gauss–Legendre quadrature uses conventional a/b/f/m/h/x/w notation.")] fn gauss(a: f64, b: f64, f: impl Fn(f64) -> f64) -> f64 { - let (m, h) = ((a + b) / 2.0, (b - a) / 2.0); + let (m, h) = (f64::midpoint(a, b), (b - a) / 2.0); GAUSS.iter().map(|(x, w)| w * f(m + h * x)).sum::() * h } @@ -55,8 +56,12 @@ const MAX_GAUSS_DEPTH: usize = 10; /// `gauss` over [a, b], halving until the two halves agree with the whole: a fixed panel count /// is far off on a tight bend, and the arc-length inverse must agree with the measure. +#[expect( + clippy::many_single_char_names, + reason = "Adaptive quadrature keeps the panel endpoints, midpoint and left/right integrals in mathematical notation." +)] fn adaptive_gauss(a: f64, b: f64, whole: f64, f: &impl Fn(f64) -> f64, depth: usize) -> f64 { - let m = (a + b) / 2.0; + let m = f64::midpoint(a, b); let (l, r) = (gauss(a, m, f), gauss(m, b, f)); if depth == 0 || !(l + r).is_finite() || (l + r - whole).abs() <= 1e-10 * (l + r).abs() { return l + r; @@ -76,6 +81,7 @@ fn bezier_knots(breaks: &[f64], p: usize) -> Vec { } /// One degree elevation of a homogeneous Bézier piece. +#[expect(clippy::cast_precision_loss, reason = "Bézier pieces are bounded by MAX_EDIT_DEGREE, so their control indices are exact as f64.")] fn elevate_bezier(p: &[H]) -> Vec { let n = p.len(); let zero = (Vec2::ZERO, 0.0); @@ -122,6 +128,7 @@ impl Spline { } /// True when the spline carries weights (a NURBS rather than a plain B-spline). + #[must_use] pub fn is_rational(&self) -> bool { !self.weights.is_empty() } @@ -148,6 +155,7 @@ impl Spline { } /// First derivative dC/dt (zero on an invalid spline). + #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { if !self.is_valid() { return Vec2::ZERO; @@ -208,6 +216,7 @@ impl Spline { /// Unit tangent at `t` in the direction of increasing parameter; a central difference stands /// in where the derivative vanishes. Zero when the curve does not move at all. + #[must_use] pub fn unit_tangent(&self, t: f64) -> Vec2 { let d = self.derivative(t).normalized(); if d != Vec2::ZERO { @@ -220,6 +229,8 @@ impl Spline { /// Insert knot `t` once (Boehm's algorithm, in homogeneous coordinates). The result has no /// fit data and is open. + #[must_use] + #[expect(clippy::many_single_char_names, reason = "Boehm knot insertion keeps the standard p/n/k/i/h/a equation notation.")] pub fn insert_knot(&self, t: f64) -> Option { if !self.is_valid() || !t.is_finite() || self.control.len() >= MAX_EDIT_CONTROL { return None; @@ -287,6 +298,7 @@ impl Spline { } /// Split at parameter `t` into (before, after). `None` at the ends or on invalid input. + #[must_use] pub fn split_at(&self, t: f64) -> Option<(Spline, Spline)> { let (lo, hi) = self.domain(); if !(t > lo + 1e-12 && t < hi - 1e-12) { @@ -297,6 +309,7 @@ impl Spline { } /// The open piece between parameters `a < b`. + #[must_use] pub fn sub_between(&self, a: f64, b: f64) -> Option { let (lo, hi) = self.domain(); let mut s = self.clone(); @@ -313,6 +326,7 @@ impl Spline { /// The same curve with clamped ends (end knots repeated degree + 1 times), so it starts and /// ends on its first and last control points. Fit data is dropped. + #[must_use] pub fn clamped(&self) -> Option { if !self.is_valid() { return None; @@ -321,7 +335,7 @@ impl Spline { let (lo, hi) = self.domain(); let mut s = self.clone(); s.fit.clear(); - s.fit_opts = Default::default(); + s.fit_opts = crate::FitOptions::default(); if !s.knots.get(..=p).is_some_and(|k| k.iter().all(|x| (*x - lo).abs() < 1e-12)) { s = s.split_raw(lo)?.1; } @@ -335,6 +349,7 @@ impl Spline { /// Reversed direction: control points, weights, fit points and knots (and the fit end /// tangents swap ends and turn round). + #[must_use] pub fn reversed(&self) -> Spline { let (lo, hi) = (self.knots.first().copied().unwrap_or(0.0), self.knots.last().copied().unwrap_or(1.0)); Spline { @@ -387,6 +402,7 @@ impl Spline { } /// The same curve at a higher (or equal) degree, clamped. + #[must_use] pub fn elevated(&self, degree: usize) -> Option { if degree < self.degree || degree > MAX_EDIT_DEGREE { return None; @@ -412,6 +428,11 @@ impl Spline { /// point becomes their midpoint). Degrees are matched by elevation, weights rescaled so the /// junction carries one weight, and `other`'s parameters follow on at a similar speed. The /// junction is a knot of multiplicity `degree`, so the curve passes through it exactly. + #[must_use] + #[expect( + clippy::many_single_char_names, + reason = "Spline joining keeps the two curves, homogeneous points and knot spans in standard short notation." + )] pub fn joined(&self, other: &Spline) -> Option { let deg = self.degree.max(other.degree); let a = self.elevated(deg)?; @@ -440,6 +461,8 @@ impl Spline { /// A straight line from `a` to `b` as a clamped spline of `degree` (evenly spaced control /// points, parameter = distance). + #[must_use] + #[expect(clippy::cast_precision_loss, reason = "The degree is clamped by MAX_EDIT_DEGREE (25), so every control index is exact as f64.")] pub fn from_line(a: Vec2, b: Vec2, degree: usize) -> Spline { let p = degree.clamp(1, MAX_EDIT_DEGREE); let control = (0..=p).map(|i| a.lerp(b, i as f64 / p as f64)).collect(); @@ -453,6 +476,14 @@ impl Spline { /// The elliptical arc `center + u·cos θ + v·sin θ` for θ from `start` over `sweep` (negative /// runs clockwise) as an exact rational quadratic spline, in pieces of at most a quarter /// turn. Circular arcs are the case `|u| = |v|`, `u ⟂ v`. + #[must_use] + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::many_single_char_names, + reason = "Conic decomposition uses one to four pieces and standard parametric notation, so all piece indices are exact as f64." + )] pub fn from_conic_arc(center: Vec2, u: Vec2, v: Vec2, start: f64, sweep: f64) -> Option { if !(start.is_finite() && sweep.is_finite() && center.is_finite() && u.is_finite() && v.is_finite()) || sweep.abs() < 1e-12 @@ -482,6 +513,7 @@ impl Spline { } /// An ellipse or elliptical arc as an exact rational spline (counter-clockwise). + #[must_use] pub fn from_ellipse(e: &Ellipse) -> Option { let s = Spline::from_conic_arc(e.center, e.major, e.minor(), e.start, e.sweep())?; Some(Spline { closed: e.is_full(), ..s }) @@ -489,6 +521,7 @@ impl Spline { /// Run the spline on in a straight line along its end tangent by `dist` > 0: past the end /// (`at_end`) or before the start. The result is clamped, open and has no fit data. + #[must_use] pub fn extended(&self, at_end: bool, dist: f64) -> Option { if !(dist.is_finite() && dist > 0.0) || self.closed { return None; @@ -515,7 +548,7 @@ impl Spline { for w in cuts.windows(2) { let (Some(&x0), Some(&x1)) = (w.first(), w.get(1)) else { continue }; for i in 0..4 { - out.push((x0 + (x1 - x0) * i as f64 / 4.0, x0 + (x1 - x0) * (i + 1) as f64 / 4.0)); + out.push((x0 + (x1 - x0) * f64::from(i) / 4.0, x0 + (x1 - x0) * f64::from(i + 1) / 4.0)); } } out @@ -531,12 +564,14 @@ impl Spline { } /// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span). + #[must_use] pub fn length_between(&self, a: f64, b: f64) -> f64 { let l = self.integrated_length(a, b); if l.is_finite() { l } else { 0.0 } } /// Arc length of the whole spline. + #[must_use] pub fn length(&self) -> f64 { let (lo, hi) = self.domain(); self.length_between(lo, hi) @@ -563,6 +598,7 @@ impl Spline { /// The parameter `len` along the curve from parameter `from` (forward for positive `len`, /// backward for negative), clamped to the domain. + #[must_use] pub fn param_at_length(&self, from: f64, len: f64) -> f64 { let (lo, hi) = self.domain(); if !self.is_valid() { @@ -587,7 +623,7 @@ impl Spline { let (near, far) = if len > 0.0 { (x0, x1) } else { (x1, x0) }; let (mut s0, mut s1) = (near, far); for _ in 0..60 { - let m = (s0 + s1) / 2.0; + let m = f64::midpoint(s0, s1); let lm = self.panel_length(near.min(m), near.max(m), Spline::derivative_unchecked); if lm < rest { s0 = m; @@ -595,7 +631,7 @@ impl Spline { s1 = m; } } - return (s0 + s1) / 2.0; + return f64::midpoint(s0, s1); } acc += l; } @@ -605,11 +641,19 @@ impl Spline { impl Ellipse { /// dP/dθ at parameter `t`. + #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { self.minor() * t.cos() - self.major * t.sin() } /// Arc length from parameter `t0` counter-clockwise over `sweep` (radians, >= 0). + #[must_use] + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "The quadrature panel count is clamped to 1..=512, so panel indices are nonnegative and exact as f64." + )] pub fn arc_length_from(&self, t0: f64, sweep: f64) -> f64 { if !(t0.is_finite() && sweep.is_finite()) || sweep <= 0.0 { return 0.0; @@ -628,12 +672,14 @@ impl Ellipse { } /// Arc length of the ellipse or elliptical arc. + #[must_use] pub fn length(&self) -> f64 { self.arc_length_from(self.start, self.sweep()) } /// The parameter reached `len` along the ellipse from `t0`: counter-clockwise for positive /// `len`, clockwise for negative. `None` for a whole turn or more, or degenerate input. + #[must_use] pub fn param_at_length(&self, t0: f64, len: f64) -> Option { let full = self.arc_length_from(0.0, TAU); if !(t0.is_finite() && len.is_finite() && full > EPS) || len.abs() >= full { @@ -643,14 +689,14 @@ impl Ellipse { let along = |s: f64| if len >= 0.0 { self.arc_length_from(t0, s) } else { self.arc_length_from(t0 - s, s) }; let (mut a, mut b) = (0.0, TAU); for _ in 0..80 { - let m = (a + b) / 2.0; + let m = f64::midpoint(a, b); if along(m) < target { a = m; } else { b = m; } } - let s = (a + b) / 2.0; + let s = f64::midpoint(a, b); Some(if len >= 0.0 { t0 + s } else { t0 - s }) } } @@ -795,7 +841,7 @@ mod tests { s.weights = vec![1.0, 2.0, 0.5, 1.0, 1.5]; let (lo, hi) = s.domain(); for i in 1..20 { - let t = lo + (hi - lo) * i as f64 / 20.0; + let t = lo + (hi - lo) * f64::from(i) / 20.0; let h = 1e-6; let fd = (s.eval(t + h) - s.eval(t - h)) / (2.0 * h); assert!(s.derivative(t).near(fd, 1e-4), "{t}: {:?} vs {fd:?}", s.derivative(t)); @@ -825,7 +871,7 @@ mod tests { assert!(!c.is_periodic()); let ((plo, phi), (clo, chi)) = (p.domain(), c.domain()); for i in 0..=20 { - let f = i as f64 / 20.0; + let f = f64::from(i) / 20.0; assert!(p.eval(plo + (phi - plo) * f).near(c.eval(clo + (chi - clo) * f), 1e-9)); } assert!(c.control.first().unwrap().near(p.eval(plo), 1e-9)); @@ -837,7 +883,7 @@ mod tests { let e = s.elevated(5).unwrap(); assert_eq!(e.degree, 5); for i in 0..=20 { - let t = i as f64 / 20.0; + let t = f64::from(i) / 20.0; assert!(e.eval(t).near(s.eval(t), 1e-9), "{t}"); } // A rational quarter circle elevated to a cubic stays on the circle. @@ -845,12 +891,13 @@ mod tests { let q3 = q.elevated(3).unwrap(); let (lo, hi) = q3.domain(); for i in 0..=20 { - assert!((q3.eval(lo + (hi - lo) * i as f64 / 20.0).len() - 2.0).abs() < 1e-9); + assert!((q3.eval(lo + (hi - lo) * f64::from(i) / 20.0).len() - 2.0).abs() < 1e-9); } assert!(s.elevated(2).is_none() && s.elevated(1000).is_none()); } #[test] + #[expect(clippy::many_single_char_names, reason = "The ellipse equation check keeps conventional center/axis/point notation.")] fn conic_arcs_are_exact() { let e = Ellipse { center: Vec2::new(1.0, 2.0), major: Vec2::new(4.0, 3.0), ratio: 0.5, start: 0.3, end: 5.5 }; let s = Spline::from_ellipse(&e).unwrap(); @@ -860,7 +907,7 @@ mod tests { let (a, b) = (e.major.len(), e.major.len() * e.ratio); let ux = e.major.normalized(); for i in 0..=40 { - let p = s.eval(lo + (hi - lo) * i as f64 / 40.0) - e.center; + let p = s.eval(lo + (hi - lo) * f64::from(i) / 40.0) - e.center; let (x, y) = (p.dot(ux), p.dot(ux.perp())); assert!(((x / a).powi(2) + (y / b).powi(2) - 1.0).abs() < 1e-9); } @@ -881,8 +928,8 @@ mod tests { assert!(j.eval(lo).near(Vec2::new(-5.0, 0.0), 1e-12) && j.eval(hi).near(Vec2::new(12.0, 2.0), 1e-12)); // The line part is straight (parameter = distance), the spline part unchanged. for i in 0..=10 { - assert!(j.eval(lo + 0.5 * i as f64).near(Vec2::new(-5.0 + 0.5 * i as f64, 0.0), 1e-12)); - let f = i as f64 / 10.0; + assert!(j.eval(lo + 0.5 * f64::from(i)).near(Vec2::new(-5.0 + 0.5 * f64::from(i), 0.0), 1e-12)); + let f = f64::from(i) / 10.0; assert!(j.eval(5.0 + (hi - 5.0) * f).near(s.eval(f), 1e-9)); } assert!((j.length() - (5.0 + s.length())).abs() < 1e-6); @@ -917,7 +964,7 @@ mod tests { assert!(q.eval(t).near(Vec2::new(0.0, 2.0), 1e-6)); let t = q.param_at_length(hi, -std::f64::consts::PI / 2.0); assert!(q.eval(t).near(Vec2::new(-2f64.sqrt(), 2f64.sqrt()), 1e-6)); - assert_eq!(q.param_at_length(lo, 1e9), hi); + assert_eq!(q.param_at_length(lo, 1e9).to_bits(), hi.to_bits()); } #[test] @@ -966,12 +1013,13 @@ mod tests { nan.knots[nan.degree] = f64::NAN; assert!(!nan.is_valid() && nan.domain().0.is_nan()); for s in [reversed, nan] { - assert_eq!(s.param_at_length(0.5, 1.0), 0.5); - assert_eq!(s.param_at_length(0.5, -1.0), 0.5); + assert_eq!(s.param_at_length(0.5, 1.0).to_bits(), 0.5_f64.to_bits()); + assert_eq!(s.param_at_length(0.5, -1.0).to_bits(), 0.5_f64.to_bits()); } } #[test] + #[expect(clippy::many_single_char_names, reason = "The ellipse arc-length reference uses conventional a/b/h/t notation.")] fn ellipse_arc_length() { let c = Ellipse::full(Vec2::ZERO, Vec2::new(3.0, 0.0), 1.0); assert!((c.length() - TAU * 3.0).abs() < 1e-9); diff --git a/crates/geom/src/property_tests.rs b/crates/geom/src/property_tests.rs index 0584c9109..27299d641 100644 --- a/crates/geom/src/property_tests.rs +++ b/crates/geom/src/property_tests.rs @@ -22,13 +22,15 @@ impl Rng { x ^= x << 25; x ^= x >> 27; self.0 = x; - x.wrapping_mul(0x2545F4914F6CDD1D) + x.wrapping_mul(0x2545_F491_4F6C_DD1D) } /// Uniform in `[-scale, scale]`. + #[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")] fn f64(&mut self, scale: f64) -> f64 { ((self.next() >> 11) as f64 / (1u64 << 53) as f64) * 2.0 * scale - scale } /// Uniform in `[lo, hi]`. + #[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")] fn range(&mut self, lo: f64, hi: f64) -> f64 { lo + (hi - lo) * (self.next() >> 11) as f64 / (1u64 << 53) as f64 } @@ -96,7 +98,7 @@ fn on_line(p: Vec2, a: Vec2, d: Vec2, rel: f64) -> bool { /// The infinite-line intersection lies on both lines, and swapping the lines gives the same point. #[test] fn line_line_infinite_lies_on_both_and_is_symmetric() { - let mut r = Rng::new(0xC0FFEE); + let mut r = Rng::new(0xC0_FFEE); let mut checked = 0; for _ in 0..4000 { let (a1, a2, b1, b2) = (r.vec(1000.0), r.vec(1000.0), r.vec(1000.0), r.vec(1000.0)); @@ -115,8 +117,9 @@ fn line_line_infinite_lies_on_both_and_is_symmetric() { /// The finite-line result agrees with the parameters of the infinite one. #[test] +#[expect(clippy::many_single_char_names, reason = "The property uses the same a/b/p/t/u notation as the geometric equations under test.")] fn line_line_matches_infinite_parameters() { - let mut r = Rng::new(0xBAD5EED); + let mut r = Rng::new(0xBAD_5EED); for _ in 0..4000 { let a = Line::new(r.vec(100.0), r.vec(100.0)); let b = Line::new(r.vec(100.0), r.vec(100.0)); @@ -220,7 +223,7 @@ fn circle_circle_hits_lie_on_both_and_match_the_closed_form() { /// Degenerate and hostile circles: concentric, contained, negative/NaN radii, extreme centres. #[test] fn circle_circle_degenerate_and_hostile_never_panic() { - let mut r = Rng::new(0xD15EA5E); + let mut r = Rng::new(0xD15_EA5E); for _ in 0..3000 { let c1 = Circle { center: Vec2::new(r.hostile(), r.hostile()), radius: r.hostile() }; let c2 = Circle { center: Vec2::new(r.hostile(), r.hostile()), radius: r.hostile() }; @@ -240,7 +243,7 @@ fn circle_circle_degenerate_and_hostile_never_panic() { /// Extending segments only adds hits: the finite result is a subset of the extended one. #[test] fn segment_extension_only_adds_hits() { - let mut r = Rng::new(0x5E6C0DE); + let mut r = Rng::new(0x5E6_C0DE); for _ in 0..3000 { let s1 = Segment::Line(Line::new(r.vec(100.0), r.vec(100.0))); let s2 = Segment::Line(Line::new(r.vec(100.0), r.vec(100.0))); @@ -259,6 +262,7 @@ fn segment_extension_only_adds_hits() { /// The closest point on a line is a fixed point of `closest`, and the offset is perpendicular. #[test] +#[expect(clippy::many_single_char_names, reason = "The property uses conventional line/point/parameter notation from the closest-point equations.")] fn line_closest_is_a_fixed_point_and_perpendicular() { let mut r = Rng::new(0xC105E); for _ in 0..4000 { @@ -309,7 +313,7 @@ fn arc_endpoints_and_sampling_are_consistent() { assert!(pt_eq(a.at(0.0), a.start_point(), 1e-9), "at(0) != start_point"); assert!(pt_eq(a.at(1.0), a.end_point(), 1e-9), "at(1) != end_point"); for k in 0..=10 { - let t = k as f64 / 10.0; + let t = f64::from(k) / 10.0; let p = a.at(t); assert!(p.x.is_finite() && p.y.is_finite(), "arc sample not finite at t={t}: {p:?}"); assert!(on_circle(p, a.center, a.radius, 1e-9), "arc sample at t={t} off the circle: {p:?}"); diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index a132c699b..6c7578606 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -44,6 +44,10 @@ pub struct Island { pub sources: Vec, } +#[expect( + clippy::cast_possible_truncation, + reason = "Rounded tolerance-bin coordinates intentionally use the defined saturating f64-to-i64 conversion." +)] fn key(p: Vec2, origin: Vec2, q: f64) -> (i64, i64) { // The drawing may be georeferenced far from (0, 0). Quantizing absolute // coordinates saturates i64 and aliases distinct vertices into one key. @@ -90,6 +94,12 @@ fn pair_splits(segs: &[(Vec2, Vec2)], bb: &Bounds2) -> Option>> { /// `pair_splits` with explicit budgets: `None` once more than `max_visits` candidate pairs were visited /// or more than `max_pairs` distinct pairs were tested. +#[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "At most 60,000 segments and 512 grid cells bound the numeric conversions; cell coordinates are clamped before casting." +)] fn pair_splits_limited(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option>> { let n = segs.len(); let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); @@ -333,6 +343,7 @@ fn points(g: &Graph, ids: &[usize]) -> Option> { } /// The face around `p`, as vertex indices (counter-clockwise). +#[expect(clippy::many_single_char_names, reason = "Ray/edge traversal keeps conventional graph and point notation.")] fn outer_face(g: &Graph, p: Vec2) -> Option> { // Try hits along a ray to +X from nearest outward, so nested faces resolve to the innermost. let mut hits: Vec<(f64, usize, usize)> = Vec::new(); @@ -431,6 +442,11 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option> { } /// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`). +#[expect( + clippy::float_cmp, + clippy::many_single_char_names, + reason = "Exact x equality is required for the deterministic lexicographic tie-break; graph equations keep their conventional short names." +)] fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { let comp = components(g); let outer_comp: std::collections::HashSet = outer.iter().filter_map(|&i| comp.get(i).copied()).collect(); @@ -503,6 +519,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { /// The point of the nearest other curve within `snap` of the end `e` of curve `i`, as (curve, /// segment, parameter, point). `None` when the end touches a curve, or none is near. `Err` when /// the budget of segment checks runs out. +#[expect(clippy::many_single_char_names, reason = "Nearest-point search keeps conventional i/j/k/a/b/t/q/d geometry notation.")] fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, budget: &mut usize) -> Result, ()> { let mut best: Option<(f64, usize, usize, f64, Vec2)> = None; let mut touching = false; @@ -546,6 +563,8 @@ fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, bu /// curve (which gains a vertex there), so the two meet exactly. A curve that is flattened /// into chords (an ellipse, a spline) lies up to the flattening tolerance off the true curve, /// so a line that ends on the true curve can stop just short of the chords. +#[must_use] +#[expect(clippy::many_single_char_names, reason = "Endpoint snapping keeps conventional polyline, segment and point notation.")] pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { let mut out: Vec> = polys.to_vec(); if !(snap.is_finite() && snap > tol) { @@ -595,22 +614,26 @@ pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { } /// The closed loop enclosing `p`, counter-clockwise, or `None`. +#[must_use] pub fn enclosing_loop(polys: &[Vec], p: Vec2, tol: f64) -> Option> { enclosing_loop_gap(polys, p, tol, 0.0) } /// [`enclosing_loop`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). +#[must_use] pub fn enclosing_loop_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; points(&g, &outer_face(&g, p)?) } /// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed. +#[must_use] pub fn boundary_at(polys: &[Vec], p: Vec2, tol: f64) -> Option { boundary_at_gap(polys, p, tol, 0.0) } /// [`boundary_at`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). +#[must_use] pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option { let g = build_gap(polys, tol, gap)?; let ids = outer_face(&g, p)?; @@ -626,6 +649,8 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti /// The outside outline of curves that together enclose an area (counter-clockwise, dangling /// ends removed), or `None` when they enclose nothing or form more than one separate group. /// Gaps of up to `gap` between curve ends are closed (HPGAPTOL). +#[must_use] +#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")] pub fn outline(polys: &[Vec], tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; let core = prune(&g); @@ -869,6 +894,7 @@ mod tests { } #[test] + #[expect(clippy::cast_precision_loss, reason = "The test generates 17,000 segments, so every grid index is exact as f64.")] fn long_segment_crossing_in_unsampled_cell_is_split() { // A diagonal long enough to skip the grid, and a short segment crossing it in a cell the old coarse sampling missed. let mut polys = vec![vec![Vec2::new(0.0, 0.0), Vec2::new(1000.0, 1000.0)], vec![Vec2::new(11.0, 12.0), Vec2::new(12.0, 11.0)]]; @@ -943,7 +969,7 @@ mod tests { } fn lines_of(poly: &[Vec2]) -> Vec> { - poly.windows(2).map(|w| w.to_vec()).collect() + poly.windows(2).map(<[Vec2]>::to_vec).collect() } #[test] @@ -1096,6 +1122,7 @@ mod tests { } #[test] + #[expect(clippy::cast_precision_loss, reason = "The test is capped at MAX_SEGMENTS (60,000), so every generated coordinate is exact as f64.")] fn snap_ends_skips_input_over_the_segment_cap() { let mut polys: Vec> = (0..=MAX_SEGMENTS) .map(|i| { diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index 99b63f941..8192cbb30 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -6,7 +6,7 @@ use crate::{Bounds2, Vec2}; /// Largest B-spline degree treated as valid. Basis evaluation is O(degree²) per sample and /// tessellation takes O(degree) samples, so an unbounded degree (DXF/HATCH can declare up to /// 100 000) turns a tiny spline into billions of iterations (CWE-407). Real splines are low -/// degree (AutoCAD caps at 11); above this a spline evaluates to its control polygon instead. +/// degree (`AutoCAD` caps at 11); above this a spline evaluates to its control polygon instead. pub const MAX_DEGREE: usize = 64; /// A (possibly rational) B-spline curve, DXF SPLINE style. @@ -30,6 +30,7 @@ pub struct Spline { impl Spline { /// A clamped uniform spline over control points. + #[must_use] pub fn from_control(control: Vec, degree: usize) -> Spline { let n = control.len(); let degree = degree.clamp(1, n.saturating_sub(1).max(1)); @@ -39,6 +40,7 @@ impl Spline { /// Cubic interpolation through fit points (chord-length parametrisation, natural-ish ends /// via a clamped knot vector: solve the banded system for control points). + #[must_use] pub fn from_fit_points(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, false, FitOptions::default()) } @@ -47,20 +49,24 @@ impl Spline { /// include the closing chord; the knot vector is the periodic (unclamped) extension and the /// first `degree` control points repeat at the end, so the curve has continuous tangent and /// curvature at the seam. A repeated closing fit point is dropped. + #[must_use] pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, true, FitOptions::default()) } /// Interpolation through fit points, open or closed (see `from_fit_points_closed`). + #[must_use] pub fn from_fit(fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, FitOptions::default()) } /// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2). + #[must_use] pub fn is_periodic(&self) -> bool { self.closed && self.knots.first() != self.knots.get(self.degree) } + #[must_use] pub fn is_valid(&self) -> bool { let n = self.control.len(); n > self.degree @@ -70,6 +76,7 @@ impl Spline { && self.knots.windows(2).all(|w| w.first() <= w.get(1)) } + #[must_use] pub fn domain(&self) -> (f64, f64) { let lo = self.knots.get(self.degree).copied().unwrap_or(0.0); let hi = self.knots.get(self.control.len()).copied().unwrap_or(1.0); @@ -77,6 +84,7 @@ impl Spline { } /// Evaluate at parameter `t` (de Boor via basis functions). + #[must_use] pub fn eval(&self, t: f64) -> Vec2 { if !self.is_valid() { return self.control.first().copied().unwrap_or_default(); @@ -87,6 +95,7 @@ impl Spline { /// `eval` on a spline `is_valid` has accepted, given its `domain()`, so sampling many points /// validates once (`is_valid` walks the knot vector). + #[expect(clippy::many_single_char_names, reason = "De Boor evaluation keeps the standard p/w/b/k notation shared with basis_ref.")] fn eval_valid(&self, t: f64, lo: f64, hi: f64) -> Vec2 { let n = self.control.len().saturating_sub(1); let t = t.clamp(lo, hi); @@ -113,6 +122,7 @@ impl Spline { if wsum.abs() > 1e-300 { p / wsum } else { p } } + #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { if !self.is_valid() { return self.control.clone(); @@ -128,16 +138,22 @@ impl Spline { /// The segments for a control polygon `ratio` times the tolerance: dimensionless, so a /// spline and its scaled copy sample alike at any scale. + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "The floating count is clamped to 8..=2000 before its truncating conversion to usize." + )] fn segments_for(&self, ratio: f64) -> usize { let n = (ratio.sqrt() * 2.0).clamp(8.0, 2000.0) as usize * self.degree.max(1); n.min(MAX_SAMPLES) } fn polygon_length(&self) -> f64 { - self.control.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum() + self.control.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum() } /// `n + 1` points evenly spaced in parameter over the domain (the spline must be valid). + #[expect(clippy::cast_precision_loss, reason = "Internal callers cap sample counts at MAX_SAMPLES (4000), so every index is exact as f64.")] fn samples(&self, n: usize) -> impl Iterator + '_ { let (lo, hi) = self.domain(); (0..=n).map(move |i| self.eval_valid(lo + (hi - lo) * i as f64 / n as f64, lo, hi)) @@ -159,6 +175,13 @@ impl Spline { /// is its control polygon, so its control box is exact; a degenerate spline gets its control /// box, which contains the curve (the box of the finite control points when one is not /// finite: `hull` skips it, but it would poison every sample). + #[must_use] + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "Budgets and per-span counts are capped at MAX_SAMPLES; span fractions are nonnegative before conversion." + )] pub fn bounds(&self) -> Bounds2 { let hull = Bounds2::from_points(self.control.iter().copied()); let diag = hull.min.dist(hull.max); @@ -275,6 +298,10 @@ impl Spline { /// control points took minutes). const MAX_SAMPLES: usize = 4000; +#[expect( + clippy::cast_precision_loss, + reason = "Knot indices are sampled as normalized f64 parameters; any precision loss would only be beyond 2^53 allocated control points." +)] pub(crate) fn clamped_uniform_knots(n: usize, degree: usize) -> Vec { let mut k = vec![0.0; degree + 1]; let inner = n.saturating_sub(degree + 1); @@ -292,7 +319,7 @@ pub(crate) fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize { } let mut low = p; let mut high = n + 1; - let mut mid = (low + high) / 2; + let mut mid = usize::midpoint(low, high); let mut guard = 0; while guard < 200 { guard += 1; @@ -305,7 +332,7 @@ pub(crate) fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize { } else { break; } - mid = (low + high) / 2; + mid = usize::midpoint(low, high); } mid } @@ -325,6 +352,11 @@ pub(crate) fn basis(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec { /// `basis` into `n[..=p]`, with `left` and `right` as scratch; each must hold `p + 1` values or /// `n` stays as it was. +#[expect( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + reason = "Spline indices are bounded by slice lengths, and max(0) makes the converted index nonnegative." +)] fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: &mut [f64], right: &mut [f64]) { if n.len() <= p || left.len() <= p || right.len() <= p { return; @@ -358,6 +390,7 @@ fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: /// NaN, infinity or magnitudes above `1e100` (which could overflow) takes the full sweep, and so /// does a back-substitution row whose banded sum is zero (skipped zero terms can flip its sign). #[allow(clippy::needless_range_loop)] +#[expect(clippy::many_single_char_names, reason = "Gaussian elimination keeps conventional matrix/row/column notation.")] pub(crate) fn solve(mut a: Vec>, mut b: Vec) -> Option> { #[cfg(test)] if tests::DENSE_ORACLE.get() { diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index 6a81b141f..c9e19ccc9 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -1,6 +1,11 @@ use super::*; /// `basis` before it evaluated on the stack, kept as the reference. +#[expect( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + reason = "Spline indices are bounded by slice lengths, and max(0) makes the converted index nonnegative." +)] fn basis_ref(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec { let mut n = vec![0.0; p + 1]; let mut left = vec![0.0; p + 1]; @@ -23,6 +28,7 @@ fn basis_ref(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec { } /// `eval` before it evaluated on the stack, kept as the reference. +#[expect(clippy::many_single_char_names, reason = "The reference implementation keeps the NURBS equation notation used by the algorithm under test.")] fn eval_ref(s: &Spline, t: f64) -> Vec2 { let n = s.control.len() - 1; let (lo, hi) = s.domain(); @@ -41,21 +47,26 @@ fn eval_ref(s: &Spline, t: f64) -> Vec2 { } /// Deterministic pseudo-random numbers in `0..1`. +#[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")] fn noise(seed: &mut u64) -> f64 { - *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + *seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); (*seed >> 11) as f64 / (1u64 << 53) as f64 } /// Splines of degree 1..=11 over 14 control points: clamped and unclamped (uniform) knots, /// unit and random weights. +#[expect( + clippy::cast_precision_loss, + reason = "The test uses 14 control points and degrees through 11, so every knot index is exactly representable as f64." +)] fn samples() -> Vec { let mut seed = 7; let mut out = Vec::new(); for degree in 1..=11 { - let control: Vec = (0..14).map(|i| Vec2::new(i as f64 * 3.0 + noise(&mut seed), 10.0 * noise(&mut seed) - 5.0)).collect(); + let control: Vec = (0..14).map(|i| Vec2::new(f64::from(i) * 3.0 + noise(&mut seed), 10.0 * noise(&mut seed) - 5.0)).collect(); let weights: Vec = (0..14).map(|_| 0.5 + 1.5 * noise(&mut seed)).collect(); let clamped = Spline::from_control(control.clone(), degree); - let uniform = Spline { knots: (0..control.len() + degree + 1).map(|i| i as f64 * 0.25).collect(), ..clamped.clone() }; + let uniform = Spline { knots: (0..=(control.len() + degree)).map(|i| i as f64 * 0.25).collect(), ..clamped.clone() }; for base in [clamped, uniform] { out.push(Spline { weights: weights.clone(), ..base.clone() }); out.push(base); @@ -70,7 +81,7 @@ fn stack_basis_matches_the_heap_basis_bit_for_bit() { assert!(s.is_valid()); let (lo, hi) = s.domain(); for i in -20..=1020 { - let t = lo + (hi - lo) * i as f64 / 1000.0; + let t = lo + (hi - lo) * f64::from(i) / 1000.0; let got = s.eval(t); let want = eval_ref(&s, t); assert_eq!((got.x.to_bits(), got.y.to_bits()), (want.x.to_bits(), want.y.to_bits()), "degree {} at {t}: {got:?} vs {want:?}", s.degree); @@ -87,14 +98,14 @@ fn basis_into_needs_room_for_every_function() { let knots = clamped_uniform_knots(6, 3); let (mut n, mut left, mut right) = ([0.5; 3], [0.0; 4], [0.0; 4]); basis_into(3, 0.5, 3, &knots, &mut n, &mut left, &mut right); - assert_eq!(n, [0.5; 3]); + assert_eq!(n.map(f64::to_bits), [0.5; 3].map(f64::to_bits)); } /// A cubic through 300 points of a sine wave, open or closed. fn wiggly(closed: bool) -> Spline { let fit: Vec = (0..300) .map(|i| { - let x = i as f64 / 299.0; + let x = f64::from(i) / 299.0; Vec2::new(x * 100.0, 10.0 * (x * 60.0).sin()) }) .collect(); @@ -108,6 +119,7 @@ fn fine_box(s: &Spline) -> Bounds2 { /// The box of `n + 1` samples evenly spaced in parameter over the domain, as `bounds` sampled /// before it spread its samples over the knot spans. +#[expect(clippy::cast_precision_loss, reason = "Test grids are capped at MAX_SAMPLES (4000), so sample indices are exactly representable as f64.")] fn uniform_box(s: &Spline, n: usize) -> Bounds2 { let (lo, hi) = s.domain(); Bounds2::from_points((0..=n).map(|i| s.eval(lo + (hi - lo) * i as f64 / n as f64))) @@ -118,7 +130,7 @@ fn uniform_box(s: &Spline, n: usize) -> Bounds2 { /// except for a peak of 50 at t = 0.50035, inside a span of width 1e-4 that no point of a /// uniform grid of up to 4000 hits (0.50025 and 0.5005 are the nearest). fn narrow_span() -> Spline { - let control = (0..7).map(|i| Vec2::new(i as f64, if i == 3 { 100.0 } else { 0.0 })).collect(); + let control = (0..7).map(|i| Vec2::new(f64::from(i), if i == 3 { 100.0 } else { 0.0 })).collect(); Spline { degree: 2, knots: vec![0.0, 0.0, 0.0, 0.5003, 0.5003, 0.5004, 0.5004, 1.0, 1.0, 1.0], control, ..Spline::default() } } @@ -132,14 +144,14 @@ fn an_off_grid_peak_in_a_narrow_span_is_within_a_percent() { s.control[4].y = 30.0; assert!(s.is_valid()); let (a, b) = (0.5003, 0.5004); - let peak = (0..=10_000).map(|i| s.eval(a + (b - a) * i as f64 / 10_000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); + let peak = (0..=10_000).map(|i| s.eval(a + (b - a) * f64::from(i) / 10_000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); assert!(peak.y > 58.0 && peak.y < 59.0, "{peak:?}"); let hull = Bounds2::from_points(s.control.iter().copied()); let diag = hull.min.dist(hull.max); let got = s.bounds(); assert!(got.max.y <= peak.y + 1e-9 * diag && got.max.y >= peak.y - 1e-2 * diag, "{got:?} vs peak {peak:?}"); // Four segments, the floor before, missed it by more than that. - let four = (0..=4).map(|i| s.eval(a + (b - a) * i as f64 / 4.0)).fold(f64::MIN, |m, p| m.max(p.y)); + let four = (0..=4).map(|i| s.eval(a + (b - a) * f64::from(i) / 4.0)).fold(f64::MIN, |m, p| m.max(p.y)); assert!(four < peak.y - 1e-2 * diag, "{four} vs {peak:?}"); } @@ -148,7 +160,7 @@ fn bounds_see_an_extreme_inside_a_narrow_knot_span() { let s = narrow_span(); assert!(s.is_valid()); let (a, b) = (0.5003, 0.5004); - let peak = (0..=1000).map(|i| s.eval(a + (b - a) * i as f64 / 1000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); + let peak = (0..=1000).map(|i| s.eval(a + (b - a) * f64::from(i) / 1000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); assert!((peak.x - 3.0).abs() < 1e-9 && (peak.y - 50.0).abs() < 1e-9, "{peak:?}"); let hull = Bounds2::from_points(s.control.iter().copied()); let diag = hull.min.dist(hull.max); @@ -165,6 +177,7 @@ fn bounds_see_an_extreme_inside_a_narrow_knot_span() { } #[test] +#[expect(clippy::cast_precision_loss, reason = "The test grids contain 1502 or 2502 points, so all sample indices are exact as f64.")] fn bounds_keep_their_cap_over_many_spans() { // 1500 spans: eight per span would pass the cap, so two; 2500 spans: more than the cap // allows two for, so the control box, which contains the curve. A smooth curve stays diff --git a/crates/geom/src/spline_fit.rs b/crates/geom/src/spline_fit.rs index 4abdc977c..f3ead5099 100644 --- a/crates/geom/src/spline_fit.rs +++ b/crates/geom/src/spline_fit.rs @@ -1,5 +1,5 @@ //! Fit-point splines: knot parametrisation (chord, square root, uniform), end tangents and fit -//! tolerance (least-squares approximation with fewer control points), as AutoCAD's SPLINE Fit +//! tolerance (least-squares approximation with fewer control points), as `AutoCAD`'s SPLINE Fit //! method offers them. Construction follows the textbook global interpolation and approximation //! schemes (Piegl & Tiller, *The NURBS Book*, ch. 9). @@ -24,6 +24,7 @@ impl KnotParam { pub const ALL: [KnotParam; 3] = [KnotParam::Chord, KnotParam::SqrtChord, KnotParam::Uniform]; /// The name as the prompt and the "Current settings" line show it. + #[must_use] pub fn name(self) -> &'static str { match self { KnotParam::Chord => "Chord", @@ -34,6 +35,7 @@ impl KnotParam { /// Parse a keyword or JSON value ("chord", "sqrt", "square root", "uniform", or 0/1/2 as in /// the SPLKNOTS setting). + #[must_use] pub fn parse(s: &str) -> Option { Some(match s.trim().to_ascii_lowercase().as_str() { "c" | "chord" | "0" => KnotParam::Chord, @@ -44,6 +46,7 @@ impl KnotParam { } /// The SPLKNOTS code (0 chord, 1 square root, 2 uniform). + #[must_use] pub fn code(self) -> i64 { match self { KnotParam::Chord => 0, @@ -81,6 +84,7 @@ pub struct FitOptions { impl FitOptions { /// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative /// tolerance: what a spline stores. + #[must_use] pub fn sanitized(self) -> FitOptions { let dir = |t: Option| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized); FitOptions { @@ -107,26 +111,27 @@ impl Spline { /// control points. A fit point given twice in a row is a kink (SPLINEDIT Fit data Kink): the /// curve passes through it with a corner (a knot of full multiplicity) and the pieces on /// either side are fitted on their own. + #[must_use] pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline { let opts = opts.sanitized(); let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None }; - let mut s = match kinked { - Some(s) => s, - None => { - // Repeats at the ends of an open curve are no corners: fit without them. - let (pts, _) = kinks(fit, false); - let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) }; - if pts.len() != fit.len() && !closed { - s.fit = fit.to_vec(); - } - s + let mut s = if let Some(s) = kinked { + s + } else { + // Repeats at the ends of an open curve are no corners: fit without them. + let (pts, _) = kinks(fit, false); + let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) }; + if pts.len() != fit.len() && !closed { + s.fit = fit.to_vec(); } + s }; s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts }; s } /// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance. + #[must_use] pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, self.fit_opts) } @@ -134,6 +139,7 @@ impl Spline { /// Which knot parametrisation produced this spline's knots from its fit points (DXF files /// keep the knots but not the parametrisation). Compares knot vectors only (no solving), so /// it is cheap for any number of fit points. Chord when nothing matches. + #[must_use] pub fn infer_knot_param(&self) -> KnotParam { if self.fit.len() < 3 { return self.fit_opts.knots; @@ -210,19 +216,19 @@ pub(crate) fn params(pts: &[Vec2], kind: KnotParam, closed: bool) -> Vec { let mut u = vec![0.0; count]; let mut total = 0.0; for i in 1..count { - total += pts.get(i - 1).zip(pts.get(i % n.max(1))).map(|(a, b)| kind.step(a.dist(*b))).unwrap_or(1.0); + total += pts.get(i - 1).zip(pts.get(i % n.max(1))).map_or(1.0, |(a, b)| kind.step(a.dist(*b))); if let Some(x) = u.get_mut(i) { *x = total; } } - for x in u.iter_mut() { + for x in &mut u { *x /= total.max(1e-300); } u } fn chord_length(pts: &[Vec2]) -> f64 { - pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum() + pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum() } fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline { @@ -262,6 +268,11 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline { /// Global interpolation: one control point per fit point plus one per end-derivative /// constraint, knots by averaging the parameters (an end with a derivative counts its /// parameter twice). +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Interpolation uses NURBS matrix notation, and its degree is capped at three, so p is exact as f64." +)] fn interpolate(fit: &[Vec2], u: &[f64], d0: Option, d1: Option) -> Option { let (p, knots) = interp_knots(u, d0.is_some(), d1.is_some()); let m = knots.len().checked_sub(p + 1)?; @@ -305,6 +316,7 @@ fn interpolate(fit: &[Vec2], u: &[f64], d0: Option, d1: Option) -> O /// Degree and clamped knots for interpolating at parameters `u`, with optional end derivatives: /// knots average the parameters, an end with a derivative counting its parameter twice. +#[expect(clippy::cast_precision_loss, reason = "The interpolation degree is capped at three, so p is exact as f64.")] fn interp_knots(u: &[f64], d0: bool, d1: bool) -> (usize, Vec) { let m = u.len() + usize::from(d0) + usize::from(d1); let p = 3.min(m.saturating_sub(1)).max(1); @@ -323,6 +335,13 @@ fn interp_knots(u: &[f64], d0: bool, d1: bool) -> (usize, Vec) { /// Clamped knots for a least-squares fit with `m` control points of degree `p` so every span /// holds parameters (The NURBS Book eq. 9.69). Needs `p < m < u.len()`. +#[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::many_single_char_names, + reason = "Fit sizes are bounded by MAX_APPROX_POINTS, knot indices are nonnegative and clamped, and the equations use NURBS Book notation." +)] fn lsq_knots(u: &[f64], m: usize, p: usize) -> Vec { let n = u.len(); let d = n as f64 / m.saturating_sub(p).max(1) as f64; @@ -339,12 +358,18 @@ fn lsq_knots(u: &[f64], m: usize, p: usize) -> Vec { /// Periodic knots for `n` points with closed parameters `t` (`n + 1` values): knots[j] = /// t_(j-p), extended by whole periods on both sides. +#[expect( + clippy::cast_precision_loss, + clippy::cast_possible_wrap, + clippy::many_single_char_names, + reason = "Indices are bounded by slice lengths, period offsets are f64 by design, and the periodic equations use standard notation." +)] fn periodic_knots(t: &[f64], n: usize, p: usize) -> Vec { let tk = |i: isize| { let (q, r) = (i.div_euclid(n.max(1) as isize), i.rem_euclid(n.max(1) as isize) as usize); t.get(r).copied().unwrap_or(0.0) + q as f64 }; - (0..n + 2 * p + 1).map(|j| tk(j as isize - p as isize)).collect() + (0..=(n + 2 * p)).map(|j| tk(j as isize - p as isize)).collect() } /// Least-squares approximation within `tol`: the fewest control points (searched by bisection) @@ -357,7 +382,7 @@ fn approximate(fit: &[Vec2], u: &[f64], d0: Option, d1: Option, tol: let (mut lo, mut hi) = (p + 1, n.checked_sub(1)?); let mut best = None; while lo <= hi { - let mid = (lo + hi) / 2; + let mid = usize::midpoint(lo, hi); match least_squares(fit, u, mid, p, d0, d1) { Some(s) if max_deviation(&s, fit, u) <= tol => { best = Some(s); @@ -373,6 +398,11 @@ fn max_deviation(s: &Spline, fit: &[Vec2], u: &[f64]) -> f64 { fit.iter().zip(u).map(|(q, t)| s.eval(*t).dist(*q)).fold(0.0, f64::max) } +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Open least-squares fitting is cubic and keeps the NURBS Book matrix notation, so p is exact as f64." +)] fn least_squares(fit: &[Vec2], u: &[f64], m: usize, p: usize, d0: Option, d1: Option) -> Option { let n = fit.len(); if m <= p || m >= n { @@ -522,6 +552,11 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option { /// A clamped, non-rational fitted piece raised to degree 3: interpolation through two or three /// points gives a single Bézier segment of lower degree, which is raised exactly. +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Degree elevation stops at three and keeps the Bézier coefficient notation, so all indices are exact as f64." +)] fn cubic(mut s: Spline) -> Option { if s.degree == 3 { return Some(s); @@ -555,7 +590,7 @@ fn approximate_closed(pts: &[Vec2], t: &[f64], p: usize, tol: f64) -> Option { best = Some(s); @@ -570,6 +605,13 @@ fn approximate_closed(pts: &[Vec2], t: &[f64], p: usize, tol: f64) -> Option Option { let n = pts.len(); if m <= p || m >= n || t.len() != n + 1 { @@ -620,6 +662,7 @@ fn periodic_least_squares(pts: &[Vec2], t: &[f64], m: usize, p: usize) -> Option Some(Spline { degree: p, knots, control, fit: pts.to_vec(), closed: true, ..Spline::default() }) } +#[expect(clippy::many_single_char_names, reason = "Closed interpolation keeps the NURBS Book parameter, degree and matrix notation.")] fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline { let mut pts = fit.to_vec(); if pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) { @@ -748,7 +791,7 @@ mod tests { // Thirty noisy points along a gentle arc. let fit: Vec = (0..30) .map(|i| { - let t = i as f64 / 29.0; + let t = f64::from(i) / 29.0; Vec2::new(t * 10.0, (t * 3.0).sin() * 2.0 + if i % 2 == 0 { 0.01 } else { -0.01 }) }) .collect(); @@ -761,7 +804,7 @@ mod tests { assert!(max_deviation(&s, &fit, &u) <= tol + 1e-9); assert!(s.eval(0.0).near(fit[0], 1e-9) && s.eval(1.0).near(fit[29], 1e-9), "ends stay exact"); assert_eq!(s.fit, fit, "the fit points are kept"); - assert_eq!(s.fit_opts.tolerance, tol); + assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits()); // With tangents too. let t = Spline::fit_with( &fit, @@ -781,7 +824,7 @@ mod tests { // Forty slightly noisy points round a circle. let fit: Vec = (0..40) .map(|i| { - let a = i as f64 / 40.0 * std::f64::consts::TAU; + let a = f64::from(i) / 40.0 * std::f64::consts::TAU; let r = 5.0 + if i % 2 == 0 { 0.01 } else { -0.01 }; Vec2::new(a.cos() * r, a.sin() * r) }) @@ -796,7 +839,7 @@ mod tests { let (lo, hi) = s.domain(); assert!(s.eval(lo).near(s.eval(hi), 1e-9), "still closed"); assert_eq!(s.fit, fit); - assert_eq!(s.fit_opts.tolerance, tol); + assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits()); // Too tight a tolerance interpolates. let tiny = Spline::fit_with(&fit, true, FitOptions { tolerance: 1e-9, ..FitOptions::default() }); assert_eq!(tiny.control.len(), exact.control.len()); @@ -809,10 +852,14 @@ mod tests { fn on_curve(s: &Spline, q: Vec2) -> bool { let (lo, hi) = s.domain(); - (0..=4000).any(|i| s.eval(lo + (hi - lo) * i as f64 / 4000.0).dist(q) < 1e-2) + (0..=4000).any(|i| s.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q) < 1e-2) } #[test] + #[expect( + clippy::many_single_char_names, + reason = "The test names spline values and points with the same short notation as the fitting equations." + )] fn repeated_fit_points_make_kinks() { let fit = [Vec2::new(0.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(6.0, 2.0), Vec2::new(8.0, 0.0)]; let s = Spline::fit_with(&fit, false, FitOptions::default()); @@ -873,13 +920,17 @@ mod tests { let _ = Spline::fit_with(&pairs[..n], closed, FitOptions { tolerance: 0.1, ..FitOptions::default() }); } } - let tight: Vec = (0..8).map(|i| Vec2::new(i as f64 * 1e-13, 0.0)).collect(); + let tight: Vec = (0..8).map(|i| Vec2::new(f64::from(i) * 1e-13, 0.0)).collect(); let _ = Spline::fit_with(&tight, true, FitOptions { tolerance: 1.0, ..FitOptions::default() }); } /// Above the interpolation cap the fit points become control points instead of a dense /// system the size of their count squared (issue #702); just below it they still interpolate. #[test] + #[expect( + clippy::cast_precision_loss, + reason = "The generated test grids are bounded by MAX_INTERP_POINTS + 1, so their indices are exact as f64." + )] fn too_many_fit_points_are_not_interpolated() { let wave = |n: usize| -> Vec { (0..n).map(|i| Vec2::new((i * i) as f64 * 1e-3, (i % 5) as f64)).collect() }; let fit = wave(MAX_INTERP_POINTS + 1); diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 57ffcd663..52aa42683 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -214,7 +214,7 @@ fn segment_offset() { let s = Segment::Arc { arc: Arc::new(Vec2::ZERO, 5.0, 0.0, PI), ccw: true }; let o = s.offset(1.0).unwrap(); if let Segment::Arc { arc, .. } = o { - assert!(close(arc.radius, 4.0)) + assert!(close(arc.radius, 4.0)); } else { panic!() } @@ -341,8 +341,8 @@ fn polyline_area_is_stable_far_from_the_origin() { fn shoelace_preserves_small_polygon_area_at_large_coordinates() { let o = 1.0e12; let corners = [Vec2::new(o, o), Vec2::new(o + 10.0, o), Vec2::new(o + 10.0, o + 10.0), Vec2::new(o, o + 10.0)]; - assert_eq!(shoelace(&corners), 100.0); - assert_eq!(shoelace(&corners.iter().rev().copied().collect::>()), -100.0); + assert_eq!(shoelace(&corners).to_bits(), 100.0_f64.to_bits()); + assert_eq!(shoelace(&corners.iter().rev().copied().collect::>()).to_bits(), (-100.0_f64).to_bits()); } #[test] diff --git a/crates/geom/src/vec.rs b/crates/geom/src/vec.rs index ba0f358e2..d21359e69 100644 --- a/crates/geom/src/vec.rs +++ b/crates/geom/src/vec.rs @@ -14,78 +14,100 @@ impl Vec2 { pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 }; pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 }; + #[must_use] pub const fn new(x: f64, y: f64) -> Self { Vec2 { x, y } } /// Unit vector at `angle` radians. + #[must_use] pub fn from_angle(angle: f64) -> Self { Vec2::new(angle.cos(), angle.sin()) } + #[must_use] pub fn polar(center: Vec2, radius: f64, angle: f64) -> Self { center + Vec2::from_angle(angle) * radius } + #[must_use] pub fn dot(self, o: Vec2) -> f64 { self.x * o.x + self.y * o.y } /// z of the 3D cross product. + #[must_use] pub fn cross(self, o: Vec2) -> f64 { self.x * o.y - self.y * o.x } + #[must_use] pub fn len(self) -> f64 { self.x.hypot(self.y) } + #[must_use] pub fn len2(self) -> f64 { self.dot(self) } + #[must_use] pub fn dist(self, o: Vec2) -> f64 { (self - o).len() } + #[must_use] pub fn angle(self) -> f64 { crate::norm_angle(self.y.atan2(self.x)) } + #[must_use] pub fn angle_to(self, o: Vec2) -> f64 { (o - self).angle() } /// Unit vector, or zero for a zero-length vector. + #[must_use] pub fn normalized(self) -> Vec2 { let l = self.len(); if l > crate::EPS { self / l } else { Vec2::ZERO } } /// Rotated 90° counter-clockwise. + #[must_use] pub fn perp(self) -> Vec2 { Vec2::new(-self.y, self.x) } + #[must_use] pub fn rotate(self, a: f64) -> Vec2 { let (s, c) = a.sin_cos(); Vec2::new(self.x * c - self.y * s, self.x * s + self.y * c) } + #[must_use] pub fn rotate_about(self, center: Vec2, a: f64) -> Vec2 { center + (self - center).rotate(a) } + #[must_use] pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { self + (o - self) * t } + #[must_use] pub fn mid(self, o: Vec2) -> Vec2 { Vec2::new(self.x.midpoint(o.x), self.y.midpoint(o.y)) } + #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() } + #[must_use] pub fn near(self, o: Vec2, tol: f64) -> bool { // Squaring very large finite values can overflow on both sides and make // unrelated points compare equal (infinity <= infinity). tol.is_finite() && tol >= 0.0 && self.dist(o) <= tol } + #[must_use] pub fn to3(self, z: f64) -> Vec3 { Vec3::new(self.x, self.y, z) } + #[must_use] pub fn min(self, o: Vec2) -> Vec2 { Vec2::new(self.x.min(o.x), self.y.min(o.y)) } + #[must_use] pub fn max(self, o: Vec2) -> Vec2 { Vec2::new(self.x.max(o.x), self.y.max(o.y)) } /// Mirror across the infinite line through `a` and `b`. + #[must_use] pub fn mirror(self, a: Vec2, b: Vec2) -> Vec2 { let d = (b - a).normalized(); if d == Vec2::ZERO { @@ -151,26 +173,33 @@ pub struct Vec3 { impl Vec3 { pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 }; + #[must_use] pub const fn new(x: f64, y: f64, z: f64) -> Self { Vec3 { x, y, z } } + #[must_use] pub fn xy(self) -> Vec2 { Vec2::new(self.x, self.y) } + #[must_use] pub fn dot(self, o: Vec3) -> f64 { self.x * o.x + self.y * o.y + self.z * o.z } + #[must_use] pub fn cross(self, o: Vec3) -> Vec3 { Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x) } + #[must_use] pub fn len(self) -> f64 { // Avoid overflowing the squared components of large finite vectors. self.x.hypot(self.y).hypot(self.z) } + #[must_use] pub fn normalized(self) -> Vec3 { let l = self.len(); if l > crate::EPS { self * (1.0 / l) } else { Vec3::ZERO } } + #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() && self.z.is_finite() } From 64f707968fed2308217bff386b5d275561f17fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 19:43:35 +0100 Subject: [PATCH 03/24] test(geom): use assert_eq for NaN arc bound --- crates/geom/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 52aa42683..8dc561337 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -237,7 +237,7 @@ fn polyline_tessellation_is_bounded() { fn arc_segments_bounded() { assert_eq!(arc_segments(0.0, 1.0, 0.1), 1); assert!(arc_segments(1e9, TAU, 1e-12) <= 4096); - assert!(arc_segments(f64::NAN, TAU, 0.1) == 1); + assert_eq!(arc_segments(f64::NAN, TAU, 0.1), 1); } #[test] From ff2163ddfe8d3b35f5454e5f6d4f2d433fae70dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 23:42:36 +0100 Subject: [PATCH 04/24] style(geom): remove review churn --- crates/geom/src/bounds.rs | 11 ------- crates/geom/src/curve.rs | 62 ----------------------------------- crates/geom/src/fillet.rs | 3 -- crates/geom/src/intersect.rs | 6 ---- crates/geom/src/lib.rs | 8 +---- crates/geom/src/mat.rs | 19 ----------- crates/geom/src/nurbs.rs | 21 ------------ crates/geom/src/region.rs | 6 ---- crates/geom/src/spline.rs | 10 ------ crates/geom/src/spline_fit.rs | 7 ---- crates/geom/src/vec.rs | 29 ---------------- 11 files changed, 1 insertion(+), 181 deletions(-) diff --git a/crates/geom/src/bounds.rs b/crates/geom/src/bounds.rs index ad7f2549f..5efaca027 100644 --- a/crates/geom/src/bounds.rs +++ b/crates/geom/src/bounds.rs @@ -24,7 +24,6 @@ impl Default for Bounds2 { impl Bounds2 { pub const EMPTY: Bounds2 = Bounds2 { min: Vec2 { x: f64::INFINITY, y: f64::INFINITY }, max: Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY } }; - #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Bounds2 { min: a.min(b), max: a.max(b) } } @@ -35,7 +34,6 @@ impl Bounds2 { } b } - #[must_use] pub fn is_empty(&self) -> bool { !(self.min.x <= self.max.x && self.min.y <= self.max.y) } @@ -45,7 +43,6 @@ impl Bounds2 { self.max = self.max.max(p); } } - #[must_use] pub fn union(&self, o: &Bounds2) -> Bounds2 { if o.is_empty() { return *self; @@ -55,15 +52,12 @@ impl Bounds2 { } Bounds2 { min: self.min.min(o.min), max: self.max.max(o.max) } } - #[must_use] pub fn width(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.x, self.max.x) } } - #[must_use] pub fn height(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.y, self.max.y) } } - #[must_use] pub fn center(&self) -> Vec2 { if self.is_empty() { return Vec2::ZERO; @@ -75,27 +69,22 @@ impl Bounds2 { }; Vec2::new(mid(self.min.x, self.max.x), mid(self.min.y, self.max.y)) } - #[must_use] pub fn contains(&self, p: Vec2) -> bool { p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y } /// True when `o` lies entirely inside. - #[must_use] pub fn contains_box(&self, o: &Bounds2) -> bool { !o.is_empty() && self.contains(o.min) && self.contains(o.max) } - #[must_use] pub fn intersects(&self, o: &Bounds2) -> bool { !(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y) } - #[must_use] pub fn expand(&self, d: f64) -> Bounds2 { if self.is_empty() { return *self; } Bounds2 { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) } } - #[must_use] pub fn corners(&self) -> [Vec2; 4] { [self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)] } diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index ddda27e82..7f3bd74c5 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -10,53 +10,42 @@ pub struct Line { } impl Line { - #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Line { a, b } } - #[must_use] pub fn len(&self) -> f64 { self.a.dist(self.b) } - #[must_use] pub fn dir(&self) -> Vec2 { (self.b - self.a).normalized() } - #[must_use] pub fn mid(&self) -> Vec2 { self.a.mid(self.b) } /// Parameter (0..1 on the segment) of the projection of `p`. - #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let d = self.b - self.a; let l2 = d.len2(); if l2 <= EPS * EPS { 0.0 } else { (p - self.a).dot(d) / l2 } } - #[must_use] pub fn at(&self, t: f64) -> Vec2 { self.a.lerp(self.b, t) } /// Closest point on the segment. - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p).clamp(0.0, 1.0)) } /// Foot of the perpendicular on the infinite line. - #[must_use] pub fn project(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p)) } - #[must_use] pub fn dist(&self, p: Vec2) -> f64 { self.closest(p).dist(p) } /// Signed side: > 0 left of a→b. - #[must_use] pub fn side(&self, p: Vec2) -> f64 { (self.b - self.a).cross(p - self.a) } - #[must_use] pub fn offset(&self, d: f64) -> Line { let n = (self.b - self.a).normalized().perp() * d; Line::new(self.a + n, self.b + n) @@ -73,41 +62,32 @@ pub struct Arc { } impl Arc { - #[must_use] pub fn new(center: Vec2, radius: f64, start: f64, end: f64) -> Self { Arc { center, radius: radius.abs(), start: norm_angle(start), end: norm_angle(end) } } - #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } - #[must_use] pub fn start_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start) } - #[must_use] pub fn end_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.end) } - #[must_use] pub fn mid_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() / 2.0) } - #[must_use] pub fn len(&self) -> f64 { self.radius * self.sweep() } - #[must_use] pub fn contains_angle(&self, a: f64) -> bool { angle_in_sweep(a, self.start, self.end) } /// Point at parameter `t` in 0..1 along the sweep. - #[must_use] pub fn at(&self, t: f64) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() * t) } /// Arc through three points, or `None` when collinear. - #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { let c = Circle::from_3_points(p1, p2, p3)?; let a1 = c.center.angle_to(p1); @@ -117,11 +97,9 @@ impl Arc { if angle_in_sweep(a2, a1, a3) { Some(Arc::new(c.center, c.radius, a1, a3)) } else { Some(Arc::new(c.center, c.radius, a3, a1)) } } /// Arc from start point, center and end point (CCW). - #[must_use] pub fn from_start_center_end(s: Vec2, c: Vec2, e: Vec2) -> Arc { Arc::new(c, s.dist(c), c.angle_to(s), c.angle_to(e)) } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let a = self.center.angle_to(p); if self.contains_angle(a) && p.dist(self.center) > EPS { @@ -132,7 +110,6 @@ impl Arc { if s.dist(p) <= e.dist(p) { s } else { e } } } - #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points([self.start_point(), self.end_point()]); for k in 0..4 { @@ -161,11 +138,9 @@ pub struct Circle { } impl Circle { - #[must_use] pub fn new(center: Vec2, radius: f64) -> Self { Circle { center, radius: radius.abs() } } - #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { // Work in point-relative coordinates. Absolute coordinate squares lose the small // differences between points in drawings far from the origin. @@ -191,16 +166,13 @@ impl Circle { } Some(Circle::new(c, radius)) } - #[must_use] pub fn from_2_points(p1: Vec2, p2: Vec2) -> Circle { Circle::new(p1.mid(p2), p1.dist(p2) / 2.0) } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let d = p - self.center; if d.len() < EPS { self.center + Vec2::X * self.radius } else { self.center + d.normalized() * self.radius } } - #[must_use] pub fn bounds(&self) -> Bounds2 { Bounds2::new(self.center - Vec2::new(self.radius, self.radius), self.center + Vec2::new(self.radius, self.radius)) } @@ -208,7 +180,6 @@ impl Circle { Arc { center: self.center, radius: self.radius, start: 0.0, end: TAU }.tessellate(tol, out); } /// Tangent points from external point `p`. - #[must_use] pub fn tangent_points(&self, p: Vec2) -> Vec { let d = p.dist(self.center); if d <= self.radius + EPS { @@ -222,7 +193,6 @@ impl Circle { /// up to two outer (belt) tangents and two inner (crossed) tangents. Empty for concentric /// circles or when one circle lies inside the other; tangents that touch both circles at the /// same point (circles touching each other) are left out. - #[must_use] #[expect(clippy::many_single_char_names, reason = "Circle-tangent equations use conventional r/v/d/u/c/h/n/p/q notation.")] pub fn common_tangents(&self, other: &Circle) -> Vec<(Vec2, Vec2)> { let (r1, r2) = (self.radius, other.radius); @@ -264,23 +234,18 @@ pub struct Ellipse { } impl Ellipse { - #[must_use] pub fn full(center: Vec2, major: Vec2, ratio: f64) -> Self { Ellipse { center, major, ratio, start: 0.0, end: TAU } } - #[must_use] pub fn is_full(&self) -> bool { (ccw_sweep(self.start, self.end) - TAU).abs() < 1e-9 } - #[must_use] pub fn minor(&self) -> Vec2 { self.major.perp() * self.ratio } - #[must_use] pub fn at_param(&self, t: f64) -> Vec2 { self.center + self.major * t.cos() + self.minor() * t.sin() } - #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } @@ -310,7 +275,6 @@ impl Ellipse { out.push(self.at_param(self.start + sweep * i as f64 / n as f64)); } } - #[must_use] pub fn bounds(&self) -> Bounds2 { // Sampled bounds can cut off the true extrema, especially on a small arc or // a large drawing. The derivative of each coordinate gives two exact @@ -325,7 +289,6 @@ impl Ellipse { bounds } /// Parameter of the point on the ellipse nearest the direction of `p` (approximate). - #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let ma = self.major.len(); if ma < EPS { @@ -338,7 +301,6 @@ impl Ellipse { let mb = ma * self.ratio; norm_angle((y / mb.max(EPS)).atan2(x / ma)) } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let mut pts = Vec::new(); self.tessellate(self.major.len() * 1e-3, &mut pts); @@ -373,7 +335,6 @@ pub enum Segment { } impl Segment { - #[must_use] pub fn start(&self) -> Vec2 { match self { Segment::Line(l) => l.a, @@ -381,7 +342,6 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.end_point(), } } - #[must_use] pub fn end(&self) -> Vec2 { match self { Segment::Line(l) => l.b, @@ -389,28 +349,24 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.start_point(), } } - #[must_use] pub fn len(&self) -> f64 { match self { Segment::Line(l) => l.len(), Segment::Arc { arc, .. } => arc.len(), } } - #[must_use] pub fn mid(&self) -> Vec2 { match self { Segment::Line(l) => l.mid(), Segment::Arc { arc, .. } => arc.mid_point(), } } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { match self { Segment::Line(l) => l.closest(p), Segment::Arc { arc, .. } => arc.closest(p), } } - #[must_use] pub fn bounds(&self) -> Bounds2 { match self { Segment::Line(l) => Bounds2::new(l.a, l.b), @@ -434,7 +390,6 @@ impl Segment { } } /// Point at parameter `t` (0..1) in segment direction. - #[must_use] pub fn at(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.at(t), @@ -442,7 +397,6 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.at(1.0 - t), } } - #[must_use] pub fn reversed(&self) -> Segment { match *self { Segment::Line(l) => Segment::Line(Line::new(l.b, l.a)), @@ -450,7 +404,6 @@ impl Segment { } } /// Tangent direction (unit) at parameter t. - #[must_use] pub fn tangent(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.dir(), @@ -462,7 +415,6 @@ impl Segment { } } /// Offset by `d` to the left of travel direction. `None` if an arc collapses. - #[must_use] pub fn offset(&self, d: f64) -> Option { match *self { Segment::Line(l) => Some(Segment::Line(l.offset(d))), @@ -491,18 +443,15 @@ pub struct PolyVertex { } impl PolyVertex { - #[must_use] pub fn new(p: Vec2) -> Self { PolyVertex { p, ..Default::default() } } - #[must_use] pub fn with_bulge(p: Vec2, bulge: f64) -> Self { PolyVertex { p, bulge, ..Default::default() } } } /// Convert a bulge segment to an arc. `None` for a straight (zero-bulge or degenerate) segment. -#[must_use] pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { if bulge.abs() < 1e-12 || !bulge.is_finite() || a.near(b, EPS) { return None; @@ -527,7 +476,6 @@ pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { } /// Bulge for an arc traversed from `a` to `b` with the given sweep (signed: + = CCW). -#[must_use] pub fn arc_to_bulge(signed_sweep: f64) -> f64 { (signed_sweep / 4.0).tan() } @@ -543,12 +491,10 @@ pub struct Polyline { pub const MAX_TESSELLATED_POINTS: usize = 4_000_000; impl Polyline { - #[must_use] pub fn from_points(pts: &[Vec2], closed: bool) -> Self { Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed } } /// The segments, including the closing segment when closed. - #[must_use] pub fn segments(&self) -> Vec { let n = self.vertices.len(); let mut out = Vec::with_capacity(n); @@ -568,7 +514,6 @@ impl Polyline { pub fn len(&self) -> f64 { self.segments().iter().map(Segment::len).sum() } - #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points(self.vertices.iter().map(|v| v.p)); for s in self.segments() { @@ -576,7 +521,6 @@ impl Polyline { } b } - #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { let mut budget = MAX_TESSELLATED_POINTS; self.tessellate_within(tol, &mut budget) @@ -605,7 +549,6 @@ impl Polyline { out } /// Signed area (CCW positive) of a closed polyline including bulge areas. - #[must_use] pub fn area(&self) -> f64 { // Integrate the chords exactly and add the signed circular-segment area // for every bulge. A tessellated shoelace loses precision on large arcs. @@ -633,7 +576,6 @@ impl Polyline { } twice_area / 2.0 } - #[must_use] pub fn closest(&self, p: Vec2) -> Option { let mut best: Option<(f64, Vec2)> = None; for s in self.segments() { @@ -646,7 +588,6 @@ impl Polyline { best.map(|(_, c)| c).or_else(|| self.vertices.first().map(|v| v.p)) } /// True if `p` is inside a closed polyline (even-odd on the tessellation). - #[must_use] pub fn contains(&self, p: Vec2) -> bool { point_in_polygon(&self.tessellate(1e-3), p) } @@ -685,13 +626,11 @@ impl Polyline { } /// Area centroid of a closed polygon. `None` at zero area. -#[must_use] pub fn polygon_centroid(pts: &[Vec2]) -> Option { Polyline::from_points(pts, true).centroid() } /// Signed polygon area (CCW positive). -#[must_use] pub fn shoelace(pts: &[Vec2]) -> f64 { let n = pts.len(); if n < 3 { @@ -712,7 +651,6 @@ pub fn shoelace(pts: &[Vec2]) -> f64 { } /// Even-odd point-in-polygon test. -#[must_use] pub fn point_in_polygon(poly: &[Vec2], p: Vec2) -> bool { let n = poly.len(); if n < 3 { diff --git a/crates/geom/src/fillet.rs b/crates/geom/src/fillet.rs index 74b06385b..bf5214cd7 100644 --- a/crates/geom/src/fillet.rs +++ b/crates/geom/src/fillet.rs @@ -49,7 +49,6 @@ struct Range { impl TanCurve { /// Point at parameter `t`. - #[must_use] pub fn point(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.a + (l.b - l.a) * t, @@ -60,7 +59,6 @@ impl TanCurve { } /// First derivative at parameter `t`. - #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.b - l.a, @@ -240,7 +238,6 @@ fn refine(c1: &TanCurve, r1: &Range, d1: f64, c2: &TanCurve, r2: &Range, d2: f64 /// Circles of radius `r` tangent to both curves (`r = 0`: the points where they cross). `near` /// (the pick points) widens the search window for lines. Every distinct solution is returned; /// callers choose one, usually the nearest the picks. -#[must_use] pub fn tangent_circles(c1: &TanCurve, c2: &TanCurve, r: f64, near: &[Vec2]) -> Vec { if !(r.is_finite() && r >= 0.0) { return Vec::new(); diff --git a/crates/geom/src/intersect.rs b/crates/geom/src/intersect.rs index 4e7714b6e..12f1b2e9a 100644 --- a/crates/geom/src/intersect.rs +++ b/crates/geom/src/intersect.rs @@ -1,7 +1,6 @@ use crate::{Arc, Circle, EPS, Line, Segment, Vec2}; /// Intersection of two infinite lines through (a1,a2) and (b1,b2), with parameters on each. -#[must_use] pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec2, f64, f64)> { let r = a2 - a1; let s = b2 - b1; @@ -15,7 +14,6 @@ pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec } /// Intersection of two finite segments. -#[must_use] #[expect(clippy::many_single_char_names, reason = "Segment endpoints and parameters use conventional a/b/p/t/u geometric notation.")] pub fn line_line(a: &Line, b: &Line) -> Option { let (p, t, u) = line_line_infinite(a.a, a.b, b.a, b.b)?; @@ -24,7 +22,6 @@ pub fn line_line(a: &Line, b: &Line) -> Option { } /// Intersections of the infinite line through `l` with a circle. Returns points with line params. -#[must_use] #[expect(clippy::many_single_char_names, reason = "The line/circle quadratic uses conventional a/d/f/t mathematical notation.")] pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { let d = l.b - l.a; @@ -57,7 +54,6 @@ pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { } /// Intersections of two full circles. -#[must_use] pub fn circle_circle(c1: &Circle, c2: &Circle) -> Vec { let delta = c2.center - c1.center; let d = delta.len(); @@ -107,14 +103,12 @@ fn on_arc(a: &Arc, p: Vec2) -> bool { } /// Intersections between two segments (finite). -#[must_use] pub fn intersect_segments(s1: &Segment, s2: &Segment) -> Vec { intersect_segments_ext(s1, s2, false) } /// Intersections; with `extend` true, lines are infinite and arcs are full circles /// (used by TRIM/EXTEND edge mode and apparent intersections). -#[must_use] pub fn intersect_segments_ext(s1: &Segment, s2: &Segment, extend: bool) -> Vec { let tol = 1e-9; match (s1, s2) { diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 40b47d6d5..bc320f584 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,4 +1,4 @@ -//! `CADCraft` geometry: double-precision 2D/3D math for drafting. +//! CADCraft geometry: double-precision 2D/3D math for drafting. //! //! Everything a CAD kernel needs below the document model: vectors and affine transforms, //! bounding boxes, angles, lines, circular arcs (and polyline bulges), ellipses, NURBS splines, @@ -36,7 +36,6 @@ pub const TAU: f64 = std::f64::consts::TAU; pub const PI: f64 = std::f64::consts::PI; /// Normalize an angle to `[0, 2π)`. -#[must_use] pub fn norm_angle(a: f64) -> f64 { if !a.is_finite() { return 0.0; @@ -46,31 +45,26 @@ pub fn norm_angle(a: f64) -> f64 { } /// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`. -#[must_use] pub fn ccw_sweep(start: f64, end: f64) -> f64 { let s = norm_angle(end - start); if s <= EPS { TAU } else { s } } /// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance). -#[must_use] pub fn angle_in_sweep(a: f64, start: f64, end: f64) -> bool { let sweep = ccw_sweep(start, end); let d = norm_angle(a - start); d <= sweep + 1e-12 || (TAU - d) < 1e-12 } -#[must_use] pub fn deg(r: f64) -> f64 { r.to_degrees() } -#[must_use] pub fn rad(d: f64) -> f64 { d.to_radians() } /// Number of segments needed to approximate an arc of `radius` and `sweep` within `tol`. -#[must_use] #[expect( clippy::cast_possible_truncation, clippy::cast_sign_loss, diff --git a/crates/geom/src/mat.rs b/crates/geom/src/mat.rs index ec7a2075b..374712fc1 100644 --- a/crates/geom/src/mat.rs +++ b/crates/geom/src/mat.rs @@ -22,30 +22,24 @@ impl Default for Mat3 { impl Mat3 { pub const IDENTITY: Mat3 = Mat3 { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; - #[must_use] pub fn translate(v: Vec2) -> Mat3 { Mat3 { e: v.x, f: v.y, ..Mat3::IDENTITY } } - #[must_use] pub fn scale(sx: f64, sy: f64) -> Mat3 { Mat3 { a: sx, d: sy, ..Mat3::IDENTITY } } - #[must_use] pub fn rotate(angle: f64) -> Mat3 { let (s, c) = angle.sin_cos(); Mat3 { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 } } /// Scale about `base`. - #[must_use] pub fn scale_about(base: Vec2, s: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::scale(s, s)).then_before(Mat3::translate(-base)) } - #[must_use] pub fn rotate_about(base: Vec2, angle: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::rotate(angle)).then_before(Mat3::translate(-base)) } /// Reflection across the line through `p1`, `p2`. - #[must_use] pub fn mirror(p1: Vec2, p2: Vec2) -> Mat3 { let d = (p2 - p1).normalized(); if d == Vec2::ZERO { @@ -56,7 +50,6 @@ impl Mat3 { Mat3::translate(p1).then_before(r).then_before(Mat3::translate(-p1)) } /// `self * o`: apply `o` first, then `self`. - #[must_use] pub fn then_before(self, o: Mat3) -> Mat3 { Mat3 { a: self.a * o.a + self.c * o.b, @@ -68,23 +61,18 @@ impl Mat3 { } } /// Apply `self` first, then `o`. - #[must_use] pub fn then(self, o: Mat3) -> Mat3 { o.then_before(self) } - #[must_use] pub fn apply(&self, p: Vec2) -> Vec2 { Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f) } - #[must_use] pub fn apply_vec(&self, v: Vec2) -> Vec2 { Vec2::new(self.a * v.x + self.c * v.y, self.b * v.x + self.d * v.y) } - #[must_use] pub fn det(&self) -> f64 { self.a * self.d - self.b * self.c } - #[must_use] #[expect(clippy::many_single_char_names, reason = "Matrix coefficients use the same a–f notation as Mat3 and the affine-transform formula.")] pub fn inverse(&self) -> Option { let det = self.det(); @@ -101,16 +89,13 @@ impl Mat3 { Some(Mat3 { a, b, c, d, e, f }) } /// Uniform scale factor (geometric mean of the axis scales). - #[must_use] pub fn scale_factor(&self) -> f64 { self.det().abs().sqrt() } /// Rotation angle of the transformed X axis. - #[must_use] pub fn rotation(&self) -> f64 { crate::norm_angle(self.b.atan2(self.a)) } - #[must_use] pub fn is_mirroring(&self) -> bool { self.det() < 0.0 } @@ -138,7 +123,6 @@ impl Default for Mat4 { impl Mat4 { pub const IDENTITY: Mat4 = Mat4 { m: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] }; - #[must_use] pub fn mul(&self, o: &Mat4) -> Mat4 { let mut r = [[0.0; 4]; 4]; for (i, row) in r.iter_mut().enumerate() { @@ -148,7 +132,6 @@ impl Mat4 { } Mat4 { m: r } } - #[must_use] pub fn apply(&self, p: Vec3) -> Vec3 { let m = &self.m; let w = m[3][0] * p.x + m[3][1] * p.y + m[3][2] * p.z + m[3][3]; @@ -159,12 +142,10 @@ impl Mat4 { (m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3]) / w, ) } - #[must_use] pub fn from_mat3(t: &Mat3) -> Mat4 { Mat4 { m: [[t.a, t.c, 0.0, t.e], [t.b, t.d, 0.0, t.f], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] } } /// The "arbitrary axis algorithm" frame for an extrusion direction (DXF OCS → WCS). - #[must_use] pub fn ocs(normal: Vec3) -> Mat4 { let n = normal.normalized(); if n == Vec3::ZERO || (n.x.abs() < 1e-12 && n.y.abs() < 1e-12 && n.z > 0.0) { diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 2c8e070f5..4d2e9a5a9 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -128,7 +128,6 @@ impl Spline { } /// True when the spline carries weights (a NURBS rather than a plain B-spline). - #[must_use] pub fn is_rational(&self) -> bool { !self.weights.is_empty() } @@ -155,7 +154,6 @@ impl Spline { } /// First derivative dC/dt (zero on an invalid spline). - #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { if !self.is_valid() { return Vec2::ZERO; @@ -216,7 +214,6 @@ impl Spline { /// Unit tangent at `t` in the direction of increasing parameter; a central difference stands /// in where the derivative vanishes. Zero when the curve does not move at all. - #[must_use] pub fn unit_tangent(&self, t: f64) -> Vec2 { let d = self.derivative(t).normalized(); if d != Vec2::ZERO { @@ -229,7 +226,6 @@ impl Spline { /// Insert knot `t` once (Boehm's algorithm, in homogeneous coordinates). The result has no /// fit data and is open. - #[must_use] #[expect(clippy::many_single_char_names, reason = "Boehm knot insertion keeps the standard p/n/k/i/h/a equation notation.")] pub fn insert_knot(&self, t: f64) -> Option { if !self.is_valid() || !t.is_finite() || self.control.len() >= MAX_EDIT_CONTROL { @@ -298,7 +294,6 @@ impl Spline { } /// Split at parameter `t` into (before, after). `None` at the ends or on invalid input. - #[must_use] pub fn split_at(&self, t: f64) -> Option<(Spline, Spline)> { let (lo, hi) = self.domain(); if !(t > lo + 1e-12 && t < hi - 1e-12) { @@ -309,7 +304,6 @@ impl Spline { } /// The open piece between parameters `a < b`. - #[must_use] pub fn sub_between(&self, a: f64, b: f64) -> Option { let (lo, hi) = self.domain(); let mut s = self.clone(); @@ -326,7 +320,6 @@ impl Spline { /// The same curve with clamped ends (end knots repeated degree + 1 times), so it starts and /// ends on its first and last control points. Fit data is dropped. - #[must_use] pub fn clamped(&self) -> Option { if !self.is_valid() { return None; @@ -349,7 +342,6 @@ impl Spline { /// Reversed direction: control points, weights, fit points and knots (and the fit end /// tangents swap ends and turn round). - #[must_use] pub fn reversed(&self) -> Spline { let (lo, hi) = (self.knots.first().copied().unwrap_or(0.0), self.knots.last().copied().unwrap_or(1.0)); Spline { @@ -402,7 +394,6 @@ impl Spline { } /// The same curve at a higher (or equal) degree, clamped. - #[must_use] pub fn elevated(&self, degree: usize) -> Option { if degree < self.degree || degree > MAX_EDIT_DEGREE { return None; @@ -428,7 +419,6 @@ impl Spline { /// point becomes their midpoint). Degrees are matched by elevation, weights rescaled so the /// junction carries one weight, and `other`'s parameters follow on at a similar speed. The /// junction is a knot of multiplicity `degree`, so the curve passes through it exactly. - #[must_use] #[expect( clippy::many_single_char_names, reason = "Spline joining keeps the two curves, homogeneous points and knot spans in standard short notation." @@ -461,7 +451,6 @@ impl Spline { /// A straight line from `a` to `b` as a clamped spline of `degree` (evenly spaced control /// points, parameter = distance). - #[must_use] #[expect(clippy::cast_precision_loss, reason = "The degree is clamped by MAX_EDIT_DEGREE (25), so every control index is exact as f64.")] pub fn from_line(a: Vec2, b: Vec2, degree: usize) -> Spline { let p = degree.clamp(1, MAX_EDIT_DEGREE); @@ -476,7 +465,6 @@ impl Spline { /// The elliptical arc `center + u·cos θ + v·sin θ` for θ from `start` over `sweep` (negative /// runs clockwise) as an exact rational quadratic spline, in pieces of at most a quarter /// turn. Circular arcs are the case `|u| = |v|`, `u ⟂ v`. - #[must_use] #[expect( clippy::cast_precision_loss, clippy::cast_possible_truncation, @@ -513,7 +501,6 @@ impl Spline { } /// An ellipse or elliptical arc as an exact rational spline (counter-clockwise). - #[must_use] pub fn from_ellipse(e: &Ellipse) -> Option { let s = Spline::from_conic_arc(e.center, e.major, e.minor(), e.start, e.sweep())?; Some(Spline { closed: e.is_full(), ..s }) @@ -521,7 +508,6 @@ impl Spline { /// Run the spline on in a straight line along its end tangent by `dist` > 0: past the end /// (`at_end`) or before the start. The result is clamped, open and has no fit data. - #[must_use] pub fn extended(&self, at_end: bool, dist: f64) -> Option { if !(dist.is_finite() && dist > 0.0) || self.closed { return None; @@ -564,14 +550,12 @@ impl Spline { } /// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span). - #[must_use] pub fn length_between(&self, a: f64, b: f64) -> f64 { let l = self.integrated_length(a, b); if l.is_finite() { l } else { 0.0 } } /// Arc length of the whole spline. - #[must_use] pub fn length(&self) -> f64 { let (lo, hi) = self.domain(); self.length_between(lo, hi) @@ -598,7 +582,6 @@ impl Spline { /// The parameter `len` along the curve from parameter `from` (forward for positive `len`, /// backward for negative), clamped to the domain. - #[must_use] pub fn param_at_length(&self, from: f64, len: f64) -> f64 { let (lo, hi) = self.domain(); if !self.is_valid() { @@ -641,13 +624,11 @@ impl Spline { impl Ellipse { /// dP/dθ at parameter `t`. - #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { self.minor() * t.cos() - self.major * t.sin() } /// Arc length from parameter `t0` counter-clockwise over `sweep` (radians, >= 0). - #[must_use] #[expect( clippy::cast_precision_loss, clippy::cast_possible_truncation, @@ -672,14 +653,12 @@ impl Ellipse { } /// Arc length of the ellipse or elliptical arc. - #[must_use] pub fn length(&self) -> f64 { self.arc_length_from(self.start, self.sweep()) } /// The parameter reached `len` along the ellipse from `t0`: counter-clockwise for positive /// `len`, clockwise for negative. `None` for a whole turn or more, or degenerate input. - #[must_use] pub fn param_at_length(&self, t0: f64, len: f64) -> Option { let full = self.arc_length_from(0.0, TAU); if !(t0.is_finite() && len.is_finite() && full > EPS) || len.abs() >= full { diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index 6c7578606..12ff47220 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -563,7 +563,6 @@ fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, bu /// curve (which gains a vertex there), so the two meet exactly. A curve that is flattened /// into chords (an ellipse, a spline) lies up to the flattening tolerance off the true curve, /// so a line that ends on the true curve can stop just short of the chords. -#[must_use] #[expect(clippy::many_single_char_names, reason = "Endpoint snapping keeps conventional polyline, segment and point notation.")] pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { let mut out: Vec> = polys.to_vec(); @@ -614,26 +613,22 @@ pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { } /// The closed loop enclosing `p`, counter-clockwise, or `None`. -#[must_use] pub fn enclosing_loop(polys: &[Vec], p: Vec2, tol: f64) -> Option> { enclosing_loop_gap(polys, p, tol, 0.0) } /// [`enclosing_loop`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). -#[must_use] pub fn enclosing_loop_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; points(&g, &outer_face(&g, p)?) } /// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed. -#[must_use] pub fn boundary_at(polys: &[Vec], p: Vec2, tol: f64) -> Option { boundary_at_gap(polys, p, tol, 0.0) } /// [`boundary_at`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). -#[must_use] pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option { let g = build_gap(polys, tol, gap)?; let ids = outer_face(&g, p)?; @@ -649,7 +644,6 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti /// The outside outline of curves that together enclose an area (counter-clockwise, dangling /// ends removed), or `None` when they enclose nothing or form more than one separate group. /// Gaps of up to `gap` between curve ends are closed (HPGAPTOL). -#[must_use] #[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")] pub fn outline(polys: &[Vec], tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index 8192cbb30..68e5d5b94 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -30,7 +30,6 @@ pub struct Spline { impl Spline { /// A clamped uniform spline over control points. - #[must_use] pub fn from_control(control: Vec, degree: usize) -> Spline { let n = control.len(); let degree = degree.clamp(1, n.saturating_sub(1).max(1)); @@ -40,7 +39,6 @@ impl Spline { /// Cubic interpolation through fit points (chord-length parametrisation, natural-ish ends /// via a clamped knot vector: solve the banded system for control points). - #[must_use] pub fn from_fit_points(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, false, FitOptions::default()) } @@ -49,24 +47,20 @@ impl Spline { /// include the closing chord; the knot vector is the periodic (unclamped) extension and the /// first `degree` control points repeat at the end, so the curve has continuous tangent and /// curvature at the seam. A repeated closing fit point is dropped. - #[must_use] pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, true, FitOptions::default()) } /// Interpolation through fit points, open or closed (see `from_fit_points_closed`). - #[must_use] pub fn from_fit(fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, FitOptions::default()) } /// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2). - #[must_use] pub fn is_periodic(&self) -> bool { self.closed && self.knots.first() != self.knots.get(self.degree) } - #[must_use] pub fn is_valid(&self) -> bool { let n = self.control.len(); n > self.degree @@ -76,7 +70,6 @@ impl Spline { && self.knots.windows(2).all(|w| w.first() <= w.get(1)) } - #[must_use] pub fn domain(&self) -> (f64, f64) { let lo = self.knots.get(self.degree).copied().unwrap_or(0.0); let hi = self.knots.get(self.control.len()).copied().unwrap_or(1.0); @@ -84,7 +77,6 @@ impl Spline { } /// Evaluate at parameter `t` (de Boor via basis functions). - #[must_use] pub fn eval(&self, t: f64) -> Vec2 { if !self.is_valid() { return self.control.first().copied().unwrap_or_default(); @@ -122,7 +114,6 @@ impl Spline { if wsum.abs() > 1e-300 { p / wsum } else { p } } - #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { if !self.is_valid() { return self.control.clone(); @@ -175,7 +166,6 @@ impl Spline { /// is its control polygon, so its control box is exact; a degenerate spline gets its control /// box, which contains the curve (the box of the finite control points when one is not /// finite: `hull` skips it, but it would poison every sample). - #[must_use] #[expect( clippy::cast_precision_loss, clippy::cast_possible_truncation, diff --git a/crates/geom/src/spline_fit.rs b/crates/geom/src/spline_fit.rs index f3ead5099..720488e4e 100644 --- a/crates/geom/src/spline_fit.rs +++ b/crates/geom/src/spline_fit.rs @@ -24,7 +24,6 @@ impl KnotParam { pub const ALL: [KnotParam; 3] = [KnotParam::Chord, KnotParam::SqrtChord, KnotParam::Uniform]; /// The name as the prompt and the "Current settings" line show it. - #[must_use] pub fn name(self) -> &'static str { match self { KnotParam::Chord => "Chord", @@ -35,7 +34,6 @@ impl KnotParam { /// Parse a keyword or JSON value ("chord", "sqrt", "square root", "uniform", or 0/1/2 as in /// the SPLKNOTS setting). - #[must_use] pub fn parse(s: &str) -> Option { Some(match s.trim().to_ascii_lowercase().as_str() { "c" | "chord" | "0" => KnotParam::Chord, @@ -46,7 +44,6 @@ impl KnotParam { } /// The SPLKNOTS code (0 chord, 1 square root, 2 uniform). - #[must_use] pub fn code(self) -> i64 { match self { KnotParam::Chord => 0, @@ -84,7 +81,6 @@ pub struct FitOptions { impl FitOptions { /// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative /// tolerance: what a spline stores. - #[must_use] pub fn sanitized(self) -> FitOptions { let dir = |t: Option| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized); FitOptions { @@ -111,7 +107,6 @@ impl Spline { /// control points. A fit point given twice in a row is a kink (SPLINEDIT Fit data Kink): the /// curve passes through it with a corner (a knot of full multiplicity) and the pieces on /// either side are fitted on their own. - #[must_use] pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline { let opts = opts.sanitized(); let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None }; @@ -131,7 +126,6 @@ impl Spline { } /// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance. - #[must_use] pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, self.fit_opts) } @@ -139,7 +133,6 @@ impl Spline { /// Which knot parametrisation produced this spline's knots from its fit points (DXF files /// keep the knots but not the parametrisation). Compares knot vectors only (no solving), so /// it is cheap for any number of fit points. Chord when nothing matches. - #[must_use] pub fn infer_knot_param(&self) -> KnotParam { if self.fit.len() < 3 { return self.fit_opts.knots; diff --git a/crates/geom/src/vec.rs b/crates/geom/src/vec.rs index d21359e69..ba0f358e2 100644 --- a/crates/geom/src/vec.rs +++ b/crates/geom/src/vec.rs @@ -14,100 +14,78 @@ impl Vec2 { pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 }; pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 }; - #[must_use] pub const fn new(x: f64, y: f64) -> Self { Vec2 { x, y } } /// Unit vector at `angle` radians. - #[must_use] pub fn from_angle(angle: f64) -> Self { Vec2::new(angle.cos(), angle.sin()) } - #[must_use] pub fn polar(center: Vec2, radius: f64, angle: f64) -> Self { center + Vec2::from_angle(angle) * radius } - #[must_use] pub fn dot(self, o: Vec2) -> f64 { self.x * o.x + self.y * o.y } /// z of the 3D cross product. - #[must_use] pub fn cross(self, o: Vec2) -> f64 { self.x * o.y - self.y * o.x } - #[must_use] pub fn len(self) -> f64 { self.x.hypot(self.y) } - #[must_use] pub fn len2(self) -> f64 { self.dot(self) } - #[must_use] pub fn dist(self, o: Vec2) -> f64 { (self - o).len() } - #[must_use] pub fn angle(self) -> f64 { crate::norm_angle(self.y.atan2(self.x)) } - #[must_use] pub fn angle_to(self, o: Vec2) -> f64 { (o - self).angle() } /// Unit vector, or zero for a zero-length vector. - #[must_use] pub fn normalized(self) -> Vec2 { let l = self.len(); if l > crate::EPS { self / l } else { Vec2::ZERO } } /// Rotated 90° counter-clockwise. - #[must_use] pub fn perp(self) -> Vec2 { Vec2::new(-self.y, self.x) } - #[must_use] pub fn rotate(self, a: f64) -> Vec2 { let (s, c) = a.sin_cos(); Vec2::new(self.x * c - self.y * s, self.x * s + self.y * c) } - #[must_use] pub fn rotate_about(self, center: Vec2, a: f64) -> Vec2 { center + (self - center).rotate(a) } - #[must_use] pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { self + (o - self) * t } - #[must_use] pub fn mid(self, o: Vec2) -> Vec2 { Vec2::new(self.x.midpoint(o.x), self.y.midpoint(o.y)) } - #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() } - #[must_use] pub fn near(self, o: Vec2, tol: f64) -> bool { // Squaring very large finite values can overflow on both sides and make // unrelated points compare equal (infinity <= infinity). tol.is_finite() && tol >= 0.0 && self.dist(o) <= tol } - #[must_use] pub fn to3(self, z: f64) -> Vec3 { Vec3::new(self.x, self.y, z) } - #[must_use] pub fn min(self, o: Vec2) -> Vec2 { Vec2::new(self.x.min(o.x), self.y.min(o.y)) } - #[must_use] pub fn max(self, o: Vec2) -> Vec2 { Vec2::new(self.x.max(o.x), self.y.max(o.y)) } /// Mirror across the infinite line through `a` and `b`. - #[must_use] pub fn mirror(self, a: Vec2, b: Vec2) -> Vec2 { let d = (b - a).normalized(); if d == Vec2::ZERO { @@ -173,33 +151,26 @@ pub struct Vec3 { impl Vec3 { pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 }; - #[must_use] pub const fn new(x: f64, y: f64, z: f64) -> Self { Vec3 { x, y, z } } - #[must_use] pub fn xy(self) -> Vec2 { Vec2::new(self.x, self.y) } - #[must_use] pub fn dot(self, o: Vec3) -> f64 { self.x * o.x + self.y * o.y + self.z * o.z } - #[must_use] pub fn cross(self, o: Vec3) -> Vec3 { Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x) } - #[must_use] pub fn len(self) -> f64 { // Avoid overflowing the squared components of large finite vectors. self.x.hypot(self.y).hypot(self.z) } - #[must_use] pub fn normalized(self) -> Vec3 { let l = self.len(); if l > crate::EPS { self * (1.0 / l) } else { Vec3::ZERO } } - #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() && self.z.is_finite() } From fefb973754d67cbf9bb34b3b9eade45749eab1b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Tue, 3 Nov 2026 14:13:43 +0100 Subject: [PATCH 05/24] fix(geom): move NURBS lint expectations to velocity --- crates/geom/src/nurbs.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 4d2e9a5a9..4d9d5fabc 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -172,6 +172,11 @@ impl Spline { } /// [`Spline::derivative_unchecked`] before a value past f64's range is read as zero. + #[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "The NURBS derivative keeps its standard equation notation, and MAX_DEGREE makes p exact as f64." + )] fn velocity(&self, t: f64) -> Vec2 { let p = self.degree; let Some(n) = self.control.len().checked_sub(1) else { return Vec2::ZERO }; From 06203e49589fb504e9fb99d584e864b7e847708e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 16:38:26 +0100 Subject: [PATCH 06/24] refactor(fonts): satisfy Clippy pedantic lints --- crates/fonts/build.rs | 4 +- crates/fonts/src/bidi.rs | 10 +- crates/fonts/src/complex.rs | 99 ++++++++-------- crates/fonts/src/craft_fonts.rs | 2 +- crates/fonts/src/lib.rs | 150 ++++++++++++++----------- crates/fonts/src/mtext.rs | 83 +++++++------- crates/fonts/src/mtext/para.rs | 139 ++++++++++++----------- crates/fonts/src/stroke.rs | 13 +-- crates/fonts/src/subset.rs | 9 +- crates/fonts/src/ttf.rs | 63 +++++++---- crates/fonts/tests/mtext_paragraphs.rs | 6 +- 11 files changed, 323 insertions(+), 255 deletions(-) diff --git a/crates/fonts/build.rs b/crates/fonts/build.rs index a290aecd0..5ee19c378 100644 --- a/crates/fonts/build.rs +++ b/crates/fonts/build.rs @@ -3,7 +3,7 @@ //! empty, `CRAFT_FONTS` is empty and the build is unchanged. It only reads the local checkout //! (no network). A bad checkout is a warning, or an error with `CRAFT_FONTS_REQUIRED=1`. //! -//! On wasm32 it embeds only BIZ UDPGothic Regular, the `Arab` and `Geor` faces and the `Thai` +//! On wasm32 it embeds only `BIZ UDPGothic` Regular, the `Arab` and `Geor` faces and the `Thai` //! Regular faces (about 6.1 MB), to keep the web build within hosting limits (Cloudflare Pages: //! 25 MiB per file). The web build has no system fonts, so these are its only fallback for //! Japanese, Arabic-script, Georgian and Thai text. @@ -22,7 +22,7 @@ fn main() { println!("cargo::error=CRAFT_FONTS_DIR={}: {}", one_line(&dir.display().to_string()), one_line(&e)); } Err(e) => { - println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {}", one_line(&dir.display().to_string()), one_line(&e)) + println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {}", one_line(&dir.display().to_string()), one_line(&e)); } } } diff --git a/crates/fonts/src/bidi.rs b/crates/fonts/src/bidi.rs index 0cebd6bbc..d7134ed42 100644 --- a/crates/fonts/src/bidi.rs +++ b/crates/fonts/src/bidi.rs @@ -36,6 +36,7 @@ pub(crate) fn is_mark(c: char) -> bool { /// right-to-left, `Some(false)` left-to-right, `None` when it has no strong character. As rule /// P2 requires, characters between an isolate initiator and its matching PDI (or the end of the /// paragraph, when unmatched) are skipped. +#[must_use] pub fn base_rtl(s: &str) -> Option { let mut isolate_depth: usize = 0; for c in s.chars() { @@ -65,6 +66,7 @@ fn byte_starts(text: &str) -> Vec { /// each flagged right-to-left or not. The paragraph direction comes from the first strong /// character (or `base` when given). Characters inside a right-to-left run are still in logical /// order: the caller lays them out from right to left. +#[must_use] pub fn visual_runs(chars: &[char], base: Option) -> Vec<(Range, bool)> { if chars.is_empty() { return Vec::new(); @@ -77,7 +79,7 @@ pub fn visual_runs(chars: &[char], base: Option) -> Vec<(Range, boo runs.into_iter() .filter(|r| !r.is_empty()) .map(|r| { - let rtl = levels.get(r.start).is_some_and(|l| l.is_rtl()); + let rtl = levels.get(r.start).is_some_and(Level::is_rtl); (char_at(r.start)..char_at(r.end), rtl) }) .collect() @@ -85,6 +87,7 @@ pub fn visual_runs(chars: &[char], base: Option) -> Vec<(Range, boo /// Resolved embedding level of every character of one line (after rule L1), for reordering /// pieces of the line with [`reorder`]. +#[must_use] pub fn char_levels(text: &str, base: Option) -> Vec { if text.is_empty() { return Vec::new(); @@ -95,12 +98,14 @@ pub fn char_levels(text: &str, base: Option) -> Vec { /// Display order (rule L2) of items with the given embedding levels: indices into `levels`, /// left to right. +#[must_use] pub fn reorder(levels: &[u8]) -> Vec { let lv: Vec = levels.iter().map(|l| Level::new(*l).unwrap_or_else(|_| Level::ltr())).collect(); ParagraphBidiInfo::reorder_visual(&lv) } /// The mirrored glyph of a paired bracket in right-to-left text (rule L4, common pairs). +#[must_use] pub fn mirror(c: char) -> char { match c { '(' => ')', @@ -123,6 +128,7 @@ pub fn mirror(c: char) -> char { /// A line in display order, code point by code point: right-to-left runs reversed and their /// brackets mirrored. Shows what the layout draws, before glyph shaping. +#[must_use] pub fn visual_order(s: &str) -> String { let chars: Vec = s.chars().collect(); let mut out = String::with_capacity(s.len()); @@ -223,6 +229,7 @@ pub enum Form { /// The contextual form of every character of a logical-order run (`None` for characters that /// don't join: spaces, digits, Latin, marks, ZWNJ). +#[must_use] pub fn joining_forms(chars: &[char]) -> Vec> { let jt: Vec = chars.iter().map(|c| joining_type(*c)).collect(); // Neighbour joining types, skipping transparent marks. @@ -308,6 +315,7 @@ const FORMS_A: &[(u32, u32, u32)] = &[ ]; /// The presentation-form code point of `c` in `form`, when Unicode has one. +#[must_use] pub fn presentation_form(c: char, form: Form) -> Option { let u = u32::from(c); let slot = match form { diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index ce2fbcb61..fd85b2b16 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -79,80 +79,81 @@ pub(crate) fn shape(primary: Option<&Face>, s: &str, height: f64, width_factor: /// Lay out decoded directional runs, keeping advances and decoration spans for empty glyphs. fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { - let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; - let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; + let normalized_height = if height.is_finite() && height > 0.0 { height } else { 1.0 }; + let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; let shear = oblique.tan().clamp(-10.0, 10.0); - let sc = h / stroke::CAP; - let cs: Vec = chars.iter().map(|c| c.0).collect(); - let flags = |i: usize| chars.get(i).map(|c| (c.1, c.2)).unwrap_or((false, false)); - let mut out = Shaped::default(); + let stroke_scale = normalized_height / stroke::CAP; + let characters: Vec = chars.iter().map(|character| character.0).collect(); + let flags = |index: usize| chars.get(index).map_or((false, false), |character| (character.1, character.2)); + let mut shaped = Shaped::default(); let mut points_left = ttf::MAX_SHAPED_POINTS; let mut spans: Vec<(f64, f64, bool, bool)> = Vec::new(); - let mut x = 0.0; + let mut pen_x = 0.0; // Whether the rightmost glyph so far is a stroke-font glyph. let mut stroke_last = false; - for (run, rtl) in bidi::visual_runs(&cs, base_rtl) { - let mut pieces = itemize(&cs, run, primary); + for (run, rtl) in bidi::visual_runs(&characters, base_rtl) { + let mut pieces = itemize(&characters, run, primary); if rtl { pieces.reverse(); } - for (src, r) in pieces { + for (src, range) in pieces { match &src { Src::Hidden => {} Src::Stroke | Src::Missing => { - let idx: Vec = if rtl { r.rev().collect() } else { r.collect() }; - for i in idx { - let c = cs.get(i).copied().unwrap_or(' '); - let c = if rtl { bidi::mirror(c) } else { c }; - match (&src, stroke::glyph(c)) { - (Src::Stroke, Some((_, spec))) => crate::draw_stroke_glyph(&mut out, spec, x, sc, wf, shear), - (Src::Missing, _) => crate::missing_glyph_box(&mut out, x, h, sc * wf), + let indices: Vec = if rtl { range.rev().collect() } else { range.collect() }; + for index in indices { + let character = characters.get(index).copied().unwrap_or(' '); + let character = if rtl { bidi::mirror(character) } else { character }; + match (&src, stroke::glyph(character)) { + (Src::Stroke, Some((_, spec))) => { + crate::draw_stroke_glyph(&mut shaped, spec, pen_x, stroke_scale, scale_x, shear); + } + (Src::Missing, _) => crate::missing_glyph_box(&mut shaped, pen_x, normalized_height, stroke_scale * scale_x), _ => {} } - let adv = crate::char_advance(c) * h * wf; - let (u, o) = flags(i); - spans.push((x, x + adv, u, o)); - x += adv; + let advance = crate::char_advance(character) * normalized_height * scale_x; + let (underline, overline) = flags(index); + spans.push((pen_x, pen_x + advance, underline, overline)); + pen_x += advance; stroke_last = true; } } Src::Face(face) => { - let glyphs = shape_run(face, &cs, r.clone(), rtl); + let glyphs = shape_run(face, &characters, range.clone(), rtl); // Right-to-left runs stay outlines only: their glyphs come in display order // and include ligatures (lam-alef) that stand for several characters. - let shows = if rtl { Vec::new() } else { glyph_chars(face, &cs, &glyphs, r.end) }; - for (n, g) in glyphs.iter().enumerate() { - let outline = ttf::glyph_by_id(face, g.gid); - let k = h / outline.cap * wf; - let dy = g.dy * h / outline.cap; - if let Some(mut contours) = ttf::place_glyph_budgeted(&outline, x + g.dx * k, h, wf, shear, &mut points_left) { - for p in contours.iter_mut().flatten() { - *p += Vec2::new(dy * shear, dy); + let shows = if rtl { Vec::new() } else { glyph_chars(face, &characters, &glyphs, range.end) }; + for (n, glyph) in glyphs.iter().enumerate() { + let outline = ttf::glyph_by_id(face, glyph.gid); + let glyph_scale = normalized_height / outline.cap * scale_x; + let offset_y = glyph.dy * normalized_height / outline.cap; + if let Some(mut contours) = + ttf::place_glyph_budgeted(&outline, pen_x + glyph.dx * glyph_scale, normalized_height, scale_x, shear, &mut points_left) + { + for point in contours.iter_mut().flatten() { + *point += Vec2::new(offset_y * shear, offset_y); } - let origin = Vec2::new(x + g.dx * k + dy * shear, dy); - let text = shows - .get(n) - .copied() - .flatten() - .filter(|c| !c.is_whitespace()) - .and_then(|c| ttf::text_glyph_at(&outline, c, origin, h / outline.cap, wf, shear)); - out.push_glyph(contours, text); + let origin = Vec2::new(pen_x + glyph.dx * glyph_scale + offset_y * shear, offset_y); + let text = shows.get(n).copied().flatten().filter(|character| !character.is_whitespace()).and_then(|character| { + ttf::text_glyph_at(&outline, character, origin, normalized_height / outline.cap, scale_x, shear) + }); + shaped.push_glyph(contours, text); } - let adv = g.advance * k; - let (u, o) = flags(g.cluster); - spans.push((x, x + adv, u, o)); - x += adv; + let advance = glyph.advance * glyph_scale; + let (underline, overline) = flags(glyph.cluster); + spans.push((pen_x, pen_x + advance, underline, overline)); + pen_x += advance; stroke_last = false; } } } } } - out.strokes.extend(crate::decorations(&spans, h)); + shaped.strokes.extend(crate::decorations(&spans, normalized_height)); // A stroke-font glyph at the right end: the width leaves out its trailing gap, like // `shape_stroke`. - out.width = if stroke_last { (x - stroke::GAP * sc * wf).max(0.0) } else { x }; - out + shaped.width = if stroke_last { (pen_x - stroke::GAP * stroke_scale * scale_x).max(0.0) } else { pen_x }; + shaped } /// Split a logical-order run into pieces by what draws each character. Joiners and combining @@ -333,7 +334,7 @@ mod tests { assert!(shaped.text.is_empty()); let underlined = shape(Some(&face), "%%u ", 1.0, 1.0, 0.0, None).expect("shapes decorated empty glyph"); - assert_eq!(underlined.width, shaped.width); + assert!((underlined.width - shaped.width).abs() < f64::EPSILON); assert!(underlined.glyphs.is_empty()); assert!(underlined.text.is_empty()); assert!(!underlined.strokes.is_empty(), "decoration spans survive an empty outline"); @@ -350,7 +351,7 @@ mod tests { assert!((crate::line_width(s, 1.0, 1.0) - sh.width).abs() < 1e-9); let digits: Vec = sh.strokes.iter().filter(|st| !(st.len() == 5 && st.first() == st.last())).flatten().map(|p| p.x).collect(); assert!(!digits.is_empty()); - let (lo, hi) = (digits.iter().cloned().fold(f64::MAX, f64::min), digits.iter().cloned().fold(f64::MIN, f64::max)); + let (lo, hi) = (digits.iter().copied().fold(f64::MAX, f64::min), digits.iter().copied().fold(f64::MIN, f64::max)); assert!(lo > 0.2 * sh.width && hi < 0.8 * sh.width, "digits between the words: {lo}..{hi} of {}", sh.width); } @@ -382,7 +383,7 @@ mod tests { fn nominal(f: &Face, c: char) -> Option { use skrifa::MetadataProvider; - f.font().and_then(|font| font.charmap().map(c)).map(|g| g.to_u32()) + f.font().and_then(|font| font.charmap().map(c)).map(skrifa::GlyphId::to_u32) } #[test] @@ -407,7 +408,7 @@ mod tests { assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no missing-glyph boxes"); // The ASCII digits are stroke glyphs in the middle of the line. let stroke_x: Vec = sh.strokes.iter().flatten().map(|p| p.x).collect(); - let (lo, hi) = (stroke_x.iter().cloned().fold(f64::MAX, f64::min), stroke_x.iter().cloned().fold(f64::MIN, f64::max)); + let (lo, hi) = (stroke_x.iter().copied().fold(f64::MAX, f64::min), stroke_x.iter().copied().fold(f64::MIN, f64::max)); assert!(lo > 0.2 * sh.width && hi < 0.8 * sh.width, "digits between the words: {lo}..{hi} of {}", sh.width); assert!((crate::line_width("قیمت 25 تومان", 1.0, 1.0) - sh.width).abs() < 1e-9); } diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index 3436d1d5f..affbd40d6 100644 --- a/crates/fonts/src/craft_fonts.rs +++ b/crates/fonts/src/craft_fonts.rs @@ -1,7 +1,7 @@ //! Fonts from the optional craft-fonts build input (). //! //! Built with `CRAFT_FONTS_DIR=`, `build.rs` embeds the fonts listed in its -//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular, the Arabic and Georgian faces and +//! `fonts/manifest.txt` (web builds: only `BIZ UDPGothic` Regular, the `Arab` and `Geor` faces and //! the Thai Regular faces). Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`]) //! lists the embedded fonts with the installed ones, under [`CraftFont::stem`]. A text style //! can name one (`BIZ UDPGothic`), and they are fallbacks for characters a text's font lacks. diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index c41898cee..534fa3b1e 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -1,7 +1,7 @@ -//! CADCraft text layout. +//! `CADCraft` text layout. //! //! Turns TEXT and MTEXT into stroke polylines with the built-in single-stroke font -//! ("CADCraft Stroke"), the user's SHX shape fonts and big fonts ([`shx`]) or glyph outlines +//! ("`CADCraft` Stroke"), the user's SHX shape fonts and big fonts ([`shx`]) or glyph outlines //! of installed TrueType fonts ([`ttf`]), with a //! per-character fallback to installed fonts for characters the chosen font lacks. Handles the //! `%%` control codes, alignment modes, width factor, obliquing, MTEXT inline formatting @@ -46,24 +46,25 @@ pub struct Run { /// Replace `%%` control codes: `%%d` degree, `%%p` plus/minus, `%%c` diameter, `%%%` percent, /// `%%nnn` character code, and `\U+XXXX` Unicode escapes. Underline/overline toggles (`%%u`, /// `%%o`) are returned as flags per character. -pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> { - let mut out = Vec::with_capacity(s.len()); +#[must_use] +pub fn decode_controls(text: &str) -> Vec<(char, bool, bool)> { + let mut out = Vec::with_capacity(text.len()); let mut under = false; let mut over = false; - let chars: Vec = s.chars().collect(); - let mut i = 0; - while i < chars.len() { - let c = chars.get(i).copied().unwrap_or(' '); + let chars: Vec = text.chars().collect(); + let mut index = 0; + while index < chars.len() { + let character = chars.get(index).copied().unwrap_or(' '); // `\U+XXXX`: a Unicode character by its code. - if c == '\\' - && let Some(u) = unicode_escape(&chars, i) + if character == '\\' + && let Some(u) = unicode_escape(&chars, index) { out.push((u, under, over)); - i += 7; + index += 7; continue; } - if c == '%' && chars.get(i + 1) == Some(&'%') { - let code = chars.get(i + 2).copied().unwrap_or(' '); + if character == '%' && chars.get(index + 1) == Some(&'%') { + let code = chars.get(index + 2).copied().unwrap_or(' '); match code.to_ascii_lowercase() { 'd' => out.push(('°', under, over)), 'p' => out.push(('±', under, over)), @@ -71,24 +72,24 @@ pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> { '%' => out.push(('%', under, over)), 'u' => under = !under, 'o' => over = !over, - d if d.is_ascii_digit() => { - let digits: String = chars.iter().skip(i + 2).take(3).take_while(|c| c.is_ascii_digit()).collect(); - let n: u32 = digits.parse().unwrap_or(32); - out.push((char::from_u32(n).unwrap_or('?'), under, over)); - i += 2 + digits.len(); + digit if digit.is_ascii_digit() => { + let digits: String = chars.iter().skip(index + 2).take(3).take_while(|character| character.is_ascii_digit()).collect(); + let codepoint: u32 = digits.parse().unwrap_or(32); + out.push((char::from_u32(codepoint).unwrap_or('?'), under, over)); + index += 2 + digits.len(); continue; } _ => { out.push(('%', under, over)); - i += 1; + index += 1; continue; } } - i += 3; + index += 3; continue; } - out.push((c, under, over)); - i += 1; + out.push((character, under, over)); + index += 1; } out } @@ -106,6 +107,7 @@ pub(crate) fn unicode_escape(chars: &[char], i: usize) -> Option { } /// Advance width of one character at height 1 and width factor 1. +#[must_use] pub fn char_advance(c: char) -> f64 { match stroke::glyph(c) { Some((w, _)) => (w + stroke::GAP) / stroke::CAP, @@ -116,6 +118,7 @@ pub fn char_advance(c: char) -> f64 { /// Whether `c` is an East Asian wide character (CJK ideographs and punctuation, kana, Hangul, /// fullwidth forms): drawn in a square cell, like a big font's characters. +#[must_use] pub fn is_wide(c: char) -> bool { matches!(u32::from(c), 0x1100..=0x115F @@ -168,87 +171,92 @@ fn stroke_advance(c: char, h: f64, wf: f64) -> f64 { /// Shape a single line in the stroke font at `height`, with `width_factor` and `oblique` /// (radians). Characters the stroke font lacks are drawn from an installed font that has them /// (glyph outlines, sized like TrueType text), else as a missing-glyph box. +#[must_use] pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Shaped { shape_stroke_dir(s, height, width_factor, oblique, None) } /// [`shape_stroke`] in the direction `base_rtl` (`None`: that of the line's first strong /// character). -pub fn shape_stroke_dir(s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { - let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; - let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; - let sc = h / stroke::CAP; +#[must_use] +pub fn shape_stroke_dir(text: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { + let normalized_height = if height.is_finite() && height > 0.0 { height } else { 1.0 }; + let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; + let stroke_scale = normalized_height / stroke::CAP; let shear = oblique.tan().clamp(-10.0, 10.0); let mut out = Shaped::default(); - let mut x = 0.0; + let mut pen_x = 0.0; let mut under_start: Option = None; let mut over_start: Option = None; - let mut gap = stroke::GAP * sc * wf; + let mut gap = stroke::GAP * stroke_scale * scale_x; // Retained fallback-outline points over the line, as the TrueType path caps them: a short string // repeating one detailed glyph would otherwise copy its outline per occurrence. let mut points_left = ttf::MAX_SHAPED_POINTS; // The simple path lays a line out left to right: one asked to run right to left goes through // the bidi path even without right-to-left letters. - if (complex::needed(s) || base_rtl == Some(true)) - && let Some(sh) = complex::shape(None, s, h, wf, oblique, base_rtl) + if (complex::needed(text) || base_rtl == Some(true)) + && let Some(sh) = complex::shape(None, text, normalized_height, scale_x, oblique, base_rtl) { return sh; } - for (c, under, over) in decode_controls(s) { - if bidi::is_format_control(c) { + for (character, under, over) in decode_controls(text) { + if bidi::is_format_control(character) { continue; } - let mut adv = char_advance(c) * h * wf; - gap = stroke::GAP * sc * wf; - match stroke::glyph(c) { - Some((_, spec)) => draw_stroke_glyph(&mut out, spec, x, sc, wf, shear), - None if !c.is_whitespace() => match ttf::fallback_glyph(c) { - Some(g) => { - let (y, scale) = stroke_fallback_metrics(&g, c, h); - let contours = match points_left.checked_sub(g.points) { + let mut adv = char_advance(character) * normalized_height * scale_x; + gap = stroke::GAP * stroke_scale * scale_x; + match stroke::glyph(character) { + Some((_, spec)) => draw_stroke_glyph(&mut out, spec, pen_x, stroke_scale, scale_x, shear), + None if !character.is_whitespace() => match ttf::fallback_glyph(character) { + Some(glyph) => { + let (origin_y, scale) = stroke_fallback_metrics(&glyph, character, normalized_height); + let contours = match points_left.checked_sub(glyph.points) { Some(rest) => { points_left = rest; - ttf::place_glyph_at(&g, Vec2::new(x, y), scale, wf, shear) + ttf::place_glyph_at(&glyph, Vec2::new(pen_x, origin_y), scale, scale_x, shear) } None => Vec::new(), }; if !contours.is_empty() { - out.push_glyph(contours, ttf::text_glyph_at(&g, c, Vec2::new(x + y * shear, y), scale, wf, shear)); + out.push_glyph( + contours, + ttf::text_glyph_at(&glyph, character, Vec2::new(pen_x + origin_y * shear, origin_y), scale, scale_x, shear), + ); } - adv = g.advance * scale * wf; + adv = glyph.advance * scale * scale_x; gap = 0.0; } - None => missing_glyph_box(&mut out, x, h, sc * wf), + None => missing_glyph_box(&mut out, pen_x, normalized_height, stroke_scale * scale_x), }, None => {} } // Decorations. match (under, under_start) { - (true, None) => under_start = Some(x), + (true, None) => under_start = Some(pen_x), (false, Some(sx)) => { - out.strokes.push(vec![Vec2::new(sx, -h * 0.2), Vec2::new(x, -h * 0.2)]); + out.strokes.push(vec![Vec2::new(sx, -normalized_height * 0.2), Vec2::new(pen_x, -normalized_height * 0.2)]); under_start = None; } _ => {} } match (over, over_start) { - (true, None) => over_start = Some(x), + (true, None) => over_start = Some(pen_x), (false, Some(sx)) => { - out.strokes.push(vec![Vec2::new(sx, h * 1.2), Vec2::new(x, h * 1.2)]); + out.strokes.push(vec![Vec2::new(sx, normalized_height * 1.2), Vec2::new(pen_x, normalized_height * 1.2)]); over_start = None; } _ => {} } - x += adv; + pen_x += adv; } // The stroke font's gap after the last character isn't part of the line; a fallback glyph // has none. - let end = (x - gap).max(0.0); + let end = (pen_x - gap).max(0.0); if let Some(sx) = under_start { - out.strokes.push(vec![Vec2::new(sx, -h * 0.2), Vec2::new(end, -h * 0.2)]); + out.strokes.push(vec![Vec2::new(sx, -normalized_height * 0.2), Vec2::new(end, -normalized_height * 0.2)]); } if let Some(sx) = over_start { - out.strokes.push(vec![Vec2::new(sx, h * 1.2), Vec2::new(end, h * 1.2)]); + out.strokes.push(vec![Vec2::new(sx, normalized_height * 1.2), Vec2::new(end, normalized_height * 1.2)]); } out.width = end; out @@ -277,6 +285,7 @@ fn missing_glyph_box(out: &mut Shaped, x: f64, h: f64, k: f64) { /// Lay out a single line at `height`, with `width_factor` and `oblique` (radians), in the /// stroke font (fallback glyphs become closed outlines). +#[must_use] pub fn layout_line(s: &str, height: f64, width_factor: f64, oblique: f64) -> Run { let sh = shape_stroke(s, height, width_factor, oblique); let mut strokes = sh.strokes; @@ -285,6 +294,7 @@ pub fn layout_line(s: &str, height: f64, width_factor: f64, oblique: f64) -> Run } /// Width of a line without building strokes. +#[must_use] pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { if complex::needed(s) { let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; @@ -304,6 +314,7 @@ pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { /// Width of the gap MTEXT leaves between two words. Words are measured without their trailing /// letter gap, so the stroke font's gap is added on both sides of the space, as TEXT lays it out. +#[must_use] pub fn space_width(font: &TextFont, height: f64, width_factor: f64) -> f64 { if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, " ", height, width_factor) @@ -360,8 +371,9 @@ impl TextFont { if builtin { return TextFont::Stroke; } - ttf::find(alt_main).map(TextFont::Outline).unwrap_or(TextFont::Stroke) + ttf::find(alt_main).map_or(TextFont::Stroke, TextFont::Outline) } + #[must_use] pub fn is_outline(&self) -> bool { matches!(self, TextFont::Outline(_)) } @@ -444,10 +456,12 @@ impl Shaped { self.strokes.extend(other.strokes); self.glyphs.extend(other.glyphs); } + #[must_use] pub fn is_empty(&self) -> bool { self.strokes.is_empty() && self.glyphs.is_empty() } /// All geometry as polylines (outlines become closed polylines). + #[must_use] pub fn outlines(&self) -> Vec> { let mut v = self.strokes.clone(); v.extend(self.glyphs.iter().flatten().cloned()); @@ -485,12 +499,14 @@ pub(crate) fn decorations(spans: &[(f64, f64, bool, bool)], h: f64) -> Vec Shaped { shape_line_dir(font, s, height, width_factor, oblique, None) } /// [`shape_line`] in the direction `base_rtl` (`None`: that of the line's first strong /// character). +#[must_use] pub fn shape_line_dir(font: &TextFont, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { if let TextFont::Outline(face) = font && let Some(sh) = ttf::shape_dir(face, s, height, width_factor, oblique, base_rtl) @@ -503,11 +519,12 @@ pub fn shape_line_dir(font: &TextFont, s: &str, height: f64, width_factor: f64, shape_stroke_dir(s, height, width_factor, oblique, base_rtl) } -/// Single-line TEXT (and attributes) runs left to right, as AutoCAD lays it out: neutral +/// Single-line TEXT (and attributes) runs left to right, as `AutoCAD` lays it out: neutral /// characters before a right-to-left word ("- " in "- פרוייקט") stay on its left (#2500). const TEXT_BASE_RTL: Option = Some(false); /// Width of one line in `font`. +#[must_use] pub fn text_width(font: &TextFont, s: &str, height: f64, width_factor: f64) -> f64 { if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, s, height, width_factor) @@ -562,6 +579,7 @@ pub struct TextParams { } impl TextParams { + #[must_use] pub fn new(insert: Vec2, height: f64) -> Self { TextParams { insert, @@ -577,6 +595,7 @@ impl TextParams { } } /// Centred on `p` both ways (dimension and table text). + #[must_use] pub fn centered(p: Vec2, height: f64, rotation: f64) -> Self { TextParams { align_pt: Some(p), rotation, h: Align::Middle, v: VAlign::Middle, ..TextParams::new(p, height) } } @@ -585,13 +604,14 @@ impl TextParams { /// Where a single-line TEXT's baseline starts (the left end of its first character's baseline), /// in world coordinates: what DXF/DWG store as a justified text's insertion point (group 10), /// computed from its alignment point (group 11) and its width in `font`. +#[must_use] pub fn baseline_start(font: &TextFont, s: &str, p: &TextParams) -> Vec2 { let (origin, local, rot, mirror) = frame(font, s, p); origin + Vec2::new(local.x * mirror.x, local.y * mirror.y).rotate(rot) } /// How far below the baseline a bottom-justified text's alignment point lies: a third of the -/// height for the stroke font (as AutoCAD places it with SHX fonts), the face's descent for an +/// height for the stroke font (as `AutoCAD` places it with SHX fonts), the face's descent for an /// outline font (#2229). fn bottom_depth(font: &TextFont, height: f64) -> f64 { match font { @@ -602,12 +622,12 @@ fn bottom_depth(font: &TextFont, height: f64) -> f64 { } /// The vertical middle of shaped text's ink (its strokes and outlines), above the baseline; -/// `None` when it draws nothing. A Middle (M) text is centred there: AutoCAD centres it on the +/// `None` when it draws nothing. A Middle (M) text is centred there: `AutoCAD` centres it on the /// string's own extents, descenders included, not at half the height (#2229). fn ink_middle(sh: &Shaped) -> Option { let ys = sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).map(|q| q.y).filter(|y| y.is_finite()); let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); - (lo <= hi).then_some((lo + hi) / 2.0) + (lo <= hi).then_some(f64::midpoint(lo, hi)) } /// The offset of a line's baseline start from its alignment point, for justification `h`/`v`. @@ -648,6 +668,7 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) { /// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its /// bounding box. +#[must_use] pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; let mut wf = p.width_factor; @@ -693,6 +714,7 @@ pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { /// Place a single-line TEXT in world coordinates with the stroke font. Returns strokes and the /// text's bounding box. #[allow(clippy::too_many_arguments)] +#[must_use] pub fn place_text( s: &str, insert: Vec2, @@ -714,7 +736,7 @@ mod tests { use super::*; /// A TEXT that starts with neutral characters before a Hebrew word ("- פרוייקט") keeps them - /// on the left, as AutoCAD draws it; the line's own direction (first strong character) would + /// on the left, as `AutoCAD` draws it; the line's own direction (first strong character) would /// put the dash on the right (#2500). #[test] fn text_runs_left_to_right_whatever_its_first_strong_character() { @@ -942,7 +964,7 @@ mod justify_tests { ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))) } - /// A Middle (M) text is centred on its own ink, descenders included, as AutoCAD centres it, + /// A Middle (M) text is centred on its own ink, descenders included, as `AutoCAD` centres it, /// not at half the height: lowercase and descenders move the baseline (#2229). #[test] fn a_middle_text_is_centred_on_its_ink() { @@ -951,11 +973,11 @@ mod justify_tests { for s in ["ABC 123", "gjpqy", "Tg 1234 ABC", "ace"] { let (sh, start) = placed(&font, s, Align::Middle, VAlign::Baseline); let (lo, hi) = ink_y(&sh); - assert!(((lo + hi) / 2.0).abs() < 1e-9, "{s}: ink {lo}..{hi} is centred on the alignment point"); + assert!((f64::midpoint(lo, hi)).abs() < 1e-9, "{s}: ink {lo}..{hi} is centred on the alignment point"); // The insertion point a DWG keeps (group 10) is the baseline start, below the ink's // middle by as much as the unplaced text's ink middle is above its baseline. let (lo0, hi0) = ink_y(&shape_line(&font, s, H, 1.0, 0.0)); - assert!((start.y + (lo0 + hi0) / 2.0).abs() < 1e-9, "{s}: baseline start {start:?}"); + assert!((start.y + f64::midpoint(lo0, hi0)).abs() < 1e-9, "{s}: baseline start {start:?}"); baselines.push((s, start.y)); } // Capitals and digits span the height, so they stay at half of it. @@ -975,7 +997,7 @@ mod justify_tests { assert!((start.y + H / 2.0).abs() < 1e-9, "{start:?}"); } - /// With the stroke font (as with AutoCAD's SHX fonts), a bottom-justified text's baseline is + /// With the stroke font (as with `AutoCAD`'s SHX fonts), a bottom-justified text's baseline is /// a third of the height above its alignment point, and Middle Center still uses half. #[test] fn stroke_font_bottom_and_middle_center_are_unchanged() { @@ -989,7 +1011,7 @@ mod justify_tests { } /// With a TrueType font, a bottom-justified text's alignment point is at the face's descent, - /// where its descenders end, as AutoCAD places it (#2229: Arial's is 0.296 of the height). + /// where its descenders end, as `AutoCAD` places it (#2229: Arial's is 0.296 of the height). /// Uses the first of these common fonts that is installed (Windows, macOS and Linux each have /// one); skips without any. #[test] @@ -1009,6 +1031,6 @@ mod justify_tests { // And Middle centres the ink, as with the stroke font. let (sh, _) = placed(&font, "Tg 1234 ABC", Align::Middle, VAlign::Baseline); let (lo, hi) = ink_y(&sh); - assert!(((lo + hi) / 2.0).abs() < 1e-9, "{name}: {lo}..{hi}"); + assert!((f64::midpoint(lo, hi)).abs() < 1e-9, "{name}: {lo}..{hi}"); } } diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 1a2110116..c5d38ae3e 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -8,6 +8,7 @@ pub(crate) mod para; /// Strip MTEXT formatting codes to plain text with `\n` paragraph breaks. /// Stacked fractions `\S1/2;` become `1/2`; `\~` is a space; braces are dropped. +#[must_use] pub fn plain_mtext(s: &str) -> String { let s = unescape_codes(s); let s = s.as_ref(); @@ -19,11 +20,7 @@ pub fn plain_mtext(s: &str) -> String { '\\' => { let code = chars.get(i + 1).copied().unwrap_or(' '); match code { - 'P' => { - out.push('\n'); - i += 2; - } - 'N' => { + 'P' | 'N' => { out.push('\n'); i += 2; } @@ -79,8 +76,7 @@ pub fn plain_mtext(s: &str) -> String { _ => i += 2, } } - '{' | '}' => i += 1, - '\r' => i += 1, + '{' | '}' | '\r' => i += 1, _ => { out.push(c); i += 1; @@ -120,6 +116,7 @@ pub struct MTextParams { } impl MTextParams { + #[must_use] pub fn new(insert: Vec2, height: f64) -> Self { MTextParams { insert, @@ -357,6 +354,10 @@ fn font_switch(a: &str) -> Option { } /// Parse MTEXT contents into words, spaces and paragraph breaks with their formats. +#[expect( + clippy::too_many_lines, + reason = "The MTEXT escape grammar is one cohesive state machine; its ordered transitions are clearer in a single dispatch." +)] fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { let chars: Vec = contents.chars().collect(); let h_min = base.height * 1e-3; @@ -634,56 +635,56 @@ fn seg_width(seg: &Seg, f: &Fmt) -> f64 { } /// Shape a segment with its left end at `x` on the baseline. -fn seg_shape(seg: &Seg, f: &Fmt, x: f64) -> Shaped { - let h = f.height; +fn seg_shape(seg: &Seg, format: &Fmt, origin_x: f64) -> Shaped { + let height = format.height; let mut out = Shaped::default(); - let put = |s: &str, size: f64, at: Vec2| { - if s.is_empty() { + let put = |text: &str, size: f64, at: Vec2| { + if text.is_empty() { return Shaped::default(); } - let mut sh = shape_line(&f.font, s, size, f.wf, f.oblique); - sh.map(|p| p + at); + let mut sh = shape_line(&format.font, text, size, format.wf, format.oblique); + sh.map(|point| point + at); sh }; - let w = seg_width(seg, f); + let width = seg_width(seg, format); match seg { - Seg::Text(t) => out.extend(put(t, h, Vec2::new(x, 0.0))), + Seg::Text(text) => out.extend(put(text, height, Vec2::new(origin_x, 0.0))), Seg::Stack(top, bottom, sep) => { - let hs = h * STACK_SCALE; - let wt = text_width(&f.font, top, hs, f.wf); - let wb = text_width(&f.font, bottom, hs, f.wf); + let hs = height * STACK_SCALE; + let wt = text_width(&format.font, top, hs, format.wf); + let wb = text_width(&format.font, bottom, hs, format.wf); match sep { '#' => { - out.extend(put(top, hs, Vec2::new(x, h * 0.4))); - let sx = x + wt + h * 0.1; - out.extend(put(bottom, hs, Vec2::new(sx + h * 0.4, -h * 0.05))); - out.strokes.push(vec![Vec2::new(sx, -h * 0.1), Vec2::new(sx + h * 0.3, h * 1.1)]); + out.extend(put(top, hs, Vec2::new(origin_x, height * 0.4))); + let sx = origin_x + wt + height * 0.1; + out.extend(put(bottom, hs, Vec2::new(sx + height * 0.4, -height * 0.05))); + out.strokes.push(vec![Vec2::new(sx, -height * 0.1), Vec2::new(sx + height * 0.3, height * 1.1)]); } '^' => { // Tolerances: centred on the line, or the lower value on the baseline (\A0) or // the upper value level with the text (\A2). - let (yt, yb) = match f.valign { - 0 => (hs + h * 0.1, 0.0), - 2 => (0.0, -hs - h * 0.1), - _ => (h * 0.55, h * 0.45 - hs), + let (yt, yb) = match format.valign { + 0 => (hs + height * 0.1, 0.0), + 2 => (0.0, -hs - height * 0.1), + _ => (height * 0.55, height * 0.45 - hs), }; - out.extend(put(top, hs, Vec2::new(x, yt))); - out.extend(put(bottom, hs, Vec2::new(x, yb))); + out.extend(put(top, hs, Vec2::new(origin_x, yt))); + out.extend(put(bottom, hs, Vec2::new(origin_x, yb))); } _ => { - let bar = h * 0.45; - out.extend(put(top, hs, Vec2::new(x + (w - wt) / 2.0, bar + h * 0.12))); - out.extend(put(bottom, hs, Vec2::new(x + (w - wb) / 2.0, bar - h * 0.12 - hs))); - out.strokes.push(vec![Vec2::new(x, bar), Vec2::new(x + w, bar)]); + let bar = height * 0.45; + out.extend(put(top, hs, Vec2::new(origin_x + (width - wt) / 2.0, bar + height * 0.12))); + out.extend(put(bottom, hs, Vec2::new(origin_x + (width - wb) / 2.0, bar - height * 0.12 - hs))); + out.strokes.push(vec![Vec2::new(origin_x, bar), Vec2::new(origin_x + width, bar)]); } } } } - if f.under { - out.strokes.push(vec![Vec2::new(x, -h * 0.2), Vec2::new(x + w, -h * 0.2)]); + if format.under { + out.strokes.push(vec![Vec2::new(origin_x, -height * 0.2), Vec2::new(origin_x + width, -height * 0.2)]); } - if f.over { - out.strokes.push(vec![Vec2::new(x, h * 1.2), Vec2::new(x + w, h * 1.2)]); + if format.over { + out.strokes.push(vec![Vec2::new(origin_x, height * 1.2), Vec2::new(origin_x + width, height * 1.2)]); } out } @@ -743,6 +744,7 @@ impl Line { } /// Lay out MTEXT with the stroke font. `attach` 1..=9 (TL, TC, TR, ML, MC, MR, BL, BC, BR). +#[must_use] pub fn layout_mtext(contents: &str, insert: Vec2, height: f64, width: f64, attach: u8, rotation: f64, line_spacing: f64) -> MTextLayout { layout_mtext_with(contents, &MTextParams { insert, height, width, attach, rotation, line_spacing, ..MTextParams::new(insert, height) }) } @@ -791,8 +793,7 @@ fn plain_lines(atoms: &[Atom], fmts: &[Fmt], base: &Fmt, width: f64) -> Vec 0.0 && !line.items.is_empty() && line.width + space_width + word_width > width + 1e-9 { finish(&mut lines, &mut line, fmt(last_fmt), paragraph); } else if !line.items.is_empty() || pending_space.is_some() { @@ -1120,7 +1121,7 @@ mod tests { let cols: Vec> = l.pieces.iter().map(|p| p.color).collect(); assert_eq!(cols, vec![None, Some(MTextColor::Aci(1)), None]); let l = lay("\\c16711680;R", 0.0); - assert_eq!(l.pieces.first().map(|p| p.color), Some(Some(MTextColor::Rgb(0xFF0000)))); + assert_eq!(l.pieces.first().map(|p| p.color), Some(Some(MTextColor::Rgb(0x00FF_0000)))); } #[test] @@ -1142,8 +1143,8 @@ mod tests { let bar = l.strokes.iter().find(|s| s.len() == 2 && (s[0].y - s[1].y).abs() < 1e-12 && (s[0].y + 0.55).abs() < 1e-9); assert!(bar.is_some()); let ys: Vec = l.strokes.iter().flatten().map(|p| p.y).collect(); - let max = ys.iter().cloned().fold(f64::MIN, f64::max); - let min = ys.iter().cloned().fold(f64::MAX, f64::min); + let max = ys.iter().copied().fold(f64::MIN, f64::max); + let min = ys.iter().copied().fold(f64::MAX, f64::min); assert!(max > 0.0 && min < -1.0, "{min}..{max}"); // Narrower than the two digits side by side at full size. assert!(l.bounds.width() < crate::line_width("12", 1.0, 1.0)); diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index 63b431610..158c0ae99 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -57,7 +57,7 @@ pub enum ParaAlign { } /// Paragraph properties set by `\p…;`. Indents and tab stops are in drawing units (as in -/// AutoCAD files: `\pi4.86;` indents the first line by 4.86 units), space before and after in +/// `AutoCAD` files: `\pi4.86;` indents the first line by 4.86 units), space before and after in /// text heights. They stay in effect for the following paragraphs until another `\p` changes them. #[derive(Clone, Debug, Default, PartialEq)] pub struct ParaProps { @@ -219,6 +219,7 @@ pub enum ListStyle { impl ListStyle { /// The label of item `i` (from 0). + #[must_use] pub fn label(self, i: usize) -> String { let letters = |upper: bool| { // Bijective base 26: a … z, aa, ab … @@ -226,7 +227,7 @@ impl ListStyle { let mut s = Vec::new(); while n > 0 && s.len() < 16 { n -= 1; - let c = b'a' + (n % 26) as u8; + let c = b'a' + u8::try_from(n % 26).unwrap_or(0); s.push(char::from(if upper { c.to_ascii_uppercase() } else { c })); n /= 26; } @@ -243,6 +244,7 @@ impl ListStyle { /// Paragraphs as a list: a hanging indent of `indent` drawing units with a tab stop there, and /// each paragraph its label and a tab (`\pxi-3,l3,t3;1.First\P2.Second`). +#[must_use] pub fn list_contents(paragraphs: &[&str], style: ListStyle, indent: f64) -> String { let indent = if indent.is_finite() && indent > 0.0 { indent.min(MAX_UNITS) } else { 3.0 }; let props = ParaProps { first: -indent, left: indent, tabs: vec![(indent, TabKind::Left)], ..ParaProps::default() }; @@ -263,6 +265,7 @@ pub struct Paragraphs { } impl Paragraphs { + #[must_use] pub fn scan(contents: &str) -> Paragraphs { let contents = super::unescape_codes(contents); let chars: Vec = contents.chars().collect(); @@ -326,17 +329,20 @@ impl Paragraphs { } /// Properties of paragraph `k`. + #[must_use] pub fn props(&self, k: usize) -> &ParaProps { let st = self.para.get(k).or(self.para.last()).copied().unwrap_or(0); self.states.get(st).or(self.states.first()).unwrap_or(&DEFAULT_PROPS) } /// The break after paragraph `k` starts a new column. + #[must_use] pub fn column_break(&self, k: usize) -> bool { self.column_break.get(k).copied().unwrap_or(false) } /// Any paragraph formatting at all. + #[must_use] pub fn formatted(&self) -> bool { self.states.len() > 1 || self.column_break.iter().any(|b| *b) } @@ -544,9 +550,7 @@ impl<'a> LineBuilder<'a> { fn place(&mut self, index: usize, segments: &[(Seg, usize)]) { let word_width = self.word_width(segments); let space_width = if index == 0 { - self.pending_space - .map(|format| crate::space_width(&self.format(format).font, self.format(format).height, self.format(format).wf)) - .unwrap_or(0.0) + self.pending_space.map_or(0.0, |format| crate::space_width(&self.format(format).font, self.format(format).height, self.format(format).wf)) } else { 0.0 }; @@ -596,72 +600,80 @@ fn next_tab(x: f64, pp: &ParaProps, h: f64) -> (f64, TabKind) { } /// Lay out MTEXT with paragraph formatting and columns. `base` is the entity's own format, -/// `h` its text height, `width` the column width (0: no wrapping, no columns). -pub(super) fn layout(contents: &str, p: &MTextParams, base: &Fmt) -> MTextLayout { - let h = base.height; - let width = if p.width.is_finite() && p.width > 0.0 { p.width } else { 0.0 }; - let rotation = if p.rotation.is_finite() { p.rotation } else { 0.0 }; - let paras = Paragraphs::scan(contents); +/// `height` its text height, `width` the column width (0: no wrapping, no columns). +#[expect( + clippy::too_many_lines, + reason = "Paragraph and column placement is one ordered state machine; splitting it would obscure the transitions between lines and columns." +)] +#[expect( + clippy::cast_precision_loss, + reason = "Column indices are at most MAX_COLUMNS and gap counts at most MAX_ATOMS, so every usize converted here is exact in f64." +)] +pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextLayout { + let height = base.height; + let width = if params.width.is_finite() && params.width > 0.0 { params.width } else { 0.0 }; + let rotation = if params.rotation.is_finite() { params.rotation } else { 0.0 }; + let paragraphs = Paragraphs::scan(contents); let (atoms, fmts) = parse(contents, base.clone()); - let fmt = |i: usize| fmts.get(i).unwrap_or(base); - let lines = LineBuilder::new(¶s, &fmts, base, width, h).build(&atoms); + let fmt = |index: usize| fmts.get(index).unwrap_or(base); + let lines = LineBuilder::new(¶graphs, &fmts, base, width, height).build(&atoms); // Vertical placement: baselines below the top of each line's column. - let ls = super::sane_line_spacing(p.line_spacing); - let cols = p.columns.as_ref().filter(|_| width > 0.0); + let line_spacing = super::sane_line_spacing(params.line_spacing); + let cols = params.columns.as_ref().filter(|_| width > 0.0); let max_cols = match cols { - Some(c) if c.dynamic => MAX_COLUMNS, - Some(c) => c.count.clamp(1, MAX_COLUMNS), + Some(spec) if spec.dynamic => MAX_COLUMNS, + Some(spec) => spec.count.clamp(1, MAX_COLUMNS), None => 1, }; - let col_height = |c: usize| -> f64 { + let col_height = |column: usize| -> f64 { let Some(spec) = cols else { return 0.0 }; - let v = if spec.heights.is_empty() { spec.height } else { spec.heights.get(c).or(spec.heights.last()).copied().unwrap_or(0.0) }; - if v.is_finite() && v > 0.0 { v } else { 0.0 } + let value = if spec.heights.is_empty() { spec.height } else { spec.heights.get(column).or(spec.heights.last()).copied().unwrap_or(0.0) }; + if value.is_finite() && value > 0.0 { value } else { 0.0 } }; let mut placed: Vec<(usize, f64)> = Vec::with_capacity(lines.len()); - let (mut c, mut y, mut first_in_col, mut force) = (0usize, 0.0f64, true, false); + let (mut column, mut current_y, mut first_in_col, mut force) = (0usize, 0.0f64, true, false); let mut col_bottom = vec![0.0f64]; let mut prev_para: Option = None; - for l in &lines { - let lh = if l.max_h > 0.0 { l.max_h } else { h }; - let new_para = prev_para != Some(l.para); - let before = if new_para && prev_para.is_some() { paras.props(l.para).before * h } else { 0.0 }; - let step_h = if p.line_spacing_exact { h } else { lh }; - let pitch = |first: bool| if first { lh } else { step_h * 5.0 / 3.0 * ls + before }; - let hc = col_height(c); - if !first_in_col && c + 1 < max_cols && (force || (hc > 0.0 && y + pitch(false) > hc + 1e-9)) { - c += 1; + for line in &lines { + let line_height = if line.max_h > 0.0 { line.max_h } else { height }; + let new_para = prev_para != Some(line.para); + let before = if new_para && prev_para.is_some() { paragraphs.props(line.para).before * height } else { 0.0 }; + let step_h = if params.line_spacing_exact { height } else { line_height }; + let pitch = |first: bool| if first { line_height } else { step_h * 5.0 / 3.0 * line_spacing + before }; + let column_height = col_height(column); + if !first_in_col && column + 1 < max_cols && (force || (column_height > 0.0 && current_y + pitch(false) > column_height + 1e-9)) { + column += 1; col_bottom.push(0.0); - y = 0.0; + current_y = 0.0; first_in_col = true; } force = false; - y += pitch(first_in_col); + current_y += pitch(first_in_col); first_in_col = false; - placed.push((c, -y)); - if let Some(b) = col_bottom.get_mut(c) { - *b = y; + placed.push((column, -current_y)); + if let Some(bottom) = col_bottom.get_mut(column) { + *bottom = current_y; } - if l.para_end { - y += paras.props(l.para).after * h; - force = paras.column_break(l.para); + if line.para_end { + current_y += paragraphs.props(line.para).after * height; + force = paragraphs.column_break(line.para); } - prev_para = Some(l.para); + prev_para = Some(line.para); } let n_cols = match cols { Some(spec) if !spec.dynamic => max_cols, - _ => c + 1, + _ => column + 1, }; let content_h = col_bottom.iter().copied().fold(0.0, f64::max); let block_h = match cols { Some(_) => (0..n_cols).map(col_height).fold(content_h, f64::max), None => content_h, }; - let col_w = if width > 0.0 { width } else { lines.iter().map(|l| l.width + paras.props(l.para).right).fold(0.0, f64::max) }; - let gutter = cols.map(|s| s.gutter).filter(|g| g.is_finite() && *g >= 0.0).unwrap_or(0.0); + let col_w = if width > 0.0 { width } else { lines.iter().map(|line| line.width + paragraphs.props(line.para).right).fold(0.0, f64::max) }; + let gutter = cols.map(|spec| spec.gutter).filter(|g| g.is_finite() && *g >= 0.0).unwrap_or(0.0); let total_w = col_w * n_cols as f64 + gutter * n_cols.saturating_sub(1) as f64; - let attach = p.attach.clamp(1, 9) - 1; + let attach = params.attach.clamp(1, 9) - 1; let (acol, arow) = (attach % 3, attach / 3); let top = match arow { 0 => 0.0, @@ -673,41 +685,42 @@ pub(super) fn layout(contents: &str, p: &MTextParams, base: &Fmt) -> MTextLayout 1 => -total_w / 2.0, _ => -total_w, }; - let reversed = cols.is_some_and(|s| s.reversed); - let insert = p.insert; - let xf = |q: Vec2| insert + q.rotate(rotation); - let mut out = MTextLayout { lines: lines.iter().map(|l| l.text.clone()).collect(), ..Default::default() }; + let reversed = cols.is_some_and(|spec| spec.reversed); + let insert = params.insert; + let xf = |point: Vec2| insert + point.rotate(rotation); + let mut out = MTextLayout { lines: lines.iter().map(|line| line.text.clone()).collect(), ..Default::default() }; let mut allowance = super::Allowance::new(); - for (l, (c, base_y)) in lines.iter().zip(placed) { - let pp = paras.props(l.para); - let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(c) } else { c }; + for (line, (column, base_y)) in lines.iter().zip(placed) { + let pp = paragraphs.props(line.para); + let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column }; let col_x = box_x0 + slot as f64 * (col_w + gutter); let right_edge = col_w - pp.right; - let free = right_edge - l.width; + let free = right_edge - line.width; let align = match pp.align { ParaAlign::Default => [ParaAlign::Left, ParaAlign::Center, ParaAlign::Right].get(usize::from(acol)).copied().unwrap_or_default(), - a => a, + alignment => alignment, }; - let spread = width > 0.0 && l.gaps > 0 && free > 0.0 && (align == ParaAlign::Distributed || (align == ParaAlign::Justify && !l.para_end)); + let spread = + width > 0.0 && line.gaps > 0 && free > 0.0 && (align == ParaAlign::Distributed || (align == ParaAlign::Justify && !line.para_end)); let (shift, per_gap) = match align { ParaAlign::Center => (free / 2.0, 0.0), ParaAlign::Right => (free, 0.0), - _ if spread => (0.0, free / l.gaps as f64), + _ if spread => (0.0, free / line.gaps as f64), _ => (0.0, 0.0), }; - for it in &l.items { - let fm = fmt(it.fmt); + for item in &line.items { + let fm = fmt(item.fmt); if !allowance.left() { out.truncated = true; continue; } - let mut sh = seg_shape(&it.seg, fm, it.x); + let mut sh = seg_shape(&item.seg, fm, item.x); if !allowance.charge(&sh) { out.truncated = true; continue; } - let off = Vec2::new(col_x + shift + per_gap * it.gap as f64, top + base_y); - sh.map(|q| xf(q + off)); + let off = Vec2::new(col_x + shift + per_gap * item.gap as f64, top + base_y); + sh.map(|point| xf(point + off)); match out.pieces.last_mut() { Some(pc) if pc.color == fm.color => pc.shaped.extend(sh), _ => out.pieces.push(MTextPiece { color: fm.color, shaped: sh }), @@ -763,17 +776,17 @@ mod tests { #[test] fn props_parse_and_persist() { let p = Paragraphs::scan("\\pxi-3,l3,t3;1.\tone\\P2.\ttwo\\P\\pi0,l0,tz;plain"); - assert_eq!(p.props(0).first, -3.0); - assert_eq!(p.props(0).left, 3.0); + assert!((p.props(0).first + 3.0).abs() < f64::EPSILON); + assert!((p.props(0).left - 3.0).abs() < f64::EPSILON); assert_eq!(p.props(0).tabs, vec![(3.0, TabKind::Left)]); assert_eq!(p.props(1), p.props(0)); - assert_eq!(p.props(2).left, 0.0); + assert!(p.props(2).left.abs() < f64::EPSILON); assert!(p.props(2).tabs.is_empty()); let mut pp = ParaProps::default(); pp.apply("t2,c4,r6,d8,qc,b0.5"); assert_eq!(pp.tabs, vec![(2.0, TabKind::Left), (4.0, TabKind::Center), (6.0, TabKind::Right), (8.0, TabKind::Decimal)]); assert_eq!(pp.align, ParaAlign::Center); - assert_eq!(pp.before, 0.5); + assert!((pp.before - 0.5).abs() < f64::EPSILON); let mut back = ParaProps::default(); back.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';')); assert_eq!(back, pp); diff --git a/crates/fonts/src/stroke.rs b/crates/fonts/src/stroke.rs index 43aa2dd3f..d62689dc7 100644 --- a/crates/fonts/src/stroke.rs +++ b/crates/fonts/src/stroke.rs @@ -1,4 +1,4 @@ -//! "CADCraft Stroke": an original single-stroke drafting font, designed for CADCraft on a +//! "`CADCraft` Stroke": an original single-stroke drafting font, designed for `CADCraft` on a //! small grid (public domain / CC0 as part of this codebase). //! //! Each glyph is `(width, strokes)`. A stroke is a run of points; each point is two characters: @@ -8,8 +8,10 @@ pub(crate) const CAP: f64 = 6.0; pub(crate) const GAP: f64 = 1.6; +// List bullet: a small crossed diamond at mid x-height. +#[expect(clippy::too_many_lines, reason = "The stroke font is one static glyph table; splitting it would obscure the character-to-outline mapping.")] pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { - let g: (f64, &str) = match c { + Some(match c { ' ' => (2.4, ""), 'A' => (4.0, "0c2i4c 1f3f"), 'B' => (4.0, "0c0i3i4h4g3f0f 3f4e4d3c0c"), @@ -25,7 +27,6 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { 'L' => (4.0, "0i0c4c"), 'M' => (4.0, "0c0i2f4i4c"), 'N' => (4.0, "0c0i4c4i"), - 'O' => (4.0, "1c0d0h1i3i4h4d3c1c"), 'P' => (4.0, "0c0i3i4h4g3f0f"), 'Q' => (4.0, "1c0d0h1i3i4h4d3c1c 2e4b"), 'R' => (4.0, "0c0i3i4h4g3f0f 2f4c"), @@ -37,7 +38,7 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { 'X' => (4.0, "0i4c 0c4i"), 'Y' => (4.0, "0i2f4i 2f2c"), 'Z' => (4.0, "0i4i0c4c"), - '0' => (4.0, "1c0d0h1i3i4h4d3c1c"), + 'O' | '0' => (4.0, "1c0d0h1i3i4h4d3c1c"), '1' => (4.0, "1h2i2c 1c3c"), '2' => (4.0, "0h1i3i4h4g0c4c"), '3' => (4.0, "0h1i3i4h4g3f2f 3f4e4d3c1c0d"), @@ -108,7 +109,6 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { '°' => (2.0, "1i0h1g2h1i"), '±' => (4.0, "2e2i 0g4g 0d4d"), 'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"), - // List bullet: a small crossed diamond at mid x-height. '•' => (2.0, "1d0e1f2e1d 0e2e 1d1f"), // Original Latin diacritics, composed from our own letter bodies and marks. '\u{00C0}' => (4.0, concat!("0c2i4c 1f3f", " 1k3j")), @@ -166,8 +166,7 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { '\u{00FF}' => (4.0, concat!("0g2c 4g1a0a", " 1h1i 3h3i")), '\u{0178}' => (4.0, concat!("0i2f4i 2f2c", " 1j1k 3j3k")), _ => return None, - }; - Some(g) + }) } /// Decode one stroke string into point lists in font units. diff --git a/crates/fonts/src/subset.rs b/crates/fonts/src/subset.rs index 18f59872b..ebf2b0932 100644 --- a/crates/fonts/src/subset.rs +++ b/crates/fonts/src/subset.rs @@ -23,8 +23,8 @@ pub enum Embedding { NotTrueType, } -fn table<'a>(f: &FontRef<'a>, t: &[u8; 4]) -> Option<&'a [u8]> { - f.table_data(Tag::new(t)).map(|d| d.as_bytes()) +fn table<'a>(f: &FontRef<'a>, t: [u8; 4]) -> Option<&'a [u8]> { + f.table_data(Tag::new(&t)).map(|d| d.as_bytes()) } fn u16_at(b: &[u8], i: usize) -> Option { @@ -32,12 +32,13 @@ fn u16_at(b: &[u8], i: usize) -> Option { } /// The embedding permission of a face. +#[must_use] pub fn embedding(face: &Face) -> Embedding { let Ok(f) = FontRef::from_index(&face.bytes, face.index) else { return Embedding::NotTrueType }; - if table(&f, b"glyf").is_none() || table(&f, b"loca").is_none() || table(&f, b"head").is_none() { + if table(&f, *b"glyf").is_none() || table(&f, *b"loca").is_none() || table(&f, *b"head").is_none() { return Embedding::NotTrueType; } - let Some(fs_type) = table(&f, b"OS/2").and_then(|o| u16_at(o, 8)) else { return Embedding::Allowed }; + let Some(fs_type) = table(&f, *b"OS/2").and_then(|o| u16_at(o, 8)) else { return Embedding::Allowed }; if fs_type & 0x0200 != 0 { Embedding::BitmapOnly } else if fs_type & 0x000F == 0x0002 { diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index c166936c6..70aa4656d 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -7,10 +7,10 @@ //! //! System fonts are searched in the platform's own directories: `/System/Library/Fonts` and //! friends on macOS, `C:\Windows\Fonts` on Windows, `/system/fonts` and the product/vendor -//! partitions on Android and HarmonyOS, and the XDG directories elsewhere. Web builds have no +//! partitions on Android and `HarmonyOS`, and the XDG directories elsewhere. Web builds have no //! system fonts. //! -//! Two process-wide settings (like AutoCAD's profile variables) control substitution: +//! Two process-wide settings (like `AutoCAD`'s profile variables) control substitution: //! - [`font_alt`] (`FONTALT`): the font used for a text style font that can't be found (an SHX //! file we don't read, a missing TTF). Empty = the built-in stroke font. //! - [`fallback_fonts`] (`FONTFALLBACK`): fonts tried first for characters the text's font @@ -58,6 +58,7 @@ impl std::fmt::Debug for Face { impl Face { /// Face `index` of font file `bytes`, if it parses. + #[must_use] pub fn new(bytes: Arc>, index: u32) -> Option { FontRef::from_index(&bytes, index).ok()?; Some(Face { bytes, index }) @@ -80,6 +81,7 @@ impl Face { .is_some_and(|l| l.feature_records().iter().any(|r| tags.contains(&r.feature_tag()))) } /// Whether the face maps `c` to a glyph. + #[must_use] pub fn has_glyph(&self, c: char) -> bool { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } @@ -97,7 +99,7 @@ impl Face { pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec> { let Some(f) = self.font() else { return vec![None; chars.len()] }; let map = f.charmap(); - chars.iter().map(|c| map.map(*c).map(|g| g.to_u32())).collect() + chars.iter().map(|c| map.map(*c).map(skrifa::GlyphId::to_u32)).collect() } fn names(&self) -> Vec { let Some(f) = self.font() else { return Vec::new() }; @@ -113,6 +115,7 @@ impl Face { } /// Faces of a font file: every face of a collection (capped), or the single font. +#[must_use] pub fn faces(bytes: &Arc>) -> Vec { match FileRef::new(bytes) { Ok(FileRef::Collection(c)) => (0..c.len().min(MAX_FACES_PER_FILE)).filter_map(|i| Face::new(bytes.clone(), i)).collect(), @@ -838,11 +841,17 @@ fn key(name: &str) -> String { /// Names that mean a stroke font: never looked up as TrueType. fn is_stroke_name(k: &str) -> bool { - k.is_empty() || k.ends_with(".shx") || k == crate::BUILTIN_FONT.to_ascii_lowercase() || k == "txt" || k == "simplex" || k == "romans" + k.is_empty() + || std::path::Path::new(k).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("shx")) + || k == crate::BUILTIN_FONT.to_ascii_lowercase() + || k == "txt" + || k == "simplex" + || k == "romans" } /// A face of an installed (or registered) font by file name or family name. Stroke-font names /// (".shx", empty) return `None`. +#[must_use] pub fn find(name: &str) -> Option { let k = key(name); if is_stroke_name(&k) { @@ -882,6 +891,7 @@ fn split_list(s: &str) -> Vec { /// FONTALT: the font used for a text style font that can't be found. Empty = the built-in /// stroke font. +#[must_use] pub fn font_alt() -> String { prefs().alt.clone() } @@ -892,6 +902,7 @@ pub fn set_font_alt(name: &str) { } /// FONTFALLBACK: fonts tried first for characters a text's font lacks, comma-separated. +#[must_use] pub fn fallback_fonts() -> String { prefs().fallback.join(", ") } @@ -909,6 +920,7 @@ fn wants_fallback(c: char) -> bool { /// A face that has `c`, for text whose own font lacks it: FONTFALLBACK fonts, then FONTALT, /// then installed fonts (wide-coverage CJK fonts first). Bounded and cached. +#[must_use] pub fn fallback_for(c: char) -> Option { if !wants_fallback(c) { return None; @@ -1025,26 +1037,31 @@ impl OutlinePen for Pen { self.push(Self::pt(x, y)); } /// Flatten a quadratic segment into six samples, charging each retained point to the glyph budget. - fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { - let a = self.cur.last().copied().unwrap_or_default(); - let c = Self::pt(cx0, cy0); - let b = Self::pt(x, y); - for i in 1..=6 { - let t = f64::from(i) / 6.0; - let u = 1.0 - t; - self.push(a * (u * u) + c * (2.0 * u * t) + b * (t * t)); + fn quad_to(&mut self, cx0: f32, cy0: f32, end_x: f32, end_y: f32) { + let start = self.cur.last().copied().unwrap_or_default(); + let control = Self::pt(cx0, cy0); + let end = Self::pt(end_x, end_y); + for step in 1..=6 { + let ratio = f64::from(step) / 6.0; + let inverse_ratio = 1.0 - ratio; + self.push(start * (inverse_ratio * inverse_ratio) + control * (2.0 * inverse_ratio * ratio) + end * (ratio * ratio)); } } /// Flatten a cubic segment into eight samples, charging each retained point to the glyph budget. - fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { - let a = self.cur.last().copied().unwrap_or_default(); + fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, end_x: f32, end_y: f32) { + let start = self.cur.last().copied().unwrap_or_default(); let c0 = Self::pt(cx0, cy0); let c1 = Self::pt(cx1, cy1); - let b = Self::pt(x, y); - for i in 1..=8 { - let t = f64::from(i) / 8.0; - let u = 1.0 - t; - self.push(a * (u * u * u) + c0 * (3.0 * u * u * t) + c1 * (3.0 * u * t * t) + b * (t * t * t)); + let end = Self::pt(end_x, end_y); + for step in 1..=8 { + let ratio = f64::from(step) / 8.0; + let inverse_ratio = 1.0 - ratio; + self.push( + start * (inverse_ratio * inverse_ratio * inverse_ratio) + + c0 * (3.0 * inverse_ratio * inverse_ratio * ratio) + + c1 * (3.0 * inverse_ratio * ratio * ratio) + + end * (ratio * ratio * ratio), + ); } } fn close(&mut self) { @@ -1054,7 +1071,8 @@ impl OutlinePen for Pen { /// How far below the baseline a face reaches, as a fraction of the text height (which is the /// face's cap height): its descent over its cap height. A bottom-justified text's alignment -/// point is there, as AutoCAD places it (#2229). `None` when the face has no usable descent. +/// point is there, as `AutoCAD` places it (#2229). `None` when the face has no usable descent. +#[must_use] pub fn descent_ratio(face: &Face) -> Option { let f = face.font()?; let descent = -f64::from(f.metrics(Size::new(UPEM), LocationRef::default()).descent); @@ -1089,6 +1107,7 @@ pub(crate) fn glyph_by_id(face: &Face, gid: u32) -> Arc { /// Closed, flattened contours of a glyph at 1000 font units per em. Shared with the outline /// cache so renderers can tessellate once before applying each occurrence's affine placement. +#[must_use] pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec]> { glyph_by_id(face, u32::from(gid)).contours.clone() } @@ -1196,11 +1215,13 @@ pub(crate) fn place_glyph_at(g: &GlyphOutline, origin: Vec2, scale: f64, wf: f64 /// Shape one line with a TrueType face: closed glyph contours grouped per glyph (baseline at /// y = 0, x from 0) plus `%%u`/`%%o` decorations as strokes. Text height = cap height. /// Characters the face lacks come from a fallback font, scaled to its own cap height. +#[must_use] pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option { shape_dir(face, s, height, width_factor, oblique, None) } /// [`shape`] in the direction `base_rtl` (`None`: that of the line's first strong character). +#[must_use] pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Option { face.font()?; // As in [`crate::shape_stroke_dir`]: a line asked to run right to left takes the bidi path. @@ -1240,6 +1261,7 @@ pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique: } /// Width of one line set in a TrueType face. +#[must_use] pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option { face.font()?; if crate::complex::needed(s) @@ -1261,6 +1283,7 @@ pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option Option { let sh = shape(face, s, height, width_factor, oblique)?; let mut strokes: Vec> = sh.glyphs.into_iter().flatten().collect(); diff --git a/crates/fonts/tests/mtext_paragraphs.rs b/crates/fonts/tests/mtext_paragraphs.rs index 26291b78d..3baaa1885 100644 --- a/crates/fonts/tests/mtext_paragraphs.rs +++ b/crates/fonts/tests/mtext_paragraphs.rs @@ -22,7 +22,7 @@ fn max_x(l: &MTextLayout) -> f64 { /// Leftmost x of the geometry of line `n` (0 = first; baselines 5/3 apart below -1). fn line_min_x(l: &MTextLayout, n: usize) -> f64 { - let base = -1.0 - n as f64 * 5.0 / 3.0; + let base = -1.0 - f64::from(u32::try_from(n).unwrap_or(u32::MAX)) * 5.0 / 3.0; l.strokes.iter().flatten().filter(|p| p.y >= base - 0.4 && p.y <= base + 1.3).map(|p| p.x).fold(f64::MAX, f64::min) } @@ -59,7 +59,7 @@ fn paragraph_alignment_overrides_the_attachment() { let right = lay("\\pqr;ab", 10.0, None); assert!(max_x(&right) > 9.0 && max_x(&right) <= 10.0 + 1e-9, "{}", max_x(&right)); let centre = lay("\\pqc;ab", 10.0, None); - let c = (min_x(¢re) + max_x(¢re)) / 2.0; + let c = f64::midpoint(min_x(¢re), max_x(¢re)); assert!((c - 5.0).abs() < 0.5, "{c}"); } @@ -79,7 +79,7 @@ fn text_flows_through_static_columns() { assert!((l.bounds.width() - 34.0).abs() < 1e-9); assert!((l.bounds.height() - 6.0).abs() < 1e-9); for col in 0..3 { - let x0 = col as f64 * 12.0; + let x0 = f64::from(col) * 12.0; assert!(xs(&l).iter().any(|x| *x >= x0 && *x <= x0 + 10.0), "column {col} has text"); } // The gutters stay empty. From f8772138760b0a2cfed89b3603a130036680224c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 17:05:54 +0100 Subject: [PATCH 07/24] fix(fonts): preserve SHX dotfile handling --- crates/fonts/src/ttf.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 70aa4656d..60f92da8f 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -842,6 +842,7 @@ fn key(name: &str) -> String { /// Names that mean a stroke font: never looked up as TrueType. fn is_stroke_name(k: &str) -> bool { k.is_empty() + || k == ".shx" || std::path::Path::new(k).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("shx")) || k == crate::BUILTIN_FONT.to_ascii_lowercase() || k == "txt" @@ -1411,6 +1412,13 @@ mod family_tests { let many: Vec = (0..100).map(|i| format!("gost{i:03}")).collect(); assert!(family_candidates(&many, "gosttypea", "gost").len() <= MAX_FAMILY_FILES + MAX_FIRST_WORD_FILES); } + + #[test] + fn dotfile_shx_names_are_stroke_names() { + for name in [".shx", ".shx.ttf", ".SHX", ".SHX.TTF"] { + assert!(is_stroke_name(&key(name)), "{name}"); + } + } } #[cfg(test)] From 4072f842901bd1886e861a14466e9d48e15ffcd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 23:42:49 +0100 Subject: [PATCH 08/24] style(fonts): remove review churn --- crates/fonts/src/bidi.rs | 8 -------- crates/fonts/src/lib.rs | 23 ++--------------------- crates/fonts/src/mtext.rs | 3 --- crates/fonts/src/mtext/para.rs | 6 ------ crates/fonts/src/stroke.rs | 2 +- crates/fonts/src/subset.rs | 1 - crates/fonts/src/ttf.rs | 13 ------------- 7 files changed, 3 insertions(+), 53 deletions(-) diff --git a/crates/fonts/src/bidi.rs b/crates/fonts/src/bidi.rs index d7134ed42..27a45ee9f 100644 --- a/crates/fonts/src/bidi.rs +++ b/crates/fonts/src/bidi.rs @@ -36,7 +36,6 @@ pub(crate) fn is_mark(c: char) -> bool { /// right-to-left, `Some(false)` left-to-right, `None` when it has no strong character. As rule /// P2 requires, characters between an isolate initiator and its matching PDI (or the end of the /// paragraph, when unmatched) are skipped. -#[must_use] pub fn base_rtl(s: &str) -> Option { let mut isolate_depth: usize = 0; for c in s.chars() { @@ -66,7 +65,6 @@ fn byte_starts(text: &str) -> Vec { /// each flagged right-to-left or not. The paragraph direction comes from the first strong /// character (or `base` when given). Characters inside a right-to-left run are still in logical /// order: the caller lays them out from right to left. -#[must_use] pub fn visual_runs(chars: &[char], base: Option) -> Vec<(Range, bool)> { if chars.is_empty() { return Vec::new(); @@ -87,7 +85,6 @@ pub fn visual_runs(chars: &[char], base: Option) -> Vec<(Range, boo /// Resolved embedding level of every character of one line (after rule L1), for reordering /// pieces of the line with [`reorder`]. -#[must_use] pub fn char_levels(text: &str, base: Option) -> Vec { if text.is_empty() { return Vec::new(); @@ -98,14 +95,12 @@ pub fn char_levels(text: &str, base: Option) -> Vec { /// Display order (rule L2) of items with the given embedding levels: indices into `levels`, /// left to right. -#[must_use] pub fn reorder(levels: &[u8]) -> Vec { let lv: Vec = levels.iter().map(|l| Level::new(*l).unwrap_or_else(|_| Level::ltr())).collect(); ParagraphBidiInfo::reorder_visual(&lv) } /// The mirrored glyph of a paired bracket in right-to-left text (rule L4, common pairs). -#[must_use] pub fn mirror(c: char) -> char { match c { '(' => ')', @@ -128,7 +123,6 @@ pub fn mirror(c: char) -> char { /// A line in display order, code point by code point: right-to-left runs reversed and their /// brackets mirrored. Shows what the layout draws, before glyph shaping. -#[must_use] pub fn visual_order(s: &str) -> String { let chars: Vec = s.chars().collect(); let mut out = String::with_capacity(s.len()); @@ -229,7 +223,6 @@ pub enum Form { /// The contextual form of every character of a logical-order run (`None` for characters that /// don't join: spaces, digits, Latin, marks, ZWNJ). -#[must_use] pub fn joining_forms(chars: &[char]) -> Vec> { let jt: Vec = chars.iter().map(|c| joining_type(*c)).collect(); // Neighbour joining types, skipping transparent marks. @@ -315,7 +308,6 @@ const FORMS_A: &[(u32, u32, u32)] = &[ ]; /// The presentation-form code point of `c` in `form`, when Unicode has one. -#[must_use] pub fn presentation_form(c: char, form: Form) -> Option { let u = u32::from(c); let slot = match form { diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 534fa3b1e..c33799368 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -1,7 +1,7 @@ -//! `CADCraft` text layout. +//! CADCraft text layout. //! //! Turns TEXT and MTEXT into stroke polylines with the built-in single-stroke font -//! ("`CADCraft` Stroke"), the user's SHX shape fonts and big fonts ([`shx`]) or glyph outlines +//! ("CADCraft Stroke"), the user's SHX shape fonts and big fonts ([`shx`]) or glyph outlines //! of installed TrueType fonts ([`ttf`]), with a //! per-character fallback to installed fonts for characters the chosen font lacks. Handles the //! `%%` control codes, alignment modes, width factor, obliquing, MTEXT inline formatting @@ -46,7 +46,6 @@ pub struct Run { /// Replace `%%` control codes: `%%d` degree, `%%p` plus/minus, `%%c` diameter, `%%%` percent, /// `%%nnn` character code, and `\U+XXXX` Unicode escapes. Underline/overline toggles (`%%u`, /// `%%o`) are returned as flags per character. -#[must_use] pub fn decode_controls(text: &str) -> Vec<(char, bool, bool)> { let mut out = Vec::with_capacity(text.len()); let mut under = false; @@ -107,7 +106,6 @@ pub(crate) fn unicode_escape(chars: &[char], i: usize) -> Option { } /// Advance width of one character at height 1 and width factor 1. -#[must_use] pub fn char_advance(c: char) -> f64 { match stroke::glyph(c) { Some((w, _)) => (w + stroke::GAP) / stroke::CAP, @@ -118,7 +116,6 @@ pub fn char_advance(c: char) -> f64 { /// Whether `c` is an East Asian wide character (CJK ideographs and punctuation, kana, Hangul, /// fullwidth forms): drawn in a square cell, like a big font's characters. -#[must_use] pub fn is_wide(c: char) -> bool { matches!(u32::from(c), 0x1100..=0x115F @@ -171,14 +168,12 @@ fn stroke_advance(c: char, h: f64, wf: f64) -> f64 { /// Shape a single line in the stroke font at `height`, with `width_factor` and `oblique` /// (radians). Characters the stroke font lacks are drawn from an installed font that has them /// (glyph outlines, sized like TrueType text), else as a missing-glyph box. -#[must_use] pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Shaped { shape_stroke_dir(s, height, width_factor, oblique, None) } /// [`shape_stroke`] in the direction `base_rtl` (`None`: that of the line's first strong /// character). -#[must_use] pub fn shape_stroke_dir(text: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { let normalized_height = if height.is_finite() && height > 0.0 { height } else { 1.0 }; let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; @@ -285,7 +280,6 @@ fn missing_glyph_box(out: &mut Shaped, x: f64, h: f64, k: f64) { /// Lay out a single line at `height`, with `width_factor` and `oblique` (radians), in the /// stroke font (fallback glyphs become closed outlines). -#[must_use] pub fn layout_line(s: &str, height: f64, width_factor: f64, oblique: f64) -> Run { let sh = shape_stroke(s, height, width_factor, oblique); let mut strokes = sh.strokes; @@ -294,7 +288,6 @@ pub fn layout_line(s: &str, height: f64, width_factor: f64, oblique: f64) -> Run } /// Width of a line without building strokes. -#[must_use] pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { if complex::needed(s) { let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; @@ -314,7 +307,6 @@ pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { /// Width of the gap MTEXT leaves between two words. Words are measured without their trailing /// letter gap, so the stroke font's gap is added on both sides of the space, as TEXT lays it out. -#[must_use] pub fn space_width(font: &TextFont, height: f64, width_factor: f64) -> f64 { if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, " ", height, width_factor) @@ -373,7 +365,6 @@ impl TextFont { } ttf::find(alt_main).map_or(TextFont::Stroke, TextFont::Outline) } - #[must_use] pub fn is_outline(&self) -> bool { matches!(self, TextFont::Outline(_)) } @@ -456,12 +447,10 @@ impl Shaped { self.strokes.extend(other.strokes); self.glyphs.extend(other.glyphs); } - #[must_use] pub fn is_empty(&self) -> bool { self.strokes.is_empty() && self.glyphs.is_empty() } /// All geometry as polylines (outlines become closed polylines). - #[must_use] pub fn outlines(&self) -> Vec> { let mut v = self.strokes.clone(); v.extend(self.glyphs.iter().flatten().cloned()); @@ -499,14 +488,12 @@ pub(crate) fn decorations(spans: &[(f64, f64, bool, bool)], h: f64) -> Vec Shaped { shape_line_dir(font, s, height, width_factor, oblique, None) } /// [`shape_line`] in the direction `base_rtl` (`None`: that of the line's first strong /// character). -#[must_use] pub fn shape_line_dir(font: &TextFont, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { if let TextFont::Outline(face) = font && let Some(sh) = ttf::shape_dir(face, s, height, width_factor, oblique, base_rtl) @@ -524,7 +511,6 @@ pub fn shape_line_dir(font: &TextFont, s: &str, height: f64, width_factor: f64, const TEXT_BASE_RTL: Option = Some(false); /// Width of one line in `font`. -#[must_use] pub fn text_width(font: &TextFont, s: &str, height: f64, width_factor: f64) -> f64 { if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, s, height, width_factor) @@ -579,7 +565,6 @@ pub struct TextParams { } impl TextParams { - #[must_use] pub fn new(insert: Vec2, height: f64) -> Self { TextParams { insert, @@ -595,7 +580,6 @@ impl TextParams { } } /// Centred on `p` both ways (dimension and table text). - #[must_use] pub fn centered(p: Vec2, height: f64, rotation: f64) -> Self { TextParams { align_pt: Some(p), rotation, h: Align::Middle, v: VAlign::Middle, ..TextParams::new(p, height) } } @@ -604,7 +588,6 @@ impl TextParams { /// Where a single-line TEXT's baseline starts (the left end of its first character's baseline), /// in world coordinates: what DXF/DWG store as a justified text's insertion point (group 10), /// computed from its alignment point (group 11) and its width in `font`. -#[must_use] pub fn baseline_start(font: &TextFont, s: &str, p: &TextParams) -> Vec2 { let (origin, local, rot, mirror) = frame(font, s, p); origin + Vec2::new(local.x * mirror.x, local.y * mirror.y).rotate(rot) @@ -668,7 +651,6 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) { /// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its /// bounding box. -#[must_use] pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; let mut wf = p.width_factor; @@ -714,7 +696,6 @@ pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { /// Place a single-line TEXT in world coordinates with the stroke font. Returns strokes and the /// text's bounding box. #[allow(clippy::too_many_arguments)] -#[must_use] pub fn place_text( s: &str, insert: Vec2, diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index c5d38ae3e..06002fedc 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -8,7 +8,6 @@ pub(crate) mod para; /// Strip MTEXT formatting codes to plain text with `\n` paragraph breaks. /// Stacked fractions `\S1/2;` become `1/2`; `\~` is a space; braces are dropped. -#[must_use] pub fn plain_mtext(s: &str) -> String { let s = unescape_codes(s); let s = s.as_ref(); @@ -116,7 +115,6 @@ pub struct MTextParams { } impl MTextParams { - #[must_use] pub fn new(insert: Vec2, height: f64) -> Self { MTextParams { insert, @@ -744,7 +742,6 @@ impl Line { } /// Lay out MTEXT with the stroke font. `attach` 1..=9 (TL, TC, TR, ML, MC, MR, BL, BC, BR). -#[must_use] pub fn layout_mtext(contents: &str, insert: Vec2, height: f64, width: f64, attach: u8, rotation: f64, line_spacing: f64) -> MTextLayout { layout_mtext_with(contents, &MTextParams { insert, height, width, attach, rotation, line_spacing, ..MTextParams::new(insert, height) }) } diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index 158c0ae99..8981fb75d 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -219,7 +219,6 @@ pub enum ListStyle { impl ListStyle { /// The label of item `i` (from 0). - #[must_use] pub fn label(self, i: usize) -> String { let letters = |upper: bool| { // Bijective base 26: a … z, aa, ab … @@ -244,7 +243,6 @@ impl ListStyle { /// Paragraphs as a list: a hanging indent of `indent` drawing units with a tab stop there, and /// each paragraph its label and a tab (`\pxi-3,l3,t3;1.First\P2.Second`). -#[must_use] pub fn list_contents(paragraphs: &[&str], style: ListStyle, indent: f64) -> String { let indent = if indent.is_finite() && indent > 0.0 { indent.min(MAX_UNITS) } else { 3.0 }; let props = ParaProps { first: -indent, left: indent, tabs: vec![(indent, TabKind::Left)], ..ParaProps::default() }; @@ -265,7 +263,6 @@ pub struct Paragraphs { } impl Paragraphs { - #[must_use] pub fn scan(contents: &str) -> Paragraphs { let contents = super::unescape_codes(contents); let chars: Vec = contents.chars().collect(); @@ -329,20 +326,17 @@ impl Paragraphs { } /// Properties of paragraph `k`. - #[must_use] pub fn props(&self, k: usize) -> &ParaProps { let st = self.para.get(k).or(self.para.last()).copied().unwrap_or(0); self.states.get(st).or(self.states.first()).unwrap_or(&DEFAULT_PROPS) } /// The break after paragraph `k` starts a new column. - #[must_use] pub fn column_break(&self, k: usize) -> bool { self.column_break.get(k).copied().unwrap_or(false) } /// Any paragraph formatting at all. - #[must_use] pub fn formatted(&self) -> bool { self.states.len() > 1 || self.column_break.iter().any(|b| *b) } diff --git a/crates/fonts/src/stroke.rs b/crates/fonts/src/stroke.rs index d62689dc7..80512f3f8 100644 --- a/crates/fonts/src/stroke.rs +++ b/crates/fonts/src/stroke.rs @@ -1,4 +1,4 @@ -//! "`CADCraft` Stroke": an original single-stroke drafting font, designed for `CADCraft` on a +//! "CADCraft Stroke": an original single-stroke drafting font, designed for CADCraft on a //! small grid (public domain / CC0 as part of this codebase). //! //! Each glyph is `(width, strokes)`. A stroke is a run of points; each point is two characters: diff --git a/crates/fonts/src/subset.rs b/crates/fonts/src/subset.rs index ebf2b0932..7d41e5195 100644 --- a/crates/fonts/src/subset.rs +++ b/crates/fonts/src/subset.rs @@ -32,7 +32,6 @@ fn u16_at(b: &[u8], i: usize) -> Option { } /// The embedding permission of a face. -#[must_use] pub fn embedding(face: &Face) -> Embedding { let Ok(f) = FontRef::from_index(&face.bytes, face.index) else { return Embedding::NotTrueType }; if table(&f, *b"glyf").is_none() || table(&f, *b"loca").is_none() || table(&f, *b"head").is_none() { diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 60f92da8f..9a4ea1e92 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -58,7 +58,6 @@ impl std::fmt::Debug for Face { impl Face { /// Face `index` of font file `bytes`, if it parses. - #[must_use] pub fn new(bytes: Arc>, index: u32) -> Option { FontRef::from_index(&bytes, index).ok()?; Some(Face { bytes, index }) @@ -81,7 +80,6 @@ impl Face { .is_some_and(|l| l.feature_records().iter().any(|r| tags.contains(&r.feature_tag()))) } /// Whether the face maps `c` to a glyph. - #[must_use] pub fn has_glyph(&self, c: char) -> bool { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } @@ -115,7 +113,6 @@ impl Face { } /// Faces of a font file: every face of a collection (capped), or the single font. -#[must_use] pub fn faces(bytes: &Arc>) -> Vec { match FileRef::new(bytes) { Ok(FileRef::Collection(c)) => (0..c.len().min(MAX_FACES_PER_FILE)).filter_map(|i| Face::new(bytes.clone(), i)).collect(), @@ -852,7 +849,6 @@ fn is_stroke_name(k: &str) -> bool { /// A face of an installed (or registered) font by file name or family name. Stroke-font names /// (".shx", empty) return `None`. -#[must_use] pub fn find(name: &str) -> Option { let k = key(name); if is_stroke_name(&k) { @@ -892,7 +888,6 @@ fn split_list(s: &str) -> Vec { /// FONTALT: the font used for a text style font that can't be found. Empty = the built-in /// stroke font. -#[must_use] pub fn font_alt() -> String { prefs().alt.clone() } @@ -903,7 +898,6 @@ pub fn set_font_alt(name: &str) { } /// FONTFALLBACK: fonts tried first for characters a text's font lacks, comma-separated. -#[must_use] pub fn fallback_fonts() -> String { prefs().fallback.join(", ") } @@ -921,7 +915,6 @@ fn wants_fallback(c: char) -> bool { /// A face that has `c`, for text whose own font lacks it: FONTFALLBACK fonts, then FONTALT, /// then installed fonts (wide-coverage CJK fonts first). Bounded and cached. -#[must_use] pub fn fallback_for(c: char) -> Option { if !wants_fallback(c) { return None; @@ -1073,7 +1066,6 @@ impl OutlinePen for Pen { /// How far below the baseline a face reaches, as a fraction of the text height (which is the /// face's cap height): its descent over its cap height. A bottom-justified text's alignment /// point is there, as `AutoCAD` places it (#2229). `None` when the face has no usable descent. -#[must_use] pub fn descent_ratio(face: &Face) -> Option { let f = face.font()?; let descent = -f64::from(f.metrics(Size::new(UPEM), LocationRef::default()).descent); @@ -1108,7 +1100,6 @@ pub(crate) fn glyph_by_id(face: &Face, gid: u32) -> Arc { /// Closed, flattened contours of a glyph at 1000 font units per em. Shared with the outline /// cache so renderers can tessellate once before applying each occurrence's affine placement. -#[must_use] pub fn glyph_contours(face: &Face, gid: u16) -> Arc<[Vec]> { glyph_by_id(face, u32::from(gid)).contours.clone() } @@ -1216,13 +1207,11 @@ pub(crate) fn place_glyph_at(g: &GlyphOutline, origin: Vec2, scale: f64, wf: f64 /// Shape one line with a TrueType face: closed glyph contours grouped per glyph (baseline at /// y = 0, x from 0) plus `%%u`/`%%o` decorations as strokes. Text height = cap height. /// Characters the face lacks come from a fallback font, scaled to its own cap height. -#[must_use] pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option { shape_dir(face, s, height, width_factor, oblique, None) } /// [`shape`] in the direction `base_rtl` (`None`: that of the line's first strong character). -#[must_use] pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Option { face.font()?; // As in [`crate::shape_stroke_dir`]: a line asked to run right to left takes the bidi path. @@ -1262,7 +1251,6 @@ pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique: } /// Width of one line set in a TrueType face. -#[must_use] pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option { face.font()?; if crate::complex::needed(s) @@ -1284,7 +1272,6 @@ pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option Option { let sh = shape(face, s, height, width_factor, oblique)?; let mut strokes: Vec> = sh.glyphs.into_iter().flatten().collect(); From 6749299b950df40af9dd997ef6fc43337f571861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Tue, 3 Nov 2026 16:18:00 +0100 Subject: [PATCH 09/24] fix(fonts): preserve SHX suffix handling for path-prefixed names --- crates/fonts/src/ttf.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 9a4ea1e92..363eb4cfc 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -839,7 +839,7 @@ fn key(name: &str) -> String { /// Names that mean a stroke font: never looked up as TrueType. fn is_stroke_name(k: &str) -> bool { k.is_empty() - || k == ".shx" + || k.ends_with(".shx") || std::path::Path::new(k).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("shx")) || k == crate::BUILTIN_FONT.to_ascii_lowercase() || k == "txt" @@ -1402,7 +1402,7 @@ mod family_tests { #[test] fn dotfile_shx_names_are_stroke_names() { - for name in [".shx", ".shx.ttf", ".SHX", ".SHX.TTF"] { + for name in [".shx", ".shx.ttf", ".SHX", ".SHX.TTF", "sub/.shx", "sub/.SHX"] { assert!(is_stroke_name(&key(name)), "{name}"); } } From caaa0e37f77d4cb67fb8430aa0a946ac45ac6395 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:20:04 +0000 Subject: [PATCH 10/24] Use shared raster image codecs --- ATTRIBUTION.md | 1 + Cargo.lock | 175 +++++++++++++++++ Cargo.toml | 1 + NOTICE | 126 +++++++++++- crates/io/Cargo.toml | 3 +- crates/io/src/raster.rs | 84 ++++---- crates/io/tests/raster_decode.rs | 7 + licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt | 72 +++++++ licenses/jpeg-encoder-0.6.1/LICENSE-APACHE | 201 ++++++++++++++++++++ licenses/jpeg-encoder-0.6.1/LICENSE-MIT | 25 +++ licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt | 8 + licenses/jpeg-encoder-0.6.1/SOURCE.json | 29 +++ 12 files changed, 687 insertions(+), 45 deletions(-) create mode 100644 licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt create mode 100644 licenses/jpeg-encoder-0.6.1/LICENSE-APACHE create mode 100644 licenses/jpeg-encoder-0.6.1/LICENSE-MIT create mode 100644 licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt create mode 100644 licenses/jpeg-encoder-0.6.1/SOURCE.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a8524be64..cabf50d94 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,6 +23,7 @@ Generated-in-code assets are original and have no file to list: | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| +| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. | | `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. | | `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. | | `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. | diff --git a/Cargo.lock b/Cargo.lock index 41e541936..ee4349bb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,6 +156,21 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -513,6 +528,12 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -568,6 +589,16 @@ dependencies = [ "piper", ] +[[package]] +name = "brotli-decompressor" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -740,6 +771,7 @@ dependencies = [ "cadcraft-render", "craft-dwg", "craft-dxf", + "craft-image-codecs", "craft-pdf", "image", "miniz_oxide 0.9.1", @@ -1183,6 +1215,51 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +dependencies = [ + "craft-jpeg", + "craft-metadata", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +dependencies = [ + "brotli-decompressor", + "chrono", + "craft-tiff", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -1193,6 +1270,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1761,6 +1847,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -2265,6 +2367,9 @@ name = "hayro-jpeg2000" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] [[package]] name = "hayro-syntax" @@ -2567,9 +2672,12 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", "moxcms", "num-traits", "png", + "qoi", "tiff", "zune-core", "zune-jpeg", @@ -2709,6 +2817,12 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-encoder" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" + [[package]] name = "js-sys" version = "0.3.106" @@ -2801,6 +2915,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -2993,6 +3113,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -3861,6 +4003,15 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "2.0.1" @@ -4658,6 +4809,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -6250,6 +6407,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" @@ -6259,6 +6425,15 @@ dependencies = [ "zune-core", ] +[[package]] +name = "zune-jpegxl" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "5.15.1" diff --git a/Cargo.toml b/Cargo.toml index b22766049..39345df8a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "373d36ea3f66be15b826c861681147e32314b875" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } cadcraft-constraints = { path = "crates/constraints" } diff --git a/NOTICE b/NOTICE index 2eb24b221..f3ecf5fc1 100644 --- a/NOTICE +++ b/NOTICE @@ -11,7 +11,7 @@ Third-party material Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the -Mozilla Public License 2.0 and is used unmodified as a separate library (crates/dwg). Its source +Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source is available from crates.io and the repository above. @@ -48,3 +48,127 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root +(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1). +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 44f22cd5e..cca1841f6 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -14,6 +14,7 @@ cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } craft-dxf = { workspace = true } craft-dwg = { workspace = true } +craft-image-codecs = { workspace = true } cadcraft-render = { workspace = true } cadcraft-fonts = { workspace = true } thiserror = { workspace = true } @@ -22,9 +23,9 @@ serde = { workspace = true } miniz_oxide = "0.9" craft-pdf = { workspace = true, features = ["write"] } quick-xml = { workspace = true } -image = { workspace = true } [dev-dependencies] +image = { workspace = true } tiny-skia = { workspace = true } # Reads plotted PDFs back. craft-pdf = { workspace = true, features = ["read"] } diff --git a/crates/io/src/raster.rs b/crates/io/src/raster.rs index 3e09ef9c9..92afeb4f6 100644 --- a/crates/io/src/raster.rs +++ b/crates/io/src/raster.rs @@ -2,11 +2,9 @@ //! from the content. Files are hostile input: the size is read from the header and checked //! before any pixel is decoded. -use std::io::Cursor; - -use cadcraft_doc::Raster; - use crate::{IoError, Result}; +use cadcraft_doc::Raster; +use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType}; /// Largest image file read (bytes). pub const MAX_IMAGE_BYTES: usize = 256 << 20; @@ -17,22 +15,18 @@ fn bad(e: impl std::fmt::Display) -> IoError { IoError::Format(format!("image: {e}")) } -/// A reader over an image file, once it is small enough and of a format we read. -fn reader(bytes: &[u8]) -> Result>> { +/// The width and height in pixels of the first stored image, read without decoding pixels. +pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { if bytes.len() > MAX_IMAGE_BYTES { return Err(bad(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20))); } - // The format comes from the file's first bytes, not from its name. - let file = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(bad)?; - if file.format().is_none() { + let format = craft_image_codecs::detect(bytes).ok_or_else(|| bad("not a PNG, JPEG, BMP or TIFF file"))?; + if !matches!(format, Format::Png | Format::Jpeg | Format::Bmp | Format::Tiff) { return Err(bad("not a PNG, JPEG, BMP or TIFF file")); } - Ok(file) -} - -/// The width and height in pixels of the image in `bytes`, read from its header. -pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { - let (width, height) = reader(bytes)?.into_dimensions().map_err(bad)?; + // Match ImageReader's original header budget; check pixels ourselves for the existing diagnostic. + let limits = Limits::new(u32::MAX, u32::MAX, u64::MAX, 512 << 20); + let (width, height) = craft_image_codecs::probe_stored_size(bytes, &limits).map_err(bad)?; if width == 0 || height == 0 { return Err(bad("the image is empty")); } @@ -42,38 +36,42 @@ pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { Ok((width, height)) } -/// Decode the image in `bytes`. +/// Decode the first image, keeping its stored orientation. pub fn decode(bytes: &[u8]) -> Result { - // The size is checked first, from the header alone. let (width, height) = probe(bytes)?; - let mut file = reader(bytes)?; - file.limits(decode_limits(width, height)); - let pixels = file.decode().map_err(bad)?.into_rgba8(); - Raster::new(pixels.width(), pixels.height(), pixels.into_raw()).ok_or_else(|| bad("the image is empty")) -} - -/// What the decoder may allocate for an image of this size: the pixels themselves (up to 16 -/// bytes each before they become 8-bit RGBA) and its own working buffers. -fn decode_limits(width: u32, height: u32) -> image::Limits { let pixels = u64::from(width).saturating_mul(u64::from(height)); - let mut limits = image::Limits::default(); - limits.max_image_width = Some(width); - limits.max_image_height = Some(height); - limits.max_alloc = Some(pixels.saturating_mul(16).saturating_add(64 << 20)); - limits + let limits = Limits::new(width, height, MAX_IMAGE_PIXELS, pixels.saturating_mul(16).saturating_add(64 << 20)); + let opts = DecodeOptions { limits, keep_orientation: true }; + let format = craft_image_codecs::detect(bytes).ok_or_else(|| bad("not an image"))?; + let image = if format == Format::Tiff { + craft_image_codecs::decode_tiff_page(bytes, 0, &opts) + } else { + craft_image_codecs::decode_as_with(format, bytes, &opts) + } + .map_err(bad)?; + if image.warnings.iter().any(|w| matches!(w, DecodeWarning::Truncated { .. })) { + return Err(bad("image data is truncated")); + } + if image.dimensions() != (width, height) { + return Err(bad("decoded image size does not match its header")); + } + let rgba = if image.layout() == ChannelLayout::Rgba && image.sample_type() == SampleType::U8 { image.into_data() } else { image.to_rgba8() }; + Raster::new(width, height, rgba).ok_or_else(|| bad("the image is empty")) } -/// `raster` as a PNG file. +/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy. pub fn encode_png(raster: &Raster) -> Result> { - let mut out = Cursor::new(Vec::new()); - image::write_buffer_with_format( - &mut out, - raster.rgba(), - raster.width(), - raster.height(), - image::ExtendedColorType::Rgba8, - image::ImageFormat::Png, - ) - .map_err(bad)?; - Ok(out.into_inner()) + let stride = usize::try_from(raster.width()).ok().and_then(|w| w.checked_mul(4)).filter(|s| *s > 0).ok_or_else(|| bad("invalid image width"))?; + let mut chunks = raster.rgba().chunks_exact(stride); + let first = chunks.next().ok_or_else(|| bad("the image is empty"))?; + let row = |data: &[u8]| Image::from_u8(raster.width(), 1, ChannelLayout::Rgba, data.to_vec()).map_err(bad); + let first = row(first)?; + let mut out = Vec::new(); + let mut writer = PngRows::new(&mut out, &first, raster.height(), &EncodeOptions::default()).map_err(bad)?; + writer.push(&first).map_err(bad)?; + for chunk in chunks { + writer.push(&row(chunk)?).map_err(bad)?; + } + writer.finish().map_err(bad)?; + Ok(out) } diff --git a/crates/io/tests/raster_decode.rs b/crates/io/tests/raster_decode.rs index 51a6130b7..9dfd2c970 100644 --- a/crates/io/tests/raster_decode.rs +++ b/crates/io/tests/raster_decode.rs @@ -170,3 +170,10 @@ fn the_pixels_never_reach_the_drawing_file() { assert!(bare.rasters.is_empty() && d.rasters.len() == 1); assert_eq!(bare, d); } + +#[test] +fn long_narrow_bmp_uses_cadcrafts_pixel_limit() { + let mut file = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut file, &vec![0; 300_000 * 3], 1, 300_000, image::ExtendedColorType::Rgb8, image::ImageFormat::Bmp).unwrap(); + assert_eq!(probe(&file.into_inner()).unwrap(), (1, 300_000)); +} diff --git a/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt new file mode 100644 index 000000000..4fcb9b583 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt @@ -0,0 +1,72 @@ +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE new file mode 100644 index 000000000..dae696981 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-MIT b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT new file mode 100644 index 000000000..6a4eb8746 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt new file mode 100644 index 000000000..58e09bf43 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt @@ -0,0 +1,8 @@ +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/licenses/jpeg-encoder-0.6.1/SOURCE.json b/licenses/jpeg-encoder-0.6.1/SOURCE.json new file mode 100644 index 000000000..8a7fb7ab2 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SOURCE.json @@ -0,0 +1,29 @@ +{ + "package": "jpeg-encoder", + "version": "0.6.1", + "source": "https://crates.io/crates/jpeg-encoder/0.6.1", + "registry_checksum": "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f", + "license": "(MIT OR Apache-2.0) AND IJG", + "files": { + "LICENSE-MIT": { + "source": "LICENSE-MIT", + "source_sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503", + "sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503" + }, + "LICENSE-APACHE": { + "source": "LICENSE-APACHE", + "source_sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0", + "sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0" + }, + "IJG-NOTICE.txt": { + "source": "src/fdct.rs", + "source_sha256": "0b59244bbd05b2593ded252ecf0d010a8a4c6ec1d4713b3caeb6fb724586e4d6", + "sha256": "432424ca69caaa82565c0491c11cdab311a2e7d39180970b8ba22017996bf678" + }, + "SIMD-NOTICE.txt": { + "source": "src/avx2/fdct.rs", + "source_sha256": "bc362322f568f92c3699f4ca2922b261c12b7dd997120b01fd3cab58d9d2f9ab", + "sha256": "ee36eeaa9df1f7f09c7046f428ce4a848fcf518394e63d3e2125ec261949e8ba" + } + } +} From 281f86d602bb95df88ec7a8491901f85920c23a5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:22:04 +0000 Subject: [PATCH 11/24] Encode rendered PNGs through shared codecs --- Cargo.lock | 1 + crates/io/src/plotter.rs | 2 +- crates/render/Cargo.toml | 1 + crates/render/src/raster.rs | 28 +++++++++++++++++++++++++++- crates/render/tests/png_parity.rs | 10 ++++++++++ 5 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 crates/render/tests/png_parity.rs diff --git a/Cargo.lock b/Cargo.lock index ee4349bb2..5ed48bfc0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -805,6 +805,7 @@ dependencies = [ "cadcraft-doc", "cadcraft-fonts", "cadcraft-geom", + "craft-image-codecs", "lyon_tessellation", "rayon", "serde_json", diff --git a/crates/io/src/plotter.rs b/crates/io/src/plotter.rs index f0a174ea1..07984c798 100644 --- a/crates/io/src/plotter.rs +++ b/crates/io/src/plotter.rs @@ -116,7 +116,7 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { // PDF clips a placed plot to the printable area: blank the rest of the sheet. raster::blank_outside_printable(&mut pm, &sheet.printable, k); } - pm.encode_png().map_err(|_| IoError::Format("render failed".into())) + raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into())) } fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result> { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index d62af23b9..44d5b48da 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -12,6 +12,7 @@ workspace = true cadcraft-geom = { workspace = true } cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } +craft-image-codecs = { workspace = true } cadcraft-fonts = { workspace = true } tiny-skia = { workspace = true } lyon_tessellation = { workspace = true } diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 8c9205a14..9149d6f02 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -354,7 +354,33 @@ fn premultiplied(r: &cadcraft_doc::Raster) -> Option { Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?) } +/// Encode a premultiplied pixmap as PNG without a second full-frame copy. +pub fn encode_png(pixmap: &Pixmap) -> Option> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows}; + let width = usize::try_from(pixmap.width()).ok()?.max(1); + let mut rows = pixmap.pixels().chunks_exact(width); + let make_row = |row: &[tiny_skia::PremultipliedColorU8]| { + let rgba = row + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + Image::from_u8(pixmap.width(), 1, ChannelLayout::Rgba, rgba).ok() + }; + let first = make_row(rows.next()?)?; + let mut out = Vec::new(); + let mut encoder = PngRows::new(&mut out, &first, pixmap.height(), &EncodeOptions::default()).ok()?; + encoder.push(&first).ok()?; + for row in rows { + encoder.push(&make_row(row)?).ok()?; + } + encoder.finish().ok()?; + Some(out) +} + /// Render and encode as PNG. pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option> { - render(list, view, o)?.encode_png().ok() + encode_png(&render(list, view, o)?) } diff --git a/crates/render/tests/png_parity.rs b/crates/render/tests/png_parity.rs new file mode 100644 index 000000000..ca53f6419 --- /dev/null +++ b/crates/render/tests/png_parity.rs @@ -0,0 +1,10 @@ +//! The shared PNG writer preserves tiny-skia's straight-alpha export pixels. +#[test] +fn shared_png_matches_tiny_skia_for_premultiplied_pixels() { + let pixmap = + tiny_skia::Pixmap::from_vec(vec![0, 0, 0, 0, 32, 64, 96, 128, 1, 2, 3, 4, 255, 63, 9, 255], tiny_skia::IntSize::from_wh(4, 1).unwrap()) + .unwrap(); + let expected = tiny_skia::Pixmap::decode_png(&pixmap.encode_png().unwrap()).unwrap(); + let actual = tiny_skia::Pixmap::decode_png(&cadcraft_render::raster::encode_png(&pixmap).unwrap()).unwrap(); + assert_eq!(actual.data(), expected.data()); +} From 58a13b5a64d53c8c6feccf2b893d85358ce81e05 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:24:39 +0000 Subject: [PATCH 12/24] Update raster probe and use supported BMP dimensions --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- crates/io/tests/raster_decode.rs | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ed48bfc0..a7f3c7adb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1219,7 +1219,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" dependencies = [ "craft-jpeg", "craft-metadata", @@ -1244,7 +1244,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" dependencies = [ "thiserror 2.0.21", ] @@ -1252,7 +1252,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" dependencies = [ "brotli-decompressor", "chrono", @@ -1274,7 +1274,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=373d36ea3f66be15b826c861681147e32314b875#373d36ea3f66be15b826c861681147e32314b875" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" dependencies = [ "serde", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 39345df8a..1e7546dd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "373d36ea3f66be15b826c861681147e32314b875" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } cadcraft-constraints = { path = "crates/constraints" } diff --git a/crates/io/tests/raster_decode.rs b/crates/io/tests/raster_decode.rs index 9dfd2c970..7eff1a378 100644 --- a/crates/io/tests/raster_decode.rs +++ b/crates/io/tests/raster_decode.rs @@ -174,6 +174,6 @@ fn the_pixels_never_reach_the_drawing_file() { #[test] fn long_narrow_bmp_uses_cadcrafts_pixel_limit() { let mut file = std::io::Cursor::new(Vec::new()); - image::write_buffer_with_format(&mut file, &vec![0; 300_000 * 3], 1, 300_000, image::ExtendedColorType::Rgb8, image::ImageFormat::Bmp).unwrap(); - assert_eq!(probe(&file.into_inner()).unwrap(), (1, 300_000)); + image::write_buffer_with_format(&mut file, &vec![0; 60_000 * 3], 1, 60_000, image::ExtendedColorType::Rgb8, image::ImageFormat::Bmp).unwrap(); + assert_eq!(probe(&file.into_inner()).unwrap(), (1, 60_000)); } From 8a4e27546652334e04a03579cec6492ebb17085d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:30:38 +0000 Subject: [PATCH 13/24] Route MCP protocol through shared libraries --- Cargo.lock | 19 +++++++++ Cargo.toml | 2 + crates/mcp/Cargo.toml | 2 + crates/mcp/src/server.rs | 85 +++++++++++++++++----------------------- crates/mcp/src/tests.rs | 21 ++++++++++ 5 files changed, 81 insertions(+), 48 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 41e541936..6985344a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,6 +758,8 @@ dependencies = [ "cadcraft-io", "cadcraft-render", "clap", + "craft-jsonrpc", + "craft-mcp", "getrandom 0.4.3", "libc", "log", @@ -1183,6 +1185,23 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-jsonrpc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2c9903ca1d892b5446acf3598d8b142f3e64842f#2c9903ca1d892b5446acf3598d8b142f3e64842f" +dependencies = [ + "serde_json", +] + +[[package]] +name = "craft-mcp" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2c9903ca1d892b5446acf3598d8b142f3e64842f#2c9903ca1d892b5446acf3598d8b142f3e64842f" +dependencies = [ + "craft-jsonrpc", + "serde_json", +] + [[package]] name = "craft-pdf" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index b22766049..c964a8769 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,8 @@ cadcraft-io = { path = "crates/io" } cadcraft-engine = { path = "crates/engine" } cadcraft-ui-egui = { path = "crates/ui-egui" } cadcraft-mcp = { path = "crates/mcp" } +craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "2c9903ca1d892b5446acf3598d8b142f3e64842f" } +craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "2c9903ca1d892b5446acf3598d8b142f3e64842f" } # Which paths stored in a drawing (xrefs, data links) may be opened. craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } # PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index cb597504f..089e36d38 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -9,6 +9,8 @@ license.workspace = true workspace = true [dependencies] +craft-mcp = { workspace = true } +craft-jsonrpc = { workspace = true } cadcraft-engine = { workspace = true } cadcraft-render = { workspace = true } cadcraft-io = { workspace = true } diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index ba6627c62..6c5fb7281 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -22,25 +22,24 @@ Verify with inspect_drawing / query_entities and look with render."; pub struct Server { backend: Box, - initialized: bool, -} - -fn response(id: Value, result: Value) -> Value { - json!({"jsonrpc": "2.0", "id": id, "result": result}) -} -fn error(id: Value, code: i64, message: impl Into) -> Value { - json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) + session: craft_mcp::Session, } impl Server { pub fn new(backend: Box) -> Self { - Self { backend, initialized: false } + Self { + backend, + session: craft_mcp::Session::new("cadcraft", env!("CARGO_PKG_VERSION"), craft_mcp::Policy::Compatible) + .with_capabilities(json!({"tools": {"listChanged": false}, "resources": {"listChanged": false}})) + .unwrap_or_else(|_| craft_mcp::Session::new("cadcraft", env!("CARGO_PKG_VERSION"), craft_mcp::Policy::Compatible)) + .with_legacy_initialize(SUPPORTED, json!({"name": "cadcraft", "title": "CADCraft", "version": env!("CARGO_PKG_VERSION")})), + } } pub fn backend(&mut self) -> &mut dyn Backend { self.backend.as_mut() } pub fn is_initialized(&self) -> bool { - self.initialized + self.session.is_initialized() } /// Serve newline-delimited JSON-RPC until `input` closes (logs to stderr only). @@ -62,53 +61,43 @@ impl Server { return None; } let reply = match serde_json::from_str::(line) { - // JSON-RPC 2.0: an empty batch is one Invalid Request, not silence. - Ok(Value::Array(batch)) if batch.is_empty() => Some(error(Value::Null, INVALID_REQUEST, "empty batch")), - Ok(Value::Array(batch)) => { - let replies: Vec = batch.into_iter().filter_map(|m| self.handle(m)).collect(); - (!replies.is_empty()).then_some(Value::Array(replies)) - } - Ok(msg) => self.handle(msg), - Err(e) => Some(error(Value::Null, PARSE_ERROR, format!("parse error: {e}"))), + Ok(msg) => self.handle_message(&msg), + Err(e) => Some(craft_jsonrpc::error_response(Value::Null, craft_jsonrpc::RpcError::new(PARSE_ERROR, format!("parse error: {e}")))), }; reply.map(|r| r.to_string()) } pub fn handle(&mut self, msg: Value) -> Option { - let Value::Object(o) = &msg else { return Some(error(Value::Null, INVALID_REQUEST, "message must be an object")) }; - let id = o.get("id").cloned(); - let Some(method) = o.get("method").and_then(Value::as_str) else { - if o.contains_key("result") || o.contains_key("error") { - return None; - } - return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); - }; - let params = o.get("params").cloned().unwrap_or(Value::Null); - let Some(id) = id else { - if method == "notifications/initialized" { - self.initialized = true; - } - return None; - }; - Some(match self.request(method, ¶ms) { - Ok(r) => response(id, r), - Err((code, m)) => error(id, code, m), - }) + // `handle` historically routes only one envelope; batches belong to `handle_line`. + if msg.is_array() { + return Some(craft_jsonrpc::error_response(Value::Null, craft_jsonrpc::RpcError::new(INVALID_REQUEST, "message must be an object"))); + } + self.handle_message(&msg) + } + + fn handle_message(&mut self, msg: &Value) -> Option { + let server = std::cell::RefCell::new(self); + craft_jsonrpc::process_legacy( + msg, + |request| { + let mut server = server.borrow_mut(); + if request.method == "initialize" { + let instructions = format!("{INSTRUCTIONS} Backend: {}.", server.backend.describe()); + server.session.set_instructions(instructions); + } + if let Some(result) = server.session.request(request, msg.is_array()) { + return result; + } + server + .request(request.method, request.params.unwrap_or(&Value::Null)) + .map_err(|(code, message)| craft_jsonrpc::RpcError::new(code, message)) + }, + |request| server.borrow_mut().session.notification(request), + ) } fn request(&mut self, method: &str, params: &Value) -> Result { match method { - "initialize" => { - let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION); - let version = if SUPPORTED.contains(&asked) { asked } else { PROTOCOL_VERSION }; - Ok(json!({ - "protocolVersion": version, - "capabilities": {"tools": {"listChanged": false}, "resources": {"listChanged": false}}, - "serverInfo": {"name": "cadcraft", "title": "CADCraft", "version": env!("CARGO_PKG_VERSION")}, - "instructions": format!("{INSTRUCTIONS} Backend: {}.", self.backend.describe()), - })) - } - "ping" => Ok(json!({})), "tools/list" => Ok(tool_definitions(self.backend.has_ui())), "tools/call" => { let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index b7eee854e..44ab4eff2 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -391,3 +391,24 @@ fn render_refuses_unknown_backgrounds_and_plot_styles() { assert!(crate::Backend::call(&mut h, "ui.render", json!({"background": "purple"})).is_err()); assert!(crate::Backend::call(&mut h, "ui.render", json!({"plot_style": 3})).is_err()); } + +#[test] +fn legacy_protocol_routing_and_version_negotiation() { + let mut s = Server::new(Box::new(Headless::default())); + assert!(s.handle_line(r#"{"method":"notifications/initialized"}"#).is_none()); + assert!(s.is_initialized()); + for (params, expected) in + [(json!(null), "2025-06-18"), (json!({"protocolVersion":"2024-11-05"}), "2024-11-05"), (json!({"protocolVersion":"other"}), "2025-06-18")] + { + let response = call(&mut s, 1, "initialize", params); + assert_eq!(response["result"]["protocolVersion"], expected); + assert_eq!(response["result"]["serverInfo"]["title"], "CADCraft"); + assert!(response["result"]["instructions"].as_str().unwrap().contains("Backend:")); + } + let response: Value = + serde_json::from_str(&s.handle_line(r#"[{"id":[1],"method":"ping","params":5},{"method":"ignored"},{"result":1},{}]"#).unwrap()).unwrap(); + assert_eq!( + response, + json!([{"jsonrpc":"2.0","id":[1],"result":{}},{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"missing `method`"}}]) + ); +} From 072ec4500aebacfb1ebaa8037f0ebb8c6459d9c5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:32:54 +0000 Subject: [PATCH 14/24] Use shared codecs for preview and screenshots --- Cargo.lock | 1 + crates/io/src/raster.rs | 14 ++-------- crates/render/src/raster.rs | 19 ++++++++++++++ crates/ui-egui/Cargo.toml | 4 +-- crates/ui-egui/src/control.rs | 48 +++++++++++++++++++++++++++++++--- crates/ui-egui/src/exchange.rs | 27 ++++++++++++++----- 6 files changed, 90 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a7f3c7adb..4c4c470e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -824,6 +824,7 @@ dependencies = [ "cadcraft-io", "cadcraft-render", "chrono", + "craft-image-codecs", "craft-ui", "craft-update", "craft-window", diff --git a/crates/io/src/raster.rs b/crates/io/src/raster.rs index 92afeb4f6..0d7e19b2d 100644 --- a/crates/io/src/raster.rs +++ b/crates/io/src/raster.rs @@ -4,7 +4,7 @@ use crate::{IoError, Result}; use cadcraft_doc::Raster; -use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType}; +use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType}; /// Largest image file read (bytes). pub const MAX_IMAGE_BYTES: usize = 256 << 20; @@ -61,17 +61,7 @@ pub fn decode(bytes: &[u8]) -> Result { /// `raster` as a PNG file, encoded in rows to avoid a full extra image copy. pub fn encode_png(raster: &Raster) -> Result> { - let stride = usize::try_from(raster.width()).ok().and_then(|w| w.checked_mul(4)).filter(|s| *s > 0).ok_or_else(|| bad("invalid image width"))?; - let mut chunks = raster.rgba().chunks_exact(stride); - let first = chunks.next().ok_or_else(|| bad("the image is empty"))?; - let row = |data: &[u8]| Image::from_u8(raster.width(), 1, ChannelLayout::Rgba, data.to_vec()).map_err(bad); - let first = row(first)?; let mut out = Vec::new(); - let mut writer = PngRows::new(&mut out, &first, raster.height(), &EncodeOptions::default()).map_err(bad)?; - writer.push(&first).map_err(bad)?; - for chunk in chunks { - writer.push(&row(chunk)?).map_err(bad)?; - } - writer.finish().map_err(bad)?; + cadcraft_render::raster::write_rgba_png(&mut out, raster.width(), raster.height(), raster.rgba()).ok_or_else(|| bad("PNG encoding failed"))?; Ok(out) } diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 9149d6f02..fb734cb34 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -354,6 +354,25 @@ fn premultiplied(r: &cadcraft_doc::Raster) -> Option { Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?) } +/// Write straight-alpha RGBA8 pixels as PNG a row at a time. +pub fn write_rgba_png(mut output: impl std::io::Write, width: u32, height: u32, pixels: &[u8]) -> Option<()> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows}; + let stride = usize::try_from(width).ok()?.checked_mul(4).filter(|n| *n > 0)?; + let expected = stride.checked_mul(usize::try_from(height).ok()?)?; + if height == 0 || pixels.len() != expected { + return None; + } + let mut rows = pixels.chunks_exact(stride); + let row = |data: &[u8]| Image::from_u8(width, 1, ChannelLayout::Rgba, data.to_vec()).ok(); + let first = row(rows.next()?)?; + let mut encoder = PngRows::new(&mut output, &first, height, &EncodeOptions::default()).ok()?; + encoder.push(&first).ok()?; + for data in rows { + encoder.push(&row(data)?).ok()?; + } + encoder.finish().ok() +} + /// Encode a premultiplied pixmap as PNG without a second full-frame copy. pub fn encode_png(pixmap: &Pixmap) -> Option> { use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 034bb1d4d..b9d16801c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -16,6 +16,8 @@ cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } cadcraft-render = { workspace = true } cadcraft-engine = { workspace = true } +cadcraft-io = { workspace = true } +craft-image-codecs = { workspace = true } cadcraft-fonts = { workspace = true } craft-window = { workspace = true } egui = { workspace = true } @@ -40,8 +42,6 @@ craft-ui = { workspace = true, features = ["native-windows"] } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } # Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses). naga = { version = "30", features = ["wgsl-in", "glsl-out"] } -# Reads the synthetic dynamic-block fixture of the io tests for the dynamic grips tests. -cadcraft-io = { workspace = true } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 55e2da3f6..be605c876 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -691,6 +691,29 @@ impl Drop for PathlessShots { } } +fn write_screenshot_png(img: &image::RgbaImage, output: impl std::io::Write) -> std::io::Result<()> { + cadcraft_render::raster::write_rgba_png(output, img.width(), img.height(), img.as_raw()) + .ok_or_else(|| std::io::Error::other("PNG encoding failed")) +} + +fn save_explicit_screenshot(img: &image::RgbaImage, path: &str) -> std::io::Result<()> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image}; + let format = match image::ImageFormat::from_path(path).map_err(std::io::Error::other)? { + image::ImageFormat::Png => Format::Png, + image::ImageFormat::Jpeg => Format::Jpeg, + image::ImageFormat::Bmp => Format::Bmp, + image::ImageFormat::Tiff => Format::Tiff, + _ => return Err(std::io::Error::other("unsupported screenshot format")), + }; + if format == Format::Png { + return write_screenshot_png(img, std::fs::File::create(path)?); + } + let pixels = Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, img.as_raw().clone()).map_err(std::io::Error::other)?; + let opts = EncodeOptions { jpeg_quality: 75, jpeg_chroma_subsampling: false, ..EncodeOptions::default() }; + let bytes = craft_image_codecs::encode(&pixels, format, &opts).map_err(std::io::Error::other)?; + std::fs::write(path, bytes) +} + /// Save a pathless screenshot into the private per-process directory: re-validate or recreate it as an owner-only real directory (0700 on Unix; plain create elsewhere), then create up to 64 exclusive files (0600 on Unix) and write a PNG. fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result { use std::io::Write as _; @@ -713,7 +736,7 @@ fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Resu let path = dir.join(format!("cadcraft-shot-{token}-{}.png", next_pathless_nonce())); match create_private_file(&path) { Ok(mut file) => { - let written = img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other).and_then(|()| file.flush()); + let written = write_screenshot_png(img, &mut file).and_then(|()| file.flush()); if let Err(e) = written { // The reply carries no path on failure, so nobody else could remove the partial file. drop(file); @@ -752,7 +775,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) return inline_screenshot(&img, token); } let saved = match path { - Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other), + Some(path) => save_explicit_screenshot(&img, path).map(|()| path.to_string()), None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()), }; match saved { @@ -766,7 +789,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value { let (w, h) = img.dimensions(); let mut png = Vec::new(); - if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) { + if let Err(e) = write_screenshot_png(img, &mut png) { return json!({"ok": false, "error": e.to_string(), "request": token}); } json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}}) @@ -776,6 +799,25 @@ fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value { mod tests { use super::*; + #[test] + fn explicit_screenshot_retains_supported_file_formats() { + let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 128])); + for ext in ["png", "bmp", "tiff", "jpg"] { + let path = std::env::temp_dir().join(format!("cadcraft-format-{}-{}.{}", std::process::id(), next_pathless_nonce(), ext)); + let name = path.to_string_lossy().to_string(); + save_explicit_screenshot(&img, &name).unwrap(); + let decoded = image::open(&path).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), img.dimensions(), "{ext}"); + if ext != "jpg" { + let mut original = std::io::Cursor::new(Vec::new()); + img.write_to(&mut original, image::ImageFormat::from_path(&path).unwrap()).unwrap(); + let original = image::load_from_memory(&original.into_inner()).unwrap().to_rgba8(); + assert_eq!(decoded.as_raw(), original.as_raw(), "{ext}"); + } + std::fs::remove_file(path).unwrap(); + } + } + #[test] fn an_inline_screenshot_carries_the_png_and_its_size() { let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255])); diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index b7a0246c6..153bbf925 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -70,16 +70,12 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin if let Some(f) = ctx.data(|d| d.get_temp::(egui::Id::unique(FROM_PLOT))) { let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?; let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); - let size = [img.width() as usize, img.height() as usize]; - let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR); + let tex = preview_texture(ctx, &png)?; return Ok((tex, f.info)); } let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?; let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); - let size = [img.width() as usize, img.height() as usize]; - let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR); + let tex = preview_texture(ctx, &png)?; let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or("")); if r["landscape"].as_bool() == Some(true) { info.push_str(" · landscape"); @@ -87,6 +83,15 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin Ok((tex, info)) } +fn preview_texture(ctx: &egui::Context, png: &[u8]) -> Result { + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return Err("the preview is not a PNG".into()); + } + let img = cadcraft_io::raster::decode(png).map_err(|e| e.to_string())?; + let size = [img.width() as usize, img.height() as usize]; + Ok(ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR)) +} + /// The Plot Preview window: the sheet as it plots, with Print and Close. pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let id = egui::Id::unique("cc_plot_preview"); @@ -169,6 +174,16 @@ mod tests { (CadApp::new(Session::new(), services), asked) } + #[test] + fn plot_preview_reads_shared_png_and_rejects_other_bytes() { + let ctx = egui::Context::default(); + let mut png = Vec::new(); + cadcraft_render::raster::write_rgba_png(&mut png, 1, 1, &[10, 20, 30, 255]).unwrap(); + let texture = super::preview_texture(&ctx, &png).unwrap(); + assert_eq!(texture.size(), [1, 1]); + assert!(super::preview_texture(&ctx, b"not a PNG").is_err()); + } + #[test] fn typed_and_menu_commands_ask_json_calls_never_do() { let (mut app, asked) = app(); From ca6c1003427791e04a3d05dd081114e6720a6fd6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:35:55 +0000 Subject: [PATCH 15/24] Encode plot previews with shared PNG writer --- crates/engine/src/cmd/exchange.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 1b8d7c72e..65bdbde69 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -363,7 +363,7 @@ fn run_preview(s: &mut Session, p: &Value) -> Result { let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y))); cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b); } - let png = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?; + let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?; let layout = space.tab_name(); Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape })) } From 91b14c83cf8eae69f3f1d9c9d75fa07316a00270 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:39:16 +0000 Subject: [PATCH 16/24] Use shared Base64 for file and control data --- Cargo.lock | 16 +++++++++++ Cargo.toml | 1 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/file.rs | 40 +++------------------------- crates/engine/tests/base64_compat.rs | 14 ++++++++++ 5 files changed, 36 insertions(+), 36 deletions(-) create mode 100644 crates/engine/tests/base64_compat.rs diff --git a/Cargo.lock b/Cargo.lock index 41e541936..8ebd14522 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -700,6 +700,7 @@ dependencies = [ "cadcraft-render", "craft-docpath", "craft-dxf", + "craft-mime", "libc", "log", "rstar", @@ -1131,6 +1132,11 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=451a390542fbde0519cbb8ade3a3325cf02d97be#451a390542fbde0519cbb8ade3a3325cf02d97be" + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1183,6 +1189,16 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=451a390542fbde0519cbb8ade3a3325cf02d97be#451a390542fbde0519cbb8ade3a3325cf02d97be" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + [[package]] name = "craft-pdf" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index b22766049..69ed45ad9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "451a390542fbde0519cbb8ade3a3325cf02d97be" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } cadcraft-constraints = { path = "crates/constraints" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 21f911a97..23462fa05 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -12,6 +12,7 @@ workspace = true cadcraft-geom = { workspace = true } cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } +craft-mime = { workspace = true } craft-dxf = { workspace = true } cadcraft-constraints = { workspace = true } cadcraft-fonts = { workspace = true } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f43155c7d..973712b1a 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -1020,46 +1020,14 @@ fn run_saveas_reporting(s: &mut Session, p: &Value) -> Result { save_reporting(s, p, run_saveas, asked) } -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - +/// Encode bytes with the standard padded Base64 alphabet. pub fn base64_encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; - let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); - for i in 0..4 { - if i <= chunk.len() { - out.push(char::from(B64[((n >> (18 - 6 * i)) & 63) as usize])); - } else { - out.push('='); - } - } - } - out + craft_mime::base64::STANDARD.encode(data) } +/// Decode the legacy file/control Base64 form, retaining its permissive alphabet and padding. pub fn base64_decode(s: &str) -> Option> { - let mut out = Vec::with_capacity(s.len() * 3 / 4); - let mut buf = 0u32; - let mut bits = 0; - for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - b'=' | b'\n' | b'\r' | b' ' => continue, - _ => return None, - }; - buf = (buf << 6) | u32::from(v); - bits += 6; - if bits >= 8 { - bits -= 8; - out.push(((buf >> bits) & 0xff) as u8); - } - } - Some(out) + craft_mime::base64_compat::decode(s).ok() } #[cfg(test)] diff --git a/crates/engine/tests/base64_compat.rs b/crates/engine/tests/base64_compat.rs new file mode 100644 index 000000000..4ffa6d370 --- /dev/null +++ b/crates/engine/tests/base64_compat.rs @@ -0,0 +1,14 @@ +//! File and automation inputs retain CADCraft's accepted Base64 forms. +use cadcraft_engine::cmd::file::{base64_decode, base64_encode}; + +#[test] +fn legacy_inputs_and_standard_outputs_survive_the_shared_cutover() { + for bytes in [&b""[..], b"f", b"fo", b"foo", b"foobar", &[0, 255, 127]] { + assert_eq!(base64_decode(&base64_encode(bytes)).as_deref(), Some(bytes)); + } + assert_eq!(base64_decode("+_8=").as_deref(), Some(&[251, 255][..])); + assert_eq!(base64_decode("Z=m 9\nv\r").as_deref(), Some(&b"foo"[..])); + assert_eq!(base64_decode("A").as_deref(), Some(&b""[..])); + assert!(base64_decode("Zm9v\t").is_none()); + assert!(base64_decode("Zm9v!").is_none()); +} From 173cdf6e8a7d9ba2870bfe9f60548549388284b0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:00:46 +0000 Subject: [PATCH 17/24] Use shared MTEXT escape decoding --- Cargo.lock | 9 ++++- Cargo.toml | 2 +- crates/fonts/src/mtext.rs | 78 +-------------------------------------- 3 files changed, 11 insertions(+), 78 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 41e541936..c676a3293 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1131,6 +1131,11 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6345459e1297ee85a7ca62b428a440691bd062c1#6345459e1297ee85a7ca62b428a440691bd062c1" + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1148,9 +1153,11 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=006e4df225fca57e95ead0fb1f91920900798a99#006e4df225fca57e95ead0fb1f91920900798a99" +source = "git+https://github.com/storytold/craft-libs?rev=6345459e1297ee85a7ca62b428a440691bd062c1#6345459e1297ee85a7ca62b428a440691bd062c1" dependencies = [ + "craft-codepage", "encoding_rs", + "kurbo", "log", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index b22766049..4780e653d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft" # internal cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6345459e1297ee85a7ca62b428a440691bd062c1" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 1a2110116..06c420aa6 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -225,11 +225,8 @@ const MAX_ATOMS: usize = 200_000; /// Scale of stacked text relative to the surrounding text. const STACK_SCALE: f64 = 0.7; -/// Codes that take an argument terminated by `;` (besides `\S`, which has its own scan). Any -/// other code stands alone, so a missing `;` must not swallow the text after it. -pub(crate) fn takes_arg(code: char) -> bool { - matches!(code, 'f' | 'F' | 'H' | 'W' | 'Q' | 'T' | 'A' | 'C' | 'c' | 'p') -} +// Shared DXF escape handling and parameterized-command classification. +pub(crate) use craft_dxf::mtext::{takes_arg, unescape_codes}; /// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or /// non-finite value. @@ -237,77 +234,6 @@ pub(crate) fn sane_line_spacing(v: f64) -> f64 { if v.is_finite() && v > 0.0 { v.clamp(0.25, 4.0) } else { 1.0 } } -/// Four hex digits at `chars[at..at + 4]`. -fn hex4(chars: &[char], at: usize) -> Option { - let digits = chars.get(at..at.checked_add(4)?)?; - digits.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?)) -} - -/// Push a decoded character so that the tokenizers read it as text, never as markup. -fn push_literal(out: &mut String, c: char) { - if matches!(c, '\\' | '{' | '}') { - out.push('\\'); - } - out.push(c); -} - -/// Decode `\U+hhhh` (one UTF-16 unit; a surrogate pair gives one character, a lone surrogate -/// U+FFFD) and `\M+nhhhh` (double-byte East Asian characters) to the characters they stand -/// for. Malformed escapes are left for the tokenizers, which drop the backslash and the code. -/// An escaped backslash (`\\U+0041`) is not an escape. -pub(crate) fn unescape_codes(s: &str) -> std::borrow::Cow<'_, str> { - if !s.contains("\\U+") && !s.contains("\\M+") { - return std::borrow::Cow::Borrowed(s); - } - let chars: Vec = s.chars().collect(); - let mut out = String::with_capacity(s.len()); - let mut i = 0; - while let Some(&c) = chars.get(i) { - if c != '\\' { - out.push(c); - i += 1; - continue; - } - let (n, plus) = (chars.get(i + 1).copied(), chars.get(i + 2).copied()); - if n == Some('U') && plus == Some('+') { - if let Some(unit) = hex4(&chars, i + 3) { - i += 7; - let low = |at: usize| { - (chars.get(at) == Some(&'\\') && chars.get(at + 1) == Some(&'U') && chars.get(at + 2) == Some(&'+')) - .then(|| hex4(&chars, at + 3)) - .flatten() - .filter(|u| (0xDC00..0xE000).contains(u)) - }; - let ch = if (0xD800..0xDC00).contains(&unit) { - match low(i) { - Some(lo) => { - i += 7; - char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (lo - 0xDC00)) - } - None => None, - } - } else { - char::from_u32(unit) - }; - push_literal(&mut out, ch.unwrap_or('\u{fffd}')); - continue; - } - } else if n == Some('M') && plus == Some('+') && chars.get(i + 3).is_some_and(char::is_ascii_digit) && hex4(&chars, i + 4).is_some() { - push_literal(&mut out, craft_dxf::mif_escape_at(&chars, i).unwrap_or('\u{fffd}')); - i += 8; - continue; - } - // Any other backslash pair stays as it is (and an escaped backslash stays one). - out.push('\\'); - i += 1; - if let Some(&next) = chars.get(i) { - out.push(next); - i += 1; - } - } - std::borrow::Cow::Owned(out) -} - fn arg(chars: &[char], from: usize) -> (String, usize) { let mut j = from; let mut a = String::new(); From db70717001f744bf1460dff9a4b6f50f2bf605e2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:06:13 +0000 Subject: [PATCH 18/24] Use shared MTEXT lexical tokens --- Cargo.lock | 4 +- Cargo.toml | 2 +- crates/fonts/src/mtext.rs | 304 +++++++++------------------------ crates/fonts/src/mtext/para.rs | 60 ++----- 4 files changed, 103 insertions(+), 267 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c676a3293..e199ec5e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,7 +1134,7 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6345459e1297ee85a7ca62b428a440691bd062c1#6345459e1297ee85a7ca62b428a440691bd062c1" +source = "git+https://github.com/storytold/craft-libs?rev=b1d4c67196ee7c6b668428c8d211e7d5171dff88#b1d4c67196ee7c6b668428c8d211e7d5171dff88" [[package]] name = "craft-docpath" @@ -1153,7 +1153,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6345459e1297ee85a7ca62b428a440691bd062c1#6345459e1297ee85a7ca62b428a440691bd062c1" +source = "git+https://github.com/storytold/craft-libs?rev=b1d4c67196ee7c6b668428c8d211e7d5171dff88#b1d4c67196ee7c6b668428c8d211e7d5171dff88" dependencies = [ "craft-codepage", "encoding_rs", diff --git a/Cargo.toml b/Cargo.toml index 4780e653d..023c6ef9b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft" # internal cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6345459e1297ee85a7ca62b428a440691bd062c1" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b1d4c67196ee7c6b668428c8d211e7d5171dff88" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 06c420aa6..bc7f88eba 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -12,79 +12,22 @@ pub fn plain_mtext(s: &str) -> String { let s = unescape_codes(s); let s = s.as_ref(); let mut out = String::with_capacity(s.len()); - let chars: Vec = s.chars().collect(); - let mut i = 0; - while let Some(&c) = chars.get(i) { - match c { - '\\' => { - let code = chars.get(i + 1).copied().unwrap_or(' '); - match code { - 'P' => { - out.push('\n'); - i += 2; - } - 'N' => { - out.push('\n'); - i += 2; - } - '~' => { - out.push(' '); - i += 2; - } - '\\' | '{' | '}' => { - out.push(code); - i += 2; - } - 'S' => { - // \Snum^den; \Snum/den; \Snum#den; - let mut j = i + 2; - let mut stack = String::new(); - while let Some(&ch) = chars.get(j) { - if ch == ';' { - break; - } - stack.push(match ch { - '^' | '#' => '/', - c => c, - }); - j += 1; - } - // "6\S1/2;" reads as "6 1/2". - if out.chars().last().is_some_and(|c| c.is_ascii_digit()) && stack.starts_with(|c: char| c.is_ascii_digit()) { - out.push(' '); - } - out.push_str(stack.trim_end_matches('/')); - i = j + 1; - } - 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2, - // `\U+XXXX`: a character by its Unicode code, as the layout reads it. - 'U' if crate::unicode_escape(&chars, i).is_some() => { - if let Some(u) = crate::unicode_escape(&chars, i) { - out.push(u); - } - i += 7; - } - // Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p). - _ if takes_arg(code) => { - let mut j = i + 2; - while let Some(&ch) = chars.get(j) { - if ch == ';' { - break; - } - j += 1; - } - i = j + 1; - } - // An unknown code has no argument: drop the backslash and the code only. - _ => i += 2, + use craft_dxf::mtext_tokens::{StackMode, Token, Tokens}; + for token in Tokens::new(s, StackMode::Plain) { + match token { + Token::Control('P' | 'N') => out.push('\n'), + Token::Control('~') => out.push(' '), + Token::Control(c @ ('\\' | '{' | '}')) => out.push(c), + Token::Stack(raw) => { + let stack: String = raw.chars().map(|c| if matches!(c, '^' | '#') { '/' } else { c }).collect(); + if out.chars().last().is_some_and(|c| c.is_ascii_digit()) && stack.starts_with(|c: char| c.is_ascii_digit()) { + out.push(' '); } + out.push_str(stack.trim_end_matches('/')); } - '{' | '}' => i += 1, - '\r' => i += 1, - _ => { - out.push(c); - i += 1; - } + Token::Char('\r') => {} + Token::Char(c) => out.push(c), + _ => {} } } out @@ -226,7 +169,7 @@ const MAX_ATOMS: usize = 200_000; const STACK_SCALE: f64 = 0.7; // Shared DXF escape handling and parameterized-command classification. -pub(crate) use craft_dxf::mtext::{takes_arg, unescape_codes}; +pub(crate) use craft_dxf::mtext::unescape_codes; /// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or /// non-finite value. @@ -234,19 +177,6 @@ pub(crate) fn sane_line_spacing(v: f64) -> f64 { if v.is_finite() && v > 0.0 { v.clamp(0.25, 4.0) } else { 1.0 } } -fn arg(chars: &[char], from: usize) -> (String, usize) { - let mut j = from; - let mut a = String::new(); - while let Some(&ch) = chars.get(j) { - if ch == ';' { - return (a, j + 1); - } - a.push(ch); - j += 1; - } - (a, j) -} - fn num(a: &str) -> Option { a.trim().parse::().ok().filter(|v| v.is_finite()) } @@ -284,7 +214,7 @@ fn font_switch(a: &str) -> Option { /// Parse MTEXT contents into words, spaces and paragraph breaks with their formats. fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { - let chars: Vec = contents.chars().collect(); + use craft_dxf::mtext_tokens::{StackMode, Token, Tokens, split_stack}; let h_min = base.height * 1e-3; let h_max = if (base.height * 1e3).is_finite() { base.height * 1e3 } else { f64::MAX }; let mut fmts = vec![base]; @@ -324,158 +254,94 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { *cur = fmts.len() - 1; } }; - let mut i = 0; - while let Some(&c) = chars.get(i) { + for token in Tokens::new(contents, StackMode::Structured) { if atoms.len() > MAX_ATOMS { break; } - match c { - '\\' => { - let code = chars.get(i + 1).copied().unwrap_or(' '); - i += 2; - match code { - 'P' | 'N' => { - end_word(&mut atoms, &mut word); - atoms.push(Atom::Para(cur)); - } - '~' => push_char(&mut word, '\u{a0}', cur), - '\\' | '{' | '}' => push_char(&mut word, code, cur), - 'L' => derive(&mut fmts, &mut cur, &|f| f.under = true), - 'l' => derive(&mut fmts, &mut cur, &|f| f.under = false), - 'O' => derive(&mut fmts, &mut cur, &|f| f.over = true), - 'o' => derive(&mut fmts, &mut cur, &|f| f.over = false), - 'K' | 'k' => {} - // `\U+XXXX`: a character by its Unicode code. - 'U' if i >= 2 && crate::unicode_escape(&chars, i - 2).is_some() => { - if let Some(u) = crate::unicode_escape(&chars, i - 2) { - push_char(&mut word, u, cur); - } - i += 5; - } - 'S' => { - let mut j = i; - let (mut top, mut bottom, mut sep) = (String::new(), String::new(), None); - while let Some(&ch) = chars.get(j) { - if ch == ';' { - break; - } - if ch == '\\' { - if let Some(&n) = chars.get(j + 1) { - if sep.is_none() { top.push(n) } else { bottom.push(n) } - } - j += 2; - continue; - } - if sep.is_none() && matches!(ch, '/' | '#' | '^') { - sep = Some(ch); - } else if sep.is_none() { - top.push(ch); - } else { - bottom.push(ch); - } - j += 1; - } - i = j + 1; - word.push((Seg::Stack(top, bottom, sep.unwrap_or('/')), cur)); - } - 'f' | 'F' => { - let (a, n) = arg(&chars, i); - i = n; - if let Some(font) = font_switch(&a) { - derive(&mut fmts, &mut cur, &|f| f.font = font.clone()); - } - } - 'H' => { - let (a, n) = arg(&chars, i); - i = n; - let (rel, v) = match a.trim().strip_suffix(['x', 'X']) { - Some(r) => (true, num(r)), - None => (false, num(&a)), - }; - if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) { - // Relative heights compound; keep the result within 1e-3..1e3 times the - // MTEXT's own height, never infinite. - derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v }); - } - } - 'W' => { - let (a, n) = arg(&chars, i); - i = n; - // `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it. - let (rel, v) = match a.trim().strip_suffix(['x', 'X']) { - Some(r) => (true, num(r)), - None => (false, num(&a)), - }; - if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) { - // Relative factors compound; keep the result within the absolute range. - derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v }); - } - } - 'Q' => { - let (a, n) = arg(&chars, i); - i = n; - if let Some(v) = num(&a).filter(|v| v.abs() < 85.0) { - derive(&mut fmts, &mut cur, &|f| f.oblique = v.to_radians()); - } - } - 'C' => { - let (a, n) = arg(&chars, i); - i = n; - if let Ok(v) = a.trim().parse::() { - let col = if v == 0 || v >= 256 { None } else { Some(MTextColor::Aci(v)) }; - derive(&mut fmts, &mut cur, &|f| f.color = col); - } - } - 'c' => { - let (a, n) = arg(&chars, i); - i = n; - if let Ok(v) = a.trim().parse::() { - derive(&mut fmts, &mut cur, &|f| f.color = Some(MTextColor::Rgb(v & 0xFF_FFFF))); - } - } - 'A' => { - let (a, n) = arg(&chars, i); - i = n; - if let Ok(v @ 0..=2) = a.trim().parse::() { - derive(&mut fmts, &mut cur, &|f| f.valign = v); - } - } - _ if takes_arg(code) => { - // \T and \p: argument up to ';'. - let (_, n) = arg(&chars, i); - i = n; - } - // An unknown code has no argument: only the backslash and the code are dropped. - _ => {} + match token { + Token::Control('P' | 'N') => { + end_word(&mut atoms, &mut word); + atoms.push(Atom::Para(cur)); + } + Token::Control('~') => push_char(&mut word, '\u{a0}', cur), + Token::Control(c @ ('\\' | '{' | '}')) => push_char(&mut word, c, cur), + Token::Control('L') => derive(&mut fmts, &mut cur, &|f| f.under = true), + Token::Control('l') => derive(&mut fmts, &mut cur, &|f| f.under = false), + Token::Control('O') => derive(&mut fmts, &mut cur, &|f| f.over = true), + Token::Control('o') => derive(&mut fmts, &mut cur, &|f| f.over = false), + Token::Stack(raw) => { + let (top, bottom, sep) = split_stack(raw); + word.push((Seg::Stack(top, bottom, sep.unwrap_or('/')), cur)); + } + Token::Argument('f' | 'F', a) => { + if let Some(font) = font_switch(a) { + derive(&mut fmts, &mut cur, &|f| f.font = font.clone()); } } - '{' => { + Token::Argument('H', a) => { + let (rel, v) = match a.trim().strip_suffix(['x', 'X']) { + Some(r) => (true, num(r)), + None => (false, num(a)), + }; + if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) { + // Relative heights compound; keep the result within 1e-3..1e3 times the + // MTEXT's own height, never infinite. + derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v }); + } + } + Token::Argument('W', a) => { + // `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it. + let (rel, v) = match a.trim().strip_suffix(['x', 'X']) { + Some(r) => (true, num(r)), + None => (false, num(a)), + }; + if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) { + // Relative factors compound; keep the result within the absolute range. + derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v }); + } + } + Token::Argument('Q', a) => { + if let Some(v) = num(a).filter(|v| v.abs() < 85.0) { + derive(&mut fmts, &mut cur, &|f| f.oblique = v.to_radians()); + } + } + Token::Argument('C', a) => { + if let Ok(v) = a.trim().parse::() { + let col = if v == 0 || v >= 256 { None } else { Some(MTextColor::Aci(v)) }; + derive(&mut fmts, &mut cur, &|f| f.color = col); + } + } + Token::Argument('c', a) => { + if let Ok(v) = a.trim().parse::() { + derive(&mut fmts, &mut cur, &|f| f.color = Some(MTextColor::Rgb(v & 0xFF_FFFF))); + } + } + Token::Argument('A', a) => { + if let Ok(v @ 0..=2) = a.trim().parse::() { + derive(&mut fmts, &mut cur, &|f| f.valign = v); + } + } + Token::OpenGroup => { if stack.len() < 256 { stack.push(cur); } - i += 1; } - '}' => { + Token::CloseGroup => { if let Some(f) = stack.pop() { cur = f; } - i += 1; } - '\r' => i += 1, - '\n' => { + Token::Char('\r') => {} + Token::Char('\n') => { end_word(&mut atoms, &mut word); atoms.push(Atom::Para(cur)); - i += 1; } - ' ' => { + Token::Char(' ') => { end_word(&mut atoms, &mut word); atoms.push(Atom::Space(cur)); - i += 1; - } - _ => { - push_char(&mut word, c, cur); - i += 1; } + Token::Char(c) => push_char(&mut word, c, cur), + _ => {} } } end_word(&mut atoms, &mut word); diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index 63b431610..7499cdce5 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -7,7 +7,7 @@ use cadcraft_geom::{Bounds2, Vec2}; -use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, arg, num, parse, seg_plain, seg_shape, seg_width, split_thai}; +use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, num, parse, seg_plain, seg_shape, seg_width, split_thai}; /// Columns an MTEXT's text flows through, each as wide as the MTEXT's width. #[derive(Clone, Debug, Default, PartialEq)] @@ -265,58 +265,28 @@ pub struct Paragraphs { impl Paragraphs { pub fn scan(contents: &str) -> Paragraphs { let contents = super::unescape_codes(contents); - let chars: Vec = contents.chars().collect(); + use craft_dxf::mtext_tokens::{StackMode, Token, Tokens}; let mut out = Paragraphs { states: vec![ParaProps::default()], ..Default::default() }; let mut cur = 0usize; - let mut i = 0; let brk = |out: &mut Paragraphs, cur: usize, column: bool| { out.para.push(cur); out.column_break.push(column); }; - while let Some(&c) = chars.get(i) { - match c { - '\\' => { - let code = chars.get(i + 1).copied().unwrap_or(' '); - i += 2; - match code { - 'P' => brk(&mut out, cur, false), - 'N' => brk(&mut out, cur, true), - '~' | '\\' | '{' | '}' | 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => {} - 'S' => { - let mut j = i; - while let Some(&ch) = chars.get(j) { - if ch == ';' { - break; - } - j += if ch == '\\' { 2 } else { 1 }; - } - i = j + 1; - } - 'p' => { - let (a, n) = arg(&chars, i); - i = n; - if out.states.len() < MAX_STATES - && let Some(st) = out.states.get(cur) - { - let mut st = st.clone(); - st.apply(&a); - out.states.push(st); - cur = out.states.len() - 1; - } - } - _ if super::takes_arg(code) => { - let (_, n) = arg(&chars, i); - i = n; - } - // An unknown code has no argument: only the backslash and the code go. - _ => {} + for token in Tokens::new(&contents, StackMode::Structured) { + match token { + Token::Control('P') | Token::Char('\n') => brk(&mut out, cur, false), + Token::Control('N') => brk(&mut out, cur, true), + Token::Argument('p', a) => { + if out.states.len() < MAX_STATES + && let Some(st) = out.states.get(cur) + { + let mut st = st.clone(); + st.apply(a); + out.states.push(st); + cur = out.states.len() - 1; } } - '\n' => { - brk(&mut out, cur, false); - i += 1; - } - _ => i += 1, + _ => {} } } // A `\p` anywhere in a paragraph applies to all of it: the break pushed the state at From a20a46f7c3a992308314dc968c3933ce4980cf15 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:14:50 +0000 Subject: [PATCH 19/24] Pin MCP cutover to merged shared protocol revision --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6985344a2..e0731dbf4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1188,7 +1188,7 @@ dependencies = [ [[package]] name = "craft-jsonrpc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2c9903ca1d892b5446acf3598d8b142f3e64842f#2c9903ca1d892b5446acf3598d8b142f3e64842f" +source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c" dependencies = [ "serde_json", ] @@ -1196,7 +1196,7 @@ dependencies = [ [[package]] name = "craft-mcp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2c9903ca1d892b5446acf3598d8b142f3e64842f#2c9903ca1d892b5446acf3598d8b142f3e64842f" +source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c" dependencies = [ "craft-jsonrpc", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index c964a8769..e3dd15d16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,8 +25,8 @@ cadcraft-io = { path = "crates/io" } cadcraft-engine = { path = "crates/engine" } cadcraft-ui-egui = { path = "crates/ui-egui" } cadcraft-mcp = { path = "crates/mcp" } -craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "2c9903ca1d892b5446acf3598d8b142f3e64842f" } -craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "2c9903ca1d892b5446acf3598d8b142f3e64842f" } +craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" } +craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" } # Which paths stored in a drawing (xrefs, data links) may be opened. craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } # PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin From 9789562ac7c4f018a08ce2a57de1454a9616a66f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:17:19 +0000 Subject: [PATCH 20/24] Pin Base64 consumer to merged shared compatibility API --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8ebd14522..2aa345321 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1135,7 +1135,7 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=451a390542fbde0519cbb8ade3a3325cf02d97be#451a390542fbde0519cbb8ade3a3325cf02d97be" +source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db" [[package]] name = "craft-docpath" @@ -1192,7 +1192,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=451a390542fbde0519cbb8ade3a3325cf02d97be#451a390542fbde0519cbb8ade3a3325cf02d97be" +source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db" dependencies = [ "chrono", "craft-codepage", diff --git a/Cargo.toml b/Cargo.toml index 69ed45ad9..a610cabce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "451a390542fbde0519cbb8ade3a3325cf02d97be" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } cadcraft-constraints = { path = "crates/constraints" } From 923f4174a650a3d5069e7f8227a2922b5031441d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:38:18 +0000 Subject: [PATCH 21/24] Pin MTEXT escapes to merged shared decoder --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c676a3293..7c3ba1a01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,7 +1134,7 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6345459e1297ee85a7ca62b428a440691bd062c1#6345459e1297ee85a7ca62b428a440691bd062c1" +source = "git+https://github.com/storytold/craft-libs?rev=10f0fac31c3c7f063de8c359b39d247451324b48#10f0fac31c3c7f063de8c359b39d247451324b48" [[package]] name = "craft-docpath" @@ -1153,7 +1153,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6345459e1297ee85a7ca62b428a440691bd062c1#6345459e1297ee85a7ca62b428a440691bd062c1" +source = "git+https://github.com/storytold/craft-libs?rev=10f0fac31c3c7f063de8c359b39d247451324b48#10f0fac31c3c7f063de8c359b39d247451324b48" dependencies = [ "craft-codepage", "encoding_rs", diff --git a/Cargo.toml b/Cargo.toml index 4780e653d..b94b8d1f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft" # internal cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6345459e1297ee85a7ca62b428a440691bd062c1" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "10f0fac31c3c7f063de8c359b39d247451324b48" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } From ed6377fc4616948d19f785a856648e703ae02d09 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:22:40 +0000 Subject: [PATCH 22/24] Update code page fixtures for Johab support --- crates/io/tests/it/codepages.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/io/tests/it/codepages.rs b/crates/io/tests/it/codepages.rs index cbb4a698d..cb63ae95d 100644 --- a/crates/io/tests/it/codepages.rs +++ b/crates/io/tests/it/codepages.rs @@ -99,7 +99,7 @@ fn utf8_wins_when_valid() { /// A code page CADCraft doesn't know (or none) reads as ANSI_1252, as before. #[test] fn unknown_code_page_falls_back_to_ansi_1252() { - for cp in ["ANSI_1361", "EBCDIC", "", "\u{1}"] { + for cp in ["ANSI_UNKNOWN", "EBCDIC", "", "\u{1}"] { let d = cadcraft_io::read_dxf(&ascii_dxf("AC1015", cp, b"Caf\xE9", b"B", b"\x80 \xD8")).unwrap(); assert_eq!(names(&d), ("Café".into(), "B".into(), "€ Ø".into()), "{cp:?}"); } @@ -209,7 +209,9 @@ fn binary_dxf_honours_the_code_page() { // a pre-R2007 binary file has no way to escape to UTF-8, so its strings are never read as it. assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xD1\xB2")), "СІ"); assert_eq!(read(&bin("AC1021", "ANSI_1251", "Привет".as_bytes())), "Привет"); - assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Café"); + assert_eq!(read(&bin("AC1015", "ANSI_UNKNOWN", b"Caf\xE9")), "Café"); + assert_eq!(read(&bin("AC1015", "ANSI_1361", b"\xD0\x65\x8B\x69")), "한글"); + assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Caf\u{FFFD}"); } /// Truncated and invalid multibyte sequences become U+FFFD; nothing panics and the structure of From 007a24ef9461317cf40fb31f79cc571f58308174 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sun, 15 Nov 2026 01:30:13 +0000 Subject: [PATCH 23/24] Fonts: MTEXT shows a malformed \U+ or \M+ escape and an unknown code as typed (#2952) AutoCAD 2024 shows a \U+ without four hex digits, a malformed \M+ and an unknown code such as \Z as typed, backslash included. plain_mtext, the layout and the paragraph scan dropped the backslash and the code instead. They now keep the backslash and read on from the code. --- crates/fonts/src/mtext.rs | 45 ++++++++++++++++++++++++---------- crates/fonts/src/mtext/para.rs | 4 +-- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 06c420aa6..fba28071c 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -75,8 +75,14 @@ pub fn plain_mtext(s: &str) -> String { } i = j + 1; } - // An unknown code has no argument: drop the backslash and the code only. - _ => i += 2, + // A trailing lone backslash is dropped. + _ if chars.get(i + 1).is_none() => i += 1, + // An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD + // shows it: keep the backslash and read on from the code. + _ => { + out.push('\\'); + i += 1; + } } } '{' | '}' => i += 1, @@ -445,8 +451,15 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { let (_, n) = arg(&chars, i); i = n; } - // An unknown code has no argument: only the backslash and the code are dropped. - _ => {} + // An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD + // shows it: keep the backslash and read on from the code. A trailing lone + // backslash is dropped. + _ => { + if chars.get(i - 1).is_some() { + push_char(&mut word, '\\', cur); + i -= 1; + } + } } } '{' => { @@ -884,7 +897,7 @@ mod tests { assert_eq!(plain_mtext("\\H2.5x;Big"), "Big"); assert_eq!(plain_mtext("unterminated \\H2"), "unterminated "); assert_eq!(plain_mtext("\\U+0041B \\U+00E8"), "AB è"); - assert_eq!(plain_mtext("\\U+12"), "+12", "a short escape loses only the backslash and the code"); + assert_eq!(plain_mtext("\\U+12"), "\\U+12", "a short escape is shown as typed"); } #[test] @@ -906,18 +919,24 @@ mod tests { assert_eq!(plain_mtext("\\\\U+0041"), "\\U+0041"); // `\M+n` double-byte characters, decoded like the DXF reader does. assert_eq!(plain_mtext("\\M+5BCFE x;y"), "\u{4ef6} x;y"); - // Malformed escapes lose only the backslash and the code. - assert_eq!(plain_mtext("a\\U+12 b"), "a+12 b"); - assert_eq!(lay("a\\U+12 b", 0.0).lines, vec!["a+12 b"]); - assert_eq!(lay("\\pxql;a\\U+12 b", 0.0).lines, vec!["a+12 b"]); - assert_eq!(plain_mtext("a\\M+ b"), "a+ b"); + // Malformed escapes are shown as typed, backslash included, as AutoCAD 2024 shows them. + for s in ["a\\U+12 b", "\\U+12x", "a\\U+12;b", "a\\U+123 b", "a\\U+ b", "a\\U+00G1b", "a\\M+ b"] { + assert_eq!(plain_mtext(s), s); + assert_eq!(lay(s, 0.0).lines, vec![s]); + assert_eq!(lay(&format!("\\pxql;{s}"), 0.0).lines, vec![s]); + } + // A valid escape takes exactly four digits. + assert_eq!(plain_mtext("a\\U+12345b"), "a\u{1234}5b"); } #[test] fn unknown_code_without_semicolon_keeps_the_text() { - assert_eq!(plain_mtext("A\\Zbc d"), "Abc d"); - assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["Abc d"]); - assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["Abc d"]); + // An unknown code is shown as typed, as AutoCAD 2024 shows it. + assert_eq!(plain_mtext("A\\Zbc d"), "A\\Zbc d"); + assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["A\\Zbc d"]); + assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["A\\Zbc d"]); + // The text after it is read as usual: here a paragraph break. + assert_eq!(plain_mtext("A\\Z\\Pb"), "A\\Z\nb"); // A trailing lone backslash is dropped. assert_eq!(plain_mtext("A\\"), "A"); // Codes with an argument still take it up to the `;`, or to the end. diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index 63b431610..0fcb70d11 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -308,8 +308,8 @@ impl Paragraphs { let (_, n) = arg(&chars, i); i = n; } - // An unknown code has no argument: only the backslash and the code go. - _ => {} + // An unknown code is text, as typed: read on from the code, as the layout does. + _ => i -= 1, } } '\n' => { From 2974d74bdc55cf6264f69a28c3d70d2241093a0f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:30:49 -0500 Subject: [PATCH 24/24] Use shared raster image codecs (#3189) * Use shared raster image codecs * Encode rendered PNGs through shared codecs * Update raster probe and use supported BMP dimensions * Check raster depth and TIFF page fidelity --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- ATTRIBUTION.md | 1 + Cargo.lock | 177 +++++++++++++++++ Cargo.toml | 1 + NOTICE | 126 +++++++++++- crates/io/Cargo.toml | 4 +- crates/io/src/plotter.rs | 2 +- crates/io/src/raster.rs | 84 ++++---- crates/io/tests/raster_decode.rs | 44 +++++ crates/render/Cargo.toml | 1 + crates/render/src/raster.rs | 28 ++- crates/render/tests/png_parity.rs | 10 + licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt | 72 +++++++ licenses/jpeg-encoder-0.6.1/LICENSE-APACHE | 201 ++++++++++++++++++++ licenses/jpeg-encoder-0.6.1/LICENSE-MIT | 25 +++ licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt | 8 + licenses/jpeg-encoder-0.6.1/SOURCE.json | 29 +++ 16 files changed, 766 insertions(+), 47 deletions(-) create mode 100644 crates/render/tests/png_parity.rs create mode 100644 licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt create mode 100644 licenses/jpeg-encoder-0.6.1/LICENSE-APACHE create mode 100644 licenses/jpeg-encoder-0.6.1/LICENSE-MIT create mode 100644 licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt create mode 100644 licenses/jpeg-encoder-0.6.1/SOURCE.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a8524be64..cabf50d94 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,6 +23,7 @@ Generated-in-code assets are original and have no file to list: | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| +| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. | | `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. | | `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. | | `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. | diff --git a/Cargo.lock b/Cargo.lock index 20d7c9825..bc0d4ec50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,6 +156,21 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -513,6 +528,12 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -568,6 +589,16 @@ dependencies = [ "piper", ] +[[package]] +name = "brotli-decompressor" +version = "6.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -741,6 +772,7 @@ dependencies = [ "cadcraft-render", "craft-dwg", "craft-dxf", + "craft-image-codecs", "craft-pdf", "image", "miniz_oxide 0.9.1", @@ -748,6 +780,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "tiff", "tiny-skia", ] @@ -776,6 +809,7 @@ dependencies = [ "cadcraft-doc", "cadcraft-fonts", "cadcraft-geom", + "craft-image-codecs", "lyon_tessellation", "rayon", "serde_json", @@ -1191,6 +1225,39 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" +dependencies = [ + "craft-jpeg", + "craft-metadata", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-jsonrpc" version = "0.1.0" @@ -1208,6 +1275,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" +dependencies = [ + "brotli-decompressor", + "chrono", + "craft-tiff", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-mime" version = "0.1.0" @@ -1228,6 +1307,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1796,6 +1884,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -2300,6 +2404,9 @@ name = "hayro-jpeg2000" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] [[package]] name = "hayro-syntax" @@ -2602,9 +2709,12 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", "moxcms", "num-traits", "png", + "qoi", "tiff", "zune-core", "zune-jpeg", @@ -2744,6 +2854,12 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-encoder" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" + [[package]] name = "js-sys" version = "0.3.106" @@ -2836,6 +2952,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -3028,6 +3150,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -3896,6 +4040,15 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "2.0.1" @@ -4693,6 +4846,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -6285,6 +6444,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" @@ -6294,6 +6462,15 @@ dependencies = [ "zune-core", ] +[[package]] +name = "zune-jpegxl" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "5.15.1" diff --git a/Cargo.toml b/Cargo.toml index bc1f41278..29461710a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ cadcraft-geom = { path = "crates/geom" } # DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791). craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" } craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" } craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } diff --git a/NOTICE b/NOTICE index 2eb24b221..f3ecf5fc1 100644 --- a/NOTICE +++ b/NOTICE @@ -11,7 +11,7 @@ Third-party material Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the -Mozilla Public License 2.0 and is used unmodified as a separate library (crates/dwg). Its source +Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source is available from crates.io and the repository above. @@ -48,3 +48,127 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root +(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1). +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 44f22cd5e..a2d83e220 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -14,6 +14,7 @@ cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } craft-dxf = { workspace = true } craft-dwg = { workspace = true } +craft-image-codecs = { workspace = true } cadcraft-render = { workspace = true } cadcraft-fonts = { workspace = true } thiserror = { workspace = true } @@ -22,9 +23,10 @@ serde = { workspace = true } miniz_oxide = "0.9" craft-pdf = { workspace = true, features = ["write"] } quick-xml = { workspace = true } -image = { workspace = true } [dev-dependencies] +tiff = "0.11" +image = { workspace = true } tiny-skia = { workspace = true } # Reads plotted PDFs back. craft-pdf = { workspace = true, features = ["read"] } diff --git a/crates/io/src/plotter.rs b/crates/io/src/plotter.rs index f0a174ea1..07984c798 100644 --- a/crates/io/src/plotter.rs +++ b/crates/io/src/plotter.rs @@ -116,7 +116,7 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { // PDF clips a placed plot to the printable area: blank the rest of the sheet. raster::blank_outside_printable(&mut pm, &sheet.printable, k); } - pm.encode_png().map_err(|_| IoError::Format("render failed".into())) + raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into())) } fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result> { diff --git a/crates/io/src/raster.rs b/crates/io/src/raster.rs index 3e09ef9c9..92afeb4f6 100644 --- a/crates/io/src/raster.rs +++ b/crates/io/src/raster.rs @@ -2,11 +2,9 @@ //! from the content. Files are hostile input: the size is read from the header and checked //! before any pixel is decoded. -use std::io::Cursor; - -use cadcraft_doc::Raster; - use crate::{IoError, Result}; +use cadcraft_doc::Raster; +use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType}; /// Largest image file read (bytes). pub const MAX_IMAGE_BYTES: usize = 256 << 20; @@ -17,22 +15,18 @@ fn bad(e: impl std::fmt::Display) -> IoError { IoError::Format(format!("image: {e}")) } -/// A reader over an image file, once it is small enough and of a format we read. -fn reader(bytes: &[u8]) -> Result>> { +/// The width and height in pixels of the first stored image, read without decoding pixels. +pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { if bytes.len() > MAX_IMAGE_BYTES { return Err(bad(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20))); } - // The format comes from the file's first bytes, not from its name. - let file = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(bad)?; - if file.format().is_none() { + let format = craft_image_codecs::detect(bytes).ok_or_else(|| bad("not a PNG, JPEG, BMP or TIFF file"))?; + if !matches!(format, Format::Png | Format::Jpeg | Format::Bmp | Format::Tiff) { return Err(bad("not a PNG, JPEG, BMP or TIFF file")); } - Ok(file) -} - -/// The width and height in pixels of the image in `bytes`, read from its header. -pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { - let (width, height) = reader(bytes)?.into_dimensions().map_err(bad)?; + // Match ImageReader's original header budget; check pixels ourselves for the existing diagnostic. + let limits = Limits::new(u32::MAX, u32::MAX, u64::MAX, 512 << 20); + let (width, height) = craft_image_codecs::probe_stored_size(bytes, &limits).map_err(bad)?; if width == 0 || height == 0 { return Err(bad("the image is empty")); } @@ -42,38 +36,42 @@ pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { Ok((width, height)) } -/// Decode the image in `bytes`. +/// Decode the first image, keeping its stored orientation. pub fn decode(bytes: &[u8]) -> Result { - // The size is checked first, from the header alone. let (width, height) = probe(bytes)?; - let mut file = reader(bytes)?; - file.limits(decode_limits(width, height)); - let pixels = file.decode().map_err(bad)?.into_rgba8(); - Raster::new(pixels.width(), pixels.height(), pixels.into_raw()).ok_or_else(|| bad("the image is empty")) -} - -/// What the decoder may allocate for an image of this size: the pixels themselves (up to 16 -/// bytes each before they become 8-bit RGBA) and its own working buffers. -fn decode_limits(width: u32, height: u32) -> image::Limits { let pixels = u64::from(width).saturating_mul(u64::from(height)); - let mut limits = image::Limits::default(); - limits.max_image_width = Some(width); - limits.max_image_height = Some(height); - limits.max_alloc = Some(pixels.saturating_mul(16).saturating_add(64 << 20)); - limits + let limits = Limits::new(width, height, MAX_IMAGE_PIXELS, pixels.saturating_mul(16).saturating_add(64 << 20)); + let opts = DecodeOptions { limits, keep_orientation: true }; + let format = craft_image_codecs::detect(bytes).ok_or_else(|| bad("not an image"))?; + let image = if format == Format::Tiff { + craft_image_codecs::decode_tiff_page(bytes, 0, &opts) + } else { + craft_image_codecs::decode_as_with(format, bytes, &opts) + } + .map_err(bad)?; + if image.warnings.iter().any(|w| matches!(w, DecodeWarning::Truncated { .. })) { + return Err(bad("image data is truncated")); + } + if image.dimensions() != (width, height) { + return Err(bad("decoded image size does not match its header")); + } + let rgba = if image.layout() == ChannelLayout::Rgba && image.sample_type() == SampleType::U8 { image.into_data() } else { image.to_rgba8() }; + Raster::new(width, height, rgba).ok_or_else(|| bad("the image is empty")) } -/// `raster` as a PNG file. +/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy. pub fn encode_png(raster: &Raster) -> Result> { - let mut out = Cursor::new(Vec::new()); - image::write_buffer_with_format( - &mut out, - raster.rgba(), - raster.width(), - raster.height(), - image::ExtendedColorType::Rgba8, - image::ImageFormat::Png, - ) - .map_err(bad)?; - Ok(out.into_inner()) + let stride = usize::try_from(raster.width()).ok().and_then(|w| w.checked_mul(4)).filter(|s| *s > 0).ok_or_else(|| bad("invalid image width"))?; + let mut chunks = raster.rgba().chunks_exact(stride); + let first = chunks.next().ok_or_else(|| bad("the image is empty"))?; + let row = |data: &[u8]| Image::from_u8(raster.width(), 1, ChannelLayout::Rgba, data.to_vec()).map_err(bad); + let first = row(first)?; + let mut out = Vec::new(); + let mut writer = PngRows::new(&mut out, &first, raster.height(), &EncodeOptions::default()).map_err(bad)?; + writer.push(&first).map_err(bad)?; + for chunk in chunks { + writer.push(&row(chunk)?).map_err(bad)?; + } + writer.finish().map_err(bad)?; + Ok(out) } diff --git a/crates/io/tests/raster_decode.rs b/crates/io/tests/raster_decode.rs index 51a6130b7..a70a2b21b 100644 --- a/crates/io/tests/raster_decode.rs +++ b/crates/io/tests/raster_decode.rs @@ -170,3 +170,47 @@ fn the_pixels_never_reach_the_drawing_file() { assert!(bare.rasters.is_empty() && d.rasters.len() == 1); assert_eq!(bare, d); } + +#[test] +fn long_narrow_bmp_uses_cadcrafts_pixel_limit() { + let mut file = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut file, &vec![0; 60_000 * 3], 1, 60_000, image::ExtendedColorType::Rgb8, image::ImageFormat::Bmp).unwrap(); + assert_eq!(probe(&file.into_inner()).unwrap(), (1, 60_000)); +} + +#[test] +fn sixteen_bit_png_and_tiff_match_the_previous_rgba_conversion() { + let samples: [u16; 12] = [0, 1, 128, 255, 256, 257, 32767, 32768, 50000, 65280, 65534, 65535]; + let bytes: Vec = samples.into_iter().flat_map(u16::to_ne_bytes).collect(); + for format in [image::ImageFormat::Png, image::ImageFormat::Tiff] { + let mut out = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut out, &bytes, 2, 2, image::ExtendedColorType::Rgb16, format).unwrap(); + let file = out.into_inner(); + let old = image::load_from_memory(&file).unwrap().to_rgba8(); + let new = decode(&file).unwrap(); + assert_eq!(new.rgba(), old.as_raw(), "{format:?}"); + } +} + +#[test] +fn tiff_uses_first_directory_and_keeps_stored_orientation() { + use tiff::encoder::{TiffEncoder, colortype::RGB8}; + use tiff::tags::Tag; + let mut file = std::io::Cursor::new(Vec::new()); + { + let mut tiff = TiffEncoder::new(&mut file).unwrap(); + let mut thumbnail = tiff.new_image::(1, 2).unwrap(); + thumbnail.encoder().write_tag(Tag::NewSubfileType, 1u32).unwrap(); + thumbnail.encoder().write_tag(Tag::Orientation, 6u16).unwrap(); + thumbnail.write_data(&[10, 20, 30, 90, 100, 110]).unwrap(); + tiff.new_image::(2, 2).unwrap().write_data(&[200; 12]).unwrap(); + } + let file = file.into_inner(); + assert_eq!(craft_image_codecs::tiff_info(&file).unwrap().default_page(), Some(1)); + let old = image::load_from_memory(&file).unwrap().to_rgba8(); + assert_eq!(old.dimensions(), (1, 2)); + assert_eq!(probe(&file).unwrap(), (1, 2)); + let actual = decode(&file).unwrap(); + assert_eq!((actual.width(), actual.height()), old.dimensions()); + assert_eq!(actual.rgba(), old.as_raw()); +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index d62af23b9..44d5b48da 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -12,6 +12,7 @@ workspace = true cadcraft-geom = { workspace = true } cadcraft-color = { workspace = true } cadcraft-doc = { workspace = true } +craft-image-codecs = { workspace = true } cadcraft-fonts = { workspace = true } tiny-skia = { workspace = true } lyon_tessellation = { workspace = true } diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 8c9205a14..9149d6f02 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -354,7 +354,33 @@ fn premultiplied(r: &cadcraft_doc::Raster) -> Option { Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?) } +/// Encode a premultiplied pixmap as PNG without a second full-frame copy. +pub fn encode_png(pixmap: &Pixmap) -> Option> { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows}; + let width = usize::try_from(pixmap.width()).ok()?.max(1); + let mut rows = pixmap.pixels().chunks_exact(width); + let make_row = |row: &[tiny_skia::PremultipliedColorU8]| { + let rgba = row + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + Image::from_u8(pixmap.width(), 1, ChannelLayout::Rgba, rgba).ok() + }; + let first = make_row(rows.next()?)?; + let mut out = Vec::new(); + let mut encoder = PngRows::new(&mut out, &first, pixmap.height(), &EncodeOptions::default()).ok()?; + encoder.push(&first).ok()?; + for row in rows { + encoder.push(&make_row(row)?).ok()?; + } + encoder.finish().ok()?; + Some(out) +} + /// Render and encode as PNG. pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option> { - render(list, view, o)?.encode_png().ok() + encode_png(&render(list, view, o)?) } diff --git a/crates/render/tests/png_parity.rs b/crates/render/tests/png_parity.rs new file mode 100644 index 000000000..ca53f6419 --- /dev/null +++ b/crates/render/tests/png_parity.rs @@ -0,0 +1,10 @@ +//! The shared PNG writer preserves tiny-skia's straight-alpha export pixels. +#[test] +fn shared_png_matches_tiny_skia_for_premultiplied_pixels() { + let pixmap = + tiny_skia::Pixmap::from_vec(vec![0, 0, 0, 0, 32, 64, 96, 128, 1, 2, 3, 4, 255, 63, 9, 255], tiny_skia::IntSize::from_wh(4, 1).unwrap()) + .unwrap(); + let expected = tiny_skia::Pixmap::decode_png(&pixmap.encode_png().unwrap()).unwrap(); + let actual = tiny_skia::Pixmap::decode_png(&cadcraft_render::raster::encode_png(&pixmap).unwrap()).unwrap(); + assert_eq!(actual.data(), expected.data()); +} diff --git a/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt new file mode 100644 index 000000000..4fcb9b583 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt @@ -0,0 +1,72 @@ +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE new file mode 100644 index 000000000..dae696981 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-MIT b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT new file mode 100644 index 000000000..6a4eb8746 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt new file mode 100644 index 000000000..58e09bf43 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt @@ -0,0 +1,8 @@ +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/licenses/jpeg-encoder-0.6.1/SOURCE.json b/licenses/jpeg-encoder-0.6.1/SOURCE.json new file mode 100644 index 000000000..8a7fb7ab2 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SOURCE.json @@ -0,0 +1,29 @@ +{ + "package": "jpeg-encoder", + "version": "0.6.1", + "source": "https://crates.io/crates/jpeg-encoder/0.6.1", + "registry_checksum": "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f", + "license": "(MIT OR Apache-2.0) AND IJG", + "files": { + "LICENSE-MIT": { + "source": "LICENSE-MIT", + "source_sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503", + "sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503" + }, + "LICENSE-APACHE": { + "source": "LICENSE-APACHE", + "source_sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0", + "sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0" + }, + "IJG-NOTICE.txt": { + "source": "src/fdct.rs", + "source_sha256": "0b59244bbd05b2593ded252ecf0d010a8a4c6ec1d4713b3caeb6fb724586e4d6", + "sha256": "432424ca69caaa82565c0491c11cdab311a2e7d39180970b8ba22017996bf678" + }, + "SIMD-NOTICE.txt": { + "source": "src/avx2/fdct.rs", + "source_sha256": "bc362322f568f92c3699f4ca2922b261c12b7dd997120b01fd3cab58d9d2f9ab", + "sha256": "ee36eeaa9df1f7f09c7046f428ce4a848fcf518394e63d3e2125ec261949e8ba" + } + } +}