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
//! Monotron run-time application support for Rust.
//!
//! You need to supply a function with this prototype, marked `#[no_mangle]` in your crate.
//!
//! ```ignore
//! #![no_std]
//! #![no_main]
//! extern crate monotron_app;
//! #[no_mangle]
//! pub extern "C" fn main() -> i32 {
//!     123
//! }
//! ```
//!
//! If you want to test your app on Linux, you'll need something like:
//!
//! ```ignore
//! #![cfg_attr(target_os = "none", no_std)]
//! #![cfg_attr(target_os = "none", no_main)]
//!
//! use monotron_app::prelude::*;
//! use monotron_app::Host;
//!
//! #[cfg(not(target_os = "none"))]
//! pub fn main() {
//!     std::process::exit(monotron_main());
//! }
//!
//! #[no_mangle]
//! pub extern "C" fn monotron_main() -> i32 {
//!     write!(Host, "Hello, Rust!\n").unwrap();
//!     0
//! }
//! ```

#![cfg_attr(target_os = "none", no_std)]
#![deny(missing_docs)]

#[cfg(not(target_os = "none"))]
use std as core;

#[cfg(not(target_os = "none"))]
extern crate sdl2;

#[cfg(not(target_os = "none"))]
extern crate vga_framebuffer;

#[cfg(not(target_os = "none"))]
extern crate lazy_static;

#[cfg(not(target_os = "none"))]
mod sdl_window;

#[repr(C)]
/// The callbacks supplied by the Monotron OS.
pub struct Table {
    putchar: extern "C" fn(*const Context, u8) -> i32,
    puts: extern "C" fn(*const Context, *const u8) -> i32,
    readc: extern "C" fn(*const Context) -> i32,
    wfvbi: extern "C" fn(*const Context),
    kbhit: extern "C" fn(*const Context) -> i32,
    move_cursor: extern "C" fn(*const Context, u8, u8),
    play: extern "C" fn(*const Context, u32, u8, u8, u8) -> i32,
    change_font: extern "C" fn(*const Context, u32, *const u8),
    get_joystick: extern "C" fn(*const Context) -> u8,
    set_cursor_visible: extern "C" fn(*mut Context, u8),
}

/// Represents the Monotron we're running on. Can be passed to `write!` and
/// friends.
pub struct Host;

/// An internal representation of the context we're given by the Host.
pub struct Context;

#[derive(Debug, Clone, Copy)]
/// Represents a column on screen. Valid values are `0..=47`.
pub struct Col(pub u8);

#[derive(Debug, Clone, Copy)]
/// Represents a row on screen. Valid values are `0..=36`.
pub struct Row(pub u8);

#[derive(Debug, Clone, Copy)]
/// Represents a font we can set the screen to use. The whole screen uses the
/// same font. Custom fonts must be exactly 4096 bytes (256 chars x 16
/// bytes/char) long.
pub enum Font {
    /// Codepage 850
    Normal,
    /// ASCII with added Teletext sixel block graphics
    Teletext,
    /// A custom font
    Custom(&'static [u8]),
}

#[derive(Debug, Copy, Clone)]
/// Represents the current state of an Atari 9-pin joystick.
pub struct JoystickState(u8);

#[derive(Debug, Copy, Clone)]
/// A frequency we can give to the synthesiser.
pub struct Frequency(u32);

#[derive(Debug, Copy, Clone)]
#[repr(u8)]
/// A channel on the synthesiser. They all run concurrently.
pub enum Channel {
    /// Channel 0
    Channel0 = 0,
    /// Channel 1
    Channel1 = 1,
    /// Channel 2
    Channel2 = 2,
}

#[derive(Debug, Copy, Clone)]
#[repr(u8)]
/// A waveform on the synthesiser. You can change this note by note.
pub enum Waveform {
    /// A square wave
    Square = 0,
    /// A sine wave
    Sine = 1,
    /// A sawtooth wave
    Sawtooth = 2,
    /// A white noise (ish)
    Noise = 3,
}

impl Frequency {
    /// Convert a Frequency into centi-hz (i.e. 1 kHz is 100_000).
    pub fn as_centi_hz(&self) -> u32 {
        self.0
    }

    /// Convert a Frequency into Hz (i.e. 1 kHz is 1000).
    pub fn as_hz(&self) -> u32 {
        self.0 / 100
    }

