1use 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
29pub(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(®istry);
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
65pub(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
89fn 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
106pub fn raise_main_window(ctx: &Context) {
115 raise(ctx, ViewportId::ROOT, true);
116}
117
118fn 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 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 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 pub fn active_window_id(&self) -> String {
184 lock(&self.0.bus.registry).active().0
185 }
186
187 pub(crate) fn active_window_record(&self) -> (String, WindowKind) {
189 lock(&self.0.bus.registry).active()
190 }
191
192 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 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 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 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 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 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 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 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}