systemless 0.110.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
//! Structured headless scenarios. Execution shares the frontend scheduler.
use super::{
    configure_realtime_execution_rate, display, game, headless_time, FixtureRunner,
    HostMouseReleaseLatch, InputAction, UiThemeId,
};
use image::RgbImage;
use serde::{Deserialize, Serialize};
use std::{collections::HashSet, fs, path::Path};
use systemless::systems::macintosh::memory::MemoryBus;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Script {
    version: u32,
    clock: String,
    max_ticks: u32,
    application_partition_size: Option<u32>,
    #[serde(default)]
    reference_tolerance: u8,
    actions: Vec<Action>,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum Action {
    Run {
        ticks: u32,
    },
    MouseMove {
        v: i16,
        h: i16,
    },
    MouseDown {
        v: i16,
        h: i16,
    },
    MouseUp {
        v: i16,
        h: i16,
    },
    KeyDown {
        key: u8,
        ch: u8,
    },
    KeyUp {
        key: u8,
        ch: u8,
    },
    Screenshot {
        name: String,
    },
    RunUntilPixel {
        x: u32,
        y: u32,
        rgb: [u8; 3],
        #[serde(default)]
        not: bool,
        #[serde(default)]
        tolerance: u8,
        timeout_ticks: u32,
    },
    AssertPixel {
        x: u32,
        y: u32,
        rgb: [u8; 3],
        #[serde(default)]
        not: bool,
        #[serde(default)]
        tolerance: u8,
    },
    AssertMemoryWord {
        address: u32,
        value: u16,
    },
    AssertAudioDuring {
        ticks: u32,
        min_non_silent: usize,
    },
    Log {
        message: String,
    },
    Milestone {
        name: String,
    },
}

impl Script {
    fn parse(text: &str) -> Result<Self, String> {
        let script: Self = serde_json::from_str(text).map_err(|e| e.to_string())?;
        if script.version != 1 || script.clock != "frontend_ticks" {
            return Err("expected version=1 and clock=frontend_ticks; guest/instruction-clock scripts require manual conversion".into());
        }
        if script.max_ticks == 0 || script.actions.is_empty() {
            return Err("max_ticks and actions must be nonempty".into());
        }
        if script
            .application_partition_size
            .is_some_and(|bytes| bytes < 128 * 1024)
        {
            return Err("application_partition_size must be at least 128 KiB".into());
        }
        let mut names = HashSet::new();
        for action in &script.actions {
            match action {
                Action::Screenshot { name } => {
                    if name.eq_ignore_ascii_case("failure")
                        || name.is_empty()
                        || !name
                            .bytes()
                            .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
                        || !names.insert(name.to_ascii_lowercase())
                    {
                        return Err(format!("capture name must be unique and contain only letters, digits, '_' or '-': {name:?}"));
                    }
                }
                Action::RunUntilPixel {
                    timeout_ticks: 0, ..
                }
                | Action::AssertAudioDuring { ticks: 0, .. } => {
                    return Err("wait/audio duration must be positive".into())
                }
                Action::AssertMemoryWord { address, .. }
                    if address % 2 != 0 || *address > u32::MAX - 1 =>
                {
                    return Err("memory word address must be aligned and in range".into())
                }
                _ => {}
            }
        }
        Ok(script)
    }
}

#[derive(Default, Serialize)]
struct Report {
    version: u32,
    systemless_version: String,
    archive: String,
    script: String,
    reference_directory: Option<String>,
    mac_time_secs: u32,
    application_partition_size: Option<u32>,
    architecture: Option<String>,
    status: String,
    error: Option<String>,
    failed_action: Option<usize>,
    frontend_ticks: u32,
    guest_tick: u32,
    budget_exhausted_frames: u32,
    assertions: usize,
    checkpoints: Vec<Checkpoint>,
}
#[derive(Serialize)]
struct Checkpoint {
    name: String,
    frontend_ticks: u32,
    guest_tick: u32,
    differing_pixels: Option<usize>,
}

struct Execution<'a> {
    runner: FixtureRunner,
    mouse: HostMouseReleaseLatch,
    remainder: f64,
    max_ticks: u32,
    report: &'a mut Report,
}
impl Execution<'_> {
    fn advance(&mut self, ticks: u32) -> Result<usize, String> {
        if ticks > self.max_ticks.saturating_sub(self.report.frontend_ticks) {
            return Err(format!("scenario exceeds max_ticks={}", self.max_ticks));
        }
        let mut non_silent = 0;
        let mut audio = Vec::new();
        for _ in 0..ticks {
            let samples = systemless::systems::macintosh::sound::OUTPUT_RATE as f64
                / systemless::systems::macintosh::runner::DEFAULT_VBL_HZ
                + self.remainder;
            self.remainder = samples.fract();
            let work = headless_time::frame(&mut self.runner, samples.floor() as usize);
            self.report.frontend_ticks += 1;
            self.report.guest_tick = self.runner.guest_tick();
            self.report.budget_exhausted_frames += u32::from(work.budget_exhausted);
            if work.foreground > 0 {
                self.mouse.observe_guest_progress();
            }
            if let Some((v, h)) = self.mouse.take_ready_release() {
                self.runner.push_mouse_up(v, h);
            }
            audio.clear();
            self.runner.drain_audio_into(&mut audio);
            non_silent += audio.iter().filter(|&&v| v != 128).count();
            if self.runner.is_halted() {
                return Err("guest halted before scenario completed".into());
            }
        }
        Ok(non_silent)
    }
    fn image(&self) -> Result<RgbImage, String> {
        let mode = self.runner.dispatcher().screen_mode;
        if mode.2 == 0 || mode.3 == 0 {
            return Err("screen not initialized".into());
        }
        let rgba = display::render_screen_with_gamma(
            self.runner.bus(),
            mode,
            &self.runner.dispatcher().device_clut,
            &self.runner.dispatcher().device_gamma(),
        );
        let rgb = rgba
            .chunks_exact(4)
            .flat_map(|p| [p[0], p[1], p[2]])
            .collect();
        RgbImage::from_raw(mode.2.into(), mode.3.into(), rgb)
            .ok_or_else(|| "invalid framebuffer".into())
    }
    fn pixel(
        &self,
        x: u32,
        y: u32,
        rgb: [u8; 3],
        not: bool,
        tolerance: u8,
    ) -> Result<bool, String> {
        let frame = self.image()?;
        if x >= frame.width() || y >= frame.height() {
            return Err(format!(
                "pixel ({x},{y}) outside {}x{}",
                frame.width(),
                frame.height()
            ));
        }
        Ok(pixel_matches(frame.get_pixel(x, y).0, rgb, tolerance) != not)
    }
    fn actions(
        &mut self,
        script: &Script,
        output: &Path,
        reference: Option<&Path>,
    ) -> Result<(), String> {
        for (index, action) in script.actions.iter().enumerate() {
            self.report.failed_action = Some(index);
            eprintln!(
                "[PLAY] action={index} frontend_tick={} {action:?}",
                self.report.frontend_ticks
            );
            let input = match action {
                Action::MouseMove { v, h } => Some(InputAction::MouseMove { v: *v, h: *h }),
                Action::MouseDown { v, h } => Some(InputAction::MouseDown { v: *v, h: *h }),
                Action::MouseUp { v, h } => Some(InputAction::MouseUp { v: *v, h: *h }),
                Action::KeyDown { key, ch } => Some(InputAction::KeyDown { key: *key, ch: *ch }),
                Action::KeyUp { key, ch } => Some(InputAction::KeyUp { key: *key, ch: *ch }),
                _ => None,
            };
            if let Some(input) = input {
                headless_time::deliver(&mut self.runner, &mut self.mouse, input);
                continue;
            }
            match action {
                Action::Run { ticks } => {
                    self.advance(*ticks)?;
                }
                Action::Screenshot { name } => {
                    let frame = self.image()?;
                    frame
                        .save(output.join(format!("{name}.png")))
                        .map_err(|e| e.to_string())?;
                    let differing_pixels = reference
                        .map(|dir| {
                            compare(
                                &frame,
                                &dir.join(format!("{name}.png")),
                                script.reference_tolerance,
                            )
                        })
                        .transpose()?;
                    self.report.checkpoints.push(Checkpoint {
                        name: name.clone(),
                        frontend_ticks: self.report.frontend_ticks,
                        guest_tick: self.runner.guest_tick(),
                        differing_pixels,
                    });
                    if let Some(count) = differing_pixels {
                        self.report.assertions += 1;
                        if count > 0 {
                            return Err(format!(
                                "checkpoint {name}: {count} pixels differ from reference"
                            ));
                        }
                    }
                }
                Action::RunUntilPixel {
                    x,
                    y,
                    rgb,
                    not,
                    tolerance,
                    timeout_ticks,
                } => {
                    let mut waited = 0;
                    while !self.pixel(*x, *y, *rgb, *not, *tolerance)? {
                        if waited == *timeout_ticks {
                            return Err(format!(
                                "pixel wait timed out after {waited} frontend ticks"
                            ));
                        }
                        self.advance(1)?;
                        waited += 1;
                    }
                }
                Action::AssertPixel {
                    x,
                    y,
                    rgb,
                    not,
                    tolerance,
                } => {
                    self.report.assertions += 1;
                    if !self.pixel(*x, *y, *rgb, *not, *tolerance)? {
                        return Err(format!("pixel assertion failed at ({x},{y})"));
                    }
                }
                Action::AssertMemoryWord { address, value } => {
                    self.report.assertions += 1;
                    let actual = self.runner.bus_mut().read_word(*address);
                    if actual != *value {
                        return Err(format!(
                            "memory {address:#x}: expected {value:#x}, got {actual:#x}"
                        ));
                    }
                }
                Action::AssertAudioDuring {
                    ticks,
                    min_non_silent,
                } => {
                    self.report.assertions += 1;
                    let actual = self.advance(*ticks)?;
                    if actual < *min_non_silent {
                        return Err(format!("audio: expected at least {min_non_silent} non-silent samples, got {actual}"));
                    }
                }
                Action::Log { message } => eprintln!("[PLAY] {message}"),
                Action::Milestone { name } => eprintln!(
                    "[PLAY] milestone={name} guest_tick={}",
                    self.runner.guest_tick()
                ),
                _ => unreachable!(),
            }
        }
        self.report.failed_action = None;
        Ok(())
    }
}
fn pixel_matches(actual: [u8; 3], expected: [u8; 3], tolerance: u8) -> bool {
    actual
        .iter()
        .zip(expected)
        .all(|(a, b)| a.abs_diff(b) <= tolerance)
}
fn compare(frame: &RgbImage, path: &Path, tolerance: u8) -> Result<usize, String> {
    let expected = image::open(path)
        .map_err(|e| format!("reference {}: {e}", path.display()))?
        .to_rgb8();
    if frame.dimensions() != expected.dimensions() {
        return Err(format!(
            "reference {} has different dimensions",
            path.display()
        ));
    }
    Ok(frame
        .pixels()
        .zip(expected.pixels())
        .filter(|(a, b)| !pixel_matches(a.0, b.0, tolerance))
        .count())
}

