1use std::collections::{BTreeMap, HashMap};
53
54use egui::{Id, Rect, Ui};
55use egui_pop_model::ids::PanelId;
56use egui_pop_model::layout::{Node, WindowAreas};
57use egui_pop_model::panels::Area;
58use egui_stack::{DockArea, DockSpace, NodeIndex, TabViewer};
59use serde_json::Value as Json;
60
61use super::{area_name, area_rules, empty_dock, panel_menu, read, to_dock};
62use crate::app::AppHandle;
63use crate::windows::WindowId;
64
65#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub(crate) struct OpenFrom {
69 pub origin: Option<String>,
71 pub home: Option<String>,
73 pub area: Option<Area>,
76}
77
78impl OpenFrom {
79 pub(crate) fn of(app: &AppHandle, args: &Json) -> OpenFrom {
82 let text = |key: &str| args.get(key).and_then(Json::as_str).map(str::to_string);
83 OpenFrom {
84 origin: text("origin").or_else(|| Some(current_window(app))),
85 home: text("home"),
86 area: text("home_area").as_deref().and_then(super::area_from),
87 }
88 }
89}
90
91pub(crate) fn current_window(app: &AppHandle) -> String {
95 app.window_of_group(app.current_window_group()).to_string()
96}
97
98const DRAWN: [Area; 4] = [Area::StartSide, Area::EndSide, Area::Bottom, Area::Center];
100
101const DOCK_PREFIX: &str = "in-window:";
103
104pub(crate) fn dock_name(window: &str, area: Area) -> String {
107 format!("{DOCK_PREFIX}{window}:{}", area_name(area))
108}
109
110pub(crate) fn dock_place(name: &str) -> Option<(&str, Area)> {
113 let (window, area) = name.strip_prefix(DOCK_PREFIX)?.rsplit_once(':')?;
114 Some((window, super::area_from(area)?))
115}
116
117pub(crate) fn add_docks(space: &mut DockSpace<PanelId>, windows: &[WindowAreas]) {
122 for w in windows {
123 for area in DRAWN {
124 let name = dock_name(&w.window, area);
125 if space.has_dock(&name) {
126 continue;
127 }
128 let node = w.areas.iter().find(|(a, _)| *a == area).map(|(_, n)| n);
129 add_dock(space, &name, node);
130 }
131 }
132}
133
134fn add_dock(space: &mut DockSpace<PanelId>, name: &str, node: Option<&Node>) {
136 let mut state = node.map_or_else(empty_dock, to_dock);
137 let tree = std::mem::take(state.main_surface_mut());
138 space.add_dock_tree(name, area_rules(), tree);
139}
140
141pub(crate) fn read_docks(space: &DockSpace<PanelId>) -> BTreeMap<String, Vec<(Area, Node)>> {
144 let mut out: BTreeMap<String, Vec<(Area, Node)>> = BTreeMap::new();
145 for name in space.dock_names() {
146 let Some((window, area)) = dock_place(name) else {
147 continue;
148 };
149 let areas = out.entry(window.to_owned()).or_default();
150 if let Some(tree) = space.dock(name)
151 && !tree.is_empty()
152 && let Some(node) = read(tree, NodeIndex::root())
153 {
154 areas.push((area, node));
155 }
156 }
157 for areas in out.values_mut() {
158 areas.sort_by_key(|(a, _)| *a);
159 }
160 out
161}
162
163pub(crate) fn show(app: &AppHandle, ui: &mut Ui, window: &WindowId, content: impl FnOnce(&mut Ui)) {
168 let centre_dock = app.window_centre_dock(window);
169 let alone = app.workbench_mut().zen_in_app_window(window.as_str());
172 if let Some(panel) = alone {
173 super::show_alone(app, ui, &panel);
174 return;
175 }
176 let areas = {
179 let mut wb = app.workbench_mut();
180 wb.read_back();
181 wb.layout
182 .window_areas(window.as_str())
183 .map(|w| w.areas.clone())
184 };
185 let areas = areas.unwrap_or_default();
186 if areas.is_empty() && !centre_dock {
187 content(ui);
188 return;
189 }
190 let folded = app
191 .workbench_mut()
192 .layout
193 .window_areas(window.as_str())
194 .map(|w| w.folded.clone())
195 .unwrap_or_default();
196 let has = |area: Area| areas.iter().any(|(a, _)| *a == area);
197 let open = |area: Area| has(area) && !folded.contains(&area);
198 let strip = |area: Area| {
199 matches!(area, Area::StartSide | Area::EndSide) && has(area) && folded.contains(&area)
200 };
201 let salt = |area: Area| Id::unique(("egui_pop.window_area", window.as_str(), area_name(area)));
202 let mut viewer = WindowViewer { app };
203 let area_id = super::space_id().with(("egui_pop.app_window", window.as_str()));
207 let mut dock = |ui: &mut Ui, area: Area| {
210 let region = egui_pop_core::focus::Region::new(
211 format!("region.window.{}", area_name(area)),
212 super::rank_of(area),
213 )
214 .holding(true);
216 let Some(mut space) = app.workbench_mut().take_space() else {
217 return;
218 };
219 let name = dock_name(window.as_str(), area);
220 if centre_dock && area == Area::Center && !space.has_dock(&name) {
221 add_dock(&mut space, &name, None);
225 }
226 if space.has_dock(&name) {
227 egui_pop_core::focus::region(ui, ®ion, |ui| {
228 DockArea::dock(&mut space, &name)
229 .id(area_id)
230 .show_close_buttons(false)
231 .show_add_buttons(false)
232 .show_leaf_close_all_buttons(false)
233 .show_leaf_collapse_buttons(false)
234 .show_inside(ui, &mut viewer);
235 });
236 }
237 app.workbench_mut().put_space(space);
238 };
239 let size = ui.available_size();
240 let kit = egui_pop_core::kit::Kit::of(ui.ctx());
241 let strip_width = strip_breadth(ui.ctx(), &kit);
242 let side_frame =
246 egui::Frame::side_top_panel(ui.style()).inner_margin(kit.dock_area_margin(false));
247 let centre_frame =
248 egui::Frame::central_panel(ui.style()).inner_margin(kit.dock_area_margin(false));
249 let mut strips = Vec::new();
250 for area in [Area::StartSide, Area::EndSide] {
251 if !strip(area) {
252 continue;
253 }
254 let panel = if area == Area::StartSide {
255 egui::Panel::left(salt(area).with("strip"))
256 } else {
257 egui::Panel::right(salt(area).with("strip"))
258 };
259 let r = panel
260 .resizable(false)
261 .exact_size(strip_width)
262 .frame(egui::Frame::side_top_panel(ui.style()).inner_margin(0.0))
264 .show(ui, |ui| window_strip(app, ui, &kit, window.as_str(), area));
265 strips.push((area, r.response.rect));
266 }
267 for area in [Area::StartSide, Area::EndSide] {
268 if !open(area) {
269 continue;
270 }
271 let panel = if area == Area::StartSide {
272 egui::Panel::left(salt(area))
273 } else {
274 egui::Panel::right(salt(area))
275 };
276 side_panel(app, panel, &areas, area, size.x)
277 .frame(side_frame)
278 .show(ui, |ui| dock(ui, area));
279 }
280 if open(Area::Bottom) {
281 egui::Panel::bottom(salt(Area::Bottom))
282 .resizable(true)
283 .default_size((size.y * 0.3).max(120.0))
284 .frame(side_frame)
285 .show(ui, |ui| dock(ui, Area::Bottom));
286 }
287 let centre = if centre_dock {
288 drop(content);
291 let empty = !has(Area::Center);
292 egui::CentralPanel::default()
293 .frame(centre_frame)
294 .show(ui, |ui| {
295 let rect = ui.max_rect();
296 dock(ui, Area::Center);
297 if empty {
298 empty_centre(ui, rect);
299 }
300 })
301 .response
302 .rect
303 } else {
304 if has(Area::Center) {
305 egui::Panel::right(salt(Area::Center))
308 .resizable(true)
309 .default_size(ui.available_width() * 0.5)
310 .frame(side_frame)
311 .show(ui, |ui| dock(ui, Area::Center));
312 }
313 egui::CentralPanel::default()
314 .show(ui, |ui| {
315 let region = egui_pop_core::focus::Region::new(
316 "region.window.content",
317 super::rank_of(Area::Center),
318 );
319 egui_pop_core::focus::region(ui, ®ion, content);
320 })
321 .response
322 .rect
323 };
324 let flyout = app.workbench_mut().flyout.clone();
327 if let Some(panel) = flyout {
328 let place = app
329 .workbench_mut()
330 .layout
331 .window_place(&panel)
332 .map(|(w, a)| (w.to_string(), a));
333 if let Some((_, area)) = place.filter(|(w, _)| w == window.as_str())
334 && let Some((_, rect)) = strips.iter().find(|(a, _)| *a == area)
335 {
336 show_flyout(app, ui, &kit, &panel, area, *rect, centre);
337 }
338 }
339 let mut wb = app.workbench_mut();
342 wb.read_back();
343 let now = wb.layout.window_areas(window.as_str()).map(|w| &w.areas);
344 let changed = now.map_or(!areas.is_empty(), |now| *now != areas);
345 drop(wb);
346 if changed {
347 app.note_layout("workbench.window_areas");
348 }
349 super::settle_area_moves(app);
351}
352
353fn side_panel(
360 app: &AppHandle,
361 panel: egui::Panel,
362 areas: &[(Area, Node)],
363 area: Area,
364 across: f32,
365) -> egui::Panel {
366 let panels: Vec<PanelId> = areas
367 .iter()
368 .filter(|(a, _)| *a == area)
369 .flat_map(|(_, node)| node.panels().into_iter().cloned())
370 .collect();
371 let (min, default, max) = app
372 .workbench_mut()
373 .area_sizes(&panels, &app.shell_bounds(), across);
374 let default = if default > 0.0 {
375 default
376 } else {
377 (across * 0.22).max(160.0)
378 };
379 let max = max.max(min);
380 let mut panel = panel.resizable(true).default_size(default.clamp(min, max));
382 if min > 0.0 {
383 panel = panel.min_size(min);
384 }
385 if max.is_finite() {
386 panel = panel.max_size(max);
387 }
388 panel
389}
390
391fn empty_centre(ui: &mut Ui, rect: Rect) {
395 let text = egui_pop_core::strings::tr(ui.ctx(), &crate::strings::WORKBENCH_DROP_HERE);
396 let mut over = ui.new_child(egui::UiBuilder::new().max_rect(rect));
397 over.centered_and_justified(|ui| {
398 ui.add(egui::Label::new(egui::RichText::new(text).weak()).selectable(false));
399 });
400}
401
402fn strip_breadth(ctx: &egui::Context, kit: &egui_pop_core::kit::Kit) -> f32 {
404 let grip = kit.area_strip.data.width.max(1.0);
405 let t = egui_pop_core::theme::Tokens::of(ctx);
406 grip.max(t.size.icon_inline + 2.0 * t.space.s)
407}
408
409fn window_strip(
413 app: &AppHandle,
414 ui: &mut Ui,
415 kit: &egui_pop_core::kit::Kit,
416 window: &str,
417 area: Area,
418) {
419 let ctx = ui.ctx().clone();
420 let t = egui_pop_core::theme::Tokens::of(&ctx);
421 let rect = ui.max_rect();
422 let cell = rect.width();
423 let name = egui_pop_core::strings::tr_args(
424 &ctx,
425 &crate::strings::WORKBENCH_UNFOLD,
426 &[("area", &super::area_text(&ctx, area))],
427 );
428 let grip = Rect::from_min_size(rect.min, egui::vec2(cell, cell));
429 let icon = if super::on_left(area, app.workbench_mut().flipped) {
430 egui_pop_core::icon::Icon::ChevronRight
431 } else {
432 egui_pop_core::icon::Icon::ChevronLeft
433 };
434 let id = Id::unique(("egui_pop.window_strip_grip", window, super::area_name(area)));
435 let unfold = ui.interact(grip, id, egui::Sense::click());
436 let label = name.clone();
437 unfold.widget_info(move || egui::WidgetInfo::labeled(egui::Role::Button, true, &label));
438 let state = egui_pop_core::kit::State::from_response(&unfold);
439 let color = kit.activity_bar_item.style(state).text;
440 let glyph = Rect::from_center_size(
441 grip.center(),
442 egui::vec2(t.size.icon_inline, t.size.icon_inline),
443 );
444 egui_pop_core::icon::Source::from(icon).paint(ui, glyph, color);
445 if unfold.has_focus() {
446 egui_pop_core::focus::own_ring(&unfold.ctx, unfold.id);
447 }
448 if unfold.on_hover_text(&name).clicked() {
449 app.fold_window_area(window, area, false);
450 }
451 let panels: Vec<PanelId> = {
452 let wb = app.workbench_mut();
453 let areas = wb.layout.window_areas(window);
454 let node = areas.and_then(|w| w.areas.iter().find(|(a, _)| *a == area));
455 node.map(|(_, n)| n.panels().into_iter().cloned().collect())
456 .unwrap_or_default()
457 };
458 let mut top = grip.bottom() + t.space.xs;
459 for p in panels.iter().filter(|p| super::drawable(app, p)) {
460 let at = Rect::from_min_size(egui::pos2(rect.left(), top), egui::vec2(cell, cell));
461 if at.bottom() > rect.bottom() {
462 break;
463 }
464 super::strip_icon(app, ui, kit, area, p, at, false, false);
465 top += cell + t.space.xs;
466 }
467}
468
469fn show_flyout(
473 app: &AppHandle,
474 ui: &mut Ui,
475 kit: &egui_pop_core::kit::Kit,
476 panel: &PanelId,
477 area: Area,
478 strip: Rect,
479 centre: Rect,
480) {
481 let width = app
482 .workbench_mut()
483 .layout
484 .flyouts
485 .get(panel)
486 .copied()
487 .unwrap_or(240.0)
488 .clamp(48.0, centre.width().max(48.0));
489 let rect = if strip.center().x <= centre.center().x {
490 Rect::from_min_size(
491 egui::pos2(strip.right(), centre.top()),
492 egui::vec2(width, centre.height()),
493 )
494 } else {
495 Rect::from_min_size(
496 egui::pos2(strip.left() - width, centre.top()),
497 egui::vec2(width, centre.height()),
498 )
499 };
500 let layer = egui::LayerId::new(
501 egui::Order::Middle,
502 Id::unique(("egui_pop.window_flyout", panel.as_str())),
503 );
504 let mut over = ui.new_child(
505 egui::UiBuilder::new()
506 .layer_id(layer)
507 .id_salt(("egui_pop.window_flyout", panel.as_str()))
508 .max_rect(rect),
509 );
510 over.painter()
511 .rect_filled(rect, 0.0, over.visuals().window_fill);
512 over.painter().rect_stroke(
513 rect,
514 0.0,
515 over.visuals().window_stroke,
516 egui::StrokeKind::Inside,
517 );
518 if !super::flyout_body(app, &mut over, kit, (area, strip.width()), panel) {
519 app.change_workbench(super::Change::Flyout(panel.clone(), false));
520 }
521}
522
523struct WindowViewer<'a> {
526 app: &'a AppHandle,
527}
528
529impl TabViewer for WindowViewer<'_> {
530 type Tab = PanelId;
531
532 fn id(&mut self, tab: &mut PanelId) -> Id {
533 Id::unique(("egui_pop.window_panel", tab.as_str()))
534 }
535
536 fn title(&mut self, tab: &mut PanelId) -> egui::WidgetText {
537 self.app.panel_title(&self.app.egui(), tab).into()
538 }
539
540 fn ui(&mut self, ui: &mut Ui, tab: &mut PanelId) {
541 self.app.show_panel(ui, tab);
542 }
543
544 fn on_tab_button(&mut self, tab: &mut PanelId, response: &egui::Response) {
545 let title = self.app.panel_title(&response.ctx, tab);
546 egui_pop_core::a11y::name(response, egui::Role::Tab, &title);
547 }
548
549 fn context_menu(&mut self, ui: &mut Ui, tab: &mut PanelId, _path: egui_stack::TabPath) {
550 panel_menu::show(ui, self.app, tab);
551 }
552
553 fn allowed_in_windows(&self, _tab: &mut PanelId) -> bool {
554 false
555 }
556}
557
558pub(crate) fn region_panel(app: &AppHandle, region: &str) -> Option<PanelId> {
562 let area = super::area_from(region.strip_prefix("region.window.")?)?;
563 let window = current_window(app);
564 let wb = app.workbench_mut();
565 let w = wb.layout.window_areas(&window)?;
566 let (_, node) = w.areas.iter().find(|(a, _)| *a == area)?;
567 first_shown(node).cloned()
568}
569
570fn first_shown(node: &Node) -> Option<&PanelId> {
572 match node {
573 Node::Tabs { panels, active } => panels.get(*active).or(panels.first()),
574 Node::Split { a, b, .. } => first_shown(a).or_else(|| first_shown(b)),
575 Node::Grid { children, .. } => children.iter().find_map(first_shown),
576 }
577}
578
579pub fn panels_by_window(app: &AppHandle) -> HashMap<String, Vec<(Area, Vec<PanelId>)>> {
582 let wb = app.workbench_mut();
583 wb.layout
584 .windows
585 .iter()
586 .map(|w| {
587 let areas = (w.areas.iter())
588 .map(|(a, n)| (*a, n.panels().into_iter().cloned().collect()))
589 .collect();
590 (w.window.clone(), areas)
591 })
592 .collect()
593}