librsmsx 0.5.2

a MSX emulator written in rust, a port from gomsx
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
/*

Copyright (c) 2010 Andrea Fazzi

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

use std::{cell::RefCell, fmt, rc::Rc};

use sdl3::EventPump;
/*
The z80 package implements a Zilog Z80 emulator.
*/
use serde::{Deserialize, Serialize};

use crate::libs::{
    memory::{Memory, MemoryData},
    ports::Ports,
    ppi::PPIData,
};

use super::{
    api::{FLAG_C, FLAG_H, FLAG_N, FLAG_V},
    hook::FuncHook,
    instructions::execute_opcode,
    opcodes_disassembler::disassemble_map,
    opcodes_timings_msx::get_timings,
    util::{join_bytes, sign_extend, split_word, tern_op_b},
    z80_tables,
};

// The flags
// pub(crate) const FLAG_C: u8 = 0x01;
// pub(crate) const FLAG_N: u8 = 0x02;
// pub(crate) const FLAG_P: u8 = 0x04;
// pub(crate) const FLAG_V: u8 = FLAG_P;
// pub(crate) const FLAG_3: u8 = 0x08;
// pub(crate) const FLAG_H: u8 = 0x10;
// pub(crate) const FLAG_5: u8 = 0x20;
// pub(crate) const FLAG_Z: u8 = 0x40;
// pub(crate) const FLAG_S: u8 = 0x80;

pub(crate) const SHIFT_0X_CB: u16 = 256;
pub(crate) const SHIFT_0X_ED: u16 = 512;
pub(crate) const SHIFT_0X_DD: u16 = 768;
pub(crate) const SHIFT_0X_DDCB: u16 = 1024;
pub(crate) const SHIFT_0X_FDCB: u16 = 1024;
pub(crate) const SHIFT_0X_FD: u16 = 1280;

// /// returns (high, low)
// pub fn split_word(word: u16) -> (u8, u8) {
//     ((word >> 8) as u8, (word & 0xff) as u8)
// }

// pub fn join_bytes(h: u8, l: u8) -> u16 {
//     (l as u16) | ((h as u16) << 8)
// }

// pub fn tern_op_b(cond: bool, ret1: u8, ret2: u8) -> u8 {
//     if cond {
//         return ret1;
//     }
//     ret2
// }

// pub fn sign_extend(v: u8) -> i16 {
//     i16::from(v as i8)
// }

pub struct Register16 {
    high: u8,
    low: u8,
}

impl Register16 {
    pub(crate) fn new(high: u8, low: u8) -> Self {
        Self { high, low }
    }
    /// return high,low
    pub(crate) fn result(&self) -> (u8, u8) {
        (self.high, self.low)
    }
    // pub(crate) fn inc(&mut self) {
    //     let temp = self.get() + 1;
    //     self.high = (temp >> 8) as u8;
    //     self.low = (temp & 0xff) as u8;
    // }

    // pub(crate) fn dec(&mut self) {
    //     let temp = self.get() - 1;
    //     self.high = (temp >> 8) as u8;
    //     self.low = (temp & 0xff) as u8;
    // }

    pub(crate) fn set(&mut self, value: u16) {
        // *r.high, *r.low = splitWord(value)
        (self.high, self.low) = split_word(value);
    }

    pub(crate) fn get(&mut self) -> u16 {
        // return joinBytes(self.high, self.low)
        join_bytes(self.high, self.low)
    }
}

#[derive(Serialize, Deserialize, Clone)]
#[allow(non_snake_case)]
pub struct Z80Data {
    pub A: u8,
    pub F: u8,
    pub B: u8,
    pub C: u8,
    pub D: u8,
    pub E: u8,
    pub H: u8,
    pub L: u8,
    pub(crate) A_: u8,
    pub(crate) F_: u8,
    pub(crate) B_: u8,
    pub(crate) C_: u8,
    pub(crate) D_: u8,
    pub(crate) E_: u8,
    pub(crate) H_: u8,
    pub(crate) L_: u8,
    pub(crate) IXH: u8,
    pub(crate) IXL: u8,
    pub(crate) IYH: u8,
    pub(crate) IYL: u8,
    pub(crate) I: u8,
    pub(crate) IFF1: u8,
    pub(crate) IFF2: u8,
    pub(crate) IM: u8, // interrupt mode

