console-display 0.1.0

A tui library that focuses primarily on providing high resolution display functionality in the console.
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
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
548
549
550
551
use num_traits::NumCast;

use crate::{
    console_display::{
        DynamicConsoleDisplay,
        StaticConsoleDisplay,
    },
    drawing::DynamicCanvas,
    pixel::{
        Pixel,
        character_pixel::{
            CharacterPixel,
            CharacterPixelData,
        },
    },
    widget::{
        DynamicWidget,
        StaticWidget,
        StringData,
    },
};

pub struct DynamicCharacterDisplay<CharacterPixel> {
    width: usize,
    height: usize,
    data: Box<[CharacterPixel]>,
}

impl DynamicCharacterDisplay<CharacterPixel> {
    /// Convenience method to build a blank display struct with specified dimensions
    ///
    /// # Panics
    ///
    /// This function panics if the data generated from the fill does not match the dimensions of the display.
    /// This should not happen and is subject to change in the future.
    #[must_use]
    pub fn new(width: usize, height: usize, fill: CharacterPixel) -> Self {
        let character_width = fill.width();
        let full_columns = width / character_width;
        let padding = width % character_width;
        let total_columns = full_columns + padding;

        let mut data: Vec<CharacterPixel> =
            vec![fill; total_columns * height];

        for i in 0..padding {
            for y in 0..height {
                let x = full_columns + i;
                data[x + y * total_columns] = CharacterPixel::build(' ', fill.foreground(), fill.background())
                    .expect("Invariant violated. Should not be a control character.");
            }
        }

        Self::build_from_data(width, height, &data).expect(
            "Invariant violated, data does not mach specified dimensions.",
        )
    }

    /// Builds a display struct from the given data with the specified dimensions.
    ///
    /// # Errors
    ///
    /// Returns an error when the length of the data does not match the dimensions of the display.
    pub fn build_from_data(
        width: usize,
        height: usize,
        data: &[CharacterPixel],
    ) -> Result<Self, String> {
        let mut new_data = Vec::with_capacity(data.len());
        let mut row_length = 0;
        for i in data {
            new_data.push(*i);
            for _ in 1..i.width() {
                new_data.push(i.make_copy());
            }
            row_length += i.width();
            if row_length > width && row_length - i.width() < width {
                return Err(
                    "Data is malformed, character spans multiple rows."
                        .to_string(),
                );
            }
            if row_length >= width {
                row_length = 0;
            }
        }

        if new_data.len() != width * height {
            return Err(format!(
                "Data does not match specified dimensions. Expected length of {}, got {}.",
                width * height,
                new_data.len()
            ));
        }

        Ok(Self {
            width,
            height,
            data: new_data.into_boxed_slice(),
        })
    }
}

impl DynamicConsoleDisplay<CharacterPixel>
    for DynamicCharacterDisplay<CharacterPixel>
{
    fn width(&self) -> usize {
        self.width
    }

    fn height(&self) -> usize {
        self.height
    }

    fn data(&self) -> &[CharacterPixel] {
        &self.data
    }

    fn data_mut(&mut self) -> &mut Box<[CharacterPixel]> {
        &mut self.data
    }
}

impl DynamicWidget for DynamicCharacterDisplay<CharacterPixel> {
    fn width_characters(&self) -> usize {
        self.width / CharacterPixel::WIDTH
    }

    fn height_characters(&self) -> usize {
        self.height / CharacterPixel::HEIGHT
    }

    fn string_data(&self) -> StringData {
        let mut result = Vec::new();
        let mut row = Vec::new();
        let mut width = 0;

        let mut iter = self.data.iter();
        while let Some(cell) = iter.next() {
            if width >= self.width_characters() {
                result.push(row);
                row = Vec::new();
                width = 0;
            }

            if cell.is_copy() {
                row.push(CharacterPixel::default().into());
                width += 1;
                continue;
            }

            row.push((*cell).into());
            width += cell.width();

            for _ in 1..cell.width() {
                iter.next();
            }
        }

        if !row.is_empty() {
            result.push(row);
        }

        StringData { data: result }
    }
}

