endbasic-sdl 0.14.0

The EndBASIC programming language - SDL graphical 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
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
// EndBASIC
// Copyright 2022 Julio Merino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! Background thread that runs the SDL main loop and acts as the host for the console.
//!
//! All communication with this thread happens via channels to ensure all SDL operations are invoked
//! from a single thread.

use crate::string_error_to_io_error;
use async_trait::async_trait;
use endbasic_std::Signal;
use endbasic_std::console::drawing::{
    draw_circle, draw_circle_filled, draw_poly, draw_poly_filled, draw_text, draw_tri,
    draw_tri_filled,
};
use endbasic_std::console::graphics::{ClampedInto, ClampedMul, InputOps, RasterInfo, RasterOps};
use endbasic_std::console::{
    CharsXY, ClearType, Console, ConsoleHost, GraphicsConsole, Key, PixelsXY, RGB, Resolution,
    SizeInPixels, rgb_to_ansi_color,
};
use endbasic_std::gfx::lcd::fonts::Font;
use endbasic_std::sound::{NoopAudioOps, Tone, Waveform};
use sdl2::audio::{AudioQueue, AudioSpecDesired};
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, Mod};
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect::{Point, Rect};
use sdl2::render::{SurfaceCanvas, TextureCreator, TextureValueError, UpdateTextureError};
use sdl2::surface::{Surface, SurfaceContext};
use sdl2::video::{Window, WindowBuildError};
use sdl2::{EventPump, Sdl};
use std::cell::RefCell;
use std::convert::TryFrom;
use std::fmt::{self, Write};
use std::io;
#[cfg(any(test, feature = "testutils"))]
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender, SyncSender, TryRecvError};
use std::thread;
use std::time::Duration;

/// Sample rate to use for tone playback.
const AUDIO_SAMPLE_RATE: i32 = 44_100;

/// Raises the current app to the front.
#[cfg(target_os = "macos")]
fn activate_app() {
    use objc2::MainThreadMarker;
    use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy};

    let mtm = MainThreadMarker::new().expect("activate_app must be called from the main thread");
    let app = NSApplication::sharedApplication(mtm);
    let _ = app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
    app.activate();
}

/// Number of loop iterations to poll for requests or events before sleeping.
///
/// We do this to avoid pauses that might occur if the client is sending us consecutive requests
/// but for some reason the loop is faster and fails to notice them.
const LOOP_POLL_BUDGET: u16 = 10000;

/// Delay between loop iterations when the polling budget in `LOOP_POLL_BUDGET` is exceeded.
const LOOP_DELAY_MS: u64 = 1;

/// Converts a `fmt::Error` to an `io::Error`.
fn fmt_error_to_io_error(e: fmt::Error) -> io::Error {
    io::Error::other(e)
}

/// Converts a `TextureValueError` to an `io::Error`.
fn texture_value_error_to_io_error(e: TextureValueError) -> io::Error {
    let kind = match e {
        TextureValueError::HeightOverflows(_)
        | TextureValueError::WidthOverflows(_)
        | TextureValueError::WidthMustBeMultipleOfTwoForFormat(_, _) => io::ErrorKind::InvalidInput,
        TextureValueError::SdlError(_) => io::ErrorKind::Other,
    };
    io::Error::new(kind, e)
}

/// Converts an `UpdateTextureError` to an `io::Error`.
fn update_texture_error_to_io_error(e: UpdateTextureError) -> io::Error {
    let kind = match e {
        UpdateTextureError::HeightMustBeMultipleOfTwoForFormat(_, _)
        | UpdateTextureError::PitchMustBeMultipleOfTwoForFormat(_, _)
        | UpdateTextureError::PitchOverflows(_)
        | UpdateTextureError::WidthMustBeMultipleOfTwoForFormat(_, _)
        | UpdateTextureError::XMustBeMultipleOfTwoForFormat(_, _)
        | UpdateTextureError::YMustBeMultipleOfTwoForFormat(_, _) => io::ErrorKind::InvalidInput,
        UpdateTextureError::SdlError(_) => io::ErrorKind::Other,
    };
    io::Error::new(kind, e)
}

/// Converts a `WindowBuildError` to an `io::Error`.
fn window_build_error_to_io_error(e: WindowBuildError) -> io::Error {
    let kind = match e {
        WindowBuildError::HeightOverflows(_) | WindowBuildError::WidthOverflows(_) => {
            io::ErrorKind::InvalidInput
        }
        WindowBuildError::InvalidTitle(_) => panic!("Hardcoded window title is invalid"),
        WindowBuildError::SdlError(_) => io::ErrorKind::Other,
    };
    io::Error::new(kind, e)
}

