systemless 0.101.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
use super::*;
use crate::printing_manager::{self, PrintingArchitecture};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PpcPrintingCompatibilityOperation {
    PrClose,
    PrCloseDoc,
    PrClosePage,
    PrError,
    PrGeneral,
    PrSetError,
    PrValidate,
    PrJobDialog,
    PrOpen,
    PrOpenDoc,
    PrOpenPage,
    PrPicFile,
    PrStlDialog,
    PrintDefault,
    PrDlgMain,
    PrJobInit,
}

pub(crate) fn ppc_dispatch_printing_compatibility(
    operation: PpcPrintingCompatibilityOperation,
    cpu: &PpcCpu,
    memory: &mut PpcSectionMem,
    startup: &mut PpcToolboxStartupState,
) -> PpcImportAction {
    match operation {
        PpcPrintingCompatibilityOperation::PrSetError => {
            // PrSetError stores the current Printing Manager error.
            // PROCEDURE PrSetError(iErr: Integer);
            // Inside Macintosh: Imaging With QuickDraw (1994), p. 9-78.
            startup.printing_error =
                printing_manager::evaluate_pr_set_error(cpu.gpr[3] as u16 as i16);
            PpcImportAction::ReturnPreserve
        }
        PpcPrintingCompatibilityOperation::PrGeneral => {
            // PrGeneral reports an unsupported printer-driver opcode in
            // TGnlData.iError and in the Printing Manager's error state.
            // PROCEDURE PrGeneral(pData: Ptr);
            // Inside Macintosh: Imaging With QuickDraw (1994), pp. 9-72--9-73.
            let data = cpu.gpr[3];
            let memory_writable = data != 0
                && memory.read_u16_be(data).is_some()
                && memory.write_u16_be(data + 2, 2).is_some();
            if let Some(err) = printing_manager::evaluate_pr_general(memory_writable) {
                startup.printing_error = err;
            }
            PpcImportAction::ReturnPreserve
        }
        // Inside Macintosh: Imaging With QuickDraw (PrJobInit, PrDlgMain):
        // with no printer driver there is no job dialog to initialize, so
        // PrJobInit returns nil and PrDlgMain ends the way PrJobDialog does.
        PpcPrintingCompatibilityOperation::PrJobInit => PpcImportAction::Return(0),
        PpcPrintingCompatibilityOperation::PrJobDialog
        | PpcPrintingCompatibilityOperation::PrDlgMain
        | PpcPrintingCompatibilityOperation::PrStlDialog => {
            let confirmed = printing_manager::evaluate_pr_dialog(PrintingArchitecture::PowerPc);
            PpcImportAction::Return(u32::from(confirmed))
        }
        PpcPrintingCompatibilityOperation::PrOpenDoc => {
            PpcImportAction::Return(printing_manager::evaluate_pr_open_doc())
        }
        PpcPrintingCompatibilityOperation::PrError => {
            // FUNCTION PrError: Integer;
            // Inside Macintosh: Imaging With QuickDraw (1994), p. 9-75.
            PpcImportAction::Return(ppc_i16_result(printing_manager::evaluate_pr_error(
                startup.printing_error,
            )))
        }
        PpcPrintingCompatibilityOperation::PrValidate => {
            // PrValidate returns FALSE when the existing TPrint needs no
            // printer-specific changes. No printer driver is installed here.
            // FUNCTION PrValidate(hPrint: THPrint): Boolean;
            // Inside Macintosh: Imaging With QuickDraw (1994), p. 9-60.
            PpcImportAction::Return(u32::from(printing_manager::evaluate_pr_validate()))
        }
        PpcPrintingCompatibilityOperation::PrintDefault => {
            PpcImportAction::Return(printing_manager::evaluate_print_default())
        }
        PpcPrintingCompatibilityOperation::PrClose
        | PpcPrintingCompatibilityOperation::PrCloseDoc
        | PpcPrintingCompatibilityOperation::PrClosePage
        | PpcPrintingCompatibilityOperation::PrOpen
        | PpcPrintingCompatibilityOperation::PrOpenPage
        | PpcPrintingCompatibilityOperation::PrPicFile => PpcImportAction::ReturnPreserve,
    }
}