    // The highest bit (bit 7) of the R register
    pub(crate) R7: u8,

    // The low 7 bits of the R register. 16 bits long so it can
    // also act as an RZX instruction counter.
    pub(crate) R: u16,

    pub(crate) sp: u16,
    pub(crate) pc: u16,

    // bc: register16,
    // bc_: register16,
    // hl: register16,
    // hl_: register16,
    // af: register16,
    // de: register16,
    // de_: register16,
    // ix: register16,
    // iy: register16,
    pub(crate) event_next_event: isize,

    // Number of t_states since the beginning of the last frame.
    // The value of this variable is usually smaller than TStatesPerFrame,
    // but in some unlikely circumstances it may be >= than that.
    pub(crate) t_states: isize,

    pub(crate) halted: bool,

    // Needed when executing opcodes prefixed by 0xCB
    pub(crate) temp_addr: u16,

    pub(crate) interrupts_enabled_at: isize,

    pub(crate) rzx_instructions_offset: isize,

    // Clock Cycles
    pub cycles: u64,
    pub(crate) debug: bool,
    pub(crate) debug_step: usize,
}

impl fmt::Debug for Z80Data {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "[Z80Data]\n\
            \tA :0x{:02x}     F :0x{:02x}   BC :0x{:04x}  DE :0x{:04x}  HL :0x{:04x}\n\
            \tA_:0x{:02x}     F_:0x{:02x}   BC_:0x{:04x}  DE_:0x{:04x}  HL_:0x{:04x}\n\
            \tIX:0x{:04x}   IY:0x{:04x} I  :0x{:02x}    IF1:0x{:02x}    IF2:0x{:02x}\n\
            \tIM:0x{:02x}     R7:0x{:02x}   R  :0x{:04x}  sp :0x{:04x}  pc :0x{:04x}\n\
            \tene:0x{:04x}  ts:0x{:04x} t.a:0x{:04x}  iea:0x{:04x}  rio:0x{:04x}\n",
            self.A,
            self.F,
            self.bc(),
            self.de(),
            self.hl(),
            self.A_,
            self.F_,
            self.bc_(),
            self.de_(),
            self.hl_(),
            self.ix(),
            self.iy(),
            self.I,
            self.IFF1,
            self.IFF2,
            self.IM,
            self.R7,
            self.R,
            self.sp,
            self.pc,
            self.event_next_event,
            self.t_states,
            self.temp_addr,
            self.interrupts_enabled_at,
            self.rzx_instructions_offset,
        )
    }
}

macro_rules! fn_inc_reg {
    ($fn:tt, $r:ident) => {
        pub fn $fn(&mut self) {
            self.$r = self.$r.wrapping_add(1);
            self.F = self.F & FLAG_C
                | tern_op_b(self.$r == 0x80, FLAG_V, 0)
                | tern_op_b((self.$r & 0x0f) != 0, 0, FLAG_H)
                | z80_tables::get().sz53_table[self.$r as usize];
        }
    };
}

macro_rules! fn_dec_reg {
    ($fn:tt, $r:ident) => {
        pub fn $fn(&mut self) {
            self.F = self.F & FLAG_C | tern_op_b(self.$r & 0x0f != 0, 0, FLAG_H) | FLAG_N;
            self.$r = self.$r.wrapping_sub(1);
            self.F |= tern_op_b(self.$r == 0x7f, FLAG_V, 0)
                | z80_tables::get().sz53_table[self.$r as usize];
        }
    };
}

