neser 1.2.0

NESER - Nintendo Emulation Systems Engine (Rust). Desktop and WebAssembly frontends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Game Boy debugger controller.
//!
//! Manages debugger state: breakpoints, stepping, pause/continue flags, and view state.
//! Handles the run-frame loop with breakpoint evaluation.

use super::snapshot::GbDebuggerViewState;
use crate::gb::bus::GbBus;
use crate::gb::console::{CpuTraceLine, Gb};
use crate::platform::debugging::breakpoints::{
    BreakpointKind, BreakpointList, EvalContext, GbInterruptKind,
};
use crate::platform::debugging::controller::DebuggerControllerCore;

// Opcodes for CALL and RST instructions (for step-over)
const CALL_OPCODE: u8 = 0xCD; // CALL n16
const CALL_NZ_OPCODE: u8 = 0xC4; // CALL NZ,n16
const CALL_Z_OPCODE: u8 = 0xCC; // CALL Z,n16
const CALL_NC_OPCODE: u8 = 0xD4; // CALL NC,n16
const CALL_C_OPCODE: u8 = 0xDC; // CALL C,n16
const RST_00_OPCODE: u8 = 0xC7;
const RST_08_OPCODE: u8 = 0xCF;
const RST_10_OPCODE: u8 = 0xD7;
const RST_18_OPCODE: u8 = 0xDF;
const RST_20_OPCODE: u8 = 0xE7;
const RST_28_OPCODE: u8 = 0xEF;
const RST_30_OPCODE: u8 = 0xF7;
const RST_38_OPCODE: u8 = 0xFF;
const DEFAULT_FRAME_BUDGET_M_CYCLES: u64 = 35_112;

/// Central debugger state for Game Boy.
pub struct GbDebuggerController {
    /// Shared core debugger state (paused, breakpoints, temporary breakpoint, etc.)
    core: DebuggerControllerCore<GbInterruptKind>,
    view_state: GbDebuggerViewState,
    /// Tracks breakpoints added by run_to operations that should be removed after hitting
    run_to_breakpoint: Option<BreakpointKind>,
}

impl GbDebuggerController {
    /// Create a new controller with optional pre-loaded breakpoints.
    pub fn new(config_breakpoints: &[BreakpointKind], debugger_enabled: bool) -> Self {
        Self {
            core: DebuggerControllerCore::new(config_breakpoints, debugger_enabled),
            view_state: GbDebuggerViewState::default(),
            run_to_breakpoint: None,
        }
    }

    // ── State getters ──────────────────────────────────────────────────

    pub fn is_paused(&self) -> bool {
        self.core.is_paused()
    }

    pub fn is_debugger_open(&self) -> bool {
        self.core.is_debugger_open()
    }

    pub fn breakpoints(&self) -> &BreakpointList {
        self.core.breakpoints()
    }

    pub fn breakpoints_mut(&mut self) -> &mut BreakpointList {
        self.core.breakpoints_mut()
    }

    pub fn view_state_mut(&mut self) -> &mut GbDebuggerViewState {
        &mut self.view_state
    }

    // ── Debugger open/close ────────────────────────────────────────────

