lune-tty 0.1.0

A GPU-accelerated Wayland terminal emulator for Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
use std::io::{self, Read, Write};
use std::ops::Range;
use std::os::fd::{AsFd, BorrowedFd};
use std::process::{Command, ExitStatus};
use std::time::{Duration, Instant};

use lune_pty::{ChildExit, Pty, PtySize};
use lune_terminal::{
    CellPosition, Color, ColorScheme, CursorAppearance, CursorShape, DisplayUnit,
    GRAPHICS_PLACEHOLDER, GraphicsImage, GraphicsImageStore, GraphicsPlacement, HistoryLimits, Key,
    KeyEvent, KeyEventKind, KeySequence, MAX_STYLES, Modifiers, MouseEvent, MouseFormat,
    MouseSequence, MouseTracking, Palette, PaletteEntry, PixelPosition, ProcessFailure, Processor,
    Rgb, Row, RowRevision, Screen, ScreenBuffer, StorageError, Style, StyleError, StyleId,
    StyleRun, StyleTable, TerminalNotifications, TextSink, UnicodeWriter, Viewport,
};

use crate::{GridGeometry, PixelRect};

mod presentation;
mod wait;

pub use presentation::{
    BatchRun, CursorChange, CursorGlyph, CursorPaint, PaintBatch, PaintCommand, PaintError,
    PreparedPresentation, PresentationDamage, PresentationTracker, PresentedCursor, RowDamage,
};
pub use wait::{PtyInterest, SessionInterests, SessionReady, WaitOutcome};

const READ_BYTES: usize = 16 * 1024;
const SYNCHRONIZED_OUTPUT_TIMEOUT: Duration = Duration::from_millis(150);
pub const MAX_INPUT_BYTES: usize = 16 * 1024;
const PASTE_WRITE_BYTES: usize = MAX_INPUT_BYTES;
pub const MAX_PASTE_BYTES: usize = 1024 * 1024;

enum ResizeError {
    Storage(StorageError),
    Transport(io::Error),
}

impl From<StorageError> for ResizeError {
    fn from(error: StorageError) -> Self {
        Self::Storage(error)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MouseInputOutcome {
    Ignored,
    Queued,
    HistoryScrolled,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GraphicsStamp {
    placement_revision: u64,
    pixel_revision: u64,
    viewport_offset: usize,
    history_revision: Option<u64>,
}

#[cfg(feature = "wgpu-renderer")]
impl GraphicsStamp {
    pub(crate) fn same_layout(self, other: Self) -> bool {
        self.placement_revision == other.placement_revision
            && self.viewport_offset == other.viewport_offset
            && self.history_revision == other.history_revision
    }

    pub(crate) fn placement_revision(self) -> u64 {
        self.placement_revision
    }
}

/// Borrowed state for one presentation pass.
pub struct PresentationFrame<'a> {
    pub viewport: Viewport<'a>,
    pub geometry: GridGeometry,
    pub cursor_appearance: CursorAppearance,
    pub reverse_video: bool,
    pub styles: &'a StyleTable,
    pub palette: &'a Palette,
    graphics: &'a [GraphicsPlacement],
    graphics_revision: Option<u64>,
    virtual_graphics: bool,
    virtual_parents: bool,
    buffer: ScreenBuffer,
    processor: &'a Processor,
}

impl<'a> PresentationFrame<'a> {
    pub fn graphics_placements(&self) -> &'a [GraphicsPlacement] {
        self.graphics
    }

    pub fn graphics_image(&self, placement: &'a GraphicsPlacement) -> Option<&'a GraphicsImage> {
        placement
            .anonymous_image()
            .or_else(|| self.image_store().get(placement.placement.image.id()))
    }

    #[cfg(feature = "wgpu-renderer")]
    pub(crate) fn graphics_buffer(&self) -> ScreenBuffer {
        self.buffer
    }

    pub(crate) fn image_store(&self) -> &'a GraphicsImageStore {
        self.processor.graphics_images(self.buffer)
    }

    #[cfg(feature = "wgpu-renderer")]
    pub(crate) fn inactive_image_store(&self) -> &'a GraphicsImageStore {
        let inactive = match self.buffer {
            ScreenBuffer::Primary => ScreenBuffer::Alternate,
            ScreenBuffer::Alternate => ScreenBuffer::Primary,
        };
        self.processor.graphics_images(inactive)
    }

