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
use std::collections::TryReserveError;
use std::num::NonZeroU32;
use std::time::{Duration, Instant};

use lune_terminal::{
    CellPosition, CellText, CursorAppearance, CursorShape, DisplayUnit, GraphicsImageFormat,
    Palette, PaletteEntry, Rgb, Row, RowRevision, Style, StyleError,
};

use crate::{GridGeometry, PixelRect};

use super::{BackgroundRect, PresentationFrame, PresentationRun};

mod batch;

pub use batch::{BatchRun, PaintBatch};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RowDamage<'a> {
    All,
    /// Changed viewport row indices in ascending order.
    Rows(&'a [usize]),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PresentedCursor {
    pub position: CellPosition,
    pub appearance: CursorAppearance,
    pub color: Rgb,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CursorPaint<'a> {
    pub rect: PixelRect,
    pub color: Rgb,
    pub glyph: Option<CursorGlyph<'a>>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CursorGlyph<'a> {
    pub unit: DisplayUnit<'a>,
    pub color: Rgb,
    pub style: &'a Style,
}

impl<'a> PresentationFrame<'a> {
    /// Resolves a displayed cursor against this frame. Draw its glyph at the
    /// block origin and clip it to the rectangle.
    pub fn cursor_paint(
        &self,
        cursor: PresentedCursor,
        thickness: NonZeroU32,
    ) -> Result<Option<CursorPaint<'a>>, StyleError> {
        let Some(cell) = self.geometry.cell_pixels() else {
            return Ok(None);
        };
        let CellPosition { row, column } = cursor.position;
        if !cursor.appearance.visible || column >= usize::from(self.geometry.pty_size().columns) {
            return Ok(None);
        }
        let Some(source) = self.viewport.row(row) else {
            return Ok(None);
        };
        let cells = source.cells();
        let Some(covered) = cells.get(column) else {
            return Ok(None);
        };
        let leading = column - usize::from(covered.is_continuation());
        let covered = cells[leading];
        let Some(mut rect) = self
            .geometry
            .row_rect(row, leading..leading + covered.width())
        else {
            return Ok(None);
        };

        let mut glyph = None;
        match cursor.appearance.shape {
            CursorShape::Block
                if !covered.is_erased()
                    && covered.character() != Some(lune_terminal::GRAPHICS_PLACEHOLDER) =>
            {
                let id = covered.style();
                let style = self.resolve_style(id).ok_or(StyleError::InvalidId(id))?;
                if !style.style.hidden {
                    let color = cursor_text_color(style.background, style.foreground, cursor.color);
                    let text = if covered.has_extended_text() {
                        source
                            .text(leading)
                            .expect("The leading column is in the row")
                    } else {
                        CellText::Scalar(covered.character().expect("A leading cell has a scalar"))
                    };
                    glyph = Some(CursorGlyph {
                        unit: DisplayUnit {
                            column: leading,
                            cell: covered,
                            text,
                        },
                        color,
                        style: style.style,
                    });
                }
            }
            CursorShape::Block => {}
            CursorShape::Bar => rect.size.width = thickness.min(cell.width),
            CursorShape::Underline => {
                let height = thickness.min(cell.height);
                rect.origin.y += cell.height.get() - height.get();
                rect.size.height = height;
            }
        }
        Ok(Some(CursorPaint {
            rect,
            color: cursor.color,
            glyph,
        }))
    }
}