macro_rules! fn_get_reg16 {
    ($fn:tt, $rh:ident, $rl:ident) => {
        pub fn $fn(&self) -> u16 {
            // return self.bc.get();
            join_bytes(self.$rh, self.$rl)
        }
    };
}

macro_rules! fn_set_reg16 {
    ($fn:tt, $rh:ident, $rl:ident) => {
        pub fn $fn(&mut self, value: u16) {
            // return self.bc.get();
            (self.$rh, self.$rl) = split_word(value);
        }
    };
}

macro_rules! fn_dec_reg16 {
    ($fn:tt, $r:ident, $fs:ident) => {
        pub fn $fn(&mut self) {
            // self.bc.dec()
            let r = self.$r();
            self.$fs(r.wrapping_sub(1));
        }
    };
}

macro_rules! fn_inc_reg16 {
    ($fn:tt, $r:ident, $fs:ident) => {
        pub fn $fn(&mut self) {
            // self.bc.inc()
            let r = self.$r();
            self.$fs(r.wrapping_add(1));
        }
    };
}

#[allow(dead_code)]
impl Z80Data {
    pub(crate) fn new() -> Self {
        Self {
            A: 0,
            F: 0,
            B: 0,
            C: 0,
            D: 0,
            E: 0,
            H: 0,
            L: 0,
            A_: 0,
            F_: 0,
            B_: 0,
            C_: 0,
            D_: 0,
            E_: 0,
            H_: 0,
            L_: 0,
            IXH: 0,
            IXL: 0,
            IYH: 0,
            IYL: 0,
            I: 0,
            IFF1: 0,
            IFF2: 0,
            IM: 0,

            R7: 0,

            R: 0,

            sp: 0,
            pc: 0,

            event_next_event: 0,

            t_states: 0,

            halted: false,

            temp_addr: 0,

            interrupts_enabled_at: 0,

            rzx_instructions_offset: 0,

            cycles: 0,

            debug: false,
            debug_step: 0,
        }
    }
    pub(crate) fn reset(&mut self) {
        (
            self.A, self.F, self.B, self.C, self.D, self.E, self.H, self.L,
        ) = (0, 0, 0, 0, 0, 0, 0, 0);
        (
            self.A_, self.F_, self.B_, self.C_, self.D_, self.E_, self.H_, self.L_,
        ) = (0, 0, 0, 0, 0, 0, 0, 0);
        (self.IXH, self.IXL, self.IYH, self.IYL) = (0, 0, 0, 0);

        (
            self.sp, self.I, self.R, self.R7, self.pc, self.IFF1, self.IFF2, self.IM,
        ) = (0, 0, 0, 0, 0, 0, 0, 0);

        self.t_states = 0;

        self.halted = false;
        self.interrupts_enabled_at = 0;
        self.debug_step = 0;
    }
    pub fn set_debug(&mut self, debug: bool) {
        self.debug = debug;
    }
    pub fn set_debug_step(&mut self, step: usize) {
        self.debug_step = step;
    }
    pub fn get_debug_step(&self) -> usize {
        self.debug_step
    }
    pub fn increase_debug_step(&mut self) {
        self.debug_step += 1;
    }
    pub fn decrease_debug_step(&mut self) {
        self.debug_step -= 1;
    }
    pub fn pc(&self) -> u16 {
        self.pc
    }

    // SetPC sets the program counter.
    pub fn set_pc(&mut self, value: u16) {
        self.pc = value;
    }

    // IncPC increments the program counter.
    pub fn inc_pc(&mut self, value: u16) {
        self.pc += value;
    }

    // IncPC decrements the program counter.
    pub(crate) fn dec_pc(&mut self, value: u16) {
        self.pc -= value;
    }

    // SP returns the SP register.
    pub fn sp(&self) -> u16 {
        self.sp
    }

    // SetSP sets the SP register.
    pub(crate) fn set_sp(&mut self, value: u16) {
        self.sp = value;
    }

