From c21f3e1a198c7837f011c325a5d906cd71275f49 Mon Sep 17 00:00:00 2001 From: Hakan Seven Date: Mon, 27 Jul 2026 22:14:58 +0300 Subject: [PATCH] feat(tabs): add drag-and-drop reordering Closes #526 --- src/app/mod.rs | 12 ++ src/app/update/mod.rs | 65 +++++++++ src/app/view/mod.rs | 32 ++-- src/scene/layout.rs | 15 ++ src/ui/statusbar/mod.rs | 33 ++++- src/ui/wrap_bar.rs | 316 +++++++++++++++++++++++++++++++++++++++- 6 files changed, 457 insertions(+), 16 deletions(-) diff --git a/src/app/mod.rs b/src/app/mod.rs index 27734313..b272b879 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1497,6 +1497,12 @@ pub enum Message { TabNew, /// Switch to the given tab index. TabSwitch(usize), + /// Move a drawing tab before/after another drawing tab. + TabReorder { + from: usize, + to: usize, + after: bool, + }, /// Close the given tab index. TabClose(usize), /// Open/close the right-click menu for a drawing tab. @@ -1934,6 +1940,12 @@ pub enum Message { PspaceCommand, /// Switch to a named layout ("Model" or paper space layout name). LayoutSwitch(String), + /// Move a paper layout before/after another paper layout. + LayoutReorder { + from: String, + to: String, + after: bool, + }, /// Create a new paper space layout. LayoutCreate, /// Delete the named paper space layout (Model cannot be deleted). diff --git a/src/app/update/mod.rs b/src/app/update/mod.rs index aa6098c7..9a1979f7 100644 --- a/src/app/update/mod.rs +++ b/src/app/update/mod.rs @@ -57,6 +57,17 @@ fn format_size(bytes: u64) -> String { } } +fn reorder_insertion_index(from: usize, to: usize, after: bool, len: usize) -> Option { + if from >= len || to >= len || from == to { + return None; + } + let mut insertion = to + usize::from(after); + if from < insertion { + insertion -= 1; + } + (insertion != from).then_some(insertion) +} + mod command; mod dialog; mod dynamic; @@ -962,6 +973,28 @@ impl OpenCADStudio { Task::none() } + Message::TabReorder { from, to, after } => { + let Some(insertion) = + reorder_insertion_index(from, to, after, self.tabs.len()) + else { + return Task::none(); + }; + if self.tabs.get(from).is_some_and(|tab| tab.is_start) + || self.tabs.get(to).is_some_and(|tab| tab.is_start) + { + return Task::none(); + } + + let active_id = self.tabs[self.active_tab].id; + let moved = self.tabs.remove(from); + self.tabs.insert(insertion, moved); + if let Some(index) = self.tabs.iter().position(|tab| tab.id == active_id) { + self.active_tab = index; + } + self.doc_tab_context_menu = None; + Task::none() + } + Message::TabClose(idx) => { self.doc_tab_context_menu = None; self.on_tab_close(idx) @@ -3325,6 +3358,38 @@ impl OpenCADStudio { self.on_layout_switch(name) } + Message::LayoutReorder { from, to, after } => { + let i = self.active_tab; + if self.tabs[i].is_start { + return Task::none(); + } + let mut paper: Vec = self.tabs[i] + .scene + .layout_names() + .into_iter() + .skip(1) + .collect(); + let Some(from_index) = paper.iter().position(|name| name == &from) else { + return Task::none(); + }; + let Some(to_index) = paper.iter().position(|name| name == &to) else { + return Task::none(); + }; + let Some(insertion) = + reorder_insertion_index(from_index, to_index, after, paper.len()) + else { + return Task::none(); + }; + + let moved = paper.remove(from_index); + paper.insert(insertion, moved); + self.push_undo_snapshot(i, "LAYOUT REORDER"); + self.tabs[i].scene.set_layout_tab_order(&paper); + self.tabs[i].dirty = true; + self.layout_context_menu = None; + Task::none() + } + Message::LayoutCreate => self.on_layout_create(), Message::LayoutDelete(name) => { diff --git a/src/app/view/mod.rs b/src/app/view/mod.rs index 44150b39..cf32e4ba 100644 --- a/src/app/view/mod.rs +++ b/src/app/view/mod.rs @@ -1424,6 +1424,11 @@ impl OpenCADStudio { let last_coord = self.last_point.map(to_readout); let coords_mode = tab.scene.document.header.coords_mode; let picking = tab.active_cmd.is_some(); + let layout_names = tab.scene.layout_names(); + let mut displayed_layouts = layout_names.clone(); + if let Some(be) = &tab.block_edit { + displayed_layouts.push(be.block_name.clone()); + } self.status_bar.view( &self.snapper, self.snap_popup_open, @@ -1433,15 +1438,8 @@ impl OpenCADStudio { self.polar_popup_open, self.dyn_input, self.snapper.otrack_enabled, - { - // In a BEDIT block editor, show the block as an extra - // active space tab alongside Model/layouts. (#261) - let mut names = tab.scene.layout_names(); - if let Some(be) = &tab.block_edit { - names.push(be.block_name.clone()); - } - names - }, + displayed_layouts, + layout_names.into_iter().skip(1).collect(), tab.block_edit .as_ref() .map(|be| be.block_name.clone()) @@ -2096,6 +2094,12 @@ pub(super) fn doc_tab_bar<'a>(tabs: &'a [DocumentTab], active_tab: usize) -> Ele // Document tabs live in a flex-wrap flow so they spill onto lower rows when // there are more tabs than the width can hold on one line. let mut items: Vec> = Vec::new(); + let drag_targets: std::sync::Arc<[usize]> = tabs + .iter() + .enumerate() + .filter_map(|(idx, tab)| (!tab.is_start).then_some(idx)) + .collect::>() + .into(); for (idx, tab) in tabs.iter().enumerate() { let is_active = idx == active_tab; @@ -2147,6 +2151,16 @@ pub(super) fn doc_tab_bar<'a>(tabs: &'a [DocumentTab], active_tab: usize) -> Ele shadow: iced::Shadow::default(), snap: false, }); + let title_btn: Element<'_, Message> = if tab.is_start { + title_btn.into() + } else { + crate::ui::wrap_bar::ReorderTab::document( + idx, + drag_targets.clone(), + title_btn, + ) + .into() + }; // Start tab is fixed — no close button. Every other tab gets a close. let row_inner: Row<'_, Message> = if tab.is_start { diff --git a/src/scene/layout.rs b/src/scene/layout.rs index d0ebe8d0..cb5dd265 100644 --- a/src/scene/layout.rs +++ b/src/scene/layout.rs @@ -123,6 +123,21 @@ impl Scene { } } + /// Apply a complete paper-layout tab order. Model remains fixed at zero. + pub fn set_layout_tab_order(&mut self, ordered_names: &[String]) { + for obj in self.document.objects.values_mut() { + if let ObjectType::Layout(layout) = obj { + if layout.name == "Model" { + layout.tab_order = 0; + } else if let Some(index) = + ordered_names.iter().position(|name| name == &layout.name) + { + layout.tab_order = index as i16 + 1; + } + } + } + } + /// Rebuild the `pane_grid` layout from the current `model_tiles` rects /// (each pane value = its tile index) — used after loading a tiled config /// from the VPort table so the panes match the restored tiles. diff --git a/src/ui/statusbar/mod.rs b/src/ui/statusbar/mod.rs index 8963ff72..e87bcde4 100644 --- a/src/ui/statusbar/mod.rs +++ b/src/ui/statusbar/mod.rs @@ -8,6 +8,7 @@ use iced::widget::{ button, container, mouse_area, row, text, text_input, tooltip, }; use iced::{Background, Border, Color, Element, Length, Theme}; +use std::sync::Arc; /// Scrollable id of the status-bar layout-tab strip (retained so the existing /// `Message::ScrollLayoutTabs` handler still resolves; the strip now flex-wraps @@ -58,6 +59,7 @@ impl StatusBar { dyn_input: bool, otrack: bool, layouts: Vec, + reorderable_layouts: Vec, current_layout: String, // Start/welcome view has no drawing to own layouts. is_start: bool, @@ -375,12 +377,22 @@ impl StatusBar { let mut left: Vec> = Vec::new(); left.push(PosReport::new(SB_LAYOUTLIST_ID, menu_btn).into()); if show_layout_tabs { + let reorderable_layouts: Arc<[String]> = reorderable_layouts.into(); for name in layouts { let is_active = name == current_layout; let renaming = rename_state .filter(|(orig, _)| *orig == name) .map(|(_, edit)| edit.as_str()); - left.push(space_tab(name, is_active, renaming, !is_start).into()); + left.push( + space_tab( + name, + is_active, + renaming, + !is_start, + reorderable_layouts.clone(), + ) + .into(), + ); } left.push(add_btn.into()); } @@ -668,6 +680,7 @@ fn space_tab<'a>( is_active: bool, rename_edit: Option<&'a str>, enabled: bool, + reorderable_layouts: Arc<[String]>, ) -> Element<'a, Message> { let bg = move |is_active: bool, hovered: bool| { if is_active { @@ -791,11 +804,23 @@ fn space_tab<'a>( // PosReport records the tab's screen bounds so the context menu can // anchor next to the clicked tab instead of the screen's left edge // (#428). + let tab = mouse_area(display) + .on_press(switch_msg) + .on_right_press(ctx_msg); + let tab: Element<'a, Message> = if reorderable_layouts.contains(&label) { + crate::ui::wrap_bar::ReorderTab::layout( + label.clone(), + reorderable_layouts, + tab, + ) + .into() + } else { + tab.into() + }; + crate::ui::wrap_bar::PosReport::owned( format!("SB_LAYOUT_TAB:{label}"), - mouse_area(display) - .on_press(switch_msg) - .on_right_press(ctx_msg), + tab, ) .into() } diff --git a/src/ui/wrap_bar.rs b/src/ui/wrap_bar.rs index 7793404c..c088c472 100644 --- a/src/ui/wrap_bar.rs +++ b/src/ui/wrap_bar.rs @@ -22,9 +22,12 @@ use std::sync::Arc; use rustc_hash::FxHashMap; use iced::advanced::layout::{self, Layout}; -use iced::advanced::widget::{self, Widget}; -use iced::advanced::{mouse, overlay, renderer, Clipboard, Shell}; -use iced::{Element, Event, Length, Point, Rectangle, Renderer, Size, Theme, Vector}; +use iced::advanced::widget::{self, tree, Widget}; +use iced::advanced::{mouse, overlay, renderer, Clipboard, Renderer as _, Shell}; +use iced::{ + Background, Border, Color, Element, Event, Length, Point, Rectangle, Renderer, Shadow, Size, + Theme, Vector, +}; use crate::app::Message; @@ -1085,3 +1088,310 @@ impl<'a> From> for Element<'a, Message> { Element::new(w) } } + +// ── Drag-to-reorder tabs ───────────────────────────────────────────────── + +#[derive(Clone)] +enum ReorderSource { + Document { + from: usize, + targets: Arc<[usize]>, + }, + Layout { + from: String, + targets: Arc<[String]>, + }, +} + +#[derive(Default)] +struct ReorderState { + pressed_at: Option, + dragging: bool, +} + +/// Transparent title wrapper that turns a normal tab into a drag source. +/// +/// `PosReport` remains outside this wrapper and records the full target bounds. +/// Keeping this wrapper on the title only means a document tab's close button +/// can never accidentally start a reorder. +pub struct ReorderTab<'a> { + source: ReorderSource, + child: Element<'a, Message>, +} + +impl<'a> ReorderTab<'a> { + pub fn document( + from: usize, + targets: Arc<[usize]>, + child: impl Into>, + ) -> Self { + Self { + source: ReorderSource::Document { from, targets }, + child: child.into(), + } + } + + pub fn layout( + from: String, + targets: Arc<[String]>, + child: impl Into>, + ) -> Self { + Self { + source: ReorderSource::Layout { from, targets }, + child: child.into(), + } + } + + fn drop_target(&self, point: Point) -> Option<(Message, Rectangle, bool)> { + match &self.source { + ReorderSource::Document { from, targets } => { + targets.iter().find_map(|&to| { + if to == *from { + return None; + } + let bounds = dropdown_bounds(&format!("DOC_TAB:{to}"))?; + bounds.contains(point).then(|| { + let after = point.x >= bounds.x + bounds.width / 2.0; + ( + Message::TabReorder { + from: *from, + to, + after, + }, + bounds, + after, + ) + }) + }) + } + ReorderSource::Layout { from, targets } => { + targets.iter().find_map(|to| { + if to == from { + return None; + } + let bounds = dropdown_bounds(&format!("SB_LAYOUT_TAB:{to}"))?; + bounds.contains(point).then(|| { + let after = point.x >= bounds.x + bounds.width / 2.0; + ( + Message::LayoutReorder { + from: from.clone(), + to: to.clone(), + after, + }, + bounds, + after, + ) + }) + }) + } + } + } +} + +impl<'a> Widget for ReorderTab<'a> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::() + } + + fn state(&self) -> tree::State { + tree::State::new(ReorderState::default()) + } + + fn children(&self) -> Vec { + vec![widget::Tree::new(&self.child)] + } + + fn diff(&self, tree: &mut widget::Tree) { + tree.diff_children(&[self.child.as_widget()]); + } + + fn size(&self) -> Size { + self.child.as_widget().size() + } + + fn size_hint(&self) -> Size { + self.child.as_widget().size_hint() + } + + fn layout( + &mut self, + tree: &mut widget::Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.child + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) + } + + fn update( + &mut self, + tree: &mut widget::Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + const START_DISTANCE_SQUARED: f32 = 16.0; + let state = tree.state.downcast_mut::(); + + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + if cursor.is_over(layout.bounds()) => + { + state.pressed_at = cursor.position(); + state.dragging = false; + } + Event::Mouse(mouse::Event::CursorMoved { position }) => { + if let Some(start) = state.pressed_at { + let dx = position.x - start.x; + let dy = position.y - start.y; + if state.dragging || dx * dx + dy * dy >= START_DISTANCE_SQUARED { + state.dragging = true; + shell.capture_event(); + shell.request_redraw(); + return; + } + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => { + let was_dragging = state.dragging; + state.pressed_at = None; + state.dragging = false; + if was_dragging { + if let Some(point) = cursor.position() { + if let Some((message, _, _)) = self.drop_target(point) { + shell.publish(message); + } + } + shell.capture_event(); + shell.request_redraw(); + return; + } + } + _ => {} + } + + self.child.as_widget_mut().update( + &mut tree.children[0], + event, + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + } + + fn mouse_interaction( + &self, + tree: &widget::Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + let state = tree.state.downcast_ref::(); + if state.dragging { + return mouse::Interaction::Grabbing; + } + if cursor.is_over(layout.bounds()) { + return mouse::Interaction::Grab; + } + self.child + .as_widget() + .mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer) + } + + fn operate( + &mut self, + tree: &mut widget::Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn widget::Operation, + ) { + self.child + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); + } + + fn draw( + &self, + tree: &widget::Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + self.child.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + cursor, + viewport, + ); + + let state = tree.state.downcast_ref::(); + if state.dragging { + if let Some(point) = cursor.position() { + if let Some((_, bounds, after)) = self.drop_target(point) { + let x = if after { + bounds.x + bounds.width - 1.0 + } else { + bounds.x - 1.0 + }; + renderer.fill_quad( + renderer::Quad { + bounds: Rectangle { + x, + y: bounds.y + 2.0, + width: 2.0, + height: (bounds.height - 4.0).max(1.0), + }, + border: Border::default(), + shadow: Shadow::default(), + snap: true, + }, + Background::Color(Color { + r: 0.20, + g: 0.55, + b: 0.90, + a: 1.0, + }), + ); + } + } + } + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut widget::Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option> { + self.child.as_widget_mut().overlay( + &mut tree.children[0], + layout, + renderer, + viewport, + translation, + ) + } +} + +impl<'a> From> for Element<'a, Message> { + fn from(w: ReorderTab<'a>) -> Self { + Element::new(w) + } +}