mirror of
https://github.com/storytold/designcraft.git
synced 2026-11-21 20:39:22 +00:00
Merge pull request #2796 from aiongg/open-background
Open: read and parse documents off the UI thread
This commit is contained in:
@@ -233,6 +233,7 @@ fn services() -> Services {
|
||||
clipboard_change: Some(Box::new(clipboard_image::change_count)),
|
||||
#[cfg(target_os = "macos")]
|
||||
pointer: Some(Box::new(pointer::screen_position)),
|
||||
open_in_background: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,6 +390,8 @@ pub(crate) use file::load_document_fonts;
|
||||
pub use file::{
|
||||
DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use file::{ReadDocument, read_document};
|
||||
pub use layout::chapter_numbering;
|
||||
pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_base64, check_pasted_size, pasted_pixels, pasted_png};
|
||||
pub use paste_svg::is_svg_markup;
|
||||
|
||||
@@ -20,6 +20,8 @@ mod snippets;
|
||||
|
||||
pub use bytes::{DOCUMENT_SNIFF_BYTES, base64_decode, base64_encode, from_bytes, is_document, to_bytes, with_document_extension};
|
||||
pub(crate) use open::load_document_fonts;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use open::{ReadDocument, read_document};
|
||||
pub use open::{RecentPreview, recent_preview};
|
||||
pub(crate) use place::{crop_pdf, crop_pdf_from, document_of, prepare_placed, read_source, validate_placement};
|
||||
pub use registry::specs;
|
||||
|
||||
@@ -70,47 +70,14 @@ pub(super) fn file_open_recent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// `file.open`: the document opens and moves to the front of File › Open Recent.
|
||||
pub(super) fn file_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = open_path(s, p)?;
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
s.prefs.note_recent_file(path);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn open_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
// The content decides first: a file's extension may be missing or wrong. The extension
|
||||
// then routes files whose content isn't recognised to the reader that explains why.
|
||||
let format = craft_file_formats::detect(path, &bytes);
|
||||
let native = matches!(
|
||||
craft_file_formats::detect("", &bytes),
|
||||
Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson)
|
||||
);
|
||||
let legacy = (format == Some(craft_file_formats::Format::Indd) && !native).then(|| load_bytes(&bytes).ok()).flatten();
|
||||
if format == Some(craft_file_formats::Format::Idml) || (!native && format == Some(craft_file_formats::Format::Indd) && legacy.is_none()) {
|
||||
return crate::cmd::interchange::open_idml(s, p);
|
||||
}
|
||||
if !native && legacy.is_none() {
|
||||
return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file")));
|
||||
}
|
||||
let (mut d, mut warnings) = match legacy {
|
||||
Some(loaded) => loaded,
|
||||
None => load_bytes(&bytes)?,
|
||||
let read = match s.staged_open.take().filter(|r| r.path == path) {
|
||||
Some(read) => read,
|
||||
None => read_document(path, &std::sync::atomic::AtomicBool::new(false))?,
|
||||
};
|
||||
crate::cmd::interchange::resolve_packaged_links(&mut d, Some(std::path::Path::new(path)));
|
||||
crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path)));
|
||||
let links = crate::cmd::native_links::resolve(&mut d, Some(std::path::Path::new(path)), true);
|
||||
let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path);
|
||||
warnings.extend(font_warnings);
|
||||
warnings.extend(crate::cmd::style::grep_style_warnings(&d));
|
||||
let mut st = DocState::new(d, Some(path.to_string()));
|
||||
st.fonts = fonts;
|
||||
let checks = crate::cmd::native_links::start(&mut st, links);
|
||||
let i = s.add_document(st);
|
||||
Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "linkChecks": checks}))
|
||||
install_document(s, read)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
@@ -119,6 +86,94 @@ fn open_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A document file read and parsed by [`read_document`], which needs no session and may run on
|
||||
/// any thread. `file.open` reads its file this way and then opens what it read; one read ahead
|
||||
/// of time is handed to it with [`Session::stage_open`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub struct ReadDocument {
|
||||
path: String,
|
||||
content: ReadContent,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
enum ReadContent {
|
||||
/// A DesignCraft document (or one with an InDesign extension), its repair warnings, and the
|
||||
/// links found for the background check.
|
||||
Native { doc: Box<Document>, warnings: Vec<String>, links: crate::cmd::native_links::Opened },
|
||||
/// An IDML or InDesign file's bytes, imported when installed.
|
||||
Interchange(Vec<u8>),
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl ReadDocument {
|
||||
/// The file the document was read from.
|
||||
pub fn path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and parse the document file at `path` for `file.open`: the slow part of
|
||||
/// `file.open` (reading, unzipping and decoding the document, finding its linked files). The
|
||||
/// file roots in force on the calling thread apply. When `cancel` is set between steps it stops
|
||||
/// with an error.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn read_document(path: &str, cancel: &std::sync::atomic::AtomicBool) -> Result<ReadDocument> {
|
||||
let cancelled = || cancel.load(std::sync::atomic::Ordering::Relaxed).then(|| EngineError::Other(format!("{path}: opening cancelled")));
|
||||
let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
if let Some(e) = cancelled() {
|
||||
return Err(e);
|
||||
}
|
||||
// The content decides first: a file's extension may be missing or wrong. The extension
|
||||
// then routes files whose content isn't recognised to the reader that explains why.
|
||||
let format = craft_file_formats::detect(path, &bytes);
|
||||
let native =
|
||||
matches!(craft_file_formats::detect("", &bytes), Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson));
|
||||
let legacy = (format == Some(craft_file_formats::Format::Indd) && !native).then(|| load_bytes(&bytes).ok()).flatten();
|
||||
if format == Some(craft_file_formats::Format::Idml) || (!native && format == Some(craft_file_formats::Format::Indd) && legacy.is_none()) {
|
||||
return Ok(ReadDocument { path: path.to_string(), content: ReadContent::Interchange(bytes) });
|
||||
}
|
||||
if !native && legacy.is_none() {
|
||||
return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file")));
|
||||
}
|
||||
let (mut d, warnings) = match legacy {
|
||||
Some(loaded) => loaded,
|
||||
None => load_bytes(&bytes)?,
|
||||
};
|
||||
drop(bytes);
|
||||
if let Some(e) = cancelled() {
|
||||
return Err(e);
|
||||
}
|
||||
let file = std::path::Path::new(path);
|
||||
crate::cmd::interchange::resolve_packaged_links(&mut d, Some(file));
|
||||
crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(file));
|
||||
let links = crate::cmd::native_links::resolve(&mut d, Some(file), true);
|
||||
Ok(ReadDocument { path: path.to_string(), content: ReadContent::Native { doc: Box::new(d), warnings, links } })
|
||||
}
|
||||
|
||||
/// Open the document [`read_document`] read as the active document, with its fonts and the
|
||||
/// background check of its linked files, and move its file to the front of File › Open Recent.
|
||||
/// → what `file.open` answers.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn install_document(s: &mut Session, read: ReadDocument) -> Result<Value> {
|
||||
let ReadDocument { path, content } = read;
|
||||
let r = match content {
|
||||
ReadContent::Interchange(bytes) => crate::cmd::interchange::open_idml_file(s, bytes, &path)?,
|
||||
ReadContent::Native { doc, mut warnings, links } => {
|
||||
let mut d = *doc;
|
||||
let (fonts, faces, font_warnings) = load_document_fonts(&mut d, &path);
|
||||
warnings.extend(font_warnings);
|
||||
warnings.extend(crate::cmd::style::grep_style_warnings(&d));
|
||||
let mut st = DocState::new(d, Some(path.clone()));
|
||||
st.fonts = fonts;
|
||||
let checks = crate::cmd::native_links::start(&mut st, links);
|
||||
let i = s.add_document(st);
|
||||
json!({"index": i, "documentFonts": faces, "warnings": warnings, "linkChecks": checks})
|
||||
}
|
||||
};
|
||||
s.prefs.note_recent_file(&path);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Load the fonts in the `Document Fonts` folder beside the document file at `path` for `d` alone
|
||||
/// (`d.font_scope`) → (the scope, for the document's state to hold; faces; a warning for each
|
||||
/// font file skipped). Nothing on the web (no folders).
|
||||
@@ -699,3 +754,58 @@ mod recent_tests {
|
||||
assert!(old.recent_files.is_empty(), "older prefs.json without the list still load");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod read_install_tests {
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::read_document;
|
||||
use crate::Session;
|
||||
|
||||
/// A document read on another thread and staged for `file.open` (what a background open
|
||||
/// does) gives the document, answer and recent files that `file.open` reading the file gives,
|
||||
/// without reading the file again.
|
||||
#[test]
|
||||
fn a_document_read_on_another_thread_opens_as_file_open_opens_it() {
|
||||
let dir = std::env::temp_dir().join(format!("dc-read-install-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let image = dir.join("photo.png");
|
||||
std::fs::write(&image, designcraft_render::Rendered { width: 40, height: 20, pixels: [200, 90, 30, 255].repeat(800) }.to_png()).unwrap();
|
||||
let path = dir.join("Brochure.designcraft").to_string_lossy().to_string();
|
||||
let mut writer = Session::new();
|
||||
writer.execute("file.new", &json!({})).unwrap();
|
||||
writer.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap();
|
||||
writer.execute("file.place", &json!({"path": image.to_string_lossy(), "x": 40, "y": 260})).unwrap();
|
||||
writer.execute("file.save", &json!({"path": path})).unwrap();
|
||||
|
||||
let mut by_command = Session::new();
|
||||
let opened = by_command.execute("file.open", &json!({"path": path})).unwrap();
|
||||
|
||||
let worker_path = path.clone();
|
||||
let read = std::thread::spawn(move || read_document(&worker_path, &AtomicBool::new(false))).join().unwrap().unwrap();
|
||||
assert_eq!(read.path(), path);
|
||||
let saved = std::fs::read(&path).unwrap();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let mut staged = Session::new();
|
||||
staged.stage_open(read);
|
||||
let installed = staged.execute("file.open", &json!({"path": path})).unwrap();
|
||||
|
||||
assert_eq!(installed, opened);
|
||||
// Asset data keys are process-wide counters, so compare the saved form and the data apart.
|
||||
let (a, b) = (&staged.doc().unwrap().doc, &by_command.doc().unwrap().doc);
|
||||
assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap());
|
||||
let data = |d: &designcraft_doc::Document| d.assets.values().map(|x| (x.id, x.data.is_linked(), x.data.len())).collect::<Vec<_>>();
|
||||
assert_eq!(data(a), data(b));
|
||||
assert_eq!(staged.doc().unwrap().path, by_command.doc().unwrap().path);
|
||||
assert_eq!(staged.prefs.recent_files, by_command.prefs.recent_files);
|
||||
assert!(staged.execute("file.open", &json!({"path": path})).is_err(), "a staged document opens once");
|
||||
|
||||
std::fs::write(&path, saved).unwrap();
|
||||
let cancelled = read_document(&path, &AtomicBool::new(true));
|
||||
assert!(cancelled.is_err_and(|e| e.to_string().contains("cancelled")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,20 +474,30 @@ fn read_packaged_link(link: &str, package: Option<&std::path::Path>) -> Option<(
|
||||
}
|
||||
|
||||
pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (bytes, package, file, title) = if let Some(b) = str_param(p, "base64") {
|
||||
if let Some(b) = str_param(p, "base64") {
|
||||
let name = str_param(p, "name").unwrap_or_default();
|
||||
(base64_decode(b), None, name.to_string(), without_document_extension(name).to_string())
|
||||
} else if let Some(path) = str_param(p, "path") {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let b = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let b: Vec<u8> = Vec::new();
|
||||
let pp = std::path::Path::new(path);
|
||||
let file = pp.file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string());
|
||||
(b, Some(pp.to_path_buf()), file, pp.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_default())
|
||||
} else {
|
||||
return Err(bad("file.openIdml", "missing `path` or `base64`"));
|
||||
};
|
||||
return import_interchange(s, base64_decode(b), None, name.to_string(), without_document_extension(name).to_string());
|
||||
}
|
||||
let Some(path) = str_param(p, "path") else { return Err(bad("file.openIdml", "missing `path` or `base64`")) };
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let b = crate::io::read_file(path).map_err(EngineError::Other)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let b: Vec<u8> = Vec::new();
|
||||
open_idml_file(s, b, path)
|
||||
}
|
||||
|
||||
/// Open the IDML or InDesign file at `path`, whose content is `bytes`: titled by its file name,
|
||||
/// with the fonts in the `Document Fonts` folder beside it.
|
||||
pub(crate) fn open_idml_file(s: &mut Session, bytes: Vec<u8>, path: &str) -> Result<Value> {
|
||||
let pp = std::path::Path::new(path);
|
||||
let file = pp.file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string());
|
||||
let title = pp.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
import_interchange(s, bytes, Some(pp), file, title)
|
||||
}
|
||||
|
||||
/// Import IDML or InDesign `bytes` named `file` as a new document titled `title`. `package` is
|
||||
/// the file they were read from, which links resolve against and whose folder's fonts load.
|
||||
fn import_interchange(s: &mut Session, bytes: Vec<u8>, package: Option<&std::path::Path>, file: String, title: String) -> Result<Value> {
|
||||
let mut warnings = Vec::new();
|
||||
// InDesign's previews of linked graphics show while their files are missing (graphic `Self` →
|
||||
// preview), as InDesign shows them. One preview can stand for any number of graphics: they
|
||||
@@ -511,12 +521,12 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
let (mut d, import_warnings, story_ids) = import_report_with_previews(&bytes, package.as_deref(), &previews)?;
|
||||
let (mut d, import_warnings, story_ids) = import_report_with_previews(&bytes, package, &previews)?;
|
||||
warnings.extend(import_warnings);
|
||||
if !title.is_empty() {
|
||||
d.title = title;
|
||||
}
|
||||
let (fonts, faces, font_warnings) = match str_param(p, "path").filter(|_| str_param(p, "base64").is_none()) {
|
||||
let (fonts, faces, font_warnings) = match package.and_then(std::path::Path::to_str) {
|
||||
Some(path) => super::file::load_document_fonts(&mut d, path),
|
||||
None => (None, 0, Vec::new()),
|
||||
};
|
||||
|
||||
@@ -411,6 +411,9 @@ pub struct Session {
|
||||
/// The selection tool (`selection` or `directSelection`) chosen last: the one Cmd borrows.
|
||||
pub(crate) last_selection_tool: &'static str,
|
||||
pub journal: Vec<(String, Value)>,
|
||||
/// A document read ahead of `file.open` ([`Session::stage_open`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) staged_open: Option<cmd::ReadDocument>,
|
||||
pub(crate) find_context: Option<cmd::find::FindContext>,
|
||||
pub clipboard: Option<Arc<Document>>,
|
||||
/// The x the clipboard's objects are measured from on their spread: its spine, or the left edge of
|
||||
@@ -486,6 +489,8 @@ impl Session {
|
||||
temp_tool: None,
|
||||
last_selection_tool: "selection",
|
||||
journal: vec![],
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
staged_open: None,
|
||||
find_context: None,
|
||||
clipboard: None,
|
||||
clipboard_origin: 0.0,
|
||||
@@ -563,6 +568,14 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand `file.open` a document [`cmd::read_document`] read: the next `file.open` of its path
|
||||
/// opens it instead of reading the file, so the slow read can run on another thread. Any other
|
||||
/// `file.open` drops it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn stage_open(&mut self, read: cmd::ReadDocument) {
|
||||
self.staged_open = Some(read);
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, i: usize) {
|
||||
if i < self.docs.len() && self.active != Some(i) {
|
||||
// The composition belongs to the document it shows in.
|
||||
|
||||
@@ -19,6 +19,8 @@ mod frame;
|
||||
mod ime;
|
||||
mod input;
|
||||
mod keys;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) mod opening;
|
||||
mod quit;
|
||||
mod screenshot;
|
||||
mod view;
|
||||
@@ -130,6 +132,8 @@ impl DesignApp {
|
||||
quit_without_asking: false,
|
||||
quitting: None,
|
||||
waiting_save: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
opening: Vec::new(),
|
||||
cursors: cursors::Images::default(),
|
||||
live_preview: LivePreview::default(),
|
||||
updates_rt: updates_ui::Runtime::default(),
|
||||
|
||||
@@ -32,9 +32,28 @@ impl DesignApp {
|
||||
if purpose == "place" {
|
||||
return self.place_path(&path, false);
|
||||
}
|
||||
self.open_document(path)
|
||||
}
|
||||
|
||||
/// Open the document file at `path` as `file.open` does. Chosen by the person (File › Open,
|
||||
/// Open Recent, a drop, the operating system), the file is read on a worker thread where the
|
||||
/// host allows it ([`crate::Services::open_in_background`]) and opens on a later frame, with
|
||||
/// `Ok(Null)` now. Scripts and the control channel open it at once, so their next command
|
||||
/// finds it open.
|
||||
pub(crate) fn open_document(&mut self, path: String) -> Result<Value, String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.opens_in_background() {
|
||||
return self.open_in_background(path);
|
||||
}
|
||||
self.open_file("file.open", json!({"path": path}))
|
||||
}
|
||||
|
||||
/// Whether [`Self::open_document`] reads the file on a worker thread.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn opens_in_background(&self) -> bool {
|
||||
self.services.open_in_background && !self.in_control
|
||||
}
|
||||
|
||||
/// File › Place of the file at `path`, asking a multi-page PDF's Image Import Options first.
|
||||
/// With `append`, an image that loads the cursor queues after the ones already loaded rather
|
||||
/// than replacing them.
|
||||
@@ -376,7 +395,7 @@ impl DesignApp {
|
||||
&& designcraft_engine::io::read_capped(path, designcraft_engine::cmd::DOCUMENT_SNIFF_BYTES)
|
||||
.is_ok_and(|b| designcraft_engine::cmd::is_document(&b)));
|
||||
if document {
|
||||
return self.open_file("file.open", json!({"path": path}));
|
||||
return self.open_document(path.to_string());
|
||||
}
|
||||
// A graphic dropped on a frame that takes one fills it, as File > Place does. Text keeps
|
||||
// getting a frame of its own, so it never replaces the image in a graphic frame.
|
||||
@@ -423,7 +442,7 @@ impl DesignApp {
|
||||
|
||||
pub(crate) fn open_os_documents(&mut self) {
|
||||
for path in std::mem::take(&mut self.os_documents) {
|
||||
if let Err(e) = self.open_file("file.open", json!({"path": path})) {
|
||||
if let Err(e) = self.open_document(path.clone()) {
|
||||
log::warn!("{path}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ impl DesignApp {
|
||||
self.handle_file_dialog_answers();
|
||||
self.drain_inbox();
|
||||
self.open_os_documents();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.poll_opening(ctx);
|
||||
self.poll_link_checks(ctx);
|
||||
}
|
||||
if self.host_order_pending() {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Opening a document file without stopping the UI: the file is read and parsed on a worker
|
||||
//! thread ([`designcraft_engine::cmd::read_document`]), and `file.open` opens what it read on a
|
||||
//! later frame. A large file with embedded images takes seconds to read; the status line says
|
||||
//! which file is opening, and Esc stops waiting for it.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use designcraft_engine::cmd::ReadDocument;
|
||||
|
||||
use super::{DesignApp, Value, json};
|
||||
|
||||
/// A document file being read on a worker thread.
|
||||
pub(crate) struct Opening {
|
||||
path: String,
|
||||
/// The file name, for the status line and the alert.
|
||||
name: String,
|
||||
cancel: Arc<AtomicBool>,
|
||||
read: Receiver<Result<ReadDocument, String>>,
|
||||
}
|
||||
|
||||
impl Drop for Opening {
|
||||
/// A read nobody waits for any more stops at its next step.
|
||||
fn drop(&mut self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl DesignApp {
|
||||
/// Read the file at `path` on a worker thread; [`Self::poll_opening`] opens it when it is in.
|
||||
/// The same file asked for again while it is read opens once.
|
||||
pub(super) fn open_in_background(&mut self, path: String) -> Result<Value, String> {
|
||||
if self.opening.iter().any(|o| o.path == path) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (send, read) = std::sync::mpsc::channel();
|
||||
// The file roots in force here apply on the worker too.
|
||||
let roots = designcraft_engine::file_access::current();
|
||||
let wake = self.egui_ctx.clone();
|
||||
let (worker_path, worker_cancel) = (path.clone(), Arc::clone(&cancel));
|
||||
let spawned = std::thread::Builder::new().name("designcraft-open".into()).spawn(move || {
|
||||
let read = designcraft_engine::file_access::confine(roots.as_ref(), || {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| designcraft_engine::cmd::read_document(&worker_path, &worker_cancel)))
|
||||
});
|
||||
let read = match read {
|
||||
Ok(read) => read.map_err(|e| e.to_string()),
|
||||
Err(_) => Err(format!("{worker_path}: the file could not be read")),
|
||||
};
|
||||
// The app may have stopped waiting (Esc): nobody to tell then.
|
||||
let _ = send.send(read);
|
||||
if let Some(ctx) = wake {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("opening {path} without a thread: {e}");
|
||||
return self.open_file("file.open", json!({"path": path}));
|
||||
}
|
||||
self.opening.push(Opening { path, name, cancel, read });
|
||||
self.show_opening();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The status line while files are read: the first one still opening.
|
||||
fn show_opening(&mut self) {
|
||||
if let Some(name) = self.opening.first().map(|o| o.name.clone()) {
|
||||
self.status(crate::i18n::tr(&self.ui.language, "Opening {name}…").replace("{name}", &name));
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the files whose reads are done, in the order they were asked for, and stop waiting
|
||||
/// for all of them on Esc. Repaints at a low rate while reads run, so the status line stays.
|
||||
pub(crate) fn poll_opening(&mut self, ctx: &egui::Context) {
|
||||
if self.opening.is_empty() {
|
||||
return;
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
|
||||
// Dropping them tells their workers to stop.
|
||||
self.opening.clear();
|
||||
self.status(crate::i18n::tr(&self.ui.language, "Opening cancelled"));
|
||||
return;
|
||||
}
|
||||
let mut done = Vec::new();
|
||||
for o in std::mem::take(&mut self.opening) {
|
||||
match o.read.try_recv() {
|
||||
Ok(read) => done.push((o, read)),
|
||||
Err(TryRecvError::Empty) => self.opening.push(o),
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
let lost = format!("{}: the file could not be read", o.path);
|
||||
done.push((o, Err(lost)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (o, read) in done {
|
||||
// The status line said the file was opening; what the open reports replaces it.
|
||||
self.status(String::new());
|
||||
let params = json!({"path": o.path});
|
||||
match read {
|
||||
Ok(read) => {
|
||||
self.session.stage_open(read);
|
||||
let _ = self.open_named_file("file.open", params, o.name.clone());
|
||||
}
|
||||
Err(e) => {
|
||||
let alert = json!({"title": "Can't Open the File", "file": o.name, "message": e});
|
||||
self.status(e);
|
||||
self.ui.dialog = Some(crate::dialogs::Dialog::new("alert", alert));
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.opening.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.ui.status.is_empty() {
|
||||
self.show_opening();
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
@@ -315,6 +315,9 @@ pub struct DesignApp {
|
||||
/// A save asked for while the open-time checks of the document's linked files run: it runs
|
||||
/// once they are done, so the first save already writes the links they confirm.
|
||||
pub(crate) waiting_save: Option<WaitingSave>,
|
||||
/// Document files being read on worker threads, in the order they were asked for.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) opening: Vec<app::opening::Opening>,
|
||||
/// The tool cursor bitmaps handed to the OS.
|
||||
pub cursors: cursors::Images,
|
||||
/// A panel's live preview (a slider being dragged), committed when it is let go.
|
||||
|
||||
@@ -150,12 +150,16 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
|
||||
},
|
||||
"app.openRecent" => {
|
||||
let index = p.get("index").cloned().unwrap_or(Value::Null);
|
||||
let name = index
|
||||
.as_u64()
|
||||
.and_then(|i| usize::try_from(i).ok())
|
||||
.and_then(|i| app.session.prefs.recent_files.get(i))
|
||||
.map(|path| recent_label(path))
|
||||
.unwrap_or_default();
|
||||
let path = index.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| app.session.prefs.recent_files.get(i)).cloned();
|
||||
// Read in the background, a file still there opens as File › Open opens it;
|
||||
// `file.openRecent` explains a missing one.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if app.opens_in_background()
|
||||
&& let Some(path) = path.as_ref().filter(|p| designcraft_engine::io::is_file(p))
|
||||
{
|
||||
return Some(app.open_document(path.clone()));
|
||||
}
|
||||
let name = path.as_deref().map(recent_label).unwrap_or_default();
|
||||
app.open_named_file("file.openRecent", json!({"index": index}), name)
|
||||
}
|
||||
"app.placeDialog" => match (p.get("path").and_then(Value::as_str), p.get("paths").and_then(Value::as_array)) {
|
||||
|
||||
@@ -88,4 +88,8 @@ pub struct Services {
|
||||
/// pointer events fills no frame: an image loads the place cursor, and other files land in the
|
||||
/// middle of the view (`canvas::drop_point`).
|
||||
pub pointer: Option<PointerFn>,
|
||||
/// Documents the person opens (File › Open, Open Recent, a drop, the operating system) are
|
||||
/// read on a worker thread while the UI keeps running, with "Opening …" in the status line.
|
||||
/// Off: they open within the command, as scripts' opens always do.
|
||||
pub open_in_background: bool,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user