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
224#[cfg(all(test, feature = "tracing"))]
225pub(crate) mod tracing_test_support {
226 use std::sync::{Mutex, MutexGuard, OnceLock};
227
228 pub(crate) struct TraceTestGuard {
231 _lock: MutexGuard<'static, ()>,
232 }
233
234 impl Drop for TraceTestGuard {
235 fn drop(&mut self) {
236 tracing::callsite::rebuild_interest_cache();
237 }
238 }
239
240 pub(crate) fn acquire() -> TraceTestGuard {
241 static TRACE_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
242
243 let lock = TRACE_TEST_LOCK
245 .get_or_init(|| Mutex::new(()))
246 .lock()
247 .unwrap_or_else(|e| e.into_inner());
248 tracing::callsite::rebuild_interest_cache();
249 TraceTestGuard { _lock: lock }
250 }
251}
252
253pub use align::{Align, VerticalAlignment};
254pub use badge::Badge;
255pub use cached::{CacheKey, CachedWidget, CachedWidgetState, FnKey, HashKey, NoCacheKey};
256pub use columns::{Column, Columns};
257pub use constraint_overlay::{ConstraintOverlay, ConstraintOverlayStyle};
258#[cfg(feature = "debug-overlay")]
259pub use debug_overlay::{
260 DebugOverlay, DebugOverlayOptions, DebugOverlayState, DebugOverlayStateful,
261 DebugOverlayStatefulState,
262};
263pub use decision_card::DecisionCard;
264pub use group::Group;
265pub use help_registry::{HelpContent, HelpId, HelpRegistry, Keybinding};
266pub use history_panel::{HistoryEntry, HistoryPanel, HistoryPanelMode};
267pub use layout_debugger::{LayoutConstraints, LayoutDebugger, LayoutRecord};
268pub use log_ring::LogRing;
269pub use log_viewer::{LogViewer, LogViewerState, LogWrapMode, SearchConfig, SearchMode};
270pub use paginator::{Paginator, PaginatorMode};
271pub use panel::Panel;
272pub use sparkline::{Sparkline, SparklineMarkers};
273pub use status_line::{StatusItem, StatusLine};
274pub use tabs::{Tab, Tabs, TabsState};
275pub use virtualized::{
276 HeightCache, ItemHeight, RenderItem, Virtualized, VirtualizedList, VirtualizedListState,
277 VirtualizedStorage,
278};
279pub use voi_debug_overlay::{
280 VoiDebugOverlay, VoiDecisionSummary, VoiLedgerEntry, VoiObservationSummary, VoiOverlayData,
281 VoiOverlayStyle, VoiPosteriorSummary,
282};
283
284pub use toast::{
286 KeyEvent as ToastKeyEvent, Toast, ToastAction, ToastAnimationConfig, ToastAnimationPhase,
287 ToastAnimationState, ToastConfig, ToastContent, ToastEasing, ToastEntranceAnimation,
288 ToastEvent, ToastExitAnimation, ToastIcon, ToastId, ToastPosition, ToastState, ToastStyle,
289};
290
291pub use notification_queue::{
293 NotificationPriority, NotificationQueue, QueueAction, QueueConfig, QueueStats,
294};
295
296pub use ftui_a11y::Accessible;
298
299pub use mouse::MouseResult;
301
302pub use measurable::{MeasurableWidget, SizeConstraints};
304
305pub use measure_cache::{CacheStats, MeasureCache, WidgetId};
307pub use modal::{
308 BackdropConfig, MODAL_HIT_BACKDROP, MODAL_HIT_CONTENT, Modal, ModalAction, ModalConfig,
309 ModalPosition, ModalSizeConstraints, ModalState,
310};
311
312pub use inspector::{
314 DiagnosticEntry, DiagnosticEventKind, DiagnosticLog, HitInfo, InspectorMode, InspectorOverlay,
315 InspectorState, InspectorStyle, TelemetryCallback, TelemetryHooks, WidgetInfo,
316 diagnostics_enabled, init_diagnostics, is_deterministic_mode, reset_event_counter,
317 set_diagnostics_enabled,
318};
319
320pub use focus::{
322 FocusEvent, FocusGraph, FocusGroup, FocusId, FocusIndicator, FocusIndicatorKind, FocusManager,
323 FocusNode, FocusTrap, NavDirection,
324};
325
326pub use drag::{
328 DragConfig, DragPayload, DragState, Draggable, DropPosition, DropResult, DropTarget,
329};
330
331pub use stateful::{StateKey, Stateful, VersionedState};
333
334pub use list::ListPersistState;
336pub use table::TablePersistState;
337pub use tree::TreePersistState;
338pub use virtualized::VirtualizedListPersistState;
339
340pub use undo_support::{
342 ListOperation, ListUndoExt, SelectionOperation, TableOperation, TableUndoExt,
343 TextEditOperation, TextInputUndoExt, TreeOperation, TreeUndoExt, UndoSupport, UndoWidgetId,
344 WidgetTextEditCmd,
345};
346
347pub use validation_error::{
349 ANIMATION_DURATION_MS, ERROR_BG_DEFAULT, ERROR_FG_DEFAULT, ERROR_ICON_DEFAULT,
350 ValidationErrorDisplay, ValidationErrorState,
351};
352
353use ftui_core::geometry::Rect;
354use ftui_render::buffer::Buffer;
355use ftui_render::cell::Cell;
356use ftui_render::frame::{Frame, WidgetSignal};
357use ftui_style::Style;
358use ftui_text::grapheme_width;
359
360#[must_use]
365pub(crate) fn a11y_node_id(area: Rect) -> u64 {
366 const FNV_OFFSET: u64 = 14_695_981_039_346_656_037;
368 const FNV_PRIME: u64 = 1_099_511_628_211;
369 let mut h = FNV_OFFSET;
370 for byte in area
371 .x
372 .to_le_bytes()
373 .iter()
374 .chain(&area.y.to_le_bytes())
375 .chain(&area.width.to_le_bytes())
376 .chain(&area.height.to_le_bytes())
377 {
378 h ^= u64::from(*byte);
379 h = h.wrapping_mul(FNV_PRIME);
380 }
381 h
382}
383
384pub trait Widget {
424 fn render(&self, area: Rect, frame: &mut Frame);
430
431 fn is_essential(&self) -> bool {
442 false
443 }
444}
445
446pub trait FrameExt {
453 fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect);
455
456 fn render_stateful_widget<W: StatefulWidget + ?Sized>(
459 &mut self,
460 widget: &W,
461 area: Rect,
462 state: &mut W::State,
463 );
464}
465
466impl FrameExt for Frame<'_> {
467 #[inline]
468 fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect) {
469 widget.render(area, self);
470 }
471
472 #[inline]
473 fn render_stateful_widget<W: StatefulWidget + ?Sized>(
474 &mut self,
475 widget: &W,
476 area: Rect,
477 state: &mut W::State,
478 ) {
479 widget.render(area, self, state);
480 }
481}
482
483pub struct Budgeted<W> {
485 widget_id: u64,
486 signal: WidgetSignal,
487 inner: W,
488}
489
490impl<W> Budgeted<W> {
491 #[must_use]
493 pub fn new(widget_id: u64, inner: W) -> Self {
494 Self {
495 widget_id,
496 signal: WidgetSignal::new(widget_id),
497 inner,
498 }
499 }
500
501 #[must_use]
503 pub fn with_signal(mut self, mut signal: WidgetSignal) -> Self {
504 signal.widget_id = self.widget_id;
505 self.signal = signal;
506 self
507 }
508
509 #[must_use]
511 pub fn inner(&self) -> &W {
512 &self.inner
513 }
514}
515
516impl<W: Widget> Widget for Budgeted<W> {
517 fn render(&self, area: Rect, frame: &mut Frame) {
518 let mut signal = self.signal.clone();
519 signal.widget_id = self.widget_id;
520 signal.essential = self.inner.is_essential();
521 signal.area_cells = area.width as u32 * area.height as u32;
522 frame.register_widget_signal(signal);
523
524 if frame.should_render_widget(self.widget_id, self.inner.is_essential()) {
525 self.inner.render(area, frame);
526 }
527 }
528
529 fn is_essential(&self) -> bool {
530 self.inner.is_essential()
531 }
532}
533
534impl<W: StatefulWidget + Widget> StatefulWidget for Budgeted<W> {
535 type State = W::State;
536
537 fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
538 let mut signal = self.signal.clone();
539 signal.widget_id = self.widget_id;
540 signal.essential = self.inner.is_essential();
541 signal.area_cells = area.width as u32 * area.height as u32;
542 frame.register_widget_signal(signal);
543
544 if frame.should_render_widget(self.widget_id, self.inner.is_essential()) {
545 StatefulWidget::render(&self.inner, area, frame, state);
546 }
547 }
548}
549
550pub trait StatefulWidget {
587 type State;
589
590 fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State);
597}
598
599pub(crate) fn apply_style(cell: &mut Cell, style: Style) {
606 if let Some(fg) = style.fg {
607 cell.fg = fg;
608 }
609 if let Some(bg) = style.bg {
610 match bg.a() {
611 0 => {} 255 => cell.bg = bg, _ => cell.bg = bg.over(cell.bg), }
615 }
616 if let Some(attrs) = style.attrs {
617 let cell_flags: ftui_render::cell::StyleFlags = attrs.into();
618 cell.attrs = cell.attrs.merged_flags(cell_flags);
619 }
620}
621
622pub(crate) fn set_style_area(buf: &mut Buffer, area: Rect, style: Style) {
632 if style.is_empty() {
633 return;
634 }
635 let clipped = area.intersection(&buf.current_scissor());
636 if clipped.is_empty() {
637 return;
638 }
639
640 let opacity = buf.current_opacity();
641 let fg = style.fg.map(|fg| fg.with_opacity(opacity));
642 let bg = style.bg.map(|bg| bg.with_opacity(opacity));
643 let attrs = style.attrs.map(ftui_render::cell::StyleFlags::from);
644 for y in clipped.y..clipped.bottom() {
645 let Some(row) = buf.row_cells_mut_span(y, clipped.x, clipped.right()) else {
646 continue;
647 };
648 for cell in row {
649 if let Some(fg) = fg {
650 cell.fg = fg;
651 }
652 if let Some(bg) = bg {
653 match bg.a() {
654 0 => {} 255 => cell.bg = bg, _ => cell.bg = bg.over(cell.bg), }
658 }
659 if let Some(attrs) = attrs {
660 cell.attrs = cell.attrs.merged_flags(attrs);
661 }
662 }
663 }
664}
665
666pub(crate) fn clear_text_area(frame: &mut Frame, area: Rect, style: Style) {
668 if area.width == 0 || area.height == 0 {
669 return;
670 }
671
672 let mut cell = Cell::from_char(' ');
673 apply_style(&mut cell, style);
674 frame.buffer.fill(area, cell);
675}
676
677pub(crate) fn clear_text_row(frame: &mut Frame, area: Rect, style: Style) {
679 clear_text_area(frame, Rect::new(area.x, area.y, area.width, 1), style);
680}
681
682fn inherited_text_cell(
688 frame: &Frame,
689 x: u16,
690 y: u16,
691 content: ftui_render::cell::CellContent,
692) -> Cell {
693 let mut cell = frame.buffer.get(x, y).copied().unwrap_or_default();
694 cell.content = content;
695 cell.attrs = ftui_render::cell::CellAttrs::new(cell.attrs.flags(), 0);
696 cell
697}
698
699pub(crate) fn draw_text_span(
704 frame: &mut Frame,
705 mut x: u16,
706 y: u16,
707 content: &str,
708 style: Style,
709 max_x: u16,
710) -> u16 {
711 use unicode_segmentation::UnicodeSegmentation;
712
713 for grapheme in content.graphemes(true) {
714 if x >= max_x {
715 break;
716 }
717 let w = grapheme_width(grapheme);
718 if w == 0 {
719 continue;
720 }
721 if x.saturating_add(w as u16) > max_x {
722 break;
723 }
724
725 let cell_content = if w > 1 || grapheme.chars().count() > 1 {
727 let id = frame.intern_with_width(grapheme, w as u8);
728 ftui_render::cell::CellContent::from_grapheme(id)
729 } else if let Some(c) = grapheme.chars().next() {
730 ftui_render::cell::CellContent::from_char(c)
731 } else {
732 continue;
733 };
734
735 let mut cell = inherited_text_cell(frame, x, y, cell_content);
736 apply_style(&mut cell, style);
737
738 frame.buffer.set_fast(x, y, cell);
741
742 x = x.saturating_add(w as u16);
743 }
744 x
745}
746
747#[allow(dead_code)]
749pub(crate) fn draw_text_span_with_link(
750 frame: &mut Frame,
751 x: u16,
752 y: u16,
753 content: &str,
754 style: Style,
755 max_x: u16,
756 link_url: Option<&str>,
757) -> u16 {
758 draw_text_span_scrolled(frame, x, y, content, style, max_x, 0, link_url)
759}
760
761#[allow(dead_code, clippy::too_many_arguments)]
763pub(crate) fn draw_text_span_scrolled(
764 frame: &mut Frame,
765 mut x: u16,
766 y: u16,
767 content: &str,
768 style: Style,
769 max_x: u16,
770 scroll_x: u16,
771 link_url: Option<&str>,
772) -> u16 {
773 use unicode_segmentation::UnicodeSegmentation;
774
775 let link_id = if let Some(url) = link_url {
777 frame.register_link(url)
778 } else {
779 0
780 };
781
782 let mut visual_pos: u16 = 0;
783
784 for grapheme in content.graphemes(true) {
785 if x >= max_x {
786 break;
787 }
788 let w = grapheme_width(grapheme);
789 if w == 0 {
790 continue;
791 }
792
793 let next_visual_pos = visual_pos.saturating_add(w as u16);
794
795 if next_visual_pos <= scroll_x {
797 visual_pos = next_visual_pos;
799 continue;
800 }
801
802 if visual_pos < scroll_x {
803 visual_pos = next_visual_pos;
806 continue;
807 }
808
809 if x.saturating_add(w as u16) > max_x {
810 break;
811 }
812
813 let cell_content = if w > 1 || grapheme.chars().count() > 1 {
815 let id = frame.intern_with_width(grapheme, w as u8);
816 ftui_render::cell::CellContent::from_grapheme(id)
817 } else if let Some(c) = grapheme.chars().next() {
818 ftui_render::cell::CellContent::from_char(c)
819 } else {
820 continue;
821 };
822
823 let mut cell = inherited_text_cell(frame, x, y, cell_content);
824 apply_style(&mut cell, style);
825
826 if link_id != 0 {
828 cell.attrs = cell.attrs.with_link(link_id);
829 }
830
831 frame.buffer.set_fast(x, y, cell);
832
833 x = x.saturating_add(w as u16);
834 visual_pos = next_visual_pos;
835 }
836 x
837}
838
839pub(crate) fn contains_ignore_case(haystack: &str, needle_lower: &str) -> bool {
841 if needle_lower.is_empty() {
842 return true;
843 }
844 if haystack.is_ascii() && needle_lower.is_ascii() {
846 let haystack_bytes = haystack.as_bytes();
847 let needle_bytes = needle_lower.as_bytes();
848 if needle_bytes.len() > haystack_bytes.len() {
849 return false;
850 }
851 for i in 0..=haystack_bytes.len() - needle_bytes.len() {
853 let mut match_found = true;
854 for (j, &b) in needle_bytes.iter().enumerate() {
855 if haystack_bytes[i + j].to_ascii_lowercase() != b {
856 match_found = false;
857 break;
858 }
859 }
860 if match_found {
861 return true;
862 }
863 }
864 return false;
865 }
866 haystack.to_lowercase().contains(needle_lower)
868}
869
870#[cfg(test)]
871mod tests {
872 use super::*;
873 use ftui_render::cell::PackedRgba;
874 use ftui_render::grapheme_pool::GraphemePool;
875
876 #[test]
879 fn frame_ext_render_widget_matches_direct_render() {
880 struct Fill(char);
881 impl Widget for Fill {
882 fn render(&self, area: Rect, frame: &mut Frame) {
883 for y in area.y..area.y + area.height {
884 for x in area.x..area.x + area.width {
885 frame.buffer.set_raw(x, y, Cell::from_char(self.0));
886 }
887 }
888 }
889 }
890
891 let mut pool_a = GraphemePool::new();
892 let mut direct = Frame::new(6, 2, &mut pool_a);
893 Fill('d').render(Rect::new(1, 0, 3, 2), &mut direct);
894
895 let mut pool_b = GraphemePool::new();
896 let mut via_ext = Frame::new(6, 2, &mut pool_b);
897 via_ext.render_widget(&Fill('d'), Rect::new(1, 0, 3, 2));
898 assert_eq!(via_ext.area(), Rect::new(0, 0, 6, 2));
899
900 for y in 0..2 {
901 for x in 0..6 {
902 assert_eq!(
903 direct.buffer.get(x, y).map(|cell| cell.content),
904 via_ext.buffer.get(x, y).map(|cell| cell.content),
905 "cell ({x},{y}) differs between direct render and FrameExt"
906 );
907 }
908 }
909 assert_eq!(
910 via_ext.buffer.get(1, 0).map(|cell| cell.content),
911 Some(Cell::from_char('d').content)
912 );
913 assert_eq!(
914 via_ext.buffer.get(0, 0).map(|cell| cell.content),
915 Some(Cell::default().content)
916 );
917 }
918
919 #[test]
924 fn rendering_accessible_widgets_pushes_their_nodes_into_the_frame() {
925 use crate::block::Block;
926 use crate::list::{List, ListState};
927 use crate::paragraph::Paragraph;
928 use ftui_a11y::node::A11yRole;
929 use ftui_a11y::tree::A11yTreeBuilder;
930
931 let mut pool = GraphemePool::new();
932 let mut builder = A11yTreeBuilder::new();
933 let mut frame = Frame::new(30, 8, &mut pool);
934 frame.set_a11y(&mut builder);
935
936 let mut list_state = ListState::default();
937 let list = List::new(["alpha", "beta"]);
938 StatefulWidget::render(&list, Rect::new(0, 0, 30, 3), &mut frame, &mut list_state);
939 Block::new()
940 .title("Details")
941 .render(Rect::new(0, 3, 30, 3), &mut frame);
942 Paragraph::new("hello").render(Rect::new(0, 6, 30, 1), &mut frame);
943 frame.finish_a11y();
944 let order = frame.take_a11y_order();
945 drop(frame);
946
947 let tree = builder.build();
948 assert_eq!(order.len(), tree.node_count());
949 assert!(
950 order.len() >= 5,
951 "list + 2 items + block + paragraph: {order:?}"
952 );
953 let roles: Vec<A11yRole> = order
954 .iter()
955 .filter_map(|id| tree.node(*id).map(|n| n.role))
956 .collect();
957 assert_eq!(roles[0], A11yRole::List);
958 assert_eq!(roles[1], A11yRole::ListItem);
959 assert_eq!(roles[2], A11yRole::ListItem);
960 assert!(roles.contains(&A11yRole::Group), "{roles:?}");
961 let list_id = order[0];
962 assert_eq!(
963 tree.node(list_id).map(|n| n.children.len()),
964 Some(2),
965 "list items are the list's children"
966 );
967 assert_eq!(
968 tree.root_id(),
969 Some(list_id),
970 "first parentless node is the root"
971 );
972 let text = tree.dump_text(&order);
973 assert!(text.contains("ListItem \"alpha\""), "{text}");
974 assert!(text.contains("Group \"Details\""), "{text}");
975
976 let mut pool = GraphemePool::new();
978 let mut frame = Frame::new(30, 8, &mut pool);
979 Paragraph::new("hello").render(Rect::new(0, 0, 30, 1), &mut frame);
980 assert!(frame.a11y_order().is_empty());
981 }
982
983 #[test]
985 fn frame_ext_render_stateful_widget_passes_state() {
986 struct Counter;
987 impl StatefulWidget for Counter {
988 type State = u32;
989 fn render(&self, _area: Rect, _frame: &mut Frame, state: &mut u32) {
990 *state += 1;
991 }
992 }
993 let mut pool = GraphemePool::new();
994 let mut frame = Frame::new(4, 1, &mut pool);
995 let mut count = 0;
996 frame.render_stateful_widget(&Counter, frame.area(), &mut count);
997 frame.render_stateful_widget(&Counter, Rect::new(0, 0, 1, 1), &mut count);
998 assert_eq!(count, 2);
999 }
1000
1001 #[test]
1002 fn apply_style_sets_fg() {
1003 let mut cell = Cell::default();
1004 let style = Style::new().fg(PackedRgba::rgb(255, 0, 0));
1005 apply_style(&mut cell, style);
1006 assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
1007 }
1008
1009 #[test]
1010 fn apply_style_sets_bg() {
1011 let mut cell = Cell::default();
1012 let style = Style::new().bg(PackedRgba::rgb(0, 255, 0));
1013 apply_style(&mut cell, style);
1014 assert_eq!(cell.bg, PackedRgba::rgb(0, 255, 0));
1015 }
1016
1017 #[test]
1018 fn apply_style_preserves_content() {
1019 let mut cell = Cell::from_char('Z');
1020 let style = Style::new().fg(PackedRgba::rgb(1, 2, 3));
1021 apply_style(&mut cell, style);
1022 assert_eq!(cell.content.as_char(), Some('Z'));
1023 }
1024
1025 #[test]
1026 fn apply_style_empty_is_noop() {
1027 let original = Cell::default();
1028 let mut cell = Cell::default();
1029 apply_style(&mut cell, Style::default());
1030 assert_eq!(cell.fg, original.fg);
1031 assert_eq!(cell.bg, original.bg);
1032 }
1033
1034 #[test]
1035 fn apply_style_bg_only_preserves_fg() {
1036 let mut cell = Cell::from_char('x').with_fg(PackedRgba::rgb(0, 200, 0));
1038 let selection = Style::new().bg(PackedRgba::rgb(0, 0, 180));
1039 apply_style(&mut cell, selection);
1040 assert_eq!(cell.fg, PackedRgba::rgb(0, 200, 0));
1042 assert_eq!(cell.bg, PackedRgba::rgb(0, 0, 180));
1043 }
1044
1045 #[test]
1046 fn apply_style_composites_alpha_bg() {
1047 let base_bg = PackedRgba::rgb(200, 0, 0);
1048 let mut cell = Cell::default().with_bg(base_bg);
1049 let overlay = PackedRgba::rgba(0, 0, 200, 128);
1050 apply_style(&mut cell, Style::new().bg(overlay));
1051 assert_eq!(cell.bg, overlay.over(base_bg));
1052 }
1053
1054 #[test]
1055 fn apply_style_transparent_bg_is_noop() {
1056 let base_bg = PackedRgba::rgb(100, 100, 100);
1057 let mut cell = Cell::default().with_bg(base_bg);
1058 apply_style(&mut cell, Style::new().bg(PackedRgba::rgba(255, 0, 0, 0)));
1059 assert_eq!(cell.bg, base_bg);
1060 }
1061
1062 #[test]
1063 fn apply_style_merges_attrs_not_replaces() {
1064 use ftui_render::cell::StyleFlags as CellFlags;
1065 let mut cell = Cell::default();
1067 cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1068 let overlay = Style::new().italic();
1070 apply_style(&mut cell, overlay);
1071 assert!(cell.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1072 assert!(
1073 cell.attrs.has_flag(CellFlags::ITALIC),
1074 "ITALIC must be added"
1075 );
1076 }
1077
1078 #[test]
1079 fn set_style_area_bg_only_preserves_per_cell_fg() {
1080 let mut buf = Buffer::new(3, 1);
1082 buf.set(0, 0, Cell::from_char('R').with_fg(PackedRgba::RED));
1083 buf.set(1, 0, Cell::from_char('G').with_fg(PackedRgba::GREEN));
1084 buf.set(2, 0, Cell::from_char('B').with_fg(PackedRgba::BLUE));
1085
1086 let highlight = Style::new().bg(PackedRgba::rgb(40, 40, 40));
1088 set_style_area(&mut buf, Rect::new(0, 0, 3, 1), highlight);
1089
1090 assert_eq!(buf.get(0, 0).unwrap().fg, PackedRgba::RED);
1092 assert_eq!(buf.get(1, 0).unwrap().fg, PackedRgba::GREEN);
1093 assert_eq!(buf.get(2, 0).unwrap().fg, PackedRgba::BLUE);
1094 assert_eq!(buf.get(0, 0).unwrap().bg, PackedRgba::rgb(40, 40, 40));
1096 }
1097
1098 #[test]
1099 fn set_style_area_merges_attrs_not_replaces() {
1100 use ftui_render::cell::StyleFlags as CellFlags;
1101 let mut buf = Buffer::new(1, 1);
1102 let mut cell = Cell::from_char('X');
1103 cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1104 buf.set(0, 0, cell);
1105
1106 set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().italic());
1107
1108 let result = buf.get(0, 0).unwrap();
1109 assert!(result.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1110 assert!(
1111 result.attrs.has_flag(CellFlags::ITALIC),
1112 "ITALIC must be added"
1113 );
1114 }
1115
1116 #[test]
1117 fn set_style_area_applies_to_all_cells() {
1118 let mut buf = Buffer::new(3, 2);
1119 let area = Rect::new(0, 0, 3, 2);
1120 let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1121 set_style_area(&mut buf, area, style);
1122
1123 for y in 0..2 {
1124 for x in 0..3 {
1125 assert_eq!(
1126 buf.get(x, y).unwrap().bg,
1127 PackedRgba::rgb(10, 20, 30),
1128 "cell ({x},{y}) should have style applied"
1129 );
1130 }
1131 }
1132 }
1133
1134 #[test]
1135 fn set_style_area_composites_alpha_bg_over_existing_bg() {
1136 let mut buf = Buffer::new(1, 1);
1137 let base = PackedRgba::rgb(200, 0, 0);
1138 buf.set(0, 0, Cell::default().with_bg(base));
1139
1140 let overlay = PackedRgba::rgba(0, 0, 200, 128);
1141 set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(overlay));
1142
1143 let expected = overlay.over(base);
1144 assert_eq!(buf.get(0, 0).unwrap().bg, expected);
1145 }
1146
1147 #[test]
1148 fn set_style_area_partial_rect() {
1149 let mut buf = Buffer::new(5, 5);
1150 let area = Rect::new(1, 1, 2, 2);
1151 let style = Style::new().fg(PackedRgba::rgb(99, 99, 99));
1152 set_style_area(&mut buf, area, style);
1153
1154 assert_eq!(buf.get(1, 1).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1156 assert_eq!(buf.get(2, 2).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1157
1158 assert_ne!(buf.get(0, 0).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1160 }
1161
1162 #[test]
1163 fn set_style_area_empty_style_is_noop() {
1164 let mut buf = Buffer::new(3, 3);
1165 buf.set(0, 0, Cell::from_char('A'));
1166 let original_fg = buf.get(0, 0).unwrap().fg;
1167
1168 set_style_area(&mut buf, Rect::new(0, 0, 3, 3), Style::default());
1169
1170 assert_eq!(buf.get(0, 0).unwrap().fg, original_fg);
1172 assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
1173 }
1174
1175 #[test]
1176 fn set_style_area_respects_scissor() {
1177 let mut buf = Buffer::new(3, 3);
1178 let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1179
1180 buf.push_scissor(Rect::new(1, 1, 1, 1));
1181 set_style_area(&mut buf, Rect::new(0, 0, 3, 3), style);
1182
1183 assert_eq!(buf.get(1, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1184 assert_ne!(buf.get(0, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1185 assert_ne!(buf.get(1, 0).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1186 assert_ne!(buf.get(2, 2).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1187 }
1188
1189 #[test]
1190 fn set_style_area_respects_opacity_stack() {
1191 let mut buf = Buffer::new(1, 1);
1192 let base_fg = PackedRgba::rgb(20, 30, 40);
1193 let base_bg = PackedRgba::rgb(50, 60, 70);
1194 buf.set(0, 0, Cell::from_char('X').with_fg(base_fg).with_bg(base_bg));
1195
1196 let overlay_fg = PackedRgba::rgb(200, 100, 0);
1197 let overlay_bg = PackedRgba::rgb(0, 0, 200);
1198 buf.push_opacity(0.5);
1199 set_style_area(
1200 &mut buf,
1201 Rect::new(0, 0, 1, 1),
1202 Style::new().fg(overlay_fg).bg(overlay_bg),
1203 );
1204
1205 let cell = buf.get(0, 0).unwrap();
1206 assert_eq!(cell.fg, overlay_fg.with_opacity(0.5));
1207 assert_eq!(cell.bg, overlay_bg.with_opacity(0.5).over(base_bg));
1208 }
1209
1210 #[test]
1211 fn draw_text_span_basic() {
1212 let mut pool = GraphemePool::new();
1213 let mut frame = Frame::new(10, 1, &mut pool);
1214 let end_x = draw_text_span(&mut frame, 0, 0, "ABC", Style::default(), 10);
1215
1216 assert_eq!(end_x, 3);
1217 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1218 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
1219 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1220 }
1221
1222 #[test]
1223 fn draw_text_span_clipped_at_max_x() {
1224 let mut pool = GraphemePool::new();
1225 let mut frame = Frame::new(10, 1, &mut pool);
1226 let end_x = draw_text_span(&mut frame, 0, 0, "ABCDEF", Style::default(), 3);
1227
1228 assert_eq!(end_x, 3);
1229 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1230 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1231 assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1233 }
1234
1235 #[test]
1236 fn draw_text_span_starts_at_offset() {
1237 let mut pool = GraphemePool::new();
1238 let mut frame = Frame::new(10, 1, &mut pool);
1239 let end_x = draw_text_span(&mut frame, 5, 0, "XY", Style::default(), 10);
1240
1241 assert_eq!(end_x, 7);
1242 assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('X'));
1243 assert_eq!(frame.buffer.get(6, 0).unwrap().content.as_char(), Some('Y'));
1244 assert!(frame.buffer.get(4, 0).unwrap().is_empty());
1245 }
1246
1247 #[test]
1248 fn draw_text_span_empty_string() {
1249 let mut pool = GraphemePool::new();
1250 let mut frame = Frame::new(5, 1, &mut pool);
1251 let end_x = draw_text_span(&mut frame, 0, 0, "", Style::default(), 5);
1252 assert_eq!(end_x, 0);
1253 }
1254
1255 #[test]
1256 fn draw_text_span_applies_style() {
1257 let mut pool = GraphemePool::new();
1258 let mut frame = Frame::new(5, 1, &mut pool);
1259 let style = Style::new().fg(PackedRgba::rgb(255, 128, 0));
1260 draw_text_span(&mut frame, 0, 0, "A", style, 5);
1261
1262 assert_eq!(
1263 frame.buffer.get(0, 0).unwrap().fg,
1264 PackedRgba::rgb(255, 128, 0)
1265 );
1266 }
1267
1268 #[test]
1269 fn draw_text_span_preserves_existing_overlay_fg_and_bg() {
1270 let mut pool = GraphemePool::new();
1271 let mut frame = Frame::new(3, 1, &mut pool);
1272 frame.buffer.set(
1273 0,
1274 0,
1275 Cell::from_char('x').with_fg(PackedRgba::rgb(200, 40, 10)),
1276 );
1277 set_style_area(
1278 &mut frame.buffer,
1279 Rect::new(0, 0, 1, 1),
1280 Style::new().bg(PackedRgba::rgb(20, 30, 40)),
1281 );
1282
1283 draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1284
1285 let cell = frame.buffer.get(0, 0).unwrap();
1286 assert_eq!(cell.content.as_char(), Some('A'));
1287 assert_eq!(cell.fg, PackedRgba::rgb(200, 40, 10));
1288 assert_eq!(cell.bg, PackedRgba::rgb(20, 30, 40));
1289 }
1290
1291 #[test]
1292 fn draw_text_span_drops_stale_link_id_but_keeps_style_flags() {
1293 use ftui_render::cell::{CellAttrs, StyleFlags as CellFlags};
1294
1295 let mut pool = GraphemePool::new();
1296 let mut frame = Frame::new(3, 1, &mut pool);
1297 frame.buffer.set(
1298 0,
1299 0,
1300 Cell::from_char('x').with_attrs(CellAttrs::new(CellFlags::UNDERLINE, 42)),
1301 );
1302
1303 draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1304
1305 let cell = frame.buffer.get(0, 0).unwrap();
1306 assert_eq!(cell.content.as_char(), Some('A'));
1307 assert!(cell.attrs.has_flag(CellFlags::UNDERLINE));
1308 assert_eq!(cell.attrs.link_id(), 0);
1309 }
1310
1311 #[test]
1312 fn draw_text_span_max_x_at_start_draws_nothing() {
1313 let mut pool = GraphemePool::new();
1314 let mut frame = Frame::new(5, 1, &mut pool);
1315 let end_x = draw_text_span(&mut frame, 3, 0, "ABC", Style::default(), 3);
1316 assert_eq!(end_x, 3);
1317 assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1318 }
1319
1320 #[test]
1321 fn widget_is_essential_default_false() {
1322 struct DummyWidget;
1323 impl Widget for DummyWidget {
1324 fn render(&self, _: Rect, _: &mut Frame) {}
1325 }
1326 assert!(!DummyWidget.is_essential());
1327 }
1328
1329 #[test]
1330 fn budgeted_new_and_inner() {
1331 struct TestW;
1332 impl Widget for TestW {
1333 fn render(&self, _: Rect, _: &mut Frame) {}
1334 }
1335 let b = Budgeted::new(42, TestW);
1336 assert_eq!(b.widget_id, 42);
1337 let _ = b.inner(); }
1339
1340 #[test]
1341 fn budgeted_with_signal() {
1342 struct TestW;
1343 impl Widget for TestW {
1344 fn render(&self, _: Rect, _: &mut Frame) {}
1345 }
1346 let sig = WidgetSignal::new(99);
1347 let b = Budgeted::new(42, TestW).with_signal(sig);
1348 assert_eq!(b.signal.widget_id, 42);
1350 }
1351
1352 #[test]
1353 fn set_style_area_transparent_bg_is_noop() {
1354 let mut buf = Buffer::new(1, 1);
1355 let base = PackedRgba::rgb(100, 100, 100);
1356 buf.set(0, 0, Cell::default().with_bg(base));
1357
1358 let transparent = PackedRgba::rgba(255, 0, 0, 0);
1360 set_style_area(
1361 &mut buf,
1362 Rect::new(0, 0, 1, 1),
1363 Style::new().bg(transparent),
1364 );
1365 assert_eq!(buf.get(0, 0).unwrap().bg, base);
1366 }
1367
1368 #[test]
1369 fn set_style_area_opaque_bg_replaces() {
1370 let mut buf = Buffer::new(1, 1);
1371 buf.set(
1372 0,
1373 0,
1374 Cell::default().with_bg(PackedRgba::rgb(100, 100, 100)),
1375 );
1376
1377 let opaque = PackedRgba::rgba(0, 255, 0, 255);
1378 set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(opaque));
1379 assert_eq!(buf.get(0, 0).unwrap().bg, opaque);
1380 }
1381
1382 #[test]
1383 fn draw_text_span_scrolled_skips_chars() {
1384 let mut pool = GraphemePool::new();
1385 let mut frame = Frame::new(10, 1, &mut pool);
1386 let end_x =
1388 draw_text_span_scrolled(&mut frame, 0, 0, "ABCDE", Style::default(), 10, 2, None);
1389
1390 assert_eq!(end_x, 3);
1391 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('C'));
1392 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('D'));
1393 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('E'));
1394 }
1395}