Skip to main content

waft_winui/controls/
content_dialog.rs

1//! ContentDialog_themeresources.xaml and ContentDialog_Partial.cpp: a modal dialog over the
2//! window with a title, content and up to three command buttons. `show_async` pushes it onto the
3//! root navigator as a dialog route whose barrier is the smoke layer; a command button, Escape,
4//! Enter on the default button or `hide` closes it through the cancelable Closing event.
5//!
6//! The invariant a later editor must keep: a showing ends only in `finish_closing`, once the
7//! route has animated out or its page is gone, so the Closed event and the result always come
8//! after the close transition, and exactly once per `show_async`.
9
10use super::flyout::shadow::PopupShadow;
11use crate::*;
12use std::{cell::Cell, collections::HashMap, fmt, rc::Rc, time::Duration};
13use waft_animation::{AnimationStatus, AnimationStatusListener, Cubic, Curve, Curves};
14use waft_embedder::{FontWeight, TextDirection};
15use waft_foundation::{
16    App, ChangeNotifier, ChangeNotifierData, Completer, CompleterFuture, Handle, HandleId,
17    ListenableObject, Listener, OptionRetained, Ref,
18};
19use waft_painting::{BorderRadius, EdgeInsetsGeometry};
20use waft_rendering::{BoxConstraints, CrossAxisAlignment, MainAxisSize};
21use waft_scheduler::{FrameCallback, SchedulerBinding};
22use waft_services::{KeyEvent, LogicalKeyboardKey};
23use waft_widgets::*;
24
25/// XAML `ContentDialogButton`: one of the three command buttons, or none.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
27pub enum ContentDialogButton {
28    #[default]
29    None,
30    Primary,
31    Secondary,
32    Close,
33}
34
35/// XAML `ContentDialogResult`: the command that closed the dialog. The close button, Escape and
36/// `hide` close it with `None`.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
38pub enum ContentDialogResult {
39    #[default]
40    None,
41    Primary,
42    Secondary,
43}
44
45/// `ContentDialogButtonClickDeferral`: what `ContentDialogButtonClickEventArgs::get_deferral`
46/// gives.
47pub type ContentDialogButtonClickDeferral = Deferral;
48
49/// `ContentDialogClosingDeferral`: what `ContentDialogClosingEventArgs::get_deferral` gives.
50pub type ContentDialogClosingDeferral = Deferral;
51
52/// Arguments of a command button's click, raised before the dialog closes. A handler that
53/// decides later keeps them and takes a deferral.
54pub struct ContentDialogButtonClickEventArgs {
55    cancel: Cell<bool>,
56    deferrals: Rc<DeferralManager>,
57    generation: u64,
58}
59
60impl ContentDialogButtonClickEventArgs {
61    /// `Cancel`: whether the dialog stays open.
62    pub fn cancel(&self) -> bool {
63        self.cancel.get()
64    }
65
66    /// Sets Cancel.
67    pub fn set_cancel(&self, cancel: bool) {
68        self.cancel.set(cancel);
69    }
70
71    /// `GetDeferral`: the dialog reads Cancel, and closes, once the deferral is complete.
72    pub fn get_deferral(&self) -> Result<ContentDialogButtonClickDeferral, DeferralCompleted> {
73        self.deferrals.get_deferral(self.generation)
74    }
75}
76
77impl fmt::Debug for ContentDialogButtonClickEventArgs {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.debug_struct("ContentDialogButtonClickEventArgs")
80            .field("cancel", &self.cancel.get())
81            .finish_non_exhaustive()
82    }
83}
84
85/// Arguments of the Closing event. A handler that decides later keeps them and takes a
86/// deferral.
87pub struct ContentDialogClosingEventArgs {
88    result: ContentDialogResult,
89    cancel: Cell<bool>,
90    deferrals: Rc<DeferralManager>,
91    generation: u64,
92}
93
94impl ContentDialogClosingEventArgs {
95    /// `Result`: the result the dialog is closing with.
96    pub fn result(&self) -> ContentDialogResult {
97        self.result
98    }
99
100    /// `Cancel`: whether the dialog stays open.
101    pub fn cancel(&self) -> bool {
102        self.cancel.get()
103    }
104
105    /// Sets Cancel.
106    pub fn set_cancel(&self, cancel: bool) {
107        self.cancel.set(cancel);
108    }
109
110    /// `GetDeferral`: the dialog reads Cancel, and closes, once the deferral is complete.
111    pub fn get_deferral(&self) -> Result<ContentDialogClosingDeferral, DeferralCompleted> {
112        self.deferrals.get_deferral(self.generation)
113    }
114}
115
116impl fmt::Debug for ContentDialogClosingEventArgs {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("ContentDialogClosingEventArgs")
119            .field("result", &self.result)
120            .field("cancel", &self.cancel.get())
121            .finish_non_exhaustive()
122    }
123}
124
125/// Arguments of the Closed event.
126#[derive(Clone, Copy, Debug)]
127pub struct ContentDialogClosedEventArgs {
128    /// The result the dialog closed with.
129    pub result: ContentDialogResult,
130}
131
132/// Receives a command button's cancelable click.
133pub type ContentDialogButtonClickHandler =
134    Rc<dyn Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>)>;
135
136/// Receives the cancelable Closing event.
137pub type ContentDialogClosingHandler = Rc<dyn Fn(&mut App, &Rc<ContentDialogClosingEventArgs>)>;
138
139/// Receives the Closed event.
140pub type ContentDialogClosedHandler = Rc<dyn Fn(&mut App, ContentDialogClosedEventArgs)>;
141
142/// Why `show_async` refused to show a dialog.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub enum ContentDialogError {
145    /// `ERROR_CONTENTDIALOG_MULTIPLE_OPEN`: this dialog is still showing, or another is open in
146    /// the same window.
147    MultipleOpen,
148}
149
150impl fmt::Display for ContentDialogError {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            Self::MultipleOpen => f.write_str("only one ContentDialog can be open at a time"),
154        }
155    }
156}
157
158impl std::error::Error for ContentDialogError {}
159
160/// `ContentDialogMetadata`: the dialog open in each window, keyed by its root navigator.
161#[derive(Default)]
162struct ContentDialogMetadata {
163    open: HashMap<HandleId, Handle<ContentDialog>>,
164}
165
166/// A persistent dialog object: set its properties, show it with `show_async` from a context
167/// beneath a `Navigator`, and dispose it when its owner is disposed.
168pub struct ContentDialog {
169    /// `Title`: shown above the content in the subtitle size, on at most two lines. Without one,
170    /// the title row and its margin collapse.
171    pub title: Option<WidgetRef>,
172
173    /// `Content`: shown below the title in the body size, wrapping.
174    pub content: Option<WidgetRef>,
175
176    /// `PrimaryButtonText`: the leftmost button's label; empty hides the button.
177    pub primary_button_text: String,
178
179    /// `SecondaryButtonText`: the middle button's label; empty hides the button.
180    pub secondary_button_text: String,
181
182    /// `CloseButtonText`: the rightmost button's label, which Escape also invokes; empty hides
183    /// the button.
184    pub close_button_text: String,
185
186    /// `IsPrimaryButtonEnabled`.
187    pub is_primary_button_enabled: bool,
188
189    /// `IsSecondaryButtonEnabled`.
190    pub is_secondary_button_enabled: bool,
191
192    /// `DefaultButton`: drawn in the accent style and invoked by Enter.
193    pub default_button: ContentDialogButton,
194
195    /// `FullSizeDesired`: whether the dialog takes the window's height, up to its maximum.
196    pub full_size_desired: bool,
197
198    /// `PrimaryButtonClick`: can cancel the close the primary button asks for.
199    pub primary_button_click: Option<ContentDialogButtonClickHandler>,
200
201    /// `SecondaryButtonClick`: can cancel the close the secondary button asks for.
202    pub secondary_button_click: Option<ContentDialogButtonClickHandler>,
203
204    /// `CloseButtonClick`: can cancel the close the close button or Escape asks for.
205    pub close_button_click: Option<ContentDialogButtonClickHandler>,
206
207    /// `Opened`: called after the dialog's first frame and its initial focus.
208    pub opened: Option<Listener>,
209
210    /// `Closing`: can cancel any close but one the dialog's route was removed for.
211    pub closing: Option<ContentDialogClosingHandler>,
212
213    /// `Closed`: called after the close transition, before the result is delivered.
214    pub closed: Option<ContentDialogClosedHandler>,
215
216    /// Rebuilds the shown presenter when a property changes.
217    notifier: ChangeNotifierData,
218
219    /// The current showing, from `show_async` until the dialog has finished closing.
220    showing: Option<Showing>,
221
222    /// `m_spButtonClickDeferralManager`: a new one for each showing, so a click deferral that a
223    /// closed showing left pending cannot hold back the next showing's clicks.
224    button_click_deferrals: Rc<DeferralManager>,
225
226    /// `m_spClosingDeferralManager`.
227    closing_deferrals: Rc<DeferralManager>,
228
229    /// Set by `dispose`; the dialog is freed once its owner and its route let go.
230    disposed: bool,
231}
232
233/// One showing of a dialog.
234struct Showing {
235    route: AnyRoute,
236    navigator: Handle<NavigatorState>,
237
238    /// `m_tpCurrentAsyncOperation`: completed with the result once the dialog has closed.
239    completion: Completer<ContentDialogResult>,
240
241    /// The result the dialog closes with, once a close is under way.
242    result: ContentDialogResult,
243
244    /// `m_hideInProgress`: a close was accepted and the route is leaving.
245    hide_in_progress: bool,
246
247    /// `m_skipClosingEventOnHide`: true until the dialog has opened, and when the route was
248    /// removed by something other than the dialog.
249    skip_closing_event: bool,
250
251    /// The theme and direction of the context that showed the dialog, which its route, in the
252    /// root overlay, does not inherit.
253    resources: Rc<ThemeResources>,
254    direction: TextDirection,
255}
256
257impl fmt::Debug for ContentDialog {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_struct("ContentDialog")
260            .field("primary_button_text", &self.primary_button_text)
261            .field("secondary_button_text", &self.secondary_button_text)
262            .field("close_button_text", &self.close_button_text)
263            .field("default_button", &self.default_button)
264            .field("showing", &self.showing.is_some())
265            .finish_non_exhaustive()
266    }
267}
268
269impl ChangeNotifier for ContentDialog {
270    fn change_notifier_data(&self) -> &ChangeNotifierData {
271        &self.notifier
272    }
273
274    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
275        &mut self.notifier
276    }
277}
278
279impl ContentDialog {
280    /// Creates a dialog with no title, no content and no buttons.
281    pub fn new(app: &mut App) -> Ref<Self> {
282        app.create(Self {
283            title: None,
284            content: None,
285            primary_button_text: String::new(),
286            secondary_button_text: String::new(),
287            close_button_text: String::new(),
288            is_primary_button_enabled: true,
289            is_secondary_button_enabled: true,
290            default_button: ContentDialogButton::None,
291            full_size_desired: false,
292            primary_button_click: None,
293            secondary_button_click: None,
294            close_button_click: None,
295            opened: None,
296            closing: None,
297            closed: None,
298            notifier: ChangeNotifierData::new(),
299            showing: None,
300            button_click_deferrals: DeferralManager::new(),
301            closing_deferrals: DeferralManager::new(),
302            disposed: false,
303        })
304    }
305
306    /// Sets Title.
307    #[cfg_attr(debug_assertions, track_caller)]
308    pub fn title<K>(self: Handle<Self>, app: &mut App, title: impl IntoWidget<K>) {
309        self.change(app, |dialog| dialog.title = Some(title.into_widget()))
310    }
311
312    /// Sets Content.
313    #[cfg_attr(debug_assertions, track_caller)]
314    pub fn content<K>(self: Handle<Self>, app: &mut App, content: impl IntoWidget<K>) {
315        self.change(app, |dialog| dialog.content = Some(content.into_widget()))
316    }
317
318    /// Sets PrimaryButtonText.
319    pub fn primary_button_text(self: Handle<Self>, app: &mut App, text: impl Into<String>) {
320        self.change(app, |dialog| dialog.primary_button_text = text.into())
321    }
322
323    /// Sets SecondaryButtonText.
324    pub fn secondary_button_text(self: Handle<Self>, app: &mut App, text: impl Into<String>) {
325        self.change(app, |dialog| dialog.secondary_button_text = text.into())
326    }
327
328    /// Sets CloseButtonText.
329    pub fn close_button_text(self: Handle<Self>, app: &mut App, text: impl Into<String>) {
330        self.change(app, |dialog| dialog.close_button_text = text.into())
331    }
332
333    /// Sets IsPrimaryButtonEnabled.
334    pub fn is_primary_button_enabled(self: Handle<Self>, app: &mut App, value: bool) {
335        self.change(app, |dialog| dialog.is_primary_button_enabled = value)
336    }
337
338    /// Sets IsSecondaryButtonEnabled.
339    pub fn is_secondary_button_enabled(self: Handle<Self>, app: &mut App, value: bool) {
340        self.change(app, |dialog| dialog.is_secondary_button_enabled = value)
341    }
342
343    /// Sets DefaultButton.
344    pub fn default_button(self: Handle<Self>, app: &mut App, button: ContentDialogButton) {
345        self.change(app, |dialog| dialog.default_button = button)
346    }
347
348    /// Sets FullSizeDesired.
349    pub fn full_size_desired(self: Handle<Self>, app: &mut App, value: bool) {
350        self.change(app, |dialog| dialog.full_size_desired = value)
351    }
352
353    /// Sets the PrimaryButtonClick handler.
354    pub fn primary_button_click(
355        self: Handle<Self>,
356        app: &mut App,
357        handler: impl Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>) + 'static,
358    ) {
359        app.get_mut(self).primary_button_click = Some(Rc::new(handler));
360    }
361
362    /// Sets the SecondaryButtonClick handler.
363    pub fn secondary_button_click(
364        self: Handle<Self>,
365        app: &mut App,
366        handler: impl Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>) + 'static,
367    ) {
368        app.get_mut(self).secondary_button_click = Some(Rc::new(handler));
369    }
370
371    /// Sets the CloseButtonClick handler.
372    pub fn close_button_click(
373        self: Handle<Self>,
374        app: &mut App,
375        handler: impl Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>) + 'static,
376    ) {
377        app.get_mut(self).close_button_click = Some(Rc::new(handler));
378    }
379
380    /// Sets the Opened handler.
381    pub fn opened(self: Handle<Self>, app: &mut App, handler: Listener) {
382        app.get_mut(self).opened = Some(handler);
383    }
384
385    /// Sets the Closing handler.
386    pub fn closing(
387        self: Handle<Self>,
388        app: &mut App,
389        handler: impl Fn(&mut App, &Rc<ContentDialogClosingEventArgs>) + 'static,
390    ) {
391        app.get_mut(self).closing = Some(Rc::new(handler));
392    }
393
394    /// Sets the Closed handler.
395    pub fn closed(
396        self: Handle<Self>,
397        app: &mut App,
398        handler: impl Fn(&mut App, ContentDialogClosedEventArgs) + 'static,
399    ) {
400        app.get_mut(self).closed = Some(Rc::new(handler));
401    }
402
403    /// `ShowAsync`: shows the dialog over the window of `context`'s root navigator. The future
404    /// completes with the result once the dialog has closed.
405    pub fn show_async(
406        self: Handle<Self>,
407        app: &mut App,
408        context: BuildContext,
409    ) -> Result<CompleterFuture<ContentDialogResult>, ContentDialogError> {
410        assert!(
411            !app.get(self).disposed,
412            "cannot show a disposed ContentDialog"
413        );
414        let navigator = Navigator::of(app, context, true);
415        let metadata = app.singleton::<ContentDialogMetadata>();
416        if app.get(self).showing.is_some() || app.get(metadata).open.contains_key(&navigator.id()) {
417            return Err(ContentDialogError::MultipleOpen);
418        }
419        let resources = ThemeResources::of(app, context);
420        let direction = Directionality::maybe_of(app, context).unwrap_or(TextDirection::Ltr);
421        let dialog_route = self.dialog_route(app, &resources);
422        let route = dialog_route.as_route();
423        let completion = Completer::new();
424        let result = completion.future();
425        app.get_mut(self).showing = Some(Showing {
426            route,
427            navigator,
428            completion,
429            result: ContentDialogResult::None,
430            hide_in_progress: false,
431            skip_closing_event: true,
432            resources,
433            direction,
434        });
435        app.get_mut(metadata).open.insert(navigator.id(), self);
436        navigator
437            .push(app, dialog_route.clone().into_erased())
438            .then(app, move |app, _| self.route_popped(app, route));
439        self.finish_closing_when_dismissed(app, dialog_route.handle());
440        Ok(result)
441    }
442
443    /// `Hide`: closes the dialog with `None`, through the Closing event.
444    pub fn hide(self: Handle<Self>, app: &mut App) {
445        self.hide_internal(app, ContentDialogResult::None);
446    }
447
448    /// Releases the dialog. A shown dialog closes first, without its Closing and Closed events,
449    /// and its result is `None`.
450    pub fn dispose(self: Handle<Self>, app: &mut App) {
451        if app.get(self).disposed {
452            return;
453        }
454        app.get_mut(self).disposed = true;
455        if app.get(self).showing.is_none() {
456            self.notifier_dispose(app);
457            return;
458        }
459        self.hide_internal(app, ContentDialogResult::None);
460    }
461
462    /// Applies `change` to the dialog's properties and rebuilds a shown presenter.
463    fn change(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut Self)) {
464        change(app.get_mut(self));
465        self.notify_listeners(app);
466    }
467
468    /// The route the dialog is shown in, with the smoke layer of `resources`.
469    fn dialog_route(
470        self: Handle<Self>,
471        app: &mut App,
472        resources: &ThemeResources,
473    ) -> Ref<ContentDialogRoute> {
474        let smoke = resources.content_dialog_smoke_fill;
475        let dialog = self.keep(app);
476        ContentDialogRoute::new(app, dialog, smoke)
477    }
478
479    /// Ends the showing once `route` has animated out, even when its page never mounted, as
480    /// when the dialog is hidden in the frame it was shown in. The page's removal ends it
481    /// otherwise, whichever comes first.
482    fn finish_closing_when_dismissed(
483        self: Handle<Self>,
484        app: &mut App,
485        route: Handle<ContentDialogRoute>,
486    ) {
487        let Some(animation) = TransitionRoute::animation(route, app) else {
488            return;
489        };
490        let shown = route.as_route();
491        animation.add_status_listener(
492            app,
493            AnimationStatusListener::new(move |status, app| {
494                if status == AnimationStatus::Dismissed {
495                    self.finish_closing(app, shown);
496                }
497            }),
498        );
499    }
500
501    /// `OnCommandButtonClicked`: raises the button's cancelable click and, once the click's
502    /// deferrals are complete and no handler canceled, closes with the button's result. A click
503    /// while an earlier click's deferrals are outstanding is ignored.
504    fn command_button_clicked(self: Handle<Self>, app: &mut App, button: ContentDialogButton) {
505        if !app.contains(self) || !self.is_accepting_commands(app) {
506            return;
507        }
508        let dialog = app.get(self);
509        let (handler, result) = match button {
510            ContentDialogButton::Primary => (
511                dialog.primary_button_click.clone(),
512                ContentDialogResult::Primary,
513            ),
514            ContentDialogButton::Secondary => (
515                dialog.secondary_button_click.clone(),
516                ContentDialogResult::Secondary,
517            ),
518            ContentDialogButton::Close => {
519                (dialog.close_button_click.clone(), ContentDialogResult::None)
520            }
521            ContentDialogButton::None => return,
522        };
523        let deferrals = Rc::clone(&dialog.button_click_deferrals);
524        let Some(generation) = deferrals.prepare() else {
525            return;
526        };
527        let args = Rc::new(ContentDialogButtonClickEventArgs {
528            cancel: Cell::new(false),
529            deferrals: Rc::clone(&deferrals),
530            generation,
531        });
532        if let Some(handler) = handler {
533            handler(app, &args);
534        }
535        deferrals.continue_with(app, move |app| {
536            if app.contains(self) && !args.cancel() {
537                self.hide_internal(app, result);
538            }
539        });
540    }
541
542    /// `ExecuteCloseAction`: Escape and the system back request press the close button when
543    /// there is one, and otherwise close with `None`.
544    fn execute_close_action(self: Handle<Self>, app: &mut App) {
545        if app.get(self).close_button_text.is_empty() {
546            self.hide_internal(app, ContentDialogResult::None);
547        } else {
548            self.command_button_clicked(app, ContentDialogButton::Close);
549        }
550    }
551
552    /// Enter presses the default button when it is enabled; false when there is none to press.
553    fn invoke_default_button(self: Handle<Self>, app: &mut App) -> bool {
554        let dialog = app.get(self);
555        let enabled = match dialog.default_button {
556            ContentDialogButton::None => return false,
557            ContentDialogButton::Primary => dialog.is_primary_button_enabled,
558            ContentDialogButton::Secondary => dialog.is_secondary_button_enabled,
559            ContentDialogButton::Close => true,
560        };
561        if enabled {
562            let button = dialog.default_button;
563            self.command_button_clicked(app, button);
564        }
565        enabled
566    }
567
568    /// `HideInternal`: raises the cancelable Closing event, unless it is skipped, and once its
569    /// deferrals are complete closes the route with `result`.
570    fn hide_internal(self: Handle<Self>, app: &mut App, result: ContentDialogResult) {
571        if !self.is_accepting_commands(app) {
572            return;
573        }
574        let deferrals = Rc::clone(&app.get(self).closing_deferrals);
575        let generation = deferrals
576            .prepare()
577            .expect("a close in progress stops new ones");
578        let dialog = app.get_mut(self);
579        let disposed = dialog.disposed;
580        let showing = dialog.showing.as_mut().expect("a showing dialog");
581        showing.hide_in_progress = true;
582        let fire_closing = !showing.skip_closing_event && !disposed;
583        let args = fire_closing.then(|| {
584            Rc::new(ContentDialogClosingEventArgs {
585                result,
586                cancel: Cell::new(false),
587                deferrals: Rc::clone(&deferrals),
588                generation,
589            })
590        });
591        if let Some(args) = &args
592            && let Some(closing) = app.get(self).closing.clone()
593        {
594            closing(app, args);
595        }
596        deferrals.continue_with(app, move |app| {
597            if app.contains(self) {
598                let canceled = args.is_some_and(|args| args.cancel());
599                self.hide_after_deferral(app, canceled, result);
600            }
601        });
602    }
603
604    /// `HideAfterDeferralWorker`: a canceled close keeps the dialog open while its route is still
605    /// shown; otherwise the window's open-dialog slot is freed and the route leaves with
606    /// `result`.
607    fn hide_after_deferral(
608        self: Handle<Self>,
609        app: &mut App,
610        canceled: bool,
611        result: ContentDialogResult,
612    ) {
613        let disposed = app.get(self).disposed;
614        let Some(showing) = app.get(self).showing.as_ref() else {
615            return;
616        };
617        let (route, navigator) = (showing.route, showing.navigator);
618        let keep_open = canceled && !disposed && route.is_active(app);
619        let showing = app
620            .get_mut(self)
621            .showing
622            .as_mut()
623            .expect("a showing dialog");
624        if keep_open {
625            showing.hide_in_progress = false;
626            return;
627        }
628        showing.result = result;
629        self.leave_metadata(app, navigator);
630        if route.is_current(app) {
631            navigator.pop(app, None);
632        } else if route.is_active(app) {
633            navigator.remove_route(app, route, None);
634        }
635    }
636
637    /// Whether a showing can still be closed: it is shown and no close is under way.
638    fn is_accepting_commands(self: Handle<Self>, app: &App) -> bool {
639        app.get(self)
640            .showing
641            .as_ref()
642            .is_some_and(|showing| !showing.hide_in_progress)
643    }
644
645    /// `OnPopupOpened`: from now on a close raises Closing.
646    fn finish_opening(self: Handle<Self>, app: &mut App, route: AnyRoute) {
647        let Some(showing) = self.showing_of(app, route) else {
648            return;
649        };
650        showing.skip_closing_event = false;
651        if let Some(opened) = app.get(self).opened.clone() {
652            opened.call(app);
653        }
654    }
655
656    /// The route left the navigator. A route removed by something other than the dialog closes
657    /// it with `None`, without Closing, as when an app closes the dialog's popup itself.
658    fn route_popped(self: Handle<Self>, app: &mut App, route: AnyRoute) {
659        let Some(showing) = self.showing_of(app, route) else {
660            return;
661        };
662        if showing.hide_in_progress {
663            return;
664        }
665        showing.hide_in_progress = true;
666        showing.skip_closing_event = true;
667        showing.result = ContentDialogResult::None;
668        let navigator = showing.navigator;
669        self.leave_metadata(app, navigator);
670    }
671
672    /// `OnFinishedClosing`: the route's page is gone, so the showing ends: Closed is raised and
673    /// the result delivered.
674    fn finish_closing(self: Handle<Self>, app: &mut App, route: AnyRoute) {
675        if self.showing_of(app, route).is_none() {
676            return;
677        }
678        let showing = app.get_mut(self).showing.take().expect("a showing dialog");
679        self.leave_metadata(app, showing.navigator);
680        let result = showing.result;
681        if app.get(self).disposed {
682            showing.completion.complete(app, result);
683            self.notifier_dispose(app);
684            return;
685        }
686        if let Some(closed) = app.get(self).closed.clone() {
687            closed(app, ContentDialogClosedEventArgs { result });
688        }
689        let dialog = app.get_mut(self);
690        dialog.button_click_deferrals.disconnect();
691        dialog.button_click_deferrals = DeferralManager::new();
692        showing.completion.complete(app, result);
693    }
694
695    /// The current showing, when it is the one shown in `route`.
696    fn showing_of(self: Handle<Self>, app: &mut App, route: AnyRoute) -> Option<&mut Showing> {
697        if !app.contains(self) {
698            return None;
699        }
700        app.get_mut(self)
701            .showing
702            .as_mut()
703            .filter(|showing| showing.route == route)
704    }
705
706    /// Frees the window's open-dialog slot, when this dialog holds it.
707    fn leave_metadata(self: Handle<Self>, app: &mut App, navigator: Handle<NavigatorState>) {
708        let metadata = app.singleton::<ContentDialogMetadata>();
709        let open = &mut app.get_mut(metadata).open;
710        if open.get(&navigator.id()) == Some(&self) {
711            open.remove(&navigator.id());
712        }
713    }
714
715    fn notifier_dispose(self: Handle<Self>, app: &mut App) {
716        ChangeNotifierData::dispose(app, self);
717    }
718}
719
720/// `ButtonsVisibilityStates`: which command buttons have text.
721#[derive(Clone, Copy, Debug, PartialEq, Eq)]
722#[allow(clippy::enum_variant_names, reason = "the template's state names")]
723enum ButtonsVisibilityState {
724    AllVisible,
725    NoneVisible,
726    PrimaryVisible,
727    SecondaryVisible,
728    CloseVisible,
729    PrimaryAndSecondaryVisible,
730    PrimaryAndCloseVisible,
731    SecondaryAndCloseVisible,
732}
733
734impl ButtonsVisibilityState {
735    /// The state `ChangeVisualState` goes to for the button texts that are set.
736    fn of(has_primary: bool, has_secondary: bool, has_close: bool) -> ButtonsVisibilityState {
737        use ButtonsVisibilityState::*;
738        match (has_primary, has_secondary, has_close) {
739            (true, true, true) => AllVisible,
740            (false, false, false) => NoneVisible,
741            (true, false, false) => PrimaryVisible,
742            (false, true, false) => SecondaryVisible,
743            (false, false, true) => CloseVisible,
744            (true, true, false) => PrimaryAndSecondaryVisible,
745            (true, false, true) => PrimaryAndCloseVisible,
746            (false, true, true) => SecondaryAndCloseVisible,
747        }
748    }
749
750    /// The command space's columns and the column of each visible button: the template's,
751    /// with this state's setters applied. `None` for `NoneVisible`, which collapses the command
752    /// space.
753    fn layout(self, r: &ThemeResources) -> Option<CommandLayout> {
754        use ButtonsVisibilityState::*;
755        let spacing = GridLength::pixel(r.content_dialog_button_spacing);
756        // `PrimaryColumn`, `FirstSpacer`, `SecondaryColumn`, `SecondSpacer`, `CloseColumn`.
757        let mut columns = [
758            GridLength::STAR,
759            GridLength::pixel(0.0),
760            GridLength::pixel(0.0),
761            spacing,
762            GridLength::STAR,
763        ];
764        // `PrimaryButton` and `SecondaryButton` sit in the first column, `CloseButton` in the
765        // last, unless a setter moves them.
766        let (primary, secondary, close) = match self {
767            NoneVisible => return None,
768            AllVisible => {
769                columns[1] = spacing;
770                columns[2] = GridLength::STAR;
771                (Some(0), Some(2), Some(4))
772            }
773            PrimaryVisible => (Some(4), None, None),
774            SecondaryVisible => (None, Some(4), None),
775            CloseVisible => (None, None, Some(4)),
776            PrimaryAndSecondaryVisible => (Some(0), Some(4), None),
777            PrimaryAndCloseVisible => (Some(0), None, Some(4)),
778            SecondaryAndCloseVisible => (None, Some(0), Some(4)),
779        };
780        Some(CommandLayout {
781            columns,
782            primary,
783            secondary,
784            close,
785        })
786    }
787}
788
789/// The command space's five columns, and the column each visible command button takes.
790#[derive(Clone, Copy, Debug, PartialEq)]
791struct CommandLayout {
792    columns: [GridLength; 5],
793    primary: Option<usize>,
794    secondary: Option<usize>,
795    close: Option<usize>,
796}
797
798/// `DefaultButtonStates`: the button drawn in the accent style. While the focus is on a command
799/// button, only the default button itself keeps the accent, when it is the one focused.
800fn accented_button(
801    default: ContentDialogButton,
802    focused: Option<ContentDialogButton>,
803) -> ContentDialogButton {
804    match focused {
805        Some(focused) if focused != default => ContentDialogButton::None,
806        _ => default,
807    }
808}
809
810/// `ContentDialogOpenCloseThemeTransition`'s `s_OpenScaleDuration`: opening shrinks the dialog
811/// from its scaled factor over this long, which is also how long the route takes to open.
812const OPEN_SCALE_DURATION: Duration = Duration::from_millis(250);
813
814/// `s_CloseScaleDuration`: closing grows the dialog back to its scaled factor over this long,
815/// which is also how long the route takes to close.
816const CLOSE_SCALE_DURATION: Duration = Duration::from_millis(167);
817
818/// `s_OpacityChangeDuration`: the dialog and its smoke layer fade in, and out, over this long.
819const OPACITY_CHANGE_DURATION: Duration = Duration::from_millis(83);
820
821/// The transition's `scaledFactor`: the dialog's scale as it starts to open and ends closing.
822const SCALED_FACTOR: f64 = 1.05;
823
824/// `ContentDialogOpenCloseThemeTransition`, which a dialog shown in a popup plays as it opens
825/// and closes: the opacity of the dialog and its smoke layer, and the dialog's scale, at `value`
826/// of its route's animation going in the direction `status` says. The opacity changes linearly,
827/// the scale along cubic-bezier (0, 0, 0, 1).
828fn open_close_transition(status: AnimationStatus, value: f64) -> (f64, f64) {
829    let easing = Cubic::new(0.0, 0.0, 0.0, 1.0);
830    let fade = OPACITY_CHANGE_DURATION.as_secs_f64();
831    let progress = |elapsed: f64, duration: f64| (elapsed / duration).clamp(0.0, 1.0);
832    if matches!(
833        status,
834        AnimationStatus::Reverse | AnimationStatus::Dismissed
835    ) {
836        let close = CLOSE_SCALE_DURATION.as_secs_f64();
837        let elapsed = (1.0 - value) * close;
838        let opacity = 1.0 - progress(elapsed, fade);
839        let scale = 1.0 + (SCALED_FACTOR - 1.0) * easing.transform(progress(elapsed, close));
840        (opacity, scale)
841    } else {
842        let open = OPEN_SCALE_DURATION.as_secs_f64();
843        let elapsed = value * open;
844        let opacity = progress(elapsed, fade);
845        let scale =
846            SCALED_FACTOR - (SCALED_FACTOR - 1.0) * easing.transform(progress(elapsed, open));
847        (opacity, scale)
848    }
849}
850
851/// The route a dialog is shown in: a `RawDialogRoute` whose page is the presenter and whose
852/// barrier is the smoke layer, opening and closing in the time `ContentDialogOpenCloseThemeTransition`
853/// takes, and keeping the keyboard focus inside the dialog.
854struct ContentDialogRoute {
855    route: RouteData,
856    overlay_route: OverlayRouteData,
857    transition_route: TransitionRouteData,
858    local_history: LocalHistoryRouteData,
859    modal_route: ModalRouteData,
860    raw_dialog_route: RawDialogRouteData,
861}
862
863impl ContentDialogRoute {
864    /// A route showing `dialog` over a `smoke` layer.
865    fn new(app: &mut App, dialog: Ref<ContentDialog>, smoke: Color) -> Ref<Self> {
866        let page_builder: RoutePageBuilder = Rc::new(move |_, _, animation, _| {
867            ContentDialogPresenter {
868                dialog: dialog.handle(),
869                animation,
870            }
871            .into_widget()
872        });
873        let mut raw_dialog_route = RawDialogRouteData::new(page_builder);
874        raw_dialog_route.barrier_dismissible = false;
875        raw_dialog_route.barrier_color = Some(smoke);
876        raw_dialog_route.transition_duration = OPEN_SCALE_DURATION;
877        raw_dialog_route.transition_builder = Some(Rc::new(|_, _, _, _, child| child));
878        let mut modal_route = ModalRouteData::new(app);
879        modal_route.traversal_edge_behavior = Some(TraversalEdgeBehavior::ClosedLoop);
880        let route = RouteData::new(app, None, None);
881        let transition_route = TransitionRouteData::new(app);
882        app.create(ContentDialogRoute {
883            route,
884            overlay_route: OverlayRouteData::new(),
885            transition_route,
886            local_history: LocalHistoryRouteData::new(),
887            modal_route,
888            raw_dialog_route,
889        })
890    }
891}
892
893impl Route for ContentDialogRoute {
894    waft_widgets::modal_route_overrides!();
895}
896
897impl OverlayRoute for ContentDialogRoute {
898    waft_widgets::modal_overlay_route_overrides!();
899}
900
901impl PredictiveBackRoute for ContentDialogRoute {
902    waft_widgets::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
903}
904
905impl TransitionRoute for ContentDialogRoute {
906    waft_widgets::raw_dialog_route_transition_route_overrides!();
907
908    fn reverse_transition_duration(self: Handle<Self>, _app: &mut App) -> Duration {
909        CLOSE_SCALE_DURATION
910    }
911}
912
913impl LocalHistoryRoute for ContentDialogRoute {
914    waft_widgets::local_history_route_accessors!();
915}
916
917impl ModalRoute for ContentDialogRoute {
918    waft_widgets::raw_dialog_route_modal_route_overrides!();
919}
920
921impl PopupRoute for ContentDialogRoute {}
922
923impl RawDialogRouteLeaf for ContentDialogRoute {
924    waft_widgets::raw_dialog_route_accessors!();
925
926    /// `SmokeLayerBackground`: blocks input to the page beneath and fades with the dialog.
927    fn build_modal_barrier(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
928        let animation = TransitionRoute::animation(self, app).expect("an installed route");
929        let kept = animation.keep(app);
930        let smoke = self
931            .raw_dialog_route_data(app)
932            .barrier_color
933            .expect("the smoke fill");
934        ListenableBuilder::new(Rc::new(kept), move |app, _, _| {
935            let (opacity, _) = open_close_transition(animation.status(app), animation.value(app));
936            ModalBarrier::new()
937                .color(smoke.with_values(Some(smoke.a * opacity), None, None, None, None))
938                .dismissible(false)
939                .into_widget()
940        })
941        .into_widget()
942    }
943}
944
945/// The route's page: `LayoutRoot` of the template, the dialog centered in the window.
946#[derive(Debug)]
947struct ContentDialogPresenter {
948    dialog: Handle<ContentDialog>,
949
950    /// The route's animation, which drives the showing and hiding storyboards.
951    animation: AnimationRef<f64>,
952}
953
954/// The focus nodes the template's behavior needs, and the showing the presenter belongs to.
955struct ContentDialogPresenterState {
956    state: StateData<ContentDialogPresenter>,
957
958    /// The route of the showing this presenter was built for.
959    route: Option<AnyRoute>,
960
961    /// Encloses `Content`, whose first focusable element takes the initial focus.
962    content_focus: Option<Ref<FocusNode>>,
963
964    /// The primary, secondary and close buttons' focus, which decides the accented button.
965    button_focus: Vec<(ContentDialogButton, Ref<FocusNode>)>,
966
967    /// Rebuilds the presenter for property and focus changes.
968    rebuild: Option<Listener>,
969}
970
971impl StatefulWidget for ContentDialogPresenter {
972    type State = ContentDialogPresenterState;
973
974    fn create_state(&self) -> Self::State {
975        ContentDialogPresenterState {
976            state: StateData::new(),
977            route: None,
978            content_focus: None,
979            button_focus: Vec::new(),
980            rebuild: None,
981        }
982    }
983}
984
985impl State for ContentDialogPresenterState {
986    type Widget = ContentDialogPresenter;
987    waft_widgets::state_accessors!();
988
989    fn init_state(self: Handle<Self>, app: &mut App) {
990        let dialog = self.widget(app).dialog;
991        let route = app
992            .get(dialog)
993            .showing
994            .as_ref()
995            .map(|showing| showing.route);
996        let rebuild = Listener::new(move |app| {
997            if self.mounted(app) {
998                self.set_state(app, |_| {});
999            }
1000        });
1001        dialog.add_listener(app, rebuild.clone());
1002        let content_focus = FocusNode::new(app);
1003        let button_focus: Vec<_> = [
1004            ContentDialogButton::Primary,
1005            ContentDialogButton::Secondary,
1006            ContentDialogButton::Close,
1007        ]
1008        .into_iter()
1009        .map(|button| {
1010            let node = FocusNode::new(app);
1011            node.as_node().add_listener(app, rebuild.clone());
1012            (button, node)
1013        })
1014        .collect();
1015        let state = app.get_mut(self);
1016        state.route = route;
1017        state.content_focus = Some(content_focus);
1018        state.button_focus = button_focus;
1019        state.rebuild = Some(rebuild);
1020        self.open_after_first_frame(app);
1021    }
1022
1023    fn dispose(self: Handle<Self>, app: &mut App) {
1024        let dialog = self.widget(app).dialog;
1025        let state = app.get_mut(self);
1026        let rebuild = state.rebuild.take().expect("an initialized presenter");
1027        let nodes: Vec<_> = state
1028            .button_focus
1029            .drain(..)
1030            .map(|(_, node)| node)
1031            .chain(state.content_focus.take())
1032            .collect();
1033        let route = state.route;
1034        if app.contains(dialog) {
1035            dialog.remove_listener(app, &rebuild);
1036        }
1037        for node in nodes {
1038            node.as_node().remove_listener(app, &rebuild);
1039            node.as_node().dispose(app);
1040        }
1041        if let Some(route) = route {
1042            after_next_frame(
1043                app,
1044                // Disposed, the presenter is in no view any more.
1045                None,
1046                FrameCallback::new(move |app, _| dialog.finish_closing(app, route)),
1047            );
1048        }
1049    }
1050
1051    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1052        let dialog = self.widget(app).dialog;
1053        let Some(showing) = app.get(dialog).showing.as_ref() else {
1054            return SizedBox::shrink().into_widget();
1055        };
1056        let (resources, direction) = (showing.resources.clone(), showing.direction);
1057        let background = self.background_element(app, &resources);
1058        let animation = self.widget(app).animation.clone();
1059        let animated = ListenableBuilder::new(Rc::new(animation.clone()), move |app, _, child| {
1060            let status = animation.status(app);
1061            let (opacity, scale) = open_close_transition(status, animation.value(app));
1062            // The template makes the dialog unreachable while its closing transition plays;
1063            // the scale is `BackgroundElement`'s `ScaleTransform`.
1064            IgnorePointer::new()
1065                .ignoring(status == AnimationStatus::Reverse)
1066                .child(
1067                    Opacity::new(opacity).child(
1068                        Transform::scale(Some(scale), None, None)
1069                            .child(child.cloned().expect("the dialog's background element")),
1070                    ),
1071                )
1072                .into_widget()
1073        })
1074        .child(background);
1075        // `Container` and its `LayoutRoot`: the dialog centered over the window, where the route's
1076        // barrier is `SmokeLayerBackground`, in the room the system's bars and the keyboard leave.
1077        let layout_root = Focus::new(clear_of_the_system(app, context, animated.into_widget()))
1078            .can_request_focus(false)
1079            .skip_traversal(true)
1080            .on_key_event(Rc::new(move |app, _, event| {
1081                layout_root_key(app, dialog, event)
1082            }));
1083        let back_request = PopScope::new(layout_root)
1084            .can_pop(false)
1085            .on_pop_invoked_with_result(Rc::new(move |app, did_pop, _| {
1086                if !did_pop {
1087                    dialog.execute_close_action(app);
1088                }
1089            }));
1090        ThemeScope::with_resources(resources, Directionality::new(direction, back_request))
1091            .into_widget()
1092    }
1093}
1094
1095/// `dialog`, centered in what the system's bars and the keyboard leave of the window, as Flutter's
1096/// `showDialog` (`useSafeArea`) and `Dialog` (`AnimatedPadding` by `MediaQuery.viewInsets`, over
1097/// 100 ms, decelerating) keep a dialog: WinUI centers it over the whole window and leaves the
1098/// keyboard to scroll the focused text box into view, which the kit does not port.
1099fn clear_of_the_system(app: &mut App, context: BuildContext, dialog: WidgetRef) -> WidgetRef {
1100    let media = MediaQuery::of(app, context);
1101    let keyboard = media.view_insets;
1102    let content = MediaQuery::new(
1103        media.remove_view_insets(true, true, true, true),
1104        Center::new().child(dialog),
1105    )
1106    .into_widget();
1107    SafeArea::new(
1108        AnimatedPadding::new(
1109            EdgeInsetsGeometry::from_ltrb(
1110                keyboard.left,
1111                keyboard.top,
1112                keyboard.right,
1113                keyboard.bottom,
1114            ),
1115            Duration::from_millis(100),
1116        )
1117        .curve(Curves::decelerate())
1118        .child(content),
1119    )
1120    .into_widget()
1121}
1122
1123/// `ProcessLayoutRootKey`: Escape runs the close action; Enter presses the default button.
1124fn layout_root_key(
1125    app: &mut App,
1126    dialog: Handle<ContentDialog>,
1127    event: &KeyEvent,
1128) -> KeyEventResult {
1129    if !matches!(event, KeyEvent::Down(_)) || !app.contains(dialog) {
1130        return KeyEventResult::Ignored;
1131    }
1132    match event.logical_key() {
1133        LogicalKeyboardKey::ESCAPE => {
1134            dialog.execute_close_action(app);
1135            KeyEventResult::Handled
1136        }
1137        LogicalKeyboardKey::ENTER | LogicalKeyboardKey::NUMPAD_ENTER
1138            if dialog.invoke_default_button(app) =>
1139        {
1140            KeyEventResult::Handled
1141        }
1142        _ => KeyEventResult::Ignored,
1143    }
1144}
1145
1146impl ContentDialogPresenterState {
1147    /// `BackgroundElement`: the bordered, rounded, shadowed dialog between its minimum and
1148    /// maximum sizes, as wide as its content asks.
1149    fn background_element(
1150        self: Handle<Self>,
1151        app: &mut App,
1152        resources: &ThemeResources,
1153    ) -> WidgetRef {
1154        let dialog = app.get(self.widget(app).dialog);
1155        let full_size = dialog.full_size_desired;
1156        let r = &resources;
1157        let dialog_space = self.dialog_space(app, resources);
1158        let border = ControlBorder::new(
1159            Brush::Solid(r.content_dialog_background),
1160            Brush::Solid(r.content_dialog_border_brush),
1161        )
1162        .border_thickness_ltrb(r.content_dialog_border_width)
1163        .corner_radius(r.overlay_corner_radius[0])
1164        .background_sizing(BackgroundSizing::InnerBorderEdge)
1165        .child(
1166            // `DialogSpace` rounds its own corners with `OverlayCornerRadius`.
1167            ClipRRect::new()
1168                .border_radius(BorderRadius::circular(r.overlay_corner_radius[0]).into())
1169                .child(dialog_space),
1170        );
1171        let shadowed = CustomPaint::new()
1172            .painter(PopupShadow::for_dialog(resources, resources.theme))
1173            .child(border);
1174        let sized = IntrinsicWidth::new().child(shadowed);
1175        // FullDialogSizing stretches the dialog to the window's height, up to its maximum.
1176        let sized = if full_size {
1177            SizedBox::new()
1178                .height(f64::INFINITY)
1179                .child(sized)
1180                .into_widget()
1181        } else {
1182            sized.into_widget()
1183        };
1184        ConstrainedBox::new(
1185            BoxConstraints::new()
1186                .min_width(r.content_dialog_min_width)
1187                .max_width(r.content_dialog_max_width)
1188                .min_height(r.content_dialog_min_height)
1189                .max_height(r.content_dialog_max_height),
1190        )
1191        .child(sized)
1192        .into_widget()
1193    }
1194
1195    /// `DialogSpace`: the content area over the command space. The content area takes what the
1196    /// buttons leave, clipped, as its scroll viewer with scrolling disabled does; in full size it
1197    /// takes all of it.
1198    fn dialog_space(self: Handle<Self>, app: &mut App, resources: &ThemeResources) -> WidgetRef {
1199        let full_size = app.get(self.widget(app).dialog).full_size_desired;
1200        let content_area = ClipRect::new().child(self.content_area(app, resources));
1201        let fit = if full_size {
1202            FlexFit::Tight
1203        } else {
1204            FlexFit::Loose
1205        };
1206        let mut children = vec![Flexible::new(content_area).fit(fit).into_widget()];
1207        if let Some(command_space) = self.command_space(app, resources) {
1208            children.push(command_space);
1209        }
1210        Column::new()
1211            .main_axis_size(MainAxisSize::Min)
1212            .cross_axis_alignment(CrossAxisAlignment::Stretch)
1213            .children(children)
1214            .into_widget()
1215    }
1216
1217    /// The grid inside `ContentScrollViewer`: `Title` above `Content`, on the top overlay, over
1218    /// the separator.
1219    fn content_area(self: Handle<Self>, app: &mut App, resources: &ThemeResources) -> WidgetRef {
1220        let dialog = app.get(self.widget(app).dialog);
1221        let r = &resources;
1222        let foreground = r.content_dialog_foreground;
1223        let mut children = Vec::new();
1224        if let Some(title) = dialog.title.clone() {
1225            // `Title`: left aligned, where `Content` stretches.
1226            children.push(
1227                Align::new()
1228                    .alignment(AlignmentDirectional::TOP_START.into())
1229                    .child(Margin::new(
1230                        r.content_dialog_title_margin,
1231                        DefaultTextStyle::new(
1232                            control_text_style(resources, 20.0, FontWeight::W600, foreground),
1233                            title,
1234                        )
1235                        .max_lines(2)
1236                        .soft_wrap(true),
1237                    ))
1238                    .into_widget(),
1239            );
1240        }
1241        if let Some(content) = dialog.content.clone() {
1242            let focus = app
1243                .get(self)
1244                .content_focus
1245                .clone()
1246                .expect("an initialized presenter");
1247            children.push(
1248                Focus::new(DefaultTextStyle::new(
1249                    control_text_style(
1250                        resources,
1251                        r.control_content_theme_font_size,
1252                        FontWeight::NORMAL,
1253                        foreground,
1254                    ),
1255                    content,
1256                ))
1257                .focus_node(focus.erase())
1258                .can_request_focus(false)
1259                .skip_traversal(true)
1260                .into_widget(),
1261            );
1262        }
1263        ControlBorder::new(
1264            Brush::Solid(r.content_dialog_top_overlay),
1265            Brush::Solid(r.content_dialog_separator_border_brush),
1266        )
1267        .border_thickness_ltrb(r.content_dialog_separator_thickness)
1268        .padding(r.content_dialog_padding)
1269        .child(
1270            Column::new()
1271                .main_axis_size(MainAxisSize::Min)
1272                .cross_axis_alignment(CrossAxisAlignment::Stretch)
1273                .children(children),
1274        )
1275        .into_widget()
1276    }
1277
1278    /// `CommandSpace`: the buttons with text, in the columns their visibility state gives them;
1279    /// nothing when no button has text.
1280    fn command_space(
1281        self: Handle<Self>,
1282        app: &mut App,
1283        resources: &ThemeResources,
1284    ) -> Option<WidgetRef> {
1285        let dialog_handle = self.widget(app).dialog;
1286        let dialog = app.get(dialog_handle);
1287        let layout = ButtonsVisibilityState::of(
1288            !dialog.primary_button_text.is_empty(),
1289            !dialog.secondary_button_text.is_empty(),
1290            !dialog.close_button_text.is_empty(),
1291        )
1292        .layout(resources)?;
1293        let accented = accented_button(dialog.default_button, self.focused_button(app));
1294        let dialog = app.get(dialog_handle);
1295        // `PrimaryButton`, `SecondaryButton` and `CloseButton`.
1296        let buttons = [
1297            (
1298                ContentDialogButton::Primary,
1299                layout.primary,
1300                dialog.primary_button_text.clone(),
1301                dialog.is_primary_button_enabled,
1302            ),
1303            (
1304                ContentDialogButton::Secondary,
1305                layout.secondary,
1306                dialog.secondary_button_text.clone(),
1307                dialog.is_secondary_button_enabled,
1308            ),
1309            (
1310                ContentDialogButton::Close,
1311                layout.close,
1312                dialog.close_button_text.clone(),
1313                true,
1314            ),
1315        ];
1316        let cells: Vec<WidgetRef> = buttons
1317            .into_iter()
1318            .filter_map(|(button, column, text, enabled)| {
1319                let column = column?;
1320                let style = if button == accented {
1321                    ButtonStyle::Accent
1322                } else {
1323                    ButtonStyle::Default
1324                };
1325                let node = self.focus_of(app, button);
1326                let click =
1327                    Listener::new(move |app| dialog_handle.command_button_clicked(app, button));
1328                let button = Button::text(text, click)
1329                    .style(style)
1330                    .is_enabled(enabled)
1331                    .focus_node(node.erase());
1332                Some(GridCell::new(button).column(column).into_widget())
1333            })
1334            .collect();
1335        let background = resources.content_dialog_background;
1336        Some(
1337            Grid::new()
1338                .column_definitions(layout.columns.map(ColumnDefinition::new))
1339                .padding(resources.content_dialog_padding)
1340                .background(Brush::Solid(background))
1341                .children(cells)
1342                .into_widget(),
1343        )
1344    }
1345
1346    /// The command button that has the focus, if one has.
1347    fn focused_button(self: Handle<Self>, app: &mut App) -> Option<ContentDialogButton> {
1348        let buttons = app.get(self).button_focus.clone();
1349        buttons
1350            .into_iter()
1351            .find(|(_, node)| node.as_node().has_focus(app))
1352            .map(|(button, _)| button)
1353    }
1354
1355    fn focus_of(self: Handle<Self>, app: &App, button: ContentDialogButton) -> Ref<FocusNode> {
1356        app.get(self)
1357            .button_focus
1358            .iter()
1359            .find(|(candidate, _)| *candidate == button)
1360            .map(|(_, node)| node.clone())
1361            .expect("a command button")
1362    }
1363
1364    /// `OnLayoutRootLoaded` and `OnPopupOpened`: once the dialog is laid out, its initial focus is
1365    /// set and it has opened.
1366    fn open_after_first_frame(self: Handle<Self>, app: &mut App) {
1367        SchedulerBinding::add_post_frame_callback(
1368            app,
1369            FrameCallback::new(move |app, _| {
1370                if !self.mounted(app) {
1371                    return;
1372                }
1373                let dialog = self.widget(app).dialog;
1374                let Some(route) = app.get(self).route else {
1375                    return;
1376                };
1377                self.set_initial_focus(app);
1378                dialog.finish_opening(app, route);
1379            }),
1380            View::maybe_id_of(app, self.context(app)),
1381        );
1382    }
1383
1384    /// `SetInitialFocusElement`: the content's first focusable element, else the default button,
1385    /// else the first command button that can take the focus.
1386    fn set_initial_focus(self: Handle<Self>, app: &mut App) {
1387        let content = app
1388            .get(self)
1389            .content_focus
1390            .handle()
1391            .expect("an initialized presenter");
1392        let first_in_content = content
1393            .as_node()
1394            .traversal_descendants(app)
1395            .into_iter()
1396            .find(|node| node.can_request_focus(app));
1397        if let Some(node) = first_in_content {
1398            node.request_focus(app, None);
1399            return;
1400        }
1401        let default = app.get(self.widget(app).dialog).default_button;
1402        let candidates = std::iter::once(default).chain([
1403            ContentDialogButton::Primary,
1404            ContentDialogButton::Secondary,
1405            ContentDialogButton::Close,
1406        ]);
1407        for button in candidates {
1408            if button == ContentDialogButton::None {
1409                continue;
1410            }
1411            let node = self.focus_of(app, button).as_node();
1412            if node.context(app).is_some() && node.can_request_focus(app) {
1413                node.request_focus(app, None);
1414                return;
1415            }
1416        }
1417    }
1418}
1419
1420#[cfg(test)]
1421mod tests {
1422    use super::*;
1423
1424    #[test]
1425    fn each_set_of_button_texts_picks_its_columns() {
1426        let r = ThemeResources::new(Theme::Light, AccentPalette::default());
1427        let layout = |primary, secondary, close| {
1428            ButtonsVisibilityState::of(primary, secondary, close).layout(&r)
1429        };
1430        let all = layout(true, true, true).unwrap();
1431        assert_eq!(
1432            (all.primary, all.secondary, all.close),
1433            (Some(0), Some(2), Some(4))
1434        );
1435        assert_eq!(
1436            all.columns[1],
1437            GridLength::pixel(r.content_dialog_button_spacing)
1438        );
1439        let secondary_and_close = layout(false, true, true).unwrap();
1440        assert_eq!(
1441            (secondary_and_close.secondary, secondary_and_close.close),
1442            (Some(0), Some(4))
1443        );
1444        let primary_alone = layout(true, false, false).unwrap();
1445        assert_eq!(primary_alone.primary, Some(4));
1446        assert_eq!(
1447            ButtonsVisibilityState::of(false, false, false),
1448            ButtonsVisibilityState::NoneVisible
1449        );
1450        assert_eq!(layout(false, false, false), None);
1451    }
1452
1453    #[test]
1454    fn focusing_another_command_button_takes_the_accent_from_the_default() {
1455        use ContentDialogButton::{Close, Primary};
1456        assert_eq!(accented_button(Primary, None), Primary);
1457        assert_eq!(accented_button(Primary, Some(Primary)), Primary);
1458        assert_eq!(
1459            accented_button(Primary, Some(Close)),
1460            ContentDialogButton::None
1461        );
1462        assert_eq!(
1463            accented_button(ContentDialogButton::None, Some(Close)),
1464            ContentDialogButton::None
1465        );
1466    }
1467
1468    #[test]
1469    fn opening_and_closing_fade_in_83_ms_and_scale_over_their_own_durations() {
1470        let fraction = |part: Duration, whole: Duration| part.as_secs_f64() / whole.as_secs_f64();
1471        let (opacity, scale) = open_close_transition(AnimationStatus::Forward, 0.0);
1472        assert_eq!((opacity, scale), (0.0, SCALED_FACTOR));
1473        let faded_in = fraction(OPACITY_CHANGE_DURATION, OPEN_SCALE_DURATION);
1474        let (opacity, scale) = open_close_transition(AnimationStatus::Forward, faded_in);
1475        assert!((opacity - 1.0).abs() < 1e-9 && scale > 1.0);
1476        assert_eq!(
1477            open_close_transition(AnimationStatus::Completed, 1.0),
1478            (1.0, 1.0)
1479        );
1480        let faded_out = 1.0 - fraction(OPACITY_CHANGE_DURATION, CLOSE_SCALE_DURATION);
1481        let (opacity, scale) = open_close_transition(AnimationStatus::Reverse, faded_out);
1482        assert!(opacity.abs() < 1e-9 && scale > 1.0 && scale < SCALED_FACTOR);
1483        let (_, scale) = open_close_transition(AnimationStatus::Dismissed, 0.0);
1484        assert!((scale - SCALED_FACTOR).abs() < 1e-9);
1485    }
1486}