diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ca0070611..813fc2726 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -40,14 +40,15 @@ mod props; pub use blocks::library::{clear_library_cache, list_library, read_library_file}; pub use dimstyle_cli::usable_dim_style_name; pub use draw2::breakline::BreaklineOptions; -pub use props::MatchProps; pub(crate) use props::UNIT_RANGES; +pub use props::{MatchProps, text_styles_in_use}; pub(crate) use props::{current_color_value, set_current_color_value}; mod qselect; mod selecttools; mod settings; mod spline_opts; pub mod table; +mod textstyle_cli; mod tolerance; mod trimextend; pub use trimextend::PREVIEW_MAX_PICKS as TRIM_PREVIEW_MAX_PICKS; @@ -196,6 +197,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(annotate::specs()); v.extend(dimstyles::specs()); v.extend(dimstyle_cli::specs()); + v.extend(textstyle_cli::specs()); v.extend(mleader_edit::specs()); v.extend(annoscale::specs()); v.extend(hatch::specs()); diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 5423c6bb0..ea1dfe9b6 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -31,9 +31,8 @@ use polygon::{PolygonM, run_polygon}; use solid::{SolidM, run_solid}; pub(super) use spline::SplineM; use spline::run_spline; - use text::{MTextM, TextM, run_mtext, run_text}; -pub(crate) use text::{justify, justify_prompt}; +pub(crate) use text::{fixed_height, justify, justify_prompt}; /// Every draw command's spec: JSON parameters, menu path, aliases and the interactive prompt /// machine each command starts. @@ -110,13 +109,16 @@ pub fn specs() -> Vec { CommandSpec::new("text", "Single Line Text", run_text) .menu(&["Draw", "Text", "Single Line Text"]) .alias(&["dt", "dtext"]) - .params("{at, text, height?, rotation? (degrees), justify?: L|C|R|M|TL|TC|TR|ML|MC|MR|BL|BC|BR}") + .params( + "{at, text, height? (default: the style's fixed height, else TEXTSIZE), rotation? (degrees), justify?: L|C|R|M|TL|TC|TR|ML|MC|MR|BL|BC|BR, \ + style? (default: the current style; the text takes its width factor and obliquing angle)}", + ) .interactive(|s| Ok(Box::new(TextM::new(s)))), CommandSpec::new("mtext", "Multiline Text", run_mtext) .menu(&["Draw", "Text", "Multiline Text..."]) .alias(&["t", "mt"]) .params( - "{at, text, height?, width?, attach?: 1..9 | justify?: TL..BR, rotation?, style?, lineSpacing?, lineSpacingExact?, \ + "{at, text, height? (default: the style's fixed height, else TEXTSIZE), width?, attach?: 1..9 | justify?: TL..BR, rotation?, style?, lineSpacing?, lineSpacingExact?, \ list?: bullet|number|lower|upper, indent?, firstIndent?, rightIndent?, tabs?: [..], align?: left|center|right|justify|distributed, \ columns?: {type: static|dynamic, count?, gutter?, height, heights?, reversed?}} (indents and tabs in text heights; width = one column)", ) diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 7f7259011..9ca869745 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -35,11 +35,44 @@ pub(crate) fn justify_prompt(two_points: bool) -> Prompt { Prompt::new("Enter an option", Accept::TEXT).kw(&options) } -pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind { - let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()); - // New text takes Backwards and Upside down from its style, as AutoCAD's does; later style - // changes don't change them. - let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style)).map_or((false, false), |t| (t.backwards, t.upside_down)); +/// Justification → the name TEXT's status line gives it. +fn justify_name(j: (HAlign, VAlign)) -> &'static str { + match j { + (HAlign::Left, VAlign::Baseline) => "Left", + (HAlign::Center, VAlign::Baseline) => "Center", + (HAlign::Right, VAlign::Baseline) => "Right", + (HAlign::Aligned, _) => "Align", + (HAlign::Middle, _) => "Middle", + (HAlign::Fit, _) => "Fit", + (HAlign::Left, VAlign::Top) => "TL", + (HAlign::Center, VAlign::Top) => "TC", + (HAlign::Right, VAlign::Top) => "TR", + (HAlign::Left, VAlign::Middle) => "ML", + (HAlign::Center, VAlign::Middle) => "MC", + (HAlign::Right, VAlign::Middle) => "MR", + (HAlign::Left, VAlign::Bottom) => "BL", + (HAlign::Center, VAlign::Bottom) => "BC", + (HAlign::Right, VAlign::Bottom) => "BR", + } +} + +/// The height text style `style` fixes for its text (`None`: asked when text is placed). +pub(crate) fn fixed_height(d: &cadcraft_doc::Drawing, style: &str) -> Option { + d.text_style(style).map(|t| t.height).filter(|h| h.is_finite() && *h > 0.0) +} + +/// TEXT in `style`, which gives it its width factor and obliquing angle, as AutoCAD's new text +/// takes them from its style (later style changes don't change them). Backwards and upside down +/// come from the same style, as AutoCAD's do. +pub(crate) fn make_text(s: &Session, style: &str, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind { + let (width_factor, oblique) = s + .doc() + .ok() + .and_then(|d| d.text_style(style)) + .map(|t| (t.width_factor, t.oblique)) + .filter(|(w, o)| w.is_finite() && *w > 0.0 && o.is_finite()) + .unwrap_or((1.0, 0.0)); + let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(style)).map_or((false, false), |t| (t.backwards, t.upside_down)); let (h, v) = j; let left = h == HAlign::Left && v == VAlign::Baseline; EntityKind::Text(Text { @@ -48,9 +81,9 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio height, value: value.into(), rotation, - width_factor: 1.0, - oblique: 0.0, - style, + width_factor, + oblique, + style: style.to_string(), halign: h, valign: v, backwards, @@ -58,29 +91,38 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio }) } +/// A `style` parameter: the drawing's style of that name, else the current style. +fn style_param(s: &Session, cmd: &str, p: &Value) -> Result { + let d = s.doc()?; + match str_param(p, "style") { + Some(n) => d.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad(cmd, format!("no text style \"{n}\""))), + None => Ok(d.header.str("TEXTSTYLE", "Standard")), + } +} + pub(super) fn run_text(s: &mut Session, p: &Value) -> Result { let at = point_req("text", p, "at")?; let text = str_param(p, "text").ok_or_else(|| bad("text", "`text` is required"))?; - let height = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2)); - if height <= 0.0 { + let style = style_param(s, "text", p)?; + let d = s.doc()?; + let height = f64_or(p, "height", fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2))); + if !(height > 0.0 && height.is_finite()) { return Err(bad("text", "height must be positive")); } let j = justify(str_param(p, "justify").unwrap_or("L")).ok_or_else(|| bad("text", "unknown justification"))?; - let k = make_text(s, at, text, height, f64_or(p, "rotation", 0.0).to_radians(), j); + let k = make_text(s, &style, at, text, height, f64_or(p, "rotation", 0.0).to_radians(), j); added(s.add_entity(k)?) } pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result { let at = point_req("mtext", p, "at")?; let text = str_param(p, "text").ok_or_else(|| bad("mtext", "`text` is required"))?; - let height = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2)); - if height <= 0.0 { + let style = style_param(s, "mtext", p)?; + let d = s.doc()?; + let height = f64_or(p, "height", fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2))); + if !(height > 0.0 && height.is_finite()) { return Err(bad("mtext", "height must be positive")); } - let style = match str_param(p, "style") { - Some(n) => s.doc()?.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad("mtext", format!("no text style \"{n}\"")))?, - None => s.doc()?.header.str("TEXTSTYLE", "Standard"), - }; let attach = match str_param(p, "justify") { Some(j) => crate::cmd::mtext_opts::attach_code(j).ok_or_else(|| bad("mtext", "`justify` must be TL, TC, TR, ML, MC, MR, BL, BC or BR"))?, None => p.get("attach").and_then(Value::as_u64).unwrap_or(1).clamp(1, 9) as u8, @@ -102,13 +144,23 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result { added(s.add_entity(k)?) } +/// A question TEXT asks besides its main prompts. +#[derive(Clone, Copy, PartialEq)] +enum TextAsk { + Justify, + Style, + StyleList, +} + pub(super) struct TextM { at: Option, height: Option, rotation: Option, justify: (HAlign, VAlign), - asking_justify: bool, + ask: Option, line: usize, + /// The style of the text continued below (Enter at the start point); else the current one. + style: Option, /// Run by a LISP routine (`command`): one line of text ends the command, as AutoLISP's /// `command` runs TEXT; typed and in scripts each line asks for the next. single_line: bool, @@ -121,11 +173,58 @@ impl TextM { height: None, rotation: None, justify: (HAlign::Left, VAlign::Baseline), - asking_justify: false, + ask: None, line: 0, + style: None, single_line: s.lisp_running(), } } + + /// The style new lines are set in. + fn style(&self, s: &Session) -> String { + self.style.clone().unwrap_or_else(|| s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into())) + } + + /// The status line: the style, the height it fixes (else TEXTSIZE), annotative, justify. + fn status(&self, s: &mut Session) -> Result<()> { + let style = self.style(s); + let d = s.doc()?; + let anno = if d.text_style(&style).is_some_and(|st| st.annotative) { "Yes" } else { "No" }; + let height = fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2)); + s.echo(format!("Current text style: \"{style}\" Text height: {height:.4} Annotative: {anno} Justify: {}", justify_name(self.justify))); + Ok(()) + } + + /// Continue directly below the last TEXT in this space, with its style, height, rotation and + /// justification, as Enter at AutoCAD's start point does. False when there is none. + fn continue_below(&mut self, s: &Session) -> bool { + let Ok(d) = s.doc() else { return false }; + let last = d.space(&s.space()).and_then(|st| st.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t) } else { None }).last()); + let Some(t) = last else { return false }; + let usable = |h: f64| h.is_finite() && h > 0.0; + let h = if usable(t.height) { + t.height + } else { + let size = d.header.f64("TEXTSIZE", 0.2); + // Neither the last text's height nor TEXTSIZE can space the next line: nothing to continue. + if !usable(size) { + return false; + } + size + }; + let r = if t.rotation.is_finite() { t.rotation } else { 0.0 }; + // Aligned and fit text need two points: the next line is left-justified at the start point. + let (j, from) = match t.halign { + HAlign::Aligned | HAlign::Fit => ((HAlign::Left, VAlign::Baseline), t.insert.xy()), + _ => ((t.halign, t.valign), t.justify_point()), + }; + self.at = Some(from + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0)); + self.height = Some(h); + self.rotation = Some(r); + self.justify = j; + self.style = d.text_style(&t.style).map(|st| st.name.clone()); + true + } } impl Interactive for TextM { @@ -134,43 +233,96 @@ impl Interactive for TextM { } fn prompt(&self, s: &Session) -> Prompt { let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2); - if self.asking_justify { - return justify_prompt(true); + match self.ask { + Some(TextAsk::Justify) => { + return justify_prompt(true); + } + Some(TextAsk::Style) => return Prompt::new("Enter style name", Accept::TEXT).kw(&["?"]).default(self.style(s)), + Some(TextAsk::StyleList) => return Prompt::new("Enter text style(s) to list", Accept::TEXT).default("*"), + None => {} } match (self.at, self.height, self.rotation) { (None, _, _) => Prompt::new("Specify start point of text", Accept::POINT).kw(&["Justify", "Style"]), - (Some(a), None, _) => Prompt::new("Specify height", Accept::POINT_OR_NUMBER).default(format!("{th:.4}")).base(a), + (Some(a), None, _) => { + // An annotative style's text is sized as it measures on paper. + let annotative = s.doc().is_ok_and(|d| d.text_style(&self.style(s)).is_some_and(|st| st.annotative)); + let ask = if annotative { "Specify paper text height" } else { "Specify height" }; + Prompt::new(ask, Accept::POINT_OR_NUMBER).default(format!("{th:.4}")).base(a) + } (Some(a), Some(_), None) => Prompt::new("Specify rotation angle of text", Accept::POINT_OR_NUMBER).default("0").base(a), _ => Prompt::new("Enter text", Accept::TEXT), } } fn begin(&mut self, s: &mut Session) -> Result { - let d = s.doc()?; - let style = d.header.str("TEXTSTYLE", "Standard"); - let anno = if d.text_style(&style).is_some_and(|st| st.annotative) { "Yes" } else { "No" }; - let msg = - format!("Current text style: \"{style}\" Text height: {:.4} Annotative: {anno} Justify: Left", d.header.f64("TEXTSIZE", 0.2)); - s.echo(msg); + self.status(s)?; Ok(Step::Continue) } fn input(&mut self, s: &mut Session, i: Input) -> Result { - if self.asking_justify { - let code = match &i { - Input::Keyword(k) | Input::Text(k) => k.clone(), - _ => return Ok(Step::Continue), - }; - self.justify = justify(&code).unwrap_or(self.justify); - self.asking_justify = false; - return Ok(Step::Continue); + let word = match &i { + Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_string()), + _ => None, + }; + match self.ask { + Some(TextAsk::Justify) => { + // Enter leaves the question with the justification as it was (as Style's does). + let Some(code) = word.filter(|w| !w.is_empty()) else { + self.ask = None; + return Ok(Step::Continue); + }; + // As MTEXT's: an answer that is no option is refused, and asked again. + self.justify = justify(&code).ok_or_else(|| crate::EngineError::Other("Invalid option keyword.".into()))?; + self.ask = None; + return Ok(Step::Continue); + } + Some(TextAsk::Style) => { + match word.as_deref() { + None | Some("") => self.ask = None, + Some("?") => self.ask = Some(TextAsk::StyleList), + Some(name) => { + let found = s.doc()?.text_style(name).map(|t| t.name.clone()); + let name = found.ok_or_else(|| crate::EngineError::Other(format!("Cannot find text style \"{name}\".")))?; + // Like AutoCAD's Style option, the style becomes current. + s.doc_mut()?.header.set_str("TEXTSTYLE", &name); + self.style = None; + self.ask = None; + self.status(s)?; + } + } + return Ok(Step::Continue); + } + Some(TextAsk::StyleList) => { + let pattern = word.filter(|w| !w.is_empty()).unwrap_or_else(|| "*".into()); + let d = s.doc()?; + let lines: Vec = + crate::cmd::textstyle_cli::styles_matching(d, &pattern).into_iter().map(crate::cmd::textstyle_cli::listing).collect(); + for l in lines { + s.echo(l); + } + self.ask = Some(TextAsk::Style); + return Ok(Step::Continue); + } + None => {} } let th = s.doc()?.header.f64("TEXTSIZE", 0.2); match (self.at, self.height, self.rotation, i) { - (None, _, _, Input::Keyword(k)) if k == "Justify" => self.asking_justify = true, - (None, _, _, Input::Point(p)) => self.at = Some(p), + (None, _, _, Input::Keyword(k)) if k == "Justify" => self.ask = Some(TextAsk::Justify), + (None, _, _, Input::Keyword(k)) if k == "Style" => self.ask = Some(TextAsk::Style), + (None, _, _, Input::Point(p)) => { + self.at = Some(p); + // A fixed-height style isn't asked for a height. + self.height = fixed_height(s.doc()?, &self.style(s)); + } + (None, _, _, Input::Enter) => { + if !self.continue_below(s) { + return Ok(Step::Done); + } + } (Some(_), None, _, Input::Enter) => self.height = Some(th), (Some(a), None, _, Input::Point(p)) => self.height = Some(a.dist(p).max(1e-9)), (Some(_), None, _, Input::Text(t)) => { - let h = number(&t).filter(|h| *h > 0.0).ok_or_else(|| crate::EngineError::Other("Requires a positive height.".into()))?; + let h = number(&t) + .filter(|h| *h > 0.0 && h.is_finite()) + .ok_or_else(|| crate::EngineError::Other("Requires a positive height.".into()))?; self.height = Some(h); s.doc_mut()?.header.set_f64("TEXTSIZE", h); } @@ -181,7 +333,7 @@ impl Interactive for TextM { } (Some(a), Some(h), Some(r), Input::Text(t)) => { let at = a + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0 * self.line as f64); - let k = make_text(s, at, &t, h, r, self.justify); + let k = make_text(s, &self.style(s), at, &t, h, r, self.justify); s.add_entity(k)?; self.line += 1; if self.single_line { diff --git a/crates/engine/src/cmd/mtext_opts.rs b/crates/engine/src/cmd/mtext_opts.rs index 301b2ea80..f62e44083 100644 --- a/crates/engine/src/cmd/mtext_opts.rs +++ b/crates/engine/src/cmd/mtext_opts.rs @@ -56,8 +56,14 @@ impl Default for MTextOpts { impl MTextOpts { pub(super) fn new(s: &Session) -> Self { - let (height, style) = - s.doc().map(|d| (d.header.f64("TEXTSIZE", 0.2), d.header.str("TEXTSTYLE", "Standard"))).unwrap_or((0.2, "Standard".into())); + let (height, style) = s + .doc() + .map(|d| { + let style = d.header.str("TEXTSTYLE", "Standard"); + // A fixed-height style sets the height new text starts with. + (super::draw::fixed_height(d, &style).unwrap_or_else(|| d.header.f64("TEXTSIZE", 0.2)), style) + }) + .unwrap_or((0.2, "Standard".into())); MTextOpts { height, style, ..MTextOpts::default() } } @@ -232,6 +238,9 @@ impl MTextAsk { return Ok(Outcome::Ask(MTextAsk::Style)); } o.style = d.text_style(&name).map(|t| t.name.clone()).ok_or_else(|| other(format!("Cannot find text style \"{name}\".")))?; + if let Some(h) = super::draw::fixed_height(d, &o.style) { + o.height = h; + } Ok(Outcome::Back) } (MTextAsk::Width, Input::Point(p)) => { diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index cd14477c3..ed4231724 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -446,7 +446,7 @@ fn styles_json(d: &cadcraft_doc::Drawing) -> Value { json!({ "current": cur, "styles": d.text_styles.iter().map(|t| style_json(t, &cur)).collect::>() }) } -fn run_style(s: &mut Session, p: &Value) -> Result { +pub(super) fn run_style(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("style", "`name` is required"))?.trim().to_string(); if name.is_empty() || name.len() > 255 { return Err(bad("style", "bad style name")); @@ -516,7 +516,7 @@ fn run_style_current(s: &mut Session, p: &Value) -> Result { /// Text style names used by entities (in model, paper spaces and blocks), dimension, /// multileader and table styles (their cell styles), and the text of complex linetypes. -pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec { +pub fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec { let mut out: Vec = d.dim_styles.iter().map(|s| s.text_style.clone()).collect(); out.extend(d.mleader_styles.iter().map(|s| s.text_style.clone())); out.extend(d.table_styles.iter().flat_map(|s| s.cell_styles.iter().map(|c| c.text_style.clone()))); diff --git a/crates/engine/src/cmd/textstyle_cli.rs b/crates/engine/src/cmd/textstyle_cli.rs new file mode 100644 index 000000000..8297bc2b2 --- /dev/null +++ b/crates/engine/src/cmd/textstyle_cli.rs @@ -0,0 +1,352 @@ +//! -STYLE, text styles at the command line (scripts, the keyboard): AutoCAD's prompts for a +//! style's name, font, height (or annotative paper height), width factor, obliquing angle, +//! backwards and upside-down text (and vertical text for SHX fonts), which then becomes the +//! current style. Also `style.fonts`, the installed fonts a style can name, by family and style +//! (the Text Style dialog's font lists). +//! Behavior reference: +//! and . + +use cadcraft_doc::{Drawing, TextStyle}; +use serde_json::{Value, json}; + +use super::CommandSpec; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("-style", "Text Style", super::props::run_style) + .params("same as `style`: {name, font?, bigFont?, height?, widthFactor?, oblique? (degrees), backwards?, upsideDown?, vertical?, annotative?, current?} → styles") + .interactive(|_| Ok(Box::new(DashStyle::default()))), + CommandSpec::new("style.fonts", "List Fonts", run_fonts) + .params("{} → {fonts: [{family, style, file}]} (the built-in stroke font first, then the installed fonts; a text style's `font` takes `file`)") + .noundo(), + ] +} + +fn run_fonts(_s: &mut Session, _p: &Value) -> Result { + let builtin = cadcraft_fonts::BUILTIN_FONT; + let mut fonts = vec![json!({ "family": builtin, "style": "Regular", "file": builtin })]; + fonts.extend(cadcraft_fonts::ttf::installed_fonts().into_iter().map(|f| json!({ "family": f.family, "style": f.style, "file": f.file }))); + Ok(json!({ "fonts": fonts })) +} + +fn other(m: impl Into) -> EngineError { + EngineError::Other(m.into()) +} + +/// Whether `font` names an SHX font (the only kind with a vertical form). +fn is_shx(font: &str) -> bool { + cadcraft_fonts::is_shx_name(font) +} + +fn yes(text: Option<&str>, default: bool) -> bool { + match text.map(str::to_ascii_lowercase).as_deref() { + Some("yes" | "y") => true, + Some("no" | "n") => false, + _ => default, + } +} + +/// A style's settings in one line, as `?` lists them. +pub(super) fn listing(st: &TextStyle) -> String { + let mut generation: Vec<&str> = Vec::new(); + if st.backwards { + generation.push("Backwards"); + } + if st.upside_down { + generation.push("Upside-down"); + } + if st.vertical { + generation.push("Vertical"); + } + let generation = if generation.is_empty() { "Normal".to_string() } else { generation.join(", ") }; + let annotative = if st.annotative { " Annotative" } else { "" }; + format!( + "Style name: \"{}\" Font files: {} Height: {:.4} Width factor: {:.4} Obliquing angle: {:.0} Generation: {generation}{annotative}", + st.name, + st.font, + st.height, + st.width_factor, + st.oblique.to_degrees() + ) +} + +/// Text style names matching `pattern` (`*` and `?` wildcards, any case). +pub(super) fn styles_matching<'a>(d: &'a Drawing, pattern: &str) -> Vec<&'a TextStyle> { + let p: Vec = pattern.trim().to_lowercase().chars().take(255).collect(); + let p = if p.is_empty() { vec!['*'] } else { p }; + d.text_styles.iter().filter(|st| wildcard(&p, &st.name.to_lowercase().chars().collect::>())).collect() +} + +/// `*` and `?` matching without recursion (bounded by the two lengths). +fn wildcard(p: &[char], s: &[char]) -> bool { + let (mut pi, mut si) = (0, 0); + let mut star: Option<(usize, usize)> = None; + while si < s.len() { + match p.get(pi) { + Some('*') => { + star = Some((pi, si)); + pi += 1; + } + Some(c) if *c == '?' || Some(c) == s.get(si) => { + pi += 1; + si += 1; + } + _ => match star { + Some((sp, ss)) => { + pi = sp + 1; + si = ss + 1; + star = Some((sp, ss + 1)); + } + None => return false, + }, + } + } + p.get(pi..).is_some_and(|rest| rest.iter().all(|c| *c == '*')) +} + +#[derive(Default)] +enum Ask { + #[default] + Name, + ListPattern, + Font, + Height, + Annotative, + Orientation, + PaperHeight, + Width, + Oblique, + Backwards, + UpsideDown, + Vertical, +} + +/// The style being defined: its settings so far, starting from the existing style (or, for a +/// new one, the current style). +#[derive(Default)] +struct DashStyle { + ask: Ask, + style: TextStyle, +} + +impl DashStyle { + fn finish(&self, s: &mut Session) -> Result { + let st = &self.style; + super::props::run_style( + s, + &json!({ + "name": st.name, + "font": st.font, + // A new style keeps the big font of the style it starts from. + "bigFont": st.big_font, + "height": st.height, + "widthFactor": st.width_factor, + "oblique": st.oblique.to_degrees(), + "backwards": st.backwards, + "upsideDown": st.upside_down, + "vertical": st.vertical, + "annotative": st.annotative, + "current": true, + }), + )?; + s.echo(format!("\"{}\" is now the current text style.", st.name)); + Ok(Step::Done) + } +} + +fn number(t: &str) -> Option { + t.trim().parse::().ok().or_else(|| crate::units::parse_distance(t)).filter(|v| v.is_finite()) +} + +impl Interactive for DashStyle { + fn name(&self) -> &'static str { + "-STYLE" + } + fn begin(&mut self, s: &mut Session) -> Result { + let d = s.doc()?; + let current = d.header.str("TEXTSTYLE", "Standard"); + self.style = d.text_style(¤t).cloned().unwrap_or_default(); + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + let st = &self.style; + let (lu, lp) = s.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4)); + let dist = |v: f64| crate::units::format_distance(v, lu, lp); + let yes_no = |b: bool| if b { "Yes" } else { "No" }; + match self.ask { + Ask::Name => Prompt::new("Enter name of text style", Accept::TEXT).kw(&["?"]).default(st.name.clone()), + Ask::ListPattern => Prompt::new("Enter text style(s) to list", Accept::TEXT).default("*"), + Ask::Font => Prompt::new("Specify full font name or font filename (TTF or SHX)", Accept::TEXT).default(st.font.clone()), + Ask::Height => Prompt::new("Specify height of text", Accept::TEXT).kw(&["Annotative"]).default(dist(st.height)), + // Asked after Annotative was picked: Enter says yes. + Ask::Annotative => Prompt::new("Create annotative text style?", Accept::TEXT).kw(&["Yes", "No"]).default("Yes"), + Ask::Orientation => Prompt::new("Match text orientation to layout?", Accept::TEXT).kw(&["Yes", "No"]).default("No"), + Ask::PaperHeight => Prompt::new("Specify paper text height", Accept::TEXT).default(dist(st.height)), + Ask::Width => Prompt::new("Specify width factor", Accept::TEXT).default(format!("{:.4}", st.width_factor)), + Ask::Oblique => Prompt::new("Specify obliquing angle", Accept::TEXT).default(format!("{:.0}", st.oblique.to_degrees())), + Ask::Backwards => Prompt::new("Display text backwards?", Accept::TEXT).kw(&["Yes", "No"]).default(yes_no(st.backwards)), + Ask::UpsideDown => Prompt::new("Display text upside-down?", Accept::TEXT).kw(&["Yes", "No"]).default(yes_no(st.upside_down)), + Ask::Vertical => Prompt::new("Vertical?", Accept::TEXT).kw(&["Yes", "No"]).default(yes_no(st.vertical)), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let ask = std::mem::take(&mut self.ask); + let text = match &i { + Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()), + _ => None, + }; + let t = text.as_deref(); + match ask { + Ask::Name => match t { + Some("?") => self.ask = Ask::ListPattern, + _ => { + let name = t.map_or_else(|| self.style.name.clone(), str::to_string); + if name.len() > 255 || name.contains(['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`']) { + self.ask = Ask::Name; + return Err(other("Invalid text style name.")); + } + let d = s.doc()?; + match d.text_style(&name) { + Some(existing) => { + self.style = existing.clone(); + s.echo("Existing style.".to_string()); + } + None => { + // A new style starts with the current style's settings. + self.style.name = name; + s.echo("New style.".to_string()); + } + } + self.ask = Ask::Font; + } + }, + Ask::ListPattern => { + let d = s.doc()?; + let lines: Vec = styles_matching(d, t.unwrap_or("*")).into_iter().map(listing).collect(); + let current = d.header.str("TEXTSTYLE", "Standard"); + for l in lines { + s.echo(l); + } + s.echo(format!("Current text style: {current}")); + return Ok(Step::Done); + } + Ask::Font => { + if let Some(f) = t { + let (normal, big) = f.split_once(',').map_or((f, None), |(normal, big)| (normal, Some(big))); + let clean = |name: &str| name.trim().trim_matches('"').trim().chars().take(255).collect::(); + let normal = clean(normal); + if !normal.is_empty() { + if cadcraft_fonts::ttf::find(&normal).is_none() + && !is_shx(&normal) + && !normal.eq_ignore_ascii_case(cadcraft_fonts::BUILTIN_FONT) + { + s.echo(format!("Font {normal} is not installed; text is drawn with a substitute.")); + } + self.style.font = normal; + } + match big { + Some(big) if !big.trim().is_empty() => self.style.big_font = clean(big), + None => self.style.big_font.clear(), + _ => {} + } + } + self.ask = Ask::Height; + } + Ask::Height => match t { + Some(k) if k.eq_ignore_ascii_case("annotative") || k.eq_ignore_ascii_case("a") => self.ask = Ask::Annotative, + Some(v) => match number(v).filter(|h| *h >= 0.0) { + Some(h) => { + self.style.height = h; + self.ask = Ask::Width; + } + None => { + self.ask = Ask::Height; + return Err(other("Requires a distance, or Annotative.")); + } + }, + None => self.ask = Ask::Width, + }, + Ask::Annotative => { + self.style.annotative = yes(t, true); + // No asks for the height again, as it measures in the drawing. + self.ask = if self.style.annotative { Ask::Orientation } else { Ask::Height }; + } + // CADCraft doesn't model the layout orientation; the answer is taken and not kept. + Ask::Orientation => self.ask = Ask::PaperHeight, + Ask::PaperHeight => match t.map(number) { + Some(Some(h)) if h >= 0.0 => { + self.style.height = h; + self.ask = Ask::Width; + } + Some(_) => { + self.ask = Ask::PaperHeight; + return Err(other("Requires a positive distance or 0.")); + } + None => self.ask = Ask::Width, + }, + Ask::Width => match t.map(number) { + Some(Some(w)) if w > 0.0 && w <= 100.0 => { + self.style.width_factor = w; + self.ask = Ask::Oblique; + } + Some(_) => { + self.ask = Ask::Width; + return Err(other("Requires a width factor greater than 0 and at most 100.")); + } + None => self.ask = Ask::Oblique, + }, + Ask::Oblique => { + let angle = t.map(|v| { + v.trim().parse::().ok().or_else(|| { + crate::units::parse_angle(v).map(|a| { + let d = a.to_degrees().rem_euclid(360.0); + if d > 180.0 { d - 360.0 } else { d } + }) + }) + }); + match angle { + Some(Some(a)) if a.abs() <= 85.0 => { + self.style.oblique = a.to_radians(); + self.ask = Ask::Backwards; + } + Some(_) => { + self.ask = Ask::Oblique; + return Err(other("Requires an angle between -85 and 85.")); + } + None => self.ask = Ask::Backwards, + } + } + Ask::Backwards => { + self.style.backwards = yes(t, self.style.backwards); + self.ask = Ask::UpsideDown; + } + Ask::UpsideDown => { + self.style.upside_down = yes(t, self.style.upside_down); + if !is_shx(&self.style.font) { + self.style.vertical = false; + return self.finish(s); + } + self.ask = Ask::Vertical; + } + Ask::Vertical => { + self.style.vertical = yes(t, self.style.vertical); + return self.finish(s); + } + } + Ok(Step::Continue) + } +} + +#[cfg(test)] +mod tests { + use super::wildcard; + + #[test] + fn wildcards() { + let m = |p: &str, s: &str| wildcard(&p.chars().collect::>(), &s.chars().collect::>()); + assert!(m("*", "anything") && m("st*", "standard") && m("s?andard", "standard") && m("*d", "standard")); + assert!(!m("st", "standard") && !m("x*", "standard")); + assert!(m(&"*".repeat(10_000), "abc")); + } +} diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 9be1b5d60..d3f5c51db 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -69,6 +69,7 @@ pub const FILES: &[&str] = &[ /// Commands that can't be held to the roots, and why. pub const REFUSED: &[(&str, &str)] = &[ + ("style.fonts", "it reads installed fonts outside the automation roots"), ("drawingrecovery", "it works on the autosave folder (SAVEFILEPATH), which is the server's own"), ("blocklibraries", "it keeps its list of libraries in the settings folder, which is the server's own"), ]; @@ -87,6 +88,7 @@ pub const NO_FILES: &[&str] = &[ "blockspalette", "dimoverride.clear", "-dimstyle", + "-style", "dimstyle.overrides", "dimstyle.saveas", "properties.describe", diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 33e33424e..58b947dc7 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -199,6 +199,7 @@ mod temp_tracking; mod text_commands; mod text_generation_flags; mod text_left_justify; +mod text_style_creation; mod tolerance; mod transparent; mod trim_closed_polyline; diff --git a/crates/engine/tests/it/text_style_creation.rs b/crates/engine/tests/it/text_style_creation.rs new file mode 100644 index 000000000..5a90def98 --- /dev/null +++ b/crates/engine/tests/it/text_style_creation.rs @@ -0,0 +1,207 @@ +//! New text follows its style as AutoCAD's does: a fixed-height style isn't asked for a height, +//! an annotative style is asked for the paper height, TEXT takes the style's width factor and +//! obliquing angle, the Style option picks the style, and Enter at the start point continues +//! below the last TEXT. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, HAlign, MText, Text, VAlign}; +use serde_json::json; + +fn lines(s: &mut Session, input: &[&str]) { + for l in input { + s.cmdline(l).unwrap_or_else(|e| panic!("{l:?}: {e:?}")); + } +} + +fn texts(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).collect() +} + +fn mtexts(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t.clone()) } else { None }).collect() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_fixed_height_style_is_not_asked_for_a_height() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Fixed", "height": 2.5 })).unwrap(); + s.cmdline("TEXT").unwrap(); + assert!(s.log.iter().any(|l| l.contains("\"Fixed\"") && l.contains("Text height: 2.5000")), "{:?}", s.log); + s.cmdline("0,0").unwrap(); + assert!(s.prompt_text().contains("Specify rotation angle of text"), "{}", s.prompt_text()); + lines(&mut s, &["0", "Hello", ""]); + assert_eq!(texts(&s)[0].height, 2.5); + // TEXTSIZE isn't changed by a fixed height; JSON text takes the fixed height by default. + assert_eq!(s.doc().unwrap().header.f64("TEXTSIZE", 0.0), 0.2); + s.execute("text", &json!({ "at": [0, 10], "text": "Json" })).unwrap(); + assert_eq!(texts(&s)[1].height, 2.5); + s.execute("text", &json!({ "at": [0, 20], "text": "Own", "height": 1 })).unwrap(); + assert_eq!(texts(&s)[2].height, 1.0, "an explicit height is kept"); +} + +#[test] +fn new_text_takes_the_styles_width_factor_and_oblique_angle() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Narrow", "widthFactor": 0.8, "oblique": 15 })).unwrap(); + lines(&mut s, &["TEXT", "0,0", "1", "0", "Typed", ""]); + s.execute("text", &json!({ "at": [0, 5], "text": "Json" })).unwrap(); + s.execute("style", &json!({ "name": "Plain", "current": false })).unwrap(); + s.execute("text", &json!({ "at": [0, 10], "text": "Other", "style": "plain" })).unwrap(); + let t = texts(&s); + for x in &t[..2] { + assert_eq!((x.style.as_str(), x.width_factor), ("Narrow", 0.8)); + assert!(close(x.oblique.to_degrees(), 15.0)); + } + assert_eq!((t[2].style.as_str(), t[2].width_factor, t[2].oblique), ("Plain", 1.0, 0.0)); + // Changing the style afterwards leaves existing text as it is. + s.execute("style", &json!({ "name": "Narrow", "widthFactor": 1.5 })).unwrap(); + assert_eq!(texts(&s)[0].width_factor, 0.8); + assert!(s.execute("text", &json!({ "at": [0, 0], "text": "x", "style": "Nope" })).is_err()); +} + +#[test] +fn an_annotative_style_is_asked_for_the_paper_height() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Notes", "annotative": true })).unwrap(); + lines(&mut s, &["TEXT", "0,0"]); + assert!(s.prompt_text().contains("Specify paper text height"), "{}", s.prompt_text()); + lines(&mut s, &["0.125", "0", "Note", ""]); + let d = s.doc().unwrap(); + let e = d.model.iter().find(|e| matches!(e.kind, EntityKind::Text(_))).unwrap(); + assert!(cadcraft_engine::doc::is_annotative(e)); + assert_eq!(texts(&s)[0].height, 0.125); +} + +#[test] +fn the_style_option_makes_a_style_current() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Title", "height": 5, "current": false })).unwrap(); + lines(&mut s, &["TEXT", "S"]); + assert!(s.prompt_text().contains("Enter style name or [?] "), "{}", s.prompt_text()); + // ? lists the styles, then asks for the name again. + lines(&mut s, &["?", ""]); + assert!(s.log.iter().any(|l| l.contains("Style name: \"Title\"")), "{:?}", s.log); + let _ = s.cmdline("Nope"); + assert!(s.log.iter().any(|l| l.contains("Cannot find text style \"Nope\".")), "{:?}", s.log); + assert!(s.prompt_text().contains("Enter style name"), "asked again: {}", s.prompt_text()); + s.cmdline("title").unwrap(); + assert_eq!(s.doc().unwrap().header.str("TEXTSTYLE", ""), "Title"); + assert!(s.log.iter().any(|l| l.contains("Current text style: \"Title\" Text height: 5.0000")), "{:?}", s.log); + assert!(s.prompt_text().contains("Specify start point of text"), "{}", s.prompt_text()); + // Title fixes the height: the next question is the rotation. + s.cmdline("0,0").unwrap(); + assert!(s.prompt_text().contains("Specify rotation angle of text"), "{}", s.prompt_text()); + lines(&mut s, &["0", "Big", ""]); + assert_eq!(texts(&s)[0].style, "Title"); + assert_eq!(texts(&s)[0].height, 5.0); +} + +#[test] +fn a_justification_that_is_no_option_is_asked_again() { + let mut s = Session::new(); + lines(&mut s, &["TEXT", "J"]); + let _ = s.cmdline("X"); + assert!(s.log.iter().any(|l| l.contains("Invalid option keyword.")), "{:?}", s.log); + assert!(s.prompt_text().contains("Enter an option"), "asked again: {}", s.prompt_text()); + s.cmdline("MC").unwrap(); + lines(&mut s, &["0,0", "2", "0", "Centered", ""]); + assert_eq!(texts(&s)[0].halign, cadcraft_engine::doc::HAlign::Center); + // Enter leaves the question, as the start point's prompt shows. + lines(&mut s, &["TEXT", "J", ""]); + assert!(s.prompt_text().contains("Specify start point of text"), "{}", s.prompt_text()); + s.cancel(); +} + +#[test] +fn enter_at_the_start_point_continues_below_the_last_text() { + let mut s = Session::new(); + lines(&mut s, &["TEXT", "J", "MC", "10,10", "2", "90", "First", ""]); + s.execute("style", &json!({ "name": "Other" })).unwrap(); + lines(&mut s, &["TEXT", ""]); + assert!(s.prompt_text().contains("Enter text"), "no height or rotation asked: {}", s.prompt_text()); + lines(&mut s, &["Second", "Third", ""]); + let t = texts(&s); + assert_eq!(t.len(), 3); + for (i, x) in t.iter().enumerate().skip(1) { + assert_eq!((x.height, x.halign, x.valign), (2.0, HAlign::Center, VAlign::Middle)); + assert!(close(x.rotation.to_degrees(), 90.0)); + assert_eq!(x.style, "Standard", "the continued text's style, not the current one"); + // Rotated 90°: lines go to +X, one line spacing (5/3 of the height) apart. + let p = x.justify_point(); + assert!(close(p.x, 10.0 + 2.0 * 5.0 / 3.0 * i as f64) && close(p.y, 10.0), "line {i}: {p:?}"); + } + // With no text in the drawing, Enter ends the command. + let mut empty = Session::new(); + lines(&mut empty, &["TEXT", ""]); + assert!(empty.running.is_none()); + assert!(texts(&empty).is_empty()); +} + +#[test] +fn enter_at_the_start_point_does_not_continue_with_an_unusable_height() { + let mut s = Session::new(); + lines(&mut s, &["TEXT", "10,10", "2", "0", "First", ""]); + assert_eq!(texts(&s).len(), 1); + // The last text's height and TEXTSIZE are both unusable: nothing spaces the next line. + { + let d = s.doc_mut().unwrap(); + d.header.set_f64("TEXTSIZE", 0.0); + let handle = d.model.iter().next().expect("the first text").handle; + d.model.modify(handle, |e| { + if let EntityKind::Text(t) = &mut e.kind { + t.height = 0.0; + } + }); + } + lines(&mut s, &["TEXT", ""]); + assert!(s.running.is_none(), "Enter ends the command: {}", s.prompt_text()); + assert_eq!(texts(&s).len(), 1, "no text of height 0 was made"); +} + +#[test] +fn mtext_starts_with_a_fixed_style_height() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Fixed", "height": 3 })).unwrap(); + lines(&mut s, &["MTEXT", "0,0", "20,-10", "Para", ""]); + s.execute("mtext", &json!({ "at": [0, 20], "text": "Json" })).unwrap(); + // The Style option takes a fixed style's height too. + s.execute("style", &json!({ "name": "Free" })).unwrap(); + s.execute("style", &json!({ "name": "Tall", "height": 7, "current": false })).unwrap(); + lines(&mut s, &["MTEXT", "0,40", "S", "Tall", "20,30", "Tall text", ""]); + let heights: Vec = mtexts(&s).iter().map(|m| m.height).collect(); + assert_eq!(heights, [3.0, 3.0, 7.0]); +} + +#[test] +fn hostile_text_input_never_panics() { + // A caught panic comes back as an internal error: refused input may fail, but never so. + let not_internal = |r: &Result<_, cadcraft_engine::EngineError>, what: &str| { + assert!(!matches!(r, Err(cadcraft_engine::EngineError::Internal(..))), "{what}: {:?}", r.as_ref().err()); + }; + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Weird", "height": 1e308, "widthFactor": 1e-300 })).unwrap(); + for script in [ + vec!["TEXT", "S", "?", &"*".repeat(50_000)], + vec!["TEXT", "S", &"x".repeat(100_000)], + vec!["TEXT", "0,0", "0", "x", ""], + vec!["TEXT", "", "", "", ""], + ] { + for l in script { + not_internal(&s.cmdline(l).map(|_| ()), l); + } + s.cancel(); + } + for p in [ + json!({ "at": [0, 0], "text": "x", "style": 5 }), + json!({ "at": [0, 0], "text": "x", "height": f64::MAX }), + json!({ "at": [0, 0], "text": "x", "height": -1 }), + ] { + for cmd in ["text", "mtext"] { + not_internal(&s.execute(cmd, &p).map(|_| ()), cmd); + } + } +} diff --git a/crates/engine/tests/textstyle_cli.rs b/crates/engine/tests/textstyle_cli.rs new file mode 100644 index 000000000..e621f2691 --- /dev/null +++ b/crates/engine/tests/textstyle_cli.rs @@ -0,0 +1,233 @@ +//! -STYLE at the command line (AutoCAD's prompt order, so scripts written for AutoCAD run) and +//! `style.fonts`, the fonts the Text Style dialog offers. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::TextStyle; +use serde_json::json; + +fn style(s: &Session, name: &str) -> TextStyle { + s.doc().unwrap().text_style(name).cloned().unwrap() +} + +fn current(s: &Session) -> String { + s.doc().unwrap().header.str("TEXTSTYLE", "") +} + +fn lines(s: &mut Session, input: &[&str]) { + for l in input { + s.cmdline(l).unwrap_or_else(|e| panic!("{l:?}: {e:?}")); + } +} + +/// A font file with only a naming table (Windows English names), built here: no font file is +/// committed. +fn font_with_names(family: &str, style: &str) -> Vec { + let mut strings = Vec::new(); + let mut recs = Vec::new(); + for (id, s) in [(1u16, family), (2, style)] { + let bytes: Vec = s.encode_utf16().flat_map(u16::to_be_bytes).collect(); + for v in [3u16, 1, 0x0409, id, bytes.len() as u16, strings.len() as u16] { + recs.extend_from_slice(&v.to_be_bytes()); + } + strings.extend(bytes); + } + let mut name = Vec::new(); + for v in [0u16, 2, (6 + recs.len()) as u16] { + name.extend_from_slice(&v.to_be_bytes()); + } + name.extend(recs); + name.extend(strings); + let mut out = Vec::new(); + out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + for v in [1u16, 16, 0, 0] { + out.extend_from_slice(&v.to_be_bytes()); + } + out.extend_from_slice(b"name"); + out.extend_from_slice(&0u32.to_be_bytes()); + out.extend_from_slice(&28u32.to_be_bytes()); + out.extend_from_slice(&(name.len() as u32).to_be_bytes()); + out.extend(name); + out +} + +#[test] +fn style_fonts_lists_families_and_styles() { + cadcraft_fonts::ttf::register("cadcraft-style-test-bd.ttf", font_with_names("CADCraft Style Test", "Bold")); + cadcraft_fonts::ttf::register("cadcraft-style-test.ttf", font_with_names("CADCraft Style Test", "Regular")); + let mut s = Session::new(); + let r = s.execute("style.fonts", &json!({})).unwrap(); + let fonts = r["fonts"].as_array().unwrap(); + assert_eq!(fonts[0]["file"], cadcraft_fonts::BUILTIN_FONT, "the built-in font first"); + let ours: Vec<(&str, &str)> = + fonts.iter().filter(|f| f["family"] == "CADCraft Style Test").map(|f| (f["style"].as_str().unwrap(), f["file"].as_str().unwrap())).collect(); + assert_eq!(ours, [("Regular", "cadcraft-style-test.ttf"), ("Bold", "cadcraft-style-test-bd.ttf")]); + // A style naming the file uses that face. + s.execute("style", &json!({ "name": "Heavy", "font": "cadcraft-style-test-bd.ttf" })).unwrap(); + assert!(cadcraft_fonts::ttf::find(&style(&s, "Heavy").font).is_some()); +} + +#[test] +fn dash_style_asks_in_autocads_order() { + let mut s = Session::new(); + s.cmdline("-STYLE").unwrap(); + assert!(s.prompt_text().contains("Enter name of text style or [?] "), "{}", s.prompt_text()); + lines(&mut s, &["Notes", "romans.shx"]); + assert!(s.prompt_text().contains("Specify height of text or [Annotative]"), "{}", s.prompt_text()); + lines(&mut s, &["0.25", "0.8", "15", "Y", "N"]); + // SHX fonts are asked about vertical text. + assert!(s.prompt_text().contains("Vertical?"), "{}", s.prompt_text()); + s.cmdline("N").unwrap(); + assert!(s.running.is_none()); + let st = style(&s, "Notes"); + assert_eq!((st.font.as_str(), st.height, st.width_factor), ("romans.shx", 0.25, 0.8)); + assert!((st.oblique.to_degrees() - 15.0).abs() < 1e-9); + assert!(st.backwards && !st.upside_down && !st.vertical); + assert_eq!(current(&s), "Notes"); + assert!(s.log.iter().any(|l| l.contains("\"Notes\" is now the current text style.")), "{:?}", s.log); +} + +#[test] +fn enter_keeps_an_existing_styles_settings() { + let mut s = Session::new(); + s.execute( + "style", + &json!({ "name": "Plan", "font": "CADCraft Stroke", "height": 2.5, "widthFactor": 0.9, "oblique": 10, "upsideDown": true, "current": false }), + ) + .unwrap(); + s.cmdline("-STYLE").unwrap(); + s.cmdline("plan").unwrap(); + assert!(s.log.iter().any(|l| l == "Existing style."), "{:?}", s.log); + // Font, height, width factor, obliquing angle, backwards, upside down: all Enter. A TrueType or + // stroke font isn't asked about vertical text. + lines(&mut s, &["", "", "", "", "", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let st = style(&s, "Plan"); + assert_eq!((st.height, st.width_factor, st.upside_down), (2.5, 0.9, true)); + assert!((st.oblique.to_degrees() - 10.0).abs() < 1e-9); + assert_eq!(current(&s), "Plan"); +} + +#[test] +fn annotative_styles_ask_for_the_paper_height() { + let mut s = Session::new(); + lines(&mut s, &["-STYLE", "Anno", "", "A", "Y"]); + assert!(s.prompt_text().contains("Match text orientation to layout?"), "{}", s.prompt_text()); + s.cmdline("N").unwrap(); + assert!(s.prompt_text().contains("Specify paper text height"), "{}", s.prompt_text()); + lines(&mut s, &["0.125", "", "", "", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let st = style(&s, "Anno"); + assert!(st.annotative); + assert_eq!(st.height, 0.125); + // Enter at the question says yes, as its default shows; No asks for the height again. + lines(&mut s, &["-STYLE", "Plain", "", "A"]); + assert!(s.prompt_text().contains(""), "{}", s.prompt_text()); + s.cmdline("N").unwrap(); + assert!(s.prompt_text().contains("Specify height of text or [Annotative]"), "{}", s.prompt_text()); + lines(&mut s, &["0.2", "", "", "", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert!(!style(&s, "Plain").annotative); +} + +#[test] +fn a_new_style_keeps_the_current_styles_big_font() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Asian", "font": "txt.shx", "bigFont": "bigfont.shx" })).unwrap(); + // Name, font, height, width factor, obliquing angle, backwards, upside down, vertical. + lines(&mut s, &["-STYLE", "Copy", "", "", "", "", "", "", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(style(&s, "Copy").big_font, "bigfont.shx"); +} + +#[test] +fn shx_font_answers_select_the_right_fonts_and_prompt() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Existing", "font": "old.shx", "bigFont": "old-big.shx" })).unwrap(); + lines(&mut s, &["-STYLE", "Existing", "romans,new-big.shx", "", "", "", "", ""]); + assert!(s.prompt_text().contains("Vertical?"), "{}", s.prompt_text()); + s.cmdline("Y").unwrap(); + let st = style(&s, "Existing"); + assert_eq!((st.font.as_str(), st.big_font.as_str(), st.vertical), ("romans", "new-big.shx", true)); + + lines(&mut s, &["-STYLE", "Existing", ",other-big.shx", "", "", "", "", "", ""]); + let st = style(&s, "Existing"); + assert_eq!((st.font.as_str(), st.big_font.as_str()), ("romans", "other-big.shx")); + + lines(&mut s, &["-STYLE", "Existing", "romans,", "", "", "", "", "", ""]); + assert_eq!(style(&s, "Existing").big_font, "other-big.shx"); + lines(&mut s, &["-STYLE", "Existing", "romans", "", "", "", "", "", ""]); + assert!(style(&s, "Existing").big_font.is_empty()); +} + +#[test] +fn extensionless_installed_outline_font_does_not_ask_for_vertical_text() { + cadcraft_fonts::ttf::register("cadcraft-outline-regression.ttf", font_with_names("CADCraft Outline Regression", "Regular")); + let mut s = Session::new(); + lines(&mut s, &["-STYLE", "Outline", "cadcraft-outline-regression", "", "", "", "", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); +} + +#[test] +fn bad_answers_ask_again() { + let mut s = Session::new(); + let still = |s: &mut Session, answer: &str, prompt: &str| { + let _ = s.cmdline(answer); + assert!(s.prompt_text().contains(prompt), "{answer:?} is refused: {}", s.prompt_text()); + }; + lines(&mut s, &["-STYLE", "Wide", ""]); + still(&mut s, "-1", "Specify height of text"); + still(&mut s, "0", "Specify width factor"); + still(&mut s, "0", "Specify width factor"); + still(&mut s, "2", "Specify obliquing angle"); + still(&mut s, "86", "Specify obliquing angle"); + lines(&mut s, &["-20", "", ""]); + assert!(s.running.is_none()); + let st = style(&s, "Wide"); + assert_eq!(st.width_factor, 2.0); + assert!((st.oblique.to_degrees() + 20.0).abs() < 1e-9); +} + +#[test] +fn question_mark_lists_styles() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Title", "height": 5, "current": false })).unwrap(); + lines(&mut s, &["-STYLE", "?"]); + let before = s.log.len(); + s.cmdline("T*").unwrap(); + let listed: Vec<&String> = s.log[before..].iter().collect(); + assert!(listed.iter().any(|l| l.contains("Style name: \"Title\"") && l.contains("Height: 5.0000")), "{listed:?}"); + assert!(!listed.iter().any(|l| l.contains("\"Standard\"")), "{listed:?}"); + assert!(s.running.is_none(), "listing ends the command"); + s.cmdline("LINE").unwrap(); + assert!(s.prompt_text().contains("first point"), "the next command starts: {}", s.prompt_text()); + s.cancel(); +} + +#[test] +fn json_form_is_the_style_command() { + let mut s = Session::new(); + s.execute("-style", &json!({ "name": "Json", "widthFactor": 0.75, "current": false })).unwrap(); + assert_eq!(style(&s, "Json").width_factor, 0.75); + assert_eq!(current(&s), "Standard"); + assert!(s.execute("-style", &json!({})).is_err()); +} + +#[test] +fn hostile_input_never_panics() { + let mut s = Session::new(); + let long = "x".repeat(100_000); + for script in [ + vec!["-STYLE", "?", &long], + vec!["-STYLE", "a/b"], + vec!["-STYLE", "Ok", &long, "1e308", "NaN", "inf", "-0", "1e-300", "85.0000001", "-85", "maybe", "y", "y"], + vec!["-STYLE", "Shx", "x.shx", "", "", "", "", "", "Yes"], + ] { + for l in script { + let _ = s.cmdline(l); + } + s.cancel(); + } + for p in [json!({ "name": 5 }), json!({ "name": "n", "height": -1, "widthFactor": 1e300, "oblique": f64::MAX }), json!({ "name": long })] { + let _ = s.execute("-style", &p); + } +} diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 1aee50569..603441e2e 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -36,6 +36,20 @@ pub use craft_fonts::{CRAFT_FONTS, CraftFont}; /// Name of the built-in font. pub const BUILTIN_FONT: &str = "CADCraft Stroke"; +/// Whether a style font name denotes an SHX font. An extensionless installed outline font keeps +/// its outline behavior; an unrecognized bare name is treated as an SHX name without `.shx`. +pub fn is_shx_name(name: &str) -> bool { + let name = name.trim(); + if name.is_empty() || name.eq_ignore_ascii_case(BUILTIN_FONT) { + return false; + } + let file = name.rsplit(['/', '\\']).next().unwrap_or(name); + if let Some((_, extension)) = file.rsplit_once('.') { + return extension.eq_ignore_ascii_case("shx"); + } + ttf::find(name).is_none() +} + /// One laid-out run of text: strokes in local coordinates (baseline at y = 0, x from 0). #[derive(Clone, Debug, Default, PartialEq)] pub struct Run { diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 67cf592e1..dc42ec714 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -37,6 +37,8 @@ use skrifa::{FontRef, GlyphId, MetadataProvider}; use crate::{Run, Shaped}; +mod list; +pub use list::{FontEntry, installed_fonts}; #[cfg(not(target_arch = "wasm32"))] mod dirs; @@ -320,6 +322,7 @@ struct Fallback { } /// Where a font file's bytes come from. +#[derive(Clone)] enum Source { /// An installed font file, read on first use. File(PathBuf), diff --git a/crates/fonts/src/ttf/list.rs b/crates/fonts/src/ttf/list.rs new file mode 100644 index 000000000..26f30abb1 --- /dev/null +++ b/crates/fonts/src/ttf/list.rs @@ -0,0 +1,288 @@ +//! The installed and registered fonts by family and style, as a font picker lists them. Only +//! each file's table directory and naming table are read, so listing every installed font is +//! cheap; the installed fonts are listed once per process. + +use std::io::{Read, Seek, SeekFrom}; +use std::sync::{Arc, OnceLock}; + +use skrifa::FontRef; +use skrifa::raw::tables::name::{Name, NameId}; +use skrifa::raw::types::Tag; +use skrifa::raw::{FontData, FontRead}; + +use super::{Source, lock}; + +/// A font face a text style can name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FontEntry { + /// The family ("Arial"): the typographic family when the font names one. + pub family: String, + /// The style within the family ("Regular", "Bold Italic"). + pub style: String, + /// What a text style stores to use this face: its file name ("arialbd.ttf"). + pub file: String, +} + +/// Faces listed at most, and the longest family or style name kept. +const MAX_ENTRIES: usize = 5000; +const MAX_NAME_CHARS: usize = 128; +/// Bounds on what is read of one file: table records, and the naming table's size. +const MAX_TABLES: usize = 512; +const MAX_NAME_TABLE: usize = 1 << 20; + +/// Every installed or registered font face (the first face of a collection), by family then +/// style (Regular, Italic, Bold, Bold Italic, then the rest by name). Fonts without a usable +/// naming table are left out. +pub fn installed_fonts() -> Vec { + static INSTALLED: OnceLock> = OnceLock::new(); + // Registered fonts (web builds, tests) have no file; installed files loaded so far are + // listed from their paths. + let registered: Vec<(String, Arc>)> = { + let g = lock(); + g.files.iter().filter(|(k, _)| !g.paths.contains_key(*k)).map(|(k, b)| (k.clone(), b.clone())).collect() + }; + let installed = INSTALLED.get_or_init(|| { + let paths: Vec<(String, Source)> = lock().paths.iter().map(|(k, s)| (k.clone(), s.clone())).collect(); + let mut out = Vec::new(); + for (stem, source) in paths { + let entry = match source { + Source::File(path) => file_names(&path).map(|(family, style)| { + let file = path.file_name().map(|f| f.to_string_lossy().to_ascii_lowercase()).unwrap_or_else(|| format!("{stem}.ttf")); + FontEntry { family, style, file } + }), + Source::Static(bytes) => memory_names(bytes).map(|(family, style)| FontEntry { family, style, file: format!("{stem}.ttf") }), + }; + out.extend(entry); + if out.len() >= MAX_ENTRIES { + break; + } + } + out + }); + let mut all = installed.clone(); + for (stem, bytes) in registered { + if let Some((family, style)) = memory_names(&bytes) { + all.push(FontEntry { family, style, file: format!("{stem}.ttf") }); + } + } + sorted(all) +} + +/// `entries` sorted, one per family and style (the first file listed wins). +fn sorted(mut entries: Vec) -> Vec { + entries.sort_by(|a, b| { + a.family.to_lowercase().cmp(&b.family.to_lowercase()).then(style_rank(&a.style).cmp(&style_rank(&b.style))).then(a.file.cmp(&b.file)) + }); + entries.dedup_by(|a, b| a.family.eq_ignore_ascii_case(&b.family) && a.style.eq_ignore_ascii_case(&b.style)); + entries.truncate(MAX_ENTRIES); + entries +} + +/// Regular, Italic, Bold and Bold Italic first, as AutoCAD's Font Style list has them. +fn style_rank(style: &str) -> (usize, String) { + let s = style.to_lowercase(); + let rank = ["regular", "italic", "bold", "bold italic"].iter().position(|r| *r == s).unwrap_or(4); + (rank, s) +} + +/// (family, style) of a font file's first face, reading only its table directory and naming +/// table. +fn file_names(path: &std::path::Path) -> Option<(String, String)> { + let mut f = std::fs::File::open(path).ok()?; + let mut read = |offset: u64, len: usize| -> Option> { + f.seek(SeekFrom::Start(offset)).ok()?; + let mut buf = vec![0u8; len]; + f.read_exact(&mut buf).ok()?; + Some(buf) + }; + names_from(&mut read) +} + +/// (family, style) of the first face of font bytes held in memory. +fn memory_names(bytes: &[u8]) -> Option<(String, String)> { + let font = FontRef::from_index(bytes, 0).ok()?; + let data = font.table_data(Tag::new(b"name"))?; + family_and_style(data.as_bytes()) +} + +/// (family, style) of the first face of a font file read through `read(offset, len)`: the sfnt +/// or collection header, the table records, then the naming table. +pub(super) fn names_from(read: &mut dyn FnMut(u64, usize) -> Option>) -> Option<(String, String)> { + let head = read(0, 12)?; + let mut face = 0u64; + if head.get(0..4)? == b"ttcf" { + // A collection: the offset of its first face's table directory. + let first = read(12, 4)?; + face = u64::from(be32(&first, 0)?); + } + let dir = if face == 0 { head } else { read(face, 12)? }; + let tables = usize::from(be16(&dir, 4)?).min(MAX_TABLES); + let records = read(face + 12, tables * 16)?; + let (offset, len) = (0..tables).find_map(|i| { + let r = records.get(i * 16..i * 16 + 16)?; + (r.get(0..4)? == b"name").then(|| Some((be32(r, 8)?, be32(r, 12)?)))? + })?; + let len = usize::try_from(len).ok().filter(|l| *l > 0 && *l <= MAX_NAME_TABLE)?; + family_and_style(&read(u64::from(offset), len)?) +} + +fn be16(b: &[u8], at: usize) -> Option { + Some(u16::from_be_bytes(b.get(at..at + 2)?.try_into().ok()?)) +} + +fn be32(b: &[u8], at: usize) -> Option { + Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?)) +} + +/// The family and style a naming table gives: the typographic family and subfamily (IDs 16, 17) +/// when present, else the family and subfamily (IDs 1, 2); English names preferred. +fn family_and_style(table: &[u8]) -> Option<(String, String)> { + let name = Name::read(FontData::new(table)).ok()?; + let data = name.string_data(); + // Lower is better: Windows English, other Windows, Mac English, Unicode, anything else. + let rank = |platform: u16, language: u16| match (platform, language) { + (3, 0x0409) => 0, + (3, _) => 1, + (1, 0) => 2, + (0, _) => 3, + _ => 4, + }; + let best = |id: NameId| -> Option { + let mut found: Option<(u8, String)> = None; + for r in name.name_record().iter().filter(|r| r.name_id() == id) { + let rk = rank(r.platform_id(), r.language_id()); + if found.as_ref().is_some_and(|(k, _)| *k <= rk) { + continue; + } + let Ok(s) = r.string(data) else { continue }; + let s: String = s.chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect(); + let s = s.trim().to_string(); + if !s.is_empty() { + found = Some((rk, s)); + } + } + found.map(|(_, s)| s) + }; + let family = best(NameId::TYPOGRAPHIC_FAMILY_NAME).or_else(|| best(NameId::FAMILY_NAME))?; + let style = best(NameId::TYPOGRAPHIC_SUBFAMILY_NAME).or_else(|| best(NameId::SUBFAMILY_NAME)).unwrap_or_else(|| "Regular".into()); + Some((family, style)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn be16v(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_be_bytes()); + } + + /// A naming table with Windows English records (platform 3, encoding 1, UTF-16BE). + pub(crate) fn name_table(records: &[(u16, &str)]) -> Vec { + let mut strings = Vec::new(); + let mut recs = Vec::new(); + for (id, s) in records { + let bytes: Vec = s.encode_utf16().flat_map(u16::to_be_bytes).collect(); + for v in [3u16, 1, 0x0409, *id, bytes.len() as u16, strings.len() as u16] { + be16v(&mut recs, v); + } + strings.extend(bytes); + } + let mut t = Vec::new(); + for v in [0u16, records.len() as u16, (6 + recs.len()) as u16] { + be16v(&mut t, v); + } + t.extend(recs); + t.extend(strings); + t + } + + /// An sfnt with only a naming table, or a collection of one such face. + pub(crate) fn font_with_names(records: &[(u16, &str)], collection: bool) -> Vec { + let name = name_table(records); + let base = if collection { 16u32 } else { 0 }; + let mut out = Vec::new(); + if collection { + out.extend_from_slice(b"ttcf"); + out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + out.extend_from_slice(&1u32.to_be_bytes()); + out.extend_from_slice(&base.to_be_bytes()); + } + out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + for v in [1u16, 16, 0, 0] { + be16v(&mut out, v); + } + out.extend_from_slice(b"name"); + out.extend_from_slice(&0u32.to_be_bytes()); + out.extend_from_slice(&(base + 28).to_be_bytes()); + out.extend_from_slice(&(name.len() as u32).to_be_bytes()); + out.extend(name); + out + } + + fn read_from(bytes: &[u8]) -> impl FnMut(u64, usize) -> Option> + '_ { + |offset, len| { + let start = usize::try_from(offset).ok()?; + bytes.get(start..start.checked_add(len)?).map(<[u8]>::to_vec) + } + } + + #[test] + fn families_and_styles_come_from_the_naming_table() { + let plain = font_with_names(&[(1, "Test Sans Semibold"), (2, "Regular"), (16, "Test Sans"), (17, "Semibold")], false); + assert_eq!(names_from(&mut read_from(&plain)), Some(("Test Sans".into(), "Semibold".into())), "typographic names first"); + let old = font_with_names(&[(1, "Old Face"), (2, "Bold Italic")], true); + assert_eq!(names_from(&mut read_from(&old)), Some(("Old Face".into(), "Bold Italic".into())), "a collection's first face"); + assert_eq!(memory_names(&font_with_names(&[(1, "In Memory")], false)), Some(("In Memory".into(), "Regular".into()))); + assert_eq!(names_from(&mut read_from(&font_with_names(&[(2, "Bold")], false))), None, "no family"); + } + + #[test] + fn styles_sort_as_autocad_lists_them() { + let e = |family: &str, style: &str, file: &str| FontEntry { family: family.into(), style: style.into(), file: file.into() }; + let got = sorted(vec![ + e("b", "Bold", "bb.ttf"), + e("B", "Light", "bl.ttf"), + e("b", "Regular", "b.ttf"), + e("a", "Regular", "a.ttf"), + e("b", "Bold Italic", "bz.ttf"), + e("B", "regular", "copy.ttf"), + e("b", "Italic", "bi.ttf"), + ]); + let order: Vec<&str> = got.iter().map(|e| e.file.as_str()).collect(); + assert_eq!(order, ["a.ttf", "b.ttf", "bi.ttf", "bb.ttf", "bz.ttf", "bl.ttf"]); + } + + #[test] + fn hostile_font_files_never_panic() { + let good = font_with_names(&[(1, "Fine")], true); + let mut cases: Vec> = vec![Vec::new(), b"ttcf".to_vec(), vec![0xFF; 12], vec![0; 40]]; + for cut in [3, 12, 15, 20, 30, 40, good.len() - 1] { + cases.push(good[..cut.min(good.len())].to_vec()); + } + // A huge table count, a name table past the end, an absurd length. + let mut many = good.clone(); + many[20..22].copy_from_slice(&u16::MAX.to_be_bytes()); + cases.push(many); + let mut far = good.clone(); + far[36..40].copy_from_slice(&u32::MAX.to_be_bytes()); + cases.push(far); + let mut long = good.clone(); + long[40..44].copy_from_slice(&u32::MAX.to_be_bytes()); + cases.push(long); + let mut seed = 0x9E37_79B9u32; + for _ in 0..200 { + let mut b = good.clone(); + for _ in 0..4 { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let i = seed as usize % b.len(); + b[i] = (seed >> 24) as u8; + } + cases.push(b); + } + for c in &cases { + let _ = names_from(&mut read_from(c)); + let _ = memory_names(c); + let _ = family_and_style(c); + } + } +} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e83ee1574..a69105e6f 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -185,6 +185,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "layers", "bedit", "palettes", + "managers/textstyle", "managers/dimstyle", "parametric", "quick", diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 15607f953..2a509c96e 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -411,6 +411,7 @@ List 列表 List Blocks 列出块 List Dimension Styles 列出标注样式 + List Fonts 列出字体 List Groups 列出编组 List Layer States 列出图层状态 List Layouts 列出布局 @@ -925,6 +926,7 @@ Text 文字 Text Editor 文字编辑器 Text Height 文字高度 + Text Style 文字样式 Text Style... 文字样式... Text height 文字高度 Text override 文字替代 diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fdce8b3ff..ed518fae3 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -116,6 +116,8 @@ pub enum Icon { QuickProps, Gear, Annotation, + /// An annotative style or object: a drafting set square. + Annotative, Workspace, ChevronDown, ChevronUp, @@ -815,7 +817,7 @@ fn paint_layer_tools(pen: &Pen<'_>, icon: Icon, _b: Color32, _a: Color32, dim: b } } -fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, _a: Color32, dim: bool) { +fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, dim: bool) { let alpha = |c: Color32| if dim { c.gamma_multiply(0.4) } else { c }; use Icon::*; match icon { @@ -924,6 +926,10 @@ fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, _a: Color32, dim pen.l(12.0, 9.0, 12.0, 15.0); pen.fill_c(12.0, 17.5, 1.0, b); } + Annotative => { + pen.poly(&[(4.0, 3.0), (4.0, 20.0), (21.0, 20.0)], true, b); + pen.poly(&[(7.5, 10.5), (7.5, 16.5), (13.5, 16.5)], true, a); + } Workspace => { pen.rect(3.0, 4.0, 18.0, 16.0, b); pen.l(9.0, 4.0, 9.0, 20.0); diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 0a5884889..31421e1c5 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -21,6 +21,8 @@ mod battman; mod dimstyle; /// Named Viewports (View > Viewports > Named Viewports...). mod named_vports; +/// The Text Style dialog (STYLE). +mod textstyle; /// Open the dialog for a typed or menu-invoked command. `None` if `id` has no dialog here or the /// call carries parameters. @@ -55,7 +57,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool "battman" => battman::dialog(app, ctx, open), "linetype" => linetype(app, ctx, open), "ptype" => point_style(app, ctx, open), - "textstyle" => text_style(app, ctx, open), + "textstyle" => textstyle::dialog(app, ctx, open), "dimstyle" => dimstyle::dialog(app, ctx, open), "tablestyle" => table_style(app, ctx, open), "mleaderstyle" => mleader_style(app, ctx, open), @@ -351,32 +353,6 @@ struct Style { fields: Vec, } -fn text_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { - let Ok(d) = app.session.doc() else { - no_drawing(ctx, "Text Style", open); - return None; - }; - let mut styles: Vec