systemless 0.122.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
use super::*;
use ppc::PpcCpu;
use std::collections::HashMap;

#[test]
fn ppc_exit_to_shell_halt_is_distinct_from_other_ppc_stops() {
    let mut exit = test_ppc_import_binding(7, "InterfaceLib", "ExitToShell");
    exit.dispatcher_target = PpcImportDispatcherTarget::ExitToShell;
    let imports = vec![exit];
    let halted = PpcRunResult::Halted {
        pc: PPC_HALT_PC,
        cycles: 4,
    };

    assert!(ppc_halted_by_exit_to_shell(&imports, halted, Some(7), None));
    assert!(!ppc_halted_by_exit_to_shell(
        &imports,
        halted,
        Some(7),
        Some(7)
    ));
    assert!(!ppc_halted_by_exit_to_shell(
        &imports,
        halted,
        Some(8),
        None
    ));
    let mut unsupported = test_ppc_import_binding(7, "InterfaceLib", "MysteryCall");
    unsupported.dispatcher_target = PpcImportDispatcherTarget::Unsupported;
    let duplicate_imports = vec![unsupported, imports[0].clone()];
    assert!(!ppc_halted_by_exit_to_shell(
        &duplicate_imports,
        halted,
        Some(7),
        None
    ));
    assert!(!ppc_halted_by_exit_to_shell(
        &imports,
        PpcRunResult::MemoryFault {
            pc: PPC_CODE_BASE,
            addr: 0,
            was_write: false,
            cycles: 4,
        },
        Some(7),
        None
    ));
}

#[test]
fn ppc_unimpl_histogram_key_names_unsupported_imports() {
    let imports = vec![test_ppc_import_binding(7, "InterfaceLib", "MysteryCall")];

    assert_eq!(
        ppc_unimpl_histogram_key(&imports, PpcRunResult::CycleLimit { cycles: 0 }, Some(7)),
        Some("import #7 InterfaceLib:MysteryCall".to_string())
    );
    assert_eq!(
        ppc_unimpl_histogram_key(&imports, PpcRunResult::CycleLimit { cycles: 0 }, Some(8)),
        Some("import #8 <unknown>".to_string())
    );
}

#[test]
fn ppc_unimpl_histogram_key_records_instruction_decode_errors() {
    assert_eq!(
        ppc_unimpl_histogram_key(
            &[],
            PpcRunResult::Unimplemented {
                pc: 0x0100_0000,
                error: ppc::PpcDecodeError::UnsupportedPrimaryOpcode(1),
                cycles: 12,
            },
            None,
        ),
        Some("instruction pc=$01000000 UnsupportedPrimaryOpcode(1)".to_string())
    );
}

#[test]
fn ppc_unimpl_histogram_formatter_sorts_by_count_then_key() {
    let mut histogram = HashMap::new();
    merge_ppc_unimpl_histogram(&mut histogram, "import #7 InterfaceLib:Foo".to_string());
    merge_ppc_unimpl_histogram(&mut histogram, "import #7 InterfaceLib:Foo".to_string());
    merge_ppc_unimpl_histogram(&mut histogram, "instruction pc=$01000000 Bar".to_string());

    assert_eq!(
        format_ppc_unimpl_histogram(&histogram, 2),
        "[PPC-UNIMPL-HIST] top 2 of 2 unsupported stops (3 total)\n\
             [PPC-UNIMPL-HIST]            2  import #7 InterfaceLib:Foo\n\
             [PPC-UNIMPL-HIST]            1  instruction pc=$01000000 Bar\n"
    );
}

