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
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
use super::*;

pub(super) struct PpcCursorDispatchContext<'a> {
    pub(super) binding: &'a PpcImportBinding,
    pub(super) cpu: &'a mut PpcCpu,
    pub(super) memory: &'a mut PpcSectionMem,
    pub(super) process_memory_manager: &'a mut ProcessNativeMemoryManager,
    pub(super) heap_cursor: &'a mut u32,
    pub(super) heap_limit: u32,
    pub(super) last_mem_error: &'a mut i16,
    pub(super) handles: &'a mut Vec<PpcHandleRecord>,
    pub(super) vfs_resources: &'a mut Vec<PpcVfsResourceRecord>,
    pub(super) current_resource_refnum: i16,
    pub(super) last_resource_error: &'a mut i16,
    pub(super) cursor_state: &'a SharedProcessCursorState,
    pub(super) gworlds: &'a [PpcGWorldRecord],
    pub(super) current_gworld: u32,
    pub(super) screen_clut: &'a [[u16; 3]; 256],
}

pub(super) fn dispatch_cursor_import(
    context: PpcCursorDispatchContext<'_>,
) -> Option<PpcImportAction> {
    let PpcCursorDispatchContext {
        binding,
        cpu,
        memory,
        process_memory_manager,
        heap_cursor,
        heap_limit,
        last_mem_error,
        handles,
        vfs_resources,
        current_resource_refnum,
        last_resource_error,
        cursor_state,
        gworlds,
        current_gworld,
        screen_clut,
    } = context;

    match binding.dispatcher_target {
        PpcImportDispatcherTarget::InitCursor => {
            // InitCursor (_InitCursor)
            // Sets the standard arrow cursor and makes it visible.
            // PROCEDURE InitCursor;
            // Inside Macintosh: Imaging With QuickDraw (1994), p. 8-22.
            let _action = crate::cursor_manager::evaluate_init_cursor();
            cursor_state.init();
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::GetQDGlobalsArrow => {
            // Carbon's accessor copies the QuickDraw arrow Cursor into the
            // caller's 68-byte record and returns the same pointer.
            // Carbon Porting Guide (2002), "A Porting Example".
            let params = crate::cursor_manager::evaluate_get_qd_globals_arrow_parameters(cpu.gpr[3]);
            if !ppc_memory_can_write_bytes(
                memory,
                params.destination_ptr,
                crate::cursor_manager::CURSOR_RECORD_SIZE as u32,
            ) {
                return Some(PpcImportAction::Return(0));
            }
            let (data, mask, hot_v, hot_h) = crate::display::default_arrow_cursor();
            let _ = memory.write_bytes(
                params.destination_ptr + crate::cursor_manager::CURSOR_DATA_OFFSET as u32,
                &data,
            );
            let _ = memory.write_bytes(
                params.destination_ptr + crate::cursor_manager::CURSOR_MASK_OFFSET as u32,
                &mask,
            );
            let _ = memory.write_u16_be(
                params.destination_ptr + crate::cursor_manager::CURSOR_HOT_V_OFFSET as u32,
                hot_v as u16,
            );
            let _ = memory.write_u16_be(
                params.destination_ptr + crate::cursor_manager::CURSOR_HOT_H_OFFSET as u32,
                hot_h as u16,
            );
            Some(PpcImportAction::Return(params.destination_ptr))
        }
        PpcImportDispatcherTarget::HideCursor => {
            let _action = crate::cursor_manager::evaluate_hide_cursor();
            cursor_state.hide();
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::ShowCursor => {
            let _action = crate::cursor_manager::evaluate_show_cursor();
            cursor_state.show();
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::ShieldCursor => {
            // ShieldCursor decrements the cursor level and must be balanced by
            // ShowCursor. The mouse driver decides whether the shield rectangle
            // currently requires erasing the cursor.
            // Imaging With QuickDraw (1994), p. 8-29.
            let _params = crate::cursor_manager::evaluate_shield_cursor_parameters(
                cpu.gpr[3],
                cpu.gpr[4] as i16,
                (cpu.gpr[4] >> 16) as i16,
            );
            cursor_state.hide();
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::CrsrDevNextDevice => {
            // The reference machine exposes a single aggregate mouse through
            // the Event Manager, not a Cursor Device Manager device chain.
            let params = crate::cursor_manager::evaluate_crsr_dev_next_device_parameters(cpu.gpr[3]);
            if params.device_ptr != 0 && ppc_memory_can_write_bytes(memory, params.device_ptr, 4) {
                let _ = memory.write_u32_be(params.device_ptr, 0);
            }
            Some(PpcImportAction::Return(ppc_i16_result(-1)))
        }
        PpcImportDispatcherTarget::CrsrDevMoveTo => {
            let _params = crate::cursor_manager::evaluate_crsr_dev_move_to_parameters(
                cpu.gpr[3],
                cpu.gpr[4] as i32,
                cpu.gpr[5] as i32,
            );
            Some(PpcImportAction::Return(ppc_i16_result(-1)))
        }
        PpcImportDispatcherTarget::GetCursor => {
            let params = crate::cursor_manager::evaluate_get_cursor_parameters(cpu.gpr[3] as u16 as i16);
            Some(PpcImportAction::Return(ppc_get_cursor(
                params.cursor_id,
                process_memory_manager,
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
                vfs_resources,
                current_resource_refnum,
                last_resource_error,
            )))
        }
        PpcImportDispatcherTarget::SetCursor => {
            let params = crate::cursor_manager::evaluate_set_cursor_parameters(cpu.gpr[3]);
            ppc_set_cursor(memory, params.cursor_ptr, cursor_state);
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::GetCCursor => {
            let params = crate::cursor_manager::evaluate_get_ccursor_parameters(cpu.gpr[3] as u16 as i16);
            Some(PpcImportAction::Return(ppc_get_ccursor(
                params.cursor_id,
                process_memory_manager,
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
                vfs_resources,
                current_resource_refnum,
                last_resource_error,
            )))
        }
        PpcImportDispatcherTarget::GetCIcon => {
            let params = crate::cursor_manager::evaluate_get_cicon_parameters(cpu.gpr[3] as u16 as i16);
            Some(PpcImportAction::Return(ppc_get_cicon(
                params.icon_id,
                process_memory_manager,
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
                vfs_resources,
                current_resource_refnum,
                last_resource_error,
            )))
        }
        PpcImportDispatcherTarget::PlotCIcon => {
            let params = crate::cursor_manager::evaluate_plot_cicon_parameters(cpu.gpr[3], cpu.gpr[4]);
            let _ = ppc_plot_cicon(&params, memory, gworlds, current_gworld, screen_clut);
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::PlotCIconHandle => {
            let params = crate::cursor_manager::evaluate_plot_cicon_parameters(cpu.gpr[3], cpu.gpr[6]);
            let result = ppc_plot_cicon_with_options(&params, cpu.gpr[4] as u16, cpu.gpr[5] as u16, memory, gworlds, current_gworld, screen_clut);
            Some(PpcImportAction::Return(ppc_i16_result(result.err().unwrap_or(0))))
        }
        PpcImportDispatcherTarget::PlotIconSuite => {
            let result = ppc_plot_icon_suite(
                cpu.gpr[3],
                cpu.gpr[4] as u16,
                cpu.gpr[5] as u16,
                cpu.gpr[6],
                memory,
                process_memory_manager,
                heap_cursor,
                last_mem_error,
                handles,
                gworlds,
                current_gworld,
                screen_clut,
            );
            Some(PpcImportAction::Return(ppc_i16_result(
                result.err().unwrap_or(0),
            )))
        }
        PpcImportDispatcherTarget::PlotIconID => {
            let result = ppc_plot_icon_id(
                cpu.gpr[3],
                cpu.gpr[4] as u16,
                cpu.gpr[5] as u16,
                cpu.gpr[6] as u16 as i16,
                memory,
                process_memory_manager,
                heap_cursor,
                last_mem_error,
                vfs_resources,
                current_resource_refnum,
                gworlds,
                current_gworld,
                screen_clut,
            );
            Some(PpcImportAction::Return(ppc_i16_result(
                result.err().unwrap_or(0),
            )))
        }
        PpcImportDispatcherTarget::DisposeCIcon => {
            let params = crate::cursor_manager::evaluate_dispose_cicon_parameters(cpu.gpr[3]);
            ppc_dispose_cicon(
                params.cicon_handle,
                process_memory_manager,
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
            );
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::SetCCursor => {
            let _params = crate::cursor_manager::evaluate_set_ccursor_parameters(cpu.gpr[3]);
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::DisposeCCursor => {
            let _params = crate::cursor_manager::evaluate_dispose_ccursor_parameters(cpu.gpr[3]);
            Some(PpcImportAction::ReturnPreserve)
        }
        _ => None,
    }
}

fn ppc_get_ccursor(
    crsr_id: i16,
    process_memory_manager: &mut ProcessNativeMemoryManager,
    memory: &mut PpcSectionMem,
    heap_cursor: &mut u32,
    heap_limit: u32,
    last_mem_error: &mut i16,
    handles: &mut Vec<PpcHandleRecord>,
    vfs_resources: &mut [PpcVfsResourceRecord],
    current_resource_refnum: i16,
    last_resource_error: &mut i16,
) -> u32 {
    let res_type = u32::from_be_bytes(*b"crsr");
    let Some(index) = ppc_vfs_resource_index(
        vfs_resources,
        current_resource_refnum,
        res_type,
        crsr_id,
        false,
    ) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    ppc_materialize_vfs_resource_handle(
        process_memory_manager,
        memory,
        heap_cursor,
        heap_limit,
        last_mem_error,
        handles,
        vfs_resources,
        index,
        true,
        last_resource_error,
    )
}

fn ppc_get_cicon(
    icon_id: i16,
    process_memory_manager: &mut ProcessNativeMemoryManager,
    memory: &mut PpcSectionMem,
    heap_cursor: &mut u32,
    heap_limit: u32,
    last_mem_error: &mut i16,
    handles: &mut Vec<PpcHandleRecord>,
    vfs_resources: &[PpcVfsResourceRecord],
    current_resource_refnum: i16,
    last_resource_error: &mut i16,
) -> u32 {
    let icon_type = u32::from_be_bytes(*b"cicn");
    let Some(index) = ppc_vfs_resource_index(
        vfs_resources,
        current_resource_refnum,
        icon_type,
        icon_id,
        false,
    ) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        if ppc_hle_trace_enabled() {
            eprintln!(
                "[PPC-TRACE] GetCIcon({}) current_ref={} -> NULL err={}",
                icon_id, current_resource_refnum, PPC_RES_NOT_FOUND_ERR
            );
        }
        return 0;
    };
    let data = &vfs_resources[index].data;
    let read_u16 = |offset: usize| {
        let bytes: [u8; 2] = data.get(offset..offset.checked_add(2)?)?.try_into().ok()?;
        Some(u16::from_be_bytes(bytes))
    };
    let Some(pm_top) = read_u16(6).map(|value| value as i16) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(pm_bottom) = read_u16(10).map(|value| value as i16) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let icon_height = i32::from(pm_bottom) - i32::from(pm_top);
    let Some(mask_row_bytes) = read_u16(54).map(|value| usize::from(value & 0x3fff)) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(bitmap_row_bytes) = read_u16(68).map(|value| usize::from(value & 0x3fff)) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Ok(icon_height) = usize::try_from(icon_height) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(mask_size) = mask_row_bytes.checked_mul(icon_height) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(bitmap_size) = bitmap_row_bytes.checked_mul(icon_height) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(color_table_offset) = 82usize
        .checked_add(mask_size)
        .and_then(|offset| offset.checked_add(bitmap_size))
    else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(color_table_size) = read_u16(color_table_offset + 6)
        .and_then(|size| usize::from(size).checked_add(1))
        .and_then(|count| count.checked_mul(8))
        .and_then(|entries| entries.checked_add(8))
    else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let Some(pixel_data_offset) = color_table_offset.checked_add(color_table_size) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };
    let (Some(color_table), Some(pixel_data)) = (
        data.get(color_table_offset..pixel_data_offset),
        data.get(pixel_data_offset..),
    ) else {
        *last_resource_error = PPC_RES_NOT_FOUND_ERR;
        return 0;
    };

    // Imaging With QuickDraw (1994), pp. 4-105--4-106: the compiled cicn
    // stores its mask, monochrome bitmap, color table, and pixels inline.
    // GetCIcon returns a private live CIcon with address/Handle fields fixed
    // up to independently owned copies.
    let icon_handle = ppc_process_alloc_handle_with_bytes(
        process_memory_manager,
        memory,
        heap_cursor,
        last_mem_error,
        handles,
        data,
    );
    let color_table_handle = ppc_process_alloc_handle_with_bytes(
        process_memory_manager,
        memory,
        heap_cursor,
        last_mem_error,
        handles,
        color_table,
    );
    let pixel_data_handle = ppc_process_alloc_handle_with_bytes(
        process_memory_manager,
        memory,
        heap_cursor,
        last_mem_error,
        handles,
        pixel_data,
    );
    if icon_handle == 0 || color_table_handle == 0 || pixel_data_handle == 0 {
        let mut allocator = PpcProcessAllocatorView {
            memory_manager: process_memory_manager,
        };
        for handle in [icon_handle, color_table_handle, pixel_data_handle] {
            let _ = allocator.dispose_handle(
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
                handle,
            );
        }
        *last_mem_error = PPC_MEM_FULL_ERR;
        return 0;
    }
    let Some(icon_ptr) = memory.read_u32_be(icon_handle) else {
        *last_mem_error = PPC_MEM_FULL_ERR;
        return 0;
    };
    let Some(pixel_data_ptr) = memory.read_u32_be(pixel_data_handle) else {
        *last_mem_error = PPC_MEM_FULL_ERR;
        return 0;
    };
    let mask_data_ptr = icon_ptr + 82;
    let bitmap_data_ptr = mask_data_ptr + mask_size as u32;
    let patched = memory.write_u32_be(icon_ptr, pixel_data_ptr).is_some()
        && memory
            .write_u32_be(icon_ptr + 42, color_table_handle)
            .is_some()
        && memory.write_u32_be(icon_ptr + 50, mask_data_ptr).is_some()
        && memory
            .write_u32_be(icon_ptr + 64, bitmap_data_ptr)
            .is_some()
        && memory
            .write_u32_be(icon_ptr + 78, pixel_data_handle)
            .is_some();
    if !patched {
        *last_mem_error = PPC_MEM_FULL_ERR;
        return 0;
    }
    *last_mem_error = PPC_NO_ERR;
    *last_resource_error = PPC_NO_ERR;
    if ppc_hle_trace_enabled() {
        let record = &vfs_resources[index];
        eprintln!(
            "[PPC-TRACE] GetCIcon({}) current_ref={} -> handle=${:08X} home_ref={} path=\"{}\" size={} pixel_size={}",
            icon_id,
            current_resource_refnum,
            icon_handle,
            record.ref_num,
            record.path,
            record.data.len(),
            pixel_data.len()
        );
    }
    icon_handle
}

fn ppc_cicon_color(
    memory: &mut PpcSectionMem,
    color_table_handle: u32,
    index: u8,
) -> Option<PpcRgbColor> {
    let color_table = memory.read_u32_be(color_table_handle)?;
    let count = u32::from(memory.read_u16_be(color_table + 6)?).checked_add(1)?;
    let mut ordinal = None;
    for entry_index in 0..count.min(256) {
        let entry = color_table.checked_add(8 + entry_index * 8)?;
        let value = memory.read_u16_be(entry)?;
        if entry_index == u32::from(index) {
            ordinal = Some(entry);
        }
        if value == u16::from(index) {
            return Some(PpcRgbColor {
                red: memory.read_u16_be(entry + 2)?,
                green: memory.read_u16_be(entry + 4)?,
                blue: memory.read_u16_be(entry + 6)?,
            });
        }
    }
    let entry = ordinal?;
    Some(PpcRgbColor {
        red: memory.read_u16_be(entry + 2)?,
        green: memory.read_u16_be(entry + 4)?,
        blue: memory.read_u16_be(entry + 6)?,
    })
}

fn ppc_scale_icon_coordinate(
    dst_coordinate: i16,
    dst_start: i16,
    dst_end: i16,
    src_start: i16,
    src_end: i16,
) -> Option<i16> {
    let dst_size = i32::from(dst_end) - i32::from(dst_start);
    let src_size = i32::from(src_end) - i32::from(src_start);
    if dst_size <= 0 || src_size <= 0 {
        return None;
    }
    let dst_offset = i32::from(dst_coordinate) - i32::from(dst_start);
    i16::try_from(i32::from(src_start) + dst_offset * src_size / dst_size).ok()
}

fn ppc_plot_cicon(
    params: &crate::cursor_manager::PlotCIconParameters,
    memory: &mut PpcSectionMem,
    gworlds: &[PpcGWorldRecord],
    current_gworld: u32,
    screen_clut: &[[u16; 3]; 256],
) -> bool {
    ppc_plot_cicon_with_options(params, 0, 0, memory, gworlds, current_gworld, screen_clut)
        .unwrap_or(false)
}

fn ppc_plot_cicon_with_options(
    params: &crate::cursor_manager::PlotCIconParameters,
    alignment: u16,
    transform: u16,
    memory: &mut PpcSectionMem,
    gworlds: &[PpcGWorldRecord],
    current_gworld: u32,
    _screen_clut: &[[u16; 3]; 256],
) -> Result<bool, i16> {
    if alignment & !0x000F != 0 || transform & !0x4703 != 0 {
        return Err(PPC_PARAM_ERR);
    }
    let rect_ptr = params.rect_ptr;
    let icon_handle = params.cicon_handle;
    let (Some(port_dst_rect), Some(icon_ptr)) = (
        ppc_read_rect(memory, rect_ptr),
        memory.read_u32_be(icon_handle).filter(|ptr| *ptr != 0),
    ) else {
        return Err(PPC_PARAM_ERR);
    };
    let Some(surface) = ppc_live_quickdraw_surface(memory, gworlds, current_gworld) else {
        return Err(PPC_PARAM_ERR);
    };
    let front_buffer = surface.front_buffer;
    let (mut dst_top, mut dst_left, mut dst_bottom, mut dst_right) =
        surface.local_rect_i16(port_dst_rect);
    if !matches!(front_buffer.depth, 1 | 2 | 4 | 8 | 16) {
        return Err(PPC_PARAM_ERR);
    }
    let Some(pixel_base) = memory.read_u32_be(icon_ptr) else {
        return Err(PPC_PARAM_ERR);
    };
    let Some(pixel_row_bytes) = memory
        .read_u16_be(icon_ptr + 4)
        .map(|value| u32::from(value & 0x3fff))
    else {
        return Err(PPC_PARAM_ERR);
    };
    let pixel_bounds = (
        memory.read_u16_be(icon_ptr + 6).unwrap_or(0) as i16,
        memory.read_u16_be(icon_ptr + 8).unwrap_or(0) as i16,
        memory.read_u16_be(icon_ptr + 10).unwrap_or(0) as i16,
        memory.read_u16_be(icon_ptr + 12).unwrap_or(0) as i16,
    );
    let pixel_size = memory.read_u16_be(icon_ptr + 32).unwrap_or(0);
    let color_table_handle = memory.read_u32_be(icon_ptr + 42).unwrap_or(0);
    let mask_base = memory.read_u32_be(icon_ptr + 50).unwrap_or(0);
    let mask_row_bytes = u32::from(memory.read_u16_be(icon_ptr + 54).unwrap_or(0) & 0x3fff);
    let mask_bounds = (
        memory.read_u16_be(icon_ptr + 56).unwrap_or(0) as i16,
        memory.read_u16_be(icon_ptr + 58).unwrap_or(0) as i16,
        memory.read_u16_be(icon_ptr + 60).unwrap_or(0) as i16,
        memory.read_u16_be(icon_ptr + 62).unwrap_or(0) as i16,
    );
    if dst_bottom <= dst_top
        || dst_right <= dst_left
        || pixel_bounds.2 <= pixel_bounds.0
        || pixel_bounds.3 <= pixel_bounds.1
        || mask_bounds.2 <= mask_bounds.0
        || mask_bounds.3 <= mask_bounds.1
    {
        return Err(PPC_PARAM_ERR);
    }

    if alignment != 0 {
        let mut opaque: Option<(i16, i16, i16, i16)> = None;
        for v in mask_bounds.0..mask_bounds.2 {
            for h in mask_bounds.1..mask_bounds.3 {
                if ppc_read_packed_bitmap_index(
                    memory,
                    mask_base,
                    mask_row_bytes,
                    1,
                    mask_bounds,
                    v,
                    h,
                ) == Some(1)
                {
                    opaque = Some(match opaque {
                        None => (v, h, v + 1, h + 1),
                        Some((t, l, b, r)) => (t.min(v), l.min(h), b.max(v + 1), r.max(h + 1)),
                    });
                }
            }
        }
        let Some((top, left, bottom, right)) = opaque else {
            return Ok(false);
        };
        // More Macintosh Toolbox, p. 5-21: stretch first, then align mask edges.
        let project =
            |value: i16, origin: i16, source_end: i16, target_start: i16, target_end: i16| {
                let numerator = (i64::from(value) - i64::from(origin))
                    * (i64::from(target_end) - i64::from(target_start));
                let denominator = i64::from(source_end) - i64::from(origin);
                i32::from(target_start) + ((numerator + denominator - 1) / denominator) as i32
            };
        let t = project(top, mask_bounds.0, mask_bounds.2, dst_top, dst_bottom);
        let b = project(bottom, mask_bounds.0, mask_bounds.2, dst_top, dst_bottom);
        let l = project(left, mask_bounds.1, mask_bounds.3, dst_left, dst_right);
        let r = project(right, mask_bounds.1, mask_bounds.3, dst_left, dst_right);
        let shift = |mode: u16, start: i16, end: i16, first: i32, last: i32| match mode {
            1 => (i32::from(start) + i32::from(end) - first - last) / 2,
            2 => i32::from(start) - first,
            3 => i32::from(end) - last,
            _ => 0,
        };
        let dv = shift(alignment & 3, dst_top, dst_bottom, t, b);
        let dh = shift((alignment >> 2) & 3, dst_left, dst_right, l, r);
        dst_top = i16::try_from(i32::from(dst_top) + dv).map_err(|_| PPC_PARAM_ERR)?;
        dst_bottom = i16::try_from(i32::from(dst_bottom) + dv).map_err(|_| PPC_PARAM_ERR)?;
        dst_left = i16::try_from(i32::from(dst_left) + dh).map_err(|_| PPC_PARAM_ERR)?;
        dst_right = i16::try_from(i32::from(dst_right) + dh).map_err(|_| PPC_PARAM_ERR)?;
    }
    let mut clips = Vec::new();
    for offset in [
        PPC_CGRAF_PORT_VIS_RGN_OFFSET,
        PPC_CGRAF_PORT_CLIP_RGN_OFFSET,
    ] {
        if let Some(handle) = memory.read_u32_be(current_gworld.wrapping_add(offset)) {
            if let Some(region) = ppc_region_storage(memory, handle) {
                clips.push(region);
            }
        }
    }
    // More Macintosh Toolbox (1993), pp. 5-25--5-26: PlotCIcon scales the
    // color PixMap into the destination rectangle and applies the icon mask.
    let mut drew = false;
    for dst_v in dst_top.max(0)..dst_bottom.min(front_buffer.height.min(i16::MAX as u32) as i16) {
        let Some(src_v) =
            ppc_scale_icon_coordinate(dst_v, dst_top, dst_bottom, pixel_bounds.0, pixel_bounds.2)
        else {
            continue;
        };
        let Some(mask_v) =
            ppc_scale_icon_coordinate(dst_v, dst_top, dst_bottom, mask_bounds.0, mask_bounds.2)
        else {
            continue;
        };
        for dst_h in dst_left.max(0)..dst_right.min(front_buffer.width.min(i16::MAX as u32) as i16)
        {
            let point = (
                dst_v.wrapping_add(surface.top),
                dst_h.wrapping_add(surface.left),
            );
            if !clips
                .iter()
                .all(|region| ppc_point_in_region_storage(region, point.0, point.1))
            {
                continue;
            }
            let Some(mask_h) =
                ppc_scale_icon_coordinate(dst_h, dst_left, dst_right, mask_bounds.1, mask_bounds.3)
            else {
                continue;
            };
            if ppc_read_packed_bitmap_index(
                memory,
                mask_base,
                mask_row_bytes,
                1,
                mask_bounds,
                mask_v,
                mask_h,
            ) != Some(1)
            {
                continue;
            }
            let Some(src_h) = ppc_scale_icon_coordinate(
                dst_h,
                dst_left,
                dst_right,
                pixel_bounds.1,
                pixel_bounds.3,
            ) else {
                continue;
            };
            let Some(index) = ppc_read_packed_bitmap_index(
                memory,
                pixel_base,
                pixel_row_bytes,
                pixel_size,
                pixel_bounds,
                src_v,
                src_h,
            ) else {
                continue;
            };
            let Some(mut color) = ppc_cicon_color(memory, color_table_handle, index) else {
                continue;
            };
            // Icon Toolkit states are visual transforms, not changes to source data.
            // Apple TN QD18 permits system-dependent state appearance.
            let mut channels = [color.red, color.green, color.blue];
            let label = usize::from((transform >> 8) & 7);
            if label != 0 {
                const LABELS: [[u16; 3]; 8] = [
                    [0; 3],
                    [0x8888; 3],
                    [0, 0x8888, 0],
                    [0x8888, 0x2222, 0xAAAA],
                    [0, 0x7777, 0xFFFF],
                    [0xFFFF, 0xAAAA, 0],
                    [0xFFFF, 0x2222, 0],
                    [0xFFFF, 0xFFFF, 0],
                ];
                for (component, tint) in channels.iter_mut().zip(LABELS[label]) {
                    *component = ((u32::from(*component) + u32::from(tint)) / 2) as u16;
                }
            }
            match transform & 3 {
                1 => {
                    for component in &mut channels {
                        *component = ((u32::from(*component) + 0xFFFF) / 2) as u16;
                    }
                }
                2 => {
                    let gray =
                        ((u32::from(channels[0]) + u32::from(channels[1]) + u32::from(channels[2]))
                            / 3) as u16;
                    channels = [gray; 3];
                }
                3 => {
                    for component in &mut channels {
                        *component = ((u32::from(*component) + 3 * 0xFFFF) / 4) as u16;
                    }
                }
                _ => {}
            }
            if transform & 0x4000 != 0 {
                for component in &mut channels {
                    *component /= 2;
                }
            }
            color = PpcRgbColor {
                red: channels[0],
                green: channels[1],
                blue: channels[2],
            };
            let Some(raw_pixel) = ppc_quickdraw_surface_color_pixel(memory, surface, color) else {
                continue;
            };
            drew |= ppc_quickdraw_write_raw_pixel(
                memory,
                front_buffer,
                (i32::from(dst_h), i32::from(dst_v)),
                raw_pixel,
            );
        }
    }
    if ppc_hle_trace_enabled() {
        let (port_top, port_left, port_bottom, port_right) = port_dst_rect;
        eprintln!(
            "[PPC-TRACE] PlotCIcon rect=({}, {}, {}, {}) local=({}, {}, {}, {}) icon=${:08X} depth={} drew={}",
            port_top,
            port_left,
            port_bottom,
            port_right,
            dst_top,
            dst_left,
            dst_bottom,
            dst_right,
            icon_handle,
            front_buffer.depth,
            drew
        );
    }
    Ok(drew)
}

#[allow(clippy::too_many_arguments)]
fn ppc_dispose_cicon(
    icon_handle: u32,
    process_memory_manager: &mut ProcessNativeMemoryManager,
    memory: &mut PpcSectionMem,
    heap_cursor: &mut u32,
    heap_limit: u32,
    last_mem_error: &mut i16,
    handles: &mut Vec<PpcHandleRecord>,
) {
    let icon_ptr = memory.read_u32_be(icon_handle).unwrap_or(0);
    let (color_table_handle, pixel_data_handle) = if icon_ptr == 0 {
        (0, 0)
    } else {
        (
            memory.read_u32_be(icon_ptr + 42).unwrap_or(0),
            memory.read_u32_be(icon_ptr + 78).unwrap_or(0),
        )
    };
    for handle in [color_table_handle, pixel_data_handle, icon_handle] {
        let _ = ppc_dispose_process_native_handle(
            process_memory_manager,
            memory,
            heap_cursor,
            heap_limit,
            last_mem_error,
            handles,
            handle,
        );
    }
}

fn ppc_set_cursor(
    memory: &mut PpcSectionMem,
    cursor_ptr: u32,
    cursor_state: &SharedProcessCursorState,
) -> Option<()> {
    // SetCursor(crsr: Cursor) installs the 16-by-16 data and mask bitmaps plus
    // the Point hotspot stored at byte offset 64 in the 68-byte Cursor record.
    // Imaging With QuickDraw (1994), pp. 8-19 and 8-25.
    let mut data = [0; crate::cursor_manager::CURSOR_BITMAP_SIZE];
    let mut mask = [0; crate::cursor_manager::CURSOR_BITMAP_SIZE];
    memory.read_bytes_into(
        cursor_ptr.checked_add(crate::cursor_manager::CURSOR_DATA_OFFSET as u32)?,
        &mut data,
    )?;
    memory.read_bytes_into(
        cursor_ptr.checked_add(crate::cursor_manager::CURSOR_MASK_OFFSET as u32)?,
        &mut mask,
    )?;
    let hot_v = memory.read_u16_be(
        cursor_ptr.checked_add(crate::cursor_manager::CURSOR_HOT_V_OFFSET as u32)?,
    )? as i16;
    let hot_h = memory.read_u16_be(
        cursor_ptr.checked_add(crate::cursor_manager::CURSOR_HOT_H_OFFSET as u32)?,
    )? as i16;

    cursor_state.install(crate::display::CursorImage::mono(data, mask, hot_v, hot_h));
    Some(())
}

fn ppc_get_cursor(
    cursor_id: i16,
    process_memory_manager: &mut ProcessNativeMemoryManager,
    memory: &mut PpcSectionMem,
    heap_cursor: &mut u32,
    heap_limit: u32,
    last_mem_error: &mut i16,
    handles: &mut Vec<PpcHandleRecord>,
    vfs_resources: &mut Vec<PpcVfsResourceRecord>,
    current_resource_refnum: i16,
    last_resource_error: &mut i16,
) -> u32 {
    let res_type = u32::from_be_bytes(*b"CURS");
    let index = match ppc_vfs_resource_index(
        vfs_resources,
        current_resource_refnum,
        res_type,
        cursor_id,
        false,
    ) {
        Some(index) => index,
        None => {
            let Some((data, mask, hot_v, hot_h)) =
                crate::trap::TrapDispatcher::system_cursor(cursor_id)
            else {
                *last_resource_error = PPC_RES_NOT_FOUND_ERR;
                return 0;
            };
            let mut cursor = Vec::with_capacity(68);
            cursor.extend_from_slice(&data);
            cursor.extend_from_slice(&mask);
            cursor.extend_from_slice(&(hot_v as u16).to_be_bytes());
            cursor.extend_from_slice(&(hot_h as u16).to_be_bytes());
            vfs_resources.push(PpcVfsResourceRecord {
                ref_num: 0,
                path: "__system__/CURS".to_string(),
                res_type,
                res_id: cursor_id,
                name: Vec::new(),
                data: cursor.into(),
                raw_data: None,
                raw_attrs: None,
                attrs: 0,
                handle: 0,
            });
            vfs_resources.len() - 1
        }
    };
    ppc_materialize_vfs_resource_handle(
        process_memory_manager,
        memory,
        heap_cursor,
        heap_limit,
        last_mem_error,
        handles,
        vfs_resources,
        index,
        true,
        last_resource_error,
    )
}

// Icons.h: PlotIconID draws an icon family from the current resource chain.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)]
fn ppc_plot_icon_id(
    rect: u32,
    alignment: u16,
    transform: u16,
    id: i16,
    memory: &mut PpcSectionMem,
    allocator: &mut ProcessNativeMemoryManager,
    heap_cursor: &mut u32,
    last_mem_error: &mut i16,
    resources: &[PpcVfsResourceRecord],
    refnum: i16,
    gworlds: &[PpcGWorldRecord],
    port: u32,
    screen_clut: &[[u16; 3]; 256],
) -> Result<bool, i16> {
    if alignment & !0xF != 0 || transform & !0x4703 != 0 {
        return Err(PPC_PARAM_ERR);
    }
    let (t, l, b, r) = ppc_read_rect(memory, rect).ok_or(PPC_PARAM_ERR)?;
    let surface = ppc_live_quickdraw_surface(memory, gworlds, port).ok_or(PPC_PARAM_ERR)?;
    let small = i32::from(b) - i32::from(t) <= 16 && i32::from(r) - i32::from(l) <= 16;
    let mini = small && i32::from(b) - i32::from(t) <= 12;
    let families = if mini {
        [2, 1, 0]
    } else if small {
        [1, 2, 0]
    } else {
        [0, 1, 2]
    };
    for family in families {
        let (width, height, mono, color4, color8) = match family {
            0 => (32usize, 32usize, *b"ICN#", *b"icl4", *b"icl8"),
            1 => (16, 16, *b"ics#", *b"ics4", *b"ics8"),
            _ => (16, 12, *b"icm#", *b"icm4", *b"icm8"),
        };
        let find = |kind: [u8; 4]| {
            ppc_vfs_resource_index(resources, refnum, u32::from_be_bytes(kind), id, false)
                .map(|index| resources[index].data.as_slice())
        };
        let Some(bitmap) = find(mono) else {
            continue;
        };
        let plane = width * height / 8;
        if bitmap.len() < plane * 2 {
            return Err(PPC_PARAM_ERR);
        }
        let (depth, pixels) = if surface.front_buffer.depth >= 8 {
            if let Some(data) = find(color8) {
                (8u16, data)
            } else if let Some(data) = find(color4) {
                (4, data)
            } else {
                (1, &bitmap[..plane])
            }
        } else if surface.front_buffer.depth >= 4 {
            if let Some(data) = find(color4) {
                (4, data)
            } else {
                (1, &bitmap[..plane])
            }
        } else {
            (1, &bitmap[..plane])
        };
        let pixel_len = plane * usize::from(depth);
        if pixels.len() < pixel_len {
            return Err(PPC_PARAM_ERR);
        }
        return ppc_plot_icon_family(
            rect,
            alignment,
            transform,
            width,
            height,
            depth,
            bitmap,
            pixels,
            memory,
            allocator,
            heap_cursor,
            last_mem_error,
            gworlds,
            port,
            screen_clut,
        );
    }
    Err(PPC_RES_NOT_FOUND_ERR)
}

/// Select an existing suite member and plot it without changing its handles.
/// See More Macintosh Toolbox, Icon Utilities, PlotIconSuite (QD18).
#[allow(clippy::too_many_arguments)]
fn ppc_plot_icon_suite(
    rect: u32,
    alignment: u16,
    transform: u16,
    suite: u32,
    memory: &mut PpcSectionMem,
    allocator: &mut ProcessNativeMemoryManager,
    heap_cursor: &mut u32,
    last_mem_error: &mut i16,
    handles: &[PpcHandleRecord],
    gworlds: &[PpcGWorldRecord],
    port: u32,
    screen_clut: &[[u16; 3]; 256],
) -> Result<bool, i16> {
    // Keep the same supported transform contract as the classic suite path.
    if alignment & !0x000f != 0 || transform & !0x4001 != 0 {
        return Err(PPC_PARAM_ERR);
    }
    let bytes = ppc_handle_bytes(memory, handles, suite).ok_or(PPC_PARAM_ERR)?;
    if bytes.len() < 10 || &bytes[..4] != b"ISUT" || bytes[4..8] != [0; 4] {
        return Err(PPC_PARAM_ERR);
    }
    let count = usize::from(u16::from_be_bytes([bytes[8], bytes[9]]));
    if count > 9 || bytes.len() < 10 + count * 8 {
        return Err(PPC_PARAM_ERR);
    }
    let (top, left, bottom, right) = ppc_read_rect(memory, rect).ok_or(PPC_PARAM_ERR)?;
    let surface = ppc_live_quickdraw_surface(memory, gworlds, port).ok_or(PPC_PARAM_ERR)?;
    if bottom <= top || right <= left {
        return Ok(false);
    }
    let width = i32::from(right) - i32::from(left);
    let height = i32::from(bottom) - i32::from(top);
    let order = if width > 16 || height > 16 {
        [0, 1, 2]
    } else if height > 12 {
        [1, 0, 2]
    } else {
        [2, 1, 0]
    };
    let entries: Vec<(u32, u32)> = bytes[10..10 + count * 8]
        .chunks_exact(8)
        .map(|e| {
            (
                u32::from_be_bytes(e[..4].try_into().unwrap()),
                u32::from_be_bytes(e[4..].try_into().unwrap()),
            )
        })
        .collect();
    for family in order {
        let (w, h, mono, four, eight) = match family {
            0 => (32usize, 32usize, *b"ICN#", *b"icl4", *b"icl8"),
            1 => (16, 16, *b"ics#", *b"ics4", *b"ics8"),
            _ => (16, 12, *b"icm#", *b"icm4", *b"icm8"),
        };
        let plane = w * h / 8;
        let find = |kind: [u8; 4]| {
            entries
                .iter()
                .find(|(t, _)| *t == u32::from_be_bytes(kind))
                .map(|(_, h)| *h)
        };
        let Some(bitmap) = find(mono)
            .and_then(|h| ppc_handle_bytes(memory, handles, h))
            .filter(|b| b.len() >= plane * 2)
        else {
            continue;
        };
        let mut depth = 1u16;
        let mut pixels = bitmap[..plane].to_vec();
        for (candidate, kind) in [(8u16, eight), (4, four)] {
            if u32::from(candidate) > surface.front_buffer.depth {
                continue;
            }
            if let Some(data) = find(kind)
                .and_then(|h| ppc_handle_bytes(memory, handles, h))
                .filter(|b| b.len() >= plane * usize::from(candidate))
            {
                depth = candidate;
                pixels = data;
                break;
            }
        }
        return ppc_plot_icon_family(
            rect,
            alignment,
            transform,
            w,
            h,
            depth,
            &bitmap,
            &pixels,
            memory,
            allocator,
            heap_cursor,
            last_mem_error,
            gworlds,
            port,
            screen_clut,
        );
    }
    Err(-1000)
}

#[allow(clippy::too_many_arguments)]
fn ppc_plot_icon_family(
    rect: u32,
    alignment: u16,
    transform: u16,
    width: usize,
    height: usize,
    depth: u16,
    bitmap: &[u8],
    pixels: &[u8],
    memory: &mut PpcSectionMem,
    allocator: &mut ProcessNativeMemoryManager,
    heap_cursor: &mut u32,
    last_mem_error: &mut i16,
    gworlds: &[PpcGWorldRecord],
    port: u32,
    screen_clut: &[[u16; 3]; 256],
) -> Result<bool, i16> {
    let plane = width * height / 8;
    let pixel_len = plane * usize::from(depth);
    let (palette, count) =
        crate::trap::TrapDispatcher::standard_mac_indexed_clut(depth).ok_or(PPC_PARAM_ERR)?;
    let table_offset = 90 + plane;
    let pixels_offset = table_offset + 8 + count * 8;
    let mut bytes = vec![0u8; pixels_offset + pixel_len];
    // Private live CIcon record plus inline master pointers, mask, CLUT and pixels.
    bytes[4..6].copy_from_slice(&((width * usize::from(depth) / 8) as u16 | 0x8000).to_be_bytes());
    bytes[10..12].copy_from_slice(&(height as u16).to_be_bytes());
    bytes[12..14].copy_from_slice(&(width as u16).to_be_bytes());
    bytes[32..34].copy_from_slice(&depth.to_be_bytes());
    bytes[54..56].copy_from_slice(&((width / 8) as u16).to_be_bytes());
    bytes[60..62].copy_from_slice(&(height as u16).to_be_bytes());
    bytes[62..64].copy_from_slice(&(width as u16).to_be_bytes());
    bytes[90..table_offset].copy_from_slice(&bitmap[plane..plane * 2]);
    bytes[table_offset + 6..table_offset + 8].copy_from_slice(&((count - 1) as u16).to_be_bytes());
    for (index, color) in palette.iter().take(count).enumerate() {
        let offset = table_offset + 8 + index * 8;
        bytes[offset..offset + 2].copy_from_slice(&(index as u16).to_be_bytes());
        for (channel, value) in color.iter().enumerate() {
            bytes[offset + 2 + channel * 2..offset + 4 + channel * 2]
                .copy_from_slice(&value.to_be_bytes());
        }
    }
    bytes[pixels_offset..].copy_from_slice(&pixels[..pixel_len]);
    let base = allocator.new_native_ptr(memory, bytes.len() as u32, true);
    ppc_apply_process_native_allocator(allocator, memory, heap_cursor, last_mem_error);
    if base == 0 {
        return Err(PPC_MEM_FULL_ERR);
    }
    for (offset, pointer) in [
        (0, base + pixels_offset as u32),
        (42, base + 86),
        (50, base + 90),
        (82, base),
        (86, base + table_offset as u32),
    ] {
        bytes[offset..offset + 4].copy_from_slice(&pointer.to_be_bytes());
    }
    let result = if memory.write_bytes(base, &bytes).is_some() {
        let params = crate::cursor_manager::evaluate_plot_cicon_parameters(rect, base + 82);
        ppc_plot_cicon_with_options(
            &params,
            alignment,
            transform,
            memory,
            gworlds,
            port,
            screen_clut,
        )
    } else {
        Err(PPC_MEM_FULL_ERR)
    };
    let _ = allocator.dispose_native_ptr(base);
    ppc_apply_process_native_allocator(allocator, memory, heap_cursor, last_mem_error);
    result
}