iocraft/
canvas.rs

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
use crate::style::{Color, Weight};
use crossterm::{
    csi,
    style::{Attribute, Colored},
};
use std::{
    fmt::{self, Display},
    io::{self, Write},
};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

#[derive(Clone, Debug, PartialEq)]
struct Character {
    value: String,
    style: CanvasTextStyle,
}

impl Character {
    fn required_padding(&self) -> usize {
        if self.value.contains('\u{fe0f}') {
            // for the image variation selector, we need to explicitly append padding to keep things lining up
            self.value.width() - 1
        } else {
            0
        }
    }
}

/// Describes the style of text to be rendered via a [`Canvas`].
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CanvasTextStyle {
    /// The color of the text.
    pub color: Option<Color>,

    /// The weight of the text.
    pub weight: Weight,

    /// Whether the text is underlined.
    pub underline: bool,
}

#[derive(Clone, Default, PartialEq)]
struct Cell {
    background_color: Option<Color>,
    character: Option<Character>,
}

impl Cell {
    fn is_empty(&self) -> bool {
        self.background_color.is_none() && self.character.is_none()
    }
}

/// `Canvas` is the medium that output is drawn to before being rendered to the terminal or other
/// destinations.
///
/// Typical use of the library doesn't require direct interaction with this struct. It is primarily useful for two cases:
///
/// - When implementing low-level components, you'll need to utilize the `Canvas` drawing methods.
/// - When implementing unit tests for components, you may want to render to a `Canvas` for inspection.
#[derive(Clone, PartialEq)]
pub struct Canvas {
    width: usize,
    cells: Vec<Vec<Cell>>,
}

