systemless 0.37.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
//! Software glyph rasteriser used by `DrawString` / `DrawText` / friends.
//!
//! Reads the active font/style from the current `GrafPort` (`txFont`,
//! `txSize`, `txFace`) and emits per-glyph coverage strips at the
//! current pen location. Bypasses the trap dispatcher entirely — this
//! is plain Rust glyph blitting, used by every QuickDraw text op
//! after argument decode.
//!
//! Glyph data lives in [`crate::quickdraw::fonts`] (original systemless
//! bitmap art, `const fn`-decoded at compile time). Italic faces are
//! synthesised by the runtime shear-blit at draw time.

use crate::quickdraw::fonts::{
    get_font_face_or_default, get_italic_glyph as get_italic_glyph_fn, get_macroman_glyph,
    override_format, FontMetrics, Glyph,
};

/// Architecture-neutral interpretation of QuickDraw's low-order `Style` byte.
///
/// QuickDraw and the Font Manager accept any combination of bold, italic,
/// underline, outline, shadow, condense, and extend. Intrinsic font faces take
/// priority; the remaining styles are synthesized while drawing. Inside
/// Macintosh: Text (1993), pp. 3-5--3-7 and 3-69--3-70.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct QuickDrawTextStyle(u8);

impl QuickDrawTextStyle {
    pub(crate) const BOLD_BIT: u8 = 0x01;
    pub(crate) const ITALIC_BIT: u8 = 0x02;
    pub(crate) const UNDERLINE_BIT: u8 = 0x04;
    pub(crate) const OUTLINE_BIT: u8 = 0x08;
    pub(crate) const SHADOW_BIT: u8 = 0x10;
    pub(crate) const CONDENSE_BIT: u8 = 0x20;
    pub(crate) const EXTEND_BIT: u8 = 0x40;
    const EFFECT_BITS: u8 = Self::BOLD_BIT
        | Self::ITALIC_BIT
        | Self::UNDERLINE_BIT
        | Self::OUTLINE_BIT
        | Self::SHADOW_BIT
        | Self::CONDENSE_BIT
        | Self::EXTEND_BIT;
    const PER_GLYPH_EFFECT_BITS: u8 = Self::EFFECT_BITS & !Self::UNDERLINE_BIT;

    pub(crate) const fn from_bits(bits: u8) -> Self {
        Self(bits & Self::EFFECT_BITS)
    }

    pub(crate) const fn plain() -> Self {
        Self(0)
    }

    pub(crate) const fn is_plain(self) -> bool {
        self.0 == 0
    }

    pub(crate) const fn has_per_glyph_effect(self) -> bool {
        self.0 & Self::PER_GLYPH_EFFECT_BITS != 0
    }

    pub(crate) const fn bold(self) -> bool {
        self.0 & Self::BOLD_BIT != 0
    }

    pub(crate) const fn italic(self) -> bool {
        self.0 & Self::ITALIC_BIT != 0
    }

    pub(crate) const fn underline(self) -> bool {
        self.0 & Self::UNDERLINE_BIT != 0
    }

    pub(crate) const fn outline(self) -> bool {
        self.0 & Self::OUTLINE_BIT != 0
    }

    pub(crate) const fn shadow(self) -> bool {
        self.0 & Self::SHADOW_BIT != 0
    }

    pub(crate) const fn condensed(self) -> bool {
        self.0 & Self::CONDENSE_BIT != 0
    }

    pub(crate) const fn extended(self) -> bool {
        self.0 & Self::EXTEND_BIT != 0
    }

    /// Advance one synthesized glyph using the frozen Roman system-font
    /// metrics shared by both guest adapters.
    pub(crate) fn glyph_advance(self, glyph_advance: i32) -> i32 {
        let mut advance = glyph_advance;
        if self.bold() {
            advance += 1;
        }
        if self.outline() {
            advance += 1;
        }
        if self.shadow() {
            advance += 2;
        }
        if self.condensed() && advance >= 6 {
            advance -= 1;
        }
        if self.extended() {
            advance += 1;
        }
        advance.max(1)
    }

