systemless 0.106.0

High-Level Emulation for classic Macintosh applications
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
use super::*;
use crate::callback_manager::CallbackTaskArchitecture;
use crate::execution_kernel::{ExecutionTaskId, ExecutionTaskState};
use crate::guest_call::{M68kResultTarget, M68kResume, PowerPcReturnState};
use crate::memory::globals::addr;
use crate::mixed_mode::special_case;
use ppc::PpcRunResult;
use std::collections::HashMap;

#[test]
fn ppc_initialization_attaches_both_cpu_adapters_to_one_guest_call_stack() {
    let app = halted_ppc_app_with_sound(PpcSoundState::default());
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);

    runner.dispatcher.guest_calls.begin_m68k(
        crate::guest_call::GuestCallTarget {
            isa: crate::guest_procedure::GuestIsa::M68k,
            entry: 0x1000,
            rtoc: 0,
        },
        0x2000,
        0x3000,
    );
    let ppc_app = runner.native.application_mut().expect("PPC app");
    assert_eq!(ppc_app.toolbox_startup.execution.calls().len(), 1);
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .complete_m68k(0x2002, 0x3000));
    assert!(runner.dispatcher.guest_calls.is_empty());
}

#[test]
fn ppc_initialization_attaches_both_cpu_adapters_to_one_sound_manager() {
    let app = halted_ppc_app_with_sound(PpcSoundState::default());
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);

    {
        let ppc_app = runner.native.application_mut().expect("PPC app");
        assert!(ppc_app
            .sound
            .manager
            .ptr_eq(&runner.dispatcher.sound_manager));
        ppc_app.sound.manager.register_channel(
            0x0050_1000,
            false,
            0x0012_3456,
            CallbackTaskArchitecture::M68k,
        );
        ppc_app.sound.manager.set_default_output_volume(0x0000_8000);
    }

    let classic_callback = runner
        .dispatcher
        .sound_manager
        .with_channel_mut(0x0050_1000, |channel| {
            channel.set_volume(0x0000_4000);
            channel.callback_addr
        })
        .expect("native channel visible to classic adapter");
    assert_eq!(classic_callback, 0x0012_3456);
    runner
        .dispatcher
        .sound_manager
        .set_sys_beep_volume(0x0000_2000);

    let ppc_app = runner.native.application().expect("PPC app");
    assert_eq!(ppc_app.sound.manager.default_output_volume(), 0x0000_8000);
    assert_eq!(ppc_app.sound.manager.sys_beep_volume(), 0x0000_2000);
    assert!(ppc_app
        .sound
        .manager
        .channels
        .iter()
        .any(|channel| channel.guest_ptr == 0x0050_1000));
}

#[test]
fn ppc_initialization_shares_current_resource_file_and_detaches_clones() {
    let app = halted_ppc_app_with_sound(PpcSoundState::default());
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner
        .dispatcher
        .set_loaded_resources_for_test(LoadedResources {
            files: HashMap::from([
                (5, ResourceFileMap::default()),
                (9, ResourceFileMap::default()),
            ]),
            names: HashMap::new(),
            search_order: vec![5, 9],
            current_file: 5,
        });
    runner.init_app(&app);

    assert_eq!(runner.dispatcher.current_resource_refnum(), 5);
    assert_eq!(
        runner
            .native
            .application()
            .expect("PPC app")
            .current_resource_refnum(),
        5
    );

    runner
        .dispatcher
        .set_current_resource_refnum(&mut runner.bus, 9);
    assert_eq!(
        runner
            .native
            .application()
            .expect("PPC app")
            .current_resource_refnum(),
        9
    );
    assert_eq!(runner.bus.read_word(0x0A5A), 9);

    runner
        .native
        .application_mut()
        .expect("PPC app")
        .set_current_resource_refnum(5);
    assert_eq!(runner.dispatcher.current_resource_refnum(), 5);
    assert_eq!(runner.bus.read_word(0x0A5A), 5);

    let mut detached = runner.native.application().expect("PPC app").clone();
    runner
        .native
        .application_mut()
        .expect("PPC app")
        .set_current_resource_refnum(9);
    assert_eq!(detached.current_resource_refnum(), 5);
    detached.set_current_resource_refnum(7);
    assert_eq!(runner.dispatcher.current_resource_refnum(), 9);
    assert_eq!(runner.bus.read_word(0x0A5A), 9);

    runner
        .native
        .application_mut()
        .expect("PPC app")
        .set_current_resource_refnum(5);
    assert!(runner
        .dispatcher
        .close_resource_file_refnum(&mut runner.bus, 5));
    assert_eq!(runner.dispatcher.current_resource_refnum(), 9);
    assert_eq!(runner.bus.read_word(0x0A5A), 9);
}

#[test]
fn relaunch_with_pending_execution_preserves_the_existing_engine() {
    let app = halted_ppc_app_with_sound(PpcSoundState::default());
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    let calls = runner.dispatcher.guest_calls.shared_handle();
    runner.m68k.cpu.write_reg(Register::PC, 0x1234);
    assert!(calls.begin_m68k(
        crate::guest_call::GuestCallTarget {
            isa: crate::guest_procedure::GuestIsa::M68k,
            entry: 0x1000,
            rtoc: 0,
        },
        0x2000,
        0x3000
    ));
    let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| runner.init_app(&app)));
    assert!(rejected.is_err());
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0x1234);
    assert!(!calls.is_empty());
    assert!(calls.complete_m68k(0x2002, 0x3000));
    runner.init_app(&app);
    assert!(runner.m68k.can_relaunch());
    let worker = calls
        .create_native_thread(
            crate::guest_call::NativeThreadContext {
                context: PpcCpu::new().capture_execution_context(),
            },
            crate::guest_call::ThreadStorage {
                result_destination: 0,
                stack_base: 0,
                stack_limit: 0,
                managed_pointer: true,
            },
            true,
            |_| true,
        )
        .unwrap();
    let native_pc = runner.native.application().unwrap().cpu.pc;
    let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| runner.init_app(&app)));
    assert!(rejected.is_err());
    assert_eq!(runner.native.application().unwrap().cpu.pc, native_pc);
    assert!(calls.scheduling_state(worker).is_some());
    assert!(calls.set_scheduling_state(worker, ExecutionTaskState::Ready));
    {
        let cpu = &mut runner.native.application_mut().unwrap().cpu;
        assert!(calls.yield_native_thread(cpu, worker.thread_id()).unwrap());
        assert!(calls
            .yield_native_thread(cpu, ExecutionTaskId::APPLICATION.thread_id())
            .unwrap());
        assert!(calls
            .retire_native_thread(worker, cpu, false, |_| true)
            .is_ok());
    }
    assert_eq!(calls.scheduling_state(worker), None);
    assert!(!calls.switch_to_task(worker));
    runner.set_launch_state(41, 1, u64::MAX);
    runner.init_app(&app);
    assert_eq!(
        runner.native.application().unwrap().cpu.time_base(),
        u64::MAX
    );
    {
        let cpu = &mut runner.native.application_mut().unwrap().cpu;
        assert_eq!(
            cpu.step_instruction((31 << 26) | (11 << 21) | (12 << 16) | (8 << 11) | (371 << 1)),
            ppc::PpcStepResult::Stepped
        );
        assert_eq!(cpu.gpr[11], u32::MAX);
        assert_eq!(cpu.time_base(), 0);
    }
    let mut replacement = ppc::PpcExecutionContext::fresh();
    replacement.architectural_mut().gpr[20] = 0xaabb_ccdd;
    let replacement = calls
        .create_native_thread(
            crate::guest_call::NativeThreadContext {
                context: replacement,
            },
            crate::guest_call::ThreadStorage::default(),
            false,
            |_| true,
        )
        .unwrap();
    let cpu = &mut runner.native.application_mut().unwrap().cpu;
    assert!(calls
        .yield_native_thread(cpu, replacement.thread_id())
        .unwrap());
    assert_eq!(cpu.gpr[20], 0xaabb_ccdd);
    assert_eq!(cpu.time_base(), 0);
}