#[test]
fn ppc_loaded_app_runs_through_fixture_runner() {
    let mut memory = PpcSectionMem::new();
    memory.add_region(PPC_CODE_BASE, 0x4e80_0020u32.to_be_bytes().to_vec());
    let mut cpu = PpcCpu::new();
    cpu.pc = PPC_CODE_BASE;
    cpu.lr = PPC_HALT_PC;
    cpu.gpr[1] = PPC_STACK_TOP - 64;

    let app = LoadedApp::from_ppc(PpcLoadedApp {
        cpu,
        memory,
        entry_pc: PPC_CODE_BASE,
        rtoc: 0,
        stack_base: PPC_STACK_BASE,
        stack_size: PPC_STACK_SIZE,
        stack_pointer: PPC_STACK_TOP - 64,
        launch_partition_storage: Default::default(),
        tick_state: SharedProcessTickState::default(),
        clock_cycles_per_tick: 1,
        clock_cycle_phase: 0,
        trap_default_gateways: Default::default(),
        native_exception_handler: 0,
        power_mq: 0,
        native_exception_stack: Vec::new(),
        stdc_qsort_stack: Vec::new(),
        stdc_bsearch_stack: Vec::new(),
        dialog_callback_stack: Vec::new(),
        collection_callback_stack: Vec::new(),
        picture_callback_stack: Vec::new(),
        drag_tracking_stack: Vec::new(),
        pending_file_completions: VecDeque::new(),
        file_completion_context: None,
        parked_interrupt_callback: None,
        interrupt_callback_parks: 0,
        apple_events: Default::default(),
        cfm: Some(crate::cfm::CfmState::default()),
        controls: Default::default(),
        screen_clut: SharedProcessDisplayClut::from_value(TrapDispatcher::standard_mac_8bpp_clut()),
        display_gamma: SharedProcessDisplayGamma::default(),
        process_quickdraw_port_state_attached: false,
        color_manager_clut: SharedProcessDisplayClut::from_value(
            TrapDispatcher::standard_mac_8bpp_clut(),
        ),
        aliases: Vec::new(),
        agl: Default::default(),
        gworlds: Vec::new(),
        gworld_pixel_states: Default::default(),
        q3_objects: Vec::new(),
        q3_object_refs: Vec::new(),
        next_q3_object: 0,
        q3_error_state: Default::default(),
        q3_lifecycle: Default::default(),
        q3_memory_storages: Vec::new(),
        q3_gpu_texture_cache: Default::default(),
        q3_files: Vec::new(),
        q3_group_memberships: Vec::new(),
        q3_file_groups: Vec::new(),
        q3_views: Vec::new(),
        q3_submissions: Vec::new(),
        q3_view_transforms: Vec::new(),
        q3_submission_transforms: Vec::new(),
        q3_view_materials: Vec::new(),
        q3_submission_materials: Vec::new(),
        q3_submission_lights: Vec::new(),
        q3_view_state_stack: Vec::new(),
        q3_completed_frames: Vec::new(),
        q3_retained_frames: Vec::new(),
        q3_state_only_completed_frame_batches: Vec::new(),
        q3_fog_styles: Vec::new(),
        q3_immediate_trimeshes: Default::default(),
        q3_attributes: Vec::new(),
        q3_shader_uv_transforms: Vec::new(),
        q3_shader_boundaries: Vec::new(),
        q3_mipmap_textures: Vec::new(),
        q3_texture_shaders: Vec::new(),
        q3_renderer_preferences: Vec::new(),
        q3_draw_contexts: Vec::new(),
        q3_trimeshes: Vec::new(),
        q3_styles: Vec::new(),
        q3_cameras: Vec::new(),
        q3_lights: Vec::new(),
        q3_present_pacing: Default::default(),
        input_sprocket: Default::default(),
        input_sprocket_virtual_elements: Vec::new(),
        toolbox_startup: Default::default(),
        quicktime: Default::default(),
        sound: Default::default(),
        timer_tasks: Default::default(),
        vbl_tasks: Default::default(),
        callback_scheduling: Default::default(),
        process_file_system: SharedProcessFileSystem::from_state(
            ProcessFileSystemState {
                files: Default::default(),
                stdio_streams: ppc_initial_stdio_streams(),
                vfs_volumes: crate::process_context::SharedProcessValue::default(),
                vfs_directories: crate::process_context::SharedProcessValue::from_value(vec![
                    PpcVfsDirectory {
                        dir_id: 19,
                        parent_dir_id: 17,
                        path: "System Folder/Preferences/Test App Saves".to_string(),
                        creator: u32::from_be_bytes(*b"Nano"),
                        file_type: u32::from_be_bytes(*b"dir "),
                        finder_flags: 0x0080,
                        dirty: true,
                    },
                ]),
                next_vfs_dir_id: crate::process_context::SharedProcessValue::from_value(20),
                default_dir_id: crate::process_context::SharedProcessValue::from_value(2),
                vfs_files: vec![PpcVfsFileRecord {
                    path: "System Folder/Preferences/Test App Prefs".to_string(),
                    data: (b"prefs".to_vec()).into(),
                    creator: u32::from_be_bytes(*b"Nano"),
                    file_type: u32::from_be_bytes(*b"pref"),
                    finder_flags: 0x0200,
                    dirty: true,
                }]
                .into(),
                deleted_vfs_file_paths: vec!["System Folder/Preferences/Old Prefs".to_string()],
                resource_manager: Default::default(),
                next_file_ref_num: 128,
                ..ProcessFileSystemState::default()
            }
            .with_resources(
                Vec::new(),
                vec![PpcVfsResourceFileRecord {
                    path: "System Folder/Preferences/Test App HighScores".to_string(),
                    creator: u32::from_be_bytes(*b"Nano"),
                    file_type: u32::from_be_bytes(*b"pref"),
                    finder_flags: 0x0400,
                    resource_len: 0,
                    raw_data: None,
                    map_attrs: 0,
                    dirty: true,
                }],
                vec![PpcVfsResourceRecord {
                    ref_num: 128,
                    path: "System Folder/Preferences/Test App HighScores".to_string(),
                    res_type: u32::from_be_bytes(*b"pref"),
                    res_id: 200,
                    name: b"Scores".to_vec(),
                    data: b"score".to_vec().into(),
                    raw_data: None,
                    raw_attrs: None,
                    attrs: 0,
                    handle: 0,
                }],
            ),
        ),
        current_gworld: SharedProcessGraphicsPort::from_value(PPC_MAIN_GWORLD),
        current_gdevice: SharedProcessGraphicsDevice::from_value(PPC_MAIN_GDEVICE),
        quickdraw_op_colors: Default::default(),
        quickdraw_hilite_colors: Default::default(),
        quickdraw_fore_color: PpcRgbColor {
            red: 0,
            green: 0,
            blue: 0,
        },
        quickdraw_fore_indices: Default::default(),
        quickdraw_back_color: PpcRgbColor {
            red: 0xffff,
            green: 0xffff,
            blue: 0xffff,
        },
        quickdraw_pen_h: 0,
        quickdraw_pen_v: 0,
        quickdraw_text_mode: PPC_QD_TEXT_MODE_SRC_OR,
        quickdraw_text_size: PPC_QD_TEXT_SIZE_SYSTEM,
        cursor_state: crate::process_context::SharedProcessCursorState::default(),
        param_text: Default::default(),
        scrap: Default::default(),
        list_manager: Default::default(),
        collections: Default::default(),
        drag_manager: Default::default(),
        halt_pc: PPC_HALT_PC,
        import_trap_base: PPC_IMPORT_TRAP_BASE,
        import_count: 0,
        imports: Vec::new(),
        section_bases: Vec::new(),
        input: PpcInputSnapshot::default(),
        process_input: Default::default(),
        event_queue: Default::default(),
        window_list: Default::default(),
        process_memory_manager: PpcProcessMemoryManager::with_heap(PPC_HEAP_BASE, PPC_STACK_BASE),
        glm_mode: None,
        glm_callbacks: [None; 8],
        glm_callback_stack: Vec::new(),
        glm_allocations: HashMap::new(),
        rave: Default::default(),
        glm_page_free_all_queue: VecDeque::new(),
        glm_error: 0,
        draw_sprocket: PpcDrawSprocketState::default(),
    });
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    let output_dir = tempfile::tempdir().unwrap();
    let old_host_path = output_dir
        .path()
        .join("System Folder/Preferences/Old Prefs");
    std::fs::create_dir_all(old_host_path.parent().unwrap()).unwrap();
    std::fs::write(&old_host_path, b"old").unwrap();
    let old_rsrc_path = output_dir
        .path()
        .join("System Folder/Preferences/.rsrc/Old Prefs");
    std::fs::create_dir_all(old_rsrc_path.parent().unwrap()).unwrap();
    std::fs::write(&old_rsrc_path, b"old-rsrc").unwrap();
    runner.dispatcher_mut().output_dir = Some(output_dir.path().to_path_buf());
    runner.dispatcher_mut().vfs.insert(
        "System Folder/Preferences/Old Prefs".to_string(),
        b"old".to_vec(),
    );
    runner.dispatcher_mut().vfs_rsrc.insert(
        "System Folder/Preferences/Old Prefs".to_string(),
        b"old-rsrc".to_vec(),
    );
    runner.dispatcher_mut().set_vfs_entry_finfo(
        "System Folder/Preferences/Old Prefs",
        u32::from_be_bytes(*b"pref"),
        u32::from_be_bytes(*b"Nano"),
        0x4000,
    );
    runner
        .dispatcher_mut()
        .locked_files
        .insert("System Folder/Preferences/Old Prefs".to_string());

    let (steps, running) = runner.run_steps(8, None);

    assert_eq!(steps, 1);
    assert!(!running);
    assert!(runner.is_halted());
    assert_eq!(runner.halted_pc(), Some(PPC_HALT_PC));
    assert_eq!(runner.halted_sp(), Some(PPC_STACK_TOP - 64));
    assert_eq!(
        runner
            .dispatcher()
            .vfs
            .get("System Folder/Preferences/Test App Prefs")
            .map(Vec::as_slice),
        Some(b"prefs".as_slice())
    );
    let prefs_metadata = runner
        .dispatcher()
        .vfs_metadata
        .get("System Folder/Preferences/Test App Prefs")
        .copied()
        .expect("dirty PPC data fork should carry Finder metadata");
    assert_eq!(prefs_metadata.creator, u32::from_be_bytes(*b"Nano"));
    assert_eq!(prefs_metadata.file_type, u32::from_be_bytes(*b"pref"));
    assert_eq!(prefs_metadata.finder_flags, 0x0200);
    assert!(!runner
        .dispatcher()
        .vfs
        .contains_key("System Folder/Preferences/Old Prefs"));
    assert!(!runner
        .dispatcher()
        .vfs_rsrc
        .contains_key("System Folder/Preferences/Old Prefs"));
    assert!(!runner
        .dispatcher()
        .vfs_metadata
        .contains_key("System Folder/Preferences/Old Prefs"));
    assert!(!runner
        .dispatcher()
        .locked_files
        .contains("System Folder/Preferences/Old Prefs"));
    assert_eq!(
        std::fs::read(
            output_dir
                .path()
                .join("System Folder/Preferences/Test App Prefs")
        )
        .unwrap()
        .as_slice(),
        b"prefs".as_slice()
    );
    assert!(!old_host_path.exists());
    assert!(!old_rsrc_path.exists());
    let fork_bytes = runner
        .dispatcher()
        .vfs_rsrc
        .get("System Folder/Preferences/Test App HighScores")
        .expect("dirty PPC resource fork should sync to dispatcher VFS");
    let fork = ResourceFork::parse(fork_bytes).unwrap();
    assert_eq!(fork.get(*b"pref", 200).unwrap().data, b"score");
    let scores_metadata = runner
        .dispatcher()
        .vfs_metadata
        .get("System Folder/Preferences/Test App HighScores")
        .copied()
        .expect("dirty PPC resource fork should carry Finder metadata");
    assert_eq!(scores_metadata.creator, u32::from_be_bytes(*b"Nano"));
    assert_eq!(scores_metadata.file_type, u32::from_be_bytes(*b"pref"));
    assert_eq!(scores_metadata.finder_flags, 0x0400);
    let saves_directory = runner
        .dispatcher()
        .vfs_directories
        .iter()
        .find(|directory| directory.path == "System Folder/Preferences/Test App Saves")
        .expect("dirty PPC directory should remain in the shared catalogue");
    assert_eq!(
        TrapDispatcher::vfs_basename(&saves_directory.path),
        "Test App Saves"
    );
    assert!(output_dir
        .path()
        .join("System Folder/Preferences/Test App Saves")
        .is_dir());
    assert_eq!(
        std::fs::read(
            output_dir
                .path()
                .join("System Folder/Preferences/.rsrc/Test App HighScores")
        )
        .unwrap()
        .as_slice(),
        fork_bytes.as_slice()
    );
    assert!(!runner.native.application().unwrap().vfs_files[0].dirty);
    assert!(!runner.native.application().unwrap().vfs_directories[0].dirty);
    assert!(runner
        .native
        .application()
        .unwrap()
        .deleted_vfs_file_paths
        .is_empty());
    assert!(!runner.native.application().unwrap().vfs_resource_files[0].dirty);

    let prefs_path = "System Folder/Preferences/Test App Prefs";
    runner
        .native
        .application_mut()
        .unwrap()
        .with_test_vfs_file_mut(0, |file| {
            file.data
                .with_mut(|data| data.extend_from_slice(b"-native"));
        })
        .expect("seeded native preferences file");
    assert_eq!(
        runner.dispatcher().vfs.get(prefs_path).unwrap(),
        b"prefs-native",
        "classic File Manager view must observe native writes before another runner sync"
    );

    runner
        .dispatcher_mut()
        .vfs
        .with_entry_mut(prefs_path, |bytes| bytes.extend_from_slice(b"-classic"))
        .unwrap();
    let native_file = &runner.native.application().unwrap().vfs_files[0];
    let classic_file = runner.dispatcher().vfs.get_shared(prefs_path).unwrap();
    assert!(native_file.data.ptr_eq(classic_file));
    assert_eq!(native_file.data.as_slice(), b"prefs-native-classic");
}