    // IncSP increments the SP register.
    pub(crate) fn inc_sp(&mut self) {
        self.sp += 1;
    }

    // DecSP decrements the SP register.
    pub(crate) fn dec_sp(&mut self) {
        self.sp -= 1;
    }

    // IR returns the IR register.
    pub(crate) fn ir(&mut self) -> u16 {
        let mut ir: u16 = 0;
        ir |= (self.I as u16) << 8;
        ir |= self.R7 as u16 & 0x80 | self.R & 0x7f;
        ir
    }
    fn_inc_reg!(inc_a, A);
    fn_dec_reg!(dec_a, A);

    fn_inc_reg!(inc_b, B);
    fn_dec_reg!(dec_b, B);

    fn_inc_reg!(inc_c, C);
    fn_dec_reg!(dec_c, C);

    fn_inc_reg!(inc_d, D);
    fn_dec_reg!(dec_d, D);

    fn_inc_reg!(inc_e, E);
    fn_dec_reg!(dec_e, E);

    fn_inc_reg!(inc_f, F);
    fn_dec_reg!(dec_f, F);

    fn_inc_reg!(inc_h, H);
    fn_dec_reg!(dec_h, H);

    fn_inc_reg!(inc_i, I);
    fn_dec_reg!(dec_i, I);

    fn_inc_reg!(inc_l, L);
    fn_dec_reg!(dec_l, L);

    fn_inc_reg!(inc_r7, R7);
    fn_dec_reg!(dec_r7, R7);

    fn_inc_reg!(inc_a_, A_);
    fn_dec_reg!(dec_a_, A_);

    fn_inc_reg!(inc_b_, B_);
    fn_dec_reg!(dec_b_, B_);

    fn_inc_reg!(inc_c_, C_);
    fn_dec_reg!(dec_c_, C_);

    fn_inc_reg!(inc_d_, D_);
    fn_dec_reg!(dec_d_, D_);

    fn_inc_reg!(inc_e_, E_);
    fn_dec_reg!(dec_e_, E_);

    fn_inc_reg!(inc_f_, F_);
    fn_dec_reg!(dec_f_, F_);

    fn_inc_reg!(inc_h_, H_);
    fn_dec_reg!(dec_h_, H_);

    fn_inc_reg!(inc_l_, L_);
    fn_dec_reg!(dec_l_, L_);

    fn_inc_reg!(inc_ixl, IXL);
    fn_dec_reg!(dec_ixl, IXL);

    fn_inc_reg!(inc_ixh, IXH);
    fn_dec_reg!(dec_ixh, IXH);

    fn_inc_reg!(inc_iyl, IYL);
    fn_dec_reg!(dec_iyl, IYL);

    fn_inc_reg!(inc_iyh, IYH);
    fn_dec_reg!(dec_iyh, IYH);

    // Generated getters/setters and INC/DEC functions for 16bit registers

    fn_get_reg16!(bc, B, C);
    fn_set_reg16!(set_bc, B, C);
    fn_dec_reg16!(dec_bc, bc, set_bc);
    fn_inc_reg16!(inc_bc, bc, set_bc);

    fn_get_reg16!(de, D, E);
    fn_set_reg16!(set_de, D, E);
    fn_dec_reg16!(dec_de, de, set_de);
    fn_inc_reg16!(inc_de, de, set_de);

    fn_get_reg16!(hl, H, L);
    fn_set_reg16!(set_hl, H, L);
    fn_dec_reg16!(dec_hl, hl, set_hl);
    fn_inc_reg16!(inc_hl, hl, set_hl);

    fn_get_reg16!(bc_, B_, C_);
    fn_set_reg16!(set_bc_, B_, C_);
    fn_dec_reg16!(dec_bc_, bc_, set_bc_);
    fn_inc_reg16!(inc_bc_, bc_, set_bc_);

