1use std::sync::{Arc, Mutex};
32
33use bus_contract::{Bus, ListenOpts, Point as _};
34use egui::{Context, ViewportCommand, ViewportId};
35use egui_pop_core::lock;
36use serde_json::json;
37
38use super::{
39 FOCUS, OWNER, PLACE, REGISTRY, Reason, Registry, WindowKind, WindowReparent, WindowRequest,
40 asking, emit,
41};
42use crate::app::AppHandle;
43use crate::windows::WindowId;
44
45pub const STEP_WINDOW_REPARENT: egui_pop_model::ids::StepId =
48 egui_pop_model::ids::StepId::from_static("window.reparent");
49
50pub(super) const MOVED_IN: &str = "moved_in";
52
53pub(super) fn declare(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::ctx::CtxError> {
55 ctx.step(
56 crate::steps::StepSpec::new(
57 STEP_WINDOW_REPARENT,
58 "A window's content moves to another window (`window`, `parent`: `main` to move into the main window, none to go back to a window of its own): its listeners on the bus run in their declared order.",
59 )
60 .args(json!({ "window": "import", "kind": "app", "owner": "app", "reason": "user", "parent": "main" })),
61 )?;
62 Ok(())
63}
64
65pub(super) fn install(kernel: &dyn Bus, registry: &Arc<Mutex<Registry>>) {
68 let mine = || ListenOpts::new().owner(OWNER);
69 let registry = registry.clone();
70 let listened = [
71 kernel.listen::<WindowReparent>(REGISTRY, mine().before(PLACE), move |req, did| {
72 let Some(app) = asking() else { return Ok(()) };
73 if req.kind == WindowKind::Panel {
74 if req.parent.as_deref() == Some(WindowId::MAIN)
77 && lock(®istry).close(&req.window)
78 {
79 lock(®istry).adopt(&req.window, WindowId::MAIN);
81 super::panels::left(&app, &req.window);
82 let mut w = app.windows_mut();
83 w.moved_events
84 .push(("window.closed", json!({ "window": req.window })));
85 w.moved_events.push((
86 "window.moved",
87 json!({ "window": req.window, "to": WindowId::MAIN }),
88 ));
89 did.push(format!("{REGISTRY}: `{}` docked in the main window", req.window));
90 }
91 return Ok(());
92 }
93 let id = WindowId::new(&req.window);
94 match req.parent.as_deref() {
95 Some(WindowId::MAIN) => {
96 if app.move_into_root(&id) {
97 let mut registry = lock(®istry);
98 registry.close(&req.window);
99 did.push(format!(
100 "{REGISTRY}: `{}` drawn in the main window",
101 req.window
102 ));
103 let adopted = registry.adopt(&req.window, WindowId::MAIN);
105 if adopted > 0 {
106 did.push(format!(
107 "{REGISTRY}: {adopted} of its popups now the main window's"
108 ));
109 }
110 did.extend(super::panels::follow_shell(&app, &mut registry, true));
111 }
112 }
113 None => {
114 if app.move_out_of_root() {
115 let mut registry = lock(®istry);
116 registry.open(req, Some(id.deferred_viewport()));
117 did.push(format!(
118 "{REGISTRY}: `{}` in a window of its own",
119 req.window
120 ));
121 did.extend(super::panels::follow_shell(&app, &mut registry, false));
122 }
123 }
124 Some(other) => {
125 return Err(format!(
126 "`{}` cannot move into `{other}`: only the main window takes another's content",
127 req.window
128 )
129 .into());
130 }
131 }
132 Ok(())
133 }),
134 kernel.listen::<WindowReparent>(PLACE, mine().after(REGISTRY), |_, did| {
135 let Some(app) = asking() else { return Ok(()) };
136 if app.keep_moved_places() > 0 {
137 did.push(format!("{PLACE}: each keeps its place"));
138 }
139 Ok(())
140 }),
141 kernel.listen::<WindowReparent>(FOCUS, mine().after(PLACE), |_, did| {
142 let Some(app) = asking() else { return Ok(()) };
143 app.request_window_activate(WindowRequest::new(
146 WindowId::MAIN,
147 WindowKind::Main,
148 OWNER,
149 Reason::System,
150 ));
151 did.push(format!("{FOCUS}: the main window is active"));
152 Ok(())
153 }),
154 ];
155 for l in listened {
156 debug_assert!(l.is_ok(), "{l:?}");
157 }
158}
159
160pub(super) fn close_children_of_main(app: &AppHandle, req: &WindowRequest, did: &mut Vec<String>) {
164 let reason = if req.reason == Reason::Quit {
165 Reason::Quit
166 } else {
167 Reason::ParentClosed
168 };
169 let children: Vec<WindowRequest> = app
170 .windows_list()
171 .into_iter()
172 .filter(|w| w.kind == WindowKind::App)
173 .map(|w| {
174 let mut child = WindowRequest::new(w.id, w.kind, w.owner, reason);
175 child.cause = req.cause;
176 child.parent(WindowId::MAIN)
177 })
178 .collect();
179 let mut closed = 0;
180 for child in children {
181 if app.request_window_close(child) {
182 closed += 1;
183 }
184 }
185 if closed > 0 {
186 did.push(format!("{}: {closed} windows closed", super::CHILDREN));
187 }
188}
189
190pub(super) fn move_in_instead(app: &AppHandle, req: &WindowRequest) -> Option<serde_json::Value> {
194 if req.kind != WindowKind::Main || req.reason == Reason::Quit {
195 return None;
196 }
197 let id = app.window_to_move_in()?;
198 let owner = app
199 .windows_list()
200 .into_iter()
201 .find(|w| w.id == id.as_str())
202 .map_or_else(|| "app".to_string(), |w| w.owner);
203 let mut moving = WindowRequest::new(id.as_str(), WindowKind::App, owner, Reason::User)
204 .parent(WindowId::MAIN);
205 moving.cause = req.cause;
206 let moved = app.request_window_reparent(moving);
207 Some(json!({ MOVED_IN: id, "reparented": moved }))
208}
209
210impl AppHandle {
211 pub fn request_window_reparent(&self, request: WindowRequest) -> bool {
222 let args = serde_json::to_value(&request).unwrap_or_default();
223 let outcome = self.step(&STEP_WINDOW_REPARENT, args, |app, args| {
224 let req = serde_json::from_value::<WindowRequest>(args.clone())
225 .map_err(|e| format!("not a window request: {e}"))?;
226 let did = emit::<WindowReparent>(app, req);
227 Ok(json!({ "did": did }))
228 });
229 let said = std::mem::take(&mut self.windows_mut().moved_events);
230 match outcome {
231 crate::steps::Outcome::Vetoed { by, reason } => {
232 self.publish(
233 "egui_pop",
234 request.cause,
235 "window.refused",
236 json!({ "request": WindowReparent::ID.as_str(), "window": request.window, "owner": request.owner, "vetoed_by": by, "reason": reason }),
237 );
238 false
239 }
240 crate::steps::Outcome::Done(result) => {
241 let moved = !said.is_empty();
242 for (name, data) in said {
243 self.publish("egui_pop", request.cause, name, data);
244 }
245 result.is_ok() && moved
246 }
247 }
248 }
249
250 pub(crate) fn ask_main_close(&self, reason: Reason) -> bool {
253 self.request_window_close(WindowRequest::new(
254 WindowId::MAIN,
255 WindowKind::Main,
256 "app",
257 reason,
258 ))
259 }
260
261 pub(crate) fn main_close_seen(&self, ctx: &Context) {
266 if !ctx.input(|i| i.viewport().close_requested()) {
267 return;
268 }
269 let quit_asked = self.take_quitting();
270 let closing = !lock(&self.0.bus.registry).holds(WindowId::MAIN);
271 if quit_asked || closing {
272 return;
273 }
274 if !self.ask_main_close(Reason::User) {
275 ctx.send_viewport_cmd(ViewportCommand::CancelClose);
276 }
277 }
278
279 pub(super) fn registry_close_main(&self) {
282 let ctx = self.egui();
283 if !ctx.input_for(ViewportId::ROOT, |i| i.viewport().close_requested()) {
284 ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Close);
285 }
286 ctx.request_repaint_of(ViewportId::ROOT);
287 }
288
289 pub(crate) fn ask_home(&self) {
293 let Some(id) = self.take_going_home() else {
294 return;
295 };
296 self.request_window_reparent(WindowRequest::new(
297 id.as_str(),
298 WindowKind::App,
299 "app",
300 Reason::User,
301 ));
302 }
303
304 pub(crate) fn frame_close(&self, ctx: &Context) -> bool {
309 if ctx.viewport_id() == ViewportId::ROOT {
310 return self.ask_main_close(Reason::User);
311 }
312 ctx.send_viewport_cmd(ViewportCommand::Close);
313 true
314 }
315}