// PMDefinitions.h result codes.
const PPC_PM_OUT_OF_SCOPE: i16 = -30871;
const PPC_PM_NO_DEFAULT_PRINTER: i16 = -30872;
const PPC_PM_INVALID_PRINT_SETTINGS: i16 = -30875;
const PPC_PM_INVALID_PAGE_FORMAT: i16 = -30876;

// The page format and print settings objects are opaque to applications.
// Each is a tagged block so that a reference can be validated, and its
// flattened form is a copy of the block.
const PPC_PM_PAGE_FORMAT_TAG: u32 = u32::from_be_bytes(*b"PMpf");
const PPC_PM_PRINT_SETTINGS_TAG: u32 = u32::from_be_bytes(*b"PMps");
const PPC_PM_PAGE_FORMAT_SIZE: u32 = 20;
const PPC_PM_PRINT_SETTINGS_SIZE: u32 = 16;
// With no printer driver to describe a page, the defaults describe a US
// Letter sheet at 72 dpi with quarter-inch margins: the paper rectangle is
// relative to the imageable page rectangle's origin.
const PPC_PM_DEFAULT_PAPER_RECT: [i16; 4] = [-18, -18, 774, 594];
const PPC_PM_DEFAULT_PAGE_RECT: [i16; 4] = [0, 0, 756, 576];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PpcCarbonPrintingOperation {
    Begin,
    End,
    NewPageFormat,
    NewPrintSettings,
    DefaultPageFormat,
    DefaultPrintSettings,
    ValidatePageFormat,
    ValidatePrintSettings,
    DisposePageFormat,
    DisposePrintSettings,
    FlattenPageFormat,
    FlattenPrintSettings,
    UnflattenPageFormat,
    UnflattenPrintSettings,
    GetAdjustedPageRect,
    PageSetupDialog,
    PrintDialog,
    BeginDocument,
    EndDocument,
    BeginPage,
    EndPage,
}

impl PpcCarbonPrintingOperation {
    /// Whether the object is a page format rather than print settings.
    fn page_format(self) -> bool {
        matches!(
            self,
            Self::NewPageFormat
                | Self::DefaultPageFormat
                | Self::ValidatePageFormat
                | Self::DisposePageFormat
                | Self::FlattenPageFormat
                | Self::UnflattenPageFormat
        )
    }
}

fn ppc_pm_object_spec(page_format: bool) -> (u32, u32, i16) {
    if page_format {
        (
            PPC_PM_PAGE_FORMAT_TAG,
            PPC_PM_PAGE_FORMAT_SIZE,
            PPC_PM_INVALID_PAGE_FORMAT,
        )
    } else {
        (
            PPC_PM_PRINT_SETTINGS_TAG,
            PPC_PM_PRINT_SETTINGS_SIZE,
            PPC_PM_INVALID_PRINT_SETTINGS,
        )
    }
}

fn ppc_pm_default_object(page_format: bool) -> Vec<u8> {
    let mut bytes = Vec::new();
    if page_format {
        bytes.extend_from_slice(&PPC_PM_PAGE_FORMAT_TAG.to_be_bytes());
        for value in PPC_PM_DEFAULT_PAPER_RECT
            .iter()
            .chain(&PPC_PM_DEFAULT_PAGE_RECT)
        {
            bytes.extend_from_slice(&value.to_be_bytes());
        }
    } else {
        // First page 1, last page "all pages", one copy.
        bytes.extend_from_slice(&PPC_PM_PRINT_SETTINGS_TAG.to_be_bytes());
        bytes.extend_from_slice(&1_u32.to_be_bytes());
        bytes.extend_from_slice(&u32::MAX.to_be_bytes());
        bytes.extend_from_slice(&1_u32.to_be_bytes());
    }
    bytes
}

fn ppc_pm_is_object(memory: &mut PpcSectionMem, object: u32, tag: u32) -> bool {
    object != 0 && memory.read_u32_be(object) == Some(tag)
}