/// A native loop that renders one QuickDraw 3D frame per iteration
/// (StartRendering, EndRendering) to a double-buffered window draw context,
/// run through the runner with present pacing on or off. A small `bl` loop
/// keeps it free of every other import, and counts its frames in r31.
fn q3_present_loop_runner(pacing: bool, audio_bytes: usize) -> FixtureRunner {
    const VIEW: u32 = 0x0200_0100;
    const CONTEXT: u32 = 0x0200_0200;
    const LOOP: u32 = PPC_CODE_BASE + 0x1000;
    const START_TRAP: u32 = PPC_IMPORT_TRAP_BASE;
    const END_TRAP: u32 = PPC_IMPORT_TRAP_BASE + 4;
    let branch = |from: u32, to: u32, link: bool| {
        0x4800_0000 | (to.wrapping_sub(from) & 0x03ff_fffc) | u32::from(link)
    };
    let code = [
        0x3c60_0000 | (VIEW >> 16),    // lis r3, VIEW@h
        0x6063_0000 | (VIEW & 0xffff), // ori r3, r3, VIEW@l
        branch(LOOP + 8, START_TRAP, true),
        0x3c60_0000 | (VIEW >> 16),
        0x6063_0000 | (VIEW & 0xffff),
        branch(LOOP + 20, END_TRAP, true),
        0x3bff_0001, // addi r31, r31, 1: frames rendered
        branch(LOOP + 28, LOOP, false),
    ];

    let sound = PpcSoundState::default();
    if audio_bytes > 0 {
        sound.manager.play_buffer_command_for_architecture(
            0x0500_1000,
            (0..audio_bytes).map(|n| 0x80 ^ (n as u8 & 0x1f)).collect(),
            OUTPUT_RATE << 16,
            CallbackTaskArchitecture::M68k,
        );
    }
    let mut app = halted_ppc_app_with_sound(sound);
    let native = app.ppc.as_mut().unwrap();
    native.memory.add_region(
        LOOP,
        code.into_iter().flat_map(u32::to_be_bytes).collect(),
    );
    native.memory.add_region(PPC_IMPORT_TRAP_BASE, vec![0; 16]);
    native.cpu.pc = LOOP;
    native.entry_pc = LOOP;
    for (index, (symbol, target, trap)) in [
        ("Q3View_StartRendering", PpcImportDispatcherTarget::Q3ViewStartRendering, START_TRAP),
        ("Q3View_EndRendering", PpcImportDispatcherTarget::Q3ViewEndRendering, END_TRAP),
    ]
    .into_iter()
    .enumerate()
    {
        let mut binding = test_ppc_import_binding(index as u32, "QuickDraw3DLib", symbol);
        binding.dispatcher_target = target;
        binding.trap_pc = trap;
        native.imports.push(binding);
    }
    native.import_count = native.imports.len() as u32;
    let mut data = vec![0u8; PPC_Q3_MAC_DRAW_CONTEXT_DATA_SIZE as usize];
    let state = PPC_Q3_DRAW_CONTEXT_DOUBLE_BUFFER_STATE_OFFSET as usize;
    data[state..state + 4].copy_from_slice(&1u32.to_be_bytes());
    let port = PPC_Q3_MAC_DRAW_CONTEXT_PORT_OFFSET as usize;
    data[port..port + 4].copy_from_slice(&PPC_MAIN_GWORLD.to_be_bytes());
    native.q3_draw_contexts.push(PpcQ3DrawContextRecord {
        draw_context: CONTEXT,
        draw_context_type: PPC_Q3_DRAW_CONTEXT_TYPE_MACINTOSH,
        data,
    });
    native.q3_views.push(PpcQ3ViewStateRecord {
        draw_context: CONTEXT,
        ..PpcQ3ViewStateRecord::new(VIEW)
    });
    native.q3_present_pacing.enabled = pacing;

    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.init_app(&app);
    // Long enough for many frames of this loop per tick.
    runner.set_instructions_per_tick(200_000);
    runner
}