    /// Convert a number of Hz into a Frequency.
    pub fn from_hz(hz: u16) -> Frequency {
        Frequency((hz as u32) * 100)
    }

    /// Convert a number of centi-Hz into a Frequency.
    pub fn from_centi_hz(centi_hz: u32) -> Frequency {
        Frequency(centi_hz)
    }
}

impl JoystickState {
    /// True if joystick is pointing up.
    pub fn is_up(&self) -> bool {
        (self.0 & 0b10000) != 0
    }

    /// True if joystick is pointing down.
    pub fn is_down(&self) -> bool {
        (self.0 & 0b01000) != 0
    }

    /// True if joystick is pointing left.
    pub fn is_left(&self) -> bool {
        (self.0 & 0b00100) != 0
    }

    /// True if joystick is pointing right.
    pub fn is_right(&self) -> bool {
        (self.0 & 0b00010) != 0
    }

    /// True if joystick has fire pressed.
    pub fn is_fire_pressed(&self) -> bool {
        (self.0 & 0b00001) != 0
    }
}

/// Notes on an piano keyboard, where A4 = 440 Hz.
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(u8)]
#[allow(missing_docs)]
pub enum Note {
    Rest,
    C0,
    CsDb0,
    D0,
    DsEb0,
    E0,
    F0,
    FsGb0,
    G0,
    GsAb0,
    A0,
    AsBb0,
    B0,
    C1,
    CsDb1,
    D1,
    DsEb1,
    E1,
    F1,
    FsGb1,
    G1,
    GsAb1,
    A1,
    AsBb1,
    B1,
    C2,
    CsDb2,
    D2,
    DsEb2,
    E2,
    F2,
    FsGb2,
    G2,
    GsAb2,
    A2,
    AsBb2,
    B2,
    C3,
    CsDb3,
    D3,
    DsEb3,
    E3,
    F3,
    FsGb3,
    G3,
    GsAb3,
    A3,
    AsBb3,
    B3,
    C4,
    CsDb4,
    D4,
    DsEb4,
    E4,
    F4,
    FsGb4,
    G4,
    GsAb4,
    A4,
    AsBb4,
    B4,
    C5,
    CsDb5,
    D5,
    DsEb5,
    E5,
    F5,
    FsGb5,
    G5,
    GsAb5,
    A5,
    AsBb5,
    B5,
    C6,
    CsDb6,
    D6,
    DsEb6,
    E6,
    F6,
    FsGb6,
    G6,
    GsAb6,
    A6,
    AsBb6,
    B6,
    C7,
    CsDb7,
    D7,
    DsEb7,
    E7,
    F7,
    FsGb7,
    G7,
    GsAb7,
    A7,
    AsBb7,
    B7,
    C8,
    CsDb8,
    D8,
    DsEb8,
    E8,
    F8,
    FsGb8,
    G8,
    GsAb8,
    A8,
    AsBb8,
    B8,
}

