DGNIMPORT: reference naming, cells, text placement, curves, references

Name clashes, DGNIMPORTMODE and prefixing as the reference names them;
V7 cell copies, unshared cells and mirrored placements as blocks;
justified text and text nodes placed at their justification points with
the reference's MTEXT contents; B-spline curves as splines and 3D arcs and
ellipses in their own planes; every V8 level as a layer; design models
only; reference attachments translated, ignored or attached as underlays.
The colour index palette comes from the codec fix it depends on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
ramox81andClaude Opus 5.5 committed 2026-10-16 14:33:07 +03:00
1 parent 218150c76a
commit 6fdff6c515
38 files changed
+1774 -437

No files matched your search

Generated
+1 -1
View File
@@ -4373,7 +4373,7 @@ dependencies = [
[[package]]
name = "opencadcodec"
version = "0.6.0"
source = "git+https://github.com/HakanSeven12/opencadcodec.git?rev=102f04c#102f04c8ecda1cd409f7ecc4b6eab2dc895c9095"
source = "git+https://github.com/ramox81/cadcodec.git?rev=6434df7#6434df7049b4b81e66b8884180587efda343e070"
dependencies = [
"anyhow",
"bitflags 2.13.1",
+3
View File
@@ -222,3 +222,6 @@ harness = false
[[test]]
name = "integration"
path = "tests/integration.rs"
[patch."https://github.com/HakanSeven12/opencadcodec.git"]
opencadcodec = { git = "https://github.com/ramox81/cadcodec.git", rev = "6434df7" }
+4 -1
View File
@@ -6684,7 +6684,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6672,7 +6672,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6669,7 +6669,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6670,7 +6670,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6672,7 +6672,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6671,7 +6671,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6672,7 +6672,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6669,7 +6669,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6672,7 +6672,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6660,7 +6660,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6656,7 +6656,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6671,7 +6671,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6660,7 +6660,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6671,7 +6671,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6672,7 +6672,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6670,7 +6670,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6671,7 +6671,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6672,7 +6672,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6673,7 +6673,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6593,7 +6593,10 @@ dgn-import =
.references = Dış DGN referansları
.bind = Blok / xref yap
.attach = DGN altlığı bağla
.references-note = DGN dosyalarının referans ekleri okunmaz; dışarıda bırakılır.
.existing = Çevrilmiş çizim zaten varsa
.prompt-overwrite = Sor
.overwrite = Sormadan üzerine yaz
.keep-existing = Üzerine yazma
.mapping = Özellik eşleme
.mapping-standard = Standart eşleme kurulumu.
.mapping-note = Önizleme seçili kurulumun bu dosyaya etkisini gösterir.
+4 -1
View File
@@ -6655,7 +6655,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6667,7 +6667,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+308 -84
View File
@@ -8,7 +8,9 @@ use std::collections::HashMap;
use std::sync::Arc;
use super::*;
use crate::modules::insert::dgn_import::{self, DgnImportCommand, DgnImportRequest};
use crate::modules::insert::dgn_import::{
self, DgnImportCommand, DgnImportRequest, ExistingReference, ReferenceMode,
};
use crate::ui::window::import_dialogs::{
unsupported_reason, DgnImportState, ImportDialogMsg, ImportFileState, Support, FORMATS,
};
@@ -53,7 +55,7 @@ fn exists(path: &str) -> bool {
/// Whether the file is a DGN model DGNIMPORT reads.
fn is_dgn(path: &str) -> bool {
crate::scene::model::underlay_vector::item_names(codec::entities::UnderlayType::Dgn, path)
crate::scene::model::underlay_vector::dgn_import_models(path)
.and_then(|models| models.into_iter().next())
.is_some_and(|model| crate::scene::model::underlay_vector::dgn_import(path, &model).is_some())
}
@@ -158,28 +160,38 @@ impl OpenCADStudio {
/// The DGN Import window for a file; an error when it is no DGN model.
pub(in crate::app) fn open_dgn_import_dialog(&mut self, path: &str) -> Result<(), String> {
use crate::scene::model::underlay_vector::{dgn_import, item_names};
let models = item_names(codec::entities::UnderlayType::Dgn, path).unwrap_or_default();
use crate::scene::model::underlay_vector::{dgn_import, dgn_import_models};
let models = dgn_import_models(path).unwrap_or_default();
let Some(import) = models.first().and_then(|m| dgn_import(path, m)) else {
return Err(crate::t!("Invalid or unsupported DGN file.").into_owned());
};
// The options chosen last stay when the file is changed.
// The options chosen last (DGNIMPORTMODE and the kept import
// settings when the window opens) stay when the file is changed.
let previous = self.import_dialogs.dgn.take();
let saved = dgn_import::settings();
let keep = |f: fn(&DgnImportState) -> bool, default: bool| {
previous.as_ref().map_or(default, f)
};
self.import_dialogs.dgn = Some(DgnImportState {
path: path.to_string(),
version: if import.v7 { "V7" } else { "V8" },
// Sheet models are not imported.
models: crate::ui::window::pdf_dialogs::item_thumbs(
codec::entities::UnderlayType::Dgn,
path,
),
)
.into_iter()
.filter(|m| models.contains(&m.label))
.collect(),
model: 0,
current_drawing: keep(|s| s.current_drawing, false),
prefix_duplicates: keep(|s| s.prefix_duplicates, false),
current_drawing: keep(|s| s.current_drawing, saved.mode != 0),
prefix_duplicates: keep(|s| s.prefix_duplicates, saved.mode == 2),
sub_units: keep(|s| s.sub_units, false),
explode_text_nodes: keep(|s| s.explode_text_nodes, false),
explode_text_nodes: keep(|s| s.explode_text_nodes, saved.explode_text_nodes),
references: previous.as_ref().map_or(saved.references, |s| s.references),
existing_reference: previous
.as_ref()
.map_or(saved.existing_reference, |s| s.existing_reference),
units: import.unit_names.clone(),
mapping_tab: previous.as_ref().map_or(0, |s| s.mapping_tab),
mapping: [0, 1, 2, 3].map(|tab| dgn_import::mapping_rows(&import, tab)),
@@ -366,6 +378,16 @@ impl OpenCADStudio {
s.explode_text_nodes = on;
}
}
ImportDialogMsg::DgnReferences(mode) => {
if let Some(s) = self.import_dialogs.dgn.as_mut() {
s.references = mode;
}
}
ImportDialogMsg::DgnExisting(choice) => {
if let Some(s) = self.import_dialogs.dgn.as_mut() {
s.existing_reference = choice;
}
}
ImportDialogMsg::DgnMappingTab(tab) => {
if let Some(s) = self.import_dialogs.dgn.as_mut() {
s.mapping_tab = tab.min(3);
@@ -386,7 +408,22 @@ impl OpenCADStudio {
explode_text_nodes: s.explode_text_nodes,
current_drawing: s.current_drawing,
prefix_duplicates: s.prefix_duplicates,
references: s.references,
existing_reference: s.existing_reference,
};
// The window's choices become DGNIMPORTMODE and the kept
// settings the command line imports with.
dgn_import::set_settings(dgn_import::DgnImportSettings {
mode: match (s.current_drawing, s.prefix_duplicates) {
(false, _) => 0,
(true, false) => 1,
(true, true) => 2,
},
explode_text_nodes: s.explode_text_nodes,
references: s.references,
existing_reference: s.existing_reference,
});
self.save_config();
self.close_active_modal();
return self.run_dgn_import(i, request);
}
@@ -394,7 +431,8 @@ impl OpenCADStudio {
Task::none()
}
/// The import: into a new drawing (or the current one), one undo step.
/// The import: into a new drawing (or the current one), one undo step;
/// then the model's reference attachments as the request says.
pub(in crate::app) fn run_dgn_import(&mut self, i: usize, request: DgnImportRequest) -> Task<Message> {
let Some(import) =
crate::scene::model::underlay_vector::dgn_import(&request.path, &request.model)
@@ -413,84 +451,33 @@ impl OpenCADStudio {
self.active_tab
};
self.push_undo_snapshot(i, "DGNIMPORT");
let stem = std::path::Path::new(&request.path.replace('\\', "/"))
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let scene = &mut self.tabs[i].scene;
// In the current drawing, names it already has keep the existing
// definitions, or are imported under the file's name as prefix.
let prefix = (request.current_drawing && request.prefix_duplicates)
.then(|| format!("{stem}$0$"));
let rename = |taken: bool, name: &str| match &prefix {
Some(p) if taken && name != "0" => format!("{p}{name}"),
_ => name.to_string(),
let naming = if !request.current_drawing {
Naming::Number
} else if request.prefix_duplicates {
let stem = std::path::Path::new(&request.path.replace('\\', "/"))
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
Naming::Prefix(format!("{stem} - {}$0$", request.model))
} else {
Naming::Keep
};
let mut layers: HashMap<String, String> = HashMap::new();
for (name, color) in &converted.layers {
let target = rename(scene.document.layers.contains(name), name);
if !scene.document.layers.contains(&target) {
let mut layer = codec::tables::Layer::new(target.as_str());
layer.handle = scene.document.allocate_handle();
layer.color = *color;
let _ = scene.document.layers.add(layer);
let layers = place_converted(&mut self.tabs[i].scene, converted, &naming);
if request.references != ReferenceMode::Ignore {
let k = if request.sub_units { import.sub_per_master } else { 1.0 };
// A reference is placed on the model's default level.
let layer = import
.levels
.get(&64)
.map(|l| l.0.clone())
.unwrap_or_else(|| "0".to_string());
let layer = layers.get(&layer).cloned().unwrap_or(layer);
for reference in &import.references {
self.attach_dgn_reference(i, &request, reference, k, &layer);
}
layers.insert(name.clone(), target);
}
let mut styles: HashMap<String, String> = HashMap::new();
for (name, font) in &converted.styles {
let target = rename(scene.document.text_styles.contains(name), name);
if !scene.document.text_styles.contains(&target) {
let mut style = codec::tables::TextStyle::new(target.as_str());
style.handle = scene.document.allocate_handle();
style.font_file = font.clone();
let _ = scene.document.text_styles.add(style);
}
styles.insert(name.clone(), target);
}
let mut blocks: HashMap<String, String> = HashMap::new();
for (name, _) in &converted.blocks {
let taken = scene.document.block_records.get(name).is_some();
blocks.insert(name.clone(), rename(taken, name));
}
let fix = |mut entity: codec::EntityType| {
let common = entity.common_mut();
if let Some(layer) = layers.get(&common.layer) {
common.layer = layer.clone();
}
match &mut entity {
codec::EntityType::Text(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::MText(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::Insert(insert) => {
if let Some(b) = blocks.get(&insert.block_name) {
insert.block_name = b.clone();
}
}
_ => {}
}
entity
};
for (name, entities) in converted.blocks {
let target = &blocks[&name];
if scene.document.block_records.get(target).is_some() {
continue;
}
let entities = entities.into_iter().map(&fix).collect();
let _ = scene.define_block_from_owned_entities(entities, target, glam::DVec3::ZERO);
}
for entity in converted.entities {
scene.add_entity(fix(entity));
}
if !request.current_drawing {
scene.fit_all();
self.tabs[i].scene.fit_all();
}
self.tabs[i].dirty = true;
self.command_line.push_output("Regenerating model.");
@@ -498,4 +485,241 @@ impl OpenCADStudio {
self.refresh_properties();
task
}
/// One reference attachment: its file translated to "<file>-<model>.dwg"
/// beside it and attached as the external reference "<file> - <model>",
/// or the file attached as a DGN underlay, at the attachment's place.
fn attach_dgn_reference(
&mut self,
i: usize,
request: &DgnImportRequest,
reference: &crate::scene::model::underlay_vector::DgnReference,
units: f64,
layer: &str,
) {
use crate::scene::model::underlay_vector::{dgn_import, dgn_import_models};
let host_dir = std::path::Path::new(&request.path)
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_default();
let named = std::path::Path::new(&reference.file.replace('\\', "/")).to_path_buf();
let file = if named.is_file() {
named
} else {
host_dir.join(named.file_name().unwrap_or_default())
};
let path = file.to_string_lossy().into_owned();
if crate::scene::model::pdf_raster::source_bytes(&path).is_none() {
return;
}
let Some(model) = (if reference.model.is_empty() {
dgn_import_models(&path).and_then(|m| m.into_iter().next())
} else {
Some(reference.model.clone())
}) else {
return;
};
let origin = glam::DVec3::from_array(reference.origin) * units;
if request.references == ReferenceMode::Underlay {
let mut placed = crate::modules::insert::pdf_attach::underlays_for_pages(
codec::entities::UnderlayType::Dgn,
std::slice::from_ref(&model),
origin,
reference.scale,
reference.rotation,
);
let scene = &mut self.tabs[i].scene;
for (page, mut entity) in placed.drain(..) {
let definition = crate::modules::insert::pdf_attach::ensure_underlay_definition(
&mut scene.document,
codec::entities::UnderlayType::Dgn,
&path,
&page,
);
if let codec::EntityType::Underlay(underlay) = &mut entity {
underlay.definition_handle = definition;
}
entity.common_mut().layer = layer.to_string();
scene.add_entity(entity);
}
return;
}
let stem = file
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let target = file.with_file_name(format!("{stem}-{model}.dwg"));
// ponytail: "Prompt to overwrite" keeps the existing drawing, as the
// reference does when it cannot ask; ask here if a window is wanted.
let write = !target.is_file() || request.existing_reference == ExistingReference::Overwrite;
if write {
let Some(source) = dgn_import(&path, &model) else {
return;
};
let mut scene = crate::scene::Scene::new();
let converted = dgn_import::convert(&source, false, request.explode_text_nodes);
place_converted(&mut scene, converted, &Naming::Number);
if let Err(error) = crate::io::save(&scene.document, &target) {
self.command_line.push_error(&error);
return;
}
}
let xref = crate::modules::insert::xattach::XrefAttachRequest {
path: target.to_string_lossy().into_owned(),
overlay: false,
path_type: crate::io::xref_model::Pathtype::Relative,
};
let name = format!("{stem} - {model}");
let full = crate::modules::insert::xattach::resolve_xref_store_path(&xref.path, None);
self.command_line
.push_output(&format!("Attach Xref \"{name}\": {full}"));
let host = self.tabs[i].current_path.clone();
let block = crate::modules::insert::xattach::prepare_named_xref_definition(
&mut self.tabs[i].scene,
&xref,
host.as_deref(),
&name,
);
if host.is_none() {
self.tabs[i].xref_relative_on_save.insert(block.clone());
}
self.command_line
.push_output(&format!("\"{name}\" loaded: {full}"));
let mut insert = codec::entities::Insert::new(
block,
codec::types::Vector3::new(origin.x, origin.y, origin.z),
)
.with_scale(reference.scale, reference.scale, reference.scale)
.with_rotation(reference.rotation);
insert.common.layer = layer.to_string();
insert.common.linetype = "Continuous".to_string();
self.tabs[i]
.scene
.add_entity(codec::EntityType::Insert(insert));
self.refresh_xref_manager();
}
}
/// How imported names meet the names a drawing already has: a new drawing
/// numbers a clashing layer "<name>_1" and a clashing block or text style
/// "<name>1" (layer 0 and the Standard style are shared); the current
/// drawing either keeps its own definitions or prefixes every imported name
/// (layers 0 and Defpoints excepted).
enum Naming {
Number,
Keep,
Prefix(String),
}
impl Naming {
fn name(&self, kind: char, name: &str, taken: &dyn Fn(&str) -> bool) -> String {
match self {
Naming::Keep => name.to_string(),
Naming::Prefix(p) => {
let shared = kind == 'l'
&& (name == "0" || name.eq_ignore_ascii_case("Defpoints"));
if shared {
name.to_string()
} else {
format!("{p}{name}")
}
}
Naming::Number => {
let shared = (kind == 'l' && name == "0")
|| (kind == 's' && name.eq_ignore_ascii_case("Standard"));
if shared || !taken(name) {
return name.to_string();
}
let sep = if kind == 'l' { "_" } else { "" };
(1..)
.map(|n| format!("{name}{sep}{n}"))
.find(|n| !taken(n))
.unwrap_or_default()
}
}
}
}
/// Adds converted objects to a drawing under the naming rule; returns the
/// layer names as placed.
fn place_converted(
scene: &mut crate::scene::Scene,
converted: dgn_import::Converted,
naming: &Naming,
) -> HashMap<String, String> {
let mut layers: HashMap<String, String> = HashMap::new();
for (name, color) in &converted.layers {
let doc = &scene.document;
let taken = |n: &str| doc.layers.iter().any(|l| l.name.eq_ignore_ascii_case(n));
let target = naming.name('l', name, &taken);
if !scene.document.layers.iter().any(|l| l.name.eq_ignore_ascii_case(&target)) {
let mut layer = codec::tables::Layer::new(target.as_str());
layer.handle = scene.document.allocate_handle();
layer.color = *color;
let _ = scene.document.layers.add(layer);
}
layers.insert(name.clone(), target);
}
let mut styles: HashMap<String, String> = HashMap::new();
for (name, font) in &converted.styles {
let doc = &scene.document;
let taken = |n: &str| doc.text_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n));
let target = naming.name('s', name, &taken);
if !scene.document.text_styles.iter().any(|s| s.name.eq_ignore_ascii_case(&target)) {
let mut style = codec::tables::TextStyle::new(target.as_str());
style.handle = scene.document.allocate_handle();
style.font_file = font.clone();
let _ = scene.document.text_styles.add(style);
}
styles.insert(name.clone(), target);
}
let mut blocks: HashMap<String, String> = HashMap::new();
let mut claimed: Vec<String> = Vec::new();
for (name, _) in &converted.blocks {
let doc = &scene.document;
let taken = |n: &str| {
doc.block_records.iter().any(|b| b.name.eq_ignore_ascii_case(n))
|| claimed.iter().any(|c| c.eq_ignore_ascii_case(n))
};
let target = naming.name('b', name, &taken);
claimed.push(target.clone());
blocks.insert(name.clone(), target);
}
let fix = |mut entity: codec::EntityType| {
let common = entity.common_mut();
if let Some(layer) = layers.get(&common.layer) {
common.layer = layer.clone();
}
match &mut entity {
codec::EntityType::Text(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::MText(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::Insert(insert) => {
if let Some(b) = blocks.get(&insert.block_name) {
insert.block_name = b.clone();
}
}
_ => {}
}
entity
};
for (name, entities) in converted.blocks {
let target = &blocks[&name];
if scene.document.block_records.get(target).is_some() {
continue;
}
let entities = entities.into_iter().map(&fix).collect();
let _ = scene.define_block_from_owned_entities(entities, target, glam::DVec3::ZERO);
}
for entity in converted.entities {
scene.add_entity(fix(entity));
}
layers
}
+1
View File
@@ -834,6 +834,7 @@ inventory::submit!(crate::command::CommandRegistration {
"SELECTIONCYCLING",
"UCSDETECT",
"SURFACEASSOCIATIVITY",
"DGNIMPORTMODE",
"LAYOUTCREATEVIEWPORT",
"TXT2MTXTCOMBINEMTEXT",
"TXT2MTXTTEXTORDER",
+36
View File
@@ -1223,6 +1223,7 @@ impl OpenCADStudio {
| "SELECTIONCYCLING"
| "UCSDETECT"
| "SURFACEASSOCIATIVITY"
| "DGNIMPORTMODE"
| "UCSORTHO"
| "UCSVIEW"
| "LAYOUTCREATEVIEWPORT"
@@ -1622,6 +1623,41 @@ impl OpenCADStudio {
}
return Some(self.finish_dispatch(cmd));
}
if name == "DGNIMPORTMODE" {
// Where DGNIMPORT puts the model: 0 a new drawing, 1 the
// current one keeping its definitions, 2 the current one
// with prefixed names.
use crate::modules::insert::dgn_import::{set_settings, settings};
let mut s = settings();
let current = s.mode;
match value
.as_deref()
.map(|v| v.trim().parse::<u8>().ok().filter(|v| *v <= 2))
{
Some(Some(mode)) => {
if current != mode {
s.mode = mode;
set_settings(s);
self.save_config();
}
}
Some(None) => {
self.command_line
.push_error("Requires an integer between 0 and 2.");
self.command_line.push_output(&format!(
"Enter new value for DGNIMPORTMODE <{current}>:"
));
self.pending_setvar = Some(name.clone());
}
None => {
self.command_line.push_output(&format!(
"Enter new value for DGNIMPORTMODE <{current}>:"
));
self.pending_setvar = Some(name.clone());
}
}
return Some(self.finish_dispatch(cmd));
}
if name == "SURFACEASSOCIATIVITY" {
use crate::scene::model::sweep_model;
let current = i16::from(sweep_model::surface_associativity());
+13
View File
@@ -2201,6 +2201,7 @@ impl OpenCADStudio {
// The DGN Import window, one field per call: "path=<file>" (as
// Change… picks it), "model=<n>", "target=new|current",
// "conflict=prefix|ignore", "units=master|sub", "explode=on|off",
// "references=translate|ignore|underlay", "existing=prompt|overwrite|keep",
// "mapping=layer|linetype|lineweight|color", "ok" or "cancel".
"dgn_import_dialog" => {
use crate::ui::window::import_dialogs::ImportDialogMsg as I;
@@ -2238,6 +2239,18 @@ impl OpenCADStudio {
_ => return Err(bad()),
}),
"explode" => I::DgnExplode(on(value)?),
"references" => I::DgnReferences(match value {
"translate" => crate::modules::insert::dgn_import::ReferenceMode::Translate,
"ignore" => crate::modules::insert::dgn_import::ReferenceMode::Ignore,
"underlay" => crate::modules::insert::dgn_import::ReferenceMode::Underlay,
_ => return Err(bad()),
}),
"existing" => I::DgnExisting(match value {
"prompt" => crate::modules::insert::dgn_import::ExistingReference::Prompt,
"overwrite" => crate::modules::insert::dgn_import::ExistingReference::Overwrite,
"keep" => crate::modules::insert::dgn_import::ExistingReference::Keep,
_ => return Err(bad()),
}),
"mapping" => I::DgnMappingTab(match value {
"layer" => 0,
"linetype" => 1,
+3
View File
@@ -519,6 +519,8 @@ pub struct UserSettings {
/// PDFSHXTEXT's recognition settings (fonts, threshold, PDFSHXLAYER,
/// PDFSHXBESTFONT, PDFSHXTEXTSETTINGS).
pub pdf_shx_text: crate::modules::insert::pdf_shx_text::ShxTextSettings,
/// DGNIMPORTMODE and the DGN Import window's last choices.
pub dgn_import: crate::modules::insert::dgn_import::DgnImportSettings,
/// Nested-copy symbol handling: false inserts, true binds.
pub ncopy_bind: bool,
/// Last Options page; unknown saved names fall back without rejecting the config.
@@ -999,6 +1001,7 @@ impl Default for UserSettings {
ucs_view: true,
layout_create_viewport: true,
pdf_shx_text: Default::default(),
dgn_import: Default::default(),
ncopy_bind: false,
cursor_type: CursorType::Crosshair,
crosshair_color: None,
+2
View File
@@ -864,6 +864,7 @@ impl OpenCADStudio {
ucs_view: crate::modules::view::view_cmd::ucs_view(),
layout_create_viewport: crate::scene::layout_create_viewport(),
pdf_shx_text: crate::modules::insert::pdf_shx_text::settings(),
dgn_import: crate::modules::insert::dgn_import::settings(),
ncopy_bind: self.ncopy_bind,
cursor_type: self.cursor_type,
crosshair_color: self.crosshair_color,
@@ -1013,6 +1014,7 @@ impl OpenCADStudio {
crate::modules::view::view_cmd::set_ucs_view(s.ucs_view);
crate::scene::set_layout_create_viewport(s.layout_create_viewport);
crate::modules::insert::pdf_shx_text::set_settings(s.pdf_shx_text.clone());
crate::modules::insert::dgn_import::set_settings(s.dgn_import);
self.ncopy_bind = s.ncopy_bind;
self.cursor_type = s.cursor_type;
self.crosshair_color = s.crosshair_color;
+4 -1
View File
@@ -3498,7 +3498,10 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"External DGN references" => Some(("dgn-import", "references")),
"Bind as block / xref" => Some(("dgn-import", "bind")),
"Attach as DGN underlay" => Some(("dgn-import", "attach")),
"Reference attachments of DGN files are not read; they are left out." => Some(("dgn-import", "references-note")),
"When the translated drawing exists" => Some(("dgn-import", "existing")),
"Prompt to overwrite" => Some(("dgn-import", "prompt-overwrite")),
"Overwrite without prompting" => Some(("dgn-import", "overwrite")),
"Do not overwrite" => Some(("dgn-import", "keep-existing")),
"Property mapping" => Some(("dgn-import", "mapping")),
"Standard mapping setup." => Some(("dgn-import", "mapping-standard")),
"The preview shows the selected setup's effect on this file." => Some(("dgn-import", "mapping-note")),
File diff suppressed because it is too large. Load diff
+11 -1
View File
@@ -651,7 +651,17 @@ pub fn prepare_xref_definition(
request: &XrefAttachRequest,
host_file: Option<&std::path::Path>,
) -> String {
let stem = path_to_block_name(&request.path);
prepare_named_xref_definition(scene, request, host_file, &path_to_block_name(&request.path))
}
/// [`prepare_xref_definition`] under a chosen name instead of the file's.
pub fn prepare_named_xref_definition(
scene: &mut Scene,
request: &XrefAttachRequest,
host_file: Option<&std::path::Path>,
stem: &str,
) -> String {
let stem = stem.to_string();
if let Some(existing) = existing_reference(scene, &stem) {
return existing;
}
+65 -28
View File
@@ -6,8 +6,8 @@
use std::collections::HashMap;
use super::model::{
arc_cubics, bspline_points, dgn_color_table, paths_bounds, scaled_elements, DgnCollector,
DgnElement, DgnGeom, DgnImport, Path, PathBuilder, Segment, Sheet, SubPath, Text,
arc_cubics, bspline_points, dgn_color_table, paths_bounds, scaled_elements, By, DgnCollector,
DgnColor, DgnElement, DgnGeom, DgnImport, Path, PathBuilder, Segment, Sheet, SubPath, Text,
DGN_DEFAULT_COLORS,
};
@@ -140,7 +140,9 @@ struct Instance {
/// chains and shapes (joined), B-splines, text and shared cell instances.
fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let mut raw = Raw::default();
let mut spline: Option<(usize, usize, [u8; 3], f64)> = None;
// An open B-spline curve: order, pole count, colour, closed, and the
// header as the element it imports as.
let mut spline: Option<(usize, usize, [u8; 3], bool, DgnElement)> = None;
let mut knots: Vec<f64> = Vec::new();
// A complex shape or chain collects its components into one path.
let mut complex: Option<(
@@ -212,11 +214,16 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let color = colors[(symbology >> 8) as usize];
let element = |geom: DgnGeom| DgnElement {
level: level(e) as u32,
color: Some(color),
weight: Some(((symbology >> 3) & 31) as u32),
style: Some((symbology & 7) as u32),
color: By::Own(DgnColor {
index: (symbology >> 8) as u32,
table: color,
rgb: color,
}),
weight: By::Own(((symbology >> 3) & 31) as u32),
style: By::Own((symbology & 7) as u32),
geom,
};
let flat = |p: [f64; 2]| [p[0], p[1], 0.0];
// One pixel wide, as V8 models draw: the element weight is a
// lineweight, not shown while lineweights are off.
let stroke = Some((color, -1.0));
@@ -224,10 +231,16 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let int_pt =
|i: usize| -> Option<[f64; 2]> { Some([int32(e, i)? as f64, int32(e, i + 4)? as f64]) };
match kind {
// A text node: its count of text components.
// A text node: its count of text components, justification
// (45), line spacing (46) and origin (62).
7 => collect.open(
uint16(e, 38).unwrap_or(0) as usize,
element(DgnGeom::TextNode(Vec::new())),
element(DgnGeom::TextNode {
lines: Vec::new(),
origin: int_pt(62).map(flat),
just: e.get(45).copied().unwrap_or(0),
line_spacing: int32(e, 46).map(|v| v as f64),
}),
),
12 | 14 => {
let n = uint16(e, 38).unwrap_or(0) as usize;
@@ -244,7 +257,7 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
}
3 => {
if let (Some(a), Some(b)) = (int_pt(36), int_pt(44)) {
collect.push(element(DgnGeom::Line(a, b)));
collect.push(element(DgnGeom::Line(flat(a), flat(b))));
push(
&mut raw,
&mut complex,
@@ -263,7 +276,7 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let n = uint16(e, 36).unwrap_or(0) as usize;
let pts: Vec<[f64; 2]> = (0..n).filter_map(|k| int_pt(38 + k * 8)).collect();
if pts.len() >= 2 {
collect.push(element(DgnGeom::Points(pts.clone())));
collect.push(element(DgnGeom::Points(pts.iter().map(|p| flat(*p)).collect())));
push(
&mut raw,
&mut complex,
@@ -312,9 +325,9 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let turn = (r as f64 / 360000.0).to_radians();
let (c, s) = (turn.cos(), turn.sin());
collect.push(element(DgnGeom::Arc {
center: [ox, oy],
u: [a * c, a * s],
v: [-b * s, b * c],
center: [ox, oy, 0.0],
u: [a * c, a * s, 0.0],
v: [-b * s, b * c, 0.0],
start: start.to_radians(),
sweep: sweep.to_radians(),
}));
@@ -353,7 +366,11 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let Some(chars) = e.get(60..60 + n) else {
continue;
};
let (height, width) = (height as f64 * 6.0 / 1000.0, width as f64 * 6.0 / 1000.0);
// Sizes in whole UORs (the multipliers are 1000/6 of one).
let (height, width) = (
(height as f64 * 6.0 / 1000.0).round(),
(width as f64 * 6.0 / 1000.0).round(),
);
let text = Text {
text: String::from_utf8_lossy(chars)
.trim_end_matches('\0')
@@ -365,26 +382,35 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
color,
font: "txt".to_string(),
};
// A V7 font is drawn monospaced: the text is as long as its
// characters times their width.
collect.push(element(DgnGeom::Text {
text: text.text.clone(),
origin,
origin: flat(origin),
height,
width_factor: text.width_factor,
length: text.text.chars().count() as f64 * width,
rotation: text.rotation,
just: e[37],
font: Some(e[36] as u32),
}));
raw.texts.push(text);
}
27 => {
// B-spline curve header: order, pole count.
let order = ((e.get(40).copied().unwrap_or(0) & 0x0f) + 2) as usize;
// B-spline curve header: order and closure (40), pole count
// (42), knot count (44); the curve imports with the header's
// level and symbology.
let flags = e.get(40).copied().unwrap_or(0);
let order = ((flags & 0x0f) + 2) as usize;
let poles = uint16(e, 42).unwrap_or(0) as usize;
spline = Some((order, poles, color, -1.0));
knots.clear();
let header = element(DgnGeom::Chain(Vec::new()));
spline = Some((order, poles, color, flags & 0x80 != 0, header));
knots = vec![f64::NAN; uint16(e, 44).unwrap_or(0) as usize];
}
26 => {
// Interior knots as fractions of the parameter range.
let n = spline.map(|s| s.1.saturating_sub(s.0)).unwrap_or(0);
// Knots as fractions of the parameter range; a closed
// curve's list also holds its ends.
let n = knots.len();
knots = (0..n)
.filter_map(|k| int32(e, 36 + k * 4))
.map(|v| v as u32 as f64 / 2_147_483_648.0)
@@ -393,10 +419,15 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
21 => {
let n = uint16(e, 36).unwrap_or(0) as usize;
let poles: Vec<[f64; 2]> = (0..n).filter_map(|k| int_pt(38 + k * 8)).collect();
if let Some((order, count, color, width)) = spline.take() {
if let Some((order, count, color, closed, header)) = spline.take() {
if poles.len() == count && count >= order {
let interior = if knots.len() == count - order {
knots.clone()
let stored: Vec<f64> = knots
.iter()
.copied()
.filter(|k| *k > 1e-9 && *k < 1.0 - 1e-6)
.collect();
let interior = if stored.len() == count - order {
stored
} else {
(1..=count - order)
.map(|k| k as f64 / (count - order + 1) as f64)
@@ -407,13 +438,18 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
full.extend(vec![1.0; order]);
let pts = bspline_points(order, &poles, &full, 24 * count);
collect.push(DgnElement {
color: Some(color),
..element(DgnGeom::Points(pts.clone()))
geom: DgnGeom::Spline {
degree: order - 1,
knots: full,
poles: poles.iter().map(|p| flat(*p)).collect(),
closed,
},
..header
});
push(
&mut raw,
&mut complex,
polyline(&pts, false, Some((color, width)), None),
polyline(&pts, false, Some((color, -1.0)), None),
);
}
}
@@ -443,7 +479,7 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
collect.push(element(DgnGeom::Cell {
name: name.clone(),
m: [m0, m1, m2, m3],
origin: [ox as f64, oy as f64],
origin: [ox as f64, oy as f64, 0.0],
z_scale: 1.0,
}));
raw.instances.push(Instance {
@@ -743,5 +779,6 @@ pub fn import(bytes: &[u8]) -> Option<DgnImport> {
sub_per_master: u.sub_per_master,
unit_names: (unit_name(bytes, 1120), unit_name(bytes, 1122)),
v7: true,
..Default::default()
})
}
+332 -26
View File
@@ -8,8 +8,9 @@ use std::collections::HashMap;
use std::io::Read;
use super::model::{
arc_cubics, dgn_color_table, paths_bounds, scaled_elements, DgnCollector, DgnElement, DgnGeom,
DgnImport, Path, PathBuilder, Segment, Sheet, SubPath, Text, DGN_DEFAULT_COLORS,
arc_cubics, bspline_points, dgn_color_table, paths_bounds, scaled_elements, By, DgnCollector,
DgnColor, DgnElement, DgnGeom, DgnImport, DgnReference, Path, PathBuilder, Segment, Sheet,
SubPath, Text, DGN_DEFAULT_COLORS,
};
// ── Compound file ───────────────────────────────────────────────────────────
@@ -384,6 +385,100 @@ impl Styles {
.copied()
.unwrap_or([255, 255, 255])
}
/// The colour word as an element's colour: the level's (0xFFFFFFFF),
/// the enclosing cell's (0xFFFFFFFE), or a table index (low byte) with
/// the table entry and the colour drawn.
fn color_word(&self, e: &[u8]) -> By<DgnColor> {
match u32_at(e, 52) {
None | Some(u32::MAX) => By::Level,
Some(0xFFFF_FFFE) => By::Cell,
Some(word) => {
let index = word & 0xff;
By::Own(DgnColor {
index,
table: self
.colors
.get(index as usize)
.copied()
.unwrap_or([255, 255, 255]),
rgb: self.color(e),
})
}
}
}
}
/// A B-spline curve from its order and poles, with uniform knots. A closed
/// curve (its last pole repeating the first) is periodic: its distinct
/// poles wrap around with knots (i + 1) / (count + 1), and the curve is
/// clamped at both ends of its domain by knot insertion, as the reference
/// converts it.
fn bspline_geom(order: usize, poles: Vec<[f64; 3]>, closed: bool) -> DgnGeom {
let degree = order - 1;
let distinct = poles.len() - usize::from(closed && poles.first() == poles.last());
if !closed || distinct < order {
let interior = poles.len() - order;
let mut knots = vec![0.0; order];
knots.extend((1..=interior).map(|k| k as f64 / (interior + 1) as f64));
knots.extend(vec![1.0; order]);
return DgnGeom::Spline {
degree,
knots,
poles,
closed,
};
}
let mut ctrl: Vec<[f64; 3]> = (0..distinct + degree).map(|i| poles[i % distinct]).collect();
let count = ctrl.len() + order;
let mut knots: Vec<f64> = (0..count).map(|i| (i + 1) as f64 / (count + 1) as f64).collect();
let (lo, hi) = (knots[degree], knots[ctrl.len()]);
let same = |a: f64, b: f64| (a - b).abs() < 1e-12;
// Knot insertion (Boehm) of t until it is a degree-fold knot.
let mut insert = |t: f64| loop {
let mult = knots.iter().filter(|k| same(**k, t)).count();
if mult >= degree {
return;
}
let Some(k) = knots.iter().rposition(|x| *x <= t + 1e-12) else {
return;
};
let mut next = Vec::with_capacity(ctrl.len() + 1);
for i in 0..=ctrl.len() {
if i + degree <= k {
next.push(ctrl[i]);
} else if i + mult > k {
next.push(ctrl[i - 1]);
} else {
let a = (t - knots[i]) / (knots[i + degree] - knots[i]);
next.push(std::array::from_fn(|c| (1.0 - a) * ctrl[i - 1][c] + a * ctrl[i][c]));
}
}
ctrl = next;
knots.insert(k + 1, t);
};
insert(lo);
insert(hi);
// The domain clamped: an order-fold knot at each end, the poles that
// span it.
let first = knots.iter().position(|k| same(*k, lo)).unwrap_or(1).max(1);
let last = knots.iter().rposition(|k| same(*k, hi)).unwrap_or(knots.len() - 1);
let mut clamped = vec![lo];
clamped.extend_from_slice(&knots[first..=last]);
clamped.push(hi);
let poles: Vec<[f64; 3]> = ctrl
.iter()
.skip(first - 1)
.take(clamped.len() - order)
.copied()
.collect();
let knots = clamped;
DgnGeom::Spline {
degree,
knots,
poles,
closed: true,
}
}
/// Plan geometry in UORs, and the shared cells it places.
@@ -554,18 +649,29 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
[q[0], q[1]]
};
let mut collect = DgnCollector::default();
// An open B-spline curve: order, pole count, closure and its header.
let mut spline: Option<(usize, usize, bool, DgnElement)> = None;
for (index, e) in run.iter().enumerate() {
if e.len() < 104 || styles.hidden.contains(&u32_at(e, 12).unwrap_or(0)) {
continue;
}
let color = styles.color(e);
// Colour and weight words: 0xFFFFFFFF takes the level's; line style
// 0x7FFFFFFF (or 0xFFFFFFFF).
// Colour and weight words: 0xFFFFFFFF takes the level's, 0xFFFFFFFE
// the enclosing cell's; line style 0x7FFFFFFF (or 0xFFFFFFFF) the
// level's, 0x7FFFFFFE the cell's.
let element = |geom: DgnGeom| DgnElement {
level: u32_at(e, 12).unwrap_or(0),
color: (u32_at(e, 52) != Some(u32::MAX)).then_some(color),
weight: u32_at(e, 48).filter(|w| *w != u32::MAX).map(|w| w & 31),
style: u32_at(e, 44).filter(|s| *s != u32::MAX && *s != 0x7FFF_FFFF),
color: styles.color_word(e),
weight: match u32_at(e, 48) {
None | Some(u32::MAX) => By::Level,
Some(0xFFFF_FFFE) => By::Cell,
Some(w) => By::Own(w & 31),
},
style: match u32_at(e, 44) {
None | Some(u32::MAX) | Some(0x7FFF_FFFF) => By::Level,
Some(0xFFFF_FFFE) | Some(0x7FFF_FFFE) => By::Cell,
Some(s) => By::Own(s),
},
geom,
};
let stroke = Some((color, -1.0));
@@ -578,6 +684,9 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
if d3 { f64_at(e, at + 16)? } else { 0.0 },
])
};
// A point or vector placed in the model (3D kept for the import).
let at3 = |p: [f64; 3]| xf_point(xf, p);
let dir3 = |v: [f64; 3]| xf_vector(xf, v);
match kind(e) {
// A text node: grouped when its count is followed by that many
// text components.
@@ -587,7 +696,34 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
parts.iter().all(|p| p.len() >= 104 && kind(p) == 17 && is_component(p))
});
if texts {
collect.open(n, element(DgnGeom::TextNode(Vec::new())));
// 2D: justification 118, origin 152 (the node's
// justification point).
let origin = (!d3).then(|| p3(152)).flatten().map(at3);
collect.open(
n,
element(DgnGeom::TextNode {
lines: Vec::new(),
origin,
just: if d3 { 0 } else { e.get(118).copied().unwrap_or(0) },
line_spacing: None,
}),
);
}
}
// A cell (not shared): its components follow, flagged as such.
2 => {
let n = u32_at(e, 104).unwrap_or(0) as usize;
let parts = run
.get(index + 1..index + 1 + n)
.is_some_and(|parts| parts.iter().all(|p| is_component(p)));
if parts && n > 0 {
collect.open(
n,
element(DgnGeom::CellGroup {
name: marked_string(e, 104).unwrap_or_default(),
parts: Vec::new(),
}),
);
}
}
12 | 14 => {
@@ -602,7 +738,7 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
}
3 => {
if let (Some(a), Some(b)) = (p3(104), p3(if d3 { 128 } else { 120 })) {
collect.push(element(DgnGeom::Line(plan(a), plan(b))));
collect.push(element(DgnGeom::Line(at3(a), at3(b))));
push(
&mut raw,
&mut complex,
@@ -620,12 +756,10 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
4 | 6 | 11 => {
let n = u32_at(e, 104).unwrap_or(0) as usize;
let stride = if d3 { 24 } else { 16 };
let pts: Vec<[f64; 2]> = (0..n)
.filter_map(|k| p3(112 + k * stride))
.map(plan)
.collect();
let pts3: Vec<[f64; 3]> = (0..n).filter_map(|k| p3(112 + k * stride)).collect();
let pts: Vec<[f64; 2]> = pts3.iter().map(|p| plan(*p)).collect();
if pts.len() >= 2 {
collect.push(element(DgnGeom::Points(pts.clone())));
collect.push(element(DgnGeom::Points(pts3.iter().map(|p| at3(*p)).collect())));
let mut pb = PathBuilder::default();
pb.move_to(pts[0]);
for p in &pts[1..] {
@@ -702,11 +836,11 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
};
let closed = sweep.abs() >= std::f64::consts::TAU - 1e-9;
{
let (pu, pv) = (axis(u), axis(v));
let (du, dv) = (dir3(u), dir3(v));
collect.push(element(DgnGeom::Arc {
center: plan(c),
u: [a * pu[0], a * pu[1]],
v: [b * pv[0], b * pv[1]],
center: at3(c),
u: du.map(|x| a * x),
v: dv.map(|x| b * x),
start,
sweep,
}));
@@ -758,6 +892,16 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
let Some((width, height, (u, v), origin, text)) = placed else {
continue;
};
// 2D: the justification (108) and the length of the text box
// along the baseline (128).
let (just, length) = if d3 {
(2, 0.0)
} else {
(
e.get(108).copied().unwrap_or(2),
f64_at(e, 128).filter(|l| l.is_finite()).unwrap_or(0.0),
)
};
// The text's axes as the plan shows them: its baseline sets the
// angle, and each axis's plan length scales its size.
let (pu, pv) = (axis(u), axis(v));
@@ -769,10 +913,12 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
let width_factor = if height > 0.0 { width / height } else { 1.0 };
collect.push(element(DgnGeom::Text {
text: text.clone(),
origin: plan(origin),
origin: at3(origin),
height,
width_factor,
length: length * su,
rotation: pu[1].atan2(pu[0]),
just,
font: None,
}));
raw.texts.push(Text {
@@ -804,7 +950,7 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
collect.push(element(DgnGeom::Cell {
name: name.clone(),
m: [m[0], m[1], m[3], m[4]],
origin: [o[0], o[1]],
origin: o,
z_scale: m[8],
}));
raw.instances.push(Instance {
@@ -812,6 +958,48 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
xf: xf_compose(xf, &local),
});
}
27 => {
// B-spline curve header: order and closure in the word at
// 108, pole count 112; its poles follow (type 21).
let flags = u16::from_le_bytes([e[108], e[109]]);
spline = Some((
((flags & 0x0f) + 2) as usize,
u32_at(e, 112).unwrap_or(0) as usize,
flags & 0x0180 != 0,
element(DgnGeom::Chain(Vec::new())),
));
}
21 => {
let n = u32_at(e, 104).unwrap_or(0) as usize;
let stride = if d3 { 24 } else { 16 };
let poles: Vec<[f64; 3]> = (0..n).filter_map(|k| p3(112 + k * stride)).collect();
if let Some((order, count, closed, header)) = spline.take() {
if poles.len() == count && count >= order && order >= 2 {
let poles: Vec<[f64; 3]> = poles.iter().map(|p| at3(*p)).collect();
let geom = bspline_geom(order, poles, closed);
if let DgnGeom::Spline { degree, knots, poles, .. } = &geom {
let plan_poles: Vec<[f64; 2]> =
poles.iter().map(|p| [p[0], p[1]]).collect();
let pts = bspline_points(degree + 1, &plan_poles, knots, 24 * count);
let mut pb = PathBuilder::default();
pb.move_to(pts[0]);
for p in &pts[1..] {
pb.line_to(*p);
}
push(
&mut raw,
&mut complex,
Path {
subpaths: pb.finish(),
stroke,
fill: None,
},
);
}
collect.push(DgnElement { geom, ..header });
}
}
}
_ => {}
}
}
@@ -983,12 +1171,14 @@ fn level_table(nm: &[&[u8]]) -> Vec<(u32, String, u32)> {
out
}
/// The level table with the file's own names.
/// The level table with the file's own names: the first one (the file's;
/// a later level table holds a reference attachment's levels).
fn level_table_raw(nm: &[&[u8]]) -> Vec<(u32, String, u32)> {
let mut out = Vec::new();
let mut in_levels = false;
for e in nm {
match kind(e) {
96 if u32_at(e, 12) == Some(1) && !out.is_empty() => break,
96 => in_levels = u32_at(e, 12) == Some(1),
95 if in_levels && e.len() >= 80 => {
let (Some(id), Some(color)) = (u32_at(e, 32), u32_at(e, 72)) else {
@@ -1156,13 +1346,108 @@ fn unit_name(metres: f64) -> String {
/// The named model element by element (DGNIMPORT): in master units with
/// the global origin at 0,0, shared cell definitions in master units, and
/// every level by id with its own name and colour.
/// A design model (not a sheet): the model type byte of its header (4105)
/// is 2 for a sheet.
fn is_design(header: &[u8]) -> bool {
header.get(4105) != Some(&2)
}
/// The models DGNIMPORT offers: the design models (sheets are not
/// imported).
pub fn design_model_names(bytes: &[u8]) -> Option<Vec<String>> {
let cfb = Cfb::open(bytes)?;
let names: Vec<String> = models(&cfb)
.into_iter()
.filter(|m| is_design(&m.2))
.map(|m| m.0)
.collect();
(!names.is_empty()).then_some(names)
}
/// The control stream (Dgn^C) of each model, in the order `models` lists
/// them.
fn control_streams(cfb: &Cfb) -> Vec<Vec<u8>> {
let streams = cfb.streams();
let mut dirs: Vec<String> = streams
.iter()
.filter_map(|(p, _)| p.strip_suffix("/Dgn^G/$1").map(|d| d.to_string()))
.collect();
dirs.sort();
dirs.iter()
.map(|dir| {
streams
.iter()
.find(|(p, _)| *p == format!("{dir}/Dgn^C/$1"))
.map(|(_, e)| inflate(&cfb.stream(e)))
.unwrap_or_default()
})
.collect()
}
/// Every string of an element stored after the "ff fe 01 00" marker, with
/// the subtype of the string linkage before it (2 file name, 3 full path,
/// 4 logical name).
fn linked_strings(e: &[u8]) -> Vec<(u32, String)> {
let mut out = Vec::new();
let mut from = 0;
while let Some(i) = e
.get(from..)
.and_then(|rest| rest.windows(4).position(|w| w == [0xff, 0xfe, 0x01, 0x00]))
{
let at = from + i;
let end = e[at + 4..]
.iter()
.position(|&c| c == 0 || c < 0x20)
.map(|n| at + 4 + n)
.unwrap_or(e.len());
let subtype = at.checked_sub(8).and_then(|p| u32_at(e, p)).unwrap_or(0);
out.push((subtype, String::from_utf8_lossy(&e[at + 4..end]).to_string()));
from = end.max(at + 4);
}
out
}
/// The reference attachments (type 100) of a model's control stream: the
/// file (full path, else file name), origin 192, rotation rows from 216,
/// scale 288, in UORs of the model.
fn references(control: &[u8]) -> Vec<DgnReference> {
elements(control)
.into_iter()
.filter(|e| kind(e) == 100 && e.len() >= 296)
.filter_map(|e| {
let strings = linked_strings(e);
let file = strings
.iter()
.find(|s| s.0 == 3)
.or_else(|| strings.iter().find(|s| s.0 == 2))?
.1
.clone();
Some(DgnReference {
file,
model: strings
.iter()
.find(|s| s.0 == 1)
.map(|s| s.1.clone())
.unwrap_or_default(),
origin: [f64_at(e, 192)?, f64_at(e, 200)?, f64_at(e, 208)?],
scale: f64_at(e, 288).filter(|s| *s > 0.0).unwrap_or(1.0),
rotation: f64_at(e, 240)?.atan2(f64_at(e, 216)?),
})
})
.collect()
}
pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
let cfb = Cfb::open(bytes)?;
let all = models(&cfb);
let (_, graphics, header) = all
let controls = control_streams(&cfb);
let designs: Vec<usize> = (0..all.len()).filter(|k| is_design(&all[*k].2)).collect();
let k = designs
.iter()
.find(|m| m.0.eq_ignore_ascii_case(name))
.or_else(|| all.first())?;
.copied()
.find(|k| all[*k].0.eq_ignore_ascii_case(name))
.or_else(|| designs.first().copied())?;
let (_, graphics, header) = &all[k];
let non_model = non_model(&cfb);
let nm = elements(&non_model);
let colors = nm
@@ -1184,6 +1469,7 @@ pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
(*id, (name.clone(), rgb))
})
.collect();
let level_order = table.iter().map(|l| l.0).collect();
let (per_unit, sub_uor) = units(header);
let s = 1.0 / per_unit;
let mut cells = Vec::new();
@@ -1195,8 +1481,12 @@ pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
while j < nm.len() && is_component(nm[j]) {
j += 1;
}
let def = read_run(&nm[i + 1..j], &styles, &IDENTITY).elements;
cells.push((cell, scaled_elements(&def, s, [0.0, 0.0])));
// The cell that draws points is the writer's own; the reference
// leaves it out of the drawing.
if !cell.eq_ignore_ascii_case("POINT_DISPLAY") {
let def = read_run(&nm[i + 1..j], &styles, &IDENTITY).elements;
cells.push((cell, scaled_elements(&def, s, [0.0, 0.0])));
}
i = j;
} else {
i += 1;
@@ -1210,13 +1500,29 @@ pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
(Some(n), Some(d)) if n > 0.0 && d > 0.0 => unit_name(d / n),
_ => String::new(),
};
let references = controls
.get(k)
.map(|c| references(c))
.unwrap_or_default()
.into_iter()
.map(|r| DgnReference {
origin: [
(r.origin[0] - origin[0]) * s,
(r.origin[1] - origin[1]) * s,
r.origin[2] * s,
],
..r
})
.collect();
Some(DgnImport {
elements: scaled_elements(&raw.elements, s, [-origin[0] * s, -origin[1] * s]),
cells,
levels,
level_order,
sub_per_master: per_unit / sub_uor,
unit_names: (metres(4180), metres(4196)),
v7: false,
references,
})
}
+15 -1
View File
@@ -20,7 +20,10 @@ use std::sync::{Arc, Mutex, OnceLock};
use codec::entities::UnderlayType;
pub use model::{scaled_elements, DgnElement, DgnGeom, DgnImport, Path, Segment, Sheet, SubPath};
pub use model::{
scaled_elements, By, DgnColor, DgnElement, DgnGeom, DgnImport, DgnReference, Path, Segment,
Sheet, SubPath, P3,
};
use super::pdf_raster::{source_bytes, PdfPage};
@@ -35,6 +38,17 @@ pub fn dgn_import(path: &str, item: &str) -> Option<DgnImport> {
}
}
/// The models DGNIMPORT offers: a V7 file's one model, a V8 file's design
/// models (sheet models are not imported).
pub fn dgn_import_models(path: &str) -> Option<Vec<String>> {
let bytes = source_bytes(path)?;
if dgn7::is_v7(&bytes) {
dgn7::model_names(&bytes)
} else {
dgn8::design_model_names(&bytes)
}
}
/// Sheet names (DWF) or model names (DGN) of a file.
pub fn item_names(kind: UnderlayType, path: &str) -> Option<Vec<String>> {
let bytes = source_bytes(path)?;
+126 -24
View File
@@ -532,55 +532,108 @@ pub fn dgn_color_table(e: &[u8], first: usize) -> Option<Vec<[u8; 3]>> {
Some(out)
}
/// A symbology attribute of a DGN element: the level's, the enclosing
/// cell's (V8 "by cell"), or its own.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum By<T> {
Level,
Cell,
Own(T),
}
impl<T> By<T> {
pub fn own(self) -> Option<T> {
match self {
By::Own(v) => Some(v),
_ => None,
}
}
}
/// An element's own colour: its index in the file's colour table, that
/// table entry's RGB and the RGB it is drawn in (a true colour can differ
/// from the table entry it names).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DgnColor {
pub index: u32,
pub table: [u8; 3],
pub rgb: [u8; 3],
}
/// A DGN element as drawing geometry (what DGNIMPORT converts): its level,
/// symbology and shape, in the units of the run that read it.
#[derive(Clone, Debug, PartialEq)]
pub struct DgnElement {
/// Level number (V7) or id (V8).
pub level: u32,
/// Colour; `None` takes the level's.
pub color: Option<[u8; 3]>,
/// Weight 0-31; `None` takes the level's.
pub weight: Option<u32>,
/// Line style; `None` takes the level's.
pub style: Option<u32>,
pub color: By<DgnColor>,
/// Weight 0-31.
pub weight: By<u32>,
/// Line style.
pub style: By<u32>,
pub geom: DgnGeom,
}
/// A point of a DGN element (z 0 in a 2D file).
pub type P3 = [f64; 3];
#[derive(Clone, Debug, PartialEq)]
pub enum DgnGeom {
Line([f64; 2], [f64; 2]),
/// A line string, curve or B-spline (sampled), or a shape (its points
/// end where they start).
Points(Vec<[f64; 2]>),
Line(P3, P3),
/// A line string, curve or shape (its points end where they start).
Points(Vec<P3>),
/// An elliptical arc: the point at parameter t is
/// `center + cos t · u + sin t · v`, from `start` over `sweep` (radians).
Arc {
center: [f64; 2],
u: [f64; 2],
v: [f64; 2],
center: P3,
u: P3,
v: P3,
start: f64,
sweep: f64,
},
/// A B-spline curve: degree, full knot vector and poles.
Spline {
degree: usize,
knots: Vec<f64>,
poles: Vec<P3>,
closed: bool,
},
/// A complex chain or shape: its components in order.
Chain(Vec<DgnGeom>),
Text {
text: String,
origin: [f64; 2],
/// The text's lower left (baseline start).
origin: P3,
height: f64,
width_factor: f64,
/// Length of the text along its baseline (its justification box).
length: f64,
rotation: f64,
/// DGN justification code (2 left bottom).
just: u8,
/// Font number (V7); `None` when the file's font is not read.
font: Option<u32>,
},
/// A text node: its lines.
TextNode(Vec<DgnGeom>),
/// A text node: its lines, its origin (the justification point, when
/// read), its justification and (V7) the space between its lines.
TextNode {
lines: Vec<DgnGeom>,
origin: Option<P3>,
just: u8,
line_spacing: Option<f64>,
},
/// A cell that is not shared: its name (empty when anonymous) and its
/// components, each with its own level and symbology.
CellGroup {
name: String,
parts: Vec<DgnElement>,
},
/// A shared cell instance: x' = m[0]·x + m[1]·y + origin.x,
/// y' = m[2]·x + m[3]·y + origin.y.
Cell {
name: String,
m: [f64; 4],
origin: [f64; 2],
origin: P3,
/// Scale along z (1 in a 2D file).
z_scale: f64,
},
@@ -589,8 +642,8 @@ pub enum DgnGeom {
impl DgnGeom {
/// The geometry through x' = s·x + t (lengths scaled by `s`).
pub fn scaled(&self, s: f64, t: [f64; 2]) -> DgnGeom {
let p = |q: [f64; 2]| [q[0] * s + t[0], q[1] * s + t[1]];
let v = |q: [f64; 2]| [q[0] * s, q[1] * s];
let p = |q: P3| [q[0] * s + t[0], q[1] * s + t[1], q[2] * s];
let v = |q: P3| [q[0] * s, q[1] * s, q[2] * s];
match self {
DgnGeom::Line(a, b) => DgnGeom::Line(p(*a), p(*b)),
DgnGeom::Points(pts) => DgnGeom::Points(pts.iter().map(|q| p(*q)).collect()),
@@ -607,23 +660,50 @@ impl DgnGeom {
start: *start,
sweep: *sweep,
},
DgnGeom::Spline {
degree,
knots,
poles,
closed,
} => DgnGeom::Spline {
degree: *degree,
knots: knots.clone(),
poles: poles.iter().map(|q| p(*q)).collect(),
closed: *closed,
},
DgnGeom::Chain(parts) => DgnGeom::Chain(parts.iter().map(|g| g.scaled(s, t)).collect()),
DgnGeom::TextNode(parts) => {
DgnGeom::TextNode(parts.iter().map(|g| g.scaled(s, t)).collect())
}
DgnGeom::CellGroup { name, parts } => DgnGeom::CellGroup {
name: name.clone(),
parts: scaled_elements(parts, s, t),
},
DgnGeom::TextNode {
lines,
origin,
just,
line_spacing,
} => DgnGeom::TextNode {
lines: lines.iter().map(|g| g.scaled(s, t)).collect(),
origin: origin.map(p),
just: *just,
line_spacing: line_spacing.map(|l| l * s),
},
DgnGeom::Text {
text,
origin,
height,
width_factor,
length,
rotation,
just,
font,
} => DgnGeom::Text {
text: text.clone(),
origin: p(*origin),
height: height * s,
width_factor: *width_factor,
length: length * s,
rotation: *rotation,
just: *just,
font: *font,
},
DgnGeom::Cell {
@@ -662,8 +742,12 @@ impl DgnCollector {
pub fn push(&mut self, element: DgnElement) {
if let Some((left, header)) = self.open.as_mut() {
if let DgnGeom::Chain(parts) | DgnGeom::TextNode(parts) = &mut header.geom {
parts.push(element.geom);
match &mut header.geom {
DgnGeom::Chain(parts) | DgnGeom::TextNode { lines: parts, .. } => {
parts.push(element.geom)
}
DgnGeom::CellGroup { parts, .. } => parts.push(element),
_ => {}
}
*left -= 1;
if *left == 0 {
@@ -690,11 +774,29 @@ pub struct DgnImport {
pub elements: Vec<DgnElement>,
pub cells: Vec<(String, Vec<DgnElement>)>,
pub levels: std::collections::HashMap<u32, (String, Option<[u8; 3]>)>,
/// Level ids in the file's level table order; a V8 file's levels all
/// become layers, used or not.
pub level_order: Vec<u32>,
pub sub_per_master: f64,
/// Master and sub unit names, when the file has them.
pub unit_names: (String, String),
/// A V7 file (its elements carry their own line style and weight).
pub v7: bool,
/// The model's reference attachments.
pub references: Vec<DgnReference>,
}
/// A reference attachment of a DGN model: the file and model it shows and
/// how it is placed (in master units of the attaching model).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DgnReference {
/// The file as the attachment names it.
pub file: String,
pub model: String,
pub origin: P3,
/// Scale of the reference's master units into the model's.
pub scale: f64,
pub rotation: f64,
}
/// The elements through x' = s·x + t.
+40 -8
View File
@@ -32,6 +32,8 @@ pub enum ImportDialogMsg {
DgnPrefix(bool),
DgnSub(bool),
DgnExplode(bool),
DgnReferences(crate::modules::insert::dgn_import::ReferenceMode),
DgnExisting(crate::modules::insert::dgn_import::ExistingReference),
DgnMappingTab(usize),
DgnOk,
Help(&'static str),
@@ -142,6 +144,8 @@ pub struct DgnImportState {
pub prefix_duplicates: bool,
pub sub_units: bool,
pub explode_text_nodes: bool,
pub references: crate::modules::insert::dgn_import::ReferenceMode,
pub existing_reference: crate::modules::insert::dgn_import::ExistingReference,
/// Master and sub unit names.
pub units: (String, String),
pub mapping_tab: usize,
@@ -564,21 +568,49 @@ pub fn view_dgn_import<'a>(
]
.spacing(8),
);
// The DGN readers do not read reference attachments, so their handling
// is shown but cannot be chosen.
use crate::modules::insert::dgn_import::{ExistingReference as E, ReferenceMode as R};
let translate = state.references == R::Translate;
let references = card(
t!("External DGN references").into_owned(),
column![
segmented(vec![
(t!("Bind as block / xref").into_owned(), false, None),
(t!("Ignore").into_owned(), true, None),
(t!("Attach as DGN underlay").into_owned(), false, None),
(
t!("Bind as block / xref").into_owned(),
translate,
Some(msg(ImportDialogMsg::DgnReferences(R::Translate)))
),
(
t!("Ignore").into_owned(),
state.references == R::Ignore,
Some(msg(ImportDialogMsg::DgnReferences(R::Ignore)))
),
(
t!("Attach as DGN underlay").into_owned(),
state.references == R::Underlay,
Some(msg(ImportDialogMsg::DgnReferences(R::Underlay)))
),
]),
text(t!("Reference attachments of DGN files are not read; they are left out."))
.size(11)
text(t!("When the translated drawing exists"))
.size(10)
.style(muted_style),
segmented(
[
(t!("Prompt to overwrite"), E::Prompt),
(t!("Overwrite without prompting"), E::Overwrite),
(t!("Do not overwrite"), E::Keep),
]
.into_iter()
.map(|(label, value)| {
(
label.into_owned(),
translate && state.existing_reference == value,
translate.then(|| msg(ImportDialogMsg::DgnExisting(value))),
)
})
.collect()
),
]
.spacing(8),
.spacing(6),
);
let tabs = [t!("Layer"), t!("Linetype"), t!("Lineweight"), t!("Color")];
let mut table = column![row![