fix(units): make the units selector reach what it names

The status-bar units button wrote INSUNITS, which nothing on screen reads.
INSUNITS only tells the drawing how to scale content arriving from
elsewhere, so picking a unit relabelled the drawing and changed nothing
visible — the selector looked broken because the variable it moved was
invisible.

Point the button at LUNITS instead, the setting that decides how every
coordinate and distance is written, and give the three questions the word
"units" runs together a place each:

- The button offers the five length formats, each shown beside a sample of
  itself, so Engineering and Architectural are told apart by sight.
- UNITS / DDUNITS opens a real dialog: length and angle format and
  precision, the direction angle zero points, whether positive angles run
  clockwise, and the insertion unit. Its sample comes from the same
  formatters the drawing uses, so it cannot drift from the readout.
- DWGUNITS converts. Model geometry, viewport framing, the header's length
  defaults and each dimension style's scale all move together in one undo
  step; paper space is left alone, since the sheet is still the same sheet.
  Locked layers are converted too — a half-converted drawing would be at
  two scales at once.

The coordinate readout formatted at four decimal places whatever the
drawing asked for; it now goes through the same format_length the
properties panel uses. That made the angle formats reachable in turn, so
degrees-minutes-seconds now carries the d/'/" marks that say which
convention it is, and surveyor's units are written at all.

Typed input is still plain decimal: a length the readout writes as
5'-6 1/2" cannot yet be typed back. ANGBASE and ANGDIR are stored but not
yet applied to displayed directions.

Closes #668

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
Hakan SevenandClaude Opus 5 committed 2026-08-07 19:59:09 +03:00
1 parent cfc7c06c6c
commit 523b85f42b
14 files changed
+937 -69

No files matched your search

