Skip to main content

egui_pop_api/
palettes.rs

1//! Palettes: toolboxes, colour palettes, navigators floating over the
2//! interface (not the command palette, [`crate::palette`]).
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! A palette is a panel ([`PanelSpec::palette`]) placed floating instead
8//! of docked: one model, two placements. It opens floating, is dragged by
9//! its header band ([`egui_pop_core::band`], the movable dialogs' band),
10//! clamped inside the workbench, snapping to the workbench's edges and to
11//! the other palettes within the `palette.magnet` token. Dropped on an
12//! edge of the workbench, it is anchored there ([`anchor_of`]) and keeps
13//! its distance to it as the window is resized ([`anchored_pos`]); dragged
14//! away, it no longer is. Dropped on a
15//! side or bottom area (or a closed one's edge, with the workbench's drop
16//! hint) with the dock keys held, it docks there; a docked floatable
17//! panel floats again from its tab menu (Float).
18//!
19//! **Moving or docking** (`docs/design/drag-move-vs-dock.md`). By
20//! default a plain drag only moves a palette: the drop targets (an area,
21//! another palette's group) show and take it only while the dock keys
22//! are held (`gesture.workbench.dock`, `Ctrl` and the drag, Cmd on
23//! macOS, rebindable in the shortcuts editor), read every pass of the
24//! drag, so pressing or releasing them mid-drag counts. The
25//! `input.dock_drag` setting ([`crate::pointer::SETTING_DOCK_DRAG`]; its
26//! default the application's, `AppBuilder::dock_drag`, else the pointer
27//! profile's) picks the mode ([`DockDrag`]): `modifier-docks` (the
28//! default), `modifier-floats` (a plain drag docks, the keys keep it
29//! floating: Photoshop's profile) or `dwell` (docking arms once the
30//! pointer rests on a target for [`DWELL`]). Whether the targets are
31//! armed shows in [`GroupHint::armed`] and the workbench's
32//! `DropHint::armed`; only armed targets are drawn. While a palette is
33//! dragged over a target, a one-line hint says how to dock or not
34//! ([`drag_hint`]): in the status bar, or under the pointer without one.
35//! A floating panel's menu docks it too (Dock in), for a pointer with no
36//! keyboard. Its band carries Close, Roll up (down to the band)
37//! and Pin (kept in place, in sight and opaque); a double click on the
38//! band rolls it up or down. A right click on its title, or on a tab of
39//! its group, opens the panel menu a docked tab opens
40//! ([`crate::workbench::panel_menu`]): Detach into a window, Move to
41//! group, Dock back (where it floated from), Close.
42//!
43//! **Never modal.** A palette never blocks the interface: anything that
44//! must be answered first is a dialog ([`crate::dialogs`]). It takes the
45//! keyboard only when clicked into; Escape there gives it back to the
46//! panel that had it.
47//!
48//! **Behaviour.** The `palettes.toggle` command (Tab, rebindable) hides
49//! and shows the unpinned palettes. Tab is the toggle only while some
50//! panel floats, no widget has the keyboard and no overlay is open:
51//! otherwise it moves the keyboard to the next widget, as always. While a stroke is in progress
52//! ([`set_stroke`]) the palettes fade when the `palettes.fade_on_stroke`
53//! setting is on; `palettes.idle_opacity` makes them translucent while
54//! the pointer is elsewhere. `palettes.reset` puts them back where they
55//! open first, rolled down and sized by their content.
56//!
57//! **Groups.** Palettes float in groups ([`FloatingGroup`]), a palette
58//! alone being a group of one. A palette dropped on another one's top or
59//! bottom quarter ([`join_at`], with the drop hint the tabs use) stacks
60//! above or below it, in a column where each keeps its own band and
61//! roll-up. The group's band (over its members') drags, pins and anchors
62//! the whole group, and docks every member over an area, as tabs
63//! (floating one of them again gives the group back); a member's own
64//! band drags it out of the group. Dropped on the middle of another
65//! palette, a palette joins its group as a tab: the group's band then
66//! holds the tabs, and the shown member its own band.
67//!
68//! **Docking conventions** (as in Photoshop, Krita, GIMP, Qt docks and
69//! VS Code). Close group is an entry of the menu on the group's band,
70//! not a button on it. A tab dragged out of its tabs comes out of them,
71//! alone or into the palette it is dropped on. Closing the shown tab
72//! shows its right neighbour, or its left one at the end. A palette
73//! dropped on the top or bottom edge of a group of tabs stacks beside
74//! them and the tabs stay tabs: a stack's member may be a tab group
75//! ([`Member::tabs`]), one level deep, whose band drags it out whole.
76//!
77//! **Sizes.** A palette is sized by its content until the user resizes
78//! it: each of its edges and corners drag its size (a left or top edge
79//! keeping the opposite one where it is) (the `palette.grip` token's width), kept between the
80//! `palette.min-width` and `palette.max-width` tokens (and its panels'
81//! own least width), `palette.min-height` and `palette.max-height`, and
82//! inside the workbench. The size is the group's
83//! ([`FloatingGroup::size`], saved in the layout): a group keeps it as
84//! palettes join it, a palette coming out of it is sized by its content
85//! again. Its content scrolls when it is taller than the room left; a
86//! rolled-up palette keeps its width and only its band's height. A
87//! double click on an edge gives the content its size back. Resized
88//! against an edge of the workbench, a palette is anchored there as when
89//! it is dropped.
90//!
91//! **Steps** (ADR 0011): `palette.open` (`{panel}`), `palette.float`
92//! (`{panel, pos}`), `palette.dock` (`{panel, area}`, `group: true` for
93//! the whole group), `palette.move` (`{panel, pos}`, once a drag is
94//! dropped), `palette.resize` (`{panel, size}`, `size` being
95//! `[width, height]` or `null` for the content's, once an edge is
96//! dropped; with `pos` too when a left or top edge moved it), `palette.roll` (`{panel, rolled}`), `palette.pin`
97//! (`{panel, pinned}`), `palette.group` (`{panels, into, at}`),
98//! `palette.ungroup` (`{panel, pos}`, `tabs: true` for a nested tab group
99//! whole) and `palette.close_group` (`{panel}`); `pos` is the top-left
100//! corner in points from the workbench's top-left. Each done change is
101//! published as `palette.opened`, `palette.floated`, `palette.docked`,
102//! `palette.moved`, `palette.resized`, `palette.rolled`, `palette.pinned`,
103//! `palette.grouped`, `palette.ungrouped` or `palette.group_closed`.
104//!
105//! Not built yet: a palette outside the main window (a native utility
106//! window through egui's viewports).
107//!
108//! [`PanelSpec::palette`]: egui_pop_model::panels::PanelSpec::palette
109
110use std::collections::BTreeMap;
111
112use egui::{Id, Key, Modifiers, Pos2, Rect, Ui, Vec2};
113use egui_pop_core::band::{self, BandStyle};
114use egui_pop_core::focus;
115use egui_pop_core::icon::Icon;
116use egui_pop_core::kit::{Glyph, Kit, KitCx, Part, State};
117use egui_pop_core::lock;
118use egui_pop_core::strings;
119use egui_pop_core::theme::Tokens;
120use egui_pop_core::ui::UiPop as _;
121use egui_pop_core::widgets;
122use egui_pop_model::commands::CommandSpec;
123use egui_pop_model::ids::{CommandId, PanelId, SettingId, StepId};
124use egui_pop_model::keymap::BindOptions;
125use egui_pop_model::keymap::{Button, Pointer};
126use egui_pop_model::layout::{Anchor, AnchorEdge, Arrangement, FloatingGroup, Join, Member};
127use egui_pop_model::panels::{Area, PanelKind};
128use egui_pop_model::pointer::{DockDrag, PointerMap, SCOPE_PALETTE, gesture};
129use egui_pop_model::values::Descriptor;
130use serde_json::{Value as Json, json};
131
132use crate::app::AppHandle;
133use crate::steps::{Outcome, StepSpec};
134use crate::strings as txt;
135use crate::workbench::Change;
136use crate::{Ctx, CtxError};
137
138/// A palette opens (`{panel}`).
139pub const STEP_OPEN: StepId = StepId::from_static("palette.open");
140/// A panel floats over the interface (`{panel, pos}`).
141pub const STEP_FLOAT: StepId = StepId::from_static("palette.float");
142/// A floating panel docks in an area (`{panel, area}`).
143pub const STEP_DOCK: StepId = StepId::from_static("palette.dock");
144/// A floating panel is moved: dropped after a drag, reset
145/// (`{panel, pos}`).
146pub const STEP_MOVE: StepId = StepId::from_static("palette.move");
147/// A floating panel's group is resized, once an edge is dropped, or
148/// sized by its content again (`{panel, size}`, `size` being
149/// `[width, height]` in points or `null`; with `pos`, the place too,
150/// for a left or top edge dragged).
151pub const STEP_RESIZE: StepId = StepId::from_static("palette.resize");
152/// A floating panel rolls up or down (`{panel, rolled}`).
153pub const STEP_ROLL: StepId = StepId::from_static("palette.roll");
154/// A floating panel is pinned or unpinned (`{panel, pinned}`).
155pub const STEP_PIN: StepId = StepId::from_static("palette.pin");
156/// Floating panels join another one's group (`{panels, into, at}`, `at`
157/// being `above`, `below` or `tab`).
158pub const STEP_GROUP: StepId = StepId::from_static("palette.group");
159/// A floating panel comes out of its group, alone (`{panel, pos}`); with
160/// `tabs: true`, the tab group it is a tab of comes out of its stack
161/// whole.
162pub const STEP_UNGROUP: StepId = StepId::from_static("palette.ungroup");
163/// Every palette of a floating panel's group closes (`{panel}`): the
164/// group band's menu, Close group.
165pub const STEP_CLOSE_GROUP: StepId = StepId::from_static("palette.close_group");
166
167/// Hides or shows the unpinned palettes (Tab).
168pub const CMD_TOGGLE: CommandId = CommandId::from_static("palettes.toggle");
169/// Puts the palettes back where they first open.
170pub const CMD_RESET: CommandId = CommandId::from_static("palettes.reset");
171
172/// The setting: palettes fade while a stroke is in progress.
173pub const SETTING_FADE: SettingId = SettingId::from_static("palettes.fade_on_stroke");
174/// The setting: how opaque a palette is while the pointer is elsewhere.
175pub const SETTING_IDLE_OPACITY: SettingId = SettingId::from_static("palettes.idle_opacity");
176
177/// The context key saying a stroke is in progress ([`set_stroke`]).
178pub const CONTEXT_STROKE: &str = "strokeActive";
179/// The context key saying the palettes are hidden (`palettes.toggle`).
180pub const CONTEXT_HIDDEN: &str = "palettesHidden";
181/// The context key saying some panel floats (shown or hidden): only
182/// then is Tab the palettes' toggle.
183pub const CONTEXT_FLOATING: &str = "palettesFloat";
184
185/// How long the pointer rests on a target before a drag in the `dwell`
186/// mode ([`DockDrag::Dwell`]) docks there, in seconds.
187pub const DWELL: f64 = 0.5;
188
189/// What is left of a palette while a stroke is in progress.
190const STROKE_OPACITY: f32 = 0.15;
191
192/// Says a stroke (a brush, a drag on the canvas) starts or ends: the
193/// palettes fade meanwhile when the `palettes.fade_on_stroke` setting is
194/// on.
195pub fn set_stroke(app: &AppHandle, on: bool) {
196    app.set_context(CONTEXT_STROKE, if on { "true" } else { "false" });
197    app.egui().request_repaint();
198}
199
200/// Whether the unpinned palettes are hidden (`palettes.toggle`).
201pub fn hidden(app: &AppHandle) -> bool {
202    app.context().get(CONTEXT_HIDDEN) == "true"
203}
204
205/// Hides or shows the unpinned palettes.
206pub fn set_hidden(app: &AppHandle, hidden: bool) {
207    app.set_context(CONTEXT_HIDDEN, if hidden { "true" } else { "false" });
208    app.publish(
209        "egui_pop",
210        None,
211        "palette.toggled",
212        json!({ "hidden": hidden }),
213    );
214    app.egui().request_repaint();
215}
216
217/// The palettes' steps, settings and commands, as the framework declares
218/// them.
219pub(crate) fn declare(ctx: &mut Ctx<'_>) -> Result<(), CtxError> {
220    let panel = json!({ "panel": "app.tools" });
221    for (step, about, args) in [
222        (
223            STEP_OPEN,
224            "A palette opens, floating (`panel`).",
225            panel.clone(),
226        ),
227        (
228            STEP_FLOAT,
229            "A panel floats over the interface (`panel`, `pos`).",
230            json!({ "panel": "app.tools", "pos": [16.0, 16.0] }),
231        ),
232        (
233            STEP_DOCK,
234            "A floating panel docks in an area (`panel`, `area`); with `group`, every member of its group does, as tabs.",
235            json!({ "panel": "app.tools", "area": "start_side" }),
236        ),
237        (
238            STEP_GROUP,
239            "Floating panels join another one's group, above it, below it or as a tab (`panels`, `into`, `at`).",
240            json!({ "panels": ["app.colours"], "into": "app.tools", "at": "below" }),
241        ),
242        (
243            STEP_UNGROUP,
244            "A floating panel comes out of its group, alone at a place (`panel`, `pos`); with `tabs`, the tab group it is a tab of comes out of its stack whole.",
245            json!({ "panel": "app.colours", "pos": [16.0, 300.0] }),
246        ),
247        (
248            STEP_CLOSE_GROUP,
249            "Every palette of a floating panel's group closes (`panel`).",
250            panel.clone(),
251        ),
252        (
253            STEP_MOVE,
254            "A floating panel is moved, once dropped (`panel`, `pos`).",
255            json!({ "panel": "app.tools", "pos": [120.0, 40.0] }),
256        ),
257        (
258            STEP_RESIZE,
259            "A floating panel's group is resized, once an edge is dropped (`panel`, `size` as `[width, height]`, or `null` for its content's size).",
260            json!({ "panel": "app.tools", "size": [240.0, 320.0] }),
261        ),
262        (
263            STEP_ROLL,
264            "A floating panel rolls up to its band, or down (`panel`, `rolled`).",
265            json!({ "panel": "app.tools", "rolled": true }),
266        ),
267        (
268            STEP_PIN,
269            "A floating panel is pinned in place, or unpinned (`panel`, `pinned`).",
270            json!({ "panel": "app.tools", "pinned": true }),
271        ),
272    ] {
273        ctx.step(StepSpec::new(step, about).args(args))?;
274    }
275    ctx.setting(
276        SETTING_FADE,
277        Descriptor::bool("Fade palettes while drawing", false)
278            .description("Palettes fade while a stroke is in progress on the canvas."),
279    )?;
280    ctx.setting(
281        SETTING_IDLE_OPACITY,
282        Descriptor::float("Palette opacity away from the pointer", 0.2, 1.0, 1.0)
283            .description(
284                "How opaque a palette is while the pointer is elsewhere; 1 keeps it opaque.",
285            )
286            .step(0.05),
287    )?;
288    ctx.command(
289        CommandSpec::new(CMD_TOGGLE, "Hide or show palettes", "View")
290            .description("Hides the palettes that are not pinned, or shows them again.")
291            .when("palettesFloat && !widgetFocus && !overlayOpen")
292            .key_with("Tab", BindOptions::global()),
293        |call| {
294            // Tab is this command here, not a move to the next widget.
295            call.app
296                .egui()
297                .memory_mut(|m| m.move_focus(egui::FocusDirection::None));
298            let now = !hidden(call.app);
299            set_hidden(call.app, now);
300            Ok(json!({ "hidden": now }))
301        },
302    )?;
303    ctx.command(
304        CommandSpec::new(CMD_RESET, "Reset palettes", "View")
305            .icon("reset")
306            .description("Puts the floating palettes back where they first open, rolled down and sized by their content."),
307        |call| {
308            reset(call.app);
309            Ok(Json::Null)
310        },
311    )?;
312    Ok(())
313}
314
315/// Puts the floating palettes back where they first open, rolled down
316/// and sized by their content,
317/// each through its steps.
318pub fn reset(app: &AppHandle) {
319    let floating: Vec<FloatingGroup> = app.workbench_mut().layout.floating.clone();
320    for (n, g) in floating.iter().enumerate() {
321        app.change_workbench(Change::MovePalette(
322            g.lead().clone(),
323            FloatingGroup::cascade(n),
324        ));
325        for m in g.members.iter().filter(|m| m.rolled) {
326            app.change_workbench(Change::Roll(m.panel.clone(), false));
327        }
328        if g.size.is_some() {
329            app.change_workbench(Change::ResizePalette(g.lead().clone(), None));
330        }
331    }
332    if hidden(app) {
333        set_hidden(app, false);
334    }
335}
336
337/// A rectangle snapped to the bounds' edges and to the others' edges
338/// (side by side or aligned) when within `magnet` of them; the nearest
339/// edge wins on each axis.
340///
341/// ```
342/// use egui::{Rect, pos2, vec2};
343/// use egui_pop_api::palettes::snap;
344///
345/// let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
346/// let r = Rect::from_min_size(pos2(7.0, 300.0), vec2(100.0, 50.0));
347/// assert_eq!(snap(r, bounds, &[], 12.0).min, pos2(0.0, 300.0));
348/// let other = Rect::from_min_size(pos2(200.0, 290.0), vec2(100.0, 80.0));
349/// let r = Rect::from_min_size(pos2(95.0, 300.0), vec2(100.0, 50.0));
350/// assert_eq!(snap(r, bounds, &[other], 12.0).max.x, 200.0);
351/// ```
352pub fn snap(rect: Rect, bounds: Rect, others: &[Rect], magnet: f32) -> Rect {
353    fn best(cur: &mut Option<f32>, d: f32, magnet: f32) {
354        if d.abs() <= magnet && cur.is_none_or(|c| d.abs() < c.abs()) {
355            *cur = Some(d);
356        }
357    }
358    let (mut dx, mut dy) = (None, None);
359    best(&mut dx, bounds.left() - rect.left(), magnet);
360    best(&mut dx, bounds.right() - rect.right(), magnet);
361    best(&mut dy, bounds.top() - rect.top(), magnet);
362    best(&mut dy, bounds.bottom() - rect.bottom(), magnet);
363    for o in others {
364        let beside = rect.top() < o.bottom() + magnet && o.top() < rect.bottom() + magnet;
365        let above = rect.left() < o.right() + magnet && o.left() < rect.right() + magnet;
366        if beside {
367            for d in [
368                o.left() - rect.right(),
369                o.right() - rect.left(),
370                o.left() - rect.left(),
371                o.right() - rect.right(),
372            ] {
373                best(&mut dx, d, magnet);
374            }
375        }
376        if above {
377            for d in [
378                o.top() - rect.bottom(),
379                o.bottom() - rect.top(),
380                o.top() - rect.top(),
381                o.bottom() - rect.bottom(),
382            ] {
383                best(&mut dy, d, magnet);
384            }
385        }
386    }
387    rect.translate(egui::vec2(dx.unwrap_or(0.0), dy.unwrap_or(0.0)))
388}
389
390/// How near a workbench edge a palette's side lies to be on it, in
391/// points: snapped there or clamped against it.
392const ON_EDGE: f32 = 0.5;
393
394/// The workbench edges a palette's `rect` lies on, within half a point:
395/// its anchor. A side off the edges (dragged away, or snapped to another
396/// palette) is not anchored; on both edges of an axis (as large as the
397/// workbench), the start wins.
398///
399/// ```
400/// use egui::{Rect, pos2, vec2};
401/// use egui_pop_api::palettes::anchor_of;
402/// use egui_pop_model::layout::AnchorEdge;
403///
404/// let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
405/// let r = Rect::from_min_size(pos2(700.0, 200.0), vec2(100.0, 50.0));
406/// let a = anchor_of(r, bounds);
407/// assert_eq!((a.x, a.y), (AnchorEdge::End, AnchorEdge::None));
408/// ```
409pub fn anchor_of(rect: Rect, bounds: Rect) -> Anchor {
410    fn axis(lo: f32, hi: f32, start: f32, end: f32) -> (AnchorEdge, f32) {
411        let (before, after) = (lo - start, end - hi);
412        if before.abs() <= ON_EDGE {
413            (AnchorEdge::Start, before.max(0.0))
414        } else if after.abs() <= ON_EDGE {
415            (AnchorEdge::End, after.max(0.0))
416        } else {
417            (AnchorEdge::None, 0.0)
418        }
419    }
420    let (x, ox) = axis(rect.left(), rect.right(), bounds.left(), bounds.right());
421    let (y, oy) = axis(rect.top(), rect.bottom(), bounds.top(), bounds.bottom());
422    Anchor {
423        x,
424        y,
425        offset: [ox, oy],
426    }
427}
428
429/// Where a palette's top-left corner goes in `bounds`: an anchored axis
430/// keeps its distance to its edge, the other keeps `pos` (from the
431/// bounds' top-left); kept inside either way.
432///
433/// ```
434/// use egui::{Rect, pos2, vec2};
435/// use egui_pop_api::palettes::anchored_pos;
436/// use egui_pop_model::layout::{Anchor, AnchorEdge};
437///
438/// let right = Anchor { x: AnchorEdge::End, ..Anchor::default() };
439/// let wider = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0));
440/// let at = anchored_pos([700.0, 200.0], vec2(100.0, 50.0), wider, &right);
441/// assert_eq!(at, pos2(900.0, 200.0));
442/// ```
443pub fn anchored_pos(pos: [f32; 2], size: Vec2, bounds: Rect, anchor: &Anchor) -> Pos2 {
444    let axis = |edge: AnchorEdge, at: f32, offset: f32, start: f32, end: f32, len: f32| match edge {
445        AnchorEdge::None => start + at,
446        AnchorEdge::Start => start + offset,
447        AnchorEdge::End => end - offset - len,
448    };
449    let x = axis(
450        anchor.x,
451        pos[0],
452        anchor.offset[0],
453        bounds.left(),
454        bounds.right(),
455        size.x,
456    );
457    let y = axis(
458        anchor.y,
459        pos[1],
460        anchor.offset[1],
461        bounds.top(),
462        bounds.bottom(),
463        size.y,
464    );
465    clamp(Pos2::new(x, y), size, bounds)
466}
467
468/// A top-left corner keeping a box of `size` inside `bounds` (at its
469/// top-left when it is larger).
470fn clamp(min: Pos2, size: Vec2, bounds: Rect) -> Pos2 {
471    let max = (bounds.max - size).max(bounds.min);
472    min.clamp(bounds.min, max)
473}
474
475fn setting_bool(app: &AppHandle, id: SettingId) -> bool {
476    lock(&app.store())
477        .get(&format!("settings/{id}"))
478        .and_then(|e| e.value.as_bool())
479        .unwrap_or(false)
480}
481
482fn setting_f32(app: &AppHandle, id: SettingId) -> Option<f32> {
483    lock(&app.store())
484        .get(&format!("settings/{id}"))
485        .and_then(|e| e.value.as_f64())
486        .map(|v| v as f32)
487}
488
489/// A palette's area id.
490pub fn area_id(panel: &PanelId) -> Id {
491    Id::unique(("egui_pop.palette", panel.as_str()))
492}
493
494/// What a palette drag holds.
495#[derive(Clone, Copy, Debug, PartialEq, Eq)]
496pub(crate) enum DragKind {
497    /// A group's band: the whole group moves.
498    Group,
499    /// A member's own band: it comes out of its group.
500    Member,
501    /// A nested tab group's band: the tab group comes out of its stack
502    /// whole.
503    Tabs,
504    /// A tab: it comes out of its tabs.
505    Tab,
506}
507
508/// A palette's band, or a tab, being dragged.
509#[derive(Clone, Debug, PartialEq)]
510pub(crate) struct PaletteDrag {
511    /// The palette dragged: its group's first member when the group's
512    /// band is, the shown tab for a nested tab group's band.
513    pub panel: PanelId,
514    /// What is dragged.
515    pub kind: DragKind,
516    /// Where the dragged palettes were when the drag started, from the
517    /// workbench's top-left.
518    pub start: [f32; 2],
519    /// Where they are now (snapped, kept inside).
520    pub pos: [f32; 2],
521    /// The pointer.
522    pub at: Pos2,
523    /// What it is over: an area it docks in, a palette it joins.
524    pub target: Option<Target>,
525    /// Since when (the input's time) it is over that target.
526    pub since: f64,
527    /// Whether a drop now docks or joins (the mode and the keys held).
528    pub armed: bool,
529}
530
531/// What a dragged palette is over.
532#[derive(Clone, Debug, PartialEq)]
533pub(crate) enum Target {
534    /// An area it docks in.
535    Area(Area),
536    /// Another palette it joins, and where.
537    Join(PanelId, Join),
538}
539
540/// The palette drag mode in force: the `input.dock_drag` setting, else
541/// the pointer profile's.
542fn mode(ctx: &egui::Context) -> DockDrag {
543    egui_pop_core::pointer::map(ctx).options.dock_drag
544}
545
546/// Whether the dock keys (`gesture.workbench.dock`) are held now.
547fn dock_keys_held(ctx: &egui::Context, map: &PointerMap) -> bool {
548    let held = ctx.input(|i| i.modifiers);
549    let chord = egui_pop_core::pointer::chord(held, Pointer::Drag(Button::Primary));
550    map.command(SCOPE_PALETTE, &chord) == Some(&gesture::WORKBENCH_DOCK)
551}
552
553/// Whether a drop now docks or joins: the dock keys held (or not, for
554/// `modifier-floats`), or the pointer resting on the target since
555/// `since` for [`DWELL`].
556fn armed_now(ctx: &egui::Context, since: Option<f64>) -> bool {
557    let map = egui_pop_core::pointer::map(ctx);
558    match map.options.dock_drag {
559        DockDrag::ModifierDocks => dock_keys_held(ctx, &map),
560        DockDrag::ModifierFloats => !dock_keys_held(ctx, &map),
561        DockDrag::Dwell => since.is_some_and(|s| ctx.input(|i| i.time) - s >= DWELL),
562    }
563}
564
565/// A drag's pass over what it is over (a group hint, else an area the
566/// workbench docks in at `at`): its target, since when, and whether it
567/// is armed. A dwell still running asks for the pass that ends it.
568fn track(
569    app: &AppHandle,
570    ctx: &egui::Context,
571    mine: Option<&PaletteDrag>,
572    hint: Option<&GroupHint>,
573    at: Pos2,
574) -> (Option<Target>, f64, bool) {
575    let target = match hint {
576        Some(h) => Some(Target::Join(h.into.clone(), h.at)),
577        None => app
578            .workbench_mut()
579            .dock_at(at, magnet(ctx))
580            .map(Target::Area),
581    };
582    let time = ctx.input(|i| i.time);
583    let since = match mine {
584        Some(x) if x.target == target => x.since,
585        _ => time,
586    };
587    let armed = armed_now(ctx, target.is_some().then_some(since));
588    if target.is_some() && !armed && mode(ctx) == DockDrag::Dwell {
589        let left = (since + DWELL - time).max(0.0);
590        ctx.request_repaint_after(std::time::Duration::from_secs_f64(left));
591    }
592    (target, since, armed)
593}
594
595/// The dock keys as the platform names them (`Ctrl`, `Cmd` on macOS):
596/// the first chord bound to `gesture.workbench.dock`'s modifiers; `None`
597/// when none is bound, or one without modifiers.
598fn dock_keys_text(ctx: &egui::Context, map: &PointerMap) -> Option<String> {
599    let dock = gesture::WORKBENCH_DOCK;
600    let c = map.chords(SCOPE_PALETTE, &dock).next()?.clone();
601    let mac = ctx.os() == egui::os::OperatingSystem::Mac;
602    let parts: Vec<&str> = [
603        (c.ctrl, if mac { "Cmd" } else { "Ctrl" }),
604        (c.alt, if mac { "Option" } else { "Alt" }),
605        (c.shift, "Shift"),
606        (c.meta, "Meta"),
607    ]
608    .into_iter()
609    .filter_map(|(on, name)| on.then_some(name))
610    .collect();
611    (!parts.is_empty()).then(|| parts.join("+"))
612}
613
614/// The hint while a palette is dragged over a target, worded after the
615/// drag mode and the keys bound to `gesture.workbench.dock` (a rebind
616/// changes it): "Hold Ctrl to dock" or "Release Ctrl to move only"
617/// (`modifier-docks`), "Hold Ctrl to move without docking"
618/// (`modifier-floats`, the keys not held), "Rest here to dock" (`dwell`,
619/// while the delay runs). `None` while no palette is dragged over a
620/// target.
621///
622/// <div class="warning">Experimental: may change in any release
623/// (docs/stability.md).</div>
624pub fn drag_hint(app: &AppHandle) -> Option<String> {
625    let drag = app.try_workbench()?.palette_drag.clone()?;
626    drag.target.as_ref()?;
627    let ctx = app.egui();
628    let map = egui_pop_core::pointer::map(&ctx);
629    let keys = || dock_keys_text(&ctx, &map);
630    let held = dock_keys_held(&ctx, &map);
631    let (key, keys) = match map.options.dock_drag {
632        DockDrag::ModifierDocks if held => (&txt::PALETTE_DRAG_RELEASE_TO_MOVE, keys()?),
633        DockDrag::ModifierDocks => (&txt::PALETTE_DRAG_HOLD_TO_DOCK, keys()?),
634        DockDrag::ModifierFloats if !held => (&txt::PALETTE_DRAG_HOLD_TO_FLOAT, keys()?),
635        DockDrag::ModifierFloats => return None,
636        DockDrag::Dwell if !drag.armed => return Some(strings::tr(&ctx, &txt::PALETTE_DRAG_REST)),
637        DockDrag::Dwell => return None,
638    };
639    Some(strings::tr_args(&ctx, key, &[("keys", &keys)]))
640}
641
642/// A palette's edge being dragged.
643#[derive(Clone, Debug, PartialEq)]
644pub(crate) struct PaletteResize {
645    /// Its group's first member.
646    pub panel: PanelId,
647    /// The group's size before the drag (`None`: its content's).
648    pub saved: Option<[f32; 2]>,
649    /// The frame drawn when the drag started.
650    pub from: Rect,
651    /// The edges dragged, on each axis.
652    pub edges: Sides,
653}
654
655/// The edges a resize drags, on each axis (x, then y): `-1` the start
656/// edge (left, top), `1` the end edge (right, bottom), `0` neither.
657pub type Sides = [i8; 2];
658
659/// A palette's frame once the edges `sides` say are dragged by `delta`
660/// from `start`: a start edge moves its side and keeps the opposite one
661/// where it is. Its size is kept between `least` and `most`, and inside
662/// `bounds`.
663///
664/// ```
665/// use egui::{Rect, pos2, vec2};
666/// use egui_pop_api::palettes::resize_rect;
667///
668/// let (least, most) = (vec2(120.0, 64.0), vec2(640.0, 900.0));
669/// let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 800.0));
670/// let start = Rect::from_min_size(pos2(300.0, 100.0), vec2(200.0, 300.0));
671/// // The left edge, 40 out: 40 wider, the right edge still.
672/// let r = resize_rect(start, vec2(-40.0, 0.0), [-1, 0], least, most, bounds);
673/// assert_eq!(r, Rect::from_min_max(pos2(260.0, 100.0), pos2(500.0, 400.0)));
674/// // Never under the least width.
675/// let r = resize_rect(start, vec2(500.0, 0.0), [-1, 0], least, most, bounds);
676/// assert_eq!((r.width(), r.right()), (120.0, 500.0));
677/// // The bottom-right corner, kept inside.
678/// let r = resize_rect(start, vec2(900.0, 25.0), [1, 1], least, most, bounds);
679/// assert_eq!(r.max, pos2(940.0, 425.0));
680/// ```
681pub fn resize_rect(
682    start: Rect,
683    delta: Vec2,
684    sides: Sides,
685    least: Vec2,
686    most: Vec2,
687    bounds: Rect,
688) -> Rect {
689    let (mut min, mut max) = (start.min, start.max);
690    for axis in 0..2 {
691        let lo = least[axis];
692        let hi = most[axis].max(lo);
693        match sides[axis] {
694            1 => {
695                let at = start.max[axis] + delta[axis];
696                let top = (min[axis] + hi).min(bounds.max[axis]).max(min[axis] + lo);
697                max[axis] = at.min(top).max(min[axis] + lo);
698            }
699            -1 => {
700                let at = start.min[axis] + delta[axis];
701                let bottom = (max[axis] - hi).max(bounds.min[axis]).min(max[axis] - lo);
702                min[axis] = at.max(bottom).min(max[axis] - lo);
703            }
704            _ => {}
705        }
706    }
707    Rect::from_min_max(min, max)
708}
709
710/// The largest size the `palette.max-width` and `palette.max-height`
711/// tokens give a palette.
712fn max_size(ctx: &egui::Context) -> Vec2 {
713    Vec2::new(
714        palette_dimension(ctx, "palette.max-width", 640.0),
715        palette_dimension(ctx, "palette.max-height", 900.0),
716    )
717}
718
719/// A palette's size once its right edge (`edges[0]`) and bottom edge
720/// (`edges[1]`) are dragged by `delta` from `start`, kept between `least`
721/// and `most`.
722///
723/// ```
724/// use egui::vec2;
725/// use egui_pop_api::palettes::resize_by;
726///
727/// let (least, most) = (vec2(120.0, 64.0), vec2(640.0, 900.0));
728/// let start = vec2(200.0, 300.0);
729/// assert_eq!(resize_by(start, vec2(40.0, 25.0), [true, false], least, most), vec2(240.0, 300.0));
730/// assert_eq!(resize_by(start, vec2(40.0, 25.0), [true, true], least, most), vec2(240.0, 325.0));
731/// assert_eq!(resize_by(start, vec2(-500.0, 0.0), [true, true], least, most), vec2(120.0, 300.0));
732/// ```
733pub fn resize_by(start: Vec2, delta: Vec2, edges: [bool; 2], least: Vec2, most: Vec2) -> Vec2 {
734    let w = if edges[0] { start.x + delta.x } else { start.x };
735    let h = if edges[1] { start.y + delta.y } else { start.y };
736    Vec2::new(w, h).clamp(least, most.max(least))
737}
738
739/// A palette dimension token (`palette.grip`...), `fallback` when the
740/// theme has none.
741fn palette_dimension(ctx: &egui::Context, path: &str, fallback: f32) -> f32 {
742    Tokens::of(ctx)
743        .resolved()
744        .dimension(path)
745        .unwrap_or(fallback)
746}
747
748/// The least and the largest size of a group drawn at `pos`: the
749/// `palette.min-*` and `palette.max-*` tokens, at least `least_width`
750/// wide (its panels' least width and the frame), and inside the
751/// workbench.
752fn size_limits(ctx: &egui::Context, least_width: f32, pos: Pos2, content: Rect) -> (Vec2, Vec2) {
753    let least = Vec2::new(
754        palette_dimension(ctx, "palette.min-width", 120.0).max(least_width),
755        palette_dimension(ctx, "palette.min-height", 64.0),
756    );
757    let most = max_size(ctx).min(content.max - pos).max(least);
758    (least, most)
759}
760
761/// Where the least width a palette's content took is kept, `id` being
762/// its area's.
763fn least_width_id(id: Id) -> Id {
764    id.with("least_content_width")
765}
766
767/// The least width a palette's content took, measured when it was given
768/// less room (`0` until then), `id` being its area's.
769fn least_content_width(ctx: &egui::Context, id: Id) -> f32 {
770    ctx.data(|d| d.get_temp::<f32>(least_width_id(id)))
771        .unwrap_or(0.0)
772}
773
774/// Draws `add` in a vertical scroll area `height` high, as wide as the
775/// room: a resized palette's content. Its band drags the palette, so the
776/// area scrolls by its bar and the wheel, not by a drag.
777fn scrolled(ui: &mut Ui, id: Id, height: f32, add: impl FnOnce(&mut Ui)) {
778    use egui::scroll_area::ScrollSource;
779    ui.scroll_area(
780        egui::ScrollArea::vertical()
781            .id_salt(id.with("scroll"))
782            .scroll_source(ScrollSource::SCROLL_BAR | ScrollSource::MOUSE_WHEEL)
783            .auto_shrink([false, false])
784            .max_height(height)
785            .min_scrolled_height(height),
786        add,
787    );
788}
789
790/// A palette's resize edges, over its frame drawn at `rect`, `grip`
791/// wide: the left and right edges, and when it is not rolled up
792/// (`vertical`) the top and bottom edges and the four corners; each with
793/// the edges it drags, and the cursor of its direction.
794fn resize_edges(
795    ui: &mut Ui,
796    id: Id,
797    rect: Rect,
798    grip: f32,
799    vertical: bool,
800) -> Vec<(egui::Response, Sides)> {
801    use egui_pop_core::pointer::DragKind as Kind;
802    let half = grip.max(2.0) / 2.0;
803    let sense = egui::Sense::CLICK | egui::Sense::DRAG;
804    let x = |at: f32| at - half..=at + half;
805    let mut grips: Vec<(Rect, Sides, &str)> = vec![
806        (
807            Rect::from_x_y_ranges(x(rect.left()), rect.y_range()),
808            [-1, 0],
809            "left",
810        ),
811        (
812            Rect::from_x_y_ranges(x(rect.right()), rect.y_range()),
813            [1, 0],
814            "right",
815        ),
816    ];
817    if vertical {
818        let corner = |p: Pos2| Rect::from_center_size(p, Vec2::splat(4.0 * half));
819        grips.extend([
820            (
821                Rect::from_x_y_ranges(rect.x_range(), x(rect.top())),
822                [0, -1],
823                "top",
824            ),
825            (
826                Rect::from_x_y_ranges(rect.x_range(), x(rect.bottom())),
827                [0, 1],
828                "bottom",
829            ),
830            (corner(rect.left_top()), [-1, -1], "corner.left_top"),
831            (corner(rect.right_top()), [1, -1], "corner.right_top"),
832            (corner(rect.left_bottom()), [-1, 1], "corner.left_bottom"),
833            (corner(rect.right_bottom()), [1, 1], "corner"),
834        ]);
835    }
836    grips
837        .into_iter()
838        .map(|(r, sides, name)| {
839            let response = ui.interact(r, id.with(("resize", name)), sense);
840            let kind = match sides {
841                [0, _] => Kind::ResizeVertical,
842                [_, 0] => Kind::ResizeHorizontal,
843                [a, b] if a == b => Kind::ResizeNwSe,
844                _ => Kind::ResizeNeSw,
845            };
846            // A click on an edge does nothing: dragging is its only action.
847            egui_pop_core::pointer::drag_cursor(&response, kind).clicks(false);
848            (response, sides)
849        })
850        .collect()
851}
852
853/// Follows a palette's resize edges: a drag resizes its group live
854/// (between `limits`, inside `content`; a left or top edge moves it too,
855/// the opposite edge staying), the drop resizes it through
856/// `palette.resize` (anchoring it again); a double click gives it its
857/// content's size back.
858fn follow_resize(
859    app: &AppHandle,
860    ctx: &egui::Context,
861    g: &FloatingGroup,
862    rect: Rect,
863    edges: &[(egui::Response, Sides)],
864    (least, most): (Vec2, Vec2),
865    content: Rect,
866) {
867    let lead = g.lead().clone();
868    if edges.iter().any(|(r, _)| r.double_clicked()) {
869        if g.size.is_some() {
870            run(app, &lead, Some(Change::ResizePalette(lead.clone(), None)));
871            ctx.request_repaint();
872        }
873        return;
874    }
875    let mine = app
876        .workbench_mut()
877        .palette_resize
878        .clone()
879        .filter(|r| r.panel == lead);
880    if let Some((_, e)) = edges.iter().find(|(r, _)| r.dragged()) {
881        let (origin, now) = ctx.input(|i| (i.pointer.press_origin(), i.pointer.latest_pos()));
882        let (Some(origin), Some(now)) = (origin, now) else {
883            return;
884        };
885        let from = mine.as_ref().map_or(rect, |r| r.from);
886        let to = resize_rect(from, now - origin, *e, least, most, content);
887        let size = to.size();
888        let at = to.min - content.min;
889        let mut wb = app.workbench_mut();
890        let mut changed = false;
891        if let Some(fl) = wb.layout.floating_mut(&lead) {
892            changed = fl.size != Some([size.x, size.y]) || fl.pos != [at.x, at.y];
893            fl.size = Some([size.x, size.y]);
894            fl.pos = [at.x, at.y];
895        }
896        if mine.is_none() {
897            // Measured again from the new drag on: the content may have
898            // become narrower.
899            ctx.data_mut(|d| d.remove::<f32>(least_width_id(area_id(&lead))));
900            wb.palette_resize = Some(PaletteResize {
901                panel: lead,
902                saved: g.size,
903                from,
904                edges: *e,
905            });
906        }
907        if changed {
908            ctx.request_repaint();
909        }
910        return;
911    }
912    let Some(r) = mine else {
913        return;
914    };
915    // Dropped: back to the size and the place it had, then the step
916    // decides (with the place, when a left or top edge moved it).
917    let start = r.from.min - content.min;
918    let start = [start.x, start.y];
919    let (to, at) = {
920        let mut wb = app.workbench_mut();
921        wb.palette_resize = None;
922        match wb.layout.floating_mut(&lead) {
923            Some(fl) => (
924                std::mem::replace(&mut fl.size, r.saved),
925                std::mem::replace(&mut fl.pos, start),
926            ),
927            None => (None, start),
928        }
929    };
930    match to {
931        Some(size) if at != start => run(
932            app,
933            &lead,
934            Some(Change::ResizePaletteAt(lead.clone(), size, at)),
935        ),
936        Some(_) if to != r.saved => {
937            run(app, &lead, Some(Change::ResizePalette(lead.clone(), to)));
938        }
939        _ => {}
940    }
941    ctx.request_repaint();
942}
943
944/// Where dropping the dragged palettes would group them, while they are
945/// dragged over another palette: what [`group_hint`] reports.
946#[derive(Clone, Debug, PartialEq)]
947pub struct GroupHint {
948    /// The palettes dropped: a whole group, or one member of a group.
949    pub panels: Vec<PanelId>,
950    /// The palette they would join.
951    pub into: PanelId,
952    /// Above it, below it, or as a tab.
953    pub at: Join,
954    /// Where the hint is drawn, in points.
955    pub rect: Rect,
956    /// Whether a drop now joins: the drag mode and the keys held say so
957    /// (`input.dock_drag`). Not armed, the hint is not drawn and a drop
958    /// only moves.
959    pub armed: bool,
960}
961
962/// Where dropping the palettes dragged now would group them, if they
963/// are dragged over another palette.
964pub fn group_hint(app: &AppHandle) -> Option<GroupHint> {
965    app.workbench_mut().group_hint.clone()
966}
967
968/// Where a palette dropped with the pointer at `at`, over another
969/// palette drawn at `rect`, joins its group: on its top quarter above
970/// it, on its bottom quarter below it, in between as a tab; outside it,
971/// none.
972///
973/// ```
974/// use egui::{Rect, pos2, vec2};
975/// use egui_pop_api::palettes::join_at;
976/// use egui_pop_model::layout::Join;
977///
978/// let r = Rect::from_min_size(pos2(100.0, 100.0), vec2(200.0, 200.0));
979/// assert_eq!(join_at(r, pos2(150.0, 110.0)), Some(Join::Above));
980/// assert_eq!(join_at(r, pos2(150.0, 290.0)), Some(Join::Below));
981/// assert_eq!(join_at(r, pos2(150.0, 200.0)), Some(Join::Tab));
982/// assert_eq!(join_at(r, pos2(50.0, 110.0)), None);
983/// ```
984pub fn join_at(rect: Rect, at: Pos2) -> Option<Join> {
985    if !rect.contains(at) {
986        return None;
987    }
988    let edge = rect.height() / 4.0;
989    if at.y < rect.top() + edge {
990        Some(Join::Above)
991    } else if at.y > rect.bottom() - edge {
992        Some(Join::Below)
993    } else {
994        Some(Join::Tab)
995    }
996}
997
998/// Where a group hint is drawn over the palette joined: its top half,
999/// its bottom half, or all of it for a tab.
1000fn join_rect(rect: Rect, at: Join) -> Rect {
1001    match at {
1002        Join::Above => Rect::from_min_max(rect.min, egui::pos2(rect.max.x, rect.center().y)),
1003        Join::Below => Rect::from_min_max(egui::pos2(rect.min.x, rect.center().y), rect.max),
1004        Join::Tab => rect,
1005    }
1006}
1007
1008/// The palette the pointer at `at` drops the dragged ones on, and where,
1009/// skipping the panels `skip` says (the dragged ones).
1010fn join_target(
1011    members: &BTreeMap<PanelId, Rect>,
1012    at: Pos2,
1013    skip: impl Fn(&PanelId) -> bool,
1014) -> Option<(PanelId, Join, Rect)> {
1015    members
1016        .iter()
1017        .filter(|(p, _)| !skip(p))
1018        .find_map(|(p, r)| join_at(*r, at).map(|j| (p.clone(), j, join_rect(*r, j))))
1019}
1020
1021/// What a palette's band rows read: the tokens, and what each panel's
1022/// one mark slot shows (`pop.panel.state`, its kind).
1023struct RowCx<'a> {
1024    t: &'a Tokens,
1025    states: &'a crate::bus::panel_state::States,
1026    kinds: BTreeMap<PanelId, PanelKind>,
1027}
1028
1029impl RowCx<'_> {
1030    fn kind(&self, panel: &PanelId) -> PanelKind {
1031        self.kinds.get(panel).copied().unwrap_or_default()
1032    }
1033
1034    /// After a band's title: the panel's mark, inline.
1035    fn mark(&self, ui: &mut Ui, panel: &PanelId) {
1036        crate::bus::panel_state::add_inline(self.states, ui, panel.as_str(), self.kind(panel));
1037    }
1038
1039    /// On a palette's tab: the panel's mark, on its corner.
1040    fn mark_on(&self, tab: &egui::Response, panel: &PanelId) {
1041        crate::bus::panel_state::paint_tab(self.states, tab, panel.as_str(), self.kind(panel));
1042    }
1043}
1044
1045/// What a palette's band buttons, menu and tabs asked for.
1046#[derive(Default)]
1047struct Asked {
1048    close: Option<PanelId>,
1049    roll: Option<PanelId>,
1050    pin: bool,
1051    /// The group's menu: Close group.
1052    close_group: bool,
1053    /// The tab to show.
1054    show: Option<PanelId>,
1055    /// The tabs drawn, and whether each is dragged.
1056    grabs: Vec<(PanelId, bool)>,
1057    /// The titles and tabs drawn, each opening its panel's menu.
1058    menus: Vec<(egui::Response, PanelId)>,
1059}
1060
1061/// A member's band as laid out, with where the member is drawn
1062/// vertically (its band's top to its content's bottom).
1063struct MemberBand {
1064    /// The panel shown (a nested tab group's shown tab).
1065    panel: PanelId,
1066    /// A nested tab group's band.
1067    tabs: bool,
1068    band: band::Band,
1069    top: f32,
1070    bottom: f32,
1071}
1072
1073/// Draws the floating palettes over the workbench, each group as one
1074/// unit, and follows their drags: a group's band moves the group, a
1075/// member's band takes it out of its group; dropped over another palette
1076/// they join its group, over an area they dock there, elsewhere they
1077/// move through `palette.move` or `palette.ungroup`.
1078pub(crate) fn show(app: &AppHandle, ctx: &egui::Context) {
1079    let (floating, content, before, members_before) = {
1080        let mut wb = app.workbench_mut();
1081        if wb.palette_drag.is_none() {
1082            wb.group_hint = None;
1083        }
1084        (
1085            wb.layout.floating.clone(),
1086            wb.content,
1087            wb.palette_rects.clone(),
1088            wb.member_rects.clone(),
1089        )
1090    };
1091    let any = if floating.is_empty() { "false" } else { "true" };
1092    if app.context().get(CONTEXT_FLOATING) != any {
1093        app.set_context(CONTEXT_FLOATING, any);
1094    }
1095    if floating.is_empty() || !content.is_positive() {
1096        let mut wb = app.workbench_mut();
1097        wb.palette_rects.clear();
1098        wb.member_rects.clear();
1099        return;
1100    }
1101    let t = Tokens::of(ctx);
1102    let hide = hidden(app);
1103    let stroke = app.context().get(CONTEXT_STROKE) == "true" && setting_bool(app, SETTING_FADE);
1104    let idle = setting_f32(app, SETTING_IDLE_OPACITY)
1105        .unwrap_or(1.0)
1106        .clamp(0.0, 1.0);
1107    let gap = group_gap(ctx);
1108    let pointer = ctx.input(|i| i.pointer.latest_pos());
1109    let mut rects = BTreeMap::new();
1110    let mut members = BTreeMap::new();
1111    for g in floating {
1112        if hide && !g.pinned {
1113            continue;
1114        }
1115        let specs: Vec<_> = g
1116            .panels()
1117            .filter_map(|p| app.workbench_mut().spec(p).cloned())
1118            .collect();
1119        if specs.len() != g.panels().count() {
1120            continue;
1121        }
1122        let lead = g.lead().clone();
1123        let id = area_id(&lead);
1124        let drawn = before.get(&lead).map(|r| r.size());
1125        let size = drawn.unwrap_or(Vec2::ZERO);
1126        let size = g.size.map_or(size, Vec2::from);
1127        let dragging = app
1128            .workbench_mut()
1129            .palette_drag
1130            .as_ref()
1131            .is_some_and(|d| d.kind == DragKind::Group && d.panel == lead);
1132        let resizing = app
1133            .workbench_mut()
1134            .palette_resize
1135            .as_ref()
1136            .is_some_and(|r| r.panel == lead);
1137        // Inside the workbench, again when the window is resized; an
1138        // anchored group keeps its distance to its edges (not while it
1139        // is dragged or resized: the drop sets its anchor again).
1140        let pos = if dragging || resizing {
1141            clamp(content.min + Vec2::from(g.pos), size, content)
1142        } else {
1143            anchored_pos(g.pos, size, content, &g.anchor)
1144        };
1145        if !g.anchor.is_none() && !dragging && !resizing && drawn.is_some() {
1146            // Its place follows the edges (not a move: no step).
1147            let at = [pos.x - content.min.x, pos.y - content.min.y];
1148            if at != g.pos {
1149                let moved = match app.workbench_mut().layout.floating_mut(&lead) {
1150                    Some(fl) => {
1151                        fl.pos = at;
1152                        true
1153                    }
1154                    None => false,
1155                };
1156                if moved {
1157                    app.note_layout("palette.place");
1158                }
1159            }
1160        }
1161        let hovered = before
1162            .get(&lead)
1163            .zip(pointer)
1164            .is_some_and(|(r, p)| r.contains(p));
1165        let target = if g.pinned || dragging {
1166            1.0
1167        } else if stroke {
1168            STROKE_OPACITY
1169        } else if hovered {
1170            1.0
1171        } else {
1172            idle
1173        };
1174        let opacity = ctx.animate_value_with_time(id.with("opacity"), target, t.motion_duration);
1175        let titles: BTreeMap<PanelId, String> = g
1176            .panels()
1177            .map(|p| (p.clone(), app.panel_title(ctx, p)))
1178            .collect();
1179        let row = RowCx {
1180            t: &t,
1181            states: &app.0.bus.panel_states,
1182            kinds: g.panels().map(|p| (p.clone(), app.panel_kind(p))).collect(),
1183        };
1184        // The least width: its panels' declared one, or the width their
1185        // content took when it could not shrink to the room it was given
1186        // (a row that does not wrap), whichever is wider.
1187        let measured = least_content_width(ctx, id);
1188        let min = specs.iter().map(|s| s.min_size).fold(measured, f32::max);
1189        let max = specs
1190            .iter()
1191            .map(|s| s.default_size.unwrap_or(320.0).max(s.min_size))
1192            .fold(min, f32::max);
1193        // Its size once resized, between its limits.
1194        let margin = Kit::of(ctx)
1195            .palette_window
1196            .frame(State::REST, ctx.pixels_per_point())
1197            .total_margin()
1198            .sum();
1199        let (least, most) = size_limits(ctx, min + margin.x, pos, content);
1200        let fixed = g.size.map(|s| Vec2::from(s).clamp(least, most));
1201        let inner = fixed.map(|s| (s - margin).max(Vec2::ZERO));
1202        // Rolled up, it keeps its width and only its bands' height.
1203        let unrolled = g
1204            .members
1205            .iter()
1206            .any(|m| !m.rolled && (g.arrangement == Arrangement::Stack || m.panel == *g.shown()));
1207        let mut asked = Asked::default();
1208        let mut moved: Option<band::Band> = None;
1209        let mut bands: Vec<MemberBand> = Vec::new();
1210        let mut edges: Vec<(egui::Response, Sides)> = Vec::new();
1211        let shown = egui::Area::new(id)
1212            .order(egui::Order::Middle)
1213            .fixed_pos(pos)
1214            .constrain(false)
1215            .show(ctx, |ui| {
1216                ui.multiply_opacity(opacity);
1217                let kit = Kit::of(ui.ctx());
1218                let window = &kit.palette_window;
1219                let style = BandStyle {
1220                    padding: window.data.padding_x,
1221                    gap: kit.header_band.data.padding_y,
1222                };
1223                let shadow = ui.visuals().window_shadow;
1224                let region = focus::Region::new(
1225                    format!("region.palette.{}", crate::app::scope_name(lead.as_str())),
1226                    crate::workbench::RANK_PALETTE,
1227                );
1228                let framed = focus::region(ui, &region, |ui| {
1229                    window.show(ui, State::REST, shadow, |ui| {
1230                        match inner {
1231                            Some(i) => {
1232                                ui.set_min_width(i.x);
1233                                ui.set_max_width(i.x);
1234                            }
1235                            None => {
1236                                ui.set_min_width(min);
1237                                ui.set_max_width(max);
1238                            }
1239                        }
1240                        let top = ui.cursor().top();
1241                        // The room left under the bands for a resized one.
1242                        let body = |ui: &Ui| {
1243                            inner
1244                                .filter(|_| unrolled)
1245                                .map(|i| (top + i.y - ui.cursor().top()).max(0.0))
1246                        };
1247                        if g.is_lone() {
1248                            let m = &g.members[0];
1249                            let (_, b) = band::begin(ui, &style, |ui, state| {
1250                                let title = &titles[&m.panel];
1251                                band_row(ui, &row, title, state, m, Some(g.pinned), &mut asked);
1252                            });
1253                            if let Some(r) = &b.response {
1254                                asked.menus.push((r.clone(), m.shown().clone()));
1255                            }
1256                            if !m.rolled {
1257                                match body(ui) {
1258                                    Some(h) => {
1259                                        scrolled(ui, id, h, |ui| app.show_panel(ui, &m.panel))
1260                                    }
1261                                    None => app.show_panel(ui, &m.panel),
1262                                }
1263                            }
1264                            band::paint(ui, &b, &style);
1265                            moved = Some(b);
1266                            return;
1267                        }
1268                        // The group's band (its tabs, for tabs), then each
1269                        // member shown under its own.
1270                        let joined = g
1271                            .panels()
1272                            .map(|p| titles[p].as_str())
1273                            .collect::<Vec<_>>()
1274                            .join(" · ");
1275                        let tabs = g.arrangement == Arrangement::Tabs;
1276                        let (_, b) = band::begin(ui, &style, |ui, state| {
1277                            group_row(ui, &row, &joined, &g, &titles, state, &mut asked);
1278                        });
1279                        // The group's band acts on its shown panel.
1280                        if let Some(r) = &b.response {
1281                            asked.menus.push((r.clone(), g.shown().clone()));
1282                        }
1283                        let mut column = |ui: &mut Ui| {
1284                            for m in &g.members {
1285                                if tabs && m.panel != *g.shown() {
1286                                    continue;
1287                                }
1288                                let shown = m.shown().clone();
1289                                if !bands.is_empty() {
1290                                    ui.add_space(gap);
1291                                }
1292                                // Room for the member's band to reach up into.
1293                                ui.add_space(style.padding);
1294                                let top = ui.cursor().top() - style.padding;
1295                                let (mb, bottom) = ui
1296                                    .push_id(("egui_pop.palette.member", m.panel.as_str()), |ui| {
1297                                        let (_, mb) = band::begin(ui, &style, |ui, state| {
1298                                            if m.is_tabs() {
1299                                                tabs_row(ui, &row, m, &titles, &mut asked);
1300                                            } else {
1301                                                let title = &titles[&m.panel];
1302                                                band_row(
1303                                                    ui, &row, title, state, m, None, &mut asked,
1304                                                );
1305                                            }
1306                                        });
1307                                        if !m.rolled {
1308                                            app.show_panel(ui, &shown);
1309                                        }
1310                                        (mb, ui.min_rect().bottom())
1311                                    })
1312                                    .inner;
1313                                if let Some(r) = &mb.response {
1314                                    asked.menus.push((r.clone(), shown.clone()));
1315                                }
1316                                bands.push(MemberBand {
1317                                    panel: shown,
1318                                    tabs: m.is_tabs(),
1319                                    band: mb,
1320                                    top,
1321                                    bottom,
1322                                });
1323                            }
1324                            // Painted once the column's width is known.
1325                            for mb in &bands {
1326                                band::paint(ui, &mb.band, &style);
1327                            }
1328                        };
1329                        match body(ui) {
1330                            Some(h) => scrolled(ui, id, h, |ui| {
1331                                ui.set_min_width(ui.available_width());
1332                                column(ui);
1333                            }),
1334                            None => column(ui),
1335                        }
1336                        band::paint(ui, &b, &style);
1337                        moved = Some(b);
1338                    })
1339                });
1340                let grip = palette_dimension(ui.ctx(), "palette.grip", 6.0);
1341                edges = resize_edges(ui, id, framed.response.rect, grip, unrolled);
1342            });
1343        let rect = shown.response.rect;
1344        // Content wider than the room it was given widens the frame past
1345        // the band's row, whose buttons stay at the room's end: its width
1346        // becomes the least one, and the pass is drawn again with it.
1347        let room = inner.map_or(max, |i| i.x);
1348        let took = rect.width() - margin.x;
1349        if took > room + 0.5 && took > measured + 0.5 {
1350            ctx.data_mut(|d| d.insert_temp(least_width_id(id), took));
1351            ctx.request_discard("a palette's content is wider than its room");
1352        }
1353        for p in g.panels() {
1354            rects.insert(p.clone(), rect);
1355        }
1356        if g.is_lone() {
1357            members.insert(lead.clone(), rect);
1358        }
1359        // Each member from its band's top to the next one's (the last to
1360        // the frame's bottom).
1361        let own: Vec<Rect> = bands
1362            .iter()
1363            .enumerate()
1364            .map(|(i, mb)| {
1365                let bottom = bands.get(i + 1).map_or(rect.bottom(), |n| n.top);
1366                Rect::from_x_y_ranges(rect.x_range(), mb.top..=bottom.max(mb.bottom))
1367            })
1368            .collect();
1369        // A group of tabs is dropped on as a whole: its edges stack
1370        // beside the tabs, its middle adds a tab.
1371        let tabs = g.arrangement == Arrangement::Tabs;
1372        for (mb, r) in bands.iter().zip(&own) {
1373            members.insert(mb.panel.clone(), if tabs { rect } else { *r });
1374        }
1375        // Escape in a palette gives the keyboard back. The key first,
1376        // then the focused widget's layer, read without touching the
1377        // focus (egui's `read_response` drops the focus of a widget a
1378        // click did not land on, such as a tree focused through its row).
1379        let layer = shown.response.layer_id;
1380        if ctx.input(|i| i.key_pressed(Key::Escape))
1381            && let Some(focused) = ctx.memory(|m| m.focused())
1382            && focus::peek_response(ctx, focused).is_some_and(|r| r.layer_id == layer)
1383            && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape))
1384        {
1385            ctx.memory_mut(|m| m.surrender_focus(focused));
1386        }
1387        // Each title and tab opens its panel's menu, the one a docked tab
1388        // opens.
1389        for (r, panel) in &asked.menus {
1390            crate::workbench::panel_menu::context_menu(r, app, panel);
1391        }
1392        if asked.close_group {
1393            run(app, &lead, Some(Change::CloseGroup(lead.clone())));
1394            continue;
1395        }
1396        if let Some(p) = asked.close {
1397            app.set_panel_visible(&p, false);
1398            continue;
1399        }
1400        if let Some(p) = asked.roll {
1401            app.change_workbench(Change::Roll(p.clone(), !g.rolled(&p)));
1402        }
1403        if asked.pin {
1404            app.change_workbench(Change::Pin(lead.clone(), !g.pinned));
1405        }
1406        if let Some(p) = &asked.show {
1407            // Which tab shows: the group's state, not a step.
1408            if let Some(fl) = app.workbench_mut().layout.floating_mut(&lead) {
1409                fl.show(p);
1410            }
1411            ctx.request_repaint();
1412        }
1413        let drag = Drag {
1414            content,
1415            before: &before,
1416            members: &members_before,
1417        };
1418        if let Some(b) = moved {
1419            follow(app, ctx, &g, rect, &b, &drag);
1420        }
1421        follow_resize(app, ctx, &g, rect, &edges, (least, max_size(ctx)), content);
1422        for (mb, own) in bands.iter().zip(&own) {
1423            let kind = if mb.tabs {
1424                DragKind::Tabs
1425            } else {
1426                DragKind::Member
1427            };
1428            let b = &mb.band;
1429            let grab = Grab {
1430                panel: &mb.panel,
1431                kind,
1432                dragging: b.dragging,
1433                double_clicked: b.double_clicked,
1434            };
1435            follow_member(app, ctx, &g, grab, *own, rect, &drag);
1436        }
1437        // A tab dragged out of its tabs: from where its tabs are drawn
1438        // (a nested tab group's member, or the whole group of tabs).
1439        for (panel, dragging) in &asked.grabs {
1440            let at = bands
1441                .iter()
1442                .position(|mb| g.member(panel).is_some_and(|m| m.holds(&mb.panel)));
1443            let from = match at {
1444                Some(i) if !tabs => own[i],
1445                _ => rect,
1446            };
1447            let grab = Grab {
1448                panel,
1449                kind: DragKind::Tab,
1450                dragging: *dragging,
1451                double_clicked: false,
1452            };
1453            follow_member(app, ctx, &g, grab, from, rect, &drag);
1454        }
1455    }
1456    {
1457        let mut wb = app.workbench_mut();
1458        wb.palette_rects = rects;
1459        wb.member_rects = members;
1460    }
1461    paint_hints(app, ctx, content, &members_before);
1462}
1463
1464/// The band's row of a palette alone, or of a member of a group: the
1465/// title (in the band's `state`), then Close, Roll and, for a palette
1466/// alone (`pinned` is its pin), Pin at its end.
1467fn band_row(
1468    ui: &mut Ui,
1469    row: &RowCx<'_>,
1470    title: &str,
1471    state: State,
1472    m: &Member,
1473    pinned: Option<bool>,
1474    asked: &mut Asked,
1475) {
1476    let side = row.t.size.control_height.max(24.0);
1477    let kit = Kit::of(ui.ctx());
1478    ui.horizontal(|ui| {
1479        ui.add(
1480            egui::Label::new(
1481                egui::RichText::new(title)
1482                    .strong()
1483                    .color(kit.header_band.style(state).text),
1484            )
1485            .truncate()
1486            .selectable(false),
1487        );
1488        row.mark(ui, &m.panel);
1489        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
1490            // Named with the palette's title: one name per button.
1491            let named = |ui: &Ui, key: &strings::StrKey| {
1492                strings::tr_args(ui.ctx(), key, &[("palette", title)])
1493            };
1494            let name = named(ui, &txt::PALETTE_CLOSE);
1495            if band::button(ui, side, kit.glyph(Glyph::Close), &name, false).clicked() {
1496                asked.close = Some(m.panel.clone());
1497            }
1498            let (icon, name) = if m.rolled {
1499                (Icon::ChevronDown, &txt::PALETTE_ROLL_DOWN)
1500            } else {
1501                (Icon::ChevronUp, &txt::PALETTE_ROLL_UP)
1502            };
1503            let name = named(ui, name);
1504            if band::button(ui, side, icon, &name, false).clicked() {
1505                asked.roll = Some(m.panel.clone());
1506            }
1507            if let Some(pinned) = pinned {
1508                pin_button(ui, side, title, pinned, asked);
1509            }
1510        });
1511    });
1512}
1513
1514/// The band's row of a group: its members' titles (as tabs, for a group
1515/// of tabs), then Pin and the group's menu (Close group).
1516fn group_row(
1517    ui: &mut Ui,
1518    row: &RowCx<'_>,
1519    title: &str,
1520    g: &FloatingGroup,
1521    titles: &BTreeMap<PanelId, String>,
1522    state: State,
1523    asked: &mut Asked,
1524) {
1525    let side = row.t.size.control_height.max(24.0);
1526    let kit = Kit::of(ui.ctx());
1527    ui.horizontal(|ui| {
1528        if g.arrangement == Arrangement::Tabs {
1529            let shown = g.shown();
1530            for m in &g.members {
1531                tab(
1532                    ui,
1533                    row,
1534                    &titles[&m.panel],
1535                    &m.panel,
1536                    m.panel == *shown,
1537                    asked,
1538                );
1539            }
1540        } else {
1541            ui.add(
1542                egui::Label::new(
1543                    egui::RichText::new(title)
1544                        .weak()
1545                        .color(kit.header_band.style(state).text),
1546                )
1547                .truncate()
1548                .selectable(false),
1549            );
1550        }
1551        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
1552            group_menu(ui, side, title, asked);
1553            pin_button(ui, side, title, g.pinned, asked);
1554        });
1555    });
1556}
1557
1558/// The band's row of a tab group nested in a stack: its tabs, then the
1559/// shown tab's Close and the tab group's Roll.
1560fn tabs_row(
1561    ui: &mut Ui,
1562    row: &RowCx<'_>,
1563    m: &Member,
1564    titles: &BTreeMap<PanelId, String>,
1565    asked: &mut Asked,
1566) {
1567    let side = row.t.size.control_height.max(24.0);
1568    let kit = Kit::of(ui.ctx());
1569    let shown = m.shown().clone();
1570    let title = titles[&shown].as_str();
1571    ui.horizontal(|ui| {
1572        for p in m.panels() {
1573            tab(ui, row, &titles[p], p, *p == shown, asked);
1574        }
1575        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
1576            let named = |ui: &Ui, key: &strings::StrKey| {
1577                strings::tr_args(ui.ctx(), key, &[("palette", title)])
1578            };
1579            let name = named(ui, &txt::PALETTE_CLOSE);
1580            if band::button(ui, side, kit.glyph(Glyph::Close), &name, false).clicked() {
1581                asked.close = Some(shown.clone());
1582            }
1583            let (icon, name) = if m.rolled {
1584                (Icon::ChevronDown, &txt::PALETTE_ROLL_DOWN)
1585            } else {
1586                (Icon::ChevronUp, &txt::PALETTE_ROLL_UP)
1587            };
1588            let name = named(ui, name);
1589            if band::button(ui, side, icon, &name, false).clicked() {
1590                asked.roll = Some(shown.clone());
1591            }
1592        });
1593    });
1594}
1595
1596/// A tab of a group of tabs or of a nested tab group: a click shows it,
1597/// a drag takes it out of its tabs; its panel's one mark on its corner,
1598/// as on a docked tab.
1599fn tab(
1600    ui: &mut Ui,
1601    row: &RowCx<'_>,
1602    title: &str,
1603    panel: &PanelId,
1604    selected: bool,
1605    asked: &mut Asked,
1606) {
1607    let r = widgets::selectable_label(ui, selected, title).interact(egui::Sense::drag());
1608    row.mark_on(&r, panel);
1609    egui_pop_core::pointer::drag_cursor(&r, egui_pop_core::pointer::DragKind::Carry);
1610    if r.clicked() {
1611        asked.show = Some(panel.clone());
1612    }
1613    asked.grabs.push((panel.clone(), r.dragged()));
1614    asked.menus.push((r, panel.clone()));
1615}
1616
1617/// The group's menu button on its band, and its menu: Close group (a
1618/// menu entry, so that a stray click on the band never closes a group).
1619fn group_menu(ui: &mut Ui, side: f32, title: &str, asked: &mut Asked) {
1620    let name = strings::tr_args(ui.ctx(), &txt::PALETTE_GROUP_MENU, &[("palette", title)]);
1621    let r = band::button(ui, side, Icon::More, &name, false);
1622    egui::Popup::menu(&r).show(|ui| {
1623        if ui
1624            .button(strings::tr(ui.ctx(), &txt::PALETTE_CLOSE_GROUP))
1625            .clicked()
1626        {
1627            asked.close_group = true;
1628            ui.close();
1629        }
1630    });
1631    egui_pop_core::overlay::follow_menu(&r, "palette group menu");
1632}
1633
1634/// Pin, or Unpin, named with the palette's (or the group's) title.
1635fn pin_button(ui: &mut Ui, side: f32, title: &str, pinned: bool, asked: &mut Asked) {
1636    let (icon, key) = if pinned {
1637        (Icon::Lock, &txt::PALETTE_UNPIN)
1638    } else {
1639        (Icon::Unlock, &txt::PALETTE_PIN)
1640    };
1641    let name = strings::tr_args(ui.ctx(), key, &[("palette", title)]);
1642    if band::button(ui, side, icon, &name, pinned).clicked() {
1643        asked.pin = true;
1644    }
1645}
1646
1647/// What a drag reads of the last frame: the workbench's rectangle, each
1648/// panel's group as drawn, each member as drawn.
1649struct Drag<'a> {
1650    content: Rect,
1651    before: &'a BTreeMap<PanelId, Rect>,
1652    members: &'a BTreeMap<PanelId, Rect>,
1653}
1654
1655impl Drag<'_> {
1656    /// Where a box of `size` dragged from `start` lands with the pointer
1657    /// moved from `origin` to `now`: snapped to the workbench's edges and
1658    /// to the palettes `skip` does not name, kept inside.
1659    fn land(
1660        &self,
1661        ctx: &egui::Context,
1662        start: [f32; 2],
1663        size: Vec2,
1664        origin: Pos2,
1665        now: Pos2,
1666        skip: impl Fn(&PanelId) -> bool,
1667    ) -> [f32; 2] {
1668        let raw = Rect::from_min_size(self.content.min + Vec2::from(start) + (now - origin), size);
1669        let others: Vec<Rect> = self
1670            .before
1671            .iter()
1672            .filter(|(p, _)| !skip(p))
1673            .map(|(_, r)| *r)
1674            .collect();
1675        let at = clamp(
1676            snap(raw, self.content, &others, magnet(ctx)).min,
1677            size,
1678            self.content,
1679        );
1680        [at.x - self.content.min.x, at.y - self.content.min.y]
1681    }
1682}
1683
1684/// Follows a group's band (a palette alone's band): a drag moves the
1685/// group live (snapped, clamped), the drop joins another palette's group
1686/// over it (`palette.group`), docks every member over an area
1687/// (`palette.dock`), else moves it (`palette.move`); a double click rolls
1688/// a palette alone up or down.
1689fn follow(
1690    app: &AppHandle,
1691    ctx: &egui::Context,
1692    g: &FloatingGroup,
1693    rect: Rect,
1694    b: &band::Band,
1695    d: &Drag<'_>,
1696) {
1697    let lead = g.lead().clone();
1698    if b.double_clicked {
1699        if g.is_lone() {
1700            app.change_workbench(Change::Roll(lead.clone(), !g.rolled(&lead)));
1701        }
1702        return;
1703    }
1704    let drag = app.workbench_mut().palette_drag.clone();
1705    let mine = drag.filter(|x| x.kind == DragKind::Group && x.panel == lead);
1706    if b.dragging && !g.pinned {
1707        let (origin, now) = ctx.input(|i| (i.pointer.press_origin(), i.pointer.latest_pos()));
1708        let (Some(origin), Some(now)) = (origin, now) else {
1709            return;
1710        };
1711        let start = mine.as_ref().map_or(g.pos, |x| x.start);
1712        let pos = d.land(ctx, start, rect.size(), origin, now, |p| g.holds(p));
1713        let mut hint = join_target(d.members, now, |p| g.holds(p)).map(|(into, at, r)| GroupHint {
1714            panels: g.panels().cloned().collect(),
1715            into,
1716            at,
1717            rect: r,
1718            armed: false,
1719        });
1720        let (target, since, armed) = track(app, ctx, mine.as_ref(), hint.as_ref(), now);
1721        if let Some(h) = &mut hint {
1722            h.armed = armed;
1723        }
1724        let rearmed = mine.as_ref().is_some_and(|x| x.armed != armed);
1725        let mut wb = app.workbench_mut();
1726        let mut moved = false;
1727        if let Some(fl) = wb.layout.floating_mut(&lead) {
1728            moved = fl.pos != pos;
1729            fl.pos = pos;
1730        }
1731        wb.palette_drag = Some(PaletteDrag {
1732            panel: lead,
1733            kind: DragKind::Group,
1734            start,
1735            pos,
1736            at: now,
1737            target,
1738            since,
1739            armed,
1740        });
1741        wb.group_hint = hint;
1742        // Only a move (or the targets armed or not) needs another frame:
1743        // a held, still pointer does not.
1744        if moved || rearmed {
1745            ctx.request_repaint();
1746        }
1747        return;
1748    }
1749    let Some(x) = mine else {
1750        return;
1751    };
1752    // Dropped: back where it started, then the step decides; docking or
1753    // joining only when armed (the keys held now, the dwell run).
1754    let armed = armed_now(ctx, x.target.is_some().then_some(x.since));
1755    let (to, area, hint) = {
1756        let mut wb = app.workbench_mut();
1757        wb.palette_drag = None;
1758        let hint = wb.group_hint.take().filter(|_| armed);
1759        let area = wb.dock_at(x.at, magnet(ctx)).filter(|_| armed);
1760        let fl = wb.layout.floating_mut(&lead);
1761        let to = fl.map(|fl| std::mem::replace(&mut fl.pos, x.start));
1762        (to, area, hint)
1763    };
1764    let change = match (hint, area, to) {
1765        (Some(h), _, _) => Some(Change::Group(h.panels, h.into, h.at)),
1766        (None, Some(area), _) if g.is_lone() => Some(Change::Dock(lead.clone(), area)),
1767        (None, Some(area), _) => Some(Change::DockGroup(lead.clone(), area)),
1768        (None, None, Some(to)) if to != x.start => Some(Change::MovePalette(lead.clone(), to)),
1769        _ => None,
1770    };
1771    run(app, &lead, change);
1772    ctx.request_repaint();
1773}
1774
1775/// A member's band or a tab, as the pointer left it this pass.
1776struct Grab<'a> {
1777    /// The member's panel (a nested tab group's shown tab), or the tab's.
1778    panel: &'a PanelId,
1779    kind: DragKind,
1780    dragging: bool,
1781    double_clicked: bool,
1782}
1783
1784/// Follows the band of a member of a group, or a tab: a drag shows where
1785/// it would go, the drop joins another palette's group over it (or moves
1786/// it within its own), docks it over an area, takes it out of its group
1787/// anywhere else (`palette.ungroup`; a nested tab group's band takes the
1788/// tab group out whole), or leaves it in its group when dropped back over
1789/// it; a double click on a band rolls it up or down.
1790fn follow_member(
1791    app: &AppHandle,
1792    ctx: &egui::Context,
1793    g: &FloatingGroup,
1794    grab: Grab<'_>,
1795    own: Rect,
1796    group: Rect,
1797    d: &Drag<'_>,
1798) {
1799    let Grab {
1800        panel,
1801        kind,
1802        dragging,
1803        double_clicked,
1804    } = grab;
1805    if double_clicked {
1806        app.change_workbench(Change::Roll(panel.clone(), !g.rolled(panel)));
1807        return;
1808    }
1809    let drag = app.workbench_mut().palette_drag.clone();
1810    let mine = drag.filter(|x| x.kind == kind && x.panel == *panel);
1811    // What moves, and what it is not dropped on: itself, and a tab's
1812    // fellow tabs.
1813    let held = |p: &PanelId| -> Vec<PanelId> {
1814        g.member(p)
1815            .map_or_else(|| vec![p.clone()], |m| m.panels().cloned().collect())
1816    };
1817    let moving = if kind == DragKind::Tabs {
1818        held(panel)
1819    } else {
1820        vec![panel.clone()]
1821    };
1822    let mates: Vec<PanelId> = match kind {
1823        DragKind::Tab if g.arrangement == Arrangement::Tabs => g.panels().cloned().collect(),
1824        DragKind::Tab => held(panel),
1825        _ => moving.clone(),
1826    };
1827    if dragging && !g.pinned {
1828        let (origin, now) = ctx.input(|i| (i.pointer.press_origin(), i.pointer.latest_pos()));
1829        let (Some(origin), Some(now)) = (origin, now) else {
1830            return;
1831        };
1832        let from = own.min - d.content.min;
1833        let start = mine.as_ref().map_or([from.x, from.y], |x| x.start);
1834        let pos = d.land(ctx, start, own.size(), origin, now, |p| g.holds(p));
1835        let mut hint =
1836            join_target(d.members, now, |p| mates.contains(p)).map(|(into, at, r)| GroupHint {
1837                panels: moving.clone(),
1838                into,
1839                at,
1840                rect: r,
1841                armed: false,
1842            });
1843        let (target, since, armed) = track(app, ctx, mine.as_ref(), hint.as_ref(), now);
1844        if let Some(h) = &mut hint {
1845            h.armed = armed;
1846        }
1847        let mut wb = app.workbench_mut();
1848        let moved = mine
1849            .as_ref()
1850            .is_none_or(|x| x.pos != pos || x.at != now || x.armed != armed);
1851        wb.palette_drag = Some(PaletteDrag {
1852            panel: panel.clone(),
1853            kind,
1854            start,
1855            pos,
1856            at: now,
1857            target,
1858            since,
1859            armed,
1860        });
1861        wb.group_hint = hint;
1862        if moved {
1863            ctx.request_repaint();
1864        }
1865        return;
1866    }
1867    let Some(x) = mine else {
1868        return;
1869    };
1870    let armed = armed_now(ctx, x.target.is_some().then_some(x.since));
1871    let (area, hint) = {
1872        let mut wb = app.workbench_mut();
1873        wb.palette_drag = None;
1874        let hint = wb.group_hint.take().filter(|_| armed);
1875        (wb.dock_at(x.at, magnet(ctx)).filter(|_| armed), hint)
1876    };
1877    let changes = match (hint, area) {
1878        (Some(h), _) => vec![Change::Group(h.panels, h.into, h.at)],
1879        // Docked: the shown one last, so that it shows.
1880        (None, Some(area)) => moving
1881            .iter()
1882            .filter(|p| *p != panel)
1883            .chain([panel])
1884            .map(|p| Change::Dock(p.clone(), area))
1885            .collect(),
1886        (None, None) if group.contains(x.at) => Vec::new(),
1887        (None, None) if kind == DragKind::Tabs => vec![Change::UngroupTabs(panel.clone(), x.pos)],
1888        (None, None) => vec![Change::Ungroup(panel.clone(), x.pos)],
1889    };
1890    for c in changes {
1891        run(app, panel, Some(c));
1892    }
1893    ctx.request_repaint();
1894}
1895
1896/// Runs a dropped palette's change, telling why when it is refused.
1897fn run(app: &AppHandle, panel: &PanelId, change: Option<Change>) {
1898    let out = change.and_then(|c| app.change_workbench(c));
1899    if let Some(Outcome::Done(Err(e))) = &out {
1900        app.workbench_refused(&format!("palette {panel}"), e);
1901    }
1902}
1903
1904/// While palettes are dragged: over another palette, where they would
1905/// join its group (the kit's `dock-preview`, as for tabs); a member
1906/// dragged out of its group, where it would float alone.
1907fn paint_hints(
1908    app: &AppHandle,
1909    ctx: &egui::Context,
1910    content: Rect,
1911    members: &BTreeMap<PanelId, Rect>,
1912) {
1913    let (drag, hint, dock) = {
1914        let wb = app.workbench_mut();
1915        let dock = wb
1916            .palette_drag
1917            .as_ref()
1918            .filter(|d| d.armed)
1919            .and_then(|d| wb.dock_at(d.at, magnet(ctx)));
1920        (
1921            wb.palette_drag.clone(),
1922            wb.group_hint.clone().filter(|h| h.armed),
1923            dock,
1924        )
1925    };
1926    if drag.is_some() && app.service(&crate::strips::STRIPS).is_none() {
1927        paint_drag_hint(app, ctx);
1928    }
1929    let rect = match (&hint, &drag) {
1930        (Some(h), _) => h.rect,
1931        (None, Some(d)) if d.kind != DragKind::Group && dock.is_none() => {
1932            let Some(own) = members.get(&d.panel) else {
1933                return;
1934            };
1935            Rect::from_min_size(content.min + Vec2::from(d.pos), own.size())
1936        }
1937        _ => return,
1938    };
1939    let kit = Kit::of(ctx);
1940    let painter = ctx.layer_painter(egui::LayerId::new(
1941        egui::Order::Foreground,
1942        Id::unique("egui_pop.palette.hint"),
1943    ));
1944    let cx = KitCx {
1945        painter: &painter,
1946        ppp: ctx.pixels_per_point(),
1947    };
1948    kit.dock_preview.paint_part(
1949        &cx,
1950        &Part {
1951            rect,
1952            room: rect,
1953            state: State::REST,
1954            label: None,
1955        },
1956    );
1957}
1958
1959/// The drag's hint ([`drag_hint`]) under the pointer, for an application
1960/// without a status bar.
1961fn paint_drag_hint(app: &AppHandle, ctx: &egui::Context) {
1962    let (Some(text), Some(at)) = (drag_hint(app), ctx.input(|i| i.pointer.latest_pos())) else {
1963        return;
1964    };
1965    let t = Tokens::of(ctx);
1966    egui::Area::new(Id::unique("egui_pop.palette.drag_hint"))
1967        .order(egui::Order::Tooltip)
1968        .fixed_pos(at + Vec2::new(t.space.m, t.space.l))
1969        .interactable(false)
1970        .show(ctx, |ui| {
1971            egui::Frame::popup(ui.style()).show(ui, |ui| {
1972                ui.add(egui::Label::new(text).selectable(false).extend());
1973            });
1974        });
1975}
1976
1977/// The room between the members of a stacked group (`palette.group.gap`).
1978fn group_gap(ctx: &egui::Context) -> f32 {
1979    Tokens::of(ctx)
1980        .resolved()
1981        .dimension("palette.group.gap")
1982        .unwrap_or(0.0)
1983}
1984
1985/// How close a dragged palette snaps to an edge or another palette, and
1986/// docks in an area (`palette.magnet`).
1987pub(crate) fn magnet(ctx: &egui::Context) -> f32 {
1988    Tokens::of(ctx)
1989        .resolved()
1990        .dimension("palette.magnet")
1991        .unwrap_or(0.0)
1992}
1993
1994#[cfg(test)]
1995mod tests {
1996    use super::*;
1997    use egui::{pos2, vec2};
1998
1999    fn bounds(w: f32, h: f32) -> Rect {
2000        Rect::from_min_size(pos2(10.0, 20.0), vec2(w, h))
2001    }
2002
2003    const SIZE: Vec2 = Vec2::new(100.0, 50.0);
2004
2005    /// A palette of `SIZE` at `pos` from the bounds' top-left.
2006    fn at(b: Rect, pos: [f32; 2]) -> Rect {
2007        Rect::from_min_size(b.min + Vec2::from(pos), SIZE)
2008    }
2009
2010    #[test]
2011    fn each_corner_anchors_both_axes_and_follows_a_resize() {
2012        let small = bounds(800.0, 600.0);
2013        let large = bounds(1000.0, 700.0);
2014        for (pos, x, y, moved) in [
2015            ([0.0, 0.0], AnchorEdge::Start, AnchorEdge::Start, [0.0, 0.0]),
2016            (
2017                [700.0, 0.0],
2018                AnchorEdge::End,
2019                AnchorEdge::Start,
2020                [900.0, 0.0],
2021            ),
2022            (
2023                [0.0, 550.0],
2024                AnchorEdge::Start,
2025                AnchorEdge::End,
2026                [0.0, 650.0],
2027            ),
2028            (
2029                [700.0, 550.0],
2030                AnchorEdge::End,
2031                AnchorEdge::End,
2032                [900.0, 650.0],
2033            ),
2034        ] {
2035            let a = anchor_of(at(small, pos), small);
2036            assert_eq!((a.x, a.y), (x, y), "{pos:?}");
2037            assert_eq!(a.offset, [0.0, 0.0]);
2038            let p = anchored_pos(pos, SIZE, large, &a);
2039            assert_eq!(p, large.min + Vec2::from(moved), "{pos:?}");
2040        }
2041    }
2042
2043    #[test]
2044    fn one_axis_only_keeps_the_other_place() {
2045        let small = bounds(800.0, 600.0);
2046        let a = anchor_of(at(small, [700.0, 200.0]), small);
2047        assert_eq!((a.x, a.y), (AnchorEdge::End, AnchorEdge::None));
2048        let large = bounds(1000.0, 700.0);
2049        let p = anchored_pos([700.0, 200.0], SIZE, large, &a);
2050        assert_eq!(p, large.min + vec2(900.0, 200.0));
2051        let a = anchor_of(at(small, [300.0, 550.0]), small);
2052        assert_eq!((a.x, a.y), (AnchorEdge::None, AnchorEdge::End));
2053        let p = anchored_pos([300.0, 550.0], SIZE, large, &a);
2054        assert_eq!(p, large.min + vec2(300.0, 650.0));
2055    }
2056
2057    #[test]
2058    fn the_offset_is_kept_through_a_resize() {
2059        let a = Anchor {
2060            x: AnchorEdge::End,
2061            y: AnchorEdge::Start,
2062            offset: [12.0, 8.0],
2063        };
2064        for w in [600.0, 800.0, 1200.0] {
2065            let b = bounds(w, 500.0);
2066            let p = anchored_pos([0.0, 0.0], SIZE, b, &a);
2067            assert_eq!(b.right() - (p.x + SIZE.x), 12.0, "{w}");
2068            assert_eq!(p.y - b.top(), 8.0, "{w}");
2069        }
2070        // Too small for the offset: still inside.
2071        let b = bounds(105.0, 500.0);
2072        let p = anchored_pos([0.0, 0.0], SIZE, b, &a);
2073        assert_eq!(p.x, b.left());
2074    }
2075
2076    #[test]
2077    fn dragged_away_from_the_edge_or_onto_a_palette_it_is_not_anchored() {
2078        let b = bounds(800.0, 600.0);
2079        // Dropped away from the edges, beyond the magnet: snap leaves it,
2080        // so no anchor.
2081        let away = snap(at(b, [650.0, 200.0]), b, &[], 12.0);
2082        assert!(anchor_of(away, b).is_none());
2083        // Within the magnet: snapped onto the edge, anchored.
2084        let near = snap(at(b, [692.0, 200.0]), b, &[], 12.0);
2085        assert_eq!(anchor_of(near, b).x, AnchorEdge::End);
2086        // Snapped beside another palette (not the workbench): no anchor.
2087        let other = Rect::from_min_size(b.min + vec2(400.0, 180.0), SIZE);
2088        let beside = snap(at(b, [505.0, 200.0]), b, &[other], 12.0);
2089        assert_eq!(beside.left(), other.right());
2090        assert!(anchor_of(beside, b).is_none());
2091        // Unanchored: today's behaviour, clamped inside.
2092        let p = anchored_pos([780.0, 200.0], SIZE, b, &Anchor::default());
2093        assert_eq!(p, b.min + vec2(700.0, 200.0));
2094    }
2095}