ailloli_ui_widgets/controls/
terminal_widget.rs

1//! Interactive terminal-grid renderer backed by `ailloli_ui_terminal_core` state.
2
3use 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
38/// Shared callback receiving bytes encoded for the terminal peer.
39type InputHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, Vec<u8>)>;
40/// Poll callback that can replace the complete terminal state.
41type StateSync = Rc<dyn Fn() -> Option<TerminalState>>;
42/// Resize callback receiving grid size and saturated 16-bit pixel extents.
43type ResizeSync = Rc<dyn Fn(TerminalViewportSize) -> Option<TerminalState>>;
44/// Geometry callback receiving measured cell metrics and 32-bit pixel extents.
45type GeometrySync = Rc<dyn Fn(TerminalGeometry) -> Option<TerminalState>>;
46
47#[derive(Debug, Clone, Copy, PartialEq)]
48/// Measured monospace cell geometry in logical pixels.
49///
50/// Values are not validated by [`Self::new`]. Runtime measurement clamps cell
51/// width/height and baseline fallbacks to at least `1.0`.
52///
53/// # Examples
54///
55/// ```
56/// use ailloli_ui_widgets::controls::TerminalCellMetrics;
57/// let metrics = TerminalCellMetrics::new(8.0, 19.0, 14.0);
58/// assert_eq!((metrics.cell_width, metrics.cell_height, metrics.baseline), (8.0, 19.0, 14.0));
59/// ```
60pub struct TerminalCellMetrics {
61    /// Width of one terminal column in logical pixels.
62    pub cell_width: f32,
63    /// Height of one terminal row in logical pixels.
64    pub cell_height: f32,
65    /// Baseline offset from the row top in logical pixels.
66    pub baseline: f32,
67}
68
69impl TerminalCellMetrics {
70    /// Stores cell metrics unchanged, including zero or non-finite values.
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// use ailloli_ui_widgets::controls::TerminalCellMetrics;
76    /// let metrics = TerminalCellMetrics::new(7.5, 18.0, 13.0);
77    /// assert_eq!(metrics.cell_width, 7.5);
78    /// ```
79    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)]
89/// Committed terminal viewport geometry.
90///
91/// `pixel_width`/`pixel_height` are rounded non-negative content extents in the
92/// runtime coordinate space. Grid dimensions are whole cells and normally stay
93/// within `1..=u16::MAX`. [`Self::new`] itself stores all inputs unchanged.
94///
95/// # Examples
96///
97/// ```
98/// use ailloli_ui_widgets::controls::{TerminalCellMetrics, TerminalGeometry};
99/// let geometry = TerminalGeometry::new(
100///     640,
101///     380,
102///     TerminalCellMetrics::new(8.0, 19.0, 14.0),
103///     80,
104///     20,
105/// );
106/// assert_eq!(geometry.terminal_size().cols, 80);
107/// ```
108pub struct TerminalGeometry {
109    /// Rounded content width, saturated at [`u32::MAX`] by runtime measurement.
110    pub pixel_width: u32,
111    /// Rounded content height, saturated at [`u32::MAX`] by runtime measurement.
112    pub pixel_height: u32,
113    /// Cell width, height, and baseline used to derive the grid.
114    pub metrics: TerminalCellMetrics,
115    /// Visible column count in cells.
116    pub cols: u16,
117    /// Visible row count in cells.
118    pub rows: u16,
119}
120
121impl TerminalGeometry {
122    /// Stores viewport geometry unchanged.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use ailloli_ui_widgets::controls::{TerminalCellMetrics, TerminalGeometry};
128    /// let geometry = TerminalGeometry::new(800, 600, TerminalCellMetrics::new(8.0, 20.0, 14.0), 100, 30);
129    /// assert_eq!((geometry.pixel_width, geometry.rows), (800, 30));
130    /// ```
131    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    /// Converts `(rows, cols)` to a core [`TerminalSize`].
148    ///
149    /// `TerminalSize::new` replaces a zero row or column with one.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use ailloli_ui_widgets::controls::{TerminalCellMetrics, TerminalGeometry};
155    /// let geometry = TerminalGeometry::new(0, 0, TerminalCellMetrics::new(1.0, 1.0, 1.0), 0, 0);
156    /// assert_eq!((geometry.terminal_size().rows, geometry.terminal_size().cols), (1, 1));
157    /// ```
158    pub fn terminal_size(self) -> TerminalSize {
159        TerminalSize::new(self.rows as usize, self.cols as usize)
160    }
161
162    /// Converts to the resize callback payload.
163    ///
164    /// Pixel extents above [`u16::MAX`] saturate independently; grid dimensions
165    /// pass through [`Self::terminal_size`].
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use ailloli_ui_widgets::controls::{TerminalCellMetrics, TerminalGeometry};
171    /// let geometry = TerminalGeometry::new(100_000, 480, TerminalCellMetrics::new(8.0, 20.0, 14.0), 80, 24);
172    /// let viewport = geometry.viewport_size();
173    /// assert_eq!(viewport.pixel_width, u16::MAX);
174    /// assert_eq!(viewport.pixel_height, 480);
175    /// ```
176    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)]
186/// Compact resize payload for terminal/PTY integrations.
187///
188/// # Examples
189///
190/// ```
191/// use ailloli_ui_terminal_core::TerminalSize;
192/// use ailloli_ui_widgets::controls::TerminalViewportSize;
193/// let viewport = TerminalViewportSize::new(TerminalSize::new(24, 80), 640, 480);
194/// assert_eq!((viewport.terminal.rows, viewport.pixel_width), (24, 640));
195/// ```
196pub struct TerminalViewportSize {
197    /// Terminal grid size in rows and columns.
198    pub terminal: TerminalSize,
199    /// Rounded content width in the 16-bit PTY protocol range.
200    pub pixel_width: u16,
201    /// Rounded content height in the 16-bit PTY protocol range.
202    pub pixel_height: u16,
203}
204
205impl TerminalViewportSize {
206    /// Stores the resize payload unchanged.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// use ailloli_ui_terminal_core::TerminalSize;
212    /// use ailloli_ui_widgets::controls::TerminalViewportSize;
213    /// let viewport = TerminalViewportSize::new(TerminalSize::new(30, 100), 800, 600);
214    /// assert_eq!(viewport.terminal.cols, 100);
215    /// ```
216    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)]
226/// Selection granularity recorded by the terminal widget.
227///
228/// Single, repeated double, and repeated triple clicks select character, word,
229/// and line granularity respectively. A configured initial mode is retained as
230/// metadata until the next click, which derives its mode from click count.
231///
232/// # Examples
233///
234/// ```
235/// use ailloli_ui_widgets::controls::TerminalSelectionMode;
236/// let modes = [
237///     TerminalSelectionMode::Character,
238///     TerminalSelectionMode::Word,
239///     TerminalSelectionMode::Line,
240/// ];
241/// assert_eq!(modes.len(), 3);
242/// assert_eq!(TerminalSelectionMode::default(), TerminalSelectionMode::Character);
243/// ```
244pub enum TerminalSelectionMode {
245    /// Select one cell/range endpoint; the default.
246    #[default]
247    Character,
248    /// Expand across alphanumeric and `_ - . / :` word cells.
249    Word,
250    /// Select complete visual lines.
251    Line,
252}
253
254#[derive(Clone, Debug, PartialEq)]
255/// Resolved terminal colors, typography, and logical-pixel geometry.
256///
257/// Runtime measurement clamps fallback `char_width` and `line_height` to at
258/// least `1.0`. Padding can collapse content to zero; other custom non-finite
259/// geometry may propagate into layout or painting.
260///
261/// # Examples
262///
263/// ```
264/// use ailloli_ui_core::Theme;
265/// use ailloli_ui_widgets::controls::TerminalWidgetStyle;
266/// let style = TerminalWidgetStyle::from_theme(Theme::dark());
267/// assert_eq!((style.width, style.height), (760.0, 280.0));
268/// assert_eq!((style.line_height, style.char_width), (19.0, 7.8));
269/// ```
270pub struct TerminalWidgetStyle {
271    /// Rounded terminal surface fill.
272    pub background: Color,
273    /// Unfocused outer border.
274    pub border: Border,
275    /// Border repainted over the outer border while focused.
276    pub focus_ring: Border,
277    /// Base monospace terminal text style.
278    pub text: TextStyle,
279    /// Selection highlight fill.
280    pub selection_background: Color,
281    /// Cursor fill.
282    pub cursor: Color,
283    /// Scrollbar track fill.
284    pub scrollbar_track: Color,
285    /// Scrollbar thumb fill.
286    pub scrollbar_thumb: Color,
287    /// Error diagnostic accent.
288    pub diagnostic_error: Color,
289    /// Warning diagnostic accent.
290    pub diagnostic_warning: Color,
291    /// Informational diagnostic accent.
292    pub diagnostic_info: Color,
293    /// Hint diagnostic accent.
294    pub diagnostic_hint: Color,
295    /// Terminal surface corner radii.
296    pub radius: Radius,
297    /// Horizontal content padding in logical pixels.
298    pub padding_x: f32,
299    /// Vertical content padding in logical pixels.
300    pub padding_y: f32,
301    /// Intrinsic widget width in logical pixels.
302    pub width: f32,
303    /// Intrinsic widget height in logical pixels.
304    pub height: f32,
305    /// Terminal row height and scroll-line amount in logical pixels.
306    pub line_height: f32,
307    /// Fallback cell width without a text system, in logical pixels.
308    pub char_width: f32,
309    /// Scrollbar track/thumb width in logical pixels.
310    pub scrollbar_width: f32,
311    /// Scrollbar distance from widget edges and reserved content gap.
312    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    /// Resolves the dark terminal presentation from a UI theme.
323    ///
324    /// # Examples
325    ///
326    /// ```
327    /// use ailloli_ui_core::Theme;
328    /// use ailloli_ui_widgets::controls::TerminalWidgetStyle;
329    /// let style = TerminalWidgetStyle::from_theme(Theme::default());
330    /// assert_eq!((style.padding_x, style.padding_y), (12.0, 10.0));
331    /// assert_eq!((style.scrollbar_width, style.scrollbar_inset), (6.0, 4.0));
332    /// ```
333    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
361/// Interactive view of a live [`TerminalState`].
362///
363/// The state signal is both read and updated for local/external resize results.
364/// Without an input callback the widget is read-only and unhandled navigation
365/// keys scroll it. With a callback, keyboard, paste, and enabled terminal mouse
366/// tracking produce protocol bytes. Ctrl+Shift+C/V are reserved for clipboard;
367/// Shift+Page/Home/End always scrolls locally. Scrollbar track and thumb
368/// interactions are handled locally before terminal mouse reporting and never
369/// emit protocol bytes. With mouse tracking enabled, an unmodified wheel remains
370/// terminal input, while `Shift` keeps its existing local-history bypass.
371///
372/// # Examples
373///
374/// ```
375/// use ailloli_ui_runtime::component::State;
376/// use ailloli_ui_terminal_core::TerminalState;
377/// use ailloli_ui_widgets::controls::Terminal;
378/// let state = State::new(TerminalState::new());
379/// let terminal: Terminal<()> = Terminal::new(state).follow_output(true);
380/// let _ = terminal;
381/// ```
382pub struct Terminal<A = ()> {
383    /// Layout configuration initialized from style width/height.
384    pub(crate) layout: LayoutStyle,
385    /// Flex behavior used by the parent layout.
386    pub(crate) flex_item: FlexItemStyle,
387    /// Live terminal emulator snapshot.
388    state: Signal<TerminalState>,
389    /// Resolved paint and cell-fallback geometry.
390    style: TerminalWidgetStyle,
391    /// Initial non-negative vertical scroll offset in logical pixels.
392    initial_scroll_y: f32,
393    /// Optional initial visual-line selection.
394    selection: Option<TerminalSelection>,
395    /// Initial retained selection-mode metadata.
396    selection_mode: TerminalSelectionMode,
397    /// Whether new output initially keeps the viewport at the bottom.
398    follow_output: bool,
399    /// Whether to resize local state without an external resize callback.
400    auto_resize: bool,
401    /// Whether to reserve and paint the vertical scrollbar.
402    scrollbars: bool,
403    /// Optional protocol-byte consumer.
404    on_input: Option<InputHandler<A>>,
405    /// Optional complete-state polling callback.
406    state_sync: Option<StateSync>,
407    /// Optional compact resize callback.
408    resize_sync: Option<ResizeSync>,
409    /// Optional measured geometry callback; takes priority over resize sync.
410    geometry_sync: Option<GeometrySync>,
411}
412
413crate::impl_layout_builders!(Terminal);
414
415impl<A: 'static> Terminal<A> {
416    /// Creates a focused-capable terminal from a writable state signal.
417    ///
418    /// It defaults to 760 by 280 logical pixels, follows output, auto-resizes
419    /// local state, shows scrollbars, and has no input/synchronization callbacks.
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// use ailloli_ui_runtime::component::State;
425    /// use ailloli_ui_terminal_core::TerminalState;
426    /// use ailloli_ui_widgets::controls::Terminal;
427    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()));
428    /// let _ = terminal;
429    /// ```
430    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    /// Replaces visual style and resets layout width/height to its intrinsic size.
453    ///
454    /// Call layout builders after this method to override those dimensions.
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// use ailloli_ui_runtime::component::State;
460    /// use ailloli_ui_terminal_core::TerminalState;
461    /// use ailloli_ui_widgets::controls::{Terminal, TerminalWidgetStyle};
462    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()))
463    ///     .terminal_style(TerminalWidgetStyle::default())
464    ///     .width(900.0);
465    /// let _ = terminal;
466    /// ```
467    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    /// Sets initial vertical scroll offset in logical pixels.
474    ///
475    /// Negative values and NaN become zero. Positive infinity is retained and
476    /// subsequently clamps to the bottom during viewport synchronization.
477    ///
478    /// # Examples
479    ///
480    /// ```
481    /// use ailloli_ui_runtime::component::State;
482    /// use ailloli_ui_terminal_core::TerminalState;
483    /// use ailloli_ui_widgets::controls::Terminal;
484    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()))
485    ///     .initial_scroll_y(120.0);
486    /// let _ = terminal;
487    /// ```
488    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    /// Sets the initial selection in visual-line/cell coordinates.
494    ///
495    /// Line indices are clamped to available visual lines during paint; column
496    /// endpoints are clamped independently for each extracted/highlighted line.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use ailloli_ui_runtime::component::State;
502    /// use ailloli_ui_terminal_core::TerminalState;
503    /// use ailloli_ui_widgets::controls::{Terminal, TerminalPosition, TerminalSelection};
504    /// let selection = TerminalSelection::new(
505    ///     TerminalPosition::new(0, 0),
506    ///     TerminalPosition::new(0, 4),
507    /// );
508    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new())).selection(selection);
509    /// let _ = terminal;
510    /// ```
511    pub fn selection(mut self, selection: TerminalSelection) -> Self {
512        self.selection = Some(selection);
513        self
514    }
515
516    /// Sets initial retained selection-mode metadata.
517    ///
518    /// Pointer clicks subsequently replace it according to click count.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// use ailloli_ui_runtime::component::State;
524    /// use ailloli_ui_terminal_core::TerminalState;
525    /// use ailloli_ui_widgets::controls::{Terminal, TerminalSelectionMode};
526    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()))
527    ///     .selection_mode(TerminalSelectionMode::Word);
528    /// let _ = terminal;
529    /// ```
530    pub fn selection_mode(mut self, mode: TerminalSelectionMode) -> Self {
531        self.selection_mode = mode;
532        self
533    }
534
535    /// Sets whether line-count changes keep the viewport at the bottom.
536    ///
537    /// User scrolling turns follow mode off when farther than one cell height
538    /// from the bottom and on again within that threshold.
539    ///
540    /// # Examples
541    ///
542    /// ```
543    /// use ailloli_ui_runtime::component::State;
544    /// use ailloli_ui_terminal_core::TerminalState;
545    /// use ailloli_ui_widgets::controls::Terminal;
546    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new())).follow_output(false);
547    /// let _ = terminal;
548    /// ```
549    pub fn follow_output(mut self, follow_output: bool) -> Self {
550        self.follow_output = follow_output;
551        self
552    }
553
554    /// Requests an initial bottom scroll and enables output following.
555    ///
556    /// This uses [`f32::MAX`] as a sentinel that is clamped to the actual maximum.
557    ///
558    /// # Examples
559    ///
560    /// ```
561    /// use ailloli_ui_runtime::component::State;
562    /// use ailloli_ui_terminal_core::TerminalState;
563    /// use ailloli_ui_widgets::controls::Terminal;
564    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new())).jump_bottom();
565    /// let _ = terminal;
566    /// ```
567    pub fn jump_bottom(mut self) -> Self {
568        self.initial_scroll_y = f32::MAX;
569        self.follow_output = true;
570        self
571    }
572
573    /// Enables or disables local terminal-grid resizing.
574    ///
575    /// Geometry/resize callbacks take precedence regardless of this flag. The
576    /// default is `true`.
577    ///
578    /// # Examples
579    ///
580    /// ```
581    /// use ailloli_ui_runtime::component::State;
582    /// use ailloli_ui_terminal_core::TerminalState;
583    /// use ailloli_ui_widgets::controls::Terminal;
584    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new())).auto_resize(false);
585    /// let _ = terminal;
586    /// ```
587    pub fn auto_resize(mut self, auto_resize: bool) -> Self {
588        self.auto_resize = auto_resize;
589        self
590    }
591
592    /// Shows/reserves or hides/releases the interactive vertical scrollbar.
593    ///
594    /// Scrolling remains available when hidden. The default is `true`.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use ailloli_ui_runtime::component::State;
600    /// use ailloli_ui_terminal_core::TerminalState;
601    /// use ailloli_ui_widgets::controls::Terminal;
602    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new())).scrollbars(false);
603    /// let _ = terminal;
604    /// ```
605    pub fn scrollbars(mut self, scrollbars: bool) -> Self {
606        self.scrollbars = scrollbars;
607        self
608    }
609
610    /// Maps each encoded terminal input byte vector to an application action.
611    ///
612    /// Keyboard input, bracketed paste, and enabled mouse-tracking reports share
613    /// this callback. A later input builder replaces it.
614    ///
615    /// # Examples
616    ///
617    /// ```
618    /// use ailloli_ui_runtime::component::State;
619    /// use ailloli_ui_terminal_core::TerminalState;
620    /// use ailloli_ui_widgets::controls::Terminal;
621    /// #[derive(Clone)]
622    /// enum Action { Input(Vec<u8>) }
623    /// let terminal = Terminal::new(State::new(TerminalState::new())).on_input(Action::Input);
624    /// let _ = terminal;
625    /// ```
626    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    /// Installs a context-aware encoded-input handler.
632    ///
633    /// A later input builder replaces it.
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// use ailloli_ui_runtime::component::State;
639    /// use ailloli_ui_terminal_core::TerminalState;
640    /// use ailloli_ui_widgets::controls::Terminal;
641    /// let terminal = Terminal::<()>::new(State::new(TerminalState::new()))
642    ///     .on_input_ctx(|_ctx, bytes| assert!(!bytes.is_empty()));
643    /// let _ = terminal;
644    /// ```
645    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    /// Installs a state poll invoked during authoritative layout and event handling.
651    ///
652    /// `Some(state)` replaces the signal only when different; `None` leaves it
653    /// unchanged. A layout poll is staged and becomes visible only after that
654    /// authoritative layout commits; paint never polls or mutates terminal state.
655    /// The callback should be fast and non-blocking.
656    ///
657    /// # Examples
658    ///
659    /// ```
660    /// use ailloli_ui_runtime::component::State;
661    /// use ailloli_ui_terminal_core::TerminalState;
662    /// use ailloli_ui_widgets::controls::Terminal;
663    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()))
664    ///     .sync_state_from(|| None);
665    /// let _ = terminal;
666    /// ```
667    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    /// Installs a compact resize callback.
673    ///
674    /// It runs after committed geometry or state-grid changes when no geometry
675    /// callback is installed. Returning `Some` replaces differing state;
676    /// returning `None` supports side-effect-only PTY resize requests.
677    ///
678    /// # Examples
679    ///
680    /// ```
681    /// use ailloli_ui_runtime::component::State;
682    /// use ailloli_ui_terminal_core::TerminalState;
683    /// use ailloli_ui_widgets::controls::Terminal;
684    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()))
685    ///     .sync_resize_to(|viewport| { assert!(viewport.terminal.cols >= 1); None });
686    /// let _ = terminal;
687    /// ```
688    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    /// Installs the highest-priority measured-geometry callback.
697    ///
698    /// It receives 32-bit rounded content extents, cell metrics, and grid size
699    /// after committed geometry or state-grid changes. `Some` replaces differing
700    /// state; `None` supports side-effect-only synchronization.
701    ///
702    /// # Examples
703    ///
704    /// ```
705    /// use ailloli_ui_runtime::component::State;
706    /// use ailloli_ui_terminal_core::TerminalState;
707    /// use ailloli_ui_widgets::controls::Terminal;
708    /// let terminal: Terminal<()> = Terminal::new(State::new(TerminalState::new()))
709    ///     .sync_geometry_to(|geometry| { assert!(geometry.cols >= 1); None });
710    /// let _ = terminal;
711    /// ```
712    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
721/// Component properties used to allocate scroll, geometry, and selection state.
722struct TerminalComponent<A> {
723    /// Outer logical sizing policy.
724    layout: LayoutStyle,
725    /// Caller-owned terminal grid, history, cursor, and mode state.
726    state: Signal<TerminalState>,
727    /// Font, color, padding, cursor, selection, and scrollbar styling.
728    style: TerminalWidgetStyle,
729    /// Initial vertical history offset in logical lines.
730    initial_scroll_y: f32,
731    /// Optional initial terminal-cell selection.
732    selection: Option<TerminalSelection>,
733    /// Character, word, or line selection expansion mode.
734    selection_mode: TerminalSelectionMode,
735    /// Whether new output should keep the viewport at the history end.
736    follow_output: bool,
737    /// Whether committed layout should resize terminal rows and columns.
738    auto_resize: bool,
739    /// Whether overflow paints visual scrollbars.
740    scrollbars: bool,
741    /// Optional callback receiving encoded keyboard/mouse input bytes.
742    on_input: Option<InputHandler<A>>,
743    /// Optional sink receiving widget-driven terminal-state changes.
744    state_sync: Option<StateSync>,
745    /// Optional sink receiving row/column resize requests.
746    resize_sync: Option<ResizeSync>,
747    /// Optional sink receiving committed logical/pixel geometry.
748    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
811/// Retained terminal widget implementing synchronization, input, and painting.
812struct TerminalWidget<A> {
813    /// Outer logical sizing policy.
814    layout: LayoutStyle,
815    /// Caller-owned terminal grid, history, cursor, and mode state.
816    state: Signal<TerminalState>,
817    /// Retained viewport offset in logical pixels.
818    scroll: Signal<ScrollState>,
819    /// Last geometry emitted after committed layout.
820    last_geometry: Signal<Option<TerminalGeometry>>,
821    /// Terminal size last written through state synchronization.
822    last_resize_state_size: Signal<Option<TerminalSize>>,
823    /// Whether output growth currently keeps the viewport at the end.
824    follow_output: Signal<bool>,
825    /// Line count observed during the previous synchronization pass.
826    last_line_count: Signal<usize>,
827    /// Retained terminal-cell selection.
828    selection: Signal<Option<TerminalSelection>>,
829    /// Character, word, or line selection expansion mode.
830    selection_mode: Signal<TerminalSelectionMode>,
831    /// Terminal cell captured at pointer-drag start.
832    drag_anchor: Signal<Option<TerminalPosition>>,
833    /// Mouse button currently captured for selection or reporting.
834    mouse_button: Signal<Option<MouseButton>>,
835    /// Terminal cell of the previous click for multi-click detection.
836    last_click: Signal<Option<TerminalPosition>>,
837    /// Saturating consecutive click count at the same cell.
838    click_count: Signal<u8>,
839    /// Retained hover and captured scrollbar gesture.
840    scrollbar_interaction: Signal<ScrollbarInteraction>,
841    /// Font, color, padding, cursor, selection, and scrollbar styling.
842    style: TerminalWidgetStyle,
843    /// Wheel scaling and vertical axis-filtering policy.
844    behavior: ScrollBehavior,
845    /// Whether committed layout should resize terminal rows and columns.
846    auto_resize: bool,
847    /// Whether overflow paints visual scrollbars.
848    scrollbars: bool,
849    /// Optional callback receiving encoded keyboard/mouse input bytes.
850    on_input: Option<InputHandler<A>>,
851    /// Optional sink receiving widget-driven terminal-state changes.
852    state_sync: Option<StateSync>,
853    /// Optional sink receiving row/column resize requests.
854    resize_sync: Option<ResizeSync>,
855    /// Optional sink receiving committed logical/pixel geometry.
856    geometry_sync: Option<GeometrySync>,
857    /// Authoritative layout-derived state awaiting successful commit.
858    pending_layout: RefCell<Option<TransactionalLayoutPending<PendingTerminalLayout>>>,
859}
860
861/// State derived by one authoritative terminal layout attempt.
862struct PendingTerminalLayout {
863    /// Complete external state polled for this attempt, when it differs.
864    external_state: Option<TerminalState>,
865    /// Cell and viewport geometry measured by this attempt.
866    geometry: TerminalGeometry,
867    /// Scroll offset clamped against the state used by this attempt.
868    scroll: ScrollState,
869    /// Visual-line count used by the staged scroll calculation.
870    line_count: usize,
871    /// Gesture state reconciled against the staged scrollbar geometry.
872    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    /// Polls external state without publishing it into the retained signal.
1202    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    /// Polls external state during input and replaces the signal when changed.
1210    fn sync_external_state(&self) -> bool {
1211        let current = with_untracked_reads(|| self.state.read());
1212        let Some(next) = self.poll_external_state(&current) else {
1213            return false;
1214        };
1215        self.state.set(next);
1216        true
1217    }
1218
1219    /// Publishes changed geometry through geometry, resize, or local-resize priority.
1220    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    /// Resizes local state only when its active-screen grid differs.
1279    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    /// Insets widget bounds and reserves scrollbar width when enabled.
1290    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    /// Measures cell metrics and derives complete geometry for content bounds.
1305    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    /// Reads committed cell metrics or the style-based fallback.
1316    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    /// Counts scrollback plus screen lines, or alternate-screen lines alone.
1324    fn visual_line_count(&self) -> usize {
1325        terminal_visual_line_count(&self.state.read())
1326    }
1327
1328    /// Builds vertical scroll metrics using the committed cell height.
1329    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    /// Resolves the styled vertical bar through the shared Core geometry.
1334    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    /// Resolves the styled vertical bar for an explicit staged scroll state.
1345    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    /// Follows changed output to bottom and clamps scroll to current metrics.
1368    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    /// Computes follow/clamp output without mutating retained state.
1379    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    /// Publishes one authoritative viewport snapshot after layout commits.
1403    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    /// Builds viewport/content extents for a visual-line count.
1415    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    /// Enables follow mode when the viewport is within one row of bottom.
1428    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    /// Converts repeated clicks at one cell into character/word/line modes.
1435    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    /// Maps a content-space pointer to a clamped visual line and cell column.
1451    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    /// Handles Shift+Page/Home/End as local scrolling before terminal input.
1475    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    /// Scrolls navigation keys when no terminal byte handler consumed them.
1498    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    /// Applies one-row, 86%-page, top, or bottom keyboard scrolling.
1519    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    /// Handles Ctrl+Shift+C/V selection copy and bracketed terminal paste.
1566    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    /// Encodes and dispatches mouse events when terminal tracking is active.
1601    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
1644/// Rounds a positive finite pixel extent and saturates it to `u32`.
1645fn 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
1652/// Measures an `M` cell width while retaining configured row height.
1653fn 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
1676/// Derives rounded pixel extents and floored grid dimensions from content.
1677fn 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
1689/// Floors positive finite cells into `1..=u16::MAX`, else returns one.
1690fn 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
1697/// Borrows visual lines for the active normal/alternate screen.
1698fn 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
1709/// Counts visual lines without allocating their reference vector.
1710fn 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
1717/// Converts the active-screen cursor row to a visual-line index.
1718fn 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
1725/// Extracts selected terminal text in visual-line order.
1726///
1727/// Normal-screen visual lines are scrollback followed by the visible screen;
1728/// alternate-screen visual lines contain no scrollback. Selection direction is
1729/// normalized, line indices clamp to available lines, and the ending column is
1730/// exclusive. Wide trailing cells are skipped, trailing ASCII spaces are removed
1731/// from each selected line, and lines are joined with `\n`. Empty state or an
1732/// empty range returns an empty string.
1733///
1734/// # Examples
1735///
1736/// ```
1737/// use ailloli_ui_terminal_core::TerminalState;
1738/// use ailloli_ui_widgets::controls::{
1739///     terminal_selection_text, TerminalPosition, TerminalSelection,
1740/// };
1741/// let mut state = TerminalState::new();
1742/// state.write_str("hello");
1743/// let selection = TerminalSelection::new(
1744///     TerminalPosition::new(0, 0),
1745///     TerminalPosition::new(0, 5),
1746/// );
1747/// assert_eq!(terminal_selection_text(&state, selection), "hello");
1748/// ```
1749pub 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
1773/// Extracts an exclusive cell range, skipping wide trailers and trimming spaces.
1774fn 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
1788/// Creates character, word-expanded, or whole-line selection at a position.
1789fn 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
1801/// Expands a position across adjacent terminal word cells on one visual line.
1802fn 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
1834/// Recognizes alphanumeric or shell/path punctuation in a leading/narrow cell.
1835fn 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
1847/// UTF-8 encodes paste text, adding bracketed-paste delimiters when enabled.
1848fn 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
1860/// Reads key/text character data and applies ASCII uppercase conversion.
1861fn 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
1868/// Borrowed state required to paint the currently visible terminal rows.
1869struct TerminalPaintModel<'a> {
1870    /// Borrowed font, color, padding, cursor, and selection styling.
1871    style: &'a TerminalWidgetStyle,
1872    /// Shared cell advance and line-height geometry in logical pixels.
1873    metrics: TerminalCellMetrics,
1874    /// Borrowed terminal cursor and mode state.
1875    state: &'a TerminalState,
1876    /// Visible history/screen lines in paint order.
1877    lines: &'a [&'a CoreTerminalLine],
1878    /// Current viewport offset in logical pixels.
1879    scroll: ScrollState,
1880    /// Optional terminal-cell selection to highlight.
1881    selection: Option<TerminalSelection>,
1882}
1883
1884/// Paints virtualized visible rows, diagnostics, selection, text, and cursor.
1885fn 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
1954/// Finds the first diagnostic whose inclusive source range covers a visual line.
1955fn 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
1966/// Paints a translucent diagnostic row and leading severity stripe.
1967fn 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
1992/// Paints a fixed-width severity badge at the row's trailing edge.
1993fn 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
2022/// Returns the compact uppercase label for every diagnostic severity.
2023fn 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
2032/// Resolves every diagnostic severity through terminal style colors.
2033fn 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
2045/// Shapes and paints non-empty styled terminal text at a row baseline.
2046fn 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
2074/// Produces a cached unwrapped styled layout for one terminal row fragment.
2075fn 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)]
2091/// Non-default background run for one terminal cell or wide-cell pair.
2092struct CellBackground {
2093    /// Starting terminal column.
2094    col: usize,
2095    /// Covered column count: one or two.
2096    cols: usize,
2097    /// Resolved background color.
2098    color: Color,
2099}
2100
2101/// Flattens terminal cells into text, foreground spans, and background runs.
2102fn 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
2142/// Resolves default/ANSI colors, inverse mode, and dim foreground alpha.
2143fn 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
2155/// Resolves every terminal color encoding to a concrete UI color.
2156fn 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
2166/// Resolves an ANSI palette index, clamping indices above 15 to white.
2167fn 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
2175/// Resolves the 256-color xterm palette: ANSI, color cube, then grayscale.
2176fn 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
2191/// Converts a color-cube coordinate in `0..=5` to its xterm channel value.
2192fn xterm_cube(v: u8) -> u8 {
2193    if v == 0 {
2194        0
2195    } else {
2196        55 + v * 40
2197    }
2198}
2199
2200/// Computes the IME cursor rectangle from widget bounds and scroll state.
2201fn 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
2224/// Computes a visible block, underline, or bar cursor rectangle.
2225fn 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
2271/// Creates a non-empty selection highlight clamped to content width.
2272fn 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
2292/// Resolves normalized exclusive selection columns for one visual line.
2293fn 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
2314/// Paints a proportional vertical scrollbar with a 24-pixel minimum thumb.
2315fn 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)]
2334/// Geometry and state used to encode a terminal mouse event.
2335struct TerminalMouseLayout {
2336    /// Pointer-active terminal content rectangle.
2337    content: Rect,
2338    /// Cell dimensions used for one-based row/column mapping.
2339    metrics: TerminalCellMetrics,
2340    /// Current vertical scroll offset.
2341    scroll: ScrollState,
2342    /// Visual-line count; zero disables encoding.
2343    line_count: usize,
2344}
2345
2346/// Encodes pointer button, motion, or wheel events using SGR/legacy mouse modes.
2347fn 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
2415/// Maps left/middle/right buttons to XTerm codes and rejects `Other`.
2416fn 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
2425/// Encodes a pressed key using default terminal modes.
2426///
2427/// Supported named keys are Enter, Backspace, Tab, Escape, four arrows,
2428/// Home/End, PageUp/PageDown, Delete, Insert, and Space. Character/dead-key text
2429/// is UTF-8. Ctrl combinations are limited to C, D, L, and Z. Alt prefixes one
2430/// Escape byte unless the base sequence already begins with Escape. Releases and
2431/// unsupported keys return `None`; repeat presses are encoded normally.
2432///
2433/// # Examples
2434///
2435/// ```
2436/// use ailloli_ui_core::event::{Key, KeyEvent, KeyState, Modifiers, NamedKey};
2437/// use ailloli_ui_widgets::controls::terminal_key_bytes;
2438/// let key = KeyEvent {
2439///     state: KeyState::Pressed,
2440///     key: Key::Named(NamedKey::Enter),
2441///     modifiers: Modifiers::default(),
2442///     repeat: false,
2443///     pointer_pos: None,
2444///     text: None,
2445/// };
2446/// assert_eq!(terminal_key_bytes(&key), Some(b"\r".to_vec()));
2447/// ```
2448pub fn terminal_key_bytes(key: &KeyEvent) -> Option<Vec<u8>> {
2449    terminal_key_bytes_with_modes(key, &TerminalModes::default())
2450}
2451
2452/// Encodes a pressed key while honoring terminal application-cursor mode.
2453///
2454/// When `application_cursor` is enabled, arrows and Home/End use SS3 sequences;
2455/// all other mappings match [`terminal_key_bytes`].
2456///
2457/// # Examples
2458///
2459/// ```
2460/// use ailloli_ui_core::event::{Key, KeyEvent, KeyState, Modifiers, NamedKey};
2461/// use ailloli_ui_terminal_core::TerminalModes;
2462/// use ailloli_ui_widgets::controls::terminal_key_bytes_with_modes;
2463/// let key = KeyEvent {
2464///     state: KeyState::Pressed,
2465///     key: Key::Named(NamedKey::ArrowUp),
2466///     modifiers: Modifiers::default(),
2467///     repeat: false,
2468///     pointer_pos: None,
2469///     text: None,
2470/// };
2471/// let modes = TerminalModes { application_cursor: true, ..TerminalModes::default() };
2472/// assert_eq!(terminal_key_bytes_with_modes(&key, &modes), Some(b"\x1bOA".to_vec()));
2473/// ```
2474pub 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
2522/// Encodes the supported single-character Ctrl combinations C, D, L, and Z.
2523fn 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)]
2539/// Scenarios for input protocols, geometry synchronization, and text extraction.
2540mod 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    /// Builds a pressed non-repeat key event for protocol mapping scenarios.
2553    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}