egui_stack 0.29.1

Docking system for egui, continuing egui_dock
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! egui_stack's points on an application's bus ([bus-contract](https://docs.rs/bus-contract)),
//! with the `bus` feature: see [`DockSpace::with_bus`].
//!
//! The points are prefixed by the crate that declares them, `stack.`, so that egui_stack and
//! the application's other libraries share one bus:
//!
//! | Point | Kind | Input → value |
//! |---|---|---|
//! | [`stack.dock.drop`](DockDrop) | request, fail-closed | [`DropAsk`] → `()`; a refusal vetoes the drop |
//! | [`stack.layout.changed`](LayoutChanged) | event | [`LayoutChange`] |
//! | [`stack.window.detached`](WindowDetached) | event | [`DetachedInfo`] |
//! | [`stack.window.close`](WindowClose) | request, fails open | [`CloseAsk`] → [`ClosePolicy`] |
//! | [`stack.window.closed`](WindowClosed) | event | [`ClosedInfo`] |
//! | [`stack.window.repaired`](WindowRepaired) | event | [`RepairedInfo`] |
//!
//! Payloads are plain `Send + Sync` values: tabs are named by the key function given to
//! [`DockSpace::with_bus`], never passed as the application's tab type.
//!
//! - `stack.dock.drop` is asked when a dragged tab's destination changes and again at release,
//!   never once per frame; given a bus, it replaces
//!   [`TabViewer::dock_drop_allowed`](crate::TabViewer::dock_drop_allowed). A listener that
//!   fails refuses the drop (fail-closed).
//! - `stack.window.close` starts from the viewer's
//!   [`close_policy`](crate::TabViewer::close_policy); its listeners may change it. A listener
//!   that fails, or refuses, gives [`ClosePolicy::default`] (fails open), so a broken listener
//!   never keeps a window from closing.

use std::fmt;
use std::sync::{Arc, Mutex};

pub use bus_contract;
use bus_contract::{Bus, Point, PointDecl, PointKind, declare_all};

pub use crate::floats::ClosePolicy;
use crate::{DockSpace, Split};

/// `stack.dock.drop`: a tab, or a group, is about to be dropped. A listener refusing it
/// ([`HookError::refuse`](bus_contract::HookError::refuse)) vetoes the drop, its reason shown on
/// the preview. Fail-closed.
#[derive(Debug)]
pub struct DockDrop;

impl Point for DockDrop {
    const ID: &'static str = "stack.dock.drop";
    const KIND: PointKind = PointKind::Request;
    type Input = DropAsk;
    type Value = ();
}

/// `stack.layout.changed`: the layout or the docks changed.
#[derive(Debug)]
pub struct LayoutChanged;

impl Point for LayoutChanged {
    const ID: &'static str = "stack.layout.changed";
    const KIND: PointKind = PointKind::Event;
    type Input = LayoutChange;
    type Value = ();
}

/// `stack.window.detached`: a float opened from a tab or a group moved out of a dock.
#[derive(Debug)]
pub struct WindowDetached;

impl Point for WindowDetached {
    const ID: &'static str = "stack.window.detached";
    const KIND: PointKind = PointKind::Event;
    type Input = DetachedInfo;
    type Value = ();
}

/// `stack.window.close`: the user closes a float; the value is what becomes of its tabs.
/// Fails open to [`ClosePolicy::default`].
#[derive(Debug)]
pub struct WindowClose;

impl Point for WindowClose {
    const ID: &'static str = "stack.window.close";
    const KIND: PointKind = PointKind::Request;
    type Input = CloseAsk;
    type Value = ClosePolicy;
}

/// `stack.window.closed`: a float closed.
#[derive(Debug)]
pub struct WindowClosed;

impl Point for WindowClosed {
    const ID: &'static str = "stack.window.closed";
    const KIND: PointKind = PointKind::Event;
    type Input = ClosedInfo;
    type Value = ();
}

/// `stack.window.repaired`: a float was brought back onto a screen, or docked back when its
/// screen went.
#[derive(Debug)]
pub struct WindowRepaired;

impl Point for WindowRepaired {
    const ID: &'static str = "stack.window.repaired";
    const KIND: PointKind = PointKind::Event;
    type Input = RepairedInfo;
    type Value = ();
}

/// egui_stack's points, readable before anything is built; [`DockSpace::with_bus`] declares
/// them ([`declare_all`]).
pub const POINTS: &[PointDecl] = &[
    PointDecl::of::<DockDrop>(
        "A dragged tab or group is about to be dropped; a refusal vetoes it.",
    )
    .fail_closed(),
    PointDecl::of::<LayoutChanged>("The layout or the docks changed."),
    PointDecl::of::<WindowDetached>("A float opened from a tab or a group moved out of a dock."),
    PointDecl::of::<WindowClose>("A float is closing: what becomes of its tabs."),
    PointDecl::of::<WindowClosed>("A float closed."),
    PointDecl::of::<WindowRepaired>("A float was brought back onto a screen, or docked back."),
];

/// Where a dragged tab would go, for [`DockDrop`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DropTarget {
    /// A new float.
    NewWindow,
    /// An empty dock, as a whole.
    EmptyDock,
    /// After a leaf's tabs.
    Append,
    /// Into a leaf's tabs, at this index.
    Insert(usize),
    /// Beside a leaf, splitting it.
    Split(Split),
}

/// The input of [`DockDrop`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropAsk {
    /// The tabs moved, by the space's key function, in order.
    pub tabs: Vec<String>,
    /// Whether a whole group (a leaf and all its tabs) moves.
    pub group: bool,
    /// The dock they leave; `None` for a legacy window.
    pub from: Option<String>,
    /// The dock they enter; `None` for a new float or a legacy window.
    pub to: Option<String>,
    /// Whether they leave a dock a float shows.
    pub from_float: bool,
    /// Whether they enter a dock a float shows.
    pub to_float: bool,
    /// Where in the destination.
    pub target: DropTarget,
    /// The layout zone they are dropped in: the folded zone whose strip, or the collapsed zone
    /// whose restore band, they are released on (the zone
    /// [`DockSpace::take_unfolds`](crate::DockSpace::take_unfolds) reports), else the zone
    /// holding the dock they enter, as [`DockSpace::bind`](crate::DockSpace::bind) last read it.
    /// `None` for a new float, or for a dock no bound layout holds.
    pub zone: Option<String>,
}