    /// Open the debugger and pause emulation.
    pub fn enter_debugger<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        // Clear any leftover temporary breakpoints from previous run-to operations
        self.clear_temporary_breakpoint();
        // Remove run_to breakpoint if it was hit
        if let Some(kind) = self.run_to_breakpoint.take() {
            self.core.breakpoints_mut().remove_first_matching(&kind);
        }
        gb.set_cpu_trace_enabled(true);
        self.core.paused = true;
        self.core.debugger_open = true;
    }

    /// Close the debugger and resume emulation.
    pub fn continue_from_debugger<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        if self
            .core
            .breakpoints()
            .has_enabled_pc_breakpoint_at(gb.cpu.regs.pc)
        {
            self.core.breakpoint_ignore_once_at_pc = Some(gb.cpu.regs.pc);
        }

        self.core.last_post_instruction_cycles = gb.cpu.cycles();
        self.core.last_post_instruction_frame = gb.cpu.bus.ppu().frame_count();

        gb.set_cpu_trace_enabled(false);
        self.core.paused = false;
        self.core.debugger_open = false;
    }

    /// Toggle the debugger: open+pause if closed, continue if open.
    pub fn toggle_debugger<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        if self.core.debugger_open {
            self.continue_from_debugger(gb);
        } else {
            self.enter_debugger(gb);
        }
    }

    // ── Stepping ───────────────────────────────────────────────────────

    /// Execute one instruction and re-enter the debugger.
    pub fn step_into<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        if self.core.paused {
            self.core.paused = false;
            self.run_one_instruction(gb);
            self.core.paused = true;
        }
    }

    /// Step over CALL/RST instructions (break at return address).
    pub fn step_over<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        if !self.core.paused {
            return;
        }

        let pc = gb.cpu.regs.pc;
        let opcode = gb.read_for_debugger(pc);

        // Check if it's a CALL or RST instruction
        let is_call_or_rst = matches!(
            opcode,
            CALL_OPCODE
                | CALL_NZ_OPCODE
                | CALL_Z_OPCODE
                | CALL_NC_OPCODE
                | CALL_C_OPCODE
                | RST_00_OPCODE
                | RST_08_OPCODE
                | RST_10_OPCODE
                | RST_18_OPCODE
                | RST_20_OPCODE
                | RST_28_OPCODE
                | RST_30_OPCODE
                | RST_38_OPCODE
        );

        if is_call_or_rst {
            // Calculate return address (CALL is 3 bytes, RST is 1 byte)
            let return_addr = if opcode == CALL_OPCODE
                || opcode == CALL_NZ_OPCODE
                || opcode == CALL_Z_OPCODE
                || opcode == CALL_NC_OPCODE
                || opcode == CALL_C_OPCODE
            {
                pc.wrapping_add(3)
            } else {
                pc.wrapping_add(1)
            };

            self.set_temporary_breakpoint(return_addr);
            self.core.paused = false;
            self.core.debugger_open = false;
        } else {
            // Not a call - just step into
            self.step_into(gb);
        }
    }

    /// Run until next frame boundary.
    pub fn run_to_next_frame<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        if !self.core.paused {
            return;
        }

        let target_frame = gb.cpu.bus.ppu().frame_count() + 1;
        let kind = BreakpointKind::Frame(target_frame);
        self.core.breakpoints_mut().add(kind);
        self.run_to_breakpoint = Some(kind);
    }

    /// Run until next scanline.
    /// Run to next scanline (not yet implemented).
    ///
    /// Scanline stepping is not yet implemented for the Game Boy debugger.
    /// This method intentionally leaves the debugger paused rather than
    /// approximating with a frame breakpoint, which would be misleading.
    /// True scanline stepping support requires scanline polling with a
    /// max-steps guard or a dedicated breakpoint type.
    pub fn run_to_next_scanline<B: GbBus>(&mut self, _gb: &mut Gb<B>) {
        // Intentionally left as a no-op until true scanline stepping support
        // is implemented. Approximating with run_to_next_frame() would confuse
        // debugger users expecting single-scanline behavior.
    }

    /// Run until specific interrupt is about to fire.
    pub fn run_to_interrupt<B: GbBus>(&mut self, _gb: &mut Gb<B>, kind: GbInterruptKind) {
        if !self.core.paused {
            return;
        }

        let bp_kind = BreakpointKind::GbInterrupt(kind);
        self.core.breakpoints_mut().add(bp_kind);
        self.run_to_breakpoint = Some(bp_kind);
    }

    /// Apply UI actions from the debugger interface.
    ///
    /// Handles step over, step into, continue, run-to commands, and breakpoint management.
    pub fn apply_ui_action<B: GbBus>(
        &mut self,
        gb: &mut Gb<B>,
        action: super::ui::GbDebuggerUiAction,
    ) {
        if !self.core.debugger_open {
            return;
        }

        let mut should_continue = action.continue_run;

        if action.step_over {
            self.step_over(gb);
            should_continue = false; // step_over unpauses internally
        }

        if action.step_into {
            self.step_into(gb);
            should_continue = false; // step_into unpauses internally
        }

        if action.run_to_next_frame {
            self.run_to_next_frame(gb);
            should_continue = true; // will call continue_from_debugger
        }

        if action.run_to_next_scanline {
            self.run_to_next_scanline(gb);
            // Note: currently a no-op, leaves debugger paused
        }

        if action.run_to_vblank {
            self.run_to_interrupt(gb, GbInterruptKind::VBlank);
            should_continue = true; // will call continue_from_debugger
        }

        if action.run_to_stat {
            self.run_to_interrupt(gb, GbInterruptKind::Stat);
            should_continue = true; // will call continue_from_debugger
        }

        if action.run_to_timer {
            self.run_to_interrupt(gb, GbInterruptKind::Timer);
            should_continue = true; // will call continue_from_debugger
        }

        if should_continue {
            self.continue_from_debugger(gb);
        }

        if let Some(kind) = action.add_breakpoint {
            self.core.breakpoints_mut().add(kind);
        }
        if let Some(index) = action.remove_breakpoint {
            self.core.breakpoints_mut().remove(index);
        }
        if let Some(index) = action.enable_breakpoint {
            self.core.breakpoints_mut().enable(index);
        }
        if let Some(index) = action.disable_breakpoint {
            self.core.breakpoints_mut().disable(index);
        }
    }

    // ── Main execution loop ────────────────────────────────────────────

    /// Run the emulator until frame ready or debugger pause.
    ///
    /// audio_drain: callback to drain audio samples during execution.
    pub fn run_frame<B: GbBus, F>(&mut self, gb: &mut Gb<B>, audio_drain: &mut F)
    where
        F: FnMut(&mut Gb<B>),
    {
        self.run_frame_with_cycle_budget(gb, DEFAULT_FRAME_BUDGET_M_CYCLES, audio_drain);
    }

    /// Run the emulator until frame ready, debugger pause, or a frontend safety budget.
    ///
    /// The budget prevents native rendering from blocking forever before presenting
    /// a window if a ROM/hardware path fails to raise `frame_ready`.
    fn run_frame_with_cycle_budget<B: GbBus, F>(
        &mut self,
        gb: &mut Gb<B>,
        max_m_cycles: u64,
        audio_drain: &mut F,
    ) where
        F: FnMut(&mut Gb<B>),
    {
        if self.core.paused {
            return;
        }

        let start_cycles = gb.cycles();
        while !gb.is_frame_ready() {
            if gb.cycles().saturating_sub(start_cycles) >= max_m_cycles {
                return;
            }

            // Check pre-instruction breakpoints (PC, interrupt)
            if self.check_breakpoint_hit_pre_instruction(gb) {
                self.enter_debugger(gb);
                return;
            }

            // Execute one instruction
            self.run_one_instruction(gb);

            // Check post-instruction breakpoints (cycle, frame, write)
            if self.check_post_instruction_breakpoints(gb) {
                self.enter_debugger(gb);
                return;
            }

            // Drain audio
            audio_drain(gb);
        }
    }

    // ── Internal helpers ───────────────────────────────────────────────

    fn run_one_instruction<B: GbBus>(&mut self, gb: &mut Gb<B>) {
        // Capture trace before execution
        if gb.cpu_trace_enabled() {
            let pc = gb.cpu.regs.pc;
            let opcode = gb.read_for_debugger(pc);

            // Determine instruction length
            let len = if opcode == 0xCB {
                2
            } else {
                crate::gb::cpu::opcode::lookup(opcode).bytes() as usize
            };

            let mut bytes = Vec::with_capacity(len);
            for i in 0..len {
                bytes.push(gb.read_for_debugger(pc.wrapping_add(i as u16)));
            }

            let actual_op = if opcode == 0xCB {
                bytes.get(1).copied().unwrap_or(0)
            } else {
                opcode
            };
            let text = crate::gb::debugging::disasm::format_instruction(actual_op, pc, &bytes);

            gb.push_cpu_trace_line(CpuTraceLine {
                addr: pc,
                bytes,
                text,
            });
        }

        // Execute instruction
        gb.step();

        // Clear last write address after checking post-instruction breakpoints
        // (We need it for write-address breakpoint evaluation)
    }

    fn check_breakpoint_hit_pre_instruction<B: GbBus>(&mut self, gb: &Gb<B>) -> bool {
        let pc = gb.cpu.regs.pc;

        // Skip if we're ignoring this PC once
        if self.core.breakpoint_ignore_once_at_pc == Some(pc) {
            self.core.breakpoint_ignore_once_at_pc = None;
            return false;
        }

        // Build eval context for pre-instruction checks (PC, interrupt)
        let ie = gb.read_for_debugger(0xFFFF);
        let if_reg = gb.read_for_debugger(0xFF0F);
        let ime = gb.cpu.ime;

        let ctx = EvalContext {
            pc,
            prev_cpu_cycles: gb.cpu.cycles(),
            cpu_cycles: gb.cpu.cycles(),
            prev_frame: gb.cpu.bus.ppu().frame_count(),
            frame: gb.cpu.bus.ppu().frame_count(),
            write_addr: None,
            gb_ie: Some(ie),
            gb_if: Some(if_reg),
            gb_ime: Some(ime),
        };

        // Check temporary breakpoint first
        if let Some(ref mut tb) = self.core.temporary_breakpoint {
            // Check if we've exited the required interrupt
            if let Some(required) = tb.required_interrupt {
                let pending = (ie & if_reg & required.bit_mask()) != 0;
                if !pending && !tb.has_exited_required_interrupt {
                    tb.has_exited_required_interrupt = true;
                }
            }

            // Check if temporary breakpoint is hit
            if tb.pc == pc {
                let should_trigger = if let Some(required) = tb.required_interrupt {
                    tb.has_exited_required_interrupt
                        && (ie & if_reg & required.bit_mask()) != 0
                        && ime
                } else {
                    true
                };

                if should_trigger {
                    self.clear_temporary_breakpoint();
                    return true;
                }
            }

            // If ignoring other breakpoints, skip regular evaluation
            if tb.ignore_other_breakpoints {
                return false;
            }
        }

        // Check regular breakpoints
        self.core
            .breakpoints()
            .iter()
            .any(|bp| bp.enabled && bp.is_hit(&ctx))
    }

    fn check_post_instruction_breakpoints<B: GbBus>(&mut self, gb: &mut Gb<B>) -> bool {
        let cycles = gb.cpu.cycles();
        let frame = gb.cpu.bus.ppu().frame_count();
        let write_addr = gb.cpu.last_cpu_write_addr();

        // Skip temporary breakpoint interference
        if let Some(ref tb) = self.core.temporary_breakpoint
            && tb.ignore_other_breakpoints
        {
            self.core.last_post_instruction_cycles = cycles;
            self.core.last_post_instruction_frame = frame;
            return false;
        }

        let ctx = EvalContext {
            pc: gb.cpu.regs.pc,
            prev_cpu_cycles: self.core.last_post_instruction_cycles,
            cpu_cycles: cycles,
            prev_frame: self.core.last_post_instruction_frame,
            frame,
            write_addr,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
        };

        self.core.last_post_instruction_cycles = cycles;
        self.core.last_post_instruction_frame = frame;

        let hit = self
            .core
            .breakpoints()
            .iter()
            .any(|bp| bp.enabled && bp.is_hit(&ctx));

        // Clear last_write_addr after evaluating post-instruction breakpoints
        // to enforce strict "this instruction only" semantics for write-address
        // breakpoints. Even though the CPU clears at instruction boundary,
        // this extra clear ensures the debugger doesn't hold stale write info.
        gb.cpu.clear_last_write_addr();

        hit
    }

    // ── Temporary breakpoint management ────────────────────────────────

    fn clear_temporary_breakpoint(&mut self) {
        if let Some(tb) = self.core.temporary_breakpoint.take() {
            if tb.already_present {
                // Restore original enabled state
                if !tb.was_enabled_before {
                    self.core
                        .breakpoints_mut()
                        .set_pc_breakpoint_enabled(tb.pc, false);
                }
            } else {
                self.remove_pc_breakpoint(tb.pc);
            }
        }
    }

    fn set_temporary_breakpoint(&mut self, pc: u16) {
        use crate::platform::debugging::controller::TemporaryBreakpoint;
        self.clear_temporary_breakpoint();

        let already_present = self.core.breakpoints().has_pc_breakpoint_at(pc);
        let was_enabled_before = if already_present {
            self.core
                .breakpoints_mut()
                .force_enable_pc_breakpoint_at(pc)
                .unwrap_or(false)
        } else {
            self.add_pc_breakpoint(pc);
            true
        };

        self.core.temporary_breakpoint = Some(TemporaryBreakpoint::new(
            pc,
            already_present,
            was_enabled_before,
        ));
    }

    fn add_pc_breakpoint(&mut self, addr: u16) {
        self.core.breakpoints_mut().add(BreakpointKind::Pc(addr));
    }

    fn remove_pc_breakpoint(&mut self, addr: u16) {
        if let Some(idx) = self
            .core
            .breakpoints()
            .iter()
            .position(|b| b.kind == BreakpointKind::Pc(addr))
        {
            self.core.breakpoints_mut().remove(idx);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gb::bus::{DmgBus, GbBus};
    use crate::gb::cartridge::load_cartridge;
    use crate::gb::console::Gb;
    use crate::gb::model::DmgModel;
    use crate::gb::ppu::Ppu;

    // ── Test helpers ───────────────────────────────────────────────────

    fn minimal_cart_with_nop_loop() -> Box<dyn crate::gb::cartridge::GbCartridge> {
        let mut rom = vec![0u8; 0x8000];
        // Write NOP loop at $0000: NOP; JP $0000
        rom[0x0000] = 0x00; // NOP
        rom[0x0001] = 0xC3; // JP $0000
        rom[0x0002] = 0x00; // low byte
        rom[0x0003] = 0x00; // high byte
        // Cartridge header
        rom[0x0147] = 0x00; // ROM only
        rom[0x0148] = 0x00; // 32 KB
        rom[0x0149] = 0x00; // no RAM
        let chk = rom[0x0134..=0x014C]
            .iter()
            .fold(0u8, |acc, &b| acc.wrapping_sub(b).wrapping_sub(1));
        rom[0x014D] = chk;
        load_cartridge(&rom).expect("valid ROM")
    }

    fn default_controller() -> GbDebuggerController {
        GbDebuggerController::new(&[], false)
    }

    fn gb_with_nop_loop() -> Gb<DmgBus> {
        let bus = DmgBus::new(minimal_cart_with_nop_loop(), DmgModel::DmgB);
        let mut gb = Gb::new(bus);

        // Disable boot ROM so we can execute code from $0000
        gb.cpu.bus.write(0xFF50, 0x01);
        gb.cpu.regs.pc = 0x0000;
        gb
    }

    struct NoFrameBus {
        ppu: Ppu,
    }

    impl GbBus for NoFrameBus {
        fn read(&mut self, _addr: u16) -> u8 {
            0x00
        }

        fn write(&mut self, _addr: u16, _val: u8) {}

        fn ppu(&self) -> &Ppu {
            &self.ppu
        }

        fn read_for_debugger(&self, _addr: u16) -> u8 {
            0x00
        }
    }

    fn gb_without_frame_ready() -> Gb<NoFrameBus> {
        Gb::new(NoFrameBus { ppu: Ppu::new() })
    }

    // ── State management tests ─────────────────────────────────────────

    #[test]
    fn test_new_controller_is_not_paused_and_debugger_closed() {
        let ctrl = default_controller();
        assert!(!ctrl.is_paused());
        assert!(!ctrl.is_debugger_open());
    }

    #[test]
    fn test_new_controller_with_debugger_enabled() {
        let ctrl = GbDebuggerController::new(&[], true);
        assert!(ctrl.is_paused());
        assert!(ctrl.is_debugger_open());
    }

    #[test]
    fn test_new_controller_with_config_breakpoints() {
        let ctrl = GbDebuggerController::new(
            &[BreakpointKind::Pc(0xC000), BreakpointKind::Cycle(1000)],
            false,
        );
        assert_eq!(ctrl.breakpoints().len(), 2);
    }

    #[test]
    fn test_enter_debugger_sets_paused_and_open() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();
        ctrl.enter_debugger(&mut gb);
        assert!(ctrl.is_paused());
        assert!(ctrl.is_debugger_open());
    }

    #[test]
    fn test_continue_from_debugger_clears_paused_and_open() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);
        ctrl.continue_from_debugger(&mut gb);

        assert!(!ctrl.is_paused());
        assert!(!ctrl.is_debugger_open());
    }

    #[test]
    fn test_toggle_debugger_opens_when_closed() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.toggle_debugger(&mut gb);
        assert!(ctrl.is_paused());
        assert!(ctrl.is_debugger_open());
    }

    #[test]
    fn test_toggle_debugger_closes_when_open() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);
        ctrl.toggle_debugger(&mut gb);

        assert!(!ctrl.is_paused());
        assert!(!ctrl.is_debugger_open());
    }

    // ── Stepping tests ─────────────────────────────────────────────────

    #[test]
    fn test_step_into_executes_one_instruction() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);
        let initial_pc = gb.cpu.regs.pc;

        ctrl.step_into(&mut gb);

        // NOP should advance PC by 1
        assert_eq!(gb.cpu.regs.pc, initial_pc.wrapping_add(1));
        assert!(ctrl.is_paused());
    }

    #[test]
    fn test_step_over_on_nop_behaves_like_step_into() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);
        let initial_pc = gb.cpu.regs.pc;

        ctrl.step_over(&mut gb);

        // NOP is not a CALL/RST, should just step
        assert_eq!(gb.cpu.regs.pc, initial_pc.wrapping_add(1));
        assert!(ctrl.is_paused());
    }

    // ── Breakpoint tests ───────────────────────────────────────────────

    #[test]
    fn test_pc_breakpoint_pauses_execution() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        // Add breakpoint at PC+1
        ctrl.breakpoints_mut().add(BreakpointKind::Pc(0x0001));

        let mut audio_drain = |_: &mut Gb<DmgBus>| {};

        // Run should stop at breakpoint
        ctrl.run_frame(&mut gb, &mut audio_drain);

        assert_eq!(gb.cpu.regs.pc, 0x0001);
        assert!(ctrl.is_paused());
        assert!(
            ctrl.is_debugger_open(),
            "Debugger should open when breakpoint is hit"
        );
    }

    #[test]
    fn test_run_frame_returns_when_frame_budget_is_exhausted() {
        let mut ctrl = default_controller();
        let mut gb = gb_without_frame_ready();
        let mut audio_drain = |_: &mut Gb<NoFrameBus>| {};

        ctrl.run_frame_with_cycle_budget(&mut gb, 8, &mut audio_drain);

        assert!(
            gb.cycles() >= 8,
            "run_frame should execute until the safety budget is reached"
        );
        assert!(
            !ctrl.is_paused(),
            "exhausting the safety budget should not enter the debugger"
        );
        assert!(
            !gb.is_frame_ready(),
            "test bus intentionally never produces a complete frame"
        );
    }

    #[test]
    fn test_breakpoint_ignore_once_on_continue() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        // Set PC to where we have a breakpoint
        gb.cpu.regs.pc = 0x0001;
        ctrl.breakpoints_mut().add(BreakpointKind::Pc(0x0001));

        ctrl.enter_debugger(&mut gb);
        ctrl.continue_from_debugger(&mut gb);

        // Should set ignore flag so we don't immediately re-trigger
        assert!(ctrl.core.breakpoint_ignore_once_at_pc.is_some());
    }

    #[test]
    fn test_step_over_on_call_sets_temporary_breakpoint() {
        let mut ctrl = default_controller();

        // Create ROM with CALL instruction
        let mut rom = vec![0u8; 0x8000];
        rom[0x0000] = 0xCD; // CALL n16
        rom[0x0001] = 0x10; // target low
        rom[0x0002] = 0xC0; // target high -> CALL $C010
        rom[0x0010] = 0xC9; // RET at target
        // Cartridge header
        rom[0x0147] = 0x00;
        rom[0x0148] = 0x00;
        rom[0x0149] = 0x00;
        let chk = rom[0x0134..=0x014C]
            .iter()
            .fold(0u8, |acc, &b| acc.wrapping_sub(b).wrapping_sub(1));
        rom[0x014D] = chk;

        let cart = load_cartridge(&rom).expect("valid ROM");
        let bus = DmgBus::new(cart, DmgModel::DmgB);
        let mut gb = Gb::new(bus);

        gb.cpu.bus.write(0xFF50, 0x01); // Disable boot ROM
        gb.cpu.regs.pc = 0x0000;

        ctrl.enter_debugger(&mut gb);
        ctrl.step_over(&mut gb);

        // Should have set temporary breakpoint at return address (PC + 3)
        assert!(ctrl.core.temporary_breakpoint.is_some());
        let temp_bp = ctrl.core.temporary_breakpoint.as_ref().unwrap();
        assert_eq!(temp_bp.pc, 0x0003);
        // Should unpause and close debugger UI to run until breakpoint
        assert!(!ctrl.is_paused());
        assert!(!ctrl.is_debugger_open());
    }

    #[test]
    fn test_step_over_on_rst_sets_temporary_breakpoint() {
        let mut ctrl = default_controller();

        // Create ROM with RST instruction
        let mut rom = vec![0u8; 0x8000];
        rom[0x0000] = 0xC7; // RST $00
        rom[0x0001] = 0x00; // next instruction
        // Cartridge header
        rom[0x0147] = 0x00;
        rom[0x0148] = 0x00;
        rom[0x0149] = 0x00;
        let chk = rom[0x0134..=0x014C]
            .iter()
            .fold(0u8, |acc, &b| acc.wrapping_sub(b).wrapping_sub(1));
        rom[0x014D] = chk;

        let cart = load_cartridge(&rom).expect("valid ROM");
        let bus = DmgBus::new(cart, DmgModel::DmgB);
        let mut gb = Gb::new(bus);

        gb.cpu.bus.write(0xFF50, 0x01);
        gb.cpu.regs.pc = 0x0000;

        ctrl.enter_debugger(&mut gb);
        ctrl.step_over(&mut gb);

        // Should have set temporary breakpoint at return address (PC + 1)
        assert!(ctrl.core.temporary_breakpoint.is_some());
        let temp_bp = ctrl.core.temporary_breakpoint.as_ref().unwrap();
        assert_eq!(temp_bp.pc, 0x0001);
        // Should unpause and close debugger UI to run until breakpoint
        assert!(!ctrl.is_paused());
        assert!(!ctrl.is_debugger_open());
    }

    // ── UI Action tests ────────────────────────────────────────────────

    #[test]
    fn test_apply_ui_action_run_to_next_scanline() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);

        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            run_to_next_scanline: true,
            ..Default::default()
        };

        ctrl.apply_ui_action(&mut gb, action);

        // Currently run_to_next_scanline is a no-op, so should stay paused
        assert!(ctrl.is_paused());
    }

    #[test]
    fn test_apply_ui_action_run_to_next_frame() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);

        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            run_to_next_frame: true,
            ..Default::default()
        };

        ctrl.apply_ui_action(&mut gb, action);

        // Should have added a Frame breakpoint (not a temporary PC breakpoint)
        assert!(
            ctrl.breakpoints()
                .iter()
                .any(|bp| matches!(bp.kind, BreakpointKind::Frame(_))),
            "should have added Frame breakpoint"
        );
        assert!(!ctrl.is_paused(), "should be running");
        assert!(!ctrl.is_debugger_open(), "debugger should be closed");
    }

    #[test]
    fn test_apply_ui_action_run_to_vblank() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb);

        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            run_to_vblank: true,
            ..Default::default()
        };

        ctrl.apply_ui_action(&mut gb, action);

        // Should have added a GbInterrupt breakpoint (not a temporary PC breakpoint)
        assert!(
            ctrl.breakpoints().iter().any(|bp| matches!(
                bp.kind,
                BreakpointKind::GbInterrupt(GbInterruptKind::VBlank)
            )),
            "should have added VBlank interrupt breakpoint"
        );
        assert!(!ctrl.is_paused(), "should be running");
        assert!(!ctrl.is_debugger_open(), "debugger should be closed");
    }

    #[test]
    fn test_apply_ui_action_add_breakpoint() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb); // Open debugger

        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            add_breakpoint: Some(BreakpointKind::Pc(0xC000)),
            ..Default::default()
        };

        ctrl.apply_ui_action(&mut gb, action);

        // Should have added breakpoint
        assert_eq!(ctrl.breakpoints().len(), 1);
        assert!(
            ctrl.breakpoints()
                .iter()
                .any(|b| b.kind == BreakpointKind::Pc(0xC000))
        );
    }

    #[test]
    fn test_apply_ui_action_remove_breakpoint() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb); // Open debugger

        // Add a breakpoint first
        ctrl.breakpoints_mut().add(BreakpointKind::Pc(0xC000));
        ctrl.breakpoints_mut().add(BreakpointKind::Cycle(1000));

        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            remove_breakpoint: Some(0),
            ..Default::default()
        };

        ctrl.apply_ui_action(&mut gb, action);

        // Should have removed first breakpoint
        assert_eq!(ctrl.breakpoints().len(), 1);
        assert!(
            ctrl.breakpoints()
                .iter()
                .any(|b| b.kind == BreakpointKind::Cycle(1000))
        );
    }

    #[test]
    fn test_apply_ui_action_enable_disable_breakpoint() {
        let mut ctrl = default_controller();
        let mut gb = gb_with_nop_loop();

        ctrl.enter_debugger(&mut gb); // Open debugger

        // Add a breakpoint
        ctrl.breakpoints_mut().add(BreakpointKind::Pc(0xC000));
        assert!(ctrl.breakpoints().iter().next().unwrap().enabled);

        // Disable it
        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            disable_breakpoint: Some(0),
            ..Default::default()
        };
        ctrl.apply_ui_action(&mut gb, action);

        // Should have disabled breakpoint
        assert!(!ctrl.breakpoints().iter().next().unwrap().enabled);

        // Enable it again
        let action = crate::gb::debugging::ui::GbDebuggerUiAction {
            enable_breakpoint: Some(0),
            ..Default::default()
        };
        ctrl.apply_ui_action(&mut gb, action);

        // Should be enabled again
        assert!(ctrl.breakpoints().iter().next().unwrap().enabled);
    }

    // ── PC advancement tests ───────────────────────────────────────────

    #[test]
    fn test_step_into_advances_pc_by_one_instruction() {
        let mut gb = gb_with_nop_loop();
        let mut ctrl = default_controller();
        ctrl.enter_debugger(&mut gb);

        // Set PC to 0x0000 (NOP instruction, 1 byte)
        gb.cpu.regs.pc = 0x0000;
        let pc_before = gb.cpu.regs.pc;

        // Step one instruction
        ctrl.step_into(&mut gb);

        // Should advance by exactly 1 byte (NOP is 1 byte)
        assert_eq!(
            gb.cpu.regs.pc,
            pc_before + 1,
            "step_into should execute exactly one NOP instruction"
        );
    }

    #[test]
    fn test_step_over_non_call_advances_pc_by_one_instruction() {
        let mut gb = gb_with_nop_loop();
        let mut ctrl = default_controller();
        ctrl.enter_debugger(&mut gb);

        // Set PC to 0x0000 (NOP instruction, 1 byte)
        gb.cpu.regs.pc = 0x0000;
        let pc_before = gb.cpu.regs.pc;

        // Step over (NOP is not a CALL, so should behave like step_into)
        ctrl.step_over(&mut gb);

        // Should advance by exactly 1 byte
        assert_eq!(
            gb.cpu.regs.pc,
            pc_before + 1,
            "step_over on NOP should execute exactly one instruction"
        );
    }

    // ── View state tests ───────────────────────────────────────────────

    #[test]
    fn test_view_state_is_accessible() {
        let mut ctrl = default_controller();
        let view_state = ctrl.view_state_mut();

        // Should be able to modify view state
        view_state.set_wram_hexdump_base(0xC100);
        assert_eq!(ctrl.view_state_mut().wram_hexdump_base(), Some(0xC100));
    }
}