1use crate::chart::{build_histogram_config, render_chart, Candle, ChartBuilder, HistogramBuilder};
2use crate::event::{Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseKind};
3use crate::halfblock::HalfBlockImage;
4use crate::layout::{Command, Direction};
5use crate::rect::Rect;
6use crate::style::{
7 Align, Border, BorderSides, Breakpoint, Color, Constraints, ContainerStyle, Justify, Margin,
8 Modifiers, Padding, Style, Theme, WidgetColors,
9};
10use crate::widgets::{
11 ApprovalAction, ButtonVariant, CommandPaletteState, ContextItem, FilePickerState, FormField,
12 FormState, ListState, MultiSelectState, RadioState, ScrollState, SelectState, SpinnerState,
13 StreamingTextState, TableState, TabsState, TextInputState, TextareaState, ToastLevel,
14 ToastState, ToolApprovalState, TreeState,
15};
16use crate::FrameState;
17use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
18
19#[allow(dead_code)]
20fn slt_assert(condition: bool, msg: &str) {
21 if !condition {
22 panic!("[SLT] {}", msg);
23 }
24}
25
26#[cfg(debug_assertions)]
27#[allow(dead_code)]
28fn slt_warn(msg: &str) {
29 eprintln!("\x1b[33m[SLT warning]\x1b[0m {}", msg);
30}
31
32#[cfg(not(debug_assertions))]
33#[allow(dead_code)]
34fn slt_warn(_msg: &str) {}
35
36#[derive(Debug, Copy, Clone, PartialEq, Eq)]
38pub struct State<T> {
39 idx: usize,
40 _marker: std::marker::PhantomData<T>,
41}
42
43impl<T: 'static> State<T> {
44 pub fn get<'a>(&self, ui: &'a Context) -> &'a T {
46 ui.hook_states[self.idx]
47 .downcast_ref::<T>()
48 .unwrap_or_else(|| {
49 panic!(
50 "use_state type mismatch at hook index {} — expected {}",
51 self.idx,
52 std::any::type_name::<T>()
53 )
54 })
55 }
56
57 pub fn get_mut<'a>(&self, ui: &'a mut Context) -> &'a mut T {
59 ui.hook_states[self.idx]
60 .downcast_mut::<T>()
61 .unwrap_or_else(|| {
62 panic!(
63 "use_state type mismatch at hook index {} — expected {}",
64 self.idx,
65 std::any::type_name::<T>()
66 )
67 })
68 }
69}
70
71#[derive(Debug, Clone, Default)]
90pub struct Response {
91 pub clicked: bool,
93 pub hovered: bool,
95 pub changed: bool,
97 pub focused: bool,
99 pub rect: Rect,
101}
102
103impl Response {
104 pub fn none() -> Self {
106 Self::default()
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum BarDirection {
113 Horizontal,
115 Vertical,
117}
118
119#[derive(Debug, Clone)]
121pub struct Bar {
122 pub label: String,
124 pub value: f64,
126 pub color: Option<Color>,
128 pub text_value: Option<String>,
129 pub value_style: Option<Style>,
130}
131
132impl Bar {
133 pub fn new(label: impl Into<String>, value: f64) -> Self {
135 Self {
136 label: label.into(),
137 value,
138 color: None,
139 text_value: None,
140 value_style: None,
141 }
142 }
143
144 pub fn color(mut self, color: Color) -> Self {
146 self.color = Some(color);
147 self
148 }
149
150 pub fn text_value(mut self, text: impl Into<String>) -> Self {
151 self.text_value = Some(text.into());
152 self
153 }
154
155 pub fn value_style(mut self, style: Style) -> Self {
156 self.value_style = Some(style);
157 self
158 }
159}
160
161#[derive(Debug, Clone, Copy)]
162pub struct BarChartConfig {
163 pub direction: BarDirection,
164 pub bar_width: u16,
165 pub bar_gap: u16,
166 pub group_gap: u16,
167 pub max_value: Option<f64>,
168}
169
170impl Default for BarChartConfig {
171 fn default() -> Self {
172 Self {
173 direction: BarDirection::Horizontal,
174 bar_width: 1,
175 bar_gap: 0,
176 group_gap: 2,
177 max_value: None,
178 }
179 }
180}
181
182impl BarChartConfig {
183 pub fn direction(&mut self, direction: BarDirection) -> &mut Self {
184 self.direction = direction;
185 self
186 }
187
188 pub fn bar_width(&mut self, bar_width: u16) -> &mut Self {
189 self.bar_width = bar_width.max(1);
190 self
191 }
192
193 pub fn bar_gap(&mut self, bar_gap: u16) -> &mut Self {
194 self.bar_gap = bar_gap;
195 self
196 }
197
198 pub fn group_gap(&mut self, group_gap: u16) -> &mut Self {
199 self.group_gap = group_gap;
200 self
201 }
202
203 pub fn max_value(&mut self, max_value: f64) -> &mut Self {
204 self.max_value = Some(max_value);
205 self
206 }
207}
208
209#[derive(Debug, Clone)]
211pub struct BarGroup {
212 pub label: String,
214 pub bars: Vec<Bar>,
216}
217
218impl BarGroup {
219 pub fn new(label: impl Into<String>, bars: Vec<Bar>) -> Self {
221 Self {
222 label: label.into(),
223 bars,
224 }
225 }
226}
227
228pub trait Widget {
290 type Response;
293
294 fn ui(&mut self, ctx: &mut Context) -> Self::Response;
300}
301
302pub struct Context {
318 pub(crate) commands: Vec<Command>,
320 pub(crate) events: Vec<Event>,
321 pub(crate) consumed: Vec<bool>,
322 pub(crate) should_quit: bool,
323 pub(crate) area_width: u32,
324 pub(crate) area_height: u32,
325 pub(crate) tick: u64,
326 pub(crate) focus_index: usize,
327 pub(crate) focus_count: usize,
328 pub(crate) hook_states: Vec<Box<dyn std::any::Any>>,
329 pub(crate) hook_cursor: usize,
330 prev_focus_count: usize,
331 scroll_count: usize,
332 prev_scroll_infos: Vec<(u32, u32)>,
333 prev_scroll_rects: Vec<Rect>,
334 interaction_count: usize,
335 pub(crate) prev_hit_map: Vec<Rect>,
336 pub(crate) group_stack: Vec<String>,
337 pub(crate) prev_group_rects: Vec<(String, Rect)>,
338 group_count: usize,
339 prev_focus_groups: Vec<Option<String>>,
340 _prev_focus_rects: Vec<(usize, Rect)>,
341 mouse_pos: Option<(u32, u32)>,
342 click_pos: Option<(u32, u32)>,
343 last_text_idx: Option<usize>,
344 overlay_depth: usize,
345 pub(crate) modal_active: bool,
346 prev_modal_active: bool,
347 pub(crate) clipboard_text: Option<String>,
348 debug: bool,
349 theme: Theme,
350 pub(crate) dark_mode: bool,
351 pub(crate) is_real_terminal: bool,
352 pub(crate) deferred_draws: Vec<Option<RawDrawCallback>>,
353 pub(crate) notification_queue: Vec<(String, ToastLevel, u64)>,
354}
355
356type RawDrawCallback = Box<dyn FnOnce(&mut crate::buffer::Buffer, Rect)>;
357
358struct ContextSnapshot {
359 cmd_count: usize,
360 last_text_idx: Option<usize>,
361 focus_count: usize,
362 interaction_count: usize,
363 scroll_count: usize,
364 group_count: usize,
365 group_stack_len: usize,
366 overlay_depth: usize,
367 modal_active: bool,
368 hook_cursor: usize,
369 hook_states_len: usize,
370 dark_mode: bool,
371 deferred_draws_len: usize,
372 notification_queue_len: usize,
373}
374
375impl ContextSnapshot {
376 fn capture(ctx: &Context) -> Self {
377 Self {
378 cmd_count: ctx.commands.len(),
379 last_text_idx: ctx.last_text_idx,
380 focus_count: ctx.focus_count,
381 interaction_count: ctx.interaction_count,
382 scroll_count: ctx.scroll_count,
383 group_count: ctx.group_count,
384 group_stack_len: ctx.group_stack.len(),
385 overlay_depth: ctx.overlay_depth,
386 modal_active: ctx.modal_active,
387 hook_cursor: ctx.hook_cursor,
388 hook_states_len: ctx.hook_states.len(),
389 dark_mode: ctx.dark_mode,
390 deferred_draws_len: ctx.deferred_draws.len(),
391 notification_queue_len: ctx.notification_queue.len(),
392 }
393 }
394
395 fn restore(&self, ctx: &mut Context) {
396 ctx.commands.truncate(self.cmd_count);
397 ctx.last_text_idx = self.last_text_idx;
398 ctx.focus_count = self.focus_count;
399 ctx.interaction_count = self.interaction_count;
400 ctx.scroll_count = self.scroll_count;
401 ctx.group_count = self.group_count;
402 ctx.group_stack.truncate(self.group_stack_len);
403 ctx.overlay_depth = self.overlay_depth;
404 ctx.modal_active = self.modal_active;
405 ctx.hook_cursor = self.hook_cursor;
406 ctx.hook_states.truncate(self.hook_states_len);
407 ctx.dark_mode = self.dark_mode;
408 ctx.deferred_draws.truncate(self.deferred_draws_len);
409 ctx.notification_queue.truncate(self.notification_queue_len);
410 }
411}
412
413#[must_use = "ContainerBuilder does nothing until .col(), .row(), .line(), or .draw() is called"]
434pub struct ContainerBuilder<'a> {
435 ctx: &'a mut Context,
436 gap: u32,
437 align: Align,
438 justify: Justify,
439 border: Option<Border>,
440 border_sides: BorderSides,
441 border_style: Style,
442 bg: Option<Color>,
443 dark_bg: Option<Color>,
444 dark_border_style: Option<Style>,
445 group_hover_bg: Option<Color>,
446 group_hover_border_style: Option<Style>,
447 group_name: Option<String>,
448 padding: Padding,
449 margin: Margin,
450 constraints: Constraints,
451 title: Option<(String, Style)>,
452 grow: u16,
453 scroll_offset: Option<u32>,
454}
455
456#[derive(Debug, Clone, Copy)]
463struct CanvasPixel {
464 bits: u32,
465 color: Color,
466}
467
468#[derive(Debug, Clone)]
470struct CanvasLabel {
471 x: usize,
472 y: usize,
473 text: String,
474 color: Color,
475}
476
477#[derive(Debug, Clone)]
479struct CanvasLayer {
480 grid: Vec<Vec<CanvasPixel>>,
481 labels: Vec<CanvasLabel>,
482}
483
484pub struct CanvasContext {
485 layers: Vec<CanvasLayer>,
486 cols: usize,
487 rows: usize,
488 px_w: usize,
489 px_h: usize,
490 current_color: Color,
491}
492
493impl CanvasContext {
494 fn new(cols: usize, rows: usize) -> Self {
495 Self {
496 layers: vec![Self::new_layer(cols, rows)],
497 cols,
498 rows,
499 px_w: cols * 2,
500 px_h: rows * 4,
501 current_color: Color::Reset,
502 }
503 }
504
505 fn new_layer(cols: usize, rows: usize) -> CanvasLayer {
506 CanvasLayer {
507 grid: vec![
508 vec![
509 CanvasPixel {
510 bits: 0,
511 color: Color::Reset,
512 };
513 cols
514 ];
515 rows
516 ],
517 labels: Vec::new(),
518 }
519 }
520
521 fn current_layer_mut(&mut self) -> Option<&mut CanvasLayer> {
522 self.layers.last_mut()
523 }
524
525 fn dot_with_color(&mut self, x: usize, y: usize, color: Color) {
526 if x >= self.px_w || y >= self.px_h {
527 return;
528 }
529
530 let char_col = x / 2;
531 let char_row = y / 4;
532 let sub_col = x % 2;
533 let sub_row = y % 4;
534 const LEFT_BITS: [u32; 4] = [0x01, 0x02, 0x04, 0x40];
535 const RIGHT_BITS: [u32; 4] = [0x08, 0x10, 0x20, 0x80];
536
537 let bit = if sub_col == 0 {
538 LEFT_BITS[sub_row]
539 } else {
540 RIGHT_BITS[sub_row]
541 };
542
543 if let Some(layer) = self.current_layer_mut() {
544 let cell = &mut layer.grid[char_row][char_col];
545 let new_bits = cell.bits | bit;
546 if new_bits != cell.bits {
547 cell.bits = new_bits;
548 cell.color = color;
549 }
550 }
551 }
552
553 fn dot_isize(&mut self, x: isize, y: isize) {
554 if x >= 0 && y >= 0 {
555 self.dot(x as usize, y as usize);
556 }
557 }
558
559 pub fn width(&self) -> usize {
561 self.px_w
562 }
563
564 pub fn height(&self) -> usize {
566 self.px_h
567 }
568
569 pub fn dot(&mut self, x: usize, y: usize) {
571 self.dot_with_color(x, y, self.current_color);
572 }
573
574 pub fn line(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
576 let (mut x, mut y) = (x0 as isize, y0 as isize);
577 let (x1, y1) = (x1 as isize, y1 as isize);
578 let dx = (x1 - x).abs();
579 let dy = -(y1 - y).abs();
580 let sx = if x < x1 { 1 } else { -1 };
581 let sy = if y < y1 { 1 } else { -1 };
582 let mut err = dx + dy;
583
584 loop {
585 self.dot_isize(x, y);
586 if x == x1 && y == y1 {
587 break;
588 }
589 let e2 = 2 * err;
590 if e2 >= dy {
591 err += dy;
592 x += sx;
593 }
594 if e2 <= dx {
595 err += dx;
596 y += sy;
597 }
598 }
599 }
600
601 pub fn rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
603 if w == 0 || h == 0 {
604 return;
605 }
606
607 self.line(x, y, x + w.saturating_sub(1), y);
608 self.line(
609 x + w.saturating_sub(1),
610 y,
611 x + w.saturating_sub(1),
612 y + h.saturating_sub(1),
613 );
614 self.line(
615 x + w.saturating_sub(1),
616 y + h.saturating_sub(1),
617 x,
618 y + h.saturating_sub(1),
619 );
620 self.line(x, y + h.saturating_sub(1), x, y);
621 }
622
623 pub fn circle(&mut self, cx: usize, cy: usize, r: usize) {
625 let mut x = r as isize;
626 let mut y: isize = 0;
627 let mut err: isize = 1 - x;
628 let (cx, cy) = (cx as isize, cy as isize);
629
630 while x >= y {
631 for &(dx, dy) in &[
632 (x, y),
633 (y, x),
634 (-x, y),
635 (-y, x),
636 (x, -y),
637 (y, -x),
638 (-x, -y),
639 (-y, -x),
640 ] {
641 let px = cx + dx;
642 let py = cy + dy;
643 self.dot_isize(px, py);
644 }
645
646 y += 1;
647 if err < 0 {
648 err += 2 * y + 1;
649 } else {
650 x -= 1;
651 err += 2 * (y - x) + 1;
652 }
653 }
654 }
655
656 pub fn set_color(&mut self, color: Color) {
658 self.current_color = color;
659 }
660
661 pub fn color(&self) -> Color {
663 self.current_color
664 }
665
666 pub fn filled_rect(&mut self, x: usize, y: usize, w: usize, h: usize) {
668 if w == 0 || h == 0 {
669 return;
670 }
671
672 let x_end = x.saturating_add(w).min(self.px_w);
673 let y_end = y.saturating_add(h).min(self.px_h);
674 if x >= x_end || y >= y_end {
675 return;
676 }
677
678 for yy in y..y_end {
679 self.line(x, yy, x_end.saturating_sub(1), yy);
680 }
681 }
682
683 pub fn filled_circle(&mut self, cx: usize, cy: usize, r: usize) {
685 let (cx, cy, r) = (cx as isize, cy as isize, r as isize);
686 for y in (cy - r)..=(cy + r) {
687 let dy = y - cy;
688 let span_sq = (r * r - dy * dy).max(0);
689 let dx = (span_sq as f64).sqrt() as isize;
690 for x in (cx - dx)..=(cx + dx) {
691 self.dot_isize(x, y);
692 }
693 }
694 }
695
696 pub fn triangle(&mut self, x0: usize, y0: usize, x1: usize, y1: usize, x2: usize, y2: usize) {
698 self.line(x0, y0, x1, y1);
699 self.line(x1, y1, x2, y2);
700 self.line(x2, y2, x0, y0);
701 }
702
703 pub fn filled_triangle(
705 &mut self,
706 x0: usize,
707 y0: usize,
708 x1: usize,
709 y1: usize,
710 x2: usize,
711 y2: usize,
712 ) {
713 let vertices = [
714 (x0 as isize, y0 as isize),
715 (x1 as isize, y1 as isize),
716 (x2 as isize, y2 as isize),
717 ];
718 let min_y = vertices.iter().map(|(_, y)| *y).min().unwrap_or(0);
719 let max_y = vertices.iter().map(|(_, y)| *y).max().unwrap_or(-1);
720
721 for y in min_y..=max_y {
722 let mut intersections: Vec<f64> = Vec::new();
723
724 for edge in [(0usize, 1usize), (1usize, 2usize), (2usize, 0usize)] {
725 let (x_a, y_a) = vertices[edge.0];
726 let (x_b, y_b) = vertices[edge.1];
727 if y_a == y_b {
728 continue;
729 }
730
731 let (x_start, y_start, x_end, y_end) = if y_a < y_b {
732 (x_a, y_a, x_b, y_b)
733 } else {
734 (x_b, y_b, x_a, y_a)
735 };
736
737 if y < y_start || y >= y_end {
738 continue;
739 }
740
741 let t = (y - y_start) as f64 / (y_end - y_start) as f64;
742 intersections.push(x_start as f64 + t * (x_end - x_start) as f64);
743 }
744
745 intersections.sort_by(|a, b| a.total_cmp(b));
746 let mut i = 0usize;
747 while i + 1 < intersections.len() {
748 let x_start = intersections[i].ceil() as isize;
749 let x_end = intersections[i + 1].floor() as isize;
750 for x in x_start..=x_end {
751 self.dot_isize(x, y);
752 }
753 i += 2;
754 }
755 }
756
757 self.triangle(x0, y0, x1, y1, x2, y2);
758 }
759
760 pub fn points(&mut self, pts: &[(usize, usize)]) {
762 for &(x, y) in pts {
763 self.dot(x, y);
764 }
765 }
766
767 pub fn polyline(&mut self, pts: &[(usize, usize)]) {
769 for window in pts.windows(2) {
770 if let [(x0, y0), (x1, y1)] = window {
771 self.line(*x0, *y0, *x1, *y1);
772 }
773 }
774 }
775
776 pub fn print(&mut self, x: usize, y: usize, text: &str) {
779 if text.is_empty() {
780 return;
781 }
782
783 let color = self.current_color;
784 if let Some(layer) = self.current_layer_mut() {
785 layer.labels.push(CanvasLabel {
786 x,
787 y,
788 text: text.to_string(),
789 color,
790 });
791 }
792 }
793
794 pub fn layer(&mut self) {
796 self.layers.push(Self::new_layer(self.cols, self.rows));
797 }
798
799 pub(crate) fn render(&self) -> Vec<Vec<(String, Color)>> {
800 let mut final_grid = vec![
801 vec![
802 CanvasPixel {
803 bits: 0,
804 color: Color::Reset,
805 };
806 self.cols
807 ];
808 self.rows
809 ];
810 let mut labels_overlay: Vec<Vec<Option<(char, Color)>>> =
811 vec![vec![None; self.cols]; self.rows];
812
813 for layer in &self.layers {
814 for (row, final_row) in final_grid.iter_mut().enumerate().take(self.rows) {
815 for (col, dst) in final_row.iter_mut().enumerate().take(self.cols) {
816 let src = layer.grid[row][col];
817 if src.bits == 0 {
818 continue;
819 }
820
821 let merged = dst.bits | src.bits;
822 if merged != dst.bits {
823 dst.bits = merged;
824 dst.color = src.color;
825 }
826 }
827 }
828
829 for label in &layer.labels {
830 let row = label.y / 4;
831 if row >= self.rows {
832 continue;
833 }
834 let start_col = label.x / 2;
835 for (offset, ch) in label.text.chars().enumerate() {
836 let col = start_col + offset;
837 if col >= self.cols {
838 break;
839 }
840 labels_overlay[row][col] = Some((ch, label.color));
841 }
842 }
843 }
844
845 let mut lines: Vec<Vec<(String, Color)>> = Vec::with_capacity(self.rows);
846 for row in 0..self.rows {
847 let mut segments: Vec<(String, Color)> = Vec::new();
848 let mut current_color: Option<Color> = None;
849 let mut current_text = String::new();
850
851 for col in 0..self.cols {
852 let (ch, color) = if let Some((label_ch, label_color)) = labels_overlay[row][col] {
853 (label_ch, label_color)
854 } else {
855 let bits = final_grid[row][col].bits;
856 let ch = char::from_u32(0x2800 + bits).unwrap_or(' ');
857 (ch, final_grid[row][col].color)
858 };
859
860 match current_color {
861 Some(c) if c == color => {
862 current_text.push(ch);
863 }
864 Some(c) => {
865 segments.push((std::mem::take(&mut current_text), c));
866 current_text.push(ch);
867 current_color = Some(color);
868 }
869 None => {
870 current_text.push(ch);
871 current_color = Some(color);
872 }
873 }
874 }
875
876 if let Some(color) = current_color {
877 segments.push((current_text, color));
878 }
879 lines.push(segments);
880 }
881
882 lines
883 }
884}
885
886impl<'a> ContainerBuilder<'a> {
887 pub fn apply(mut self, style: &ContainerStyle) -> Self {
892 if let Some(v) = style.border {
893 self.border = Some(v);
894 }
895 if let Some(v) = style.border_sides {
896 self.border_sides = v;
897 }
898 if let Some(v) = style.border_style {
899 self.border_style = v;
900 }
901 if let Some(v) = style.bg {
902 self.bg = Some(v);
903 }
904 if let Some(v) = style.dark_bg {
905 self.dark_bg = Some(v);
906 }
907 if let Some(v) = style.dark_border_style {
908 self.dark_border_style = Some(v);
909 }
910 if let Some(v) = style.padding {
911 self.padding = v;
912 }
913 if let Some(v) = style.margin {
914 self.margin = v;
915 }
916 if let Some(v) = style.gap {
917 self.gap = v;
918 }
919 if let Some(v) = style.grow {
920 self.grow = v;
921 }
922 if let Some(v) = style.align {
923 self.align = v;
924 }
925 if let Some(v) = style.justify {
926 self.justify = v;
927 }
928 if let Some(w) = style.w {
929 self.constraints.min_width = Some(w);
930 self.constraints.max_width = Some(w);
931 }
932 if let Some(h) = style.h {
933 self.constraints.min_height = Some(h);
934 self.constraints.max_height = Some(h);
935 }
936 if let Some(v) = style.min_w {
937 self.constraints.min_width = Some(v);
938 }
939 if let Some(v) = style.max_w {
940 self.constraints.max_width = Some(v);
941 }
942 if let Some(v) = style.min_h {
943 self.constraints.min_height = Some(v);
944 }
945 if let Some(v) = style.max_h {
946 self.constraints.max_height = Some(v);
947 }
948 if let Some(v) = style.w_pct {
949 self.constraints.width_pct = Some(v);
950 }
951 if let Some(v) = style.h_pct {
952 self.constraints.height_pct = Some(v);
953 }
954 self
955 }
956
957 pub fn border(mut self, border: Border) -> Self {
959 self.border = Some(border);
960 self
961 }
962
963 pub fn border_top(mut self, show: bool) -> Self {
965 self.border_sides.top = show;
966 self
967 }
968
969 pub fn border_right(mut self, show: bool) -> Self {
971 self.border_sides.right = show;
972 self
973 }
974
975 pub fn border_bottom(mut self, show: bool) -> Self {
977 self.border_sides.bottom = show;
978 self
979 }
980
981 pub fn border_left(mut self, show: bool) -> Self {
983 self.border_sides.left = show;
984 self
985 }
986
987 pub fn border_sides(mut self, sides: BorderSides) -> Self {
989 self.border_sides = sides;
990 self
991 }
992
993 pub fn rounded(self) -> Self {
995 self.border(Border::Rounded)
996 }
997
998 pub fn border_style(mut self, style: Style) -> Self {
1000 self.border_style = style;
1001 self
1002 }
1003
1004 pub fn dark_border_style(mut self, style: Style) -> Self {
1006 self.dark_border_style = Some(style);
1007 self
1008 }
1009
1010 pub fn bg(mut self, color: Color) -> Self {
1011 self.bg = Some(color);
1012 self
1013 }
1014
1015 pub fn dark_bg(mut self, color: Color) -> Self {
1017 self.dark_bg = Some(color);
1018 self
1019 }
1020
1021 pub fn group_hover_bg(mut self, color: Color) -> Self {
1023 self.group_hover_bg = Some(color);
1024 self
1025 }
1026
1027 pub fn group_hover_border_style(mut self, style: Style) -> Self {
1029 self.group_hover_border_style = Some(style);
1030 self
1031 }
1032
1033 pub fn p(self, value: u32) -> Self {
1037 self.pad(value)
1038 }
1039
1040 pub fn pad(mut self, value: u32) -> Self {
1042 self.padding = Padding::all(value);
1043 self
1044 }
1045
1046 pub fn px(mut self, value: u32) -> Self {
1048 self.padding.left = value;
1049 self.padding.right = value;
1050 self
1051 }
1052
1053 pub fn py(mut self, value: u32) -> Self {
1055 self.padding.top = value;
1056 self.padding.bottom = value;
1057 self
1058 }
1059
1060 pub fn pt(mut self, value: u32) -> Self {
1062 self.padding.top = value;
1063 self
1064 }
1065
1066 pub fn pr(mut self, value: u32) -> Self {
1068 self.padding.right = value;
1069 self
1070 }
1071
1072 pub fn pb(mut self, value: u32) -> Self {
1074 self.padding.bottom = value;
1075 self
1076 }
1077
1078 pub fn pl(mut self, value: u32) -> Self {
1080 self.padding.left = value;
1081 self
1082 }
1083
1084 pub fn padding(mut self, padding: Padding) -> Self {
1086 self.padding = padding;
1087 self
1088 }
1089
1090 pub fn m(mut self, value: u32) -> Self {
1094 self.margin = Margin::all(value);
1095 self
1096 }
1097
1098 pub fn mx(mut self, value: u32) -> Self {
1100 self.margin.left = value;
1101 self.margin.right = value;
1102 self
1103 }
1104
1105 pub fn my(mut self, value: u32) -> Self {
1107 self.margin.top = value;
1108 self.margin.bottom = value;
1109 self
1110 }
1111
1112 pub fn mt(mut self, value: u32) -> Self {
1114 self.margin.top = value;
1115 self
1116 }
1117
1118 pub fn mr(mut self, value: u32) -> Self {
1120 self.margin.right = value;
1121 self
1122 }
1123
1124 pub fn mb(mut self, value: u32) -> Self {
1126 self.margin.bottom = value;
1127 self
1128 }
1129
1130 pub fn ml(mut self, value: u32) -> Self {
1132 self.margin.left = value;
1133 self
1134 }
1135
1136 pub fn margin(mut self, margin: Margin) -> Self {
1138 self.margin = margin;
1139 self
1140 }
1141
1142 pub fn w(mut self, value: u32) -> Self {
1146 self.constraints.min_width = Some(value);
1147 self.constraints.max_width = Some(value);
1148 self
1149 }
1150
1151 pub fn xs_w(self, value: u32) -> Self {
1158 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1159 if is_xs {
1160 self.w(value)
1161 } else {
1162 self
1163 }
1164 }
1165
1166 pub fn sm_w(self, value: u32) -> Self {
1168 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1169 if is_sm {
1170 self.w(value)
1171 } else {
1172 self
1173 }
1174 }
1175
1176 pub fn md_w(self, value: u32) -> Self {
1178 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1179 if is_md {
1180 self.w(value)
1181 } else {
1182 self
1183 }
1184 }
1185
1186 pub fn lg_w(self, value: u32) -> Self {
1188 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1189 if is_lg {
1190 self.w(value)
1191 } else {
1192 self
1193 }
1194 }
1195
1196 pub fn xl_w(self, value: u32) -> Self {
1198 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1199 if is_xl {
1200 self.w(value)
1201 } else {
1202 self
1203 }
1204 }
1205 pub fn w_at(self, bp: Breakpoint, value: u32) -> Self {
1206 if self.ctx.breakpoint() == bp {
1207 self.w(value)
1208 } else {
1209 self
1210 }
1211 }
1212
1213 pub fn h(mut self, value: u32) -> Self {
1215 self.constraints.min_height = Some(value);
1216 self.constraints.max_height = Some(value);
1217 self
1218 }
1219
1220 pub fn xs_h(self, value: u32) -> Self {
1222 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1223 if is_xs {
1224 self.h(value)
1225 } else {
1226 self
1227 }
1228 }
1229
1230 pub fn sm_h(self, value: u32) -> Self {
1232 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1233 if is_sm {
1234 self.h(value)
1235 } else {
1236 self
1237 }
1238 }
1239
1240 pub fn md_h(self, value: u32) -> Self {
1242 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1243 if is_md {
1244 self.h(value)
1245 } else {
1246 self
1247 }
1248 }
1249
1250 pub fn lg_h(self, value: u32) -> Self {
1252 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1253 if is_lg {
1254 self.h(value)
1255 } else {
1256 self
1257 }
1258 }
1259
1260 pub fn xl_h(self, value: u32) -> Self {
1262 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1263 if is_xl {
1264 self.h(value)
1265 } else {
1266 self
1267 }
1268 }
1269 pub fn h_at(self, bp: Breakpoint, value: u32) -> Self {
1270 if self.ctx.breakpoint() == bp {
1271 self.h(value)
1272 } else {
1273 self
1274 }
1275 }
1276
1277 pub fn min_w(mut self, value: u32) -> Self {
1279 self.constraints.min_width = Some(value);
1280 self
1281 }
1282
1283 pub fn xs_min_w(self, value: u32) -> Self {
1285 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1286 if is_xs {
1287 self.min_w(value)
1288 } else {
1289 self
1290 }
1291 }
1292
1293 pub fn sm_min_w(self, value: u32) -> Self {
1295 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1296 if is_sm {
1297 self.min_w(value)
1298 } else {
1299 self
1300 }
1301 }
1302
1303 pub fn md_min_w(self, value: u32) -> Self {
1305 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1306 if is_md {
1307 self.min_w(value)
1308 } else {
1309 self
1310 }
1311 }
1312
1313 pub fn lg_min_w(self, value: u32) -> Self {
1315 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1316 if is_lg {
1317 self.min_w(value)
1318 } else {
1319 self
1320 }
1321 }
1322
1323 pub fn xl_min_w(self, value: u32) -> Self {
1325 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1326 if is_xl {
1327 self.min_w(value)
1328 } else {
1329 self
1330 }
1331 }
1332 pub fn min_w_at(self, bp: Breakpoint, value: u32) -> Self {
1333 if self.ctx.breakpoint() == bp {
1334 self.min_w(value)
1335 } else {
1336 self
1337 }
1338 }
1339
1340 pub fn max_w(mut self, value: u32) -> Self {
1342 self.constraints.max_width = Some(value);
1343 self
1344 }
1345
1346 pub fn xs_max_w(self, value: u32) -> Self {
1348 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1349 if is_xs {
1350 self.max_w(value)
1351 } else {
1352 self
1353 }
1354 }
1355
1356 pub fn sm_max_w(self, value: u32) -> Self {
1358 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1359 if is_sm {
1360 self.max_w(value)
1361 } else {
1362 self
1363 }
1364 }
1365
1366 pub fn md_max_w(self, value: u32) -> Self {
1368 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1369 if is_md {
1370 self.max_w(value)
1371 } else {
1372 self
1373 }
1374 }
1375
1376 pub fn lg_max_w(self, value: u32) -> Self {
1378 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1379 if is_lg {
1380 self.max_w(value)
1381 } else {
1382 self
1383 }
1384 }
1385
1386 pub fn xl_max_w(self, value: u32) -> Self {
1388 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1389 if is_xl {
1390 self.max_w(value)
1391 } else {
1392 self
1393 }
1394 }
1395 pub fn max_w_at(self, bp: Breakpoint, value: u32) -> Self {
1396 if self.ctx.breakpoint() == bp {
1397 self.max_w(value)
1398 } else {
1399 self
1400 }
1401 }
1402
1403 pub fn min_h(mut self, value: u32) -> Self {
1405 self.constraints.min_height = Some(value);
1406 self
1407 }
1408
1409 pub fn max_h(mut self, value: u32) -> Self {
1411 self.constraints.max_height = Some(value);
1412 self
1413 }
1414
1415 pub fn min_width(mut self, value: u32) -> Self {
1417 self.constraints.min_width = Some(value);
1418 self
1419 }
1420
1421 pub fn max_width(mut self, value: u32) -> Self {
1423 self.constraints.max_width = Some(value);
1424 self
1425 }
1426
1427 pub fn min_height(mut self, value: u32) -> Self {
1429 self.constraints.min_height = Some(value);
1430 self
1431 }
1432
1433 pub fn max_height(mut self, value: u32) -> Self {
1435 self.constraints.max_height = Some(value);
1436 self
1437 }
1438
1439 pub fn w_pct(mut self, pct: u8) -> Self {
1441 self.constraints.width_pct = Some(pct.min(100));
1442 self
1443 }
1444
1445 pub fn h_pct(mut self, pct: u8) -> Self {
1447 self.constraints.height_pct = Some(pct.min(100));
1448 self
1449 }
1450
1451 pub fn constraints(mut self, constraints: Constraints) -> Self {
1453 self.constraints = constraints;
1454 self
1455 }
1456
1457 pub fn gap(mut self, gap: u32) -> Self {
1461 self.gap = gap;
1462 self
1463 }
1464
1465 pub fn xs_gap(self, value: u32) -> Self {
1467 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1468 if is_xs {
1469 self.gap(value)
1470 } else {
1471 self
1472 }
1473 }
1474
1475 pub fn sm_gap(self, value: u32) -> Self {
1477 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1478 if is_sm {
1479 self.gap(value)
1480 } else {
1481 self
1482 }
1483 }
1484
1485 pub fn md_gap(self, value: u32) -> Self {
1492 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1493 if is_md {
1494 self.gap(value)
1495 } else {
1496 self
1497 }
1498 }
1499
1500 pub fn lg_gap(self, value: u32) -> Self {
1502 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1503 if is_lg {
1504 self.gap(value)
1505 } else {
1506 self
1507 }
1508 }
1509
1510 pub fn xl_gap(self, value: u32) -> Self {
1512 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1513 if is_xl {
1514 self.gap(value)
1515 } else {
1516 self
1517 }
1518 }
1519
1520 pub fn gap_at(self, bp: Breakpoint, value: u32) -> Self {
1521 if self.ctx.breakpoint() == bp {
1522 self.gap(value)
1523 } else {
1524 self
1525 }
1526 }
1527
1528 pub fn grow(mut self, grow: u16) -> Self {
1530 self.grow = grow;
1531 self
1532 }
1533
1534 pub fn xs_grow(self, value: u16) -> Self {
1536 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1537 if is_xs {
1538 self.grow(value)
1539 } else {
1540 self
1541 }
1542 }
1543
1544 pub fn sm_grow(self, value: u16) -> Self {
1546 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1547 if is_sm {
1548 self.grow(value)
1549 } else {
1550 self
1551 }
1552 }
1553
1554 pub fn md_grow(self, value: u16) -> Self {
1556 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1557 if is_md {
1558 self.grow(value)
1559 } else {
1560 self
1561 }
1562 }
1563
1564 pub fn lg_grow(self, value: u16) -> Self {
1566 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1567 if is_lg {
1568 self.grow(value)
1569 } else {
1570 self
1571 }
1572 }
1573
1574 pub fn xl_grow(self, value: u16) -> Self {
1576 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1577 if is_xl {
1578 self.grow(value)
1579 } else {
1580 self
1581 }
1582 }
1583 pub fn grow_at(self, bp: Breakpoint, value: u16) -> Self {
1584 if self.ctx.breakpoint() == bp {
1585 self.grow(value)
1586 } else {
1587 self
1588 }
1589 }
1590
1591 pub fn xs_p(self, value: u32) -> Self {
1593 let is_xs = self.ctx.breakpoint() == Breakpoint::Xs;
1594 if is_xs {
1595 self.p(value)
1596 } else {
1597 self
1598 }
1599 }
1600
1601 pub fn sm_p(self, value: u32) -> Self {
1603 let is_sm = self.ctx.breakpoint() == Breakpoint::Sm;
1604 if is_sm {
1605 self.p(value)
1606 } else {
1607 self
1608 }
1609 }
1610
1611 pub fn md_p(self, value: u32) -> Self {
1613 let is_md = self.ctx.breakpoint() == Breakpoint::Md;
1614 if is_md {
1615 self.p(value)
1616 } else {
1617 self
1618 }
1619 }
1620
1621 pub fn lg_p(self, value: u32) -> Self {
1623 let is_lg = self.ctx.breakpoint() == Breakpoint::Lg;
1624 if is_lg {
1625 self.p(value)
1626 } else {
1627 self
1628 }
1629 }
1630
1631 pub fn xl_p(self, value: u32) -> Self {
1633 let is_xl = self.ctx.breakpoint() == Breakpoint::Xl;
1634 if is_xl {
1635 self.p(value)
1636 } else {
1637 self
1638 }
1639 }
1640 pub fn p_at(self, bp: Breakpoint, value: u32) -> Self {
1641 if self.ctx.breakpoint() == bp {
1642 self.p(value)
1643 } else {
1644 self
1645 }
1646 }
1647
1648 pub fn align(mut self, align: Align) -> Self {
1652 self.align = align;
1653 self
1654 }
1655
1656 pub fn center(self) -> Self {
1658 self.align(Align::Center)
1659 }
1660
1661 pub fn justify(mut self, justify: Justify) -> Self {
1663 self.justify = justify;
1664 self
1665 }
1666
1667 pub fn space_between(self) -> Self {
1669 self.justify(Justify::SpaceBetween)
1670 }
1671
1672 pub fn space_around(self) -> Self {
1674 self.justify(Justify::SpaceAround)
1675 }
1676
1677 pub fn space_evenly(self) -> Self {
1679 self.justify(Justify::SpaceEvenly)
1680 }
1681
1682 pub fn title(self, title: impl Into<String>) -> Self {
1686 self.title_styled(title, Style::new())
1687 }
1688
1689 pub fn title_styled(mut self, title: impl Into<String>, style: Style) -> Self {
1691 self.title = Some((title.into(), style));
1692 self
1693 }
1694
1695 pub fn scroll_offset(mut self, offset: u32) -> Self {
1699 self.scroll_offset = Some(offset);
1700 self
1701 }
1702
1703 fn group_name(mut self, name: String) -> Self {
1704 self.group_name = Some(name);
1705 self
1706 }
1707
1708 pub fn col(self, f: impl FnOnce(&mut Context)) -> Response {
1713 self.finish(Direction::Column, f)
1714 }
1715
1716 pub fn row(self, f: impl FnOnce(&mut Context)) -> Response {
1721 self.finish(Direction::Row, f)
1722 }
1723
1724 pub fn line(mut self, f: impl FnOnce(&mut Context)) -> Response {
1729 self.gap = 0;
1730 self.finish(Direction::Row, f)
1731 }
1732
1733 pub fn draw(self, f: impl FnOnce(&mut crate::buffer::Buffer, Rect) + 'static) {
1748 let draw_id = self.ctx.deferred_draws.len();
1749 self.ctx.deferred_draws.push(Some(Box::new(f)));
1750 self.ctx.interaction_count += 1;
1751 self.ctx.commands.push(Command::RawDraw {
1752 draw_id,
1753 constraints: self.constraints,
1754 grow: self.grow,
1755 margin: self.margin,
1756 });
1757 }
1758
1759 fn finish(mut self, direction: Direction, f: impl FnOnce(&mut Context)) -> Response {
1760 let interaction_id = self.ctx.interaction_count;
1761 self.ctx.interaction_count += 1;
1762
1763 let in_hovered_group = self
1764 .group_name
1765 .as_ref()
1766 .map(|name| self.ctx.is_group_hovered(name))
1767 .unwrap_or(false)
1768 || self
1769 .ctx
1770 .group_stack
1771 .last()
1772 .map(|name| self.ctx.is_group_hovered(name))
1773 .unwrap_or(false);
1774 let in_focused_group = self
1775 .group_name
1776 .as_ref()
1777 .map(|name| self.ctx.is_group_focused(name))
1778 .unwrap_or(false)
1779 || self
1780 .ctx
1781 .group_stack
1782 .last()
1783 .map(|name| self.ctx.is_group_focused(name))
1784 .unwrap_or(false);
1785
1786 let resolved_bg = if self.ctx.dark_mode {
1787 self.dark_bg.or(self.bg)
1788 } else {
1789 self.bg
1790 };
1791 let resolved_border_style = if self.ctx.dark_mode {
1792 self.dark_border_style.unwrap_or(self.border_style)
1793 } else {
1794 self.border_style
1795 };
1796 let bg_color = if in_hovered_group || in_focused_group {
1797 self.group_hover_bg.or(resolved_bg)
1798 } else {
1799 resolved_bg
1800 };
1801 let border_style = if in_hovered_group || in_focused_group {
1802 self.group_hover_border_style
1803 .unwrap_or(resolved_border_style)
1804 } else {
1805 resolved_border_style
1806 };
1807 let group_name = self.group_name.take();
1808 let is_group_container = group_name.is_some();
1809
1810 if let Some(scroll_offset) = self.scroll_offset {
1811 self.ctx.commands.push(Command::BeginScrollable {
1812 grow: self.grow,
1813 border: self.border,
1814 border_sides: self.border_sides,
1815 border_style,
1816 padding: self.padding,
1817 margin: self.margin,
1818 constraints: self.constraints,
1819 title: self.title,
1820 scroll_offset,
1821 });
1822 } else {
1823 self.ctx.commands.push(Command::BeginContainer {
1824 direction,
1825 gap: self.gap,
1826 align: self.align,
1827 justify: self.justify,
1828 border: self.border,
1829 border_sides: self.border_sides,
1830 border_style,
1831 bg_color,
1832 padding: self.padding,
1833 margin: self.margin,
1834 constraints: self.constraints,
1835 title: self.title,
1836 grow: self.grow,
1837 group_name,
1838 });
1839 }
1840 f(self.ctx);
1841 self.ctx.commands.push(Command::EndContainer);
1842 self.ctx.last_text_idx = None;
1843
1844 if is_group_container {
1845 self.ctx.group_stack.pop();
1846 self.ctx.group_count = self.ctx.group_count.saturating_sub(1);
1847 }
1848
1849 self.ctx.response_for(interaction_id)
1850 }
1851}
1852
1853impl Context {
1854 pub(crate) fn new(
1855 events: Vec<Event>,
1856 width: u32,
1857 height: u32,
1858 state: &mut FrameState,
1859 theme: Theme,
1860 ) -> Self {
1861 let consumed = vec![false; events.len()];
1862
1863 let mut mouse_pos = state.last_mouse_pos;
1864 let mut click_pos = None;
1865 for event in &events {
1866 if let Event::Mouse(mouse) = event {
1867 mouse_pos = Some((mouse.x, mouse.y));
1868 if matches!(mouse.kind, MouseKind::Down(MouseButton::Left)) {
1869 click_pos = Some((mouse.x, mouse.y));
1870 }
1871 }
1872 }
1873
1874 let mut focus_index = state.focus_index;
1875 if let Some((mx, my)) = click_pos {
1876 let mut best: Option<(usize, u64)> = None;
1877 for &(fid, rect) in &state.prev_focus_rects {
1878 if mx >= rect.x && mx < rect.right() && my >= rect.y && my < rect.bottom() {
1879 let area = rect.width as u64 * rect.height as u64;
1880 if best.map_or(true, |(_, ba)| area < ba) {
1881 best = Some((fid, area));
1882 }
1883 }
1884 }
1885 if let Some((fid, _)) = best {
1886 focus_index = fid;
1887 }
1888 }
1889
1890 Self {
1891 commands: Vec::new(),
1892 events,
1893 consumed,
1894 should_quit: false,
1895 area_width: width,
1896 area_height: height,
1897 tick: state.tick,
1898 focus_index,
1899 focus_count: 0,
1900 hook_states: std::mem::take(&mut state.hook_states),
1901 hook_cursor: 0,
1902 prev_focus_count: state.prev_focus_count,
1903 scroll_count: 0,
1904 prev_scroll_infos: std::mem::take(&mut state.prev_scroll_infos),
1905 prev_scroll_rects: std::mem::take(&mut state.prev_scroll_rects),
1906 interaction_count: 0,
1907 prev_hit_map: std::mem::take(&mut state.prev_hit_map),
1908 group_stack: Vec::new(),
1909 prev_group_rects: std::mem::take(&mut state.prev_group_rects),
1910 group_count: 0,
1911 prev_focus_groups: std::mem::take(&mut state.prev_focus_groups),
1912 _prev_focus_rects: std::mem::take(&mut state.prev_focus_rects),
1913 mouse_pos,
1914 click_pos,
1915 last_text_idx: None,
1916 overlay_depth: 0,
1917 modal_active: false,
1918 prev_modal_active: state.prev_modal_active,
1919 clipboard_text: None,
1920 debug: state.debug_mode,
1921 theme,
1922 dark_mode: theme.is_dark,
1923 is_real_terminal: false,
1924 deferred_draws: Vec::new(),
1925 notification_queue: std::mem::take(&mut state.notification_queue),
1926 }
1927 }
1928
1929 pub(crate) fn process_focus_keys(&mut self) {
1930 for (i, event) in self.events.iter().enumerate() {
1931 if let Event::Key(key) = event {
1932 if key.kind != KeyEventKind::Press {
1933 continue;
1934 }
1935 if key.code == KeyCode::Tab && !key.modifiers.contains(KeyModifiers::SHIFT) {
1936 if self.prev_focus_count > 0 {
1937 self.focus_index = (self.focus_index + 1) % self.prev_focus_count;
1938 }
1939 self.consumed[i] = true;
1940 } else if (key.code == KeyCode::Tab && key.modifiers.contains(KeyModifiers::SHIFT))
1941 || key.code == KeyCode::BackTab
1942 {
1943 if self.prev_focus_count > 0 {
1944 self.focus_index = if self.focus_index == 0 {
1945 self.prev_focus_count - 1
1946 } else {
1947 self.focus_index - 1
1948 };
1949 }
1950 self.consumed[i] = true;
1951 }
1952 }
1953 }
1954 }
1955
1956 pub fn widget<W: Widget>(&mut self, w: &mut W) -> W::Response {
1960 w.ui(self)
1961 }
1962
1963 pub fn error_boundary(&mut self, f: impl FnOnce(&mut Context)) {
1978 self.error_boundary_with(f, |ui, msg| {
1979 ui.styled(
1980 format!("⚠ Error: {msg}"),
1981 Style::new().fg(ui.theme.error).bold(),
1982 );
1983 });
1984 }
1985
1986 pub fn error_boundary_with(
2006 &mut self,
2007 f: impl FnOnce(&mut Context),
2008 fallback: impl FnOnce(&mut Context, String),
2009 ) {
2010 let snapshot = ContextSnapshot::capture(self);
2011
2012 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2013 f(self);
2014 }));
2015
2016 match result {
2017 Ok(()) => {}
2018 Err(panic_info) => {
2019 if self.is_real_terminal {
2020 let _ = crossterm::terminal::enable_raw_mode();
2021 let _ = crossterm::execute!(
2022 std::io::stdout(),
2023 crossterm::terminal::EnterAlternateScreen
2024 );
2025 }
2026
2027 snapshot.restore(self);
2028
2029 let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
2030 (*s).to_string()
2031 } else if let Some(s) = panic_info.downcast_ref::<String>() {
2032 s.clone()
2033 } else {
2034 "widget panicked".to_string()
2035 };
2036
2037 fallback(self, msg);
2038 }
2039 }
2040 }
2041
2042 pub fn interaction(&mut self) -> Response {
2048 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
2049 return Response::none();
2050 }
2051 let id = self.interaction_count;
2052 self.interaction_count += 1;
2053 self.response_for(id)
2054 }
2055
2056 pub fn register_focusable(&mut self) -> bool {
2061 if (self.modal_active || self.prev_modal_active) && self.overlay_depth == 0 {
2062 return false;
2063 }
2064 let id = self.focus_count;
2065 self.focus_count += 1;
2066 self.commands.push(Command::FocusMarker(id));
2067 if self.prev_focus_count == 0 {
2068 return true;
2069 }
2070 self.focus_index % self.prev_focus_count == id
2071 }
2072
2073 pub fn use_state<T: 'static>(&mut self, init: impl FnOnce() -> T) -> State<T> {
2091 let idx = self.hook_cursor;
2092 self.hook_cursor += 1;
2093
2094 if idx >= self.hook_states.len() {
2095 self.hook_states.push(Box::new(init()));
2096 }
2097
2098 State {
2099 idx,
2100 _marker: std::marker::PhantomData,
2101 }
2102 }
2103
2104 pub fn use_memo<T: 'static, D: PartialEq + Clone + 'static>(
2112 &mut self,
2113 deps: &D,
2114 compute: impl FnOnce(&D) -> T,
2115 ) -> &T {
2116 let idx = self.hook_cursor;
2117 self.hook_cursor += 1;
2118
2119 let should_recompute = if idx >= self.hook_states.len() {
2120 true
2121 } else {
2122 let (stored_deps, _) = self.hook_states[idx]
2123 .downcast_ref::<(D, T)>()
2124 .unwrap_or_else(|| {
2125 panic!(
2126 "use_memo type mismatch at hook index {} — expected {}",
2127 idx,
2128 std::any::type_name::<D>()
2129 )
2130 });
2131 stored_deps != deps
2132 };
2133
2134 if should_recompute {
2135 let value = compute(deps);
2136 let slot = Box::new((deps.clone(), value));
2137 if idx < self.hook_states.len() {
2138 self.hook_states[idx] = slot;
2139 } else {
2140 self.hook_states.push(slot);
2141 }
2142 }
2143
2144 let (_, value) = self.hook_states[idx]
2145 .downcast_ref::<(D, T)>()
2146 .unwrap_or_else(|| {
2147 panic!(
2148 "use_memo type mismatch at hook index {} — expected {}",
2149 idx,
2150 std::any::type_name::<D>()
2151 )
2152 });
2153 value
2154 }
2155
2156 pub fn light_dark(&self, light: Color, dark: Color) -> Color {
2158 if self.theme.is_dark {
2159 dark
2160 } else {
2161 light
2162 }
2163 }
2164
2165 pub fn notify(&mut self, message: &str, level: ToastLevel) {
2175 let tick = self.tick;
2176 self.notification_queue
2177 .push((message.to_string(), level, tick));
2178 }
2179
2180 pub(crate) fn render_notifications(&mut self) {
2181 self.notification_queue
2182 .retain(|(_, _, created)| self.tick.saturating_sub(*created) < 180);
2183 if self.notification_queue.is_empty() {
2184 return;
2185 }
2186
2187 let items: Vec<(String, Color)> = self
2188 .notification_queue
2189 .iter()
2190 .rev()
2191 .map(|(message, level, _)| {
2192 let color = match level {
2193 ToastLevel::Info => self.theme.primary,
2194 ToastLevel::Success => self.theme.success,
2195 ToastLevel::Warning => self.theme.warning,
2196 ToastLevel::Error => self.theme.error,
2197 };
2198 (message.clone(), color)
2199 })
2200 .collect();
2201
2202 self.overlay(|ui| {
2203 ui.row(|ui| {
2204 ui.spacer();
2205 ui.col(|ui| {
2206 for (message, color) in &items {
2207 ui.styled(format!("● {message}"), Style::new().fg(*color));
2208 }
2209 });
2210 });
2211 });
2212 }
2213}
2214
2215mod widgets_display;
2216mod widgets_input;
2217mod widgets_interactive;
2218mod widgets_viz;
2219
2220#[inline]
2221fn byte_index_for_char(value: &str, char_index: usize) -> usize {
2222 if char_index == 0 {
2223 return 0;
2224 }
2225 value
2226 .char_indices()
2227 .nth(char_index)
2228 .map_or(value.len(), |(idx, _)| idx)
2229}
2230
2231fn format_token_count(count: usize) -> String {
2232 if count >= 1_000_000 {
2233 format!("{:.1}M", count as f64 / 1_000_000.0)
2234 } else if count >= 1_000 {
2235 format!("{:.1}k", count as f64 / 1_000.0)
2236 } else {
2237 format!("{count}")
2238 }
2239}
2240
2241fn format_table_row(cells: &[String], widths: &[u32], separator: &str) -> String {
2242 let mut parts: Vec<String> = Vec::new();
2243 for (i, width) in widths.iter().enumerate() {
2244 let cell = cells.get(i).map(String::as_str).unwrap_or("");
2245 let cell_width = UnicodeWidthStr::width(cell) as u32;
2246 let padding = (*width).saturating_sub(cell_width) as usize;
2247 parts.push(format!("{cell}{}", " ".repeat(padding)));
2248 }
2249 parts.join(separator)
2250}
2251
2252fn table_visible_len(state: &TableState) -> usize {
2253 if state.page_size == 0 {
2254 return state.visible_indices().len();
2255 }
2256
2257 let start = state
2258 .page
2259 .saturating_mul(state.page_size)
2260 .min(state.visible_indices().len());
2261 let end = (start + state.page_size).min(state.visible_indices().len());
2262 end.saturating_sub(start)
2263}
2264
2265pub(crate) fn handle_vertical_nav(
2266 selected: &mut usize,
2267 max_index: usize,
2268 key_code: KeyCode,
2269) -> bool {
2270 match key_code {
2271 KeyCode::Up | KeyCode::Char('k') => {
2272 if *selected > 0 {
2273 *selected -= 1;
2274 true
2275 } else {
2276 false
2277 }
2278 }
2279 KeyCode::Down | KeyCode::Char('j') => {
2280 if *selected < max_index {
2281 *selected += 1;
2282 true
2283 } else {
2284 false
2285 }
2286 }
2287 _ => false,
2288 }
2289}
2290
2291fn format_compact_number(value: f64) -> String {
2292 if value.fract().abs() < f64::EPSILON {
2293 return format!("{value:.0}");
2294 }
2295
2296 let mut s = format!("{value:.2}");
2297 while s.contains('.') && s.ends_with('0') {
2298 s.pop();
2299 }
2300 if s.ends_with('.') {
2301 s.pop();
2302 }
2303 s
2304}
2305
2306fn center_text(text: &str, width: usize) -> String {
2307 let text_width = UnicodeWidthStr::width(text);
2308 if text_width >= width {
2309 return text.to_string();
2310 }
2311
2312 let total = width - text_width;
2313 let left = total / 2;
2314 let right = total - left;
2315 format!("{}{}{}", " ".repeat(left), text, " ".repeat(right))
2316}
2317
2318struct TextareaVLine {
2319 logical_row: usize,
2320 char_start: usize,
2321 char_count: usize,
2322}
2323
2324fn textarea_build_visual_lines(lines: &[String], wrap_width: u32) -> Vec<TextareaVLine> {
2325 let mut out = Vec::new();
2326 for (row, line) in lines.iter().enumerate() {
2327 if line.is_empty() || wrap_width == u32::MAX {
2328 out.push(TextareaVLine {
2329 logical_row: row,
2330 char_start: 0,
2331 char_count: line.chars().count(),
2332 });
2333 continue;
2334 }
2335 let mut seg_start = 0usize;
2336 let mut seg_chars = 0usize;
2337 let mut seg_width = 0u32;
2338 for (idx, ch) in line.chars().enumerate() {
2339 let cw = UnicodeWidthChar::width(ch).unwrap_or(0) as u32;
2340 if seg_width + cw > wrap_width && seg_chars > 0 {
2341 out.push(TextareaVLine {
2342 logical_row: row,
2343 char_start: seg_start,
2344 char_count: seg_chars,
2345 });
2346 seg_start = idx;
2347 seg_chars = 0;
2348 seg_width = 0;
2349 }
2350 seg_chars += 1;
2351 seg_width += cw;
2352 }
2353 out.push(TextareaVLine {
2354 logical_row: row,
2355 char_start: seg_start,
2356 char_count: seg_chars,
2357 });
2358 }
2359 out
2360}
2361
2362fn textarea_logical_to_visual(
2363 vlines: &[TextareaVLine],
2364 logical_row: usize,
2365 logical_col: usize,
2366) -> (usize, usize) {
2367 for (i, vl) in vlines.iter().enumerate() {
2368 if vl.logical_row != logical_row {
2369 continue;
2370 }
2371 let seg_end = vl.char_start + vl.char_count;
2372 if logical_col >= vl.char_start && logical_col < seg_end {
2373 return (i, logical_col - vl.char_start);
2374 }
2375 if logical_col == seg_end {
2376 let is_last_seg = vlines
2377 .get(i + 1)
2378 .map_or(true, |next| next.logical_row != logical_row);
2379 if is_last_seg {
2380 return (i, logical_col - vl.char_start);
2381 }
2382 }
2383 }
2384 (vlines.len().saturating_sub(1), 0)
2385}
2386
2387fn textarea_visual_to_logical(
2388 vlines: &[TextareaVLine],
2389 visual_row: usize,
2390 visual_col: usize,
2391) -> (usize, usize) {
2392 if let Some(vl) = vlines.get(visual_row) {
2393 let logical_col = vl.char_start + visual_col.min(vl.char_count);
2394 (vl.logical_row, logical_col)
2395 } else {
2396 (0, 0)
2397 }
2398}
2399
2400fn open_url(url: &str) -> std::io::Result<()> {
2401 #[cfg(target_os = "macos")]
2402 {
2403 std::process::Command::new("open").arg(url).spawn()?;
2404 }
2405 #[cfg(target_os = "linux")]
2406 {
2407 std::process::Command::new("xdg-open").arg(url).spawn()?;
2408 }
2409 #[cfg(target_os = "windows")]
2410 {
2411 std::process::Command::new("cmd")
2412 .args(["/c", "start", "", url])
2413 .spawn()?;
2414 }
2415 Ok(())
2416}
2417
2418#[cfg(test)]
2419mod tests {
2420 use super::*;
2421 use crate::test_utils::TestBackend;
2422
2423 #[test]
2424 fn use_memo_type_mismatch_includes_hook_index_and_expected_type() {
2425 let mut state = FrameState::default();
2426 let mut ctx = Context::new(Vec::new(), 20, 5, &mut state, Theme::dark());
2427 ctx.hook_states.push(Box::new(42u32));
2428 ctx.hook_cursor = 0;
2429
2430 let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2431 let deps = 1u8;
2432 let _ = ctx.use_memo(&deps, |_| 7u8);
2433 }))
2434 .expect_err("use_memo should panic on type mismatch");
2435
2436 let message = panic_message(panic);
2437 assert!(
2438 message.contains("use_memo type mismatch at hook index 0"),
2439 "panic message should include hook index, got: {message}"
2440 );
2441 assert!(
2442 message.contains(std::any::type_name::<u8>()),
2443 "panic message should include expected type, got: {message}"
2444 );
2445 }
2446
2447 #[test]
2448 fn light_dark_uses_current_theme_mode() {
2449 let mut dark_backend = TestBackend::new(10, 2);
2450 dark_backend.render(|ui| {
2451 let color = ui.light_dark(Color::Red, Color::Blue);
2452 ui.text("X").fg(color);
2453 });
2454 assert_eq!(dark_backend.buffer().get(0, 0).style.fg, Some(Color::Blue));
2455
2456 let mut light_backend = TestBackend::new(10, 2);
2457 light_backend.render(|ui| {
2458 ui.set_theme(Theme::light());
2459 let color = ui.light_dark(Color::Red, Color::Blue);
2460 ui.text("X").fg(color);
2461 });
2462 assert_eq!(light_backend.buffer().get(0, 0).style.fg, Some(Color::Red));
2463 }
2464
2465 fn panic_message(panic: Box<dyn std::any::Any + Send>) -> String {
2466 if let Some(s) = panic.downcast_ref::<String>() {
2467 s.clone()
2468 } else if let Some(s) = panic.downcast_ref::<&str>() {
2469 (*s).to_string()
2470 } else {
2471 "<non-string panic payload>".to_string()
2472 }
2473 }
2474}