endbasic-std 0.14.0

The EndBASIC programming language - standard library
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
// EndBASIC
// Copyright 2024 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Support to implement graphical consoles.

use crate::sound::{AudioOps, Tone};

use super::{
    AnsiColor, CharsXY, ClearType, Console, Key, LineBuffer, PixelsXY, RGB, SizeInPixels,
    ansi_color_to_rgb, drawing, remove_control_chars,
};
use async_trait::async_trait;
use std::convert::TryFrom;
use std::io;

/// Default foreground color, used at console creation time and when requesting the default color
/// via the `COLOR` command.
const DEFAULT_FG_COLOR: u8 = AnsiColor::White as u8;

/// Default background color, used at console creation time and when requesting the default color
/// via the `COLOR` command.
const DEFAULT_BG_COLOR: u8 = AnsiColor::Black as u8;

/// Conversion between types with silent value clamping.
pub trait ClampedInto<T> {
    /// Converts self into `T` capping values at `T`'s maximum or minimum boundaries.
    fn clamped_into(self) -> T;
}

impl ClampedInto<usize> for i16 {
    fn clamped_into(self) -> usize {
        if self < 0 { 0 } else { self as usize }
    }
}

impl ClampedInto<i16> for u16 {
    fn clamped_into(self) -> i16 {
        if self > u16::try_from(i16::MAX).unwrap() { i16::MAX } else { self as i16 }
    }
}

impl ClampedInto<i16> for i32 {
    fn clamped_into(self) -> i16 {
        if self > i32::from(i16::MAX) {
            i16::MAX
        } else if self < i32::from(i16::MIN) {
            i16::MIN
        } else {
            self as i16
        }
    }
}

impl ClampedInto<u16> for i32 {
    fn clamped_into(self) -> u16 {
        if self > i32::from(u16::MAX) {
            u16::MAX
        } else if self < 0 {
            0
        } else {
            self as u16
        }
    }
}

impl ClampedInto<u16> for u32 {
    fn clamped_into(self) -> u16 {
        if self > u32::from(u16::MAX) { u16::MAX } else { self as u16 }
    }
}

/// Multiplication of values into a narrower type with silent value clamping.
pub trait ClampedMul<T, O> {
    /// Multiplies self by `rhs` and clamps the result to fit in `O`.
    fn clamped_mul(self, rhs: T) -> O;
}

impl ClampedMul<u16, i16> for u16 {
    fn clamped_mul(self, rhs: u16) -> i16 {
        let product = u32::from(self) * u32::from(rhs);
        if product > i16::MAX as u32 { i16::MAX } else { product as i16 }
    }
}

impl ClampedMul<u16, u16> for u16 {
    fn clamped_mul(self, rhs: u16) -> u16 {
        let product = u32::from(self) * u32::from(rhs);
        if product > u16::MAX as u32 { u16::MAX } else { product as u16 }
    }
}

impl ClampedMul<u16, i32> for u16 {
    fn clamped_mul(self, rhs: u16) -> i32 {
        i32::from(self).checked_mul(i32::from(rhs)).unwrap_or(i32::MAX)
    }
}

impl ClampedMul<u16, u32> for u16 {
    fn clamped_mul(self, rhs: u16) -> u32 {
        u32::from(self).checked_mul(u32::from(rhs)).expect("Result must have fit")
    }
}

impl ClampedMul<usize, usize> for usize {
    fn clamped_mul(self, rhs: usize) -> usize {
        match self.checked_mul(rhs) {
            Some(v) => v,
            None => usize::MAX,
        }
    }
}

impl ClampedMul<SizeInPixels, PixelsXY> for CharsXY {
    fn clamped_mul(self, rhs: SizeInPixels) -> PixelsXY {
        PixelsXY { x: self.x.clamped_mul(rhs.width), y: self.y.clamped_mul(rhs.height) }
    }
}

/// Returns true if the polygon has at least one non-degenerate edge.
fn poly_points(points: &[PixelsXY]) -> bool {
    points.windows(2).any(|ps| ps[0] != ps[1])
        || (points.len() > 2 && points.first() != points.last())
}