impl core::convert::Into<Frequency> for Note {
    fn into(self) -> Frequency {
        Frequency::from_centi_hz(match self {
            Note::Rest => 0,
            Note::C0 => 1635,
            Note::CsDb0 => 1732,
            Note::D0 => 1835,
            Note::DsEb0 => 1945,
            Note::E0 => 2060,
            Note::F0 => 2183,
            Note::FsGb0 => 2312,
            Note::G0 => 2450,
            Note::GsAb0 => 2596,
            Note::A0 => 2750,
            Note::AsBb0 => 2914,
            Note::B0 => 3087,
            Note::C1 => 3270,
            Note::CsDb1 => 3465,
            Note::D1 => 3671,
            Note::DsEb1 => 3889,
            Note::E1 => 4120,
            Note::F1 => 4365,
            Note::FsGb1 => 4625,
            Note::G1 => 4900,
            Note::GsAb1 => 5191,
            Note::A1 => 5500,
            Note::AsBb1 => 5827,
            Note::B1 => 6174,
            Note::C2 => 6541,
            Note::CsDb2 => 6930,
            Note::D2 => 7342,
            Note::DsEb2 => 7778,
            Note::E2 => 8241,
            Note::F2 => 8731,
            Note::FsGb2 => 9250,
            Note::G2 => 9800,
            Note::GsAb2 => 10383,
            Note::A2 => 11000,
            Note::AsBb2 => 11654,
            Note::B2 => 12347,
            Note::C3 => 13081,
            Note::CsDb3 => 13859,
            Note::D3 => 14683,
            Note::DsEb3 => 15556,
            Note::E3 => 16481,
            Note::F3 => 17461,
            Note::FsGb3 => 18500,
            Note::G3 => 19600,
            Note::GsAb3 => 20765,
            Note::A3 => 22000,
            Note::AsBb3 => 23308,
            Note::B3 => 24694,
            Note::C4 => 26163,
            Note::CsDb4 => 27718,
            Note::D4 => 29366,
            Note::DsEb4 => 31113,
            Note::E4 => 32963,
            Note::F4 => 34923,
            Note::FsGb4 => 36999,
            Note::G4 => 39200,
            Note::GsAb4 => 41530,
            Note::A4 => 44000,
            Note::AsBb4 => 46616,
            Note::B4 => 49388,
            Note::C5 => 52325,
            Note::CsDb5 => 55437,
            Note::D5 => 58733,
            Note::DsEb5 => 62225,
            Note::E5 => 65925,
            Note::F5 => 69846,
            Note::FsGb5 => 73999,
            Note::G5 => 78399,
            Note::GsAb5 => 83061,
            Note::A5 => 88000,
            Note::AsBb5 => 93233,
            Note::B5 => 98777,
            Note::C6 => 104650,
            Note::CsDb6 => 110873,
            Note::D6 => 117466,
            Note::DsEb6 => 124451,
            Note::E6 => 131851,
            Note::F6 => 139691,
            Note::FsGb6 => 147998,
            Note::G6 => 156798,
            Note::GsAb6 => 166122,
            Note::A6 => 176000,
            Note::AsBb6 => 186466,
            Note::B6 => 197553,
            Note::C7 => 209300,
            Note::CsDb7 => 221746,
            Note::D7 => 234932,
            Note::DsEb7 => 248902,
            Note::E7 => 263702,
            Note::F7 => 279383,
            Note::FsGb7 => 295996,
            Note::G7 => 313596,
            Note::GsAb7 => 332244,
            Note::A7 => 352000,
            Note::AsBb7 => 372931,
            Note::B7 => 395107,
            Note::C8 => 418601,
            Note::CsDb8 => 443492,
            Note::D8 => 469863,
            Note::DsEb8 => 497803,
            Note::E8 => 527404,
            Note::F8 => 558765,
            Note::FsGb8 => 591991,
            Note::G8 => 627193,
            Note::GsAb8 => 664488,
            Note::A8 => 704000,
            Note::AsBb8 => 745862,
            Note::B8 => 790213,
        })
    }
}

#[cfg(target_os = "none")]
/// Implementation used when building code for the Montron
pub mod target {
    use super::*;

    #[link_section = ".entry_point"]
    #[no_mangle]
    #[used]
    /// The pointer Monotron calls to start running this application.
    pub static ENTRY_POINT: fn(*const Table, *mut Context) -> i32 = entry_point;
    /// Pointer to the callback table we're given by the host.
    static mut TABLE_POINTER: Option<&'static Table> = None;
    /// Pointer to the context we're given by the host.
    static mut TABLE_CONTEXT: Option<&'static mut Context> = None;

    #[no_mangle]
    /// The function called by the host to start us up. Does some setup, then
    /// jumps to a function called `main` defined by the actual application using
    /// this crate.
    pub fn entry_point(table: *const Table, ctx: *mut Context) -> i32 {
        // Turn the pointer into a reference and store in a static.
        unsafe {
            TABLE_POINTER = Some(&*table);
            TABLE_CONTEXT = Some(&mut *ctx);
        };

        extern "C" {
            fn monotron_main() -> i32;
        }
        // call the user application
        unsafe { monotron_main() }
    }

    impl Table {
        fn get() -> (&'static Table, &'static mut Context) {
            unsafe {
                if let (Some(tbl), Some(ctx)) = (&TABLE_POINTER, &mut TABLE_CONTEXT) {
                    (tbl, ctx)
                } else {
                    panic!("Bad context");
                }
            }
        }
    }

