mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 21:42:59 -05:00
DXF Import: OK places the drawing the dialog previewed
OK in DXF Import Options, for a DXF or DWG drawing placed by path, compared the file on disk with the previewed bytes and refused to place it when they differed. The place job now takes the bytes the dialog read (PlaceJob::with_bytes), so OK places the previewed drawing even when the file was written over meanwhile, and the UI thread no longer reads the file at OK. The placed object's link and the journaled file.place params keep the path, and the read roots in force still apply to it. A DXF drawing laid out again for an artboard that changed before it was placed uses the same bytes.
This commit is contained in:
1 parent
ca20b965f2
commit
eacba80e0c
6 files changed
+105
-33
No files matched your search
@@ -202,10 +202,28 @@ fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result<Vec<u8>> {
|
||||
/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except
|
||||
/// that a file an importer would place (one `importer` names, or an extension no built-in format
|
||||
/// reads that an importer which places its files lists) is read, or decoded, only when it is at
|
||||
/// most [`import::MAX_INPUT_BYTES`] long.
|
||||
pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
|
||||
/// most [`import::MAX_INPUT_BYTES`] long. `given`: the bytes of the file `path` names, read already,
|
||||
/// which are used instead of reading the path again (by the same size rule).
|
||||
pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str, given: Option<&[u8]>) -> Result<Source<'a>> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }),
|
||||
Some(path) => {
|
||||
let bytes = match given {
|
||||
Some(bytes) => {
|
||||
// The roots in force now still apply to the path, though it is not read again.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
super::may_read(path)?;
|
||||
let explicit = named(p, cmd)?.is_some();
|
||||
let importer = explicit || importer_reads(&extension(path), Mode::Place);
|
||||
let built_in = !explicit && detect(path, bytes.get(..SNIFF_BYTES).unwrap_or(bytes)).is_some();
|
||||
if importer && !built_in && bytes.len() > import::MAX_INPUT_BYTES {
|
||||
return Err(too_large(path, Mode::Place));
|
||||
}
|
||||
bytes.to_vec()
|
||||
}
|
||||
None => read_path_for(path, p, Mode::Place, cmd)?,
|
||||
};
|
||||
Ok(Source { name: path, bytes, path: Some(path) })
|
||||
}
|
||||
None => {
|
||||
check_data_for(p, Mode::Place, cmd)?;
|
||||
super::source(p, cmd)
|
||||
|
||||
@@ -183,13 +183,13 @@ pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
|
||||
|
||||
/// [`load_sliced`] without the slices.
|
||||
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
|
||||
load_into(p, cmd, board, link_pdf, &mut vec![])
|
||||
load_into(p, cmd, board, link_pdf, None, &mut vec![])
|
||||
}
|
||||
|
||||
/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in.
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: Option<&[u8]>) -> Result<(Loaded, Slices)> {
|
||||
let mut slices = vec![];
|
||||
let l = load_into(p, cmd, board, link_pdf, &mut slices)?;
|
||||
let l = load_into(p, cmd, board, link_pdf, given, &mut slices)?;
|
||||
Ok((l, slices))
|
||||
}
|
||||
|
||||
@@ -197,9 +197,10 @@ fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Res
|
||||
/// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed
|
||||
/// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB
|
||||
/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one
|
||||
/// no built-in format reads) is read by it ([`plugin_art`]).
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::importer::place_source(p, cmd)?;
|
||||
/// no built-in format reads) is read by it ([`plugin_art`]). `given`: the bytes of the file `p`'s
|
||||
/// `path` names, read already ([`PlaceJob::with_bytes`]).
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: Option<&[u8]>, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::importer::place_source(p, cmd, given)?;
|
||||
let name = fileio::file_name(src.name);
|
||||
if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? {
|
||||
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
|
||||
@@ -760,8 +761,13 @@ pub struct PlaceJob {
|
||||
/// The object Replace swaps as it was when Place started.
|
||||
replaced: Option<Node>,
|
||||
target: Option<Rect>,
|
||||
/// The bytes of the file `path` names, read already ([`PlaceJob::with_bytes`]).
|
||||
bytes: Option<GivenBytes>,
|
||||
}
|
||||
|
||||
/// The bytes of a file read already, shared with whoever read them ([`PlaceJob::with_bytes`]).
|
||||
pub type GivenBytes = Arc<dyn AsRef<[u8]> + Send + Sync>;
|
||||
|
||||
/// A file [`PlaceJob::read`] read, which [`Session::place_read`] places.
|
||||
pub struct PlaceRead {
|
||||
job: PlaceJob,
|
||||
@@ -775,6 +781,14 @@ impl PlaceJob {
|
||||
str_param(&self.params, "path").or_else(|| str_param(&self.params, "name")).map(fileio::file_name).unwrap_or_else(|| "Untitled".into())
|
||||
}
|
||||
|
||||
/// The job placing `bytes` as the file its `path` names, which [`PlaceJob::read`] then does not
|
||||
/// read again: the placed object's link and the journaled params keep the path. Without a
|
||||
/// `path` the bytes are not used.
|
||||
pub fn with_bytes(mut self, bytes: GivenBytes) -> Self {
|
||||
self.bytes = Some(bytes);
|
||||
self
|
||||
}
|
||||
|
||||
/// Read and decode the file, as `file.place` does, without the session. The pixels of a PNG,
|
||||
/// JPEG, GIF or WebP file are decoded here to check that they can be read (an error when they
|
||||
/// can't), a linked image's preview is made from that decode, and the decoded pixels are kept in
|
||||
@@ -782,7 +796,7 @@ impl PlaceJob {
|
||||
/// ([`super::links::readable_and_kept`]).
|
||||
pub fn read(self) -> Result<PlaceRead> {
|
||||
crate::cancel::check()?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true, self.bytes.as_deref().map(AsRef::as_ref))?;
|
||||
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
|
||||
match &mut loaded.art {
|
||||
Art::Image(img, _) => {
|
||||
@@ -941,12 +955,12 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
|
||||
};
|
||||
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at), bytes: None })
|
||||
}
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read;
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, bytes, .. }, mut loaded, slices: read_slices } = read;
|
||||
let p = ¶ms;
|
||||
let template = bool_or(p, "template", false);
|
||||
let at = at_param(p)?;
|
||||
@@ -957,10 +971,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
// The artboard under `at` as it is now, as a replay of the journal finds it: a DXF drawing laid
|
||||
// out on the artboard it was read for is read again when that artboard changed meanwhile.
|
||||
// out on the artboard it was read for is read again when that artboard changed meanwhile, from
|
||||
// the same bytes when the job was given them.
|
||||
let target = board_at(&st.doc, at);
|
||||
if loaded.board.is_some() && target != read_for {
|
||||
loaded = load(p, PLACE, target, true)?;
|
||||
loaded = load_into(p, PLACE, target, true, bytes.as_deref().map(AsRef::as_ref), &mut vec![])?;
|
||||
}
|
||||
// Type reflows rather than scales: its frame takes the size it is placed at.
|
||||
let is_text = matches!(loaded.art, Art::Text(_));
|
||||
@@ -1347,7 +1362,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["link"], "file.place.info")?;
|
||||
check_numbers(p, &["thumbnail"], "file.place.info")?;
|
||||
// A PDF/.ai page linked or not has the same size and art.
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?;
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false, None)?;
|
||||
let natural = l.natural;
|
||||
let mut out = json!({
|
||||
"name": l.name,
|
||||
|
||||
@@ -498,12 +498,6 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R
|
||||
if let Some(placement) = placement {
|
||||
placement.check(app)?;
|
||||
}
|
||||
// Place reads the file again: it must still be the drawing the dialog previewed.
|
||||
if let (Some(path), Some(read)) = (source.path.as_deref(), app.services.read.as_ref())
|
||||
&& read(path)? != source.file.bytes
|
||||
{
|
||||
return Err(tl!("The drawing changed on disk. Place it again to use the new version.").to_owned());
|
||||
}
|
||||
app.ui.dxf_import = remembered;
|
||||
let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file);
|
||||
p["dxf"] = dxf;
|
||||
@@ -530,8 +524,14 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R
|
||||
if let Some(converted) = &source.converted {
|
||||
app.placing.keep_next = Some(Box::new(converted.held.clone()));
|
||||
}
|
||||
// The drawing placed is the one the dialog showed, not the file as it is on disk now;
|
||||
// its link and the journal keep the path.
|
||||
if let Some(path) = &source.path {
|
||||
app.placing.bytes_next = Some((path.clone(), source.file.clone()));
|
||||
}
|
||||
let r = crate::place::run_for_user(app, &p).map(|_| ());
|
||||
app.placing.keep_next = None;
|
||||
app.placing.bytes_next = None;
|
||||
if let (Some(current), Some(insertion)) = (current, restore) {
|
||||
current.restore_changed(&insertion, app);
|
||||
}
|
||||
@@ -924,7 +924,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A DWG drawing placed through its dialog is the drawing the dialog previewed: a file written
|
||||
/// over it on disk while the dialog is open is not placed, and OK keeps the dialog open.
|
||||
/// over it on disk while the dialog is open is not placed.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn ok_places_the_drawing_the_dialog_previewed() {
|
||||
@@ -958,16 +958,18 @@ mod tests {
|
||||
finish_conversions(&mut app);
|
||||
assert_eq!(host::fields(&app, KIND)["mode"], "place");
|
||||
std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(flatter.as_bytes(), "AC1018").unwrap()).unwrap();
|
||||
let steps = app.session.doc().unwrap().history.undo.len();
|
||||
let refused = host::confirm(&mut app, KIND);
|
||||
assert_eq!(refused, Err("The drawing changed on disk. Place it again to use the new version.".to_owned()));
|
||||
assert!(host::is_open(&app, KIND), "the dialog stays open");
|
||||
assert!(app.placing.pending.is_empty());
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing is placed");
|
||||
// Written back as it was, the drawing the dialog previewed is placed.
|
||||
std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(&drawing(), "AC1018").unwrap()).unwrap();
|
||||
let before = app.session.doc().unwrap().selection.objects.clone();
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
assert_eq!(placed_size(&mut app), previewed, "OK places the drawing the dialog opened on");
|
||||
let size = placed_size(&mut app);
|
||||
assert_ne!(app.session.doc().unwrap().selection.objects, before, "OK places a new object");
|
||||
assert_eq!(size, previewed, "OK places the drawing the dialog opened on");
|
||||
assert!(app.placing.bytes_next.is_none());
|
||||
// Placed again, the file as it is on disk now is read.
|
||||
let before = app.session.doc().unwrap().selection.objects.clone();
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "showImportOptions": false })).unwrap();
|
||||
let size = placed_size(&mut app);
|
||||
assert_ne!(app.session.doc().unwrap().selection.objects, before, "the place adds a new object");
|
||||
assert_ne!(size, previewed, "a later place reads the new file");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,13 @@ impl DialogFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's bytes, as a place given them reads them ([`vectorcraft_engine::cmd::place::GivenBytes`]).
|
||||
impl AsRef<[u8]> for DialogFile {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Equal by token: a token names one file's bytes, so a dialog's values compare without reading them.
|
||||
impl PartialEq for DialogFile {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
|
||||
@@ -346,7 +346,22 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
|
||||
}
|
||||
r
|
||||
}
|
||||
_ => engine(app, "file.place", &p),
|
||||
_ => match crate::placing::given_bytes(app, &p) {
|
||||
// A drawing placed through its import options places the bytes the dialog showed.
|
||||
Some(bytes) => {
|
||||
// The edit the tool computes on another thread comes first, as for `placing::start`.
|
||||
let r = app.session.finish_tool_edit();
|
||||
crate::canvas::apply_requests(app, r);
|
||||
let job = app.session.prepare_place(&p).and_then(|job| job.with_bytes(bytes).read());
|
||||
let r = job.and_then(|read| app.session.place_read(read)).map_err(|e| e.to_string());
|
||||
app.sync_views();
|
||||
if let Err(e) = &r {
|
||||
app.status(e.clone());
|
||||
}
|
||||
r
|
||||
}
|
||||
None => engine(app, "file.place", &p),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -202,6 +202,10 @@ pub struct Placing {
|
||||
/// dropped: the conversion of a DWG drawing placed through its import options, which the read
|
||||
/// then finds without converting the drawing again.
|
||||
pub(crate) keep_next: Option<Box<dyn std::any::Any + Send>>,
|
||||
/// The path and the bytes of a drawing placed through its import options: the next place of
|
||||
/// that path ([`crate::place::run_for_user`]) places these bytes, the ones the dialog showed,
|
||||
/// instead of reading the file again.
|
||||
pub(crate) bytes_next: Option<(String, vectorcraft_engine::cmd::place::GivenBytes)>,
|
||||
/// A deferred paste awaiting its own Swatch Conflict dialog.
|
||||
swatch_paste: Option<PendingSwatch>,
|
||||
/// Set by unit tests whose app reads the files the user places off the UI thread.
|
||||
@@ -305,12 +309,23 @@ pub fn start(app: &mut VectorcraftApp, p: &Value, dropped: bool) -> Result<Value
|
||||
// one selected after it.
|
||||
let r = app.session.finish_tool_edit();
|
||||
crate::canvas::apply_requests(app, r);
|
||||
let job = app.session.prepare_place(p).map_err(|e| e.to_string())?;
|
||||
let given = given_bytes(app, p);
|
||||
let mut job = app.session.prepare_place(p).map_err(|e| e.to_string())?;
|
||||
if let Some(bytes) = given {
|
||||
job = job.with_bytes(bytes);
|
||||
}
|
||||
let name = job.name();
|
||||
let insertion = Insertion::of(app).ok_or("no document")?;
|
||||
spawn(app, name.clone(), name, dropped, move || job.read().map(|r| Read::Place(Box::new(r), insertion)).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// The bytes [`Placing::bytes_next`] holds for the file `p`'s `path` names, taken; `None` (and the
|
||||
/// bytes dropped) for any other place.
|
||||
pub(crate) fn given_bytes(app: &mut VectorcraftApp, p: &Value) -> Option<vectorcraft_engine::cmd::place::GivenBytes> {
|
||||
let (path, bytes) = app.placing.bytes_next.take()?;
|
||||
(p.get("path").and_then(Value::as_str) == Some(path.as_str())).then_some(bytes)
|
||||
}
|
||||
|
||||
/// `file.place.queue` with `p` for the active document, its files read and their thumbnails made off
|
||||
/// the UI thread → `{background: true, status}`; the place cursor is loaded once they are ready.
|
||||
/// `asks`: the cursor's files ask for their import options when placed ([`crate::place::show_thumbnails`]).
|
||||
|
||||
Reference in new issue
Block a user