/// Constructs an SDL `Point` from a `PixelsXY`.
fn point_xy(xy: PixelsXY) -> Point {
    Point::new(i32::from(xy.x), i32::from(xy.y))
}

/// Constructs an SDL `Rect` from a `PixelsXY` `origin` and a `PixelsSize` `size`.
fn rect_origin_size(origin: PixelsXY, size: SizeInPixels) -> Rect {
    Rect::new(
        i32::from(origin.x),
        i32::from(origin.y),
        u32::from(size.width),
        u32::from(size.height),
    )
}

/// Returns the logical console size in pixels for explicit resolutions.
fn requested_size_pixels(resolution: Resolution) -> Option<SizeInPixels> {
    match resolution {
        Resolution::FullScreen(size) | Resolution::Windowed(size) => {
            Some(SizeInPixels::new(size.0.get().clamped_into(), size.1.get().clamped_into()))
        }
        Resolution::FullScreenDesktop => None,
    }
}

/// Converts our own `RGB` type to an SDL `Color`.
fn rgb_to_color(rgb: RGB) -> Color {
    Color::RGB(rgb.0, rgb.1, rgb.2)
}

/// Given an SDL `event`, converts it to a `Key` event if it is a key press; otherwise, returns
/// `None` for unknown events.
fn parse_event(event: Event) -> Option<Key> {
    let ctrl_mods = Mod::LCTRLMOD | Mod::RCTRLMOD;

    match event {
        Event::Quit { .. } => {
            // TODO(jmmv): This isn't really a key so we should be handling it in some other way.
            // For now, we recognize it here so that closing the window causes the interpreter to
            // exit... but that only works when the interpreter is waiting for input (which means
            // that this also confuses INKEY).
            Some(Key::EofOrDelete)
        }

        Event::KeyDown { keycode: Some(keycode), keymod, .. } => match keycode {
            Keycode::A if keymod.intersects(ctrl_mods) => Some(Key::Home),
            Keycode::B if keymod.intersects(ctrl_mods) => Some(Key::ArrowLeft),
            Keycode::C if keymod.intersects(ctrl_mods) => Some(Key::Interrupt),
            Keycode::D if keymod.intersects(ctrl_mods) => Some(Key::EofOrDelete),
            Keycode::E if keymod.intersects(ctrl_mods) => Some(Key::End),
            Keycode::F if keymod.intersects(ctrl_mods) => Some(Key::ArrowRight),
            Keycode::J if keymod.intersects(ctrl_mods) => Some(Key::NewLine),
            Keycode::M if keymod.intersects(ctrl_mods) => Some(Key::NewLine),
            Keycode::N if keymod.intersects(ctrl_mods) => Some(Key::ArrowDown),
            Keycode::P if keymod.intersects(ctrl_mods) => Some(Key::ArrowUp),

            Keycode::Backspace => Some(Key::Backspace),
            Keycode::Delete => Some(Key::Delete),
            Keycode::End => Some(Key::End),
            Keycode::Escape => Some(Key::Escape),
            Keycode::Home => Some(Key::Home),
            Keycode::Return => Some(Key::NewLine),
            Keycode::Tab => Some(Key::Tab),

            Keycode::Down => Some(Key::ArrowDown),
            Keycode::Left => Some(Key::ArrowLeft),
            Keycode::Right => Some(Key::ArrowRight),
            Keycode::Up => Some(Key::ArrowUp),

            Keycode::PageDown => Some(Key::PageDown),
            Keycode::PageUp => Some(Key::PageUp),

            _ => None,
        },

        Event::TextInput { text, .. } => {
            let mut chars = text.chars();
            let first =
                chars.next().unwrap_or_else(|| panic!("Cannot handle TextInput event: {:?}", text));
            Some(Key::Char(first))
        }

        _ => None,
    }
}

/// Implementation of the EndBASIC console on top of an SDL2 window.
///
/// The current struct-based code is derived from how this used to be a direct implementation of
/// the `Console` trait and serves to keep track of all the state we need to maintain the console.
/// However, this is incomplete without the main driver loop in `run`, which waits for events and
/// manipulates the console.
struct Context {
    /// SDL2 library context.  Must remain alive for the lifetime of the console: if it is dropped
    /// early, all further SDL operations fail.
    #[cfg_attr(not(test), allow(unused))]
    sdl: Sdl,

