forked from 1b-agent/opencadstudio-upstream
Merge pull request #1462 from ramox81:codex/xref-attach-parity
This commit is contained in:
commit
1988424638
47 files changed
+2716
-362
No files matched your search
+3
-2
@@ -74,8 +74,8 @@ const WEB_ALIAS_KEY: &str = "opencadstudio.aliases";
|
||||
/// defaults add aliases or change a default target, so existing profiles can be
|
||||
/// migrated forward (see `introduced_at` / `migrate_aliases`). Version 1 shipped
|
||||
/// the pre-REDRAW table; version 2 introduced the REDRAW-family aliases; version 3
|
||||
/// introduced HB (HATCHTOBACK).
|
||||
const DEFAULT_ALIASES_VERSION: u32 = 3;
|
||||
/// introduced HB (HATCHTOBACK); version 4 introduced ER (EXTERNALREFERENCES).
|
||||
const DEFAULT_ALIASES_VERSION: u32 = 4;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const WEB_ALIAS_VERSION_KEY: &str = "opencadstudio.aliases.version";
|
||||
@@ -93,6 +93,7 @@ fn introduced_at(version: u32) -> &'static [(&'static str, &'static str)] {
|
||||
("REA", "REGENALL"),
|
||||
],
|
||||
3 => &[("HB", "HATCHTOBACK")],
|
||||
4 => &[("ER", "EXTERNALREFERENCES")],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
+12
-55
@@ -3127,60 +3127,17 @@ impl OpenCADStudio {
|
||||
self.sync_dyn_fields();
|
||||
self.refresh_area_preview(i);
|
||||
}
|
||||
CmdResult::CommitAndExit(mut entity) => {
|
||||
// For XATTACH: ensure the xref block definition exists before
|
||||
// committing the INSERT entity that references it.
|
||||
// Extract path early to avoid borrow conflicts.
|
||||
let xattach_path: Option<String> = {
|
||||
let tab = &self.tabs[i];
|
||||
if let Some(cmd) = tab.active_cmd.as_ref() {
|
||||
if cmd.name() == "XATTACH" {
|
||||
cmd.xattach_path()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(path) = xattach_path {
|
||||
// XREF-Task6: the host drawing path lives in the tab
|
||||
// (`current_path`), not in `Scene`, so the self-attach
|
||||
// guard runs here via the pure `is_self_attach` helper.
|
||||
let host_file = self.tabs[i].current_path.clone();
|
||||
let host_base = host_file
|
||||
.as_deref()
|
||||
.and_then(|p| p.parent())
|
||||
.map(|p| p.to_path_buf());
|
||||
if let Some(host) = host_file.as_deref() {
|
||||
if crate::modules::insert::xattach::is_self_attach(
|
||||
host,
|
||||
&path,
|
||||
host_base.as_deref(),
|
||||
) {
|
||||
self.command_line.push_error(crate::t!("XATTACH: cannot attach the host drawing into itself.").as_ref());
|
||||
self.tabs[i].scene.clear_preview_wire();
|
||||
self.tabs[i].active_cmd = None;
|
||||
self.tabs[i].snap_result = None;
|
||||
self.restore_pre_cmd_tangent();
|
||||
return Task::none();
|
||||
}
|
||||
}
|
||||
let prepared_name = crate::modules::insert::xattach::prepare_xref_block(
|
||||
&mut self.tabs[i].scene,
|
||||
&path,
|
||||
host_base.as_deref(),
|
||||
);
|
||||
// `prepare_xref_block` may suffix a colliding stem. The
|
||||
// command was created before that collision was known, so
|
||||
// retarget its pending INSERT to the actual new block.
|
||||
if let acadrust::EntityType::Insert(insert) = &mut entity {
|
||||
insert.block_name = prepared_name;
|
||||
}
|
||||
// Resolving the xref merged its layer / linetype tables
|
||||
// into the document — mirror them into the Layers panel
|
||||
// and ribbon dropdowns now, not on the next reopen (#407).
|
||||
self.refresh_layer_panel();
|
||||
CmdResult::CommitAndExit(entity) => {
|
||||
// XATTACH: the definition and its INSERT are created together
|
||||
// in one undo step.
|
||||
let xattach_request = self.tabs[i]
|
||||
.active_cmd
|
||||
.as_ref()
|
||||
.filter(|cmd| cmd.name() == "XATTACH")
|
||||
.and_then(|cmd| cmd.xattach_request());
|
||||
if let Some(request) = xattach_request {
|
||||
self.commit_xref_attach(i, request, entity);
|
||||
return Task::none();
|
||||
}
|
||||
let insert_block_name = match &entity {
|
||||
acadrust::EntityType::Insert(ins) => Some(ins.block_name.clone()),
|
||||
@@ -9274,7 +9231,7 @@ impl OpenCADStudio {
|
||||
out
|
||||
}
|
||||
|
||||
fn restore_pre_cmd_tangent(&mut self) {
|
||||
pub(super) fn restore_pre_cmd_tangent(&mut self) {
|
||||
if let Some(was_on) = self.pre_cmd_tangent.take() {
|
||||
if !was_on {
|
||||
self.snapper.enabled.remove(&crate::snap::SnapType::Tangent);
|
||||
|
||||
@@ -663,10 +663,6 @@ impl OpenCADStudio {
|
||||
"PDFATTACH" => {
|
||||
return Some(Task::done(Message::PdfAttachPick));
|
||||
}
|
||||
"XATTACH" => {
|
||||
// Launch the file picker; XAttachPickResult will start the command.
|
||||
return Some(Task::done(Message::XAttachPick));
|
||||
}
|
||||
cmd if cmd == "WBLOCK" || cmd == "WB" || cmd.starts_with("WBLOCK ") => {
|
||||
let arg = cmd.splitn(2, ' ').nth(1).unwrap_or("").trim();
|
||||
if arg.is_empty() {
|
||||
@@ -1366,11 +1362,16 @@ impl OpenCADStudio {
|
||||
if after.is_empty() {
|
||||
return Some(Task::done(Message::XAttachPick));
|
||||
}
|
||||
let cmd = crate::modules::insert::xattach::XAttachCommand::with_path(
|
||||
after.to_string(),
|
||||
self.start_xref_attach(
|
||||
i,
|
||||
crate::modules::insert::xattach::XrefAttachRequest {
|
||||
path: after.trim_matches('"').to_string(),
|
||||
overlay: false,
|
||||
path_type: crate::io::xref_model::Pathtype::Full,
|
||||
},
|
||||
crate::modules::insert::xattach::XrefPlacement::on_screen(),
|
||||
"-XREF",
|
||||
);
|
||||
self.command_line.push_info(&cmd.prompt());
|
||||
self.tabs[i].active_cmd = Some(Box::new(cmd));
|
||||
} else {
|
||||
self.command_line.push_error(crate::tf!(
|
||||
"XREF: unknown option '{}'. Options: ? Reload Unload Detach Path Pathtype Bind Overlay Attach",
|
||||
|
||||
@@ -5,6 +5,7 @@ use iced::Task;
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod blocks;
|
||||
mod xref_attach;
|
||||
mod dim;
|
||||
pub(crate) mod display;
|
||||
mod draw;
|
||||
@@ -246,6 +247,9 @@ impl OpenCADStudio {
|
||||
if let Some(t) = self.dispatch_layers(cmd, i) {
|
||||
return Some(t);
|
||||
}
|
||||
if let Some(t) = self.dispatch_xref_attach(cmd, i) {
|
||||
return Some(t);
|
||||
}
|
||||
if let Some(t) = self.dispatch_blocks(cmd, i) {
|
||||
return Some(t);
|
||||
}
|
||||
@@ -652,6 +656,7 @@ inventory::submit!(crate::command::CommandRegistration {
|
||||
"3DORBIT",
|
||||
"3O",
|
||||
"ABOUT",
|
||||
"ATTACH",
|
||||
"ATTDISP",
|
||||
"ATTEXT",
|
||||
"BACKGROUND",
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//! Attaching drawing references: ATTACH / XATTACH (file picker, then the
|
||||
//! Attach External Reference dialog), the -XREF command line, the `?` list,
|
||||
//! and the commit that creates the definition and its INSERT as one undo step.
|
||||
|
||||
use super::*;
|
||||
use crate::io::xref_model::Pathtype;
|
||||
use crate::modules::insert::xattach::{
|
||||
existing_reference, path_to_block_name, prepare_xref_definition, stored_path,
|
||||
XAttachCommand, XrefAttachRequest, XrefPlacement,
|
||||
};
|
||||
use crate::modules::insert::xref_cmd::display_path;
|
||||
use crate::ui::window::xref_attach::{XrefAttachMsg, XrefAttachState};
|
||||
|
||||
impl OpenCADStudio {
|
||||
/// Commands owned here; `None` defers to the other families.
|
||||
pub(super) fn dispatch_xref_attach(&mut self, cmd: &str, i: usize) -> Option<Task<Message>> {
|
||||
let upper = cmd.to_ascii_uppercase();
|
||||
let (verb, rest) = match cmd.split_once(char::is_whitespace) {
|
||||
Some((verb, rest)) => (verb.to_ascii_uppercase(), rest.trim()),
|
||||
None => (upper.clone(), ""),
|
||||
};
|
||||
match (verb.as_str(), rest.is_empty()) {
|
||||
("ATTACH", true) => Some(Task::done(Message::AttachPick)),
|
||||
("XATTACH", true) => Some(Task::done(Message::XAttachPick)),
|
||||
// A file named on the command line skips the picker.
|
||||
// Handled at once, so the placement it starts belongs to this
|
||||
// command line (automation included).
|
||||
("ATTACH", false) => Some(self.update(Message::AttachPickResult(Ok(
|
||||
std::path::PathBuf::from(rest.trim_matches('"')),
|
||||
)))),
|
||||
("XATTACH", false) => {
|
||||
self.open_xref_attach_dialog(std::path::PathBuf::from(rest.trim_matches('"')));
|
||||
Some(Task::none())
|
||||
}
|
||||
// XREF opens the External References palette; -XREF asks on the
|
||||
// command line. Both keep their argument forms for scripts.
|
||||
("XREF", true) | ("XREFSHOW", true) => {
|
||||
if !self.show_external_references {
|
||||
return self.dispatch_blocks("EXTERNALREFERENCES", i);
|
||||
}
|
||||
self.refresh_xref_manager();
|
||||
Some(self.finish_dispatch(cmd))
|
||||
}
|
||||
("-XREF", true) => {
|
||||
let saved: Vec<(String, String)> = self.tabs[i]
|
||||
.scene
|
||||
.document
|
||||
.block_records
|
||||
.iter()
|
||||
.filter(|br| br.flags.is_xref || br.flags.is_xref_overlay)
|
||||
.map(|br| (br.name.clone(), br.xref_path.clone()))
|
||||
.collect();
|
||||
let command = crate::modules::insert::xref_cmd::XrefCommand::new(saved);
|
||||
self.command_line.push_info(&command.prompt());
|
||||
self.tabs[i].active_cmd = Some(Box::new(command));
|
||||
Some(Task::none())
|
||||
}
|
||||
("XREFLIST", _) => {
|
||||
self.list_xrefs(i, if rest.is_empty() { "*" } else { rest });
|
||||
Some(self.finish_dispatch(cmd))
|
||||
}
|
||||
("XREFATTACHFILE", false) | ("XREFOVERLAYFILE", false) => {
|
||||
let request = XrefAttachRequest {
|
||||
path: rest.trim_matches('"').to_string(),
|
||||
overlay: verb == "XREFOVERLAYFILE",
|
||||
// The reference default (REFPATHTYPE 1): relative once the
|
||||
// drawing is saved, the full path before that.
|
||||
path_type: Pathtype::Relative,
|
||||
};
|
||||
self.start_xref_attach(i, request, XrefPlacement::on_screen(), "-XREF");
|
||||
Some(Task::none())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `-XREF ?` — the reference table as the reference application prints it.
|
||||
fn list_xrefs(&mut self, i: usize, pattern: &str) {
|
||||
let rows: Vec<(String, &'static str, String)> = self.tabs[i]
|
||||
.scene
|
||||
.document
|
||||
.block_records
|
||||
.iter()
|
||||
.filter(|br| br.flags.is_xref || br.flags.is_xref_overlay)
|
||||
.filter(|br| {
|
||||
pattern == "*" || crate::io::xref_model::wildcard_match(&br.name, pattern)
|
||||
})
|
||||
.map(|br| {
|
||||
let kind = if br.flags.is_xref_overlay { "Overlay" } else { "Attach" };
|
||||
(br.name.clone(), kind, display_path(&br.xref_path))
|
||||
})
|
||||
.collect();
|
||||
let out = &mut self.command_line;
|
||||
out.push_output("");
|
||||
out.push_output(&format!(
|
||||
"{:<34}{:<13}{}",
|
||||
"Xref name",
|
||||
"Xref Type",
|
||||
"Path"
|
||||
));
|
||||
out.push_output(&format!("{:<34}{:<13}{}", "----------------------", "---------", "----------"));
|
||||
out.push_output("");
|
||||
for (name, kind, path) in &rows {
|
||||
out.push_output(&format!("{:<34}{:<13}{}", format!("\"{name}\""), *kind, path));
|
||||
}
|
||||
out.push_output("");
|
||||
out.push_output(&format!("Total Xref(s): {}", rows.len()));
|
||||
}
|
||||
|
||||
/// Checks the file, reports it the way the reference does, then asks
|
||||
/// for whatever is left on-screen (or commits straight away).
|
||||
pub(in crate::app) fn start_xref_attach(
|
||||
&mut self,
|
||||
i: usize,
|
||||
request: XrefAttachRequest,
|
||||
placement: XrefPlacement,
|
||||
label: &'static str,
|
||||
) {
|
||||
let name = path_to_block_name(&request.path);
|
||||
let full = crate::modules::insert::xattach::resolve_xref_store_path(&request.path, None);
|
||||
let host = self.tabs[i].current_path.clone();
|
||||
if let Some(host) = host.as_deref() {
|
||||
if crate::modules::insert::xattach::is_self_attach(host, &full, host.parent()) {
|
||||
self.command_line.push_error(
|
||||
"Error: Possible circular reference to current drawing. *Invalid*",
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let existing = existing_reference(&self.tabs[i].scene, &name);
|
||||
if let Some(existing) = existing.as_ref() {
|
||||
self.command_line
|
||||
.push_output(&format!("Xref \"{}\" has already been defined.", existing));
|
||||
self.command_line
|
||||
.push_output("Using existing definition.");
|
||||
} else {
|
||||
let verb = if request.overlay {
|
||||
format!("Overlay Xref \"{}\": {}", name, display_path(&full))
|
||||
} else {
|
||||
format!("Attach Xref \"{}\": {}", name, display_path(&full))
|
||||
};
|
||||
self.command_line.push_output(&verb);
|
||||
if !std::path::Path::new(&full).is_file() {
|
||||
let file = std::path::Path::new(&full.replace('\\', "/"))
|
||||
.file_name()
|
||||
.map(|f| f.to_string_lossy().into_owned())
|
||||
.unwrap_or(full.clone());
|
||||
self.command_line
|
||||
.push_output(&format!("\"{}\" cannot be found.", file));
|
||||
self.command_line.push_error("*Invalid*");
|
||||
return;
|
||||
}
|
||||
self.command_line
|
||||
.push_output(&format!("\"{}\" loaded.", name));
|
||||
}
|
||||
let command = XAttachCommand::new(request.clone(), placement, label);
|
||||
if let Some(entity) = command.immediate() {
|
||||
self.commit_xref_attach(i, request, entity);
|
||||
return;
|
||||
}
|
||||
let (wires, source_units) = self.xref_preview(i, existing.as_deref(), &full);
|
||||
let host_units = self.tabs[i].scene.document.header.insertion_units;
|
||||
let unit = crate::app::properties::insert_unit_scale(host_units, source_units).unwrap_or(1.0);
|
||||
let command = command.with_preview(wires, unit);
|
||||
self.command_line.push_info(&command.prompt());
|
||||
self.tabs[i].active_cmd = Some(Box::new(command));
|
||||
}
|
||||
|
||||
/// The reference's geometry for the placement ghost, in its own units:
|
||||
/// an existing definition's content, or the file's model space.
|
||||
fn xref_preview(
|
||||
&self,
|
||||
i: usize,
|
||||
existing: Option<&str>,
|
||||
path: &str,
|
||||
) -> (Vec<crate::scene::model::wire_model::WireModel>, i16) {
|
||||
// ponytail: a huge reference skips the ghost; cap by entity count.
|
||||
const MAX_PREVIEW_ENTITIES: usize = 20_000;
|
||||
let scene = &self.tabs[i].scene;
|
||||
if let Some(name) = existing {
|
||||
let units = scene
|
||||
.document
|
||||
.block_records
|
||||
.get(name)
|
||||
.map(|br| br.units)
|
||||
.unwrap_or(0);
|
||||
return (scene.block_preview_wires(name), units);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Ok(source) = crate::io::load_file(std::path::Path::new(path)) {
|
||||
let owner = source.header.model_space_block_handle;
|
||||
let entities: Vec<acadrust::EntityType> = source
|
||||
.entities()
|
||||
.filter(|e| e.common().owner_handle == owner)
|
||||
.filter(|e| {
|
||||
!matches!(
|
||||
e,
|
||||
acadrust::EntityType::Block(_) | acadrust::EntityType::BlockEnd(_)
|
||||
)
|
||||
})
|
||||
.take(MAX_PREVIEW_ENTITIES + 1)
|
||||
.cloned()
|
||||
.collect();
|
||||
if entities.len() <= MAX_PREVIEW_ENTITIES {
|
||||
return (
|
||||
scene.wires_for_entities(&entities),
|
||||
source.header.insertion_units,
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = path;
|
||||
(Vec::new(), 0)
|
||||
}
|
||||
|
||||
/// Creates (or reuses) the definition and commits its INSERT — one undo
|
||||
/// step for both, so undo leaves no definition behind.
|
||||
pub(in crate::app) fn commit_xref_attach(
|
||||
&mut self,
|
||||
i: usize,
|
||||
request: XrefAttachRequest,
|
||||
mut entity: acadrust::EntityType,
|
||||
) {
|
||||
let pending = self.begin_undo(i, "XATTACH", 1, false);
|
||||
let host = self.tabs[i].current_path.clone();
|
||||
let name = prepare_xref_definition(&mut self.tabs[i].scene, &request, host.as_deref());
|
||||
if host.is_none() && request.path_type == Pathtype::Relative {
|
||||
self.tabs[i].xref_relative_on_save.insert(name.clone());
|
||||
}
|
||||
if let acadrust::EntityType::Insert(insert) = &mut entity {
|
||||
insert.block_name = name;
|
||||
}
|
||||
// Resolving merged the reference's layers and linetypes — mirror
|
||||
// them into the Layers panel and ribbon dropdowns now (#407).
|
||||
self.refresh_layer_panel();
|
||||
let _ = self.commit_entity_handle(entity);
|
||||
self.tabs[i].dirty = true;
|
||||
self.tabs[i].scene.clear_preview_wire();
|
||||
self.tabs[i].active_cmd = None;
|
||||
self.tabs[i].snap_result = None;
|
||||
self.restore_pre_cmd_tangent();
|
||||
if let Some(pending) = pending {
|
||||
self.commit_undo_delta(i, pending);
|
||||
}
|
||||
self.refresh_xref_manager();
|
||||
}
|
||||
|
||||
/// Opens the Attach External Reference dialog for `path`.
|
||||
pub(in crate::app) fn open_xref_attach_dialog(&mut self, path: std::path::PathBuf) {
|
||||
let i = self.active_tab;
|
||||
let existing: Vec<(String, String)> = self.tabs[i]
|
||||
.scene
|
||||
.document
|
||||
.block_records
|
||||
.iter()
|
||||
.filter(|br| br.flags.is_xref || br.flags.is_xref_overlay)
|
||||
.map(|br| (br.name.clone(), br.xref_path.clone()))
|
||||
.collect();
|
||||
let mut state = XrefAttachState::new(existing);
|
||||
self.load_xref_attach_file(&mut state, &path.to_string_lossy());
|
||||
self.xref_attach = Some(state);
|
||||
self.active_modal = Some(crate::app::ModalKind::XrefAttach);
|
||||
}
|
||||
|
||||
/// Fills the dialog from the chosen file: name, preview, block unit and
|
||||
/// the paths shown under Details.
|
||||
fn load_xref_attach_file(&self, state: &mut XrefAttachState, path: &str) {
|
||||
let i = self.active_tab;
|
||||
state.path = path.to_string();
|
||||
state.name = path_to_block_name(path);
|
||||
state.found_in = display_path(path);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
state.preview = crate::io::thumbnail::read_handle(std::path::Path::new(path));
|
||||
let host_units = self.tabs[i].scene.document.header.insertion_units;
|
||||
let source_units = crate::io::load_file(std::path::Path::new(path))
|
||||
.map(|doc| doc.header.insertion_units)
|
||||
.unwrap_or(0);
|
||||
state.unit_label = crate::t!(crate::app::properties::insunits_name(source_units))
|
||||
.into_owned();
|
||||
let factor =
|
||||
crate::app::properties::insert_unit_scale(host_units, source_units).unwrap_or(1.0);
|
||||
state.unit_factor = crate::app::properties::format_unit_factor(factor);
|
||||
}
|
||||
self.refresh_xref_attach_saved_path(state);
|
||||
}
|
||||
|
||||
fn refresh_xref_attach_saved_path(&self, state: &mut XrefAttachState) {
|
||||
let host = self.tabs[self.active_tab].current_path.clone();
|
||||
let request = XrefAttachRequest {
|
||||
path: state.path.clone(),
|
||||
overlay: state.overlay,
|
||||
path_type: state.path_type.0,
|
||||
};
|
||||
state.saved_path = display_path(&stored_path(&request, host.as_deref()));
|
||||
}
|
||||
|
||||
/// Messages of the ATTACH picker and the dialog.
|
||||
pub(in crate::app) fn update_xref_attach(&mut self, message: Message) -> Task<Message> {
|
||||
match message {
|
||||
Message::AttachPick => Task::perform(
|
||||
async {
|
||||
let handle = crate::sys::file_dialog()
|
||||
.set_title(crate::t!("Select Reference File").as_ref())
|
||||
.add_filter(
|
||||
crate::t!("All Reference Files").as_ref(),
|
||||
&[
|
||||
"dwg", "dxf", "pdf", "png", "jpg", "jpeg", "bmp", "tif", "tiff",
|
||||
],
|
||||
)
|
||||
.add_filter(crate::t!("Drawing").as_ref(), &["dwg", "dxf"])
|
||||
.add_filter(crate::t!("PDF Files").as_ref(), &["pdf"])
|
||||
.add_filter(
|
||||
crate::t!("Images").as_ref(),
|
||||
&["png", "jpg", "jpeg", "bmp", "tif", "tiff"],
|
||||
)
|
||||
.pick_file()
|
||||
.await;
|
||||
match handle {
|
||||
Some(h) => Ok(crate::sys::handle_path(&h)),
|
||||
None => Err("Cancelled".to_string()),
|
||||
}
|
||||
},
|
||||
Message::AttachPickResult,
|
||||
),
|
||||
Message::AttachPickResult(Ok(path)) => {
|
||||
let ext = path
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
match ext.as_str() {
|
||||
"pdf" => match std::fs::read(&path) {
|
||||
Ok(bytes) => self.update(Message::PdfAttachPickResult(Ok((
|
||||
path,
|
||||
std::sync::Arc::new(bytes),
|
||||
)))),
|
||||
Err(e) => self.update(Message::PdfAttachPickResult(Err(e.to_string()))),
|
||||
},
|
||||
"png" | "jpg" | "jpeg" | "bmp" | "tif" | "tiff" => {
|
||||
let result = image::image_dimensions(&path)
|
||||
.map(|(w, h)| (path.clone(), w, h))
|
||||
.map_err(|e| e.to_string());
|
||||
self.update(Message::ImagePickResult(result))
|
||||
}
|
||||
_ => {
|
||||
self.open_xref_attach_dialog(path);
|
||||
Task::none()
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::AttachPickResult(Err(e)) => {
|
||||
if e != "Cancelled" {
|
||||
self.command_line
|
||||
.push_error(format!("ATTACH: {e}").as_ref());
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::XrefAttachBrowseResult(Ok(path)) => {
|
||||
if let Some(mut state) = self.xref_attach.take() {
|
||||
self.load_xref_attach_file(&mut state, &path.to_string_lossy());
|
||||
self.xref_attach = Some(state);
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::XrefAttachBrowseResult(Err(_)) => Task::none(),
|
||||
Message::XrefAttach(edit) => self.edit_xref_attach(edit),
|
||||
_ => Task::none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_xref_attach(&mut self, edit: XrefAttachMsg) -> Task<Message> {
|
||||
let Some(mut state) = self.xref_attach.take() else {
|
||||
return Task::none();
|
||||
};
|
||||
let mut task = Task::none();
|
||||
match edit {
|
||||
XrefAttachMsg::Name(name) => {
|
||||
if let Some((_, saved)) = state
|
||||
.existing
|
||||
.iter()
|
||||
.find(|(n, _)| n.eq_ignore_ascii_case(&name))
|
||||
.cloned()
|
||||
{
|
||||
let host = self.tabs[self.active_tab].current_path.clone();
|
||||
let base = host.as_deref().and_then(|h| h.parent());
|
||||
let full = crate::modules::insert::xattach::resolve_xref_store_path(&saved, base);
|
||||
self.load_xref_attach_file(&mut state, &full);
|
||||
}
|
||||
}
|
||||
XrefAttachMsg::Browse => {
|
||||
task = Task::perform(
|
||||
async {
|
||||
let handle = crate::sys::file_dialog()
|
||||
.set_title(crate::t!("Select Reference File").as_ref())
|
||||
.add_filter(crate::t!("Drawing").as_ref(), &["dwg", "dxf"])
|
||||
.pick_file()
|
||||
.await;
|
||||
match handle {
|
||||
Some(h) => Ok(crate::sys::handle_path(&h)),
|
||||
None => Err("Cancelled".to_string()),
|
||||
}
|
||||
},
|
||||
Message::XrefAttachBrowseResult,
|
||||
);
|
||||
}
|
||||
XrefAttachMsg::Overlay(overlay) => state.overlay = overlay,
|
||||
XrefAttachMsg::ScaleOnScreen(on) => state.scale_on_screen = on,
|
||||
XrefAttachMsg::Scale(axis, value) => {
|
||||
if axis == 0 && state.uniform {
|
||||
state.scale = [value.clone(), value.clone(), value];
|
||||
} else if let Some(slot) = state.scale.get_mut(axis) {
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
XrefAttachMsg::Uniform(on) => {
|
||||
state.uniform = on;
|
||||
if on {
|
||||
let x = state.scale[0].clone();
|
||||
state.scale = [x.clone(), x.clone(), x];
|
||||
}
|
||||
}
|
||||
XrefAttachMsg::InsertOnScreen(on) => state.insert_on_screen = on,
|
||||
XrefAttachMsg::Insert(axis, value) => {
|
||||
if let Some(slot) = state.insert.get_mut(axis) {
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
XrefAttachMsg::PathType(choice) => {
|
||||
state.path_type = choice;
|
||||
self.refresh_xref_attach_saved_path(&mut state);
|
||||
}
|
||||
XrefAttachMsg::RotationOnScreen(on) => state.rotation_on_screen = on,
|
||||
XrefAttachMsg::Rotation(value) => state.rotation = value,
|
||||
XrefAttachMsg::Details(on) => state.details = on,
|
||||
XrefAttachMsg::Help => {
|
||||
self.command_line.push_info(
|
||||
crate::t!("Inserts references to external files such as other drawings, raster images, and underlays.")
|
||||
.as_ref(),
|
||||
);
|
||||
}
|
||||
XrefAttachMsg::Apply => {
|
||||
let placement = XrefPlacement {
|
||||
insert: (!state.insert_on_screen)
|
||||
.then(|| state.insert_point())
|
||||
.flatten(),
|
||||
scale: (!state.scale_on_screen).then(|| state.scale_values()).flatten(),
|
||||
rotation: (!state.rotation_on_screen)
|
||||
.then(|| crate::entities::common::parse_typed_angle(&state.rotation))
|
||||
.flatten()
|
||||
.map(f64::to_degrees),
|
||||
};
|
||||
let invalid = (!state.insert_on_screen && placement.insert.is_none())
|
||||
|| (!state.scale_on_screen
|
||||
&& placement
|
||||
.scale
|
||||
.is_none_or(|s| s.iter().any(|v| *v == 0.0)))
|
||||
|| (!state.rotation_on_screen && placement.rotation.is_none());
|
||||
if invalid || state.path.is_empty() {
|
||||
self.command_line
|
||||
.push_error(crate::t!("Invalid input.").as_ref());
|
||||
self.xref_attach = Some(state);
|
||||
return Task::none();
|
||||
}
|
||||
let request = XrefAttachRequest {
|
||||
path: state.path.clone(),
|
||||
overlay: state.overlay,
|
||||
path_type: state.path_type.0,
|
||||
};
|
||||
self.active_modal = None;
|
||||
let i = self.active_tab;
|
||||
self.start_xref_attach(i, request, placement, "XATTACH");
|
||||
return Task::none();
|
||||
}
|
||||
}
|
||||
self.xref_attach = Some(state);
|
||||
task
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ fn color_value(color: acadrust::types::Color) -> Value {
|
||||
}
|
||||
pub(super) const NAMES: &[&str] = &[
|
||||
"close_modal",
|
||||
"dialog_ok",
|
||||
"close_document",
|
||||
"toggle_properties",
|
||||
"toggle_layers",
|
||||
@@ -663,6 +664,14 @@ impl OpenCADStudio {
|
||||
let name = string(req, "name")?;
|
||||
let msg = match name {
|
||||
"close_modal" => Message::CloseModal,
|
||||
// The open dialog's OK button.
|
||||
"dialog_ok" => match self.active_modal {
|
||||
Some(crate::app::ModalKind::XrefAttach) => Message::XrefAttach(
|
||||
crate::ui::window::xref_attach::XrefAttachMsg::Apply,
|
||||
),
|
||||
Some(crate::app::ModalKind::BlockDefinition) => Message::BlockDefApply,
|
||||
_ => return Err(failure("no_dialog", "No dialog with an OK button is open")),
|
||||
},
|
||||
"close_document" => Message::TabClose(self.active_tab),
|
||||
"toggle_properties" => Message::ToggleProperties,
|
||||
"toggle_layers" => Message::ToggleLayers,
|
||||
|
||||
@@ -231,6 +231,9 @@ pub(super) struct DocumentTab {
|
||||
/// Session set of unloaded reference keys (Task 8b). Owns the set that
|
||||
/// `collect_entries` takes as `unloaded`, so CLI and palette agree.
|
||||
pub(super) xref_unloaded: crate::io::xref_model::UnloadSet,
|
||||
/// References attached with a relative path while the drawing had no
|
||||
/// file yet: stored full until the first save, then made relative.
|
||||
pub(super) xref_relative_on_save: rustc_hash::FxHashSet<String>,
|
||||
/// Load-time mtimes per reference key (Task 8b). Written on every
|
||||
/// palette refresh; `Stale` is detectable from the second refresh on.
|
||||
pub(super) xref_stat_cache: crate::io::xref_model::RefStatCache,
|
||||
@@ -650,6 +653,7 @@ impl DocumentTab {
|
||||
active_mleader_style: "Standard".to_string(),
|
||||
last_synced_camera_gen: 0,
|
||||
xref_unloaded: crate::io::xref_model::UnloadSet::default(),
|
||||
xref_relative_on_save: rustc_hash::FxHashSet::default(),
|
||||
xref_stat_cache: crate::io::xref_model::RefStatCache::default(),
|
||||
xref_missing: 0,
|
||||
is_start: false,
|
||||
|
||||
@@ -493,6 +493,8 @@ pub(super) struct OpenCADStudio {
|
||||
drawing_units: Option<crate::ui::window::drawing_units::State>,
|
||||
/// Working copy of the Block Definition dialog; `None` while it is closed.
|
||||
block_definition: Option<crate::ui::window::block_definition::BlockDefinitionState>,
|
||||
/// Working copy of the Attach External Reference dialog; None while closed.
|
||||
xref_attach: Option<crate::ui::window::xref_attach::XrefAttachState>,
|
||||
/// Working copy of the structured feature-control-frame editor.
|
||||
geometric_tolerance: Option<crate::ui::window::geometric_tolerance::State>,
|
||||
/// PICKDRAG (#226): false (default) = press-drag lassoes; true =
|
||||
@@ -1880,6 +1882,7 @@ pub enum ModalKind {
|
||||
LayerTranslator,
|
||||
DrawingUnits,
|
||||
BlockDefinition,
|
||||
XrefAttach,
|
||||
GeometricTolerance,
|
||||
DraftingSettings,
|
||||
AutoConstrainSettings,
|
||||
@@ -3788,6 +3791,14 @@ pub enum Message {
|
||||
XAttachPick,
|
||||
/// Result of the XATTACH file picker.
|
||||
XAttachPickResult(Result<std::path::PathBuf, String>),
|
||||
/// ATTACH: pick a drawing, image or PDF to reference.
|
||||
AttachPick,
|
||||
/// Result of the ATTACH file picker.
|
||||
AttachPickResult(Result<std::path::PathBuf, String>),
|
||||
/// An edit in the Attach External Reference dialog.
|
||||
XrefAttach(crate::ui::window::xref_attach::XrefAttachMsg),
|
||||
/// Result of the dialog's Browse picker.
|
||||
XrefAttachBrowseResult(Result<std::path::PathBuf, String>),
|
||||
// ── WBLOCK ────────────────────────────────────────────────────────────
|
||||
/// Trigger the WBLOCK save dialog for `block_name` (or `*` = selection).
|
||||
WblockSave(String),
|
||||
@@ -3950,6 +3961,7 @@ impl OpenCADStudio {
|
||||
layer_translator: None,
|
||||
drawing_units: None,
|
||||
block_definition: None,
|
||||
xref_attach: None,
|
||||
geometric_tolerance: None,
|
||||
pick_drag_rect: false,
|
||||
perf_hud: false,
|
||||
|
||||
+85
-3
@@ -1478,6 +1478,25 @@ impl OpenCADStudio {
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(br) = doc
|
||||
.block_records
|
||||
.get(&ins.block_name)
|
||||
.filter(|br| br.flags.is_xref || br.flags.is_xref_overlay)
|
||||
{
|
||||
let base_dir = self.tabs[i]
|
||||
.current_path
|
||||
.as_deref()
|
||||
.and_then(|p| p.parent())
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||
let overrides = crate::io::xref::layer_overrides(
|
||||
doc,
|
||||
&br.name,
|
||||
&br.xref_path,
|
||||
&base_dir,
|
||||
);
|
||||
xref_rows(&mut sections, ins, &br.xref_path, factor, overrides);
|
||||
}
|
||||
}
|
||||
// Underlay: name + path from the referenced definition.
|
||||
acadrust::EntityType::Underlay(ul) => {
|
||||
@@ -3702,6 +3721,69 @@ fn merge_prop_value(
|
||||
/// Set the first property row matching `field` (across all sections) to a
|
||||
/// read-only `value`. No-op when the field is absent. Used to fill the
|
||||
/// doc-dependent placeholder rows the entity builders leave empty.
|
||||
/// An external reference's rows as the reference application lists them:
|
||||
/// Insertion point X/Y/Z, Scale X/Y/Z without the unit conversion the INSERT
|
||||
/// carries (no uniform-scale or Annotative rows), Saved Path after the name
|
||||
/// and Layer property overrides last.
|
||||
fn xref_rows(
|
||||
sections: &mut [crate::scene::model::object::PropSection],
|
||||
ins: &acadrust::entities::Insert,
|
||||
saved_path: &str,
|
||||
factor: f64,
|
||||
overrides: bool,
|
||||
) {
|
||||
use crate::entities::common::{edit_prop, ro_prop};
|
||||
let factor = if factor.abs() > 0.0 { factor } else { 1.0 };
|
||||
for section in sections.iter_mut() {
|
||||
for prop in section.props.iter_mut() {
|
||||
let label = match prop.field {
|
||||
"ins_x" => "Insertion point X",
|
||||
"ins_y" => "Insertion point Y",
|
||||
"ins_z" => "Insertion point Z",
|
||||
_ => continue,
|
||||
};
|
||||
prop.label = t!(label).into_owned();
|
||||
}
|
||||
let scale_at = section.props.iter().position(|p| {
|
||||
matches!(p.field, "x_scale" | "y_scale" | "z_scale" | "u_scale" | "ins_uniform")
|
||||
});
|
||||
section.props.retain(|p| {
|
||||
!matches!(
|
||||
p.field,
|
||||
"x_scale" | "y_scale" | "z_scale" | "u_scale" | "ins_uniform" | "annotative"
|
||||
)
|
||||
});
|
||||
if let Some(at) = scale_at {
|
||||
let at = at.min(section.props.len());
|
||||
section.props.splice(
|
||||
at..at,
|
||||
[
|
||||
edit_prop(t!("Scale X").as_ref(), "xref_x_scale", ins.x_scale() / factor),
|
||||
edit_prop(t!("Scale Y").as_ref(), "xref_y_scale", ins.y_scale() / factor),
|
||||
edit_prop(t!("Scale Z").as_ref(), "xref_z_scale", ins.z_scale() / factor),
|
||||
],
|
||||
);
|
||||
}
|
||||
if let Some(at) = section.props.iter().position(|p| p.field == "block") {
|
||||
section.props.insert(
|
||||
at + 1,
|
||||
ro_prop(
|
||||
t!("Saved Path").as_ref(),
|
||||
"xref_saved_path",
|
||||
crate::modules::insert::xref_cmd::display_path(saved_path),
|
||||
),
|
||||
);
|
||||
}
|
||||
if section.props.iter().any(|p| p.field == "unit_factor") {
|
||||
section.props.push(ro_prop(
|
||||
t!("Layer property overrides").as_ref(),
|
||||
"xref_layer_overrides",
|
||||
if overrides { t!("Yes") } else { t!("No") }.into_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_row(sections: &mut [crate::scene::model::object::PropSection], field: &str, value: String) {
|
||||
for section in sections.iter_mut() {
|
||||
if let Some(row) = section.props.iter_mut().find(|p| p.field == field) {
|
||||
@@ -4092,7 +4174,7 @@ fn dim_lineweight_label(dimlwd: i16) -> String {
|
||||
}
|
||||
|
||||
/// Human-readable INSUNITS name (DXF group 70 unit codes).
|
||||
fn insunits_name(code: i16) -> &'static str {
|
||||
pub(in crate::app) fn insunits_name(code: i16) -> &'static str {
|
||||
match code {
|
||||
1 => "Inches",
|
||||
2 => "Feet",
|
||||
@@ -4124,7 +4206,7 @@ fn insunits_name(code: i16) -> &'static str {
|
||||
}
|
||||
|
||||
/// Unit-conversion scale for a new INSERT.
|
||||
fn insert_unit_scale(host_units: i16, src_units: i16) -> Option<f64> {
|
||||
pub(in crate::app) fn insert_unit_scale(host_units: i16, src_units: i16) -> Option<f64> {
|
||||
let host_mm = insunits_to_mm(host_units)?;
|
||||
let src_mm = insunits_to_mm(src_units)?;
|
||||
let ratio = src_mm / host_mm;
|
||||
@@ -4134,7 +4216,7 @@ fn insert_unit_scale(host_units: i16, src_units: i16) -> Option<f64> {
|
||||
Some(ratio)
|
||||
}
|
||||
|
||||
fn format_unit_factor(factor: f64) -> String {
|
||||
pub(in crate::app) fn format_unit_factor(factor: f64) -> String {
|
||||
let magnitude = factor.abs();
|
||||
if magnitude > 0.0 && !(1.0e-4..1.0e7).contains(&magnitude) {
|
||||
format!("{factor:.4e}")
|
||||
|
||||
@@ -3515,6 +3515,46 @@ pub(super) fn on_tab_close(&mut self, idx: usize) -> Task<Message> {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(axis) = match field {
|
||||
"xref_x_scale" => Some(0),
|
||||
"xref_y_scale" => Some(1),
|
||||
"xref_z_scale" => Some(2),
|
||||
_ => None,
|
||||
} {
|
||||
// An xref's Scale rows show the scale without the
|
||||
// unit conversion its INSERT carries; write it back
|
||||
// with that conversion.
|
||||
let value = val
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite() && *v != 0.0);
|
||||
if let Some(value) = value {
|
||||
let host = self.tabs[i].scene.document.header.insertion_units;
|
||||
for &handle in &handles {
|
||||
let factor = match self.tabs[i].scene.document.get_entity(handle) {
|
||||
Some(acadrust::EntityType::Insert(ins)) => self.tabs[i]
|
||||
.scene
|
||||
.document
|
||||
.block_records
|
||||
.get(&ins.block_name)
|
||||
.and_then(|br| {
|
||||
crate::app::properties::insert_unit_scale(host, br.units)
|
||||
})
|
||||
.unwrap_or(1.0),
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(acadrust::EntityType::Insert(ins)) =
|
||||
self.tabs[i].scene.document.get_entity_mut(handle)
|
||||
{
|
||||
match axis {
|
||||
0 => ins.set_x_scale(value * factor),
|
||||
1 => ins.set_y_scale(value * factor),
|
||||
_ => ins.set_z_scale(value * factor),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if field == "block" {
|
||||
// Name row on a block reference: an existing name
|
||||
// re-points the selected inserts; a new one renames
|
||||
|
||||
+19
-1
@@ -2149,7 +2149,8 @@ impl OpenCADStudio {
|
||||
}
|
||||
|
||||
let mut recent_task = Task::none();
|
||||
let saved = match crate::io::save_to_bytes(&self.tabs[i].scene.document, &ext, version) {
|
||||
let document = self.tabs[i].scene.document_for_save();
|
||||
let saved = match crate::io::save_to_bytes(&document, &ext, version) {
|
||||
Ok(bytes) => {
|
||||
crate::sys::download_bytes(&filename, &bytes);
|
||||
let cache_name = std::path::Path::new(&filename)
|
||||
@@ -2347,6 +2348,15 @@ impl OpenCADStudio {
|
||||
});
|
||||
let clone_started = iced::time::Instant::now();
|
||||
let mut snapshot = self.tabs[i].scene.document_for_save();
|
||||
// First save: references attached with a relative path type while
|
||||
// the drawing had no file become relative to it.
|
||||
if self.tabs[i].current_path.is_none() && purpose != crate::app::SavePurpose::Autosave {
|
||||
crate::io::xref::make_relative(
|
||||
&mut snapshot,
|
||||
&self.tabs[i].xref_relative_on_save,
|
||||
&path,
|
||||
);
|
||||
}
|
||||
// Save-As across folders: rebase relative reference paths onto the
|
||||
// new base dir inside the snapshot only (live strings are untouched).
|
||||
if purpose == crate::app::SavePurpose::SaveAs {
|
||||
@@ -2649,6 +2659,14 @@ impl OpenCADStudio {
|
||||
}
|
||||
if outcome.set_current_path {
|
||||
let old_path = self.tabs[i].current_path.clone();
|
||||
if old_path.is_none() {
|
||||
let pending = std::mem::take(&mut self.tabs[i].xref_relative_on_save);
|
||||
crate::io::xref::make_relative(
|
||||
&mut self.tabs[i].scene.document,
|
||||
&pending,
|
||||
&outcome.path,
|
||||
);
|
||||
}
|
||||
self.tabs[i].current_path = Some(outcome.path.clone());
|
||||
self.tabs[i].scene.document.version = outcome.version;
|
||||
if outcome.purpose == crate::app::SavePurpose::SaveAs {
|
||||
|
||||
@@ -208,6 +208,7 @@ impl OpenCADStudio {
|
||||
}
|
||||
Some(GeometricTolerance) => self.geometric_tolerance = None,
|
||||
Some(BlockDefinition) => self.block_definition = None,
|
||||
Some(XrefAttach) => self.xref_attach = None,
|
||||
Some(Hyperlink) => {
|
||||
self.hyperlink_editor_handles.clear();
|
||||
self.hyperlink_editor_url.clear();
|
||||
@@ -1354,15 +1355,13 @@ impl OpenCADStudio {
|
||||
),
|
||||
|
||||
Message::XAttachPickResult(Ok(path)) => {
|
||||
use crate::command::CadCommand;
|
||||
use crate::modules::insert::xattach::XAttachCommand;
|
||||
let path_str = path.to_string_lossy().into_owned();
|
||||
let cmd = XAttachCommand::with_path(path_str);
|
||||
let i = self.active_tab;
|
||||
self.command_line.push_info(&cmd.prompt());
|
||||
self.tabs[i].active_cmd = Some(Box::new(cmd));
|
||||
self.open_xref_attach_dialog(path);
|
||||
Task::none()
|
||||
}
|
||||
message @ (Message::AttachPick
|
||||
| Message::AttachPickResult(_)
|
||||
| Message::XrefAttach(_)
|
||||
| Message::XrefAttachBrowseResult(_)) => self.update_xref_attach(message),
|
||||
|
||||
Message::XAttachPickResult(Err(e)) => {
|
||||
if e != "Cancelled" {
|
||||
|
||||
@@ -24,6 +24,7 @@ impl OpenCADStudio {
|
||||
Some(K::LayerTranslator) => crate::t!("Layer Translator").into_owned(),
|
||||
Some(K::DrawingUnits) => crate::t!("Drawing Units").into_owned(),
|
||||
Some(K::BlockDefinition) => crate::t!("Block Definition").into_owned(),
|
||||
Some(K::XrefAttach) => crate::t!("Attach External Reference").into_owned(),
|
||||
Some(K::GeometricTolerance) => crate::t!("Geometric Tolerance").into_owned(),
|
||||
Some(K::DraftingSettings) => crate::t!("Drafting Settings").into_owned(),
|
||||
Some(K::AutoConstrainSettings) => crate::t!("Constraint Settings").into_owned(),
|
||||
@@ -506,6 +507,13 @@ impl OpenCADStudio {
|
||||
crate::ui::window::block_definition::view_window(state, flow)
|
||||
})
|
||||
}
|
||||
super::super::ModalKind::XrefAttach => {
|
||||
let state = self.xref_attach.as_ref()?;
|
||||
let height = if state.details { 520 } else { 450 };
|
||||
sized_flow(ex, 740, height, |flow| {
|
||||
crate::ui::window::xref_attach::view_window(state, flow)
|
||||
})
|
||||
}
|
||||
super::super::ModalKind::GeometricTolerance => {
|
||||
let state = self.geometric_tolerance.as_ref()?;
|
||||
sized_flow(ex, 670, 530, |flow| {
|
||||
|
||||
Reference in new issue
Block a user