impl Canvas {
    /// Constructs a new canvas with the given dimensions.
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            width,
            cells: vec![vec![Cell::default(); width]; height],
        }
    }

    /// Returns the width of the canvas.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the height of the canvas.
    pub fn height(&self) -> usize {
        self.cells.len()
    }

    fn set_background_color(&mut self, x: usize, y: usize, w: usize, h: usize, color: Color) {
        for y in y..y + h {
            let row = &mut self.cells[y];
            for x in x..x + w {
                if x < row.len() {
                    row[x].background_color = Some(color);
                }
            }
        }
    }

    fn set_text_row_chars<I>(&mut self, mut x: usize, y: usize, chars: I, style: CanvasTextStyle)
    where
        I: IntoIterator<Item = char>,
    {
        // Divide the string up into characters, which may consist of multiple Unicode code points.
        let row = &mut self.cells[y];
        let mut buf = String::new();
        for c in chars.into_iter() {
            if x >= row.len() {
                break;
            }
            let width = c.width().unwrap_or(0);
            if width > 0 && !buf.is_empty() {
                row[x].character = Some(Character {
                    value: buf.clone(),
                    style,
                });
                x += buf.width().max(1);
                buf.clear();
            }
            buf.push(c);
        }
        if !buf.is_empty() && x < row.len() {
            row[x].character = Some(Character { value: buf, style });
        }
    }

    /// Gets a subview of the canvas for writing.
    pub fn subview_mut(
        &mut self,
        x: usize,
        y: usize,
        width: usize,
        height: usize,
        clip: bool,
    ) -> CanvasSubviewMut {
        CanvasSubviewMut {
            y,
            x,
            width,
            height,
            clip,
            canvas: self,
        }
    }

    fn write_impl<W: Write>(
        &self,
        mut w: W,
        ansi: bool,
        omit_final_newline: bool,
    ) -> io::Result<()> {
        if ansi {
            write!(w, csi!("0m"))?;
        }

        let mut background_color = None;
        let mut text_style = CanvasTextStyle::default();

        for y in 0..self.cells.len() {
            let row = &self.cells[y];
            let last_non_empty = row.iter().rposition(|cell| !cell.is_empty());
            let row = &row[..last_non_empty.map_or(0, |i| i + 1)];
            let mut col = 0;
            while col < row.len() {
                let cell = &row[col];

                if ansi {
                    // For certain changes, we need to reset all attributes.
                    let mut needs_reset = false;
                    if let Some(c) = &cell.character {
                        if c.style.weight != text_style.weight && c.style.weight == Weight::Normal {
                            needs_reset = true;
                        }
                        if !c.style.underline && text_style.underline {
                            needs_reset = true;
                        }
                    } else if text_style.underline {
                        needs_reset = true;
                    }
                    if needs_reset {
                        write!(w, csi!("0m"))?;
                        background_color = None;
                        text_style = CanvasTextStyle::default();
                    }

                    if cell.background_color != background_color {
                        write!(
                            w,
                            csi!("{}m"),
                            Colored::BackgroundColor(cell.background_color.unwrap_or(Color::Reset))
                        )?;
                        background_color = cell.background_color;
                    }

                    if let Some(c) = &cell.character {
                        if c.style.color != text_style.color {
                            write!(
                                w,
                                csi!("{}m"),
                                Colored::ForegroundColor(c.style.color.unwrap_or(Color::Reset))
                            )?;
                        }

                        if c.style.weight != text_style.weight {
                            match c.style.weight {
                                Weight::Bold => write!(w, csi!("{}m"), Attribute::Bold.sgr())?,
                                Weight::Normal => {}
                                Weight::Light => write!(w, csi!("{}m"), Attribute::Dim.sgr())?,
                            }
                        }

                        if c.style.underline && !text_style.underline {
                            write!(w, csi!("{}m"), Attribute::Underlined.sgr())?;
                        }

                        text_style = c.style;
                    }
                }

                if let Some(c) = &cell.character {
                    write!(w, "{}{}", c.value, " ".repeat(c.required_padding()))?;
                    col += c.value.width().max(1);
                } else {
                    w.write_all(b" ")?;
                    col += 1;
                }
            }
            if ansi {
                // if the background color is set, we need to reset it
                if background_color.is_some() {
                    write!(w, csi!("{}m"), Colored::BackgroundColor(Color::Reset))?;
                    background_color = None;
                }
                // clear until end of line
                write!(w, csi!("K"))?;
            }
            if !omit_final_newline || y < self.cells.len() - 1 {
                if ansi {
                    // add a carriage return in case we're in raw mode
                    w.write_all(b"\r\n")?;
                } else {
                    w.write_all(b"\n")?;
                }
            }
        }
        if ansi {
            write!(w, csi!("0m"))?;
        }
        w.flush()?;
        Ok(())
    }

    /// Writes the canvas to the given writer with ANSI escape codes.
    pub fn write_ansi<W: Write>(&self, w: W) -> io::Result<()> {
        self.write_impl(w, true, false)
    }

    pub(crate) fn write_ansi_without_final_newline<W: Write>(&self, w: W) -> io::Result<()> {
        self.write_impl(w, true, true)
    }

    /// Writes the canvas to the given writer as unstyled text, without ANSI escape codes.
    pub fn write<W: Write>(&self, w: W) -> io::Result<()> {
        self.write_impl(w, false, false)
    }
}

impl Display for Canvas {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut buf = Vec::with_capacity(self.width * self.cells.len());
        self.write(&mut buf).unwrap();
        f.write_str(&String::from_utf8_lossy(&buf))?;
        Ok(())
    }
}

/// Represents a writeable region of a [`Canvas`]. All coordinates provided to functions of this
/// type are relative to the region's top-left corner.
pub struct CanvasSubviewMut<'a> {
    x: usize,
    y: usize,
    width: usize,
    height: usize,
    clip: bool,
    canvas: &'a mut Canvas,
}

