files-w5: net change of 2 commits

- files-w5: written from its sheet
- files-w5: repair 1
This commit is contained in:
bflatastic
2026-11-21 23:42:14 +07:00
parent 2f04494f5c
commit ba6cec7ee2
4 changed files with 309 additions and 586 deletions
+24 -15
View File
@@ -1,34 +1,43 @@
use super::{VectorcraftApp, io, place};
use crate::services::Inbox;
use craft::host::{Host, PendingPick, PickKind};
impl VectorcraftApp {
/// A file dialog is open off the UI thread (a sheet on macOS, [`picks`]): what asked for it runs
/// again when it answers.
pub fn file_dialog_open(&self) -> bool {
self.picks.is_waiting()
/// The oldest pick the file service has not answered, the one on screen.
fn pending_pick(&self) -> Option<PendingPick> {
Host::try_of_ctx(self.ui_ctx.as_ref()?)?.files().pending_pick()
}
/// A file dialog is open as a sheet on the window ([`Services::dialogs_are_sheets`]): nothing
/// closes or quits until it answers.
/// A file dialog is open off the UI thread: what asked for it runs when it answers.
pub fn file_dialog_open(&self) -> bool {
self.pending_pick().is_some()
}
/// A file dialog is open as a sheet on the window: nothing closes or quits until it answers.
pub fn file_sheet_open(&self) -> bool {
self.services.dialogs_are_sheets && self.file_dialog_open()
self.pending_pick().is_some_and(|p| p.sheet)
}
/// The kind of dialog open (`ui.inspect`'s `fileDialog`).
pub(crate) fn file_dialog_kind(&self) -> Option<&'static str> {
let PendingPick { request, .. } = self.pending_pick()?;
Some(match request.kind {
_ if request.purpose == "place" => "place",
PickKind::Open | PickKind::OpenMany => "open",
PickKind::Save => "save",
PickKind::Folder => "folder",
})
}
pub(crate) fn drain_inbox(&mut self) {
fn take(q: Option<&Inbox>) -> Vec<(String, Vec<u8>)> {
q.map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default()
}
let answers = self.services.picked_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner())));
// The web's file picker answers for automation when automation opened it; the page's script
// is automation.
// The page's script is automation.
let mut arrived: Vec<_> = take(self.services.inbox.as_ref()).into_iter().map(|f| (f, false)).collect();
for answer in answers.unwrap_or_default() {
let automated = self.picks.answer_web_open();
arrived.extend(answer.map(|f| (f, automated)));
}
arrived.extend(take(self.services.page_inbox.as_ref()).into_iter().map(|f| (f, true)));
for ((name, bytes), automated) in arrived {
crate::picks::as_automated(self, automated, |app| {
crate::file_asks::as_automated(self, automated, |app| {
if let Err(e) = io::open_bytes(app, &name, &bytes, None) {
io::report_open_error(app, &name, &e);
}
+3 -6
View File
@@ -5,10 +5,7 @@ use super::{VectorcraftApp, browsable_url};
impl VectorcraftApp {
/// Open a link in the browser (Help → Discord, website, GitHub…).
pub fn open_url(&mut self, url: &str) {
match self.services.open_url.as_mut() {
Some(open) => open(url),
None => self.pending_url = Some(url.to_string()),
}
self.pending_url = Some(url.to_string());
self.ui.status = format!("Opened {url}");
}
@@ -37,10 +34,10 @@ impl VectorcraftApp {
}
/// Did automation ask for what is being handled now: [`Self::automation_is_acting`], or the
/// answer of a file dialog that automation opened ([`crate::picks::as_automated`]), even when a
/// answer of a file dialog that automation opened ([`crate::file_asks::as_automated`]), even when a
/// person picked the file in it?
pub(crate) fn automation_asked(&self) -> bool {
self.automation_is_acting() || self.picks.automated()
self.automation_is_acting() || self.file_asks.automated()
}
/// Run a Help link command and open the URL it returns.
+282
View File
@@ -0,0 +1,282 @@
//! What waits on a file dialog. The host's file service shows the picker and queues requests in
//! order; an ask files the continuation that handles the answer, and [`poll`] runs it once the
//! answer arrives, on the document it was asked for and under the access it was asked with.
// PLAN: this crate needs `craft-host` and `craft-dialogs` in its Cargo.toml (hub-w1 owns the manifest).
use std::path::PathBuf;
use craft::dialogs::ui::UnavailableWords;
use craft::host::{Host, PickId, PickKind, PickRequest, Picked};
use craft_ui::dialog::{DialogId, DialogResult, PromptChoice, StandardPrompt};
// PLAN: assumed re-export paths for `HostedParamDialog`, `PathRequest` and `Env`.
use craft_ui::HostedParamDialog;
use craft_ui::runtime::Env;
use craft_ui::runtime::requests::PathRequest;
use serde_json::{Map, Value, json};
use vectorcraft_engine::file_access::ScopeHandle;
use crate::VectorcraftApp;
use crate::dialogs::confirm::{ReplaceFiles, ReplaceFilesPrompt};
type Then = Box<dyn FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String>>;
/// Whose answer a continuation is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Owner {
/// The active document when it was asked: dropped with [`closed`] when it has closed, made
/// active before the continuation runs.
Document,
/// Acts on no document (an app preference, a library, a shortcut set): it goes on whatever is open.
Free,
}
/// A pick asked for and not yet answered.
struct Waiting {
ticket: PickId,
owner: Owner,
/// The active document's uid when asked (`DocState::uid`); `None` for [`Owner::Free`].
doc: Option<u64>,
/// The automation roots in force when asked: the continuation runs under them, not under the
/// desktop's access of the frame the answer comes in.
scope: ScopeHandle,
/// Automation asked ([`VectorcraftApp::automation_asked`]): the continuation runs as its.
automated: bool,
then: Then,
}
/// A replace question on the dialog host, and what proceeding runs.
struct Replacing {
dialog: DialogId,
then: Box<dyn FnOnce(&mut VectorcraftApp) -> Result<Value, String>>,
}
/// The app's pending file asks ([`VectorcraftApp`]'s `file_asks`).
#[derive(Default)]
pub(crate) struct FileAsks {
waiting: Vec<Waiting>,
replacing: Vec<Replacing>,
/// Numbers the replace questions so each is its own dialog.
next_question: u64,
automated: bool,
}
impl FileAsks {
/// What runs now handles the answer of a file dialog automation opened ([`as_automated`]).
pub(crate) fn automated(&self) -> bool {
self.automated
}
}
// PLAN: callers use the function form of `BUSY` and `CLOSED`; `tl!` is a runtime lookup, so they are not consts.
/// What the status bar says when a file dialog is open and the app must not go on.
pub(crate) fn busy() -> &'static str {
tl!("A file dialog is open: choose there first")
}
/// What the status bar says when the document a file dialog was asked for closed before it answered.
pub(crate) fn closed() -> &'static str {
tl!("The document was closed while its file dialog was open")
}
/// Run `f` as the continuation of a dialog automation opened (`automated`), or as a person's.
pub(crate) fn as_automated<R>(app: &mut VectorcraftApp, automated: bool, f: impl FnOnce(&mut VectorcraftApp) -> R) -> R {
let before = std::mem::replace(&mut app.file_asks.automated, automated);
let r = f(app);
app.file_asks.automated = before;
r
}
/// Whether a dialog for `kind` can open: every kind on the desktop, only the opening ones on the web.
pub(crate) fn can(app: &VectorcraftApp, kind: PickKind) -> bool {
matches!(kind, PickKind::Open | PickKind::OpenMany) || !crate::io::is_web(app)
}
/// Show `request` and run `then` with the answer. Returns `{pending: "fileDialog"}`, or `Null` when
/// no file service is there to ask.
pub(crate) fn ask(
app: &mut VectorcraftApp,
request: PickRequest,
owner: Owner,
then: impl FnOnce(&mut VectorcraftApp, Picked) -> Result<Value, String> + 'static,
) -> Value {
let Some(host) = app.ui_ctx.as_ref().and_then(Host::try_of_ctx) else { return Value::Null };
let ticket = host.files().pick(request);
let doc = match owner {
Owner::Document => app.session.active().map(|d| d.uid),
Owner::Free => None,
};
let (scope, automated) = (ScopeHandle::capture(), app.automation_asked());
app.file_asks.waiting.push(Waiting { ticket, owner, doc, scope, automated, then: Box::new(then) });
json!({ "pending": "fileDialog" })
}
/// Ask whether to replace the file `path`, which the save dialog did not ask about (it answered
/// `answered`); `then` runs when the user proceeds. Returns `{pending: "replaceFile"}`.
pub(crate) fn ask_replace(
app: &mut VectorcraftApp,
path: &str,
answered: &str,
then: impl FnOnce(&mut VectorcraftApp) -> Result<Value, String> + 'static,
) -> Value {
let Some(dialogs) = app.dialogs() else { return Value::Null };
let name = |p: &str| std::path::Path::new(p).file_name().map_or_else(|| p.to_string(), |n| n.to_string_lossy().into_owned());
app.file_asks.next_question += 1;
let prompt = StandardPrompt::replace_file(name(path), Some(name(answered))).instance(("vectorcraft.replaceFile", app.file_asks.next_question));
let dialog = dialogs.with(|host| host.open(prompt));
app.file_asks.replacing.push(Replacing { dialog, then: Box::new(then) });
json!({ "pending": "replaceFile" })
}
/// A parameter dialog's Browse button: show `pick` for `request` and give the dialog the path with
/// `then` ([`answer_path`] for a plain answer). A cancelled or unavailable dialog ends the request;
/// nothing happens once the dialog has closed.
pub(crate) fn browse(
app: &mut VectorcraftApp,
dialog: DialogId,
request: PathRequest,
pick: PickRequest,
then: impl FnOnce(&mut VectorcraftApp, DialogId, String, PathBuf) + 'static,
) -> Value {
let key = request.key;
ask(app, pick, Owner::Free, move |app, picked| {
let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) };
if dialogs.with(|host| host.get_by_id::<HostedParamDialog>(dialog).is_none()) {
return Ok(Value::Null);
}
let path = match &picked {
Picked::Paths(_) | Picked::Saved { .. } => picked.first_path(),
_ => None,
};
match path {
Some(path) => then(app, dialog, key, path),
None => dialogs.with(|host| {
if let Some(d) = host.get_mut_by_id::<HostedParamDialog>(dialog) {
d.cancel_requests();
}
}),
}
Ok(Value::Null)
})
}
/// Give the open dialog `dialog` the path picked for its row `key`.
pub(crate) fn answer_path(app: &mut VectorcraftApp, dialog: DialogId, key: String, path: PathBuf) {
let Some(dialogs) = app.dialogs() else { return };
dialogs.with(|host| {
if let Some(d) = host.get_mut_by_id::<HostedParamDialog>(dialog) {
d.answer_path(key, path);
}
});
}
/// The first file of an Open answer as the params of an open command: `path`, or the bytes with the
/// `name` the browser gave. `None` for any other answer.
pub(crate) fn open_params(picked: &Picked) -> Option<Map<String, Value>> {
let mut params = Map::new();
match picked {
Picked::Paths(paths) => {
params.insert("path".into(), json!(paths.first()?.to_string_lossy()));
}
Picked::Contents(files) => {
let (name, bytes) = files.first()?;
params.insert("name".into(), json!(name));
params.insert("dataBase64".into(), json!(vectorcraft_svg::base64_encode(bytes)));
}
_ => return None,
}
Some(params)
}
/// Make the document asked for (`doc`, by uid) active before its continuation runs: another may be
/// active by now, or it may be gone → false when it can't run (the status bar says why).
fn on_document(app: &mut VectorcraftApp, doc: Option<u64>) -> bool {
let Some(uid) = doc else { return true };
let Some(i) = app.session.documents().iter().position(|d| d.uid == uid) else {
app.status(closed());
return false;
};
if app.session.active_index() != Some(i)
&& let Err(e) = app.run("document.activate", json!({ "index": i }))
{
app.status(e);
return false;
}
true
}
/// An `Err` other than "cancelled" from a continuation goes to the status line.
fn report(app: &mut VectorcraftApp, result: Result<Value, String>) {
if let Err(e) = result
&& e != "cancelled"
{
app.status(e);
}
}
/// Once per frame, before the save flow's pump: run the continuations of the answered picks.
pub(crate) fn poll(app: &mut VectorcraftApp) {
app.file_asks.automated = false;
let Some(ctx) = app.ui_ctx.clone() else { return };
let Some(host) = Host::try_of_ctx(&ctx) else { return };
let mut answered = Vec::new();
// Taken first: a continuation may ask again.
for w in std::mem::take(&mut app.file_asks.waiting) {
match host.files().take_answer(w.ticket) {
Some(picked) => answered.push((w, picked)),
None => app.file_asks.waiting.push(w),
}
}
for (w, picked) in answered {
match &picked {
Picked::Cancelled => continue,
Picked::Unavailable(why) => {
app.status(Env::of_root(&ctx).words::<UnavailableWords>().sentence(why));
continue;
}
_ => {}
}
if w.owner == Owner::Document && !on_document(app, w.doc) {
continue;
}
let Waiting { scope, automated, then, .. } = w;
let result = scope.run(|| as_automated(app, automated, |app| then(app, picked)));
report(app, result);
}
}
/// Once per frame on the dialog host: run what the answered replace questions allow, and the
/// replace-files question's command.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let mut proceed = Vec::new();
let mut open = Vec::new();
let previous = std::mem::take(&mut app.file_asks.replacing);
let files = dialogs.with(|host| {
for r in previous {
match host.take_by_id::<StandardPrompt>(r.dialog) {
Some(DialogResult::Ok(answer)) if answer.choice == PromptChoice::Proceed => proceed.push(r.then),
Some(_) => {}
None if host.get_by_id::<StandardPrompt>(r.dialog).is_some() => open.push(r),
// Neither open nor holding a result: closed from outside.
None => {}
}
}
host.take::<ReplaceFilesPrompt>()
});
app.file_asks.replacing.extend(open);
for then in proceed {
let result = then(app);
report(app, result);
}
// PLAN: assumed `ReplaceFiles { doc: u64, files: Vec<String>, allowed: Vec<String>, command: String, params: Value }` (widgets-w10).
if let Some(DialogResult::Ok(mut answer)) = files
&& answer.choice == PromptChoice::Proceed
&& let Some(r) = answer.take_tag::<ReplaceFiles>()
&& on_document(app, Some(r.doc))
{
let all: Vec<String> = r.files.iter().chain(&r.allowed).cloned().collect();
crate::io::save::allow_replacing(app, &all);
let result = app.run(&r.command, r.params);
report(app, result);
}
}
-565
View File
@@ -1,565 +0,0 @@
//! File dialogs that leave the window running (#592, #867).
//!
//! The app asks for a path where it needs one (Open, Save As, Export, Place, Relink, presets…)
//! and goes on with it at once, so a dialog shown on the UI thread holds the window until it
//! closes. On Windows the dialog runs the window's events meanwhile. On Linux nothing does, so a
//! Wayland compositor finds the window not answering and offers to kill it (#592); on macOS the
//! panel's modal loop runs inside winit's event handler, and an event winit had held back meanwhile
//! re-enters it and aborts the app (#867). There the host shows dialogs off the UI thread (Linux)
//! or as sheets (macOS) ([`Services::start_pick`]): asking returns no path for now, and when the
//! dialog answers, what asked (the command, the dialog's OK, a panel's button: the *entry*) runs
//! again, on the document it asked for, and gets the picked path at once. Everything that asks
//! must run as an entry ([`as_entry`]): outside one the dialog is shown in line, which macOS
//! refuses.
//!
//! While a dialog is open ([`VectorcraftApp::file_dialog_open`]) another is refused; on macOS,
//! where it is a sheet on the window, the menu bar does nothing and the app neither quits nor
//! closes documents, as under the modal dialog before.
use std::rc::Rc;
use std::sync::mpsc::{Receiver, TryRecvError};
use serde_json::Value;
use vectorcraft_engine::file_access::ScopeHandle;
use crate::state::Dialog;
use crate::{FilePick, VectorcraftApp};
/// A file dialog to show.
#[derive(Clone, Debug, PartialEq)]
pub enum PickRequest {
/// An open dialog for one file.
Open(FilePick),
/// An open dialog for files to place.
OpenMany,
/// An open dialog for several files of the pick's types.
OpenFiles(FilePick),
/// A save dialog.
Save(FilePick),
/// A folder picker.
Folder,
/// A folder picker that starts in the folder given.
FolderAt(String),
}
/// The paths a dialog shown off the UI thread picked (none: cancelled). A save dialog that reports
/// which of its file types was picked (the XDG portal's on Linux and the BSDs) answers that type's
/// first extension after the path.
pub type PickAnswer = Vec<String>;
/// Shows a dialog off the UI thread; its answer arrives on the receiver. `None` when it can't, and
/// the dialog is then shown in line.
pub type StartPick = Box<dyn FnMut(PickRequest) -> Option<Receiver<PickAnswer>>>;
/// A button's action that runs again with the picked path.
type Call = Rc<dyn Fn(&mut VectorcraftApp)>;
/// What runs again with the picked path.
#[derive(Clone)]
pub(crate) enum Entry {
/// A command (`app.run`).
Command(String, Value),
/// A dialog's OK (`dialogs::confirm`), on the dialog as it was.
Confirm(Box<Dialog>),
/// A panel's or a dialog's button.
Call(Rc<dyn Fn(&mut VectorcraftApp)>),
/// A dialog's button that acts on no document (an app preference): its answer goes on even
/// when the document active at the time has closed meanwhile.
AppCall(Rc<dyn Fn(&mut VectorcraftApp)>),
}
/// Commands that ask for a file but act on no document: their answer goes on even when the
/// document active at the time has closed meanwhile.
const DOCUMENT_FREE: &[&str] = &[
"file.open",
"file.openWith",
"file.newFromTemplate",
"ui.installPlugin",
"ui.checkScript",
"ui.runScript",
"window.swatchLibrary.other",
"window.graphicStyleLibrary.other",
"ui.libraryPanel.locate",
"shortcuts.import",
"shortcuts.export",
"shortcuts.exportText",
"ui.shortcutImportDialog",
crate::panels::actions::SAVE_SET,
crate::panels::actions::LOAD_SET,
crate::panels::actions::REPLACE_SET,
];
impl Entry {
/// The document it acts on when it runs again: the active one, unless it acts on none.
fn document(&self, app: &VectorcraftApp) -> Option<u64> {
match self {
Entry::Command(id, _) if DOCUMENT_FREE.contains(&id.as_str()) => None,
Entry::AppCall(_) => None,
_ => app.session.active().map(|d| d.uid),
}
}
}
/// A dialog shown off the UI thread, waiting for its answer.
struct Waiting {
request: PickRequest,
answer: Receiver<PickAnswer>,
entry: Entry,
/// The active document when it was asked for ([`vectorcraft_engine::DocState::uid`]).
doc: Option<u64>,
/// The automation roots in force when it was asked for: the entry runs again under them, not
/// with the desktop's access of the frame the answer comes in.
scope: ScopeHandle,
/// Automation asked for it ([`VectorcraftApp::automation_asked`]): the entry runs again as
/// automation's ([`as_automated`]).
automated: bool,
}
/// The app's file dialogs ([`VectorcraftApp`]'s `picks`).
#[derive(Default)]
pub(crate) struct Picks {
/// What is running now and asks for a path, the outermost one.
entry: Option<Entry>,
waiting: Option<Waiting>,
/// A picked answer for the entry running again: the dialog it asks for gets it.
answer: Option<(PickRequest, PickAnswer)>,
/// Another dialog was refused while this one is open ([`busy`]).
refused: bool,
/// A save dialog's answer waiting for the question whether to replace the file it names
/// ([`ask_to_replace`]).
replacing: Option<Replacing>,
/// The file that question's OK allows to be replaced while what asked runs again.
replace_ok: Option<String>,
/// The files that the OK of the question whether to replace the files a save or export writes
/// beside the one picked allows to be replaced while it runs that again
/// ([`crate::dialogs::confirm::ask_replace_files`]).
pub(crate) replace_files_ok: Vec<String>,
/// The files each document's last save wrote beside its own file, by document uid: its next
/// save replaces them without asking.
pub(crate) written_beside: std::collections::HashMap<u64, Vec<String>>,
/// What runs now handles the answer of a file dialog automation opened ([`as_automated`]).
automated: bool,
/// The web's file pickers opened ([`open_async`]) that have not answered yet
/// (`Services::picked_inbox`).
web_opens: u32,
/// Automation opened one of them: their answers are automation's.
web_open_automated: bool,
}
/// A save dialog's answer that names, once the app gave it an extension, a file that is there.
struct Replacing {
request: PickRequest,
answer: PickAnswer,
/// The file it names.
path: String,
entry: Entry,
/// The active document when it was asked for ([`vectorcraft_engine::DocState::uid`]).
doc: Option<u64>,
}
impl Picks {
/// Nothing asking for file dialogs is running.
pub(crate) fn is_entry_free(&self) -> bool {
self.entry.is_none()
}
/// A dialog shown off the UI thread is open.
pub(crate) fn is_waiting(&self) -> bool {
self.waiting.is_some()
}
/// After a panic the guard caught (a bug): no entry is running any more, and an answer kept for
/// one is stale. The open dialog's answer still arrives.
pub(crate) fn recover(&mut self) {
self.entry = None;
self.answer = None;
self.replace_ok = None;
self.replace_files_ok.clear();
self.automated = false;
}
/// What runs now handles the answer of a file dialog automation opened ([`as_automated`]).
pub(crate) fn automated(&self) -> bool {
self.automated
}
/// One of the web's file pickers answered (a file, or canceled): whether the answer is
/// automation's. Once none is waiting, the next one the person opens answers for the person.
pub(crate) fn answer_web_open(&mut self) -> bool {
let automated = self.web_open_automated;
self.web_opens = self.web_opens.saturating_sub(1);
if self.web_opens == 0 {
self.web_open_automated = false;
}
automated
}
/// The kind of dialog open off the UI thread (`ui.inspect`'s `fileDialog`).
pub(crate) fn waiting_kind(&self) -> Option<&'static str> {
self.waiting.as_ref().map(|w| match w.request {
PickRequest::Open(_) | PickRequest::OpenFiles(_) => "open",
PickRequest::OpenMany => "place",
PickRequest::Save(_) => "save",
PickRequest::Folder | PickRequest::FolderAt(_) => "folder",
})
}
}
/// What the status bar says when a dialog is asked for while another is open.
pub(crate) fn busy() -> &'static str {
tl!("A file dialog is open: choose there first")
}
/// What the status bar says when the dialog whose button asked closed before the file dialog
/// answered.
pub(crate) fn dialog_gone() -> &'static str {
tl!("The dialog was closed before its file dialog answered")
}
/// Run `f` as `entry`: a dialog it asks for off the UI thread runs `entry` again when it
/// answers. Inside another entry, that one runs again instead.
pub(crate) fn as_entry<R>(app: &mut VectorcraftApp, entry: impl FnOnce() -> Entry, f: impl FnOnce(&mut VectorcraftApp) -> R) -> R {
if app.picks.entry.is_some() {
return f(app);
}
app.picks.entry = Some(entry());
let r = f(app);
app.picks.entry = None;
r
}
/// Run a continuation under its own entry: a refused Save's panel must resume Save As, not retry
/// the original Save. Restore the enclosing entry for any work it does afterwards.
pub(crate) fn as_own_entry<R>(app: &mut VectorcraftApp, entry: Entry, f: impl FnOnce(&mut VectorcraftApp) -> R) -> R {
let outer = app.picks.entry.replace(entry);
let r = f(app);
app.picks.entry = outer;
r
}
/// Run `f` as handling the answer of a file dialog automation opened when `automated` (and inside
/// one already, as that): [`VectorcraftApp::automation_asked`] is true meanwhile.
pub(crate) fn as_automated<R>(app: &mut VectorcraftApp, automated: bool, f: impl FnOnce(&mut VectorcraftApp) -> R) -> R {
let outer = app.picks.automated;
app.picks.automated = outer || automated;
let r = f(app);
app.picks.automated = outer;
r
}
/// Opens the web's file picker, whose file arrives later through `Services::picked_inbox`, noting
/// whether automation asked for it ([`VectorcraftApp::automation_asked`]) → false when the host has
/// none. While a picker automation opened has not answered, every answer is automation's, also one
/// to a picker the person opened.
pub(crate) fn open_async(app: &mut VectorcraftApp) -> bool {
let automated = app.automation_asked();
let Some(f) = app.services.open_async.as_mut() else { return false };
f();
app.picks.web_opens += 1;
app.picks.web_open_automated |= automated;
true
}
/// [`as_entry`] for a panel's or a dialog's button that `f` handles.
pub(crate) fn button(app: &mut VectorcraftApp, f: impl Fn(&mut VectorcraftApp) + 'static) {
let f = Rc::new(f);
let again = f.clone();
as_entry(app, move || Entry::Call(again), |app| f(app));
}
/// A dialog body's action `f` on `d` (the open dialog's copy) that asks for a file dialog: shown
/// off the UI thread, its answer runs `f` again on the open dialog, when it is still of that kind.
/// A question whether to replace a file that `f` asks ([`ask_to_replace`]) takes `d`'s place, with
/// `d` under it.
pub(crate) fn in_dialog(
app: &mut VectorcraftApp,
d: &mut Dialog,
f: impl Fn(&mut VectorcraftApp, &mut Dialog) -> Result<(), String> + 'static,
) -> Result<(), String> {
dialog_entry(app, d, Entry::Call, f)
}
/// [`in_dialog`] for an action that acts on no document (an app preference): its answer runs `f`
/// again on the open dialog even when the document active at the time has closed meanwhile.
pub(crate) fn in_app_dialog(
app: &mut VectorcraftApp,
d: &mut Dialog,
f: impl Fn(&mut VectorcraftApp, &mut Dialog) -> Result<(), String> + 'static,
) -> Result<(), String> {
dialog_entry(app, d, Entry::AppCall, f)
}
/// [`in_dialog`] with `wrap` making the entry (a [`Entry::Call`] or an [`Entry::AppCall`]).
fn dialog_entry(
app: &mut VectorcraftApp,
d: &mut Dialog,
wrap: fn(Call) -> Entry,
f: impl Fn(&mut VectorcraftApp, &mut Dialog) -> Result<(), String> + 'static,
) -> Result<(), String> {
let f = Rc::new(move |app: &mut VectorcraftApp, d: &mut Dialog| {
let r = f(app, d);
if let Some(mut question) = app.ui.dialog.take_if(|q| q.kind == crate::dialogs::confirm::REPLACE) {
question.fields.insert(crate::dialogs::PARENT.into(), serde_json::to_value(&*d).unwrap_or_default());
*d = question;
}
r
});
let (again, kind) = (f.clone(), d.kind.clone());
let entry = move || {
wrap(Rc::new(move |app: &mut VectorcraftApp| {
let Some(mut d) = app.ui.dialog.take_if(|d| d.kind == kind) else {
app.status(dialog_gone());
return;
};
let r = again(app, &mut d);
app.ui.dialog = Some(d);
if let Err(e) = r {
app.status(e);
}
}))
};
as_entry(app, entry, |app| f(app, d))
}
/// A dialog body's folder button: the folder picked into field `key` of `d` ([`in_dialog`]).
pub(crate) fn folder_field(app: &mut VectorcraftApp, d: &mut Dialog, key: &'static str) {
let r = in_dialog(app, d, move |app, d| {
if let Some(f) = folder(app) {
d.fields.insert(key.into(), serde_json::json!(f));
}
Ok(())
});
// Picking a folder doesn't fail.
let _ = r;
}
/// A path from an open dialog for `pick` (none: cancelled, or shown off the UI thread for now).
pub(crate) fn open(app: &mut VectorcraftApp, pick: &FilePick) -> Option<String> {
ask(app, PickRequest::Open(pick.clone()))?.into_iter().next()
}
/// A path from a save dialog for `pick`.
pub(crate) fn save(app: &mut VectorcraftApp, pick: &FilePick) -> Option<String> {
ask(app, PickRequest::Save(pick.clone()))?.into_iter().next()
}
/// A path from a save dialog for `pick`, and the extension of the file type picked in it when the
/// dialog reports one ([`PickAnswer`]).
pub(crate) fn save_with_type(app: &mut VectorcraftApp, pick: &FilePick) -> Option<(String, Option<String>)> {
let mut answer = ask(app, PickRequest::Save(pick.clone()))?.into_iter();
Some((answer.next()?, answer.next()))
}
/// A folder from the folder picker.
pub(crate) fn folder(app: &mut VectorcraftApp) -> Option<String> {
ask(app, PickRequest::Folder)?.into_iter().next()
}
/// A folder from the folder picker, which starts in `start` when the host can start it there.
pub(crate) fn folder_at(app: &mut VectorcraftApp, start: &str) -> Option<String> {
ask(app, PickRequest::FolderAt(start.to_string()))?.into_iter().next()
}
/// Paths from the open dialog for files to place (none: cancelled).
pub(crate) fn open_many(app: &mut VectorcraftApp) -> Vec<String> {
ask(app, PickRequest::OpenMany).unwrap_or_default()
}
/// Paths from an open dialog for several files of `pick`'s types (none: cancelled, or shown off the
/// UI thread for now).
pub(crate) fn open_files(app: &mut VectorcraftApp, pick: &FilePick) -> Vec<String> {
ask(app, PickRequest::OpenFiles(pick.clone())).unwrap_or_default()
}
/// Whether the host shows `request`'s kind of dialog at all.
pub(crate) fn can(app: &VectorcraftApp, request: &PickRequest) -> bool {
let s = &app.services;
match request {
PickRequest::Open(_) => s.pick_open.is_some(),
PickRequest::OpenMany => s.pick_open_multi.is_some() || s.pick_open.is_some(),
PickRequest::OpenFiles(_) => s.pick_open_files.is_some() || s.pick_open.is_some(),
PickRequest::Save(_) => s.pick_save.is_some(),
PickRequest::Folder => s.pick_folder.is_some(),
PickRequest::FolderAt(_) => s.pick_folder_at.is_some() || s.pick_folder.is_some(),
}
}
/// The paths `request`'s dialog picked: the answer kept for it, else shown off the UI thread (no
/// paths for now), else shown in line.
fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option<PickAnswer> {
// One for another dialog is dropped: the entry took another way this time.
if let Some((asked, answer)) = app.picks.answer.take()
&& asked == request
{
return Some(answer);
}
if !can(app, &request) {
return None;
}
if app.services.start_pick.is_some() && app.picks.waiting.is_some() {
app.status(busy());
app.picks.refused = true;
return None;
}
match (app.picks.entry.clone(), app.services.start_pick.as_mut()) {
(Some(entry), Some(start)) => {
if let Some(answer) = start(request.clone()) {
let (doc, automated) = (entry.document(app), app.automation_asked());
app.picks.waiting = Some(Waiting { request, answer, entry, doc, scope: ScopeHandle::capture(), automated });
return None;
}
}
// Shown in line it holds the window (Linux) or is refused (macOS): what asks must run as
// an entry.
(None, Some(_)) => log::warn!("a file dialog asked for outside a command, a dialog's OK or a button: {request:?}"),
_ => {}
}
let s = &mut app.services;
let one = |p: Option<String>| Some(p.into_iter().collect());
match &request {
PickRequest::Open(pick) => one(s.pick_open.as_mut().and_then(|f| f(pick))),
PickRequest::Save(pick) => one(s.pick_save.as_mut().and_then(|f| f(pick))),
PickRequest::Folder => one(s.pick_folder.as_mut().and_then(|f| f())),
PickRequest::FolderAt(start) => match (s.pick_folder_at.as_mut(), s.pick_folder.as_mut()) {
(Some(at), _) => one(at(start)),
(None, Some(f)) => one(f()),
(None, None) => None,
},
PickRequest::OpenMany => match (s.pick_open_multi.as_mut(), s.pick_open.as_mut()) {
(Some(many), _) => Some(many()),
(None, Some(f)) => one(f(&FilePick::default())),
(None, None) => None,
},
PickRequest::OpenFiles(pick) => match (s.pick_open_files.as_mut(), s.pick_open.as_mut()) {
(Some(many), _) => Some(many(pick)),
(None, Some(f)) => one(f(pick)),
(None, None) => None,
},
}
}
/// Each frame: when the dialog shown off the UI thread answers with paths, run its entry again
/// with them. While it is open, look again shortly.
pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) {
// Clear the "cancelled" that a save leaves in the status bar when it stops to ask whether to
// replace a file ([`ask_to_replace`]).
if app.ui.status == "cancelled" && app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::confirm::REPLACE) {
app.ui.status.clear();
}
let Some(w) = &app.picks.waiting else { return };
let answer = match w.answer.try_recv() {
Ok(answer) => answer,
Err(TryRecvError::Empty) => {
// What asked gave up for now: no "cancelled" while the dialog is open, unless it was
// another dialog, refused.
if app.ui.status == "cancelled" {
app.ui.status = if std::mem::take(&mut app.picks.refused) { busy().into() } else { String::new() };
}
// The host wakes the window when the dialog answers; this is in case it can't.
ctx.request_repaint_after(std::time::Duration::from_secs(1));
return;
}
// The dialog's thread is gone: as cancelled.
Err(TryRecvError::Disconnected) => vec![],
};
let Some(Waiting { request, entry, doc, scope, automated, .. }) = app.picks.waiting.take() else { return };
app.picks.refused = false;
// Once more: what waited for the dialog (files from the Finder, the menu bar) goes on.
ctx.request_repaint();
if answer.is_empty() {
return;
}
scope.run(|| {
if !on_document(app, doc) {
return;
}
app.picks.answer = Some((request, answer));
as_automated(app, automated, |app| rerun(app, entry));
// An entry that took another way this time leaves the answer unused.
app.picks.answer = None;
});
}
/// Make the document an entry asked for (`doc`, by its uid) active again before it runs again:
/// another may be active by now (opened from the Finder, by an agent), or it may be gone → false
/// when it can't run (the status bar says why).
pub(crate) fn on_document(app: &mut VectorcraftApp, doc: Option<u64>) -> bool {
let Some(uid) = doc else { return true };
let Some(i) = app.session.documents().iter().position(|d| d.uid == uid) else {
app.status(tl!("The document was closed while its file dialog was open"));
return false;
};
if app.session.active_index() != Some(i)
&& let Err(e) = app.run("document.activate", serde_json::json!({ "index": i }))
{
app.status(e);
return false;
}
true
}
/// `picked`, a save dialog's answer to `request` (with `file_type`, the extension of the file type
/// picked in it when the dialog reports one), names `path`, another file, once the app gave it
/// an extension: the dialog checked only `picked` for an existing file, not `path`. When a file is
/// at `path`, ask before replacing it, over the dialog open now → true while the question is open
/// (nothing is written meanwhile). OK runs what asked again with the same answer, and `path` is
/// written then ([`replace`]); Cancel writes nothing. Nothing is asked while that OK runs what
/// asked, or outside an entry, which nothing could run again.
pub(crate) fn ask_to_replace(app: &mut VectorcraftApp, request: PickRequest, picked: &str, file_type: Option<&str>, path: &str) -> bool {
if app.picks.replace_ok.as_deref() == Some(path) || !app.services.exists.as_ref().is_some_and(|exists| exists(path)) {
return false;
}
let Some(entry) = app.picks.entry.clone() else { return false };
let doc = entry.document(app);
let answer = std::iter::once(picked).chain(file_type).map(str::to_string).collect();
app.picks.replacing = Some(Replacing { request, answer, path: path.to_string(), entry, doc });
crate::dialogs::confirm::ask_replace(app, path, picked);
true
}
/// The OK of the question whether to replace the file at `path` ([`ask_to_replace`]): the dialog
/// it was asked over shows again, and what asked runs again with the same answer, on the document
/// it asked for, replacing the file.
pub(crate) fn replace(app: &mut VectorcraftApp, path: &str) -> Result<Value, String> {
app.ui.dialog = app.ui.dialog.take().and_then(|d| crate::dialogs::parent(&d));
let Some(Replacing { request, answer, path, entry, doc }) = app.picks.replacing.take().filter(|r| r.path == path) else {
return Ok(Value::Null);
};
if !on_document(app, doc) {
return Ok(Value::Null);
}
app.picks.answer = Some((request, answer));
app.picks.replace_ok = Some(path);
// A dialog it asks for next runs what asked again, not this question.
let outer = app.picks.entry.replace(entry.clone());
rerun(app, entry);
app.picks.entry = outer;
app.picks.answer = None;
app.picks.replace_ok = None;
Ok(Value::Null)
}
/// Run `entry` again.
fn rerun(app: &mut VectorcraftApp, entry: Entry) {
let r = match entry {
Entry::Command(id, params) => app.run(&id, params).map(|_| ()),
Entry::Confirm(d) => {
app.ui.dialog = Some(*d);
crate::dialogs::confirm(app).map(|_| ())
}
// An entry again, so a dialog it asks for next is shown off the UI thread too.
Entry::Call(f) => {
let again = f.clone();
as_entry(app, move || Entry::Call(again), |app| f(app));
Ok(())
}
Entry::AppCall(f) => {
let again = f.clone();
as_entry(app, move || Entry::AppCall(again), |app| f(app));
Ok(())
}
};
if let Err(e) = r {
app.status(e);
}
}