#[allow(clippy::too_many_arguments)]
pub(super) fn run(
    archive: &Path,
    script_path: &Path,
    output: &Path,
    reference: Option<&Path>,
    start_time: u32,
    addressing_24_bit: bool,
    depth: Option<u16>,
    theme: UiThemeId,
    gpu: bool,
) -> Result<(), String> {
    // Never reuse stale captures or modify adjacent saves during a reproduction.
    fs::create_dir_all(output).map_err(|e| e.to_string())?;
    if fs::read_dir(output)
        .map_err(|e| e.to_string())?
        .next()
        .is_some()
    {
        return Err("play output directory must be empty".into());
    }
    let mut report = Report {
        version: 1,
        systemless_version: env!("CARGO_PKG_VERSION").into(),
        archive: archive.display().to_string(),
        script: script_path.display().to_string(),
        reference_directory: reference.map(|p| p.display().to_string()),
        mac_time_secs: start_time,
        status: "failed".into(),
        ..Report::default()
    };
    let result = (|| {
        let script = Script::parse(&fs::read_to_string(script_path).map_err(|e| e.to_string())?)?;
        let mut runner = match depth {
            Some(d) => game::new_runner_with_configuration(!addressing_24_bit, d),
            None => game::new_runner_with_addressing(!addressing_24_bit),
        };
        runner.set_application_partition_size(script.application_partition_size);
        report.application_partition_size = script.application_partition_size;
        runner.set_ui_theme(theme);
        if gpu {
            runner.set_q3_gpu_renderer(Box::new(super::wgpu_qd3d::Qd3dRenderer::new()));
            runner.set_quickdraw_gpu_renderer(Box::new(super::wgpu_quickdraw::QuickDrawRenderer::new()));
        }
        runner.set_app_start_time(start_time);
        let app = game::load_game_from_path(&mut runner, archive)
            .map_err(|e| format!("load {}: {e}", archive.display()))?;
        game::init_game_owned(&mut runner, app);
        runner.prepare_text_presentation();
        configure_realtime_execution_rate(&mut runner);
        runner.composite_frame();
        report.architecture = Some(
            if runner.is_powerpc_app() {
                "ppc"
            } else {
                "68k"
            }
            .into(),
        );
        report.guest_tick = runner.guest_tick();
        let mut execution = Execution {
            runner,
            mouse: HostMouseReleaseLatch::default(),
            remainder: 0.0,
            max_ticks: script.max_ticks,
            report: &mut report,
        };
        let result = execution.actions(&script, output, reference);
        if result.is_err() {
            if let Ok(frame) = execution.image() {
                let _ = frame.save(output.join("failure.png"));
            }
        }
        result
    })();
    match &result {
        Ok(()) => report.status = "passed".into(),
        Err(e) => report.error = Some(e.clone()),
    }
    fs::write(
        output.join("report.json"),
        serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?,
    )
    .map_err(|e| e.to_string())?;
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn cli_requires_headless_and_rejects_other_replay_clocks() {
        use super::super::Cli;
        use clap::Parser;
        assert!(
            Cli::try_parse_from(["systemless", "app.sit", "--play-script", "script.json"]).is_err()
        );
        assert!(Cli::try_parse_from([
            "systemless",
            "app.sit",
            "--headless",
            "--play-script",
            "script.json",
            "--max-ticks",
            "10"
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "systemless",
            "app.sit",
            "--headless",
            "--play-script",
            "script.json",
            "--play-output",
            "captures"
        ])
        .is_ok());
    }
    #[test]
    fn rejects_ambiguous_or_unsafe_scripts() {
        for text in [
            r#"{"actions":[]}"#,
            r#"{"version":1,"clock":"guest_ticks","max_ticks":1,"actions":[{"type":"run","ticks":1}]}"#,
            r#"{"version":1,"clock":"frontend_ticks","max_ticks":1,"actions":[{"type":"screenshot","name":"../escape"}]}"#,
            r#"{"version":1,"clock":"frontend_ticks","max_ticks":1,"actions":[{"type":"run","ticks":1,"instructions":100}]}"#,
        ] {
            assert!(Script::parse(text).is_err(), "{text}");
        }
    }
    #[test]
    fn reference_requires_exact_file_dimensions_and_pixels() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("title.png");
        let a = RgbImage::from_pixel(2, 2, image::Rgb([10, 20, 30]));
        assert!(compare(&a, &path, 0).is_err());
        let mut b = a.clone();
        b.put_pixel(1, 1, image::Rgb([11, 20, 30]));
        b.save(&path).unwrap();
        assert_eq!(compare(&a, &path, 0).unwrap(), 1);
        assert_eq!(compare(&a, &path, 1).unwrap(), 0);
        RgbImage::new(1, 1).save(&path).unwrap();
        assert!(compare(&a, &path, 0).is_err());
    }

    #[test]
    fn scripts_validate_optional_application_partitions() {
        let script = r#"{"version":1,"clock":"frontend_ticks","max_ticks":1,"actions":[{"type":"run","ticks":1}]}"#;
        assert_eq!(
            Script::parse(script).unwrap().application_partition_size,
            None
        );
        let configured = script.replacen("{", "{\"application_partition_size\":134217728,", 1);
        assert_eq!(
            Script::parse(&configured)
                .unwrap()
                .application_partition_size,
            Some(134217728)
        );
        assert!(Script::parse(&configured.replace("134217728", "131071")).is_err());
        assert!(Script::parse(&configured.replace("134217728", "4294967296")).is_err());
    }
}