Skip to main content

egui_pop_api/
dialogs.rs

1//! Dialogs, as a plugin ([`DialogsPlugin`], in `DefaultPlugins`): a
2//! question before an action ([`Confirm`]), a form of typed fields
3//! ([`Form`], from value descriptors), a choice among options, each
4//! answering a value of its own, with a filter field ([`Choose`]), a
5//! notice to acknowledge ([`Info`]), and a dialog with a body of its own
6//! ([`Custom`], opened with [`Dialogs::open_custom`]). They queue, one
7//! shown at a time, modal, drawn from the theme's tokens.
8//!
9//! A dialog belongs to the window it was opened from (ADR 0025): the
10//! application window being drawn, or the one whose command opened it
11//! (its `appWindow`), else the active one. Each application window has
12//! its own queue, one dialog shown at a time in each, and a dialog blocks
13//! its own window only: the main window and an application window each
14//! answer their own. In the main window's group, a dialog comes up over
15//! the window of it the user worked in last
16//! ([`AppHandle::active_window`]): a detached panel's window when the
17//! dialog was opened from there, the main window otherwise, or once that
18//! window is closed; it blocks the main window and its detached panels
19//! (their keys dropped, a backdrop over them; a click there brings the
20//! dialog's window to the front). A dialog whose application window
21//! closes is cancelled with it, as a file choice asked from there is; one
22//! whose window moves into the main window (the main window closed while
23//! it was open) goes to the main window's queue.
24//!
25//! A dialog is a popup on the bus (ADR 0029): coming up, it asks its
26//! `pop.popup.open` (`dialog:<id>`, owned by the plugin that opened it or by
27//! this one, its parent the window of its group); answered, cancelled, or
28//! its plugin gone, its `pop.popup.close`. Its window closing asks that
29//! `pop.popup.close` (`parent-closed`), and this plugin's listener on it
30//! ([`POPUP_LISTENER`]) cancels the dialog in that call; the dialogs still
31//! waiting in that window's queue are cancelled by [`CANCEL_ON_CLOSE`], a
32//! listener of `pop.window.close`. The dialogs' block is in the `WINDOW_OVERLAYS` zone, drawn in
33//! every window.
34//!
35//! [`Dialogs::current`], [`Dialogs::answer`] and the `dialogs` collector
36//! address the dialog shown in the current window group (the one being
37//! drawn, or commanded, or an agent's call names), else the first one
38//! queued.
39//!
40//! A custom dialog is a host of the mount contract (ADR 0013): its body
41//! is drawn by a closure kept on the application's side (the queue
42//! stays `Clone` and `Send`), in a size of the dialog's own, in a
43//! `dialog` focus scope and a fault boundary, every frame (the body's
44//! components keep draining their workers' queues). It keeps every
45//! dialog rule: the primary button says what it does, Enter accepts and
46//! Escape cancels, steps, the debug bridge, movable, closable, the
47//! backdrop. Keys the body claims ([`Custom::claims`], from its
48//! component's `Mountable`) go to it first: when it claims Enter,
49//! Ctrl+Enter accepts; when it claims Escape, Escape goes to the body
50//! while it has something to cancel ([`CustomPass::claim_escape`], a
51//! drag), and cancels the dialog otherwise. Its values
52//! ([`CustomPass::value`]) are merged into the command's arguments; the
53//! `dialogs` collector shows its description ([`CustomPass::describe`])
54//! and answers it as a form.
55//!
56//! Rules: the primary button says what it does ("Delete 3 images", never
57//! "OK"); a dangerous one is styled as such and the focus starts on
58//! Cancel; Enter accepts (except a danger), Escape cancels. Accepting
59//! runs the dialog's command (through the host) with its arguments, the
60//! form's values and the choice merged in.
61//!
62//! No header band and no close button by default: Cancel and Escape are
63//! the way out. A dialog opened as [`DialogSpec::closable()`] (or every
64//! dialog, with the `dialogs.closable` setting) has a ✕ at the right end
65//! of its title row, named "Close", which is Escape: the same cancel,
66//! through the same step and hooks, refused when Escape is.
67//!
68//! A notice and a confirmation have a Copy button in their bottom left
69//! corner (left out with `.copyable(false)`): it puts their title and
70//! text on the clipboard, then their [`Details`], key-value lines for a
71//! bug report, under a separator. The details stay off screen, or show
72//! in a collapsed "Details" section ([`DetailsMode`]; shown by default
73//! on an error, [`Info::error`]).
74//!
75//! A dialog opened as [`DialogSpec::movable()`] (or every dialog, with
76//! the `dialogs.movable` setting) has a header band instead of its title
77//! row: its own tone, a separator, the move cursor, the ✕ when it is
78//! closable. Dragging the band moves the dialog, kept inside the window
79//! (again when the window is resized); a double click on it centres it
80//! again; the `dialogs.move` command (Alt+F7) moves it with the arrow
81//! keys (Shift for bigger steps), Enter keeping the place and Escape
82//! putting it back. A dialog comes up centred, or where it was left when
83//! opened with [`DialogSpec::remember_position()`] (kept per key in the
84//! host's store, under `ui/dialogs/<key>`).
85//!
86//! Its backdrop ([`Backdrop`]) dims the interface (`Dim`, the
87//! `backdrop.opacity` token's strength, fading while the dialog is
88//! dragged) or leaves it untouched (`Clear`, for a dialog previewing its
89//! effect on the image); the dialog stays modal either way, and a click
90//! on the backdrop never closes it.
91//!
92//! A form's path field (a descriptor made with `Descriptor::path`) has a
93//! Browse button: the file chooser ([`crate::files`]: the system's, or
94//! the in-app picker), its result written into the field when it comes;
95//! without the files plugin, the in-app picker inside the dialog.
96//!
97//! Every open dialog is data: the debug bridge's `dialogs` collector
98//! shows the current one (a form's values also as a plain `values` map)
99//! and answers it (`answer`, the user's unless the application offers it
100//! to agents) as its caller, so an agent sees and answers what a person
101//! would, with its origin recorded. Accepting a dialog runs its command
102//! with the answer's origin; an answer that would run a command not
103//! offered to agents (`CommandSpec::no_agent`) is refused to anyone but
104//! the user, whoever gives it (`dialog.answer.refused` on the journal),
105//! and the dialog stays open.
106//!
107//! Steps (ADR 0011): `dialog.show` runs when a dialog comes up (a
108//! before-hook may veto it: it is cancelled), `dialog.answer` around each
109//! answer (a before-hook may veto it, the dialog staying open with the
110//! reason, or redirect it to another answer; a run-hook may answer its
111//! own way), `dialog.move` when a dialog is dropped, moved by a key or
112//! centred again (a before-hook may veto it, the dialog going back, or
113//! redirect it elsewhere). The journal says `dialog.answered`, then
114//! `dialog.chosen` (the option's index, label and value) or
115//! `dialog.cancelled`, `dialog.filtered` as a choice's filter changes,
116//! and `dialog.moved` once a move is done.
117//!
118//! A dialog belongs to the plugin of its command, and a custom one also to
119//! the plugin that opened it (whose command, connection or handler was
120//! running). When that plugin is disconnected, the dialog is cancelled
121//! at once (ADR 0028): `dialog.cancelled` from `egui_pop`, with the reason
122//! ("its plugin `x` is disconnected"), and the next queued one shows.
123//!
124//! ```
125//! use egui_pop_api::dialogs::{self, Confirm};
126//! use egui_pop_api::App;
127//! use egui_pop_model::ids::CommandId;
128//!
129//! let app = App::builder()
130//!     .plugin(dialogs::DialogsPlugin)
131//!     .build(&egui::Context::default())
132//!     .unwrap();
133//! let d = app.handle().service(&dialogs::DIALOGS).unwrap();
134//! d.open(Confirm::new("Delete 3 images?", "Delete 3 images", CommandId::from_static("doc.delete"))
135//!     .detail("They go to the trash.")
136//!     .danger());
137//! assert_eq!(d.describe()["kind"], "confirm");
138//! ```
139
140use std::collections::VecDeque;
141use std::path::{Path, PathBuf};
142
143use std::sync::{Arc, Mutex};
144
145use egui::{Key, Modifiers, Response, Ui, Vec2};
146use egui_pop_core::band;
147use egui_pop_core::debug::FnCollector;
148use egui_pop_core::icon::{Icon, Size as IconSize};
149use egui_pop_core::kit::{self, Kit};
150use egui_pop_core::lock;
151use egui_pop_core::overlay::{self, Kind, OverlaySpec};
152use egui_pop_core::strings::{self, CANCEL, CLOSE};
153use egui_pop_core::theme::Tokens;
154use egui_pop_core::ui::{TextRole, UiPop as _};
155use egui_pop_core::widgets;
156use egui_pop_model::commands::{CommandSpec, Origin};
157use egui_pop_model::fuzzy;
158use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PluginId, SettingId, StepId};
159use egui_pop_model::keymap::BindOptions;
160use egui_pop_model::mount::{
161    ClaimKey, Dismiss, FocusPolicy, HostOffer, HostSize, Keep, Lifetime, Mountable,
162};
163use egui_pop_model::values::{Change, Descriptor, PathHint, PathKind, Set, Type, Value};
164use serde::Serialize;
165use serde_json::{Map, Value as Json, json};
166
167use bus_contract::{ListenOpts, Point as _};
168
169use crate::app::AppHandle;
170use crate::bus::{
171    CHILDREN, FOCUS, PopupClose, REGISTRY, Reason, WindowClose, WindowKind, WindowRequest,
172};
173use crate::files::{self, FILES, FilePicker, FileRequest, PickerAnswer};
174use crate::host::Pending;
175use crate::host::source_of;
176use crate::services::ServiceToken;
177use crate::steps::{Outcome, StepSpec};
178use crate::strings as txt;
179use crate::windows::WindowId;
180use crate::zones::{self, Block};
181use crate::{Ctx, Plugin, PluginError};
182
183/// The dialogs, as a service.
184pub const DIALOGS: ServiceToken<Dialogs> = ServiceToken::new("app.dialogs");
185
186/// A dialog comes up: its arguments are its description; a veto cancels
187/// it.
188pub const STEP_SHOW: StepId = StepId::from_static("dialog.show");
189/// A dialog is answered: `{"dialog": description, "answer": answer,
190/// "origin": source}`; a veto keeps it open with the reason, a redirect
191/// changes the answer.
192pub const STEP_ANSWER: StepId = StepId::from_static("dialog.answer");
193/// The setting: every dialog has the close button, as if opened
194/// [`DialogSpec::closable()`].
195pub const SETTING_CLOSABLE: SettingId = SettingId::from_static("dialogs.closable");
196/// A dialog is moved: dropped after a drag, moved by a key, centred
197/// again. `{"id", "title", "key", "how": "drag" | "keys" | "recentre",
198/// "from": [x, y], "to": [x, y]}`, offsets from the window's centre in
199/// points; a veto puts it back where it was, a redirect places it at its
200/// own `to`.
201pub const STEP_MOVE: StepId = StepId::from_static("dialog.move");
202/// The setting: every dialog is movable, as if opened
203/// [`DialogSpec::movable()`].
204pub const SETTING_MOVABLE: SettingId = SettingId::from_static("dialogs.movable");
205/// Moves the dialog shown with the arrow keys (Alt+F7): Shift for bigger
206/// steps, Enter keeps the place, Escape puts it back.
207pub const CMD_MOVE: CommandId = CommandId::from_static("dialogs.move");
208
209/// The plugin's id, owner of the positions it keeps.
210pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.dialogs");
211
212/// The dialogs' listener on `pop.popup.close`: the dialog of that popup is
213/// cancelled, whoever asked (its window closing, among others).
214pub const POPUP_LISTENER: &str = "pop.dialogs.popup";
215/// The dialogs' listener on `pop.window.close`: the dialogs waiting in the
216/// closing window's queue (never shown, so no popup yet) are cancelled.
217pub const CANCEL_ON_CLOSE: &str = "pop.dialogs.cancel-on-close";
218/// A dialog's popup id in the registry: `dialog:<id>`.
219pub const POPUP_PREFIX: &str = "dialog:";
220/// What is left of the backdrop while a dialog is dragged.
221const DRAG_DIM: f32 = 0.35;
222/// How many arrow steps one Shift+arrow press moves.
223const BIG_STEP: f32 = 8.0;
224
225/// A question before an action: a primary button and Cancel, or, with a
226/// [`Secondary`], the classic three buttons ("Save", "Don't save",
227/// "Cancel") in the platform's order ([`ButtonOrder`]).
228///
229/// ```
230/// use egui_pop_api::dialogs::{Confirm, Secondary};
231/// use egui_pop_model::ids::CommandId;
232///
233/// let ask = Confirm::new("Quit with unsaved edits?", "Retry saving", CommandId::from_static("doc.save"))
234///     .secondary(Secondary::new("Quit without saving", CommandId::from_static("app.quit")).danger())
235///     .cancel("Keep editing");
236/// assert!(ask.secondary.as_ref().is_some_and(|s| s.danger));
237/// ```
238///
239/// Need (dialog): a confirmation dialog.
240/// Need (dialog): ask before a destructive action.
241/// Need (dialog): a three-button question (Save, Don't save, Cancel).
242#[derive(Clone, Debug, PartialEq, Serialize)]
243pub struct Confirm {
244    pub title: String,
245    /// The consequences, in one line.
246    pub detail: String,
247    /// The primary button: what it does.
248    pub verb: String,
249    /// Destructive: the danger style, the focus starts on Cancel, Enter
250    /// does not accept.
251    pub danger: bool,
252    pub command: CommandId,
253    pub args: Json,
254    /// The Copy button in its bottom corner (on by default).
255    pub copy: bool,
256    /// Technical lines for a bug report (none by default).
257    #[serde(skip_serializing_if = "Details::is_empty")]
258    pub details: Details,
259    /// A second action beside the primary one (none by default):
260    /// answered as the choice of index 1 (`{"answer": "choose", "index":
261    /// 1}`), the primary one being index 0 or an accept.
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub secondary: Option<Secondary>,
264    /// The Cancel button's text: "Cancel", translated, when empty.
265    #[serde(skip_serializing_if = "String::is_empty")]
266    pub cancel: String,
267    /// The buttons' order: the context's ([`ButtonOrder::of`], the
268    /// platform's unless pinned) unless given.
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub order: Option<ButtonOrder>,
271}
272
273/// A confirmation's second action ([`Confirm::secondary`]): often the
274/// destructive one ("Don't save", "Quit without saving"), in the danger
275/// tone, which is never the default: Enter takes the primary button.
276#[derive(Clone, Debug, PartialEq, Serialize)]
277pub struct Secondary {
278    /// Its button: what it does.
279    pub verb: String,
280    pub command: CommandId,
281    pub args: Json,
282    /// Destructive: the danger tone.
283    pub danger: bool,
284}
285
286impl Secondary {
287    pub fn new(verb: &str, command: CommandId) -> Self {
288        Self {
289            verb: verb.into(),
290            command,
291            args: Json::Null,
292            danger: false,
293        }
294    }
295
296    /// Destructive: drawn in the danger tone.
297    pub fn danger(mut self) -> Self {
298        self.danger = true;
299        self
300    }
301
302    pub fn args(mut self, args: Json) -> Self {
303        self.args = args;
304        self
305    }
306}
307
308/// Where [`ButtonOrder::pin`] keeps a context's order.
309const PINNED_ORDER: &str = "egui_pop.dialogs.button_order";
310
311/// The order of a dialog's buttons along its footer, as the platform
312/// has it.
313#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
314#[serde(rename_all = "kebab-case")]
315pub enum ButtonOrder {
316    /// The primary button at the end, Cancel before it, a secondary
317    /// action apart at the start: "Don't save … Cancel Save" (macOS,
318    /// GNOME).
319    PrimaryLast,
320    /// The primary button first, then the secondary, then Cancel: "Save
321    /// Don't save Cancel" (Windows, KDE Plasma).
322    PrimaryFirst,
323}
324
325impl ButtonOrder {
326    /// The order of this platform: Windows' and Plasma's
327    /// ([`ButtonOrder::PrimaryFirst`]), else macOS's and GNOME's.
328    pub fn platform() -> Self {
329        let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
330        Self::for_platform(cfg!(windows), &desktop)
331    }
332
333    /// Gives every dialog drawn in `ctx` this order, unless its own says
334    /// ([`Confirm::order`]), in place of [`ButtonOrder::platform`]: a
335    /// test's, so that its pictures and its keyboard walks are the same
336    /// on every platform.
337    pub fn pin(ctx: &egui::Context, order: ButtonOrder) {
338        ctx.data_mut(|d| d.insert_temp(egui::Id::unique(PINNED_ORDER), order));
339    }
340
341    /// The order of the dialogs drawn in `ctx`: the one [pinned](ButtonOrder::pin)
342    /// there, else the platform's.
343    pub fn of(ctx: &egui::Context) -> Self {
344        ctx.data(|d| d.get_temp(egui::Id::unique(PINNED_ORDER)))
345            .unwrap_or_else(Self::platform)
346    }
347
348    /// The order on Windows (`windows`) or on a desktop
349    /// (`XDG_CURRENT_DESKTOP`, as `KDE` or `GNOME:Ubuntu`).
350    pub fn for_platform(windows: bool, desktop: &str) -> Self {
351        let kde = desktop.split(':').any(|d| d.eq_ignore_ascii_case("KDE"));
352        if windows || kde {
353            Self::PrimaryFirst
354        } else {
355            Self::PrimaryLast
356        }
357    }
358}
359
360impl Confirm {
361    pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
362        Self {
363            title: title.into(),
364            detail: String::new(),
365            verb: verb.into(),
366            danger: false,
367            command,
368            args: Json::Null,
369            copy: true,
370            details: Details::default(),
371            secondary: None,
372            cancel: String::new(),
373            order: None,
374        }
375    }
376
377    /// A second action beside the primary one: three buttons.
378    pub fn secondary(mut self, secondary: Secondary) -> Self {
379        self.secondary = Some(secondary);
380        self
381    }
382
383    /// The Cancel button's own text ("Keep editing").
384    pub fn cancel(mut self, label: &str) -> Self {
385        self.cancel = label.into();
386        self
387    }
388
389    /// The buttons in this order rather than the platform's.
390    pub fn order(mut self, order: ButtonOrder) -> Self {
391        self.order = Some(order);
392        self
393    }
394
395    /// With or without the Copy button.
396    pub fn copyable(mut self, copy: bool) -> Self {
397        self.copy = copy;
398        self
399    }
400
401    /// With technical details: key-value lines the Copy button appends to
402    /// the copied text, hidden or shown ([`DetailsMode`]; hidden by
403    /// default on a confirmation).
404    pub fn details<K: Into<String>, V: Into<String>>(
405        mut self,
406        lines: impl IntoIterator<Item = (K, V)>,
407        mode: DetailsMode,
408    ) -> Self {
409        self.details = Details::new(lines, mode);
410        self
411    }
412
413    pub fn detail(mut self, detail: &str) -> Self {
414        self.detail = detail.into();
415        self
416    }
417
418    pub fn danger(mut self) -> Self {
419        self.danger = true;
420        self
421    }
422
423    pub fn args(mut self, args: Json) -> Self {
424        self.args = args;
425        self
426    }
427}
428
429/// One field of a form.
430#[derive(Clone, Debug, PartialEq, Serialize)]
431pub struct Field {
432    /// Its key in the command's arguments.
433    pub key: String,
434    pub descriptor: Descriptor,
435    pub value: Value,
436}
437
438/// Fields typed by value descriptors, and the command they go to.
439#[derive(Clone, Debug, PartialEq, Serialize)]
440pub struct Form {
441    pub title: String,
442    pub fields: Vec<Field>,
443    pub verb: String,
444    pub command: CommandId,
445    /// Arguments the fields are merged into.
446    pub args: Json,
447}
448
449impl Form {
450    pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
451        Self {
452            title: title.into(),
453            fields: Vec::new(),
454            verb: verb.into(),
455            command,
456            args: Json::Null,
457        }
458    }
459
460    /// Adds a field starting at its descriptor's default.
461    pub fn field(mut self, key: &str, descriptor: Descriptor) -> Self {
462        let value = descriptor.default.clone();
463        self.fields.push(Field {
464            key: key.into(),
465            descriptor,
466            value,
467        });
468        self
469    }
470
471    /// Adds a field starting at a value.
472    pub fn field_at(mut self, key: &str, descriptor: Descriptor, value: Value) -> Self {
473        self.fields.push(Field {
474            key: key.into(),
475            descriptor,
476            value,
477        });
478        self
479    }
480}
481
482/// One option of a [`Choose`]: what it shows and the value it answers.
483#[derive(Clone, Debug, PartialEq, Serialize)]
484pub struct ChooseOption {
485    pub label: String,
486    /// What the command gets when it is chosen.
487    pub value: Json,
488    /// A second line, filtered on too (a path, a size).
489    #[serde(skip_serializing_if = "String::is_empty")]
490    pub hint: String,
491}
492
493impl ChooseOption {
494    pub fn new(label: &str, value: Json) -> Self {
495        Self {
496            label: label.into(),
497            value,
498            hint: String::new(),
499        }
500    }
501
502    pub fn hint(mut self, hint: &str) -> Self {
503        self.hint = hint.into();
504        self
505    }
506}
507
508/// One option among several, under a filter field; the command gets the
509/// option's value (under `value_key`, `value` by default), its index
510/// (`choice`) and its `label`, merged into `args`.
511#[derive(Clone, Debug, PartialEq, Serialize)]
512pub struct Choose {
513    pub title: String,
514    pub detail: String,
515    pub options: Vec<ChooseOption>,
516    pub command: CommandId,
517    pub args: Json,
518    /// The argument the chosen value goes in.
519    pub value_key: String,
520}
521
522impl Choose {
523    /// Options by label, each answering its label.
524    pub fn new(title: &str, options: &[&str], command: CommandId) -> Self {
525        Self::with_options(
526            title,
527            options
528                .iter()
529                .map(|o| ChooseOption::new(o, json!(o)))
530                .collect(),
531            command,
532        )
533    }
534
535    /// Options with values of their own.
536    pub fn with_options(title: &str, options: Vec<ChooseOption>, command: CommandId) -> Self {
537        Self {
538            title: title.into(),
539            detail: String::new(),
540            options,
541            command,
542            args: Json::Null,
543            value_key: "value".into(),
544        }
545    }
546
547    /// Adds an option.
548    pub fn option(mut self, option: ChooseOption) -> Self {
549        self.options.push(option);
550        self
551    }
552
553    pub fn detail(mut self, detail: &str) -> Self {
554        self.detail = detail.into();
555        self
556    }
557
558    /// Arguments the answer is merged into.
559    pub fn args(mut self, args: Json) -> Self {
560        self.args = args;
561        self
562    }
563
564    /// The argument the chosen value goes in (`value` by default).
565    pub fn value_key(mut self, key: &str) -> Self {
566        self.value_key = key.into();
567        self
568    }
569
570    /// The options a filter shows, best match first (all, in order,
571    /// without a filter): their indexes.
572    pub fn visible(&self, filter: &str) -> Vec<usize> {
573        if filter.trim().is_empty() {
574            return (0..self.options.len()).collect();
575        }
576        fuzzy::rank(&self.options, filter, |o| format!("{} {}", o.label, o.hint))
577            .into_iter()
578            .map(|(i, _)| i)
579            .collect()
580    }
581}
582
583/// Something to read and acknowledge: a message, or an error
584/// ([`Info::error`]).
585///
586/// ```
587/// use egui_pop_api::dialogs::{DetailsMode, Info};
588///
589/// let failed = Info::error("Export failed", "The disk is full.")
590///     .details([("version", "1.2.0"), ("job", "42")], DetailsMode::Auto);
591/// assert!(failed.details.shown(failed.error));
592/// assert_eq!(
593///     failed.copy_text(),
594///     "Export failed\n\nThe disk is full.\n\n---\nversion: 1.2.0\njob: 42"
595/// );
596/// ```
597#[derive(Clone, Debug, PartialEq, Serialize)]
598pub struct Info {
599    pub title: String,
600    pub text: String,
601    /// An error: its details are shown (collapsed) by default.
602    pub error: bool,
603    /// The Copy button in its bottom corner (on by default).
604    pub copy: bool,
605    /// Technical lines for a bug report (none by default).
606    #[serde(skip_serializing_if = "Details::is_empty")]
607    pub details: Details,
608}
609
610impl Info {
611    pub fn new(title: &str, text: &str) -> Self {
612        Self {
613            title: title.into(),
614            text: text.into(),
615            error: false,
616            copy: true,
617            details: Details::default(),
618        }
619    }
620
621    /// An error to acknowledge: its details are shown by default, in a
622    /// collapsed "Details" section.
623    pub fn error(title: &str, text: &str) -> Self {
624        Self {
625            error: true,
626            ..Self::new(title, text)
627        }
628    }
629
630    /// With or without the Copy button.
631    pub fn copyable(mut self, copy: bool) -> Self {
632        self.copy = copy;
633        self
634    }
635
636    /// With technical details: key-value lines the Copy button appends to
637    /// the copied text, hidden or shown ([`DetailsMode`]; shown on an
638    /// error, hidden otherwise, by default).
639    pub fn details<K: Into<String>, V: Into<String>>(
640        mut self,
641        lines: impl IntoIterator<Item = (K, V)>,
642        mode: DetailsMode,
643    ) -> Self {
644        self.details = Details::new(lines, mode);
645        self
646    }
647
648    /// What its Copy button puts on the clipboard.
649    pub fn copy_text(&self) -> String {
650        copy_text(&self.title, &self.text, &self.details)
651    }
652}
653
654impl Confirm {
655    /// What its Copy button puts on the clipboard.
656    pub fn copy_text(&self) -> String {
657        copy_text(&self.title, &self.detail, &self.details)
658    }
659}
660
661/// Where a dialog's details go.
662#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
663#[serde(rename_all = "lowercase")]
664pub enum DetailsMode {
665    /// The dialog's default: shown on an error ([`Info::error`]), hidden
666    /// otherwise.
667    #[default]
668    Auto,
669    /// Only in the copied text, never on screen.
670    Hidden,
671    /// Also on screen, in a collapsed "Details" section: a read-only,
672    /// monospace, selectable area holding the lines the Copy button
673    /// copies.
674    Shown,
675}
676
677/// A dialog's technical details, for a bug report: key-value lines,
678/// copied after its text under a `---` separator, each `key: value`.
679#[derive(Clone, Debug, Default, PartialEq, Serialize)]
680pub struct Details {
681    pub lines: Vec<(String, String)>,
682    pub mode: DetailsMode,
683}
684
685impl Details {
686    pub fn new<K: Into<String>, V: Into<String>>(
687        lines: impl IntoIterator<Item = (K, V)>,
688        mode: DetailsMode,
689    ) -> Self {
690        Self {
691            lines: lines
692                .into_iter()
693                .map(|(k, v)| (k.into(), v.into()))
694                .collect(),
695            mode,
696        }
697    }
698
699    pub fn is_empty(&self) -> bool {
700        self.lines.is_empty()
701    }
702
703    /// The lines, `key: value` each, one per line.
704    pub fn text(&self) -> String {
705        self.lines
706            .iter()
707            .map(|(k, v)| format!("{k}: {v}"))
708            .collect::<Vec<_>>()
709            .join("\n")
710    }
711
712    /// Shown on screen, in a dialog that is an error or not.
713    pub fn shown(&self, error: bool) -> bool {
714        !self.is_empty()
715            && match self.mode {
716                DetailsMode::Auto => error,
717                DetailsMode::Hidden => false,
718                DetailsMode::Shown => true,
719            }
720    }
721}
722
723/// The text a Copy button copies: the title, the message, then the
724/// details under a separator.
725fn copy_text(title: &str, message: &str, details: &Details) -> String {
726    let mut text = title.to_string();
727    if !message.is_empty() {
728        text.push_str("\n\n");
729        text.push_str(message);
730    }
731    if !details.is_empty() {
732        text.push_str("\n\n---\n");
733        text.push_str(&details.text());
734    }
735    text
736}
737
738/// A dialog with a body of its own (ADR 0013), drawn by a closure
739/// given to [`Dialogs::open_custom`]: a preview, a viewport, a curve.
740///
741/// ```
742/// use egui_pop_api::dialogs::Custom;
743/// use egui_pop_model::ids::CommandId;
744/// use egui_pop_model::mount::ClaimKey;
745///
746/// let preview = Custom::new("Export preview", "Export 3 images", CommandId::from_static("doc.export"))
747///     .share(0.7)
748///     .claims(&[ClaimKey::Escape]);
749/// assert_eq!(preview.verb, "Export 3 images");
750/// assert!(preview.claims_key(ClaimKey::Escape));
751/// ```
752#[derive(Clone, Debug, PartialEq, Serialize)]
753pub struct Custom {
754    pub title: String,
755    /// The primary button: what it does ("Export 3 images"); empty with
756    /// no command: a Close button only.
757    pub verb: String,
758    /// Destructive: the danger style, the focus starts on Cancel, no key
759    /// accepts.
760    pub danger: bool,
761    /// What accepting runs, with `args` and the body's values merged in;
762    /// `None`: accepting closes the dialog.
763    pub command: Option<CommandId>,
764    pub args: Json,
765    /// The body's size in points (capped to the window); `None`: a
766    /// share of the window.
767    pub size: Option<[f32; 2]>,
768    /// The share of the window the body takes without a size.
769    pub share: f32,
770    /// Keys the body claims: Enter (Ctrl+Enter then accepts), Escape (it
771    /// goes to the body first).
772    pub claims: Vec<ClaimKey>,
773    /// What the body's component needs: checked against the custom
774    /// dialog's offer when it opens (a refusal opens nothing), and
775    /// recorded as a mount while it is open.
776    pub needs: Option<Mountable>,
777    /// The dialog draws its footer (the primary button and Cancel) and
778    /// accepts on Enter; `false` ([`Custom::own_footer`]): the body draws
779    /// its own buttons (a wizard's Back, Next and Finish) and answers
780    /// through [`CustomPass::accept`] and [`CustomPass::cancel`].
781    pub footer: bool,
782}
783
784impl Custom {
785    /// The share of the window a body takes by default.
786    pub const SHARE: f32 = 0.7;
787
788    /// A dialog whose primary button says what it does and runs
789    /// `command`.
790    pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
791        Self {
792            title: title.into(),
793            verb: verb.into(),
794            danger: false,
795            command: Some(command),
796            args: Json::Null,
797            size: None,
798            share: Self::SHARE,
799            claims: Vec::new(),
800            needs: None,
801            footer: true,
802        }
803    }
804
805    /// A dialog that only closes (a Close button).
806    pub fn closing(title: &str) -> Self {
807        Self {
808            title: title.into(),
809            verb: String::new(),
810            danger: false,
811            command: None,
812            args: Json::Null,
813            size: None,
814            share: Self::SHARE,
815            claims: Vec::new(),
816            needs: None,
817            footer: true,
818        }
819    }
820
821    pub fn danger(mut self) -> Self {
822        self.danger = true;
823        self
824    }
825
826    /// Arguments the values are merged into.
827    pub fn args(mut self, args: Json) -> Self {
828        self.args = args;
829        self
830    }
831
832    /// The body's size, in points.
833    pub fn size(mut self, width: f32, height: f32) -> Self {
834        self.size = Some([width.max(1.0), height.max(1.0)]);
835        self
836    }
837
838    /// The share of the window the body takes (0.2 to 1).
839    pub fn share(mut self, share: f32) -> Self {
840        self.share = share.clamp(0.2, 1.0);
841        self
842    }
843
844    /// Keys the body takes first.
845    pub fn claims(mut self, keys: &[ClaimKey]) -> Self {
846        for k in keys {
847            if !self.claims.contains(k) {
848                self.claims.push(*k);
849            }
850        }
851        self
852    }
853
854    /// What the body's component needs: its claimed keys become the
855    /// dialog's, and it is checked against the custom dialog's offer.
856    pub fn needs(mut self, needs: Mountable) -> Self {
857        let claims = needs.claims.clone();
858        self.needs = Some(needs);
859        self.claims(&claims)
860    }
861
862    /// The body draws its own buttons: no footer, and Enter is the
863    /// body's (it claims it). It answers through [`CustomPass::accept`]
864    /// and [`CustomPass::cancel`]; Escape still cancels unless the body
865    /// claims it too.
866    pub fn own_footer(mut self) -> Self {
867        self.footer = false;
868        self.claims(&[ClaimKey::Enter])
869    }
870
871    /// Whether the body claims a key.
872    pub fn claims_key(&self, key: ClaimKey) -> bool {
873        self.claims.contains(&key)
874    }
875
876    /// The body's size in a window of `room` points.
877    pub fn body_size(&self, room: Vec2) -> Vec2 {
878        let size = match self.size {
879            Some([w, h]) => egui::vec2(w.min(room.x - 64.0), h.min(room.y - 160.0)),
880            None => egui::vec2(room.x * self.share, room.y * self.share - 120.0),
881        };
882        size.max(egui::vec2(120.0, 80.0))
883    }
884}
885
886/// What the custom dialog offers its body (ADR 0013): a size of its
887/// own, modal, transient, Enter and Escape given to a body claiming
888/// them, a focus scope and a fault boundary, the main window, sRGB first
889/// (decided 2026-10-14), outside the context stack's projection.
890pub fn custom_host() -> HostOffer {
891    HostOffer::new(crate::mounts::CUSTOM_DIALOG, "C", "Custom dialog")
892        .source("dialogs: Dialog::Custom, Dialogs::open_custom")
893        .size(HostSize::Given)
894        .focus(FocusPolicy::ModalExclusive)
895        .owns_keys(&[ClaimKey::Enter, ClaimKey::Escape])
896        .honours_claims()
897        .dismissed_by(&[Dismiss::Answer, Dismiss::Escape])
898        .lifetime(Lifetime::Transient)
899        .keeps(&[Keep::Place])
900}
901
902/// What a custom dialog's body says during a pass: its values, whether
903/// the primary action is possible, its description, an Escape it
904/// takes, an answer of its own.
905#[derive(Debug, Default)]
906pub struct CustomPass {
907    values: Map<String, Json>,
908    ready: bool,
909    describe: Json,
910    escape: bool,
911    answer: Option<Answer>,
912}
913
914impl CustomPass {
915    /// A value merged into the command's arguments when accepted (kept
916    /// from pass to pass).
917    pub fn value(&mut self, key: &str, value: Json) {
918        self.values.insert(key.into(), value);
919    }
920
921    /// The values so far.
922    pub fn values(&self) -> &Map<String, Json> {
923        &self.values
924    }
925
926    /// Whether the primary action is possible now (kept from pass to
927    /// pass; possible at first).
928    pub fn ready(&mut self, ready: bool) {
929        self.ready = ready;
930    }
931
932    /// What the debug bridge shows of the body (the `dialogs`
933    /// collector's `body`).
934    pub fn describe(&mut self, description: Json) {
935        self.describe = description;
936    }
937
938    /// This pass's Escape is the body's: it has something to cancel (a
939    /// drag, a selection, a popup). Only for a body claiming Escape.
940    pub fn claim_escape(&mut self) {
941        self.escape = true;
942    }
943
944    /// Accepts the dialog, as its primary button.
945    pub fn accept(&mut self) {
946        self.answer = Some(Answer::Accept {
947            values: self.values.clone(),
948        });
949    }
950
951    /// Cancels the dialog.
952    pub fn cancel(&mut self) {
953        self.answer = Some(Answer::Cancel);
954    }
955}
956
957/// A custom dialog's body.
958type BodyFn = Box<dyn FnMut(&mut Ui, &AppHandle, &mut CustomPass)>;
959
960/// The bodies of the custom dialogs, by dialog id, on the application's
961/// side.
962#[derive(Default)]
963struct Bodies(std::cell::RefCell<std::collections::BTreeMap<u64, BodyFn>>);
964
965/// A dialog.
966#[derive(Clone, Debug, PartialEq, Serialize)]
967#[serde(tag = "kind", rename_all = "lowercase")]
968pub enum Dialog {
969    Confirm(Confirm),
970    Form(Form),
971    Choose(Choose),
972    Info(Info),
973    Custom(Box<Custom>),
974}
975
976impl From<Custom> for Dialog {
977    fn from(d: Custom) -> Self {
978        Dialog::Custom(Box::new(d))
979    }
980}
981
982impl From<Confirm> for Dialog {
983    fn from(d: Confirm) -> Self {
984        Dialog::Confirm(d)
985    }
986}
987
988impl From<Form> for Dialog {
989    fn from(d: Form) -> Self {
990        Dialog::Form(d)
991    }
992}
993
994impl From<Choose> for Dialog {
995    fn from(d: Choose) -> Self {
996        Dialog::Choose(d)
997    }
998}
999
1000impl From<Info> for Dialog {
1001    fn from(d: Info) -> Self {
1002        Dialog::Info(d)
1003    }
1004}
1005
1006impl Dialog {
1007    pub fn title(&self) -> &str {
1008        match self {
1009            Dialog::Confirm(d) => &d.title,
1010            Dialog::Form(d) => &d.title,
1011            Dialog::Choose(d) => &d.title,
1012            Dialog::Info(d) => &d.title,
1013            Dialog::Custom(d) => &d.title,
1014        }
1015    }
1016}
1017
1018/// What a modal dialog does to the interface behind it. Either way the
1019/// interface is blocked while the dialog is open, and a click on it never
1020/// closes the dialog.
1021#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
1022#[serde(rename_all = "lowercase")]
1023pub enum Backdrop {
1024    /// Dimmed, as much as the `backdrop.opacity` token says (less while
1025    /// the dialog is dragged).
1026    #[default]
1027    Dim,
1028    /// Left untouched: for a dialog previewing its effect on the image.
1029    Clear,
1030}
1031
1032/// A dialog and how it is presented around its content: what
1033/// [`Dialogs::open`] takes (any dialog converts into one, presented by
1034/// default).
1035///
1036/// ```
1037/// use egui_pop_api::dialogs::{Backdrop, DialogSpec, Info};
1038///
1039/// let spec = DialogSpec::new(Info::new("Saved", "The document was saved.")).closable(true);
1040/// assert!(spec.closable);
1041/// let spec = DialogSpec::new(Info::new("Levels", "Drag to adjust."))
1042///     .movable(true)
1043///     .backdrop(Backdrop::Clear)
1044///     .remember_position("levels");
1045/// assert_eq!(spec.remember.as_deref(), Some("levels"));
1046/// ```
1047#[derive(Clone, Debug, PartialEq)]
1048pub struct DialogSpec {
1049    pub dialog: Dialog,
1050    /// A ✕ at the right end of the title row, doing what Escape does
1051    /// (off by default; the [`SETTING_CLOSABLE`] setting turns it on for
1052    /// every dialog).
1053    pub closable: bool,
1054    /// A header band to drag the dialog by (off by default; the
1055    /// [`SETTING_MOVABLE`] setting turns it on for every dialog).
1056    pub movable: bool,
1057    /// What the dialog does to the interface behind it.
1058    pub backdrop: Backdrop,
1059    /// The key the dialog's place is kept under: it comes up where it
1060    /// was left instead of centred.
1061    pub remember: Option<String>,
1062}
1063
1064impl DialogSpec {
1065    pub fn new(dialog: impl Into<Dialog>) -> Self {
1066        Self {
1067            dialog: dialog.into(),
1068            closable: false,
1069            movable: false,
1070            backdrop: Backdrop::Dim,
1071            remember: None,
1072        }
1073    }
1074
1075    /// With the close button (a notice without Cancel, an application
1076    /// following the web's convention).
1077    pub fn closable(mut self, closable: bool) -> Self {
1078        self.closable = closable;
1079        self
1080    }
1081
1082    /// With a header band to drag it by (a dialog hiding what it acts
1083    /// on).
1084    pub fn movable(mut self, movable: bool) -> Self {
1085        self.movable = movable;
1086        self
1087    }
1088
1089    /// What it does to the interface behind it ([`Backdrop::Dim`] by
1090    /// default).
1091    pub fn backdrop(mut self, backdrop: Backdrop) -> Self {
1092        self.backdrop = backdrop;
1093        self
1094    }
1095
1096    /// Comes up where it was last left, kept under `key` (letters,
1097    /// digits, `. _ - :`) in the host's store; otherwise centred.
1098    pub fn remember_position(mut self, key: &str) -> Self {
1099        self.remember = Some(key.into());
1100        self
1101    }
1102}
1103
1104impl From<Dialog> for DialogSpec {
1105    fn from(d: Dialog) -> Self {
1106        Self::new(d)
1107    }
1108}
1109
1110impl From<Confirm> for DialogSpec {
1111    fn from(d: Confirm) -> Self {
1112        Self::new(d)
1113    }
1114}
1115
1116impl From<Form> for DialogSpec {
1117    fn from(d: Form) -> Self {
1118        Self::new(d)
1119    }
1120}
1121
1122impl From<Choose> for DialogSpec {
1123    fn from(d: Choose) -> Self {
1124        Self::new(d)
1125    }
1126}
1127
1128impl From<Info> for DialogSpec {
1129    fn from(d: Info) -> Self {
1130        Self::new(d)
1131    }
1132}
1133
1134impl From<Custom> for DialogSpec {
1135    fn from(d: Custom) -> Self {
1136        Self::new(d)
1137    }
1138}
1139
1140/// An answer.
1141#[derive(Clone, Debug, PartialEq, Serialize)]
1142#[serde(tag = "answer", rename_all = "lowercase")]
1143pub enum Answer {
1144    /// The primary action (a form's values as they are, or changed:
1145    /// `values` by field key).
1146    Accept {
1147        values: Map<String, Json>,
1148    },
1149    /// One of a choice's options, by index.
1150    Choose {
1151        index: usize,
1152    },
1153    /// One of a choice's options, by its value.
1154    Value {
1155        value: Json,
1156    },
1157    Cancel,
1158}
1159
1160impl Answer {
1161    /// As the debug bridge sends it: `{"answer": "accept", "values":
1162    /// {...}}`, `{"answer": "choose", "index": 1}` or `{"answer":
1163    /// "choose", "value": ...}`, `{"answer": "cancel"}`.
1164    pub fn from_json(json: &Json) -> Result<Answer, String> {
1165        match json.get("answer").and_then(Json::as_str) {
1166            Some("accept") => Ok(Answer::Accept {
1167                values: json
1168                    .get("values")
1169                    .and_then(Json::as_object)
1170                    .cloned()
1171                    .unwrap_or_default(),
1172            }),
1173            Some("choose" | "value") => match (json.get("value"), json.get("index")) {
1174                (Some(v), _) => Ok(Answer::Value { value: v.clone() }),
1175                (None, Some(i)) => i
1176                    .as_u64()
1177                    .map(|i| Answer::Choose { index: i as usize })
1178                    .ok_or_else(|| "`index` is a number".into()),
1179                (None, None) => Err("`value` or `index` is missing".into()),
1180            },
1181            Some("cancel") => Ok(Answer::Cancel),
1182            _ => Err("`answer` is accept, choose or cancel".into()),
1183        }
1184    }
1185}
1186
1187/// An open dialog.
1188#[derive(Clone, Debug)]
1189struct Open {
1190    id: u64,
1191    dialog: Dialog,
1192    /// Opened with the close button.
1193    closable: bool,
1194    /// Opened movable.
1195    movable: bool,
1196    backdrop: Backdrop,
1197    /// The key its place is kept under.
1198    remember: Option<String>,
1199    /// Where it is: its offset from the window's centre, in points.
1200    offset: Vec2,
1201    /// Moved by the keys: where it was when that started.
1202    moving: Option<Vec2>,
1203    /// Dragged: where it was when the drag started.
1204    drag_from: Option<Vec2>,
1205    /// Focus placed on its first pass.
1206    focused: bool,
1207    /// When its Copy button was last clicked (egui's time): the "Copied"
1208    /// note shows a moment.
1209    copied_at: Option<f64>,
1210    /// The window it is shown over: the active one of its group when it
1211    /// came up.
1212    window: Option<egui::ViewportId>,
1213    /// The window group it belongs to (`AppHandle::window_group`): the one
1214    /// current when it was opened, else the active one's when it first
1215    /// shows.
1216    group: Option<egui::ViewportId>,
1217    /// The in-app picker open inside the dialog for a field (without the
1218    /// files plugin): its key and picker.
1219    picking: Option<(String, FilePicker)>,
1220    /// A field's Browse asked for a choice (started by the next frame).
1221    browse: Option<(String, FileRequest)>,
1222    /// A choice under way for a field: its key, the choice's id and
1223    /// result to come.
1224    choosing: Option<(String, u64, Pending)>,
1225    error: Option<String>,
1226    /// A choice's filter, and the option highlighted among those shown.
1227    filter: String,
1228    highlight: usize,
1229    /// A custom dialog's values, readiness and description, as its body
1230    /// left them.
1231    values: Map<String, Json>,
1232    ready: bool,
1233    body: Json,
1234    /// The owner it was opened under (`values::current_scope`), if any.
1235    opener: Option<OwnerId>,
1236    /// Its `pop.popup.open` was asked (it came up): its end asks `pop.popup.close`.
1237    on_bus: bool,
1238}
1239
1240impl Open {
1241    /// Its popup's id in the registry.
1242    fn popup(&self) -> String {
1243        format!("{POPUP_PREFIX}{}", self.id)
1244    }
1245
1246    /// Who owns its popup: the plugin that opened it, else this one.
1247    fn owner(&self) -> String {
1248        self.opener
1249            .as_ref()
1250            .map_or_else(|| PLUGIN.as_str().to_string(), |o| o.as_str().to_string())
1251    }
1252}
1253
1254#[derive(Debug, Default)]
1255struct State {
1256    next: u64,
1257    queue: VecDeque<Open>,
1258    /// Answers given (by the bridge) for the next frame.
1259    given: Vec<(u64, Answer, Origin)>,
1260    /// What happened to the last dialogs: title and answer.
1261    answered: VecDeque<(String, Answer, Origin)>,
1262}
1263
1264/// The queue of dialogs.
1265#[derive(Clone, Debug, Default)]
1266pub struct Dialogs(Arc<Mutex<State>>);
1267
1268impl Dialogs {
1269    /// Queues a dialog (or a [`DialogSpec`]); returns its id.
1270    pub fn open(&self, dialog: impl Into<DialogSpec>) -> u64 {
1271        let spec = dialog.into();
1272        let mut s = lock(&self.0);
1273        s.next += 1;
1274        let id = s.next;
1275        s.queue.push_back(Open {
1276            id,
1277            dialog: spec.dialog,
1278            closable: spec.closable,
1279            movable: spec.movable,
1280            backdrop: spec.backdrop,
1281            remember: spec.remember,
1282            offset: Vec2::ZERO,
1283            moving: None,
1284            drag_from: None,
1285            focused: false,
1286            copied_at: None,
1287            window: None,
1288            group: crate::windows::current_group(),
1289            picking: None,
1290            browse: None,
1291            choosing: None,
1292            error: None,
1293            filter: String::new(),
1294            highlight: 0,
1295            values: Map::new(),
1296            ready: true,
1297            body: Json::Null,
1298            opener: egui_pop_model::values::current_scope(),
1299            on_bus: false,
1300        });
1301        id
1302    }
1303
1304    /// Shows a dialog now, ahead of the queue: a question that the dialog
1305    /// shown is waiting for (a file picker inside it asking before
1306    /// replacing a file). That one comes back once this one is answered.
1307    pub(crate) fn open_now(&self, dialog: impl Into<DialogSpec>) -> u64 {
1308        let id = self.open(dialog);
1309        let mut s = lock(&self.0);
1310        if let Some(open) = s.queue.pop_back() {
1311            s.queue.push_front(open);
1312        }
1313        id
1314    }
1315
1316    /// Queues a dialog with a body of its own ([`Custom`]): the body is
1317    /// kept on the application's side and drawn every frame the dialog
1318    /// is shown. When the dialog says what its body needs
1319    /// ([`Custom::needs`]), the need is checked against the custom
1320    /// dialog's offer first: a refusal is reported with its rule and
1321    /// opens nothing (ADR 0003, ADR 0013).
1322    pub fn open_custom(
1323        &self,
1324        app: &AppHandle,
1325        spec: impl Into<DialogSpec>,
1326        body: impl FnMut(&mut Ui, &AppHandle, &mut CustomPass) + 'static,
1327    ) -> Result<u64, String> {
1328        let spec = spec.into();
1329        let Dialog::Custom(custom) = &spec.dialog else {
1330            return Err(format!(
1331                "`{}` is not a custom dialog: open it with `open`",
1332                spec.dialog.title()
1333            ));
1334        };
1335        if let Some(needs) = &custom.needs {
1336            app.mount_needs(needs, &custom_host())?;
1337        }
1338        let id = self.open(spec);
1339        app.local::<Bodies>()
1340            .0
1341            .borrow_mut()
1342            .insert(id, Box::new(body));
1343        Ok(id)
1344    }
1345
1346    /// The dialog shown in the current window group (see the module's
1347    /// documentation), with its id.
1348    pub fn current(&self) -> Option<(u64, Dialog)> {
1349        let s = lock(&self.0);
1350        shown_at(&s, crate::windows::current_group())
1351            .map(|i| (s.queue[i].id, s.queue[i].dialog.clone()))
1352    }
1353
1354    /// The dialog shown in a window group (`AppHandle::window_group`), with
1355    /// its id.
1356    pub fn current_in(&self, group: egui::ViewportId) -> Option<(u64, Dialog)> {
1357        let s = lock(&self.0);
1358        shown_at(&s, Some(group)).map(|i| (s.queue[i].id, s.queue[i].dialog.clone()))
1359    }
1360
1361    /// Where the dialog shown is: its offset from the window's centre, in
1362    /// points (zero: centred).
1363    pub fn offset(&self) -> Option<Vec2> {
1364        let s = lock(&self.0);
1365        shown_at(&s, crate::windows::current_group()).map(|i| s.queue[i].offset)
1366    }
1367
1368    /// Whether a dialog is still open (shown or waiting).
1369    pub fn is_open(&self, id: u64) -> bool {
1370        lock(&self.0).queue.iter().any(|o| o.id == id)
1371    }
1372
1373    /// How many dialogs wait, the shown one included.
1374    pub fn len(&self) -> usize {
1375        lock(&self.0).queue.len()
1376    }
1377
1378    pub fn is_empty(&self) -> bool {
1379        self.len() == 0
1380    }
1381
1382    /// Answers the shown dialog (applied on the next frame), as `origin`.
1383    pub fn answer(&self, answer: Answer, origin: Origin) -> Result<(), String> {
1384        let mut s = lock(&self.0);
1385        let at = shown_at(&s, crate::windows::current_group()).ok_or("no dialog is open")?;
1386        let id = s.queue[at].id;
1387        s.given.push((id, answer, origin));
1388        Ok(())
1389    }
1390
1391    /// Answers a dialog by its id, shown or waiting (applied on the next
1392    /// frame, through the [`STEP_ANSWER`] step, as `origin`): a body that
1393    /// lives elsewhere (a wizard run as a sheet) ended. Returns whether it
1394    /// was open.
1395    pub(crate) fn give(&self, id: u64, answer: Answer, origin: Origin) -> bool {
1396        let mut s = lock(&self.0);
1397        if !s.queue.iter().any(|o| o.id == id) {
1398            return false;
1399        }
1400        s.given.push((id, answer, origin));
1401        true
1402    }
1403
1404    /// Cancels a dialog by its id, shown or waiting (applied on the next
1405    /// frame, through the [`STEP_ANSWER`] step, as `origin`): what opened
1406    /// it no longer wants an answer, its question expired. Returns
1407    /// whether it was open.
1408    pub fn cancel(&self, id: u64, origin: Origin) -> bool {
1409        let mut s = lock(&self.0);
1410        if !s.queue.iter().any(|o| o.id == id) {
1411            return false;
1412        }
1413        s.given.push((id, Answer::Cancel, origin));
1414        true
1415    }
1416
1417    /// The dialog shown in the current window group and how many wait
1418    /// behind it, as the bridge shows them.
1419    pub fn describe(&self) -> Json {
1420        let id = {
1421            let s = lock(&self.0);
1422            shown_at(&s, crate::windows::current_group()).map(|i| s.queue[i].id)
1423        };
1424        id.map_or(Json::Null, |id| self.describe_one(id))
1425    }
1426
1427    /// Each window group's dialog shown, by window name, with how many
1428    /// wait behind it: `[{ "window", "id", "title", "waiting" }]`.
1429    pub fn windows(&self, app: &AppHandle) -> Vec<Json> {
1430        let s = lock(&self.0);
1431        let mut groups: Vec<egui::ViewportId> = Vec::new();
1432        for o in &s.queue {
1433            let g = o.group.unwrap_or(egui::ViewportId::ROOT);
1434            if !groups.contains(&g) {
1435                groups.push(g);
1436            }
1437        }
1438        groups
1439            .into_iter()
1440            .filter_map(|g| {
1441                let i = shown_at(&s, Some(g))?;
1442                let o = &s.queue[i];
1443                Some(json!({
1444                    "window": app.window_of_group(g),
1445                    "id": o.id,
1446                    "title": o.dialog.title(),
1447                    "waiting": s.queue.iter().filter(|q| q.group == o.group).count() - 1,
1448                }))
1449            })
1450            .collect()
1451    }
1452
1453    /// One open dialog, as the bridge shows it.
1454    fn describe_one(&self, id: u64) -> Json {
1455        let s = lock(&self.0);
1456        match s.queue.iter().find(|o| o.id == id) {
1457            Some(o) => {
1458                let mut d = serde_json::to_value(&o.dialog).unwrap_or(Json::Null);
1459                d["id"] = json!(o.id);
1460                d["closable"] = json!(o.closable);
1461                d["movable"] = json!(o.movable);
1462                d["backdrop"] = json!(o.backdrop);
1463                d["offset"] = json!([o.offset.x, o.offset.y]);
1464                d["moving"] = json!(o.moving.is_some());
1465                if let Some(key) = &o.remember {
1466                    d["remember"] = json!(key);
1467                }
1468                d["waiting"] = json!(s.queue.iter().filter(|q| q.group == o.group).count() - 1);
1469                match &o.dialog {
1470                    // The typed values as they are, and plainly by key.
1471                    Dialog::Form(f) => d["values"] = Json::Object(values_of(&f.fields)),
1472                    Dialog::Choose(c) => {
1473                        d["filter"] = json!(o.filter);
1474                        d["shown"] = json!(c.visible(&o.filter));
1475                    }
1476                    Dialog::Custom(_) => {
1477                        d["values"] = Json::Object(o.values.clone());
1478                        d["ready"] = json!(o.ready);
1479                        d["body"] = o.body.clone();
1480                    }
1481                    _ => {}
1482                }
1483                d
1484            }
1485            None => Json::Null,
1486        }
1487    }
1488
1489    /// The last answers, oldest first: title, answer, origin.
1490    pub fn answered(&self) -> Vec<(String, Answer, Origin)> {
1491        lock(&self.0).answered.iter().cloned().collect()
1492    }
1493}
1494
1495/// The dialog shown in a window group: the first queued in it. Without a
1496/// group, the first queued at all. A dialog whose group is not known yet
1497/// counts in the main window's.
1498fn shown_at(s: &State, group: Option<egui::ViewportId>) -> Option<usize> {
1499    match group {
1500        None => (!s.queue.is_empty()).then_some(0),
1501        Some(g) => s
1502            .queue
1503            .iter()
1504            .position(|o| o.group.unwrap_or(egui::ViewportId::ROOT) == g),
1505    }
1506}
1507
1508/// The plugin.
1509#[derive(Debug, Default)]
1510pub struct DialogsPlugin;
1511
1512impl Plugin for DialogsPlugin {
1513    fn id(&self) -> PluginId {
1514        PLUGIN
1515    }
1516
1517    fn title(&self) -> String {
1518        "Dialogs".into()
1519    }
1520
1521    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1522        let dialogs = Dialogs::default();
1523        ctx.service(&DIALOGS, dialogs.clone())?;
1524        ctx.setting(
1525            SETTING_CLOSABLE,
1526            Descriptor::bool("Close button on every dialog", false).description(
1527                "A close button at the right end of each dialog's title row, doing what Escape does.",
1528            ),
1529        )?;
1530        ctx.setting(
1531            SETTING_MOVABLE,
1532            Descriptor::bool("Movable dialogs", false).description(
1533                "Every dialog has a header band to drag it by; Alt+F7 moves it with the arrow keys.",
1534            ),
1535        )?;
1536        let moved = dialogs.clone();
1537        ctx.command(
1538            CommandSpec::new(CMD_MOVE, "Move dialog", "Dialogs")
1539                .description("Moves the dialog shown with the arrow keys; Enter keeps the place, Escape puts it back.")
1540                .when("modalOpen")
1541                .key_with("Alt+F7", BindOptions::global().through_modal()),
1542            move |call| {
1543                let all = setting(call.app, SETTING_MOVABLE);
1544                let mut s = lock(&moved.0);
1545                let at = shown_at(&s, crate::windows::current_group()).ok_or("no dialog is open")?;
1546                let o = &mut s.queue[at];
1547                if !(o.movable || all) {
1548                    return Err("the dialog shown is not movable".into());
1549                }
1550                o.moving = Some(o.offset);
1551                o.drag_from = None;
1552                call.app.egui().request_repaint();
1553                Ok(json!({ "id": o.id }))
1554            },
1555        )?;
1556        ctx.step(
1557            StepSpec::new(
1558                STEP_MOVE,
1559                "A dialog is moved (dropped, moved by a key, centred again); a veto puts it back, a redirect places it elsewhere.",
1560            )
1561            .args(json!({ "id": 1, "title": "Levels", "key": "levels", "how": "drag", "from": [0.0, 0.0], "to": [120.0, -40.0] })),
1562        )?;
1563        ctx.step(
1564            StepSpec::new(STEP_SHOW, "A dialog comes up; a veto cancels it.")
1565                .args(json!({ "kind": "confirm", "id": 1, "title": "Delete 3 images?" })),
1566        )?;
1567        ctx.step(
1568            StepSpec::new(
1569                STEP_ANSWER,
1570                "A dialog is answered; a veto keeps it open, a redirect changes the answer.",
1571            )
1572            .args(json!({ "dialog": { "kind": "choose", "id": 1 }, "answer": { "answer": "choose", "index": 0 }, "origin": "user" })),
1573        )?;
1574        let (a, b) = (dialogs.clone(), dialogs);
1575        let weak = ctx.app().downgrade();
1576        let weak_a = ctx.app().downgrade();
1577        ctx.collector(
1578            FnCollector::new(
1579                "dialogs",
1580                "The dialog shown (kind, title, fields, verb, command) and how many wait; `answer` answers it as its caller.",
1581            )
1582            .snapshot(move |_| {
1583                let windows = weak_a.get().map(|app| a.windows(&app)).unwrap_or_default();
1584                json!({ "current": a.describe(), "windows": windows, "answered": a.answered() })
1585            })
1586            .action_as("answer", "Answers the dialog shown as its caller: accept (with `values`), choose (`value` or `index`) or cancel. An answer that would run a command not offered to agents is the user's only.", true, move |_, args, origin| {
1587                let answer = Answer::from_json(args)?;
1588                let app = weak.get()?;
1589                let open = {
1590                    let s = lock(&b.0);
1591                    let at = shown_at(&s, crate::windows::current_group()).ok_or("no dialog is open")?;
1592                    s.queue[at].clone()
1593                };
1594                refuse_unoffered(&app, &open, &answer, origin)?;
1595                b.answer(answer, origin.clone())?;
1596                Ok(json!({ "queued": true }))
1597            })
1598            .args(json!({ "answer": "accept", "values": {} })),
1599        )?;
1600        ctx.block(
1601            zones::WINDOW_OVERLAYS,
1602            Block::add(BlockId::from_static("egui_pop.dialogs"), 10, show),
1603        );
1604        listen(&ctx.app());
1605        Ok(())
1606    }
1607}
1608
1609/// The overlay a dialog is drawn in.
1610pub(crate) fn overlay_id(dialog: u64) -> egui::Id {
1611    egui::Id::unique(("egui_pop.dialog", dialog))
1612}
1613
1614/// How many answers are remembered.
1615const ANSWERED: usize = 16;
1616
1617/// The command an answer runs, with its arguments: `None` when it runs
1618/// none (a cancel, an information).
1619fn target(open: &Open, answer: &Answer) -> Result<Option<(CommandId, Json)>, String> {
1620    Ok(match (&open.dialog, &answer) {
1621        (_, Answer::Cancel) => None,
1622        (Dialog::Confirm(c), Answer::Accept { .. } | Answer::Choose { index: 0 }) => {
1623            Some((c.command.clone(), c.args.clone()))
1624        }
1625        (Dialog::Confirm(c), Answer::Choose { index: 1 }) => {
1626            let s = c
1627                .secondary
1628                .as_ref()
1629                .ok_or_else(|| format!("{} has no second action", c.title))?;
1630            Some((s.command.clone(), s.args.clone()))
1631        }
1632        (Dialog::Info(_), Answer::Accept { .. }) => None,
1633        (Dialog::Custom(c), Answer::Accept { values }) => {
1634            if !open.ready {
1635                return Err(format!("{} cannot be accepted yet", c.title));
1636            }
1637            c.command.as_ref().map(|command| {
1638                let mut args = match &c.args {
1639                    Json::Object(m) => m.clone(),
1640                    _ => Map::new(),
1641                };
1642                args.extend(open.values.clone());
1643                args.extend(values.clone());
1644                (command.clone(), Json::Object(args))
1645            })
1646        }
1647        (Dialog::Form(f), Answer::Accept { values }) => {
1648            let mut args = match &f.args {
1649                Json::Object(m) => m.clone(),
1650                _ => Map::new(),
1651            };
1652            // A note answers nothing.
1653            for field in f.fields.iter().filter(|x| !x.descriptor.note) {
1654                let v = match values.get(&field.key) {
1655                    Some(j) => Value::from_json(field.descriptor.ty, j)
1656                        .map_err(|e| format!("`{}`: {e}", field.key))?,
1657                    None => field.value.clone(),
1658                };
1659                args.insert(field.key.clone(), v.to_json());
1660            }
1661            Some((f.command.clone(), Json::Object(args)))
1662        }
1663        (Dialog::Choose(c), Answer::Choose { .. } | Answer::Value { .. }) => {
1664            let index = match &answer {
1665                Answer::Choose { index } => *index,
1666                Answer::Value { value } => c
1667                    .options
1668                    .iter()
1669                    .position(|o| o.value == *value)
1670                    .ok_or_else(|| format!("no option of value {value}"))?,
1671                _ => unreachable!("matched above"),
1672            };
1673            let option = c
1674                .options
1675                .get(index)
1676                .ok_or_else(|| format!("no option {index}"))?;
1677            let mut args = match &c.args {
1678                Json::Object(m) => m.clone(),
1679                _ => Map::new(),
1680            };
1681            args.insert("choice".into(), json!(index));
1682            args.insert("label".into(), json!(option.label));
1683            args.insert(c.value_key.clone(), option.value.clone());
1684            Some((c.command.clone(), Json::Object(args)))
1685        }
1686        (_, a) => return Err(format!("{a:?} does not answer this dialog")),
1687    })
1688}
1689
1690/// Refuses an answer that would run, for anyone but the user, a command
1691/// not offered to agents (`CommandSpec::no_agent`): said on the journal
1692/// (`dialog.answer.refused`, from the caller) and as the error.
1693fn refuse_unoffered(
1694    app: &AppHandle,
1695    open: &Open,
1696    answer: &Answer,
1697    origin: &Origin,
1698) -> Result<(), String> {
1699    if *origin == Origin::User {
1700        return Ok(());
1701    }
1702    let Some((command, _)) = target(open, answer)? else {
1703        return Ok(());
1704    };
1705    let offered = app
1706        .commands()
1707        .iter()
1708        .any(|(s, _)| s.id == command && s.agent);
1709    if offered {
1710        return Ok(());
1711    }
1712    let reason = format!(
1713        "accepting `{}` runs `{command}`, which is not offered to agents; only the user may",
1714        open.dialog.title()
1715    );
1716    app.publish(
1717        &source_of(origin),
1718        None,
1719        "dialog.answer.refused",
1720        json!({
1721            "id": open.id,
1722            "title": open.dialog.title(),
1723            "answer": answer,
1724            "command": command,
1725            "reason": reason,
1726        }),
1727    );
1728    Err(reason)
1729}
1730
1731/// Applies an answer to the shown dialog: runs its command if accepted,
1732/// as `origin`; refused when that command is not offered to agents and
1733/// `origin` is not the user.
1734fn apply(
1735    app: &AppHandle,
1736    d: &Dialogs,
1737    id: u64,
1738    answer: Answer,
1739    origin: Origin,
1740) -> Result<(), String> {
1741    let open = lock(&d.0)
1742        .queue
1743        .iter()
1744        .find(|o| o.id == id)
1745        .cloned()
1746        .ok_or("no dialog is open")?;
1747    refuse_unoffered(app, &open, &answer, &origin)?;
1748    let run = target(&open, &answer)?;
1749    if let Dialog::Custom(c) = &open.dialog {
1750        app.local::<Bodies>().0.borrow_mut().remove(&open.id);
1751        if let Some(needs) = &c.needs {
1752            app.unmount(&needs.id, crate::mounts::CUSTOM_DIALOG);
1753        }
1754    }
1755    {
1756        let mut s = lock(&d.0);
1757        s.queue.retain(|o| o.id != id);
1758        if s.answered.len() == ANSWERED {
1759            s.answered.pop_front();
1760        }
1761        s.answered.push_back((
1762            open.dialog.title().to_string(),
1763            answer.clone(),
1764            origin.clone(),
1765        ));
1766    }
1767    let source = source_of(&origin);
1768    app.publish(
1769        &source,
1770        None,
1771        "dialog.answered",
1772        json!({ "title": open.dialog.title(), "answer": answer }),
1773    );
1774    match (&open.dialog, &run) {
1775        (_, None) if answer == Answer::Cancel => app.publish(
1776            &source,
1777            None,
1778            "dialog.cancelled",
1779            json!({ "id": open.id, "title": open.dialog.title() }),
1780        ),
1781        (Dialog::Choose(c), Some((_, args))) => app.publish(
1782            &source,
1783            None,
1784            "dialog.chosen",
1785            json!({
1786                "id": open.id,
1787                "title": c.title,
1788                "index": args["choice"],
1789                "label": args["label"],
1790                "value": args[c.value_key.as_str()],
1791            }),
1792        ),
1793        _ => {}
1794    }
1795    if open.on_bus {
1796        let reason = if origin == Origin::User {
1797            Reason::User
1798        } else {
1799            Reason::Command
1800        };
1801        app.request_popup_close(WindowRequest::new(
1802            open.popup(),
1803            WindowKind::Popup,
1804            open.owner(),
1805            reason,
1806        ));
1807    }
1808    if let Some((command, args)) = run {
1809        app.run_as(command, args, origin);
1810    }
1811    Ok(())
1812}
1813
1814/// The command a dialog runs when accepted, if any.
1815fn command_of(dialog: &Dialog) -> Option<&CommandId> {
1816    match dialog {
1817        Dialog::Confirm(c) => Some(&c.command),
1818        Dialog::Form(f) => Some(&f.command),
1819        Dialog::Choose(c) => Some(&c.command),
1820        Dialog::Custom(c) => c.command.as_ref(),
1821        Dialog::Info(_) => None,
1822    }
1823}
1824
1825/// A plugin went (ADR 0028): the dialogs open on one of its commands, and
1826/// the custom ones it opened, are cancelled at once, `dialog.cancelled`
1827/// saying why. No hook may keep them: their owner is gone. Returns how
1828/// many.
1829pub(crate) fn owner_gone(
1830    app: &AppHandle,
1831    plugin: &PluginId,
1832    owner: &OwnerId,
1833    commands: &[CommandId],
1834) -> usize {
1835    let Some(d) = app.service(&DIALOGS) else {
1836        return 0;
1837    };
1838    let gone: Vec<Open> = {
1839        let mut s = lock(&d.0);
1840        let (gone, kept): (VecDeque<Open>, VecDeque<Open>) =
1841            std::mem::take(&mut s.queue).into_iter().partition(|o| {
1842                command_of(&o.dialog).is_some_and(|c| commands.contains(c))
1843                    || (matches!(o.dialog, Dialog::Custom(_)) && o.opener.as_ref() == Some(owner))
1844            });
1845        s.queue = kept;
1846        gone.into()
1847    };
1848    let reason = format!("its plugin `{plugin}` is disconnected");
1849    let ctx = app.egui();
1850    for open in &gone {
1851        // Its overlay leaves the stack now: the next dialog comes up as
1852        // the top one, not under a modal no one draws.
1853        overlay::close(&ctx, overlay_id(open.id));
1854        if let Dialog::Custom(c) = &open.dialog {
1855            app.local::<Bodies>().0.borrow_mut().remove(&open.id);
1856            if let Some(needs) = &c.needs {
1857                app.unmount(&needs.id, crate::mounts::CUSTOM_DIALOG);
1858            }
1859        }
1860        {
1861            let mut s = lock(&d.0);
1862            if s.answered.len() == ANSWERED {
1863                s.answered.pop_front();
1864            }
1865            s.answered.push_back((
1866                open.dialog.title().to_string(),
1867                Answer::Cancel,
1868                Origin::User,
1869            ));
1870        }
1871        log::info!(
1872            target: "egui_pop",
1873            "dialog `{}` cancelled: {reason}",
1874            open.dialog.title()
1875        );
1876        app.publish(
1877            "egui_pop",
1878            None,
1879            "dialog.cancelled",
1880            json!({ "id": open.id, "title": open.dialog.title(), "reason": reason }),
1881        );
1882        if open.on_bus {
1883            app.request_popup_close(WindowRequest::new(
1884                open.popup(),
1885                WindowKind::Popup,
1886                open.owner(),
1887                Reason::OwnerGone,
1888            ));
1889        }
1890    }
1891    if !gone.is_empty() {
1892        app.egui().request_repaint();
1893    }
1894    gone.len()
1895}
1896
1897/// Answers the shown dialog through the [`STEP_ANSWER`] step: hooks may
1898/// stop the answer (the reason is the error) or change it.
1899fn answer_step(
1900    app: &AppHandle,
1901    d: &Dialogs,
1902    id: u64,
1903    answer: Answer,
1904    origin: Origin,
1905) -> Result<(), String> {
1906    let args = json!({
1907        "dialog": d.describe_one(id),
1908        "answer": answer,
1909        "origin": source_of(&origin),
1910    });
1911    let out = app.step(&STEP_ANSWER, args, |app, args| {
1912        let answer = Answer::from_json(&args["answer"])?;
1913        apply(app, d, id, answer, origin.clone()).map(|()| Json::Null)
1914    });
1915    match out {
1916        Outcome::Done(r) => r.map(|_| ()),
1917        Outcome::Vetoed { reason, .. } => Err(reason),
1918    }
1919}
1920
1921/// Registers the dialogs' listeners on the bus, replacing those of an
1922/// earlier connection: [`POPUP_LISTENER`] on `pop.popup.close`,
1923/// [`CANCEL_ON_CLOSE`] on `pop.window.close`.
1924fn listen(app: &AppHandle) {
1925    let bus = app.bus();
1926    bus.unlisten(&PopupClose::ID, POPUP_LISTENER);
1927    bus.unlisten(&WindowClose::ID, CANCEL_ON_CLOSE);
1928    let mine = || ListenOpts::new().owner(PLUGIN.as_str());
1929    let listened = [
1930        bus.listen::<PopupClose>(POPUP_LISTENER, mine().before(REGISTRY), |req, did| {
1931            let Some(id) = req
1932                .window
1933                .strip_prefix(POPUP_PREFIX)
1934                .and_then(|n| n.parse::<u64>().ok())
1935            else {
1936                return Ok(());
1937            };
1938            let Some(app) = crate::bus::asking() else {
1939                return Ok(());
1940            };
1941            let Some(d) = app.service(&DIALOGS) else {
1942                return Ok(());
1943            };
1944            // Its popup closes now: the cancel asks no second one.
1945            let title = {
1946                let mut s = lock(&d.0);
1947                s.queue.iter_mut().find(|o| o.id == id).map(|o| {
1948                    o.on_bus = false;
1949                    o.dialog.title().to_string()
1950                })
1951            };
1952            let Some(title) = title else {
1953                return Ok(());
1954            };
1955            overlay::close(&app.egui(), overlay_id(id));
1956            apply(&app, &d, id, Answer::Cancel, Origin::User)?;
1957            did.push(format!(
1958                "{POPUP_LISTENER}: `{title}` cancelled ({})",
1959                req.reason.as_str()
1960            ));
1961            Ok(())
1962        }),
1963        bus.listen::<WindowClose>(
1964            CANCEL_ON_CLOSE,
1965            mine().after(CHILDREN).before(FOCUS),
1966            |req, did| {
1967                if req.kind != WindowKind::App {
1968                    return Ok(());
1969                }
1970                let Some(app) = crate::bus::asking() else {
1971                    return Ok(());
1972                };
1973                let (Some(d), Some(window)) = (
1974                    app.service(&DIALOGS),
1975                    app.window_viewport(&WindowId::new(&req.window)),
1976                ) else {
1977                    return Ok(());
1978                };
1979                let waiting: Vec<u64> = lock(&d.0)
1980                    .queue
1981                    .iter()
1982                    .filter(|o| o.group == Some(window))
1983                    .map(|o| o.id)
1984                    .collect();
1985                for id in &waiting {
1986                    apply(&app, &d, *id, Answer::Cancel, Origin::User)?;
1987                }
1988                if !waiting.is_empty() {
1989                    did.push(format!(
1990                        "{CANCEL_ON_CLOSE}: {} waiting dialogs cancelled",
1991                        waiting.len()
1992                    ));
1993                }
1994                Ok(())
1995            },
1996        ),
1997    ];
1998    for l in listened {
1999        if let Err(e) = l {
2000            log::error!(target: "egui_pop", "{e}");
2001        }
2002    }
2003}
2004
2005/// Draws the dialog shown, and applies the answers given meanwhile.
2006fn show(ui: &mut Ui, app: &AppHandle) {
2007    let Some(d) = app.service(&DIALOGS) else {
2008        return;
2009    };
2010    let ctx = ui.ctx().clone();
2011    let here = ctx.viewport_id();
2012    let group = app.window_group(here);
2013    // Each dialog's group: the one it was opened in, while that window is
2014    // open (the main window's otherwise); the active one's when unknown.
2015    {
2016        let active = app.window_group(app.active_window());
2017        let mut s = lock(&d.0);
2018        for o in s.queue.iter_mut() {
2019            let g = app.window_group(o.group.unwrap_or(active));
2020            if o.group != Some(g) {
2021                o.group = Some(g);
2022                o.window = None;
2023            }
2024        }
2025    }
2026    let given: Vec<(u64, Answer, Origin)> = std::mem::take(&mut lock(&d.0).given);
2027    for (id, answer, origin) in given {
2028        if d.is_open(id)
2029            && let Err(e) = answer_step(app, &d, id, answer, origin)
2030            && let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == id)
2031        {
2032            o.error = Some(e);
2033        }
2034    }
2035    // Shown over the window of its group it was opened from (the active
2036    // one when it came up), or the main window once that one is closed;
2037    // drawn in that window's pass only, the others of the group blocked
2038    // meanwhile.
2039    let Some((window, shown_id)) = ({
2040        let mut s = lock(&d.0);
2041        shown_at(&s, Some(group)).map(|i| {
2042            let o = &mut s.queue[i];
2043            (*o.window.get_or_insert_with(|| app.shown_in(group)), o.id)
2044        })
2045    }) else {
2046        return;
2047    };
2048    if app.still_open(window) != here {
2049        return;
2050    }
2051    let Some(mut open_dialog) = lock(&d.0).queue.iter().find(|o| o.id == shown_id).cloned() else {
2052        return;
2053    };
2054    // A dialog a question was put in front of leaves the stack before the
2055    // question enters it: it would close what was opened above it once it
2056    // stopped being shown. It comes back with the answer.
2057    for under in lock(&d.0)
2058        .queue
2059        .iter()
2060        .filter(|o| o.group == Some(group) && o.id != shown_id)
2061        .map(|o| o.id)
2062        .collect::<Vec<_>>()
2063    {
2064        overlay::close(&ctx, overlay_id(under));
2065    }
2066    if !open_dialog.focused {
2067        // It comes up: hooks may stop it (it is cancelled).
2068        let out = app.step(&STEP_SHOW, d.describe_one(shown_id), |_, _| Ok(Json::Null));
2069        if out.vetoed().is_some() {
2070            if let Err(e) = apply(app, &d, shown_id, Answer::Cancel, Origin::User) {
2071                log::warn!(target: "egui_pop", "dialog: {e}");
2072            }
2073            return;
2074        }
2075        // It is on screen: a popup of its group's window.
2076        if !open_dialog.on_bus {
2077            let req = WindowRequest::new(
2078                open_dialog.popup(),
2079                WindowKind::Popup,
2080                open_dialog.owner(),
2081                Reason::Command,
2082            )
2083            .parent(app.registry_window_of(group));
2084            app.overlay_on_its_own(overlay_id(open_dialog.id));
2085            if app.request_popup_open(req) {
2086                open_dialog.on_bus = true;
2087                if let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == shown_id) {
2088                    o.on_bus = true;
2089                }
2090            }
2091        }
2092        // Where it was left, when it keeps its place; centred otherwise.
2093        if let Some(key) = &open_dialog.remember {
2094            open_dialog.offset = remembered(app, key).unwrap_or(Vec2::ZERO);
2095        }
2096    }
2097    let filter = open_dialog.filter.clone();
2098    let closable = open_dialog.closable || setting(app, SETTING_CLOSABLE);
2099    let movable = open_dialog.movable || setting(app, SETTING_MOVABLE);
2100    let id = overlay_id(open_dialog.id);
2101    if movable {
2102        // Inside the window, again when the window was resized.
2103        open_dialog.offset = clamp(&ctx, id, open_dialog.offset);
2104        if let Some(start) = open_dialog.moving {
2105            move_by_keys(app, &ctx, &mut open_dialog, start);
2106        }
2107    } else {
2108        open_dialog.offset = Vec2::ZERO;
2109        open_dialog.moving = None;
2110        open_dialog.drag_from = None;
2111    }
2112    // The dim fades while the dialog is dragged.
2113    let dragged = ctx.animate_bool_with_time(
2114        id.with("dragged"),
2115        open_dialog.drag_from.is_some(),
2116        Tokens::of(&ctx).motion_duration,
2117    );
2118    let dim = match open_dialog.backdrop {
2119        Backdrop::Dim => 1.0 - (1.0 - DRAG_DIM) * dragged,
2120        Backdrop::Clear => 0.0,
2121    };
2122    let mut spec = OverlaySpec::new(
2123        ("egui_pop.dialog", open_dialog.id),
2124        open_dialog.dialog.title(),
2125        Kind::Modal,
2126    )
2127    .offset(open_dialog.offset)
2128    .dim(dim);
2129    debug_assert_eq!(spec.id, id);
2130    let mut open = true;
2131    let mut answer: Option<Answer> = None;
2132    // The ✕ is shown only where Escape works.
2133    let closable = closable && spec.dismiss_on_escape;
2134    if let Dialog::Custom(c) = &open_dialog.dialog {
2135        spec = spec.width(
2136            c.body_size(ctx.content_rect().size())
2137                .x
2138                .min(overlay::modal_max_size(&ctx).x),
2139        );
2140        if c.claims_key(ClaimKey::Escape) {
2141            // The body sees Escape first; the dialog cancels after it.
2142            spec = spec.keep_on_escape();
2143        }
2144    }
2145    if open_dialog.moving.is_some() {
2146        // Escape puts the dialog back instead of closing it.
2147        spec = spec.keep_on_escape();
2148    }
2149    let mut closed = false;
2150    let mut band = Band::default();
2151    overlay::show(&ctx, &spec, &mut open, None, |ui| {
2152        let header = Header {
2153            closable,
2154            movable,
2155            closed: &mut closed,
2156            band: &mut band,
2157        };
2158        answer = body(ui, app, &mut open_dialog, header);
2159    });
2160    if movable {
2161        drag(app, &ctx, id, &mut open_dialog, &band);
2162    }
2163    // The ✕ is Escape: the overlay dismissed, whatever else the pass
2164    // said (Enter on the ✕ included), answered as a cancel below.
2165    if closed {
2166        open = false;
2167        answer = None;
2168    }
2169    if !open && answer.is_none() {
2170        answer = Some(Answer::Cancel);
2171    }
2172    if open_dialog.filter != filter
2173        && let Dialog::Choose(c) = &open_dialog.dialog
2174    {
2175        app.publish(
2176            "user",
2177            None,
2178            "dialog.filtered",
2179            json!({
2180                "id": open_dialog.id,
2181                "filter": open_dialog.filter,
2182                "shown": c.visible(&open_dialog.filter).len(),
2183            }),
2184        );
2185    }
2186    browse(app, &mut open_dialog);
2187    match answer {
2188        Some(a) => {
2189            if let Err(e) = answer_step(app, &d, shown_id, a, Origin::User) {
2190                open_dialog.error = Some(e);
2191                if let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == shown_id) {
2192                    *o = open_dialog;
2193                }
2194            } else {
2195                overlay::close(&ctx, spec.id);
2196            }
2197        }
2198        None => {
2199            if let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == shown_id) {
2200                *o = open_dialog;
2201            }
2202        }
2203    }
2204}
2205
2206/// One row of a choice: a selectable row, wrapped, of the same size
2207/// whether it is at rest, hovered or highlighted (as every row is).
2208fn choice_row(ui: &mut Ui, selected: bool, text: egui::WidgetText) -> egui::Response {
2209    ui.add(widgets::SelectableRow::new(selected, text).wrap())
2210}
2211
2212/// A custom dialog's state between passes, as its body left it.
2213struct CustomState<'a> {
2214    id: u64,
2215    values: &'a mut Map<String, Json>,
2216    ready: &'a mut bool,
2217    describe: &'a mut Json,
2218}
2219
2220/// A custom dialog's body, its footer and its keys; its answer when
2221/// given.
2222fn custom_body(
2223    ui: &mut Ui,
2224    app: &AppHandle,
2225    c: &Custom,
2226    state: CustomState<'_>,
2227    first: bool,
2228) -> Option<Answer> {
2229    let CustomState {
2230        id,
2231        values,
2232        ready,
2233        describe,
2234    } = state;
2235    let (enter, ctrl_enter) = ui.input(|i| {
2236        let pressed = i.key_pressed(Key::Enter);
2237        let command = i.modifiers.command || i.modifiers.ctrl;
2238        (pressed && !command && !i.modifiers.alt, pressed && command)
2239    });
2240    // The body's size, held to what the window leaves it once the frame,
2241    // the header above and the footer below have theirs: the footer stays
2242    // whole in the window.
2243    let size = {
2244        let t = Tokens::of(ui.ctx());
2245        let spacing = ui.spacing().item_spacing.y;
2246        let above = ui.cursor().min.y - ui.min_rect().top();
2247        let below = t.space.m + ui.spacing().interact_size.y + 2.0 * spacing;
2248        let room = overlay::modal_max_size(ui.ctx()) - egui::vec2(0.0, above + below);
2249        c.body_size(ui.ctx().content_rect().size())
2250            .min(room)
2251            .max(Vec2::ZERO)
2252    };
2253    let mut pass = CustomPass {
2254        values: std::mem::take(values),
2255        ready: *ready,
2256        describe: std::mem::take(describe),
2257        escape: false,
2258        answer: None,
2259    };
2260    let bodies = app.local::<Bodies>();
2261    let taken = bodies.0.borrow_mut().remove(&id);
2262    match taken {
2263        Some(mut draw) => {
2264            ui.allocate_ui_with_layout(size, egui::Layout::top_down(egui::Align::Min), |ui| {
2265                ui.set_min_size(size);
2266                ui.set_max_size(size);
2267                egui_pop_core::focus::scope(ui, "dialog", &[], |ui| {
2268                    egui_pop_core::fault::boundary(
2269                        ui,
2270                        ("egui_pop.dialog.body", id),
2271                        &c.title,
2272                        |ui| draw(ui, app, &mut pass),
2273                    );
2274                });
2275            });
2276            bodies.0.borrow_mut().insert(id, draw);
2277        }
2278        None => {
2279            log::warn!(target: "egui_pop", "dialog `{}`: its body is gone", c.title);
2280            ui.allocate_space(size);
2281        }
2282    }
2283    // Escape after the body: the body's when it claims Escape and has
2284    // something to cancel, the dialog's otherwise (without a claim, the
2285    // overlay closed the dialog on Escape before the body saw it).
2286    let escape =
2287        c.claims_key(ClaimKey::Escape) && !pass.escape && ui.input(|i| i.key_pressed(Key::Escape));
2288    let mut answer = pass.answer.take();
2289    *values = std::mem::take(&mut pass.values);
2290    *ready = pass.ready;
2291    *describe = std::mem::take(&mut pass.describe);
2292    // A body claiming Enter keeps the focus: a focused button would take
2293    // Enter from it.
2294    let focus_button = first && !c.claims_key(ClaimKey::Enter);
2295    if !c.footer {
2296        // The body's own buttons answered, or will.
2297    } else if c.command.is_none() && c.verb.is_empty() {
2298        let t = Tokens::of(ui.ctx());
2299        ui.add_space(t.space.m);
2300        let close = ui.button(strings::tr(ui.ctx(), &CLOSE));
2301        if focus_button {
2302            close.request_focus();
2303        }
2304        if close.clicked() {
2305            answer = Some(Answer::Accept {
2306                values: values.clone(),
2307            });
2308        }
2309    } else if let Some(a) = footer(
2310        ui,
2311        Buttons::two(ui.ctx(), &c.verb, c.danger),
2312        focus_button,
2313        None,
2314    ) {
2315        answer = Some(match a {
2316            Answer::Accept { .. } => Answer::Accept {
2317                values: values.clone(),
2318            },
2319            other => other,
2320        });
2321    }
2322    // Enter accepts, unless the body claims it (Ctrl+Enter does then) or
2323    // a text input owns the keyboard (a text field, or an open typed
2324    // entry, which commits on Enter); no key accepts a danger.
2325    let by_key = if !c.footer {
2326        false
2327    } else if c.claims_key(ClaimKey::Enter) {
2328        ctrl_enter
2329    } else {
2330        ctrl_enter || (enter && !egui_pop_core::focus::text_input_owns_keyboard(ui.ctx()))
2331    };
2332    if answer.is_none() && by_key && !c.danger && *ready {
2333        answer = Some(Answer::Accept {
2334            values: values.clone(),
2335        });
2336    }
2337    if answer.is_none() && escape {
2338        answer = Some(Answer::Cancel);
2339    }
2340    answer
2341}
2342
2343/// The values of a form's fields, by key.
2344fn values_of(fields: &[Field]) -> Map<String, Json> {
2345    fields
2346        .iter()
2347        .filter(|f| !f.descriptor.note)
2348        .map(|f| (f.key.clone(), f.value.to_json()))
2349        .collect()
2350}
2351
2352/// What a dialog's head shows, and what happened to it.
2353struct Header<'a> {
2354    closable: bool,
2355    movable: bool,
2356    /// Its ✕ was pressed.
2357    closed: &'a mut bool,
2358    /// Its header band (when movable).
2359    band: &'a mut Band,
2360}
2361
2362/// A dialog's content and footer; its answer when given.
2363fn body(ui: &mut Ui, app: &AppHandle, o: &mut Open, header: Header<'_>) -> Option<Answer> {
2364    let t = Tokens::of(ui.ctx());
2365    let first = !o.focused;
2366    o.focused = true;
2367    let title = o.dialog.title().to_string();
2368    let Header {
2369        closable,
2370        movable,
2371        closed,
2372        band,
2373    } = header;
2374    let heading = if movable {
2375        header_band(ui, &title, closable, closed, band)
2376    } else {
2377        title_row(ui, &title, closable, closed)
2378    };
2379    ui.add_space(t.space.s);
2380    let mut answer = None;
2381    let enter = ui.input(|i| i.key_pressed(Key::Enter));
2382    match &mut o.dialog {
2383        Dialog::Confirm(c) => {
2384            if !c.detail.is_empty() {
2385                ui.label(&c.detail);
2386            }
2387            if c.details.shown(false) {
2388                details_section(ui, o.id, &c.details);
2389            }
2390            let (verb, danger) = (c.verb.clone(), c.danger);
2391            let buttons = Buttons {
2392                verb: &verb,
2393                danger,
2394                secondary: c.secondary.as_ref().map(|s| (s.verb.as_str(), s.danger)),
2395                cancel: &c.cancel,
2396                order: c.order.unwrap_or_else(|| ButtonOrder::of(ui.ctx())),
2397            };
2398            let copy = c.copy.then(|| (c.copy_text(), &mut o.copied_at));
2399            if let Some(a) = footer(ui, buttons, first, copy) {
2400                answer = Some(a);
2401            } else if enter && !danger && !copied_now(ui, o.copied_at) {
2402                answer = Some(Answer::Accept { values: Map::new() });
2403            }
2404        }
2405        Dialog::Info(i) => {
2406            ui.label(&i.text);
2407            if i.details.shown(i.error) {
2408                details_section(ui, o.id, &i.details);
2409            }
2410            ui.add_space(t.space.m);
2411            let copy = i.copy.then(|| (i.copy_text(), &mut o.copied_at));
2412            let close = ui
2413                .with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
2414                    let close = ui.button(strings::tr(ui.ctx(), &CLOSE));
2415                    if let Some((text, at)) = copy {
2416                        copy_corner(ui, &text, at);
2417                    }
2418                    close
2419                })
2420                .inner;
2421            if first {
2422                close.request_focus();
2423            }
2424            // Enter on the Copy button copies, it does not close.
2425            if close.clicked() || (enter && !copied_now(ui, o.copied_at)) {
2426                answer = Some(Answer::Accept { values: Map::new() });
2427            }
2428        }
2429        Dialog::Choose(c) => {
2430            if !c.detail.is_empty() {
2431                ui.label(&c.detail);
2432            }
2433            ui.add_space(t.space.s);
2434            // Arrows move the highlight, typing filters, Enter chooses.
2435            let (down, up) = ui.input_mut(|i| {
2436                (
2437                    i.consume_key(egui::Modifiers::NONE, Key::ArrowDown),
2438                    i.consume_key(egui::Modifiers::NONE, Key::ArrowUp),
2439                )
2440            });
2441            let field = ui
2442                .add(
2443                    egui::TextEdit::singleline(&mut o.filter)
2444                        .hint_text(strings::tr(ui.ctx(), &txt::DIALOG_FILTER))
2445                        .desired_width(f32::INFINITY),
2446                )
2447                .labelled_by(heading.id);
2448            if first {
2449                field.request_focus();
2450            }
2451            let shown = c.visible(&o.filter);
2452            if field.changed() {
2453                o.highlight = 0;
2454            }
2455            if down {
2456                o.highlight = (o.highlight + 1).min(shown.len().saturating_sub(1));
2457            }
2458            if up {
2459                o.highlight = o.highlight.saturating_sub(1);
2460            }
2461            ui.add_space(t.space.s);
2462            ui.scroll_area(
2463                egui::ScrollArea::vertical()
2464                    .id_salt("egui_pop.choose")
2465                    .max_height(320.0),
2466                |ui| {
2467                    // Full-width rows, their text left-aligned and wrapped.
2468                    let rows = egui::Layout::top_down_justified(egui::Align::Min);
2469                    ui.with_layout(rows, |ui| {
2470                        for (n, &i) in shown.iter().enumerate() {
2471                            let option = &c.options[i];
2472                            let text = if option.hint.is_empty() {
2473                                egui::WidgetText::from(option.label.as_str())
2474                            } else {
2475                                egui::WidgetText::from(format!(
2476                                    "{}  ·  {}",
2477                                    option.label, option.hint
2478                                ))
2479                            };
2480                            let b = choice_row(ui, n == o.highlight, text);
2481                            if n == o.highlight && (down || up) {
2482                                b.scroll_to_me(None);
2483                            }
2484                            if b.clicked() {
2485                                answer = Some(Answer::Choose { index: i });
2486                            }
2487                        }
2488                    });
2489                    if shown.is_empty() {
2490                        ui.weak(strings::tr(ui.ctx(), &txt::NOTHING_MATCHES));
2491                    }
2492                },
2493            );
2494            if enter && let Some(&i) = shown.get(o.highlight) {
2495                answer = Some(Answer::Choose { index: i });
2496            }
2497            ui.add_space(t.space.m);
2498            if ui.button(strings::tr(ui.ctx(), &CANCEL)).clicked() {
2499                answer = Some(Answer::Cancel);
2500            }
2501        }
2502        Dialog::Custom(c) => {
2503            let state = CustomState {
2504                id: o.id,
2505                values: &mut o.values,
2506                ready: &mut o.ready,
2507                describe: &mut o.body,
2508            };
2509            answer = custom_body(ui, app, c, state, first);
2510        }
2511        Dialog::Form(f) => {
2512            let browse = &mut o.browse;
2513            egui::Grid::new(("egui_pop.form", &f.title))
2514                .num_columns(2)
2515                .spacing([t.space.m, t.space.s])
2516                .show(ui, |ui| {
2517                    for (n, field) in f.fields.iter_mut().enumerate() {
2518                        // A note: its words, nothing to edit.
2519                        if field.descriptor.note {
2520                            ui.label("");
2521                            ui.weak(&field.descriptor.label);
2522                            ui.end_row();
2523                            continue;
2524                        }
2525                        let label = ui.label(&field.descriptor.label);
2526                        let r = edit_field(ui, field, browse, &f.command, label.id);
2527                        if first && n == 0 {
2528                            r.request_focus();
2529                        }
2530                        ui.end_row();
2531                    }
2532                });
2533            if let Some((key, picker)) = o.picking.as_mut()
2534                && let Some(field) = f.fields.iter_mut().find(|x| x.key == *key)
2535            {
2536                ui.separator();
2537                match picker.show(
2538                    ui,
2539                    &files::Places {
2540                        home: files::home(),
2541                        ..Default::default()
2542                    },
2543                ) {
2544                    Some(PickerAnswer::Chosen(p)) => {
2545                        if let Some(p) = p.first() {
2546                            field.value = Value::Text(p.display().to_string());
2547                        }
2548                        o.picking = None;
2549                    }
2550                    Some(PickerAnswer::Cancel) => o.picking = None,
2551                    // This picker chooses an existing file or a folder:
2552                    // it has no question to ask, a folder it makes has no
2553                    // one to tell, and it lists no bookmarks.
2554                    Some(_) | None => {}
2555                }
2556            }
2557            // The file chooser's in-app picker, inside the dialog.
2558            if let Some(id) = o.choosing.as_ref().map(|(_, id, _)| *id)
2559                && let Some(files) = app.service(&FILES)
2560            {
2561                ui.separator();
2562                files.show_inline(ui, app, id);
2563            }
2564            let verb = f.verb.clone();
2565            if let Some(a) = footer(ui, Buttons::two(ui.ctx(), &verb, false), false, None) {
2566                answer = Some(match a {
2567                    Answer::Accept { .. } => Answer::Accept {
2568                        values: values_of(&f.fields),
2569                    },
2570                    other => other,
2571                });
2572            } else if enter
2573                && !ui.ctx().text_edit_focused()
2574                && o.picking.is_none()
2575                && o.choosing.is_none()
2576            {
2577                answer = Some(Answer::Accept {
2578                    values: values_of(&f.fields),
2579                });
2580            }
2581        }
2582    }
2583    if let Some(e) = &o.error {
2584        ui.colored_label(t.status.danger, e);
2585    }
2586    paint_band(ui, band);
2587    answer
2588}
2589
2590/// Where a dialog's header band sits: reaching the dialog's edges, with
2591/// the dialog header's room below its title.
2592fn band_style(k: &Kit) -> band::BandStyle {
2593    band::BandStyle {
2594        padding: k.dialog.data.padding_x,
2595        gap: k.dialog_header.data.padding_y,
2596    }
2597}
2598
2599/// The header band: the title and the ✕ (when closable) on the kit's
2600/// `header-band`, above its line, under the move cursor
2601/// ([`egui_pop_core::band`]).
2602fn header_band(
2603    ui: &mut Ui,
2604    title: &str,
2605    closable: bool,
2606    closed: &mut bool,
2607    out: &mut Band,
2608) -> Response {
2609    let kit = Kit::of(ui.ctx());
2610    let side = close_side(ui);
2611    let (heading, b) = band::begin(ui, &band_style(&kit), |ui, state| {
2612        ui.horizontal_top(|ui| {
2613            let room = if closable {
2614                (ui.available_width() - side - ui.spacing().item_spacing.x).max(0.0)
2615            } else {
2616                ui.available_width()
2617            };
2618            // Not selectable: a press on the title drags the dialog.
2619            let heading = ui
2620                .allocate_ui(egui::vec2(room, side), |ui| {
2621                    ui.add(
2622                        egui::Label::new(
2623                            egui::RichText::new(title)
2624                                .heading()
2625                                .color(kit.dialog_header.style(state).text),
2626                        )
2627                        .wrap()
2628                        .selectable(false),
2629                    )
2630                })
2631                .inner;
2632            if closable {
2633                ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
2634                    if close_button(ui, side).clicked() {
2635                        *closed = true;
2636                    }
2637                });
2638            }
2639            heading
2640        })
2641        .inner
2642    });
2643    *out = Band(Some(b));
2644    heading
2645}
2646
2647/// Paints the header band, when there is one.
2648fn paint_band(ui: &Ui, b: &Band) {
2649    if let Some(b) = &b.0 {
2650        band::paint(ui, b, &band_style(&Kit::of(ui.ctx())));
2651    }
2652}
2653
2654/// A movable dialog's header band as laid out this pass.
2655#[derive(Debug, Default)]
2656struct Band(Option<band::Band>);
2657
2658/// Whether a boolean setting is on.
2659fn setting(app: &AppHandle, id: SettingId) -> bool {
2660    lock(&app.store())
2661        .get(&format!("settings/{id}"))
2662        .and_then(|e| e.value.as_bool())
2663        .unwrap_or(false)
2664}
2665
2666/// An offset keeping the dialog inside the window (its size is the last
2667/// pass's; unchanged before it was drawn).
2668fn clamp(ctx: &egui::Context, id: egui::Id, offset: Vec2) -> Vec2 {
2669    let Some(rect) = overlay::rect(ctx, id) else {
2670        return offset;
2671    };
2672    let room = ((ctx.content_rect().size() - rect.size()) / 2.0).max(Vec2::ZERO);
2673    offset.clamp(-room, room)
2674}
2675
2676/// What the pointer did to the band: a drag moves the dialog freely
2677/// (clamped), the drop goes through the move step; a double click
2678/// centres it again.
2679fn drag(app: &AppHandle, ctx: &egui::Context, id: egui::Id, o: &mut Open, band: &Band) {
2680    let Some(band) = &band.0 else {
2681        return;
2682    };
2683    if band.double_clicked {
2684        o.drag_from = None;
2685        o.moving = None;
2686        let from = o.offset;
2687        move_to(app, o, "recentre", from, Vec2::ZERO);
2688        return;
2689    }
2690    if band.dragging && o.drag_from.is_none() {
2691        o.drag_from = Some(o.offset);
2692        o.moving = None;
2693    }
2694    if band.dragging && band.delta != Vec2::ZERO {
2695        o.offset = clamp(ctx, id, o.offset + band.delta);
2696        ctx.request_repaint();
2697    }
2698    // Dropped (or the drag lost): the move step decides.
2699    if !band.dragging
2700        && let Some(from) = o.drag_from.take()
2701    {
2702        let to = o.offset;
2703        move_to(app, o, "drag", from, to);
2704        ctx.request_repaint();
2705    }
2706}
2707
2708/// Moving by the keys: an arrow moves it one step (Shift: bigger ones),
2709/// Enter keeps the place, Escape puts it back where it was.
2710fn move_by_keys(app: &AppHandle, ctx: &egui::Context, o: &mut Open, start: Vec2) {
2711    let step = Tokens::of(ctx).space.m;
2712    let (by, enter, escape) = ctx.input_mut(|i| {
2713        let mut by = Vec2::ZERO;
2714        for (key, dir) in [
2715            (Key::ArrowLeft, egui::vec2(-1.0, 0.0)),
2716            (Key::ArrowRight, egui::vec2(1.0, 0.0)),
2717            (Key::ArrowUp, egui::vec2(0.0, -1.0)),
2718            (Key::ArrowDown, egui::vec2(0.0, 1.0)),
2719        ] {
2720            // Shift first: a plain match ignores an extra Shift.
2721            while i.consume_key(Modifiers::SHIFT, key) {
2722                by += dir * step * BIG_STEP;
2723            }
2724            while i.consume_key(Modifiers::NONE, key) {
2725                by += dir * step;
2726            }
2727        }
2728        (
2729            by,
2730            i.consume_key(Modifiers::NONE, Key::Enter),
2731            i.consume_key(Modifiers::NONE, Key::Escape),
2732        )
2733    });
2734    let id = overlay_id(o.id);
2735    if by != Vec2::ZERO {
2736        let from = o.offset;
2737        let to = clamp(ctx, id, from + by);
2738        move_to(app, o, "keys", from, to);
2739    }
2740    if escape {
2741        let from = o.offset;
2742        move_to(app, o, "keys", from, start);
2743        o.moving = None;
2744    } else if enter {
2745        o.moving = None;
2746    }
2747}
2748
2749/// Moves the dialog through the [`STEP_MOVE`] step: a veto leaves it
2750/// where it was, a redirect places it elsewhere. Done, it is published
2751/// (`dialog.moved`) and its place kept when it keeps one.
2752fn move_to(app: &AppHandle, o: &mut Open, how: &str, from: Vec2, to: Vec2) {
2753    if from == to {
2754        o.offset = to;
2755        return;
2756    }
2757    let args = json!({
2758        "id": o.id,
2759        "title": o.dialog.title(),
2760        "key": o.remember,
2761        "how": how,
2762        "from": [from.x, from.y],
2763        "to": [to.x, to.y],
2764    });
2765    let out = app.step(&STEP_MOVE, args, |_, args| Ok(json!({ "to": args["to"] })));
2766    let placed = match out {
2767        Outcome::Done(Ok(result)) => vec2_of(&result["to"]),
2768        Outcome::Done(Err(e)) => {
2769            log::info!(target: "egui_pop", "dialog.move: {e}");
2770            None
2771        }
2772        Outcome::Vetoed { .. } => None,
2773    };
2774    let Some(at) = placed else {
2775        o.offset = from;
2776        return;
2777    };
2778    o.offset = at;
2779    app.publish(
2780        "user",
2781        None,
2782        "dialog.moved",
2783        json!({ "id": o.id, "title": o.dialog.title(), "how": how, "offset": [at.x, at.y] }),
2784    );
2785    if let Some(key) = &o.remember {
2786        remember(app, key, at);
2787    }
2788}
2789
2790/// `[x, y]` as a vector.
2791fn vec2_of(json: &Json) -> Option<Vec2> {
2792    let a = json.as_array()?;
2793    match a.as_slice() {
2794        [x, y] => Some(egui::vec2(x.as_f64()? as f32, y.as_f64()? as f32)),
2795        _ => None,
2796    }
2797}
2798
2799/// Where a dialog's place is kept, declared in the host's store (a value
2800/// saved before is picked up then).
2801fn position_path(app: &AppHandle, key: &str) -> Option<String> {
2802    let path = format!("ui/dialogs/{key}");
2803    let store = app.store();
2804    let mut s = lock(&store);
2805    if s.get(&path).is_none()
2806        && let Err(e) = s.declare(
2807            &OwnerId::from(&PLUGIN),
2808            &path,
2809            Descriptor::floats("Dialog position", 2, -1.0e6, 1.0e6, &[0.0, 0.0])
2810                .description("A dialog's offset from the window's centre, in points."),
2811        )
2812    {
2813        log::warn!(target: "egui_pop", "dialog position `{key}`: {e}");
2814        return None;
2815    }
2816    Some(path)
2817}
2818
2819/// The place kept for a dialog.
2820fn remembered(app: &AppHandle, key: &str) -> Option<Vec2> {
2821    let path = position_path(app, key)?;
2822    match &lock(&app.store()).get(&path)?.value {
2823        Value::Floats(v) if v.len() == 2 => Some(egui::vec2(v[0] as f32, v[1] as f32)),
2824        _ => None,
2825    }
2826}
2827
2828/// Keeps a dialog's place (no undo step).
2829fn remember(app: &AppHandle, key: &str, offset: Vec2) {
2830    let Some(path) = position_path(app, key) else {
2831        return;
2832    };
2833    let set = Set::new(
2834        &path,
2835        Change::To(Value::Floats(vec![
2836            f64::from(offset.x),
2837            f64::from(offset.y),
2838        ])),
2839        Origin::User,
2840    )
2841    .by(&OwnerId::FRAMEWORK)
2842    .untracked();
2843    if let Err(e) = lock(&app.store()).set(set) {
2844        log::warn!(target: "egui_pop", "dialog position `{key}`: {e:?}");
2845    }
2846}
2847
2848/// The title row: the title, and the ✕ at its right end when the dialog
2849/// is closable. No band behind it: a movable dialog has its header band
2850/// instead ([`header_band`]).
2851fn title_row(ui: &mut Ui, title: &str, closable: bool, closed: &mut bool) -> Response {
2852    let text = egui::RichText::new(title)
2853        .heading()
2854        .color(Kit::of(ui.ctx()).dialog_header.style(kit::State::REST).text);
2855    if !closable {
2856        return ui.label(text);
2857    }
2858    let side = close_side(ui);
2859    ui.horizontal_top(|ui| {
2860        // The title wraps before the ✕.
2861        let room = (ui.available_width() - side - ui.spacing().item_spacing.x).max(0.0);
2862        let heading = ui
2863            .allocate_ui(egui::vec2(room, side), |ui| {
2864                ui.add(egui::Label::new(text).wrap())
2865            })
2866            .inner;
2867        ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
2868            if close_button(ui, side).clicked() {
2869                *closed = true;
2870            }
2871        });
2872        heading
2873    })
2874    .inner
2875}
2876
2877/// The close button's side: a target of at least 24 points (WCAG 2.5.8),
2878/// as tall as a control.
2879fn close_side(ui: &Ui) -> f32 {
2880    Tokens::of(ui.ctx()).size.control_height.max(24.0)
2881}
2882
2883/// The ✕: the kit's close glyph on a `band-icon-button`, named "Close".
2884/// Never focused when the dialog opens (nothing asks it to be).
2885fn close_button(ui: &mut Ui, side: f32) -> Response {
2886    let name = strings::tr(ui.ctx(), &CLOSE);
2887    let glyph = Kit::of(ui.ctx()).glyph(kit::Glyph::Close);
2888    band::button(ui, side, glyph, &name, false)
2889}
2890
2891/// Cancel and the primary button, right-aligned; the Copy button in the
2892/// other corner, given its text and when it last copied.
2893/// A confirmation's buttons: its primary verb, a second action (its verb
2894/// and whether it is destructive), Cancel's text (the default when
2895/// empty), and their order.
2896struct Buttons<'a> {
2897    verb: &'a str,
2898    danger: bool,
2899    secondary: Option<(&'a str, bool)>,
2900    cancel: &'a str,
2901    order: ButtonOrder,
2902}
2903
2904impl<'a> Buttons<'a> {
2905    /// The primary button and Cancel, in `ctx`'s order
2906    /// ([`ButtonOrder::of`]).
2907    fn two(ctx: &egui::Context, verb: &'a str, danger: bool) -> Self {
2908        Self {
2909            verb,
2910            danger,
2911            secondary: None,
2912            cancel: "",
2913            order: ButtonOrder::of(ctx),
2914        }
2915    }
2916}
2917
2918/// A button in the danger tone when `danger`: the verb and the outline
2919/// in the danger colour, on the button's own background (no new
2920/// contrast pair).
2921fn toned_button(ui: &mut Ui, verb: &str, danger: bool) -> egui::Response {
2922    let t = Tokens::of(ui.ctx());
2923    let button = if danger {
2924        egui::Button::new(egui::RichText::new(verb).color(t.status.danger))
2925            .stroke(egui::Stroke::new(1.0, t.status.danger))
2926    } else {
2927        egui::Button::new(verb)
2928    };
2929    ui.add(button)
2930}
2931
2932fn footer(
2933    ui: &mut Ui,
2934    buttons: Buttons<'_>,
2935    first: bool,
2936    copy: Option<(String, &mut Option<f64>)>,
2937) -> Option<Answer> {
2938    let t = Tokens::of(ui.ctx());
2939    ui.add_space(t.space.m);
2940    let mut answer = None;
2941    let Buttons {
2942        verb,
2943        danger,
2944        secondary,
2945        cancel,
2946        order,
2947    } = buttons;
2948    let cancel_text = if cancel.is_empty() {
2949        strings::tr(ui.ctx(), &CANCEL)
2950    } else {
2951        cancel.to_string()
2952    };
2953    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
2954        // Laid from the end: the platform's order read backwards.
2955        let (p, second, cancel) = match order {
2956            ButtonOrder::PrimaryLast => {
2957                let p = toned_button(ui, verb, danger);
2958                let cancel = ui.button(&cancel_text);
2959                let second = secondary.map(|(v, d)| {
2960                    ui.add_space(t.space.l);
2961                    toned_button(ui, v, d)
2962                });
2963                (p, second, cancel)
2964            }
2965            ButtonOrder::PrimaryFirst => {
2966                let cancel = ui.button(&cancel_text);
2967                let second = secondary.map(|(v, d)| toned_button(ui, v, d));
2968                let p = toned_button(ui, verb, danger);
2969                (p, second, cancel)
2970            }
2971        };
2972        // The focus starts on the default: the primary button, or Cancel
2973        // when the primary one is destructive; never the second action.
2974        if first {
2975            if danger {
2976                cancel.request_focus();
2977            } else {
2978                p.request_focus();
2979            }
2980        }
2981        if p.clicked() {
2982            answer = Some(Answer::Accept { values: Map::new() });
2983        }
2984        if second.as_ref().is_some_and(egui::Response::clicked) {
2985            answer = Some(Answer::Choose { index: 1 });
2986        }
2987        if cancel.clicked() {
2988            answer = Some(Answer::Cancel);
2989        }
2990        if let Some((text, at)) = copy {
2991            copy_corner(ui, &text, at);
2992        }
2993    });
2994    answer
2995}
2996
2997/// How long the "Copied" note stays, in seconds.
2998const COPIED_FOR: f64 = 2.0;
2999
3000/// The Copy button, at the start of the row left before it (the bottom
3001/// left corner): the kit's `icon-button` with the copy icon, named and
3002/// tooltipped "Copy", in the focus order after the dialog's buttons. A
3003/// click puts `text` on the clipboard (egui's `copy_text`) and shows a
3004/// short "Copied" note beside it.
3005fn copy_corner(ui: &mut Ui, text: &str, at: &mut Option<f64>) {
3006    ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
3007        let ctx = ui.ctx().clone();
3008        let name = strings::tr(&ctx, &txt::DIALOG_COPY);
3009        let button = ui.add(Icon::Copy.size(IconSize::Inline).label(&name).sense_click());
3010        let now = ctx.input(|i| i.time);
3011        if button.clicked() {
3012            ctx.copy_text(text.to_string());
3013            *at = Some(now);
3014        }
3015        if let Some(when) = *at {
3016            let left = COPIED_FOR - (now - when);
3017            if left > 0.0 {
3018                ui.text_role(TextRole::Muted, strings::tr(&ctx, &txt::DIALOG_COPIED));
3019                ctx.request_repaint_after_secs(left as f32);
3020            } else {
3021                *at = None;
3022            }
3023        }
3024    });
3025}
3026
3027/// The Copy button copied during this pass (Enter on it copies only).
3028fn copied_now(ui: &Ui, at: Option<f64>) -> bool {
3029    at == Some(ui.input(|i| i.time))
3030}
3031
3032/// A dialog's details on screen: a collapsed "Details" section holding a
3033/// read-only, monospace, selectable area with the lines its Copy button
3034/// copies.
3035fn details_section(ui: &mut Ui, id: u64, details: &Details) {
3036    let text = details.text();
3037    let title = strings::tr(ui.ctx(), &txt::DIALOG_DETAILS);
3038    egui::CollapsingHeader::new(&title)
3039        .id_salt(("egui_pop.dialog.details", id))
3040        .default_open(false)
3041        .show(ui, |ui| {
3042            let mut shown = text.as_str();
3043            ui.add(
3044                egui::TextEdit::multiline(&mut shown)
3045                    .font(egui::TextStyle::Monospace)
3046                    .desired_width(f32::INFINITY)
3047                    .desired_rows(details.lines.len().clamp(1, 8)),
3048            )
3049            .on_hover_text(&title);
3050        });
3051}
3052
3053/// A field's editor, labelled by `label`.
3054fn edit_field(
3055    ui: &mut Ui,
3056    field: &mut Field,
3057    browse: &mut Option<(String, FileRequest)>,
3058    command: &CommandId,
3059    label: egui::Id,
3060) -> Response {
3061    let d = &field.descriptor;
3062    let r = match (&mut field.value, d.ty) {
3063        (Value::Bool(v), _) => widgets::checkbox(ui, v, ""),
3064        (Value::Float(v), _) => {
3065            let (lo, hi) = d.soft.or(d.hard).unwrap_or((0.0, 1.0));
3066            ui.add(
3067                egui::DragValue::new(v)
3068                    .range(lo..=hi)
3069                    .speed(d.step)
3070                    .max_decimals(d.precision as usize),
3071            )
3072        }
3073        (Value::Int(v), _) => {
3074            let (lo, hi) = d.hard.unwrap_or((i64::MIN as f64, i64::MAX as f64));
3075            ui.add(egui::DragValue::new(v).range(lo as i64..=hi as i64))
3076        }
3077        (Value::Choice(v), _) => {
3078            let mut picked = v.clone();
3079            let combo = widgets::combo_box(("egui_pop.form.choice", &field.key))
3080                .selected_text(picked.as_str());
3081            let r = ui
3082                .combo_box(combo, |ui| {
3083                    for c in &d.choices {
3084                        widgets::selectable_value(ui, &mut picked, c.clone(), c);
3085                    }
3086                })
3087                .response;
3088            *v = picked;
3089            r
3090        }
3091        (Value::Text(v), Type::Text) => {
3092            let path = d.path.clone();
3093            ui.horizontal(|ui| {
3094                let r = ui.text_edit_singleline(v);
3095                egui_pop_core::focus_mode::follow_pointer(&r);
3096                if let Some(hint) = path
3097                    && ui
3098                        .button(strings::tr(ui.ctx(), &txt::DIALOG_BROWSE))
3099                        .clicked()
3100                {
3101                    *browse = Some((
3102                        field.key.clone(),
3103                        request_for(
3104                            &field.descriptor.label,
3105                            v,
3106                            &hint,
3107                            &format!("{command}.{}", field.key),
3108                        ),
3109                    ));
3110                }
3111                r
3112            })
3113            .inner
3114        }
3115        (v, _) => ui.monospace(v.to_json().to_string()),
3116    };
3117    r.labelled_by(label)
3118}
3119
3120/// The choice a path field's Browse asks for: titled by the hint, else by
3121/// the field's label; its last folder remembered under the hint's purpose,
3122/// else `purpose`. A value naming a folder (or a file in one) starts there,
3123/// over the purpose's last folder.
3124fn request_for(label: &str, value: &str, hint: &PathHint, purpose: &str) -> FileRequest {
3125    let title = hint.title.as_deref().unwrap_or(label);
3126    let mut r = match hint.kind {
3127        PathKind::Dir => FileRequest::folder(title),
3128        PathKind::File => FileRequest::open(title),
3129    }
3130    .purpose(hint.purpose.as_deref().unwrap_or(purpose));
3131    r = match value_dir(value) {
3132        Some(dir) => r.force_directory(dir),
3133        None => r.directory(start_dir(value)),
3134    };
3135    if !hint.extensions.is_empty() {
3136        let exts: Vec<&str> = hint.extensions.iter().map(String::as_str).collect();
3137        let name = hint.filter_name.clone().unwrap_or_else(|| exts.join(", "));
3138        r = r.filter(&name, &exts);
3139    }
3140    r
3141}
3142
3143/// The folder a value names, or holds its file: none for an empty value or
3144/// one whose folder is gone.
3145fn value_dir(value: &str) -> Option<PathBuf> {
3146    if value.trim().is_empty() {
3147        return None;
3148    }
3149    let p = Path::new(value);
3150    if p.is_dir() {
3151        return Some(p.to_path_buf());
3152    }
3153    p.parent().filter(|d| d.is_dir()).map(Path::to_path_buf)
3154}
3155
3156/// Starts the choice a Browse asked for (through the files plugin, else
3157/// the in-app picker inside the dialog), and writes a finished choice
3158/// into its field.
3159fn browse(app: &AppHandle, o: &mut Open) {
3160    if let Some((key, request)) = o.browse.take() {
3161        match app.service(&FILES) {
3162            Some(f) => {
3163                let (id, pending) = f.choose_inline(app, request);
3164                o.choosing = Some((key, id, pending));
3165            }
3166            None => o.picking = Some((key, FilePicker::new(&request))),
3167        }
3168    }
3169    let Some(result) = o.choosing.as_ref().and_then(|(_, _, p)| p.take()) else {
3170        return;
3171    };
3172    let Some((key, ..)) = o.choosing.take() else {
3173        return;
3174    };
3175    match files::chosen(&result) {
3176        Ok(files::Chosen::Paths(paths)) => {
3177            if let (Dialog::Form(f), Some(p)) = (&mut o.dialog, paths.first())
3178                && let Some(field) = f.fields.iter_mut().find(|x| x.key == key)
3179            {
3180                field.value = Value::Text(p.display().to_string());
3181            }
3182        }
3183        Ok(files::Chosen::Cancelled) => {}
3184        Err(e) => o.error = Some(e),
3185    }
3186}
3187
3188/// Where a chooser starts: the value's folder, else home, else the root.
3189fn start_dir(value: &str) -> PathBuf {
3190    let p = Path::new(value);
3191    if p.is_dir() {
3192        return p.to_path_buf();
3193    }
3194    if let Some(parent) = p.parent().filter(|d| d.is_dir()) {
3195        return parent.to_path_buf();
3196    }
3197    std::env::var_os("HOME")
3198        .or_else(|| std::env::var_os("USERPROFILE"))
3199        .map(PathBuf::from)
3200        .filter(|d| d.is_dir())
3201        .unwrap_or_else(|| PathBuf::from("/"))
3202}
3203
3204/// The entries of a folder a picker lists: folders, then the files the
3205/// hint accepts (none for a folder picker), by name; hidden ones left
3206/// out.
3207pub fn entries(dir: &Path, hint: &PathHint) -> Vec<(PathBuf, bool)> {
3208    let Ok(read) = std::fs::read_dir(dir) else {
3209        return Vec::new();
3210    };
3211    let mut out: Vec<(PathBuf, bool)> = read
3212        .filter_map(Result::ok)
3213        .map(|e| e.path())
3214        .filter(|p| {
3215            !p.file_name()
3216                .and_then(|n| n.to_str())
3217                .is_some_and(|n| n.starts_with('.'))
3218        })
3219        .filter_map(|p| {
3220            let is_dir = p.is_dir();
3221            (is_dir || (hint.kind == PathKind::File && hint.accepts(&p))).then_some((p, is_dir))
3222        })
3223        .collect();
3224    out.sort_by(|a, b| (!a.1, &a.0).cmp(&(!b.1, &b.0)));
3225    out
3226}