    pub(crate) fn graphics_stamp(&self) -> Option<GraphicsStamp> {
        self.graphics_revision
            .map(|placement_revision| GraphicsStamp {
                placement_revision,
                pixel_revision: self.image_store().visual_revision(),
                viewport_offset: self.viewport.offset(),
                history_revision: self
                    .virtual_parents
                    .then(|| self.viewport.source().history_revision())
                    .flatten(),
            })
    }

    #[cfg(feature = "wgpu-renderer")]
    pub(crate) fn has_virtual_graphics(&self) -> bool {
        self.virtual_graphics
    }

    #[cfg(feature = "wgpu-renderer")]
    pub(crate) fn has_virtual_parents(&self) -> bool {
        self.virtual_parents
    }

    pub(crate) fn graphics_placeholder_revisions(
        &self,
    ) -> impl Iterator<Item = Option<RowRevision>> + '_ {
        self.viewport
            .rows_for_graphics(self.virtual_parents)
            .take(if self.virtual_graphics { usize::MAX } else { 0 })
            .map(Row::graphics_placeholder_revision)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PresentationStyle<'a> {
    pub foreground: Rgb,
    pub background: Rgb,
    pub underline_color: Rgb,
    /// Rendition attributes used for glyphs, decorations, and visibility.
    pub style: &'a Style,
}

pub struct PresentationRun<'a> {
    row: &'a Row,
    columns: Range<usize>,
    pub style: PresentationStyle<'a>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BackgroundRect {
    pub rect: PixelRect,
    pub color: Rgb,
}

impl<'a> PresentationRun<'a> {
    #[inline]
    pub fn columns(&self) -> Range<usize> {
        self.columns.clone()
    }

    /// Complete units intersecting the span. Clip painting to its columns.
    #[inline]
    pub fn units(&self) -> impl Iterator<Item = DisplayUnit<'a>> + use<'a> {
        self.row
            .display_units(self.columns())
            .filter(|unit| unit.cell.character() != Some(GRAPHICS_PLACEHOLDER))
    }
}

impl<'a> PresentationFrame<'a> {
    /// Resolves a row's style spans inside the requested visible columns.
    /// Uncovered columns of a short history row use the default style.
    #[inline]
    pub fn row_runs(
        &self,
        row: usize,
        columns: Range<usize>,
    ) -> Option<impl Iterator<Item = Result<PresentationRun<'a>, StyleError>> + '_> {
        let row = self.viewport.row(row)?;
        let (columns, mut padding) = self.row_columns(row, columns);
        let mut runs = row.style_runs(columns);
        Some(std::iter::from_fn(move || {
            let run = runs.next().or_else(|| padding.take())?;
            let style = self
                .resolve_style(run.style)
                .ok_or(StyleError::InvalidId(run.style));
            Some(style.map(|style| PresentationRun {
                row,
                columns: run.columns,
                style,
            }))
        }))
    }