    fn_get_reg16!(de_, D_, E_);
    fn_set_reg16!(set_de_, D_, E_);
    fn_dec_reg16!(dec_de_, de_, set_de_);
    fn_inc_reg16!(inc_de_, de_, set_de_);

    fn_get_reg16!(hl_, H_, L_);
    fn_set_reg16!(set_hl_, H_, L_);
    fn_dec_reg16!(dec_hl_, hl_, set_hl_);
    fn_inc_reg16!(inc_hl_, hl_, set_hl_);

    fn_get_reg16!(ix, IXH, IXL);
    fn_set_reg16!(set_ix, IXH, IXL);
    fn_dec_reg16!(dec_ix, ix, set_ix);
    fn_inc_reg16!(inc_ix, ix, set_ix);

    fn_get_reg16!(iy, IYH, IYL);
    fn_set_reg16!(set_iy, IYH, IYL);
    fn_dec_reg16!(dec_iy, iy, set_iy);
    fn_inc_reg16!(inc_iy, iy, set_iy);
}
impl Default for Z80Data {
    fn default() -> Self {
        Self::new()
    }
}

pub struct DefaultFuncHook {}
impl Default for DefaultFuncHook {
    fn default() -> Self {
        Self::new()
    }
}

impl DefaultFuncHook {
    pub(crate) fn new() -> Self {
        Self {}
    }
}
impl FuncHook for DefaultFuncHook {}

#[allow(non_snake_case)]
pub struct Z80<'a> {
    pub(super) data: Z80Data,

    pub(crate) memory: Memory,
    ports: Ports<'a>,
    pub(crate) hook: Rc<RefCell<dyn FuncHook>>,
}

