Skip to content

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

Panels: Close and Close Tab Group on a dock tab's context menu (#1924)

Nigel Ihza Firdausy748821864e18
diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs
index 49c917f0b..8cfa3ff26 100644
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@ -154,7 +154,7 @@ impl Group {
}
}
-/// Order, heights and collapsed state of the dock groups.
+/// Order, heights, collapsed state and visibility of individual dock tabs.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct DockLayout {
@@ -165,6 +165,9 @@ pub struct DockLayout {
pub heights: BTreeMap<Group, f32>,
/// Groups collapsed to their tab strip.
pub collapsed: Vec<Group>,
+ /// 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>>,
}
/// Gap between groups; it is also the splitter's grab area.
@@ -173,6 +176,32 @@ 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.
+ 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()
+ }
+
+ /// Hide one tab; it can be reopened through Window › Panel.
+ pub fn hide_tab(&mut self, group: Group, tab: usize, pro: bool) {
+ let Some(&name) = group.tabs(pro).get(tab) else { return };
+ let hidden = self.hidden_tabs.entry(group).or_default();
+ if !hidden.iter().any(|x| x.as_str() == name) {
+ hidden.push(name.to_owned());
+ }
+ }
+
+ /// Restore the tab requested by the Window menu or icon rail.
+ pub fn show_tab(&mut self, group: Group, tab: usize, pro: bool) {
+ let Some(&name) = group.tabs(pro).get(tab) else { return };
+ if let Some(hidden) = self.hidden_tabs.get_mut(&group) {
+ hidden.retain(|n| n != name);
+ if hidden.is_empty() {
+ self.hidden_tabs.remove(&group);
+ }
+ }
+ }
+
/// Every group once, in display order.
pub fn order(&self) -> Vec<Group> {
let mut out: Vec<Group> = Vec::with_capacity(Group::ALL.len());
@@ -298,6 +327,9 @@ impl DockLayout {
/// brought back, whatever state it was left in (#129).
pub fn reveal(app: &mut PhotocraftApp, g: Group) {
*g.shown_mut(&mut app.ui.panels) = true;
+ let selected = *g.tab_mut(&mut app.ui.dock_tabs);
+ let pro = matches!(app.ui.theme, crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium);
+ app.ui.dock.show_tab(g, selected, pro);
app.ui.dock.set_collapsed(g, false);
}
@@ -320,6 +352,7 @@ pub fn rail_click(app: &mut PhotocraftApp, g: Group, docked: bool) {
enum Action {
ToggleCollapse(Group),
Close(Group),
+ CloseTab(Group, usize),
Move(Group, Option<Group>),
}
@@ -372,9 +405,15 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
child.set_clip_rect(rect.intersect(ui.clip_rect()));
child.spacing_mut().item_spacing.y = if t.pro { 0.0 } else { 6.0 };
let before = *g.tab_mut(&mut app.ui.dock_tabs);
- let mut sel = before;
- let tabs = g.tabs(t.pro);
- let resp = widgets::card_ex(&mut child, g.key(), tabs, &mut sel, collapsed, |ui, tab| {
+ let visible = app.ui.dock.visible_tabs(g, t.pro);
+ if visible.is_empty() {
+ continue;
+ }
+ 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 Some(&tab) = indices.get(shown_tab) else { return };
let inner = ui.available_height().max(0.0);
if g.scrolls_itself(tab) {
ui.set_min_height(inner);
@@ -387,10 +426,27 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
.show(ui, |ui| body(app, ui, g, tab));
}
});
- strips.push(StripRects { group: g, tabs: resp.tabs.clone(), menu: resp.menu.rect, chevron: resp.chevron });
- // The body may switch tabs itself (Adjustments jumps back to Properties).
- if sel != before {
- *g.tab_mut(&mut app.ui.dock_tabs) = sel.min(tabs.len().saturating_sub(1));
+ strips.push(StripRects {
+ group: g,
+ tabs: resp.tabs.iter().filter_map(|(i, r)| indices.get(*i).map(|original| (*original, *r))).collect(),
+ menu: resp.menu.rect,
+ chevron: resp.chevron,
+ });
+ // The strip uses visible indices; dockTabs and the panel bodies use original indices.
+ if let Some(&picked) = indices.get(sel)
+ && picked != before
+ {
+ *g.tab_mut(&mut app.ui.dock_tabs) = picked;
+ }
+ if let Some(context) = resp.tab_context {
+ match context {
+ crate::tab_strip::TabContextAction::Close(i) => {
+ if let Some(&tab) = indices.get(i) {
+ actions.push(Action::CloseTab(g, tab));
+ }
+ }
+ crate::tab_strip::TabContextAction::CloseGroup => actions.push(Action::Close(g)),
+ }
}
if resp.strip.double_clicked() || resp.tab_double_clicked || (collapsed && resp.tab_clicked) {
actions.push(Action::ToggleCollapse(g));
@@ -470,6 +526,19 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
app.ui.dock.set_collapsed(g, on);
}
Action::Close(g) => *g.shown_mut(&mut app.ui.panels) = false,
+ Action::CloseTab(g, tab) => {
+ 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());
+ if let Some(&(next, _)) = next {
+ *g.tab_mut(&mut app.ui.dock_tabs) = next;
+ }
+ }
+ }
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 ae41188a1..3d629c985 100644
--- a/crates/ui-egui/src/dock_tests.rs
+++ b/crates/ui-egui/src/dock_tests.rs
@@ -378,6 +378,88 @@ fn clicking_around_the_ui_keeps_the_panels_put() {
}
}
+#[test]
+fn closing_tabs_keeps_stable_names_across_themes_and_workspace_round_trips() {
+ let mut dock = DockLayout::default();
+ // In Pro the first Color group tab is Color; in Studio it is Swatches.
+ dock.hide_tab(Group::Color, 0, true);
+ assert_eq!(dock.visible_tabs(Group::Color, true).iter().map(|(_, n)| *n).collect::<Vec<_>>(), vec!["Swatches", "Gradients", "Patterns"]);
+ assert_eq!(dock.visible_tabs(Group::Color, false).iter().map(|(_, n)| *n).collect::<Vec<_>>(), vec!["Swatches", "Gradients", "Patterns"]);
+ dock.hide_tab(Group::Color, 999, true);
+ assert_eq!(dock.hidden_tabs[&Group::Color], vec!["Color"]);
+ let saved = serde_json::to_value(&dock).unwrap();
+ let mut restored: DockLayout = serde_json::from_value(saved).unwrap();
+ assert_eq!(restored, dock);
+ // Window › Color (Studio index 1) brings back precisely that tab.
+ restored.show_tab(Group::Color, 1, false);
+ assert!(restored.hidden_tabs.is_empty());
+ assert_eq!(restored.visible_tabs(Group::Color, false).len(), 4);
+}
+
+fn right_click_tab(h: &mut Harness<'static, PhotocraftApp>, group: Group, original_index: usize) {
+ let p = last_strips(&h.ctx)
+ .into_iter()
+ .find(|s| s.group == group)
+ .and_then(|s| s.tabs.into_iter().find(|(i, _)| *i == original_index))
+ .map(|(_, r)| r.center())
+ .unwrap_or_else(|| panic!("requested dock tab visible: {:?}", last_strips(&h.ctx).iter().map(|s| (s.group, s.tabs.clone())).collect::<Vec<_>>()));
+ h.hover_at(p);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
+ h.step();
+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
+ h.run_steps(2);
+}
+
+/// #1753: both themes offer Close for the clicked tab and Close Tab Group independently.
+/// Closing the last tab hides its group; Window restores a hidden tab. (Studio floats
+/// Properties outside the dock, so it closes Layers tabs instead.)
+#[test]
+fn panel_tab_context_menu_closes_one_tab_or_its_group() {
+ use egui_kittest::kittest::Queryable;
+
+ for (theme, g, window) in [(ThemeKind::ProMedium, Group::Properties, "window.panel.properties"), (ThemeKind::Studio, Group::Layers, "window.panel.layers")]
+ {
+ let pro = is_pro(theme);
+ let names = g.tabs(pro);
+ let (app, _, _) = app_with_layers();
+ let mut h = harness(app, vec2(1300.0, 850.0), theme);
+ // Close the first tab: the group stays, showing (and selecting) the next one.
+ right_click_tab(&mut h, g, 0);
+ h.get_by_label("Close").click();
+ h.run_steps(3);
+ assert!(g.shown(&h.state().ui.panels), "{theme:?}: closing one tab keeps the group");
+ assert_eq!(*g.tab_mut(&mut h.state_mut().ui.dock_tabs), 1);
+ let rest: Vec<(usize, &str)> = names.iter().copied().enumerate().skip(1).collect();
+ assert_eq!(h.state().ui.dock.visible_tabs(g, pro), rest);
+ let strip: Vec<usize> = last_strips(&h.ctx).iter().find(|s| s.group == g).unwrap().tabs.iter().map(|(i, _)| *i).collect();
+ assert_eq!(strip, rest.iter().map(|(i, _)| *i).collect::<Vec<_>>());
+
+ // Close the remaining tabs: the last one hides this group, not the other dock groups.
+ for i in 1..names.len() {
+ right_click_tab(&mut h, g, i);
+ h.get_by_label("Close").click();
+ h.run_steps(3);
+ }
+ assert!(!g.shown(&h.state().ui.panels), "{theme:?}");
+ assert!(h.state().ui.panels.color, "{theme:?}");
+
+ // The Window menu reopens only the requested tab; hidden tabs stay hidden.
+ let ctx = h.ctx.clone();
+ crate::menus::invoke(h.state_mut(), &ctx, window, json!({})).unwrap();
+ h.run_steps(3);
+ assert!(g.shown(&h.state().ui.panels) && !h.state().ui.dock.is_collapsed(g));
+ assert_eq!(h.state().ui.dock.visible_tabs(g, pro), vec![(0, names[0])]);
+
+ // A tab's Close Tab Group closes the entire group without hiding its one tab.
+ right_click_tab(&mut h, g, 0);
+ h.get_by_label("Close Tab Group").click();
+ h.run_steps(3);
+ assert!(!g.shown(&h.state().ui.panels));
+ assert_eq!(h.state().ui.dock.visible_tabs(g, pro), vec![(0, names[0])]);
+ }
+}
+
fn is_pro(theme: ThemeKind) -> bool {
matches!(theme, ThemeKind::Pro | ThemeKind::ProMedium)
}
diff --git a/crates/ui-egui/src/tab_strip.rs b/crates/ui-egui/src/tab_strip.rs
index 108686222..f6b3b1cfd 100644
--- a/crates/ui-egui/src/tab_strip.rs
+++ b/crates/ui-egui/src/tab_strip.rs
@@ -84,11 +84,19 @@ pub fn elided(ui: &Ui, text: &str, font: egui::FontId, color: egui::Color32, max
ui.painter().layout_job(job)
}
+/// Context-menu action chosen on a dock tab.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TabContextAction {
+ Close(usize),
+ CloseGroup,
+}
+
/// What a strip reported this frame.
pub struct StripOut {
/// A tab was activated, including a choice from the overflow menu.
pub clicked: bool,
pub double_clicked: bool,
+ pub context: Option<TabContextAction>,
/// Rects of the tabs on the strip, `(tab index, rect)`.
pub tabs: Vec<(usize, Rect)>,
/// The » overflow button, when some tabs didn't fit.
@@ -144,7 +152,7 @@ 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, 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 };
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()));
@@ -159,6 +167,18 @@ fn tabs_in(
out.clicked = true;
*selected = i;
}
+ // The context menu belongs to the actual tab response, so its normal clicks
+ // and double-click-to-collapse behavior are not intercepted by an overlay.
+ resp.context_menu(|ui| {
+ if ui.button(tl!("Close")).clicked() {
+ out.context = Some(TabContextAction::Close(i));
+ ui.close();
+ }
+ if ui.button(tl!("Close Tab Group")).clicked() {
+ out.context = Some(TabContextAction::CloseGroup);
+ ui.close();
+ }
+ });
out.tabs.push((i, r));
x = r.right();
}
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 74f2f0444..6a5b8966e 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -51,6 +51,8 @@ pub struct CardResponse {
pub tab_clicked: bool,
/// A tab was double-clicked (Photoshop collapses the group).
pub tab_double_clicked: bool,
+ /// Right-click action selected for a visible tab.
+ pub tab_context: Option<crate::tab_strip::TabContextAction>,
/// Rects of the tabs on the strip, `(tab index, rect)`; tabs that don't fit are in the
/// chevron menu instead (#151).
pub tabs: Vec<(usize, Rect)>,
@@ -92,6 +94,7 @@ pub fn card_ex(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, colla
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,
}
@@ -163,6 +166,7 @@ fn pro_panel(ui: &mut Ui, id: &str, tabs: &[&str], selected: &mut usize, collaps
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,
}