    /// Returns solid background rectangles in physical pixels, merging adjacent
    /// spans of the same resolved color. The row must have known pixel metrics.
    #[inline]
    pub fn row_backgrounds(
        &self,
        row: usize,
        columns: Range<usize>,
    ) -> Option<impl Iterator<Item = Result<BackgroundRect, StyleError>> + '_> {
        self.geometry.cell_pixels()?;
        if row >= usize::from(self.geometry.pty_size().rows) {
            return None;
        }
        let source = self.viewport.row(row)?;
        let (columns, mut padding) = self.row_columns(source, columns);
        let mut spans = source.style_runs(columns);
        let mut runs = std::iter::from_fn(move || {
            let run = spans.next().or_else(|| padding.take())?;
            let style = self.styles.get(run.style).ok_or(run.style);
            Some(style.map(|style| {
                let color = if style.inverse {
                    style.foreground
                } else {
                    style.background
                };
                let role = if self.reverse_video ^ style.inverse {
                    PaletteEntry::Foreground
                } else {
                    PaletteEntry::Background
                };
                (run.columns, self.palette.resolve(color, role))
            }))
        });
        let mut pending = None;
        Some(std::iter::from_fn(move || {
            let (mut columns, color) = match pending.take().or_else(|| runs.next())? {
                Ok(span) => span,
                Err(id) => return Some(Err(StyleError::InvalidId(id))),
            };
            for next in runs.by_ref() {
                match next {
                    Ok((next_columns, next_color)) if next_color == color => {
                        columns.end = next_columns.end;
                    }
                    _ => {
                        pending = Some(next);
                        break;
                    }
                }
            }
            let rect = self.geometry.row_rect(row, columns)?;
            Some(Ok(BackgroundRect { rect, color }))
        }))
    }

    #[inline]
    fn row_columns(&self, row: &Row, columns: Range<usize>) -> (Range<usize>, Option<StyleRun>) {
        let end = columns.end.min(self.geometry.pty_size().columns.into());
        let start = columns.start.min(end);
        let padding = start.max(row.cells().len());
        let padding = (padding < end).then_some(StyleRun {
            columns: padding..end,
            style: StyleId::default(),
        });
        (start..end, padding)
    }

    /// Resolves colors against this frame. Screen inversion swaps the default
    /// roles before cell inversion exchanges the resolved foreground and background.
    #[inline]
    pub fn resolve_style(&self, id: StyleId) -> Option<PresentationStyle<'a>> {
        let style = self.styles.get(id)?;
        let (fg_role, bg_role) = if self.reverse_video {
            (PaletteEntry::Background, PaletteEntry::Foreground)
        } else {
            (PaletteEntry::Foreground, PaletteEntry::Background)
        };
        let fg = self.palette.resolve(style.foreground, fg_role);
        let bg = self.palette.resolve(style.background, bg_role);
        let (foreground, background) = if style.inverse { (bg, fg) } else { (fg, bg) };
        let underline_color = match style.underline_color {
            Color::Default => foreground,
            color => self.palette.resolve(color, PaletteEntry::Foreground),
        };
        Some(PresentationStyle {
            foreground,
            background,
            underline_color,
            style,
        })
    }
}

/// Drives terminal state and child I/O from a nonblocking PTY.
pub struct Session<T = Pty> {
    transport: T,
    child_exit: Option<ChildExit>,
    geometry: GridGeometry,
    screen: Screen,
    processor: Processor,
    writer: UnicodeWriter,
    incoming: [u8; READ_BYTES],
    incoming_bytes: Option<Range<usize>>,
    outgoing: [u8; MAX_INPUT_BYTES],
    outgoing_bytes: Range<usize>,
    large_paste: Option<Vec<u8>>,
    write_closed: bool,
    read_closed: bool,
    finished: bool,
    presentation_deadline: Option<Instant>,
}

impl Session<Pty> {
    /// Starts a session with a child exit monitor on Linux 5.3 or later.
    pub fn spawn(command: Command, size: PtySize, palette: Palette) -> io::Result<Self> {
        let screen = Screen::new(usize::from(size.columns), usize::from(size.rows))
            .map_err(io::Error::other)?;
        let processor = Processor::new(MAX_STYLES, palette).map_err(io::Error::other)?;

        let mut transport = Pty::spawn(command, size)?;
        transport.set_nonblocking(true)?;
        let child_exit = transport.monitor_child()?;
        let mut session = Self::new(transport, size, screen, processor);
        session.child_exit = Some(child_exit);
        Ok(session)
    }

    /// Commits a PTY resize and reflows its screen before publishing VT geometry.
    /// A pending input chunk returns `WouldBlock`; pump it before retrying.
    pub fn resize(&mut self, size: PtySize) -> io::Result<()> {
        if self.write_closed {
            return Err(io::ErrorKind::BrokenPipe.into());
        }
        let previous = self.geometry.pty_size();
        if size == previous {
            return Ok(());
        }
        if self.incoming_bytes.is_some() {
            return Err(io::ErrorKind::WouldBlock.into());
        }

        let grid_changed = size.columns != previous.columns || size.rows != previous.rows;
        self.screen
            .reflow_with(
                usize::from(size.columns),
                usize::from(size.rows),
                StyleId::default(),
                || {
                    self.transport
                        .resize(size)
                        .map_err(ResizeError::Transport)?;
                    if grid_changed {
                        self.writer.boundary();
                    }
                    Ok(())
                },
            )
            .map_err(|error| match error {
                ResizeError::Storage(error) => io::Error::other(error),
                ResizeError::Transport(error) => error,
            })?;
        self.geometry = GridGeometry::from_pty_size(size);
        self.processor.update_geometry(
            &mut self.screen,
            self.geometry.text_area_pixels(),
            self.geometry.cell_pixels(),
        );
        self.poll_graphics_animations(Instant::now);
        Ok(())
    }