    /// Monospaced font to use in the console.
    font: &'static Font,

    /// Event pump to read keyboard events from.
    event_pump: EventPump,

    /// Window that hosts the console.
    window: Window,

    /// Off-screen canvas in which to draw the console.  Use `present_canvas` to copy the contents
    /// of this surface onto the window.
    canvas: SurfaceCanvas<'static>,

    /// The pixel format used in the `canvas`; cached to avoid calls into SDL.
    pixel_format: PixelFormatEnum,

    /// The texture creator for the `canvas`; cached to avoid calls into SDL.
    texture_creator: TextureCreator<SurfaceContext<'static>>,

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

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

    /// Current draw color.  Used only to track if we need to update the context.
    draw_color: RGB,

    /// Audio queue for tone playback.
    ///
    /// This is lazily initialized because audio support may not be present (as we seen during CI
    /// runs on Windows).
    audio_device: Option<AudioQueue<i16>>,
}

impl Context {
    /// Initializes a new SDL console.
    ///
    /// The console is sized to `resolution` pixels and the font is set to `font`.
    ///
    /// There can only be one active `SdlConsole` at any given time given that this initializes and
    /// owns the SDL context.
    fn new(resolution: Resolution, font: &'static Font) -> io::Result<Self> {
        let sdl = sdl2::init().map_err(string_error_to_io_error)?;
        let event_pump = sdl.event_pump().map_err(string_error_to_io_error)?;
        let video = sdl.video().map_err(string_error_to_io_error)?;

        video.text_input().start();

        let mut title = format!("EndBASIC {}", env!("CARGO_PKG_VERSION"));
        let mut window = match resolution {
            Resolution::FullScreenDesktop => {
                let mut window = video.window(&title, 0, 0);
                window.fullscreen_desktop();
                window
            }
            Resolution::FullScreen(size) => {
                let mut window = video.window(&title, size.0.get(), size.1.get());
                window.fullscreen();
                window
            }
            Resolution::Windowed(size) => {
                let mut window = video.window(&title, size.0.get(), size.1.get());
                window.position_centered();
                window
            }
        }
        .build()
        .map_err(window_build_error_to_io_error)?;

        // macOS causes graphical apps started from the terminal to go into the background
        // (the end of the Command+Tab switcher), which is confusing and unexpected.  We have
        // to force the app to raise to the front.
        #[cfg(target_os = "macos")]
        activate_app();
        window.raise();

        let size_pixels = requested_size_pixels(resolution).unwrap_or_else(|| {
            let (width, height) = window.size();
            SizeInPixels::new(width.clamped_into(), height.clamped_into())
        });
        let size_chars = font.chars_in_area(size_pixels);

        write!(
            &mut title,
            " - {}x{} pixels, {}x{} chars",
            size_pixels.width, size_pixels.height, size_chars.x, size_chars.y
        )
        .map_err(fmt_error_to_io_error)?;
        window.set_title(&title).expect("There should have been no NULLs in the formatted title");

        let pixel_format = window.window_pixel_format();
        let surface =
            Surface::new(u32::from(size_pixels.width), u32::from(size_pixels.height), pixel_format)
                .map_err(string_error_to_io_error)?;
        let mut canvas = surface.into_canvas().map_err(string_error_to_io_error)?;
        let texture_creator = canvas.texture_creator();

        let draw_color = RGB::default();
        canvas.set_draw_color(rgb_to_color(draw_color));

        Ok(Self {
            sdl,
            font,
            event_pump,
            window,
            canvas,
            pixel_format,
            texture_creator,
            size_pixels,
            size_chars,
            draw_color,
            audio_device: None,
        })
    }

    /// Obtains the audio queue to use for tone playback.
    fn get_audio_device(&mut self) -> io::Result<&mut AudioQueue<i16>> {
        if self.audio_device.is_none() {
            let audio = self.sdl.audio().map_err(string_error_to_io_error)?;
            let desired_spec = AudioSpecDesired {
                freq: Some(AUDIO_SAMPLE_RATE),
                channels: Some(1),
                samples: None,
            };
            let audio_device = audio
                .open_queue::<i16, _>(None, &desired_spec)
                .map_err(string_error_to_io_error)?;
            self.audio_device = Some(audio_device);
        }

        Ok(self.audio_device.as_mut().expect("Audio device must have been initialized"))
    }

