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
use crate::interfaces::Interface;
use crate::processor::Processor;
extern crate crossterm;
extern crate kira;

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    event::{poll, read, Event, KeyCode, KeyModifiers},
    terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType},
    ExecutableCommand,
};
use kira::{
    manager::{AudioManager, AudioManagerSettings, DefaultBackend},
    sound::{
        static_sound::{StaticSoundData, StaticSoundHandle},
        PlaybackState,
    },
    tween::Tween,
};

use std::{
    io::{stdout, Stdout, Write},
    time::Duration,
};

const KEY_MAP: [char; 16] = [
    'x', '1', '2', '3', 'q', 'w', 'e', 'a', 's', 'd', 'z', 'c', '4', 'r', 'f', 'v',
];

/**
 * An interface that uses the terminal.
 * Mostly useful for debugging purposes.
 */
pub struct TerminalInterface {
    stdout: Stdout,
    sound_handle: StaticSoundHandle,
}

impl TerminalInterface {
    pub fn new() -> TerminalInterface {
        let mut stdout = stdout();
        enable_raw_mode().unwrap();
        stdout.execute(Hide).unwrap();
        let mut am = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default()).unwrap();
        let sd = StaticSoundData::from_file("sound.ogg").unwrap();
        let mut sh = am.play(sd.clone()).unwrap();
        let tween = Tween {
            start_time: kira::StartTime::Immediate,
            duration: Duration::from_micros(0),
            easing: kira::tween::Easing::Linear,
        };
        sh.set_loop_region(0.025..0.075);
        sh.pause(tween);

        return TerminalInterface {
            stdout: stdout,
            sound_handle: sh,
        };
    }
}
impl Interface for TerminalInterface {
    fn update(&mut self, p: &mut Processor) -> bool {
        let mut inputs: [bool; 0x10] = core::array::from_fn(|i| p.get_input_state(i));
        if poll(Duration::from_millis(0)).unwrap() {
            match read().unwrap() {
                Event::Key(evt) => {
                    if evt.code == KeyCode::Char('c')
                        && evt.modifiers.contains(KeyModifiers::CONTROL)
                    {
                        return true;
                    }
                    // For Terminal, we toggle the keys instead of detecting key up/key down
                    match evt.code {
                        KeyCode::Char(c) => match KEY_MAP.iter().position(|ch| *ch == c) {
                            Some(i) => {
                                inputs[i] = !inputs[i];
                                if !inputs[i] {
                                    p.on_key_release(i as u8);
                                }
                            }
                            None => {}
                        },
                        _ => {}
                    }
                }
                _ => {}
            }
            p.update_inputs(inputs);
        }
        // Hacky-ish way to detect key up
        for i in 0..0xF {
            if !inputs[i] && p.get_input_state(i) {
                p.on_key_release(i as u8);
                break;
            }
        }
        p.update_inputs(inputs);
        let tween = Tween {
            start_time: kira::StartTime::Immediate,
            duration: Duration::from_micros(0),
            easing: kira::tween::Easing::Linear,
        };
        if p.get_st() > 0 && self.sound_handle.state() == PlaybackState::Paused {
            self.sound_handle.resume(tween);
        }
        if p.get_st() == 0 && self.sound_handle.state() == PlaybackState::Playing {
            self.sound_handle.pause(tween);
        }
        return false;
    }
    fn exit(&mut self) {
        self.stdout.execute(Show).unwrap();
        disable_raw_mode().unwrap();
    }

    fn render(&mut self, p: &Processor) {
        self.stdout.execute(Clear(ClearType::All)).unwrap();
        self.stdout.execute(MoveTo(0, 0)).unwrap();
        // Create a buffer for the actual screen for speed reasons
        let mut buf = [[' ' as u8; 2 * 64]; 32];
        for y in 0..32 {
            for x in 0..64 {
                if p.get_pixel_at(x as u8, y as u8) {
                    buf[y][2 * x] = '[' as u8;
                    buf[y][2 * x + 1] = ']' as u8;
                };
            }
        }
        let eol = ['\r' as u8, '\n' as u8];
        for row in buf {
            self.stdout.write(&row).unwrap();
            self.stdout.write(&eol).unwrap();
        }
        // Print debug information
        self.stdout.execute(MoveTo(0, 33)).unwrap();
        print!("  PC  |  I   |");
        (0..=0xF).for_each(|r| print!("  V{:x}  |", r));
        self.stdout.execute(MoveTo(0, 34)).unwrap();
        print!("{:#6X}|{:#6X}|", p.get_program_counter(), p.get_i());
        (0..=0xF).for_each(|r| print!(" {:#4X} |", p.get_register_value(r)));
        self.stdout.execute(MoveTo(0, 35)).unwrap();
        print!("  DT  |  ST  ");
        (0..=0xF).for_each(|i| print!("|  I{:X}  ", i));
        self.stdout.execute(MoveTo(0, 36)).unwrap();
        print!(" {:#4X?} | {:#4X?} ", p.get_dt(), p.get_st());
        (0..=0xF).for_each(|i| print!("|  {}   ", if p.get_input_state(i) { 'T' } else { 'F' }));
        self.stdout.execute(MoveTo(0, 37)).unwrap();
        self.stdout.flush().unwrap();
    }
}