mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-24 21:09:40 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cda891fb4e | ||
|
|
39fca9e2a7 | ||
|
|
506ad531eb | ||
|
|
003ab113c2 | ||
|
|
273437af7a | ||
|
|
d0d027ac8f | ||
|
|
4c004d5dd5 | ||
|
|
3e98ef30e7 | ||
|
|
4840d576a5 | ||
|
|
07bdd66b1d | ||
|
|
9e7663b25c | ||
|
|
10727f5025 | ||
|
|
1515833f2c | ||
|
|
28d8ba72c5 | ||
|
|
5af8fc020a | ||
|
|
a3e04070be | ||
|
|
210a99ecc8 | ||
|
|
bc703cb134 | ||
|
|
84eb20b5c0 | ||
|
|
27e408d91b | ||
|
|
195c052931 | ||
|
|
7d1d0ba55b | ||
|
|
8920c0fb6f | ||
|
|
68fbe896a7 | ||
|
|
f9756d5083 | ||
|
|
7a199cc2e1 | ||
|
|
88ef222cdf | ||
|
|
64e0b5c2a4 | ||
|
|
b27cc3ce22 | ||
|
|
b355f1e14a | ||
|
|
ad6314967f |
@@ -39,7 +39,7 @@ pub use header::{HVal, Header};
|
||||
pub use plotstyle::*;
|
||||
pub use plotter::*;
|
||||
pub use raster::{Raster, Rasters};
|
||||
pub use refedit::{RefEdit, WorkItem};
|
||||
pub use refedit::{RefEdit, WorkItem, XrefSource};
|
||||
pub use store::EntityStore;
|
||||
pub use tables::*;
|
||||
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
|
||||
|
||||
@@ -42,6 +42,36 @@ pub struct RefEdit {
|
||||
/// Block objects taken out of the working set with their edits (block coordinates, the block
|
||||
/// object's handle).
|
||||
pub released: Vec<Entity>,
|
||||
/// The nested references picked through to reach the edited block: block references inside
|
||||
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
|
||||
pub path: Vec<Handle>,
|
||||
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
|
||||
/// into its source drawing.
|
||||
pub xref: Option<XrefSource>,
|
||||
}
|
||||
|
||||
/// Where an xref edited in place is written back to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct XrefSource {
|
||||
/// The xref (its block name in this drawing).
|
||||
pub xref: String,
|
||||
/// The source drawing file.
|
||||
pub file: String,
|
||||
/// `file` with every symbolic link resolved when the edit began: the file that is written.
|
||||
/// The save is refused when `file` leads somewhere else by then.
|
||||
pub real: String,
|
||||
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
|
||||
/// is written back in that version (`None`: in the drawing's own).
|
||||
pub version: Option<String>,
|
||||
/// Whether the file is a binary DXF (written back as one).
|
||||
pub binary: bool,
|
||||
/// The block of the source drawing being edited; `None` for its model space.
|
||||
pub block: Option<String>,
|
||||
/// The file's size and modification time when the edit began.
|
||||
pub stamp: Option<(u64, std::time::SystemTime)>,
|
||||
/// Edited block objects (their handles in this drawing) and the objects of the source
|
||||
/// drawing they were loaded from.
|
||||
pub sources: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
impl RefEdit {
|
||||
|
||||
@@ -728,6 +728,11 @@ pub struct Block {
|
||||
/// The parameters of an associative array when this is an array block.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub array: Option<crate::ArrayParams>,
|
||||
/// An xref's file as its loaded objects were read from it: size and modification time (as the
|
||||
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
|
||||
/// the file changed since this drawing loaded it (session state; not saved).
|
||||
#[serde(skip)]
|
||||
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
|
||||
}
|
||||
|
||||
/// The load state of an external reference.
|
||||
@@ -774,6 +779,7 @@ impl Block {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -134,7 +134,7 @@ struct Ctx {
|
||||
}
|
||||
|
||||
/// The folder of the host drawing at `host` (a file path).
|
||||
fn folder(host: Option<&Path>) -> Option<PathBuf> {
|
||||
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
|
||||
let p = host?.parent()?;
|
||||
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
|
||||
}
|
||||
@@ -293,8 +293,17 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
|
||||
Ok(out.is_file().then_some(out))
|
||||
}
|
||||
|
||||
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
|
||||
/// binary DXF sentinel).
|
||||
const HEAD_BYTES: usize = 4096;
|
||||
|
||||
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
|
||||
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
|
||||
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
|
||||
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
|
||||
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
|
||||
/// binary DXF) describes the same read.
|
||||
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
|
||||
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
@@ -303,7 +312,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
|
||||
let limit = MAX_XREF_BYTES.min(left);
|
||||
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
|
||||
let len = f.metadata().map_err(|e| e.to_string())?.len();
|
||||
let meta = f.metadata().map_err(|e| e.to_string())?;
|
||||
let len = meta.len();
|
||||
let before = stamp_of(&meta);
|
||||
let too_big = || {
|
||||
if limit < MAX_XREF_BYTES {
|
||||
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
|
||||
@@ -321,7 +332,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
return Err(too_big());
|
||||
}
|
||||
cx.bytes = cx.bytes.saturating_add(n);
|
||||
(hooks.read)(&bytes, &file.to_string_lossy())
|
||||
let after = f.metadata().ok().as_ref().and_then(stamp_of);
|
||||
let read_as = before.filter(|b| Some(*b) == after);
|
||||
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
|
||||
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
@@ -330,6 +344,33 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
|
||||
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
|
||||
/// system gives it: counted from 1970, a file dated before then would have none and always look
|
||||
/// changed.
|
||||
pub(crate) type Stamp = (u64, std::time::SystemTime);
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
|
||||
Some((m.len(), m.modified().ok()?))
|
||||
}
|
||||
|
||||
/// The [`Stamp`] of the file at `file` now.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
|
||||
stamp_of(&std::fs::metadata(file).ok()?)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
|
||||
/// first bytes of the bytes read (see [`read`]).
|
||||
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
|
||||
read(file, &mut Ctx::new(None))
|
||||
}
|
||||
|
||||
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
|
||||
/// own path.
|
||||
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
|
||||
@@ -393,8 +434,14 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
|
||||
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
|
||||
clear(d, &key);
|
||||
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
|
||||
Ok((x, file)) => match import(d, &key, &x, cx) {
|
||||
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
|
||||
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
|
||||
Ok(()) => {
|
||||
// This drawing's own baseline: another drawing loading the file later doesn't move it.
|
||||
if let Some(b) = d.blocks.get_mut(&key) {
|
||||
Arc::make_mut(b).xref_stamp = read_as;
|
||||
}
|
||||
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
|
||||
}
|
||||
Err(e) => {
|
||||
// Whatever made it in before the failure goes again. A fetch that failed imported
|
||||
// nothing, so it doesn't pay for a second scan of the block table.
|
||||
@@ -409,7 +456,13 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
|
||||
}
|
||||
|
||||
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
|
||||
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
|
||||
fn fetch(
|
||||
path: &str,
|
||||
host: Option<&Path>,
|
||||
chosen: bool,
|
||||
cx: &mut Ctx,
|
||||
depth: usize,
|
||||
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
|
||||
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Err(unresolved("xrefs are nested too deeply"));
|
||||
@@ -423,7 +476,7 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
|
||||
return Err(unresolved("too many referenced files"));
|
||||
}
|
||||
cx.files += 1;
|
||||
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
|
||||
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
|
||||
cx.chain.push(canon);
|
||||
let nested: Vec<String> =
|
||||
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
|
||||
@@ -434,15 +487,20 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
|
||||
}
|
||||
}
|
||||
cx.chain.pop();
|
||||
Ok((x, file))
|
||||
Ok((x, file, read_as))
|
||||
}
|
||||
|
||||
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
|
||||
/// space and every block's.
|
||||
pub(crate) fn object_count(x: &Drawing) -> usize {
|
||||
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
|
||||
}
|
||||
|
||||
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
|
||||
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
|
||||
/// host's settings, so layer changes survive a reload).
|
||||
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
|
||||
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
|
||||
cx.objects = cx.objects.saturating_add(count);
|
||||
cx.objects = cx.objects.saturating_add(object_count(x));
|
||||
if cx.objects > MAX_XREF_OBJECTS {
|
||||
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
|
||||
}
|
||||
|
||||
@@ -721,12 +721,13 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
|
||||
/// ([`crate::atomic_write::write_atomic_with`]). Nothing
|
||||
/// to keep when there is no file yet. A file that doesn't look like a drawing
|
||||
/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone.
|
||||
/// Returns whether the backup was written. Also used for an xref REFEDIT writes back.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
|
||||
let mut src = match std::fs::File::open(path) {
|
||||
Ok(f) if f.metadata()?.is_file() => f,
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Ok(_) => return Ok(false),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let (head, tail, len) = ends(&mut src)?;
|
||||
@@ -735,7 +736,7 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
// the roots (or to another computer) isn't looked at.
|
||||
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
|
||||
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private
|
||||
// 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
|
||||
@@ -761,7 +762,8 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
}
|
||||
std::io::Write::write_all(out, &head)?;
|
||||
std::io::copy(&mut src, out).map(|_| ())
|
||||
})
|
||||
})?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
|
||||
|
||||
@@ -48,6 +48,8 @@ pub const FILES: &[&str] = &[
|
||||
"publish",
|
||||
"qsave",
|
||||
"recover",
|
||||
"refclose",
|
||||
"refedit",
|
||||
"reinit",
|
||||
"saveas",
|
||||
"script",
|
||||
@@ -260,9 +262,8 @@ pub const NO_FILES: &[&str] = &[
|
||||
"attdisp.normal",
|
||||
"attdisp.on",
|
||||
"attdisp.off",
|
||||
"refedit",
|
||||
"refedit.levels",
|
||||
"refset",
|
||||
"refclose",
|
||||
"bedit",
|
||||
"bsave",
|
||||
"bsaveas",
|
||||
@@ -514,9 +515,9 @@ mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
|
||||
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
|
||||
/// direction.
|
||||
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
|
||||
/// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested
|
||||
/// references, and `blocks.reference.grips` reports a direction.
|
||||
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"];
|
||||
|
||||
/// The words of a command's documentation, lower case.
|
||||
fn words(doc: &str) -> BTreeSet<String> {
|
||||
|
||||
@@ -108,6 +108,9 @@ impl Session {
|
||||
return Ok(Some(label));
|
||||
}
|
||||
let st = self.state_mut()?;
|
||||
if let Some(why) = st.undo.last().and_then(|snap| cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)) {
|
||||
return Err(EngineError::Other(why));
|
||||
}
|
||||
let Some(snap) = st.undo.pop() else { return Ok(None) };
|
||||
let cur = st.swap_in(snap);
|
||||
let label = cur.label.clone();
|
||||
|
||||
@@ -311,6 +311,7 @@ mod tests {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
blk.entities
|
||||
.push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 })));
|
||||
|
||||
@@ -81,6 +81,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
|
||||
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
|
||||
// How much objects outside the working set fade while a reference is edited in place (REFEDIT).
|
||||
("XFADECTL", Kind::Int(0, 90), Def::Int(50)),
|
||||
];
|
||||
|
||||
/// The standard lineweights in hundredths of a millimetre.
|
||||
|
||||
@@ -143,6 +143,7 @@ mod recent_commands;
|
||||
mod rectang_ortho;
|
||||
mod rectang_polygon_order;
|
||||
mod refedit;
|
||||
mod refedit_xref;
|
||||
mod region;
|
||||
mod rename_cmdline;
|
||||
mod rotate_reference;
|
||||
|
||||
@@ -104,6 +104,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
d.blocks.insert("*D1".into(), std::sync::Arc::new(block));
|
||||
d.model.modify(dim, |e| {
|
||||
|
||||
@@ -279,7 +279,7 @@ fn interactive_refedit_refset_and_refclose() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xrefs_are_refused_with_a_message() {
|
||||
fn an_xref_that_is_not_loaded_is_refused_with_a_message() {
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().blocks.insert(
|
||||
"X".into(),
|
||||
@@ -291,5 +291,6 @@ fn xrefs_are_refused_with_a_message() {
|
||||
);
|
||||
let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0);
|
||||
let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err();
|
||||
assert!(e.to_string().contains("external reference"), "{e}");
|
||||
// Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be.
|
||||
assert!(e.to_string().contains("not loaded"), "{e}");
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -305,3 +305,36 @@ fn drawings_sharing_a_name_keep_their_own_backups() {
|
||||
assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak");
|
||||
assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak");
|
||||
}
|
||||
|
||||
/// REFCLOSE Save writes an xref back the way SAVE writes a drawing: with ISAVEBAK off it keeps
|
||||
/// no `.bak` (and reports none), with it on it keeps the previous file.
|
||||
#[test]
|
||||
fn an_xref_written_back_by_refclose_keeps_a_backup_as_save_does() {
|
||||
let _g = saving();
|
||||
hooks();
|
||||
let dir = temp_dir("refclose");
|
||||
let site = dir.join("site.dxf");
|
||||
let mut x = Session::new();
|
||||
add_circle(&mut x, 0.0);
|
||||
x.execute("saveas", &json!({ "path": site.to_string_lossy() })).unwrap();
|
||||
let host = dir.join("host.dxf");
|
||||
let mut s = Session::new();
|
||||
s.execute("saveas", &json!({ "path": host.to_string_lossy() })).unwrap();
|
||||
let insert = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap()["handle"].as_str().unwrap().to_string();
|
||||
let bak = backup_path(&site);
|
||||
|
||||
cadcraft_engine::autosave::set_isavebak(false);
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
add_circle(&mut s, 110.0);
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(circles(&site), 2, "the edit is written");
|
||||
assert!(out["backup"].is_null() && !bak.exists(), "ISAVEBAK off keeps no backup: {out}");
|
||||
|
||||
cadcraft_engine::autosave::set_isavebak(true);
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
add_circle(&mut s, 120.0);
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!((circles(&site), circles(&bak)), (3, 2), "{out}");
|
||||
assert_eq!(files(&dir), ["host.dxf", "site.dxf", "site.dxf.bak"], "no staging files are left");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -39,6 +39,8 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) {
|
||||
explodable,
|
||||
units,
|
||||
array,
|
||||
// Session state (when an xref was read), never in a file.
|
||||
xref_stamp: _,
|
||||
} = block.as_ref();
|
||||
equal(name, &back.name, &path, "name");
|
||||
equal(annotative, &back.annotative, &path, "annotative");
|
||||
|
||||
@@ -58,6 +58,15 @@ fn shown_transparency(b: &mut Builder, ctx: &Ctx, e: &Entity, layer_transparency
|
||||
own
|
||||
}
|
||||
|
||||
/// While a reference is edited in place (REFEDIT), everything outside the working set is faded by
|
||||
/// XFADECTL percent on screen: how much `e` fades (0 when it doesn't).
|
||||
fn refedit_fade(b: &Builder, ctx: &Ctx, e: &Entity) -> u8 {
|
||||
match b.fade {
|
||||
Some(f) if !b.plotting && !f.working.contains(&if ctx.depth == 0 { e.handle } else { ctx.top }) => f.percent,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
// A top-level annotative object draws at the view's annotation scale: a viewport's scale for
|
||||
// model space seen through it, else the drawing's (CANNOSCALE in model space, 1:1 on paper).
|
||||
@@ -81,6 +90,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
if !visible {
|
||||
return;
|
||||
}
|
||||
let fade = fade.max(refedit_fade(b, ctx, e));
|
||||
let own = shown_transparency(b, ctx, e, layer_transparency, fade);
|
||||
// A plot style's linetype replaces the object's.
|
||||
let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) {
|
||||
|
||||
@@ -130,6 +130,24 @@ struct Builder<'a> {
|
||||
points: &'a std::sync::atomic::AtomicUsize,
|
||||
/// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests).
|
||||
max_points: usize,
|
||||
/// While a reference is edited in place: what is drawn faded ([`Fade::of`]).
|
||||
fade: Option<&'a Fade>,
|
||||
}
|
||||
|
||||
/// While a reference is edited in place (REFEDIT), everything outside the working set is drawn
|
||||
/// faded by XFADECTL percent on screen. Built once per display list: a lookup per object drawn
|
||||
/// would scan the working set each time.
|
||||
struct Fade {
|
||||
working: std::collections::HashSet<Handle>,
|
||||
percent: u8,
|
||||
}
|
||||
|
||||
impl Fade {
|
||||
fn of(d: &Drawing) -> Option<Fade> {
|
||||
let r = d.refedit.as_ref()?;
|
||||
let percent = u8::try_from(d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50);
|
||||
Some(Fade { working: r.items.iter().map(|i| i.copy).collect(), percent })
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy
|
||||
@@ -370,6 +388,7 @@ impl<'a> Builder<'a> {
|
||||
transparency: self.transparency,
|
||||
points: self.points,
|
||||
max_points: self.max_points,
|
||||
fade: self.fade,
|
||||
}
|
||||
}
|
||||
/// Take one unit of the block-expansion budget; false once it is spent, or once the build
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT};
|
||||
use super::draw::entity;
|
||||
use super::viewports::{MAX_VIEWPORTS, viewport};
|
||||
use super::{
|
||||
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen, plotstyle,
|
||||
point,
|
||||
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Fade, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen,
|
||||
plotstyle, point,
|
||||
};
|
||||
|
||||
/// Build options.
|
||||
@@ -114,6 +114,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo
|
||||
let opts = &with_point_view(d, space, opts);
|
||||
let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t));
|
||||
let points = std::sync::atomic::AtomicUsize::new(0);
|
||||
let fade = Fade::of(d);
|
||||
let mut b = Builder {
|
||||
list: DisplayList::default(),
|
||||
opts,
|
||||
@@ -124,6 +125,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo
|
||||
transparency: 0,
|
||||
points: &points,
|
||||
max_points,
|
||||
fade: fade.as_ref(),
|
||||
};
|
||||
if let Space::Paper(name) = space {
|
||||
b.list.sheet = paper::sheet(d, name);
|
||||
@@ -171,7 +173,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
|
||||
use rayon::prelude::*;
|
||||
let ents: Vec<&std::sync::Arc<Entity>> = store.iter().collect();
|
||||
let budget = std::sync::atomic::AtomicUsize::new(0);
|
||||
let (opts, plotting, points, max_points) = (b.opts, b.plotting, b.points, b.max_points);
|
||||
let (opts, plotting, points, max_points, fade) = (b.opts, b.plotting, b.points, b.max_points, b.fade);
|
||||
let parts: Vec<DisplayList> = ents
|
||||
.par_chunks(PARALLEL_CHUNK)
|
||||
.map(|chunk| {
|
||||
@@ -185,6 +187,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
|
||||
transparency: 0,
|
||||
points,
|
||||
max_points,
|
||||
fade,
|
||||
};
|
||||
for e in chunk {
|
||||
entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
|
||||
@@ -238,6 +241,7 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
|
||||
opts
|
||||
};
|
||||
let points = std::sync::atomic::AtomicUsize::new(0);
|
||||
let fade = Fade::of(d);
|
||||
let mut b = Builder {
|
||||
list: DisplayList::default(),
|
||||
opts,
|
||||
@@ -248,6 +252,7 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
|
||||
transparency: 0,
|
||||
points: &points,
|
||||
max_points: MAX_DISPLAY_POINTS,
|
||||
fade: fade.as_ref(),
|
||||
};
|
||||
for e in ents {
|
||||
entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
|
||||
|
||||
@@ -6,8 +6,8 @@ use super::draw::entity;
|
||||
use super::pipeline::PARALLEL_CHUNK;
|
||||
use super::pipeline::{Options, style_table, top_ctx, with_point_view};
|
||||
use super::{
|
||||
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper, pen,
|
||||
plotstyle,
|
||||
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Fade, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper,
|
||||
pen, plotstyle,
|
||||
};
|
||||
|
||||
/// Upper bound on viewports drawn per layout (hostile files).
|
||||
@@ -71,6 +71,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
|
||||
let opts = &with_point_view(d, space, opts);
|
||||
let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t));
|
||||
let points = std::sync::atomic::AtomicUsize::new(0);
|
||||
let fade = Fade::of(d);
|
||||
let mut b = Builder {
|
||||
list: DisplayList::default(),
|
||||
opts,
|
||||
@@ -81,6 +82,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
|
||||
transparency: 0,
|
||||
points: &points,
|
||||
max_points: MAX_DISPLAY_POINTS,
|
||||
fade: fade.as_ref(),
|
||||
};
|
||||
contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle));
|
||||
b.list
|
||||
@@ -135,6 +137,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
|
||||
transparency: 0,
|
||||
points: b.points,
|
||||
max_points: b.max_points,
|
||||
fade: b.fade,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK;
|
||||
@@ -146,7 +149,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
|
||||
// As `build_parallel`: chunks built side by side, joined in drawing order.
|
||||
use rayon::prelude::*;
|
||||
let ents: Vec<&std::sync::Arc<Entity>> = d.model.iter().collect();
|
||||
let (opts, points, max_points) = (b.opts, b.points, b.max_points);
|
||||
let (opts, points, max_points, fade) = (b.opts, b.points, b.max_points, b.fade);
|
||||
let parts: Vec<DisplayList> = ents
|
||||
.par_chunks(PARALLEL_CHUNK)
|
||||
.map(|chunk| {
|
||||
@@ -160,6 +163,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
|
||||
transparency: 0,
|
||||
points,
|
||||
max_points,
|
||||
fade,
|
||||
};
|
||||
let c = ctx();
|
||||
for me in chunk.iter().filter(|me| seen(me)) {
|
||||
|
||||
@@ -1189,6 +1189,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
|
||||
app.canvas.draw_ms = crate::now_ms() - t0;
|
||||
compare::paint(app, ui.ctx(), painter, &xf_paper, rect);
|
||||
blockedit::paint(app, ui.ctx(), painter, &xf_paper, rect);
|
||||
refedit::paint(app, ui.ctx(), rect);
|
||||
// Constraint bars and dynamic dimensional constraints (model space, or inside a viewport).
|
||||
if sheet.is_none() || active_vp.is_some() {
|
||||
let clip = match &active_vp {
|
||||
@@ -1323,3 +1324,5 @@ mod compare;
|
||||
/// Background rebuilds of the display list for a new view.
|
||||
mod images;
|
||||
mod rebuild;
|
||||
/// The Edit Reference bar while a reference is edited in place (REFEDIT).
|
||||
mod refedit;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Editing a reference in place (REFEDIT) on the canvas: a bar over the drawing with the
|
||||
//! reference's name (and, for an xref, the file it writes to), the working set's size, Add to /
|
||||
//! Remove from Working Set, and Save Changes / Discard Changes (REFCLOSE). The rest of the
|
||||
//! drawing is drawn faded by the renderer (XFADECTL) and locked by the engine.
|
||||
|
||||
use egui::{Rect, RichText, Stroke, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::CadApp;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
fn id() -> egui::Id {
|
||||
egui::Id::unique("cadcraft-refedit-bar")
|
||||
}
|
||||
|
||||
/// The edit shown: (block, xref file, working-set size).
|
||||
fn editing(app: &CadApp) -> Option<(String, Option<String>, usize)> {
|
||||
let r = app.session.state().ok()?.doc.refedit.clone()?;
|
||||
Some((r.block, r.xref.map(|x| x.file), r.items.len()))
|
||||
}
|
||||
|
||||
/// What a bar button asks for.
|
||||
enum Act {
|
||||
Start(&'static str),
|
||||
Run(&'static str, serde_json::Value),
|
||||
}
|
||||
|
||||
/// The bar (over the drawing, at its top).
|
||||
pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, rect: Rect) {
|
||||
let Some((name, file, count)) = editing(app) else { return };
|
||||
let t = Tokens::get();
|
||||
let sel: Vec<String> = app.session.selection().iter().map(|h| h.hex()).collect();
|
||||
let mut act = None;
|
||||
egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
egui::Frame::new().fill(t.cmd_bg).stroke(Stroke::new(1.0, t.accent)).corner_radius(4.0).inner_margin(6.0).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(crate::tl!("Edit Reference")).color(t.accent).strong());
|
||||
let shown = ui.label(RichText::new(&name).color(t.text));
|
||||
if let Some(f) = &file {
|
||||
shown.on_hover_text(crate::tf!("Saving writes {file}", file = f));
|
||||
}
|
||||
ui.label(RichText::new(crate::tf!("{n} in the working set", n = count)).color(t.text_dim));
|
||||
ui.separator();
|
||||
if ui.button(crate::tl!("Add to Working Set")).clicked() {
|
||||
act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "add": sel })) });
|
||||
}
|
||||
if ui.button(crate::tl!("Remove from Working Set")).clicked() {
|
||||
act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "remove": sel })) });
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(RichText::new(crate::tl!("Save Changes")).color(t.accent)).clicked() {
|
||||
act = Some(Act::Run("refclose", json!({ "option": "save" })));
|
||||
}
|
||||
if ui.button(crate::tl!("Discard Changes")).clicked() {
|
||||
act = Some(Act::Run("refclose", json!({ "option": "discard" })));
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
match act {
|
||||
Some(Act::Start(id)) => app.start(id),
|
||||
Some(Act::Run(id, p)) => {
|
||||
if let Err(e) = app.run(id, p) {
|
||||
app.set_status(e);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -1367,6 +1367,12 @@ menu Modify Edita
|
||||
Check for Updates… Verifica aggiornamenti…
|
||||
CADCraft is up to date. CADCraft è aggiornato.
|
||||
Could not check for updates. Impossibile verificare gli aggiornamenti.
|
||||
Edit Reference Modifica riferimento
|
||||
Saving writes {file} Il salvataggio scrive {file}
|
||||
{n} in the working set {n} nel gruppo di lavoro
|
||||
Remove from Working Set Rimuovi dal gruppo di lavoro
|
||||
Save Changes Salva modifiche
|
||||
Discard Changes Annulla modifiche
|
||||
Add a drawing file as a block library Aggiungi un file di disegno come libreria di blocchi
|
||||
Add a folder of drawings or a drawing file to use its blocks. Aggiungi una cartella di disegni o un file di disegno per usarne i blocchi.
|
||||
Block Libraries Librerie di blocchi
|
||||
|
||||
|
@@ -1394,6 +1394,12 @@
|
||||
Check for Updates… Перевірити оновлення…
|
||||
CADCraft is up to date. Встановлено найновішу версію CADCraft.
|
||||
Could not check for updates. Не вдалося перевірити оновлення.
|
||||
Edit Reference Редагування посилання
|
||||
Saving writes {file} Збереження записує {file}
|
||||
{n} in the working set {n} у робочому наборі
|
||||
Remove from Working Set Вилучити з робочого набору
|
||||
Save Changes Зберегти зміни
|
||||
Discard Changes Скасувати зміни
|
||||
Save changes to block "{name}"? Зберегти зміни в блоці «{name}»?
|
||||
Add a drawing file as a block library Додати файл креслення як бібліотеку блоків
|
||||
Add a folder of drawings or a drawing file to use its blocks. Додайте теку з кресленнями або файл креслення, щоб використовувати його блоки.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1403 and column 24.
|
@@ -683,6 +683,7 @@
|
||||
Select an object to measure Select an object to measure
|
||||
Add to Working Set 添加到工作集
|
||||
Edit Reference In-Place 就地编辑参照
|
||||
Reference Nesting Levels 参照嵌套级别
|
||||
Save Reference Edits 保存参照编辑
|
||||
Working Set 工作集
|
||||
Xref and Block In-place Editing 外部参照和块的就地编辑
|
||||
|
||||
|
Reference in New Issue
Block a user