    /// Returns true if the point falls within the canvas bounds.
    fn contains_pixel(&self, xy: PixelsXY) -> bool {
        xy.x >= 0
            && xy.y >= 0
            && u16::try_from(xy.x).unwrap_or(u16::MAX) < self.size_pixels.width
            && u16::try_from(xy.y).unwrap_or(u16::MAX) < self.size_pixels.height
    }

    /// Reproduces `tone` using SDL's audio queue.
    fn play_tone(&mut self, tone: Tone) -> io::Result<()> {
        if tone.frequency_hz == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Tone frequency must be positive",
            ));
        }

        let sample_count = (tone.duration.as_secs_f64() * f64::from(AUDIO_SAMPLE_RATE))
            .round()
            .clamp(0.0, usize::MAX as f64) as usize;
        if sample_count == 0 {
            return Ok(());
        }

        let samples = match tone.waveform {
            Waveform::Square => {
                let half_period = f64::from(AUDIO_SAMPLE_RATE) / f64::from(tone.frequency_hz) / 2.0;
                let amplitude = i16::MAX / 4;
                let mut samples = Vec::with_capacity(sample_count);
                for i in 0..sample_count {
                    let sample = if (((i as f64) / half_period).floor() as u64).is_multiple_of(2) {
                        amplitude
                    } else {
                        -amplitude
                    };
                    samples.push(sample);
                }
                samples
            }
        };

        let audio_device = self.get_audio_device()?;
        audio_device.clear();
        audio_device.queue_audio(&samples).map_err(string_error_to_io_error)?;
        audio_device.resume();
        while audio_device.size() > 0 {
            thread::sleep(Duration::from_millis(1));
        }
        audio_device.pause();
        Ok(())
    }
}

impl RasterOps for Context {
    type ID = (Vec<u8>, SizeInPixels);

    fn get_info(&self) -> RasterInfo {
        RasterInfo {
            size_chars: self.size_chars,
            size_pixels: self.size_pixels,
            glyph_size: self.font.glyph_size.into(),
        }
    }

    fn set_draw_color(&mut self, color: RGB) {
        if self.draw_color != color {
            self.canvas.set_draw_color(rgb_to_color(color));
            self.draw_color = color;
        }
    }

    fn clear(&mut self) -> io::Result<()> {
        self.canvas.clear();
        Ok(())
    }

    fn present_canvas(&mut self) -> io::Result<()> {
        let mut window_surface =
            self.window.surface(&self.event_pump).map_err(string_error_to_io_error)?;
        self.canvas
            .surface()
            .blit_scaled(None, &mut window_surface, None)
            .map_err(string_error_to_io_error)?;
        window_surface.finish().map_err(string_error_to_io_error)
    }

    fn peek_pixel(&self, xy: PixelsXY) -> io::Result<Option<u8>> {
        if !self.contains_pixel(xy) {
            return Ok(None);
        }

        let rect = rect_origin_size(xy, SizeInPixels::new(1, 1));
        let data = self
            .canvas
            .read_pixels(rect, PixelFormatEnum::RGB24)
            .map_err(string_error_to_io_error)?;
        Ok(rgb_to_ansi_color((data[0], data[1], data[2])))
    }

