mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
Merge #187: ui: shared panel docking with floating window trees, and task panes for office apps
This commit is contained in:
commit
7fdbab4f0d
50 files changed
+15798
-1018
No files matched your search
@@ -16,6 +16,10 @@ serde = { version = "1", features = ["derive"], optional = true }
|
||||
|
||||
[features]
|
||||
serde = ["dep:serde"]
|
||||
# Floating windows may move to their own OS windows (desktop egui backends with viewports).
|
||||
native-windows = []
|
||||
# `docking::testing`: a headless driver for application docking tests.
|
||||
testing = []
|
||||
|
||||
[dev-dependencies]
|
||||
egui = { workspace = true, features = ["default_fonts"] }
|
||||
|
||||
@@ -108,6 +108,12 @@ tabs before hiding them, keeps input order and retains the selected tab. Tiny st
|
||||
its width to zero. Negative/non-finite dimensions become zero and large dimensions are bounded.
|
||||
The work is linear in tab count with at most 32 fitting passes; the caller caps its own tab count.
|
||||
|
||||
`tabs::fit_whole(natural_widths, selected, available, overflow_width)` keeps every shown tab at its
|
||||
natural width and sends the rest to overflow. Tabs are shown in order up to the first that does not
|
||||
fit; the selected tab is always shown in its logical place, taking the place of the last tabs that
|
||||
fit when it lies past them. Only a selected tab wider than the strip minus the overflow button is
|
||||
narrowed. Docking tab strips use this policy.
|
||||
|
||||
`tabs::Tab` registers a tab at a supplied rectangle and invokes the application's painter:
|
||||
|
||||
```rust
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Floating window chrome: an opaque frame with anchored resize handles, and a title bar with an
|
||||
//! optional title, ▾ menu button and ×. [`super::DockArea`] draws its floating windows with
|
||||
//! these; other hosts (task panes) use them with their own ids and actions. Nothing here changes
|
||||
//! a layout: the caller turns the responses into its own commands.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{
|
||||
Color32, Context, FontId, Galley, Id, Key, LayerId, Order, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetText, pos2, vec2,
|
||||
};
|
||||
|
||||
use super::{DockStyle, PanelLimits, resize::AnchoredResize};
|
||||
|
||||
/// Height of a floating window's title bar.
|
||||
pub const TITLE_HEIGHT: f32 = 14.0;
|
||||
|
||||
/// Names of the resize handles, appended to the frame id: `id.with(name)`.
|
||||
pub const RESIZE_HANDLES: [&str; 8] =
|
||||
["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left", "resize-top", "resize-top-left", "resize-top-right"];
|
||||
|
||||
/// Height of the top resize band of a resizable frame. The frame's contents start below it, so
|
||||
/// the band takes no moves or clicks from a title bar.
|
||||
pub const RESIZE_BAND: f32 = 4.0;
|
||||
|
||||
/// Colors and font of the frame and title bar.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ChromeStyle {
|
||||
/// Painted under the contents, so the window stays opaque when the contents are not.
|
||||
pub background: Color32,
|
||||
pub stroke: Stroke,
|
||||
pub title_background: Color32,
|
||||
pub text: Color32,
|
||||
pub weak_text: Color32,
|
||||
pub accent: Color32,
|
||||
pub font: FontId,
|
||||
/// Mirror the title bar: buttons at the left, the title at the right.
|
||||
pub right_to_left: bool,
|
||||
}
|
||||
|
||||
impl ChromeStyle {
|
||||
pub fn from_ui(ui: &Ui) -> Self {
|
||||
Self::from_dock(&DockStyle::from_ui(ui))
|
||||
}
|
||||
|
||||
pub fn from_dock(style: &DockStyle) -> Self {
|
||||
Self {
|
||||
background: style.floating_background,
|
||||
stroke: style.floating_stroke,
|
||||
title_background: style.tab_background,
|
||||
text: style.text,
|
||||
weak_text: style.inactive_text,
|
||||
accent: style.accent,
|
||||
font: style.font.clone(),
|
||||
right_to_left: style.right_to_left,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resize handle hit rects and the edges they move: every side and corner. The top handles
|
||||
/// fill the band above the contents; the others lie over the contents' edges.
|
||||
fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 8] {
|
||||
let band_bottom = (rect.top() + RESIZE_BAND).min(rect.bottom());
|
||||
let left_corner = (rect.left() + 12.0).min(rect.right());
|
||||
let right_corner = (rect.right() - 12.0).max(rect.left());
|
||||
[
|
||||
("resize", Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max), vec2(1.0, 1.0)),
|
||||
(
|
||||
"resize-left",
|
||||
Rect::from_min_max(pos2(rect.left(), rect.top() + 12.0), pos2((rect.left() + 4.0).min(rect.right()), rect.bottom() - 12.0)),
|
||||
vec2(-1.0, 0.0),
|
||||
),
|
||||
(
|
||||
"resize-right",
|
||||
Rect::from_min_max(pos2((rect.right() - 4.0).max(rect.left()), rect.top() + 12.0), pos2(rect.right(), rect.bottom() - 12.0)),
|
||||
vec2(1.0, 0.0),
|
||||
),
|
||||
(
|
||||
"resize-bottom",
|
||||
Rect::from_min_max(pos2(rect.left() + 12.0, (rect.bottom() - 4.0).max(rect.top())), pos2(rect.right() - 12.0, rect.bottom())),
|
||||
vec2(0.0, 1.0),
|
||||
),
|
||||
(
|
||||
"resize-bottom-left",
|
||||
Rect::from_min_max(pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), pos2(left_corner, rect.bottom())),
|
||||
vec2(-1.0, 1.0),
|
||||
),
|
||||
("resize-top", Rect::from_min_max(pos2(left_corner, rect.top()), pos2(right_corner, band_bottom)), vec2(0.0, -1.0)),
|
||||
("resize-top-left", Rect::from_min_max(rect.min, pos2(left_corner, band_bottom)), vec2(-1.0, -1.0)),
|
||||
("resize-top-right", Rect::from_min_max(pos2(right_corner, rect.top()), pos2(rect.right(), band_bottom)), vec2(1.0, -1.0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// An opaque in-window frame on its own `Order::Middle` layer, `id`, at `rect`.
|
||||
pub struct FloatingFrame<'a> {
|
||||
id: Id,
|
||||
rect: Rect,
|
||||
bounds: Option<Rect>,
|
||||
limits: PanelLimits,
|
||||
resizable: bool,
|
||||
resize_label: &'a str,
|
||||
}
|
||||
|
||||
/// What a [`FloatingFrame`] did this frame.
|
||||
pub struct FrameResponse<R> {
|
||||
pub inner: R,
|
||||
/// Where the frame was drawn, inside its bounds.
|
||||
pub rect: Rect,
|
||||
pub layer: LayerId,
|
||||
/// The rect a resize handle asks for: pointer drags anchored at the opposite edges, or
|
||||
/// arrow keys on a focused handle (8 pt per press). Escape and focus loss end a resize.
|
||||
pub resized: Option<Rect>,
|
||||
/// The handle whose pointer resize started this frame.
|
||||
pub resize_started: Option<Id>,
|
||||
/// Every handle's response, for focus and gesture bookkeeping.
|
||||
pub handles: Vec<Response>,
|
||||
}
|
||||
|
||||
impl<'a> FloatingFrame<'a> {
|
||||
pub fn new(id: Id, rect: Rect) -> Self {
|
||||
Self { id, rect, bounds: None, limits: PanelLimits::default(), resizable: true, resize_label: "Resize window" }
|
||||
}
|
||||
|
||||
/// The frame stays inside `bounds`; the default is the viewport's content rect.
|
||||
pub fn bounds(mut self, bounds: Rect) -> Self {
|
||||
self.bounds = Some(bounds);
|
||||
self
|
||||
}
|
||||
|
||||
/// Size limits of a resize, top resize band included. The frame itself is drawn at the
|
||||
/// given rect.
|
||||
pub fn limits(mut self, limits: PanelLimits) -> Self {
|
||||
self.limits = limits;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn resizable(mut self, resizable: bool) -> Self {
|
||||
self.resizable = resizable;
|
||||
self
|
||||
}
|
||||
|
||||
/// Accessibility label of the resize handles.
|
||||
pub fn resize_label(mut self, label: &'a str) -> Self {
|
||||
self.resize_label = label;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn layer(id: Id) -> LayerId {
|
||||
LayerId::new(Order::Middle, id)
|
||||
}
|
||||
|
||||
/// Draw the frame, then `add_contents` with the rect for its contents (the frame's rect below
|
||||
/// the top resize band when resizable), then the outline and handles.
|
||||
pub fn show<R>(self, ctx: &Context, style: &ChromeStyle, add_contents: impl FnOnce(&mut Ui, Rect) -> R) -> FrameResponse<R> {
|
||||
let bounds = self.bounds.unwrap_or_else(|| ctx.content_rect());
|
||||
let rect = clamp(self.rect, bounds);
|
||||
let area = egui::Area::new(self.id)
|
||||
.fade_in(false)
|
||||
.order(Order::Middle)
|
||||
.fixed_pos(rect.min)
|
||||
.default_size(rect.size())
|
||||
.movable(false)
|
||||
.constrain_to(bounds);
|
||||
let shown = area.show(ctx, |ui| {
|
||||
// Drawn at `rect` itself, also in egui's first (sizing) pass of a new area.
|
||||
ui.set_min_size(rect.size());
|
||||
ui.allocate_rect(rect, Sense::hover());
|
||||
ui.painter().rect_filled(rect, 0.0, style.background);
|
||||
let contents =
|
||||
if self.resizable { Rect::from_min_max(pos2(rect.left(), (rect.top() + RESIZE_BAND).min(rect.bottom())), rect.max) } else { rect };
|
||||
let inner = add_contents(ui, contents);
|
||||
ui.painter().rect_stroke(rect, 0.0, style.stroke, StrokeKind::Outside);
|
||||
let (resized, resize_started, handles) = if self.resizable { self.handles(ui, rect, bounds, style) } else { (None, None, Vec::new()) };
|
||||
FrameResponse { inner, rect, layer: Self::layer(self.id), resized, resize_started, handles }
|
||||
});
|
||||
shown.inner
|
||||
}
|
||||
|
||||
fn handles(&self, ui: &mut Ui, rect: Rect, bounds: Rect, style: &ChromeStyle) -> (Option<Rect>, Option<Id>, Vec<Response>) {
|
||||
let mut resized = None;
|
||||
let mut started = None;
|
||||
let mut responses = Vec::new();
|
||||
let limits = PanelLimits { min: self.limits.min.max(vec2(40.0, RESIZE_BAND + TITLE_HEIGHT + 20.0)).min(self.limits.max), ..self.limits };
|
||||
let canceled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused);
|
||||
for (name, handle, direction) in handles(rect) {
|
||||
if !super::targets::usable(handle) {
|
||||
continue;
|
||||
}
|
||||
let cursor = if direction.x == 0.0 {
|
||||
egui::CursorIcon::ResizeVertical
|
||||
} else if direction.y == 0.0 {
|
||||
egui::CursorIcon::ResizeHorizontal
|
||||
} else if direction.x == direction.y {
|
||||
egui::CursorIcon::ResizeNwSe
|
||||
} else {
|
||||
egui::CursorIcon::ResizeNeSw
|
||||
};
|
||||
let response = ui.interact(handle, self.id.with(name), Sense::drag()).on_hover_cursor(cursor);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.resize_label));
|
||||
let anchor_id = response.id.with("pointer-anchor");
|
||||
crate::layout::drag_focus(ui, &response);
|
||||
if response.drag_started()
|
||||
&& let Some(origin) = ui.input(|i| i.pointer.press_origin())
|
||||
&& let Some(anchor) = AnchoredResize::new(rect, origin, direction)
|
||||
{
|
||||
ui.ctx().data_mut(|data| data.insert_temp(anchor_id, anchor));
|
||||
started = Some(response.id);
|
||||
}
|
||||
let mut delta = Vec2::ZERO;
|
||||
if response.has_focus() {
|
||||
ui.memory_mut(|memory| {
|
||||
memory.set_focus_lock_filter(
|
||||
response.id,
|
||||
egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() },
|
||||
)
|
||||
});
|
||||
ui.input_mut(|input| {
|
||||
for (key, step) in [
|
||||
(Key::ArrowLeft, vec2(-8.0, 0.0)),
|
||||
(Key::ArrowRight, vec2(8.0, 0.0)),
|
||||
(Key::ArrowUp, vec2(0.0, -8.0)),
|
||||
(Key::ArrowDown, vec2(0.0, 8.0)),
|
||||
] {
|
||||
if input.consume_key(egui::Modifiers::NONE, key) {
|
||||
delta += step;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let next = if response.dragged() || response.drag_stopped() {
|
||||
ui.ctx()
|
||||
.data(|data| data.get_temp::<AnchoredResize>(anchor_id))
|
||||
.and_then(|anchor| ui.ctx().pointer_interact_pos().and_then(|pointer| anchor.rect(pointer, bounds, limits)))
|
||||
} else if delta != Vec2::ZERO {
|
||||
AnchoredResize::new(rect, rect.max, direction).and_then(|anchor| anchor.rect(rect.max + delta, bounds, limits))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if response.enabled()
|
||||
&& !canceled
|
||||
&& let Some(next) = next.filter(|next| *next != rect)
|
||||
{
|
||||
resized = Some(next);
|
||||
}
|
||||
if canceled || !ui.input(|input| input.pointer.primary_down()) {
|
||||
ui.ctx().data_mut(|data| data.remove::<AnchoredResize>(anchor_id));
|
||||
}
|
||||
if name == "resize" && (response.hovered() || response.dragged() || response.has_focus()) {
|
||||
ui.painter().line_segment([handle.left_bottom(), handle.right_top()], Stroke::new(2.0, style.accent));
|
||||
}
|
||||
responses.push(response);
|
||||
}
|
||||
(resized, started, responses)
|
||||
}
|
||||
}
|
||||
|
||||
/// A drop preview: a 2 pt accent outline inside `rect`, filled with 15% accent when `filled`.
|
||||
/// Docking and the pane host draw every destination and drag ghost with it.
|
||||
pub fn drop_preview(painter: &egui::Painter, rect: Rect, accent: Color32, filled: bool) {
|
||||
let fill = if filled { accent.gamma_multiply(0.15) } else { Color32::TRANSPARENT };
|
||||
painter.rect(rect, 0.0, fill, Stroke::new(2.0, accent), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// Keep `rect` inside `bounds`, shrinking it when it is larger.
|
||||
pub fn clamp(rect: Rect, bounds: Rect) -> Rect {
|
||||
if !super::targets::usable(bounds) {
|
||||
return rect;
|
||||
}
|
||||
let size = rect.size().max(vec2(1.0, 1.0)).min(bounds.size());
|
||||
let min = rect.min.max(bounds.min).min(bounds.max - size);
|
||||
Rect::from_min_size(min, size)
|
||||
}
|
||||
|
||||
/// `text` on one line no wider than `width`, cut at the end with '…'. egui does not wrap a
|
||||
/// host's pre-laid-out `WidgetText::Galley` again, so that one is laid out again from its job.
|
||||
pub(super) fn truncated(ui: &Ui, text: WidgetText, width: f32, font: FontId) -> Arc<Galley> {
|
||||
let galley = text.into_galley(ui, Some(egui::TextWrapMode::Truncate), width, font);
|
||||
if galley.size().x <= width + 0.5 {
|
||||
return galley;
|
||||
}
|
||||
let mut job = (*galley.job).clone();
|
||||
job.wrap = egui::text::TextWrapping::truncate_at_width(width);
|
||||
ui.painter().layout_job(job)
|
||||
}
|
||||
|
||||
/// A title bar: an optional title, an optional ▾ menu button and an optional ×, 10 pt
|
||||
/// in from the right edge, mirrored when [`ChromeStyle::right_to_left`] is set. The bar senses
|
||||
/// clicks and drags; double-clicks are the caller's.
|
||||
pub struct TitleBar<'a> {
|
||||
id: Id,
|
||||
move_label: &'a str,
|
||||
title: Option<WidgetText>,
|
||||
menu: Option<&'a str>,
|
||||
close: Option<&'a str>,
|
||||
movable: bool,
|
||||
}
|
||||
|
||||
/// The parts of a [`TitleBar`] that were shown.
|
||||
pub struct TitleResponse {
|
||||
/// Drag to move; double-click is the caller's (docking minimizes every group).
|
||||
pub bar: Response,
|
||||
pub menu: Option<Response>,
|
||||
pub close: Option<Response>,
|
||||
}
|
||||
|
||||
impl<'a> TitleBar<'a> {
|
||||
/// `id` is the bar's own; the buttons use `id.with("menu")` and `id.with("close")`.
|
||||
/// `move_label` names the bar for accessibility.
|
||||
pub fn new(id: Id, move_label: &'a str) -> Self {
|
||||
Self { id, move_label, title: None, menu: None, close: None, movable: true }
|
||||
}
|
||||
|
||||
/// Text at the leading edge, cut with '…' to fit.
|
||||
pub fn title(mut self, title: impl Into<WidgetText>) -> Self {
|
||||
self.title = Some(title.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Show a ▾ button with this accessibility label.
|
||||
pub fn menu(mut self, label: &'a str) -> Self {
|
||||
self.menu = Some(label);
|
||||
self
|
||||
}
|
||||
|
||||
/// Show a × button with this accessibility label.
|
||||
pub fn close(mut self, label: &'a str) -> Self {
|
||||
self.close = Some(label);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the bar shows the grab cursor. It senses drags either way.
|
||||
pub fn movable(mut self, movable: bool) -> Self {
|
||||
self.movable = movable;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn show(self, ui: &mut Ui, rect: Rect, style: &ChromeStyle) -> TitleResponse {
|
||||
let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
painter.rect_filled(rect, 0.0, style.title_background);
|
||||
let side = rect.height();
|
||||
// Laid out left to right, then mirrored in a right-to-left layout.
|
||||
let mirror = |r: Rect| {
|
||||
if style.right_to_left {
|
||||
Rect::from_x_y_ranges((rect.left() + rect.right() - r.right())..=(rect.left() + rect.right() - r.left()), r.y_range())
|
||||
} else {
|
||||
r
|
||||
}
|
||||
};
|
||||
let close_rect = self.close.map(|_| Rect::from_center_size(pos2(rect.right() - 10.0, rect.center().y), vec2(side, side)));
|
||||
let menu_right = close_rect.map_or(rect.right() - 3.0, |close| close.left() - 2.0);
|
||||
let menu_rect = self.menu.map(|_| Rect::from_min_max(pos2(menu_right - side, rect.top()), pos2(menu_right, rect.bottom())));
|
||||
let buttons = menu_rect.or(close_rect).map_or(rect.right(), |r| r.left());
|
||||
let bar_rect = mirror(Rect::from_min_max(rect.min, pos2(buttons.max(rect.left()), rect.bottom())));
|
||||
let (close_rect, menu_rect) = (close_rect.map(mirror), menu_rect.map(mirror));
|
||||
let bar = ui.interact(bar_rect, self.id, Sense::click_and_drag());
|
||||
let bar = if self.movable { bar.on_hover_cursor(egui::CursorIcon::Grab) } else { bar };
|
||||
bar.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.move_label));
|
||||
if let Some(title) = self.title {
|
||||
let galley = truncated(ui, title, (bar_rect.width() - 12.0).max(0.0), style.font.clone());
|
||||
let x = if style.right_to_left { bar_rect.right() - 6.0 - galley.size().x } else { bar_rect.left() + 6.0 };
|
||||
painter.galley(pos2(x, rect.center().y - galley.size().y * 0.5), galley, style.text);
|
||||
}
|
||||
if bar.has_focus() {
|
||||
painter.rect_stroke(bar_rect.shrink(1.0), 0.0, Stroke::new(1.0, style.accent), StrokeKind::Inside);
|
||||
}
|
||||
let button = |ui: &mut Ui, rect: Rect, name: &str, label: &str| {
|
||||
let response = ui.interact(rect, self.id.with(name), Sense::click());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label));
|
||||
let color = if response.hovered() || response.has_focus() { style.text } else { style.weak_text };
|
||||
(response, Stroke::new(1.2, color))
|
||||
};
|
||||
let menu = menu_rect.zip(self.menu).map(|(menu_rect, label)| {
|
||||
let (response, stroke) = button(ui, menu_rect, "menu", label);
|
||||
let c = menu_rect.center();
|
||||
painter.add(egui::Shape::convex_polygon(vec![c + vec2(-3.5, -1.5), c + vec2(3.5, -1.5), c + vec2(0.0, 2.5)], stroke.color, Stroke::NONE));
|
||||
response
|
||||
});
|
||||
let close = close_rect.zip(self.close).map(|(close_rect, label)| {
|
||||
let (response, stroke) = button(ui, close_rect, "close", label);
|
||||
let r = Rect::from_center_size(close_rect.center(), Vec2::splat((side * 0.5).max(4.0)));
|
||||
painter.line_segment([r.left_top(), r.right_bottom()], stroke);
|
||||
painter.line_segment([r.right_top(), r.left_bottom()], stroke);
|
||||
response
|
||||
});
|
||||
TitleResponse { bar, menu, close }
|
||||
}
|
||||
}
|
||||
|
||||
/// One step of a title-bar move, from [`live_move`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum MoveStep {
|
||||
/// The rect follows the pointer, inside the bounds.
|
||||
Moving(Rect),
|
||||
/// Escape or window focus loss ended the move: the rect it started from.
|
||||
Canceled(Rect),
|
||||
/// Released over `pointer`, with the rect where it was dropped.
|
||||
Dropped { rect: Rect, pointer: Pos2 },
|
||||
}
|
||||
|
||||
/// Move `rect` with a drag on `bar` (usually [`TitleResponse::bar`]). The rect and the press
|
||||
/// position at drag start are kept in egui memory under the bar's id, so the window follows the
|
||||
/// pointer without drift. Escape or window focus loss ends the move and returns the start rect;
|
||||
/// the rest of that drag is ignored. `None` when the bar is not being moved.
|
||||
pub fn live_move(ctx: &Context, bar: &Response, rect: Rect, bounds: Rect) -> Option<MoveStep> {
|
||||
let key = bar.id.with("live-move");
|
||||
if bar.drag_started()
|
||||
&& let Some(origin) = ctx.input(|input| input.pointer.press_origin())
|
||||
{
|
||||
ctx.data_mut(|data| data.insert_temp(key, (rect, origin)));
|
||||
}
|
||||
let (start, origin) = ctx.data(|data| data.get_temp::<(Rect, Pos2)>(key))?;
|
||||
let forget = || ctx.data_mut(|data| data.remove::<(Rect, Pos2)>(key));
|
||||
if ctx.input(|input| input.key_pressed(Key::Escape) || !input.focused) {
|
||||
forget();
|
||||
return Some(MoveStep::Canceled(start));
|
||||
}
|
||||
let pointer = ctx.pointer_latest_pos().unwrap_or(origin);
|
||||
let moved = clamp(start.translate(pointer - origin), bounds);
|
||||
if bar.drag_stopped() {
|
||||
forget();
|
||||
return Some(MoveStep::Dropped { rect: moved, pointer });
|
||||
}
|
||||
if bar.dragged() {
|
||||
return Some(MoveStep::Moving(moved));
|
||||
}
|
||||
// The drag ended without a release on this bar (the bar was not shown).
|
||||
forget();
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
//! The shared docking command vocabulary (feature `serde`).
|
||||
//!
|
||||
//! Applications deserialize a control command's JSON params, with its id under `"command"`,
|
||||
//! into [`DockCommand`] and apply it. craft-ui does not depend on `serde_json`.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let mut params = params.clone();
|
||||
//! params["command"] = json!(id);
|
||||
//! let command: DockCommand<PanelId> = serde_json::from_value(params)?;
|
||||
//! let space = float_space(ctx, DOCK_ID).unwrap_or_else(|| FloatSpace::new(ctx.content_rect()));
|
||||
//! command.apply(&mut app.workspace, style.right_to_left, &space, |p| app.permissions(p))?;
|
||||
//! ```
|
||||
|
||||
use std::hash::Hash;
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
use super::{
|
||||
Action, DockError, FloatSpace, Layout, Permissions, Placement, Side, Target, Workspace, Zone, dock_model::Place, surface::DEFAULT_FLOAT,
|
||||
};
|
||||
use crate::layout::SplitSize;
|
||||
|
||||
/// A docking command, tagged by its control id under `"command"`.
|
||||
///
|
||||
/// Ids and params (`?` marks optional ones):
|
||||
///
|
||||
/// | Id | Params |
|
||||
/// |---|---|
|
||||
/// | `window.panel.layout` | `{action}`: a serialized [`Action`] |
|
||||
/// | `window.panel.move` | `{panel, anchor, zone?, before?, group?, placement?}` |
|
||||
/// | `window.panel.float` | `{panel, x?, y?, width?, height?, group?, column?}` |
|
||||
/// | `window.panel.dock` | `{panel, anchor?, zone?, before?, group?, column?, side?}` |
|
||||
/// | `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` |
|
||||
/// | `window.panel.minimize` | `{panel, minimized?}`; without `minimized` it toggles |
|
||||
/// | `window.panel.iconic` | `{panel, iconic?}`; without `iconic` it toggles |
|
||||
/// | `window.panel.window` | `{panel, native?}` (desktop) |
|
||||
/// | `window.workspace`, `.new`, `.delete` | `{name}` |
|
||||
/// | `window.workspace.reset`, `ui.dock.reset` | `{}` |
|
||||
/// | `window.workspace.lock` | `{locked?}`; without `locked` it toggles |
|
||||
/// | `ui.dock` | `{action}`, or `{operation, …}`, see [`DockOperation`] |
|
||||
///
|
||||
/// `zone` is `tab` (the default for `move` and `dock`), `center`, `left`, `right`, `top`,
|
||||
/// `bottom`, `above` or `below` (a new group in a dock column, or a split in a floating window). The side
|
||||
/// zones map onto the anchor's container with [`Placement::for_zone`]. `before`
|
||||
/// names the tab to insert before; `null` appends. `group` moves the panel's whole group,
|
||||
/// `column` its dock column. `side` is `Start` or `End`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "command", bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))]
|
||||
#[non_exhaustive]
|
||||
pub enum DockCommand<P> {
|
||||
#[serde(rename = "window.panel.layout")]
|
||||
Layout { action: Action<P> },
|
||||
#[serde(rename = "window.panel.move")]
|
||||
Move {
|
||||
panel: P,
|
||||
anchor: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
zone: Option<ZoneName>,
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
before: Option<Option<P>>,
|
||||
#[serde(default)]
|
||||
group: bool,
|
||||
/// A serialized [`Placement`]; it takes precedence over `zone` and `before`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
placement: Option<Placement<P>>,
|
||||
},
|
||||
#[serde(rename = "window.panel.float")]
|
||||
Float {
|
||||
panel: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
x: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
y: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
width: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
height: Option<f32>,
|
||||
#[serde(default)]
|
||||
group: bool,
|
||||
#[serde(default)]
|
||||
column: bool,
|
||||
},
|
||||
/// To `anchor`; else to a new column of the dock on `side` (a new dock when it has none);
|
||||
/// else with a `left`, `right`, `top` or `bottom` zone to a new frame on that outer edge
|
||||
/// ([`Placement::Edge`]); else a floating panel joins the first dock group (or frame) as a
|
||||
/// tab, and a docked one stays. A hidden panel without `anchor` and `side` is shown at its
|
||||
/// last location, then moved to the edge a zone names.
|
||||
#[serde(rename = "window.panel.dock")]
|
||||
Dock {
|
||||
panel: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
anchor: Option<P>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
zone: Option<ZoneName>,
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
before: Option<Option<P>>,
|
||||
#[serde(default)]
|
||||
group: bool,
|
||||
#[serde(default)]
|
||||
column: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
side: Option<Side>,
|
||||
},
|
||||
/// Select a panel; a hidden one is shown at its last location first.
|
||||
#[serde(rename = "window.panel.activate")]
|
||||
Activate { panel: P },
|
||||
#[serde(rename = "window.panel.close")]
|
||||
Close { panel: P },
|
||||
#[serde(rename = "window.panel.closeGroup")]
|
||||
CloseGroup { panel: P },
|
||||
#[serde(rename = "window.panel.closeOthers")]
|
||||
CloseOthers { panel: P },
|
||||
#[serde(rename = "window.panel.minimize")]
|
||||
Minimize {
|
||||
panel: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
minimized: Option<bool>,
|
||||
},
|
||||
#[serde(rename = "window.panel.iconic")]
|
||||
Iconic {
|
||||
panel: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
iconic: Option<bool>,
|
||||
},
|
||||
/// Move the panel's floating window to its own OS window (`native`, the default) or back.
|
||||
/// A docked panel's group floats first.
|
||||
#[serde(rename = "window.panel.window")]
|
||||
Window {
|
||||
panel: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
native: Option<bool>,
|
||||
},
|
||||
/// Switch to a named workspace. The application owns named workspaces.
|
||||
#[serde(rename = "window.workspace")]
|
||||
Workspace { name: String },
|
||||
#[serde(rename = "window.workspace.new")]
|
||||
NewWorkspace { name: String },
|
||||
#[serde(rename = "window.workspace.delete")]
|
||||
DeleteWorkspace { name: String },
|
||||
/// Reset the current workspace to its saved or built-in arrangement (application-owned).
|
||||
#[serde(rename = "window.workspace.reset", alias = "ui.dock.reset")]
|
||||
ResetWorkspace {},
|
||||
#[serde(rename = "window.workspace.lock")]
|
||||
Lock {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
locked: Option<bool>,
|
||||
},
|
||||
/// The `ui.dock` shape of LightCraft, PDFCraft, CADCraft and SoundCraft.
|
||||
#[serde(rename = "ui.dock")]
|
||||
UiDock(UiDock<P>),
|
||||
}
|
||||
|
||||
/// `ui.dock` params: a raw action, or an operation.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(untagged, bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))]
|
||||
pub enum UiDock<P> {
|
||||
Action { action: Action<P> },
|
||||
Operation(DockOperation<P>),
|
||||
}
|
||||
|
||||
/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone`
|
||||
/// (default `center`) and `before`, which only applies to a center move.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "operation", rename_all = "camelCase", bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))]
|
||||
#[non_exhaustive]
|
||||
pub enum DockOperation<P> {
|
||||
/// Show a panel at its last location and select it.
|
||||
Open {
|
||||
panel: P,
|
||||
},
|
||||
Close {
|
||||
panel: P,
|
||||
},
|
||||
Activate {
|
||||
panel: P,
|
||||
},
|
||||
Float {
|
||||
panel: P,
|
||||
rect: [f32; 4],
|
||||
},
|
||||
MoveFloating {
|
||||
panel: P,
|
||||
rect: [f32; 4],
|
||||
},
|
||||
Move {
|
||||
panel: P,
|
||||
target: P,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
zone: Option<ZoneName>,
|
||||
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
|
||||
before: Option<Option<P>>,
|
||||
},
|
||||
SetStackOpen {
|
||||
panel: P,
|
||||
open: bool,
|
||||
},
|
||||
/// `height` is required; `null` clears it.
|
||||
ResizeStack {
|
||||
panel: P,
|
||||
#[serde(deserialize_with = "required")]
|
||||
height: Option<f32>,
|
||||
},
|
||||
ResizeSplit {
|
||||
path: Vec<bool>,
|
||||
size: SplitSize,
|
||||
},
|
||||
}
|
||||
|
||||
/// A drop zone by name, as control protocols write it. PascalCase [`Zone`] names also parse.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ZoneName {
|
||||
Tab,
|
||||
#[serde(alias = "Center")]
|
||||
Center,
|
||||
#[serde(alias = "Left")]
|
||||
Left,
|
||||
#[serde(alias = "Right")]
|
||||
Right,
|
||||
#[serde(alias = "Top")]
|
||||
Top,
|
||||
#[serde(alias = "Bottom")]
|
||||
Bottom,
|
||||
Above,
|
||||
Below,
|
||||
}
|
||||
|
||||
/// A present field, `null` included: `Some(None)` for `null`, `None` when absent.
|
||||
fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
/// A required field that may be `null`.
|
||||
fn required<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> {
|
||||
T::deserialize(deserializer)
|
||||
}
|
||||
|
||||
/// Where a command puts what it moves relative to `anchor`: `zone` and `before`, with side
|
||||
/// zones mapped by [`Placement::for_zone`]. `default` is the zone when none is given.
|
||||
struct Zoned<'a, P> {
|
||||
layout: &'a Layout<P>,
|
||||
right_to_left: bool,
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> Zoned<'_, P> {
|
||||
fn placement(&self, anchor: &P, zone: Option<ZoneName>, before: &Option<Option<P>>, default: ZoneName) -> Result<Placement<P>, DockError> {
|
||||
let side = |zone| Placement::for_zone(self.layout, anchor, zone, self.right_to_left);
|
||||
Ok(match (zone.unwrap_or(default), before.clone()) {
|
||||
(ZoneName::Tab | ZoneName::Center, Some(before)) => Placement::Tab { before },
|
||||
(ZoneName::Tab, None) => Placement::Tab { before: None },
|
||||
(ZoneName::Center, None) => Placement::Split(Zone::Center),
|
||||
(_, Some(_)) => return Err(DockError::InvalidPlacement),
|
||||
(ZoneName::Left, None) => side(Zone::Left)?,
|
||||
(ZoneName::Right, None) => side(Zone::Right)?,
|
||||
(ZoneName::Top, None) => side(Zone::Top)?,
|
||||
(ZoneName::Bottom, None) => side(Zone::Bottom)?,
|
||||
(ZoneName::Above, None) => Placement::Group { below: false, height: None },
|
||||
(ZoneName::Below, None) => Placement::Group { below: true, height: None },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of the layout a command moves.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Unit {
|
||||
Panel,
|
||||
Group,
|
||||
Column,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
fn of(group: bool, column: bool) -> Self {
|
||||
if column {
|
||||
Self::Column
|
||||
} else if group {
|
||||
Self::Group
|
||||
} else {
|
||||
Self::Panel
|
||||
}
|
||||
}
|
||||
|
||||
/// The action that moves this unit of `panel` to `to`. A floating panel's column is its
|
||||
/// whole window.
|
||||
fn to<P: Clone + Eq + Hash>(self, layout: &Layout<P>, panel: &P, to: Target<P>) -> Result<Action<P>, DockError> {
|
||||
let floating = matches!(layout.place(panel), Some(Place::Floating { .. }));
|
||||
let panel = panel.clone();
|
||||
Ok(match (self, to) {
|
||||
(Self::Panel, Target::At { anchor, placement }) => Action::Move { panel, anchor, placement },
|
||||
(Self::Panel, to) => Action::MovePanel { panel, to },
|
||||
(Self::Group, to) => Action::MoveGroup { panel, to },
|
||||
(Self::Column, to) if floating => Action::MoveWindow { panel, to },
|
||||
(Self::Column, to) => Action::MoveColumn { panel, to },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> DockCommand<P> {
|
||||
/// Every command id, for an application's command registry.
|
||||
pub const IDS: &'static [&'static str] = &[
|
||||
"window.panel.layout",
|
||||
"window.panel.move",
|
||||
"window.panel.float",
|
||||
"window.panel.dock",
|
||||
"window.panel.activate",
|
||||
"window.panel.close",
|
||||
"window.panel.closeGroup",
|
||||
"window.panel.closeOthers",
|
||||
"window.panel.minimize",
|
||||
"window.panel.iconic",
|
||||
"window.panel.window",
|
||||
"window.workspace",
|
||||
"window.workspace.new",
|
||||
"window.workspace.delete",
|
||||
"window.workspace.reset",
|
||||
"window.workspace.lock",
|
||||
"ui.dock",
|
||||
"ui.dock.reset",
|
||||
];
|
||||
|
||||
/// Named workspaces and Reset belong to the application, which handles these commands
|
||||
/// before [`Self::apply`].
|
||||
pub fn is_app_owned(&self) -> bool {
|
||||
matches!(self, Self::Workspace { .. } | Self::NewWorkspace { .. } | Self::DeleteWorkspace { .. } | Self::ResetWorkspace {})
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> DockCommand<P> {
|
||||
/// The layout actions this command makes on `workspace`, to apply all or none.
|
||||
/// Showing a hidden panel and Lock change more than the layout, and named workspaces
|
||||
/// belong to the application: those return [`DockError::NotAllowed`]; use [`Self::apply`].
|
||||
/// A panel or anchor that is not shown returns [`DockError::MissingPanel`] or
|
||||
/// [`DockError::MissingTarget`].
|
||||
///
|
||||
/// `left`, `right`, `top` and `bottom` zones follow [`Placement::for_zone`]: beside a docked
|
||||
/// anchor they make a new column or group, and `right_to_left` is the
|
||||
/// [`super::DockStyle::right_to_left`] the layout is drawn with.
|
||||
///
|
||||
/// `space` is where `window.panel.float` floats what it moves when it gives no rect: at the
|
||||
/// size a drag would float it at, inside the dock area and clear of the app's menu bar. Pass
|
||||
/// [`super::float_space`] of the area that draws `workspace`. Given `x`, `y`, `width` and
|
||||
/// `height` replace the matching values, and a group or column that is already a whole
|
||||
/// floating window keeps its rect.
|
||||
pub fn to_actions(&self, workspace: &Workspace<P>, right_to_left: bool, space: &FloatSpace<P>) -> Result<Vec<Action<P>>, DockError> {
|
||||
let layout = &workspace.layout;
|
||||
let zoned = Zoned { layout, right_to_left };
|
||||
let shown = |panel: &P| if layout.contains(panel) { Ok(()) } else { Err(DockError::MissingPanel) };
|
||||
let one = |action: Action<P>| Ok(vec![action]);
|
||||
match self {
|
||||
Self::Layout { action } | Self::UiDock(UiDock::Action { action }) => one(action.clone()),
|
||||
Self::Move { panel, anchor, zone, before, group, placement: given } => {
|
||||
shown(panel)?;
|
||||
let placement = match given {
|
||||
Some(placement) => placement.clone(),
|
||||
None => zoned.placement(anchor, *zone, before, ZoneName::Tab)?,
|
||||
};
|
||||
one(Unit::of(*group, false).to(layout, panel, Target::At { anchor: anchor.clone(), placement })?)
|
||||
}
|
||||
Self::Float { panel, x, y, width, height, group, column } => {
|
||||
shown(panel)?;
|
||||
let given = [*x, *y, *width, *height];
|
||||
let window = layout.floating.iter().find(|w| w.contains(panel)).map(|w| w.rect);
|
||||
let rect = |base: [f32; 4]| {
|
||||
let mut rect = base;
|
||||
for (value, given) in rect.iter_mut().zip(given) {
|
||||
*value = given.unwrap_or(*value);
|
||||
}
|
||||
rect
|
||||
};
|
||||
let any = given.iter().any(Option::is_some);
|
||||
let unit = Unit::of(*group, *column);
|
||||
let lone = layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1);
|
||||
let whole =
|
||||
layout.floating.iter().any(|w| w.contains(panel) && matches!(w.root, super::Node::Tabs { .. } | super::Node::Stack { .. }));
|
||||
// The rect a drag would float the unit at, inside the area.
|
||||
let placed = || {
|
||||
let docked = layout.location(panel).ok().and_then(|l| l.group).and_then(|g| g.column).map(|c| c.width);
|
||||
let fallback = egui::vec2(docked.filter(|_| !matches!(unit, Unit::Panel)).unwrap_or(DEFAULT_FLOAT.x), DEFAULT_FLOAT.y);
|
||||
let size = match unit {
|
||||
Unit::Panel => space.panel(panel),
|
||||
Unit::Group => space.group(panel),
|
||||
Unit::Column => space.column(panel),
|
||||
};
|
||||
rect(space.place(size.unwrap_or(fallback)))
|
||||
};
|
||||
match (unit, window) {
|
||||
(Unit::Panel, Some(base)) if lone => one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }),
|
||||
(Unit::Column, Some(base)) => one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }),
|
||||
// Without given values the window keeps its rect and native state.
|
||||
(Unit::Group, Some(base)) if whole => one(unit.to(layout, panel, Target::Float { rect: any.then(|| rect(base)) })?),
|
||||
(Unit::Panel, _) => one(Action::Float { panel: panel.clone(), rect: placed() }),
|
||||
(unit, _) => one(unit.to(layout, panel, Target::Float { rect: Some(placed()) })?),
|
||||
}
|
||||
}
|
||||
Self::Dock { panel, anchor, zone, before, group, column, side } => {
|
||||
shown(panel)?;
|
||||
let unit = Unit::of(*group, *column);
|
||||
if let Some(anchor) = anchor {
|
||||
let placement = zoned.placement(anchor, *zone, before, ZoneName::Tab)?;
|
||||
return one(unit.to(layout, panel, Target::At { anchor: anchor.clone(), placement })?);
|
||||
}
|
||||
if let Some(side) = side {
|
||||
let to = match last_column(layout, *side) {
|
||||
Some(column) => match column.into_iter().find(|p| !members(layout, panel, unit).contains(p)) {
|
||||
Some(anchor) => Target::At { anchor, placement: Placement::Column { after: true } },
|
||||
// What moves already is that dock's last column.
|
||||
None => return Ok(Vec::new()),
|
||||
},
|
||||
None => Target::NewDock { side: *side },
|
||||
};
|
||||
let unit = match (unit, &to) {
|
||||
(Unit::Panel, Target::NewDock { .. }) if group_len(layout, panel) == Some(1) => Unit::Group,
|
||||
(unit, _) => unit,
|
||||
};
|
||||
return one(unit.to(layout, panel, to)?);
|
||||
}
|
||||
let members = members(layout, panel, unit);
|
||||
if let Some(zone) = self.edge() {
|
||||
if before.is_some() {
|
||||
return Err(DockError::InvalidPlacement);
|
||||
}
|
||||
let anchor = layout
|
||||
.panels()
|
||||
.into_iter()
|
||||
.find(|p| !members.contains(p) && matches!(layout.place(p), Some(Place::Dock { .. } | Place::Node(_))))
|
||||
.cloned()
|
||||
.ok_or(DockError::MissingTarget)?;
|
||||
return one(unit.to(layout, panel, Target::At { anchor, placement: Placement::Edge(zone) })?);
|
||||
}
|
||||
if !matches!(layout.place(panel), Some(Place::Floating { .. })) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let panels = layout.panels();
|
||||
let free = || panels.iter().copied().filter(|p| !members.contains(p));
|
||||
let docked = free().find(|p| matches!(layout.place(p), Some(Place::Dock { .. })));
|
||||
let framed = || free().find(|p| matches!(layout.place(p), Some(Place::Node(_))));
|
||||
let anchor = docked.or_else(framed).cloned().ok_or(DockError::MissingTarget)?;
|
||||
one(unit.to(layout, panel, Target::At { anchor, placement: Placement::Tab { before: None } })?)
|
||||
}
|
||||
Self::Activate { panel } => {
|
||||
shown(panel)?;
|
||||
one(Action::Activate { panel: panel.clone() })
|
||||
}
|
||||
Self::Close { panel } => one(Action::Close { panel: panel.clone() }),
|
||||
Self::CloseGroup { panel } => one(Action::CloseGroup { panel: panel.clone() }),
|
||||
Self::CloseOthers { panel } => one(Action::CloseOthers { panel: panel.clone() }),
|
||||
Self::Minimize { panel, minimized } => {
|
||||
let place = layout.place(panel).ok_or(DockError::MissingPanel)?;
|
||||
// An accordion entry is minimized while it is closed.
|
||||
let current = match &place {
|
||||
Place::Node(path) => match layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, path)) {
|
||||
Some(super::Node::Stack { entries }) => entries.iter().any(|e| &e.panel == panel && !e.open),
|
||||
_ => false,
|
||||
},
|
||||
Place::Floating { window, .. } => layout.floating.get(*window).is_some_and(|w| w.minimized),
|
||||
place => layout.group(place).is_some_and(|g| g.minimized),
|
||||
};
|
||||
one(Action::SetMinimized { panel: panel.clone(), minimized: minimized.unwrap_or(!current) })
|
||||
}
|
||||
Self::Iconic { panel, iconic } => {
|
||||
let location = layout.location(panel)?;
|
||||
let current = location.group.and_then(|g| g.column).is_some_and(|c| c.iconic);
|
||||
one(Action::SetIconic { panel: panel.clone(), iconic: iconic.unwrap_or(!current) })
|
||||
}
|
||||
Self::Window { panel, native } => {
|
||||
shown(panel)?;
|
||||
if !native.unwrap_or(true) {
|
||||
return one(Action::SetNative { panel: panel.clone(), rect: None });
|
||||
}
|
||||
let mut actions = Vec::new();
|
||||
let mut scratch = layout.clone();
|
||||
if !scratch.floating.iter().any(|w| w.contains(panel)) {
|
||||
let float = Action::MoveGroup { panel: panel.clone(), to: Target::Float { rect: None } };
|
||||
scratch.apply(float.clone())?;
|
||||
actions.push(float);
|
||||
}
|
||||
let rect = scratch.floating.iter().find(|w| w.contains(panel)).map(|w| w.rect).ok_or(DockError::MissingPanel)?;
|
||||
actions.push(Action::SetNative { panel: panel.clone(), rect: Some(rect) });
|
||||
Ok(actions)
|
||||
}
|
||||
Self::UiDock(UiDock::Operation(operation)) => match operation {
|
||||
DockOperation::Open { panel } | DockOperation::Activate { panel } => {
|
||||
shown(panel)?;
|
||||
one(Action::Activate { panel: panel.clone() })
|
||||
}
|
||||
DockOperation::Close { panel } => one(Action::Close { panel: panel.clone() }),
|
||||
DockOperation::Float { panel, rect } => one(Action::Float { panel: panel.clone(), rect: *rect }),
|
||||
DockOperation::MoveFloating { panel, rect } => one(Action::MoveFloating { panel: panel.clone(), rect: *rect }),
|
||||
DockOperation::Move { panel, target, zone, before } => {
|
||||
let placement = zoned.placement(target, *zone, before, ZoneName::Center)?;
|
||||
one(Action::Move { panel: panel.clone(), anchor: target.clone(), placement })
|
||||
}
|
||||
DockOperation::SetStackOpen { panel, open } => one(Action::SetStackOpen { panel: panel.clone(), open: *open }),
|
||||
DockOperation::ResizeStack { panel, height } => one(Action::ResizeStack { panel: panel.clone(), height: *height }),
|
||||
DockOperation::ResizeSplit { path, size } => one(Action::ResizeSplit { path: path.clone(), size: *size }),
|
||||
},
|
||||
Self::Workspace { .. } | Self::NewWorkspace { .. } | Self::DeleteWorkspace { .. } | Self::ResetWorkspace {} | Self::Lock { .. } => {
|
||||
Err(DockError::NotAllowed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the command to `workspace`, all or nothing, and return the panels it closed so
|
||||
/// the application can release their state. Showing a hidden panel restores its last
|
||||
/// location; Lock sets [`Workspace::locked`]. Application-owned commands
|
||||
/// ([`Self::is_app_owned`]) return [`DockError::NotAllowed`] and change nothing.
|
||||
/// `space` is where `window.panel.float` floats, as for [`Self::to_actions`].
|
||||
pub fn apply(
|
||||
&self,
|
||||
workspace: &mut Workspace<P>,
|
||||
right_to_left: bool,
|
||||
space: &FloatSpace<P>,
|
||||
permissions: impl Fn(&P) -> Permissions,
|
||||
) -> Result<Vec<P>, DockError> {
|
||||
let show = match self {
|
||||
Self::Activate { panel }
|
||||
| Self::Dock { panel, anchor: None, side: None, .. }
|
||||
| Self::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) => Some(panel),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(panel) = show.filter(|p| !workspace.layout.contains(p)) {
|
||||
if self.edge().is_none() {
|
||||
workspace.set_visible(panel.clone(), true, None, &permissions)?;
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// Shown, then moved to the edge, all or nothing.
|
||||
let mut shown = workspace.clone();
|
||||
shown.set_visible(panel.clone(), true, None, &permissions)?;
|
||||
let closed = shown.apply_all(self.to_actions(&shown, right_to_left, space)?, permissions)?;
|
||||
*workspace = shown;
|
||||
return Ok(closed);
|
||||
}
|
||||
if let Self::Lock { locked } = self {
|
||||
workspace.locked = locked.unwrap_or(!workspace.locked);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let actions = self.to_actions(workspace, right_to_left, space)?;
|
||||
workspace.apply_all(actions, permissions)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> DockCommand<P> {
|
||||
/// The outer edge `window.panel.dock` goes to: a side zone without an anchor or side.
|
||||
fn edge(&self) -> Option<Zone> {
|
||||
match self {
|
||||
Self::Dock { anchor: None, side: None, zone: Some(zone), .. } => match zone {
|
||||
ZoneName::Left => Some(Zone::Left),
|
||||
ZoneName::Right => Some(Zone::Right),
|
||||
ZoneName::Top => Some(Zone::Top),
|
||||
ZoneName::Bottom => Some(Zone::Bottom),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The panels of the last column of the dock on `side`, or `None` without such a dock.
|
||||
fn last_column<P: Clone + Eq + Hash>(layout: &Layout<P>, side: Side) -> Option<Vec<P>> {
|
||||
let path = layout.dock_path(side)?;
|
||||
let node = layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, &path))?;
|
||||
match node {
|
||||
super::Node::Dock { columns, .. } => Some(columns.last()?.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn group_len<P: Clone + Eq + Hash>(layout: &Layout<P>, panel: &P) -> Option<usize> {
|
||||
layout.members(panel, super::dock_model::Unit::Group).ok().map(|members| members.len())
|
||||
}
|
||||
|
||||
/// The panels that move with `panel`.
|
||||
fn members<P: Clone + Eq + Hash>(layout: &Layout<P>, panel: &P, unit: Unit) -> Vec<P> {
|
||||
match unit {
|
||||
Unit::Panel => vec![panel.clone()],
|
||||
Unit::Group => layout.members(panel, super::dock_model::Unit::Group).unwrap_or_default(),
|
||||
Unit::Column => match layout.place(panel) {
|
||||
Some(Place::Dock { path, column, .. }) => match layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, &path)) {
|
||||
Some(super::Node::Dock { columns, .. }) => {
|
||||
columns.get(column).map(|c| c.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect()).unwrap_or_default()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
},
|
||||
Some(Place::Floating { .. }) => {
|
||||
layout.floating.iter().find(|w| w.contains(panel)).map(|w| w.panels().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
_ => vec![panel.clone()],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
//! `DockCommand`: every documented shape parses and maps to atomic layout actions.
|
||||
#![cfg(feature = "serde")]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
|
||||
type P = String;
|
||||
|
||||
fn s(panel: &str) -> P {
|
||||
panel.to_owned()
|
||||
}
|
||||
|
||||
fn permissions(panel: &P) -> Permissions {
|
||||
if panel == "canvas" { Permissions::PROTECTED } else { Permissions::default() }
|
||||
}
|
||||
|
||||
/// A start dock with one column of `[layers, channels]` and `[history]` beside the canvas, a
|
||||
/// floating `color`, and `swatches` hidden from history's group.
|
||||
fn workspace() -> Workspace<P> {
|
||||
let groups = vec![Group::new(vec![s("layers"), s("channels")], 0), Group::new(vec![s("history"), s("swatches")], 0)];
|
||||
let dock = Node::Dock { side: Side::Start, columns: vec![Column::new(groups, 240.0)] };
|
||||
let canvas = Node::Tabs { panels: vec![s("canvas")], active: 0 };
|
||||
let layout = Layout {
|
||||
root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), first: Box::new(dock), second: Box::new(canvas) }),
|
||||
floating: vec![Floating::single(vec![s("color")], 0, [300.0, 200.0, 200.0, 150.0])],
|
||||
};
|
||||
let mut workspace = Workspace::new(layout);
|
||||
workspace.apply(Action::Close { panel: s("swatches") }, permissions).unwrap();
|
||||
workspace
|
||||
}
|
||||
|
||||
/// An 800x600 dock area that has drawn nothing.
|
||||
fn space() -> FloatSpace<P> {
|
||||
FloatSpace::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)))
|
||||
}
|
||||
|
||||
fn parse(params: Value) -> Result<DockCommand<P>, serde_json::Error> {
|
||||
serde_json::from_value(params)
|
||||
}
|
||||
|
||||
/// The actions `params` makes on a fresh workspace.
|
||||
fn actions(params: Value) -> Vec<Action<P>> {
|
||||
let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}"));
|
||||
command.to_actions(&workspace(), false, &space()).unwrap_or_else(|e| panic!("{params}: {e}"))
|
||||
}
|
||||
|
||||
/// Apply `params` to a fresh workspace; return it and the panels closed.
|
||||
fn applied(params: Value) -> (Workspace<P>, Vec<P>) {
|
||||
let mut workspace = workspace();
|
||||
let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}"));
|
||||
let closed = command.apply(&mut workspace, false, &space(), permissions).unwrap_or_else(|e| panic!("{params}: {e}"));
|
||||
(workspace, closed)
|
||||
}
|
||||
|
||||
/// `params` parses but applying it fails with `error` and changes nothing.
|
||||
fn rejected(params: Value, error: DockError) {
|
||||
let mut workspace = workspace();
|
||||
let before = workspace.clone();
|
||||
let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}"));
|
||||
assert_eq!(command.apply(&mut workspace, false, &space(), permissions), Err(error), "{params}");
|
||||
assert_eq!(workspace, before, "{params}");
|
||||
}
|
||||
|
||||
fn tab(before: Option<&str>) -> Placement<P> {
|
||||
Placement::Tab { before: before.map(s) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut id = |params: Value| {
|
||||
seen.insert(params["command"].as_str().unwrap().to_owned());
|
||||
params
|
||||
};
|
||||
|
||||
// The raw action form, in both protocols.
|
||||
let raw = json!({"MoveFloating": {"panel": "color", "rect": [44, 66, 360, 450]}});
|
||||
let moved = vec![Action::MoveFloating { panel: s("color"), rect: [44.0, 66.0, 360.0, 450.0] }];
|
||||
assert_eq!(actions(id(json!({"command": "window.panel.layout", "action": raw}))), moved);
|
||||
assert_eq!(actions(id(json!({"command": "ui.dock", "action": raw}))), moved);
|
||||
|
||||
// move: tab by default, before a tab or appended, zones, a serialized placement, a group.
|
||||
let mv = |placement| vec![Action::Move { panel: s("history"), anchor: s("layers"), placement }];
|
||||
let base = json!({"command": "window.panel.move", "panel": "history", "anchor": "layers"});
|
||||
let with = |extra: Value| {
|
||||
let mut params = base.clone();
|
||||
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
params
|
||||
};
|
||||
assert_eq!(actions(id(base.clone())), mv(tab(None)));
|
||||
assert_eq!(actions(with(json!({"before": "channels"}))), mv(tab(Some("channels"))));
|
||||
assert_eq!(actions(with(json!({"zone": "center", "before": null}))), mv(tab(None)));
|
||||
assert_eq!(actions(with(json!({"zone": "center"}))), mv(Placement::Split(Zone::Center)));
|
||||
assert_eq!(actions(with(json!({"zone": "Left"}))), mv(Placement::Column { after: false }));
|
||||
assert_eq!(actions(with(json!({"zone": "below"}))), mv(Placement::Group { below: true, height: None }));
|
||||
assert_eq!(actions(with(json!({"placement": {"Column": {"after": true}}}))), mv(Placement::Column { after: true }));
|
||||
assert_eq!(
|
||||
actions(with(json!({"group": true, "zone": "above"}))),
|
||||
vec![Action::MoveGroup {
|
||||
panel: s("history"),
|
||||
to: Target::At { anchor: s("layers"), placement: Placement::Group { below: false, height: None } }
|
||||
}]
|
||||
);
|
||||
|
||||
// float: a docked panel, a lone floating panel, a group and a column.
|
||||
assert_eq!(
|
||||
actions(id(json!({"command": "window.panel.float", "panel": "layers", "x": 10, "y": 20}))),
|
||||
vec![Action::Float { panel: s("layers"), rect: [10.0, 20.0, 260.0, 320.0] }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.float", "panel": "color", "width": 320})),
|
||||
vec![Action::MoveFloating { panel: s("color"), rect: [300.0, 200.0, 320.0, 150.0] }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.float", "panel": "layers", "group": true})),
|
||||
vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: Some([24.0, 24.0, 240.0, 320.0]) } }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.float", "panel": "history", "column": true})),
|
||||
vec![Action::MoveColumn { panel: s("history"), to: Target::Float { rect: Some([24.0, 24.0, 240.0, 320.0]) } }]
|
||||
);
|
||||
|
||||
// dock: to an anchor, to a side, back into the dock, and a hidden panel to its last place.
|
||||
assert_eq!(
|
||||
actions(id(json!({"command": "window.panel.dock", "panel": "color", "anchor": "history", "zone": "tab"}))),
|
||||
vec![Action::Move { panel: s("color"), anchor: s("history"), placement: tab(None) }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.dock", "panel": "color", "side": "End"})),
|
||||
vec![Action::MoveGroup { panel: s("color"), to: Target::NewDock { side: Side::End } }]
|
||||
);
|
||||
let new_column = Target::At { anchor: s("layers"), placement: Placement::Column { after: true } };
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.dock", "panel": "color", "column": true, "side": "Start"})),
|
||||
vec![Action::MoveWindow { panel: s("color"), to: new_column.clone() }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.dock", "panel": "history", "group": true, "side": "Start"})),
|
||||
vec![Action::MoveGroup { panel: s("history"), to: new_column }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.dock", "panel": "color"})),
|
||||
vec![Action::Move { panel: s("color"), anchor: s("layers"), placement: tab(None) }]
|
||||
);
|
||||
assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "layers"})), vec![]);
|
||||
let (shown, _) = applied(json!({"command": "window.panel.dock", "panel": "swatches"}));
|
||||
assert!(shown.layout.contains(&s("swatches")) && shown.hidden.is_empty());
|
||||
|
||||
// activate shows a hidden panel; close actions report what they closed.
|
||||
let (shown, _) = applied(id(json!({"command": "window.panel.activate", "panel": "swatches"})));
|
||||
assert!(shown.layout.contains(&s("swatches")));
|
||||
assert_eq!(actions(json!({"command": "window.panel.activate", "panel": "channels"})), vec![Action::Activate { panel: s("channels") }]);
|
||||
assert_eq!(applied(id(json!({"command": "window.panel.close", "panel": "channels"}))).1, vec![s("channels")]);
|
||||
assert_eq!(applied(id(json!({"command": "window.panel.closeGroup", "panel": "channels"}))).1, vec![s("layers"), s("channels")]);
|
||||
assert_eq!(applied(id(json!({"command": "window.panel.closeOthers", "panel": "channels"}))).1, vec![s("layers")]);
|
||||
|
||||
// minimize and iconic toggle without a value.
|
||||
assert_eq!(
|
||||
actions(id(json!({"command": "window.panel.minimize", "panel": "layers"}))),
|
||||
vec![Action::SetMinimized { panel: s("layers"), minimized: true }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.minimize", "panel": "layers", "minimized": false})),
|
||||
vec![Action::SetMinimized { panel: s("layers"), minimized: false }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(id(json!({"command": "window.panel.iconic", "panel": "history"}))),
|
||||
vec![Action::SetIconic { panel: s("history"), iconic: true }]
|
||||
);
|
||||
|
||||
// window: a floating window goes native at its rect; a docked group floats first.
|
||||
assert_eq!(
|
||||
actions(id(json!({"command": "window.panel.window", "panel": "color"}))),
|
||||
vec![Action::SetNative { panel: s("color"), rect: Some([300.0, 200.0, 200.0, 150.0]) }]
|
||||
);
|
||||
let docked = actions(json!({"command": "window.panel.window", "panel": "layers"}));
|
||||
assert!(
|
||||
matches!(docked.as_slice(), [Action::MoveGroup { to: Target::Float { rect: None }, .. }, Action::SetNative { rect: Some(_), .. }]),
|
||||
"{docked:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
actions(json!({"command": "window.panel.window", "panel": "color", "native": false})),
|
||||
vec![Action::SetNative { panel: s("color"), rect: None }]
|
||||
);
|
||||
|
||||
// Named workspaces and Reset belong to the application.
|
||||
for params in [
|
||||
json!({"command": "window.workspace", "name": "Painting"}),
|
||||
json!({"command": "window.workspace.new", "name": "Mine"}),
|
||||
json!({"command": "window.workspace.delete", "name": "Mine"}),
|
||||
json!({"command": "window.workspace.reset"}),
|
||||
json!({"command": "ui.dock.reset"}),
|
||||
] {
|
||||
let command = parse(id(params.clone())).unwrap();
|
||||
assert!(command.is_app_owned(), "{params}");
|
||||
rejected(params, DockError::NotAllowed);
|
||||
}
|
||||
assert_eq!(parse(json!({"command": "ui.dock.reset"})).unwrap(), DockCommand::ResetWorkspace {});
|
||||
|
||||
// Lock toggles or sets.
|
||||
assert!(applied(id(json!({"command": "window.workspace.lock"}))).0.locked);
|
||||
assert!(!applied(json!({"command": "window.workspace.lock", "locked": false})).0.locked);
|
||||
|
||||
// The small apps' ui.dock operations.
|
||||
let op = |params: Value| {
|
||||
let mut params = params;
|
||||
params["command"] = json!("ui.dock");
|
||||
params
|
||||
};
|
||||
let (shown, _) = applied(op(json!({"operation": "open", "panel": "swatches"})));
|
||||
assert!(shown.layout.contains(&s("swatches")));
|
||||
assert_eq!(actions(op(json!({"operation": "close", "panel": "layers"}))), vec![Action::Close { panel: s("layers") }]);
|
||||
assert_eq!(actions(op(json!({"operation": "activate", "panel": "channels"}))), vec![Action::Activate { panel: s("channels") }]);
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "float", "panel": "layers", "rect": [1, 2, 300, 200]}))),
|
||||
vec![Action::Float { panel: s("layers"), rect: [1.0, 2.0, 300.0, 200.0] }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "moveFloating", "panel": "color", "rect": [1, 2, 300, 200]}))),
|
||||
vec![Action::MoveFloating { panel: s("color"), rect: [1.0, 2.0, 300.0, 200.0] }]
|
||||
);
|
||||
let to_layers = |placement| vec![Action::Move { panel: s("color"), anchor: s("layers"), placement }];
|
||||
assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers"}))), to_layers(Placement::Split(Zone::Center)));
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "left"}))),
|
||||
to_layers(Placement::Column { after: false })
|
||||
);
|
||||
assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": null}))), to_layers(tab(None)));
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": "channels"}))),
|
||||
to_layers(tab(Some("channels")))
|
||||
);
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "setStackOpen", "panel": "layers", "open": false}))),
|
||||
vec![Action::SetStackOpen { panel: s("layers"), open: false }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "resizeStack", "panel": "layers", "height": null}))),
|
||||
vec![Action::ResizeStack { panel: s("layers"), height: None }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "resizeStack", "panel": "layers", "height": 120}))),
|
||||
vec![Action::ResizeStack { panel: s("layers"), height: Some(120.0) }]
|
||||
);
|
||||
assert_eq!(
|
||||
actions(op(json!({"operation": "resizeSplit", "path": [], "size": {"Ratio": 0.35}}))),
|
||||
vec![Action::ResizeSplit { path: vec![], size: SplitSize::Ratio(0.35) }]
|
||||
);
|
||||
|
||||
let ids: BTreeSet<String> = DockCommand::<P>::IDS.iter().map(|id| (*id).to_owned()).collect();
|
||||
assert_eq!(seen, ids, "one case per id");
|
||||
|
||||
// Bad params: parse errors, or a DockError with nothing changed.
|
||||
for params in [
|
||||
json!({"command": "window.panel.unknown", "panel": "layers"}),
|
||||
json!({"command": "window.panel.move", "panel": "layers"}),
|
||||
json!({"command": "window.panel.move", "panel": "layers", "anchor": "history", "zone": "middle"}),
|
||||
json!({"command": "window.panel.minimize", "panel": "layers", "minimized": "yes"}),
|
||||
op(json!({"operation": "spin", "panel": "layers"})),
|
||||
op(json!({"operation": "float", "panel": "layers", "rect": [1, 2, 3]})),
|
||||
op(json!({"operation": "resizeStack", "panel": "layers"})),
|
||||
op(json!({"operation": "setStackOpen", "panel": "layers"})),
|
||||
op(json!({"operation": "move", "panel": "layers"})),
|
||||
] {
|
||||
assert!(parse(params.clone()).is_err(), "{params}");
|
||||
}
|
||||
rejected(json!({"command": "window.panel.move", "panel": "layers", "anchor": "nowhere"}), DockError::MissingTarget);
|
||||
rejected(json!({"command": "window.panel.move", "panel": "nowhere", "anchor": "layers"}), DockError::MissingPanel);
|
||||
rejected(
|
||||
json!({"command": "window.panel.move", "panel": "layers", "anchor": "history", "zone": "left", "before": null}),
|
||||
DockError::InvalidPlacement,
|
||||
);
|
||||
rejected(json!({"command": "window.panel.float", "panel": "layers", "width": 1e30}), DockError::InvalidGeometry);
|
||||
rejected(json!({"command": "window.panel.move", "panel": "canvas", "anchor": "layers"}), DockError::NotAllowed);
|
||||
rejected(op(json!({"operation": "moveFloating", "panel": "color", "rect": [0, 0, -5, 10]})), DockError::InvalidGeometry);
|
||||
rejected(
|
||||
op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "top", "before": "channels"})),
|
||||
DockError::InvalidPlacement,
|
||||
);
|
||||
rejected(op(json!({"operation": "resizeSplit", "path": [true, true, true], "size": {"Ratio": 0.5}})), DockError::MissingTarget);
|
||||
// A docked group cannot float into a native window when locked.
|
||||
let mut locked = workspace();
|
||||
locked.locked = true;
|
||||
let before = locked.clone();
|
||||
assert!(parse(json!({"command": "window.panel.window", "panel": "layers"})).unwrap().apply(&mut locked, false, &space(), permissions).is_err());
|
||||
assert_eq!(locked, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_zones_map_to_the_placement_the_anchor_container_takes_in_either_direction() {
|
||||
let command =
|
||||
|zone: &str, anchor: &str| parse(json!({"command": "window.panel.move", "panel": "history", "anchor": anchor, "zone": zone})).unwrap();
|
||||
let placed = |zone: &str, anchor: &str, rtl: bool| match command(zone, anchor).to_actions(&workspace(), rtl, &space()) {
|
||||
Ok(actions) => match actions.as_slice() {
|
||||
[Action::Move { placement, .. }] => Ok(placement.clone()),
|
||||
other => panic!("{other:?}"),
|
||||
},
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
// A start dock is on the left edge left to right, on the right edge right to left.
|
||||
assert_eq!(placed("right", "layers", false), Ok(Placement::Column { after: true }));
|
||||
assert_eq!(placed("right", "layers", true), Ok(Placement::Column { after: false }));
|
||||
assert_eq!(placed("left", "layers", true), Ok(Placement::Column { after: true }));
|
||||
assert_eq!(placed("top", "layers", false), Ok(Placement::Group { below: false, height: None }));
|
||||
// A floating window is a tree like the docked layout's.
|
||||
assert_eq!(placed("bottom", "color", false), Ok(Placement::Split(Zone::Bottom)));
|
||||
assert_eq!(placed("left", "color", false), Ok(Placement::Split(Zone::Left)));
|
||||
assert_eq!(placed("left", "canvas", true), Ok(Placement::Split(Zone::Left)));
|
||||
|
||||
let (workspace, _) = applied(json!({"command": "window.panel.move", "panel": "history", "anchor": "layers", "zone": "right"}));
|
||||
let Some(Node::Split { first, .. }) = &workspace.layout.root else { panic!() };
|
||||
let Node::Dock { columns, .. } = &**first else { panic!() };
|
||||
assert_eq!(columns.len(), 2);
|
||||
assert_eq!(columns[1].groups[0].panels, vec![s("history")]);
|
||||
}
|
||||
|
||||
/// `layers` prefers 200x150 when it floats.
|
||||
struct Sized;
|
||||
|
||||
impl DockContent<P> for Sized {
|
||||
fn body(&mut self, _: &mut egui::Ui, _: &P) {}
|
||||
fn permissions(&self, panel: &P) -> Permissions {
|
||||
permissions(panel)
|
||||
}
|
||||
fn floating_size(&self, panel: &P) -> Option<egui::Vec2> {
|
||||
(panel == "layers").then_some(egui::vec2(200.0, 150.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() {
|
||||
// The area starts under a 30 pt menu bar.
|
||||
let area = egui::Rect::from_min_max(egui::pos2(0.0, 30.0), egui::pos2(800.0, 600.0));
|
||||
let d = testing::DockDriver::new(workspace().layout, Sized).with_area(area);
|
||||
let space = float_space::<P>(&d.ctx, d.id).expect("the area records its float space");
|
||||
assert_eq!(space.area, area);
|
||||
let float = |params: Value| parse(params).unwrap().to_actions(&workspace(), false, &space).unwrap();
|
||||
|
||||
let panel = float(json!({"command": "window.panel.float", "panel": "layers"}));
|
||||
// The floating_size width, and an empty body's least fitted height under its 150 points.
|
||||
assert_eq!(panel, vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 120.0] }], "floating_size, inset in the area");
|
||||
let [Action::MoveGroup { to: Target::Float { rect: Some([x, y, width, height]) }, .. }] =
|
||||
float(json!({"command": "window.panel.float", "panel": "history", "group": true}))[..]
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!([x, y], [24.0, 54.0]);
|
||||
assert!(width > 100.0 && width <= 240.0 && height <= 320.0, "the docked group's size, capped: {width}x{height}");
|
||||
|
||||
// Given values stay exactly; a lone floating window keeps its rect.
|
||||
let given = float(json!({"command": "window.panel.float", "panel": "layers", "x": 5, "y": 6, "width": 100, "height": 90}));
|
||||
assert_eq!(given, vec![Action::Float { panel: s("layers"), rect: [5.0, 6.0, 100.0, 90.0] }]);
|
||||
let color = float(json!({"command": "window.panel.float", "panel": "color", "group": true}));
|
||||
assert_eq!(color, vec![Action::MoveGroup { panel: s("color"), to: Target::Float { rect: None } }]);
|
||||
|
||||
// Without recorded sizes a unit floats at the layout's size, shrunk into a small area.
|
||||
let small = FloatSpace::new(egui::Rect::from_min_size(egui::pos2(0.0, 30.0), egui::vec2(200.0, 200.0)));
|
||||
let applied = parse(json!({"command": "window.panel.float", "panel": "layers", "group": true})).unwrap().to_actions(&workspace(), false, &small);
|
||||
assert_eq!(applied, Ok(vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: Some([0.0, 30.0, 200.0, 200.0]) } }]));
|
||||
|
||||
// A host seeds the size of a panel the area never drew; a recorded size still wins.
|
||||
let seeded = FloatSpace::new(area).with_panel_size(s("layers"), egui::vec2(180.0, 240.0));
|
||||
let applied = parse(json!({"command": "window.panel.float", "panel": "layers"})).unwrap().to_actions(&workspace(), false, &seeded);
|
||||
assert_eq!(applied, Ok(vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 180.0, 240.0] }]));
|
||||
let recorded = space.clone().with_panel_size(s("layers"), egui::vec2(180.0, 240.0));
|
||||
assert_eq!(float_with(&recorded, "layers"), vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 120.0] }]);
|
||||
}
|
||||
|
||||
fn float_with(space: &FloatSpace<P>, panel: &str) -> Vec<Action<P>> {
|
||||
parse(json!({"command": "window.panel.float", "panel": panel})).unwrap().to_actions(&workspace(), false, space).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_to_a_side_without_a_dock_takes_one_panel_out_of_a_shared_group() {
|
||||
let params = json!({"command": "window.panel.dock", "panel": "layers", "side": "End"});
|
||||
assert_eq!(actions(params.clone()), vec![Action::MovePanel { panel: s("layers"), to: Target::NewDock { side: Side::End } }]);
|
||||
let (workspace, _) = applied(params);
|
||||
let side = |panel: &str| workspace.layout.location(&s(panel)).unwrap().group.and_then(|g| g.column).map(|c| c.side);
|
||||
assert_eq!(side("layers"), Some(Side::End));
|
||||
assert_eq!(side("channels"), Some(Side::Start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimize_without_a_value_toggles_an_accordion_entry_both_ways() {
|
||||
let entry = |panel: &str| StackEntry { panel: s(panel), open: true, height: None };
|
||||
let mut workspace = Workspace::new(Layout { root: Some(Node::Stack { entries: vec![entry("layers"), entry("history")] }), floating: Vec::new() });
|
||||
let toggle = parse(json!({"command": "window.panel.minimize", "panel": "layers"})).unwrap();
|
||||
toggle.apply(&mut workspace, false, &space(), permissions).unwrap();
|
||||
assert_eq!(workspace.layout.panel_state(&s("layers")), PanelState::Open);
|
||||
toggle.apply(&mut workspace, false, &space(), permissions).unwrap();
|
||||
assert_eq!(workspace.layout.panel_state(&s("layers")), PanelState::Front);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_with_a_side_zone_and_no_anchor_makes_an_outer_edge_frame() {
|
||||
let edge = |panel: &str, zone| Action::Move { panel: s(panel), anchor: s("layers"), placement: Placement::Edge(zone) };
|
||||
assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "color", "zone": "left"})), vec![edge("color", Zone::Left)]);
|
||||
assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "history", "zone": "bottom"})), vec![edge("history", Zone::Bottom)]);
|
||||
let (moved, _) = applied(json!({"command": "window.panel.dock", "panel": "color", "zone": "right"}));
|
||||
assert!(matches!(moved.layout.place(&s("color")), Some(crate::docking::dock_model::Place::Node(_))), "{:?}", moved.layout);
|
||||
let (shown, _) = applied(json!({"command": "window.panel.dock", "panel": "swatches", "zone": "top"}));
|
||||
assert!(
|
||||
matches!(shown.layout.place(&s("swatches")), Some(crate::docking::dock_model::Place::Node(_))) && shown.hidden.is_empty(),
|
||||
"{:?}",
|
||||
shown.layout
|
||||
);
|
||||
rejected(json!({"command": "window.panel.dock", "panel": "color", "zone": "left", "before": null}), DockError::InvalidPlacement);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_to_the_side_a_panel_already_leads_the_last_column_of() {
|
||||
// Layers leads the dock's only column: it moves out to a new column after it.
|
||||
let (workspace, _) = applied(json!({"command": "window.panel.dock", "panel": "layers", "side": "Start"}));
|
||||
assert!(matches!(workspace.layout.place(&s("layers")), Some(dock_model::Place::Dock { column: 1, .. })));
|
||||
assert!(matches!(workspace.layout.place(&s("channels")), Some(dock_model::Place::Dock { column: 0, .. })));
|
||||
// The whole column already is the last one: nothing to do.
|
||||
assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "layers", "column": true, "side": "Start"})), vec![]);
|
||||
}
|
||||
@@ -0,0 +1,850 @@
|
||||
//! Docks, columns, groups and floating windows: their types and the structural edits behind
|
||||
//! group, column and window moves.
|
||||
//!
|
||||
//! A group, column or floating window is named by a panel it contains. Edits run on a proposed
|
||||
//! copy of the layout, so a helper that fails part-way leaves nothing behind.
|
||||
|
||||
use std::{collections::HashMap, hash::Hash};
|
||||
|
||||
use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, MAX_PANELS, Node, Placement, Zone, valid_height, valid_rect, valid_width};
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
|
||||
/// Width of a new column when nothing better is known.
|
||||
pub(super) const DEFAULT_COLUMN_WIDTH: f32 = 240.0;
|
||||
/// Rect of a new floating window when the caller gives none and the source has no size.
|
||||
const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0];
|
||||
|
||||
/// The window edge a [`Node::Dock`] sits on, in reading order so right-to-left interfaces
|
||||
/// mirror. `Start` is the edge of a horizontal split's first child (left in a left-to-right
|
||||
/// layout); the renderer maps it to a physical edge from the layout direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum Side {
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
/// Tabs that move, minimize and size together in a dock column.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", serde(bound(deserialize = "P: serde::Deserialize<'de>")))]
|
||||
pub struct Group<P> {
|
||||
pub panels: Vec<P>,
|
||||
pub active: usize,
|
||||
/// Only the tab strip shows. `height` is kept for when the group expands again.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub minimized: bool,
|
||||
/// Preferred height in points; `None` shares the free height of the column or stack.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub height: Option<f32>,
|
||||
}
|
||||
|
||||
impl<P> Group<P> {
|
||||
pub fn new(panels: Vec<P>, active: usize) -> Self {
|
||||
Self { panels, active, minimized: false, height: None }
|
||||
}
|
||||
|
||||
pub fn active_panel(&self) -> Option<&P> {
|
||||
self.panels.get(self.active)
|
||||
}
|
||||
}
|
||||
|
||||
/// One column of a dock: groups from top to bottom.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", serde(bound(deserialize = "P: serde::Deserialize<'de>")))]
|
||||
pub struct Column<P> {
|
||||
pub groups: Vec<Group<P>>,
|
||||
/// Expanded width in points.
|
||||
pub width: f32,
|
||||
/// Collapsed to one icon per panel.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub iconic: bool,
|
||||
/// Width while iconic; labels show beside the icons when it is wide enough.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub iconic_width: Option<f32>,
|
||||
}
|
||||
|
||||
impl<P> Column<P> {
|
||||
pub fn new(groups: Vec<Group<P>>, width: f32) -> Self {
|
||||
Self { groups, width, iconic: false, iconic_width: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a group, column or floating window goes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum Target<P> {
|
||||
/// Relative to the panel `anchor`, which must not be part of what moves.
|
||||
At { anchor: P, placement: Placement<P> },
|
||||
/// A new dock on an edge that has none (or an empty one). The root becomes the other side
|
||||
/// of a horizontal split.
|
||||
NewDock { side: Side },
|
||||
/// A new floating window. `None` keeps the source's size at a default position.
|
||||
Float { rect: Option<[f32; 4]> },
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> Placement<P> {
|
||||
/// The placement for a drop zone on `anchor`'s group, in the vocabulary its container
|
||||
/// accepts. `zone` is physical: `Left` is the left half on screen in either direction.
|
||||
///
|
||||
/// | Anchor in | `Center` | `Top`, `Bottom` | `Left`, `Right` |
|
||||
/// |---|---|---|---|
|
||||
/// | the split tree or a floating window | [`Placement::Split`] | `Split` | `Split` |
|
||||
/// | a dock column | `Split(Center)` (join as tabs) | [`Placement::Group`] above or below | [`Placement::Column`] on that side |
|
||||
///
|
||||
/// A dock's `Column { after }` counts from its window edge, which depends on the dock's
|
||||
/// side and `right_to_left` (see [`Side`]); this picks `after` so the new column lands on
|
||||
/// the zone's side of the anchor's column.
|
||||
pub fn for_zone(layout: &Layout<P>, anchor: &P, zone: Zone, right_to_left: bool) -> Result<Self, DockError> {
|
||||
let place = layout.place(anchor).ok_or(DockError::MissingTarget)?;
|
||||
Ok(match (place, zone) {
|
||||
(Place::Node(_) | Place::Floating { .. }, zone) | (_, zone @ Zone::Center) => Placement::Split(zone),
|
||||
(Place::Dock { .. }, Zone::Top | Zone::Bottom) => Placement::Group { below: zone == Zone::Bottom, height: None },
|
||||
(Place::Dock { path, .. }, _) => {
|
||||
let side = match layout.root.as_ref().and_then(|root| node_at(root, &path)) {
|
||||
Some(Node::Dock { side, .. }) => *side,
|
||||
_ => return Err(DockError::MissingTarget),
|
||||
};
|
||||
// The physical edge of the dock: Start is left in a left-to-right layout.
|
||||
let left_edge = (side == Side::Start) != right_to_left;
|
||||
// `after` is away from the window edge: rightwards for a left dock.
|
||||
Placement::Column { after: (zone == Zone::Right) == left_edge }
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Window menu shows for a panel. The model does not track the z-order of floating
|
||||
/// windows, so `Front` means "showing": the active tab of an expanded group in an expanded column.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PanelState {
|
||||
Hidden,
|
||||
Open,
|
||||
Front,
|
||||
}
|
||||
|
||||
/// The group a closed panel was in, when that group was in a dock.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct GroupLocation {
|
||||
pub minimized: bool,
|
||||
pub height: Option<f32>,
|
||||
/// The column, when the group was docked.
|
||||
pub column: Option<ColumnLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ColumnLocation {
|
||||
pub side: Side,
|
||||
pub width: f32,
|
||||
pub iconic: bool,
|
||||
pub iconic_width: Option<f32>,
|
||||
}
|
||||
|
||||
/// Where a panel is. Paths lead from the root: false is a split's first child, true its second.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Place {
|
||||
/// A `Tabs` or `Stack` node.
|
||||
Node(Vec<bool>),
|
||||
Dock {
|
||||
path: Vec<bool>,
|
||||
column: usize,
|
||||
group: usize,
|
||||
},
|
||||
/// A `Tabs` or `Stack` node of a floating window's tree.
|
||||
Floating {
|
||||
window: usize,
|
||||
path: Vec<bool>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Place {
|
||||
/// The tree (`None` for the docked layout, else a floating window) and the path of a
|
||||
/// `Tabs` or `Stack` node.
|
||||
pub(super) fn tree_path(&self) -> Option<(Option<usize>, &[bool])> {
|
||||
match self {
|
||||
Place::Node(path) => Some((None, path)),
|
||||
Place::Floating { window, path } => Some((Some(*window), path)),
|
||||
Place::Dock { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which container a whole-container action names.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Unit {
|
||||
Group,
|
||||
Column,
|
||||
Window,
|
||||
}
|
||||
|
||||
/// Groups in transit, with the size and state of the container they came from.
|
||||
pub(super) struct Moving<P> {
|
||||
pub groups: Vec<Group<P>>,
|
||||
/// A floating window's whole tree, whose leaves are `groups`. A split or a new window
|
||||
/// takes the tree; docks take the groups.
|
||||
pub node: Option<Node<P>>,
|
||||
pub minimized: bool,
|
||||
pub width: Option<f32>,
|
||||
pub iconic: bool,
|
||||
pub iconic_width: Option<f32>,
|
||||
pub rect: Option<[f32; 4]>,
|
||||
pub native: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl<P> Moving<P> {
|
||||
pub fn group(group: Group<P>) -> Self {
|
||||
Self { groups: vec![group], node: None, minimized: false, width: None, iconic: false, iconic_width: None, rect: None, native: None }
|
||||
}
|
||||
|
||||
fn into_column(self, width: f32) -> Column<P> {
|
||||
Column { groups: self.groups, width: self.width.unwrap_or(width), iconic: self.iconic, iconic_width: self.iconic_width }
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn node_at<'a, P>(mut node: &'a Node<P>, path: &[bool]) -> Option<&'a Node<P>> {
|
||||
for second_child in path {
|
||||
let Node::Split { first, second, .. } = node else { return None };
|
||||
node = if *second_child { second } else { first };
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
pub(super) fn node_at_mut<'a, P>(mut node: &'a mut Node<P>, path: &[bool]) -> Option<&'a mut Node<P>> {
|
||||
for second_child in path {
|
||||
let Node::Split { first, second, .. } = node else { return None };
|
||||
node = if *second_child { second } else { first };
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
/// Every `Tabs`, `Stack` and `Dock` node of a tree with its path, first to last. Stops at
|
||||
/// [`MAX_NODES`] for an invalid tree.
|
||||
pub(super) fn leaves<P>(root: &Node<P>) -> Vec<(&Node<P>, Vec<bool>)> {
|
||||
let mut out = Vec::new();
|
||||
let mut visit = vec![(root, Vec::new())];
|
||||
let mut visited = 0usize;
|
||||
while let Some((node, path)) = visit.pop() {
|
||||
visited = visited.saturating_add(1);
|
||||
if visited > MAX_NODES {
|
||||
break;
|
||||
}
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
let mut second_path = path.clone();
|
||||
second_path.push(true);
|
||||
let mut first_path = path;
|
||||
first_path.push(false);
|
||||
visit.push((second, second_path));
|
||||
visit.push((first, first_path));
|
||||
}
|
||||
leaf => out.push((leaf, path)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The panels of a tree in order, without recursion; at most [`MAX_PANELS`].
|
||||
pub(super) fn tree_panels<P>(root: &Node<P>) -> Vec<&P> {
|
||||
let mut panels = Vec::new();
|
||||
for (leaf, _) in leaves(root) {
|
||||
let room = MAX_PANELS.saturating_sub(panels.len());
|
||||
match leaf {
|
||||
Node::Tabs { panels: group, .. } => panels.extend(group.iter().take(room)),
|
||||
Node::Stack { entries } => panels.extend(entries.iter().map(|e| &e.panel).take(room)),
|
||||
Node::Dock { columns, .. } => panels.extend(columns.iter().flat_map(|c| &c.groups).flat_map(|g| &g.panels).take(room)),
|
||||
Node::Split { .. } => {}
|
||||
}
|
||||
}
|
||||
panels
|
||||
}
|
||||
|
||||
/// The shown panel of a tree's first group.
|
||||
#[cfg(feature = "native-windows")]
|
||||
pub(super) fn first_active<P>(root: &Node<P>) -> Option<&P> {
|
||||
match leaves(root).into_iter().next()?.0 {
|
||||
Node::Tabs { panels, active } => panels.get(*active),
|
||||
Node::Stack { entries } => entries.first().map(|e| &e.panel),
|
||||
Node::Split { .. } | Node::Dock { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The groups of a tree, first to last: what a dock column takes from a floating window.
|
||||
pub(super) fn tree_groups<P: Clone>(root: &Node<P>) -> Vec<Group<P>> {
|
||||
let mut groups = Vec::new();
|
||||
for (leaf, _) in leaves(root) {
|
||||
match leaf {
|
||||
Node::Tabs { panels, active } => groups.push(Group::new(panels.clone(), *active)),
|
||||
Node::Stack { entries } => groups.push(Group::new(entries.iter().map(|e| e.panel.clone()).collect(), 0)),
|
||||
Node::Dock { columns, .. } => groups.extend(columns.iter().flat_map(|c| c.groups.iter().cloned())),
|
||||
Node::Split { .. } => {}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Groups stacked top to bottom as a tree: each group over a vertical split of the ones below
|
||||
/// it, sized by their heights, with an equal share where a group has none.
|
||||
pub(super) fn stack_tree<P>(groups: Vec<Group<P>>) -> Option<Node<P>> {
|
||||
let height = |g: &Group<P>| g.height.filter(|h| h.is_finite() && *h > 0.0);
|
||||
let known: Vec<f32> = groups.iter().filter_map(height).collect();
|
||||
let share = if known.is_empty() { 1.0 } else { known.iter().sum::<f32>() / known.len() as f32 };
|
||||
let weights: Vec<f32> = groups.iter().map(|g| height(g).unwrap_or(share)).collect();
|
||||
let mut node = None;
|
||||
let mut below = 0.0;
|
||||
for (group, weight) in groups.into_iter().zip(weights).rev() {
|
||||
let tabs = Node::Tabs { panels: group.panels, active: group.active };
|
||||
node = Some(match node {
|
||||
None => tabs,
|
||||
Some(rest) => {
|
||||
let ratio = (weight / (weight + below)).clamp(0.0, 1.0);
|
||||
Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(ratio), first: Box::new(tabs), second: Box::new(rest) }
|
||||
}
|
||||
});
|
||||
below += weight;
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
/// Put `new` on the `zone` side of the frame at `path`: the frame splits into two halves and
|
||||
/// every other frame keeps its size.
|
||||
pub(super) fn split_frame<P>(root: &mut Node<P>, path: &[bool], new: Node<P>, zone: Zone) -> bool {
|
||||
let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal };
|
||||
let new_first = matches!(zone, Zone::Top | Zone::Left);
|
||||
let Some(node) = node_at_mut(root, path) else { return false };
|
||||
let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 });
|
||||
let (first, second) = if new_first { (new, old) } else { (old, new) };
|
||||
*node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) };
|
||||
true
|
||||
}
|
||||
|
||||
/// Insert `new` at `index` and select the member at `index + selected`.
|
||||
fn splice<P>(panels: &mut Vec<P>, active: &mut usize, index: usize, new: Vec<P>, selected: usize) {
|
||||
let index = index.min(panels.len());
|
||||
let count = new.len();
|
||||
panels.splice(index..index, new);
|
||||
*active = index + selected.min(count.saturating_sub(1));
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> Layout<P> {
|
||||
pub(super) fn place(&self, panel: &P) -> Option<Place> {
|
||||
for (w, window) in self.floating.iter().enumerate() {
|
||||
for (leaf, path) in leaves(&window.root) {
|
||||
if leaf_holds(leaf, panel) {
|
||||
return Some(Place::Floating { window: w, path });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (leaf, path) in self.root.as_ref().map(leaves).unwrap_or_default() {
|
||||
match leaf {
|
||||
Node::Dock { columns, .. } => {
|
||||
for (c, column) in columns.iter().enumerate() {
|
||||
if let Some(g) = column.groups.iter().position(|group| group.panels.contains(panel)) {
|
||||
return Some(Place::Dock { path, column: c, group: g });
|
||||
}
|
||||
}
|
||||
}
|
||||
leaf if leaf_holds(leaf, panel) => return Some(Place::Node(path)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// [`Self::place`] of every panel, from one traversal: the renderer looks up many panels a
|
||||
/// frame.
|
||||
pub(super) fn places(&self) -> HashMap<P, Place> {
|
||||
fn note<P: Clone + Eq + Hash>(places: &mut HashMap<P, Place>, leaf: &Node<P>, place: &dyn Fn() -> Place) {
|
||||
match leaf {
|
||||
Node::Tabs { panels, .. } => {
|
||||
for panel in panels {
|
||||
places.entry(panel.clone()).or_insert_with(place);
|
||||
}
|
||||
}
|
||||
Node::Stack { entries } => {
|
||||
for entry in entries {
|
||||
places.entry(entry.panel.clone()).or_insert_with(place);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut places = HashMap::new();
|
||||
for (w, window) in self.floating.iter().enumerate() {
|
||||
for (leaf, path) in leaves(&window.root) {
|
||||
note(&mut places, leaf, &|| Place::Floating { window: w, path: path.clone() });
|
||||
}
|
||||
}
|
||||
for (leaf, path) in self.root.as_ref().map(leaves).unwrap_or_default() {
|
||||
if let Node::Dock { columns, .. } = leaf {
|
||||
for (c, column) in columns.iter().enumerate() {
|
||||
for (g, group) in column.groups.iter().enumerate() {
|
||||
for panel in &group.panels {
|
||||
places.entry(panel.clone()).or_insert_with(|| Place::Dock { path: path.clone(), column: c, group: g });
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
note(&mut places, leaf, &|| Place::Node(path.clone()));
|
||||
}
|
||||
}
|
||||
places
|
||||
}
|
||||
|
||||
/// The docked layout (`None`) or a floating window's tree.
|
||||
pub(super) fn tree(&self, window: Option<usize>) -> Option<&Node<P>> {
|
||||
match window {
|
||||
None => self.root.as_ref(),
|
||||
Some(window) => self.floating.get(window).map(|w| &w.root),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tree_mut(&mut self, window: Option<usize>) -> Option<&mut Node<P>> {
|
||||
match window {
|
||||
None => self.root.as_mut(),
|
||||
Some(window) => self.floating.get_mut(window).map(|w| &mut w.root),
|
||||
}
|
||||
}
|
||||
|
||||
/// The docked layout's tree, then each floating window's.
|
||||
pub(super) fn trees_mut(&mut self) -> impl Iterator<Item = &mut Node<P>> {
|
||||
self.root.iter_mut().chain(self.floating.iter_mut().map(|w| &mut w.root))
|
||||
}
|
||||
|
||||
/// The `Tabs` or `Stack` node at a tree place.
|
||||
pub(super) fn node_of(&self, place: &Place) -> Option<&Node<P>> {
|
||||
let (window, path) = place.tree_path()?;
|
||||
node_at(self.tree(window)?, path)
|
||||
}
|
||||
|
||||
fn node_of_mut(&mut self, place: &Place) -> Option<&mut Node<P>> {
|
||||
let (window, path) = place.tree_path()?;
|
||||
node_at_mut(self.tree_mut(window)?, path)
|
||||
}
|
||||
|
||||
pub(super) fn dock_path(&self, side: Side) -> Option<Vec<bool>> {
|
||||
let mut visit: Vec<(&Node<P>, Vec<bool>)> = self.root.iter().map(|node| (node, Vec::new())).collect();
|
||||
let mut visited = 0usize;
|
||||
while let Some((node, path)) = visit.pop() {
|
||||
visited = visited.saturating_add(1);
|
||||
if visited > MAX_NODES {
|
||||
return None;
|
||||
}
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
let mut second_path = path.clone();
|
||||
second_path.push(true);
|
||||
let mut first_path = path;
|
||||
first_path.push(false);
|
||||
visit.push((second, second_path));
|
||||
visit.push((first, first_path));
|
||||
}
|
||||
Node::Dock { side: s, .. } if *s == side => return Some(path),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The node an edge split wraps: the root, or the part between the docks.
|
||||
pub(in crate::docking) fn edge_path(&self) -> Vec<bool> {
|
||||
let mut path = Vec::new();
|
||||
let mut node = self.root.as_ref();
|
||||
while let Some(Node::Split { axis: SplitAxis::Horizontal, first, second, .. }) = node {
|
||||
if path.len() > MAX_DEPTH {
|
||||
break;
|
||||
}
|
||||
let second_side = match (&**first, &**second) {
|
||||
(Node::Dock { .. }, _) => true,
|
||||
(_, Node::Dock { .. }) => false,
|
||||
_ => break,
|
||||
};
|
||||
path.push(second_side);
|
||||
node = Some(if second_side { second } else { first });
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
pub(super) fn columns_mut(&mut self, path: &[bool]) -> Option<&mut Vec<Column<P>>> {
|
||||
match self.root.as_mut().and_then(|root| node_at_mut(root, path)) {
|
||||
Some(Node::Dock { columns, .. }) => Some(columns),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn column(&self, place: &Place) -> Option<&Column<P>> {
|
||||
let Place::Dock { path, column, .. } = place else { return None };
|
||||
match self.root.as_ref().and_then(|root| node_at(root, path)) {
|
||||
Some(Node::Dock { columns, .. }) => columns.get(*column),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn column_mut(&mut self, place: &Place) -> Option<&mut Column<P>> {
|
||||
let Place::Dock { path, column, .. } = place else { return None };
|
||||
self.columns_mut(path)?.get_mut(*column)
|
||||
}
|
||||
|
||||
/// The dock group at `place`; `None` for a `Tabs` or `Stack` node.
|
||||
pub(super) fn group(&self, place: &Place) -> Option<&Group<P>> {
|
||||
match place {
|
||||
Place::Dock { group, .. } => self.column(place)?.groups.get(*group),
|
||||
Place::Node(_) | Place::Floating { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn group_mut(&mut self, place: &Place) -> Option<&mut Group<P>> {
|
||||
match place {
|
||||
Place::Dock { group, .. } => self.column_mut(place)?.groups.get_mut(*group),
|
||||
Place::Node(_) | Place::Floating { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the node at `path` of the docked layout; its parent split collapses into the
|
||||
/// sibling.
|
||||
pub(super) fn take_node(&mut self, path: &[bool]) -> Option<Node<P>> {
|
||||
self.take_node_in(None, path)
|
||||
}
|
||||
|
||||
/// [`Self::take_node`] in the docked layout (`None`) or a floating window, which closes
|
||||
/// when its root goes.
|
||||
fn take_node_in(&mut self, window: Option<usize>, path: &[bool]) -> Option<Node<P>> {
|
||||
let Some((second_child, parent_path)) = path.split_last() else {
|
||||
return match window {
|
||||
None => self.root.take(),
|
||||
Some(window) => (window < self.floating.len()).then(|| self.floating.remove(window).root),
|
||||
};
|
||||
};
|
||||
let parent = self.tree_mut(window).and_then(|root| node_at_mut(root, parent_path))?;
|
||||
if !matches!(parent, Node::Split { .. }) {
|
||||
return None;
|
||||
}
|
||||
match std::mem::replace(parent, Node::Tabs { panels: Vec::new(), active: 0 }) {
|
||||
Node::Split { first, second, .. } => {
|
||||
let (taken, kept) = if *second_child { (second, first) } else { (first, second) };
|
||||
*parent = *kept;
|
||||
Some(*taken)
|
||||
}
|
||||
other => {
|
||||
*parent = other;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of the group, column or floating window containing `panel`, in order.
|
||||
/// An accordion entry is a group of one.
|
||||
pub(super) fn members(&self, panel: &P, unit: Unit) -> Result<Vec<P>, DockError> {
|
||||
let place = self.place(panel).ok_or(DockError::MissingPanel)?;
|
||||
match (unit, &place) {
|
||||
(Unit::Group, Place::Node(_) | Place::Floating { .. }) => match self.node_of(&place) {
|
||||
Some(Node::Tabs { panels, .. }) => Ok(panels.clone()),
|
||||
Some(Node::Stack { .. }) => Ok(vec![panel.clone()]),
|
||||
_ => Err(DockError::MissingPanel),
|
||||
},
|
||||
(Unit::Group, _) => self.group(&place).map(|g| g.panels.clone()).ok_or(DockError::MissingPanel),
|
||||
(Unit::Column, Place::Dock { .. }) => {
|
||||
let column = self.column(&place).ok_or(DockError::MissingPanel)?;
|
||||
Ok(column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect())
|
||||
}
|
||||
(Unit::Window, Place::Floating { window, .. }) => {
|
||||
let window = self.floating.get(*window).ok_or(DockError::MissingPanel)?;
|
||||
Ok(window.panels().cloned().collect())
|
||||
}
|
||||
(Unit::Column | Unit::Window, _) => Err(DockError::InvalidPlacement),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take_unit(&mut self, panel: &P, unit: Unit) -> Result<Moving<P>, DockError> {
|
||||
match unit {
|
||||
Unit::Group => self.take_group(panel),
|
||||
Unit::Column => self.take_column(panel),
|
||||
Unit::Window => self.take_window(panel),
|
||||
}
|
||||
}
|
||||
|
||||
fn take_group(&mut self, panel: &P) -> Result<Moving<P>, DockError> {
|
||||
let place = self.place(panel).ok_or(DockError::MissingPanel)?;
|
||||
match place {
|
||||
Place::Node(_) | Place::Floating { .. } => {
|
||||
let (window, path) = place.tree_path().map(|(w, p)| (w, p.to_vec())).ok_or(DockError::MissingPanel)?;
|
||||
// A group leaving a floating window keeps its width; the window's only group
|
||||
// takes the window's rect along.
|
||||
let source = window.and_then(|w| self.floating.get(w)).map(|w| (w.rect, w.native, w.minimized));
|
||||
let whole = |moving: Moving<P>| match source {
|
||||
Some((rect, native, minimized)) if path.is_empty() => {
|
||||
Moving { width: rect.get(2).copied(), rect: Some(rect), native, minimized, ..moving }
|
||||
}
|
||||
Some((rect, ..)) => Moving { width: rect.get(2).copied(), ..moving },
|
||||
None => moving,
|
||||
};
|
||||
if let Some(Node::Stack { entries }) = self.node_of_mut(&place)
|
||||
&& entries.len() > 1
|
||||
&& let Some(index) = entries.iter().position(|e| &e.panel == panel)
|
||||
{
|
||||
let entry = entries.remove(index);
|
||||
let group = Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height };
|
||||
let moving = whole(Moving::group(group));
|
||||
return Ok(Moving { rect: None, native: None, ..moving });
|
||||
}
|
||||
match self.take_node_in(window, &path) {
|
||||
Some(Node::Tabs { panels, active }) => Ok(whole(Moving::group(Group::new(panels, active)))),
|
||||
Some(Node::Stack { mut entries }) if entries.len() == 1 => {
|
||||
let entry = entries.remove(0);
|
||||
Ok(whole(Moving::group(Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height })))
|
||||
}
|
||||
_ => Err(DockError::MissingPanel),
|
||||
}
|
||||
}
|
||||
Place::Dock { path, column, group } => {
|
||||
let columns = self.columns_mut(&path).ok_or(DockError::MissingPanel)?;
|
||||
let source = columns.get_mut(column).ok_or(DockError::MissingPanel)?;
|
||||
if group >= source.groups.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = source.groups.remove(group);
|
||||
let width = source.width;
|
||||
if source.groups.is_empty() {
|
||||
columns.remove(column);
|
||||
}
|
||||
if columns.is_empty() {
|
||||
self.take_node(&path);
|
||||
}
|
||||
Ok(Moving { width: Some(width), ..Moving::group(taken) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_column(&mut self, panel: &P) -> Result<Moving<P>, DockError> {
|
||||
let Some(Place::Dock { path, column, .. }) = self.place(panel) else { return Err(DockError::InvalidPlacement) };
|
||||
let columns = self.columns_mut(&path).ok_or(DockError::MissingPanel)?;
|
||||
if column >= columns.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = columns.remove(column);
|
||||
if columns.is_empty() {
|
||||
self.take_node(&path);
|
||||
}
|
||||
Ok(Moving {
|
||||
groups: taken.groups,
|
||||
node: None,
|
||||
minimized: false,
|
||||
width: Some(taken.width),
|
||||
iconic: taken.iconic,
|
||||
iconic_width: taken.iconic_width,
|
||||
rect: None,
|
||||
native: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn take_window(&mut self, panel: &P) -> Result<Moving<P>, DockError> {
|
||||
let Some(Place::Floating { window, .. }) = self.place(panel) else { return Err(DockError::InvalidPlacement) };
|
||||
if window >= self.floating.len() {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
let taken = self.floating.remove(window);
|
||||
Ok(Moving {
|
||||
groups: tree_groups(&taken.root),
|
||||
node: Some(taken.root),
|
||||
minimized: taken.minimized,
|
||||
width: taken.rect.get(2).copied(),
|
||||
iconic: false,
|
||||
iconic_width: None,
|
||||
rect: Some(taken.rect),
|
||||
native: taken.native,
|
||||
})
|
||||
}
|
||||
|
||||
/// Insert groups taken by [`Self::take_unit`] (or a new single-panel group).
|
||||
pub(super) fn insert_moving(&mut self, moving: Moving<P>, to: Target<P>) -> Result<(), DockError> {
|
||||
if moving.groups.is_empty() || moving.groups.iter().any(|g| g.panels.is_empty()) {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
match to {
|
||||
Target::Float { rect } => {
|
||||
let native = if rect.is_none() { moving.native } else { None };
|
||||
let rect = rect.or(moving.rect).unwrap_or_else(|| {
|
||||
let [x, y, width, height] = DEFAULT_FLOAT;
|
||||
[x, y, moving.width.unwrap_or(width), height]
|
||||
});
|
||||
if !valid_rect(rect) {
|
||||
return Err(DockError::InvalidGeometry);
|
||||
}
|
||||
let root = match moving.node {
|
||||
Some(node) => node,
|
||||
None => stack_tree(moving.groups).ok_or(DockError::MissingPanel)?,
|
||||
};
|
||||
self.floating.push(Floating { root, rect, native, minimized: moving.minimized });
|
||||
Ok(())
|
||||
}
|
||||
Target::NewDock { side } => {
|
||||
if let Some(path) = self.dock_path(side) {
|
||||
let columns = self.columns_mut(&path).ok_or(DockError::MissingTarget)?;
|
||||
if !columns.is_empty() {
|
||||
return Err(DockError::InvalidPlacement);
|
||||
}
|
||||
columns.push(moving.into_column(DEFAULT_COLUMN_WIDTH));
|
||||
return Ok(());
|
||||
}
|
||||
let column = moving.into_column(DEFAULT_COLUMN_WIDTH);
|
||||
self.add_dock(side, column);
|
||||
Ok(())
|
||||
}
|
||||
Target::At { anchor, placement } => {
|
||||
let place = self.place(&anchor).ok_or(DockError::MissingTarget)?;
|
||||
match placement {
|
||||
Placement::Tab { before } => {
|
||||
let index = match &before {
|
||||
Some(before) => {
|
||||
if self.place(before).as_ref() != Some(&place) {
|
||||
return Err(DockError::MissingTarget);
|
||||
}
|
||||
self.index_in(&place, before)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
self.merge(&place, index, moving)
|
||||
}
|
||||
Placement::Split(Zone::Center) => {
|
||||
let index = self.index_in(&place, &anchor).map(|i| i + 1);
|
||||
self.merge(&place, index, moving)
|
||||
}
|
||||
Placement::Split(zone) => {
|
||||
let (window, path) = place.tree_path().ok_or(DockError::InvalidPlacement)?;
|
||||
let new = match moving.node {
|
||||
Some(node) => node,
|
||||
None => {
|
||||
let (panels, active) = flatten(moving.groups);
|
||||
Node::Tabs { panels, active }
|
||||
}
|
||||
};
|
||||
let root = self.tree_mut(window).ok_or(DockError::MissingTarget)?;
|
||||
if split_frame(root, path, new, zone) { Ok(()) } else { Err(DockError::MissingTarget) }
|
||||
}
|
||||
// A floating window is a tree: a group above or below splits the anchor's group.
|
||||
Placement::Group { below, .. } if matches!(place, Place::Floating { .. }) => {
|
||||
let zone = if below { Zone::Bottom } else { Zone::Top };
|
||||
self.insert_moving(moving, Target::At { anchor, placement: Placement::Split(zone) })
|
||||
}
|
||||
Placement::Group { below, height } => {
|
||||
if !valid_height(height) {
|
||||
return Err(DockError::InvalidGeometry);
|
||||
}
|
||||
let mut moving = moving;
|
||||
if height.is_some() {
|
||||
moving.groups.iter_mut().for_each(|group| group.height = height);
|
||||
}
|
||||
let (groups, index) = match &place {
|
||||
Place::Dock { group, .. } => (&mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups, *group),
|
||||
Place::Node(_) | Place::Floating { .. } => return Err(DockError::InvalidPlacement),
|
||||
};
|
||||
let index = (index + usize::from(below)).min(groups.len());
|
||||
groups.splice(index..index, moving.groups);
|
||||
Ok(())
|
||||
}
|
||||
Placement::Edge(zone) => {
|
||||
if zone == Zone::Center || matches!(place, Place::Floating { .. }) {
|
||||
return Err(DockError::InvalidPlacement);
|
||||
}
|
||||
let path = self.edge_path();
|
||||
let node = self.root.as_mut().and_then(|root| node_at_mut(root, &path)).ok_or(DockError::MissingTarget)?;
|
||||
if matches!(node, Node::Dock { .. }) {
|
||||
return Err(DockError::InvalidPlacement);
|
||||
}
|
||||
let (panels, active) = flatten(moving.groups);
|
||||
let new = Node::Tabs { panels, active };
|
||||
let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 });
|
||||
let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal };
|
||||
let (first, second, size) = if matches!(zone, Zone::Top | Zone::Left) { (new, old, 0.25) } else { (old, new, 0.75) };
|
||||
*node = Node::Split { axis, size: SplitSize::Ratio(size), first: Box::new(first), second: Box::new(second) };
|
||||
Ok(())
|
||||
}
|
||||
Placement::Column { after } => {
|
||||
let Place::Dock { path, column, .. } = &place else { return Err(DockError::InvalidPlacement) };
|
||||
let columns = self.columns_mut(path).ok_or(DockError::MissingTarget)?;
|
||||
let width = columns.get(*column).map_or(DEFAULT_COLUMN_WIDTH, |c| c.width);
|
||||
let index = (column + usize::from(after)).min(columns.len());
|
||||
columns.insert(index, moving.into_column(width));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap the root in a horizontal split with a new dock on `side`. The split's fixed size is
|
||||
/// the column width.
|
||||
pub(super) fn add_dock(&mut self, side: Side, column: Column<P>) {
|
||||
let width = column.width;
|
||||
let dock = Node::Dock { side, columns: vec![column] };
|
||||
self.root = Some(match self.root.take() {
|
||||
None => dock,
|
||||
Some(root) => {
|
||||
let (first, second, size) = match side {
|
||||
Side::Start => (dock, root, SplitSize::FixedFirst(width)),
|
||||
Side::End => (root, dock, SplitSize::FixedSecond(width)),
|
||||
};
|
||||
Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(first), second: Box::new(second) }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn index_in(&self, place: &Place, panel: &P) -> Option<usize> {
|
||||
match place {
|
||||
Place::Node(_) | Place::Floating { .. } => match self.node_of(place)? {
|
||||
Node::Tabs { panels, .. } => panels.iter().position(|p| p == panel),
|
||||
Node::Stack { entries } => entries.iter().position(|e| &e.panel == panel),
|
||||
_ => None,
|
||||
},
|
||||
_ => self.group(place)?.panels.iter().position(|p| p == panel),
|
||||
}
|
||||
}
|
||||
|
||||
/// Join every moving panel to the group at `place`, before `index` or at the end. The first
|
||||
/// moving group's active panel becomes active.
|
||||
fn merge(&mut self, place: &Place, index: Option<usize>, moving: Moving<P>) -> Result<(), DockError> {
|
||||
let (panels, selected) = flatten(moving.groups);
|
||||
match place {
|
||||
Place::Node(_) | Place::Floating { .. } => match self.node_of_mut(place) {
|
||||
Some(Node::Tabs { panels: target, active }) => {
|
||||
splice(target, active, index.unwrap_or(target.len()), panels, selected);
|
||||
Ok(())
|
||||
}
|
||||
Some(Node::Stack { entries }) => {
|
||||
let index = index.unwrap_or(entries.len()).min(entries.len());
|
||||
entries.splice(index..index, panels.into_iter().map(|panel| super::StackEntry { panel, open: true, height: None }));
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(DockError::MissingTarget),
|
||||
},
|
||||
_ => {
|
||||
let group = self.group_mut(place).ok_or(DockError::MissingTarget)?;
|
||||
let end = group.panels.len();
|
||||
splice(&mut group.panels, &mut group.active, index.unwrap_or(end), panels, selected);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn leaf_holds<P: PartialEq>(leaf: &Node<P>, panel: &P) -> bool {
|
||||
match leaf {
|
||||
Node::Tabs { panels, .. } => panels.contains(panel),
|
||||
Node::Stack { entries } => entries.iter().any(|e| &e.panel == panel),
|
||||
Node::Split { .. } | Node::Dock { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// All panels in order, and the index of the first group's active panel among them.
|
||||
fn flatten<P>(groups: Vec<Group<P>>) -> (Vec<P>, usize) {
|
||||
let selected = groups.first().map_or(0, |g| g.active.min(g.panels.len().saturating_sub(1)));
|
||||
(groups.into_iter().flat_map(|g| g.panels).collect(), selected)
|
||||
}
|
||||
|
||||
pub(super) fn valid_column<P>(column: &Column<P>) -> bool {
|
||||
valid_width(column.width) && column.iconic_width.is_none_or(valid_width)
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
//! [D] Docks: columns, stacked groups, seams, column bars and their drops.
|
||||
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Context, Event, Id, Modifiers, PointerButton, Pos2, RawInput, Rect, UiBuilder, pos2, vec2};
|
||||
|
||||
const AREA: &str = "dock-area";
|
||||
|
||||
fn group(panels: &[u32]) -> Group<u32> {
|
||||
Group::new(panels.to_vec(), 0)
|
||||
}
|
||||
|
||||
/// A dock on `side` with `columns` (each a list of groups, 240 wide) beside canvas 0.
|
||||
fn docked(side: Side, columns: &[&[&[u32]]]) -> Layout<u32> {
|
||||
let dock = Node::Dock { side, columns: columns.iter().map(|groups| Column::new(groups.iter().map(|g| group(g)).collect(), 240.0)).collect() };
|
||||
let canvas = Node::Tabs { panels: vec![0], active: 0 };
|
||||
let (first, second, size) = match side {
|
||||
Side::Start => (dock, canvas, SplitSize::FixedFirst(240.0)),
|
||||
Side::End => (canvas, dock, SplitSize::FixedSecond(240.0)),
|
||||
};
|
||||
Layout { root: Some(Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(first), second: Box::new(second) }), floating: Vec::new() }
|
||||
}
|
||||
|
||||
fn with_floating(mut layout: Layout<u32>, windows: &[(u32, [f32; 4])]) -> Layout<u32> {
|
||||
layout.floating.extend(windows.iter().map(|(panel, rect)| Floating::single(vec![*panel], 0, *rect)));
|
||||
layout
|
||||
}
|
||||
|
||||
fn columns(layout: &Layout<u32>, side: Side) -> Vec<Vec<Vec<u32>>> {
|
||||
fn find(node: &Node<u32>, side: Side) -> Option<Vec<Vec<Vec<u32>>>> {
|
||||
match node {
|
||||
Node::Dock { side: s, columns } if *s == side => {
|
||||
Some(columns.iter().map(|c| c.groups.iter().map(|g| g.panels.clone()).collect()).collect())
|
||||
}
|
||||
Node::Split { first, second, .. } => find(first, side).or_else(|| find(second, side)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
layout.root.as_ref().and_then(|root| find(root, side)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn column(layout: &Layout<u32>, index: usize) -> Column<u32> {
|
||||
fn find(node: &Node<u32>) -> Option<&Vec<Column<u32>>> {
|
||||
match node {
|
||||
Node::Dock { columns, .. } => Some(columns),
|
||||
Node::Split { first, second, .. } => find(first).or_else(|| find(second)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
layout.root.as_ref().and_then(find).and_then(|c| c.get(index)).cloned().unwrap()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestContent {
|
||||
min_height: f32,
|
||||
}
|
||||
|
||||
impl DockContent<u32> for TestContent {
|
||||
fn body(&mut self, ui: &mut egui::Ui, _: &u32) {
|
||||
ui.label("Body");
|
||||
}
|
||||
fn permissions(&self, panel: &u32) -> Permissions {
|
||||
if *panel == 0 { Permissions::PROTECTED } else { Permissions::default() }
|
||||
}
|
||||
fn limits(&self, _: &u32) -> PanelLimits {
|
||||
PanelLimits { min: vec2(0.0, self.min_height), ..PanelLimits::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders a layout in a 600x600 area of an 800x600 window and applies what it emits.
|
||||
struct Driver {
|
||||
ctx: Context,
|
||||
layout: Layout<u32>,
|
||||
content: TestContent,
|
||||
focused: bool,
|
||||
right_to_left: bool,
|
||||
shapes: Vec<egui::epaint::ClippedShape>,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl Driver {
|
||||
fn new(layout: Layout<u32>) -> Self {
|
||||
Self::with(layout, TestContent::default(), false)
|
||||
}
|
||||
|
||||
fn with(layout: Layout<u32>, content: TestContent, right_to_left: bool) -> Self {
|
||||
let mut driver = Self { ctx: Context::default(), layout, content, focused: true, right_to_left, shapes: Vec::new(), time: 0.0 };
|
||||
// Floating areas settle after their sizing pass.
|
||||
for _ in 0..3 {
|
||||
driver.step(vec![]);
|
||||
}
|
||||
driver
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>) -> DockOutput<u32> {
|
||||
let mut output = DockOutput::default();
|
||||
self.time += 1.0 / 60.0;
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))),
|
||||
events,
|
||||
focused: self.focused,
|
||||
time: Some(self.time),
|
||||
..Default::default()
|
||||
};
|
||||
let (layout, content, rtl) = (&self.layout, &mut self.content, self.right_to_left);
|
||||
let mut full = self.ctx.run_ui(input, |ui| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
style.right_to_left = rtl;
|
||||
ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 600.0))), |ui| {
|
||||
output = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content);
|
||||
});
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
self.shapes = full.shapes;
|
||||
output
|
||||
}
|
||||
|
||||
fn step(&mut self, events: Vec<Event>) -> DockOutput<u32> {
|
||||
let output = self.frame(events);
|
||||
assert!(output.error.is_none(), "{output:?}");
|
||||
let permissions = |p: &u32| self.content.permissions(p);
|
||||
for action in &output.actions {
|
||||
self.layout.apply_with_permissions(action.clone(), permissions).unwrap();
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn rect(&self, name: &str, panel: u32) -> Rect {
|
||||
self.ctx.read_response(Id::new(AREA).with((name, Some(&panel)))).unwrap().rect
|
||||
}
|
||||
|
||||
fn tab(&self, panel: u32) -> Rect {
|
||||
self.ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect
|
||||
}
|
||||
|
||||
fn hold(&mut self, from: Pos2, to: Pos2) -> DockOutput<u32> {
|
||||
self.step(vec![Event::PointerMoved(from)]);
|
||||
self.step(vec![button(from, true)]);
|
||||
self.step(vec![Event::PointerMoved(from + vec2(8.0, 6.0))]);
|
||||
self.step(vec![Event::PointerMoved(to)])
|
||||
}
|
||||
|
||||
fn drag(&mut self, from: Pos2, to: Pos2) -> DockOutput<u32> {
|
||||
self.hold(from, to);
|
||||
self.step(vec![button(to, false)])
|
||||
}
|
||||
|
||||
fn click(&mut self, at: Pos2) -> DockOutput<u32> {
|
||||
self.step(vec![Event::PointerMoved(at), button(at, true)]);
|
||||
self.step(vec![button(at, false)])
|
||||
}
|
||||
|
||||
/// Two frames: egui reports a moved widget's rect a frame late.
|
||||
fn settle(&mut self) {
|
||||
self.step(vec![]);
|
||||
self.step(vec![]);
|
||||
}
|
||||
|
||||
fn wait(&mut self) {
|
||||
for _ in 0..45 {
|
||||
self.step(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the last frame painted the filled insertion line `line`.
|
||||
fn painted(&self, line: Rect) -> bool {
|
||||
self.shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Rect(shape) => shape.rect == line && shape.fill != egui::Color32::TRANSPARENT,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn button(pos: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn key(key: egui::Key) -> Event {
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn moved(actions: &[Action<u32>]) -> Option<(u32, &Target<u32>)> {
|
||||
actions.iter().find_map(|a| match a {
|
||||
Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } => Some((*panel, to)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn hline(y: f32, x: std::ops::RangeInclusive<f32>) -> Rect {
|
||||
Rect::from_x_y_ranges(x, (y - 2.0)..=(y + 2.0))
|
||||
}
|
||||
|
||||
fn vline(x: f32, y: std::ops::RangeInclusive<f32>) -> Rect {
|
||||
Rect::from_x_y_ranges((x - 2.0)..=(x + 2.0), y)
|
||||
}
|
||||
|
||||
/// A floating group's drag bar.
|
||||
fn bar(d: &Driver, panel: u32) -> Pos2 {
|
||||
d.rect("drag-bar", panel).center()
|
||||
}
|
||||
|
||||
// Geometry of `docked(Start, ..)`: the dock is 0..240 wide, its column bar 14 high, and two open
|
||||
// groups share 14..600, meeting at y = 307.
|
||||
|
||||
#[test]
|
||||
fn group_dropped_on_a_seam_inserts_between_and_shows_a_horizontal_line() {
|
||||
let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [400.0, 300.0, 150.0, 150.0])]);
|
||||
let mut d = Driver::new(layout);
|
||||
assert_eq!(d.tab(3).top(), 307.0);
|
||||
let seam = pos2(120.0, 309.0);
|
||||
d.hold(bar(&d, 5), seam);
|
||||
assert!(d.painted(hline(307.0, 0.0..=240.0)), "a horizontal line across the column at the seam");
|
||||
let out = d.step(vec![button(seam, false)]);
|
||||
assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Group { below: true, height: None } })));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![5], vec![3]]]);
|
||||
assert!(d.layout.floating.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_dropped_on_a_seam_or_column_edge_moves_only_that_panel() {
|
||||
let mut d = Driver::new(docked(Side::Start, &[&[&[2, 3], &[4]]]));
|
||||
let out = d.drag(d.tab(3).center(), pos2(120.0, 309.0));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: 3, anchor: 2, placement: Placement::Group { below: true, height: None } }]);
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3], vec![4]]]);
|
||||
d.settle();
|
||||
d.drag(d.tab(4).center(), pos2(246.0, 200.0));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3]], vec![vec![4]]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_dropped_on_a_top_or_bottom_band_stacks_above_or_below() {
|
||||
for (at, expected) in [
|
||||
// The top quarter of group 2's body, and the bottom quarter of group 3's.
|
||||
(pos2(120.0, 14.0 + 26.0 + 20.0), vec![vec![5], vec![2], vec![3]]),
|
||||
(pos2(120.0, 590.0), vec![vec![2], vec![3], vec![5]]),
|
||||
// The middle of a body joins as tabs.
|
||||
(pos2(120.0, 450.0), vec![vec![2], vec![3, 5]]),
|
||||
] {
|
||||
let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [400.0, 300.0, 150.0, 150.0])]);
|
||||
let mut d = Driver::new(layout);
|
||||
d.drag(bar(&d, 5), at);
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![expected], "{at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_dropped_on_a_column_edge_makes_a_new_column() {
|
||||
// The dock's inner edge: a column after the existing one, previewed full height.
|
||||
let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [400.0, 300.0, 150.0, 150.0])]);
|
||||
let mut d = Driver::new(layout.clone());
|
||||
let edge = pos2(246.0, 200.0);
|
||||
d.hold(bar(&d, 5), edge);
|
||||
assert!(d.painted(vline(240.0, 0.0..=600.0)), "a vertical line the full height of the dock");
|
||||
let out = d.step(vec![button(edge, false)]);
|
||||
assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Column { after: true } })));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3]], vec![vec![5]]]);
|
||||
assert_eq!(column(&d.layout, 1).width, 150.0, "the new column keeps the window's width");
|
||||
|
||||
// The window edge of the outermost column: a column before it.
|
||||
let mut d = Driver::new(layout);
|
||||
d.drag(bar(&d, 5), pos2(3.0, 200.0));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]], vec![vec![2], vec![3]]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_dropped_on_the_window_edge_without_a_dock_makes_a_new_dock() {
|
||||
for (side, at, new) in [(Side::Start, pos2(595.0, 200.0), Side::End), (Side::End, pos2(4.0, 200.0), Side::Start)] {
|
||||
let layout = with_floating(docked(side, &[&[&[2]]]), &[(5, [300.0, 300.0, 150.0, 150.0])]);
|
||||
let mut d = Driver::new(layout);
|
||||
d.hold(bar(&d, 5), at);
|
||||
let x = if new == Side::End { 598.0 } else { 2.0 };
|
||||
assert!(d.painted(vline(x, 0.0..=600.0)), "{new:?}: a vertical line at the window edge");
|
||||
let out = d.step(vec![button(at, false)]);
|
||||
assert_eq!(moved(&out.actions), Some((5, &Target::NewDock { side: new })));
|
||||
assert_eq!(columns(&d.layout, new), vec![vec![vec![5]]]);
|
||||
assert_eq!(columns(&d.layout, side), vec![vec![vec![2]]]);
|
||||
// The new dock is drawn on its edge, its »/« button at the window edge.
|
||||
d.settle();
|
||||
let button = d.rect("column-collapse", 5);
|
||||
assert!(if new == Side::End { button.right() == 600.0 } else { button.left() == 0.0 }, "{button:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_dragged_to_the_window_edge_without_a_dock_makes_a_dock_of_that_panel() {
|
||||
let mut d = testing::DockDriver::new(docked(Side::Start, &[&[&[2, 3]]]), TestContent::default());
|
||||
let tab = d.hit(&Hit::Tab(3)).unwrap_or_else(|| panic!("{:?}", d.hits()));
|
||||
let out = d.drag(tab.center(), pos2(795.0, 300.0));
|
||||
assert!(out.actions.contains(&Action::MovePanel { panel: 3, to: Target::NewDock { side: Side::End } }), "{:?}", out.actions);
|
||||
assert_eq!(columns(&d.layout, Side::End), vec![vec![vec![3]]]);
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2]]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_takes_groups_anywhere_in_it_and_as_tabs() {
|
||||
let windows = [(5, [400.0, 40.0, 150.0, 120.0]), (6, [400.0, 220.0, 150.0, 120.0]), (7, [400.0, 400.0, 150.0, 120.0])];
|
||||
let mut d = Driver::new(with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &windows));
|
||||
// Onto group 3's tab strip: joins as a tab.
|
||||
d.drag(bar(&d, 5), pos2(d.tab(3).right() + 20.0, d.tab(3).center().y));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3, 5]]]);
|
||||
// Onto the middle of group 2's body: joins as the last tab.
|
||||
d.drag(bar(&d, 6), pos2(120.0, 160.0));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2, 6], vec![3, 5]]]);
|
||||
// Into the room under the groups, every group minimized: below the last group.
|
||||
d.step(vec![Event::PointerMoved(pos2(700.0, 10.0))]);
|
||||
let mut minimized = d.layout.clone();
|
||||
for panel in [2, 3] {
|
||||
minimized.apply(Action::SetMinimized { panel, minimized: true }).unwrap();
|
||||
}
|
||||
d.layout = minimized;
|
||||
d.step(vec![]);
|
||||
d.drag(bar(&d, 7), pos2(120.0, 500.0));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2, 6], vec![3, 5], vec![7]]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_too_tall_for_the_window_scrolls() {
|
||||
let groups: [&[u32]; 5] = [&[2], &[3], &[4], &[5], &[6]];
|
||||
let mut d = Driver::with(docked(Side::Start, &[&groups]), TestContent { min_height: 160.0 }, false);
|
||||
let last = d.tab(6);
|
||||
assert!(last.top() > 600.0, "the last group starts below the window: {last:?}");
|
||||
let over = d.tab(2).center();
|
||||
for _ in 0..6 {
|
||||
d.step(vec![
|
||||
Event::PointerMoved(over),
|
||||
Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -200.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
]);
|
||||
}
|
||||
d.wait();
|
||||
let moved = d.tab(6);
|
||||
assert!(moved.top() < last.top() - 100.0, "scrolled up: {moved:?} from {last:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_bar_drag_moves_the_column_and_away_from_a_dock_floats_its_groups() {
|
||||
let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[3]], &[&[5]]]));
|
||||
// The second column to the window edge: it becomes the first.
|
||||
let out = d.drag(d.rect("column-bar", 5).center(), pos2(3.0, 200.0));
|
||||
assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Column { after: false } })));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]], vec![vec![2], vec![3]]]);
|
||||
d.settle();
|
||||
// Away from the dock: a floating window holding the column's groups.
|
||||
let source = Rect::from_min_max(pos2(240.0, 0.0), pos2(480.0, 600.0));
|
||||
assert_eq!(d.rect("column-bar", 2).left(), 240.0 + 18.0);
|
||||
let grab = d.rect("column-bar", 2).center();
|
||||
d.hold(grab, pos2(560.0, 300.0));
|
||||
// The column's width; a docked column floats at most 320 pt tall.
|
||||
let size = vec2(source.width(), 320.0);
|
||||
let ghost = egui::Rect::from_min_size(pos2(560.0, 300.0) - (grab - source.min), size);
|
||||
let ghost = egui::Rect::from_min_size(ghost.min.min(pos2(800.0, 600.0) - size).max(Pos2::ZERO), size);
|
||||
assert!(
|
||||
d.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == ghost && r.fill != egui::Color32::TRANSPARENT)),
|
||||
"a ghost of the column follows the pointer"
|
||||
);
|
||||
let out = d.step(vec![button(pos2(560.0, 300.0), false)]);
|
||||
assert!(matches!(moved(&out.actions), Some((2, Target::Float { .. }))), "{:?}", out.actions);
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]]]);
|
||||
assert_eq!(d.layout.floating[0].groups(), vec![group(&[2]), group(&[3])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_drag_escape_focus_loss_pointer_exit_and_cancel_drag_leave_the_layout_unchanged() {
|
||||
let layout = docked(Side::Start, &[&[&[2], &[3]], &[&[5]]]);
|
||||
for case in ["escape", "focus", "exit", "cancel"] {
|
||||
let mut d = Driver::new(layout.clone());
|
||||
let target = pos2(3.0, 200.0);
|
||||
let held = d.hold(d.rect("column-bar", 5).center(), target);
|
||||
assert_eq!(held.group_drag, Some(5), "{case}");
|
||||
let out = match case {
|
||||
"escape" => d.step(vec![key(egui::Key::Escape)]),
|
||||
"focus" => {
|
||||
d.focused = false;
|
||||
let out = d.step(vec![]);
|
||||
d.focused = true;
|
||||
out
|
||||
}
|
||||
"exit" => d.step(vec![Event::PointerGone]),
|
||||
_ => {
|
||||
cancel_drag::<u32>(&d.ctx, Id::new(AREA));
|
||||
d.step(vec![Event::PointerMoved(target + vec2(1.0, 0.0))])
|
||||
}
|
||||
};
|
||||
assert!(out.actions.is_empty(), "{case}: {out:?}");
|
||||
let out = d.step(vec![Event::PointerMoved(target), button(target, false)]);
|
||||
assert!(out.actions.is_empty() && out.group_drag.is_none(), "{case}: {out:?}");
|
||||
assert_eq!(d.layout, layout, "{case}");
|
||||
assert!(!is_dragging::<u32>(&d.ctx, Id::new(AREA)), "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_and_group_dividers_resize_and_minimized_groups_keep_their_height() {
|
||||
let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[4]]]));
|
||||
// The dock's inner edge widens its column; the canvas gives way.
|
||||
d.drag(pos2(240.0, 300.0), pos2(280.0, 300.0));
|
||||
assert_eq!(column(&d.layout, 0).width, 280.0);
|
||||
d.settle();
|
||||
assert_eq!(d.rect("column-bar", 2).right(), 280.0);
|
||||
// The divider between the groups saves both heights.
|
||||
d.wait();
|
||||
d.drag(pos2(120.0, 307.0), pos2(120.0, 357.0));
|
||||
let groups = column(&d.layout, 0).groups;
|
||||
assert_eq!((groups[0].height, groups[1].height), (Some(343.0), Some(243.0)));
|
||||
d.settle();
|
||||
assert_eq!(d.tab(4).top(), 357.0);
|
||||
// Minimized, the lower group keeps its saved height and the upper one takes the room.
|
||||
d.layout.apply(Action::SetMinimized { panel: 4, minimized: true }).unwrap();
|
||||
d.settle();
|
||||
assert_eq!(column(&d.layout, 0).groups[1].height, Some(243.0));
|
||||
assert_eq!(d.tab(4).top(), 600.0 - 26.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_divider_dragged_past_the_lower_groups_minimum_shrinks_the_next_group() {
|
||||
let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[3], &[4]]]));
|
||||
let divider = d.rect("group-resize", 2).center();
|
||||
d.drag(divider, divider + vec2(0.0, 500.0));
|
||||
// Groups 3 and 4 are at their minimum: a tab strip and a 40 pt body.
|
||||
let heights = column(&d.layout, 0).groups.iter().map(|g| g.height).collect::<Vec<_>>();
|
||||
assert_eq!(heights[1..], [Some(66.0), Some(66.0)], "{heights:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_on_a_docked_tab_minimizes_and_clicking_another_tab_expands() {
|
||||
let mut d = Driver::new(docked(Side::Start, &[&[&[2, 3], &[4]]]));
|
||||
let minimized = |d: &Driver| column(&d.layout, 0).groups[0].minimized;
|
||||
let tab = d.tab(2).center();
|
||||
d.click(tab);
|
||||
d.click(tab);
|
||||
assert!(minimized(&d));
|
||||
d.settle();
|
||||
assert_eq!(d.tab(4).top(), 14.0 + 26.0, "the minimized group takes its strip");
|
||||
d.wait();
|
||||
d.click(d.tab(3).center());
|
||||
assert!(!minimized(&d));
|
||||
assert_eq!(column(&d.layout, 0).groups[0].active_panel(), Some(&3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapse_button_and_column_bar_double_click_emit_set_iconic() {
|
||||
let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[3]]]));
|
||||
let iconic = |d: &Driver| column(&d.layout, 0).iconic;
|
||||
let button = d.rect("column-collapse", 2).center();
|
||||
let out = d.click(button);
|
||||
assert_eq!(out.actions, vec![Action::SetIconic { panel: 2, iconic: true }]);
|
||||
assert!(iconic(&d));
|
||||
d.wait();
|
||||
d.click(d.rect("column-collapse", 2).center());
|
||||
assert!(!iconic(&d));
|
||||
d.wait();
|
||||
let bar = d.rect("column-bar", 2).center();
|
||||
d.click(bar);
|
||||
d.click(bar);
|
||||
assert!(iconic(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_targets_respect_occlusion_by_floating_windows() {
|
||||
// Window 5 covers the column's seam at x 150..240; window 6 is dragged.
|
||||
let windows = [(5, [150.0, 250.0, 200.0, 150.0]), (6, [400.0, 450.0, 150.0, 120.0])];
|
||||
let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &windows);
|
||||
let mut d = Driver::new(layout.clone());
|
||||
let out = d.drag(bar(&d, 6), pos2(200.0, 309.0));
|
||||
assert!(matches!(moved(&out.actions), Some((6, Target::At { anchor: 5, .. }))), "joins the window in front: {:?}", out.actions);
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3]]]);
|
||||
// Left of the window, the seam takes it.
|
||||
let mut d = Driver::new(layout);
|
||||
d.drag(bar(&d, 6), pos2(100.0, 309.0));
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![6], vec![3]]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_mirrors_docks_their_edges_and_new_docks() {
|
||||
let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [100.0, 300.0, 150.0, 150.0])]);
|
||||
let mut d = Driver::with(layout.clone(), TestContent::default(), true);
|
||||
// The start dock is on the right, its »/« button at the window edge.
|
||||
let column_bar = d.rect("column-bar", 2);
|
||||
assert_eq!((column_bar.left(), column_bar.right()), (360.0, 600.0 - 18.0));
|
||||
// Its inner edge is on the left: dragging it left widens the column.
|
||||
d.drag(pos2(360.0, 300.0), pos2(320.0, 300.0));
|
||||
assert_eq!(column(&d.layout, 0).width, 280.0);
|
||||
// The left window edge has no dock: a new end dock.
|
||||
d.wait();
|
||||
let out = d.drag(bar(&d, 5), pos2(4.0, 200.0));
|
||||
assert_eq!(moved(&out.actions), Some((5, &Target::NewDock { side: Side::End })));
|
||||
d.settle();
|
||||
assert_eq!(d.rect("column-collapse", 5).left(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_s_first_tab_dropped_on_its_own_column_edge_anchors_on_another_panel() {
|
||||
// Two columns, 0..240 and 240..480; the dragged tab is the first panel of the last one.
|
||||
let wide = |columns: &[&[&[u32]]]| {
|
||||
let mut layout = docked(Side::Start, columns);
|
||||
if let Some(Node::Split { size, .. }) = &mut layout.root {
|
||||
*size = SplitSize::FixedFirst(480.0);
|
||||
}
|
||||
layout
|
||||
};
|
||||
let mut d = Driver::new(wide(&[&[&[2]], &[&[3, 4]]]));
|
||||
let out = d.drag(d.tab(3).center(), pos2(484.0, 300.0));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: 3, anchor: 4, placement: Placement::Column { after: true } }]);
|
||||
assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2]], vec![vec![4]], vec![vec![3]]]);
|
||||
|
||||
// Alone in its column, the panel stays where it is.
|
||||
let layout = wide(&[&[&[2]], &[&[3]]]);
|
||||
let mut d = Driver::new(layout.clone());
|
||||
let out = d.drag(d.tab(3).center(), pos2(484.0, 300.0));
|
||||
assert_eq!(out.actions, vec![]);
|
||||
assert_eq!(d.layout, layout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dock_wider_than_the_window_shrinks_to_fit_and_resizes() {
|
||||
let widths = render::fit_widths(&[(600.0, Some(40.0)), (600.0, Some(40.0)), (48.0, None)], 800.0);
|
||||
assert!((widths.iter().sum::<f32>() - 800.0).abs() < 0.01 && widths[2] == 48.0, "{widths:?}");
|
||||
assert_eq!(render::fit_widths(&[(600.0, Some(300.0)), (600.0, Some(300.0))], 400.0), vec![300.0, 300.0]);
|
||||
|
||||
// Three 600-wide columns saved on a larger screen, in an 800-wide window.
|
||||
let mut layout = docked(Side::Start, &[&[&[1]], &[&[2]], &[&[3]]]);
|
||||
if let Some(Node::Split { first, .. }) = &mut layout.root
|
||||
&& let Node::Dock { columns, .. } = &mut **first
|
||||
{
|
||||
for column in columns {
|
||||
column.width = 600.0;
|
||||
}
|
||||
}
|
||||
let mut d = testing::DockDriver::new(layout, TestContent::default());
|
||||
for panel in [1, 2, 3] {
|
||||
let divider = d.hit(&Hit::Divider(Divider::Column(panel))).unwrap();
|
||||
assert!(d.hit(&Hit::Tab(panel)).is_some_and(|tab| tab.width() > 0.0), "{panel}");
|
||||
assert!(divider.right() < 800.0, "{panel}: {divider:?}");
|
||||
}
|
||||
let divider = d.hit(&Hit::Divider(Divider::Column(1))).unwrap().center();
|
||||
d.press(divider);
|
||||
d.move_to(divider + vec2(-8.0, 0.0));
|
||||
let out = d.move_to(divider + vec2(-30.0, 0.0));
|
||||
assert!(out.error.is_none() && !out.actions.is_empty(), "{out:?}");
|
||||
for action in &out.actions {
|
||||
assert!(matches!(action, Action::ResizeColumn { width, .. } if *width > 0.0), "{action:?}");
|
||||
}
|
||||
d.release(divider + vec2(-30.0, 0.0));
|
||||
let total: f32 = (0..3).map(|i| column(&d.layout, i).width).sum();
|
||||
assert!(total < 800.0, "{total}");
|
||||
assert!((d.hit(&Hit::Divider(Divider::Column(1))).unwrap().center().x - (divider.x - 30.0)).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_reader_values_follow_the_column_width_on_either_edge() {
|
||||
use egui::accesskit::{Action as A, ActionData, ActionRequest, TreeId};
|
||||
for (side, right_to_left) in [(Side::End, false), (Side::Start, true), (Side::Start, false)] {
|
||||
let mut d = testing::DockDriver::new(docked(side, &[&[&[2]]]), TestContent::default()).with_style(move |s| s.right_to_left = right_to_left);
|
||||
d.ctx.enable_accesskit();
|
||||
d.settle();
|
||||
let id = DockArea::<u32>::hit_id(d.id, &Hit::Divider(Divider::Column(2)));
|
||||
let request =
|
||||
|action, data| Event::AccessKitActionRequest(ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.accesskit_id(), data });
|
||||
let case = format!("{side:?}, right to left {right_to_left}");
|
||||
let out = d.frame(vec![request(A::SetValue, Some(ActionData::NumericValue(300.0)))]);
|
||||
assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width: 300.0 }], "{case}");
|
||||
let out = d.frame(vec![request(A::Increment, None)]);
|
||||
assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width: 248.0 }], "{case}");
|
||||
// Arrow keys stay physical: right moves the divider right.
|
||||
d.ctx.memory_mut(|m| m.request_focus(id));
|
||||
d.frame(vec![]);
|
||||
let out = d.frame(vec![key(egui::Key::ArrowRight)]);
|
||||
let wider = d.hit(&Hit::Divider(Divider::Column(2))).unwrap().center().x < 400.0;
|
||||
let width = if wider { 248.0 } else { 232.0 };
|
||||
assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width }], "{case}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
//! Floating windows (title bar, stacks, close), the split-tree settings (outer edge, Maximize,
|
||||
//! Ctrl/Cmd undock, frame menu items), hidden panels, native windows and the public chrome.
|
||||
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Context, Event, Id, Modifiers, PointerButton, RawInput, Rect, Vec2, pos2, vec2};
|
||||
|
||||
const AREA: &str = "floating-area";
|
||||
|
||||
fn tabs(panels: &[u32], active: usize) -> Node<u32> {
|
||||
Node::Tabs { panels: panels.to_vec(), active }
|
||||
}
|
||||
|
||||
/// `[1] | [2, 3]` with panel 3 selected.
|
||||
fn frames() -> Layout<u32> {
|
||||
Layout {
|
||||
root: Some(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::FixedFirst(300.0),
|
||||
first: Box::new(tabs(&[1], 0)),
|
||||
second: Box::new(tabs(&[2, 3], 1)),
|
||||
}),
|
||||
floating: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A start dock (`[2, 3]` above `[4]`) beside protected canvas 0; window W1 stacks `[5]` above
|
||||
/// `[6, 7]`; window W2 holds `[8]`.
|
||||
fn workspace() -> Layout<u32> {
|
||||
Layout {
|
||||
root: Some(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::FixedFirst(240.0),
|
||||
first: Box::new(Node::Dock {
|
||||
side: Side::Start,
|
||||
columns: vec![Column::new(vec![Group::new(vec![2, 3], 1), Group::new(vec![4], 0)], 240.0)],
|
||||
}),
|
||||
second: Box::new(tabs(&[0], 0)),
|
||||
}),
|
||||
floating: vec![
|
||||
Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [300.0, 80.0, 240.0, 300.0]).unwrap(),
|
||||
Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Content {
|
||||
native: bool,
|
||||
keep: Vec<u32>,
|
||||
/// Canvas 0 accepts side splits, as an app that opens panels beside it does.
|
||||
beside: bool,
|
||||
drawn: Vec<u32>,
|
||||
}
|
||||
|
||||
impl DockContent<u32> for Content {
|
||||
fn body(&mut self, ui: &mut egui::Ui, panel: &u32) {
|
||||
self.drawn.push(*panel);
|
||||
ui.label("Body");
|
||||
}
|
||||
fn logical_label(&self, panel: &u32) -> String {
|
||||
format!("Panel {panel}")
|
||||
}
|
||||
fn permissions(&self, panel: &u32) -> Permissions {
|
||||
match *panel {
|
||||
0 if self.beside => Permissions { accepts_splits: true, ..Permissions::PROTECTED },
|
||||
0 => Permissions::PROTECTED,
|
||||
_ => Permissions::default(),
|
||||
}
|
||||
}
|
||||
fn allow_native(&self, _: &u32) -> bool {
|
||||
self.native
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Hide {
|
||||
None,
|
||||
All,
|
||||
Keep,
|
||||
}
|
||||
|
||||
/// The style of an editor whose layout is one split tree of tab groups, as FilmCraft sets it.
|
||||
pub(super) fn frame_style(style: &mut DockStyle) {
|
||||
style.side_edge_zones = true;
|
||||
style.new_dock_zones = false;
|
||||
style.close_others_item = true;
|
||||
style.maximize_item = true;
|
||||
style.command_press_floats = true;
|
||||
style.float_on_empty_drop = false;
|
||||
style.title_bar_docks = false;
|
||||
style.float_hint = true;
|
||||
style.wheel_selects_tabs = true;
|
||||
style.middle_click_closes_tabs = true;
|
||||
style.float_label = "Undock Panel".into();
|
||||
style.float_group_label = "Undock Panel Group".into();
|
||||
style.close_group_label = "Close Panel Group".into();
|
||||
}
|
||||
|
||||
struct Driver {
|
||||
ctx: Context,
|
||||
layout: Layout<u32>,
|
||||
content: Content,
|
||||
split_tree: bool,
|
||||
maximized: Option<u32>,
|
||||
hide: Hide,
|
||||
modifiers: Modifiers,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl Driver {
|
||||
fn new(layout: Layout<u32>, split_tree: bool) -> Self {
|
||||
let mut driver = Self {
|
||||
ctx: Context::default(),
|
||||
layout,
|
||||
content: Content::default(),
|
||||
split_tree,
|
||||
maximized: None,
|
||||
hide: Hide::None,
|
||||
modifiers: Modifiers::NONE,
|
||||
time: 0.0,
|
||||
};
|
||||
driver.step(vec![]);
|
||||
driver.step(vec![]);
|
||||
driver
|
||||
}
|
||||
|
||||
fn frame(&mut self, mut events: Vec<Event>) -> DockOutput<u32> {
|
||||
let mut output = DockOutput::default();
|
||||
events.insert(0, Event::ModifiersChanged(self.modifiers));
|
||||
self.time += 1.0 / 60.0;
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))),
|
||||
events,
|
||||
focused: true,
|
||||
time: Some(self.time),
|
||||
..Default::default()
|
||||
};
|
||||
let (layout, content, split_tree, maximized, hide) = (&self.layout, &mut self.content, self.split_tree, self.maximized, self.hide);
|
||||
let keep: Vec<u32> = content.keep.clone();
|
||||
let keep = move |p: &u32| keep.contains(p);
|
||||
let full = self.ctx.run_ui(input, |ui| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
if split_tree {
|
||||
frame_style(&mut style);
|
||||
}
|
||||
let hide = match hide {
|
||||
Hide::None => HidePanels::None,
|
||||
Hide::All => HidePanels::All,
|
||||
Hide::Keep => HidePanels::Except(&keep),
|
||||
};
|
||||
output = DockArea::new(Id::new(AREA)).maximized(maximized).hide_panels(hide).show_content(ui, layout, &style, content);
|
||||
});
|
||||
let mut full = full;
|
||||
full.textures_delta.clear();
|
||||
output
|
||||
}
|
||||
|
||||
fn step(&mut self, events: Vec<Event>) -> DockOutput<u32> {
|
||||
let output = self.frame(events);
|
||||
assert!(output.error.is_none(), "{output:?}");
|
||||
for action in &output.actions {
|
||||
self.layout.apply_with_permissions(action.clone(), |p| self.content.permissions(p)).unwrap();
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn response(&self, id: Id) -> Option<Rect> {
|
||||
self.ctx.read_response(id).map(|r| r.rect)
|
||||
}
|
||||
|
||||
fn title(&self, first: u32) -> Rect {
|
||||
self.response(Id::new(AREA).with(("move-group", Some(&first)))).unwrap()
|
||||
}
|
||||
|
||||
fn tab(&self, panel: u32) -> Option<Rect> {
|
||||
self.response(Id::new(AREA).with(("tab", &panel)))
|
||||
}
|
||||
|
||||
fn hold(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput<u32> {
|
||||
self.step(vec![Event::PointerMoved(from), button(from, true)]);
|
||||
self.step(vec![Event::PointerMoved(from + vec2(8.0, 6.0))]);
|
||||
self.step(vec![Event::PointerMoved(to)])
|
||||
}
|
||||
|
||||
fn drag(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput<u32> {
|
||||
self.hold(from, to);
|
||||
self.step(vec![button(to, false)])
|
||||
}
|
||||
|
||||
fn click(&mut self, at: egui::Pos2) -> DockOutput<u32> {
|
||||
self.step(vec![Event::PointerMoved(at), button(at, true)]);
|
||||
self.step(vec![button(at, false)])
|
||||
}
|
||||
|
||||
fn wait(&mut self) {
|
||||
for _ in 0..45 {
|
||||
self.step(vec![]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn done(mut full: egui::FullOutput) {
|
||||
full.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn button(pos: egui::Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn window_of(layout: &Layout<u32>, panel: u32) -> Option<&Floating<u32>> {
|
||||
layout.floating.iter().find(|w| w.contains(&panel))
|
||||
}
|
||||
|
||||
fn groups_of(window: &Floating<u32>) -> Vec<Vec<u32>> {
|
||||
window.groups().iter().map(|g| g.panels.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_groups() {
|
||||
// The window follows the pointer with every group; Escape puts it back.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(5).center();
|
||||
d.hold(title, title + vec2(40.0, 30.0));
|
||||
assert_eq!(d.layout.floating[0].rect, [340.0, 110.0, 240.0, 300.0]);
|
||||
assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![5], vec![6, 7]]);
|
||||
d.step(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
d.step(vec![button(title + vec2(40.0, 30.0), false)]);
|
||||
assert_eq!(d.layout, workspace());
|
||||
|
||||
// Released over another window's lower band: its tree goes below that window's group,
|
||||
// unless that leaves a group without room; then its panels join that group.
|
||||
let out = d.drag(title, pos2(660.0, 480.0));
|
||||
assert!(
|
||||
out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::At { anchor: 8, placement: Placement::Split(Zone::Center) } }),
|
||||
"{:?}",
|
||||
out.actions
|
||||
);
|
||||
assert_eq!(d.layout.floating.len(), 1);
|
||||
assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![8, 5, 6, 7]]);
|
||||
|
||||
// Released over a docked group's strip: every panel joins it as tabs.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(5).center();
|
||||
let strip = d.tab(4).unwrap().center();
|
||||
let out = d.drag(title, strip);
|
||||
assert!(out.actions.iter().any(|a| matches!(a, Action::MoveWindow { panel: 5, to: Target::At { anchor: 4, .. } })), "{:?}", out.actions);
|
||||
assert!(window_of(&d.layout, 5).is_none() && window_of(&d.layout, 7).is_none());
|
||||
assert_eq!(d.layout.place(&4), d.layout.place(&6));
|
||||
|
||||
// Released over the canvas: the window stays where it was moved and hosts get the release.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(5).center();
|
||||
let out = d.drag(title, pos2(500.0, 300.0));
|
||||
assert!(!out.actions.iter().any(|a| matches!(a, Action::MoveWindow { .. })), "{:?}", out.actions);
|
||||
assert_eq!(out.group_drop, Some((5, pos2(500.0, 300.0))));
|
||||
assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![6, 7]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_bar_drag_onto_dock_targets_docks_the_window() {
|
||||
// Released on the seam between two docked groups: the window's group stacks between them.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(8).center();
|
||||
let seam = pos2(120.0, d.tab(4).unwrap().top());
|
||||
let out = d.drag(title, seam);
|
||||
assert!(
|
||||
out.actions
|
||||
.contains(&Action::MoveWindow { panel: 8, to: Target::At { anchor: 2, placement: Placement::Group { below: true, height: None } } }),
|
||||
"{:?}",
|
||||
out.actions
|
||||
);
|
||||
assert!(window_of(&d.layout, 8).is_none());
|
||||
let Some(Node::Split { first, .. }) = &d.layout.root else { panic!("{:?}", d.layout.root) };
|
||||
let Node::Dock { columns, .. } = first.as_ref() else { panic!("{first:?}") };
|
||||
let stacked: Vec<_> = columns[0].groups.iter().map(|g| g.panels.clone()).collect();
|
||||
assert_eq!(stacked, vec![vec![2, 3], vec![8], vec![4]]);
|
||||
|
||||
// Released on the new-dock band along the right edge: the window becomes an end dock.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(5).center();
|
||||
let out = d.drag(title, pos2(796.0, 300.0));
|
||||
assert!(out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::NewDock { side: Side::End } }), "{:?}", out.actions);
|
||||
assert!(window_of(&d.layout, 5).is_none() && window_of(&d.layout, 6).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_floating_window_is_a_tree_whose_groups_split_and_resize_like_frames() {
|
||||
// A group dragged by its bar to another window's top band splits that window's group.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let bar = d.response(Id::new(AREA).with(("drag-bar", Some(&6u32)))).unwrap().center();
|
||||
let out = d.drag(bar, pos2(660.0, 360.0));
|
||||
assert!(
|
||||
out.actions.contains(&Action::MoveGroup { panel: 6, to: Target::At { anchor: 8, placement: Placement::Split(Zone::Top) } }),
|
||||
"{:?}",
|
||||
out.actions
|
||||
);
|
||||
assert_eq!(groups_of(window_of(&d.layout, 8).unwrap()), vec![vec![6, 7], vec![8]]);
|
||||
assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5]]);
|
||||
|
||||
// The gap between two groups of a window is no target.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let tab = d.tab(8).unwrap().center();
|
||||
let gap = pos2(420.0, d.tab(6).unwrap().top() - 2.0);
|
||||
d.drag(tab, gap);
|
||||
assert_eq!(d.layout, workspace());
|
||||
|
||||
// The divider between them resizes both.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let divider = d.response(DockArea::hit_id(Id::new(AREA), &Hit::Divider(Divider::WindowSplit(5u32, Vec::new())))).unwrap().center();
|
||||
d.drag(divider, divider + vec2(0.0, 40.0));
|
||||
let Node::Split { size: SplitSize::Ratio(ratio), .. } = window_of(&d.layout, 5).unwrap().root else { panic!("{:?}", d.layout) };
|
||||
assert!(ratio > 0.6, "{ratio}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_bar_double_click_minimizes_every_group_and_close_box_closes_the_window() {
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(5).center();
|
||||
d.click(title);
|
||||
d.click(title);
|
||||
assert!(window_of(&d.layout, 5).unwrap().minimized);
|
||||
d.wait();
|
||||
d.click(title);
|
||||
d.click(title);
|
||||
assert!(!window_of(&d.layout, 5).unwrap().minimized);
|
||||
|
||||
let close = d.response(Id::new(AREA).with(("move-group", Some(&5u32))).with("close")).unwrap();
|
||||
assert_eq!(close.center().x, 530.0, "× sits 10 pt in from the right edge");
|
||||
let before = d.layout.clone();
|
||||
d.wait();
|
||||
let out = d.click(close.center());
|
||||
assert_eq!(out.actions, vec![Action::CloseWindow { panel: 5 }]);
|
||||
assert_eq!(before.closed_by(&Action::CloseWindow { panel: 5 }), Ok(vec![5, 6, 7]));
|
||||
assert!(window_of(&d.layout, 6).is_none() && d.layout.contains(&8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_floating_window_reopens_each_panel_at_its_last_rect() {
|
||||
let mut layout = workspace();
|
||||
let locations: Vec<_> = [5, 6, 7].map(|p| (p, layout.location(&p).unwrap())).into();
|
||||
layout.apply(Action::CloseWindow { panel: 6 }).unwrap();
|
||||
for (panel, location) in locations {
|
||||
layout.restore(panel, &location).unwrap();
|
||||
assert_eq!(window_of(&layout, panel).unwrap().rect, [300.0, 80.0, 240.0, 300.0], "{panel}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_drag_from_a_frame_strip_undocks_to_a_floating_window() {
|
||||
let mut d = Driver::new(frames(), true);
|
||||
let tab = d.tab(3).unwrap().center();
|
||||
let other = d.tab(1).unwrap().center();
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
d.hold(tab, other);
|
||||
d.modifiers = Modifiers::NONE;
|
||||
let out = d.step(vec![button(other, false)]);
|
||||
assert!(matches!(out.actions.as_slice(), [Action::Float { panel: 3, .. }]), "{:?}", out.actions);
|
||||
assert!(window_of(&d.layout, 3).is_some());
|
||||
|
||||
// Without the modifier the same drag joins the other frame.
|
||||
let mut d = Driver::new(frames(), true);
|
||||
let out = d.drag(tab, other);
|
||||
assert!(matches!(out.actions.as_slice(), [Action::Move { panel: 3, anchor: 1, .. }]), "{:?}", out.actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outer_edge_band_splits_at_the_root() {
|
||||
// With side edge zones: all four edges.
|
||||
let mut d = Driver::new(frames(), true);
|
||||
let tab = d.tab(3).unwrap().center();
|
||||
let out = d.drag(tab, pos2(3.0, 300.0));
|
||||
assert!(out.actions.contains(&Action::Move { panel: 3, anchor: 1, placement: Placement::Edge(Zone::Left) }), "{:?}", out.actions);
|
||||
let Some(Node::Split { axis: SplitAxis::Horizontal, first, .. }) = &d.layout.root else { panic!("{:?}", d.layout) };
|
||||
assert_eq!(**first, tabs(&[3], 0));
|
||||
|
||||
// The defaults: the bottom edge of the part between the docks, for a Timeline.
|
||||
let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, false);
|
||||
let tab = d.tab(2).unwrap().center();
|
||||
let out = d.drag(tab, pos2(500.0, 597.0));
|
||||
assert!(out.actions.iter().any(|a| matches!(a, Action::Move { panel: 2, placement: Placement::Edge(Zone::Bottom), .. })), "{:?}", out.actions);
|
||||
let Some(Node::Split { first, second, .. }) = &d.layout.root else { panic!() };
|
||||
assert!(matches!(**first, Node::Dock { .. }));
|
||||
assert!(matches!(&**second, Node::Split { axis: SplitAxis::Vertical, second, .. } if **second == tabs(&[2], 0)));
|
||||
|
||||
// Its left and right edges are the docks' (new columns and docks), not root splits.
|
||||
let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, false);
|
||||
let tab = d.tab(4).unwrap().center();
|
||||
let out = d.drag(tab, pos2(246.0, 300.0));
|
||||
assert!(!out.actions.iter().any(|a| matches!(a, Action::Move { placement: Placement::Edge(_), .. })), "{:?}", out.actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximized_frame_fills_the_area_and_other_frames_do_not_render_or_take_input() {
|
||||
let mut layout = frames();
|
||||
layout.floating.push(Floating::single(vec![5], 0, [400.0, 300.0, 200.0, 150.0]));
|
||||
let mut d = Driver::new(layout.clone(), true);
|
||||
let window_title = d.title(5).center();
|
||||
d.maximized = Some(2);
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.tab(2).unwrap().left(), 0.0, "the maximized frame starts at the area's edge");
|
||||
assert!(d.tab(1).is_none());
|
||||
assert!(d.response(Id::new(AREA).with(("move-group", Some(&5u32)))).is_none());
|
||||
let out = d.drag(window_title, window_title + vec2(30.0, 30.0));
|
||||
assert!(out.actions.iter().all(|a| !matches!(a, Action::MoveFloating { .. } | Action::MoveWindow { .. })), "{:?}", out.actions);
|
||||
|
||||
// A floating panel does not maximize.
|
||||
let mut d = Driver::new(layout, true);
|
||||
d.maximized = Some(5);
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert!(d.tab(1).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_other_panels_keeps_only_the_chosen_tab() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
type State = (Content, Vec<Action<u32>>, Vec<DockEvent<u32>>);
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, (content, actions, events): &mut State| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
frame_style(&mut style);
|
||||
let out = DockArea::new(Id::new(AREA)).show_content(ui, &frames(), &style, content);
|
||||
actions.extend(out.actions);
|
||||
events.extend(out.events);
|
||||
},
|
||||
(Content::default(), Vec::new(), Vec::new()),
|
||||
);
|
||||
h.run_steps(2);
|
||||
let at = h.ctx.read_response(Id::new(AREA).with(("tab", &3u32))).unwrap().rect.center();
|
||||
let open_menu = |h: &mut Harness<'_, State>| {
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(at),
|
||||
Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
};
|
||||
open_menu(&mut h);
|
||||
for label in ["Undock Panel", "Close Panel Group", "Undock Panel Group", "Close Other Panels in Group", "Maximize Frame"] {
|
||||
assert_eq!(h.query_all_by_label(label).count(), 1, "{label}");
|
||||
}
|
||||
assert_eq!(h.query_all_by_label("Minimize").count(), 0);
|
||||
h.get_by_label("Close Other Panels in Group").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().1, vec![Action::CloseOthers { panel: 3 }]);
|
||||
let mut layout = frames();
|
||||
layout.apply(Action::CloseOthers { panel: 3 }).unwrap();
|
||||
assert!(layout.contains(&3) && !layout.contains(&2));
|
||||
|
||||
open_menu(&mut h);
|
||||
h.get_by_label("Maximize Frame").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().2, vec![DockEvent::ToggleMaximize { panel: 3 }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_panels_keeps_protected_panels_and_the_except_set() {
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
d.hide = Hide::All;
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
for panel in [2, 3, 4, 5, 6, 8] {
|
||||
assert!(d.tab(panel).is_none(), "{panel}");
|
||||
}
|
||||
assert!(d.layout == workspace(), "hiding leaves the layout unchanged");
|
||||
|
||||
d.hide = Hide::Keep;
|
||||
d.content.keep = vec![4, 6];
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.tab(4).map(|r| r.left()), Some(0.0));
|
||||
assert!(d.tab(6).is_some());
|
||||
for panel in [2, 3, 5, 7, 8] {
|
||||
assert!(d.tab(panel).is_none(), "{panel}");
|
||||
}
|
||||
// A window keeps its rect with its hidden groups left out.
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.title(6).min, pos2(300.0, 84.0), "below the resize band");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canvas_that_accepts_splits_is_still_protected() {
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
d.content.beside = true;
|
||||
d.hide = Hide::All;
|
||||
d.step(vec![]);
|
||||
d.content.drawn.clear();
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.content.drawn, vec![0], "hiding every panel keeps the canvas");
|
||||
assert!(d.tab(0).is_none());
|
||||
assert!(d.response(DockArea::<u32>::hit_id(Id::new(AREA), &Hit::DragBar(0))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_window_falls_back_in_window_when_viewports_are_embedded() {
|
||||
let mut layout = workspace();
|
||||
layout.floating[0].native = Some([1200.0, 900.0, 240.0, 300.0]);
|
||||
let mut d = Driver::new(layout.clone(), false);
|
||||
d.content.native = true;
|
||||
assert!(d.ctx.embed_viewports());
|
||||
let out = d.step(vec![]);
|
||||
assert!(out.actions.is_empty(), "{out:?}");
|
||||
assert_eq!(d.title(5).min, pos2(300.0, 84.0));
|
||||
assert_eq!(d.layout, layout);
|
||||
}
|
||||
|
||||
#[cfg(feature = "native-windows")]
|
||||
#[test]
|
||||
fn native_window_close_returns_the_group_to_its_in_window_rect() {
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
let close = Rc::new(Cell::new(false));
|
||||
let requested = close.clone();
|
||||
// A backend with real viewports: the child reports its place and, when asked, a close.
|
||||
Context::set_immediate_viewport_renderer(move |ctx, mut viewport| {
|
||||
let mut info = egui::ViewportInfo {
|
||||
outer_rect: Some(Rect::from_min_size(pos2(1210.0, 905.0), vec2(250.0, 330.0))),
|
||||
inner_rect: Some(Rect::from_min_size(pos2(1210.0, 935.0), vec2(250.0, 300.0))),
|
||||
..Default::default()
|
||||
};
|
||||
if requested.get() {
|
||||
info.events.push(egui::ViewportEvent::Close);
|
||||
}
|
||||
let input = RawInput {
|
||||
viewport_id: viewport.ids.this,
|
||||
viewports: std::iter::once((viewport.ids.this, info)).collect(),
|
||||
screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(250.0, 300.0))),
|
||||
..Default::default()
|
||||
};
|
||||
done(ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)));
|
||||
});
|
||||
let mut layout = workspace();
|
||||
layout.floating[0].native = Some([1200.0, 900.0, 240.0, 300.0]);
|
||||
let mut d = Driver::new(Layout::default(), false);
|
||||
d.ctx.set_embed_viewports(false);
|
||||
d.content.native = true;
|
||||
d.layout = layout;
|
||||
let out = d.step(vec![]);
|
||||
assert!(d.response(Id::new(AREA).with(("move-group", Some(&5u32)))).is_none(), "drawn in its own OS window");
|
||||
assert!(out.actions.contains(&Action::SetNative { panel: 5, rect: Some([1210.0, 905.0, 250.0, 300.0]) }), "{:?}", out.actions);
|
||||
|
||||
close.set(true);
|
||||
let out = d.step(vec![]);
|
||||
assert!(out.actions.contains(&Action::SetNative { panel: 5, rect: None }), "{:?}", out.actions);
|
||||
assert_eq!(d.layout.floating[0].native, None);
|
||||
assert_eq!(d.layout.floating[0].rect, [300.0, 80.0, 240.0, 300.0]);
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.title(5).min, pos2(300.0, 84.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chrome_frame_and_title_bar_work_without_a_dock_area() {
|
||||
use chrome::{ChromeStyle, FloatingFrame, TitleBar};
|
||||
let ctx = Context::default();
|
||||
let id = Id::new("task-pane");
|
||||
let rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(300.0, 200.0));
|
||||
let mut time = 0.0;
|
||||
let mut frame = |events: Vec<Event>| {
|
||||
time += 1.0 / 60.0;
|
||||
let input =
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), events, time: Some(time), ..Default::default() };
|
||||
let mut result = None;
|
||||
done(ctx.run_ui(input, |ui| {
|
||||
let style = ChromeStyle::from_ui(ui);
|
||||
let shown = FloatingFrame::new(id, rect).show(ui.ctx(), &style, |ui, inner| {
|
||||
let title = Rect::from_min_size(inner.min, vec2(inner.width(), 22.0));
|
||||
let bar = TitleBar::new(id.with("title"), "Move pane").title("Styles").menu("Pane menu").close("Close pane").show(ui, title, &style);
|
||||
(bar.bar.dragged(), bar.bar.drag_delta(), bar.menu.is_some_and(|r| r.clicked()), bar.close.is_some_and(|r| r.clicked()))
|
||||
});
|
||||
result = Some((shown.inner, shown.resized));
|
||||
}));
|
||||
result.unwrap()
|
||||
};
|
||||
frame(vec![]);
|
||||
frame(vec![]);
|
||||
type Shown = ((bool, Vec2, bool, bool), Option<Rect>);
|
||||
let click = |frame: &mut dyn FnMut(Vec<Event>) -> Shown, at| {
|
||||
frame(vec![Event::PointerMoved(at), button(at, true)]);
|
||||
frame(vec![button(at, false)])
|
||||
};
|
||||
let ((_, _, _, closed), _) = click(&mut frame, pos2(390.0, 111.0));
|
||||
assert!(closed, "× 10 pt in from the right");
|
||||
let ((_, _, menu, _), _) = click(&mut frame, pos2(374.0, 111.0));
|
||||
assert!(menu, "▾ left of ×");
|
||||
|
||||
frame(vec![Event::PointerMoved(pos2(200.0, 110.0)), button(pos2(200.0, 110.0), true)]);
|
||||
frame(vec![Event::PointerMoved(pos2(210.0, 115.0))]);
|
||||
let ((dragged, delta, ..), _) = frame(vec![Event::PointerMoved(pos2(230.0, 125.0))]);
|
||||
assert!(dragged && delta == vec2(20.0, 10.0), "{delta:?}");
|
||||
frame(vec![button(pos2(230.0, 125.0), false)]);
|
||||
|
||||
let edge = pos2(398.0, 200.0);
|
||||
frame(vec![Event::PointerMoved(edge), button(edge, true)]);
|
||||
frame(vec![Event::PointerMoved(edge + vec2(10.0, 0.0))]);
|
||||
let (_, resized) = frame(vec![Event::PointerMoved(edge + vec2(50.0, 0.0))]);
|
||||
assert_eq!(resized, Some(Rect::from_min_size(rect.min, vec2(350.0, 200.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_panels_leave_their_split_and_resizing_names_the_layout_path() {
|
||||
let layout = Layout {
|
||||
root: Some(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::FixedFirst(200.0),
|
||||
first: Box::new(tabs(&[9], 0)),
|
||||
second: Box::new(Node::Split {
|
||||
axis: SplitAxis::Vertical,
|
||||
size: SplitSize::Ratio(0.5),
|
||||
first: Box::new(tabs(&[1], 0)),
|
||||
second: Box::new(tabs(&[2], 0)),
|
||||
}),
|
||||
}),
|
||||
floating: Vec::new(),
|
||||
};
|
||||
let mut d = Driver::new(layout, true);
|
||||
d.hide = Hide::Keep;
|
||||
d.content.keep = vec![1, 2];
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.tab(1).map(|r| r.left()), Some(0.0), "the hidden frame's space goes to the others");
|
||||
// Hits and widget ids name the split by its layout path, as `ResizeSplit` does.
|
||||
let hit = Hit::Divider(Divider::Split(vec![true]));
|
||||
assert!(DockArea::<u32>::hit_rects(&d.ctx, Id::new(AREA)).iter().any(|(h, _)| *h == hit), "the hits name the layout path");
|
||||
let divider = d.response(DockArea::<u32>::hit_id(Id::new(AREA), &hit)).unwrap().center();
|
||||
let out = d.hold(divider, divider + vec2(0.0, 60.0));
|
||||
assert!(out.actions.iter().any(|a| matches!(a, Action::ResizeSplit { path, .. } if path == &vec![true])), "{:?}", out.actions);
|
||||
let Some(Node::Split { size: SplitSize::FixedFirst(200.0), second, .. }) = &d.layout.root else { panic!("{:?}", d.layout) };
|
||||
assert!(matches!(**second, Node::Split { size, .. } if size != SplitSize::Ratio(0.5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_floating_window_does_not_cover_dock_targets() {
|
||||
// Window 5 covers the column's seam at x 150..240 until it is hidden.
|
||||
let mut layout = workspace();
|
||||
layout.floating = vec![Floating::single(vec![5], 0, [150.0, 250.0, 200.0, 150.0]), Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0])];
|
||||
let mut d = Driver::new(layout, false);
|
||||
d.hide = Hide::Keep;
|
||||
d.content.keep = vec![2, 3, 4, 8];
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
d.drag(d.title(8).center(), pos2(200.0, 309.0));
|
||||
let Some(Node::Split { first, .. }) = &d.layout.root else { panic!("{:?}", d.layout.root) };
|
||||
let Node::Dock { columns, .. } = &**first else { panic!("{first:?}") };
|
||||
let groups: Vec<Vec<u32>> = columns[0].groups.iter().map(|g| g.panels.clone()).collect();
|
||||
assert_eq!(groups, vec![vec![2, 3], vec![8], vec![4]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_edges_resize_from_the_band_above_the_title_bar() {
|
||||
// W2 holds [8] at [560, 300, 200, 200]; each top handle keeps the opposite edges.
|
||||
let area = Id::new(AREA);
|
||||
for (edge, by, expected) in [
|
||||
(ResizeEdge::Top, vec2(0.0, -40.0), [560.0, 260.0, 200.0, 240.0]),
|
||||
(ResizeEdge::TopLeft, vec2(-30.0, 20.0), [530.0, 320.0, 230.0, 180.0]),
|
||||
(ResizeEdge::TopRight, vec2(20.0, -10.0), [560.0, 290.0, 220.0, 210.0]),
|
||||
] {
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let handle = d.response(DockArea::hit_id(area, &Hit::Resize(8u32, edge))).unwrap();
|
||||
assert_eq!(handle.bottom(), d.title(8).top(), "{edge:?} lies above the title bar");
|
||||
d.drag(handle.center(), handle.center() + by);
|
||||
assert_eq!(window_of(&d.layout, 8).unwrap().rect, expected, "{edge:?}");
|
||||
}
|
||||
// The title bar still moves the window, and arrow keys move the focused top edge.
|
||||
let mut d = Driver::new(workspace(), false);
|
||||
let title = d.title(8);
|
||||
d.drag(pos2(title.center().x, title.top() + 1.0), pos2(title.center().x - 50.0, title.top() + 1.0));
|
||||
assert_eq!(window_of(&d.layout, 8).unwrap().rect, [510.0, 300.0, 200.0, 200.0]);
|
||||
d.ctx.memory_mut(|m| m.request_focus(DockArea::hit_id(area, &Hit::Resize(8u32, ResizeEdge::Top))));
|
||||
d.step(vec![Event::Key { key: egui::Key::ArrowUp, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
assert_eq!(window_of(&d.layout, 8).unwrap().rect, [510.0, 292.0, 200.0, 208.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undock_panel_group_floats_one_group_of_a_floating_window() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let stacked = || Layout {
|
||||
root: Some(tabs(&[1], 0)),
|
||||
floating: vec![Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 0)], [300.0, 80.0, 300.0, 400.0]).unwrap()],
|
||||
};
|
||||
type State = (Content, Layout<u32>, Vec<Action<u32>>);
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, (content, layout, actions): &mut State| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
frame_style(&mut style);
|
||||
let out = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content);
|
||||
actions.extend(out.actions);
|
||||
},
|
||||
(Content::default(), stacked(), Vec::new()),
|
||||
);
|
||||
h.run_steps(2);
|
||||
let menu = |h: &mut Harness<'_, State>, panel: u32| {
|
||||
let at = h.ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect.center();
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(at),
|
||||
Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
};
|
||||
menu(&mut h, 6);
|
||||
h.get_by_label("Undock Panel Group").click();
|
||||
h.run_steps(2);
|
||||
let actions = std::mem::take(&mut h.state_mut().2);
|
||||
assert!(matches!(&actions[..], [Action::MoveGroup { panel: 6, to: Target::Float { rect: Some(_) } }]), "{actions:?}");
|
||||
let mut layout = stacked();
|
||||
layout.apply_all(actions, |_| Permissions::default()).unwrap();
|
||||
assert_eq!(layout.floating.iter().map(groups_of).collect::<Vec<_>>(), vec![vec![vec![5]], vec![vec![6, 7]]]);
|
||||
|
||||
// A window's only group has nothing to undock from.
|
||||
h.state_mut().1 = layout;
|
||||
h.run_steps(2);
|
||||
menu(&mut h, 5);
|
||||
assert_eq!(h.query_all_by_label("Undock Panel Group").count(), 0);
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
//! Whole-group gestures: drag bar, top border, drop resolution, minimize and the floating frame.
|
||||
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Color32, Context, Event, Id, Modifiers, PointerButton, RawInput, Rect, UiBuilder, Vec2, pos2, vec2};
|
||||
|
||||
const AREA: &str = "group-area";
|
||||
|
||||
#[path = "trial_tests.rs"]
|
||||
mod trial;
|
||||
|
||||
fn tabs(panels: &[u32], active: usize) -> Node<u32> {
|
||||
Node::Tabs { panels: panels.to_vec(), active }
|
||||
}
|
||||
|
||||
/// `[1] | [2, 3]` with panel 3 selected.
|
||||
fn frames() -> Layout<u32> {
|
||||
Layout {
|
||||
root: Some(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::FixedFirst(300.0),
|
||||
first: Box::new(tabs(&[1], 0)),
|
||||
second: Box::new(tabs(&[2, 3], 1)),
|
||||
}),
|
||||
floating: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A start dock with one column holding `[2, 3]` (3 selected) above `[4]`, beside canvas 0.
|
||||
fn docked() -> Layout<u32> {
|
||||
Layout {
|
||||
root: Some(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::FixedFirst(240.0),
|
||||
first: Box::new(Node::Dock {
|
||||
side: Side::Start,
|
||||
columns: vec![Column::new(vec![Group::new(vec![2, 3], 1), Group::new(vec![4], 0)], 240.0)],
|
||||
}),
|
||||
second: Box::new(tabs(&[0], 0)),
|
||||
}),
|
||||
floating: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestContent {
|
||||
protected: Vec<u32>,
|
||||
header: f32,
|
||||
header_clicks: usize,
|
||||
/// The strip width the last header was sized for.
|
||||
strip_width: std::cell::Cell<f32>,
|
||||
floating_size: Option<Vec2>,
|
||||
host_owned: bool,
|
||||
whole_group: bool,
|
||||
/// Height every body takes; `None` draws a one-line label.
|
||||
body_height: Option<f32>,
|
||||
/// Every body takes its whole rect.
|
||||
fill: bool,
|
||||
}
|
||||
|
||||
impl DockContent<u32> for TestContent {
|
||||
fn body(&mut self, ui: &mut egui::Ui, _: &u32) {
|
||||
if self.fill {
|
||||
ui.allocate_rect(ui.max_rect(), egui::Sense::hover());
|
||||
return;
|
||||
}
|
||||
match self.body_height {
|
||||
Some(height) => _ = ui.allocate_exact_size(vec2(10.0, height), egui::Sense::hover()),
|
||||
None => _ = ui.label("Body"),
|
||||
}
|
||||
}
|
||||
fn logical_label(&self, panel: &u32) -> String {
|
||||
format!("Panel {panel}")
|
||||
}
|
||||
fn permissions(&self, panel: &u32) -> Permissions {
|
||||
if self.protected.contains(panel) { Permissions::PROTECTED } else { Permissions::default() }
|
||||
}
|
||||
fn floating_size(&self, _: &u32) -> Option<Vec2> {
|
||||
self.floating_size
|
||||
}
|
||||
fn resolve_drag(&mut self, _: &Context, _: &DockStyle, request: &DropRequest<'_, u32>) -> Option<DropFeedback> {
|
||||
self.whole_group |= request.whole_group;
|
||||
self.host_owned.then(DropFeedback::default)
|
||||
}
|
||||
fn group_header_width(&self, _: &[u32], _: &u32, _: bool, strip_width: f32) -> f32 {
|
||||
self.strip_width.set(strip_width);
|
||||
self.header
|
||||
}
|
||||
fn group_header(&mut self, ui: &mut egui::Ui, _: &[u32], _: &u32, _: bool) {
|
||||
if ui.button("≡").clicked() {
|
||||
self.header_clicks += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders a layout through `show_content` in `area` of an 800x600 window and applies what
|
||||
/// it emits, the way an application's command handler would.
|
||||
struct Driver {
|
||||
ctx: Context,
|
||||
layout: Layout<u32>,
|
||||
content: TestContent,
|
||||
area: Rect,
|
||||
modifiers: Modifiers,
|
||||
focused: bool,
|
||||
transparent: bool,
|
||||
/// Applied to the style every frame.
|
||||
tweak: fn(&mut DockStyle),
|
||||
shapes: Vec<egui::epaint::ClippedShape>,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl Driver {
|
||||
fn new(layout: Layout<u32>) -> Self {
|
||||
Self::with(layout, TestContent::default(), Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)))
|
||||
}
|
||||
|
||||
fn with(layout: Layout<u32>, content: TestContent, area: Rect) -> Self {
|
||||
let mut driver = Self {
|
||||
ctx: Context::default(),
|
||||
layout,
|
||||
content,
|
||||
area,
|
||||
modifiers: Modifiers::NONE,
|
||||
focused: true,
|
||||
transparent: false,
|
||||
tweak: |_| {},
|
||||
shapes: Vec::new(),
|
||||
time: 0.0,
|
||||
};
|
||||
driver.step(vec![]);
|
||||
driver.step(vec![]);
|
||||
driver
|
||||
}
|
||||
|
||||
fn frame(&mut self, mut events: Vec<Event>) -> DockOutput<u32> {
|
||||
let mut output = DockOutput::default();
|
||||
events.insert(0, Event::ModifiersChanged(self.modifiers));
|
||||
self.time += 1.0 / 60.0;
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))),
|
||||
events,
|
||||
focused: self.focused,
|
||||
time: Some(self.time),
|
||||
..Default::default()
|
||||
};
|
||||
let (layout, content, area, transparent, tweak) = (&self.layout, &mut self.content, self.area, self.transparent, self.tweak);
|
||||
let mut full = self.ctx.run_ui(input, |ui| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
if transparent {
|
||||
style.background = Color32::TRANSPARENT;
|
||||
style.tab_background = Color32::TRANSPARENT;
|
||||
}
|
||||
tweak(&mut style);
|
||||
ui.scope_builder(UiBuilder::new().max_rect(area), |ui| {
|
||||
output = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content);
|
||||
});
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
self.shapes = full.shapes;
|
||||
output
|
||||
}
|
||||
|
||||
fn step(&mut self, events: Vec<Event>) -> DockOutput<u32> {
|
||||
let output = self.frame(events);
|
||||
assert!(output.error.is_none(), "{output:?}");
|
||||
let permissions = |p: &u32| self.content.permissions(p);
|
||||
for action in &output.actions {
|
||||
self.layout.apply_with_permissions(action.clone(), permissions).unwrap();
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn rect(&self, name: &str, panel: u32) -> Rect {
|
||||
self.ctx.read_response(Id::new(AREA).with((name, Some(&panel)))).unwrap().rect
|
||||
}
|
||||
|
||||
fn tab(&self, panel: u32) -> Rect {
|
||||
self.ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect
|
||||
}
|
||||
|
||||
/// Press at `from`, pass the drag threshold, move to `to`; returns the last move's output.
|
||||
fn hold(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput<u32> {
|
||||
self.step(vec![Event::PointerMoved(from), button(from, true)]);
|
||||
self.step(vec![Event::PointerMoved(from + vec2(8.0, 6.0))]);
|
||||
self.step(vec![Event::PointerMoved(to)])
|
||||
}
|
||||
|
||||
/// A full drag; returns the release frame's output.
|
||||
fn drag(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput<u32> {
|
||||
self.hold(from, to);
|
||||
self.step(vec![button(to, false)])
|
||||
}
|
||||
|
||||
/// Lets egui's double- and triple-click windows pass.
|
||||
fn wait(&mut self) {
|
||||
for _ in 0..45 {
|
||||
self.step(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
fn click(&mut self, at: egui::Pos2) -> DockOutput<u32> {
|
||||
self.step(vec![Event::PointerMoved(at), button(at, true)]);
|
||||
self.step(vec![button(at, false)])
|
||||
}
|
||||
}
|
||||
|
||||
fn button(pos: egui::Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn key(key: egui::Key) -> Event {
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn moved_group(actions: &[Action<u32>]) -> Option<&Target<u32>> {
|
||||
actions.iter().find_map(|a| match a {
|
||||
Action::MoveGroup { to, .. } => Some(to),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docked_two_tab_group_drags_by_its_bar_and_keeps_order_and_active_tab() {
|
||||
// Onto another group's strip: one MoveGroup, both panels in order, 3 still selected.
|
||||
let mut d = Driver::new(frames());
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
assert!(bar.width() >= 40.0);
|
||||
let out = d.drag(bar.center(), d.tab(1).center());
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, placement: Placement::Tab { .. } })), "{:?}", out.actions);
|
||||
assert_eq!(out.actions.len(), 1);
|
||||
assert!(out.group_drop.is_none(), "a resolved target leaves group_drop empty");
|
||||
assert_eq!(d.layout.root, Some(tabs(&[1, 2, 3], 2)));
|
||||
|
||||
// Onto empty space: a floating window at the group's docked size.
|
||||
let mut d = Driver::new(frames());
|
||||
let border = d.rect("drag-border", 2);
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
let out = d.drag(bar.center(), pos2(700.0, 200.0));
|
||||
let Some(Target::Float { rect: Some([_, _, width, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) };
|
||||
assert_eq!((*width, *height), (border.width(), 600.0));
|
||||
assert_eq!(out.group_drop, Some((2, pos2(700.0, 200.0))));
|
||||
assert_eq!(d.layout.root, Some(tabs(&[1], 0)));
|
||||
assert_eq!(d.layout.floating[0].groups(), vec![Group::new(vec![2, 3], 1)]);
|
||||
|
||||
// The same group in a dock column joins the group below it.
|
||||
let mut d = Driver::new(docked());
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
let out = d.drag(bar.center(), d.tab(4).center());
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 4, .. })), "{:?}", out.actions);
|
||||
let Some(Node::Split { first, .. }) = &d.layout.root else { panic!() };
|
||||
let Node::Dock { columns, .. } = first.as_ref() else { panic!() };
|
||||
assert_eq!(columns[0].groups.len(), 1);
|
||||
assert_eq!(columns[0].groups[0].panels, vec![4, 2, 3]);
|
||||
assert_eq!(columns[0].groups[0].active_panel(), Some(&3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_bar_survives_a_strip_full_of_tabs() {
|
||||
let layout = Layout { root: Some(tabs(&[1, 2, 3, 4, 5, 6, 7, 8], 0)), floating: Vec::new() };
|
||||
let content = TestContent { header: 24.0, ..Default::default() };
|
||||
let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 400.0)));
|
||||
let bar = d.rect("drag-bar", 1);
|
||||
assert!(bar.width() >= 40.0, "{bar:?}");
|
||||
assert_eq!(bar.right(), 300.0 - 24.0, "the bar ends at the header");
|
||||
assert_eq!(d.content.strip_width.get(), 300.0, "the header is sized for the whole strip");
|
||||
assert!(d.ctx.read_response(Id::new(AREA).with(("overflow", &1u32))).is_some(), "tabs overflow before the bar narrows");
|
||||
let out = d.drag(bar.center(), pos2(500.0, 300.0));
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions);
|
||||
assert_eq!(d.layout.floating[0].groups()[0].panels.len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_border_drags_the_group_and_the_menu_button_only_clicks() {
|
||||
let content = TestContent { header: 30.0, ..Default::default() };
|
||||
let mut d = Driver::with(frames(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let border = d.rect("drag-border", 2);
|
||||
assert!(border.height() <= 4.0);
|
||||
// The band lies over the tabs and wins there.
|
||||
let over_tab = pos2(d.tab(2).center().x, border.center().y);
|
||||
let menu = pos2(576.0, d.tab(2).center().y);
|
||||
|
||||
// Pressing ≡ and dragging moves nothing; clicking it reaches the host.
|
||||
let held = d.hold(menu, menu + vec2(0.0, 200.0));
|
||||
assert!(held.group_drag.is_none());
|
||||
let out = d.step(vec![button(menu + vec2(0.0, 200.0), false)]);
|
||||
assert!(out.actions.iter().all(|a| !matches!(a, Action::MoveGroup { .. } | Action::Move { .. } | Action::Float { .. })), "{:?}", out.actions);
|
||||
// A press in the header focuses the group's shown panel, like a press on its tab.
|
||||
let pressed = d.step(vec![Event::PointerMoved(menu), button(menu, true)]);
|
||||
assert_eq!(pressed.focused, Some(3));
|
||||
d.step(vec![button(menu, false)]);
|
||||
assert_eq!(d.content.header_clicks, 1);
|
||||
|
||||
let out = d.drag(over_tab, d.tab(1).center());
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, .. })), "{:?}", out.actions);
|
||||
assert_eq!(d.layout.root, Some(tabs(&[1, 2, 3], 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_drop_on_a_frame_edge_splits_and_on_a_protected_canvas_floats() {
|
||||
let canvas = || TestContent { protected: vec![1], ..Default::default() };
|
||||
let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0));
|
||||
let mut d = Driver::with(frames(), TestContent::default(), area);
|
||||
let out = d.drag(d.rect("drag-bar", 2).center(), pos2(20.0, 300.0));
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, placement: Placement::Split(Zone::Left) })), "{:?}", out.actions);
|
||||
let Some(Node::Split { first, second, .. }) = &d.layout.root else { panic!() };
|
||||
assert_eq!(**first, tabs(&[2, 3], 1));
|
||||
assert_eq!(**second, tabs(&[1], 0));
|
||||
|
||||
// A protected canvas takes nothing, at its center or its edge: no join, no split, no
|
||||
// preview; the group floats there.
|
||||
for at in [pos2(150.0, 300.0), pos2(20.0, 300.0)] {
|
||||
let mut d = Driver::with(frames(), canvas(), area);
|
||||
let out = d.drag(d.rect("drag-bar", 2).center(), at);
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions);
|
||||
assert_eq!(d.layout.root, Some(tabs(&[1], 0)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_or_cmd_held_at_release_always_floats() {
|
||||
for modifiers in [Modifiers::CTRL, Modifiers::MAC_CMD, Modifiers::COMMAND] {
|
||||
let mut d = Driver::new(frames());
|
||||
let target = d.tab(1).center();
|
||||
d.hold(d.rect("drag-bar", 2).center(), target);
|
||||
d.modifiers = modifiers;
|
||||
let out = d.step(vec![button(target, false)]);
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{modifiers:?}: {:?}", out.actions);
|
||||
assert_eq!(d.layout.root, Some(tabs(&[1], 0)));
|
||||
|
||||
// A tab drag floats the same way.
|
||||
let mut d = Driver::new(frames());
|
||||
let target = d.tab(1).center();
|
||||
d.hold(d.tab(3).center(), target);
|
||||
d.modifiers = modifiers;
|
||||
let out = d.step(vec![button(target, false)]);
|
||||
assert!(out.actions.iter().any(|a| matches!(a, Action::Float { panel: 3, .. })), "{modifiers:?}: {:?}", out.actions);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_drag_escape_focus_loss_pointer_exit_and_cancel_drag_leave_the_layout_unchanged() {
|
||||
for case in ["escape", "focus", "exit", "cancel"] {
|
||||
let mut d = Driver::new(frames());
|
||||
let target = d.tab(1).center();
|
||||
let held = d.hold(d.rect("drag-bar", 2).center(), target);
|
||||
assert_eq!(held.group_drag, Some(2));
|
||||
let out = match case {
|
||||
"escape" => d.step(vec![key(egui::Key::Escape)]),
|
||||
"focus" => {
|
||||
d.focused = false;
|
||||
let out = d.step(vec![]);
|
||||
d.focused = true;
|
||||
out
|
||||
}
|
||||
"exit" => d.step(vec![Event::PointerGone]),
|
||||
_ => {
|
||||
cancel_drag::<u32>(&d.ctx, Id::new(AREA));
|
||||
d.step(vec![Event::PointerMoved(target + vec2(1.0, 0.0))])
|
||||
}
|
||||
};
|
||||
assert!(out.actions.is_empty() && out.group_drop.is_none(), "{case}: {out:?}");
|
||||
let out = d.step(vec![Event::PointerMoved(target), button(target, false)]);
|
||||
assert!(out.actions.is_empty() && out.group_drop.is_none() && out.group_drag.is_none(), "{case}: {out:?}");
|
||||
assert_eq!(d.layout, frames(), "{case}");
|
||||
assert!(!is_dragging::<u32>(&d.ctx, Id::new(AREA)), "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floated_panel_fits_its_content_up_to_floating_size_not_the_column_height() {
|
||||
for size in [Some(vec2(200.0, 150.0)), None] {
|
||||
let mut layout = docked();
|
||||
let Some(Node::Split { first, .. }) = &mut layout.root else { panic!() };
|
||||
**first = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![2, 3], 1)], 240.0)] };
|
||||
let content = TestContent { protected: vec![0], floating_size: size, body_height: Some(200.0), ..Default::default() };
|
||||
let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let out = d.drag(d.tab(3).center(), pos2(700.0, 100.0));
|
||||
let Some([_, _, width, height]) = out.actions.iter().find_map(|a| match a {
|
||||
Action::Float { panel: 3, rect } => Some(*rect),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("{:?}", out.actions)
|
||||
};
|
||||
let fitted = crate::docking::chrome::TITLE_HEIGHT + d.rect("drag-bar", 2).height() + 200.0;
|
||||
match size {
|
||||
Some(size) => assert_eq!((width, height), (size.x, size.y)),
|
||||
None => assert_eq!(height, fitted),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_window_is_opaque_with_a_transparent_host_background() {
|
||||
let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let mut d = Driver::new(layout);
|
||||
d.transparent = true;
|
||||
d.step(vec![]);
|
||||
let window = Rect::from_min_size(pos2(80.0, 70.0), vec2(300.0, 220.0));
|
||||
let fill = d.ctx.global_style().visuals.window_fill;
|
||||
assert_ne!(fill, Color32::TRANSPARENT);
|
||||
fn filled(shape: &egui::Shape, rect: Rect, fill: Color32) -> bool {
|
||||
match shape {
|
||||
egui::Shape::Rect(shape) => shape.rect == rect && shape.fill == fill,
|
||||
egui::Shape::Vec(shapes) => shapes.iter().any(|shape| filled(shape, rect, fill)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
assert!(d.shapes.iter().any(|clipped| filled(&clipped.shape, window, fill)), "no opaque fill under the floating window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_on_a_floating_tab_or_bar_minimizes_and_another_tab_expands() {
|
||||
let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let mut d = Driver::new(layout);
|
||||
let minimized = |d: &Driver| d.layout.floating[0].minimized;
|
||||
let tab = d.tab(6).center();
|
||||
d.click(tab);
|
||||
let out = d.click(tab);
|
||||
assert!(out.actions.contains(&Action::SetMinimized { panel: 6, minimized: true }), "{:?}", out.actions);
|
||||
assert!(minimized(&d));
|
||||
d.wait();
|
||||
|
||||
// Another tab of the minimized group expands it and selects that tab.
|
||||
let other = d.tab(5).center();
|
||||
d.click(other);
|
||||
assert!(!minimized(&d));
|
||||
assert_eq!(d.layout.floating[0].groups()[0].active_panel(), Some(&5));
|
||||
|
||||
d.wait();
|
||||
let bar = d.rect("drag-bar", 5).center();
|
||||
d.click(bar);
|
||||
d.click(bar);
|
||||
assert!(minimized(&d));
|
||||
d.wait();
|
||||
d.click(bar);
|
||||
d.click(bar);
|
||||
assert!(!minimized(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_over_own_position_is_a_noop() {
|
||||
let mut d = Driver::new(frames());
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
let out = d.drag(bar.center(), bar.center() + vec2(0.0, 200.0));
|
||||
assert!(out.actions.is_empty() && out.group_drop.is_none(), "{out:?}");
|
||||
assert_eq!(d.layout, frames());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_border_and_drag_bar_move_and_cancel_as_a_group() {
|
||||
for name in ["drag-border", "drag-bar"] {
|
||||
let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let mut d = Driver::new(layout.clone());
|
||||
let from = d.rect(name, 5).center();
|
||||
d.hold(from, from + vec2(50.0, 40.0));
|
||||
assert_eq!(d.layout, layout, "{name}: a ghost moves, not the window");
|
||||
d.step(vec![key(egui::Key::Escape)]);
|
||||
d.step(vec![button(from + vec2(50.0, 40.0), false)]);
|
||||
assert_eq!(d.layout, layout, "{name}");
|
||||
|
||||
let out = d.drag(from, from + vec2(50.0, 40.0));
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{name}: {:?}", out.actions);
|
||||
let [x, y, w, h] = d.layout.floating[0].rect;
|
||||
assert_eq!([x, y, w, h], [130.0, 110.0, 300.0, 220.0], "{name}");
|
||||
assert_eq!(d.layout.floating[0].groups()[0], Group::new(vec![5, 6], 1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_border_movement_does_not_accumulate_fractional_step_rounding() {
|
||||
let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let mut d = Driver::new(layout);
|
||||
let from = d.rect("drag-border", 5).center();
|
||||
d.step(vec![Event::PointerMoved(from), button(from, true)]);
|
||||
for index in 1..=8 {
|
||||
d.step(vec![Event::PointerMoved(from + vec2(80.3, 60.7) * (index as f32 / 8.0))]);
|
||||
}
|
||||
d.step(vec![button(from + vec2(80.3, 60.7), false)]);
|
||||
let [x, y, ..] = d.layout.floating[0].rect;
|
||||
assert!((x - 160.3).abs() <= 1.0 && (y - 130.7).abs() <= 1.0, "{x} {y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docked_header_drag_reaches_the_host_hook_and_preserves_the_group() {
|
||||
for name in ["drag-border", "drag-bar"] {
|
||||
let content = TestContent { host_owned: true, ..Default::default() };
|
||||
let mut d = Driver::with(frames(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let out = d.drag(d.rect(name, 2).center(), pos2(70.0, 300.0));
|
||||
assert!(d.content.whole_group, "{name}");
|
||||
assert!(out.actions.is_empty() && out.group_drop.is_none(), "{name}: the host owns the release");
|
||||
assert_eq!(d.layout, frames());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_protected_panel_draws_no_strip_and_no_bar() {
|
||||
struct Bare;
|
||||
impl DockContent<u32> for Bare {
|
||||
fn body(&mut self, _: &mut egui::Ui, _: &u32) {}
|
||||
fn permissions(&self, panel: &u32) -> Permissions {
|
||||
if *panel == 1 { Permissions::PROTECTED } else { Permissions::default() }
|
||||
}
|
||||
}
|
||||
let ctx = Context::default();
|
||||
for _ in 0..2 {
|
||||
ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, |ui| {
|
||||
DockArea::new(Id::new(AREA)).show_content(ui, &frames(), &DockStyle::from_ui(ui), &mut Bare);
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
}
|
||||
assert!(ctx.read_response(Id::new(AREA).with(("drag-bar", Some(&1u32)))).is_none());
|
||||
assert!(ctx.read_response(Id::new(AREA).with(("tab", &1u32))).is_none());
|
||||
assert!(ctx.read_response(Id::new(AREA).with(("drag-bar", Some(&2u32)))).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, (content, actions): &mut (TestContent, Vec<Action<u32>>)| {
|
||||
let out = DockArea::new(Id::new(AREA)).show_content(ui, &docked(), &DockStyle::from_ui(ui), content);
|
||||
actions.extend(out.actions);
|
||||
},
|
||||
(TestContent { protected: vec![0], ..Default::default() }, Vec::new()),
|
||||
);
|
||||
h.run_steps(2);
|
||||
let bar_id = Id::new(AREA).with(("drag-bar", Some(&2u32)));
|
||||
let at = h.ctx.read_response(bar_id).unwrap().rect.center();
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(at),
|
||||
Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
for label in ["Close Tab Group", "Minimize", "Float Tab Group", "Move Group To"] {
|
||||
assert_eq!(h.query_all_by_label(label).count(), 1, "{label}");
|
||||
}
|
||||
h.get_by_label("Close Tab Group").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().1.contains(&Action::CloseGroup { panel: 3 }), "{:?}", h.state().1);
|
||||
|
||||
h.ctx.memory_mut(|memory| memory.request_focus(bar_id));
|
||||
h.run_steps(1);
|
||||
assert!(DockArea::<u32>::new(Id::new(AREA)).chrome_has_focus(&h.ctx, &docked()));
|
||||
h.input_mut().events.push(key(egui::Key::Enter));
|
||||
h.run_steps(2);
|
||||
assert!(egui::Popup::is_any_open(&h.ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() {
|
||||
let stack = Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [80.0, 70.0, 300.0, 400.0]).unwrap();
|
||||
let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![stack] };
|
||||
let mut d = Driver::new(layout);
|
||||
let from = d.rect("drag-bar", 6).center();
|
||||
let out = d.drag(from, pos2(700.0, 300.0));
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 189.0]) })), "{:?}", out.actions);
|
||||
assert_eq!(d.layout.floating.len(), 2);
|
||||
assert_eq!(d.layout.floating[0].groups(), vec![Group::new(vec![5], 0)]);
|
||||
assert_eq!(d.layout.floating[1].groups(), vec![Group::new(vec![6, 7], 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_docked_panel_floats_at_its_content_height_up_to_its_floating_size() {
|
||||
let title = crate::docking::chrome::TITLE_HEIGHT;
|
||||
let float = |body: f32, floating_size: Option<Vec2>| {
|
||||
let content = TestContent { body_height: Some(body), floating_size, ..Default::default() };
|
||||
let mut d = Driver::with(docked(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let strip = d.rect("drag-bar", 4).height();
|
||||
let recorded = crate::docking::float_space::<u32>(&d.ctx, Id::new(AREA)).unwrap().panel(&4).unwrap();
|
||||
let target = pos2(400.0, 300.0);
|
||||
d.hold(d.tab(4).center(), target);
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
let out = d.step(vec![button(target, false)]);
|
||||
let Some([_, _, width, height]) = out.actions.iter().find_map(|a| match a {
|
||||
Action::Float { panel: 4, rect } => Some(*rect),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("{:?}", out.actions)
|
||||
};
|
||||
assert_eq!(recorded, vec2(width, height), "a command floats at the size a drag does");
|
||||
(strip, vec2(width, height))
|
||||
};
|
||||
let (strip, size) = float(150.0, None);
|
||||
assert_eq!(size.y, title + strip + 150.0);
|
||||
assert_eq!(float(0.0, None).1.y, 120.0, "an empty panel floats at the least fitted height");
|
||||
assert_eq!(float(600.0, None).1.y, 320.0, "a tall docked panel keeps the docked cap");
|
||||
// The host's floating size gives the width and the most height.
|
||||
assert_eq!(float(150.0, Some(vec2(300.0, 360.0))).1, vec2(300.0, title + strip + 150.0));
|
||||
assert_eq!(float(150.0, Some(vec2(300.0, 160.0))).1, vec2(300.0, 160.0));
|
||||
|
||||
// A group takes its active panel's content height.
|
||||
let content = TestContent { body_height: Some(150.0), ..Default::default() };
|
||||
let mut d = Driver::with(docked(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let target = pos2(400.0, 300.0);
|
||||
d.hold(d.rect("drag-bar", 2).center(), target);
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
let out = d.step(vec![button(target, false)]);
|
||||
let Some(Target::Float { rect: Some([_, _, _, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) };
|
||||
assert_eq!(*height, title + strip + 150.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panel_that_fills_its_frame_floats_at_its_floating_size_or_320() {
|
||||
let float = |floating_size: Option<Vec2>| {
|
||||
let content = TestContent { fill: true, floating_size, ..Default::default() };
|
||||
let mut d = Driver::with(frames(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let target = pos2(400.0, 300.0);
|
||||
d.hold(d.tab(3).center(), target);
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
let out = d.step(vec![button(target, false)]);
|
||||
out.actions
|
||||
.iter()
|
||||
.find_map(|a| match a {
|
||||
Action::Float { panel: 3, rect } => Some(rect[3]),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("{:?}", out.actions))
|
||||
};
|
||||
assert_eq!(float(None), 320.0);
|
||||
assert_eq!(float(Some(vec2(300.0, 400.0))), 400.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_focus_follows_only_the_users_input() {
|
||||
let mut d = Driver::new(docked());
|
||||
let tab = Id::new(AREA).with(("tab", &4u32));
|
||||
// Keyboard focus as Tab gives it.
|
||||
d.ctx.memory_mut(|m| m.request_focus(tab));
|
||||
d.step(vec![]);
|
||||
assert!(d.ctx.memory(|m| m.has_focus(tab)));
|
||||
|
||||
// A reset that moves the panel takes its focus away and reports no new focus.
|
||||
let mut reset = docked();
|
||||
let Some(Node::Split { first, .. }) = &mut reset.root else { panic!() };
|
||||
let Node::Dock { columns, .. } = first.as_mut() else { panic!() };
|
||||
columns[0].groups.reverse();
|
||||
d.layout = reset;
|
||||
let out = d.step(vec![]);
|
||||
assert_eq!(out.focused, None);
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.ctx.memory(|m| m.focused()), None, "the moved tab gives up keyboard focus");
|
||||
|
||||
// A user drag keeps the dragged tab's focus where the user put it.
|
||||
let mut d = Driver::new(docked());
|
||||
d.ctx.memory_mut(|m| m.request_focus(tab));
|
||||
d.drag(d.tab(4).center(), d.tab(2).center());
|
||||
d.step(vec![]);
|
||||
assert!(d.layout.place(&4) != docked().place(&4));
|
||||
assert!(d.ctx.memory(|m| m.has_focus(tab)), "a tab moved by the user keeps focus");
|
||||
|
||||
// A closed panel's tab gives focus up too.
|
||||
let out = d.step(vec![]);
|
||||
assert!(out.actions.is_empty());
|
||||
d.layout.apply(Action::Close { panel: 4 }).unwrap();
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.ctx.memory(|m| m.focused()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_tabs_follow_the_wheel_and_close_on_a_middle_click() {
|
||||
let second = |d: &Driver| match &d.layout.root {
|
||||
Some(Node::Split { second, .. }) => (**second).clone(),
|
||||
_ => panic!("{:?}", d.layout.root),
|
||||
};
|
||||
let wheel = |unit, y| Event::MouseWheel { unit, delta: vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE };
|
||||
let middle = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Middle, pressed, modifiers: Modifiers::NONE };
|
||||
|
||||
// Off by default.
|
||||
let mut d = Driver::new(frames());
|
||||
let over = d.tab(2).center();
|
||||
d.step(vec![Event::PointerMoved(over), wheel(egui::MouseWheelUnit::Line, 1.0)]);
|
||||
d.step(vec![middle(over, true)]);
|
||||
d.step(vec![middle(over, false)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 1));
|
||||
|
||||
let mut d = Driver::new(frames());
|
||||
d.tweak = super::floating_tests::frame_style;
|
||||
d.step(vec![]);
|
||||
let over = d.tab(2).center();
|
||||
d.step(vec![Event::PointerMoved(over), wheel(egui::MouseWheelUnit::Line, 1.0)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 0), "wheel up selects the previous tab");
|
||||
d.step(vec![wheel(egui::MouseWheelUnit::Line, 1.0)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 0), "and stops at the first");
|
||||
d.step(vec![wheel(egui::MouseWheelUnit::Point, -30.0)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 0), "trackpad scrolling adds up to a notch");
|
||||
let out = d.step(vec![wheel(egui::MouseWheelUnit::Point, -30.0)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 1));
|
||||
assert_eq!(out.focused, Some(3));
|
||||
d.step(vec![wheel(egui::MouseWheelUnit::Line, -1e30)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 1), "a huge delta stops at the last tab");
|
||||
d.step(vec![wheel(egui::MouseWheelUnit::Line, 1e30)]);
|
||||
assert_eq!(second(&d), tabs(&[2, 3], 0), "and at the first");
|
||||
|
||||
d.step(vec![middle(over, true)]);
|
||||
let out = d.step(vec![middle(over, false)]);
|
||||
assert_eq!(out.actions, vec![Action::Close { panel: 2 }]);
|
||||
assert_eq!(second(&d), tabs(&[3], 0));
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Where each docking gesture starts, for control protocols and tests.
|
||||
|
||||
use std::{collections::HashMap, fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Id, LayerId, Order, Rect};
|
||||
|
||||
use super::{DockArea, Floating, Layout, Node, render::RESIZE_HANDLES};
|
||||
|
||||
/// A rendered docking control that starts a gesture. Groups, columns and windows are named by
|
||||
/// their first panel.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum Hit<P> {
|
||||
/// A tab: click activates, drag moves the panel (S1).
|
||||
Tab(P),
|
||||
/// A group's drag bar: drag moves the group; a right click, Enter or Space opens the group
|
||||
/// menu (S2).
|
||||
DragBar(P),
|
||||
/// The top border of a group's strip: drag moves the group (S3).
|
||||
Border(P),
|
||||
/// The "…" button of a group whose tabs overflow; named by the active panel.
|
||||
Overflow(P),
|
||||
/// [D] A column bar: drag moves the column (S6).
|
||||
ColumnBar(P),
|
||||
/// [D] The »/« button of a column bar (M2).
|
||||
Collapse(P),
|
||||
/// An accordion entry's −/+ button.
|
||||
StackToggle(P),
|
||||
/// A floating window's title bar (S5).
|
||||
Title(P),
|
||||
/// A floating window's × button.
|
||||
Close(P),
|
||||
/// [D] A panel's icon in an iconic column (S7, M5).
|
||||
Icon(P),
|
||||
/// [D] The grip above an icon group (S8).
|
||||
IconGrip(P),
|
||||
/// A floating window's resize handle.
|
||||
Resize(P, ResizeEdge),
|
||||
Divider(Divider<P>),
|
||||
}
|
||||
|
||||
/// The edge or corner a floating window's resize handle moves.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum ResizeEdge {
|
||||
Left,
|
||||
Right,
|
||||
Bottom,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
Top,
|
||||
TopLeft,
|
||||
TopRight,
|
||||
}
|
||||
|
||||
/// A divider that resizes what is on either side of it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum Divider<P> {
|
||||
/// A split, by its path from the root (see [`super::Action::ResizeSplit`]).
|
||||
Split(Vec<bool>),
|
||||
/// Below the accordion entry of this panel.
|
||||
Stack(P),
|
||||
/// [D] The inner edge of the column holding this panel first.
|
||||
Column(P),
|
||||
/// Below the dock group holding this panel first.
|
||||
Group(P),
|
||||
/// Where the divider of a split inside another split ends on the outer split's divider,
|
||||
/// by the outer and the inner split's paths. Dragging it moves both dividers.
|
||||
Intersection(Vec<bool>, Vec<bool>),
|
||||
/// A divider in the floating window holding the panel, by its path from the window's root.
|
||||
WindowSplit(P, Vec<bool>),
|
||||
WindowIntersection(P, Vec<bool>, Vec<bool>),
|
||||
}
|
||||
|
||||
fn key(area: Id) -> Id {
|
||||
area.with("hit-rects")
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'_, P> {
|
||||
/// Every gesture source the area drew in its last frame, with its rect in points. Hosts
|
||||
/// return these from a `ui.docking` control method beside the layout and `focused`; tests
|
||||
/// drag from their centers.
|
||||
pub fn hit_rects(ctx: &Context, id: Id) -> Vec<(Hit<P>, Rect)> {
|
||||
let Some((layout, rects)) = ctx.data(|d| d.get_temp::<Recorded<P>>(key(id))) else { return Vec::new() };
|
||||
let mut names = named(id, &layout);
|
||||
rects.into_iter().filter_map(|(id, rect)| Some((names.remove(&id)?, rect))).collect()
|
||||
}
|
||||
|
||||
/// The egui widget id of the control `hit` names in the area `id`, for tests and
|
||||
/// automation that focus a control or read its response.
|
||||
pub fn hit_id(id: Id, hit: &Hit<P>) -> Id {
|
||||
match hit {
|
||||
Hit::Tab(p) => id.with(("tab", p)),
|
||||
Hit::Icon(p) => id.with(("icon", p)),
|
||||
Hit::Overflow(p) => id.with(("overflow", p)),
|
||||
Hit::StackToggle(p) => id.with(("collapse", p)),
|
||||
Hit::Divider(Divider::Stack(p)) => id.with(("stack-resize", p)),
|
||||
Hit::DragBar(p) => id.with(("drag-bar", Some(p))),
|
||||
Hit::Border(p) => id.with(("drag-border", Some(p))),
|
||||
Hit::IconGrip(p) => id.with(("icon-grip", Some(p))),
|
||||
Hit::ColumnBar(p) => id.with(("column-bar", Some(p))),
|
||||
Hit::Collapse(p) => id.with(("column-collapse", Some(p))),
|
||||
Hit::Divider(Divider::Column(p)) => id.with(("column-resize", Some(p))),
|
||||
Hit::Divider(Divider::Group(p)) => id.with(("group-resize", Some(p))),
|
||||
Hit::Divider(Divider::Split(path)) => id.with(("split", path)),
|
||||
Hit::Divider(Divider::Intersection(outer, inner)) => id.with(("intersection", outer, inner)),
|
||||
Hit::Divider(Divider::WindowSplit(p, path)) => id.with(("window-split", p, path)),
|
||||
Hit::Divider(Divider::WindowIntersection(p, outer, inner)) => id.with(("window-intersection", p, outer, inner)),
|
||||
Hit::Title(p) => id.with(("move-group", Some(p))),
|
||||
Hit::Close(p) => id.with(("move-group", Some(p))).with("close"),
|
||||
Hit::Resize(p, edge) => {
|
||||
let name = match edge {
|
||||
ResizeEdge::BottomRight => RESIZE_HANDLES[0],
|
||||
ResizeEdge::Left => RESIZE_HANDLES[1],
|
||||
ResizeEdge::Right => RESIZE_HANDLES[2],
|
||||
ResizeEdge::Bottom => RESIZE_HANDLES[3],
|
||||
ResizeEdge::BottomLeft => RESIZE_HANDLES[4],
|
||||
ResizeEdge::Top => RESIZE_HANDLES[5],
|
||||
ResizeEdge::TopLeft => RESIZE_HANDLES[6],
|
||||
ResizeEdge::TopRight => RESIZE_HANDLES[7],
|
||||
};
|
||||
id.with(("floating", p)).with(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The egui layer of a floating window in the area `id`; `None` for an empty window. Of two
|
||||
/// layers, the later in `ctx.memory(|m| m.layer_ids())` is drawn on top, and
|
||||
/// `ctx.memory(|m| m.area_rect(layer.id))` is the window's rect. A window the area does not
|
||||
/// draw (all its panels hidden, or a frame maximized) keeps its last rect there: check
|
||||
/// `ctx.memory(|m| m.areas().is_visible(&layer))` before treating it as covering anything.
|
||||
pub fn floating_layer(id: Id, window: &Floating<P>) -> Option<LayerId> {
|
||||
window.panels().next().map(|first| LayerId::new(Order::Middle, id.with(("floating", first))))
|
||||
}
|
||||
}
|
||||
|
||||
/// Every control the area `area` can draw for `layout`, by widget id.
|
||||
pub(super) fn named<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(area: Id, layout: &Layout<P>) -> HashMap<Id, Hit<P>> {
|
||||
let mut names: HashMap<Id, Hit<P>> = HashMap::new();
|
||||
let mut name = |hit: Hit<P>| {
|
||||
names.insert(DockArea::<P>::hit_id(area, &hit), hit);
|
||||
};
|
||||
for panel in layout.panels() {
|
||||
let p = || panel.clone();
|
||||
for hit in [
|
||||
Hit::Tab(p()),
|
||||
Hit::Icon(p()),
|
||||
Hit::Overflow(p()),
|
||||
Hit::StackToggle(p()),
|
||||
Hit::Divider(Divider::Stack(p())),
|
||||
Hit::DragBar(p()),
|
||||
Hit::Border(p()),
|
||||
Hit::IconGrip(p()),
|
||||
Hit::ColumnBar(p()),
|
||||
Hit::Collapse(p()),
|
||||
Hit::Divider(Divider::Column(p())),
|
||||
Hit::Divider(Divider::Group(p())),
|
||||
Hit::Title(p()),
|
||||
Hit::Close(p()),
|
||||
] {
|
||||
name(hit);
|
||||
}
|
||||
for edge in [
|
||||
ResizeEdge::BottomRight,
|
||||
ResizeEdge::Left,
|
||||
ResizeEdge::Right,
|
||||
ResizeEdge::Bottom,
|
||||
ResizeEdge::BottomLeft,
|
||||
ResizeEdge::Top,
|
||||
ResizeEdge::TopLeft,
|
||||
ResizeEdge::TopRight,
|
||||
] {
|
||||
name(Hit::Resize(p(), edge));
|
||||
}
|
||||
}
|
||||
if let Some(root) = &layout.root {
|
||||
name_splits(root, &mut |path, outer| match outer {
|
||||
None => name(Hit::Divider(Divider::Split(path))),
|
||||
Some(outer) => name(Hit::Divider(Divider::Intersection(outer, path))),
|
||||
});
|
||||
}
|
||||
for window in &layout.floating {
|
||||
let Some(key) = window.panels().next() else { continue };
|
||||
name_splits(&window.root, &mut |path, outer| match outer {
|
||||
None => name(Hit::Divider(Divider::WindowSplit(key.clone(), path))),
|
||||
Some(outer) => name(Hit::Divider(Divider::WindowIntersection(key.clone(), outer, path))),
|
||||
});
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Every split of a tree by its path (`None`), and every pair of a split and a split inside it
|
||||
/// (`Some(outer)`), whose dividers may meet.
|
||||
fn name_splits<P>(root: &Node<P>, name: &mut dyn FnMut(Vec<bool>, Option<Vec<bool>>)) {
|
||||
let mut nodes = vec![(root, Vec::<bool>::new())];
|
||||
let mut splits: Vec<Vec<bool>> = Vec::new();
|
||||
while let Some((node, path)) = nodes.pop() {
|
||||
if splits.len() > super::model::MAX_NODES {
|
||||
break;
|
||||
}
|
||||
if let Node::Split { first, second, .. } = node {
|
||||
name(path.clone(), None);
|
||||
for outer in splits.iter().filter(|outer| path.starts_with(outer)) {
|
||||
name(path.clone(), Some(outer.clone()));
|
||||
}
|
||||
splits.push(path.clone());
|
||||
let mut second_path = path.clone();
|
||||
second_path.push(true);
|
||||
let mut first_path = path;
|
||||
first_path.push(false);
|
||||
nodes.push((second, second_path));
|
||||
nodes.push((first, first_path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The layout of the last frame and the rects of the controls it registered, by widget id.
|
||||
type Recorded<P> = (Layout<P>, Vec<(Id, Rect)>);
|
||||
|
||||
/// Store the rects of the controls the renderer registered this frame. They are named only
|
||||
/// when [`DockArea::hit_rects`] asks, which tests and automation do, not every frame.
|
||||
pub(super) fn record<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(ctx: &Context, area: Id, layout: &Layout<P>, owned: &[Id]) {
|
||||
let rects: Vec<(Id, Rect)> =
|
||||
owned.iter().filter_map(|id| Some((*id, ctx.read_response(*id)?.rect))).filter(|(_, rect)| rect.is_positive()).collect();
|
||||
ctx.data_mut(|d| d.insert_temp::<Recorded<P>>(key(area), (layout.clone(), rects)));
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
//! [D] Iconic columns, flyouts and hit rects, driven through `testing::DockDriver`.
|
||||
|
||||
use super::testing::DockDriver;
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Key, Pos2, Rect, pos2, vec2};
|
||||
|
||||
struct Content;
|
||||
|
||||
impl DockContent<u32> for Content {
|
||||
fn body(&mut self, ui: &mut egui::Ui, _: &u32) {
|
||||
ui.label("Body");
|
||||
}
|
||||
fn logical_label(&self, panel: &u32) -> String {
|
||||
format!("Panel {panel}")
|
||||
}
|
||||
fn permissions(&self, panel: &u32) -> Permissions {
|
||||
if *panel == 0 { Permissions::PROTECTED } else { Permissions::default() }
|
||||
}
|
||||
}
|
||||
|
||||
type Driver = DockDriver<u32, Content>;
|
||||
|
||||
/// A name and a test for one kind of [`Hit`].
|
||||
type Check<'a> = (&'a str, &'a dyn Fn(&Hit<u32>) -> bool);
|
||||
|
||||
/// A left dock with one column of `groups`, iconic when `iconic`, beside canvas 0.
|
||||
fn docked(groups: &[&[u32]], iconic: bool) -> Layout<u32> {
|
||||
let mut column = Column::new(groups.iter().map(|g| Group::new(g.to_vec(), 0)).collect(), 240.0);
|
||||
column.iconic = iconic;
|
||||
let dock = Node::Dock { side: Side::Start, columns: vec![column] };
|
||||
let canvas = Node::Tabs { panels: vec![0], active: 0 };
|
||||
Layout {
|
||||
root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), first: Box::new(dock), second: Box::new(canvas) }),
|
||||
floating: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn first_column(layout: &Layout<u32>) -> Column<u32> {
|
||||
match &layout.root {
|
||||
Some(Node::Split { first, .. }) => match first.as_ref() {
|
||||
Node::Dock { columns, .. } => columns.first().cloned().unwrap(),
|
||||
other => panic!("no dock: {other:?}"),
|
||||
},
|
||||
other => panic!("no split: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn groups(layout: &Layout<u32>) -> Vec<Vec<u32>> {
|
||||
first_column(layout).groups.iter().map(|g| g.panels.clone()).collect()
|
||||
}
|
||||
|
||||
fn hit(d: &Driver, hit: Hit<u32>) -> Rect {
|
||||
d.hit(&hit).unwrap_or_else(|| panic!("{hit:?} in {:?}", d.hits()))
|
||||
}
|
||||
|
||||
fn open(d: &Driver) -> Option<u32> {
|
||||
flyout::<u32>(&d.ctx, d.id)
|
||||
}
|
||||
|
||||
fn texts(d: &Driver) -> Vec<String> {
|
||||
d.shapes()
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) => Some(text.galley.text().to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
const CANVAS: Pos2 = pos2(600.0, 400.0);
|
||||
|
||||
#[test]
|
||||
fn collapsed_column_shows_one_icon_per_panel_with_group_separators() {
|
||||
let d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content);
|
||||
let (one, two, three) = (hit(&d, Hit::Icon(1)), hit(&d, Hit::Icon(2)), hit(&d, Hit::Icon(3)));
|
||||
let (grip1, grip3) = (hit(&d, Hit::IconGrip(1)), hit(&d, Hit::IconGrip(3)));
|
||||
assert_eq!(one.width(), 36.0, "the column takes the style's iconic width");
|
||||
assert_eq!(one.bottom(), two.top(), "a group's icons follow each other");
|
||||
assert_eq!(three.top() - two.bottom(), 7.0, "groups are apart by the separator, with no room for a grip");
|
||||
assert_eq!((grip1.top(), grip1.bottom()), (one.top(), one.top() + 4.0), "the first group's band is its top edge");
|
||||
assert_eq!((grip3.top(), grip3.bottom()), (two.bottom(), three.top() + 4.0), "a later group's band covers the separator");
|
||||
assert!(d.hit(&Hit::Tab(1)).is_none(), "an iconic column draws no tabs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_an_iconic_column_shows_labels() {
|
||||
let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content);
|
||||
assert!(!texts(&d).iter().any(|t| t == "Panel 1"));
|
||||
let edge = hit(&d, Hit::Divider(Divider::Column(1)));
|
||||
let out = d.drag(edge.center(), pos2(150.0, edge.center().y));
|
||||
assert!(out.error.is_none());
|
||||
let width = first_column(&d.layout).iconic_width.unwrap();
|
||||
assert!((100.0..=160.0).contains(&width), "{width}");
|
||||
d.settle();
|
||||
let labels = texts(&d);
|
||||
assert!(["Panel 1", "Panel 2", "Panel 3"].iter().all(|l| labels.iter().any(|t| t == l)), "{labels:?}");
|
||||
let edge = hit(&d, Hit::Divider(Divider::Column(1)));
|
||||
d.drag(edge.center(), pos2(20.0, edge.center().y));
|
||||
d.settle();
|
||||
assert_eq!(first_column(&d.layout).iconic_width, Some(36.0));
|
||||
assert!(!texts(&d).iter().any(|t| t == "Panel 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icon_click_opens_a_flyout_on_the_canvas_side_and_auto_collapse_closes_it() {
|
||||
let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content);
|
||||
let icon = hit(&d, Hit::Icon(2)).center();
|
||||
let out = d.click(icon);
|
||||
assert!(out.actions.contains(&Action::Activate { panel: 2 }));
|
||||
d.settle();
|
||||
assert_eq!(open(&d), Some(2));
|
||||
let column = hit(&d, Hit::Icon(1));
|
||||
let tab = hit(&d, Hit::Tab(2));
|
||||
assert!(tab.left() >= column.right(), "the flyout opens on the canvas side: {tab:?}");
|
||||
assert!(tab.top() <= hit(&d, Hit::IconGrip(1)).bottom(), "beside its group");
|
||||
assert_eq!(first_column(&d.layout).groups.first().map(|g| g.active), Some(1));
|
||||
|
||||
// Another icon switches flyouts, the same icon closes.
|
||||
d.click(hit(&d, Hit::Icon(3)).center());
|
||||
d.settle();
|
||||
assert_eq!(open(&d), Some(3));
|
||||
assert!(d.hit(&Hit::Tab(2)).is_none());
|
||||
d.click(hit(&d, Hit::Icon(3)).center());
|
||||
d.settle();
|
||||
assert_eq!(open(&d), None);
|
||||
|
||||
// Escape and a press outside close it.
|
||||
d.click(icon);
|
||||
d.settle();
|
||||
d.key(Key::Escape);
|
||||
d.settle();
|
||||
assert_eq!(open(&d), None);
|
||||
d.click(icon);
|
||||
d.settle();
|
||||
let inside = hit(&d, Hit::Tab(2)).center();
|
||||
d.click(inside);
|
||||
d.settle();
|
||||
assert_eq!(open(&d), Some(2), "a press inside keeps it");
|
||||
d.click(CANVAS);
|
||||
d.settle();
|
||||
assert_eq!(open(&d), None);
|
||||
|
||||
// Auto-Collapse off: it stays until an icon closes it.
|
||||
d.auto_collapse = false;
|
||||
d.click(icon);
|
||||
d.settle();
|
||||
d.key(Key::Escape);
|
||||
d.click(CANVAS);
|
||||
d.settle();
|
||||
assert_eq!(open(&d), Some(2));
|
||||
d.click(icon);
|
||||
d.settle();
|
||||
assert_eq!(open(&d), None);
|
||||
|
||||
// U3: raising an iconic panel, as the Window menu does, opens its flyout.
|
||||
d.raise = Some(3);
|
||||
d.settle();
|
||||
assert_eq!(open(&d), Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_collapse_toggle_is_a_column_menu_event() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let layout = docked(&[&[1, 2]], true);
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, events: &mut Vec<DockEvent<u32>>| {
|
||||
let out = DockArea::new(egui::Id::new("menu")).show_content(ui, &layout, &DockStyle::from_ui(ui), &mut Content);
|
||||
events.extend(out.events);
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
h.run_steps(2);
|
||||
let bar = h.ctx.read_response(egui::Id::new("menu").with(("column-bar", Some(&1u32)))).unwrap().rect.center();
|
||||
h.input_mut().events.extend([
|
||||
egui::Event::PointerMoved(bar),
|
||||
egui::Event::PointerButton { pos: bar, button: egui::PointerButton::Secondary, pressed: true, modifiers: egui::Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(egui::Event::PointerButton {
|
||||
pos: bar,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Auto-Collapse Iconic Panels").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state(), &vec![DockEvent::ToggleAutoCollapse]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_flyout_strip_floats_its_group() {
|
||||
let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content);
|
||||
d.click(hit(&d, Hit::Icon(1)).center());
|
||||
d.settle();
|
||||
// A one-line body: the flyout and the floated group take the least fitted height.
|
||||
let flyout = d.ctx.memory(|m| m.area_rect(d.id.with("flyout"))).unwrap();
|
||||
assert_eq!(flyout.height(), 120.0);
|
||||
let bar = hit(&d, Hit::DragBar(1));
|
||||
let out = d.drag(bar.center(), CANVAS);
|
||||
let [Action::MoveGroup { panel: 1, to: Target::Float { rect: Some(rect) } }] = out.actions.as_slice() else { panic!("{:?}", out.actions) };
|
||||
assert_eq!(rect[3], 120.0);
|
||||
assert_eq!(groups(&d.layout), vec![vec![3]]);
|
||||
assert_eq!(d.layout.floating.len(), 1);
|
||||
assert_eq!(d.layout.floating.first().map(|w| w.panels().copied().collect::<Vec<_>>()), Some(vec![1, 2]));
|
||||
d.settle();
|
||||
assert_eq!(open(&d), None, "the flyout closes with its group gone");
|
||||
|
||||
// A tab dragged out of a flyout floats that panel alone.
|
||||
d.click(hit(&d, Hit::Icon(3)).center());
|
||||
d.settle();
|
||||
let tab = hit(&d, Hit::Tab(3));
|
||||
let out = d.drag(tab.center(), pos2(450.0, 200.0));
|
||||
assert!(matches!(out.actions.as_slice(), [Action::Float { panel: 3, .. }]), "{:?}", out.actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icon_and_icon_group_grip_drags_move_a_panel_and_a_group() {
|
||||
let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content);
|
||||
let before = d.layout.clone();
|
||||
// Escape, focus loss and cancel_drag end an icon drag with no change.
|
||||
let icon = hit(&d, Hit::Icon(2)).center();
|
||||
d.hold(icon, CANVAS);
|
||||
d.key(Key::Escape);
|
||||
d.release(CANVAS);
|
||||
d.hold(icon, CANVAS);
|
||||
d.focus(false);
|
||||
d.focus(true);
|
||||
d.release(CANVAS);
|
||||
d.hold(icon, CANVAS);
|
||||
cancel_drag::<u32>(&d.ctx, d.id);
|
||||
d.release(CANVAS);
|
||||
assert_eq!(d.layout, before);
|
||||
|
||||
let out = d.drag(icon, CANVAS);
|
||||
let Some(Action::Float { panel: 2, rect }) = out.actions.first() else { panic!("{:?}", out.actions) };
|
||||
assert_eq!((rect[2], rect[3]), (240.0, 320.0), "a panel floated from its icon takes the column's expanded width");
|
||||
assert_eq!(groups(&d.layout), vec![vec![1], vec![3]]);
|
||||
|
||||
let grip = hit(&d, Hit::IconGrip(3)).center();
|
||||
let out = d.drag(grip, pos2(450.0, 250.0));
|
||||
assert!(matches!(out.actions.as_slice(), [Action::MoveGroup { panel: 3, to: Target::Float { .. } }]), "{:?}", out.actions);
|
||||
assert_eq!(groups(&d.layout), vec![vec![1]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_dropped_on_an_iconic_column_joins_as_an_icon_group() {
|
||||
let mut layout = docked(&[&[1], &[2]], true);
|
||||
layout.floating.push(Floating::single(vec![5, 6], 0, [300.0, 200.0, 240.0, 200.0]));
|
||||
let mut d = DockDriver::new(layout, Content);
|
||||
let bar = hit(&d, Hit::DragBar(5)).center();
|
||||
let one = hit(&d, Hit::Icon(1));
|
||||
let target = pos2(one.center().x, one.bottom() - 2.0);
|
||||
d.hold(bar, target);
|
||||
let column = Rect::from_min_max(pos2(0.0, 14.0), pos2(36.0, 600.0));
|
||||
assert!(d.outlined(column.shrink(1.0)), "the column is outlined");
|
||||
let line = Rect::from_x_y_ranges(column.x_range(), (one.bottom() - 2.0)..=(one.bottom() + 2.0));
|
||||
assert!(d.filled(line), "with the insertion line under group 1");
|
||||
let out = d.release(target);
|
||||
assert!(
|
||||
out.actions
|
||||
.contains(&Action::MoveGroup { panel: 5, to: Target::At { anchor: 1, placement: Placement::Group { below: true, height: None } } }),
|
||||
"{:?}",
|
||||
out.actions
|
||||
);
|
||||
assert_eq!(groups(&d.layout), vec![vec![1], vec![5, 6], vec![2]]);
|
||||
assert!(first_column(&d.layout).iconic);
|
||||
}
|
||||
|
||||
/// Every kind of gesture source has a rect, and dragging from it does something.
|
||||
#[test]
|
||||
fn hit_rects_cover_every_gesture_source() {
|
||||
let mut expanded = Column::new(vec![Group::new(vec![1, 2, 3, 4, 5, 6, 7], 0), Group::new(vec![8], 0)], 150.0);
|
||||
expanded.width = 150.0;
|
||||
let mut icons = Column::new(vec![Group::new(vec![9], 0)], 240.0);
|
||||
icons.iconic = true;
|
||||
let dock = Node::Dock { side: Side::Start, columns: vec![icons, expanded] };
|
||||
let stack = Node::Stack { entries: vec![StackEntry { panel: 10, open: true, height: None }, StackEntry { panel: 11, open: true, height: None }] };
|
||||
let frames = Node::Split {
|
||||
axis: SplitAxis::Vertical,
|
||||
size: SplitSize::Ratio(0.5),
|
||||
first: Box::new(Node::Tabs { panels: vec![0], active: 0 }),
|
||||
second: Box::new(stack),
|
||||
};
|
||||
let window = Floating::stack(vec![Group::new(vec![12], 0), Group::new(vec![13], 0)], [500.0, 60.0, 220.0, 300.0]).unwrap();
|
||||
let layout = Layout {
|
||||
root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(200.0), first: Box::new(dock), second: Box::new(frames) }),
|
||||
floating: vec![window],
|
||||
};
|
||||
let d = DockDriver::new(layout.clone(), Content);
|
||||
let hits = d.hits();
|
||||
let kinds = |f: &dyn Fn(&Hit<u32>) -> bool| hits.iter().filter(|(h, _)| f(h)).count();
|
||||
let expected: [Check<'_>; 15] = [
|
||||
("tab", &|h| matches!(h, Hit::Tab(_))),
|
||||
("drag bar", &|h| matches!(h, Hit::DragBar(_))),
|
||||
("border", &|h| matches!(h, Hit::Border(_))),
|
||||
("overflow", &|h| matches!(h, Hit::Overflow(_))),
|
||||
("column bar", &|h| matches!(h, Hit::ColumnBar(_))),
|
||||
("collapse", &|h| matches!(h, Hit::Collapse(_))),
|
||||
("stack toggle", &|h| matches!(h, Hit::StackToggle(_))),
|
||||
("title", &|h| matches!(h, Hit::Title(12))),
|
||||
("close", &|h| matches!(h, Hit::Close(12))),
|
||||
("icon", &|h| matches!(h, Hit::Icon(9))),
|
||||
("icon grip", &|h| matches!(h, Hit::IconGrip(9))),
|
||||
("resize", &|h| matches!(h, Hit::Resize(12, _))),
|
||||
("split", &|h| matches!(h, Hit::Divider(Divider::Split(_)))),
|
||||
("column divider", &|h| matches!(h, Hit::Divider(Divider::Column(_)))),
|
||||
("group divider", &|h| matches!(h, Hit::Divider(Divider::Group(_)))),
|
||||
];
|
||||
for (name, kind) in expected {
|
||||
assert!(kinds(kind) > 0, "{name}: {hits:?}");
|
||||
}
|
||||
assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Divider(Divider::Stack(10)))));
|
||||
assert_eq!(hits.iter().filter(|(h, _)| matches!(h, Hit::Resize(..))).count(), 8);
|
||||
for (hit, rect) in hits.iter().filter(|(h, _)| !matches!(h, Hit::Overflow(_) | Hit::Collapse(_) | Hit::StackToggle(_) | Hit::Close(_))) {
|
||||
let mut d = DockDriver::new(layout.clone(), Content);
|
||||
let from = rect.center();
|
||||
let moved = d.hold(from, from + vec2(-30.0, 40.0));
|
||||
let dragging = is_dragging::<u32>(&d.ctx, d.id);
|
||||
let released = d.release(from + vec2(-30.0, 40.0));
|
||||
assert!(dragging || !moved.actions.is_empty() || !released.actions.is_empty(), "{hit:?} at {rect:?} does nothing");
|
||||
}
|
||||
for (hit, rect) in hits.iter().filter(|(h, _)| matches!(h, Hit::Overflow(_) | Hit::Collapse(_) | Hit::StackToggle(_) | Hit::Close(_))) {
|
||||
let mut d = DockDriver::new(layout.clone(), Content);
|
||||
let out = d.click(rect.center());
|
||||
let opened = egui::Popup::is_any_open(&d.ctx);
|
||||
assert!(opened || !out.actions.is_empty(), "{hit:?} at {rect:?} does nothing");
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints panel 1's icon as a dot in code; panel 2 has neither a painted icon nor an image.
|
||||
struct Painted;
|
||||
|
||||
impl DockContent<u32> for Painted {
|
||||
fn body(&mut self, _: &mut egui::Ui, _: &u32) {}
|
||||
fn logical_label(&self, panel: &u32) -> String {
|
||||
format!("Panel {panel}")
|
||||
}
|
||||
fn paint_icon(&mut self, painter: &egui::Painter, rect: Rect, panel: &u32, color: egui::Color32) -> bool {
|
||||
if *panel != 1 {
|
||||
return false;
|
||||
}
|
||||
painter.circle_filled(rect.center(), 3.0, color);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_painted_in_code_replaces_the_initial_and_others_fall_back() {
|
||||
let d = DockDriver::new(docked(&[&[1, 2]], true), Painted);
|
||||
let (one, two) = (d.hit(&Hit::Icon(1)).unwrap(), d.hit(&Hit::Icon(2)).unwrap());
|
||||
let dots: Vec<Pos2> = d
|
||||
.shapes()
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Circle(circle) if circle.radius == 3.0 => Some(circle.center),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(dots.len(), 1, "{dots:?}");
|
||||
assert!(one.contains(dots[0]) && !two.contains(dots[0]), "the dot sits in panel 1's cell: {dots:?}");
|
||||
let initials: Vec<Pos2> = d
|
||||
.shapes()
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == "P" => Some(text.pos),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(initials.len(), 1, "only panel 2 draws its initial: {initials:?}");
|
||||
assert!(two.contains(initials[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chrome_has_focus_covers_every_drawn_control() {
|
||||
let mut layout = docked(&[&[1, 2], &[3]], true);
|
||||
layout.floating.push(Floating::single(vec![5, 6], 0, [400.0, 100.0, 240.0, 200.0]));
|
||||
let mut d = Driver::new(layout, Content);
|
||||
d.settle();
|
||||
let hits = d.hits();
|
||||
assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Icon(_))), "{hits:?}");
|
||||
assert!(hits.iter().any(|(h, _)| matches!(h, Hit::IconGrip(_))), "{hits:?}");
|
||||
assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Resize(_, ResizeEdge::Left))), "{hits:?}");
|
||||
for (hit, _) in hits {
|
||||
d.ctx.memory_mut(|m| m.request_focus(DockArea::<u32>::hit_id(d.id, &hit)));
|
||||
assert!(DockArea::<u32>::new(d.id).chrome_has_focus(&d.ctx, &d.layout), "{hit:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_windows_stay_inside_the_float_bounds() {
|
||||
// The app's title bar strip (top 30 pt) is outside the bounds: a window saved there is
|
||||
// drawn below it, and a title bar drag towards it stops at its edge. Command keeps the
|
||||
// drag from docking.
|
||||
let mut layout = docked(&[&[1]], false);
|
||||
layout.floating.push(Floating::single(vec![5], 0, [400.0, 0.0, 240.0, 200.0]));
|
||||
let mut d = DockDriver::new(layout, Content);
|
||||
d.float_bounds = Some(Rect::from_min_max(pos2(0.0, 30.0), pos2(800.0, 600.0)));
|
||||
d.settle();
|
||||
let title = hit(&d, Hit::Title(5));
|
||||
assert!(title.top() >= 30.0, "{title:?}");
|
||||
d.modifiers = egui::Modifiers::COMMAND;
|
||||
d.drag(title.center(), pos2(title.center().x, 2.0));
|
||||
d.modifiers = egui::Modifiers::NONE;
|
||||
d.settle();
|
||||
let title = hit(&d, Hit::Title(5));
|
||||
assert!(title.top() >= 30.0, "{title:?}");
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! One keyed hook for every label in [`DockStyle`].
|
||||
|
||||
use super::DockStyle;
|
||||
|
||||
impl DockStyle {
|
||||
/// Replace every `*_label` field with `translate(key)`, keeping the English default where it
|
||||
/// returns `None`. The defaults of menu items are in title case; those of controls, which
|
||||
/// only screen readers announce, in sentence case. An application translates the docking
|
||||
/// chrome in one place:
|
||||
///
|
||||
/// ```
|
||||
/// fn dock_style(ui: &egui::Ui) -> craft_ui::docking::DockStyle {
|
||||
/// craft_ui::docking::DockStyle::from_ui(ui).localized(|key| match key {
|
||||
/// "dock.close" => Some("Fermer le panneau".to_owned()),
|
||||
/// _ => None,
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// | Key | Field | English default |
|
||||
/// |---|---|---|
|
||||
/// | `dock.float` | `float_label` | Float Panel |
|
||||
/// | `dock.close` | `close_label` | Close Panel |
|
||||
/// | `dock.movePanelTo` | `move_panel_to_label` | Move Panel to Group |
|
||||
/// | `dock.panels` | `panels_label` | Panels |
|
||||
/// | `dock.resize` | `resize_label` | Resize panels |
|
||||
/// | `dock.resizeWindow` | `resize_window_label` | Resize panel window |
|
||||
/// | `dock.moveGroup` | `move_group_label` | Move tab group |
|
||||
/// | `dock.closeGroup` | `close_group_label` | Close Tab Group |
|
||||
/// | `dock.minimize` | `minimize_label` | Minimize |
|
||||
/// | `dock.expand` | `expand_label` | Expand |
|
||||
/// | `dock.floatGroup` | `float_group_label` | Float Tab Group |
|
||||
/// | `dock.moveGroupTo` | `move_group_to_label` | Move Group To |
|
||||
/// | `dock.moveColumn` | `move_column_label` | Move panel column |
|
||||
/// | `dock.collapseToIcons` | `collapse_to_icons_label` | Collapse to Icons |
|
||||
/// | `dock.expandPanels` | `expand_panels_label` | Expand Panels |
|
||||
/// | `dock.collapseColumn` | `collapse_column_label` | Collapse column to icons |
|
||||
/// | `dock.expandColumn` | `expand_column_label` | Expand column |
|
||||
/// | `dock.moveWindow` | `move_window_label` | Move panel window |
|
||||
/// | `dock.closeWindow` | `close_window_label` | Close panel window |
|
||||
/// | `dock.closeOthers` | `close_others_label` | Close Other Panels in Group |
|
||||
/// | `dock.maximize` | `maximize_label` | Maximize Frame |
|
||||
/// | `dock.restoreFrame` | `restore_frame_label` | Restore Frame Size |
|
||||
/// | `dock.newWindow` | `new_window_label` | Move Panel to New Window |
|
||||
/// | `dock.autoCollapse` | `auto_collapse_label` | Auto-Collapse Iconic Panels |
|
||||
/// | `dock.floatHint` | `float_hint_label` | Hold {key} to undock |
|
||||
#[must_use]
|
||||
pub fn localized(mut self, translate: impl Fn(&str) -> Option<String>) -> Self {
|
||||
for (key, label) in self.labels_mut() {
|
||||
if let Some(text) = translate(key) {
|
||||
*label = text;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn labels_mut(&mut self) -> [(&'static str, &mut String); 25] {
|
||||
[
|
||||
("dock.float", &mut self.float_label),
|
||||
("dock.close", &mut self.close_label),
|
||||
("dock.movePanelTo", &mut self.move_panel_to_label),
|
||||
("dock.panels", &mut self.panels_label),
|
||||
("dock.resize", &mut self.resize_label),
|
||||
("dock.resizeWindow", &mut self.resize_window_label),
|
||||
("dock.moveGroup", &mut self.move_group_label),
|
||||
("dock.closeGroup", &mut self.close_group_label),
|
||||
("dock.minimize", &mut self.minimize_label),
|
||||
("dock.expand", &mut self.expand_label),
|
||||
("dock.floatGroup", &mut self.float_group_label),
|
||||
("dock.moveGroupTo", &mut self.move_group_to_label),
|
||||
("dock.moveColumn", &mut self.move_column_label),
|
||||
("dock.collapseToIcons", &mut self.collapse_to_icons_label),
|
||||
("dock.expandPanels", &mut self.expand_panels_label),
|
||||
("dock.collapseColumn", &mut self.collapse_column_label),
|
||||
("dock.expandColumn", &mut self.expand_column_label),
|
||||
("dock.moveWindow", &mut self.move_window_label),
|
||||
("dock.closeWindow", &mut self.close_window_label),
|
||||
("dock.closeOthers", &mut self.close_others_label),
|
||||
("dock.maximize", &mut self.maximize_label),
|
||||
("dock.restoreFrame", &mut self.restore_frame_label),
|
||||
("dock.newWindow", &mut self.new_window_label),
|
||||
("dock.autoCollapse", &mut self.auto_collapse_label),
|
||||
("dock.floatHint", &mut self.float_hint_label),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,49 @@
|
||||
//! Validate deserialized layouts before rendering them. Every transaction checks its complete
|
||||
//! input and commits only a valid result; a rejected move cannot lose the source panel.
|
||||
|
||||
pub mod chrome;
|
||||
#[cfg(feature = "serde")]
|
||||
mod command;
|
||||
mod dock_model;
|
||||
mod hits;
|
||||
mod labels;
|
||||
mod model;
|
||||
mod render;
|
||||
mod resize;
|
||||
mod surface;
|
||||
mod targets;
|
||||
#[cfg(any(test, feature = "testing"))]
|
||||
pub mod testing;
|
||||
mod workspace;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
pub use command::{DockCommand, DockOperation, UiDock, ZoneName};
|
||||
pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target};
|
||||
pub use hits::{Divider, Hit, ResizeEdge};
|
||||
pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone};
|
||||
pub use surface::{DockArea, DockContent, DockOutput, DockStyle, PanelLimits, begin_drag, cancel_drag};
|
||||
pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect};
|
||||
pub use render::{close_flyout, flyout, open_flyout};
|
||||
pub use surface::{
|
||||
DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, FloatSpace, HidePanels, PanelLimits, begin_drag, cancel_drag,
|
||||
float_space, is_dragging,
|
||||
};
|
||||
pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect, zone_shape};
|
||||
pub use workspace::Workspace;
|
||||
|
||||
use surface::{Drag, GroupDrag, GroupGesture};
|
||||
|
||||
#[cfg(test)]
|
||||
mod command_tests;
|
||||
#[cfg(test)]
|
||||
mod dock_tests;
|
||||
#[cfg(test)]
|
||||
mod floating_tests;
|
||||
#[cfg(test)]
|
||||
mod group_tests;
|
||||
#[cfg(test)]
|
||||
mod iconic_tests;
|
||||
#[cfg(test)]
|
||||
mod model_tests;
|
||||
#[cfg(test)]
|
||||
mod split_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+775
-134
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,593 @@
|
||||
use super::dock_model::{Place, node_at};
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
|
||||
pub(super) fn g(panels: &[u32], active: usize) -> Group<u32> {
|
||||
Group::new(panels.to_vec(), active)
|
||||
}
|
||||
|
||||
fn tabs(panels: &[u32], active: usize) -> Node<u32> {
|
||||
Node::Tabs { panels: panels.to_vec(), active }
|
||||
}
|
||||
|
||||
fn hsplit(size: SplitSize, first: Node<u32>, second: Node<u32>) -> Node<u32> {
|
||||
Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(first), second: Box::new(second) }
|
||||
}
|
||||
|
||||
/// Canvas 1 above frame tabs [11, 12]; an end dock with column A ([2, 3], [4]) and column B
|
||||
/// ([5]); a floating window with groups [6, 7] and [8].
|
||||
pub(super) fn docked() -> Layout<u32> {
|
||||
let middle =
|
||||
Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(0.7), first: Box::new(tabs(&[1], 0)), second: Box::new(tabs(&[11, 12], 1)) };
|
||||
let dock =
|
||||
Node::Dock { side: Side::End, columns: vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)], 180.0), Column::new(vec![g(&[5], 0)], 120.0)] };
|
||||
Layout {
|
||||
root: Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)),
|
||||
floating: vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], [100.0, 100.0, 300.0, 400.0]).unwrap()],
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const ALL: [u32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12];
|
||||
|
||||
fn sorted(layout: &Layout<u32>) -> Vec<u32> {
|
||||
let mut panels: Vec<u32> = layout.panels().into_iter().copied().collect();
|
||||
panels.sort_unstable();
|
||||
panels
|
||||
}
|
||||
|
||||
/// Members, active panel and minimized state of the group holding `panel`.
|
||||
fn group_state(layout: &Layout<u32>, panel: u32) -> (Vec<u32>, u32, bool) {
|
||||
match layout.place(&panel).unwrap() {
|
||||
place @ (Place::Node(_) | Place::Floating { .. }) => match layout.node_of(&place).unwrap() {
|
||||
Node::Tabs { panels, active } => (panels.clone(), panels[*active], false),
|
||||
other => panic!("{other:?}"),
|
||||
},
|
||||
place => {
|
||||
let group = layout.group(&place).unwrap();
|
||||
(group.panels.clone(), group.panels[group.active], group.minimized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dock(layout: &Layout<u32>, side: Side) -> &Vec<Column<u32>> {
|
||||
let path = layout.dock_path(side).unwrap();
|
||||
let Some(Node::Dock { columns, .. }) = node_at(layout.root.as_ref().unwrap(), &path) else { panic!() };
|
||||
columns
|
||||
}
|
||||
|
||||
fn panels_of(groups: &[Group<u32>]) -> Vec<Vec<u32>> {
|
||||
groups.iter().map(|g| g.panels.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_moves_keep_order_active_tab_and_minimized_state() {
|
||||
let targets = [
|
||||
Target::At { anchor: 5, placement: Placement::Group { below: true, height: None } },
|
||||
Target::At { anchor: 5, placement: Placement::Column { after: true } },
|
||||
Target::At { anchor: 8, placement: Placement::Group { below: false, height: None } },
|
||||
Target::NewDock { side: Side::Start },
|
||||
Target::Float { rect: Some([20.0, 20.0, 200.0, 300.0]) },
|
||||
Target::Float { rect: None },
|
||||
];
|
||||
// A frame Tabs node, a column group and a floating group.
|
||||
for source in [11, 2, 6] {
|
||||
for to in &targets {
|
||||
let mut layout = docked();
|
||||
if source != 11 {
|
||||
layout.apply(Action::SetMinimized { panel: source, minimized: true }).unwrap();
|
||||
}
|
||||
let before = group_state(&layout, source);
|
||||
layout.apply(Action::MoveGroup { panel: source, to: to.clone() }).unwrap_or_else(|e| panic!("{source} {to:?}: {e}"));
|
||||
let after = group_state(&layout, source);
|
||||
assert_eq!((&after.0, after.1), (&before.0, before.1), "{source} {to:?}");
|
||||
// A group keeps its minimized state from dock to dock; a floating window's tree
|
||||
// has no minimized groups.
|
||||
if matches!((source, layout.place(&source)), (2, Some(Place::Dock { .. }))) {
|
||||
assert_eq!(after.2, before.2, "{source} {to:?}");
|
||||
}
|
||||
assert_eq!(sorted(&layout), ALL);
|
||||
}
|
||||
}
|
||||
// Into a frame split the group becomes a Tabs node with the same order and selection.
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveGroup { panel: 6, to: Target::At { anchor: 1, placement: Placement::Split(Zone::Left) } }).unwrap();
|
||||
assert_eq!(group_state(&layout, 6), (vec![6, 7], 7, false));
|
||||
assert_eq!(layout.floating[0].groups().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_merge_into_tabs_inserts_every_member_before_the_anchor_tab() {
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveGroup { panel: 6, to: Target::At { anchor: 2, placement: Placement::Tab { before: Some(3) } } }).unwrap();
|
||||
assert_eq!(group_state(&layout, 2), (vec![2, 6, 7, 3], 7, false));
|
||||
assert_eq!(panels_of(&layout.floating[0].groups()), [vec![8]]);
|
||||
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 11, placement: Placement::Tab { before: Some(12) } } }).unwrap();
|
||||
assert_eq!(group_state(&layout, 11), (vec![11, 2, 3, 12], 3, false));
|
||||
assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![4]]);
|
||||
|
||||
// A target inside the moving group is a no-op; a protected anchor refuses tabs.
|
||||
let before = docked();
|
||||
let mut layout = before.clone();
|
||||
layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 3, placement: Placement::Tab { before: None } } }).unwrap();
|
||||
assert_eq!(layout, before);
|
||||
let protect = |p: &u32| if *p == 1 { Permissions::PROTECTED } else { Permissions::default() };
|
||||
let to = Target::At { anchor: 1, placement: Placement::Tab { before: None } };
|
||||
assert_eq!(layout.apply_with_permissions(Action::MoveGroup { panel: 2, to }, protect), Err(DockError::NotAllowed));
|
||||
assert_eq!(layout, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_moves_and_floats_keep_every_group() {
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::SetIconic { panel: 4, iconic: true }).unwrap();
|
||||
layout.apply(Action::MoveColumn { panel: 2, to: Target::NewDock { side: Side::Start } }).unwrap();
|
||||
let Some(Node::Split { size, first, .. }) = &layout.root else { panic!() };
|
||||
assert_eq!(*size, SplitSize::FixedFirst(180.0));
|
||||
assert!(matches!(**first, Node::Dock { side: Side::Start, .. }));
|
||||
let start = dock(&layout, Side::Start);
|
||||
assert_eq!(start.len(), 1);
|
||||
assert_eq!(panels_of(&start[0].groups), [vec![2, 3], vec![4]]);
|
||||
assert_eq!((start[0].width, start[0].iconic, start[0].groups[0].active), (180.0, true, 1));
|
||||
assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![5]]);
|
||||
|
||||
// The last column leaves the end dock, which collapses.
|
||||
layout.apply(Action::MoveColumn { panel: 5, to: Target::At { anchor: 2, placement: Placement::Column { after: false } } }).unwrap();
|
||||
assert!(layout.dock_path(Side::End).is_none());
|
||||
let start = dock(&layout, Side::Start);
|
||||
assert_eq!(start.iter().map(|c| c.width).collect::<Vec<_>>(), [120.0, 180.0]);
|
||||
|
||||
layout.apply(Action::MoveColumn { panel: 3, to: Target::Float { rect: None } }).unwrap();
|
||||
let window = layout.floating.last().unwrap();
|
||||
assert_eq!(panels_of(&window.groups()), [vec![2, 3], vec![4]]);
|
||||
assert_eq!(window.rect[2], 180.0);
|
||||
assert_eq!(sorted(&layout), ALL);
|
||||
assert_eq!(layout.apply(Action::MoveColumn { panel: 11, to: Target::Float { rect: None } }), Err(DockError::InvalidPlacement));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_docks_as_stacked_groups_or_merges_as_tabs() {
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveWindow { panel: 8, to: Target::At { anchor: 4, placement: Placement::Group { below: true, height: None } } }).unwrap();
|
||||
assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![2, 3], vec![4], vec![6, 7], vec![8]]);
|
||||
assert!(layout.floating.is_empty());
|
||||
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveWindow { panel: 8, to: Target::At { anchor: 11, placement: Placement::Tab { before: None } } }).unwrap();
|
||||
assert_eq!(group_state(&layout, 11), (vec![11, 12, 6, 7, 8], 7, false));
|
||||
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveWindow { panel: 6, to: Target::NewDock { side: Side::Start } }).unwrap();
|
||||
let start = dock(&layout, Side::Start);
|
||||
assert_eq!((panels_of(&start[0].groups), start[0].width), (vec![vec![6, 7], vec![8]], 300.0));
|
||||
|
||||
let before = docked();
|
||||
let mut layout = before.clone();
|
||||
layout.apply(Action::MoveWindow { panel: 7, to: Target::At { anchor: 8, placement: Placement::Tab { before: None } } }).unwrap();
|
||||
assert_eq!(layout, before);
|
||||
assert_eq!(layout.apply(Action::MoveWindow { panel: 2, to: Target::Float { rect: None } }), Err(DockError::InvalidPlacement));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_group_and_close_window_record_a_restorable_location_per_member() {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
let allow = |_: &u32| Permissions::default();
|
||||
assert_eq!(workspace.apply(Action::CloseGroup { panel: 3 }, allow).unwrap(), [2, 3]);
|
||||
assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::<Vec<_>>(), [2, 3]);
|
||||
assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![4]]);
|
||||
workspace.set_visible(2, true, None, |_| Permissions::default()).unwrap();
|
||||
workspace.set_visible(3, true, None, |_| Permissions::default()).unwrap();
|
||||
assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![2, 3], vec![4]]);
|
||||
|
||||
assert_eq!(workspace.layout.closed_by(&Action::CloseWindow { panel: 7 }).unwrap(), [6, 7, 8]);
|
||||
assert_eq!(workspace.apply(Action::CloseWindow { panel: 7 }, allow).unwrap(), [6, 7, 8]);
|
||||
assert!(workspace.layout.floating.is_empty());
|
||||
assert_eq!(workspace.hidden.len(), 3);
|
||||
for panel in [6, 7, 8] {
|
||||
workspace.set_visible(panel, true, None, |_| Permissions::default()).unwrap();
|
||||
}
|
||||
assert_eq!(workspace.layout.floating.len(), 1);
|
||||
assert_eq!(panels_of(&workspace.layout.floating[0].groups()), [vec![6, 7], vec![8]]);
|
||||
assert_eq!(workspace.layout.floating[0].rect, [100.0, 100.0, 300.0, 400.0]);
|
||||
|
||||
workspace.apply(Action::CloseOthers { panel: 12 }, allow).unwrap();
|
||||
assert_eq!(group_state(&workspace.layout, 12).0, [12]);
|
||||
workspace.set_visible(11, true, None, |_| Permissions::default()).unwrap();
|
||||
assert_eq!(group_state(&workspace.layout, 12).0, [11, 12]);
|
||||
assert!(workspace.hidden.is_empty());
|
||||
assert_eq!(sorted(&workspace.layout), ALL);
|
||||
|
||||
// A member that may not close keeps the whole group open.
|
||||
let keep = |p: &u32| if *p == 4 { Permissions { closable: false, ..Permissions::default() } } else { Permissions::default() };
|
||||
let before = workspace.clone();
|
||||
assert_eq!(workspace.apply(Action::CloseGroup { panel: 4 }, keep), Err(DockError::NotAllowed));
|
||||
assert_eq!(workspace, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_into_a_column_group_seam_and_new_column_round_trips() {
|
||||
let column_a = Column::new(vec![g(&[2, 3], 1), Group { minimized: true, height: Some(150.0), ..g(&[4], 0) }, g(&[9], 0)], 180.0);
|
||||
let column_b = Column { iconic: true, iconic_width: Some(48.0), ..Column::new(vec![g(&[5], 0)], 120.0) };
|
||||
let end = Node::Dock { side: Side::End, columns: vec![column_a, column_b] };
|
||||
let start = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![g(&[10], 0)], 200.0)] };
|
||||
let original = Layout {
|
||||
root: Some(hsplit(SplitSize::FixedFirst(200.0), start, hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end))),
|
||||
floating: vec![Floating::stack(vec![g(&[6], 0), Group { height: Some(90.0), ..g(&[7], 0) }], [10.0, 10.0, 200.0, 300.0]).unwrap()],
|
||||
};
|
||||
original.validate().unwrap();
|
||||
// 4: the seam between [2, 3] and [9]; 9: below [4]; 5: a new column after A; 10: alone in
|
||||
// its dock; 3: a tab; 7: below a floating group.
|
||||
for panel in [4, 9, 5, 10, 3, 7] {
|
||||
let mut layout = original.clone();
|
||||
let location = layout.location(&panel).unwrap();
|
||||
#[cfg(feature = "serde")]
|
||||
let location: Location<u32> = serde_json::from_str(&serde_json::to_string(&location).unwrap()).unwrap();
|
||||
layout.apply(Action::Close { panel }).unwrap();
|
||||
layout.restore(panel, &location).unwrap_or_else(|e| panic!("{panel}: {e} {location:?}"));
|
||||
assert_eq!(layout, original, "{panel}: {location:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_validation_rejects_two_docks_per_side_nested_docks_empty_columns_and_bad_widths() {
|
||||
docked().validate().unwrap();
|
||||
let empty_dock = |side| Node::Dock { side, columns: Vec::new() };
|
||||
Layout { root: Some(hsplit(SplitSize::FixedFirst(10.0), empty_dock(Side::Start), tabs(&[1], 0))), floating: Vec::new() }.validate().unwrap();
|
||||
|
||||
let two = hsplit(SplitSize::Ratio(0.5), empty_dock(Side::Start), empty_dock(Side::Start));
|
||||
let nested = Node::Split {
|
||||
axis: SplitAxis::Vertical,
|
||||
size: SplitSize::Ratio(0.5),
|
||||
first: Box::new(empty_dock(Side::Start)),
|
||||
second: Box::new(tabs(&[1], 0)),
|
||||
};
|
||||
let wrong_side = hsplit(SplitSize::Ratio(0.5), empty_dock(Side::End), tabs(&[1], 0));
|
||||
for root in [two, nested, wrong_side] {
|
||||
assert_eq!(Layout { root: Some(root), floating: Vec::new() }.validate(), Err(DockError::InvalidPlacement));
|
||||
}
|
||||
|
||||
let with_column = |column: Column<u32>| Layout { root: Some(Node::Dock { side: Side::End, columns: vec![column] }), floating: Vec::new() };
|
||||
let bad = [
|
||||
Column::new(Vec::new(), 100.0),
|
||||
Column::new(vec![g(&[], 0)], 100.0),
|
||||
Column::new(vec![g(&[2], 1)], 100.0),
|
||||
Column::new(vec![Group { height: Some(f32::NAN), ..g(&[2], 0) }], 100.0),
|
||||
Column::new(vec![g(&[2], 0)], 0.0),
|
||||
Column::new(vec![g(&[2], 0)], -5.0),
|
||||
Column::new(vec![g(&[2], 0)], f32::INFINITY),
|
||||
Column::new(vec![g(&[2], 0)], 2.0e6),
|
||||
Column { iconic_width: Some(f32::NAN), ..Column::new(vec![g(&[2], 0)], 100.0) },
|
||||
];
|
||||
for column in bad {
|
||||
assert!(with_column(column.clone()).validate().is_err(), "{column:?}");
|
||||
}
|
||||
|
||||
let mut duplicate = docked();
|
||||
duplicate.floating[0].root = Node::Tabs { panels: vec![6, 7, 2], active: 0 };
|
||||
assert_eq!(duplicate.validate(), Err(DockError::DuplicatePanel));
|
||||
let mut empty_window = docked();
|
||||
empty_window.floating[0].root = Node::Tabs { panels: Vec::new(), active: 0 };
|
||||
assert_eq!(empty_window.validate(), Err(DockError::InvalidGeometry));
|
||||
let mut docked_window = docked();
|
||||
docked_window.floating[0].root = Node::Dock { side: Side::End, columns: vec![Column::new(vec![g(&[6, 7], 0)], 100.0)] };
|
||||
assert_eq!(docked_window.validate(), Err(DockError::InvalidPlacement));
|
||||
let mut native = docked();
|
||||
native.floating[0].native = Some([0.0, 0.0, -1.0, 10.0]);
|
||||
assert_eq!(native.validate(), Err(DockError::InvalidGeometry));
|
||||
let mut layout = docked();
|
||||
assert_eq!(layout.apply(Action::ResizeColumn { panel: 2, width: f32::NAN }), Err(DockError::InvalidGeometry));
|
||||
assert_eq!(layout.apply(Action::ResizeColumn { panel: 11, width: 50.0 }), Err(DockError::InvalidPlacement));
|
||||
assert_eq!(layout, docked());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_workspace_rejects_structure_but_allows_activate_open_minimize_and_resize() {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
let allow = |_: &u32| Permissions::default();
|
||||
workspace.apply(Action::Close { panel: 12 }, allow).unwrap();
|
||||
workspace.locked = true;
|
||||
let before = workspace.clone();
|
||||
let refused = [
|
||||
Action::Move { panel: 2, anchor: 5, placement: Placement::Tab { before: None } },
|
||||
Action::MoveGroup { panel: 2, to: Target::Float { rect: None } },
|
||||
Action::MoveColumn { panel: 5, to: Target::NewDock { side: Side::Start } },
|
||||
Action::MoveWindow { panel: 6, to: Target::At { anchor: 4, placement: Placement::Group { below: true, height: None } } },
|
||||
Action::Float { panel: 4, rect: [0.0, 0.0, 100.0, 100.0] },
|
||||
Action::MoveFloating { panel: 6, rect: [0.0, 0.0, 100.0, 100.0] },
|
||||
Action::Close { panel: 4 },
|
||||
Action::CloseGroup { panel: 4 },
|
||||
Action::CloseWindow { panel: 6 },
|
||||
Action::SetNative { panel: 6, rect: Some([0.0, 0.0, 100.0, 100.0]) },
|
||||
];
|
||||
for action in refused {
|
||||
assert_eq!(workspace.apply(action.clone(), allow), Err(DockError::NotAllowed), "{action:?}");
|
||||
assert_eq!(workspace, before);
|
||||
}
|
||||
assert_eq!(workspace.set_visible(4, false, None, |_| Permissions::default()), Err(DockError::NotAllowed));
|
||||
let allowed = [
|
||||
Action::Activate { panel: 2 },
|
||||
Action::Open { panel: 12, anchor: Some(11) },
|
||||
Action::SetMinimized { panel: 4, minimized: true },
|
||||
Action::SetIconic { panel: 5, iconic: true },
|
||||
Action::ResizeColumn { panel: 5, width: 160.0 },
|
||||
Action::ResizeGroup { panel: 4, height: Some(120.0) },
|
||||
Action::ResizeIconic { panel: 5, width: Some(60.0) },
|
||||
Action::ResizeSplit { path: Vec::new(), size: SplitSize::FixedSecond(320.0) },
|
||||
];
|
||||
workspace.apply_all(allowed, allow).unwrap();
|
||||
assert!(workspace.hidden.is_empty());
|
||||
assert_eq!(workspace.layout.panel_state(&12), PanelState::Front);
|
||||
assert_eq!(workspace.layout.panel_state(&4), PanelState::Open);
|
||||
assert_eq!(workspace.layout.panel_state(&5), PanelState::Open);
|
||||
assert_eq!(workspace.layout.panel_state(&2), PanelState::Front);
|
||||
assert_eq!(workspace.layout.panel_state(&3), PanelState::Open);
|
||||
// Opening at a chosen place works too; moving a shown panel there does not.
|
||||
workspace.apply(Action::OpenAt { panel: 13, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow).unwrap();
|
||||
assert!(workspace.layout.contains(&13));
|
||||
assert_eq!(
|
||||
workspace.apply(Action::OpenAt { panel: 2, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow),
|
||||
Err(DockError::NotAllowed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hiding_a_panel_that_may_not_close_is_refused() {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
let canvas = |p: &u32| if *p == 1 { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() };
|
||||
assert_eq!(workspace.set_visible(1, false, None, canvas), Err(DockError::NotAllowed));
|
||||
assert!(workspace.layout.contains(&1) && workspace.hidden.is_empty());
|
||||
workspace.set_visible(2, false, None, canvas).unwrap();
|
||||
assert!(!workspace.layout.contains(&2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() {
|
||||
let default = Workspace::new(docked());
|
||||
let mut workspace = default.clone();
|
||||
workspace.layout.apply(Action::Close { panel: 5 }).unwrap();
|
||||
workspace.layout.apply(Action::Close { panel: 12 }).unwrap();
|
||||
workspace.layout.apply(Action::OpenAt { panel: 99, anchor: 2, placement: Placement::Tab { before: None } }).unwrap();
|
||||
let stray = workspace.layout.location(&99).unwrap();
|
||||
workspace.hidden.push((98, stray));
|
||||
let registered = |p: &u32| *p < 90;
|
||||
workspace.reconcile(registered, |_| Permissions::default(), &default);
|
||||
workspace.validate().unwrap();
|
||||
// Unregistered panels wait in `hidden` and come back once registered.
|
||||
assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::<Vec<_>>(), [98, 99]);
|
||||
assert_eq!(sorted(&workspace.layout), ALL);
|
||||
workspace.set_visible(99, true, None, |_| Permissions::default()).unwrap();
|
||||
assert_eq!(group_state(&workspace.layout, 2).0, [2, 3, 99]);
|
||||
assert_eq!(dock(&workspace.layout, Side::End).len(), 2);
|
||||
assert_eq!(group_state(&workspace.layout, 11).0, [11, 12]);
|
||||
|
||||
let mut broken = default.clone();
|
||||
broken.layout.floating[0].rect[2] = -1.0;
|
||||
broken.reconcile(registered, |_| Permissions::default(), &default);
|
||||
assert_eq!(broken.layout, default.layout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_returns_to_saved_or_default() {
|
||||
let default = docked();
|
||||
let mut workspace = Workspace::new(default.clone());
|
||||
workspace.apply(Action::MoveGroup { panel: 6, to: Target::NewDock { side: Side::Start } }, |_| Permissions::default()).unwrap();
|
||||
workspace.reset(&default);
|
||||
assert_eq!(workspace.layout, default);
|
||||
|
||||
let mut saved = default.clone();
|
||||
saved.apply(Action::Close { panel: 8 }).unwrap();
|
||||
saved.apply(Action::MoveGroup { panel: 11, to: Target::Float { rect: None } }).unwrap();
|
||||
workspace.saved = Some(saved.clone());
|
||||
workspace.reset(&default);
|
||||
assert_eq!(workspace.layout, saved);
|
||||
assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::<Vec<_>>(), [8]);
|
||||
workspace.validate().unwrap();
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
mod serde_tests {
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn a_saved_stack_of_groups_loads_as_a_vertical_split_by_their_heights() {
|
||||
let saved = json!({
|
||||
"groups": [{"panels": [4], "active": 0, "height": 100.0}, {"panels": [5, 6], "active": 1, "height": 300.0}],
|
||||
"rect": [1.0, 2.0, 300.0, 400.0],
|
||||
});
|
||||
let window: Floating<u32> = serde_json::from_value(saved).unwrap();
|
||||
let expected = Node::Split {
|
||||
axis: SplitAxis::Vertical,
|
||||
size: SplitSize::Ratio(0.25),
|
||||
first: Box::new(Node::Tabs { panels: vec![4], active: 0 }),
|
||||
second: Box::new(Node::Tabs { panels: vec![5, 6], active: 1 }),
|
||||
};
|
||||
assert_eq!((window.root, window.minimized), (expected, false));
|
||||
let all_minimized = json!({"groups": [{"panels": [4], "active": 0, "minimized": true}], "rect": [1.0, 2.0, 300.0, 400.0]});
|
||||
let window: Floating<u32> = serde_json::from_value(all_minimized).unwrap();
|
||||
assert_eq!((window.root, window.minimized), (Node::Tabs { panels: vec![4], active: 0 }, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_plain_floating_window_writes_the_v1_shape() {
|
||||
let rect = [1.0, 2.0, 300.0, 200.0];
|
||||
let plain = Floating::single(vec![4u32, 5], 1, rect);
|
||||
assert_eq!(serde_json::to_value(&plain).unwrap(), json!({"panels": [4, 5], "active": 1, "rect": rect}));
|
||||
let minimized = Floating { minimized: true, ..Floating::single(vec![4u32], 0, rect) };
|
||||
let stacked = Floating::stack(vec![g(&[4], 0), g(&[5], 0)], rect).unwrap();
|
||||
let native = Floating { native: Some(rect), ..Floating::single(vec![4u32], 0, rect) };
|
||||
for window in [minimized, stacked, native] {
|
||||
let value = serde_json::to_value(&window).unwrap();
|
||||
assert!(value.get("root").is_some() && value.get("panels").is_none(), "{value}");
|
||||
assert_eq!(serde_json::from_value::<Floating<u32>>(value).unwrap(), window);
|
||||
}
|
||||
assert!(serde_json::from_value::<Floating<u32>>(json!({"rect": rect})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_round_trips() {
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::CloseGroup { panel: 4 }, |_| Permissions::default()).unwrap();
|
||||
workspace.apply(Action::SetNative { panel: 8, rect: Some([5.0, 5.0, 400.0, 300.0]) }, |_| Permissions::default()).unwrap();
|
||||
workspace.saved = Some(docked());
|
||||
workspace.locked = true;
|
||||
let text = serde_json::to_string(&workspace).unwrap();
|
||||
let parsed: Workspace<u32> = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(parsed, workspace);
|
||||
assert_eq!(serde_json::from_str::<Value>(&text).unwrap()["version"], json!(2));
|
||||
|
||||
let mut old = parsed.clone();
|
||||
old.version = 1;
|
||||
let mut value = serde_json::to_value(&old).unwrap();
|
||||
value.as_object_mut().unwrap().remove("version");
|
||||
assert_eq!(serde_json::from_value::<Workspace<u32>>(value).unwrap().version, 1);
|
||||
old.version = 3;
|
||||
assert_eq!(old.validate(), Err(DockError::UnsupportedVersion));
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Kind {
|
||||
Layout,
|
||||
Workspace,
|
||||
Hidden,
|
||||
}
|
||||
|
||||
/// App, file contents, and the JSON pointers to its docking values.
|
||||
type Fixture = (&'static str, &'static str, &'static [(&'static str, Kind)]);
|
||||
|
||||
#[test]
|
||||
fn v1_layout_json_parses_unchanged() {
|
||||
use Kind::*;
|
||||
let fixtures: [Fixture; 7] = [
|
||||
(
|
||||
"designcraft",
|
||||
include_str!("../../tests/fixtures/v1/designcraft.json"),
|
||||
&[
|
||||
("/docking", Layout),
|
||||
("/dockingHidden", Hidden),
|
||||
("/customWorkspaces/0/docking", Layout),
|
||||
("/customWorkspaces/0/dockingHidden", Hidden),
|
||||
],
|
||||
),
|
||||
("vectorcraft", include_str!("../../tests/fixtures/v1/vectorcraft.json"), &[("/docking", Layout), ("/docking_hidden", Hidden)]),
|
||||
("lightcraft", include_str!("../../tests/fixtures/v1/lightcraft.json"), &[("/docking", Workspace)]),
|
||||
("pdfcraft", include_str!("../../tests/fixtures/v1/pdfcraft.json"), &[("/docking", Workspace)]),
|
||||
("cadcraft", include_str!("../../tests/fixtures/v1/cadcraft.json"), &[("/workspace/docking", Workspace)]),
|
||||
("soundcraft", include_str!("../../tests/fixtures/v1/soundcraft.json"), &[("/docking", Workspace), ("/mix_docking", Workspace)]),
|
||||
(
|
||||
"photocraft",
|
||||
include_str!("../../tests/fixtures/v1/photocraft.json"),
|
||||
&[("/docking", Layout), ("/docking_hidden", Hidden), ("/panel_layout/docking", Layout), ("/panel_layout/dockingHidden", Hidden)],
|
||||
),
|
||||
];
|
||||
for (app, text, fields) in fixtures {
|
||||
let file: Value = serde_json::from_str(text).unwrap();
|
||||
for (pointer, kind) in fields {
|
||||
let value = file.pointer(pointer).unwrap_or_else(|| panic!("{app}{pointer}")).clone();
|
||||
let layout_value = match kind {
|
||||
Layout => value.clone(),
|
||||
Workspace => value["layout"].clone(),
|
||||
Hidden => {
|
||||
let hidden: std::collections::BTreeMap<String, Location<String>> = serde_json::from_value(value).unwrap();
|
||||
assert!(!hidden.is_empty(), "{app}{pointer}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Workspace = kind {
|
||||
let workspace: super::Workspace<String> = serde_json::from_value(value).unwrap_or_else(|e| panic!("{app}{pointer}: {e}"));
|
||||
workspace.validate().unwrap_or_else(|e| panic!("{app}{pointer}: {e}"));
|
||||
assert_eq!(workspace.version, 1);
|
||||
for (panel, location) in &workspace.hidden {
|
||||
let mut layout = workspace.layout.clone();
|
||||
layout.restore(panel.clone(), location).unwrap_or_else(|e| panic!("{app}{pointer} {panel}: {e}"));
|
||||
}
|
||||
}
|
||||
let layout: super::Layout<String> = serde_json::from_value(layout_value.clone()).unwrap_or_else(|e| panic!("{app}{pointer}: {e}"));
|
||||
layout.validate().unwrap_or_else(|e| panic!("{app}{pointer}: {e}"));
|
||||
// Nothing new is in use, so the layout writes back exactly as read.
|
||||
assert_eq!(serde_json::to_value(&layout).unwrap(), layout_value, "{app}{pointer}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_app_fixture_reconciles_with_its_canvas_shown() {
|
||||
let s = |p: &str| p.to_owned();
|
||||
let permissions = |p: &String| if p == "canvas" { Permissions::PROTECTED } else { Permissions::default() };
|
||||
// The canvas between a start dock and the properties, which no fixture matches exactly.
|
||||
let beside = super::Layout {
|
||||
root: Some(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::FixedFirst(240.0),
|
||||
first: Box::new(Node::Dock {
|
||||
side: Side::Start,
|
||||
columns: vec![Column::new(vec![Group::new(vec![s("layers"), s("pages")], 0)], 240.0)],
|
||||
}),
|
||||
second: Box::new(Node::Split {
|
||||
axis: SplitAxis::Horizontal,
|
||||
size: SplitSize::Ratio(0.75),
|
||||
first: Box::new(Node::Tabs { panels: vec![s("canvas")], active: 0 }),
|
||||
second: Box::new(Node::Tabs { panels: vec![s("properties"), s("stroke")], active: 0 }),
|
||||
}),
|
||||
}),
|
||||
floating: Vec::new(),
|
||||
};
|
||||
// The canvas with no anchor to go back beside.
|
||||
let alone = super::Layout { root: Some(Node::Tabs { panels: vec![s("canvas")], active: 0 }), floating: Vec::new() };
|
||||
let fixtures = [
|
||||
("designcraft", include_str!("../../tests/fixtures/v1/designcraft.json"), "/docking"),
|
||||
("designcraft", include_str!("../../tests/fixtures/v1/designcraft.json"), "/customWorkspaces/0/docking"),
|
||||
("vectorcraft", include_str!("../../tests/fixtures/v1/vectorcraft.json"), "/docking"),
|
||||
("lightcraft", include_str!("../../tests/fixtures/v1/lightcraft.json"), "/docking/layout"),
|
||||
("pdfcraft", include_str!("../../tests/fixtures/v1/pdfcraft.json"), "/docking/layout"),
|
||||
("cadcraft", include_str!("../../tests/fixtures/v1/cadcraft.json"), "/workspace/docking/layout"),
|
||||
("soundcraft", include_str!("../../tests/fixtures/v1/soundcraft.json"), "/docking/layout"),
|
||||
("soundcraft", include_str!("../../tests/fixtures/v1/soundcraft.json"), "/mix_docking/layout"),
|
||||
("photocraft", include_str!("../../tests/fixtures/v1/photocraft.json"), "/docking"),
|
||||
("photocraft", include_str!("../../tests/fixtures/v1/photocraft.json"), "/panel_layout/docking"),
|
||||
];
|
||||
for (app, text, pointer) in fixtures {
|
||||
let file: Value = serde_json::from_str(text).unwrap();
|
||||
let mut saved: super::Layout<String> = serde_json::from_value(file.pointer(pointer).unwrap().clone()).unwrap();
|
||||
let own = saved.contains(&s("canvas")).then(|| saved.clone());
|
||||
saved.take(&s("canvas"));
|
||||
for default in own.iter().chain([&beside, &alone]) {
|
||||
let mut workspace = super::Workspace::new(saved.clone());
|
||||
// A file written while the canvas could still be lost.
|
||||
if let Ok(location) = default.location(&s("canvas")) {
|
||||
workspace.hidden.push((s("canvas"), location));
|
||||
}
|
||||
for mut workspace in [super::Workspace::new(saved.clone()), workspace] {
|
||||
workspace.reconcile(|_| true, permissions, &super::Workspace::new(default.clone()));
|
||||
workspace.validate().unwrap_or_else(|e| panic!("{app}{pointer}: {e}"));
|
||||
assert!(workspace.layout.contains(&s("canvas")), "{app}{pointer}: {:?}", workspace.layout);
|
||||
assert!(workspace.hidden.iter().all(|(p, _)| p != "canvas"), "{app}{pointer}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_placement_splits_the_part_between_the_docks_or_the_root() {
|
||||
// Dock layout: a floating window lands under the frames, beside the end dock.
|
||||
let mut layout = docked();
|
||||
layout.apply(Action::MoveWindow { panel: 6, to: Target::At { anchor: 1, placement: Placement::Edge(Zone::Bottom) } }).unwrap();
|
||||
let Some(Node::Split { first, second, .. }) = &layout.root else { panic!("{layout:?}") };
|
||||
assert!(matches!(&**second, Node::Dock { .. }));
|
||||
let Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(size), second: bottom, .. } = &**first else { panic!("{first:?}") };
|
||||
assert_eq!(*size, 0.75);
|
||||
assert_eq!(**bottom, tabs(&[6, 7, 8], 1));
|
||||
assert!(layout.floating.is_empty());
|
||||
|
||||
// Frame layout: one panel takes the whole left edge.
|
||||
let mut frames = Layout { root: Some(hsplit(SplitSize::Ratio(0.5), tabs(&[1], 0), tabs(&[2, 3], 0))), floating: Vec::new() };
|
||||
frames.apply(Action::Move { panel: 3, anchor: 1, placement: Placement::Edge(Zone::Left) }).unwrap();
|
||||
let Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(size), first, .. }) = &frames.root else { panic!() };
|
||||
assert_eq!((*size, &**first), (0.25, &tabs(&[3], 0)));
|
||||
|
||||
let before = frames.clone();
|
||||
assert_eq!(frames.apply(Action::Move { panel: 2, anchor: 1, placement: Placement::Edge(Zone::Center) }), Err(DockError::InvalidPlacement));
|
||||
assert_eq!(frames, before);
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
//! [D] Docks: side docks of columns, each a column bar above stacked groups.
|
||||
//!
|
||||
//! Columns run from the window edge inwards. Every column's inner edge resizes it; the last
|
||||
//! column's inner edge is the dock's inner edge. Behavior follows VectorCraft `floating.rs`
|
||||
//! (column layout, drop geometry) and PhotoCraft `dock.rs` (group heights).
|
||||
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2};
|
||||
|
||||
use super::{GroupKind, Renderer, RowItem, row_drag, row_range};
|
||||
use crate::docking::{
|
||||
Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Placement, Side, Target,
|
||||
dock_model::Unit,
|
||||
targets::{DockDrop, DockTarget, column_edge, horizontal_line, resolve_dock, usable, vertical_line},
|
||||
};
|
||||
use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis};
|
||||
|
||||
/// Width of the »/« button at the outer end of a column bar.
|
||||
const COLLAPSE_WIDTH: f32 = 18.0;
|
||||
|
||||
/// The physical window edge a dock sits on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(in crate::docking) enum Edge {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// `Start` is the left edge in a left-to-right layout and the right edge in a right-to-left one.
|
||||
pub(in crate::docking) fn edge_of(side: Side, right_to_left: bool) -> Edge {
|
||||
match (side, right_to_left) {
|
||||
(Side::Start, false) | (Side::End, true) => Edge::Left,
|
||||
(Side::Start, true) | (Side::End, false) => Edge::Right,
|
||||
}
|
||||
}
|
||||
|
||||
fn side_at(edge: Edge, right_to_left: bool) -> Side {
|
||||
match (edge, right_to_left) {
|
||||
(Edge::Left, false) | (Edge::Right, true) => Side::Start,
|
||||
(Edge::Left, true) | (Edge::Right, false) => Side::End,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rects of a dock beside `other` in `rect`, and the widest the dock may get.
|
||||
pub(in crate::docking) fn dock_rects<P>(
|
||||
side: Side,
|
||||
columns: &[Column<P>],
|
||||
other: &Node<P>,
|
||||
rect: Rect,
|
||||
style: &DockStyle,
|
||||
content: &dyn crate::docking::DockContent<P>,
|
||||
) -> (Rect, Rect, f32) {
|
||||
let gap = style.gap;
|
||||
let room = (rect.width() - gap - super::node_limits(other, style, content).min.x).clamp(0.0, rect.width());
|
||||
let width = columns.iter().map(|c| column_width(c, style)).sum::<f32>().clamp(0.0, room);
|
||||
let (dock, rest) = match edge_of(side, style.right_to_left) {
|
||||
Edge::Left => (
|
||||
Rect::from_min_max(rect.min, pos2(rect.left() + width, rect.bottom())),
|
||||
Rect::from_min_max(pos2((rect.left() + width + gap).min(rect.right()), rect.top()), rect.max),
|
||||
),
|
||||
Edge::Right => (
|
||||
Rect::from_min_max(pos2(rect.right() - width, rect.top()), rect.max),
|
||||
Rect::from_min_max(rect.min, pos2((rect.right() - width - gap).max(rect.left()), rect.bottom())),
|
||||
),
|
||||
};
|
||||
(dock, rest, room)
|
||||
}
|
||||
|
||||
pub(in crate::docking) fn column_width<P>(column: &Column<P>, style: &DockStyle) -> f32 {
|
||||
if column.iconic { column.iconic_width.unwrap_or(style.iconic_width).clamp(style.iconic_width, style.iconic_max_width) } else { column.width }
|
||||
}
|
||||
|
||||
/// Heights of stacked groups in a column body `room` high. Each entry is (minimized, saved
|
||||
/// height, minimum). Minimized groups take `strip`, groups with a saved height keep it, and the
|
||||
/// rest share what is left; when every open group has a height, the last one takes the rest.
|
||||
/// Saved heights shrink towards their minimums before the column overflows and scrolls.
|
||||
pub(in crate::docking) fn group_heights(groups: &[(bool, Option<f32>, f32)], strip: f32, room: f32) -> Vec<f32> {
|
||||
let open: Vec<usize> = (0..groups.len()).filter(|i| groups.get(*i).is_some_and(|g| !g.0)).collect();
|
||||
let mut shared: Vec<usize> = open.iter().copied().filter(|i| groups.get(*i).is_some_and(|g| g.1.is_none_or(|h| !h.is_finite()))).collect();
|
||||
if shared.is_empty() {
|
||||
shared.extend(open.last());
|
||||
}
|
||||
let mut heights: Vec<f32> = groups
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (minimized, height, min))| {
|
||||
if *minimized {
|
||||
strip
|
||||
} else if shared.contains(&i) {
|
||||
0.0
|
||||
} else {
|
||||
height.unwrap_or(*min).max(*min)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mins: Vec<f32> = groups.iter().map(|g| if g.0 { strip } else { g.2 }).collect();
|
||||
let shared_min: f32 = shared.iter().filter_map(|i| mins.get(*i)).sum();
|
||||
let deficit = heights.iter().sum::<f32>() + shared_min - room;
|
||||
let slack: f32 = open.iter().filter(|i| !shared.contains(i)).filter_map(|i| Some(heights.get(*i)? - mins.get(*i)?)).sum();
|
||||
if deficit > 0.0 && slack > 0.0 {
|
||||
let take = deficit.min(slack) / slack;
|
||||
for i in open.iter().filter(|i| !shared.contains(i)) {
|
||||
if let (Some(height), Some(min)) = (heights.get_mut(*i), mins.get(*i)) {
|
||||
*height -= (*height - min) * take;
|
||||
}
|
||||
}
|
||||
}
|
||||
let free = (room - heights.iter().sum::<f32>()).max(0.0);
|
||||
let share = free / shared.len().max(1) as f32;
|
||||
for i in &shared {
|
||||
if let (Some(height), Some(min)) = (heights.get_mut(*i), mins.get(*i)) {
|
||||
*height = share.max(*min);
|
||||
}
|
||||
}
|
||||
heights
|
||||
}
|
||||
|
||||
/// Column widths that fit `room`. Each entry is (width, floor); a column with a floor shrinks
|
||||
/// in proportion, never below its floor, and one without keeps its width. A dock saved on a
|
||||
/// larger screen still fits, as far as the floors allow.
|
||||
pub(in crate::docking) fn fit_widths(columns: &[(f32, Option<f32>)], room: f32) -> Vec<f32> {
|
||||
let mut widths: Vec<f32> = columns.iter().map(|(w, _)| *w).collect();
|
||||
for _ in 0..columns.len() {
|
||||
let total: f32 = widths.iter().sum();
|
||||
if total <= room {
|
||||
break;
|
||||
}
|
||||
let flex: f32 = widths.iter().zip(columns).filter(|(w, (_, floor))| floor.is_some_and(|f| **w > f)).map(|(w, _)| *w).sum();
|
||||
if flex <= 0.0 {
|
||||
break;
|
||||
}
|
||||
let scale = ((room - (total - flex)) / flex).max(0.0);
|
||||
for (width, (_, floor)) in widths.iter_mut().zip(columns) {
|
||||
if let Some(floor) = *floor
|
||||
&& *width > floor
|
||||
{
|
||||
*width = (*width * scale).max(floor);
|
||||
}
|
||||
}
|
||||
}
|
||||
widths
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
/// A horizontal split with a dock child: the dock takes its columns' width on its physical
|
||||
/// edge, the sibling the rest. False when neither child is a dock.
|
||||
pub(super) fn dock_split(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
first: &Node<P>,
|
||||
second: &Node<P>,
|
||||
rect: Rect,
|
||||
path: &mut Vec<bool>,
|
||||
root: (&Node<P>, Rect),
|
||||
) -> bool {
|
||||
let (dock_first, side, columns, other) = match (first, second) {
|
||||
(Node::Dock { side, columns }, other) => (true, *side, columns, other),
|
||||
(other, Node::Dock { side, columns }) => (false, *side, columns, other),
|
||||
_ => return false,
|
||||
};
|
||||
let (dock, rest, room) = dock_rects(side, columns, other, rect, self.style, &*self.content);
|
||||
self.dock(ui, side, columns, dock, room);
|
||||
path.push(dock_first);
|
||||
self.node(ui, other, rest, path, root);
|
||||
path.pop();
|
||||
true
|
||||
}
|
||||
|
||||
/// One dock in `rect`, columns from its outer edge. `room` is the widest the dock may get.
|
||||
pub(super) fn dock(&mut self, ui: &mut Ui, side: Side, columns: &[Column<P>], rect: Rect, room: f32) {
|
||||
let edge = edge_of(side, self.style.right_to_left);
|
||||
let (outer, inward) = match edge {
|
||||
Edge::Left => (rect.left(), 1.0),
|
||||
Edge::Right => (rect.right(), -1.0),
|
||||
};
|
||||
if columns.is_empty() {
|
||||
let (band, line) = column_edge(outer, inward, rect.y_range());
|
||||
let band = band.union(Rect::from_x_y_ranges(
|
||||
outer.min(outer + inward * self.style.new_dock_band)..=outer.max(outer + inward * self.style.new_dock_band),
|
||||
rect.y_range(),
|
||||
));
|
||||
self.dock_targets.push(DockDrop { target: DockTarget::NewDock { side }, band, line });
|
||||
return;
|
||||
}
|
||||
if usable(rect) {
|
||||
ui.painter().rect_filled(rect, 0.0, self.style.background);
|
||||
}
|
||||
let bounds: Vec<(f32, f32)> =
|
||||
columns.iter().map(|c| if c.iconic { (self.style.iconic_width, self.style.iconic_max_width) } else { self.column_bounds(c) }).collect();
|
||||
let natural: Vec<(f32, Option<f32>)> =
|
||||
columns.iter().zip(&bounds).map(|(c, (lo, _))| (column_width(c, self.style), (!c.iconic).then_some(lo.max(1.0)))).collect();
|
||||
let widths = fit_widths(&natural, rect.width());
|
||||
let scaled = widths.iter().zip(&natural).any(|(w, (n, _))| w != n);
|
||||
let total: f32 = widths.iter().sum();
|
||||
let mut x = outer;
|
||||
let mut drawn = Vec::new();
|
||||
for (index, column) in columns.iter().enumerate() {
|
||||
let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { continue };
|
||||
let fitted = widths.get(index).copied().unwrap_or_default();
|
||||
let width = fitted.min((rect.width() - (x - outer).abs()).max(0.0));
|
||||
let inner = x + inward * width;
|
||||
let column_rect = Rect::from_x_y_ranges(x.min(inner)..=x.max(inner), rect.y_range());
|
||||
self.column(ui, column, first, column_rect, edge);
|
||||
if index == 0 {
|
||||
let (band, line) = column_edge(x, inward, rect.y_range());
|
||||
self.dock_targets.push(DockDrop { target: DockTarget::ColumnEdge { anchor: first.clone(), after: false }, band, line });
|
||||
}
|
||||
let (band, line) = column_edge(inner, -inward, rect.y_range());
|
||||
self.dock_targets.push(DockDrop { target: DockTarget::ColumnEdge { anchor: first.clone(), after: true }, band, line });
|
||||
drawn.push((index, column, first, width, inner));
|
||||
x = inner;
|
||||
}
|
||||
// Registered after the columns, so the narrow hit areas win at the edges.
|
||||
for (index, column, first, width, inner) in drawn {
|
||||
if width < 1.0 {
|
||||
continue;
|
||||
}
|
||||
let others = total - widths.get(index).copied().unwrap_or_default();
|
||||
let (lo, hi) = bounds.get(index).copied().unwrap_or_default();
|
||||
let hi = hi.min(room - others).max(lo.min(room - others).max(0.0));
|
||||
let lo = lo.min(hi);
|
||||
let divider = Rect::from_x_y_ranges((inner - 1.0)..=(inner + 1.0), rect.y_range());
|
||||
let response = ResizeHandle::new(
|
||||
self.id.with(("column-resize", Some(first))),
|
||||
SplitAxis::Horizontal,
|
||||
divider,
|
||||
&self.style.resize_label,
|
||||
self.handle_style(),
|
||||
)
|
||||
.value(width, lo..=hi)
|
||||
.reversed(inward < 0.0)
|
||||
.show(ui);
|
||||
self.register_interaction(ui.ctx(), response.response.id);
|
||||
let next = (width + inward * response.delta).clamp(lo, hi);
|
||||
if response.delta != 0.0 && next != width && next > 0.0 {
|
||||
self.output.actions.push(if column.iconic {
|
||||
Action::ResizeIconic { panel: first.clone(), width: Some(next) }
|
||||
} else {
|
||||
Action::ResizeColumn { panel: first.clone(), width: next }
|
||||
});
|
||||
// A dock shrunk to fit keeps the widths it was drawn at, so the resized column
|
||||
// follows the pointer instead of being scaled again.
|
||||
if scaled {
|
||||
for (other, (column, width)) in columns.iter().zip(&widths).enumerate() {
|
||||
let first = column.groups.first().and_then(|g| g.panels.first());
|
||||
if let Some(first) = first.filter(|_| other != index && !column.iconic && *width > 0.0) {
|
||||
self.output.actions.push(Action::ResizeColumn { panel: first.clone(), width: *width });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_style(&self) -> ResizeHandleStyle {
|
||||
ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }
|
||||
}
|
||||
|
||||
/// Width bounds of an expanded column from its panels' limits.
|
||||
fn column_bounds(&self, column: &Column<P>) -> (f32, f32) {
|
||||
let mut lo = self.style.min_pane;
|
||||
let mut hi = f32::INFINITY;
|
||||
for panel in column.groups.iter().flat_map(|g| g.panels.iter()) {
|
||||
let limits = self.limits(panel);
|
||||
lo = lo.max(limits.min.x);
|
||||
hi = hi.min(limits.max.x);
|
||||
}
|
||||
(lo, hi.max(lo))
|
||||
}
|
||||
|
||||
/// Least height of an open group: its strip and the tallest minimum of its panels.
|
||||
fn group_min(&self, group: &Group<P>) -> f32 {
|
||||
let body = group.panels.iter().map(|p| self.limits(p).min.y).fold(self.style.min_pane, f32::max);
|
||||
self.style.tab_height + body
|
||||
}
|
||||
|
||||
fn column(&mut self, ui: &mut Ui, column: &Column<P>, first: &P, rect: Rect, edge: Edge) {
|
||||
if !usable(rect) {
|
||||
return;
|
||||
}
|
||||
self.record_column_float(column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect(), rect);
|
||||
let bar = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.column_bar_height).min(rect.bottom())));
|
||||
self.column_bar(ui, column, first, bar, rect, edge);
|
||||
let body = Rect::from_min_max(pos2(rect.left(), bar.bottom()), rect.max);
|
||||
if column.iconic && usable(body) {
|
||||
self.iconic_column(ui, column, body, edge);
|
||||
}
|
||||
if column.iconic || !usable(body) {
|
||||
ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside);
|
||||
return;
|
||||
}
|
||||
let sizes: Vec<_> = column.groups.iter().map(|g| (g.minimized, g.height, self.group_min(g))).collect();
|
||||
let heights = group_heights(&sizes, self.style.tab_height, body.height());
|
||||
let total: f32 = heights.iter().sum();
|
||||
let start = self.targets.len();
|
||||
if total > body.height() + 0.5 {
|
||||
let mut child =
|
||||
ui.new_child(UiBuilder::new().id_salt(("dock-column", first)).max_rect(body).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
child.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt(self.id.with(("column-scroll", first)))
|
||||
.auto_shrink([false, false])
|
||||
.scroll_source(egui::scroll_area::ScrollSource::SCROLL_BAR | egui::scroll_area::ScrollSource::MOUSE_WHEEL)
|
||||
.show(&mut child, |ui| {
|
||||
let (content, _) = ui.allocate_exact_size(vec2(ui.available_width(), total), Sense::hover());
|
||||
self.column_groups(ui, column, &heights, content, body);
|
||||
});
|
||||
} else {
|
||||
self.column_groups(ui, column, &heights, body, body);
|
||||
}
|
||||
// A group scrolled out of view takes nothing.
|
||||
for target in self.targets.iter_mut().skip(start) {
|
||||
target.rect = target.rect.intersect(body);
|
||||
target.tab_strip = target.tab_strip.map(|strip| strip.intersect(body));
|
||||
for (_, tab) in &mut target.tabs {
|
||||
*tab = tab.intersect(body);
|
||||
}
|
||||
}
|
||||
ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// Groups top to bottom in `area` (the scrolled content when the column scrolls), their
|
||||
/// seams and bands clipped to the visible `view`, and the height dividers.
|
||||
fn column_groups(&mut self, ui: &mut Ui, column: &Column<P>, heights: &[f32], area: Rect, view: Rect) {
|
||||
let mut top = area.top();
|
||||
let mut rects = Vec::new();
|
||||
for (group, height) in column.groups.iter().zip(heights) {
|
||||
let rect = Rect::from_min_max(pos2(area.left(), top), pos2(area.right(), top + height));
|
||||
self.group(ui, &group.panels, group.active, group.minimized, rect, GroupKind::Dock);
|
||||
rects.push(rect);
|
||||
top += height;
|
||||
}
|
||||
let xs = view.x_range();
|
||||
let half = self.style.seam_band * 0.5;
|
||||
let push = |targets: &mut Vec<DockDrop<P>>, target: DockTarget<P>, band: Rect, line: Rect| {
|
||||
let band = band.intersect(view);
|
||||
if usable(band) {
|
||||
targets.push(DockDrop { target, band, line: line.intersect(view.expand(2.0)) });
|
||||
}
|
||||
};
|
||||
let mut previous: Option<&P> = None;
|
||||
for (group, rect) in column.groups.iter().zip(&rects) {
|
||||
let Some(anchor) = group.panels.first() else { continue };
|
||||
if let Some(above) = previous {
|
||||
let band = Rect::from_x_y_ranges(xs, (rect.top() - half)..=(rect.top() + half));
|
||||
push(&mut self.dock_targets, DockTarget::Seam { anchor: above.clone() }, band, horizontal_line(rect.top(), xs));
|
||||
}
|
||||
if !group.minimized {
|
||||
let body = Rect::from_min_max(pos2(rect.left(), (rect.top() + self.style.tab_height).min(rect.bottom())), rect.max);
|
||||
let quarter = body.height() * 0.25;
|
||||
let upper = Rect::from_x_y_ranges(xs, body.top()..=(body.top() + quarter));
|
||||
let lower = Rect::from_x_y_ranges(xs, (body.bottom() - quarter)..=body.bottom());
|
||||
push(&mut self.dock_targets, DockTarget::GroupBand { anchor: anchor.clone(), below: false }, upper, horizontal_line(rect.top(), xs));
|
||||
push(
|
||||
&mut self.dock_targets,
|
||||
DockTarget::GroupBand { anchor: anchor.clone(), below: true },
|
||||
lower,
|
||||
horizontal_line(rect.bottom(), xs),
|
||||
);
|
||||
}
|
||||
previous = Some(anchor);
|
||||
}
|
||||
// The room under the last group, when every group is minimized, stacks below it.
|
||||
if let Some(last) = previous
|
||||
&& top < view.bottom()
|
||||
{
|
||||
let band = Rect::from_x_y_ranges(xs, top..=view.bottom());
|
||||
push(&mut self.dock_targets, DockTarget::GroupBand { anchor: last.clone(), below: true }, band, horizontal_line(top, xs));
|
||||
}
|
||||
// Height dividers between an open group and the next open one, after the groups so
|
||||
// their hit areas win at the boundary. The heights of the groups a drag changes are
|
||||
// saved: the upper group, and the lower groups that give way in turn, or the reverse.
|
||||
let open: Vec<usize> = (0..column.groups.len()).filter(|i| column.groups.get(*i).is_some_and(|g| !g.minimized)).collect();
|
||||
let row: Vec<RowItem> = open
|
||||
.iter()
|
||||
.filter_map(|i| Some(RowItem { size: *heights.get(*i)?, min: self.group_min(column.groups.get(*i)?), max: f32::INFINITY }))
|
||||
.collect();
|
||||
for (index, pair) in open.windows(2).enumerate() {
|
||||
let &[i, _] = pair else { continue };
|
||||
let (Some(upper), Some(rect), Some(a)) = (column.groups.get(i), rects.get(i), heights.get(i)) else { continue };
|
||||
let Some(first) = upper.panels.first() else { continue };
|
||||
let (lo, hi) = row_range(&row, index);
|
||||
let divider = Rect::from_x_y_ranges(rect.x_range(), (rect.bottom() - 1.0)..=(rect.bottom() + 1.0));
|
||||
let response = ResizeHandle::new(
|
||||
self.id.with(("group-resize", Some(first))),
|
||||
SplitAxis::Vertical,
|
||||
divider,
|
||||
&self.style.resize_label,
|
||||
self.handle_style(),
|
||||
)
|
||||
.value(*a, (a + lo)..=(a + hi))
|
||||
.show(ui);
|
||||
self.register_interaction(ui.ctx(), response.response.id);
|
||||
if response.delta == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for ((group, item), next) in open.iter().filter_map(|g| column.groups.get(*g)).zip(&row).zip(row_drag(&row, index, response.delta)) {
|
||||
if let Some(panel) = group.panels.first().filter(|_| next != item.size) {
|
||||
self.output.actions.push(Action::ResizeGroup { panel: panel.clone(), height: Some(next) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The column bar: the »/« button at its outer end, the rest drags the column (S6),
|
||||
/// toggles iconic on double-click (M2) and opens the column menu (U1).
|
||||
fn column_bar(&mut self, ui: &mut Ui, column: &Column<P>, first: &P, bar: Rect, rect: Rect, edge: Edge) {
|
||||
ui.painter().rect_filled(bar, 0.0, self.style.tab_background);
|
||||
let width = COLLAPSE_WIDTH.min(bar.width());
|
||||
let (button, grip) = match edge {
|
||||
Edge::Left => (
|
||||
Rect::from_min_max(bar.min, pos2(bar.left() + width, bar.bottom())),
|
||||
Rect::from_min_max(pos2(bar.left() + width, bar.top()), bar.max),
|
||||
),
|
||||
Edge::Right => (
|
||||
Rect::from_min_max(pos2(bar.right() - width, bar.top()), bar.max),
|
||||
Rect::from_min_max(bar.min, pos2(bar.right() - width, bar.bottom())),
|
||||
),
|
||||
};
|
||||
let label = if column.iconic { self.style.expand_panels_label.clone() } else { self.style.collapse_to_icons_label.clone() };
|
||||
if usable(button) {
|
||||
let response = ui.interact(button, self.id.with(("column-collapse", Some(first))), Sense::click());
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
let button_label = if column.iconic { &self.style.expand_column_label } else { &self.style.collapse_column_label };
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), button_label));
|
||||
// The arrows point where the column goes: towards the window edge when it collapses.
|
||||
let glyph = if (edge == Edge::Left) != column.iconic { "«" } else { "»" };
|
||||
let color = if response.hovered() || response.has_focus() { self.style.text } else { self.style.inactive_text };
|
||||
ui.painter().with_clip_rect(button).text(button.center(), egui::Align2::CENTER_CENTER, glyph, self.style.font.clone(), color);
|
||||
if response.clicked() {
|
||||
self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic });
|
||||
}
|
||||
}
|
||||
if !usable(grip) {
|
||||
return;
|
||||
}
|
||||
let movable = column.groups.iter().flat_map(|g| g.panels.iter()).all(|p| self.permissions(p).movable);
|
||||
let response = ui.interact(grip, self.id.with(("column-bar", Some(first))), Sense::click_and_drag());
|
||||
let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response };
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_column_label));
|
||||
if movable && response.drag_started() {
|
||||
let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center());
|
||||
let drag = GroupDrag {
|
||||
panel: first.clone(),
|
||||
original: [rect.left(), rect.top(), rect.width(), rect.height()],
|
||||
gesture: GroupGesture::Column,
|
||||
members: column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect(),
|
||||
origin,
|
||||
source: rect,
|
||||
};
|
||||
ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag));
|
||||
}
|
||||
if response.double_clicked() {
|
||||
self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic });
|
||||
}
|
||||
if response.has_focus() || response.hovered() {
|
||||
ui.painter().with_clip_rect(grip).rect_stroke(
|
||||
grip.shrink(1.0),
|
||||
0.0,
|
||||
Stroke::new(1.0, self.style.accent.gamma_multiply(0.5)),
|
||||
StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
let keyboard = response.has_focus() && ui.input(|i| i.key_pressed(Key::Enter) || i.key_pressed(Key::Space));
|
||||
let command = if response.secondary_clicked() || keyboard {
|
||||
Some(egui::SetOpenCommand::Bool(true))
|
||||
} else if response.clicked() {
|
||||
Some(egui::SetOpenCommand::Bool(false))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
egui::Popup::menu(&response).open_memory(command).show(|ui| {
|
||||
if self.menu_action(ui, &label) {
|
||||
self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic });
|
||||
}
|
||||
if self.auto_collapse_item(ui) {
|
||||
self.output.events.push(DockEvent::ToggleAutoCollapse);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a floating window drawn this frame (other than the one following the pointer)
|
||||
/// or a host overlay covers `pointer`. Covered dock targets take nothing.
|
||||
fn dock_covered(&self, pointer: Pos2, moving: Option<&P>) -> bool {
|
||||
self.blockers.iter().any(|r| r.contains(pointer))
|
||||
|| self.iconic.covers(pointer)
|
||||
|| self.frame.windows.iter().any(|window| window.window.contains(pointer) && !moving.is_some_and(|p| window.members.contains(p)))
|
||||
}
|
||||
|
||||
/// Dock targets, with the new-dock bands along the docked area's left and right edges that
|
||||
/// have no dock yet.
|
||||
fn dock_candidates(&self) -> Vec<DockDrop<P>> {
|
||||
let mut candidates = self.dock_targets.clone();
|
||||
if !self.style.new_dock_zones || !usable(self.workspace) {
|
||||
return candidates;
|
||||
}
|
||||
let rtl = self.style.right_to_left;
|
||||
let ys = self.workspace.y_range();
|
||||
for edge in [Edge::Left, Edge::Right] {
|
||||
let side = side_at(edge, rtl);
|
||||
if self.layout.dock_path(side).is_some() {
|
||||
continue;
|
||||
}
|
||||
let (x, inward) = match edge {
|
||||
Edge::Left => (self.workspace.left(), self.style.new_dock_band),
|
||||
Edge::Right => (self.workspace.right(), -self.style.new_dock_band),
|
||||
};
|
||||
let band = Rect::from_x_y_ranges(x.min(x + inward)..=x.max(x + inward), ys);
|
||||
let line = vertical_line(x + inward.signum() * 2.0, ys);
|
||||
candidates.push(DockDrop { target: DockTarget::NewDock { side }, band, line });
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// The dock target a whole group or column drag would take at `pointer`, with the action
|
||||
/// and its line. A target that leaves the layout unchanged is a no-op: `None` action.
|
||||
pub(super) fn dock_group_proposal(&self, drag: &GroupDrag<P>, pointer: Pos2) -> Option<(Option<Action<P>>, Rect)> {
|
||||
let moving = (drag.gesture == GroupGesture::Window).then_some(&drag.panel);
|
||||
if self.dock_covered(pointer, moving) {
|
||||
return None;
|
||||
}
|
||||
let candidates = self.dock_candidates();
|
||||
let drop = resolve_dock(pointer, &candidates)?;
|
||||
let action = group_action(drag, drop.target.to());
|
||||
self.checked(action).map(|action| (action, drop.line))
|
||||
}
|
||||
|
||||
/// The dock target a single tab drag would take: a new group, column or dock of that panel.
|
||||
/// A panel alone in its group takes the group's state to a new dock; one that shares its
|
||||
/// group leaves the other tabs behind (P6).
|
||||
pub(super) fn dock_tab_proposal(&self, panel: &P, pointer: Pos2) -> Option<(Option<Action<P>>, Rect)> {
|
||||
if self.dock_covered(pointer, None) {
|
||||
return None;
|
||||
}
|
||||
let candidates = self.dock_candidates();
|
||||
let drop = resolve_dock(pointer, &candidates)?;
|
||||
let action = match drop.target.to() {
|
||||
// A target named by the dragged panel is its own group or column: another panel
|
||||
// there names the same one. With none, the drop leaves the panel where it is.
|
||||
Target::At { anchor, placement } if &anchor == panel => {
|
||||
let unit = if matches!(placement, Placement::Column { .. }) { Unit::Column } else { Unit::Group };
|
||||
match self.layout.members(panel, unit).ok()?.into_iter().find(|p| p != panel) {
|
||||
Some(anchor) => Action::Move { panel: panel.clone(), anchor, placement },
|
||||
None => return Some((None, drop.line)),
|
||||
}
|
||||
}
|
||||
Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement },
|
||||
to @ Target::NewDock { .. } if self.place(panel).and_then(|place| self.layout.group(place)).is_some_and(|g| g.panels.len() == 1) => {
|
||||
Action::MoveGroup { panel: panel.clone(), to }
|
||||
}
|
||||
to @ Target::NewDock { .. } => Action::MovePanel { panel: panel.clone(), to },
|
||||
Target::Float { .. } => return None,
|
||||
};
|
||||
self.checked(action).map(|action| (action, drop.line))
|
||||
}
|
||||
|
||||
/// `Some(None)` when the action is valid but changes nothing, `None` when it is invalid.
|
||||
fn checked(&self, action: Action<P>) -> Option<Option<Action<P>>> {
|
||||
let mut candidate = self.layout.clone();
|
||||
candidate.apply_with_permissions(action.clone(), |p| self.permissions(p)).ok()?;
|
||||
Some((candidate != *self.layout).then_some(action))
|
||||
}
|
||||
|
||||
/// The insertion line of a dock target.
|
||||
pub(super) fn paint_dock_line(&self, ctx: &Context, line: Rect) {
|
||||
if usable(line) {
|
||||
let painter = self.preview_painter(ctx);
|
||||
self.iconic.outline(&painter, line, self.style);
|
||||
painter.rect_filled(line, 1.0, self.style.accent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The move a group gesture makes: the column for a column bar, every group for a window's
|
||||
/// title bar, else the group.
|
||||
pub(super) fn group_action<P: Clone>(drag: &GroupDrag<P>, to: Target<P>) -> Action<P> {
|
||||
match drag.gesture {
|
||||
GroupGesture::Column => Action::MoveColumn { panel: drag.panel.clone(), to },
|
||||
GroupGesture::Window => Action::MoveWindow { panel: drag.panel.clone(), to },
|
||||
GroupGesture::Group => Action::MoveGroup { panel: drag.panel.clone(), to },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Id, Key, Pos2, Rect, Ui, pos2, vec2};
|
||||
|
||||
use super::{GroupKind, Renderer, clamp_float, node_limits};
|
||||
use crate::docking::chrome::{ChromeStyle, FloatingFrame, RESIZE_BAND, TitleBar};
|
||||
use crate::docking::{Action, DropProposal, Floating, GroupDrag, GroupGesture, Node, PanelLimits, Placement, Target};
|
||||
|
||||
pub(in crate::docking) use crate::docking::chrome::RESIZE_HANDLES;
|
||||
|
||||
/// A floating window as drawn: what covers the layout behind it.
|
||||
pub(in crate::docking) struct WindowHit<P> {
|
||||
pub(super) window: Rect,
|
||||
pub(super) members: Vec<P>,
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
pub(in crate::docking) fn floating(&mut self, ctx: &Context, windows: &[Floating<P>]) {
|
||||
let screen = self.float_bounds;
|
||||
if !crate::docking::targets::usable(screen) {
|
||||
return;
|
||||
}
|
||||
let layers = ctx.memory(|memory| memory.layer_ids().collect::<Vec<_>>());
|
||||
let mut windows: Vec<_> = windows.iter().collect();
|
||||
windows.sort_by_key(|window| {
|
||||
let id = window.panels().next().map(|panel| self.id.with(("floating", panel)));
|
||||
layers.iter().position(|layer| Some(layer.id) == id).unwrap_or(usize::MAX)
|
||||
});
|
||||
#[cfg(feature = "native-windows")]
|
||||
let windows = self.native_windows(ctx, windows);
|
||||
for window in windows {
|
||||
self.floating_window(ctx, window, screen);
|
||||
}
|
||||
}
|
||||
|
||||
/// Size limits of a floating window: its title bar and, unless it is minimized, its tree.
|
||||
pub(super) fn window_limits(&self, window: &Floating<P>) -> PanelLimits {
|
||||
let chrome = self.window_chrome(window);
|
||||
let tree = node_limits(&window.root, self.style, &*self.content);
|
||||
let body = match (&window.root, window.minimized) {
|
||||
(Node::Tabs { .. }, true) => (self.style.tab_height, self.style.tab_height),
|
||||
(_, true) => (0.0, 0.0),
|
||||
(_, false) => (tree.min.y, tree.max.y),
|
||||
};
|
||||
let min = vec2(tree.min.x, chrome + body.0).min(vec2(1_000_000.0, 1_000_000.0));
|
||||
PanelLimits { min, max: vec2(tree.max.x, chrome + body.1).max(min).min(vec2(1_000_000.0, 1_000_000.0)) }
|
||||
}
|
||||
|
||||
/// The title bar and, for a movable (resizable) window, the resize band above it.
|
||||
fn window_chrome(&self, window: &Floating<P>) -> f32 {
|
||||
let band = if window.panels().all(|panel| self.permissions(panel).movable) { RESIZE_BAND } else { 0.0 };
|
||||
band + self.style.title_height
|
||||
}
|
||||
|
||||
/// Where a floating window draws its tree, as [`Self::floating_window`] places it.
|
||||
pub(super) fn window_body(&self, window: &Floating<P>) -> Rect {
|
||||
let [x, y, width, height] = window.rect;
|
||||
let limits = self.window_limits(window);
|
||||
let size = vec2(width, height).max(limits.min).min(limits.max);
|
||||
let rect = crate::docking::chrome::clamp(Rect::from_min_size(pos2(x, y), size), self.float_bounds);
|
||||
Rect::from_min_max(pos2(rect.left(), (rect.top() + self.window_chrome(window)).min(rect.bottom())), rect.max)
|
||||
}
|
||||
|
||||
fn floating_window(&mut self, ctx: &Context, window: &Floating<P>, screen: Rect) {
|
||||
let Some(first) = window.panels().next() else { return };
|
||||
let [x, y, width, height] = window.rect;
|
||||
let limits = self.window_limits(window);
|
||||
let size = vec2(width, height).max(limits.min).min(limits.max);
|
||||
let rect = crate::docking::chrome::clamp(Rect::from_min_size(pos2(x, y), size), screen);
|
||||
let id = self.id.with(("floating", first));
|
||||
if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) {
|
||||
ctx.move_to_top(FloatingFrame::layer(id));
|
||||
}
|
||||
let movable = window.panels().all(|panel| self.permissions(panel).movable);
|
||||
let style = ChromeStyle::from_dock(self.style);
|
||||
let resize_label = self.style.resize_window_label.clone();
|
||||
let response = FloatingFrame::new(id, rect).bounds(screen).limits(limits).resizable(movable).resize_label(&resize_label).show(
|
||||
ctx,
|
||||
&style,
|
||||
|ui, contents| self.window_contents(ui, window, contents, rect, &style),
|
||||
);
|
||||
for handle in &response.handles {
|
||||
self.register_interaction(ctx, handle.id);
|
||||
}
|
||||
let down = ctx.input(|i| i.pointer.primary_down());
|
||||
ctx.data_mut(|data| {
|
||||
let key = self.id.with("pointer-resize");
|
||||
if let Some(started) = response.resize_started {
|
||||
data.insert_temp(key, started);
|
||||
} else if !down && data.get_temp::<Id>(key).is_some_and(|id| response.handles.iter().any(|h| h.id == id)) {
|
||||
data.remove::<Id>(key);
|
||||
}
|
||||
});
|
||||
if let Some(resized) = response.resized {
|
||||
self.output
|
||||
.actions
|
||||
.push(Action::MoveFloating { panel: first.clone(), rect: [resized.left(), resized.top(), resized.width(), resized.height()] });
|
||||
}
|
||||
}
|
||||
|
||||
/// The title bar, then the window's tree below it, in `contents`. Moves carry the whole
|
||||
/// `frame`, resize band included.
|
||||
fn window_contents(&mut self, ui: &mut Ui, window: &Floating<P>, contents: Rect, frame: Rect, style: &ChromeStyle) {
|
||||
let title = Rect::from_min_max(contents.min, pos2(contents.right(), (contents.top() + self.style.title_height).min(contents.bottom())));
|
||||
self.title_bar(ui, window, title, frame, style);
|
||||
let body = Rect::from_min_max(pos2(contents.left(), title.bottom()), contents.max);
|
||||
self.floating_body(ui, window, body, frame);
|
||||
}
|
||||
|
||||
/// A floating window's tree in `body`, like the docked layout's: splits, groups, dividers
|
||||
/// and intersections. A minimized window shows the tab strip of its only group, or nothing.
|
||||
pub(super) fn floating_body(&mut self, ui: &mut Ui, window: &Floating<P>, body: Rect, frame: Rect) {
|
||||
let Some(key) = window.panels().next().cloned() else { return };
|
||||
match (&window.root, window.minimized) {
|
||||
(Node::Tabs { panels, active }, true) => self.group(ui, panels, *active, true, body, GroupKind::Floating { window: frame }),
|
||||
(_, true) => {}
|
||||
(root, false) => {
|
||||
let outer = self.tree.replace((key, frame));
|
||||
self.node(ui, root, body, &mut Vec::new(), (root, body));
|
||||
self.tree = outer;
|
||||
}
|
||||
}
|
||||
self.frame.windows.push(WindowHit { window: frame, members: window.panels().cloned().collect() });
|
||||
}
|
||||
|
||||
/// Drag moves the whole window live, double-click minimizes or expands it, × closes every
|
||||
/// panel in it.
|
||||
fn title_bar(&mut self, ui: &mut Ui, window: &Floating<P>, title: Rect, rect: Rect, style: &ChromeStyle) {
|
||||
let Some(first) = window.panels().next() else { return };
|
||||
let movable = window.panels().all(|p| self.permissions(p).movable);
|
||||
let closable = self.style.close_button && window.panels().all(|p| self.permissions(p).closable);
|
||||
let (move_label, close_label) = (self.style.move_window_label.clone(), self.style.close_window_label.clone());
|
||||
let mut bar = TitleBar::new(self.id.with(("move-group", Some(first))), &move_label).movable(movable);
|
||||
if closable {
|
||||
bar = bar.close(&close_label);
|
||||
}
|
||||
let response = bar.show(ui, title, style);
|
||||
self.register_interaction(ui.ctx(), response.bar.id);
|
||||
if movable && response.bar.drag_started() {
|
||||
let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(title.center());
|
||||
let drag = GroupDrag {
|
||||
panel: first.clone(),
|
||||
original: [rect.left(), rect.top(), rect.width(), rect.height()],
|
||||
gesture: GroupGesture::Window,
|
||||
members: window.panels().cloned().collect(),
|
||||
origin,
|
||||
source: rect,
|
||||
};
|
||||
ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag));
|
||||
}
|
||||
if movable
|
||||
&& response.bar.dragged()
|
||||
&& let Some(drag) = ui.ctx().data(|d| d.get_temp::<GroupDrag<P>>(self.id.with("group-drag")))
|
||||
&& drag.gesture == GroupGesture::Window
|
||||
&& let Some(pointer) = ui.ctx().pointer_interact_pos()
|
||||
&& !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused)
|
||||
{
|
||||
// From the press origin, so fractional pointer steps do not accumulate rounding.
|
||||
let moved = clamp_float(drag.source.translate(pointer - drag.origin), self.float_bounds);
|
||||
self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] });
|
||||
}
|
||||
if response.bar.double_clicked() {
|
||||
self.output.actions.push(Action::SetMinimized { panel: first.clone(), minimized: !window.minimized });
|
||||
}
|
||||
if let Some(close) = response.close {
|
||||
self.register_interaction(ui.ctx(), close.id);
|
||||
if close.clicked() {
|
||||
self.output.actions.push(Action::CloseWindow { panel: first.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The title bar of a floating window occludes what lies behind it: a no-op proposal. Then
|
||||
/// the layout's outer edge (P8). None leaves the pointer to the group targets. `skip_own`
|
||||
/// looks through the window holding `members` (a window moving live).
|
||||
pub(super) fn extra_proposal(&self, members: &[P], pointer: Pos2, skip_own: bool) -> Option<DropProposal<P>> {
|
||||
let own = |panels: &[P]| panels.iter().any(|p| members.contains(p));
|
||||
let window = self.frame.windows.iter().rev().find(|w| w.window.contains(pointer) && !(skip_own && own(&w.members)));
|
||||
if let Some(window) = window {
|
||||
let in_group = self.targets.iter().any(|t| t.rect.contains(pointer) && t.tabs.iter().any(|(p, _)| window.members.contains(p)));
|
||||
if in_group {
|
||||
return None;
|
||||
}
|
||||
let anchor = members.first()?.clone();
|
||||
return Some(DropProposal { anchor, placement: Placement::Tab { before: None }, preview: Rect::NOTHING, insertion: None, noop: true });
|
||||
}
|
||||
let (anchor, zone, preview) = self.edge_proposal(members, pointer)?;
|
||||
let lead = members.first()?.clone();
|
||||
let action = match members {
|
||||
[_] => Action::Move { panel: lead, anchor: anchor.clone(), placement: Placement::Edge(zone) },
|
||||
_ => Action::MoveGroup { panel: lead, to: Target::At { anchor: anchor.clone(), placement: Placement::Edge(zone) } },
|
||||
};
|
||||
if !self.leaves_room(action) {
|
||||
return None;
|
||||
}
|
||||
Some(DropProposal { anchor, placement: Placement::Edge(zone), preview, insertion: None, noop: false })
|
||||
}
|
||||
|
||||
/// What a group drag carries: the whole window rect for the only group of a floating
|
||||
/// window, so floating it again keeps the window's size; else the group's rect.
|
||||
pub(super) fn drag_source(&self, owner: &super::group::TabGroup<'_, P>) -> Rect {
|
||||
match owner.kind {
|
||||
GroupKind::Floating { window } if owner.panels.first().is_some_and(|p| self.whole_window(p)) => window,
|
||||
_ => owner.rect,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a double-click or the group menu minimizes `owner`: a dock group, or the only
|
||||
/// group of a floating window, which minimizes the window to that group's strip.
|
||||
pub(super) fn minimizes(&self, owner: &super::group::TabGroup<'_, P>) -> bool {
|
||||
match owner.kind {
|
||||
GroupKind::Dock => true,
|
||||
GroupKind::Floating { .. } => self.whole_window(owner.selected),
|
||||
GroupKind::Frame => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `panel`'s group is the whole tree of a floating window.
|
||||
pub(super) fn whole_window(&self, panel: &P) -> bool {
|
||||
matches!(self.place(panel), Some(crate::docking::dock_model::Place::Floating { path, .. }) if path.is_empty())
|
||||
}
|
||||
|
||||
/// Release of a title bar drag. The window already sits where it was dragged; a dock or
|
||||
/// group target docks or merges every group in it, else hosts get the release in
|
||||
/// `group_drop`.
|
||||
pub(super) fn drop_window(&mut self, drag: &GroupDrag<P>, pointer: Pos2, float_only: bool) {
|
||||
let float_only = float_only || !self.style.title_bar_docks;
|
||||
if !float_only && let Some((action, _)) = self.dock_group_proposal(drag, pointer) {
|
||||
self.output.actions.extend(action);
|
||||
return;
|
||||
}
|
||||
let proposal = if float_only { None } else { self.group_proposal(drag, pointer) };
|
||||
match proposal.filter(|p| !p.noop) {
|
||||
Some(proposal) => {
|
||||
let to = Target::At { anchor: proposal.anchor, placement: proposal.placement };
|
||||
self.output.actions.push(super::dock::group_action(drag, to));
|
||||
}
|
||||
None => self.output.group_drop = Some((drag.panel.clone(), pointer)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! What the split tree adds around the groups: Maximize Frame, the outer edge band, hidden
|
||||
//! panels, the float hint and the group menu tail.
|
||||
|
||||
use std::{borrow::Cow, collections::HashMap, fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Pos2, Rect, pos2, vec2};
|
||||
|
||||
use super::{GroupKind, Renderer, floating::WindowHit, group::TabGroup};
|
||||
use crate::docking::{
|
||||
Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Zone,
|
||||
dock_model::{Place, node_at},
|
||||
};
|
||||
|
||||
/// How far below the pointer the float hint sits, clear of the cursor.
|
||||
const HINT_OFFSET: f32 = 28.0;
|
||||
|
||||
/// What the renderer draws when it is not the layout itself, and the targets that depend on it.
|
||||
pub(in crate::docking) struct FrameState<P> {
|
||||
/// View path to layout path of each split, when the view is not the layout.
|
||||
paths: Option<HashMap<Vec<bool>, Vec<bool>>>,
|
||||
/// The same for each floating window's splits, by the window's first shown panel.
|
||||
window_paths: HashMap<P, HashMap<Vec<bool>, Vec<bool>>>,
|
||||
/// The view node whose rect is the outer edge area; none while a frame is maximized.
|
||||
edge_path: Option<Vec<bool>>,
|
||||
pub(super) edge: Option<Rect>,
|
||||
pub(super) maximized: Option<P>,
|
||||
/// Floating windows as drawn, back to front.
|
||||
pub(super) windows: Vec<WindowHit<P>>,
|
||||
}
|
||||
|
||||
/// The layout as shown: a maximized frame alone, and hidden panels left out.
|
||||
pub(in crate::docking) fn view<'a, P: Clone + Eq + Hash>(
|
||||
layout: &'a Layout<P>,
|
||||
maximized: Option<&P>,
|
||||
hide: HidePanels<'_, P>,
|
||||
content: &dyn DockContent<P>,
|
||||
) -> (Cow<'a, Layout<P>>, FrameState<P>) {
|
||||
let protected = |p: &P| content.permissions(p).is_protected();
|
||||
let hidden = |p: &P| match hide {
|
||||
HidePanels::None => false,
|
||||
HidePanels::All => !protected(p),
|
||||
HidePanels::Except(keep) => !protected(p) && !keep(p),
|
||||
};
|
||||
// Only a docked panel maximizes its frame.
|
||||
let maximized = maximized.and_then(|panel| match layout.place(panel)? {
|
||||
Place::Node(path) => Some((panel.clone(), path.clone(), layout.root.as_ref().and_then(|root| node_at(root, &path))?.clone())),
|
||||
place @ Place::Dock { .. } => {
|
||||
let group = layout.group(&place)?;
|
||||
Some((panel.clone(), path_of(&place), Node::Tabs { panels: group.panels.clone(), active: group.active }))
|
||||
}
|
||||
Place::Floating { .. } => None,
|
||||
});
|
||||
let mut state = FrameState { paths: None, window_paths: HashMap::new(), edge_path: None, edge: None, maximized: None, windows: Vec::new() };
|
||||
if maximized.is_none() && matches!(hide, HidePanels::None) {
|
||||
state.edge_path = Some(layout.edge_path());
|
||||
return (Cow::Borrowed(layout), state);
|
||||
}
|
||||
let mut paths = HashMap::new();
|
||||
let view = match maximized {
|
||||
Some((panel, path, node)) => {
|
||||
state.maximized = Some(panel);
|
||||
Layout { root: prune(&node, path, Vec::new(), &hidden, &mut paths), floating: Vec::new() }
|
||||
}
|
||||
None => {
|
||||
let root = layout.root.as_ref().and_then(|root| prune(root, Vec::new(), Vec::new(), &hidden, &mut paths));
|
||||
let mut floating = Vec::new();
|
||||
for window in &layout.floating {
|
||||
let mut paths = HashMap::new();
|
||||
let Some(root) = prune(&window.root, Vec::new(), Vec::new(), &hidden, &mut paths) else { continue };
|
||||
let shown = Floating { root, ..window.clone() };
|
||||
if let Some(key) = shown.panels().next() {
|
||||
state.window_paths.insert(key.clone(), paths);
|
||||
}
|
||||
floating.push(shown);
|
||||
}
|
||||
Layout { root, floating }
|
||||
}
|
||||
};
|
||||
if state.maximized.is_none() {
|
||||
state.edge_path = Some(view.edge_path());
|
||||
}
|
||||
state.paths = Some(paths);
|
||||
(Cow::Owned(view), state)
|
||||
}
|
||||
|
||||
fn path_of(place: &Place) -> Vec<bool> {
|
||||
match place {
|
||||
Place::Node(path) | Place::Dock { path, .. } => path.clone(),
|
||||
Place::Floating { .. } => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn visible<P>(node: &Node<P>, hidden: &dyn Fn(&P) -> bool) -> bool {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => visible(first, hidden) || visible(second, hidden),
|
||||
Node::Tabs { panels, .. } => panels.iter().any(|p| !hidden(p)),
|
||||
Node::Stack { entries } => entries.iter().any(|e| !hidden(&e.panel)),
|
||||
Node::Dock { columns, .. } => columns.iter().flat_map(|c| &c.groups).flat_map(|g| &g.panels).any(|p| !hidden(p)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `node` without hidden panels; a split with one visible side becomes that side. Records the
|
||||
/// layout path of every split kept.
|
||||
fn prune<P: Clone + PartialEq>(
|
||||
node: &Node<P>,
|
||||
path: Vec<bool>,
|
||||
at: Vec<bool>,
|
||||
hidden: &dyn Fn(&P) -> bool,
|
||||
paths: &mut HashMap<Vec<bool>, Vec<bool>>,
|
||||
) -> Option<Node<P>> {
|
||||
let child = |path: &[bool], side: bool| [path, &[side]].concat();
|
||||
match node {
|
||||
Node::Split { axis, size, first, second } => match (visible(first, hidden), visible(second, hidden)) {
|
||||
(true, true) => {
|
||||
let first = prune(first, child(&path, false), child(&at, false), hidden, paths)?;
|
||||
let second = prune(second, child(&path, true), child(&at, true), hidden, paths)?;
|
||||
paths.insert(at, path);
|
||||
Some(Node::Split { axis: *axis, size: *size, first: Box::new(first), second: Box::new(second) })
|
||||
}
|
||||
(true, false) => prune(first, child(&path, false), at, hidden, paths),
|
||||
(false, true) => prune(second, child(&path, true), at, hidden, paths),
|
||||
(false, false) => None,
|
||||
},
|
||||
Node::Tabs { panels, active } => {
|
||||
let group = prune_group(&Group::new(panels.clone(), *active), hidden)?;
|
||||
Some(Node::Tabs { panels: group.panels, active: group.active })
|
||||
}
|
||||
Node::Stack { entries } => {
|
||||
let entries: Vec<_> = entries.iter().filter(|e| !hidden(&e.panel)).cloned().collect();
|
||||
(!entries.is_empty()).then_some(Node::Stack { entries })
|
||||
}
|
||||
Node::Dock { side, columns } => {
|
||||
let columns: Vec<_> = columns
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let groups: Vec<_> = c.groups.iter().filter_map(|g| prune_group(g, hidden)).collect();
|
||||
(!groups.is_empty()).then(|| Column { groups, ..c.clone() })
|
||||
})
|
||||
.collect();
|
||||
(!columns.is_empty()).then_some(Node::Dock { side: *side, columns })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group without hidden panels; the selected panel stays selected when it is shown.
|
||||
fn prune_group<P: Clone + PartialEq>(group: &Group<P>, hidden: &dyn Fn(&P) -> bool) -> Option<Group<P>> {
|
||||
let selected = group.active_panel();
|
||||
let panels: Vec<P> = group.panels.iter().filter(|p| !hidden(p)).cloned().collect();
|
||||
let active = selected.and_then(|s| panels.iter().position(|p| p == s)).unwrap_or(0);
|
||||
(!panels.is_empty()).then(|| Group { panels, active, ..group.clone() })
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
pub(super) fn note_edge(&mut self, path: &[bool], rect: Rect) {
|
||||
if self.tree.is_none() && self.frame.edge_path.as_deref() == Some(path) {
|
||||
self.frame.edge = Some(rect);
|
||||
}
|
||||
}
|
||||
|
||||
/// The layout path of a split drawn at view path `path`, in the tree being drawn.
|
||||
pub(super) fn original_path(&self, path: &[bool]) -> Vec<bool> {
|
||||
let paths = match &self.tree {
|
||||
None => self.frame.paths.as_ref(),
|
||||
Some((key, _)) => self.frame.window_paths.get(key),
|
||||
};
|
||||
paths.and_then(|paths| paths.get(path).cloned()).unwrap_or_else(|| path.to_vec())
|
||||
}
|
||||
|
||||
/// The outer edge band under the pointer (P8): top and bottom, and left and right with
|
||||
/// [`crate::docking::DockStyle::side_edge_zones`]. Returns a docked anchor that is not
|
||||
/// moving, the zone and the preview of the new frame.
|
||||
pub(super) fn edge_proposal(&self, members: &[P], pointer: Pos2) -> Option<(P, Zone, Rect)> {
|
||||
let area = self.frame.edge.filter(|area| area.contains(pointer))?;
|
||||
let band = self.style.edge_band.min(area.width() / 4.0).min(area.height() / 4.0);
|
||||
let mut edges = vec![(pointer.y - area.top(), Zone::Top), (area.bottom() - pointer.y, Zone::Bottom)];
|
||||
if self.style.side_edge_zones {
|
||||
edges.extend([(pointer.x - area.left(), Zone::Left), (area.right() - pointer.x, Zone::Right)]);
|
||||
}
|
||||
let (distance, zone) = edges.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?;
|
||||
if distance > band {
|
||||
return None;
|
||||
}
|
||||
let anchor =
|
||||
self.layout.panels().into_iter().find(|p| !members.contains(p) && !matches!(self.place(p), Some(Place::Floating { .. }) | None))?.clone();
|
||||
let size = area.size() * 0.25;
|
||||
let preview = match zone {
|
||||
Zone::Left => Rect::from_min_size(area.min, vec2(size.x, area.height())),
|
||||
Zone::Right => Rect::from_min_max(pos2(area.right() - size.x, area.top()), area.max),
|
||||
Zone::Top => Rect::from_min_size(area.min, vec2(area.width(), size.y)),
|
||||
Zone::Bottom | Zone::Center => Rect::from_min_max(pos2(area.left(), area.bottom() - size.y), area.max),
|
||||
};
|
||||
Some((anchor, zone, preview))
|
||||
}
|
||||
|
||||
/// Under the pointer while a drag offers a docking target: which modifier floats the drop
|
||||
/// instead.
|
||||
pub(super) fn paint_float_hint(&self, ctx: &Context, pointer: Pos2) {
|
||||
if !self.style.float_hint || self.style.float_hint_label.is_empty() {
|
||||
return;
|
||||
}
|
||||
let key = if ctx.os() == egui::os::OperatingSystem::Mac { "⌘" } else { "Ctrl" };
|
||||
let painter = self.preview_painter(ctx);
|
||||
let galley = painter.layout_no_wrap(self.style.float_hint_label.replace("{key}", key), self.style.font.clone(), self.style.text);
|
||||
let rect = Rect::from_center_size(pointer + vec2(0.0, HINT_OFFSET), galley.size() + vec2(12.0, 6.0));
|
||||
let rect = crate::docking::chrome::clamp(rect, self.float_bounds);
|
||||
painter.rect(rect, 4.0, self.style.floating_background, egui::Stroke::new(1.0, self.style.accent), egui::StrokeKind::Inside);
|
||||
painter.galley(rect.center() - galley.size() * 0.5, galley, self.style.text);
|
||||
}
|
||||
|
||||
/// Ctrl/Cmd held when a split-tree tab drag starts: the drop floats (S9).
|
||||
pub(super) fn latch_undock(&self, ctx: &Context, kind: Option<GroupKind>) {
|
||||
let command = ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.mac_cmd);
|
||||
if self.style.command_press_floats && matches!(kind, Some(GroupKind::Frame | GroupKind::Floating { .. })) && command {
|
||||
ctx.data_mut(|d| {
|
||||
if let Some(drag) = d.get_temp::<crate::docking::Drag<P>>(self.id.with("drag")) {
|
||||
d.insert_temp(self.id.with("drag"), crate::docking::Drag { undock: true, ..drag });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu tail: Close Other Panels in Group and Maximize Frame when the style shows
|
||||
/// them, and Move Panel to New Window where native windows are available.
|
||||
pub(super) fn frame_items(&mut self, ui: &mut egui::Ui, owner: &TabGroup<'_, P>, panel: &P) {
|
||||
let others = owner.panels.iter().filter(|p| *p != panel).all(|p| self.permissions(p).closable);
|
||||
if self.style.close_others_item
|
||||
&& owner.panels.len() > 1
|
||||
&& others
|
||||
&& self.style.close_menu_items
|
||||
&& self.menu_action(ui, &self.style.close_others_label.clone())
|
||||
{
|
||||
self.output.actions.push(Action::CloseOthers { panel: panel.clone() });
|
||||
}
|
||||
if self.style.maximize_item && owner.kind == GroupKind::Frame {
|
||||
let restore = self.frame.maximized.as_ref().is_some_and(|m| owner.panels.contains(m));
|
||||
let label = if restore { self.style.restore_frame_label.clone() } else { self.style.maximize_label.clone() };
|
||||
if self.menu_action(ui, &label) {
|
||||
let panel = if restore { self.frame.maximized.clone().unwrap_or_else(|| panel.clone()) } else { panel.clone() };
|
||||
self.output.events.push(DockEvent::ToggleMaximize { panel });
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "native-windows")]
|
||||
self.new_window_item(ui, owner, panel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
use std::{fmt::Debug, hash::Hash, sync::Arc};
|
||||
|
||||
use egui::{Color32, Galley, Id, Key, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2};
|
||||
|
||||
use super::{Renderer, clamp_float, stripless};
|
||||
use crate::docking::{Action, DropTarget, GroupDrag, GroupGesture, Placement, Target, begin_drag, surface::TAB_PADDING};
|
||||
use crate::tabs;
|
||||
|
||||
/// Where a group is drawn. It decides the drop targets the group offers and its gestures.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(in crate::docking) enum GroupKind {
|
||||
/// A `Tabs` node of the split tree: side drops split it.
|
||||
Frame,
|
||||
/// A group in a dock column.
|
||||
Dock,
|
||||
/// A `Tabs` node of the floating window drawn at `window`: side drops split it.
|
||||
Floating { window: Rect },
|
||||
}
|
||||
|
||||
/// The group a tab belongs to, for its menu and minimize gestures.
|
||||
pub(super) struct TabGroup<'a, P> {
|
||||
pub(super) panels: &'a [P],
|
||||
pub(super) selected: &'a P,
|
||||
pub(super) minimized: bool,
|
||||
pub(super) kind: GroupKind,
|
||||
pub(super) rect: Rect,
|
||||
}
|
||||
|
||||
/// The top band of a strip that drags the whole group.
|
||||
const BORDER_BAND: f32 = 4.0;
|
||||
|
||||
/// Width of the "…" button that lists the panels a strip has no room for.
|
||||
const OVERFLOW_WIDTH: f32 = 22.0;
|
||||
|
||||
/// Points of smooth (trackpad) scrolling that make one wheel notch.
|
||||
const WHEEL_NOTCH: f32 = 40.0;
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, minimized: bool, rect: Rect, kind: GroupKind) {
|
||||
let Some(selected) = panels.get(active) else { return };
|
||||
self.record_float(panels, rect.size(), rect.size());
|
||||
let policy = self.permissions(selected);
|
||||
let splits = matches!(kind, GroupKind::Frame | GroupKind::Floating { .. }) && policy.accepts_splits;
|
||||
let rtl = self.style.right_to_left;
|
||||
if stripless(panels, &*self.content) {
|
||||
self.contents(ui, selected, rect);
|
||||
self.targets.push(DropTarget {
|
||||
anchor: selected.clone(),
|
||||
rect,
|
||||
tab_strip: None,
|
||||
tabs: vec![(selected.clone(), Rect::NOTHING)],
|
||||
allow_splits: splits,
|
||||
accepts_tabs: policy.accepts_tabs,
|
||||
right_to_left: rtl,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let movable = panels.iter().all(|p| self.permissions(p).movable);
|
||||
let strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom())));
|
||||
ui.painter().rect_filled(strip, 0.0, self.style.tab_background);
|
||||
let floating = matches!(kind, GroupKind::Floating { .. });
|
||||
// Laid out left to right, then mirrored in a right-to-left layout: tabs from the right
|
||||
// edge, the header (the host's ≡) at the left.
|
||||
let mirror = |r: Rect| {
|
||||
if rtl {
|
||||
Rect::from_x_y_ranges((strip.left() + strip.right() - r.right())..=(strip.left() + strip.right() - r.left()), r.y_range())
|
||||
} else {
|
||||
r
|
||||
}
|
||||
};
|
||||
let requested = self.content.group_header_width(panels, selected, floating, strip.width());
|
||||
let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 };
|
||||
if header_width > 0.0 {
|
||||
let header = mirror(Rect::from_min_max(pos2(strip.right() - header_width, strip.top()), strip.max));
|
||||
let mut child = ui.new_child(UiBuilder::new().id(self.id.with(("header", selected))).max_rect(header));
|
||||
child.set_clip_rect(header.intersect(ui.clip_rect()));
|
||||
self.content.group_header(&mut child, panels, selected, floating);
|
||||
// A press in the header focuses the shown panel, as a press on its tab does.
|
||||
if child.rect_contains_pointer(header) && child.input(|i| i.pointer.any_pressed()) {
|
||||
self.output.focused = Some(selected.clone());
|
||||
}
|
||||
}
|
||||
// The drag bar keeps its reserved width: tabs overflow before it narrows.
|
||||
let bar_width = self.style.drag_bar_width.clamp(0.0, (strip.width() - header_width).max(0.0));
|
||||
let tabs_width = (strip.width() - header_width - bar_width).max(0.0);
|
||||
let widths: Vec<f32> = panels
|
||||
.iter()
|
||||
.map(|p| {
|
||||
self.content
|
||||
.label(ui, p, &self.label_of(p), &self.style.font, self.style.text)
|
||||
.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, self.style.font.clone())
|
||||
.size()
|
||||
.x
|
||||
+ TAB_PADDING
|
||||
})
|
||||
.collect();
|
||||
// Tabs keep their full names; the rest go to the overflow menu. Only an active tab wider
|
||||
// than the strip is cut, with its name in a tooltip.
|
||||
let fit = tabs::fit_whole(&widths, active, tabs_width, OVERFLOW_WIDTH);
|
||||
let owner = TabGroup { panels, selected, minimized, kind, rect };
|
||||
let mut x = strip.left();
|
||||
let mut shown = Vec::new();
|
||||
for (index, width) in &fit.shown {
|
||||
let Some(panel) = panels.get(*index) else { continue };
|
||||
let tab = mirror(Rect::from_min_size(pos2(x, strip.top()), vec2(*width, strip.height())));
|
||||
self.tab(ui, panel, tab, *index == active, rect, Some(&owner));
|
||||
shown.push((panel.clone(), tab));
|
||||
x += width;
|
||||
}
|
||||
if !fit.overflow.is_empty() && fit.overflow_width > 0.0 {
|
||||
let overflow = mirror(Rect::from_min_size(pos2(x, strip.top()), vec2(fit.overflow_width, strip.height())));
|
||||
let response = ui.interact(overflow, self.id.with(("overflow", selected)), Sense::click());
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.panels_label));
|
||||
ui.painter().with_clip_rect(overflow).text(overflow.center(), egui::Align2::CENTER_CENTER, "…", self.style.font.clone(), self.style.text);
|
||||
egui::Popup::menu(&response).show(|ui| {
|
||||
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
|
||||
for index in &fit.overflow {
|
||||
if let Some(panel) = panels.get(*index)
|
||||
&& self.menu_label(ui, panel).clicked()
|
||||
{
|
||||
self.output.actions.push(Action::Activate { panel: panel.clone() });
|
||||
self.output.focused = Some(panel.clone());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
x += fit.overflow_width;
|
||||
}
|
||||
let bar =
|
||||
mirror(Rect::from_min_max(pos2(x.min(strip.right() - header_width), strip.top()), pos2(strip.right() - header_width, strip.bottom())));
|
||||
self.group_handle(ui, "drag-bar", bar, &owner, movable);
|
||||
// Registered last, so the band wins over the tabs below it.
|
||||
let border = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, (strip.top() + BORDER_BAND).min(strip.bottom()))));
|
||||
self.group_handle(ui, "drag-border", border, &owner, movable);
|
||||
if self.style.wheel_selects_tabs {
|
||||
let tabs_area = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, strip.bottom())));
|
||||
self.wheel_tabs(ui, tabs_area, panels, active);
|
||||
}
|
||||
// Logical order, hidden tabs included without a hit area, for no-op detection.
|
||||
let tabs =
|
||||
panels.iter().map(|panel| (panel.clone(), shown.iter().find(|(p, _)| p == panel).map_or(Rect::NOTHING, |(_, rect)| *rect))).collect();
|
||||
self.targets.push(DropTarget {
|
||||
anchor: selected.clone(),
|
||||
rect,
|
||||
tab_strip: Some(strip),
|
||||
tabs,
|
||||
allow_splits: splits,
|
||||
accepts_tabs: policy.accepts_tabs,
|
||||
right_to_left: rtl,
|
||||
});
|
||||
if !minimized {
|
||||
self.contents(ui, selected, Rect::from_min_max(pos2(rect.left(), strip.bottom()), rect.max));
|
||||
}
|
||||
ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// The drag bar (`drag-bar`: drag, double-click, and the group menu on a right click, Enter
|
||||
/// or Space) or the top border band (`drag-border`: drag only). Both move the whole group;
|
||||
/// a left click on the bar only focuses it.
|
||||
fn group_handle(&mut self, ui: &mut Ui, name: &'static str, hit: Rect, owner: &TabGroup<'_, P>, movable: bool) {
|
||||
if !crate::docking::targets::usable(hit) {
|
||||
return;
|
||||
}
|
||||
let bar = name == "drag-bar";
|
||||
let sense = if bar { Sense::click_and_drag() } else { Sense::drag() };
|
||||
let response = ui.interact(hit, self.id.with((name, owner.panels.first())), sense);
|
||||
let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response };
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label));
|
||||
if movable && response.drag_started() {
|
||||
self.start_group_drag(ui, owner.panels, self.drag_source(owner));
|
||||
}
|
||||
if !bar {
|
||||
return;
|
||||
}
|
||||
if self.minimizes(owner) && response.double_clicked() {
|
||||
self.output.actions.push(Action::SetMinimized { panel: owner.selected.clone(), minimized: !owner.minimized });
|
||||
}
|
||||
let active = response.has_focus() || response.hovered();
|
||||
if active {
|
||||
ui.painter().with_clip_rect(hit).rect_stroke(
|
||||
hit.shrink(1.0),
|
||||
0.0,
|
||||
Stroke::new(1.0, self.style.accent.gamma_multiply(0.5)),
|
||||
StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
let keyboard = response.has_focus() && ui.input(|i| i.key_pressed(Key::Enter) || i.key_pressed(Key::Space));
|
||||
let command = if response.secondary_clicked() || keyboard {
|
||||
Some(egui::SetOpenCommand::Bool(true))
|
||||
} else if response.clicked() {
|
||||
Some(egui::SetOpenCommand::Bool(false))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
egui::Popup::menu(&response).open_memory(command).show(|ui| self.group_menu(ui, owner, owner.selected));
|
||||
}
|
||||
|
||||
/// The wheel over a group's strip: down selects the next tab, up the previous, one tab per
|
||||
/// notch, stopping at the ends. Trackpad scrolling adds up to a notch.
|
||||
fn wheel_tabs(&mut self, ui: &Ui, strip: Rect, panels: &[P], active: usize) {
|
||||
let key = self.id.with(("tab-wheel", panels.first()));
|
||||
if !ui.rect_contains_pointer(strip) {
|
||||
ui.ctx().data_mut(|d| d.remove::<f32>(key));
|
||||
return;
|
||||
}
|
||||
let notches: f32 = ui.input(|i| {
|
||||
i.events
|
||||
.iter()
|
||||
.map(|event| match event {
|
||||
egui::Event::MouseWheel { unit, delta, modifiers, .. } if !modifiers.command && !modifiers.ctrl => match unit {
|
||||
egui::MouseWheelUnit::Point => delta.y / WHEEL_NOTCH,
|
||||
egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y,
|
||||
},
|
||||
_ => 0.0,
|
||||
})
|
||||
.sum()
|
||||
});
|
||||
if notches == 0.0 || !notches.is_finite() {
|
||||
return;
|
||||
}
|
||||
let total = ui.ctx().data(|d| d.get_temp::<f32>(key)).unwrap_or(0.0) + notches;
|
||||
let steps = total.trunc();
|
||||
ui.ctx().data_mut(|d| d.insert_temp(key, total - steps));
|
||||
// A wheel turned down scrolls content up: a negative delta selects the next tab.
|
||||
let to = (active as i64).saturating_sub(steps as i64).clamp(0, panels.len().saturating_sub(1) as i64) as usize;
|
||||
if to != active
|
||||
&& let Some(panel) = panels.get(to)
|
||||
{
|
||||
self.output.actions.push(Action::Activate { panel: panel.clone() });
|
||||
self.output.focused = Some(panel.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn start_group_drag(&mut self, ui: &Ui, panels: &[P], rect: Rect) {
|
||||
let Some(first) = panels.first() else { return };
|
||||
let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(rect.center());
|
||||
let drag = GroupDrag {
|
||||
panel: first.clone(),
|
||||
original: [rect.left(), rect.top(), rect.width(), rect.height()],
|
||||
gesture: GroupGesture::Group,
|
||||
members: panels.to_vec(),
|
||||
origin,
|
||||
source: rect,
|
||||
};
|
||||
ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag));
|
||||
}
|
||||
|
||||
/// The group items of the menu tail: Close Tab Group, Minimize or Expand, Float Tab Group
|
||||
/// and Move Group To. `panel` is the panel whose menu this is.
|
||||
fn group_menu(&mut self, ui: &mut Ui, owner: &TabGroup<'_, P>, panel: &P) {
|
||||
let all = |check: &dyn Fn(crate::docking::Permissions) -> bool| owner.panels.iter().all(|p| check(self.permissions(p)));
|
||||
let closable = self.style.close_menu_items && all(&|p| p.closable);
|
||||
let movable = all(&|p| p.movable);
|
||||
let floatable = movable && all(&|p| p.floatable);
|
||||
if closable && self.menu_action(ui, &self.style.close_group_label.clone()) {
|
||||
self.output.actions.push(Action::CloseGroup { panel: panel.clone() });
|
||||
}
|
||||
if self.minimizes(owner) {
|
||||
let label = if owner.minimized { self.style.expand_label.clone() } else { self.style.minimize_label.clone() };
|
||||
if self.menu_action(ui, &label) {
|
||||
self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !owner.minimized });
|
||||
}
|
||||
}
|
||||
if owner.kind == GroupKind::Dock && self.menu_action(ui, &self.style.collapse_to_icons_label.clone()) {
|
||||
self.output.actions.push(Action::SetIconic { panel: panel.clone(), iconic: true });
|
||||
}
|
||||
let whole_window = matches!(owner.kind, GroupKind::Floating { .. }) && self.whole_window(panel);
|
||||
if floatable && !whole_window && self.menu_action(ui, &self.style.float_group_label.clone()) {
|
||||
let size = self.group_float_size(owner.panels, owner.rect.size());
|
||||
let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), self.float_bounds);
|
||||
self.output.actions.push(Action::MoveGroup {
|
||||
panel: panel.clone(),
|
||||
to: Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) },
|
||||
});
|
||||
}
|
||||
let targets = if movable { self.group_targets(owner.panels) } else { Vec::new() };
|
||||
if !targets.is_empty() {
|
||||
let logical = self.style.move_group_to_label.clone();
|
||||
let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text);
|
||||
let response = ui.menu_button(text, |ui| {
|
||||
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
|
||||
for target in &targets {
|
||||
if self.menu_label(ui, target).clicked() {
|
||||
self.output.actions.push(Action::MoveGroup {
|
||||
panel: panel.clone(),
|
||||
to: Target::At { anchor: target.clone(), placement: Placement::Tab { before: None } },
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
response.response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical));
|
||||
}
|
||||
self.frame_items(ui, owner, panel);
|
||||
}
|
||||
|
||||
/// A stock menu button with shaped text and its logical accessibility label; true when
|
||||
/// clicked, after closing the menu.
|
||||
pub(super) fn menu_action(&mut self, ui: &mut Ui, logical: &str) -> bool {
|
||||
let text = self.content.action_label(ui, logical, &self.style.font, self.style.text);
|
||||
let response = ui.button(text);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), logical));
|
||||
if response.clicked() {
|
||||
ui.close();
|
||||
}
|
||||
response.clicked()
|
||||
}
|
||||
|
||||
/// One anchor per other group that accepts a whole group as tabs, in layout order.
|
||||
fn group_targets(&self, members: &[P]) -> Vec<P> {
|
||||
let Some(first) = members.first() else { return Vec::new() };
|
||||
let mut places = Vec::new();
|
||||
let mut anchors = Vec::new();
|
||||
for anchor in self.layout.move_targets(first, |p| self.permissions(p)) {
|
||||
if members.contains(anchor) {
|
||||
continue;
|
||||
}
|
||||
let Some(place) = self.place(anchor) else { continue };
|
||||
if !places.contains(&place) {
|
||||
places.push(place);
|
||||
anchors.push(anchor.clone());
|
||||
}
|
||||
}
|
||||
anchors
|
||||
}
|
||||
|
||||
pub(super) fn menu_label(&mut self, ui: &mut Ui, panel: &P) -> egui::Response {
|
||||
let logical = self.label_of(panel);
|
||||
let text = self.content.label(ui, panel, &logical, &self.style.font, self.style.text);
|
||||
let response = ui.button(text);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical));
|
||||
response
|
||||
}
|
||||
|
||||
/// A tab's label, cut at the end with '…' to fit `width`.
|
||||
pub(super) fn tab_label(&mut self, ui: &Ui, panel: &P, label: &str, color: Color32, width: f32) -> Arc<Galley> {
|
||||
let text = self.content.label(ui, panel, label, &self.style.font, color);
|
||||
crate::docking::chrome::truncated(ui, text, width, self.style.font.clone())
|
||||
}
|
||||
|
||||
/// True while a tab's focus came from the pointer, which shows no focus outline. Tab or an
|
||||
/// arrow key (keyboard navigation) clears it.
|
||||
fn pointer_focus(&self, ui: &Ui, tab: Id) -> bool {
|
||||
let key = tab.with("pointer-focus");
|
||||
let navigated = ui.input(|i| [Key::Tab, Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown].iter().any(|k| i.key_pressed(*k)));
|
||||
if navigated {
|
||||
ui.ctx().data_mut(|d| d.remove_temp::<bool>(key));
|
||||
}
|
||||
ui.ctx().data(|d| d.get_temp::<bool>(key)).unwrap_or(false)
|
||||
}
|
||||
|
||||
pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect, owner: Option<&TabGroup<'_, P>>) {
|
||||
let minimized = owner.filter(|owner| self.minimizes(owner)).map(|owner| owner.minimized);
|
||||
let policy = self.permissions(panel);
|
||||
let label = self.label_of(panel);
|
||||
let color = if active { self.style.text } else { self.style.inactive_text };
|
||||
let galley = self.tab_label(ui, panel, &label, color, (rect.width() - TAB_PADDING).max(0.0));
|
||||
let elided = galley.elided;
|
||||
let tab_id = self.id.with(("tab", panel));
|
||||
let pointer_focus = self.pointer_focus(ui, tab_id);
|
||||
let response = tabs::Tab::new(tab_id, &label, active)
|
||||
.sense(if policy.movable { Sense::click_and_drag() } else { Sense::click() })
|
||||
.focus_stroke(if pointer_focus { Stroke::NONE } else { Stroke::new(1.0, self.style.accent) })
|
||||
.show_at(ui, rect, |ui, response| {
|
||||
let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
painter.rect_filled(rect, 0.0, if active || response.hovered() { self.style.active_background } else { self.style.tab_background });
|
||||
let at = pos2(rect.left() + TAB_PADDING * 0.5, rect.center().y - galley.size().y * 0.5);
|
||||
painter.galley(at, galley.clone(), color);
|
||||
});
|
||||
let response = if elided { response.on_hover_text(&label) } else { response };
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
if response.is_pointer_button_down_on() || response.clicked() {
|
||||
ui.ctx().data_mut(|d| d.insert_temp(tab_id.with("pointer-focus"), true));
|
||||
}
|
||||
// The click that expands a minimized group is not the first half of a double-click.
|
||||
let expand_key = self.id.with(("expanded-by-click", owner.map(|owner| owner.panels.first())));
|
||||
if response.clicked() {
|
||||
self.output.actions.push(Action::Activate { panel: panel.clone() });
|
||||
self.output.focused = Some(panel.clone());
|
||||
if minimized == Some(true) && !active {
|
||||
self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: false });
|
||||
let now = ui.input(|i| i.time);
|
||||
ui.ctx().data_mut(|d| d.insert_temp(expand_key, now));
|
||||
}
|
||||
}
|
||||
if let Some(minimized) = minimized
|
||||
&& response.double_clicked()
|
||||
{
|
||||
let (now, window) = (ui.input(|i| i.time), ui.ctx().options(|o| o.input_options.max_double_click_delay));
|
||||
let expanded_by_first_click = ui.ctx().data_mut(|d| d.remove_temp::<f64>(expand_key)).is_some_and(|t| now - t <= window);
|
||||
if !expanded_by_first_click {
|
||||
self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized });
|
||||
}
|
||||
}
|
||||
if self.style.middle_click_closes_tabs && policy.closable && response.clicked_by(egui::PointerButton::Middle) {
|
||||
self.output.actions.push(Action::Close { panel: panel.clone() });
|
||||
}
|
||||
if policy.movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), group) {
|
||||
self.latch_undock(ui.ctx(), owner.map(|owner| owner.kind));
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
self.content.panel_menu(ui, panel);
|
||||
if policy.movable && policy.floatable {
|
||||
let logical = self.style.float_label.clone();
|
||||
let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text);
|
||||
let response = ui.button(text);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical));
|
||||
if response.clicked() {
|
||||
let size = self.float_size(panel, group.size());
|
||||
let rect = clamp_float(Rect::from_min_size(group.min + vec2(24.0, 24.0), size), self.float_bounds);
|
||||
self.output.actions.push(Action::Float { panel: panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] });
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
let targets: Vec<P> =
|
||||
if policy.movable { self.layout.move_targets(panel, |p| self.permissions(p)).into_iter().cloned().collect() } else { Vec::new() };
|
||||
if !targets.is_empty() {
|
||||
let text = self.content.action_label(ui, &self.style.move_panel_to_label, &self.style.font, self.style.text);
|
||||
let response = ui.menu_button(text, |ui| {
|
||||
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
|
||||
for target in &targets {
|
||||
if self.menu_label(ui, target).clicked() {
|
||||
self.output.actions.push(Action::Move {
|
||||
panel: panel.clone(),
|
||||
anchor: target.clone(),
|
||||
placement: Placement::Tab { before: None },
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
response
|
||||
.response
|
||||
.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_panel_to_label));
|
||||
}
|
||||
if policy.closable && self.style.close_menu_items {
|
||||
let text = self.content.action_label(ui, &self.style.close_label, &self.style.font, self.style.text);
|
||||
let response = ui.button(text);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.close_label));
|
||||
if response.clicked() {
|
||||
self.output.actions.push(Action::Close { panel: panel.clone() });
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if let Some(owner) = owner {
|
||||
ui.separator();
|
||||
self.group_menu(ui, owner, panel);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! [D] Iconic columns: one icon per panel, groups apart, and the flyout an icon opens.
|
||||
//!
|
||||
//! Behavior follows VectorCraft `dock.rs` (icon column, flyouts beside it on the canvas side,
|
||||
//! names when the column is widened) and PhotoCraft `dock.rs` (Auto-Collapse Iconic Panels).
|
||||
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Id, Key, Order, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2};
|
||||
|
||||
use super::{GroupKind, Renderer, dock::Edge};
|
||||
use crate::docking::{
|
||||
Column, DockStyle, Group, GroupDrag, GroupGesture, begin_drag,
|
||||
chrome::{ChromeStyle, FloatingFrame},
|
||||
is_dragging,
|
||||
targets::{DockDrop, DockTarget, horizontal_line, usable},
|
||||
};
|
||||
|
||||
/// How far an icon group's drag band reaches into its first icon. The band also covers the
|
||||
/// separator room above the group; it reserves no height of its own.
|
||||
const GROUP_BAND: f32 = 4.0;
|
||||
/// Room between two icon groups, with the separator line in its middle.
|
||||
const SEPARATOR: f32 = 7.0;
|
||||
/// Height of a flyout, or of a panel floated from an icon, when nothing else sizes it.
|
||||
const FLYOUT_HEIGHT: f32 = 320.0;
|
||||
|
||||
/// The panel whose icon opened the flyout of an area.
|
||||
#[derive(Clone)]
|
||||
struct Open<P>(P);
|
||||
|
||||
fn key(area: Id) -> Id {
|
||||
area.with("flyout")
|
||||
}
|
||||
|
||||
/// [D] Open the flyout of the group holding `panel`, when that group is in an iconic column.
|
||||
/// The flyout shows from the next frame on. [`crate::docking::DockArea::raise_panel`] does the
|
||||
/// same for a panel the Window menu opens.
|
||||
pub fn open_flyout<P: Clone + Send + Sync + 'static>(ctx: &Context, area_id: Id, panel: P) {
|
||||
ctx.data_mut(|d| d.insert_temp(key(area_id), Open(panel)));
|
||||
}
|
||||
|
||||
/// [D] Close the area's flyout.
|
||||
pub fn close_flyout<P: Clone + Send + Sync + 'static>(ctx: &Context, area_id: Id) {
|
||||
ctx.data_mut(|d| d.remove::<Open<P>>(key(area_id)));
|
||||
}
|
||||
|
||||
/// [D] The panel whose icon opened the area's flyout, while one is open.
|
||||
pub fn flyout<P: Clone + Send + Sync + 'static>(ctx: &Context, area_id: Id) -> Option<P> {
|
||||
ctx.data(|d| d.get_temp::<Open<P>>(key(area_id))).map(|open| open.0)
|
||||
}
|
||||
|
||||
/// The flyout last reported by [`crate::docking::DockEvent::FlyoutChanged`].
|
||||
#[derive(Clone)]
|
||||
struct Reported<P>(Option<P>);
|
||||
|
||||
/// The flyout an iconic column asks for this frame.
|
||||
struct Request<P> {
|
||||
group: Group<P>,
|
||||
/// The icons of the group, where the flyout's top aligns.
|
||||
icons: Rect,
|
||||
/// The iconic column, which a press does not close the flyout in.
|
||||
column: Rect,
|
||||
edge: Edge,
|
||||
/// The column's expanded width.
|
||||
width: f32,
|
||||
}
|
||||
|
||||
/// Per-frame iconic state of a renderer.
|
||||
pub(in crate::docking) struct Iconic<P> {
|
||||
auto_collapse: bool,
|
||||
/// Iconic column bodies drawn this frame, outlined by a drop into them (P9).
|
||||
columns: Vec<Rect>,
|
||||
/// Expanded column width of each panel drawn as an icon: a panel floated from its icon
|
||||
/// takes it.
|
||||
widths: Vec<(P, f32)>,
|
||||
request: Option<Request<P>>,
|
||||
/// The flyout drawn this frame; it occludes dock targets behind it.
|
||||
rect: Option<Rect>,
|
||||
}
|
||||
|
||||
impl<P: PartialEq> Iconic<P> {
|
||||
pub(in crate::docking) fn new(auto_collapse: bool) -> Self {
|
||||
Self { auto_collapse, columns: Vec::new(), widths: Vec::new(), request: None, rect: None }
|
||||
}
|
||||
|
||||
pub(super) fn covers(&self, pointer: Pos2) -> bool {
|
||||
self.rect.is_some_and(|rect| rect.contains(pointer))
|
||||
}
|
||||
|
||||
/// Outline the iconic column an insertion line lies in.
|
||||
pub(super) fn outline(&self, painter: &egui::Painter, line: Rect, style: &DockStyle) {
|
||||
if let Some(column) = self.columns.iter().find(|column| column.shrink(1.0).contains(line.center())) {
|
||||
painter.rect_stroke(column.shrink(1.0), 0.0, Stroke::new(2.0, style.accent), StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn float_width(&self, panel: &P) -> Option<f32> {
|
||||
self.widths.iter().find(|(p, _)| p == panel).map(|(_, width)| *width)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
fn row_height(&self) -> f32 {
|
||||
self.style.icon_size + 10.0
|
||||
}
|
||||
|
||||
fn icon_group_height(&self, group: &Group<P>) -> f32 {
|
||||
group.panels.len() as f32 * self.row_height()
|
||||
}
|
||||
|
||||
/// The body of an iconic column: icon groups top to bottom, scrolling when they do not fit.
|
||||
pub(super) fn iconic_column(&mut self, ui: &mut Ui, column: &Column<P>, body: Rect, edge: Edge) {
|
||||
self.iconic.columns.push(body);
|
||||
for panel in column.groups.iter().flat_map(|g| g.panels.iter()) {
|
||||
self.iconic.widths.push((panel.clone(), column.width));
|
||||
}
|
||||
// Opening a panel from the Window menu opens its flyout (U3).
|
||||
if let Some(panel) = self.activation.as_ref().filter(|p| column.groups.iter().any(|g| g.panels.contains(p))) {
|
||||
open_flyout(ui.ctx(), self.id, panel.clone());
|
||||
}
|
||||
let total: f32 =
|
||||
column.groups.iter().map(|g| self.icon_group_height(g)).sum::<f32>() + column.groups.len().saturating_sub(1) as f32 * SEPARATOR;
|
||||
if total > body.height() + 0.5 {
|
||||
let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { return };
|
||||
let mut child =
|
||||
ui.new_child(UiBuilder::new().id_salt(("icon-column", first)).max_rect(body).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
child.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt(self.id.with(("icon-scroll", first)))
|
||||
.auto_shrink([false, false])
|
||||
.scroll_source(egui::scroll_area::ScrollSource::SCROLL_BAR | egui::scroll_area::ScrollSource::MOUSE_WHEEL)
|
||||
.show(&mut child, |ui| {
|
||||
let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), total), Sense::hover());
|
||||
self.icon_groups(ui, column, area, body, edge);
|
||||
});
|
||||
} else {
|
||||
self.icon_groups(ui, column, body, body, edge);
|
||||
}
|
||||
}
|
||||
|
||||
/// Icon groups in `area` (the scrolled content when the column scrolls), their drop bands
|
||||
/// clipped to the visible `view`.
|
||||
fn icon_groups(&mut self, ui: &mut Ui, column: &Column<P>, area: Rect, view: Rect, edge: Edge) {
|
||||
let open = flyout::<P>(ui.ctx(), self.id);
|
||||
let labels = view.width() >= self.style.iconic_label_width;
|
||||
let xs = view.x_range();
|
||||
let mut top = area.top();
|
||||
let mut bands = Vec::new();
|
||||
for (index, group) in column.groups.iter().enumerate() {
|
||||
let Some(first) = group.panels.first() else { continue };
|
||||
let band_top = if index > 0 { top } else { area.top() };
|
||||
if index > 0 {
|
||||
let y = top + SEPARATOR * 0.5;
|
||||
ui.painter().with_clip_rect(view).hline(area.x_range().shrink(4.0), y, self.style.border);
|
||||
top += SEPARATOR;
|
||||
}
|
||||
let rect = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), self.icon_group_height(group)));
|
||||
let showing = open.as_ref().filter(|p| group.panels.contains(p));
|
||||
let mut y = rect.top();
|
||||
for panel in &group.panels {
|
||||
let cell = Rect::from_min_size(pos2(rect.left(), y), vec2(rect.width(), self.row_height()));
|
||||
self.icon(ui, panel, cell, labels, showing);
|
||||
y = cell.bottom();
|
||||
}
|
||||
// After the icons, so the band wins the top of the first icon.
|
||||
let band = Rect::from_min_max(pos2(rect.left(), band_top), pos2(rect.right(), (rect.top() + GROUP_BAND).min(rect.bottom())));
|
||||
self.icon_grip(ui, group, band, rect.top(), column.width);
|
||||
// The state again: a click above may have opened or closed this group's flyout.
|
||||
if flyout::<P>(ui.ctx(), self.id).is_some_and(|p| group.panels.contains(&p)) {
|
||||
self.iconic.request = Some(Request { group: group.clone(), icons: rect.intersect(view), column: view, edge, width: column.width });
|
||||
}
|
||||
bands.push((first.clone(), rect));
|
||||
top = rect.bottom();
|
||||
}
|
||||
// P9: the upper half of an icon group inserts above it, the lower half and the room
|
||||
// under the last group below it. The line sits on the group's edge.
|
||||
let count = bands.len();
|
||||
for (index, (anchor, rect)) in bands.into_iter().enumerate() {
|
||||
let middle = rect.center().y;
|
||||
let upper_top = if index == 0 { view.top() } else { rect.top() - SEPARATOR * 0.5 };
|
||||
let lower_bottom = if index + 1 == count { view.bottom() } else { rect.bottom() + SEPARATOR * 0.5 };
|
||||
for (below, ys, line) in [(false, upper_top..=middle, rect.top()), (true, middle..=lower_bottom, rect.bottom())] {
|
||||
let band = Rect::from_x_y_ranges(xs, ys).intersect(view);
|
||||
if usable(band) {
|
||||
let line = horizontal_line(line.clamp(view.top() + 2.0, view.bottom() - 2.0), xs);
|
||||
self.dock_targets.push(DockDrop { target: DockTarget::GroupBand { anchor: anchor.clone(), below }, band, line });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The band on an icon group's top edge drags the whole group (S8). `top` is the group's
|
||||
/// first icon's top, where a floated group's source starts.
|
||||
fn icon_grip(&mut self, ui: &mut Ui, group: &Group<P>, grip: Rect, top: f32, width: f32) {
|
||||
let Some(first) = group.panels.first() else { return };
|
||||
let movable = group.panels.iter().all(|p| self.permissions(p).movable);
|
||||
let response = ui.interact(grip, self.id.with(("icon-grip", Some(first))), Sense::drag());
|
||||
let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response };
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
let height = group.height.filter(|h| h.is_finite()).unwrap_or(FLYOUT_HEIGHT);
|
||||
let source = Rect::from_min_size(pos2(grip.left(), top), vec2(width.max(self.style.min_pane), height.max(self.style.tab_height)));
|
||||
self.record_float(&group.panels, vec2(grip.width(), self.row_height()), source.size());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label));
|
||||
if movable && response.drag_started() {
|
||||
let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center());
|
||||
let drag = GroupDrag {
|
||||
panel: first.clone(),
|
||||
original: [source.left(), source.top(), source.width(), source.height()],
|
||||
gesture: GroupGesture::Group,
|
||||
members: group.panels.clone(),
|
||||
origin,
|
||||
source,
|
||||
};
|
||||
ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag));
|
||||
close_flyout::<P>(ui.ctx(), self.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// One panel's icon: a click opens, switches or closes the flyout (M5); a drag moves the
|
||||
/// panel (S7). `showing` is the panel whose icon opened this group's flyout.
|
||||
fn icon(&mut self, ui: &mut Ui, panel: &P, cell: Rect, labels: bool, showing: Option<&P>) {
|
||||
let movable = self.permissions(panel).movable;
|
||||
let label = self.label_of(panel);
|
||||
let response = ui.interact(cell, self.id.with(("icon", panel)), if movable { Sense::click_and_drag() } else { Sense::click() });
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
let current = showing == Some(panel);
|
||||
response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), current, &label));
|
||||
let painter = ui.painter().with_clip_rect(cell.intersect(ui.clip_rect()));
|
||||
if current || response.hovered() {
|
||||
painter.rect_filled(cell.shrink(2.0), 3.0, self.style.active_background);
|
||||
}
|
||||
if response.has_focus() {
|
||||
painter.rect_stroke(cell.shrink(1.0), 3.0, Stroke::new(1.0, self.style.accent), StrokeKind::Inside);
|
||||
}
|
||||
let size = self.style.icon_size;
|
||||
let inset = ((self.style.iconic_width - size) * 0.5).max(2.0);
|
||||
let icon = Rect::from_min_size(pos2(cell.left() + inset, cell.center().y - size * 0.5), vec2(size, size));
|
||||
let color = if current { self.style.text } else { self.style.inactive_text };
|
||||
if !self.content.paint_icon(&painter, icon, panel, color) {
|
||||
if let Some(source) = self.content.icon(panel) {
|
||||
egui::Image::new(source).tint(color).paint_at(ui, icon.intersect(cell));
|
||||
} else {
|
||||
let initial: String = label.chars().next().into_iter().flat_map(char::to_uppercase).collect();
|
||||
painter.rect_stroke(icon, 3.0, Stroke::new(1.0, color), StrokeKind::Inside);
|
||||
painter.text(icon.center(), egui::Align2::CENTER_CENTER, initial, self.style.font.clone(), color);
|
||||
}
|
||||
}
|
||||
if labels {
|
||||
let text = self.content.label(ui, panel, &label, &self.style.font, color);
|
||||
let galley =
|
||||
text.into_galley(ui, Some(egui::TextWrapMode::Truncate), (cell.right() - icon.right() - 12.0).max(0.0), self.style.font.clone());
|
||||
painter.galley(pos2(icon.right() + 6.0, cell.center().y - galley.size().y * 0.5), galley, color);
|
||||
} else if response.hovered() && !response.dragged() {
|
||||
response.clone().on_hover_text(&label);
|
||||
}
|
||||
if response.clicked() {
|
||||
if current {
|
||||
close_flyout::<P>(ui.ctx(), self.id);
|
||||
} else {
|
||||
if showing.is_none() {
|
||||
ui.ctx().move_to_top(FloatingFrame::layer(self.id.with("flyout")));
|
||||
}
|
||||
open_flyout(ui.ctx(), self.id, panel.clone());
|
||||
self.output.actions.push(crate::docking::Action::Activate { panel: panel.clone() });
|
||||
self.output.focused = Some(panel.clone());
|
||||
}
|
||||
}
|
||||
if movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), cell) {
|
||||
close_flyout::<P>(ui.ctx(), self.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Auto-Collapse Iconic Panels item of a column menu (U1): true when chosen.
|
||||
pub(super) fn auto_collapse_item(&mut self, ui: &mut Ui) -> bool {
|
||||
let logical = self.style.auto_collapse_label.clone();
|
||||
let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text);
|
||||
let mut on = self.iconic.auto_collapse;
|
||||
let response = ui.add(egui::Checkbox::new(&mut on, text));
|
||||
response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), self.iconic.auto_collapse, &logical));
|
||||
if response.clicked() {
|
||||
ui.close();
|
||||
}
|
||||
response.clicked()
|
||||
}
|
||||
|
||||
/// Draw the flyout an iconic column asked for, beside the column on the canvas side, or
|
||||
/// forget a flyout whose group is no longer iconic. With Auto-Collapse, Escape or a press
|
||||
/// outside the flyout and its column closes it.
|
||||
pub(in crate::docking) fn flyout(&mut self, ctx: &Context) {
|
||||
let Some(request) = self.iconic.request.take() else {
|
||||
close_flyout::<P>(ctx, self.id);
|
||||
return;
|
||||
};
|
||||
let Some(active) = request.group.active_panel().cloned() else { return };
|
||||
let id = self.id.with("flyout");
|
||||
if self.iconic.auto_collapse && self.flyout_dismissed(ctx, id, request.column) {
|
||||
close_flyout::<P>(ctx, self.id);
|
||||
return;
|
||||
}
|
||||
let bounds = self.workspace.intersect(self.float_bounds);
|
||||
let width = request.width.max(self.style.min_pane).min(bounds.width());
|
||||
let max = self
|
||||
.content
|
||||
.floating_size(&active)
|
||||
.map(|size| size.y)
|
||||
.or(request.group.height)
|
||||
.filter(|h| h.is_finite() && *h > 0.0)
|
||||
.unwrap_or(FLYOUT_HEIGHT);
|
||||
// A flyout fits the content its panel last drew, up to that height.
|
||||
let height = self
|
||||
.fitted_height(&active, self.style.tab_height, max)
|
||||
.unwrap_or(max)
|
||||
.max(self.style.tab_height + self.style.min_pane)
|
||||
.min(bounds.height());
|
||||
let left = match request.edge {
|
||||
Edge::Left => request.column.right(),
|
||||
Edge::Right => request.column.left() - width,
|
||||
};
|
||||
let top = request.icons.top().min(bounds.bottom() - height).max(bounds.top());
|
||||
let rect = Rect::from_min_size(pos2(left, top), vec2(width, height));
|
||||
let style = ChromeStyle::from_dock(self.style);
|
||||
let group = request.group;
|
||||
let response = FloatingFrame::new(id, rect).bounds(bounds).resizable(false).show(ctx, &style, |ui, rect| {
|
||||
self.group(ui, &group.panels, group.active, false, rect, GroupKind::Dock);
|
||||
});
|
||||
self.iconic.rect = Some(response.rect);
|
||||
}
|
||||
|
||||
/// Report a flyout that differs from the last one reported.
|
||||
pub(in crate::docking) fn report_flyout(&mut self, ctx: &Context) {
|
||||
let shown = flyout::<P>(ctx, self.id);
|
||||
let key = self.id.with("flyout-reported");
|
||||
let reported = ctx.data(|d| d.get_temp::<Reported<P>>(key)).and_then(|r| r.0);
|
||||
if shown != reported {
|
||||
ctx.data_mut(|d| d.insert_temp(key, Reported(shown.clone())));
|
||||
self.output.events.push(crate::docking::DockEvent::FlyoutChanged { panel: shown });
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape (outside a drag) or a primary press outside the flyout, its column and any menu.
|
||||
fn flyout_dismissed(&self, ctx: &Context, id: Id, column: Rect) -> bool {
|
||||
let escape = !is_dragging::<P>(ctx, self.id) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape));
|
||||
let press = ctx.input(|i| i.pointer.primary_pressed().then(|| i.pointer.press_origin()).flatten());
|
||||
let outside = press.is_some_and(|pos| {
|
||||
let inside = ctx.memory(|m| m.area_rect(id)).is_some_and(|r| r.contains(pos)) || column.contains(pos);
|
||||
let menu = ctx.layer_id_at(pos).is_some_and(|layer| matches!(layer.order, Order::Foreground | Order::Tooltip));
|
||||
!inside && !menu
|
||||
});
|
||||
escape || outside
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
use std::{collections::HashMap, fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, CursorIcon, Id, Rect, Sense, Ui, UiBuilder, Vec2, pos2, vec2};
|
||||
|
||||
use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis};
|
||||
|
||||
use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions, dock_model::Place};
|
||||
|
||||
mod dock;
|
||||
mod floating;
|
||||
mod frame;
|
||||
mod iconic;
|
||||
#[cfg(feature = "native-windows")]
|
||||
mod native;
|
||||
|
||||
pub(in crate::docking) use frame::{FrameState, view};
|
||||
|
||||
pub(in crate::docking) use group::GroupKind;
|
||||
|
||||
pub(in crate::docking) use iconic::Iconic;
|
||||
pub use iconic::{close_flyout, flyout, open_flyout};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(in crate::docking) use dock::fit_widths;
|
||||
pub(in crate::docking) use floating::RESIZE_HANDLES;
|
||||
mod group;
|
||||
mod preview;
|
||||
mod sizes;
|
||||
|
||||
pub(in crate::docking) use sizes::{DROP_MARGIN, Drawn, RowItem, Sizer, row_drag, row_range};
|
||||
|
||||
pub(super) struct Renderer<'a, P> {
|
||||
pub(super) id: Id,
|
||||
pub(super) style: &'a DockStyle,
|
||||
pub(super) content: &'a mut dyn DockContent<P>,
|
||||
pub(super) activation: Option<P>,
|
||||
pub(super) blockers: Vec<Rect>,
|
||||
pub(super) layout: &'a Layout<P>,
|
||||
/// The docked area, for host drop requests.
|
||||
pub(super) workspace: Rect,
|
||||
/// Where floating windows, flyouts and drag ghosts go: [`crate::docking::DockArea::float_bounds`].
|
||||
pub(super) float_bounds: Rect,
|
||||
pub(super) targets: Vec<DropTarget<P>>,
|
||||
/// [D] Seams, group bands, column edges and new-dock bands, see [`crate::docking::targets::DockDrop`].
|
||||
pub(super) dock_targets: Vec<crate::docking::targets::DockDrop<P>>,
|
||||
pub(super) owned_interactions: Vec<Id>,
|
||||
pub(super) output: DockOutput<P>,
|
||||
pub(super) frame: FrameState<P>,
|
||||
/// [D] Flyout and iconic column state for this frame.
|
||||
pub(super) iconic: Iconic<P>,
|
||||
/// What a drag would float from each drawn panel, group and column, for commands.
|
||||
pub(super) float_space: crate::docking::FloatSpace<P>,
|
||||
/// Each panel's place in `layout`, and its entry in `float_space.contents`.
|
||||
pub(super) places: HashMap<P, Place>,
|
||||
pub(super) contents: HashMap<P, usize>,
|
||||
/// Split dividers drawn so far, by view path, for the intersections of their ancestors.
|
||||
pub(super) dividers: Vec<DrawnDivider>,
|
||||
/// The floating window whose tree is being drawn: its first panel, which names it in
|
||||
/// ids and actions, and its rect. `None` while the docked layout draws.
|
||||
pub(super) tree: Option<(P, Rect)>,
|
||||
}
|
||||
|
||||
pub(super) struct DrawnDivider {
|
||||
path: Vec<bool>,
|
||||
axis: SplitAxis,
|
||||
divider: Rect,
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
pub(super) fn place(&self, panel: &P) -> Option<&Place> {
|
||||
self.places.get(panel)
|
||||
}
|
||||
|
||||
/// The height `panel`'s content last used: `Some(None)` when it filled its body.
|
||||
pub(super) fn content_height(&self, panel: &P) -> Option<Option<f32>> {
|
||||
self.contents.get(panel).and_then(|i| self.float_space.contents.get(*i)).map(|(_, height)| *height)
|
||||
}
|
||||
|
||||
pub(super) fn label_of(&self, panel: &P) -> String {
|
||||
self.content.logical_label(panel)
|
||||
}
|
||||
|
||||
pub(super) fn permissions(&self, panel: &P) -> Permissions {
|
||||
self.content.permissions(panel)
|
||||
}
|
||||
|
||||
pub(super) fn limits(&self, panel: &P) -> PanelLimits {
|
||||
self.content.limits(panel)
|
||||
}
|
||||
|
||||
pub(super) fn register_interaction(&mut self, ctx: &Context, id: Id) {
|
||||
// A validated tree has at most 2*MAX_PANELS nodes. Tabs, stack dividers,
|
||||
// floating grips/corners and splits fit comfortably inside this fixed bound.
|
||||
const CAP: usize = 8 * crate::docking::MAX_PANELS;
|
||||
if self.owned_interactions.len() < CAP && !self.owned_interactions.contains(&id) {
|
||||
self.owned_interactions.push(id);
|
||||
}
|
||||
// Retain prior-frame controls until return, and publish current controls before
|
||||
// app callbacks. No Context lock spans a callback or a stop_dragging call.
|
||||
ctx.data_mut(|d| {
|
||||
let ids = d.get_temp_mut_or_default::<Vec<Id>>(self.id.with("owned-interactions"));
|
||||
if ids.len() < CAP && !ids.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Draws `node` at view path `path` in `rect`, in the tree `root` (its root node and rect),
|
||||
/// which a dragged divider resizes beyond `node`.
|
||||
pub(in crate::docking) fn node(&mut self, ui: &mut Ui, node: &Node<P>, rect: Rect, path: &mut Vec<bool>, root: (&Node<P>, Rect)) {
|
||||
if !crate::docking::targets::usable(rect) {
|
||||
return;
|
||||
}
|
||||
self.note_edge(path, rect);
|
||||
match node {
|
||||
Node::Split { axis: SplitAxis::Horizontal, first, second, .. } if self.dock_split(ui, first, second, rect, path, root) => {}
|
||||
Node::Split { axis, size, first, second } => {
|
||||
let sizer = self.sizer();
|
||||
let Some(split) = sizer.split(*axis, *size, first, second, rect) else { return };
|
||||
let (lo, hi) = sizer.range(root, path);
|
||||
let mark = self.dividers.len();
|
||||
path.push(false);
|
||||
self.node(ui, first, split.first, path, root);
|
||||
path.pop();
|
||||
path.push(true);
|
||||
self.node(ui, second, split.second, path, root);
|
||||
path.pop();
|
||||
// The divider's inner-edge hit margin must win over child scrollbars, just
|
||||
// as accordion dividers win over the adjacent panel's content.
|
||||
// Named by its layout path, which `ResizeSplit` takes and hits report.
|
||||
let layout_path = self.original_path(path);
|
||||
let response = ResizeHandle::new(
|
||||
self.split_id(&layout_path),
|
||||
*axis,
|
||||
split.divider,
|
||||
&self.style.resize_label,
|
||||
ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent },
|
||||
)
|
||||
.value(split.first_size(), (split.first_size() + lo)..=(split.first_size() + hi))
|
||||
.show(ui);
|
||||
self.register_interaction(ui.ctx(), response.response.id);
|
||||
if response.delta != 0.0 {
|
||||
let actions = self.divider_actions(root, path, response.delta);
|
||||
self.output.actions.extend(actions);
|
||||
}
|
||||
self.intersections(ui, (node, rect), path, split.divider, mark, root);
|
||||
if self.dividers.len() < crate::docking::model::MAX_NODES {
|
||||
self.dividers.push(DrawnDivider { path: path.clone(), axis: *axis, divider: split.divider });
|
||||
}
|
||||
}
|
||||
Node::Tabs { panels, active } => {
|
||||
let kind = match &self.tree {
|
||||
None => GroupKind::Frame,
|
||||
Some((_, window)) => GroupKind::Floating { window: *window },
|
||||
};
|
||||
self.group(ui, panels, *active, false, rect, kind);
|
||||
}
|
||||
Node::Dock { side, columns } => self.dock(ui, *side, columns, rect, rect.width()),
|
||||
Node::Stack { entries } => {
|
||||
let total_header = (entries.len() as f32 * self.style.tab_height).min(rect.height());
|
||||
let remaining = (rect.height() - total_header).max(0.0);
|
||||
let total_wanted: f64 = entries.iter().filter(|e| e.open).map(|e| f64::from(e.height.unwrap_or(self.style.min_pane).max(1.0))).sum();
|
||||
let header = self.style.tab_height.min(rect.height() / entries.len().max(1) as f32);
|
||||
let mut top = rect.top();
|
||||
let mut dividers = Vec::new();
|
||||
for (index, entry) in entries.iter().enumerate() {
|
||||
let share = if entry.open && total_wanted > 0.0 {
|
||||
(f64::from(remaining) * f64::from(entry.height.unwrap_or(self.style.min_pane).max(1.0)) / total_wanted) as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let panel_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), (top + header + share).min(rect.bottom())));
|
||||
let title_rect = Rect::from_min_max(panel_rect.min, pos2(panel_rect.right(), (top + header).min(panel_rect.bottom())));
|
||||
self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect, None);
|
||||
let collapse = if self.style.right_to_left {
|
||||
Rect::from_min_max(title_rect.min, pos2((title_rect.left() + 18.0).min(title_rect.right()), title_rect.bottom()))
|
||||
} else {
|
||||
Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max)
|
||||
};
|
||||
let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click());
|
||||
self.register_interaction(ui.ctx(), response.id);
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), entry.open, self.label_of(&entry.panel))
|
||||
});
|
||||
ui.painter().with_clip_rect(collapse).text(
|
||||
collapse.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if entry.open { "−" } else { "+" },
|
||||
self.style.font.clone(),
|
||||
self.style.text,
|
||||
);
|
||||
if response.clicked() {
|
||||
self.output.actions.push(Action::SetStackOpen { panel: entry.panel.clone(), open: !entry.open });
|
||||
}
|
||||
let body_rect = Rect::from_min_max(pos2(rect.left(), title_rect.bottom()), panel_rect.max);
|
||||
if entry.open {
|
||||
self.contents(ui, &entry.panel, body_rect);
|
||||
}
|
||||
self.targets.push(DropTarget {
|
||||
anchor: entry.panel.clone(),
|
||||
rect: panel_rect,
|
||||
tab_strip: Some(title_rect),
|
||||
tabs: vec![(entry.panel.clone(), title_rect)],
|
||||
allow_splits: self.permissions(&entry.panel).accepts_splits,
|
||||
accepts_tabs: self.permissions(&entry.panel).accepts_tabs,
|
||||
right_to_left: self.style.right_to_left,
|
||||
});
|
||||
top = panel_rect.bottom();
|
||||
if entry.open && remaining > 0.0 {
|
||||
dividers.push((index, Rect::from_min_max(pos2(rect.left(), top - 1.0), pos2(rect.right(), top + 1.0)).intersect(rect)));
|
||||
}
|
||||
}
|
||||
// Register dividers after the headers so their narrow hit regions win at the
|
||||
// shared boundary. Closed entries retain their saved sizes and are skipped.
|
||||
let scale = if total_wanted > 0.0 { f64::from(remaining) / total_wanted } else { 0.0 };
|
||||
let body_limits = |panel: &P| {
|
||||
let mut limits = self.limits(panel);
|
||||
limits.min.y = limits.min.y.max(self.style.min_pane);
|
||||
limits.max = limits.max.max(limits.min);
|
||||
limits
|
||||
};
|
||||
let open: Vec<&crate::docking::StackEntry<P>> = entries.iter().filter(|entry| entry.open).collect();
|
||||
let row: Vec<RowItem> = open
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let limits = body_limits(&entry.panel);
|
||||
let size = (f64::from(entry.height.unwrap_or(self.style.min_pane).max(1.0)) * scale) as f32;
|
||||
RowItem { size, min: limits.min.y, max: limits.max.y }
|
||||
})
|
||||
.collect();
|
||||
for (index, divider) in dividers {
|
||||
let Some(first) = entries.get(index) else { continue };
|
||||
let Some(position) = open.iter().position(|entry| std::ptr::eq(*entry, first)) else { continue };
|
||||
let Some(first_size) = row.get(position).map(|item| item.size) else { continue };
|
||||
if position + 1 >= row.len() {
|
||||
continue;
|
||||
}
|
||||
let (lo, hi) = row_range(&row, position);
|
||||
let response = ResizeHandle::new(
|
||||
self.id.with(("stack-resize", &first.panel)),
|
||||
SplitAxis::Vertical,
|
||||
divider,
|
||||
&self.style.resize_label,
|
||||
ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent },
|
||||
)
|
||||
.value(first_size, (first_size + lo)..=(first_size + hi))
|
||||
.show(ui);
|
||||
self.register_interaction(ui.ctx(), response.response.id);
|
||||
if response.delta != 0.0 && scale > 0.0 {
|
||||
for ((entry, item), next) in open.iter().zip(&row).zip(row_drag(&row, position, response.delta)) {
|
||||
if next != item.size {
|
||||
let height = (f64::from(next) / scale).clamp(1.0, 1_000_000.0) as f32;
|
||||
self.output.actions.push(Action::ResizeStack { panel: entry.panel.clone(), height: Some(height) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sizer(&self) -> Sizer<'_, P> {
|
||||
Sizer { style: self.style, content: &*self.content }
|
||||
}
|
||||
|
||||
/// `ResizeSplit` actions that move the divider of the split at view path `path` in the
|
||||
/// tree `root` by `delta` points.
|
||||
fn divider_actions(&self, root: (&Node<P>, Rect), path: &[bool], delta: f32) -> Vec<Action<P>> {
|
||||
let sizes = self.sizer().drag(root, path, delta);
|
||||
let resize = |path: Vec<bool>, size| match &self.tree {
|
||||
None => Action::ResizeSplit { path, size },
|
||||
Some((panel, _)) => Action::ResizeWindowSplit { panel: panel.clone(), path, size },
|
||||
};
|
||||
sizes.into_iter().map(|(path, size)| resize(self.original_path(&path), size)).collect()
|
||||
}
|
||||
|
||||
/// The id of the divider of the split at `path` in the tree being drawn, as
|
||||
/// [`crate::docking::DockArea::hit_id`] names it.
|
||||
fn split_id(&self, path: &[bool]) -> Id {
|
||||
match &self.tree {
|
||||
None => self.id.with(("split", path)),
|
||||
Some((panel, _)) => self.id.with(("window-split", panel, path)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Four-way handles where a divider drawn inside the split `node` (since `mark`) ends on
|
||||
/// the split's own divider: dragging one moves both dividers.
|
||||
fn intersections(&mut self, ui: &mut Ui, (node, rect): (&Node<P>, Rect), path: &[bool], divider: Rect, mark: usize, root: (&Node<P>, Rect)) {
|
||||
let Node::Split { axis, .. } = node else { return };
|
||||
let side = (self.style.gap * 3.0).max(12.0);
|
||||
let mut found = Vec::new();
|
||||
for inner in self.dividers.get(mark..).unwrap_or_default() {
|
||||
if inner.axis == *axis || !inner.divider.expand(1.0).intersects(divider) {
|
||||
continue;
|
||||
}
|
||||
let center = match axis {
|
||||
SplitAxis::Horizontal => pos2(divider.center().x, inner.divider.center().y),
|
||||
SplitAxis::Vertical => pos2(inner.divider.center().x, divider.center().y),
|
||||
};
|
||||
found.push((inner.path.clone(), Rect::from_center_size(center, Vec2::splat(side)).intersect(rect)));
|
||||
}
|
||||
for (inner_path, hit) in found {
|
||||
let Some(inner) = inner_path.get(path.len()..).and_then(|rest| crate::docking::dock_model::node_at(node, rest)) else { continue };
|
||||
let (outer, inner_layout) = (self.original_path(path), self.original_path(&inner_path));
|
||||
let id = match &self.tree {
|
||||
None => self.id.with(("intersection", outer, inner_layout)),
|
||||
Some((panel, _)) => self.id.with(("window-intersection", panel, outer, inner_layout)),
|
||||
};
|
||||
// Pointer only: each of the two dividers it joins already takes keyboard focus.
|
||||
let response = ui.interact(hit, id, Sense::DRAG);
|
||||
self.register_interaction(ui.ctx(), id);
|
||||
if response.hovered() || response.dragged() {
|
||||
ui.ctx().set_cursor_icon(CursorIcon::Move);
|
||||
}
|
||||
let delta = response.drag_delta();
|
||||
if delta != Vec2::ZERO && delta.is_finite() {
|
||||
let along = |axis: SplitAxis| if axis == SplitAxis::Horizontal { delta.x } else { delta.y };
|
||||
let Node::Split { axis: inner_axis, .. } = inner else { continue };
|
||||
let mut actions = self.divider_actions(root, path, along(*axis));
|
||||
actions.extend(self.divider_actions(root, &inner_path, along(*inner_axis)));
|
||||
self.output.actions.extend(actions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn contents(&mut self, ui: &mut Ui, panel: &P, rect: Rect) {
|
||||
if !crate::docking::targets::usable(rect) {
|
||||
return;
|
||||
}
|
||||
ui.painter().rect_filled(rect, 0.0, self.style.background);
|
||||
let mut child =
|
||||
ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
self.content.body(&mut child, panel);
|
||||
let at = self.contents.get(panel).copied();
|
||||
let at = self.float_space.record_content(at, panel.clone(), child.min_rect().height(), rect.height());
|
||||
self.contents.insert(panel.clone(), at);
|
||||
// Any button: a canvas pans with the middle button and opens menus with the secondary.
|
||||
if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.any_pressed()) {
|
||||
self.output.focused = Some(panel.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A lone protected panel draws no tab strip and no drag bar.
|
||||
pub(in crate::docking) fn stripless<P>(panels: &[P], content: &dyn DockContent<P>) -> bool {
|
||||
match panels {
|
||||
[panel] => content.permissions(panel).is_protected(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Size policy of a subtree, shared by the renderer and its measurements.
|
||||
pub(in crate::docking) fn node_limits<P>(node: &Node<P>, style: &DockStyle, content: &dyn DockContent<P>) -> PanelLimits {
|
||||
match node {
|
||||
Node::Dock { columns, .. } => {
|
||||
let width: f32 = columns.iter().map(|c| dock::column_width(c, style)).sum();
|
||||
PanelLimits { min: vec2(width.clamp(style.min_pane, 1_000_000.0), style.min_pane), ..PanelLimits::default() }
|
||||
}
|
||||
// A group is as large as its largest panel allows: a panel without a maximum lifts the
|
||||
// maximum of the panels it joins.
|
||||
Node::Tabs { panels, .. } => {
|
||||
let mut limits = PanelLimits { min: Vec2::ZERO, max: if panels.is_empty() { PanelLimits::default().max } else { Vec2::ZERO } };
|
||||
for panel in panels {
|
||||
let policy = content.limits(panel);
|
||||
limits.min = limits.min.max(policy.min).max(Vec2::splat(style.min_pane));
|
||||
limits.max = limits.max.max(policy.max);
|
||||
}
|
||||
limits.max = limits.max.max(limits.min);
|
||||
if !stripless(panels, content) {
|
||||
limits.min.y = (limits.min.y + style.tab_height).min(1_000_000.0);
|
||||
limits.max.y = (limits.max.y + style.tab_height).min(1_000_000.0);
|
||||
}
|
||||
limits
|
||||
}
|
||||
Node::Stack { entries } => {
|
||||
let mut limits = PanelLimits::default();
|
||||
if !entries.is_empty() {
|
||||
limits.max.x = 0.0;
|
||||
}
|
||||
for entry in entries {
|
||||
let policy = content.limits(&entry.panel);
|
||||
limits.min.x = limits.min.x.max(policy.min.x).max(style.min_pane);
|
||||
limits.min.y += if entry.open { policy.min.y.max(style.min_pane) } else { 0.0 } + style.tab_height;
|
||||
limits.max.x = limits.max.x.max(policy.max.x);
|
||||
}
|
||||
limits.min = limits.min.min(Vec2::splat(1_000_000.0));
|
||||
limits.max = limits.max.max(limits.min);
|
||||
limits
|
||||
}
|
||||
Node::Split { axis, first, second, .. } => {
|
||||
let a = node_limits(first, style, content);
|
||||
let b = node_limits(second, style, content);
|
||||
let limits = match axis {
|
||||
SplitAxis::Horizontal => PanelLimits {
|
||||
min: vec2(a.min.x + b.min.x + style.gap, a.min.y.max(b.min.y)),
|
||||
max: vec2(a.max.x + b.max.x + style.gap, a.max.y.min(b.max.y)),
|
||||
},
|
||||
SplitAxis::Vertical => PanelLimits {
|
||||
min: vec2(a.min.x.max(b.min.x), a.min.y + b.min.y + style.gap),
|
||||
max: vec2(a.max.x.min(b.max.x), a.max.y + b.max.y + style.gap),
|
||||
},
|
||||
};
|
||||
PanelLimits { min: limits.min.min(Vec2::splat(1_000_000.0)), max: limits.max.max(limits.min).min(Vec2::splat(1_000_000.0)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clamp_float(rect: Rect, screen: Rect) -> Rect {
|
||||
crate::docking::chrome::clamp(rect, screen)
|
||||
}
|
||||
|
||||
pub(super) fn split_bounds(available: f32, axis: SplitAxis, first: PanelLimits, second: PanelLimits) -> (f32, f32) {
|
||||
let (a_min, a_max, b_min, b_max) = match axis {
|
||||
SplitAxis::Horizontal => (first.min.x, first.max.x, second.min.x, second.max.x),
|
||||
SplitAxis::Vertical => (first.min.y, first.max.y, second.min.y, second.max.y),
|
||||
};
|
||||
let scale = if a_min + b_min > available { available / (a_min + b_min).max(1.0) } else { 1.0 };
|
||||
let lo = (a_min * scale).min(available);
|
||||
let hi = (available - b_min * scale).max(lo).min(available);
|
||||
let constrained_lo = lo.max(available - b_max);
|
||||
let constrained_hi = hi.min(a_max);
|
||||
if constrained_lo <= constrained_hi { (constrained_lo, constrained_hi) } else { (lo, hi) }
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Floating windows in their own OS windows (feature `native-windows`). A window with a native
|
||||
//! rect is drawn with `show_viewport_immediate` where the backend has viewports; where egui
|
||||
//! embeds viewports (wasm, tests) it stays in-window at its in-window rect. Tabs and groups do
|
||||
//! not drag between OS windows.
|
||||
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Pos2, Rect, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId, vec2};
|
||||
|
||||
use super::{Renderer, clamp_float, group::TabGroup};
|
||||
use crate::docking::{Action, Drag, Floating, GroupDrag};
|
||||
|
||||
/// Smallest and largest native window, and the farthest it may sit from the desktop origin.
|
||||
const MIN_SIZE: [f32; 2] = [160.0, 100.0];
|
||||
const MAX_SIZE: f32 = 16_384.0;
|
||||
const MAX_POSITION: f32 = 100_000.0;
|
||||
|
||||
/// A rect safe to hand to the windowing system: finite, its size and position bounded.
|
||||
/// Hostile workspace files and bad monitor reports included.
|
||||
pub(super) fn sanitized(rect: [f32; 4]) -> [f32; 4] {
|
||||
let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback };
|
||||
let [x, y, w, h] = rect;
|
||||
[
|
||||
finite(x, 0.0).clamp(-MAX_POSITION, MAX_POSITION),
|
||||
finite(y, 0.0).clamp(-MAX_POSITION, MAX_POSITION),
|
||||
finite(w, 420.0).clamp(MIN_SIZE[0], MAX_SIZE),
|
||||
finite(h, 320.0).clamp(MIN_SIZE[1], MAX_SIZE),
|
||||
]
|
||||
}
|
||||
|
||||
/// The desktop rect a native viewport reports: outer position, inner size. None when the
|
||||
/// backend reports nothing usable.
|
||||
fn placed(outer: Option<Rect>, inner: Option<Rect>) -> Option<[f32; 4]> {
|
||||
let (outer, inner) = (outer?, inner?);
|
||||
(outer.min.is_finite() && inner.size().is_finite()).then(|| sanitized([outer.min.x, outer.min.y, inner.width(), inner.height()]))
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
/// Show the native windows and return the windows to draw in-window.
|
||||
pub(super) fn native_windows<'w>(&mut self, ctx: &Context, windows: Vec<&'w Floating<P>>) -> Vec<&'w Floating<P>> {
|
||||
let native = !ctx.embed_viewports();
|
||||
let mut shown = Vec::new();
|
||||
let mut in_window = Vec::new();
|
||||
for window in windows {
|
||||
match window.native {
|
||||
Some(rect) if native && window.panels().all(|p| self.content.allow_native(p)) => {
|
||||
if let Some(id) = self.native_window(ctx, window, rect) {
|
||||
shown.push(id);
|
||||
}
|
||||
}
|
||||
_ => in_window.push(window),
|
||||
}
|
||||
}
|
||||
// Forget where windows that are no longer native were told to open.
|
||||
let key = self.id.with("native-shown");
|
||||
let previous = ctx.data_mut(|d| d.remove_temp::<Vec<egui::Id>>(key)).unwrap_or_default();
|
||||
ctx.data_mut(|d| {
|
||||
for id in previous.iter().filter(|id| !shown.contains(id)) {
|
||||
d.remove::<[f32; 4]>(*id);
|
||||
}
|
||||
d.insert_temp(key, shown);
|
||||
});
|
||||
in_window
|
||||
}
|
||||
|
||||
/// One floating window in its own viewport. Returns the key of its spawn rect.
|
||||
fn native_window(&mut self, ctx: &Context, window: &Floating<P>, rect: [f32; 4]) -> Option<egui::Id> {
|
||||
let first = window.panels().next()?.clone();
|
||||
let viewport = ViewportId::from_hash_of((self.id, "native", &first));
|
||||
// The window opens at its saved rect; after that the window system owns its position
|
||||
// and size, which are read back below.
|
||||
let spawn_key = self.id.with(("native-spawn", &first));
|
||||
let spawn = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(spawn_key, || sanitized(rect)));
|
||||
let title = crate::docking::dock_model::first_active(&window.root).map(|p| self.label_of(p)).unwrap_or_default();
|
||||
let builder = ViewportBuilder::default()
|
||||
.with_title(title)
|
||||
.with_position([spawn[0], spawn[1]])
|
||||
.with_inner_size([spawn[2], spawn[3]])
|
||||
.with_min_inner_size(MIN_SIZE);
|
||||
if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) {
|
||||
ctx.send_viewport_cmd_to(viewport, ViewportCommand::Focus);
|
||||
}
|
||||
let (targets, windows) = (self.targets.len(), self.frame.windows.len());
|
||||
let (closed, placed) = ctx.show_viewport_immediate(viewport, builder, |ui, class| {
|
||||
let rect = ui.max_rect();
|
||||
ui.painter().rect_filled(rect, 0.0, self.style.floating_background);
|
||||
self.floating_body(ui, window, rect, rect);
|
||||
// An embedded fallback reads the main window's input: its close request and place
|
||||
// are not this window's.
|
||||
if matches!(class, ViewportClass::Immediate | ViewportClass::Deferred) {
|
||||
ui.input(|i| (i.viewport().close_requested(), placed(i.viewport().outer_rect, i.viewport().inner_rect)))
|
||||
} else {
|
||||
(false, None)
|
||||
}
|
||||
});
|
||||
// Targets in another OS window are in its coordinates, and no drag crosses windows.
|
||||
self.targets.truncate(targets);
|
||||
self.frame.windows.truncate(windows);
|
||||
ctx.data_mut(|d| {
|
||||
if d.get_temp::<Drag<P>>(self.id.with("drag")).is_some_and(|drag| window.contains(&drag.panel)) {
|
||||
d.remove::<Drag<P>>(self.id.with("drag"));
|
||||
}
|
||||
if d.get_temp::<GroupDrag<P>>(self.id.with("group-drag")).is_some_and(|drag| window.contains(&drag.panel)) {
|
||||
d.remove::<GroupDrag<P>>(self.id.with("group-drag"));
|
||||
}
|
||||
});
|
||||
if closed {
|
||||
ctx.data_mut(|d| d.remove::<[f32; 4]>(spawn_key));
|
||||
self.output.actions.push(Action::SetNative { panel: first, rect: None });
|
||||
return None;
|
||||
}
|
||||
if let Some(placed) = placed.filter(|placed| placed.iter().zip(rect).any(|(a, b)| (a - b).abs() > 0.5)) {
|
||||
self.output.actions.push(Action::SetNative { panel: first, rect: Some(placed) });
|
||||
}
|
||||
Some(spawn_key)
|
||||
}
|
||||
|
||||
/// Move Panel to New Window: a floating panel's window, or the panel floated on its own.
|
||||
pub(super) fn new_window_item(&mut self, ui: &mut egui::Ui, owner: &TabGroup<'_, P>, panel: &P) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if ctx.embed_viewports() {
|
||||
return;
|
||||
}
|
||||
let window = self.layout.floating.iter().find(|w| w.contains(panel));
|
||||
if window.is_some_and(|w| w.native.is_some()) {
|
||||
return;
|
||||
}
|
||||
let movers: Vec<P> = window.map_or_else(|| vec![panel.clone()], |w| w.panels().cloned().collect());
|
||||
let allowed = |p: &P| self.content.allow_native(p) && self.permissions(p).floatable && self.permissions(p).movable;
|
||||
if !movers.iter().all(allowed) {
|
||||
return;
|
||||
}
|
||||
let in_window = match window {
|
||||
Some(window) => window.rect,
|
||||
None => {
|
||||
let size = self.float_size(panel, owner.rect.size());
|
||||
let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), self.float_bounds);
|
||||
[rect.left(), rect.top(), rect.width(), rect.height()]
|
||||
}
|
||||
};
|
||||
if !self.menu_action(ui, &self.style.new_window_label.clone()) {
|
||||
return;
|
||||
}
|
||||
// Over the panel's place in the app window: its content's position on the desktop.
|
||||
let origin = ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(Pos2::ZERO);
|
||||
let [x, y, w, h] = in_window;
|
||||
if window.is_none() {
|
||||
self.output.actions.push(Action::Float { panel: panel.clone(), rect: in_window });
|
||||
}
|
||||
let native = sanitized([origin.x + x, origin.y + y, w, h]);
|
||||
self.output.actions.push(Action::SetNative { panel: panel.clone(), rect: Some(native) });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
use std::{collections::HashMap, fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Key, Pos2, Rect, Ui, Vec2, pos2, vec2};
|
||||
|
||||
use super::{DROP_MARGIN, Drawn, Renderer, clamp_float, dock::group_action};
|
||||
use crate::docking::chrome::drop_preview;
|
||||
use crate::docking::{
|
||||
Action, Drag, DropProposal, DropRequest, DropTarget, GroupDrag, GroupGesture, Layout, Node, Placement, Target, Zone, cancel_drag,
|
||||
dock_model::Place, resolve_drop, surface::TAB_PADDING,
|
||||
};
|
||||
|
||||
/// Ctrl (Windows, Linux) or Cmd (macOS) held: the drop floats and no target is offered.
|
||||
fn float_only(ctx: &Context) -> bool {
|
||||
ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.mac_cmd)
|
||||
}
|
||||
|
||||
/// Height of a panel floated out of a dock column when the host gives no floating size.
|
||||
const DOCKED_FLOAT_HEIGHT: f32 = 320.0;
|
||||
|
||||
/// Least height of a floating window or flyout fitted to a short panel's content.
|
||||
pub(super) const MIN_FITTED_HEIGHT: f32 = 120.0;
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Renderer<'_, P> {
|
||||
pub(in crate::docking) fn finish_group_drag(&mut self, ui: &Ui) {
|
||||
let ctx = ui.ctx();
|
||||
let key = self.id.with("group-drag");
|
||||
let Some(drag) = ctx.data(|d| d.get_temp::<GroupDrag<P>>(key)) else { return };
|
||||
if !drag.members.iter().all(|p| self.layout.contains(p) && self.permissions(p).movable) {
|
||||
ctx.data_mut(|d| d.remove::<GroupDrag<P>>(key));
|
||||
return;
|
||||
}
|
||||
let (escape, focused, down, released, pointer) =
|
||||
ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos()));
|
||||
let pointer = pointer.filter(|p| p.is_finite());
|
||||
let ghost = pointer.map(|pointer| self.group_ghost(&drag, pointer));
|
||||
if !escape
|
||||
&& focused
|
||||
&& (down || released)
|
||||
&& let Some(pointer) = pointer
|
||||
&& !self.blockers.iter().any(|r| r.contains(pointer))
|
||||
&& self.host_drop(ctx, &drag.panel, pointer, true, released, ghost.filter(|_| drag.gesture != GroupGesture::Window))
|
||||
{
|
||||
if released {
|
||||
ctx.data_mut(|d| d.remove::<GroupDrag<P>>(key));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A button release outside the window may never reach egui.
|
||||
let has_pointer = ctx.input(|i| i.pointer.has_pointer());
|
||||
// Touch-up also removes the pointer, but still completes a drop.
|
||||
let touch_ended = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::End, .. })));
|
||||
let float_only = float_only(ctx);
|
||||
if escape || !focused || !down || !has_pointer {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
if escape || !focused {
|
||||
if drag.gesture == GroupGesture::Window {
|
||||
self.output.actions.push(Action::MoveFloating { panel: drag.panel, rect: drag.original });
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Leaving the window ends a group drag where it is, with no drop, unless only a
|
||||
// release outside the window floats.
|
||||
let gone = !has_pointer && !touch_ended;
|
||||
let floats_outside = !self.style.float_on_empty_drop && drag.gesture != GroupGesture::Window;
|
||||
if !(released && !gone) && !(gone && floats_outside) {
|
||||
return;
|
||||
}
|
||||
let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return };
|
||||
let outside = gone || !ctx.content_rect().contains(pointer);
|
||||
match drag.gesture {
|
||||
GroupGesture::Window => self.drop_window(&drag, pointer, float_only),
|
||||
GroupGesture::Group | GroupGesture::Column => self.drop_group(&drag, pointer, float_only || outside),
|
||||
}
|
||||
} else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) {
|
||||
self.output.group_drag = Some(drag.panel.clone());
|
||||
self.paint_group_drag(ui, &drag, pointer, float_only);
|
||||
}
|
||||
}
|
||||
|
||||
/// The valid target under the pointer for a whole group. A target holding the group
|
||||
/// itself is a no-op proposal; a target the model would reject is no target. A window
|
||||
/// moving live looks through itself and does not split frames or join a body's center.
|
||||
pub(super) fn group_proposal(&self, drag: &GroupDrag<P>, pointer: Pos2) -> Option<DropProposal<P>> {
|
||||
let window = drag.gesture == GroupGesture::Window;
|
||||
if let Some(proposal) = self.extra_proposal(&drag.members, pointer, window) {
|
||||
return self.valid_group(drag, proposal);
|
||||
}
|
||||
let target = self.group_target(drag, pointer)?;
|
||||
self.group_proposal_at(drag, pointer, target)
|
||||
}
|
||||
|
||||
/// The group under the pointer that a group drag addresses. A window moving live looks
|
||||
/// through itself.
|
||||
fn group_target(&self, drag: &GroupDrag<P>, pointer: Pos2) -> Option<&DropTarget<P>> {
|
||||
let window = drag.gesture == GroupGesture::Window;
|
||||
let own = |t: &DropTarget<P>| t.tabs.iter().any(|(p, _)| drag.members.contains(p));
|
||||
self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer) && !(window && own(t)))
|
||||
}
|
||||
|
||||
/// [`Self::group_proposal`] on `target` alone.
|
||||
fn group_proposal_at(&self, drag: &GroupDrag<P>, pointer: Pos2, target: &DropTarget<P>) -> Option<DropProposal<P>> {
|
||||
let window = drag.gesture == GroupGesture::Window;
|
||||
if target.tabs.iter().any(|(p, _)| drag.members.contains(p)) {
|
||||
return Some(DropProposal {
|
||||
anchor: drag.panel.clone(),
|
||||
placement: Placement::Tab { before: None },
|
||||
preview: target.rect,
|
||||
insertion: None,
|
||||
noop: true,
|
||||
});
|
||||
}
|
||||
let proposal = self.resolve_roomy(&drag.panel, pointer, std::slice::from_ref(target), |to| group_action(drag, to))?;
|
||||
// A window moving live splits only groups of other floating windows.
|
||||
let into_window = matches!(self.place(&proposal.anchor), Some(Place::Floating { .. }));
|
||||
if window && !into_window && matches!(proposal.placement, Placement::Split(_)) {
|
||||
return None;
|
||||
}
|
||||
self.valid_group(drag, proposal)
|
||||
}
|
||||
|
||||
/// `proposal` when it is a no-op or the model takes it for the whole group.
|
||||
fn valid_group(&self, drag: &GroupDrag<P>, proposal: DropProposal<P>) -> Option<DropProposal<P>> {
|
||||
let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() };
|
||||
(proposal.noop || self.layout.clone().apply_with_permissions(group_action(drag, to), |p| self.permissions(p)).is_ok()).then_some(proposal)
|
||||
}
|
||||
|
||||
/// [`resolve_drop`], where a split that would leave a group without room becomes a join
|
||||
/// of the target group.
|
||||
fn resolve_roomy(&self, panel: &P, pointer: Pos2, targets: &[DropTarget<P>], action: impl Fn(Target<P>) -> Action<P>) -> Option<DropProposal<P>> {
|
||||
let proposal = resolve_drop(panel, pointer, targets, self.style.zone_depth)?;
|
||||
if !matches!(proposal.placement, Placement::Split(zone) if zone != Zone::Center) {
|
||||
return Some(proposal);
|
||||
}
|
||||
if self.leaves_room(action(Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() })) {
|
||||
return Some(proposal);
|
||||
}
|
||||
let target = targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer))?;
|
||||
resolve_drop(panel, pointer, std::slice::from_ref(&DropTarget { allow_splits: false, ..target.clone() }), self.style.zone_depth)
|
||||
}
|
||||
|
||||
/// Whether `action`, a drop that splits a group or the outer edge, leaves room: every group
|
||||
/// it makes smaller stays [`DROP_MARGIN`] above its minimum, so each divider can still
|
||||
/// travel both ways. An action the model rejects is left to the model's check.
|
||||
pub(super) fn leaves_room(&self, action: Action<P>) -> bool {
|
||||
let mut candidate = self.layout.clone();
|
||||
if candidate.apply_with_permissions(action, |p| self.permissions(p)).is_err() {
|
||||
return true;
|
||||
}
|
||||
let sizer = self.sizer();
|
||||
let drawn = |layout: &Layout<P>| {
|
||||
let mut out: Vec<Drawn<'_, P>> = Vec::new();
|
||||
if let Some(root) = &layout.root {
|
||||
sizer.groups(root, self.workspace, &mut out);
|
||||
}
|
||||
for window in layout.floating.iter().filter(|w| !w.minimized) {
|
||||
sizer.groups(&window.root, self.window_body(window), &mut out);
|
||||
}
|
||||
out.into_iter().filter_map(|d| Some((lead(d.node)?.clone(), d.rect.size(), d.limits.min))).collect::<Vec<_>>()
|
||||
};
|
||||
let before: HashMap<P, Vec2> = drawn(self.layout).into_iter().map(|(panel, size, _)| (panel, size)).collect();
|
||||
drawn(&candidate).into_iter().all(|(panel, size, min)| {
|
||||
let room = size - min;
|
||||
(room.x >= DROP_MARGIN && room.y >= DROP_MARGIN) || before.get(&panel).is_some_and(|old| size.x >= old.x - 0.5 && size.y >= old.y - 0.5)
|
||||
})
|
||||
}
|
||||
|
||||
/// Release of a group drag: join or split at the target, or float at the ghost with the
|
||||
/// group's size. Over its own docked position nothing changes; a floating group released
|
||||
/// over itself moves there.
|
||||
fn drop_group(&mut self, drag: &GroupDrag<P>, pointer: Pos2, float_only: bool) {
|
||||
if pointer.distance(drag.origin) < 2.0 {
|
||||
return;
|
||||
}
|
||||
if !float_only && let Some((action, _)) = self.dock_group_proposal(drag, pointer) {
|
||||
self.output.actions.extend(action);
|
||||
return;
|
||||
}
|
||||
let floating = matches!(self.place(&drag.panel), Some(Place::Floating { .. }));
|
||||
let proposal = if float_only { None } else { self.group_proposal(drag, pointer) };
|
||||
if let Some(proposal) = proposal.as_ref().filter(|p| !p.noop) {
|
||||
let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() };
|
||||
self.output.actions.push(group_action(drag, to));
|
||||
return;
|
||||
}
|
||||
if proposal.is_some() && !floating {
|
||||
return;
|
||||
}
|
||||
if !float_only && !self.style.float_on_empty_drop {
|
||||
return;
|
||||
}
|
||||
// No target: hosts that still apply their own policy for a whole-group release get it.
|
||||
self.output.group_drop = Some((drag.panel.clone(), pointer));
|
||||
let rect = self.group_ghost(drag, pointer);
|
||||
let action = group_action(drag, Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) });
|
||||
if self.layout.clone().apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() {
|
||||
self.output.actions.push(action);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ghost at the pointer (a window moving live is its own ghost) under one destination
|
||||
/// preview. The ghost has a translucent fill, a 2 pt outline and the members' labels.
|
||||
fn paint_group_drag(&mut self, ui: &Ui, drag: &GroupDrag<P>, pointer: Pos2, float_only: bool) {
|
||||
let ctx = ui.ctx();
|
||||
let painter = self.preview_painter(ctx);
|
||||
if drag.gesture != GroupGesture::Window {
|
||||
let ghost = self.group_ghost(drag, pointer);
|
||||
drop_preview(&painter, ghost, self.style.accent, true);
|
||||
let strip = Rect::from_min_size(ghost.min, vec2(ghost.width(), self.style.tab_height.min(ghost.height())));
|
||||
let labels = painter.with_clip_rect(strip.shrink(2.0));
|
||||
let mut x = strip.left() + TAB_PADDING * 0.5;
|
||||
for panel in &drag.members {
|
||||
let width = strip.right() - TAB_PADDING * 0.5 - x;
|
||||
if width <= 0.0 {
|
||||
break;
|
||||
}
|
||||
let label = self.label_of(panel);
|
||||
let galley = self.tab_label(ui, panel, &label, self.style.text, width);
|
||||
let advance = galley.size().x + TAB_PADDING;
|
||||
labels.galley(pos2(x, strip.center().y - galley.size().y * 0.5), galley, self.style.text);
|
||||
x += advance;
|
||||
}
|
||||
}
|
||||
if float_only || (drag.gesture == GroupGesture::Window && !self.style.title_bar_docks) {
|
||||
return;
|
||||
}
|
||||
if let Some((action, line)) = self.dock_group_proposal(drag, pointer) {
|
||||
if action.is_some() {
|
||||
self.paint_dock_line(ctx, line);
|
||||
self.paint_float_hint(ctx, pointer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let proposal = self.group_proposal(drag, pointer).filter(|p| !p.noop);
|
||||
let zones = self.paint_group_zones(&painter, drag, pointer, proposal.as_ref());
|
||||
if let Some(proposal) = proposal {
|
||||
let split = matches!(proposal.placement, Placement::Split(zone) | Placement::Edge(zone) if zone != Zone::Center);
|
||||
if crate::docking::targets::usable(proposal.preview) && !zones {
|
||||
drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, split);
|
||||
}
|
||||
if let Some(marker) = proposal.insertion {
|
||||
painter.rect_filled(marker, 0.0, self.style.accent);
|
||||
}
|
||||
if drag.gesture != GroupGesture::Window {
|
||||
self.paint_float_hint(ctx, pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::docking) fn finish_drag(&mut self, ctx: &Context) {
|
||||
let Some(drag) = ctx.data(|d| d.get_temp::<Drag<P>>(self.id.with("drag"))) else { return };
|
||||
let (pointer, down, released, focused, gone) =
|
||||
ctx.input(|i| (i.pointer.interact_pos(), i.pointer.primary_down(), i.pointer.primary_released(), i.focused, !i.pointer.has_pointer()));
|
||||
// Leaving the window is the drop: on X11 and Windows the release outside never reaches
|
||||
// egui, so the drag would otherwise stay on the pointer. `interact_pos` still holds the
|
||||
// last position this frame, and the panel floats there rather than docking at the edge.
|
||||
let released = released || gone;
|
||||
let escape = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape));
|
||||
if escape || !focused || !self.layout.contains(&drag.panel) || (!down && !released) {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
return;
|
||||
}
|
||||
let Some(pointer) = pointer.filter(|p| p.is_finite()) else {
|
||||
if released {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
}
|
||||
return;
|
||||
};
|
||||
if self.blockers.iter().any(|rect| rect.contains(pointer)) {
|
||||
if released {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let float_only = float_only(ctx) || drag.undock;
|
||||
let outside = gone || !ctx.content_rect().contains(pointer);
|
||||
let empty_drop =
|
||||
self.style.float_on_empty_drop && (!drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel)));
|
||||
let floatable = self.permissions(&drag.panel).floatable && (float_only || outside || empty_drop);
|
||||
let floating_rect = floatable.then(|| self.tab_float_rect(&drag, pointer));
|
||||
if self.host_drop(ctx, &drag.panel, pointer, false, released, floating_rect) {
|
||||
if released {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let dock = if float_only || outside { None } else { self.dock_tab_proposal(&drag.panel, pointer) };
|
||||
if let Some((action, line)) = dock {
|
||||
if released {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
if let Some(action) = action.filter(|_| pointer.distance(drag.origin) >= 2.0) {
|
||||
self.output.actions.push(action);
|
||||
self.output.focused = Some(drag.panel);
|
||||
}
|
||||
} else if action.is_some() {
|
||||
self.paint_dock_line(ctx, line);
|
||||
self.paint_float_hint(ctx, pointer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let proposal = if float_only { None } else { self.tab_proposal(&drag.panel, pointer) };
|
||||
if released {
|
||||
cancel_drag::<P>(ctx, self.id);
|
||||
if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !outside) {
|
||||
return;
|
||||
}
|
||||
let action = if let Some(proposal) = proposal.filter(|_| !outside) {
|
||||
Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement })
|
||||
} else if let Some(rect) = floating_rect {
|
||||
Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(action) = action {
|
||||
// Validate the proposed gesture against the same complete snapshot. The app
|
||||
// still applies it via its own command path after body rendering finishes.
|
||||
let mut candidate = self.layout.clone();
|
||||
if candidate.apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() {
|
||||
self.output.actions.push(action);
|
||||
self.output.focused = Some(drag.panel);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let painter = self.preview_painter(ctx);
|
||||
let zones = !float_only && self.paint_tab_zones(&painter, &drag.panel, pointer, proposal.as_ref());
|
||||
if let Some(proposal) = proposal {
|
||||
// Reordering inside the source strip shows only the insertion line.
|
||||
let same_group = proposal.insertion.is_some()
|
||||
&& self.targets.iter().any(|target| target.rect == proposal.preview && target.tabs.iter().any(|(panel, _)| panel == &drag.panel));
|
||||
if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) && !zones {
|
||||
drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, true);
|
||||
}
|
||||
if let Some(marker) = proposal.insertion {
|
||||
painter.rect_filled(marker, 0.0, self.style.accent);
|
||||
}
|
||||
if !proposal.noop {
|
||||
self.paint_float_hint(ctx, pointer);
|
||||
}
|
||||
} else if let Some(rect) = floating_rect {
|
||||
drop_preview(&painter, rect, self.style.accent, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// The group target a single tab drag would take at `pointer`.
|
||||
pub(super) fn tab_proposal(&self, panel: &P, pointer: Pos2) -> Option<DropProposal<P>> {
|
||||
self.extra_proposal(std::slice::from_ref(panel), pointer, false).or_else(|| {
|
||||
self.resolve_roomy(panel, pointer, &self.targets, |to| match to {
|
||||
Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement },
|
||||
to => Action::MovePanel { panel: panel.clone(), to },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// [`Self::paint_zones`] for a tab drag of `panel`. The center of the group holding the panel
|
||||
/// is not a target: a drop there reorders or changes nothing.
|
||||
pub(super) fn paint_tab_zones(&self, painter: &egui::Painter, panel: &P, pointer: Pos2, proposal: Option<&DropProposal<P>>) -> bool {
|
||||
if !self.style.side_edge_zones || self.extra_proposal(std::slice::from_ref(panel), pointer, false).is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(target) = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer)) else {
|
||||
return false;
|
||||
};
|
||||
let own = target.tabs.iter().any(|(p, _)| p == panel);
|
||||
let at = |at: Pos2| {
|
||||
let move_to = |to| match to {
|
||||
Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement },
|
||||
to => Action::MovePanel { panel: panel.clone(), to },
|
||||
};
|
||||
let proposal = self.resolve_roomy(panel, at, std::slice::from_ref(target), move_to)?;
|
||||
let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() };
|
||||
let joins = matches!(proposal.placement, Placement::Tab { .. } | Placement::Split(Zone::Center));
|
||||
(!(own && joins) && self.layout.clone().apply_with_permissions(move_to(to), |p| self.permissions(p)).is_ok()).then_some(proposal)
|
||||
};
|
||||
self.paint_zones(painter, target, proposal, at)
|
||||
}
|
||||
|
||||
/// [`Self::paint_zones`] for a group drag.
|
||||
pub(super) fn paint_group_zones(&self, painter: &egui::Painter, drag: &GroupDrag<P>, pointer: Pos2, proposal: Option<&DropProposal<P>>) -> bool {
|
||||
let window = drag.gesture == GroupGesture::Window;
|
||||
if !self.style.side_edge_zones || self.extra_proposal(&drag.members, pointer, window).is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(target) = self.group_target(drag, pointer) else { return false };
|
||||
self.paint_zones(painter, target, proposal, |at| self.group_proposal_at(drag, at, target))
|
||||
}
|
||||
|
||||
/// With [`crate::docking::DockStyle::side_edge_zones`], a drag over a group outlines each
|
||||
/// of its drop zones that a drop would change something in (a side's trapezoid, the center
|
||||
/// rectangle, the tab strip as part of the center) and fills the zone of `proposal`, the
|
||||
/// drop under the pointer. `at` is the drop a point of `target` would get. False when it
|
||||
/// painted nothing.
|
||||
fn paint_zones(
|
||||
&self,
|
||||
painter: &egui::Painter,
|
||||
target: &DropTarget<P>,
|
||||
proposal: Option<&DropProposal<P>>,
|
||||
at: impl Fn(Pos2) -> Option<DropProposal<P>>,
|
||||
) -> bool {
|
||||
use crate::docking::targets::{header_height, usable, zone_shape};
|
||||
let zone_of = |proposal: &DropProposal<P>| match proposal.placement {
|
||||
_ if proposal.noop => None,
|
||||
Placement::Split(zone) => Some(zone),
|
||||
Placement::Tab { .. } => Some(Zone::Center),
|
||||
_ => None,
|
||||
};
|
||||
let header = header_height(target);
|
||||
let centroid = |points: &[Pos2]| points.iter().fold(Vec2::ZERO, |sum, p| sum + p.to_vec2()) / points.len() as f32;
|
||||
let takes = |zone: Zone, point: Pos2| at(point).as_ref().and_then(zone_of) == Some(zone);
|
||||
let mut shapes: Vec<(Zone, Vec<Pos2>)> = [Zone::Left, Zone::Right, Zone::Top, Zone::Bottom, Zone::Center]
|
||||
.into_iter()
|
||||
.filter_map(|zone| Some((zone, zone_shape(target.rect, header, self.style.zone_depth, zone)?)))
|
||||
.filter(|(zone, points)| takes(*zone, centroid(points).to_pos2()))
|
||||
.collect();
|
||||
let strip = target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|strip| usable(*strip) && takes(Zone::Center, strip.center()));
|
||||
if let Some(strip) = strip {
|
||||
shapes.push((Zone::Center, vec![strip.left_top(), strip.right_top(), strip.right_bottom(), strip.left_bottom()]));
|
||||
}
|
||||
if shapes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let hovered = proposal.and_then(zone_of);
|
||||
let fill = self.style.accent.gamma_multiply(0.3);
|
||||
for (_, points) in shapes.iter().filter(|(zone, _)| Some(*zone) == hovered) {
|
||||
painter.add(egui::Shape::convex_polygon(points.clone(), fill, egui::Stroke::NONE));
|
||||
}
|
||||
let stroke = egui::Stroke::new(1.0, self.style.accent.gamma_multiply(0.6));
|
||||
for (_, points) in shapes {
|
||||
painter.add(egui::Shape::closed_line(points, stroke));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The single drop preview layer, above every floating window.
|
||||
pub(super) fn preview_painter(&self, ctx: &Context) -> egui::Painter {
|
||||
let layer = egui::LayerId::new(egui::Order::Tooltip, self.id.with("drop-preview"));
|
||||
ctx.move_to_top(layer);
|
||||
ctx.layer_painter(layer)
|
||||
}
|
||||
|
||||
/// Size of a panel floated by a drag or the Float menu: the host's floating size, else the
|
||||
/// source size within the panel limits. Out of a dock or frame, or with a floating size, the
|
||||
/// height fits the content the panel last drew, up to that height (else 320). Content that
|
||||
/// filled its body floats at that height.
|
||||
pub(super) fn float_size(&self, panel: &P, source: Vec2) -> Vec2 {
|
||||
let chrome = self.style.title_height + self.style.tab_height;
|
||||
if let Some(size) = self.content.floating_size(panel).filter(|s| s.is_finite() && s.x > 0.0 && s.y > 0.0) {
|
||||
return vec2(size.x, self.fitted_height(panel, chrome, size.y).unwrap_or(size.y));
|
||||
}
|
||||
let mut size = self.iconic.float_width(panel).map_or(source, |width| vec2(width, DOCKED_FLOAT_HEIGHT));
|
||||
if matches!(self.place(panel), Some(Place::Dock { .. } | Place::Node(_))) {
|
||||
size.y = match self.fitted_height(panel, chrome, DOCKED_FLOAT_HEIGHT) {
|
||||
Some(height) => height,
|
||||
None if self.content_height(panel) == Some(None) => DOCKED_FLOAT_HEIGHT,
|
||||
None => size.y.min(DOCKED_FLOAT_HEIGHT),
|
||||
};
|
||||
}
|
||||
let limits = self.limits(panel);
|
||||
let header = vec2(0.0, self.style.tab_height);
|
||||
size.max(limits.min + header).min(limits.max + header)
|
||||
}
|
||||
|
||||
/// Height of a window around `panel`'s group: `chrome` (title bar and tab strip) and the
|
||||
/// content height the panel last drew, at least [`MIN_FITTED_HEIGHT`] and at most `max`.
|
||||
/// `None` for a panel the area has not drawn.
|
||||
pub(super) fn fitted_height(&self, panel: &P, chrome: f32, max: f32) -> Option<f32> {
|
||||
let content = self.content_height(panel).flatten()?;
|
||||
Some((chrome + content).max(MIN_FITTED_HEIGHT).min(max))
|
||||
}
|
||||
|
||||
/// Record what a drag floats from `panels`, one group drawn at `group` whose panels drag
|
||||
/// from `panel` rects, for commands that float without a rect.
|
||||
pub(super) fn record_float(&mut self, panels: &[P], panel: Vec2, group: Vec2) {
|
||||
let group = self.group_float_size(panels, group);
|
||||
for p in panels {
|
||||
let size = self.float_size(p, panel);
|
||||
self.float_space.panels.push((p.clone(), size));
|
||||
self.float_space.groups.push((p.clone(), group));
|
||||
}
|
||||
}
|
||||
|
||||
/// Record what a drag floats from a dock column drawn at `rect`.
|
||||
pub(super) fn record_column_float(&mut self, members: Vec<P>, rect: Rect) {
|
||||
let size = self.group_float_size(&members, rect.size());
|
||||
self.float_space.columns.extend(members.into_iter().map(|p| (p, size)));
|
||||
}
|
||||
|
||||
/// Size of a group or column floated by a drag or Float Tab Group: the source width, and the
|
||||
/// tallest member's floating height, else the source height capped like a panel leaving a
|
||||
/// dock column. A group fits that height to its active panel's content. A group that already
|
||||
/// floats keeps its size.
|
||||
pub(super) fn group_float_size(&self, members: &[P], source: Vec2) -> Vec2 {
|
||||
let Some(place) = members.first().and_then(|panel| self.place(panel)) else { return source };
|
||||
if matches!(place, Place::Floating { .. }) {
|
||||
return source;
|
||||
}
|
||||
let valid = |s: &Vec2| s.is_finite() && s.x > 0.0 && s.y > 0.0;
|
||||
let host = members.iter().filter_map(|panel| self.content.floating_size(panel).filter(valid)).map(|s| s.y).reduce(f32::max);
|
||||
let docked = matches!(place, Place::Dock { .. });
|
||||
let chrome = self.style.title_height + self.style.tab_height;
|
||||
let max = host.or(docked.then_some(DOCKED_FLOAT_HEIGHT));
|
||||
let fitted = max.and_then(|max| self.group_active(members, place).and_then(|active| self.fitted_height(active, chrome, max)));
|
||||
vec2(source.x, fitted.or(host).unwrap_or(if docked { source.y.min(DOCKED_FLOAT_HEIGHT) } else { source.y }))
|
||||
}
|
||||
|
||||
/// The active panel of the group at `place` when `members` are that whole group.
|
||||
fn group_active<'a>(&'a self, members: &[P], place: &Place) -> Option<&'a P> {
|
||||
let (panels, active) = match place {
|
||||
Place::Node(_) | Place::Floating { .. } => match self.layout.node_of(place) {
|
||||
Some(Node::Tabs { panels, active }) => (panels, *active),
|
||||
_ => return None,
|
||||
},
|
||||
_ => self.layout.group(place).map(|group| (&group.panels, group.active))?,
|
||||
};
|
||||
(panels.len() == members.len() && members.iter().all(|m| panels.contains(m))).then(|| panels.get(active)).flatten()
|
||||
}
|
||||
|
||||
/// Where a group or column drag floats with the pointer at `pointer`, keeping the grab
|
||||
/// offset, inside the window (Z2).
|
||||
fn group_ghost(&self, drag: &GroupDrag<P>, pointer: Pos2) -> Rect {
|
||||
let size = if drag.gesture == GroupGesture::Window { drag.source.size() } else { self.group_float_size(&drag.members, drag.source.size()) };
|
||||
let grab = (drag.origin - drag.source.min).clamp(Vec2::ZERO, size);
|
||||
clamp_float(Rect::from_min_size(pointer - grab, size), self.float_bounds)
|
||||
}
|
||||
|
||||
fn tab_float_rect(&self, drag: &Drag<P>, pointer: Pos2) -> Rect {
|
||||
let size = self.float_size(&drag.panel, drag.source.size());
|
||||
let grab = drag.grab.min(vec2(size.x, self.style.tab_height));
|
||||
clamp_float(Rect::from_min_size(pointer - grab, size), self.float_bounds)
|
||||
}
|
||||
|
||||
/// Offer the gesture to [`crate::docking::DockContent::resolve_drag`]. True when the host
|
||||
/// owns it; its feedback replaces the renderer's preview.
|
||||
pub(super) fn host_drop(
|
||||
&mut self,
|
||||
ctx: &Context,
|
||||
panel: &P,
|
||||
pointer: Pos2,
|
||||
whole_group: bool,
|
||||
released: bool,
|
||||
floating_rect: Option<Rect>,
|
||||
) -> bool {
|
||||
let request = DropRequest {
|
||||
panel,
|
||||
pointer,
|
||||
targets: &self.targets,
|
||||
floating_rect,
|
||||
whole_group,
|
||||
released,
|
||||
workspace: self.workspace,
|
||||
screen: self.float_bounds,
|
||||
};
|
||||
let Some(feedback) = self.content.resolve_drag(ctx, self.style, &request) else { return false };
|
||||
if !released {
|
||||
let painter = self.preview_painter(ctx);
|
||||
if let Some(rect) = feedback.preview.filter(|rect| crate::docking::targets::usable(*rect)) {
|
||||
drop_preview(&painter, rect, self.style.accent, true);
|
||||
}
|
||||
if let Some(rect) = feedback.insertion.filter(|rect| crate::docking::targets::usable(*rect)) {
|
||||
painter.rect_filled(rect, 0.0, self.style.accent);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel that names a drawn group: its first panel; none for a dock or a split.
|
||||
fn lead<P>(node: &Node<P>) -> Option<&P> {
|
||||
match node {
|
||||
Node::Tabs { panels, .. } => panels.first(),
|
||||
Node::Stack { entries } => entries.first().map(|e| &e.panel),
|
||||
Node::Split { .. } | Node::Dock { .. } => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Split-tree geometry: where each split draws its children, how far a divider can travel,
|
||||
//! and the sizes that move a divider.
|
||||
//!
|
||||
//! A dragged divider grows the groups touching it on one side, up to their maximums, and
|
||||
//! shrinks the groups on the other side in turn: the group touching the divider gives way
|
||||
//! down to its minimum, then the next group along the axis, and so on, until every group on
|
||||
//! that side is at its minimum. Groups side by side across the axis shrink together, and the
|
||||
//! line goes on past them once one is at its minimum. The line follows splits of the drag's
|
||||
//! axis up the tree and ends at a split across it or beside a dock. Every other group keeps
|
||||
//! its size.
|
||||
|
||||
use egui::Rect;
|
||||
|
||||
use super::{dock::dock_rects, node_limits, split_bounds};
|
||||
use crate::docking::{DockContent, DockStyle, Node, PanelLimits};
|
||||
use crate::layout::{SplitAxis, SplitLayout, SplitSize, split_rect};
|
||||
|
||||
/// A split's two children with the rects they are drawn in.
|
||||
type Children<'n, P> = [(&'n Node<P>, Rect); 2];
|
||||
|
||||
/// Room a group keeps above its minimum after a drop, so each of its dividers can still
|
||||
/// travel both ways.
|
||||
pub(in crate::docking) const DROP_MARGIN: f32 = 1.0;
|
||||
|
||||
pub(in crate::docking) struct Sizer<'a, P> {
|
||||
pub(in crate::docking) style: &'a DockStyle,
|
||||
pub(in crate::docking) content: &'a dyn DockContent<P>,
|
||||
}
|
||||
|
||||
/// One group as drawn: its node, rect and limits.
|
||||
pub(in crate::docking) struct Drawn<'a, P> {
|
||||
pub(in crate::docking) node: &'a Node<P>,
|
||||
pub(in crate::docking) rect: Rect,
|
||||
pub(in crate::docking) limits: PanelLimits,
|
||||
}
|
||||
|
||||
fn extent(rect: Rect, axis: SplitAxis) -> f32 {
|
||||
match axis {
|
||||
SplitAxis::Horizontal => rect.width(),
|
||||
SplitAxis::Vertical => rect.height(),
|
||||
}
|
||||
}
|
||||
|
||||
fn along(v: egui::Vec2, axis: SplitAxis) -> f32 {
|
||||
match axis {
|
||||
SplitAxis::Horizontal => v.x,
|
||||
SplitAxis::Vertical => v.y,
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Sizer<'_, P> {
|
||||
fn limits(&self, node: &Node<P>) -> PanelLimits {
|
||||
node_limits(node, self.style, self.content)
|
||||
}
|
||||
|
||||
/// The split as drawn: its stored size, clamped so both children fit their limits.
|
||||
pub(in crate::docking) fn split(&self, axis: SplitAxis, size: SplitSize, first: &Node<P>, second: &Node<P>, rect: Rect) -> Option<SplitLayout> {
|
||||
let wanted = split_rect(rect, axis, size, self.style.gap, 0.0)?;
|
||||
let (lo, hi) = split_bounds(wanted.available(), axis, self.limits(first), self.limits(second));
|
||||
split_rect(rect, axis, SplitSize::FixedFirst(wanted.first_size().clamp(lo, hi)), self.style.gap, 0.0)
|
||||
}
|
||||
|
||||
/// The children of a split drawn in `rect`, with their rects; a dock beside its neighbour
|
||||
/// is drawn by the dock renderer.
|
||||
pub(in crate::docking) fn children<'n>(&self, node: &'n Node<P>, rect: Rect) -> Option<[(&'n Node<P>, Rect); 2]> {
|
||||
let Node::Split { axis, size, first, second } = node else { return None };
|
||||
match (&**first, &**second) {
|
||||
(Node::Dock { side, columns }, other) if *axis == SplitAxis::Horizontal => {
|
||||
let (dock, rest, _) = dock_rects(*side, columns, other, rect, self.style, self.content);
|
||||
Some([(first, dock), (second, rest)])
|
||||
}
|
||||
(other, Node::Dock { side, columns }) if *axis == SplitAxis::Horizontal => {
|
||||
let (dock, rest, _) = dock_rects(*side, columns, other, rect, self.style, self.content);
|
||||
Some([(first, rest), (second, dock)])
|
||||
}
|
||||
_ => {
|
||||
let split = self.split(*axis, *size, first, second, rect)?;
|
||||
Some([(first, split.first), (second, split.second)])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every group of `node` drawn in `rect`; a dock counts as one.
|
||||
pub(in crate::docking) fn groups<'n>(&self, node: &'n Node<P>, rect: Rect, out: &mut Vec<Drawn<'n, P>>) {
|
||||
match self.children(node, rect) {
|
||||
Some(children) => children.into_iter().for_each(|(child, rect)| self.groups(child, rect, out)),
|
||||
None => out.push(Drawn { node, rect, limits: self.limits(node) }),
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the end edge (`end`) or start edge of `node` drawn in `rect` can move along
|
||||
/// `axis`: inward until every group along the axis from that edge is at its minimum, and
|
||||
/// outward while the groups touching it stay below their maximums. Groups side by side
|
||||
/// across the axis move together, so the first of them to reach its limit stops them.
|
||||
pub(in crate::docking) fn travel(&self, node: &Node<P>, rect: Rect, axis: SplitAxis, end: bool) -> (f32, f32) {
|
||||
let docked =
|
||||
matches!(node, Node::Split { first, second, .. } if matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. }));
|
||||
match (node, self.children(node, rect)) {
|
||||
(Node::Split { first, .. }, Some([a, b])) if docked => {
|
||||
let (other, rect) = if matches!(**first, Node::Dock { .. }) { b } else { a };
|
||||
self.travel(other, rect, axis, end)
|
||||
}
|
||||
(Node::Split { axis: split_axis, .. }, Some([a, b])) if *split_axis == axis => {
|
||||
let (near, far) = if end { (b, a) } else { (a, b) };
|
||||
let (near, far) = (self.travel(near.0, near.1, axis, end), self.travel(far.0, far.1, axis, end));
|
||||
(near.0 + far.0, near.1)
|
||||
}
|
||||
(_, Some([a, b])) => {
|
||||
let (a, b) = (self.travel(a.0, a.1, axis, end), self.travel(b.0, b.1, axis, end));
|
||||
(a.0.min(b.0), a.1.min(b.1))
|
||||
}
|
||||
(_, None) => {
|
||||
let limits = self.limits(node);
|
||||
let size = extent(rect, axis);
|
||||
((size - along(limits.min, axis)).max(0.0), (along(limits.max, axis) - size).max(0.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sizes that move the end (`end`) or start edge of `node` drawn in `rect` outward by
|
||||
/// `grow` points. Growing, only the groups touching that edge change. Shrinking, the group
|
||||
/// at the edge gives way down to its minimum, then the next one along the axis, and so on.
|
||||
/// Paths are relative to `path`.
|
||||
pub(in crate::docking) fn follow(
|
||||
&self,
|
||||
(node, rect): (&Node<P>, Rect),
|
||||
axis: SplitAxis,
|
||||
end: bool,
|
||||
grow: f32,
|
||||
path: &mut Vec<bool>,
|
||||
out: &mut Vec<(Vec<bool>, SplitSize)>,
|
||||
) {
|
||||
let Some([a, b]) = self.children(node, rect) else { return };
|
||||
let Node::Split { axis: split_axis, first, second, .. } = node else { return };
|
||||
let docked = matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. });
|
||||
let visit = |child: (&Node<P>, Rect), second_child: bool, grow: f32, path: &mut Vec<bool>, out: &mut Vec<(Vec<bool>, SplitSize)>| {
|
||||
path.push(second_child);
|
||||
self.follow(child, axis, end, grow, path, out);
|
||||
path.pop();
|
||||
};
|
||||
if docked {
|
||||
let dock_first = matches!(**first, Node::Dock { .. });
|
||||
visit(if dock_first { b } else { a }, dock_first, grow, path, out);
|
||||
} else if *split_axis == axis {
|
||||
let (near, far) = if end { (b, a) } else { (a, b) };
|
||||
let near_grow = if grow < 0.0 { grow.max(-self.travel(near.0, near.1, axis, end).0) } else { grow };
|
||||
let far_grow = grow - near_grow;
|
||||
let (near_size, far_size) = (extent(near.1, axis) + near_grow, extent(far.1, axis) + far_grow);
|
||||
let first_size = if end { far_size } else { near_size };
|
||||
push_ratio(path, first_size, near_size + far_size, out);
|
||||
visit(near, end, near_grow, path, out);
|
||||
if far_grow != 0.0 {
|
||||
visit(far, !end, far_grow, path, out);
|
||||
}
|
||||
} else {
|
||||
visit(a, false, grow, path, out);
|
||||
visit(b, true, grow, path, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawn splits from `root` down to the one at `path`, each with its rect.
|
||||
fn chain<'n>(&self, root: (&'n Node<P>, Rect), path: &[bool]) -> Option<Vec<(&'n Node<P>, Rect)>> {
|
||||
let mut chain = vec![root];
|
||||
for &second in path {
|
||||
let (node, rect) = *chain.last()?;
|
||||
let [a, b] = self.children(node, rect)?;
|
||||
chain.push(if second { b } else { a });
|
||||
}
|
||||
Some(chain)
|
||||
}
|
||||
|
||||
/// The ancestors that continue the line of the split at the end of `chain` along `axis`:
|
||||
/// each with its children and whether the line runs through its second child, nearest first.
|
||||
/// The line ends at a split across the axis or beside a dock.
|
||||
fn line<'n>(&self, chain: &[(&'n Node<P>, Rect)], path: &[bool], axis: SplitAxis) -> Vec<(usize, Children<'n, P>, bool)> {
|
||||
let mut line = Vec::new();
|
||||
for depth in (0..path.len()).rev() {
|
||||
let Some(&(node, rect)) = chain.get(depth) else { break };
|
||||
let Node::Split { axis: split_axis, first, second, .. } = node else { break };
|
||||
if *split_axis != axis || matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. }) {
|
||||
break;
|
||||
}
|
||||
let (Some(children), Some(&second_child)) = (self.children(node, rect), path.get(depth)) else { break };
|
||||
line.push((depth, children, second_child));
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// The divider of the split at `path` under `root` (a node and the rect it is drawn in)
|
||||
/// moved by `delta` points, clamped to its travel. The groups touching the divider on the
|
||||
/// side it moves toward give way, then the groups beyond them along the axis, one after
|
||||
/// another, as far as the line of same-axis splits reaches; the groups on the other side
|
||||
/// that touch the divider take the room. Paths are absolute, like `path`.
|
||||
pub(in crate::docking) fn drag(&self, root: (&Node<P>, Rect), path: &[bool], delta: f32) -> Vec<(Vec<bool>, SplitSize)> {
|
||||
let Some(chain) = self.chain(root, path) else { return Vec::new() };
|
||||
let Some(&(node, rect)) = chain.last() else { return Vec::new() };
|
||||
let Node::Split { axis, size, first, second } = node else { return Vec::new() };
|
||||
let axis = *axis;
|
||||
let Some(split) = self.split(axis, *size, first, second, rect) else { return Vec::new() };
|
||||
let (lo, hi) = self.range(root, path);
|
||||
let delta = delta.clamp(lo, hi);
|
||||
if delta == 0.0 || !delta.is_finite() || split.available() <= 0.0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// Toward the end edge the second child gives way, toward the start the first.
|
||||
let forward = delta > 0.0;
|
||||
let moved = delta.abs();
|
||||
let given = if forward {
|
||||
moved.min(self.travel(second, split.second, axis, false).0)
|
||||
} else {
|
||||
moved.min(self.travel(first, split.first, axis, true).0)
|
||||
};
|
||||
let (first_grow, second_grow) = if forward { (moved, -given) } else { (-given, moved) };
|
||||
let mut out = Vec::new();
|
||||
let mut path = path.to_vec();
|
||||
let first_size = split.first_size() + first_grow;
|
||||
push_ratio(&path, first_size, first_size + extent(split.second, axis) + second_grow, &mut out);
|
||||
path.push(false);
|
||||
self.follow((first, split.first), axis, true, first_grow, &mut path, &mut out);
|
||||
path.pop();
|
||||
path.push(true);
|
||||
self.follow((second, split.second), axis, false, second_grow, &mut path, &mut out);
|
||||
path.pop();
|
||||
// What the split's own child could not give, the ancestors' children beyond it give:
|
||||
// the split grows by `rest` toward them, and so does each ancestor until one absorbs it.
|
||||
let mut rest = moved - given;
|
||||
for (depth, [a, b], second_child) in self.line(&chain, &path, axis) {
|
||||
if rest <= 0.0 {
|
||||
break;
|
||||
}
|
||||
path.truncate(depth);
|
||||
let (a_size, b_size) = (extent(a.1, axis), extent(b.1, axis));
|
||||
let (first_size, second_size) = match (forward, second_child) {
|
||||
(true, false) => {
|
||||
let taken = rest.min(self.travel(b.0, b.1, axis, false).0);
|
||||
path.push(true);
|
||||
self.follow(b, axis, false, -taken, &mut path, &mut out);
|
||||
path.pop();
|
||||
let sizes = (a_size + rest, b_size - taken);
|
||||
rest -= taken;
|
||||
sizes
|
||||
}
|
||||
(false, true) => {
|
||||
let taken = rest.min(self.travel(a.0, a.1, axis, true).0);
|
||||
path.push(false);
|
||||
self.follow(a, axis, true, -taken, &mut path, &mut out);
|
||||
path.pop();
|
||||
let sizes = (a_size - taken, b_size + rest);
|
||||
rest -= taken;
|
||||
sizes
|
||||
}
|
||||
(true, true) => (a_size, b_size + rest),
|
||||
(false, false) => (a_size + rest, b_size),
|
||||
};
|
||||
push_ratio(&path, first_size, first_size + second_size, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far the divider of the split at `path` under `root` can move: `(lo, hi)`, with
|
||||
/// `lo <= 0 <= hi`. Each way it is the lesser of the room the groups touching the divider
|
||||
/// have to grow and the room every group beyond the divider, along the line of same-axis
|
||||
/// splits, has to shrink.
|
||||
pub(in crate::docking) fn range(&self, root: (&Node<P>, Rect), path: &[bool]) -> (f32, f32) {
|
||||
let Some(chain) = self.chain(root, path) else { return (0.0, 0.0) };
|
||||
let Some(&(node, rect)) = chain.last() else { return (0.0, 0.0) };
|
||||
let Node::Split { axis, size, first, second } = node else { return (0.0, 0.0) };
|
||||
let Some(split) = self.split(*axis, *size, first, second, rect) else { return (0.0, 0.0) };
|
||||
let (mut first_in, first_out) = self.travel(first, split.first, *axis, true);
|
||||
let (mut second_in, second_out) = self.travel(second, split.second, *axis, false);
|
||||
for (_, [a, b], second_child) in self.line(&chain, path, *axis) {
|
||||
if second_child {
|
||||
first_in += self.travel(a.0, a.1, *axis, true).0;
|
||||
} else {
|
||||
second_in += self.travel(b.0, b.1, *axis, false).0;
|
||||
}
|
||||
}
|
||||
(-first_in.min(second_out), first_out.min(second_in))
|
||||
}
|
||||
}
|
||||
|
||||
/// The size of a split at `path` whose first child is `first` of `available` points.
|
||||
fn push_ratio(path: &[bool], first: f32, available: f32, out: &mut Vec<(Vec<bool>, SplitSize)>) {
|
||||
if available > 0.0 {
|
||||
out.push((path.to_vec(), SplitSize::Ratio((first / available).clamp(0.0, 1.0))));
|
||||
}
|
||||
}
|
||||
|
||||
/// One group of a flat row, such as the panels of a stack or the groups of a dock column:
|
||||
/// its size along the row and its limits.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::docking) struct RowItem {
|
||||
pub(in crate::docking) size: f32,
|
||||
pub(in crate::docking) min: f32,
|
||||
pub(in crate::docking) max: f32,
|
||||
}
|
||||
|
||||
/// How far the divider after `row[index]` can move: `(lo, hi)`, with `lo <= 0 <= hi`, by the
|
||||
/// rule of [`row_drag`].
|
||||
pub(in crate::docking) fn row_range(row: &[RowItem], index: usize) -> (f32, f32) {
|
||||
let room = |items: &[RowItem]| items.iter().map(|item| (item.size - item.min).max(0.0)).sum::<f32>();
|
||||
let grow = |item: Option<&RowItem>| item.map_or(0.0, |item| (item.max - item.size).max(0.0));
|
||||
let (before, after) = row.split_at((index + 1).min(row.len()));
|
||||
(-room(before).min(grow(after.first())), room(after).min(grow(before.last())))
|
||||
}
|
||||
|
||||
/// The sizes of `row` after the divider after `row[index]` moves by `delta`, clamped to its
|
||||
/// travel: the item touching the divider on the side it moves toward gives way down to its
|
||||
/// minimum, then the next one, and so on; the item on the other side takes the room.
|
||||
pub(in crate::docking) fn row_drag(row: &[RowItem], index: usize, delta: f32) -> Vec<f32> {
|
||||
let (lo, hi) = row_range(row, index);
|
||||
let delta = if delta.is_finite() { delta.clamp(lo, hi) } else { 0.0 };
|
||||
let mut sizes: Vec<f32> = row.iter().map(|item| item.size).collect();
|
||||
let (grows, givers): (usize, Vec<usize>) =
|
||||
if delta > 0.0 { (index, (index + 1..row.len()).collect()) } else { (index + 1, (0..=index).rev().collect()) };
|
||||
let mut rest = delta.abs();
|
||||
for giver in givers {
|
||||
let (Some(size), Some(item)) = (sizes.get_mut(giver), row.get(giver)) else { continue };
|
||||
let taken = rest.min((item.size - item.min).max(0.0));
|
||||
*size -= taken;
|
||||
rest -= taken;
|
||||
}
|
||||
if let Some(size) = sizes.get_mut(grows) {
|
||||
*size += delta.abs() - rest;
|
||||
}
|
||||
sizes
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use egui::{Pos2, Rect, Vec2};
|
||||
|
||||
use super::PanelLimits;
|
||||
|
||||
/// A pointer-anchored resize. The opposite edges and handle grab offset stay fixed
|
||||
/// through boundary overshoot; viewport constraints never translate the window.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AnchoredResize {
|
||||
start: Rect,
|
||||
offset: Vec2,
|
||||
direction: Vec2,
|
||||
}
|
||||
|
||||
impl AnchoredResize {
|
||||
pub fn new(start: Rect, pointer: Pos2, direction: Vec2) -> Option<Self> {
|
||||
if !start.is_finite()
|
||||
|| !start.is_positive()
|
||||
|| !pointer.is_finite()
|
||||
|| ![-1.0, 0.0, 1.0].contains(&direction.x)
|
||||
|| ![-1.0, 0.0, 1.0].contains(&direction.y)
|
||||
|| direction == Vec2::ZERO
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let edge =
|
||||
egui::pos2(if direction.x < 0.0 { start.left() } else { start.right() }, if direction.y < 0.0 { start.top() } else { start.bottom() });
|
||||
Some(Self { start, offset: pointer - edge, direction })
|
||||
}
|
||||
|
||||
/// None suspends resizing when the fixed anchor cannot accommodate the minimum.
|
||||
pub fn rect(self, pointer: Pos2, viewport: Rect, limits: PanelLimits) -> Option<Rect> {
|
||||
if !pointer.is_finite()
|
||||
|| !viewport.is_finite()
|
||||
|| !viewport.is_positive()
|
||||
|| !limits.min.is_finite()
|
||||
|| !limits.max.is_finite()
|
||||
|| limits.min.x <= 0.0
|
||||
|| limits.min.y <= 0.0
|
||||
|| limits.max.x < limits.min.x
|
||||
|| limits.max.y < limits.min.y
|
||||
|| !viewport.contains_rect(self.start)
|
||||
|| self.start.width() < limits.min.x
|
||||
|| self.start.height() < limits.min.y
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let desired = pointer - self.offset;
|
||||
if !desired.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let mut rect = self.start;
|
||||
for (axis, direction) in [(0, self.direction.x), (1, self.direction.y)] {
|
||||
if direction == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (lo, hi) = if direction < 0.0 {
|
||||
((self.start.max[axis] - limits.max[axis]).max(viewport.min[axis]), self.start.max[axis] - limits.min[axis])
|
||||
} else {
|
||||
(self.start.min[axis] + limits.min[axis], (self.start.min[axis] + limits.max[axis]).min(viewport.max[axis]))
|
||||
};
|
||||
if !lo.is_finite() || !hi.is_finite() || lo > hi {
|
||||
return None;
|
||||
}
|
||||
if direction < 0.0 {
|
||||
rect.min[axis] = desired[axis].clamp(lo, hi);
|
||||
} else {
|
||||
rect.max[axis] = desired[axis].clamp(lo, hi);
|
||||
}
|
||||
}
|
||||
Some(rect)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::{pos2, vec2};
|
||||
|
||||
#[test]
|
||||
fn every_handle_tracks_absolute_pointer_and_keeps_opposite_edges() {
|
||||
let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0));
|
||||
let viewport = Rect::from_min_max(Pos2::ZERO, pos2(800.0, 600.0));
|
||||
let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(500.0, 400.0) };
|
||||
for direction in
|
||||
[vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(0.0, -1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0)]
|
||||
{
|
||||
let edge =
|
||||
pos2(if direction.x < 0.0 { start.left() } else { start.right() }, if direction.y < 0.0 { start.top() } else { start.bottom() });
|
||||
let pointer = edge + vec2(2.0, -3.0);
|
||||
let resize = AnchoredResize::new(start, pointer, direction).unwrap();
|
||||
let rect = resize.rect(pointer + vec2(20.0, 25.0), viewport, limits).unwrap();
|
||||
// A moving edge follows the pointer; every other edge stays.
|
||||
let moved = |d: f32, lo: f32, hi: f32, by: f32| match d {
|
||||
d if d < 0.0 => (lo + by, hi),
|
||||
d if d > 0.0 => (lo, hi + by),
|
||||
_ => (lo, hi),
|
||||
};
|
||||
assert_eq!((rect.left(), rect.right()), moved(direction.x, start.left(), start.right(), 20.0), "{direction:?}");
|
||||
assert_eq!((rect.top(), rect.bottom()), moved(direction.y, start.top(), start.bottom(), 25.0), "{direction:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overshoot_requires_pointer_to_return_to_the_valid_range() {
|
||||
let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0));
|
||||
let viewport = Rect::from_min_max(Pos2::ZERO, pos2(600.0, 500.0));
|
||||
let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(1000.0, 1000.0) };
|
||||
let resize = AnchoredResize::new(start, pos2(398.0, 200.0), vec2(1.0, 0.0)).unwrap();
|
||||
for x in [800.0, 750.0, 598.0] {
|
||||
let rect = resize.rect(pos2(x, 200.0), viewport, limits).unwrap();
|
||||
assert_eq!((rect.left(), rect.right()), (100.0, 600.0));
|
||||
}
|
||||
for x in [120.0, 200.0, 258.0] {
|
||||
assert_eq!(resize.rect(pos2(x, 200.0), viewport, limits).unwrap().right(), 260.0);
|
||||
}
|
||||
assert_eq!(resize.rect(pos2(278.0, 200.0), viewport, limits).unwrap().right(), 280.0);
|
||||
let left = AnchoredResize::new(start, pos2(102.0, 200.0), vec2(-1.0, 0.0)).unwrap();
|
||||
assert_eq!(left.rect(pos2(-300.0, 200.0), viewport, limits).unwrap().min.x, 0.0);
|
||||
assert_eq!(left.rect(pos2(350.0, 200.0), viewport, limits).unwrap().min.x, 240.0);
|
||||
assert_eq!(left.rect(pos2(300.0, 200.0), viewport, limits).unwrap().min.x, 240.0);
|
||||
assert_eq!(left.rect(pos2(222.0, 200.0), viewport, limits).unwrap().min.x, 220.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_maximum_caps_edges_without_losing_the_absolute_anchor() {
|
||||
let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0));
|
||||
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
|
||||
let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(320.0, 240.0) };
|
||||
let resize = AnchoredResize::new(start, start.max, Vec2::splat(1.0)).unwrap();
|
||||
for pointer in [pos2(700.0, 550.0), pos2(600.0, 450.0)] {
|
||||
assert_eq!(resize.rect(pointer, viewport, limits).unwrap(), Rect::from_min_max(start.min, pos2(420.0, 320.0)));
|
||||
}
|
||||
assert_eq!(resize.rect(pos2(410.0, 310.0), viewport, limits).unwrap(), Rect::from_min_max(start.min, pos2(410.0, 310.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_viewports_and_invalid_geometry_suspend_resize() {
|
||||
let start = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 90.0));
|
||||
let resize = AnchoredResize::new(start, start.max, Vec2::splat(1.0)).unwrap();
|
||||
assert!(resize.rect(start.max, start, PanelLimits { min: vec2(160.0, 120.0), ..Default::default() }).is_none());
|
||||
assert!(AnchoredResize::new(start, pos2(f32::NAN, 0.0), Vec2::splat(1.0)).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
//! A split tree of tab groups in an editing layout like FilmCraft's: Source | Program |
|
||||
//! Properties over Project | Tools | Timeline | Audio Meters, every group an ordinary
|
||||
//! resizable one. One test per docking rule, the stuck cases of the FilmCraft map, and a
|
||||
//! property test over random drops.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::floating_tests::frame_style;
|
||||
use super::render::{Drawn, Sizer};
|
||||
use super::testing::DockDriver;
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Modifiers, Pos2, Rect, Vec2, pos2, vec2};
|
||||
|
||||
const SOURCE: [u32; 4] = [1, 11, 12, 13];
|
||||
const PROGRAM: u32 = 2;
|
||||
const PROPERTIES: [u32; 3] = [3, 31, 32];
|
||||
const PROJECT: [u32; 7] = [4, 41, 42, 43, 44, 45, 46];
|
||||
const TOOLS: u32 = 5;
|
||||
const TIMELINE: u32 = 6;
|
||||
const METERS: u32 = 7;
|
||||
const INFO: u32 = 9;
|
||||
|
||||
const SCREEN: Vec2 = Vec2::new(1440.0, 860.0);
|
||||
|
||||
/// Panel bodies by their rects; `caps` are maximum widths a host asks for, `rules` the
|
||||
/// permissions of panels that differ from the default.
|
||||
#[derive(Default)]
|
||||
struct Film {
|
||||
bodies: HashMap<u32, Rect>,
|
||||
caps: HashMap<u32, f32>,
|
||||
rules: HashMap<u32, Permissions>,
|
||||
}
|
||||
|
||||
impl DockContent<u32> for Film {
|
||||
fn body(&mut self, ui: &mut egui::Ui, panel: &u32) {
|
||||
self.bodies.insert(*panel, ui.max_rect());
|
||||
}
|
||||
fn logical_label(&self, panel: &u32) -> String {
|
||||
format!("Panel {panel}")
|
||||
}
|
||||
fn limits(&self, panel: &u32) -> PanelLimits {
|
||||
match self.caps.get(panel) {
|
||||
Some(width) => PanelLimits { min: Vec2::ZERO, max: vec2(*width, 1_000_000.0) },
|
||||
None => PanelLimits::default(),
|
||||
}
|
||||
}
|
||||
fn permissions(&self, panel: &u32) -> Permissions {
|
||||
self.rules.get(panel).copied().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
type Driver = DockDriver<u32, Film>;
|
||||
|
||||
fn tabs(panels: &[u32]) -> Node<u32> {
|
||||
Node::Tabs { panels: panels.to_vec(), active: 0 }
|
||||
}
|
||||
|
||||
fn split(axis: SplitAxis, ratio: f32, first: Node<u32>, second: Node<u32>) -> Node<u32> {
|
||||
Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) }
|
||||
}
|
||||
|
||||
fn hsplit(ratio: f32, first: Node<u32>, second: Node<u32>) -> Node<u32> {
|
||||
split(SplitAxis::Horizontal, ratio, first, second)
|
||||
}
|
||||
|
||||
/// The Editing workspace, with Info floating over Properties.
|
||||
fn editing() -> Layout<u32> {
|
||||
let top = hsplit(0.69, hsplit(0.5, tabs(&SOURCE), tabs(&[PROGRAM])), tabs(&PROPERTIES));
|
||||
let row = hsplit(0.06, tabs(&[TOOLS]), hsplit(0.88, tabs(&[TIMELINE]), tabs(&[METERS])));
|
||||
let bottom = hsplit(0.29, tabs(&PROJECT), row);
|
||||
Layout {
|
||||
root: Some(split(SplitAxis::Vertical, 0.57, top, bottom)),
|
||||
floating: vec![Floating::single(vec![INFO], 0, [1120.0, 60.0, 280.0, 200.0])],
|
||||
}
|
||||
}
|
||||
|
||||
fn driver(layout: Layout<u32>, content: Film) -> Driver {
|
||||
let mut d = DockDriver::new(layout, content).with_style(frame_style);
|
||||
d.screen = Rect::from_min_size(Pos2::ZERO, SCREEN);
|
||||
d.area = d.screen;
|
||||
d.settle();
|
||||
d
|
||||
}
|
||||
|
||||
fn film() -> Driver {
|
||||
driver(editing(), Film::default())
|
||||
}
|
||||
|
||||
/// A group's rect: its active body and its tab strip.
|
||||
fn group(d: &Driver, panel: u32) -> Rect {
|
||||
let body = d.content.bodies.get(&panel).copied().unwrap_or_else(|| panic!("panel {panel} not drawn"));
|
||||
Rect::from_min_max(pos2(body.left(), body.top() - 26.0), body.max)
|
||||
}
|
||||
|
||||
fn tab(d: &Driver, panel: u32) -> Pos2 {
|
||||
d.hit(&Hit::Tab(panel)).unwrap_or_else(|| panic!("tab {panel}")).center()
|
||||
}
|
||||
|
||||
/// Drag a divider by `delta`, hovering it first as a pointer does.
|
||||
fn drag_hit(d: &mut Driver, hit: Hit<u32>, delta: Vec2) {
|
||||
let at = d.hit(&hit).unwrap_or_else(|| panic!("{hit:?} in {:?}", d.hits())).center();
|
||||
d.move_to(at);
|
||||
d.drag(at, at + delta);
|
||||
d.settle();
|
||||
}
|
||||
|
||||
fn divider(path: &[bool]) -> Hit<u32> {
|
||||
Hit::Divider(Divider::Split(path.to_vec()))
|
||||
}
|
||||
|
||||
fn sizes(d: &Driver, panels: &[u32]) -> Vec<Vec2> {
|
||||
panels.iter().map(|p| group(d, *p).size()).collect()
|
||||
}
|
||||
|
||||
fn close(a: Rect, b: Rect) -> bool {
|
||||
(a.min - b.min).length() < 1.0 && (a.max - b.max).length() < 1.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_is_a_picture_frame_whose_edges_split_it_in_half_and_whose_middle_joins_it() {
|
||||
let base = film();
|
||||
let timeline = group(&base, TIMELINE);
|
||||
let others = [PROJECT[0], TOOLS, METERS, SOURCE[0], PROGRAM, PROPERTIES[0]];
|
||||
// Halfway into each 40 pt band of the body below the tab strip.
|
||||
let inset = |zone| {
|
||||
let (w, h) = (20.0, 20.0);
|
||||
match zone {
|
||||
Zone::Left => pos2(timeline.left() + w, timeline.center().y + 13.0),
|
||||
Zone::Right => pos2(timeline.right() - w, timeline.center().y + 13.0),
|
||||
Zone::Top => pos2(timeline.center().x, timeline.top() + 26.0 + h),
|
||||
Zone::Bottom => pos2(timeline.center().x, timeline.bottom() - h),
|
||||
Zone::Center => pos2(timeline.center().x, timeline.center().y + 13.0),
|
||||
}
|
||||
};
|
||||
for zone in [Zone::Left, Zone::Right, Zone::Top, Zone::Bottom] {
|
||||
let mut d = film();
|
||||
let before = sizes(&d, &others);
|
||||
let at = inset(zone);
|
||||
d.hold(tab(&d, INFO), at);
|
||||
assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, zone).unwrap()), "{zone:?}: the preview fills that band");
|
||||
let out = d.release(at);
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TIMELINE, placement: Placement::Split(zone) }], "{zone:?}");
|
||||
d.settle();
|
||||
let (info, rest) = (group(&d, INFO), group(&d, TIMELINE));
|
||||
assert!(close(info.union(rest), timeline), "{zone:?}: the two halves fill the group: {info:?} {rest:?} in {timeline:?}");
|
||||
assert!((info.area() - rest.area()).abs() < info.area() * 0.05, "{zone:?}: about halves");
|
||||
assert_eq!(sizes(&d, &others), before, "{zone:?}: no other group changes");
|
||||
}
|
||||
// The middle and the tab row join the group.
|
||||
let mut d = film();
|
||||
let out = d.drag(tab(&d, INFO), inset(Zone::Center));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TIMELINE, placement: Placement::Split(Zone::Center) }]);
|
||||
let mut d = film();
|
||||
let out = d.drag(tab(&d, INFO), pos2(timeline.center().x, timeline.top() + 10.0));
|
||||
assert!(matches!(&out.actions[..], [Action::Move { panel: INFO, placement: Placement::Tab { .. }, .. }]), "{:?}", out.actions);
|
||||
// The gap between two groups belongs to neither: the drag cancels.
|
||||
let mut d = film();
|
||||
let tools = group(&d, TOOLS);
|
||||
let gap = pos2(tools.right() + 2.0, tools.center().y);
|
||||
let out = d.drag(tab(&d, INFO), gap);
|
||||
assert!(out.actions.is_empty(), "{:?}", out.actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_edges_add_a_full_column_or_row_without_taking_the_groups_edges() {
|
||||
let mut d = film();
|
||||
let project = group(&d, PROJECT[0]);
|
||||
let out = d.drag(tab(&d, INFO), pos2(3.0, project.center().y));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: SOURCE[0], placement: Placement::Edge(Zone::Left) }]);
|
||||
d.settle();
|
||||
let info = group(&d, INFO);
|
||||
assert_eq!((info.top(), info.bottom(), info.left()), (0.0, SCREEN.y, 0.0), "a full-height column at the left");
|
||||
assert!((info.width() - SCREEN.x * 0.25).abs() < 4.0, "{info:?}");
|
||||
|
||||
for (at, zone) in [(pos2(SCREEN.x - 3.0, 300.0), Zone::Right), (pos2(700.0, 3.0), Zone::Top), (pos2(700.0, SCREEN.y - 3.0), Zone::Bottom)] {
|
||||
let mut d = film();
|
||||
let out = d.drag(tab(&d, INFO), at);
|
||||
assert!(matches!(&out.actions[..], [Action::Move { placement: Placement::Edge(z), .. }] if *z == zone), "{zone:?}: {:?}", out.actions);
|
||||
}
|
||||
// Past the window band, the group's own edge band splits that group.
|
||||
let mut d = film();
|
||||
let out = d.drag(tab(&d, INFO), pos2(project.left() + 20.0, project.center().y + 13.0));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: PROJECT[0], placement: Placement::Split(Zone::Left) }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_have_one_small_minimum_and_no_maximum() {
|
||||
let mut d = film();
|
||||
let tools = group(&d, TOOLS).width();
|
||||
drag_hit(&mut d, divider(&[true, true]), vec2(400.0, 0.0));
|
||||
assert!((group(&d, TOOLS).width() - (tools + 400.0)).abs() < 1.0, "Tools grows as wide as it is dragged");
|
||||
drag_hit(&mut d, divider(&[true, true]), vec2(-2000.0, 0.0));
|
||||
assert_eq!(group(&d, TOOLS).width(), 40.0, "and shrinks to the minimum, no further");
|
||||
|
||||
// A group too narrow for two halves takes a drop on its edge as a tab.
|
||||
let tools = group(&d, TOOLS);
|
||||
let out = d.drag(tab(&d, INFO), pos2(tools.right() - 4.0, tools.center().y + 30.0));
|
||||
assert!(
|
||||
matches!(&out.actions[..], [Action::Move { panel: INFO, anchor: TOOLS, placement: Placement::Split(Zone::Center) | Placement::Tab { .. } }]),
|
||||
"{:?}",
|
||||
out.actions
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_divider_resizes_only_the_groups_that_share_it() {
|
||||
// Timeline | Meters: Project and Tools keep their widths.
|
||||
let mut d = film();
|
||||
let (project, tools, timeline, meters) = (group(&d, PROJECT[0]), group(&d, TOOLS), group(&d, TIMELINE), group(&d, METERS));
|
||||
drag_hit(&mut d, divider(&[true, true, true]), vec2(-100.0, 0.0));
|
||||
assert_eq!((group(&d, PROJECT[0]), group(&d, TOOLS)), (project, tools));
|
||||
assert!((group(&d, TIMELINE).width() - (timeline.width() - 100.0)).abs() < 1.0);
|
||||
assert!((group(&d, METERS).width() - (meters.width() + 100.0)).abs() < 1.0);
|
||||
|
||||
// Project | the rest: only Tools, on the other side, gives way; Timeline and Meters stay.
|
||||
let mut d = film();
|
||||
drag_hit(&mut d, divider(&[true]), vec2(15.0, 0.0));
|
||||
assert!((group(&d, PROJECT[0]).width() - (project.width() + 15.0)).abs() < 1.0);
|
||||
assert!((group(&d, TOOLS).width() - (tools.width() - 15.0)).abs() < 1.0);
|
||||
assert!(close(group(&d, TIMELINE), timeline) && close(group(&d, METERS), meters), "{:?}", d.layout);
|
||||
|
||||
// Top row: Source | Program leaves Properties alone.
|
||||
let mut d = film();
|
||||
let properties = group(&d, PROPERTIES[0]);
|
||||
drag_hit(&mut d, divider(&[false, false]), vec2(80.0, 0.0));
|
||||
assert_eq!(group(&d, PROPERTIES[0]), properties);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_divider_dragged_past_a_groups_minimum_shrinks_the_next_group_along_the_row() {
|
||||
// A | B | C | D, 357 pt each, as (A | B) | (C | D): the cascade runs on past B's split.
|
||||
let row = hsplit(0.5, hsplit(0.5, tabs(&[1]), tabs(&[2])), hsplit(0.5, tabs(&[3]), tabs(&[4])));
|
||||
let mut d = driver(Layout { root: Some(row), floating: Vec::new() }, Film::default());
|
||||
let widths = |d: &Driver| [1, 2, 3, 4].map(|panel| group(d, panel).width().round());
|
||||
assert_eq!(widths(&d), [357.0, 357.0, 357.0, 357.0]);
|
||||
// B gives way down to its 40 pt minimum, then C.
|
||||
drag_hit(&mut d, divider(&[false]), vec2(400.0, 0.0));
|
||||
assert_eq!(widths(&d), [757.0, 40.0, 274.0, 357.0]);
|
||||
// The drag stops when B, C and D are all at their minimums.
|
||||
drag_hit(&mut d, divider(&[false]), vec2(670.0, 0.0));
|
||||
assert_eq!(widths(&d), [1308.0, 40.0, 40.0, 40.0]);
|
||||
// Back the other way, A gives way and only B, which touches the divider, grows.
|
||||
drag_hit(&mut d, divider(&[false]), vec2(-1300.0, 0.0));
|
||||
assert_eq!(widths(&d), [40.0, 1308.0, 40.0, 40.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_intersection_moves_both_dividers() {
|
||||
let mut d = film();
|
||||
let (project, tools, source) = (group(&d, PROJECT[0]), group(&d, TOOLS), group(&d, SOURCE[0]));
|
||||
let hit = Hit::Divider(Divider::Intersection(vec![], vec![true]));
|
||||
let at = d.hit(&hit).unwrap_or_else(|| panic!("{:?}", d.hits()));
|
||||
assert!(at.contains(pos2(project.right() + 2.0, project.top() - 2.0)), "{at:?} at Project's top right corner");
|
||||
drag_hit(&mut d, hit, vec2(15.0, -60.0));
|
||||
assert!((group(&d, PROJECT[0]).width() - (project.width() + 15.0)).abs() < 1.0);
|
||||
assert!((group(&d, PROJECT[0]).height() - (project.height() + 60.0)).abs() < 1.0);
|
||||
assert!((group(&d, TOOLS).width() - (tools.width() - 15.0)).abs() < 1.0);
|
||||
assert!((group(&d, SOURCE[0]).height() - (source.height() - 60.0)).abs() < 1.0);
|
||||
assert_eq!(group(&d, SOURCE[0]).width(), source.width());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_group_gives_its_space_to_its_neighbours() {
|
||||
let mut d = film();
|
||||
let (tools, meters) = (group(&d, TOOLS), group(&d, METERS));
|
||||
d.layout.apply(Action::CloseGroup { panel: TIMELINE }).unwrap();
|
||||
d.settle();
|
||||
let meters_now = group(&d, METERS);
|
||||
assert_eq!(group(&d, TOOLS), tools);
|
||||
assert_eq!((meters_now.right(), meters_now.top(), meters_now.bottom()), (meters.right(), meters.top(), meters.bottom()));
|
||||
assert!((meters_now.left() - (tools.right() + 4.0)).abs() < 1.0, "the row has no hole: {meters_now:?}");
|
||||
}
|
||||
|
||||
// The stuck cases of the FilmCraft map (map.md section 3).
|
||||
|
||||
#[test]
|
||||
fn info_dropped_onto_a_capped_group_lifts_the_cap() {
|
||||
let content = Film { caps: HashMap::from([(METERS, 116.0)]), ..Film::default() };
|
||||
let mut d = driver(editing(), content);
|
||||
let meters = group(&d, METERS);
|
||||
d.drag(tab(&d, INFO), pos2(meters.center().x, meters.center().y + 13.0));
|
||||
d.settle();
|
||||
assert!(d.layout.location(&INFO).is_ok_and(|l| l.anchor == Some(METERS)), "{:?}", d.layout);
|
||||
// Info is the group's shown panel.
|
||||
let width = group(&d, INFO).width();
|
||||
drag_hit(&mut d, divider(&[true, true, true]), vec2(-200.0, 0.0));
|
||||
assert!((group(&d, INFO).width() - (width + 200.0)).abs() < 1.0, "the group grows past the cap of one of its panels");
|
||||
drag_hit(&mut d, divider(&[true, true, true]), vec2(150.0, 0.0));
|
||||
assert!((group(&d, INFO).width() - (width + 50.0)).abs() < 1.0, "and shrinks again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_beside_a_narrow_group_splits_that_group_only() {
|
||||
let mut d = film();
|
||||
drag_hit(&mut d, divider(&[true, true]), vec2(80.0, 0.0));
|
||||
let (tools, project, timeline, meters) = (group(&d, TOOLS), group(&d, PROJECT[0]), group(&d, TIMELINE), group(&d, METERS));
|
||||
assert!(tools.width() > 120.0, "{tools:?}");
|
||||
let at = pos2(tools.right() - 8.0, tools.center().y + 13.0);
|
||||
d.hold(tab(&d, INFO), at);
|
||||
assert!(d.filled_polygon(&zone_shape(tools, 26.0, 40.0, Zone::Right).unwrap()), "the preview fills Tools' right band");
|
||||
let out = d.release(at);
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TOOLS, placement: Placement::Split(Zone::Right) }]);
|
||||
d.settle();
|
||||
assert!(close(group(&d, TOOLS).union(group(&d, INFO)), tools));
|
||||
assert_eq!((group(&d, PROJECT[0]), group(&d, TIMELINE), group(&d, METERS)), (project, timeline, meters));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_divider_travels_after_drops() {
|
||||
let mut d = film();
|
||||
let tools = group(&d, TOOLS);
|
||||
d.drag(tab(&d, INFO), pos2(tools.right() - 8.0, tools.center().y + 13.0));
|
||||
d.settle();
|
||||
let meters = group(&d, METERS);
|
||||
d.drag(tab(&d, PROGRAM), pos2(meters.center().x, meters.center().y + 13.0));
|
||||
d.settle();
|
||||
let timeline = group(&d, TIMELINE);
|
||||
d.drag(tab(&d, PROPERTIES[0]), pos2(timeline.center().x, timeline.bottom() - 10.0));
|
||||
d.settle();
|
||||
assert_dividers_travel(&mut d);
|
||||
}
|
||||
|
||||
/// Each split divider, in the docked layout and in floating windows, moves both ways when
|
||||
/// dragged, from the layout as it is.
|
||||
fn assert_dividers_travel(d: &mut Driver) {
|
||||
let start = d.layout.clone();
|
||||
let dividers: Vec<Hit<u32>> = d
|
||||
.hits()
|
||||
.into_iter()
|
||||
.filter_map(|(hit, _)| matches!(hit, Hit::Divider(Divider::Split(_) | Divider::WindowSplit(..))).then_some(hit))
|
||||
.collect();
|
||||
assert!(!dividers.is_empty());
|
||||
// A floating window may cover the dividers of the main area and of other windows.
|
||||
let covers: Vec<(Rect, &Floating<u32>)> = start
|
||||
.floating
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let drawn = w.panels().filter(|p| d.content.bodies.contains_key(p)).map(|p| group(d, *p));
|
||||
let rect = Rect::from_min_size(pos2(w.rect[0], w.rect[1]), vec2(w.rect[2], w.rect[3]));
|
||||
(drawn.fold(rect, |a, b| a.union(b)), w)
|
||||
})
|
||||
.collect();
|
||||
for hit in dividers {
|
||||
let own = |w: &Floating<u32>| matches!(&hit, Hit::Divider(Divider::WindowSplit(key, _)) if w.contains(key));
|
||||
if d.hit(&hit).is_some_and(|r| covers.iter().any(|(c, w)| c.intersects(r) && !own(w))) {
|
||||
continue;
|
||||
}
|
||||
for step in [12.0, -24.0] {
|
||||
let Some(rect) = d.hit(&hit) else { continue };
|
||||
let delta = if rect.width() < rect.height() { vec2(step, 0.0) } else { vec2(0.0, step) };
|
||||
let before = d.layout.clone();
|
||||
drag_hit(d, hit.clone(), delta);
|
||||
assert_ne!(d.layout, before, "divider {hit:?} does not move by {step}");
|
||||
}
|
||||
d.layout = start.clone();
|
||||
d.settle();
|
||||
}
|
||||
}
|
||||
|
||||
/// Every group at or above its minimum, and every divider with room both ways, in the docked
|
||||
/// layout and in each floating window. Reads the bodies drawn last.
|
||||
fn assert_sizes(d: &Driver, context: &str) {
|
||||
let mut style = DockStyle::default();
|
||||
frame_style(&mut style);
|
||||
let sizer = Sizer { style: &style, content: &d.content };
|
||||
let mut trees: Vec<(&Node<u32>, Rect)> = d.layout.root.iter().map(|root| (root, d.area)).collect();
|
||||
for window in d.layout.floating.iter().filter(|w| !w.minimized) {
|
||||
// The window's body is the union of its groups.
|
||||
let drawn = window.panels().filter(|p| d.content.bodies.contains_key(p)).map(|p| group(d, *p));
|
||||
if let Some(rect) = drawn.reduce(|a, b| a.union(b)) {
|
||||
trees.push((&window.root, rect));
|
||||
}
|
||||
}
|
||||
for (root, area) in trees {
|
||||
let mut groups: Vec<Drawn<'_, u32>> = Vec::new();
|
||||
sizer.groups(root, area, &mut groups);
|
||||
for g in &groups {
|
||||
let room = g.rect.size() - g.limits.min;
|
||||
assert!(room.x >= -0.01 && room.y >= -0.01, "{context}: {:?} is below its minimum {:?}", g.rect, g.limits.min);
|
||||
}
|
||||
let mut nodes = vec![(root, area, Vec::new())];
|
||||
while let Some((node, rect, path)) = nodes.pop() {
|
||||
let Some([a, b]) = sizer.children(node, rect) else { continue };
|
||||
let (lo, hi) = sizer.range((root, area), &path);
|
||||
assert!(lo < -0.5 && hi > 0.5, "{context}: a divider is stuck ({lo}, {hi}) at {rect:?} in {:?}", d.layout);
|
||||
for (second, (child, rect)) in [(false, a), (true, b)] {
|
||||
let mut path = path.clone();
|
||||
path.push(second);
|
||||
nodes.push((child, rect, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A small deterministic generator, so a failing sequence repeats.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||
self.0 >> 33
|
||||
}
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n.max(1) as u64) as usize
|
||||
}
|
||||
fn unit(&mut self) -> f32 {
|
||||
(self.next() % 1000) as f32 / 1000.0
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_drops_leave_every_group_its_minimum_and_every_divider_travel() {
|
||||
// Drops land in the docked layout and in two floating windows, one of them split; tabs and
|
||||
// drag bars move panels and groups between all three, and Ctrl/Cmd floats some.
|
||||
let windows = || {
|
||||
let mut layout = editing();
|
||||
layout.floating.push(Floating::new(hsplit(0.5, tabs(&[8]), tabs(&[50, 51])), [80.0, 420.0, 640.0, 380.0]));
|
||||
layout
|
||||
};
|
||||
for seed in 1..=6u64 {
|
||||
let mut rng = Lcg(seed);
|
||||
let mut d = driver(windows(), Film::default());
|
||||
let all = panel_set(&d.layout);
|
||||
for step in 0..16 {
|
||||
// Only the bodies drawn now.
|
||||
d.content.bodies.clear();
|
||||
d.settle();
|
||||
let panels: Vec<u32> = d.layout.panels().into_iter().copied().collect();
|
||||
let panel = panels[rng.below(panels.len())];
|
||||
let bar = d.hit(&Hit::DragBar(panel)).filter(|_| rng.below(3) == 0);
|
||||
let Some(from) = bar.or_else(|| d.hit(&Hit::Tab(panel))).map(|r| r.center()) else { continue };
|
||||
let target = panels[rng.below(panels.len())];
|
||||
let Some(rect) = d.content.bodies.get(&target).copied() else { continue };
|
||||
let to = match rng.below(8) {
|
||||
// A window edge.
|
||||
0 => {
|
||||
let edges = [
|
||||
pos2(3.0, rect.center().y),
|
||||
pos2(SCREEN.x - 3.0, rect.center().y),
|
||||
pos2(rect.center().x, 3.0),
|
||||
pos2(rect.center().x, SCREEN.y - 3.0),
|
||||
];
|
||||
edges[rng.below(4)]
|
||||
}
|
||||
// The tab row.
|
||||
1 => pos2(rect.center().x, rect.top() - 13.0),
|
||||
// Anywhere in the body: an edge band or the middle.
|
||||
_ => rect.lerp_inside(vec2(0.02 + rng.unit() * 0.96, 0.02 + rng.unit() * 0.96)),
|
||||
};
|
||||
if rng.below(12) == 0 {
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
}
|
||||
d.drag(from, to);
|
||||
d.modifiers = Modifiers::NONE;
|
||||
d.content.bodies.clear();
|
||||
d.settle();
|
||||
let context = format!("seed {seed}, step {step}");
|
||||
assert_eq!(d.layout.validate(), Ok(()), "{context}");
|
||||
assert_eq!(panel_set(&d.layout), all, "{context}: a panel was lost");
|
||||
assert_sizes(&d, &context);
|
||||
}
|
||||
assert_dividers_travel(&mut d);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_or_cmd_floats_from_a_tab_or_a_drag_bar_and_the_preview_says_so() {
|
||||
// The hint names the platform's key, as `ctx.os()` reports it in tests.
|
||||
let key = if egui::os::OperatingSystem::from_target_os() == egui::os::OperatingSystem::Mac { "⌘" } else { "Ctrl" };
|
||||
let hint = format!("Hold {key} to undock");
|
||||
let floated = |actions: &[Action<u32>], panel: u32| match actions {
|
||||
[Action::Float { panel: p, .. }] => *p == panel,
|
||||
[Action::MoveGroup { panel: p, to: Target::Float { .. } }] => *p == panel,
|
||||
_ => false,
|
||||
};
|
||||
fn texts(d: &Driver) -> Vec<String> {
|
||||
fn walk(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)),
|
||||
egui::Shape::Text(text) => out.push(text.galley.text().to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
d.shapes().iter().for_each(|clipped| walk(&clipped.shape, &mut out));
|
||||
out
|
||||
}
|
||||
let d = film();
|
||||
let over = group(&d, TIMELINE).center() + vec2(0.0, 13.0);
|
||||
let from_tab = tab(&d, PROJECT[0]);
|
||||
let from_bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center();
|
||||
for from in [from_tab, from_bar] {
|
||||
// Without the modifier, a release over a group docks there; the preview names the modifier.
|
||||
let mut d = film();
|
||||
d.hold(from, over);
|
||||
assert!(texts(&d).contains(&hint), "{from:?}: {:?}", texts(&d));
|
||||
let out = d.release(over);
|
||||
assert!(!out.actions.is_empty() && !floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions);
|
||||
// Held, it floats, and the hint is gone.
|
||||
let mut d = film();
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
d.hold(from, over);
|
||||
assert!(!texts(&d).contains(&hint), "{from:?}");
|
||||
let out = d.release(over);
|
||||
assert!(floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Editing workspace under a 24 pt menu bar and above a 20 pt status bar.
|
||||
fn film_in_window() -> Driver {
|
||||
let mut d = DockDriver::new(editing(), Film::default()).with_style(frame_style);
|
||||
d.screen = Rect::from_min_size(Pos2::ZERO, SCREEN);
|
||||
d.area = Rect::from_min_max(pos2(0.0, 24.0), pos2(SCREEN.x, SCREEN.y - 20.0));
|
||||
d.settle();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_over_no_target_inside_the_window_cancels_the_drag() {
|
||||
let d = film_in_window();
|
||||
let (source, program) = (group(&d, SOURCE[0]), group(&d, PROGRAM));
|
||||
let gap = pos2((source.right() + program.left()) * 0.5, source.center().y);
|
||||
let from_tab = tab(&d, PROJECT[0]);
|
||||
let from_bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center();
|
||||
for from in [from_tab, from_bar] {
|
||||
for to in [pos2(600.0, 10.0), pos2(600.0, SCREEN.y - 8.0), gap] {
|
||||
let mut d = film_in_window();
|
||||
let before = d.layout.clone();
|
||||
let out = d.drag(from, to);
|
||||
d.settle();
|
||||
assert!(out.actions.is_empty(), "{from:?} to {to:?}: {:?}", out.actions);
|
||||
assert_eq!(d.layout, before, "{from:?} to {to:?}");
|
||||
}
|
||||
// Ctrl/Cmd held floats it there.
|
||||
let mut d = film_in_window();
|
||||
d.modifiers = Modifiers::COMMAND;
|
||||
d.drag(from, pos2(600.0, 10.0));
|
||||
d.settle();
|
||||
assert!(d.layout.floating.iter().any(|w| w.contains(&PROJECT[0])), "{from:?}: {:?}", d.layout.floating);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_outside_the_window_floats() {
|
||||
let d = film_in_window();
|
||||
let from_tab = tab(&d, PROJECT[0]);
|
||||
let from_bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center();
|
||||
for from in [from_tab, from_bar] {
|
||||
let mut d = film_in_window();
|
||||
d.hold(from, pos2(600.0, 10.0));
|
||||
d.leave();
|
||||
d.settle();
|
||||
let window = d.layout.floating.iter().find(|w| w.contains(&PROJECT[0]));
|
||||
assert!(window.is_some(), "{from:?}: {:?}", d.layout);
|
||||
// A tab takes one panel; a drag bar takes the group.
|
||||
assert_eq!(window.unwrap().contains(&PROJECT[1]), from == from_bar, "{from:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_bar_moves_a_floating_window_without_docking() {
|
||||
let mut d = film();
|
||||
let title = d.hit(&Hit::Title(INFO)).unwrap().center();
|
||||
let timeline = group(&d, TIMELINE);
|
||||
d.drag(title, timeline.center());
|
||||
d.settle();
|
||||
let window = d.layout.floating.iter().find(|w| w.contains(&INFO)).expect("still floating");
|
||||
assert!(window.rect[0] < 1000.0 && window.rect[1] > 400.0, "moved towards the drop: {:?}", window.rect);
|
||||
assert_eq!(d.layout.root, editing().root);
|
||||
}
|
||||
|
||||
fn panel_set(layout: &Layout<u32>) -> Vec<u32> {
|
||||
let mut panels: Vec<u32> = layout.panels().into_iter().copied().collect();
|
||||
panels.sort_unstable();
|
||||
panels
|
||||
}
|
||||
|
||||
fn window_of(layout: &Layout<u32>, panel: u32) -> &Floating<u32> {
|
||||
layout.floating.iter().find(|w| w.contains(&panel)).unwrap_or_else(|| panic!("{panel} does not float: {layout:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_and_drag_bars_dock_into_a_floating_window_and_out_of_it() {
|
||||
let mut d = film();
|
||||
let all = panel_set(&d.layout);
|
||||
let info = group(&d, INFO);
|
||||
let out = d.drag(tab(&d, PROGRAM), pos2(info.left() + 10.0, info.center().y + 13.0));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: PROGRAM, anchor: INFO, placement: Placement::Split(Zone::Left) }]);
|
||||
d.settle();
|
||||
assert!(matches!(window_of(&d.layout, INFO).root, Node::Split { axis: SplitAxis::Horizontal, .. }), "{:?}", d.layout.floating);
|
||||
let (program, info) = (group(&d, PROGRAM), group(&d, INFO));
|
||||
assert!(program.right() < info.left() && (program.width() - info.width()).abs() < 2.0, "{program:?} {info:?}");
|
||||
|
||||
// A drag bar inside the window moves its group to a group of the main area.
|
||||
let timeline = group(&d, TIMELINE);
|
||||
let bar = d.hit(&Hit::DragBar(INFO)).unwrap().center();
|
||||
let out = d.drag(bar, timeline.center() + vec2(0.0, 13.0));
|
||||
assert_eq!(out.actions, vec![Action::MoveGroup { panel: INFO, to: Target::At { anchor: TIMELINE, placement: Placement::Split(Zone::Center) } }]);
|
||||
d.settle();
|
||||
assert_eq!(window_of(&d.layout, PROGRAM).root, tabs(&[PROGRAM]));
|
||||
assert_eq!(panel_set(&d.layout), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_floating_window_tree_resizes_by_its_dividers_and_intersections() {
|
||||
let mut layout = editing();
|
||||
let tree = hsplit(0.5, tabs(&[INFO]), split(SplitAxis::Vertical, 0.5, tabs(&[50]), tabs(&[51])));
|
||||
layout.floating = vec![Floating::new(tree, [700.0, 100.0, 600.0, 500.0])];
|
||||
let mut d = driver(layout, Film::default());
|
||||
let ratios = |d: &Driver| match &d.layout.floating[0].root {
|
||||
Node::Split { size: SplitSize::Ratio(outer), second, .. } => match &**second {
|
||||
Node::Split { size: SplitSize::Ratio(inner), .. } => (*outer, *inner),
|
||||
other => panic!("{other:?}"),
|
||||
},
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let outer = Hit::Divider(Divider::WindowSplit(INFO, Vec::new()));
|
||||
let inner = Hit::Divider(Divider::WindowSplit(INFO, vec![true]));
|
||||
for (hit, delta) in [(&outer, vec2(30.0, 0.0)), (&outer, vec2(-60.0, 0.0)), (&inner, vec2(0.0, 30.0)), (&inner, vec2(0.0, -60.0))] {
|
||||
let before = ratios(&d);
|
||||
drag_hit(&mut d, hit.clone(), delta);
|
||||
let after = ratios(&d);
|
||||
let moved = if hit == &outer { (after.0 - before.0) * delta.x } else { (after.1 - before.1) * delta.y };
|
||||
assert!(moved > 0.0, "{hit:?} by {delta:?}: {before:?} to {after:?}");
|
||||
assert_eq!(d.layout.root, editing().root, "the main area keeps its sizes");
|
||||
}
|
||||
// The four-way handle where the inner divider meets the outer one moves both.
|
||||
let before = ratios(&d);
|
||||
drag_hit(&mut d, Hit::Divider(Divider::WindowIntersection(INFO, Vec::new(), vec![true])), vec2(25.0, 25.0));
|
||||
let after = ratios(&d);
|
||||
assert!(after.0 > before.0 && after.1 > before.1, "{before:?} to {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moves_between_windows_are_one_action_and_lose_no_panel() {
|
||||
let mut layout = editing();
|
||||
layout.floating.push(Floating::single(vec![50, 51], 0, [200.0, 520.0, 320.0, 260.0]));
|
||||
let mut d = driver(layout, Film::default());
|
||||
let all = panel_set(&d.layout);
|
||||
// Floating to floating: a whole group, by its drag bar, beside Info.
|
||||
let info = group(&d, INFO);
|
||||
let bar = d.hit(&Hit::DragBar(50)).unwrap().center();
|
||||
let out = d.drag(bar, pos2(info.right() - 10.0, info.center().y + 13.0));
|
||||
assert_eq!(out.actions, vec![Action::MoveGroup { panel: 50, to: Target::At { anchor: INFO, placement: Placement::Split(Zone::Right) } }]);
|
||||
d.settle();
|
||||
assert_eq!(d.layout.floating.len(), 1);
|
||||
assert_eq!(panel_set(&d.layout), all);
|
||||
// Main to floating: a tab joins the window's group.
|
||||
let fifty = group(&d, 50);
|
||||
let out = d.drag(tab(&d, SOURCE[1]), fifty.center() + vec2(0.0, 13.0));
|
||||
assert_eq!(out.actions, vec![Action::Move { panel: SOURCE[1], anchor: 50, placement: Placement::Split(Zone::Center) }]);
|
||||
d.settle();
|
||||
assert!(window_of(&d.layout, 50).contains(&SOURCE[1]));
|
||||
assert_eq!(panel_set(&d.layout), all);
|
||||
assert_eq!(d.layout.validate(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_floating_window_closes_its_panels_and_each_reopens_where_it_was() {
|
||||
let mut layout = editing();
|
||||
let tree = hsplit(0.4, tabs(&[INFO]), tabs(&[50]));
|
||||
layout.floating = vec![Floating::new(tree.clone(), [700.0, 100.0, 600.0, 400.0])];
|
||||
let mut d = driver(layout, Film::default());
|
||||
let locations: Vec<_> = [INFO, 50].into_iter().map(|p| (p, d.layout.location(&p).unwrap())).collect();
|
||||
let close = d.hit(&Hit::Close(INFO)).unwrap().center();
|
||||
let out = d.click(close);
|
||||
assert_eq!(out.actions, vec![Action::CloseWindow { panel: INFO }]);
|
||||
assert!(d.layout.floating.is_empty() && !d.layout.contains(&50));
|
||||
for (panel, location) in &locations {
|
||||
d.layout.restore(*panel, location).unwrap();
|
||||
}
|
||||
let window = &d.layout.floating[0];
|
||||
assert_eq!((&window.root, window.rect), (&tree, [700.0, 100.0, 600.0, 400.0]));
|
||||
}
|
||||
|
||||
/// The zone outlines of the last frame: closed 1 pt paths without a fill.
|
||||
fn zone_outlines(d: &Driver) -> Vec<Vec<Pos2>> {
|
||||
d.shapes()
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Path(path) if path.closed && path.fill == egui::Color32::TRANSPARENT && path.stroke.width == 1.0 => {
|
||||
Some(path.points.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same_polygon(a: &[Pos2], b: &[Pos2]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.distance(*b) <= 0.5)
|
||||
}
|
||||
|
||||
fn corners(rect: Rect) -> Vec<Pos2> {
|
||||
vec![rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_fills_the_zone_under_the_pointer_and_no_result_rect() {
|
||||
let d = film();
|
||||
let timeline = group(&d, TIMELINE);
|
||||
let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0));
|
||||
// A side band: its trapezoid, without the half the panel takes.
|
||||
for (zone, at) in
|
||||
[(Zone::Left, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)), (Zone::Bottom, pos2(timeline.center().x, timeline.bottom() - 20.0))]
|
||||
{
|
||||
let mut d = film();
|
||||
d.hold(tab(&d, INFO), at);
|
||||
assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, zone).unwrap()), "{zone:?}");
|
||||
assert!(!d.outlined(zone_rect(timeline, zone).unwrap().shrink(1.0)), "{zone:?}");
|
||||
d.key(egui::Key::Escape);
|
||||
}
|
||||
// The middle and the tab row: the center rectangle and the strip.
|
||||
for at in [timeline.center() + vec2(0.0, 13.0), strip.center()] {
|
||||
let mut d = film();
|
||||
d.hold(tab(&d, INFO), at);
|
||||
assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, Zone::Center).unwrap()), "{at:?}");
|
||||
assert!(d.filled_polygon(&corners(strip)), "{at:?}");
|
||||
assert!(!d.outlined(timeline.shrink(1.0)), "{at:?}");
|
||||
d.key(egui::Key::Escape);
|
||||
}
|
||||
// A group's drag bar shows the same.
|
||||
let mut d = film();
|
||||
let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center();
|
||||
d.hold(bar, pos2(timeline.left() + 8.0, timeline.center().y + 13.0));
|
||||
assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, Zone::Left).unwrap()));
|
||||
assert_eq!(zone_outlines(&d).len(), 6);
|
||||
d.key(egui::Key::Escape);
|
||||
|
||||
// The dock-and-canvas arrangement keeps its filled half.
|
||||
let mut d = DockDriver::new(editing(), Film::default());
|
||||
d.screen = Rect::from_min_size(Pos2::ZERO, SCREEN);
|
||||
d.area = d.screen;
|
||||
d.settle();
|
||||
d.hold(tab(&d, INFO), pos2(timeline.left() + 8.0, timeline.center().y + 13.0));
|
||||
assert!(!d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, Zone::Left).unwrap()));
|
||||
assert!(zone_outlines(&d).is_empty());
|
||||
assert!(d.filled(zone_rect(timeline, Zone::Left).unwrap().shrink(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_over_a_group_outlines_all_its_zones_and_fills_the_one_drop_zone_names() {
|
||||
let d = film();
|
||||
let timeline = group(&d, TIMELINE);
|
||||
let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0));
|
||||
let shape = |zone| zone_shape(timeline, 26.0, 40.0, zone).unwrap();
|
||||
let all: Vec<Vec<Pos2>> =
|
||||
[Zone::Left, Zone::Right, Zone::Top, Zone::Bottom, Zone::Center].map(shape).into_iter().chain([corners(strip)]).collect();
|
||||
let body = Rect::from_min_max(pos2(timeline.left(), strip.bottom()), timeline.max);
|
||||
// Each band, near its corners too, the middle, and the tab row.
|
||||
let points = [
|
||||
pos2(body.left() + 30.0, body.center().y),
|
||||
pos2(body.left() + 30.0, body.top() + 34.0),
|
||||
pos2(body.right() - 2.0, body.bottom() - 12.0),
|
||||
pos2(body.center().x, body.top() + 5.0),
|
||||
pos2(body.left() + 50.0, body.bottom() - 30.0),
|
||||
body.center(),
|
||||
pos2(body.left() + 45.0, body.top() + 45.0),
|
||||
strip.center(),
|
||||
];
|
||||
for at in points {
|
||||
let mut d = film();
|
||||
d.hold(tab(&d, INFO), at);
|
||||
let outlines = zone_outlines(&d);
|
||||
assert_eq!(outlines.len(), all.len(), "{at:?}: four sides, the center and the strip");
|
||||
assert!(all.iter().all(|zone| outlines.iter().any(|o| same_polygon(o, zone))), "{at:?}: only Timeline's zones");
|
||||
let zone = drop_zone(timeline, 26.0, 40.0, at).unwrap();
|
||||
assert!(d.filled_polygon(&shape(zone)), "{at:?}: {zone:?} is filled");
|
||||
let filled = all.iter().filter(|z| d.filled_polygon(z)).count();
|
||||
assert_eq!(filled, if zone == Zone::Center { 2 } else { 1 }, "{at:?}: only {zone:?}");
|
||||
d.key(egui::Key::Escape);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zones_a_group_does_not_take_are_not_drawn() {
|
||||
let timeline = group(&film(), TIMELINE);
|
||||
let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0));
|
||||
let shape = |zone| zone_shape(timeline, 26.0, 40.0, zone).unwrap();
|
||||
let at = pos2(timeline.left() + 8.0, timeline.center().y + 13.0);
|
||||
let content = |rules: Permissions| Film { rules: HashMap::from([(TIMELINE, rules)]), ..Film::default() };
|
||||
// No splits: the center and the strip only, and the left band under the pointer neither
|
||||
// outlined nor filled.
|
||||
let mut d = driver(editing(), content(Permissions { accepts_splits: false, ..Permissions::default() }));
|
||||
d.hold(tab(&d, INFO), at);
|
||||
let outlines = zone_outlines(&d);
|
||||
assert_eq!(outlines.len(), 2, "{outlines:?}");
|
||||
assert!(outlines.iter().any(|o| same_polygon(o, &shape(Zone::Center))) && outlines.iter().any(|o| same_polygon(o, &corners(strip))));
|
||||
assert!(!d.filled_polygon(&shape(Zone::Left)));
|
||||
d.key(egui::Key::Escape);
|
||||
// No tabs: the four sides only.
|
||||
let mut d = driver(editing(), content(Permissions { accepts_tabs: false, ..Permissions::default() }));
|
||||
d.hold(tab(&d, INFO), at);
|
||||
let outlines = zone_outlines(&d);
|
||||
assert_eq!(outlines.len(), 4, "{outlines:?}");
|
||||
assert!([Zone::Left, Zone::Right, Zone::Top, Zone::Bottom].into_iter().all(|z| outlines.iter().any(|o| same_polygon(o, &shape(z)))));
|
||||
assert!(d.filled_polygon(&shape(Zone::Left)));
|
||||
d.key(egui::Key::Escape);
|
||||
// A tab over its own single-tab group: nothing to drop on.
|
||||
let mut d = film();
|
||||
d.hold(tab(&d, TIMELINE), timeline.center() + vec2(0.0, 13.0));
|
||||
assert!(zone_outlines(&d).is_empty());
|
||||
}
|
||||
+596
-669
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
use egui::{Pos2, Rect, pos2};
|
||||
use egui::{Pos2, Rangef, Rect, Vec2, pos2};
|
||||
|
||||
use super::{Placement, Zone};
|
||||
use super::{Placement, Side, Target, Zone};
|
||||
|
||||
/// One visible group, supplied in back-to-front order to [`resolve_drop`]. An empty tab strip
|
||||
/// or a group that rejects tabs may still accept side splits, e.g. a protected document canvas.
|
||||
@@ -12,6 +12,9 @@ pub struct DropTarget<P> {
|
||||
pub tabs: Vec<(P, Rect)>,
|
||||
pub allow_splits: bool,
|
||||
pub accepts_tabs: bool,
|
||||
/// The strip runs right to left: the first tab is rightmost, and an insertion slot sits
|
||||
/// at the right edge of the tab it precedes.
|
||||
pub right_to_left: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -20,26 +23,87 @@ pub struct DropProposal<P> {
|
||||
pub placement: Placement<P>,
|
||||
pub preview: Rect,
|
||||
pub insertion: Option<Rect>,
|
||||
/// The pointer addresses the tab's current insertion slot.
|
||||
pub noop: bool,
|
||||
}
|
||||
|
||||
pub(super) fn usable(rect: Rect) -> bool {
|
||||
rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0 && rect.width() <= 1_000_000.0 && rect.height() <= 1_000_000.0
|
||||
}
|
||||
|
||||
/// Tab header is the center; otherwise the nearest quarter-width/height edge wins.
|
||||
/// Outside, non-finite, empty and inverted rectangles have no target.
|
||||
pub fn drop_zone(rect: Rect, tab_height: f32, pointer: Pos2) -> Option<Zone> {
|
||||
/// Tab header (the top `tab_height` of `rect`) is the center; otherwise the nearest side zone of
|
||||
/// the body below it wins. Every side zone reaches the same depth into the body: `depth`, or a
|
||||
/// quarter of the body's smaller side when that is less, so a body always keeps a center and a
|
||||
/// narrow body's top and bottom zones are no deeper than its left and right ones. A `depth` of
|
||||
/// zero or less leaves only the center. Outside, non-finite, empty and inverted rectangles have
|
||||
/// no target.
|
||||
pub fn drop_zone(rect: Rect, tab_height: f32, depth: f32, pointer: Pos2) -> Option<Zone> {
|
||||
if !usable(rect) || !pointer.is_finite() || !rect.contains(pointer) || !tab_height.is_finite() || tab_height < 0.0 {
|
||||
return None;
|
||||
}
|
||||
if pointer.y < rect.top() + tab_height.min(rect.height()) {
|
||||
let body = body(rect, tab_height);
|
||||
if pointer.y < body.top() || !usable(body) {
|
||||
return Some(Zone::Center);
|
||||
}
|
||||
let x = (pointer.x - rect.left()) / rect.width();
|
||||
let y = (pointer.y - rect.top()) / rect.height();
|
||||
let distances = [(x, Zone::Left), (1.0 - x, Zone::Right), (y, Zone::Top), (1.0 - y, Zone::Bottom)];
|
||||
let (distance, zone) = distances.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?;
|
||||
Some(if distance > 0.25 { Zone::Center } else { zone })
|
||||
let Vec2 { x, y } = side_depths(body, depth);
|
||||
let sides = [
|
||||
(pointer.x - body.left(), x, Zone::Left),
|
||||
(body.right() - pointer.x, x, Zone::Right),
|
||||
(pointer.y - body.top(), y, Zone::Top),
|
||||
(body.bottom() - pointer.y, y, Zone::Bottom),
|
||||
];
|
||||
let nearest =
|
||||
sides.into_iter().filter(|(_, depth, _)| *depth > 0.0).map(|(gap, depth, zone)| (gap / depth, zone)).min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
Some(match nearest {
|
||||
Some((distance, zone)) if distance <= 1.0 => zone,
|
||||
_ => Zone::Center,
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of a group drawn at `rect` below its tab header.
|
||||
fn body(rect: Rect, tab_height: f32) -> Rect {
|
||||
Rect::from_min_max(pos2(rect.left(), rect.top() + tab_height.min(rect.height())), rect.max)
|
||||
}
|
||||
|
||||
/// How deep the side zones of `body` reach in from its left and right edges (`x`) and its top
|
||||
/// and bottom edges (`y`): the same on all four sides.
|
||||
fn side_depths(body: Rect, depth: f32) -> Vec2 {
|
||||
let depth = if depth > 0.0 { depth } else { 0.0 };
|
||||
Vec2::splat(depth.min(body.width().min(body.height()) / 4.0))
|
||||
}
|
||||
|
||||
/// The outline of a drop zone of the group drawn at `rect`, as [`drop_zone`] finds it with the
|
||||
/// same `tab_height` and `depth`: a side's trapezoid (its outer edge the whole side of the body,
|
||||
/// its inner edge on the center rectangle), or the center rectangle. The tab header, a grouping
|
||||
/// zone too, is not part of any shape. None for a side without depth.
|
||||
pub fn zone_shape(rect: Rect, tab_height: f32, depth: f32, zone: Zone) -> Option<Vec<Pos2>> {
|
||||
if !usable(rect) || !tab_height.is_finite() || tab_height < 0.0 {
|
||||
return None;
|
||||
}
|
||||
let body = body(rect, tab_height);
|
||||
let depths = side_depths(body, depth);
|
||||
let flat = match zone {
|
||||
Zone::Left | Zone::Right => depths.x <= 0.0,
|
||||
Zone::Top | Zone::Bottom => depths.y <= 0.0,
|
||||
Zone::Center => false,
|
||||
};
|
||||
if !usable(body) || flat {
|
||||
return None;
|
||||
}
|
||||
let inner = body.shrink2(depths);
|
||||
Some(match zone {
|
||||
Zone::Left => vec![body.left_top(), inner.left_top(), inner.left_bottom(), body.left_bottom()],
|
||||
Zone::Right => vec![inner.right_top(), body.right_top(), body.right_bottom(), inner.right_bottom()],
|
||||
Zone::Top => vec![body.left_top(), body.right_top(), inner.right_top(), inner.left_top()],
|
||||
Zone::Bottom => vec![inner.left_bottom(), inner.right_bottom(), body.right_bottom(), body.left_bottom()],
|
||||
Zone::Center => vec![inner.left_top(), inner.right_top(), inner.right_bottom(), inner.left_bottom()],
|
||||
})
|
||||
}
|
||||
|
||||
/// Height of the tab header of `target` that [`resolve_drop`] treats as a grouping zone: from the
|
||||
/// top of its rect to the bottom of its tab strip.
|
||||
pub(super) fn header_height<P>(target: &DropTarget<P>) -> f32 {
|
||||
target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|strip| usable(*strip)).map_or(0.0, |strip| strip.bottom() - target.rect.top())
|
||||
}
|
||||
|
||||
/// Preview of the region occupied after a split or group merge.
|
||||
@@ -57,10 +121,41 @@ pub fn zone_rect(rect: Rect, zone: Zone) -> Option<Rect> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounded insertion marker for a logical slot in a measured tab strip. Hidden tabs
|
||||
/// retain their order; their slot uses the next visible boundary or the visible strip end.
|
||||
pub fn tab_insertion_marker<P: Eq>(target: &DropTarget<P>, before: Option<&P>) -> Option<Rect> {
|
||||
if target.tabs.len() > super::MAX_PANELS || !target.accepts_tabs || !usable(target.rect) {
|
||||
return None;
|
||||
}
|
||||
let strip = target.tab_strip?.intersect(target.rect);
|
||||
if !usable(strip) {
|
||||
return None;
|
||||
}
|
||||
let index = before.and_then(|before| target.tabs.iter().position(|(panel, _)| panel == before));
|
||||
let rtl = target.right_to_left;
|
||||
let leading = |rect: &Rect| if rtl { rect.right() } else { rect.left() };
|
||||
let visible = || target.tabs.iter().filter(|(_, rect)| usable(*rect)).map(|(_, rect)| rect);
|
||||
let x = index
|
||||
.and_then(|index| target.tabs.get(index..))
|
||||
.and_then(|tabs| tabs.iter().find(|(_, rect)| usable(*rect)).map(|(_, rect)| leading(rect)))
|
||||
.unwrap_or_else(|| {
|
||||
if rtl {
|
||||
visible().map(|rect| rect.left()).fold(strip.right(), f32::min).max(strip.left())
|
||||
} else {
|
||||
visible().map(|rect| rect.right()).fold(strip.left(), f32::max).min(strip.right())
|
||||
}
|
||||
});
|
||||
let width = strip.width().min(2.0);
|
||||
let left = (x - width * 0.5).max(strip.left()).min((strip.right() - width).max(strip.left()));
|
||||
Some(Rect::from_min_max(pos2(left, strip.top()), pos2((left + width).min(strip.right()), strip.bottom())))
|
||||
}
|
||||
|
||||
/// Resolve a pointer against visible groups. The frontmost containing group occludes groups
|
||||
/// behind it even if it rejects the drop. A strip reorders by midpoint; the body of the source
|
||||
/// group is a no-op at center. Floating groups normally set `allow_splits` to false.
|
||||
pub fn resolve_drop<P: Clone + Eq>(panel: &P, pointer: Pos2, targets: &[DropTarget<P>]) -> Option<DropProposal<P>> {
|
||||
/// group is a no-op at center. The body's side zones are [`drop_zone`]'s with `zone_depth` (see
|
||||
/// [`crate::docking::DockStyle::zone_depth`]): one depth on all four sides, at most a quarter of
|
||||
/// the body's smaller side. Floating groups normally set `allow_splits` to false.
|
||||
pub fn resolve_drop<P: Clone + Eq>(panel: &P, pointer: Pos2, targets: &[DropTarget<P>], zone_depth: f32) -> Option<DropProposal<P>> {
|
||||
if !pointer.is_finite() || targets.len() > super::MAX_PANELS {
|
||||
return None;
|
||||
}
|
||||
@@ -68,26 +163,49 @@ pub fn resolve_drop<P: Clone + Eq>(panel: &P, pointer: Pos2, targets: &[DropTarg
|
||||
if target.tabs.len() > super::MAX_PANELS {
|
||||
return None;
|
||||
}
|
||||
let anchor = if &target.anchor == panel { target.tabs.iter().find(|(p, _)| p != panel).map(|(p, _)| p)? } else { &target.anchor };
|
||||
let strip = target.tab_strip.filter(|r| usable(*r) && r.contains(pointer));
|
||||
if let Some(strip) = strip {
|
||||
let anchor = if &target.anchor == panel { target.tabs.iter().find(|(p, _)| p != panel).map(|(p, _)| p).unwrap_or(panel) } else { &target.anchor };
|
||||
let strip = target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|r| usable(*r) && r.contains(pointer));
|
||||
if strip.is_some() {
|
||||
if !target.accepts_tabs {
|
||||
return None;
|
||||
}
|
||||
let before = target.tabs.iter().filter(|(_, r)| usable(*r)).find(|(_, r)| pointer.x < r.center().x);
|
||||
let ahead = |r: &Rect| if target.right_to_left { pointer.x > r.center().x } else { pointer.x < r.center().x };
|
||||
let before = target.tabs.iter().filter(|(_, r)| usable(*r)).find(|(_, r)| ahead(r));
|
||||
let before_panel = before.map(|(p, _)| p.clone());
|
||||
let x = before.map(|(_, r)| r.left()).unwrap_or_else(|| {
|
||||
target.tabs.iter().filter(|(_, r)| usable(*r)).map(|(_, r)| r.right()).fold(strip.left(), f32::max).min(strip.right())
|
||||
});
|
||||
let insertion = Rect::from_min_max(pos2((x - 1.0).max(strip.left()), strip.top()), pos2((x + 1.0).min(strip.right()), strip.bottom()));
|
||||
let insertion = tab_insertion_marker(target, before_panel.as_ref())?;
|
||||
let old_order: Vec<_> = target.tabs.iter().map(|(p, _)| p).collect();
|
||||
let mut order = old_order.clone();
|
||||
let noop = if before_panel.as_ref() == Some(panel) {
|
||||
old_order.contains(&panel)
|
||||
} else if old_order.contains(&panel) {
|
||||
order.retain(|p| *p != panel);
|
||||
let at = before_panel.as_ref().and_then(|before| order.iter().position(|p| *p == before)).unwrap_or(order.len());
|
||||
order.insert(at, panel);
|
||||
order == old_order
|
||||
} else {
|
||||
false
|
||||
};
|
||||
return Some(DropProposal {
|
||||
anchor: anchor.clone(),
|
||||
placement: Placement::Tab { before: before_panel },
|
||||
preview: target.rect,
|
||||
insertion: Some(insertion),
|
||||
noop,
|
||||
});
|
||||
}
|
||||
let zone = if target.allow_splits { drop_zone(target.rect, 0.0, pointer)? } else { Zone::Center };
|
||||
let zone = if target.allow_splits { drop_zone(target.rect, header_height(target), zone_depth, pointer)? } else { Zone::Center };
|
||||
if zone == Zone::Center && target.accepts_tabs && target.tabs.iter().any(|(p, _)| p == panel) {
|
||||
return Some(DropProposal {
|
||||
anchor: anchor.clone(),
|
||||
placement: Placement::Tab { before: Some(panel.clone()) },
|
||||
preview: target.rect,
|
||||
insertion: None,
|
||||
noop: true,
|
||||
});
|
||||
}
|
||||
if anchor == panel {
|
||||
return None;
|
||||
}
|
||||
if zone == Zone::Center {
|
||||
if !target.accepts_tabs || target.tabs.iter().any(|(p, _)| p == panel) {
|
||||
return None;
|
||||
@@ -95,5 +213,83 @@ pub fn resolve_drop<P: Clone + Eq>(panel: &P, pointer: Pos2, targets: &[DropTarg
|
||||
} else if !target.allow_splits {
|
||||
return None;
|
||||
}
|
||||
Some(DropProposal { anchor: anchor.clone(), placement: Placement::Split(zone), preview: zone_rect(target.rect, zone)?, insertion: None })
|
||||
Some(DropProposal {
|
||||
anchor: anchor.clone(),
|
||||
placement: Placement::Split(zone),
|
||||
preview: zone_rect(target.rect, zone)?,
|
||||
insertion: None,
|
||||
noop: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// [D] A dock drop target, built once per frame next to the [`DropTarget`]s. The pointer selects
|
||||
/// it inside `band`; the preview is the line `line`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct DockDrop<P> {
|
||||
pub(super) target: DockTarget<P>,
|
||||
pub(super) band: Rect,
|
||||
pub(super) line: Rect,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) enum DockTarget<P> {
|
||||
/// Column edge: a new column beside the column of `anchor`, further from the window edge
|
||||
/// when `after` (P5).
|
||||
ColumnEdge { anchor: P, after: bool },
|
||||
/// The seam between two stacked groups: a new group below the group of `anchor` (P4).
|
||||
Seam { anchor: P },
|
||||
/// The top or bottom quarter of a group body, or the free room under a column's last group (P3).
|
||||
GroupBand { anchor: P, below: bool },
|
||||
/// A window edge without a dock, or an empty dock (P5, P6).
|
||||
NewDock { side: Side },
|
||||
}
|
||||
|
||||
impl<P: Clone> DockTarget<P> {
|
||||
pub(super) fn to(&self) -> Target<P> {
|
||||
match self {
|
||||
Self::ColumnEdge { anchor, after } => Target::At { anchor: anchor.clone(), placement: Placement::Column { after: *after } },
|
||||
Self::Seam { anchor } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: true, height: None } },
|
||||
Self::GroupBand { anchor, below } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: *below, height: None } },
|
||||
Self::NewDock { side } => Target::NewDock { side: *side },
|
||||
}
|
||||
}
|
||||
|
||||
/// Rank in resolution order: column edges reach past their columns, so they come first.
|
||||
fn rank(&self) -> u8 {
|
||||
match self {
|
||||
Self::ColumnEdge { .. } => 0,
|
||||
Self::Seam { .. } => 1,
|
||||
Self::GroupBand { .. } => 2,
|
||||
Self::NewDock { .. } => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The dock target under the pointer: column edges, then seams, then group bands, then new docks.
|
||||
pub(super) fn resolve_dock<P: Clone>(pointer: Pos2, targets: &[DockDrop<P>]) -> Option<&DockDrop<P>> {
|
||||
if !pointer.is_finite() {
|
||||
return None;
|
||||
}
|
||||
targets.iter().filter(|t| usable(t.band) && t.band.contains(pointer)).min_by_key(|t| t.target.rank())
|
||||
}
|
||||
|
||||
/// Width of the insertion lines dock targets preview with.
|
||||
const LINE: f32 = 4.0;
|
||||
/// How far a column edge band reaches into the column, and past the edge out of it.
|
||||
const EDGE_IN: f32 = 6.0;
|
||||
const EDGE_OUT: f32 = 10.0;
|
||||
|
||||
/// Band and line of a column edge at `x`. `inward` is +1 when the column lies right of the edge,
|
||||
/// -1 when it lies left of it. The band reaches further out of the column than into it.
|
||||
pub(super) fn column_edge(x: f32, inward: f32, ys: Rangef) -> (Rect, Rect) {
|
||||
let (a, b) = (x + inward * EDGE_IN, x - inward * EDGE_OUT);
|
||||
(Rect::from_x_y_ranges(a.min(b)..=a.max(b), ys), vertical_line(x, ys))
|
||||
}
|
||||
|
||||
pub(super) fn vertical_line(x: f32, ys: Rangef) -> Rect {
|
||||
Rect::from_x_y_ranges((x - LINE * 0.5)..=(x + LINE * 0.5), ys)
|
||||
}
|
||||
|
||||
pub(super) fn horizontal_line(y: f32, xs: Rangef) -> Rect {
|
||||
Rect::from_x_y_ranges(xs, (y - LINE * 0.5)..=(y + LINE * 0.5))
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Drive a [`DockArea`] with real egui input in application tests (feature `testing`).
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let mut driver = DockDriver::new(app_layout(), Panels::default());
|
||||
//! let bar = driver.hit(&Hit::DragBar(PanelId::Layers)).unwrap();
|
||||
//! driver.drag(bar.center(), egui::pos2(2.0, 300.0));
|
||||
//! driver.settle();
|
||||
//! assert!(driver.hit(&Hit::ColumnBar(PanelId::Layers)).is_some());
|
||||
//! ```
|
||||
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
|
||||
use egui::{Context, Event, Id, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, UiBuilder, epaint::ClippedShape, vec2};
|
||||
|
||||
use super::{DockArea, DockContent, DockOutput, DockStyle, Hit, Layout};
|
||||
|
||||
/// Pointer travel that starts a drag before moving to its destination.
|
||||
const NUDGE: egui::Vec2 = egui::Vec2::new(8.0, 6.0);
|
||||
|
||||
type StyleFn = Box<dyn Fn(&mut DockStyle)>;
|
||||
|
||||
/// A [`DockArea`] in a headless egui context, with its layout and content. Each frame advances
|
||||
/// the clock by 1/60 s, so double-clicks register. [`Self::step`] applies what a frame emits,
|
||||
/// the way an application's command path would.
|
||||
pub struct DockDriver<P, C> {
|
||||
pub ctx: Context,
|
||||
pub layout: Layout<P>,
|
||||
pub content: C,
|
||||
/// The area's id, for [`DockArea::hit_rects`] and the free docking functions.
|
||||
pub id: Id,
|
||||
/// The window, 800x600 by default.
|
||||
pub screen: Rect,
|
||||
/// Where the area draws inside the window; the whole window by default.
|
||||
pub area: Rect,
|
||||
/// Whether the window has focus. Losing it cancels gestures (C2).
|
||||
pub focused: bool,
|
||||
/// Modifiers held for the following events.
|
||||
pub modifiers: Modifiers,
|
||||
/// Passed to [`DockArea::auto_collapse_iconic`].
|
||||
pub auto_collapse: bool,
|
||||
/// Passed to [`DockArea::maximized`].
|
||||
pub maximized: Option<P>,
|
||||
/// Passed to [`DockArea::raise_panel`] on the next frame only.
|
||||
pub raise: Option<P>,
|
||||
/// Passed to [`DockArea::float_bounds`].
|
||||
pub float_bounds: Option<Rect>,
|
||||
style: Option<StyleFn>,
|
||||
shapes: Vec<ClippedShape>,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static, C: DockContent<P>> DockDriver<P, C> {
|
||||
/// A driver whose first frames have settled, so every control has its rect.
|
||||
pub fn new(layout: Layout<P>, content: C) -> Self {
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
|
||||
let mut driver = Self {
|
||||
ctx: Context::default(),
|
||||
layout,
|
||||
content,
|
||||
id: Id::new("dock-driver"),
|
||||
screen,
|
||||
area: screen,
|
||||
focused: true,
|
||||
modifiers: Modifiers::NONE,
|
||||
auto_collapse: true,
|
||||
maximized: None,
|
||||
raise: None,
|
||||
float_bounds: None,
|
||||
style: None,
|
||||
shapes: Vec::new(),
|
||||
time: 0.0,
|
||||
};
|
||||
driver.settle();
|
||||
driver
|
||||
}
|
||||
|
||||
/// Adjust the style each frame, after [`DockStyle::from_ui`]. Settles again.
|
||||
pub fn with_style(mut self, style: impl Fn(&mut DockStyle) + 'static) -> Self {
|
||||
self.style = Some(Box::new(style));
|
||||
self.settle();
|
||||
self
|
||||
}
|
||||
|
||||
/// Draw in `area` of the window. Settles again.
|
||||
pub fn with_area(mut self, area: Rect) -> Self {
|
||||
self.area = area;
|
||||
self.settle();
|
||||
self
|
||||
}
|
||||
|
||||
/// Render one frame with `events` and return its output. Nothing is applied.
|
||||
pub fn frame(&mut self, events: Vec<Event>) -> DockOutput<P> {
|
||||
let mut output = DockOutput::default();
|
||||
self.time += 1.0 / 60.0;
|
||||
let input = RawInput {
|
||||
screen_rect: Some(self.screen),
|
||||
events: std::iter::once(Event::ModifiersChanged(self.modifiers)).chain(events).collect(),
|
||||
focused: self.focused,
|
||||
time: Some(self.time),
|
||||
..Default::default()
|
||||
};
|
||||
let (layout, content, area, id) = (&self.layout, &mut self.content, self.area, self.id);
|
||||
let (style_fn, maximized, raise, auto, bounds) =
|
||||
(&self.style, self.maximized.clone(), self.raise.take(), self.auto_collapse, self.float_bounds);
|
||||
let mut full = self.ctx.run_ui(input, |ui| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
if let Some(adjust) = style_fn {
|
||||
adjust(&mut style);
|
||||
}
|
||||
ui.scope_builder(UiBuilder::new().max_rect(area), |ui| {
|
||||
let mut dock = DockArea::new(id).maximized(maximized.clone()).auto_collapse_iconic(auto);
|
||||
if let Some(panel) = raise.clone() {
|
||||
dock = dock.raise_panel(panel);
|
||||
}
|
||||
if let Some(bounds) = bounds {
|
||||
dock = dock.float_bounds(bounds);
|
||||
}
|
||||
output = dock.show_content(ui, layout, &style, content);
|
||||
});
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
self.shapes = full.shapes;
|
||||
output
|
||||
}
|
||||
|
||||
/// Render one frame and apply its actions, all or none, with the content's permissions. A
|
||||
/// rejected batch is reported in the output's `error`.
|
||||
pub fn step(&mut self, events: Vec<Event>) -> DockOutput<P> {
|
||||
let mut output = self.frame(events);
|
||||
if output.error.is_none()
|
||||
&& let Err(error) = self.layout.apply_all(output.actions.clone(), |p| self.content.permissions(p))
|
||||
{
|
||||
output.error = Some(error);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Empty frames until moved widgets report their rects; egui reports them a frame late.
|
||||
pub fn settle(&mut self) {
|
||||
for _ in 0..3 {
|
||||
self.step(Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_to(&mut self, pos: Pos2) -> DockOutput<P> {
|
||||
self.step(vec![Event::PointerMoved(pos)])
|
||||
}
|
||||
|
||||
pub fn press(&mut self, pos: Pos2) -> DockOutput<P> {
|
||||
self.step(vec![Event::PointerMoved(pos), self.button(pos, true)])
|
||||
}
|
||||
|
||||
pub fn release(&mut self, pos: Pos2) -> DockOutput<P> {
|
||||
self.step(vec![Event::PointerMoved(pos), self.button(pos, false)])
|
||||
}
|
||||
|
||||
/// Press and release at `pos`; the output is the release frame's.
|
||||
pub fn click(&mut self, pos: Pos2) -> DockOutput<P> {
|
||||
self.press(pos);
|
||||
self.release(pos)
|
||||
}
|
||||
|
||||
/// Press at `from`, move past the drag threshold and on to `to`, without releasing.
|
||||
pub fn hold(&mut self, from: Pos2, to: Pos2) -> DockOutput<P> {
|
||||
self.press(from);
|
||||
self.move_to(from + NUDGE);
|
||||
self.move_to(to)
|
||||
}
|
||||
|
||||
/// A whole drag; the output is the release frame's.
|
||||
pub fn drag(&mut self, from: Pos2, to: Pos2) -> DockOutput<P> {
|
||||
self.hold(from, to);
|
||||
self.release(to)
|
||||
}
|
||||
|
||||
/// Press and release `key` in one frame.
|
||||
pub fn key(&mut self, key: Key) -> DockOutput<P> {
|
||||
let modifiers = self.modifiers;
|
||||
self.step(vec![
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers },
|
||||
Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers },
|
||||
])
|
||||
}
|
||||
|
||||
/// Give or take the window's focus for this and the following frames.
|
||||
pub fn focus(&mut self, focused: bool) -> DockOutput<P> {
|
||||
self.focused = focused;
|
||||
self.step(vec![Event::WindowFocused(focused)])
|
||||
}
|
||||
|
||||
/// The pointer leaves the window.
|
||||
pub fn leave(&mut self) -> DockOutput<P> {
|
||||
self.step(vec![Event::PointerGone])
|
||||
}
|
||||
|
||||
/// Every gesture source of the last frame.
|
||||
pub fn hits(&self) -> Vec<(Hit<P>, Rect)> {
|
||||
DockArea::<P>::hit_rects(&self.ctx, self.id)
|
||||
}
|
||||
|
||||
/// The rect of one gesture source in the last frame.
|
||||
pub fn hit(&self, hit: &Hit<P>) -> Option<Rect> {
|
||||
self.hits().into_iter().find(|(h, _)| h == hit).map(|(_, rect)| rect)
|
||||
}
|
||||
|
||||
/// The shapes of the last frame.
|
||||
pub fn shapes(&self) -> &[ClippedShape] {
|
||||
&self.shapes
|
||||
}
|
||||
|
||||
/// Whether the last frame filled `rect` (an insertion line or a split preview).
|
||||
pub fn filled(&self, rect: Rect) -> bool {
|
||||
self.shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Rect(shape) => shape.rect == rect && shape.fill != egui::Color32::TRANSPARENT,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the last frame filled a polygon with these corners, each within half a point.
|
||||
pub fn filled_polygon(&self, corners: &[Pos2]) -> bool {
|
||||
self.shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Path(path) => {
|
||||
path.fill != egui::Color32::TRANSPARENT
|
||||
&& path.points.len() == corners.len()
|
||||
&& path.points.iter().zip(corners).all(|(a, b)| a.distance(*b) <= 0.5)
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the last frame outlined `rect` without filling it.
|
||||
pub fn outlined(&self, rect: Rect) -> bool {
|
||||
self.shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Rect(shape) => shape.rect == rect && shape.fill == egui::Color32::TRANSPARENT && shape.stroke.width > 0.0,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn button(&self, pos: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: self.modifiers }
|
||||
}
|
||||
}
|
||||
+694
-67
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
use crate::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Context, Event, Id, Modifiers, PointerButton, RawInput, Rect, pos2, vec2};
|
||||
use egui::{Context, Event, Id, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
|
||||
|
||||
fn tabs(panels: &[u32], active: usize) -> Node<u32> {
|
||||
Node::Tabs { panels: panels.to_vec(), active }
|
||||
@@ -14,7 +14,7 @@ fn sample() -> Layout<u32> {
|
||||
first: Box::new(tabs(&[1], 0)),
|
||||
second: Box::new(tabs(&[2, 3, 4], 1)),
|
||||
}),
|
||||
floating: vec![Floating { panels: vec![5, 6], active: 1, rect: [80.0, 70.0, 300.0, 220.0] }],
|
||||
floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,8 +29,8 @@ fn floating_brush_panel_joins_main_tabs_without_losing_other_panels() {
|
||||
let Node::Split { size, second, .. } = layout.root.as_ref().unwrap() else { panic!() };
|
||||
assert_eq!(*size, SplitSize::FixedSecond(240.0));
|
||||
assert_eq!(**second, tabs(&[2, 3, 5, 4], 2));
|
||||
assert_eq!(layout.floating[0].panels, vec![6]);
|
||||
assert_eq!(layout.floating[0].active, 0);
|
||||
assert_eq!(layout.floating[0].groups()[0].panels, vec![6]);
|
||||
assert_eq!(layout.floating[0].groups()[0].active, 0);
|
||||
layout.validate().unwrap();
|
||||
assert_eq!(layout.panels().len(), 6);
|
||||
}
|
||||
@@ -43,21 +43,46 @@ fn detach_redock_merge_and_collapse_empty_source_containers() {
|
||||
layout.apply(move_to(1, 2, Zone::Left)).unwrap();
|
||||
assert_eq!(layout.floating.len(), 1);
|
||||
layout.apply(move_to(5, 6, Zone::Center)).unwrap();
|
||||
assert_eq!(layout.floating[0].panels, vec![6, 5]);
|
||||
assert_eq!(layout.floating[0].active, 1);
|
||||
assert_eq!(layout.floating[0].groups()[0].panels, vec![6, 5]);
|
||||
assert_eq!(layout.floating[0].groups()[0].active, 1);
|
||||
layout.apply(move_to(6, 3, Zone::Center)).unwrap();
|
||||
layout.apply(move_to(5, 3, Zone::Center)).unwrap();
|
||||
assert!(layout.floating.is_empty());
|
||||
assert_eq!(layout.panels().len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_targets_skip_the_panel_itself_and_protected_anchors() {
|
||||
let layout = sample();
|
||||
let all = |_: &u32| Permissions::default();
|
||||
let targets = layout.move_targets(&1, all);
|
||||
assert_eq!(targets.len(), 5);
|
||||
assert!(!targets.contains(&&1));
|
||||
let guarded = |p: &u32| if *p == 3 { Permissions::PROTECTED } else { Permissions::default() };
|
||||
assert!(!layout.move_targets(&1, guarded).contains(&&3));
|
||||
|
||||
// A lone panel has nowhere to go — its "Move Panel to Group" menu hides
|
||||
// (storytold/lightcraft#1768).
|
||||
let single = Layout { root: Some(tabs(&[1], 0)), floating: Vec::new() };
|
||||
assert!(single.move_targets(&1, all).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_targets_skip_the_panels_own_group() {
|
||||
let layout = sample();
|
||||
let all = |_: &u32| Permissions::default();
|
||||
assert_eq!(layout.move_targets(&3, all), vec![&1, &5, &6]);
|
||||
let pair = Layout { root: Some(tabs(&[1, 2], 0)), floating: Vec::new() };
|
||||
assert!(pair.move_targets(&1, all).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_moves_are_atomic_including_after_a_source_would_have_been_removed() {
|
||||
let layout = sample();
|
||||
for action in [
|
||||
move_to(5, 99, Zone::Center),
|
||||
move_to(99, 2, Zone::Center),
|
||||
move_to(5, 6, Zone::Left),
|
||||
Action::Move { panel: 5, anchor: 6, placement: Placement::Column { after: true } },
|
||||
move_to(5, 5, Zone::Center),
|
||||
Action::Move { panel: 5, anchor: 2, placement: Placement::Tab { before: Some(6) } },
|
||||
Action::Float { panel: 3, rect: [f32::NAN, 0.0, 100.0, 100.0] },
|
||||
@@ -119,13 +144,15 @@ fn protected_canvas_remains_present_and_cannot_be_grouped_with_panels() {
|
||||
move_to(1, 3, Zone::Center),
|
||||
move_to(3, 1, Zone::Center),
|
||||
Action::OpenAt { panel: 1, anchor: 3, placement: Placement::Tab { before: None } },
|
||||
Action::OpenAt { panel: 7, anchor: 1, placement: Placement::Split(Zone::Left) },
|
||||
] {
|
||||
let mut next = layout.clone();
|
||||
assert_eq!(next.apply_with_permissions(action, permissions), Err(DockError::NotAllowed));
|
||||
assert_eq!(next, layout);
|
||||
}
|
||||
let beside = |panel: &u32| if *panel == 1 { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() };
|
||||
let mut next = layout;
|
||||
next.apply_with_permissions(Action::OpenAt { panel: 7, anchor: 1, placement: Placement::Split(Zone::Left) }, permissions).unwrap();
|
||||
next.apply_with_permissions(Action::OpenAt { panel: 7, anchor: 1, placement: Placement::Split(Zone::Left) }, beside).unwrap();
|
||||
assert!(next.contains(&1) && next.contains(&7));
|
||||
}
|
||||
|
||||
@@ -142,6 +169,17 @@ fn moving_a_floating_group_needs_every_member_movable() {
|
||||
assert_eq!(next, layout);
|
||||
next.apply_with_permissions(Action::MoveFloating { panel: 5, rect: [0.0, 0.0, 300.0, 220.0] }, |_: &u32| Permissions::default()).unwrap();
|
||||
assert_eq!(next.floating[0].rect, [0.0, 0.0, 300.0, 220.0]);
|
||||
|
||||
// The same holds when 6 sits in another group of the window's tree.
|
||||
let mut split = sample();
|
||||
split.floating[0].root =
|
||||
Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(0.5), first: Box::new(tabs(&[5], 0)), second: Box::new(tabs(&[6], 0)) };
|
||||
let before = split.clone();
|
||||
assert_eq!(
|
||||
split.apply_with_permissions(Action::MoveFloating { panel: 5, rect: [0.0, 0.0, 300.0, 220.0] }, permissions),
|
||||
Err(DockError::NotAllowed)
|
||||
);
|
||||
assert_eq!(split, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -153,7 +191,7 @@ fn close_and_restore_preserve_fixed_side_and_floating_geometry() {
|
||||
first: Box::new(tabs(&[1], 0)),
|
||||
second: Box::new(tabs(&[2], 0)),
|
||||
}),
|
||||
floating: vec![Floating { panels: vec![3], active: 0, rect: [41.0, 52.0, 233.0, 244.0] }],
|
||||
floating: vec![Floating::single(vec![3], 0, [41.0, 52.0, 233.0, 244.0])],
|
||||
};
|
||||
let saved = layout.clone();
|
||||
let first = layout.location(&1).unwrap();
|
||||
@@ -196,12 +234,18 @@ fn closing_and_reopening_an_entire_accordion_restores_its_kind_and_heights() {
|
||||
#[test]
|
||||
fn invalid_saved_layouts_reject_duplicates_selection_depth_and_nonfinite_geometry() {
|
||||
let mut duplicate = sample();
|
||||
duplicate.floating[0].panels.push(1);
|
||||
if let Node::Tabs { panels, .. } = &mut duplicate.floating[0].root {
|
||||
panels.push(1);
|
||||
}
|
||||
assert_eq!(duplicate.validate(), Err(DockError::DuplicatePanel));
|
||||
let mut invalid = sample();
|
||||
invalid.floating[0].active = usize::MAX;
|
||||
if let Node::Tabs { active, .. } = &mut invalid.floating[0].root {
|
||||
*active = usize::MAX;
|
||||
}
|
||||
assert_eq!(invalid.validate(), Err(DockError::InvalidSelection));
|
||||
invalid.floating[0].active = 0;
|
||||
if let Node::Tabs { active, .. } = &mut invalid.floating[0].root {
|
||||
*active = 0;
|
||||
}
|
||||
invalid.floating[0].rect[3] = f32::INFINITY;
|
||||
assert_eq!(invalid.validate(), Err(DockError::InvalidGeometry));
|
||||
let mut deep = tabs(&[0], 0);
|
||||
@@ -213,6 +257,13 @@ fn invalid_saved_layouts_reject_duplicates_selection_depth_and_nonfinite_geometr
|
||||
assert_eq!(deep.apply(Action::Activate { panel: 0 }), Err(DockError::LimitExceeded));
|
||||
let oversized = Layout { root: Some(Node::Tabs { panels: (0..=MAX_PANELS as u32).collect(), active: 0 }), floating: Vec::new() };
|
||||
assert_eq!(oversized.validate(), Err(DockError::LimitExceeded));
|
||||
for empty in [tabs(&[], 0), Node::Stack { entries: Vec::new() }] {
|
||||
let root = Layout { root: Some(empty.clone()), floating: Vec::new() };
|
||||
assert_eq!(root.validate(), Err(DockError::InvalidGeometry));
|
||||
let beside =
|
||||
Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(0.5), first: Box::new(tabs(&[1], 0)), second: Box::new(empty) };
|
||||
assert_eq!(Layout { root: Some(beside), floating: Vec::new() }.validate(), Err(DockError::InvalidGeometry));
|
||||
}
|
||||
}
|
||||
|
||||
fn target(anchor: u32, members: &[u32], rect: Rect) -> DropTarget<u32> {
|
||||
@@ -228,6 +279,7 @@ fn target(anchor: u32, members: &[u32], rect: Rect) -> DropTarget<u32> {
|
||||
.collect(),
|
||||
allow_splits: true,
|
||||
accepts_tabs: true,
|
||||
right_to_left: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,52 +287,109 @@ fn target(anchor: u32, members: &[u32], rect: Rect) -> DropTarget<u32> {
|
||||
fn pointer_targets_distinguish_reorder_center_split_and_occlusion() {
|
||||
let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(300.0, 200.0));
|
||||
let group = target(2, &[2, 3], rect);
|
||||
let placement = resolve_drop(&5, pos2(90.0, 30.0), std::slice::from_ref(&group)).unwrap();
|
||||
let placement = resolve_drop(&5, pos2(90.0, 30.0), std::slice::from_ref(&group), 40.0).unwrap();
|
||||
assert_eq!(placement.placement, Placement::Tab { before: Some(3) });
|
||||
assert!(placement.insertion.unwrap().is_finite());
|
||||
assert_eq!(resolve_drop(&5, rect.center(), std::slice::from_ref(&group)).unwrap().placement, Placement::Split(Zone::Center));
|
||||
assert_eq!(resolve_drop(&5, pos2(11.0, 90.0), std::slice::from_ref(&group)).unwrap().placement, Placement::Split(Zone::Left));
|
||||
assert!(resolve_drop(&3, rect.center(), std::slice::from_ref(&group)).is_none());
|
||||
assert!(resolve_drop(&3, pos2(11.0, 90.0), std::slice::from_ref(&group)).is_some());
|
||||
assert_eq!(resolve_drop(&5, rect.center(), std::slice::from_ref(&group), 40.0).unwrap().placement, Placement::Split(Zone::Center));
|
||||
assert_eq!(resolve_drop(&5, pos2(11.0, 90.0), std::slice::from_ref(&group), 40.0).unwrap().placement, Placement::Split(Zone::Left));
|
||||
assert!(resolve_drop(&3, rect.center(), std::slice::from_ref(&group), 40.0).unwrap().noop);
|
||||
assert!(resolve_drop(&3, pos2(11.0, 90.0), std::slice::from_ref(&group), 40.0).is_some());
|
||||
let mut overlay = target(5, &[5], rect);
|
||||
overlay.accepts_tabs = false;
|
||||
overlay.allow_splits = false;
|
||||
assert!(resolve_drop(&3, rect.center(), &[group, overlay]).is_none());
|
||||
assert!(drop_zone(Rect::NOTHING, 24.0, pos2(0.0, 0.0)).is_none());
|
||||
assert!(drop_zone(rect, 24.0, pos2(f32::NAN, 0.0)).is_none());
|
||||
assert!(resolve_drop(&3, rect.center(), &[group, overlay], 40.0).is_none());
|
||||
assert!(drop_zone(Rect::NOTHING, 24.0, 40.0, pos2(0.0, 0.0)).is_none());
|
||||
assert!(drop_zone(rect, 24.0, 40.0, pos2(f32::NAN, 0.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_zones_are_40_pt_deep_or_a_quarter_of_the_bodys_smaller_side() {
|
||||
let depth = DockStyle::default().zone_depth;
|
||||
assert_eq!(depth, 40.0);
|
||||
// The inner corner of the left trapezoid is the depth of both bands.
|
||||
let inner = |rect: Rect| zone_shape(rect, 0.0, depth, Zone::Left).unwrap()[1] - rect.min;
|
||||
for size in [vec2(600.0, 400.0), vec2(160.0, 160.0)] {
|
||||
let rect = Rect::from_min_size(pos2(10.0, 20.0), size);
|
||||
assert_eq!(inner(rect), vec2(40.0, 40.0), "{size:?}");
|
||||
let y = rect.center().y;
|
||||
assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 39.0, y)), Some(Zone::Left), "{size:?}");
|
||||
assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 41.0, y)), Some(Zone::Center), "{size:?}");
|
||||
}
|
||||
// A 90 pt body keeps a 45 pt center.
|
||||
let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(90.0, 90.0));
|
||||
assert_eq!(inner(rect), vec2(22.5, 22.5));
|
||||
assert_eq!(drop_zone(rect, 0.0, depth, rect.center()), Some(Zone::Center));
|
||||
assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 22.0, rect.center().y)), Some(Zone::Left));
|
||||
// A tall narrow body: its top and bottom zones are as deep as its left and right ones.
|
||||
let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(120.0, 600.0));
|
||||
assert_eq!(inner(rect), vec2(30.0, 30.0));
|
||||
let top = zone_shape(rect, 0.0, depth, Zone::Top).unwrap();
|
||||
assert_eq!(top[2].y - rect.top(), 30.0);
|
||||
assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.center().x, rect.top() + 29.0)), Some(Zone::Top));
|
||||
assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.center().x, rect.top() + 31.0)), Some(Zone::Center));
|
||||
// The bands start below the tab header.
|
||||
let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(600.0, 400.0));
|
||||
assert_eq!(drop_zone(rect, 24.0, depth, pos2(rect.center().x, rect.top() + 60.0)), Some(Zone::Top));
|
||||
assert_eq!(zone_shape(rect, 24.0, depth, Zone::Top).unwrap()[0], rect.left_top() + vec2(0.0, 24.0));
|
||||
// Without depth there are no sides.
|
||||
assert_eq!(drop_zone(rect, 0.0, 0.0, pos2(rect.left() + 1.0, rect.center().y)), Some(Zone::Center));
|
||||
assert!(zone_shape(rect, 0.0, 0.0, Zone::Left).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_action_sequence_never_loses_or_duplicates_a_panel() {
|
||||
let mut layout = sample();
|
||||
let mut seed = 72u64;
|
||||
for step in 0..800 {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
let panel = (seed % 6 + 1) as u32;
|
||||
let anchor = ((seed >> 16) % 6 + 1) as u32;
|
||||
let action = if step % 7 == 0 {
|
||||
Action::Float { panel, rect: [10.0, 20.0, 200.0, 220.0] }
|
||||
} else {
|
||||
move_to(
|
||||
panel,
|
||||
anchor,
|
||||
match seed % 5 {
|
||||
0 => Zone::Left,
|
||||
1 => Zone::Right,
|
||||
2 => Zone::Top,
|
||||
3 => Zone::Bottom,
|
||||
_ => Zone::Center,
|
||||
},
|
||||
)
|
||||
};
|
||||
let before = layout.clone();
|
||||
if layout.apply(action).is_err() {
|
||||
assert_eq!(layout, before);
|
||||
for (start, ids) in [(sample(), vec![1, 2, 3, 4, 5, 6]), (super::model_tests::docked(), super::model_tests::ALL.to_vec())] {
|
||||
let mut workspace = Workspace::new(start);
|
||||
let mut seed = 72u64;
|
||||
for step in 0..800 {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
let pick = |bits: u64| ids[(bits % ids.len() as u64) as usize];
|
||||
let (panel, anchor) = (pick(seed >> 8), pick(seed >> 24));
|
||||
let placement = match (seed >> 40) % 7 {
|
||||
0 => Placement::Split(Zone::Left),
|
||||
1 => Placement::Split(Zone::Right),
|
||||
2 => Placement::Split(Zone::Top),
|
||||
3 => Placement::Split(Zone::Bottom),
|
||||
4 => Placement::Split(Zone::Center),
|
||||
5 => Placement::Group { below: seed & 1 == 0, height: None },
|
||||
_ => Placement::Column { after: seed & 2 == 0 },
|
||||
};
|
||||
let to = match (seed >> 32) % 4 {
|
||||
0 => Target::Float { rect: None },
|
||||
1 => Target::NewDock { side: if seed & 4 == 0 { Side::Start } else { Side::End } },
|
||||
_ => Target::At { anchor, placement: placement.clone() },
|
||||
};
|
||||
let action = match step % 13 {
|
||||
0 => Action::Float { panel, rect: [10.0, 20.0, 200.0, 220.0] },
|
||||
1 => Action::MoveGroup { panel, to },
|
||||
2 => Action::MoveColumn { panel, to },
|
||||
3 => Action::MoveWindow { panel, to },
|
||||
4 => Action::CloseGroup { panel },
|
||||
5 => Action::CloseWindow { panel },
|
||||
6 => Action::CloseOthers { panel },
|
||||
7 => Action::Close { panel },
|
||||
8 => Action::SetMinimized { panel, minimized: seed & 8 == 0 },
|
||||
9 => Action::SetIconic { panel, iconic: seed & 16 == 0 },
|
||||
_ => Action::Move { panel, anchor, placement },
|
||||
};
|
||||
let before = workspace.clone();
|
||||
if workspace.apply(action, |_| Permissions::default()).is_err() {
|
||||
assert_eq!(workspace, before);
|
||||
}
|
||||
if step % 3 == 0
|
||||
&& let Some((hidden, _)) = workspace.hidden.first().cloned()
|
||||
{
|
||||
let fallback = workspace.layout.panels().first().map(|p| **p);
|
||||
let before = workspace.clone();
|
||||
if workspace.set_visible(hidden, true, fallback, |_| Permissions::default()).is_err() {
|
||||
assert_eq!(workspace, before);
|
||||
}
|
||||
}
|
||||
workspace.validate().unwrap();
|
||||
let mut panels: Vec<u32> = workspace.layout.panels().into_iter().copied().chain(workspace.hidden.iter().map(|(p, _)| *p)).collect();
|
||||
panels.sort_unstable();
|
||||
assert_eq!(panels, ids, "step {step}");
|
||||
}
|
||||
layout.validate().unwrap();
|
||||
let mut panels: Vec<u32> = layout.panels().into_iter().copied().collect();
|
||||
panels.sort_unstable();
|
||||
assert_eq!(panels, vec![1, 2, 3, 4, 5, 6]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,6 +440,8 @@ fn frame(ctx: &Context, layout: &Layout<u32>, events: Vec<Event>, focused: bool)
|
||||
ui.label("Actual panel content");
|
||||
},
|
||||
);
|
||||
let cursor = ctx.output(|o| o.cursor_icon);
|
||||
ctx.data_mut(|d| d.insert_temp(Id::new("test-cursor"), cursor));
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
@@ -403,13 +514,37 @@ fn actual_pointer_drag_docks_a_floating_panel_into_the_main_tab_strip() {
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(target)]);
|
||||
let actions = step(&ctx, &mut layout, vec![pointer_button(target, false)]);
|
||||
assert!(actions.iter().any(|a| matches!(a, Action::Move { panel: 5, .. })), "{actions:?}");
|
||||
assert!(!layout.floating.iter().any(|g| g.panels.contains(&5)));
|
||||
assert!(!layout.floating.iter().any(|g| g.contains(&5)));
|
||||
assert_eq!(layout.panels().len(), 6);
|
||||
let Node::Split { second, .. } = layout.root.as_ref().unwrap() else { panic!() };
|
||||
let Node::Tabs { panels, active } = second.as_ref() else { panic!() };
|
||||
assert_eq!(panels.get(*active), Some(&5));
|
||||
}
|
||||
|
||||
/// On X11 and Windows a release outside the window never reaches egui (egui-winit drops a
|
||||
/// button event once the pointer has left), so a tab dragged out of the window used to stay on
|
||||
/// the pointer for good. Leaving the window detaches the panel where it left, even over a dock
|
||||
/// target, and ends the drag.
|
||||
#[test]
|
||||
fn tab_dragged_out_of_the_window_floats_where_it_left() {
|
||||
let ctx = Context::default();
|
||||
let mut layout = sample();
|
||||
for _ in 0..3 {
|
||||
step(&ctx, &mut layout, Vec::new());
|
||||
}
|
||||
let tab = ctx.read_response(Id::new("test-area").with(("tab", &3u32))).unwrap().rect.center();
|
||||
let exit = pos2(4.0, 300.0);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(tab), pointer_button(tab, true)]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(tab + vec2(-8.0, 0.0))]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(exit)]);
|
||||
let actions = step(&ctx, &mut layout, vec![Event::PointerGone]);
|
||||
assert!(actions.iter().any(|a| matches!(a, Action::Float { panel: 3, .. })), "{actions:?}");
|
||||
assert!(layout.floating.iter().any(|g| g.panels().eq([3].iter())), "{layout:?}");
|
||||
let back = pos2(400.0, 300.0);
|
||||
assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(back)]).is_empty());
|
||||
assert!(step(&ctx, &mut layout, vec![pointer_button(back, false)]).is_empty(), "the drag ended when the pointer left");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_size_limits_clamp_geometry_without_overwriting_preferred_widths() {
|
||||
let layout = Layout {
|
||||
@@ -475,7 +610,10 @@ fn focused_floating_resize_grip_accepts_both_arrow_axes_and_releases_tab() {
|
||||
for _ in 0..3 {
|
||||
step(&ctx, &mut layout, Vec::new());
|
||||
}
|
||||
let id = Id::new("test-area").with(("floating", &5u32)).with("resize");
|
||||
let id = DockArea::hit_id(Id::new("test-area"), &Hit::Resize(5u32, ResizeEdge::BottomRight));
|
||||
let layer = DockArea::floating_layer(Id::new("test-area"), &layout.floating[0]).unwrap();
|
||||
let [x, y, width, height] = layout.floating[0].rect;
|
||||
assert_eq!(ctx.memory(|m| m.area_rect(layer.id)), Some(Rect::from_min_size(pos2(x, y), vec2(width, height))));
|
||||
ctx.memory_mut(|memory| memory.request_focus(id));
|
||||
let key = |key| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
|
||||
step(&ctx, &mut layout, vec![key(egui::Key::ArrowRight), key(egui::Key::ArrowDown)]);
|
||||
@@ -522,6 +660,17 @@ fn stack_dividers_resize_adjacent_open_bodies_by_pointer_and_keyboard() {
|
||||
let Node::Stack { entries } = layout.root.as_ref().unwrap() else { panic!() };
|
||||
assert!(entries[0].height.unwrap() > after_pointer);
|
||||
assert!((entries[0].height.unwrap() + entries[2].height.unwrap() - 300.0).abs() < 0.001);
|
||||
// Dragged past the next body's minimum, the one after it gives way too, down to the same
|
||||
// minimum; the closed entry keeps its height.
|
||||
let start = ctx.read_response(id).unwrap().rect.center();
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(0.0, 600.0))]);
|
||||
step(&ctx, &mut layout, vec![pointer_button(start + vec2(0.0, 600.0), false)]);
|
||||
let Node::Stack { entries } = layout.root.as_ref().unwrap() else { panic!() };
|
||||
let heights = entries.iter().map(|entry| entry.height.unwrap()).collect::<Vec<_>>();
|
||||
assert!((heights[2] - heights[3]).abs() < 0.01 && heights[3] < 120.0, "{heights:?}");
|
||||
assert!((heights[0] + heights[2] + heights[3] - 420.0).abs() < 0.01, "{heights:?}");
|
||||
assert_eq!(heights[1], 91.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -579,8 +728,10 @@ fn split_inner_edge_remains_draggable_beside_a_scrollbar() {
|
||||
frame(&mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
frame(&mut layout, vec![Event::PointerMoved(start + vec2(40.0, 0.0))]);
|
||||
frame(&mut layout, vec![pointer_button(start + vec2(40.0, 0.0), false)]);
|
||||
let Node::Split { size: SplitSize::FixedFirst(width), .. } = layout.root.unwrap() else { panic!() };
|
||||
assert!((width - 260.0).abs() < 0.001, "sidebar width after inner-edge drag: {width}");
|
||||
// A dragged divider keeps a ratio of the space, whatever mode it was saved with.
|
||||
let Node::Split { size: SplitSize::Ratio(ratio), .. } = layout.root.unwrap() else { panic!() };
|
||||
// 800 points less the 4 point divider.
|
||||
assert!((ratio * 796.0 - 260.0).abs() < 0.01, "sidebar width after inner-edge drag: {}", ratio * 796.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -609,7 +760,7 @@ fn restoring_a_panel_beside_a_nested_subtree_preserves_the_complete_workspace()
|
||||
#[test]
|
||||
fn floating_only_surface_does_not_allocate_the_callers_document_region() {
|
||||
let ctx = Context::default();
|
||||
let layout = Layout { root: None, floating: vec![Floating { panels: vec![1u32], active: 0, rect: [30.0, 40.0, 200.0, 200.0] }] };
|
||||
let layout = Layout { root: None, floating: vec![Floating::single(vec![1u32], 0, [30.0, 40.0, 200.0, 200.0])] };
|
||||
ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, |ui| {
|
||||
let before = ui.available_rect_before_wrap();
|
||||
let out = DockArea::new(Id::new("float-only")).show(
|
||||
@@ -641,8 +792,8 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() {
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
let actions = step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(50.0, 40.0))]);
|
||||
assert!(actions.iter().any(|a| matches!(a, Action::MoveFloating { .. })));
|
||||
assert_eq!(layout.floating[0].panels, original.panels);
|
||||
assert_eq!(layout.floating[0].active, original.active);
|
||||
assert_eq!(layout.floating[0].groups()[0].panels, original.groups()[0].panels);
|
||||
assert_eq!(layout.floating[0].groups()[0].active, original.groups()[0].active);
|
||||
assert_ne!(layout.floating[0].rect, original.rect);
|
||||
step(&ctx, &mut layout, vec![pointer_button(start + vec2(50.0, 40.0), false)]);
|
||||
for _ in 0..2 {
|
||||
@@ -651,11 +802,115 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() {
|
||||
let tab = ctx.read_response(Id::new("test-area").with(("tab", &5u32))).unwrap().rect.center();
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(tab), pointer_button(tab, true)]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(tab + vec2(8.0, 0.0))]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(tab + vec2(100.0, 100.0))]);
|
||||
let detached = step(&ctx, &mut layout, vec![pointer_button(tab + vec2(100.0, 100.0), false)]);
|
||||
// Inside the source window the release is a no-op; outside it floats.
|
||||
let outside = pos2(780.0, 650.0);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(outside)]);
|
||||
let detached = step(&ctx, &mut layout, vec![pointer_button(outside, false)]);
|
||||
assert!(detached.iter().any(|a| matches!(a, Action::Float { panel: 5, .. })));
|
||||
assert_eq!(layout.floating.len(), 2);
|
||||
assert_eq!(layout.floating[0].panels, vec![6]);
|
||||
assert_eq!(layout.floating[0].groups()[0].panels, vec![6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_group_drag_ends_on_release_or_pointer_exit() {
|
||||
for (released, leaves) in [(false, true), (true, true), (true, false)] {
|
||||
let ctx = Context::default();
|
||||
let mut layout = sample();
|
||||
for _ in 0..2 {
|
||||
step(&ctx, &mut layout, vec![]);
|
||||
}
|
||||
let start = pos2(86.0, 82.0);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
let moved = start + vec2(50.0, 40.0);
|
||||
let actions = step(&ctx, &mut layout, vec![Event::PointerMoved(moved)]);
|
||||
assert!(actions.iter().any(|action| matches!(action, Action::MoveFloating { .. })));
|
||||
let last = layout.clone();
|
||||
let mut events = vec![];
|
||||
if released {
|
||||
events.push(pointer_button(moved, false));
|
||||
}
|
||||
if leaves {
|
||||
events.push(Event::PointerGone);
|
||||
}
|
||||
let (out, _) = frame(&ctx, &layout, events, true);
|
||||
assert_eq!(out.group_drop, if leaves { None } else { Some((5, moved)) });
|
||||
for action in out.actions {
|
||||
layout.apply(action).unwrap();
|
||||
}
|
||||
assert_eq!(layout, last);
|
||||
for pointer in [moved + vec2(20.0, 20.0), moved + vec2(30.0, 30.0)] {
|
||||
let (out, _) = frame(&ctx, &layout, vec![Event::PointerMoved(pointer)], true);
|
||||
assert!(out.actions.is_empty(), "{out:?}");
|
||||
assert!(out.group_drag.is_none() && out.group_drop.is_none());
|
||||
}
|
||||
assert!(out.group_drag.is_none());
|
||||
assert_eq!(ctx.dragged_id(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_group_touch_release_reports_drop_after_pointer_gone() {
|
||||
for web_order in [false, true] {
|
||||
let ctx = Context::default();
|
||||
let mut layout = sample();
|
||||
for _ in 0..2 {
|
||||
step(&ctx, &mut layout, vec![]);
|
||||
}
|
||||
let touch = |phase, pos| Event::Touch { device_id: egui::TouchDeviceId(0), id: egui::TouchId(1), phase, pos, force: None };
|
||||
let start = pos2(86.0, 82.0);
|
||||
let press = pointer_button(start, true);
|
||||
let events = if web_order {
|
||||
vec![press, touch(egui::TouchPhase::Start, start)]
|
||||
} else {
|
||||
vec![touch(egui::TouchPhase::Start, start), Event::PointerMoved(start), press]
|
||||
};
|
||||
step(&ctx, &mut layout, events);
|
||||
let moved = start + vec2(50.0, 40.0);
|
||||
let events = if web_order {
|
||||
vec![Event::PointerMoved(moved), touch(egui::TouchPhase::Move, moved)]
|
||||
} else {
|
||||
vec![touch(egui::TouchPhase::Move, moved), Event::PointerMoved(moved)]
|
||||
};
|
||||
assert!(step(&ctx, &mut layout, events).iter().any(|action| matches!(action, Action::MoveFloating { .. })));
|
||||
// egui-winit emits Touch before release/gone; eframe web emits it afterwards.
|
||||
let events = if web_order {
|
||||
vec![pointer_button(moved, false), Event::PointerGone, touch(egui::TouchPhase::End, moved)]
|
||||
} else {
|
||||
vec![touch(egui::TouchPhase::End, moved), pointer_button(moved, false), Event::PointerGone]
|
||||
};
|
||||
let (out, _) = frame(&ctx, &layout, events, true);
|
||||
assert!(!ctx.input(|i| i.pointer.has_pointer()));
|
||||
assert_eq!(out.group_drop, Some((5, moved)));
|
||||
assert!(out.group_drag.is_none());
|
||||
assert_eq!(ctx.dragged_id(), None);
|
||||
assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(moved + vec2(30.0, 30.0))]).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_group_exit_with_escape_or_focus_loss_restores_original_geometry() {
|
||||
for escape in [false, true] {
|
||||
let ctx = Context::default();
|
||||
let mut layout = sample();
|
||||
let original = layout.clone();
|
||||
for _ in 0..2 {
|
||||
step(&ctx, &mut layout, vec![]);
|
||||
}
|
||||
let start = pos2(86.0, 82.0);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(50.0, 40.0))]);
|
||||
assert_ne!(layout.floating[0].rect, original.floating[0].rect);
|
||||
let mut events = vec![Event::PointerGone];
|
||||
if escape {
|
||||
events.push(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
}
|
||||
let (out, _) = frame(&ctx, &layout, events, escape);
|
||||
assert!(out.group_drag.is_none() && out.group_drop.is_none());
|
||||
for action in out.actions {
|
||||
layout.apply(action).unwrap();
|
||||
}
|
||||
assert_eq!(layout.floating[0].rect, original.floating[0].rect);
|
||||
}
|
||||
}
|
||||
|
||||
struct CustomContent {
|
||||
@@ -705,7 +960,7 @@ impl DockContent<u32> for CustomContent {
|
||||
self.menus += 1;
|
||||
ui.button("App menu").clicked();
|
||||
}
|
||||
fn group_header_width(&self, _: &[u32], _: &u32, _: bool) -> f32 {
|
||||
fn group_header_width(&self, _: &[u32], _: &u32, _: bool, _: f32) -> f32 {
|
||||
40.0
|
||||
}
|
||||
fn group_header(&mut self, ui: &mut egui::Ui, _: &[u32], _: &u32, _: bool) {
|
||||
@@ -746,11 +1001,12 @@ fn custom_chrome_shaped_labels_and_programmatic_raise_are_available() {
|
||||
custom_frame(&ctx, &layout, &mut content, vec![], &[], false);
|
||||
}
|
||||
let out = custom_frame(&ctx, &layout, &mut content, vec![], &[], true);
|
||||
assert_eq!(out.focused, Some(5));
|
||||
assert_eq!(out.focused, None, "a programmatic raise is not user focus");
|
||||
assert_eq!(ctx.memory(|m| m.focused()), None, "a raise draws no keyboard-focus ring");
|
||||
assert!(out.actions.is_empty());
|
||||
assert!(content.headers >= 3 && content.bodies >= 3);
|
||||
assert!(content.labels.iter().any(|s| s == "Logical 5"));
|
||||
let at = pos2(130.0, 82.0);
|
||||
let at = pos2(130.0, 96.0);
|
||||
custom_frame(
|
||||
&ctx,
|
||||
&layout,
|
||||
@@ -941,7 +1197,7 @@ fn chrome_focus_classifies_rendered_tab_but_excludes_body_text_field_and_invalid
|
||||
assert!(!DockArea::new(Id::new("focus-area")).chrome_has_focus(&ctx, &layout));
|
||||
paint(tab);
|
||||
let mut invalid = layout.clone();
|
||||
invalid.floating.push(Floating { panels: vec![3], active: 0, rect: [10.0, 10.0, 100.0, 100.0] });
|
||||
invalid.floating.push(Floating::single(vec![3], 0, [10.0, 10.0, 100.0, 100.0]));
|
||||
assert!(!DockArea::new(Id::new("focus-area")).chrome_has_focus(&ctx, &invalid));
|
||||
assert!(!DockArea::<u32>::new(Id::new("focus-area")).chrome_has_focus(&ctx, &Layout::default()));
|
||||
ctx.memory_mut(|memory| memory.request_focus(Id::new("unrendered")));
|
||||
@@ -1122,7 +1378,7 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() {
|
||||
CustomContent { labels: vec![], headers: 0, menus: 0, bodies: 0 },
|
||||
);
|
||||
h.run_steps(2);
|
||||
let tab = Id::new("action-label-test").with(("tab", &5_u32));
|
||||
let tab = Id::new("action-label-test").with(("tab", &6_u32));
|
||||
let at = h.ctx.read_response(tab).unwrap().rect.center();
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(at),
|
||||
@@ -1132,14 +1388,12 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() {
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert!(egui::Popup::is_any_open(&h.ctx));
|
||||
for logical in ["Float panel", "Move to group", "Close panel"] {
|
||||
for logical in ["Float Panel", "Move Panel to Group", "Close Panel"] {
|
||||
assert!(
|
||||
h.output().shapes.iter().any(|shape| paints(&shape.shape, &format!("Action visual: {logical}"))),
|
||||
"custom action must paint: {logical}"
|
||||
);
|
||||
// This sample also has a floating-group grip labeled Move to group.
|
||||
let expected = if logical == "Move to group" { 2 } else { 1 };
|
||||
assert_eq!(h.query_all_by_label(logical).count(), expected, "popup action must retain its own logical accessibility: {logical}");
|
||||
assert_eq!(h.query_all_by_label(logical).count(), 1, "popup action must retain its own logical accessibility: {logical}");
|
||||
assert_eq!(
|
||||
h.query_all_by_label(&format!("Action visual: {logical}")).count(),
|
||||
0,
|
||||
@@ -1147,3 +1401,376 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_strip_shows_whole_tabs_and_lists_the_others_in_the_overflow_menu() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
fn elided(shape: &egui::Shape) -> bool {
|
||||
match shape {
|
||||
egui::Shape::Text(text) => text.galley.elided,
|
||||
egui::Shape::Vec(shapes) => shapes.iter().any(elided),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let area = Id::new("whole-tabs");
|
||||
let layout = Layout { root: Some(tabs(&[1, 2, 3, 4, 5, 6], 5)), floating: vec![] };
|
||||
let mut h = Harness::builder().with_size(vec2(260.0, 240.0)).build_ui(move |ui| {
|
||||
DockArea::new(area).show(
|
||||
ui,
|
||||
&layout,
|
||||
&DockStyle::from_ui(ui),
|
||||
|panel| format!("Panel {panel}"),
|
||||
|_| Permissions::default(),
|
||||
|_: &mut egui::Ui, _: &u32| {},
|
||||
);
|
||||
});
|
||||
h.run_steps(2);
|
||||
let shown: Vec<u32> = (1..=6).filter(|p| h.ctx.read_response(area.with(("tab", p))).is_some()).collect();
|
||||
assert!((2..6).contains(&shown.len()), "{shown:?}");
|
||||
// The active last tab takes the place of the last tab that fits; the others keep their order.
|
||||
let mut expected: Vec<u32> = (1..shown.len() as u32).collect();
|
||||
expected.push(6);
|
||||
assert_eq!(shown, expected);
|
||||
assert!(h.output().shapes.iter().all(|shape| !elided(&shape.shape)), "every shown tab keeps its full name");
|
||||
h.get_by_role_and_label(Role::Button, "Panels").click();
|
||||
h.run_steps(2);
|
||||
let listed: Vec<u32> = (1..=6).filter(|p| h.query_by_role_and_label(Role::Button, &format!("Panel {p}")).is_some()).collect();
|
||||
let hidden: Vec<u32> = (1..=6).filter(|p| !shown.contains(p)).collect();
|
||||
assert_eq!(listed, hidden, "the overflow menu lists exactly the hidden panels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_active_tab_wider_than_the_strip_is_truncated_and_named_in_a_tooltip() {
|
||||
let ctx = Context::default();
|
||||
ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0);
|
||||
let layout = Layout { root: Some(tabs(&[1, 2, 3], 0)), floating: vec![] };
|
||||
let label = |p: &u32| format!("Eigenschaften und Anpassungen {p}");
|
||||
let run = |events: Vec<Event>| {
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(150.0, 200.0))), events, ..Default::default() };
|
||||
let mut output = ctx.run_ui(input, |ui| {
|
||||
DockArea::new(Id::new("truncate")).show(
|
||||
ui,
|
||||
&layout,
|
||||
&DockStyle::from_ui(ui),
|
||||
label,
|
||||
|_| Permissions::default(),
|
||||
|ui, _| {
|
||||
ui.label("Body");
|
||||
},
|
||||
);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
output.shapes
|
||||
};
|
||||
run(vec![]);
|
||||
let shapes = run(vec![]);
|
||||
let tab = |p: u32| ctx.read_response(Id::new("truncate").with(("tab", &p))).map(|response| response.rect);
|
||||
assert!(tab(2).is_none() && tab(3).is_none(), "the other tabs overflow instead of shrinking");
|
||||
let active = tab(1).unwrap();
|
||||
// The clip rect would hide an overflowing label; what is laid out must itself fit.
|
||||
let painted: Vec<&egui::epaint::TextShape> = shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match &shape.shape {
|
||||
egui::Shape::Text(text) if active.contains(text.visual_bounding_rect().center()) => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(painted.len(), 1, "{painted:?}");
|
||||
assert!(painted[0].galley.elided);
|
||||
assert!(active.contains_rect(painted[0].visual_bounding_rect()), "label {:?} overflows {active:?}", painted[0].visual_bounding_rect());
|
||||
run(vec![Event::PointerMoved(active.center())]);
|
||||
let shapes = run(vec![]);
|
||||
let full = label(&1);
|
||||
// An elided galley still reports its whole text, so the cut tab label alone would match.
|
||||
assert!(
|
||||
shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == full && !text.galley.elided)),
|
||||
"a truncated tab names its panel in full on hover"
|
||||
);
|
||||
}
|
||||
|
||||
// Ported from storytold/craft-libs#110 by @Zenodeon.
|
||||
|
||||
#[test]
|
||||
fn resize_cancellation_retains_ownership_across_other_host_rendering() {
|
||||
let ctx = Context::default();
|
||||
let area = Id::new("test-area");
|
||||
let mut layout = sample();
|
||||
for _ in 0..3 {
|
||||
step(&ctx, &mut layout, vec![]);
|
||||
}
|
||||
let id = area.with(("floating", &5u32)).with("resize-right");
|
||||
let start = ctx.read_response(id).unwrap().rect.center();
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(20.0, 0.0))]);
|
||||
assert_eq!(ctx.dragged_id(), Some(id));
|
||||
ctx.data_mut(|data| data.insert_temp(area.with("owned-interactions"), vec![Id::new("another-host-control")]));
|
||||
cancel_drag::<u32>(&ctx, area);
|
||||
assert!(ctx.dragged_id().is_none());
|
||||
let before = layout.clone();
|
||||
assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(100.0, 0.0))]).is_empty());
|
||||
assert_eq!(layout, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_floating_height_cap_does_not_disable_keyboard_width_resizing() {
|
||||
let ctx = Context::default();
|
||||
let mut layout = Layout { root: None, floating: vec![Floating::single(vec![1u32], 0, [80.0, 70.0, 300.0, 26.0])] };
|
||||
let id = Id::new("collapsed-resize").with(("floating", &1u32)).with("resize-right");
|
||||
let mut frame = |events| {
|
||||
let mut actions = Vec::new();
|
||||
ctx.run_ui(
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), focused: true, events, ..Default::default() },
|
||||
|ui| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
style.min_pane = 0.0;
|
||||
actions = DockArea::new(Id::new("collapsed-resize"))
|
||||
.show_with_limits(
|
||||
ui,
|
||||
&layout,
|
||||
&style,
|
||||
|p| p.to_string(),
|
||||
|_| Permissions::default(),
|
||||
|_| PanelLimits { min: vec2(220.0, 0.0), max: vec2(1000.0, 0.0) },
|
||||
|_, _| {},
|
||||
)
|
||||
.actions;
|
||||
},
|
||||
)
|
||||
.textures_delta
|
||||
.clear();
|
||||
for action in actions {
|
||||
layout.apply(action).unwrap();
|
||||
}
|
||||
};
|
||||
for _ in 0..3 {
|
||||
frame(vec![]);
|
||||
}
|
||||
ctx.memory_mut(|memory| memory.request_focus(id));
|
||||
frame(vec![Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
assert_eq!(layout.floating[0].rect, [80.0, 70.0, 308.0, 44.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returning_to_a_singleton_or_floating_source_body_is_an_explicit_noop() {
|
||||
for panels in [vec![1u32], vec![1, 2, 3]] {
|
||||
for allow_splits in [false, true] {
|
||||
let rect = Rect::from_min_size(Pos2::ZERO, vec2(300.0, 300.0));
|
||||
let target = DropTarget {
|
||||
anchor: 1,
|
||||
rect,
|
||||
tab_strip: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 26.0))),
|
||||
tabs: panels.iter().map(|id| (*id, Rect::NOTHING)).collect(),
|
||||
allow_splits,
|
||||
accepts_tabs: true,
|
||||
right_to_left: false,
|
||||
};
|
||||
let proposal = resolve_drop(&1, rect.center(), &[target], 40.0).unwrap();
|
||||
assert!(proposal.noop);
|
||||
assert!(proposal.insertion.is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_floating_resize_stops_at_edges_and_waits_for_cursor_to_return() {
|
||||
for name in ["resize-right", "resize-left", "resize-bottom", "resize", "resize-bottom-left"] {
|
||||
let ctx = Context::default();
|
||||
let mut layout = sample();
|
||||
for _ in 0..3 {
|
||||
step(&ctx, &mut layout, vec![]);
|
||||
}
|
||||
let id = Id::new("test-area").with(("floating", &5u32)).with(name);
|
||||
let start = ctx.read_response(id).unwrap().rect.center();
|
||||
let original = layout.floating[0].rect;
|
||||
let horizontal = name != "resize-bottom";
|
||||
let left = name.contains("left");
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]);
|
||||
let outside = if horizontal { pos2(if left { -200.0 } else { 1100.0 }, start.y) } else { pos2(start.x, 1000.0) };
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(outside)]);
|
||||
let stopped = layout.floating[0].rect;
|
||||
if horizontal {
|
||||
if left {
|
||||
assert_eq!(stopped[0] + stopped[2], original[0] + original[2]);
|
||||
} else {
|
||||
assert_eq!(stopped[0], original[0]);
|
||||
assert_eq!(stopped[0] + stopped[2], 800.0);
|
||||
}
|
||||
} else {
|
||||
assert_eq!(stopped[1], original[1]);
|
||||
assert_eq!(stopped[1] + stopped[3], 600.0);
|
||||
}
|
||||
let still_outside = if horizontal { outside + vec2(if left { 100.0 } else { -100.0 }, 0.0) } else { outside - vec2(0.0, 100.0) };
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(still_outside)]);
|
||||
assert_eq!(layout.floating[0].rect, stopped, "{name}: reversal outside the edge must not resize");
|
||||
step(&ctx, &mut layout, vec![Event::PointerMoved(start)]);
|
||||
assert_eq!(layout.floating[0].rect, original, "{name}: returning to the original handle restores its geometry");
|
||||
step(&ctx, &mut layout, vec![pointer_button(start, false)]);
|
||||
assert!(ctx.memory(|memory| memory.focused()).is_none(), "{name}: the grip gives up focus after a pointer drag");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_tab_slots_are_explicit_noops_with_bounded_insertion_markers() {
|
||||
let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 200.0));
|
||||
let target = DropTarget {
|
||||
anchor: 1,
|
||||
rect,
|
||||
tab_strip: Some(Rect::from_min_size(rect.min, vec2(300.0, 30.0))),
|
||||
tabs: vec![
|
||||
(1, Rect::from_min_size(pos2(0.0, 0.0), vec2(60.0, 30.0))),
|
||||
(2, Rect::from_min_size(pos2(60.0, 0.0), vec2(60.0, 30.0))),
|
||||
(3, Rect::from_min_size(pos2(120.0, 0.0), vec2(60.0, 30.0))),
|
||||
],
|
||||
allow_splits: true,
|
||||
accepts_tabs: true,
|
||||
right_to_left: false,
|
||||
};
|
||||
for (panel, positions) in [(1, [10.0, 50.0]), (2, [70.0, 110.0]), (3, [130.0, 210.0])] {
|
||||
for x in positions {
|
||||
let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target), 40.0).unwrap();
|
||||
assert!(proposal.noop, "{panel}/{x}");
|
||||
assert!(target.tab_strip.unwrap().contains_rect(proposal.insertion.unwrap()));
|
||||
}
|
||||
}
|
||||
for (panel, x) in [(1, 140.0), (3, 10.0), (2, 210.0)] {
|
||||
let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target), 40.0).unwrap();
|
||||
assert!(!proposal.noop);
|
||||
assert!(proposal.insertion.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_owned_noop_consumes_release_without_a_fallback_float() {
|
||||
struct Content(usize);
|
||||
impl DockContent<u32> for Content {
|
||||
fn body(&mut self, _ui: &mut egui::Ui, _panel: &u32) {}
|
||||
fn resolve_drag(&mut self, _ctx: &Context, _style: &DockStyle, request: &DropRequest<'_, u32>) -> Option<DropFeedback> {
|
||||
if request.released {
|
||||
self.0 += 1;
|
||||
}
|
||||
Some(DropFeedback::default())
|
||||
}
|
||||
}
|
||||
let ctx = Context::default();
|
||||
let area = Id::new("host-owned");
|
||||
let layout = sample();
|
||||
let mut content = Content(0);
|
||||
let from = pos2(30.0, 20.0);
|
||||
let to = pos2(400.0, 300.0);
|
||||
let render = |events: Vec<Event>, content: &mut Content| {
|
||||
let mut output = DockOutput::default();
|
||||
ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }, |ui| {
|
||||
output = DockArea::new(area).show_customized(
|
||||
ui,
|
||||
&layout,
|
||||
&DockStyle::from_ui(ui),
|
||||
|p| p.to_string(),
|
||||
|_| Permissions::default(),
|
||||
|_| PanelLimits::default(),
|
||||
content,
|
||||
);
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
output
|
||||
};
|
||||
render(
|
||||
vec![
|
||||
Event::PointerMoved(from),
|
||||
Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE },
|
||||
],
|
||||
&mut content,
|
||||
);
|
||||
assert!(begin_drag(&ctx, area, 1u32, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0))));
|
||||
render(vec![Event::PointerMoved(to)], &mut content);
|
||||
let output = render(
|
||||
vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }],
|
||||
&mut content,
|
||||
);
|
||||
assert_eq!(content.0, 1);
|
||||
assert!(output.actions.iter().all(|action| !matches!(action, Action::Move { .. } | Action::Float { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow_noop_detection_uses_logical_order_including_hidden_tabs() {
|
||||
let rect = Rect::from_min_size(Pos2::ZERO, vec2(140.0, 200.0));
|
||||
let target = DropTarget {
|
||||
anchor: 1,
|
||||
rect,
|
||||
tab_strip: Some(Rect::from_min_size(Pos2::ZERO, vec2(140.0, 30.0))),
|
||||
tabs: vec![
|
||||
(1, Rect::from_min_size(Pos2::ZERO, vec2(60.0, 30.0))),
|
||||
(2, Rect::NOTHING),
|
||||
(3, Rect::from_min_size(pos2(60.0, 0.0), vec2(60.0, 30.0))),
|
||||
],
|
||||
allow_splits: true,
|
||||
accepts_tabs: true,
|
||||
right_to_left: false,
|
||||
};
|
||||
assert!(resolve_drop(&1, pos2(10.0, 12.0), std::slice::from_ref(&target), 40.0).unwrap().noop);
|
||||
// Before the next visible tab crosses hidden tab 2 and really changes the order.
|
||||
assert!(!resolve_drop(&1, pos2(65.0, 12.0), std::slice::from_ref(&target), 40.0).unwrap().noop);
|
||||
assert!(resolve_drop(&3, pos2(130.0, 12.0), std::slice::from_ref(&target), 40.0).unwrap().noop);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertion_markers_stay_inside_clipped_and_singleton_strips() {
|
||||
for width in [0.5, 1.0, 20.0, 140.0] {
|
||||
let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(width, 200.0));
|
||||
let strip = Rect::from_min_size(rect.min, vec2(width, 30.0));
|
||||
for tab_left in [-100.0, 10.0, 300.0] {
|
||||
let target = DropTarget {
|
||||
anchor: 1,
|
||||
rect,
|
||||
tab_strip: Some(strip.expand(5.0)),
|
||||
tabs: vec![(1, Rect::from_min_size(pos2(tab_left, 20.0), vec2(60.0, 30.0)))],
|
||||
allow_splits: true,
|
||||
accepts_tabs: true,
|
||||
right_to_left: false,
|
||||
};
|
||||
for x in [rect.left(), rect.center().x, rect.right()] {
|
||||
let proposal = resolve_drop(&1, pos2(x, 25.0), std::slice::from_ref(&target), 40.0).unwrap();
|
||||
assert!(proposal.noop);
|
||||
let marker = proposal.insertion.unwrap();
|
||||
assert!(rect.intersect(target.tab_strip.unwrap()).contains_rect(marker));
|
||||
assert!(marker.width() > 0.0 && marker.width() <= 2.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertion_marker_handles_subpixel_strip_crossing_zero_without_panicking() {
|
||||
let rect = Rect::from_min_max(pos2(-0.001, 0.0), pos2(0.002, 30.0));
|
||||
let target =
|
||||
DropTarget { anchor: 1, rect, tab_strip: Some(rect), tabs: vec![(1, rect)], allow_splits: true, accepts_tabs: true, right_to_left: false };
|
||||
let proposal = resolve_drop(&1, pos2(0.0, 12.0), &[target], 40.0).unwrap();
|
||||
assert!(proposal.noop);
|
||||
assert!(rect.contains_rect(proposal.insertion.unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflowing_strip_paints_a_single_ellipsis_symbol() {
|
||||
use egui_kittest::Harness;
|
||||
fn paints(shape: &egui::Shape, text: &str) -> bool {
|
||||
match shape {
|
||||
egui::Shape::Text(shape) => shape.galley.text() == text,
|
||||
egui::Shape::Vec(shapes) => shapes.iter().any(|shape| paints(shape, text)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let layout = Layout { root: Some(tabs(&[1, 2, 3, 4, 5, 6], 0)), floating: vec![] };
|
||||
let mut h = Harness::builder().with_size(vec2(150.0, 240.0)).build_ui(move |ui| {
|
||||
DockArea::new(Id::new("overflow-symbol")).show(
|
||||
ui,
|
||||
&layout,
|
||||
&DockStyle::from_ui(ui),
|
||||
|panel| format!("Panel {panel}"),
|
||||
|_| Permissions::default(),
|
||||
|_ui: &mut egui::Ui, _panel: &u32| {},
|
||||
);
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert!(h.output().shapes.iter().any(|shape| paints(&shape.shape, "\u{2026}")));
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
//! Fixes from the DesignCraft trial: group float size, tab label elision, the drag ghost and
|
||||
//! grip, double-clicks on minimized groups, pointer focus, label keys and borrowed lookups; then
|
||||
//! split permissions, body focus, right-to-left strips, close controls, menu and button names,
|
||||
//! zone mapping, closed panels from `apply`, group heights and flyout events.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Every shape, with nested `Shape::Vec`s flattened.
|
||||
fn flat(shapes: &[egui::epaint::ClippedShape]) -> Vec<(Rect, egui::Shape)> {
|
||||
fn walk(clip: Rect, shape: &egui::Shape, out: &mut Vec<(Rect, egui::Shape)>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(clip, s, out)),
|
||||
shape => out.push((clip, shape.clone())),
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for clipped in shapes {
|
||||
walk(clipped.clip_rect, &clipped.shape, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn texts(d: &Driver) -> Vec<(Rect, egui::epaint::TextShape)> {
|
||||
flat(&d.shapes)
|
||||
.into_iter()
|
||||
.filter_map(|(clip, shape)| match shape {
|
||||
egui::Shape::Text(text) => Some((clip, text)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rects(d: &Driver) -> Vec<egui::epaint::RectShape> {
|
||||
flat(&d.shapes)
|
||||
.into_iter()
|
||||
.filter_map(|(_, shape)| match shape {
|
||||
egui::Shape::Rect(rect) => Some(rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn last_char(galley: &egui::Galley) -> Option<char> {
|
||||
galley.rows.last().and_then(|row| row.glyphs.last()).map(|glyph| glyph.chr)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_height_docked_group_floats_at_the_host_or_capped_height_inside_the_window() {
|
||||
for size in [None, Some(vec2(200.0, 150.0))] {
|
||||
let mut layout = docked();
|
||||
let Some(Node::Split { first, .. }) = &mut layout.root else { panic!() };
|
||||
**first = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![2, 3], 1)], 240.0)] };
|
||||
let content = TestContent { protected: vec![0], floating_size: size, body_height: Some(600.0), ..Default::default() };
|
||||
let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)));
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
let out = d.drag(bar.center(), pos2(420.0, 300.0));
|
||||
let Some(Target::Float { rect: Some([x, y, width, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) };
|
||||
match size {
|
||||
Some(size) => assert_eq!(*height, size.y),
|
||||
None => assert_eq!(*height, 320.0),
|
||||
}
|
||||
assert!(*width > 100.0 && *width <= 240.0, "{width}");
|
||||
let window = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
|
||||
assert!(window.contains_rect(Rect::from_min_size(pos2(*x, *y), vec2(*width, *height))), "{x} {y} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Labels as a host's pre-laid-out galleys, which egui does not wrap again.
|
||||
struct GalleyLabels;
|
||||
|
||||
impl DockContent<u32> for GalleyLabels {
|
||||
fn body(&mut self, _: &mut egui::Ui, _: &u32) {}
|
||||
fn logical_label(&self, panel: &u32) -> String {
|
||||
format!("Character Styles {panel}")
|
||||
}
|
||||
fn label(&mut self, ui: &egui::Ui, _: &u32, logical: &str, font: &egui::FontId, color: Color32) -> egui::WidgetText {
|
||||
egui::WidgetText::Galley(ui.painter().layout_no_wrap(logical.to_owned(), font.clone(), color))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn galley_labels_stay_whole_and_only_an_over_wide_active_tab_ends_with_an_ellipsis_inside_it() {
|
||||
let panels = [1, 2, 3, 4, 5, 6];
|
||||
let layout = Layout { root: Some(tabs(&panels, 3)), floating: Vec::new() };
|
||||
for width in [320.0, 90.0] {
|
||||
let ctx = Context::default();
|
||||
let mut content = GalleyLabels;
|
||||
let mut shapes = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() };
|
||||
let mut full = ctx.run_ui(input, |ui| {
|
||||
let style = DockStyle::from_ui(ui);
|
||||
ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 400.0))), |ui| {
|
||||
DockArea::new(Id::new(AREA)).show_content(ui, &layout, &style, &mut content);
|
||||
});
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
shapes = full.shapes;
|
||||
}
|
||||
let texts: Vec<_> = flat(&shapes)
|
||||
.into_iter()
|
||||
.filter_map(|(clip, shape)| match shape {
|
||||
egui::Shape::Text(text) => Some((clip, text)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let shown: Vec<u32> = panels.into_iter().filter(|p| ctx.read_response(Id::new(AREA).with(("tab", p))).is_some()).collect();
|
||||
assert!(shown.contains(&4) && shown.len() < panels.len(), "{width}: {shown:?}");
|
||||
for panel in shown {
|
||||
let tab = ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect;
|
||||
let Some((clip, text)) = texts.iter().find(|(_, t)| t.galley.text().ends_with(&format!(" {panel}")) && tab.contains(t.pos)) else {
|
||||
panic!("no label in tab {panel}")
|
||||
};
|
||||
let cut = width < 100.0;
|
||||
assert_eq!(last_char(&text.galley), if cut { Some('…') } else { char::from_digit(panel, 10) }, "{width}: tab {panel}");
|
||||
let drawn = Rect::from_min_size(text.pos, text.galley.size());
|
||||
assert!(drawn.right() <= tab.right() + 0.5 && drawn.left() >= tab.left(), "tab {panel}: {drawn:?} in {tab:?}");
|
||||
assert!(tab.contains_rect(clip.intersect(drawn)), "tab {panel}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_bar_draws_no_mark_at_rest_and_a_group_drag_paints_a_filled_labeled_ghost() {
|
||||
let mut d = Driver::new(frames());
|
||||
let visuals = d.ctx.global_style().visuals.clone();
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
let mark = flat(&d.shapes).into_iter().any(|(_, shape)| match shape {
|
||||
egui::Shape::LineSegment { points, .. } => bar.contains(points[0]) && bar.contains(points[1]),
|
||||
_ => false,
|
||||
});
|
||||
assert!(!mark, "a mark in the drag bar at rest");
|
||||
|
||||
d.hold(bar.center(), pos2(150.0, 300.0));
|
||||
let fill = visuals.selection.stroke.color.gamma_multiply(0.15);
|
||||
let Some(ghost) = rects(&d).into_iter().find(|r| r.fill == fill && r.stroke.width == 2.0 && r.rect.contains(pos2(150.0, 300.0))) else {
|
||||
panic!("no filled ghost under the pointer")
|
||||
};
|
||||
for label in ["Panel 2", "Panel 3"] {
|
||||
assert!(texts(&d).iter().any(|(_, t)| t.galley.text() == label && ghost.rect.contains(t.pos)), "{label} missing from the ghost");
|
||||
}
|
||||
d.step(vec![key(egui::Key::Escape)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_on_a_tab_of_a_minimized_group_ends_expanded() {
|
||||
let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let mut d = Driver::new(layout);
|
||||
let minimized = |d: &Driver| d.layout.floating[0].minimized;
|
||||
let active = d.tab(6).center();
|
||||
d.click(active);
|
||||
d.click(active);
|
||||
assert!(minimized(&d));
|
||||
d.wait();
|
||||
|
||||
let other = d.tab(5).center();
|
||||
d.click(other);
|
||||
d.click(other);
|
||||
assert!(!minimized(&d));
|
||||
assert_eq!(d.layout.floating[0].groups()[0].active_panel(), Some(&5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clicked_tab_shows_no_focus_outline_but_tab_key_focus_does() {
|
||||
let mut d = Driver::new(frames());
|
||||
let accent = d.ctx.global_style().visuals.selection.stroke.color;
|
||||
let id = Id::new(AREA).with(("tab", &3u32));
|
||||
let outline = d.tab(3).shrink(2.0);
|
||||
let outlined = |d: &Driver| rects(d).iter().any(|r| r.rect == outline && r.stroke.width > 0.0 && r.stroke.color == accent);
|
||||
|
||||
d.click(d.tab(3).center());
|
||||
// A platform may focus the clicked widget, as an AccessKit focus request does.
|
||||
d.ctx.memory_mut(|m| m.request_focus(id));
|
||||
d.step(vec![]);
|
||||
assert_eq!(d.ctx.memory(|m| m.focused()), Some(id));
|
||||
assert!(!outlined(&d));
|
||||
|
||||
d.ctx.memory_mut(|m| m.surrender_focus(id));
|
||||
for _ in 0..20 {
|
||||
if d.ctx.memory(|m| m.focused()) == Some(id) {
|
||||
break;
|
||||
}
|
||||
d.step(vec![key(egui::Key::Tab)]);
|
||||
}
|
||||
assert_eq!(d.ctx.memory(|m| m.focused()), Some(id));
|
||||
d.step(vec![]);
|
||||
assert!(outlined(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_covers_every_label_and_contains_takes_a_borrowed_panel() {
|
||||
let mut debug = String::new();
|
||||
let mut full = Context::default().run_ui(RawInput::default(), |ui| {
|
||||
debug = format!("{:?}", DockStyle::from_ui(ui).localized(|key| Some(key.to_owned())));
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
let values: Vec<&str> = debug.split("_label: \"").skip(1).filter_map(|rest| rest.split('"').next()).collect();
|
||||
assert_eq!(values.len(), 25, "{debug}");
|
||||
assert!(values.iter().all(|v| v.starts_with("dock.")), "a label without a key: {values:?}");
|
||||
let unique: std::collections::HashSet<_> = values.iter().collect();
|
||||
assert_eq!(unique.len(), values.len());
|
||||
|
||||
let window = Floating::single(vec!["swatches".to_owned()], 0, [0.0, 0.0, 200.0, 200.0]);
|
||||
assert!(window.contains("swatches"));
|
||||
assert!(!window.contains("layers"));
|
||||
}
|
||||
|
||||
const AREA_600: Rect = Rect { min: pos2(0.0, 0.0), max: pos2(600.0, 600.0) };
|
||||
|
||||
#[test]
|
||||
fn a_protected_canvas_takes_no_side_split_and_a_group_dropped_on_its_edge_floats() {
|
||||
let protected = |p: &u32| if *p == 0 { Permissions::PROTECTED } else { Permissions::default() };
|
||||
let split = Action::Move { panel: 4, anchor: 0, placement: Placement::Split(Zone::Left) };
|
||||
let mut layout = docked();
|
||||
assert_eq!(layout.apply_with_permissions(split.clone(), protected), Err(DockError::NotAllowed));
|
||||
let opt_in = |p: &u32| if *p == 0 { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() };
|
||||
assert!(layout.apply_with_permissions(split, opt_in).is_ok());
|
||||
|
||||
let mut d = Driver::with(docked(), TestContent { protected: vec![0], ..Default::default() }, AREA_600);
|
||||
let bar = d.rect("drag-bar", 2);
|
||||
let out = d.drag(bar.center(), pos2(300.0, 300.0));
|
||||
assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_press_in_a_stripless_panel_reports_it_focused() {
|
||||
let mut d = Driver::with(docked(), TestContent { protected: vec![0], ..Default::default() }, AREA_600);
|
||||
for pressed in [PointerButton::Primary, PointerButton::Secondary, PointerButton::Middle] {
|
||||
let at = pos2(420.0, 300.0);
|
||||
let press = Event::PointerButton { pos: at, button: pressed, pressed: true, modifiers: Modifiers::NONE };
|
||||
let out = d.step(vec![Event::PointerMoved(at), press]);
|
||||
assert_eq!(out.focused, Some(0), "{pressed:?}");
|
||||
d.step(vec![Event::PointerButton { pos: at, button: pressed, pressed: false, modifiers: Modifiers::NONE }]);
|
||||
d.step(vec![key(egui::Key::Escape)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_mirrors_the_tab_strip_and_its_insertion_slots() {
|
||||
let mut d = Driver::with(frames(), TestContent { header: 30.0, ..Default::default() }, AREA_600);
|
||||
d.tweak = |style| style.right_to_left = true;
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
let (first, second, bar) = (d.tab(2), d.tab(3), d.rect("drag-bar", 2));
|
||||
assert!((first.right() - 600.0).abs() < 1.0, "the first tab starts at the right edge: {first:?}");
|
||||
assert!(second.right() <= first.left() + 0.5, "{first:?} {second:?}");
|
||||
assert!(bar.right() <= second.left() + 0.5 && bar.left() >= 304.0 + 30.0 - 0.5, "the bar sits between the tabs and the header: {bar:?}");
|
||||
|
||||
// Just right of the first tab's center is before it in a right-to-left strip.
|
||||
let out = d.drag(d.tab(1).center(), pos2(first.center().x + 6.0, first.center().y));
|
||||
assert!(out.actions.contains(&Action::Move { panel: 1, anchor: 3, placement: Placement::Tab { before: Some(2) } }), "{:?}", out.actions);
|
||||
|
||||
let strip = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 20.0));
|
||||
let target = DropTarget {
|
||||
anchor: 1,
|
||||
rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 80.0)),
|
||||
tab_strip: Some(strip),
|
||||
tabs: vec![(1, Rect::from_min_max(pos2(60.0, 0.0), pos2(100.0, 20.0))), (2, Rect::from_min_max(pos2(20.0, 0.0), pos2(60.0, 20.0)))],
|
||||
allow_splits: true,
|
||||
accepts_tabs: true,
|
||||
right_to_left: true,
|
||||
};
|
||||
let drop = |x: f32| resolve_drop(&9, pos2(x, 10.0), std::slice::from_ref(&target), 40.0).unwrap();
|
||||
assert_eq!((drop(90.0).placement, drop(90.0).insertion.unwrap().center().x), (Placement::Tab { before: Some(1) }, 99.0));
|
||||
assert_eq!((drop(70.0).placement, drop(70.0).insertion.unwrap().center().x), (Placement::Tab { before: Some(2) }, 60.0));
|
||||
assert_eq!((drop(10.0).placement, drop(10.0).insertion.unwrap().center().x), (Placement::Tab { before: None }, 20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_right_to_left_title_bar_puts_its_buttons_left_and_cuts_a_galley_title() {
|
||||
let ctx = Context::default();
|
||||
let mut shapes = Vec::new();
|
||||
let mut rects = (Rect::NOTHING, Rect::NOTHING, Rect::NOTHING);
|
||||
let bar = Rect::from_min_size(pos2(10.0, 10.0), vec2(120.0, 18.0));
|
||||
for _ in 0..2 {
|
||||
let mut full = ctx.run_ui(RawInput::default(), |ui| {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
style.right_to_left = true;
|
||||
let chrome = chrome::ChromeStyle::from_dock(&style);
|
||||
let title = egui::WidgetText::Galley(ui.painter().layout_no_wrap("Paragraph Styles and More".into(), style.font.clone(), style.text));
|
||||
let shown = chrome::TitleBar::new(Id::new("title"), "Move").title(title).menu("Menu").close("Close").show(ui, bar, &chrome);
|
||||
rects = (shown.bar.rect, shown.menu.unwrap().rect, shown.close.unwrap().rect);
|
||||
});
|
||||
full.textures_delta.clear();
|
||||
shapes = full.shapes;
|
||||
}
|
||||
let (grip, menu, close) = rects;
|
||||
assert!(close.center().x < menu.center().x && menu.right() <= grip.left() + 0.5, "{close:?} {menu:?} {grip:?}");
|
||||
assert!((grip.right() - bar.right()).abs() < 0.5);
|
||||
let title = flat(&shapes)
|
||||
.into_iter()
|
||||
.find_map(|(_, shape)| match shape {
|
||||
egui::Shape::Text(text) if text.galley.text().starts_with("Para") => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(last_char(&title.galley), Some('…'));
|
||||
assert!(title.pos.x + title.galley.size().x <= grip.right() + 0.5 && title.pos.x >= grip.left());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_close_controls_leave_closing_to_the_host() {
|
||||
let layout = Layout { root: Some(tabs(&[1, 2], 0)), floating: vec![Floating::single(vec![5, 6], 0, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let close = Id::new(AREA).with(("move-group", Some(&5u32))).with("close");
|
||||
let mut d = Driver::new(layout);
|
||||
assert!(d.ctx.read_response(close).is_some());
|
||||
d.tweak = |style| {
|
||||
style.close_button = false;
|
||||
style.close_menu_items = false;
|
||||
};
|
||||
d.step(vec![]);
|
||||
d.step(vec![]);
|
||||
assert!(d.ctx.read_response(close).is_none());
|
||||
let at = d.tab(1).center();
|
||||
let secondary = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
|
||||
d.step(vec![Event::PointerMoved(at), secondary(true)]);
|
||||
d.step(vec![secondary(false)]);
|
||||
d.step(vec![]);
|
||||
let painted = |d: &Driver, label: &str| texts(d).iter().any(|(_, t)| t.galley.text() == label);
|
||||
assert!(painted(&d, "Float Panel"), "the tab menu is open");
|
||||
assert!(!painted(&d, "Close Panel") && !painted(&d, "Close Tab Group"));
|
||||
// The panels stay closable: the host's own Close applies and reports what it closed.
|
||||
assert_eq!(d.layout.apply_with_permissions(Action::CloseWindow { panel: 5 }, |p| d.content.permissions(p)), Ok(vec![5, 6]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_all_returns_every_panel_its_actions_closed() {
|
||||
let mut layout = Layout { root: Some(tabs(&[1, 2, 3], 0)), floating: vec![Floating::single(vec![5, 6], 0, [80.0, 70.0, 300.0, 220.0])] };
|
||||
let closed = layout
|
||||
.apply_all([Action::Activate { panel: 2 }, Action::CloseOthers { panel: 2 }, Action::CloseWindow { panel: 6 }], |_| Permissions::default());
|
||||
assert_eq!(closed, Ok(vec![1, 3, 5, 6]));
|
||||
assert_eq!(layout.apply(Action::Close { panel: 2 }), Ok(vec![2]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_button_and_the_column_menu_item_have_distinct_names() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, content: &mut TestContent| {
|
||||
DockArea::new(Id::new(AREA)).show_content(ui, &docked(), &DockStyle::from_ui(ui), content);
|
||||
},
|
||||
TestContent { protected: vec![0], ..Default::default() },
|
||||
);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.query_all_by_label("Collapse column to icons").count(), 1);
|
||||
assert_eq!(h.query_all_by_label("Collapse to Icons").count(), 0);
|
||||
let at = h.ctx.read_response(Id::new(AREA).with(("column-bar", Some(&2u32)))).unwrap().rect.center();
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(at),
|
||||
Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(1);
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.query_all_by_label("Collapse to Icons").count(), 1);
|
||||
assert_eq!(h.query_all_by_label("Collapse column to icons").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_zone_maps_side_zones_onto_columns_groups_and_splits() {
|
||||
let layout = Layout { root: docked().root, floating: vec![Floating::single(vec![5], 0, [300.0, 80.0, 200.0, 200.0])] };
|
||||
let zone = |anchor, zone, rtl| Placement::for_zone(&layout, &anchor, zone, rtl);
|
||||
assert_eq!(zone(2, Zone::Right, false), Ok(Placement::Column { after: true }));
|
||||
assert_eq!(zone(2, Zone::Right, true), Ok(Placement::Column { after: false }));
|
||||
assert_eq!(zone(4, Zone::Bottom, false), Ok(Placement::Group { below: true, height: None }));
|
||||
assert_eq!(zone(2, Zone::Center, false), Ok(Placement::Split(Zone::Center)));
|
||||
assert_eq!(zone(5, Zone::Top, false), Ok(Placement::Split(Zone::Top)));
|
||||
assert_eq!(zone(5, Zone::Left, false), Ok(Placement::Split(Zone::Left)));
|
||||
assert_eq!(zone(0, Zone::Left, true), Ok(Placement::Split(Zone::Left)));
|
||||
assert_eq!(zone(9, Zone::Left, false), Err(DockError::MissingTarget));
|
||||
|
||||
// An end dock mirrors a start dock.
|
||||
let mut end = docked();
|
||||
let Some(Node::Split { first, second, size, .. }) = &mut end.root else { panic!() };
|
||||
std::mem::swap(first, second);
|
||||
*size = SplitSize::FixedSecond(240.0);
|
||||
let Node::Dock { side, .. } = &mut **second else { panic!() };
|
||||
*side = Side::End;
|
||||
assert_eq!(Placement::for_zone(&end, &2, Zone::Left, false), Ok(Placement::Column { after: true }));
|
||||
assert_eq!(Placement::for_zone(&end, &2, Zone::Left, true), Ok(Placement::Column { after: false }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_placement_gives_the_inserted_group_its_height() {
|
||||
let mut layout = docked();
|
||||
let below = |height| Placement::Group { below: true, height };
|
||||
layout.apply(Action::OpenAt { panel: 7, anchor: 4, placement: below(Some(180.0)) }).unwrap();
|
||||
layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 7, placement: below(Some(90.0)) } }).unwrap();
|
||||
layout.apply(Action::OpenAt { panel: 8, anchor: 4, placement: below(None) }).unwrap();
|
||||
let Some(Node::Split { first, .. }) = &layout.root else { panic!() };
|
||||
let Node::Dock { columns, .. } = &**first else { panic!() };
|
||||
let heights: Vec<_> = columns[0].groups.iter().map(|g| (g.panels.clone(), g.height)).collect();
|
||||
assert_eq!(heights, vec![(vec![4], None), (vec![8], None), (vec![7], Some(180.0)), (vec![2, 3], Some(90.0))]);
|
||||
assert_eq!(layout.apply(Action::OpenAt { panel: 9, anchor: 4, placement: below(Some(f32::NAN)) }), Err(DockError::InvalidGeometry));
|
||||
}
|
||||
|
||||
struct Icons;
|
||||
|
||||
impl DockContent<u32> for Icons {
|
||||
fn body(&mut self, _: &mut egui::Ui, _: &u32) {}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_flyout_change_reports_one_event_whatever_caused_it() {
|
||||
use crate::docking::testing::DockDriver;
|
||||
let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)], 240.0);
|
||||
column.iconic = true;
|
||||
let dock = Node::Dock { side: Side::Start, columns: vec![column] };
|
||||
let canvas = Node::Tabs { panels: vec![0], active: 0 };
|
||||
let layout = Layout {
|
||||
root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), first: Box::new(dock), second: Box::new(canvas) }),
|
||||
floating: Vec::new(),
|
||||
};
|
||||
let mut d = DockDriver::new(layout, Icons);
|
||||
let flyouts = |outputs: Vec<DockOutput<u32>>| -> Vec<Option<u32>> {
|
||||
outputs
|
||||
.into_iter()
|
||||
.flat_map(|out| out.events)
|
||||
.filter_map(|event| match event {
|
||||
DockEvent::FlyoutChanged { panel } => Some(panel),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let icon = |d: &DockDriver<u32, Icons>, panel| d.hit(&Hit::Icon(panel)).unwrap().center();
|
||||
let quiet = |d: &mut DockDriver<u32, Icons>| (0..3).map(|_| d.step(Vec::new())).collect::<Vec<_>>();
|
||||
|
||||
let (one, two) = (icon(&d, 1), icon(&d, 2));
|
||||
assert_eq!(flyouts(vec![d.press(one), d.release(one)]), [Some(1)], "an icon opens it");
|
||||
assert_eq!(flyouts(quiet(&mut d)), [], "an open flyout reports nothing more");
|
||||
assert_eq!(flyouts(vec![d.press(two), d.release(two)]), [Some(2)], "another icon switches it");
|
||||
assert_eq!(flyouts(vec![d.key(egui::Key::Escape)]), [None], "Escape closes it");
|
||||
open_flyout(&d.ctx, d.id, 3u32);
|
||||
assert_eq!(flyouts(vec![d.step(Vec::new())]), [Some(3)], "open_flyout");
|
||||
close_flyout::<u32>(&d.ctx, d.id);
|
||||
assert_eq!(flyouts(vec![d.step(Vec::new())]), [None], "close_flyout");
|
||||
d.raise = Some(1);
|
||||
assert_eq!(flyouts(vec![d.step(Vec::new())]), [Some(1)], "raising an iconic panel opens it");
|
||||
let outside = pos2(600.0, 400.0);
|
||||
assert_eq!(flyouts(vec![d.press(outside), d.release(outside)]), [None], "a press outside closes it");
|
||||
assert_eq!(flyouts(quiet(&mut d)), []);
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//! A saved arrangement: the current layout, where hidden panels go back, the user's saved
|
||||
//! arrangement for Reset, and Lock Workspace.
|
||||
//!
|
||||
//! Storage, file names and size caps stay with the application. A file that does not parse or
|
||||
//! validate, or comes from a newer version, should be kept on disk and not overwritten.
|
||||
|
||||
use std::{collections::HashSet, hash::Hash};
|
||||
|
||||
use super::model::{Action, DockError, Layout, Location, MAX_PANELS, Permissions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", serde(default, bound(deserialize = "P: serde::Deserialize<'de>")))]
|
||||
pub struct Workspace<P> {
|
||||
/// Format version; files without one are v1 (`{layout, hidden}`). Always written as
|
||||
/// [`Workspace::VERSION`].
|
||||
#[cfg_attr(feature = "serde", serde(default = "first_version", serialize_with = "write_version"))]
|
||||
pub version: u32,
|
||||
/// The current arrangement, changes included.
|
||||
pub layout: Layout<P>,
|
||||
/// Closed panels, and panels the application does not register now, with where each one
|
||||
/// goes back.
|
||||
pub hidden: Vec<(P, Location<P>)>,
|
||||
/// A user workspace's saved arrangement; Reset returns to it. Built-in workspaces use the
|
||||
/// application's default instead.
|
||||
pub saved: Option<Layout<P>>,
|
||||
/// Lock Workspace, saved with this workspace: [`Self::apply`] uses
|
||||
/// [`Permissions::locked`], so moving, floating and closing are rejected while activating,
|
||||
/// opening, minimizing and resizing still work. An application with a global lock
|
||||
/// preference instead passes locked permissions itself.
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn first_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn write_version<S: serde::Serializer>(_: &u32, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_u32(Workspace::<()>::VERSION)
|
||||
}
|
||||
|
||||
impl<P> Default for Workspace<P> {
|
||||
fn default() -> Self {
|
||||
Self::new(Layout::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> Workspace<P> {
|
||||
pub const VERSION: u32 = 2;
|
||||
|
||||
pub fn new(layout: Layout<P>) -> Self {
|
||||
Self { version: Self::VERSION, layout, hidden: Vec::new(), saved: None, locked: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
/// Check the version, both layouts and that every hidden panel is hidden once and absent
|
||||
/// from the current layout.
|
||||
pub fn validate(&self) -> Result<(), DockError> {
|
||||
if self.version > Self::VERSION {
|
||||
return Err(DockError::UnsupportedVersion);
|
||||
}
|
||||
self.layout.validate()?;
|
||||
if let Some(saved) = &self.saved {
|
||||
saved.validate()?;
|
||||
}
|
||||
if self.hidden.len() > MAX_PANELS {
|
||||
return Err(DockError::LimitExceeded);
|
||||
}
|
||||
let visible: HashSet<&P> = self.layout.panels().into_iter().collect();
|
||||
let mut seen = HashSet::new();
|
||||
for (panel, _) in &self.hidden {
|
||||
if visible.contains(panel) || !seen.insert(panel) {
|
||||
return Err(DockError::DuplicatePanel);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply one action. Closed panels record where they go back, so each one can be reopened
|
||||
/// with [`Self::set_visible`]. Honors [`Self::locked`]. Returns the panels the action
|
||||
/// closed, in group order, so the application can release their state.
|
||||
pub fn apply(&mut self, action: Action<P>, permissions: impl Fn(&P) -> Permissions) -> Result<Vec<P>, DockError> {
|
||||
self.apply_all([action], permissions)
|
||||
}
|
||||
|
||||
/// Apply every action in order, or none. Returns the panels the actions closed, in order.
|
||||
pub fn apply_all(&mut self, actions: impl IntoIterator<Item = Action<P>>, permissions: impl Fn(&P) -> Permissions) -> Result<Vec<P>, DockError> {
|
||||
self.validate()?;
|
||||
let locked = self.locked;
|
||||
let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) };
|
||||
let mut proposed = self.clone();
|
||||
let mut all_closed = Vec::new();
|
||||
for action in actions {
|
||||
let closed = proposed.layout.closed_by(&action)?;
|
||||
let locations = close_locations(&proposed.layout, &closed);
|
||||
proposed.layout.apply_with_permissions(action, policy)?;
|
||||
for (panel, location) in locations {
|
||||
proposed.hidden.retain(|(p, _)| p != &panel);
|
||||
proposed.hidden.push((panel, location));
|
||||
}
|
||||
all_closed.extend(closed);
|
||||
}
|
||||
let visible: HashSet<P> = proposed.layout.panels().into_iter().cloned().collect();
|
||||
proposed.hidden.retain(|(p, _)| !visible.contains(p));
|
||||
let mut seen = HashSet::new();
|
||||
all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone()));
|
||||
proposed.validate()?;
|
||||
*self = proposed;
|
||||
Ok(all_closed)
|
||||
}
|
||||
|
||||
/// Show or hide one panel. Showing restores its recorded location, following the chain of
|
||||
/// hidden anchors when its own anchor is hidden too; otherwise it opens beside `fallback`.
|
||||
/// A shown panel becomes the active tab of its group. Hiding follows `permissions` and
|
||||
/// [`Self::locked`], as [`Self::apply`] does, so a protected canvas stays shown.
|
||||
pub fn set_visible(&mut self, panel: P, visible: bool, fallback: Option<P>, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> {
|
||||
self.validate()?;
|
||||
if !visible {
|
||||
if !self.layout.contains(&panel) {
|
||||
return Ok(());
|
||||
}
|
||||
return self.apply(Action::Close { panel }, permissions).map(drop);
|
||||
}
|
||||
if self.layout.contains(&panel) {
|
||||
return self.apply(Action::Activate { panel }, |_| Permissions::default()).map(drop);
|
||||
}
|
||||
let mut layout = self.layout.clone();
|
||||
if self.restore_into(&mut layout, &panel).is_err() {
|
||||
layout = self.layout.clone();
|
||||
layout.apply(Action::Open { panel: panel.clone(), anchor: fallback })?;
|
||||
}
|
||||
layout.apply(Action::Activate { panel: panel.clone() })?;
|
||||
self.layout = layout;
|
||||
self.hidden.retain(|(p, _)| p != &panel);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_into(&self, layout: &mut Layout<P>, panel: &P) -> Result<(), DockError> {
|
||||
let find = |p: &P| self.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location);
|
||||
let mut location = find(panel).ok_or(DockError::MissingTarget)?;
|
||||
for _ in 0..=self.hidden.len() {
|
||||
match layout.restore(panel.clone(), location) {
|
||||
Err(DockError::MissingTarget) => {
|
||||
let next = location.anchor.as_ref().filter(|anchor| *anchor != panel).and_then(find);
|
||||
location = next.ok_or(DockError::MissingTarget)?;
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
Err(DockError::MissingTarget)
|
||||
}
|
||||
|
||||
/// Fit a loaded workspace to the panels the application registers now. An invalid
|
||||
/// workspace is replaced by `default`. Panels not registered now (plug-ins, on-demand or
|
||||
/// numbered panels) move to `hidden` with their location, so they come back once registered;
|
||||
/// the saved arrangement drops them. Registered panels in `default` that are neither shown
|
||||
/// nor hidden go to their default place, or to `hidden` when that place cannot be rebuilt.
|
||||
/// A registered panel that `permissions` says cannot close, such as a protected canvas, is
|
||||
/// always shown: at its recorded or default place, else at the outer edge of the docked
|
||||
/// area. Pass the panels' own permissions, not [`Permissions::locked`] ones.
|
||||
/// `hidden` keeps at most [`MAX_PANELS`] entries, dropping the oldest unregistered ones first.
|
||||
pub fn reconcile(&mut self, registered: impl Fn(&P) -> bool, permissions: impl Fn(&P) -> Permissions, default: &Workspace<P>) {
|
||||
if self.validate().is_err() {
|
||||
*self = Workspace { locked: self.locked, ..default.clone() };
|
||||
}
|
||||
let unknown: Vec<P> = self.layout.panels().into_iter().filter(|p| !registered(p)).cloned().collect();
|
||||
let locations = close_locations(&self.layout, &unknown);
|
||||
for panel in &unknown {
|
||||
self.layout.take(panel);
|
||||
}
|
||||
self.hidden.extend(locations);
|
||||
if let Some(saved) = self.saved.as_mut() {
|
||||
let unknown: Vec<P> = saved.panels().into_iter().filter(|p| !registered(p)).cloned().collect();
|
||||
for panel in unknown {
|
||||
saved.take(&panel);
|
||||
}
|
||||
if saved.validate().is_err() {
|
||||
self.saved = None;
|
||||
}
|
||||
}
|
||||
let known: HashSet<P> = self.layout.panels().into_iter().chain(self.hidden.iter().map(|(p, _)| p)).cloned().collect();
|
||||
let mut missing: Vec<(P, Location<P>)> = Vec::new();
|
||||
for panel in default.layout.panels() {
|
||||
if registered(panel)
|
||||
&& !known.contains(panel)
|
||||
&& let Ok(location) = default.layout.location(panel)
|
||||
{
|
||||
missing.push((panel.clone(), location));
|
||||
}
|
||||
}
|
||||
// Anchors may themselves be missing: place what fits, then retry the rest.
|
||||
while !missing.is_empty() {
|
||||
let before = missing.len();
|
||||
missing.retain(|(panel, location)| self.layout.restore(panel.clone(), location).is_err());
|
||||
if missing.len() == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.hidden.extend(missing);
|
||||
for (panel, location) in &default.hidden {
|
||||
if registered(panel) && !known.contains(panel) && !self.layout.contains(panel) && !self.hidden.iter().any(|(p, _)| p == panel) {
|
||||
self.hidden.push((panel.clone(), location.clone()));
|
||||
}
|
||||
}
|
||||
let stuck: Vec<P> = self.hidden.iter().map(|(p, _)| p).filter(|p| registered(p) && !permissions(p).closable).cloned().collect();
|
||||
for panel in stuck {
|
||||
let mut layout = self.layout.clone();
|
||||
let shown = self.restore_into(&mut layout, &panel).is_ok()
|
||||
|| default.layout.location(&panel).is_ok_and(|location| layout.restore(panel.clone(), &location).is_ok())
|
||||
|| layout.open_at_edge(panel.clone()).is_ok();
|
||||
if shown {
|
||||
self.layout = layout;
|
||||
self.hidden.retain(|(p, _)| p != &panel);
|
||||
}
|
||||
}
|
||||
let mut excess = self.hidden.len().saturating_sub(MAX_PANELS);
|
||||
self.hidden.retain(|(p, _)| {
|
||||
let drop = excess > 0 && !registered(p);
|
||||
excess -= usize::from(drop);
|
||||
!drop
|
||||
});
|
||||
self.hidden.truncate(MAX_PANELS);
|
||||
}
|
||||
|
||||
/// Reset: return to the saved arrangement, or `default` when there is none. Panels the
|
||||
/// reset layout does not show stay hidden with their last location.
|
||||
pub fn reset(&mut self, default: &Layout<P>) {
|
||||
let layout = self.saved.clone().unwrap_or_else(|| default.clone());
|
||||
let shown: HashSet<P> = layout.panels().into_iter().cloned().collect();
|
||||
for panel in self.layout.panels() {
|
||||
if !shown.contains(panel)
|
||||
&& !self.hidden.iter().any(|(p, _)| p == panel)
|
||||
&& let Ok(location) = self.layout.location(panel)
|
||||
{
|
||||
self.hidden.push((panel.clone(), location));
|
||||
}
|
||||
}
|
||||
self.hidden.retain(|(p, _)| !shown.contains(p));
|
||||
self.layout = layout;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each of `closed` goes back, captured as if they closed last to first. Reopening them
|
||||
/// first to last rebuilds the group: the first restores the group itself, the rest join it.
|
||||
fn close_locations<P: Clone + Eq + Hash>(layout: &Layout<P>, closed: &[P]) -> Vec<(P, Location<P>)> {
|
||||
if let [panel] = closed {
|
||||
return layout.location(panel).map(|location| vec![(panel.clone(), location)]).unwrap_or_default();
|
||||
}
|
||||
let mut scratch = layout.clone();
|
||||
let mut locations = Vec::new();
|
||||
for panel in closed.iter().rev() {
|
||||
if let Ok(location) = scratch.location(panel) {
|
||||
locations.push((panel.clone(), location));
|
||||
}
|
||||
scratch.take(panel);
|
||||
}
|
||||
locations.reverse();
|
||||
locations
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod resize;
|
||||
mod toolbar;
|
||||
|
||||
pub use geometry::{SplitAxis, SplitLayout, SplitSize, split_rect};
|
||||
pub(crate) use resize::drag_focus;
|
||||
pub use resize::{ResizeHandle, ResizeHandleStyle, ResizeResponse};
|
||||
pub use toolbar::{ToolbarFit, fit_toolbar};
|
||||
|
||||
|
||||
@@ -24,7 +24,8 @@ pub struct ResizeResponse {
|
||||
/// A focusable divider with pointer, arrow-key and accessibility resizing.
|
||||
///
|
||||
/// This widget never stores or changes a pane size. IDs and labels are separate, so translated
|
||||
/// labels do not change identity. Pointer drags retain egui's immediate `Sense::drag` behavior.
|
||||
/// labels do not change identity. Pointer drags retain egui's immediate `Sense::drag` behavior
|
||||
/// and hold focus only for the gesture (see [`drag_focus`]).
|
||||
/// Only arrows along the split axis are consumed, while this handle has focus. Tab remains
|
||||
/// available for normal focus traversal.
|
||||
pub struct ResizeHandle<'a> {
|
||||
@@ -36,11 +37,12 @@ pub struct ResizeHandle<'a> {
|
||||
hit_margin: f32,
|
||||
step: f32,
|
||||
value: Option<(f32, RangeInclusive<f32>)>,
|
||||
reversed: bool,
|
||||
}
|
||||
|
||||
impl<'a> ResizeHandle<'a> {
|
||||
pub fn new(id: Id, axis: SplitAxis, rect: Rect, label: &'a str, style: ResizeHandleStyle) -> Self {
|
||||
Self { id, axis, rect, label, style, hit_margin: 3.0, step: 8.0, value: None }
|
||||
Self { id, axis, rect, label, style, hit_margin: 3.0, step: 8.0, value: None, reversed: false }
|
||||
}
|
||||
|
||||
/// Expand the hit rectangle along the movement axis, in logical points. Default: 3.
|
||||
@@ -62,6 +64,14 @@ impl<'a> ResizeHandle<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The value grows against the axis, as for a column docked on the right edge that widens
|
||||
/// as its divider moves left. Accessibility actions then work on the value; the pointer
|
||||
/// and arrow keys stay physical, and `delta` stays along the axis.
|
||||
pub fn reversed(mut self, reversed: bool) -> Self {
|
||||
self.reversed = reversed;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn show(self, ui: &mut Ui) -> ResizeResponse {
|
||||
let hit = self.rect.expand2(match self.axis {
|
||||
SplitAxis::Horizontal => Vec2::new(self.hit_margin, 0.0),
|
||||
@@ -83,9 +93,7 @@ impl<'a> ResizeHandle<'a> {
|
||||
let enabled = valid && response.enabled();
|
||||
let mut delta = 0.0;
|
||||
if enabled {
|
||||
if response.drag_started() {
|
||||
response.request_focus();
|
||||
}
|
||||
drag_focus(ui, &response);
|
||||
if response.dragged() {
|
||||
let drag = response.drag_delta();
|
||||
delta = match self.axis {
|
||||
@@ -117,27 +125,30 @@ impl<'a> ResizeHandle<'a> {
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut change = 0.0;
|
||||
ui.input_mut(|input| {
|
||||
input.consume_accesskit_action_requests(response.id, |request| match request.action {
|
||||
accesskit::Action::Increment => {
|
||||
delta += self.step;
|
||||
change += self.step;
|
||||
true
|
||||
}
|
||||
accesskit::Action::Decrement => {
|
||||
delta -= self.step;
|
||||
change -= self.step;
|
||||
true
|
||||
}
|
||||
accesskit::Action::SetValue => {
|
||||
if let (Some((value, range)), Some(accesskit::ActionData::NumericValue(new_value))) = (&self.value, &request.data)
|
||||
&& new_value.is_finite()
|
||||
{
|
||||
delta = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32;
|
||||
change = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32;
|
||||
delta = 0.0;
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
});
|
||||
delta += if self.reversed { -change } else { change };
|
||||
}
|
||||
if !delta.is_finite() {
|
||||
delta = 0.0;
|
||||
@@ -196,3 +207,19 @@ impl<'a> ResizeHandle<'a> {
|
||||
ResizeResponse { response, delta }
|
||||
}
|
||||
}
|
||||
|
||||
/// A pointer drag focuses its handle for the gesture only and gives the focus up on release,
|
||||
/// so the app's shortcuts and its canvas arrow keys work again (they defer to a focused
|
||||
/// widget). A handle focused from the keyboard (Tab, F6) before the drag keeps its focus.
|
||||
pub(crate) fn drag_focus(ui: &Ui, response: &Response) {
|
||||
let key = response.id.with("pointer-focus");
|
||||
if response.drag_started() {
|
||||
if !response.has_focus() {
|
||||
ui.ctx().data_mut(|d| d.insert_temp(key, ()));
|
||||
}
|
||||
response.request_focus();
|
||||
}
|
||||
if response.drag_stopped() && ui.ctx().data_mut(|d| d.remove_temp::<()>(key)).is_some() {
|
||||
response.surrender_focus();
|
||||
}
|
||||
}
|
||||
@@ -171,9 +171,32 @@ fn resize_handle_preserves_pointer_drag_lifecycle_and_reports_per_frame_delta()
|
||||
let (response, _) = h.frame(vec![pointer(center + vec2(16.0, 0.0), false)]);
|
||||
assert!(response.response.drag_stopped());
|
||||
assert_eq!(response.delta, 0.0);
|
||||
assert!(!response.response.has_focus());
|
||||
let (response, _) = h.frame(vec![key(Key::ArrowRight)]);
|
||||
assert!(h.ctx.memory(|m| m.focused()).is_none(), "after a pointer drag no widget has focus, so app shortcuts work");
|
||||
assert_eq!(response.delta, 0.0, "arrow keys are left to the app");
|
||||
assert_eq!(h.value, 100.0, "the component never owns pane state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_focused_handle_keeps_focus_through_a_pointer_drag_and_arrow_resizing() {
|
||||
let mut h = HandleTest::new();
|
||||
let center = h.rect.center();
|
||||
h.settle();
|
||||
h.frame(vec![key(Key::Tab)]);
|
||||
let (response, _) = h.frame(vec![]);
|
||||
assert!(response.response.has_focus(), "Tab reaches the handle");
|
||||
h.frame(vec![Event::PointerMoved(center), pointer(center, true)]);
|
||||
h.frame(vec![Event::PointerMoved(center + vec2(12.0, 0.0))]);
|
||||
h.frame(vec![pointer(center + vec2(12.0, 0.0), false)]);
|
||||
let (response, _) = h.frame(vec![key(Key::ArrowRight)]);
|
||||
assert!(response.response.has_focus());
|
||||
assert_eq!(response.delta, 8.0);
|
||||
let (response, _) = h.frame(vec![key(Key::ArrowLeft)]);
|
||||
assert!(response.response.has_focus());
|
||||
assert_eq!(response.delta, -8.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focused_handle_resizes_with_axis_arrows_and_draws_visible_focus() {
|
||||
for (axis, forward, back) in [(SplitAxis::Horizontal, Key::ArrowRight, Key::ArrowLeft), (SplitAxis::Vertical, Key::ArrowDown, Key::ArrowUp)] {
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod buttons;
|
||||
pub mod docking;
|
||||
pub mod icons;
|
||||
pub mod layout;
|
||||
pub mod panes;
|
||||
pub mod printing;
|
||||
pub mod tabs;
|
||||
pub mod theme;
|
||||
@@ -0,0 +1,734 @@
|
||||
//! Task panes for document apps: side and bottom panes around the app's own central document.
|
||||
//!
|
||||
//! [`PaneHost`] draws each open pane as an egui side or bottom panel, or as a floating frame, with
|
||||
//! a title bar (title, ▾ menu, ×) and a resizable inner edge. Call it before the app's
|
||||
//! `CentralPanel`; the document never becomes a panel. The app owns which panes are open and
|
||||
//! where they are: the host takes the open list and each pane's [`PaneState`] every frame and
|
||||
//! returns [`PaneRequest`]s for the app to run through its own commands. Docking chrome
|
||||
//! ([`crate::docking::chrome`]) draws the floating frames and title bars.
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use egui::{Context, Frame, Id, Key, LayerId, Margin, Modifiers, Order, Pos2, Rect, Response, Sense, Ui, UiBuilder, Vec2, pos2, vec2};
|
||||
|
||||
use crate::docking::PanelLimits;
|
||||
use crate::docking::chrome::{self, ChromeStyle, FloatingFrame, MoveStep, TitleBar};
|
||||
use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis};
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A title dragged this far out of a docked pane floats it; a pane dropped this close to the
|
||||
/// host's left or right edge docks there.
|
||||
pub const DOCK_SNAP: f32 = 32.0;
|
||||
/// Height of a pane's title bar.
|
||||
pub const TITLE_BAR_HEIGHT: f32 = 24.0;
|
||||
/// Size of a pane floated for the first time.
|
||||
pub const FLOAT_DEFAULT: Vec2 = vec2(270.0, 480.0);
|
||||
const FLOAT_MIN_HEIGHT: f32 = 160.0;
|
||||
/// Where the title bar is held when a dragged-out pane floats at the pointer.
|
||||
const FLOAT_GRAB: Vec2 = vec2(40.0, 12.0);
|
||||
|
||||
/// A logical edge of the host area. `Start` is left in left-to-right interfaces and right in
|
||||
/// right-to-left ones.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum Edge {
|
||||
Start,
|
||||
End,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
/// Where a pane is shown.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum Place {
|
||||
Docked(Edge),
|
||||
Floating,
|
||||
}
|
||||
|
||||
/// The persisted layout of one pane. The app stores it where it keeps its preferences.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PaneState {
|
||||
pub place: Place,
|
||||
/// Width of a side pane or height of a bottom pane, in points. `None`: the pane's default.
|
||||
pub size: Option<f32>,
|
||||
/// `[x, y, width, height]` of the floating pane, also kept while it is docked.
|
||||
pub float_rect: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl PaneState {
|
||||
pub fn docked(edge: Edge, size: f32) -> Self {
|
||||
Self { place: Place::Docked(edge), size: Some(size), float_rect: None }
|
||||
}
|
||||
|
||||
fn apply<P>(&mut self, request: &PaneRequest<P>) {
|
||||
match request {
|
||||
PaneRequest::Place(_, place) => self.place = *place,
|
||||
PaneRequest::Resize(_, size) => self.size = Some(*size),
|
||||
PaneRequest::FloatRect(_, rect) => self.float_rect = Some(*rect),
|
||||
PaneRequest::Close(_) | PaneRequest::Focus(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How docked panes share an edge.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum SidePolicy {
|
||||
/// Every pane on an edge is shown, side by side in `open` order, the first outermost.
|
||||
#[default]
|
||||
Columns,
|
||||
/// One pane per edge: the last of the edge's closable panes in `open`. Panes that are not
|
||||
/// closable (context panes the app shows from its own state) are shown beside the slot.
|
||||
OneSlot,
|
||||
}
|
||||
|
||||
/// A change the user asked for. The host applies none of them to the app's state.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum PaneRequest<P> {
|
||||
Close(P),
|
||||
Place(P, Place),
|
||||
Resize(P, f32),
|
||||
FloatRect(P, [f32; 4]),
|
||||
/// The pane took focus from a click, keyboard focus or F6.
|
||||
Focus(P),
|
||||
}
|
||||
|
||||
impl<P> PaneRequest<P> {
|
||||
pub fn pane(&self) -> &P {
|
||||
match self {
|
||||
Self::Close(p) | Self::Place(p, _) | Self::Resize(p, _) | Self::FloatRect(p, _) | Self::Focus(p) => p,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`PaneHost::show`] returns.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PaneOutput<P> {
|
||||
/// In the order they happened; apply them in order. Resize and FloatRect arrive every
|
||||
/// frame a gesture changes the size or rect.
|
||||
pub requests: Vec<PaneRequest<P>>,
|
||||
/// The pane holding keyboard focus or last clicked, if it is still shown.
|
||||
pub focused: Option<P>,
|
||||
/// F6 moved focus past the last pane (or Shift+F6 past the first): focus the document.
|
||||
pub to_document: bool,
|
||||
}
|
||||
|
||||
/// The app's side of a pane: its contents and defaults.
|
||||
pub trait PaneContent<P> {
|
||||
/// May follow the selection (Format Shape, Format Picture).
|
||||
fn title(&self, pane: &P) -> String;
|
||||
fn body(&mut self, ui: &mut Ui, pane: &P);
|
||||
/// Used when the state callback returns `None` and the host has none in memory.
|
||||
fn default_state(&self, pane: &P) -> PaneState;
|
||||
/// Width (or bottom height) limits of the docked pane.
|
||||
fn size_range(&self, _pane: &P) -> RangeInclusive<f32> {
|
||||
200.0..=520.0
|
||||
}
|
||||
/// `false`: no Move or Float items and no title drag.
|
||||
fn movable(&self, _pane: &P) -> bool {
|
||||
true
|
||||
}
|
||||
/// `false`: no × and no Close item (context panes such as PivotTable Fields).
|
||||
fn closable(&self, _pane: &P) -> bool {
|
||||
true
|
||||
}
|
||||
/// App items, shown above the Move, Float and Close items of the ▾ menu.
|
||||
fn menu(&mut self, _ui: &mut Ui, _pane: &P) {}
|
||||
}
|
||||
|
||||
/// Labels of the chrome; translate them in the app.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PaneLabels {
|
||||
pub menu: String,
|
||||
pub move_start: String,
|
||||
pub move_end: String,
|
||||
pub move_bottom: String,
|
||||
pub float: String,
|
||||
pub close: String,
|
||||
/// Accessibility label of the title bar. `{title}` is replaced with the pane's title, so
|
||||
/// each title bar has its own name.
|
||||
pub move_pane: String,
|
||||
/// Accessibility label of the resize edges.
|
||||
pub resize: String,
|
||||
}
|
||||
|
||||
impl Default for PaneLabels {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
menu: "Pane options".into(),
|
||||
move_start: "Move to Start".into(),
|
||||
move_end: "Move to End".into(),
|
||||
move_bottom: "Move to Bottom".into(),
|
||||
float: "Float".into(),
|
||||
close: "Close".into(),
|
||||
move_pane: "Move {title} pane".into(),
|
||||
resize: "Resize pane".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the open panes. Build it every frame.
|
||||
pub struct PaneHost {
|
||||
id: Id,
|
||||
rtl: bool,
|
||||
policy: SidePolicy,
|
||||
max_fraction: f32,
|
||||
f6: bool,
|
||||
labels: PaneLabels,
|
||||
frame: Option<Frame>,
|
||||
margin: Margin,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Side {
|
||||
Left,
|
||||
Right,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Memory {
|
||||
active: Option<Id>,
|
||||
last_focus: Option<Id>,
|
||||
/// F6 pressed or [`focus_next`] called: `true` cycles backwards.
|
||||
cycle: Option<bool>,
|
||||
drag_out: Option<DragOut>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct DragOut {
|
||||
pane: Id,
|
||||
canceled: bool,
|
||||
}
|
||||
|
||||
struct Shown<P> {
|
||||
pane: P,
|
||||
id: Id,
|
||||
state: PaneState,
|
||||
}
|
||||
|
||||
/// Where a pane was drawn, for focus tracking.
|
||||
struct Region {
|
||||
pane: Id,
|
||||
rect: Rect,
|
||||
floating: Option<LayerId>,
|
||||
}
|
||||
|
||||
fn memory_id(id: Id) -> Id {
|
||||
id.with("panes-memory")
|
||||
}
|
||||
|
||||
/// Move focus to the next pane (the previous one with `reverse`) at the host's next frame. For
|
||||
/// apps that route F6 through their own commands; see [`PaneHost::f6`].
|
||||
pub fn focus_next(ctx: &Context, id: impl Into<Id>, reverse: bool) {
|
||||
let key = memory_id(id.into());
|
||||
ctx.data_mut(|data| data.get_temp_mut_or_default::<Memory>(key).cycle = Some(reverse));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
impl PaneHost {
|
||||
pub fn new(id: impl Into<Id>) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
rtl: false,
|
||||
policy: SidePolicy::Columns,
|
||||
max_fraction: 1.0,
|
||||
f6: true,
|
||||
labels: PaneLabels::default(),
|
||||
frame: None,
|
||||
margin: Margin::same(8),
|
||||
}
|
||||
}
|
||||
|
||||
/// Right-to-left interface: `Start` is the right edge.
|
||||
pub fn rtl(mut self, rtl: bool) -> Self {
|
||||
self.rtl = rtl;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn policy(mut self, policy: SidePolicy) -> Self {
|
||||
self.policy = policy;
|
||||
self
|
||||
}
|
||||
|
||||
/// Largest share of the host's width (height for bottom panes) one docked pane may take.
|
||||
pub fn max_fraction(mut self, fraction: f32) -> Self {
|
||||
self.max_fraction = if fraction.is_finite() { fraction.clamp(0.0, 1.0) } else { 1.0 };
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the host takes F6 and Shift+F6 to cycle focus through the panes and back to the
|
||||
/// document. Default on. Apps that bind F6 themselves call [`focus_next`].
|
||||
pub fn f6(mut self, f6: bool) -> Self {
|
||||
self.f6 = f6;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn labels(mut self, labels: PaneLabels) -> Self {
|
||||
self.labels = labels;
|
||||
self
|
||||
}
|
||||
|
||||
/// Frame of the docked panels. Default: the panel fill and a hairline border, no margin.
|
||||
pub fn frame(mut self, frame: Frame) -> Self {
|
||||
self.frame = Some(frame);
|
||||
self
|
||||
}
|
||||
|
||||
/// Margin around each pane's body. Default 8.
|
||||
pub fn body_margin(mut self, margin: Margin) -> Self {
|
||||
self.margin = margin;
|
||||
self
|
||||
}
|
||||
|
||||
fn pane_id<P: Hash + Debug>(&self, pane: &P) -> Id {
|
||||
self.id.with(("pane", pane))
|
||||
}
|
||||
|
||||
fn side(&self, edge: Edge) -> Side {
|
||||
match (edge, self.rtl) {
|
||||
(Edge::Bottom, _) => Side::Bottom,
|
||||
(Edge::Start, false) | (Edge::End, true) => Side::Left,
|
||||
(Edge::Start, true) | (Edge::End, false) => Side::Right,
|
||||
}
|
||||
}
|
||||
|
||||
/// The edge a pane dropped at `pointer` docks against, if it is within [`DOCK_SNAP`] of the
|
||||
/// host's left or right edge.
|
||||
fn snap(&self, pointer: Pos2, bounds: Rect) -> Option<Edge> {
|
||||
let left = if self.rtl { Edge::End } else { Edge::Start };
|
||||
let right = if self.rtl { Edge::Start } else { Edge::End };
|
||||
if pointer.x <= bounds.left() + DOCK_SNAP {
|
||||
Some(left)
|
||||
} else if pointer.x >= bounds.right() - DOCK_SNAP {
|
||||
Some(right)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the panes in `open` with the state `states` returns for each (`None`: the state the
|
||||
/// host kept from earlier requests, else the pane's default). Call between the app's top
|
||||
/// and bottom bars and its `CentralPanel`.
|
||||
pub fn show<P: Clone + Hash + Debug, C: PaneContent<P>>(
|
||||
self,
|
||||
ui: &mut Ui,
|
||||
open: &[P],
|
||||
states: impl Fn(&P) -> Option<PaneState>,
|
||||
content: &mut C,
|
||||
) -> PaneOutput<P> {
|
||||
let ctx = ui.ctx().clone();
|
||||
let bounds = ui.available_rect_before_wrap();
|
||||
let style = ChromeStyle { right_to_left: self.rtl, ..ChromeStyle::from_ui(ui) };
|
||||
let key = memory_id(self.id);
|
||||
let mut memory = ctx.data(|data| data.get_temp::<Memory>(key)).unwrap_or_default();
|
||||
let mut requests = Vec::new();
|
||||
let mut to_document = false;
|
||||
|
||||
if self.f6 {
|
||||
ui.input_mut(|input| {
|
||||
if input.consume_key(Modifiers::SHIFT, Key::F6) {
|
||||
memory.cycle = Some(true);
|
||||
} else if input.consume_key(Modifiers::NONE, Key::F6) {
|
||||
memory.cycle = Some(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let mut shown: Vec<Shown<P>> = Vec::new();
|
||||
for pane in open {
|
||||
let id = self.pane_id(pane);
|
||||
if shown.iter().any(|s| s.id == id) {
|
||||
continue;
|
||||
}
|
||||
let state =
|
||||
states(pane).or_else(|| ctx.data(|data| data.get_temp::<PaneState>(id.with("state")))).unwrap_or_else(|| content.default_state(pane));
|
||||
shown.push(Shown { pane: pane.clone(), id, state });
|
||||
}
|
||||
if self.policy == SidePolicy::OneSlot {
|
||||
let mut taken = Vec::new();
|
||||
for index in (0..shown.len()).rev() {
|
||||
if let Place::Docked(edge) = shown[index].state.place
|
||||
&& content.closable(&shown[index].pane)
|
||||
{
|
||||
if taken.contains(&edge) {
|
||||
shown.remove(index);
|
||||
} else {
|
||||
taken.push(edge);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let previous = memory.active.filter(|active| shown.iter().any(|s| s.id == *active));
|
||||
memory.active = previous;
|
||||
let mut focus_target = None;
|
||||
if let Some(reverse) = memory.cycle.take() {
|
||||
let current = memory.active.and_then(|active| shown.iter().position(|s| s.id == active));
|
||||
let next = match (current, reverse) {
|
||||
(None, false) => shown.first(),
|
||||
(None, true) => shown.last(),
|
||||
(Some(i), false) => shown.get(i + 1),
|
||||
(Some(i), true) => i.checked_sub(1).and_then(|i| shown.get(i)),
|
||||
};
|
||||
focus_target = next.map(|s| s.id);
|
||||
memory.active = focus_target;
|
||||
if focus_target.is_none() {
|
||||
to_document = true;
|
||||
ctx.memory_mut(|m| {
|
||||
if let Some(focused) = m.focused() {
|
||||
m.surrender_focus(focused);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let preview = ctx.layer_painter(LayerId::new(Order::Tooltip, self.id.with("drop-preview")));
|
||||
let mut regions = Vec::new();
|
||||
for edge in [Edge::Start, Edge::End, Edge::Bottom] {
|
||||
for s in shown.iter().filter(|s| s.state.place == Place::Docked(edge)) {
|
||||
let rect = self.docked(ui, s, edge, content, &style, focus_target == Some(s.id), bounds, &mut memory, &preview, &mut requests);
|
||||
regions.push(Region { pane: s.id, rect, floating: None });
|
||||
}
|
||||
}
|
||||
for s in shown.iter().filter(|s| s.state.place == Place::Floating) {
|
||||
let (rect, layer) = self.floating(&ctx, s, content, &style, focus_target == Some(s.id), bounds, &mut requests);
|
||||
regions.push(Region { pane: s.id, rect, floating: Some(layer) });
|
||||
}
|
||||
|
||||
if focus_target.is_none() && !to_document {
|
||||
self.track_focus(&ctx, ui.layer_id(), ®ions, &mut memory);
|
||||
}
|
||||
memory.last_focus = ctx.memory(|m| m.focused());
|
||||
if memory.active != previous
|
||||
&& let Some(s) = memory.active.and_then(|active| shown.iter().find(|s| s.id == active))
|
||||
{
|
||||
requests.push(PaneRequest::Focus(s.pane.clone()));
|
||||
}
|
||||
|
||||
for s in &shown {
|
||||
let mut state = s.state;
|
||||
let mut changed = false;
|
||||
for request in requests.iter().filter(|r| self.pane_id(r.pane()) == s.id) {
|
||||
state.apply(request);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
ctx.data_mut(|data| data.insert_temp(s.id.with("state"), state));
|
||||
}
|
||||
}
|
||||
let focused = memory.active.and_then(|active| shown.iter().find(|s| s.id == active)).map(|s| s.pane.clone());
|
||||
ctx.data_mut(|data| data.insert_temp(key, memory));
|
||||
PaneOutput { requests, focused, to_document }
|
||||
}
|
||||
|
||||
/// The pane under a primary press, or the pane holding a newly focused widget, becomes active.
|
||||
/// Presses and focus outside every pane (the document) clear it; presses on other layers
|
||||
/// (menus, the app's own windows) leave it.
|
||||
fn track_focus(&self, ctx: &Context, layer: LayerId, regions: &[Region], memory: &mut Memory) {
|
||||
let find = |at_layer: Option<LayerId>, pos: Pos2| -> Option<Option<Id>> {
|
||||
if let Some(region) = regions.iter().find(|r| r.floating.is_some() && r.floating == at_layer) {
|
||||
return Some(Some(region.pane));
|
||||
}
|
||||
if at_layer.is_none() || at_layer == Some(layer) {
|
||||
return Some(regions.iter().find(|r| r.floating.is_none() && r.rect.contains(pos)).map(|r| r.pane));
|
||||
}
|
||||
None
|
||||
};
|
||||
if ctx.input(|input| input.pointer.primary_pressed())
|
||||
&& let Some(pos) = ctx.input(|input| input.pointer.press_origin())
|
||||
&& let Some(active) = find(ctx.layer_id_at(pos), pos)
|
||||
{
|
||||
memory.active = active;
|
||||
}
|
||||
let focused = ctx.memory(|m| m.focused());
|
||||
if focused != memory.last_focus
|
||||
&& let Some(response) = focused.and_then(|id| ctx.read_response(id))
|
||||
&& let Some(active) = find(Some(response.layer_id), response.rect.center())
|
||||
{
|
||||
memory.active = active;
|
||||
}
|
||||
}
|
||||
|
||||
fn limits<P, C: PaneContent<P>>(&self, content: &C, pane: &P, extent: f32) -> (f32, f32) {
|
||||
let range = content.size_range(pane);
|
||||
let min = if range.start().is_finite() { range.start().max(0.0) } else { 0.0 };
|
||||
let max = if range.end().is_finite() { range.end().max(min) } else { min.max(extent) };
|
||||
(min, max.min(self.max_fraction * extent).max(min))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn docked<P: Clone + Hash + Debug, C: PaneContent<P>>(
|
||||
&self,
|
||||
ui: &mut Ui,
|
||||
s: &Shown<P>,
|
||||
edge: Edge,
|
||||
content: &mut C,
|
||||
style: &ChromeStyle,
|
||||
focus: bool,
|
||||
bounds: Rect,
|
||||
memory: &mut Memory,
|
||||
preview: &egui::Painter,
|
||||
requests: &mut Vec<PaneRequest<P>>,
|
||||
) -> Rect {
|
||||
let side = self.side(edge);
|
||||
let extent = if side == Side::Bottom { bounds.height() } else { bounds.width() };
|
||||
let (min, max) = self.limits(content, &s.pane, extent);
|
||||
let default = content.default_state(&s.pane).size;
|
||||
let size = s.state.size.filter(|v| v.is_finite()).or(default.filter(|v| v.is_finite())).unwrap_or(min).clamp(min, max);
|
||||
let panel_id = s.id.with("panel");
|
||||
let panel = match side {
|
||||
Side::Left => egui::Panel::left(panel_id),
|
||||
Side::Right => egui::Panel::right(panel_id),
|
||||
Side::Bottom => egui::Panel::bottom(panel_id),
|
||||
};
|
||||
let frame = self.frame.unwrap_or_else(|| Frame::NONE.fill(ui.visuals().panel_fill).stroke(ui.visuals().widgets.noninteractive.bg_stroke));
|
||||
let shown = panel.exact_size(size).resizable(false).frame(frame).show(ui, |ui| {
|
||||
let top = ui.max_rect();
|
||||
let title = Rect::from_min_size(top.min, vec2(top.width(), TITLE_BAR_HEIGHT));
|
||||
ui.allocate_rect(title, Sense::hover());
|
||||
let bar = self.chrome(ui, title, s, content, style, focus, bounds, requests);
|
||||
// The pane reserves exactly its size and clips its body. egui cuts a panel wider
|
||||
// than its exact size at its outer edge, so a wide body would shift a right or
|
||||
// bottom pane's reserved rect inwards and the document would draw over the pane.
|
||||
let body = Rect::from_min_max(pos2(top.left(), title.bottom()), top.max);
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(body).layout(*ui.layout()));
|
||||
child.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
Frame::NONE.inner_margin(self.margin).show(&mut child, |ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
content.body(ui, &s.pane);
|
||||
});
|
||||
ui.allocate_rect(body, Sense::hover());
|
||||
bar
|
||||
});
|
||||
let rect = shown.response.rect;
|
||||
let bar = shown.inner;
|
||||
|
||||
let (axis, strip) = match side {
|
||||
Side::Left => (SplitAxis::Horizontal, Rect::from_x_y_ranges(rect.right() - 2.0..=rect.right() + 2.0, rect.y_range())),
|
||||
Side::Right => (SplitAxis::Horizontal, Rect::from_x_y_ranges(rect.left() - 2.0..=rect.left() + 2.0, rect.y_range())),
|
||||
Side::Bottom => (SplitAxis::Vertical, Rect::from_x_y_ranges(rect.x_range(), rect.top() - 2.0..=rect.top() + 2.0)),
|
||||
};
|
||||
let handle_style = ResizeHandleStyle { hovered: style.accent.gamma_multiply(0.5), dragged: style.accent, focused: style.accent };
|
||||
let resize = ResizeHandle::new(s.id.with("resize"), axis, strip, &self.labels.resize, handle_style).show(ui);
|
||||
let next = if resize.response.dragged() {
|
||||
resize.response.interact_pointer_pos().map(|p| match side {
|
||||
Side::Left => p.x - rect.left(),
|
||||
Side::Right => rect.right() - p.x,
|
||||
Side::Bottom => rect.bottom() - p.y,
|
||||
})
|
||||
} else if resize.delta != 0.0 {
|
||||
// Arrow keys move the edge: right grows a left pane, left grows a right pane.
|
||||
Some(if side == Side::Left { size + resize.delta } else { size - resize.delta })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(next) = next.filter(|v| v.is_finite()).map(|v| v.clamp(min, max).round())
|
||||
&& next != size
|
||||
{
|
||||
requests.push(PaneRequest::Resize(s.pane.clone(), next));
|
||||
}
|
||||
|
||||
if content.movable(&s.pane) {
|
||||
self.drag_out(ui.ctx(), &bar, s, edge, rect, bounds, memory, preview, style, requests);
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
/// A docked pane's title dragged beyond [`DOCK_SNAP`] of the pane: dropped near the host's
|
||||
/// left or right edge it docks there, elsewhere it floats under the pointer.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn drag_out<P: Clone>(
|
||||
&self,
|
||||
ctx: &Context,
|
||||
bar: &Response,
|
||||
s: &Shown<P>,
|
||||
edge: Edge,
|
||||
rect: Rect,
|
||||
bounds: Rect,
|
||||
memory: &mut Memory,
|
||||
preview: &egui::Painter,
|
||||
style: &ChromeStyle,
|
||||
requests: &mut Vec<PaneRequest<P>>,
|
||||
) {
|
||||
if bar.drag_started() {
|
||||
memory.drag_out = Some(DragOut { pane: s.id, canceled: false });
|
||||
}
|
||||
let Some(mut drag) = memory.drag_out.filter(|d| d.pane == s.id) else { return };
|
||||
if ctx.input(|input| input.key_pressed(Key::Escape) || !input.focused) {
|
||||
drag.canceled = true;
|
||||
}
|
||||
let near = rect.expand(DOCK_SNAP);
|
||||
let Some(pointer) = ctx.pointer_latest_pos() else { return };
|
||||
let outside = if edge == Edge::Bottom { !near.y_range().contains(pointer.y) } else { !near.x_range().contains(pointer.x) };
|
||||
let size = s.state.float_rect.map_or(FLOAT_DEFAULT, |r| vec2(r[2], r[3]));
|
||||
let float = float_rect(Some(rect_array(Rect::from_min_size(pointer - FLOAT_GRAB, size))), bounds, vec2(0.0, FLOAT_MIN_HEIGHT));
|
||||
let target = self.snap(pointer, bounds);
|
||||
if bar.drag_stopped() {
|
||||
memory.drag_out = None;
|
||||
if drag.canceled || !outside {
|
||||
return;
|
||||
}
|
||||
match target {
|
||||
Some(target) if target != edge => requests.push(PaneRequest::Place(s.pane.clone(), Place::Docked(target))),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
requests.push(PaneRequest::Place(s.pane.clone(), Place::Floating));
|
||||
requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(float)));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !bar.dragged() {
|
||||
memory.drag_out = None;
|
||||
return;
|
||||
}
|
||||
memory.drag_out = Some(drag);
|
||||
if drag.canceled || !outside {
|
||||
return;
|
||||
}
|
||||
let shape = match target.map(|t| self.side(t)) {
|
||||
Some(Side::Left) => Rect::from_x_y_ranges(bounds.left()..=bounds.left() + rect.width(), bounds.y_range()),
|
||||
Some(_) => Rect::from_x_y_ranges(bounds.right() - rect.width()..=bounds.right(), bounds.y_range()),
|
||||
None => float,
|
||||
};
|
||||
chrome::drop_preview(preview, shape.shrink(1.0), style.accent, true);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn floating<P: Clone + Hash + Debug, C: PaneContent<P>>(
|
||||
&self,
|
||||
ctx: &Context,
|
||||
s: &Shown<P>,
|
||||
content: &mut C,
|
||||
style: &ChromeStyle,
|
||||
focus: bool,
|
||||
bounds: Rect,
|
||||
requests: &mut Vec<PaneRequest<P>>,
|
||||
) -> (Rect, LayerId) {
|
||||
let (min_width, _) = self.limits(content, &s.pane, bounds.width());
|
||||
let min = vec2(min_width, FLOAT_MIN_HEIGHT);
|
||||
let rect = float_rect(s.state.float_rect, bounds, min);
|
||||
let limits = PanelLimits { min, max: bounds.size().max(min) };
|
||||
let shown = FloatingFrame::new(s.id.with("float"), rect).bounds(bounds).limits(limits).resize_label(&self.labels.resize).show(
|
||||
ctx,
|
||||
style,
|
||||
|ui, rect| {
|
||||
let title = Rect::from_min_size(rect.min, vec2(rect.width(), TITLE_BAR_HEIGHT));
|
||||
let bar = self.chrome(ui, title, s, content, style, focus, bounds, requests);
|
||||
let body = Rect::from_min_max(pos2(rect.left(), title.bottom()), rect.max) - self.margin;
|
||||
if body.is_positive() {
|
||||
ui.scope_builder(UiBuilder::new().max_rect(body), |ui| {
|
||||
ui.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
content.body(ui, &s.pane);
|
||||
});
|
||||
}
|
||||
bar
|
||||
},
|
||||
);
|
||||
if let Some(resized) = shown.resized {
|
||||
requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(resized)));
|
||||
}
|
||||
if content.movable(&s.pane) {
|
||||
match chrome::live_move(ctx, &shown.inner, shown.rect, bounds) {
|
||||
Some(MoveStep::Moving(next) | MoveStep::Canceled(next)) if next != shown.rect => {
|
||||
requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(next)));
|
||||
}
|
||||
Some(MoveStep::Dropped { rect, pointer }) => {
|
||||
if let Some(edge) = self.snap(pointer, bounds) {
|
||||
requests.push(PaneRequest::Place(s.pane.clone(), Place::Docked(edge)));
|
||||
} else if rect != shown.rect {
|
||||
requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(rect)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(shown.rect, shown.layer)
|
||||
}
|
||||
|
||||
/// Title, ▾ menu and ×. Returns the bar, which senses the title drag.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn chrome<P: Clone, C: PaneContent<P>>(
|
||||
&self,
|
||||
ui: &mut Ui,
|
||||
rect: Rect,
|
||||
s: &Shown<P>,
|
||||
content: &mut C,
|
||||
style: &ChromeStyle,
|
||||
focus: bool,
|
||||
bounds: Rect,
|
||||
requests: &mut Vec<PaneRequest<P>>,
|
||||
) -> Response {
|
||||
let movable = content.movable(&s.pane);
|
||||
let closable = content.closable(&s.pane);
|
||||
let title = content.title(&s.pane);
|
||||
let move_label = self.labels.move_pane.replace("{title}", &title);
|
||||
let mut bar = TitleBar::new(s.id.with("title"), &move_label).title(title).menu(&self.labels.menu).movable(movable);
|
||||
if closable {
|
||||
bar = bar.close(&self.labels.close);
|
||||
}
|
||||
let title = bar.show(ui, rect, style);
|
||||
if focus {
|
||||
title.bar.request_focus();
|
||||
}
|
||||
if title.close.as_ref().is_some_and(Response::clicked) {
|
||||
requests.push(PaneRequest::Close(s.pane.clone()));
|
||||
}
|
||||
if let Some(menu) = &title.menu {
|
||||
egui::Popup::menu(menu).show(|ui| {
|
||||
let top = ui.cursor().top();
|
||||
content.menu(ui, &s.pane);
|
||||
if ui.cursor().top() > top && (movable || closable) {
|
||||
ui.separator();
|
||||
}
|
||||
if movable {
|
||||
let mut places = vec![(Place::Docked(Edge::Start), &self.labels.move_start), (Place::Docked(Edge::End), &self.labels.move_end)];
|
||||
if content.default_state(&s.pane).place == Place::Docked(Edge::Bottom) {
|
||||
places.push((Place::Docked(Edge::Bottom), &self.labels.move_bottom));
|
||||
}
|
||||
places.push((Place::Floating, &self.labels.float));
|
||||
for (place, label) in places {
|
||||
if ui.selectable_label(s.state.place == place, label.as_str()).clicked() && s.state.place != place {
|
||||
requests.push(PaneRequest::Place(s.pane.clone(), place));
|
||||
if place == Place::Floating {
|
||||
let rect = float_rect(s.state.float_rect, bounds, vec2(0.0, FLOAT_MIN_HEIGHT));
|
||||
requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(rect)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if closable && ui.button(self.labels.close.as_str()).clicked() {
|
||||
requests.push(PaneRequest::Close(s.pane.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
title.bar
|
||||
}
|
||||
}
|
||||
|
||||
fn rect_array(rect: Rect) -> [f32; 4] {
|
||||
[rect.min.x, rect.min.y, rect.width(), rect.height()]
|
||||
}
|
||||
|
||||
/// The floating rect for `saved` (`[x, y, width, height]`), at least `min` and at most the
|
||||
/// bounds in size, inside `bounds`. Without a saved rect: [`FLOAT_DEFAULT`] right of the middle.
|
||||
/// Non-finite or negative values fall back to the defaults, so the result is always finite.
|
||||
pub fn float_rect(saved: Option<[f32; 4]>, bounds: Rect, min: Vec2) -> Rect {
|
||||
let bounds = if bounds.is_finite() && bounds.is_positive() { bounds } else { Rect::from_min_size(Pos2::ZERO, FLOAT_DEFAULT) };
|
||||
let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback };
|
||||
let size = saved.map_or(FLOAT_DEFAULT, |r| vec2(finite(r[2], FLOAT_DEFAULT.x), finite(r[3], FLOAT_DEFAULT.y)));
|
||||
let size = size.max(min.max(Vec2::splat(1.0))).min(bounds.size());
|
||||
let free = (bounds.size() - size).max(Vec2::ZERO);
|
||||
let default = (bounds.min + vec2(free.x * 0.75, free.y * 0.3)).round();
|
||||
let pos = saved.map_or(default, |r| pos2(finite(r[0], default.x), finite(r[1], default.y)));
|
||||
let pos = pos.max(bounds.min).min((bounds.max - size).max(bounds.min));
|
||||
Rect::from_min_size(pos, size)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,342 @@
|
||||
//! Behavior tests for the pane host, driven by egui pointer and key events in an 800 × 600
|
||||
//! window. The harness's root ui has an 8 pt margin, so the host spans x 8..792, y 8..592.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2, Rect, Ui, pos2, vec2};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
|
||||
use super::*;
|
||||
|
||||
const L: f32 = 8.0;
|
||||
const R: f32 = 792.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
enum Pane {
|
||||
Nav,
|
||||
Styles,
|
||||
Comments,
|
||||
/// A context pane, like PivotTable Fields: not closable, not movable.
|
||||
Pivot,
|
||||
}
|
||||
|
||||
struct Content;
|
||||
|
||||
impl PaneContent<Pane> for Content {
|
||||
fn title(&self, pane: &Pane) -> String {
|
||||
format!("{pane:?}")
|
||||
}
|
||||
fn body(&mut self, ui: &mut Ui, pane: &Pane) {
|
||||
ui.label(format!("{pane:?} body"));
|
||||
}
|
||||
fn default_state(&self, pane: &Pane) -> PaneState {
|
||||
let edge = if matches!(pane, Pane::Comments | Pane::Pivot) { Edge::End } else { Edge::Start };
|
||||
PaneState::docked(edge, 250.0)
|
||||
}
|
||||
fn movable(&self, pane: &Pane) -> bool {
|
||||
*pane != Pane::Pivot
|
||||
}
|
||||
fn closable(&self, pane: &Pane) -> bool {
|
||||
*pane != Pane::Pivot
|
||||
}
|
||||
}
|
||||
|
||||
/// The app side: open list, persisted states and every request it received.
|
||||
struct App {
|
||||
open: Vec<Pane>,
|
||||
states: HashMap<Pane, PaneState>,
|
||||
log: Vec<PaneRequest<Pane>>,
|
||||
focused: Option<Pane>,
|
||||
to_document: usize,
|
||||
rtl: bool,
|
||||
policy: SidePolicy,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new(open: &[Pane]) -> Self {
|
||||
Self { open: open.to_vec(), states: HashMap::new(), log: Vec::new(), focused: None, to_document: 0, rtl: false, policy: SidePolicy::Columns }
|
||||
}
|
||||
|
||||
fn frame(&mut self, ui: &mut Ui) {
|
||||
let states = self.states.clone();
|
||||
let out = PaneHost::new("panes").rtl(self.rtl).policy(self.policy).show(ui, &self.open, |p| states.get(p).copied(), &mut Content);
|
||||
egui::CentralPanel::default().show(ui, |ui| ui.label("Document"));
|
||||
for request in &out.requests {
|
||||
match request {
|
||||
PaneRequest::Close(p) => self.open.retain(|o| o != p),
|
||||
PaneRequest::Focus(_) => {}
|
||||
other => {
|
||||
let pane = *other.pane();
|
||||
let state = self.states.entry(pane).or_insert_with(|| Content.default_state(&pane));
|
||||
state.apply(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.log.extend(out.requests);
|
||||
self.focused = out.focused;
|
||||
self.to_document += usize::from(out.to_document);
|
||||
}
|
||||
|
||||
fn place(&self, pane: Pane) -> Place {
|
||||
self.states.get(&pane).map_or_else(|| Content.default_state(&pane).place, |s| s.place)
|
||||
}
|
||||
}
|
||||
|
||||
fn harness(app: App) -> Harness<'static, App> {
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(|ui, app: &mut App| app.frame(ui), app);
|
||||
h.input_mut().focused = true;
|
||||
h.run_steps(2);
|
||||
h
|
||||
}
|
||||
|
||||
fn pane_id(pane: Pane) -> Id {
|
||||
Id::new("panes").with(("pane", &pane))
|
||||
}
|
||||
|
||||
fn rect(h: &Harness<'_, App>, id: Id) -> Option<Rect> {
|
||||
h.ctx.read_response(id).map(|r| r.rect)
|
||||
}
|
||||
|
||||
fn title(h: &Harness<'_, App>, pane: Pane) -> Rect {
|
||||
rect(h, pane_id(pane).with("title")).unwrap()
|
||||
}
|
||||
|
||||
/// The x of a side pane's inner edge.
|
||||
fn edge(h: &Harness<'_, App>, pane: Pane) -> f32 {
|
||||
rect(h, pane_id(pane).with("resize")).unwrap().center().x
|
||||
}
|
||||
|
||||
fn button(pos: Pos2, pressed: bool) -> Event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn send(h: &mut Harness<'_, App>, events: Vec<Event>) {
|
||||
h.input_mut().events.extend(events);
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, App>, at: Pos2) {
|
||||
send(h, vec![Event::PointerMoved(at), button(at, true)]);
|
||||
send(h, vec![button(at, false)]);
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn hold(h: &mut Harness<'_, App>, from: Pos2, to: Pos2) {
|
||||
send(h, vec![Event::PointerMoved(from), button(from, true)]);
|
||||
send(h, vec![Event::PointerMoved(from + vec2(8.0, 6.0))]);
|
||||
send(h, vec![Event::PointerMoved(to)]);
|
||||
}
|
||||
|
||||
fn drag(h: &mut Harness<'_, App>, from: Pos2, to: Pos2) {
|
||||
hold(h, from, to);
|
||||
send(h, vec![button(to, false)]);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn key(h: &mut Harness<'_, App>, key: Key, modifiers: Modifiers) {
|
||||
send(h, vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]);
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
/// The requests that change a pane's state or open list.
|
||||
fn changes(app: &App) -> Vec<PaneRequest<Pane>> {
|
||||
app.log.iter().filter(|r| !matches!(r, PaneRequest::Focus(_))).cloned().collect()
|
||||
}
|
||||
|
||||
fn last_resize(app: &App, pane: Pane) -> Option<f32> {
|
||||
app.log.iter().rev().find_map(|r| match r {
|
||||
PaneRequest::Resize(p, size) if *p == pane => Some(*size),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_sit_side_by_side_resize_and_move_to_end() {
|
||||
let mut h = harness(App::new(&[Pane::Nav, Pane::Styles]));
|
||||
assert_eq!(edge(&h, Pane::Nav), L + 250.0);
|
||||
assert_eq!(edge(&h, Pane::Styles), L + 500.0);
|
||||
assert!(title(&h, Pane::Nav).left() < L + 2.0);
|
||||
|
||||
drag(&mut h, pos2(L + 250.0, 300.0), pos2(L + 300.0, 300.0));
|
||||
assert_eq!(last_resize(h.state(), Pane::Nav), Some(300.0));
|
||||
assert_eq!(edge(&h, Pane::Nav), L + 300.0);
|
||||
assert_eq!(edge(&h, Pane::Styles), L + 550.0, "the second column follows");
|
||||
|
||||
let at = rect(&h, pane_id(Pane::Nav).with("title").with("menu")).unwrap().center();
|
||||
click(&mut h, at);
|
||||
for label in ["Move to Start", "Move to End", "Float", "Close"] {
|
||||
assert!(h.query_all_by_label(label).count() >= 1, "{label}");
|
||||
}
|
||||
h.get_by_label("Move to End").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().log.contains(&PaneRequest::Place(Pane::Nav, Place::Docked(Edge::End))));
|
||||
assert_eq!(edge(&h, Pane::Nav), R - 300.0, "a 300 pt pane at the right edge");
|
||||
assert_eq!(edge(&h, Pane::Styles), L + 250.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_dragged_out_floats_and_a_drop_near_an_edge_docks() {
|
||||
// Drag-out-to-float and the 32 pt edge snap follow wordcraft#2584.
|
||||
let mut h = harness(App::new(&[Pane::Styles]));
|
||||
let from = title(&h, Pane::Styles).center();
|
||||
// Within DOCK_SNAP of the pane: nothing happens.
|
||||
drag(&mut h, from, pos2(L + 270.0, 300.0));
|
||||
assert!(changes(h.state()).is_empty(), "{:?}", h.state().log);
|
||||
|
||||
drag(&mut h, from, pos2(400.0, 300.0));
|
||||
assert_eq!(
|
||||
changes(h.state()),
|
||||
vec![PaneRequest::Place(Pane::Styles, Place::Floating), PaneRequest::FloatRect(Pane::Styles, [360.0, 112.0, 270.0, 480.0])],
|
||||
"floats under the pointer, clamped to the window"
|
||||
);
|
||||
assert_eq!(title(&h, Pane::Styles).min, pos2(360.0, 116.0));
|
||||
|
||||
// Dropped within 32 pt of the right edge: docked at End.
|
||||
h.state_mut().log.clear();
|
||||
let from = title(&h, Pane::Styles).center();
|
||||
drag(&mut h, from, pos2(780.0, 300.0));
|
||||
assert_eq!(h.state().log.last(), Some(&PaneRequest::Place(Pane::Styles, Place::Docked(Edge::End))));
|
||||
assert_eq!(edge(&h, Pane::Styles), R - 250.0);
|
||||
// The floating rect's size is kept for the next float.
|
||||
assert_eq!(h.state().states[&Pane::Styles].float_rect.map(|r| [r[2], r[3]]), Some([270.0, 480.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_and_focus_loss_restore_a_floating_pane_during_a_move() {
|
||||
let mut app = App::new(&[Pane::Styles]);
|
||||
let start = [300.0, 100.0, 270.0, 400.0];
|
||||
app.states.insert(Pane::Styles, PaneState { place: Place::Floating, size: None, float_rect: Some(start) });
|
||||
let mut h = harness(app);
|
||||
let from = title(&h, Pane::Styles).center();
|
||||
let float_rect = |h: &Harness<'_, App>| h.state().states[&Pane::Styles].float_rect;
|
||||
|
||||
hold(&mut h, from, from + vec2(40.0, 30.0));
|
||||
assert_eq!(float_rect(&h), Some([340.0, 130.0, 270.0, 400.0]), "follows the pointer");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
assert_eq!(float_rect(&h), Some(start));
|
||||
send(&mut h, vec![Event::PointerMoved(pos2(790.0, 300.0))]);
|
||||
send(&mut h, vec![button(pos2(790.0, 300.0), false)]);
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.state().place(Pane::Styles), Place::Floating, "the rest of the drag is ignored");
|
||||
assert_eq!(float_rect(&h), Some(start));
|
||||
|
||||
hold(&mut h, from, from + vec2(-60.0, 20.0));
|
||||
assert_eq!(float_rect(&h), Some([240.0, 120.0, 270.0, 400.0]));
|
||||
h.input_mut().focused = false;
|
||||
h.run_steps(1);
|
||||
h.input_mut().focused = true;
|
||||
send(&mut h, vec![button(from + vec2(-60.0, 20.0), false)]);
|
||||
assert_eq!(float_rect(&h), Some(start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f6_cycles_through_the_panes_and_back_to_the_document() {
|
||||
let mut h = harness(App::new(&[Pane::Nav, Pane::Comments]));
|
||||
let focused_widget = |h: &Harness<'_, App>| h.ctx.memory(|m| m.focused());
|
||||
key(&mut h, Key::F6, Modifiers::NONE);
|
||||
assert_eq!(h.state().focused, Some(Pane::Nav));
|
||||
assert_eq!(focused_widget(&h), Some(pane_id(Pane::Nav).with("title")));
|
||||
key(&mut h, Key::F6, Modifiers::NONE);
|
||||
assert_eq!(h.state().focused, Some(Pane::Comments));
|
||||
key(&mut h, Key::F6, Modifiers::NONE);
|
||||
assert_eq!((h.state().focused, h.state().to_document), (None, 1));
|
||||
assert_eq!(focused_widget(&h), None);
|
||||
key(&mut h, Key::F6, Modifiers::SHIFT);
|
||||
assert_eq!(h.state().focused, Some(Pane::Comments), "Shift+F6 from the document goes to the last pane");
|
||||
let focus: Vec<_> = h.state().log.iter().filter(|r| matches!(r, PaneRequest::Focus(_))).cloned().collect();
|
||||
assert_eq!(focus, vec![PaneRequest::Focus(Pane::Nav), PaneRequest::Focus(Pane::Comments), PaneRequest::Focus(Pane::Comments)]);
|
||||
|
||||
// A click in the document clears it; a click in a pane sets it.
|
||||
click(&mut h, pos2(400.0, 300.0));
|
||||
assert_eq!(h.state().focused, None);
|
||||
click(&mut h, pos2(100.0, 300.0));
|
||||
assert_eq!(h.state().focused, Some(Pane::Nav));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_slot_shows_the_last_pane_per_edge_beside_context_panes() {
|
||||
let mut app = App::new(&[Pane::Pivot, Pane::Comments, Pane::Styles]);
|
||||
app.policy = SidePolicy::OneSlot;
|
||||
app.states.insert(Pane::Styles, PaneState::docked(Edge::End, 300.0));
|
||||
let mut h = harness(app);
|
||||
assert!(rect(&h, pane_id(Pane::Comments).with("title")).is_none());
|
||||
assert_eq!(edge(&h, Pane::Pivot), R - 250.0, "the context pane stays, outermost");
|
||||
assert_eq!(edge(&h, Pane::Styles), R - 550.0);
|
||||
assert!(rect(&h, pane_id(Pane::Pivot).with("title").with("close")).is_none());
|
||||
|
||||
let at = rect(&h, pane_id(Pane::Styles).with("title").with("close")).unwrap().center();
|
||||
click(&mut h, at);
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.state().open, vec![Pane::Pivot, Pane::Comments]);
|
||||
assert_eq!(edge(&h, Pane::Comments), R - 500.0, "the slot shows the remaining pane");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_mirrors_sides_and_edge_snaps() {
|
||||
let mut app = App::new(&[Pane::Nav, Pane::Comments]);
|
||||
app.rtl = true;
|
||||
let mut h = harness(app);
|
||||
assert_eq!(edge(&h, Pane::Nav), R - 250.0, "Start is the right edge");
|
||||
assert_eq!(edge(&h, Pane::Comments), L + 250.0);
|
||||
|
||||
let from = title(&h, Pane::Nav).center();
|
||||
drag(&mut h, from, pos2(10.0, 300.0));
|
||||
assert_eq!(changes(h.state()), vec![PaneRequest::Place(Pane::Nav, Place::Docked(Edge::End))], "the left edge is End");
|
||||
// Both on End, outermost first in open order.
|
||||
assert_eq!(edge(&h, Pane::Nav), L + 250.0);
|
||||
assert_eq!(edge(&h, Pane::Comments), L + 500.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_rect_is_finite_and_inside_the_bounds() {
|
||||
let bounds = Rect::from_min_size(pos2(0.0, 100.0), vec2(800.0, 500.0));
|
||||
let min = vec2(200.0, 160.0);
|
||||
assert_eq!(float_rect(Some([300.0, 150.0, 280.0, 300.0]), bounds, min), Rect::from_min_size(pos2(300.0, 150.0), vec2(280.0, 300.0)));
|
||||
for junk in [[f32::NAN, 0.0, 1.0, -3.0], [5000.0, -5000.0, 1.0e9, 1.0e9], [f32::NEG_INFINITY, f32::INFINITY, f32::NAN, 0.0]] {
|
||||
let r = float_rect(Some(junk), bounds, min);
|
||||
assert!(r.is_finite() && bounds.contains_rect(r) && r.width() >= 200.0, "{junk:?} -> {r:?}");
|
||||
}
|
||||
assert_eq!(float_rect(None, bounds, min).size(), FLOAT_DEFAULT.min(bounds.size()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn pane_state_round_trips_through_json() {
|
||||
let state = PaneState { place: Place::Docked(Edge::End), size: Some(280.0), float_rect: Some([1.0, 2.0, 270.0, 480.0]) };
|
||||
let json = serde_json::to_string(&state).unwrap();
|
||||
assert_eq!(serde_json::from_str::<PaneState>(&json).unwrap(), state);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_wider_than_its_pane_is_clipped_and_the_document_starts_at_the_pane_edge() {
|
||||
struct Wide;
|
||||
impl PaneContent<Pane> for Wide {
|
||||
fn title(&self, pane: &Pane) -> String {
|
||||
format!("{pane:?}")
|
||||
}
|
||||
fn body(&mut self, ui: &mut Ui, _: &Pane) {
|
||||
ui.allocate_exact_size(vec2(400.0, 40.0), Sense::hover());
|
||||
}
|
||||
fn default_state(&self, pane: &Pane) -> PaneState {
|
||||
PaneState::docked(if *pane == Pane::Comments { Edge::End } else { Edge::Start }, 250.0)
|
||||
}
|
||||
}
|
||||
let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|
||||
|ui, document: &mut Rect| {
|
||||
PaneHost::new("panes").show(ui, &[Pane::Nav, Pane::Comments], |_| None, &mut Wide);
|
||||
*document = ui.available_rect_before_wrap();
|
||||
},
|
||||
Rect::NOTHING,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let document = *h.state();
|
||||
assert_eq!(document.left(), L + 250.0, "{document:?}");
|
||||
assert_eq!(document.right(), R - 250.0, "{document:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_title_bar_is_named_after_its_pane() {
|
||||
let h = harness(App::new(&[Pane::Nav, Pane::Comments]));
|
||||
assert_eq!(h.query_all_by_label("Move Nav pane").count(), 1);
|
||||
assert_eq!(h.query_all_by_label("Move Comments pane").count(), 1);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Tab fitting and accessible tab interactions without owning a dock or document model.
|
||||
//!
|
||||
//! The caller owns identity, localization, selection, painting, overflow menus and drag actions.
|
||||
//! [`fit`] only assigns widths; [`Tab`] returns the complete egui response, including double-click
|
||||
//! and drag phases, so a panel strip can collapse, reorder or tear off according to its app.
|
||||
//! [`fit`] (tabs shrink before they overflow) and [`fit_whole`] (tabs keep their full width) only
|
||||
//! assign widths; [`Tab`] returns the complete egui response, including double-click and drag
|
||||
//! phases, so a panel strip can collapse, reorder or tear off according to its app.
|
||||
|
||||
use egui::{Id, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2};
|
||||
|
||||
@@ -70,6 +71,48 @@ pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32,
|
||||
TabFit { shown, overflow, overflow_width }
|
||||
}
|
||||
|
||||
/// Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu.
|
||||
///
|
||||
/// Tabs are shown in input order up to the first one that does not fit beside the selected tab
|
||||
/// and an overflow button of `overflow_width`. The selected tab (or the final tab if `selected`
|
||||
/// is out of bounds) is always shown, in its logical place: when it lies past that run, it takes
|
||||
/// the place of the last tabs that fit. Only a selected tab wider than the strip minus the button
|
||||
/// gets less than its natural width; its painter elides the label. A lone tab never reserves a
|
||||
/// button.
|
||||
///
|
||||
/// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never
|
||||
/// exceed the sanitized available width. Work and storage are linear in the input count.
|
||||
pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit {
|
||||
let available = extent(available);
|
||||
let natural: Vec<f32> = natural.iter().map(|&w| extent(w)).collect();
|
||||
if natural.iter().map(|&w| f64::from(w)).sum::<f64>() <= f64::from(available) {
|
||||
return TabFit { shown: natural.into_iter().enumerate().collect(), ..Default::default() };
|
||||
}
|
||||
if let [width] = natural[..] {
|
||||
return TabFit { shown: vec![(0, width.min(available))], ..Default::default() };
|
||||
}
|
||||
let overflow_width = extent(overflow_width).min(available);
|
||||
let budget = available - overflow_width;
|
||||
let selected = selected.min(natural.len().saturating_sub(1));
|
||||
let active = natural.get(selected).copied().unwrap_or(0.0).min(budget);
|
||||
let mut room = f64::from(budget - active);
|
||||
let mut shown = Vec::new();
|
||||
let mut overflow = Vec::new();
|
||||
let mut full = false;
|
||||
for (i, &width) in natural.iter().enumerate() {
|
||||
if i == selected {
|
||||
shown.push((i, active));
|
||||
} else if !full && f64::from(width) <= room {
|
||||
room -= f64::from(width);
|
||||
shown.push((i, width));
|
||||
} else {
|
||||
full = true;
|
||||
overflow.push(i);
|
||||
}
|
||||
}
|
||||
TabFit { shown, overflow, overflow_width }
|
||||
}
|
||||
|
||||
fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec<(usize, f32)> {
|
||||
let width = |i: usize| natural.get(i).copied().unwrap_or(0.0);
|
||||
let sum_at = |cap: f32| indices.iter().map(|&i| f64::from(width(i).min(cap.max(width(i).min(minimum))))).sum::<f64>();
|
||||
|
||||
@@ -72,6 +72,48 @@ fn many_tabs_keep_the_last_selected_without_quadratic_membership_scans() {
|
||||
assert!(total(&f) <= 240.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_tabs_keep_their_width_and_the_selected_tab_replaces_the_last_that_fits() {
|
||||
let natural = [60.0, 70.0, 80.0, 50.0, 90.0, 40.0];
|
||||
// 200 points: 22 for the button leaves 178.
|
||||
let f = fit_whole(&natural, 0, 200.0, 22.0);
|
||||
assert_eq!(f.shown, [(0, 60.0), (1, 70.0)]);
|
||||
assert_eq!(f.overflow, [2, 3, 4, 5]);
|
||||
assert_eq!(f.overflow_width, 22.0);
|
||||
// The last tab, selected, takes the place of tab 1 and keeps its order.
|
||||
let f = fit_whole(&natural, 5, 200.0, 22.0);
|
||||
assert_eq!(f.shown, [(0, 60.0), (1, 70.0), (5, 40.0)]);
|
||||
assert_eq!(f.overflow, [2, 3, 4]);
|
||||
let f = fit_whole(&natural, 4, 200.0, 22.0);
|
||||
assert_eq!(f.shown, [(0, 60.0), (4, 90.0)]);
|
||||
assert_eq!(f.overflow, [1, 2, 3, 5]);
|
||||
// Everything fits: no button.
|
||||
let f = fit_whole(&natural, 4, 390.0, 22.0);
|
||||
assert_eq!(f.shown.len(), 6);
|
||||
assert!(f.overflow.is_empty() && f.overflow_width == 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_selected_tab_wider_than_the_strip_is_narrowed() {
|
||||
let f = fit_whole(&[60.0, 300.0, 70.0], 1, 200.0, 22.0);
|
||||
assert_eq!(f.shown, [(1, 178.0)]);
|
||||
assert_eq!(f.overflow, [0, 2]);
|
||||
for selected in [0, 1, 2, usize::MAX] {
|
||||
for available in [0.0, 1.0, 21.0, 22.0, 100.0, 200.0, 500.0] {
|
||||
let natural = [60.0, 300.0, 70.0];
|
||||
let f = fit_whole(&natural, selected, available, 22.0);
|
||||
let selected = selected.min(2);
|
||||
assert!(f.shown.iter().all(|&(i, w)| i == selected || w == natural[i]), "{selected} at {available}: {f:?}");
|
||||
assert!(f.shown.iter().any(|&(i, _)| i == selected));
|
||||
assert_eq!(f.shown.len() + f.overflow.len(), 3);
|
||||
assert!(total(&f) <= available + 0.001, "{available}: {f:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(fit_whole(&[80.0], 0, 10.0, 22.0).shown, [(0, 10.0)]);
|
||||
let f = fit_whole(&[f32::NAN, f32::INFINITY, -5.0, 30.0], usize::MAX, f32::NAN, f32::MAX);
|
||||
assert!(f.shown.iter().all(|&(_, w)| w.is_finite() && w >= 0.0) && total(&f) == 0.0);
|
||||
}
|
||||
|
||||
struct TabTest {
|
||||
ctx: Context,
|
||||
labels: [String; 2],
|
||||
|
||||
@@ -55,7 +55,7 @@ impl Harness {
|
||||
first: Box::new(Node::Tabs { panels: vec![CANVAS], active: 0 }),
|
||||
second: Box::new(Node::Tabs { panels: vec![LAYERS, PROPERTIES], active: 0 }),
|
||||
}),
|
||||
floating: vec![Floating { panels: vec![BRUSHES], active: 0, rect: [38.0, 76.0, 210.0, 250.0] }],
|
||||
floating: vec![Floating::single(vec![BRUSHES], 0, [38.0, 76.0, 210.0, 250.0])],
|
||||
};
|
||||
let mut harness = Self {
|
||||
ctx,
|
||||
@@ -235,7 +235,7 @@ fn floating_brushes_merge_detach_and_redock_through_real_pointer_input() {
|
||||
assert_eq!(h.body_ids[&BRUSHES], brush_id);
|
||||
h.capture(&directory, "02-merged-main-tabs");
|
||||
h.drag(h.tab(BRUSHES).center(), pos2((width - 240.0) * 0.5, 270.0));
|
||||
assert!(h.layout.floating.iter().any(|g| g.panels.contains(&BRUSHES)), "{name}: {:?}", h.applied);
|
||||
assert!(h.layout.floating.iter().any(|g| g.contains(&BRUSHES)), "{name}: {:?}", h.applied);
|
||||
h.capture(&directory, "03-detached-again");
|
||||
h.drag(h.tab(BRUSHES).center(), h.tab(LAYERS).left_center() + vec2(4.0, 0.0));
|
||||
assert!(h.layout.floating.is_empty(), "{name}");
|
||||
@@ -250,3 +250,188 @@ fn floating_brushes_merge_detach_and_redock_through_real_pointer_input() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each app's saved v1 layout goes through a docking session driven by real pointer input and a
|
||||
/// command, then writes and reads back unchanged.
|
||||
#[cfg(all(feature = "serde", feature = "testing"))]
|
||||
mod v1_fixtures {
|
||||
use craft_ui::docking::{DockCommand, DockContent, Hit, Layout, Node, Permissions, ResizeEdge, Side, testing::DockDriver};
|
||||
use egui::{Pos2, Rect, pos2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
struct Content;
|
||||
|
||||
impl DockContent<String> for Content {
|
||||
fn body(&mut self, ui: &mut egui::Ui, panel: &String) {
|
||||
ui.label(panel.as_str());
|
||||
}
|
||||
fn logical_label(&self, panel: &String) -> String {
|
||||
panel.clone()
|
||||
}
|
||||
fn permissions(&self, panel: &String) -> Permissions {
|
||||
if panel == "canvas" { Permissions::PROTECTED } else { Permissions::default() }
|
||||
}
|
||||
}
|
||||
|
||||
type Driver = DockDriver<String, Content>;
|
||||
type Columns = Vec<Vec<Vec<String>>>;
|
||||
|
||||
/// App, file contents and the JSON pointer to a saved layout.
|
||||
const FIXTURES: [(&str, &str, &str); 10] = [
|
||||
("designcraft", include_str!("fixtures/v1/designcraft.json"), "/docking"),
|
||||
("designcraft", include_str!("fixtures/v1/designcraft.json"), "/customWorkspaces/0/docking"),
|
||||
("vectorcraft", include_str!("fixtures/v1/vectorcraft.json"), "/docking"),
|
||||
("lightcraft", include_str!("fixtures/v1/lightcraft.json"), "/docking/layout"),
|
||||
("pdfcraft", include_str!("fixtures/v1/pdfcraft.json"), "/docking/layout"),
|
||||
("cadcraft", include_str!("fixtures/v1/cadcraft.json"), "/workspace/docking/layout"),
|
||||
("soundcraft", include_str!("fixtures/v1/soundcraft.json"), "/docking/layout"),
|
||||
("soundcraft", include_str!("fixtures/v1/soundcraft.json"), "/mix_docking/layout"),
|
||||
("photocraft", include_str!("fixtures/v1/photocraft.json"), "/docking"),
|
||||
("photocraft", include_str!("fixtures/v1/photocraft.json"), "/panel_layout/docking"),
|
||||
];
|
||||
|
||||
/// The start dock's columns, each a list of groups.
|
||||
fn start_columns(layout: &Layout<String>) -> Columns {
|
||||
fn find(node: &Node<String>) -> Option<Columns> {
|
||||
match node {
|
||||
Node::Dock { side: Side::Start, columns } => {
|
||||
Some(columns.iter().map(|column| column.groups.iter().map(|group| group.panels.clone()).collect()).collect())
|
||||
}
|
||||
Node::Split { first, second, .. } => find(first).or_else(|| find(second)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
layout.root.as_ref().and_then(find).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn iconic(layout: &Layout<String>) -> bool {
|
||||
fn find(node: &Node<String>) -> Option<bool> {
|
||||
match node {
|
||||
Node::Dock { side: Side::Start, columns } => columns.first().map(|column| column.iconic),
|
||||
Node::Split { first, second, .. } => find(first).or_else(|| find(second)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
layout.root.as_ref().and_then(find).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn hit(d: &Driver, hit: Hit<String>) -> Rect {
|
||||
d.hit(&hit).unwrap_or_else(|| panic!("{hit:?} in {:?}", d.hits()))
|
||||
}
|
||||
|
||||
/// A point of `from` that no floating window above it covers, as drawn last frame.
|
||||
fn grab(d: &Driver, from: &Hit<String>, panel: &String) -> Option<Pos2> {
|
||||
let rect = d.hit(from)?;
|
||||
let own = d.layout.floating.iter().position(|w| w.contains(panel));
|
||||
let windows: Vec<Rect> = d
|
||||
.layout
|
||||
.floating
|
||||
.iter()
|
||||
.filter_map(|w| {
|
||||
let first = w.panels().next()?.clone();
|
||||
Some(Rect::from_min_max(d.hit(&Hit::Title(first.clone()))?.min, d.hit(&Hit::Resize(first, ResizeEdge::BottomRight))?.max))
|
||||
})
|
||||
.collect();
|
||||
let covered = |p: Pos2| windows.iter().enumerate().any(|(i, w)| own.is_none_or(|own| i > own) && w.contains(p));
|
||||
let mut x = rect.left() + 4.0;
|
||||
while x < rect.right() {
|
||||
let p = pos2(x, rect.center().y);
|
||||
if !covered(p) {
|
||||
return Some(p);
|
||||
}
|
||||
x += 4.0;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Drag from an uncovered point of `from` to `to`; something must change.
|
||||
fn drag(d: &mut Driver, from: Hit<String>, to: Pos2, what: &str) {
|
||||
let panel = match &from {
|
||||
Hit::DragBar(p) | Hit::Title(p) => p.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let at = grab(d, &from, &panel).unwrap_or_else(|| panic!("{what}: {from:?} is covered"));
|
||||
let out = d.drag(at, to);
|
||||
assert!(out.error.is_none() && !out.actions.is_empty(), "{what}: {out:?}\n{:?}\n{:?}", d.layout, d.hits());
|
||||
d.settle();
|
||||
}
|
||||
|
||||
fn sorted(layout: &Layout<String>) -> Vec<String> {
|
||||
let mut panels: Vec<String> = layout.panels().into_iter().cloned().collect();
|
||||
panels.sort();
|
||||
panels
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v1_layouts_dock_collapse_float_redock_and_reload() {
|
||||
let mut seams = Vec::new();
|
||||
for (app, text, pointer) in FIXTURES {
|
||||
let at = format!("{app}{pointer}");
|
||||
let file: Value = serde_json::from_str(text).unwrap();
|
||||
let layout: Layout<String> = serde_json::from_value(file.pointer(pointer).unwrap().clone()).unwrap_or_else(|e| panic!("{at}: {e}"));
|
||||
let panels = sorted(&layout);
|
||||
let mut d = Driver::new(layout, Content);
|
||||
let mut bars: Vec<String> = Vec::new();
|
||||
for (h, _) in d.hits() {
|
||||
if let Hit::DragBar(panel) = h
|
||||
&& !bars.contains(&panel)
|
||||
{
|
||||
bars.push(panel);
|
||||
}
|
||||
}
|
||||
assert!(bars.len() >= 2, "{at}: two movable groups in {bars:?}");
|
||||
|
||||
// The first group's bar dropped on the window's start edge makes a dock.
|
||||
drag(&mut d, Hit::DragBar(bars[0].clone()), pos2(2.0, 300.0), &format!("{at}: new dock"));
|
||||
let columns = start_columns(&d.layout);
|
||||
assert!(columns.len() == 1 && columns[0].len() == 1 && columns[0][0][0] == bars[0], "{at}: {columns:?}");
|
||||
|
||||
// The second group stacks below it, and a third goes into the seam between them.
|
||||
let first = hit(&d, Hit::Tab(bars[0].clone()));
|
||||
let bottom = d.area.bottom();
|
||||
drag(&mut d, Hit::DragBar(bars[1].clone()), pos2(first.center().x, bottom - 10.0), &format!("{at}: stack below"));
|
||||
let third = bars[2..].iter().find(|p| grab(&d, &Hit::DragBar((*p).clone()), p).is_some()).cloned();
|
||||
if let Some(third) = &third {
|
||||
seams.push(at.clone());
|
||||
let second = hit(&d, Hit::Tab(bars[1].clone()));
|
||||
drag(&mut d, Hit::DragBar(third.clone()), pos2(second.center().x, second.top() + 2.0), &format!("{at}: seam"));
|
||||
}
|
||||
let columns = start_columns(&d.layout);
|
||||
let heads: Vec<&String> = columns[0].iter().map(|group| &group[0]).collect();
|
||||
let expected: Vec<&String> = match &third {
|
||||
Some(third) => vec![&bars[0], third, &bars[1]],
|
||||
None => vec![&bars[0], &bars[1]],
|
||||
};
|
||||
assert_eq!((columns.len(), heads), (1, expected), "{at}");
|
||||
|
||||
// Collapse the column to icons and expand it again.
|
||||
d.click(hit(&d, Hit::Collapse(bars[0].clone())).center());
|
||||
d.settle();
|
||||
assert!(iconic(&d.layout), "{at}: collapsed");
|
||||
assert!(d.hit(&Hit::Icon(bars[0].clone())).is_some(), "{at}: icons");
|
||||
d.click(hit(&d, Hit::Collapse(bars[0].clone())).center());
|
||||
d.settle();
|
||||
assert!(!iconic(&d.layout), "{at}: expanded");
|
||||
|
||||
// Float the column by command, then drag its window back to the start edge.
|
||||
let float: DockCommand<String> =
|
||||
serde_json::from_value(json!({"command": "window.panel.float", "panel": bars[0], "column": true})).unwrap();
|
||||
let space = craft_ui::docking::float_space(&d.ctx, d.id).unwrap();
|
||||
let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone()), false, &space).unwrap();
|
||||
d.layout.apply_all(actions, |p| d.content.permissions(p)).unwrap_or_else(|e| panic!("{at}: {e}"));
|
||||
d.settle();
|
||||
assert!(start_columns(&d.layout).is_empty(), "{at}: floated");
|
||||
drag(&mut d, Hit::Title(bars[0].clone()), pos2(2.0, 300.0), &format!("{at}: dock back"));
|
||||
assert_eq!(start_columns(&d.layout), columns, "{at}: docked back");
|
||||
|
||||
// Nothing was lost, and the layout reads back as written.
|
||||
assert_eq!(sorted(&d.layout), panels, "{at}");
|
||||
let written = serde_json::to_string(&d.layout).unwrap();
|
||||
let read: Layout<String> = serde_json::from_str(&written).unwrap();
|
||||
read.validate().unwrap_or_else(|e| panic!("{at}: {e}"));
|
||||
assert_eq!(read, d.layout, "{at}");
|
||||
}
|
||||
// The fixtures with a third movable group, uncovered, try the seam.
|
||||
assert_eq!(seams.len(), 6, "{seams:?}");
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"version": 1,
|
||||
"workspace": {
|
||||
"docking": {
|
||||
"layout": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedFirst": 220.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"toolSets"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedSecond": 300.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Stack": {
|
||||
"entries": [
|
||||
{
|
||||
"panel": "layers",
|
||||
"open": true,
|
||||
"height": 280.0
|
||||
},
|
||||
{
|
||||
"panel": "properties",
|
||||
"open": false,
|
||||
"height": null
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"quickCalc"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
320.0,
|
||||
200.0,
|
||||
240.0,
|
||||
300.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"hidden": [
|
||||
[
|
||||
"externalReferences",
|
||||
{
|
||||
"floating": null,
|
||||
"anchor": "layers",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": "properties"
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": [
|
||||
true,
|
||||
null
|
||||
],
|
||||
"sibling": []
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
{
|
||||
"uiScale": 1.0,
|
||||
"theme": "dark",
|
||||
"docking": {
|
||||
"root": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"properties",
|
||||
"pages",
|
||||
"layers",
|
||||
"stroke"
|
||||
],
|
||||
"active": 2
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"swatches",
|
||||
"color"
|
||||
],
|
||||
"active": 1,
|
||||
"rect": [
|
||||
640.0,
|
||||
120.0,
|
||||
280.0,
|
||||
360.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"dockingHidden": {
|
||||
"gradient": {
|
||||
"floating": [
|
||||
640.0,
|
||||
120.0,
|
||||
280.0,
|
||||
360.0
|
||||
],
|
||||
"anchor": "swatches",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": null
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": null,
|
||||
"sibling": []
|
||||
},
|
||||
"effects": {
|
||||
"floating": null,
|
||||
"anchor": "layers",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": "stroke"
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": null,
|
||||
"sibling": []
|
||||
}
|
||||
},
|
||||
"customWorkspaces": [
|
||||
{
|
||||
"name": "Print",
|
||||
"docking": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedFirst": 268.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"layers"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"properties",
|
||||
"pages"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"swatches"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
120.0,
|
||||
160.0,
|
||||
280.0,
|
||||
360.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"dockingHidden": {
|
||||
"stroke": {
|
||||
"floating": null,
|
||||
"anchor": "layers",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": null
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": null,
|
||||
"sibling": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"uiScale": 1.0,
|
||||
"docking": {
|
||||
"layout": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedSecond": 270.0
|
||||
},
|
||||
"first": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedFirst": 268.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"library"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"tools"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": []
|
||||
},
|
||||
"hidden": [
|
||||
[
|
||||
"presets",
|
||||
{
|
||||
"floating": null,
|
||||
"anchor": "canvas",
|
||||
"placement": {
|
||||
"Split": "Right"
|
||||
},
|
||||
"size": {
|
||||
"FixedSecond": 300.0
|
||||
},
|
||||
"stack": null,
|
||||
"sibling": [
|
||||
"canvas"
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"docking": {
|
||||
"layout": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedFirst": 272.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"tools"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedSecond": 330.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"inspector"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": []
|
||||
},
|
||||
"hidden": []
|
||||
},
|
||||
"docking_left_open": true,
|
||||
"docking_right": null,
|
||||
"recent": []
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
{
|
||||
"docking": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedSecond": 300.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Split": {
|
||||
"axis": "Vertical",
|
||||
"size": {
|
||||
"Ratio": 0.5
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"layers",
|
||||
"channels",
|
||||
"paths"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"adjustments",
|
||||
"history"
|
||||
],
|
||||
"active": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"properties"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
120.0,
|
||||
160.0,
|
||||
320.0,
|
||||
440.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"docking_hidden": {
|
||||
"navigator": {
|
||||
"floating": null,
|
||||
"anchor": "layers",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": "channels"
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": null,
|
||||
"sibling": []
|
||||
}
|
||||
},
|
||||
"panel_layout": {
|
||||
"docking": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedSecond": 300.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Split": {
|
||||
"axis": "Vertical",
|
||||
"size": {
|
||||
"Ratio": 0.5
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"layers",
|
||||
"channels",
|
||||
"paths"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"adjustments",
|
||||
"history"
|
||||
],
|
||||
"active": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"properties"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
120.0,
|
||||
160.0,
|
||||
320.0,
|
||||
440.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"dockingHidden": {
|
||||
"navigator": {
|
||||
"floating": null,
|
||||
"anchor": "layers",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": "channels"
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": null,
|
||||
"sibling": []
|
||||
}
|
||||
},
|
||||
"dockingCollapsed": []
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
{
|
||||
"docking": {
|
||||
"layout": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Vertical",
|
||||
"size": {
|
||||
"FixedSecond": 348.0
|
||||
},
|
||||
"first": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedFirst": 168.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"tracks"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedSecond": 230.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"clips"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"midi"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"memory"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
160.0,
|
||||
120.0,
|
||||
480.0,
|
||||
280.0
|
||||
]
|
||||
},
|
||||
{
|
||||
"panels": [
|
||||
"history"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
680.0,
|
||||
120.0,
|
||||
260.0,
|
||||
300.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"hidden": []
|
||||
},
|
||||
"mix_docking": {
|
||||
"layout": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Horizontal",
|
||||
"size": {
|
||||
"FixedFirst": 168.0
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"tracks"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"canvas"
|
||||
],
|
||||
"active": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"memory"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
160.0,
|
||||
120.0,
|
||||
480.0,
|
||||
280.0
|
||||
]
|
||||
},
|
||||
{
|
||||
"panels": [
|
||||
"history"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
680.0,
|
||||
120.0,
|
||||
260.0,
|
||||
300.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"hidden": [
|
||||
[
|
||||
"clips",
|
||||
{
|
||||
"floating": null,
|
||||
"anchor": "canvas",
|
||||
"placement": {
|
||||
"Split": "Right"
|
||||
},
|
||||
"size": {
|
||||
"FixedSecond": 230.0
|
||||
},
|
||||
"stack": null,
|
||||
"sibling": [
|
||||
"canvas"
|
||||
]
|
||||
}
|
||||
],
|
||||
[
|
||||
"midi",
|
||||
{
|
||||
"floating": null,
|
||||
"anchor": "tracks",
|
||||
"placement": {
|
||||
"Split": "Bottom"
|
||||
},
|
||||
"size": {
|
||||
"FixedSecond": 348.0
|
||||
},
|
||||
"stack": null,
|
||||
"sibling": [
|
||||
"tracks",
|
||||
"canvas"
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"dock_tab": "layers",
|
||||
"docking": {
|
||||
"root": {
|
||||
"Split": {
|
||||
"axis": "Vertical",
|
||||
"size": {
|
||||
"Ratio": 0.625
|
||||
},
|
||||
"first": {
|
||||
"Tabs": {
|
||||
"panels": [
|
||||
"properties",
|
||||
"layers",
|
||||
"libraries"
|
||||
],
|
||||
"active": 1
|
||||
}
|
||||
},
|
||||
"second": {
|
||||
"Stack": {
|
||||
"entries": [
|
||||
{
|
||||
"panel": "color",
|
||||
"open": true,
|
||||
"height": 180.0
|
||||
},
|
||||
{
|
||||
"panel": "swatches",
|
||||
"open": false,
|
||||
"height": null
|
||||
},
|
||||
{
|
||||
"panel": "stroke",
|
||||
"open": true,
|
||||
"height": null
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"floating": [
|
||||
{
|
||||
"panels": [
|
||||
"brushes",
|
||||
"symbols"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
200.0,
|
||||
140.0,
|
||||
300.0,
|
||||
400.0
|
||||
]
|
||||
},
|
||||
{
|
||||
"panels": [
|
||||
"gradient"
|
||||
],
|
||||
"active": 0,
|
||||
"rect": [
|
||||
540.0,
|
||||
180.0,
|
||||
260.0,
|
||||
320.0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"docking_hidden": {
|
||||
"patternOptions": {
|
||||
"floating": null,
|
||||
"anchor": "color",
|
||||
"placement": {
|
||||
"Tab": {
|
||||
"before": "swatches"
|
||||
}
|
||||
},
|
||||
"size": null,
|
||||
"stack": [
|
||||
true,
|
||||
240.0
|
||||
],
|
||||
"sibling": []
|
||||
}
|
||||
},
|
||||
"docking_icons": [
|
||||
"stroke"
|
||||
]
|
||||
}
|
||||
+342
-111
@@ -1,151 +1,382 @@
|
||||
# Panel docking
|
||||
|
||||
`craft_ui::docking` lets an application move the same panel between docked tabs, side splits and
|
||||
floating groups. The shared layer owns placement and interaction; the application owns each
|
||||
panel's contents, commands, document state and persistence policy.
|
||||
`craft_ui::docking` lets the user arrange an app's panels: tab groups, docks with columns,
|
||||
splits, floating windows and iconic columns. craft-ui owns the layout model, the renderer and the
|
||||
gestures. The app owns panel contents, commands, document state and where layouts are saved.
|
||||
|
||||
## Model and transactions
|
||||
Office apps that draw their own document with a few task panes beside it use
|
||||
[`craft_ui::panes`](ui-panes.md) instead.
|
||||
|
||||
`Layout<P>` contains an optional root `Node<P>` and floating tab groups. A node can be:
|
||||
## Arrangements
|
||||
|
||||
- `Tabs`: ordered panel identities with one active index.
|
||||
- `Split`: horizontal or vertical children, with a ratio or fixed first/second size.
|
||||
- `Stack`: accordion entries with individual open state and optional content height.
|
||||
One model serves every app. What differs between apps is the default layout and a few
|
||||
`DockStyle` settings. An app builds its style with `DockStyle::from_ui`, `from_visuals` or
|
||||
`default` and then sets fields; new fields can be added, so the struct has no literal form
|
||||
outside the crate.
|
||||
|
||||
Choose a stable, nonlocalized panel ID type implementing `Clone + Eq + Hash`. Rendering also
|
||||
requires `Debug + Send + Sync + 'static`. A panel identity occurs at most once in the layout.
|
||||
Keep transient document/sequence tabs separate when they represent documents inside one panel.
|
||||
| Arrangement | Layout | Style settings | Apps |
|
||||
|---|---|---|---|
|
||||
| Docks beside a canvas (the defaults) | `Node::Dock`s on the window's start and end edges. A dock has columns; a column has stacked groups and can collapse to icons. Frames (tab groups and splits) fill the space between the docks. | `new_dock_zones` on | Creative apps with a canvas and panel docks |
|
||||
| A split tree of tab groups | `Split`s and `Tabs` only. | `side_edge_zones`, `maximize_item`, `close_others_item`, `command_press_floats`, `float_hint`, `wheel_selects_tabs`, `middle_click_closes_tabs` on, `new_dock_zones`, `float_on_empty_drop` and `title_bar_docks` off; menu labels such as "Undock Panel" set on `float_label`, `float_group_label` and `close_group_label` | Apps whose whole window is frames |
|
||||
|
||||
Sides are logical: `Side::Start` is the left edge, or the right edge when
|
||||
`DockStyle::right_to_left` is set. egui has no app-wide direction, so the app sets it from its
|
||||
locale. Right to left, tab strips also mirror: the first tab is rightmost, the group header and
|
||||
drag bar are at the left, and drop insertion slots follow. Accordion headers and floating title
|
||||
bars (`chrome::TitleBar`, through `ChromeStyle::right_to_left`) mirror too. Frame splits keep
|
||||
their sides.
|
||||
|
||||
## Model
|
||||
|
||||
`Layout<P>` holds an optional root `Node<P>` and a list of `Floating` windows.
|
||||
|
||||
| Node | Holds |
|
||||
|---|---|
|
||||
| `Tabs` | A tab group: panels and the active index. |
|
||||
| `Split` | Two children, horizontal or vertical, with a ratio. A fixed first or second size from a saved layout is drawn at that size until the divider moves; a moved divider stores a ratio. |
|
||||
| `Stack` | Accordion entries, each open or closed, with an optional height. |
|
||||
| `Dock` | A side and its columns. A `Column` has `Group`s, a width, and `iconic`. |
|
||||
|
||||
A `Floating` window holds a tree like the docked layout's (`root`: splits, tab groups and
|
||||
accordions, no docks), a rect, an optional native-window rect and `minimized`.
|
||||
`Floating::single` makes a window with one group, `Floating::new` one with a tree, and
|
||||
`Floating::stack` one with groups stacked top to bottom (a vertical split sized by the groups'
|
||||
heights, as an app's own stacked layouts migrate); `panels()` and `contains()` read it. Saved layouts keep loading: a window stored as one group (v1) or as a
|
||||
stack of groups loads as that group or as a vertical split of the stacked groups, sized by their
|
||||
heights.
|
||||
|
||||
`P` is the app's panel id: stable, not localized, `Clone + Eq + Hash`. The renderer also needs
|
||||
`Debug + Send + Sync + 'static`. A panel occurs at most once in a layout.
|
||||
|
||||
Change a layout only through `Action`s:
|
||||
|
||||
```rust
|
||||
use craft_ui::docking::{Action, Floating, Layout, Node, Placement};
|
||||
|
||||
let mut layout = Layout {
|
||||
root: Some(Node::Tabs { panels: vec!["layers", "properties"], active: 0 }),
|
||||
floating: vec![Floating {
|
||||
panels: vec!["brushes"], active: 0, rect: [40.0, 80.0, 240.0, 300.0],
|
||||
}],
|
||||
floating: vec![Floating::single(vec!["brushes"], 0, [40.0, 80.0, 240.0, 300.0])],
|
||||
};
|
||||
layout.apply(Action::Move {
|
||||
panel: "brushes", anchor: "layers",
|
||||
panel: "brushes",
|
||||
anchor: "layers",
|
||||
placement: Placement::Tab { before: Some("properties") },
|
||||
})?;
|
||||
# Ok::<(), craft_ui::docking::DockError>(())
|
||||
```
|
||||
|
||||
Every transaction validates the original layout before cloning or recursive mutation. It checks
|
||||
the resulting layout before replacing the original. Missing or self targets, duplicate IDs,
|
||||
invalid active indices, excessive depth/count and invalid geometry return `DockError`; they do
|
||||
not remove the source panel. Tab removals retain the selected panel by identity when possible.
|
||||
Empty source groups collapse. Moving within an accordion preserves its entry state and height;
|
||||
unaffected split sizing and accordion entries remain unchanged.
|
||||
- `Move`, `MovePanel`, `Float` and `Close` act on one panel. `MoveGroup`, `MoveColumn` and
|
||||
`MoveWindow` move a group, a dock column or a floating window, named by any panel in it.
|
||||
- A `Target` is `At { anchor, placement }`, `Float { rect }` or `NewDock { side }`.
|
||||
- A `Placement` is a tab position, a split zone, a new group above or below (with an optional
|
||||
preferred `height`), a new column, or a new frame on an outer edge.
|
||||
- Containers take different placements: a dock column takes groups and columns, not splits.
|
||||
`Placement::for_zone(layout, anchor, zone, right_to_left)` maps a left, right, top, bottom or
|
||||
center zone onto what the anchor's container takes: a split in the frame tree, a new column on
|
||||
that side or a new group above or below in a dock. A floating window takes splits as the
|
||||
docked layout does; `Placement::Group` on a floating anchor splits its group above or below.
|
||||
- A side split zone puts what moves in a new half-size split of the anchor's frame, and no
|
||||
other frame changes size. The new split has its own divider, and the drop preview shows the
|
||||
half the new frame takes.
|
||||
- Other actions select, minimize, collapse to icons, resize splits (`ResizeSplit` in the docked
|
||||
layout, `ResizeWindowSplit` in the floating window holding a panel), columns and groups, and
|
||||
move a floating window to its own OS window (`SetNative`, feature `native-windows`).
|
||||
- A move between windows (docked to floating, floating to floating) is one action, checked as a
|
||||
whole like any other.
|
||||
|
||||
`OpenAt` adds a currently absent registered panel at an explicit tab or side destination. `Open`
|
||||
is the simpler group-reveal operation. Registry checks remain app-owned: the shared model cannot
|
||||
know whether an ID names an actual panel or whether its content is supported by the application.
|
||||
Every action checks the whole result before it commits. A bad target, a duplicate id, a stale
|
||||
split path or invalid geometry returns a `DockError` and leaves the layout unchanged. The source
|
||||
panel is never lost. `apply`, `apply_with_permissions` and `apply_all` return the panels the
|
||||
actions closed, so the app can release their state; `closed_by` lists them before applying.
|
||||
|
||||
Use `apply_with_permissions` to prevent moving/closing a document canvas or merging a panel into
|
||||
it. `Permissions::PROTECTED` disallows these operations while allowing side splits around it.
|
||||
An app that requires a permanently docked panel also checks that policy before accepting a
|
||||
transaction; an empty shared root is valid when all panels float.
|
||||
`Permissions` limit what may happen to a panel: `movable`, `floatable`, `closable`,
|
||||
`accepts_tabs` and `accepts_splits`. `apply_with_permissions` enforces them for every action,
|
||||
whoever issues it. `Permissions::PROTECTED` keeps a canvas docked and open and takes neither tabs
|
||||
nor side splits; a group dropped on it floats there. An app that opens panels beside its canvas
|
||||
uses `Permissions { accepts_splits: true, ..Permissions::PROTECTED }`.
|
||||
|
||||
## Rendering and interaction
|
||||
## Workspace
|
||||
|
||||
Existing renderers can convert their layout into the shared model for transactions and retain
|
||||
their own panel chrome. `DropTarget` describes visible body/tab rectangles and whether a group
|
||||
accepts tabs or splits. Supply targets back-to-front, including floating-window layer order.
|
||||
`resolve_drop` returns a tab insertion or side/center placement and its preview rectangle.
|
||||
The frontmost containing group blocks targets underneath even when it rejects a drop.
|
||||
`Workspace<P>` is what an app saves: the layout, the hidden panels with where each one goes back,
|
||||
an optional saved arrangement for Reset, and `locked`.
|
||||
|
||||
The optional `DockArea` renderer handles tab fitting and overflow, drag/drop previews,
|
||||
Escape/focus-loss cancellation, split/accordion dividers and floating-group resize grips. It renders a
|
||||
snapshot and returns `DockOutput.actions`; apply them through the application's command path.
|
||||
With `serde` enabled, `Action` also serializes so pointer, keyboard and control-channel requests
|
||||
can share that command path, including splitter changes, tab reorder and floating bounds.
|
||||
Panel body callbacks receive stable global egui IDs, so moving a panel does not reset its widget
|
||||
memory. The application should still keep durable panel/document data outside transient egui
|
||||
widget memory.
|
||||
| Method | Does |
|
||||
|---|---|
|
||||
| `apply`, `apply_all` | Apply actions all or none, with the app's permissions. Closed panels are recorded in `hidden`. While `locked`, moving, floating and closing are refused. |
|
||||
| `set_visible(panel, visible, fallback, permissions)` | Hide a panel that may close, or show it at its recorded place, else beside `fallback`. |
|
||||
| `reconcile(registered, permissions, default)` | Fit a loaded workspace to the panels the app has now. Unknown panels move to `hidden`, so they come back when registered again. A registered panel that cannot close, such as the canvas, is always shown. |
|
||||
| `reset(default)` | Return to the saved arrangement, or to `default` for a built-in workspace. |
|
||||
| `validate` | Check a loaded workspace before use. |
|
||||
|
||||
`DockStyle` supplies colors, font, spacing and localized action labels. `show_with_limits` also
|
||||
accepts per-panel minimum/maximum sizes. Visible geometry clamps to the available area; a narrow
|
||||
viewport relaxes minima proportionally. Persisted preferred sizes are unchanged by this drawing
|
||||
clamp. A divider gesture produces an explicit resize action.
|
||||
With the `serde` feature, `Workspace`, `Layout` and `Action` serialize. Files without a version
|
||||
are v1 and load unchanged. craft-ui does not choose where files go; the app does.
|
||||
|
||||
Use `begin_drag` with the same area ID to carry an existing tab/header gesture into `DockArea`
|
||||
when an app switches from its default arrangement to a customizable workspace.
|
||||
## Rendering
|
||||
|
||||
Floating groups are egui areas in one viewport. Native child windows, cross-viewport drag
|
||||
transport, OS window ownership and multi-monitor coordinate conversion remain the host's
|
||||
responsibility. The model does not instantiate or reparent native windows.
|
||||
`DockArea::new(id).show_content(ui, &layout, &style, &mut content)` draws a layout snapshot and
|
||||
returns a `DockOutput`. It does not change the layout. The app applies `output.actions` through
|
||||
its own command path, so pointer, keyboard and control commands share one path.
|
||||
|
||||
## Persistence and visibility
|
||||
`DockContent<P>` is the app's adapter. It draws each panel body and gives its label, icon,
|
||||
permissions, size limits, preferred floating size, panel menu and group header. The group header
|
||||
sits at the end of the tab strip; `group_header_width` gets the strip width, so a header that
|
||||
draws its own tabs can size them to the room left. An icon is an image (`icon`), or drawn in code by `paint_icon`, which
|
||||
gets a painter, the icon rect and the tint color and returns true when it painted. Panel bodies keep a stable egui id when they move, so widget memory
|
||||
survives.
|
||||
|
||||
Enable `craft-ui`'s optional `serde` feature to serialize the shared model, or retain an existing
|
||||
schema through an adapter. The serialization feature does not choose a filesystem location or
|
||||
write preferences. Applications validate panel IDs, payload size and schema version before
|
||||
committing loaded state. Bound recursive deserialization/conversion in the app as well as using
|
||||
`Layout::validate`; the validator cannot retroactively protect an unbounded parser.
|
||||
`DockOutput` also has:
|
||||
|
||||
To hide a panel without forgetting its placement, capture `Layout::location`, then close it.
|
||||
Keep the resulting `Location` with the app's visibility state. `restore` uses stable neighbor
|
||||
IDs, restores captured fixed sizing/floating bounds and recreates a previously closed accordion
|
||||
group. If a neighbor was removed, it returns an unchanged layout and `MissingTarget`; choose an
|
||||
explicit fallback such as a default side or remembered floating rectangle. Restoring multiple
|
||||
panels closed from the same group in reverse close order preserves neighbor relationships.
|
||||
- `focused`: the panel the user focused this frame: a clicked tab, a drop, or a press of any
|
||||
pointer button in a panel body (protected panels included) or in the group header,
|
||||
which focuses the group's shown panel. Commands, `raise_panel` and
|
||||
workspace resets never set it; a host that tracks the last focused panel clears it when a reset
|
||||
or command hides, closes or moves that panel.
|
||||
- `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (`maximize_item`) and
|
||||
`DockEvent::ToggleAutoCollapse` and `DockEvent::FlyoutChanged { panel }` (docks): the
|
||||
flyout opened, switched or closed (`None`). It comes once per change, whatever made it: an
|
||||
icon, Escape, a press outside, a raised panel, `open_flyout` or `close_flyout`.
|
||||
- `error`: a rejected gesture.
|
||||
|
||||
## Acceptance
|
||||
Builder options on `DockArea`:
|
||||
|
||||
The shared tests cover lossless moves, tab reorder, stale targets, atomic errors, protected
|
||||
canvases, accordion state, fixed sizing, hidden-panel restoration, bounded malformed layouts,
|
||||
and a deterministic sequence of 800 panel moves. Pointer tests exercise dragging a floating
|
||||
panel into the main tab strip and canceling a drag.
|
||||
| Option | Use |
|
||||
|---|---|
|
||||
| `maximized(panel)` | Maximize Frame: that frame fills the area. |
|
||||
| `hide_panels(HidePanels)` | Hide panels for Tab and Shift+Tab. Protected panels stay. |
|
||||
| `auto_collapse_iconic(on)` | Close a flyout on Escape or a click outside (default on). |
|
||||
| `raise_panel(panel)` | Raise a panel's floating window, or open its flyout, this frame. It moves no keyboard focus and does not set `DockOutput::focused`. |
|
||||
| `blocked_rects(rects)` | App overlays that docking gestures must ignore. |
|
||||
| `float_bounds(rect)` | Where floating windows, flyouts and drag ghosts may go (default: the whole viewport). Pass the viewport below a title bar drawn under a transparent OS title bar, so no floating window sits where a press moves the app window. |
|
||||
|
||||
`tests/docking_workflows.rs` renders a document and populated Layers/Properties/Brushes panels,
|
||||
then uses actual pointer events to merge, detach and redock Brushes. It checks retained values
|
||||
and widget identity at two widths, two display scales and both egui themes. To retain captures:
|
||||
`DockStyle::close_menu_items` and `DockStyle::close_button` hide the built-in Close menu items
|
||||
and the floating window ×. They hide controls only: a panel that stays `closable` still closes
|
||||
by the app's own Close items and commands.
|
||||
|
||||
`DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome (any control a
|
||||
`Hit` names) rather than on a panel body. Focus follows only the user's input: a tab keeps keyboard focus until a command or a
|
||||
workspace reset hides, closes or moves its panel, and then gives it up. A divider or a floating
|
||||
window's resize grip holds focus only while the pointer drags it, so the app's shortcuts and
|
||||
canvas arrow keys work right after; one reached with Tab or F6 keeps its focus, and arrow keys
|
||||
resize it. Hovering focuses nothing. `begin_drag` hands a drag that started in the app's own chrome to the area.
|
||||
`docking::chrome` has the floating frame, the title bar and `drop_preview` (the drop preview
|
||||
docking and `craft_ui::panes` both draw) for apps that draw their own windows.
|
||||
|
||||
## Tab strips
|
||||
|
||||
Every shown tab carries its panel's full name. Tabs that do not fit go to the "…" button at the
|
||||
end of the strip, whose menu lists the hidden panels; choosing one makes it active. The active tab
|
||||
is always shown, in its logical place: when it lies past the tabs that fit, it takes the place of
|
||||
the last of them. Only an active tab wider than the room beside the "…" button, or a lone tab
|
||||
wider than the strip, is cut with "…", and its tooltip names it in full. The drag bar always keeps
|
||||
its reserved width: tabs go to the overflow menu before it narrows, and only a strip narrower than
|
||||
the bar itself shrinks it. A tab dropped on the "…" button goes to the end of the group.
|
||||
|
||||
## Floating size
|
||||
|
||||
A panel or group floated by a drag, a menu or a command without a rect takes its content height:
|
||||
the title bar, the tab strip and the height the active panel's content used when it was last
|
||||
drawn (the content ui's `min_rect`), at least 120 points. The most it takes is the height of
|
||||
`DockContent::floating_size`, or 320 points for a panel leaving a dock or frame and a group
|
||||
leaving a dock. A short panel therefore floats as a short window. Content that reaches the bottom
|
||||
of its body (a panel that allocates its whole rect) has no height of its own: it floats at the
|
||||
`floating_size` height, else at 320 points. A panel's width is its `floating_size` width, else
|
||||
its docked width; a group keeps its docked width.
|
||||
A flyout fits its content the same way, without the title bar.
|
||||
|
||||
- A panel the area has not drawn floats at the `floating_size` height, else the docked height
|
||||
capped at 320, or at a `FloatSpace::with_panel_size` size for commands.
|
||||
- A group from a frame without a `floating_size` keeps its frame size. A dock column of several
|
||||
groups floats at the tallest `floating_size` height, else its column height capped at 320.
|
||||
- A rect from a command and a window the user resized keep their size; floating windows are not
|
||||
refitted while open.
|
||||
- Docked layout does not change: a column's last group still fills the column.
|
||||
|
||||
## Gestures
|
||||
|
||||
- A tab drags one panel. A group's drag bar (the space beside its tabs) or its top border drags
|
||||
the whole group. A column bar drags a column. A floating window's title bar drags the window;
|
||||
with `title_bar_docks` a release over a target docks the whole window there, else it only
|
||||
moves.
|
||||
- Inside a floating window, tabs and drag bars drag and dock as they do in the docked layout,
|
||||
into any window. Its groups split, join and resize like frames, with dividers and four-way
|
||||
handles (`Divider::WindowSplit` and `Divider::WindowIntersection`, named by the window's first
|
||||
panel). Double-clicking the title bar minimizes the window to its title bar, or to the tab strip
|
||||
of its only group; so does double-clicking that group's strip. The group menu's float item
|
||||
floats one group of a window that has several. Closing the window closes its panels; each
|
||||
reopens where it was while the window or its neighbour in it is open, else in a window at the
|
||||
window's last rect.
|
||||
- A movable floating window resizes from every edge and corner. The top edge and corners are a
|
||||
4 pt band above the title bar (`chrome::RESIZE_BAND`), so they take no moves and no clicks on
|
||||
the title bar's buttons. A resize keeps the opposite edges in place and stays within the size
|
||||
limits and the screen. A focused resize handle moves its edge 8 pt per arrow key.
|
||||
- Over a frame, the tab strip and the middle join its tabs, and the nearest side splits it. The
|
||||
side zones are trapezoids along the four edges of the body below the tab strip, like a picture
|
||||
frame, all four the same depth: `DockStyle::zone_depth` (40 pt), or a quarter of the body's
|
||||
smaller side when that is less, so every frame keeps a center. A split that would leave either half without
|
||||
`DockStyle::min_pane` joins the frame's tabs instead. The gap between two frames is no target.
|
||||
- The outer edge band (`DockStyle::edge_band`) takes a drop as a new frame across the whole
|
||||
window side: top and bottom, and left and right with `side_edge_zones`. It takes a quarter of
|
||||
the window and is offered only when every frame keeps its minimum. Past the band, a frame's own
|
||||
side zones apply.
|
||||
- A dragged divider grows the frames that touch it on one side, up to their maximums. On the
|
||||
other side the frame touching it shrinks to its minimum, then the next frame along the same
|
||||
axis, and so on: the divider stops when every frame on that side is at its minimum. Frames
|
||||
side by side across the axis shrink together, and the next frame gives way once one of them
|
||||
is at its minimum. The line of frames ends at a split across the axis or at a dock; every
|
||||
other frame keeps its size. Dividers between stacked panels and between the groups of a dock
|
||||
column work the same way. Where a divider ends on another divider, a four-way handle
|
||||
(`Divider::Intersection`) moves both.
|
||||
- Every frame has the same minimum, `DockStyle::min_pane` (plus its tab strip), unless its panels
|
||||
ask for more through `PanelLimits::min`. Frames have no maximum unless every panel in them asks
|
||||
for one through `PanelLimits::max`: a panel without a maximum lifts the maximum of the panels it
|
||||
joins.
|
||||
- Drop previews show the destination: an outline for tabs, a line for a new group, column or dock,
|
||||
a filled half for a split. With `side_edge_zones`, a drag over a group instead outlines each of
|
||||
its zones that a drop would change something in (the side trapezoids, the center rectangle and
|
||||
the tab strip; `zone_shape` gives the outlines) and fills the zone under the pointer. Sides the
|
||||
group does not take, by its permissions or because a split leaves no room, are not drawn; nor is
|
||||
the center of the group a tab comes from. Escape or losing window focus cancels
|
||||
a drag.
|
||||
- With `float_on_empty_drop`, a release over no target floats what moves at the pointer, such
|
||||
as a panel dropped on a protected canvas. Without it, that release cancels the drag and
|
||||
nothing moves: the gap between two groups, a menu bar or a status bar is no target. A release
|
||||
outside the app window floats in both cases.
|
||||
- Ctrl (⌘ on macOS) held at the drop floats it wherever it lands. With `command_press_floats`,
|
||||
the key held when a tab drag of a frame starts is enough. With `float_hint`, a hint under the
|
||||
pointer names the modifier while a drag offers a docking target: `float_hint_label`, where
|
||||
`{key}` becomes ⌘ or Ctrl.
|
||||
- Double-click a tab or drag bar to minimize a group to its strip.
|
||||
- Right-click a tab for its menu, or a drag bar for the group menu; Enter or Space on a focused
|
||||
drag bar opens it too. A left click on the drag bar only focuses it.
|
||||
- With `DockStyle::wheel_selects_tabs`, the mouse wheel over a tab strip selects the next or
|
||||
previous tab. With `middle_click_closes_tabs`, a middle click on a closable panel's tab closes
|
||||
it.
|
||||
- A column's »/« button collapses it to icons, one icon per panel with a separator between groups.
|
||||
Widen an iconic column to show panel names. Click an icon to open its group as a flyout on the
|
||||
canvas side. Drag an icon to move its panel, or an icon group's top edge (the separator line above it) to move the group.
|
||||
|
||||
## Commands
|
||||
|
||||
With the `serde` feature, `DockCommand<P>` is the shared control vocabulary. The app puts the
|
||||
command id under `"command"` in the params and deserializes them. craft-ui has no `serde_json`
|
||||
dependency.
|
||||
|
||||
```rust,ignore
|
||||
let mut params = params.clone();
|
||||
params["command"] = json!(id);
|
||||
let command: DockCommand<PanelId> = serde_json::from_value(params)?;
|
||||
if command.is_app_owned() {
|
||||
return app.workspace_command(command);
|
||||
}
|
||||
let space = float_space(ctx, DOCK_ID).unwrap_or_else(|| FloatSpace::new(ctx.content_rect()));
|
||||
let closed = command.apply(&mut app.workspace, style.right_to_left, &space, |panel| app.permissions(panel))?;
|
||||
```
|
||||
|
||||
| Id | Params (`?` is optional) |
|
||||
|---|---|
|
||||
| `window.panel.layout` | `{action}`: a serialized `Action` |
|
||||
| `window.panel.move` | `{panel, anchor, zone?, before?, group?, placement?}` |
|
||||
| `window.panel.float` | `{panel, x?, y?, width?, height?, group?, column?}` |
|
||||
| `window.panel.dock` | `{panel, anchor?, zone?, before?, group?, column?, side?}` |
|
||||
| `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` |
|
||||
| `window.panel.minimize` | `{panel, minimized?}` |
|
||||
| `window.panel.iconic` | `{panel, iconic?}` |
|
||||
| `window.panel.window` | `{panel, native?}` |
|
||||
| `window.workspace`, `.new`, `.delete` | `{name}` |
|
||||
| `window.workspace.reset`, `ui.dock.reset` | `{}` |
|
||||
| `window.workspace.lock` | `{locked?}` |
|
||||
| `ui.dock` | `{action}`, or `{operation, …}` |
|
||||
|
||||
- `zone` is `tab`, `center`, `left`, `right`, `top`, `bottom`, `above` or `below`. `before` names
|
||||
the tab to insert before; `null` appends. `left`, `right`, `top` and `bottom` follow
|
||||
`Placement::for_zone`, so beside a docked panel they make a new column or group. `apply` and
|
||||
`to_actions` take the layout's `right_to_left` for that.
|
||||
- `group` moves the panel's whole group; `column` moves its dock column, or its whole window when
|
||||
it floats. `side` is `Start` or `End`: what moves becomes a new last column of that dock, or
|
||||
a new dock; when it already is that dock's last column, the command does nothing.
|
||||
- `window.panel.dock` with `left`, `right`, `top` or `bottom` and no `anchor` or `side` makes a
|
||||
new frame on that outer edge (`Placement::Edge`). A hidden panel is shown first.
|
||||
- `window.panel.float` without a rect floats what it moves at the size a drag floats it at (see
|
||||
Floating size). It goes
|
||||
inside the dock area, 24 points from its top-left corner, so it stays clear of the menu bar.
|
||||
The area records that geometry in a `FloatSpace` each frame; `float_space(ctx, id)` reads it
|
||||
and `apply` and `to_actions` take it. Before the area has drawn, `FloatSpace::new(area)` floats
|
||||
a panel at 260x320 and a group or column at its column width by 320.
|
||||
`FloatSpace::with_panel_size(panel, size)` gives a panel the area has not drawn (a hidden
|
||||
panel, a headless run) the host's own size; a size the area recorded wins. `x`, `y`, `width` and
|
||||
`height` replace the matching values, and a group or column that is already a whole floating
|
||||
window keeps its rect.
|
||||
- Without a value, `minimized`, `iconic` and `locked` toggle.
|
||||
- `ui.dock` operations are those of LightCraft, PDFCraft, CADCraft and SoundCraft: `open`,
|
||||
`close`, `activate`, `float {rect}`, `moveFloating {rect}`, `move {target, zone?, before?}`,
|
||||
`setStackOpen {open}`, `resizeStack {height}` and `resizeSplit {path, size}`. `rect` is
|
||||
`[x, y, width, height]`.
|
||||
|
||||
`to_actions` returns the actions a command makes without applying them. `apply` applies them all
|
||||
or none and returns the panels it closed, so the app can release their state. Showing a hidden
|
||||
panel and Lock change the workspace directly. Named workspaces and Reset belong to the app:
|
||||
`is_app_owned` is true for them and `apply` refuses them. `DockCommand::IDS` lists every id for
|
||||
the app's command registry. App-specific aliases stay in the app.
|
||||
|
||||
## Labels
|
||||
|
||||
Every visible and accessibility label is a `*_label` field of `DockStyle`, with an English
|
||||
default: title case for menu items, sentence case for names only screen readers announce. `DockStyle::localized` sets them all from one keyed lookup:
|
||||
|
||||
```rust,ignore
|
||||
let style = DockStyle::from_ui(ui).localized(|key| app.strings.get(key).cloned());
|
||||
```
|
||||
|
||||
Keys are `dock.close`, `dock.float`, `dock.collapseToIcons` and so on; the rustdoc of `localized`
|
||||
lists them all. `DockContent::label` and `action_label` can shape panel and action text further;
|
||||
the logical label stays the accessibility name.
|
||||
|
||||
## Testing
|
||||
|
||||
`DockArea::hit_rects(ctx, id)` lists every gesture source drawn last frame as a `Hit` with its
|
||||
rect: tabs, drag bars, borders, column bars, »/« buttons, title bars, close buttons, icons, icon
|
||||
grips, resize edges and dividers. It is always compiled, so an app can return it from a
|
||||
`ui.docking` control method next to the layout and the focused panel.
|
||||
|
||||
`DockArea::hit_id(id, &hit)` is the egui widget id of a control, for tests and automation that
|
||||
focus it or read its response. `DockArea::floating_layer(id, &window)` is a floating window's
|
||||
egui layer: compare its place in `memory.layer_ids()` with another layer to tell whether the
|
||||
window covers it, and read its rect with `memory.area_rect(layer.id)`. A window the area does not
|
||||
draw (its panels hidden, or a frame maximized) keeps its last rect there, so check
|
||||
`memory.areas().is_visible(&layer)` first.
|
||||
|
||||
The `testing` feature adds `docking::testing::DockDriver`. It runs a `DockArea` in a headless
|
||||
egui context with real pointer and key events, and applies the actions each frame emits.
|
||||
|
||||
```rust,ignore
|
||||
let mut driver = DockDriver::new(app_layout(), Panels::default());
|
||||
let bar = driver.hit(&Hit::DragBar(PanelId::Layers)).unwrap();
|
||||
driver.drag(bar.center(), egui::pos2(2.0, 300.0));
|
||||
driver.settle();
|
||||
assert!(driver.hit(&Hit::ColumnBar(PanelId::Layers)).is_some());
|
||||
```
|
||||
|
||||
It also has `press`, `release`, `click`, `hold`, `key`, `focus`, `hits`, and checks for painted
|
||||
previews (`filled`, `outlined`).
|
||||
|
||||
craft-ui's own tests in `crates/ui/tests/docking_workflows.rs`:
|
||||
|
||||
- Load every app's v1 layout fixture, dock groups into a new dock, a bottom band and a seam,
|
||||
collapse and expand the column, float it by command and drag it back, then check the layout
|
||||
reads back as written.
|
||||
- Render Layers, Properties and Brushes panels with real content, and merge, detach and redock
|
||||
Brushes by pointer at two widths, two scales and both themes. Set `CRAFT_UI_DOCK_VISUAL_DIR`
|
||||
to keep the captures:
|
||||
|
||||
```sh
|
||||
CRAFT_UI_DOCK_VISUAL_DIR=/absolute/output/path cargo test -p craft-ui --test docking_workflows --all-features
|
||||
```
|
||||
|
||||
These are offscreen egui checks. An adopting application still needs command, content, workspace
|
||||
reload, theme and input tests using its own renderer and persistence adapter.
|
||||
An adopting app still tests its own commands, contents, saved workspaces and themes.
|
||||
|
||||
## Application chrome and activation
|
||||
## What stays in the app
|
||||
|
||||
`DockArea::show_customized` accepts one mutable `DockContent<P>` adapter, with body,
|
||||
panel-menu, group-header and label methods. Apps queue commands in these callbacks and
|
||||
apply them after rendering the readonly snapshot. `group_header_width` reserves a bounded
|
||||
trailing portion of the existing tab strip; its child UI is clipped to that region.
|
||||
Collapsed accordion entries still have panel menus; collapsing tab groups is host policy.
|
||||
|
||||
`label` returns `WidgetText`, including an application-shaped galley, used for tab width,
|
||||
painting and menu labels. The separate logical label callback supplies tab accessibility
|
||||
text. `action_label` independently shapes the localized stock Float/Move/Close menu
|
||||
text without receiving a panel identity. Its default returns unchanged logical `WidgetText`;
|
||||
custom visual text never replaces the action's logical accessibility label. Panel targets
|
||||
and overflow entries continue to use `label`. Original `show` and `show_with_limits` call
|
||||
sites remain supported.
|
||||
|
||||
Apply `Action::Activate` in the host, then use `DockArea::raise_panel(panel)` on the next
|
||||
frame to raise the owning in-viewport floating layer and focus the panel tab. This request
|
||||
does not mutate the serialized layout or persist z-order. Floating area identity still
|
||||
derives from the first panel; native-window identity remains host-owned.
|
||||
|
||||
Floating groups have a distinct 12-point grip in the existing tab strip. Moving it emits
|
||||
`MoveFloating` for the whole group; dragging an individual tab detaches just that panel.
|
||||
`DockOutput::group_drag` and `group_drop` expose the group identity and release position
|
||||
for app-owned atomic group docking policies. Escape/lost focus restores the group's
|
||||
starting rectangle. No generic group docking or app command registry is inferred.
|
||||
|
||||
Hosts supply overlay rectangles via `blocked_rects` before showing the surface. These
|
||||
block drop previews, release actions and float fallback at the pointer, including overlays
|
||||
appearing mid-drag. Hosts must provide current overlay geometry or cancel docking when
|
||||
modal state prevents interaction; later-drawn overlays cannot be discovered retroactively.
|
||||
|
||||
`DockArea::chrome_has_focus(ctx, layout)` classifies focus on rendered dock tabs,
|
||||
collapse buttons, overflow, split/stack dividers, floating resize corners and group
|
||||
grips. It excludes panel content and custom header/menu widgets and rejects invalid
|
||||
layouts. Hosts can permit global commands from chrome while reserving Enter, Space,
|
||||
Tab, Escape and arrow keys for activation, traversal, cancellation and resizing.
|
||||
Content widgets retain their usual keyboard ownership. The renderer owns the IDs;
|
||||
hosts do not need to reconstruct them.
|
||||
- The panel registry, panel contents and document state.
|
||||
- Named workspaces, Reset, and when and where layouts are saved.
|
||||
- Menus and key bindings outside the docking chrome.
|
||||
- Native window ownership on platforms without egui viewports.
|
||||
@@ -0,0 +1,113 @@
|
||||
# Task panes
|
||||
|
||||
`craft_ui::panes` draws task panes around an app's own document: Navigation, Styles, Comments,
|
||||
Format Shape and the like. Each pane is an egui side or bottom panel, or a floating frame. The
|
||||
document stays the app's `CentralPanel`.
|
||||
|
||||
## Panes or docking
|
||||
|
||||
| Use | When |
|
||||
|---|---|
|
||||
| `panes` | Office-style apps (WordCraft, DeckCraft, GridCraft). A few panes at the sides of a document the app draws itself; the app's commands own which panes are open. |
|
||||
| `docking` | Creative apps whose whole window is panels: tab groups, splits, stacked groups, workspaces, a protected canvas panel. See [ui-docking.md](ui-docking.md). |
|
||||
| plain egui panels | Fixed view parts: slide thumbnails, notes, formula bar, sheet tabs, status bar. |
|
||||
| `egui::Window` | Free tool windows that never dock (Read Aloud, Power Query). |
|
||||
|
||||
`panes` needs no docking types; it uses only the docking chrome (`FloatingFrame`, `TitleBar`,
|
||||
`live_move`).
|
||||
|
||||
## API
|
||||
|
||||
```rust
|
||||
use craft_ui::panes::{Edge, PaneContent, PaneHost, PaneRequest, PaneState, Place, SidePolicy};
|
||||
|
||||
impl PaneContent<Pane> for MyPanes<'_> {
|
||||
fn title(&self, pane: &Pane) -> String { tr(pane.title()) }
|
||||
fn body(&mut self, ui: &mut egui::Ui, pane: &Pane) { /* the pane's contents */ }
|
||||
fn default_state(&self, pane: &Pane) -> PaneState { PaneState::docked(Edge::End, 250.0) }
|
||||
// Optional: size_range (200..=520), movable, closable, menu (app items in the ▾ menu).
|
||||
}
|
||||
|
||||
// Every frame, after the top and bottom bars and before the CentralPanel:
|
||||
let out = PaneHost::new("task-panes")
|
||||
.rtl(ui_is_rtl)
|
||||
.policy(SidePolicy::Columns)
|
||||
.show(ui, &open_panes, |pane| prefs.pane_state(pane), &mut MyPanes { app });
|
||||
for request in out.requests {
|
||||
match request {
|
||||
PaneRequest::Close(pane) => app.run(pane.close_command()),
|
||||
PaneRequest::Place(pane, place) => prefs.set_place(pane, place),
|
||||
PaneRequest::Resize(pane, size) => prefs.set_size(pane, size),
|
||||
PaneRequest::FloatRect(pane, rect) => prefs.set_float_rect(pane, rect),
|
||||
PaneRequest::Focus(_) => {}
|
||||
}
|
||||
}
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
let response = document(ui);
|
||||
if out.to_document {
|
||||
// F6 or Shift+F6 left the panes: the document takes keyboard focus.
|
||||
response.request_focus();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
| Piece | Behavior |
|
||||
|---|---|
|
||||
| `Edge::{Start, End, Bottom}` | Logical edges. `Start` is left, or right with `.rtl(true)`. |
|
||||
| `SidePolicy::Columns` | Every docked pane shows; panes on one edge sit side by side in `open` order, the first outermost. |
|
||||
| `SidePolicy::OneSlot` | One closable pane per edge: the last one in `open`. Non-closable context panes (PivotTable Fields) show beside the slot. |
|
||||
| `.max_fraction(f)` | One docked pane takes at most `f` of the host's width (height for bottom panes). |
|
||||
| Chrome | Title, ▾ menu (app items, Move to Start, Move to End, Move to Bottom for bottom panes, Float, Close), ×, a resize edge with pointer and arrow keys. The title bar mirrors with `.rtl(true)`. Its accessible name is `PaneLabels::move_pane` with `{title}` replaced by the pane's title ("Move Styles pane"). |
|
||||
| Size | A docked pane reserves exactly its size and clips its body, so a body wider than the pane never pushes into the document. |
|
||||
| Drag out | A docked pane's title dragged more than `DOCK_SNAP` (32 pt) out of the pane floats it under the pointer when dropped; dropped within 32 pt of the host's left or right edge it docks there. |
|
||||
| Floating | `FloatingFrame` with its resize handles; the title bar moves it. Escape or window focus loss during a move puts it back. A drop within 32 pt of the left or right edge docks it. Rects are clamped to the host area. |
|
||||
| Focus | `out.focused` is the pane holding keyboard focus or last clicked; a click or focus in the document clears it. F6 and Shift+F6 cycle through the shown panes and then report `out.to_document`: give focus to the document. `.f6(false)` leaves F6 to the app, which calls `panes::focus_next(ctx, id, reverse)` instead. |
|
||||
|
||||
State:
|
||||
|
||||
- The host never stores which panes are open and never writes files.
|
||||
- `states` returns the app's saved `PaneState` (place, size, float rect; serde with the `serde`
|
||||
feature). Return `None` to let the host keep the state in egui memory for the session, as
|
||||
egui panels keep widths today.
|
||||
- Apply `Resize` and `FloatRect` as they come: they arrive every frame of a gesture, and an
|
||||
Escape sends the start rect back.
|
||||
- `panes::float_rect` brings a saved rect back inside the window, whatever the file says.
|
||||
|
||||
## Adoption
|
||||
|
||||
### WordCraft (`Columns`)
|
||||
|
||||
- Add a `Pane` enum for the nine panes and implement `PaneContent` by calling the existing
|
||||
bodies; drop their `header()` calls, since the host draws the title and ×.
|
||||
- Build `open` each frame from the `ViewState` flags, in today's order: SmartArt Text Pane (only
|
||||
while SmartArt is selected), Navigation and Clipboard at `Start`; Styles, Style Inspector,
|
||||
Accessibility, Alt Text, Restrict Editing and Comments at `End`. Default widths as today.
|
||||
- `Close(p)` runs the pane's existing command (`view.navigationPane {value: false}`, …). Command
|
||||
ids and `nav_pane` in `ui.json` stay as they are.
|
||||
- Styles takes #2584's behavior through the host: map `StylesPaneDock::{Left, Right, Floating}`
|
||||
to `Place` (`Left` is `Docked(Start)` in left-to-right interfaces), run `view.stylesPaneDock`
|
||||
on `Place`, keep the float rect in UI prefs. #2584's own drag, snap and `float_rect` code goes.
|
||||
- Other panes return `None` from `states`; their widths stay session-only, as now.
|
||||
- Pane title bars are focusable. Check that Tab in the canvas still stays in the document, so
|
||||
panes stay off its keyboard focus. Use `.f6(false)` if F6 is bound elsewhere.
|
||||
|
||||
### DeckCraft (`OneSlot`)
|
||||
|
||||
- `open` is `ui.pane` (one entry) at `End`; `states` returns `PaneState::docked(Edge::End,
|
||||
pane_width)`; `Resize` writes `pane_width`; `Close` clears `ui.pane` as the × does today.
|
||||
`size_range` is 240..=520. The `ui.json` fields stay.
|
||||
- Format, Animation and Selection return `movable = true`; the rest `false`. Saving their place
|
||||
needs new optional `ui.json` fields (`#[serde(default)]`).
|
||||
- Thumbnails, outline, notes and the #835 canvas shell stay plain panels.
|
||||
- F6 from the host closes the ui-parity F6 gap.
|
||||
|
||||
### GridCraft (`OneSlot`, `.max_fraction(0.5)`)
|
||||
|
||||
- `open` is the task slot pane (`grid.pane`, or "comments" while `session.comments_pane`) plus
|
||||
PivotTable Fields while the active cell is in a pivot. PivotTable Fields returns
|
||||
`closable = false` and `movable = false`, so it stays beside the slot.
|
||||
- `Close("comments")` runs `review.showComments {on: false}`; agents still drive it through the
|
||||
engine.
|
||||
- No pane prefs today: return `None` from `states`.
|
||||
- Code Editor (#1193) and Queries & Connections (#1203) become slot panes. The formula bar,
|
||||
sheet tabs and status bar stay plain panels.
|
||||
Reference in new issue
Block a user