1use std::cell::RefCell;
4use std::mem;
5use std::rc::Rc;
6use std::sync::Arc;
7
8use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
9use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
10use ailloli_ui_core::event::{Event, Key, KeyEvent, KeyState, NamedKey};
11use ailloli_ui_core::geometry::{Constraints, Rect, Size};
12use ailloli_ui_core::scroll::{
13 ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState, ScrollbarAxis, ScrollbarGeometry,
14 ScrollbarGeometrySpec,
15};
16use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
17use ailloli_ui_core::{ClipShape, Color, FontId, Offset, TextStyle, Theme};
18use ailloli_ui_runtime::component::reactive::with_untracked_reads;
19use ailloli_ui_runtime::component::{ComponentNode, Context, IntoView, Signal, View, Widget};
20use ailloli_ui_runtime::input::{EventCtx, FocusPolicy, InputRole};
21use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
22use ailloli_ui_runtime::scene::PaintCtx;
23use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, DrawRect, DrawText, Invalidation};
24use ailloli_ui_terminal_core::{
25 terminal_visual_line_global_indices, ActiveScreen, CellWidth, TerminalColor,
26 TerminalCursorShape, TerminalDiagnostic, TerminalDiagnosticSeverity,
27 TerminalLine as CoreTerminalLine, TerminalModes, TerminalMouseTrackingMode, TerminalSize,
28 TerminalState, TerminalStyle,
29};
30use ailloli_ui_text::{
31 PreparedTextLayout, StyledTextLayoutParams, StyledTextSpan, TextSystem, WrapMode,
32};
33
34use super::terminal::{TerminalPosition, TerminalSelection};
35use crate::scrollbar::{thumb_color_for_state, ScrollbarInteraction};
36use crate::transactional_layout::TransactionalLayoutPending;
37
38type InputHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, Vec<u8>)>;
40type StateSync = Rc<dyn Fn() -> Option<TerminalState>>;
42type ResizeSync = Rc<dyn Fn(TerminalViewportSize) -> Option<TerminalState>>;
44type GeometrySync = Rc<dyn Fn(TerminalGeometry) -> Option<TerminalState>>;
46
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct TerminalCellMetrics {
61 pub cell_width: f32,
63 pub cell_height: f32,
65 pub baseline: f32,
67}
68
69impl TerminalCellMetrics {
70 pub const fn new(cell_width: f32, cell_height: f32, baseline: f32) -> Self {
80 Self {
81 cell_width,
82 cell_height,
83 baseline,
84 }
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq)]
89pub struct TerminalGeometry {
109 pub pixel_width: u32,
111 pub pixel_height: u32,
113 pub metrics: TerminalCellMetrics,
115 pub cols: u16,
117 pub rows: u16,
119}
120
121impl TerminalGeometry {
122 pub const fn new(
132 pixel_width: u32,
133 pixel_height: u32,
134 metrics: TerminalCellMetrics,
135 cols: u16,
136 rows: u16,
137 ) -> Self {
138 Self {
139 pixel_width,
140 pixel_height,
141 metrics,
142 cols,
143 rows,
144 }
145 }
146
147 pub fn terminal_size(self) -> TerminalSize {
159 TerminalSize::new(self.rows as usize, self.cols as usize)
160 }
161
162 pub fn viewport_size(self) -> TerminalViewportSize {
177 TerminalViewportSize::new(
178 self.terminal_size(),
179 self.pixel_width.min(u16::MAX as u32) as u16,
180 self.pixel_height.min(u16::MAX as u32) as u16,
181 )
182 }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub struct TerminalViewportSize {
197 pub terminal: TerminalSize,
199 pub pixel_width: u16,
201 pub pixel_height: u16,
203}
204
205impl TerminalViewportSize {
206 pub const fn new(terminal: TerminalSize, pixel_width: u16, pixel_height: u16) -> Self {
217 Self {
218 terminal,
219 pixel_width,
220 pixel_height,
221 }
222 }
223}
224
225#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
226pub enum TerminalSelectionMode {
245 #[default]
247 Character,
248 Word,
250 Line,
252}
253
254#[derive(Clone, Debug, PartialEq)]
255pub struct TerminalWidgetStyle {
271 pub background: Color,
273 pub border: Border,
275 pub focus_ring: Border,
277 pub text: TextStyle,
279 pub selection_background: Color,
281 pub cursor: Color,
283 pub scrollbar_track: Color,
285 pub scrollbar_thumb: Color,
287 pub diagnostic_error: Color,
289 pub diagnostic_warning: Color,
291 pub diagnostic_info: Color,
293 pub diagnostic_hint: Color,
295 pub radius: Radius,
297 pub padding_x: f32,
299 pub padding_y: f32,
301 pub width: f32,
303 pub height: f32,
305 pub line_height: f32,
307 pub char_width: f32,
309 pub scrollbar_width: f32,
311 pub scrollbar_inset: f32,
313}
314
315impl Default for TerminalWidgetStyle {
316 fn default() -> Self {
317 Self::from_theme(Theme::default())
318 }
319}
320
321impl TerminalWidgetStyle {
322 pub fn from_theme(theme: Theme) -> Self {
334 let palette = theme.palette();
335 Self {
336 background: Color::hex_rgb(0x080C10),
337 border: Border::new(1.0, palette.border.with_alpha(0.70)),
338 focus_ring: Border::new(1.0, palette.focus),
339 text: TextStyle::new(FontId::Mono, 13, Color::hex_rgb(0xD9E2EC)),
340 selection_background: palette.accent.with_alpha(0.24),
341 cursor: Color::hex_rgb(0xEAF2FF),
342 scrollbar_track: Color::rgba(148, 163, 184, 0.16),
343 scrollbar_thumb: Color::rgba(148, 163, 184, 0.58),
344 diagnostic_error: palette.danger,
345 diagnostic_warning: palette.warning,
346 diagnostic_info: palette.info,
347 diagnostic_hint: palette.text_muted,
348 radius: Radius::uniform(theme.radius().md),
349 padding_x: 12.0,
350 padding_y: 10.0,
351 width: 760.0,
352 height: 280.0,
353 line_height: 19.0,
354 char_width: 7.8,
355 scrollbar_width: 6.0,
356 scrollbar_inset: 4.0,
357 }
358 }
359}
360
361pub struct Terminal<A = ()> {
383 pub(crate) layout: LayoutStyle,
385 pub(crate) flex_item: FlexItemStyle,
387 state: Signal<TerminalState>,
389 style: TerminalWidgetStyle,
391 initial_scroll_y: f32,
393 selection: Option<TerminalSelection>,
395 selection_mode: TerminalSelectionMode,
397 follow_output: bool,
399 auto_resize: bool,
401 scrollbars: bool,
403 on_input: Option<InputHandler<A>>,
405 state_sync: Option<StateSync>,
407 resize_sync: Option<ResizeSync>,
409 geometry_sync: Option<GeometrySync>,
411}
412
413crate::impl_layout_builders!(Terminal);
414
415impl<A: 'static> Terminal<A> {
416 pub fn new(state: impl Into<Signal<TerminalState>>) -> Self {
431 let style = TerminalWidgetStyle::default();
432 Self {
433 layout: LayoutStyle::default()
434 .width(style.width)
435 .height(style.height),
436 flex_item: FlexItemStyle::default(),
437 state: state.into(),
438 style,
439 initial_scroll_y: 0.0,
440 selection: None,
441 selection_mode: TerminalSelectionMode::Character,
442 follow_output: true,
443 auto_resize: true,
444 scrollbars: true,
445 on_input: None,
446 state_sync: None,
447 resize_sync: None,
448 geometry_sync: None,
449 }
450 }
451
452 pub fn terminal_style(mut self, style: TerminalWidgetStyle) -> Self {
468 self.layout = self.layout.width(style.width).height(style.height);
469 self.style = style;
470 self
471 }
472
473 pub fn initial_scroll_y(mut self, scroll_y: f32) -> Self {
489 self.initial_scroll_y = scroll_y.max(0.0);
490 self
491 }
492
493 pub fn selection(mut self, selection: TerminalSelection) -> Self {
512 self.selection = Some(selection);
513 self
514 }
515
516 pub fn selection_mode(mut self, mode: TerminalSelectionMode) -> Self {
531 self.selection_mode = mode;
532 self
533 }
534
535 pub fn follow_output(mut self, follow_output: bool) -> Self {
550 self.follow_output = follow_output;
551 self
552 }
553
554 pub fn jump_bottom(mut self) -> Self {
568 self.initial_scroll_y = f32::MAX;
569 self.follow_output = true;
570 self
571 }
572
573 pub fn auto_resize(mut self, auto_resize: bool) -> Self {
588 self.auto_resize = auto_resize;
589 self
590 }
591
592 pub fn scrollbars(mut self, scrollbars: bool) -> Self {
606 self.scrollbars = scrollbars;
607 self
608 }
609
610 pub fn on_input(mut self, f: impl Fn(Vec<u8>) -> A + 'static) -> Self {
627 self.on_input = Some(Rc::new(move |ctx, bytes| ctx.dispatch(f(bytes))));
628 self
629 }
630
631 pub fn on_input_ctx(mut self, f: impl Fn(&mut EventCtx<A>, Vec<u8>) + 'static) -> Self {
646 self.on_input = Some(Rc::new(f));
647 self
648 }
649
650 pub fn sync_state_from(mut self, f: impl Fn() -> Option<TerminalState> + 'static) -> Self {
668 self.state_sync = Some(Rc::new(f));
669 self
670 }
671
672 pub fn sync_resize_to(
689 mut self,
690 f: impl Fn(TerminalViewportSize) -> Option<TerminalState> + 'static,
691 ) -> Self {
692 self.resize_sync = Some(Rc::new(f));
693 self
694 }
695
696 pub fn sync_geometry_to(
713 mut self,
714 f: impl Fn(TerminalGeometry) -> Option<TerminalState> + 'static,
715 ) -> Self {
716 self.geometry_sync = Some(Rc::new(f));
717 self
718 }
719}
720
721struct TerminalComponent<A> {
723 layout: LayoutStyle,
725 state: Signal<TerminalState>,
727 style: TerminalWidgetStyle,
729 initial_scroll_y: f32,
731 selection: Option<TerminalSelection>,
733 selection_mode: TerminalSelectionMode,
735 follow_output: bool,
737 auto_resize: bool,
739 scrollbars: bool,
741 on_input: Option<InputHandler<A>>,
743 state_sync: Option<StateSync>,
745 resize_sync: Option<ResizeSync>,
747 geometry_sync: Option<GeometrySync>,
749}
750
751impl<A: 'static> ComponentNode<A> for TerminalComponent<A> {
752 fn build(&self, context: &mut Context<A>) -> View<A> {
753 View::leaf(TerminalWidget {
754 layout: self.layout,
755 state: self.state.clone(),
756 scroll: context.signal_with_invalidation(
757 ScrollState::with_offset(Offset::new(0.0, self.initial_scroll_y)),
758 Invalidation::Paint,
759 ),
760 last_geometry: context.signal_with_invalidation(None, Invalidation::Paint),
761 last_resize_state_size: context.signal_with_invalidation(None, Invalidation::Paint),
762 follow_output: context
763 .signal_with_invalidation(self.follow_output, Invalidation::Paint),
764 last_line_count: context.signal_with_invalidation(usize::MAX, Invalidation::Paint),
765 selection: context.signal(self.selection),
766 selection_mode: context.signal(self.selection_mode),
767 drag_anchor: context.signal(None),
768 mouse_button: context.signal(None),
769 last_click: context.signal(None),
770 click_count: context.signal(0),
771 scrollbar_interaction: context
772 .signal_with_invalidation(ScrollbarInteraction::default(), Invalidation::Paint),
773 style: self.style.clone(),
774 behavior: ScrollBehavior::new(ScrollAxes::VERTICAL)
775 .with_line_px(self.style.line_height),
776 auto_resize: self.auto_resize,
777 scrollbars: self.scrollbars,
778 on_input: self.on_input.clone(),
779 state_sync: self.state_sync.clone(),
780 resize_sync: self.resize_sync.clone(),
781 geometry_sync: self.geometry_sync.clone(),
782 pending_layout: RefCell::new(None),
783 })
784 }
785}
786
787impl<A: 'static> IntoView<A> for Terminal<A> {
788 fn into_view(self) -> View<A> {
789 finish_view_sized(
790 View::component(TerminalComponent {
791 layout: self.layout,
792 state: self.state,
793 style: self.style,
794 initial_scroll_y: self.initial_scroll_y,
795 selection: self.selection,
796 selection_mode: self.selection_mode,
797 follow_output: self.follow_output,
798 auto_resize: self.auto_resize,
799 scrollbars: self.scrollbars,
800 on_input: self.on_input,
801 state_sync: self.state_sync,
802 resize_sync: self.resize_sync,
803 geometry_sync: self.geometry_sync,
804 }),
805 self.flex_item,
806 LayoutSizeHint::from_layout(self.layout),
807 )
808 }
809}
810
811struct TerminalWidget<A> {
813 layout: LayoutStyle,
815 state: Signal<TerminalState>,
817 scroll: Signal<ScrollState>,
819 last_geometry: Signal<Option<TerminalGeometry>>,
821 last_resize_state_size: Signal<Option<TerminalSize>>,
823 follow_output: Signal<bool>,
825 last_line_count: Signal<usize>,
827 selection: Signal<Option<TerminalSelection>>,
829 selection_mode: Signal<TerminalSelectionMode>,
831 drag_anchor: Signal<Option<TerminalPosition>>,
833 mouse_button: Signal<Option<MouseButton>>,
835 last_click: Signal<Option<TerminalPosition>>,
837 click_count: Signal<u8>,
839 scrollbar_interaction: Signal<ScrollbarInteraction>,
841 style: TerminalWidgetStyle,
843 behavior: ScrollBehavior,
845 auto_resize: bool,
847 scrollbars: bool,
849 on_input: Option<InputHandler<A>>,
851 state_sync: Option<StateSync>,
853 resize_sync: Option<ResizeSync>,
855 geometry_sync: Option<GeometrySync>,
857 pending_layout: RefCell<Option<TransactionalLayoutPending<PendingTerminalLayout>>>,
859}
860
861struct PendingTerminalLayout {
863 external_state: Option<TerminalState>,
865 geometry: TerminalGeometry,
867 scroll: ScrollState,
869 line_count: usize,
871 scrollbar_interaction: Option<ScrollbarInteraction>,
873}
874
875impl<A: 'static> Widget<A> for TerminalWidget<A> {
876 fn debug_name(&self) -> &'static str {
877 "Terminal"
878 }
879
880 fn layout(
881 &self,
882 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
883 ctx: &mut LayoutCtx<'_>,
884 _children: &mut [LayoutChild],
885 constraints: Constraints,
886 ) -> LayoutResult {
887 let retained_state = self.state.read();
888 let external_state = ctx
889 .layout_pass()
890 .is_committed()
891 .then(|| self.poll_external_state(&retained_state))
892 .flatten();
893 let effective_state = external_state.as_ref().unwrap_or(&retained_state);
894 let intrinsic = Size::new(self.style.width, self.style.height);
895 let size = apply_layout_size(intrinsic, self.layout, constraints);
896 let viewport = Rect::new(0.0, 0.0, size.w, size.h);
897 let geometry = self.geometry_for_bounds(ctx.text_system.as_deref_mut(), viewport);
898 let line_count = terminal_visual_line_count(effective_state);
899 let scroll =
900 self.viewport_state_for_lines(Size::new(size.w, size.h), geometry.metrics, line_count);
901 let geometries = self
902 .scrollbar_geometry_for_state(viewport, geometry.metrics, line_count, scroll)
903 .into_iter()
904 .collect::<Vec<_>>();
905 let mut interaction = with_untracked_reads(|| self.scrollbar_interaction.read());
906 let interaction_changed = interaction.reconcile(ctx.layout_pass(), &geometries);
907 if ctx.layout_pass().is_committed() {
908 self.pending_layout.replace(TransactionalLayoutPending::new(
909 ctx,
910 PendingTerminalLayout {
911 external_state,
912 geometry,
913 scroll,
914 line_count,
915 scrollbar_interaction: interaction_changed.then_some(interaction),
916 },
917 ));
918 }
919 LayoutResult {
920 size,
921 children: Vec::new(),
922 paint_bounds: viewport,
923 visual_bounds: viewport,
924 overlay_hit_bounds: geometries
925 .iter()
926 .map(|geometry| geometry.hit_track)
927 .collect(),
928 clip: Some(ClipShape::Rect(viewport)),
929 is_window_root_clip: false,
930 artifact: None,
931 }
932 }
933
934 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
935 let Some(pending) = self
936 .pending_layout
937 .borrow_mut()
938 .take()
939 .and_then(|pending| pending.into_committed(ctx))
940 else {
941 return;
942 };
943 if let Some(next) = pending.external_state {
944 let changed = with_untracked_reads(|| self.state.read() != next);
945 if changed {
946 self.state.set(next);
947 }
948 }
949 let state_changed = self.sync_committed_geometry(pending.geometry);
950 let (scroll, line_count) = if state_changed {
951 let line_count = with_untracked_reads(|| self.visual_line_count());
952 (
953 self.viewport_state_for_lines(
954 Size::new(bounds.w, bounds.h),
955 pending.geometry.metrics,
956 line_count,
957 ),
958 line_count,
959 )
960 } else {
961 (pending.scroll, pending.line_count)
962 };
963 self.commit_viewport_state(scroll, line_count);
964 if let Some(interaction) = pending.scrollbar_interaction {
965 self.scrollbar_interaction.set(interaction);
966 }
967 }
968
969 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
970 let state = self.state.read();
971 let lines = terminal_visual_lines(&state);
972 let Some(geometry) = self.last_geometry.read() else {
973 return;
974 };
975
976 ctx.push(DrawCmd::RRect(DrawRRect {
977 rect: bounds,
978 radius: self.style.radius.tl,
979 color: self.style.background,
980 }));
981 ctx.push(DrawCmd::Border(DrawBorder {
982 rect: bounds,
983 radius: self.style.radius,
984 border: self.style.border,
985 }));
986 if ctx.is_focused() {
987 ctx.push(DrawCmd::Border(DrawBorder {
988 rect: bounds,
989 radius: self.style.radius,
990 border: self.style.focus_ring,
991 }));
992 }
993
994 let content = self.content_rect(bounds);
995 let scroll = self.scroll.read();
996 let selection = self.selection.read().and_then(|s| s.clamp(lines.len()));
997
998 ctx.with_clip(content, |ctx| {
999 paint_terminal_state(
1000 ctx,
1001 content,
1002 TerminalPaintModel {
1003 style: &self.style,
1004 metrics: geometry.metrics,
1005 state: &state,
1006 lines: &lines,
1007 scroll,
1008 selection,
1009 },
1010 );
1011 });
1012
1013 if let Some(scrollbar) =
1014 self.scrollbar_geometry_for_state(bounds, geometry.metrics, lines.len(), scroll)
1015 {
1016 let visual = self
1017 .scrollbar_interaction
1018 .read()
1019 .visual_state(scrollbar.axis, ctx.is_hovered());
1020 paint_terminal_scrollbar(ctx, scrollbar, &self.style, visual);
1021 }
1022 }
1023
1024 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1025 if self.sync_external_state() {
1026 ctx.request_repaint();
1027 }
1028 let state = self.state.read();
1029 let line_count = terminal_visual_line_count(&state);
1030 let metrics = self.committed_metrics();
1031 self.update_viewport_for_lines_with_metrics(
1032 Size::new(bounds.w, bounds.h),
1033 metrics,
1034 line_count,
1035 );
1036
1037 if matches!(event, Event::Pointer(_)) {
1038 let geometries = self
1039 .scrollbar_geometry(bounds, metrics, line_count)
1040 .into_iter()
1041 .collect::<Vec<_>>();
1042 let current = self.scroll.read();
1043 let mut interaction = self.scrollbar_interaction.read();
1044 let response = interaction.handle_event(ctx, event, &geometries);
1045 if response.state_changed {
1046 self.scrollbar_interaction.set(interaction);
1047 }
1048 if let Some((ScrollbarAxis::Vertical, target)) = response.scroll_to {
1049 let content = self.content_rect(bounds);
1050 let scroll_metrics =
1051 self.scroll_metrics_with_cell_metrics(content, metrics, line_count);
1052 let outcome = current.scroll_to(
1053 Offset::new(0.0, target),
1054 scroll_metrics,
1055 ScrollAxes::VERTICAL,
1056 );
1057 if outcome.changed {
1058 let next = outcome.state();
1059 self.scroll.set(next);
1060 self.sync_follow_from_scroll(next, scroll_metrics);
1061 }
1062 }
1063 if response.repaint {
1064 ctx.request_repaint();
1065 }
1066 if response.consumed {
1067 ctx.stop_propagation();
1068 return;
1069 }
1070 }
1071
1072 match event {
1073 Event::Pointer(PointerEvent::Wheel {
1074 pos,
1075 delta,
1076 modifiers,
1077 ..
1078 }) => {
1079 if !bounds.contains(pos.x, pos.y) {
1080 return;
1081 }
1082 if !modifiers.shift
1083 && self.handle_terminal_mouse_event(ctx, event, bounds, line_count, &state)
1084 {
1085 return;
1086 }
1087 let content = self.content_rect(bounds);
1088 let metrics = self.scroll_metrics(content, line_count);
1089 let out = self.scroll.read().scroll_by(
1090 self.behavior.wheel_delta_with_modifiers(*delta, *modifiers),
1091 metrics,
1092 ScrollAxes::VERTICAL,
1093 );
1094 if out.changed {
1095 let next = out.state();
1096 self.scroll.set(next);
1097 self.sync_follow_from_scroll(next, metrics);
1098 ctx.request_repaint();
1099 ctx.stop_propagation();
1100 }
1101 }
1102 Event::Pointer(PointerEvent::Button {
1103 pos,
1104 button: MouseButton::Left,
1105 pressed: true,
1106 modifiers,
1107 ..
1108 }) if bounds.contains(pos.x, pos.y) => {
1109 if !modifiers.shift
1110 && self.handle_terminal_mouse_event(ctx, event, bounds, line_count, &state)
1111 {
1112 return;
1113 }
1114 if let Some(anchor) = self.position_at(bounds, pos.x, pos.y, line_count) {
1115 let mode = self.click_selection_mode(anchor);
1116 self.drag_anchor.set(Some(anchor));
1117 self.selection
1118 .set(Some(selection_for_mode(&state, anchor, mode)));
1119 self.selection_mode.set(mode);
1120 ctx.request_repaint();
1121 ctx.stop_propagation();
1122 }
1123 }
1124 Event::Pointer(PointerEvent::Moved { pos, modifiers }) => {
1125 if !modifiers.shift
1126 && self.handle_terminal_mouse_event(ctx, event, bounds, line_count, &state)
1127 {
1128 return;
1129 }
1130 let Some(anchor) = self.drag_anchor.read() else {
1131 return;
1132 };
1133 if let Some(focus) = self.position_at(bounds, pos.x, pos.y, line_count) {
1134 self.selection
1135 .set(Some(TerminalSelection::new(anchor, focus)));
1136 ctx.request_repaint();
1137 ctx.stop_propagation();
1138 }
1139 }
1140 Event::Pointer(PointerEvent::Button {
1141 button: MouseButton::Left,
1142 pressed: false,
1143 modifiers,
1144 ..
1145 }) => {
1146 if !modifiers.shift {
1147 let handled =
1148 self.handle_terminal_mouse_event(ctx, event, bounds, line_count, &state);
1149 self.mouse_button.set(None);
1150 if handled {
1151 return;
1152 }
1153 }
1154 self.drag_anchor.set(None);
1155 }
1156 Event::Keyboard(key) if key.state == KeyState::Pressed => {
1157 if self.handle_keyboard_scroll(ctx, key, bounds, line_count) {
1158 return;
1159 }
1160 if self.handle_clipboard_shortcut(ctx, key, &state) {
1161 return;
1162 }
1163 if let (Some(handler), Some(bytes)) = (
1164 self.on_input.as_ref(),
1165 terminal_key_bytes_with_modes(key, &state.modes),
1166 ) {
1167 handler(ctx, bytes);
1168 ctx.request_repaint();
1169 ctx.stop_propagation();
1170 return;
1171 }
1172 self.handle_readonly_keyboard_scroll(ctx, key, bounds, line_count);
1173 }
1174 _ => {}
1175 }
1176 }
1177
1178 fn focus_policy(&self) -> FocusPolicy {
1179 FocusPolicy::Focusable
1180 }
1181
1182 fn input_role(&self) -> InputRole {
1183 InputRole::TextMultiLine
1184 }
1185
1186 fn ime_cursor_rect(&self, bounds: Rect, _layout: &LayoutResult) -> Option<Rect> {
1187 let state = self.state.read();
1188 let lines = terminal_visual_lines(&state);
1189 cursor_rect(
1190 bounds,
1191 &self.style,
1192 self.committed_metrics(),
1193 &state,
1194 &lines,
1195 self.scroll.read(),
1196 )
1197 }
1198}
1199
1200impl<A: 'static> TerminalWidget<A> {
1201 fn poll_external_state(&self, current: &TerminalState) -> Option<TerminalState> {
1203 self.state_sync
1204 .as_ref()
1205 .and_then(|sync| sync())
1206 .filter(|next| next != current)
1207 }
1208
1209 fn sync_external_state(&self) -> bool {
1211 let current = with_untracked_reads(|| self.state.read());
1212 let Some(next) = self.poll_external_state(¤t) else {
1213 return false;
1214 };
1215 self.state.set(next);
1216 true
1217 }
1218
1219 fn sync_committed_geometry(&self, geometry: TerminalGeometry) -> bool {
1221 let (geometry_changed, state_size, state_size_changed) = with_untracked_reads(|| {
1222 let state_size = self.state.read().active_screen().size();
1223 (
1224 self.last_geometry.read() != Some(geometry),
1225 state_size,
1226 self.last_resize_state_size.read() != Some(state_size),
1227 )
1228 });
1229 if !geometry_changed && !state_size_changed {
1230 return false;
1231 }
1232 self.last_geometry.set(Some(geometry));
1233 self.last_resize_state_size.set(Some(state_size));
1234
1235 tracing::debug!(
1236 target: "ailloli_ui_terminal_geometry",
1237 bounds_w = geometry.pixel_width,
1238 bounds_h = geometry.pixel_height,
1239 cell_w = geometry.metrics.cell_width,
1240 cell_h = geometry.metrics.cell_height,
1241 cols = geometry.cols,
1242 rows = geometry.rows,
1243 "terminal geometry committed"
1244 );
1245
1246 if let Some(sync) = self.geometry_sync.as_ref() {
1247 if let Some(next) = sync(geometry) {
1248 if with_untracked_reads(|| self.state.read() != next) {
1249 self.last_resize_state_size
1250 .set(Some(next.active_screen().size()));
1251 self.state.set(next);
1252 return true;
1253 }
1254 }
1255 return false;
1256 }
1257
1258 if let Some(sync) = self.resize_sync.as_ref() {
1259 let viewport = geometry.viewport_size();
1260 if let Some(next) = sync(viewport) {
1261 if with_untracked_reads(|| self.state.read() != next) {
1262 self.last_resize_state_size
1263 .set(Some(next.active_screen().size()));
1264 self.state.set(next);
1265 return true;
1266 }
1267 }
1268 return false;
1269 }
1270
1271 if self.auto_resize {
1272 return self.resize_local_state_to(geometry.terminal_size());
1273 }
1274
1275 false
1276 }
1277
1278 fn resize_local_state_to(&self, next: TerminalSize) -> bool {
1280 let current = with_untracked_reads(|| self.state.read().active_screen().size());
1281 if current == next {
1282 return false;
1283 }
1284 self.state.update(|state| state.resize(next));
1285 self.last_resize_state_size.set(Some(next));
1286 true
1287 }
1288
1289 fn content_rect(&self, bounds: Rect) -> Rect {
1291 let reserve = if self.scrollbars {
1292 self.style.scrollbar_width + self.style.scrollbar_inset * 2.0
1293 } else {
1294 0.0
1295 };
1296 Rect::new(
1297 bounds.x + self.style.padding_x,
1298 bounds.y + self.style.padding_y,
1299 (bounds.w - self.style.padding_x * 2.0 - reserve).max(0.0),
1300 (bounds.h - self.style.padding_y * 2.0).max(0.0),
1301 )
1302 }
1303
1304 fn geometry_for_bounds(
1306 &self,
1307 text_system: Option<&mut TextSystem>,
1308 bounds: Rect,
1309 ) -> TerminalGeometry {
1310 let metrics = terminal_cell_metrics(text_system, &self.style);
1311 let content = self.content_rect(bounds);
1312 terminal_geometry_for_content(content, metrics)
1313 }
1314
1315 fn committed_metrics(&self) -> TerminalCellMetrics {
1317 self.last_geometry
1318 .read()
1319 .map(|geometry| geometry.metrics)
1320 .unwrap_or_else(|| terminal_cell_metrics(None, &self.style))
1321 }
1322
1323 fn visual_line_count(&self) -> usize {
1325 terminal_visual_line_count(&self.state.read())
1326 }
1327
1328 fn scroll_metrics(&self, content: Rect, line_count: usize) -> ScrollMetrics {
1330 self.scroll_metrics_with_cell_metrics(content, self.committed_metrics(), line_count)
1331 }
1332
1333 fn scrollbar_geometry(
1335 &self,
1336 bounds: Rect,
1337 cell_metrics: TerminalCellMetrics,
1338 line_count: usize,
1339 ) -> Option<ScrollbarGeometry> {
1340 let scroll = self.scroll.read();
1341 self.scrollbar_geometry_for_state(bounds, cell_metrics, line_count, scroll)
1342 }
1343
1344 fn scrollbar_geometry_for_state(
1346 &self,
1347 bounds: Rect,
1348 cell_metrics: TerminalCellMetrics,
1349 line_count: usize,
1350 scroll: ScrollState,
1351 ) -> Option<ScrollbarGeometry> {
1352 if !self.scrollbars {
1353 return None;
1354 }
1355 let content = self.content_rect(bounds);
1356 ScrollbarGeometrySpec::new(
1357 ScrollbarAxis::Vertical,
1358 bounds,
1359 self.scroll_metrics_with_cell_metrics(content, cell_metrics, line_count),
1360 scroll,
1361 )
1362 .with_paint_metrics(self.style.scrollbar_width, 24.0, self.style.scrollbar_inset)
1363 .with_hit_thickness(16.0)
1364 .resolve()
1365 }
1366
1367 fn update_viewport_for_lines_with_metrics(
1369 &self,
1370 size: Size,
1371 metrics: TerminalCellMetrics,
1372 line_count: usize,
1373 ) {
1374 let scroll = self.viewport_state_for_lines(size, metrics, line_count);
1375 self.commit_viewport_state(scroll, line_count);
1376 }
1377
1378 fn viewport_state_for_lines(
1380 &self,
1381 size: Size,
1382 metrics: TerminalCellMetrics,
1383 line_count: usize,
1384 ) -> ScrollState {
1385 let content = self.content_rect(Rect::new(0.0, 0.0, size.w, size.h));
1386 let metrics = self.scroll_metrics_with_cell_metrics(content, metrics, line_count);
1387 let (previous, mut next, follow_output) = with_untracked_reads(|| {
1388 (
1389 self.last_line_count.read(),
1390 self.scroll.read(),
1391 self.follow_output.read(),
1392 )
1393 });
1394 if previous != line_count && follow_output {
1395 next = next
1396 .scroll_to(metrics.max_offset(), metrics, ScrollAxes::VERTICAL)
1397 .state();
1398 }
1399 next.clamp_to(metrics, ScrollAxes::VERTICAL).state()
1400 }
1401
1402 fn commit_viewport_state(&self, scroll: ScrollState, line_count: usize) {
1404 let (retained_scroll, previous) =
1405 with_untracked_reads(|| (self.scroll.read(), self.last_line_count.read()));
1406 if retained_scroll != scroll {
1407 self.scroll.set(scroll);
1408 }
1409 if previous != line_count {
1410 self.last_line_count.set(line_count);
1411 }
1412 }
1413
1414 fn scroll_metrics_with_cell_metrics(
1416 &self,
1417 content: Rect,
1418 metrics: TerminalCellMetrics,
1419 line_count: usize,
1420 ) -> ScrollMetrics {
1421 ScrollMetrics::new(
1422 Size::new(content.w, content.h),
1423 Size::new(content.w, line_count as f32 * metrics.cell_height),
1424 )
1425 }
1426
1427 fn sync_follow_from_scroll(&self, scroll: ScrollState, metrics: ScrollMetrics) {
1429 let max_y = metrics.max_offset().y;
1430 self.follow_output
1431 .set((max_y - scroll.offset.y).abs() <= self.committed_metrics().cell_height);
1432 }
1433
1434 fn click_selection_mode(&self, pos: TerminalPosition) -> TerminalSelectionMode {
1436 let count = if self.last_click.read() == Some(pos) {
1437 self.click_count.read().saturating_add(1)
1438 } else {
1439 1
1440 };
1441 self.last_click.set(Some(pos));
1442 self.click_count.set(count.min(3));
1443 match count {
1444 1 => TerminalSelectionMode::Character,
1445 2 => TerminalSelectionMode::Word,
1446 _ => TerminalSelectionMode::Line,
1447 }
1448 }
1449
1450 fn position_at(
1452 &self,
1453 bounds: Rect,
1454 x: f32,
1455 y: f32,
1456 line_count: usize,
1457 ) -> Option<TerminalPosition> {
1458 if line_count == 0 {
1459 return None;
1460 }
1461 let content = self.content_rect(bounds);
1462 let metrics = self.committed_metrics();
1463 if !content.contains(x, y) {
1464 return None;
1465 }
1466 let scroll_y = self.scroll.read().offset.y;
1467 let line = ((y - content.y + scroll_y) / metrics.cell_height)
1468 .floor()
1469 .max(0.0) as usize;
1470 let column = ((x - content.x) / metrics.cell_width).floor().max(0.0) as usize;
1471 Some(TerminalPosition::new(line.min(line_count - 1), column))
1472 }
1473
1474 fn handle_keyboard_scroll(
1476 &self,
1477 ctx: &mut EventCtx<A>,
1478 key: &KeyEvent,
1479 bounds: Rect,
1480 line_count: usize,
1481 ) -> bool {
1482 if !key.modifiers.shift {
1483 return false;
1484 }
1485 match key.key {
1486 Key::Named(NamedKey::PageUp)
1487 | Key::Named(NamedKey::PageDown)
1488 | Key::Named(NamedKey::Home)
1489 | Key::Named(NamedKey::End) => {
1490 self.scroll_for_key(ctx, &key.key, bounds, line_count);
1491 true
1492 }
1493 _ => false,
1494 }
1495 }
1496
1497 fn handle_readonly_keyboard_scroll(
1499 &self,
1500 ctx: &mut EventCtx<A>,
1501 key: &KeyEvent,
1502 bounds: Rect,
1503 line_count: usize,
1504 ) {
1505 match key.key {
1506 Key::Named(NamedKey::ArrowUp)
1507 | Key::Named(NamedKey::ArrowDown)
1508 | Key::Named(NamedKey::PageUp)
1509 | Key::Named(NamedKey::PageDown)
1510 | Key::Named(NamedKey::Home)
1511 | Key::Named(NamedKey::End) => {
1512 self.scroll_for_key(ctx, &key.key, bounds, line_count);
1513 }
1514 _ => {}
1515 }
1516 }
1517
1518 fn scroll_for_key(&self, ctx: &mut EventCtx<A>, key: &Key, bounds: Rect, line_count: usize) {
1520 let content = self.content_rect(bounds);
1521 let cell_metrics = self.committed_metrics();
1522 let metrics = self.scroll_metrics(content, line_count);
1523 let out = match key {
1524 Key::Named(NamedKey::Home) => {
1525 self.scroll
1526 .read()
1527 .scroll_to(Offset::new(0.0, 0.0), metrics, ScrollAxes::VERTICAL)
1528 }
1529 Key::Named(NamedKey::End) => {
1530 self.scroll
1531 .read()
1532 .scroll_to(metrics.max_offset(), metrics, ScrollAxes::VERTICAL)
1533 }
1534 Key::Named(NamedKey::ArrowUp) => self.scroll.read().scroll_by(
1535 Offset::new(0.0, -cell_metrics.cell_height),
1536 metrics,
1537 ScrollAxes::VERTICAL,
1538 ),
1539 Key::Named(NamedKey::ArrowDown) => self.scroll.read().scroll_by(
1540 Offset::new(0.0, cell_metrics.cell_height),
1541 metrics,
1542 ScrollAxes::VERTICAL,
1543 ),
1544 Key::Named(NamedKey::PageUp) => self.scroll.read().scroll_by(
1545 Offset::new(0.0, -content.h * 0.86),
1546 metrics,
1547 ScrollAxes::VERTICAL,
1548 ),
1549 Key::Named(NamedKey::PageDown) => self.scroll.read().scroll_by(
1550 Offset::new(0.0, content.h * 0.86),
1551 metrics,
1552 ScrollAxes::VERTICAL,
1553 ),
1554 _ => return,
1555 };
1556 if out.changed {
1557 let next = out.state();
1558 self.scroll.set(next);
1559 self.sync_follow_from_scroll(next, metrics);
1560 ctx.request_repaint();
1561 ctx.stop_propagation();
1562 }
1563 }
1564
1565 fn handle_clipboard_shortcut(
1567 &self,
1568 ctx: &mut EventCtx<A>,
1569 key: &KeyEvent,
1570 state: &TerminalState,
1571 ) -> bool {
1572 if !(key.modifiers.ctrl && key.modifiers.shift) {
1573 return false;
1574 }
1575 match key_character_upper(key).as_deref() {
1576 Some("C") => {
1577 if let Some(selection) = self.selection.read() {
1578 let text = terminal_selection_text(state, selection);
1579 if !text.is_empty() {
1580 let _ = ctx.write_clipboard_text(&text);
1581 }
1582 }
1583 ctx.stop_propagation();
1584 true
1585 }
1586 Some("V") => {
1587 if let (Some(handler), Some(text)) =
1588 (self.on_input.as_ref(), ctx.read_clipboard_text())
1589 {
1590 handler(ctx, terminal_paste_bytes(&text, &state.modes));
1591 ctx.request_repaint();
1592 }
1593 ctx.stop_propagation();
1594 true
1595 }
1596 _ => false,
1597 }
1598 }
1599
1600 fn handle_terminal_mouse_event(
1602 &self,
1603 ctx: &mut EventCtx<A>,
1604 event: &Event,
1605 bounds: Rect,
1606 line_count: usize,
1607 state: &TerminalState,
1608 ) -> bool {
1609 if state.modes.mouse_tracking == TerminalMouseTrackingMode::Off {
1610 return false;
1611 }
1612 let content = self.content_rect(bounds);
1613 let metrics = self.committed_metrics();
1614 let mouse_layout = TerminalMouseLayout {
1615 content,
1616 metrics,
1617 scroll: self.scroll.read(),
1618 line_count,
1619 };
1620 let Some(bytes) =
1621 terminal_mouse_bytes_from_event(event, state, mouse_layout, self.mouse_button.read())
1622 else {
1623 return false;
1624 };
1625
1626 if let Event::Pointer(PointerEvent::Button {
1627 button,
1628 pressed: true,
1629 ..
1630 }) = event
1631 {
1632 self.mouse_button.set(Some(*button));
1633 }
1634
1635 if let Some(handler) = self.on_input.as_ref() {
1636 handler(ctx, bytes);
1637 }
1638 ctx.request_repaint();
1639 ctx.stop_propagation();
1640 true
1641 }
1642}
1643
1644fn viewport_pixel_extent_u32(value: f32) -> u32 {
1646 if !value.is_finite() || value <= 0.0 {
1647 return 0;
1648 }
1649 value.round().min(u32::MAX as f32) as u32
1650}
1651
1652fn terminal_cell_metrics(
1654 text_system: Option<&mut TextSystem>,
1655 style: &TerminalWidgetStyle,
1656) -> TerminalCellMetrics {
1657 let fallback = TerminalCellMetrics::new(
1658 style.char_width.max(1.0),
1659 style.line_height.max(1.0),
1660 style.text.px_size as f32,
1661 );
1662 let Some(text_system) = text_system else {
1663 return fallback;
1664 };
1665 let prepared = terminal_layout(text_system, "M", &[], style);
1666 let cell_width = prepared.width().ceil().max(1.0);
1667 let baseline = prepared
1668 .lines
1669 .first()
1670 .map(|line| line.baseline_y)
1671 .unwrap_or(fallback.baseline)
1672 .max(1.0);
1673 TerminalCellMetrics::new(cell_width, fallback.cell_height, baseline)
1674}
1675
1676fn terminal_geometry_for_content(content: Rect, metrics: TerminalCellMetrics) -> TerminalGeometry {
1678 let rows = terminal_grid_extent(content.h, metrics.cell_height);
1679 let cols = terminal_grid_extent(content.w, metrics.cell_width);
1680 TerminalGeometry::new(
1681 viewport_pixel_extent_u32(content.w),
1682 viewport_pixel_extent_u32(content.h),
1683 metrics,
1684 cols,
1685 rows,
1686 )
1687}
1688
1689fn terminal_grid_extent(px: f32, cell: f32) -> u16 {
1691 if !px.is_finite() || !cell.is_finite() || px <= 0.0 || cell <= 0.0 {
1692 return 1;
1693 }
1694 ((px / cell).floor().max(1.0).min(u16::MAX as f32)) as u16
1695}
1696
1697fn terminal_visual_lines(state: &TerminalState) -> Vec<&CoreTerminalLine> {
1699 match state.active_screen {
1700 ActiveScreen::Normal => state
1701 .scrollback
1702 .iter()
1703 .chain(state.screen.lines.iter())
1704 .collect(),
1705 ActiveScreen::Alternate => state.alternate_screen.lines.iter().collect(),
1706 }
1707}
1708
1709fn terminal_visual_line_count(state: &TerminalState) -> usize {
1711 match state.active_screen {
1712 ActiveScreen::Normal => state.scrollback.len() + state.screen.lines.len(),
1713 ActiveScreen::Alternate => state.alternate_screen.lines.len(),
1714 }
1715}
1716
1717fn terminal_cursor_visual_line(state: &TerminalState) -> usize {
1719 match state.active_screen {
1720 ActiveScreen::Normal => state.scrollback.len() + state.cursor.row,
1721 ActiveScreen::Alternate => state.cursor.row,
1722 }
1723}
1724
1725pub fn terminal_selection_text(state: &TerminalState, selection: TerminalSelection) -> String {
1750 let lines = terminal_visual_lines(state);
1751 let Some(selection) = selection.clamp(lines.len()) else {
1752 return String::new();
1753 };
1754 let (start, end) = selection.normalized();
1755 let mut selected = Vec::new();
1756 for (line_idx, line) in lines.iter().enumerate().take(end.line + 1).skip(start.line) {
1757 let line_len = line.len();
1758 let start_col = if line_idx == start.line {
1759 start.column.min(line_len)
1760 } else {
1761 0
1762 };
1763 let end_col = if line_idx == end.line {
1764 end.column.min(line_len)
1765 } else {
1766 line_len
1767 };
1768 selected.push(terminal_line_text_range(line, start_col, end_col));
1769 }
1770 selected.join("\n")
1771}
1772
1773fn terminal_line_text_range(line: &CoreTerminalLine, start_col: usize, end_col: usize) -> String {
1775 if start_col >= end_col {
1776 return String::new();
1777 }
1778 let mut text = String::new();
1779 for (col, cell) in line.cells.iter().enumerate() {
1780 if col < start_col || col >= end_col || cell.width == CellWidth::WideTrailing {
1781 continue;
1782 }
1783 text.push_str(&cell.text);
1784 }
1785 text.trim_end_matches(' ').to_string()
1786}
1787
1788fn selection_for_mode(
1790 state: &TerminalState,
1791 pos: TerminalPosition,
1792 mode: TerminalSelectionMode,
1793) -> TerminalSelection {
1794 match mode {
1795 TerminalSelectionMode::Character => TerminalSelection::new(pos, pos),
1796 TerminalSelectionMode::Word => word_selection_at(state, pos),
1797 TerminalSelectionMode::Line => TerminalSelection::lines(pos.line, pos.line),
1798 }
1799}
1800
1801fn word_selection_at(state: &TerminalState, pos: TerminalPosition) -> TerminalSelection {
1803 let lines = terminal_visual_lines(state);
1804 let Some(line) = lines.get(pos.line) else {
1805 return TerminalSelection::new(pos, pos);
1806 };
1807 let len = line.len();
1808 if pos.column >= len {
1809 return TerminalSelection::new(
1810 TerminalPosition::new(pos.line, len),
1811 TerminalPosition::new(pos.line, len),
1812 );
1813 }
1814 let mut start = pos.column;
1815 let mut end = pos.column + 1;
1816 if !terminal_word_cell(line, pos.column) {
1817 return TerminalSelection::new(
1818 TerminalPosition::new(pos.line, start),
1819 TerminalPosition::new(pos.line, end.min(len)),
1820 );
1821 }
1822 while start > 0 && terminal_word_cell(line, start - 1) {
1823 start -= 1;
1824 }
1825 while end < len && terminal_word_cell(line, end) {
1826 end += 1;
1827 }
1828 TerminalSelection::new(
1829 TerminalPosition::new(pos.line, start),
1830 TerminalPosition::new(pos.line, end),
1831 )
1832}
1833
1834fn terminal_word_cell(line: &CoreTerminalLine, col: usize) -> bool {
1836 let Some(cell) = line.cell(col) else {
1837 return false;
1838 };
1839 if cell.width == CellWidth::WideTrailing {
1840 return false;
1841 }
1842 cell.text
1843 .chars()
1844 .any(|ch| ch.is_alphanumeric() || matches!(ch, '_' | '-' | '.' | '/' | ':'))
1845}
1846
1847fn terminal_paste_bytes(text: &str, modes: &TerminalModes) -> Vec<u8> {
1849 if modes.bracketed_paste {
1850 let mut bytes = Vec::with_capacity(text.len() + 12);
1851 bytes.extend_from_slice(b"\x1b[200~");
1852 bytes.extend_from_slice(text.as_bytes());
1853 bytes.extend_from_slice(b"\x1b[201~");
1854 bytes
1855 } else {
1856 text.as_bytes().to_vec()
1857 }
1858}
1859
1860fn key_character_upper(key: &KeyEvent) -> Option<String> {
1862 match &key.key {
1863 Key::Character(ch) => Some(ch.to_ascii_uppercase()),
1864 _ => key.text.as_ref().map(|text| text.to_ascii_uppercase()),
1865 }
1866}
1867
1868struct TerminalPaintModel<'a> {
1870 style: &'a TerminalWidgetStyle,
1872 metrics: TerminalCellMetrics,
1874 state: &'a TerminalState,
1876 lines: &'a [&'a CoreTerminalLine],
1878 scroll: ScrollState,
1880 selection: Option<TerminalSelection>,
1882}
1883
1884fn paint_terminal_state(ctx: &mut PaintCtx<'_>, content: Rect, model: TerminalPaintModel<'_>) {
1886 let TerminalPaintModel {
1887 style,
1888 metrics,
1889 state,
1890 lines,
1891 scroll,
1892 selection,
1893 } = model;
1894
1895 if lines.is_empty() || metrics.cell_height <= 0.0 {
1896 return;
1897 }
1898
1899 let first = (scroll.offset.y / metrics.cell_height).floor().max(0.0) as usize;
1900 let offset_y = scroll.offset.y - first as f32 * metrics.cell_height;
1901 let visible = (content.h / metrics.cell_height).ceil().max(0.0) as usize + 2;
1902 let end = (first + visible).min(lines.len());
1903 let global_lines = terminal_visual_line_global_indices(state);
1904
1905 for line_idx in first..end {
1906 let row_y = content.y - offset_y + (line_idx - first) as f32 * metrics.cell_height;
1907 if row_y + metrics.cell_height < content.y || row_y > content.bottom() {
1908 continue;
1909 }
1910
1911 let diagnostic = terminal_diagnostic_for_visual_line(state, &global_lines, line_idx);
1912 if let Some(diagnostic) = diagnostic {
1913 paint_terminal_diagnostic_row(ctx, content, row_y, style, metrics, diagnostic);
1914 }
1915
1916 let (text, spans, backgrounds) = terminal_line_render_parts(lines[line_idx], style);
1917 for bg in backgrounds {
1918 ctx.push(DrawCmd::Rect(DrawRect {
1919 rect: Rect::new(
1920 content.x + bg.col as f32 * metrics.cell_width,
1921 row_y,
1922 bg.cols as f32 * metrics.cell_width,
1923 metrics.cell_height,
1924 ),
1925 color: bg.color,
1926 }));
1927 }
1928
1929 if let Some(selection) = selection.and_then(|s| s.clamp(lines.len())) {
1930 if let Some((start_col, end_col)) =
1931 selection_columns_for_line(selection, line_idx, lines[line_idx].len())
1932 {
1933 ctx.push(DrawCmd::Rect(DrawRect {
1934 rect: highlight_rect(content, row_y, style, metrics, start_col, end_col),
1935 color: style.selection_background,
1936 }));
1937 }
1938 }
1939
1940 paint_terminal_text(ctx, content.x, row_y, &text, &spans, style);
1941 if let Some(diagnostic) = diagnostic {
1942 paint_terminal_diagnostic_badge(ctx, content, row_y, style, metrics, diagnostic);
1943 }
1944 }
1945
1946 if let Some(rect) = cursor_rect_from_lines(content, style, metrics, state, lines, scroll) {
1947 ctx.push(DrawCmd::Rect(DrawRect {
1948 rect,
1949 color: style.cursor.with_alpha(0.72),
1950 }));
1951 }
1952}
1953
1954fn terminal_diagnostic_for_visual_line<'a>(
1956 state: &'a TerminalState,
1957 global_lines: &[Option<u64>],
1958 visual_line: usize,
1959) -> Option<&'a TerminalDiagnostic> {
1960 let global = global_lines.get(visual_line).copied().flatten()?;
1961 state.diagnostics.iter().find(|diagnostic| {
1962 diagnostic.source_range.start_line <= global && global <= diagnostic.source_range.end_line
1963 })
1964}
1965
1966fn paint_terminal_diagnostic_row(
1968 ctx: &mut PaintCtx<'_>,
1969 content: Rect,
1970 row_y: f32,
1971 style: &TerminalWidgetStyle,
1972 metrics: TerminalCellMetrics,
1973 diagnostic: &TerminalDiagnostic,
1974) {
1975 let color = terminal_diagnostic_color(style, diagnostic.severity);
1976 ctx.push(DrawCmd::Rect(DrawRect {
1977 rect: Rect::new(content.x, row_y, content.w, metrics.cell_height),
1978 color: color.with_alpha(0.10),
1979 }));
1980 ctx.push(DrawCmd::RRect(DrawRRect {
1981 rect: Rect::new(
1982 content.x,
1983 row_y + 3.0,
1984 4.0,
1985 (metrics.cell_height - 6.0).max(1.0),
1986 ),
1987 radius: 2.0,
1988 color,
1989 }));
1990}
1991
1992fn paint_terminal_diagnostic_badge(
1994 ctx: &mut PaintCtx<'_>,
1995 content: Rect,
1996 row_y: f32,
1997 style: &TerminalWidgetStyle,
1998 metrics: TerminalCellMetrics,
1999 diagnostic: &TerminalDiagnostic,
2000) {
2001 let label = terminal_diagnostic_label(diagnostic.severity);
2002 let color = terminal_diagnostic_color(style, diagnostic.severity);
2003 let badge_w = 34.0;
2004 let badge = Rect::new(
2005 content.right() - badge_w - 4.0,
2006 row_y + 3.0,
2007 badge_w,
2008 (metrics.cell_height - 6.0).max(12.0),
2009 );
2010 ctx.push(DrawCmd::RRect(DrawRRect {
2011 rect: badge,
2012 radius: 5.0,
2013 color: color.with_alpha(0.22),
2014 }));
2015 let spans = [StyledTextSpan {
2016 range: 0..label.len(),
2017 style: TextStyle::new(style.text.font, 10, color),
2018 }];
2019 paint_terminal_text(ctx, badge.x + 6.0, badge.y - 1.0, label, &spans, style);
2020}
2021
2022fn terminal_diagnostic_label(severity: TerminalDiagnosticSeverity) -> &'static str {
2024 match severity {
2025 TerminalDiagnosticSeverity::Error => "ERR",
2026 TerminalDiagnosticSeverity::Warning => "WARN",
2027 TerminalDiagnosticSeverity::Info => "INFO",
2028 TerminalDiagnosticSeverity::Hint => "HINT",
2029 }
2030}
2031
2032fn terminal_diagnostic_color(
2034 style: &TerminalWidgetStyle,
2035 severity: TerminalDiagnosticSeverity,
2036) -> Color {
2037 match severity {
2038 TerminalDiagnosticSeverity::Error => style.diagnostic_error,
2039 TerminalDiagnosticSeverity::Warning => style.diagnostic_warning,
2040 TerminalDiagnosticSeverity::Info => style.diagnostic_info,
2041 TerminalDiagnosticSeverity::Hint => style.diagnostic_hint,
2042 }
2043}
2044
2045fn paint_terminal_text(
2047 ctx: &mut PaintCtx<'_>,
2048 x: f32,
2049 row_y: f32,
2050 text: &str,
2051 spans: &[StyledTextSpan],
2052 style: &TerminalWidgetStyle,
2053) {
2054 if text.is_empty() {
2055 return;
2056 }
2057 let Some(text_system) = ctx.text_system.as_deref_mut() else {
2058 return;
2059 };
2060 let prepared = terminal_layout(text_system, text, spans, style);
2061 let baseline = prepared
2062 .lines
2063 .first()
2064 .map(|line| line.baseline_y)
2065 .unwrap_or(style.text.px_size as f32);
2066 ctx.push(DrawCmd::Text(DrawText {
2067 pos: [x, row_y + baseline],
2068 color: style.text.color,
2069 decoration: ailloli_ui_core::TextDecoration::None,
2070 layout: prepared,
2071 }));
2072}
2073
2074fn terminal_layout(
2076 text_system: &mut TextSystem,
2077 text: &str,
2078 spans: &[StyledTextSpan],
2079 style: &TerminalWidgetStyle,
2080) -> Arc<PreparedTextLayout> {
2081 text_system.layout_styled_cached(StyledTextLayoutParams {
2082 text,
2083 base_style: style.text,
2084 spans,
2085 max_width: None,
2086 wrap_mode: WrapMode::NoWrap,
2087 })
2088}
2089
2090#[derive(Debug, Clone, Copy, PartialEq)]
2091struct CellBackground {
2093 col: usize,
2095 cols: usize,
2097 color: Color,
2099}
2100
2101fn terminal_line_render_parts(
2103 line: &CoreTerminalLine,
2104 style: &TerminalWidgetStyle,
2105) -> (String, Vec<StyledTextSpan>, Vec<CellBackground>) {
2106 let mut text = String::new();
2107 let mut spans = Vec::new();
2108 let mut backgrounds = Vec::new();
2109
2110 for (col, cell) in line.cells.iter().enumerate() {
2111 if cell.width == CellWidth::WideTrailing {
2112 continue;
2113 }
2114
2115 let (fg, bg) = terminal_cell_colors(cell.style, style);
2116 let cols = match cell.width {
2117 CellWidth::WideLeading => 2,
2118 CellWidth::Narrow | CellWidth::WideTrailing => 1,
2119 };
2120 if bg != style.background {
2121 backgrounds.push(CellBackground {
2122 col,
2123 cols,
2124 color: bg,
2125 });
2126 }
2127
2128 let start = text.len();
2129 text.push_str(&cell.text);
2130 let end = text.len();
2131 if start < end && fg != style.text.color {
2132 spans.push(StyledTextSpan {
2133 range: start..end,
2134 style: TextStyle::new(style.text.font, style.text.px_size, fg),
2135 });
2136 }
2137 }
2138
2139 (text, spans, backgrounds)
2140}
2141
2142fn terminal_cell_colors(cell: TerminalStyle, style: &TerminalWidgetStyle) -> (Color, Color) {
2144 let mut fg = terminal_color(cell.fg, style.text.color, style.background);
2145 let mut bg = terminal_color(cell.bg, style.text.color, style.background);
2146 if cell.inverse {
2147 mem::swap(&mut fg, &mut bg);
2148 }
2149 if cell.dim {
2150 fg = fg.with_alpha(fg.a * 0.70);
2151 }
2152 (fg, bg)
2153}
2154
2155fn terminal_color(color: TerminalColor, default_fg: Color, default_bg: Color) -> Color {
2157 match color {
2158 TerminalColor::DefaultFg => default_fg,
2159 TerminalColor::DefaultBg => default_bg,
2160 TerminalColor::Ansi(index) => ansi_color(index),
2161 TerminalColor::Indexed(index) => indexed_color(index),
2162 TerminalColor::Rgb(r, g, b) => Color::rgb(r, g, b),
2163 }
2164}
2165
2166fn ansi_color(index: u8) -> Color {
2168 const PALETTE: [u32; 16] = [
2169 0x1E1E1E, 0xD84A4A, 0x39A853, 0xE3B341, 0x4F86F7, 0xB86AD8, 0x24B8C4, 0xD6D6D6, 0x6B7280,
2170 0xFF6B6B, 0x63D471, 0xFFD166, 0x7AA2FF, 0xD987FF, 0x4DD0E1, 0xFFFFFF,
2171 ];
2172 Color::hex_rgb(PALETTE[index.min(15) as usize])
2173}
2174
2175fn indexed_color(index: u8) -> Color {
2177 if index < 16 {
2178 return ansi_color(index);
2179 }
2180 if index <= 231 {
2181 let n = index - 16;
2182 let r = n / 36;
2183 let g = (n % 36) / 6;
2184 let b = n % 6;
2185 return Color::rgb(xterm_cube(r), xterm_cube(g), xterm_cube(b));
2186 }
2187 let v = 8 + (index - 232) * 10;
2188 Color::rgb(v, v, v)
2189}
2190
2191fn xterm_cube(v: u8) -> u8 {
2193 if v == 0 {
2194 0
2195 } else {
2196 55 + v * 40
2197 }
2198}
2199
2200fn cursor_rect(
2202 bounds: Rect,
2203 style: &TerminalWidgetStyle,
2204 metrics: TerminalCellMetrics,
2205 state: &TerminalState,
2206 lines: &[&CoreTerminalLine],
2207 scroll: ScrollState,
2208) -> Option<Rect> {
2209 cursor_rect_from_lines(
2210 Rect::new(
2211 bounds.x + style.padding_x,
2212 bounds.y + style.padding_y,
2213 bounds.w - style.padding_x * 2.0 - style.scrollbar_width - style.scrollbar_inset * 2.0,
2214 bounds.h - style.padding_y * 2.0,
2215 ),
2216 style,
2217 metrics,
2218 state,
2219 lines,
2220 scroll,
2221 )
2222}
2223
2224fn cursor_rect_from_lines(
2226 content: Rect,
2227 _style: &TerminalWidgetStyle,
2228 metrics: TerminalCellMetrics,
2229 state: &TerminalState,
2230 lines: &[&CoreTerminalLine],
2231 scroll: ScrollState,
2232) -> Option<Rect> {
2233 if !state.cursor.visible || lines.is_empty() {
2234 return None;
2235 }
2236 let line_idx = terminal_cursor_visual_line(state);
2237 if line_idx >= lines.len() || metrics.cell_height <= 0.0 {
2238 return None;
2239 }
2240 let first = (scroll.offset.y / metrics.cell_height).floor().max(0.0) as usize;
2241 let visible = (content.h / metrics.cell_height).ceil().max(0.0) as usize + 2;
2242 if line_idx < first || line_idx >= first + visible {
2243 return None;
2244 }
2245 let offset_y = scroll.offset.y - first as f32 * metrics.cell_height;
2246 let row_y = content.y - offset_y + (line_idx - first) as f32 * metrics.cell_height;
2247 if row_y + metrics.cell_height < content.y || row_y > content.bottom() {
2248 return None;
2249 }
2250
2251 let x = content.x + state.cursor.col as f32 * metrics.cell_width;
2252 Some(match state.cursor.shape {
2253 TerminalCursorShape::Block => Rect::new(
2254 x,
2255 row_y + 2.0,
2256 metrics.cell_width.max(1.0),
2257 (metrics.cell_height - 4.0).max(1.0),
2258 ),
2259 TerminalCursorShape::Underline => Rect::new(
2260 x,
2261 row_y + metrics.cell_height - 4.0,
2262 metrics.cell_width.max(1.0),
2263 2.0,
2264 ),
2265 TerminalCursorShape::Bar => {
2266 Rect::new(x, row_y + 2.0, 2.0, (metrics.cell_height - 4.0).max(1.0))
2267 }
2268 })
2269}
2270
2271fn highlight_rect(
2273 content: Rect,
2274 row_y: f32,
2275 _style: &TerminalWidgetStyle,
2276 metrics: TerminalCellMetrics,
2277 start_col: usize,
2278 end_col: usize,
2279) -> Rect {
2280 let start = start_col.min(end_col);
2281 let end = end_col.max(start + 1);
2282 Rect::new(
2283 content.x + start as f32 * metrics.cell_width,
2284 row_y + 2.0,
2285 ((end - start) as f32 * metrics.cell_width)
2286 .min(content.w)
2287 .max(metrics.cell_width),
2288 (metrics.cell_height - 4.0).max(1.0),
2289 )
2290}
2291
2292fn selection_columns_for_line(
2294 selection: TerminalSelection,
2295 line: usize,
2296 line_len: usize,
2297) -> Option<(usize, usize)> {
2298 let (start, end) = selection.normalized();
2299 if line < start.line || line > end.line {
2300 return None;
2301 }
2302 let start_col = if line == start.line { start.column } else { 0 };
2303 let end_col = if line == end.line {
2304 end.column.min(line_len)
2305 } else {
2306 line_len
2307 };
2308 Some((
2309 start_col.min(line_len),
2310 end_col.max(start_col).min(line_len),
2311 ))
2312}
2313
2314fn paint_terminal_scrollbar(
2316 ctx: &mut PaintCtx<'_>,
2317 geometry: ScrollbarGeometry,
2318 style: &TerminalWidgetStyle,
2319 visual: crate::scrollbar::ScrollbarVisualState,
2320) {
2321 ctx.push(DrawCmd::RRect(DrawRRect {
2322 rect: geometry.track,
2323 radius: style.scrollbar_width * 0.5,
2324 color: style.scrollbar_track,
2325 }));
2326 ctx.push(DrawCmd::RRect(DrawRRect {
2327 rect: geometry.thumb,
2328 radius: style.scrollbar_width * 0.5,
2329 color: thumb_color_for_state(style.scrollbar_thumb, visual),
2330 }));
2331}
2332
2333#[derive(Clone, Copy)]
2334struct TerminalMouseLayout {
2336 content: Rect,
2338 metrics: TerminalCellMetrics,
2340 scroll: ScrollState,
2342 line_count: usize,
2344}
2345
2346fn terminal_mouse_bytes_from_event(
2348 event: &Event,
2349 state: &TerminalState,
2350 layout: TerminalMouseLayout,
2351 pressed_button: Option<MouseButton>,
2352) -> Option<Vec<u8>> {
2353 if state.modes.mouse_tracking == TerminalMouseTrackingMode::Off {
2354 return None;
2355 }
2356 let (pos, code, release_or_motion) = match event {
2357 Event::Pointer(PointerEvent::Button {
2358 pos,
2359 button,
2360 pressed,
2361 ..
2362 }) => {
2363 let code = if *pressed {
2364 terminal_mouse_button_code(*button)?
2365 } else {
2366 3
2367 };
2368 (*pos, code, !*pressed)
2369 }
2370 Event::Pointer(PointerEvent::Moved { pos, .. }) => {
2371 let motion_allowed = match state.modes.mouse_tracking {
2372 TerminalMouseTrackingMode::ButtonMotion => pressed_button.is_some(),
2373 TerminalMouseTrackingMode::AnyMotion => true,
2374 _ => false,
2375 };
2376 if !motion_allowed {
2377 return None;
2378 }
2379 let code =
2380 terminal_mouse_button_code(pressed_button.unwrap_or(MouseButton::Left))? + 32;
2381 (*pos, code, false)
2382 }
2383 Event::Pointer(PointerEvent::Wheel { pos, delta, .. }) => {
2384 let y = match delta {
2385 ailloli_ui_core::event::WheelDelta::LineDelta { y, .. }
2386 | ailloli_ui_core::event::WheelDelta::PixelDelta { y, .. } => *y,
2387 };
2388 (*pos, if y > 0.0 { 64 } else { 65 }, false)
2389 }
2390 _ => return None,
2391 };
2392 if !layout.content.contains(pos.x, pos.y) || layout.line_count == 0 {
2393 return None;
2394 }
2395
2396 let col = ((pos.x - layout.content.x) / layout.metrics.cell_width)
2397 .floor()
2398 .max(0.0) as usize
2399 + 1;
2400 let row = ((pos.y - layout.content.y + layout.scroll.offset.y) / layout.metrics.cell_height)
2401 .floor()
2402 .max(0.0) as usize
2403 + 1;
2404
2405 if state.modes.sgr_mouse {
2406 let suffix = if release_or_motion { 'm' } else { 'M' };
2407 Some(format!("\x1b[<{code};{col};{row}{suffix}").into_bytes())
2408 } else {
2409 let col = (col + 32).min(255) as u8;
2410 let row = (row + 32).min(255) as u8;
2411 Some(vec![0x1b, b'[', b'M', (code + 32).min(255) as u8, col, row])
2412 }
2413}
2414
2415fn terminal_mouse_button_code(button: MouseButton) -> Option<usize> {
2417 match button {
2418 MouseButton::Left => Some(0),
2419 MouseButton::Middle => Some(1),
2420 MouseButton::Right => Some(2),
2421 MouseButton::Other(_) => None,
2422 }
2423}
2424
2425pub fn terminal_key_bytes(key: &KeyEvent) -> Option<Vec<u8>> {
2449 terminal_key_bytes_with_modes(key, &TerminalModes::default())
2450}
2451
2452pub fn terminal_key_bytes_with_modes(key: &KeyEvent, modes: &TerminalModes) -> Option<Vec<u8>> {
2475 if key.state != KeyState::Pressed {
2476 return None;
2477 }
2478
2479 let mut bytes = match &key.key {
2480 Key::Named(NamedKey::Enter) => b"\r".to_vec(),
2481 Key::Named(NamedKey::Backspace) => vec![0x7f],
2482 Key::Named(NamedKey::Tab) => b"\t".to_vec(),
2483 Key::Named(NamedKey::Escape) => vec![0x1b],
2484 Key::Named(NamedKey::ArrowUp) if modes.application_cursor => b"\x1bOA".to_vec(),
2485 Key::Named(NamedKey::ArrowDown) if modes.application_cursor => b"\x1bOB".to_vec(),
2486 Key::Named(NamedKey::ArrowRight) if modes.application_cursor => b"\x1bOC".to_vec(),
2487 Key::Named(NamedKey::ArrowLeft) if modes.application_cursor => b"\x1bOD".to_vec(),
2488 Key::Named(NamedKey::Home) if modes.application_cursor => b"\x1bOH".to_vec(),
2489 Key::Named(NamedKey::End) if modes.application_cursor => b"\x1bOF".to_vec(),
2490 Key::Named(NamedKey::ArrowUp) => b"\x1b[A".to_vec(),
2491 Key::Named(NamedKey::ArrowDown) => b"\x1b[B".to_vec(),
2492 Key::Named(NamedKey::ArrowRight) => b"\x1b[C".to_vec(),
2493 Key::Named(NamedKey::ArrowLeft) => b"\x1b[D".to_vec(),
2494 Key::Named(NamedKey::Home) => b"\x1b[H".to_vec(),
2495 Key::Named(NamedKey::End) => b"\x1b[F".to_vec(),
2496 Key::Named(NamedKey::PageUp) => b"\x1b[5~".to_vec(),
2497 Key::Named(NamedKey::PageDown) => b"\x1b[6~".to_vec(),
2498 Key::Named(NamedKey::Delete) => b"\x1b[3~".to_vec(),
2499 Key::Named(NamedKey::Insert) => b"\x1b[2~".to_vec(),
2500 Key::Named(NamedKey::Space) => b" ".to_vec(),
2501 Key::Character(ch) if key.modifiers.ctrl => ctrl_key_bytes(ch)?,
2502 Key::Character(ch) => key
2503 .text
2504 .as_ref()
2505 .filter(|text| !text.is_empty())
2506 .unwrap_or(ch)
2507 .as_bytes()
2508 .to_vec(),
2509 Key::Dead(Some(ch)) => ch.as_bytes().to_vec(),
2510 _ => return None,
2511 };
2512
2513 if key.modifiers.alt && bytes.first().copied() != Some(0x1b) {
2514 let mut prefixed = Vec::with_capacity(bytes.len() + 1);
2515 prefixed.push(0x1b);
2516 prefixed.extend(bytes);
2517 bytes = prefixed;
2518 }
2519 Some(bytes)
2520}
2521
2522fn ctrl_key_bytes(ch: &str) -> Option<Vec<u8>> {
2524 let mut chars = ch.chars();
2525 let c = chars.next()?;
2526 if chars.next().is_some() {
2527 return None;
2528 }
2529 match c.to_ascii_uppercase() {
2530 'C' => Some(vec![0x03]),
2531 'D' => Some(vec![0x04]),
2532 'L' => Some(vec![0x0c]),
2533 'Z' => Some(vec![0x1a]),
2534 _ => None,
2535 }
2536}
2537
2538#[cfg(test)]
2539mod tests {
2541 use super::*;
2542 use ailloli_ui_core::event::{KeyState, Modifiers};
2543 use ailloli_ui_core::math::Scale;
2544 use ailloli_ui_runtime::app::{Runtime, RuntimeHandle};
2545 use ailloli_ui_runtime::component::{IntoView, State, View, ViewKind};
2546 use ailloli_ui_runtime::input::InputRouter;
2547 use ailloli_ui_text::TextSystem;
2548 use std::cell::RefCell;
2549 use std::collections::VecDeque;
2550 use std::rc::Rc;
2551
2552 fn key(key: Key, modifiers: Modifiers, text: Option<&str>) -> KeyEvent {
2554 KeyEvent {
2555 state: KeyState::Pressed,
2556 key,
2557 modifiers,
2558 repeat: false,
2559 pointer_pos: None,
2560 text: text.map(str::to_string),
2561 }
2562 }
2563
2564 #[test]
2565 fn terminal_builder_accepts_public_state_binding() {
2566 let state = State::new(TerminalState::new());
2567 let view: View<()> = Terminal::new(state).into_view();
2568 assert!(matches!(view.kind, ViewKind::Component(_)));
2569 }
2570
2571 #[test]
2572 fn terminal_widget_does_not_import_pty_runtime() {
2573 assert!(!include_str!("../../Cargo.toml").contains("ailloli_ui_terminal_pty"));
2574 }
2575
2576 #[test]
2577 fn terminal_key_bytes_maps_named_text_ctrl_and_alt() {
2578 assert_eq!(
2579 terminal_key_bytes(&key(
2580 Key::Named(NamedKey::Enter),
2581 Modifiers::default(),
2582 None
2583 )),
2584 Some(b"\r".to_vec())
2585 );
2586 assert_eq!(
2587 terminal_key_bytes(&key(
2588 Key::Named(NamedKey::ArrowUp),
2589 Modifiers::default(),
2590 None
2591 )),
2592 Some(b"\x1b[A".to_vec())
2593 );
2594 assert_eq!(
2595 terminal_key_bytes(&key(
2596 Key::Character("c".into()),
2597 Modifiers {
2598 ctrl: true,
2599 ..Modifiers::default()
2600 },
2601 None
2602 )),
2603 Some(vec![0x03])
2604 );
2605 assert_eq!(
2606 terminal_key_bytes(&key(
2607 Key::Character("x".into()),
2608 Modifiers {
2609 alt: true,
2610 ..Modifiers::default()
2611 },
2612 Some("x")
2613 )),
2614 Some(b"\x1bx".to_vec())
2615 );
2616 }
2617
2618 #[test]
2619 fn terminal_key_bytes_respects_application_cursor_mode() {
2620 let modes = TerminalModes {
2621 application_cursor: true,
2622 ..TerminalModes::default()
2623 };
2624
2625 assert_eq!(
2626 terminal_key_bytes_with_modes(
2627 &key(Key::Named(NamedKey::ArrowUp), Modifiers::default(), None),
2628 &modes
2629 ),
2630 Some(b"\x1bOA".to_vec())
2631 );
2632 assert_eq!(
2633 terminal_key_bytes_with_modes(
2634 &key(Key::Named(NamedKey::End), Modifiers::default(), None),
2635 &modes
2636 ),
2637 Some(b"\x1bOF".to_vec())
2638 );
2639 }
2640
2641 #[test]
2642 fn terminal_selection_text_extracts_wide_and_combining_cells() {
2643 let mut state = TerminalState::with_config(ailloli_ui_terminal_core::TerminalConfig {
2644 size: TerminalSize::new(2, 8),
2645 scrollback_limit: 2,
2646 security: ailloli_ui_terminal_core::TerminalSecurityPolicy::default(),
2647 });
2648 state.write_char('e');
2649 state.write_char('\u{301}');
2650 state.write_char(' ');
2651 state.write_char('界');
2652 state.write_str("\r\nnext");
2653
2654 let text = terminal_selection_text(
2655 &state,
2656 TerminalSelection::new(TerminalPosition::new(0, 0), TerminalPosition::new(1, 4)),
2657 );
2658
2659 assert_eq!(text, "e\u{301} 界\nnext");
2660 }
2661
2662 #[test]
2663 fn terminal_paste_bytes_wraps_when_bracketed_paste_is_enabled() {
2664 assert_eq!(
2665 terminal_paste_bytes("abc", &TerminalModes::default()),
2666 b"abc".to_vec()
2667 );
2668
2669 let modes = TerminalModes {
2670 bracketed_paste: true,
2671 ..TerminalModes::default()
2672 };
2673 assert_eq!(
2674 terminal_paste_bytes("abc", &modes),
2675 b"\x1b[200~abc\x1b[201~".to_vec()
2676 );
2677 }
2678
2679 #[test]
2680 fn terminal_mouse_bytes_encode_sgr_button_and_wheel() {
2681 let mut state = TerminalState::new();
2682 state.modes.mouse_tracking = TerminalMouseTrackingMode::Normal;
2683 state.modes.sgr_mouse = true;
2684 let content = Rect::new(10.0, 20.0, 200.0, 100.0);
2685
2686 let layout = TerminalMouseLayout {
2687 content,
2688 metrics: TerminalCellMetrics::new(8.0, 19.0, 13.0),
2689 scroll: ScrollState::default(),
2690 line_count: 10,
2691 };
2692 let press = terminal_mouse_bytes_from_event(
2693 &Event::Pointer(PointerEvent::Button {
2694 pos: ailloli_ui_core::Point::new(18.0, 39.0),
2695 button: MouseButton::Left,
2696 pressed: true,
2697 modifiers: Modifiers::default(),
2698 }),
2699 &state,
2700 layout,
2701 None,
2702 );
2703 assert_eq!(press, Some(b"\x1b[<0;2;2M".to_vec()));
2704
2705 let wheel = terminal_mouse_bytes_from_event(
2706 &Event::Pointer(PointerEvent::Wheel {
2707 pos: ailloli_ui_core::Point::new(18.0, 39.0),
2708 delta: ailloli_ui_core::event::WheelDelta::LineDelta { x: 0.0, y: 1.0 },
2709 modifiers: Modifiers::default(),
2710 precise: false,
2711 }),
2712 &state,
2713 layout,
2714 None,
2715 );
2716 assert_eq!(wheel, Some(b"\x1b[<64;2;2M".to_vec()));
2717 }
2718
2719 #[test]
2720 fn terminal_scrollbar_drag_precedes_mouse_protocol_reporting() {
2721 let mut terminal_state =
2722 TerminalState::with_config(ailloli_ui_terminal_core::TerminalConfig {
2723 size: TerminalSize::new(3, 20),
2724 scrollback_limit: 32,
2725 security: ailloli_ui_terminal_core::TerminalSecurityPolicy::default(),
2726 });
2727 for line in 0..16 {
2728 terminal_state.write_str(&format!("line {line:02}\r\n"));
2729 }
2730 terminal_state.modes.mouse_tracking = TerminalMouseTrackingMode::Normal;
2731 terminal_state.modes.sgr_mouse = true;
2732 let state = State::new(terminal_state);
2733 let emitted = Rc::new(RefCell::new(Vec::<Vec<u8>>::new()));
2734 let emitted_for_input = emitted.clone();
2735 let style = TerminalWidgetStyle::default();
2736 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2737 let mut app = Runtime::new(runtime.clone());
2738 app.reconcile(
2739 Terminal::new(state)
2740 .terminal_style(style.clone())
2741 .auto_resize(false)
2742 .width(200.0)
2743 .height(80.0)
2744 .on_input_ctx(move |_ctx, bytes| emitted_for_input.borrow_mut().push(bytes))
2745 .into_view(),
2746 );
2747 let mut text_system = TextSystem::new();
2748 app.layout(
2749 Constraints::tight(200.0, 80.0),
2750 Scale::new(1.0),
2751 &mut text_system,
2752 );
2753 let scene = app.paint(&mut text_system);
2754 let thumb = scene
2755 .layers
2756 .iter()
2757 .flat_map(|layer| layer.cmds.iter())
2758 .find_map(|cmd| match cmd {
2759 DrawCmd::RRect(rrect)
2760 if rrect.color == style.scrollbar_thumb && rrect.rect.h > rrect.rect.w =>
2761 {
2762 Some(*rrect)
2763 }
2764 _ => None,
2765 })
2766 .expect("terminal scrollbar thumb");
2767 let press = ailloli_ui_core::Point::new(
2768 thumb.rect.x + thumb.rect.w * 0.5,
2769 thumb.rect.y + thumb.rect.h * 0.5,
2770 );
2771 let initial_thumb_y = thumb.rect.y;
2772 let mut router = InputRouter::default();
2773 router.route_event(
2774 &app.tree,
2775 runtime.clone(),
2776 &Event::Pointer(PointerEvent::Button {
2777 pos: press,
2778 button: MouseButton::Left,
2779 pressed: true,
2780 modifiers: Modifiers::default(),
2781 }),
2782 );
2783 router.route_event(
2784 &app.tree,
2785 runtime.clone(),
2786 &Event::Pointer(PointerEvent::Moved {
2787 pos: ailloli_ui_core::Point::new(press.x, 0.0),
2788 modifiers: Modifiers::default(),
2789 }),
2790 );
2791 router.route_event(
2792 &app.tree,
2793 runtime,
2794 &Event::Pointer(PointerEvent::Button {
2795 pos: ailloli_ui_core::Point::new(press.x, 0.0),
2796 button: MouseButton::Left,
2797 pressed: false,
2798 modifiers: Modifiers::default(),
2799 }),
2800 );
2801
2802 assert!(
2803 emitted.borrow().is_empty(),
2804 "local scrollbar gestures must not emit terminal protocol bytes"
2805 );
2806 let after = app.paint(&mut text_system);
2807 let after_thumb_y = after
2808 .layers
2809 .iter()
2810 .flat_map(|layer| layer.cmds.iter())
2811 .find_map(|cmd| match cmd {
2812 DrawCmd::RRect(rrect)
2813 if rrect.color == style.scrollbar_thumb && rrect.rect.h > rrect.rect.w =>
2814 {
2815 Some(rrect.rect.y)
2816 }
2817 _ => None,
2818 })
2819 .expect("terminal scrollbar thumb after drag");
2820 assert!(
2821 after_thumb_y < initial_thumb_y,
2822 "dragging upward must move the retained scrollback thumb"
2823 );
2824 }
2825
2826 #[test]
2827 fn terminal_layout_auto_resize_clamps_to_minimum() {
2828 let state = State::new(TerminalState::new());
2829 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2830 let mut app = Runtime::new(runtime);
2831 app.reconcile(
2832 Terminal::new(state.clone())
2833 .width(1.0)
2834 .height(1.0)
2835 .into_view(),
2836 );
2837 let mut text_system = TextSystem::new();
2838
2839 app.layout(
2840 Constraints::tight(1.0, 1.0),
2841 Scale::new(1.0),
2842 &mut text_system,
2843 );
2844
2845 assert_eq!(state.read().active_screen().size(), TerminalSize::new(1, 1));
2846 }
2847
2848 #[test]
2849 fn terminal_layout_reports_effective_size() {
2850 let state = State::new(TerminalState::new());
2851 let calls = Rc::new(RefCell::new(Vec::<TerminalViewportSize>::new()));
2852 let resize_calls = calls.clone();
2853 let style = TerminalWidgetStyle {
2854 padding_x: 0.0,
2855 padding_y: 0.0,
2856 line_height: 10.0,
2857 char_width: 8.0,
2858 width: 80.0,
2859 height: 40.0,
2860 ..Default::default()
2861 };
2862 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2863 let mut app = Runtime::new(runtime);
2864 app.reconcile(
2865 Terminal::new(state)
2866 .terminal_style(style)
2867 .auto_resize(false)
2868 .scrollbars(false)
2869 .sync_resize_to(move |viewport| {
2870 resize_calls.borrow_mut().push(viewport);
2871 None
2872 })
2873 .into_view(),
2874 );
2875 let mut text_system = TextSystem::new();
2876
2877 app.layout(
2878 Constraints::tight(80.0, 40.0),
2879 Scale::new(1.0),
2880 &mut text_system,
2881 );
2882 app.layout(
2883 Constraints::tight(80.0, 40.0),
2884 Scale::new(1.0),
2885 &mut text_system,
2886 );
2887
2888 assert_eq!(
2889 calls.borrow().as_slice(),
2890 &[TerminalViewportSize::new(TerminalSize::new(4, 10), 80, 40)]
2891 );
2892 }
2893
2894 #[test]
2895 fn terminal_geometry_matches_visible_bounds() {
2896 let state = State::new(TerminalState::new());
2897 let calls = Rc::new(RefCell::new(Vec::<TerminalGeometry>::new()));
2898 let geometry_calls = calls.clone();
2899 let style = TerminalWidgetStyle {
2900 padding_x: 0.0,
2901 padding_y: 0.0,
2902 line_height: 19.0,
2903 char_width: 8.0,
2904 width: 420.0,
2905 height: 190.0,
2906 ..Default::default()
2907 };
2908 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2909 let mut app = Runtime::new(runtime);
2910 app.reconcile(
2911 Terminal::new(state)
2912 .terminal_style(style)
2913 .auto_resize(false)
2914 .scrollbars(false)
2915 .sync_geometry_to(move |geometry| {
2916 geometry_calls.borrow_mut().push(geometry);
2917 None
2918 })
2919 .into_view(),
2920 );
2921 let mut text_system = TextSystem::new();
2922
2923 app.layout(
2924 Constraints::tight(420.0, 190.0),
2925 Scale::new(1.0),
2926 &mut text_system,
2927 );
2928
2929 let geometry = calls.borrow()[0];
2930 assert_eq!(geometry.pixel_width, 420);
2931 assert_eq!(geometry.pixel_height, 190);
2932 assert!(
2933 geometry.cols >= 40,
2934 "expected terminal cols to follow visible bounds, got {}",
2935 geometry.cols
2936 );
2937 assert_ne!(geometry.cols, 18);
2938 }
2939
2940 #[test]
2941 fn terminal_paint_does_not_report_external_resize() {
2942 let state = State::new(TerminalState::new());
2943 let calls = Rc::new(RefCell::new(Vec::<TerminalViewportSize>::new()));
2944 let resize_calls = calls.clone();
2945 let sync_queue = Rc::new(RefCell::new(VecDeque::from([
2946 None,
2947 Some(TerminalState::new()),
2948 ])));
2949 let sync_state = sync_queue.clone();
2950 let style = TerminalWidgetStyle {
2951 padding_x: 0.0,
2952 padding_y: 0.0,
2953 line_height: 10.0,
2954 char_width: 8.0,
2955 width: 80.0,
2956 height: 40.0,
2957 ..Default::default()
2958 };
2959 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2960 let mut app = Runtime::new(runtime);
2961 app.reconcile(
2962 Terminal::new(state)
2963 .terminal_style(style)
2964 .auto_resize(false)
2965 .scrollbars(false)
2966 .sync_state_from(move || sync_state.borrow_mut().pop_front().unwrap_or(None))
2967 .sync_resize_to(move |viewport| {
2968 resize_calls.borrow_mut().push(viewport);
2969 let mut next = TerminalState::new();
2970 next.resize(viewport.terminal);
2971 Some(next)
2972 })
2973 .into_view(),
2974 );
2975 let mut text_system = TextSystem::new();
2976
2977 app.layout(
2978 Constraints::tight(80.0, 40.0),
2979 Scale::new(1.0),
2980 &mut text_system,
2981 );
2982 let _ = app.paint(&mut text_system);
2983
2984 assert_eq!(
2985 calls.borrow().as_slice(),
2986 &[TerminalViewportSize::new(TerminalSize::new(4, 10), 80, 40)]
2987 );
2988 }
2989
2990 #[test]
2991 fn terminal_sync_state_from_updates_before_layout() {
2992 let state = State::new(TerminalState::new());
2993 let mut external = TerminalState::new();
2994 external.write_str("layout-sync");
2995 let calls = Rc::new(RefCell::new(0_usize));
2996 let sync_calls = calls.clone();
2997 let sync_state = external.clone();
2998 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2999 let mut app = Runtime::new(runtime);
3000 app.reconcile(
3001 Terminal::new(state.clone())
3002 .sync_state_from(move || {
3003 *sync_calls.borrow_mut() += 1;
3004 Some(sync_state.clone())
3005 })
3006 .into_view(),
3007 );
3008 let mut text_system = TextSystem::new();
3009
3010 app.layout(
3011 Constraints::tight(320.0, 180.0),
3012 Scale::new(1.0),
3013 &mut text_system,
3014 );
3015
3016 assert!(*calls.borrow() >= 1);
3017 assert!(state
3018 .read()
3019 .screen
3020 .line(0)
3021 .expect("line")
3022 .plain_text()
3023 .contains("layout-sync"));
3024 }
3025
3026 #[test]
3027 fn terminal_paint_does_not_poll_external_state() {
3028 let state = State::new(TerminalState::new());
3029 let mut paint_state = TerminalState::new();
3030 paint_state.write_str("paint-sync");
3031 let queue = Rc::new(RefCell::new(VecDeque::from([
3032 None,
3033 Some(paint_state.clone()),
3034 ])));
3035 let sync_queue = queue.clone();
3036 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
3037 let mut app = Runtime::new(runtime.clone());
3038 app.reconcile(
3039 Terminal::new(state.clone())
3040 .sync_state_from(move || sync_queue.borrow_mut().pop_front().unwrap_or(None))
3041 .into_view(),
3042 );
3043 let mut text_system = TextSystem::new();
3044
3045 app.layout(
3046 Constraints::tight(320.0, 180.0),
3047 Scale::new(1.0),
3048 &mut text_system,
3049 );
3050 assert!(!state
3051 .read()
3052 .screen
3053 .line(0)
3054 .expect("line")
3055 .plain_text()
3056 .contains("paint-sync"));
3057
3058 let _ = app.paint(&mut text_system);
3059
3060 assert!(!state
3061 .read()
3062 .screen
3063 .line(0)
3064 .expect("line")
3065 .plain_text()
3066 .contains("paint-sync"));
3067 assert_eq!(queue.borrow().len(), 1, "paint must not poll state");
3068
3069 let mut router = InputRouter::default();
3070 router.route_event(
3071 &app.tree,
3072 runtime,
3073 &Event::Pointer(PointerEvent::Moved {
3074 pos: ailloli_ui_core::Point::new(1.0, 1.0),
3075 modifiers: Modifiers::default(),
3076 }),
3077 );
3078
3079 assert!(state
3080 .read()
3081 .screen
3082 .line(0)
3083 .expect("line")
3084 .plain_text()
3085 .contains("paint-sync"));
3086 }
3087
3088 #[test]
3089 fn normal_screen_includes_scrollback_but_alternate_screen_does_not() {
3090 let mut state = TerminalState::with_config(ailloli_ui_terminal_core::TerminalConfig {
3091 size: TerminalSize::new(2, 3),
3092 scrollback_limit: 4,
3093 security: ailloli_ui_terminal_core::TerminalSecurityPolicy::default(),
3094 });
3095 state.write_str("abcdefghi");
3096 assert!(terminal_visual_line_count(&state) > state.screen.rows);
3097
3098 state.switch_to_alternate_screen();
3099 assert_eq!(
3100 terminal_visual_line_count(&state),
3101 state.alternate_screen.rows
3102 );
3103 }
3104
3105 #[test]
3106 fn wide_trailing_cell_is_not_rendered_twice() {
3107 let mut state = TerminalState::with_config(ailloli_ui_terminal_core::TerminalConfig {
3108 size: TerminalSize::new(1, 4),
3109 scrollback_limit: 0,
3110 security: ailloli_ui_terminal_core::TerminalSecurityPolicy::default(),
3111 });
3112 state.write_char('界');
3113 let (text, _, _) = terminal_line_render_parts(
3114 state.screen.line(0).expect("line"),
3115 &TerminalWidgetStyle::default(),
3116 );
3117
3118 assert_eq!(text.chars().filter(|ch| *ch == '界').count(), 1);
3119 }
3120
3121 #[test]
3122 fn terminal_colors_resolve_ansi_indexed_rgb_inverse_and_dim() {
3123 let style = TerminalWidgetStyle::default();
3124 assert_ne!(
3125 terminal_color(TerminalColor::Ansi(1), style.text.color, style.background),
3126 style.text.color
3127 );
3128 assert_ne!(
3129 terminal_color(
3130 TerminalColor::Indexed(196),
3131 style.text.color,
3132 style.background
3133 ),
3134 style.text.color
3135 );
3136 assert_eq!(
3137 terminal_color(
3138 TerminalColor::Rgb(1, 2, 3),
3139 style.text.color,
3140 style.background
3141 ),
3142 Color::rgb(1, 2, 3)
3143 );
3144
3145 let terminal_style = TerminalStyle {
3146 inverse: true,
3147 dim: true,
3148 ..TerminalStyle::default()
3149 };
3150 let (fg, bg) = terminal_cell_colors(terminal_style, &style);
3151 assert_eq!(bg, style.text.color);
3152 assert!(fg.a < style.background.a);
3153 }
3154
3155 #[test]
3156 fn cursor_rect_respects_shape_and_visibility() {
3157 let mut state = TerminalState::new();
3158 state.cursor.col = 2;
3159 state.cursor.shape = TerminalCursorShape::Bar;
3160 let lines = terminal_visual_lines(&state);
3161 let style = TerminalWidgetStyle::default();
3162 let metrics = TerminalCellMetrics::new(
3163 style.char_width,
3164 style.line_height,
3165 style.text.px_size as f32,
3166 );
3167 let rect = cursor_rect_from_lines(
3168 Rect::new(0.0, 0.0, 400.0, 200.0),
3169 &style,
3170 metrics,
3171 &state,
3172 &lines,
3173 ScrollState::default(),
3174 )
3175 .expect("cursor rect");
3176 assert_eq!(rect.w, 2.0);
3177
3178 state.cursor.visible = false;
3179 let lines = terminal_visual_lines(&state);
3180 assert!(cursor_rect_from_lines(
3181 Rect::new(0.0, 0.0, 400.0, 200.0),
3182 &style,
3183 metrics,
3184 &state,
3185 &lines,
3186 ScrollState::default(),
3187 )
3188 .is_none());
3189 }
3190
3191 #[test]
3192 fn terminal_caret_uses_terminal_cell_metrics() {
3193 let mut state = TerminalState::new();
3194 state.cursor.col = 3;
3195 state.cursor.shape = TerminalCursorShape::Block;
3196 let lines = terminal_visual_lines(&state);
3197 let style = TerminalWidgetStyle {
3198 char_width: 4.0,
3199 line_height: 9.0,
3200 ..Default::default()
3201 };
3202 let metrics = TerminalCellMetrics::new(11.0, 17.0, 12.0);
3203
3204 let rect = cursor_rect_from_lines(
3205 Rect::new(0.0, 0.0, 400.0, 200.0),
3206 &style,
3207 metrics,
3208 &state,
3209 &lines,
3210 ScrollState::default(),
3211 )
3212 .expect("cursor rect");
3213
3214 assert_eq!(rect.x, 33.0);
3215 assert_eq!(rect.w, 11.0);
3216 assert_eq!(rect.h, 13.0);
3217 }
3218
3219 #[test]
3220 fn selection_columns_clamp_to_line_limits() {
3221 let selection =
3222 TerminalSelection::new(TerminalPosition::new(0, 2), TerminalPosition::new(0, 99));
3223 assert_eq!(selection_columns_for_line(selection, 0, 5), Some((2, 5)));
3224 }
3225
3226 #[test]
3227 fn terminal_diagnostics_map_to_visible_global_lines() {
3228 let mut state = TerminalState::with_config(ailloli_ui_terminal_core::TerminalConfig {
3229 size: TerminalSize::new(4, 80),
3230 scrollback_limit: 20,
3231 security: ailloli_ui_terminal_core::TerminalSecurityPolicy::default(),
3232 });
3233 state.write_str("error: failed\n --> src/main.rs:2:3\n");
3234 state.classify_terminal_output();
3235 let globals = terminal_visual_line_global_indices(&state);
3236
3237 assert!(terminal_diagnostic_for_visual_line(&state, &globals, 0).is_some());
3238 assert!(terminal_diagnostic_for_visual_line(&state, &globals, 1).is_some());
3239 }
3240
3241 #[test]
3242 fn terminal_diagnostic_colors_follow_severity() {
3243 let style = TerminalWidgetStyle::default();
3244 assert_eq!(
3245 terminal_diagnostic_color(&style, TerminalDiagnosticSeverity::Error),
3246 style.diagnostic_error
3247 );
3248 assert_eq!(
3249 terminal_diagnostic_label(TerminalDiagnosticSeverity::Warning),
3250 "WARN"
3251 );
3252 }
3253}