1mod bindings;
24pub(crate) mod command;
25mod compose_image;
26mod cv;
27mod detection_overlay;
28mod icons;
29mod image;
30mod layout;
31#[path = "ui/style.gen.rs"]
32mod style_gen;
33mod text;
34#[path = "ui/type.gen.rs"]
35mod type_gen;
36#[path = "ui/type.rs"]
37pub mod types;
38mod viewport;
39
40use crate::Color;
41use crate::input::{
42 GAMEPAD_AXIS_LEFT_X, GAMEPAD_AXIS_LEFT_Y, GAMEPAD_BUTTON_DPAD_DOWN, GAMEPAD_BUTTON_DPAD_LEFT,
43 GAMEPAD_BUTTON_DPAD_RIGHT, GAMEPAD_BUTTON_DPAD_UP, GAMEPAD_BUTTON_EAST, GAMEPAD_BUTTON_SOUTH,
44 InputEvent, InputEventKind, InputState, Key, MotionSpeed,
45};
46use crate::runtime::UiPipelines;
47use crate::{
48 Error, Result,
49 runtime::{RenderingCommands, RuntimeHandle, SyncCommands},
50};
51use bindings::UiFrameBindings;
52use command::{UiCmd, UiCmdList};
53use compose_image::ComposeImage;
54pub use cv::{CvBbox, CvFrame, CvOverlay};
55pub use detection_overlay::{DetectionOverlay, DetectionOverlayItem};
56pub use image::{IMAGE_MAX_PLANES, ImageDtype, ImagePlanes};
57use layout::{LayoutStack, PanelScope, default_item_height, resolve_width, separator_rect};
58pub use text::{FontId, GlyphBuffer, GlyphInstance, PositionedGlyph, TextAtlas, TextLayout};
59pub use type_gen::{
60 CvBboxesConfig, DetectionOverlayConfig, GlyphInfo, TextLayoutConfig, UiDropdownConfig,
61 UiGridConfig, UiHeatmapConfig, UiPlotConfig, UiPopupConfig, UiPropertyRowConfig, UiScrollConfig,
62 UiSplitConfig, UiTabBarResult, UiTableConfig, UiTooltipConfig, UiTreeRowConfig, UiTreeRowResult,
63};
64pub use types::{
65 NodeCanvas, NodeCanvasGrid, NodeCanvasHit, NodeCanvasHitItem, NodeCanvasState, PixelRect,
66 UiAccessibilityRole, UiAccessibilitySnapshot, UiAlign, UiChevronDirection, UiDirection, UiEdge,
67 UiIcon, UiIconButtonStyle, UiLayout, UiPropertyRegion, UiScrollRegion, UiSizing, UiSplitRegion,
68 UiStyle, UiTabBarState, UiTabItem, UiTableState, UiVirtualRange, WorldAabb,
69};
70pub use viewport::{RenderLayer, ScissorDesc, Viewport, ViewportDesc, ViewportMode};
71
72pub struct Ui<'runtime> {
79 runtime: &'runtime crate::Runtime,
80 pub(crate) state: Option<UiState>,
81}
82
83struct WidgetMotion {
84 start: f32,
85 current: f32,
86 target: f32,
87 elapsed_ms: f32,
88 last_seen: u64,
89}
90
91pub(crate) struct UiState {
92 pub(crate) runtime: RuntimeHandle,
93 sync_commands: SyncCommands,
95 rendering_commands: RenderingCommands,
96 pipelines: std::rc::Rc<UiPipelines>,
97 compose: std::rc::Rc<ComposeImage>,
98 text_atlas: std::rc::Rc<TextAtlas>,
99 style_stack: Vec<UiStyle>,
100 layout: LayoutStack,
101 pub(crate) cmds: UiCmdList,
102 input: InputState,
103 content_scale: f32,
104 motion_speed: MotionSpeed,
105 frame_delta_ms: f32,
106 frame_index: u64,
107 widget_motion: std::collections::HashMap<u64, WidgetMotion>,
108 focused: u64,
110 hovered: u64,
112 pressed: u64,
114 press_origin: [f32; 2],
116 drag: Option<UiDrag>,
118 frame_matrices: Vec<crate::Matrix>,
120 frame_textures: Vec<crate::Texture>,
121 frame_storages: Vec<crate::runtime::Storage>,
122 in_frame: bool,
124 input_pending_chars: Vec<char>,
126 input_pending_backspace: u32,
128 input_pending_dir: [i32; 2],
130 input_pending_activate: u32,
132 pad_axis_dir: [i32; 2],
134 focusables: Vec<u64>,
136 ime_rect: Option<PixelRect>,
138 input_preedit: String,
141 recording_error: Option<Error>,
143 popup_open: u64,
145 popup_anchor: PixelRect,
147 scroll_offsets: std::collections::HashMap<u64, i32>,
149}
150
151impl<'runtime> Ui<'runtime> {
152 pub fn init(runtime: &'runtime crate::Runtime, width: u32, height: u32) -> Result<Self> {
156 Self::init_with_style(runtime, width, height, UiStyle::default())
157 }
158
159 pub fn init_with_style(
161 runtime: &'runtime crate::Runtime,
162 width: u32,
163 height: u32,
164 style: UiStyle,
165 ) -> Result<Self> {
166 if width == 0 || height == 0 {
167 return Err(Error::invalid_argument(
168 "Ui compose extent must be non-zero",
169 ));
170 }
171 let handle = runtime.handle();
172 handle.require_ui_bindings()?;
173 let compose = {
174 let device = handle.raw_device();
175 let pipelines =
176 std::rc::Rc::new(handle.with_pipeline_cache(|cache| UiPipelines::new(&device, cache))?);
177 let compose = std::rc::Rc::new(ComposeImage::new(&handle, width, height)?);
178 let text_atlas = std::rc::Rc::new(TextAtlas::new(&handle)?);
179 UiState {
180 sync_commands: handle.ui_sync_commands(),
181 rendering_commands: handle.ui_rendering_commands(),
182 runtime: handle,
183 pipelines,
184 compose,
185 text_atlas,
186 style_stack: vec![style],
187 layout: LayoutStack::default(),
188 cmds: UiCmdList::default(),
189 input: InputState::default(),
190 content_scale: 1.0,
191 motion_speed: MotionSpeed::Normal,
192 frame_delta_ms: 0.0,
193 frame_index: 0,
194 widget_motion: std::collections::HashMap::new(),
195 focused: 0,
196 hovered: 0,
197 pressed: 0,
198 press_origin: [0.0; 2],
199 drag: None,
200 frame_matrices: Vec::new(),
201 frame_textures: Vec::new(),
202 frame_storages: Vec::new(),
203 in_frame: false,
204 input_pending_chars: Vec::new(),
205 input_pending_backspace: 0,
206 input_pending_dir: [0; 2],
207 input_pending_activate: 0,
208 pad_axis_dir: [0; 2],
209 focusables: Vec::new(),
210 ime_rect: None,
211 input_preedit: String::new(),
212 recording_error: None,
213 popup_open: 0,
214 popup_anchor: PixelRect::default(),
215 scroll_offsets: std::collections::HashMap::new(),
216 }
217 };
218 Ok(Self {
219 runtime,
220 state: Some(compose),
221 })
222 }
223
224 pub fn resize(&mut self, width: u32, height: u32) -> Result<()> {
226 if width == 0 || height == 0 {
227 return Err(Error::invalid_argument(
228 "Ui compose extent must be non-zero",
229 ));
230 }
231 let state = self
232 .state
233 .as_mut()
234 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
235 let new_compose = ComposeImage::new(&state.runtime, width, height)?;
236 state.compose = std::rc::Rc::new(new_compose);
237 Ok(())
238 }
239
240 pub fn content_scale(&self) -> f32 {
242 self.state.as_ref().map_or(1.0, |state| state.content_scale)
243 }
244
245 pub fn set_content_scale(&mut self, scale: f32) -> Result<()> {
247 if !scale.is_finite() || scale <= 0.0 {
248 return Err(Error::invalid_argument(
249 "Ui content scale must be finite and positive",
250 ));
251 }
252 let state = self
253 .state
254 .as_mut()
255 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
256 state.content_scale = scale;
257 Ok(())
258 }
259
260 pub fn set_motion_speed(&mut self, speed: MotionSpeed) -> Result<()> {
262 let state = self
263 .state
264 .as_mut()
265 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
266 if state.motion_speed != speed {
267 state.motion_speed = speed;
268 for motion in state.widget_motion.values_mut() {
269 motion.start = motion.current;
270 motion.elapsed_ms = 0.0;
271 }
272 }
273 Ok(())
274 }
275
276 pub fn motion_speed(&self) -> MotionSpeed {
278 self
279 .state
280 .as_ref()
281 .map_or(MotionSpeed::Normal, |state| state.motion_speed)
282 }
283
284 pub fn begin_frame(&mut self, delta_ms: f32) {
288 let Some(state) = self.state.as_mut() else {
289 return;
290 };
291 state.frame_delta_ms = if delta_ms.is_finite() {
292 delta_ms.clamp(0.0, 1000.0)
293 } else {
294 0.0
295 };
296 state.frame_index = state.frame_index.wrapping_add(1);
297 state
298 .widget_motion
299 .retain(|_, motion| state.frame_index.wrapping_sub(motion.last_seen) <= 600);
300 state.frame_matrices.clear();
301 state.frame_textures.clear();
302 state.frame_storages.clear();
303 state.cmds.clear_all();
304 state.hovered = 0;
305 state.focusables.clear();
306 state.ime_rect = None;
307 state.in_frame = true;
308 let bg = state
310 .style_stack
311 .last()
312 .map_or(Color::new(0.0, 0.0, 0.0, 1.0), |s| s.background);
313 state.cmds.push(UiCmd::Clear { color: bg });
314 }
315
316 pub fn route_event(&mut self, event: &InputEvent) -> bool {
318 let Some(state) = self.state.as_mut() else {
319 return false;
320 };
321 match event.kind {
322 InputEventKind::MouseMove => {
323 state.input.pointer_x = event.mouse_x;
324 state.input.pointer_y = event.mouse_y;
325 state.input.mouse_x = event.mouse_x;
326 state.input.mouse_y = event.mouse_y;
327 state.input.mouse_dx = event.mouse_dx;
328 state.input.mouse_dy = event.mouse_dy;
329 }
330 InputEventKind::MouseDown => {
331 state.input.pointer_x = event.mouse_x;
332 state.input.pointer_y = event.mouse_y;
333 state.input.mouse_x = event.mouse_x;
334 state.input.mouse_y = event.mouse_y;
335 if event.button == 1 {
336 state.input.l_button = true;
337 state.input.pointer_down = true;
338 state.input.l_pressed = true;
339 state.input.l_click_count = event.click_count;
340 state.press_origin = [event.mouse_x, event.mouse_y];
341 } else if event.button == 2 {
342 state.input.m_button = true;
343 } else if event.button == 3 {
344 state.input.r_button = true;
345 }
346 if state.hovered != 0 && event.button == 1 {
348 state.pressed = state.hovered;
349 return true;
350 }
351 }
352 InputEventKind::MouseUp => {
353 state.input.pointer_x = event.mouse_x;
354 state.input.pointer_y = event.mouse_y;
355 if event.button == 1 {
356 state.input.l_button = false;
357 state.input.pointer_down = false;
358 state.input.l_released = true;
359 } else if event.button == 2 {
360 state.input.m_button = false;
361 } else if event.button == 3 {
362 state.input.r_button = false;
363 }
364 }
365 InputEventKind::MouseScroll => {
366 state.input.scroll_x += event.scroll_x;
367 state.input.scroll_y += event.scroll_y;
368 }
369 InputEventKind::KeyDown => {
370 state.input.modifiers = event.modifiers;
371 state.input.shift = event.shift();
372 state.input.ctrl = event.ctrl();
373 if event.key == Key::Tab {
374 if state.focusables.is_empty() {
376 return state.focused != 0;
377 }
378 let n = state.focusables.len() as i32;
379 let cur = state
380 .focusables
381 .iter()
382 .position(|id| *id == state.focused)
383 .map_or(-1, |i| i as i32);
384 let next = if event.shift() {
385 (cur - 1).rem_euclid(n)
386 } else {
387 (cur + 1).rem_euclid(n)
388 };
389 state.focused = state.focusables[next as usize];
390 return true;
391 }
392 if event.key == Key::Backspace && state.focused != 0 {
393 state.input_pending_backspace += 1;
394 return true;
395 }
396 if matches!(event.key, Key::Return | Key::KpEnter) && state.focused != 0 {
397 state.input_pending_chars.push('\n');
400 state.input_pending_activate += 1;
401 return true;
402 }
403 if matches!(event.key, Key::Space) && state.focused != 0 {
404 state.input_pending_activate += 1;
405 return true;
406 }
407 if matches!(event.key, Key::Left | Key::Right | Key::Up | Key::Down) && state.focused != 0 {
408 state.input_pending_dir = match event.key {
409 Key::Left => [-1, 0],
410 Key::Right => [1, 0],
411 Key::Up => [0, -1],
412 _ => [0, 1],
413 };
414 return true;
415 }
416 if event.key == Key::Escape {
417 state.focused = 0;
418 state.drag = None;
419 }
420 }
421 InputEventKind::KeyChar => {
422 if state.focused != 0 && !event.text.is_empty() {
424 state.input_pending_chars.extend(event.text.chars());
425 state.input_preedit.clear();
426 return true;
427 }
428 }
429 InputEventKind::TextEditing => {
430 if state.focused != 0 {
433 state.input_preedit = event.text.clone();
434 return true;
435 }
436 }
437 InputEventKind::KeyUp => {
438 state.input.modifiers = event.modifiers;
439 state.input.shift = event.shift();
440 state.input.ctrl = event.ctrl();
441 }
442 InputEventKind::GamepadButtonDown => {
443 if state.focused == 0 {
444 if matches!(event.gamepad_button, GAMEPAD_BUTTON_SOUTH) && !state.focusables.is_empty() {
446 state.focused = state.focusables[0];
447 return true;
448 }
449 return false;
450 }
451 match event.gamepad_button {
452 GAMEPAD_BUTTON_DPAD_UP => {
453 state.input_pending_dir = [0, -1];
454 return true;
455 }
456 GAMEPAD_BUTTON_DPAD_DOWN => {
457 state.input_pending_dir = [0, 1];
458 return true;
459 }
460 GAMEPAD_BUTTON_DPAD_LEFT => {
461 state.input_pending_dir = [-1, 0];
462 return true;
463 }
464 GAMEPAD_BUTTON_DPAD_RIGHT => {
465 state.input_pending_dir = [1, 0];
466 return true;
467 }
468 GAMEPAD_BUTTON_SOUTH => {
469 state.input_pending_activate += 1;
470 return true;
471 }
472 GAMEPAD_BUTTON_EAST => {
473 state.focused = 0;
474 state.drag = None;
475 return true;
476 }
477 _ => {}
478 }
479 }
480 InputEventKind::GamepadAxisMotion => {
481 let slot = match event.gamepad_axis {
484 GAMEPAD_AXIS_LEFT_X => 0,
485 GAMEPAD_AXIS_LEFT_Y => 1,
486 _ => return false,
487 };
488 let dir = (event.gamepad_value > 16_000) as i32 - (event.gamepad_value < -16_000) as i32;
489 let mut nav = false;
490 if dir != 0 && state.pad_axis_dir[slot] == 0 && state.focused != 0 {
491 state.input_pending_dir = if slot == 0 { [dir, 0] } else { [0, dir] };
492 nav = true;
493 }
494 if dir == 0 {
495 state.pad_axis_dir[slot] = 0;
496 } else if nav {
497 state.pad_axis_dir[slot] = dir;
498 }
499 return nav;
500 }
501 InputEventKind::WindowResize => {}
502 _ => {}
503 }
504 false
505 }
506
507 pub fn end_frame(&mut self) {
509 let Some(state) = self.state.as_mut() else {
510 return;
511 };
512 state.in_frame = false;
513 if state.input.l_released {
514 state.pressed = 0;
515 state.drag = None;
516 }
517 state.input.l_pressed = false;
518 state.input.l_released = false;
519 state.input.scroll_x = 0.0;
520 state.input.scroll_y = 0.0;
521 state.input_pending_chars.clear();
522 state.input_pending_backspace = 0;
523 state.input_pending_dir = [0; 2];
524 state.input_pending_activate = 0;
525 }
526
527 pub fn input(&self) -> &InputState {
529 self.state.as_ref().map_or(&InputState::EMPTY, |s| &s.input)
530 }
531
532 pub fn drag_source(&mut self, id: &str, rect: PixelRect) -> bool {
540 let Some(state) = self.state.as_mut() else {
541 return false;
542 };
543 let id = widget_hash(id, Some(rect));
544 if point_in_rect(state.input.pointer_x, state.input.pointer_y, rect) {
545 state.hovered = id;
546 }
547 if state.pressed != id || !state.input.pointer_down {
548 return false;
549 }
550 let dx = state.input.pointer_x - state.press_origin[0];
551 let dy = state.input.pointer_y - state.press_origin[1];
552 if dx * dx + dy * dy <= 16.0 {
553 return false;
554 }
555 if state.drag.is_none() {
556 state.drag = Some(UiDrag::default());
557 }
558 true
559 }
560
561 pub fn set_drag_payload<T: std::any::Any>(&mut self, kind: &str, payload: T) {
564 if let Some(state) = self.state.as_mut()
565 && let Some(drag) = state.drag.as_mut()
566 {
567 drag.payload = Some((
568 kind.to_owned(),
569 std::rc::Rc::new(payload) as std::rc::Rc<dyn std::any::Any>,
570 ));
571 }
572 }
573
574 pub fn drag_hovering(&self, rect: PixelRect, kind: &str) -> bool {
577 let Some(state) = self.state.as_ref() else {
578 return false;
579 };
580 state.input.pointer_down
581 && point_in_rect(state.input.pointer_x, state.input.pointer_y, rect)
582 && state
583 .drag
584 .as_ref()
585 .is_some_and(|drag| drag.payload.as_ref().is_some_and(|(k, _)| k == kind))
586 }
587
588 pub fn drag_drop<T: std::any::Any>(&self, rect: PixelRect, kind: &str) -> Option<std::rc::Rc<T>> {
593 let state = self.state.as_ref()?;
594 if state.input.pointer_down {
595 return None;
596 }
597 let (k, payload) = state.drag.as_ref()?.payload.as_ref()?;
598 if k != kind || !point_in_rect(state.input.pointer_x, state.input.pointer_y, rect) {
599 return None;
600 }
601 payload.clone().downcast::<T>().ok()
602 }
603
604 pub fn runtime(&self) -> &'runtime crate::Runtime {
606 self.runtime
607 }
608
609 pub fn push_style(&mut self, style: UiStyle) {
612 let Some(state) = self.state.as_mut() else {
613 return;
614 };
615 state.style_stack.push(style);
616 }
617
618 pub fn pop_style(&mut self) {
619 let Some(state) = self.state.as_mut() else {
620 return;
621 };
622 if state.style_stack.len() > 1 {
623 state.style_stack.pop();
624 }
625 }
626
627 fn current_style_ref(state: &UiState) -> &UiStyle {
628 state.style_stack.last().expect("style stack is non-empty")
629 }
630
631 fn compose_clip(state: &UiState, rect: PixelRect) -> PixelRect {
636 let bounds = PixelRect {
637 x: 0,
638 y: 0,
639 w: state.compose.width,
640 h: state.compose.height,
641 };
642 let clipped = bounds.clip(&rect);
643 state
644 .layout
645 .top()
646 .map_or(clipped, |scope| scope.clip().clip(&clipped))
647 }
648
649 #[must_use]
653 pub fn current_style(&self) -> UiStyle {
654 self.state.as_ref().map_or_else(UiStyle::default, |state| {
655 Self::current_style_ref(state).clone()
656 })
657 }
658
659 pub fn begin_panel(&mut self, _id: &str, rect: PixelRect) {
663 self.begin_panel_with_layout(_id, rect, UiLayout::default());
664 }
665
666 pub fn begin_panel_with_layout(&mut self, _id: &str, rect: PixelRect, layout: UiLayout) {
668 let Some(state) = self.state.as_mut() else {
669 return;
670 };
671 let style = Self::current_style_ref(state).clone();
672 let clip = state
673 .layout
674 .top()
675 .map_or(rect, |parent| parent.clip().clip(&rect));
676 state.cmds.push(UiCmd::Rect {
678 rect,
679 color: style.background,
680 clip,
681 corner_radius: style.corner_radius,
682 });
683 let mut scope = PanelScope::new(rect, layout);
684 scope.clip_override = Some(clip);
685 state.layout.push(scope);
686 }
687
688 pub fn end_panel(&mut self) {
690 let Some(state) = self.state.as_mut() else {
691 return;
692 };
693 state.layout.pop();
694 }
695
696 pub fn spacing(&mut self, pixels: f32) {
698 let Some(state) = self.state.as_mut() else {
699 return;
700 };
701 if let Some(scope) = state.layout.top_mut() {
702 match scope.layout.direction {
703 UiDirection::Column => scope.cursor[1] += pixels as i32,
704 UiDirection::Row => scope.cursor[0] += pixels as i32,
705 }
706 }
707 }
708
709 pub fn separator(&mut self) {
711 let Some(state) = self.state.as_mut() else {
712 return;
713 };
714 let (sep_rect, sep_clip) = {
715 let Some(scope) = state.layout.top() else {
716 return;
717 };
718 (separator_rect(scope), scope.clip())
719 };
720 let color = Self::current_style_ref(state).border;
721 state.cmds.push(UiCmd::Rect {
722 rect: sep_rect,
723 color,
724 clip: sep_clip,
725 corner_radius: 0.0,
726 });
727 if let Some(scope) = state.layout.top_mut() {
728 scope.allocate(sep_rect.w, sep_rect.h);
729 }
730 }
731
732 pub fn begin_row(&mut self) {
734 let Some(state) = self.state.as_mut() else {
735 return;
736 };
737 if let Some(parent) = state.layout.top() {
738 let row_rect = PixelRect {
739 x: parent.cursor[0],
740 y: parent.cursor[1],
741 w: parent.inner.w,
742 h: 0,
743 };
744 let row_layout = UiLayout {
745 direction: UiDirection::Row,
746 ..UiLayout::default()
747 };
748 state.layout.push(PanelScope::new(row_rect, row_layout));
749 }
750 }
751
752 pub fn end_row(&mut self) {
754 let Some(state) = self.state.as_mut() else {
755 return;
756 };
757 let row_h = state.layout.top().map_or(0, |s| s.row_width);
758 state.layout.pop();
759 if let Some(parent) = state.layout.top_mut() {
760 parent.cursor[1] += row_h as i32 + parent.layout.gap as i32;
761 }
762 }
763
764 pub fn button(&mut self, label: &str) -> bool {
768 let Some(state) = self.state.as_mut() else {
769 return false;
770 };
771 let style = Self::current_style_ref(state).clone();
772 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
773
774 let (rect, clip) = allocate_widget(state, style.padding);
775 state.focusables.push(id);
776
777 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
779 if hovered && state.input.l_pressed {
780 state.focused = id;
781 }
782 let activated = (hovered && was_pressed_and_released(state, id)) || take_activate(state, id);
783
784 if hovered {
785 state.hovered = id;
786 }
787
788 let bg = if state.pressed == id {
790 Color::new(
791 style.accent.r * 0.7,
792 style.accent.g * 0.7,
793 style.accent.b * 0.7,
794 1.0,
795 )
796 } else if hovered {
797 style.surface
798 } else {
799 Color::new(
800 style.surface.r * 0.85,
801 style.surface.g * 0.85,
802 style.surface.b * 0.85,
803 1.0,
804 )
805 };
806 state.cmds.push(UiCmd::Rect {
807 rect,
808 color: bg,
809 clip,
810 corner_radius: style.corner_radius,
811 });
812 state.cmds.push(UiCmd::RectOutline {
813 rect,
814 color: if state.focused == id {
815 style.accent
816 } else {
817 style.border
818 },
819 thickness: 1,
820 clip,
821 corner_radius: style.corner_radius,
822 });
823 let text_config = TextLayoutConfig {
824 font: FontId::SansSemibold,
825 size: style.font_size,
826 ..TextLayoutConfig::default()
827 };
828 Self::emit_text_or_record(state, label, rect, style.text, text_config);
829
830 activated
831 }
832
833 pub fn checkbox(&mut self, label: &str, value: &mut bool) -> bool {
835 let Some(state) = self.state.as_mut() else {
836 return false;
837 };
838 let style = Self::current_style_ref(state).clone();
839 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
840
841 let (rect, clip) = allocate_widget(state, style.padding);
842 state.focusables.push(id);
843 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
844 if hovered && state.input.l_pressed {
845 state.focused = id;
846 }
847 let activated = (hovered && was_pressed_and_released(state, id)) || take_activate(state, id);
848 if activated {
849 *value = !*value;
850 }
851 if hovered {
852 state.hovered = id;
853 }
854
855 let bg = if *value { style.accent } else { style.surface };
856 state.cmds.push(UiCmd::Rect {
857 rect,
858 color: bg,
859 clip,
860 corner_radius: style.corner_radius,
861 });
862 state.cmds.push(UiCmd::RectOutline {
863 rect,
864 color: if state.focused == id {
865 style.accent
866 } else {
867 style.border
868 },
869 thickness: 1,
870 clip,
871 corner_radius: style.corner_radius,
872 });
873 let text_config = TextLayoutConfig {
874 font: FontId::Sans,
875 size: style.font_size,
876 ..TextLayoutConfig::default()
877 };
878 Self::emit_text_or_record(state, label, rect, style.text, text_config);
879 activated
880 }
881
882 pub fn slider_f32(&mut self, label: &str, value: &mut f32, min: f32, max: f32) -> bool {
884 if min >= max {
885 return false;
886 }
887 let Some(state) = self.state.as_mut() else {
888 return false;
889 };
890 let style = Self::current_style_ref(state).clone();
891 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
892
893 let (rect, clip) = allocate_widget(state, style.padding);
894 state.focusables.push(id);
895 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
896 if hovered {
897 state.hovered = id;
898 }
899
900 let mut changed = false;
901 if state.pressed == id && state.input.pointer_down {
902 let fraction =
903 ((state.input.pointer_x - rect.x as f32) / rect.w.max(1) as f32).clamp(0.0, 1.0);
904 let new_val = min + fraction * (max - min);
905 if (*value - new_val).abs() > 1e-6 {
906 *value = new_val;
907 changed = true;
908 }
909 }
910 if hovered && state.input.pointer_down {
911 state.pressed = id;
912 state.focused = id;
913 }
914 let dir = take_dir(state, id);
915 if dir[0] != 0 {
916 *value = (*value + (max - min) * 0.02 * dir[0] as f32).clamp(min, max);
917 changed = true;
918 }
919
920 state.cmds.push(UiCmd::Rect {
922 rect,
923 color: style.surface,
924 clip,
925 corner_radius: style.corner_radius,
926 });
927 let fraction = ((*value - min) / (max - min)).clamp(0.0, 1.0);
929 let fill_w = (rect.w as f32 * fraction) as u32;
930 if fill_w > 0 {
931 let fill_rect = PixelRect {
932 x: rect.x,
933 y: rect.y,
934 w: fill_w,
935 h: rect.h,
936 };
937 state.cmds.push(UiCmd::Rect {
938 rect: fill_rect,
939 color: style.accent,
940 clip,
941 corner_radius: style.corner_radius,
942 });
943 }
944 if state.focused == id {
945 state.cmds.push(UiCmd::RectOutline {
946 rect,
947 color: style.accent,
948 thickness: 1,
949 clip,
950 corner_radius: style.corner_radius,
951 });
952 }
953 let text = format!("{label}: {:.3}", *value);
954 let text_config = TextLayoutConfig {
955 font: FontId::Mono,
956 size: style.font_size - 1.0,
957 ..TextLayoutConfig::default()
958 };
959 Self::emit_text_or_record(state, &text, rect, style.text, text_config);
960 changed
961 }
962
963 pub fn progress_bar(&mut self, fraction: f32) {
965 let overlay = if fraction.is_finite() {
966 format!("{:.0}%", fraction.clamp(0.0, 1.0) * 100.0)
967 } else {
968 String::new()
969 };
970 self.progress_bar_with_overlay(fraction, &overlay);
971 }
972
973 pub fn progress_bar_with_overlay(&mut self, fraction: f32, overlay: &str) {
975 let Some(state) = self.state.as_mut() else {
976 return;
977 };
978 let style = Self::current_style_ref(state).clone();
979 let (rect, clip) = allocate_widget(state, style.padding);
980 state.cmds.push(UiCmd::Rect {
982 rect,
983 color: style.surface,
984 clip,
985 corner_radius: style.corner_radius,
986 });
987 let fill_w = (rect.w as f32 * fraction.clamp(0.0, 1.0)) as u32;
989 if fill_w > 0 {
990 let fill_rect = PixelRect {
991 x: rect.x,
992 y: rect.y,
993 w: fill_w,
994 h: rect.h,
995 };
996 state.cmds.push(UiCmd::Rect {
997 rect: fill_rect,
998 color: style.accent,
999 clip,
1000 corner_radius: style.corner_radius,
1001 });
1002 }
1003 let text_config = TextLayoutConfig {
1004 font: FontId::Sans,
1005 size: style.font_size - 1.0,
1006 ..TextLayoutConfig::default()
1007 };
1008 Self::emit_text_or_record(state, overlay, rect, style.text, text_config);
1009 }
1010
1011 pub fn label(&mut self, text: &str) {
1018 let Some(state) = self.state.as_mut() else {
1019 return;
1020 };
1021 let style = Self::current_style_ref(state).clone();
1022 let (rect, _clip) = allocate_widget(state, style.padding);
1023 if rect.w == 0 || rect.h == 0 {
1024 return;
1025 }
1026 let cfg = TextLayoutConfig {
1027 font: FontId::SansSemibold,
1028 size: style.font_size,
1029 ..TextLayoutConfig::default()
1030 };
1031 Self::emit_text_or_record(state, text, rect, style.text_secondary, cfg);
1032 }
1033
1034 pub fn slider_i32(&mut self, label: &str, value: &mut i32, min: i32, max: i32) -> bool {
1038 if min >= max {
1039 return false;
1040 }
1041 let Some(state) = self.state.as_mut() else {
1042 return false;
1043 };
1044 let style = Self::current_style_ref(state).clone();
1045 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
1046
1047 let (rect, clip) = allocate_widget(state, style.padding);
1048 state.focusables.push(id);
1049 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
1050 if hovered {
1051 state.hovered = id;
1052 }
1053
1054 let mut changed = false;
1055 if state.pressed == id && state.input.pointer_down {
1056 let fraction =
1057 ((state.input.pointer_x - rect.x as f32) / rect.w.max(1) as f32).clamp(0.0, 1.0);
1058 let new_val = min + (fraction * (max - min) as f32).round() as i32;
1059 let new_val = new_val.clamp(min, max);
1060 if *value != new_val {
1061 *value = new_val;
1062 changed = true;
1063 }
1064 }
1065 if hovered && state.input.pointer_down {
1066 state.pressed = id;
1067 state.focused = id;
1068 }
1069 let dir = take_dir(state, id);
1070 if dir[0] != 0 {
1071 *value = (*value + dir[0]).clamp(min, max);
1072 changed = true;
1073 }
1074
1075 state.cmds.push(UiCmd::Rect {
1077 rect,
1078 color: style.surface,
1079 clip,
1080 corner_radius: style.corner_radius,
1081 });
1082 let fraction = ((*value - min) as f32 / (max - min) as f32).clamp(0.0, 1.0);
1084 let fill_w = (rect.w as f32 * fraction) as u32;
1085 if fill_w > 0 {
1086 state.cmds.push(UiCmd::Rect {
1087 rect: PixelRect {
1088 x: rect.x,
1089 y: rect.y,
1090 w: fill_w,
1091 h: rect.h,
1092 },
1093 color: style.accent,
1094 clip,
1095 corner_radius: style.corner_radius,
1096 });
1097 }
1098 if state.focused == id {
1099 state.cmds.push(UiCmd::RectOutline {
1100 rect,
1101 color: style.accent,
1102 thickness: 1,
1103 clip,
1104 corner_radius: style.corner_radius,
1105 });
1106 }
1107 let text = format!("{label}: {}", *value);
1108 let text_config = TextLayoutConfig {
1109 font: FontId::Mono,
1110 size: style.font_size - 1.0,
1111 ..TextLayoutConfig::default()
1112 };
1113 Self::emit_text_or_record(state, &text, rect, style.text, text_config);
1114 changed
1115 }
1116
1117 pub fn input_text(&mut self, label: &str, value: &mut String) -> bool {
1125 let Some(state) = self.state.as_mut() else {
1126 return false;
1127 };
1128 let style = Self::current_style_ref(state).clone();
1129 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
1130
1131 let (rect, clip) = allocate_widget(state, style.padding);
1132 state.focusables.push(id);
1133 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
1134 if hovered && state.input.l_pressed {
1135 state.focused = id;
1136 }
1137 let focused = state.focused == id;
1138
1139 let bg = if focused {
1141 style.surface
1142 } else {
1143 Color::new(
1144 style.surface.r * 0.75,
1145 style.surface.g * 0.75,
1146 style.surface.b * 0.75,
1147 1.0,
1148 )
1149 };
1150 state.cmds.push(UiCmd::Rect {
1151 rect,
1152 color: bg,
1153 clip,
1154 corner_radius: style.corner_radius,
1155 });
1156 let border_color = if focused { style.accent } else { style.border };
1157 state.cmds.push(UiCmd::RectOutline {
1158 rect,
1159 color: border_color,
1160 thickness: 1,
1161 clip,
1162 corner_radius: style.corner_radius,
1163 });
1164
1165 let cfg = TextLayoutConfig {
1168 font: FontId::Mono,
1169 size: style.font_size - 1.0,
1170 ..TextLayoutConfig::default()
1171 };
1172 let inner = PixelRect {
1173 x: rect.x + style.padding as i32,
1174 y: rect.y,
1175 w: rect.w.saturating_sub(style.padding as u32 * 2),
1176 h: rect.h,
1177 };
1178 let preedit;
1179 let shown: &str = if focused && !state.input_preedit.is_empty() {
1180 preedit = format!("{value}{}", state.input_preedit);
1181 &preedit
1182 } else {
1183 value
1184 };
1185 Self::emit_text_or_record(state, shown, inner, style.text, cfg);
1186 if focused {
1187 state.ime_rect = Some(inner);
1188 }
1189
1190 let mut changed = false;
1193 if focused {
1194 for ch in state.input_pending_chars.drain(..) {
1195 if ch == '\n' {
1196 continue;
1197 }
1198 value.push(ch);
1199 changed = true;
1200 }
1201 if state.input_pending_backspace > 0 {
1202 for _ in 0..state.input_pending_backspace {
1203 value.pop();
1204 }
1205 changed = state.input_pending_backspace > 0;
1206 }
1207 state.input_pending_backspace = 0;
1208 }
1209 changed
1210 }
1211
1212 pub fn input_text_multiline(&mut self, label: &str, value: &mut String, rows: u32) -> bool {
1219 let Some(state) = self.state.as_mut() else {
1220 return false;
1221 };
1222 let style = Self::current_style_ref(state).clone();
1223 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
1224 let line_h = (style.font_size + 4.0) as i32;
1225 let h = (rows.max(1) as i32 * line_h + 2 * style.padding as i32) as u32;
1226
1227 let (rect, clip) = allocate_widget_explicit(state, style.padding, h);
1228 state.focusables.push(id);
1229 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
1230 if hovered && state.input.l_pressed {
1231 state.focused = id;
1232 }
1233 let focused = state.focused == id;
1234
1235 let bg = if focused {
1236 style.surface
1237 } else {
1238 Color::new(
1239 style.surface.r * 0.75,
1240 style.surface.g * 0.75,
1241 style.surface.b * 0.75,
1242 1.0,
1243 )
1244 };
1245 state.cmds.push(UiCmd::Rect {
1246 rect,
1247 color: bg,
1248 clip,
1249 corner_radius: style.corner_radius,
1250 });
1251 state.cmds.push(UiCmd::RectOutline {
1252 rect,
1253 color: if focused { style.accent } else { style.border },
1254 thickness: 1,
1255 clip,
1256 corner_radius: style.corner_radius,
1257 });
1258
1259 let pad = style.padding as i32;
1260 let inner = PixelRect {
1261 x: rect.x + pad,
1262 y: rect.y + pad,
1263 w: rect.w.saturating_sub(pad as u32 * 2),
1264 h: rect.h.saturating_sub(pad as u32 * 2),
1265 };
1266 let cfg = TextLayoutConfig {
1267 font: FontId::Mono,
1268 size: style.font_size - 1.0,
1269 ..TextLayoutConfig::default()
1270 };
1271 let preedit;
1273 let shown: &str = if focused && !state.input_preedit.is_empty() {
1274 preedit = format!("{value}{}", state.input_preedit);
1275 &preedit
1276 } else {
1277 value
1278 };
1279 if focused {
1280 state.ime_rect = Some(inner);
1281 }
1282 for (i, line) in shown.split('\n').enumerate() {
1283 let line_rect = PixelRect {
1284 x: inner.x,
1285 y: inner.y + i as i32 * line_h,
1286 w: inner.w,
1287 h: line_h as u32,
1288 };
1289 if line_rect.y + line_rect.h as i32 > inner.y + inner.h as i32 {
1290 break;
1291 }
1292 Self::emit_text_or_record(state, line, line_rect, style.text, cfg);
1293 }
1294
1295 let mut changed = false;
1296 if focused {
1297 for ch in state.input_pending_chars.drain(..) {
1298 value.push(ch);
1299 changed = true;
1300 }
1301 for _ in 0..state.input_pending_backspace {
1302 value.pop();
1303 }
1304 changed |= state.input_pending_backspace > 0;
1305 state.input_pending_backspace = 0;
1306 }
1307 changed
1308 }
1309
1310 pub fn color_swatch(&mut self, color: Color, size: [f32; 2]) {
1315 let Some(state) = self.state.as_mut() else {
1316 return;
1317 };
1318 let style = Self::current_style_ref(state).clone();
1319 let clip = state.layout.top().map(|s| s.clip()).unwrap_or_default();
1320 let Some(scope) = state.layout.top_mut() else {
1321 return;
1322 };
1323 let w = size[0].max(1.0) as u32;
1324 let h = size[1].max(1.0) as u32;
1325 let rect = scope.allocate(w, h);
1326 state.cmds.push(UiCmd::Rect {
1327 rect,
1328 color,
1329 clip,
1330 corner_radius: style.corner_radius,
1331 });
1332 state.cmds.push(UiCmd::RectOutline {
1333 rect,
1334 color: style.border,
1335 thickness: 1,
1336 clip,
1337 corner_radius: style.corner_radius,
1338 });
1339 }
1340
1341 pub fn color_picker(&mut self, label: &str, value: &mut Color) -> bool {
1345 let Some(state) = self.state.as_mut() else {
1346 return false;
1347 };
1348 let style = Self::current_style_ref(state).clone();
1349 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
1350 let popup_id = widget_hash(&format!("__cp_{label}"), None);
1351
1352 let (rect, clip) = allocate_widget(state, style.padding);
1353 state.focusables.push(id);
1354 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
1355 if hovered {
1356 state.hovered = id;
1357 }
1358 if hovered && state.input.l_pressed {
1359 state.focused = id;
1360 }
1361 if (hovered && was_pressed_and_released(state, id)) || take_activate(state, id) {
1362 if state.popup_open == popup_id {
1363 state.popup_open = 0;
1364 } else {
1365 state.popup_open = popup_id;
1366 state.popup_anchor = rect;
1367 }
1368 }
1369
1370 state.cmds.push(UiCmd::Rect {
1372 rect,
1373 color: style.surface,
1374 clip,
1375 corner_radius: style.corner_radius,
1376 });
1377 state.cmds.push(UiCmd::RectOutline {
1378 rect,
1379 color: if state.popup_open == popup_id {
1380 style.accent
1381 } else {
1382 style.border
1383 },
1384 thickness: 1,
1385 clip,
1386 corner_radius: style.corner_radius,
1387 });
1388 let cfg = TextLayoutConfig {
1389 font: FontId::Sans,
1390 size: style.font_size - 1.0,
1391 ..Default::default()
1392 };
1393 Self::emit_text_or_record(state, label, rect, style.text, cfg);
1394 let swatch = PixelRect {
1395 x: rect.x + rect.w as i32 - (rect.h as i32 + 4),
1396 y: rect.y + 4,
1397 w: rect.h.saturating_sub(8),
1398 h: rect.h.saturating_sub(8),
1399 };
1400 state.cmds.push(UiCmd::Rect {
1401 rect: swatch,
1402 color: *value,
1403 clip,
1404 corner_radius: 2.0,
1405 });
1406 state.cmds.push(UiCmd::RectOutline {
1407 rect: swatch,
1408 color: style.border,
1409 thickness: 1,
1410 clip,
1411 corner_radius: 2.0,
1412 });
1413
1414 let is_open = state.popup_open == popup_id;
1415 let outside_click = is_open
1416 && state.input.l_pressed
1417 && !point_in_rect(
1418 state.input.pointer_x,
1419 state.input.pointer_y,
1420 PixelRect {
1421 x: rect.x,
1422 y: rect.y + rect.h as i32 + 2,
1423 w: rect.w,
1424 h: (5 * default_item_height(style.padding) as i32 + 40) as u32,
1425 },
1426 ) && !point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
1427 if outside_click {
1428 state.popup_open = 0;
1429 }
1430 let mut changed = false;
1431 if is_open && !outside_click {
1432 let item_h = default_item_height(style.padding);
1433 let popup_rect = PixelRect {
1434 x: rect.x,
1435 y: rect.y + rect.h as i32 + 2,
1436 w: rect.w,
1437 h: 5 * item_h + 40,
1438 };
1439 state.cmds.push(UiCmd::Rect {
1440 rect: popup_rect,
1441 color: style.background,
1442 clip: popup_rect,
1443 corner_radius: style.corner_radius,
1444 });
1445 state.cmds.push(UiCmd::RectOutline {
1446 rect: popup_rect,
1447 color: style.border,
1448 thickness: 1,
1449 clip: popup_rect,
1450 corner_radius: style.corner_radius,
1451 });
1452 let inner = PixelRect {
1453 x: popup_rect.x + 4,
1454 y: popup_rect.y + 4,
1455 w: popup_rect.w.saturating_sub(8),
1456 h: popup_rect.h.saturating_sub(8),
1457 };
1458 let preview_color = *value;
1459 self.begin_panel("__cpanel", inner);
1460 let Some(state) = self.state.as_mut() else {
1461 return changed;
1462 };
1463 let preview = state
1464 .layout
1465 .top_mut()
1466 .map(|s| s.allocate(inner.w, item_h))
1467 .unwrap_or(inner);
1468 state.cmds.push(UiCmd::Rect {
1469 rect: preview,
1470 color: preview_color,
1471 clip: inner,
1472 corner_radius: style.corner_radius,
1473 });
1474 changed |= self.slider_f32(&format!("{label} r"), &mut value.r, 0.0, 1.0);
1475 changed |= self.slider_f32(&format!("{label} g"), &mut value.g, 0.0, 1.0);
1476 changed |= self.slider_f32(&format!("{label} b"), &mut value.b, 0.0, 1.0);
1477 changed |= self.slider_f32(&format!("{label} a"), &mut value.a, 0.0, 1.0);
1478 self.end_panel();
1479 }
1480 changed
1481 }
1482
1483 pub fn tab_bar(
1487 &mut self,
1488 _id: &str,
1489 rect: PixelRect,
1490 items: &[UiTabItem],
1491 state_out: &mut UiTabBarState,
1492 ) -> UiTabBarResult {
1493 let mut result = UiTabBarResult {
1494 bar: rect,
1495 tabs: rect,
1496 first_visible: state_out.first_visible,
1497 one_past_last: items.len() as i32,
1498 activated_index: -1,
1499 close_requested_index: -1,
1500 selection_changed: false,
1501 dragged_index: -1,
1502 drop_index: -1,
1503 dropped: false,
1504 };
1505 let Some(state) = self.state.as_mut() else {
1506 return result;
1507 };
1508 let style = Self::current_style_ref(state).clone();
1509 let clip = rect;
1510 let bar_id = widget_hash(_id, Some(rect));
1511 state.focusables.push(bar_id);
1512 if point_in_rect(state.input.pointer_x, state.input.pointer_y, rect) && state.input.l_pressed {
1513 state.focused = bar_id;
1514 }
1515 let dir = take_dir(state, bar_id);
1516 if dir[0] != 0 && !items.is_empty() {
1517 let next = (state_out.selected + dir[0]).clamp(0, items.len() as i32 - 1);
1518 if next != state_out.selected {
1519 state_out.selected = next;
1520 result.selection_changed = true;
1521 }
1522 }
1523
1524 state.cmds.push(UiCmd::Rect {
1526 rect,
1527 color: style.background,
1528 clip,
1529 corner_radius: 0.0,
1530 });
1531 state.cmds.push(UiCmd::RectOutline {
1533 rect,
1534 color: if state.focused == bar_id {
1535 style.accent
1536 } else {
1537 style.border
1538 },
1539 thickness: 1,
1540 clip,
1541 corner_radius: 0.0,
1542 });
1543
1544 if items.is_empty() {
1545 return result;
1546 }
1547
1548 let tab_h = rect.h;
1549 let min_w: i32 = 88;
1550 let max_w: i32 = 220;
1551 let available_w = rect.w as i32;
1552 let n = items.len() as i32;
1553 let tab_w = (available_w / n).clamp(min_w, max_w);
1554
1555 let drag_id = (state_out.drag_index >= 0 && (state_out.drag_index as usize) < items.len())
1556 .then(|| widget_hash(&items[state_out.drag_index as usize].id, Some(rect)));
1557
1558 let mut x = rect.x;
1559 for (i, item) in items.iter().enumerate() {
1560 let i = i as i32;
1561 if i < state_out.first_visible {
1562 continue;
1563 }
1564 if x + tab_w > rect.x + rect.w as i32 {
1565 result.one_past_last = i;
1566 break;
1567 }
1568 let tab_rect = PixelRect {
1569 x,
1570 y: rect.y,
1571 w: tab_w as u32,
1572 h: tab_h,
1573 };
1574 let selected = state_out.selected == i;
1575 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, tab_rect);
1576
1577 let id = widget_hash(&item.id, Some(rect));
1579 let clicked = hovered && was_pressed_and_released(state, id);
1580 if hovered {
1581 state.hovered = id;
1582 }
1583 if hovered && state.input.pointer_down {
1584 state.pressed = id;
1585 }
1586 if hovered && state.input.l_pressed {
1587 state_out.drag_index = i;
1588 state_out.drag_origin = [state.input.pointer_x, state.input.pointer_y];
1589 }
1590 if clicked && state_out.selected != i {
1591 state_out.selected = i;
1592 result.activated_index = i;
1593 result.selection_changed = true;
1594 }
1595
1596 let bg = if selected {
1597 style.surface
1598 } else if hovered {
1599 Color::new(
1600 style.surface.r * 0.85,
1601 style.surface.g * 0.85,
1602 style.surface.b * 0.85,
1603 1.0,
1604 )
1605 } else {
1606 style.background
1607 };
1608 state.cmds.push(UiCmd::Rect {
1609 rect: tab_rect,
1610 color: bg,
1611 clip,
1612 corner_radius: 0.0,
1613 });
1614 if selected {
1615 let sel_line = PixelRect {
1617 x: tab_rect.x,
1618 y: tab_rect.y + tab_rect.h as i32 - 2,
1619 w: tab_rect.w,
1620 h: 2,
1621 };
1622 state.cmds.push(UiCmd::Rect {
1623 rect: sel_line,
1624 color: style.accent,
1625 clip,
1626 corner_radius: 0.0,
1627 });
1628 }
1629 state.cmds.push(UiCmd::RectOutline {
1631 rect: tab_rect,
1632 color: style.border,
1633 thickness: 1,
1634 clip,
1635 corner_radius: 0.0,
1636 });
1637
1638 let label_text = if item.dirty {
1640 format!("● {}", item.label)
1641 } else {
1642 item.label.clone()
1643 };
1644 let cfg = TextLayoutConfig {
1645 font: FontId::Sans,
1646 size: style.font_size - 1.0,
1647 ..TextLayoutConfig::default()
1648 };
1649 let text_color = if item.enabled {
1650 style.text
1651 } else {
1652 style.text_secondary
1653 };
1654 Self::emit_text_or_record(state, &label_text, tab_rect, text_color, cfg);
1655
1656 x += tab_w;
1657 }
1658
1659 if state_out.drag_index >= 0 {
1664 let dx = state.input.pointer_x - state_out.drag_origin[0];
1665 let dy = state.input.pointer_y - state_out.drag_origin[1];
1666 let past_threshold = dx * dx + dy * dy > 16.0;
1667 let target = (((state.input.pointer_x - rect.x as f32) / tab_w as f32) + 0.5) as i32;
1668 if let Some(drag_id) = drag_id
1669 && state.pressed == drag_id
1670 && state.input.pointer_down
1671 && past_threshold
1672 {
1673 result.dragged_index = state_out.drag_index;
1674 if point_in_rect(state.input.pointer_x, state.input.pointer_y, rect) {
1675 let line = PixelRect {
1676 x: rect.x + target.clamp(0, n) * tab_w - 1,
1677 y: rect.y,
1678 w: 2,
1679 h: rect.h,
1680 };
1681 state.cmds.push(UiCmd::Rect {
1682 rect: line,
1683 color: style.accent,
1684 clip,
1685 corner_radius: 0.0,
1686 });
1687 }
1688 }
1689 if !state.input.pointer_down {
1690 if past_threshold {
1691 result.dragged_index = state_out.drag_index;
1692 result.drop_index = target.clamp(0, n);
1693 result.dropped = true;
1694 }
1695 state_out.drag_index = -1;
1696 }
1697 }
1698
1699 result
1700 }
1701
1702 pub fn tree_row(
1706 &mut self,
1707 id: &str,
1708 rect: PixelRect,
1709 label: &str,
1710 config: UiTreeRowConfig,
1711 ) -> UiTreeRowResult {
1712 let mut result = UiTreeRowResult {
1713 row: rect,
1714 open: config.open,
1715 ..UiTreeRowResult::default()
1716 };
1717 let Some(state) = self.state.as_mut() else {
1718 return result;
1719 };
1720 let style = Self::current_style_ref(state).clone();
1721 let clip = rect;
1722 let widget_id = widget_hash(id, Some(rect));
1723
1724 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
1725 if hovered {
1726 state.hovered = widget_id;
1727 }
1728 let clicked = hovered && was_pressed_and_released(state, widget_id);
1729 if hovered && state.input.l_pressed {
1730 state.pressed = widget_id;
1731 }
1732 if clicked {
1733 result.activated = true;
1734 }
1735
1736 let bg = if config.selected {
1738 Color::new(
1739 style.accent.r * 0.25,
1740 style.accent.g * 0.25,
1741 style.accent.b * 0.35,
1742 1.0,
1743 )
1744 } else if hovered {
1745 Color::new(
1746 style.surface.r * 1.1,
1747 style.surface.g * 1.1,
1748 style.surface.b * 1.1,
1749 1.0,
1750 )
1751 } else {
1752 Color::new(0.0, 0.0, 0.0, 0.0)
1753 };
1754 if bg.a > 0.0 {
1755 state.cmds.push(UiCmd::Rect {
1756 rect,
1757 color: bg,
1758 clip,
1759 corner_radius: 0.0,
1760 });
1761 }
1762
1763 let indent = config.indent * config.depth;
1765 let disc_x = rect.x + indent;
1766 let disc_w = config.disclosure_width.max(0) as u32;
1767 let disc_rect = PixelRect {
1768 x: disc_x,
1769 y: rect.y,
1770 w: disc_w,
1771 h: rect.h,
1772 };
1773
1774 if config.has_children {
1775 let arrow_rect = PixelRect {
1778 x: disc_x + 4,
1779 y: rect.y + rect.h as i32 / 2 - 4,
1780 w: 8,
1781 h: 8,
1782 };
1783 let arrow_color = if config.open {
1784 style.text
1785 } else {
1786 style.text_secondary
1787 };
1788 state.cmds.push(UiCmd::Rect {
1789 rect: arrow_rect,
1790 color: arrow_color,
1791 clip,
1792 corner_radius: 1.0,
1793 });
1794
1795 if clicked && point_in_rect(state.input.pointer_x, state.input.pointer_y, disc_rect) {
1797 result.open = !config.open;
1798 result.open_changed = true;
1799 }
1800 }
1801 result.disclosure = disc_rect;
1802
1803 let label_x = disc_x + disc_w as i32;
1805 let label_rect = PixelRect {
1806 x: label_x,
1807 y: rect.y,
1808 w: (rect.x + rect.w as i32 - label_x).max(0) as u32,
1809 h: rect.h,
1810 };
1811 result.label = label_rect;
1812 let text_color = if config.enabled {
1813 style.text
1814 } else {
1815 style.text_secondary
1816 };
1817 let cfg = TextLayoutConfig {
1818 font: FontId::Sans,
1819 size: style.font_size - 1.0,
1820 ..TextLayoutConfig::default()
1821 };
1822 Self::emit_text_or_record(state, label, label_rect, text_color, cfg);
1823
1824 result
1825 }
1826
1827 pub fn node_canvas_grid(&mut self, canvas: &NodeCanvas, rect: PixelRect) {
1835 let Some(state) = self.state.as_mut() else {
1836 return;
1837 };
1838 let style = Self::current_style_ref(state).clone();
1839
1840 let bg = Color::new(
1842 style.background.r * 0.88,
1843 style.background.g * 0.88,
1844 style.background.b * 0.88,
1845 1.0,
1846 );
1847 state.cmds.push(UiCmd::Rect {
1848 rect,
1849 color: bg,
1850 clip: rect,
1851 corner_radius: 0.0,
1852 });
1853
1854 let zoom = canvas.state().zoom;
1856 let pan = canvas.state().pan;
1857 let base_step = 10.0_f32;
1858 let step_px = base_step * zoom;
1859 if step_px < 4.0 {
1860 return; }
1862
1863 let world_origin = canvas.screen_to_world([rect.x as f32, rect.y as f32]);
1865
1866 let start_wx = (world_origin[0] / base_step).floor() * base_step;
1868 let start_wy = (world_origin[1] / base_step).floor() * base_step;
1869
1870 let minor_color = Color::new(style.border.r, style.border.g, style.border.b, 0.35);
1871 let major_color = Color::new(style.border.r, style.border.g, style.border.b, 0.65);
1872
1873 let mut wx = start_wx;
1875 loop {
1876 let sx = canvas.world_to_screen([wx, 0.0])[0];
1877 if sx > (rect.x + rect.w as i32) as f32 {
1878 break;
1879 }
1880 if sx >= rect.x as f32 {
1881 let is_major = (wx / base_step).abs() % 10.0 < 0.5;
1882 let color = if is_major { major_color } else { minor_color };
1883 let line = PixelRect {
1884 x: sx as i32,
1885 y: rect.y,
1886 w: 1,
1887 h: rect.h,
1888 };
1889 state.cmds.push(UiCmd::Rect {
1890 rect: line,
1891 color,
1892 clip: rect,
1893 corner_radius: 0.0,
1894 });
1895 }
1896 wx += base_step;
1897 if wx - start_wx > (rect.w as f32 / zoom + base_step * 2.0) {
1898 break;
1899 }
1900 }
1901
1902 let _ = pan; let mut wy = start_wy;
1905 loop {
1906 let sy = canvas.world_to_screen([0.0, wy])[1];
1907 if sy > (rect.y + rect.h as i32) as f32 {
1908 break;
1909 }
1910 if sy >= rect.y as f32 {
1911 let is_major = (wy / base_step).abs() % 10.0 < 0.5;
1912 let color = if is_major { major_color } else { minor_color };
1913 let line = PixelRect {
1914 x: rect.x,
1915 y: sy as i32,
1916 w: rect.w,
1917 h: 1,
1918 };
1919 state.cmds.push(UiCmd::Rect {
1920 rect: line,
1921 color,
1922 clip: rect,
1923 corner_radius: 0.0,
1924 });
1925 }
1926 wy += base_step;
1927 if wy - start_wy > (rect.h as f32 / zoom + base_step * 2.0) {
1928 break;
1929 }
1930 }
1931 }
1932
1933 pub fn plot_line_bindless(
1939 &mut self,
1940 values_idx: u32,
1941 count: u32,
1942 y_min: f32,
1943 y_max: f32,
1944 color: Color,
1945 ) {
1946 let Some(state) = self.state.as_mut() else {
1947 return;
1948 };
1949 let style = Self::current_style_ref(state).clone();
1950 let (rect, clip) = allocate_plot(state, style.padding);
1951 state.cmds.push(UiCmd::PlotLine {
1952 values_idx,
1953 count,
1954 rect,
1955 clip,
1956 x_min: 0.0,
1957 x_max: count.saturating_sub(1).max(1) as f32,
1958 y_min,
1959 y_max,
1960 color,
1961 fill: false,
1962 explicit_xy: false,
1963 band: false,
1964 antialias_samples: 4,
1965 line_width: 1.35,
1966 });
1967 }
1968
1969 pub fn plot_line_at(
1975 &mut self,
1976 values: &[f32],
1977 rect: PixelRect,
1978 y_min: f32,
1979 y_max: f32,
1980 color: Color,
1981 line_width: f32,
1982 ) -> Result<()> {
1983 if values.is_empty() {
1984 return Ok(());
1985 }
1986 if rect.w == 0 || rect.h == 0 || !y_min.is_finite() || !y_max.is_finite() || y_min >= y_max {
1987 return Err(Error::invalid_argument(
1988 "UI line plot requires a positive rectangle and finite increasing Y limits",
1989 ));
1990 }
1991 if !line_width.is_finite() || line_width <= 0.0 {
1992 return Err(Error::invalid_argument(
1993 "UI line width must be finite and positive",
1994 ));
1995 }
1996 let matrix = crate::Matrix::new_from_f32_on(self.runtime, [values.len()], values)?;
1997 let descriptor = matrix
1998 .runtime()
1999 .storage_descriptor_index(matrix.storage())?;
2000 let state = self
2001 .state
2002 .as_mut()
2003 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2004 state.cmds.push(UiCmd::PlotLine {
2005 values_idx: descriptor,
2006 count: u32::try_from(values.len())
2007 .map_err(|_| Error::out_of_range("UI plot sample count exceeds u32"))?,
2008 rect,
2009 clip: PixelRect {
2010 x: 0,
2011 y: 0,
2012 w: state.compose.width,
2013 h: state.compose.height,
2014 },
2015 x_min: 0.0,
2016 x_max: values.len().saturating_sub(1).max(1) as f32,
2017 y_min,
2018 y_max,
2019 color,
2020 fill: false,
2021 explicit_xy: false,
2022 band: false,
2023 antialias_samples: 4,
2024 line_width,
2025 });
2026 state.frame_matrices.push(matrix);
2027 Ok(())
2028 }
2029
2030 pub fn plot_band_at(
2037 &mut self,
2038 y_lo: &[f32],
2039 y_hi: &[f32],
2040 rect: PixelRect,
2041 y_min: f32,
2042 y_max: f32,
2043 color: Color,
2044 ) -> Result<()> {
2045 if y_lo.len() != y_hi.len() {
2046 return Err(Error::invalid_argument(
2047 "plot_band_at: y_lo and y_hi must have equal length",
2048 ));
2049 }
2050 if y_lo.is_empty() {
2051 return Ok(());
2052 }
2053 if rect.w == 0 || rect.h == 0 || !y_min.is_finite() || !y_max.is_finite() || y_min >= y_max {
2054 return Err(Error::invalid_argument(
2055 "UI band plot requires a positive rectangle and finite increasing Y limits",
2056 ));
2057 }
2058 let mut packed: Vec<f32> = Vec::with_capacity(y_lo.len() * 2);
2059 packed.extend_from_slice(y_lo);
2060 packed.extend_from_slice(y_hi);
2061 let matrix = crate::Matrix::new_from_f32_on(self.runtime, [packed.len()], &packed)?;
2062 let descriptor = matrix
2063 .runtime()
2064 .storage_descriptor_index(matrix.storage())?;
2065 let state = self
2066 .state
2067 .as_mut()
2068 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2069 let clip = Self::compose_clip(state, rect);
2070 if clip.w == 0 || clip.h == 0 {
2071 return Ok(());
2072 }
2073 state.cmds.push(UiCmd::PlotLine {
2074 values_idx: descriptor,
2075 count: u32::try_from(y_lo.len())
2076 .map_err(|_| Error::out_of_range("UI band sample count exceeds u32"))?,
2077 rect,
2078 clip,
2079 x_min: 0.0,
2080 x_max: y_lo.len().saturating_sub(1).max(1) as f32,
2081 y_min,
2082 y_max,
2083 color,
2084 fill: false,
2085 explicit_xy: false,
2086 band: true,
2087 antialias_samples: 4,
2088 line_width: 1.35,
2089 });
2090 state.frame_matrices.push(matrix);
2091 Ok(())
2092 }
2093
2094 pub fn plot_line(
2106 &mut self,
2107 values: &[f32],
2108 rect: PixelRect,
2109 config: &UiPlotConfig,
2110 ) -> Result<()> {
2111 if values.is_empty() {
2112 return Ok(());
2113 }
2114 if rect.w == 0 || rect.h == 0 {
2115 return Err(Error::invalid_argument(
2116 "UI line plot requires a positive rectangle",
2117 ));
2118 }
2119 if !config.x_min.is_finite() || !config.x_max.is_finite() {
2120 return Err(Error::invalid_argument(
2121 "UI line plot requires finite X limits",
2122 ));
2123 }
2124 if !config.auto_scale && (!config.y_min.is_finite() || !config.y_max.is_finite()) {
2125 return Err(Error::invalid_argument(
2126 "UI line plot requires finite Y limits",
2127 ));
2128 }
2129 let (mut y_min, mut y_max) = if config.auto_scale {
2130 let mut lo = f32::INFINITY;
2131 let mut hi = f32::NEG_INFINITY;
2132 for &value in values {
2133 if !value.is_finite() {
2134 continue;
2135 }
2136 lo = lo.min(value);
2137 hi = hi.max(value);
2138 }
2139 (lo, hi)
2140 } else {
2141 (config.y_min, config.y_max)
2142 };
2143 if !y_min.is_finite() || !y_max.is_finite() {
2144 return Ok(());
2145 }
2146 if y_max <= y_min {
2147 let margin = (y_min.abs() * 0.05).max(1.0e-4);
2148 y_min -= margin;
2149 y_max += margin;
2150 }
2151 if config.draw_surface || config.show_grid {
2152 self.grid(
2153 rect,
2154 chart_grid_config(
2155 rect,
2156 self.content_scale(),
2157 config.draw_surface,
2158 config.show_grid,
2159 ),
2160 );
2161 }
2162 let matrix = crate::Matrix::new_from_f32_on(self.runtime, [values.len()], values)?;
2163 let descriptor = matrix
2164 .runtime()
2165 .storage_descriptor_index(matrix.storage())?;
2166 let state = self
2167 .state
2168 .as_mut()
2169 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2170 let clip = Self::compose_clip(state, rect);
2171 if clip.w == 0 || clip.h == 0 {
2172 return Ok(());
2173 }
2174 state.cmds.push(UiCmd::PlotLine {
2175 values_idx: descriptor,
2176 count: u32::try_from(values.len())
2177 .map_err(|_| Error::out_of_range("UI plot sample count exceeds u32"))?,
2178 rect,
2179 clip,
2180 x_min: config.x_min,
2181 x_max: config.x_max,
2182 y_min,
2183 y_max,
2184 color: config.color,
2185 fill: config.fill,
2186 explicit_xy: false,
2187 band: false,
2188 antialias_samples: match config.antialias_samples {
2189 1 | 8 => config.antialias_samples,
2190 _ => 4,
2191 },
2192 line_width: if config.line_width.is_finite() {
2193 config.line_width.clamp(0.5, 16.0)
2194 } else {
2195 1.35
2196 },
2197 });
2198 state.frame_matrices.push(matrix);
2199 Ok(())
2200 }
2201
2202 pub fn line_at(
2204 &mut self,
2205 from: [f32; 2],
2206 to: [f32; 2],
2207 color: Color,
2208 thickness: f32,
2209 bounds: PixelRect,
2210 ) -> Result<()> {
2211 if from.into_iter().chain(to).any(|value| !value.is_finite())
2212 || !thickness.is_finite()
2213 || thickness <= 0.0
2214 || bounds.w == 0
2215 || bounds.h == 0
2216 {
2217 return Err(Error::invalid_argument(
2218 "UI line requires finite coordinates, positive thickness, and positive bounds",
2219 ));
2220 }
2221 let state = self
2222 .state
2223 .as_mut()
2224 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2225 state.cmds.push(UiCmd::Line {
2226 x0: from[0],
2227 y0: from[1],
2228 x1: to[0],
2229 y1: to[1],
2230 color,
2231 thickness,
2232 bounds,
2233 });
2234 Ok(())
2235 }
2236
2237 pub fn image_at(&mut self, texture: &crate::Texture, rect: PixelRect) -> Result<()> {
2239 self.image_at_channel(texture, rect, 0)
2240 }
2241
2242 pub(crate) fn video_planes_at(
2243 &mut self,
2244 frame: &crate::VideoFrame,
2245 dst: PixelRect,
2246 ) -> Result<()> {
2247 use crate::video::{VideoColorMatrix, VideoColorRange};
2248 let (planes, layout) = frame
2249 .canvas_planes()
2250 .ok_or_else(|| Error::invalid_argument("video canvas requires a staged plane buffer"))?;
2251 let state = self
2252 .state
2253 .as_mut()
2254 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2255 let color = frame.color_info();
2256 let matrix = match color.matrix() {
2257 VideoColorMatrix::Bt601 => 0,
2258 VideoColorMatrix::Bt709 | VideoColorMatrix::Unspecified => 1,
2259 VideoColorMatrix::Bt2020 => 2,
2260 };
2261 let planes_idx = state.runtime.storage_descriptor_index(planes)?;
2262 state.cmds.push(UiCmd::BlitYuv {
2263 planes_idx,
2264 dst,
2265 push: [
2266 layout.extent.width,
2267 layout.extent.height,
2268 dst.x as u32,
2269 dst.y as u32,
2270 dst.w,
2271 dst.h,
2272 layout.cb_offset,
2273 layout.cr_offset,
2274 layout.sample_bits,
2275 u32::from(layout.interleaved),
2276 matrix,
2277 u32::from(color.range() == VideoColorRange::Full),
2278 ],
2279 });
2280 state.frame_storages.push(planes.clone());
2281 Ok(())
2282 }
2283
2284 pub(crate) fn image_at_channel(
2292 &mut self,
2293 texture: &crate::Texture,
2294 rect: PixelRect,
2295 channel: u32,
2296 ) -> Result<()> {
2297 if channel > 4 {
2298 return Err(Error::invalid_argument("UI image channel must be in 0..=4"));
2299 }
2300 if rect.w == 0 || rect.h == 0 {
2301 return Err(Error::invalid_argument(
2302 "UI image rectangle must be positive",
2303 ));
2304 }
2305 if !texture.runtime().same_as(&self.runtime.handle()) {
2306 return Err(Error::invalid_argument(
2307 "UI Texture belongs to a different Runtime",
2308 ));
2309 }
2310 let view = texture
2311 .native()
2312 .map(|native| native.view())
2313 .ok_or_else(|| Error::failed_precondition("UI image requires a buffer-backed Texture"))?;
2314 let src_w = u32::try_from(texture.width())
2315 .map_err(|_| Error::out_of_range("Texture width exceeds UI ABI"))?;
2316 let src_h = u32::try_from(texture.height())
2317 .map_err(|_| Error::out_of_range("Texture height exceeds UI ABI"))?;
2318 let state = self
2319 .state
2320 .as_mut()
2321 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2322 state.cmds.push(UiCmd::BlitRgba {
2323 view,
2324 src_w,
2325 src_h,
2326 dst_x: rect.x,
2327 dst_y: rect.y,
2328 dst_w: rect.w,
2329 dst_h: rect.h,
2330 clip: PixelRect {
2331 x: 0,
2332 y: 0,
2333 w: state.compose.width,
2334 h: state.compose.height,
2335 },
2336 channel,
2337 linear: rect.w < src_w || rect.h < src_h,
2338 });
2339 state.frame_textures.push(texture.clone());
2340 Ok(())
2341 }
2342
2343 pub(crate) fn measure_text(&self, text: &str, config: TextLayoutConfig) -> Result<f32> {
2345 let state = self
2346 .state
2347 .as_ref()
2348 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2349 let shaped = TextLayout::shape(
2350 &state.text_atlas,
2351 text,
2352 [0.0, 0.0],
2353 config,
2354 Color::default(),
2355 )?;
2356 Ok(shaped.iter().map(|g| g.advance).sum())
2357 }
2358
2359 pub fn text_at(
2361 &mut self,
2362 text: &str,
2363 origin: [f32; 2],
2364 config: TextLayoutConfig,
2365 color: Color,
2366 clip: PixelRect,
2367 ) -> Result<()> {
2368 let state = self
2369 .state
2370 .as_mut()
2371 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2372 let positioned = TextLayout::shape(&state.text_atlas, text, origin, config, color)?;
2373 if positioned.is_empty() {
2374 return Ok(());
2375 }
2376 let mut bytes = Vec::with_capacity(positioned.len() * 48);
2377 for glyph in positioned {
2378 let Some(info) = state
2379 .text_atlas
2380 .find_glyph(glyph.font, glyph.codepoint, config.size)
2381 else {
2382 continue;
2383 };
2384 let scale = config.size / info.raster_size;
2385 for value in [
2386 0.0_f32,
2387 0.0,
2388 glyph.x + info.bearing_x * scale,
2389 glyph.y - info.bearing_y * scale,
2390 info.atlas_w * scale,
2391 info.atlas_h * scale,
2392 ] {
2393 bytes.extend_from_slice(&value.to_le_bytes());
2394 }
2395 for value in [
2396 info.atlas_x as u32,
2397 info.atlas_y as u32,
2398 info.atlas_w as u32,
2399 info.atlas_h as u32,
2400 glyph.color.to_u32(),
2401 0,
2402 ] {
2403 bytes.extend_from_slice(&value.to_le_bytes());
2404 }
2405 }
2406 if bytes.is_empty() {
2407 return Ok(());
2408 }
2409 Self::emit_glyph_records(state, bytes, clip)
2410 }
2411
2412 pub fn text_vertical_at(
2419 &mut self,
2420 text: &str,
2421 origin: [f32; 2],
2422 config: TextLayoutConfig,
2423 color: Color,
2424 clip: PixelRect,
2425 ) -> Result<()> {
2426 let state = self
2427 .state
2428 .as_mut()
2429 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2430 let positioned = TextLayout::shape(&state.text_atlas, text, [0.0, 0.0], config, color)?;
2431 if positioned.is_empty() {
2432 return Ok(());
2433 }
2434 let mut bytes = Vec::with_capacity(positioned.len() * 48);
2435 for glyph in positioned {
2436 let Some(info) = state
2437 .text_atlas
2438 .find_glyph(glyph.font, glyph.codepoint, config.size)
2439 else {
2440 continue;
2441 };
2442 let scale = config.size / info.raster_size;
2443 let w = info.atlas_w * scale;
2444 let h = info.atlas_h * scale;
2445 for value in [
2451 0.0_f32,
2452 0.0,
2453 origin[0] + glyph.y - info.bearing_y * scale,
2454 origin[1] - (glyph.x + info.bearing_x * scale) - w,
2455 w,
2456 h,
2457 ] {
2458 bytes.extend_from_slice(&value.to_le_bytes());
2459 }
2460 for value in [
2461 info.atlas_x as u32,
2462 info.atlas_y as u32,
2463 info.atlas_w as u32,
2464 info.atlas_h as u32,
2465 glyph.color.to_u32(),
2466 1u32,
2467 ] {
2468 bytes.extend_from_slice(&value.to_le_bytes());
2469 }
2470 }
2471 if bytes.is_empty() {
2472 return Ok(());
2473 }
2474 Self::emit_glyph_records(state, bytes, clip)
2475 }
2476
2477 fn emit_glyph_records(state: &mut UiState, bytes: Vec<u8>, clip: PixelRect) -> Result<()> {
2479 let storage = state.runtime.create_storage(&bytes)?;
2480 let glyph_idx = state.runtime.storage_descriptor_index(&storage)?;
2481 let count = u32::try_from(bytes.len() / 48)
2482 .map_err(|_| Error::out_of_range("glyph count exceeds u32"))?;
2483 state.cmds.push(UiCmd::Glyphs {
2484 glyph_idx,
2485 atlas_idx: state.text_atlas.descriptor(),
2486 count,
2487 dst: None,
2488 clip,
2489 atlas_w: state.text_atlas.width(),
2490 atlas_h: state.text_atlas.height(),
2491 });
2492 state.frame_storages.push(storage);
2493 Ok(())
2494 }
2495
2496 pub fn rect_raw(&mut self, rect: PixelRect, color: Color, clip: PixelRect, corner_radius: f32) {
2502 if let Some(state) = self.state.as_mut() {
2503 state.cmds.push(UiCmd::Rect {
2504 rect,
2505 color,
2506 clip,
2507 corner_radius,
2508 });
2509 }
2510 }
2511
2512 pub fn rect_outline_raw(
2514 &mut self,
2515 rect: PixelRect,
2516 color: Color,
2517 thickness: u32,
2518 clip: PixelRect,
2519 ) {
2520 self.rect_outline_rounded_at(rect, color, thickness, clip, 0.0);
2521 }
2522
2523 pub fn rect_outline_rounded_at(
2525 &mut self,
2526 rect: PixelRect,
2527 color: Color,
2528 thickness: u32,
2529 clip: PixelRect,
2530 radius: f32,
2531 ) {
2532 if let Some(state) = self.state.as_mut() {
2533 state.cmds.push(UiCmd::RectOutline {
2534 rect,
2535 color,
2536 thickness,
2537 clip,
2538 corner_radius: radius,
2539 });
2540 }
2541 }
2542
2543 pub fn rect(&mut self, rect: PixelRect, color: Color, corner_radius: f32) -> Result<()> {
2549 if !corner_radius.is_finite() || corner_radius < 0.0 {
2550 return Err(Error::invalid_argument(
2551 "Ui::rect requires a finite non-negative corner radius",
2552 ));
2553 }
2554 if rect.w == 0 || rect.h == 0 {
2555 return Ok(());
2556 }
2557 let Some(state) = self.state.as_mut() else {
2558 return Ok(());
2559 };
2560 let clip = Self::compose_clip(state, rect);
2561 if clip.w == 0 || clip.h == 0 {
2562 return Ok(());
2563 }
2564 state.cmds.push(UiCmd::Rect {
2565 rect,
2566 color,
2567 clip,
2568 corner_radius: corner_radius.min(0.5 * rect.w.min(rect.h) as f32),
2569 });
2570 Ok(())
2571 }
2572
2573 pub fn rect_outline(
2577 &mut self,
2578 rect: PixelRect,
2579 color: Color,
2580 thickness: u32,
2581 corner_radius: f32,
2582 ) -> Result<()> {
2583 if !corner_radius.is_finite() || corner_radius < 0.0 {
2584 return Err(Error::invalid_argument(
2585 "Ui::rect_outline requires a finite non-negative corner radius",
2586 ));
2587 }
2588 if rect.w == 0 || rect.h == 0 {
2589 return Ok(());
2590 }
2591 let Some(state) = self.state.as_mut() else {
2592 return Ok(());
2593 };
2594 let clip = Self::compose_clip(state, rect);
2595 if clip.w == 0 || clip.h == 0 {
2596 return Ok(());
2597 }
2598 state.cmds.push(UiCmd::RectOutline {
2599 rect,
2600 color,
2601 thickness: thickness.max(1),
2602 clip,
2603 corner_radius: corner_radius.min(0.5 * rect.w.min(rect.h) as f32),
2604 });
2605 Ok(())
2606 }
2607
2608 pub fn rect_outlines(
2616 &mut self,
2617 detections: &crate::vision::DetectionBuffer,
2618 dst: PixelRect,
2619 clip: PixelRect,
2620 color: Color,
2621 thickness: u32,
2622 ) -> Result<()> {
2623 if !detections.runtime().same_as(&self.runtime.handle()) {
2624 return Err(Error::invalid_argument(
2625 "Ui::rect_outlines requires a DetectionBuffer from its runtime",
2626 ));
2627 }
2628 if detections.count() == 0 || dst.w == 0 || dst.h == 0 || clip.w == 0 || clip.h == 0 {
2629 return Ok(());
2630 }
2631 let clip = dst.clip(&clip);
2632 if clip.w == 0 || clip.h == 0 {
2633 return Ok(());
2634 }
2635 let rect_idx = detections.bindless_index()?;
2636 let state = self
2637 .state
2638 .as_mut()
2639 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2640 state.cmds.push(UiCmd::RectOutlines {
2641 rect_idx,
2642 count: detections.count(),
2643 dst,
2644 clip,
2645 thickness: thickness.max(1),
2646 rgba: color.to_u32(),
2647 });
2648 state
2649 .frame_storages
2650 .push(detections.storage().storage().clone());
2651 Ok(())
2652 }
2653
2654 pub fn glyphs(&mut self, buffer: &GlyphBuffer, dst: PixelRect, clip: PixelRect) -> Result<()> {
2662 if !buffer.runtime().same_as(&self.runtime.handle()) {
2663 return Err(Error::invalid_argument(
2664 "Ui::glyphs requires a GlyphBuffer from its runtime",
2665 ));
2666 }
2667 if buffer.count() == 0 || dst.w == 0 || dst.h == 0 || clip.w == 0 || clip.h == 0 {
2668 return Ok(());
2669 }
2670 let clip = dst.clip(&clip);
2671 if clip.w == 0 || clip.h == 0 {
2672 return Ok(());
2673 }
2674 let glyph_idx = buffer.bindless_index()?;
2675 let state = self
2676 .state
2677 .as_mut()
2678 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
2679 state.cmds.push(UiCmd::Glyphs {
2680 glyph_idx,
2681 atlas_idx: state.text_atlas.descriptor(),
2682 count: buffer.count(),
2683 dst: Some(dst),
2684 clip,
2685 atlas_w: state.text_atlas.width(),
2686 atlas_h: state.text_atlas.height(),
2687 });
2688 state
2689 .frame_storages
2690 .push(buffer.storage().storage().clone());
2691 Ok(())
2692 }
2693
2694 pub fn text_atlas(&self) -> Result<&TextAtlas> {
2704 Ok(
2705 self
2706 .state
2707 .as_ref()
2708 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?
2709 .text_atlas
2710 .as_ref(),
2711 )
2712 }
2713
2714 pub fn timeline(
2725 &mut self,
2726 id: &str,
2727 rect: PixelRect,
2728 fraction: &mut f32,
2729 out_active: Option<&mut bool>,
2730 ) -> bool {
2731 let Some(state) = self.state.as_mut() else {
2732 return false;
2733 };
2734 let style = Self::current_style_ref(state).clone();
2735 let widget_id = widget_hash(id, Some(rect));
2736 let clip = rect;
2737
2738 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
2739 if state.input.l_pressed {
2740 if point_in_rect(state.press_origin[0], state.press_origin[1], rect) {
2741 state.pressed = widget_id;
2742 } else if state.pressed == widget_id {
2743 state.pressed = 0;
2744 }
2745 }
2746 if hovered {
2747 state.hovered = widget_id;
2748 }
2749 let dragging = state.pressed == widget_id && state.input.pointer_down;
2750 let mut changed = false;
2751 if dragging || (state.pressed == widget_id && state.input.l_released) {
2752 let new_frac =
2753 ((state.input.pointer_x - rect.x as f32) / rect.w.max(1) as f32).clamp(0.0, 1.0);
2754 if (*fraction - new_frac).abs() > 1e-5 {
2755 *fraction = new_frac;
2756 changed = true;
2757 }
2758 }
2759 if let Some(active) = out_active {
2760 *active = dragging;
2761 }
2762
2763 let track_h = (4.0 * state.content_scale).round().max(1.0) as u32;
2765 let track_h = track_h.min(rect.h);
2766 let track_rect = PixelRect {
2767 x: rect.x,
2768 y: rect.y + (rect.h - track_h) as i32 / 2,
2769 w: rect.w,
2770 h: track_h,
2771 };
2772 state.cmds.push(UiCmd::Rect {
2773 rect: track_rect,
2774 color: Color {
2775 a: 0.78,
2776 ..style.surface
2777 },
2778 clip,
2779 corner_radius: track_h as f32 * 0.5,
2780 });
2781 let frac = fraction.clamp(0.0, 1.0);
2783 let fill_w = (track_rect.w as f32 * frac) as u32;
2784 if fill_w > 0 {
2785 state.cmds.push(UiCmd::Rect {
2786 rect: PixelRect {
2787 x: track_rect.x,
2788 y: track_rect.y,
2789 w: fill_w,
2790 h: track_rect.h,
2791 },
2792 color: style.accent,
2793 clip,
2794 corner_radius: track_h as f32 * 0.5,
2795 });
2796 }
2797 let base_diameter = ((20.0 * state.content_scale).round().max(1.0) as u32).min(rect.h);
2799 let hover_mix = animate_hover(state, widget_id, hovered);
2800 let diameter = ((if dragging {
2801 18.0
2802 } else {
2803 20.0 + 4.0 * hover_mix
2804 }) * state.content_scale)
2805 .round()
2806 .max(1.0) as u32;
2807 let diameter = diameter.min(rect.h);
2808 let thumb_cx = rect.x
2809 + base_diameter as i32 / 2
2810 + (rect.w.saturating_sub(base_diameter) as f32 * frac).round() as i32;
2811 let thumb_rect = PixelRect::new(
2812 thumb_cx - diameter as i32 / 2,
2813 rect.y + (rect.h - diameter) as i32 / 2,
2814 diameter,
2815 diameter,
2816 );
2817 state.cmds.push(UiCmd::Rect {
2818 rect: thumb_rect,
2819 color: if dragging || hovered {
2820 style.accent_hover
2821 } else {
2822 style.text
2823 },
2824 clip,
2825 corner_radius: diameter as f32 * 0.5,
2826 });
2827 changed
2828 }
2829
2830 pub fn waveform_timeline(
2839 &mut self,
2840 id: &str,
2841 rect: PixelRect,
2842 envelope: &[f32],
2843 fraction: &mut f32,
2844 ) -> bool {
2845 let Some(state) = self.state.as_mut() else {
2846 return false;
2847 };
2848 let style = Self::current_style_ref(state).clone();
2849 let clip = rect;
2850
2851 state.cmds.push(UiCmd::Rect {
2853 rect,
2854 color: Color::new(
2855 style.surface.r * 0.6,
2856 style.surface.g * 0.6,
2857 style.surface.b * 0.6,
2858 1.0,
2859 ),
2860 clip,
2861 corner_radius: 0.0,
2862 });
2863
2864 if !envelope.is_empty() {
2866 let n = envelope.len();
2867 let bar_w = (rect.w as f32 / n as f32).max(1.0);
2868 for (i, &) in envelope.iter().enumerate() {
2869 let amp = amp.clamp(0.0, 1.0);
2870 let bar_h = (rect.h as f32 * amp).max(1.0) as u32;
2871 let bar_x = rect.x + (i as f32 * bar_w) as i32;
2872 let bar_y = rect.y + (rect.h - bar_h) as i32 / 2;
2873 let bar_rect = PixelRect {
2874 x: bar_x,
2875 y: bar_y,
2876 w: bar_w as u32,
2877 h: bar_h,
2878 };
2879 state.cmds.push(UiCmd::Rect {
2880 rect: bar_rect,
2881 color: style.text_secondary,
2882 clip,
2883 corner_radius: 0.0,
2884 });
2885 }
2886 }
2887
2888 self.timeline(id, rect, fraction, None)
2890 }
2891
2892 pub fn begin_scroll_panel(
2901 &mut self,
2902 id: &str,
2903 rect: PixelRect,
2904 content_height: i32,
2905 config: UiScrollConfig,
2906 ) -> UiScrollRegion {
2907 if rect.w == 0
2908 || rect.h == 0
2909 || rect.w > i32::MAX as u32
2910 || rect.h > i32::MAX as u32
2911 || content_height < 0
2912 || !config.wheel_step.is_finite()
2913 || config.wheel_step <= 0.0
2914 || !config.scrollbar_width.is_finite()
2915 || config.scrollbar_width > i32::MAX as f32
2916 || (config.show_scrollbar && config.scrollbar_width <= 0.0)
2917 || !config.scrollbar_gap.is_finite()
2918 || config.scrollbar_gap > i32::MAX as f32
2919 || config.scrollbar_gap < 0.0
2920 {
2921 return UiScrollRegion::default();
2922 }
2923 let panel_id = widget_hash(id, Some(rect));
2924 let viewport_height = i32::try_from(rect.h).unwrap_or(i32::MAX);
2925 let content_height = content_height.max(viewport_height);
2926 let max_offset = content_height.saturating_sub(viewport_height);
2927
2928 let Some(state) = self.state.as_mut() else {
2929 return UiScrollRegion {
2930 viewport: rect,
2931 content: rect,
2932 ..Default::default()
2933 };
2934 };
2935
2936 if point_in_rect(state.input.pointer_x, state.input.pointer_y, rect) {
2938 let dy = -state.input.scroll_y;
2939 if dy.abs() > 0.5 {
2940 let entry = state.scroll_offsets.entry(panel_id).or_insert(0);
2941 *entry = entry
2942 .saturating_add((dy * config.wheel_step) as i32)
2943 .clamp(0, max_offset);
2944 }
2945 }
2946 let offset_y = *state.scroll_offsets.get(&panel_id).unwrap_or(&0);
2947 let offset_y = offset_y.clamp(0, max_offset);
2948 state.scroll_offsets.insert(panel_id, offset_y);
2949
2950 let scrollbar_width = config.scrollbar_width.ceil().max(1.0) as u32;
2952 let scrollbar_gap = config.scrollbar_gap.ceil() as u32;
2953 let show_scrollbar = config.show_scrollbar
2954 && max_offset > 0
2955 && rect.w > scrollbar_width.saturating_add(scrollbar_gap);
2956 let sb_room = if show_scrollbar {
2957 (scrollbar_width + scrollbar_gap) as i32
2958 } else {
2959 0
2960 };
2961 let content_rect = PixelRect {
2962 x: rect.x,
2963 y: rect.y.saturating_sub(offset_y),
2964 w: (rect.w as i32 - sb_room).max(0) as u32,
2965 h: content_height as u32,
2966 };
2967 let viewport = PixelRect {
2968 h: rect.h,
2969 w: content_rect.w,
2970 ..rect
2971 };
2972 let panel_clip = state
2973 .layout
2974 .top()
2975 .map_or(rect, |parent| parent.clip().clip(&rect));
2976 let clip = panel_clip.clip(&viewport);
2977
2978 let style = Self::current_style_ref(state).clone();
2980 state.cmds.push(UiCmd::Rect {
2981 rect,
2982 color: style.background,
2983 clip: panel_clip,
2984 corner_radius: 0.0,
2985 });
2986
2987 if show_scrollbar {
2989 let sb_x = rect
2990 .x
2991 .saturating_add(rect.w as i32 - scrollbar_width as i32);
2992 let sb_track = PixelRect {
2993 x: sb_x,
2994 y: rect.y,
2995 w: scrollbar_width,
2996 h: rect.h,
2997 };
2998 state.cmds.push(UiCmd::Rect {
2999 rect: sb_track,
3000 color: Color::new(
3001 style.surface.r * 0.7,
3002 style.surface.g * 0.7,
3003 style.surface.b * 0.7,
3004 1.0,
3005 ),
3006 clip: panel_clip,
3007 corner_radius: scrollbar_width as f32 * 0.5,
3008 });
3009 let thumb_h = ((rect.h as f32 * rect.h as f32 / content_height as f32) as u32)
3010 .max(16)
3011 .min(rect.h);
3012 let thumb_y =
3013 rect.y + (offset_y as f32 / max_offset as f32 * (rect.h - thumb_h) as f32) as i32;
3014 state.cmds.push(UiCmd::Rect {
3015 rect: PixelRect {
3016 x: sb_x,
3017 y: thumb_y,
3018 w: scrollbar_width,
3019 h: thumb_h,
3020 },
3021 color: style.accent,
3022 clip: panel_clip,
3023 corner_radius: scrollbar_width as f32 * 0.5,
3024 });
3025 }
3026
3027 let layout = UiLayout {
3029 padding: UiEdge::all(0.0),
3030 ..UiLayout::default()
3031 };
3032 let mut scope = PanelScope::new(content_rect, layout);
3033 scope.clip_override = Some(clip);
3034 scope.scroll_viewport = Some(viewport);
3035 scope.scroll_offset_y = offset_y;
3036 state.layout.push(scope);
3037
3038 UiScrollRegion {
3039 viewport,
3040 content: content_rect,
3041 offset_y,
3042 max_offset_y: max_offset,
3043 }
3044 }
3045
3046 pub fn end_scroll_panel(&mut self) {
3050 let Some(state) = self.state.as_mut() else {
3051 return;
3052 };
3053 if state
3054 .layout
3055 .top()
3056 .is_some_and(|scope| scope.scroll_viewport.is_some())
3057 {
3058 state.layout.pop();
3059 }
3060 }
3061
3062 pub fn virtual_rows(
3067 &mut self,
3068 item_count: i32,
3069 row_height: i32,
3070 row_gap: i32,
3071 overscan_rows: i32,
3072 ) -> UiVirtualRange {
3073 let Some(scope) = self.state.as_ref().and_then(|state| state.layout.top()) else {
3074 return UiVirtualRange::default();
3075 };
3076 let Some(viewport) = scope.scroll_viewport else {
3077 return UiVirtualRange::default();
3078 };
3079 virtual_row_range(
3080 item_count,
3081 row_height,
3082 row_gap,
3083 overscan_rows,
3084 scope.scroll_offset_y,
3085 viewport.h,
3086 scope.layout.padding.top,
3087 )
3088 }
3089
3090 pub fn split_pane(
3094 &mut self,
3095 id: &str,
3096 rect: PixelRect,
3097 ratio: &mut f32,
3098 config: UiSplitConfig,
3099 ) -> UiSplitRegion {
3100 let total = match config.direction {
3101 UiDirection::Row => rect.w,
3102 UiDirection::Column => rect.h,
3103 };
3104 if rect.w == 0
3105 || rect.h == 0
3106 || total > i32::MAX as u32
3107 || !config.handle_size.is_finite()
3108 || config.handle_size < 1.0
3109 || !config.minimum_first.is_finite()
3110 || config.minimum_first < 0.0
3111 || !config.minimum_second.is_finite()
3112 || config.minimum_second < 0.0
3113 || !config.keyboard_step.is_finite()
3114 || config.keyboard_step <= 0.0
3115 || !ratio.is_finite()
3116 {
3117 return UiSplitRegion::default();
3118 }
3119 let widget_id = widget_hash(id, Some(rect));
3120 let handle_px = config.handle_size.ceil() as i32;
3121 let available = total as i32 - handle_px;
3122 let minimum_first = config.minimum_first.ceil() as i64;
3123 let minimum_second = config.minimum_second.ceil() as i64;
3124 if available <= 0 || minimum_first + minimum_second > i64::from(available) {
3125 return UiSplitRegion::default();
3126 }
3127 let clamp_ratio = |r: f32| {
3128 let lo = minimum_first as f32 / available as f32;
3129 let hi = 1.0 - minimum_second as f32 / available as f32;
3130 r.clamp(lo, hi)
3131 };
3132 let clamped = clamp_ratio(*ratio);
3133 let mut changed = clamped != *ratio;
3134 *ratio = clamped;
3135
3136 let Some(state) = self.state.as_mut() else {
3137 return UiSplitRegion::default();
3138 };
3139 let style = Self::current_style_ref(state).clone();
3140
3141 let (_, handle_rect, _) = split_rects(rect, config.direction, handle_px as u32, *ratio);
3142
3143 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, handle_rect);
3144 state.focusables.push(widget_id);
3145 if hovered && state.input.pointer_down {
3146 state.pressed = widget_id;
3147 state.focused = widget_id;
3148 }
3149 let dragging = state.pressed == widget_id && state.input.pointer_down;
3150 if dragging {
3151 let new_ratio = match config.direction {
3152 UiDirection::Row => {
3153 (state.input.pointer_x - rect.x as f32 - handle_px as f32 * 0.5) / available as f32
3154 }
3155 UiDirection::Column => {
3156 (state.input.pointer_y - rect.y as f32 - handle_px as f32 * 0.5) / available as f32
3157 }
3158 };
3159 let clamped = clamp_ratio(new_ratio);
3160 if (*ratio - clamped).abs() > 1e-5 {
3161 *ratio = clamped;
3162 changed = true;
3163 }
3164 }
3165 let dir = take_dir(state, widget_id);
3168 let step_dir = match config.direction {
3169 UiDirection::Row => dir[0],
3170 UiDirection::Column => dir[1],
3171 };
3172 if step_dir != 0 {
3173 let stepped = clamp_ratio(*ratio + config.keyboard_step * step_dir as f32 / available as f32);
3174 if (*ratio - stepped).abs() > 1e-5 {
3175 *ratio = stepped;
3176 changed = true;
3177 }
3178 }
3179
3180 let (first_rect, handle_rect, second_rect) =
3181 split_rects(rect, config.direction, handle_px as u32, *ratio);
3182
3183 let handle_color = if dragging || hovered || state.focused == widget_id {
3185 style.accent
3186 } else {
3187 style.border
3188 };
3189 state.cmds.push(UiCmd::Rect {
3190 rect: handle_rect,
3191 color: handle_color,
3192 clip: rect,
3193 corner_radius: 0.0,
3194 });
3195
3196 UiSplitRegion {
3197 first: first_rect,
3198 handle: handle_rect,
3199 second: second_rect,
3200 changed,
3201 }
3202 }
3203
3204 pub fn property_row(
3208 &mut self,
3209 _id: &str,
3210 rect: PixelRect,
3211 label: &str,
3212 value: &str,
3213 config: UiPropertyRowConfig,
3214 ) -> UiPropertyRegion {
3215 let Some(state) = self.state.as_mut() else {
3216 return UiPropertyRegion::default();
3217 };
3218 let style = Self::current_style_ref(state).clone();
3219 let clip = rect;
3220
3221 let label_w = (rect.w as f32 * config.label_fraction) as u32;
3222 let gap = config.gap as i32;
3223 let label_rect = PixelRect {
3224 x: rect.x + config.padding_x as i32,
3225 y: rect.y,
3226 w: label_w.saturating_sub(config.padding_x as u32),
3227 h: rect.h,
3228 };
3229 let value_rect = PixelRect {
3230 x: rect.x + label_w as i32 + gap,
3231 y: rect.y,
3232 w: (rect.w as i32 - label_w as i32 - gap - config.padding_x as i32).max(0) as u32,
3233 h: rect.h,
3234 };
3235
3236 if config.alternate {
3237 state.cmds.push(UiCmd::Rect {
3238 rect,
3239 color: Color::new(
3240 style.surface.r * 0.7,
3241 style.surface.g * 0.7,
3242 style.surface.b * 0.7,
3243 0.5,
3244 ),
3245 clip,
3246 corner_radius: 0.0,
3247 });
3248 }
3249
3250 let text_cfg = TextLayoutConfig {
3251 font: FontId::Sans,
3252 size: style.font_size - 1.0,
3253 ..Default::default()
3254 };
3255 Self::emit_text_or_record(state, label, label_rect, style.text_secondary, text_cfg);
3256 Self::emit_text_or_record(state, value, value_rect, style.text, text_cfg);
3257
3258 UiPropertyRegion {
3259 row: rect,
3260 label: label_rect,
3261 value: value_rect,
3262 }
3263 }
3264
3265 pub fn open_popup(&mut self, id: &str) {
3271 let Some(state) = self.state.as_mut() else {
3272 return;
3273 };
3274 let popup_id = widget_hash(id, None);
3275 state.popup_open = popup_id;
3276 state.popup_anchor = PixelRect {
3277 x: state.input.pointer_x as i32,
3278 y: state.input.pointer_y as i32,
3279 w: 0,
3280 h: 0,
3281 };
3282 }
3283
3284 pub fn open_popup_at(&mut self, id: &str, anchor: PixelRect) {
3288 let Some(state) = self.state.as_mut() else {
3289 return;
3290 };
3291 let popup_id = widget_hash(id, None);
3292 state.popup_open = popup_id;
3293 state.popup_anchor = anchor;
3294 }
3295
3296 pub fn close_popup(&mut self) {
3300 let Some(state) = self.state.as_mut() else {
3301 return;
3302 };
3303 state.popup_open = 0;
3304 }
3305
3306 pub fn is_popup_open(&mut self, id: &str) -> bool {
3310 let Some(state) = self.state.as_ref() else {
3311 return false;
3312 };
3313 state.popup_open == widget_hash(id, None)
3314 }
3315
3316 pub fn begin_popup(&mut self, id: &str, config: UiPopupConfig) -> bool {
3322 let popup_id = widget_hash(id, None);
3323 let Some(state) = self.state.as_mut() else {
3324 return false;
3325 };
3326 if state.popup_open != popup_id {
3327 return false;
3328 }
3329 let anchor = state.popup_anchor;
3330 let style = Self::current_style_ref(state).clone();
3331
3332 let width = i64::from(state.compose.width);
3334 let height = i64::from(state.compose.height);
3335 let margin = 4_i64.min(width.min(height) / 2);
3336 let popup_w = (config.width.max(anchor.w as f32) as i64).clamp(1, (width - 2 * margin).max(1));
3337 let popup_h = (if config.height > 0.0 {
3338 config.height as i64
3339 } else {
3340 200
3341 })
3342 .clamp(1, (height - 2 * margin).max(1));
3343 let below = i64::from(anchor.y) + i64::from(anchor.h) + config.gap.max(0.0) as i64;
3344 let above = i64::from(anchor.y) - config.gap.max(0.0) as i64 - popup_h;
3345 let y = if below + popup_h <= height - margin {
3346 below
3347 } else if above >= margin {
3348 above
3349 } else {
3350 below.clamp(margin, (height - margin - popup_h).max(margin))
3351 };
3352 let popup_rect = PixelRect::new(
3353 i64::from(anchor.x).clamp(margin, (width - margin - popup_w).max(margin)) as i32,
3354 y as i32,
3355 popup_w as u32,
3356 popup_h as u32,
3357 );
3358 if state.input.l_pressed
3361 && !point_in_rect(state.input.pointer_x, state.input.pointer_y, popup_rect)
3362 && !point_in_rect(state.input.pointer_x, state.input.pointer_y, anchor)
3363 {
3364 state.popup_open = 0;
3365 return false;
3366 }
3367
3368 state.cmds.push(UiCmd::Rect {
3370 rect: popup_rect,
3371 color: style.background,
3372 clip: popup_rect,
3373 corner_radius: style.corner_radius,
3374 });
3375 state.cmds.push(UiCmd::RectOutline {
3376 rect: popup_rect,
3377 color: style.border,
3378 thickness: 1,
3379 clip: popup_rect,
3380 corner_radius: style.corner_radius,
3381 });
3382
3383 let inner = UiLayout {
3384 padding: UiEdge::all(config.padding),
3385 gap: 4.0 * state.content_scale,
3386 ..UiLayout::default()
3387 };
3388 state.layout.push(PanelScope::new(popup_rect, inner));
3389 true
3390 }
3391
3392 pub fn end_popup(&mut self) {
3396 self.end_panel();
3397 }
3398
3399 pub fn menu_item(&mut self, label: &str, selected: bool, enabled: bool) -> bool {
3403 let Some(state) = self.state.as_mut() else {
3404 return false;
3405 };
3406 let style = Self::current_style_ref(state).clone();
3407 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
3408 let height = ((style.font_size + 8.0) * state.content_scale)
3409 .ceil()
3410 .max(1.0) as u32;
3411 let (rect, clip) = allocate_widget_explicit(state, style.padding, height);
3412
3413 let hovered = enabled && point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
3414 if hovered && state.input.l_pressed {
3415 state.pressed = id;
3416 }
3417 let held = enabled && state.pressed == id && state.input.pointer_down;
3418 let activated = hovered && state.input.l_released && state.pressed == id;
3419 if activated {
3420 state.popup_open = 0;
3422 }
3423 if hovered {
3424 state.hovered = id;
3425 }
3426
3427 let bg = if selected {
3428 Color::new(
3429 style.accent.r,
3430 style.accent.g,
3431 style.accent.b,
3432 if hovered { 0.35 } else { 0.22 },
3433 )
3434 } else if hovered || held {
3435 if held {
3436 style.surface_active
3437 } else {
3438 style.surface_hover
3439 }
3440 } else {
3441 Color::new(0.0, 0.0, 0.0, 0.0)
3442 };
3443 if bg.a > 0.0 {
3444 state.cmds.push(UiCmd::Rect {
3445 rect,
3446 color: bg,
3447 clip,
3448 corner_radius: (style.corner_radius * 0.65).min(rect.h as f32 * 0.5),
3449 });
3450 }
3451 let text_color = if enabled {
3452 style.text
3453 } else {
3454 style.text_disabled
3455 };
3456 let cfg = TextLayoutConfig {
3457 font: FontId::Sans,
3458 size: style.font_size * state.content_scale,
3459 ..Default::default()
3460 };
3461 if selected {
3462 state.cmds.push(UiCmd::Rect {
3463 rect: PixelRect::new(rect.x, rect.y, rect.w.min(3), rect.h),
3464 color: style.accent,
3465 clip,
3466 corner_radius: 1.5,
3467 });
3468 }
3469 let padding = ((6.0 + if selected { 4.0 } else { 0.0 }) * state.content_scale).round() as u32;
3470 let text_rect = PixelRect::new(
3471 rect.x + padding as i32,
3472 rect.y,
3473 rect.w.saturating_sub(padding),
3474 rect.h,
3475 );
3476 Self::emit_text_or_record(state, label, text_rect, text_color, cfg);
3477 activated
3478 }
3479
3480 pub fn menu(&mut self, label: &str) -> bool {
3487 let popup_label = format!("__menu_{label}");
3488 let Some(state) = self.state.as_mut() else {
3489 return false;
3490 };
3491 let style = Self::current_style_ref(state).clone();
3492 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
3493 let popup_id = widget_hash(&popup_label, None);
3494
3495 let (rect, clip) = allocate_widget(state, style.padding);
3496 state.focusables.push(id);
3497 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
3498 if hovered && state.input.l_pressed {
3499 state.focused = id;
3500 }
3501 let activated = (hovered && was_pressed_and_released(state, id)) || take_activate(state, id);
3502 if activated {
3503 if state.popup_open == popup_id {
3504 state.popup_open = 0;
3505 } else {
3506 state.popup_open = popup_id;
3507 state.popup_anchor = rect;
3508 }
3509 }
3510 if hovered {
3511 state.hovered = id;
3512 }
3513
3514 let open = state.popup_open == popup_id;
3515 state.cmds.push(UiCmd::Rect {
3516 rect,
3517 color: if open || hovered {
3518 style.surface
3519 } else {
3520 Color::new(
3521 style.surface.r * 0.85,
3522 style.surface.g * 0.85,
3523 style.surface.b * 0.85,
3524 1.0,
3525 )
3526 },
3527 clip,
3528 corner_radius: style.corner_radius,
3529 });
3530 state.cmds.push(UiCmd::RectOutline {
3531 rect,
3532 color: if open || state.focused == id {
3533 style.accent
3534 } else {
3535 style.border
3536 },
3537 thickness: 1,
3538 clip,
3539 corner_radius: style.corner_radius,
3540 });
3541 let cfg = TextLayoutConfig {
3542 font: FontId::SansSemibold,
3543 size: style.font_size,
3544 ..TextLayoutConfig::default()
3545 };
3546 Self::emit_text_or_record(state, label, rect, style.text, cfg);
3547 if !open {
3548 return false;
3549 }
3550 self.begin_popup(
3551 &popup_label,
3552 UiPopupConfig {
3553 width: 0.0,
3554 height: 0.0,
3555 gap: 2.0,
3556 padding: 4.0,
3557 },
3558 )
3559 }
3560
3561 pub fn end_menu(&mut self) {
3563 self.end_popup();
3564 }
3565
3566 pub fn dropdown(
3575 &mut self,
3576 label: &str,
3577 items: &[&str],
3578 selected: &mut i32,
3579 _config: UiDropdownConfig,
3580 ) -> bool {
3581 let Some(state) = self.state.as_mut() else {
3582 return false;
3583 };
3584 let style = Self::current_style_ref(state).clone();
3585 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
3586 let popup_id = widget_hash(&format!("__dd_{label}"), None);
3587
3588 let (rect, clip) = allocate_widget(state, style.padding);
3589 state.focusables.push(id);
3590 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
3591 if hovered {
3592 state.hovered = id;
3593 }
3594 if hovered && state.input.l_pressed {
3595 state.focused = id;
3596 }
3597
3598 let clicked = (hovered && was_pressed_and_released(state, id)) || take_activate(state, id);
3599 if clicked {
3600 if state.popup_open == popup_id {
3601 state.popup_open = 0;
3602 } else {
3603 state.popup_open = popup_id;
3604 state.popup_anchor = rect;
3605 }
3606 }
3607
3608 let is_open = state.popup_open == popup_id;
3610 let bg = if is_open || hovered {
3611 style.surface
3612 } else {
3613 Color::new(
3614 style.surface.r * 0.85,
3615 style.surface.g * 0.85,
3616 style.surface.b * 0.85,
3617 1.0,
3618 )
3619 };
3620 state.cmds.push(UiCmd::Rect {
3621 rect,
3622 color: bg,
3623 clip,
3624 corner_radius: style.corner_radius,
3625 });
3626 state.cmds.push(UiCmd::RectOutline {
3627 rect,
3628 color: if is_open { style.accent } else { style.border },
3629 thickness: 1,
3630 clip,
3631 corner_radius: style.corner_radius,
3632 });
3633 let display = if *selected >= 0 && (*selected as usize) < items.len() {
3634 items[*selected as usize]
3635 } else {
3636 label
3637 };
3638 let cfg = TextLayoutConfig {
3639 font: FontId::Sans,
3640 size: style.font_size - 1.0,
3641 ..Default::default()
3642 };
3643 Self::emit_text_or_record(state, display, rect, style.text, cfg);
3644
3645 let mut changed = false;
3647 if is_open && !items.is_empty() {
3648 let item_h = default_item_height(style.padding) as i32;
3649 let popup_h = (items.len() as i32 * (item_h + 2) + 8).min(300);
3650 let popup_rect = PixelRect {
3651 x: rect.x,
3652 y: rect.y + rect.h as i32 + 2,
3653 w: rect.w,
3654 h: popup_h as u32,
3655 };
3656 if state.input.l_pressed
3658 && !point_in_rect(state.input.pointer_x, state.input.pointer_y, popup_rect)
3659 && !point_in_rect(state.input.pointer_x, state.input.pointer_y, rect)
3660 {
3661 state.popup_open = 0;
3662 } else {
3663 state.cmds.push(UiCmd::Rect {
3664 rect: popup_rect,
3665 color: style.background,
3666 clip: popup_rect,
3667 corner_radius: style.corner_radius,
3668 });
3669 state.cmds.push(UiCmd::RectOutline {
3670 rect: popup_rect,
3671 color: style.border,
3672 thickness: 1,
3673 clip: popup_rect,
3674 corner_radius: style.corner_radius,
3675 });
3676 for (i, &item) in items.iter().enumerate() {
3677 let item_rect = PixelRect {
3678 x: popup_rect.x + 4,
3679 y: popup_rect.y + 4 + i as i32 * (item_h + 2),
3680 w: popup_rect.w.saturating_sub(8),
3681 h: item_h as u32,
3682 };
3683 let hov = point_in_rect(state.input.pointer_x, state.input.pointer_y, item_rect);
3684 let iid = widget_hash(&format!("__ddi_{i}_{label}"), None);
3685 if hov {
3686 state.hovered = iid;
3687 }
3688 if hov && was_pressed_and_released(state, iid) {
3689 *selected = i as i32;
3690 state.popup_open = 0;
3691 changed = true;
3692 }
3693 let item_bg = if *selected == i as i32 {
3694 Color::new(
3695 style.accent.r * 0.3,
3696 style.accent.g * 0.3,
3697 style.accent.b * 0.4,
3698 1.0,
3699 )
3700 } else if hov {
3701 style.surface
3702 } else {
3703 Color::new(0.0, 0.0, 0.0, 0.0)
3704 };
3705 if item_bg.a > 0.0 {
3706 state.cmds.push(UiCmd::Rect {
3707 rect: item_rect,
3708 color: item_bg,
3709 clip: popup_rect,
3710 corner_radius: 0.0,
3711 });
3712 }
3713 let icfg = TextLayoutConfig {
3714 font: FontId::Sans,
3715 size: style.font_size - 1.0,
3716 ..Default::default()
3717 };
3718 Self::emit_text_or_record(state, item, item_rect, style.text, icfg);
3719 }
3720 }
3721 }
3722 changed
3723 }
3724
3725 pub fn combo(
3734 &mut self,
3735 label: &str,
3736 items: &[&str],
3737 selected: &mut i32,
3738 filter: &mut String,
3739 ) -> bool {
3740 let Some(state) = self.state.as_mut() else {
3741 return false;
3742 };
3743 let style = Self::current_style_ref(state).clone();
3744 let id = widget_hash(label, state.layout.top().map(|s| s.outer));
3745 let popup_id = widget_hash(&format!("__cb_{label}"), None);
3746
3747 let (rect, clip) = allocate_widget(state, style.padding);
3748 state.focusables.push(id);
3749 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
3750 if hovered {
3751 state.hovered = id;
3752 }
3753
3754 let clicked = (hovered && was_pressed_and_released(state, id)) || take_activate(state, id);
3755 if clicked {
3756 if state.popup_open == popup_id {
3757 state.popup_open = 0;
3758 state.focused = 0;
3759 } else {
3760 state.popup_open = popup_id;
3761 state.popup_anchor = rect;
3762 state.focused = id;
3763 }
3764 }
3765
3766 let is_open = state.popup_open == popup_id;
3767 let bg = if is_open || hovered {
3768 style.surface
3769 } else {
3770 Color::new(
3771 style.surface.r * 0.85,
3772 style.surface.g * 0.85,
3773 style.surface.b * 0.85,
3774 1.0,
3775 )
3776 };
3777 state.cmds.push(UiCmd::Rect {
3778 rect,
3779 color: bg,
3780 clip,
3781 corner_radius: style.corner_radius,
3782 });
3783 state.cmds.push(UiCmd::RectOutline {
3784 rect,
3785 color: if is_open { style.accent } else { style.border },
3786 thickness: 1,
3787 clip,
3788 corner_radius: style.corner_radius,
3789 });
3790
3791 let display: &str = if is_open {
3794 filter.as_str()
3795 } else if *selected >= 0 && (*selected as usize) < items.len() {
3796 items[*selected as usize]
3797 } else {
3798 label
3799 };
3800 let cfg = TextLayoutConfig {
3801 font: FontId::Sans,
3802 size: style.font_size - 1.0,
3803 ..Default::default()
3804 };
3805 Self::emit_text_or_record(state, display, rect, style.text, cfg);
3806
3807 let mut changed = false;
3810 if is_open && state.focused == id {
3811 for ch in state.input_pending_chars.drain(..) {
3812 if ch == '\n' {
3813 continue;
3814 }
3815 filter.push(ch);
3816 }
3817 if state.input_pending_backspace > 0 {
3818 for _ in 0..state.input_pending_backspace {
3819 filter.pop();
3820 }
3821 }
3822 state.input_pending_backspace = 0;
3823 }
3824
3825 if is_open && !items.is_empty() {
3827 let needle = filter.to_lowercase();
3828 let visible: Vec<usize> = items
3829 .iter()
3830 .enumerate()
3831 .filter(|(_, item)| needle.is_empty() || item.to_lowercase().contains(&needle))
3832 .map(|(index, _)| index)
3833 .collect();
3834 let item_h = default_item_height(style.padding) as i32;
3835 let popup_h = (visible.len() as i32 * (item_h + 2) + 8).clamp(item_h + 10, 300);
3836 let popup_rect = PixelRect {
3837 x: rect.x,
3838 y: rect.y + rect.h as i32 + 2,
3839 w: rect.w,
3840 h: popup_h as u32,
3841 };
3842 if state.input.l_pressed
3843 && !point_in_rect(state.input.pointer_x, state.input.pointer_y, popup_rect)
3844 && !point_in_rect(state.input.pointer_x, state.input.pointer_y, rect)
3845 {
3846 state.popup_open = 0;
3847 state.focused = 0;
3848 } else {
3849 state.cmds.push(UiCmd::Rect {
3850 rect: popup_rect,
3851 color: style.background,
3852 clip: popup_rect,
3853 corner_radius: style.corner_radius,
3854 });
3855 state.cmds.push(UiCmd::RectOutline {
3856 rect: popup_rect,
3857 color: style.border,
3858 thickness: 1,
3859 clip: popup_rect,
3860 corner_radius: style.corner_radius,
3861 });
3862 for (row, &i) in visible.iter().enumerate() {
3863 let item_rect = PixelRect {
3864 x: popup_rect.x + 4,
3865 y: popup_rect.y + 4 + row as i32 * (item_h + 2),
3866 w: popup_rect.w.saturating_sub(8),
3867 h: item_h as u32,
3868 };
3869 let hov = point_in_rect(state.input.pointer_x, state.input.pointer_y, item_rect);
3870 let iid = widget_hash(&format!("__cbi_{i}_{label}"), None);
3871 if hov {
3872 state.hovered = iid;
3873 }
3874 if hov && was_pressed_and_released(state, iid) {
3875 *selected = i as i32;
3876 *filter = items[i].to_owned();
3877 state.popup_open = 0;
3878 state.focused = 0;
3879 changed = true;
3880 }
3881 let item_bg = if *selected == i as i32 {
3882 Color::new(
3883 style.accent.r * 0.3,
3884 style.accent.g * 0.3,
3885 style.accent.b * 0.4,
3886 1.0,
3887 )
3888 } else if hov {
3889 style.surface
3890 } else {
3891 Color::new(0.0, 0.0, 0.0, 0.0)
3892 };
3893 if item_bg.a > 0.0 {
3894 state.cmds.push(UiCmd::Rect {
3895 rect: item_rect,
3896 color: item_bg,
3897 clip: popup_rect,
3898 corner_radius: 0.0,
3899 });
3900 }
3901 let icfg = TextLayoutConfig {
3902 font: FontId::Sans,
3903 size: style.font_size - 1.0,
3904 ..Default::default()
3905 };
3906 Self::emit_text_or_record(state, items[i], item_rect, style.text, icfg);
3907 }
3908 if visible.is_empty() {
3909 let icfg = TextLayoutConfig {
3910 font: FontId::Sans,
3911 size: style.font_size - 1.0,
3912 ..Default::default()
3913 };
3914 let empty_rect = PixelRect {
3915 x: popup_rect.x + 4,
3916 y: popup_rect.y + 4,
3917 w: popup_rect.w.saturating_sub(8),
3918 h: item_h as u32,
3919 };
3920 Self::emit_text_or_record(
3921 state,
3922 "(no matches)",
3923 empty_rect,
3924 style.text_secondary,
3925 icfg,
3926 );
3927 }
3928 }
3929 }
3930 changed
3931 }
3932
3933 pub fn table(
3943 &mut self,
3944 id: &str,
3945 columns: &[&str],
3946 rows: &[&[&str]],
3947 widths: &[f32],
3948 state: &mut UiTableState,
3949 config: UiTableConfig,
3950 ) -> bool {
3951 let Some(ui_state) = self.state.as_mut() else {
3952 return false;
3953 };
3954 let style = Self::current_style_ref(ui_state).clone();
3955 if columns.is_empty() {
3956 return false;
3957 }
3958 let item_h = default_item_height(style.padding) as i32;
3959 let row_h = if config.row_height > 0 {
3960 config.row_height
3961 } else {
3962 item_h
3963 };
3964 let visible = if config.max_visible_rows > 0 {
3965 rows.len().min(config.max_visible_rows as usize)
3966 } else {
3967 rows.len()
3968 };
3969 let header_h = if config.show_header { item_h } else { 0 };
3970 let total_h = (header_h + (visible as i32).max(1) * row_h).max(item_h);
3971
3972 let (rect, clip) = allocate_widget_explicit(ui_state, style.padding, total_h as u32);
3973 if rect.w == 0 || rect.h == 0 {
3974 return false;
3975 }
3976 ui_state.cmds.push(UiCmd::Rect {
3977 rect,
3978 color: style.surface,
3979 clip,
3980 corner_radius: style.corner_radius,
3981 });
3982 ui_state.cmds.push(UiCmd::RectOutline {
3983 rect,
3984 color: style.border,
3985 thickness: 1,
3986 clip,
3987 corner_radius: style.corner_radius,
3988 });
3989
3990 let ratios: Vec<f32> = if widths.len() == columns.len() && widths.iter().all(|w| *w > 0.0) {
3992 let sum: f32 = widths.iter().sum();
3993 widths.iter().map(|w| w / sum).collect()
3994 } else {
3995 vec![1.0 / columns.len() as f32; columns.len()]
3996 };
3997 let mut col_x = Vec::with_capacity(columns.len() + 1);
3998 col_x.push(rect.x);
3999 for ratio in &ratios {
4000 col_x.push(col_x.last().copied().unwrap_or(rect.x) + (ratio * rect.w as f32) as i32);
4001 }
4002 col_x[columns.len()] = rect.x + rect.w as i32;
4003
4004 let cell_rect = |row_y: i32, col: usize| PixelRect {
4005 x: col_x[col] + 4,
4006 y: row_y,
4007 w: (col_x[col + 1] - col_x[col] - 8).max(0) as u32,
4008 h: row_h.max(item_h) as u32,
4009 };
4010
4011 if config.show_header {
4013 let header = PixelRect {
4014 x: rect.x,
4015 y: rect.y,
4016 w: rect.w,
4017 h: header_h as u32,
4018 };
4019 ui_state.cmds.push(UiCmd::Rect {
4020 rect: header,
4021 color: style.surface_hover,
4022 clip,
4023 corner_radius: 0.0,
4024 });
4025 let hcfg = TextLayoutConfig {
4026 font: FontId::Sans,
4027 size: style.font_size - 1.0,
4028 ..Default::default()
4029 };
4030 for (col, name) in columns.iter().enumerate() {
4031 Self::emit_text_or_record(
4032 ui_state,
4033 name,
4034 cell_rect(rect.y, col),
4035 style.text_secondary,
4036 hcfg,
4037 );
4038 }
4039 ui_state.cmds.push(UiCmd::Rect {
4040 rect: PixelRect {
4041 x: rect.x,
4042 y: rect.y + header_h - 1,
4043 w: rect.w,
4044 h: 1,
4045 },
4046 color: style.border,
4047 clip,
4048 corner_radius: 0.0,
4049 });
4050 }
4051
4052 let mut changed = false;
4054 let tcfg = TextLayoutConfig {
4055 font: FontId::Sans,
4056 size: style.font_size - 1.0,
4057 ..Default::default()
4058 };
4059 for (index, cells) in rows.iter().enumerate().take(visible) {
4060 let row_y = rect.y + header_h + index as i32 * row_h;
4061 let row_rect = PixelRect {
4062 x: rect.x,
4063 y: row_y,
4064 w: rect.w,
4065 h: row_h as u32,
4066 };
4067 let rid = widget_hash(&format!("__tbl_{id}_{index}"), None);
4068 let hov = point_in_rect(ui_state.input.pointer_x, ui_state.input.pointer_y, row_rect);
4069 if hov {
4070 ui_state.hovered = rid;
4071 }
4072 if hov && was_pressed_and_released(ui_state, rid) {
4073 state.selected = index as i32;
4074 changed = true;
4075 }
4076 let row_bg = if state.selected == index as i32 {
4077 Color::new(
4078 style.accent.r * 0.3,
4079 style.accent.g * 0.3,
4080 style.accent.b * 0.4,
4081 1.0,
4082 )
4083 } else if hov {
4084 style.surface_hover
4085 } else if config.zebra && index % 2 == 1 {
4086 Color::new(
4087 style.surface_hover.r,
4088 style.surface_hover.g,
4089 style.surface_hover.b,
4090 0.4,
4091 )
4092 } else {
4093 Color::new(0.0, 0.0, 0.0, 0.0)
4094 };
4095 if row_bg.a > 0.0 {
4096 ui_state.cmds.push(UiCmd::Rect {
4097 rect: row_rect,
4098 color: row_bg,
4099 clip,
4100 corner_radius: 0.0,
4101 });
4102 }
4103 for (col, name) in cells.iter().enumerate() {
4104 if col >= columns.len() {
4105 break;
4106 }
4107 Self::emit_text_or_record(ui_state, name, cell_rect(row_y, col), style.text, tcfg);
4108 }
4109 }
4110 changed
4111 }
4112
4113 pub fn tooltip(&mut self, text: &str, _config: UiTooltipConfig) {
4121 let Some(state) = self.state.as_mut() else {
4122 return;
4123 };
4124 if state.hovered == 0 {
4125 return;
4126 }
4127 let style = Self::current_style_ref(state).clone();
4128 let px = state.input.pointer_x;
4129 let py = state.input.pointer_y;
4130 let pad = _config.padding;
4131 let max_w = _config.max_width as u32;
4132 let tip_h = (style.font_size + pad * 2.0) as u32;
4133 let tip_rect = PixelRect {
4134 x: px as i32 + _config.gap as i32,
4135 y: py as i32 - tip_h as i32 - _config.gap as i32,
4136 w: max_w,
4137 h: tip_h,
4138 };
4139 state.cmds.push(UiCmd::Rect {
4140 rect: tip_rect,
4141 color: Color::new(
4142 style.surface.r * 1.15,
4143 style.surface.g * 1.15,
4144 style.surface.b * 1.15,
4145 0.95,
4146 ),
4147 clip: tip_rect,
4148 corner_radius: style.corner_radius,
4149 });
4150 state.cmds.push(UiCmd::RectOutline {
4151 rect: tip_rect,
4152 color: style.border,
4153 thickness: 1,
4154 clip: tip_rect,
4155 corner_radius: style.corner_radius,
4156 });
4157 let cfg = TextLayoutConfig {
4158 font: FontId::Sans,
4159 size: style.font_size - 1.0,
4160 ..Default::default()
4161 };
4162 Self::emit_text_or_record(state, text, tip_rect, style.text, cfg);
4163 }
4164
4165 pub fn heatmap_inline(
4174 &mut self,
4175 _label: &str,
4176 data: &[f32],
4177 config: UiHeatmapConfig,
4178 ) -> Result<()> {
4179 if config.rows <= 0 || config.cols <= 0 {
4180 return Err(Error::invalid_argument("heatmap rows and cols must be > 0"));
4181 }
4182 let n = (config.rows * config.cols) as usize;
4183 let data_slice = if data.len() >= n { &data[..n] } else { data };
4184
4185 let (v_min, v_max) = if config.auto_scale && !data_slice.is_empty() {
4186 let lo = data_slice.iter().cloned().fold(f32::INFINITY, f32::min);
4187 let hi = data_slice.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
4188 if lo < hi {
4189 (lo, hi)
4190 } else {
4191 (config.v_min, config.v_max)
4192 }
4193 } else {
4194 (config.v_min, config.v_max)
4195 };
4196 let range = (v_max - v_min).max(1e-9);
4197
4198 let style;
4199 let rect;
4200 let clip;
4201 {
4202 let Some(state) = self.state.as_mut() else {
4203 return Ok(());
4204 };
4205 style = Self::current_style_ref(state).clone();
4206 let alloc_h = (config.rows as u32) * (default_item_height(style.padding));
4207 let (r, c) = allocate_widget_explicit(state, style.padding, alloc_h);
4208 rect = r;
4209 clip = c;
4210 }
4211
4212 let cell_w = (rect.w / config.cols as u32).max(1);
4213 let cell_h = (rect.h / config.rows as u32).max(1);
4214
4215 for row in 0..config.rows {
4216 for col in 0..config.cols {
4217 let idx = (row * config.cols + col) as usize;
4218 let val = if idx < data_slice.len() {
4219 data_slice[idx]
4220 } else {
4221 0.0
4222 };
4223 let t = ((val - v_min) / range).clamp(0.0, 1.0);
4224 let color = colormap_sample(t, config.colormap);
4226 let cx = rect.x + col * cell_w as i32;
4227 let cy = rect.y + row * cell_h as i32;
4228 let cell_rect = PixelRect {
4229 x: cx,
4230 y: cy,
4231 w: cell_w,
4232 h: cell_h,
4233 };
4234 if let Some(state) = self.state.as_mut() {
4235 state.cmds.push(UiCmd::Rect {
4236 rect: cell_rect,
4237 color,
4238 clip,
4239 corner_radius: 0.0,
4240 });
4241 if config.show_grid {
4242 state.cmds.push(UiCmd::RectOutline {
4243 rect: cell_rect,
4244 color: style.border,
4245 thickness: 1,
4246 clip,
4247 corner_radius: 0.0,
4248 });
4249 }
4250 }
4251 }
4252 }
4253 Ok(())
4254 }
4255
4256 pub fn text(&mut self, content: &str) {
4264 let Some(state) = self.state.as_mut() else {
4265 return;
4266 };
4267 let style = Self::current_style_ref(state).clone();
4268 let (rect, _clip) = allocate_widget(state, style.padding);
4269 if rect.w == 0 || rect.h == 0 {
4270 return;
4271 }
4272 let cfg = TextLayoutConfig {
4273 font: FontId::Sans,
4274 size: style.font_size,
4275 ..Default::default()
4276 };
4277 Self::emit_text_or_record(state, content, rect, style.text, cfg);
4278 }
4279
4280 pub fn label_fmt(&mut self, text: &str) {
4284 self.label(text);
4288 }
4289
4290 pub fn icon_button(
4296 &mut self,
4297 id: &str,
4298 rect: PixelRect,
4299 icon: UiIcon,
4300 enabled: bool,
4301 style_kind: UiIconButtonStyle,
4302 ) -> bool {
4303 let Some(state) = self.state.as_mut() else {
4304 return false;
4305 };
4306 if rect.w == 0
4307 || rect.h == 0
4308 || rect.w > state.compose.width
4309 || rect.h > state.compose.height
4310 || rect.w > i32::MAX as u32
4311 || rect.h > i32::MAX as u32
4312 || rect.x.checked_add(rect.w as i32).is_none()
4313 || rect.y.checked_add(rect.h as i32).is_none()
4314 {
4315 if state.recording_error.is_none() {
4316 state.recording_error = Some(Error::invalid_argument(
4317 "icon_button requires bounded nonempty geometry",
4318 ));
4319 }
4320 return false;
4321 }
4322 let widget_id = widget_hash(id, Some(rect));
4323 let hovered = enabled && point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
4324 if hovered {
4325 state.hovered = widget_id;
4326 }
4327 if hovered && state.input.l_pressed {
4328 state.pressed = widget_id;
4329 }
4330 let activated = hovered && state.input.l_released && state.pressed == widget_id;
4331 let held = enabled && state.pressed == widget_id && state.input.pointer_down;
4332 let hover_mix = animate_hover(state, widget_id, hovered);
4333 let window_control = style_kind == UiIconButtonStyle::WindowControl;
4334 let inset = if window_control {
4335 (5.0 * state.content_scale).round() as u32
4336 } else {
4337 0
4338 };
4339 let fill_rect = if inset.saturating_mul(2) < rect.w.min(rect.h) {
4340 PixelRect::new(
4341 rect.x + inset as i32,
4342 rect.y + inset as i32,
4343 rect.w - inset * 2,
4344 rect.h - inset * 2,
4345 )
4346 } else {
4347 rect
4348 };
4349 let fill_alpha = if !enabled {
4350 0.0
4351 } else if held || activated {
4352 0.30
4353 } else {
4354 0.15 * hover_mix
4355 };
4356 if fill_alpha > 0.0 {
4357 state.cmds.push(UiCmd::Rect {
4358 rect: fill_rect,
4359 color: Color::new(1.0, 1.0, 1.0, fill_alpha),
4360 clip: rect,
4361 corner_radius: fill_rect.w.min(fill_rect.h) as f32 * 0.5,
4362 });
4363 }
4364 if state.focused == widget_id {
4365 state.cmds.push(UiCmd::RectOutline {
4366 rect,
4367 color: Self::current_style_ref(state).accent,
4368 thickness: 1,
4369 clip: rect,
4370 corner_radius: rect.w.min(rect.h) as f32 * 0.5,
4371 });
4372 }
4373 let alpha = if !enabled {
4374 0.38
4375 } else if style_kind == UiIconButtonStyle::Overlay {
4376 0.94
4377 } else if held || activated {
4378 1.0
4379 } else {
4380 0.68 + 0.32 * hover_mix
4381 };
4382 let color = Color::new(1.0, 1.0, 1.0, alpha);
4383 let transport = if enabled {
4384 Color::new(1.0, 1.0, 1.0, 1.0)
4385 } else {
4386 color
4387 };
4388 let viewport = PixelRect::new(0, 0, state.compose.width, state.compose.height);
4389 let clip = state
4390 .layout
4391 .top()
4392 .map_or(viewport, |panel| viewport.clip(&panel.clip()))
4393 .clip(&rect);
4394 if clip.w != 0 && clip.h != 0 {
4395 icons::draw(
4396 &mut state.cmds,
4397 rect,
4398 clip,
4399 icon,
4400 state.content_scale,
4401 window_control,
4402 [color, transport],
4403 );
4404 }
4405 activated
4406 }
4407
4408 pub fn heatmap_matrix_at(
4411 &mut self,
4412 values: &crate::Matrix,
4413 rect: PixelRect,
4414 range: [f32; 2],
4415 colormap: u32,
4416 show_grid: bool,
4417 ) -> Result<()> {
4418 let state = self
4419 .state
4420 .as_mut()
4421 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
4422 if values.dtype() != crate::DType::F32
4423 || values.shape().len() != 2
4424 || values.shape().contains(&0)
4425 || !values.runtime().same_as(&state.runtime)
4426 || !range.iter().all(|v| v.is_finite())
4427 || range[0] >= range[1]
4428 || colormap > 3
4429 {
4430 return Err(Error::invalid_argument(
4431 "heatmap requires an owned dense FP32 matrix and finite increasing range",
4432 ));
4433 }
4434 let rows = u32::try_from(values.shape()[0])
4435 .map_err(|_| Error::out_of_range("heatmap rows exceed u32"))?;
4436 let cols = u32::try_from(values.shape()[1])
4437 .map_err(|_| Error::out_of_range("heatmap columns exceed u32"))?;
4438 if rect.w == 0
4439 || rect.h == 0
4440 || rect.w > state.compose.width
4441 || rect.h > state.compose.height
4442 || rect
4443 .x
4444 .checked_add(
4445 i32::try_from(rect.w).map_err(|_| Error::out_of_range("heatmap width exceeds i32"))?,
4446 )
4447 .is_none()
4448 || rect
4449 .y
4450 .checked_add(
4451 i32::try_from(rect.h).map_err(|_| Error::out_of_range("heatmap height exceeds i32"))?,
4452 )
4453 .is_none()
4454 || u64::from(rows) * u64::from(cols) > u64::from(u32::MAX / 4)
4455 || cols.checked_mul(rect.w).is_none()
4456 || rows.checked_mul(rect.h).is_none()
4457 {
4458 return Err(Error::out_of_range(
4459 "heatmap geometry or indexing exceeds donor ABI",
4460 ));
4461 }
4462 let viewport = PixelRect::new(0, 0, state.compose.width, state.compose.height);
4463 let clip = state
4464 .layout
4465 .top()
4466 .map_or(viewport, |panel| viewport.clip(&panel.clip()))
4467 .clip(&rect);
4468 let values_idx = state.runtime.storage_descriptor_index(values.storage())?;
4469 let push = [
4470 values_idx,
4471 rows,
4472 cols,
4473 0,
4474 rect.x as u32,
4475 rect.y as u32,
4476 rect.w,
4477 rect.h,
4478 range[0].to_bits(),
4479 range[1].to_bits(),
4480 colormap,
4481 0,
4482 0,
4483 u32::from(show_grid),
4484 clip.x as u32,
4485 clip.y as u32,
4486 clip.w,
4487 clip.h,
4488 ];
4489 state.cmds.push(UiCmd::Heatmap {
4490 values_idx,
4491 rect,
4492 push,
4493 });
4494 state.frame_matrices.push(values.clone());
4495 Ok(())
4496 }
4497
4498 pub fn waveform_matrix_at(
4501 &mut self,
4502 values: &crate::Matrix,
4503 rect: PixelRect,
4504 fraction: f32,
4505 played: Color,
4506 remaining: Color,
4507 ) -> Result<()> {
4508 let state = self
4509 .state
4510 .as_mut()
4511 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
4512 if values.dtype() != crate::DType::F32
4513 || values.shape().len() != 2
4514 || values.shape()[1] != 2
4515 || values.shape()[0] == 0
4516 || !values.runtime().same_as(&state.runtime)
4517 || !fraction.is_finite()
4518 || !played
4519 .to_array()
4520 .iter()
4521 .chain(remaining.to_array().iter())
4522 .all(|v| v.is_finite())
4523 {
4524 return Err(Error::invalid_argument(
4525 "waveform requires an owned FP32 [bins, 2] envelope and finite colors/fraction",
4526 ));
4527 }
4528 let bins = u32::try_from(values.shape()[0])
4529 .map_err(|_| Error::out_of_range("waveform bins exceed u32"))?;
4530 if rect.w == 0
4531 || rect.h == 0
4532 || rect.w > state.compose.width
4533 || rect.h > state.compose.height
4534 || rect
4535 .x
4536 .checked_add(
4537 i32::try_from(rect.w).map_err(|_| Error::out_of_range("waveform width exceeds i32"))?,
4538 )
4539 .is_none()
4540 || rect
4541 .y
4542 .checked_add(
4543 i32::try_from(rect.h).map_err(|_| Error::out_of_range("waveform height exceeds i32"))?,
4544 )
4545 .is_none()
4546 || bins > u32::MAX / 8
4547 || bins.checked_mul(rect.w).is_none()
4548 {
4549 return Err(Error::out_of_range(
4550 "waveform geometry or indexing exceeds donor ABI",
4551 ));
4552 }
4553 let viewport = PixelRect::new(0, 0, state.compose.width, state.compose.height);
4554 let clip = state
4555 .layout
4556 .top()
4557 .map_or(viewport, |panel| viewport.clip(&panel.clip()))
4558 .clip(&rect);
4559 let values_idx = state.runtime.storage_descriptor_index(values.storage())?;
4560 let push = [
4561 values_idx,
4562 bins,
4563 0,
4564 rect.x as u32,
4565 rect.y as u32,
4566 rect.w,
4567 rect.h,
4568 fraction.clamp(0.0, 1.0).to_bits(),
4569 played.to_u32(),
4570 remaining.to_u32(),
4571 clip.x as u32,
4572 clip.y as u32,
4573 clip.w,
4574 clip.h,
4575 ];
4576 state.cmds.push(UiCmd::Waveform {
4577 values_idx,
4578 rect,
4579 push,
4580 });
4581 state.frame_matrices.push(values.clone());
4582 Ok(())
4583 }
4584
4585 pub fn waveform_matrix_timeline(
4588 &mut self,
4589 id: &str,
4590 rect: PixelRect,
4591 values: &crate::Matrix,
4592 fraction: &mut f32,
4593 ) -> Result<bool> {
4594 let state = self
4595 .state
4596 .as_mut()
4597 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
4598 let widget_id = widget_hash(id, Some(rect));
4599 let hovered = point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
4600 if hovered {
4601 state.hovered = widget_id;
4602 }
4603 if hovered && state.input.l_pressed {
4604 state.pressed = widget_id;
4605 state.focused = widget_id;
4606 }
4607 let held = state.pressed == widget_id && state.input.pointer_down;
4608 let activated = hovered && state.input.l_released && state.pressed == widget_id;
4609 let mut changed = false;
4610 if held || activated {
4611 let next = ((state.input.pointer_x - rect.x as f32) / rect.w.max(1) as f32).clamp(0.0, 1.0);
4612 changed = next != *fraction;
4613 *fraction = next;
4614 }
4615 let style = Self::current_style_ref(state).clone();
4616 let scale = state.content_scale;
4617 let remaining = Color {
4618 a: 0.60,
4619 ..style.text_secondary
4620 };
4621 self.waveform_matrix_at(values, rect, *fraction, style.accent, remaining)?;
4622 let base = ((20.0 * scale).round().max(1.0) as u32).min(rect.h);
4623 let center = rect.x
4624 + base as i32 / 2
4625 + (rect.w.saturating_sub(base) as f32 * fraction.clamp(0.0, 1.0)).round() as i32;
4626 let width = ((if hovered || held { 3.0 } else { 2.0 }) * scale)
4627 .round()
4628 .max(1.0) as u32;
4629 let width = width.min(rect.w);
4630 let x = (center - width as i32 / 2).clamp(rect.x, rect.x + rect.w as i32 - width as i32);
4631 self.rect_raw(
4632 PixelRect::new(x, rect.y, width, rect.h),
4633 if hovered || held {
4634 style.accent_hover
4635 } else {
4636 style.text
4637 },
4638 rect,
4639 0.0,
4640 );
4641 Ok(changed)
4642 }
4643
4644 pub fn mask_rounded_rect(&mut self, rect: PixelRect, radius: f32, outside: Color) -> Result<()> {
4646 let state = self
4647 .state
4648 .as_mut()
4649 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
4650 if rect.w == 0
4651 || rect.h == 0
4652 || rect.w > state.compose.width
4653 || rect.h > state.compose.height
4654 || rect.x.checked_add(rect.w as i32).is_none()
4655 || rect.y.checked_add(rect.h as i32).is_none()
4656 || !radius.is_finite()
4657 || radius < 0.0
4658 || !outside.to_array().iter().all(|v| v.is_finite())
4659 {
4660 return Err(Error::invalid_argument(
4661 "rounded mask requires bounded geometry and finite radius/color",
4662 ));
4663 }
4664 let viewport = PixelRect::new(0, 0, state.compose.width, state.compose.height);
4665 let clip = state
4666 .layout
4667 .top()
4668 .map_or(viewport, |panel| viewport.clip(&panel.clip()))
4669 .clip(&rect);
4670 if clip.w != 0 && clip.h != 0 {
4671 state.cmds.push(UiCmd::RoundedMask {
4672 rect,
4673 radius,
4674 outside,
4675 clip,
4676 });
4677 }
4678 Ok(())
4679 }
4680
4681 pub fn chevron_button(
4685 &mut self,
4686 id: &str,
4687 rect: PixelRect,
4688 direction: UiChevronDirection,
4689 enabled: bool,
4690 ) -> bool {
4691 let icon = match direction {
4692 UiChevronDirection::Previous => UiIcon::Previous,
4693 UiChevronDirection::Next => UiIcon::Next,
4694 };
4695 self.icon_button(id, rect, icon, enabled, UiIconButtonStyle::Header)
4696 }
4697
4698 pub fn text_button(
4702 &mut self,
4703 id: &str,
4704 rect: PixelRect,
4705 text: &str,
4706 text_color: Color,
4707 enabled: bool,
4708 ) -> bool {
4709 let Some(state) = self.state.as_mut() else {
4710 return false;
4711 };
4712 let style = Self::current_style_ref(state).clone();
4713 let widget_id = widget_hash(id, Some(rect));
4714 let clip = rect;
4715
4716 let hovered = enabled && point_in_rect(state.input.pointer_x, state.input.pointer_y, rect);
4717 let activated = hovered && was_pressed_and_released(state, widget_id);
4718 if hovered {
4719 state.hovered = widget_id;
4720 }
4721 if hovered && state.input.pointer_down {
4722 state.pressed = widget_id;
4723 }
4724
4725 let bg = if state.pressed == widget_id {
4726 Color::new(
4727 style.accent.r * 0.7,
4728 style.accent.g * 0.7,
4729 style.accent.b * 0.7,
4730 1.0,
4731 )
4732 } else if hovered {
4733 style.surface
4734 } else {
4735 Color::new(0.0, 0.0, 0.0, 0.0)
4736 };
4737 if bg.a > 0.0 {
4738 state.cmds.push(UiCmd::Rect {
4739 rect,
4740 color: bg,
4741 clip,
4742 corner_radius: style.corner_radius,
4743 });
4744 }
4745 let effective_color = if enabled {
4746 text_color
4747 } else {
4748 style.text_secondary
4749 };
4750 let cfg = TextLayoutConfig {
4751 font: FontId::Sans,
4752 size: style.font_size,
4753 ..Default::default()
4754 };
4755 Self::emit_text_or_record(state, text, rect, effective_color, cfg);
4756 activated
4757 }
4758
4759 pub fn grid(&mut self, rect: PixelRect, config: UiGridConfig) {
4766 let Some(state) = self.state.as_mut() else {
4767 return;
4768 };
4769 let thicknesses = [
4770 config.minor_thickness,
4771 config.major_thickness,
4772 config.super_major_thickness,
4773 config.axis_thickness,
4774 ];
4775 let colors = [
4776 config.background_top,
4777 config.background_bottom,
4778 config.minor_color,
4779 config.major_color,
4780 config.super_major_color,
4781 config.axis_color,
4782 ];
4783 let valid = rect.w != 0
4784 && rect.h != 0
4785 && rect.w <= i32::MAX as u32
4786 && rect.h <= i32::MAX as u32
4787 && thicknesses
4788 .iter()
4789 .all(|v| v.is_finite() && *v > 0.0 && *v <= 16.0)
4790 && config
4791 .origin
4792 .iter()
4793 .chain(config.guide_fade_center.iter())
4794 .all(|v| v.is_finite())
4795 && config
4796 .minor_spacing
4797 .iter()
4798 .all(|v| v.is_finite() && *v > 0.0)
4799 && config.opacity.is_finite()
4800 && (0.0..=1.0).contains(&config.opacity)
4801 && (2..=100).contains(&config.major_every)
4802 && (config.major_every.saturating_mul(2)..=10000).contains(&config.super_major_every)
4803 && config
4804 .super_major_every
4805 .is_multiple_of(config.major_every.max(1))
4806 && config.guide_fade_inner_radius.is_finite()
4807 && config.guide_fade_inner_radius >= 0.0
4808 && config.guide_fade_outer_radius.is_finite()
4809 && config.guide_fade_outer_radius > config.guide_fade_inner_radius
4810 && config.guide_fade_outer_radius <= 1.0e7
4811 && colors
4812 .iter()
4813 .all(|c| [c.r, c.g, c.b, c.a].iter().all(|v| v.is_finite()));
4814 if !valid {
4815 if state.recording_error.is_none() {
4816 state.recording_error = Some(Error::invalid_argument(
4817 "ui::grid requires finite geometry, positive spacing/thickness/fade radii, opacity in [0,1], and divisible tiers",
4818 ));
4819 }
4820 return;
4821 }
4822 let parent = state.layout.top().map_or(
4824 PixelRect::new(0, 0, state.compose.width, state.compose.height),
4825 |panel| panel.clip(),
4826 );
4827 let left = i64::from(rect.x).max(i64::from(parent.x)).max(0);
4828 let top = i64::from(rect.y).max(i64::from(parent.y)).max(0);
4829 let right = (i64::from(rect.x) + i64::from(rect.w))
4830 .min(i64::from(parent.x) + i64::from(parent.w))
4831 .min(i64::from(state.compose.width));
4832 let bottom = (i64::from(rect.y) + i64::from(rect.h))
4833 .min(i64::from(parent.y) + i64::from(parent.h))
4834 .min(i64::from(state.compose.height));
4835 if right <= left || bottom <= top {
4836 return;
4837 }
4838 let clip = PixelRect::new(
4839 left as i32,
4840 top as i32,
4841 (right - left) as u32,
4842 (bottom - top) as u32,
4843 );
4844 let style = Self::current_style_ref(state);
4845 let light = style.background.r + style.background.g + style.background.b > 1.5;
4846 let resolve = |requested: Color, fallback: Color| {
4847 if requested.a <= 0.0 {
4848 fallback
4849 } else {
4850 requested
4851 }
4852 };
4853 let line = |requested: Color, fallback: Color| {
4854 let mut color = resolve(requested, fallback);
4855 color.a *= config.opacity;
4856 color.to_u32()
4857 };
4858 let top_color = Color::new(
4859 style.surface.r + (1.0 - style.surface.r) * 0.055,
4860 style.surface.g + (1.0 - style.surface.g) * 0.055,
4861 style.surface.b + (1.0 - style.surface.b) * 0.055,
4862 style.surface.a,
4863 );
4864 let bottom_color = Color::new(
4865 style.surface.r * 0.955,
4866 style.surface.g * 0.955,
4867 style.surface.b * 0.955,
4868 style.surface.a,
4869 );
4870 let minor = if light {
4871 Color::new(0.0, 0.0, 0.0, 0.045)
4872 } else {
4873 Color::new(1.0, 1.0, 1.0, 0.045)
4874 };
4875 let major = if light {
4876 Color::new(0.0, 0.0, 0.0, 0.14)
4877 } else {
4878 Color::new(0.78, 0.80, 0.82, 0.16)
4879 };
4880 let super_major = if light {
4881 Color::new(0.12, 0.12, 0.12, 0.24)
4882 } else {
4883 Color::new(0.03, 0.03, 0.03, 0.62)
4884 };
4885 let axis = Color::new(0.0, 0.0, 0.0, if light { 0.60 } else { 0.82 });
4886 let flags = u32::from(config.fill_background)
4887 | (u32::from(config.draw_axes) << 1)
4888 | (u32::from(config.draw_grid) << 2)
4889 | (u32::from(config.radial_guide_fade) << 3)
4890 | (u32::from(config.dither_background) << 4);
4891 let push = [
4893 0,
4894 clip.x as u32,
4895 clip.y as u32,
4896 clip.w,
4897 clip.h,
4898 config.origin[0].to_bits(),
4899 config.origin[1].to_bits(),
4900 config.minor_spacing[0].to_bits(),
4901 config.minor_spacing[1].to_bits(),
4902 config.major_every,
4903 config.super_major_every,
4904 config.minor_thickness.to_bits(),
4905 config.major_thickness.to_bits(),
4906 config.super_major_thickness.to_bits(),
4907 config.axis_thickness.to_bits(),
4908 resolve(config.background_top, top_color).to_u32(),
4909 resolve(config.background_bottom, bottom_color).to_u32(),
4910 line(config.minor_color, minor),
4911 line(config.major_color, major),
4912 line(config.super_major_color, super_major),
4913 line(config.axis_color, axis),
4914 config.guide_fade_center[0].to_bits(),
4915 config.guide_fade_center[1].to_bits(),
4916 config.guide_fade_inner_radius.to_bits(),
4917 config.guide_fade_outer_radius.to_bits(),
4918 flags,
4919 clip.x as u32,
4920 clip.y as u32,
4921 clip.w,
4922 clip.h,
4923 ];
4924 state.cmds.push(UiCmd::CanvasGrid { rect: clip, push });
4925 }
4926
4927 pub fn image_planar(
4937 &mut self,
4938 planes: &crate::ui::ImagePlanes,
4939 dst_x: i32,
4940 dst_y: i32,
4941 ) -> Result<()> {
4942 let state = self
4943 .state
4944 .as_mut()
4945 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
4946 if !planes.is_valid() || !planes.runtime().same_as(&state.runtime) {
4947 return Err(Error::invalid_argument(
4948 "UI image_planar requires valid planes from its runtime",
4949 ));
4950 }
4951 let mut slots = [u32::MAX; crate::ui::IMAGE_MAX_PLANES];
4952 for (channel, slot) in slots.iter_mut().enumerate() {
4953 *slot = planes.plane_index(channel)?;
4954 }
4955 self.push_planar_cmd(
4956 planes,
4957 slots,
4958 (0..planes.channel_count()).fold(0_u32, |packed, channel| {
4959 packed | ((planes.plane_dtype(channel) as u32) & 0x3) << (channel * 2)
4960 }),
4961 u32::try_from(planes.channel_count())
4962 .map_err(|_| Error::out_of_range("plane count exceeds donor ABI"))?,
4963 dst_x,
4964 dst_y,
4965 )
4966 }
4967
4968 pub fn image_plane(
4972 &mut self,
4973 planes: &crate::ui::ImagePlanes,
4974 channel: usize,
4975 dst_x: i32,
4976 dst_y: i32,
4977 ) -> Result<()> {
4978 let state = self
4979 .state
4980 .as_mut()
4981 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
4982 if !planes.is_valid()
4983 || !planes.runtime().same_as(&state.runtime)
4984 || channel >= planes.channel_count()
4985 {
4986 return Err(Error::invalid_argument(
4987 "UI image_plane requires a valid channel from its runtime",
4988 ));
4989 }
4990 let index = planes.plane_index(channel)?;
4991 self.push_planar_cmd(
4992 planes,
4993 [index, u32::MAX, u32::MAX, u32::MAX],
4994 u32::from(planes.plane_dtype(channel) as u8) & 0x3,
4995 1,
4996 dst_x,
4997 dst_y,
4998 )
4999 }
5000
5001 fn push_planar_cmd(
5002 &mut self,
5003 planes: &crate::ui::ImagePlanes,
5004 slots: [u32; 4],
5005 dtypes: u32,
5006 channels: u32,
5007 dst_x: i32,
5008 dst_y: i32,
5009 ) -> Result<()> {
5010 let state = self
5011 .state
5012 .as_mut()
5013 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
5014 let native_w =
5015 u32::try_from(planes.width()).map_err(|_| Error::out_of_range("plane width exceeds u32"))?;
5016 let native_h = u32::try_from(planes.height())
5017 .map_err(|_| Error::out_of_range("plane height exceeds u32"))?;
5018 let (x, y, w, h) = state.layout.top().map_or_else(
5019 || (dst_x, dst_y, native_w, native_h),
5020 |panel| {
5021 (
5022 panel.outer.x + dst_x,
5023 panel.outer.y + dst_y,
5024 panel.outer.w,
5025 panel.outer.h,
5026 )
5027 },
5028 );
5029 let viewport = PixelRect::new(0, 0, state.compose.width, state.compose.height);
5030 let destination = PixelRect::new(x, y, w, h);
5031 let clip = state
5032 .layout
5033 .top()
5034 .map_or(viewport, |panel| viewport.clip(&panel.clip()))
5035 .clip(&destination);
5036 if clip.w == 0 || clip.h == 0 {
5037 return Ok(());
5038 }
5039 state.cmds.push(UiCmd::BlitPlanar {
5040 r_idx: slots[0],
5041 g_idx: slots[1],
5042 b_idx: slots[2],
5043 a_idx: slots[3],
5044 src_w: u32::try_from(planes.width())
5045 .map_err(|_| Error::out_of_range("plane width exceeds donor ABI"))?,
5046 src_h: u32::try_from(planes.height())
5047 .map_err(|_| Error::out_of_range("plane height exceeds donor ABI"))?,
5048 dst_x: x,
5049 dst_y: y,
5050 dtypes,
5051 channels,
5052 dst_w: w,
5053 dst_h: h,
5054 clip,
5055 });
5056 planes.retain_planes(&mut state.frame_matrices);
5057 Ok(())
5058 }
5059
5060 #[allow(clippy::too_many_arguments)]
5068 pub fn plot_line_xy_at(
5069 &mut self,
5070 x: &[f32],
5071 y: &[f32],
5072 rect: PixelRect,
5073 y_min: f32,
5074 y_max: f32,
5075 color: Color,
5076 line_width: f32,
5077 ) -> Result<()> {
5078 if x.len() != y.len() {
5079 return Err(Error::invalid_argument(
5080 "plot_line_xy: x and y must have equal length",
5081 ));
5082 }
5083 if x.is_empty() {
5084 return Ok(());
5085 }
5086 let (mut x_min, mut x_max) = (f32::INFINITY, f32::NEG_INFINITY);
5087 for &value in x {
5088 if value.is_finite() {
5089 x_min = x_min.min(value);
5090 x_max = x_max.max(value);
5091 }
5092 }
5093 if !x_min.is_finite() || !x_max.is_finite() {
5094 return Ok(());
5095 }
5096 if x_max <= x_min {
5097 let margin = (x_min.abs() * 0.05).max(1.0e-4);
5098 x_min -= margin;
5099 x_max += margin;
5100 }
5101 self.plot_xy_at(x, y, rect, x_min, x_max, y_min, y_max, color, 4, line_width)
5102 }
5103
5104 #[allow(clippy::too_many_arguments)]
5112 pub fn plot_xy_at(
5113 &mut self,
5114 x: &[f32],
5115 y: &[f32],
5116 rect: PixelRect,
5117 x_min: f32,
5118 x_max: f32,
5119 y_min: f32,
5120 y_max: f32,
5121 color: Color,
5122 antialias_samples: u32,
5123 line_width: f32,
5124 ) -> Result<()> {
5125 if x.len() != y.len() {
5126 return Err(Error::invalid_argument(
5127 "plot_xy_at: x and y must have equal length",
5128 ));
5129 }
5130 if x.is_empty() {
5131 return Ok(());
5132 }
5133 if rect.w == 0
5134 || rect.h == 0
5135 || !x_min.is_finite()
5136 || !x_max.is_finite()
5137 || x_min >= x_max
5138 || !y_min.is_finite()
5139 || !y_max.is_finite()
5140 || y_min >= y_max
5141 {
5142 return Err(Error::invalid_argument(
5143 "UI XY line plot requires a positive rectangle and finite increasing limits",
5144 ));
5145 }
5146 let mut packed: Vec<f32> = Vec::with_capacity(x.len() * 2);
5147 packed.extend_from_slice(x);
5148 packed.extend_from_slice(y);
5149 let matrix = crate::Matrix::new_from_f32_on(self.runtime, [packed.len()], &packed)?;
5150 let descriptor = matrix
5151 .runtime()
5152 .storage_descriptor_index(matrix.storage())?;
5153 let state = self
5154 .state
5155 .as_mut()
5156 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
5157 let clip = Self::compose_clip(state, rect);
5158 if clip.w == 0 || clip.h == 0 {
5159 return Ok(());
5160 }
5161 state.cmds.push(UiCmd::PlotLine {
5162 values_idx: descriptor,
5163 count: u32::try_from(x.len()).map_err(|_| Error::out_of_range("sample count exceeds u32"))?,
5164 rect,
5165 clip,
5166 x_min,
5167 x_max,
5168 y_min,
5169 y_max,
5170 color,
5171 fill: false,
5172 explicit_xy: true,
5173 band: false,
5174 antialias_samples: match antialias_samples {
5175 1 | 8 => antialias_samples,
5176 _ => 4,
5177 },
5178 line_width: if line_width.is_finite() {
5179 line_width.clamp(0.5, 16.0)
5180 } else {
5181 1.35
5182 },
5183 });
5184 state.frame_matrices.push(matrix);
5185 Ok(())
5186 }
5187
5188 #[allow(clippy::too_many_arguments)]
5196 pub fn plot_xy_matrix_at(
5197 &mut self,
5198 values: &crate::Matrix,
5199 rect: PixelRect,
5200 x_min: f32,
5201 x_max: f32,
5202 y_min: f32,
5203 y_max: f32,
5204 color: Color,
5205 antialias_samples: u32,
5206 line_width: f32,
5207 ) -> Result<()> {
5208 let shape = values.shape();
5209 if values.dtype() != crate::DType::F32 || shape.len() != 2 || shape[0] != 2 || shape[1] == 0 {
5210 return Err(Error::invalid_argument(
5211 "UI XY matrix line plot requires an F32 [2, N] matrix",
5212 ));
5213 }
5214 if rect.w == 0
5215 || rect.h == 0
5216 || !x_min.is_finite()
5217 || !x_max.is_finite()
5218 || x_min >= x_max
5219 || !y_min.is_finite()
5220 || !y_max.is_finite()
5221 || y_min >= y_max
5222 {
5223 return Err(Error::invalid_argument(
5224 "UI XY line plot requires a positive rectangle and finite increasing limits",
5225 ));
5226 }
5227 let descriptor = values
5228 .runtime()
5229 .storage_descriptor_index(values.storage())?;
5230 let count =
5231 u32::try_from(shape[1]).map_err(|_| Error::out_of_range("sample count exceeds u32"))?;
5232 let state = self
5233 .state
5234 .as_mut()
5235 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
5236 let clip = Self::compose_clip(state, rect);
5237 if clip.w == 0 || clip.h == 0 {
5238 return Ok(());
5239 }
5240 state.cmds.push(UiCmd::PlotLine {
5241 values_idx: descriptor,
5242 count,
5243 rect,
5244 clip,
5245 x_min,
5246 x_max,
5247 y_min,
5248 y_max,
5249 color,
5250 fill: false,
5251 explicit_xy: true,
5252 band: false,
5253 antialias_samples: match antialias_samples {
5254 1 | 8 => antialias_samples,
5255 _ => 4,
5256 },
5257 line_width: if line_width.is_finite() {
5258 line_width.clamp(0.5, 16.0)
5259 } else {
5260 1.35
5261 },
5262 });
5263 state.frame_matrices.push(values.clone());
5264 Ok(())
5265 }
5266
5267 pub fn plot_line_matrix_at(
5273 &mut self,
5274 values: &crate::Matrix,
5275 rect: PixelRect,
5276 y_min: f32,
5277 y_max: f32,
5278 color: Color,
5279 line_width: f32,
5280 ) -> Result<()> {
5281 let shape = values.shape();
5282 if values.dtype() != crate::DType::F32 || shape.len() != 1 {
5283 return Err(Error::invalid_argument(
5284 "UI matrix line plot requires an F32 [N] matrix",
5285 ));
5286 }
5287 if shape[0] == 0 {
5288 return Ok(());
5289 }
5290 if rect.w == 0 || rect.h == 0 || !y_min.is_finite() || !y_max.is_finite() || y_min >= y_max {
5291 return Err(Error::invalid_argument(
5292 "UI line plot requires a positive rectangle and finite increasing Y limits",
5293 ));
5294 }
5295 let descriptor = values
5296 .runtime()
5297 .storage_descriptor_index(values.storage())?;
5298 let count =
5299 u32::try_from(shape[0]).map_err(|_| Error::out_of_range("sample count exceeds u32"))?;
5300 let state = self
5301 .state
5302 .as_mut()
5303 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
5304 let clip = Self::compose_clip(state, rect);
5305 if clip.w == 0 || clip.h == 0 {
5306 return Ok(());
5307 }
5308 state.cmds.push(UiCmd::PlotLine {
5309 values_idx: descriptor,
5310 count,
5311 rect,
5312 clip,
5313 x_min: 0.0,
5314 x_max: shape[0].saturating_sub(1).max(1) as f32,
5315 y_min,
5316 y_max,
5317 color,
5318 fill: false,
5319 explicit_xy: false,
5320 band: false,
5321 antialias_samples: 4,
5322 line_width: if line_width.is_finite() {
5323 line_width.clamp(0.5, 16.0)
5324 } else {
5325 1.35
5326 },
5327 });
5328 state.frame_matrices.push(values.clone());
5329 Ok(())
5330 }
5331
5332 #[allow(clippy::too_many_arguments)]
5338 pub fn plot_line_ring_at(
5339 &mut self,
5340 data: &[f32],
5341 offset: usize,
5342 rect: PixelRect,
5343 y_min: f32,
5344 y_max: f32,
5345 color: Color,
5346 line_width: f32,
5347 ) -> Result<()> {
5348 if data.is_empty() {
5349 return Ok(());
5350 }
5351 let mut ordered: Vec<f32> = Vec::with_capacity(data.len());
5353 ordered.extend_from_slice(&data[offset..]);
5354 ordered.extend_from_slice(&data[..offset]);
5355 self.plot_line_at(&ordered, rect, y_min, y_max, color, line_width)
5356 }
5357
5358 pub fn accessibility_snapshot(&self) -> UiAccessibilitySnapshot {
5368 let count = self.state.as_ref().map_or(0, |s| s.cmds.cmds.len());
5369 UiAccessibilitySnapshot { node_count: count }
5370 }
5371
5372 pub fn wants_text_input(&self) -> bool {
5377 self.state.as_ref().is_some_and(|s| s.ime_rect.is_some())
5378 }
5379
5380 pub fn text_input_rect(&self) -> Option<PixelRect> {
5389 self.state.as_ref().and_then(|s| s.ime_rect)
5390 }
5391
5392 pub fn glyphs_at(
5400 &mut self,
5401 text: &str,
5402 origin: [f32; 2],
5403 config: TextLayoutConfig,
5404 color: Color,
5405 clip: PixelRect,
5406 ) -> Result<()> {
5407 self.text_at(text, origin, config, color, clip)
5408 }
5409
5410 fn emit_text(
5415 state: &mut UiState,
5416 text: &str,
5417 rect: PixelRect,
5418 color: Color,
5419 config: TextLayoutConfig,
5420 ) -> Result<()> {
5421 if text.is_empty() || rect.w == 0 || rect.h == 0 {
5422 return Ok(());
5423 }
5424 let baseline_y = rect.y as f32 + rect.h as f32 * 0.5 + config.size * 0.35;
5425 let origin = [rect.x as f32 + 4.0, baseline_y];
5426 let positioned = TextLayout::shape(&state.text_atlas, text, origin, config, color)?;
5427 if positioned.is_empty() {
5428 return Ok(());
5429 }
5430 let mut bytes = Vec::with_capacity(positioned.len() * 48);
5431 for glyph in positioned {
5432 let Some(info) = state
5433 .text_atlas
5434 .find_glyph(glyph.font, glyph.codepoint, config.size)
5435 else {
5436 continue;
5437 };
5438 let scale = config.size / info.raster_size;
5439 for value in [
5440 0.0_f32,
5441 0.0,
5442 glyph.x + info.bearing_x * scale,
5443 glyph.y - info.bearing_y * scale,
5444 info.atlas_w * scale,
5445 info.atlas_h * scale,
5446 ] {
5447 bytes.extend_from_slice(&value.to_le_bytes());
5448 }
5449 for value in [
5450 info.atlas_x as u32,
5451 info.atlas_y as u32,
5452 info.atlas_w as u32,
5453 info.atlas_h as u32,
5454 glyph.color.to_u32(),
5455 0,
5456 ] {
5457 bytes.extend_from_slice(&value.to_le_bytes());
5458 }
5459 }
5460 if bytes.is_empty() {
5461 return Ok(());
5462 }
5463 let clip = rect;
5464 let storage = state.runtime.create_storage(&bytes)?;
5465 let glyph_idx = state.runtime.storage_descriptor_index(&storage)?;
5466 let count = u32::try_from(bytes.len() / 48)
5467 .map_err(|_| Error::out_of_range("glyph count exceeds u32"))?;
5468 state.cmds.push(UiCmd::Glyphs {
5469 glyph_idx,
5470 atlas_idx: state.text_atlas.descriptor(),
5471 count,
5472 dst: None,
5473 clip,
5474 atlas_w: state.text_atlas.width(),
5475 atlas_h: state.text_atlas.height(),
5476 });
5477 state.frame_storages.push(storage);
5478 Ok(())
5479 }
5480
5481 fn emit_text_or_record(
5482 state: &mut UiState,
5483 text: &str,
5484 rect: PixelRect,
5485 color: Color,
5486 config: TextLayoutConfig,
5487 ) {
5488 if let Err(error) = Self::emit_text(state, text, rect, color, config)
5489 && state.recording_error.is_none()
5490 {
5491 state.recording_error = Some(error);
5492 }
5493 }
5494
5495 fn frame_bindings(state: &UiState) -> Result<std::rc::Rc<UiFrameBindings>> {
5496 state.runtime.prepare_ui_sources()?;
5497 let runtime = &state.runtime;
5498 let storages = state
5499 .frame_storages
5500 .iter()
5501 .chain(std::iter::once(state.text_atlas.storage()))
5502 .chain(state.frame_matrices.iter().map(crate::Matrix::storage));
5503 let mut buffers = std::collections::HashMap::new();
5504 for storage in storages {
5505 buffers.insert(
5506 runtime.storage_descriptor_index(storage)?,
5507 runtime.ui_buffer_info(storage)?,
5508 );
5509 }
5510 Ok(std::rc::Rc::new(UiFrameBindings::new(
5511 runtime,
5512 &state.pipelines.layouts,
5513 &state.cmds.cmds,
5514 |index| {
5515 buffers
5516 .get(&index)
5517 .copied()
5518 .ok_or_else(|| Error::internal("UI command source is not retained"))
5519 },
5520 )?))
5521 }
5522
5523 fn record_render_state(
5524 state: &UiState,
5525 device: &vk::Device,
5526 command_buffer: vk::CommandBuffer,
5527 bindings: &UiFrameBindings,
5528 ) -> Result<()> {
5529 let w = state.compose.width;
5530 let h = state.compose.height;
5531
5532 let range = vk::ImageSubresourceRange::new()
5536 .set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
5537 .set_level_count(1)
5538 .set_layer_count(1);
5539 let prior_layout = state.compose.layout();
5540 let barrier_in = vk::ImageMemoryBarrier2::new()
5541 .set_src_stage_mask(if prior_layout == vk::ImageLayout::UNDEFINED {
5542 vk::PipelineStageFlagBits2::NONE
5543 } else {
5544 vk::PipelineStageFlagBits2::ALL_TRANSFER_BIT
5545 })
5546 .set_src_access_mask(if prior_layout == vk::ImageLayout::UNDEFINED {
5547 vk::AccessFlagBits2::NONE
5548 } else {
5549 vk::AccessFlagBits2::TRANSFER_READ_BIT
5550 })
5551 .set_dst_stage_mask(vk::PipelineStageFlagBits2::COLOR_ATTACHMENT_OUTPUT_BIT)
5552 .set_dst_access_mask(
5553 vk::AccessFlagBits2::COLOR_ATTACHMENT_READ_BIT
5554 | vk::AccessFlagBits2::COLOR_ATTACHMENT_WRITE_BIT,
5555 )
5556 .set_old_layout(prior_layout)
5557 .set_new_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
5558 .set_image(state.compose.raw_image())
5559 .set_subresource_range(range);
5560 let shader_stages = vk::PipelineStageFlagBits2::VERTEX_SHADER_BIT
5561 | vk::PipelineStageFlagBits2::FRAGMENT_SHADER_BIT;
5562
5563 unsafe {
5567 state.sync_commands.pipeline_barrier(
5568 device,
5569 command_buffer,
5570 &vk::DependencyInfo::new()
5571 .set_image_memory_barriers(&[barrier_in])
5572 .map_err(Error::from)?
5573 .set_memory_barriers(&[vk::MemoryBarrier2::new()
5574 .set_src_stage_mask(
5575 vk::PipelineStageFlagBits2::ALL_COMMANDS_BIT | vk::PipelineStageFlagBits2::HOST_BIT,
5576 )
5577 .set_src_access_mask(vk::AccessFlagBits2::MEMORY_WRITE_BIT)
5578 .set_dst_stage_mask(shader_stages)
5579 .set_dst_access_mask(vk::AccessFlagBits2::SHADER_STORAGE_READ_BIT)])
5580 .map_err(Error::from)?,
5581 )?;
5582
5583 let clear_value = vk::ClearValue {
5587 color: vk::ClearColorValue { float32: [0.0; 4] },
5588 };
5589 let color_attachment = vk::RenderingAttachmentInfo::new()
5590 .set_image_view(state.compose.raw_view())
5591 .set_image_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
5592 .set_load_op(vk::AttachmentLoadOp::CLEAR)
5593 .set_store_op(vk::AttachmentStoreOp::STORE)
5594 .set_clear_value(clear_value);
5595 let rendering_info = vk::RenderingInfo::new()
5596 .set_render_area(vk::Rect2D {
5597 offset: vk::Offset2D::new(),
5598 extent: vk::Extent2D {
5599 width: w,
5600 height: h,
5601 },
5602 })
5603 .set_layer_count(1)
5604 .set_color_attachments(std::slice::from_ref(&color_attachment))
5605 .map_err(Error::from)?;
5606 state
5607 .rendering_commands
5608 .begin(device, command_buffer, &rendering_info)?;
5609
5610 let viewport = vk::Viewport {
5611 x: 0.0,
5612 y: 0.0,
5613 width: w as f32,
5614 height: h as f32,
5615 min_depth: 0.0,
5616 max_depth: 1.0,
5617 };
5618 device.cmd_set_viewport(command_buffer, 0, &[viewport])?;
5619 }
5620
5621 for (index, cmd) in state.cmds.cmds.iter().enumerate() {
5622 unsafe {
5625 device.cmd_bind_descriptor_sets(
5626 command_buffer,
5627 vk::PipelineBindPoint::GRAPHICS,
5628 bindings.layouts[index],
5629 0,
5630 &[bindings.sets[index]],
5631 &[],
5632 )?;
5633 }
5634 Self::record_cmd(state, device, command_buffer, cmd)?;
5635 }
5636
5637 unsafe {
5639 state.rendering_commands.end(device, command_buffer)?;
5640 }
5641 Ok(())
5642 }
5643
5644 fn scissor_rect(state: &UiState, clip: PixelRect) -> Option<vk::Rect2D> {
5647 let image = PixelRect::new(0, 0, state.compose.width, state.compose.height);
5648 let region = image.clip(&clip);
5649 if !region.is_non_empty() {
5650 return None;
5651 }
5652 Some(vk::Rect2D {
5653 offset: vk::Offset2D {
5654 x: region.x,
5655 y: region.y,
5656 },
5657 extent: vk::Extent2D {
5658 width: region.w,
5659 height: region.h,
5660 },
5661 })
5662 }
5663
5664 unsafe fn record_draw(
5670 device: &vk::Device,
5671 cmd_buf: vk::CommandBuffer,
5672 pipeline: &crate::runtime::GraphicsPipeline,
5673 scissor: Option<vk::Rect2D>,
5674 push: &[u8],
5675 vertices: u32,
5676 instances: u32,
5677 ) -> Result<()> {
5678 let Some(scissor) = scissor else {
5679 return Ok(());
5680 };
5681 let stages = vk::ShaderStageFlagBits::VERTEX_BIT | vk::ShaderStageFlagBits::FRAGMENT_BIT;
5682 unsafe {
5685 device.cmd_bind_pipeline(cmd_buf, vk::PipelineBindPoint::GRAPHICS, pipeline.raw())?;
5686 device.cmd_set_scissor(cmd_buf, 0, &[scissor])?;
5687 device.cmd_push_constants(cmd_buf, pipeline.layout(), stages, 0, push)?;
5688 device.cmd_draw(cmd_buf, vertices, instances, 0, 0)?;
5689 }
5690 Ok(())
5691 }
5692
5693 fn record_cmd(
5694 state: &UiState,
5695 device: &vk::Device,
5696 cmd_buf: vk::CommandBuffer,
5697 cmd: &UiCmd,
5698 ) -> Result<()> {
5699 let w = state.compose.width;
5700 let h = state.compose.height;
5701 let fullscreen = PixelRect::new(0, 0, w, h);
5702
5703 match cmd {
5704 UiCmd::Clear { color } => {
5705 let words = [color.to_u32()];
5706 let push = bytemuck_push(&words);
5707 unsafe {
5708 Self::record_draw(
5709 device,
5710 cmd_buf,
5711 &state.pipelines.clear,
5712 Self::scissor_rect(state, fullscreen),
5713 push,
5714 3,
5715 1,
5716 )?;
5717 }
5718 }
5719 UiCmd::Heatmap { rect, push, .. } => {
5720 let mut raster = [0u8; 48];
5723 write_u32(&mut raster, 0, push[1]);
5724 write_u32(&mut raster, 4, push[2]);
5725 write_i32(&mut raster, 8, rect.x);
5726 write_i32(&mut raster, 12, rect.y);
5727 write_u32(&mut raster, 16, rect.w);
5728 write_u32(&mut raster, 20, rect.h);
5729 write_u32(&mut raster, 24, push[8]);
5730 write_u32(&mut raster, 28, push[9]);
5731 write_u32(&mut raster, 32, push[10]);
5732 write_u32(&mut raster, 36, push[11]);
5733 write_u32(&mut raster, 40, push[12]);
5734 write_u32(&mut raster, 44, push[13]);
5735 let clip = PixelRect::new(push[14] as i32, push[15] as i32, push[16], push[17]);
5736 unsafe {
5737 Self::record_draw(
5738 device,
5739 cmd_buf,
5740 &state.pipelines.heatmap,
5741 Self::scissor_rect(state, clip.clip(rect)),
5742 &raster,
5743 3,
5744 1,
5745 )?;
5746 }
5747 }
5748 UiCmd::Waveform { rect, push, .. } => {
5749 let mut raster = [0u8; 32];
5751 write_u32(&mut raster, 0, push[1]);
5752 write_i32(&mut raster, 4, rect.x);
5753 write_i32(&mut raster, 8, rect.y);
5754 write_u32(&mut raster, 12, rect.w);
5755 write_u32(&mut raster, 16, rect.h);
5756 write_u32(&mut raster, 20, push[7]);
5757 write_u32(&mut raster, 24, push[8]);
5758 write_u32(&mut raster, 28, push[9]);
5759 let clip = PixelRect::new(push[10] as i32, push[11] as i32, push[12], push[13]);
5760 unsafe {
5761 Self::record_draw(
5762 device,
5763 cmd_buf,
5764 &state.pipelines.waveform,
5765 Self::scissor_rect(state, clip.clip(rect)),
5766 &raster,
5767 3,
5768 1,
5769 )?;
5770 }
5771 }
5772 UiCmd::RoundedMask {
5773 rect,
5774 radius,
5775 outside,
5776 clip,
5777 } => {
5778 let scissor = Self::scissor_rect(state, clip.clip(rect));
5782 let mut push = [0u8; 28];
5783 write_i32(&mut push, 0, rect.x);
5784 write_i32(&mut push, 4, rect.y);
5785 write_u32(&mut push, 8, rect.w);
5786 write_u32(&mut push, 12, rect.h);
5787 write_f32(&mut push, 16, *radius);
5788 write_u32(&mut push, 20, outside.to_u32());
5789 unsafe {
5790 write_u32(&mut push, 24, 0);
5791 Self::record_draw(
5792 device,
5793 cmd_buf,
5794 &state.pipelines.mask_modulate,
5795 scissor,
5796 &push,
5797 3,
5798 1,
5799 )?;
5800 write_u32(&mut push, 24, 1);
5801 Self::record_draw(
5802 device,
5803 cmd_buf,
5804 &state.pipelines.mask_additive,
5805 scissor,
5806 &push,
5807 3,
5808 1,
5809 )?;
5810 }
5811 }
5812 UiCmd::Triangle {
5813 points,
5814 color,
5815 bounds,
5816 } => {
5817 let mut push = [0u8; 28];
5818 write_f32(&mut push, 0, points[0][0]);
5819 write_f32(&mut push, 4, points[0][1]);
5820 write_f32(&mut push, 8, points[1][0]);
5821 write_f32(&mut push, 12, points[1][1]);
5822 write_f32(&mut push, 16, points[2][0]);
5823 write_f32(&mut push, 20, points[2][1]);
5824 write_u32(&mut push, 24, color.to_u32());
5825 unsafe {
5826 Self::record_draw(
5827 device,
5828 cmd_buf,
5829 &state.pipelines.triangle,
5830 Self::scissor_rect(state, *bounds),
5831 &push,
5832 3,
5833 1,
5834 )?;
5835 }
5836 }
5837 UiCmd::CanvasGrid { rect, push } => {
5838 let mut raster = [0u8; 100];
5843 write_i32(&mut raster, 0, rect.x);
5844 write_i32(&mut raster, 4, rect.y);
5845 write_u32(&mut raster, 8, rect.w);
5846 write_u32(&mut raster, 12, rect.h);
5847 for (word, value) in push[5..25].iter().enumerate() {
5848 write_u32(&mut raster, 16 + word * 4, *value);
5849 }
5850 write_u32(&mut raster, 96, push[25]);
5851 unsafe {
5852 Self::record_draw(
5853 device,
5854 cmd_buf,
5855 &state.pipelines.canvas_grid,
5856 Self::scissor_rect(state, *rect),
5857 &raster,
5858 3,
5859 1,
5860 )?;
5861 }
5862 }
5863 UiCmd::Rect {
5864 rect,
5865 color,
5866 clip,
5867 corner_radius,
5868 } => {
5869 let mut push = [0u8; 24];
5870 write_i32(&mut push, 0, rect.x);
5871 write_i32(&mut push, 4, rect.y);
5872 write_u32(&mut push, 8, rect.w);
5873 write_u32(&mut push, 12, rect.h);
5874 write_u32(&mut push, 16, color.to_u32());
5875 write_f32(&mut push, 20, *corner_radius);
5876 unsafe {
5877 Self::record_draw(
5878 device,
5879 cmd_buf,
5880 &state.pipelines.rect,
5881 Self::scissor_rect(state, clip.clip(rect)),
5882 &push,
5883 3,
5884 1,
5885 )?;
5886 }
5887 }
5888 UiCmd::RectOutline {
5889 rect,
5890 color,
5891 thickness,
5892 clip,
5893 corner_radius,
5894 } => {
5895 let mut push = [0u8; 28];
5896 write_i32(&mut push, 0, rect.x);
5897 write_i32(&mut push, 4, rect.y);
5898 write_u32(&mut push, 8, rect.w);
5899 write_u32(&mut push, 12, rect.h);
5900 write_u32(&mut push, 16, *thickness);
5901 write_u32(&mut push, 20, color.to_u32());
5902 write_f32(&mut push, 24, *corner_radius);
5903 unsafe {
5904 Self::record_draw(
5905 device,
5906 cmd_buf,
5907 &state.pipelines.rect_outline,
5908 Self::scissor_rect(state, clip.clip(rect)),
5909 &push,
5910 3,
5911 1,
5912 )?;
5913 }
5914 }
5915 UiCmd::Line {
5916 x0,
5917 y0,
5918 x1,
5919 y1,
5920 color,
5921 thickness,
5922 bounds,
5923 } => {
5924 let mut push = [0u8; 24];
5925 write_f32(&mut push, 0, *x0);
5926 write_f32(&mut push, 4, *y0);
5927 write_f32(&mut push, 8, *x1);
5928 write_f32(&mut push, 12, *y1);
5929 write_f32(&mut push, 16, *thickness);
5930 write_u32(&mut push, 20, color.to_u32());
5931 unsafe {
5932 Self::record_draw(
5933 device,
5934 cmd_buf,
5935 &state.pipelines.line,
5936 Self::scissor_rect(state, *bounds),
5937 &push,
5938 3,
5939 1,
5940 )?;
5941 }
5942 }
5943 UiCmd::BlitRgba {
5944 src_w,
5945 src_h,
5946 dst_x,
5947 dst_y,
5948 dst_w,
5949 dst_h,
5950 clip,
5951 channel,
5952 linear,
5953 ..
5954 } => {
5955 let mut push = [0u8; 32];
5956 write_u32(&mut push, 0, *src_w);
5957 write_u32(&mut push, 4, *src_h);
5958 write_i32(&mut push, 8, *dst_x);
5959 write_i32(&mut push, 12, *dst_y);
5960 write_u32(&mut push, 16, *dst_w);
5961 write_u32(&mut push, 20, *dst_h);
5962 write_u32(&mut push, 24, *channel);
5963 write_u32(&mut push, 28, u32::from(*linear));
5964 let region = PixelRect::new(*dst_x, *dst_y, *dst_w, *dst_h);
5965 unsafe {
5966 Self::record_draw(
5967 device,
5968 cmd_buf,
5969 &state.pipelines.blit_texture,
5970 Self::scissor_rect(state, clip.clip(®ion)),
5971 &push,
5972 3,
5973 1,
5974 )?;
5975 }
5976 }
5977 UiCmd::BlitYuv { dst, push, .. } => unsafe {
5978 Self::record_draw(
5979 device,
5980 cmd_buf,
5981 &state.pipelines.blit_yuv,
5982 Self::scissor_rect(state, fullscreen.clip(dst)),
5983 bytemuck_push(push),
5984 3,
5985 1,
5986 )?;
5987 },
5988 UiCmd::BlitPlanar {
5989 src_w,
5990 src_h,
5991 dst_x,
5992 dst_y,
5993 dtypes,
5994 channels,
5995 dst_w,
5996 dst_h,
5997 clip,
5998 ..
5999 } => {
6000 let mut push = [0u8; 32];
6001 write_u32(&mut push, 0, *src_w);
6002 write_u32(&mut push, 4, *src_h);
6003 write_i32(&mut push, 8, *dst_x);
6004 write_i32(&mut push, 12, *dst_y);
6005 write_u32(&mut push, 16, *dtypes);
6006 write_u32(&mut push, 20, *channels);
6007 write_u32(&mut push, 24, *dst_w);
6008 write_u32(&mut push, 28, *dst_h);
6009 let region = PixelRect::new(*dst_x, *dst_y, *dst_w, *dst_h);
6010 unsafe {
6011 Self::record_draw(
6012 device,
6013 cmd_buf,
6014 &state.pipelines.blit_planar,
6015 Self::scissor_rect(state, clip.clip(®ion)),
6016 &push,
6017 3,
6018 1,
6019 )?;
6020 }
6021 }
6022 UiCmd::PlotLine {
6023 count,
6024 rect,
6025 clip,
6026 x_min,
6027 x_max,
6028 y_min,
6029 y_max,
6030 color,
6031 fill,
6032 explicit_xy,
6033 band,
6034 antialias_samples,
6035 line_width,
6036 ..
6037 } => {
6038 let mut push = [0u8; 52];
6039 write_u32(&mut push, 0, *count);
6040 write_i32(&mut push, 4, rect.x);
6041 write_i32(&mut push, 8, rect.y);
6042 write_u32(&mut push, 12, rect.w);
6043 write_u32(&mut push, 16, rect.h);
6044 write_f32(&mut push, 20, *x_min);
6045 write_f32(&mut push, 24, *x_max);
6046 write_f32(&mut push, 28, *y_min);
6047 write_f32(&mut push, 32, *y_max);
6048 write_u32(&mut push, 36, color.to_u32());
6049 let flags: u32 =
6050 if *fill { 2 } else { 0 } | if *explicit_xy { 4 } else { 0 } | if *band { 8 } else { 0 };
6051 write_u32(&mut push, 40, flags);
6052 let aa = match *antialias_samples {
6053 1 => 1u32,
6054 8 => 8u32,
6055 _ => 4u32,
6056 };
6057 write_u32(&mut push, 44, aa);
6058 write_f32(&mut push, 48, *line_width);
6059 unsafe {
6060 Self::record_draw(
6061 device,
6062 cmd_buf,
6063 &state.pipelines.plot_line,
6064 Self::scissor_rect(state, clip.clip(rect)),
6065 &push,
6066 3,
6067 1,
6068 )?;
6069 }
6070 }
6071 UiCmd::Glyphs {
6072 count,
6073 dst,
6074 clip,
6075 atlas_w,
6076 atlas_h,
6077 ..
6078 } => {
6079 let (dst_x, dst_y, dst_w, dst_h) =
6080 dst.map_or((0, 0, w, h), |rect| (rect.x, rect.y, rect.w, rect.h));
6081 let mut push = [0_u8; 44];
6082 write_i32(&mut push, 0, dst_x);
6083 write_i32(&mut push, 4, dst_y);
6084 write_u32(&mut push, 8, dst_w);
6085 write_u32(&mut push, 12, dst_h);
6086 write_u32(&mut push, 16, w);
6087 write_u32(&mut push, 20, h);
6088 write_u32(&mut push, 24, 0);
6089 write_u32(&mut push, 28, 0);
6090 write_u32(&mut push, 32, *atlas_w);
6091 write_u32(&mut push, 36, *atlas_h);
6092 write_f32(&mut push, 40, 0.0);
6093 unsafe {
6094 Self::record_draw(
6095 device,
6096 cmd_buf,
6097 &state.pipelines.glyphs,
6098 Self::scissor_rect(state, *clip),
6099 &push,
6100 6,
6101 *count,
6102 )?;
6103 }
6104 }
6105 UiCmd::RectOutlines {
6106 count,
6107 dst,
6108 clip,
6109 thickness,
6110 rgba,
6111 ..
6112 } => {
6113 let mut push = [0_u8; 32];
6114 write_i32(&mut push, 0, dst.x);
6115 write_i32(&mut push, 4, dst.y);
6116 write_u32(&mut push, 8, dst.w);
6117 write_u32(&mut push, 12, dst.h);
6118 write_u32(&mut push, 16, w);
6119 write_u32(&mut push, 20, h);
6120 write_u32(&mut push, 24, *thickness);
6121 write_u32(&mut push, 28, *rgba);
6122 unsafe {
6123 Self::record_draw(
6124 device,
6125 cmd_buf,
6126 &state.pipelines.rect_outlines,
6127 Self::scissor_rect(state, *clip),
6128 &push,
6129 6,
6130 *count,
6131 )?;
6132 }
6133 }
6134 }
6135 Ok(())
6136 }
6137
6138 pub fn render_rgba8(&mut self) -> Result<Vec<u8>> {
6143 if let Some(error) = self
6144 .state
6145 .as_mut()
6146 .and_then(|state| state.recording_error.take())
6147 {
6148 return Err(error);
6149 }
6150 let state = self
6151 .state
6152 .as_ref()
6153 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
6154 let handle = state.runtime.clone();
6155 let image = state.compose.raw_image();
6156 let width = state.compose.width;
6157 let height = state.compose.height;
6158 let bindings = Self::frame_bindings(state)?;
6159 let retention = (
6162 state.pipelines.clone(),
6163 state.compose.clone(),
6164 state.text_atlas.clone(),
6165 state.frame_matrices.clone(),
6166 state.frame_textures.clone(),
6167 state.frame_storages.clone(),
6168 bindings.clone(),
6169 );
6170 let submission = handle.submit_ui_readback(image, width, height, |device, command| {
6171 Self::record_render_state(state, device, command, &bindings)
6172 });
6173 let (event, readback) = match submission {
6174 Ok(submission) => submission,
6175 Err(error) => {
6176 std::mem::forget(retention);
6177 return Err(error);
6178 }
6179 };
6180 state
6181 .compose
6182 .set_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL);
6183 if let Err(error) = event.wait() {
6184 std::mem::forget((retention, readback));
6185 return Err(error);
6186 }
6187 let mut rgba = vec![0_u8; width as usize * height as usize * 4];
6188 readback.read_prefix(&mut rgba)?;
6189 Ok(rgba)
6190 }
6191
6192 pub fn compose_extent(&self) -> Option<[u32; 2]> {
6194 self
6195 .state
6196 .as_ref()
6197 .map(|s| [s.compose.width, s.compose.height])
6198 }
6199
6200 pub fn present_to(&mut self, presenter: &mut crate::Presenter<'_>) -> Result<bool> {
6207 if let Some(error) = self
6208 .state
6209 .as_mut()
6210 .and_then(|state| state.recording_error.take())
6211 {
6212 return Err(error);
6213 }
6214 let state = self
6215 .state
6216 .as_ref()
6217 .ok_or_else(|| Error::failed_precondition("Ui is closed"))?;
6218 presenter.validate_ui_runtime(&state.runtime)?;
6219 let image = state.compose.raw_image();
6220 let width = state.compose.width;
6221 let height = state.compose.height;
6222 let bindings = Self::frame_bindings(state)?;
6223 let retention = std::rc::Rc::new((
6227 state.pipelines.clone(),
6228 state.compose.clone(),
6229 state.text_atlas.clone(),
6230 state.frame_matrices.clone(),
6231 state.frame_textures.clone(),
6232 state.frame_storages.clone(),
6233 bindings.clone(),
6234 ));
6235 let result = presenter.present_compose_retained(
6236 image,
6237 width,
6238 height,
6239 Some(retention),
6240 |device, cmd| Self::record_render_state(state, device, cmd, &bindings),
6241 )?;
6242 state
6243 .compose
6244 .set_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL);
6245 Ok(result)
6246 }
6247
6248 pub fn close(&mut self) -> Result<()> {
6252 if self.state.is_none() {
6253 return Ok(());
6254 }
6255 self.state = None;
6256 Ok(())
6257 }
6258}
6259
6260impl Drop for Ui<'_> {
6261 fn drop(&mut self) {
6262 self.state.take();
6263 }
6264}
6265
6266fn widget_hash(label: &str, panel_rect: Option<PixelRect>) -> u64 {
6270 use std::hash::{Hash, Hasher};
6271 let mut h = std::collections::hash_map::DefaultHasher::new();
6272 label.hash(&mut h);
6273 if let Some(r) = panel_rect {
6274 r.x.hash(&mut h);
6275 r.y.hash(&mut h);
6276 }
6277 h.finish()
6278}
6279
6280fn point_in_rect(x: f32, y: f32, rect: PixelRect) -> bool {
6282 x >= rect.x as f32
6283 && y >= rect.y as f32
6284 && x < (rect.x + rect.w as i32) as f32
6285 && y < (rect.y + rect.h as i32) as f32
6286}
6287
6288#[derive(Default)]
6292struct UiDrag {
6293 payload: Option<(String, std::rc::Rc<dyn std::any::Any>)>,
6294}
6295
6296fn was_pressed_and_released(state: &mut UiState, id: u64) -> bool {
6297 if state.pressed == id && !state.input.pointer_down {
6298 state.pressed = 0;
6299 return true;
6300 }
6301 false
6302}
6303
6304fn take_activate(state: &mut UiState, id: u64) -> bool {
6307 if state.focused == id && state.input_pending_activate > 0 {
6308 state.input_pending_activate -= 1;
6309 return true;
6310 }
6311 false
6312}
6313
6314fn take_dir(state: &mut UiState, id: u64) -> [i32; 2] {
6316 if state.focused == id {
6317 let dir = state.input_pending_dir;
6318 state.input_pending_dir = [0; 2];
6319 return dir;
6320 }
6321 [0; 2]
6322}
6323
6324fn animate_hover(state: &mut UiState, widget_id: u64, hovered: bool) -> f32 {
6326 let target = u8::from(hovered) as f32;
6327 let motion = state
6328 .widget_motion
6329 .entry(widget_id)
6330 .or_insert(WidgetMotion {
6331 start: 0.0,
6332 current: 0.0,
6333 target: 0.0,
6334 elapsed_ms: 0.0,
6335 last_seen: state.frame_index,
6336 });
6337 motion.last_seen = state.frame_index;
6338 if motion.target != target {
6339 motion.start = motion.current;
6340 motion.target = target;
6341 motion.elapsed_ms = 0.0;
6342 }
6343 let duration = state.motion_speed.duration_ms(120.0);
6344 motion.elapsed_ms = (motion.elapsed_ms + state.frame_delta_ms).min(duration);
6345 let fraction = if duration <= 0.0 {
6346 1.0
6347 } else {
6348 motion.elapsed_ms / duration
6349 };
6350 let inverse = 1.0 - fraction;
6351 motion.current = motion.start + (target - motion.start) * (1.0 - inverse * inverse * inverse);
6352 motion.current
6353}
6354
6355fn allocate_widget(state: &mut UiState, padding: f32) -> (PixelRect, PixelRect) {
6356 let clip = state.layout.top().map(|s| s.clip()).unwrap_or_default();
6357 let Some(scope) = state.layout.top_mut() else {
6358 return (PixelRect::default(), PixelRect::default());
6359 };
6360 let h = default_item_height(padding);
6361 let w = resolve_width(&scope.layout.width.clone(), scope.content_width());
6362 let r = scope.allocate(w.max(1), h);
6363 (r, clip)
6364}
6365
6366fn chart_grid_config(
6371 rect: PixelRect,
6372 content_scale: f32,
6373 fill_background: bool,
6374 draw_grid: bool,
6375) -> UiGridConfig {
6376 let short_side = (rect.w.min(rect.h).saturating_sub(1)).max(1) as f32;
6377 let target_major_pixels = (144.0 * content_scale).max(1.0);
6378 let short_side_cells = (short_side / target_major_pixels).round() as i32;
6379 let short_side_cells = short_side_cells.clamp(4, 6);
6380 let minor_spacing = (short_side / (short_side_cells * 10) as f32).max(1.0);
6381 UiGridConfig {
6382 origin: [
6383 rect.x as f32 + 0.5 * (rect.w - 1) as f32,
6384 rect.y as f32 + 0.5 * (rect.h - 1) as f32,
6385 ],
6386 minor_spacing: [minor_spacing, minor_spacing],
6387 opacity: 0.65,
6388 fill_background,
6389 draw_grid,
6390 draw_axes: draw_grid,
6391 ..UiGridConfig::default()
6392 }
6393}
6394
6395fn allocate_widget_explicit(state: &mut UiState, _padding: f32, h: u32) -> (PixelRect, PixelRect) {
6397 let clip = state.layout.top().map(|s| s.clip()).unwrap_or_default();
6398 let Some(scope) = state.layout.top_mut() else {
6399 return (PixelRect::default(), PixelRect::default());
6400 };
6401 let w = resolve_width(&scope.layout.width.clone(), scope.content_width());
6402 let r = scope.allocate(w.max(1), h.max(1));
6403 (r, clip)
6404}
6405
6406fn virtual_row_range(
6409 item_count: i32,
6410 row_height: i32,
6411 row_gap: i32,
6412 overscan_rows: i32,
6413 scroll_offset_y: i32,
6414 viewport_height: u32,
6415 padding_top: f32,
6416) -> UiVirtualRange {
6417 if item_count <= 0
6418 || row_height <= 0
6419 || row_gap < 0
6420 || overscan_rows < 0
6421 || !padding_top.is_finite()
6422 {
6423 return UiVirtualRange::default();
6424 }
6425 let stride = i64::from(row_height) + i64::from(row_gap);
6426 let padding = padding_top.floor().max(0.0) as i64;
6427 let offset = i64::from(scroll_offset_y.max(0));
6428 let begin = (offset - padding).max(0);
6429 let end = (offset + i64::from(viewport_height) - padding).max(begin);
6430 let first = (begin / stride - i64::from(overscan_rows)).max(0);
6431 let last = ((end + stride - 1) / stride + i64::from(overscan_rows)).min(i64::from(item_count));
6432 UiVirtualRange {
6433 first: first.min(i64::from(item_count)) as i32,
6434 one_past_last: last as i32,
6435 }
6436}
6437
6438fn split_rects(
6439 rect: PixelRect,
6440 direction: UiDirection,
6441 handle_width: u32,
6442 ratio: f32,
6443) -> (PixelRect, PixelRect, PixelRect) {
6444 let extent = match direction {
6445 UiDirection::Row => rect.w,
6446 UiDirection::Column => rect.h,
6447 };
6448 let available = extent.saturating_sub(handle_width);
6449 let first = (available as f32 * ratio)
6450 .round()
6451 .clamp(0.0, available as f32) as u32;
6452 let second = available - first;
6453 match direction {
6454 UiDirection::Row => {
6455 let handle_x = rect.x.saturating_add(first as i32);
6456 (
6457 PixelRect::new(rect.x, rect.y, first, rect.h),
6458 PixelRect::new(handle_x, rect.y, handle_width, rect.h),
6459 PixelRect::new(
6460 handle_x.saturating_add(handle_width as i32),
6461 rect.y,
6462 second,
6463 rect.h,
6464 ),
6465 )
6466 }
6467 UiDirection::Column => {
6468 let handle_y = rect.y.saturating_add(first as i32);
6469 (
6470 PixelRect::new(rect.x, rect.y, rect.w, first),
6471 PixelRect::new(rect.x, handle_y, rect.w, handle_width),
6472 PixelRect::new(
6473 rect.x,
6474 handle_y.saturating_add(handle_width as i32),
6475 rect.w,
6476 second,
6477 ),
6478 )
6479 }
6480 }
6481}
6482
6483fn colormap_sample(t: f32, colormap: i32) -> crate::Color {
6487 let t = t.clamp(0.0, 1.0);
6488 match colormap {
6489 0 => crate::Color::new(t, t, t, 1.0),
6490 2 => {
6491 if t < 0.5 {
6493 let s = t * 2.0;
6494 crate::Color::new(s * 0.85, s * 0.33, 0.85 - s * 0.6, 1.0)
6495 } else {
6496 let s = (t - 0.5) * 2.0;
6497 crate::Color::new(0.85 + s * 0.15, 0.66 + s * 0.34, 0.25 + s * 0.75, 1.0)
6498 }
6499 }
6500 _ => {
6501 if t < 0.33 {
6503 let s = t / 0.33;
6504 crate::Color::new(0.27 - s * 0.15, 0.0 + s * 0.25, 0.33 + s * 0.40, 1.0)
6505 } else if t < 0.66 {
6506 let s = (t - 0.33) / 0.33;
6507 crate::Color::new(0.12 + s * 0.40, 0.25 + s * 0.50, 0.73 - s * 0.40, 1.0)
6508 } else {
6509 let s = (t - 0.66) / 0.34;
6510 crate::Color::new(0.52 + s * 0.48, 0.75 + s * 0.25, 0.33 - s * 0.33, 1.0)
6511 }
6512 }
6513 }
6514}
6515
6516fn allocate_plot(state: &mut UiState, padding: f32) -> (PixelRect, PixelRect) {
6519 let clip = state.layout.top().map(|s| s.clip()).unwrap_or_default();
6520 let Some(scope) = state.layout.top_mut() else {
6521 return (PixelRect::default(), PixelRect::default());
6522 };
6523 let h = default_item_height(padding) * 6;
6524 let w = resolve_width(&scope.layout.width.clone(), scope.content_width());
6525 let r = scope.allocate(w.max(1), h);
6526 (r, clip)
6527}
6528
6529fn bytemuck_push(words: &[u32]) -> &[u8] {
6532 unsafe { std::slice::from_raw_parts(words.as_ptr().cast(), words.len() * 4) }
6534}
6535
6536fn write_u32(buf: &mut [u8], offset: usize, val: u32) {
6537 buf[offset..offset + 4].copy_from_slice(&val.to_ne_bytes());
6538}
6539fn write_i32(buf: &mut [u8], offset: usize, val: i32) {
6540 buf[offset..offset + 4].copy_from_slice(&val.to_ne_bytes());
6541}
6542fn write_f32(buf: &mut [u8], offset: usize, val: f32) {
6543 buf[offset..offset + 4].copy_from_slice(&val.to_bits().to_ne_bytes());
6544}