    fn read_pixels(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<Self::ID> {
        let rect = rect_origin_size(xy, size);
        let data = match self.canvas.read_pixels(rect, self.pixel_format) {
            Ok(data) => data,
            Err(e) if e == "Can't read outside the current viewport" => {
                // The SDL read pixels operation intersects the requested rect with the viewport.
                // However, SDL2-compat does not like it when the two don't intersect at all.
                // Fake the response so that our SDL2 code remains compatible with SDL2-compat.
                vec![
                    0;
                    usize::from(size.width)
                        * usize::from(size.height)
                        * self.pixel_format.byte_size_per_pixel()
                ]
            }
            Err(e) => {
                return Err(string_error_to_io_error(e));
            }
        };
        Ok((data, size))
    }

    fn put_pixels(&mut self, xy: PixelsXY, (data, size): &Self::ID) -> io::Result<()> {
        let rect = rect_origin_size(xy, *size);
        let mut texture = self
            .texture_creator
            .create_texture_static(None, rect.width(), rect.height())
            .map_err(texture_value_error_to_io_error)?;
        let width = if cfg!(debug_assertions) {
            usize::try_from(rect.width()).expect("Width must fit in usize")
        } else {
            rect.width() as usize
        }
        .clamped_mul(self.pixel_format.byte_size_per_pixel());
        texture.update(None, data, width).map_err(update_texture_error_to_io_error)?;
        self.canvas.copy(&texture, None, rect).map_err(string_error_to_io_error)
    }

    fn move_pixels(
        &mut self,
        x1y1: PixelsXY,
        x2y2: PixelsXY,
        size: SizeInPixels,
    ) -> io::Result<()> {
        let shifted = {
            let src = self.canvas.surface();
            let mut temp = Surface::new(src.width(), src.height(), self.pixel_format)
                .map_err(string_error_to_io_error)?;
            let src_rect = rect_origin_size(x1y1, size);
            let dst_rect = rect_origin_size(x2y2, size);
            temp.fill_rect(src_rect, rgb_to_color(self.draw_color))
                .map_err(string_error_to_io_error)?;
            src.blit(src_rect, &mut temp, dst_rect).map_err(string_error_to_io_error)?;
            temp
        };
        shifted.blit(None, self.canvas.surface_mut(), None).map_err(string_error_to_io_error)?;
        Ok(())
    }

    fn write_text(&mut self, xy: PixelsXY, text: &str) -> io::Result<()> {
        draw_text(self, self.font, xy, text)
    }

    fn draw_circle(&mut self, center: PixelsXY, radius: u16) -> io::Result<()> {
        draw_circle(self, center, radius)
    }

    fn draw_circle_filled(&mut self, center: PixelsXY, radius: u16) -> io::Result<()> {
        draw_circle_filled(self, center, radius)
    }

    fn draw_line(&mut self, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()> {
        if x1y1 == x2y2 {
            // Paper over differences between platforms.  On Linux, this would paint a single dot,
            // but on Windows, it paints nothing.  For consistency with drawing a circle of radius
            // 0, and for consistency with the web interface, avoid painting anything here.
            return Ok(());
        }

        self.canvas.draw_line(point_xy(x1y1), point_xy(x2y2)).map_err(string_error_to_io_error)
    }

    fn draw_pixel(&mut self, xy: PixelsXY) -> io::Result<()> {
        self.canvas.draw_point(point_xy(xy)).map_err(string_error_to_io_error)
    }

    fn draw_poly(&mut self, points: &[PixelsXY]) -> io::Result<()> {
        draw_poly(self, points)
    }

    fn draw_poly_filled(&mut self, points: &[PixelsXY]) -> io::Result<()> {
        draw_poly_filled(self, points)
    }

    fn draw_rect(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<()> {
        let rect = rect_origin_size(xy, size);
        self.canvas.draw_rect(rect).map_err(string_error_to_io_error)
    }

    fn draw_rect_filled(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<()> {
        let rect = rect_origin_size(xy, size);
        self.canvas.fill_rect(rect).map_err(string_error_to_io_error)
    }

    fn draw_tri(&mut self, x1y1: PixelsXY, x2y2: PixelsXY, x3y3: PixelsXY) -> io::Result<()> {
        draw_tri(self, x1y1, x2y2, x3y3)
    }

    fn draw_tri_filled(
        &mut self,
        x1y1: PixelsXY,
        x2y2: PixelsXY,
        x3y3: PixelsXY,
    ) -> io::Result<()> {
        draw_tri_filled(self, x1y1, x2y2, x3y3)
    }
}

#[derive(Clone)]
struct SharedContext(Rc<RefCell<Context>>);

impl SharedContext {
    fn play_tone(&mut self, tone: Tone) -> io::Result<()> {
        (*self.0).borrow_mut().play_tone(tone)
    }

    fn poll_event(&mut self) -> Option<Event> {
        (*self.0).borrow_mut().event_pump.poll_event()
    }

    #[cfg(any(test, feature = "testutils"))]
    fn push_event(&mut self, ev: Event) -> io::Result<()> {
        let event_ss = (*self.0).borrow().sdl.event().map_err(string_error_to_io_error)?;
        event_ss.push_event(ev).map_err(string_error_to_io_error)
    }

    #[cfg(any(test, feature = "testutils"))]
    fn save_bmp(&self, path: &Path) -> io::Result<()> {
        let ctx = (*self.0).borrow_mut();
        let surface = ctx.canvas.surface();
        surface.save_bmp(path).map_err(string_error_to_io_error)
    }
}

impl RasterOps for SharedContext {
    type ID = (Vec<u8>, SizeInPixels);

    fn get_info(&self) -> RasterInfo {
        self.0.borrow().get_info()
    }

    fn set_draw_color(&mut self, color: RGB) {
        (*self.0).borrow_mut().set_draw_color(color)
    }

    fn clear(&mut self) -> io::Result<()> {
        (*self.0).borrow_mut().clear()
    }

    fn present_canvas(&mut self) -> io::Result<()> {
        (*self.0).borrow_mut().present_canvas()
    }

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

    fn read_pixels(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<Self::ID> {
        (*self.0).borrow_mut().read_pixels(xy, size)
    }

    fn put_pixels(&mut self, xy: PixelsXY, data: &Self::ID) -> io::Result<()> {
        (*self.0).borrow_mut().put_pixels(xy, data)
    }

    fn move_pixels(
        &mut self,
        x1y1: PixelsXY,
        x2y2: PixelsXY,
        size: SizeInPixels,
    ) -> io::Result<()> {
        (*self.0).borrow_mut().move_pixels(x1y1, x2y2, size)
    }

    fn write_text(&mut self, xy: PixelsXY, text: &str) -> io::Result<()> {
        (*self.0).borrow_mut().write_text(xy, text)
    }

    fn draw_circle(&mut self, center: PixelsXY, radius: u16) -> io::Result<()> {
        (*self.0).borrow_mut().draw_circle(center, radius)
    }

    fn draw_circle_filled(&mut self, center: PixelsXY, radius: u16) -> io::Result<()> {
        (*self.0).borrow_mut().draw_circle_filled(center, radius)
    }

    fn draw_line(&mut self, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()> {
        (*self.0).borrow_mut().draw_line(x1y1, x2y2)
    }

    fn draw_pixel(&mut self, xy: PixelsXY) -> io::Result<()> {
        (*self.0).borrow_mut().draw_pixel(xy)
    }

    fn draw_poly(&mut self, points: &[PixelsXY]) -> io::Result<()> {
        (*self.0).borrow_mut().draw_poly(points)
    }

    fn draw_poly_filled(&mut self, points: &[PixelsXY]) -> io::Result<()> {
        (*self.0).borrow_mut().draw_poly_filled(points)
    }

    fn draw_rect(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<()> {
        (*self.0).borrow_mut().draw_rect(xy, size)
    }

    fn draw_rect_filled(&mut self, xy: PixelsXY, size: SizeInPixels) -> io::Result<()> {
        (*self.0).borrow_mut().draw_rect_filled(xy, size)
    }

    fn draw_tri(&mut self, x1y1: PixelsXY, x2y2: PixelsXY, x3y3: PixelsXY) -> io::Result<()> {
        (*self.0).borrow_mut().draw_tri(x1y1, x2y2, x3y3)
    }

    fn draw_tri_filled(
        &mut self,
        x1y1: PixelsXY,
        x2y2: PixelsXY,
        x3y3: PixelsXY,
    ) -> io::Result<()> {
        (*self.0).borrow_mut().draw_tri_filled(x1y1, x2y2, x3y3)
    }
}

/// Representation of requests that the console host can handle.
pub(crate) enum Request {
    Exit,

    Clear(ClearType),
    SetColor(Option<u8>, Option<u8>),
    EnterAlt,
    HideCursor,
    LeaveAlt,
    Locate(CharsXY),
    MoveWithinLine(i16),
    Print(String),
    ShowCursor,
    SizeChars,
    GlyphSize,
    SizePixels,
    Write(String),
    BucketFill(PixelsXY),
    DrawCircle(PixelsXY, u16),
    DrawCircleFilled(PixelsXY, u16),
    DrawLine(PixelsXY, PixelsXY),
    DrawPixel(PixelsXY),
    DrawPoly(Vec<PixelsXY>),
    DrawPolyFilled(Vec<PixelsXY>),
    DrawRect(PixelsXY, PixelsXY),
    DrawRectFilled(PixelsXY, PixelsXY),
    DrawTri(PixelsXY, PixelsXY, PixelsXY),
    DrawTriFilled(PixelsXY, PixelsXY, PixelsXY),
    PeekPixel(PixelsXY),
    PlayTone(Tone),
    SyncNow,
    SetSync(bool),

    #[cfg(any(test, feature = "testutils"))]
    PushEvent(Event),
    #[cfg(any(test, feature = "testutils"))]
    SaveBmp(PathBuf),
}

/// Representation of responses that the host sends back to the client.
#[derive(Debug)]
pub(crate) enum Response {
    Empty(io::Result<()>),
    PeekPixel(io::Result<Option<u8>>),
    SizeChars(CharsXY),
    GlyphSize(SizeInPixels),
    SizePixels(SizeInPixels),
    SetSync(io::Result<bool>),
}

/// Implementation of `InputOps` that should never be used.
// TODO(jmmv): This is necessary because the host-level console implementation requires these
// methods to be present but the input operations are handled in the client-side console.  This
// might mean we need a better design.
struct NoopInputOps {}

#[async_trait(?Send)]
impl InputOps for NoopInputOps {
    async fn poll_key(&mut self) -> io::Result<Option<Key>> {
        unreachable!();
    }

    async fn read_key(&mut self) -> io::Result<Key> {
        unreachable!();
    }
}

/// Runs the main graphics loop.
#[allow(clippy::too_many_arguments)]
pub(crate) fn run(
    resolution: Resolution,
    default_fg_color: Option<u8>,
    default_bg_color: Option<u8>,
    font: &'static Font,
    request_rx: Receiver<Request>,
    response_tx: SyncSender<Response>,
    on_key_tx: Sender<Key>,
    signals_tx: async_channel::Sender<Signal>,
) {
    let ctx = match Context::new(resolution, font) {
        Ok(ctx) => ctx,
        Err(e) => {
            response_tx.send(Response::Empty(Err(e))).expect("Channel must be alive");
            return;
        }
    };

    let info = ctx.get_info();
    let mut ctx = SharedContext(Rc::from(RefCell::from(ctx)));

    let input = NoopInputOps {};
    let mut console =
        GraphicsConsole::new(input, ctx.clone(), NoopAudioOps, default_fg_color, default_bg_color)
            .expect("Console initialization must succeed");

    response_tx.send(Response::Empty(Ok(()))).expect("Channel must be alive");

    let mut budget = LOOP_POLL_BUDGET;
    loop {
        let mut did_something = false;

        match request_rx.try_recv() {
            Ok(request) => {
                let response = match request {
                    Request::Exit => break,

                    Request::Clear(how) => Response::Empty(console.clear(how)),
                    Request::SetColor(fg, bg) => Response::Empty(console.set_color(fg, bg)),
                    Request::EnterAlt => Response::Empty(console.enter_alt()),
                    Request::HideCursor => Response::Empty(console.hide_cursor()),
                    Request::LeaveAlt => Response::Empty(console.leave_alt()),
                    Request::Locate(pos) => Response::Empty(console.locate(pos)),
                    Request::MoveWithinLine(off) => Response::Empty(console.move_within_line(off)),
                    Request::Print(text) => Response::Empty(console.print(&text)),
                    Request::ShowCursor => Response::Empty(console.show_cursor()),
                    Request::GlyphSize => Response::GlyphSize(info.glyph_size),
                    Request::SizeChars => Response::SizeChars(info.size_chars),
                    Request::SizePixels => Response::SizePixels(info.size_pixels),
                    Request::Write(text) => Response::Empty(console.write(&text)),
                    Request::BucketFill(xy) => Response::Empty(console.bucket_fill(xy)),
                    Request::DrawCircle(center, radius) => {
                        Response::Empty(console.draw_circle(center, radius))
                    }
                    Request::DrawCircleFilled(center, radius) => {
                        Response::Empty(console.draw_circle_filled(center, radius))
                    }
                    Request::DrawLine(x1y1, x2y2) => Response::Empty(console.draw_line(x1y1, x2y2)),
                    Request::DrawPixel(xy) => Response::Empty(console.draw_pixel(xy)),
                    Request::DrawPoly(points) => Response::Empty(console.draw_poly(&points)),
                    Request::DrawPolyFilled(points) => {
                        Response::Empty(console.draw_poly_filled(&points))
                    }
                    Request::DrawRect(x1y1, x2y2) => Response::Empty(console.draw_rect(x1y1, x2y2)),
                    Request::DrawRectFilled(x1y1, x2y2) => {
                        Response::Empty(console.draw_rect_filled(x1y1, x2y2))
                    }
                    Request::DrawTri(x1y1, x2y2, x3y3) => {
                        Response::Empty(console.draw_tri(x1y1, x2y2, x3y3))
                    }
                    Request::DrawTriFilled(x1y1, x2y2, x3y3) => {
                        Response::Empty(console.draw_tri_filled(x1y1, x2y2, x3y3))
                    }
                    Request::PeekPixel(xy) => Response::PeekPixel(console.peek_pixel(xy)),
                    Request::PlayTone(tone) => Response::Empty(ctx.play_tone(tone)),
                    Request::SyncNow => Response::Empty(console.sync_now()),
                    Request::SetSync(enabled) => Response::SetSync(console.set_sync(enabled)),

                    #[cfg(any(test, feature = "testutils"))]
                    Request::PushEvent(ev) => Response::Empty(ctx.push_event(ev)),

                    #[cfg(any(test, feature = "testutils"))]
                    Request::SaveBmp(path) => Response::Empty(ctx.save_bmp(&path)),
                };

                // TODO(jmmv): This is inefficient.  Most of the operations above could probably
                // benefit from _not_ returning a response at all, being asynchronous from the
                // client perspective -- but the code is like this right now because it is adapted
                // from a previous version that was synchronous.
                response_tx.send(response).expect("Channel must be alive");

                did_something = true;
            }
            Err(TryRecvError::Empty) => (),
            Err(TryRecvError::Disconnected) => panic!("Channel must be alive"),
        }

        if let Some(event) = ctx.poll_event() {
            if let Some(key) = parse_event(event) {
                if key == Key::Interrupt {
                    // signals_tx is an async channel because that's what the execution engine
                    // needs.  This means that we cannot use a regular "send" here because we
                    // would need to await for it, which is a no-no because we are not in an
                    // async context.  Using "try_send" should be sufficient though given that
                    // the channel we use is not bounded.
                    signals_tx.try_send(Signal::Break).expect("Channel must be alive and not full")
                }

                on_key_tx.send(key).expect("Channel must be alive");
            }

            did_something = true;
        }

        if did_something {
            budget = LOOP_POLL_BUDGET;
        } else {
            if budget > 0 {
                budget -= 1;
            } else {
                thread::sleep(Duration::from_millis(LOOP_DELAY_MS));
            }
        }
    }
}

/// Host loop for an SDL-backed console.
pub(crate) struct SdlConsoleHost {
    pub(crate) resolution: Resolution,
    pub(crate) default_fg_color: Option<u8>,
    pub(crate) default_bg_color: Option<u8>,
    pub(crate) font: &'static Font,
    pub(crate) request_rx: Receiver<Request>,
    pub(crate) response_tx: SyncSender<Response>,
    pub(crate) on_key_tx: Sender<Key>,
    pub(crate) signals_tx: async_channel::Sender<Signal>,
}

impl ConsoleHost for SdlConsoleHost {
    fn run(self: Box<Self>) -> io::Result<()> {
        // TODO(jmmv): The top-level run function should be inlined here but it was kept separate
        // during the initial introduction of SdlConsoleHost to keep the diff clean.
        run(
            self.resolution,
            self.default_fg_color,
            self.default_bg_color,
            self.font,
            self.request_rx,
            self.response_tx,
            self.on_key_tx,
            self.signals_tx,
        );
        Ok(())
    }
}

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

    /// Creates an `Event::KeyDown` struct for `keycode` with `keymod`.
    fn key_down(keycode: Keycode, keymod: Mod) -> Event {
        Event::KeyDown {
            keycode: Some(keycode),
            scancode: None,
            keymod,
            timestamp: 0,
            repeat: false,
            window_id: 0,
        }
    }

    #[test]
    fn test_parse_event_ctrl_keycodes_with_extra_modifiers() {
        assert_eq!(
            Some(Key::Interrupt),
            parse_event(key_down(Keycode::C, Mod::LCTRLMOD | Mod::NUMMOD))
        );
        assert_eq!(
            Some(Key::EofOrDelete),
            parse_event(key_down(Keycode::D, Mod::RCTRLMOD | Mod::CAPSMOD))
        );
        assert_eq!(Some(Key::Delete), parse_event(key_down(Keycode::Delete, Mod::NOMOD)));
    }

    #[test]
    fn test_rect_origin_size() {
        assert_eq!(
            Rect::new(-31000, -32000, 63000, 64000),
            rect_origin_size(PixelsXY { x: -31000, y: -32000 }, SizeInPixels::new(63000, 64000))
        );
    }

    #[test]
    fn test_requested_size_pixels_uses_requested_size_for_explicit_resolutions() {
        let size = requested_size_pixels(Resolution::Windowed((
            NonZeroU32::new(1024).unwrap(),
            NonZeroU32::new(768).unwrap(),
        )));
        assert_eq!(Some(SizeInPixels::new(1024, 768)), size);

        let size = requested_size_pixels(Resolution::FullScreen((
            NonZeroU32::new(640).unwrap(),
            NonZeroU32::new(480).unwrap(),
        )));
        assert_eq!(Some(SizeInPixels::new(640, 480)), size);

        assert_eq!(None, requested_size_pixels(Resolution::FullScreenDesktop));
    }
}