ailloli_ui_widgets/controls/terminal.rs
1//! Retained terminal-log viewer with streaming events, search, selection, and scrolling.
2//!
3//! The widget renders styled logical lines rather than emulating a terminal
4//! protocol. Event chunks are joined and split on newlines, complete history is
5//! bounded, and the optional event source is drained during layout, paint, and input.
6
7use std::cell::{Cell, RefCell};
8use std::collections::VecDeque;
9use std::rc::Rc;
10use std::sync::Arc;
11
12use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
13use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
14use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
15use ailloli_ui_core::geometry::{Constraints, Rect, Size};
16use ailloli_ui_core::scroll::{
17 ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState, ScrollbarAxis, ScrollbarGeometry,
18 ScrollbarGeometrySpec,
19};
20use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
21use ailloli_ui_core::{ClipShape, Color, FontId, Offset, TextStyle, Theme};
22use ailloli_ui_runtime::component::reactive::with_untracked_reads;
23use ailloli_ui_runtime::component::{
24 Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
25};
26use ailloli_ui_runtime::input::{EventCtx, FocusPolicy, InputRole};
27use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
28use ailloli_ui_runtime::scene::PaintCtx;
29use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, DrawRect, DrawText, Invalidation};
30use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
31
32use crate::scrollbar::{thumb_color_for_state, ScrollbarInteraction};
33use crate::transactional_layout::TransactionalLayoutPending;
34
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36/// Semantic line category used to choose a default text style.
37///
38/// # Examples
39///
40/// ```
41/// use ailloli_ui_widgets::controls::TerminalLineKind;
42/// assert_eq!(TerminalLineKind::default(), TerminalLineKind::Stdout);
43/// assert_ne!(TerminalLineKind::Stderr, TerminalLineKind::Success);
44/// ```
45pub enum TerminalLineKind {
46 /// Shell or application prompt text.
47 Prompt,
48 /// Entered command text; currently styled like a prompt.
49 Command,
50 #[default]
51 /// Normal process output.
52 Stdout,
53 /// Error-stream output.
54 Stderr,
55 /// Viewer or process-status message.
56 System,
57 /// Successful-result message.
58 Success,
59 /// Warning message.
60 Warning,
61}
62
63#[derive(Debug, Clone, Copy, Default, PartialEq)]
64/// Optional per-line colors and emphasis flags.
65///
66/// `foreground` overrides the kind color and `background` paints the complete
67/// row. `dim` multiplies foreground alpha by `0.72`; `bold` is retained metadata
68/// but is not currently interpreted by the renderer.
69///
70/// # Examples
71///
72/// ```
73/// use ailloli_ui_core::Color;
74/// use ailloli_ui_widgets::controls::TerminalLineAttrs;
75/// let attrs = TerminalLineAttrs { foreground: Some(Color::WHITE), bold: true, ..Default::default() };
76/// assert!(attrs.bold);
77/// ```
78pub struct TerminalLineAttrs {
79 /// Optional text-color override.
80 pub foreground: Option<Color>,
81 /// Optional full-row background.
82 pub background: Option<Color>,
83 /// Reserved emphasis flag; currently not rendered.
84 pub bold: bool,
85 /// Whether to multiply foreground alpha by `0.72`.
86 pub dim: bool,
87}
88
89#[derive(Debug, Clone, PartialEq)]
90/// One logical terminal line with semantic and optional timestamp metadata.
91///
92/// Text is stored unchanged and never parsed for ANSI escape sequences.
93///
94/// # Examples
95///
96/// ```
97/// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
98/// let line = TerminalLine::stderr("failed").timestamp_ms(1_000);
99/// assert_eq!(line.kind, TerminalLineKind::Stderr);
100/// assert_eq!(line.timestamp_ms, Some(1_000));
101/// ```
102pub struct TerminalLine {
103 /// Unparsed line text without an implied newline.
104 pub text: String,
105 /// Semantic category selecting the base text style.
106 pub kind: TerminalLineKind,
107 /// Optional color and emphasis overrides.
108 pub attrs: TerminalLineAttrs,
109 /// Optional caller-defined timestamp in milliseconds.
110 pub timestamp_ms: Option<i64>,
111}
112
113impl TerminalLine {
114 /// Creates an untimestamped stdout line with default attributes.
115 ///
116 /// # Examples
117 ///
118 /// ```
119 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
120 /// let line = TerminalLine::new("ready");
121 /// assert_eq!((line.text.as_str(), line.kind), ("ready", TerminalLineKind::Stdout));
122 /// ```
123 pub fn new(text: impl Into<String>) -> Self {
124 Self {
125 text: text.into(),
126 kind: TerminalLineKind::Stdout,
127 attrs: TerminalLineAttrs::default(),
128 timestamp_ms: None,
129 }
130 }
131
132 /// Creates a prompt line.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
138 /// assert_eq!(TerminalLine::prompt("$ ").kind, TerminalLineKind::Prompt);
139 /// ```
140 pub fn prompt(text: impl Into<String>) -> Self {
141 Self::new(text).kind(TerminalLineKind::Prompt)
142 }
143
144 /// Creates a command line.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
150 /// assert_eq!(TerminalLine::command("cargo test").kind, TerminalLineKind::Command);
151 /// ```
152 pub fn command(text: impl Into<String>) -> Self {
153 Self::new(text).kind(TerminalLineKind::Command)
154 }
155
156 /// Creates a stderr line.
157 ///
158 /// # Examples
159 ///
160 /// ```
161 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
162 /// assert_eq!(TerminalLine::stderr("error").kind, TerminalLineKind::Stderr);
163 /// ```
164 pub fn stderr(text: impl Into<String>) -> Self {
165 Self::new(text).kind(TerminalLineKind::Stderr)
166 }
167
168 /// Creates a system-status line.
169 ///
170 /// # Examples
171 ///
172 /// ```
173 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
174 /// assert_eq!(TerminalLine::system("connected").kind, TerminalLineKind::System);
175 /// ```
176 pub fn system(text: impl Into<String>) -> Self {
177 Self::new(text).kind(TerminalLineKind::System)
178 }
179
180 /// Creates a success line.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
186 /// assert_eq!(TerminalLine::success("done").kind, TerminalLineKind::Success);
187 /// ```
188 pub fn success(text: impl Into<String>) -> Self {
189 Self::new(text).kind(TerminalLineKind::Success)
190 }
191
192 /// Creates a warning line.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
198 /// assert_eq!(TerminalLine::warning("retrying").kind, TerminalLineKind::Warning);
199 /// ```
200 pub fn warning(text: impl Into<String>) -> Self {
201 Self::new(text).kind(TerminalLineKind::Warning)
202 }
203
204 /// Replaces the semantic line category.
205 ///
206 /// # Examples
207 ///
208 /// ```
209 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineKind};
210 /// assert_eq!(TerminalLine::new("ok").kind(TerminalLineKind::Success).kind, TerminalLineKind::Success);
211 /// ```
212 pub fn kind(mut self, kind: TerminalLineKind) -> Self {
213 self.kind = kind;
214 self
215 }
216
217 /// Replaces all per-line attributes.
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalLineAttrs};
223 /// let line = TerminalLine::new("quiet").attrs(TerminalLineAttrs { dim: true, ..Default::default() });
224 /// assert!(line.attrs.dim);
225 /// ```
226 pub fn attrs(mut self, attrs: TerminalLineAttrs) -> Self {
227 self.attrs = attrs;
228 self
229 }
230
231 /// Sets caller-defined millisecond timestamp metadata.
232 ///
233 /// Negative values are retained verbatim and no clock epoch is imposed.
234 ///
235 /// # Examples
236 ///
237 /// ```
238 /// use ailloli_ui_widgets::controls::TerminalLine;
239 /// assert_eq!(TerminalLine::new("boot").timestamp_ms(-1).timestamp_ms, Some(-1));
240 /// ```
241 pub fn timestamp_ms(mut self, timestamp_ms: i64) -> Self {
242 self.timestamp_ms = Some(timestamp_ms);
243 self
244 }
245}
246
247#[derive(Debug, Clone, PartialEq)]
248/// Mutation consumed by a [`TerminalView`] buffer.
249///
250/// # Examples
251///
252/// ```
253/// use ailloli_ui_widgets::controls::{TerminalEventKind, TerminalLine};
254/// let event = TerminalEventKind::AppendLine(TerminalLine::new("ready"));
255/// assert!(matches!(event, TerminalEventKind::AppendLine(_)));
256/// ```
257pub enum TerminalEventKind {
258 /// Flushes a pending chunk then appends one complete line.
259 AppendLine(TerminalLine),
260 /// Joins stdout text to the partial line and splits on `\n`.
261 StdoutChunk(String),
262 /// Joins stderr text to the partial line and splits on `\n`.
263 StderrChunk(String),
264 /// Flushes a pending chunk then appends an untimestamped system line.
265 Status(String),
266 /// Removes complete and partial lines.
267 Clear,
268}
269
270#[derive(Debug, Clone, PartialEq)]
271/// Sequenced terminal-buffer mutation with optional timestamp metadata.
272///
273/// Sequence numbers are retained for clients but events are applied in supplied
274/// order without sorting or duplicate rejection.
275///
276/// # Examples
277///
278/// ```
279/// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind};
280/// let event = TerminalEvent::clear(9);
281/// assert_eq!(event.sequence, 9);
282/// assert!(matches!(event.kind, TerminalEventKind::Clear));
283/// ```
284pub struct TerminalEvent {
285 /// Caller-assigned sequence metadata.
286 pub sequence: u64,
287 /// Optional timestamp inherited by appended lines/chunks where applicable.
288 pub timestamp_ms: Option<i64>,
289 /// Buffer mutation payload.
290 pub kind: TerminalEventKind,
291}
292
293impl TerminalEvent {
294 /// Creates an untimestamped event with the supplied sequence metadata.
295 ///
296 /// # Examples
297 ///
298 /// ```
299 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind};
300 /// let event = TerminalEvent::new(1, TerminalEventKind::Clear);
301 /// assert_eq!(event.timestamp_ms, None);
302 /// ```
303 pub fn new(sequence: u64, kind: TerminalEventKind) -> Self {
304 Self {
305 sequence,
306 timestamp_ms: None,
307 kind,
308 }
309 }
310
311 /// Creates a complete-line append event.
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind, TerminalLine};
317 /// let event = TerminalEvent::append_line(2, TerminalLine::new("done"));
318 /// assert!(matches!(event.kind, TerminalEventKind::AppendLine(_)));
319 /// ```
320 pub fn append_line(sequence: u64, line: TerminalLine) -> Self {
321 Self::new(sequence, TerminalEventKind::AppendLine(line))
322 }
323
324 /// Creates a streaming stdout chunk event.
325 ///
326 /// # Examples
327 ///
328 /// ```
329 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind};
330 /// let event = TerminalEvent::stdout_chunk(3, "one\ntwo");
331 /// assert!(matches!(event.kind, TerminalEventKind::StdoutChunk(_)));
332 /// ```
333 pub fn stdout_chunk(sequence: u64, text: impl Into<String>) -> Self {
334 Self::new(sequence, TerminalEventKind::StdoutChunk(text.into()))
335 }
336
337 /// Creates a streaming stderr chunk event.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind};
343 /// let event = TerminalEvent::stderr_chunk(4, "warning");
344 /// assert!(matches!(event.kind, TerminalEventKind::StderrChunk(_)));
345 /// ```
346 pub fn stderr_chunk(sequence: u64, text: impl Into<String>) -> Self {
347 Self::new(sequence, TerminalEventKind::StderrChunk(text.into()))
348 }
349
350 /// Creates a system-status event.
351 ///
352 /// # Examples
353 ///
354 /// ```
355 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind};
356 /// let event = TerminalEvent::status(5, "connected");
357 /// assert!(matches!(event.kind, TerminalEventKind::Status(_)));
358 /// ```
359 pub fn status(sequence: u64, text: impl Into<String>) -> Self {
360 Self::new(sequence, TerminalEventKind::Status(text.into()))
361 }
362
363 /// Creates an event that clears complete and partial lines.
364 ///
365 /// # Examples
366 ///
367 /// ```
368 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventKind};
369 /// assert!(matches!(TerminalEvent::clear(6).kind, TerminalEventKind::Clear));
370 /// ```
371 pub fn clear(sequence: u64) -> Self {
372 Self::new(sequence, TerminalEventKind::Clear)
373 }
374
375 /// Sets caller-defined millisecond timestamp metadata.
376 ///
377 /// # Examples
378 ///
379 /// ```
380 /// use ailloli_ui_widgets::controls::TerminalEvent;
381 /// assert_eq!(TerminalEvent::clear(1).timestamp_ms(42).timestamp_ms, Some(42));
382 /// ```
383 pub fn timestamp_ms(mut self, timestamp_ms: i64) -> Self {
384 self.timestamp_ms = Some(timestamp_ms);
385 self
386 }
387}
388
389/// Pull source drained by the terminal during layout, paint, and input.
390///
391/// Implementations should return promptly; events are applied in returned order.
392///
393/// # Examples
394///
395/// ```
396/// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventSource};
397/// struct Empty;
398/// impl TerminalEventSource for Empty { fn drain_events(&self) -> Vec<TerminalEvent> { Vec::new() } }
399/// assert!(Empty.drain_events().is_empty());
400/// ```
401pub trait TerminalEventSource: 'static {
402 /// Removes and returns currently pending events in application order.
403 ///
404 /// # Examples
405 ///
406 /// ```
407 /// use ailloli_ui_widgets::controls::{TerminalEventBuffer, TerminalEventSource};
408 /// let source = TerminalEventBuffer::new();
409 /// assert!(source.drain_events().is_empty());
410 /// ```
411 fn drain_events(&self) -> Vec<TerminalEvent>;
412}
413
414#[derive(Clone, Default)]
415/// Cloneable single-threaded FIFO event source.
416///
417/// Clones share the same `Rc<RefCell<_>>` queue. Reentrant mutable access panics
418/// according to [`RefCell`] rules; the type is not thread-safe.
419///
420/// # Examples
421///
422/// ```
423/// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventBuffer, TerminalEventSource};
424/// let writer = TerminalEventBuffer::new();
425/// let reader = writer.clone();
426/// writer.push(TerminalEvent::clear(1));
427/// assert_eq!(reader.drain_events().len(), 1);
428/// ```
429pub struct TerminalEventBuffer {
430 /// Shared pending FIFO.
431 pending: Rc<RefCell<VecDeque<TerminalEvent>>>,
432}
433
434impl TerminalEventBuffer {
435 /// Creates an empty shared queue.
436 ///
437 /// # Examples
438 ///
439 /// ```
440 /// use ailloli_ui_widgets::controls::TerminalEventBuffer;
441 /// assert!(TerminalEventBuffer::new().is_empty());
442 /// ```
443 pub fn new() -> Self {
444 Self::default()
445 }
446
447 /// Appends one event to the FIFO tail.
448 ///
449 /// # Panics
450 ///
451 /// Panics if the shared queue is already mutably borrowed reentrantly.
452 ///
453 /// # Examples
454 ///
455 /// ```
456 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventBuffer};
457 /// let buffer = TerminalEventBuffer::new();
458 /// buffer.push(TerminalEvent::clear(1));
459 /// assert!(!buffer.is_empty());
460 /// ```
461 pub fn push(&self, event: TerminalEvent) {
462 self.pending.borrow_mut().push_back(event);
463 }
464
465 /// Appends events to the FIFO tail in iterator order.
466 ///
467 /// # Panics
468 ///
469 /// Panics if the shared queue is already mutably borrowed reentrantly.
470 ///
471 /// # Examples
472 ///
473 /// ```
474 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalEventBuffer, TerminalEventSource};
475 /// let buffer = TerminalEventBuffer::new();
476 /// buffer.extend([TerminalEvent::clear(1), TerminalEvent::clear(2)]);
477 /// assert_eq!(buffer.drain_events().len(), 2);
478 /// ```
479 pub fn extend(&self, events: impl IntoIterator<Item = TerminalEvent>) {
480 self.pending.borrow_mut().extend(events);
481 }
482
483 /// Reports whether the shared queue currently has no pending event.
484 ///
485 /// # Panics
486 ///
487 /// Panics if the shared queue is already mutably borrowed.
488 ///
489 /// # Examples
490 ///
491 /// ```
492 /// use ailloli_ui_widgets::controls::TerminalEventBuffer;
493 /// assert!(TerminalEventBuffer::new().is_empty());
494 /// ```
495 pub fn is_empty(&self) -> bool {
496 self.pending.borrow().is_empty()
497 }
498}
499
500impl TerminalEventSource for TerminalEventBuffer {
501 /// Drains every queued event in FIFO order.
502 fn drain_events(&self) -> Vec<TerminalEvent> {
503 self.pending.borrow_mut().drain(..).collect()
504 }
505}
506
507#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
508/// Zero-based logical line and Unicode-scalar column.
509///
510/// # Examples
511///
512/// ```
513/// use ailloli_ui_widgets::controls::TerminalPosition;
514/// assert_eq!(TerminalPosition::new(2, 4), TerminalPosition { line: 2, column: 4 });
515/// ```
516pub struct TerminalPosition {
517 /// Zero-based logical line index.
518 pub line: usize,
519 /// Zero-based Unicode-scalar column; may exceed actual line length.
520 pub column: usize,
521}
522
523impl TerminalPosition {
524 /// Creates a position without bounds validation.
525 ///
526 /// # Examples
527 ///
528 /// ```
529 /// use ailloli_ui_widgets::controls::TerminalPosition;
530 /// let pos = TerminalPosition::new(1, 3);
531 /// assert_eq!((pos.line, pos.column), (1, 3));
532 /// ```
533 pub const fn new(line: usize, column: usize) -> Self {
534 Self { line, column }
535 }
536}
537
538#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
539/// Direction-preserving anchor/focus text selection.
540///
541/// # Examples
542///
543/// ```
544/// use ailloli_ui_widgets::controls::{TerminalPosition, TerminalSelection};
545/// let selection = TerminalSelection::new(TerminalPosition::new(0, 1), TerminalPosition::new(2, 3));
546/// assert_eq!(selection.anchor.line, 0);
547/// ```
548pub struct TerminalSelection {
549 /// Position where dragging began.
550 pub anchor: TerminalPosition,
551 /// Current drag position.
552 pub focus: TerminalPosition,
553}
554
555impl TerminalSelection {
556 /// Creates a selection without ordering or bounds normalization.
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use ailloli_ui_widgets::controls::{TerminalPosition, TerminalSelection};
562 /// let selection = TerminalSelection::new(TerminalPosition::new(3, 2), TerminalPosition::new(1, 0));
563 /// assert_eq!(selection.normalized().0.line, 1);
564 /// ```
565 pub const fn new(anchor: TerminalPosition, focus: TerminalPosition) -> Self {
566 Self { anchor, focus }
567 }
568
569 /// Selects from column zero of `start` through the end of `end`.
570 ///
571 /// `usize::MAX` is used as the end-of-line sentinel and is clamped during
572 /// painting; line indices are not validated here.
573 ///
574 /// # Examples
575 ///
576 /// ```
577 /// use ailloli_ui_widgets::controls::TerminalSelection;
578 /// let selection = TerminalSelection::lines(2, 4);
579 /// assert_eq!((selection.anchor.column, selection.focus.column), (0, usize::MAX));
580 /// ```
581 pub const fn lines(start: usize, end: usize) -> Self {
582 Self {
583 anchor: TerminalPosition::new(start, 0),
584 focus: TerminalPosition::new(end, usize::MAX),
585 }
586 }
587
588 /// Returns endpoints in lexicographic `(line, column)` order.
589 ///
590 /// # Examples
591 ///
592 /// ```
593 /// use ailloli_ui_widgets::controls::{TerminalPosition, TerminalSelection};
594 /// let (start, end) = TerminalSelection::new(TerminalPosition::new(2, 0), TerminalPosition::new(1, 9)).normalized();
595 /// assert_eq!((start.line, end.line), (1, 2));
596 /// ```
597 pub fn normalized(self) -> (TerminalPosition, TerminalPosition) {
598 if (self.anchor.line, self.anchor.column) <= (self.focus.line, self.focus.column) {
599 (self.anchor, self.focus)
600 } else {
601 (self.focus, self.anchor)
602 }
603 }
604
605 /// Clamps both line indices to an available buffer.
606 ///
607 /// Returns `None` for an empty buffer. Columns are retained verbatim and are
608 /// clamped against line text only when rendered.
609 ///
610 /// # Examples
611 ///
612 /// ```
613 /// use ailloli_ui_widgets::controls::TerminalSelection;
614 /// assert!(TerminalSelection::lines(1, 4).clamp(0).is_none());
615 /// assert_eq!(TerminalSelection::lines(1, 4).clamp(3).unwrap().focus.line, 2);
616 /// ```
617 pub fn clamp(self, line_count: usize) -> Option<Self> {
618 if line_count == 0 {
619 return None;
620 }
621 let max_line = line_count - 1;
622 Some(Self {
623 anchor: TerminalPosition::new(self.anchor.line.min(max_line), self.anchor.column),
624 focus: TerminalPosition::new(self.focus.line.min(max_line), self.focus.column),
625 })
626 }
627}
628
629#[derive(Debug, Clone, PartialEq, Eq)]
630/// One non-overlapping search hit expressed as UTF-8 byte offsets.
631///
632/// `start` is inclusive and `end` is exclusive within the matched line.
633///
634/// # Examples
635///
636/// ```
637/// use ailloli_ui_widgets::controls::TerminalSearchMatch;
638/// let hit = TerminalSearchMatch { line: 1, start: 2, end: 5 };
639/// assert_eq!(hit.end - hit.start, 3);
640/// ```
641pub struct TerminalSearchMatch {
642 /// Zero-based logical line index.
643 pub line: usize,
644 /// Inclusive UTF-8 byte offset.
645 pub start: usize,
646 /// Exclusive UTF-8 byte offset.
647 pub end: usize,
648}
649
650#[derive(Clone, Debug, PartialEq)]
651/// Terminal palette, typography, geometry, and scrollbar metrics.
652///
653/// Dimensions are logical pixels. Fields are consumed as supplied; nonpositive
654/// line height prevents line painting, while content dimensions are floored at
655/// zero. The default uses the default theme.
656///
657/// # Examples
658///
659/// ```
660/// use ailloli_ui_widgets::controls::TerminalViewStyle;
661/// let style = TerminalViewStyle::default();
662/// assert_eq!((style.width, style.height, style.line_height), (680.0, 260.0, 19.0));
663/// ```
664pub struct TerminalViewStyle {
665 /// Root terminal surface.
666 pub background: Color,
667 /// Unfocused root border.
668 pub border: Border,
669 /// Border painted in addition while focused.
670 pub focus_ring: Border,
671 /// Normal stdout text style.
672 pub text: TextStyle,
673 /// Prompt and command text style.
674 pub prompt_text: TextStyle,
675 /// Stderr text style.
676 pub stderr_text: TextStyle,
677 /// System/status text style.
678 pub system_text: TextStyle,
679 /// Success text style.
680 pub success_text: TextStyle,
681 /// Warning text style.
682 pub warning_text: TextStyle,
683 /// Selection highlight color.
684 pub selection_background: Color,
685 /// Non-active search-hit color.
686 pub search_background: Color,
687 /// First search-hit color.
688 pub active_search_background: Color,
689 /// Cursor color.
690 pub cursor: Color,
691 /// Scrollbar track color.
692 pub scrollbar_track: Color,
693 /// Scrollbar thumb color.
694 pub scrollbar_thumb: Color,
695 /// Root corner radii.
696 pub radius: Radius,
697 /// Horizontal content inset in logical pixels.
698 pub padding_x: f32,
699 /// Vertical content inset in logical pixels.
700 pub padding_y: f32,
701 /// Default/intrinsic width in logical pixels.
702 pub width: f32,
703 /// Default/intrinsic height in logical pixels.
704 pub height: f32,
705 /// Row advance and vertical scrolling unit in logical pixels.
706 pub line_height: f32,
707 /// Approximate character width used for hit testing and highlights.
708 pub char_width: f32,
709 /// Painted cursor width in logical pixels.
710 pub cursor_width: f32,
711 /// Scrollbar track/thumb width in logical pixels.
712 pub scrollbar_width: f32,
713 /// Scrollbar inset from the right/top/bottom edges in logical pixels.
714 pub scrollbar_inset: f32,
715}
716
717impl Default for TerminalViewStyle {
718 fn default() -> Self {
719 Self::from_theme(Theme::default())
720 }
721}
722
723impl TerminalViewStyle {
724 /// Derives a dark terminal palette from `theme` with fixed geometry defaults.
725 ///
726 /// # Examples
727 ///
728 /// ```
729 /// use ailloli_ui_core::Theme;
730 /// use ailloli_ui_widgets::controls::TerminalViewStyle;
731 /// let style = TerminalViewStyle::from_theme(Theme::default());
732 /// assert_eq!((style.padding_x, style.padding_y, style.char_width), (12.0, 10.0, 7.8));
733 /// ```
734 pub fn from_theme(theme: Theme) -> Self {
735 let palette = theme.palette();
736 let text = TextStyle::new(FontId::Mono, 13, Color::hex_rgb(0xD9E2EC));
737 Self {
738 background: Color::hex_rgb(0x090D12),
739 border: Border::new(1.0, palette.border.with_alpha(0.72)),
740 focus_ring: Border::new(1.0, palette.focus),
741 text,
742 prompt_text: TextStyle::new(FontId::Mono, 13, palette.accent),
743 stderr_text: TextStyle::new(FontId::Mono, 13, palette.danger),
744 system_text: TextStyle::new(FontId::Mono, 13, palette.text_muted),
745 success_text: TextStyle::new(FontId::Mono, 13, palette.success),
746 warning_text: TextStyle::new(FontId::Mono, 13, palette.warning),
747 selection_background: palette.accent.with_alpha(0.24),
748 search_background: palette.warning.with_alpha(0.34),
749 active_search_background: palette.accent.with_alpha(0.40),
750 cursor: Color::hex_rgb(0xD9E2EC),
751 scrollbar_track: Color::rgba(148, 163, 184, 0.16),
752 scrollbar_thumb: Color::rgba(148, 163, 184, 0.58),
753 radius: Radius::uniform(theme.radius().md),
754 padding_x: 12.0,
755 padding_y: 10.0,
756 width: 680.0,
757 height: 260.0,
758 line_height: 19.0,
759 char_width: 7.8,
760 cursor_width: 7.0,
761 scrollbar_width: 6.0,
762 scrollbar_inset: 4.0,
763 }
764 }
765}
766
767/// Scrollable terminal-log widget with static lines and/or streaming events.
768///
769/// This is a log viewer, not a PTY or ANSI parser. It is always keyboard
770/// focusable; selection controls only pointer selection. The default history cap
771/// is 2,000 complete lines and matching is ASCII-case-insensitive. Its overlay
772/// scrollbar supports captured thumb dragging and centered track clicks;
773/// wheel, track, and drag all use the same bounded history offset.
774///
775/// # Examples
776///
777/// ```
778/// use ailloli_ui_widgets::controls::{TerminalLine, TerminalView};
779/// let terminal = TerminalView::new().line(TerminalLine::success("finished"));
780/// let _ = terminal;
781/// ```
782pub struct TerminalView {
783 /// Root layout configuration, initialized from style width/height.
784 pub(crate) layout: LayoutStyle,
785 /// Flex-parent participation metadata.
786 pub(crate) flex_item: FlexItemStyle,
787 /// Initial complete lines.
788 lines: Vec<TerminalLine>,
789 /// Initial buffer mutations applied after complete lines.
790 events: Vec<TerminalEvent>,
791 /// Optional source drained during layout, paint, and input.
792 event_source: Option<Rc<dyn TerminalEventSource>>,
793 /// Maximum retained complete-line count.
794 max_history: usize,
795 /// Static or reactive exact search query.
796 search_query: Binding<String>,
797 /// Whether search matching preserves ASCII case.
798 search_case_sensitive: bool,
799 /// Optional initial selection.
800 selection: Option<TerminalSelection>,
801 /// Appearance and geometry tokens.
802 style: TerminalViewStyle,
803 /// Requested initial nonnegative vertical scroll offset.
804 initial_scroll_y: f32,
805 /// Whether to paint a cursor after a line.
806 show_cursor: bool,
807 /// Explicit cursor line, or `None` for last visible buffer line.
808 cursor_line: Option<usize>,
809 /// Whether pointer dragging can update selection.
810 selectable: bool,
811 /// Whether to reserve and paint a vertical scrollbar.
812 scrollbars: bool,
813}
814
815crate::impl_layout_builders_unit!(TerminalView);
816
817impl Default for TerminalView {
818 fn default() -> Self {
819 Self::new()
820 }
821}
822
823impl TerminalView {
824 /// Creates an empty terminal with default style and interaction settings.
825 ///
826 /// The initial size is `680 x 260` logical pixels, cursor/selection/scrollbar
827 /// behavior is enabled, and vertical scroll starts at zero.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// use ailloli_ui_widgets::controls::TerminalView;
833 /// let terminal = TerminalView::new();
834 /// let _ = terminal;
835 /// ```
836 pub fn new() -> Self {
837 let style = TerminalViewStyle::default();
838 Self {
839 layout: LayoutStyle::default()
840 .width(style.width)
841 .height(style.height),
842 flex_item: FlexItemStyle::default(),
843 lines: Vec::new(),
844 events: Vec::new(),
845 event_source: None,
846 max_history: 2_000,
847 search_query: Binding::Static(String::new()),
848 search_case_sensitive: false,
849 selection: None,
850 style,
851 initial_scroll_y: 0.0,
852 show_cursor: true,
853 cursor_line: None,
854 selectable: true,
855 scrollbars: true,
856 }
857 }
858
859 /// Appends one initial complete line.
860 ///
861 /// # Examples
862 ///
863 /// ```
864 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalView};
865 /// let terminal = TerminalView::new().line(TerminalLine::prompt("$ "));
866 /// let _ = terminal;
867 /// ```
868 pub fn line(mut self, line: TerminalLine) -> Self {
869 self.lines.push(line);
870 self
871 }
872
873 /// Extends initial complete lines in iterator order.
874 ///
875 /// Existing lines are preserved and the history cap is applied during build.
876 ///
877 /// # Examples
878 ///
879 /// ```
880 /// use ailloli_ui_widgets::controls::{TerminalLine, TerminalView};
881 /// let terminal = TerminalView::new().lines([TerminalLine::new("one"), TerminalLine::new("two")]);
882 /// let _ = terminal;
883 /// ```
884 pub fn lines(mut self, lines: impl IntoIterator<Item = TerminalLine>) -> Self {
885 self.lines.extend(lines);
886 self
887 }
888
889 /// Appends one initial event to apply after initial lines.
890 ///
891 /// # Examples
892 ///
893 /// ```
894 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalView};
895 /// let terminal = TerminalView::new().event(TerminalEvent::stdout_chunk(1, "building"));
896 /// let _ = terminal;
897 /// ```
898 pub fn event(mut self, event: TerminalEvent) -> Self {
899 self.events.push(event);
900 self
901 }
902
903 /// Extends initial events in iterator order without sorting by sequence.
904 ///
905 /// # Examples
906 ///
907 /// ```
908 /// use ailloli_ui_widgets::controls::{TerminalEvent, TerminalView};
909 /// let terminal = TerminalView::new().events([TerminalEvent::clear(1), TerminalEvent::status(2, "ready")]);
910 /// let _ = terminal;
911 /// ```
912 pub fn events(mut self, events: impl IntoIterator<Item = TerminalEvent>) -> Self {
913 self.events.extend(events);
914 self
915 }
916
917 /// Installs a pull source, replacing any previous source.
918 ///
919 /// It is synchronously drained during layout, paint, and input; sources should
920 /// therefore return promptly and avoid blocking UI work.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// use std::rc::Rc;
926 /// use ailloli_ui_widgets::controls::{TerminalEventBuffer, TerminalView};
927 /// let terminal = TerminalView::new().event_source(Rc::new(TerminalEventBuffer::new()));
928 /// let _ = terminal;
929 /// ```
930 pub fn event_source(mut self, source: Rc<dyn TerminalEventSource>) -> Self {
931 self.event_source = Some(source);
932 self
933 }
934
935 /// Installs a cloneable shared FIFO event buffer as the source.
936 ///
937 /// Keep a clone before moving the buffer when later producers need to push.
938 ///
939 /// # Examples
940 ///
941 /// ```
942 /// use ailloli_ui_widgets::controls::{TerminalEventBuffer, TerminalView};
943 /// let writer = TerminalEventBuffer::new();
944 /// let terminal = TerminalView::new().event_buffer(writer.clone());
945 /// let _ = terminal;
946 /// ```
947 pub fn event_buffer(self, buffer: TerminalEventBuffer) -> Self {
948 self.event_source(Rc::new(buffer))
949 }
950
951 /// Sets the maximum number of retained complete lines.
952 ///
953 /// Oldest complete lines are removed first. Zero rejects complete appended
954 /// lines; an unfinished nonempty chunk may still be visible as the partial line.
955 ///
956 /// # Examples
957 ///
958 /// ```
959 /// use ailloli_ui_widgets::controls::TerminalView;
960 /// let terminal = TerminalView::new().max_history(500);
961 /// let _ = terminal;
962 /// ```
963 pub fn max_history(mut self, max_history: usize) -> Self {
964 self.max_history = max_history;
965 self
966 }
967
968 /// Sets the static or reactive exact search query.
969 ///
970 /// Empty queries produce no matches; whitespace is not trimmed.
971 ///
972 /// # Examples
973 ///
974 /// ```
975 /// use ailloli_ui_widgets::controls::TerminalView;
976 /// let terminal = TerminalView::new().search_query("error".to_string());
977 /// let _ = terminal;
978 /// ```
979 pub fn search_query(mut self, query: impl Into<Binding<String>>) -> Self {
980 self.search_query = query.into();
981 self
982 }
983
984 /// Selects exact-case or ASCII-case-insensitive matching.
985 ///
986 /// The default is `false` (ASCII-case-insensitive).
987 ///
988 /// # Examples
989 ///
990 /// ```
991 /// use ailloli_ui_widgets::controls::TerminalView;
992 /// let terminal = TerminalView::new().search_case_sensitive(true);
993 /// let _ = terminal;
994 /// ```
995 pub fn search_case_sensitive(mut self, case_sensitive: bool) -> Self {
996 self.search_case_sensitive = case_sensitive;
997 self
998 }
999
1000 /// Sets the initial selection; line bounds are clamped during build/paint.
1001 ///
1002 /// The selection still paints when pointer selection is disabled.
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// use ailloli_ui_widgets::controls::{TerminalSelection, TerminalView};
1008 /// let terminal = TerminalView::new().selection(TerminalSelection::lines(0, 2));
1009 /// let _ = terminal;
1010 /// ```
1011 pub fn selection(mut self, selection: TerminalSelection) -> Self {
1012 self.selection = Some(selection);
1013 self
1014 }
1015
1016 /// Replaces style and resets explicit layout width/height to its defaults.
1017 ///
1018 /// Call width/height builders after this method to override the style sizes.
1019 ///
1020 /// # Examples
1021 ///
1022 /// ```
1023 /// use ailloli_ui_widgets::controls::{TerminalView, TerminalViewStyle};
1024 /// let terminal = TerminalView::new().terminal_style(TerminalViewStyle::default());
1025 /// let _ = terminal;
1026 /// ```
1027 pub fn terminal_style(mut self, style: TerminalViewStyle) -> Self {
1028 self.layout = self.layout.width(style.width).height(style.height);
1029 self.style = style;
1030 self
1031 }
1032
1033 /// Sets requested initial vertical scroll offset in logical pixels.
1034 ///
1035 /// `f32::max` normalizes negative values and NaN to zero; positive infinity
1036 /// is retained until scroll metrics clamp it during layout.
1037 ///
1038 /// # Examples
1039 ///
1040 /// ```
1041 /// use ailloli_ui_widgets::controls::TerminalView;
1042 /// let terminal = TerminalView::new().initial_scroll_y(120.0);
1043 /// let _ = terminal;
1044 /// ```
1045 pub fn initial_scroll_y(mut self, scroll_y: f32) -> Self {
1046 self.initial_scroll_y = scroll_y.max(0.0);
1047 self
1048 }
1049
1050 /// Enables or disables cursor painting; enabled by default.
1051 ///
1052 /// # Examples
1053 ///
1054 /// ```
1055 /// use ailloli_ui_widgets::controls::TerminalView;
1056 /// let terminal = TerminalView::new().show_cursor(false);
1057 /// let _ = terminal;
1058 /// ```
1059 pub fn show_cursor(mut self, show_cursor: bool) -> Self {
1060 self.show_cursor = show_cursor;
1061 self
1062 }
1063
1064 /// Sets the zero-based line after which the cursor is painted.
1065 ///
1066 /// Without this call the last buffer line is used. An out-of-range index
1067 /// paints no cursor.
1068 ///
1069 /// # Examples
1070 ///
1071 /// ```
1072 /// use ailloli_ui_widgets::controls::TerminalView;
1073 /// let terminal = TerminalView::new().cursor_line(3);
1074 /// let _ = terminal;
1075 /// ```
1076 pub fn cursor_line(mut self, cursor_line: usize) -> Self {
1077 self.cursor_line = Some(cursor_line);
1078 self
1079 }
1080
1081 /// Enables or disables pointer-drag selection updates.
1082 ///
1083 /// This does not change focusability, keyboard scrolling, or a supplied
1084 /// initial selection. The default is `true`.
1085 ///
1086 /// # Examples
1087 ///
1088 /// ```
1089 /// use ailloli_ui_widgets::controls::TerminalView;
1090 /// let terminal = TerminalView::new().selectable(false);
1091 /// let _ = terminal;
1092 /// ```
1093 pub fn selectable(mut self, selectable: bool) -> Self {
1094 self.selectable = selectable;
1095 self
1096 }
1097
1098 /// Enables scrollbar reservation, painting, and pointer interaction.
1099 /// This is enabled by default.
1100 ///
1101 /// Scrolling remains available when this is `false`.
1102 ///
1103 /// # Examples
1104 ///
1105 /// ```
1106 /// use ailloli_ui_widgets::controls::TerminalView;
1107 /// let terminal = TerminalView::new().scrollbars(false);
1108 /// let _ = terminal;
1109 /// ```
1110 pub fn scrollbars(mut self, scrollbars: bool) -> Self {
1111 self.scrollbars = scrollbars;
1112 self
1113 }
1114}
1115
1116/// Component-stage terminal configuration copied into the retained widget.
1117struct TerminalViewComponent {
1118 /// Root layout declarations.
1119 layout: LayoutStyle,
1120 /// Initial complete lines.
1121 lines: Vec<TerminalLine>,
1122 /// Initial events applied after lines.
1123 events: Vec<TerminalEvent>,
1124 /// Optional synchronously drained event source.
1125 event_source: Option<Rc<dyn TerminalEventSource>>,
1126 /// Complete-line history cap.
1127 max_history: usize,
1128 /// Static or reactive search query.
1129 search_query: Binding<String>,
1130 /// Search case behavior.
1131 search_case_sensitive: bool,
1132 /// Optional initial selection.
1133 selection: Option<TerminalSelection>,
1134 /// Appearance and geometry tokens.
1135 style: TerminalViewStyle,
1136 /// Requested initial vertical scroll offset.
1137 initial_scroll_y: f32,
1138 /// Whether to paint a cursor.
1139 show_cursor: bool,
1140 /// Optional explicit cursor line.
1141 cursor_line: Option<usize>,
1142 /// Whether pointer dragging changes selection.
1143 selectable: bool,
1144 /// Whether to reserve and paint a scrollbar.
1145 scrollbars: bool,
1146}
1147
1148impl<A: 'static> ComponentNode<A> for TerminalViewComponent {
1149 /// Builds the initial bounded buffer and allocates retained interaction state.
1150 fn build(&self, context: &mut Context<A>) -> View<A> {
1151 let mut buffer = TerminalBufferState::new(self.max_history);
1152 for line in self.lines.iter().cloned() {
1153 buffer.append_line(line);
1154 }
1155 buffer.apply_events(self.events.clone());
1156
1157 let lines_len = buffer.visible_lines().len();
1158 let initial_selection = self.selection.and_then(|s| s.clamp(lines_len));
1159
1160 View::leaf(TerminalViewWidget {
1161 layout: self.layout,
1162 buffer: context.signal(buffer),
1163 scroll: context.signal_with_invalidation(
1164 ScrollState::with_offset(Offset::new(0.0, self.initial_scroll_y)),
1165 Invalidation::Paint,
1166 ),
1167 selection: context.signal(initial_selection),
1168 drag_anchor: context.signal(None),
1169 scrollbar_interaction: context
1170 .signal_with_invalidation(ScrollbarInteraction::default(), Invalidation::Paint),
1171 event_source: self.event_source.clone(),
1172 search_query: self.search_query.clone(),
1173 search_case_sensitive: self.search_case_sensitive,
1174 style: self.style.clone(),
1175 behavior: ScrollBehavior::new(ScrollAxes::VERTICAL)
1176 .with_line_px(self.style.line_height),
1177 show_cursor: self.show_cursor,
1178 cursor_line: self.cursor_line,
1179 selectable: self.selectable,
1180 scrollbars: self.scrollbars,
1181 pending_layout: Cell::new(None),
1182 })
1183 }
1184}
1185
1186impl<A: 'static> IntoView<A> for TerminalView {
1187 /// Builds the retained component and preserves flex/size metadata.
1188 fn into_view(self) -> View<A> {
1189 finish_view_sized(
1190 View::component(TerminalViewComponent {
1191 layout: self.layout,
1192 lines: self.lines,
1193 events: self.events,
1194 event_source: self.event_source,
1195 max_history: self.max_history,
1196 search_query: self.search_query,
1197 search_case_sensitive: self.search_case_sensitive,
1198 selection: self.selection,
1199 style: self.style,
1200 initial_scroll_y: self.initial_scroll_y,
1201 show_cursor: self.show_cursor,
1202 cursor_line: self.cursor_line,
1203 selectable: self.selectable,
1204 scrollbars: self.scrollbars,
1205 }),
1206 self.flex_item,
1207 LayoutSizeHint::from_layout(self.layout),
1208 )
1209 }
1210}
1211
1212#[derive(Clone, Debug, PartialEq)]
1213/// Bounded complete-line history plus one streaming partial line.
1214struct TerminalBufferState {
1215 /// Complete lines in oldest-to-newest order.
1216 lines: Vec<TerminalLine>,
1217 /// Current unterminated stdout/stderr chunk line.
1218 partial: Option<TerminalLine>,
1219 /// Maximum retained complete-line count.
1220 max_history: usize,
1221}
1222
1223impl TerminalBufferState {
1224 /// Creates an empty buffer with an exact complete-line cap.
1225 fn new(max_history: usize) -> Self {
1226 Self {
1227 lines: Vec::new(),
1228 partial: None,
1229 max_history,
1230 }
1231 }
1232
1233 /// Appends a complete line then removes oldest overflow; zero clears state.
1234 fn append_line(&mut self, line: TerminalLine) {
1235 if self.max_history == 0 {
1236 self.lines.clear();
1237 self.partial = None;
1238 return;
1239 }
1240 self.lines.push(line);
1241 self.trim_history();
1242 }
1243
1244 /// Applies mutations in iterator order, ignoring sequence metadata for ordering.
1245 fn apply_events(&mut self, events: impl IntoIterator<Item = TerminalEvent>) {
1246 for event in events {
1247 match event.kind {
1248 TerminalEventKind::AppendLine(mut line) => {
1249 line.timestamp_ms = line.timestamp_ms.or(event.timestamp_ms);
1250 self.flush_partial();
1251 self.append_line(line);
1252 }
1253 TerminalEventKind::StdoutChunk(text) => {
1254 self.append_chunk(text, TerminalLineKind::Stdout, event.timestamp_ms);
1255 }
1256 TerminalEventKind::StderrChunk(text) => {
1257 self.append_chunk(text, TerminalLineKind::Stderr, event.timestamp_ms);
1258 }
1259 TerminalEventKind::Status(text) => {
1260 self.flush_partial();
1261 self.append_line(TerminalLine::system(text));
1262 }
1263 TerminalEventKind::Clear => {
1264 self.lines.clear();
1265 self.partial = None;
1266 }
1267 }
1268 }
1269 }
1270
1271 /// Clones complete lines and appends a nonempty partial line for rendering.
1272 fn visible_lines(&self) -> Vec<TerminalLine> {
1273 let mut lines = self.lines.clone();
1274 if let Some(partial) = self.partial.as_ref() {
1275 if !partial.text.is_empty() {
1276 lines.push(partial.clone());
1277 }
1278 }
1279 lines
1280 }
1281
1282 /// Joins chunk text, discards carriage returns, and completes lines at newlines.
1283 ///
1284 /// A continuing partial adopts the latest chunk kind and the first available
1285 /// timestamp. An empty trailing partial remains internal but is not visible.
1286 fn append_chunk(&mut self, text: String, kind: TerminalLineKind, timestamp_ms: Option<i64>) {
1287 let mut partial = self.partial.take().unwrap_or_else(|| TerminalLine {
1288 text: String::new(),
1289 kind,
1290 attrs: TerminalLineAttrs::default(),
1291 timestamp_ms,
1292 });
1293 partial.kind = kind;
1294 partial.timestamp_ms = partial.timestamp_ms.or(timestamp_ms);
1295
1296 for ch in text.chars() {
1297 match ch {
1298 '\n' => {
1299 let mut finished = partial;
1300 if finished.text.ends_with('\r') {
1301 finished.text.pop();
1302 }
1303 self.append_line(finished);
1304 partial = TerminalLine {
1305 text: String::new(),
1306 kind,
1307 attrs: TerminalLineAttrs::default(),
1308 timestamp_ms,
1309 };
1310 }
1311 '\r' => {}
1312 _ => partial.text.push(ch),
1313 }
1314 }
1315 self.partial = Some(partial);
1316 }
1317
1318 /// Promotes a nonempty partial line into bounded complete history.
1319 fn flush_partial(&mut self) {
1320 if let Some(partial) = self.partial.take() {
1321 if !partial.text.is_empty() {
1322 self.append_line(partial);
1323 }
1324 }
1325 }
1326
1327 /// Removes oldest complete lines until the history cap is met.
1328 fn trim_history(&mut self) {
1329 if self.lines.len() > self.max_history {
1330 let trim = self.lines.len() - self.max_history;
1331 self.lines.drain(0..trim);
1332 }
1333 }
1334}
1335
1336/// Retained terminal widget with reactive buffer, scroll, and selection state.
1337struct TerminalViewWidget {
1338 /// Root layout declarations.
1339 layout: LayoutStyle,
1340 /// Bounded complete/partial line state.
1341 buffer: Signal<TerminalBufferState>,
1342 /// Vertical scroll state.
1343 scroll: Signal<ScrollState>,
1344 /// Current optional selection.
1345 selection: Signal<Option<TerminalSelection>>,
1346 /// Pointer-drag anchor while selecting.
1347 drag_anchor: Signal<Option<TerminalPosition>>,
1348 /// Retained hover and captured scrollbar gesture.
1349 scrollbar_interaction: Signal<ScrollbarInteraction>,
1350 /// Optional synchronously drained event source.
1351 event_source: Option<Rc<dyn TerminalEventSource>>,
1352 /// Static or reactive search query.
1353 search_query: Binding<String>,
1354 /// Search case behavior.
1355 search_case_sensitive: bool,
1356 /// Appearance and geometry tokens.
1357 style: TerminalViewStyle,
1358 /// Vertical wheel and line-scroll policy.
1359 behavior: ScrollBehavior,
1360 /// Whether to paint a cursor.
1361 show_cursor: bool,
1362 /// Optional explicit cursor line.
1363 cursor_line: Option<usize>,
1364 /// Whether pointer dragging updates selection.
1365 selectable: bool,
1366 /// Whether to reserve and paint a scrollbar.
1367 scrollbars: bool,
1368 /// Geometry-derived state owned by one exact authoritative attempt.
1369 pending_layout: Cell<Option<TransactionalLayoutPending<PendingTerminalViewLayout>>>,
1370}
1371
1372/// State published only by the successful attempt that computed it.
1373#[derive(Clone, Copy)]
1374struct PendingTerminalViewLayout {
1375 /// Final authoritative scroll clamp.
1376 scroll: Option<ScrollState>,
1377 /// Geometry-dependent gesture cleanup.
1378 scrollbar_interaction: Option<ScrollbarInteraction>,
1379}
1380
1381impl<A: 'static> Widget<A> for TerminalViewWidget {
1382 /// Returns the stable diagnostic widget name.
1383 fn debug_name(&self) -> &'static str {
1384 "TerminalView"
1385 }
1386
1387 /// Drains events, resolves root size, and clamps vertical scroll.
1388 fn layout(
1389 &self,
1390 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1391 ctx: &mut LayoutCtx<'_>,
1392 _children: &mut [LayoutChild],
1393 constraints: Constraints,
1394 ) -> LayoutResult {
1395 self.drain_source();
1396 let lines = self.buffer.read().visible_lines();
1397 let intrinsic = Size::new(self.style.width, self.style.height);
1398 let size = apply_layout_size(intrinsic, self.layout, constraints);
1399 let scroll = self.clamped_scroll(Size::new(size.w, size.h), lines.len());
1400
1401 let viewport = Rect::new(0.0, 0.0, size.w, size.h);
1402 let geometries = self
1403 .scrollbar_geometry_for_state(viewport, lines.len(), scroll)
1404 .into_iter()
1405 .collect::<Vec<_>>();
1406 // Authoritative geometry can retire a captured gesture. This signal
1407 // already has a context-owned Paint invalidator, and observing its old
1408 // value would make the same layout transaction stale when reconciled.
1409 let mut interaction = with_untracked_reads(|| self.scrollbar_interaction.read());
1410 let interaction_changed = interaction.reconcile(ctx.layout_pass(), &geometries);
1411 if ctx.layout_pass().is_committed() {
1412 let retained_scroll = with_untracked_reads(|| self.scroll.read());
1413 self.pending_layout.set(TransactionalLayoutPending::new(
1414 ctx,
1415 PendingTerminalViewLayout {
1416 scroll: (retained_scroll != scroll).then_some(scroll),
1417 scrollbar_interaction: interaction_changed.then_some(interaction),
1418 },
1419 ));
1420 }
1421 LayoutResult {
1422 size,
1423 children: Vec::new(),
1424 paint_bounds: viewport,
1425 visual_bounds: viewport,
1426 overlay_hit_bounds: geometries
1427 .iter()
1428 .map(|geometry| geometry.hit_track)
1429 .collect(),
1430 clip: Some(ClipShape::Rect(viewport)),
1431 is_window_root_clip: false,
1432 artifact: None,
1433 }
1434 }
1435
1436 /// Publishes only the state derived by the successful authoritative pass.
1437 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
1438 let Some(pending) = self
1439 .pending_layout
1440 .take()
1441 .and_then(|pending| pending.into_committed(ctx))
1442 else {
1443 return;
1444 };
1445 if let Some(scroll) = pending.scroll {
1446 self.scroll.set(scroll);
1447 }
1448 if let Some(interaction) = pending.scrollbar_interaction {
1449 self.scrollbar_interaction.set(interaction);
1450 }
1451 }
1452
1453 /// Paints surface, lines, search/selection/cursor, and optional scrollbar.
1454 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1455 self.drain_source();
1456 let lines = self.buffer.read().visible_lines();
1457 let style = &self.style;
1458
1459 ctx.push(DrawCmd::RRect(DrawRRect {
1460 rect: bounds,
1461 radius: style.radius.tl,
1462 color: style.background,
1463 }));
1464 ctx.push(DrawCmd::Border(DrawBorder {
1465 rect: bounds,
1466 radius: style.radius,
1467 border: style.border,
1468 }));
1469 if ctx.is_focused() {
1470 ctx.push(DrawCmd::Border(DrawBorder {
1471 rect: bounds,
1472 radius: style.radius,
1473 border: style.focus_ring,
1474 }));
1475 }
1476
1477 let content = self.content_rect(bounds);
1478 let scroll = self.scroll.read();
1479 let query = self.search_query.read();
1480 let matches = terminal_search_matches(&lines, &query, self.search_case_sensitive);
1481 let selection = self.selection.read().and_then(|s| s.clamp(lines.len()));
1482
1483 ctx.with_clip(content, |ctx| {
1484 paint_terminal_lines(
1485 ctx,
1486 content,
1487 style,
1488 &lines,
1489 scroll,
1490 &matches,
1491 selection,
1492 self.show_cursor,
1493 self.cursor_line,
1494 );
1495 });
1496
1497 if let Some(geometry) = self.scrollbar_geometry(bounds, lines.len()) {
1498 let visual = self
1499 .scrollbar_interaction
1500 .read()
1501 .visual_state(geometry.axis, ctx.is_hovered());
1502 paint_terminal_scrollbar(ctx, geometry, style, visual);
1503 }
1504 }
1505
1506 /// Handles wheel/keyboard scrolling and optional pointer-drag selection.
1507 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1508 self.drain_source();
1509 let lines = self.buffer.read().visible_lines();
1510 self.clamp_scroll(Size::new(bounds.w, bounds.h), lines.len());
1511
1512 if matches!(event, Event::Pointer(_)) {
1513 let geometries = self
1514 .scrollbar_geometry(bounds, lines.len())
1515 .into_iter()
1516 .collect::<Vec<_>>();
1517 let current = self.scroll.read();
1518 let mut interaction = self.scrollbar_interaction.read();
1519 let response = interaction.handle_event(ctx, event, &geometries);
1520 if response.state_changed {
1521 self.scrollbar_interaction.set(interaction);
1522 }
1523 if let Some((ScrollbarAxis::Vertical, target)) = response.scroll_to {
1524 let content = self.content_rect(bounds);
1525 let metrics = self.scroll_metrics(content, lines.len());
1526 let outcome =
1527 current.scroll_to(Offset::new(0.0, target), metrics, ScrollAxes::VERTICAL);
1528 if outcome.changed {
1529 self.scroll.set(outcome.state());
1530 }
1531 }
1532 if response.repaint {
1533 ctx.request_repaint();
1534 }
1535 if response.consumed {
1536 ctx.stop_propagation();
1537 return;
1538 }
1539 }
1540
1541 match event {
1542 Event::Pointer(PointerEvent::Wheel {
1543 pos,
1544 delta,
1545 modifiers,
1546 ..
1547 }) => {
1548 if !bounds.contains(pos.x, pos.y) {
1549 return;
1550 }
1551 let content = self.content_rect(bounds);
1552 let metrics = self.scroll_metrics(content, lines.len());
1553 let out = self.scroll.read().scroll_by(
1554 self.behavior.wheel_delta_with_modifiers(*delta, *modifiers),
1555 metrics,
1556 ScrollAxes::VERTICAL,
1557 );
1558 if out.changed {
1559 self.scroll.set(out.state());
1560 ctx.request_repaint();
1561 ctx.stop_propagation();
1562 }
1563 }
1564 Event::Pointer(PointerEvent::Button {
1565 pos,
1566 button: MouseButton::Left,
1567 pressed: true,
1568 ..
1569 }) if self.selectable && bounds.contains(pos.x, pos.y) => {
1570 if let Some(anchor) = self.position_at(bounds, pos.x, pos.y, lines.len()) {
1571 self.drag_anchor.set(Some(anchor));
1572 self.selection
1573 .set(Some(TerminalSelection::new(anchor, anchor)));
1574 ctx.request_repaint();
1575 ctx.stop_propagation();
1576 }
1577 }
1578 Event::Pointer(PointerEvent::Moved { pos, .. }) if self.selectable => {
1579 let Some(anchor) = self.drag_anchor.read() else {
1580 return;
1581 };
1582 if let Some(focus) = self.position_at(bounds, pos.x, pos.y, lines.len()) {
1583 self.selection
1584 .set(Some(TerminalSelection::new(anchor, focus)));
1585 ctx.request_repaint();
1586 ctx.stop_propagation();
1587 }
1588 }
1589 Event::Pointer(PointerEvent::Button {
1590 button: MouseButton::Left,
1591 pressed: false,
1592 ..
1593 }) if self.selectable => {
1594 self.drag_anchor.set(None);
1595 }
1596 Event::Keyboard(key) if key.state == KeyState::Pressed => {
1597 let content = self.content_rect(bounds);
1598 let metrics = self.scroll_metrics(content, lines.len());
1599 let delta = match &key.key {
1600 Key::Named(NamedKey::ArrowUp) => Some(-self.style.line_height),
1601 Key::Named(NamedKey::ArrowDown) => Some(self.style.line_height),
1602 Key::Named(NamedKey::PageUp) => Some(-content.h * 0.86),
1603 Key::Named(NamedKey::PageDown) => Some(content.h * 0.86),
1604 Key::Named(NamedKey::Home) => {
1605 let out = self.scroll.read().scroll_to(
1606 Offset::new(0.0, 0.0),
1607 metrics,
1608 ScrollAxes::VERTICAL,
1609 );
1610 if out.changed {
1611 self.scroll.set(out.state());
1612 ctx.request_repaint();
1613 ctx.stop_propagation();
1614 }
1615 None
1616 }
1617 Key::Named(NamedKey::End) => {
1618 let out = self.scroll.read().scroll_to(
1619 metrics.max_offset(),
1620 metrics,
1621 ScrollAxes::VERTICAL,
1622 );
1623 if out.changed {
1624 self.scroll.set(out.state());
1625 ctx.request_repaint();
1626 ctx.stop_propagation();
1627 }
1628 None
1629 }
1630 _ => None,
1631 };
1632 if let Some(dy) = delta {
1633 let out = self.scroll.read().scroll_by(
1634 Offset::new(0.0, dy),
1635 metrics,
1636 ScrollAxes::VERTICAL,
1637 );
1638 if out.changed {
1639 self.scroll.set(out.state());
1640 ctx.request_repaint();
1641 ctx.stop_propagation();
1642 }
1643 }
1644 }
1645 _ => {}
1646 }
1647 }
1648
1649 /// Keeps the terminal keyboard focusable for scrolling in every state.
1650 fn focus_policy(&self) -> FocusPolicy {
1651 FocusPolicy::Focusable
1652 }
1653
1654 /// Exposes a multiline-text accessibility/input role.
1655 fn input_role(&self) -> InputRole {
1656 InputRole::TextMultiLine
1657 }
1658}
1659
1660impl TerminalViewWidget {
1661 /// Drains and applies currently pending source events, if any.
1662 fn drain_source(&self) {
1663 let Some(source) = self.event_source.as_ref() else {
1664 return;
1665 };
1666 let events = source.drain_events();
1667 if events.is_empty() {
1668 return;
1669 }
1670 self.buffer.update(|buffer| buffer.apply_events(events));
1671 }
1672
1673 /// Insets root bounds and reserves scrollbar width when enabled.
1674 fn content_rect(&self, bounds: Rect) -> Rect {
1675 let reserve = if self.scrollbars {
1676 self.style.scrollbar_width + self.style.scrollbar_inset * 2.0
1677 } else {
1678 0.0
1679 };
1680 Rect::new(
1681 bounds.x + self.style.padding_x,
1682 bounds.y + self.style.padding_y,
1683 (bounds.w - self.style.padding_x * 2.0 - reserve).max(0.0),
1684 (bounds.h - self.style.padding_y * 2.0).max(0.0),
1685 )
1686 }
1687
1688 /// Builds vertical metrics from content height and line count.
1689 fn scroll_metrics(&self, content: Rect, line_count: usize) -> ScrollMetrics {
1690 ScrollMetrics::new(
1691 Size::new(content.w, content.h),
1692 Size::new(content.w, line_count as f32 * self.style.line_height),
1693 )
1694 }
1695
1696 /// Resolves shared vertical scrollbar geometry while preserving terminal styling.
1697 fn scrollbar_geometry(&self, bounds: Rect, line_count: usize) -> Option<ScrollbarGeometry> {
1698 self.scrollbar_geometry_for_state(bounds, line_count, self.scroll.read())
1699 }
1700
1701 /// Resolves scrollbar geometry for an explicit transaction-local state.
1702 fn scrollbar_geometry_for_state(
1703 &self,
1704 bounds: Rect,
1705 line_count: usize,
1706 scroll: ScrollState,
1707 ) -> Option<ScrollbarGeometry> {
1708 if !self.scrollbars {
1709 return None;
1710 }
1711 let content = self.content_rect(bounds);
1712 ScrollbarGeometrySpec::new(
1713 ScrollbarAxis::Vertical,
1714 bounds,
1715 self.scroll_metrics(content, line_count),
1716 scroll,
1717 )
1718 .with_paint_metrics(self.style.scrollbar_width, 24.0, self.style.scrollbar_inset)
1719 .with_hit_thickness(16.0)
1720 .resolve()
1721 }
1722
1723 /// Clamps retained vertical offset against the current viewport and content.
1724 fn clamp_scroll(&self, size: Size, line_count: usize) {
1725 let current = with_untracked_reads(|| self.scroll.read());
1726 let next = self.clamped_scroll(size, line_count);
1727 if current != next {
1728 self.scroll.set(next);
1729 }
1730 }
1731
1732 /// Computes the bounded offset without mutating state during layout.
1733 fn clamped_scroll(&self, size: Size, line_count: usize) -> ScrollState {
1734 let content = self.content_rect(Rect::new(0.0, 0.0, size.w, size.h));
1735 let metrics = self.scroll_metrics(content, line_count);
1736 with_untracked_reads(|| self.scroll.read())
1737 .clamp_to(metrics, ScrollAxes::VERTICAL)
1738 .state()
1739 }
1740
1741 /// Converts a point inside content to a clamped line and approximate column.
1742 ///
1743 /// Returns `None` for an empty buffer or point outside content.
1744 fn position_at(
1745 &self,
1746 bounds: Rect,
1747 x: f32,
1748 y: f32,
1749 line_count: usize,
1750 ) -> Option<TerminalPosition> {
1751 if line_count == 0 {
1752 return None;
1753 }
1754 let content = self.content_rect(bounds);
1755 if !content.contains(x, y) {
1756 return None;
1757 }
1758 let scroll_y = self.scroll.read().offset.y;
1759 let line = ((y - content.y + scroll_y) / self.style.line_height)
1760 .floor()
1761 .max(0.0) as usize;
1762 let column = ((x - content.x) / self.style.char_width).floor().max(0.0) as usize;
1763 Some(TerminalPosition::new(line.min(line_count - 1), column))
1764 }
1765}
1766
1767#[allow(clippy::too_many_arguments)]
1768/// Paints the virtualized visible line range and optional cursor.
1769///
1770/// Search and selection highlights are emitted before a line's explicit
1771/// background, so an opaque line background can cover those highlights.
1772fn paint_terminal_lines(
1773 ctx: &mut PaintCtx<'_>,
1774 content: Rect,
1775 style: &TerminalViewStyle,
1776 lines: &[TerminalLine],
1777 scroll: ScrollState,
1778 matches: &[TerminalSearchMatch],
1779 selection: Option<TerminalSelection>,
1780 show_cursor: bool,
1781 cursor_line: Option<usize>,
1782) {
1783 if lines.is_empty() || style.line_height <= 0.0 {
1784 return;
1785 }
1786
1787 let first = (scroll.offset.y / style.line_height).floor().max(0.0) as usize;
1788 let offset_y = scroll.offset.y - first as f32 * style.line_height;
1789 let visible = (content.h / style.line_height).ceil().max(0.0) as usize + 2;
1790 let end = (first + visible).min(lines.len());
1791
1792 for line_idx in first..end {
1793 let row_y = content.y - offset_y + (line_idx - first) as f32 * style.line_height;
1794 let row = Rect::new(content.x, row_y, content.w, style.line_height);
1795 if row.bottom() < content.y || row.y > content.bottom() {
1796 continue;
1797 }
1798
1799 for m in matches.iter().filter(|m| m.line == line_idx) {
1800 let start_col = char_count_until(&lines[line_idx].text, m.start);
1801 let end_col = char_count_until(&lines[line_idx].text, m.end);
1802 let rect = highlight_rect(content, row_y, style, start_col, end_col);
1803 ctx.push(DrawCmd::Rect(DrawRect {
1804 rect,
1805 color: if matches.first() == Some(m) {
1806 style.active_search_background
1807 } else {
1808 style.search_background
1809 },
1810 }));
1811 }
1812
1813 if let Some(selection) = selection.and_then(|s| s.clamp(lines.len())) {
1814 if let Some((start_col, end_col)) = selection_columns_for_line(
1815 selection,
1816 line_idx,
1817 lines[line_idx].text.chars().count(),
1818 ) {
1819 ctx.push(DrawCmd::Rect(DrawRect {
1820 rect: highlight_rect(content, row_y, style, start_col, end_col),
1821 color: style.selection_background,
1822 }));
1823 }
1824 }
1825
1826 if let Some(bg) = lines[line_idx].attrs.background {
1827 ctx.push(DrawCmd::Rect(DrawRect {
1828 rect: row,
1829 color: bg,
1830 }));
1831 }
1832
1833 paint_terminal_text(ctx, content.x, row_y, &lines[line_idx], style);
1834 }
1835
1836 if show_cursor {
1837 let line_idx = cursor_line.unwrap_or_else(|| lines.len().saturating_sub(1));
1838 if line_idx >= first && line_idx < end {
1839 let row_y = content.y - offset_y + (line_idx - first) as f32 * style.line_height;
1840 let col = lines[line_idx].text.chars().count();
1841 ctx.push(DrawCmd::Rect(DrawRect {
1842 rect: Rect::new(
1843 content.x + col as f32 * style.char_width,
1844 row_y + 3.0,
1845 style.cursor_width,
1846 (style.line_height - 6.0).max(1.0),
1847 ),
1848 color: style.cursor.with_alpha(0.72),
1849 }));
1850 }
1851 }
1852}
1853
1854/// Paints one unwrapped line when a text system is available.
1855fn paint_terminal_text(
1856 ctx: &mut PaintCtx<'_>,
1857 x: f32,
1858 row_y: f32,
1859 line: &TerminalLine,
1860 style: &TerminalViewStyle,
1861) {
1862 let Some(text_system) = ctx.text_system.as_deref_mut() else {
1863 return;
1864 };
1865 let text_style = line_text_style(line, style);
1866 let prepared = terminal_layout(text_system, &line.text, text_style);
1867 let baseline = prepared
1868 .lines
1869 .first()
1870 .map(|line| line.baseline_y)
1871 .unwrap_or(style.text.px_size as f32);
1872 ctx.push(DrawCmd::Text(DrawText {
1873 pos: [x, row_y + baseline],
1874 color: text_style.color,
1875 decoration: ailloli_ui_core::TextDecoration::None,
1876 layout: prepared,
1877 }));
1878}
1879
1880/// Obtains a cached unwrapped layout for terminal text.
1881fn terminal_layout(
1882 text_system: &mut TextSystem,
1883 text: &str,
1884 style: TextStyle,
1885) -> Arc<ailloli_ui_text::PreparedTextLayout> {
1886 text_system.layout_cached(TextLayoutParams {
1887 text,
1888 style,
1889 max_width: None,
1890 wrap_mode: WrapMode::NoWrap,
1891 })
1892}
1893
1894/// Resolves kind style, foreground override, and optional dimming.
1895fn line_text_style(line: &TerminalLine, style: &TerminalViewStyle) -> TextStyle {
1896 let mut text = match line.kind {
1897 TerminalLineKind::Prompt | TerminalLineKind::Command => style.prompt_text,
1898 TerminalLineKind::Stdout => style.text,
1899 TerminalLineKind::Stderr => style.stderr_text,
1900 TerminalLineKind::System => style.system_text,
1901 TerminalLineKind::Success => style.success_text,
1902 TerminalLineKind::Warning => style.warning_text,
1903 };
1904 if let Some(foreground) = line.attrs.foreground {
1905 text.color = foreground;
1906 }
1907 if line.attrs.dim {
1908 text.color = text.color.with_alpha(text.color.a * 0.72);
1909 }
1910 text
1911}
1912
1913/// Maps a scalar-column interval to a bounded logical-pixel highlight rectangle.
1914fn highlight_rect(
1915 content: Rect,
1916 row_y: f32,
1917 style: &TerminalViewStyle,
1918 start_col: usize,
1919 end_col: usize,
1920) -> Rect {
1921 let start = start_col.min(end_col);
1922 let end = end_col.max(start + 1);
1923 Rect::new(
1924 content.x + start as f32 * style.char_width,
1925 row_y + 2.0,
1926 ((end - start) as f32 * style.char_width)
1927 .min(content.w)
1928 .max(style.char_width),
1929 (style.line_height - 4.0).max(1.0),
1930 )
1931}
1932
1933/// Intersects a normalized selection with one line's scalar-column range.
1934fn selection_columns_for_line(
1935 selection: TerminalSelection,
1936 line: usize,
1937 line_len: usize,
1938) -> Option<(usize, usize)> {
1939 let (start, end) = selection.normalized();
1940 if line < start.line || line > end.line {
1941 return None;
1942 }
1943 let start_col = if line == start.line { start.column } else { 0 };
1944 let end_col = if line == end.line {
1945 end.column.min(line_len)
1946 } else {
1947 line_len
1948 };
1949 Some((
1950 start_col.min(line_len),
1951 end_col.max(start_col).min(line_len),
1952 ))
1953}
1954
1955/// Counts Unicode scalar values before a byte offset, tolerating invalid boundaries.
1956fn char_count_until(text: &str, byte_idx: usize) -> usize {
1957 text.get(..byte_idx.min(text.len()))
1958 .unwrap_or(text)
1959 .chars()
1960 .count()
1961}
1962
1963/// Finds non-overlapping exact substring matches in line order.
1964///
1965/// Results use UTF-8 byte offsets with inclusive `start` and exclusive `end`.
1966/// Empty queries return no matches. When `case_sensitive` is `false`, both sides
1967/// use ASCII lowercase conversion; the query is not trimmed.
1968///
1969/// # Examples
1970///
1971/// ```
1972/// use ailloli_ui_widgets::controls::{terminal_search_matches, TerminalLine};
1973/// let lines = [TerminalLine::new("Cargo CHECK"), TerminalLine::new("unchecked")];
1974/// let hits = terminal_search_matches(&lines, "check", false);
1975/// assert_eq!(hits.iter().map(|hit| hit.line).collect::<Vec<_>>(), vec![0, 1]);
1976/// assert!(terminal_search_matches(&lines, "Check", true).is_empty());
1977/// ```
1978pub fn terminal_search_matches(
1979 lines: &[TerminalLine],
1980 query: &str,
1981 case_sensitive: bool,
1982) -> Vec<TerminalSearchMatch> {
1983 if query.is_empty() {
1984 return Vec::new();
1985 }
1986 let needle = if case_sensitive {
1987 query.to_string()
1988 } else {
1989 query.to_ascii_lowercase()
1990 };
1991 if needle.is_empty() {
1992 return Vec::new();
1993 }
1994
1995 let mut matches = Vec::new();
1996 for (line_idx, line) in lines.iter().enumerate() {
1997 let haystack = if case_sensitive {
1998 line.text.clone()
1999 } else {
2000 line.text.to_ascii_lowercase()
2001 };
2002 let mut offset = 0usize;
2003 while let Some(found) = haystack[offset..].find(&needle) {
2004 let start = offset + found;
2005 let end = start + needle.len();
2006 matches.push(TerminalSearchMatch {
2007 line: line_idx,
2008 start,
2009 end,
2010 });
2011 offset = end.max(start + 1);
2012 if offset >= haystack.len() {
2013 break;
2014 }
2015 }
2016 }
2017 matches
2018}
2019
2020/// Paints a proportional vertical scrollbar only for overflowing content.
2021///
2022/// The thumb has a 24-pixel preferred minimum capped by track height.
2023fn paint_terminal_scrollbar(
2024 ctx: &mut PaintCtx<'_>,
2025 geometry: ScrollbarGeometry,
2026 style: &TerminalViewStyle,
2027 visual: crate::scrollbar::ScrollbarVisualState,
2028) {
2029 ctx.push(DrawCmd::RRect(DrawRRect {
2030 rect: geometry.track,
2031 radius: style.scrollbar_width * 0.5,
2032 color: style.scrollbar_track,
2033 }));
2034 ctx.push(DrawCmd::RRect(DrawRRect {
2035 rect: geometry.thumb,
2036 radius: style.scrollbar_width * 0.5,
2037 color: thumb_color_for_state(style.scrollbar_thumb, visual),
2038 }));
2039}
2040
2041#[cfg(test)]
2042/// Buffer, chunking, search, and selection regression scenarios.
2043mod tests {
2044 use super::*;
2045 use ailloli_ui_core::event::Modifiers;
2046 use ailloli_ui_core::{Point, Scale};
2047 use ailloli_ui_runtime::app::{Runtime, RuntimeHandle};
2048 use ailloli_ui_runtime::input::InputRouter;
2049 use ailloli_ui_text::TextSystem;
2050
2051 #[test]
2052 fn buffer_trims_history() {
2053 let mut buffer = TerminalBufferState::new(3);
2054 for i in 0..5 {
2055 buffer.append_line(TerminalLine::new(format!("line {i}")));
2056 }
2057 let lines = buffer.visible_lines();
2058 assert_eq!(lines.len(), 3);
2059 assert_eq!(lines[0].text, "line 2");
2060 assert_eq!(lines[2].text, "line 4");
2061 }
2062
2063 #[test]
2064 fn chunk_events_keep_partial_line_visible() {
2065 let mut buffer = TerminalBufferState::new(10);
2066 buffer.apply_events([
2067 TerminalEvent::stdout_chunk(1, "hello"),
2068 TerminalEvent::stdout_chunk(2, " world\nnext"),
2069 ]);
2070 let lines = buffer.visible_lines();
2071 assert_eq!(lines.len(), 2);
2072 assert_eq!(lines[0].text, "hello world");
2073 assert_eq!(lines[1].text, "next");
2074 }
2075
2076 #[test]
2077 fn search_finds_ascii_case_insensitive_matches() {
2078 let lines = vec![
2079 TerminalLine::new("cargo check finished"),
2080 TerminalLine::new("CHECK target cache"),
2081 ];
2082 let matches = terminal_search_matches(&lines, "check", false);
2083 assert_eq!(matches.len(), 2);
2084 assert_eq!(matches[0].line, 0);
2085 assert_eq!(matches[1].line, 1);
2086 }
2087
2088 #[test]
2089 fn selection_normalizes_and_clamps() {
2090 let selection =
2091 TerminalSelection::new(TerminalPosition::new(8, 4), TerminalPosition::new(2, 1));
2092 let clamped = selection.clamp(4).expect("selection");
2093 let (start, end) = clamped.normalized();
2094 assert_eq!(start.line, 2);
2095 assert_eq!(end.line, 3);
2096 }
2097
2098 #[test]
2099 fn terminal_view_scrollbar_drag_moves_scrollback_outside_bounds() {
2100 let lines = (0..24)
2101 .map(|line| TerminalLine::new(format!("line {line:02}")))
2102 .collect::<Vec<_>>();
2103 let style = TerminalViewStyle::default();
2104 let runtime: RuntimeHandle<()> = RuntimeHandle::new();
2105 let mut app = Runtime::new(runtime.clone());
2106 app.reconcile(
2107 TerminalView::new()
2108 .lines(lines)
2109 .terminal_style(style.clone())
2110 .width(220.0)
2111 .height(80.0)
2112 .into_view(),
2113 );
2114 let mut text_system = TextSystem::new();
2115 app.layout(
2116 Constraints::tight(220.0, 80.0),
2117 Scale::new(1.0),
2118 &mut text_system,
2119 );
2120 let initial = app.paint(&mut text_system);
2121 let thumb = initial
2122 .layers
2123 .iter()
2124 .flat_map(|layer| layer.cmds.iter())
2125 .find_map(|cmd| match cmd {
2126 DrawCmd::RRect(rrect)
2127 if rrect.color == style.scrollbar_thumb && rrect.rect.h > rrect.rect.w =>
2128 {
2129 Some(*rrect)
2130 }
2131 _ => None,
2132 })
2133 .expect("terminal view scrollbar thumb");
2134 let press = Point::new(
2135 thumb.rect.x + thumb.rect.w * 0.5,
2136 thumb.rect.y + thumb.rect.h * 0.5,
2137 );
2138 let mut router = InputRouter::default();
2139 router.route_event(
2140 &app.tree,
2141 runtime.clone(),
2142 &Event::Pointer(PointerEvent::Button {
2143 pos: press,
2144 button: MouseButton::Left,
2145 pressed: true,
2146 modifiers: Modifiers::default(),
2147 }),
2148 );
2149 router.route_event(
2150 &app.tree,
2151 runtime.clone(),
2152 &Event::Pointer(PointerEvent::Moved {
2153 pos: Point::new(press.x, 1_000.0),
2154 modifiers: Modifiers::default(),
2155 }),
2156 );
2157 router.route_event(
2158 &app.tree,
2159 runtime,
2160 &Event::Pointer(PointerEvent::Button {
2161 pos: Point::new(press.x, 1_000.0),
2162 button: MouseButton::Left,
2163 pressed: false,
2164 modifiers: Modifiers::default(),
2165 }),
2166 );
2167
2168 let after = app.paint(&mut text_system);
2169 let after_thumb_y = after
2170 .layers
2171 .iter()
2172 .flat_map(|layer| layer.cmds.iter())
2173 .find_map(|cmd| match cmd {
2174 DrawCmd::RRect(rrect)
2175 if rrect.color == style.scrollbar_thumb && rrect.rect.h > rrect.rect.w =>
2176 {
2177 Some(rrect.rect.y)
2178 }
2179 _ => None,
2180 })
2181 .expect("terminal view scrollbar thumb after drag");
2182 assert!(after_thumb_y > thumb.rect.y);
2183 }
2184}