impl<S: Pixel<U = CharacterPixelData>> DynamicCanvas<S>
    for DynamicCharacterDisplay<CharacterPixel>
{
    type A = usize;

    fn pixel(
        &self,
        x: Self::A,
        y: Self::A,
    ) -> Result<CharacterPixelData, String>
    where
        [(); S::WIDTH * S::HEIGHT]:,
    {
        let x: Option<usize> = NumCast::from(x);
        let y: Option<usize> = NumCast::from(y);
        if let Some(x) = x &&
            let Some(y) = y
        {
            if x >= self.width() || y >= self.height() {
                return Err(format!(
                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
                ));
            }

            let block_x: usize = x / S::WIDTH;
            let block_y: usize = y / S::HEIGHT;
            let offset_x: usize = x % S::WIDTH;
            let offset_y: usize = y % S::HEIGHT;

            let pixel =
                &self.data()[block_x + block_y * self.width_characters()];

            Ok(pixel
                .subpixel(offset_x, offset_y)
                .expect("Offset should be 0 or 1."))
        }
        else {
            Err("Coordinates could not be converted to usize.".to_string())
        }
    }

    fn set_pixel(
        &mut self,
        x: Self::A,
        y: Self::A,
        value: S::U,
    ) -> Result<(), String>
    where
        [(); S::WIDTH * S::HEIGHT]:,
    {
        let x: Option<usize> = NumCast::from(x);
        let y: Option<usize> = NumCast::from(y);
        if let Some(x) = x &&
            let Some(y) = y
        {
            if x >= self.width() || y >= self.height() {
                return Err(format!(
                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
                ));
            }

            let block_x: usize = x / S::WIDTH;
            let block_y: usize = y / S::HEIGHT;
            let offset_x: usize = x % S::WIDTH;
            let offset_y: usize = y % S::HEIGHT;

            let width_characters = self.width_characters();
            let pixel =
                &mut self.data_mut()[block_x + block_y * width_characters];
            pixel
                .set_subpixel(offset_x, offset_y, value)
                .expect("Offset should be 0 or 1.");

            Ok(())
        }
        else {
            Err("Coordinates could not be converted to usize.".to_string())
        }
    }
}

#[derive(Clone)]
pub struct StaticCharacterDisplay<
    CharacterPixel,
    const WIDTH: usize,
    const HEIGHT: usize,
> {
    data: Box<[CharacterPixel]>,
}

impl<const WIDTH: usize, const HEIGHT: usize>
    StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
{
    /// Convenience method to build a blank display struct with specified dimensions
    ///
    /// # Panics
    ///
    /// This function panics if the data generated from the fill does not match the dimensions of the display.
    /// This should not happen and is subject to change in the future.
    #[must_use]
    pub fn new(fill: CharacterPixel) -> Self
    where
        [(); WIDTH * HEIGHT]:,
    {
        let character_width = fill.width();
        let full_columns = WIDTH / character_width;
        let padding = WIDTH % character_width;
        let total_columns = full_columns + padding;

        let mut data: Vec<CharacterPixel> =
            vec![fill; total_columns * HEIGHT];

        for i in 0..padding {
            for y in 0..HEIGHT {
                let x = full_columns + i;
                data[x + y * total_columns] = CharacterPixel::build(' ', fill.foreground(), fill.background())
                    .expect("Invariant violated. Should not be a control character.");
            }
        }

        Self::build_from_data(&data).expect(
            "Invariant violated, data does not mach specified dimensions.",
        )
    }

    /// Builds a display struct with the specified dimensions from the given data.
    ///
    /// # Errors
    /// Returns an error when the data length does not match the dimensions of the display.
    /// This also applies if double-width characters, like あ, are used and exceed the dimensions of the display.
    pub fn build_from_data(
        data: &[CharacterPixel],
    ) -> Result<Self, String> {
        let mut new_data = Vec::with_capacity(data.len());
        let mut row_length = 0;
        for i in data {
            new_data.push(*i);
            for _ in 1..i.width() {
                new_data.push(i.make_copy());
            }
            row_length += i.width();
            if row_length > WIDTH && row_length - i.width() < WIDTH {
                return Err(
                    "Data is malformed, character spans multiple rows."
                        .to_string(),
                );
            }
            if row_length >= WIDTH {
                row_length = 0;
            }
        }

        if new_data.len() != WIDTH * HEIGHT {
            return Err(format!(
                "Data does not match specified dimensions. Expected length of {}, got {}.",
                WIDTH * HEIGHT,
                new_data.len()
            ));
        }

        Ok(Self {
            data: new_data.into_boxed_slice(),
        })
    }
}

impl<const WIDTH: usize, const HEIGHT: usize>
    StaticConsoleDisplay<CharacterPixel>
    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
{
    const WIDTH: usize = WIDTH;

    const HEIGHT: usize = HEIGHT;
}

impl<const WIDTH: usize, const HEIGHT: usize>
    DynamicConsoleDisplay<CharacterPixel>
    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
{
    fn width(&self) -> usize {
        WIDTH
    }

    fn height(&self) -> usize {
        HEIGHT
    }

    fn data(&self) -> &[CharacterPixel] {
        &self.data
    }

    fn data_mut(&mut self) -> &mut Box<[CharacterPixel]> {
        &mut self.data
    }
}

