mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1cb40332b | ||
|
|
b7d5ed3401 | ||
|
|
6b767073d8 | ||
|
|
7bcfe25938 | ||
|
|
3886fb952d | ||
|
|
6c9eedd7e1 | ||
|
|
6411c1a4ab | ||
|
|
6f203fb64b | ||
|
|
a2d209e10b | ||
|
|
cd226cdf0f | ||
|
|
8d2c9d1a26 | ||
|
|
0156fd9b9f | ||
|
|
df2a5131af | ||
|
|
5644c6c946 | ||
|
|
0fa45daf25 | ||
|
|
a92fb047d8 | ||
|
|
33dc795c5f | ||
|
|
4255108429 | ||
|
|
0b585fa8cb | ||
|
|
21d9627840 | ||
|
|
1c611d610d | ||
|
|
076b7761a3 | ||
|
|
71a0ef2260 | ||
|
|
4fadc54dbe | ||
|
|
9c2ebc0e12 | ||
|
|
98240d82d0 | ||
|
|
1e1cf10a1c | ||
|
|
af460caac6 | ||
|
|
ad072e6cb0 |
@@ -233,11 +233,38 @@ fn saved_window(app_ron: &str) -> bool {
|
||||
ron::from_str::<std::collections::HashMap<String, String>>(app_ron).is_ok_and(|kv| kv.contains_key(WINDOW_KEY))
|
||||
}
|
||||
|
||||
/// The window state from the last session is saved and will be restored (#2595).
|
||||
/// The window state from the last session is saved and will be restored (#2595). A saved size
|
||||
/// below the minimum (seen on Windows: 64×64 points, which eframe restores un-maximized and
|
||||
/// unusable) is dropped first, so the window opens at its default size.
|
||||
fn restores_window() -> bool {
|
||||
eframe::storage_dir(APP_ID).and_then(|dir| std::fs::read_to_string(dir.join("app.ron")).ok()).is_some_and(|ron| saved_window(&ron))
|
||||
let Some(path) = eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron")) else { return false };
|
||||
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
|
||||
if let Some(fixed) = without_tiny_window(&ron)
|
||||
&& std::fs::write(&path, &fixed).is_ok()
|
||||
{
|
||||
ron = fixed;
|
||||
}
|
||||
saved_window(&ron)
|
||||
}
|
||||
|
||||
/// `app_ron` without its window entry when that entry's inner size is below `MIN_INNER_SIZE`;
|
||||
/// `None` when there is nothing to drop (no entry, a usable size, or an unreadable file).
|
||||
fn without_tiny_window(app_ron: &str) -> Option<String> {
|
||||
let mut kv = ron::from_str::<std::collections::BTreeMap<String, String>>(app_ron).ok()?;
|
||||
let w = kv.get(WINDOW_KEY)?;
|
||||
let size = &w[w.find("inner_size_points:")?..];
|
||||
let num = |k: &str| size[size.find(k)? + k.len()..].split([',', ')']).next()?.trim().parse::<f32>().ok();
|
||||
let (x, y) = (num("x:")?, num("y:")?);
|
||||
if x >= MIN_INNER_SIZE[0] && y >= MIN_INNER_SIZE[1] {
|
||||
return None;
|
||||
}
|
||||
kv.remove(WINDOW_KEY);
|
||||
ron::ser::to_string_pretty(&kv, ron::ser::PrettyConfig::default()).ok()
|
||||
}
|
||||
|
||||
/// The smallest main window, in points.
|
||||
const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
|
||||
|
||||
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
|
||||
/// saved by the last session is restored instead of opening centred.
|
||||
fn window_options(restoring: bool) -> eframe::NativeOptions {
|
||||
@@ -245,7 +272,7 @@ fn window_options(restoring: bool) -> eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("CADCraft")
|
||||
.with_inner_size([1600.0, 1000.0])
|
||||
.with_min_inner_size([900.0, 560.0])
|
||||
.with_min_inner_size(MIN_INNER_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
@@ -403,6 +430,9 @@ fn main() -> eframe::Result {
|
||||
app.ui = ui;
|
||||
}
|
||||
app.set_system_cursor_default(vars.system_cursor == Switch::On);
|
||||
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
app.set_native_menus(vars.no_native_menu != Switch::On);
|
||||
if let Some(error) = &workspace_error {
|
||||
eprintln!("CADCraft workspace: {error}");
|
||||
app.set_status(error);
|
||||
@@ -481,7 +511,7 @@ fn main() -> eframe::Result {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{filters_for_save, follow_desktop, saved_window, window_options};
|
||||
use super::{filters_for_save, follow_desktop, saved_window, window_options, without_tiny_window};
|
||||
|
||||
#[test]
|
||||
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
|
||||
@@ -525,6 +555,17 @@ mod tests {
|
||||
assert!(!saved_window("not ron at all"));
|
||||
}
|
||||
|
||||
/// A saved 64×64 window (below the minimum) is dropped; a usable one is kept.
|
||||
#[test]
|
||||
fn a_tiny_saved_window_is_dropped() {
|
||||
let tiny = r#"{"window": "(normal_geometry:(outer_position_pixels:Some((x:0.0,y:0.0)),scale_factor:1.25,inner_size_points:(x:64.0,y:64.0)),fullscreen:false,maximized:true)", "cadcraft.prefs": "{}"}"#;
|
||||
let fixed = without_tiny_window(tiny).expect("dropped");
|
||||
assert!(!saved_window(&fixed) && fixed.contains("cadcraft.prefs"));
|
||||
let ok = tiny.replace("x:64.0,y:64.0)),", "x:1600.0,y:1000.0)),");
|
||||
assert_eq!(without_tiny_window(&ok), None);
|
||||
assert_eq!(without_tiny_window("not ron"), None);
|
||||
}
|
||||
|
||||
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
|
||||
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
|
||||
#[test]
|
||||
|
||||
@@ -805,11 +805,9 @@ pub struct PageSetup {
|
||||
/// Plot objects with their transparency ("Plot transparency"; PLOTTRANSPARENCYOVERRIDE can
|
||||
/// override it). The DXF plot layout flags have no bit for it, so it is not saved in DXF.
|
||||
pub plot_transparency: bool,
|
||||
/// Explicit paper-space unit for the layout: `Some(true)` for millimetres (plot paper units 1
|
||||
/// in DXF), `Some(false)` for inches, or `None` to follow the drawing's `MEASUREMENT` (#1058,
|
||||
/// #3249).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub paper_mm: Option<bool>,
|
||||
/// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the
|
||||
/// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058).
|
||||
pub paper_mm: bool,
|
||||
/// Paper size (DXF groups 44, 45) and plot rotation (group 73) as the file stored them.
|
||||
/// Saving writes them back while they still describe `width_mm`, `height_mm` and
|
||||
/// `landscape`, so each program's convention for media defined wider than tall survives a
|
||||
@@ -841,7 +839,7 @@ impl Default for PageSetup {
|
||||
lineweights: true,
|
||||
show_plot_styles: false,
|
||||
plot_transparency: false,
|
||||
paper_mm: None,
|
||||
paper_mm: false,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ pub(crate) mod groups;
|
||||
pub(crate) mod hatch;
|
||||
mod image;
|
||||
mod inquiry;
|
||||
pub mod interface;
|
||||
mod layer;
|
||||
mod layout;
|
||||
mod lisp;
|
||||
@@ -212,6 +213,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(inquiry::specs());
|
||||
v.extend(settings::specs());
|
||||
v.extend(options::specs());
|
||||
v.extend(interface::specs());
|
||||
v.extend(utility::specs());
|
||||
v.extend(table::specs());
|
||||
v.extend(tolerance::specs());
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_color::Rgb;
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Space};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, PageSetup, Space};
|
||||
use cadcraft_geom::{Bounds2, Mat3, Vec2};
|
||||
use cadcraft_render::paper::{self, Sheet};
|
||||
use cadcraft_render::raster::{RasterOptions, View};
|
||||
@@ -276,8 +276,18 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc()?;
|
||||
let mut page = match space.layout() {
|
||||
Some(n) => d.layout(n).map(|l| l.page.clone()).unwrap_or_default(),
|
||||
// Model space plots on ISO A4 (metric) or ANSI A, like the PDF plotter.
|
||||
None => paper::model_page(d),
|
||||
None => {
|
||||
// Model space plots on A4 (metric) or ANSI A, like the PDF plotter.
|
||||
let mut page = PageSetup::default();
|
||||
if paper::paper_unit_mm(d) == 1.0
|
||||
&& let Some(a4) = paper::paper_size("A4")
|
||||
{
|
||||
page.paper = a4.name.into();
|
||||
page.width_mm = a4.width_mm;
|
||||
page.height_mm = a4.height_mm;
|
||||
}
|
||||
page
|
||||
}
|
||||
};
|
||||
if let Some(name) = str_param(p, "paper") {
|
||||
let ps = paper::paper_size(name).ok_or_else(|| bad("preview", format!("unknown paper size `{name}`")))?;
|
||||
@@ -285,10 +295,6 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
page.width_mm = ps.width_mm;
|
||||
page.height_mm = ps.height_mm;
|
||||
}
|
||||
// A model-space plot takes its units from the paper it was given (a layout keeps its page setup's).
|
||||
if matches!(space, Space::Model) {
|
||||
paper::apply_model_paper_units(&mut page);
|
||||
}
|
||||
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
|
||||
page.landscape = l;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! MENUBAR and TOOLBAR: show or hide the window's menu bar and tool bar from the command line, as
|
||||
//! in AutoCAD. With the menu bar hidden on Windows and Linux (where it is the only menu), typing
|
||||
//! these is the way back.
|
||||
//!
|
||||
//! The UI owns the bars: it reports what it shows in [`Session::bars_shown`] and applies
|
||||
//! [`Session::bars_request`], which these commands set.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad};
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
/// The interface bars MENUBAR and TOOLBAR control.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct InterfaceBars {
|
||||
pub menubar: bool,
|
||||
pub toolbar: bool,
|
||||
}
|
||||
|
||||
impl Default for InterfaceBars {
|
||||
fn default() -> Self {
|
||||
InterfaceBars { menubar: true, toolbar: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// A change MENUBAR or TOOLBAR asked for: only the bars a command set, so the UI leaves the other
|
||||
/// as it is (it may have been changed since).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BarsRequest {
|
||||
pub menubar: Option<bool>,
|
||||
pub toolbar: Option<bool>,
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("menubar", "Menu Bar", run_menubar)
|
||||
.params("{value?: 0|1} (1 shows the in-window menu bar, 0 hides it; without it, reports it)")
|
||||
.enabled(always)
|
||||
.noundo()
|
||||
.interactive(|s| Ok(Box::new(MenubarM { current: s.bars_shown.menubar }))),
|
||||
CommandSpec::new("toolbar", "Tool Bar", run_toolbar)
|
||||
.alias(&["-toolbar"])
|
||||
.params("{show?: bool} (without it, reports it)")
|
||||
.enabled(always)
|
||||
.noundo()
|
||||
.interactive(|_| Ok(Box::new(ToolbarM))),
|
||||
]
|
||||
}
|
||||
|
||||
fn set_menubar(s: &mut Session, on: bool) {
|
||||
s.bars_shown.menubar = on;
|
||||
s.bars_request.menubar = Some(on);
|
||||
}
|
||||
|
||||
fn set_toolbar(s: &mut Session, show: bool) {
|
||||
s.bars_shown.toolbar = show;
|
||||
s.bars_request.toolbar = Some(show);
|
||||
}
|
||||
|
||||
fn run_menubar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let v = match p.get("value") {
|
||||
None | Some(Value::Null) => return Ok(json!({ "value": u8::from(s.bars_shown.menubar) })),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.or_else(|| v.as_str().and_then(|t| t.trim().parse().ok()))
|
||||
.filter(|v| *v <= 1)
|
||||
.ok_or_else(|| bad("menubar", "`value` must be 0 or 1"))?,
|
||||
};
|
||||
set_menubar(s, v == 1);
|
||||
Ok(json!({ "value": v }))
|
||||
}
|
||||
|
||||
fn run_toolbar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(show) = p.get("show").filter(|v| !v.is_null()) else { return Ok(json!({ "show": s.bars_shown.toolbar })) };
|
||||
let show = show.as_bool().ok_or_else(|| bad("toolbar", "`show` must be true or false"))?;
|
||||
set_toolbar(s, show);
|
||||
Ok(json!({ "show": show }))
|
||||
}
|
||||
|
||||
/// Typed MENUBAR: "Enter new value for MENUBAR <1>:".
|
||||
struct MenubarM {
|
||||
current: bool,
|
||||
}
|
||||
|
||||
impl Interactive for MenubarM {
|
||||
fn name(&self) -> &'static str {
|
||||
"MENUBAR"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
Prompt::new("Enter new value for MENUBAR", Accept::NUMBER).default(u8::from(self.current).to_string())
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match i {
|
||||
Input::Enter => Ok(Step::Done),
|
||||
Input::Text(t) => match run_menubar(s, &json!({ "value": t })) {
|
||||
Ok(_) => Ok(Step::Done),
|
||||
Err(_) => {
|
||||
s.echo("Requires 0 or 1.");
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
},
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed TOOLBAR: "Enter tool bar option [Show/Hide] <Show>:" (CADCraft has one tool bar).
|
||||
struct ToolbarM;
|
||||
|
||||
impl Interactive for ToolbarM {
|
||||
fn name(&self) -> &'static str {
|
||||
"TOOLBAR"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
Prompt::new("Enter tool bar option", Accept::TEXT).kw(&["Show", "Hide"]).default("Show")
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let word = match &i {
|
||||
Input::Enter => "show".to_string(),
|
||||
Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let show = if !word.is_empty() && "show".starts_with(&word) {
|
||||
true
|
||||
} else if !word.is_empty() && "hide".starts_with(&word) {
|
||||
false
|
||||
} else {
|
||||
s.echo("Invalid option keyword.");
|
||||
return Ok(Step::Continue);
|
||||
};
|
||||
run_toolbar(s, &json!({ "show": show }))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
|
||||
.menu(&["File", "Page Setup Manager..."])
|
||||
.params(
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
),
|
||||
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
|
||||
.menu(&["File", "Print..."])
|
||||
@@ -641,7 +641,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"width",
|
||||
"height",
|
||||
"landscape",
|
||||
"paperUnits",
|
||||
"margins",
|
||||
"lineweights",
|
||||
"plotArea",
|
||||
@@ -683,22 +682,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
page.width_mm = ps.width_mm;
|
||||
page.height_mm = ps.height_mm;
|
||||
}
|
||||
// The picked paper's own units become the layout's paper units: millimetres for a metric
|
||||
// paper, else the drawing's MEASUREMENT. Otherwise ISO A0 in a new (imperial) drawing's
|
||||
// layout is 33.11 x 46.81 units (#2836). This holds for a standard size from the page's
|
||||
// device's list too (the built-in devices list every standard size), and a device's own
|
||||
// paper that is not a standard size keeps the layout's units. Only a saved page setup changes
|
||||
// units; a one-off plot's `paper` keeps the layout's, so its objects stay the size they were
|
||||
// drawn. A custom `width` and `height` in the same call replace this paper below, and a
|
||||
// custom size keeps the layout's units, with `paper` or without it. An explicit `paperUnits`
|
||||
// in the same call wins (below).
|
||||
if p.get("paper").is_some()
|
||||
&& p.get("width").is_none()
|
||||
&& p.get("height").is_none()
|
||||
&& let Some(ps) = cadcraft_render::paper_size(&page.paper)
|
||||
{
|
||||
page.paper_mm = (!ps.imperial).then_some(true);
|
||||
}
|
||||
let mm = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0 && *v <= 5080.0);
|
||||
match (mm("width"), mm("height")) {
|
||||
(Some(w), Some(h)) => {
|
||||
@@ -712,15 +695,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
|
||||
page.landscape = l;
|
||||
}
|
||||
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
|
||||
// (an ARCH D sheet can be drawn in millimetres, #3249).
|
||||
if let Some(v) = p.get("paperUnits") {
|
||||
page.paper_mm = Some(match v.as_str().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("mm" | "millimeters" | "millimetres") => true,
|
||||
Some("in" | "inch" | "inches") => false,
|
||||
_ => return Err(bad(cmd, "`paperUnits` must be \"mm\" or \"inches\"")),
|
||||
});
|
||||
}
|
||||
if let Some(m) = p.get("margins") {
|
||||
let a: Vec<f64> = m.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
match a[..] {
|
||||
|
||||
@@ -165,57 +165,14 @@ fn viewport_scale_lock_and_layers() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #2836: picking a paper sets the layout's paper units from it. In a new drawing (imperial,
|
||||
/// MEASUREMENT 0) ISO A0 was 46.81 x 33.11 units, the inch equivalent; now it is 1189 x 841.
|
||||
/// An inch paper gives the layout back the drawing's units.
|
||||
#[test]
|
||||
fn pagesetup_paper_sets_the_layout_paper_units() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(cadcraft_render::paper::paper_unit_mm(s.doc().unwrap()), 25.4, "a new drawing is imperial");
|
||||
let size = |s: &Session| {
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
((sheet.size.x * 100.0).round() / 100.0, (sheet.size.y * 100.0).round() / 100.0, sheet.unit_mm)
|
||||
};
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A0", "landscape": true})).unwrap();
|
||||
assert_eq!(r["page"]["paperMm"], true);
|
||||
assert_eq!(size(&s), (1189.0, 841.0, 1.0), "ISO A0 in millimetres");
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ANSI D"})).unwrap();
|
||||
assert_eq!(size(&s), (34.0, 22.0, 25.4), "ANSI D in the drawing's inches");
|
||||
// A custom size replaces the named paper in the same call and keeps the layout's units.
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A4", "width": 254, "height": 508})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, None, "the layout still follows MEASUREMENT");
|
||||
assert_eq!(size(&s), (20.0, 10.0, 25.4), "the custom size in the layout's inches");
|
||||
}
|
||||
|
||||
/// #2836 through a device: the built-in devices list every standard size, so a paper picked in
|
||||
/// Page Setup with CADCraft PDF as the device comes from the device's list. It sets the layout's
|
||||
/// paper units as a paper picked with no device does.
|
||||
#[test]
|
||||
fn pagesetup_device_paper_sets_the_layout_paper_units() {
|
||||
let mut s = Session::new();
|
||||
let size = |s: &Session| {
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
((sheet.size.x * 100.0).round() / 100.0, (sheet.size.y * 100.0).round() / 100.0, sheet.unit_mm)
|
||||
};
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "CADCraft PDF", "landscape": true})).unwrap();
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ISO A0 (841.00 x 1189.00 MM)"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.device, "CADCraft PDF");
|
||||
assert_eq!(size(&s), (1189.0, 841.0, 1.0), "ISO A0 from the device's list in millimetres");
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ANSI D"})).unwrap();
|
||||
assert_eq!(size(&s), (34.0, 22.0, 25.4), "ANSI D from the device's list in the drawing's inches");
|
||||
// An explicit choice in the same call wins over the paper's own units (#3249).
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "paperUnits": "mm"})).unwrap();
|
||||
assert_eq!(size(&s), (914.4, 609.6, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_paper_table() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A3", "landscape": true, "margins": [5, 5, 5, 5]})).unwrap();
|
||||
assert_eq!(r["page"]["widthMm"], 297.0);
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
// An imperial drawing, but a metric paper: the layout's paper units are millimetres (#2836).
|
||||
assert!((sheet.size.x - 420.0).abs() < 1e-9 && (sheet.size.y - 297.0).abs() < 1e-9);
|
||||
// Imperial drawing: paper units are inches.
|
||||
assert!((sheet.size.x - 420.0 / 25.4).abs() < 1e-9 && (sheet.size.y - 297.0 / 25.4).abs() < 1e-9);
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "Z12"})).is_err());
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "margins": [1, 2]})).is_err());
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "width": 1e308, "height": 5})).is_err());
|
||||
@@ -233,40 +190,6 @@ fn pagesetup_paper_table() {
|
||||
assert_eq!((p.width_mm, p.height_mm), (300.0, 500.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_paper_units_make_an_inch_sheet_metric() {
|
||||
// An ARCH D sheet in a drawing that measures in millimetres (#3249): the page setup's paper
|
||||
// units decide the paper-space unit, so the sheet can be 914.4 x 609.6 mm.
|
||||
let mut s = Session::new();
|
||||
s.execute("units", &json!({"insunits": 4})).unwrap();
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "landscape": true, "paperUnits": "mm"})).unwrap();
|
||||
assert_eq!(r["page"]["paperMm"], true);
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((sheet.size.x - 914.4).abs() < 1e-9 && (sheet.size.y - 609.6).abs() < 1e-9, "{:?}", sheet.size);
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "Inches"})).unwrap();
|
||||
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((sheet.size.x - 36.0).abs() < 1e-9 && (sheet.size.y - 24.0).abs() < 1e-9, "{:?}", sheet.size);
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "millimeters"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(true));
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "feet"})).is_err());
|
||||
assert!(s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": 4})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pagesetup_paper_units_inches_overrides_metric_measurement() {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({"name": "MEASUREMENT", "value": 1})).unwrap();
|
||||
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "ARCH D", "landscape": true})).unwrap();
|
||||
// Without an explicit paperUnits choice, MEASUREMENT = 1 keeps the sheet in millimetres.
|
||||
let metric = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((metric.size.x - 914.4).abs() < 1e-9 && (metric.size.y - 609.6).abs() < 1e-9, "{:?}", metric.size);
|
||||
let r = s.execute("pagesetup", &json!({"layout": "Layout1", "paperUnits": "inches"})).unwrap();
|
||||
assert_eq!(r["page"]["paperMm"], false);
|
||||
assert_eq!(s.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
let inch = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
}
|
||||
|
||||
fn fake_plot(d: &Drawing, space: &Space, opts: &Value) -> std::result::Result<Vec<u8>, String> {
|
||||
let _ = d;
|
||||
Ok(format!("%PDF-1.4 fake {space:?} {opts}").into_bytes())
|
||||
|
||||
@@ -156,6 +156,10 @@ pub struct Session {
|
||||
lisp_last: Option<std::result::Result<lisp::value::Value, String>>,
|
||||
/// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks).
|
||||
pub hatch_picks: Option<cmd::hatch::HatchPicks>,
|
||||
/// The window's menu bar and tool bar as the UI shows them (it reports them every frame).
|
||||
pub bars_shown: cmd::interface::InterfaceBars,
|
||||
/// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply.
|
||||
pub bars_request: cmd::interface::BarsRequest,
|
||||
/// The object named with a point for the input a prompt picking one object is taking
|
||||
/// ([`Session::input_object`]): a pick at exactly that point picks that object
|
||||
/// ([`Session::pick_object`]).
|
||||
@@ -215,6 +219,8 @@ impl Session {
|
||||
lisp: lisp::LispState::default(),
|
||||
lisp_last: None,
|
||||
hatch_picks: None,
|
||||
bars_shown: Default::default(),
|
||||
bars_request: Default::default(),
|
||||
pick_hint: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut V
|
||||
// LAYOUT has two 330s: owner dict and the block record; take the last.
|
||||
let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default();
|
||||
let plot = T(tg.get(..start).unwrap_or(&[]));
|
||||
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot, &tg), limits(&t)));
|
||||
layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot), limits(&t)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,9 +231,8 @@ impl Objects {
|
||||
}
|
||||
}
|
||||
|
||||
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm), and its
|
||||
/// CADCraft xdata in the record's `tags`.
|
||||
pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
|
||||
pub(super) fn page_setup(t: &T) -> PageSetup {
|
||||
let mut p = PageSetup::default();
|
||||
let mm = |code: i32, d: f64| {
|
||||
let v = t.fd(code, d);
|
||||
@@ -245,17 +244,9 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
p.height_mm = w.max(h);
|
||||
}
|
||||
p.margins_mm = [mm(40, p.margins_mm[0]), mm(41, p.margins_mm[1]), mm(42, p.margins_mm[2]), mm(43, p.margins_mm[3])];
|
||||
// CADCraft's paper units come first (PSUNITS xdata: 0 inches, 1 millimetres, 2 follows
|
||||
// MEASUREMENT), because plot paper units 0 cannot tell an explicit inch layout from an unset
|
||||
// one: earlier CADCraft versions wrote 0 for every layout, so 0 alone is left to MEASUREMENT.
|
||||
// Plot paper units 1 is millimetres (#3249).
|
||||
let units = crate::dxf_ext::xdata_list(crate::dxf_ext::xdata(tags, crate::dxf_ext::APP), "PSUNITS");
|
||||
p.paper_mm = match units.iter().find(|t| t.code == 1070).map(|t| t.i64()) {
|
||||
Some(0) => Some(false),
|
||||
Some(1) => Some(true),
|
||||
Some(2) => None,
|
||||
_ => (t.i(72) == Some(1)).then_some(true),
|
||||
};
|
||||
// Plot paper units 1: millimetres. 0 (inches) is left to MEASUREMENT: earlier CADCraft
|
||||
// versions wrote 0 for every layout.
|
||||
p.paper_mm = t.i(72) == Some(1);
|
||||
// Plot rotation 1 or 3 turns the media a quarter turn; media defined wider than tall is
|
||||
// already landscape.
|
||||
let rotated = matches!(t.i(73), Some(1 | 3));
|
||||
|
||||
@@ -473,35 +473,14 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
w.p(17, Vec3::new(0.0, 1.0, 0.0));
|
||||
w.i(76, 0);
|
||||
w.s(330, brh);
|
||||
// CADCraft xdata: the saved paper-space view (centre, height), and the layout's paper units.
|
||||
// Group 72 cannot carry the choice on its own: 0 means inches, but it is also what earlier
|
||||
// CADCraft versions wrote for a layout that follows MEASUREMENT, and 1 is what a layout that
|
||||
// inherits a metric MEASUREMENT writes too. PSUNITS keeps the three states apart: 0 inches,
|
||||
// 1 millimetres, 2 follows MEASUREMENT (#3249).
|
||||
let view = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite());
|
||||
let unit_marker = match page.paper_mm {
|
||||
Some(false) => Some(0),
|
||||
Some(true) => Some(1),
|
||||
// An inherited imperial layout writes group 72 = 0, which already reads back as
|
||||
// inherited; only group 72 = 1 is ambiguous and needs the marker.
|
||||
None if cadcraft_render::paper::page_unit_mm(d, page) == 1.0 => Some(2),
|
||||
None => None,
|
||||
};
|
||||
if view.is_some() || unit_marker.is_some() {
|
||||
// The saved paper-space view (centre, height) as CADCraft xdata.
|
||||
if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) {
|
||||
w.s(1001, dxf_ext::APP);
|
||||
if let Some((c, height)) = view {
|
||||
w.s(1000, "PSVIEW");
|
||||
w.s(1002, "{");
|
||||
w.p(1010, c.to3(0.0));
|
||||
w.f(1040, height);
|
||||
w.s(1002, "}");
|
||||
}
|
||||
if let Some(units) = unit_marker {
|
||||
w.s(1000, "PSUNITS");
|
||||
w.s(1002, "{");
|
||||
w.i(1070, units);
|
||||
w.s(1002, "}");
|
||||
}
|
||||
w.s(1000, "PSVIEW");
|
||||
w.s(1002, "{");
|
||||
w.p(1010, c.to3(0.0));
|
||||
w.f(1040, height);
|
||||
w.s(1002, "}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-6
@@ -292,8 +292,17 @@ fn links_json(v: Option<&Value>) -> Vec<(Handle, String)> {
|
||||
pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<PageSetup> {
|
||||
let mut page = match space.layout() {
|
||||
Some(n) => d.layout(n).map(|l| l.page.clone()).ok_or_else(|| IoError::Format(format!("no layout `{n}`")))?,
|
||||
// Model space has no stored page setup: ISO A4 in a metric drawing, ANSI A otherwise.
|
||||
None => paper::model_page(d),
|
||||
None => {
|
||||
let mut p = PageSetup::default();
|
||||
if paper::paper_unit_mm(d) == 1.0
|
||||
&& let Some(a4) = paper::paper_size("A4")
|
||||
{
|
||||
p.paper = a4.name.into();
|
||||
p.width_mm = a4.width_mm;
|
||||
p.height_mm = a4.height_mm;
|
||||
}
|
||||
p
|
||||
}
|
||||
};
|
||||
if let Some(name) = &o.paper {
|
||||
let ps = paper::paper_size(name).ok_or_else(|| IoError::Format(format!("unknown paper size `{name}`")))?;
|
||||
@@ -316,10 +325,6 @@ pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<PageSetup>
|
||||
if let (Space::Model, Some(m)) = (space, o.margins) {
|
||||
page.margins_mm = m;
|
||||
}
|
||||
// A model-space plot takes its units from the paper it was given; a layout keeps its page setup's.
|
||||
if matches!(space, Space::Model) {
|
||||
paper::apply_model_paper_units(&mut page);
|
||||
}
|
||||
page.width_mm = page.width_mm.clamp(1.0, MAX_SHEET_MM);
|
||||
page.height_mm = page.height_mm.clamp(1.0, MAX_SHEET_MM);
|
||||
Ok(page)
|
||||
|
||||
@@ -169,7 +169,7 @@ fn the_added_paper_viewport_follows_the_plot_scale() {
|
||||
let sheet_width = |scale: f64, fit: bool| {
|
||||
let mut d = Drawing::new_metric();
|
||||
let page = &mut d.layouts[0].page;
|
||||
(page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, Some(true));
|
||||
(page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, true);
|
||||
(page.scale, page.scale_to_fit) = (scale, fit);
|
||||
let first = Space::Paper(d.layouts[0].name.clone());
|
||||
d.add(&first, Common::default(), viewport(2)).unwrap();
|
||||
|
||||
@@ -19,7 +19,7 @@ fn drawing() -> Drawing {
|
||||
height_mm: 297.0,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: true,
|
||||
paper_mm: Some(true),
|
||||
paper_mm: true,
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
@@ -57,81 +57,16 @@ fn plot_paper_units_round_trip_through_dxf() {
|
||||
// Written as group 72 = 1 (millimetres) and read back as such.
|
||||
let back = read(write_dxf(&drawing()).as_bytes(), "x.dxf").unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
|
||||
assert_eq!(page.paper_mm, Some(true));
|
||||
assert!(page.paper_mm);
|
||||
assert_eq!(cadcraft_render::sheet(&back, "SHEET").unwrap().unit_mm, 1.0);
|
||||
// A metric drawing's layouts stay in millimetres even from files that say 72 = 0 and carry
|
||||
// no PSUNITS xdata (what earlier CADCraft versions wrote for every layout).
|
||||
// A metric drawing's layouts stay in millimetres even from files that say 72 = 0 (what
|
||||
// earlier CADCraft versions wrote for every layout).
|
||||
let mut metric = Drawing::new_metric();
|
||||
metric.header.set_i64("MEASUREMENT", 1);
|
||||
let written = write_dxf(&metric);
|
||||
let text = written
|
||||
.replace("1001\r\nCADCRAFT\r\n1000\r\nPSUNITS\r\n1002\r\n{\r\n1070\r\n2\r\n1002\r\n}\r\n", "")
|
||||
.replace("\r\n 72\r\n1\r\n", "\r\n 72\r\n0\r\n");
|
||||
let text = written.replace("\r\n 72\r\n1\r\n", "\r\n 72\r\n0\r\n");
|
||||
assert_ne!(text, written, "the layouts' 72 = 1 became 0");
|
||||
let back = read(text.as_bytes(), "old.dxf").unwrap();
|
||||
let name = back.layouts.first().unwrap().name.clone();
|
||||
assert_eq!(cadcraft_render::sheet(&back, &name).unwrap().unit_mm, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_inch_layout_round_trips_on_a_metric_drawing() {
|
||||
// #3249: group 72 = 0 is also what an unset layout writes, so the explicit inch choice
|
||||
// travels in CADCraft xdata and must win over the group 72 fallback.
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
let mut l = Layout::new("INCHES", 3);
|
||||
l.page = PageSetup {
|
||||
paper: "ARCH D".into(),
|
||||
width_mm: 609.6,
|
||||
height_mm: 914.4,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: true,
|
||||
paper_mm: Some(false),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
let back = read(write_dxf(&d).as_bytes(), "x.dxf").unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "INCHES").unwrap().page;
|
||||
assert_eq!(page.paper_mm, Some(false));
|
||||
let sheet = cadcraft_render::sheet(&back, "INCHES").unwrap();
|
||||
assert_eq!(sheet.unit_mm, 25.4);
|
||||
assert!((sheet.size.x - 36.0).abs() < 1e-9 && (sheet.size.y - 24.0).abs() < 1e-9, "{:?}", sheet.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_layout_keeps_following_measurement_after_a_dxf_round_trip() {
|
||||
// #3249: a layout that never chose its paper units reads back as inherited, not fixed to the
|
||||
// MEASUREMENT it had when saved. An ARCH D sheet on a metric drawing is 914.4 x 609.6; after
|
||||
// MEASUREMENT changes to imperial it must be 36 x 24. The explicit choices do not move.
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
for (name, paper_mm) in [("INHERITED", None), ("INCHES", Some(false)), ("MILLIMETRES", Some(true))] {
|
||||
let mut l = Layout::new(name, 3);
|
||||
l.page = PageSetup {
|
||||
paper: "ARCH D".into(),
|
||||
width_mm: 609.6,
|
||||
height_mm: 914.4,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: true,
|
||||
paper_mm,
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
}
|
||||
|
||||
let mut back = read(write_dxf(&d).as_bytes(), "x.dxf").unwrap();
|
||||
let units = |d: &Drawing, name: &str| d.layouts.iter().find(|l| l.name == name).unwrap().page.paper_mm;
|
||||
assert_eq!(units(&back, "INHERITED"), None);
|
||||
assert_eq!(units(&back, "INCHES"), Some(false));
|
||||
assert_eq!(units(&back, "MILLIMETRES"), Some(true));
|
||||
|
||||
back.header.set_i64("MEASUREMENT", 0);
|
||||
let sheet = |name: &str| cadcraft_render::sheet(&back, name).unwrap();
|
||||
let inherited = sheet("INHERITED");
|
||||
assert_eq!(inherited.unit_mm, 25.4);
|
||||
assert!((inherited.size.x - 36.0).abs() < 1e-9 && (inherited.size.y - 24.0).abs() < 1e-9, "{:?}", inherited.size);
|
||||
assert_eq!(sheet("INCHES").unit_mm, 25.4);
|
||||
let metric = sheet("MILLIMETRES");
|
||||
assert_eq!(metric.unit_mm, 1.0);
|
||||
assert!((metric.size.x - 914.4).abs() < 1e-9 && (metric.size.y - 609.6).abs() < 1e-9, "{:?}", metric.size);
|
||||
}
|
||||
|
||||
@@ -60,7 +60,6 @@ mod pdf_layers;
|
||||
#[path = "../support/pdf_read.rs"]
|
||||
mod pdf_read;
|
||||
mod plot_layout_scale;
|
||||
mod plot_model_metric_units;
|
||||
mod plot_model_png_scale;
|
||||
mod plot_styles;
|
||||
mod polyface_roundtrip;
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
//! #1828: a model-space plot at 1:1 in a drawing whose units are millimetres puts a 10 mm line
|
||||
//! at 28.35 pt on an ISO A4 sheet, whatever MEASUREMENT says. A drawing made in millimetres by
|
||||
//! changing the drawing units (UNITS sets INSUNITS, not MEASUREMENT) was plotted 25.4 times too
|
||||
//! large, because model-space paper units were taken as inches.
|
||||
//!
|
||||
//! The model plot's units are the paper's, never the layouts' page setups': a layout whose page
|
||||
//! setup is in inches still plots its paper space in inches (#1866).
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, PageSetup, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
use cadcraft_io::plot;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::pdf_read;
|
||||
|
||||
/// The page size in points.
|
||||
fn media_box(pdf: &[u8]) -> (f64, f64) {
|
||||
pdf_read::read(pdf).media()
|
||||
}
|
||||
|
||||
/// The plotted length in points of the single horizontal line.
|
||||
fn line_pt(pdf: &[u8]) -> f64 {
|
||||
let doc = pdf_read::read(pdf);
|
||||
let xs: Vec<f64> = pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m" || o.op == "l").filter_map(|o| o.nums.first().copied()).collect();
|
||||
assert_eq!(xs.len(), 2, "one line, two ends: {xs:?}");
|
||||
(xs[1] - xs[0]).abs()
|
||||
}
|
||||
|
||||
/// A drawing with one 10-unit line in model space and the given drawing units.
|
||||
fn drawing(insunits: i64, measurement: i64) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_i64("INSUNITS", insunits);
|
||||
d.header.set_i64("MEASUREMENT", measurement);
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
|
||||
d.add(&Space::Model, Common::default(), line).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Plot the model at 1:1 on the named paper, as the Plot dialog does.
|
||||
fn plot_on(d: &Drawing, paper: &str) -> Vec<u8> {
|
||||
let opts: Value = json!({
|
||||
"paper": paper,
|
||||
"landscape": false,
|
||||
"fit": false,
|
||||
"scale": 1,
|
||||
"lineweights": false,
|
||||
"compress": false,
|
||||
});
|
||||
plot(d, &Space::Model, &opts).unwrap()
|
||||
}
|
||||
|
||||
const A4_PT: (f64, f64) = (595.28, 841.89);
|
||||
const ANSI_A_PT: (f64, f64) = (612.0, 792.0);
|
||||
const TEN_MM_PT: f64 = 28.3465;
|
||||
const TEN_IN_PT: f64 = 720.0;
|
||||
|
||||
fn assert_pt(actual: f64, want: f64) {
|
||||
assert!((actual - want).abs() < 0.01, "{actual} pt, want {want}");
|
||||
}
|
||||
|
||||
/// The MediaBox is the sheet in points (A4 or ANSI A, portrait).
|
||||
fn assert_media(pdf: &[u8], size: (f64, f64)) {
|
||||
let (w, h) = media_box(pdf);
|
||||
assert!((w - size.0).abs() < 0.01 && (h - size.1).abs() < 0.01, "{w} x {h} pt, want {size:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_in_a_metric_drawing_is_one_to_one() {
|
||||
let pdf = plot_on(&drawing(4, 1), "ISO A4");
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_MM_PT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_follows_the_length_unit_when_measurement_says_inches() {
|
||||
// A drawing started imperial whose units the user changed to millimetres with UNITS:
|
||||
// MEASUREMENT stays 0, the length unit is what says the drawing is in millimetres.
|
||||
let pdf = plot_on(&drawing(4, 0), "ISO A4");
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_MM_PT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_takes_units_from_the_paper() {
|
||||
// A millimetre sheet at 1:1 prints one drawing unit per millimetre, whatever the drawing's
|
||||
// length unit is.
|
||||
let pdf = plot_on(&drawing(1, 0), "ISO A4");
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_MM_PT);
|
||||
// An inch sheet prints one drawing unit per inch, whatever the drawing's length unit is.
|
||||
let pdf = plot_on(&drawing(4, 0), "ANSI A");
|
||||
assert_media(&pdf, ANSI_A_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_IN_PT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_plot_on_an_inch_sheet_is_in_inches_whatever_measurement_says() {
|
||||
// MEASUREMENT 1 (an ISO-template drawing) must not turn an inch sheet's units into
|
||||
// millimetres: a 10-unit line on ANSI A at 1:1 is 10 inches for every drawing unit.
|
||||
for (insunits, measurement) in [(4, 1), (0, 1), (1, 1), (4, 0)] {
|
||||
let pdf = plot_on(&drawing(insunits, measurement), "ANSI A");
|
||||
assert_media(&pdf, ANSI_A_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_IN_PT);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_plot_keeps_its_page_setup_units() {
|
||||
// The @echelon regression: a metric drawing whose layout has a page setup in inches. The
|
||||
// layout's paper space is in inches (25.4 mm per unit), not in the drawing's millimetres,
|
||||
// and its A4 sheet is still A4.
|
||||
let mut d = drawing(4, 0);
|
||||
let mut l = Layout::new("SHEET", 3);
|
||||
l.page = PageSetup {
|
||||
paper: "ISO A4".into(),
|
||||
width_mm: 210.0,
|
||||
height_mm: 297.0,
|
||||
margins_mm: [0.0; 4],
|
||||
landscape: false,
|
||||
paper_mm: Some(false),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) });
|
||||
d.add(&Space::Paper("SHEET".into()), Common::default(), line).unwrap();
|
||||
let opts = json!({"fit": false, "scale": 1, "lineweights": false, "compress": false});
|
||||
let pdf = plot(&d, &Space::Paper("SHEET".into()), &opts).unwrap();
|
||||
assert_media(&pdf, A4_PT);
|
||||
assert_pt(line_pt(&pdf), TEN_IN_PT);
|
||||
}
|
||||
@@ -197,7 +197,7 @@ pub(super) fn layouts() -> Case {
|
||||
let mut drawing = cases::drawing();
|
||||
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)];
|
||||
for (index, layout) in drawing.layouts.iter_mut().enumerate() {
|
||||
layout.page.paper_mm = Some(true);
|
||||
layout.page.paper_mm = true;
|
||||
// PageSetup stores portrait dimensions; landscape is a separate orientation flag.
|
||||
layout.page.width_mm = 297.0;
|
||||
layout.page.height_mm = 420.0;
|
||||
|
||||
+6
-170
@@ -1,9 +1,7 @@
|
||||
//! Paper sizes and the layout sheet (paper rectangle, printable area) for paper space.
|
||||
//!
|
||||
//! Paper-space units follow a layout's explicit page-setup choice (millimetres or inches), and
|
||||
//! otherwise `MEASUREMENT` (millimetres when 1, inches otherwise). The sheet's lower-left corner is the paper-space origin.
|
||||
//! Model-space plots have no stored page setup, so they take their units from the paper itself
|
||||
//! ([`model_page`], [`model_unit_mm`]).
|
||||
//! Paper-space units are millimetres in metric drawings (`MEASUREMENT` = 1) and on layouts whose
|
||||
//! page setup is in millimetres, and inches otherwise. The sheet's lower-left corner is the paper-space origin.
|
||||
|
||||
use cadcraft_doc::{Drawing, PageSetup};
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
@@ -83,70 +81,11 @@ pub fn paper_unit_mm(d: &Drawing) -> f64 {
|
||||
if d.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 25.4 }
|
||||
}
|
||||
|
||||
/// Whether the drawing's length unit is metric: `INSUNITS` millimetres to kilometres and
|
||||
/// angstroms to parsecs (4..=7, 11..=20) are metric, inches to US survey units (1, 2, 3, 8, 9,
|
||||
/// 10, 21, 22, 23, 24) imperial. A unitless drawing (`INSUNITS` 0, absent or unknown, as files
|
||||
/// without `$INSUNITS` are read, #1209) falls back to `MEASUREMENT` = 1.
|
||||
///
|
||||
/// `MEASUREMENT` only chooses the imperial or ISO hatch and linetype libraries (#1649, #1826),
|
||||
/// so it is not what says a drawing is metric: a drawing whose units are millimetres but whose
|
||||
/// MEASUREMENT is 0 — what UNITS leaves when the user picks millimetres, and what AutoCAD writes
|
||||
/// for many metric drawings — is metric by this test (#1828).
|
||||
pub fn metric_length_unit(d: &Drawing) -> bool {
|
||||
match d.header.i64("INSUNITS", 0) {
|
||||
// Inches, feet, miles, microinches, mils, yards and US survey units.
|
||||
1 | 2 | 3 | 8 | 9 | 10 | 21 | 22 | 23 | 24 => false,
|
||||
// Millimetres, centimetres, metres, kilometres, angstroms, nanometres, microns,
|
||||
// decimetres to gigametres, astronomical units, light years and parsecs.
|
||||
4..=7 | 11..=20 => true,
|
||||
// Unitless: as MEASUREMENT says.
|
||||
_ => d.header.i64("MEASUREMENT", 0) == 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Millimetres per paper unit of the paper named by `page`, from the paper itself: 1.0 for ISO
|
||||
/// and user-defined millimetre sizes, 25.4 for the ANSI, ARCH and Legal sheets. A name that is
|
||||
/// no known paper size is treated as a user millimetre size (1.0).
|
||||
pub fn model_unit_mm(page: &PageSetup) -> f64 {
|
||||
match paper_size(&page.paper) {
|
||||
Some(p) if p.imperial => 25.4,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The page a model-space plot starts from: ISO A4 in a drawing whose length unit is metric,
|
||||
/// ANSI A otherwise. Model space has no stored page setup, so the plot takes its sheet (and its
|
||||
/// units) from here unless the caller picks another paper.
|
||||
pub fn model_page(d: &Drawing) -> PageSetup {
|
||||
let mut page = PageSetup::default();
|
||||
if let Some(p) = paper_size(if metric_length_unit(d) { "A4" } else { "ANSI A" }) {
|
||||
page.paper = p.name.into();
|
||||
page.width_mm = p.width_mm;
|
||||
page.height_mm = p.height_mm;
|
||||
}
|
||||
apply_model_paper_units(&mut page);
|
||||
page
|
||||
}
|
||||
|
||||
/// Set a model-space plot's paper units once its paper is known: the paper's own units decide
|
||||
/// (ISO and user millimetre sizes are millimetres, ANSI and ARCH sheets inches), as a model-space
|
||||
/// page setup's "plot paper units" would. Layouts keep their stored page setup and go through
|
||||
/// [`page_unit_mm`]; only model-space callers use this. The units are set explicitly either
|
||||
/// way: an inch sheet left to follow `MEASUREMENT` would plot in millimetres in a drawing whose
|
||||
/// `MEASUREMENT` is 1.
|
||||
pub fn apply_model_paper_units(page: &mut PageSetup) {
|
||||
page.paper_mm = Some(model_unit_mm(page) == 1.0);
|
||||
}
|
||||
|
||||
/// Millimetres per paper-space unit on a layout with page setup `page`: `1.0` when the page
|
||||
/// chooses millimetres, `25.4` when it chooses inches, else as the drawing's `MEASUREMENT`
|
||||
/// says. Drawings from AutoCAD often have `MEASUREMENT` 0 with layouts in millimetres (#1058).
|
||||
/// Millimetres per paper-space unit on a layout with page setup `page`: millimetres when the
|
||||
/// page says so (plot paper units mm), else as the drawing's MEASUREMENT says. Drawings from
|
||||
/// AutoCAD often have MEASUREMENT 0 with layouts in millimetres (#1058).
|
||||
pub fn page_unit_mm(d: &Drawing, page: &PageSetup) -> f64 {
|
||||
match page.paper_mm {
|
||||
Some(true) => 1.0,
|
||||
Some(false) => 25.4,
|
||||
None => paper_unit_mm(d),
|
||||
}
|
||||
if page.paper_mm { 1.0 } else { paper_unit_mm(d) }
|
||||
}
|
||||
|
||||
/// Millimetres per paper-space unit on the layout holding the paper-space entity `h` (the
|
||||
@@ -200,92 +139,6 @@ pub fn sheet(d: &Drawing, layout: &str) -> Option<Sheet> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn metric_length_unit_reads_the_length_unit() {
|
||||
// Metric units, whatever MEASUREMENT says.
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_i64("MEASUREMENT", 0);
|
||||
for u in [4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] {
|
||||
d.header.set_i64("INSUNITS", u);
|
||||
assert!(metric_length_unit(&d), "INSUNITS {u} is metric");
|
||||
}
|
||||
// Imperial units, even with MEASUREMENT 1.
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
for u in [1, 2, 3, 8, 9, 10, 21, 22, 23, 24] {
|
||||
d.header.set_i64("INSUNITS", u);
|
||||
assert!(!metric_length_unit(&d), "INSUNITS {u} is imperial");
|
||||
}
|
||||
// Unitless: as MEASUREMENT says.
|
||||
for u in [0, 25] {
|
||||
d.header.set_i64("INSUNITS", u);
|
||||
d.header.set_i64("MEASUREMENT", 1);
|
||||
assert!(metric_length_unit(&d), "unitless with MEASUREMENT 1 is metric");
|
||||
d.header.set_i64("MEASUREMENT", 0);
|
||||
assert!(!metric_length_unit(&d), "unitless with MEASUREMENT 0 is imperial");
|
||||
}
|
||||
d.header.vars.remove("INSUNITS");
|
||||
d.header.vars.remove("MEASUREMENT");
|
||||
assert!(!metric_length_unit(&d), "no units at all is imperial, as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paper_unit_mm_still_follows_measurement() {
|
||||
let mut m = Drawing::new_metric();
|
||||
assert_eq!(paper_unit_mm(&m), 1.0);
|
||||
m.header.set_i64("MEASUREMENT", 0);
|
||||
assert_eq!(paper_unit_mm(&m), 25.4, "layouts stay on MEASUREMENT (page setups in inches fit)");
|
||||
let mut i = Drawing::new_imperial();
|
||||
assert_eq!(paper_unit_mm(&i), 25.4);
|
||||
i.header.set_i64("INSUNITS", 4);
|
||||
assert_eq!(paper_unit_mm(&i), 25.4, "a metric length unit does not move layout paper units");
|
||||
i.header.set_i64("MEASUREMENT", 1);
|
||||
assert_eq!(paper_unit_mm(&i), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_unit_mm_reads_the_paper() {
|
||||
let page = |name: &str| PageSetup { paper: name.into(), ..PageSetup::default() };
|
||||
assert_eq!(model_unit_mm(&page("ISO A4")), 1.0);
|
||||
assert_eq!(model_unit_mm(&page("ISO A0")), 1.0);
|
||||
assert_eq!(model_unit_mm(&page("ANSI A")), 25.4);
|
||||
assert_eq!(model_unit_mm(&page("ARCH D")), 25.4);
|
||||
assert_eq!(model_unit_mm(&page("User (300.00 x 400.00 MM)")), 1.0);
|
||||
assert_eq!(model_unit_mm(&page("nope")), 1.0, "an unknown paper is a user millimetre size");
|
||||
assert_eq!(model_unit_mm(&PageSetup::default()), 25.4, "the default page is ANSI A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_page_is_a4_for_metric_drawings() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let page = model_page(&d);
|
||||
assert_eq!(page.paper, "ISO A4 (210.00 x 297.00 MM)");
|
||||
assert_eq!((page.width_mm, page.height_mm), (210.0, 297.0));
|
||||
assert_eq!(page.paper_mm, Some(true), "A4 in a metric drawing is in millimetres");
|
||||
// The length unit decides, not MEASUREMENT.
|
||||
d.header.set_i64("MEASUREMENT", 0);
|
||||
assert_eq!(model_page(&d).paper, "ISO A4 (210.00 x 297.00 MM)");
|
||||
// An imperial drawing starts on ANSI A.
|
||||
let page = model_page(&Drawing::new_imperial());
|
||||
assert_eq!(page.paper, "ANSI A (8.50 x 11.00 Inches)");
|
||||
assert!((page.width_mm - 215.9).abs() < 1e-9 && (page.height_mm - 279.4).abs() < 1e-9);
|
||||
assert_eq!(page.paper_mm, Some(false), "ANSI A in an imperial drawing is in inches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_paper_units_follow_the_chosen_paper() {
|
||||
// The sheet decides, whatever the drawing's length unit is.
|
||||
let mut a4 = PageSetup { paper: "ISO A4 (210.00 x 297.00 MM)".into(), ..PageSetup::default() };
|
||||
apply_model_paper_units(&mut a4);
|
||||
assert_eq!(a4.paper_mm, Some(true), "ISO A4 is a millimetre sheet");
|
||||
let mut ansi = PageSetup { paper: "ANSI A (8.50 x 11.00 Inches)".into(), ..PageSetup::default() };
|
||||
apply_model_paper_units(&mut ansi);
|
||||
assert_eq!(ansi.paper_mm, Some(false), "ANSI A is an inch sheet");
|
||||
// A user size in millimetres is one to one.
|
||||
let mut user = PageSetup { paper: "User (300.00 x 400.00 MM)".into(), ..PageSetup::default() };
|
||||
apply_model_paper_units(&mut user);
|
||||
assert_eq!(user.paper_mm, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_and_sheet() {
|
||||
assert_eq!(paper_size("a4").map(|p| p.width_mm), Some(210.0));
|
||||
@@ -301,23 +154,6 @@ mod tests {
|
||||
let s = Sheet::from_page(&hostile, 0.0);
|
||||
assert!(s.size.x > 0.0 && s.printable == s.bounds());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_unit_mm_honours_explicit_choice_and_falls_back_to_measurement() {
|
||||
let mut imperial = Drawing::new_imperial();
|
||||
imperial.header.set_i64("MEASUREMENT", 0);
|
||||
let mut metric = Drawing::new_metric();
|
||||
metric.header.set_i64("MEASUREMENT", 1);
|
||||
let unset = PageSetup::default();
|
||||
let mm = PageSetup { paper_mm: Some(true), ..PageSetup::default() };
|
||||
let inches = PageSetup { paper_mm: Some(false), ..PageSetup::default() };
|
||||
assert_eq!(page_unit_mm(&imperial, &unset), 25.4);
|
||||
assert_eq!(page_unit_mm(&imperial, &mm), 1.0);
|
||||
assert_eq!(page_unit_mm(&imperial, &inches), 25.4);
|
||||
assert_eq!(page_unit_mm(&metric, &unset), 1.0);
|
||||
assert_eq!(page_unit_mm(&metric, &mm), 1.0);
|
||||
assert_eq!(page_unit_mm(&metric, &inches), 25.4);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a layout's saved page setup says about how to plot it, for a plot that was not given the
|
||||
|
||||
@@ -308,6 +308,14 @@ fn key_from(name: &str) -> Option<egui::Key> {
|
||||
}
|
||||
|
||||
pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
|
||||
let out = handle_request(app, ctx, req);
|
||||
// A command the request ran may have asked for a bar (MENUBAR, TOOLBAR): apply it before
|
||||
// the next request, so a later query or `ui.set` sees the bars as they are now.
|
||||
app.sync_bars();
|
||||
out
|
||||
}
|
||||
|
||||
fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
|
||||
let p = &req.params;
|
||||
let s = |k: &str| p.get(k).and_then(Value::as_str);
|
||||
let f = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
|
||||
@@ -316,6 +316,10 @@ pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<V
|
||||
}
|
||||
|
||||
/// Validate and repair the stored workspace, sync it with the app, and render the dock panels; a failed restore falls back to the default layout with a status message.
|
||||
/// Draw the docked workspace: restore or fall back from the persisted layout, render every
|
||||
/// panel body plus the header close buttons, and apply the resulting actions through
|
||||
/// [`command`]. Bodies may dispatch commands, so the canonical workspace is published before
|
||||
/// rendering while the layout snapshot stays immutable.
|
||||
pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
|
||||
let t = crate::theme::Tokens::get();
|
||||
let mut workspace = app.ui.docking.clone();
|
||||
@@ -348,7 +352,33 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
|
||||
if let Some(panel) = app.raise_panel.take() {
|
||||
area = area.raise_panel(panel);
|
||||
}
|
||||
let mut output = area.show_content(ui, &workspace.layout, &style, &mut Panels { app });
|
||||
let (mut output, header_close) = {
|
||||
let mut panels = Panels { app, close: None };
|
||||
let output = area.show_content(ui, &workspace.layout, &style, &mut panels);
|
||||
(output, panels.close)
|
||||
};
|
||||
// Accordion title bars are rendered by the shared surface without a header callback, so
|
||||
// place the same close button over their title bar, left of the stock collapse control.
|
||||
let mut close = header_close;
|
||||
for panel in stack_panels(&workspace.layout) {
|
||||
if !permissions(&panel).closable {
|
||||
continue;
|
||||
}
|
||||
let Some(title) = ui.ctx().read_response(egui::Id::unique("cadcraft-docking").with(("tab", panel))) else { continue };
|
||||
if !title.rect.is_positive() {
|
||||
continue;
|
||||
}
|
||||
let rect = egui::Rect::from_center_size(
|
||||
egui::pos2(title.rect.right() - 18.0 - CLOSE_BUTTON * 0.5 - 4.0, title.rect.center().y),
|
||||
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
|
||||
);
|
||||
if close_button(ui, panel, rect) {
|
||||
close = Some(panel);
|
||||
}
|
||||
}
|
||||
if let Some(panel) = close {
|
||||
output.actions.push(Action::Close { panel });
|
||||
}
|
||||
// Keys typed in a floating panel's own OS window run the main window's shortcuts and
|
||||
// command line; files dropped on one open like files dropped on the main window.
|
||||
app.forward_native_input(ui.ctx(), std::mem::take(&mut output.forwarded_events), output.forwarded_modifiers);
|
||||
@@ -393,9 +423,55 @@ pub fn native_input_blocked(app: &crate::CadApp, ctx: &egui::Context) -> bool {
|
||||
/// The panels' contents, names, size limits and icons for the dock area.
|
||||
pub struct Panels<'a> {
|
||||
pub app: &'a mut crate::CadApp,
|
||||
/// The panel whose header close button was clicked this frame.
|
||||
pub close: Option<Panel>,
|
||||
}
|
||||
|
||||
/// Size of a panel header's close button, in points.
|
||||
const CLOSE_BUTTON: f32 = 16.0;
|
||||
|
||||
/// The accessible name of a header's close button. One translated template carries both the
|
||||
/// verb and the panel name, so a catalog translates the whole name instead of leaving an
|
||||
/// English verb in front of a translated panel label.
|
||||
fn close_label(panel: Panel) -> String {
|
||||
crate::tf!("Close {panel}", panel = crate::i18n::t(panel.label()))
|
||||
}
|
||||
|
||||
/// A visible close button for a panel header. It runs the same action as the tab context
|
||||
/// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct.
|
||||
fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool {
|
||||
let t = crate::theme::Tokens::get();
|
||||
let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click());
|
||||
let label = close_label(panel);
|
||||
crate::icons::describe_control(ui, &response, &label, None, false);
|
||||
if response.hovered() {
|
||||
ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6));
|
||||
}
|
||||
crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Close, false);
|
||||
response.on_hover_text(crate::tl!("Close panel")).clicked()
|
||||
}
|
||||
|
||||
/// Panels whose title bar is an accordion entry rather than a tab group header.
|
||||
fn stack_panels(layout: &Layout<Panel>) -> Vec<Panel> {
|
||||
let mut panels = Vec::new();
|
||||
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
|
||||
while let Some(node) = nodes.pop() {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
nodes.push(first);
|
||||
nodes.push(second);
|
||||
}
|
||||
Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)),
|
||||
// Tab groups draw their own header; nothing else stacks an accordion entry.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panels
|
||||
}
|
||||
|
||||
impl DockContent<Panel> for Panels<'_> {
|
||||
/// Render `panel`'s existing view; Layers, Properties and External References scroll
|
||||
/// independently, and the drawing canvas paints its own background before the view.
|
||||
fn body(&mut self, ui: &mut egui::Ui, panel: &Panel) {
|
||||
let app = &mut *self.app;
|
||||
match panel {
|
||||
@@ -445,6 +521,23 @@ impl DockContent<Panel> for Panels<'_> {
|
||||
crate::icons::paint(painter, rect, icon, false);
|
||||
true
|
||||
}
|
||||
/// Reserve header space for the close button only when `active` may be closed, so the
|
||||
/// drawing view's title gets no empty gap.
|
||||
fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 {
|
||||
if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 }
|
||||
}
|
||||
/// Draw the close button at the right edge of a tab-group header and remember the panel
|
||||
/// to close once the docking surface has returned, so layout changes stay outside rendering.
|
||||
fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) {
|
||||
let header = ui.max_rect();
|
||||
let rect = egui::Rect::from_center_size(
|
||||
egui::pos2(header.right() - CLOSE_BUTTON * 0.5 - 4.0, header.center().y),
|
||||
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
|
||||
);
|
||||
if close_button(ui, *active, rect) {
|
||||
self.close = Some(*active);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn panel_limits(panel: &Panel) -> PanelLimits {
|
||||
|
||||
@@ -139,11 +139,13 @@
|
||||
Clip Viewport Delimitar ventana gráfica
|
||||
Clipboard Portapapeles
|
||||
Close Cerrar
|
||||
Close {panel} Cerrar {panel}
|
||||
Close All Cerrar todo
|
||||
Close All Other Drawings Cerrar todos los demás dibujos
|
||||
Close Array Editing Cerrar la edición de matriz
|
||||
Close Comparison Cerrar comparación
|
||||
Export Comparison Exportar comparación
|
||||
Close panel Cerrar panel
|
||||
Closed Cerrada
|
||||
Coincident Coincidente
|
||||
Collapse Palettes Contraer paletas
|
||||
@@ -542,6 +544,7 @@
|
||||
Measure Medir
|
||||
Measure Distance Medir distancia
|
||||
Measure Geometry Medir geometría
|
||||
Menu Bar Barra de menús
|
||||
Merge Cells Combinar celdas
|
||||
Merged PRs PR integradas
|
||||
Mid Between 2 Points Punto medio entre 2 puntos
|
||||
|
||||
|
@@ -146,6 +146,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
|
||||
"chrome",
|
||||
"cmdline",
|
||||
"credits",
|
||||
"docking",
|
||||
"dialogs",
|
||||
"hatchdlg",
|
||||
"aliasdlg",
|
||||
|
||||
@@ -143,11 +143,13 @@
|
||||
Xref Clip Frame Рамка обрізки зовнішнього посилання
|
||||
Clipboard Буфер обміну
|
||||
Close Закрити
|
||||
Close {panel} Закрити {panel}
|
||||
Close All Закрити всі
|
||||
Close All Other Drawings Закрити всі інші креслення
|
||||
Closed Замкнений
|
||||
Close Comparison Закрити порівняння
|
||||
Export Comparison Експортувати порівняння
|
||||
Close panel Закрити панель
|
||||
Coincident Збіг
|
||||
Collapse Palettes Згорнути палітри
|
||||
Collapse Tool Sets Згорнути набори інструментів
|
||||
@@ -534,6 +536,7 @@
|
||||
Measure Розмітити
|
||||
Measure Distance Виміряти відстань
|
||||
Measure Geometry Виміряти геометрію
|
||||
Menu Bar Рядок меню
|
||||
Merge Cells Об'єднати комірки
|
||||
Merged PRs Об'єднані PR
|
||||
Mid Between 2 Points Середина між 2 точками
|
||||
|
||||
|
@@ -928,6 +928,7 @@
|
||||
Time 时间
|
||||
To get started, create or open a drawing. 若要开始,请创建或打开一个图形。
|
||||
Tool Bar 工具栏
|
||||
Menu Bar 菜单栏
|
||||
Tool Sets 工具集
|
||||
Tools 工具
|
||||
Torus 圆环体
|
||||
|
||||
|
@@ -283,6 +283,9 @@ pub struct CadApp {
|
||||
pub system_animations: Option<bool>,
|
||||
/// What `ui.system_cursor` goes back to when the interface is reset ([`Self::set_system_cursor_default`]).
|
||||
pub system_cursor_default: bool,
|
||||
/// Whether the host has a native menu bar: off where the menus stay in the window
|
||||
/// ([`Self::set_native_menus`]).
|
||||
pub native_menus: bool,
|
||||
pub session: Session,
|
||||
pub ui: UiState,
|
||||
/// The interface's own preferences from the Options dialog ([`options`]).
|
||||
@@ -381,6 +384,7 @@ impl CadApp {
|
||||
system_languages: Vec::new(),
|
||||
system_animations: None,
|
||||
system_cursor_default: false,
|
||||
native_menus: cfg!(target_os = "macos"),
|
||||
session,
|
||||
ui: UiState::default(),
|
||||
options: options::UiOptions::default(),
|
||||
@@ -588,7 +592,11 @@ impl CadApp {
|
||||
if let Some(r) = menus::run_ui_command(self, id, ¶ms) {
|
||||
return r;
|
||||
}
|
||||
// The bars as the interface shows them now (a `ui.set` may have just changed one), and any
|
||||
// MENUBAR or TOOLBAR request applied at once.
|
||||
self.sync_bars();
|
||||
let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());
|
||||
self.sync_bars();
|
||||
if let Ok(v) = &r
|
||||
&& let Some(m) = v.get("message").and_then(Value::as_str)
|
||||
{
|
||||
@@ -607,6 +615,7 @@ impl CadApp {
|
||||
if menus::run_ui_command(self, name, &Value::Null).is_some() {
|
||||
return;
|
||||
}
|
||||
self.sync_bars();
|
||||
if let Err(e) = self.session.start(name) {
|
||||
self.session.echo(e.to_string());
|
||||
}
|
||||
@@ -622,6 +631,7 @@ impl CadApp {
|
||||
/// command or system variable) runs `fallback` instead: Enter on a partly typed name accepts
|
||||
/// the highlighted AutoComplete suggestion.
|
||||
pub fn cmdline_or(&mut self, text: &str, fallback: Option<&str>) -> Option<String> {
|
||||
self.sync_bars();
|
||||
if !self.session.prompting() {
|
||||
let first = text.split_whitespace().next().unwrap_or("");
|
||||
// `cmd {json}` is a programmatic call: the engine runs it with those parameters.
|
||||
@@ -636,7 +646,9 @@ impl CadApp {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let e = match (self.session.cmdline(text), fallback) {
|
||||
let r = self.session.cmdline(text);
|
||||
self.sync_bars();
|
||||
let e = match (r, fallback) {
|
||||
(Ok(()), _) => return None,
|
||||
(Err(cadcraft_engine::EngineError::UnknownCommand(_)), Some(f)) => return self.cmdline(f),
|
||||
(Err(e), _) => e.to_string(),
|
||||
@@ -645,6 +657,18 @@ impl CadApp {
|
||||
Some(e)
|
||||
}
|
||||
|
||||
/// Apply a menu bar / tool bar change MENUBAR or TOOLBAR asked for, and report the bars shown.
|
||||
fn sync_bars(&mut self) {
|
||||
let b = std::mem::take(&mut self.session.bars_request);
|
||||
if let Some(on) = b.menubar {
|
||||
self.ui.in_window_menu = on;
|
||||
}
|
||||
if let Some(show) = b.toolbar {
|
||||
self.ui.show_toolbar = show;
|
||||
}
|
||||
self.session.bars_shown = cadcraft_engine::cmd::interface::InterfaceBars { menubar: self.ui.in_window_menu, toolbar: self.ui.show_toolbar };
|
||||
}
|
||||
|
||||
/// The theme the interface shows now (the choice resolved against the OS appearance).
|
||||
pub fn shown_theme(&self) -> egui::Theme {
|
||||
self.shown_theme.unwrap_or_else(|| self.ui.theme.resolve(None))
|
||||
@@ -731,6 +755,15 @@ impl CadApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the interface whether the host has a native menu bar. Where it has none, the
|
||||
/// in-window menu is the only menu, so it is shown and a reset keeps it.
|
||||
pub fn set_native_menus(&mut self, on: bool) {
|
||||
self.native_menus = on;
|
||||
if !on {
|
||||
self.ui.in_window_menu = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_status(&mut self, s: impl Into<String>) {
|
||||
self.status = Some((s.into(), now_ms()));
|
||||
}
|
||||
@@ -1087,6 +1120,7 @@ impl CadApp {
|
||||
/// Draw one UI pass: title/toolbar, optional menu/status bar/file tabs, the standalone tool-set strip when a drawing is shown but Tool Sets is not docked, docking or the start page, and the floating overlays; record `frame_ms`. Runs on every pass, including one egui later discards.
|
||||
fn draw(&mut self, ui: &mut egui::Ui) {
|
||||
let t0 = now_ms();
|
||||
self.sync_bars();
|
||||
control::begin_frame(ui.ctx());
|
||||
let t = theme::Tokens::get();
|
||||
chrome::title_and_toolbar(self, ui);
|
||||
@@ -1408,4 +1442,54 @@ mod tests {
|
||||
let ui: UiState = serde_json::from_value(json!({ "saveFormat": "dwg" })).unwrap_or_default();
|
||||
assert_eq!(ui.save_format, SaveFormat::Dwg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reset_brings_the_interface_back() {
|
||||
// Hiding the interface (View/Window toggles) can leave no way back — on Windows the
|
||||
// in-window menu bar is the only menu there is. Options > Reset must restore it (#1240).
|
||||
let mut a = app();
|
||||
a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap();
|
||||
a.run("ui.toggle.menubar", json!({ "on": cfg!(target_os = "macos") })).unwrap();
|
||||
a.start("ui.hidepalettes");
|
||||
assert!(!a.ui.show_toolbar && !a.ui.show_palettes && !a.ui.show_toolsets);
|
||||
assert_eq!(a.ui.in_window_menu, cfg!(target_os = "macos"), "the test did not hide the menu bar");
|
||||
a.run("options", json!({ "reset": true })).unwrap();
|
||||
assert!(a.ui.show_toolbar, "the tool bar is still hidden");
|
||||
assert!(a.ui.show_palettes, "the palettes are still hidden");
|
||||
assert!(a.ui.show_toolsets);
|
||||
assert_eq!(a.ui.in_window_menu, !cfg!(target_os = "macos"), "the menu bar did not come back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reset_keeps_the_menu_where_the_host_has_no_native_one() {
|
||||
// With CADCRAFT_NO_NATIVE_MENU=1 the menus stay in the window: the host reports no native
|
||||
// menu bar, so the in-window one is the only menu and the reset must leave it (#1240).
|
||||
let mut a = app();
|
||||
a.set_native_menus(false);
|
||||
assert!(a.ui.in_window_menu, "the host's setting did not show the in-window menu");
|
||||
a.run("ui.toggle.menubar", json!({ "on": false })).unwrap();
|
||||
a.run("options", json!({ "reset": true })).unwrap();
|
||||
assert!(a.ui.in_window_menu, "the only menu bar did not come back");
|
||||
// Beside a native menu bar, the reset returns to the platform default.
|
||||
a.set_native_menus(true);
|
||||
a.run("ui.toggle.menubar", json!({ "on": true })).unwrap();
|
||||
a.run("options", json!({ "reset": true })).unwrap();
|
||||
assert!(!a.ui.in_window_menu, "the in-window menu is not the default beside a native one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reset_keeps_the_users_shortcuts_and_folders() {
|
||||
// The reset brings hidden bars back (#1240); it must not also lose the user's own
|
||||
// keyboard shortcuts or the folders the file pickers remember.
|
||||
let mut a = app();
|
||||
a.ui.shortcuts.insert("line".into(), "Ctrl+Shift+L".into());
|
||||
a.ui.last_lisp_dir = Some("lisp-folder".into());
|
||||
a.ui.last_pgp_dir = Some("pgp-folder".into());
|
||||
a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap();
|
||||
a.run("options", json!({ "reset": true })).unwrap();
|
||||
assert!(a.ui.show_toolbar, "the tool bar is still hidden");
|
||||
assert_eq!(a.ui.shortcuts.get("line").map(String::as_str), Some("Ctrl+Shift+L"), "the reset lost a user shortcut");
|
||||
assert_eq!(a.ui.last_lisp_dir.as_deref(), Some("lisp-folder"));
|
||||
assert_eq!(a.ui.last_pgp_dir.as_deref(), Some("pgp-folder"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,8 +584,7 @@ fn page_setup(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action
|
||||
let Some((_, name, page)) = layouts.iter().find(|l| l.1 == sel) else { return };
|
||||
right.label(RichText::new(format!("Page setup of {name}")).strong());
|
||||
// Layout plotting always prints the whole sheet, so only that area is offered.
|
||||
let paper_mm = cadcraft_render::paper::page_unit_mm(d, page) == 1.0;
|
||||
let rows = PageRows { areas: &["layout"], scale: true, center: true, paper_mm: Some(paper_mm) };
|
||||
let rows = PageRows { areas: &["layout"], scale: true, center: true };
|
||||
egui::Grid::new("pagesetup_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(right, |ui| {
|
||||
if let Some((k, v)) = page_rows(ui, egui::Id::unique(("pagesetup", name)), page, &rows, &choices, None) {
|
||||
action = Some(("pagesetup", json!({ "layout": name, k: v })));
|
||||
@@ -605,9 +604,6 @@ struct PageRows {
|
||||
areas: &'static [&'static str],
|
||||
scale: bool,
|
||||
center: bool,
|
||||
/// Effective paper units (`Some(true)` = millimetres, `Some(false)` = inches) for the layout's
|
||||
/// page setup, or `None` to hide the row (the Plot dialog).
|
||||
paper_mm: Option<bool>,
|
||||
}
|
||||
|
||||
/// The devices and plot style tables the page-setup rows offer.
|
||||
@@ -670,7 +666,7 @@ fn parse_ratio(t: &str) -> Option<f64> {
|
||||
/// The page-setup rows (device, paper, orientation, plot area, fit, scale, center, lineweights,
|
||||
/// transparency, plot style table) shared by the Page Setup Manager and the Plot dialog, inside a
|
||||
/// two-column grid. Returns the setting the user changed as a `pagesetup` parameter (`device`,
|
||||
/// `paper`, `landscape`, `paperUnits`, `plotArea`, `scaleToFit`, `scale`, `center`, `lineweights`,
|
||||
/// `paper`, `landscape`, `plotArea`, `scaleToFit`, `scale`, `center`, `lineweights`,
|
||||
/// `plotTransparency` or `plotStyleTable`).
|
||||
fn page_rows(
|
||||
ui: &mut egui::Ui,
|
||||
@@ -728,23 +724,6 @@ fn page_rows(
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
if let Some(mm) = rows.paper_mm {
|
||||
ui.label(crate::tl!("Paper units"));
|
||||
ui.horizontal(|ui| {
|
||||
// Every click records the choice, even on the selected radio: while the layout has
|
||||
// no explicit units it inherits MEASUREMENT, and clicking the value it currently
|
||||
// inherits must lock that choice against a later MEASUREMENT change (#3249).
|
||||
if ui.radio(!mm, crate::tl!("Inches")).clicked() {
|
||||
change = Some(("paperUnits", json!("inches")));
|
||||
}
|
||||
if ui.radio(mm, crate::tl!("Millimeters")).clicked() {
|
||||
change = Some(("paperUnits", json!("mm")));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text(crate::tl!("What one paper-space unit is on this layout"));
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label("Plot area");
|
||||
ui.add_enabled_ui(rows.areas.len() > 1, |ui| {
|
||||
craft_ui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
|
||||
@@ -930,7 +909,7 @@ fn plot_page(d: &cadcraft_doc::Drawing, target: &str) -> cadcraft_doc::PageSetup
|
||||
return page;
|
||||
}
|
||||
let mut page = cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() };
|
||||
if cadcraft_render::paper::metric_length_unit(d)
|
||||
if cadcraft_render::paper::paper_unit_mm(d) == 1.0
|
||||
&& let Some(a4) = cadcraft_render::paper_size("A4")
|
||||
{
|
||||
page.paper = a4.name.into();
|
||||
@@ -1055,9 +1034,9 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
|
||||
ui.horizontal_top(|ui| {
|
||||
egui::Grid::new("plot_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
|
||||
let rows = if model {
|
||||
PageRows { areas: MODEL_AREAS, scale: true, center: false, paper_mm: None }
|
||||
PageRows { areas: MODEL_AREAS, scale: true, center: false }
|
||||
} else {
|
||||
PageRows { areas: &["layout"], scale: false, center: false, paper_mm: None }
|
||||
PageRows { areas: &["layout"], scale: false, center: false }
|
||||
};
|
||||
let placement = model.then_some((&mut st.center, &mut st.offset_mm, offset_supported));
|
||||
if let Some((k, v)) = page_rows(ui, egui::Id::unique(("plot", st.target.as_str())), &st.page, &rows, &choices, placement) {
|
||||
|
||||
@@ -797,13 +797,20 @@ fn switch_on_hover(ctx: &egui::Context, titles: &[egui::Response]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Activate a menu command. QuickCalc toggles transparently; other items clear pending
|
||||
/// command-line text and start their command interactively.
|
||||
/// Activate a menu command. QuickCalc toggles transparently, and Reference Manager closes its
|
||||
/// palette when it is open (typed XREF only opens it); other items clear pending command-line
|
||||
/// text and start their command interactively.
|
||||
pub fn activate(app: &mut CadApp, id: &str) {
|
||||
if id == "ui.toggle.quickcalc" {
|
||||
run_transparent(app, id);
|
||||
return;
|
||||
}
|
||||
if id == "xref" && app.ui.docking.layout.contains(&crate::docking::Panel::ExternalRefs) {
|
||||
if let Err(e) = crate::xrefs::close_palette(app) {
|
||||
app.set_status(e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
app.cmd.buffer.clear();
|
||||
app.start(id);
|
||||
}
|
||||
|
||||
@@ -434,13 +434,30 @@ fn apply_right_click(o: &mut UiOptions, c: &UiChanges) {
|
||||
|
||||
/// The interface preferences back to their defaults (the interface language stays).
|
||||
fn reset_ui(app: &mut CadApp) {
|
||||
let d = crate::UiState::default();
|
||||
app.ui.theme = d.theme;
|
||||
app.ui.animations = d.animations;
|
||||
app.ui.save_format = d.save_format;
|
||||
app.ui.save_version = d.save_version;
|
||||
// Everything interface, back to its defaults: a hidden menu bar, tool bar, palettes or
|
||||
// panels and a rearranged panel layout come back — once the menu bar is hidden there may be
|
||||
// no other way to reach the toggles (#1240). The interface language stays; the open dialog,
|
||||
// the start tab, the recent files and the remembered folders are state, not preferences, and
|
||||
// stay too. The user's keyboard shortcuts are their own customisation, which Window > Reset
|
||||
// Palettes keeps as well: a reset meant to bring a bar back must not lose them.
|
||||
let (language, dialog, start_tab) = (app.ui.interface_language, app.ui.dialog.take(), app.ui.start_tab);
|
||||
let recent_files = std::mem::take(&mut app.ui.recent_files);
|
||||
let shortcuts = std::mem::take(&mut app.ui.shortcuts);
|
||||
let (last_lisp_dir, last_pgp_dir) = (app.ui.last_lisp_dir.take(), app.ui.last_pgp_dir.take());
|
||||
app.ui = crate::UiState {
|
||||
interface_language: language,
|
||||
dialog,
|
||||
start_tab,
|
||||
recent_files,
|
||||
shortcuts,
|
||||
last_lisp_dir,
|
||||
last_pgp_dir,
|
||||
..Default::default()
|
||||
};
|
||||
// Where the host has no native menu bar the in-window one is the only menu: the reset must
|
||||
// leave it in place (#1240).
|
||||
app.ui.in_window_menu = !app.native_menus;
|
||||
app.ui.system_cursor = app.system_cursor_default;
|
||||
app.ui.history_lines = d.history_lines;
|
||||
app.options = UiOptions::default();
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ fn open_palette(app: &mut CadApp) -> Result<Value, String> {
|
||||
crate::docking::command(app, false, &json!({ "operation": "open", "panel": Panel::ExternalRefs.id() }))
|
||||
}
|
||||
|
||||
/// Close the palette: Window ▸ Reference Manager while it is open, as Window ▸ QuickCalc closes
|
||||
/// QuickCalc (#2273).
|
||||
pub(crate) fn close_palette(app: &mut CadApp) -> Result<Value, String> {
|
||||
crate::docking::command(app, false, &json!({ "operation": "close", "panel": Panel::ExternalRefs.id() }))
|
||||
}
|
||||
|
||||
/// A picked file inside the host drawing's folder is attached by its relative path, so the
|
||||
/// project folder can move.
|
||||
fn relative_to_host(app: &CadApp, picked: &str) -> String {
|
||||
|
||||
@@ -123,7 +123,7 @@ fn palette_icons_are_painted_in_code_and_shown_in_an_iconic_column() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut paint = |panel: Panel| {
|
||||
let mut painted = false;
|
||||
let mut content = Panels { app: &mut app };
|
||||
let mut content = Panels { app: &mut app, close: None };
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::background());
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(20.0, 20.0));
|
||||
@@ -593,3 +593,62 @@ fn group_drag_bar_moves_the_whole_group_into_the_other_dock() {
|
||||
assert_eq!(frames(layout), [[Panel::Canvas]]);
|
||||
assert_eq!(h.state().session.doc().unwrap(), &document);
|
||||
}
|
||||
|
||||
/// Guard that every closable panel header offers a visible close button: a docked tab group,
|
||||
/// the default accordion stack, and a floating group. Each click must remove the panel, the
|
||||
/// button must not cover the title, and the tab context menu must still close the same panel.
|
||||
#[test]
|
||||
fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() {
|
||||
let mut h = harness(None, 1280.0, 1.0);
|
||||
assert!(h.query_by_label("Close Tool Sets").is_some(), "docked tab headers show a close button");
|
||||
assert!(h.query_by_label("Close Drawing").is_none(), "the drawing view is not a closable panel");
|
||||
// External References opens as a tabbed pane; its button sits beside the title, not over it.
|
||||
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"externalReferences"})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.docking.layout.contains(&Panel::ExternalRefs));
|
||||
let close = h.get_by_label("Close External References").rect();
|
||||
let title = h.get_by_role_and_label(egui::accesskit::Role::Tab, "External References").rect();
|
||||
assert!(!close.intersects(title), "the close button does not cover the panel title");
|
||||
h.get_by_label("Close External References").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.docking.layout.contains(&Panel::ExternalRefs));
|
||||
|
||||
// Accordion headers (the default Layers/Properties stack) get one too.
|
||||
assert!(h.state().ui.docking.layout.contains(&Panel::Layers));
|
||||
h.get_by_label("Close Layers").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers));
|
||||
|
||||
// The context menu still closes the same panel after it is reopened.
|
||||
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"layers"})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.docking.layout.contains(&Panel::Layers));
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Tab, "Layers").click_button(PointerButton::Secondary);
|
||||
h.run_steps(3);
|
||||
// The docking surface's stock tab menu item ("Close Panel"), not our tooltip.
|
||||
h.get_by_label("Close Panel").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers));
|
||||
|
||||
// Floating panels get the same button in their group header.
|
||||
h.state_mut().run("ui.dock", json!({"operation":"float","panel":"properties","rect":[400,250,300,350]})).unwrap();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Close Properties").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.docking.layout.contains(&Panel::Properties));
|
||||
}
|
||||
|
||||
/// The accessible name is one translated string, not an English verb glued to a translated
|
||||
/// panel label: Spanish readers must hear "Cerrar Capas", never "Close Capas".
|
||||
#[test]
|
||||
fn spanish_close_button_accessible_name_is_localized_as_a_whole() {
|
||||
let mut h = harness(None, 1280.0, 1.0);
|
||||
h.state_mut().run("ui.language", json!({"lang": "es"})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Cerrar Capas").is_some(), "the accordion close button is named in Spanish");
|
||||
assert!(h.query_by_label("Cerrar Propiedades").is_some(), "every panel's close button follows the language");
|
||||
assert!(h.query_by_label("Close Capas").is_none(), "no English verb survives the translation");
|
||||
h.get_by_label("Cerrar Capas").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers), "the localized name still closes its panel");
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ mod native_menu_text_keys;
|
||||
mod native_windows;
|
||||
mod options_dialog;
|
||||
mod options_right_click;
|
||||
mod page_setup_paper_units;
|
||||
mod parameters_rename;
|
||||
mod pickdrag;
|
||||
mod properties_described;
|
||||
|
||||
@@ -252,3 +252,22 @@ fn selection_highlight_settings_set_save_and_show_in_the_selection_tab() {
|
||||
assert!(text.contains(label), "{label} missing from:\n{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_brings_back_hidden_menu_bar_toolbar_and_status_bar() {
|
||||
// #1240: with the in-window menu bar, the toolbar and the status bar hidden, OPTIONS ▸ Reset
|
||||
// to Defaults (typed, or from the right-click menu) is the way back.
|
||||
let mut a = app();
|
||||
let d = cadcraft_ui_egui::UiState::default();
|
||||
a.ui.in_window_menu = !d.in_window_menu;
|
||||
a.ui.show_toolbar = false;
|
||||
a.ui.show_status_bar = false;
|
||||
a.ui.show_command_line = false;
|
||||
a.ui.show_palettes = false;
|
||||
a.run("options", json!({"reset": true})).unwrap();
|
||||
assert_eq!(a.ui.in_window_menu, d.in_window_menu);
|
||||
assert_eq!(a.ui.show_toolbar, d.show_toolbar);
|
||||
assert_eq!(a.ui.show_status_bar, d.show_status_bar);
|
||||
assert_eq!(a.ui.show_command_line, d.show_command_line);
|
||||
assert_eq!(a.ui.show_palettes, d.show_palettes);
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
//! File ▸ Page Setup Manager: a layout's paper units can be millimetres on an inch-family sheet
|
||||
//! (an ARCH D sheet in a metric drawing, #3249), so the sheet measures 914.4 x 609.6 units.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn page_setup_switches_an_arch_d_sheet_to_millimetres() {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("units", json!({ "insunits": 4 })).unwrap();
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
|
||||
let inch = cadcraft_render::sheet(app.session.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
app.start("pagesetup");
|
||||
// The dialog's existing combo boxes (device, paper, plot area, plot style) have no
|
||||
// accessible name yet; that check is not what this test is about.
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.get_by_label("Millimeters").click();
|
||||
h.run_steps(5);
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(true));
|
||||
let mm = cadcraft_render::sheet(d, "Layout1").unwrap();
|
||||
assert!((mm.size.x - 914.4).abs() < 1e-9 && (mm.size.y - 609.6).abs() < 1e-9, "{:?}", mm.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_setup_switches_a_metric_drawing_sheet_to_inches() {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("setvar", json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
|
||||
let mm = cadcraft_render::sheet(app.session.doc().unwrap(), "Layout1").unwrap();
|
||||
assert!((mm.size.x - 914.4).abs() < 1e-9 && (mm.size.y - 609.6).abs() < 1e-9, "{:?}", mm.size);
|
||||
app.start("pagesetup");
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.get_by_label("Inches").click();
|
||||
h.run_steps(5);
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
let inch = cadcraft_render::sheet(d, "Layout1").unwrap();
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_the_inherited_paper_units_records_the_choice() {
|
||||
// The layout starts with no explicit units and inherits MEASUREMENT 0 (inches). Clicking the
|
||||
// selected Inches radio must record that choice, so a later MEASUREMENT change cannot flip
|
||||
// the sheet to millimetres (#3249).
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("pagesetup", json!({ "layout": "Layout1", "paper": "ARCH D", "landscape": true })).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, None);
|
||||
app.start("pagesetup");
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.get_by_label("Inches").click();
|
||||
h.run_steps(5);
|
||||
assert_eq!(h.state().session.doc().unwrap().layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
h.state_mut().run("setvar", json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.layout("Layout1").unwrap().page.paper_mm, Some(false));
|
||||
let inch = cadcraft_render::sheet(d, "Layout1").unwrap();
|
||||
assert_eq!(inch.unit_mm, 25.4);
|
||||
assert!((inch.size.x - 36.0).abs() < 1e-9 && (inch.size.y - 24.0).abs() < 1e-9, "{:?}", inch.size);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! MENUBAR and TOOLBAR at the command line bring a hidden menu bar and tool bar back (#1341):
|
||||
//! on Windows and Linux the in-window menu bar is the only menu, so with it hidden typing these
|
||||
//! is the way back, as in AutoCAD.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use serde_json::json;
|
||||
|
||||
fn app() -> CadApp {
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_menubar_shows_and_hides_the_menu_bar() {
|
||||
let mut app = app();
|
||||
app.ui.in_window_menu = false;
|
||||
app.cmdline("MENUBAR");
|
||||
assert_eq!(app.session.prompt_text(), "MENUBAR Enter new value for MENUBAR <0>:");
|
||||
app.cmdline("1");
|
||||
assert!(app.session.running.is_none());
|
||||
assert!(app.ui.in_window_menu);
|
||||
// 0 hides it again; anything else is refused and asked again.
|
||||
app.cmdline("MENUBAR");
|
||||
app.cmdline("2");
|
||||
assert!(app.session.running.is_some(), "still asking");
|
||||
app.cmdline("0");
|
||||
assert!(!app.ui.in_window_menu);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_toolbar_shows_the_tool_bar_by_default() {
|
||||
let mut app = app();
|
||||
app.ui.show_toolbar = false;
|
||||
app.cmdline("TOOLBAR");
|
||||
assert_eq!(app.session.prompt_text(), "TOOLBAR Enter tool bar option or [Show/Hide] <Show>:");
|
||||
app.cmdline("");
|
||||
assert!(app.ui.show_toolbar);
|
||||
app.cmdline("TOOLBAR");
|
||||
app.cmdline("H");
|
||||
assert!(!app.ui.show_toolbar);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_json_forms_report_and_set_the_bars() {
|
||||
let mut app = app();
|
||||
app.ui.in_window_menu = true;
|
||||
app.ui.show_toolbar = false;
|
||||
app.cmdline("MENUBAR");
|
||||
app.cmdline("");
|
||||
assert_eq!(app.session.execute("menubar", &json!({})).unwrap(), json!({ "value": 1 }));
|
||||
assert_eq!(app.session.execute("toolbar", &json!({})).unwrap(), json!({ "show": false }));
|
||||
app.session.execute("toolbar", &json!({ "show": true })).unwrap();
|
||||
app.cmdline("MENUBAR");
|
||||
app.cmdline("");
|
||||
assert!(app.ui.show_toolbar && app.ui.in_window_menu);
|
||||
assert!(app.session.execute("menubar", &json!({ "value": 3 })).is_err());
|
||||
}
|
||||
|
||||
/// MENUBAR changes only the menu bar: a tool bar change made before the request is applied
|
||||
/// stays (a control-API `ui.set` can come between them).
|
||||
#[test]
|
||||
fn menubar_leaves_a_later_tool_bar_change() {
|
||||
let mut app = app();
|
||||
app.ui.in_window_menu = true;
|
||||
app.ui.show_toolbar = true;
|
||||
app.session.execute("menubar", &json!({ "value": 0 })).unwrap();
|
||||
app.ui.show_toolbar = false;
|
||||
app.cmdline("'REDRAW");
|
||||
assert!(!app.ui.in_window_menu, "MENUBAR applied");
|
||||
assert!(!app.ui.show_toolbar, "the tool bar keeps its later change");
|
||||
}
|
||||
|
||||
/// A bar query through `CadApp::run` reports the bars as the interface shows them now, even when
|
||||
/// a UI change came just before it with no frame drawn in between.
|
||||
#[test]
|
||||
fn a_bar_query_sees_a_ui_change_just_made() {
|
||||
let mut app = app();
|
||||
app.ui.show_toolbar = true;
|
||||
assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": true }));
|
||||
app.ui.show_toolbar = false;
|
||||
assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": false }));
|
||||
app.run("toolbar", json!({ "show": true })).unwrap();
|
||||
assert!(app.ui.show_toolbar, "the request is applied at once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menubar_started_from_the_ui_offers_the_bar_as_shown_now() {
|
||||
let mut app = app();
|
||||
app.ui.in_window_menu = true;
|
||||
app.cmdline("");
|
||||
app.ui.in_window_menu = false;
|
||||
app.start("menubar");
|
||||
let prompt = app.session.prompt_text();
|
||||
assert!(prompt.contains("<0>"), "{prompt}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_through_the_control_api_applies_the_bar_before_the_next_request() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
app.ui.show_toolbar = false;
|
||||
app.start("toolbar");
|
||||
let (req, _pending) = cadcraft_ui_egui::control::ControlRequest::new("cmdline.key", serde_json::json!({ "key": "enter" }));
|
||||
cadcraft_ui_egui::control::handle(&mut app, &ctx, &req);
|
||||
assert!(app.session.running.is_none());
|
||||
assert!(app.ui.show_toolbar, "TOOLBAR's default Show is applied before the next request");
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io};
|
||||
use cadcraft_engine::doc::geom::Vec3;
|
||||
use cadcraft_engine::doc::{Drawing, Entity, EntityKind, Handle, Layer, Line, XrefStatus};
|
||||
use cadcraft_ui_egui::{CadApp, Services, docking::Panel};
|
||||
use cadcraft_ui_egui::{CadApp, Services, docking::Panel, menus};
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -71,6 +71,23 @@ fn xref_opens_the_palette_and_its_buttons_manage_the_xref() {
|
||||
h.get_by_label("site");
|
||||
}
|
||||
|
||||
/// Window ▸ Reference Manager closes the palette when it is open, like Window ▸ QuickCalc; typed,
|
||||
/// XREF only ever opens it (#2273).
|
||||
#[test]
|
||||
fn the_window_menu_item_closes_an_open_palette() {
|
||||
let mut app = CadApp::new(Session::default(), Services::default());
|
||||
let open = |app: &CadApp| app.ui.docking.layout.contains(&Panel::ExternalRefs);
|
||||
menus::activate(&mut app, "xref");
|
||||
assert!(open(&app), "the menu item opens the palette");
|
||||
menus::activate(&mut app, "xref");
|
||||
assert!(!open(&app), "the menu item closes the open palette");
|
||||
menus::activate(&mut app, "xref");
|
||||
assert!(open(&app), "and opens it again");
|
||||
assert!(app.cmdline("XREF").is_none());
|
||||
assert!(app.cmdline("XR").is_none());
|
||||
assert!(open(&app), "typed XREF keeps it open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_xref_lists_and_never_opens_the_palette() {
|
||||
let mut app = CadApp::new(Session::default(), Services::default());
|
||||
|
||||
@@ -144,6 +144,12 @@ The shortcut also works with text-field focus. Toggling preserves the running dr
|
||||
and pending command-line input. The expression, history and calculator variables survive
|
||||
closing/reopening within the same session; they are not saved across application restarts.
|
||||
|
||||
The External References palette (`externalReferences`) is not part of the default arrangement
|
||||
either. Typed `XREF`/`XR` opens and activates it. **Window > Reference Manager** (also
|
||||
`ui.menu.invoke` with `xref`) opens it too, but closes it when it is present, as Window >
|
||||
QuickCalc does; closing leaves the running command and command-line input alone. `xref` with
|
||||
JSON parameters lists the references and never opens or closes the palette.
|
||||
|
||||
Invoke these UI commands through `engine.execute`, for example `{"command":"ui.dock","params":{"operation":"float","panel":"layers","rect":[100,100,320,440]}}`.
|
||||
|
||||
Advanced `ui.dock` operations use the same validated transaction as pointer gestures:
|
||||
|
||||
Reference in New Issue
Block a user