1use std::collections::VecDeque;
141use std::path::{Path, PathBuf};
142
143use std::sync::{Arc, Mutex};
144
145use egui::{Key, Modifiers, Response, Ui, Vec2};
146use egui_pop_core::band;
147use egui_pop_core::debug::FnCollector;
148use egui_pop_core::icon::{Icon, Size as IconSize};
149use egui_pop_core::kit::{self, Kit};
150use egui_pop_core::lock;
151use egui_pop_core::overlay::{self, Kind, OverlaySpec};
152use egui_pop_core::strings::{self, CANCEL, CLOSE};
153use egui_pop_core::theme::Tokens;
154use egui_pop_core::ui::{TextRole, UiPop as _};
155use egui_pop_core::widgets;
156use egui_pop_model::commands::{CommandSpec, Origin};
157use egui_pop_model::fuzzy;
158use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PluginId, SettingId, StepId};
159use egui_pop_model::keymap::BindOptions;
160use egui_pop_model::mount::{
161 ClaimKey, Dismiss, FocusPolicy, HostOffer, HostSize, Keep, Lifetime, Mountable,
162};
163use egui_pop_model::values::{Change, Descriptor, PathHint, PathKind, Set, Type, Value};
164use serde::Serialize;
165use serde_json::{Map, Value as Json, json};
166
167use bus_contract::{ListenOpts, Point as _};
168
169use crate::app::AppHandle;
170use crate::bus::{
171 CHILDREN, FOCUS, PopupClose, REGISTRY, Reason, WindowClose, WindowKind, WindowRequest,
172};
173use crate::files::{self, FILES, FilePicker, FileRequest, PickerAnswer};
174use crate::host::Pending;
175use crate::host::source_of;
176use crate::services::ServiceToken;
177use crate::steps::{Outcome, StepSpec};
178use crate::strings as txt;
179use crate::windows::WindowId;
180use crate::zones::{self, Block};
181use crate::{Ctx, Plugin, PluginError};
182
183pub const DIALOGS: ServiceToken<Dialogs> = ServiceToken::new("app.dialogs");
185
186pub const STEP_SHOW: StepId = StepId::from_static("dialog.show");
189pub const STEP_ANSWER: StepId = StepId::from_static("dialog.answer");
193pub const SETTING_CLOSABLE: SettingId = SettingId::from_static("dialogs.closable");
196pub const STEP_MOVE: StepId = StepId::from_static("dialog.move");
202pub const SETTING_MOVABLE: SettingId = SettingId::from_static("dialogs.movable");
205pub const CMD_MOVE: CommandId = CommandId::from_static("dialogs.move");
208
209pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.dialogs");
211
212pub const POPUP_LISTENER: &str = "pop.dialogs.popup";
215pub const CANCEL_ON_CLOSE: &str = "pop.dialogs.cancel-on-close";
218pub const POPUP_PREFIX: &str = "dialog:";
220const DRAG_DIM: f32 = 0.35;
222const BIG_STEP: f32 = 8.0;
224
225#[derive(Clone, Debug, PartialEq, Serialize)]
243pub struct Confirm {
244 pub title: String,
245 pub detail: String,
247 pub verb: String,
249 pub danger: bool,
252 pub command: CommandId,
253 pub args: Json,
254 pub copy: bool,
256 #[serde(skip_serializing_if = "Details::is_empty")]
258 pub details: Details,
259 #[serde(skip_serializing_if = "Option::is_none")]
263 pub secondary: Option<Secondary>,
264 #[serde(skip_serializing_if = "String::is_empty")]
266 pub cancel: String,
267 #[serde(skip_serializing_if = "Option::is_none")]
270 pub order: Option<ButtonOrder>,
271}
272
273#[derive(Clone, Debug, PartialEq, Serialize)]
277pub struct Secondary {
278 pub verb: String,
280 pub command: CommandId,
281 pub args: Json,
282 pub danger: bool,
284}
285
286impl Secondary {
287 pub fn new(verb: &str, command: CommandId) -> Self {
288 Self {
289 verb: verb.into(),
290 command,
291 args: Json::Null,
292 danger: false,
293 }
294 }
295
296 pub fn danger(mut self) -> Self {
298 self.danger = true;
299 self
300 }
301
302 pub fn args(mut self, args: Json) -> Self {
303 self.args = args;
304 self
305 }
306}
307
308const PINNED_ORDER: &str = "egui_pop.dialogs.button_order";
310
311#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
314#[serde(rename_all = "kebab-case")]
315pub enum ButtonOrder {
316 PrimaryLast,
320 PrimaryFirst,
323}
324
325impl ButtonOrder {
326 pub fn platform() -> Self {
329 let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
330 Self::for_platform(cfg!(windows), &desktop)
331 }
332
333 pub fn pin(ctx: &egui::Context, order: ButtonOrder) {
338 ctx.data_mut(|d| d.insert_temp(egui::Id::unique(PINNED_ORDER), order));
339 }
340
341 pub fn of(ctx: &egui::Context) -> Self {
344 ctx.data(|d| d.get_temp(egui::Id::unique(PINNED_ORDER)))
345 .unwrap_or_else(Self::platform)
346 }
347
348 pub fn for_platform(windows: bool, desktop: &str) -> Self {
351 let kde = desktop.split(':').any(|d| d.eq_ignore_ascii_case("KDE"));
352 if windows || kde {
353 Self::PrimaryFirst
354 } else {
355 Self::PrimaryLast
356 }
357 }
358}
359
360impl Confirm {
361 pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
362 Self {
363 title: title.into(),
364 detail: String::new(),
365 verb: verb.into(),
366 danger: false,
367 command,
368 args: Json::Null,
369 copy: true,
370 details: Details::default(),
371 secondary: None,
372 cancel: String::new(),
373 order: None,
374 }
375 }
376
377 pub fn secondary(mut self, secondary: Secondary) -> Self {
379 self.secondary = Some(secondary);
380 self
381 }
382
383 pub fn cancel(mut self, label: &str) -> Self {
385 self.cancel = label.into();
386 self
387 }
388
389 pub fn order(mut self, order: ButtonOrder) -> Self {
391 self.order = Some(order);
392 self
393 }
394
395 pub fn copyable(mut self, copy: bool) -> Self {
397 self.copy = copy;
398 self
399 }
400
401 pub fn details<K: Into<String>, V: Into<String>>(
405 mut self,
406 lines: impl IntoIterator<Item = (K, V)>,
407 mode: DetailsMode,
408 ) -> Self {
409 self.details = Details::new(lines, mode);
410 self
411 }
412
413 pub fn detail(mut self, detail: &str) -> Self {
414 self.detail = detail.into();
415 self
416 }
417
418 pub fn danger(mut self) -> Self {
419 self.danger = true;
420 self
421 }
422
423 pub fn args(mut self, args: Json) -> Self {
424 self.args = args;
425 self
426 }
427}
428
429#[derive(Clone, Debug, PartialEq, Serialize)]
431pub struct Field {
432 pub key: String,
434 pub descriptor: Descriptor,
435 pub value: Value,
436}
437
438#[derive(Clone, Debug, PartialEq, Serialize)]
440pub struct Form {
441 pub title: String,
442 pub fields: Vec<Field>,
443 pub verb: String,
444 pub command: CommandId,
445 pub args: Json,
447}
448
449impl Form {
450 pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
451 Self {
452 title: title.into(),
453 fields: Vec::new(),
454 verb: verb.into(),
455 command,
456 args: Json::Null,
457 }
458 }
459
460 pub fn field(mut self, key: &str, descriptor: Descriptor) -> Self {
462 let value = descriptor.default.clone();
463 self.fields.push(Field {
464 key: key.into(),
465 descriptor,
466 value,
467 });
468 self
469 }
470
471 pub fn field_at(mut self, key: &str, descriptor: Descriptor, value: Value) -> Self {
473 self.fields.push(Field {
474 key: key.into(),
475 descriptor,
476 value,
477 });
478 self
479 }
480}
481
482#[derive(Clone, Debug, PartialEq, Serialize)]
484pub struct ChooseOption {
485 pub label: String,
486 pub value: Json,
488 #[serde(skip_serializing_if = "String::is_empty")]
490 pub hint: String,
491}
492
493impl ChooseOption {
494 pub fn new(label: &str, value: Json) -> Self {
495 Self {
496 label: label.into(),
497 value,
498 hint: String::new(),
499 }
500 }
501
502 pub fn hint(mut self, hint: &str) -> Self {
503 self.hint = hint.into();
504 self
505 }
506}
507
508#[derive(Clone, Debug, PartialEq, Serialize)]
512pub struct Choose {
513 pub title: String,
514 pub detail: String,
515 pub options: Vec<ChooseOption>,
516 pub command: CommandId,
517 pub args: Json,
518 pub value_key: String,
520}
521
522impl Choose {
523 pub fn new(title: &str, options: &[&str], command: CommandId) -> Self {
525 Self::with_options(
526 title,
527 options
528 .iter()
529 .map(|o| ChooseOption::new(o, json!(o)))
530 .collect(),
531 command,
532 )
533 }
534
535 pub fn with_options(title: &str, options: Vec<ChooseOption>, command: CommandId) -> Self {
537 Self {
538 title: title.into(),
539 detail: String::new(),
540 options,
541 command,
542 args: Json::Null,
543 value_key: "value".into(),
544 }
545 }
546
547 pub fn option(mut self, option: ChooseOption) -> Self {
549 self.options.push(option);
550 self
551 }
552
553 pub fn detail(mut self, detail: &str) -> Self {
554 self.detail = detail.into();
555 self
556 }
557
558 pub fn args(mut self, args: Json) -> Self {
560 self.args = args;
561 self
562 }
563
564 pub fn value_key(mut self, key: &str) -> Self {
566 self.value_key = key.into();
567 self
568 }
569
570 pub fn visible(&self, filter: &str) -> Vec<usize> {
573 if filter.trim().is_empty() {
574 return (0..self.options.len()).collect();
575 }
576 fuzzy::rank(&self.options, filter, |o| format!("{} {}", o.label, o.hint))
577 .into_iter()
578 .map(|(i, _)| i)
579 .collect()
580 }
581}
582
583#[derive(Clone, Debug, PartialEq, Serialize)]
598pub struct Info {
599 pub title: String,
600 pub text: String,
601 pub error: bool,
603 pub copy: bool,
605 #[serde(skip_serializing_if = "Details::is_empty")]
607 pub details: Details,
608}
609
610impl Info {
611 pub fn new(title: &str, text: &str) -> Self {
612 Self {
613 title: title.into(),
614 text: text.into(),
615 error: false,
616 copy: true,
617 details: Details::default(),
618 }
619 }
620
621 pub fn error(title: &str, text: &str) -> Self {
624 Self {
625 error: true,
626 ..Self::new(title, text)
627 }
628 }
629
630 pub fn copyable(mut self, copy: bool) -> Self {
632 self.copy = copy;
633 self
634 }
635
636 pub fn details<K: Into<String>, V: Into<String>>(
640 mut self,
641 lines: impl IntoIterator<Item = (K, V)>,
642 mode: DetailsMode,
643 ) -> Self {
644 self.details = Details::new(lines, mode);
645 self
646 }
647
648 pub fn copy_text(&self) -> String {
650 copy_text(&self.title, &self.text, &self.details)
651 }
652}
653
654impl Confirm {
655 pub fn copy_text(&self) -> String {
657 copy_text(&self.title, &self.detail, &self.details)
658 }
659}
660
661#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
663#[serde(rename_all = "lowercase")]
664pub enum DetailsMode {
665 #[default]
668 Auto,
669 Hidden,
671 Shown,
675}
676
677#[derive(Clone, Debug, Default, PartialEq, Serialize)]
680pub struct Details {
681 pub lines: Vec<(String, String)>,
682 pub mode: DetailsMode,
683}
684
685impl Details {
686 pub fn new<K: Into<String>, V: Into<String>>(
687 lines: impl IntoIterator<Item = (K, V)>,
688 mode: DetailsMode,
689 ) -> Self {
690 Self {
691 lines: lines
692 .into_iter()
693 .map(|(k, v)| (k.into(), v.into()))
694 .collect(),
695 mode,
696 }
697 }
698
699 pub fn is_empty(&self) -> bool {
700 self.lines.is_empty()
701 }
702
703 pub fn text(&self) -> String {
705 self.lines
706 .iter()
707 .map(|(k, v)| format!("{k}: {v}"))
708 .collect::<Vec<_>>()
709 .join("\n")
710 }
711
712 pub fn shown(&self, error: bool) -> bool {
714 !self.is_empty()
715 && match self.mode {
716 DetailsMode::Auto => error,
717 DetailsMode::Hidden => false,
718 DetailsMode::Shown => true,
719 }
720 }
721}
722
723fn copy_text(title: &str, message: &str, details: &Details) -> String {
726 let mut text = title.to_string();
727 if !message.is_empty() {
728 text.push_str("\n\n");
729 text.push_str(message);
730 }
731 if !details.is_empty() {
732 text.push_str("\n\n---\n");
733 text.push_str(&details.text());
734 }
735 text
736}
737
738#[derive(Clone, Debug, PartialEq, Serialize)]
753pub struct Custom {
754 pub title: String,
755 pub verb: String,
758 pub danger: bool,
761 pub command: Option<CommandId>,
764 pub args: Json,
765 pub size: Option<[f32; 2]>,
768 pub share: f32,
770 pub claims: Vec<ClaimKey>,
773 pub needs: Option<Mountable>,
777 pub footer: bool,
782}
783
784impl Custom {
785 pub const SHARE: f32 = 0.7;
787
788 pub fn new(title: &str, verb: &str, command: CommandId) -> Self {
791 Self {
792 title: title.into(),
793 verb: verb.into(),
794 danger: false,
795 command: Some(command),
796 args: Json::Null,
797 size: None,
798 share: Self::SHARE,
799 claims: Vec::new(),
800 needs: None,
801 footer: true,
802 }
803 }
804
805 pub fn closing(title: &str) -> Self {
807 Self {
808 title: title.into(),
809 verb: String::new(),
810 danger: false,
811 command: None,
812 args: Json::Null,
813 size: None,
814 share: Self::SHARE,
815 claims: Vec::new(),
816 needs: None,
817 footer: true,
818 }
819 }
820
821 pub fn danger(mut self) -> Self {
822 self.danger = true;
823 self
824 }
825
826 pub fn args(mut self, args: Json) -> Self {
828 self.args = args;
829 self
830 }
831
832 pub fn size(mut self, width: f32, height: f32) -> Self {
834 self.size = Some([width.max(1.0), height.max(1.0)]);
835 self
836 }
837
838 pub fn share(mut self, share: f32) -> Self {
840 self.share = share.clamp(0.2, 1.0);
841 self
842 }
843
844 pub fn claims(mut self, keys: &[ClaimKey]) -> Self {
846 for k in keys {
847 if !self.claims.contains(k) {
848 self.claims.push(*k);
849 }
850 }
851 self
852 }
853
854 pub fn needs(mut self, needs: Mountable) -> Self {
857 let claims = needs.claims.clone();
858 self.needs = Some(needs);
859 self.claims(&claims)
860 }
861
862 pub fn own_footer(mut self) -> Self {
867 self.footer = false;
868 self.claims(&[ClaimKey::Enter])
869 }
870
871 pub fn claims_key(&self, key: ClaimKey) -> bool {
873 self.claims.contains(&key)
874 }
875
876 pub fn body_size(&self, room: Vec2) -> Vec2 {
878 let size = match self.size {
879 Some([w, h]) => egui::vec2(w.min(room.x - 64.0), h.min(room.y - 160.0)),
880 None => egui::vec2(room.x * self.share, room.y * self.share - 120.0),
881 };
882 size.max(egui::vec2(120.0, 80.0))
883 }
884}
885
886pub fn custom_host() -> HostOffer {
891 HostOffer::new(crate::mounts::CUSTOM_DIALOG, "C", "Custom dialog")
892 .source("dialogs: Dialog::Custom, Dialogs::open_custom")
893 .size(HostSize::Given)
894 .focus(FocusPolicy::ModalExclusive)
895 .owns_keys(&[ClaimKey::Enter, ClaimKey::Escape])
896 .honours_claims()
897 .dismissed_by(&[Dismiss::Answer, Dismiss::Escape])
898 .lifetime(Lifetime::Transient)
899 .keeps(&[Keep::Place])
900}
901
902#[derive(Debug, Default)]
906pub struct CustomPass {
907 values: Map<String, Json>,
908 ready: bool,
909 describe: Json,
910 escape: bool,
911 answer: Option<Answer>,
912}
913
914impl CustomPass {
915 pub fn value(&mut self, key: &str, value: Json) {
918 self.values.insert(key.into(), value);
919 }
920
921 pub fn values(&self) -> &Map<String, Json> {
923 &self.values
924 }
925
926 pub fn ready(&mut self, ready: bool) {
929 self.ready = ready;
930 }
931
932 pub fn describe(&mut self, description: Json) {
935 self.describe = description;
936 }
937
938 pub fn claim_escape(&mut self) {
941 self.escape = true;
942 }
943
944 pub fn accept(&mut self) {
946 self.answer = Some(Answer::Accept {
947 values: self.values.clone(),
948 });
949 }
950
951 pub fn cancel(&mut self) {
953 self.answer = Some(Answer::Cancel);
954 }
955}
956
957type BodyFn = Box<dyn FnMut(&mut Ui, &AppHandle, &mut CustomPass)>;
959
960#[derive(Default)]
963struct Bodies(std::cell::RefCell<std::collections::BTreeMap<u64, BodyFn>>);
964
965#[derive(Clone, Debug, PartialEq, Serialize)]
967#[serde(tag = "kind", rename_all = "lowercase")]
968pub enum Dialog {
969 Confirm(Confirm),
970 Form(Form),
971 Choose(Choose),
972 Info(Info),
973 Custom(Box<Custom>),
974}
975
976impl From<Custom> for Dialog {
977 fn from(d: Custom) -> Self {
978 Dialog::Custom(Box::new(d))
979 }
980}
981
982impl From<Confirm> for Dialog {
983 fn from(d: Confirm) -> Self {
984 Dialog::Confirm(d)
985 }
986}
987
988impl From<Form> for Dialog {
989 fn from(d: Form) -> Self {
990 Dialog::Form(d)
991 }
992}
993
994impl From<Choose> for Dialog {
995 fn from(d: Choose) -> Self {
996 Dialog::Choose(d)
997 }
998}
999
1000impl From<Info> for Dialog {
1001 fn from(d: Info) -> Self {
1002 Dialog::Info(d)
1003 }
1004}
1005
1006impl Dialog {
1007 pub fn title(&self) -> &str {
1008 match self {
1009 Dialog::Confirm(d) => &d.title,
1010 Dialog::Form(d) => &d.title,
1011 Dialog::Choose(d) => &d.title,
1012 Dialog::Info(d) => &d.title,
1013 Dialog::Custom(d) => &d.title,
1014 }
1015 }
1016}
1017
1018#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
1022#[serde(rename_all = "lowercase")]
1023pub enum Backdrop {
1024 #[default]
1027 Dim,
1028 Clear,
1030}
1031
1032#[derive(Clone, Debug, PartialEq)]
1048pub struct DialogSpec {
1049 pub dialog: Dialog,
1050 pub closable: bool,
1054 pub movable: bool,
1057 pub backdrop: Backdrop,
1059 pub remember: Option<String>,
1062}
1063
1064impl DialogSpec {
1065 pub fn new(dialog: impl Into<Dialog>) -> Self {
1066 Self {
1067 dialog: dialog.into(),
1068 closable: false,
1069 movable: false,
1070 backdrop: Backdrop::Dim,
1071 remember: None,
1072 }
1073 }
1074
1075 pub fn closable(mut self, closable: bool) -> Self {
1078 self.closable = closable;
1079 self
1080 }
1081
1082 pub fn movable(mut self, movable: bool) -> Self {
1085 self.movable = movable;
1086 self
1087 }
1088
1089 pub fn backdrop(mut self, backdrop: Backdrop) -> Self {
1092 self.backdrop = backdrop;
1093 self
1094 }
1095
1096 pub fn remember_position(mut self, key: &str) -> Self {
1099 self.remember = Some(key.into());
1100 self
1101 }
1102}
1103
1104impl From<Dialog> for DialogSpec {
1105 fn from(d: Dialog) -> Self {
1106 Self::new(d)
1107 }
1108}
1109
1110impl From<Confirm> for DialogSpec {
1111 fn from(d: Confirm) -> Self {
1112 Self::new(d)
1113 }
1114}
1115
1116impl From<Form> for DialogSpec {
1117 fn from(d: Form) -> Self {
1118 Self::new(d)
1119 }
1120}
1121
1122impl From<Choose> for DialogSpec {
1123 fn from(d: Choose) -> Self {
1124 Self::new(d)
1125 }
1126}
1127
1128impl From<Info> for DialogSpec {
1129 fn from(d: Info) -> Self {
1130 Self::new(d)
1131 }
1132}
1133
1134impl From<Custom> for DialogSpec {
1135 fn from(d: Custom) -> Self {
1136 Self::new(d)
1137 }
1138}
1139
1140#[derive(Clone, Debug, PartialEq, Serialize)]
1142#[serde(tag = "answer", rename_all = "lowercase")]
1143pub enum Answer {
1144 Accept {
1147 values: Map<String, Json>,
1148 },
1149 Choose {
1151 index: usize,
1152 },
1153 Value {
1155 value: Json,
1156 },
1157 Cancel,
1158}
1159
1160impl Answer {
1161 pub fn from_json(json: &Json) -> Result<Answer, String> {
1165 match json.get("answer").and_then(Json::as_str) {
1166 Some("accept") => Ok(Answer::Accept {
1167 values: json
1168 .get("values")
1169 .and_then(Json::as_object)
1170 .cloned()
1171 .unwrap_or_default(),
1172 }),
1173 Some("choose" | "value") => match (json.get("value"), json.get("index")) {
1174 (Some(v), _) => Ok(Answer::Value { value: v.clone() }),
1175 (None, Some(i)) => i
1176 .as_u64()
1177 .map(|i| Answer::Choose { index: i as usize })
1178 .ok_or_else(|| "`index` is a number".into()),
1179 (None, None) => Err("`value` or `index` is missing".into()),
1180 },
1181 Some("cancel") => Ok(Answer::Cancel),
1182 _ => Err("`answer` is accept, choose or cancel".into()),
1183 }
1184 }
1185}
1186
1187#[derive(Clone, Debug)]
1189struct Open {
1190 id: u64,
1191 dialog: Dialog,
1192 closable: bool,
1194 movable: bool,
1196 backdrop: Backdrop,
1197 remember: Option<String>,
1199 offset: Vec2,
1201 moving: Option<Vec2>,
1203 drag_from: Option<Vec2>,
1205 focused: bool,
1207 copied_at: Option<f64>,
1210 window: Option<egui::ViewportId>,
1213 group: Option<egui::ViewportId>,
1217 picking: Option<(String, FilePicker)>,
1220 browse: Option<(String, FileRequest)>,
1222 choosing: Option<(String, u64, Pending)>,
1225 error: Option<String>,
1226 filter: String,
1228 highlight: usize,
1229 values: Map<String, Json>,
1232 ready: bool,
1233 body: Json,
1234 opener: Option<OwnerId>,
1236 on_bus: bool,
1238}
1239
1240impl Open {
1241 fn popup(&self) -> String {
1243 format!("{POPUP_PREFIX}{}", self.id)
1244 }
1245
1246 fn owner(&self) -> String {
1248 self.opener
1249 .as_ref()
1250 .map_or_else(|| PLUGIN.as_str().to_string(), |o| o.as_str().to_string())
1251 }
1252}
1253
1254#[derive(Debug, Default)]
1255struct State {
1256 next: u64,
1257 queue: VecDeque<Open>,
1258 given: Vec<(u64, Answer, Origin)>,
1260 answered: VecDeque<(String, Answer, Origin)>,
1262}
1263
1264#[derive(Clone, Debug, Default)]
1266pub struct Dialogs(Arc<Mutex<State>>);
1267
1268impl Dialogs {
1269 pub fn open(&self, dialog: impl Into<DialogSpec>) -> u64 {
1271 let spec = dialog.into();
1272 let mut s = lock(&self.0);
1273 s.next += 1;
1274 let id = s.next;
1275 s.queue.push_back(Open {
1276 id,
1277 dialog: spec.dialog,
1278 closable: spec.closable,
1279 movable: spec.movable,
1280 backdrop: spec.backdrop,
1281 remember: spec.remember,
1282 offset: Vec2::ZERO,
1283 moving: None,
1284 drag_from: None,
1285 focused: false,
1286 copied_at: None,
1287 window: None,
1288 group: crate::windows::current_group(),
1289 picking: None,
1290 browse: None,
1291 choosing: None,
1292 error: None,
1293 filter: String::new(),
1294 highlight: 0,
1295 values: Map::new(),
1296 ready: true,
1297 body: Json::Null,
1298 opener: egui_pop_model::values::current_scope(),
1299 on_bus: false,
1300 });
1301 id
1302 }
1303
1304 pub(crate) fn open_now(&self, dialog: impl Into<DialogSpec>) -> u64 {
1308 let id = self.open(dialog);
1309 let mut s = lock(&self.0);
1310 if let Some(open) = s.queue.pop_back() {
1311 s.queue.push_front(open);
1312 }
1313 id
1314 }
1315
1316 pub fn open_custom(
1323 &self,
1324 app: &AppHandle,
1325 spec: impl Into<DialogSpec>,
1326 body: impl FnMut(&mut Ui, &AppHandle, &mut CustomPass) + 'static,
1327 ) -> Result<u64, String> {
1328 let spec = spec.into();
1329 let Dialog::Custom(custom) = &spec.dialog else {
1330 return Err(format!(
1331 "`{}` is not a custom dialog: open it with `open`",
1332 spec.dialog.title()
1333 ));
1334 };
1335 if let Some(needs) = &custom.needs {
1336 app.mount_needs(needs, &custom_host())?;
1337 }
1338 let id = self.open(spec);
1339 app.local::<Bodies>()
1340 .0
1341 .borrow_mut()
1342 .insert(id, Box::new(body));
1343 Ok(id)
1344 }
1345
1346 pub fn current(&self) -> Option<(u64, Dialog)> {
1349 let s = lock(&self.0);
1350 shown_at(&s, crate::windows::current_group())
1351 .map(|i| (s.queue[i].id, s.queue[i].dialog.clone()))
1352 }
1353
1354 pub fn current_in(&self, group: egui::ViewportId) -> Option<(u64, Dialog)> {
1357 let s = lock(&self.0);
1358 shown_at(&s, Some(group)).map(|i| (s.queue[i].id, s.queue[i].dialog.clone()))
1359 }
1360
1361 pub fn offset(&self) -> Option<Vec2> {
1364 let s = lock(&self.0);
1365 shown_at(&s, crate::windows::current_group()).map(|i| s.queue[i].offset)
1366 }
1367
1368 pub fn is_open(&self, id: u64) -> bool {
1370 lock(&self.0).queue.iter().any(|o| o.id == id)
1371 }
1372
1373 pub fn len(&self) -> usize {
1375 lock(&self.0).queue.len()
1376 }
1377
1378 pub fn is_empty(&self) -> bool {
1379 self.len() == 0
1380 }
1381
1382 pub fn answer(&self, answer: Answer, origin: Origin) -> Result<(), String> {
1384 let mut s = lock(&self.0);
1385 let at = shown_at(&s, crate::windows::current_group()).ok_or("no dialog is open")?;
1386 let id = s.queue[at].id;
1387 s.given.push((id, answer, origin));
1388 Ok(())
1389 }
1390
1391 pub(crate) fn give(&self, id: u64, answer: Answer, origin: Origin) -> bool {
1396 let mut s = lock(&self.0);
1397 if !s.queue.iter().any(|o| o.id == id) {
1398 return false;
1399 }
1400 s.given.push((id, answer, origin));
1401 true
1402 }
1403
1404 pub fn cancel(&self, id: u64, origin: Origin) -> bool {
1409 let mut s = lock(&self.0);
1410 if !s.queue.iter().any(|o| o.id == id) {
1411 return false;
1412 }
1413 s.given.push((id, Answer::Cancel, origin));
1414 true
1415 }
1416
1417 pub fn describe(&self) -> Json {
1420 let id = {
1421 let s = lock(&self.0);
1422 shown_at(&s, crate::windows::current_group()).map(|i| s.queue[i].id)
1423 };
1424 id.map_or(Json::Null, |id| self.describe_one(id))
1425 }
1426
1427 pub fn windows(&self, app: &AppHandle) -> Vec<Json> {
1430 let s = lock(&self.0);
1431 let mut groups: Vec<egui::ViewportId> = Vec::new();
1432 for o in &s.queue {
1433 let g = o.group.unwrap_or(egui::ViewportId::ROOT);
1434 if !groups.contains(&g) {
1435 groups.push(g);
1436 }
1437 }
1438 groups
1439 .into_iter()
1440 .filter_map(|g| {
1441 let i = shown_at(&s, Some(g))?;
1442 let o = &s.queue[i];
1443 Some(json!({
1444 "window": app.window_of_group(g),
1445 "id": o.id,
1446 "title": o.dialog.title(),
1447 "waiting": s.queue.iter().filter(|q| q.group == o.group).count() - 1,
1448 }))
1449 })
1450 .collect()
1451 }
1452
1453 fn describe_one(&self, id: u64) -> Json {
1455 let s = lock(&self.0);
1456 match s.queue.iter().find(|o| o.id == id) {
1457 Some(o) => {
1458 let mut d = serde_json::to_value(&o.dialog).unwrap_or(Json::Null);
1459 d["id"] = json!(o.id);
1460 d["closable"] = json!(o.closable);
1461 d["movable"] = json!(o.movable);
1462 d["backdrop"] = json!(o.backdrop);
1463 d["offset"] = json!([o.offset.x, o.offset.y]);
1464 d["moving"] = json!(o.moving.is_some());
1465 if let Some(key) = &o.remember {
1466 d["remember"] = json!(key);
1467 }
1468 d["waiting"] = json!(s.queue.iter().filter(|q| q.group == o.group).count() - 1);
1469 match &o.dialog {
1470 Dialog::Form(f) => d["values"] = Json::Object(values_of(&f.fields)),
1472 Dialog::Choose(c) => {
1473 d["filter"] = json!(o.filter);
1474 d["shown"] = json!(c.visible(&o.filter));
1475 }
1476 Dialog::Custom(_) => {
1477 d["values"] = Json::Object(o.values.clone());
1478 d["ready"] = json!(o.ready);
1479 d["body"] = o.body.clone();
1480 }
1481 _ => {}
1482 }
1483 d
1484 }
1485 None => Json::Null,
1486 }
1487 }
1488
1489 pub fn answered(&self) -> Vec<(String, Answer, Origin)> {
1491 lock(&self.0).answered.iter().cloned().collect()
1492 }
1493}
1494
1495fn shown_at(s: &State, group: Option<egui::ViewportId>) -> Option<usize> {
1499 match group {
1500 None => (!s.queue.is_empty()).then_some(0),
1501 Some(g) => s
1502 .queue
1503 .iter()
1504 .position(|o| o.group.unwrap_or(egui::ViewportId::ROOT) == g),
1505 }
1506}
1507
1508#[derive(Debug, Default)]
1510pub struct DialogsPlugin;
1511
1512impl Plugin for DialogsPlugin {
1513 fn id(&self) -> PluginId {
1514 PLUGIN
1515 }
1516
1517 fn title(&self) -> String {
1518 "Dialogs".into()
1519 }
1520
1521 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1522 let dialogs = Dialogs::default();
1523 ctx.service(&DIALOGS, dialogs.clone())?;
1524 ctx.setting(
1525 SETTING_CLOSABLE,
1526 Descriptor::bool("Close button on every dialog", false).description(
1527 "A close button at the right end of each dialog's title row, doing what Escape does.",
1528 ),
1529 )?;
1530 ctx.setting(
1531 SETTING_MOVABLE,
1532 Descriptor::bool("Movable dialogs", false).description(
1533 "Every dialog has a header band to drag it by; Alt+F7 moves it with the arrow keys.",
1534 ),
1535 )?;
1536 let moved = dialogs.clone();
1537 ctx.command(
1538 CommandSpec::new(CMD_MOVE, "Move dialog", "Dialogs")
1539 .description("Moves the dialog shown with the arrow keys; Enter keeps the place, Escape puts it back.")
1540 .when("modalOpen")
1541 .key_with("Alt+F7", BindOptions::global().through_modal()),
1542 move |call| {
1543 let all = setting(call.app, SETTING_MOVABLE);
1544 let mut s = lock(&moved.0);
1545 let at = shown_at(&s, crate::windows::current_group()).ok_or("no dialog is open")?;
1546 let o = &mut s.queue[at];
1547 if !(o.movable || all) {
1548 return Err("the dialog shown is not movable".into());
1549 }
1550 o.moving = Some(o.offset);
1551 o.drag_from = None;
1552 call.app.egui().request_repaint();
1553 Ok(json!({ "id": o.id }))
1554 },
1555 )?;
1556 ctx.step(
1557 StepSpec::new(
1558 STEP_MOVE,
1559 "A dialog is moved (dropped, moved by a key, centred again); a veto puts it back, a redirect places it elsewhere.",
1560 )
1561 .args(json!({ "id": 1, "title": "Levels", "key": "levels", "how": "drag", "from": [0.0, 0.0], "to": [120.0, -40.0] })),
1562 )?;
1563 ctx.step(
1564 StepSpec::new(STEP_SHOW, "A dialog comes up; a veto cancels it.")
1565 .args(json!({ "kind": "confirm", "id": 1, "title": "Delete 3 images?" })),
1566 )?;
1567 ctx.step(
1568 StepSpec::new(
1569 STEP_ANSWER,
1570 "A dialog is answered; a veto keeps it open, a redirect changes the answer.",
1571 )
1572 .args(json!({ "dialog": { "kind": "choose", "id": 1 }, "answer": { "answer": "choose", "index": 0 }, "origin": "user" })),
1573 )?;
1574 let (a, b) = (dialogs.clone(), dialogs);
1575 let weak = ctx.app().downgrade();
1576 let weak_a = ctx.app().downgrade();
1577 ctx.collector(
1578 FnCollector::new(
1579 "dialogs",
1580 "The dialog shown (kind, title, fields, verb, command) and how many wait; `answer` answers it as its caller.",
1581 )
1582 .snapshot(move |_| {
1583 let windows = weak_a.get().map(|app| a.windows(&app)).unwrap_or_default();
1584 json!({ "current": a.describe(), "windows": windows, "answered": a.answered() })
1585 })
1586 .action_as("answer", "Answers the dialog shown as its caller: accept (with `values`), choose (`value` or `index`) or cancel. An answer that would run a command not offered to agents is the user's only.", true, move |_, args, origin| {
1587 let answer = Answer::from_json(args)?;
1588 let app = weak.get()?;
1589 let open = {
1590 let s = lock(&b.0);
1591 let at = shown_at(&s, crate::windows::current_group()).ok_or("no dialog is open")?;
1592 s.queue[at].clone()
1593 };
1594 refuse_unoffered(&app, &open, &answer, origin)?;
1595 b.answer(answer, origin.clone())?;
1596 Ok(json!({ "queued": true }))
1597 })
1598 .args(json!({ "answer": "accept", "values": {} })),
1599 )?;
1600 ctx.block(
1601 zones::WINDOW_OVERLAYS,
1602 Block::add(BlockId::from_static("egui_pop.dialogs"), 10, show),
1603 );
1604 listen(&ctx.app());
1605 Ok(())
1606 }
1607}
1608
1609pub(crate) fn overlay_id(dialog: u64) -> egui::Id {
1611 egui::Id::unique(("egui_pop.dialog", dialog))
1612}
1613
1614const ANSWERED: usize = 16;
1616
1617fn target(open: &Open, answer: &Answer) -> Result<Option<(CommandId, Json)>, String> {
1620 Ok(match (&open.dialog, &answer) {
1621 (_, Answer::Cancel) => None,
1622 (Dialog::Confirm(c), Answer::Accept { .. } | Answer::Choose { index: 0 }) => {
1623 Some((c.command.clone(), c.args.clone()))
1624 }
1625 (Dialog::Confirm(c), Answer::Choose { index: 1 }) => {
1626 let s = c
1627 .secondary
1628 .as_ref()
1629 .ok_or_else(|| format!("{} has no second action", c.title))?;
1630 Some((s.command.clone(), s.args.clone()))
1631 }
1632 (Dialog::Info(_), Answer::Accept { .. }) => None,
1633 (Dialog::Custom(c), Answer::Accept { values }) => {
1634 if !open.ready {
1635 return Err(format!("{} cannot be accepted yet", c.title));
1636 }
1637 c.command.as_ref().map(|command| {
1638 let mut args = match &c.args {
1639 Json::Object(m) => m.clone(),
1640 _ => Map::new(),
1641 };
1642 args.extend(open.values.clone());
1643 args.extend(values.clone());
1644 (command.clone(), Json::Object(args))
1645 })
1646 }
1647 (Dialog::Form(f), Answer::Accept { values }) => {
1648 let mut args = match &f.args {
1649 Json::Object(m) => m.clone(),
1650 _ => Map::new(),
1651 };
1652 for field in f.fields.iter().filter(|x| !x.descriptor.note) {
1654 let v = match values.get(&field.key) {
1655 Some(j) => Value::from_json(field.descriptor.ty, j)
1656 .map_err(|e| format!("`{}`: {e}", field.key))?,
1657 None => field.value.clone(),
1658 };
1659 args.insert(field.key.clone(), v.to_json());
1660 }
1661 Some((f.command.clone(), Json::Object(args)))
1662 }
1663 (Dialog::Choose(c), Answer::Choose { .. } | Answer::Value { .. }) => {
1664 let index = match &answer {
1665 Answer::Choose { index } => *index,
1666 Answer::Value { value } => c
1667 .options
1668 .iter()
1669 .position(|o| o.value == *value)
1670 .ok_or_else(|| format!("no option of value {value}"))?,
1671 _ => unreachable!("matched above"),
1672 };
1673 let option = c
1674 .options
1675 .get(index)
1676 .ok_or_else(|| format!("no option {index}"))?;
1677 let mut args = match &c.args {
1678 Json::Object(m) => m.clone(),
1679 _ => Map::new(),
1680 };
1681 args.insert("choice".into(), json!(index));
1682 args.insert("label".into(), json!(option.label));
1683 args.insert(c.value_key.clone(), option.value.clone());
1684 Some((c.command.clone(), Json::Object(args)))
1685 }
1686 (_, a) => return Err(format!("{a:?} does not answer this dialog")),
1687 })
1688}
1689
1690fn refuse_unoffered(
1694 app: &AppHandle,
1695 open: &Open,
1696 answer: &Answer,
1697 origin: &Origin,
1698) -> Result<(), String> {
1699 if *origin == Origin::User {
1700 return Ok(());
1701 }
1702 let Some((command, _)) = target(open, answer)? else {
1703 return Ok(());
1704 };
1705 let offered = app
1706 .commands()
1707 .iter()
1708 .any(|(s, _)| s.id == command && s.agent);
1709 if offered {
1710 return Ok(());
1711 }
1712 let reason = format!(
1713 "accepting `{}` runs `{command}`, which is not offered to agents; only the user may",
1714 open.dialog.title()
1715 );
1716 app.publish(
1717 &source_of(origin),
1718 None,
1719 "dialog.answer.refused",
1720 json!({
1721 "id": open.id,
1722 "title": open.dialog.title(),
1723 "answer": answer,
1724 "command": command,
1725 "reason": reason,
1726 }),
1727 );
1728 Err(reason)
1729}
1730
1731fn apply(
1735 app: &AppHandle,
1736 d: &Dialogs,
1737 id: u64,
1738 answer: Answer,
1739 origin: Origin,
1740) -> Result<(), String> {
1741 let open = lock(&d.0)
1742 .queue
1743 .iter()
1744 .find(|o| o.id == id)
1745 .cloned()
1746 .ok_or("no dialog is open")?;
1747 refuse_unoffered(app, &open, &answer, &origin)?;
1748 let run = target(&open, &answer)?;
1749 if let Dialog::Custom(c) = &open.dialog {
1750 app.local::<Bodies>().0.borrow_mut().remove(&open.id);
1751 if let Some(needs) = &c.needs {
1752 app.unmount(&needs.id, crate::mounts::CUSTOM_DIALOG);
1753 }
1754 }
1755 {
1756 let mut s = lock(&d.0);
1757 s.queue.retain(|o| o.id != id);
1758 if s.answered.len() == ANSWERED {
1759 s.answered.pop_front();
1760 }
1761 s.answered.push_back((
1762 open.dialog.title().to_string(),
1763 answer.clone(),
1764 origin.clone(),
1765 ));
1766 }
1767 let source = source_of(&origin);
1768 app.publish(
1769 &source,
1770 None,
1771 "dialog.answered",
1772 json!({ "title": open.dialog.title(), "answer": answer }),
1773 );
1774 match (&open.dialog, &run) {
1775 (_, None) if answer == Answer::Cancel => app.publish(
1776 &source,
1777 None,
1778 "dialog.cancelled",
1779 json!({ "id": open.id, "title": open.dialog.title() }),
1780 ),
1781 (Dialog::Choose(c), Some((_, args))) => app.publish(
1782 &source,
1783 None,
1784 "dialog.chosen",
1785 json!({
1786 "id": open.id,
1787 "title": c.title,
1788 "index": args["choice"],
1789 "label": args["label"],
1790 "value": args[c.value_key.as_str()],
1791 }),
1792 ),
1793 _ => {}
1794 }
1795 if open.on_bus {
1796 let reason = if origin == Origin::User {
1797 Reason::User
1798 } else {
1799 Reason::Command
1800 };
1801 app.request_popup_close(WindowRequest::new(
1802 open.popup(),
1803 WindowKind::Popup,
1804 open.owner(),
1805 reason,
1806 ));
1807 }
1808 if let Some((command, args)) = run {
1809 app.run_as(command, args, origin);
1810 }
1811 Ok(())
1812}
1813
1814fn command_of(dialog: &Dialog) -> Option<&CommandId> {
1816 match dialog {
1817 Dialog::Confirm(c) => Some(&c.command),
1818 Dialog::Form(f) => Some(&f.command),
1819 Dialog::Choose(c) => Some(&c.command),
1820 Dialog::Custom(c) => c.command.as_ref(),
1821 Dialog::Info(_) => None,
1822 }
1823}
1824
1825pub(crate) fn owner_gone(
1830 app: &AppHandle,
1831 plugin: &PluginId,
1832 owner: &OwnerId,
1833 commands: &[CommandId],
1834) -> usize {
1835 let Some(d) = app.service(&DIALOGS) else {
1836 return 0;
1837 };
1838 let gone: Vec<Open> = {
1839 let mut s = lock(&d.0);
1840 let (gone, kept): (VecDeque<Open>, VecDeque<Open>) =
1841 std::mem::take(&mut s.queue).into_iter().partition(|o| {
1842 command_of(&o.dialog).is_some_and(|c| commands.contains(c))
1843 || (matches!(o.dialog, Dialog::Custom(_)) && o.opener.as_ref() == Some(owner))
1844 });
1845 s.queue = kept;
1846 gone.into()
1847 };
1848 let reason = format!("its plugin `{plugin}` is disconnected");
1849 let ctx = app.egui();
1850 for open in &gone {
1851 overlay::close(&ctx, overlay_id(open.id));
1854 if let Dialog::Custom(c) = &open.dialog {
1855 app.local::<Bodies>().0.borrow_mut().remove(&open.id);
1856 if let Some(needs) = &c.needs {
1857 app.unmount(&needs.id, crate::mounts::CUSTOM_DIALOG);
1858 }
1859 }
1860 {
1861 let mut s = lock(&d.0);
1862 if s.answered.len() == ANSWERED {
1863 s.answered.pop_front();
1864 }
1865 s.answered.push_back((
1866 open.dialog.title().to_string(),
1867 Answer::Cancel,
1868 Origin::User,
1869 ));
1870 }
1871 log::info!(
1872 target: "egui_pop",
1873 "dialog `{}` cancelled: {reason}",
1874 open.dialog.title()
1875 );
1876 app.publish(
1877 "egui_pop",
1878 None,
1879 "dialog.cancelled",
1880 json!({ "id": open.id, "title": open.dialog.title(), "reason": reason }),
1881 );
1882 if open.on_bus {
1883 app.request_popup_close(WindowRequest::new(
1884 open.popup(),
1885 WindowKind::Popup,
1886 open.owner(),
1887 Reason::OwnerGone,
1888 ));
1889 }
1890 }
1891 if !gone.is_empty() {
1892 app.egui().request_repaint();
1893 }
1894 gone.len()
1895}
1896
1897fn answer_step(
1900 app: &AppHandle,
1901 d: &Dialogs,
1902 id: u64,
1903 answer: Answer,
1904 origin: Origin,
1905) -> Result<(), String> {
1906 let args = json!({
1907 "dialog": d.describe_one(id),
1908 "answer": answer,
1909 "origin": source_of(&origin),
1910 });
1911 let out = app.step(&STEP_ANSWER, args, |app, args| {
1912 let answer = Answer::from_json(&args["answer"])?;
1913 apply(app, d, id, answer, origin.clone()).map(|()| Json::Null)
1914 });
1915 match out {
1916 Outcome::Done(r) => r.map(|_| ()),
1917 Outcome::Vetoed { reason, .. } => Err(reason),
1918 }
1919}
1920
1921fn listen(app: &AppHandle) {
1925 let bus = app.bus();
1926 bus.unlisten(&PopupClose::ID, POPUP_LISTENER);
1927 bus.unlisten(&WindowClose::ID, CANCEL_ON_CLOSE);
1928 let mine = || ListenOpts::new().owner(PLUGIN.as_str());
1929 let listened = [
1930 bus.listen::<PopupClose>(POPUP_LISTENER, mine().before(REGISTRY), |req, did| {
1931 let Some(id) = req
1932 .window
1933 .strip_prefix(POPUP_PREFIX)
1934 .and_then(|n| n.parse::<u64>().ok())
1935 else {
1936 return Ok(());
1937 };
1938 let Some(app) = crate::bus::asking() else {
1939 return Ok(());
1940 };
1941 let Some(d) = app.service(&DIALOGS) else {
1942 return Ok(());
1943 };
1944 let title = {
1946 let mut s = lock(&d.0);
1947 s.queue.iter_mut().find(|o| o.id == id).map(|o| {
1948 o.on_bus = false;
1949 o.dialog.title().to_string()
1950 })
1951 };
1952 let Some(title) = title else {
1953 return Ok(());
1954 };
1955 overlay::close(&app.egui(), overlay_id(id));
1956 apply(&app, &d, id, Answer::Cancel, Origin::User)?;
1957 did.push(format!(
1958 "{POPUP_LISTENER}: `{title}` cancelled ({})",
1959 req.reason.as_str()
1960 ));
1961 Ok(())
1962 }),
1963 bus.listen::<WindowClose>(
1964 CANCEL_ON_CLOSE,
1965 mine().after(CHILDREN).before(FOCUS),
1966 |req, did| {
1967 if req.kind != WindowKind::App {
1968 return Ok(());
1969 }
1970 let Some(app) = crate::bus::asking() else {
1971 return Ok(());
1972 };
1973 let (Some(d), Some(window)) = (
1974 app.service(&DIALOGS),
1975 app.window_viewport(&WindowId::new(&req.window)),
1976 ) else {
1977 return Ok(());
1978 };
1979 let waiting: Vec<u64> = lock(&d.0)
1980 .queue
1981 .iter()
1982 .filter(|o| o.group == Some(window))
1983 .map(|o| o.id)
1984 .collect();
1985 for id in &waiting {
1986 apply(&app, &d, *id, Answer::Cancel, Origin::User)?;
1987 }
1988 if !waiting.is_empty() {
1989 did.push(format!(
1990 "{CANCEL_ON_CLOSE}: {} waiting dialogs cancelled",
1991 waiting.len()
1992 ));
1993 }
1994 Ok(())
1995 },
1996 ),
1997 ];
1998 for l in listened {
1999 if let Err(e) = l {
2000 log::error!(target: "egui_pop", "{e}");
2001 }
2002 }
2003}
2004
2005fn show(ui: &mut Ui, app: &AppHandle) {
2007 let Some(d) = app.service(&DIALOGS) else {
2008 return;
2009 };
2010 let ctx = ui.ctx().clone();
2011 let here = ctx.viewport_id();
2012 let group = app.window_group(here);
2013 {
2016 let active = app.window_group(app.active_window());
2017 let mut s = lock(&d.0);
2018 for o in s.queue.iter_mut() {
2019 let g = app.window_group(o.group.unwrap_or(active));
2020 if o.group != Some(g) {
2021 o.group = Some(g);
2022 o.window = None;
2023 }
2024 }
2025 }
2026 let given: Vec<(u64, Answer, Origin)> = std::mem::take(&mut lock(&d.0).given);
2027 for (id, answer, origin) in given {
2028 if d.is_open(id)
2029 && let Err(e) = answer_step(app, &d, id, answer, origin)
2030 && let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == id)
2031 {
2032 o.error = Some(e);
2033 }
2034 }
2035 let Some((window, shown_id)) = ({
2040 let mut s = lock(&d.0);
2041 shown_at(&s, Some(group)).map(|i| {
2042 let o = &mut s.queue[i];
2043 (*o.window.get_or_insert_with(|| app.shown_in(group)), o.id)
2044 })
2045 }) else {
2046 return;
2047 };
2048 if app.still_open(window) != here {
2049 return;
2050 }
2051 let Some(mut open_dialog) = lock(&d.0).queue.iter().find(|o| o.id == shown_id).cloned() else {
2052 return;
2053 };
2054 for under in lock(&d.0)
2058 .queue
2059 .iter()
2060 .filter(|o| o.group == Some(group) && o.id != shown_id)
2061 .map(|o| o.id)
2062 .collect::<Vec<_>>()
2063 {
2064 overlay::close(&ctx, overlay_id(under));
2065 }
2066 if !open_dialog.focused {
2067 let out = app.step(&STEP_SHOW, d.describe_one(shown_id), |_, _| Ok(Json::Null));
2069 if out.vetoed().is_some() {
2070 if let Err(e) = apply(app, &d, shown_id, Answer::Cancel, Origin::User) {
2071 log::warn!(target: "egui_pop", "dialog: {e}");
2072 }
2073 return;
2074 }
2075 if !open_dialog.on_bus {
2077 let req = WindowRequest::new(
2078 open_dialog.popup(),
2079 WindowKind::Popup,
2080 open_dialog.owner(),
2081 Reason::Command,
2082 )
2083 .parent(app.registry_window_of(group));
2084 app.overlay_on_its_own(overlay_id(open_dialog.id));
2085 if app.request_popup_open(req) {
2086 open_dialog.on_bus = true;
2087 if let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == shown_id) {
2088 o.on_bus = true;
2089 }
2090 }
2091 }
2092 if let Some(key) = &open_dialog.remember {
2094 open_dialog.offset = remembered(app, key).unwrap_or(Vec2::ZERO);
2095 }
2096 }
2097 let filter = open_dialog.filter.clone();
2098 let closable = open_dialog.closable || setting(app, SETTING_CLOSABLE);
2099 let movable = open_dialog.movable || setting(app, SETTING_MOVABLE);
2100 let id = overlay_id(open_dialog.id);
2101 if movable {
2102 open_dialog.offset = clamp(&ctx, id, open_dialog.offset);
2104 if let Some(start) = open_dialog.moving {
2105 move_by_keys(app, &ctx, &mut open_dialog, start);
2106 }
2107 } else {
2108 open_dialog.offset = Vec2::ZERO;
2109 open_dialog.moving = None;
2110 open_dialog.drag_from = None;
2111 }
2112 let dragged = ctx.animate_bool_with_time(
2114 id.with("dragged"),
2115 open_dialog.drag_from.is_some(),
2116 Tokens::of(&ctx).motion_duration,
2117 );
2118 let dim = match open_dialog.backdrop {
2119 Backdrop::Dim => 1.0 - (1.0 - DRAG_DIM) * dragged,
2120 Backdrop::Clear => 0.0,
2121 };
2122 let mut spec = OverlaySpec::new(
2123 ("egui_pop.dialog", open_dialog.id),
2124 open_dialog.dialog.title(),
2125 Kind::Modal,
2126 )
2127 .offset(open_dialog.offset)
2128 .dim(dim);
2129 debug_assert_eq!(spec.id, id);
2130 let mut open = true;
2131 let mut answer: Option<Answer> = None;
2132 let closable = closable && spec.dismiss_on_escape;
2134 if let Dialog::Custom(c) = &open_dialog.dialog {
2135 spec = spec.width(
2136 c.body_size(ctx.content_rect().size())
2137 .x
2138 .min(overlay::modal_max_size(&ctx).x),
2139 );
2140 if c.claims_key(ClaimKey::Escape) {
2141 spec = spec.keep_on_escape();
2143 }
2144 }
2145 if open_dialog.moving.is_some() {
2146 spec = spec.keep_on_escape();
2148 }
2149 let mut closed = false;
2150 let mut band = Band::default();
2151 overlay::show(&ctx, &spec, &mut open, None, |ui| {
2152 let header = Header {
2153 closable,
2154 movable,
2155 closed: &mut closed,
2156 band: &mut band,
2157 };
2158 answer = body(ui, app, &mut open_dialog, header);
2159 });
2160 if movable {
2161 drag(app, &ctx, id, &mut open_dialog, &band);
2162 }
2163 if closed {
2166 open = false;
2167 answer = None;
2168 }
2169 if !open && answer.is_none() {
2170 answer = Some(Answer::Cancel);
2171 }
2172 if open_dialog.filter != filter
2173 && let Dialog::Choose(c) = &open_dialog.dialog
2174 {
2175 app.publish(
2176 "user",
2177 None,
2178 "dialog.filtered",
2179 json!({
2180 "id": open_dialog.id,
2181 "filter": open_dialog.filter,
2182 "shown": c.visible(&open_dialog.filter).len(),
2183 }),
2184 );
2185 }
2186 browse(app, &mut open_dialog);
2187 match answer {
2188 Some(a) => {
2189 if let Err(e) = answer_step(app, &d, shown_id, a, Origin::User) {
2190 open_dialog.error = Some(e);
2191 if let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == shown_id) {
2192 *o = open_dialog;
2193 }
2194 } else {
2195 overlay::close(&ctx, spec.id);
2196 }
2197 }
2198 None => {
2199 if let Some(o) = lock(&d.0).queue.iter_mut().find(|o| o.id == shown_id) {
2200 *o = open_dialog;
2201 }
2202 }
2203 }
2204}
2205
2206fn choice_row(ui: &mut Ui, selected: bool, text: egui::WidgetText) -> egui::Response {
2209 ui.add(widgets::SelectableRow::new(selected, text).wrap())
2210}
2211
2212struct CustomState<'a> {
2214 id: u64,
2215 values: &'a mut Map<String, Json>,
2216 ready: &'a mut bool,
2217 describe: &'a mut Json,
2218}
2219
2220fn custom_body(
2223 ui: &mut Ui,
2224 app: &AppHandle,
2225 c: &Custom,
2226 state: CustomState<'_>,
2227 first: bool,
2228) -> Option<Answer> {
2229 let CustomState {
2230 id,
2231 values,
2232 ready,
2233 describe,
2234 } = state;
2235 let (enter, ctrl_enter) = ui.input(|i| {
2236 let pressed = i.key_pressed(Key::Enter);
2237 let command = i.modifiers.command || i.modifiers.ctrl;
2238 (pressed && !command && !i.modifiers.alt, pressed && command)
2239 });
2240 let size = {
2244 let t = Tokens::of(ui.ctx());
2245 let spacing = ui.spacing().item_spacing.y;
2246 let above = ui.cursor().min.y - ui.min_rect().top();
2247 let below = t.space.m + ui.spacing().interact_size.y + 2.0 * spacing;
2248 let room = overlay::modal_max_size(ui.ctx()) - egui::vec2(0.0, above + below);
2249 c.body_size(ui.ctx().content_rect().size())
2250 .min(room)
2251 .max(Vec2::ZERO)
2252 };
2253 let mut pass = CustomPass {
2254 values: std::mem::take(values),
2255 ready: *ready,
2256 describe: std::mem::take(describe),
2257 escape: false,
2258 answer: None,
2259 };
2260 let bodies = app.local::<Bodies>();
2261 let taken = bodies.0.borrow_mut().remove(&id);
2262 match taken {
2263 Some(mut draw) => {
2264 ui.allocate_ui_with_layout(size, egui::Layout::top_down(egui::Align::Min), |ui| {
2265 ui.set_min_size(size);
2266 ui.set_max_size(size);
2267 egui_pop_core::focus::scope(ui, "dialog", &[], |ui| {
2268 egui_pop_core::fault::boundary(
2269 ui,
2270 ("egui_pop.dialog.body", id),
2271 &c.title,
2272 |ui| draw(ui, app, &mut pass),
2273 );
2274 });
2275 });
2276 bodies.0.borrow_mut().insert(id, draw);
2277 }
2278 None => {
2279 log::warn!(target: "egui_pop", "dialog `{}`: its body is gone", c.title);
2280 ui.allocate_space(size);
2281 }
2282 }
2283 let escape =
2287 c.claims_key(ClaimKey::Escape) && !pass.escape && ui.input(|i| i.key_pressed(Key::Escape));
2288 let mut answer = pass.answer.take();
2289 *values = std::mem::take(&mut pass.values);
2290 *ready = pass.ready;
2291 *describe = std::mem::take(&mut pass.describe);
2292 let focus_button = first && !c.claims_key(ClaimKey::Enter);
2295 if !c.footer {
2296 } else if c.command.is_none() && c.verb.is_empty() {
2298 let t = Tokens::of(ui.ctx());
2299 ui.add_space(t.space.m);
2300 let close = ui.button(strings::tr(ui.ctx(), &CLOSE));
2301 if focus_button {
2302 close.request_focus();
2303 }
2304 if close.clicked() {
2305 answer = Some(Answer::Accept {
2306 values: values.clone(),
2307 });
2308 }
2309 } else if let Some(a) = footer(
2310 ui,
2311 Buttons::two(ui.ctx(), &c.verb, c.danger),
2312 focus_button,
2313 None,
2314 ) {
2315 answer = Some(match a {
2316 Answer::Accept { .. } => Answer::Accept {
2317 values: values.clone(),
2318 },
2319 other => other,
2320 });
2321 }
2322 let by_key = if !c.footer {
2326 false
2327 } else if c.claims_key(ClaimKey::Enter) {
2328 ctrl_enter
2329 } else {
2330 ctrl_enter || (enter && !egui_pop_core::focus::text_input_owns_keyboard(ui.ctx()))
2331 };
2332 if answer.is_none() && by_key && !c.danger && *ready {
2333 answer = Some(Answer::Accept {
2334 values: values.clone(),
2335 });
2336 }
2337 if answer.is_none() && escape {
2338 answer = Some(Answer::Cancel);
2339 }
2340 answer
2341}
2342
2343fn values_of(fields: &[Field]) -> Map<String, Json> {
2345 fields
2346 .iter()
2347 .filter(|f| !f.descriptor.note)
2348 .map(|f| (f.key.clone(), f.value.to_json()))
2349 .collect()
2350}
2351
2352struct Header<'a> {
2354 closable: bool,
2355 movable: bool,
2356 closed: &'a mut bool,
2358 band: &'a mut Band,
2360}
2361
2362fn body(ui: &mut Ui, app: &AppHandle, o: &mut Open, header: Header<'_>) -> Option<Answer> {
2364 let t = Tokens::of(ui.ctx());
2365 let first = !o.focused;
2366 o.focused = true;
2367 let title = o.dialog.title().to_string();
2368 let Header {
2369 closable,
2370 movable,
2371 closed,
2372 band,
2373 } = header;
2374 let heading = if movable {
2375 header_band(ui, &title, closable, closed, band)
2376 } else {
2377 title_row(ui, &title, closable, closed)
2378 };
2379 ui.add_space(t.space.s);
2380 let mut answer = None;
2381 let enter = ui.input(|i| i.key_pressed(Key::Enter));
2382 match &mut o.dialog {
2383 Dialog::Confirm(c) => {
2384 if !c.detail.is_empty() {
2385 ui.label(&c.detail);
2386 }
2387 if c.details.shown(false) {
2388 details_section(ui, o.id, &c.details);
2389 }
2390 let (verb, danger) = (c.verb.clone(), c.danger);
2391 let buttons = Buttons {
2392 verb: &verb,
2393 danger,
2394 secondary: c.secondary.as_ref().map(|s| (s.verb.as_str(), s.danger)),
2395 cancel: &c.cancel,
2396 order: c.order.unwrap_or_else(|| ButtonOrder::of(ui.ctx())),
2397 };
2398 let copy = c.copy.then(|| (c.copy_text(), &mut o.copied_at));
2399 if let Some(a) = footer(ui, buttons, first, copy) {
2400 answer = Some(a);
2401 } else if enter && !danger && !copied_now(ui, o.copied_at) {
2402 answer = Some(Answer::Accept { values: Map::new() });
2403 }
2404 }
2405 Dialog::Info(i) => {
2406 ui.label(&i.text);
2407 if i.details.shown(i.error) {
2408 details_section(ui, o.id, &i.details);
2409 }
2410 ui.add_space(t.space.m);
2411 let copy = i.copy.then(|| (i.copy_text(), &mut o.copied_at));
2412 let close = ui
2413 .with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
2414 let close = ui.button(strings::tr(ui.ctx(), &CLOSE));
2415 if let Some((text, at)) = copy {
2416 copy_corner(ui, &text, at);
2417 }
2418 close
2419 })
2420 .inner;
2421 if first {
2422 close.request_focus();
2423 }
2424 if close.clicked() || (enter && !copied_now(ui, o.copied_at)) {
2426 answer = Some(Answer::Accept { values: Map::new() });
2427 }
2428 }
2429 Dialog::Choose(c) => {
2430 if !c.detail.is_empty() {
2431 ui.label(&c.detail);
2432 }
2433 ui.add_space(t.space.s);
2434 let (down, up) = ui.input_mut(|i| {
2436 (
2437 i.consume_key(egui::Modifiers::NONE, Key::ArrowDown),
2438 i.consume_key(egui::Modifiers::NONE, Key::ArrowUp),
2439 )
2440 });
2441 let field = ui
2442 .add(
2443 egui::TextEdit::singleline(&mut o.filter)
2444 .hint_text(strings::tr(ui.ctx(), &txt::DIALOG_FILTER))
2445 .desired_width(f32::INFINITY),
2446 )
2447 .labelled_by(heading.id);
2448 if first {
2449 field.request_focus();
2450 }
2451 let shown = c.visible(&o.filter);
2452 if field.changed() {
2453 o.highlight = 0;
2454 }
2455 if down {
2456 o.highlight = (o.highlight + 1).min(shown.len().saturating_sub(1));
2457 }
2458 if up {
2459 o.highlight = o.highlight.saturating_sub(1);
2460 }
2461 ui.add_space(t.space.s);
2462 ui.scroll_area(
2463 egui::ScrollArea::vertical()
2464 .id_salt("egui_pop.choose")
2465 .max_height(320.0),
2466 |ui| {
2467 let rows = egui::Layout::top_down_justified(egui::Align::Min);
2469 ui.with_layout(rows, |ui| {
2470 for (n, &i) in shown.iter().enumerate() {
2471 let option = &c.options[i];
2472 let text = if option.hint.is_empty() {
2473 egui::WidgetText::from(option.label.as_str())
2474 } else {
2475 egui::WidgetText::from(format!(
2476 "{} · {}",
2477 option.label, option.hint
2478 ))
2479 };
2480 let b = choice_row(ui, n == o.highlight, text);
2481 if n == o.highlight && (down || up) {
2482 b.scroll_to_me(None);
2483 }
2484 if b.clicked() {
2485 answer = Some(Answer::Choose { index: i });
2486 }
2487 }
2488 });
2489 if shown.is_empty() {
2490 ui.weak(strings::tr(ui.ctx(), &txt::NOTHING_MATCHES));
2491 }
2492 },
2493 );
2494 if enter && let Some(&i) = shown.get(o.highlight) {
2495 answer = Some(Answer::Choose { index: i });
2496 }
2497 ui.add_space(t.space.m);
2498 if ui.button(strings::tr(ui.ctx(), &CANCEL)).clicked() {
2499 answer = Some(Answer::Cancel);
2500 }
2501 }
2502 Dialog::Custom(c) => {
2503 let state = CustomState {
2504 id: o.id,
2505 values: &mut o.values,
2506 ready: &mut o.ready,
2507 describe: &mut o.body,
2508 };
2509 answer = custom_body(ui, app, c, state, first);
2510 }
2511 Dialog::Form(f) => {
2512 let browse = &mut o.browse;
2513 egui::Grid::new(("egui_pop.form", &f.title))
2514 .num_columns(2)
2515 .spacing([t.space.m, t.space.s])
2516 .show(ui, |ui| {
2517 for (n, field) in f.fields.iter_mut().enumerate() {
2518 if field.descriptor.note {
2520 ui.label("");
2521 ui.weak(&field.descriptor.label);
2522 ui.end_row();
2523 continue;
2524 }
2525 let label = ui.label(&field.descriptor.label);
2526 let r = edit_field(ui, field, browse, &f.command, label.id);
2527 if first && n == 0 {
2528 r.request_focus();
2529 }
2530 ui.end_row();
2531 }
2532 });
2533 if let Some((key, picker)) = o.picking.as_mut()
2534 && let Some(field) = f.fields.iter_mut().find(|x| x.key == *key)
2535 {
2536 ui.separator();
2537 match picker.show(
2538 ui,
2539 &files::Places {
2540 home: files::home(),
2541 ..Default::default()
2542 },
2543 ) {
2544 Some(PickerAnswer::Chosen(p)) => {
2545 if let Some(p) = p.first() {
2546 field.value = Value::Text(p.display().to_string());
2547 }
2548 o.picking = None;
2549 }
2550 Some(PickerAnswer::Cancel) => o.picking = None,
2551 Some(_) | None => {}
2555 }
2556 }
2557 if let Some(id) = o.choosing.as_ref().map(|(_, id, _)| *id)
2559 && let Some(files) = app.service(&FILES)
2560 {
2561 ui.separator();
2562 files.show_inline(ui, app, id);
2563 }
2564 let verb = f.verb.clone();
2565 if let Some(a) = footer(ui, Buttons::two(ui.ctx(), &verb, false), false, None) {
2566 answer = Some(match a {
2567 Answer::Accept { .. } => Answer::Accept {
2568 values: values_of(&f.fields),
2569 },
2570 other => other,
2571 });
2572 } else if enter
2573 && !ui.ctx().text_edit_focused()
2574 && o.picking.is_none()
2575 && o.choosing.is_none()
2576 {
2577 answer = Some(Answer::Accept {
2578 values: values_of(&f.fields),
2579 });
2580 }
2581 }
2582 }
2583 if let Some(e) = &o.error {
2584 ui.colored_label(t.status.danger, e);
2585 }
2586 paint_band(ui, band);
2587 answer
2588}
2589
2590fn band_style(k: &Kit) -> band::BandStyle {
2593 band::BandStyle {
2594 padding: k.dialog.data.padding_x,
2595 gap: k.dialog_header.data.padding_y,
2596 }
2597}
2598
2599fn header_band(
2603 ui: &mut Ui,
2604 title: &str,
2605 closable: bool,
2606 closed: &mut bool,
2607 out: &mut Band,
2608) -> Response {
2609 let kit = Kit::of(ui.ctx());
2610 let side = close_side(ui);
2611 let (heading, b) = band::begin(ui, &band_style(&kit), |ui, state| {
2612 ui.horizontal_top(|ui| {
2613 let room = if closable {
2614 (ui.available_width() - side - ui.spacing().item_spacing.x).max(0.0)
2615 } else {
2616 ui.available_width()
2617 };
2618 let heading = ui
2620 .allocate_ui(egui::vec2(room, side), |ui| {
2621 ui.add(
2622 egui::Label::new(
2623 egui::RichText::new(title)
2624 .heading()
2625 .color(kit.dialog_header.style(state).text),
2626 )
2627 .wrap()
2628 .selectable(false),
2629 )
2630 })
2631 .inner;
2632 if closable {
2633 ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
2634 if close_button(ui, side).clicked() {
2635 *closed = true;
2636 }
2637 });
2638 }
2639 heading
2640 })
2641 .inner
2642 });
2643 *out = Band(Some(b));
2644 heading
2645}
2646
2647fn paint_band(ui: &Ui, b: &Band) {
2649 if let Some(b) = &b.0 {
2650 band::paint(ui, b, &band_style(&Kit::of(ui.ctx())));
2651 }
2652}
2653
2654#[derive(Debug, Default)]
2656struct Band(Option<band::Band>);
2657
2658fn setting(app: &AppHandle, id: SettingId) -> bool {
2660 lock(&app.store())
2661 .get(&format!("settings/{id}"))
2662 .and_then(|e| e.value.as_bool())
2663 .unwrap_or(false)
2664}
2665
2666fn clamp(ctx: &egui::Context, id: egui::Id, offset: Vec2) -> Vec2 {
2669 let Some(rect) = overlay::rect(ctx, id) else {
2670 return offset;
2671 };
2672 let room = ((ctx.content_rect().size() - rect.size()) / 2.0).max(Vec2::ZERO);
2673 offset.clamp(-room, room)
2674}
2675
2676fn drag(app: &AppHandle, ctx: &egui::Context, id: egui::Id, o: &mut Open, band: &Band) {
2680 let Some(band) = &band.0 else {
2681 return;
2682 };
2683 if band.double_clicked {
2684 o.drag_from = None;
2685 o.moving = None;
2686 let from = o.offset;
2687 move_to(app, o, "recentre", from, Vec2::ZERO);
2688 return;
2689 }
2690 if band.dragging && o.drag_from.is_none() {
2691 o.drag_from = Some(o.offset);
2692 o.moving = None;
2693 }
2694 if band.dragging && band.delta != Vec2::ZERO {
2695 o.offset = clamp(ctx, id, o.offset + band.delta);
2696 ctx.request_repaint();
2697 }
2698 if !band.dragging
2700 && let Some(from) = o.drag_from.take()
2701 {
2702 let to = o.offset;
2703 move_to(app, o, "drag", from, to);
2704 ctx.request_repaint();
2705 }
2706}
2707
2708fn move_by_keys(app: &AppHandle, ctx: &egui::Context, o: &mut Open, start: Vec2) {
2711 let step = Tokens::of(ctx).space.m;
2712 let (by, enter, escape) = ctx.input_mut(|i| {
2713 let mut by = Vec2::ZERO;
2714 for (key, dir) in [
2715 (Key::ArrowLeft, egui::vec2(-1.0, 0.0)),
2716 (Key::ArrowRight, egui::vec2(1.0, 0.0)),
2717 (Key::ArrowUp, egui::vec2(0.0, -1.0)),
2718 (Key::ArrowDown, egui::vec2(0.0, 1.0)),
2719 ] {
2720 while i.consume_key(Modifiers::SHIFT, key) {
2722 by += dir * step * BIG_STEP;
2723 }
2724 while i.consume_key(Modifiers::NONE, key) {
2725 by += dir * step;
2726 }
2727 }
2728 (
2729 by,
2730 i.consume_key(Modifiers::NONE, Key::Enter),
2731 i.consume_key(Modifiers::NONE, Key::Escape),
2732 )
2733 });
2734 let id = overlay_id(o.id);
2735 if by != Vec2::ZERO {
2736 let from = o.offset;
2737 let to = clamp(ctx, id, from + by);
2738 move_to(app, o, "keys", from, to);
2739 }
2740 if escape {
2741 let from = o.offset;
2742 move_to(app, o, "keys", from, start);
2743 o.moving = None;
2744 } else if enter {
2745 o.moving = None;
2746 }
2747}
2748
2749fn move_to(app: &AppHandle, o: &mut Open, how: &str, from: Vec2, to: Vec2) {
2753 if from == to {
2754 o.offset = to;
2755 return;
2756 }
2757 let args = json!({
2758 "id": o.id,
2759 "title": o.dialog.title(),
2760 "key": o.remember,
2761 "how": how,
2762 "from": [from.x, from.y],
2763 "to": [to.x, to.y],
2764 });
2765 let out = app.step(&STEP_MOVE, args, |_, args| Ok(json!({ "to": args["to"] })));
2766 let placed = match out {
2767 Outcome::Done(Ok(result)) => vec2_of(&result["to"]),
2768 Outcome::Done(Err(e)) => {
2769 log::info!(target: "egui_pop", "dialog.move: {e}");
2770 None
2771 }
2772 Outcome::Vetoed { .. } => None,
2773 };
2774 let Some(at) = placed else {
2775 o.offset = from;
2776 return;
2777 };
2778 o.offset = at;
2779 app.publish(
2780 "user",
2781 None,
2782 "dialog.moved",
2783 json!({ "id": o.id, "title": o.dialog.title(), "how": how, "offset": [at.x, at.y] }),
2784 );
2785 if let Some(key) = &o.remember {
2786 remember(app, key, at);
2787 }
2788}
2789
2790fn vec2_of(json: &Json) -> Option<Vec2> {
2792 let a = json.as_array()?;
2793 match a.as_slice() {
2794 [x, y] => Some(egui::vec2(x.as_f64()? as f32, y.as_f64()? as f32)),
2795 _ => None,
2796 }
2797}
2798
2799fn position_path(app: &AppHandle, key: &str) -> Option<String> {
2802 let path = format!("ui/dialogs/{key}");
2803 let store = app.store();
2804 let mut s = lock(&store);
2805 if s.get(&path).is_none()
2806 && let Err(e) = s.declare(
2807 &OwnerId::from(&PLUGIN),
2808 &path,
2809 Descriptor::floats("Dialog position", 2, -1.0e6, 1.0e6, &[0.0, 0.0])
2810 .description("A dialog's offset from the window's centre, in points."),
2811 )
2812 {
2813 log::warn!(target: "egui_pop", "dialog position `{key}`: {e}");
2814 return None;
2815 }
2816 Some(path)
2817}
2818
2819fn remembered(app: &AppHandle, key: &str) -> Option<Vec2> {
2821 let path = position_path(app, key)?;
2822 match &lock(&app.store()).get(&path)?.value {
2823 Value::Floats(v) if v.len() == 2 => Some(egui::vec2(v[0] as f32, v[1] as f32)),
2824 _ => None,
2825 }
2826}
2827
2828fn remember(app: &AppHandle, key: &str, offset: Vec2) {
2830 let Some(path) = position_path(app, key) else {
2831 return;
2832 };
2833 let set = Set::new(
2834 &path,
2835 Change::To(Value::Floats(vec![
2836 f64::from(offset.x),
2837 f64::from(offset.y),
2838 ])),
2839 Origin::User,
2840 )
2841 .by(&OwnerId::FRAMEWORK)
2842 .untracked();
2843 if let Err(e) = lock(&app.store()).set(set) {
2844 log::warn!(target: "egui_pop", "dialog position `{key}`: {e:?}");
2845 }
2846}
2847
2848fn title_row(ui: &mut Ui, title: &str, closable: bool, closed: &mut bool) -> Response {
2852 let text = egui::RichText::new(title)
2853 .heading()
2854 .color(Kit::of(ui.ctx()).dialog_header.style(kit::State::REST).text);
2855 if !closable {
2856 return ui.label(text);
2857 }
2858 let side = close_side(ui);
2859 ui.horizontal_top(|ui| {
2860 let room = (ui.available_width() - side - ui.spacing().item_spacing.x).max(0.0);
2862 let heading = ui
2863 .allocate_ui(egui::vec2(room, side), |ui| {
2864 ui.add(egui::Label::new(text).wrap())
2865 })
2866 .inner;
2867 ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
2868 if close_button(ui, side).clicked() {
2869 *closed = true;
2870 }
2871 });
2872 heading
2873 })
2874 .inner
2875}
2876
2877fn close_side(ui: &Ui) -> f32 {
2880 Tokens::of(ui.ctx()).size.control_height.max(24.0)
2881}
2882
2883fn close_button(ui: &mut Ui, side: f32) -> Response {
2886 let name = strings::tr(ui.ctx(), &CLOSE);
2887 let glyph = Kit::of(ui.ctx()).glyph(kit::Glyph::Close);
2888 band::button(ui, side, glyph, &name, false)
2889}
2890
2891struct Buttons<'a> {
2897 verb: &'a str,
2898 danger: bool,
2899 secondary: Option<(&'a str, bool)>,
2900 cancel: &'a str,
2901 order: ButtonOrder,
2902}
2903
2904impl<'a> Buttons<'a> {
2905 fn two(ctx: &egui::Context, verb: &'a str, danger: bool) -> Self {
2908 Self {
2909 verb,
2910 danger,
2911 secondary: None,
2912 cancel: "",
2913 order: ButtonOrder::of(ctx),
2914 }
2915 }
2916}
2917
2918fn toned_button(ui: &mut Ui, verb: &str, danger: bool) -> egui::Response {
2922 let t = Tokens::of(ui.ctx());
2923 let button = if danger {
2924 egui::Button::new(egui::RichText::new(verb).color(t.status.danger))
2925 .stroke(egui::Stroke::new(1.0, t.status.danger))
2926 } else {
2927 egui::Button::new(verb)
2928 };
2929 ui.add(button)
2930}
2931
2932fn footer(
2933 ui: &mut Ui,
2934 buttons: Buttons<'_>,
2935 first: bool,
2936 copy: Option<(String, &mut Option<f64>)>,
2937) -> Option<Answer> {
2938 let t = Tokens::of(ui.ctx());
2939 ui.add_space(t.space.m);
2940 let mut answer = None;
2941 let Buttons {
2942 verb,
2943 danger,
2944 secondary,
2945 cancel,
2946 order,
2947 } = buttons;
2948 let cancel_text = if cancel.is_empty() {
2949 strings::tr(ui.ctx(), &CANCEL)
2950 } else {
2951 cancel.to_string()
2952 };
2953 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
2954 let (p, second, cancel) = match order {
2956 ButtonOrder::PrimaryLast => {
2957 let p = toned_button(ui, verb, danger);
2958 let cancel = ui.button(&cancel_text);
2959 let second = secondary.map(|(v, d)| {
2960 ui.add_space(t.space.l);
2961 toned_button(ui, v, d)
2962 });
2963 (p, second, cancel)
2964 }
2965 ButtonOrder::PrimaryFirst => {
2966 let cancel = ui.button(&cancel_text);
2967 let second = secondary.map(|(v, d)| toned_button(ui, v, d));
2968 let p = toned_button(ui, verb, danger);
2969 (p, second, cancel)
2970 }
2971 };
2972 if first {
2975 if danger {
2976 cancel.request_focus();
2977 } else {
2978 p.request_focus();
2979 }
2980 }
2981 if p.clicked() {
2982 answer = Some(Answer::Accept { values: Map::new() });
2983 }
2984 if second.as_ref().is_some_and(egui::Response::clicked) {
2985 answer = Some(Answer::Choose { index: 1 });
2986 }
2987 if cancel.clicked() {
2988 answer = Some(Answer::Cancel);
2989 }
2990 if let Some((text, at)) = copy {
2991 copy_corner(ui, &text, at);
2992 }
2993 });
2994 answer
2995}
2996
2997const COPIED_FOR: f64 = 2.0;
2999
3000fn copy_corner(ui: &mut Ui, text: &str, at: &mut Option<f64>) {
3006 ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
3007 let ctx = ui.ctx().clone();
3008 let name = strings::tr(&ctx, &txt::DIALOG_COPY);
3009 let button = ui.add(Icon::Copy.size(IconSize::Inline).label(&name).sense_click());
3010 let now = ctx.input(|i| i.time);
3011 if button.clicked() {
3012 ctx.copy_text(text.to_string());
3013 *at = Some(now);
3014 }
3015 if let Some(when) = *at {
3016 let left = COPIED_FOR - (now - when);
3017 if left > 0.0 {
3018 ui.text_role(TextRole::Muted, strings::tr(&ctx, &txt::DIALOG_COPIED));
3019 ctx.request_repaint_after_secs(left as f32);
3020 } else {
3021 *at = None;
3022 }
3023 }
3024 });
3025}
3026
3027fn copied_now(ui: &Ui, at: Option<f64>) -> bool {
3029 at == Some(ui.input(|i| i.time))
3030}
3031
3032fn details_section(ui: &mut Ui, id: u64, details: &Details) {
3036 let text = details.text();
3037 let title = strings::tr(ui.ctx(), &txt::DIALOG_DETAILS);
3038 egui::CollapsingHeader::new(&title)
3039 .id_salt(("egui_pop.dialog.details", id))
3040 .default_open(false)
3041 .show(ui, |ui| {
3042 let mut shown = text.as_str();
3043 ui.add(
3044 egui::TextEdit::multiline(&mut shown)
3045 .font(egui::TextStyle::Monospace)
3046 .desired_width(f32::INFINITY)
3047 .desired_rows(details.lines.len().clamp(1, 8)),
3048 )
3049 .on_hover_text(&title);
3050 });
3051}
3052
3053fn edit_field(
3055 ui: &mut Ui,
3056 field: &mut Field,
3057 browse: &mut Option<(String, FileRequest)>,
3058 command: &CommandId,
3059 label: egui::Id,
3060) -> Response {
3061 let d = &field.descriptor;
3062 let r = match (&mut field.value, d.ty) {
3063 (Value::Bool(v), _) => widgets::checkbox(ui, v, ""),
3064 (Value::Float(v), _) => {
3065 let (lo, hi) = d.soft.or(d.hard).unwrap_or((0.0, 1.0));
3066 ui.add(
3067 egui::DragValue::new(v)
3068 .range(lo..=hi)
3069 .speed(d.step)
3070 .max_decimals(d.precision as usize),
3071 )
3072 }
3073 (Value::Int(v), _) => {
3074 let (lo, hi) = d.hard.unwrap_or((i64::MIN as f64, i64::MAX as f64));
3075 ui.add(egui::DragValue::new(v).range(lo as i64..=hi as i64))
3076 }
3077 (Value::Choice(v), _) => {
3078 let mut picked = v.clone();
3079 let combo = widgets::combo_box(("egui_pop.form.choice", &field.key))
3080 .selected_text(picked.as_str());
3081 let r = ui
3082 .combo_box(combo, |ui| {
3083 for c in &d.choices {
3084 widgets::selectable_value(ui, &mut picked, c.clone(), c);
3085 }
3086 })
3087 .response;
3088 *v = picked;
3089 r
3090 }
3091 (Value::Text(v), Type::Text) => {
3092 let path = d.path.clone();
3093 ui.horizontal(|ui| {
3094 let r = ui.text_edit_singleline(v);
3095 egui_pop_core::focus_mode::follow_pointer(&r);
3096 if let Some(hint) = path
3097 && ui
3098 .button(strings::tr(ui.ctx(), &txt::DIALOG_BROWSE))
3099 .clicked()
3100 {
3101 *browse = Some((
3102 field.key.clone(),
3103 request_for(
3104 &field.descriptor.label,
3105 v,
3106 &hint,
3107 &format!("{command}.{}", field.key),
3108 ),
3109 ));
3110 }
3111 r
3112 })
3113 .inner
3114 }
3115 (v, _) => ui.monospace(v.to_json().to_string()),
3116 };
3117 r.labelled_by(label)
3118}
3119
3120fn request_for(label: &str, value: &str, hint: &PathHint, purpose: &str) -> FileRequest {
3125 let title = hint.title.as_deref().unwrap_or(label);
3126 let mut r = match hint.kind {
3127 PathKind::Dir => FileRequest::folder(title),
3128 PathKind::File => FileRequest::open(title),
3129 }
3130 .purpose(hint.purpose.as_deref().unwrap_or(purpose));
3131 r = match value_dir(value) {
3132 Some(dir) => r.force_directory(dir),
3133 None => r.directory(start_dir(value)),
3134 };
3135 if !hint.extensions.is_empty() {
3136 let exts: Vec<&str> = hint.extensions.iter().map(String::as_str).collect();
3137 let name = hint.filter_name.clone().unwrap_or_else(|| exts.join(", "));
3138 r = r.filter(&name, &exts);
3139 }
3140 r
3141}
3142
3143fn value_dir(value: &str) -> Option<PathBuf> {
3146 if value.trim().is_empty() {
3147 return None;
3148 }
3149 let p = Path::new(value);
3150 if p.is_dir() {
3151 return Some(p.to_path_buf());
3152 }
3153 p.parent().filter(|d| d.is_dir()).map(Path::to_path_buf)
3154}
3155
3156fn browse(app: &AppHandle, o: &mut Open) {
3160 if let Some((key, request)) = o.browse.take() {
3161 match app.service(&FILES) {
3162 Some(f) => {
3163 let (id, pending) = f.choose_inline(app, request);
3164 o.choosing = Some((key, id, pending));
3165 }
3166 None => o.picking = Some((key, FilePicker::new(&request))),
3167 }
3168 }
3169 let Some(result) = o.choosing.as_ref().and_then(|(_, _, p)| p.take()) else {
3170 return;
3171 };
3172 let Some((key, ..)) = o.choosing.take() else {
3173 return;
3174 };
3175 match files::chosen(&result) {
3176 Ok(files::Chosen::Paths(paths)) => {
3177 if let (Dialog::Form(f), Some(p)) = (&mut o.dialog, paths.first())
3178 && let Some(field) = f.fields.iter_mut().find(|x| x.key == key)
3179 {
3180 field.value = Value::Text(p.display().to_string());
3181 }
3182 }
3183 Ok(files::Chosen::Cancelled) => {}
3184 Err(e) => o.error = Some(e),
3185 }
3186}
3187
3188fn start_dir(value: &str) -> PathBuf {
3190 let p = Path::new(value);
3191 if p.is_dir() {
3192 return p.to_path_buf();
3193 }
3194 if let Some(parent) = p.parent().filter(|d| d.is_dir()) {
3195 return parent.to_path_buf();
3196 }
3197 std::env::var_os("HOME")
3198 .or_else(|| std::env::var_os("USERPROFILE"))
3199 .map(PathBuf::from)
3200 .filter(|d| d.is_dir())
3201 .unwrap_or_else(|| PathBuf::from("/"))
3202}
3203
3204pub fn entries(dir: &Path, hint: &PathHint) -> Vec<(PathBuf, bool)> {
3208 let Ok(read) = std::fs::read_dir(dir) else {
3209 return Vec::new();
3210 };
3211 let mut out: Vec<(PathBuf, bool)> = read
3212 .filter_map(Result::ok)
3213 .map(|e| e.path())
3214 .filter(|p| {
3215 !p.file_name()
3216 .and_then(|n| n.to_str())
3217 .is_some_and(|n| n.starts_with('.'))
3218 })
3219 .filter_map(|p| {
3220 let is_dir = p.is_dir();
3221 (is_dir || (hint.kind == PathKind::File && hint.accepts(&p))).then_some((p, is_dir))
3222 })
3223 .collect();
3224 out.sort_by(|a, b| (!a.1, &a.0).cmp(&(!b.1, &b.0)));
3225 out
3226}