1use std::collections::TryReserveError;
2use std::num::NonZeroU32;
3use std::time::{Duration, Instant};
4
5use lune_terminal::{
6 CellPosition, CellText, CursorAppearance, CursorShape, DisplayUnit, GraphicsImageFormat,
7 Palette, PaletteEntry, Rgb, Row, RowRevision, Style, StyleError,
8};
9
10use crate::{GridGeometry, PixelRect};
11
12use super::{BackgroundRect, PresentationFrame, PresentationRun};
13
14mod batch;
15
16pub use batch::{BatchRun, PaintBatch};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum RowDamage<'a> {
20 All,
21 Rows(&'a [usize]),
23}
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct PresentedCursor {
27 pub position: CellPosition,
28 pub appearance: CursorAppearance,
29 pub color: Rgb,
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct CursorPaint<'a> {
34 pub rect: PixelRect,
35 pub color: Rgb,
36 pub glyph: Option<CursorGlyph<'a>>,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct CursorGlyph<'a> {
41 pub unit: DisplayUnit<'a>,
42 pub color: Rgb,
43 pub style: &'a Style,
44}
45
46impl<'a> PresentationFrame<'a> {
47 pub fn cursor_paint(
50 &self,
51 cursor: PresentedCursor,
52 thickness: NonZeroU32,
53 ) -> Result<Option<CursorPaint<'a>>, StyleError> {
54 let Some(cell) = self.geometry.cell_pixels() else {
55 return Ok(None);
56 };
57 let CellPosition { row, column } = cursor.position;
58 if !cursor.appearance.visible || column >= usize::from(self.geometry.pty_size().columns) {
59 return Ok(None);
60 }
61 let Some(source) = self.viewport.row(row) else {
62 return Ok(None);
63 };
64 let cells = source.cells();
65 let Some(covered) = cells.get(column) else {
66 return Ok(None);
67 };
68 let leading = column - usize::from(covered.is_continuation());
69 let covered = cells[leading];
70 let Some(mut rect) = self
71 .geometry
72 .row_rect(row, leading..leading + covered.width())
73 else {
74 return Ok(None);
75 };
76
77 let mut glyph = None;
78 match cursor.appearance.shape {
79 CursorShape::Block
80 if !covered.is_erased()
81 && covered.character() != Some(lune_terminal::GRAPHICS_PLACEHOLDER) =>
82 {
83 let id = covered.style();
84 let style = self.resolve_style(id).ok_or(StyleError::InvalidId(id))?;
85 if !style.style.hidden {
86 let color = cursor_text_color(style.background, style.foreground, cursor.color);
87 let text = if covered.has_extended_text() {
88 source
89 .text(leading)
90 .expect("The leading column is in the row")
91 } else {
92 CellText::Scalar(covered.character().expect("A leading cell has a scalar"))
93 };
94 glyph = Some(CursorGlyph {
95 unit: DisplayUnit {
96 column: leading,
97 cell: covered,
98 text,
99 },
100 color,
101 style: style.style,
102 });
103 }
104 }
105 CursorShape::Block => {}
106 CursorShape::Bar => rect.size.width = thickness.min(cell.width),
107 CursorShape::Underline => {
108 let height = thickness.min(cell.height);
109 rect.origin.y += cell.height.get() - height.get();
110 rect.size.height = height;
111 }
112 }
113 Ok(Some(CursorPaint {
114 rect,
115 color: cursor.color,
116 glyph,
117 }))
118 }
119}
120
121fn cursor_text_color(background: Rgb, foreground: Rgb, cursor: Rgb) -> Rgb {
122 if background != cursor {
123 background
124 } else if foreground != cursor {
125 foreground
126 } else {
127 let brightness = 54 * u32::from(cursor.red)
128 + 183 * u32::from(cursor.green)
129 + 19 * u32::from(cursor.blue);
130 let channel = if brightness >= 128 * 256 { 0 } else { 255 };
131 Rgb {
132 red: channel,
133 green: channel,
134 blue: channel,
135 }
136 }
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub struct CursorChange {
141 pub before: Option<PresentedCursor>,
142 pub after: Option<PresentedCursor>,
143}
144
145impl CursorChange {
146 fn between(before: Option<PresentedCursor>, after: Option<PresentedCursor>) -> Option<Self> {
147 (before != after).then_some(Self { before, after })
148 }
149}
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub struct PresentationDamage<'a> {
153 pub rows: RowDamage<'a>,
154 pub graphics_changed: bool,
155 pub cursor: Option<CursorChange>,
157 pub displayed_cursor: Option<PresentedCursor>,
158}
159
160pub enum PaintCommand<'a, Run> {
161 Background(BackgroundRect),
162 Text {
163 clip: PixelRect,
164 run: Run,
165 },
166 Cursor(Option<CursorPaint<'a>>),
168}
169
170#[derive(Debug)]
171pub enum PaintError<E> {
172 GeometryUnavailable,
173 InvalidRow(usize),
174 Style(StyleError),
175 Sink(E),
176}
177
178impl<'a> PresentationFrame<'a> {
179 pub fn visit_paint_commands<E>(
182 &self,
183 damage: PresentationDamage<'_>,
184 cursor_thickness: NonZeroU32,
185 mut emit: impl FnMut(PaintCommand<'a, PresentationRun<'a>>) -> Result<(), E>,
186 ) -> Result<(), PaintError<E>> {
187 if self.geometry.cell_pixels().is_none() {
188 return Err(PaintError::GeometryUnavailable);
189 }
190 let size = self.geometry.pty_size();
191 let width = usize::from(size.columns);
192 let mut replace_cursor = damage.cursor.is_some();
193 let mut paint_row = |row| {
194 let source = self
195 .viewport
196 .row(row)
197 .filter(|_| row < usize::from(size.rows))
198 .ok_or(PaintError::InvalidRow(row))?;
199 let backgrounds = self
200 .row_backgrounds(row, 0..width)
201 .expect("The row has pixel geometry");
202 for background in backgrounds {
203 let background = background.map_err(PaintError::Style)?;
204 emit(PaintCommand::Background(background)).map_err(PaintError::Sink)?;
205 }
206 let runs = self
207 .row_runs(row, 0..source.cells().len())
208 .expect("The row is in the viewport");
209 for run in runs {
210 let run = run.map_err(PaintError::Style)?;
211 if !run.style.style.hidden {
212 let clip = self
213 .geometry
214 .row_rect(row, run.columns())
215 .expect("The span clips to visible columns");
216 emit(PaintCommand::Text { clip, run }).map_err(PaintError::Sink)?;
217 }
218 }
219 replace_cursor |= damage
220 .displayed_cursor
221 .is_some_and(|cursor| cursor.position.row == row);
222 Ok(())
223 };
224
225 match damage.rows {
226 RowDamage::All => {
227 for row in 0..self.viewport.rows() {
228 paint_row(row)?;
229 }
230 replace_cursor = true;
231 }
232 RowDamage::Rows(rows) => {
233 for &row in rows {
234 paint_row(row)?;
235 }
236 }
237 }
238 if replace_cursor {
239 let cursor = damage
240 .displayed_cursor
241 .map(|cursor| self.cursor_paint(cursor, cursor_thickness))
242 .transpose()
243 .map_err(PaintError::Style)?
244 .flatten();
245 emit(PaintCommand::Cursor(cursor)).map_err(PaintError::Sink)?;
246 }
247 Ok(())
248 }
249}
250
251#[derive(Default)]
253pub struct PresentationTracker {
254 committed_geometry: Option<GridGeometry>,
255 committed_graphics: Option<super::GraphicsStamp>,
256 indexed_graphics: bool,
257 graphics_palette: u64,
258 revisions: Vec<RowRevision>,
259 placeholder_rows: Vec<Option<RowRevision>>,
260 changed_rows: Vec<usize>,
261 palette: Option<Palette>,
262 reverse_video: bool,
263 cursor: CursorOverlay,
264}
265
266#[must_use = "commit the presentation after submitting it"]
268pub struct PreparedPresentation<'a> {
269 tracker: &'a mut PresentationTracker,
270 geometry: GridGeometry,
271 graphics: Option<super::GraphicsStamp>,
272 graphics_changed: bool,
273 indexed_graphics: bool,
274 graphics_palette: u64,
275 all_rows: bool,
276 cursor_change: Option<CursorChange>,
277 cursor: Option<CursorOverlay>,
278}
279
280impl PreparedPresentation<'_> {
281 #[inline]
282 pub fn damage(&self) -> PresentationDamage<'_> {
283 PresentationDamage {
284 rows: if self.all_rows {
285 RowDamage::All
286 } else {
287 RowDamage::Rows(&self.tracker.changed_rows)
288 },
289 graphics_changed: self.graphics_changed,
290 cursor: self.cursor_change,
291 displayed_cursor: self
292 .cursor
293 .as_ref()
294 .unwrap_or(&self.tracker.cursor)
295 .displayed(),
296 }
297 }
298
299 #[inline]
301 pub fn commit(self) {
302 self.tracker.committed_geometry = Some(self.geometry);
303 self.tracker.committed_graphics = self.graphics;
304 self.tracker.indexed_graphics = self.indexed_graphics;
305 self.tracker.graphics_palette = self.graphics_palette;
306 if let Some(cursor) = self.cursor {
307 self.tracker.cursor = cursor;
308 }
309 }
310}
311
312impl PresentationTracker {
313 pub fn invalidate(&mut self) {
315 self.committed_geometry = None;
316 self.cursor.source = None;
317 self.cursor.deadline = None;
318 }
319
320 pub fn set_cursor_blink_interval(
322 &mut self,
323 interval: Duration,
324 now: Instant,
325 ) -> Option<CursorChange> {
326 if self.cursor.interval == interval {
327 return None;
328 }
329 self.cursor.interval = interval;
330 self.restart_cursor_blink(now)
331 }
332
333 pub fn restart_cursor_blink(&mut self, now: Instant) -> Option<CursorChange> {
335 let before = self.cursor.displayed();
336 self.cursor.restart(now);
337 CursorChange::between(before, self.cursor.displayed())
338 }
339
340 pub fn cursor_deadline(&self) -> Option<Instant> {
341 self.cursor.deadline
342 }
343
344 pub fn displayed_cursor(&self) -> Option<PresentedCursor> {
345 self.cursor.displayed()
346 }
347
348 pub fn tick_cursor(&mut self, now: Instant) -> Option<CursorChange> {
350 self.cursor.tick(now)
351 }
352
353 pub fn prepare(
355 &mut self,
356 frame: &PresentationFrame<'_>,
357 now: Instant,
358 ) -> Result<PreparedPresentation<'_>, TryReserveError> {
359 let rows = frame.viewport.rows();
360 let height_changed = self.revisions.len() != rows;
361 if rows > self.revisions.len() {
362 self.revisions
363 .try_reserve_exact(rows - self.revisions.len())?;
364 self.changed_rows
365 .try_reserve_exact(rows - self.changed_rows.len())?;
366 }
367 let placeholder_rows = frame.graphics_placeholder_revisions().size_hint().0;
368 if placeholder_rows > self.placeholder_rows.len() {
369 self.placeholder_rows
370 .try_reserve_exact(placeholder_rows - self.placeholder_rows.len())?;
371 }
372
373 let colors_changed = self
374 .palette
375 .as_ref()
376 .is_none_or(|palette| !palette.same_text_colors(frame.palette));
377 let committed_geometry = self.committed_geometry.take();
379 let graphics = frame.graphics_stamp();
380 let indexed_graphics = if graphics.map(|stamp| stamp.placement_revision)
381 == self
382 .committed_graphics
383 .map(|stamp| stamp.placement_revision)
384 {
385 self.indexed_graphics
386 } else {
387 frame.graphics_placements().iter().any(|placement| {
388 frame
389 .graphics_image(placement)
390 .is_some_and(|image| image.format() != GraphicsImageFormat::Rgba)
391 })
392 };
393 let graphics_palette = frame.palette.revision();
394 let mut graphics_changed = graphics != self.committed_graphics
395 || (graphics.is_some() && committed_geometry != Some(frame.geometry))
396 || (indexed_graphics && graphics_palette != self.graphics_palette);
397 let all_rows = height_changed
398 || committed_geometry != Some(frame.geometry)
399 || colors_changed
400 || self.reverse_video != frame.reverse_video;
401 self.changed_rows.clear();
402 if all_rows {
403 self.revisions.clear();
404 self.revisions
405 .extend(frame.viewport.iter_rows().map(Row::revision));
406 self.reverse_video = frame.reverse_video;
407 } else {
408 for (index, (previous, row)) in self
409 .revisions
410 .iter_mut()
411 .zip(frame.viewport.iter_rows())
412 .enumerate()
413 {
414 let revision = row.revision();
415 if *previous != revision {
416 *previous = revision;
417 self.changed_rows.push(index);
418 }
419 }
420 }
421 if colors_changed {
422 self.palette = Some(frame.palette.clone());
423 }
424 graphics_changed |= self.graphics_rows_changed(frame, placeholder_rows, all_rows);
425
426 let source = frame
427 .viewport
428 .cursor()
429 .filter(|_| frame.cursor_appearance.visible)
430 .map(|cursor| PresentedCursor {
431 position: CellPosition {
432 row: cursor.row,
433 column: cursor.column,
434 },
435 appearance: frame.cursor_appearance,
436 color: frame.palette.color(PaletteEntry::Cursor),
437 });
438 let source_changed = self.cursor.source != source;
439 let (cursor, cursor_change) =
440 if source_changed || self.cursor.deadline.is_some_and(|deadline| now >= deadline) {
441 let mut cursor = self.cursor;
442 let change = if source_changed {
443 let before = cursor.displayed();
444 cursor.source = source;
445 cursor.restart(now);
446 CursorChange::between(before, source)
447 } else {
448 cursor.tick(now)
449 };
450 (Some(cursor), change)
451 } else {
452 (None, None)
453 };
454 Ok(PreparedPresentation {
455 tracker: self,
456 geometry: frame.geometry,
457 graphics,
458 graphics_changed,
459 indexed_graphics,
460 graphics_palette,
461 all_rows,
462 cursor_change,
463 cursor,
464 })
465 }
466
467 fn graphics_rows_changed(
468 &mut self,
469 frame: &PresentationFrame<'_>,
470 count: usize,
471 all_rows: bool,
472 ) -> bool {
473 if count == 0 {
474 self.placeholder_rows.clear();
475 return false;
476 }
477 let revisions = || frame.graphics_placeholder_revisions();
478 if all_rows || self.placeholder_rows.len() != count {
479 let changed = !revisions().eq(self.placeholder_rows.iter().copied());
480 self.placeholder_rows.clear();
481 self.placeholder_rows.extend(revisions());
482 return changed;
483 }
484 let mut changed = false;
485 for &index in &self.changed_rows {
486 let row = frame.viewport.row(index).expect("Damaged rows are visible");
487 let revision = row.graphics_placeholder_revision();
488 changed |= std::mem::replace(&mut self.placeholder_rows[index], revision) != revision;
489 }
490 let visible = frame.viewport.rows();
491 if count > visible {
492 for (previous, revision) in self.placeholder_rows[visible..]
493 .iter_mut()
494 .zip(revisions().skip(visible))
495 {
496 changed |= std::mem::replace(previous, revision) != revision;
497 }
498 }
499 changed
500 }
501}
502
503#[derive(Clone, Copy, Default)]
504struct CursorOverlay {
505 source: Option<PresentedCursor>,
506 interval: Duration,
507 deadline: Option<Instant>,
508 hidden: bool,
509}
510
511impl CursorOverlay {
512 fn displayed(&self) -> Option<PresentedCursor> {
513 if self.hidden { None } else { self.source }
514 }
515
516 fn restart(&mut self, now: Instant) {
517 self.hidden = false;
518 self.deadline = if !self.interval.is_zero()
519 && self.source.is_some_and(|cursor| cursor.appearance.blinking)
520 {
521 now.checked_add(self.interval)
522 } else {
523 None
524 };
525 }
526
527 fn tick(&mut self, now: Instant) -> Option<CursorChange> {
528 if !self.advance(now) {
529 return None;
530 }
531 let (before, after) = if self.hidden {
532 (self.source, None)
533 } else {
534 (None, self.source)
535 };
536 Some(CursorChange { before, after })
537 }
538
539 fn advance(&mut self, now: Instant) -> bool {
540 let Some(deadline) = self.deadline.filter(|&deadline| now >= deadline) else {
541 return false;
542 };
543 let overdue = now.duration_since(deadline);
544 let (toggle, next) = if overdue < self.interval {
545 (true, deadline.checked_add(self.interval))
546 } else {
547 let overdue_nanos = overdue.as_nanos();
548 let interval_nanos = self.interval.as_nanos();
549 let skipped = overdue_nanos / interval_nanos;
550 let wait = Duration::from_nanos_u128(interval_nanos - overdue_nanos % interval_nanos);
551 (skipped.is_multiple_of(2), now.checked_add(wait))
552 };
553 self.deadline = next;
554 let was_hidden = self.hidden;
555 self.hidden = next.is_some() && (was_hidden ^ toggle);
556 self.hidden != was_hidden
557 }
558}