#[test]
fn malformed_m68k_return_shapes_leave_registers_unchanged() {
    let mut cpu = M68kCpu::new();
    let mut memory = PpcSectionMem::new();
    cpu.core.set_d(0, 0xabcd_1234);
    cpu.core.set_a(0, 0x1234_abcd);
    cpu.core.set_ccr(0x15);
    for target in [
        M68kResultTarget::Data { index: 8, size: 4 },
        M68kResultTarget::Address { index: 8, size: 4 },
        M68kResultTarget::Data { index: 0, size: 3 },
        M68kResultTarget::SpecialCase {
            selector: crate::mixed_mode::special_case::TE_FIND_WORD as u8,
            scratch: u32::MAX,
        },
    ] {
        assert!(!M68kExecution::apply_m68k_resume_result(
            &mut cpu,
            &mut memory,
            M68kResume {
                return_pc: 0x1000,
                final_sp: 0x2000,
                result: Some(target),
                powerpc: PowerPcReturnState { gpr3: 42 },
            }
        ));
        assert_eq!(cpu.core.d(0), 0xabcd_1234);
        assert_eq!(cpu.core.a(0), 0x1234_abcd);
        assert_eq!(cpu.core.get_ccr(), 0x15);
    }
}

#[test]
fn parked_m68k_caller_receives_native_register_and_ccr_results() {
    const RETURN_PC: u32 = 0x0306_5000;
    const FINAL_SP: u32 = 0x0306_6000;
    for target in [
        M68kResultTarget::Data { index: 2, size: 4 },
        M68kResultTarget::Address { index: 3, size: 4 },
        M68kResultTarget::Ccr { mask: 4 },
        M68kResultTarget::SpecialCase {
            selector: special_case::WIDTH_HOOK as u8,
            scratch: 0,
        },
    ] {
        let app = halted_ppc_app_with_sound(PpcSoundState::default());
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner.init_app(&app);
        let mut native_context = runner.native.take(NativeEngineRole::Application).unwrap();
        let mut ppc_app = native_context.adapter_mut();
        assert!(ppc_app
            .toolbox_startup
            .execution
            .calls()
            .begin_m68k_to_powerpc(
                crate::guest_call::GuestCallTarget {
                    isa: crate::guest_procedure::GuestIsa::PowerPc,
                    entry: PPC_CODE_BASE,
                    rtoc: 0,
                },
                crate::guest_call::PowerPcArguments::from_slice(&[]).unwrap(),
                RETURN_PC,
                FINAL_SP,
                Some(target),
            ));
        ppc_app
            .toolbox_startup
            .execution
            .calls()
            .activate_powerpc_from_m68k(&mut ppc_app.cpu, RETURN_PC)
            .unwrap();
        ppc_app.cpu.pc = RETURN_PC;
        ppc_app.cpu.gpr[3] = 0x1234_5678;
        assert!(ppc_app
            .toolbox_startup
            .execution
            .calls()
            .complete_powerpc_for_m68k(&mut ppc_app.cpu));
        let (task, call_id) = ppc_app
            .toolbox_startup
            .execution
            .calls()
            .pending_m68k_resume_owner()
            .unwrap();
        runner.m68k.cpu.core.set_d(1, 0xabcd_0000);
        runner.m68k.cpu.core.set_d(7, 0xcafe_babe);
        runner.m68k.cpu.core.set_ccr(0x11);
        assert!(ppc_app
            .guest_calls()
            .park_context(
                &mut runner
                    .dispatcher
                    .guest_calls
                    .m68k_context_bank()
                    .borrow_mut(),
                task,
                call_id,
                std::mem::take(&mut runner.m68k.cpu),
            )
            .is_ok());
        assert!(runner.resume_m68k_after_powerpc(&mut ppc_app), "{target:?}");
        match target {
            M68kResultTarget::Data { .. } => assert_eq!(runner.m68k.cpu.core.d(2), 0x1234_5678),
            M68kResultTarget::Address { .. } => {
                assert_eq!(runner.m68k.cpu.core.a(3), 0x1234_5678)
            }
            M68kResultTarget::Ccr { .. } => assert_eq!(runner.m68k.cpu.core.get_ccr(), 0x15),
            M68kResultTarget::SpecialCase { .. } => {
                assert_eq!(runner.m68k.cpu.core.d(1), 0xabcd_5678)
            }
            _ => unreachable!(),
        }
        assert_eq!(runner.m68k.cpu.core.d(7), 0xcafe_babe);
        assert_eq!(runner.m68k.cpu.read_reg(Register::PC), RETURN_PC);
        assert_eq!(runner.m68k.cpu.read_reg(Register::A7), FINAL_SP);
        assert!(ppc_app.toolbox_startup.execution.calls().is_empty());
        assert!(runner
            .dispatcher
            .guest_calls
            .m68k_context_bank()
            .borrow()
            .is_empty());
    }
}