    impl core::fmt::Write for Host {
        fn write_str(&mut self, s: &str) -> core::fmt::Result {
            let (tbl, ctx) = Table::get();
            for ch in s.bytes() {
                (tbl.putchar)(ctx, ch);
            }
            Ok(())
        }
    }

    impl Host {
        /// Get the (width, height) of the Monotron TTY
        pub fn getsize() -> (u16, u16) {
            (48, 36)
        }

        /// Send a single 8-bit character to the screen.
        pub fn putchar(ch: u8) {
            let (tbl, ctx) = Table::get();
            (tbl.putchar)(ctx, ch);
        }

        /// Send a single 8-bit character to the screen.
        pub fn puts(str8bit: &[u8]) {
            let (tbl, ctx) = Table::get();
            for &ch in str8bit {
                (tbl.putchar)(ctx, ch);
            }
        }

        /// Return true if there is a keypress waiting (i.e. `readc` won't block).
        pub fn kbhit() -> bool {
            let (tbl, ctx) = Table::get();
            (tbl.kbhit)(ctx) != 0
        }

        /// Read an 8-bit character from the console.
        pub fn readc() -> u8 {
            let (tbl, ctx) = Table::get();
            (tbl.readc)(ctx) as u8
        }

        /// Wait For Vertical Blanking Interval
        pub fn wfvbi() {
            let (tbl, ctx) = Table::get();
            (tbl.wfvbi)(ctx)
        }

        /// Move the cursor on the screen.
        pub fn move_cursor(row: Row, col: Col) {
            let (tbl, ctx) = Table::get();
            (tbl.move_cursor)(ctx, row.0, col.0);
        }

        /// Start playing a tone. It will continue.
        pub fn play<F>(frequency: F, channel: Channel, waveform: Waveform, volume: u8)
        where
            F: Into<Frequency>,
        {
            let (tbl, ctx) = Table::get();
            (tbl.play)(
                ctx,
                frequency.into().as_centi_hz(),
                channel as u8,
                waveform as u8,
                volume,
            );
        }

        /// Move the cursor on the screen.
        pub fn set_font(font: Font) -> Result<(), &'static str> {
            let (tbl, ctx) = Table::get();
            match font {
                Font::Normal => (tbl.change_font)(ctx, 0, core::ptr::null()),
                Font::Teletext => (tbl.change_font)(ctx, 1, core::ptr::null()),
                Font::Custom(ram) => {
                    if ram.len() != 4096 {
                        return Err("bad font length");
                    }
                    (tbl.change_font)(ctx, 2, ram.as_ptr());
                }
            }
            Ok(())
        }

        /// Get the Joystick state
        pub fn get_joystick() -> JoystickState {
            let (tbl, ctx) = Table::get();
            let b = (tbl.get_joystick)(ctx);
            JoystickState(b)
        }

        /// Show/hide the cursor
        pub fn set_cursor_visible(visible: bool) {
            let (tbl, ctx) = Table::get();
            (tbl.set_cursor_visible)(ctx, if visible { 1 } else { 0 });
        }
    }

    use core::panic::PanicInfo;
    use core::sync::atomic::{self, Ordering};

    #[inline(never)]
    #[panic_handler]
    #[cfg(all(feature = "print-panic", target_os = "none"))]
    fn panic(info: &PanicInfo) -> ! {
        use core::fmt::Write;
        // This uses about 15 KiB of our 24 KiB of RAM
        write!(
            Host,
            "\u{001B}Z\u{001B}R\u{001B}kPanic: {:?}\u{001B}W",
            info
        );
        loop {
            atomic::compiler_fence(Ordering::SeqCst);
        }
    }

    #[inline(never)]
    #[panic_handler]
    #[cfg(all(not(feature = "print-panic"), target_os = "none"))]
    fn panic(_info: &PanicInfo) -> ! {
        loop {
            atomic::compiler_fence(Ordering::SeqCst);
        }
    }

}

#[cfg(not(target_os = "none"))]
/// Implementation used when building code for Linux/Windows
pub mod target {
    use super::*;
    use lazy_static::lazy_static;
    use std::sync::Mutex;

    lazy_static! {
        static ref VIDEO_CONTEXT: Mutex<Option<sdl_window::Context<'static>>> = Mutex::new(None);
    }

