Skip to main content

oa/viewer/
workspace.rs

1//! Workspace dock model for `ViewerMode::Workspace`.
2//!
3//! The workspace composes existing `Ui` primitives — `split_pane` for the dock
4//! tree and `tab_bar` for leaf pane selection — into an editor-style host.
5//! The dock layout is serializable application state: [`Workspace::to_json`]
6//! and [`Workspace::from_json`] round-trip the node tree, while pane content
7//! stays outside the serialized record. `Ui` supplies the primitives and
8//! input routing; the workspace owns no document model, asset browser, or
9//! undo stack.
10
11use serde_json::Value;
12
13use super::{ViewerLiveCapabilities, ViewerLiveSource};
14use crate::input::{InputEvent, InputEventKind};
15use crate::ui::{PixelRect, Ui, UiDirection, UiSplitConfig, UiTabBarState, UiTabItem};
16use crate::{Engine, Error, Result};
17
18/// Content provider rendered inside one workspace leaf pane.
19///
20/// Donor scope note: items are application-owned surfaces (figure views,
21/// media views, inspectors); the workspace only routes geometry and events.
22pub trait WorkspaceItem {
23	/// Stable identifier referenced by `WorkspaceNode::Tabs::tabs`.
24	fn id(&self) -> &str;
25	/// Visible tab label.
26	fn title(&self) -> &str;
27	/// Whether the pane's tab shows a close button.
28	fn closable(&self) -> bool {
29		true
30	}
31	/// Per-frame update. `delta_ms` is the frame time in milliseconds.
32	fn update(&mut self, _delta_ms: f32) -> Result<()> {
33		Ok(())
34	}
35	/// Render the item inside `rect`, clipped to the pane's panel scope.
36	fn render(&mut self, ui: &mut Ui<'_>, rect: PixelRect) -> Result<()>;
37	/// Pointer events are routed to the leaf under the cursor; key and text
38	/// events are routed to the focused leaf (the last pane clicked).
39	fn on_event(&mut self, _event: &InputEvent) -> Result<()> {
40		Ok(())
41	}
42}
43
44/// One node of the serializable dock tree.
45#[derive(Clone, Debug)]
46pub enum WorkspaceNode {
47	/// Leaf pane: a tab bar over a set of item ids plus caller-owned tab state.
48	Tabs {
49		tabs: Vec<String>,
50		state: UiTabBarState,
51	},
52	/// Interior split: two children laid out by `direction` at `ratio`.
53	Split {
54		direction: UiDirection,
55		ratio: f32,
56		first: Box<WorkspaceNode>,
57		second: Box<WorkspaceNode>,
58	},
59}
60
61impl WorkspaceNode {
62	/// Leaf pane holding `tabs` with the first tab selected.
63	pub fn tabs(tabs: &[&str]) -> Self {
64		Self::Tabs {
65			tabs: tabs.iter().map(|t| (*t).to_owned()).collect(),
66			state: UiTabBarState::default(),
67		}
68	}
69
70	/// Split `first`/`second` at `ratio` along `direction`.
71	pub fn split(
72		direction: UiDirection,
73		ratio: f32,
74		first: WorkspaceNode,
75		second: WorkspaceNode,
76	) -> Self {
77		Self::Split {
78			direction,
79			ratio,
80			first: Box::new(first),
81			second: Box::new(second),
82		}
83	}
84
85	fn to_json_value(&self) -> Value {
86		match self {
87			Self::Tabs { tabs, state } => serde_json::json!({
88				"kind": "tabs",
89				"tabs": tabs,
90				"selected": state.selected,
91				"first_visible": state.first_visible,
92			}),
93			Self::Split {
94				direction,
95				ratio,
96				first,
97				second,
98			} => serde_json::json!({
99				"kind": "split",
100				"direction": match direction {
101					UiDirection::Row => "row",
102					UiDirection::Column => "column",
103				},
104				"ratio": ratio,
105				"first": first.to_json_value(),
106				"second": second.to_json_value(),
107			}),
108		}
109	}
110
111	fn from_json_value(value: &Value) -> Result<Self> {
112		let kind = value
113			.get("kind")
114			.and_then(Value::as_str)
115			.ok_or_else(|| Error::invalid_argument("workspace node is missing a string `kind`"))?;
116		match kind {
117			"tabs" => {
118				let tabs = value
119					.get("tabs")
120					.and_then(Value::as_array)
121					.ok_or_else(|| Error::invalid_argument("workspace tabs node needs a `tabs` array"))?
122					.iter()
123					.map(|t| {
124						t.as_str()
125							.map(str::to_owned)
126							.ok_or_else(|| Error::invalid_argument("workspace tab ids must be strings"))
127					})
128					.collect::<Result<Vec<String>>>()?;
129				let selected = value.get("selected").and_then(Value::as_i64).unwrap_or(0) as i32;
130				let first_visible = value
131					.get("first_visible")
132					.and_then(Value::as_i64)
133					.unwrap_or(0) as i32;
134				Ok(Self::Tabs {
135					tabs,
136					state: UiTabBarState {
137						selected,
138						first_visible,
139						..UiTabBarState::default()
140					},
141				})
142			}
143			"split" => {
144				let direction = match value.get("direction").and_then(Value::as_str) {
145					Some("row") => UiDirection::Row,
146					Some("column") => UiDirection::Column,
147					_ => {
148						return Err(Error::invalid_argument(
149							"workspace split direction must be `row` or `column`",
150						));
151					}
152				};
153				let ratio =
154					value.get("ratio").and_then(Value::as_f64).ok_or_else(|| {
155						Error::invalid_argument("workspace split node needs a numeric `ratio`")
156					})? as f32;
157				if !ratio.is_finite() {
158					return Err(Error::invalid_argument(
159						"workspace split ratio must be finite",
160					));
161				}
162				let first = value
163					.get("first")
164					.ok_or_else(|| Error::invalid_argument("workspace split node is missing `first`"))?;
165				let second = value
166					.get("second")
167					.ok_or_else(|| Error::invalid_argument("workspace split node is missing `second`"))?;
168				Ok(Self::Split {
169					direction,
170					ratio,
171					first: Box::new(Self::from_json_value(first)?),
172					second: Box::new(Self::from_json_value(second)?),
173				})
174			}
175			_ => Err(Error::invalid_argument(
176				"workspace node `kind` must be `tabs` or `split`",
177			)),
178		}
179	}
180}
181
182/// `Rc<RefCell<T>>` adapter: registers shared item state — the ownership
183/// pattern the Python bindings use for `FigureView` — as a workspace item.
184/// `id`/`title`/`closable` are snapshotted at construction because RefCell
185/// borrows cannot escape the trait's `&self` signatures; pane identity is
186/// treated as stable for the workspace's lifetime.
187pub struct SharedItem<T: WorkspaceItem> {
188	inner: std::rc::Rc<std::cell::RefCell<T>>,
189	id: String,
190	title: String,
191	closable: bool,
192}
193
194impl<T: WorkspaceItem> SharedItem<T> {
195	/// Snapshot the item's identity and register the shared state.
196	pub fn new(inner: std::rc::Rc<std::cell::RefCell<T>>) -> Self {
197		let (id, title, closable) = {
198			let borrowed = inner.borrow();
199			(
200				borrowed.id().to_owned(),
201				borrowed.title().to_owned(),
202				borrowed.closable(),
203			)
204		};
205		Self {
206			inner,
207			id,
208			title,
209			closable,
210		}
211	}
212}
213
214impl<T: WorkspaceItem> WorkspaceItem for SharedItem<T> {
215	fn id(&self) -> &str {
216		&self.id
217	}
218
219	fn title(&self) -> &str {
220		&self.title
221	}
222
223	fn closable(&self) -> bool {
224		self.closable
225	}
226
227	fn update(&mut self, delta_ms: f32) -> Result<()> {
228		self.inner.borrow_mut().update(delta_ms)
229	}
230
231	fn render(&mut self, ui: &mut Ui<'_>, rect: PixelRect) -> Result<()> {
232		self.inner.borrow_mut().render(ui, rect)
233	}
234
235	fn on_event(&mut self, event: &InputEvent) -> Result<()> {
236		self.inner.borrow_mut().on_event(event)
237	}
238}
239
240/// Editor-style dock host: a serializable node tree over registered items.
241///
242/// Implements [`ViewerLiveSource`] so a `Viewer` opened with
243/// `ViewerMode::Workspace` renders and routes through it unchanged; the
244/// dock layout round-trips through [`Workspace::to_json`] /
245/// [`Workspace::from_json`] as application-owned state.
246pub struct Workspace {
247	root: WorkspaceNode,
248	items: Vec<Box<dyn WorkspaceItem>>,
249	/// (item id, leaf rect) pairs from the last rendered frame; pointer events
250	/// are routed to the leaf whose rect contains the cursor.
251	hits: Vec<(String, PixelRect)>,
252	/// Leaf geometry from the current render pass; tab drops resolve against
253	/// these rects once the dock walk completes.
254	panes: Vec<PaneHit>,
255	/// Tab drops reported during the current render pass: (source leaf path,
256	/// dragged tab index, insertion index). Applied after traversal.
257	drops: Vec<(String, i32, i32)>,
258	/// Item that owns key/text events; set when a pane is clicked.
259	focused: Option<String>,
260}
261
262/// One rendered leaf pane's geometry.
263struct PaneHit {
264	/// Dock path of the leaf (`"ws"`, `"ws/0"`, `"ws/1"`, ...).
265	path: String,
266	/// Full leaf rectangle, tab bar included.
267	rect: PixelRect,
268	/// Tab-bar strip inside `rect`.
269	bar: PixelRect,
270}
271
272impl Workspace {
273	/// Empty workspace over `root`; register content with [`Workspace::add_item`].
274	pub fn new(root: WorkspaceNode) -> Self {
275		Self {
276			root,
277			items: Vec::new(),
278			hits: Vec::new(),
279			panes: Vec::new(),
280			drops: Vec::new(),
281			focused: None,
282		}
283	}
284
285	/// Replace the dock tree with a parsed layout document (see
286	/// [`Workspace::from_json`]); registered items are preserved.
287	pub fn set_layout(&mut self, json: &str) -> Result<()> {
288		self.root = Workspace::from_json(json)?.root;
289		Ok(())
290	}
291
292	/// Register `item` and append its id to the root tab set. Returns an
293	/// error when the root is a split — multi-pane docks place tabs through
294	/// [`Workspace::root_mut`] or [`Workspace::set_layout`].
295	pub fn open_tab(&mut self, item: Box<dyn WorkspaceItem>) -> Result<()> {
296		let id = item.id().to_owned();
297		self.add_item(item);
298		match &mut self.root {
299			WorkspaceNode::Tabs { tabs, state } => {
300				tabs.push(id);
301				if state.selected < 0 {
302					state.selected = 0;
303				}
304				Ok(())
305			}
306			WorkspaceNode::Split { .. } => Err(Error::invalid_argument(
307				"Workspace::open_tab needs a tabbed root; place tabs on a split dock through root_mut or set_layout",
308			)),
309		}
310	}
311
312	/// Borrow the dock tree.
313	pub fn root(&self) -> &WorkspaceNode {
314		&self.root
315	}
316
317	/// Mutably borrow the dock tree (e.g. to attach or detach panes).
318	pub fn root_mut(&mut self) -> &mut WorkspaceNode {
319		&mut self.root
320	}
321
322	/// Register pane content. Registering a second item under an existing id
323	/// replaces the previous entry.
324	pub fn add_item(&mut self, item: Box<dyn WorkspaceItem>) {
325		self.items.retain(|i| i.id() != item.id());
326		self.items.push(item);
327	}
328
329	/// Look up registered content by id.
330	pub fn item(&self, id: &str) -> Option<&dyn WorkspaceItem> {
331		self.items.iter().find(|i| i.id() == id).map(|i| &**i)
332	}
333
334	/// Mutably look up registered content by id.
335	pub fn item_mut(&mut self, id: &str) -> Option<&mut (dyn WorkspaceItem + '_)> {
336		for item in &mut self.items {
337			if item.id() == id {
338				return Some(&mut **item);
339			}
340		}
341		None
342	}
343
344	/// Registered item ids in registration order.
345	pub fn item_ids(&self) -> impl Iterator<Item = &str> {
346		self.items.iter().map(|i| i.id())
347	}
348
349	/// Serialize the dock tree (no item content) to a JSON document.
350	pub fn to_json(&self) -> Result<String> {
351		let document = serde_json::json!({
352			"version": 1,
353			"root": self.root.to_json_value(),
354		});
355		serde_json::to_string(&document)
356			.map_err(|e| Error::backend_failure("serde_json", "workspace layout encode", e))
357	}
358
359	/// Parse a document produced by [`Workspace::to_json`]. Tab ids are
360	/// preserved verbatim; items are registered separately and unresolved ids
361	/// render as disabled tabs until content arrives.
362	pub fn from_json(json: &str) -> Result<Self> {
363		let document: Value = serde_json::from_str(json)
364			.map_err(|e| Error::invalid_argument(format!("workspace layout JSON is malformed: {e}")))?;
365		let version = document.get("version").and_then(Value::as_u64).unwrap_or(0);
366		if version != 1 {
367			return Err(Error::invalid_argument(
368				"workspace layout version must be 1",
369			));
370		}
371		let root = document
372			.get("root")
373			.ok_or_else(|| Error::invalid_argument("workspace layout document is missing `root`"))?;
374		Ok(Self::new(WorkspaceNode::from_json_value(root)?))
375	}
376
377	/// Record one frame: walk the dock tree over `rect`, driving `split_pane`
378	/// and `tab_bar`, then render each leaf's selected item.
379	pub fn render(&mut self, ui: &mut Ui<'_>, rect: PixelRect) -> Result<()> {
380		self.hits.clear();
381		self.panes.clear();
382		self.drops.clear();
383		let pointer = [ui.input().pointer_x, ui.input().pointer_y];
384		let tab_drag_active = tab_drag_active(&self.root);
385		render_node(
386			&mut self.root,
387			&mut DockFrame {
388				items: &mut self.items,
389				hits: &mut self.hits,
390				panes: &mut self.panes,
391				drops: &mut self.drops,
392				tab_drag_active,
393				pointer,
394			},
395			ui,
396			rect,
397			"ws",
398		)?;
399		for (source, index, insert) in std::mem::take(&mut self.drops) {
400			self.apply_tab_drop(&source, index, insert, pointer);
401		}
402		Ok(())
403	}
404
405	/// Apply one released tab drag: dropping on another leaf's edge quarter
406	/// splits that leaf so the tab opens a new pane on that side; dropping on
407	/// its tab bar or center merges the tab into the leaf; dropping on the
408	/// source bar reorders in place; anywhere else cancels the move. A leaf
409	/// emptied by a completed move collapses out of the split tree.
410	fn apply_tab_drop(&mut self, source: &str, index: i32, insert: i32, pointer: [f32; 2]) {
411		let [px, py] = pointer;
412		let in_rect = |r: PixelRect| {
413			px >= r.x as f32
414				&& py >= r.y as f32
415				&& px < (r.x + r.w as i32) as f32
416				&& py < (r.y + r.h as i32) as f32
417		};
418		let Some(target) = self.panes.iter().find(|p| in_rect(p.rect)) else {
419			return;
420		};
421		if target.path == source && !in_rect(target.bar) {
422			// Dropped back onto the source leaf's content: no move.
423			return;
424		}
425		let target_path = target.path.clone();
426		let over_target_bar = in_rect(target.bar);
427		let zone = classify_zone(target.rect, px, py);
428
429		let Some(WorkspaceNode::Tabs { tabs, state }) = node_at_mut(&mut self.root, source) else {
430			return;
431		};
432		if index < 0 || index as usize >= tabs.len() {
433			return;
434		}
435		let id = tabs.remove(index as usize);
436		if state.selected >= tabs.len() as i32 {
437			state.selected = tabs.len() as i32 - 1;
438		}
439
440		if target_path == source {
441			// In-bar reorder: `insert` is a pre-removal boundary index.
442			let at = if insert > index { insert - 1 } else { insert };
443			tabs.insert(at.clamp(0, tabs.len() as i32) as usize, id);
444			state.selected = at.clamp(0, tabs.len() as i32 - 1);
445			return;
446		}
447		if !over_target_bar && zone != DropZone::Center {
448			// Edge zone: wrap the target leaf in a new split so the dragged
449			// tab opens a pane on that side.
450			let direction = match zone {
451				DropZone::Left | DropZone::Right => UiDirection::Row,
452				DropZone::Top | DropZone::Bottom | DropZone::Center => UiDirection::Column,
453			};
454			let leaf = WorkspaceNode::Tabs {
455				tabs: vec![id],
456				state: UiTabBarState::default(),
457			};
458			let Some(target_node) = node_at_mut(&mut self.root, &target_path) else {
459				return;
460			};
461			let existing = std::mem::replace(target_node, WorkspaceNode::tabs(&[]));
462			let (first, second) = if matches!(zone, DropZone::Left | DropZone::Top) {
463				(leaf, existing)
464			} else {
465				(existing, leaf)
466			};
467			*target_node = WorkspaceNode::Split {
468				direction,
469				ratio: 0.5,
470				first: Box::new(first),
471				second: Box::new(second),
472			};
473			collapse_empty(&mut self.root);
474			return;
475		}
476		let Some(WorkspaceNode::Tabs {
477			tabs: target_tabs,
478			state: target_state,
479		}) = node_at_mut(&mut self.root, &target_path)
480		else {
481			return;
482		};
483		let at = if over_target_bar {
484			// Mirror Ui::tab_bar's slot width so the drop lands where the
485			// insertion indicator was drawn.
486			let bar = self
487				.panes
488				.iter()
489				.find(|p| p.path == target_path)
490				.map(|p| p.bar)
491				.unwrap_or_default();
492			let tab_w = (bar.w as i32 / target_tabs.len().max(1) as i32).clamp(88, 220);
493			(((px - bar.x as f32) / tab_w as f32) + 0.5) as i32
494		} else {
495			target_tabs.len() as i32
496		};
497		target_tabs.insert(at.clamp(0, target_tabs.len() as i32) as usize, id);
498		target_state.selected = target_tabs.len() as i32 - 1;
499		collapse_empty(&mut self.root);
500	}
501
502	/// Route a UI-space input event: pointer events go to the leaf under the
503	/// cursor (and move focus there on press); key and text events go to the
504	/// focused leaf.
505	pub fn route_event(&mut self, event: &InputEvent) -> Result<()> {
506		let is_pointer = matches!(
507			event.kind,
508			InputEventKind::MouseDown
509				| InputEventKind::MouseUp
510				| InputEventKind::MouseMove
511				| InputEventKind::MouseScroll
512		);
513		let target = if is_pointer {
514			let hit = self
515				.hits
516				.iter()
517				.find(|(_, rect)| {
518					let px = event.mouse_x as i32;
519					let py = event.mouse_y as i32;
520					px >= rect.x && py >= rect.y && px < rect.x + rect.w as i32 && py < rect.y + rect.h as i32
521				})
522				.map(|(id, _)| id.clone());
523			if matches!(event.kind, InputEventKind::MouseDown)
524				&& event.button == 1
525				&& let Some(id) = &hit
526			{
527				self.focused = Some(id.clone());
528			}
529			hit.or_else(|| self.focused.clone())
530		} else {
531			self.focused.clone()
532		};
533		if let Some(id) = target
534			&& let Some(item) = self.item_mut(&id)
535		{
536			item.on_event(event)?;
537		}
538		Ok(())
539	}
540}
541
542impl Default for Workspace {
543	/// One empty tabbed root — the common "add views and run" dock.
544	fn default() -> Self {
545		Self::new(WorkspaceNode::tabs(&[]))
546	}
547}
548
549impl ViewerLiveSource for Workspace {
550	fn capabilities(&self) -> ViewerLiveCapabilities {
551		ViewerLiveCapabilities {
552			receives_events: true,
553			..ViewerLiveCapabilities::default()
554		}
555	}
556
557	fn open(&mut self, _engine: &Engine) -> Result<()> {
558		Ok(())
559	}
560
561	fn update(&mut self, delta_ms: f32) -> Result<()> {
562		for item in &mut self.items {
563			item.update(delta_ms)?;
564		}
565		Ok(())
566	}
567
568	fn render(&mut self, ui: &mut Ui<'_>, width: u32, height: u32) -> Result<()> {
569		Workspace::render(self, ui, PixelRect::new(0, 0, width, height))
570	}
571
572	fn on_event(&mut self, event: &InputEvent) -> Result<()> {
573		self.route_event(event)
574	}
575
576	fn close(&mut self) -> Result<()> {
577		Ok(())
578	}
579}
580
581/// Per-frame out-params threaded through the dock walk.
582struct DockFrame<'a> {
583	items: &'a mut [Box<dyn WorkspaceItem>],
584	hits: &'a mut Vec<(String, PixelRect)>,
585	panes: &'a mut Vec<PaneHit>,
586	drops: &'a mut Vec<(String, i32, i32)>,
587	/// Whether a tab is held anywhere in the dock; drives the drop-zone
588	/// preview on leaves other than the drag source.
589	tab_drag_active: bool,
590	/// UI-space pointer position for preview classification.
591	pointer: [f32; 2],
592}
593
594/// Where inside a leaf's rect a released tab drop lands.
595#[derive(Clone, Copy, PartialEq, Eq, Debug)]
596enum DropZone {
597	/// Split the leaf along the row axis with the dragged tab left of it.
598	Left,
599	/// Split the leaf along the row axis with the dragged tab right of it.
600	Right,
601	/// Split the leaf along the column axis with the dragged tab above it.
602	Top,
603	/// Split the leaf along the column axis with the dragged tab below it.
604	Bottom,
605	/// Merge into the leaf's tab set (tab bar or middle region).
606	Center,
607}
608
609/// Classify `px,py` inside `rect`: the outer quarter on each side is an
610/// edge-split zone (corners resolve to the deeper edge); the interior is
611/// the merge zone.
612fn classify_zone(rect: PixelRect, px: f32, py: f32) -> DropZone {
613	let x = px - rect.x as f32;
614	let y = py - rect.y as f32;
615	let w = rect.w as f32;
616	let h = rect.h as f32;
617	let edges = [
618		(w * 0.25 - x, DropZone::Left),
619		(x - w * 0.75, DropZone::Right),
620		(h * 0.25 - y, DropZone::Top),
621		(y - h * 0.75, DropZone::Bottom),
622	];
623	let (depth, zone) = edges
624		.iter()
625		.fold((f32::NEG_INFINITY, DropZone::Center), |best, &(d, z)| {
626			if d > best.0 { (d, z) } else { best }
627		});
628	if depth > 0.0 { zone } else { DropZone::Center }
629}
630
631/// Whether any leaf currently holds a pressed tab — the drag may still be
632/// inside its movement threshold, but the preview only shows when the
633/// pointer has already reached another leaf.
634fn tab_drag_active(node: &WorkspaceNode) -> bool {
635	match node {
636		WorkspaceNode::Tabs { state, .. } => state.drag_index >= 0,
637		WorkspaceNode::Split { first, second, .. } => tab_drag_active(first) || tab_drag_active(second),
638	}
639}
640
641/// Merge leaf panes left empty by a completed move out of the split tree;
642/// the root always keeps at least one node.
643fn collapse_empty(node: &mut WorkspaceNode) {
644	let WorkspaceNode::Split { first, second, .. } = node else {
645		return;
646	};
647	collapse_empty(first);
648	collapse_empty(second);
649	let first_empty = matches!(&**first, WorkspaceNode::Tabs { tabs, .. } if tabs.is_empty());
650	let second_empty = matches!(&**second, WorkspaceNode::Tabs { tabs, .. } if tabs.is_empty());
651	if second_empty {
652		*node = std::mem::replace(&mut **first, WorkspaceNode::tabs(&[]));
653	} else if first_empty {
654		*node = std::mem::replace(&mut **second, WorkspaceNode::tabs(&[]));
655	}
656}
657
658/// Half of `rect` on `zone`'s side — the region a new pane would occupy.
659fn zone_preview_rect(rect: PixelRect, zone: DropZone) -> PixelRect {
660	let half_w = rect.w / 2;
661	let half_h = rect.h / 2;
662	match zone {
663		DropZone::Left => PixelRect { w: half_w, ..rect },
664		DropZone::Right => PixelRect {
665			x: rect.x + (rect.w - half_w) as i32,
666			w: half_w,
667			..rect
668		},
669		DropZone::Top => PixelRect { h: half_h, ..rect },
670		DropZone::Bottom => PixelRect {
671			y: rect.y + (rect.h - half_h) as i32,
672			h: half_h,
673			..rect
674		},
675		DropZone::Center => rect,
676	}
677}
678
679/// Render one dock node. `path` is the stable widget-id prefix for this
680/// subtree position (`"ws"`, `"ws/0"`, `"ws/1"`, ...).
681fn render_node(
682	node: &mut WorkspaceNode,
683	frame: &mut DockFrame<'_>,
684	ui: &mut Ui<'_>,
685	rect: PixelRect,
686	path: &str,
687) -> Result<()> {
688	if rect.w == 0 || rect.h == 0 {
689		return Ok(());
690	}
691	match node {
692		WorkspaceNode::Tabs { tabs, state } => {
693			let bar_h = (28.0 * ui.content_scale()).round().max(1.0) as u32;
694			let bar_rect = PixelRect {
695				x: rect.x,
696				y: rect.y,
697				w: rect.w,
698				h: bar_h.min(rect.h),
699			};
700			let content_rect = PixelRect {
701				x: rect.x,
702				y: rect.y + bar_rect.h as i32,
703				w: rect.w,
704				h: rect.h.saturating_sub(bar_rect.h),
705			};
706			let tab_items: Vec<UiTabItem> = tabs
707				.iter()
708				.map(|id| {
709					let registered = frame.items.iter().find(|i| i.id() == id);
710					UiTabItem {
711						id: id.clone(),
712						label: registered
713							.map(|i| i.title().to_owned())
714							.unwrap_or_else(|| id.clone()),
715						dirty: false,
716						closable: registered.is_none_or(|i| i.closable()),
717						enabled: registered.is_some(),
718					}
719				})
720				.collect();
721			frame.panes.push(PaneHit {
722				path: path.to_owned(),
723				rect,
724				bar: bar_rect,
725			});
726			let result = ui.tab_bar(path, bar_rect, &tab_items, state);
727			if result.dropped {
728				frame
729					.drops
730					.push((path.to_owned(), result.dragged_index, result.drop_index));
731			}
732			if result.close_requested_index >= 0 && (result.close_requested_index as usize) < tabs.len() {
733				tabs.remove(result.close_requested_index as usize);
734				if state.selected >= tabs.len() as i32 {
735					state.selected = tabs.len() as i32 - 1;
736				}
737				return Ok(());
738			}
739			let selected = state.selected.clamp(0, tabs.len().saturating_sub(1) as i32);
740			if let Some(tab_id) = tabs.get(selected.max(0) as usize).cloned() {
741				frame.hits.push((tab_id.clone(), rect));
742				if let Some(item) = frame.items.iter_mut().find(|i| i.id() == tab_id) {
743					ui.begin_panel(&format!("{path}/pane"), content_rect);
744					let result = item.render(ui, content_rect);
745					ui.end_panel();
746					result?;
747				}
748			}
749			// Drop-zone preview: while a tab is held elsewhere, tint the
750			// region a release here would hand to the dragged tab.
751			let [px, py] = frame.pointer;
752			if frame.tab_drag_active
753				&& state.drag_index < 0
754				&& px >= rect.x as f32
755				&& px < (rect.x + rect.w as i32) as f32
756				&& py >= (rect.y + bar_rect.h as i32) as f32
757				&& py < (rect.y + rect.h as i32) as f32
758			{
759				let zone = classify_zone(rect, px, py);
760				let preview = zone_preview_rect(rect, zone);
761				let accent = ui.current_style().accent;
762				ui.rect_raw(preview, accent.with_alpha(0.18), preview, 4.0);
763				ui.rect_outline_raw(preview, accent.with_alpha(0.7), 1, preview);
764			}
765			Ok(())
766		}
767		WorkspaceNode::Split {
768			direction,
769			ratio,
770			first,
771			second,
772		} => {
773			let region = ui.split_pane(
774				path,
775				rect,
776				ratio,
777				UiSplitConfig {
778					direction: *direction,
779					handle_size: 4.0,
780					minimum_first: 96.0,
781					minimum_second: 96.0,
782					keyboard_step: 16.0,
783				},
784			);
785			render_node(first, frame, ui, region.first, &format!("{path}/0"))?;
786			render_node(second, frame, ui, region.second, &format!("{path}/1"))?;
787			Ok(())
788		}
789	}
790}
791
792/// Borrow the dock node at `path` (`"ws"`, `"ws/0"`, `"ws/1"`, ...), where
793/// each numeric segment selects a split child (`0` = first, `1` = second).
794fn node_at_mut<'a>(node: &'a mut WorkspaceNode, path: &str) -> Option<&'a mut WorkspaceNode> {
795	let mut cur = node;
796	for segment in path.split('/').skip(1) {
797		let WorkspaceNode::Split { first, second, .. } = cur else {
798			return None;
799		};
800		cur = match segment {
801			"0" => first,
802			"1" => second,
803			_ => return None,
804		};
805	}
806	Some(cur)
807}