1#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
2#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
3#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
9#![warn(unused_extern_crates)]
10#![warn(missing_docs)]
11
12zng_wgt::enable_widget_macros!();
13
14use std::{fmt, ops, path::PathBuf, sync::Arc};
15
16use bitflags::bitflags;
17use parking_lot::Mutex;
18use zng_ext_l10n::l10n;
19use zng_ext_window::{WINDOW_CLOSE_REQUESTED_EVENT, WINDOWS, WindowCloseRequestedArgs};
20use zng_var::{ContextInitHandle, animation::easing};
21use zng_view_api::dialog as native_api;
22use zng_wgt::{prelude::*, *};
23use zng_wgt_container::Container;
24use zng_wgt_fill::background_color;
25use zng_wgt_filter::drop_shadow;
26use zng_wgt_input::focus::FocusableMix;
27use zng_wgt_layer::{
28 AnchorMode,
29 popup::{ContextCapture, POPUP, POPUP_CLOSE_REQUESTED_EVENT},
30};
31use zng_wgt_style::{Style, StyleMix, impl_style_fn, style_fn};
32use zng_wgt_text::Text;
33use zng_wgt_text_input::selectable::SelectableText;
34use zng_wgt_wrap::Wrap;
35
36pub mod backdrop;
37
38pub use zng_view_api::dialog::{FileDialogFilters, FileDialogResponse};
39
40#[widget($crate::Dialog)]
42pub struct Dialog(FocusableMix<StyleMix<Container>>);
43impl Dialog {
44 fn widget_intrinsic(&mut self) {
45 self.style_intrinsic(STYLE_FN_VAR, property_id!(self::style_fn));
46
47 self.widget_builder()
48 .push_build_action(|b| b.push_intrinsic(NestGroup::EVENT, "dialog-closing", dialog_closing_node));
49
50 widget_set! {
51 self;
52 style_base_fn = style_fn!(|_| DefaultStyle!());
53
54 focus_on_init = true;
55 return_focus_on_deinit = true;
56
57 when *#is_close_delaying {
58 interactive = false;
59 }
60 }
61 }
62
63 widget_impl! {
64 pub zng_wgt_layer::popup::is_close_delaying(state: impl IntoVar<bool>);
70
71 pub on_dialog_close_canceled(args: impl WidgetHandler<DialogCloseCanceledArgs>);
75 }
76}
77impl_style_fn!(Dialog);
78
79fn dialog_closing_node(child: impl UiNode) -> impl UiNode {
80 match_node(child, move |_, op| {
81 match op {
82 UiNodeOp::Init => {
83 let id = WIDGET.id();
85 let ctx = DIALOG_CTX.get();
86 let default_response = DEFAULT_RESPONSE_VAR.actual_var();
87 let responder = ctx.responder.clone();
88 let handle = WINDOW_CLOSE_REQUESTED_EVENT.on_pre_event(app_hn!(|args: &WindowCloseRequestedArgs, _| {
89 if responder.get().is_waiting() {
91 let path = WINDOWS.widget_info(id).unwrap().path();
94 if args.windows.contains(&path.window_id()) {
95 if let Some(default) = default_response.get() {
98 responder.respond(default);
100 zng_wgt_layer::popup::POPUP_CLOSE_CMD
102 .scoped(path.window_id())
103 .notify_param(path.widget_id());
104 } else {
105 args.propagation().stop();
107 DIALOG_CLOSE_CANCELED_EVENT.notify(DialogCloseCanceledArgs::now(path));
108 }
109 }
110 }
111 }));
112 WIDGET.push_event_handle(handle);
113 WIDGET.sub_event(&POPUP_CLOSE_REQUESTED_EVENT);
114 }
115 UiNodeOp::Event { update } => {
116 if let Some(args) = POPUP_CLOSE_REQUESTED_EVENT.on(update) {
117 let ctx = DIALOG_CTX.get();
119 if ctx.responder.get().is_waiting() {
120 if let Some(r) = DEFAULT_RESPONSE_VAR.get() {
122 ctx.responder.respond(r);
123 } else {
124 args.propagation().stop();
125 DIALOG_CLOSE_CANCELED_EVENT.notify(DialogCloseCanceledArgs::now(WIDGET.info().path()));
126 }
127 }
128 }
129 }
130 _ => (),
131 }
132 })
133}
134
135event_args! {
136 pub struct DialogCloseCanceledArgs {
138 pub target: WidgetPath,
140
141 ..
142
143 fn delivery_list(&self, list: &mut UpdateDeliveryList) {
144 list.insert_wgt(&self.target);
145 }
146 }
147}
148event! {
149 pub static DIALOG_CLOSE_CANCELED_EVENT: DialogCloseCanceledArgs;
153}
154event_property! {
155 pub fn dialog_close_canceled {
159 event: DIALOG_CLOSE_CANCELED_EVENT,
160 args: DialogCloseCanceledArgs,
161 }
162}
163
164#[widget($crate::DefaultStyle)]
166pub struct DefaultStyle(Style);
167impl DefaultStyle {
168 fn widget_intrinsic(&mut self) {
169 let highlight_color = var(colors::BLACK.transparent());
170 widget_set! {
171 self;
172
173 replace = true;
174
175 background_color = light_dark(rgb(0.7, 0.7, 0.7), rgb(0.3, 0.3, 0.3));
176 drop_shadow = {
177 offset: 4,
178 blur_radius: 6,
179 color: colors::BLACK.with_alpha(50.pct()),
180 };
181
182 corner_radius = 8;
183 clip_to_bounds = true;
184
185 margin = 10;
186 zng_wgt_container::padding = 15;
187
188 align = Align::CENTER;
189
190 zng_wgt_container::child_out_top = Container! {
191 corner_radius = 0;
192 background_color = light_dark(rgb(0.85, 0.85, 0.85), rgb(0.15, 0.15, 0.15));
193 child = presenter((), TITLE_VAR);
194 child_align = Align::START;
195 padding = (4, 8);
196 zng_wgt_text::font_weight = zng_ext_font::FontWeight::BOLD;
197 }, 0;
198
199 zng_wgt_container::child_out_bottom = presenter(RESPONSES_VAR, wgt_fn!(|responses: Responses| {
200 Wrap! {
201 corner_radius = 0;
202 background_color = light_dark(rgb(0.85, 0.85, 0.85), rgb(0.15, 0.15, 0.15));
203 children_align = Align::END;
204 zng_wgt_container::padding = 3;
205 spacing = 3;
206 children = {
207 let last = responses.len().saturating_sub(1);
208 responses.0
209 .into_iter()
210 .enumerate()
211 .map(|(i, r)| presenter(
212 DialogButtonArgs { response: r, is_last: i == last },
213 BUTTON_FN_VAR
214 ).boxed())
215 .collect::<UiVec>()
216 };
217 }
218 })), 0;
219
220 zng_wgt_container::child_out_left = Container! {
221 child = presenter((), ICON_VAR);
222 child_align = Align::TOP;
223 }, 0;
224
225 zng_wgt_container::child = presenter((), CONTENT_VAR);
226
227 #[easing(250.ms())]
228 zng_wgt_filter::opacity = 30.pct();
229 #[easing(250.ms())]
230 zng_wgt_transform::transform = Transform::new_translate_y(-10).scale(98.pct());
231 when *#is_inited && !*#zng_wgt_layer::popup::is_close_delaying {
232 zng_wgt_filter::opacity = 100.pct();
233 zng_wgt_transform::transform = Transform::identity();
234 }
235
236 zng_wgt_fill::foreground_highlight = {
237 offsets: 0,
238 widths: 2,
239 sides: highlight_color.map_into(),
240 };
241 on_dialog_close_canceled = hn!(highlight_color, |_| {
242 let c = colors::ACCENT_COLOR_VAR.rgba().get();
243 let mut repeats = 0;
244 highlight_color.sequence(move |cv| {
245 repeats += 1;
246 if repeats <= 2 {
247 cv.set_ease(c, c.with_alpha(0.pct()), 120.ms(), easing::linear)
248 } else {
249 zng_var::animation::AnimationHandle::dummy()
250 }
251 }).perm();
252 });
253 }
254 }
255}
256
257context_var! {
258 pub static TITLE_VAR: WidgetFn<()> = WidgetFn::nil();
260 pub static ICON_VAR: WidgetFn<()> = WidgetFn::nil();
262 pub static CONTENT_VAR: WidgetFn<()> = WidgetFn::nil();
264 pub static BUTTON_FN_VAR: WidgetFn<DialogButtonArgs> = WidgetFn::new(default_button_fn);
266 pub static RESPONSES_VAR: Responses = Responses::ok();
268 pub static DEFAULT_RESPONSE_VAR: Option<Response> = None;
270 pub static NATIVE_DIALOGS_VAR: DialogKind = DIALOG.native_dialogs();
272}
273
274pub fn default_button_fn(args: DialogButtonArgs) -> impl UiNode {
276 zng_wgt_button::Button! {
277 child = Text!(args.response.label.clone());
278 on_click = hn_once!(|a: &zng_wgt_input::gesture::ClickArgs| {
279 a.propagation().stop();
280 DIALOG.respond(args.response);
281 });
282 focus_on_init = args.is_last;
283 when args.is_last {
284 style_fn = zng_wgt_button::PrimaryStyle!();
285 }
286 }
287}
288
289#[derive(Debug, Clone, PartialEq)]
293#[non_exhaustive]
294pub struct DialogButtonArgs {
295 pub response: Response,
297 pub is_last: bool,
299}
300impl DialogButtonArgs {
301 pub fn new(response: Response, is_last: bool) -> Self {
303 Self { response, is_last }
304 }
305}
306
307#[property(CONTEXT, default(NilUiNode), widget_impl(Dialog))]
311pub fn title(child: impl UiNode, title: impl UiNode) -> impl UiNode {
312 with_context_var(child, TITLE_VAR, WidgetFn::singleton(title))
313}
314
315#[property(CONTEXT, default(NilUiNode), widget_impl(Dialog))]
319pub fn icon(child: impl UiNode, icon: impl UiNode) -> impl UiNode {
320 with_context_var(child, ICON_VAR, WidgetFn::singleton(icon))
321}
322
323#[property(CONTEXT, default(FillUiNode), widget_impl(Dialog))]
327pub fn content(child: impl UiNode, content: impl UiNode) -> impl UiNode {
328 with_context_var(child, CONTENT_VAR, WidgetFn::singleton(content))
329}
330
331#[property(CONTEXT, default(BUTTON_FN_VAR), widget_impl(Dialog))]
333pub fn button_fn(child: impl UiNode, button: impl IntoVar<WidgetFn<DialogButtonArgs>>) -> impl UiNode {
334 with_context_var(child, BUTTON_FN_VAR, button)
335}
336
337#[property(CONTEXT, default(RESPONSES_VAR), widget_impl(Dialog))]
339pub fn responses(child: impl UiNode, responses: impl IntoVar<Responses>) -> impl UiNode {
340 with_context_var(child, RESPONSES_VAR, responses)
341}
342
343#[property(CONTEXT, default(DEFAULT_RESPONSE_VAR), widget_impl(Dialog))]
345pub fn default_response(child: impl UiNode, response: impl IntoVar<Option<Response>>) -> impl UiNode {
346 with_context_var(child, DEFAULT_RESPONSE_VAR, response)
347}
348
349#[property(CONTEXT, default(NATIVE_DIALOGS_VAR))]
353pub fn native_dialogs(child: impl UiNode, dialogs: impl IntoVar<DialogKind>) -> impl UiNode {
354 with_context_var(child, NATIVE_DIALOGS_VAR, dialogs)
355}
356
357#[widget($crate::InfoStyle)]
361pub struct InfoStyle(DefaultStyle);
362impl InfoStyle {
363 fn widget_intrinsic(&mut self) {
364 widget_set! {
365 self;
366 icon = Container! {
367 child = ICONS.req(["dialog-info", "info"]);
368 zng_wgt_size_offset::size = 48;
369 zng_wgt_text::font_color = colors::AZURE;
370 padding = 5;
371 };
372 default_response = Response::ok();
373 }
374 }
375}
376
377#[widget($crate::WarnStyle)]
381pub struct WarnStyle(DefaultStyle);
382impl WarnStyle {
383 fn widget_intrinsic(&mut self) {
384 widget_set! {
385 self;
386 icon = Container! {
387 child = ICONS.req(["dialog-warn", "warning"]);
388 zng_wgt_size_offset::size = 48;
389 zng_wgt_text::font_color = colors::ORANGE;
390 padding = 5;
391 };
392 }
393 }
394}
395
396#[widget($crate::ErrorStyle)]
400pub struct ErrorStyle(DefaultStyle);
401impl ErrorStyle {
402 fn widget_intrinsic(&mut self) {
403 widget_set! {
404 self;
405 icon = Container! {
406 child = ICONS.req(["dialog-error", "error"]);
407 zng_wgt_size_offset::size = 48;
408 zng_wgt_text::font_color = rgb(209, 29, 29);
409 padding = 5;
410 };
411 }
412 }
413}
414
415#[widget($crate::AskStyle)]
419pub struct AskStyle(DefaultStyle);
420impl AskStyle {
421 fn widget_intrinsic(&mut self) {
422 widget_set! {
423 self;
424 icon = Container! {
425 child = ICONS.req(["dialog-question", "question-mark"]);
426 zng_wgt_size_offset::size = 48;
427 zng_wgt_text::font_color = colors::AZURE;
428 padding = 5;
429 };
430 responses = Responses::no_yes();
431 }
432 }
433}
434
435#[widget($crate::ConfirmStyle)]
439pub struct ConfirmStyle(DefaultStyle);
440impl ConfirmStyle {
441 fn widget_intrinsic(&mut self) {
442 widget_set! {
443 self;
444 icon = Container! {
445 child = ICONS.req(["dialog-confirm", "question-mark"]);
446 zng_wgt_size_offset::size = 48;
447 zng_wgt_text::font_color = colors::ORANGE;
448 padding = 5;
449 };
450 responses = Responses::cancel_ok();
451 }
452 }
453}
454
455#[derive(Clone)]
457#[non_exhaustive]
458pub struct Response {
459 pub name: Txt,
461 pub label: BoxedVar<Txt>,
463}
464impl fmt::Debug for Response {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 write!(f, "{:?}", self.name)
467 }
468}
469impl PartialEq for Response {
470 fn eq(&self, other: &Self) -> bool {
471 self.name == other.name
472 }
473}
474impl Response {
475 pub fn new(name: impl Into<Txt>, label: impl IntoVar<Txt>) -> Self {
477 Self {
478 name: name.into(),
479 label: label.into_var().boxed(),
480 }
481 }
482
483 pub fn ok() -> Self {
485 Self::new("Ok", l10n!("response-ok", "Ok"))
486 }
487
488 pub fn cancel() -> Self {
490 Self::new("cancel", l10n!("response-cancel", "Cancel"))
491 }
492
493 pub fn yes() -> Self {
495 Self::new("yes", l10n!("response-yes", "Yes"))
496 }
497 pub fn no() -> Self {
499 Self::new("no", l10n!("response-no", "No"))
500 }
501
502 pub fn close() -> Self {
504 Self::new("close", l10n!("response-close", "Close"))
505 }
506}
507impl_from_and_into_var! {
508 fn from(native: native_api::MsgDialogResponse) -> Response {
509 match native {
510 native_api::MsgDialogResponse::Ok => Response::ok(),
511 native_api::MsgDialogResponse::Yes => Response::yes(),
512 native_api::MsgDialogResponse::No => Response::no(),
513 native_api::MsgDialogResponse::Cancel => Response::cancel(),
514 native_api::MsgDialogResponse::Error(e) => Response {
515 name: Txt::from_static("native-error"),
516 label: LocalVar(e).boxed(),
517 },
518 _ => unimplemented!(),
519 }
520 }
521 fn from(response: Response) -> Option<Response>;
522}
523
524#[derive(Clone, PartialEq, Debug)]
526pub struct Responses(pub Vec<Response>);
527impl Responses {
528 pub fn new(r: impl Into<Response>) -> Self {
530 Self(vec![r.into()])
531 }
532
533 pub fn with(mut self, response: impl Into<Response>) -> Self {
535 self.push(response.into());
536 self
537 }
538
539 pub fn ok() -> Self {
541 Response::ok().into()
542 }
543
544 pub fn close() -> Self {
546 Response::close().into()
547 }
548
549 pub fn no_yes() -> Self {
551 vec![Response::no(), Response::yes()].into()
552 }
553
554 pub fn cancel_ok() -> Self {
556 vec![Response::cancel(), Response::ok()].into()
557 }
558}
559impl ops::Deref for Responses {
560 type Target = Vec<Response>;
561
562 fn deref(&self) -> &Self::Target {
563 &self.0
564 }
565}
566impl ops::DerefMut for Responses {
567 fn deref_mut(&mut self) -> &mut Self::Target {
568 &mut self.0
569 }
570}
571impl_from_and_into_var! {
572 fn from(response: Response) -> Responses {
573 Responses::new(response)
574 }
575 fn from(responses: Vec<Response>) -> Responses {
576 Responses(responses)
577 }
578}
579
580pub struct DIALOG;
588impl DIALOG {
589 pub fn info(&self, title: impl IntoVar<Txt>, msg: impl IntoVar<Txt>) -> ResponseVar<()> {
591 self.message(
592 msg.into_var().boxed(),
593 title.into_var().boxed(),
594 DialogKind::INFO,
595 &|| InfoStyle!(),
596 native_api::MsgDialogIcon::Info,
597 native_api::MsgDialogButtons::Ok,
598 )
599 .map_response(|_| ())
600 }
601
602 pub fn warn(&self, title: impl IntoVar<Txt>, msg: impl IntoVar<Txt>) -> ResponseVar<()> {
604 self.message(
605 msg.into_var().boxed(),
606 title.into_var().boxed(),
607 DialogKind::WARN,
608 &|| WarnStyle!(),
609 native_api::MsgDialogIcon::Warn,
610 native_api::MsgDialogButtons::Ok,
611 )
612 .map_response(|_| ())
613 }
614
615 pub fn error(&self, title: impl IntoVar<Txt>, msg: impl IntoVar<Txt>) -> ResponseVar<()> {
617 self.message(
618 msg.into_var().boxed(),
619 title.into_var().boxed(),
620 DialogKind::ERROR,
621 &|| ErrorStyle!(),
622 native_api::MsgDialogIcon::Error,
623 native_api::MsgDialogButtons::Ok,
624 )
625 .map_response(|_| ())
626 }
627
628 pub fn ask(&self, title: impl IntoVar<Txt>, question: impl IntoVar<Txt>) -> ResponseVar<bool> {
630 self.message(
631 question.into_var().boxed(),
632 title.into_var().boxed(),
633 DialogKind::ASK,
634 &|| AskStyle!(),
635 native_api::MsgDialogIcon::Info,
636 native_api::MsgDialogButtons::YesNo,
637 )
638 .map_response(|r| r.name == "yes")
639 }
640
641 pub fn confirm(&self, title: impl IntoVar<Txt>, question: impl IntoVar<Txt>) -> ResponseVar<bool> {
643 self.message(
644 question.into_var().boxed(),
645 title.into_var().boxed(),
646 DialogKind::CONFIRM,
647 &|| ConfirmStyle!(),
648 native_api::MsgDialogIcon::Warn,
649 native_api::MsgDialogButtons::OkCancel,
650 )
651 .map_response(|r| r.name == "ok")
652 }
653
654 pub fn open_file(
656 &self,
657 title: impl IntoVar<Txt>,
658 starting_dir: impl Into<PathBuf>,
659 starting_name: impl IntoVar<Txt>,
660 filters: impl Into<FileDialogFilters>,
661 ) -> ResponseVar<FileDialogResponse> {
662 WINDOWS.native_file_dialog(
663 WINDOW.id(),
664 native_api::FileDialog::new(
665 title.into_var().get(),
666 starting_dir.into(),
667 starting_name.into_var().get(),
668 filters.into().build(),
669 native_api::FileDialogKind::OpenFile,
670 ),
671 )
672 }
673
674 pub fn open_files(
676 &self,
677 title: impl IntoVar<Txt>,
678 starting_dir: impl Into<PathBuf>,
679 starting_name: impl IntoVar<Txt>,
680 filters: impl Into<FileDialogFilters>,
681 ) -> ResponseVar<FileDialogResponse> {
682 WINDOWS.native_file_dialog(
683 WINDOW.id(),
684 native_api::FileDialog::new(
685 title.into_var().get(),
686 starting_dir.into(),
687 starting_name.into_var().get(),
688 filters.into().build(),
689 native_api::FileDialogKind::OpenFiles,
690 ),
691 )
692 }
693
694 pub fn save_file(
696 &self,
697 title: impl IntoVar<Txt>,
698 starting_dir: impl Into<PathBuf>,
699 starting_name: impl IntoVar<Txt>,
700 filters: impl Into<FileDialogFilters>,
701 ) -> ResponseVar<FileDialogResponse> {
702 WINDOWS.native_file_dialog(
703 WINDOW.id(),
704 native_api::FileDialog::new(
705 title.into_var().get(),
706 starting_dir.into(),
707 starting_name.into_var().get(),
708 filters.into().build(),
709 native_api::FileDialogKind::SaveFile,
710 ),
711 )
712 }
713
714 pub fn select_folder(
716 &self,
717 title: impl IntoVar<Txt>,
718 starting_dir: impl Into<PathBuf>,
719 starting_name: impl IntoVar<Txt>,
720 ) -> ResponseVar<FileDialogResponse> {
721 WINDOWS.native_file_dialog(
722 WINDOW.id(),
723 native_api::FileDialog::new(
724 title.into_var().get(),
725 starting_dir.into(),
726 starting_name.into_var().get(),
727 "",
728 native_api::FileDialogKind::SelectFolder,
729 ),
730 )
731 }
732
733 pub fn select_folders(
735 &self,
736 title: impl IntoVar<Txt>,
737 starting_dir: impl Into<PathBuf>,
738 starting_name: impl IntoVar<Txt>,
739 ) -> ResponseVar<FileDialogResponse> {
740 WINDOWS.native_file_dialog(
741 WINDOW.id(),
742 native_api::FileDialog::new(
743 title.into_var().get(),
744 starting_dir.into(),
745 starting_name.into_var().get(),
746 "",
747 native_api::FileDialogKind::SelectFolders,
748 ),
749 )
750 }
751
752 pub fn custom(&self, dialog: impl UiNode) -> ResponseVar<Response> {
758 self.show_impl(dialog.boxed())
759 }
760}
761
762impl DIALOG {
763 pub fn native_dialogs(&self) -> ArcVar<DialogKind> {
769 DIALOG_SV.read().native_dialogs.clone()
770 }
771}
772bitflags! {
773 #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
775 pub struct DialogKind: u32 {
776 const INFO = 0b0000_0000_0000_0001;
778 const WARN = 0b0000_0000_0000_0010;
780 const ERROR = 0b0000_0000_0000_0100;
782 const ASK = 0b0000_0000_0000_1000;
784 const CONFIRM = 0b0000_0000_0001_0000;
786
787 const OPEN_FILE = 0b1000_0000_0000_0000;
789 const OPEN_FILES = 0b0100_0000_0000_0000;
791 const SAVE_FILE = 0b0010_0000_0000_0000;
793
794 const SELECT_FOLDER = 0b0001_0000_0000_0000;
796 const SELECT_FOLDERS = 0b0000_1000_0000_0000;
798
799 const MESSAGE = Self::INFO.bits() | Self::WARN.bits() | Self::ERROR.bits() | Self::ASK.bits() | Self::CONFIRM.bits();
801 const FILE = Self::OPEN_FILE.bits() | Self::OPEN_FILES.bits() | Self::SAVE_FILE.bits() | Self::SELECT_FOLDER.bits() | Self::SELECT_FOLDERS.bits();
803 }
804}
805impl_from_and_into_var! {
806 fn from(empty_or_all: bool) -> DialogKind {
807 if empty_or_all {
808 DialogKind::all()
809 } else {
810 DialogKind::empty()
811 }
812 }
813}
814
815impl DIALOG {
816 pub fn respond(&self, response: Response) {
818 let ctx = DIALOG_CTX.get();
819 let id = *ctx.dialog_id.lock();
820 if let Some(id) = id {
821 ctx.responder.respond(response);
822 POPUP.close_id(id);
823 } else {
824 tracing::error!("DIALOG.respond called outside of a dialog");
825 }
826 }
827
828 pub fn respond_default(&self) {
833 let ctx = DIALOG_CTX.get();
834 let id = *ctx.dialog_id.lock();
835 if let Some(id) = id {
836 POPUP.close_id(id);
837 } else {
838 tracing::error!("DIALOG.respond called outside of a dialog");
839 }
840 }
841
842 fn message(
843 &self,
844 msg: BoxedVar<Txt>,
845 title: BoxedVar<Txt>,
846 kind: DialogKind,
847 style: &dyn Fn() -> zng_wgt_style::StyleBuilder,
848 native_icon: native_api::MsgDialogIcon,
849 native_buttons: native_api::MsgDialogButtons,
850 ) -> ResponseVar<Response> {
851 if NATIVE_DIALOGS_VAR.get().contains(kind) {
852 WINDOWS
853 .native_message_dialog(
854 WINDOW.id(),
855 native_api::MsgDialog::new(title.get(), msg.get(), native_icon, native_buttons),
856 )
857 .map_response(|r| r.clone().into())
858 } else {
859 self.custom(Dialog! {
860 style_fn = style();
861 title = Text! {
862 visibility = title.map(|t| Visibility::from(!t.is_empty()));
863 txt = title;
864 };
865 content = SelectableText!(msg);
866 })
867 }
868 }
869
870 fn show_impl(&self, dialog: BoxedUiNode) -> ResponseVar<Response> {
871 let (responder, response) = response_var();
872
873 let mut ctx = Some(Arc::new(DialogCtx {
874 dialog_id: Mutex::new(None),
875 responder,
876 }));
877
878 let dialog = backdrop::DialogBackdrop!(dialog);
879
880 let dialog = match_widget(
881 dialog,
882 clmv!(|c, op| {
883 match &op {
884 UiNodeOp::Init => {
885 *ctx.as_ref().unwrap().dialog_id.lock() = c.with_context(WidgetUpdateMode::Ignore, || WIDGET.id());
886 DIALOG_CTX.with_context(&mut ctx, || c.op(op));
887 *ctx.as_ref().unwrap().dialog_id.lock() = c.with_context(WidgetUpdateMode::Ignore, || WIDGET.id());
889 }
890 UiNodeOp::Deinit => {}
891 _ => {
892 DIALOG_CTX.with_context(&mut ctx, || c.op(op));
893 }
894 }
895 }),
896 );
897
898 zng_wgt_layer::popup::CLOSE_ON_FOCUS_LEAVE_VAR.with_context_var(ContextInitHandle::new(), false, || {
899 POPUP.open_config(dialog, AnchorMode::window(), ContextCapture::NoCapture)
900 });
901
902 response
903 }
904}
905
906struct DialogCtx {
907 dialog_id: Mutex<Option<WidgetId>>,
908 responder: ResponderVar<Response>,
909}
910context_local! {
911 static DIALOG_CTX: DialogCtx = DialogCtx {
912 dialog_id: Mutex::new(None),
913 responder: response_var().0,
914 };
915}
916
917struct DialogService {
918 native_dialogs: ArcVar<DialogKind>,
919}
920app_local! {
921 static DIALOG_SV: DialogService = DialogService {
922 native_dialogs: var(DialogKind::FILE),
923 };
924}