/// What changed, for [`LayoutChanged`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Change {
    /// A zone was resized.
    Resized,
    /// A zone went back to its default size.
    Reset,
    /// A zone folded.
    Folded,
    /// A zone unfolded.
    Unfolded,
    /// The solver folded a zone, short of room.
    AutoFolded,
    /// A zone the solver had folded came back.
    AutoUnfolded,
    /// A folded zone's strip was clicked.
    StripClicked,
    /// A zone opened over its neighbour from its strip.
    OpenedOver,
    /// A zone opened over from its auto-folded strip closed, back to its automatic state.
    ClosedOver,
    /// A flyout asked to close.
    FlyoutClosed,
    /// A flyout was resized.
    FlyoutResized,
    /// A tab or a group moved between docks, or inside one.
    TabMoved,
    /// A float opened from a tab or a group moved out.
    Detached,
    /// A float was moved or resized by the user.
    FloatMoved,
    /// A float closed.
    FloatClosed,
    /// A float was brought back onto a screen.
    FloatRepaired,
}

/// The input of [`LayoutChanged`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LayoutChange {
    /// What changed.
    pub change: Change,
    /// The zone, or the flyout's key, if a zone changed. For [`Change::TabMoved`], the zone the
    /// tab or the group was dropped in, as [`DropAsk::zone`] names it.
    pub zone: Option<String>,
    /// The dock, if a dock changed (the one a tab entered).
    pub dock: Option<String>,
    /// The float's key, if a float changed.
    pub float: Option<String>,
}

impl LayoutChange {
    /// The change a [`LayoutArea`](crate::layout::LayoutArea) reported.
    pub fn of(event: &crate::layout::LayoutEvent) -> Self {
        use crate::layout::LayoutEvent;
        let (change, zone) = match event {
            LayoutEvent::Resized { zone, .. } => (Change::Resized, zone.0.clone()),
            LayoutEvent::Reset { zone } => (Change::Reset, zone.0.clone()),
            LayoutEvent::Folded { zone } => (Change::Folded, zone.0.clone()),
            LayoutEvent::Unfolded { zone } => (Change::Unfolded, zone.0.clone()),
            LayoutEvent::FlyoutClosed { key } => (Change::FlyoutClosed, key.clone()),
            LayoutEvent::FlyoutResized { key, .. } => (Change::FlyoutResized, key.clone()),
            LayoutEvent::AutoFolded { zone } => (Change::AutoFolded, zone.0.clone()),
            LayoutEvent::AutoUnfolded { zone } => (Change::AutoUnfolded, zone.0.clone()),
            LayoutEvent::StripClicked { zone, .. } => (Change::StripClicked, zone.0.clone()),
            LayoutEvent::OpenedOver { zone } => (Change::OpenedOver, zone.0.clone()),
            LayoutEvent::ClosedOver { zone } => (Change::ClosedOver, zone.0.clone()),
        };
        let mut change = Self::new(change);
        change.zone = Some(zone);
        change
    }

    /// A change `change`, naming nothing yet.
    pub fn new(change: Change) -> Self {
        Self {
            change,
            zone: None,
            dock: None,
            float: None,
        }
    }
}

/// The input of [`WindowDetached`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DetachedInfo {
    /// The float's key.
    pub key: String,
    /// The dock it shows.
    pub dock: String,
    /// Its tabs, by the space's key function.
    pub tabs: Vec<String>,
    /// Whether it is a native window ([`FloatHost::Native`](crate::layout::FloatHost::Native)).
    pub native: bool,
    /// The screen it opened on, when known.
    pub screen: Option<String>,
}

/// The input of [`WindowClose`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CloseAsk {
    /// The float's key.
    pub key: String,
    /// The dock it shows.
    pub dock: String,
    /// Its tabs, by the space's key function.
    pub tabs: Vec<String>,
    /// The dock each tab came from, when recorded ([`TabOrigin`](crate::TabOrigin)).
    pub origins: Vec<Option<String>>,
}