fn q3_present_loop_frames(runner: &FixtureRunner) -> u32 {
    runner.native.application().unwrap().cpu.gpr[31]
}

fn q3_present_pacing_state(runner: &FixtureRunner) -> PpcQ3PresentPacingState {
    runner.native.application().unwrap().q3_present_pacing.clone()
}

/// Off by default, presents are not paced: the loop completes many frames
/// in a tick, and nothing waits.
#[test]
fn unpaced_q3_presents_run_many_frames_per_tick_through_the_runner() {
    let mut runner = q3_present_loop_runner(false, 0);
    let first = runner.guest_tick();
    for _ in 0..4 {
        let deadline = runner.guest_tick() + 1;
        let (_, running) = runner.run_gui_slice_with_audio(1_000_000, deadline, 0);
        assert!(running);
    }
    let ticks = runner.guest_tick() - first;
    let state = q3_present_pacing_state(&runner);
    assert!(ticks >= 4, "ticks {ticks}");
    assert_eq!(state.parks, [0; 5]);
    // A disabled model records nothing.
    assert_eq!(state.presents, [0; 5]);
    let frames = q3_present_loop_frames(&runner);
    assert!(frames > 4 * ticks, "{frames} frames in {ticks} ticks");
}

/// With pacing on, a second present in a tick blocks in EndRendering by
/// yielding to the runner. Each slice still ends at its tick deadline, the
/// blocked import is re-entered and completes once per tick, host audio is
/// mixed in every slice, and input pushed while the present is blocked is
/// accepted and published.
#[test]
fn paced_q3_presents_yield_and_keep_ticks_audio_and_input_moving() {
    const SAMPLES_PER_SLICE: usize = 64;
    const SLICES: u32 = 12;
    let mut runner = q3_present_loop_runner(true, SAMPLES_PER_SLICE * (SLICES as usize + 4));
    let first = runner.guest_tick();
    let mut audio = 0;
    let mut blocked_slices = 0;
    let mut key_pushed = false;
    for slice in 0..SLICES {
        let deadline = runner.guest_tick() + 1;
        let (_, running) =
            runner.run_gui_slice_with_audio(1_000_000, deadline, SAMPLES_PER_SLICE);
        assert!(running, "slice {slice}");
        assert_eq!(runner.guest_tick(), deadline, "slice {slice} missed its tick");
        let mixed = runner.drain_audio().len();
        assert!(mixed > 0, "slice {slice} mixed no audio");
        audio += mixed;
        let state = q3_present_pacing_state(&runner);
        if state.waiting.is_some() {
            blocked_slices += 1;
            if !key_pushed {
                // Space, between two slices of a blocked present.
                runner.push_key_down(0x31, b' ');
                let key_map = runner.bus.read_bytes(crate::memory::globals::addr::KEY_MAP_LM, 16);
                assert_ne!(key_map[0x31 / 8] & (1 << (0x31 % 8)), 0);
                key_pushed = true;
            }
        }
    }
    let ticks = runner.guest_tick() - first;
    let state = q3_present_pacing_state(&runner);
    let presents = state.presents_of(PpcQ3PresentKind::Window);
    assert_eq!(ticks, SLICES);
    assert!(key_pushed && blocked_slices > 0);
    // One present per tick: never more, and the blocked one always resumes.
    assert!(presents <= u64::from(ticks) + 1, "{presents} presents in {ticks} ticks");
    assert!(presents + 1 >= u64::from(ticks), "{presents} presents in {ticks} ticks");
    assert!(state.parks_of(PpcQ3PresentKind::Window) + 2 >= u64::from(ticks));
    let frames = q3_present_loop_frames(&runner);
    assert!(frames <= ticks + 1, "{frames} frames in {ticks} ticks");
    assert!(audio >= SAMPLES_PER_SLICE * SLICES as usize / 2, "audio {audio}");
}