#[test]
fn failed_m68k_result_application_keeps_resume_and_parked_context_retryable() {
    const RESULT: u32 = 0x0306_4000;
    const RETURN_PC: u32 = 0x0306_5000;
    const FINAL_SP: u32 = 0x0306_6000;
    const RESULT_VALUE: u32 = 0x1234_5678;
    const PARKED_D0: u32 = 0xA11C_E001;

    let app = halted_ppc_app_with_sound(PpcSoundState::default());
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    let mut native_context = runner
        .native
        .take(NativeEngineRole::Application)
        .expect("PPC app");
    let mut ppc_app = native_context.adapter_mut();
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .begin_m68k_to_powerpc(
            crate::guest_call::GuestCallTarget {
                isa: crate::guest_procedure::GuestIsa::PowerPc,
                entry: PPC_CODE_BASE,
                rtoc: 0,
            },
            crate::guest_call::PowerPcArguments::from_slice(&[]).unwrap(),
            RETURN_PC,
            FINAL_SP,
            Some(M68kResultTarget::Memory {
                address: RESULT,
                size: 4,
            }),
        ));
    ppc_app
        .toolbox_startup
        .execution
        .calls()
        .activate_powerpc_from_m68k(&mut ppc_app.cpu, RETURN_PC)
        .unwrap();
    ppc_app.cpu.pc = RETURN_PC;
    ppc_app.cpu.gpr[3] = RESULT_VALUE;
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .complete_powerpc_for_m68k(&mut ppc_app.cpu));

    // Model the caller parked by a nested native-to-68K transition. The
    // failed write must not consume either this context or its completion.
    let (task, call_id) = ppc_app
        .guest_calls()
        .pending_m68k_resume_owner()
        .expect("completed continuation owner");
    runner.m68k.cpu.core.set_d(0, PARKED_D0);
    assert!(ppc_app
        .guest_calls()
        .park_context(
            &mut runner
                .dispatcher
                .guest_calls
                .m68k_context_bank()
                .borrow_mut(),
            task,
            call_id,
            std::mem::take(&mut runner.m68k.cpu),
        )
        .is_ok());
    assert_eq!(
        runner
            .dispatcher
            .guest_calls
            .m68k_context_bank()
            .borrow()
            .task_len(task),
        1
    );
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .peek_m68k_resume()
        .is_some());

    assert!(!runner.resume_m68k_after_powerpc(&mut ppc_app));
    assert_eq!(
        runner
            .dispatcher
            .guest_calls
            .m68k_context_bank()
            .borrow()
            .task_len(task),
        1
    );
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .peek_m68k_resume()
        .is_some());

    ppc_app.memory.add_readonly_region(RESULT, vec![0xaa; 4]);
    assert!(!runner.resume_m68k_after_powerpc(&mut ppc_app));
    assert_eq!(ppc_app.memory.read_u32_be(RESULT), Some(0xaaaa_aaaa));
    assert_eq!(
        runner
            .dispatcher
            .guest_calls
            .m68k_context_bank()
            .borrow()
            .task_len(task),
        1
    );
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .peek_m68k_resume()
        .is_some());

    ppc_app.memory.add_region(RESULT, vec![0; 4]);
    assert!(runner.resume_m68k_after_powerpc(&mut ppc_app));
    assert_eq!(
        runner
            .dispatcher
            .guest_calls
            .m68k_context_bank()
            .borrow()
            .task_len(task),
        0
    );
    assert!(ppc_app
        .toolbox_startup
        .execution
        .calls()
        .peek_m68k_resume()
        .is_none());
    assert_eq!(ppc_app.memory.read_u32_be(RESULT), Some(RESULT_VALUE));
    assert_eq!(runner.m68k.cpu.core.d(0), PARKED_D0);
}

#[test]
fn ppc_exit_to_shell_stops_before_tick_and_callback_phase() {
    const CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
    let mut sound = PpcSoundState::default();
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, CALLBACK);
    let mut app = halted_ppc_app_with_sound(sound);
    let ppc_app = app.ppc.as_mut().expect("PPC app");
    ppc_app
        .memory
        .add_region(CALLBACK, 0x4e80_0020u32.to_be_bytes().to_vec());
    ppc_app
        .memory
        .write_u32_be(
            PPC_CODE_BASE,
            ppc_test_relative_branch(PPC_CODE_BASE, PPC_IMPORT_TRAP_BASE),
        )
        .unwrap();
    let mut exit = test_ppc_import_binding(0, "InterfaceLib", "ExitToShell");
    exit.trap_pc = PPC_IMPORT_TRAP_BASE;
    exit.dispatcher_target = PpcImportDispatcherTarget::ExitToShell;
    ppc_app.import_count = 1;
    ppc_app.imports = vec![exit];
    ppc_app.vbl_tasks.push(PpcVblTaskRecord {
        task_ptr: PPC_DATA_BASE + 0x3000,
        architecture: CallbackTaskArchitecture::PowerPc,
        slot: None,
        pending: false,
    });
    ppc_app.timer_tasks.push(PpcTimerTaskRecord {
        task_ptr: PPC_DATA_BASE + 0x3100,
        architecture: CallbackTaskArchitecture::PowerPc,
        extended: false,
        callback: CALLBACK,
        active: true,
        fire_at_tick: 0,
        fire_at_subtick: 0,
        last_fired_tick: None,
    });

    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    runner.set_instructions_per_tick(1_000_000);
    runner.tick_budget = 1_000_000;
    let initial_tick = runner.guest_tick();
    let initial_screen_events = runner.dispatcher.screen_event_count;

    let (_steps, running) = runner.run_steps(64, None);

    assert!(!running);
    assert!(runner.halted_by_exit_to_shell());
    assert_eq!(runner.guest_tick(), initial_tick);
    assert_eq!(runner.guest_tick(), initial_tick);
    assert_eq!(runner.dispatcher.screen_event_count, initial_screen_events);
    let ppc_app = runner.native.application().expect("PPC app retained");
    assert_eq!(ppc_app.vbl_tasks.len(), 1);
    assert_eq!(ppc_app.timer_tasks[0].last_fired_tick, None);
    assert_eq!(ppc_app.sound.manager.pending_sound_callbacks.len(), 1);
    assert!(ppc_app.sound.completion_invocations.is_empty());
}

const PPC_SOUND_EVENT_RECORD: u32 = PPC_DATA_BASE + 0x2000;
const PPC_SOUND_GET_EVENT_CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
const PPC_SOUND_POST_EVENT_CALLBACK: u32 = PPC_CODE_BASE + 0x1100;
const PPC_SOUND_SET_EVENT_MASK_CALLBACK: u32 = PPC_CODE_BASE + 0x1200;