    /// Vertical source-bitmap offset used before synthesizing a shadow.
    pub(crate) const fn glyph_y_offset(self) -> i32 {
        if self.shadow() {
            -1
        } else {
            0
        }
    }

    /// Radius of the mask smear used to synthesize hollow outline/shadow ink.
    pub(crate) const fn smear_max(self) -> Option<i32> {
        if self.shadow() && self.outline() {
            Some(3)
        } else if self.shadow() {
            Some(2)
        } else if self.outline() {
            Some(1)
        } else {
            None
        }
    }
}

pub fn get_font_metrics(font_id: i16, size: i16) -> FontMetrics {
    get_font_face_or_default(font_id, size).metrics
}

pub fn get_glyph(font_id: i16, size: i16, ch: char) -> Option<(&'static Glyph, &'static [u8])> {
    let face = get_font_face_or_default(font_id, size);
    let glyphs = face.glyphs;
    let data = face.data;

    // ASCII range: glyphs start at ' ' (32).
    if (' '..='~').contains(&ch) {
        let idx = (ch as usize) - 32;
        if idx < glyphs.len() {
            let glyph = &glyphs[idx];
            if glyph.width != 0 || glyph.height != 0 || glyph.advance != 0 {
                return Some((glyph, data));
            }
        }
        return None;
    }

    // Mac Roman extended characters (0x80-0xFF). The raw byte was cast
    // to char so char code == Mac Roman code for this range.
    let mac_code = ch as u32;
    if (0x80..=0xFF).contains(&mac_code) {
        return macroman_or_ascii_fallback(font_id, size, mac_code as u8);
    }

    // Unicode codepoints emitted directly by HLE code paths that don't
    // fit in the Mac Roman byte range. The Menu Manager emits U+2318
    // (COMMAND KEY) for command-key equivalents and U+2713 (CHECK MARK)
    // for checked items; route them through the classic System font
    // Mac Roman symbol slots. Inside Macintosh Volume I, I-247 and I-358.
    if ch == '\u{2318}' {
        if let Some(hit) =
            override_symbol_glyph(font_id, size, override_format::COMMAND_SYMBOL_GLYPH_INDEX)
        {
            return Some(hit);
        }
        if let Some(hit) = crate::quickdraw::fonts::pixel_font::menu_symbols::get_glyph(ch) {
            return Some(hit);
        }
        return get_macroman_glyph(font_id, size, 0x11);
    }
    if ch == '\u{2713}' {
        if let Some(hit) =
            override_symbol_glyph(font_id, size, override_format::CHECKMARK_SYMBOL_GLYPH_INDEX)
        {
            return Some(hit);
        }
        if let Some(hit) = crate::quickdraw::fonts::pixel_font::menu_symbols::get_glyph(ch) {
            return Some(hit);
        }
        return get_macroman_glyph(font_id, size, 0x12);
    }
    if ch == '\u{14}' || ch == '\u{F8FF}' {
        if let Some(hit) =
            override_symbol_glyph(font_id, size, override_format::APPLE_SYMBOL_GLYPH_INDEX)
        {
            return Some(hit);
        }
        return get_macroman_glyph(font_id, size, 0x14);
    }

    // HLE chrome stores text as Unicode for layout and logging. Route every
    // representable extended character back through its Mac Roman glyph slot
    // so titles and menus use the same bitmap repertoire as guest DrawText.
    if let Some(mac_code @ 0x80..=0xFF) = crate::mac_roman::encode_mac_roman_char(ch) {
        return macroman_or_ascii_fallback(font_id, size, mac_code);
    }

    None
}

fn override_symbol_glyph(
    font_id: i16,
    size: i16,
    index: usize,
) -> Option<(&'static Glyph, &'static [u8])> {
    let face = get_font_face_or_default(font_id, size);
    let glyph = face.glyphs.get(index)?;
    if glyph.width == 0 && glyph.height == 0 && glyph.advance == 0 {
        return None;
    }
    Some((glyph, face.data))
}

