Skip to main content

egui_pop_api/bus/
layout.rs

1//! The layout changed, on the bus (ADR 0029, "Panels and layout").
2//!
3//! The workbench's layout (its areas, tabs and splits, detached and
4//! floating panels, closed and folded areas) changes in a few ways: a
5//! workbench step (a panel docked, detached, floated, moved, shown or
6//! hidden, an area folded, a flyout resized), a layout put in
7//! ([`AppHandle::set_layout`]) or repaired against panels declared again,
8//! a gesture in a dock (a tab moved among its tabs, a split resized), a
9//! palette or a detached window moved or resized. Each of them notes the
10//! change ([`AppHandle::note_layout`]); none says it.
11//!
12//! The main window's pass says it, **once**, as `pop.layout.changed`
13//! ([`LayoutChanged`], a [`LayoutChange`] naming its causes), in
14//! [`AppHandle::settle_layout`], the one place that does:
15//!
16//! - not while a gesture holds (a button down in the main window, a tab
17//!   or a palette dragged, a palette resized): a drag in progress says
18//!   nothing until it is let go;
19//! - a window's or a palette's place, which follows the system's moves
20//!   with no button egui sees, once it stayed still for [`SETTLE`];
21//! - only when the layout differs from the one said, loaded or saved
22//!   last (a step that changed nothing is not a change).
23//!
24//! A button let go or a key pressed in any window is noted too: what a
25//! dock changed by itself is read back from it then, and said if it
26//! differs; nothing compares the layout on a pass where nobody did
27//! anything.
28//!
29//! egui-pop's listener, local: [`LAYOUT_SAVE`] saves the layout to the
30//! document its host names, through the `layout.save` step. An
31//! application keeping a copy of the layout elsewhere listens after it.
32
33use bus_contract::{Point, PointId, PointKind};
34use egui::Context;
35use serde::Serialize;
36
37use super::emit_with;
38use crate::app::AppHandle;
39
40/// What changed the layout: the workbench step's id (`workbench.move`,
41/// `workbench.detach`, ...), `layout.set` (a layout put in),
42/// `layout.repair` (repaired against the panels declared),
43/// `pop.window.place` (a detached window moved or resized),
44/// `palette.place` (a palette following the window's edges), `input`
45/// (a button let go or a key pressed: what a dock changed).
46#[derive(Clone, Debug, Default, PartialEq, Serialize)]
47#[non_exhaustive]
48pub struct LayoutChange {
49    /// Its causes since the last time, each once, in the order noted.
50    pub causes: Vec<String>,
51}
52
53/// The layout changed (`pop.layout.changed`), said once per real change,
54/// once the gesture that made it ended.
55#[derive(Debug)]
56pub struct LayoutChanged;
57impl Point for LayoutChanged {
58    const KIND: PointKind = PointKind::Event;
59    const ID: PointId = PointId::new("pop.layout.changed");
60    type Input = LayoutChange;
61    type Value = ();
62}
63
64/// The layout points, in the order [`super::order_dump`] prints them.
65pub const LAYOUT_POINTS: [&str; 1] = [LayoutChanged::ID.as_str()];
66
67/// egui-pop's listener saving the layout to the host's document (the
68/// `layout.save` step). An application's copy of the layout runs after
69/// it.
70pub const LAYOUT_SAVE: &str = "pop.layout.save";
71
72/// How long a place followed from the system (a window, a palette) stays
73/// still before its change is said, in seconds.
74pub const SETTLE: f64 = 0.3;
75
76/// Changes noted and not said yet.
77#[derive(Debug, Default)]
78pub(crate) struct Unsaid {
79    causes: Vec<String>,
80    /// When a place followed from the system last changed: said
81    /// [`SETTLE`] after.
82    moving: Option<f64>,
83}
84
85/// Causes that follow the system's moves, with no button egui sees.
86fn follows_the_system(cause: &str) -> bool {
87    matches!(cause, "window.place" | "palette.place")
88}
89
90impl AppHandle {
91    /// Notes that `cause` may have changed the layout: the main window's
92    /// next pass says it, once, if it did ([`AppHandle::settle_layout`]).
93    pub(crate) fn note_layout(&self, cause: &str) {
94        let ctx = self.egui();
95        let now = egui_pop_core::motion::now(&ctx);
96        {
97            let mut wb = self.workbench_mut();
98            let unsaid = wb.unsaid.get_or_insert_with(Unsaid::default);
99            if !unsaid.causes.iter().any(|c| c == cause) {
100                unsaid.causes.push(cause.to_string());
101            }
102            if follows_the_system(cause) {
103                unsaid.moving = Some(now);
104            }
105        }
106        ctx.request_repaint();
107    }
108
109    /// The layout as it stands is the one on disk (loaded or saved): no
110    /// change noted until now is said.
111    pub(crate) fn layout_said_now(&self) {
112        let now = self.saved_layout();
113        let mut wb = self.workbench_mut();
114        wb.said = Some(now);
115        wb.unsaid = None;
116    }
117
118    /// Says `pop.layout.changed` once for the changes noted, when no gesture
119    /// holds and the layout differs from the one said last: its listeners
120    /// run now, on this thread. Then notes a button let go or a key
121    /// pressed in the main window, said at the next pass, once the pass
122    /// that follows it drew what it changed. Called once per main
123    /// window's pass.
124    pub(crate) fn settle_layout(&self, ctx: &Context) {
125        let first = self.workbench_mut().said.is_none();
126        if first {
127            // What the application started with is not a change.
128            self.layout_said_now();
129            return;
130        }
131        self.say_layout(ctx);
132        if ctx.input(|i| {
133            i.pointer.any_released()
134                || i.events
135                    .iter()
136                    .any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))
137        }) {
138            self.note_layout("input");
139        }
140    }
141
142    fn say_layout(&self, ctx: &Context) {
143        let held = ctx.input(|i| i.pointer.any_down()) || {
144            let wb = self.workbench_mut();
145            wb.dragging.is_some() || wb.palette_drag.is_some() || wb.palette_resize.is_some()
146        };
147        let now = egui_pop_core::motion::now(ctx);
148        let causes = {
149            let mut wb = self.workbench_mut();
150            let Some(unsaid) = wb.unsaid.as_ref() else {
151                return;
152            };
153            if held {
154                return;
155            }
156            if let Some(at) = unsaid.moving
157                && now < at + SETTLE
158            {
159                ctx.request_repaint_after(std::time::Duration::from_secs_f64(
160                    (at + SETTLE - now).max(0.05),
161                ));
162                return;
163            }
164            wb.unsaid.take().map(|u| u.causes).unwrap_or_default()
165        };
166        let layout = self.saved_layout();
167        {
168            let mut wb = self.workbench_mut();
169            if wb.said.as_ref() == Some(&layout) {
170                return;
171            }
172            wb.said = Some(layout);
173        }
174        emit_with::<LayoutChanged>(self, LayoutChange { causes }, ());
175    }
176}