tvision_rs/screen/draw_buffer.rs
1//! `DrawBuffer`, a scratch row of cells (documented on the type).
2
3use crate::color::Style;
4use crate::screen::Cell;
5use crate::text;
6
7/// A fixed-width row of screen cells under construction.
8///
9/// `DrawBuffer` — a scratch row of [`Cell`]s.
10///
11/// A view fills a `DrawBuffer` one display line at a time and then blits it. The
12/// buffer is a `Vec<Cell>` of an explicit width; writes past the end are clipped
13/// against that width. Text writing delegates to the [`text`] primitives, so
14/// width-aware truncation and double-width handling are shared with the rest of
15/// the renderer.
16///
17/// ### No `0 = retain` sentinel
18/// [`move_char`](DrawBuffer::move_char) always writes both the char and the
19/// style. For the rare "change only the attribute / only the char of a cell"
20/// cases, use [`put_attribute`](DrawBuffer::put_attribute) /
21/// [`put_char`](DrawBuffer::put_char).
22///
23/// # Turbo Vision heritage
24///
25/// Ports `TDrawBuffer` (`drawbuf.h`, `drivers.cpp`), which allocated a fixed
26/// capacity sized to the screen; here it is a `Vec<Cell>` of an explicit width.
27/// The original packed a `0` char/attribute to mean "keep what is already there";
28/// that sentinel is dropped in favour of the typed cell model (deviation D6).
29/// Text drawing routes through the shared Unicode-aware text primitives
30/// (deviation D13).
31#[derive(Clone, Debug)]
32pub struct DrawBuffer {
33 data: Vec<Cell>,
34}
35
36impl DrawBuffer {
37 /// A blank buffer `width` columns wide (every cell a space with the default
38 /// style). `width` is the `capacity` against which all writes are clipped.
39 pub fn new(width: usize) -> Self {
40 DrawBuffer {
41 data: vec![Cell::default(); width],
42 }
43 }
44
45 /// The buffer's width in columns; all write operations are clipped to this limit.
46 ///
47 /// Equals the `width` passed to [`DrawBuffer::new`]. Use this to cap a fill
48 /// count or guard a manual write loop so it stays within the allocated buffer.
49 pub fn capacity(&self) -> usize {
50 self.data.len()
51 }
52
53 /// A read-only view of all cells in the buffer, from column 0 to
54 /// [`capacity`](DrawBuffer::capacity) − 1.
55 ///
56 /// Call this after filling the buffer to hand the completed row to a
57 /// drawing context (e.g. pass it to `ctx.write_buf`), or to inspect
58 /// individual cells in tests. The slice length always equals `capacity`.
59 pub fn cells(&self) -> &[Cell] {
60 &self.data
61 }
62
63 /// Set the char of a single cell at `indent`, leaving its style untouched.
64 ///
65 /// Prefer this over [`move_char`](DrawBuffer::move_char) when you only want to
66 /// change the glyph of an already-styled cell — for example, placing a border
67 /// corner over a cell whose colour was set by an earlier pass. Out-of-range
68 /// `indent` is a silent no-op.
69 pub fn put_char(&mut self, indent: usize, ch: char) {
70 if indent < self.data.len() {
71 self.data[indent].set_char(ch);
72 }
73 }
74
75 /// Set the style of a single cell at `indent`, leaving its char untouched.
76 ///
77 /// Prefer this over [`move_char`](DrawBuffer::move_char) when you only want to
78 /// restyle a cell without changing its glyph — for example, applying a
79 /// highlight colour to text that was placed by an earlier pass. Out-of-range
80 /// `indent` is a silent no-op.
81 pub fn put_attribute(&mut self, indent: usize, style: Style) {
82 if indent < self.data.len() {
83 self.data[indent].set_style(style);
84 }
85 }
86
87 /// Fill `count` cells from `indent` with `ch` and `style`, clipped to
88 /// capacity. (See the [`DrawBuffer`] docs on the dropped `0 = retain` sentinel.)
89 pub fn move_char(&mut self, indent: usize, ch: char, style: Style, count: usize) {
90 let cap = self.data.len();
91 if count == 0 || indent >= cap {
92 return;
93 }
94 let count = if indent.saturating_add(count) >= cap {
95 cap - indent
96 } else {
97 count
98 };
99 let mut cell = Cell::default();
100 cell.set_char(ch);
101 cell.set_style(style);
102 for slot in &mut self.data[indent..indent + count] {
103 *slot = cell.clone();
104 }
105 }
106
107 /// Write `text` at column `indent`, starting from column `str_indent` of
108 /// `text`, with a fixed `style`, writing at most `max_width` columns. Returns
109 /// the number of cells written.
110 pub fn move_str_part(
111 &mut self,
112 indent: usize,
113 text: &str,
114 style: Style,
115 max_width: usize,
116 str_indent: usize,
117 ) -> usize {
118 let cap = self.data.len();
119 if indent >= cap || text.is_empty() || max_width == 0 {
120 return 0;
121 }
122 let end = if indent.saturating_add(max_width) >= cap {
123 cap
124 } else {
125 indent + max_width
126 };
127 text::draw_str(
128 &mut self.data[..end],
129 indent,
130 text,
131 str_indent as i32,
132 style,
133 )
134 }
135
136 /// Write `text` at `indent` with `style`, unbounded width, from the start of
137 /// `text`.
138 pub fn move_str(&mut self, indent: usize, text: &str, style: Style) -> usize {
139 self.move_str_part(indent, text, style, self.data.len(), 0)
140 }
141
142 /// Write a *control string*: `text` is drawn with `lo`, and each `~` toggles
143 /// between `lo` and `hi` (the classic hotkey-highlight markup). Returns the
144 /// number of cells written.
145 pub fn move_cstr_part(
146 &mut self,
147 indent: usize,
148 text: &str,
149 lo: Style,
150 hi: Style,
151 max_width: usize,
152 str_indent: usize,
153 ) -> usize {
154 let cap = self.data.len();
155 if indent >= cap || text.is_empty() || max_width == 0 {
156 return 0;
157 }
158 let end = if indent.saturating_add(max_width) >= cap {
159 cap
160 } else {
161 indent + max_width
162 };
163 let dest = &mut self.data[..end];
164 let attrs = [lo, hi];
165 let mut cur = lo;
166 let mut toggle = 1usize; // first '~' selects attrs[1] (hi)
167 let mut i = indent;
168 let mut j = 0usize; // byte offset into text
169 let mut w = 0usize; // columns consumed while skipping str_indent
170 let bytes = text.as_bytes();
171 while j < text.len() {
172 if bytes[j] == b'~' {
173 cur = attrs[toggle];
174 toggle = 1 - toggle;
175 j += 1;
176 } else if str_indent <= w {
177 let (len, adv) = text::draw_one(dest, i, text, j, |s| *s = cur);
178 if len == 0 {
179 break;
180 }
181 i += adv;
182 j += len;
183 } else {
184 match text::next(&text[j..]) {
185 None => break,
186 Some((len, gw)) => {
187 j += len;
188 w += gw;
189 if str_indent < w && i < dest.len() {
190 // str_indent fell inside a double-width glyph.
191 dest[i].set_char(' ');
192 dest[i].set_style(cur);
193 i += 1;
194 }
195 }
196 }
197 }
198 }
199 i - indent
200 }
201
202 /// Write a control string at full width, from the start.
203 pub fn move_cstr(&mut self, indent: usize, text: &str, lo: Style, hi: Style) -> usize {
204 self.move_cstr_part(indent, text, lo, hi, self.data.len(), 0)
205 }
206
207 /// Copy a run of pre-built cells into the buffer at `indent`, clipped to
208 /// capacity.
209 ///
210 /// Use `move_buf` when you have already assembled the styled cells — for
211 /// example, copying another view's row out of a [`DrawBuffer`] or blitting a
212 /// pre-rendered sprite. For the common cases of filling with a single
213 /// character+style use [`move_char`](Self::move_char); for rendering a string
214 /// use [`move_str`](Self::move_str) or [`move_cstr`](Self::move_cstr).
215 ///
216 /// In the typed cell model the meaningful operation is copying cells, so this
217 /// takes a `&[Cell]` rather than a raw byte buffer.
218 ///
219 /// # Turbo Vision heritage
220 ///
221 /// Ports `MoveBuf` (`drivers.cpp`); the C++ `Word`/attribute pair buffer
222 /// becomes a typed `&[Cell]` slice. `MoveBuf`'s raw-byte
223 /// coupling to the `TDrawBuffer` layout has no equivalent here.
224 pub fn move_buf(&mut self, indent: usize, src: &[Cell]) {
225 let cap = self.data.len();
226 if indent >= cap {
227 return;
228 }
229 let n = src.len().min(cap - indent);
230 self.data[indent..indent + n].clone_from_slice(&src[..n]);
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use crate::color::Color;
238
239 fn render(b: &DrawBuffer) -> String {
240 b.cells().iter().map(|c| c.symbol()).collect()
241 }
242
243 #[test]
244 fn move_char_fills_and_clips() {
245 let mut b = DrawBuffer::new(5);
246 let s = Style::new(Color::Bios(0xF), Color::Bios(0x1));
247 b.move_char(1, '*', s, 2);
248 assert_eq!(render(&b), " ** "); // width-5 buffer
249 assert_eq!(b.cells()[1].style(), s);
250 assert_eq!(b.cells()[0].style(), Style::default());
251
252 // count past the end is clamped
253 b.move_char(3, '#', s, 99);
254 assert_eq!(render(&b), " **##");
255 }
256
257 #[test]
258 fn move_str_writes_and_returns_width() {
259 let mut b = DrawBuffer::new(10);
260 let s = Style::new(Color::Bios(0x7), Color::Default);
261 let n = b.move_str(2, "hello", s);
262 assert_eq!(n, 5);
263 assert_eq!(&render(&b)[..8], " hello ");
264 assert_eq!(b.cells()[2].style(), s);
265 }
266
267 #[test]
268 fn move_str_clips_to_capacity_and_max_width() {
269 let mut b = DrawBuffer::new(6);
270 // capacity clip: only 4 cells from indent 2
271 let n = b.move_str(2, "abcdef", Style::default());
272 assert_eq!(n, 4);
273 assert_eq!(render(&b), " abcd");
274
275 // explicit max_width clip
276 let mut b2 = DrawBuffer::new(10);
277 let n2 = b2.move_str_part(0, "abcdef", Style::default(), 3, 0);
278 assert_eq!(n2, 3);
279 assert_eq!(&render(&b2)[..3], "abc");
280 }
281
282 #[test]
283 fn move_str_indent_into_text() {
284 let mut b = DrawBuffer::new(10);
285 let n = b.move_str_part(0, "abcdef", Style::default(), 10, 2);
286 assert_eq!(n, 4);
287 assert_eq!(&render(&b)[..4], "cdef");
288 }
289
290 #[test]
291 fn move_cstr_toggles_attribute_on_tilde() {
292 let mut b = DrawBuffer::new(10);
293 let lo = Style::new(Color::Bios(0x7), Color::Default);
294 let hi = Style::new(Color::Bios(0xF), Color::Default);
295 // "~O~pen": 'O' is highlighted, "pen" reverts to lo.
296 let n = b.move_cstr(0, "~O~pen", lo, hi);
297 assert_eq!(n, 4); // O p e n (tildes consume no cell)
298 assert_eq!(render(&b), "Open ");
299 assert_eq!(b.cells()[0].style(), hi); // O highlighted
300 assert_eq!(b.cells()[1].style(), lo); // p reverted
301 assert_eq!(b.cells()[2].style(), lo);
302 }
303
304 #[test]
305 fn move_cstr_plain_text_uses_lo() {
306 let mut b = DrawBuffer::new(10);
307 let lo = Style::new(Color::Bios(0x7), Color::Default);
308 let hi = Style::new(Color::Bios(0xF), Color::Default);
309 let n = b.move_cstr(0, "Cancel", lo, hi);
310 assert_eq!(n, 6);
311 assert_eq!(render(&b), "Cancel ");
312 for i in 0..6 {
313 assert_eq!(b.cells()[i].style(), lo);
314 }
315 }
316
317 #[test]
318 fn put_char_and_put_attribute() {
319 let mut b = DrawBuffer::new(4);
320 let s = Style::new(Color::Bios(0x1), Color::Default);
321 b.put_char(1, 'Z');
322 b.put_attribute(1, s);
323 assert_eq!(b.cells()[1].symbol(), "Z");
324 assert_eq!(b.cells()[1].style(), s);
325 // out of range is a no-op
326 b.put_char(99, 'X');
327 assert_eq!(render(&b), " Z ");
328 }
329
330 #[test]
331 fn move_buf_copies_cells() {
332 let mut src = DrawBuffer::new(3);
333 src.move_str(0, "xyz", Style::new(Color::Bios(0x2), Color::Default));
334
335 let mut b = DrawBuffer::new(6);
336 b.move_buf(2, src.cells());
337 assert_eq!(render(&b), " xyz ");
338 assert_eq!(
339 b.cells()[2].style(),
340 Style::new(Color::Bios(0x2), Color::Default)
341 );
342
343 // clipped at capacity
344 let mut b2 = DrawBuffer::new(4);
345 b2.move_buf(3, src.cells());
346 assert_eq!(render(&b2), " x");
347 }
348
349 #[test]
350 fn move_str_wide_glyph_in_buffer() {
351 let mut b = DrawBuffer::new(6);
352 let n = b.move_str(0, "中a", Style::default());
353 assert_eq!(n, 3); // wide lead + trail + 'a'
354 assert!(b.cells()[0].is_wide());
355 assert!(b.cells()[1].is_wide_trail());
356 assert_eq!(b.cells()[2].symbol(), "a");
357 }
358}