fn macroman_or_ascii_fallback(
    font_id: i16,
    size: i16,
    mac_code: u8,
) -> Option<(&'static Glyph, &'static [u8])> {
    if let Some(hit) = get_macroman_glyph(font_id, size, mac_code) {
        return Some(hit);
    }
    if mac_code == 0xAA {
        return crate::quickdraw::fonts::pixel_font::menu_symbols::get_glyph('\u{2122}');
    }
    // ASCII fallback for extended characters that have a close ASCII
    // equivalent. Better to render a slightly-wrong glyph than silently
    // drop the character.
    // Mac Roman encoding (Inside Macintosh Volume I, I-247):
    let ascii_fallback: char = match mac_code {
        0xD0 | 0xD1 => '-',  // en-dash (–), em-dash (—)
        0xD2 | 0xD3 => '"',  // left-double, right-double quote
        0xD4 | 0xD5 => '\'', // left-single, right-single quote
        0xA5 => '*',         // bullet •
        0xCA => ' ',         // non-breaking space
        0xE1 | 0xE5 => '.',  // leading/trailing space-like
        _ => return None,
    };
    get_glyph(font_id, size, ascii_fallback)
}

pub fn get_glyph_italic(
    font_id: i16,
    size: i16,
    ch: char,
) -> Option<(&'static Glyph, &'static [u8])> {
    get_italic_glyph_fn(font_id, size, ch)
}

pub fn get_underline_thickness(_font_id: i16, _size: i16) -> i16 {
    1
}

/// One architecture-neutral Classic Mac text line.
///
/// `start..visible_end` is the part drawn on screen; `next` is the guest-text
/// offset at which the following line begins. This keeps hard line endings and
/// wrap whitespace in the logical text while excluding them from rasterization.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct WrappedTextLine {
    pub(crate) start: usize,
    pub(crate) visible_end: usize,
    pub(crate) next: usize,
}

/// Break Classic Mac text into display lines using caller-supplied glyph widths.
///
/// Both guest adapters use this primitive so TextEdit and dialog static text
/// agree on word wrapping and CR/LF/CRLF hard breaks. The width callback is
/// indexed so styled TextEdit can resolve the style run for each byte without
/// coupling this shared semantic layer to either guest's memory representation.
///
/// Inside Macintosh: Text (1993), pp. 2-88--2-89 and 5-24--5-27: TextEdit
/// prefers word-boundary breaks, uses glyph widths when laying out a line, and
/// treats trailing whitespace as non-visible.
pub(crate) fn wrap_classic_text<F>(
    text: &[u8],
    max_width: i16,
    mut byte_advance: F,
) -> Vec<WrappedTextLine>
where
    F: FnMut(usize, u8) -> i16,
{
    let mut lines = Vec::new();
    let mut line_start = 0usize;
    let max_width = max_width.max(1);

    while line_start < text.len() {
        let mut index = line_start;
        let mut width = 0i16;
        let mut last_whitespace = None::<(usize, usize)>;
        let mut completed = false;

        while index < text.len() {
            if matches!(text[index], b'\r' | b'\n') {
                let next = if text[index] == b'\r' && text.get(index + 1) == Some(&b'\n') {
                    index + 2
                } else {
                    index + 1
                };
                lines.push(WrappedTextLine {
                    start: line_start,
                    visible_end: trim_classic_line_end(text, line_start, index),
                    next,
                });
                line_start = next;
                completed = true;
                break;
            }

            let advance = byte_advance(index, text[index]).max(0);
            if index > line_start && width.saturating_add(advance) > max_width {
                let (visible_end, next) = if text[index] <= b' ' {
                    let mut next = index + 1;
                    while next < text.len()
                        && text[next] <= b' '
                        && !matches!(text[next], b'\r' | b'\n')
                    {
                        next += 1;
                    }
                    (trim_classic_line_end(text, line_start, index), next)
                } else if let Some((visible_end, next)) = last_whitespace {
                    (visible_end, next)
                } else {
                    (index, index)
                };
                lines.push(WrappedTextLine {
                    start: line_start,
                    visible_end,
                    next,
                });
                line_start = next;
                completed = true;
                break;
            }

            width = width.saturating_add(advance);
            if text[index] <= b' ' {
                let whitespace_start = index;
                let mut next = index + 1;
                while next < text.len()
                    && text[next] <= b' '
                    && !matches!(text[next], b'\r' | b'\n')
                {
                    next += 1;
                }
                last_whitespace = Some((whitespace_start, next));
            }
            index += 1;
        }

        if !completed {
            lines.push(WrappedTextLine {
                start: line_start,
                visible_end: trim_classic_line_end(text, line_start, text.len()),
                next: text.len(),
            });
            break;
        }
    }

    lines
}

