Skip to main content

egui_pop_api/bus/
activate.rs

1//! The active window on the bus (`pop.window.activate`, ADR 0029): the window
2//! the person works in, one truth held by the registry.
3//!
4//! A press, a key or text in a window asks it (`user`), a window gaining
5//! the system's focus asks it (`system`), the application asking a window
6//! to the front asks it (`command`). `pop.window.registry` holds it as the
7//! active window; [`RAISE`] shows, restores and focuses a window asked by
8//! a command, the one place egui-pop sends `ViewportCommand::Focus`;
9//! `window.activated` is said after the last listener when the active
10//! window changed. A window closing while active hands the activation to
11//! the window worked in before it (`pop.window.focus`, a `system` request).
12
13use std::cell::{Cell, RefCell};
14use std::rc::Rc;
15use std::sync::{Arc, Mutex};
16
17use bus_contract::{Bus, ListenOpts, Point as _};
18use egui::{Context, UserAttentionType, ViewportCommand, ViewportId};
19use egui_pop_core::lock;
20use serde_json::json;
21
22use super::{
23    KEYS, OWNER, RAISE, REGISTRY, Reason, Registry, WindowActivate, WindowKind, WindowRequest,
24    asking, emit,
25};
26use crate::app::AppHandle;
27use crate::windows::WindowId;
28
29/// Registers `pop.window.activate`'s listeners: the registry, then the raise
30/// (the invariants, last, are the bus's).
31pub(super) fn install(kernel: &dyn Bus, registry: &Arc<Mutex<Registry>>) {
32    let mine = || ListenOpts::new().owner(OWNER);
33    let registry = registry.clone();
34    let listened = [
35        kernel.listen::<WindowActivate>(REGISTRY, mine().before(RAISE), move |req, did| {
36            let mut registry = lock(&registry);
37            if registry.record(&req.window).is_none() {
38                return Err(format!("`{}` is not in the registry", req.window).into());
39            }
40            registry.activate(&req.window);
41            did.push(format!("{REGISTRY}: `{}` is active", req.window));
42            Ok(())
43        }),
44        kernel.listen::<WindowActivate>(RAISE, mine().after(REGISTRY), |req, did| {
45            if req.reason != Reason::Command {
46                return Ok(());
47            }
48            let Some(app) = asking() else { return Ok(()) };
49            let Some(v) = crate::window_invariants::viewport_of(req.kind, &req.window) else {
50                return Ok(());
51            };
52            raise(&app.egui(), v, req.kind == WindowKind::Main);
53            if req.kind == WindowKind::App {
54                app.0.bus.raise_pending.borrow_mut().insert(v);
55            }
56            did.push(format!("{RAISE}: `{}` to the front", req.window));
57            Ok(())
58        }),
59    ];
60    for l in listened {
61        debug_assert!(l.is_ok(), "{l:?}");
62    }
63}
64
65/// Registers [`KEYS`], a local listener on `pop.window.activate` after the
66/// registry: when the active window changes, `epoch` counts it, and each
67/// window's key dispatcher drops its shortcut in progress at its next
68/// pass. A chord begun in one window is never finished in another.
69pub(super) fn install_keys(kernel: &dyn Bus, epoch: Rc<Cell<u64>>) {
70    let last = RefCell::new(WindowId::MAIN.to_string());
71    let listened = kernel.listen_local::<WindowActivate>(
72        KEYS,
73        ListenOpts::new().owner(OWNER).after(REGISTRY),
74        move |req, did| {
75            let mut last = last.borrow_mut();
76            if *last != req.window {
77                req.window.clone_into(&mut last);
78                epoch.set(epoch.get() + 1);
79                did.push(format!("{KEYS}: shortcuts in progress dropped"));
80            }
81            Ok(())
82        },
83    );
84    if let Err(e) = listened {
85        log::warn!(target: "egui_pop", "{KEYS}: {e}");
86    }
87}
88
89/// Shows a window, restores it when minimized and asks the system's focus
90/// for it. On Wayland a window cannot take the focus by itself (the
91/// compositor needs an activation token, which egui does not pass on):
92/// the main window asks for attention instead, and the desktop says so.
93fn raise(ctx: &Context, v: ViewportId, main: bool) {
94    ctx.send_viewport_cmd_to(v, ViewportCommand::Visible(true));
95    ctx.send_viewport_cmd_to(v, ViewportCommand::Minimized(false));
96    ctx.send_viewport_cmd_to(v, ViewportCommand::Focus);
97    if main && wayland() {
98        ctx.send_viewport_cmd_to(
99            v,
100            ViewportCommand::RequestUserAttention(UserAttentionType::Informational),
101        );
102    }
103    ctx.request_repaint_of(v);
104}
105
106/// The main window shown, restored and focused, for a program without an
107/// egui-pop application (the platform readers used standalone): what
108/// [`RAISE`] does for a `pop.window.activate` of the main window. An
109/// application asks `pop.window.activate` instead
110/// ([`AppHandle::request_window_activate`]).
111///
112/// <div class="warning">Experimental: may change in any release
113/// (docs/stability.md).</div>
114pub fn raise_main_window(ctx: &Context) {
115    raise(ctx, ViewportId::ROOT, true);
116}
117
118/// Whether the session is a Wayland one.
119fn wayland() -> bool {
120    cfg!(all(unix, not(target_os = "macos")))
121        && (std::env::var_os("WAYLAND_DISPLAY").is_some()
122            || std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland"))
123}
124
125impl AppHandle {
126    /// Asks for a window to become the active one, the window worked in
127    /// (`pop.window.activate`, ADR 0029): the registry holds it as active, and
128    /// with the reason `command` it is brought to the front. Its listeners
129    /// run now, in their declared order; `window.activated` is said after
130    /// the last one when the active window changed. A window not in the
131    /// registry is refused, said as `window.refused`. Whether it ran.
132    ///
133    /// <div class="warning">Experimental: may change in any release
134    /// (docs/stability.md).</div>
135    pub fn request_window_activate(&self, request: WindowRequest) -> bool {
136        let (before, held) = {
137            let r = lock(&self.0.bus.registry);
138            (r.active().0, r.record(&request.window).map(|w| w.kind))
139        };
140        let Some(kind) = held else {
141            self.publish(
142                "egui_pop",
143                request.cause,
144                "window.refused",
145                json!({ "request": WindowActivate::ID.as_str(), "window": request.window, "owner": request.owner, "reason": "no open window of this id" }),
146            );
147            return false;
148        };
149        let request = WindowRequest { kind, ..request };
150        let did = emit::<WindowActivate>(self, request.clone());
151        let after = self.active_window_id();
152        if after != before {
153            // The other windows lost the focus, whether or not they drew a
154            // pass since: one focused again gains it anew.
155            let here = crate::window_invariants::viewport_of(request.kind, &request.window);
156            self.0
157                .bus
158                .focus_seen
159                .borrow_mut()
160                .retain(|v, _| Some(*v) == here);
161            self.publish(
162                "egui_pop",
163                request.cause,
164                "window.activated",
165                json!({
166                    "window": request.window,
167                    "kind": request.kind,
168                    "owner": request.owner,
169                    "reason": request.reason,
170                    "from": before,
171                    "did": did,
172                }),
173            );
174        }
175        true
176    }
177
178    /// The active window's id in the registry (`main`, an application
179    /// window's id, `panel:<id>`).
180    ///
181    /// <div class="warning">Experimental: may change in any release
182    /// (docs/stability.md).</div>
183    pub fn active_window_id(&self) -> String {
184        lock(&self.0.bus.registry).active().0
185    }
186
187    /// The active window as the registry holds it: its id and kind.
188    pub(crate) fn active_window_record(&self) -> (String, WindowKind) {
189        lock(&self.0.bus.registry).active()
190    }
191
192    /// The window of the registry a viewport draws (the main window, a
193    /// detached panel's, an application window's): its id and kind.
194    pub(crate) fn registry_window_at(&self, v: ViewportId) -> Option<(String, WindowKind)> {
195        let shown = format!("{v:?}");
196        lock(&self.0.bus.registry)
197            .records
198            .iter()
199            .find(|r| {
200                matches!(
201                    r.kind,
202                    WindowKind::Main | WindowKind::App | WindowKind::Panel
203                ) && r.viewport.as_deref() == Some(shown.as_str())
204            })
205            .map(|r| (r.id.clone(), r.kind))
206    }
207
208    /// Asks the window a viewport draws (the main window, a detached
209    /// panel's, an application window's) to the front: `pop.window.activate`
210    /// with the reason `command`, as [`Self::request_window_activate`] does
211    /// for a registry id. Use it rather than `ViewportCommand::Focus`, which
212    /// would leave the registry's active window behind. Whether it ran:
213    /// `false` for a viewport no window of the registry draws.
214    ///
215    /// <div class="warning">Experimental: may change in any release
216    /// (docs/stability.md).</div>
217    pub fn raise_viewport(&self, v: ViewportId, owner: &str) -> bool {
218        match self.registry_window_at(v) {
219            Some((id, kind)) => {
220                self.request_window_activate(WindowRequest::new(id, kind, owner, Reason::Command))
221            }
222            None => false,
223        }
224    }
225
226    /// A window blocked by a modal open in another of its group
227    /// ([`egui_pop_core::overlay::block_window_raising`]): a click on its
228    /// backdrop asks the modal's window to the front (`pop.window.activate`).
229    pub(crate) fn block_window(
230        &self,
231        ctx: &Context,
232        same: &dyn Fn(ViewportId) -> bool,
233    ) -> Option<ViewportId> {
234        egui_pop_core::overlay::block_window_raising(ctx, same, &|owner| {
235            self.raise_viewport(owner, "egui_pop.dialogs");
236        })
237    }
238
239    /// The window being drawn asks to be the active one when the person
240    /// pressed, typed or wrote in it this pass (`user`), or when it gained
241    /// the system's focus (`system`). Nothing is asked for the window
242    /// already active.
243    pub(crate) fn note_window(&self, ctx: &Context) {
244        let v = ctx.viewport_id();
245        let (focused, used) = ctx.input(|i| {
246            (
247                i.viewport().focused == Some(true),
248                i.events.iter().any(|e| {
249                    matches!(
250                        e,
251                        egui::Event::Key { pressed: true, .. }
252                            | egui::Event::PointerButton { pressed: true, .. }
253                            | egui::Event::Text(_)
254                    )
255                }),
256            )
257        });
258        let had = self.0.bus.focus_seen.borrow_mut().insert(v, focused);
259        let gained = focused && had != Some(true);
260        if !used && !gained {
261            return;
262        }
263        let Some((id, kind)) = self.registry_window_at(v) else {
264            return;
265        };
266        if self.active_window_id() == id {
267            return;
268        }
269        let reason = if used { Reason::User } else { Reason::System };
270        self.request_window_activate(WindowRequest::new(id, kind, OWNER, reason));
271    }
272
273    /// From an application window's own pass: the focus asked again when
274    /// a command raised it since (`pop.window.raise`), so a window not yet
275    /// drawn when it was raised gets it too.
276    pub(crate) fn raise_in_pass(&self, ctx: &Context) {
277        if self
278            .0
279            .bus
280            .raise_pending
281            .borrow_mut()
282            .remove(&ctx.viewport_id())
283        {
284            ctx.send_viewport_cmd(ViewportCommand::Focus);
285        }
286    }
287
288    /// A closing window's focus is forgotten: a window of the same id
289    /// opened again and focused gains the focus anew.
290    pub(crate) fn forget_focus(&self, req: &WindowRequest) {
291        if let Some(v) = crate::window_invariants::viewport_of(req.kind, &req.window) {
292            self.0.bus.focus_seen.borrow_mut().remove(&v);
293            self.0.bus.raise_pending.borrow_mut().remove(&v);
294        }
295    }
296
297    /// `pop.window.focus`'s part on a window closing: when it is the active
298    /// one, the window worked in before it becomes active (a `system`
299    /// request). The window made active, if one was.
300    pub(crate) fn focus_before_close(&self, closing: &str) -> Option<String> {
301        if closing == WindowId::MAIN {
302            return None;
303        }
304        let (id, kind) = {
305            let r = lock(&self.0.bus.registry);
306            if r.active().0 != closing {
307                return None;
308            }
309            r.by_recency()
310                .find(|w| {
311                    w.id != closing
312                        && matches!(
313                            w.kind,
314                            WindowKind::Main | WindowKind::App | WindowKind::Panel
315                        )
316                })
317                .map(|w| (w.id.clone(), w.kind))
318                .unwrap_or_else(|| (WindowId::MAIN.to_string(), WindowKind::Main))
319        };
320        self.request_window_activate(WindowRequest::new(id.clone(), kind, OWNER, Reason::System));
321        Some(id)
322    }
323
324    /// The application windows other than the main one, worked in last
325    /// first (those never activated after, in opening order).
326    pub(crate) fn app_windows_by_recency(&self) -> Vec<String> {
327        let r = lock(&self.0.bus.registry);
328        let mut out: Vec<String> = r
329            .by_recency()
330            .filter(|w| w.kind == WindowKind::App)
331            .map(|w| w.id.clone())
332            .collect();
333        for w in r.records.iter().filter(|w| w.kind == WindowKind::App) {
334            if !out.contains(&w.id) {
335                out.push(w.id.clone());
336            }
337        }
338        out
339    }
340}