fn install_ppc_sound_event_boundary_fixture(app: &mut LoadedApp) {
    let ppc_app = app.ppc.as_mut().expect("PPC app");
    let mut add_callback = |address: u32, mut words: Vec<u32>, import_index: u32| {
        let branch_address = address + u32::try_from(words.len()).unwrap() * 4;
        words.push(ppc_test_relative_branch(
            branch_address,
            PPC_IMPORT_TRAP_BASE + import_index * 4,
        ));
        ppc_app.memory.add_region(
            address,
            words.into_iter().flat_map(u32::to_be_bytes).collect(),
        );
    };
    add_callback(
        PPC_SOUND_GET_EVENT_CALLBACK,
        vec![
            0x3860_ffff, // li r3,-1
            0x3c80_0200, // lis r4,$0200
            0x6084_2000, // ori r4,r4,$2000
        ],
        0,
    );
    add_callback(
        PPC_SOUND_POST_EVENT_CALLBACK,
        vec![
            0x3860_0005, // li r3,5
            0x3c80_5566, // lis r4,$5566
            0x6084_7788, // ori r4,r4,$7788
        ],
        1,
    );
    add_callback(
        PPC_SOUND_SET_EVENT_MASK_CALLBACK,
        vec![0x3860_1234], // li r3,$1234
        2,
    );
    ppc_app
        .memory
        .add_region(PPC_SOUND_EVENT_RECORD, vec![0; 16]);
    ppc_app.import_count = 3;
    ppc_app.imports = [
        (
            "GetNextEvent",
            PpcImportDispatcherTarget::GetNextEvent(PpcEventPollOperation::GetNextEvent),
        ),
        ("PostEvent", PpcImportDispatcherTarget::PostEvent),
        ("SetEventMask", PpcImportDispatcherTarget::SetEventMask),
    ]
    .into_iter()
    .enumerate()
    .map(|(index, (symbol, dispatcher_target))| {
        let index = u32::try_from(index).unwrap();
        PpcImportBinding {
            library_index: 0,
            symbol_index: index,
            library_name: "InterfaceLib".into(),
            symbol_name: symbol.into(),
            class: 0,
            weak: false,
            address: PPC_IMPORT_TRAP_BASE + index * 4,
            tvector_address: None,
            trap_pc: PPC_IMPORT_TRAP_BASE + index * 4,
            dispatcher_target,
        }
    })
    .collect();
    ppc_app.gworlds.push(PpcGWorldRecord {
        ui_theme: crate::ui_theme::UiThemeId::ClassicSystem7,
        port: PPC_MAIN_GWORLD,
        pixmap_handle: 0,
        pixmap: 0,
        base_addr: 0,
        gdevice: PPC_MAIN_GDEVICE,
        width: 512,
        height: 342,
        depth: 8,
        row_bytes: 512,
        pixels_locked: false,
        pixels_no_purge: false,
    });
    ppc_app.set_input_snapshot(PpcInputSnapshot {
        mouse_v: 17,
        mouse_h: 19,
        ..PpcInputSnapshot::default()
    });
}

fn assert_ppc_sound_event_boundary(
    mut app: LoadedApp,
    fire_callbacks: impl FnOnce(&mut FixtureRunner),
) {
    install_ppc_sound_event_boundary_fixture(&mut app);
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    let (offset_v, offset_h) = runner.ppc_viewport_offset();
    assert!(
        offset_v > 0 && offset_h > 0,
        "fixture must use a centered viewport"
    );
    runner
        .process_context
        .shared_event_queue()
        .push_back(QueuedEvent {
            what: 3,
            message: 0x1122_3344,
            when: 0,
            where_v: 120,
            where_h: 180,
            modifiers: 0x0080,
        });

    fire_callbacks(&mut runner);

    let ppc_app = runner.native.application_mut().expect("PPC app");
    assert_eq!(
        ppc_app.memory.read_u16_be(PPC_SOUND_EVENT_RECORD + 10),
        Some(120)
    );
    assert_eq!(
        ppc_app.memory.read_u16_be(PPC_SOUND_EVENT_RECORD + 12),
        Some(180)
    );
    assert_eq!(runner.process_context.event_queue().len(), 1);
    let posted = runner.process_context.event_queue().get(0).unwrap();
    assert_eq!((posted.what, posted.message), (5, 0x5566_7788));
    assert_eq!((posted.where_v, posted.where_h), (17, 19));
    assert_eq!(
        runner
            .bus
            .read_word(crate::memory::globals::addr::SYS_EVT_MASK),
        0x1234
    );
    assert_eq!(
        ppc_app
            .memory
            .read_u16_be(crate::memory::globals::addr::SYS_EVT_MASK),
        Some(0x1234)
    );
}

#[test]
fn ppc_sound_doublebacks_preserve_centered_viewport_event_coordinates() {
    let callback = |callback| PpcSoundDoubleBackRecord {
        architecture: CallbackTaskArchitecture::PowerPc,
        channel: 0x0300_1000,
        header: 0x0300_2000,
        exhausted_buffer: 0x0300_3000,
        exhausted_buffer_index: 0,
        callback,
        tick: 0,
        instruction_count: 0,
    };
    let sound = PpcSoundState::default();
    sound.manager.replace_pending_process_doublebacks(vec![
        callback(PPC_SOUND_GET_EVENT_CALLBACK),
        callback(PPC_SOUND_POST_EVENT_CALLBACK),
        callback(PPC_SOUND_SET_EVENT_MASK_CALLBACK),
    ]);
    let app = halted_ppc_app_with_sound(sound);

    assert_ppc_sound_event_boundary(app, FixtureRunner::fire_pending_ppc_sound_doublebacks);
}

#[test]
fn ppc_sound_completions_preserve_centered_viewport_event_coordinates() {
    let mut sound = PpcSoundState::default();
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, PPC_SOUND_GET_EVENT_CALLBACK);
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, PPC_SOUND_POST_EVENT_CALLBACK);
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, PPC_SOUND_SET_EVENT_MASK_CALLBACK);
    let app = halted_ppc_app_with_sound(sound);

    assert_ppc_sound_event_boundary(app, FixtureRunner::fire_pending_ppc_sound_completions);
}

#[test]
fn ppc_host_mouse_input_enters_the_shared_queue_in_global_coordinates() {
    let mut app = halted_ppc_app_with_sound(PpcSoundState::default());
    install_ppc_sound_event_boundary_fixture(&mut app);
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    let (offset_v, offset_h) = runner.ppc_viewport_offset();
    assert!(offset_v > 0 && offset_h > 0);

    runner.push_mouse_down(offset_v.saturating_add(12), offset_h.saturating_add(34));

    let event = runner
        .process_context
        .event_queue()
        .back()
        .expect("mouseDown");
    assert_eq!((event.where_v, event.where_h), (12, 34));
    let ppc_app = runner.native.application().expect("PPC app");
    let native_event = ppc_app.event_queue.back().expect("shared mouseDown");
    assert_eq!((native_event.where_v, native_event.where_h), (12, 34));
    assert_eq!(runner.bus.read_word(addr::M_TEMP), 12);
    assert_eq!(runner.bus.read_word(addr::M_TEMP + 2), 34);
}