fn trim_classic_line_end(text: &[u8], start: usize, mut end: usize) -> usize {
    while end > start && text[end - 1] <= b' ' {
        end -= 1;
    }
    end
}

#[cfg(test)]
mod tests {
    use super::{get_glyph, wrap_classic_text, QuickDrawTextStyle, WrappedTextLine};

    #[test]
    fn quickdraw_style_plan_combines_all_low_order_face_bits() {
        let style = QuickDrawTextStyle::from_bits(0xff);

        assert!(style.bold());
        assert!(style.italic());
        assert!(style.underline());
        assert!(style.outline());
        assert!(style.shadow());
        assert!(style.condensed());
        assert!(style.extended());
        assert_eq!(style.glyph_y_offset(), -1);
        assert_eq!(style.smear_max(), Some(3));
        assert_eq!(style.glyph_advance(6), 10);
        assert!(QuickDrawTextStyle::from_bits(0x80).is_plain());
    }

    #[test]
    fn built_in_system_font_renders_menu_symbols() {
        for (symbol, name) in [('\u{2318}', "Command"), ('\u{2713}', "checkmark")] {
            let (glyph, data) = get_glyph(0, 12, symbol)
                .unwrap_or_else(|| panic!("{name} symbol should resolve to a bitmap glyph"));
            let glyph_len = usize::from(glyph.width) * usize::from(glyph.height);
            assert!(
                data[glyph.data_offset..glyph.data_offset + glyph_len]
                    .iter()
                    .any(|pixel| *pixel != 0),
                "{name} symbol should contain visible pixels"
            );
        }
    }

    #[test]
    fn unicode_hle_text_uses_mac_roman_extended_glyphs() {
        let (glyph, data) = get_glyph(0, 12, '').expect("Mac Roman trademark glyph");
        let glyph_len = usize::from(glyph.width) * usize::from(glyph.height);
        assert!(data[glyph.data_offset..glyph.data_offset + glyph_len]
            .iter()
            .any(|pixel| *pixel != 0));
    }

    #[test]
    fn classic_text_wrap_prefers_words_and_hides_wrap_whitespace() {
        let text = b"one two three";

        assert_eq!(
            wrap_classic_text(text, 6, |_, _| 1),
            vec![
                WrappedTextLine {
                    start: 0,
                    visible_end: 3,
                    next: 4,
                },
                WrappedTextLine {
                    start: 4,
                    visible_end: 7,
                    next: 8,
                },
                WrappedTextLine {
                    start: 8,
                    visible_end: 13,
                    next: 13,
                },
            ]
        );
    }

    #[test]
    fn classic_text_wrap_normalizes_cr_lf_and_crlf_hard_breaks() {
        let text = b"one\rtwo\nthree\r\nfour";

        assert_eq!(
            wrap_classic_text(text, 80, |_, _| 1),
            vec![
                WrappedTextLine {
                    start: 0,
                    visible_end: 3,
                    next: 4,
                },
                WrappedTextLine {
                    start: 4,
                    visible_end: 7,
                    next: 8,
                },
                WrappedTextLine {
                    start: 8,
                    visible_end: 13,
                    next: 15,
                },
                WrappedTextLine {
                    start: 15,
                    visible_end: 19,
                    next: 19,
                },
            ]
        );
    }

    #[test]
    fn classic_text_wrap_breaks_an_overlong_word_at_a_character() {
        assert_eq!(
            wrap_classic_text(b"toolbox", 3, |_, _| 1),
            vec![
                WrappedTextLine {
                    start: 0,
                    visible_end: 3,
                    next: 3,
                },
                WrappedTextLine {
                    start: 3,
                    visible_end: 6,
                    next: 6,
                },
                WrappedTextLine {
                    start: 6,
                    visible_end: 7,
                    next: 7,
                },
            ]
        );
    }
}