/// The input of [`WindowClosed`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ClosedInfo {
    /// The float's key.
    pub key: String,
    /// The dock it showed.
    pub dock: String,
    /// The policy applied; `None` when it closed because its dock emptied or went.
    pub policy: Option<ClosePolicy>,
    /// Each tab moved, by the space's key function, and the dock it went to.
    pub moved: Vec<(String, String)>,
}

/// The input of [`WindowRepaired`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RepairedInfo {
    /// The float's key.
    pub key: String,
    /// The screen it was on, if it named one.
    pub from: Option<String>,
    /// The screen it is on now; `None` when it docked back.
    pub to: Option<String>,
}

/// A space's bus and how it names tabs.
pub(crate) struct SpaceBus<Tab> {
    pub(crate) bus: Arc<dyn Bus>,
    pub(crate) key: fn(&Tab) -> String,
    /// The verdicts of `stack.dock.drop` asked since the last release, by ask: a destination
    /// is asked once while hovered, not once per frame.
    verdicts: Verdicts,
}

/// The verdicts of `stack.dock.drop` kept: each ask, and its refusal's reason.
type Verdicts = Arc<Mutex<Vec<(DropAsk, Option<String>)>>>;

impl<Tab> Clone for SpaceBus<Tab> {
    fn clone(&self) -> Self {
        Self {
            bus: self.bus.clone(),
            key: self.key,
            verdicts: self.verdicts.clone(),
        }
    }
}

impl<Tab> fmt::Debug for SpaceBus<Tab> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SpaceBus").finish_non_exhaustive()
    }
}

impl<Tab> SpaceBus<Tab> {
    /// Asks `stack.dock.drop`: the refusal's reason (an empty one when it gave none), or `None`
    /// when allowed. Asked again only when `fresh` (a release) or for an ask not asked since the
    /// last release.
    pub(crate) fn drop_refusal(&self, ask: DropAsk, fresh: bool) -> Option<String> {
        if !fresh
            && let Ok(verdicts) = self.verdicts.lock()
            && let Some((_, verdict)) = verdicts.iter().find(|(asked, _)| *asked == ask)
        {
            return verdict.clone();
        }
        let out = self.bus.alter::<DockDrop>(ask.clone(), ());
        let verdict = out.refused.map(|refusal| refusal.reason);
        if let Ok(mut verdicts) = self.verdicts.lock() {
            verdicts.retain(|(asked, _)| *asked != ask);
            verdicts.push((ask, verdict.clone()));
        }
        verdict
    }

    /// Forgets the verdicts asked: a drag ended.
    pub(crate) fn forget_verdicts(&self) {
        if let Ok(mut verdicts) = self.verdicts.lock() {
            verdicts.clear();
        }
    }

    /// Asks `stack.window.close`, starting from `policy`; a failure or a refusal gives the
    /// default.
    pub(crate) fn close_policy(&self, ask: CloseAsk, policy: ClosePolicy) -> ClosePolicy {
        let out = self.bus.alter::<WindowClose>(ask, policy);
        if out.failures.is_empty() && out.refused.is_none() {
            out.value
        } else {
            ClosePolicy::default()
        }
    }

    /// Emits the event `P`.
    pub(crate) fn emit<P: Point<Value = ()>>(&self, input: P::Input) {
        let _ = self.bus.alter::<P>(input, ());
    }
}

impl<Tab> DockSpace<Tab> {
    /// Gives the space the application's bus: egui_stack's points ([`POINTS`]) are declared on
    /// it, the drop veto and the close policy are asked through it, and the layout and window
    /// events are emitted on it. `key` names a tab in the points' payloads (a stable id, never
    /// the tab itself).
    ///
    /// Given a bus, `stack.dock.drop` replaces
    /// [`TabViewer::dock_drop_allowed`](crate::TabViewer::dock_drop_allowed). The events are
    /// also kept for [`take_float_events`](Self::take_float_events).
    #[must_use]
    pub fn with_bus(mut self, bus: Arc<dyn Bus>, key: fn(&Tab) -> String) -> Self {
        self.set_bus(bus, key);
        self
    }

    /// Gives the space the application's bus; see [`with_bus`](Self::with_bus). Points already
    /// declared on it (another space) are kept.
    pub fn set_bus(&mut self, bus: Arc<dyn Bus>, key: fn(&Tab) -> String) {
        // Declaring twice is refused: a second space on the same bus shares the points.
        let _ = declare_all(&*bus, POINTS);
        self.bus = Some(SpaceBus {
            bus,
            key,
            verdicts: Arc::default(),
        });
    }

    /// The bus given with [`with_bus`](Self::with_bus), if any.
    pub fn bus(&self) -> Option<&Arc<dyn Bus>> {
        self.bus.as_ref().map(|bus| &bus.bus)
    }

    /// Emits `stack.layout.changed`, when the space has a bus.
    pub(crate) fn emit_change(&self, change: LayoutChange) {
        if let Some(bus) = &self.bus {
            bus.emit::<LayoutChanged>(change);
        }
    }
}