/// Given two points, calculates the origin and size of the rectangle they define.
fn rect_points(x1y1: PixelsXY, x2y2: PixelsXY) -> Option<(PixelsXY, SizeInPixels)> {
    let (x1, x2) = if x1y1.x < x2y2.x { (x1y1.x, x2y2.x) } else { (x2y2.x, x1y1.x) };
    let (y1, y2) = if x1y1.y < x2y2.y { (x1y1.y, x2y2.y) } else { (x2y2.y, x1y1.y) };

    let width = {
        let width = i32::from(x2) - i32::from(x1);
        if cfg!(debug_assertions) {
            u32::try_from(width).expect("Width must have been non-negative")
        } else {
            width as u32
        }
    }
    .clamped_into();
    let height = {
        let height = i32::from(y2) - i32::from(y1);
        if cfg!(debug_assertions) {
            u32::try_from(height).expect("Height must have been non-negative")
        } else {
            height as u32
        }
    }
    .clamped_into();

    if width == 0 || height == 0 {
        None
    } else {
        Some((PixelsXY::new(x1, y1), SizeInPixels::new(width, height)))
    }
}

/// Returns true if the three points define a non-degenerate triangle.
fn tri_points(x1y1: PixelsXY, x2y2: PixelsXY, x3y3: PixelsXY) -> bool {
    let dx21 = i32::from(x2y2.x) - i32::from(x1y1.x);
    let dy21 = i32::from(x2y2.y) - i32::from(x1y1.y);
    let dx31 = i32::from(x3y3.x) - i32::from(x1y1.x);
    let dy31 = i32::from(x3y3.y) - i32::from(x1y1.y);
    i64::from(dx21) * i64::from(dy31) != i64::from(dy21) * i64::from(dx31)
}

/// Container for configuration information of the backing surface.
pub struct RasterInfo {
    /// Size of the console in pixels.
    pub size_pixels: SizeInPixels,

    /// Size of each character.
    pub glyph_size: SizeInPixels,

    /// Size of the console in characters.  This is derived from `size_pixels` and `glyph_size`.
    pub size_chars: CharsXY,
}

/// Primitive graphical console raster operations.
pub trait RasterOps {
    /// Type of the image data (raw pixels).
    type ID;

    /// Queries information about the backend.
    fn get_info(&self) -> RasterInfo;

    /// Sets the drawing color for subsequent operations.
    fn set_draw_color(&mut self, color: RGB);

    /// Clears the whole console with the given color.
    fn clear(&mut self) -> io::Result<()>;

    /// Sets whether automatic presentation of the canvas is enabled or not.
    ///
    /// Raster backends might need this when the device they talk to is very slow and they want to
    /// buffer data in main memory first.
    ///
    /// Does *NOT* present the canvas.
    fn set_sync(&mut self, _enabled: bool) {}

    /// Displays any buffered changes to the console.
    ///
    /// Should ignore any sync values that the backend might have cached via `set_sync`.
    fn present_canvas(&mut self) -> io::Result<()>;

    /// Returns the color number of the pixel at `xy` if it is in bounds and exactly mappable.
    fn peek_pixel(&self, xy: PixelsXY) -> io::Result<Option<u8>>;

