mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 02:48:02 -06:00
File › Open With reads a picked file on the thread File › Open uses, with the importer and its parameters, so a slow importer does not freeze the window. A call that names path still gets document.open's result. Cancel in the progress window now raises a cancel token on that thread, which stops a running importer between two slices of its budget.
251 lines
11 KiB
Rust
251 lines
11 KiB
Rust
//! Opening documents off the UI thread (desktop): a file the user asks to open (File › Open, Open
|
||
//! Recent, the Home screen, files handed to the app) is decoded on a thread of its own, which also
|
||
//! reads its linked files and lays out its type, while the status bar shows it, and opens in a new tab
|
||
//! once it is ready, as it would at once: the same notes, recent files and errors. A file that takes
|
||
//! longer than [`DELAY`] shows a progress window ([`show`]): its name, a bar that moves while it is
|
||
//! read (the reader counts no steps), Cancel (also Esc, `file.cancelOpen`: the file doesn't open)
|
||
//! and Continue in Background (`file.openInBackground`: it goes on, shown in the status bar). On
|
||
//! wasm (no threads) and in unit tests it opens at once ([`available`]).
|
||
|
||
use std::sync::Arc;
|
||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||
|
||
use serde_json::{Value, json};
|
||
use vectorcraft_engine::cancel::{self, CancelToken};
|
||
use vectorcraft_engine::cmd::fileio::{self, ReadFile};
|
||
use vectorcraft_engine::file_access::ScopeHandle;
|
||
|
||
use crate::VectorcraftApp;
|
||
use crate::export_progress::{self, Pressed};
|
||
|
||
pub use crate::export_progress::DELAY;
|
||
|
||
/// A file being read.
|
||
pub struct Pending {
|
||
id: u64,
|
||
/// Where it is.
|
||
pub path: String,
|
||
/// What the status bar shows ("Opening Poster.vectorcraft").
|
||
pub label: String,
|
||
done: Receiver<Result<ReadFile, String>>,
|
||
/// The automation roots in force where the open started: the document is installed under
|
||
/// them too (its links are read as it opens).
|
||
scope: ScopeHandle,
|
||
/// Raised by Cancel, on the thread reading the file: an importer plug-in stops.
|
||
token: CancelToken,
|
||
/// Continue in Background: the progress window no longer shows it.
|
||
pub hidden: bool,
|
||
}
|
||
|
||
/// The files being read.
|
||
#[derive(Default)]
|
||
pub struct Opening {
|
||
pub pending: Vec<Pending>,
|
||
/// Open documents asked for again while the active one couldn't change: their tabs come to
|
||
/// the front once it can ([`may_switch`]), each in the file access scope it was asked in.
|
||
pub activate: Vec<(String, ScopeHandle)>,
|
||
next_id: u64,
|
||
}
|
||
|
||
/// Is a long operation running that should show the busy cursor and status spinner (background
|
||
/// save/export with a label, a file opening or being read for Place off the UI thread, a heavy plug-in filter, or an
|
||
/// Image Trace)?
|
||
pub fn long_operation_busy(app: &VectorcraftApp) -> bool {
|
||
app.background.jobs.iter().any(|j| !j.label.is_empty() && !j.cancelled())
|
||
|| !app.opening.pending.is_empty()
|
||
|| !app.plugin_runs.running.is_empty()
|
||
|| !app.placing.pending.is_empty()
|
||
|| !app.trace_runs.running.is_empty()
|
||
}
|
||
|
||
/// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look
|
||
/// at the document right after asking for it), or with `VECTORCRAFT_SYNC_OPEN` set.
|
||
pub fn available() -> bool {
|
||
!(cfg!(target_arch = "wasm32") || cfg!(test) || std::env::var_os("VECTORCRAFT_SYNC_OPEN").is_some())
|
||
}
|
||
|
||
/// Decode `bytes`, the file at `path`, read its linked files and lay out its type on a thread of its
|
||
/// own ([`fileio::read_for_open`]) → `{background: true, status}`, or the bytes back when no thread
|
||
/// could start (the caller opens the file at once).
|
||
pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>) -> Result<Value, Vec<u8>> {
|
||
start_with(app, path, bytes, Value::Null)
|
||
}
|
||
|
||
/// [`start`] with the `document.open` options in `params` (`importer` and its `params`).
|
||
pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>, params: Value) -> Result<Value, Vec<u8>> {
|
||
let (tx, done) = channel();
|
||
let bytes = Arc::new(bytes);
|
||
let (name, file) = (path.to_string(), bytes.clone());
|
||
// Update Links (Preferences › File Handling) applies there as it is set now.
|
||
let update_links = app.session.prefs.update_links == "automatically";
|
||
let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps;
|
||
// The automation roots in force here are in force there.
|
||
let scope = ScopeHandle::capture();
|
||
let opener = scope.clone();
|
||
let token = CancelToken::new();
|
||
let raised = token.clone();
|
||
let spawned = std::thread::Builder::new().name("vectorcraft-open".into()).spawn(move || {
|
||
let r = scope
|
||
.run(|| {
|
||
vectorcraft_engine::guard::catch_panic(|| {
|
||
cancel::scope(&raised, None, || {
|
||
fileio::read_for_open(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps).map_err(|e| e.to_string())
|
||
})
|
||
})
|
||
})
|
||
.unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)")));
|
||
// The file's bytes go before the document is handed over.
|
||
drop(file);
|
||
// The app may have quit meanwhile: nothing to hand it to.
|
||
let _ = tx.send(r);
|
||
});
|
||
if spawned.is_err() {
|
||
return Err(Arc::try_unwrap(bytes).unwrap_or_else(|b| b.to_vec()));
|
||
}
|
||
let label = format!("Opening {}", fileio::file_name(path));
|
||
app.opening.next_id += 1;
|
||
let id = app.opening.next_id;
|
||
app.opening.pending.push(Pending { id, path: path.to_string(), label: label.clone(), done, scope: opener, token, hidden: false });
|
||
let status = format!("{label}…");
|
||
app.status(status.clone());
|
||
Ok(json!({ "background": true, "status": status }))
|
||
}
|
||
|
||
/// May the active document change now ([`poll`])?
|
||
pub(crate) fn may_switch(app: &VectorcraftApp) -> bool {
|
||
let s = &app.session;
|
||
!(app.ui.dialog.is_some() || s.in_interaction() || (s.tool_busy() && s.pointer_held()))
|
||
}
|
||
|
||
/// Open the files that are ready (each frame). Not while a dialog is open: a document that opens
|
||
/// becomes the active one, and the dialog's OK acts on the active document (#1694: Save As
|
||
/// options confirmed after another file had finished opening saved that file's art under the
|
||
/// first one's name). The files wait, their status line too, until the dialog is closed. Nor while
|
||
/// an interaction is open (a drag, a slider's preview, or a tool's preview between its clicks) or
|
||
/// a tool is busy with a drag of its own while the pointer button is held: a document that opens
|
||
/// cancels it. A tool that is busy while the button is not held and no interaction is open is
|
||
/// waiting between its clicks (the Dimension tool after its first point): the file opens, and the
|
||
/// tool starts afresh, as when the user switches documents.
|
||
pub fn poll(app: &mut VectorcraftApp) {
|
||
// One at a time: a document that opens again (closed meanwhile) may ask about its links or
|
||
// fonts, and the rest wait for that dialog too.
|
||
loop {
|
||
if !may_switch(app) {
|
||
return;
|
||
}
|
||
if app.opening.activate.is_empty() {
|
||
break;
|
||
}
|
||
let (path, scope) = app.opening.activate.remove(0);
|
||
// Closed meanwhile, it opens again; a failure is reported to the user there.
|
||
let _ = scope.run(|| crate::io::open_reporting(app, &path));
|
||
}
|
||
let mut i = 0;
|
||
while let Some(p) = app.opening.pending.get(i) {
|
||
let r = match p.done.try_recv() {
|
||
Ok(r) => r,
|
||
Err(TryRecvError::Empty) => {
|
||
i += 1;
|
||
continue;
|
||
}
|
||
Err(TryRecvError::Disconnected) => Err("the file stopped being read (please report this bug)".to_string()),
|
||
};
|
||
let p = app.opening.pending.remove(i);
|
||
// The status bar no longer says it is opening.
|
||
if app.ui.status == format!("{}…", p.label) {
|
||
app.ui.status.clear();
|
||
}
|
||
p.scope.run(|| finish(app, &p.path, r));
|
||
// A file that opened and asks about its links or fonts holds back the others too.
|
||
if !may_switch(app) {
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The progress window's Cancel: the files being read don't open. An importer plug-in stops
|
||
/// between two slices of its budget; a built-in reader finishes reading and the result is dropped
|
||
/// → `{cancelled: n}`.
|
||
pub fn cancel_all(app: &mut VectorcraftApp) -> Value {
|
||
let cancelled = std::mem::take(&mut app.opening.pending);
|
||
for p in &cancelled {
|
||
p.token.cancel();
|
||
// The status bar no longer says it is opening.
|
||
if app.ui.status == format!("{}…", p.label) {
|
||
app.ui.status.clear();
|
||
}
|
||
}
|
||
json!({ "cancelled": cancelled.len() })
|
||
}
|
||
|
||
/// The progress window's Continue in Background: the files go on being read, shown in the status
|
||
/// bar only → `{hidden: n}`.
|
||
pub fn hide_all(app: &mut VectorcraftApp) -> Value {
|
||
let mut n = 0;
|
||
for p in app.opening.pending.iter_mut().filter(|p| !p.hidden) {
|
||
p.hidden = true;
|
||
n += 1;
|
||
}
|
||
json!({ "hidden": n })
|
||
}
|
||
|
||
/// Is a file being read that the progress window shows?
|
||
pub fn any_shown(app: &VectorcraftApp) -> bool {
|
||
app.opening.pending.iter().any(|p| !p.hidden)
|
||
}
|
||
|
||
/// The progress window of the first file being read it shows, once that has been read for
|
||
/// [`DELAY`]: a quick open doesn't flash it. Not while a dialog or another progress window (an
|
||
/// export, a heavy plug-in filter, an Image Trace) is open: never two modals at once.
|
||
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||
let shown: Vec<&Pending> = app.opening.pending.iter().filter(|p| !p.hidden).collect();
|
||
let Some(first) = shown.first() else { return };
|
||
let now = ctx.input(|i| i.time);
|
||
let since = ctx.data_mut(|m| {
|
||
let seen = m.get_temp_mut_or_insert_with(egui::Id::unique("opening-seen"), || (first.id, now));
|
||
if seen.0 != first.id {
|
||
*seen = (first.id, now);
|
||
}
|
||
seen.1
|
||
});
|
||
let exporting = app.background.jobs.iter().any(|j| j.progress.is_some() && !j.hidden && !j.cancelled());
|
||
let other = exporting || crate::plugin_runs::any_shown(app) || crate::trace_runs::any_shown(app);
|
||
if now - since < DELAY || app.ui.dialog.is_some() || other {
|
||
return;
|
||
}
|
||
let heading = format!("{}…", crate::i18n::msg(&first.label));
|
||
let more = shown.len() - 1;
|
||
let t = crate::theme::Tokens::get(ctx);
|
||
let pressed = export_progress::window(ctx, "opening-progress", &heading, |ui| {
|
||
export_progress::indeterminate(ui, tl!("Reading the file…"));
|
||
if more > 0 {
|
||
ui.add_space(6.0);
|
||
let queued = crate::i18n::tn(more as u64, "{n} more file waiting", "{n} more files waiting");
|
||
ui.label(egui::RichText::new(queued).size(11.5).color(t.text_dim));
|
||
}
|
||
});
|
||
let id = match pressed {
|
||
Some(Pressed::Cancel) => "file.cancelOpen",
|
||
Some(Pressed::Hide) => "file.openInBackground",
|
||
None => return,
|
||
};
|
||
if let Err(e) = app.run(id, json!({})) {
|
||
app.status(e);
|
||
}
|
||
}
|
||
|
||
/// Open a file read off the UI thread, as [`crate::io::open_reporting`] opens one read at once.
|
||
fn finish(app: &mut VectorcraftApp, path: &str, r: Result<ReadFile, String>) {
|
||
let opened = r.and_then(|file| fileio::open_read(&mut app.session, file).map_err(|e| e.to_string()));
|
||
match opened {
|
||
Ok(r) => {
|
||
crate::io::opened(app, &r);
|
||
crate::io::note_recent(app, path);
|
||
}
|
||
Err(e) => crate::io::report_open_error(app, &fileio::file_name(path), &e),
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests;
|