    /// Polls child status independently of whether PTY output has reached EOF.
    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
        self.transport.try_wait()
    }

    /// Returns the direct child process ID of this PTY session.
    pub fn child_id(&self) -> u32 {
        self.transport.child_id()
    }

    /// Returns the foreground process group ID attached to the PTY, if any.
    pub fn foreground_process_group(&self) -> Option<u32> {
        self.transport.foreground_process_group()
    }
}

impl<T: AsFd> AsFd for Session<T> {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.transport.as_fd()
    }
}

impl<T: Read + Write> Session<T> {
    fn new(transport: T, size: PtySize, mut screen: Screen, mut processor: Processor) -> Self {
        let geometry = GridGeometry::from_pty_size(size);
        processor.update_geometry(
            &mut screen,
            geometry.text_area_pixels(),
            geometry.cell_pixels(),
        );
        Self {
            transport,
            child_exit: None,
            geometry,
            screen,
            processor,
            writer: UnicodeWriter::default(),
            incoming: [0; READ_BYTES],
            incoming_bytes: None,
            outgoing: [0; MAX_INPUT_BYTES],
            outgoing_bytes: 0..0,
            large_paste: None,
            write_closed: false,
            read_closed: false,
            finished: false,
            presentation_deadline: None,
        }
    }

    pub fn screen(&self) -> &Screen {
        &self.screen
    }

    pub fn toggle_prompt_bookmark(&mut self, chronological_row: usize) -> Option<bool> {
        self.screen.toggle_prompt_bookmark(chronological_row)
    }

    pub fn geometry(&self) -> GridGeometry {
        self.geometry
    }

    /// The live screen when it is ready for presentation.
    pub fn presentation_screen(&self) -> Option<&Screen> {
        self.presentation_deadline.is_none().then_some(&self.screen)
    }