#[test]
fn ppc_event_queue_has_immediate_bidirectional_visibility() {
    let app = halted_ppc_app_with_sound(PpcSoundState::default());
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);

    // Host input pushes directly into process context canonical queue
    runner.push_mouse_down(10, 20);
    assert_eq!(runner.process_context.event_queue().len(), 1);
    assert_eq!(
        (
            runner
                .process_context
                .event_queue()
                .front()
                .unwrap()
                .where_v,
            runner
                .process_context
                .event_queue()
                .front()
                .unwrap()
                .where_h
        ),
        (10, 20)
    );

    // The attached PPC adapter observes and mutates the canonical queue directly.
    {
        let app = runner.native.application_mut().unwrap();
        assert_eq!(app.event_queue.len(), 1);
        let event = app.event_queue.pop_front().unwrap();
        assert_eq!((event.where_v, event.where_h), (10, 20));
        app.event_queue.push_back(QueuedEvent {
            what: 2, // mouseUp
            message: 0,
            when: 0,
            where_v: 30,
            where_h: 40,
            modifiers: 0,
        });
    }

    // The mutation is immediately visible in ProcessContext without a sync copy.
    assert_eq!(runner.process_context.event_queue().len(), 1);
    assert_eq!(
        runner.process_context.event_queue().front().unwrap().what,
        2
    );

    // The attached 68K dispatcher observes the same queue continuously.
    assert_eq!(runner.dispatcher.event_queue.len(), 1);
    let event = runner.dispatcher.event_queue.pop_front().unwrap();
    assert_eq!((event.where_v, event.where_h), (30, 40));

    assert!(runner.process_context.event_queue().is_empty());
}

#[test]
fn ppc_sound_doubleback_can_complete_a_large_refill() {
    const CALLBACK_CYCLES: usize = 600_000;
    const CHANNEL: u32 = 0x0300_1000;
    const HEADER: u32 = 0x0300_2000;
    const BUFFER: u32 = 0x0300_3000;
    const CALLBACK: u32 = PPC_CODE_BASE + 0x1000;

    let sound = PpcSoundState::default();
    sound
        .manager
        .replace_pending_process_doublebacks(vec![PpcSoundDoubleBackRecord {
            architecture: CallbackTaskArchitecture::PowerPc,
            channel: CHANNEL,
            header: HEADER,
            exhausted_buffer: BUFFER,
            exhausted_buffer_index: 0,
            callback: CALLBACK,
            tick: 1,
            instruction_count: 1,
        }]);
    let mut app = halted_ppc_app_with_sound(sound);
    let ppc_app = app.ppc.as_mut().expect("PPC app");
    let mut callback = Vec::with_capacity((CALLBACK_CYCLES + 1) * 4);
    for _ in 0..CALLBACK_CYCLES {
        callback.extend_from_slice(&0x6000_0000u32.to_be_bytes()); // nop
    }
    callback.extend_from_slice(&0x4e80_0020u32.to_be_bytes()); // blr
    ppc_app.memory.add_region(CALLBACK, callback);

    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    runner.fire_pending_ppc_sound_doublebacks();

    assert!(!runner.is_halted());
    let sound = &runner.native.application().expect("PPC app").sound;
    assert!(sound.manager.pending_process_doublebacks.is_empty());
    let invocation = sound
        .completion_invocations
        .last()
        .expect("doubleback invocation");
    assert!(invocation.cycles > 250_000);
    assert_eq!(
        invocation.result,
        PpcRunResult::Halted {
            pc: PPC_HALT_PC,
            cycles: (CALLBACK_CYCLES + 1) as u64,
        }
    );
}

#[test]
fn ppc_sound_doubleback_runaway_still_stops_at_the_watchdog() {
    const CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
    let sound = PpcSoundState::default();
    sound
        .manager
        .replace_pending_process_doublebacks(vec![PpcSoundDoubleBackRecord {
            architecture: CallbackTaskArchitecture::PowerPc,
            channel: 0x0300_1000,
            header: 0x0300_2000,
            exhausted_buffer: 0x0300_3000,
            exhausted_buffer_index: 0,
            callback: CALLBACK,
            tick: 1,
            instruction_count: 1,
        }]);
    let mut app = halted_ppc_app_with_sound(sound);
    app.ppc.as_mut().unwrap().memory.add_region(
        CALLBACK,
        0x4800_0000u32.to_be_bytes().to_vec(), // b .
    );
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    runner.fire_pending_ppc_sound_doublebacks();

    assert!(runner.is_halted());
    assert_eq!(runner.halted_pc(), Some(CALLBACK));
    let invocation = runner
        .native
        .application()
        .unwrap()
        .sound
        .completion_invocations
        .last()
        .unwrap();
    assert!(matches!(invocation.result, PpcRunResult::CycleLimit { cycles } if cycles > 0));
}

#[test]
fn ppc_sound_doubleback_callback_refills_and_plays_exhausted_buffer() {
    const CHANNEL: u32 = 0x0300_1000;
    const HEADER: u32 = 0x0300_2000;
    const BUFFER: u32 = 0x0300_3000;
    const CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
    const SAMPLES: [u8; 4] = [0x80, 0x90, 0x70, 0xa0];

    let sound = PpcSoundState::default();
    sound
        .manager
        .replace_double_buffer_playbacks(vec![PpcSoundDoubleBufferPlaybackRecord {
            channel: CHANNEL,
            header: HEADER,
            buffers: [BUFFER, 0],
            callback: CALLBACK,
            callback_architecture: CallbackTaskArchitecture::PowerPc,
            sample_rate_fixed: crate::sound::OUTPUT_RATE << 16,
            num_channels: 1,
            sample_size: 8,
            compression_id: 0,
            format: 0,
            packet_size: 0,
            current_buffer_index: 0,
            callback_pending_mask: 0,
            active: true,
            host_initialized: false,
            host_buffer_loaded: false,
        }]);
    let mut app = halted_ppc_app_with_sound(sound);
    let ppc_app = app.ppc.as_mut().expect("PPC app");
    ppc_app.memory.add_region(BUFFER, vec![0; 32]);

    // Inside Macintosh: Sound (1994), pp. 2-147 and 2-178: a doubleback
    // receives the exhausted SndDoubleBufferPtr and refills dbNumFrames,
    // dbFlags, and dbSoundData before setting dbBufferReady.
    let callback = [
        0x38a0_0004u32, // li r5,4
        0x90a4_0000,    // stw r5,0(r4): dbNumFrames
        0x3ca0_8090,    // lis r5,$8090
        0x60a5_70a0,    // ori r5,r5,$70A0
        0x90a4_0010,    // stw r5,16(r4): dbSoundData
        0x38a0_0005,    // li r5,5: dbBufferReady | dbLastBuffer
        0x90a4_0004,    // stw r5,4(r4): dbFlags
        0x4e80_0020,    // blr
    ]
    .into_iter()
    .flat_map(u32::to_be_bytes)
    .collect::<Vec<_>>();
    ppc_app.memory.add_region(CALLBACK, callback);

    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    runner.mix_audio(SAMPLES.len());

    assert_eq!(runner.drain_audio(), SAMPLES);
    let ppc_app = runner
        .native
        .application()
        .expect("PPC app should stay loaded");
    let mut memory = ppc_app.memory.clone();
    assert_eq!(memory.read_u32_be(BUFFER), Some(SAMPLES.len() as u32));
    assert_eq!(memory.read_u32_be(BUFFER + 4), Some(0x04));
    assert_eq!(
        memory.read_u32_be(BUFFER + 16),
        Some(u32::from_be_bytes(SAMPLES))
    );
    assert_eq!(ppc_app.sound.completion_invocations.len(), 1);
    assert!(!ppc_app.sound.manager.double_buffer_playbacks[0].active);
    assert_eq!(
        runner.dispatcher().sound_manager.debug_samples_mixed,
        SAMPLES.len() as u64
    );
}