impl<'a> CanvasSubviewMut<'a> {
    /// Fills the region with the given color.
    pub fn set_background_color(&mut self, x: isize, y: isize, w: usize, h: usize, color: Color) {
        let mut left = self.x as isize + x;
        let mut top = self.y as isize + y;
        let mut right = left + w as isize;
        let mut bottom = top + h as isize;
        if self.clip {
            left = left.max(self.x as isize);
            top = top.max(self.y as isize);
            right = right.min((self.x + self.width) as isize);
            bottom = bottom.min((self.y + self.height) as isize);
        }
        self.canvas.set_background_color(
            left as _,
            top as _,
            (right - left) as _,
            (bottom - top) as _,
            color,
        );
    }

    /// Writes text to the region.
    pub fn set_text(&mut self, x: isize, mut y: isize, text: &str, style: CanvasTextStyle) {
        let mut x = self.x as isize + x;
        let min_x = if self.clip { self.x as isize } else { 0 };
        let mut to_skip = 0;
        if x < min_x {
            to_skip = min_x - x;
            x = min_x;
        }
        let max_x = if self.clip {
            (self.x + self.width) as isize - 1
        } else {
            self.canvas.width as isize - 1
        };
        let horizontal_space = max_x - x + 1;
        for line in text.lines() {
            if !self.clip || (y >= 0 && y < self.height as isize) {
                let y = self.y as isize + y;
                if y >= 0 && y < self.canvas.height() as _ {
                    let mut skipped_width = 0;
                    let mut taken_width = 0;
                    self.canvas.set_text_row_chars(
                        x as usize,
                        y as usize,
                        line.chars()
                            .skip_while(|c| {
                                if skipped_width < to_skip {
                                    skipped_width += c.width().unwrap_or(0) as isize;
                                    true
                                } else {
                                    false
                                }
                            })
                            .take_while(|c| {
                                if taken_width < horizontal_space {
                                    taken_width += c.width().unwrap_or(0) as isize;
                                    true
                                } else {
                                    false
                                }
                            }),
                        style,
                    );
                }
            }
            y += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::*;

    #[test]
    fn test_canvas_background_color() {
        let mut canvas = Canvas::new(6, 3);
        assert_eq!(canvas.width(), 6);
        assert_eq!(canvas.height(), 3);

        canvas
            .subview_mut(2, 0, 3, 2, true)
            .set_background_color(0, 0, 5, 5, Color::Red);

        let mut actual = Vec::new();
        canvas.write_ansi(&mut actual).unwrap();

        let mut expected = Vec::new();
        write!(expected, csi!("0m")).unwrap();
        write!(expected, "  ").unwrap();
        write!(expected, csi!("{}m"), Colored::BackgroundColor(Color::Red)).unwrap();
        write!(expected, "   ").unwrap();
        write!(
            expected,
            csi!("{}m"),
            Colored::BackgroundColor(Color::Reset)
        )
        .unwrap();
        write!(expected, csi!("K")).unwrap();
        write!(expected, "\r\n").unwrap();
        write!(expected, "  ").unwrap();
        write!(expected, csi!("{}m"), Colored::BackgroundColor(Color::Red)).unwrap();
        write!(expected, "   ").unwrap();
        write!(
            expected,
            csi!("{}m"),
            Colored::BackgroundColor(Color::Reset)
        )
        .unwrap();
        write!(expected, csi!("K")).unwrap();
        write!(expected, "\r\n").unwrap();
        write!(expected, csi!("K")).unwrap();
        write!(expected, "\r\n").unwrap();
        write!(expected, csi!("0m")).unwrap();

        assert_eq!(actual, expected);
    }

    #[test]
    fn test_canvas_text_styles() {
        let mut canvas = Canvas::new(100, 1);
        assert_eq!(canvas.width(), 100);
        assert_eq!(canvas.height(), 1);

        canvas
            .subview_mut(0, 0, 1, 1, true)
            .set_text(0, 0, ".", CanvasTextStyle::default());
        canvas.subview_mut(1, 0, 1, 1, true).set_text(
            0,
            0,
            ".",
            CanvasTextStyle {
                color: Some(Color::Red),
                weight: Weight::Bold,
                underline: true,
                ..Default::default()
            },
        );
        canvas.subview_mut(2, 0, 1, 1, true).set_text(
            0,
            0,
            ".",
            CanvasTextStyle {
                color: Some(Color::Red),
                weight: Weight::Bold,
                ..Default::default()
            },
        );
        canvas.subview_mut(3, 0, 1, 1, true).set_text(
            0,
            0,
            ".",
            CanvasTextStyle {
                color: Some(Color::Red),
                weight: Weight::Light,
                ..Default::default()
            },
        );
        canvas.subview_mut(4, 0, 1, 1, true).set_text(
            0,
            0,
            ".",
            CanvasTextStyle {
                color: Some(Color::Red),
                ..Default::default()
            },
        );
        canvas.subview_mut(5, 0, 1, 1, true).set_text(
            0,
            0,
            ".",
            CanvasTextStyle {
                color: Some(Color::Green),
                ..Default::default()
            },
        );

        let mut actual = Vec::new();
        canvas.write_ansi(&mut actual).unwrap();

        let mut expected = Vec::new();
        write!(expected, csi!("0m")).unwrap();
        write!(expected, ".").unwrap();

        write!(expected, csi!("{}m"), Colored::ForegroundColor(Color::Red)).unwrap();
        write!(expected, csi!("{}m"), Attribute::Bold.sgr()).unwrap();
        write!(expected, csi!("{}m"), Attribute::Underlined.sgr()).unwrap();
        write!(expected, ".").unwrap();

        write!(expected, csi!("0m")).unwrap();
        write!(expected, csi!("{}m"), Colored::ForegroundColor(Color::Red)).unwrap();
        write!(expected, csi!("{}m"), Attribute::Bold.sgr()).unwrap();
        write!(expected, ".").unwrap();

        write!(expected, csi!("{}m"), Attribute::Dim.sgr()).unwrap();
        write!(expected, ".").unwrap();

        write!(expected, csi!("0m")).unwrap();
        write!(expected, csi!("{}m"), Colored::ForegroundColor(Color::Red)).unwrap();
        write!(expected, ".").unwrap();

        write!(
            expected,
            csi!("{}m"),
            Colored::ForegroundColor(Color::Green)
        )
        .unwrap();
        write!(expected, ".").unwrap();

        write!(expected, csi!("K")).unwrap();
        write!(expected, "\r\n").unwrap();
        write!(expected, csi!("0m")).unwrap();

        assert_eq!(actual, expected);
    }

    #[test]
    fn test_canvas_text_clipping() {
        let mut canvas = Canvas::new(10, 5);
        assert_eq!(canvas.width(), 10);
        assert_eq!(canvas.height(), 5);

        canvas.subview_mut(2, 2, 4, 2, true).set_text(
            -2,
            -1,
            "line 1\nline 2\nline 3\nline 4",
            CanvasTextStyle::default(),
        );

        let actual = canvas.to_string();
        assert_eq!(actual, "\n\n  ne 2\n  ne 3\n\n");
    }

    #[test]
    fn test_write_ansi_without_final_newline() {
        let mut canvas = Canvas::new(10, 3);

        canvas
            .subview_mut(0, 0, 10, 3, true)
            .set_text(0, 0, "hello!", CanvasTextStyle::default());

        let mut actual = Vec::new();
        canvas
            .write_ansi_without_final_newline(&mut actual)
            .unwrap();

        let mut expected = Vec::new();
        write!(expected, csi!("0m")).unwrap();
        write!(expected, "hello!").unwrap();
        write!(expected, csi!("K")).unwrap();
        write!(expected, "\r\n").unwrap();
        write!(expected, csi!("K")).unwrap();
        write!(expected, "\r\n").unwrap();
        write!(expected, csi!("K")).unwrap();
        write!(expected, csi!("0m")).unwrap();

        assert_eq!(actual, expected);
    }
}