#[allow(non_snake_case)]
impl<'a> Z80<'a> {
    pub fn new(memory: Memory, ports: Ports<'a>) -> Self {
        Self {
            data: Z80Data::default(),
            memory,
            ports,
            hook: Rc::new(RefCell::new(DefaultFuncHook::new())),
        }
    }
    pub fn set_hook(&mut self, hook: Rc<RefCell<dyn FuncHook>>) {
        self.hook = hook;
    }
    // Reset resets the Z80.
    pub(crate) fn reset(&mut self) {
        self.data.reset();
    }
    pub fn reset_cycles(&mut self) {
        self.data.cycles = 0;
    }
    pub fn get_cycles(&self) -> u64 {
        self.data.cycles
    }
    pub fn is_halted(&self) -> bool {
        self.data.halted
    }
    fn normalize_cycles(&mut self, cyclesPerFrame: u64) {
        self.data.cycles %= cyclesPerFrame;
    }
    fn can_run_within_frame(&self, cyclesPerFrame: u64) -> bool {
        self.data.cycles < cyclesPerFrame
    }
    pub fn run_test(&mut self) {
        while !self.is_halted() {
            do_opcode(
                &mut self.data,
                &mut self.memory,
                &mut self.ports,
                self.hook.clone(),
            )
        }
    }
    // Interrupt process a Z80 maskable interrupt
    pub(crate) fn interrupt(&mut self) {
        if self.data.IFF1 != 0 {
            if self.data.halted {
                self.data.pc += 1;
                self.data.halted = false;
            }

            self.data.t_states += 7;

            self.data.R = (self.data.R + 1) & 0x7f;
            (self.data.IFF1, self.data.IFF2) = (0, 0);

            // push PC
            {
                let (pch, pcl) = split_word(self.data.pc);

                self.data.sp -= 1;
                self.memory.write_byte(self.data.sp, pch);
                self.data.sp -= 1;
                self.memory.write_byte(self.data.sp, pcl);
            }

            match self.data.IM {
                0 | 1 => {
                    self.data.pc = 0x0038;
                }
                2 => {
                    let mut int_temp: u16 = ((self.data.I as u16) << 8) | 0xff;
                    let pcl = self.memory.read_byte(int_temp);
                    int_temp += 1;
                    let pch = self.memory.read_byte(int_temp);
                    self.data.pc = join_bytes(pch, pcl);
                }
                _ => {
                    panic!("Unknown interrupt mode");
                }
            }
        }
    }
    // Process a Z80 non-maskable interrupt.
    #[allow(dead_code)]
    pub(crate) fn non_maskable_interrupt(&mut self) {
        if self.data.halted {
            self.data.pc += 1;
            self.data.halted = false;
        }

        self.data.t_states += 7;

        self.data.R = (self.data.R + 1) & 0x7f;
        (self.data.IFF1, self.data.IFF2) = (0, 0);

        // push PC
        {
            let (pch, pcl) = split_word(self.data.pc);

            self.data.sp -= 1;
            self.memory.write_byte(self.data.sp, pch);
            self.data.sp -= 1;
            self.memory.write_byte(self.data.sp, pcl);
        }

        self.data.pc = 0x0066;
    }
    pub(crate) fn get_save_data(&self) -> (Z80Data, MemoryData, PPIData) {
        (
            self.data.clone(),
            self.memory.get_data(),
            self.memory.get_ppi_data(),
        )
    }
    pub(crate) fn set_save_data(
        &mut self,
        data: Z80Data,
        memoryData: MemoryData,
        ppiData: PPIData,
    ) {
        self.data = data;
        self.memory.set_data(memoryData);
        self.memory.set_ppi_data(ppiData);
    }
    pub fn reboot(&mut self) {
        self.reset();
        self.data.set_pc(0);
    }
    pub fn command_debug(&mut self, mode: u64) {
        self.hook.borrow_mut().handle_command_hook(
            &mut self.data,
            &mut self.memory,
            &mut self.ports,
            mode,
        )
    }
    pub(crate) fn run_one_frame(&mut self, cyclesPerFrame: u64) {
        self.normalize_cycles(cyclesPerFrame);
        while self.can_run_within_frame(cyclesPerFrame) {
            if self.is_halted() {
                break;
            }
            do_opcode(
                &mut self.data,
                &mut self.memory,
                &mut self.ports,
                self.hook.clone(),
            );
        }
    }
    pub fn check_keycodes(&mut self, event_pump: &mut EventPump) {
        self.ports.check_keycodes(event_pump);
    }
}

// Execute a single instruction at the program counter.
fn do_opcode(
    data: &mut Z80Data,
    memory: &mut Memory,
    ports: &mut Ports,
    hook: Rc<RefCell<dyn FuncHook>>,
) {
    if hook
        .borrow_mut()
        .handle_generic_hook(data, memory, ports)
        .is_continue()
    {
        return;
    }

    memory.contend_read(data.pc, 4);
    let opcode = memory.read_byte_internal(data.pc);
    data.R = (data.R + 1) & 0x7f;
    data.pc += 1;
    // data.cycles += get_timings[opcode](z80);
    data.cycles += get_timings(data, opcode as u16);

    // OpcodesMap[opcode](z80)
    if data.debug {
        disassemble_map(data, memory, opcode as u16);
    }
    match opcode {
        0xcb => {
            opcode_cb(data, memory, ports, hook);
        }
        0xdd => {
            opcode_dd(data, memory, ports, hook);
        }
        0xed => {
            opcode_ed(data, memory, ports, hook);
        }
        0xfd => {
            opcode_fd(data, memory, ports, hook);
        }
        _ => {
            execute_opcode(data, memory, ports, hook, opcode as u16);
        }
    }
}

fn opcode_cb(
    data: &mut Z80Data,
    memory: &mut Memory,
    ports: &mut Ports,
    hook: Rc<RefCell<dyn FuncHook>>,
) {
    memory.contend_read(data.pc, 4);
    let opcode2: u8 = memory.read_byte_internal(data.pc);
    data.pc += 1;
    data.R += 1;
    execute_opcode(data, memory, ports, hook, SHIFT_0X_CB + opcode2 as u16);
    data.cycles += get_timings(data, SHIFT_0X_CB + opcode2 as u16);
}