/// Allocates a tagged object holding `bytes` and stores it at `out`.
fn ppc_pm_new_object(
    memory: &mut PpcSectionMem,
    process_memory_manager: &mut ProcessNativeMemoryManager,
    heap_cursor: &mut u32,
    last_mem_error: &mut i16,
    out: u32,
    bytes: &[u8],
) -> i16 {
    if out == 0 || !ppc_memory_can_write_bytes(memory, out, 4) {
        return PPC_PARAM_ERR;
    }
    let object = process_memory_manager.new_native_ptr(memory, bytes.len() as u32, true);
    ppc_apply_process_native_allocator(process_memory_manager, memory, heap_cursor, last_mem_error);
    let _ = memory.write_u32_be(out, object);
    if object == 0 {
        return PPC_MEM_FULL_ERR;
    }
    let _ = memory.write_bytes(object, bytes);
    PPC_NO_ERR
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn ppc_dispatch_carbon_printing(
    operation: PpcCarbonPrintingOperation,
    cpu: &PpcCpu,
    memory: &mut PpcSectionMem,
    startup: &mut PpcToolboxStartupState,
    process_memory_manager: &mut ProcessNativeMemoryManager,
    heap_cursor: &mut u32,
    last_mem_error: &mut i16,
    handles: &mut Vec<PpcHandleRecord>,
) -> PpcImportAction {
    // Carbon Printing Manager (PMApplication.h). The runtime has no printer
    // configured: the objects work, the dialogs are dismissed without
    // being accepted, and a document cannot be opened.
    let in_scope = startup.carbon_printing_depth > 0;
    let page_format = operation.page_format();
    let (tag, size, invalid) = ppc_pm_object_spec(page_format);
    let result = match operation {
        PpcCarbonPrintingOperation::Begin => {
            startup.carbon_printing_depth = startup.carbon_printing_depth.saturating_add(1);
            PPC_NO_ERR
        }
        PpcCarbonPrintingOperation::End => {
            if in_scope {
                startup.carbon_printing_depth -= 1;
                PPC_NO_ERR
            } else {
                PPC_PM_OUT_OF_SCOPE
            }
        }
        PpcCarbonPrintingOperation::NewPageFormat
        | PpcCarbonPrintingOperation::NewPrintSettings => {
            // PMNewPageFormat(PMPageFormat *) / PMNewPrintSettings(
            // PMPrintSettings *) create objects the caller later fills with
            // PMDefaultPageFormat or PMDefaultPrintSettings.
            if !in_scope {
                PPC_PM_OUT_OF_SCOPE
            } else {
                let bytes = ppc_pm_default_object(page_format);
                ppc_pm_new_object(
                    memory,
                    process_memory_manager,
                    heap_cursor,
                    last_mem_error,
                    cpu.gpr[3],
                    &bytes,
                )
            }
        }
        PpcCarbonPrintingOperation::DefaultPageFormat
        | PpcCarbonPrintingOperation::DefaultPrintSettings => {
            if !in_scope {
                PPC_PM_OUT_OF_SCOPE
            } else if !ppc_pm_is_object(memory, cpu.gpr[3], tag) {
                invalid
            } else {
                let _ = memory.write_bytes(cpu.gpr[3], &ppc_pm_default_object(page_format));
                PPC_NO_ERR
            }
        }
        PpcCarbonPrintingOperation::ValidatePageFormat
        | PpcCarbonPrintingOperation::ValidatePrintSettings => {
            // PMValidatePageFormat(format, Boolean *result) reports whether
            // validation changed the object. Without a printer driver
            // nothing constrains it, so nothing changes.
            if !ppc_pm_is_object(memory, cpu.gpr[3], tag) {
                invalid
            } else if cpu.gpr[4] != 0 && memory.write_u8(cpu.gpr[4], 0).is_none() {
                PPC_PARAM_ERR
            } else {
                PPC_NO_ERR
            }
        }
        PpcCarbonPrintingOperation::DisposePageFormat
        | PpcCarbonPrintingOperation::DisposePrintSettings => {
            if !ppc_pm_is_object(memory, cpu.gpr[3], tag) {
                invalid
            } else {
                let _ = memory.write_u32_be(cpu.gpr[3], 0);
                let _ = process_memory_manager.dispose_native_ptr(cpu.gpr[3]);
                ppc_apply_process_native_allocator(
                    process_memory_manager,
                    memory,
                    heap_cursor,
                    last_mem_error,
                );
                PPC_NO_ERR
            }
        }
        PpcCarbonPrintingOperation::FlattenPageFormat
        | PpcCarbonPrintingOperation::FlattenPrintSettings => {
            // PMFlattenPageFormat(format, Handle *flatFormat) returns a new
            // handle the caller owns.
            let out = cpu.gpr[4];
            if !ppc_pm_is_object(memory, cpu.gpr[3], tag) {
                invalid
            } else if out == 0 || !ppc_memory_can_write_bytes(memory, out, 4) {
                PPC_PARAM_ERR
            } else {
                let bytes = ppc_memory_read_bytes(memory, cpu.gpr[3], size).unwrap_or_default();
                let handle = process_memory_manager.copy_bytes_to_new_native_handle(memory, &bytes);
                ppc_apply_process_native_allocator(
                    process_memory_manager,
                    memory,
                    heap_cursor,
                    last_mem_error,
                );
                ppc_apply_process_native_handle(process_memory_manager, handles, handle);
                let _ = memory.write_u32_be(out, handle);
                if handle == 0 {
                    PPC_MEM_FULL_ERR
                } else {
                    PPC_NO_ERR
                }
            }
        }
        PpcCarbonPrintingOperation::UnflattenPageFormat
        | PpcCarbonPrintingOperation::UnflattenPrintSettings => {
            // PMUnflattenPageFormat(Handle flatFormat, PMPageFormat *)
            // rebuilds an object from a handle PMFlattenPageFormat made.
            let handle = cpu.gpr[3];
            let data = memory
                .read_u32_be(handle)
                .filter(|_| handle != 0)
                .unwrap_or(0);
            let length =
                process_memory_manager.process_handle_size_from_master_pointer(handle, data);
            let bytes = (length == Some(size))
                .then(|| ppc_memory_read_bytes(memory, data, size))
                .flatten()
                .filter(|bytes| bytes[..4] == tag.to_be_bytes());
            match bytes {
                Some(bytes) => ppc_pm_new_object(
                    memory,
                    process_memory_manager,
                    heap_cursor,
                    last_mem_error,
                    cpu.gpr[4],
                    &bytes,
                ),
                None => invalid,
            }
        }
        PpcCarbonPrintingOperation::GetAdjustedPageRect => {
            // PMGetAdjustedPageRect(format, PMRect *) stores the imageable
            // page rectangle as four doubles: top, left, bottom, right.
            let (format, out) = (cpu.gpr[3], cpu.gpr[4]);
            if !ppc_pm_is_object(memory, format, PPC_PM_PAGE_FORMAT_TAG) {
                PPC_PM_INVALID_PAGE_FORMAT
            } else if out == 0 || !ppc_memory_can_write_bytes(memory, out, 32) {
                PPC_PARAM_ERR
            } else {
                for index in 0..4 {
                    let value = memory.read_u16_be(format + 12 + 2 * index).unwrap_or(0) as i16;
                    let _ = memory.write_u64_be(out + 8 * index, f64::from(value).to_bits());
                }
                PPC_NO_ERR
            }
        }
        PpcCarbonPrintingOperation::PageSetupDialog | PpcCarbonPrintingOperation::PrintDialog => {
            // PMPageSetupDialog(format, Boolean *accepted) and
            // PMPrintDialog(settings, format, Boolean *accepted). No printer
            // is configured, so no dialog can be accepted; as with
            // PrStlDialog and PrJobDialog, the result is false.
            let accepted = if operation == PpcCarbonPrintingOperation::PageSetupDialog {
                cpu.gpr[4]
            } else {
                cpu.gpr[5]
            };
            if accepted != 0 {
                let _ = memory.write_u8(accepted, 0);
            }
            if in_scope {
                PPC_NO_ERR
            } else {
                PPC_PM_OUT_OF_SCOPE
            }
        }
        PpcCarbonPrintingOperation::BeginDocument => {
            // PMBeginDocument(settings, format, PMPrintContext *) needs a
            // printer to open a print job.
            if cpu.gpr[5] != 0 {
                let _ = memory.write_u32_be(cpu.gpr[5], 0);
            }
            if in_scope {
                PPC_PM_NO_DEFAULT_PRINTER
            } else {
                PPC_PM_OUT_OF_SCOPE
            }
        }
        // No document can be open, so page and document ends are outside
        // the scope of any PMBeginDocument.
        PpcCarbonPrintingOperation::EndDocument
        | PpcCarbonPrintingOperation::BeginPage
        | PpcCarbonPrintingOperation::EndPage => PPC_PM_OUT_OF_SCOPE,
    };
    PpcImportAction::Return(ppc_i16_result(result))
}