    /// Borrows the visible viewport and its rendition state when presentation is ready.
    pub fn presentation_frame(&self) -> Option<PresentationFrame<'_>> {
        let screen = self.presentation_screen()?;
        Some(PresentationFrame {
            viewport: screen.viewport(),
            geometry: self.geometry,
            cursor_appearance: screen.cursor_appearance(),
            reverse_video: screen.reverse_video(),
            styles: self.processor.styles(),
            palette: self.processor.palette(),
            graphics: screen.graphics_placements(),
            graphics_revision: screen.graphics_revision(),
            virtual_graphics: screen.has_virtual_graphics(),
            virtual_parents: screen.has_virtual_graphics_parents(),
            buffer: screen.active_buffer(),
            processor: &self.processor,
        })
    }

    /// When to pump again for presentation work, even if the PTY is idle.
    pub fn presentation_deadline(&self) -> Option<Instant> {
        if self.finished {
            return None;
        }
        self.presentation_deadline.or_else(|| {
            self.processor
                .graphics_images(self.screen.active_buffer())
                .animation_deadline()
        })
    }

    pub fn processor(&self) -> &Processor {
        &self.processor
    }

    pub fn graphics_image(&self, id: u32) -> Option<&GraphicsImage> {
        self.processor
            .graphics_images(self.screen.active_buffer())
            .get(id)
    }

    pub fn take_notifications(&mut self) -> TerminalNotifications<'_> {
        self.processor.take_notifications()
    }

    pub fn set_theme(&mut self, palette: &Palette, scheme: Option<ColorScheme>) {
        self.processor.set_theme(palette, scheme);
    }

    pub fn set_default_cursor_appearance(&mut self, shape: CursorShape, blinking: bool) {
        self.processor
            .set_default_cursor_appearance(&mut self.screen, shape, blinking);
    }

    /// Updates primary scrollback limits and clamps the visible history.
    pub fn set_history_limits(&mut self, limits: HistoryLimits) -> Result<(), StorageError> {
        self.processor
            .set_history_limits(&mut self.screen, limits)?;
        self.poll_graphics_animations(Instant::now);
        Ok(())
    }

    /// Moves the local viewport. Positive steps go toward older rows.
    pub fn scroll_history(&mut self, steps: isize) -> bool {
        let offset = self.screen.viewport_offset();
        if steps > 0 {
            self.screen.scroll_viewport_up(steps as usize);
        } else {
            self.screen.scroll_viewport_down(steps.unsigned_abs());
        }
        let moved = self.screen.viewport_offset() != offset;
        if moved {
            self.poll_graphics_animations(Instant::now);
        }
        moved
    }

    /// Returns the primary viewport to the live buffer.
    pub fn follow_output(&mut self) {
        if self.screen.viewport_offset() != 0 {
            self.screen.scroll_viewport_to_bottom();
            self.poll_graphics_animations(Instant::now);
        }
    }

    /// Reclaims unreachable styles while preserving IDs held by the caller.
    pub fn collect_styles(
        &mut self,
        retained: impl IntoIterator<Item = StyleId>,
    ) -> Result<usize, StyleError> {
        self.processor.collect_styles(&self.screen, retained)
    }

    pub fn wants_read(&self) -> bool {
        !self.read_closed && self.incoming_bytes.is_none()
    }

    pub fn wants_write(&self) -> bool {
        !self.write_closed
            && (!self.outgoing_bytes.is_empty() || !self.processor.reply_bytes().is_empty())
    }

    /// Returns whether PTY output reached EOF and VT finalization succeeded.
    pub fn is_finished(&self) -> bool {
        self.finished
    }

    /// Accepts a complete input frame when earlier input and replies have drained.
    pub fn queue_input(&mut self, bytes: &[u8]) -> io::Result<()> {
        if bytes.len() > MAX_INPUT_BYTES {
            return Err(io::ErrorKind::InvalidInput.into());
        }
        self.check_input_ready()?;
        self.stage_input(bytes);
        Ok(())
    }

    /// Queues a key using current VT modes. Returns false for a suppressed event.
    pub fn queue_key(&mut self, key: Key, modifiers: Modifiers, repeat: bool) -> io::Result<bool> {
        self.queue_key_sequence(
            self.processor.input_modes().encode_key(key, modifiers),
            repeat,
        )
    }

    /// Queues a layout-resolved character with its Control and Alt modifiers.
    pub fn queue_character(
        &mut self,
        character: char,
        modifiers: Modifiers,
        repeat: bool,
    ) -> io::Result<bool> {
        self.queue_key_sequence(KeySequence::from_character(character, modifiers), repeat)
    }

    /// Queues a rich keyboard event using active Kitty keyboard protocol or legacy encoding.
    pub fn queue_key_event(&mut self, event: KeyEvent<'_>) -> io::Result<bool> {
        self.queue_key_sequence(
            self.processor.input_modes().encode_key_event(event),
            event.kind == KeyEventKind::Repeat,
        )
    }

    fn queue_key_sequence(
        &mut self,
        sequence: Option<KeySequence>,
        repeat: bool,
    ) -> io::Result<bool> {
        let Some(sequence) = sequence else {
            return Ok(false);
        };
        if repeat && !self.processor.auto_repeat_enabled() {
            return Ok(false);
        }
        self.queue_input(sequence.as_bytes())?;
        Ok(true)
    }

    /// Queues a focus transition when focus reporting is enabled.
    pub fn queue_focus(&mut self, focused: bool) -> io::Result<bool> {
        self.check_input_ready()?;
        Ok(self.stage_report(self.processor.input_modes().encode_focus(focused)))
    }

    /// Routes a pointer event to the primary viewport or the PTY.
    /// A historical viewport handles vertical wheel steps locally.
    /// Pixel reports require a position inside the committed content size.
    pub fn mouse_input(
        &mut self,
        event: MouseEvent,
        cell: CellPosition,
        pixel: Option<PixelPosition>,
        modifiers: Modifiers,
    ) -> io::Result<MouseInputOutcome> {
        let size = self.geometry.pty_size();
        if cell.row >= usize::from(size.rows) || cell.column >= usize::from(size.columns) {
            return Ok(MouseInputOutcome::Ignored);
        }
        let modes = self.processor.input_modes();
        let buffer = self.screen.active_buffer();
        if buffer == ScreenBuffer::Primary
            && (modes.mouse_tracking == MouseTracking::Disabled
                || self.write_closed
                || self.screen.viewport_offset() != 0)
        {
            let steps = match event {
                MouseEvent::WheelUp => 1,
                MouseEvent::WheelDown => -1,
                _ => return Ok(MouseInputOutcome::Ignored),
            };
            return Ok(if self.scroll_history(steps) {
                MouseInputOutcome::HistoryScrolled
            } else {
                MouseInputOutcome::Ignored
            });
        }

        self.check_input_ready()?;
        if modes.mouse_tracking == MouseTracking::Disabled {
            let key = modes.encode_alternate_scroll(event, buffer);
            return Ok(self.stage_mouse_report(key.as_ref().map(KeySequence::as_bytes)));
        }
        let report = if modes.mouse_format == MouseFormat::SgrPixels {
            let Some(pixel) = pixel.filter(|&position| self.geometry.contains(position)) else {
                return Ok(MouseInputOutcome::Ignored);
            };
            modes.encode_pixel_mouse(event, pixel, modifiers)
        } else {
            modes.encode_mouse(event, cell, modifiers)
        };
        Ok(self.stage_mouse_report(report.as_ref().map(MouseSequence::as_bytes)))
    }

    /// Routes a pixel hit in the committed grid through the current mouse mode.
    pub fn mouse_input_at(
        &mut self,
        event: MouseEvent,
        pixel: PixelPosition,
        modifiers: Modifiers,
    ) -> io::Result<MouseInputOutcome> {
        let Some(cell) = self.geometry.cell_at(pixel) else {
            return Ok(MouseInputOutcome::Ignored);
        };
        self.mouse_input(event, cell, Some(pixel), modifiers)
    }

    fn stage_mouse_report(&mut self, report: Option<&[u8]>) -> MouseInputOutcome {
        if self.stage_report(report) {
            MouseInputOutcome::Queued
        } else {
            MouseInputOutcome::Ignored
        }
    }

    fn stage_report(&mut self, report: Option<&[u8]>) -> bool {
        if let Some(bytes) = report {
            self.stage_input(bytes);
            true
        } else {
            false
        }
    }

    fn stage_input(&mut self, bytes: &[u8]) {
        self.outgoing[..bytes.len()].copy_from_slice(bytes);
        self.outgoing_bytes = 0..bytes.len();
    }

    /// Queues up to `MAX_PASTE_BYTES` of text with the current framing.
    /// The entire paste precedes later replies.
    pub fn queue_paste(&mut self, payload: &str) -> io::Result<()> {
        if payload.len() > MAX_PASTE_BYTES {
            return Err(io::ErrorKind::InvalidInput.into());
        }
        self.check_input_ready()?;

        let mut paste = self.processor.input_modes().encode_paste(payload);
        let len = paste.remaining_bytes();
        let mut large_paste = if len > self.outgoing.len() {
            let mut bytes = Vec::new();
            bytes.try_reserve_exact(len).map_err(io::Error::other)?;
            Some(bytes)
        } else {
            None
        };
        let mut offset = 0;
        while !paste.is_empty() {
            let bytes = paste.bytes();
            let end = offset + bytes.len();
            if let Some(buffer) = &mut large_paste {
                buffer.extend_from_slice(bytes);
            } else {
                self.outgoing[offset..end].copy_from_slice(bytes);
            }
            let consumed = paste.consume(bytes.len());
            debug_assert!(consumed);
            offset = end;
        }
        debug_assert_eq!(offset, len);
        self.large_paste = large_paste;
        self.outgoing_bytes = 0..len;
        Ok(())
    }

    fn check_input_ready(&self) -> io::Result<()> {
        if self.write_closed {
            return Err(io::ErrorKind::BrokenPipe.into());
        }
        if self.wants_write() || self.incoming_bytes.is_some() {
            return Err(io::ErrorKind::WouldBlock.into());
        }
        Ok(())
    }

    /// Writes at most 16 KiB of paste data and reads at most one chunk.
    /// Use level-triggered notifications and also pump on hangup.
    pub fn pump(&mut self) -> io::Result<()> {
        self.pump_with_clock(Instant::now)
    }

    fn pump_with_clock(&mut self, now: impl Fn() -> Instant) -> io::Result<()> {
        if self.finished {
            return Ok(());
        }
        if self
            .presentation_deadline
            .is_some_and(|deadline| now() >= deadline)
        {
            self.processor.end_synchronized_output();
            self.presentation_deadline = None;
            self.poll_graphics_animations(&now);
            return Ok(());
        }

        let result = self.pump_pty();
        if self.processor.synchronized_output() {
            self.presentation_deadline
                .get_or_insert_with(|| now() + SYNCHRONIZED_OUTPUT_TIMEOUT);
        } else {
            self.presentation_deadline = None;
        }
        self.poll_graphics_animations(now);
        result
    }

    fn poll_graphics_animations(&mut self, clock: impl FnOnce() -> Instant) {
        if !self.finished && self.presentation_deadline.is_none() {
            self.processor.poll_graphics_animations(&self.screen, clock);
        }
    }

    fn pump_pty(&mut self) -> io::Result<()> {
        let mut writable = self.flush_output()?;
        self.apply_input(&mut writable)?;
        if self.incoming_bytes.is_some() {
            return Ok(());
        }

        if !self.read_closed {
            loop {
                match self.transport.read(&mut self.incoming) {
                    Ok(0) => break,
                    Ok(count) => {
                        self.incoming_bytes = Some(0..count);
                        return self.apply_input(&mut writable);
                    }
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Ok(()),
                    Err(error) => return Err(error),
                }
            }
            self.read_closed = true;
            self.write_closed = true;
            self.processor.end_synchronized_output();
            self.flush_output()?;
        }

        self.processor
            .finish(&mut self.screen, &mut self.writer)
            .map_err(io::Error::other)?;
        self.finished = true;
        Ok(())
    }

    fn apply_input(&mut self, writable: &mut bool) -> io::Result<()> {
        while let Some(bytes) = &mut self.incoming_bytes {
            match self.processor.advance(
                &self.incoming[bytes.clone()],
                &mut self.screen,
                &mut self.writer,
            ) {
                Ok(_) => self.incoming_bytes = None,
                Err(error) => {
                    // An empty suffix can still have a pending processor event.
                    bytes.start += error.consumed;
                    match error.error {
                        ProcessFailure::ReplyPending => {}
                        ProcessFailure::Style(StyleError::CapacityExceeded) => {
                            if self
                                .processor
                                .collect_styles(&self.screen, [])
                                .map_err(io::Error::other)?
                                == 0
                            {
                                return Err(io::Error::other(StyleError::CapacityExceeded));
                            }
                            continue;
                        }
                        other => return Err(io::Error::other(other)),
                    }
                }
            }
            if !*writable {
                break;
            }
            *writable = self.flush_output()?;
        }
        Ok(())
    }

    fn flush_output(&mut self) -> io::Result<bool> {
        let mut paste_budget = PASTE_WRITE_BYTES;
        loop {
            // Keep each host frame contiguous on the wire, including paste markers.
            let host_input = !self.outgoing_bytes.is_empty();
            let bytes = if host_input {
                let range = self.outgoing_bytes.clone();
                if let Some(paste) = &self.large_paste {
                    let end = if self.write_closed {
                        range.end
                    } else {
                        range.end.min(range.start + paste_budget)
                    };
                    &paste[range.start..end]
                } else {
                    &self.outgoing[range]
                }
            } else {
                self.processor.reply_bytes()
            };
            if bytes.is_empty() {
                return Ok(true);
            }
            let count = if self.write_closed {
                bytes.len()
            } else {
                match self.transport.write(bytes) {
                    Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
                    Ok(count) => count,
                    Err(error) => match error.kind() {
                        io::ErrorKind::Interrupted => continue,
                        io::ErrorKind::WouldBlock => return Ok(false),
                        io::ErrorKind::BrokenPipe => {
                            self.write_closed = true;
                            bytes.len()
                        }
                        _ => return Err(error),
                    },
                }
            };

            if host_input {
                self.outgoing_bytes.start += count;
                if self.outgoing_bytes.is_empty() {
                    self.large_paste = None;
                } else if self.large_paste.is_some() && !self.write_closed {
                    paste_budget -= count;
                    if paste_budget == 0 {
                        return Ok(false);
                    }
                }
            } else {
                let consumed = self.processor.consume_reply(count);
                debug_assert!(consumed);
            }
        }
    }
}

#[cfg(test)]
mod tests;