impl<const WIDTH: usize, const HEIGHT: usize> DynamicWidget
    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
{
    fn width_characters(&self) -> usize {
        WIDTH
    }

    fn height_characters(&self) -> usize {
        HEIGHT
    }

    fn string_data(&self) -> StringData {
        let mut result = Vec::new();
        let mut row = Vec::new();
        let mut width = 0;

        let mut iter = self.data.iter();
        while let Some(cell) = iter.next() {
            if width >= Self::WIDTH_CHARACTERS {
                result.push(row);
                row = Vec::new();
                width = 0;
            }

            if cell.is_copy() {
                row.push(CharacterPixel::default().into());
                width += 1;
                continue;
            }

            row.push((*cell).into());
            width += cell.width();

            for _ in 1..cell.width() {
                iter.next();
            }
        }

        if !row.is_empty() {
            result.push(row);
        }

        StringData { data: result }
    }
}

impl<const WIDTH: usize, const HEIGHT: usize> const StaticWidget
    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
{
    const WIDTH_CHARACTERS: usize = WIDTH;

    const HEIGHT_CHARACTERS: usize = HEIGHT;
}

impl<const WIDTH: usize, const HEIGHT: usize> DynamicCanvas<CharacterPixel>
    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
{
    type A = usize;

    fn pixel(
        &self,
        x: Self::A,
        y: Self::A,
    ) -> Result<CharacterPixelData, String>
    where
        [(); CharacterPixel::WIDTH * CharacterPixel::HEIGHT]:,
    {
        let x: Option<usize> = NumCast::from(x);
        let y: Option<usize> = NumCast::from(y);
        if let Some(x) = x &&
            let Some(y) = y
        {
            if x >= self.width() || y >= self.height() {
                return Err(format!(
                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
                ));
            }

            let block_x: usize = x / CharacterPixel::WIDTH;
            let block_y: usize = y / CharacterPixel::HEIGHT;

            let pixel =
                &self.data()[block_x + block_y * self.width_characters()];

            Ok(pixel.subpixel(0, 0).expect("Offset should be 0."))
        }
        else {
            Err("Coordinates could not be converted to usize.".to_string())
        }
    }

    fn set_pixel(
        &mut self,
        x: Self::A,
        y: Self::A,
        value: CharacterPixelData,
    ) -> Result<(), String>
    where
        [(); CharacterPixel::WIDTH * CharacterPixel::HEIGHT]:,
    {
        let x: Option<usize> = NumCast::from(x);
        let y: Option<usize> = NumCast::from(y);
        if let Some(x) = x &&
            let Some(y) = y
        {
            if x >= self.width() || y >= self.height() {
                return Err(format!(
                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
                ));
            }

            let block_x: usize = x / CharacterPixel::WIDTH;
            let block_y: usize = y / CharacterPixel::HEIGHT;

            let width_characters = self.width_characters();
            let pixel =
                &mut self.data_mut()[block_x + block_y * width_characters];
            pixel
                .set_subpixel(0, 0, value)
                .expect("Offset should be 0.");

            Ok(())
        }
        else {
            Err("Coordinates could not be converted to usize.".to_string())
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::color::TerminalColor;

    use super::*;

    #[test]
    fn build_from_data_success() {
        let character_display = StaticCharacterDisplay::<
            CharacterPixel,
            1,
            1,
        >::build_from_data(&[
            CharacterPixel::build(
                ' ',
                TerminalColor::Default,
                TerminalColor::Default,
            )
            .unwrap(),
        ]);
        assert!(character_display.is_ok());
    }

    #[test]
    fn build_from_data_failure_dimensions() {
        let character_display = StaticCharacterDisplay::<
            CharacterPixel,
            8,
            10,
        >::build_from_data(&vec![
                    CharacterPixel::build(
                        ' ',
                        TerminalColor::Default,
                        TerminalColor::Default,
                    )
                    .unwrap();
                    8 * 10 - 1
                ]);
        assert!(character_display.is_err());
    }

    #[test]
    fn build_from_data_failure_fit() {
        let character_display = StaticCharacterDisplay::<
            CharacterPixel,
            9,
            10,
        >::build_from_data(&vec![
                    CharacterPixel::build(
                        'あ',
                        TerminalColor::Default,
                        TerminalColor::Default,
                    )
                    .unwrap();
                    9 * 10 / 2
                ]);
        assert!(character_display.is_err());
    }
}