    /// Reads the raw pixel data for the rectangular region specified by `xy` and `size`.
    fn read_pixels(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<Self::ID>;

    /// Restores the rectangular region stored in `data` at the `xy` coordinates.
    fn put_pixels(&mut self, xy: PixelsXY, data: &Self::ID) -> io::Result<()>;

    /// Moves the rectangular region specified by `x1y1` and `size` to `x2y2`.  The original region
    /// is erased with the current drawing color.
    fn move_pixels(&mut self, x1y1: PixelsXY, x2y2: PixelsXY, size: SizeInPixels)
    -> io::Result<()>;

    /// Writes `text` starting at `xy` with the current drawing color.
    fn write_text(&mut self, xy: PixelsXY, text: &str) -> io::Result<()>;

    /// Draws the outline of a circle at `center` with `radius` using the current drawing color.
    fn draw_circle(&mut self, center: PixelsXY, radius: u16) -> io::Result<()>;

    /// Draws a filled circle at `center` with `radius` using the current drawing color.
    fn draw_circle_filled(&mut self, center: PixelsXY, radius: u16) -> io::Result<()>;

    /// Draws a line from `x1y1` to `x2y2` using the current drawing color.
    fn draw_line(&mut self, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()>;

    /// Draws a single pixel at `xy` using the current drawing color.
    fn draw_pixel(&mut self, xy: PixelsXY) -> io::Result<()>;

    /// Draws the outline of a polygon using the current drawing color.
    fn draw_poly(&mut self, points: &[PixelsXY]) -> io::Result<()>;

    /// Draws a filled polygon using the current drawing color.
    fn draw_poly_filled(&mut self, points: &[PixelsXY]) -> io::Result<()>;

    /// Draws the outline of a rectangle from `x1y1` to `x2y2` using the current drawing color.
    fn draw_rect(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<()>;

    /// Draws a filled rectangle from `x1y1` to `x2y2` using the current drawing color.
    fn draw_rect_filled(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<()>;

    /// Draws the outline of a triangle using the current drawing color.
    fn draw_tri(&mut self, x1y1: PixelsXY, x2y2: PixelsXY, x3y3: PixelsXY) -> io::Result<()>;

    /// Draws a filled triangle using the current drawing color.
    fn draw_tri_filled(&mut self, x1y1: PixelsXY, x2y2: PixelsXY, x3y3: PixelsXY)
    -> io::Result<()>;
}

/// Primitive graphical console input operations.
#[async_trait(?Send)]
pub trait InputOps {
    /// Returns the next key press if any is available.
    async fn poll_key(&mut self) -> io::Result<Option<Key>>;

    /// Waits for and returns the next key press.
    async fn read_key(&mut self) -> io::Result<Key>;
}

/// Implementation of a console that renders to a backing surface.
pub struct GraphicsConsole<IO, RO, AO>
where
    RO: RasterOps,
{
    input_ops: IO,

    /// Operations to render to the console.
    raster_ops: RO,

    /// Operations to reproduce sound.
    audio_ops: AO,

    /// Size of the console in pixels.
    size_pixels: SizeInPixels,

    /// Size of each character.
    glyph_size: SizeInPixels,

    /// Size of the console in characters.  This is derived from `size_pixels` and `glyph_size`.
    size_chars: CharsXY,

    /// Location of the cursor.
    cursor_pos: CharsXY,

    /// Whether the cursor is visible or not.
    cursor_visible: bool,

    /// Raw pixels at the cursor position before the cursor was drawn.  Used to restore the previous
    /// contents when the cursor moves.
    cursor_backup: Option<RO::ID>,

    /// Default foreground color to use.
    default_fg_color: u8,

    /// Default background color to use.
    default_bg_color: u8,

    /// Current foreground color as exposed via `color` and `set_color`.
    ansi_fg_color: Option<u8>,

    /// Current background color as exposed via `color` and `set_color`.
    ansi_bg_color: Option<u8>,

    /// Current foreground color.  Used for text and graphical rendering.
    fg_color: RGB,

    /// Current background color.  Used to clear text.
    bg_color: RGB,

    /// State of the console right before entering the "alternate" console.
    #[allow(clippy::type_complexity)]
    alt_backup: Option<(RO::ID, CharsXY, Option<u8>, Option<u8>, RGB, RGB)>,

    /// Whether video syncing is enabled or not.
    sync_enabled: bool,
}

impl<IO, RO, AO> GraphicsConsole<IO, RO, AO>
where
    IO: InputOps,
    RO: RasterOps,
    AO: AudioOps,
{
    /// Initializes a new graphical console.
    pub fn new(
        input_ops: IO,
        raster_ops: RO,
        audio_ops: AO,
        default_fg_color: Option<u8>,
        default_bg_color: Option<u8>,
    ) -> io::Result<Self> {
        let info = raster_ops.get_info();

        let default_fg_color = default_fg_color.unwrap_or(DEFAULT_FG_COLOR);
        let default_bg_color = default_bg_color.unwrap_or(DEFAULT_BG_COLOR);

        let mut console = Self {
            input_ops,
            raster_ops,
            audio_ops,
            size_pixels: info.size_pixels,
            glyph_size: info.glyph_size,
            size_chars: info.size_chars,
            cursor_pos: CharsXY::default(),
            cursor_visible: true,
            cursor_backup: None,
            default_fg_color,
            default_bg_color,
            ansi_bg_color: None,
            ansi_fg_color: None,
            bg_color: ansi_color_to_rgb(default_bg_color),
            fg_color: ansi_color_to_rgb(default_fg_color),
            alt_backup: None,
            sync_enabled: true,
        };

        console.set_color(console.ansi_fg_color, console.ansi_bg_color)?;
        console.clear(ClearType::All)?;

        Ok(console)
    }

    /// Renders any buffered changes to the backing surface.
    fn present_canvas(&mut self) -> io::Result<()> {
        if self.sync_enabled { self.raster_ops.present_canvas() } else { Ok(()) }
    }

    /// Draws the cursor at the current position and saves the previous contents of the screen so
    /// that `clear_cursor` can restore them.
    ///
    /// Does not present the canvas.
    fn draw_cursor(&mut self) -> io::Result<()> {
        if !self.cursor_visible {
            return Ok(());
        }

        let x1y1 = self.cursor_pos.clamped_mul(self.glyph_size);

        assert!(self.cursor_backup.is_none());
        self.cursor_backup = Some(self.raster_ops.read_pixels(x1y1, self.glyph_size)?);

        // TODO(jmmv): It would be nice to draw the cursor with alpha blending so that the letters
        // under it are visible.  This was done before in the HTML canvas but was lost when I added
        // the GraphicsConsole abstraction.  Maybe all RGB colors should switch to RGBA.  Or maybe
        // we should special-case the cursor drawing.
        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_rect_filled(x1y1, self.glyph_size)
    }

    /// Clears the cursor at the current position by restoring the contents of the screen saved by
    /// an earlier call to `draw_cursor`.
    ///
    /// Does not present the canvas.
    fn clear_cursor(&mut self) -> io::Result<()> {
        if !self.cursor_visible || self.cursor_backup.is_none() {
            return Ok(());
        }

        let x1y1 = self.cursor_pos.clamped_mul(self.glyph_size);

        self.raster_ops.put_pixels(x1y1, self.cursor_backup.as_ref().unwrap())?;
        self.cursor_backup = None;
        Ok(())
    }

    /// Moves the cursor to beginning of the next line, scrolling the console if necessary.
    ///
    /// Does not clear nor draw the cursor.
    fn open_line(&mut self) -> io::Result<()> {
        if self.cursor_pos.y < self.size_chars.y - 1 {
            self.cursor_pos.x = 0;
            self.cursor_pos.y += 1;
            return Ok(());
        }

        let text_height: u16 = self.size_chars.y.clamped_mul(self.glyph_size.height);
        let x1y1 = PixelsXY::new(0, self.glyph_size.height.clamped_into());
        let x2y2 = PixelsXY::new(0, 0);
        let size = SizeInPixels::new(self.size_pixels.width, text_height - self.glyph_size.height);

        self.raster_ops.set_draw_color(self.bg_color);
        self.raster_ops.move_pixels(x1y1, x2y2, size)?;
        if text_height < self.size_pixels.height {
            let xy = PixelsXY::new(0, text_height.clamped_into());
            let size =
                SizeInPixels::new(self.size_pixels.width, self.size_pixels.height - text_height);
            self.raster_ops.draw_rect_filled(xy, size)?;
        }

        self.cursor_pos.x = 0;
        Ok(())
    }

    /// Renders the given text at the current cursor position, with wrapping and
    /// scrolling if necessary.
    fn raw_write_wrapped(&mut self, text: String) -> io::Result<()> {
        let mut line_buffer = LineBuffer::from(text);

        loop {
            let fit_chars = self.size_chars.x - self.cursor_pos.x;

            let remaining = line_buffer.split_off(usize::from(fit_chars));
            let len = match u16::try_from(line_buffer.len()) {
                Ok(len) => len,
                Err(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, "Text too long")),
            };

            if len > 0 {
                let xy = self.cursor_pos.clamped_mul(self.glyph_size);
                let size = SizeInPixels::new(
                    len.clamped_mul(self.glyph_size.width),
                    self.glyph_size.height,
                );

                self.raster_ops.set_draw_color(self.bg_color);
                self.raster_ops.draw_rect_filled(xy, size)?;

                self.raster_ops.set_draw_color(self.fg_color);
                self.raster_ops.write_text(xy, &line_buffer.into_inner())?;
                self.cursor_pos.x += len;
            }

            line_buffer = remaining;
            if line_buffer.is_empty() {
                break;
            } else {
                self.open_line()?;
            }
        }

        Ok(())
    }
}

#[async_trait(?Send)]
impl<IO, RO, AO> Console for GraphicsConsole<IO, RO, AO>
where
    IO: InputOps,
    RO: RasterOps,
    AO: AudioOps,
{
    fn clear(&mut self, how: ClearType) -> io::Result<()> {
        match how {
            ClearType::All => {
                self.raster_ops.set_draw_color(self.bg_color);
                self.raster_ops.clear()?;
                self.cursor_pos.y = 0;
                self.cursor_pos.x = 0;
                self.cursor_backup = None;
            }
            ClearType::CurrentLine => {
                self.clear_cursor()?;
                let xy = PixelsXY::new(0, self.cursor_pos.y.clamped_mul(self.glyph_size.height));
                let size = SizeInPixels::new(self.size_pixels.width, self.glyph_size.height);
                self.raster_ops.set_draw_color(self.bg_color);
                self.raster_ops.draw_rect_filled(xy, size)?;
                self.cursor_pos.x = 0;
            }
            ClearType::PreviousChar => {
                if self.cursor_pos.x > 0 {
                    self.clear_cursor()?;
                    let previous_pos = CharsXY::new(self.cursor_pos.x - 1, self.cursor_pos.y);
                    let origin = previous_pos.clamped_mul(self.glyph_size);
                    self.raster_ops.set_draw_color(self.bg_color);
                    self.raster_ops.draw_rect_filled(origin, self.glyph_size)?;
                    self.cursor_pos = previous_pos;
                }
            }
            ClearType::UntilNewLine => {
                self.clear_cursor()?;
                let pos = self.cursor_pos.clamped_mul(self.glyph_size);
                debug_assert!(pos.x >= 0, "Inputs to pos are unsigned");
                debug_assert!(pos.y >= 0, "Inputs to pos are unsigned");
                let size = SizeInPixels::new(
                    (i32::from(self.size_pixels.width) - i32::from(pos.x)).clamped_into(),
                    self.glyph_size.height,
                );
                self.raster_ops.set_draw_color(self.bg_color);
                self.raster_ops.draw_rect_filled(pos, size)?;
            }
        }
        self.draw_cursor()?;
        self.present_canvas()
    }

    fn color(&self) -> (Option<u8>, Option<u8>) {
        (self.ansi_fg_color, self.ansi_bg_color)
    }

    fn set_color(&mut self, fg: Option<u8>, bg: Option<u8>) -> io::Result<()> {
        self.ansi_fg_color = fg;
        self.fg_color = ansi_color_to_rgb(fg.unwrap_or(self.default_fg_color));
        self.ansi_bg_color = bg;
        self.bg_color = ansi_color_to_rgb(bg.unwrap_or(self.default_bg_color));
        Ok(())
    }

    fn enter_alt(&mut self) -> io::Result<()> {
        if self.alt_backup.is_some() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Cannot nest alternate screens",
            ));
        }

        let pixels = self.raster_ops.read_pixels(PixelsXY::new(0, 0), self.size_pixels)?;
        self.alt_backup = Some((
            pixels,
            self.cursor_pos,
            self.ansi_fg_color,
            self.ansi_bg_color,
            self.fg_color,
            self.bg_color,
        ));

        self.clear(ClearType::All)
    }