#[test]
fn ppc_sound_completion_preserves_callback_rnd_seed_update() {
    const CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
    let mut sound = PpcSoundState::default();
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, CALLBACK);
    let mut app = halted_ppc_app_with_sound(sound);
    let ppc_app = app.ppc.as_mut().expect("PPC app");
    ppc_app.cpu.alignment_policy = ppc::PpcAlignmentPolicy::EmulateData;
    ppc_app.memory.add_region(PPC_HALT_PC, vec![0; 64 * 1024]);
    ppc_app.memory.add_region(
        CALLBACK,
        [
            0x3c60_89abu32, // lis r3,$89ab
            0x6063_cdef,    // ori r3,r3,$cdef
            0x3880_0156,    // li r4,$0156
            0x9064_0000,    // stw r3,0(r4)
            0x4e80_0020,    // blr
        ]
        .into_iter()
        .flat_map(u32::to_be_bytes)
        .collect(),
    );

    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.set_optional_launch_state(None, Some(1), None);
    runner.init_app(&app);
    runner.fire_pending_ppc_sound_completions();

    assert_eq!(runner.bus.read_long(addr::RND_SEED), 0x89ab_cdef);
    assert_eq!(
        runner
            .native
            .application_mut()
            .expect("PPC app")
            .memory
            .read_u32_be(addr::RND_SEED),
        Some(0x89ab_cdef)
    );
}

#[test]
fn ppc_sound_completions_see_ticks_advanced_by_prior_callback() {
    const FIRST_CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
    const SECOND_CALLBACK: u32 = PPC_CODE_BASE + 0x1100;
    let mut sound = PpcSoundState::default();
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, FIRST_CALLBACK);
    queue_ppc_sound_completion(&mut sound, 0x0300_1000, SECOND_CALLBACK);
    let mut app = halted_ppc_app_with_sound(sound);
    let ppc_app = app.ppc.as_mut().expect("PPC app");
    ppc_app.cpu.alignment_policy = ppc::PpcAlignmentPolicy::EmulateData;
    ppc_app.memory.add_region(PPC_HALT_PC, vec![0; 64 * 1024]);
    ppc_app.memory.add_region(
        FIRST_CALLBACK,
        [0x6000_0000u32, 0x4e80_0020]
            .into_iter()
            .flat_map(u32::to_be_bytes)
            .collect(),
    );
    ppc_app.memory.add_region(
        SECOND_CALLBACK,
        [0x8060_016au32, 0x4e80_0020] // lwz r3,$016a(0); blr
            .into_iter()
            .flat_map(u32::to_be_bytes)
            .collect(),
    );

    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.set_optional_launch_state(Some(41), None, None);
    runner.init_app(&app);
    runner.set_instructions_per_tick(2);
    runner.fire_pending_ppc_sound_completions();

    assert_eq!(runner.bus.read_long(addr::TICKS), 43);
    assert_eq!(runner.guest_tick(), 43);
    let ppc_app = runner.native.application_mut().expect("PPC app");
    assert_eq!(
        ppc_app
            .memory
            .read_u32_be(crate::memory::globals::addr::TICKS),
        Some(43)
    );
    assert_eq!(ppc_app.memory.read_u32_be(addr::TICKS), Some(43));
    assert_eq!(ppc_app.sound.completion_invocations.len(), 2);
    assert_eq!(ppc_app.sound.completion_invocations[1].end_r3, 42);
}
#[test]
fn ppc_retained_drag_wait_advances_clock_and_timers_without_executing_idle_cycles() {
    const EVENT: u32 = PPC_DATA_BASE + 0x2000;
    const CALLBACK: u32 = PPC_CODE_BASE + 0x1000;
    let mut app = halted_ppc_app_with_sound(PpcSoundState::default());
    let native = app.ppc.as_mut().unwrap();
    native.memory.add_region(EVENT, vec![0; 16]);
    native
        .memory
        .add_region(PPC_DATA_BASE + 0x3000, vec![0; 32]);
    native
        .memory
        .add_region(CALLBACK, 0x4e80_0020u32.to_be_bytes().to_vec());
    native
        .memory
        .write_u32_be(
            PPC_CODE_BASE,
            ppc_test_relative_branch(PPC_CODE_BASE, PPC_IMPORT_TRAP_BASE),
        )
        .unwrap();
    let mut binding = test_ppc_import_binding(0, "DragLib", "TrackDrag");
    binding.trap_pc = PPC_IMPORT_TRAP_BASE;
    binding.dispatcher_target =
        PpcImportDispatcherTarget::Drag(crate::loader::ppc::PpcDragOperation::Track);
    native.import_count = 1;
    native.imports = vec![binding];
    native.timer_tasks.push(PpcTimerTaskRecord {
        task_ptr: PPC_DATA_BASE + 0x3000,
        architecture: CallbackTaskArchitecture::PowerPc,
        extended: false,
        callback: CALLBACK,
        active: true,
        fire_at_tick: 1,
        fire_at_subtick: 0,
        last_fired_tick: None,
    });
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    runner.set_instructions_per_tick(100_000);
    runner.tick_budget = 100_000;
    let native = runner.native.application_mut().unwrap();
    let reference = native
        .drag_manager
        .with_mut(|manager| manager.new_drag().unwrap());
    native.cpu.gpr[3] = reference;
    native.cpu.gpr[4] = EVENT;
    native.cpu.gpr[5] = 0;
    runner.push_mouse_down(0, 0);
    let before = runner.guest_tick();
    let instructions = runner.total_instructions;
    let (_, running) = runner.run_gui_cpu_slice(64, before + 1);
    assert!(running);
    assert!(runner.is_drag_presentation_wait());
    assert_eq!(runner.guest_tick(), before + 1);
    assert!(runner.total_instructions - instructions < 1_000);
    assert_eq!(
        runner.native.application().unwrap().timer_tasks[0].last_fired_tick,
        Some(before + 1)
    );
    let (_, running) = runner.run_gui_cpu_slice(64, before + 2);
    assert!(running);
    assert!(runner.is_drag_presentation_wait());
    assert_eq!(runner.guest_tick(), before + 2);
}

