1use bus_contract::{Bus, ListenOpts};
28use egui::{Context, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId};
29use egui_pop_model::ids::PanelId;
30use egui_pop_model::layout::Auxiliary;
31use serde_json::json;
32
33use super::{
34 CHILDREN, FOCUS, REGISTRY, Reason, WindowClose, WindowKind, WindowOpen, WindowReparent,
35 WindowRequest, asking,
36};
37use crate::app::AppHandle;
38use crate::window_invariants::PANEL_PREFIX;
39use crate::windows::WindowId;
40use crate::workbench::Change;
41
42pub const WORKBENCH_OWNER: &str = "egui_pop.workbench";
44pub const WORKBENCH_WINDOW: &str = "pop.workbench.window";
47
48pub(crate) fn window_of_panel(panel: &PanelId) -> String {
50 format!("{PANEL_PREFIX}{}", panel.as_str())
51}
52
53fn panel_of_window(id: &str) -> Option<PanelId> {
55 PanelId::new(id.strip_prefix(PANEL_PREFIX)?).ok()
56}
57
58fn request(id: &str, reason: Reason) -> WindowRequest {
60 WindowRequest::new(id, WindowKind::Panel, WORKBENCH_OWNER, reason)
61}
62
63pub(super) fn install(kernel: &dyn Bus) {
66 let mine = || ListenOpts::new().owner(WORKBENCH_OWNER);
67 let listened = [
68 kernel.listen::<WindowOpen>(WORKBENCH_WINDOW, mine().before(REGISTRY), |req, did| {
69 let Some((app, panel)) = panel_request(req) else {
70 return Ok(());
71 };
72 let named = app
76 .workbench_mut()
77 .layout
78 .window_of(&panel)
79 .filter(|a| a.panel == panel)
80 .map(|a| a.tabs.is_empty());
81 let made = match named {
82 Some(true) => true,
83 Some(false) => !app.windows_list().iter().any(|w| w.id == req.window),
84 None => false,
85 };
86 if !made {
87 app.workbench_mut().apply(&Change::Detach(panel.clone()))?;
88 did.push(format!("{WORKBENCH_WINDOW}: `{panel}` detached"));
89 }
90 Ok(())
91 }),
92 kernel.listen::<WindowClose>(
93 WORKBENCH_WINDOW,
94 mine().after(CHILDREN).before(FOCUS),
95 |req, did| dock_back(req, did, "its window closed"),
96 ),
97 kernel.listen::<WindowReparent>(WORKBENCH_WINDOW, mine().before(REGISTRY), |req, did| {
98 if req.kind == WindowKind::Panel && req.parent.as_deref() != Some(WindowId::MAIN) {
99 return Err(format!(
100 "`{}` moves only into the main window; detaching a panel is `pop.window.open`",
101 req.window
102 )
103 .into());
104 }
105 dock_back(req, did, "docked back")
106 }),
107 ];
108 for l in listened {
109 debug_assert!(l.is_ok(), "{l:?}");
110 }
111}
112
113fn panel_request(req: &WindowRequest) -> Option<(AppHandle, PanelId)> {
116 if req.kind != WindowKind::Panel {
117 return None;
118 }
119 Some((asking()?, panel_of_window(&req.window)?))
120}
121
122fn dock_back(
125 req: &WindowRequest,
126 did: &mut Vec<String>,
127 how: &str,
128) -> Result<(), bus_contract::HookError> {
129 let Some((app, panel)) = panel_request(req) else {
130 return Ok(());
131 };
132 let held = app
133 .workbench_mut()
134 .layout
135 .auxiliary
136 .iter()
137 .any(|a| a.panel == panel);
138 if held {
139 app.workbench_mut()
140 .apply(&Change::CloseWindow(panel.clone()))?;
141 did.push(format!("{WORKBENCH_WINDOW}: `{panel}` {how}"));
142 }
143 Ok(())
144}
145
146pub(crate) fn ask(app: &AppHandle, change: &Change) -> Option<Result<serde_json::Value, String>> {
151 if app.root_has_content() {
154 return None;
155 }
156 let (panel, window) = {
157 let wb = app.workbench_mut();
158 let panel = match change {
159 Change::Detach(p) | Change::Attach(p) | Change::CloseWindow(p) => p.clone(),
160 _ => return None,
161 };
162 let spec = wb.spec(&panel).cloned()?;
164 let window = wb.layout.window_of(&panel).cloned();
165 if let Change::Detach(_) = change
166 && spec
167 .refuses(&crate::mounts::panel_host(
168 egui_pop_model::panels::Place::Window,
169 ))
170 .is_some()
171 {
172 return None;
173 }
174 (panel, window)
175 };
176 match change {
177 Change::Detach(_) => {
178 if window
179 .as_ref()
180 .is_some_and(|a| a.panel == panel && a.tabs.is_empty())
181 {
182 return None;
183 }
184 app.request_panel_window_open(&panel, Reason::Command);
185 let detached = app.workbench_mut().layout.window_of(&panel).is_some();
186 Some(if detached {
187 Ok(json!({ "panel": panel, "detached": true }))
188 } else {
189 Err(format!("`{panel}` was not detached"))
190 })
191 }
192 Change::Attach(_) => {
193 let a = window.filter(|a| a.tabs.is_empty())?;
195 let req = request(&window_of_panel(&a.panel), Reason::Command).parent(WindowId::MAIN);
196 app.request_window_reparent(req);
197 let docked = app.workbench_mut().layout.window_of(&panel).is_none();
198 Some(if docked {
199 Ok(json!({ "panel": panel, "detached": false }))
200 } else {
201 Err(format!(
202 "`{panel}` stays in its window: its move was refused"
203 ))
204 })
205 }
206 _ => {
207 let a = window?;
208 let panels: Vec<PanelId> = a.panels().cloned().collect();
209 let closed =
210 app.request_window_close(request(&window_of_panel(&a.panel), Reason::User));
211 Some(if closed {
212 Ok(json!({ "panel": panel, "detached": false, "docked": panels }))
213 } else {
214 Err(format!(
215 "the window of `{panel}` stays: its close was refused"
216 ))
217 })
218 }
219 }
220}
221
222pub(super) fn left(app: &AppHandle, id: &str) {
226 if let Some(v) = crate::window_invariants::viewport_of(WindowKind::Panel, id) {
227 app.excuse_backend_once(v, false);
228 }
229}
230
231pub(crate) fn shown(app: &AppHandle) -> Vec<String> {
234 if app.root_has_content() {
235 return Vec::new();
236 }
237 app.workbench_mut()
238 .layout
239 .auxiliary
240 .iter()
241 .map(|a| window_of_panel(&a.panel))
242 .collect()
243}
244
245pub(super) fn follow_shell(
249 app: &AppHandle,
250 registry: &mut super::Registry,
251 into_main: bool,
252) -> Option<String> {
253 if into_main {
254 let before = registry.records.len();
255 registry.records.retain(|r| r.kind != WindowKind::Panel);
256 let gone = before - registry.records.len();
257 (gone > 0).then(|| format!("{REGISTRY}: {gone} detached panels' windows hidden"))
258 } else {
259 let back = shown(app);
260 for id in &back {
261 let viewport = crate::window_invariants::viewport_of(WindowKind::Panel, id);
262 registry.open(&request(id, Reason::Command), viewport);
263 }
264 (!back.is_empty()).then(|| {
265 format!(
266 "{REGISTRY}: {} detached panels' windows shown again",
267 back.len()
268 )
269 })
270 }
271}
272
273impl AppHandle {
274 fn request_panel_window_open(&self, panel: &PanelId, reason: Reason) {
278 let id = window_of_panel(panel);
279 let did = self.ask_window_open(request(&id, reason));
280 self.publish(
281 "egui_pop",
282 None,
283 "window.opened",
284 json!({ "window": id, "kind": WindowKind::Panel, "owner": WORKBENCH_OWNER, "reason": reason, "did": did }),
285 );
286 }
287
288 pub(crate) fn sync_panel_windows(&self, before: &[Auxiliary]) {
295 if self.root_has_content() {
296 return;
297 }
298 let shown = shown(self);
299 let held: Vec<String> = self
300 .windows_list()
301 .into_iter()
302 .filter(|w| w.kind == WindowKind::Panel)
303 .map(|w| w.id)
304 .collect();
305 for id in held.iter().filter(|id| !shown.contains(id)) {
306 let docked = before
307 .iter()
308 .find(|a| window_of_panel(&a.panel) == *id)
309 .is_some_and(|a| {
310 let wb = self.workbench_mut();
311 a.panels().any(|p| wb.layout.area_of(p).is_some())
312 });
313 let req = request(id, Reason::Command);
314 if docked {
315 self.request_window_reparent(req.parent(WindowId::MAIN));
316 } else {
317 self.request_window_close(req);
318 }
319 }
320 for id in shown.iter().filter(|id| !held.contains(id)) {
321 if let Some(panel) = panel_of_window(id) {
322 self.request_panel_window_open(&panel, Reason::Command);
323 }
324 }
325 }
326}
327
328pub(crate) fn show_window<T>(
331 ctx: &Context,
332 viewport: ViewportId,
333 builder: ViewportBuilder,
334 content: impl FnMut(&mut egui::Ui, ViewportClass) -> T,
335) -> T {
336 ctx.show_viewport_immediate(viewport, builder, content)
337}
338
339pub(crate) fn ask_place(
345 ctx: &Context,
346 viewport: ViewportId,
347 panel: &PanelId,
348 from: crate::window::WindowState,
349 to: crate::window::WindowState,
350) {
351 let mut commands = Vec::new();
352 if to.fullscreen != from.fullscreen {
353 commands.push(ViewportCommand::Fullscreen(to.fullscreen));
354 }
355 if to.maximized != from.maximized {
356 commands.push(ViewportCommand::Maximized(to.maximized));
357 }
358 if !to.maximized && !to.fullscreen {
359 if to.size != from.size {
360 commands.push(ViewportCommand::InnerSize(to.size));
361 }
362 if let Some(at) = to.position
363 && Some(at) != from.position
364 {
365 commands.push(ViewportCommand::OuterPosition(at));
366 }
367 }
368 for c in commands {
369 log::info!(
370 target: "egui_pop::window_size",
371 "`{panel}`'s window asked {c:?}: the application changed its place in the layout"
372 );
373 ctx.send_viewport_cmd_to(viewport, c);
374 }
375}
376
377pub(crate) fn keep_open(vctx: &Context) {
380 vctx.send_viewport_cmd(ViewportCommand::CancelClose);
381}