Skip to main content

lune/session/presentation/
batch.rs

1use std::collections::TryReserveError;
2use std::num::NonZeroU32;
3use std::ops::Range;
4
5use lune_terminal::{
6    Cell, CellText, DisplayUnit, MAX_CELL_TEXT_BYTES, MAX_DIMENSION, PixelSize, Rgb, Style,
7};
8
9use super::{
10    BackgroundRect, CursorGlyph, CursorPaint, PaintCommand, PaintError, PresentationDamage,
11};
12use crate::{PixelRect, PresentationFrame, PresentationRun, PresentationStyle};
13
14/// Owns drawing commands and their text after the source frame is released.
15#[derive(Default)]
16pub struct PaintBatch {
17    commands: Vec<StoredCommand>,
18    units: Vec<StoredUnit>,
19    text: String,
20    cell_size: Option<PixelSize>,
21}
22
23pub struct BatchRun<'a> {
24    columns: Range<usize>,
25    units: &'a [StoredUnit],
26    text: &'a str,
27    pub style: PresentationStyle<'a>,
28}
29
30impl<'a> BatchRun<'a> {
31    #[inline]
32    pub fn columns(&self) -> Range<usize> {
33        self.columns.clone()
34    }
35
36    #[inline]
37    pub fn units(&self) -> impl ExactSizeIterator<Item = DisplayUnit<'a>> + use<'a> {
38        let text = self.text;
39        self.units.iter().map(move |unit| unit.view(text))
40    }
41}
42
43impl PaintBatch {
44    /// Replaces the batch and reuses its buffers. An error leaves it empty.
45    pub fn capture(
46        &mut self,
47        frame: &PresentationFrame<'_>,
48        damage: PresentationDamage<'_>,
49        cursor_thickness: NonZeroU32,
50    ) -> Result<(), PaintError<TryReserveError>> {
51        self.clear();
52        let result =
53            frame.visit_paint_commands(damage, cursor_thickness, |command| self.store(command));
54        if result.is_ok() {
55            self.cell_size = frame.geometry.cell_pixels();
56        } else {
57            self.clear();
58        }
59        result
60    }
61
62    pub fn cell_pixels(&self) -> Option<PixelSize> {
63        self.cell_size
64    }
65
66    #[inline]
67    pub fn commands(&self) -> impl ExactSizeIterator<Item = PaintCommand<'_, BatchRun<'_>>> {
68        self.commands.iter().map(|command| match command {
69            StoredCommand::Background(rect) => PaintCommand::Background(*rect),
70            StoredCommand::Text {
71                clip,
72                columns,
73                units,
74                style,
75            } => PaintCommand::Text {
76                clip: *clip,
77                run: BatchRun {
78                    columns: columns.clone(),
79                    units: &self.units[units.clone()],
80                    text: &self.text,
81                    style: style.view(),
82                },
83            },
84            StoredCommand::Cursor(cursor) => {
85                PaintCommand::Cursor(cursor.as_ref().map(|cursor| CursorPaint {
86                    rect: cursor.rect,
87                    color: cursor.color,
88                    glyph: cursor.glyph.as_ref().map(|glyph| CursorGlyph {
89                        unit: glyph.unit.view(&self.text),
90                        color: glyph.color,
91                        style: &glyph.style,
92                    }),
93                }))
94            }
95        })
96    }
97
98    pub(crate) fn backgrounds(&self) -> impl Iterator<Item = BackgroundRect> + '_ {
99        self.commands.iter().filter_map(|command| match command {
100            StoredCommand::Background(rect) => Some(*rect),
101            _ => None,
102        })
103    }
104
105    fn clear(&mut self) {
106        self.commands.clear();
107        self.units.clear();
108        self.text.clear();
109        self.cell_size = None;
110    }
111
112    fn store(
113        &mut self,
114        command: PaintCommand<'_, PresentationRun<'_>>,
115    ) -> Result<(), TryReserveError> {
116        self.commands.try_reserve(1)?;
117        let command = match command {
118            PaintCommand::Background(rect) => StoredCommand::Background(rect),
119            PaintCommand::Text { clip, run } => {
120                let first = self.units.len();
121                let columns = run.columns();
122                self.units.try_reserve(columns.len())?;
123                for unit in run.units() {
124                    let unit = StoredUnit::store(unit, &mut self.text)?;
125                    self.units.push(unit);
126                }
127                StoredCommand::Text {
128                    clip,
129                    columns,
130                    units: first..self.units.len(),
131                    style: StoredStyle {
132                        foreground: run.style.foreground,
133                        background: run.style.background,
134                        underline_color: run.style.underline_color,
135                        style: *run.style.style,
136                    },
137                }
138            }
139            PaintCommand::Cursor(cursor) => {
140                let cursor = match cursor {
141                    Some(cursor) => {
142                        let glyph = match cursor.glyph {
143                            Some(glyph) => Some(StoredCursorGlyph {
144                                unit: StoredUnit::store(glyph.unit, &mut self.text)?,
145                                color: glyph.color,
146                                style: *glyph.style,
147                            }),
148                            None => None,
149                        };
150                        Some(StoredCursor {
151                            rect: cursor.rect,
152                            color: cursor.color,
153                            glyph,
154                        })
155                    }
156                    None => None,
157                };
158                StoredCommand::Cursor(cursor)
159            }
160        };
161        self.commands.push(command);
162        Ok(())
163    }
164}
165
166enum StoredCommand {
167    Background(BackgroundRect),
168    Text {
169        clip: PixelRect,
170        columns: Range<usize>,
171        units: Range<usize>,
172        style: StoredStyle,
173    },
174    Cursor(Option<StoredCursor>),
175}
176
177struct StoredStyle {
178    foreground: Rgb,
179    background: Rgb,
180    underline_color: Rgb,
181    style: Style,
182}
183
184impl StoredStyle {
185    #[inline]
186    fn view(&self) -> PresentationStyle<'_> {
187        PresentationStyle {
188            foreground: self.foreground,
189            background: self.background,
190            underline_color: self.underline_color,
191            style: &self.style,
192        }
193    }
194}
195
196struct StoredCursor {
197    rect: PixelRect,
198    color: Rgb,
199    glyph: Option<StoredCursorGlyph>,
200}
201
202struct StoredCursorGlyph {
203    unit: StoredUnit,
204    color: Rgb,
205    style: Style,
206}
207
208struct StoredUnit {
209    cell: Cell,
210    text_start: usize,
211    column: u16,
212    text_len: u16,
213}
214
215const _: () = assert!(MAX_CELL_TEXT_BYTES <= u16::MAX as usize);
216const _: () = assert!(MAX_DIMENSION <= u16::MAX as usize);
217
218impl StoredUnit {
219    fn store(unit: DisplayUnit<'_>, arena: &mut String) -> Result<Self, TryReserveError> {
220        let text_start = arena.len();
221        let text_len = if let CellText::Extended(text) = unit.text {
222            if arena.capacity() - text_start < text.len() {
223                arena.try_reserve(text.len())?;
224            }
225            arena.push_str(text);
226            text.len() as u16
227        } else {
228            0
229        };
230        Ok(Self {
231            cell: unit.cell,
232            text_start,
233            column: unit.column as u16,
234            text_len,
235        })
236    }
237
238    #[inline]
239    fn view<'a>(&self, arena: &'a str) -> DisplayUnit<'a> {
240        let text = if self.text_len == 0 {
241            CellText::Scalar(self.cell.character().expect("A leading cell has a scalar"))
242        } else {
243            let end = self.text_start + usize::from(self.text_len);
244            CellText::Extended(&arena[self.text_start..end])
245        };
246        DisplayUnit {
247            column: usize::from(self.column),
248            cell: self.cell,
249            text,
250        }
251    }
252}