1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
27pub enum ContentDialogButton {
28 #[default]
29 None,
30 Primary,
31 Secondary,
32 Close,
33}
34
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
38pub enum ContentDialogResult {
39 #[default]
40 None,
41 Primary,
42 Secondary,
43}
44
45pub type ContentDialogButtonClickDeferral = Deferral;
48
49pub type ContentDialogClosingDeferral = Deferral;
51
52pub struct ContentDialogButtonClickEventArgs {
55 cancel: Cell<bool>,
56 deferrals: Rc<DeferralManager>,
57 generation: u64,
58}
59
60impl ContentDialogButtonClickEventArgs {
61 pub fn cancel(&self) -> bool {
63 self.cancel.get()
64 }
65
66 pub fn set_cancel(&self, cancel: bool) {
68 self.cancel.set(cancel);
69 }
70
71 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
85pub struct ContentDialogClosingEventArgs {
88 result: ContentDialogResult,
89 cancel: Cell<bool>,
90 deferrals: Rc<DeferralManager>,
91 generation: u64,
92}
93
94impl ContentDialogClosingEventArgs {
95 pub fn result(&self) -> ContentDialogResult {
97 self.result
98 }
99
100 pub fn cancel(&self) -> bool {
102 self.cancel.get()
103 }
104
105 pub fn set_cancel(&self, cancel: bool) {
107 self.cancel.set(cancel);
108 }
109
110 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#[derive(Clone, Copy, Debug)]
127pub struct ContentDialogClosedEventArgs {
128 pub result: ContentDialogResult,
130}
131
132pub type ContentDialogButtonClickHandler =
134 Rc<dyn Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>)>;
135
136pub type ContentDialogClosingHandler = Rc<dyn Fn(&mut App, &Rc<ContentDialogClosingEventArgs>)>;
138
139pub type ContentDialogClosedHandler = Rc<dyn Fn(&mut App, ContentDialogClosedEventArgs)>;
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub enum ContentDialogError {
145 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#[derive(Default)]
162struct ContentDialogMetadata {
163 open: HashMap<HandleId, Handle<ContentDialog>>,
164}
165
166pub struct ContentDialog {
169 pub title: Option<WidgetRef>,
172
173 pub content: Option<WidgetRef>,
175
176 pub primary_button_text: String,
178
179 pub secondary_button_text: String,
181
182 pub close_button_text: String,
185
186 pub is_primary_button_enabled: bool,
188
189 pub is_secondary_button_enabled: bool,
191
192 pub default_button: ContentDialogButton,
194
195 pub full_size_desired: bool,
197
198 pub primary_button_click: Option<ContentDialogButtonClickHandler>,
200
201 pub secondary_button_click: Option<ContentDialogButtonClickHandler>,
203
204 pub close_button_click: Option<ContentDialogButtonClickHandler>,
206
207 pub opened: Option<Listener>,
209
210 pub closing: Option<ContentDialogClosingHandler>,
212
213 pub closed: Option<ContentDialogClosedHandler>,
215
216 notifier: ChangeNotifierData,
218
219 showing: Option<Showing>,
221
222 button_click_deferrals: Rc<DeferralManager>,
225
226 closing_deferrals: Rc<DeferralManager>,
228
229 disposed: bool,
231}
232
233struct Showing {
235 route: AnyRoute,
236 navigator: Handle<NavigatorState>,
237
238 completion: Completer<ContentDialogResult>,
240
241 result: ContentDialogResult,
243
244 hide_in_progress: bool,
246
247 skip_closing_event: bool,
250
251 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 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 #[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 #[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 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 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 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 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 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 pub fn default_button(self: Handle<Self>, app: &mut App, button: ContentDialogButton) {
345 self.change(app, |dialog| dialog.default_button = button)
346 }
347
348 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 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 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 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 pub fn opened(self: Handle<Self>, app: &mut App, handler: Listener) {
382 app.get_mut(self).opened = Some(handler);
383 }
384
385 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 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 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 pub fn hide(self: Handle<Self>, app: &mut App) {
445 self.hide_internal(app, ContentDialogResult::None);
446 }
447
448 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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 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 fn layout(self, r: &ThemeResources) -> Option<CommandLayout> {
754 use ButtonsVisibilityState::*;
755 let spacing = GridLength::pixel(r.content_dialog_button_spacing);
756 let mut columns = [
758 GridLength::STAR,
759 GridLength::pixel(0.0),
760 GridLength::pixel(0.0),
761 spacing,
762 GridLength::STAR,
763 ];
764 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#[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
798fn 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
810const OPEN_SCALE_DURATION: Duration = Duration::from_millis(250);
813
814const CLOSE_SCALE_DURATION: Duration = Duration::from_millis(167);
817
818const OPACITY_CHANGE_DURATION: Duration = Duration::from_millis(83);
820
821const SCALED_FACTOR: f64 = 1.05;
823
824fn 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
851struct 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 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 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#[derive(Debug)]
947struct ContentDialogPresenter {
948 dialog: Handle<ContentDialog>,
949
950 animation: AnimationRef<f64>,
952}
953
954struct ContentDialogPresenterState {
956 state: StateData<ContentDialogPresenter>,
957
958 route: Option<AnyRoute>,
960
961 content_focus: Option<Ref<FocusNode>>,
963
964 button_focus: Vec<(ContentDialogButton, Ref<FocusNode>)>,
966
967 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 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 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 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
1095fn 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
1123fn 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 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 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 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 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 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 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 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 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 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 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 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}