+69 -42
View File
@@ -1,60 +1,87 @@
//! Drawing-units status menu.
//! Linear-format status menu — the button that decides how every coordinate
//! and distance in the drawing is written.
//!
//! It offers LUNITS, not INSUNITS. Picking "Architectural" changes what the
//! readout, the properties panel and every dimension say; picking a *unit*
//! changes nothing anybody can see, which is why that choice lives in the UNITS
//! dialog next to the insertion scale it belongs to. (#668)
use iced::widget::{button, row, text};
use iced::{Element, Fill};
use iced::widget::{button, container, row, text, Space};
use iced::{Background, Element, Fill, Theme};
use crate::app::Message;
use crate::ui::statusbar::status_menu::Entry;
use crate::t;
use crate::ui::statusbar::status_menu::Entry;
/// Units offered in the picker: (INSUNITS code, menu label).
const UNITS: &[(i16, &str)] = &[
(0, "Unitless"),
(4, "Millimeters"),
(5, "Centimeters"),
(6, "Meters"),
(7, "Kilometers"),
(1, "Inches"),
(2, "Feet"),
(3, "Miles"),
(10, "Yards"),
];
/// Short label shown on the status-bar pill for an INSUNITS code.
pub fn unit_short(code: i16) -> &'static str {
match code {
1 => "in",
2 => "ft",
3 => "mi",
4 => "mm",
5 => "cm",
6 => "m",
7 => "km",
10 => "yd",
0 => "Unitless",
_ => "Unit",
}
}
use crate::modules::draw::units;
pub fn menu_entries(current: i16) -> Vec<Entry<'static>> {
UNITS
.iter()
.map(|&(code, label)| {
Entry::close(unit_row(
let mut entries: Vec<Entry<'static>> = units::linear_formats()
.map(|(code, label, sample)| {
Entry::close(format_row(
label,
sample,
code == current,
Message::SetDrawingUnits(code),
Message::SetLinearFormat(code),
))
})
.collect()
.collect();
// Precision, angles and the insertion unit are all part of the same
// decision and all live one dialog away, so the way there is offered here
// rather than left to be found.
entries.push(Entry::stay(divider()));
entries.push(Entry::close(link(
t!("Units\u{2026}").into_owned(),
"UNITS",
)));
entries.push(Entry::close(link(
t!("Convert drawing\u{2026}").into_owned(),
"DWGUNITS",
)));
entries
}
fn unit_row(label: &'static str, active: bool, msg: Message) -> Element<'static, Message> {
let check = crate::ui::icons::themed_check_cell(active);
fn divider() -> Element<'static, Message> {
container(Space::new().height(1))
.style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().background.weak.color)),
..Default::default()
})
.width(Fill)
.padding([0, 4])
.into()
}
let lbl = text(t!(label)).size(11);
fn link(label: String, command: &'static str) -> Element<'static, Message> {
button(text(label).size(11))
.on_press(Message::Command(command.into()))
.style(button::subtle)
.width(Fill)
.padding([4, 10])
.into()
}
let content = row![check, lbl].spacing(6).align_y(iced::Center);
/// One format, shown with a sample of itself so the difference between
/// Engineering and Architectural is visible rather than recalled.
fn format_row(
label: &'static str,
sample: &'static str,
active: bool,
msg: Message,
) -> Element<'static, Message> {
let content = row![
crate::ui::icons::themed_check_cell(active),
text(t!(label)).size(11),
Space::new().width(Fill),
text(sample).size(10).style(|theme: &Theme| {
iced::widget::text::Style {
color: Some(theme.palette().background.base.text.scale_alpha(0.55)),
}
}),
]
.spacing(6)
.align_y(iced::Center);
button(content)
.on_press(msg)
+23 -11
View File
@@ -102,8 +102,8 @@ impl StatusBar {
picking: bool,
// True while clean-screen mode hides the ribbon and side panels.
clean_screen: bool,
// Drawing units (INSUNITS) for the units pill.
insertion_units: i16,
// LUNITS — how lengths are written, for the units pill.
linear_format: i16,
// True when objects are hidden by Isolate / Hide.
isolation_active: bool,
// Whether entity transparency is shown (Transparency pill state).
@@ -353,11 +353,13 @@ impl StatusBar {
pills.push(
status_menu::menu_bar(
menu_tip(
popup_pill(t!(crate::ui::popup::units_popup::unit_short(insertion_units))),
t!("Drawing Units (INSUNITS)\nClick to change"),
popup_pill(t!(crate::modules::draw::units::linear_format_short(
linear_format
))),
t!("Units (LUNITS)\nHow lengths are written\nClick to change"),
tooltip_hidden,
),
crate::ui::popup::units_popup::menu_entries(insertion_units),
crate::ui::popup::units_popup::menu_entries(linear_format),
140.0,
)
.into(),
@@ -554,8 +556,15 @@ impl StatusBar {
// ── Coordinate readout ────────────────────────────────────────────────────
/// The readout, in the drawing's own linear units.
///
/// Lengths went out at four decimal places whatever the drawing asked for, so a
/// drawing set to architectural units read its coordinates in decimals, and one
/// asking for two places got four. `format_length` is the same helper the
/// properties panel formats through, so both now say a length the same way.
fn format_coords(cursor: glam::DVec3, last: Option<glam::DVec3>, mode: i16, picking: bool) -> String {
let abs = |p: glam::DVec3| format!("{:.4}, {:.4}, {:.4}", p.x, p.y, p.z);
use crate::entities::common::format_length as len;
let abs = |p: glam::DVec3| format!("{}, {}, {}", len(p.x), len(p.y), len(p.z));
match mode {
// Static: show the last picked point; the readout freezes between picks.
0 => abs(last.unwrap_or(cursor)),
@@ -565,11 +574,14 @@ fn format_coords(cursor: glam::DVec3, last: Option<glam::DVec3>, mode: i16, pick
(true, Some(l)) => {
let d = cursor - l;
let dist = (d.x * d.x + d.y * d.y).sqrt();
let mut ang = d.y.atan2(d.x).to_degrees();
if ang < 0.0 {
ang += 360.0;
}
format!("{dist:.4} < {ang:.2}\u{b0}")
// Kept in 0..2pi so the readout never shows a negative bearing,
// then handed over in radians for AUNITS / AUPREC to format.
let ang = d.y.atan2(d.x).rem_euclid(std::f64::consts::TAU);
format!(
"{} < {}",
len(dist),
crate::entities::common::format_angle(ang)
)
}
_ => abs(cursor),
},
+318
View File
@@ -0,0 +1,318 @@
//! Drawing Units — how this drawing writes lengths and angles, and what one of
//! its units measures.
//!
//! Three separate settings that the word "units" runs together, kept in one
//! place because changing one usually means looking at the others. Length and
//! angle formats decide how numbers are *written*; the insertion unit decides
//! what they *count*, and only matters when content arrives from elsewhere.
//! Nothing here moves geometry — DWGUNITS does that.
//!
//! The sample updates as the fields change, so a format is chosen by seeing it
//! rather than by knowing what its name implies. (#668)
use std::fmt;
use iced::widget::{button, checkbox, column, container, row, text, text_input, Space};
use iced::{Border, Element, Fill, Length, Theme};
use crate::app::Message;
use crate::modules::draw::units;
use crate::t;
/// The dialog's working copy. Nothing reaches the drawing until OK, so a format
/// can be tried against the sample and abandoned.
#[derive(Clone, PartialEq)]
pub struct State {
/// LUNITS / LUPREC.
pub linear_format: i16,
pub linear_precision: i16,
/// AUNITS / AUPREC.
pub angular_format: i16,
pub angular_precision: i16,
/// ANGDIR — positive angles run clockwise.
pub clockwise: bool,
/// ANGBASE — the direction angle zero points, in degrees. Held as text so
/// a half-typed number does not snap back while it is being typed.
pub base_angle: String,
/// INSUNITS.
pub insertion_units: i16,
}
/// A dropdown entry that shows a translated name but hands back a raw code.
#[derive(Clone, PartialEq, Eq)]
pub struct Choice {
pub code: i16,
label: &'static str,
sample: &'static str,
}
impl fmt::Display for Choice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = crate::i18n::translate(self.label);
if self.sample.is_empty() {
f.write_str(name.as_ref())
} else {
write!(f, "{name} · {}", self.sample)
}
}
}
/// Which field a dialog message is for.
#[derive(Clone, Debug)]
pub enum Field {
LinearFormat(i16),
LinearPrecision(i16),
AngularFormat(i16),
AngularPrecision(i16),
Clockwise(bool),
BaseAngle(String),
InsertionUnits(i16),
}
fn muted(theme: &Theme) -> iced::widget::text::Style {
iced::widget::text::Style {
color: Some(theme.palette().background.base.text.scale_alpha(0.6)),
}
}
fn group<'a>(title: String, body: Element<'a, Message>) -> Element<'a, Message> {
container(column![text(title).size(11).style(muted), body].spacing(6))
.padding(8)
.width(Fill)
.style(|theme: &Theme| container::Style {
border: Border {
width: 1.0,
radius: 4.0.into(),
color: theme.palette().background.strong.color,
},
..Default::default()
})
.into()
}
fn drop_row<'a>(
label: String,
options: Vec<Choice>,
selected: Option<Choice>,
ctor: fn(i16) -> Field,
) -> Element<'a, Message> {
let picker = iced::widget::pick_list(selected, options, |choice| choice.to_string())
.on_select(move |choice| Message::DrawingUnitsField(ctor(choice.code)))
.text_size(12)
.padding([3, 6])
.width(Fill);
row![text(label).size(11).style(muted).width(78), picker]
.spacing(8)
.align_y(iced::Center)
.into()
}
/// Precision is 0–8 places everywhere it applies; fractional and architectural
/// read the same number as a denominator power, which is why it is offered as
/// a plain count rather than as decimals.
fn precision_row<'a>(
current: i16,
fractional: bool,
ctor: fn(i16) -> Field,
) -> Element<'a, Message> {
let options: Vec<Choice> = (0..=8)
.map(|n| Choice {
code: n,
label: PRECISION_LABELS[n as usize],
sample: if fractional {
FRACTION_SAMPLES[n as usize]
} else {
""
},
})
.collect();
let selected = options
.iter()
.find(|choice| choice.code == current.clamp(0, 8))
.cloned();
drop_row(t!("Precision").into_owned(), options, selected, ctor)
}
const PRECISION_LABELS: [&str; 9] = ["0", "1", "2", "3", "4", "5", "6", "7", "8"];
const FRACTION_SAMPLES: [&str; 9] = [
"1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256",
];
pub fn view_window<'a>(
state: &State,
sizing: crate::ui::modal::ModalSizing,
) -> Element<'a, Message> {
let linear_options: Vec<Choice> = units::linear_formats()
.map(|(code, label, sample)| Choice {
code,
label,
sample,
})
.collect();
let linear_selected = linear_options
.iter()
.find(|choice| choice.code == state.linear_format)
.cloned();
// Architectural and fractional read precision as a fraction denominator,
// so the list shows fractions instead of decimal places for those two.
let fractional = matches!(state.linear_format, 4 | 5);
let angular_options: Vec<Choice> = units::angular_formats()
.map(|(code, label, sample)| Choice {
code,
label,
sample,
})
.collect();
let angular_selected = angular_options
.iter()
.find(|choice| choice.code == state.angular_format)
.cloned();
let insertion_options: Vec<Choice> = units::all()
.map(|(code, label)| Choice {
code,
label,
sample: "",
})
.collect();
let insertion_selected = insertion_options
.iter()
.find(|choice| choice.code == state.insertion_units)
.cloned();
let length = group(
t!("Length").into_owned(),
column![
drop_row(
t!("Type").into_owned(),
linear_options,
linear_selected,
Field::LinearFormat
),
precision_row(state.linear_precision, fractional, Field::LinearPrecision),
]
.spacing(6)
.into(),
);
let angle = group(
t!("Angle").into_owned(),
column![
drop_row(
t!("Type").into_owned(),
angular_options,
angular_selected,
Field::AngularFormat
),
precision_row(state.angular_precision, false, Field::AngularPrecision),
row![
text(t!("Zero at")).size(11).style(muted).width(78),
text_input("0", &state.base_angle)
.on_input(|value| Message::DrawingUnitsField(Field::BaseAngle(value)))
.size(12)
.padding([3, 6])
.width(Length::Fixed(80.0)),
text(t!("degrees")).size(11).style(muted),
]
.spacing(8)
.align_y(iced::Center),
row![
Space::new().width(Length::Fixed(78.0)),
checkbox(state.clockwise)
.on_toggle(|on| Message::DrawingUnitsField(Field::Clockwise(on)))
.size(14),
text(t!("Positive angles run clockwise")).size(11),
]
.spacing(6)
.align_y(iced::Center),
]
.spacing(6)
.into(),
);
// What the insertion unit is for, said once here, because the setting is
// invisible until content arrives from another drawing and is otherwise
// easy to mistake for the one above it.
let insertion = group(
t!("Insertion scale").into_owned(),
column![
drop_row(
t!("Unit").into_owned(),
insertion_options,
insertion_selected,
Field::InsertionUnits
),
text(t!(
"Scales blocks and drawings inserted from elsewhere. Unitless inserts them unscaled."
))
.size(10)
.style(muted),
]
.spacing(6)
.into(),
);
let sample = group(
t!("Sample output").into_owned(),
column![
text(sample_length(state)).size(12),
text(sample_angle(state)).size(12),
]
.spacing(3)
.into(),
);
let actions = row![
Space::new().width(Fill),
button(text(t!("Cancel")).size(12))
.on_press(Message::CloseModal)
.padding([4, 12]),
button(text(t!("OK")).size(12))
.on_press(Message::DrawingUnitsApply)
.style(button::primary)
.padding([4, 12]),
]
.spacing(6)
.align_y(iced::Center);
column![row![length, angle].spacing(8), insertion, sample, actions,]
.spacing(8)
.padding(10)
.width(sizing.width)
.into()
}
/// The sample is produced by the same formatters the drawing uses, so what it
/// shows is what the readout will show — not a second implementation that can
/// drift from the first.
fn sample_length(state: &State) -> String {
with_context(state, || {
crate::entities::common::format_length(1.5)
+ " "
+ &crate::entities::common::format_length(33.5)
})
}
fn sample_angle(state: &State) -> String {
with_context(state, || {
crate::entities::common::format_angle(std::f64::consts::FRAC_PI_4)
})
}
/// Format under the dialog's pending settings, then put back whatever the rest
/// of the frame is drawing with. Without the restore the sample would leak its
/// settings into every widget drawn after it.
fn with_context(state: &State, body: impl FnOnce() -> String) -> String {
use crate::entities::common::{set_unit_context, unit_context, UnitContext};
let previous = unit_context();
set_unit_context(UnitContext {
lunits: state.linear_format,
luprec: state.linear_precision,
aunits: state.angular_format,
auprec: state.angular_precision,
});
let out = body();
set_unit_context(previous);
out
}
+1
View File
@@ -2,6 +2,7 @@ pub mod about;
pub mod block_palette;
pub mod layout_manager;
pub mod layer_state_manager;
pub mod drawing_units;
pub mod layer_translator;
pub mod plot;
pub mod print_all;