1use std::cell::{Cell, RefCell};
64use std::collections::BTreeMap;
65use std::fmt;
66use std::thread::ThreadId;
67
68use egui::{Context, Ui, Vec2, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId};
69use serde::{Deserialize, Serialize};
70use serde_json::json;
71
72use crate::app::{AppHandle, WeakApp};
73use crate::bus::{Reason, WindowKind, WindowRequest};
74
75pub const CONTEXT_APP_WINDOW: &str = "appWindow";
78
79pub const GEOMETRY_DOC: &str = "windows";
81
82#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
85#[serde(transparent)]
86pub struct WindowId(String);
87
88impl WindowId {
89 pub const MAIN: &'static str = "main";
91
92 pub fn new(id: impl Into<String>) -> Self {
93 Self(id.into())
94 }
95
96 pub fn main() -> Self {
98 Self(Self::MAIN.to_string())
99 }
100
101 pub fn as_str(&self) -> &str {
102 &self.0
103 }
104
105 pub(crate) fn deferred_viewport(&self) -> ViewportId {
107 ViewportId::from_hash_of(("egui_pop.app_window", self.0.as_str()))
108 }
109}
110
111impl fmt::Display for WindowId {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 f.write_str(&self.0)
114 }
115}
116
117impl From<&str> for WindowId {
118 fn from(s: &str) -> Self {
119 Self::new(s)
120 }
121}
122
123#[derive(Clone, Debug, PartialEq)]
125pub struct WindowSpec {
126 pub id: WindowId,
127 pub title: String,
129 pub size: Option<Vec2>,
131 pub min_size: Option<Vec2>,
132 pub shell_bars: bool,
135 pub centre_dock: bool,
138}
139
140impl WindowSpec {
141 pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
142 Self {
143 id: WindowId::new(id),
144 title: title.into(),
145 size: None,
146 min_size: None,
147 shell_bars: false,
148 centre_dock: false,
149 }
150 }
151
152 pub fn shell_bars(mut self, on: bool) -> Self {
165 self.shell_bars = on;
166 self
167 }
168
169 pub fn centre_dock(mut self, on: bool) -> Self {
181 self.centre_dock = on;
182 self
183 }
184
185 pub fn size(mut self, size: impl Into<Vec2>) -> Self {
186 self.size = Some(size.into());
187 self
188 }
189
190 pub fn min_size(mut self, size: impl Into<Vec2>) -> Self {
191 self.min_size = Some(size.into());
192 self
193 }
194}
195
196#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
198pub struct Geometry {
199 pub size: [f32; 2],
201 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub position: Option<[f32; 2]>,
204 #[serde(default)]
205 pub maximized: bool,
206 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
207 pub fullscreen: bool,
208}
209
210impl Geometry {
211 pub fn follow(kept: Option<Geometry>, seen: Geometry) -> Geometry {
217 let Some(mut g) = kept else { return seen };
218 g.maximized = seen.maximized;
219 g.fullscreen = seen.fullscreen;
220 if !seen.maximized && !seen.fullscreen {
221 g.size = seen.size;
222 if seen.position.is_some() {
223 g.position = seen.position;
224 }
225 }
226 g
227 }
228}
229
230#[derive(Clone, Debug, PartialEq, Serialize)]
232pub struct WindowInfo {
233 pub id: WindowId,
234 pub title: String,
235 pub main: bool,
237 pub active: bool,
239 pub focused: Option<bool>,
242 pub geometry: Option<Geometry>,
244 #[serde(skip)]
245 pub viewport: ViewportId,
246}
247
248pub struct WindowUi<'a> {
250 app: &'a AppHandle,
251 id: WindowId,
252 title: String,
253 class: ViewportClass,
254 close_requested: bool,
255 keep_open: bool,
256 close: bool,
257}
258
259impl fmt::Debug for WindowUi<'_> {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 f.debug_struct("WindowUi")
262 .field("id", &self.id)
263 .field("title", &self.title)
264 .finish_non_exhaustive()
265 }
266}
267
268impl<'a> WindowUi<'a> {
269 pub fn id(&self) -> &WindowId {
270 &self.id
271 }
272
273 pub fn app(&self) -> &'a AppHandle {
274 self.app
275 }
276
277 pub fn title(&self) -> &str {
279 &self.title
280 }
281
282 pub fn set_title(&mut self, title: impl Into<String>) {
285 self.title = title.into();
286 }
287
288 pub fn close_requested(&self) -> bool {
291 self.close_requested
292 }
293
294 pub fn keep_open(&mut self) {
297 self.keep_open = true;
298 }
299
300 pub fn close(&mut self) {
302 self.close = true;
303 }
304
305 pub fn embedded(&self) -> bool {
308 self.class == ViewportClass::EmbeddedWindow
309 }
310}
311
312pub type Content = Box<dyn FnMut(&mut Ui, &mut WindowUi<'_>)>;
314
315pub(crate) struct Entry {
316 pub(crate) id: WindowId,
317 pub(crate) title: String,
318 sent_title: Option<String>,
320 content: Option<Content>,
322 first: (Option<Vec2>, Option<[f32; 2]>, bool, bool),
325 min_size: Option<Vec2>,
326 shell_bars: bool,
328 centre_dock: bool,
330 pub(crate) geometry: Option<Geometry>,
331 pub(crate) focused: Option<bool>,
332 pub(crate) focused_panel: Option<egui_pop_model::ids::PanelId>,
335 dispatcher: Option<crate::app::WindowKeys>,
336 pub(crate) closed: bool,
337}
338
339pub(crate) struct Root {
342 pub(crate) id: WindowId,
343 pub(crate) home: WindowId,
346 pub(crate) title: Option<String>,
348 sent_title: Option<String>,
349 content: Option<Content>,
350 pub(crate) geometry: Option<Geometry>,
351 home_title: Option<String>,
354 min_size: Option<Vec2>,
356 shell_bars: bool,
358 centre_dock: bool,
360}
361
362pub(crate) struct Windows {
364 pub(crate) root: Root,
365 pub(crate) entries: Vec<Entry>,
367 saved: Option<BTreeMap<String, Geometry>>,
368 going_home: bool,
372 quitting: bool,
375 pub(crate) moved_places: Vec<(WindowId, Geometry)>,
378 pub(crate) moved_events: Vec<(&'static str, serde_json::Value)>,
380}
381
382impl Default for Windows {
383 fn default() -> Self {
384 Self {
385 root: Root {
386 id: WindowId::main(),
387 home: WindowId::main(),
388 title: None,
389 sent_title: None,
390 content: None,
391 geometry: None,
392 home_title: None,
393 min_size: None,
394 shell_bars: false,
395 centre_dock: false,
396 },
397 entries: Vec::new(),
398 saved: None,
399 going_home: false,
400 quitting: false,
401 moved_places: Vec::new(),
402 moved_events: Vec::new(),
403 }
404 }
405}
406
407impl Windows {
408 pub(crate) fn entry(&self, id: &WindowId) -> Option<&Entry> {
409 self.entries.iter().find(|e| &e.id == id && !e.closed)
410 }
411
412 fn entry_mut(&mut self, id: &WindowId) -> Option<&mut Entry> {
413 self.entries.iter_mut().find(|e| &e.id == id && !e.closed)
414 }
415
416 pub(crate) fn by_viewport(&self, viewport: ViewportId) -> Option<&Entry> {
417 self.entries
418 .iter()
419 .find(|e| !e.closed && e.id.deferred_viewport() == viewport)
420 }
421
422 pub(crate) fn viewport_of(&self, id: &WindowId) -> Option<ViewportId> {
423 if &self.root.id == id {
424 return Some(ViewportId::ROOT);
425 }
426 self.entry(id).map(|e| e.id.deferred_viewport())
427 }
428}
429
430thread_local! {
431 static MAIN_THREAD: Cell<Option<ThreadId>> = const { Cell::new(None) };
433 static REGISTRY: RefCell<BTreeMap<ViewportId, (WeakApp, WindowId)>> =
435 const { RefCell::new(BTreeMap::new()) };
436}
437
438thread_local! {
439 static CURRENT: Cell<Option<ViewportId>> = const { Cell::new(None) };
443}
444
445pub(crate) fn current_group() -> Option<ViewportId> {
448 CURRENT.with(Cell::get)
449}
450
451pub(crate) struct GroupGuard(Option<ViewportId>);
453
454impl Drop for GroupGuard {
455 fn drop(&mut self) {
456 CURRENT.with(|c| c.set(self.0));
457 }
458}
459
460pub(crate) fn enter_group(group: Option<ViewportId>) -> GroupGuard {
463 let before = current_group();
464 if group.is_some() {
465 CURRENT.with(|c| c.set(group));
466 }
467 GroupGuard(before)
468}
469
470pub(crate) fn forget_viewport(viewport: ViewportId) {
473 REGISTRY.with(|r| r.borrow_mut().remove(&viewport));
474}
475
476fn on_main_thread() -> bool {
477 MAIN_THREAD.with(|m| m.get() == Some(std::thread::current().id()))
478}
479
480#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
484pub fn wanted_present_mode(wayland: bool) -> eframe::wgpu::PresentMode {
485 if wayland {
486 eframe::wgpu::PresentMode::AutoNoVsync
487 } else {
488 eframe::wgpu::PresentMode::AutoVsync
489 }
490}
491
492#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
497pub fn present_mode(options: &mut eframe::NativeOptions) -> eframe::wgpu::PresentMode {
498 let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty());
499 if options.wgpu_options.surface.present_mode == eframe::wgpu::PresentMode::AutoVsync {
500 options.wgpu_options.surface.present_mode = wanted_present_mode(wayland);
501 }
502 options.wgpu_options.surface.present_mode
503}
504
505impl AppHandle {
506 pub fn open_window(
515 &self,
516 spec: WindowSpec,
517 content: impl FnMut(&mut Ui, &mut WindowUi<'_>) + 'static,
518 ) -> WindowId {
519 let id = spec.id.clone();
520 self.request_window_open(spec, "app", Reason::Command, content);
521 id
522 }
523
524 pub fn request_window_open(
535 &self,
536 spec: WindowSpec,
537 owner: &str,
538 reason: Reason,
539 content: impl FnMut(&mut Ui, &mut WindowUi<'_>) + 'static,
540 ) -> Vec<String> {
541 MAIN_THREAD.with(|m| {
542 if m.get().is_none() {
543 m.set(Some(std::thread::current().id()));
544 }
545 });
546 let id = spec.id.clone();
547 let opened = {
548 let mut w = self.windows_mut();
549 if w.root.id == id || w.entry(&id).is_some() {
550 false
551 } else {
552 self.load_geometry(&mut w);
553 let saved = w.saved.as_ref().and_then(|s| s.get(id.as_str()).copied());
554 let first = match saved {
555 Some(g) => (
556 Some(Vec2::from(g.size)),
557 g.position,
558 g.maximized,
559 g.fullscreen,
560 ),
561 None => (spec.size, None, false, false),
562 };
563 w.entries.retain(|e| e.id != id);
565 w.entries.push(Entry {
566 id: id.clone(),
567 title: spec.title.clone(),
568 sent_title: Some(spec.title.clone()),
569 content: Some(Box::new(content)),
570 first,
571 min_size: spec.min_size,
572 shell_bars: spec.shell_bars,
573 centre_dock: spec.centre_dock,
574 geometry: saved,
575 focused: None,
576 focused_panel: None,
577 dispatcher: Some(crate::app::WindowKeys::default()),
578 closed: false,
579 });
580 true
581 }
582 };
583 if opened {
584 REGISTRY.with(|r| {
585 r.borrow_mut()
586 .insert(id.deferred_viewport(), (self.downgrade(), id.clone()))
587 });
588 self.app_window_opened(id.deferred_viewport());
589 }
590 let req = WindowRequest::new(id.as_str(), WindowKind::App, owner, reason);
593 let mut did = self.ask_window_open(req);
594 if !opened && self.windows_ref().entry(&id).is_some() {
595 self.raise_viewport(id.deferred_viewport(), owner);
597 did.push(format!("{}: brought to the front", crate::bus::RAISE));
598 }
599 if opened {
600 self.publish(
601 "egui_pop",
602 None,
603 "window.opened",
604 json!({ "window": id, "title": spec.title, "owner": owner, "reason": reason, "did": did }),
605 );
606 }
607 self.egui().request_repaint_of(ViewportId::ROOT);
608 did
609 }
610
611 pub fn close_window(&self, id: &WindowId) {
618 let is_root = self.windows_mut().root.id == *id;
619 if is_root {
620 self.ask_main_close(Reason::Command);
621 return;
622 }
623 self.close_entry(id, Some("app"), Reason::Command);
624 }
625
626 pub(crate) fn close_entry(&self, id: &WindowId, owner: Option<&str>, reason: Reason) -> bool {
632 if self.windows_ref().entry(id).is_none() {
633 return false;
634 }
635 let owner = match owner {
636 Some(o) => o.to_string(),
637 None => self
638 .windows_list()
639 .into_iter()
640 .find(|r| r.id == id.as_str())
641 .map(|r| r.owner)
642 .unwrap_or_else(|| "app".to_string()),
643 };
644 self.request_window_close(WindowRequest::new(
645 id.as_str(),
646 WindowKind::App,
647 owner,
648 reason,
649 ))
650 }
651
652 pub(crate) fn keep_closing_place(&self, id: &WindowId) -> bool {
655 let geometry = self
656 .windows_ref()
657 .entries
658 .iter()
659 .rev()
660 .find(|e| &e.id == id)
661 .and_then(|e| e.geometry);
662 match geometry {
663 Some(g) => {
664 self.keep_geometry(id, g);
665 true
666 }
667 None => false,
668 }
669 }
670
671 pub fn raise_window(&self, id: &WindowId) {
681 let viewport = {
682 let mut w = self.windows_mut();
683 if w.root.id == *id {
684 Some(ViewportId::ROOT)
685 } else if w.root.home == *id {
686 w.going_home = true;
689 Some(ViewportId::ROOT)
690 } else {
691 w.entry(id).map(|e| e.id.deferred_viewport())
692 }
693 };
694 if let Some(v) = viewport {
697 self.raise_viewport(v, "app");
698 }
699 if self.windows_ref().root.content.is_some() {
700 self.ask_home();
701 }
702 }
703
704 pub fn windows(&self) -> Vec<WindowInfo> {
707 let active = self.active_window();
708 let w = self.windows_ref();
709 let root_title = w.root.title.clone().unwrap_or_else(|| self.name());
710 let mut out = vec![WindowInfo {
711 id: w.root.id.clone(),
712 title: root_title,
713 main: true,
714 active: active == ViewportId::ROOT,
715 focused: self.egui().input(|i| {
716 i.raw
717 .viewports
718 .get(&ViewportId::ROOT)
719 .and_then(|v| v.focused)
720 }),
721 geometry: w.root.geometry,
722 viewport: ViewportId::ROOT,
723 }];
724 for e in w.entries.iter().filter(|e| !e.closed) {
725 let viewport = e.id.deferred_viewport();
726 out.push(WindowInfo {
727 id: e.id.clone(),
728 title: e.title.clone(),
729 main: false,
730 active: active == viewport,
731 focused: e.focused,
732 geometry: e.geometry,
733 viewport,
734 });
735 }
736 out
737 }
738
739 pub fn window_at(&self, viewport: ViewportId) -> Option<WindowId> {
741 let w = self.windows_ref();
742 if viewport == ViewportId::ROOT {
743 return Some(w.root.id.clone());
744 }
745 w.by_viewport(viewport).map(|e| e.id.clone())
746 }
747
748 pub fn window_viewport(&self, id: &WindowId) -> Option<ViewportId> {
750 self.windows_ref().viewport_of(id)
751 }
752
753 pub fn window_group(&self, viewport: ViewportId) -> ViewportId {
762 if is_app_window(self, viewport) && !self.egui().embed_viewports() {
763 viewport
764 } else {
765 ViewportId::ROOT
766 }
767 }
768
769 pub fn shown_in(&self, group: ViewportId) -> ViewportId {
773 let group = self.window_group(group);
774 if group != ViewportId::ROOT {
775 return group;
776 }
777 let active = self.active_window();
778 if self.window_group(active) == ViewportId::ROOT {
779 active
780 } else {
781 ViewportId::ROOT
782 }
783 }
784
785 pub fn current_window_group(&self) -> ViewportId {
789 match current_group() {
790 Some(g) => self.window_group(g),
791 None => self.window_group(self.active_window()),
792 }
793 }
794
795 pub(crate) fn current_window_group_or(&self, drawn: ViewportId) -> ViewportId {
798 self.window_group(current_group().unwrap_or(drawn))
799 }
800
801 pub fn window_of_group(&self, group: ViewportId) -> WindowId {
803 self.window_at(self.window_group(group))
804 .unwrap_or_else(|| self.windows_ref().root.id.clone())
805 }
806
807 pub(crate) fn sync_separate_windows(&self) {
809 let embedded = self.egui().embed_viewports();
810 let open: Vec<ViewportId> = self
811 .windows_ref()
812 .entries
813 .iter()
814 .filter(|e| !e.closed && !embedded)
815 .map(|e| e.id.deferred_viewport())
816 .collect();
817 egui_pop_core::overlay::set_separate_windows(&self.egui(), open);
818 }
819
820 pub(crate) fn shown_window_ids(&self) -> Vec<String> {
823 let w = self.windows_ref();
824 let mut ids = Vec::new();
825 if w.root.id == w.root.home {
826 ids.push(WindowId::MAIN.to_string());
827 } else {
828 ids.push(w.root.id.as_str().to_string());
830 }
831 ids.extend(
832 w.entries
833 .iter()
834 .filter(|e| !e.closed)
835 .map(|e| e.id.as_str().to_string()),
836 );
837 ids
838 }
839
840 pub fn active_app_window(&self) -> WindowId {
843 let active = self.active_window();
844 self.window_at(active)
845 .unwrap_or_else(|| self.windows_ref().root.id.clone())
846 }
847
848 pub fn set_window_title(&self, id: &WindowId, title: impl Into<String>) {
852 let title = title.into();
853 let mut w = self.windows_mut();
854 if w.root.id == *id {
855 w.root.title = Some(title);
856 drop(w);
857 self.egui().request_repaint_of(ViewportId::ROOT);
858 } else if let Some(e) = w.entry_mut(id) {
859 e.title = title;
860 let v = e.id.deferred_viewport();
861 drop(w);
862 self.egui().request_repaint_of(v);
863 }
864 }
865
866 pub fn window_geometry(&self, id: &WindowId) -> Option<Geometry> {
868 let mut w = self.windows_mut();
869 if w.root.home == *id {
870 return w.root.geometry;
871 }
872 if let Some(e) = w.entry(id) {
873 return e.geometry;
874 }
875 self.load_geometry(&mut w);
876 w.saved.as_ref().and_then(|s| s.get(id.as_str()).copied())
877 }
878
879 pub(crate) fn windows_ref(&self) -> std::cell::Ref<'_, Windows> {
880 self.0.windows.borrow()
881 }
882
883 pub(crate) fn windows_mut(&self) -> std::cell::RefMut<'_, Windows> {
884 self.0.windows.borrow_mut()
885 }
886
887 fn load_geometry(&self, w: &mut Windows) {
888 if w.saved.is_some() {
889 return;
890 }
891 let saved = self
892 .persist()
893 .and_then(|p| std::fs::read_to_string(p.path(GEOMETRY_DOC)).ok())
894 .and_then(|t| serde_json::from_str(&t).ok())
895 .unwrap_or_default();
896 w.saved = Some(saved);
897 }
898
899 fn keep_geometry(&self, id: &WindowId, g: Geometry) {
901 let text = {
902 let mut w = self.windows_mut();
903 self.load_geometry(&mut w);
904 let saved = w.saved.get_or_insert_with(BTreeMap::new);
905 if saved.get(id.as_str()) == Some(&g) {
906 return;
907 }
908 saved.insert(id.to_string(), g);
909 serde_json::to_string_pretty(saved).unwrap_or_default()
910 };
911 self.save_later(GEOMETRY_DOC, text);
912 }
913
914 pub(crate) fn window_to_move_in(&self) -> Option<WindowId> {
917 self.app_windows_by_recency()
918 .into_iter()
919 .map(|id| WindowId::new(&id))
920 .find(|id| self.windows_ref().entry(id).is_some())
921 }
922
923 pub(crate) fn move_into_root(&self, id: &WindowId) -> bool {
929 let moved = {
930 let mut w = self.windows_mut();
931 let Some(at) = w.entries.iter().position(|e| &e.id == id && !e.closed) else {
932 return false;
933 };
934 let e = w.entries.remove(at);
935 let kept = [
939 (w.root.home.clone(), w.root.geometry),
940 (e.id.clone(), e.geometry),
941 ];
942 let geometry = e.geometry.or_else(|| {
945 let (size, position, maximized, fullscreen) = e.first;
946 size.map(|s| Geometry {
947 size: [s.x, s.y],
948 position,
949 maximized,
950 fullscreen,
951 })
952 });
953 let left = std::mem::replace(&mut w.root.id, e.id.clone());
954 let shell_title = w.root.title.replace(e.title.clone());
955 if left == w.root.home {
956 w.root.home_title = shell_title;
958 }
959 w.root.min_size = e.min_size;
960 w.root.shell_bars = e.shell_bars;
961 w.root.centre_dock = e.centre_dock;
962 w.root.sent_title = None;
963 w.root.content = e.content;
964 (left, e.id, kept, geometry)
965 };
966 let (left, id, kept, geometry) = moved;
967 if let Some(g) = geometry {
968 self.apply_root_geometry(g);
969 }
970 REGISTRY.with(|r| r.borrow_mut().remove(&id.deferred_viewport()));
971 self.sync_separate_windows();
972 {
973 let mut w = self.windows_mut();
974 w.moved_places
975 .extend(kept.into_iter().filter_map(|(at, g)| g.map(|g| (at, g))));
976 w.moved_events
977 .push(("window.closed", json!({ "window": left })));
978 w.moved_events
979 .push(("window.moved", json!({ "window": id, "to": "main" })));
980 }
981 self.egui().request_repaint_of(ViewportId::ROOT);
982 true
983 }
984
985 pub(crate) fn keep_moved_places(&self) -> usize {
988 let places = std::mem::take(&mut self.windows_mut().moved_places);
989 let n = places.len();
990 for (id, g) in places {
991 self.keep_geometry(&id, g);
992 }
993 n
994 }
995
996 fn apply_root_geometry(&self, g: Geometry) {
1000 let ctx = self.egui();
1001 let root = ViewportId::ROOT;
1002 log::info!(
1003 target: "egui_pop::window_size",
1004 "the main window asked {g:?}: a window's content moved into it"
1005 );
1006 if g.fullscreen {
1007 ctx.send_viewport_cmd_to(root, ViewportCommand::Fullscreen(true));
1008 return;
1009 }
1010 ctx.send_viewport_cmd_to(root, ViewportCommand::Fullscreen(false));
1011 if g.maximized {
1012 ctx.send_viewport_cmd_to(root, ViewportCommand::Maximized(true));
1013 return;
1014 }
1015 ctx.send_viewport_cmd_to(root, ViewportCommand::Maximized(false));
1016 ctx.send_viewport_cmd_to(root, ViewportCommand::InnerSize(Vec2::from(g.size)));
1017 if let Some([x, y]) = g.position {
1018 ctx.send_viewport_cmd_to(root, ViewportCommand::OuterPosition(egui::pos2(x, y)));
1019 }
1020 }
1021
1022 pub fn main_window(&self) -> WindowId {
1024 self.windows_ref().root.home.clone()
1025 }
1026
1027 pub fn quit(&self) {
1035 self.windows_mut().quitting = true;
1036 if !self.ask_main_close(Reason::Quit) {
1037 self.windows_mut().quitting = false;
1038 }
1039 self.egui().request_repaint_of(ViewportId::ROOT);
1040 }
1041
1042 pub fn quitting(&self) -> bool {
1044 self.windows_ref().quitting
1045 }
1046
1047 pub(crate) fn take_quitting(&self) -> bool {
1050 std::mem::take(&mut self.windows_mut().quitting)
1051 }
1052
1053 pub(crate) fn take_going_home(&self) -> Option<WindowId> {
1057 let mut w = self.windows_mut();
1058 let going = std::mem::take(&mut w.going_home);
1059 (going && w.root.id != w.root.home && w.root.content.is_some()).then(|| w.root.id.clone())
1060 }
1061
1062 pub(crate) fn move_out_of_root(&self) -> bool {
1067 let back = {
1068 let mut w = self.windows_mut();
1069 w.going_home = false;
1070 if w.root.id == w.root.home {
1071 return false;
1072 }
1073 let Some(content) = w.root.content.take() else {
1074 return false;
1075 };
1076 self.load_geometry(&mut w);
1077 let home = w.root.home.clone();
1078 let id = std::mem::replace(&mut w.root.id, home.clone());
1079 let title = w.root.title.take().unwrap_or_default();
1080 let home_title = w.root.home_title.take();
1081 w.root.title = home_title.or_else(|| Some(self.name()).filter(|n| !n.is_empty()));
1082 w.root.sent_title = None;
1083 let min_size = w.root.min_size.take();
1084 let shell_bars = std::mem::take(&mut w.root.shell_bars);
1085 let centre_dock = std::mem::take(&mut w.root.centre_dock);
1086 let saved = w.saved.as_ref().and_then(|s| s.get(id.as_str()).copied());
1090 let home_geometry = w.saved.as_ref().and_then(|s| s.get(home.as_str()).copied());
1091 let first = match saved {
1092 Some(g) => (
1093 Some(Vec2::from(g.size)),
1094 g.position,
1095 g.maximized,
1096 g.fullscreen,
1097 ),
1098 None => (None, None, false, false),
1099 };
1100 w.entries.retain(|e| e.id != id);
1101 w.entries.push(Entry {
1102 id: id.clone(),
1103 title: title.clone(),
1104 sent_title: Some(title.clone()),
1105 content: Some(content),
1106 first,
1107 min_size,
1108 shell_bars,
1109 centre_dock,
1110 geometry: saved,
1111 focused: None,
1112 focused_panel: None,
1113 dispatcher: Some(crate::app::WindowKeys::default()),
1114 closed: false,
1115 });
1116 (home, id, title, home_geometry)
1117 };
1118 let (home, id, title, home_geometry) = back;
1119 if let Some(g) = home_geometry {
1120 self.apply_root_geometry(g);
1121 }
1122 REGISTRY.with(|r| {
1123 r.borrow_mut()
1124 .insert(id.deferred_viewport(), (self.downgrade(), id.clone()))
1125 });
1126 self.sync_separate_windows();
1127 {
1128 let mut w = self.windows_mut();
1129 w.moved_events.push((
1130 "window.moved",
1131 json!({ "window": id, "from": home, "to": id, "title": title }),
1132 ));
1133 w.moved_events
1134 .push(("window.opened", json!({ "window": home })));
1135 }
1136 self.egui().request_repaint_of(ViewportId::ROOT);
1137 true
1138 }
1139
1140 pub(crate) fn window_centre_dock(&self, id: &WindowId) -> bool {
1144 let w = self.windows_ref();
1145 if w.root.id == *id {
1146 return w.root.centre_dock;
1147 }
1148 w.entry(id).is_some_and(|e| e.centre_dock)
1149 }
1150
1151 pub(crate) fn root_has_content(&self) -> bool {
1154 self.windows_ref().root.content.is_some()
1155 }
1156
1157 pub(crate) fn root_pass(&self, ui: &mut Ui) -> bool {
1161 let ctx = ui.ctx().clone();
1162 if let Some(seen) = read_geometry(&ctx) {
1163 let (id, g) = {
1166 let mut w = self.windows_mut();
1167 let g = if w.root.id == w.root.home {
1168 let g = Geometry::follow(w.root.geometry, seen);
1169 w.root.geometry = Some(g);
1170 g
1171 } else {
1172 seen
1173 };
1174 (w.root.id.clone(), g)
1175 };
1176 if ctx.input(|i| i.viewport().close_requested()) {
1177 self.keep_geometry(&id, g);
1178 }
1179 }
1180 let content = self.windows_mut().root.content.take();
1181 let drawn = match content {
1182 Some(mut content) => {
1183 let (id, title, bars) = {
1184 let w = self.windows_ref();
1185 (
1186 w.root.id.clone(),
1187 w.root.title.clone().unwrap_or_default(),
1188 w.root.shell_bars,
1189 )
1190 };
1191 let mut wui = WindowUi {
1192 app: self,
1193 id,
1194 title,
1195 class: ViewportClass::Root,
1196 close_requested: false,
1197 keep_open: false,
1198 close: false,
1199 };
1200 let title = wui.title.clone();
1203 let drawn_id = wui.id.clone();
1204 framed(ui, self, &title, bars, |ui| {
1205 crate::workbench::window_areas::show(self, ui, &drawn_id, |ui| {
1206 content(ui, &mut wui);
1207 });
1208 });
1209 let mut w = self.windows_mut();
1210 if w.root.id == drawn_id {
1214 if w.root.content.is_none() {
1215 w.root.content = Some(content);
1216 }
1217 w.root.title = Some(wui.title);
1218 }
1219 drop(w);
1220 if wui.close {
1221 self.ask_main_close(Reason::User);
1222 }
1223 true
1224 }
1225 None => false,
1226 };
1227 let title = {
1228 let w = self.windows_ref();
1229 w.root
1230 .title
1231 .clone()
1232 .filter(|t| w.root.sent_title.as_ref() != Some(t))
1233 };
1234 if let Some(t) = title {
1235 ctx.send_viewport_cmd(ViewportCommand::Title(t.clone()));
1236 self.windows_mut().root.sent_title = Some(t);
1237 }
1238 drawn
1239 }
1240
1241 pub(crate) fn app_window_moved(&self, viewport: ViewportId, at: egui::Pos2) {
1245 let mut w = self.windows_mut();
1246 if let Some(e) = w
1247 .entries
1248 .iter_mut()
1249 .find(|e| e.id.deferred_viewport() == viewport)
1250 {
1251 e.first.1 = Some([at.x, at.y]);
1252 }
1253 }
1254
1255 pub(crate) fn declare_windows(&self, ctx: &Context) {
1258 if ctx.viewport_id() != ViewportId::ROOT {
1259 return;
1260 }
1261 let app_id = self.app_id();
1262 let own = crate::frame::own_frame(self);
1265 let rounded = egui_pop_core::frame::rounding(ctx);
1266 let screens = crate::window::screens();
1267 let builders: Vec<(ViewportId, ViewportBuilder)> = {
1268 let mut w = self.windows_mut();
1269 for e in w.entries.iter().filter(|e| e.closed) {
1272 crate::paint_guard::closed_for_good(e.id.deferred_viewport());
1273 }
1274 w.entries.retain(|e| !e.closed);
1275 w.entries
1276 .iter()
1277 .map(|e| {
1278 let mut b = ViewportBuilder::default()
1279 .with_title(e.title.clone())
1280 .with_decorations(!own);
1281 if own && rounded {
1283 b = b.with_transparent(true);
1284 }
1285 if !app_id.is_empty() {
1286 b = b.with_app_id(app_id.clone());
1287 }
1288 let (size, pos, maximized, fullscreen) = e.first;
1289 let place = size.map(|s| {
1291 crate::window::WindowState {
1292 position: pos.map(egui::Pos2::from),
1293 size: s,
1294 maximized,
1295 fullscreen,
1296 }
1297 .repair(&screens)
1298 });
1299 if let Some(p) = place {
1300 b = b.with_inner_size(p.size);
1301 if let Some(at) = p.position {
1302 b = b.with_position(at);
1303 }
1304 }
1305 if maximized {
1306 b = b.with_maximized(true);
1307 }
1308 if fullscreen {
1309 b = b.with_fullscreen(true);
1310 }
1311 if let Some(m) = e.min_size {
1312 b = b.with_min_inner_size(m);
1313 }
1314 (e.id.deferred_viewport(), b)
1315 })
1316 .collect()
1317 };
1318 self.sync_separate_windows();
1319 for (viewport, builder) in builders {
1320 ctx.show_viewport_deferred(viewport, builder, move |ui, class| {
1321 window_pass(viewport, ui, class)
1322 });
1323 }
1324 for viewport in self.watch_closed_windows(ctx) {
1327 ctx.show_viewport_deferred(
1328 viewport,
1329 ViewportBuilder::default().with_visible(false),
1330 move |ui, _| {
1331 crate::paint_guard::orphan_pass(ui, viewport, "it is closed");
1332 },
1333 );
1334 }
1335 }
1336
1337 fn dispatch_window_keys(&self, ctx: &Context, id: &WindowId) {
1341 self.follow_window_focus(ctx, id);
1342 let Some(mut keys) = self
1343 .windows_mut()
1344 .entry_mut(id)
1345 .and_then(|e| e.dispatcher.take())
1346 else {
1347 return;
1348 };
1349 let keymap = self.shared_keymap();
1350 let mut cx = self.when_context();
1351 cx.set(CONTEXT_APP_WINDOW, id.as_str());
1352 let dispatched = if self.capturing_keys() {
1353 Vec::new()
1354 } else {
1355 keys.dispatcher(self).process(ctx, &keymap, &cx)
1356 };
1357 if let Some(e) = self.windows_mut().entry_mut(id) {
1358 e.dispatcher = Some(keys);
1359 }
1360 for d in dispatched {
1361 let back = if d.command == crate::workbench::CMD_NEXT_REGION {
1364 Some(false)
1365 } else if d.command == crate::workbench::CMD_PREVIOUS_REGION {
1366 Some(true)
1367 } else {
1368 None
1369 };
1370 if let Some(back) = back {
1371 let user = egui_pop_model::commands::Origin::User;
1372 if let Err(e) = crate::workbench::go_to_region(self, &user, back) {
1373 log::debug!("F6 in window `{id}`: {e}");
1374 }
1375 continue;
1376 }
1377 self.run_in_context(d.command, serde_json::Value::Null, cx.clone());
1378 }
1379 }
1380}
1381
1382impl AppHandle {
1383 fn follow_window_focus(&self, ctx: &Context, id: &WindowId) {
1387 let Some(moved) = egui_pop_core::focus::take_moved(ctx) else {
1388 return;
1389 };
1390 let chain = match moved {
1391 egui_pop_core::focus::Moved::Pressed(c) | egui_pop_core::focus::Moved::Focused(c) => c,
1392 egui_pop_core::focus::Moved::Left => return,
1393 };
1394 let Some(panel) = self.workbench_mut().panel_of(&chain) else {
1395 return;
1396 };
1397 if let Some(e) = self.windows_mut().entry_mut(id) {
1398 e.focused_panel = Some(panel);
1399 }
1400 }
1401
1402 pub(crate) fn window_focused_panel(
1405 &self,
1406 viewport: ViewportId,
1407 ) -> Option<egui_pop_model::ids::PanelId> {
1408 self.windows_ref()
1409 .by_viewport(viewport)
1410 .and_then(|e| e.focused_panel.clone())
1411 }
1412}
1413
1414fn framed(ui: &mut Ui, app: &AppHandle, title: &str, bars: bool, content: impl FnOnce(&mut Ui)) {
1417 crate::frame::window_frame(ui, app, title, bars, |ui| {
1418 if bars {
1419 menu_bar(ui, app);
1420 }
1421 content(ui);
1422 });
1423}
1424
1425fn menu_bar(ui: &mut Ui, app: &AppHandle) {
1428 if !app.menu_bar() {
1429 return;
1430 }
1431 let id = egui::Id::unique(("egui_pop.window_menu", ui.ctx().viewport_id()));
1432 egui::Panel::top(id).show(ui, |ui| {
1433 egui_pop_core::focus::scope(ui, "topBar", &[], |ui| {
1434 egui::MenuBar::new().ui(ui, |ui| {
1435 crate::menus::bar(ui, app, &crate::app::MENU_MAIN);
1436 });
1437 });
1438 });
1439}
1440
1441fn read_geometry(ctx: &Context) -> Option<Geometry> {
1443 ctx.input(|i| {
1444 let v = i.viewport();
1445 let size = v
1446 .inner_rect
1447 .map(|r| r.size())
1448 .unwrap_or_else(|| i.viewport_rect().size());
1449 if size.x <= 0.0 || size.y <= 0.0 {
1450 return None;
1451 }
1452 Some(Geometry {
1453 size: [size.x, size.y],
1454 position: v.outer_rect.map(|r| [r.min.x, r.min.y]),
1455 maximized: v.maximized.unwrap_or(false),
1456 fullscreen: v.fullscreen.unwrap_or(false),
1457 })
1458 })
1459}
1460
1461fn window_pass(viewport: ViewportId, ui: &mut Ui, class: ViewportClass) {
1464 let on_main = on_main_thread();
1465 debug_assert!(on_main, "an application window drawn off the UI thread");
1466 if !on_main {
1467 log::error!(target: "egui_pop", "an application window drawn off the UI thread");
1468 return;
1469 }
1470 let Some((weak, id)) = REGISTRY.with(|r| r.borrow().get(&viewport).cloned()) else {
1471 crate::paint_guard::orphan_pass(ui, viewport, "no application window has it");
1472 return;
1473 };
1474 let Ok(app) = weak.get() else {
1475 crate::paint_guard::orphan_pass(ui, viewport, "its application is gone");
1476 return;
1477 };
1478 let _group = enter_group(Some(viewport));
1481 let ctx = ui.ctx().clone();
1482 let own_window = class != ViewportClass::EmbeddedWindow;
1483 let (content, title, bars) = {
1484 let mut w = app.windows_mut();
1485 let Some(e) = w.entry_mut(&id) else {
1486 drop(w);
1487 crate::paint_guard::orphan_pass(ui, viewport, "its window is closed");
1488 return;
1489 };
1490 let Some(content) = e.content.take() else {
1491 return;
1492 };
1493 if own_window {
1494 e.focused = ctx.input(|i| i.viewport().focused);
1495 if let Some(g) = read_geometry(&ctx) {
1496 e.geometry = Some(Geometry::follow(e.geometry, g));
1497 }
1498 }
1499 (content, e.title.clone(), e.shell_bars)
1500 };
1501 let mut content = content;
1502 if own_window {
1503 app.note_window(&ctx);
1504 crate::bus::files::begin_pass(&ctx, id.as_str());
1505 crate::bus::drag::begin_pass(&ctx, id.as_str());
1506 app.block_window(&ctx, &|v| v == viewport);
1507 egui_pop_core::overlay::begin_pass(&ctx);
1508 app.dispatch_window_keys(&ctx, &id);
1509 app.raise_in_pass(&ctx);
1510 }
1511 if let Some((from, to)) = egui_pop_core::scale::changed(&ctx) {
1512 app.publish(
1513 "egui_pop",
1514 None,
1515 "scale.changed",
1516 json!({ "viewport": id, "from": from, "to": to }),
1517 );
1518 }
1519 let close_requested = own_window && ctx.input(|i| i.viewport().close_requested());
1520 let mut wui = WindowUi {
1521 app: &app,
1522 id: id.clone(),
1523 title,
1524 class,
1525 close_requested,
1526 keep_open: false,
1527 close: false,
1528 };
1529 let mut painted = false;
1530 let mut fallback = false;
1531 if own_window {
1532 let title = wui.title.clone();
1533 framed(ui, &app, &title, bars, |ui| {
1534 let mark = crate::paint_guard::mark(ui);
1536 crate::workbench::window_areas::show(&app, ui, &id, |ui| content(ui, &mut wui));
1537 painted = crate::paint_guard::painted_since(ui.ctx(), &mark);
1538 });
1539 } else {
1540 crate::workbench::window_areas::show(&app, ui, &id, |ui| content(ui, &mut wui));
1542 }
1543 if own_window {
1544 app.show_zone(ui, &crate::zones::WINDOW_OVERLAYS);
1545 crate::bus::files::end_pass(&app, ui);
1547 crate::bus::drag::end_pass(&app, &ctx);
1549 crate::menus::draw_popup(&ctx, &app);
1551 if app.watch_app_window(&ctx, &id, painted) && app.app_window_fallback(&ctx) {
1554 wui.close = true;
1555 fallback = true;
1556 }
1557 }
1558 let closing = wui.close || (close_requested && !wui.keep_open);
1559 let send_title = {
1560 let mut w = app.windows_mut();
1561 let Some(e) = w.entry_mut(&id) else { return };
1562 e.content = Some(content);
1563 e.title = wui.title;
1564 let send = (e.sent_title.as_ref() != Some(&e.title)).then(|| e.title.clone());
1565 if send.is_some() {
1566 e.sent_title = send.clone();
1567 }
1568 send
1569 };
1570 if let Some(t) = send_title
1571 && own_window
1572 && !closing
1573 {
1574 ctx.send_viewport_cmd(ViewportCommand::Title(t));
1575 }
1576 if closing {
1577 let reason = if fallback {
1578 Reason::Guard
1579 } else {
1580 Reason::User
1581 };
1582 app.close_entry(&id, None, reason);
1583 crate::paint_guard::keep_last_page(&ctx, viewport);
1586 }
1587 if app.has_requests() {
1588 ctx.request_repaint_of(ViewportId::ROOT);
1589 }
1590}
1591
1592pub(crate) fn is_app_window(app: &AppHandle, viewport: ViewportId) -> bool {
1596 viewport != ViewportId::ROOT && app.windows_ref().by_viewport(viewport).is_some()
1597}
1598
1599pub(crate) fn describe(app: &AppHandle) -> serde_json::Value {
1601 json!(app.windows())
1602}
1603
1604pub const CMD_SWITCH: egui_pop_model::ids::CommandId =
1607 egui_pop_model::ids::CommandId::from_static("window.switch");
1608pub const CMD_CLOSE: egui_pop_model::ids::CommandId =
1610 egui_pop_model::ids::CommandId::from_static("window.close");
1611pub const CMD_PICK: egui_pop_model::ids::CommandId =
1614 egui_pop_model::ids::CommandId::from_static("window.pick");
1615pub const MENU_WINDOW: egui_pop_model::ids::MenuId =
1617 egui_pop_model::ids::MenuId::from_static("app.menu.window");
1618pub const LIST_WINDOWS: &str = "app.windows";
1620
1621#[derive(Debug, Default)]
1628pub struct WindowsPlugin;
1629
1630fn window_arg(app: &AppHandle, args: &serde_json::Value) -> Result<Option<WindowId>, String> {
1631 match args.get("window").and_then(|w| w.as_str()) {
1632 None => Ok(None),
1633 Some(w) => {
1634 let id = WindowId::new(w);
1635 if app.window_viewport(&id).is_none() && id != app.main_window() {
1638 return Err(format!("no open window `{w}`"));
1639 }
1640 Ok(Some(id))
1641 }
1642 }
1643}
1644
1645impl crate::Plugin for WindowsPlugin {
1646 fn id(&self) -> egui_pop_model::ids::PluginId {
1647 egui_pop_model::ids::PluginId::from_static("egui_pop.windows")
1648 }
1649
1650 fn title(&self) -> String {
1651 "Windows".into()
1652 }
1653
1654 fn connect(&mut self, ctx: &mut crate::Ctx<'_>) -> Result<(), crate::PluginError> {
1655 use egui_pop_model::commands::CommandSpec;
1656 use egui_pop_model::menus::MenuItem;
1657 ctx.command(
1658 CommandSpec::new(CMD_SWITCH, "Switch window", "Window")
1659 .description("Brings a window to the front: the one named, or the next one.")
1660 .args(json!({ "window": "main" })),
1661 |call| {
1662 let app = call.app;
1663 let id = match window_arg(app, call.args)? {
1664 Some(id) => id,
1665 None => {
1666 let open = app.windows();
1667 let at = open.iter().position(|w| w.active).unwrap_or(0);
1668 open[(at + 1) % open.len()].id.clone()
1669 }
1670 };
1671 app.raise_window(&id);
1672 Ok(json!({ "window": id }))
1673 },
1674 )?
1675 .command(
1676 CommandSpec::new(CMD_CLOSE, "Close window", "Window")
1677 .description("Closes a window: the one named, or the active one.")
1678 .args(json!({ "window": "main" })),
1679 |call| {
1680 let app = call.app;
1681 let id = window_arg(app, call.args)?.unwrap_or_else(|| app.active_app_window());
1682 app.close_window(&id);
1683 Ok(json!({ "window": id }))
1684 },
1685 )?;
1686 ctx.command(
1687 CommandSpec::new(CMD_PICK, "Switch to window…", "Window")
1688 .description("Lists the open windows by title; the one chosen comes to the front."),
1689 |call| {
1690 let app = call.app;
1691 let dialogs = app
1692 .service(&crate::dialogs::DIALOGS)
1693 .ok_or("no dialogs plugin")?;
1694 let mut open = app.windows();
1697 open.sort_by_key(|w| w.active);
1698 let options = open
1699 .iter()
1700 .map(|w| crate::dialogs::ChooseOption::new(&w.title, json!(w.id)))
1701 .collect();
1702 let id = dialogs.open(
1703 crate::dialogs::Choose::with_options("Switch to window", options, CMD_SWITCH)
1704 .value_key("window"),
1705 );
1706 Ok(json!({ "dialog": id, "windows": open.len() }))
1707 },
1708 )?;
1709 ctx.submenu(crate::app::MENU_MAIN, "2_window", 0, MENU_WINDOW, "Window")?;
1710 ctx.menu_item(MenuItem::command(MENU_WINDOW, "0_pick", 0, CMD_PICK))?;
1711 ctx.menu_item(MenuItem::command(MENU_WINDOW, "1_close", 0, CMD_CLOSE))?;
1712 ctx.menu_item(MenuItem::list(MENU_WINDOW, "2_windows", 0, LIST_WINDOWS))?;
1713 ctx.list_provider(LIST_WINDOWS, |app, _| {
1714 app.windows()
1715 .into_iter()
1716 .map(|w| {
1717 crate::menus::ListItem::new(&w.title, CMD_SWITCH, json!({ "window": w.id }))
1718 .checked(w.active)
1719 })
1720 .collect()
1721 });
1722 Ok(())
1723 }
1724}