mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 20:22:15 -05:00
Merge pull request #3539 from 2ez4gcx/fix/style-name-lookups
fix(doc, io): look linetypes, text and dimension styles and layouts up by name through an index, so crafted files don't open or draw in quadratic time
This commit is contained in:
22 files changed
+278
-69
No files matched your search
+22
-14
@@ -105,9 +105,12 @@ pub struct Drawing {
|
||||
pub foreign: std::sync::Arc<foreign::Foreign>,
|
||||
/// Layers in table order; [`Drawing::layer`] looks them up by name.
|
||||
pub layers: NamedList<Layer>,
|
||||
pub linetypes: Vec<Linetype>,
|
||||
pub text_styles: Vec<TextStyle>,
|
||||
pub dim_styles: Vec<DimStyle>,
|
||||
/// Linetypes in table order; [`Drawing::linetype`] looks them up by name.
|
||||
pub linetypes: NamedList<Linetype>,
|
||||
/// Text styles in table order; [`Drawing::text_style`] looks them up by name.
|
||||
pub text_styles: NamedList<TextStyle>,
|
||||
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
|
||||
pub dim_styles: NamedList<DimStyle>,
|
||||
pub mleader_styles: Vec<MLeaderStyle>,
|
||||
pub table_styles: Vec<TableStyle>,
|
||||
/// Multiline styles (MLSTYLE); STANDARD is always there.
|
||||
@@ -117,7 +120,8 @@ pub struct Drawing {
|
||||
pub model: EntityStore,
|
||||
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
|
||||
pub model_page: Option<PageSetup>,
|
||||
pub layouts: Vec<Layout>,
|
||||
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
|
||||
pub layouts: NamedList<Layout>,
|
||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
|
||||
pub active_layout: Option<String>,
|
||||
@@ -204,16 +208,17 @@ impl Drawing {
|
||||
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
|
||||
Linetype::continuous(),
|
||||
],
|
||||
text_styles: vec![TextStyle::default()],
|
||||
dim_styles: vec![DimStyle::default()],
|
||||
]
|
||||
.into(),
|
||||
text_styles: vec![TextStyle::default()].into(),
|
||||
dim_styles: vec![DimStyle::default()].into(),
|
||||
mleader_styles: vec![MLeaderStyle::default()],
|
||||
table_styles: vec![TableStyle::default()],
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: NamedMap::default(),
|
||||
model: EntityStore::new(),
|
||||
model_page: None,
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
|
||||
active_layout: None,
|
||||
views: Vec::new(),
|
||||
vports: Vec::new(),
|
||||
@@ -323,17 +328,19 @@ impl Drawing {
|
||||
}
|
||||
/// The first layer named `name`, without case, to change.
|
||||
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
|
||||
let i = self.layers.position_by_name(name)?;
|
||||
self.layers.get_mut(i)
|
||||
self.layers.by_name_mut(name)
|
||||
}
|
||||
/// The first linetype named `name`, without case.
|
||||
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
|
||||
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.linetypes.by_name(name)
|
||||
}
|
||||
/// The first text style named `name`, without case.
|
||||
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
|
||||
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.text_styles.by_name(name)
|
||||
}
|
||||
/// The first dimension style named `name`, without case.
|
||||
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
|
||||
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.dim_styles.by_name(name)
|
||||
}
|
||||
|
||||
/// The DIM* variables in the header that differ from the current dimension style, as
|
||||
@@ -405,8 +412,9 @@ impl Drawing {
|
||||
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
|
||||
self.blocks.by_name(name)
|
||||
}
|
||||
/// The first layout named `name`, without case.
|
||||
pub fn layout(&self, name: &str) -> Option<&Layout> {
|
||||
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
|
||||
self.layouts.by_name(name)
|
||||
}
|
||||
|
||||
/// Add a layer if missing; returns whether it was created.
|
||||
|
||||
+86
-14
@@ -1,10 +1,12 @@
|
||||
//! The layer and block tables, whose names are looked up without case through an index instead of a
|
||||
//! scan once a table is large and looked up often.
|
||||
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
|
||||
//! and layouts), whose names are looked up without case through an index instead of a scan once a
|
||||
//! table is large and looked up often.
|
||||
//!
|
||||
//! [`Drawing::layer`](crate::Drawing::layer) and [`Drawing::block`](crate::Drawing::block) run for
|
||||
//! every entity while a drawing is read, measured and drawn. Scanning the table on each made a file
|
||||
//! of N layers, or of N blocks and N references to blocks it does not have, cost N² name
|
||||
//! comparisons: tens of seconds to open at a few tens of thousands (#1924, F-04).
|
||||
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
|
||||
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
|
||||
//! every layout is looked up on each change. Scanning the table on each made a file of N layers,
|
||||
//! or of N blocks, linetypes or styles and N objects naming ones it does not have, cost N² name
|
||||
//! comparisons: tens of seconds to open or draw at a few tens of thousands (#1924, F-04).
|
||||
//!
|
||||
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
|
||||
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
|
||||
@@ -105,14 +107,21 @@ pub trait Named {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
impl Named for crate::Layer {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
/// Entries named by their `name` field.
|
||||
macro_rules! named_by_field {
|
||||
($($t:ty),*) => {$(
|
||||
impl Named for $t {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
|
||||
|
||||
/// A list of named entries in their own order (the drawing's layers). It reads and changes as a
|
||||
/// `Vec`; [`NamedList::by_name`] finds the first entry of a name without case.
|
||||
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
|
||||
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
|
||||
/// first entry of a name without case.
|
||||
pub struct NamedList<T> {
|
||||
list: Vec<T>,
|
||||
index: Lazy<usize>,
|
||||
@@ -131,6 +140,12 @@ impl<T: Named> NamedList<T> {
|
||||
pub fn by_name(&self, name: &str) -> Option<&T> {
|
||||
self.position_by_name(name).and_then(|i| self.list.get(i))
|
||||
}
|
||||
|
||||
/// The first entry named `name`, without case, to change (which drops the index).
|
||||
pub fn by_name_mut(&mut self, name: &str) -> Option<&mut T> {
|
||||
let i = self.position_by_name(name)?;
|
||||
self.get_mut(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for NamedList<T> {
|
||||
@@ -318,8 +333,8 @@ impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::MIN_INDEXED;
|
||||
use crate::{Block, Drawing, Layer};
|
||||
use super::{MIN_INDEXED, Named, NamedList};
|
||||
use crate::{Block, DimStyle, Drawing, Layer, Layout, Linetype, TextStyle};
|
||||
|
||||
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
|
||||
/// added (a miss).
|
||||
@@ -331,6 +346,63 @@ mod tests {
|
||||
d.layers.index.index.get().is_some()
|
||||
}
|
||||
|
||||
fn indexed<T>(list: &NamedList<T>) -> bool {
|
||||
list.index.index.get().is_some()
|
||||
}
|
||||
|
||||
/// Every lookup through `find` finds what a scan of `list` in table order finds (the first of a
|
||||
/// name without case), by pointer, for the list's names and `extra`.
|
||||
fn check_list<'a, T: Named>(list: &'a NamedList<T>, find: impl Fn(&str) -> Option<&'a T>, extra: &[&str]) {
|
||||
let names: Vec<String> = list.iter().map(|t| t.name().to_string()).collect();
|
||||
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
|
||||
let want = list.iter().find(|t| t.name().eq_ignore_ascii_case(&p)).map(std::ptr::from_ref);
|
||||
assert_eq!(find(&p).map(std::ptr::from_ref), want, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The linetype, text style, dimension style and layout lookups each find what a scan in table
|
||||
/// order finds (the first of a name without case): while they scan, once the table is indexed,
|
||||
/// and after `by_name_mut` (RENAME, STYLE, DIMSTYLE, a .lin file reloaded, a layout's UCS)
|
||||
/// changed the first of a name and dropped the index.
|
||||
#[test]
|
||||
fn linetype_style_and_layout_lookups_find_the_first_of_a_name() {
|
||||
let names: Vec<String> = (0..150).map(|i| format!("N{i}")).chain(["n7", "Dash", "DASH"].map(String::from)).collect();
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = names.iter().map(|n| Linetype::simple(n, "", &[0.5, -0.25])).collect();
|
||||
d.text_styles = names.iter().map(|n| TextStyle { name: n.clone(), ..TextStyle::default() }).collect();
|
||||
d.dim_styles = names.iter().map(|n| DimStyle { name: n.clone(), ..DimStyle::default() }).collect();
|
||||
d.layouts = names.iter().zip(1..).map(|(n, tab)| Layout::new(n, tab)).collect();
|
||||
let check = |d: &Drawing, extra: &[&str]| {
|
||||
check_list(&d.linetypes, |n| d.linetype(n), extra);
|
||||
check_list(&d.text_styles, |n| d.text_style(n), extra);
|
||||
check_list(&d.dim_styles, |n| d.dim_style(n), extra);
|
||||
check_list(&d.layouts, |n| d.layout(n), extra);
|
||||
};
|
||||
let all_indexed = |d: &Drawing| indexed(&d.linetypes) && indexed(&d.text_styles) && indexed(&d.dim_styles) && indexed(&d.layouts);
|
||||
// The first round scans until the index is built; the second reads only the index.
|
||||
check(&d, &["dash", "missing"]);
|
||||
assert!(all_indexed(&d));
|
||||
check(&d, &["dash", "missing"]);
|
||||
|
||||
// The first of a name changes, and the later one of that name is found after it.
|
||||
d.linetypes.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.text_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.dim_styles.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
d.layouts.by_name_mut("n7").unwrap().name = "Seven".into();
|
||||
assert!(!indexed(&d.linetypes) && !indexed(&d.text_styles) && !indexed(&d.dim_styles) && !indexed(&d.layouts));
|
||||
assert_eq!(d.linetype("N7").map(|l| l.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.text_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.dim_style("N7").map(|s| s.name.as_str()), Some("n7"));
|
||||
assert_eq!(d.layout("N7").map(|l| (l.name.as_str(), l.tab_order)), Some(("n7", 151)));
|
||||
assert_eq!(d.linetypes.get(7).map(|l| l.name.as_str()), Some("Seven"));
|
||||
check(&d, &["SEVEN", "n7"]);
|
||||
assert!(all_indexed(&d));
|
||||
// A miss changes nothing and keeps the index.
|
||||
assert!(d.dim_styles.by_name_mut("none").is_none());
|
||||
assert!(indexed(&d.dim_styles));
|
||||
check(&d, &["dash"]);
|
||||
}
|
||||
|
||||
fn blocks_indexed(d: &Drawing) -> bool {
|
||||
d.blocks.index.index.get().is_some()
|
||||
}
|
||||
|
||||
@@ -988,3 +988,60 @@ fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
/// Table entries for the cost tests below.
|
||||
const NAMED: usize = 40_000;
|
||||
|
||||
/// A name of 54 bytes whose first 48 every such name of `kind` shares, so comparing two costs
|
||||
/// about 50 bytes and not a length check, as in a crafted file.
|
||||
fn long_name(kind: &str, tail: &str) -> String {
|
||||
format!("{kind}{}{tail}", "x".repeat(48 - kind.len()))
|
||||
}
|
||||
|
||||
/// The [`NAMED`] names `long_name(kind, "000000")`, `..."000001"`, ...
|
||||
fn long_names(kind: &str) -> impl Iterator<Item = String> + '_ {
|
||||
(0..NAMED).map(move |i| long_name(kind, &format!("{i:06}")))
|
||||
}
|
||||
|
||||
/// Each of a table's [`NAMED`] names is looked up in other case (found) and as a missing name of
|
||||
/// the same length, well within a bound that scanning the table for each lookup misses: a file of
|
||||
/// N entries and N objects naming one it lacks, or names in other case, drew in N² name
|
||||
/// comparisons (#1924).
|
||||
fn lookups_by_name_are_quick(kind: &str, found: impl Fn(&str) -> bool) {
|
||||
let started = std::time::Instant::now();
|
||||
for i in 0..NAMED {
|
||||
assert!(found(&long_name(kind, &format!("{i:06}")).to_ascii_uppercase()), "{kind} {i}");
|
||||
assert!(!found(&long_name(kind, &format!("z{i:05}"))), "{kind} {i}");
|
||||
}
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetype_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.linetypes = long_names("LT").map(|n| Linetype::simple(&n, "", &[0.5, -0.25])).collect();
|
||||
lookups_by_name_are_quick("LT", |n| d.linetype(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.text_styles = long_names("S").map(|name| TextStyle { name, ..TextStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("S", |n| d.text_style(n).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_style_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.dim_styles = long_names("D").map(|name| DimStyle { name, ..DimStyle::default() }).collect();
|
||||
lookups_by_name_are_quick("D", |n| d.dim_style(n).is_some());
|
||||
}
|
||||
|
||||
/// Each change to a drawing looks up every layout of the drawing before it by name (the check for
|
||||
/// non-finite results), so a drawing of N layouts cost N² name comparisons per command.
|
||||
#[test]
|
||||
fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
|
||||
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
|
||||
}
|
||||
@@ -266,9 +266,9 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header = src.header.clone();
|
||||
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
|
||||
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name).into();
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
|
||||
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
|
||||
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
|
||||
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
|
||||
|
||||
@@ -129,7 +129,7 @@ fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) ->
|
||||
if let Some(a) = annotative {
|
||||
st.annotative = a;
|
||||
}
|
||||
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
let name = match d.dim_styles.by_name_mut(&name) {
|
||||
Some(existing) if replace => {
|
||||
let kept = existing.name.clone();
|
||||
*existing = DimStyle { name: kept.clone(), ..st };
|
||||
|
||||
@@ -455,15 +455,9 @@ fn tinted_dim_style(d: &mut Drawing, name: &str, color: Color, tinted: &mut Tint
|
||||
if let Some(n) = tinted.names.get(&key) {
|
||||
return Some(n.clone());
|
||||
}
|
||||
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))?.clone();
|
||||
let st = d.dim_style(name)?.clone();
|
||||
let base = format!("COMPARE_{}_{}", tag(color), st.name);
|
||||
let new = tinted.next.find(
|
||||
"dimension style",
|
||||
&base,
|
||||
d.dim_styles.len(),
|
||||
|i| suffixed(&base, i),
|
||||
|n| d.dim_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n)),
|
||||
);
|
||||
let new = tinted.next.find("dimension style", &base, d.dim_styles.len(), |i| suffixed(&base, i), |n| d.dim_style(n).is_some());
|
||||
d.dim_styles.push(DimStyle {
|
||||
name: new.clone(),
|
||||
dim_line_color: Color::ByBlock,
|
||||
|
||||
@@ -62,8 +62,7 @@ impl Scope {
|
||||
Some(_) => {
|
||||
let name = given.unwrap_or_default();
|
||||
let d = s.doc()?;
|
||||
let l =
|
||||
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
|
||||
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
|
||||
Ok(Scope::Space(Space::Paper(l.name.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,7 +449,7 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc_mut()?;
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.text_style(&name).cloned();
|
||||
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
let idx = match d.text_styles.position_by_name(&name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
d.text_styles.push(cadcraft_doc::TextStyle { name: name.clone(), ..Default::default() });
|
||||
@@ -554,7 +554,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.text_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("style.rename", format!("a text style `{to}` already exists")));
|
||||
}
|
||||
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("style.rename", "no such style"))?;
|
||||
let st = d.text_styles.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
|
||||
st.name = to.clone();
|
||||
// References follow the new name.
|
||||
let fix = |n: &mut String| {
|
||||
@@ -642,7 +642,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.dim_style(&name).cloned();
|
||||
let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default();
|
||||
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
let idx = match d.dim_styles.position_by_name(&name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
d.dim_styles.push(cadcraft_doc::DimStyle { name: name.clone(), ..base });
|
||||
@@ -792,7 +792,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.dim_style(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("dimstyle.rename", format!("a dimension style `{to}` already exists")));
|
||||
}
|
||||
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
|
||||
let st = d.dim_styles.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
|
||||
st.name = to.clone();
|
||||
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
|
||||
d.header.set_str("DIMSTYLE", &to);
|
||||
@@ -1015,7 +1015,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if d.linetype(&to).is_some() && !to.eq_ignore_ascii_case(&from) {
|
||||
return Err(bad("rename", format!("a linetype `{to}` already exists")));
|
||||
}
|
||||
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
|
||||
let st = d.linetypes.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
|
||||
st.name = to.clone();
|
||||
// References follow the new name.
|
||||
let fix = |n: &mut String| {
|
||||
|
||||
@@ -59,7 +59,7 @@ fn put(d: &mut Drawing, lt: Linetype, reload: bool, out: &mut Loaded) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match d.linetypes.iter_mut().find(|l| l.name.eq_ignore_ascii_case(<.name)) {
|
||||
match d.linetypes.by_name_mut(<.name) {
|
||||
Some(old) if reload => {
|
||||
out.reloaded.push(old.name.clone());
|
||||
// The drawing keeps the name as it had it (objects refer to it).
|
||||
|
||||
@@ -162,7 +162,7 @@ impl SpatialIndex {
|
||||
SpatialIndex {
|
||||
store: store.clone(),
|
||||
blocks: (*d.blocks).clone(),
|
||||
dim_styles: d.dim_styles.clone(),
|
||||
dim_styles: d.dim_styles.to_vec(),
|
||||
dimscale: d.header.f64("DIMSCALE", 1.0),
|
||||
anno: anno_key(d),
|
||||
hidden_layers: hidden_layers(d).map(str::to_owned).collect(),
|
||||
@@ -178,7 +178,7 @@ impl SpatialIndex {
|
||||
self.blocks.len() == d.blocks.len()
|
||||
&& self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b))
|
||||
&& self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits()
|
||||
&& self.dim_styles == d.dim_styles
|
||||
&& self.dim_styles == *d.dim_styles
|
||||
&& self.anno == anno_key(d)
|
||||
&& self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d))
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
|
||||
h.set_str("UCSNAME", name);
|
||||
}
|
||||
Space::Paper(layout) => {
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) {
|
||||
if let Some(l) = d.layouts.by_name_mut(layout) {
|
||||
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,7 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str)
|
||||
fn previous_mut<'a>(d: &'a mut Drawing, space: &Space) -> Option<&'a mut Vec<Ucs>> {
|
||||
match space {
|
||||
Space::Model => Some(&mut d.ucs_previous),
|
||||
Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous),
|
||||
Space::Paper(layout) => d.layouts.by_name_mut(layout).map(|l| &mut l.ucs_previous),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -251,10 +251,23 @@ impl LayerSet {
|
||||
}
|
||||
}
|
||||
|
||||
/// The position of the first layout of each name, so finding the layout of each of many objects
|
||||
/// is a map lookup rather than a scan of the layouts: a file of N layouts and N objects in the
|
||||
/// last of them read in N² name comparisons (#1924). The reader keeps the layouts' names and order
|
||||
/// while it fills them.
|
||||
pub(super) fn layout_positions(d: &Drawing) -> std::collections::BTreeMap<String, usize> {
|
||||
let mut at = std::collections::BTreeMap::new();
|
||||
for (i, l) in d.layouts.iter().enumerate() {
|
||||
at.entry(l.name.clone()).or_insert(i);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// Place the BLOCKS entities: model and paper space blocks go to their space, the rest become
|
||||
/// block definitions.
|
||||
pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx, paper_block_for: &HashMap<String, String>, first_layout: &str) {
|
||||
let mut layers = LayerSet::new(d);
|
||||
let layout_at = layout_positions(d);
|
||||
for (name, base, description, ents, xref) in blocks {
|
||||
let up = name.to_ascii_uppercase();
|
||||
if up == "*MODEL_SPACE" {
|
||||
@@ -265,8 +278,8 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec<BlockDef>, rx: &mut Rx,
|
||||
continue;
|
||||
}
|
||||
if up.starts_with("*PAPER_SPACE") {
|
||||
let lname = paper_block_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string());
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
|
||||
let lname = paper_block_for.get(&up).map_or(first_layout, String::as_str);
|
||||
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
for (_, _, e) in ents {
|
||||
l.entities.push(e);
|
||||
}
|
||||
@@ -324,11 +337,12 @@ pub(super) fn place_entities(
|
||||
first_layout: &str,
|
||||
) {
|
||||
let mut layers = LayerSet::new(d);
|
||||
let layout_at = layout_positions(d);
|
||||
for (owner, paper, e) in entities {
|
||||
layers.ensure(d, &e.common.layer);
|
||||
match paper_layout(owner, paper, rx, paper_block_for, first_layout) {
|
||||
Some(lname) => {
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
|
||||
if let Some(l) = layout_at.get(&lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.entities.push(e);
|
||||
}
|
||||
}
|
||||
@@ -417,6 +431,7 @@ pub(super) fn apply_sortents(
|
||||
Some(if up.starts_with("*PAPER_SPACE") { paper_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string()) + "\0paper" } else { up })
|
||||
};
|
||||
let last: HashMap<String, usize> = tables.iter().enumerate().filter_map(|(i, (owner, _))| Some((target(owner)?, i))).collect();
|
||||
let layout_at = layout_positions(d);
|
||||
for (i, (owner, map)) in tables.iter().enumerate() {
|
||||
if target(owner).and_then(|t| last.get(&t)) != Some(&i) {
|
||||
continue;
|
||||
@@ -432,7 +447,7 @@ pub(super) fn apply_sortents(
|
||||
d.model.sort_by_key(key);
|
||||
} else if up.starts_with("*PAPER_SPACE") {
|
||||
let lname = paper_for.get(&up).map(String::as_str).unwrap_or(first_layout);
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
|
||||
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.entities.sort_by_key(key);
|
||||
}
|
||||
} else if let Some(b) = d.blocks.get_mut(name.as_str()) {
|
||||
|
||||
@@ -195,6 +195,7 @@ impl Objects {
|
||||
|
||||
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
|
||||
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
|
||||
let layout_at = super::document::layout_positions(d);
|
||||
for (name, origin, x, y, named) in &self.layout_ucss {
|
||||
let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y);
|
||||
// The named UCS group 345 points at, only while the layout's frame is still that
|
||||
@@ -209,7 +210,7 @@ impl Objects {
|
||||
if !usable || (world && ucs_name.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
|
||||
if let Some(l) = layout_at.get(name).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.ucs = Some(Ucs { name: ucs_name, origin: *origin, x_axis: *x, y_axis: *y });
|
||||
}
|
||||
}
|
||||
@@ -348,8 +349,9 @@ impl Objects {
|
||||
}
|
||||
self.apply_mleader_styles(d, rx);
|
||||
crate::dxf_mleader::apply(d, &rx.mleader_fix, &self.names);
|
||||
let layout_at = super::document::layout_positions(d);
|
||||
for (name, view) in &self.layout_views {
|
||||
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) {
|
||||
if let Some(l) = layout_at.get(name).and_then(|&i| d.layouts.get_mut(i)) {
|
||||
l.view = Some(*view);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +114,11 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
// The same for linetypes (first definition wins) and text styles (last definition wins).
|
||||
let mut linetype_names: std::collections::HashSet<String> = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect();
|
||||
let mut style_index: HashMap<String, usize> = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
// And for dimension styles (a later record replaces the first of its name, which keeps its
|
||||
// place); ordered by name rather than hashed, so its cost does not depend on hash keys. Built
|
||||
// in reverse, so the first style of a name is the one kept.
|
||||
let mut dim_style_index: std::collections::BTreeMap<String, usize> =
|
||||
d.dim_styles.iter().enumerate().rev().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
for (kind, tg) in recs {
|
||||
let t = T(tg);
|
||||
match kind.as_str() {
|
||||
@@ -280,9 +285,12 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
fields.extend(crate::dxf_ext::read_newer_dimvars(tg, &rx.styles, &rx.brs, &rx.ltypes));
|
||||
let mut st = DimStyle { name: name.clone(), annotative: annotative(tg), ..DimStyle::default() };
|
||||
st.apply_fields(&fields);
|
||||
match d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) {
|
||||
match dim_style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.dim_styles.get_mut(i)) {
|
||||
Some(x) => *x = st,
|
||||
None => d.dim_styles.push(st),
|
||||
None => {
|
||||
dim_style_index.insert(name.to_ascii_lowercase(), d.dim_styles.len());
|
||||
d.dim_styles.push(st);
|
||||
}
|
||||
}
|
||||
}
|
||||
"VPORT" => vport_record(d, &t, false),
|
||||
|
||||
@@ -84,7 +84,7 @@ pub(super) fn model_ucs(d: &Drawing) -> Ucs {
|
||||
/// style are its overrides and are written instead, so they are kept with the drawing (#3100).
|
||||
fn dim_header_vars(w: &mut W, d: &Drawing) {
|
||||
let name = d.header.str("DIMSTYLE", "Standard");
|
||||
let Some(style) = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&name)) else { return };
|
||||
let Some(style) = d.dim_style(&name) else { return };
|
||||
let mut v = serde_json::to_value(style).unwrap_or_default();
|
||||
if let Some(fields) = v.as_object_mut() {
|
||||
fields.extend(d.dim_overrides());
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
|
||||
let d = match (space, margins) {
|
||||
(Space::Paper(n), Some(m)) => {
|
||||
let mut c = d.clone();
|
||||
if let Some(l) = c.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(n)) {
|
||||
if let Some(l) = c.layouts.by_name_mut(n) {
|
||||
l.page.margins_mm = m;
|
||||
}
|
||||
with_margins = c;
|
||||
|
||||
@@ -397,6 +397,60 @@ fn many_distinct_symbol_names_read_quickly() {
|
||||
assert_eq!(d.text_style("ST0").map(|s| s.height), Some(2.0));
|
||||
}
|
||||
|
||||
/// Many distinct dimension style names read in linear time, with the duplicate rule kept: a later
|
||||
/// record of a name in other case replaces the first, which keeps its place and takes the later
|
||||
/// record's name, also the Standard style a drawing starts with (#1924). The names share their
|
||||
/// first 200 bytes, so comparing two costs about that.
|
||||
#[test]
|
||||
fn many_distinct_dimension_style_names_read_quickly() {
|
||||
const N: usize = 20_000;
|
||||
let name = |i: usize| format!("D{}{i:06}", "x".repeat(199));
|
||||
let mut t = String::from("0\nSECTION\n2\nTABLES\n");
|
||||
for i in 0..N {
|
||||
t.push_str(&format!("0\nDIMSTYLE\n2\n{}\n70\n0\n40\n1\n", name(i)));
|
||||
}
|
||||
t.push_str(&format!("0\nDIMSTYLE\n2\n{}\n70\n0\n40\n2\n", name(0).to_ascii_uppercase()));
|
||||
t.push_str("0\nDIMSTYLE\n2\nSTANDARD\n70\n0\n40\n3\n0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "many.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let styles: Vec<(&str, f64)> = d.dim_styles.iter().map(|s| (s.name.as_str(), s.scale)).collect();
|
||||
assert_eq!(styles.len(), N + 1);
|
||||
assert_eq!(styles.first(), Some(&("STANDARD", 3.0)));
|
||||
assert_eq!(styles.get(1), Some(&(name(0).to_ascii_uppercase().as_str(), 2.0)));
|
||||
assert_eq!(styles.get(2), Some(&(name(1).as_str(), 1.0)));
|
||||
}
|
||||
|
||||
/// Many layouts with every paper-space object in one of the last of them read in linear time.
|
||||
/// Each object goes to the first layout of its exact name, as before: not to an earlier one whose
|
||||
/// name differs only in case, nor to a later one of the same name (#1924).
|
||||
#[test]
|
||||
fn many_layouts_read_quickly() {
|
||||
const N: usize = 40_000;
|
||||
let name = |i: usize| format!("L{}{i:06}", "x".repeat(47));
|
||||
let last = name(0).to_ascii_uppercase();
|
||||
// Layout N is the active one (its block record is *Paper_Space): paper-space objects without
|
||||
// an owner go to it. It and layout N + 1 have the first layout's name in other case.
|
||||
let mut t = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nBLOCK_RECORD\n0\nBLOCK_RECORD\n5\n1F\n2\n*Paper_Space\n0\nENDTAB\n0\nENDSEC\n");
|
||||
t.push_str("0\nSECTION\n2\nENTITIES\n");
|
||||
for i in 0..N {
|
||||
t.push_str(&format!("0\nLINE\n8\n0\n67\n1\n10\n{i}\n20\n0\n11\n{i}\n21\n1\n"));
|
||||
}
|
||||
t.push_str("0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n");
|
||||
for i in 0..N + 2 {
|
||||
let (n, owner) = if i < N { (name(i), "0") } else { (last.clone(), if i == N { "1F" } else { "0" }) };
|
||||
t.push_str(&format!("0\nLAYOUT\n5\n{:X}\n100\nAcDbPlotSettings\n100\nAcDbLayout\n1\n{n}\n71\n{}\n330\n{owner}\n", 0x1000 + i, i + 1));
|
||||
}
|
||||
t.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "layouts.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let objects: Vec<(&str, usize)> = d.layouts.iter().map(|l| (l.name.as_str(), l.entities.len())).collect();
|
||||
assert_eq!(objects.len(), N + 2);
|
||||
assert_eq!(objects.first(), Some(&(name(0).as_str(), 0)));
|
||||
assert_eq!(objects.get(N..), Some(&[(last.as_str(), N), (last.as_str(), 0)][..]));
|
||||
}
|
||||
|
||||
/// Elements with many duplicate attributes are read in bounded time.
|
||||
#[test]
|
||||
fn svg_duplicate_attributes_are_not_rescanned() {
|
||||
|
||||
@@ -14,7 +14,7 @@ use cadcraft_io::{SaveOptions, read, write_with};
|
||||
|
||||
fn three_sheets() -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.layouts = vec![Layout::new("S1", 1), Layout::new("S2", 2), Layout::new("S3", 3)];
|
||||
d.layouts = vec![Layout::new("S1", 1), Layout::new("S2", 2), Layout::new("S3", 3)].into();
|
||||
let line = |a: f64| EntityKind::Line(Line { a: Vec3::new(a, 0.0, 0.0), b: Vec3::new(a + 10.0, 10.0, 0.0) });
|
||||
d.add(&Space::Paper("S1".into()), Common::default(), line(0.0)).unwrap();
|
||||
d.add(&Space::Paper("S2".into()), Common::default(), line(20.0)).unwrap();
|
||||
|
||||
@@ -12,7 +12,7 @@ fn drawing() -> Drawing {
|
||||
let mut layout = Layout::new("Sheet", 1);
|
||||
layout.limits = Some((Vec2::new(1.038, 0.694), Vec2::new(9.506, 6.681)));
|
||||
layout.page.image_origin = Some(Vec2::new(-1.054, -0.71));
|
||||
d.layouts = vec![layout];
|
||||
d.layouts = vec![layout].into();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -195,7 +195,7 @@ pub(super) fn assert_layer_states(a: &Drawing, b: &Drawing, context: &str) {
|
||||
|
||||
pub(super) fn layouts() -> Case {
|
||||
let mut drawing = cases::drawing();
|
||||
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)];
|
||||
drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)].into();
|
||||
for (index, layout) in drawing.layouts.iter_mut().enumerate() {
|
||||
layout.page.paper_mm = Some(true);
|
||||
// PageSetup stores portrait dimensions; landscape is a separate orientation flag.
|
||||
|
||||
@@ -231,7 +231,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
||||
let cur = d.header.str("CLAYER", "0");
|
||||
let used = used_layers(d);
|
||||
let vp: Option<(Handle, cadcraft_doc::Viewport)> = dst.active_viewport();
|
||||
let linetypes: Vec<cadcraft_doc::Linetype> = d.linetypes.clone();
|
||||
let linetypes: cadcraft_doc::NamedList<cadcraft_doc::Linetype> = d.linetypes.clone();
|
||||
let library: Vec<String> = cadcraft_doc::library::standard_linetypes().into_iter().map(|l| l.name).filter(|n| d.linetype(n).is_none()).collect();
|
||||
let states: Vec<String> = d.layer_states.iter().map(|s| s.name.clone()).collect();
|
||||
let mut layers: Vec<Layer> = d.layers.to_vec();
|
||||
@@ -425,7 +425,7 @@ struct LayerRow<'a> {
|
||||
current: &'a str,
|
||||
used: &'a std::collections::HashSet<String>,
|
||||
viewport: Option<&'a (Handle, cadcraft_doc::Viewport)>,
|
||||
linetypes: &'a [cadcraft_doc::Linetype],
|
||||
linetypes: &'a cadcraft_doc::NamedList<cadcraft_doc::Linetype>,
|
||||
library: &'a [String],
|
||||
state: &'a mut LpmState,
|
||||
actions: &'a mut Vec<(&'static str, Value)>,
|
||||
@@ -467,7 +467,7 @@ fn row(ui: &mut egui::Ui, args: LayerRow<'_>) {
|
||||
lt_sample(
|
||||
ui.painter(),
|
||||
Rect::from_min_size(pos2(r.left() + 3.0, r.top()), vec2(30.0, r.height())),
|
||||
linetypes.iter().find(|x| x.name.eq_ignore_ascii_case(&l.linetype)),
|
||||
linetypes.by_name(&l.linetype),
|
||||
t.text,
|
||||
);
|
||||
ui.painter().text(pos2(r.left() + 38.0, r.center().y), egui::Align2::LEFT_CENTER, &l.linetype, crate::theme::body(), t.text);
|
||||
|
||||
@@ -787,7 +787,7 @@ fn sample(d: &Drawing, style: &DimStyle, w: u32, h: u32, bg: egui::Color32) -> O
|
||||
let doc = s.doc_mut().ok()?;
|
||||
doc.text_styles.clone_from(&d.text_styles);
|
||||
doc.linetypes.clone_from(&d.linetypes);
|
||||
doc.dim_styles = vec![DimStyle { name: "Preview".into(), ..style.clone() }];
|
||||
doc.dim_styles = vec![DimStyle { name: "Preview".into(), ..style.clone() }].into();
|
||||
doc.header.set_str("DIMSTYLE", "Preview");
|
||||
doc.sync_dim_vars();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user