Skip to main content

oa/ui/
type.rs

1//! UI types: PixelRect, layout primitives, UiStyle, widget and chrome records.
2//!
3//! Donor references: `oa/ui/canvas.h`, `oa/ui/style.h`, `oa/ui/event.h`
4
5// ── PixelRect ─────────────────────────────────────────────────────────────────
6
7/// Axis-aligned pixel rectangle in physical screen coordinates.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9pub struct PixelRect {
10	pub x: i32,
11	pub y: i32,
12	pub w: u32,
13	pub h: u32,
14}
15
16impl PixelRect {
17	pub const fn new(x: i32, y: i32, w: u32, h: u32) -> Self {
18		Self { x, y, w, h }
19	}
20
21	/// True when the rectangle has non-zero area.
22	pub const fn is_non_empty(&self) -> bool {
23		self.w > 0 && self.h > 0
24	}
25
26	/// True when `(px, py)` is inside this rectangle.
27	pub fn contains(&self, px: f32, py: f32) -> bool {
28		px >= self.x as f32
29			&& py >= self.y as f32
30			&& px < (self.x + self.w as i32) as f32
31			&& py < (self.y + self.h as i32) as f32
32	}
33
34	/// Return the bounding clip for `child` intersected with `self`.
35	pub fn clip(&self, child: &PixelRect) -> PixelRect {
36		let x0 = self.x.max(child.x);
37		let y0 = self.y.max(child.y);
38		let x1 = (self.x + self.w as i32).min(child.x + child.w as i32);
39		let y1 = (self.y + self.h as i32).min(child.y + child.h as i32);
40		if x1 <= x0 || y1 <= y0 {
41			return PixelRect::default();
42		}
43		PixelRect {
44			x: x0,
45			y: y0,
46			w: (x1 - x0) as u32,
47			h: (y1 - y0) as u32,
48		}
49	}
50}
51
52pub use super::type_gen::{
53	UiDropdownConfig, UiGridConfig, UiHeatmapConfig, UiPlotConfig, UiPopupConfig,
54	UiPropertyRowConfig, UiScrollConfig, UiSplitConfig, UiTabBarResult, UiTableConfig,
55	UiTooltipConfig, UiTreeRowConfig, UiTreeRowResult,
56};
57use crate::Color;
58
59// ── UiStyle ───────────────────────────────────────────────────────────────────
60
61/// Theme colors and metrics used by all widgets.
62#[derive(Clone, Debug)]
63pub struct UiStyle {
64	/// Panel / window background.
65	pub background: Color,
66	/// Widget surface (button, slider track).
67	pub surface: Color,
68	/// Hovered and held surfaces.
69	pub surface_hover: Color,
70	pub surface_active: Color,
71	/// Active/hovered widget accent.
72	pub accent: Color,
73	/// Hovered/held foreground accent.
74	pub accent_hover: Color,
75	/// Primary text color.
76	pub text: Color,
77	/// Secondary/muted text.
78	pub text_secondary: Color,
79	/// Disabled control text.
80	pub text_disabled: Color,
81	/// Widget border.
82	pub border: Color,
83	/// Strong visualization border.
84	pub border_strong: Color,
85	/// Figure/plot canvas background.
86	pub plot_background: Color,
87	/// Axes interior surface.
88	pub plot_surface: Color,
89	/// Plot grid line color.
90	pub plot_grid: Color,
91	/// Axes frame border.
92	pub plot_border: Color,
93	/// Data series palette; alpha-zero artist styles consume it in order.
94	pub data_palette: [Color; 6],
95	/// Widget corner radius in pixels.
96	pub corner_radius: f32,
97	/// Inner content padding in pixels.
98	pub padding: f32,
99	/// Base font size in pixels.
100	pub font_size: f32,
101}
102
103impl Default for UiStyle {
104	/// Realm dark theme — the `realm_dark` token preset
105	/// (`tool/gen/fn/schema/ui/ui_style.json`).
106	fn default() -> Self {
107		super::style_gen::ui_style_realm_dark()
108	}
109}
110
111impl UiStyle {
112	/// Realm light theme — the `realm_light` derived preset, peer resolution
113	/// of the same generated token schema.
114	pub fn realm_light() -> Self {
115		super::style_gen::ui_style_realm_light()
116	}
117
118	/// Donor media viewer palette (`oa::UiStyle::viewerDark`) — the
119	/// `viewer_dark` derived preset over the `realm_dark` token set.
120	pub fn viewer_dark() -> Self {
121		super::style_gen::ui_style_viewer_dark()
122	}
123}
124
125// ── Layout primitives ─────────────────────────────────────────────────────────
126
127/// Sizing policy for one layout axis.
128#[derive(Clone, Copy, Debug, Default)]
129pub enum UiSizing {
130	/// Expand to fill available parent space.
131	#[default]
132	Fill,
133	/// Fixed pixel size.
134	Fixed(f32),
135	/// Shrink-wrap content.
136	Hug,
137}
138
139/// Per-side padding in pixels.
140#[derive(Clone, Copy, Debug, Default)]
141pub struct UiEdge {
142	pub top: f32,
143	pub right: f32,
144	pub bottom: f32,
145	pub left: f32,
146}
147
148impl UiEdge {
149	pub const fn all(v: f32) -> Self {
150		Self {
151			top: v,
152			right: v,
153			bottom: v,
154			left: v,
155		}
156	}
157}
158
159/// Flow direction for a panel or row.
160#[derive(Clone, Copy, Debug, Default)]
161pub enum UiDirection {
162	#[default]
163	Column,
164	Row,
165}
166
167/// Alignment of children along the cross-axis.
168#[derive(Clone, Copy, Debug, Default)]
169pub enum UiAlign {
170	Start,
171	Center,
172	End,
173	#[default]
174	Stretch,
175}
176
177/// Layout descriptor passed to `begin_panel`.
178#[derive(Clone, Debug)]
179pub struct UiLayout {
180	pub direction: UiDirection,
181	pub align: UiAlign,
182	pub gap: f32,
183	pub padding: UiEdge,
184	pub width: UiSizing,
185	pub height: UiSizing,
186}
187
188impl Default for UiLayout {
189	fn default() -> Self {
190		Self {
191			direction: UiDirection::Column,
192			align: UiAlign::Stretch,
193			gap: 4.0,
194			padding: UiEdge::all(8.0),
195			width: UiSizing::Fill,
196			height: UiSizing::Hug,
197		}
198	}
199}
200
201// ── Tab bar ───────────────────────────────────────────────────────────────────
202
203/// A single tab entry passed to [`crate::ui::Ui::tab_bar`].
204///
205/// Donor: `oa::UiTabItem`.
206#[derive(Clone, Debug, Default)]
207pub struct UiTabItem {
208	/// Stable string identifier (not displayed).
209	pub id: String,
210	/// Visible tab label.
211	pub label: String,
212	/// Dirty indicator shown next to the label.
213	pub dirty: bool,
214	/// Whether the tab shows a close button.
215	pub closable: bool,
216	/// Whether the tab is enabled (greyed out when false).
217	pub enabled: bool,
218}
219
220impl UiTabItem {
221	pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
222		Self {
223			id: id.into(),
224			label: label.into(),
225			closable: true,
226			enabled: true,
227			dirty: false,
228		}
229	}
230}
231
232/// Caller-owned tab bar presentation state.
233///
234/// Donor: `oa::UiTabBarState`.
235#[derive(Clone, Debug)]
236pub struct UiTabBarState {
237	/// Index of the currently selected tab, or -1 for none.
238	pub selected: i32,
239	/// Index of the first visible tab (for overflow scrolling).
240	pub first_visible: i32,
241	/// Index of the tab held for drag-reorder, or -1.
242	pub drag_index: i32,
243	/// Pointer position where the current drag press started.
244	pub drag_origin: [f32; 2],
245}
246
247impl Default for UiTabBarState {
248	fn default() -> Self {
249		Self {
250			selected: 0,
251			first_visible: 0,
252			drag_index: -1,
253			drag_origin: [0.0; 2],
254		}
255	}
256}
257
258/// Caller-owned data-table presentation state.
259#[derive(Clone, Debug)]
260pub struct UiTableState {
261	/// Index of the selected row, or -1 for none.
262	pub selected: i32,
263}
264
265impl Default for UiTableState {
266	fn default() -> Self {
267		Self { selected: -1 }
268	}
269}
270
271// ── Tree row ──────────────────────────────────────────────────────────────────
272
273impl UiTreeRowConfig {
274	pub const fn new() -> Self {
275		Self {
276			depth: 0,
277			indent: 16,
278			disclosure_width: 18,
279			has_children: false,
280			open: false,
281			selected: false,
282			enabled: true,
283		}
284	}
285}
286
287// ── Node canvas ───────────────────────────────────────────────────────────────
288
289/// Caller-owned view state for a node-graph canvas.
290///
291/// Donor: `oa::NodeCanvasState`.
292#[derive(Clone, Debug)]
293pub struct NodeCanvasState {
294	/// World-space pan offset (origin of the viewport in world coords).
295	pub pan: [f32; 2],
296	/// Zoom factor (pixels per world unit).
297	pub zoom: f32,
298	/// Viewport dimensions in screen pixels.
299	pub view_size: [f32; 2],
300}
301
302impl Default for NodeCanvasState {
303	fn default() -> Self {
304		Self {
305			pan: [0.0, 0.0],
306			zoom: 1.0,
307			view_size: [0.0, 0.0],
308		}
309	}
310}
311
312/// World-space axis-aligned bounds for canvas hit tests and fit targets.
313///
314/// Donor: `oa::WorldAabb`.
315#[derive(Clone, Copy, Debug, Default)]
316pub struct WorldAabb {
317	pub min: [f32; 2],
318	pub max: [f32; 2],
319}
320
321impl WorldAabb {
322	/// Return whether the bounds are finite and strictly positive in extent.
323	#[must_use]
324	pub fn is_valid(&self) -> bool {
325		self.min[0].is_finite()
326			&& self.min[1].is_finite()
327			&& self.max[0].is_finite()
328			&& self.max[1].is_finite()
329			&& self.max[0] > self.min[0]
330			&& self.max[1] > self.min[1]
331	}
332
333	/// Return whether `point` lies inside the bounds.
334	#[must_use]
335	pub fn contains(&self, point: [f32; 2]) -> bool {
336		point[0] >= self.min[0]
337			&& point[0] <= self.max[0]
338			&& point[1] >= self.min[1]
339			&& point[1] <= self.max[1]
340	}
341
342	/// Return whether both bounds are valid and overlap.
343	#[must_use]
344	pub fn intersects(&self, other: &Self) -> bool {
345		self.is_valid()
346			&& other.is_valid()
347			&& self.min[0] < other.max[0]
348			&& self.max[0] > other.min[0]
349			&& self.min[1] < other.max[1]
350			&& self.max[1] > other.min[1]
351	}
352}
353
354/// Borrowed hit-test geometry for one node.
355///
356/// Donor: `oa::NodeCanvasHitItem`.
357#[derive(Clone, Copy, Debug)]
358pub struct NodeCanvasHitItem {
359	pub id: u64,
360	pub bounds: WorldAabb,
361	pub layer: i32,
362	pub enabled: bool,
363}
364
365/// The winning hit-test item and the resolved world point.
366///
367/// Donor: `oa::NodeCanvasHit`.
368#[derive(Clone, Copy, Debug, PartialEq)]
369pub struct NodeCanvasHit {
370	pub id: u64,
371	pub index: usize,
372	pub layer: i32,
373	pub world_point: [f32; 2],
374}
375
376/// Resolved grid spacing for one minor tier and its major cadences.
377///
378/// Donor: `oa::NodeCanvasGrid`.
379#[derive(Clone, Copy, Debug, PartialEq)]
380pub struct NodeCanvasGrid {
381	pub minor_world_step: f32,
382	pub minor_screen_step: f32,
383	pub origin_screen: [f32; 2],
384	pub major_every: u32,
385	pub super_major_every: u32,
386}
387
388/// Node-graph canvas navigation, coordinate mapping, and hit tests.
389///
390/// Caller-owned; passed to [`crate::ui::Ui::node_canvas_grid`] to render the
391/// background grid. Pan/zoom mutations cancel any running fit animation;
392/// `fit_to_view` starts one that `step_animation` advances.
393///
394/// Donor: `oa::NodeCanvas`.
395#[derive(Clone, Debug, Default)]
396pub struct NodeCanvas {
397	state: NodeCanvasState,
398	anim_start: NodeCanvasState,
399	anim_target: NodeCanvasState,
400	animating: bool,
401	anim_t: f32,
402}
403
404impl NodeCanvas {
405	pub const ZOOM_MIN: f32 = 0.05;
406	pub const ZOOM_MAX: f32 = 8.0;
407
408	pub fn new() -> Self {
409		Self::default()
410	}
411
412	/// Access the current canvas state.
413	pub const fn state(&self) -> &NodeCanvasState {
414		&self.state
415	}
416
417	/// Return whether a fit animation is still running.
418	#[must_use]
419	pub const fn is_animating(&self) -> bool {
420		self.animating
421	}
422
423	/// Replace the complete canvas state and cancel any animation.
424	///
425	/// # Errors
426	///
427	/// Returns an error for non-finite pan/view state, a zoom outside
428	/// [`Self::ZOOM_MIN`]..=[`Self::ZOOM_MAX`], or a non-positive view size.
429	pub fn set_state(&mut self, state: NodeCanvasState) -> crate::Result<()> {
430		if !is_valid_canvas_state(&state, true) {
431			return Err(crate::Error::invalid_argument(
432				"NodeCanvas::set_state requires finite pan, positive view size, and zoom in range",
433			));
434		}
435		self.anim_start = state.clone();
436		self.anim_target = state.clone();
437		self.state = state;
438		self.animating = false;
439		self.anim_t = 0.0;
440		Ok(())
441	}
442
443	/// Set the canvas view size (called once when the viewport is known).
444	///
445	/// # Errors
446	///
447	/// Returns an error for non-finite or non-positive dimensions.
448	pub fn set_view_size(&mut self, w: f32, h: f32) -> crate::Result<()> {
449		if !w.is_finite() || !h.is_finite() || w <= 0.0 || h <= 0.0 {
450			return Err(crate::Error::invalid_argument(
451				"NodeCanvas::set_view_size requires finite positive dimensions",
452			));
453		}
454		self.state.view_size = [w, h];
455		self.anim_start.view_size = self.state.view_size;
456		self.anim_target.view_size = self.state.view_size;
457		self.animating = false;
458		self.anim_t = 0.0;
459		Ok(())
460	}
461
462	/// Convert a world-space position to screen-space pixels.
463	#[must_use]
464	pub fn world_to_screen(&self, world: [f32; 2]) -> [f32; 2] {
465		[
466			(world[0] - self.state.pan[0]) * self.state.zoom + self.state.view_size[0] * 0.5,
467			(world[1] - self.state.pan[1]) * self.state.zoom + self.state.view_size[1] * 0.5,
468		]
469	}
470
471	/// Convert screen-space pixels to world-space coordinates.
472	#[must_use]
473	pub fn screen_to_world(&self, screen: [f32; 2]) -> [f32; 2] {
474		[
475			(screen[0] - self.state.view_size[0] * 0.5) / self.state.zoom + self.state.pan[0],
476			(screen[1] - self.state.view_size[1] * 0.5) / self.state.zoom + self.state.pan[1],
477		]
478	}
479
480	/// Return the world-space rectangle currently visible through the view.
481	#[must_use]
482	pub fn visible_world_rect(&self) -> WorldAabb {
483		let half = [
484			self.state.view_size[0] * 0.5 / self.state.zoom,
485			self.state.view_size[1] * 0.5 / self.state.zoom,
486		];
487		WorldAabb {
488			min: [self.state.pan[0] - half[0], self.state.pan[1] - half[1]],
489			max: [self.state.pan[0] + half[0], self.state.pan[1] + half[1]],
490		}
491	}
492
493	/// Find the topmost enabled item under a screen-space point.
494	///
495	/// Items are tested in order; on overlapping hits the item with the
496	/// highest layer wins, with later items breaking ties.
497	///
498	/// # Errors
499	///
500	/// Returns an error for invalid canvas state, a non-finite screen point,
501	/// zero item IDs, or invalid item bounds.
502	pub fn hit_test(
503		&self,
504		screen: [f32; 2],
505		items: &[NodeCanvasHitItem],
506	) -> crate::Result<Option<NodeCanvasHit>> {
507		if !is_valid_canvas_state(&self.state, true) {
508			return Err(invalid_canvas_state());
509		}
510		if !screen[0].is_finite() || !screen[1].is_finite() {
511			return Err(crate::Error::invalid_argument(
512				"NodeCanvas::hit_test requires a finite screen point",
513			));
514		}
515		for item in items {
516			if item.id == 0 || !item.bounds.is_valid() {
517				return Err(crate::Error::invalid_argument(
518					"NodeCanvas::hit_test requires non-zero IDs and valid bounds",
519				));
520			}
521		}
522		let world = self.screen_to_world(screen);
523		if !world[0].is_finite() || !world[1].is_finite() {
524			return Err(crate::Error::out_of_range(
525				"NodeCanvas::hit_test produced a non-finite world point",
526			));
527		}
528		let mut hit: Option<NodeCanvasHit> = None;
529		for (index, item) in items.iter().enumerate() {
530			if !item.enabled || !item.bounds.contains(world) {
531				continue;
532			}
533			if hit.is_none_or(|previous| item.layer >= previous.layer) {
534				hit = Some(NodeCanvasHit {
535					id: item.id,
536					index,
537					layer: item.layer,
538					world_point: world,
539				});
540			}
541		}
542		Ok(hit)
543	}
544
545	/// Resolve the visible minor grid tier and its major cadences.
546	///
547	/// The donor preserves a Maya-style decimal hierarchy: zooming out
548	/// promotes the minor tier by whole decades; zooming in never invents a
549	/// sub-base grid. Donor call defaults are `8.0` minimum screen spacing,
550	/// `10.0` base world step, `10` major, and `100` super-major.
551	///
552	/// # Errors
553	///
554	/// Returns an error for invalid canvas state, non-finite or out-of-range
555	/// spacing, or undivisible major/super-major tiers.
556	pub fn grid(
557		&self,
558		minimum_screen_spacing: f32,
559		base_world_step: f32,
560		major_every: u32,
561		super_major_every: u32,
562	) -> crate::Result<NodeCanvasGrid> {
563		if !is_valid_canvas_state(&self.state, true) {
564			return Err(invalid_canvas_state());
565		}
566		if !minimum_screen_spacing.is_finite()
567			|| !base_world_step.is_finite()
568			|| !(4.0..=512.0).contains(&minimum_screen_spacing)
569			|| base_world_step <= 0.0
570			|| !(2..=100).contains(&major_every)
571			|| super_major_every < major_every * 2
572			|| super_major_every > 10000
573			|| !super_major_every.is_multiple_of(major_every)
574		{
575			return Err(crate::Error::invalid_argument(
576				"NodeCanvas::grid requires finite spacing, a positive base step, and divisible major/super-major tiers",
577			));
578		}
579		let ratio =
580			f64::from(minimum_screen_spacing) / (f64::from(base_world_step) * f64::from(self.state.zoom));
581		let exponent = ratio.log10().ceil().max(0.0);
582		if !exponent.is_finite() || exponent < f64::from(i32::MIN) || exponent > f64::from(i32::MAX) {
583			return Err(crate::Error::out_of_range(
584				"NodeCanvas::grid spacing exponent is out of range",
585			));
586		}
587		let world_step = f64::from(base_world_step) * 10.0_f64.powf(exponent);
588		let screen_step = world_step * f64::from(self.state.zoom);
589		let origin = self.world_to_screen([0.0, 0.0]);
590		if !world_step.is_finite()
591			|| !screen_step.is_finite()
592			|| world_step <= 0.0
593			|| screen_step <= 0.0
594			|| world_step > f64::from(f32::MAX)
595			|| screen_step > f64::from(f32::MAX)
596			|| !origin[0].is_finite()
597			|| !origin[1].is_finite()
598		{
599			return Err(crate::Error::out_of_range(
600				"NodeCanvas::grid produced non-finite metrics",
601			));
602		}
603		Ok(NodeCanvasGrid {
604			minor_world_step: world_step as f32,
605			minor_screen_step: screen_step as f32,
606			origin_screen: origin,
607			major_every,
608			super_major_every,
609		})
610	}
611
612	/// Pan by a screen-space delta.
613	///
614	/// # Errors
615	///
616	/// Returns an error for invalid canvas state, a non-finite delta, or a
617	/// result outside the finite `f32` range.
618	pub fn pan(&mut self, delta_screen: [f32; 2]) -> crate::Result<()> {
619		if !is_valid_canvas_state(&self.state, false) {
620			return Err(invalid_canvas_state());
621		}
622		if !delta_screen[0].is_finite() || !delta_screen[1].is_finite() {
623			return Err(crate::Error::invalid_argument(
624				"NodeCanvas::pan requires a finite screen delta",
625			));
626		}
627		let next_x =
628			f64::from(self.state.pan[0]) - f64::from(delta_screen[0]) / f64::from(self.state.zoom);
629		let next_y =
630			f64::from(self.state.pan[1]) - f64::from(delta_screen[1]) / f64::from(self.state.zoom);
631		if !next_x.is_finite()
632			|| !next_y.is_finite()
633			|| next_x.abs() > f64::from(f32::MAX)
634			|| next_y.abs() > f64::from(f32::MAX)
635		{
636			return Err(crate::Error::out_of_range(
637				"NodeCanvas::pan result is out of range",
638			));
639		}
640		self.state.pan = [next_x as f32, next_y as f32];
641		self.animating = false;
642		self.anim_t = 0.0;
643		Ok(())
644	}
645
646	/// Zoom by `factor`, keeping the world point under `focus_screen` fixed.
647	///
648	/// # Errors
649	///
650	/// Returns an error for invalid canvas state, a non-positive or
651	/// non-finite factor, a non-finite focus, or an out-of-range result.
652	pub fn zoom_at(&mut self, factor: f32, focus_screen: [f32; 2]) -> crate::Result<()> {
653		if !is_valid_canvas_state(&self.state, false) {
654			return Err(invalid_canvas_state());
655		}
656		if !factor.is_finite()
657			|| factor <= 0.0
658			|| !focus_screen[0].is_finite()
659			|| !focus_screen[1].is_finite()
660		{
661			return Err(crate::Error::invalid_argument(
662				"NodeCanvas::zoom_at requires a finite positive factor and focus",
663			));
664		}
665		let previous = self.state.clone();
666		let world_before = self.screen_to_world(focus_screen);
667		if !world_before[0].is_finite() || !world_before[1].is_finite() {
668			return Err(crate::Error::out_of_range(
669				"NodeCanvas::zoom_at focus is outside the finite world range",
670			));
671		}
672		self.state.zoom = (self.state.zoom * factor).clamp(Self::ZOOM_MIN, Self::ZOOM_MAX);
673		let world_after = self.screen_to_world(focus_screen);
674		self.state.pan[0] -= world_after[0] - world_before[0];
675		self.state.pan[1] -= world_after[1] - world_before[1];
676		if !is_valid_canvas_state(&self.state, false) {
677			self.state = previous;
678			return Err(crate::Error::out_of_range(
679				"NodeCanvas::zoom_at result is out of range",
680			));
681		}
682		self.animating = false;
683		self.anim_t = 0.0;
684		Ok(())
685	}
686
687	/// Start a pan/zoom animation fitting `bounds` into the view.
688	///
689	/// # Errors
690	///
691	/// Returns an error for invalid canvas state, invalid bounds, or padding
692	/// that leaves no usable view area.
693	pub fn fit_to_view(&mut self, bounds: &WorldAabb, padding_pixels: f32) -> crate::Result<()> {
694		if !is_valid_canvas_state(&self.state, true) {
695			return Err(invalid_canvas_state());
696		}
697		if !bounds.is_valid()
698			|| !padding_pixels.is_finite()
699			|| padding_pixels < 0.0
700			|| padding_pixels * 2.0 >= self.state.view_size[0]
701			|| padding_pixels * 2.0 >= self.state.view_size[1]
702		{
703			return Err(crate::Error::invalid_argument(
704				"NodeCanvas::fit_to_view requires valid bounds and usable padding",
705			));
706		}
707		let extent_x = f64::from(bounds.max[0] - bounds.min[0]).max(1.0);
708		let extent_y = f64::from(bounds.max[1] - bounds.min[1]).max(1.0);
709		let mut target = self.state.clone();
710		target.pan = [
711			((f64::from(bounds.min[0]) + f64::from(bounds.max[0])) * 0.5) as f32,
712			((f64::from(bounds.min[1]) + f64::from(bounds.max[1])) * 0.5) as f32,
713		];
714		target.zoom = ((f64::from(self.state.view_size[0] - padding_pixels * 2.0) / extent_x)
715			.min(f64::from(self.state.view_size[1] - padding_pixels * 2.0) / extent_y)
716			as f32)
717			.clamp(Self::ZOOM_MIN, Self::ZOOM_MAX);
718		if !is_valid_canvas_state(&target, true) {
719			return Err(crate::Error::out_of_range(
720				"NodeCanvas::fit_to_view produced an invalid target",
721			));
722		}
723		self.anim_start = self.state.clone();
724		self.anim_target = target;
725		self.animating = true;
726		self.anim_t = 0.0;
727		Ok(())
728	}
729
730	/// Advance a running fit animation by `delta_ms` milliseconds.
731	///
732	/// A no-op when no animation is running. The donor eases with a smoothstep
733	/// over a 200 ms duration.
734	///
735	/// # Errors
736	///
737	/// Returns an error for a non-finite or negative delta.
738	pub fn step_animation(&mut self, delta_ms: f32) -> crate::Result<()> {
739		if !delta_ms.is_finite() || delta_ms < 0.0 {
740			return Err(crate::Error::invalid_argument(
741				"NodeCanvas::step_animation requires a finite non-negative delta",
742			));
743		}
744		if !self.animating {
745			return Ok(());
746		}
747		self.anim_t += delta_ms * 0.005;
748		if self.anim_t >= 1.0 {
749			self.state.pan = self.anim_target.pan;
750			self.state.zoom = self.anim_target.zoom;
751			self.animating = false;
752			self.anim_t = 1.0;
753			return Ok(());
754		}
755		let t = self.anim_t * self.anim_t * (3.0 - 2.0 * self.anim_t);
756		self.state.pan = [
757			self.anim_start.pan[0] + (self.anim_target.pan[0] - self.anim_start.pan[0]) * t,
758			self.anim_start.pan[1] + (self.anim_target.pan[1] - self.anim_start.pan[1]) * t,
759		];
760		self.state.zoom = self.anim_start.zoom + (self.anim_target.zoom - self.anim_start.zoom) * t;
761		Ok(())
762	}
763}
764
765fn is_valid_canvas_state(state: &NodeCanvasState, require_positive_view: bool) -> bool {
766	state.pan[0].is_finite()
767		&& state.pan[1].is_finite()
768		&& state.view_size[0].is_finite()
769		&& state.view_size[1].is_finite()
770		&& state.zoom.is_finite()
771		&& (NodeCanvas::ZOOM_MIN..=NodeCanvas::ZOOM_MAX).contains(&state.zoom)
772		&& if require_positive_view {
773			state.view_size[0] > 0.0 && state.view_size[1] > 0.0
774		} else {
775			state.view_size[0] >= 0.0 && state.view_size[1] >= 0.0
776		}
777}
778
779fn invalid_canvas_state() -> crate::Error {
780	crate::Error::failed_precondition(
781		"NodeCanvas requires finite pan/view state and an admitted zoom",
782	)
783}
784
785// ── UiScrollConfig / UiScrollRegion ─────────────────────────────────────────
786
787impl Default for UiScrollConfig {
788	fn default() -> Self {
789		Self {
790			wheel_step: 40.0,
791			scrollbar_width: 6.0,
792			scrollbar_gap: 2.0,
793			show_scrollbar: true,
794		}
795	}
796}
797
798/// Return value from [`crate::ui::Ui::begin_scroll_panel`].
799///
800/// Donor: `oa::UiScrollRegion`.
801#[derive(Clone, Debug, Default)]
802pub struct UiScrollRegion {
803	/// Visible viewport rectangle.
804	pub viewport: PixelRect,
805	/// Content area rectangle (may extend below viewport).
806	pub content: PixelRect,
807	/// Current vertical scroll offset in pixels.
808	pub offset_y: i32,
809	/// Maximum reachable vertical offset.
810	pub max_offset_y: i32,
811}
812
813// ── UiVirtualRange ───────────────────────────────────────────────────────────
814
815/// Half-open row range produced by [`crate::ui::Ui::virtual_rows`].
816///
817/// Donor: `oa::UiVirtualRange`.
818#[derive(Clone, Copy, Debug, Default)]
819pub struct UiVirtualRange {
820	/// Index of the first row to render.
821	pub first: i32,
822	/// One past the last row to render.
823	pub one_past_last: i32,
824}
825
826impl UiVirtualRange {
827	/// True when no rows are in range.
828	pub fn is_empty(self) -> bool {
829		self.one_past_last <= self.first
830	}
831}
832
833// ── UiSplitConfig / UiSplitRegion ────────────────────────────────────────────
834
835impl Default for UiSplitConfig {
836	fn default() -> Self {
837		Self {
838			direction: super::types::UiDirection::Row,
839			handle_size: 4.0,
840			minimum_first: 60.0,
841			minimum_second: 60.0,
842			keyboard_step: 8.0,
843		}
844	}
845}
846
847/// Return value from [`crate::ui::Ui::split_pane`].
848///
849/// Donor: `oa::UiSplitRegion`.
850#[derive(Clone, Debug, Default)]
851pub struct UiSplitRegion {
852	/// Bounds of the first (top or left) pane.
853	pub first: PixelRect,
854	/// Bounds of the drag handle.
855	pub handle: PixelRect,
856	/// Bounds of the second (bottom or right) pane.
857	pub second: PixelRect,
858	/// Whether the ratio changed this frame.
859	pub changed: bool,
860}
861
862// ── UiPropertyRowConfig / UiPropertyRegion ───────────────────────────────────
863
864impl Default for UiPropertyRowConfig {
865	fn default() -> Self {
866		Self {
867			label_fraction: 0.40,
868			gap: 4.0,
869			padding_x: 4.0,
870			alternate: false,
871		}
872	}
873}
874
875/// Return value from [`crate::ui::Ui::property_row`].
876///
877/// Donor: `oa::UiPropertyRegion`.
878#[derive(Clone, Debug, Default)]
879pub struct UiPropertyRegion {
880	/// Full row rectangle.
881	pub row: PixelRect,
882	/// Label sub-rectangle.
883	pub label: PixelRect,
884	/// Value sub-rectangle.
885	pub value: PixelRect,
886}
887
888// ── UiPopupConfig ────────────────────────────────────────────────────────────
889
890impl Default for UiPopupConfig {
891	fn default() -> Self {
892		Self {
893			width: 160.0,
894			height: 0.0,
895			gap: 2.0,
896			padding: 6.0,
897		}
898	}
899}
900
901// ── UiDropdownConfig ─────────────────────────────────────────────────────────
902
903impl Default for UiDropdownConfig {
904	fn default() -> Self {
905		Self {
906			max_visible_items: 8,
907			popup_width: 0.0,
908			popup_gap: 2.0,
909		}
910	}
911}
912
913// ── UiTooltipConfig ──────────────────────────────────────────────────────────
914
915impl Default for UiTooltipConfig {
916	fn default() -> Self {
917		Self {
918			delay_ms: 400.0,
919			max_width: 240.0,
920			gap: 8.0,
921			padding: 6.0,
922		}
923	}
924}
925
926// ── UiHeatmapConfig ──────────────────────────────────────────────────────────
927
928impl Default for UiHeatmapConfig {
929	fn default() -> Self {
930		Self {
931			rows: 1,
932			cols: 1,
933			v_min: 0.0,
934			v_max: 1.0,
935			colormap: 1,
936			auto_scale: true,
937			show_grid: false,
938		}
939	}
940}
941
942// ── UiGridConfig ─────────────────────────────────────────────────────────────
943
944impl Default for UiGridConfig {
945	fn default() -> Self {
946		let automatic = Color::new(0.0, 0.0, 0.0, 0.0);
947		Self {
948			origin: [0.0; 2],
949			minor_spacing: [10.0; 2],
950			major_every: 10,
951			super_major_every: 100,
952			minor_thickness: 0.65,
953			major_thickness: 0.90,
954			super_major_thickness: 1.0,
955			axis_thickness: 1.25,
956			opacity: 1.0,
957			guide_fade_center: [0.0; 2],
958			guide_fade_inner_radius: 0.0,
959			guide_fade_outer_radius: 1.0,
960			background_top: automatic,
961			background_bottom: automatic,
962			minor_color: automatic,
963			major_color: automatic,
964			super_major_color: automatic,
965			axis_color: automatic,
966			fill_background: true,
967			draw_grid: true,
968			draw_axes: true,
969			radial_guide_fade: false,
970			dither_background: false,
971		}
972	}
973}
974
975// ── UiPlotConfig ─────────────────────────────────────────────────────────────
976
977impl Default for UiPlotConfig {
978	fn default() -> Self {
979		Self {
980			color: Color::new(0.388, 0.400, 0.945, 1.0),
981			x_min: 0.0,
982			x_max: 1.0,
983			y_min: 0.0,
984			y_max: 1.0,
985			auto_scale: true,
986			show_grid: true,
987			fill: false,
988			antialias_samples: 4,
989			line_width: 1.35,
990			draw_surface: true,
991		}
992	}
993}
994
995// ── UiIcon ───────────────────────────────────────────────────────────────────
996
997/// Named icon for icon-button widgets.
998///
999/// Donor: `oa::UiIcon`.
1000#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1001pub enum UiIcon {
1002	#[default]
1003	Previous,
1004	Next,
1005	Play,
1006	Pause,
1007	Menu,
1008	Minimize,
1009	Maximize,
1010	Restore,
1011	Close,
1012	Fullscreen,
1013	ExitFullscreen,
1014	Volume,
1015	Muted,
1016	Settings,
1017}
1018
1019/// Display style for an icon button.
1020///
1021/// Donor: `oa::UiIconButtonStyle`.
1022#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1023pub enum UiIconButtonStyle {
1024	/// Semi-transparent overlay (e.g. video transport controls).
1025	#[default]
1026	Overlay,
1027	/// Inline header button.
1028	Header,
1029	/// Window chrome control (min/max/close).
1030	WindowControl,
1031}
1032
1033/// Direction for a chevron button.
1034///
1035/// Donor: `oa::UiChevronDirection`.
1036#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1037pub enum UiChevronDirection {
1038	#[default]
1039	Previous,
1040	Next,
1041}
1042
1043// ── UiAccessibility ──────────────────────────────────────────────────────────
1044
1045/// Accessibility role for a widget.
1046///
1047/// Donor: `oa::UiAccessibilityRole`.
1048#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1049pub enum UiAccessibilityRole {
1050	#[default]
1051	Button,
1052	Checkbox,
1053	Slider,
1054	TextField,
1055	ComboBox,
1056	MenuItem,
1057	Tab,
1058	TreeItem,
1059	Splitter,
1060	Timeline,
1061}
1062
1063/// Opaque accessibility snapshot — a flat list of node descriptors.
1064///
1065/// Donor: `oa::Ui::accessibilitySnapshot` return.
1066#[derive(Clone, Debug, Default)]
1067pub struct UiAccessibilitySnapshot {
1068	/// Number of nodes in the snapshot.
1069	pub node_count: usize,
1070}