From b56176c0a76090f7a0dfb43d6cf728e41c92f369 Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 4 Dec 2026 06:11:56 -0500 Subject: [PATCH 1/6] feat(measure): measure the angle between two arms Adds Kind::Angle and a measure_angle automation tool. The points are an arm end, the apex and the other arm end, plus an optional point the arc passes through (default: half the shorter arm, at least 20 points). The value is the angle in degrees, the short way, in either arm order. The scale's units and factors are not applied; only its decimal mark is. The annotation goes through the existing add() as a PolyLine: the three measured points first, then the arc in 3-degree steps. ISO 32000-2 names no angle intent, so it has no /IT and is marked /PCMeasureKind /Angle, which list() reads back. measure_info takes type "angle". Parity entry comment.measure-angle (partial). Adapted from my own MIT project pdfcer (26059ef4). Refs #8582 Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/dispatch.rs | 1 + crates/automation/src/measure.rs | 3 +- crates/automation/src/tools.rs | 6 +- crates/automation/tests/it/automation.rs | 38 ++++++ crates/engine/src/edit/labels.rs | 1 + crates/measure/README.md | 4 +- crates/measure/src/angle.rs | 140 +++++++++++++++++++++++ crates/measure/src/lib.rs | 37 +++++- crates/measure/src/tests.rs | 66 +++++++++++ parity/acrobat-features.toml | 12 ++ 10 files changed, 298 insertions(+), 10 deletions(-) create mode 100644 crates/measure/src/angle.rs diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 539feb0b26..2147f13f5a 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -852,6 +852,7 @@ impl Automation { "measure_distance" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Distance)?, "measure_perimeter" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Perimeter)?, "measure_area" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Area)?, + "measure_angle" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Angle)?, "measure_info" => self.measurement_info(&a)?, "measure_list" => self.measurement_list(&a)?, "measure_scale" => self.measurement_scale(&a)?, diff --git a/crates/automation/src/measure.rs b/crates/automation/src/measure.rs index 4cce474936..dc641ae2ea 100644 --- a/crates/automation/src/measure.rs +++ b/crates/automation/src/measure.rs @@ -42,7 +42,8 @@ impl Automation { } pub(crate) fn measurement_info(&self, a: &Args) -> Result { let (page, points) = self.measurement_points(a)?; - let kind = Kind::from_name(a.opt_str("type")?.unwrap_or("distance")).ok_or_else(|| failed("type must be distance, perimeter or area"))?; + let kind = + Kind::from_name(a.opt_str("type")?.unwrap_or("distance")).ok_or_else(|| failed("type must be distance, perimeter, area or angle"))?; let at = points.first().copied().ok_or_else(|| failed("measurement needs points"))?; let scale = self.doc(a)?.measurement_scale(page, at).map_err(failed)?; let reading = measure::reading(kind, &points, &scale).map_err(failed)?; diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 7337209e7e..36d119ba36 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -946,8 +946,10 @@ pub fn tools() -> Vec { .cmd("measure.perimeter").with(measure_schema()), t("measure_area", "Measure area", "Add an undoable area annotation from a simple polygon. The last edge closes automatically.") .cmd("measure.area").with(measure_schema()), - t("measure_info", "Read a measurement", "Calculate a live distance, perimeter or area, deltas, angle and scale without adding an annotation. Incomplete paths are allowed.") - .ro().cmd("measure.info").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"points":measure_points(),"type":{"type":"string","enum":["distance","perimeter","area"]}}), &["doc","page","points"])), + t("measure_angle", "Measure angle", "Add an undoable angle annotation: points are an arm end, the apex and the other arm end, plus an optional fourth point the arc passes through (default: half the shorter arm, at least 20 points). The value is in degrees and ignores the scale; the saved polyline draws both arms and the arc.") + .with(measure_schema()), + t("measure_info", "Read a measurement", "Calculate a live distance, perimeter, area or angle between two arms, deltas, angle and scale without adding an annotation. Incomplete paths are allowed.") + .ro().cmd("measure.info").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"points":measure_points(),"type":{"type":"string","enum":["distance","perimeter","area","angle"]}}), &["doc","page","points"])), t("measure_list", "List measurements", "Saved measurement annotations with calculated values, scale and vertices in display coordinates. Measurements with unsupported imported formats (compound or fractional units, non-rectilinear scales) or invalid geometry are listed under unsupported with a reason.") .ro().with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1}}), &["doc"])), t("measure_scale", "Set or read a measurement scale", "Read the scale at a point, or add a rectangular viewport using a ratio (page_distance in page_unit on the page = distance in unit, e.g. 1 mm = 50 mm for a 1:50 plan; page_unit defaults to unit), units_per_point or two calibration points and their real-world distance. Existing measurements retain their original scales. Undoable.") diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index eafe9c6d84..ad6554e441 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -11613,6 +11613,44 @@ fn measurements_calibrate_draw_save_reopen_and_export() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn measure_angle_draws_saves_reopens_and_ignores_the_scale() { + let dir = workdir("measure-angle"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path":"a.pdf"}))["doc"].as_u64().unwrap(); + ok(&mut a, "measure_scale", json!({"doc":doc,"page":1,"page_distance":1,"page_unit":"mm","distance":50,"unit":"mm"})); + let right = json!([[200, 100], [100, 100], [100, 200]]); + let info = ok(&mut a, "measure_info", json!({"doc":doc,"page":1,"type":"angle","points":right})); + assert!((info["reading"]["value"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}"); + ok(&mut a, "measure_angle", json!({"doc":doc,"page":1,"points":right,"label":"Corner"})); + // A fourth point places the arc; a narrower wedge reads smaller. + ok(&mut a, "measure_angle", json!({"doc":doc,"page":1,"points":[[200,300],[100,300],[200,250],[160,280]]})); + let all = ok(&mut a, "measure_list", json!({"doc":doc})); + let [first, second] = all["measurements"].as_array().unwrap().as_slice() else { panic!("{all}") }; + assert_eq!((&first["reading"]["kind"], &first["label"]), (&json!("angle"), &json!("Corner"))); + assert_eq!(first["points"], json!([[200.0, 100.0], [100.0, 100.0], [100.0, 200.0]])); + assert!(first["reading"]["label"].as_str().unwrap().ends_with('\u{b0}')); + assert!(second["reading"]["value"].as_f64().unwrap() < first["reading"]["value"].as_f64().unwrap()); + // The saved polyline draws more than the three measured points: the arc. + let comments = ok(&mut a, "comment_list", json!({"doc":doc})); + let drawn = comments["comments"][0]["points"].as_array().map_or(0, Vec::len); + assert!(drawn > 3, "{comments}"); + ok(&mut a, "edit_undo", json!({"doc":doc})); + assert_eq!(ok(&mut a, "measure_list", json!({"doc":doc}))["count"], 1); + ok(&mut a, "edit_redo", json!({"doc":doc})); + ok(&mut a, "doc_save", json!({"doc":doc,"path":"angle.pdf"})); + let reopened = ok(&mut a, "doc_open", json!({"path":"angle.pdf"}))["doc"].as_u64().unwrap(); + assert_eq!(ok(&mut a, "measure_list", json!({"doc":reopened}))["measurements"], all["measurements"]); + let before = ok(&mut a, "doc_list", json!({})); + for points in + [json!([[200, 100], [100, 100]]), json!([[200, 100], [100, 100], [300, 100]]), json!([[200, 100], [100, 100], [100, 200], [100, 100]])] + { + assert!(a.call("measure_angle", &json!({"doc":doc,"page":1,"points":points})).is_err(), "{points}"); + assert_eq!(ok(&mut a, "doc_list", json!({})), before); + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn measurement_scale_ratio_takes_the_page_side_in_a_unit() { // #2752: a plan drawn at 1:50 is "1 mm = 50 mm", so a line 10 mm long on the page is 500 mm. diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index 51d19043e4..fd960734df 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -225,6 +225,7 @@ impl Edit { pdfcraft_measure::Kind::Distance => "Measure distance", pdfcraft_measure::Kind::Perimeter => "Measure perimeter", pdfcraft_measure::Kind::Area => "Measure area", + pdfcraft_measure::Kind::Angle => "Measure angle", }), Edit::SetMeasurementScale { .. } => Label::of("Set measurement scale"), Edit::AddAnnotation(a) => Label::of(add_annotation(&a.shape)), diff --git a/crates/measure/README.md b/crates/measure/README.md index 292fcc4a3c..661c132a5d 100644 --- a/crates/measure/README.md +++ b/crates/measure/README.md @@ -6,10 +6,12 @@ Measurements are ordinary Line, PolyLine or Polygon annotations with a rectiline Scale::calibrate derives a conversion from two points and a known real-world distance. Scale::ratio takes a scale as a plan writes it, `1 mm = 50 mm` at 1:50: its page side is in pt, in, mm or cm and is converted to points, so the stored /X, /D and /A factors stay per user-space unit and the /R string keeps the units as entered. Scales read from files are used as stored. set_scale appends a named rectangular page viewport, preserving existing viewports. scale_at selects the last viewport containing the first measurement vertex. Default measurements account for UserUnit; display-coordinate conversion accounts for crop boxes and page rotation. -The desktop Measure objects panel exposes all three tools, live values and coordinate deltas, 45-degree constraints, vertex cancellation, snapping, calibration and CSV export. Automation provides measure_distance, measure_perimeter, measure_area, measure_info, measure_list, measure_scale, measure_snap and measure_export. The panel's drawing scale and measure_scale's `page_distance`/`page_unit` give the page side in a unit, by default the real-world one. Tool coordinates and explicit units-per-point scales use physical display points. +The desktop Measure objects panel exposes all three tools, live values and coordinate deltas, 45-degree constraints, vertex cancellation, snapping, calibration and CSV export. Automation provides measure_distance, measure_perimeter, measure_area, measure_angle, measure_info, measure_list, measure_scale, measure_snap and measure_export. The panel's drawing scale and measure_scale's `page_distance`/`page_unit` give the page side in a unit, by default the real-world one. Tool coordinates and explicit units-per-point scales use physical display points. Snapping interprets painted paths and nested Form XObjects, including graphics-state transforms. Cubic paths are flattened to a maximum deviation of 0.2 user units. Raster edges, glyph outlines, clipping and optional-content visibility are not interpreted. Extraction stops at 8,000,000 segments, 24,000,000 endpoint and midpoint targets, 512 MiB of decoded content, 4,096 streams, 32 nested forms or 256 nested `q`; intersection searches use at most 256 nearby segments. Extraction is lenient: a content stream that can't be decoded is skipped and counted, and the rest of the page still snaps. The UI and automation report these limits. Imported single-unit decimal rectilinear scales support differing X and Y conversion factors when CYX is present. Unit labels are text strings and may be non-ASCII ("m²"). Imported compound units (such as feet and inches, up to 8 units), fractions and values cut off to whole units (ISO 32000-2 §12.9.2 number format arrays) are read too: readings are labelled with them (`3 ft 6 1/2 in`, a last unit that rounds up carrying into the one before) and a measurement added with such a scale writes them back. Authoring them, differing coordinate and distance units, and non-rectilinear scales are not supported: `list` reports such measurements, and ones with invalid geometry, under `unsupported` with a reason instead of failing, and leaves their PDF data untouched. A polygon whose last vertex repeats the first is treated as closed. Interoperability with Acrobat-authored measurements is untested. Geospatial and 3D measuring are outside this component. +An angle measurement (`angle`) reads the angle at an apex between two arms, in degrees; it ignores the scale's units and factors (an angle is the same at any scale) and uses only its decimal mark. It is saved as a PolyLine whose first three vertices are the measured points, followed by the dimension arc. ISO 32000-2 names no angle intent, so it carries no /IT and is marked with the private key /PCMeasureKind /Angle. + Synthetic tests cover geometry, calibration, viewport precedence, coordinate transforms, saved annotations and captions, snapping targets, cyclic forms, malformed arguments, permissions, undo, save/reopen, rendering and spreadsheet-safe CSV. No sample PDF or font assets are added. diff --git a/crates/measure/src/angle.rs b/crates/measure/src/angle.rs new file mode 100644 index 0000000000..009b7825f6 --- /dev/null +++ b/crates/measure/src/angle.rs @@ -0,0 +1,140 @@ +//! Angle measurements: the angle at an apex between two arms, saved as a polyline that draws the +//! arms and a dimension arc between them. +//! +//! An angle does not change with the drawing's scale (30° on a 1:50 plan is 30°), so the scale's +//! factors and units never touch it; only its decimal mark is used. ISO 32000-2 §12.5.6.9 names no +//! angle intent, so the annotation carries no `/IT` and is recognised by `/PCMeasureKind /Angle`. +use crate::{Kind, Point, Reading, Result, Scale, check_points, distance, invalid}; + +/// The arc is drawn in steps of this many degrees, so its chord error stays bounded whatever the +/// sweep (at a 200-point radius about 0.07 pt) and a half turn costs at most 60 segments. +const ARC_STEP_DEGREES: f64 = 3.0; +/// Without a point to pass through, the arc sits at this fraction of the shorter arm. +pub const DEFAULT_ARC_FRACTION: f64 = 0.5; +/// The smallest default arc radius, in user units, so short arms still get a visible arc. +pub const MIN_ARC_RADIUS: f64 = 20.0; +/// Points closer than this are the same point. +const SAME: f64 = 1e-6; +/// The private key that marks a polyline as an angle measurement, and its value. +pub const KIND_KEY: &[u8] = b"PCMeasureKind"; +pub const KIND_VALUE: &str = "Angle"; + +/// The unit direction from `from` to `to`, or `None` when they are the same point. +fn unit(from: Point, to: Point) -> Option { + let len = distance(from, to); + (len.is_finite() && len >= SAME).then(|| [(to[0] - from[0]) / len, (to[1] - from[1]) / len]) +} + +/// The arms' unit directions for `[a, apex, b, ..]`. +fn arms(points: &[Point]) -> Result<(Point, Point, Point)> { + let [a, apex, b, ..] = points else { return Err(invalid("an angle needs three points: arm, apex, arm")) }; + let da = unit(*apex, *a).ok_or_else(|| invalid("an angle's arms must not have zero length"))?; + let db = unit(*apex, *b).ok_or_else(|| invalid("an angle's arms must not have zero length"))?; + Ok((*apex, da, db)) +} + +/// Degrees between the rays apex→a and apex→b, from 0 to 180. +pub fn degrees(points: &[Point]) -> Result { + let (_, da, db) = arms(points)?; + let dot = da[0].mul_add(db[0], da[1] * db[1]).clamp(-1.0, 1.0); + Ok(dot.acos().to_degrees()) +} + +/// The arc as `(start, sweep)` in radians: from `dir_a`, the short way to `dir_b`, the sweep in +/// (-π, π]. Each `atan2` is in (-π, π], so each loop runs at most once. +pub fn arc(dir_a: Point, dir_b: Point) -> (f64, f64) { + let a0 = dir_a[1].atan2(dir_a[0]); + let mut sweep = dir_b[1].atan2(dir_b[0]) - a0; + while sweep > std::f64::consts::PI { + sweep -= std::f64::consts::TAU; + } + while sweep <= -std::f64::consts::PI { + sweep += std::f64::consts::TAU; + } + (a0, sweep) +} + +/// `degrees` with one decimal and the scale's decimal mark, then a degree sign. The precision is +/// fixed: angular precision and degree-minute-second display are not offered yet. +pub fn label(degrees: f64, scale: &Scale) -> String { + let text = format!("{degrees:.1}"); + let mark = scale.formats.as_ref().and_then(|f| f.distance.first()).map(|f| f.decimal.as_str()).filter(|m| !m.is_empty()); + let text = match mark { + Some(m) => text.replacen('.', m, 1), + None => text, + }; + format!("{text}\u{b0}") +} + +/// The reading for `[a, apex, b, ..]`: the angle in degrees. Deltas, length and area are zero. +pub(crate) fn reading(points: &[Point], scale: &Scale) -> Result { + let value = degrees(points)?; + Ok(Reading { + kind: Kind::Angle, + value, + unit: "\u{b0}".into(), + label: label(value, scale), + delta_x: 0.0, + delta_y: 0.0, + angle: value, + length: 0.0, + area: 0.0, + }) +} + +/// Checks an angle's points: `[a, apex, b]`, or a fourth point the arc passes through. +pub(crate) fn validate(points: &[Point]) -> Result<()> { + check_points(points)?; + if !(3..=4).contains(&points.len()) { + return Err(invalid("an angle needs arm, apex and arm points, and at most one point for its arc")); + } + // Arms along each other read 0° and `add` refuses a zero value; an arc point on the apex is + // refused by `radius`. + arms(points).map(|_| ()) +} + +/// The arc radius: through the fourth point, else half the shorter arm and at least +/// [`MIN_ARC_RADIUS`]. +pub fn radius(points: &[Point]) -> Result { + let [a, apex, b, rest @ ..] = points else { return Err(invalid("an angle needs three points: arm, apex, arm")) }; + let r = match rest.first() { + Some(through) => distance(*apex, *through), + None => (distance(*apex, *a).min(distance(*apex, *b)) * DEFAULT_ARC_FRACTION).max(MIN_ARC_RADIUS), + }; + if !(r.is_finite() && r >= SAME) { + return Err(invalid("an angle's arc radius must be positive")); + } + Ok(r) +} + +/// The polyline drawn for `[a, apex, b, (through)]`: arm a, the apex, arm b, out (or back) along +/// arm b to the arc, the arc back to arm a, then out along arm a when the arc lies beyond it. +/// The first three vertices are always the measured points, which is how a saved angle is read. +pub fn path(points: &[Point]) -> Result> { + validate(points)?; + let (apex, da, db) = arms(points)?; + let r = radius(points)?; + let (a0, sweep) = arc(da, db); + let step = ARC_STEP_DEGREES.to_radians(); + let steps = (sweep.abs() / step).ceil().clamp(1.0, 60.0); + let mut out: Vec = points.iter().take(3).copied().collect(); + let mut i = steps; + while i >= 0.0 { + let angle = (i / steps).mul_add(sweep, a0); + push_distinct(&mut out, [angle.cos().mul_add(r, apex[0]), angle.sin().mul_add(r, apex[1])]); + i -= 1.0; + } + if let Some(a) = points.first() + && r > distance(apex, *a) + { + push_distinct(&mut out, *a); + } + check_points(&out)?; + Ok(out) +} + +fn push_distinct(out: &mut Vec, p: Point) { + if out.last().is_none_or(|q| distance(*q, p) >= SAME) { + out.push(p); + } +} diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index 67efab1a9a..21ce143b9a 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -3,6 +3,7 @@ //! annotations use the measurement intents of line, polygon and polyline annotations (§12.5.6). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod angle; pub mod number_format; pub mod snap; use number_format::{Formats, NumberFormat}; @@ -32,6 +33,7 @@ pub enum Kind { Distance, Perimeter, Area, + Angle, } impl Kind { pub fn name(self) -> &'static str { @@ -39,6 +41,7 @@ impl Kind { Self::Distance => "distance", Self::Perimeter => "perimeter", Self::Area => "area", + Self::Angle => "angle", } } pub fn from_name(s: &str) -> Option { @@ -46,14 +49,17 @@ impl Kind { "distance" => Some(Self::Distance), "perimeter" => Some(Self::Perimeter), "area" => Some(Self::Area), + "angle" => Some(Self::Angle), _ => None, } } - fn intent(self) -> &'static str { + /// The standard `/IT`; ISO 32000-2 names none for an angle. + fn intent(self) -> Option<&'static str> { match self { - Self::Distance => "LineDimension", - Self::Perimeter => "PolyLineDimension", - Self::Area => "PolygonDimension", + Self::Distance => Some("LineDimension"), + Self::Perimeter => Some("PolyLineDimension"), + Self::Area => Some("PolygonDimension"), + Self::Angle => None, } } } @@ -331,6 +337,9 @@ pub struct Reading { pub fn reading(kind: Kind, points: &[Point], scale: &Scale) -> Result { check_points(points)?; scale.validate()?; + if kind == Kind::Angle { + return angle::reading(points, scale); + } let points = if kind == Kind::Area { open_polygon(points) } else { points }; let mut length = 0.0; for w in points.windows(2) { @@ -394,6 +403,9 @@ pub fn open_polygon(points: &[Point]) -> &[Point] { } } fn validate_geometry(kind: Kind, points: &[Point]) -> Result<()> { + if kind == Kind::Angle { + return angle::validate(points); + } check_points(points)?; let points = if kind == Kind::Area { open_polygon(points) } else { points }; match kind { @@ -458,6 +470,9 @@ pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result Shape::Polygon { vertices: new.points.clone(), cloud: false }, + Kind::Angle => { + Shape::PolyLine { vertices: angle::path(&new.points)?, start: pdfcraft_annot::LineEnding::None, end: pdfcraft_annot::LineEnding::None } + } }; let index = pdfcraft_annot::add_annotation( doc, @@ -465,7 +480,10 @@ pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result d.set(b"IT".to_vec(), Object::name(it)), + None => d.set(angle::KIND_KEY.to_vec(), Object::name(angle::KIND_VALUE)), + } d.set(b"Measure".to_vec(), Object::Dict(new.scale.dictionary()?)); d.set(b"Subj".to_vec(), PdfString::text(new.kind.name())); d.set(b"PCMeasureLabel".to_vec(), PdfString::text(&new.label)); @@ -552,7 +570,11 @@ fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: us return Err(invalid("invalid measurement vertex count")); } let v: Vec = a.iter().map(|n| doc.resolve(n).as_f64().ok_or_else(|| invalid("invalid vertex"))).collect::>()?; - let points: Vec = v.as_chunks::<2>().0.to_vec(); + let mut points: Vec = v.as_chunks::<2>().0.to_vec(); + // A saved angle's first three vertices are the measured points; the rest draw its arc. + if kind == Kind::Angle { + points.truncate(3); + } validate_geometry(kind, &points)?; let reading = reading(kind, &points, &scale)?; Ok(Measurement { @@ -598,6 +620,9 @@ pub fn list(doc: &Document) -> Listing { Some(b"LineDimension") => Kind::Distance, Some(b"PolyLineDimension") => Kind::Perimeter, Some(b"PolygonDimension") => Kind::Area, + _ if d.get(angle::KIND_KEY).map(|o| doc.resolve(o)).as_deref().and_then(Object::as_name) == Some(angle::KIND_VALUE.as_bytes()) => { + Kind::Angle + } _ => continue, }; // An area's boundary check compares every pair of edges: charge it before reading the diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 80c09d039f..bb6161208c 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -709,3 +709,69 @@ fn a_compound_y_keeps_its_units_and_cyx() { overflow_y.y = 2.0; assert!(overflow_y.dictionary().is_err()); } +#[test] +fn an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale() { + let scale = Scale::new(2.0, "m", 3).unwrap(); + let plan = Scale::new(50.0, "mm", 1).unwrap(); + let right = reading(Kind::Angle, &[[20.0, 10.0], [10.0, 10.0], [10.0, 30.0]], &scale).unwrap(); + close(right.value, 90.0); + assert!(right.label.ends_with('\u{b0}'), "{}", right.label); + // Swapping the arms or changing the scale changes nothing. + for (points, s) in [([[10.0, 30.0], [10.0, 10.0], [20.0, 10.0]], &scale), ([[20.0, 10.0], [10.0, 10.0], [10.0, 30.0]], &plan)] { + close(reading(Kind::Angle, &points, s).unwrap().value, right.value); + } + // Arms either side of the -x axis: the wedge between them is narrow, not the reflex angle. + let narrow = reading(Kind::Angle, &[[-10.0, 1.0], [0.0, 0.0], [-10.0, -1.0]], &scale).unwrap(); + assert!(narrow.value < 20.0, "{}", narrow.value); + assert!(reading(Kind::Angle, &[[20.0, 10.0], [10.0, 10.0]], &scale).is_err()); +} +#[test] +fn an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge() { + let apex = [0.0, 0.0]; + // Arms either side of the -x axis, where the raw atan2 difference is the long way round. + let (a, b) = ([-100.0, 10.0], [-100.0, -10.0]); + for points in [vec![a, apex, b], vec![a, apex, b, [-30.0, 0.0]], vec![a, apex, b, [-150.0, 0.0]]] { + let path = angle::path(&points).unwrap(); + assert_eq!(path[..3], points[..3]); + let r = angle::radius(&points).unwrap(); + let wedge = angle::degrees(&points).unwrap(); + // Every arc vertex is on one circle, between the two arms. + let arc: Vec = path[3..].iter().copied().filter(|p| (distance(apex, *p) - r).abs() < 1e-6).collect(); + assert!(arc.len() > 2, "{path:?}"); + for p in &arc { + let to_a = angle::degrees(&[a, apex, *p]).unwrap(); + let to_b = angle::degrees(&[*p, apex, b]).unwrap(); + assert!((to_a + to_b - wedge).abs() < 1e-6, "{p:?} is outside the wedge"); + } + // An arc beyond the arms ends back on arm a's end, so the arm reaches the arc. + if r > distance(apex, a) { + assert_eq!(path.last(), Some(&a)); + } + } +} +#[test] +fn an_angle_saves_reopens_and_lists_with_its_three_points() { + let mut d = fixture("", "", &[]); + let meta = Meta { date: None, id: "angle".into() }; + let points = vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0]]; + add(&mut d, &new(Kind::Angle, points.clone()), &meta).unwrap(); + let (_, dict) = annot(&d, 0, 0).unwrap(); + assert_eq!(dict.name(b"Subtype"), Some(&b"PolyLine"[..])); + assert_eq!(dict.get(b"IT"), None); + let ap = d.resolve(dict.get(b"AP").unwrap()); + let normal = d.resolve(ap.as_dict().unwrap().get(b"N").unwrap()); + let Object::Stream(stream) = normal.as_ref() else { panic!("appearance missing") }; + assert!(String::from_utf8_lossy(&stream.decoded().unwrap()).contains("(90.0")); + let bytes = write_full(&d, &SaveOptions::default()).unwrap(); + let reopened = Document::open(Arc::new(bytes)).unwrap(); + let listing = list(&reopened); + assert_eq!(listing.unsupported, vec![]); + let [m] = &listing.measurements[..] else { panic!("{listing:?}") }; + assert_eq!((m.reading.kind, &m.points), (Kind::Angle, &points)); + close(m.reading.value, 90.0); + // Arms along each other measure nothing. + let mut d = fixture("", "", &[]); + assert!(add(&mut d, &new(Kind::Angle, vec![[200.0, 100.0], [100.0, 100.0], [300.0, 100.0]]), &meta).is_err()); + assert!(add(&mut d, &new(Kind::Angle, vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0], [100.0, 100.0]]), &meta).is_err()); + assert!(list(&d).measurements.is_empty()); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 6d6024f1b1..e75b5c638b 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4487,6 +4487,18 @@ tools = ["measure_area"] evidence = ["crates/automation/tests/it/automation.rs::measurements_calibrate_draw_save_reopen_and_export", "crates/measure/src/tests.rs::calibrated_lengths_concave_areas_and_axis_scales", "crates/ui-egui/tests/it/control.rs::measurement_tools_draw_live_calibrate_save_and_export"] notes = "Simple polygon areas, including concave boundaries and either winding. Self-intersecting boundaries are refused. Saved PolygonDimension annotations; no 3D surface measurement." +[[feature]] +id = "comment.measure-angle" +title = "Angle measuring tool" +area = "E" +tier = "P3" +milestone = "M12" +status = "partial" +commands = [] +tools = ["measure_angle"] +evidence = ["crates/automation/tests/it/automation.rs::measure_angle_draws_saves_reopens_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge", "crates/measure/src/tests.rs::an_angle_saves_reopens_and_lists_with_its_three_points"] +notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, through an optional fourth point, else half the shorter arm and at least 20 points); measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." + [[feature]] id = "comment.measure-scale" title = "Scale ratio and calibration per viewport" From 8f9e8e8c868294ae61f98afee161a8efb72d99c6 Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 4 Dec 2026 06:26:06 -0500 Subject: [PATCH 2/6] fix(measure): refuse an angle its label would show as 0.0 An angle under 0.05 degrees rounds to 0.0 in the one-decimal label, so `add` now refuses it with MeasureError::AngleTooSmall. Saved angles below it are still read. The tool text and parity note say 20 user units, not points. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/tools.rs | 2 +- crates/measure/src/angle.rs | 3 +++ crates/measure/src/lib.rs | 6 ++++++ crates/measure/src/tests.rs | 10 ++++++++++ parity/acrobat-features.toml | 4 ++-- 5 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 36d119ba36..91605f1cf0 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -946,7 +946,7 @@ pub fn tools() -> Vec { .cmd("measure.perimeter").with(measure_schema()), t("measure_area", "Measure area", "Add an undoable area annotation from a simple polygon. The last edge closes automatically.") .cmd("measure.area").with(measure_schema()), - t("measure_angle", "Measure angle", "Add an undoable angle annotation: points are an arm end, the apex and the other arm end, plus an optional fourth point the arc passes through (default: half the shorter arm, at least 20 points). The value is in degrees and ignores the scale; the saved polyline draws both arms and the arc.") + t("measure_angle", "Measure angle", "Add an undoable angle annotation: points are an arm end, the apex and the other arm end, plus an optional fourth point the arc passes through (default: half the shorter arm, at least 20 user units). The value is in degrees and ignores the scale; an angle under 0.05°, which would be labelled 0.0°, is refused. The saved polyline draws both arms and the arc.") .with(measure_schema()), t("measure_info", "Read a measurement", "Calculate a live distance, perimeter, area or angle between two arms, deltas, angle and scale without adding an annotation. Incomplete paths are allowed.") .ro().cmd("measure.info").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"points":measure_points(),"type":{"type":"string","enum":["distance","perimeter","area","angle"]}}), &["doc","page","points"])), diff --git a/crates/measure/src/angle.rs b/crates/measure/src/angle.rs index 009b7825f6..790e3cd546 100644 --- a/crates/measure/src/angle.rs +++ b/crates/measure/src/angle.rs @@ -13,6 +13,9 @@ const ARC_STEP_DEGREES: f64 = 3.0; pub const DEFAULT_ARC_FRACTION: f64 = 0.5; /// The smallest default arc radius, in user units, so short arms still get a visible arc. pub const MIN_ARC_RADIUS: f64 = 20.0; +/// The smallest angle `add` accepts: half the label's last digit, since anything smaller is +/// labelled 0.0°. Saved angles below it are still read. +pub const MIN_DEGREES: f64 = 0.05; /// Points closer than this are the same point. const SAME: f64 = 1e-6; /// The private key that marks a polyline as an angle measurement, and its value. diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index 21ce143b9a..bedea7700e 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -21,6 +21,9 @@ pub enum MeasureError { Invalid(String), #[error(transparent)] Annotation(#[from] pdfcraft_annot::AnnotError), + /// An angle smaller than [`angle::MIN_DEGREES`], which its label would show as 0.0°. + #[error("an angle of {degrees:.3}° is under {min}° and would be labelled 0.0°")] + AngleTooSmall { degrees: f64, min: f64 }, } type Result = std::result::Result; fn invalid(s: &str) -> MeasureError { @@ -453,6 +456,9 @@ fn annot(doc: &Document, page_index: usize, index: usize) -> Result<(ObjRef, Dic pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result { validate_geometry(new.kind, &new.points)?; let info = reading(new.kind, &new.points, &new.scale)?; + if new.kind == Kind::Angle && info.value < angle::MIN_DEGREES { + return Err(MeasureError::AngleTooSmall { degrees: info.value, min: angle::MIN_DEGREES }); + } if info.value <= 0.0 { return Err(invalid("measurement must have a positive length or area")); } diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index bb6161208c..1adb2d145f 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -750,6 +750,16 @@ fn an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge() { } } #[test] +fn an_angle_too_small_to_label_is_refused_by_name() { + let mut d = fixture("", "", &[]); + let meta = Meta { date: None, id: "angle".into() }; + // About 0.029°, which one decimal would show as 0.0°. + let tiny = add(&mut d, &new(Kind::Angle, vec![[1100.0, 100.0], [100.0, 100.0], [1100.0, 100.5]]), &meta); + assert!(matches!(tiny, Err(MeasureError::AngleTooSmall { degrees, .. }) if degrees > 0.0 && degrees < angle::MIN_DEGREES), "{tiny:?}"); + // About 0.086°, labelled 0.1°, is kept. + add(&mut d, &new(Kind::Angle, vec![[1100.0, 100.0], [100.0, 100.0], [1100.0, 101.5]]), &meta).unwrap(); +} +#[test] fn an_angle_saves_reopens_and_lists_with_its_three_points() { let mut d = fixture("", "", &[]); let meta = Meta { date: None, id: "angle".into() }; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index e75b5c638b..c5fb45898f 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4496,8 +4496,8 @@ milestone = "M12" status = "partial" commands = [] tools = ["measure_angle"] -evidence = ["crates/automation/tests/it/automation.rs::measure_angle_draws_saves_reopens_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge", "crates/measure/src/tests.rs::an_angle_saves_reopens_and_lists_with_its_three_points"] -notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, through an optional fourth point, else half the shorter arm and at least 20 points); measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." +evidence = ["crates/automation/tests/it/automation.rs::measure_angle_draws_saves_reopens_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge", "crates/measure/src/tests.rs::an_angle_saves_reopens_and_lists_with_its_three_points", "crates/measure/src/tests.rs::an_angle_too_small_to_label_is_refused_by_name"] +notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, through an optional fourth point, else half the shorter arm and at least 20 user units); an angle under 0.05 degrees, which would be labelled 0.0, is refused; measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." [[feature]] id = "comment.measure-scale" From c8847d46c7c56aff49eeb47bf984cdd06ebb2c76 Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:34:46 -0500 Subject: [PATCH 3/6] docs(measure): the fourth angle point sets the arc radius The arc always stays in the smaller wedge; the optional fourth point sets its radius by its distance from the apex, so the arc meets that point only when it lies inside the wedge. Tool description, angle docs and parity note now say so. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/tools.rs | 2 +- crates/measure/src/angle.rs | 9 +++++---- parity/acrobat-features.toml | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 91605f1cf0..f0af11d29a 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -946,7 +946,7 @@ pub fn tools() -> Vec { .cmd("measure.perimeter").with(measure_schema()), t("measure_area", "Measure area", "Add an undoable area annotation from a simple polygon. The last edge closes automatically.") .cmd("measure.area").with(measure_schema()), - t("measure_angle", "Measure angle", "Add an undoable angle annotation: points are an arm end, the apex and the other arm end, plus an optional fourth point the arc passes through (default: half the shorter arm, at least 20 user units). The value is in degrees and ignores the scale; an angle under 0.05°, which would be labelled 0.0°, is refused. The saved polyline draws both arms and the arc.") + t("measure_angle", "Measure angle", "Add an undoable angle annotation: points are an arm end, the apex and the other arm end, plus an optional fourth point whose distance from the apex sets the arc radius (the arc stays in the smaller wedge, so it passes through that point only when the point lies inside it; default: half the shorter arm, at least 20 user units). The value is in degrees and ignores the scale; an angle under 0.05°, which would be labelled 0.0°, is refused. The saved polyline draws both arms and the arc.") .with(measure_schema()), t("measure_info", "Read a measurement", "Calculate a live distance, perimeter, area or angle between two arms, deltas, angle and scale without adding an annotation. Incomplete paths are allowed.") .ro().cmd("measure.info").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"points":measure_points(),"type":{"type":"string","enum":["distance","perimeter","area","angle"]}}), &["doc","page","points"])), diff --git a/crates/measure/src/angle.rs b/crates/measure/src/angle.rs index 790e3cd546..03006e66cc 100644 --- a/crates/measure/src/angle.rs +++ b/crates/measure/src/angle.rs @@ -9,7 +9,7 @@ use crate::{Kind, Point, Reading, Result, Scale, check_points, distance, invalid /// The arc is drawn in steps of this many degrees, so its chord error stays bounded whatever the /// sweep (at a 200-point radius about 0.07 pt) and a half turn costs at most 60 segments. const ARC_STEP_DEGREES: f64 = 3.0; -/// Without a point to pass through, the arc sits at this fraction of the shorter arm. +/// Without a fourth point, the arc sits at this fraction of the shorter arm. pub const DEFAULT_ARC_FRACTION: f64 = 0.5; /// The smallest default arc radius, in user units, so short arms still get a visible arc. pub const MIN_ARC_RADIUS: f64 = 20.0; @@ -85,7 +85,7 @@ pub(crate) fn reading(points: &[Point], scale: &Scale) -> Result { }) } -/// Checks an angle's points: `[a, apex, b]`, or a fourth point the arc passes through. +/// Checks an angle's points: `[a, apex, b]`, or a fourth point that sets the arc radius. pub(crate) fn validate(points: &[Point]) -> Result<()> { check_points(points)?; if !(3..=4).contains(&points.len()) { @@ -96,7 +96,8 @@ pub(crate) fn validate(points: &[Point]) -> Result<()> { arms(points).map(|_| ()) } -/// The arc radius: through the fourth point, else half the shorter arm and at least +/// The arc radius: the fourth point's distance from the apex (the arc stays in the smaller +/// wedge, so it meets that point only when the point lies inside it), else half the shorter arm and at least /// [`MIN_ARC_RADIUS`]. pub fn radius(points: &[Point]) -> Result { let [a, apex, b, rest @ ..] = points else { return Err(invalid("an angle needs three points: arm, apex, arm")) }; @@ -110,7 +111,7 @@ pub fn radius(points: &[Point]) -> Result { Ok(r) } -/// The polyline drawn for `[a, apex, b, (through)]`: arm a, the apex, arm b, out (or back) along +/// The polyline drawn for `[a, apex, b, (radius point)]`: arm a, the apex, arm b, out (or back) along /// arm b to the arc, the arc back to arm a, then out along arm a when the arc lies beyond it. /// The first three vertices are always the measured points, which is how a saved angle is read. pub fn path(points: &[Point]) -> Result> { diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c5fb45898f..496ba9514c 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4497,7 +4497,7 @@ status = "partial" commands = [] tools = ["measure_angle"] evidence = ["crates/automation/tests/it/automation.rs::measure_angle_draws_saves_reopens_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge", "crates/measure/src/tests.rs::an_angle_saves_reopens_and_lists_with_its_three_points", "crates/measure/src/tests.rs::an_angle_too_small_to_label_is_refused_by_name"] -notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, through an optional fourth point, else half the shorter arm and at least 20 user units); an angle under 0.05 degrees, which would be labelled 0.0, is refused; measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." +notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, always in the smaller wedge; an optional fourth point sets its radius by its distance from the apex, else half the shorter arm and at least 20 user units); an angle under 0.05 degrees, which would be labelled 0.0, is refused; measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." [[feature]] id = "comment.measure-scale" From 93e866480cc24615fe0f6fe81f1cb7a4104c6dd6 Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:54:40 -0500 Subject: [PATCH 4/6] fix(measure): save angles without a scale An angle has no length, so a /Measure on it lets a reader apply the scale to the vertices and show a length. Angles now carry no /Measure. Read back, an angle without one takes its decimal mark from the scale at its first point. set_points also refuses /PCMeasureKind annotations, since an angle's points are where it measured. Co-Authored-By: Claude Opus 5.5 --- crates/annot/src/modify.rs | 3 ++- crates/measure/src/angle.rs | 3 ++- crates/measure/src/lib.rs | 17 +++++++++++++++-- crates/measure/src/tests.rs | 28 ++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/annot/src/modify.rs b/crates/annot/src/modify.rs index 6566337ca1..56e8e2e59f 100644 --- a/crates/annot/src/modify.rs +++ b/crates/annot/src/modify.rs @@ -816,7 +816,8 @@ pub fn set_points(doc: &mut Document, page: usize, index: usize, points: &[[f64; let (_, r) = annot_ref(doc, page, index)?; unlocked(doc, r)?; let d = annot_dict(doc, r); - if d.contains(b"Measure") { + // A measurement kind saved without a scale (an angle) is recognised by `/PCMeasureKind`. + if d.contains(b"Measure") || d.contains(b"PCMeasureKind") { return Err(AnnotError::Invalid("a measurement's points are where it measured".into())); } if points.len() > MAX_POINTS { diff --git a/crates/measure/src/angle.rs b/crates/measure/src/angle.rs index 03006e66cc..809cc10d54 100644 --- a/crates/measure/src/angle.rs +++ b/crates/measure/src/angle.rs @@ -3,7 +3,8 @@ //! //! An angle does not change with the drawing's scale (30° on a 1:50 plan is 30°), so the scale's //! factors and units never touch it; only its decimal mark is used. ISO 32000-2 §12.5.6.9 names no -//! angle intent, so the annotation carries no `/IT` and is recognised by `/PCMeasureKind /Angle`. +//! angle intent, so the annotation carries no `/IT` and is recognised by `/PCMeasureKind /Angle`. It +//! carries no `/Measure` either; read back, it takes its decimal mark from the scale at its first point. use crate::{Kind, Point, Reading, Result, Scale, check_points, distance, invalid}; /// The arc is drawn in steps of this many degrees, so its chord error stays bounded whatever the diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index bedea7700e..ebe30797de 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -490,7 +490,11 @@ pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result d.set(b"IT".to_vec(), Object::name(it)), None => d.set(angle::KIND_KEY.to_vec(), Object::name(angle::KIND_VALUE)), } - d.set(b"Measure".to_vec(), Object::Dict(new.scale.dictionary()?)); + // An angle has no length, so it carries no scale: a reader applying one to its vertices would + // show a length. + if new.kind != Kind::Angle { + d.set(b"Measure".to_vec(), Object::Dict(new.scale.dictionary()?)); + } d.set(b"Subj".to_vec(), PdfString::text(new.kind.name())); d.set(b"PCMeasureLabel".to_vec(), PdfString::text(&new.label)); d.set(b"PCMeasureValue".to_vec(), PdfString::text(&info.label)); @@ -568,7 +572,9 @@ fn scale_of(doc: &Document, d: &Dict, scales: &mut Scales) -> Result { } fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: usize, scales: &mut Scales) -> Result { - let scale = scale_of(doc, d, scales)?; + // An angle saved without `/Measure` takes its decimal mark from the scale at its first point, + // as it was given when drawn. + let saved = if kind == Kind::Angle && !d.contains(b"Measure") { None } else { Some(scale_of(doc, d, scales)?) }; let key = if kind == Kind::Distance { &b"L"[..] } else { b"Vertices" }; let o = doc.resolve(d.get(key).ok_or_else(|| invalid("measurement has no vertices"))?); let a = o.as_array().ok_or_else(|| invalid("invalid measurement vertices"))?; @@ -582,6 +588,10 @@ fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: us points.truncate(3); } validate_geometry(kind, &points)?; + let scale = match saved { + Some(scale) => scale, + None => points.first().and_then(|at| scale_at(doc, page, *at).ok()).unwrap_or_default(), + }; let reading = reading(kind, &points, &scale)?; Ok(Measurement { page, @@ -646,6 +656,9 @@ pub fn list(doc: &Document) -> Listing { continue; } work = work.saturating_add(n.saturating_mul(n)); + } else if kind == Kind::Angle && !d.contains(b"Measure") { + // Its scale is looked up among the page's viewports. + work = work.saturating_add(n.max(1)).saturating_add(MAX_VIEWPORTS); } else { work = work.saturating_add(n.max(1)); } diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 1adb2d145f..2184f0c408 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -785,3 +785,31 @@ fn an_angle_saves_reopens_and_lists_with_its_three_points() { assert!(add(&mut d, &new(Kind::Angle, vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0], [100.0, 100.0]]), &meta).is_err()); assert!(list(&d).measurements.is_empty()); } +#[test] +fn an_angle_is_saved_without_a_scale() { + let mut d = fixture("", "", &[]); + let meta = Meta { date: None, id: "angle".into() }; + add(&mut d, &new(Kind::Angle, vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0]]), &meta).unwrap(); + let (_, dict) = annot(&d, 0, 0).unwrap(); + assert_eq!((dict.get(b"Measure"), dict.name(b"PCMeasureKind")), (None, Some(&b"Angle"[..]))); +} +#[test] +fn an_angle_saved_without_a_scale_reads_back_in_degrees() { + // A polyline marked as an angle and carrying no `/Measure`, as another writer saves one. + let angle = "<< /Type /Annot /Subtype /PolyLine /Rect [90 90 210 210] /PCMeasureKind /Angle /Vertices [200 100 100 100 100 200 120 100 100 120] >>"; + let d = fixture("", "/Annots [5 0 R]", &[angle]); + let listing = list(&d); + assert_eq!(listing.unsupported, vec![]); + let [m] = &listing.measurements[..] else { panic!("{listing:?}") }; + assert_eq!((m.reading.kind, &m.points), (Kind::Angle, &vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0]])); + close(m.reading.value, 90.0); +} +#[test] +fn an_angle_saved_without_a_scale_keeps_its_points() { + let mut d = fixture("", "", &[]); + let meta = Meta { date: None, id: "angle".into() }; + add(&mut d, &new(Kind::Angle, vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0]]), &meta).unwrap(); + let moved = pdfcraft_annot::set_points(&mut d, 0, 0, &[[0.0, 0.0], [10.0, 10.0]], &meta); + assert!(moved.is_err(), "{moved:?}"); + close(list(&d).measurements[0].reading.value, 90.0); +} From df1b18b6ca7a998f6502be6f51aad535f2e2db7f Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:06:24 -0500 Subject: [PATCH 5/6] test(measure): a saved angle takes the decimal mark of the viewport at its first point Co-Authored-By: Claude Opus 5.5 --- crates/measure/src/lib.rs | 4 ++-- crates/measure/src/tests.rs | 22 +++++++++++++++++++++- parity/acrobat-features.toml | 4 ++-- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index ebe30797de..55b35e0c8b 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -572,8 +572,8 @@ fn scale_of(doc: &Document, d: &Dict, scales: &mut Scales) -> Result { } fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: usize, scales: &mut Scales) -> Result { - // An angle saved without `/Measure` takes its decimal mark from the scale at its first point, - // as it was given when drawn. + // An angle saved without `/Measure` takes its decimal mark from the scale in force at its first + // point when it is read, which a viewport added since can change. let saved = if kind == Kind::Angle && !d.contains(b"Measure") { None } else { Some(scale_of(doc, d, scales)?) }; let key = if kind == Kind::Distance { &b"L"[..] } else { b"Vertices" }; let o = doc.resolve(d.get(key).ok_or_else(|| invalid("measurement has no vertices"))?); diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 2184f0c408..2b1321dc5d 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -785,6 +785,7 @@ fn an_angle_saves_reopens_and_lists_with_its_three_points() { assert!(add(&mut d, &new(Kind::Angle, vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0], [100.0, 100.0]]), &meta).is_err()); assert!(list(&d).measurements.is_empty()); } + #[test] fn an_angle_is_saved_without_a_scale() { let mut d = fixture("", "", &[]); @@ -793,10 +794,12 @@ fn an_angle_is_saved_without_a_scale() { let (_, dict) = annot(&d, 0, 0).unwrap(); assert_eq!((dict.get(b"Measure"), dict.name(b"PCMeasureKind")), (None, Some(&b"Angle"[..]))); } + #[test] fn an_angle_saved_without_a_scale_reads_back_in_degrees() { // A polyline marked as an angle and carrying no `/Measure`, as another writer saves one. - let angle = "<< /Type /Annot /Subtype /PolyLine /Rect [90 90 210 210] /PCMeasureKind /Angle /Vertices [200 100 100 100 100 200 120 100 100 120] >>"; + let angle = + "<< /Type /Annot /Subtype /PolyLine /Rect [90 90 210 210] /PCMeasureKind /Angle /Vertices [200 100 100 100 100 200 120 100 100 120] >>"; let d = fixture("", "/Annots [5 0 R]", &[angle]); let listing = list(&d); assert_eq!(listing.unsupported, vec![]); @@ -804,6 +807,7 @@ fn an_angle_saved_without_a_scale_reads_back_in_degrees() { assert_eq!((m.reading.kind, &m.points), (Kind::Angle, &vec![[200.0, 100.0], [100.0, 100.0], [100.0, 200.0]])); close(m.reading.value, 90.0); } + #[test] fn an_angle_saved_without_a_scale_keeps_its_points() { let mut d = fixture("", "", &[]); @@ -813,3 +817,19 @@ fn an_angle_saved_without_a_scale_keeps_its_points() { assert!(moved.is_err(), "{moved:?}"); close(list(&d).measurements[0].reading.value, 90.0); } + +#[test] +fn an_angle_saved_without_a_scale_takes_the_decimal_mark_of_the_viewport_at_its_first_point() { + // A two-unit format keeps its separators (a single-unit decimal scale is read for its + // precision alone), so the viewport's comma reaches the angle. + let m_cm = "[<< /U (m) /C 0.000352778 /RD (,) >> << /U (cm) /C 100 /D 10 /RD (,) >>]"; + let measure = format!("<< /Type /Measure /Subtype /RL /R (1:1) /X {m_cm} /D {m_cm} /A [<< /U (sq m) /C 1 /RD (,) >>] >>"); + let viewport = format!("/VP [<< /Type /Viewport /BBox [0 0 300 300] /Measure {measure} >>]"); + let angle = "<< /Type /Annot /Subtype /PolyLine /Rect [90 90 210 210] /PCMeasureKind /Angle /Vertices [200 100 100 100 100 200] >>"; + let inside = fixture("", &format!("/Annots [5 0 R] {viewport}"), &[angle]); + let listing = list(&inside); + let [m] = &listing.measurements[..] else { panic!("{listing:?}") }; + assert_eq!(m.reading.label, "90,0\u{b0}"); + let outside = fixture("", "/Annots [5 0 R]", &[angle]); + assert_eq!(list(&outside).measurements[0].reading.label, "90.0\u{b0}"); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 496ba9514c..e4b7d94a4f 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4496,8 +4496,8 @@ milestone = "M12" status = "partial" commands = [] tools = ["measure_angle"] -evidence = ["crates/automation/tests/it/automation.rs::measure_angle_draws_saves_reopens_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge", "crates/measure/src/tests.rs::an_angle_saves_reopens_and_lists_with_its_three_points", "crates/measure/src/tests.rs::an_angle_too_small_to_label_is_refused_by_name"] -notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, always in the smaller wedge; an optional fourth point sets its radius by its distance from the apex, else half the shorter arm and at least 20 user units); an angle under 0.05 degrees, which would be labelled 0.0, is refused; measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." +evidence = ["crates/automation/tests/it/automation.rs::measure_angle_draws_saves_reopens_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_is_read_the_short_way_in_either_order_and_ignores_the_scale", "crates/measure/src/tests.rs::an_angle_path_draws_both_arms_and_an_arc_inside_the_wedge", "crates/measure/src/tests.rs::an_angle_saves_reopens_and_lists_with_its_three_points", "crates/measure/src/tests.rs::an_angle_too_small_to_label_is_refused_by_name", "crates/measure/src/tests.rs::an_angle_is_saved_without_a_scale", "crates/measure/src/tests.rs::an_angle_saved_without_a_scale_reads_back_in_degrees", "crates/measure/src/tests.rs::an_angle_saved_without_a_scale_keeps_its_points", "crates/measure/src/tests.rs::an_angle_saved_without_a_scale_takes_the_decimal_mark_of_the_viewport_at_its_first_point"] +notes = "The angle at an apex between two arms, in degrees with one decimal and the scale's decimal mark; the scale's units and factors are not applied. Saved as a PolyLine with the measured points first, then the arc (3-degree steps, always in the smaller wedge; an optional fourth point sets its radius by its distance from the apex, else half the shorter arm and at least 20 user units); no /Measure is saved, so read back an angle takes its decimal mark from the scale at its first point; an angle under 0.05 degrees, which would be labelled 0.0, is refused; measure_list and measure_info read it. Partial: automation only (no panel tool yet), no arrowheads on the arc, no angular precision or degree-minute-second option. The PDF standard names no angle intent, so the annotation has no /IT and is marked /PCMeasureKind /Angle: other readers show the drawing and caption but not a measurement." [[feature]] id = "comment.measure-scale" From cc8bfd60dff791350aea48e2cf1da2fcd1e15b45 Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:49:17 -0500 Subject: [PATCH 6/6] fix(measure): keep a decimal comma on single-unit scales; one page walk per listing A single-unit decimal scale was read as plain, which dropped its number formats and with them a decimal mark other than the point, so angles (and lengths) were labelled with a point. Such a scale now keeps its formats. A single-unit scale with a decimal point reads as before. list looked each angle without /Measure up through scale_at, which walked the page tree again per angle. It now hands the page it is already on to the same viewport lookup; scale_at and scale_at_or keep their signatures and behaviour. Co-Authored-By: Claude Opus 5.5 --- crates/measure/src/lib.rs | 30 ++++++++++++++++++++++++------ crates/measure/src/tests.rs | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs index 55b35e0c8b..9beb16e061 100644 --- a/crates/measure/src/lib.rs +++ b/crates/measure/src/lib.rs @@ -86,7 +86,7 @@ pub struct Scale { /// or whose values show as fractions or cut off to whole units (ISO 32000-2 §12.9.2): /// readings are labelled with them, and a measurement added with this scale writes them /// back. `unit`, `area_unit` and the factors are their first units'. `None` for single-unit - /// decimal scales, which `unit`, `area_unit` and `precision` describe. + /// decimal scales with a decimal point, which `unit`, `area_unit` and `precision` describe. #[serde(skip_serializing_if = "Option::is_none")] pub formats: Option, } @@ -260,7 +260,11 @@ impl Scale { } let areas = format(b"A")?; let (area_unit, area_factor) = first(&areas)?; - let plain = [&xs, &distances, &areas].into_iter().chain(ys.as_ref()).all(|a| number_format::plain_precision(a).is_some()); + // A decimal mark other than the point is kept with the formats, so readings and angles show it. + let plain = [&xs, &distances, &areas] + .into_iter() + .chain(ys.as_ref()) + .all(|a| number_format::plain_precision(a).is_some() && a.iter().all(|f| f.decimal == ".")); // The decimals a distance shows: of its only unit, or of its last one when compound. let precision = number_format::plain_precision(&distances) .or_else(|| { @@ -443,6 +447,8 @@ fn nums(v: impl IntoIterator) -> Object { Object::Array(v.into_iter().map(Object::Real).collect()) } fn page(doc: &Document, index: usize) -> Result { + #[cfg(test)] + PAGE_LOOKUPS.with(|n| n.set(n.get() + 1)); pdfcraft_model::pages(doc).get(index).cloned().ok_or_else(|| invalid("measurement page does not exist")) } fn annot(doc: &Document, page_index: usize, index: usize) -> Result<(ObjRef, Dict)> { @@ -571,7 +577,14 @@ fn scale_of(doc: &Document, d: &Dict, scales: &mut Scales) -> Result { } } -fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: usize, scales: &mut Scales) -> Result { +fn read_measurement( + doc: &Document, + d: &Dict, + kind: Kind, + (page, p): (usize, &pdfcraft_model::Page), + index: usize, + scales: &mut Scales, +) -> Result { // An angle saved without `/Measure` takes its decimal mark from the scale in force at its first // point when it is read, which a viewport added since can change. let saved = if kind == Kind::Angle && !d.contains(b"Measure") { None } else { Some(scale_of(doc, d, scales)?) }; @@ -590,7 +603,7 @@ fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: us validate_geometry(kind, &points)?; let scale = match saved { Some(scale) => scale, - None => points.first().and_then(|at| scale_at(doc, page, *at).ok()).unwrap_or_default(), + None => points.first().and_then(|at| scale_on(doc, p, *at, 1.0 / 72.0, "in").ok()).unwrap_or_default(), }; let reading = reading(kind, &points, &scale)?; Ok(Measurement { @@ -666,7 +679,7 @@ pub fn list(doc: &Document) -> Listing { out.truncated = true; return out; } - match read_measurement(doc, d, kind, page, index, &mut scales) { + match read_measurement(doc, d, kind, (page, p), index, &mut scales) { Ok(m) => { kept = kept.saturating_add(retained(&m)); if kept > MAX_LISTED_BYTES { @@ -688,6 +701,8 @@ const MAX_VIEWPORTS: usize = 1024; thread_local! { /// Numbers read from viewport `/BBox` arrays. pub(crate) static VIEWPORT_NUMBERS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Page trees walked to find one page. + pub(crate) static PAGE_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Last containing viewport wins, using the first point of the measurement (ISO 32000-2 §12.9). @@ -699,7 +714,10 @@ pub fn scale_at(doc: &Document, page_index: usize, at: Point) -> Result { /// are `per_point` in a PDF point (25.4 / 72 for millimetres). pub fn scale_at_or(doc: &Document, page_index: usize, at: Point, per_point: f64, unit: &str) -> Result { check_points(&[at])?; - let p = page(doc, page_index)?; + scale_on(doc, &page(doc, page_index)?, at, per_point, unit) +} +/// [`scale_at_or`] on a page already found, so a listing walks the page tree once. +fn scale_on(doc: &Document, p: &pdfcraft_model::Page, at: Point, per_point: f64, unit: &str) -> Result { if let Some(o) = p.dict.get(b"VP") { let o = doc.resolve(o); let arr = o.as_array().ok_or_else(|| invalid("invalid page viewports"))?; diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 2b1321dc5d..a94a5b82fe 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -820,8 +820,7 @@ fn an_angle_saved_without_a_scale_keeps_its_points() { #[test] fn an_angle_saved_without_a_scale_takes_the_decimal_mark_of_the_viewport_at_its_first_point() { - // A two-unit format keeps its separators (a single-unit decimal scale is read for its - // precision alone), so the viewport's comma reaches the angle. + // A two-unit format keeps its separators, so the viewport's comma reaches the angle. let m_cm = "[<< /U (m) /C 0.000352778 /RD (,) >> << /U (cm) /C 100 /D 10 /RD (,) >>]"; let measure = format!("<< /Type /Measure /Subtype /RL /R (1:1) /X {m_cm} /D {m_cm} /A [<< /U (sq m) /C 1 /RD (,) >>] >>"); let viewport = format!("/VP [<< /Type /Viewport /BBox [0 0 300 300] /Measure {measure} >>]"); @@ -833,3 +832,34 @@ fn an_angle_saved_without_a_scale_takes_the_decimal_mark_of_the_viewport_at_its_ let outside = fixture("", "/Annots [5 0 R]", &[angle]); assert_eq!(list(&outside).measurements[0].reading.label, "90.0\u{b0}"); } + +#[test] +fn a_single_unit_scale_with_a_decimal_comma_labels_angles_and_lengths_with_it() { + let x = "[<< /U (m) /C 0.000352778 /D 100 /RD (,) >>]"; + let measure = + format!("<< /Type /Measure /Subtype /RL /R (1:1) /X {x} /D [<< /U (m) /C 1 /D 100 /RD (,) >>] /A [<< /U (sq m) /C 1 /RD (,) >>] >>"); + let viewport = format!("/VP [<< /Type /Viewport /BBox [0 0 300 300] /Measure {measure} >>]"); + let angle = "<< /Type /Annot /Subtype /PolyLine /Rect [90 90 210 210] /PCMeasureKind /Angle /Vertices [200 100 100 100 100 200] >>"; + let d = fixture("", &format!("/Annots [5 0 R] {viewport}"), &[angle]); + let listing = list(&d); + let [m] = &listing.measurements[..] else { panic!("{listing:?}") }; + assert_eq!(m.reading.label, "90,0\u{b0}"); + let scale = scale_at(&d, 0, [100.0, 100.0]).unwrap(); + let line = reading(Kind::Distance, &[[0.0, 0.0], [720.0, 0.0]], &scale).unwrap(); + assert!(line.label.starts_with("0,25"), "{line:?}"); +} + +#[test] +fn listing_angles_without_a_scale_walks_the_page_tree_once() { + let angle = |n: u32| { + format!("<< /Type /Annot /Subtype /PolyLine /Rect [90 90 210 210] /PCMeasureKind /Angle /NM (a{n}) /Vertices [200 100 100 100 100 200] >>") + }; + let angles = [angle(1), angle(2), angle(3)]; + let d = fixture("", "/Annots [5 0 R 6 0 R 7 0 R]", &angles.iter().map(String::as_str).collect::>()); + PAGE_LOOKUPS.with(|c| c.set(0)); + let listing = list(&d); + assert_eq!(listing.measurements.len(), 3, "{listing:?}"); + assert_eq!(PAGE_LOOKUPS.with(std::cell::Cell::get), 0); + // The public lookup still finds its page. + assert_eq!(scale_at(&d, 0, [100.0, 100.0]).unwrap().unit, "in"); +}