    impl std::fmt::Write for Host {
        fn write_str(&mut self, s: &str) -> std::fmt::Result {
            for b in s.bytes() {
                // Ugh - this will force UTF-8 (the Rust native string format)
                // into ASCII CodePage 850, which will do bad things for
                // characters that aren't in the basic ASCII set.
                Host::putchar(b);
            }
            Ok(())
        }
    }

    impl Host {
        /// Get the (width, height) of the Monotron TTY
        pub fn getsize() -> (u16, u16) {
            (48, 36)
        }

        /// Call once at start-up to configure terminal
        pub fn init() {
            // Create SDL2 canvas and window
            // Create framebuffer to render onto canvas
            let ctx = sdl_window::Context::new();
            *VIDEO_CONTEXT.lock().unwrap() = Some(ctx);
        }

        /// Disable ncurses
        pub fn deinit() {
            // destroy SDL2 window
        }

        /// Send a single 8-bit character to the screen.
        pub fn putchar(ch: u8) {
            use vga_framebuffer::AsciiConsole;
            if let Some(ref mut ctx) = *VIDEO_CONTEXT.lock().unwrap() {
                ctx.fb.write_character(ch).unwrap();
            }
        }

        /// Send a single 8-bit character to the screen.
        pub fn puts(str8bit: &[u8]) {
            use vga_framebuffer::AsciiConsole;
            if let Some(ref mut ctx) = *VIDEO_CONTEXT.lock().unwrap() {
                for &ch in str8bit {
                    ctx.fb.write_character(ch).unwrap();
                }
            }
        }

        /// Return true if there is a keypress waiting (i.e. `readc` won't block).
        pub fn kbhit() -> bool {
            if let Some(ref mut ctx) = *VIDEO_CONTEXT.lock().unwrap() {
                ctx.keypresses.len() != 0
            } else {
                false
            }
        }

        /// Read an 8-bit character from the console.
        pub fn readc() -> u8 {
            loop {
                if let Some(ref mut ctx) = *VIDEO_CONTEXT.lock().unwrap() {
                    if let Some(ch) = ctx.keypresses.pop_front() {
                        break ch;
                    }
                }
                // Need to pump the event loop to get keypresses
                wfvbi();
            }
        }

        /// Wait For Vertical Blanking Interval
        pub fn wfvbi() {
            // redraw the screen here, as apps should call wfvbi often yes,
            // it's a kludge. It's that or we try and put the framebuffer in
            // another thread, but it's not thread-safe.
            if let Some(ref mut ctx) = *VIDEO_CONTEXT.lock().unwrap() {
                ctx.draw();
                ctx.pump();
            }
            ::std::thread::sleep(::std::time::Duration::from_micros(1_000_000 / 60));
        }

        /// Move the cursor on the screen.
        pub fn move_cursor(row: Row, col: Col) {
            use vga_framebuffer::BaseConsole;
            if col.0 as usize <= vga_framebuffer::TEXT_MAX_COL {
                if row.0 as usize <= vga_framebuffer::TEXT_MAX_ROW {
                    if let Some(ref mut ctx) = *VIDEO_CONTEXT.lock().unwrap() {
                        let p = vga_framebuffer::Position::new(
                            vga_framebuffer::Row(row.0),
                            vga_framebuffer::Col(col.0),
                        );
                        ctx.fb.set_pos(p).unwrap();
                    }
                }
            }
        }

        /// Start playing a tone. It will continue.
        pub fn play<F>(_frequency: F, _channel: Channel, _waveform: Waveform, _volume: u8)
        where
            F: Into<Frequency>,
        {

        }

        /// Move the cursor on the screen.
        pub fn set_font(_font: Font) -> Result<(), &'static str> {
            Ok(())
        }

        /// Get the Joystick state
        pub fn get_joystick() -> JoystickState {
            JoystickState(0)
        }

        /// Show/hide the cursor
        pub fn set_cursor_visible(_visible: bool) {
            // ?
        }
    }
}

#[no_mangle]
/// C FFI for Host::getsize
pub extern "C" fn getsize() -> (u16, u16) {
    Host::getsize()
}

#[no_mangle]
#[cfg(not(target_os = "none"))]
/// C FFI for Host::init
pub extern "C" fn init() {
    Host::init()
}

#[no_mangle]
#[cfg(not(target_os = "none"))]
/// C FFI for Host::deinit
pub extern "C" fn deinit() {
    Host::deinit()
}

