1#![allow(clippy::needless_range_loop)]
4#![forbid(unsafe_code)]
5
6pub mod adaptive_radix;
132pub mod align;
133pub mod badge;
135pub mod block;
137pub mod borders;
138pub mod cached;
139pub mod choreography;
140pub mod columns;
141pub mod command_palette;
142pub mod constraint_overlay;
143#[cfg(feature = "debug-overlay")]
144pub mod debug_overlay;
145pub mod decision_card;
147pub mod diagnostics;
149pub mod drag;
151pub mod drift_visualization;
153pub mod elias_fano;
155pub mod emoji;
156pub mod error_boundary;
157pub mod fenwick;
159pub mod file_picker;
160pub mod focus;
162pub mod group;
163pub mod height_predictor;
165pub mod help;
166pub mod help_registry;
167pub mod hint_ranker;
169pub mod history_panel;
171pub mod input;
172pub mod inspector;
174pub mod json_view;
175pub mod keyboard_drag;
176pub mod layout;
177pub mod layout_debugger;
178pub mod list;
179pub mod log_ring;
180pub mod log_viewer;
181pub mod louds;
182pub mod measurable;
184pub mod measure_cache;
186pub mod modal;
187pub mod mouse;
189pub mod notification_queue;
191pub mod padding;
192pub mod paginator;
193pub mod panel;
194pub mod paragraph;
196pub mod popover;
197pub mod pretty;
198pub mod progress;
199pub mod receipt_verifier_panel;
201pub mod rule;
202pub mod scrollbar;
203pub mod sparkline;
204pub mod spinner;
205pub mod stateful;
207pub mod status_line;
208pub mod stopwatch;
209pub mod table;
211pub mod tabs;
212pub mod textarea;
213pub mod timer;
214pub mod toast;
216pub mod tree;
217pub mod undo_support;
219pub mod validation_error;
221pub mod virtualized;
222pub mod voi_debug_overlay;
223
224pub mod style_names {
226 pub const BLOCK_BORDER_SUFFIX: &str = ".border";
228
229 pub const TABLE_PREFIX: &str = "table";
231
232 pub const TABLE_BORDER: &str = "border";
235 pub const TABLE_HEADER: &str = "header";
237 pub const TABLE_ROW: &str = "row";
239 pub const TABLE_ROW_ALT: &str = "row_alt";
241 pub const TABLE_ROW_SELECTED: &str = "row_selected";
243 pub const TABLE_ROW_HOVER: &str = "row_hover";
245 pub const TABLE_DIVIDER: &str = "divider";
247}
248
249#[cfg(all(test, feature = "tracing"))]
250pub(crate) mod tracing_test_support {
251 use std::sync::{Mutex, MutexGuard, OnceLock};
252
253 pub(crate) struct TraceTestGuard {
256 _lock: MutexGuard<'static, ()>,
257 }
258
259 impl Drop for TraceTestGuard {
260 fn drop(&mut self) {
261 tracing::callsite::rebuild_interest_cache();
262 }
263 }
264
265 pub(crate) fn acquire() -> TraceTestGuard {
266 static TRACE_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
267
268 let lock = TRACE_TEST_LOCK
270 .get_or_init(|| Mutex::new(()))
271 .lock()
272 .unwrap_or_else(|e| e.into_inner());
273 tracing::callsite::rebuild_interest_cache();
274 TraceTestGuard { _lock: lock }
275 }
276}
277
278pub use align::{Align, VerticalAlignment};
279pub use badge::Badge;
280pub use cached::{CacheKey, CachedWidget, CachedWidgetState, FnKey, HashKey, NoCacheKey};
281pub use columns::{Column, Columns};
282pub use constraint_overlay::{ConstraintOverlay, ConstraintOverlayStyle};
283#[cfg(feature = "debug-overlay")]
284pub use debug_overlay::{
285 DebugOverlay, DebugOverlayOptions, DebugOverlayState, DebugOverlayStateful,
286 DebugOverlayStatefulState,
287};
288pub use decision_card::DecisionCard;
289pub use ftui_style::StyleSheet;
290pub use group::Group;
291pub use help_registry::{HelpContent, HelpId, HelpRegistry, Keybinding};
292pub use history_panel::{HistoryEntry, HistoryPanel, HistoryPanelMode};
293pub use layout_debugger::{LayoutConstraints, LayoutDebugger, LayoutRecord};
294pub use log_ring::LogRing;
295pub use log_viewer::{LogViewer, LogViewerState, LogWrapMode, SearchConfig, SearchMode};
296pub use paginator::{Paginator, PaginatorMode};
297pub use panel::Panel;
298pub use sparkline::{Sparkline, SparklineMarkers};
299pub use status_line::{StatusItem, StatusLine};
300pub use table::{ColumnSpec, Row, Table, TableState, Truncate};
301pub use tabs::{Tab, Tabs, TabsState};
302pub use virtualized::{
303 HeightCache, ItemHeight, RenderItem, Virtualized, VirtualizedList, VirtualizedListState,
304 VirtualizedStorage,
305};
306pub use voi_debug_overlay::{
307 VoiDebugOverlay, VoiDecisionSummary, VoiLedgerEntry, VoiObservationSummary, VoiOverlayData,
308 VoiOverlayStyle, VoiPosteriorSummary,
309};
310
311pub use toast::{
313 KeyEvent as ToastKeyEvent, Toast, ToastAction, ToastAnimationConfig, ToastAnimationPhase,
314 ToastAnimationState, ToastConfig, ToastContent, ToastEasing, ToastEntranceAnimation,
315 ToastEvent, ToastExitAnimation, ToastIcon, ToastId, ToastPosition, ToastState, ToastStyle,
316};
317
318pub use notification_queue::{
320 NotificationPriority, NotificationQueue, QueueAction, QueueConfig, QueueStats,
321};
322
323pub use ftui_a11y::Accessible;
325
326pub use mouse::MouseResult;
328
329pub use measurable::{MeasurableWidget, SizeConstraints};
331
332pub use measure_cache::{CacheStats, MeasureCache, WidgetId};
334pub use modal::{
335 BackdropConfig, MODAL_HIT_BACKDROP, MODAL_HIT_CONTENT, Modal, ModalAction, ModalConfig,
336 ModalPosition, ModalSizeConstraints, ModalState,
337};
338
339pub use inspector::{
341 DiagnosticEntry, DiagnosticEventKind, DiagnosticLog, HitInfo, InspectorMode, InspectorOverlay,
342 InspectorState, InspectorStyle, TelemetryCallback, TelemetryHooks, WidgetInfo,
343 diagnostics_enabled, init_diagnostics, is_deterministic_mode, reset_event_counter,
344 set_diagnostics_enabled,
345};
346
347pub use focus::{
349 FocusEvent, FocusGraph, FocusGroup, FocusId, FocusIndicator, FocusIndicatorKind, FocusManager,
350 FocusNode, FocusTrap, NavDirection,
351};
352
353pub use drag::{DragPayload, DragState, Draggable, DropPosition, DropResult, DropTarget};
355
356pub use stateful::{StateKey, Stateful, VersionedState};
358
359pub use list::ListPersistState;
361pub use table::TablePersistState;
362pub use tree::TreePersistState;
363pub use virtualized::VirtualizedListPersistState;
364
365pub use undo_support::{
367 ListOperation, ListUndoExt, SelectionOperation, TableOperation, TableUndoExt,
368 TextEditOperation, TextInputUndoExt, TreeOperation, TreeUndoExt, UndoSupport, UndoWidgetId,
369 WidgetTextEditCmd,
370};
371
372pub use validation_error::{
374 ANIMATION_DURATION_MS, ERROR_BG_DEFAULT, ERROR_FG_DEFAULT, ERROR_ICON_DEFAULT,
375 ValidationErrorDisplay, ValidationErrorState,
376};
377
378use ftui_core::geometry::Rect;
379use ftui_render::buffer::Buffer;
380use ftui_render::cell::Cell;
381use ftui_render::frame::{Frame, WidgetSignal};
382use ftui_style::Style;
383use ftui_text::grapheme_width;
384
385pub(crate) fn render_block_without_a11y(block: &block::Block<'_>, area: Rect, frame: &mut Frame) {
407 if !frame.a11y_enabled() {
408 block.render(area, frame);
409 return;
410 }
411 let builder = frame.a11y.take();
412 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
413 block.render(area, frame);
414 }));
415 frame.a11y = builder;
416 if let Err(payload) = result {
417 std::panic::resume_unwind(payload);
418 }
419}
420
421#[must_use]
430pub(crate) fn a11y_node_id(area: Rect) -> u64 {
431 const FNV_OFFSET: u64 = 14_695_981_039_346_656_037;
433 const FNV_PRIME: u64 = 1_099_511_628_211;
434 let mut h = FNV_OFFSET;
435 for byte in area
436 .x
437 .to_le_bytes()
438 .iter()
439 .chain(&area.y.to_le_bytes())
440 .chain(&area.width.to_le_bytes())
441 .chain(&area.height.to_le_bytes())
442 {
443 h ^= u64::from(*byte);
444 h = h.wrapping_mul(FNV_PRIME);
445 }
446 h
447}
448
449pub trait Widget {
489 fn render(&self, area: Rect, frame: &mut Frame);
495
496 fn is_essential(&self) -> bool {
507 false
508 }
509}
510
511pub trait FrameExt {
518 fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect);
520
521 fn render_stateful_widget<W: StatefulWidget + ?Sized>(
524 &mut self,
525 widget: &W,
526 area: Rect,
527 state: &mut W::State,
528 );
529}
530
531impl FrameExt for Frame<'_> {
532 #[inline]
533 fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect) {
534 widget.render(area, self);
535 }
536
537 #[inline]
538 fn render_stateful_widget<W: StatefulWidget + ?Sized>(
539 &mut self,
540 widget: &W,
541 area: Rect,
542 state: &mut W::State,
543 ) {
544 widget.render(area, self, state);
545 }
546}
547
548pub struct Budgeted<W> {
550 widget_id: u64,
551 signal: WidgetSignal,
552 inner: W,
553}
554
555impl<W> Budgeted<W> {
556 #[must_use]
558 pub fn new(widget_id: u64, inner: W) -> Self {
559 Self {
560 widget_id,
561 signal: WidgetSignal::new(widget_id),
562 inner,
563 }
564 }
565
566 #[must_use]
568 pub fn with_signal(mut self, mut signal: WidgetSignal) -> Self {
569 signal.widget_id = self.widget_id;
570 self.signal = signal;
571 self
572 }
573
574 #[must_use]
576 pub fn inner(&self) -> &W {
577 &self.inner
578 }
579}
580
581impl<W: Widget> Widget for Budgeted<W> {
582 fn render(&self, area: Rect, frame: &mut Frame) {
583 let mut signal = self.signal.clone();
584 signal.widget_id = self.widget_id;
585 signal.essential = self.inner.is_essential();
586 signal.area_cells = area.width as u32 * area.height as u32;
587 frame.register_widget_signal(signal);
588
589 if frame.should_render_budgeted_widget(self.widget_id, self.inner.is_essential()) {
590 self.inner.render(area, frame);
591 }
592 }
593
594 fn is_essential(&self) -> bool {
595 self.inner.is_essential()
596 }
597}
598
599impl<W: StatefulWidget + Widget> StatefulWidget for Budgeted<W> {
600 type State = W::State;
601
602 fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
603 let mut signal = self.signal.clone();
604 signal.widget_id = self.widget_id;
605 signal.essential = self.inner.is_essential();
606 signal.area_cells = area.width as u32 * area.height as u32;
607 frame.register_widget_signal(signal);
608
609 if frame.should_render_budgeted_widget(self.widget_id, self.inner.is_essential()) {
610 StatefulWidget::render(&self.inner, area, frame, state);
611 }
612 }
613}
614
615pub trait StatefulWidget {
652 type State;
654
655 fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State);
662}
663
664pub(crate) fn apply_style(cell: &mut Cell, style: Style) {
671 if let Some(fg) = style.fg {
672 cell.fg = fg;
673 }
674 if let Some(bg) = style.bg {
675 match bg.a() {
676 0 => {} 255 => cell.bg = bg, _ => cell.bg = bg.over(cell.bg), }
680 }
681 if let Some(attrs) = style.attrs {
682 let cell_flags: ftui_render::cell::StyleFlags = attrs.into();
683 cell.attrs = cell.attrs.merged_flags(cell_flags);
684 }
685}
686
687pub(crate) fn set_style_area(buf: &mut Buffer, area: Rect, style: Style) {
697 if style.is_empty() {
698 return;
699 }
700 let clipped = area.intersection(&buf.current_scissor());
701 if clipped.is_empty() {
702 return;
703 }
704
705 let opacity = buf.current_opacity();
706 let fg = style.fg.map(|fg| fg.with_opacity(opacity));
707 let bg = style.bg.map(|bg| bg.with_opacity(opacity));
708 let attrs = style.attrs.map(ftui_render::cell::StyleFlags::from);
709 for y in clipped.y..clipped.bottom() {
710 let Some(row) = buf.row_cells_mut_span(y, clipped.x, clipped.right()) else {
711 continue;
712 };
713 for cell in row {
714 if let Some(fg) = fg {
715 cell.fg = fg;
716 }
717 if let Some(bg) = bg {
718 match bg.a() {
719 0 => {} 255 => cell.bg = bg, _ => cell.bg = bg.over(cell.bg), }
723 }
724 if let Some(attrs) = attrs {
725 cell.attrs = cell.attrs.merged_flags(attrs);
726 }
727 }
728 }
729}
730
731pub(crate) fn clear_text_area(frame: &mut Frame, area: Rect, style: Style) {
733 if area.width == 0 || area.height == 0 {
734 return;
735 }
736
737 let mut cell = Cell::from_char(' ');
738 apply_style(&mut cell, style);
739 frame.buffer.fill(area, cell);
740}
741
742pub(crate) fn clear_text_row(frame: &mut Frame, area: Rect, style: Style) {
744 clear_text_area(frame, Rect::new(area.x, area.y, area.width, 1), style);
745}
746
747fn inherited_text_cell(
753 frame: &Frame,
754 x: u16,
755 y: u16,
756 content: ftui_render::cell::CellContent,
757) -> Cell {
758 let mut cell = frame.buffer.get(x, y).copied().unwrap_or_default();
759 cell.content = content;
760 cell.attrs = ftui_render::cell::CellAttrs::new(cell.attrs.flags(), 0);
761 cell
762}
763
764pub(crate) fn draw_text_span(
769 frame: &mut Frame,
770 mut x: u16,
771 y: u16,
772 content: &str,
773 style: Style,
774 max_x: u16,
775) -> u16 {
776 use unicode_segmentation::UnicodeSegmentation;
777
778 for grapheme in content.graphemes(true) {
779 if x >= max_x {
780 break;
781 }
782 let w = grapheme_width(grapheme);
783 if w == 0 {
784 continue;
785 }
786 if x.saturating_add(w as u16) > max_x {
787 break;
788 }
789
790 let cell_content = if w > 1 || grapheme.chars().count() > 1 {
792 let id = frame.intern_with_width(grapheme, w as u8);
793 ftui_render::cell::CellContent::from_grapheme(id)
794 } else if let Some(c) = grapheme.chars().next() {
795 ftui_render::cell::CellContent::from_char(c)
796 } else {
797 continue;
798 };
799
800 let mut cell = inherited_text_cell(frame, x, y, cell_content);
801 apply_style(&mut cell, style);
802
803 frame.buffer.set_fast(x, y, cell);
806
807 x = x.saturating_add(w as u16);
808 }
809 x
810}
811
812#[allow(dead_code)]
814pub(crate) fn draw_text_span_with_link(
815 frame: &mut Frame,
816 x: u16,
817 y: u16,
818 content: &str,
819 style: Style,
820 max_x: u16,
821 link_url: Option<&str>,
822) -> u16 {
823 draw_text_span_scrolled(frame, x, y, content, style, max_x, 0, link_url)
824}
825
826#[allow(dead_code, clippy::too_many_arguments)]
828pub(crate) fn draw_text_span_scrolled(
829 frame: &mut Frame,
830 mut x: u16,
831 y: u16,
832 content: &str,
833 style: Style,
834 max_x: u16,
835 scroll_x: u16,
836 link_url: Option<&str>,
837) -> u16 {
838 use unicode_segmentation::UnicodeSegmentation;
839
840 let link_id = if let Some(url) = link_url {
842 frame.register_link(url)
843 } else {
844 0
845 };
846
847 let scroll_x = usize::from(scroll_x);
849 let mut visual_pos: usize = 0;
850
851 for grapheme in content.graphemes(true) {
852 if x >= max_x {
853 break;
854 }
855 let w = grapheme_width(grapheme);
856 if w == 0 {
857 continue;
858 }
859
860 let next_visual_pos = visual_pos.saturating_add(w);
861
862 if next_visual_pos <= scroll_x {
864 visual_pos = next_visual_pos;
866 continue;
867 }
868
869 if visual_pos < scroll_x {
870 visual_pos = next_visual_pos;
873 continue;
874 }
875
876 if x.saturating_add(w as u16) > max_x {
877 break;
878 }
879
880 let cell_content = if w > 1 || grapheme.chars().count() > 1 {
882 let id = frame.intern_with_width(grapheme, w as u8);
883 ftui_render::cell::CellContent::from_grapheme(id)
884 } else if let Some(c) = grapheme.chars().next() {
885 ftui_render::cell::CellContent::from_char(c)
886 } else {
887 continue;
888 };
889
890 let mut cell = inherited_text_cell(frame, x, y, cell_content);
891 apply_style(&mut cell, style);
892
893 if link_id != 0 {
895 cell.attrs = cell.attrs.with_link(link_id);
896 }
897
898 frame.buffer.set_fast(x, y, cell);
899
900 x = x.saturating_add(w as u16);
901 visual_pos = next_visual_pos;
902 }
903 x
904}
905
906pub(crate) fn contains_ignore_case(haystack: &str, needle_lower: &str) -> bool {
908 if needle_lower.is_empty() {
909 return true;
910 }
911 if haystack.is_ascii() && needle_lower.is_ascii() {
913 let haystack_bytes = haystack.as_bytes();
914 let needle_bytes = needle_lower.as_bytes();
915 if needle_bytes.len() > haystack_bytes.len() {
916 return false;
917 }
918 for i in 0..=haystack_bytes.len() - needle_bytes.len() {
920 let mut match_found = true;
921 for (j, &b) in needle_bytes.iter().enumerate() {
922 if haystack_bytes[i + j].to_ascii_lowercase() != b {
923 match_found = false;
924 break;
925 }
926 }
927 if match_found {
928 return true;
929 }
930 }
931 return false;
932 }
933 haystack.to_lowercase().contains(needle_lower)
935}
936
937#[cfg(test)]
938mod tests {
939 use super::*;
940 use ftui_render::cell::PackedRgba;
941 use ftui_render::grapheme_pool::GraphemePool;
942
943 #[test]
946 fn frame_ext_render_widget_matches_direct_render() {
947 struct Fill(char);
948 impl Widget for Fill {
949 fn render(&self, area: Rect, frame: &mut Frame) {
950 for y in area.y..area.y + area.height {
951 for x in area.x..area.x + area.width {
952 frame.buffer.set_raw(x, y, Cell::from_char(self.0));
953 }
954 }
955 }
956 }
957
958 let mut pool_a = GraphemePool::new();
959 let mut direct = Frame::new(6, 2, &mut pool_a);
960 Fill('d').render(Rect::new(1, 0, 3, 2), &mut direct);
961
962 let mut pool_b = GraphemePool::new();
963 let mut via_ext = Frame::new(6, 2, &mut pool_b);
964 via_ext.render_widget(&Fill('d'), Rect::new(1, 0, 3, 2));
965 assert_eq!(via_ext.area(), Rect::new(0, 0, 6, 2));
966
967 for y in 0..2 {
968 for x in 0..6 {
969 assert_eq!(
970 direct.buffer.get(x, y).map(|cell| cell.content),
971 via_ext.buffer.get(x, y).map(|cell| cell.content),
972 "cell ({x},{y}) differs between direct render and FrameExt"
973 );
974 }
975 }
976 assert_eq!(
977 via_ext.buffer.get(1, 0).map(|cell| cell.content),
978 Some(Cell::from_char('d').content)
979 );
980 assert_eq!(
981 via_ext.buffer.get(0, 0).map(|cell| cell.content),
982 Some(Cell::default().content)
983 );
984 }
985
986 #[test]
991 fn rendering_accessible_widgets_pushes_their_nodes_into_the_frame() {
992 use crate::block::Block;
993 use crate::list::{List, ListState};
994 use crate::paragraph::Paragraph;
995 use ftui_a11y::node::A11yRole;
996 use ftui_a11y::tree::A11yTreeBuilder;
997
998 let mut pool = GraphemePool::new();
999 let mut builder = A11yTreeBuilder::new();
1000 let mut frame = Frame::new(30, 8, &mut pool);
1001 frame.set_a11y(&mut builder);
1002
1003 let mut list_state = ListState::default();
1004 let list = List::new(["alpha", "beta"]);
1005 StatefulWidget::render(&list, Rect::new(0, 0, 30, 3), &mut frame, &mut list_state);
1006 Block::new()
1007 .title("Details")
1008 .render(Rect::new(0, 3, 30, 3), &mut frame);
1009 Paragraph::new("hello").render(Rect::new(0, 6, 30, 1), &mut frame);
1010 frame.finish_a11y();
1011 let order = frame.take_a11y_order();
1012 drop(frame);
1013
1014 let tree = builder.build();
1015 assert_eq!(order.len(), tree.node_count());
1016 assert!(
1017 order.len() >= 5,
1018 "list + 2 items + block + paragraph: {order:?}"
1019 );
1020 let roles: Vec<A11yRole> = order
1021 .iter()
1022 .filter_map(|id| tree.node(*id).map(|n| n.role))
1023 .collect();
1024 assert_eq!(roles[0], A11yRole::List);
1025 assert_eq!(roles[1], A11yRole::ListItem);
1026 assert_eq!(roles[2], A11yRole::ListItem);
1027 assert!(roles.contains(&A11yRole::Group), "{roles:?}");
1028 let list_id = order[0];
1029 assert_eq!(
1030 tree.node(list_id).map(|n| n.children.len()),
1031 Some(2),
1032 "list items are the list's children"
1033 );
1034 assert_eq!(
1035 tree.root_id(),
1036 Some(list_id),
1037 "first parentless node is the root"
1038 );
1039 let text = tree.dump_text(&order);
1040 assert!(text.contains("ListItem \"alpha\""), "{text}");
1041 assert!(text.contains("Group \"Details\""), "{text}");
1042
1043 let mut pool = GraphemePool::new();
1045 let mut frame = Frame::new(30, 8, &mut pool);
1046 Paragraph::new("hello").render(Rect::new(0, 0, 30, 1), &mut frame);
1047 assert!(frame.a11y_order().is_empty());
1048 }
1049
1050 #[test]
1052 fn frame_ext_render_stateful_widget_passes_state() {
1053 struct Counter;
1054 impl StatefulWidget for Counter {
1055 type State = u32;
1056 fn render(&self, _area: Rect, _frame: &mut Frame, state: &mut u32) {
1057 *state += 1;
1058 }
1059 }
1060 let mut pool = GraphemePool::new();
1061 let mut frame = Frame::new(4, 1, &mut pool);
1062 let mut count = 0;
1063 frame.render_stateful_widget(&Counter, frame.area(), &mut count);
1064 frame.render_stateful_widget(&Counter, Rect::new(0, 0, 1, 1), &mut count);
1065 assert_eq!(count, 2);
1066 }
1067
1068 #[test]
1069 fn apply_style_sets_fg() {
1070 let mut cell = Cell::default();
1071 let style = Style::new().fg(PackedRgba::rgb(255, 0, 0));
1072 apply_style(&mut cell, style);
1073 assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
1074 }
1075
1076 #[test]
1077 fn apply_style_sets_bg() {
1078 let mut cell = Cell::default();
1079 let style = Style::new().bg(PackedRgba::rgb(0, 255, 0));
1080 apply_style(&mut cell, style);
1081 assert_eq!(cell.bg, PackedRgba::rgb(0, 255, 0));
1082 }
1083
1084 #[test]
1085 fn apply_style_preserves_content() {
1086 let mut cell = Cell::from_char('Z');
1087 let style = Style::new().fg(PackedRgba::rgb(1, 2, 3));
1088 apply_style(&mut cell, style);
1089 assert_eq!(cell.content.as_char(), Some('Z'));
1090 }
1091
1092 #[test]
1093 fn apply_style_empty_is_noop() {
1094 let original = Cell::default();
1095 let mut cell = Cell::default();
1096 apply_style(&mut cell, Style::default());
1097 assert_eq!(cell.fg, original.fg);
1098 assert_eq!(cell.bg, original.bg);
1099 }
1100
1101 #[test]
1102 fn apply_style_bg_only_preserves_fg() {
1103 let mut cell = Cell::from_char('x').with_fg(PackedRgba::rgb(0, 200, 0));
1105 let selection = Style::new().bg(PackedRgba::rgb(0, 0, 180));
1106 apply_style(&mut cell, selection);
1107 assert_eq!(cell.fg, PackedRgba::rgb(0, 200, 0));
1109 assert_eq!(cell.bg, PackedRgba::rgb(0, 0, 180));
1110 }
1111
1112 #[test]
1113 fn apply_style_composites_alpha_bg() {
1114 let base_bg = PackedRgba::rgb(200, 0, 0);
1115 let mut cell = Cell::default().with_bg(base_bg);
1116 let overlay = PackedRgba::rgba(0, 0, 200, 128);
1117 apply_style(&mut cell, Style::new().bg(overlay));
1118 assert_eq!(cell.bg, overlay.over(base_bg));
1119 }
1120
1121 #[test]
1122 fn apply_style_transparent_bg_is_noop() {
1123 let base_bg = PackedRgba::rgb(100, 100, 100);
1124 let mut cell = Cell::default().with_bg(base_bg);
1125 apply_style(&mut cell, Style::new().bg(PackedRgba::rgba(255, 0, 0, 0)));
1126 assert_eq!(cell.bg, base_bg);
1127 }
1128
1129 #[test]
1130 fn apply_style_merges_attrs_not_replaces() {
1131 use ftui_render::cell::StyleFlags as CellFlags;
1132 let mut cell = Cell::default();
1134 cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1135 let overlay = Style::new().italic();
1137 apply_style(&mut cell, overlay);
1138 assert!(cell.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1139 assert!(
1140 cell.attrs.has_flag(CellFlags::ITALIC),
1141 "ITALIC must be added"
1142 );
1143 }
1144
1145 #[test]
1146 fn set_style_area_bg_only_preserves_per_cell_fg() {
1147 let mut buf = Buffer::new(3, 1);
1149 buf.set(0, 0, Cell::from_char('R').with_fg(PackedRgba::RED));
1150 buf.set(1, 0, Cell::from_char('G').with_fg(PackedRgba::GREEN));
1151 buf.set(2, 0, Cell::from_char('B').with_fg(PackedRgba::BLUE));
1152
1153 let highlight = Style::new().bg(PackedRgba::rgb(40, 40, 40));
1155 set_style_area(&mut buf, Rect::new(0, 0, 3, 1), highlight);
1156
1157 assert_eq!(buf.get(0, 0).unwrap().fg, PackedRgba::RED);
1159 assert_eq!(buf.get(1, 0).unwrap().fg, PackedRgba::GREEN);
1160 assert_eq!(buf.get(2, 0).unwrap().fg, PackedRgba::BLUE);
1161 assert_eq!(buf.get(0, 0).unwrap().bg, PackedRgba::rgb(40, 40, 40));
1163 }
1164
1165 #[test]
1166 fn set_style_area_merges_attrs_not_replaces() {
1167 use ftui_render::cell::StyleFlags as CellFlags;
1168 let mut buf = Buffer::new(1, 1);
1169 let mut cell = Cell::from_char('X');
1170 cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1171 buf.set(0, 0, cell);
1172
1173 set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().italic());
1174
1175 let result = buf.get(0, 0).unwrap();
1176 assert!(result.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1177 assert!(
1178 result.attrs.has_flag(CellFlags::ITALIC),
1179 "ITALIC must be added"
1180 );
1181 }
1182
1183 #[test]
1184 fn set_style_area_applies_to_all_cells() {
1185 let mut buf = Buffer::new(3, 2);
1186 let area = Rect::new(0, 0, 3, 2);
1187 let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1188 set_style_area(&mut buf, area, style);
1189
1190 for y in 0..2 {
1191 for x in 0..3 {
1192 assert_eq!(
1193 buf.get(x, y).unwrap().bg,
1194 PackedRgba::rgb(10, 20, 30),
1195 "cell ({x},{y}) should have style applied"
1196 );
1197 }
1198 }
1199 }
1200
1201 #[test]
1202 fn set_style_area_composites_alpha_bg_over_existing_bg() {
1203 let mut buf = Buffer::new(1, 1);
1204 let base = PackedRgba::rgb(200, 0, 0);
1205 buf.set(0, 0, Cell::default().with_bg(base));
1206
1207 let overlay = PackedRgba::rgba(0, 0, 200, 128);
1208 set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(overlay));
1209
1210 let expected = overlay.over(base);
1211 assert_eq!(buf.get(0, 0).unwrap().bg, expected);
1212 }
1213
1214 #[test]
1215 fn set_style_area_partial_rect() {
1216 let mut buf = Buffer::new(5, 5);
1217 let area = Rect::new(1, 1, 2, 2);
1218 let style = Style::new().fg(PackedRgba::rgb(99, 99, 99));
1219 set_style_area(&mut buf, area, style);
1220
1221 assert_eq!(buf.get(1, 1).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1223 assert_eq!(buf.get(2, 2).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1224
1225 assert_ne!(buf.get(0, 0).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1227 }
1228
1229 #[test]
1230 fn set_style_area_empty_style_is_noop() {
1231 let mut buf = Buffer::new(3, 3);
1232 buf.set(0, 0, Cell::from_char('A'));
1233 let original_fg = buf.get(0, 0).unwrap().fg;
1234
1235 set_style_area(&mut buf, Rect::new(0, 0, 3, 3), Style::default());
1236
1237 assert_eq!(buf.get(0, 0).unwrap().fg, original_fg);
1239 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
1240 }
1241
1242 #[test]
1243 fn set_style_area_respects_scissor() {
1244 let mut buf = Buffer::new(3, 3);
1245 let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1246
1247 buf.push_scissor(Rect::new(1, 1, 1, 1));
1248 set_style_area(&mut buf, Rect::new(0, 0, 3, 3), style);
1249
1250 assert_eq!(buf.get(1, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1251 assert_ne!(buf.get(0, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1252 assert_ne!(buf.get(1, 0).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1253 assert_ne!(buf.get(2, 2).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1254 }
1255
1256 #[test]
1257 fn set_style_area_respects_opacity_stack() {
1258 let mut buf = Buffer::new(1, 1);
1259 let base_fg = PackedRgba::rgb(20, 30, 40);
1260 let base_bg = PackedRgba::rgb(50, 60, 70);
1261 buf.set(0, 0, Cell::from_char('X').with_fg(base_fg).with_bg(base_bg));
1262
1263 let overlay_fg = PackedRgba::rgb(200, 100, 0);
1264 let overlay_bg = PackedRgba::rgb(0, 0, 200);
1265 buf.push_opacity(0.5);
1266 set_style_area(
1267 &mut buf,
1268 Rect::new(0, 0, 1, 1),
1269 Style::new().fg(overlay_fg).bg(overlay_bg),
1270 );
1271
1272 let cell = buf.get(0, 0).unwrap();
1273 assert_eq!(cell.fg, overlay_fg.with_opacity(0.5));
1274 assert_eq!(cell.bg, overlay_bg.with_opacity(0.5).over(base_bg));
1275 }
1276
1277 #[test]
1278 fn draw_text_span_basic() {
1279 let mut pool = GraphemePool::new();
1280 let mut frame = Frame::new(10, 1, &mut pool);
1281 let end_x = draw_text_span(&mut frame, 0, 0, "ABC", Style::default(), 10);
1282
1283 assert_eq!(end_x, 3);
1284 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1285 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
1286 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1287 }
1288
1289 #[test]
1290 fn draw_text_span_clipped_at_max_x() {
1291 let mut pool = GraphemePool::new();
1292 let mut frame = Frame::new(10, 1, &mut pool);
1293 let end_x = draw_text_span(&mut frame, 0, 0, "ABCDEF", Style::default(), 3);
1294
1295 assert_eq!(end_x, 3);
1296 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1297 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1298 assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1300 }
1301
1302 #[test]
1303 fn draw_text_span_starts_at_offset() {
1304 let mut pool = GraphemePool::new();
1305 let mut frame = Frame::new(10, 1, &mut pool);
1306 let end_x = draw_text_span(&mut frame, 5, 0, "XY", Style::default(), 10);
1307
1308 assert_eq!(end_x, 7);
1309 assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('X'));
1310 assert_eq!(frame.buffer.get(6, 0).unwrap().content.as_char(), Some('Y'));
1311 assert!(frame.buffer.get(4, 0).unwrap().is_empty());
1312 }
1313
1314 #[test]
1315 fn draw_text_span_empty_string() {
1316 let mut pool = GraphemePool::new();
1317 let mut frame = Frame::new(5, 1, &mut pool);
1318 let end_x = draw_text_span(&mut frame, 0, 0, "", Style::default(), 5);
1319 assert_eq!(end_x, 0);
1320 }
1321
1322 #[test]
1323 fn draw_text_span_applies_style() {
1324 let mut pool = GraphemePool::new();
1325 let mut frame = Frame::new(5, 1, &mut pool);
1326 let style = Style::new().fg(PackedRgba::rgb(255, 128, 0));
1327 draw_text_span(&mut frame, 0, 0, "A", style, 5);
1328
1329 assert_eq!(
1330 frame.buffer.get(0, 0).unwrap().fg,
1331 PackedRgba::rgb(255, 128, 0)
1332 );
1333 }
1334
1335 #[test]
1336 fn draw_text_span_preserves_existing_overlay_fg_and_bg() {
1337 let mut pool = GraphemePool::new();
1338 let mut frame = Frame::new(3, 1, &mut pool);
1339 frame.buffer.set(
1340 0,
1341 0,
1342 Cell::from_char('x').with_fg(PackedRgba::rgb(200, 40, 10)),
1343 );
1344 set_style_area(
1345 &mut frame.buffer,
1346 Rect::new(0, 0, 1, 1),
1347 Style::new().bg(PackedRgba::rgb(20, 30, 40)),
1348 );
1349
1350 draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1351
1352 let cell = frame.buffer.get(0, 0).unwrap();
1353 assert_eq!(cell.content.as_char(), Some('A'));
1354 assert_eq!(cell.fg, PackedRgba::rgb(200, 40, 10));
1355 assert_eq!(cell.bg, PackedRgba::rgb(20, 30, 40));
1356 }
1357
1358 #[test]
1359 fn draw_text_span_drops_stale_link_id_but_keeps_style_flags() {
1360 use ftui_render::cell::{CellAttrs, StyleFlags as CellFlags};
1361
1362 let mut pool = GraphemePool::new();
1363 let mut frame = Frame::new(3, 1, &mut pool);
1364 frame.buffer.set(
1365 0,
1366 0,
1367 Cell::from_char('x').with_attrs(CellAttrs::new(CellFlags::UNDERLINE, 42)),
1368 );
1369
1370 draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1371
1372 let cell = frame.buffer.get(0, 0).unwrap();
1373 assert_eq!(cell.content.as_char(), Some('A'));
1374 assert!(cell.attrs.has_flag(CellFlags::UNDERLINE));
1375 assert_eq!(cell.attrs.link_id(), 0);
1376 }
1377
1378 #[test]
1379 fn draw_text_span_max_x_at_start_draws_nothing() {
1380 let mut pool = GraphemePool::new();
1381 let mut frame = Frame::new(5, 1, &mut pool);
1382 let end_x = draw_text_span(&mut frame, 3, 0, "ABC", Style::default(), 3);
1383 assert_eq!(end_x, 3);
1384 assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1385 }
1386
1387 #[test]
1388 fn widget_is_essential_default_false() {
1389 struct DummyWidget;
1390 impl Widget for DummyWidget {
1391 fn render(&self, _: Rect, _: &mut Frame) {}
1392 }
1393 assert!(!DummyWidget.is_essential());
1394 }
1395
1396 #[test]
1397 fn budgeted_new_and_inner() {
1398 struct TestW;
1399 impl Widget for TestW {
1400 fn render(&self, _: Rect, _: &mut Frame) {}
1401 }
1402 let b = Budgeted::new(42, TestW);
1403 assert_eq!(b.widget_id, 42);
1404 let _ = b.inner(); }
1406
1407 #[test]
1408 fn budgeted_with_signal() {
1409 struct TestW;
1410 impl Widget for TestW {
1411 fn render(&self, _: Rect, _: &mut Frame) {}
1412 }
1413 let sig = WidgetSignal::new(99);
1414 let b = Budgeted::new(42, TestW).with_signal(sig);
1415 assert_eq!(b.signal.widget_id, 42);
1417 }
1418
1419 #[test]
1420 fn set_style_area_transparent_bg_is_noop() {
1421 let mut buf = Buffer::new(1, 1);
1422 let base = PackedRgba::rgb(100, 100, 100);
1423 buf.set(0, 0, Cell::default().with_bg(base));
1424
1425 let transparent = PackedRgba::rgba(255, 0, 0, 0);
1427 set_style_area(
1428 &mut buf,
1429 Rect::new(0, 0, 1, 1),
1430 Style::new().bg(transparent),
1431 );
1432 assert_eq!(buf.get(0, 0).unwrap().bg, base);
1433 }
1434
1435 #[test]
1436 fn set_style_area_opaque_bg_replaces() {
1437 let mut buf = Buffer::new(1, 1);
1438 buf.set(
1439 0,
1440 0,
1441 Cell::default().with_bg(PackedRgba::rgb(100, 100, 100)),
1442 );
1443
1444 let opaque = PackedRgba::rgba(0, 255, 0, 255);
1445 set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(opaque));
1446 assert_eq!(buf.get(0, 0).unwrap().bg, opaque);
1447 }
1448
1449 #[test]
1450 fn draw_text_span_scrolled_skips_chars() {
1451 let mut pool = GraphemePool::new();
1452 let mut frame = Frame::new(10, 1, &mut pool);
1453 let end_x =
1455 draw_text_span_scrolled(&mut frame, 0, 0, "ABCDE", Style::default(), 10, 2, None);
1456
1457 assert_eq!(end_x, 3);
1458 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('C'));
1459 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('D'));
1460 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('E'));
1461 }
1462}