Merge pull request #9296

With AutoCraft's conflict resolution 0d5137da.

Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
This commit is contained in:
FredAppsandautocraft-bot[bot] authored and autocraft-bot[bot] committed 2026-12-05 07:36:40 +00:00
commit 3e815ce09d
11 files changed
+438 -19

No files matched your search

+2 -1
View File
@@ -821,7 +821,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 {
+1
View File
@@ -853,6 +853,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_radius" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Radius)?,
"measure_diameter" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Diameter)?,
"measure_info" => self.measurement_info(&a)?,
+1 -1
View File
@@ -61,7 +61,7 @@ impl Automation {
pub(crate) fn measurement_info(&self, a: &Args) -> Result<Value> {
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, area, radius or diameter"))?;
.ok_or_else(|| failed("type must be distance, perimeter, area, angle, radius or diameter"))?;
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)?;
+4 -2
View File
@@ -953,12 +953,14 @@ pub fn tools() -> Vec<ToolDef> {
.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 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_radius", "Measure radius", "Add an undoable radius annotation for the circle that best fits three or more points picked on it (Taubin fit, refined). The line runs from the centre to the rim; the scale's X and Y must agree.")
.with(measure_schema()),
t("measure_diameter", "Measure diameter", "Add an undoable diameter annotation for the circle that best fits three or more points picked on it (Taubin fit, refined). The line runs rim to rim through the centre; the scale's X and Y must agree.")
.with(measure_schema()),
t("measure_info", "Read a measurement", "Calculate a live distance, perimeter, area, radius or diameter, deltas, angle and scale without adding an annotation. Incomplete paths are allowed; a radius or diameter needs three points on the circle and also reports the fitted centre and residual.")
.ro().cmd("measure.info").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"points":measure_points(),"type":{"type":"string","enum":["distance","perimeter","area","radius","diameter"]}}), &["doc","page","points"])),
t("measure_info", "Read a measurement", "Calculate a live distance, perimeter, area, angle between two arms, radius or diameter, deltas, angle and scale without adding an annotation. Incomplete paths are allowed; a radius or diameter needs three points on the circle and also reports the fitted centre and residual.")
.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","radius","diameter"]}}), &["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.")
+38
View File
@@ -11850,6 +11850,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_reads_a_length_typed_as_a_drawing_writes_it() {
// Calibrating against a dimension printed as 4'-7 1/2" reads it as 4.625 ft, without the
+1
View File
@@ -230,6 +230,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",
pdfcraft_measure::Kind::Radius => "Measure radius",
pdfcraft_measure::Kind::Diameter => "Measure diameter",
}),
+3 -1
View File
@@ -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_radius, measure_diameter, 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_radius, measure_diameter, 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.
+146
View File
@@ -0,0 +1,146 @@
//! 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`. 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
/// 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 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;
/// 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.
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<Point> {
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<f64> {
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<Reading> {
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,
circle: None,
})
}
/// 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()) {
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: 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<f64> {
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, (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<Vec<Point>> {
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<Point> = 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<Point>, p: Point) {
if out.last().is_none_or(|q| distance(*q, p) >= SAME) {
out.push(p);
}
}
+76 -14
View File
@@ -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 circle;
pub mod length;
pub mod number_format;
@@ -22,6 +23,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<T> = std::result::Result<T, MeasureError>;
fn invalid(s: &str) -> MeasureError {
@@ -34,6 +38,7 @@ pub enum Kind {
Distance,
Perimeter,
Area,
Angle,
/// Radius of the circle fitted to three or more points on it.
Radius,
/// Diameter of the circle fitted to three or more points on it.
@@ -45,6 +50,7 @@ impl Kind {
Self::Distance => "distance",
Self::Perimeter => "perimeter",
Self::Area => "area",
Self::Angle => "angle",
Self::Radius => "radius",
Self::Diameter => "diameter",
}
@@ -54,16 +60,19 @@ impl Kind {
"distance" => Some(Self::Distance),
"perimeter" => Some(Self::Perimeter),
"area" => Some(Self::Area),
"angle" => Some(Self::Angle),
"radius" => Some(Self::Radius),
"diameter" => Some(Self::Diameter),
_ => 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 | Self::Radius | Self::Diameter => "LineDimension",
Self::Perimeter => "PolyLineDimension",
Self::Area => "PolygonDimension",
Self::Distance | Self::Radius | Self::Diameter => Some("LineDimension"),
Self::Perimeter => Some("PolyLineDimension"),
Self::Area => Some("PolygonDimension"),
Self::Angle => None,
}
}
}
@@ -87,7 +96,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<Formats>,
}
@@ -261,7 +270,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(|| {
@@ -344,6 +357,9 @@ pub struct Reading {
pub fn reading(kind: Kind, points: &[Point], scale: &Scale) -> Result<Reading> {
check_points(points)?;
scale.validate()?;
if kind == Kind::Angle {
return angle::reading(points, scale);
}
if circle::is_circular(kind) {
return circle::reading(kind, points, scale);
}
@@ -428,6 +444,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)?;
if circle::is_circular(kind) {
return circle::fit_or_err(points).map(|_| ());
@@ -465,6 +484,8 @@ fn nums(v: impl IntoIterator<Item = f64>) -> Object {
Object::Array(v.into_iter().map(Object::Real).collect())
}
fn page(doc: &Document, index: usize) -> Result<pdfcraft_model::Page> {
#[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)> {
@@ -478,6 +499,9 @@ fn annot(doc: &Document, page_index: usize, index: usize) -> Result<(ObjRef, Dic
pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result<usize> {
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"));
}
@@ -499,6 +523,9 @@ pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result<usiz
Shape::PolyLine { vertices: new.points.clone(), start: pdfcraft_annot::LineEnding::None, end: pdfcraft_annot::LineEnding::None }
}
Kind::Area => 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,
@@ -506,8 +533,15 @@ pub fn add(doc: &mut Document, new: &NewMeasurement, meta: &Meta) -> Result<usiz
meta,
)?;
let (r, mut d) = annot(doc, new.page, index)?;
d.set(b"IT".to_vec(), Object::name(new.kind.intent()));
d.set(b"Measure".to_vec(), Object::Dict(new.scale.dictionary()?));
match new.kind.intent() {
Some(it) => d.set(b"IT".to_vec(), Object::name(it)),
None => d.set(angle::KIND_KEY.to_vec(), Object::name(angle::KIND_VALUE)),
}
// 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));
@@ -595,19 +629,36 @@ fn vertex_key(kind: Kind) -> &'static [u8] {
match kind {
Kind::Distance => b"L",
Kind::Radius | Kind::Diameter => b"PCMeasurePoints",
Kind::Perimeter | Kind::Area => b"Vertices",
Kind::Perimeter | Kind::Area | Kind::Angle => b"Vertices",
}
}
fn read_measurement(doc: &Document, d: &Dict, kind: Kind, page: usize, index: usize, scales: &mut Scales) -> Result<Measurement> {
let scale = scale_of(doc, d, scales)?;
fn read_measurement(
doc: &Document,
d: &Dict,
kind: Kind,
(page, p): (usize, &pdfcraft_model::Page),
index: usize,
scales: &mut Scales,
) -> Result<Measurement> {
// 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 o = doc.resolve(d.get(vertex_key(kind)).ok_or_else(|| invalid("measurement has no vertices"))?);
let a = o.as_array().ok_or_else(|| invalid("invalid measurement vertices"))?;
if a.len() % 2 != 0 || a.len() > MAX_POINTS * 2 {
return Err(invalid("invalid measurement vertex count"));
}
let v: Vec<f64> = a.iter().map(|n| doc.resolve(n).as_f64().ok_or_else(|| invalid("invalid vertex"))).collect::<Result<_>>()?;
let points: Vec<Point> = v.as_chunks::<2>().0.to_vec();
let mut points: Vec<Point> = 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 scale = match saved {
Some(scale) => scale,
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 {
page,
@@ -653,6 +704,9 @@ pub fn list(doc: &Document) -> Listing {
Some(b"LineDimension") => circle::saved_kind(doc, d, &mut fits, &mut work, MAX_LISTED_WORK).unwrap_or(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
@@ -670,6 +724,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 if circle::is_circular(kind) {
// Reading a radius or diameter fits its points twice (checking, then measuring).
work = work.saturating_add(circle::fit_work(n.max(1)).saturating_mul(2));
@@ -680,7 +737,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 {
@@ -702,6 +759,8 @@ const MAX_VIEWPORTS: usize = 1024;
thread_local! {
/// Numbers read from viewport `/BBox` arrays.
pub(crate) static VIEWPORT_NUMBERS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Page trees walked to find one page.
pub(crate) static PAGE_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Last containing viewport wins, using the first point of the measurement (ISO 32000-2 §12.9).
@@ -713,7 +772,10 @@ pub fn scale_at(doc: &Document, page_index: usize, at: Point) -> Result<Scale> {
/// 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<Scale> {
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<Scale> {
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"))?;
+154
View File
@@ -709,3 +709,157 @@ 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<Point> = 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_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() };
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());
}
#[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);
}
#[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, 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}");
}
#[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::<Vec<_>>());
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");
}
+12
View File
@@ -4499,6 +4499,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", "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-radius-diameter"
title = "Radius and diameter from points picked on a circle"