#[test]
fn gui_trap_bounded_slice_runs_long_cpu_bursts_but_stops_between_traps() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let entry = 0x0020_0000;
    for i in 0..256 {
        runner.bus.write_word(entry + i * 2, 0x4e71); // NOP
    }
    runner.bus.write_word(entry + 512, 0xa975); // TickCount
    runner.bus.write_word(entry + 514, 0x7207); // MOVEQ #7,D1
    runner.bus.write_word(entry + 516, 0xa975); // TickCount
    runner.bus.write_word(entry + 518, 0x7209); // MOVEQ #9,D1
    runner.m68k.cpu.write_reg(Register::PC, entry);
    runner.m68k.cpu.write_reg(Register::A7, 0x007f_ff00);
    let traps = runner.dispatcher.trap_count;

    let (steps, running) = runner.run_gui_cpu_slice_until_trap(64, u32::MAX);
    assert!(running);
    assert_eq!(steps, 64);
    assert_eq!(runner.dispatcher.trap_count, traps);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 128);

    let (steps, running) = runner.run_gui_cpu_slice_until_trap(8192, u32::MAX);
    assert!(running);
    assert_eq!(steps, 193);
    assert_eq!(runner.dispatcher.trap_count, traps + 1);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 514);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);

    let (steps, running) = runner.run_gui_cpu_slice_until_trap(8192, u32::MAX);
    assert!(running);
    assert_eq!(steps, 2);
    assert_eq!(runner.dispatcher.trap_count, traps + 2);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 518);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
}

#[test]
fn gui_host_work_boundary_batches_clock_reads_but_yields_after_other_traps() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let entry = 0x0020_0000;
    for (i, word) in [0xa975, 0x7207, 0xa975, 0x2417, 0xa974, 0x7209]
        .into_iter()
        .enumerate()
    {
        runner.bus.write_word(entry + i as u32 * 2, word);
    }
    runner.m68k.cpu.write_reg(Register::PC, entry);
    runner.m68k.cpu.write_reg(Register::A7, 0x007f_ff00);
    runner.dispatcher.set_tick_count_for_test(&mut runner.bus, 50);
    let tick = runner.guest_tick();
    let traps = runner.dispatcher.trap_count;
    let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
    assert!(running);
    assert_eq!(steps, 5);
    assert_eq!(runner.dispatcher.trap_count, traps + 3);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 10);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D2), tick);
}

#[test]
fn gui_host_work_boundary_keeps_clock_poll_instruction_and_tick_caps() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let entry = 0x0020_0000;
    runner.bus.write_word(entry, 0xa975);
    runner.bus.write_word(entry + 2, 0x5283); // ADDQ.L #1,D3 keeps this a counting loop
    runner.bus.write_word(entry + 4, 0x60fa); // BRA back to TickCount
    runner.m68k.cpu.write_reg(Register::PC, entry);
    runner.m68k.cpu.write_reg(Register::A7, 0x007f_ff00);
    runner.dispatcher.set_tick_count_for_test(&mut runner.bus, 50);
    let tick = runner.guest_tick();
    let (steps, running) = runner.run_gui_cpu_slice_until_host_work(64, u32::MAX);
    assert!(running);
    assert_eq!(steps, 64);
    assert_eq!(runner.guest_tick(), tick);
    runner.tick_budget = 3;
    let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, tick + 1);
    assert!(running);
    assert!(steps <= 3);
    assert_eq!(runner.guest_tick(), tick + 1);
}

#[test]
fn gui_host_work_boundary_yields_before_running_patched_clock_handler() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let entry = 0x0020_0000;
    let handler = 0x0021_0000;
    runner.bus.write_word(entry, 0xa975);
    runner.bus.write_word(handler, 0x7207); // MOVEQ #7,D1
    runner.bus.write_word(handler + 2, 0x4e75);
    runner
        .dispatcher
        .install_trap_address(&mut runner.bus, 0xa975, handler)
        .unwrap();
    runner.m68k.cpu.write_reg(Register::PC, entry);
    runner.m68k.cpu.write_reg(Register::A7, 0x007f_ff00);
    let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), handler);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
}

#[test]
fn gui_host_work_batches_default_queries_and_preserves_results() {
    for trap in [0xa858, 0xa8ad, 0xa972, 0xa97f, 0xa9b4] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let entry = 0x0020_0000;
        let sp = 0x007f_ff00;
        runner.bus.write_word(entry, trap);
        runner.bus.write_word(entry + 2, 0x7207); // MOVEQ #7,D1
        runner.bus.write_word(entry + 4, 0x2417); // MOVE.L (A7),D2
        runner.bus.write_word(entry + 6, 0xa974); // Button: host boundary
        runner.m68k.cpu.write_reg(Register::PC, entry);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        match trap {
            0xa858 => {
                runner.bus.write_long(sp, 0xff00_ff00);
                runner.bus.write_long(sp + 4, 0xf0f0_f0f0);
            }
            0xa8ad => {
                runner.bus.write_long(sp, 0x0021_0000);
                runner.bus.write_word(sp + 4, 2);
                runner.bus.write_word(sp + 6, 3);
                runner.bus.write_word(0x0021_0000, 0);
                runner.bus.write_word(0x0021_0002, 0);
                runner.bus.write_word(0x0021_0004, 8);
                runner.bus.write_word(0x0021_0006, 8);
                runner.bus.write_long(sp + 8, 0);
            }
            0xa972 => {
                runner.bus.write_long(sp, 0x0021_0000);
                runner.bus.write_long(0x0021_0000, 0xdead_beef);
            }
            0xa97f => {
                runner.bus.write_long(sp, 0);
                runner.bus.write_long(sp + 4, 0xfeed_beef);
            }
            _ => {}
        }
        let before = runner.dispatcher.trap_count;
        let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
        assert!(running, "trap {trap:04x}");
        assert_eq!(steps, 4, "trap {trap:04x}");
        assert_eq!(runner.dispatcher.trap_count, before + 2);
        assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 8);
        assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
        match trap {
            0xa858 => assert_eq!(runner.m68k.cpu.read_reg(Register::D2), 0xf000_f000),
            0xa8ad => assert_eq!(runner.m68k.cpu.read_reg(Register::D2), 0x0100_0000),
            0xa972 => assert_ne!(runner.bus.read_long(0x0021_0000), 0xdead_beef),
            0xa97f => assert_eq!(runner.m68k.cpu.read_reg(Register::D2), 0x00ed_beef),
            _ => {}
        }
    }
}

#[test]
fn gui_host_work_batches_default_set_rect_but_yields_for_patch() {
    for patched in [false, true] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let entry = 0x0020_0000;
        let sp = 0x007f_ff00;
        let rect = 0x0021_0000;
        runner.bus.write_word(entry, 0xa8a7); // SetRect
        runner.bus.write_word(entry + 2, 0x7207); // MOVEQ #7,D1
        runner.bus.write_word(entry + 4, 0xa974); // Button: boundary
        runner.bus.write_word(sp, 40); // bottom
        runner.bus.write_word(sp + 2, 30); // right
        runner.bus.write_word(sp + 4, 20); // top
        runner.bus.write_word(sp + 6, 10); // left
        runner.bus.write_long(sp + 8, rect);
        runner.m68k.cpu.write_reg(Register::PC, entry);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        if patched {
            let handler = 0x0022_0000;
            runner.bus.write_word(handler, 0x4e75);
            runner.dispatcher.install_trap_address(&mut runner.bus, 0xa8a7, handler).unwrap();
        }
        let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
        assert!(running);
        if patched {
            assert_eq!(steps, 1);
            assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0x0022_0000);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
        } else {
            assert_eq!(steps, 3);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
            assert_eq!(runner.bus.read_long(rect), 0x0014_000a);
            assert_eq!(runner.bus.read_long(rect + 4), 0x0028_001e);
        }
    }
}

