Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Let dock tabs be dragged to reorder within their group (#2272) (#2774)

Fabio Lussi37cb99eb1f8c
diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs
index 2f9d32ce7..00c483b93 100644
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@ -3,8 +3,9 @@
//! A group's height never follows its content: content taller than the group scrolls inside
//! it. The last expanded group (Layers by default) fills what the others leave. Drag the gap
//! between two groups to resize them, double-click a tab (or use the panel menu) to collapse a
-//! group to its tab strip, and drag a tab strip to move the group up or down the column
-//! (unless Window › Workspace › Lock Workspace is on).
+//! group to its tab strip, drag a tab strip (outside its tabs, or a tab dragged off the strip) to
+//! move the group up or down the column, and drag a tab along its strip to reorder the group's
+//! tabs (#2272); Window › Workspace › Lock Workspace stops all three moves.
//!
//! The layout is [`DockLayout`] in `UiState::dock` (serialisable, drivable with `ui.set`), saved
//! with Window › Workspace › New Workspace…, reset by Reset Workspace, and remembered across
@@ -168,6 +169,23 @@ pub struct DockLayout {
/// Names of tabs hidden by Close (not positions: Color/Swatches swap with the theme).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub hidden_tabs: BTreeMap<Group, Vec<String>>,
+ /// Tab order per group, left to right, by name like `hidden_tabs` (#2272). A group missing
+ /// here keeps its default order; unknown names are ignored and tabs missing from a list
+ /// follow it in their default order. Anything unreadable falls back to the defaults.
+ #[serde(rename = "tabOrder", alias = "tab_order", deserialize_with = "lenient_tab_order")]
+ pub tab_order: BTreeMap<Group, Vec<String>>,
+}
+
+/// Read `tabOrder` keeping what makes sense: unknown groups, non-list values and non-string names
+/// are dropped instead of failing the whole saved layout.
+fn lenient_tab_order<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<Group, Vec<String>>, D::Error> {
+ let v = Value::deserialize(d)?;
+ let mut out = BTreeMap::new();
+ for (k, names) in v.as_object().into_iter().flatten() {
+ let (Some(g), Some(names)) = (Group::from_key(k), names.as_array()) else { continue };
+ out.insert(g, names.iter().filter_map(Value::as_str).take(16).map(str::to_owned).collect());
+ }
+ Ok(out)
}
/// Gap between groups; it is also the splitter's grab area.
@@ -176,10 +194,49 @@ pub const GAP: f32 = 6.0;
const MAX_HEIGHT: f32 = 4000.0;
impl DockLayout {
- /// Visible tabs, retaining their original indices for commands and panel bodies.
+ /// Every tab of `group` in the user's order (#2272), with its original index (the one
+ /// `dockTabs`, commands and panel bodies use).
+ pub fn ordered_tabs(&self, group: Group, pro: bool) -> Vec<(usize, &'static str)> {
+ let all: Vec<(usize, &'static str)> = group.tabs(pro).iter().copied().enumerate().collect();
+ let mut out: Vec<(usize, &'static str)> = Vec::with_capacity(all.len());
+ for name in self.tab_order.get(&group).into_iter().flatten() {
+ if let Some(&tab) = all.iter().find(|(_, n)| *n == name.as_str())
+ && !out.contains(&tab)
+ {
+ out.push(tab);
+ }
+ }
+ for tab in all {
+ if !out.contains(&tab) {
+ out.push(tab);
+ }
+ }
+ out
+ }
+
+ /// Visible tabs in display order, retaining their original indices for commands and panel
+ /// bodies.
pub fn visible_tabs(&self, group: Group, pro: bool) -> Vec<(usize, &'static str)> {
let hidden = self.hidden_tabs.get(&group);
- group.tabs(pro).iter().copied().enumerate().filter(|(_, name)| !hidden.is_some_and(|xs| xs.iter().any(|x| x.as_str() == *name))).collect()
+ self.ordered_tabs(group, pro).into_iter().filter(|(_, name)| !hidden.is_some_and(|xs| xs.iter().any(|x| x.as_str() == *name))).collect()
+ }
+
+ /// Move tab `tab` (an original index) of `group` so it is drawn just before tab `before`
+ /// (or last when `None` or not a tab of the group). The default order is stored as no entry.
+ pub fn move_tab(&mut self, group: Group, tab: usize, before: Option<usize>, pro: bool) {
+ if before == Some(tab) {
+ return;
+ }
+ let mut order = self.ordered_tabs(group, pro);
+ let Some(at) = order.iter().position(|(i, _)| *i == tab) else { return };
+ let moved = order.remove(at);
+ let to = before.and_then(|b| order.iter().position(|(i, _)| *i == b)).unwrap_or(order.len());
+ order.insert(to, moved);
+ if order.iter().map(|(i, _)| *i).eq(0..order.len()) {
+ self.tab_order.remove(&group);
+ } else {
+ self.tab_order.insert(group, order.into_iter().map(|(_, n)| n.to_owned()).collect());
+ }
}
/// Hide one tab; it can be reopened through Window › Panel.
@@ -354,6 +411,7 @@ enum Action {
Close(Group),
CloseTab(Group, usize),
Move(Group, Option<Group>),
+ MoveTab(Group, usize, Option<usize>),
}
/// Rects of the groups drawn last frame (screen points), for tests and automation.
@@ -412,7 +470,7 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
let indices: Vec<usize> = visible.iter().map(|(i, _)| *i).collect();
let tabs: Vec<&str> = visible.iter().map(|(_, name)| *name).collect();
let mut sel = indices.iter().position(|i| *i == before).unwrap_or(0);
- let resp = widgets::card_ex(&mut child, g.key(), &tabs, &mut sel, collapsed, |ui, shown_tab| {
+ let resp = widgets::card_ex(&mut child, g.key(), &tabs, &mut sel, collapsed, !locked, |ui, shown_tab| {
let Some(&tab) = indices.get(shown_tab) else { return };
let inner = ui.available_height().max(0.0);
if g.scrolls_itself(tab) {
@@ -455,12 +513,20 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
if resp.strip.double_clicked() || resp.tab_double_clicked || (collapsed && resp.tab_clicked) {
actions.push(Action::ToggleCollapse(g));
}
- if !locked && resp.strip.dragged() {
+ // The strip uses visible indices; reorder in original ones.
+ if !locked
+ && let Some((from, before)) = resp.tab_reorder
+ && let Some(&tab) = indices.get(from)
+ {
+ actions.push(Action::MoveTab(g, tab, before.and_then(|b| indices.get(b).copied())));
+ }
+ // A tab dragged off its strip moves the whole group, as the strip itself does.
+ if !locked && (resp.strip.dragged() || resp.tab_dragging_out) {
dragging = Some(g);
}
if !locked
- && resp.strip.drag_stopped()
- && let Some(p) = ui.ctx().pointer_interact_pos()
+ && (resp.strip.drag_stopped() || resp.tab_dropped_out)
+ && let Some(p) = ui.ctx().pointer_interact_pos().or_else(|| ui.ctx().pointer_latest_pos())
{
actions.push(Action::Move(g, drop_before(&order, &rects, g, p.y)));
}
@@ -532,18 +598,21 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
}
Action::Close(g) => *g.shown_mut(&mut app.ui.panels) = false,
Action::CloseTab(g, tab) => {
+ let shown_before = app.ui.dock.visible_tabs(g, t.pro);
app.ui.dock.hide_tab(g, tab, t.pro);
let remaining = app.ui.dock.visible_tabs(g, t.pro);
if remaining.is_empty() {
*g.shown_mut(&mut app.ui.panels) = false;
} else if *g.tab_mut(&mut app.ui.dock_tabs) == tab {
- // Prefer the next tab, or the previous one when closing the last.
- let next = remaining.iter().find(|(i, _)| *i > tab).or_else(|| remaining.last());
+ // Prefer the next tab on the strip, or the previous one when closing the last.
+ let at = shown_before.iter().position(|(i, _)| *i == tab).unwrap_or(0);
+ let next = shown_before.iter().skip(at + 1).find(|x| remaining.contains(x)).or_else(|| remaining.last());
if let Some(&(next, _)) = next {
*g.tab_mut(&mut app.ui.dock_tabs) = next;
}
}
}
+ Action::MoveTab(g, tab, before) => app.ui.dock.move_tab(g, tab, before, t.pro),
Action::Move(g, before) => {
if before != Some(g) {
app.ui.dock.move_group(g, before);
diff --git a/crates/ui-egui/src/dock_tests.rs b/crates/ui-egui/src/dock_tests.rs
index 30e02c5db..94c333111 100644
--- a/crates/ui-egui/src/dock_tests.rs
+++ b/crates/ui-egui/src/dock_tests.rs
@@ -706,7 +706,7 @@ fn tab_strips_never_overlap_the_menu_button() {
return;
}
let mut s = sel;
- let r = crate::widgets::card_ex(ui, "t", tabs, &mut s, false, |ui, _| {
+ let r = crate::widgets::card_ex(ui, "t", tabs, &mut s, false, false, |ui, _| {
ui.label("body");
});
*out = Some((r.tabs, r.menu.rect, r.chevron, ui.max_rect()));
@@ -773,7 +773,7 @@ fn dock_strips_fit_and_the_chevron_menu_switches_tabs() {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
- let _ = crate::widgets::card_ex(ui, "color", &["Color", "Swatches", "Gradients", "Patterns"], sel, false, |ui, _| {
+ let _ = crate::widgets::card_ex(ui, "color", &["Color", "Swatches", "Gradients", "Patterns"], sel, false, false, |ui, _| {
ui.label("body");
});
},
@@ -820,3 +820,144 @@ fn tab_hides_all_panels_and_shift_tab_only_the_dock() {
v.as_object_mut().unwrap().remove("dock");
assert!(serde_json::from_value::<crate::state::Panels>(v).unwrap().dock);
}
+
+fn strip_tabs(h: &Harness<'static, PhotocraftApp>, g: Group) -> Vec<(usize, Rect)> {
+ last_strips(&h.ctx).into_iter().find(|s| s.group == g).map(|s| s.tabs).unwrap_or_else(|| panic!("{g:?} strip not drawn"))
+}
+
+fn tab_rect(h: &Harness<'static, PhotocraftApp>, g: Group, tab: usize) -> Rect {
+ strip_tabs(h, g).into_iter().find(|(i, _)| *i == tab).map(|(_, r)| r).unwrap_or_else(|| panic!("{g:?} tab {tab} not on the strip"))
+}
+
+fn click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) {
+ h.event(egui::Event::PointerMoved(p));
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
+ h.step();
+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+ h.run_steps(3);
+}
+
+#[test]
+fn move_tab_reorders_by_name_and_bad_saved_orders_fall_back() {
+ let mut l = DockLayout::default();
+ let names = |l: &DockLayout, g, pro| l.visible_tabs(g, pro).into_iter().map(|(_, n)| n).collect::<Vec<_>>();
+ l.move_tab(Group::Layers, 2, Some(0), true);
+ assert_eq!(l.visible_tabs(Group::Layers, true), vec![(2, "Paths"), (0, "Layers"), (1, "Channels")]);
+ l.move_tab(Group::Layers, 2, None, true);
+ assert_eq!(names(&l, Group::Layers, true), ["Layers", "Channels", "Paths"]);
+ assert!(l.tab_order.is_empty(), "the default order is stored as nothing");
+ // Out-of-range tabs and moves onto themselves change nothing; an unknown `before` is last.
+ for (tab, before) in [(9, Some(0)), (usize::MAX, None), (1, Some(1)), (2, Some(9))] {
+ let mut m = l.clone();
+ m.move_tab(Group::Layers, tab, before, true);
+ assert_eq!(names(&m, Group::Layers, true), ["Layers", "Channels", "Paths"], "{tab} {before:?}");
+ }
+ // Names, not positions: the order survives the Pro/Studio swap of Color and Swatches.
+ l.move_tab(Group::Color, 3, Some(0), true);
+ assert_eq!(names(&l, Group::Color, true), ["Patterns", "Color", "Swatches", "Gradients"]);
+ assert_eq!(names(&l, Group::Color, false), ["Patterns", "Color", "Swatches", "Gradients"]);
+ // Hidden tabs keep their place for when they come back.
+ l.hide_tab(Group::Color, 1, true);
+ assert_eq!(names(&l, Group::Color, true), ["Patterns", "Color", "Gradients"]);
+ // Garbage in a saved layout falls back per group, and never loses the rest of the layout.
+ for bad in [
+ json!(5),
+ json!("x"),
+ json!(null),
+ json!({"layers": "paths"}),
+ json!({"nope": ["Paths"]}),
+ json!({"layers": [1, null, {"a": 1}]}),
+ json!({"layers": ["Nope", "Paths", "Paths"]}),
+ ] {
+ let back: DockLayout = serde_json::from_value(json!({"order": ["layers"], "tabOrder": bad})).unwrap();
+ assert_eq!(back.order().first(), Some(&Group::Layers), "{bad}");
+ let layers = names(&back, Group::Layers, true);
+ assert!(layers == ["Layers", "Channels", "Paths"] || layers == ["Paths", "Layers", "Channels"], "{bad}: {layers:?}");
+ assert_eq!(back.visible_tabs(Group::Color, true).len(), 4);
+ }
+ let back: DockLayout = serde_json::from_value(json!({"tabOrder": {"layers": ["Channels"]}})).unwrap();
+ assert_eq!(names(&back, Group::Layers, true), ["Channels", "Layers", "Paths"], "missing tabs follow in their default order");
+}
+
+/// #2272: dragging a tab along its strip reorders the group's tabs; the order persists in the
+/// UI state, the remembered layout and saved workspaces, and clicking still selects.
+#[test]
+fn dragging_a_tab_reorders_the_group_and_the_order_persists() {
+ for theme in [ThemeKind::ProMedium, ThemeKind::Studio] {
+ let (app, _, _) = app_with_layers();
+ let mut h = harness(app, vec2(1200.0, 800.0), theme);
+ let order = h.state().ui.dock.order();
+ let rects = last_rects(&h.ctx);
+ let paths = tab_rect(&h, Group::Layers, 2);
+ let layers = tab_rect(&h, Group::Layers, 0);
+ drag(&mut h, paths.center(), layers.left_center() + vec2(4.0, 0.0));
+ let strip: Vec<usize> = strip_tabs(&h, Group::Layers).iter().map(|(i, _)| *i).collect();
+ assert_eq!(strip, [2, 0, 1], "{theme:?}: Paths moved before Layers");
+ assert_eq!(h.state().ui.dock.order(), order, "{theme:?}: a tab drag along the strip leaves the groups put");
+ assert_eq!(last_rects(&h.ctx), rects);
+ // The dragged tab is brought to the front; dockTabs keeps its original indices.
+ assert_eq!(h.state().ui.dock_tabs.layers, 2, "{theme:?}");
+
+ // A plain click still selects, and selects the tab under the pointer.
+ let layers = tab_rect(&h, Group::Layers, 0).center();
+ click(&mut h, layers);
+ assert_eq!(h.state().ui.dock_tabs.layers, 0, "{theme:?}");
+ assert_eq!(strip_tabs(&h, Group::Layers).iter().map(|(i, _)| *i).collect::<Vec<_>>(), [2, 0, 1]);
+
+ // UI state round trip (the control channel's ui.get / ui.set).
+ let dock = serde_json::to_value(&h.state().ui.dock).unwrap();
+ assert_eq!(dock["tabOrder"], json!({"layers": ["Paths", "Layers", "Channels"]}));
+ let ctx = h.ctx.clone();
+ let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"tabOrder": {"layers": ["Channels"]}}}));
+ crate::control::handle(h.state_mut(), &ctx, &req);
+ assert_eq!(h.state().ui.dock.visible_tabs(Group::Layers, is_pro(theme))[0], (1, "Channels"));
+ let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dock": dock}));
+ crate::control::handle(h.state_mut(), &ctx, &req);
+ assert_eq!(h.state().ui.dock.visible_tabs(Group::Layers, is_pro(theme))[0], (2, "Paths"));
+
+ // Remembered across launches (prefs panelLayout) ...
+ h.state_mut().session.prefs.edit(|p| p.workspace.remember_workspace_changes = true);
+ persist(h.state_mut(), &ctx);
+ let saved = h.state().session.prefs().panel_layout.clone();
+ let (mut fresh, _, _) = app_with_layers();
+ fresh.session.prefs.edit(|p| {
+ p.workspace.remember_workspace_changes = true;
+ p.panel_layout = saved.clone();
+ });
+ restore(&mut fresh);
+ assert_eq!(fresh.ui.dock.visible_tabs(Group::Layers, is_pro(theme))[0], (2, "Paths"), "{theme:?}");
+
+ // ... and in a saved workspace, which Essentials resets and selecting brings back.
+ crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.newWorkspace", json!({"name": "Paths First"})).unwrap();
+ crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.essentials", json!({})).unwrap();
+ assert!(h.state().ui.dock.tab_order.is_empty());
+ crate::menus::invoke(h.state_mut(), &ctx, "window.workspace.select", json!({"name": "Paths First"})).unwrap();
+ h.run_steps(3);
+ assert_eq!(strip_tabs(&h, Group::Layers).iter().map(|(i, _)| *i).collect::<Vec<_>>(), [2, 0, 1], "{theme:?}");
+ }
+}
+
+/// Dragging a tab off its strip moves the whole group (as dragging the strip does); a locked
+/// workspace keeps both the tab and group order.
+#[test]
+fn a_tab_dragged_off_the_strip_moves_the_group_and_locking_stops_reordering() {
+ let (app, _, _) = app_with_layers();
+ let mut h = harness(app, vec2(1200.0, 800.0), ThemeKind::ProMedium);
+ let paths = tab_rect(&h, Group::Layers, 2);
+ let to = rect_of(&h, Group::Color).left_top() + vec2(120.0, 10.0);
+ drag(&mut h, paths.center(), to);
+ assert_eq!(h.state().ui.dock.order().first(), Some(&Group::Layers));
+ assert!(h.state().ui.dock.tab_order.is_empty(), "the tabs kept their order");
+
+ h.state_mut().session.prefs.edit(|p| p.workspace_locked = true);
+ h.run_steps(2);
+ let order = h.state().ui.dock.order();
+ let paths = tab_rect(&h, Group::Layers, 2);
+ let layers = tab_rect(&h, Group::Layers, 0).left_center();
+ drag(&mut h, paths.center(), layers + vec2(4.0, 0.0));
+ assert!(h.state().ui.dock.tab_order.is_empty());
+ let paths = tab_rect(&h, Group::Layers, 2);
+ drag(&mut h, paths.center(), paths.center() + vec2(0.0, 500.0));
+ assert_eq!(h.state().ui.dock.order(), order);
+}
diff --git a/crates/ui-egui/src/tab_strip.rs b/crates/ui-egui/src/tab_strip.rs
index f6b3b1cfd..ddf1a7b67 100644
--- a/crates/ui-egui/src/tab_strip.rs
+++ b/crates/ui-egui/src/tab_strip.rs
@@ -2,6 +2,7 @@
//! the panel menu button they shrink, eliding their labels with '…', and once they are at their
//! minimum width the ones that still don't fit move into a » chevron menu at the end of the
//! strip. The selected tab always stays on the strip, and no tab ever runs under the menu button.
+//! On a reorderable strip a tab dragged along the strip moves to where it is dropped (#2272).
use egui::{CornerRadius, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
@@ -101,6 +102,13 @@ pub struct StripOut {
pub tabs: Vec<(usize, Rect)>,
/// The » overflow button, when some tabs didn't fit.
pub chevron: Option<Rect>,
+ /// A tab was dragged along the strip and dropped: `(tab, before)`, draw `tab` just before
+ /// tab `before` (`None`: last).
+ pub reorder: Option<(usize, Option<usize>)>,
+ /// A tab is being dragged away from the strip (the dock moves the whole group then).
+ pub dragging_out: bool,
+ /// A tab drag ended away from the strip.
+ pub dropped_out: bool,
}
/// Width of the » overflow button.
@@ -142,6 +150,7 @@ fn tabs_in(
font: egui::FontId,
pad: f32,
min_w: f32,
+ reorderable: bool,
active: impl Fn(usize) -> bool,
mut paint_tab: impl FnMut(&Ui, Rect, usize, std::sync::Arc<egui::Galley>, &Response, bool),
) -> StripOut {
@@ -152,11 +161,32 @@ fn tabs_in(
let natural: Vec<f32> = tabs.iter().map(|n| ui.painter().layout_no_wrap((*n).to_owned(), font.clone(), t.text).size().x + pad).collect();
let f = fit(&natural, *selected, area.width(), min_w, CHEVRON_W);
let mut x = area.left();
- let mut out = StripOut { clicked: false, double_clicked: false, context: None, tabs: Vec::with_capacity(f.shown.len()), chevron: None };
+ let mut out = StripOut {
+ clicked: false,
+ double_clicked: false,
+ context: None,
+ tabs: Vec::with_capacity(f.shown.len()),
+ chevron: None,
+ reorder: None,
+ dragging_out: false,
+ dropped_out: false,
+ };
+ // Without reordering, drags on a tab fall through to the strip behind it.
+ let sense = if reorderable { Sense::click_and_drag() } else { Sense::click() };
+ let mut drag: Option<(usize, bool)> = None;
for &(i, w) in &f.shown {
let Some(name) = tabs.get(i) else { continue };
let r = Rect::from_min_size(pos2(x, area.top()), vec2(w, area.height()));
- let resp = ui.interact(r, id.with(("tab", i)), Sense::click());
+ let resp = ui.interact(r, id.with(("tab", i)), sense);
+ // Like Photoshop, pressing a tab to drag it brings it to the front.
+ if resp.drag_started() {
+ *selected = i;
+ }
+ if resp.dragged() {
+ drag = Some((i, false));
+ } else if resp.drag_stopped() {
+ drag = Some((i, true));
+ }
// The padding gives way (down to a third) before the label is cut.
let galley = elided(ui, name, font.clone(), t.text, (w - pad / 3.0).max(1.0));
let cut = galley.size().x + pad + 0.5 < natural.get(i).copied().unwrap_or(0.0) && galley.size().x + pad / 3.0 >= w - 0.5;
@@ -192,12 +222,43 @@ fn tabs_in(
}
out.chevron = Some(r);
}
+ if let Some((tab, released)) = drag
+ && let Some(p) = ui.ctx().pointer_interact_pos().or_else(|| ui.ctx().pointer_latest_pos())
+ {
+ match drop_slot(&out.tabs, area, p) {
+ Some(slot) => {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
+ let before = match out.tabs.get(slot) {
+ Some((b, _)) => Some(*b),
+ // After the last tab on the strip: before the first overflowing one, if any.
+ None => out.tabs.last().map(|(l, _)| l + 1).filter(|b| *b < tabs.len()),
+ };
+ if released {
+ out.reorder = Some((tab, before));
+ } else if let Some((_, r)) = out.tabs.get(slot.min(out.tabs.len().saturating_sub(1))) {
+ crate::widgets::drop_line(ui, *r, slot >= out.tabs.len(), true, &t);
+ }
+ }
+ None if released => out.dropped_out = true,
+ None => out.dragging_out = true,
+ }
+ }
out
}
+/// Where a tab dragged to `p` lands: before the `n`th tab on the strip (`tabs.len()`: after the
+/// last), or `None` once the pointer has left the strip.
+pub fn drop_slot(tabs: &[(usize, Rect)], area: Rect, p: egui::Pos2) -> Option<usize> {
+ if !area.expand2(vec2(24.0, area.height())).contains(p) {
+ return None;
+ }
+ Some(tabs.iter().filter(|(_, r)| r.center().x < p.x).count())
+}
+
/// Photoshop-grammar strip (Pro themes): flat tabs on the dark strip; `menu_left` is where the
/// panel menu button starts.
-pub fn pro_tabs(ui: &mut Ui, id: egui::Id, strip: Rect, menu_left: f32, tabs: &[&str], selected: &mut usize, collapsed: bool) -> StripOut {
+#[allow(clippy::too_many_arguments)]
+pub fn pro_tabs(ui: &mut Ui, id: egui::Id, strip: Rect, menu_left: f32, tabs: &[&str], selected: &mut usize, collapsed: bool, reorderable: bool) -> StripOut {
let t = Tokens::get(ui.ctx());
let area = Rect::from_min_max(strip.min, pos2(menu_left.max(strip.left()), strip.bottom()));
let sel = *selected;
@@ -210,6 +271,7 @@ pub fn pro_tabs(ui: &mut Ui, id: egui::Id, strip: Rect, menu_left: f32, tabs: &[
egui::FontId::proportional(11.5),
22.0,
40.0,
+ reorderable,
|i| i == sel && !collapsed,
|ui, r, i, galley, resp, active| {
if active {
@@ -230,7 +292,7 @@ pub fn pro_tabs(ui: &mut Ui, id: egui::Id, strip: Rect, menu_left: f32, tabs: &[
}
/// Studio strip: pill tabs in `area` (the row minus the menu button).
-pub fn pill_tabs(ui: &mut Ui, id: egui::Id, area: Rect, tabs: &[&str], selected: &mut usize) -> StripOut {
+pub fn pill_tabs(ui: &mut Ui, id: egui::Id, area: Rect, tabs: &[&str], selected: &mut usize, reorderable: bool) -> StripOut {
let t = Tokens::get(ui.ctx());
let sel = *selected;
tabs_in(
@@ -242,6 +304,7 @@ pub fn pill_tabs(ui: &mut Ui, id: egui::Id, area: Rect, tabs: &[&str], selected:
theme::medium(12.5),
20.0,
44.0,
+ reorderable,
|i| i == sel,
|ui, r, _, galley, resp, active| {
// 2 pt between pills, as the old horizontal layout had.
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index e38e90991..0ac4d6ba8 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -55,7 +55,7 @@ pub fn surface(ui: &Ui, rect: Rect, fill: Color32, raised: bool) {
/// A dock card: rounded container with a header of pill tabs and optional trailing actions.
/// Returns the index of the selected tab.
pub fn card(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, body: impl FnOnce(&mut Ui, usize)) {
- let _ = card_ex(ui, id, tabs, selected, false, body);
+ let _ = card_ex(ui, id, tabs, selected, false, false, body);
}
/// What happened on a card's tab strip this frame (see [`card_ex`]).
@@ -75,13 +75,46 @@ pub struct CardResponse {
pub tabs: Vec<(usize, Rect)>,
/// The » overflow button, when some tabs didn't fit.
pub chevron: Option<Rect>,
+ /// A tab dragged along the strip was dropped: `(tab, before)` (#2272).
+ pub tab_reorder: Option<(usize, Option<usize>)>,
+ /// A tab is being dragged away from the strip.
+ pub tab_dragging_out: bool,
+ /// A tab drag ended away from the strip.
+ pub tab_dropped_out: bool,
+}
+
+impl CardResponse {
+ fn new(strip: Response, menu: Response, tabs: crate::tab_strip::StripOut) -> Self {
+ CardResponse {
+ strip,
+ menu,
+ tab_clicked: tabs.clicked,
+ tab_double_clicked: tabs.double_clicked,
+ tab_context: tabs.context,
+ tabs: tabs.tabs,
+ chevron: tabs.chevron,
+ tab_reorder: tabs.reorder,
+ tab_dragging_out: tabs.dragging_out,
+ tab_dropped_out: tabs.dropped_out,
+ }
+ }
}
/// [`card`] that can be collapsed to its tab strip and reports strip and menu interactions.
-pub fn card_ex(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, collapsed: bool, body: impl FnOnce(&mut Ui, usize)) -> CardResponse {
+/// With `reorderable`, tabs can be dragged along the strip (reported, not applied).
+#[allow(clippy::too_many_arguments)]
+pub fn card_ex(
+ ui: &mut Ui,
+ id: &str,
+ tabs: &[&str],
+ selected: &mut usize,
+ collapsed: bool,
+ reorderable: bool,
+ body: impl FnOnce(&mut Ui, usize),
+) -> CardResponse {
let t = Tokens::get(ui.ctx());
if t.pro {
- return pro_panel(ui, id, tabs, selected, collapsed, body);
+ return pro_panel(ui, id, tabs, selected, collapsed, reorderable, body);
}
let m = body_margin(false);
let frame = egui::Frame::NONE
@@ -101,20 +134,12 @@ pub fn card_ex(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, colla
let menu_rect = Rect::from_min_max(pos2(row.right() - 22.0, row.top() + 1.0), pos2(row.right(), row.bottom() - 1.0));
let menu = crate::icons::button(&mut ui.new_child(egui::UiBuilder::new().max_rect(menu_rect)), "ellipsis", 22.0, false, &tip);
let area = Rect::from_min_max(row.min, pos2((menu_rect.left() - 4.0).max(row.left()), row.bottom()));
- let tabs_out = crate::tab_strip::pill_tabs(ui, ui.id().with((id, "tabs")), area, tabs, selected);
+ let tabs_out = crate::tab_strip::pill_tabs(ui, ui.id().with((id, "tabs")), area, tabs, selected, reorderable);
if !collapsed {
ui.add_space(6.0);
body(ui, *selected);
}
- CardResponse {
- strip,
- menu,
- tab_clicked: tabs_out.clicked,
- tab_double_clicked: tabs_out.double_clicked,
- tab_context: tabs_out.context,
- tabs: tabs_out.tabs,
- chevron: tabs_out.chevron,
- }
+ CardResponse::new(strip, menu, tabs_out)
})
.inner;
ui.add_space(6.0);
@@ -152,7 +177,15 @@ pub fn panel_footer<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
}
/// Photoshop-grammar panel group: dark tab strip with flat tabs, flat body, hamburger menu.
-fn pro_panel(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, collapsed: bool, body: impl FnOnce(&mut Ui, usize)) -> CardResponse {
+fn pro_panel(
+ ui: &mut Ui,
+ id: &str,
+ tabs: &[&str],
+ selected: &mut usize,
+ collapsed: bool,
+ reorderable: bool,
+ body: impl FnOnce(&mut Ui, usize),
+) -> CardResponse {
let t = Tokens::get(ui.ctx());
let width = ui.available_width();
// Tab strip. Its background senses drags (move the group) and double-clicks (collapse);
@@ -163,7 +196,7 @@ fn pro_panel(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, collaps
ui.painter().rect_filled(strip, rounding, t.tab_strip);
// Panel menu (hamburger); the tabs stay left of it, eliding or overflowing (#151).
let menu = Rect::from_center_size(pos2(strip.right() - 14.0, strip.center().y), vec2(20.0, 18.0));
- let tabs_out = crate::tab_strip::pro_tabs(ui, ui.id().with((id, "tabs")), strip, menu.left(), tabs, selected, collapsed);
+ let tabs_out = crate::tab_strip::pro_tabs(ui, ui.id().with((id, "tabs")), strip, menu.left(), tabs, selected, collapsed, reorderable);
let mresp = ui.interact(menu, ui.id().with((id, "menu")), Sense::click());
let c = if mresp.hovered() { t.text } else { t.text_faint };
for k in 0..3 {
@@ -178,15 +211,7 @@ fn pro_panel(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, collaps
});
}
ui.add_space(2.0);
- CardResponse {
- strip: strip_resp,
- menu: mresp,
- tab_clicked: tabs_out.clicked,
- tab_double_clicked: tabs_out.double_clicked,
- tab_context: tabs_out.context,
- tabs: tabs_out.tabs,
- chevron: tabs_out.chevron,
- }
+ CardResponse::new(strip_resp, mresp, tabs_out)
}
pub fn pill_tab(ui: &mut Ui, label: &str, selected: bool) -> Response {
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 3d67cf672..f65113d85 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -43,7 +43,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given. `params` must be a JSON object (omit it or pass `null` for none); an array, string, number or boolean is an error naming the command, in every transport (control channel, `serve`, MCP and the CLI)
- `engine.commands`: list commands with enablement
- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `brushPicker` is `null` while closed and `{pos: [x, y], size: [w, h]?, list: {collapsed, filter, renaming, showName, showStroke, showTip, scale}}` while the Brush Preset picker is open (coordinates in screen points; `size` is the picker's content size once its corner grip was dragged, `null` before that, and the drag remembers both dimensions; the three `show*` flags pick the parts of each preset's card — at least one is always on; `scale` is the footer slider, 0.15–2 with 1 the standard, multiplying the cards' width and height — the heights stop at half size and the name and tip-size text hold their 1.0 size — and dropping the tips' size numbers at 0.40 and below; the parts and the scale are remembered across restarts, while the search, collapsed groups and a rename in progress are not). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`)
-- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerName?, brushPickerStroke?, brushPickerTip?, brushPickerScale?, gradientBlendMode?, gradientClassic?, shapeStroke?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` is `list` or `grid` for the Brushes panel; `brushPickerName`, `brushPickerStroke` and `brushPickerTip` are the Brush Preset picker's card parts (booleans, at least one on), and `brushPickerScale` its footer card-scale slider (0.15 to 2, 1 the standard); `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour; `maskTarget` targets the active layer's mask, which, like Photoshop, swaps in the foreground/background pair kept for masks (white/black until one is picked) and swaps the pixels' pair back when the pixels are targeted again)
+- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerName?, brushPickerStroke?, brushPickerTip?, brushPickerScale?, gradientBlendMode?, gradientClassic?, shapeStroke?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` is `list` or `grid` for the Brushes panel; `brushPickerName`, `brushPickerStroke` and `brushPickerTip` are the Brush Preset picker's card parts (booleans, at least one on), and `brushPickerScale` its footer card-scale slider (0.15 to 2, 1 the standard); `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"], tabOrder: {"layers": ["Paths", "Layers", "Channels"]}}`, the right-dock groups top to bottom, their heights in points, the groups collapsed to their tab strip and each group's tab order left to right by panel name (a group left out keeps its default order, unknown names are ignored and tabs not listed follow in their default order; `dockTabs` keeps indexing tabs in their default order); `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour; `maskTarget` targets the active layer's mask, which, like Photoshop, swaps in the foreground/background pair kept for masks (white/black until one is picked) and swaps the pixels' pair back when the pixels are targeted again)
- `typeTransform` is `null` outside a temporary Ctrl/Cmd Type-tool drag. During a drag it reports its source document/revision, original affine, oriented `frame` (layer, local bounds, document-space corners and pivot), and captured `gesture`. Drive it with `ui.pointer` and `command: true` at `down`; `move`/`up` may release the modifier. The document/history remain unchanged during preview, and `up` applies one `type.edit` within `textEdit`'s session. Pressing Escape during the drag cancels only the preview. This pointer state is never restored from saved UI state.
- `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.