zi 0.3.2

A declarative library for building monospace user interfaces
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
use smallstr::SmallString;
use std::{self, cmp, iter};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use super::{Position, Size};
use crate::terminal::Rect;

/// An extended grapheme cluster represented as a `SmallString`.
pub type GraphemeCluster = SmallString<[u8; 16]>;

/// A "text element", which consists of an extended grapheme cluster and
/// associated styling.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Textel {
    pub grapheme: GraphemeCluster,
    pub style: Style,
}

/// A lightweight abstract terminal. All components in Zi ultimately draw to a
/// `Canvas`, typically via their child components or directly in the case of
/// lower level components.
#[derive(Debug, Clone)]
pub struct Canvas {
    buffer: Vec<Option<Textel>>,
    size: Size,
}

impl Canvas {
    /// A lightweight abstract terminal. All components in Zi ultimately draw to a
    /// `Canvas`, typically via their child components or directly in the case of
    /// lower level components.
    ///
    /// ```
    /// # use zi::{Canvas, Size};
    /// let canvas = Canvas::new(Size::new(10, 20));
    /// ```
    pub fn new(size: Size) -> Self {
        Self {
            buffer: iter::repeat(Textel::default())
                .map(Some)
                .take(size.area())
                .collect(),
            size,
        }
    }

    #[inline]
    pub fn size(&self) -> Size {
        self.size
    }

    #[inline]
    pub fn buffer(&self) -> &[Option<Textel>] {
        self.buffer.as_slice()
    }

    #[inline]
    pub fn buffer_mut(&mut self) -> &mut [Option<Textel>] {
        self.buffer.as_mut_slice()
    }

    #[inline]
    pub fn resize(&mut self, size: Size) {
        self.buffer.resize(size.area(), Default::default());
        self.size = size;
    }

    #[inline]
    pub fn clear_region(&mut self, region: Rect, style: Style) {
        let y_range =
            region.origin.y..cmp::min(region.origin.y + region.size.height, self.size.height);
        let x_range =
            region.origin.x..cmp::min(region.origin.x + region.size.width, self.size.width);
        for y in y_range {
            self.buffer[y * self.size.width + x_range.start..y * self.size.width + x_range.end]
                .iter_mut()
                .for_each(|textel| clear_textel(textel, style, " "));
        }
    }

    #[inline]
    pub fn clear(&mut self, style: Style) {
        self.buffer
            .iter_mut()
            .for_each(|textel| clear_textel(textel, style, " "))
    }

    #[inline]
    pub fn clear_with(&mut self, style: Style, content: &str) {
        self.buffer
            .iter_mut()
            .for_each(|textel| clear_textel(textel, style, content))
    }

    #[inline]
    pub fn draw_str(&mut self, x: usize, y: usize, style: Style, text: &str) -> usize {
        self.draw_graphemes(x, y, style, UnicodeSegmentation::graphemes(text, true))
    }

    #[inline]
    pub fn draw_graphemes(
        &mut self,
        x: usize,
        y: usize,
        style: Style,
        graphemes: impl Iterator<Item = impl Into<GraphemeCluster>>,
    ) -> usize {
        if y >= self.size.height || x >= self.size.width {
            return 0;
        }

        let initial_offset = y * self.size.width + x;
        let max_offset = cmp::min((y + 1) * self.size.width + x, self.buffer.len());
        let mut current_offset = initial_offset;

        for grapheme in graphemes {
            if current_offset >= max_offset {
                break;
            }

            let grapheme = grapheme.into();
            let grapheme_width = grapheme.width();
            if grapheme_width == 0 {
                continue;
            }

            self.buffer[current_offset] = Some(Textel { grapheme, style });

            let num_modified = cmp::min(grapheme_width, max_offset - current_offset);
            self.buffer[current_offset + 1..current_offset + num_modified]
                .iter_mut()
                .for_each(|textel| *textel = None);

            current_offset += num_modified;
        }

        current_offset - initial_offset
    }

    #[inline]
    pub fn copy_region(&mut self, source: &Self, region: Rect) {
        let y_range = cmp::min(region.origin.y, self.size.height)
            ..cmp::min(region.origin.y + source.size.height, self.size.height);
        let x_range = cmp::min(region.origin.x, self.size.width)
            ..cmp::min(region.origin.x + source.size.width, self.size.width);

        for y in y_range {
            self.buffer[y * self.size.width + x_range.start..y * self.size.width + x_range.end]
                .iter_mut()
                .zip(
                    source.buffer[(y - region.origin.y) * source.size.width
                        ..(y - region.origin.y) * source.size.width
                            + (x_range.end - region.origin.x)]
                        .iter(),
                )
                .for_each(|(textel, other)| *textel = other.clone());
        }
    }

    #[inline]
    pub fn textel(&self, x: usize, y: usize) -> &Option<Textel> {
        &self.buffer[y * self.size.width + x]
    }

    #[inline]
    pub fn textel_mut(&mut self, x: usize, y: usize) -> &mut Option<Textel> {
        &mut self.buffer[y * self.size.width + x]
    }
}

impl std::fmt::Display for Canvas {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        writeln!(
            formatter,
            "[Canvas {}x{}]",
            self.size.width, self.size.height
        )?;