#[test]
fn gui_host_work_batches_only_null_non_sleeping_wait_next_event() {
    for (sleep, event, redraw, continuation) in [
        (0, false, false, false),
        (1, false, false, false),
        (0, true, false, false),
        (0, false, true, false),
        (0, false, false, true),
    ] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let entry = 0x0020_0000;
        let sp = 0x007f_ff00;
        let event_record = 0x0021_0000;
        runner.bus.write_word(entry, 0xa860); // WaitNextEvent
        runner.bus.write_word(entry + 2, 0x7207); // MOVEQ #7,D1
        runner.bus.write_word(entry + 4, 0xa974); // Button: boundary
        runner.bus.write_long(sp, 0); // mouse region
        runner.bus.write_long(sp + 4, sleep);
        runner.bus.write_long(sp + 8, event_record);
        runner.bus.write_word(sp + 12, 0xffff);
        runner.m68k.cpu.write_reg(Register::PC, entry);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        runner.dispatcher.set_sent_open_app_event_for_test(true);
        if redraw {
            runner.dispatcher.event_queue.invalidate_menu_bar();
        }
        if continuation {
            runner.dispatcher.system_task_wne_returns.push(0x0023_0000);
        }
        if event {
            runner.dispatcher.event_queue.push_back(crate::event_queue::QueuedEvent {
                what: 1, message: 0, when: 0, where_v: 10, where_h: 20, modifiers: 0,
            });
        }
        let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
        assert!(running);
        if sleep == 0 && !event && !redraw && !continuation {
            assert_eq!(steps, 3);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
            assert_eq!(runner.bus.read_word(sp + 14), 0);
        } else {
            assert_eq!(steps, 1, "sleep={sleep}, event={event}, redraw={redraw}, continuation={continuation}");
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
        }
    }
}

#[test]
fn gui_host_work_batches_only_default_sound_channel_status() {
    for selector in [0x0010_0008, 0x0510_0008, 0x0314_0008] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let entry = 0x0020_0000;
        let sp = 0x007f_ff00;
        let status = 0x0021_0000;
        runner.bus.write_word(entry, 0xa800); // SoundDispatch
        runner.bus.write_word(entry + 2, 0x7207); // MOVEQ #7,D1
        runner.bus.write_word(entry + 4, 0x3417); // MOVE.W (A7),D2
        runner.bus.write_word(entry + 6, 0xa974); // Button: host boundary
        runner.bus.write_long(sp, status);
        runner.bus.write_word(sp + 4, 24);
        runner.bus.write_long(sp + 6, 0); // unknown channel is idle
        runner.bus.write_word(sp + 10, 0xbeef);
        runner.bus.write_byte(status + 12, 0xff);
        runner.m68k.cpu.write_reg(Register::PC, entry);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        runner.m68k.cpu.write_reg(Register::D0, selector);
        let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
        assert!(running);
        if selector == 0x0314_0008 {
            assert_eq!(steps, 1, "manager-status is not admitted");
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
        } else {
            assert_eq!(steps, 4, "selector {selector:08x}");
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
            assert_eq!(runner.bus.read_byte(status + 12), 0);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D2) & 0xffff, 0);
        }
    }
}

#[test]
fn gui_host_work_yields_for_patched_sound_dispatch() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let entry = 0x0020_0000;
    let handler = 0x0021_0000;
    runner.bus.write_word(entry, 0xa800);
    runner.bus.write_word(handler, 0x7207);
    runner.bus.write_word(handler + 2, 0x4e75);
    runner
        .dispatcher
        .install_trap_address(&mut runner.bus, 0xa800, handler)
        .unwrap();
    runner.m68k.cpu.write_reg(Register::PC, entry);
    runner.m68k.cpu.write_reg(Register::A7, 0x007f_ff00);
    runner.m68k.cpu.write_reg(Register::D0, 0x0510_0008);
    let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), handler);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
}

#[test]
fn gui_host_work_yields_for_each_patched_query() {
    for trap in [0xa858, 0xa860, 0xa8a7, 0xa8ad, 0xa970, 0xa972, 0xa97f, 0xa9b4] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let entry = 0x0020_0000;
        let handler = 0x0021_0000;
        runner.bus.write_word(entry, trap);
        runner.bus.write_word(handler, 0x7207);
        runner.bus.write_word(handler + 2, 0x4e75);
        runner
            .dispatcher
            .install_trap_address(&mut runner.bus, trap, handler)
            .unwrap();
        runner.m68k.cpu.write_reg(Register::PC, entry);
        runner.m68k.cpu.write_reg(Register::A7, 0x007f_ff00);
        let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
        assert!(running, "trap {trap:04x}");
        assert_eq!(steps, 1, "trap {trap:04x}");
        assert_eq!(runner.m68k.cpu.read_reg(Register::PC), handler);
        assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
    }
}

#[test]
fn gui_host_work_batches_only_quiet_null_event_polls() {
    for (real_event, invalid_menu) in [(false, false), (true, false), (false, true)] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let entry = 0x0020_0000;
        let event = 0x0021_0000;
        let sp = 0x007f_ff00;
        runner.bus.write_word(entry, 0xa970); // GetNextEvent
        runner.bus.write_word(entry + 2, 0x7207); // MOVEQ #7,D1
        runner.bus.write_word(entry + 4, 0xa974); // Button: host boundary
        runner.bus.write_long(sp, event);
        runner
            .bus
            .write_word(sp + 4, if real_event { 2 } else { 0 });
        runner.m68k.cpu.write_reg(Register::PC, entry);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        runner.dispatcher.set_sent_open_app_event_for_test(true);
        if real_event {
            runner.dispatcher.event_queue.push_back(QueuedEvent {
                what: 1,
                message: 0,
                when: 0,
                where_v: 10,
                where_h: 20,
                modifiers: 0,
            });
        }
        if invalid_menu {
            runner.dispatcher.event_queue.invalidate_menu_bar();
        }
        let (steps, running) = runner.run_gui_cpu_slice_until_host_work(8192, u32::MAX);
        assert!(running);
        assert_eq!(runner.bus.read_word(event), u16::from(real_event));
        if real_event || invalid_menu {
            assert_eq!(steps, 1);
            assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 2);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 0);
        } else {
            assert_eq!(steps, 3);
            assert_eq!(runner.m68k.cpu.read_reg(Register::PC), entry + 6);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D1), 7);
        }
    }
}