Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M12: the page side of a measuring scale takes a unit, so 1:50 is 1 mm = 50 mm (#2752)

Guillem Hermida282ce5667507
diff --git a/crates/automation/src/measure.rs b/crates/automation/src/measure.rs
index 13500ff97..ac3d2d95f 100644
--- a/crates/automation/src/measure.rs
+++ b/crates/automation/src/measure.rs
@@ -2,7 +2,7 @@
use crate::{Args, Automation, Result, ToolError, failed};
use pdfcraft_engine::{
Edit, Style,
- measure::{self, Kind, NewMeasurement, Scale},
+ measure::{self, Kind, NewMeasurement, PageUnit, Scale},
};
use serde_json::{Value, json};
@@ -78,16 +78,30 @@ impl Automation {
let info = self.doc(a)?.info.pages.get(page).ok_or_else(|| failed("no such page"))?.clone();
let precision = u8::try_from(a.opt_int("precision")?.unwrap_or(2)).map_err(|_| failed("precision must be between 0 and 6"))?;
let unit = a.opt_str("unit")?.unwrap_or("in");
+ if ["points", "units_per_point", "page_distance"].iter().filter(|k| a.get(k).is_some()).count() > 1 {
+ return Err(failed("pass one of calibration points, units_per_point or page_distance"));
+ }
+ if a.get("page_unit").is_some() && a.get("page_distance").is_none() {
+ return Err(failed("page_unit is the unit of page_distance; pass page_distance too"));
+ }
let scale = if a.get("points").is_some() {
- if a.get("units_per_point").is_some() {
- return Err(failed("pass calibration points or units_per_point, not both"));
- }
let (_, points) = self.measurement_points(a)?;
let [from, to] = points.as_slice() else {
return Err(failed("scale calibration needs exactly two points"));
};
let length = a.opt_num("distance")?.ok_or_else(|| failed("calibration needs a real-world distance"))?;
Scale::calibrate(*from, *to, length, unit, precision).map_err(failed)?
+ } else if let Some(page_distance) = a.opt_num("page_distance")? {
+ // A ratio, "page_distance page_unit on the page = distance unit"; the page unit
+ // defaults to the real-world one, as "1:50" means 1 mm = 50 mm.
+ let page_unit = match a.opt_str("page_unit")? {
+ Some(u) => PageUnit::from_label(u).ok_or_else(|| failed("page_unit must be pt, in, mm or cm"))?,
+ None => PageUnit::from_label(unit).ok_or_else(|| failed("pass page_unit (pt, in, mm or cm) when unit is not one of them"))?,
+ };
+ let length = a.opt_num("distance")?.ok_or_else(|| failed("a scale ratio needs the real-world distance"))?;
+ let from = self.doc(a)?.measurement_to_user(page, [0.0, 0.0]).map_err(failed)?;
+ let to = self.doc(a)?.measurement_to_user(page, [1.0, 0.0]).map_err(failed)?;
+ Scale::ratio(from, to, page_distance, page_unit, length, unit, precision).map_err(failed)?
} else if let Some(factor) = a.opt_num("units_per_point")? {
{
let from = self.doc(a)?.measurement_to_user(page, [0.0, 0.0]).map_err(failed)?;
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 5e89aef78..04aaf80a7 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -611,8 +611,8 @@ pub fn tools() -> Vec<ToolDef> {
.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_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 units_per_point or two calibration points and their real-world distance. Existing measurements retain their original scales. Undoable.")
- .cmd("measure.scale").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"at":point(),"rect":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4},"name":{"type":"string"},"unit":{"type":"string"},"precision":{"type":"integer","minimum":0,"maximum":6},"units_per_point":{"type":"number","exclusiveMinimum":0},"points":measure_points(),"distance":{"type":"number","exclusiveMinimum":0}}), &["doc","page"])),
+ 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.")
+ .cmd("measure.scale").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"at":point(),"rect":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4},"name":{"type":"string"},"unit":{"type":"string"},"precision":{"type":"integer","minimum":0,"maximum":6},"units_per_point":{"type":"number","exclusiveMinimum":0},"page_distance":{"type":"number","exclusiveMinimum":0},"page_unit":{"type":"string","enum":["pt","in","mm","cm"]},"points":measure_points(),"distance":{"type":"number","exclusiveMinimum":0}}), &["doc","page"])),
t("measure_snap", "Snap a measurement vertex", "Snap a point to vector paths, endpoints, midpoints or intersections. Coordinates and tolerance are in display points. Bounded extraction reports truncated geometry.")
.ro().cmd("measure.snap").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"at":point(),"tolerance":{"type":"number","minimum":0,"maximum":10000},"endpoints":{"type":"boolean"},"midpoints":{"type":"boolean"},"intersections":{"type":"boolean"},"paths":{"type":"boolean"}}), &["doc","page","at"])),
t("measure_export", "Export measurements as CSV", "Atomically write saved measurement values, labels, authors and scale ratios as spreadsheet-safe CSV. Returns how many unsupported measurements were left out.")
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 1e662d8f3..cdf0eebe7 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -5358,6 +5358,51 @@ fn measurements_calibrate_draw_save_reopen_and_export() {
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.
+ let dir = workdir("measurement-ratio");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({"path":"a.pdf"}))["doc"].as_u64().unwrap();
+ let mm = 72.0 / 25.4;
+ let line = json!([[20.0, 30.0], [20.0 + 10.0 * mm, 30.0]]);
+ let read = |a: &mut Automation, doc: u64| ok(a, "measure_info", json!({"doc":doc,"page":1,"points":line}))["reading"]["value"].as_f64().unwrap();
+ let set = ok(&mut a, "measure_scale", json!({"doc":doc,"page":1,"page_distance":1,"page_unit":"mm","distance":50,"unit":"mm"}));
+ assert_eq!(set["scale"]["ratio"], "1 mm = 50 mm");
+ assert!((read(&mut a, doc) - 500.0).abs() < 1e-9);
+ // The PDF keeps its factors per point: 50 mm for every 25.4 / 72 mm of page.
+ assert!((set["scale"]["x"].as_f64().unwrap() - 50.0 / mm).abs() < 1e-9);
+ ok(&mut a, "edit_undo", json!({"doc":doc}));
+ assert!((read(&mut a, doc) - 10.0 / 25.4).abs() < 1e-9, "true size in inches without a scale");
+ ok(&mut a, "edit_redo", json!({"doc":doc}));
+ assert!((read(&mut a, doc) - 500.0).abs() < 1e-9);
+ ok(&mut a, "doc_save", json!({"doc":doc,"path":"ratio.pdf"}));
+ let reopened = ok(&mut a, "doc_open", json!({"path":"ratio.pdf"}))["doc"].as_u64().unwrap();
+ assert!((read(&mut a, reopened) - 500.0).abs() < 1e-9);
+ assert_eq!(ok(&mut a, "measure_scale", json!({"doc":reopened,"page":1,"at":[20,30]}))["scale"]["ratio"], "1 mm = 50 mm");
+ // The page side defaults to the real-world unit; any page unit converts to points.
+ ok(&mut a, "measure_scale", json!({"doc":doc,"page":1,"page_distance":2,"distance":1,"unit":"cm"}));
+ assert!((read(&mut a, doc) - 0.5).abs() < 1e-9);
+ ok(&mut a, "measure_scale", json!({"doc":doc,"page":1,"page_distance":0.25,"page_unit":"in","distance":1,"unit":"ft"}));
+ assert!((read(&mut a, doc) - 10.0 / 25.4 * 4.0).abs() < 1e-9);
+ // Units per point keep meaning points.
+ ok(&mut a, "measure_scale", json!({"doc":doc,"page":1,"units_per_point":50,"unit":"mm"}));
+ assert!((read(&mut a, doc) - 500.0 * mm).abs() < 1e-9);
+ let before = ok(&mut a, "doc_list", json!({}));
+ for args in [
+ json!({"doc":doc,"page":1,"page_distance":1,"page_unit":"ft","distance":1,"unit":"ft"}),
+ json!({"doc":doc,"page":1,"page_distance":1,"distance":1,"unit":"m"}),
+ json!({"doc":doc,"page":1,"page_distance":1,"unit":"mm"}),
+ json!({"doc":doc,"page":1,"page_unit":"mm","units_per_point":1}),
+ json!({"doc":doc,"page":1,"page_distance":1,"units_per_point":1,"distance":1}),
+ json!({"doc":doc,"page":1,"page_distance":1,"points":[[0,0],[10,0]],"distance":1}),
+ ] {
+ assert!(a.call("measure_scale", &args).is_err(), "{args}");
+ assert_eq!(ok(&mut a, "doc_list", json!({})), before);
+ }
+ let _ = std::fs::remove_dir_all(dir);
+}
+
#[test]
fn measurements_bad_arguments_leave_document_and_history_unchanged() {
let dir = workdir("measurement-errors");
diff --git a/crates/measure/README.md b/crates/measure/README.md
index 653cfa843..95a04a2b6 100644
--- a/crates/measure/README.md
+++ b/crates/measure/README.md
@@ -4,9 +4,9 @@ Layer L4 implements distance, connected-line perimeter and simple polygon area m
Measurements are ordinary Line, PolyLine or Polygon annotations with a rectilinear Measure dictionary and a normal appearance containing the numeric caption. Their scale is stored with the annotation, so changing a drawing scale does not change earlier measurements. Moving, restyling, replying to and deleting them uses the existing comment workflow.
-Scale::calibrate derives a conversion from two points and a known real-world distance. 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.
+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. 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_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 20,000 segments, 40,000 endpoint and midpoint targets, 16 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.
diff --git a/crates/measure/src/lib.rs b/crates/measure/src/lib.rs
index aac6663c0..72b6c4b07 100644
--- a/crates/measure/src/lib.rs
+++ b/crates/measure/src/lib.rs
@@ -110,6 +110,19 @@ impl Scale {
}
Self::new(real_distance / length, unit, precision)
}
+ /// A scale as a plan writes it: `page` `page_unit` on the page is `real` `unit` in the real
+ /// world ("1 mm = 50 mm" at 1:50). `a` and `b` are the user-space ends of one display point,
+ /// as for [`Scale::calibrate`]. The page side is converted to points, so the stored factors
+ /// stay per user-space unit; the ratio string keeps the units as entered.
+ pub fn ratio(a: Point, b: Point, page: f64, page_unit: PageUnit, real: f64, unit: &str, precision: u8) -> Result<Self> {
+ if !page.is_finite() || page <= 0.0 || !real.is_finite() || real <= 0.0 {
+ return Err(invalid("both sides of a scale ratio must be finite and positive"));
+ }
+ let mut out = Self::calibrate(a, b, real / (page * page_unit.points()), unit, precision)?;
+ out.ratio = format!("{} {} = {} {unit}", ratio_number(page), page_unit.label(), ratio_number(real));
+ out.validate()?;
+ Ok(out)
+ }
pub fn validate(&self) -> Result<()> {
for f in [self.x, self.y, self.distance_factor, self.area_factor] {
if !f.is_finite() || !(1e-12..=1e12).contains(&f) {
@@ -202,6 +215,44 @@ impl Scale {
Ok(out)
}
}
+/// The unit of the page side of a scale ratio. The PDF keeps scales per user-space unit
+/// (ISO 32000-2 §12.9), so a ratio given in one of these is converted to points.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PageUnit {
+ Pt,
+ In,
+ Mm,
+ Cm,
+}
+impl PageUnit {
+ pub const ALL: [Self; 4] = [Self::Pt, Self::In, Self::Mm, Self::Cm];
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Pt => "pt",
+ Self::In => "in",
+ Self::Mm => "mm",
+ Self::Cm => "cm",
+ }
+ }
+ pub fn from_label(s: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|u| u.label() == s.trim())
+ }
+ /// Points in one of this unit.
+ pub fn points(self) -> f64 {
+ match self {
+ Self::Pt => 1.0,
+ Self::In => 72.0,
+ Self::Mm => 72.0 / 25.4,
+ Self::Cm => 72.0 / 2.54,
+ }
+ }
+}
+/// A side of a scale ratio as people write it: at most six decimals, no trailing zeros.
+fn ratio_number(v: f64) -> String {
+ let fixed = format!("{v:.6}");
+ let short = fixed.trim_end_matches('0').trim_end_matches('.');
+ if short == "0" || short.len() > 24 { format!("{v:e}") } else { short.into() }
+}
pub(crate) fn check_points(points: &[Point]) -> Result<()> {
if points.len() > MAX_POINTS || points.iter().flatten().any(|v| !v.is_finite() || v.abs() > MAX_COORD) {
return Err(invalid("measurement geometry must be finite, within 1e9 user units, and have at most 2048 vertices"));
diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs
index 6af32632f..303f9b438 100644
--- a/crates/measure/src/tests.rs
+++ b/crates/measure/src/tests.rs
@@ -363,3 +363,43 @@ fn user_unit_is_read_as_acrobat_reads_it() {
close(view[1], 72.0);
}
}
+
+#[test]
+fn a_scale_ratio_converts_its_page_side_to_points() {
+ // #2752: a plan drawn at 1:50 is "1 mm = 50 mm", so a line 10 mm long on the page is 500 mm.
+ // The page side used to be points: 1 pt = 50 mm read the line as 1417 mm (50 × 72 / 25.4).
+ let mm = 72.0 / 25.4;
+ let line = [[20.0, 30.0], [20.0 + 10.0 * mm, 30.0]];
+ let scale = Scale::ratio([0.0, 0.0], [1.0, 0.0], 1.0, PageUnit::Mm, 50.0, "mm", 2).unwrap();
+ close(reading(Kind::Distance, &line, &scale).unwrap().value, 500.0);
+ assert_eq!(reading(Kind::Distance, &line, &scale).unwrap().label, "500.00 mm");
+ assert_eq!(scale.ratio, "1 mm = 50 mm");
+ // The PDF stores the factors per point (ISO 32000-2 §12.9): X converts user units to mm.
+ let dict = scale.dictionary().unwrap();
+ let x = dict.get(b"X").unwrap().as_array().unwrap()[0].as_dict().unwrap();
+ close(x.get(b"C").and_then(Object::as_f64).unwrap(), 50.0 / mm);
+ assert_eq!(Scale::read(&fixture("", "", &[]), &Object::Dict(dict)).unwrap(), scale);
+ // Every page unit converts: one of it on the page is one metre.
+ for (unit, points) in [(PageUnit::Pt, 1.0), (PageUnit::In, 72.0), (PageUnit::Mm, mm), (PageUnit::Cm, 10.0 * mm)] {
+ assert_eq!(PageUnit::from_label(unit.label()), Some(unit));
+ let scale = Scale::ratio([0.0, 0.0], [1.0, 0.0], 2.0, unit, 2.0, "m", 3).unwrap();
+ close(reading(Kind::Distance, &[[0.0, 0.0], [0.0, 3.0 * points]], &scale).unwrap().value, 3.0);
+ assert_eq!(scale.ratio, format!("2 {} = 2 m", unit.label()));
+ }
+ assert_eq!(PageUnit::from_label("ft"), None);
+ // On a UserUnit 2 page one display point spans half a user unit; the ratio still holds on screen.
+ let mut d = fixture("", "/UserUnit 2", &[]);
+ let (a, b) = (view_to_user(&d, 0, [0.0, 0.0]).unwrap(), view_to_user(&d, 0, [1.0, 0.0]).unwrap());
+ let scale = Scale::ratio(a, b, 1.0, PageUnit::Cm, 0.5, "m", 2).unwrap();
+ let ends = [view_to_user(&d, 0, [10.0, 10.0]).unwrap(), view_to_user(&d, 0, [10.0 + 4.0 * 10.0 * mm, 10.0]).unwrap()];
+ close(reading(Kind::Distance, &ends, &scale).unwrap().value, 2.0);
+ // Saved and reopened, the viewport keeps the factors and the ratio as written.
+ set_scale(&mut d, 0, [0.0, 0.0, 612.0, 792.0], "plan", &scale).unwrap();
+ let d = Document::open(Arc::new(write_full(&d, &SaveOptions::default()).unwrap())).unwrap();
+ assert_eq!(scale_at(&d, 0, ends[0]).unwrap(), scale);
+ // Points per unit keep meaning points, and both sides must be finite and positive.
+ assert_eq!(Scale::calibrate([0.0, 0.0], [1.0, 0.0], 50.0, "mm", 2).unwrap().ratio, "1 pt = 50 mm");
+ for (page, real) in [(0.0, 1.0), (-1.0, 1.0), (f64::NAN, 1.0), (f64::INFINITY, 1.0), (1.0, 0.0), (1.0, f64::NAN), (1e-300, 1e300)] {
+ assert!(Scale::ratio([0.0, 0.0], [1.0, 0.0], page, PageUnit::Mm, real, "mm", 2).is_err(), "{page} {real}");
+ }
+}
diff --git a/crates/ui-egui/src/measure_ui.rs b/crates/ui-egui/src/measure_ui.rs
index f031a8d07..f91e4bf3f 100644
--- a/crates/ui-egui/src/measure_ui.rs
+++ b/crates/ui-egui/src/measure_ui.rs
@@ -3,7 +3,7 @@ use crate::{LeftPanel, PdfCraftApp, QuickTool, canvas::DocView, theme::Tokens, w
use egui::{Color32, Pos2, Stroke};
use pdfcraft_engine::{
Document, Edit, Style,
- measure::{self, Kind, NewMeasurement, Point, Reading, Scale},
+ measure::{self, Kind, NewMeasurement, PageUnit, Point, Reading, Scale},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -49,9 +49,12 @@ pub struct MeasureView {
pub snaps: measure::snap::SnapOptions,
pub snap_enabled: bool,
pub sensitivity: f64,
+ /// The page side of the drawing scale, in its page unit ([`page_unit_of`]).
pub drawing_points: f64,
pub real_distance: f64,
pub unit: String,
+ /// The unit picked for the page side of the scale; `None` follows `unit`.
+ pub page_unit: Option<PageUnit>,
pub precision: u8,
pub name: String,
pub whole_page: bool,
@@ -76,9 +79,10 @@ impl Default for MeasureView {
snaps: Default::default(),
snap_enabled: true,
sensitivity: 6.0,
- drawing_points: 72.0,
+ drawing_points: 1.0,
real_distance: 1.0,
unit: "in".into(),
+ page_unit: None,
precision: 2,
name: "Drawing scale".into(),
whole_page: true,
@@ -90,6 +94,11 @@ impl Default for MeasureView {
}
}
}
+/// The unit of the page side of a drawing scale: the one picked, else the real-world unit when it
+/// is pt, in, mm or cm (a plan at 1:50 in millimetres is 1 mm = 50 mm), else the display unit.
+pub(crate) fn page_unit_of(picked: Option<PageUnit>, unit: &str, display: crate::units::Unit) -> PageUnit {
+ picked.or_else(|| PageUnit::from_label(unit)).or_else(|| PageUnit::from_label(display.label())).unwrap_or(PageUnit::Pt)
+}
impl MeasureView {
pub fn cancel(&mut self) {
self.points.clear();
@@ -194,13 +203,13 @@ pub(crate) fn page_input(
}
let finishes = closes || matches!(tool, Tool::Distance | Tool::Calibrate) && state.points.len() == 2;
if finishes {
- finish(state, &mut view.pending_edit, doc, page, tool, author);
+ finish(state, &mut view.pending_edit, doc, page, tool, author, units);
}
}
}
if state.page == Some(page) && !state.points.is_empty() {
if (resp.double_clicked() || !typing && ui.input(|i| i.key_pressed(egui::Key::Enter))) && matches!(tool, Tool::Perimeter | Tool::Area) {
- finish(state, &mut view.pending_edit, doc, page, tool, author);
+ finish(state, &mut view.pending_edit, doc, page, tool, author, units);
}
if !typing && ui.input(|i| i.key_pressed(egui::Key::Backspace)) {
state.points.pop();
@@ -252,13 +261,13 @@ pub(crate) fn page_input(
}
}
}
-fn finish(state: &mut MeasureView, pending: &mut Option<Edit>, doc: &Document, page: usize, tool: Tool, author: &str) {
+fn finish(state: &mut MeasureView, pending: &mut Option<Edit>, doc: &Document, page: usize, tool: Tool, author: &str, units: crate::units::Unit) {
if tool == Tool::Calibrate {
if let [a, b] = state.points.as_slice() {
let a = doc.measurement_to_view(page, *a);
let b = doc.measurement_to_view(page, *b);
if let (Ok(a), Ok(b)) = (a, b) {
- state.drawing_points = measure::distance(a, b);
+ state.drawing_points = measure::distance(a, b) / page_unit_of(state.page_unit, &state.unit, units).points();
}
}
state.cancel();
@@ -309,13 +318,16 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
}
if state.seeded_page != Some(page) {
state.seeded_page = Some(page);
- if let (Ok(a), Ok(b)) = (doc.measurement_to_user(page, [0.0, 0.0]), doc.measurement_to_user(page, [72.0, 0.0]))
+ // One page unit (the one the scale's unit gives) and what it measures.
+ if let Ok(a) = doc.measurement_to_user(page, [0.0, 0.0])
&& let Ok(scale) = doc.measurement_scale_or(page, a, units.per_point(), units.label())
+ && let Ok(b) = doc.measurement_to_user(page, [page_unit_of(None, &scale.unit, units).points(), 0.0])
&& let Ok(reading) = measure::reading(Kind::Distance, &[a, b], &scale)
{
- state.drawing_points = 72.0;
+ state.drawing_points = 1.0;
state.real_distance = reading.value;
state.unit = scale.unit;
+ state.page_unit = None;
state.precision = scale.precision;
}
}
@@ -353,7 +365,15 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
ui.separator();
ui.label(tl!("Drawing scale"));
ui.horizontal(|ui| {
- ui.add(egui::DragValue::new(&mut state.drawing_points).range(0.000001..=1e9).prefix("pt "));
+ ui.add(egui::DragValue::new(&mut state.drawing_points).range(0.000001..=1e9));
+ let page_unit = page_unit_of(state.page_unit, &state.unit, units);
+ egui::ComboBox::from_id_salt("measure-page-unit").selected_text(page_unit.label()).width(44.0).show_ui(ui, |ui| {
+ for u in PageUnit::ALL {
+ if ui.selectable_label(u == page_unit, u.label()).clicked() {
+ state.page_unit = Some(u);
+ }
+ }
+ });
ui.label("=");
ui.add(egui::DragValue::new(&mut state.real_distance).range(0.000001..=1e12));
});
@@ -410,7 +430,8 @@ fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, _t: &Tokens) {
if apply && let Some(info) = info {
let result =
doc.measurement_to_user(page, [0.0, 0.0]).and_then(|a| doc.measurement_to_user(page, [1.0, 0.0]).map(|b| (a, b))).and_then(|(a, b)| {
- Scale::calibrate(a, b, state.real_distance / state.drawing_points, &state.unit, state.precision).map_err(|e| e.to_string())
+ let page_unit = page_unit_of(state.page_unit, &state.unit, units);
+ Scale::ratio(a, b, state.drawing_points, page_unit, state.real_distance, &state.unit, state.precision).map_err(|e| e.to_string())
});
match result {
Ok(scale) => {
diff --git a/crates/ui-egui/tests/control.rs b/crates/ui-egui/tests/control.rs
index 88ed1c0a9..6b2cc7d81 100644
--- a/crates/ui-egui/tests/control.rs
+++ b/crates/ui-egui/tests/control.rs
@@ -1189,6 +1189,7 @@ fn measurement_tools_draw_live_calibrate_save_and_export() {
ok(&mut h, &c, "ui.command", json!({"id":"measure.scale"}));
h.run_steps(3);
h.state_mut().views[0].measure.drawing_points = 10.0;
+ h.state_mut().views[0].measure.page_unit = Some(pdfcraft_engine::measure::PageUnit::Pt);
h.state_mut().views[0].measure.real_distance = 1.0;
h.state_mut().views[0].measure.unit = "m".into();
h.get_by_label("Apply scale").click();
@@ -1237,6 +1238,49 @@ fn measurement_tools_draw_live_calibrate_save_and_export() {
let _ = std::fs::remove_dir_all(dir);
}
+#[test]
+fn a_1_to_50_scale_in_millimetres_measures_a_10_mm_line_as_500_mm() {
+ // #2752: a plan drawn at 1:50 is "1 mm = 50 mm". The page side of the scale was fixed in
+ // points, so this stored 1 pt = 50 mm, 72 / 25.4 = 2.835 times too big.
+ use pdfcraft_engine::measure::{self, Kind};
+ let (mut h, c) = harness_pages(1);
+ let doc = h.state().views[0].id;
+ h.state_mut().set_option("zoom", "100").unwrap();
+ ok(&mut h, &c, "ui.command", json!({"id":"measure.scale"}));
+ h.run_steps(3);
+ let m = &mut h.state_mut().views[0].measure;
+ (m.drawing_points, m.real_distance, m.unit) = (1.0, 50.0, "mm".into());
+ h.get_by_label("Apply scale").click();
+ h.run_steps(3);
+ let mm = 72.0 / 25.4;
+ let line = [[20.0, 30.0], [20.0 + 10.0 * mm, 30.0]];
+ let stored = |h: &Harness<'static, PdfCraftApp>| {
+ let scale = h.state().session.get(doc).unwrap().measurement_scale(0, line[0]).unwrap();
+ (measure::reading(Kind::Distance, &line, &scale).unwrap().value, scale.ratio)
+ };
+ let (value, ratio) = stored(&h);
+ assert!((value - 500.0).abs() < 1e-9, "a 10 mm line at 1:50 reads {value} ({ratio})");
+ assert_eq!(ratio, "1 mm = 50 mm");
+ // The scale is one undoable edit.
+ ok(&mut h, &c, "ui.command", json!({"id":"edit.undo"}));
+ h.run_steps(2);
+ assert!((stored(&h).0 - 500.0).abs() > 1.0);
+ ok(&mut h, &c, "ui.command", json!({"id":"edit.redo"}));
+ h.run_steps(2);
+ assert_eq!(stored(&h), (value, ratio));
+ // Measuring the line on the page with the Distance tool reads the same.
+ ok(&mut h, &c, "ui.command", json!({"id":"measure.distance"}));
+ for [x, y] in line {
+ let r = h.state().views[0].page_screen_rect(0).unwrap();
+ ok(&mut h, &c, "ui.click", json!({"x":r.left()+x as f32*r.width()/200.0,"y":r.top()+y as f32*r.height()/300.0}));
+ h.run_steps(2);
+ }
+ let measurements = h.state().session.get(doc).unwrap().measurements().unwrap().measurements;
+ assert_eq!(measurements.len(), 1);
+ assert!((measurements[0].reading.value - 500.0).abs() < 0.05, "{:?}", measurements[0].reading);
+ assert_eq!(measurements[0].reading.unit, "mm");
+}
+
#[test]
fn docking_pointer_group_float_close_restore_and_document_commands() {
use pdfcraft_ui_egui::docking::Panel;