    fn hide_cursor(&mut self) -> io::Result<()> {
        self.clear_cursor()?;
        self.cursor_visible = false;
        self.present_canvas()
    }

    fn is_interactive(&self) -> bool {
        true
    }

    fn leave_alt(&mut self) -> io::Result<()> {
        let (pixels, cursor_pos, ansi_fg_color, ansi_bg_color, fg_color, bg_color) =
            match self.alt_backup.take() {
                Some(t) => t,
                None => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "Cannot leave alternate screen; not entered",
                    ));
                }
            };

        self.clear_cursor()?;

        self.raster_ops.put_pixels(PixelsXY::new(0, 0), &pixels)?;

        self.cursor_pos = cursor_pos;
        self.ansi_fg_color = ansi_fg_color;
        self.ansi_bg_color = ansi_bg_color;
        self.fg_color = fg_color;
        self.bg_color = bg_color;
        self.draw_cursor()?;
        self.present_canvas()?;

        debug_assert!(self.alt_backup.is_none());
        Ok(())
    }

    fn locate(&mut self, pos: CharsXY) -> io::Result<()> {
        debug_assert!(pos.x < self.size_chars.x);
        debug_assert!(pos.y < self.size_chars.y);

        let previous = self.set_sync(false)?;
        self.clear_cursor()?;
        self.cursor_pos = pos;
        self.draw_cursor()?;
        self.set_sync(previous)?;
        Ok(())
    }

    fn move_within_line(&mut self, off: i16) -> io::Result<()> {
        let previous = self.set_sync(false)?;
        self.clear_cursor()?;
        if off < 0 {
            self.cursor_pos.x -= -off as u16;
        } else {
            self.cursor_pos.x += off as u16;
        }
        self.draw_cursor()?;
        self.set_sync(previous)?;
        Ok(())
    }

    fn print(&mut self, text: &str) -> io::Result<()> {
        let text = remove_control_chars(text);

        let previous = self.set_sync(false)?;
        self.clear_cursor()?;
        self.raw_write_wrapped(text)?;
        self.open_line()?;
        self.draw_cursor()?;
        self.set_sync(previous)?;
        Ok(())
    }

    async fn poll_key(&mut self) -> io::Result<Option<Key>> {
        self.input_ops.poll_key().await
    }

    async fn read_key(&mut self) -> io::Result<Key> {
        self.input_ops.read_key().await
    }

    async fn play_tone(&mut self, tone: Tone) -> io::Result<()> {
        self.audio_ops.play_tone(tone).await
    }

    fn show_cursor(&mut self) -> io::Result<()> {
        if !self.cursor_visible {
            self.cursor_visible = true;
            if let Err(e) = self.draw_cursor() {
                self.cursor_visible = false;
                return Err(e);
            }
        }
        self.present_canvas()
    }

    fn size_chars(&self) -> io::Result<CharsXY> {
        Ok(self.size_chars)
    }

    fn size_pixels(&self) -> io::Result<SizeInPixels> {
        Ok(self.size_pixels)
    }

    fn glyph_size(&self) -> io::Result<SizeInPixels> {
        Ok(self.glyph_size)
    }

    fn write(&mut self, text: &str) -> io::Result<()> {
        let text = remove_control_chars(text);

        let previous = self.set_sync(false)?;
        self.clear_cursor()?;
        self.raw_write_wrapped(text)?;
        self.draw_cursor()?;
        self.set_sync(previous)?;
        Ok(())
    }

    fn bucket_fill(&mut self, xy: PixelsXY) -> io::Result<()> {
        let fill_color = self.ansi_fg_color.unwrap_or(self.default_fg_color);
        self.raster_ops.set_draw_color(self.fg_color);
        drawing::bucket_fill(&mut self.raster_ops, xy, fill_color)?;
        self.present_canvas()
    }

    fn draw_circle(&mut self, center: PixelsXY, radius: u16) -> io::Result<()> {
        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_circle(center, radius)?;
        self.present_canvas()
    }

    fn draw_circle_filled(&mut self, center: PixelsXY, radius: u16) -> io::Result<()> {
        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_circle_filled(center, radius)?;
        self.present_canvas()
    }

    fn draw_line(&mut self, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()> {
        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_line(x1y1, x2y2)?;
        self.present_canvas()
    }

    fn draw_pixel(&mut self, xy: PixelsXY) -> io::Result<()> {
        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_pixel(xy)?;
        self.present_canvas()
    }

    fn draw_poly(&mut self, points: &[PixelsXY]) -> io::Result<()> {
        match points.len() {
            0 => Ok(()),
            1 => self.draw_pixel(points[0]),
            2 => self.draw_line(points[0], points[1]),
            3 => self.draw_tri(points[0], points[1], points[2]),
            _ => {
                if !poly_points(points) {
                    return Ok(());
                }

                self.raster_ops.set_draw_color(self.fg_color);
                self.raster_ops.draw_poly(points)?;
                self.present_canvas()
            }
        }
    }

    fn draw_poly_filled(&mut self, points: &[PixelsXY]) -> io::Result<()> {
        match points.len() {
            0 => Ok(()),
            1 => self.draw_pixel(points[0]),
            2 => self.draw_line(points[0], points[1]),
            3 => self.draw_tri_filled(points[0], points[1], points[2]),
            _ => {
                if !poly_points(points) {
                    return Ok(());
                }

                self.raster_ops.set_draw_color(self.fg_color);
                self.raster_ops.draw_poly_filled(points)?;
                self.present_canvas()
            }
        }
    }

    fn draw_rect(&mut self, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()> {
        self.raster_ops.set_draw_color(self.fg_color);
        match rect_points(x1y1, x2y2) {
            Some((xy, size)) => self.raster_ops.draw_rect(xy, size)?,
            None => self.raster_ops.draw_line(x1y1, x2y2)?,
        }
        self.present_canvas()
    }

    fn draw_rect_filled(&mut self, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()> {
        self.raster_ops.set_draw_color(self.fg_color);
        match rect_points(x1y1, x2y2) {
            Some((xy, size)) => self.raster_ops.draw_rect_filled(xy, size)?,
            None => self.raster_ops.draw_line(x1y1, x2y2)?,
        }
        self.present_canvas()
    }

    fn draw_tri(&mut self, x1y1: PixelsXY, x2y2: PixelsXY, x3y3: PixelsXY) -> io::Result<()> {
        if !tri_points(x1y1, x2y2, x3y3) {
            return Ok(());
        }

        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_tri(x1y1, x2y2, x3y3)?;
        self.present_canvas()
    }

    fn draw_tri_filled(
        &mut self,
        x1y1: PixelsXY,
        x2y2: PixelsXY,
        x3y3: PixelsXY,
    ) -> io::Result<()> {
        if !tri_points(x1y1, x2y2, x3y3) {
            return Ok(());
        }

        self.raster_ops.set_draw_color(self.fg_color);
        self.raster_ops.draw_tri_filled(x1y1, x2y2, x3y3)?;
        self.present_canvas()
    }

    fn peek_pixel(&self, xy: PixelsXY) -> io::Result<Option<u8>> {
        self.raster_ops.peek_pixel(xy)
    }

    fn sync_now(&mut self) -> io::Result<()> {
        if self.sync_enabled { Ok(()) } else { self.raster_ops.present_canvas() }
    }

    fn set_sync(&mut self, enabled: bool) -> io::Result<bool> {
        if !self.sync_enabled && enabled {
            self.raster_ops.present_canvas()?;
        }
        let previous = self.sync_enabled;
        self.sync_enabled = enabled;
        self.raster_ops.set_sync(enabled);
        Ok(previous)
    }
}

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

    #[test]
    fn test_clamped_into_u16_i16() {
        assert_eq!(0i16, 0u16.clamped_into());
        assert_eq!(10i16, 10u16.clamped_into());
        assert_eq!(i16::MAX - 1, u16::try_from(i16::MAX - 1).unwrap().clamped_into());
        assert_eq!(i16::MAX, u16::try_from(i16::MAX).unwrap().clamped_into());
        assert_eq!(i16::MAX, u16::MAX.clamped_into());
    }

    #[test]
    fn test_clamped_into_u16_i32() {
        assert_eq!(0i16, 0i32.clamped_into());
        assert_eq!(10i16, 10i32.clamped_into());
        assert_eq!(i16::MIN + 1, i32::from(i16::MIN + 1).clamped_into());
        assert_eq!(i16::MIN, i32::from(i16::MIN).clamped_into());
        assert_eq!(i16::MIN, i32::MIN.clamped_into());
        assert_eq!(i16::MAX - 1, i32::from(i16::MAX - 1).clamped_into());
        assert_eq!(i16::MAX, i32::from(i16::MAX).clamped_into());
        assert_eq!(i16::MAX, i32::MAX.clamped_into());
    }

    #[test]
    fn test_clamped_into_i32_u16() {
        assert_eq!(0u16, 0i32.clamped_into());
        assert_eq!(10u16, 10i32.clamped_into());
        assert_eq!(0u16, (-10i32).clamped_into());
        assert_eq!(u16::MAX - 1, i32::from(u16::MAX - 1).clamped_into());
        assert_eq!(u16::MAX, i32::from(u16::MAX).clamped_into());
        assert_eq!(u16::MAX, i32::MAX.clamped_into());
    }

    #[test]
    fn test_clamped_into_u32_u16() {
        assert_eq!(0u16, 0u32.clamped_into());
        assert_eq!(10u16, 10u32.clamped_into());
        assert_eq!(u16::MAX - 1, u32::from(u16::MAX - 1).clamped_into());
        assert_eq!(u16::MAX, u32::from(u16::MAX).clamped_into());
        assert_eq!(u16::MAX, u32::MAX.clamped_into());
    }

    #[test]
    fn test_clamped_mul_u16_u16_i16() {
        assert_eq!(0i16, ClampedMul::<u16, i16>::clamped_mul(0u16, 0u16));
        assert_eq!(55i16, ClampedMul::<u16, i16>::clamped_mul(11u16, 5u16));
        assert_eq!(i16::MAX, ClampedMul::<u16, i16>::clamped_mul(u16::MAX, u16::MAX));
    }

    #[test]
    fn test_clamped_mul_u16_u16_u16() {
        assert_eq!(0u16, ClampedMul::<u16, u16>::clamped_mul(0u16, 0u16));
        assert_eq!(55u16, ClampedMul::<u16, u16>::clamped_mul(11u16, 5u16));
        assert_eq!(u16::MAX, ClampedMul::<u16, u16>::clamped_mul(u16::MAX, u16::MAX));
    }

    #[test]
    fn test_clamped_mul_u16_u16_i32() {
        assert_eq!(0i32, ClampedMul::<u16, i32>::clamped_mul(0u16, 0u16));
        assert_eq!(55i32, ClampedMul::<u16, i32>::clamped_mul(11u16, 5u16));
        assert_eq!(i32::MAX, ClampedMul::<u16, i32>::clamped_mul(u16::MAX, u16::MAX));
    }

    #[test]
    fn test_clamped_mul_u16_u16_u32() {
        assert_eq!(0u32, ClampedMul::<u16, u32>::clamped_mul(0u16, 0u16));
        assert_eq!(55u32, ClampedMul::<u16, u32>::clamped_mul(11u16, 5u16));
        assert_eq!(4294836225u32, ClampedMul::<u16, u32>::clamped_mul(u16::MAX, u16::MAX));
    }

    #[test]
    fn test_clamped_mul_usize_usize_usize() {
        assert_eq!(0, ClampedMul::<usize, usize>::clamped_mul(0, 0));
        assert_eq!(55, ClampedMul::<usize, usize>::clamped_mul(11, 5));
        assert_eq!(usize::MAX, ClampedMul::<usize, usize>::clamped_mul(usize::MAX, usize::MAX));
    }

    #[test]
    fn test_clamped_mul_charsxy_sizeinpixels_pixelsxy() {
        assert_eq!(
            PixelsXY { x: 0, y: 0 },
            CharsXY { x: 0, y: 0 }.clamped_mul(SizeInPixels::new(1, 1))
        );
        assert_eq!(
            PixelsXY { x: 50, y: 120 },
            CharsXY { x: 10, y: 20 }.clamped_mul(SizeInPixels::new(5, 6))
        );
        assert_eq!(
            PixelsXY { x: i16::MAX, y: 120 },
            CharsXY { x: 10, y: 20 }.clamped_mul(SizeInPixels::new(50000, 6))
        );
        assert_eq!(
            PixelsXY { x: 50, y: i16::MAX },
            CharsXY { x: 10, y: 20 }.clamped_mul(SizeInPixels::new(5, 60000))
        );
        assert_eq!(
            PixelsXY { x: i16::MAX, y: i16::MAX },
            CharsXY { x: 10, y: 20 }.clamped_mul(SizeInPixels::new(50000, 60000))
        );
    }

    #[test]
    fn test_poly_points_ok() {
        assert!(poly_points(&[
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 20, y: 10 },
            PixelsXY { x: 15, y: 20 },
            PixelsXY { x: 10, y: 10 },
        ]));
    }

    #[test]
    fn test_poly_points_zeroes() {
        assert!(!poly_points(&[]));
        assert!(!poly_points(&[
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 10, y: 10 },
        ]));
    }

    #[test]
    fn test_rect_points_ok() {
        assert_eq!(
            Some((PixelsXY { x: 10, y: 20 }, SizeInPixels::new(100, 200))),
            rect_points(PixelsXY { x: 10, y: 20 }, PixelsXY { x: 110, y: 220 })
        );
        assert_eq!(
            Some((PixelsXY { x: 10, y: 20 }, SizeInPixels::new(100, 200))),
            rect_points(PixelsXY { x: 110, y: 20 }, PixelsXY { x: 10, y: 220 })
        );
        assert_eq!(
            Some((PixelsXY { x: 10, y: 20 }, SizeInPixels::new(100, 200))),
            rect_points(PixelsXY { x: 10, y: 220 }, PixelsXY { x: 110, y: 20 })
        );
        assert_eq!(
            Some((PixelsXY { x: 10, y: 20 }, SizeInPixels::new(100, 200))),
            rect_points(PixelsXY { x: 110, y: 220 }, PixelsXY { x: 10, y: 20 })
        );

        assert_eq!(
            Some((PixelsXY { x: -31000, y: -32000 }, SizeInPixels::new(31005, 32010))),
            rect_points(PixelsXY { x: 5, y: -32000 }, PixelsXY { x: -31000, y: 10 })
        );
        assert_eq!(
            Some((PixelsXY { x: 10, y: 5 }, SizeInPixels::new(30990, 31995))),
            rect_points(PixelsXY { x: 31000, y: 5 }, PixelsXY { x: 10, y: 32000 })
        );

        assert_eq!(
            Some((PixelsXY { x: -31000, y: -32000 }, SizeInPixels::new(62000, 64000))),
            rect_points(PixelsXY { x: -31000, y: -32000 }, PixelsXY { x: 31000, y: 32000 })
        );
        assert_eq!(
            Some((PixelsXY { x: -31000, y: -32000 }, SizeInPixels::new(62000, 64000))),
            rect_points(PixelsXY { x: 31000, y: 32000 }, PixelsXY { x: -31000, y: -32000 })
        );
    }

    #[test]
    fn test_rect_points_zeroes() {
        assert_eq!(None, rect_points(PixelsXY { x: 10, y: 10 }, PixelsXY { x: 10, y: 10 }));
        assert_eq!(None, rect_points(PixelsXY { x: 10, y: 10 }, PixelsXY { x: 10, y: 20 }));
        assert_eq!(None, rect_points(PixelsXY { x: 10, y: 10 }, PixelsXY { x: 20, y: 10 }));
    }

    #[test]
    fn test_tri_points_ok() {
        assert!(tri_points(
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 20, y: 10 },
            PixelsXY { x: 15, y: 20 }
        ));
        assert!(tri_points(
            PixelsXY { x: -31000, y: -32000 },
            PixelsXY { x: 31000, y: -32000 },
            PixelsXY { x: 0, y: 32000 }
        ));
    }

    #[test]
    fn test_tri_points_zeroes() {
        assert!(!tri_points(
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 10, y: 10 }
        ));
        assert!(!tri_points(
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 20, y: 20 },
            PixelsXY { x: 30, y: 30 }
        ));
        assert!(!tri_points(
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 10, y: 10 },
            PixelsXY { x: 20, y: 20 }
        ));
    }
}