Skip to main content

egui_pop_api/bus/
screens.rs

1//! The screens on the bus (ADR 0029).
2//!
3//! Whatever runs the event loop tells the screens
4//! ([`crate::window::set_screens`]: egui-pop's native runner, or a host
5//! running eframe on its own winit loop), at start and again when they
6//! may have changed. Each application follows the change from its main
7//! window's next pass: a screen come is said as `pop.screen.added`
8//! ([`ScreenAdded`]), a screen gone as `pop.screen.removed`
9//! ([`ScreenRemoved`]), each a [`ScreenChange`] naming the screen as
10//! winit names it.
11//!
12//! egui-pop's listeners of `pop.screen.removed`, local (they touch the
13//! interface's state), in this order:
14//!
15//! 1. [`WORKBENCH_SCREENS`]: a detached panel's window kept on the screen
16//!    gone docks back (the layout's rule: "a window on a screen that is
17//!    gone comes back docked"), by its window's `pop.window.reparent`;
18//! 2. [`super::PLACE`]: every other window (the main window, the
19//!    application windows, a detached panel's window on a screen it
20//!    cannot name) that no longer meets a screen moves onto one that is
21//!    left, and keeps that place.
22//!
23//! Where the system tells no window's position (Wayland), nothing moves:
24//! the system places the windows. The screens first told to an
25//! application are not said (nothing changed), but a window kept on a
26//! screen gone since the last run is repaired the same way. A window
27//! opening is repaired against the screens as it opens (its builder).
28//! Invariant 6 ([`crate::window_invariants::ON_SCREEN`]) checks that every
29//! positioned window meets a screen.
30
31use bus_contract::{Bus, ListenOpts, Point, PointId, PointKind};
32use egui::{Context, Pos2, Rect, ViewportCommand, ViewportId};
33use serde::Serialize;
34
35use super::{OWNER, PLACE, WindowKind, asking, emit_with};
36use crate::app::AppHandle;
37use crate::window::{Screen, WindowState};
38
39/// A screen come or gone: its name as the system gives it (winit's
40/// `MonitorHandle::name`; none when it gives none), its rectangle in
41/// points (`[x, y, width, height]`) and its scale factor.
42#[derive(Clone, Debug, PartialEq, Serialize)]
43#[non_exhaustive]
44pub struct ScreenChange {
45    pub name: Option<String>,
46    pub rect: [f32; 4],
47    pub scale: f32,
48}
49
50impl From<&Screen> for ScreenChange {
51    fn from(s: &Screen) -> Self {
52        Self {
53            name: s.name.clone(),
54            rect: [s.rect.min.x, s.rect.min.y, s.rect.width(), s.rect.height()],
55            scale: s.scale,
56        }
57    }
58}
59
60/// A screen was plugged in (`pop.screen.added`).
61#[derive(Debug)]
62pub struct ScreenAdded;
63impl Point for ScreenAdded {
64    const KIND: PointKind = PointKind::Event;
65    const ID: PointId = PointId::new("pop.screen.added");
66    type Input = ScreenChange;
67    type Value = ();
68}
69
70/// A screen was unplugged (`pop.screen.removed`): the windows on it move onto
71/// a screen left, or dock back.
72#[derive(Debug)]
73pub struct ScreenRemoved;
74impl Point for ScreenRemoved {
75    const KIND: PointKind = PointKind::Event;
76    const ID: PointId = PointId::new("pop.screen.removed");
77    type Input = ScreenChange;
78    type Value = ();
79}
80
81/// The screen points, in the order [`super::order_dump`] prints them.
82pub const SCREEN_POINTS: [&str; 2] = [ScreenAdded::ID.as_str(), ScreenRemoved::ID.as_str()];
83
84/// The workbench's listener of `pop.screen.removed`: a detached panel's
85/// window kept on the screen gone docks back.
86pub const WORKBENCH_SCREENS: &str = "pop.workbench.screens";
87
88/// What an application knows of the screens it follows.
89#[derive(Debug, Default)]
90pub(crate) struct Seen {
91    /// [`crate::window::screens_told`] when last followed; none before
92    /// the first pass.
93    told: Option<u64>,
94    screens: Vec<Screen>,
95}
96
97/// Whether two screens told are the same screen: by name, or by their
98/// rectangle when the system names neither.
99fn same(a: &Screen, b: &Screen) -> bool {
100    match (&a.name, &b.name) {
101        (Some(x), Some(y)) => x == y,
102        (None, None) => a.rect == b.rect,
103        _ => false,
104    }
105}
106
107/// Registers egui-pop's listeners of `pop.screen.removed`.
108pub(super) fn install(kernel: &dyn Bus) {
109    let mine = || ListenOpts::new().owner(OWNER);
110    let listened = [
111        kernel.listen_local::<ScreenRemoved>(WORKBENCH_SCREENS, mine().before(PLACE), |_, _| {
112            if let Some(app) = asking() {
113                app.dock_windows_off_screens();
114            }
115            Ok(())
116        }),
117        kernel.listen_local::<ScreenRemoved>(PLACE, mine().after(WORKBENCH_SCREENS), |_, _| {
118            if let Some(app) = asking() {
119                app.move_windows_onto_screens(&app.egui());
120            }
121            Ok(())
122        }),
123    ];
124    for l in listened {
125        debug_assert!(l.is_ok(), "{l:?}");
126    }
127}
128
129impl AppHandle {
130    /// From the main window's pass: the screens told since the last pass
131    /// followed. Each screen gone is said as `pop.screen.removed`, each come
132    /// as `pop.screen.added`; the screens first told (to an application that
133    /// knew none) are not said, the windows kept on a screen gone since
134    /// are repaired as on `pop.screen.removed`.
135    pub(crate) fn follow_screens(&self, ctx: &Context) {
136        if ctx.viewport_id() != ViewportId::ROOT {
137            return;
138        }
139        let told = crate::window::screens_told();
140        let (before, now) = {
141            let mut seen = self.0.bus.screens.borrow_mut();
142            if seen.told == Some(told) {
143                return;
144            }
145            seen.told = Some(told);
146            let now = crate::window::screen_list();
147            let before = std::mem::replace(&mut seen.screens, now.clone());
148            (before, now)
149        };
150        if now.is_empty() {
151            // None known any more: nothing to repair against.
152            return;
153        }
154        if before.is_empty() {
155            self.dock_windows_off_screens();
156            self.move_windows_onto_screens(ctx);
157            return;
158        }
159        for s in now.iter().filter(|s| !before.iter().any(|b| same(b, s))) {
160            log::info!(target: "egui_pop", "screen added: {s:?}");
161            emit_with::<ScreenAdded>(self, s.into(), ());
162        }
163        for s in before.iter().filter(|b| !now.iter().any(|s| same(b, s))) {
164            log::info!(target: "egui_pop", "screen removed: {s:?}");
165            emit_with::<ScreenRemoved>(self, s.into(), ());
166        }
167    }
168
169    /// The names of the screens a layout's detached windows may be kept
170    /// on: those told, and [`crate::window::UNNAMED_SCREEN`]. While no
171    /// screen is told, or one is told without a name, every screen the
172    /// layout names is kept too: nothing docks back for a screen that
173    /// cannot be told gone.
174    pub(crate) fn layout_screens(&self) -> Vec<String> {
175        let told = crate::window::screen_list();
176        let mut names = vec![crate::window::UNNAMED_SCREEN.to_string()];
177        names.extend(told.iter().filter_map(|s| s.name.clone()));
178        if told.is_empty() || told.iter().any(|s| s.name.is_none()) {
179            let wb = self.workbench_mut();
180            names.extend(wb.layout.auxiliary.iter().map(|a| a.screen.clone()));
181            names.extend(wb.dormant.iter().filter_map(|d| match &d.place {
182                egui_pop_model::layout::DormantPlace::Window { screen, .. } => Some(screen.clone()),
183                _ => None,
184            }));
185        }
186        names.sort();
187        names.dedup();
188        names
189    }
190
191    /// [`WORKBENCH_SCREENS`]: the detached panels' windows kept on a
192    /// screen no longer told dock back, each by its window's
193    /// `pop.window.reparent` into the main window. How many windows docked.
194    pub(crate) fn dock_windows_off_screens(&self) -> usize {
195        let names = self.layout_screens();
196        let screens: Vec<&str> = names.iter().map(String::as_str).collect();
197        let before = self.workbench_mut().layout.auxiliary.clone();
198        let gone = before
199            .iter()
200            .filter(|a| !screens.contains(&a.screen.as_str()))
201            .count();
202        if gone == 0 {
203            return 0;
204        }
205        let notes = {
206            let mut wb = self.workbench_mut();
207            let layout = wb.layout();
208            wb.set_layout(layout, &screens)
209        };
210        for note in notes {
211            log::info!(target: "egui_pop", "layout: {note}");
212        }
213        self.sync_panel_windows(&before);
214        self.egui().request_repaint();
215        gone
216    }
217
218    /// `pop.window.place` on `pop.screen.removed`: every window whose position the
219    /// system tells and that meets no screen told (the main window, the
220    /// application windows, the detached panels' windows) moves onto the
221    /// nearest screen left, and keeps that place. Where positions are
222    /// hidden (Wayland), nothing moves. The windows moved, by id.
223    pub(crate) fn move_windows_onto_screens(&self, ctx: &Context) -> Vec<String> {
224        let screens = crate::window::screens();
225        if screens.is_empty() {
226            return Vec::new();
227        }
228        let mut moved = Vec::new();
229        for r in self.windows_list() {
230            if !matches!(
231                r.kind,
232                WindowKind::Main | WindowKind::App | WindowKind::Panel
233            ) {
234                continue;
235            }
236            let Some(v) = crate::window_invariants::viewport_of(r.kind, &r.id) else {
237                continue;
238            };
239            let Some(rect) = positioned(ctx, v) else {
240                continue;
241            };
242            if screens.iter().any(|s| s.intersects(rect)) {
243                continue;
244            }
245            let state = WindowState {
246                position: Some(rect.min),
247                size: rect.size(),
248                maximized: false,
249                fullscreen: false,
250            }
251            .repair(&screens);
252            let Some(at) = state.position else { continue };
253            log::info!(
254                target: "egui_pop",
255                "window `{}` was on no screen left ({rect:?}): moved to {at:?}",
256                r.id
257            );
258            ctx.send_viewport_cmd_to(v, ViewportCommand::OuterPosition(at));
259            match r.kind {
260                WindowKind::App => self.app_window_moved(v, at),
261                WindowKind::Panel => self.panel_window_moved(&r.id, at),
262                _ => {}
263            }
264            ctx.request_repaint_of(v);
265            moved.push(r.id);
266        }
267        moved
268    }
269
270    /// A detached panel's window moved to `at`: its place in the layout,
271    /// on the screen it is now on.
272    fn panel_window_moved(&self, id: &str, at: Pos2) {
273        let panel = id
274            .strip_prefix(crate::window_invariants::PANEL_PREFIX)
275            .unwrap_or(id);
276        let mut wb = self.workbench_mut();
277        if let Some(a) = wb
278            .layout
279            .auxiliary
280            .iter_mut()
281            .find(|a| a.panel.as_str() == panel)
282        {
283            let [_, _, w, h] = a.rect;
284            a.rect = [at.x, at.y, w, h];
285            if let Some(name) =
286                crate::window::screen_name_at(Rect::from_min_size(at, egui::vec2(w, h)))
287            {
288                a.screen = name;
289            }
290            // Asked by the command just sent: not asked again.
291            let panel = a.panel.clone();
292            wb.window_place_asked(&panel);
293        }
294    }
295}
296
297/// A window's rectangle on the screens, where the system tells it: none
298/// where positions are hidden (Wayland), for a window not shown yet, or
299/// minimized (Windows puts those far off every screen).
300pub(crate) fn positioned(ctx: &Context, v: ViewportId) -> Option<Rect> {
301    ctx.input(|i| {
302        let info = i.raw.viewports.get(&v)?;
303        if info.minimized == Some(true) {
304            return None;
305        }
306        info.outer_rect.filter(|r| r.is_positive())
307    })
308}