fn cursor_text_color(background: Rgb, foreground: Rgb, cursor: Rgb) -> Rgb {
    if background != cursor {
        background
    } else if foreground != cursor {
        foreground
    } else {
        let brightness = 54 * u32::from(cursor.red)
            + 183 * u32::from(cursor.green)
            + 19 * u32::from(cursor.blue);
        let channel = if brightness >= 128 * 256 { 0 } else { 255 };
        Rgb {
            red: channel,
            green: channel,
            blue: channel,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CursorChange {
    pub before: Option<PresentedCursor>,
    pub after: Option<PresentedCursor>,
}

impl CursorChange {
    fn between(before: Option<PresentedCursor>, after: Option<PresentedCursor>) -> Option<Self> {
        (before != after).then_some(Self { before, after })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PresentationDamage<'a> {
    pub rows: RowDamage<'a>,
    pub graphics_changed: bool,
    /// Overlay changes. Repaint an unchanged cursor when repainting its row.
    pub cursor: Option<CursorChange>,
    pub displayed_cursor: Option<PresentedCursor>,
}

pub enum PaintCommand<'a, Run> {
    Background(BackgroundRect),
    Text {
        clip: PixelRect,
        run: Run,
    },
    /// Replaces the cursor layer. An empty value clears it.
    Cursor(Option<CursorPaint<'a>>),
}

#[derive(Debug)]
pub enum PaintError<E> {
    GeometryUnavailable,
    InvalidRow(usize),
    Style(StyleError),
    Sink(E),
}

impl<'a> PresentationFrame<'a> {
    /// Visits the changed row content, then replaces the cursor layer if needed.
    /// An interrupted visit can replay the same frame and damage.
    pub fn visit_paint_commands<E>(
        &self,
        damage: PresentationDamage<'_>,
        cursor_thickness: NonZeroU32,
        mut emit: impl FnMut(PaintCommand<'a, PresentationRun<'a>>) -> Result<(), E>,
    ) -> Result<(), PaintError<E>> {
        if self.geometry.cell_pixels().is_none() {
            return Err(PaintError::GeometryUnavailable);
        }
        let size = self.geometry.pty_size();
        let width = usize::from(size.columns);
        let mut replace_cursor = damage.cursor.is_some();
        let mut paint_row = |row| {
            let source = self
                .viewport
                .row(row)
                .filter(|_| row < usize::from(size.rows))
                .ok_or(PaintError::InvalidRow(row))?;
            let backgrounds = self
                .row_backgrounds(row, 0..width)
                .expect("The row has pixel geometry");
            for background in backgrounds {
                let background = background.map_err(PaintError::Style)?;
                emit(PaintCommand::Background(background)).map_err(PaintError::Sink)?;
            }
            let runs = self
                .row_runs(row, 0..source.cells().len())
                .expect("The row is in the viewport");
            for run in runs {
                let run = run.map_err(PaintError::Style)?;
                if !run.style.style.hidden {
                    let clip = self
                        .geometry
                        .row_rect(row, run.columns())
                        .expect("The span clips to visible columns");
                    emit(PaintCommand::Text { clip, run }).map_err(PaintError::Sink)?;
                }
            }
            replace_cursor |= damage
                .displayed_cursor
                .is_some_and(|cursor| cursor.position.row == row);
            Ok(())
        };

        match damage.rows {
            RowDamage::All => {
                for row in 0..self.viewport.rows() {
                    paint_row(row)?;
                }
                replace_cursor = true;
            }
            RowDamage::Rows(rows) => {
                for &row in rows {
                    paint_row(row)?;
                }
            }
        }
        if replace_cursor {
            let cursor = damage
                .displayed_cursor
                .map(|cursor| self.cursor_paint(cursor, cursor_thickness))
                .transpose()
                .map_err(PaintError::Style)?
                .flatten();
            emit(PaintCommand::Cursor(cursor)).map_err(PaintError::Sink)?;
        }
        Ok(())
    }
}

/// Compares successive frames from one session in viewport coordinates.
#[derive(Default)]
pub struct PresentationTracker {
    committed_geometry: Option<GridGeometry>,
    committed_graphics: Option<super::GraphicsStamp>,
    indexed_graphics: bool,
    graphics_palette: u64,
    revisions: Vec<RowRevision>,
    placeholder_rows: Vec<Option<RowRevision>>,
    changed_rows: Vec<usize>,
    palette: Option<Palette>,
    reverse_video: bool,
    cursor: CursorOverlay,
}

/// A staged frame update. Dropping it before commit forces a full redraw.
#[must_use = "commit the presentation after submitting it"]
pub struct PreparedPresentation<'a> {
    tracker: &'a mut PresentationTracker,
    geometry: GridGeometry,
    graphics: Option<super::GraphicsStamp>,
    graphics_changed: bool,
    indexed_graphics: bool,
    graphics_palette: u64,
    all_rows: bool,
    cursor_change: Option<CursorChange>,
    cursor: Option<CursorOverlay>,
}

impl PreparedPresentation<'_> {
    #[inline]
    pub fn damage(&self) -> PresentationDamage<'_> {
        PresentationDamage {
            rows: if self.all_rows {
                RowDamage::All
            } else {
                RowDamage::Rows(&self.tracker.changed_rows)
            },
            graphics_changed: self.graphics_changed,
            cursor: self.cursor_change,
            displayed_cursor: self
                .cursor
                .as_ref()
                .unwrap_or(&self.tracker.cursor)
                .displayed(),
        }
    }

    /// Acknowledges a successful submission and retains its comparison baseline.
    #[inline]
    pub fn commit(self) {
        self.tracker.committed_geometry = Some(self.geometry);
        self.tracker.committed_graphics = self.graphics;
        self.tracker.indexed_graphics = self.indexed_graphics;
        self.tracker.graphics_palette = self.graphics_palette;
        if let Some(cursor) = self.cursor {
            self.tracker.cursor = cursor;
        }
    }
}

impl PresentationTracker {
    /// Forces a full redraw and resets the cursor overlay after a surface reset.
    pub fn invalidate(&mut self) {
        self.committed_geometry = None;
        self.cursor.source = None;
        self.cursor.deadline = None;
    }

    /// Sets the duration of each blink phase. Zero displays a steady cursor.
    pub fn set_cursor_blink_interval(
        &mut self,
        interval: Duration,
        now: Instant,
    ) -> Option<CursorChange> {
        if self.cursor.interval == interval {
            return None;
        }
        self.cursor.interval = interval;
        self.restart_cursor_blink(now)
    }

    /// Restores the visible phase and restarts its timer after user activity.
    pub fn restart_cursor_blink(&mut self, now: Instant) -> Option<CursorChange> {
        let before = self.cursor.displayed();
        self.cursor.restart(now);
        CursorChange::between(before, self.cursor.displayed())
    }

    pub fn cursor_deadline(&self) -> Option<Instant> {
        self.cursor.deadline
    }

    pub fn displayed_cursor(&self) -> Option<PresentedCursor> {
        self.cursor.displayed()
    }

    /// Advances the last presented cursor independently of terminal output.
    pub fn tick_cursor(&mut self, now: Instant) -> Option<CursorChange> {
        self.cursor.tick(now)
    }

    /// Stages damage and cursor state until the renderer confirms submission.
    pub fn prepare(
        &mut self,
        frame: &PresentationFrame<'_>,
        now: Instant,
    ) -> Result<PreparedPresentation<'_>, TryReserveError> {
        let rows = frame.viewport.rows();
        let height_changed = self.revisions.len() != rows;
        if rows > self.revisions.len() {
            self.revisions
                .try_reserve_exact(rows - self.revisions.len())?;
            self.changed_rows
                .try_reserve_exact(rows - self.changed_rows.len())?;
        }
        let placeholder_rows = frame.graphics_placeholder_revisions().size_hint().0;
        if placeholder_rows > self.placeholder_rows.len() {
            self.placeholder_rows
                .try_reserve_exact(placeholder_rows - self.placeholder_rows.len())?;
        }

        let colors_changed = self
            .palette
            .as_ref()
            .is_none_or(|palette| !palette.same_text_colors(frame.palette));
        // Row cache entries can be reused only after the staged frame commits.
        let committed_geometry = self.committed_geometry.take();
        let graphics = frame.graphics_stamp();
        let indexed_graphics = if graphics.map(|stamp| stamp.placement_revision)
            == self
                .committed_graphics
                .map(|stamp| stamp.placement_revision)
        {
            self.indexed_graphics
        } else {
            frame.graphics_placements().iter().any(|placement| {
                frame
                    .graphics_image(placement)
                    .is_some_and(|image| image.format() != GraphicsImageFormat::Rgba)
            })
        };
        let graphics_palette = frame.palette.revision();
        let mut graphics_changed = graphics != self.committed_graphics
            || (graphics.is_some() && committed_geometry != Some(frame.geometry))
            || (indexed_graphics && graphics_palette != self.graphics_palette);
        let all_rows = height_changed
            || committed_geometry != Some(frame.geometry)
            || colors_changed
            || self.reverse_video != frame.reverse_video;
        self.changed_rows.clear();
        if all_rows {
            self.revisions.clear();
            self.revisions
                .extend(frame.viewport.iter_rows().map(Row::revision));
            self.reverse_video = frame.reverse_video;
        } else {
            for (index, (previous, row)) in self
                .revisions
                .iter_mut()
                .zip(frame.viewport.iter_rows())
                .enumerate()
            {
                let revision = row.revision();
                if *previous != revision {
                    *previous = revision;
                    self.changed_rows.push(index);
                }
            }
        }
        if colors_changed {
            self.palette = Some(frame.palette.clone());
        }
        graphics_changed |= self.graphics_rows_changed(frame, placeholder_rows, all_rows);

        let source = frame
            .viewport
            .cursor()
            .filter(|_| frame.cursor_appearance.visible)
            .map(|cursor| PresentedCursor {
                position: CellPosition {
                    row: cursor.row,
                    column: cursor.column,
                },
                appearance: frame.cursor_appearance,
                color: frame.palette.color(PaletteEntry::Cursor),
            });
        let source_changed = self.cursor.source != source;
        let (cursor, cursor_change) =
            if source_changed || self.cursor.deadline.is_some_and(|deadline| now >= deadline) {
                let mut cursor = self.cursor;
                let change = if source_changed {
                    let before = cursor.displayed();
                    cursor.source = source;
                    cursor.restart(now);
                    CursorChange::between(before, source)
                } else {
                    cursor.tick(now)
                };
                (Some(cursor), change)
            } else {
                (None, None)
            };
        Ok(PreparedPresentation {
            tracker: self,
            geometry: frame.geometry,
            graphics,
            graphics_changed,
            indexed_graphics,
            graphics_palette,
            all_rows,
            cursor_change,
            cursor,
        })
    }

    fn graphics_rows_changed(
        &mut self,
        frame: &PresentationFrame<'_>,
        count: usize,
        all_rows: bool,
    ) -> bool {
        if count == 0 {
            self.placeholder_rows.clear();
            return false;
        }
        let revisions = || frame.graphics_placeholder_revisions();
        if all_rows || self.placeholder_rows.len() != count {
            let changed = !revisions().eq(self.placeholder_rows.iter().copied());
            self.placeholder_rows.clear();
            self.placeholder_rows.extend(revisions());
            return changed;
        }
        let mut changed = false;
        for &index in &self.changed_rows {
            let row = frame.viewport.row(index).expect("Damaged rows are visible");
            let revision = row.graphics_placeholder_revision();
            changed |= std::mem::replace(&mut self.placeholder_rows[index], revision) != revision;
        }
        let visible = frame.viewport.rows();
        if count > visible {
            for (previous, revision) in self.placeholder_rows[visible..]
                .iter_mut()
                .zip(revisions().skip(visible))
            {
                changed |= std::mem::replace(previous, revision) != revision;
            }
        }
        changed
    }
}