        for row in self.buffer.chunks(self.size.width) {
            for textel in row.iter() {
                write!(
                    formatter,
                    "[{:2}]",
                    textel
                        .as_ref()
                        .map(|textel| textel.grapheme.as_str())
                        .unwrap_or("")
                )?;
            }
            writeln!(formatter)?;
        }

        Ok(())
    }
}

/// Specifies how content should be styled. This represents a subset of the ANSI
/// available styles which is widely supported by terminal emulators.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Style {
    pub background: Background,
    pub foreground: Foreground,
    pub bold: bool,
    pub underline: bool,
}

impl Style {
    /// Default style, white on black. This function exists as
    /// `Default::default()` is not const.
    pub const fn default() -> Self {
        Style::normal(Colour::black(), Colour::white())
    }

    #[inline]
    pub const fn normal(background: Background, foreground: Foreground) -> Self {
        Self {
            background,
            foreground,
            bold: false,
            underline: false,
        }
    }

    #[inline]
    pub const fn bold(background: Background, foreground: Foreground) -> Self {
        Self {
            background,
            foreground,
            bold: true,
            underline: false,
        }
    }

    #[inline]
    pub const fn underline(background: Background, foreground: Foreground) -> Self {
        Self {
            background,
            foreground,
            bold: false,
            underline: true,
        }
    }

    #[inline]
    pub const fn same_colour(colour: Colour) -> Self {
        Self {
            background: colour,
            foreground: colour,
            bold: false,
            underline: false,
        }
    }

    #[inline]
    pub const fn invert(self) -> Self {
        Self {
            background: self.foreground,
            foreground: self.background,
            bold: self.bold,
            underline: self.underline,
        }
    }
}

impl Default for Style {
    #[inline]
    fn default() -> Self {
        Self::default()
    }
}

/// An RGB encoded colour, 1-byte per channel.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Colour {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
}

impl Colour {
    /// Creates a colour from the provided RGB values.
    #[inline]
    pub const fn rgb(red: u8, green: u8, blue: u8) -> Self {
        Self { red, green, blue }
    }

    /// Returns black.
    #[inline]
    pub const fn black() -> Self {
        Self {
            red: 0,
            green: 0,
            blue: 0,
        }
    }

    /// Returns white.
    #[inline]
    pub const fn white() -> Self {
        Self {
            red: 255,
            green: 255,
            blue: 255,
        }
    }
}

/// Type alias for background colours.
pub type Background = Colour;

/// Type alias for foreground colours.
pub type Foreground = Colour;

#[inline]
fn clear_textel(textel: &mut Option<Textel>, style: Style, value: &str) {
    match *textel {
        Some(Textel {
            style: ref mut textel_style,
            ref mut grapheme,
        }) => {
            *textel_style = style;
            grapheme.clear();
            grapheme.push_str(value);
        }
        _ => {
            *textel = Some(Textel {
                style,
                grapheme: " ".into(),
            });
        }
    }
}

/// Wraps a [`Canvas`](terminal/struct.Canvas.html) and exposes a grid of square
/// "pixels". The size of the grid `(2 * height, width)` of the dimensions of the
/// wrapped canvas. This is implemented using Unicode's upper half block
/// character.
pub struct SquarePixelGrid {
    canvas: Canvas,
}

impl SquarePixelGrid {
    pub fn new(size: Size) -> Self {
        assert!(size.height % 2 == 0);
        let mut canvas = Canvas::new(Size::new(size.width, size.height / 2));
        canvas.clear_with(Default::default(), UPPER_HALF_BLOCK);
        Self { canvas }
    }

    pub fn from_available(size: Size) -> Self {
        let mut canvas = Canvas::new(Size::new(size.width, size.height));
        canvas.clear_with(Default::default(), UPPER_HALF_BLOCK);
        Self { canvas }
    }

    /// Returns the size of this square pixel grid. The grid has the same width
    /// as the wrapped canvas and twice the height.
    #[inline]
    pub fn size(&self) -> Size {
        let canvas_size = self.canvas.size();
        Size::new(canvas_size.width, canvas_size.height * 2)
    }

    #[inline]
    pub fn draw(&mut self, position: Position, colour: Colour) {
        let textel = self
            .canvas
            .textel_mut(position.x, position.y / 2)
            .as_mut()
            .expect("No textels should be uninitialised");
        if position.y % 2 == 0 {
            textel.style.foreground = colour;
        } else {
            textel.style.background = colour;
        }
    }

    #[inline]
    pub fn into_canvas(self) -> Canvas {
        self.canvas
    }
}

const UPPER_HALF_BLOCK: &str = "";

#[cfg(test)]
mod tests {
    use super::{GraphemeCluster, Style, Textel};

    #[test]
    fn size_of_style() {
        eprintln!(
            "std::mem::size_of::<Style>() == {}",
            std::mem::size_of::<Style>()
        );
        eprintln!(
            "std::mem::size_of::<Option<Textel>>() == {}",
            std::mem::size_of::<Option<Textel>>()
        );
        eprintln!(
            "std::mem::size_of::<GraphemeCluster>() == {}",
            std::mem::size_of::<GraphemeCluster>()
        );
        eprintln!(
            "std::mem::size_of::<Option<GraphemeCluster>>() == {}",
            std::mem::size_of::<Option<GraphemeCluster>>()
        );
    }
}