#[no_mangle]
/// C FFI for Host::putchar
pub extern "C" fn putchar(ch: u8) {
    Host::putchar(ch)
}

#[no_mangle]
/// C FFI for Host::puts
pub unsafe extern "C" fn puts(null_term_str: *const u8) {
    let mut len = 0usize;
    while *null_term_str.offset(len as isize) != 0 {
        len += 1;
    }
    Host::puts(core::slice::from_raw_parts(null_term_str, len));
}

#[no_mangle]
/// C FFI for Host::kbhit
pub extern "C" fn kbhit() -> i32 {
    if Host::kbhit() { 1 } else { 0 }
}

#[no_mangle]
/// C FFI for Host::readc
pub extern "C" fn getchar() -> u8 {
    Host::readc()
}

#[no_mangle]
/// C FFI for Host::wfvbi
pub extern "C" fn wfvbi() {
    #[cfg(not(target_os = "none"))]
    Host::wfvbi()
}

#[no_mangle]
/// C FFI for Host::move_cursor
pub extern "C" fn move_cursor(row: u8, col: u8) {
    Host::move_cursor(Row(row), Col(col))
}

#[no_mangle]
/// C FFI for Host::play
pub extern "C" fn play(frequency: u32, channel: i32, waveform: i32, volume: u8) {
    let channel = match channel {
        0 => Some(Channel::Channel0),
        1 => Some(Channel::Channel1),
        2 => Some(Channel::Channel2),
        _ => None,
    };
    let waveform = match waveform {
        0 => Some(Waveform::Square),
        1 => Some(Waveform::Sine),
        2 => Some(Waveform::Sawtooth),
        3 => Some(Waveform::Noise),
        _ => None,
    };
    if let (Some(ch), Some(wv)) = (channel, waveform) {
        Host::play(Frequency(frequency), ch, wv, volume)
    }
}

#[no_mangle]
/// C FFI for Host::set_font
pub extern "C" fn font_normal() {
    let _ = Host::set_font(Font::Normal);
}

#[no_mangle]
/// C FFI for Host::set_font
pub extern "C" fn font_teletext() {
    let _ = Host::set_font(Font::Teletext);
}

#[no_mangle]
/// C FFI for Host::get_joystick
pub extern "C" fn get_joystick() -> JoystickState {
    Host::get_joystick()
}

/// True if joystick is pointing up.
#[no_mangle]
pub extern "C" fn joystick_is_up(state: u8) -> bool {
    (state & 0b10000) != 0
}

/// True if joystick is pointing down.
#[no_mangle]
pub extern "C" fn joystick_is_down(state: u8) -> bool {
    (state & 0b01000) != 0
}

/// True if joystick is pointing left.
#[no_mangle]
pub extern "C" fn joystick_is_left(state: u8) -> bool {
    (state & 0b00100) != 0
}

/// True if joystick is pointing right.
#[no_mangle]
pub extern "C" fn joystick_is_right(state: u8) -> bool {
    (state & 0b00010) != 0
}

/// True if joystick is pointing right.
#[no_mangle]
pub extern "C" fn joystick_fire_pressed(state: u8) -> bool {
    (state & 0b00001) != 0
}

#[no_mangle]
/// Ugh
pub extern "C" fn put_separated_sixel(_char: u8) {

}

#[no_mangle]
/// C FFI for Host::set_cursor_visible
pub extern "C" fn set_cursor_visible(visible: bool) {
    Host::set_cursor_visible(visible)
}

#[no_mangle]
/// _sbrk is required by newlib
pub extern "C" fn _sbrk() {

}

#[no_mangle]
/// _write is required by newlib
pub extern "C" fn _write() {
    
}

#[no_mangle]
/// _close is required by newlib
pub extern "C" fn _close() {
    
}

#[no_mangle]
/// _lseek is required by newlib
pub extern "C" fn _lseek() {
    
}

#[no_mangle]
/// _read is required by newlib
pub extern "C" fn _read() {
    
}

#[no_mangle]
/// _fstat is required by newlib
pub extern "C" fn _fstat() {
    
}

#[no_mangle]
/// _isatty is required by newlib
pub extern "C" fn _isatty() {
    
}

/// Useful things people should have in scope.
pub mod prelude {
    pub use core::fmt::Write as _monotron_prelude_core_fmt_Write;
}