#[derive(Clone, Copy, Default)]
struct CursorOverlay {
    source: Option<PresentedCursor>,
    interval: Duration,
    deadline: Option<Instant>,
    hidden: bool,
}

impl CursorOverlay {
    fn displayed(&self) -> Option<PresentedCursor> {
        if self.hidden { None } else { self.source }
    }

    fn restart(&mut self, now: Instant) {
        self.hidden = false;
        self.deadline = if !self.interval.is_zero()
            && self.source.is_some_and(|cursor| cursor.appearance.blinking)
        {
            now.checked_add(self.interval)
        } else {
            None
        };
    }

    fn tick(&mut self, now: Instant) -> Option<CursorChange> {
        if !self.advance(now) {
            return None;
        }
        let (before, after) = if self.hidden {
            (self.source, None)
        } else {
            (None, self.source)
        };
        Some(CursorChange { before, after })
    }

    fn advance(&mut self, now: Instant) -> bool {
        let Some(deadline) = self.deadline.filter(|&deadline| now >= deadline) else {
            return false;
        };
        let overdue = now.duration_since(deadline);
        let (toggle, next) = if overdue < self.interval {
            (true, deadline.checked_add(self.interval))
        } else {
            let overdue_nanos = overdue.as_nanos();
            let interval_nanos = self.interval.as_nanos();
            let skipped = overdue_nanos / interval_nanos;
            let wait = Duration::from_nanos_u128(interval_nanos - overdue_nanos % interval_nanos);
            (skipped.is_multiple_of(2), now.checked_add(wait))
        };
        self.deadline = next;
        let was_hidden = self.hidden;
        self.hidden = next.is_some() && (was_hidden ^ toggle);
        self.hidden != was_hidden
    }
}