fn opcode_dd(
    data: &mut Z80Data,
    memory: &mut Memory,
    ports: &mut Ports,
    hook: Rc<RefCell<dyn FuncHook>>,
) {
    memory.contend_read(data.pc, 4);
    let opcode2: u8 = memory.read_byte_internal(data.pc);
    data.pc += 1;
    data.R += 1;

    match opcode2 {
        0xcb => {
            memory.contend_read(data.pc, 3);
            data.temp_addr = data.ix() + sign_extend(memory.read_byte_internal(data.pc)) as u16;
            data.pc += 1;
            memory.contend_read(data.pc, 3);
            let opcode3: u8 = memory.read_byte_internal(data.pc);
            memory.contend_read_no_mreq_loop(data.pc, 1, 2);
            data.pc += 1;
            execute_opcode(data, memory, ports, hook, SHIFT_0X_DDCB + (opcode3 as u16));
            data.cycles += get_timings(data, SHIFT_0X_DDCB + opcode3 as u16);
        }
        _ => {
            if execute_opcode(
                data,
                memory,
                ports,
                hook.clone(),
                SHIFT_0X_DD + (opcode2 as u16),
            ) {
                data.cycles += get_timings(data, SHIFT_0X_DD + (opcode2 as u16));
            } else {
                /* Instruction did not involve H or L */
                execute_opcode(data, memory, ports, hook, opcode2 as u16);
                data.cycles += get_timings(data, opcode2 as u16);
            }
        }
    }
}

fn opcode_ed(
    data: &mut Z80Data,
    memory: &mut Memory,
    ports: &mut Ports,
    hook: Rc<RefCell<dyn FuncHook>>,
) {
    memory.contend_read(data.pc, 4);
    let opcode2: u8 = memory.read_byte_internal(data.pc);
    data.pc += 1;
    data.R += 1;

    data.cycles += get_timings(data, SHIFT_0X_ED + opcode2 as u16);
    if !execute_opcode(
        data,
        memory,
        ports,
        hook.clone(),
        SHIFT_0X_ED + opcode2 as u16,
    ) {
        invalid_opcode();
    }
}

fn opcode_fd(
    data: &mut Z80Data,
    memory: &mut Memory,
    ports: &mut Ports,
    hook: Rc<RefCell<dyn FuncHook>>,
) {
    memory.contend_read(data.pc, 4);
    let opcode2: u8 = memory.read_byte_internal(data.pc);
    data.pc += 1;
    data.R += 1;

    match opcode2 {
        0xcb => {
            memory.contend_read(data.pc, 3);
            data.temp_addr = data.iy() + sign_extend(memory.read_byte_internal(data.pc)) as u16;
            data.pc += 1;
            memory.contend_read(data.pc, 3);
            let opcode3: u8 = memory.read_byte_internal(data.pc);
            memory.contend_read_no_mreq_loop(data.pc, 1, 2);
            data.pc += 1;

            execute_opcode(data, memory, ports, hook, SHIFT_0X_FDCB + (opcode3 as u16));
            data.cycles += get_timings(data, SHIFT_0X_FDCB + (opcode3 as u16));
        }

        _ => {
            if execute_opcode(
                data,
                memory,
                ports,
                hook.clone(),
                SHIFT_0X_FD + opcode2 as u16,
            ) {
                // f(z80)
                data.cycles += get_timings(data, SHIFT_0X_FD + opcode2 as u16);
            } else {
                /* Instruction did not involve H or L */
                execute_opcode(data, memory, ports, hook, opcode2 as u16);
                data.cycles += get_timings(data, opcode2 as u16);
            }
        }
    }
}

fn invalid_opcode() {
    panic!("invalid opcode");
}
// }