//! QuickDraw trap handlers (initialization, port management, pen state,
//! coordinate transforms, region ops, drawing commands).
use super::types::{read_rect, Rect, ShapeOp};
use crate::cpu::{CpuOps, Register};
use crate::machine_profile::REFERENCE_MACHINE_PROFILE;
use crate::memory::{MacMemoryBus, MemoryBus};
use crate::process_context::DEFAULT_QUICKDRAW_HILITE_COLOR;
use crate::quickdraw::fonts::{font_id_for_name, font_name_for_id, get_font_face_scaled};
use crate::quickdraw::raster::region_rows;
use crate::quickdraw::text::get_glyph;
use crate::systems::macintosh::display::{self, CursorImage};
use crate::trap::dispatch::{
selector_operation_route, CachedCopyBitmapInfo, InverseTableCacheEntry, PortDrawState,
RecentColorTableFetch, ScreenCopyBitsRect, SelectorOperationRoute, INVERSE_TABLE_CACHE_LIMIT,
};
use crate::trap::pict;
use crate::Result;
use std::sync::OnceLock;
mod deep_mask_transfer;
mod gpu_deep_mask;
mod icon_suite;
#[derive(Clone, Copy)]
pub(super) struct CopyBitmapInfo {
pub(super) base: u32,
pub(super) row_bytes: u32,
pub(super) bounds_top: i16,
pub(super) bounds_left: i16,
pub(super) bounds_bottom: i16,
pub(super) bounds_right: i16,
pub(super) pixel_size: u32,
pub(super) ctab_handle: u32,
}
fn resolved_row_copy<'a>(
mode: u16,
source: CopyBitmapInfo,
destination: CopyBitmapInfo,
source_rect: [i32; 4],
destination_rect: [i32; 4],
clip: [i32; 4],
palette: Option<&'a [u8; 256]>,
) -> crate::copy_bits::RowCopy<'a> {
use crate::copy_bits::{BytePixmap, RowCopy};
RowCopy {
mode,
source: BytePixmap {
base: source.base,
row_bytes: source.row_bytes,
depth: source.pixel_size,
bounds: [
source.bounds_top,
source.bounds_left,
source.bounds_bottom,
source.bounds_right,
]
.map(i32::from),
},
destination: BytePixmap {
base: destination.base,
row_bytes: destination.row_bytes,
depth: destination.pixel_size,
bounds: [
destination.bounds_top,
destination.bounds_left,
destination.bounds_bottom,
destination.bounds_right,
]
.map(i32::from),
},
source_rect,
destination_rect,
clip,
palette,
}
}
/// Resolved location of an individual pixel in a CGrafPort/GrafPort
/// pixmap. Produced by `resolve_pixel_target` and consumed by
/// `read_cpixel` / `write_cpixel` for SetCPixel and GetCPixel.
#[derive(Clone, Copy)]
struct PixelTarget {
base: u32,
row_bytes: u32,
pixel_size: u16,
dx: u32,
dy: u32,
ctab_handle: u32,
}
#[derive(Clone, Copy)]
pub(super) struct RawPixPat {
pub(super) data_ptr: u32,
pub(super) row_bytes: u32,
pub(super) width: i32,
pub(super) height: i32,
pub(super) pixel_size: u16,
pub(super) clut: [[u16; 3]; 256],
}
/// Smallest clip area (in pixels) for which the whole-row CopyBits path is
/// taken: below it the 256-entry table costs more than the pixels it saves.
const COPY_BITS_ROW_PATH_MIN_PIXELS: i32 = 64;
pub(super) struct RegionMembershipCache {
pub(super) top: i16,
pub(super) rows: Vec<Vec<i16>>,
}
pub(super) use crate::quickdraw::raster::region_rows::RegionBooleanOp;
pub(super) const REGION_HEADER_SIZE: u32 = 10;
const REGION_STOP: i16 = i16::MAX;
const PALETTE_HEADER_SIZE: u32 = 16;
const PALETTE_COLOR_INFO_SIZE: u32 = 16;
const PALETTE_DEFAULT_WINDOW: u32 = u32::MAX;
const C_NO_MEM_ERR: u32 = (-152i32) as u32;
const PM_COURTEOUS: i16 = 0x0000;
const PM_TOLERANT: i16 = 0x0002;
const PM_ANIMATED: i16 = 0x0004;
const PM_EXPLICIT: i16 = 0x0008;
const PM_NO_UPDATES: i16 = -0x8000;
const PM_BK_UPDATES: i16 = -0x6000;
const PM_FG_UPDATES: i16 = -0x4000;
// Classic Color QuickDraw's 8-bit color-arbitration order. The Palette
// Manager walks this spread when a tolerant request has no in-tolerance
// match, preserving the protected white/black endpoints while distributing
// replacements across the device table. This is deliberately not numerical
// CLUT order or nearest-RGB order.
const PM_8BPP_ALLOCATION_ORDER: [u8; 256] = [
0, 255, 16, 18, 20, 22, 24, 63, 47, 95, 79, 127, 111, 159, 143, 31, 15, 254, 238, 222, 206,
190, 174, 62, 46, 94, 78, 126, 110, 158, 142, 26, 14, 253, 237, 221, 205, 189, 173, 61, 45, 93,
77, 125, 109, 157, 141, 29, 13, 252, 236, 220, 204, 188, 172, 156, 44, 124, 76, 92, 108, 60,
140, 28, 12, 251, 235, 219, 203, 187, 171, 155, 43, 123, 75, 91, 107, 59, 139, 27, 11, 250,
234, 218, 202, 186, 170, 154, 42, 122, 74, 90, 106, 58, 138, 30, 10, 249, 233, 217, 201, 185,
169, 153, 41, 121, 73, 89, 105, 57, 137, 25, 9, 248, 232, 216, 200, 184, 168, 152, 40, 120, 72,
88, 104, 56, 136, 175, 8, 247, 231, 215, 199, 183, 167, 151, 39, 119, 71, 87, 103, 55, 135, 23,
7, 246, 230, 214, 198, 182, 166, 150, 38, 118, 70, 86, 102, 54, 134, 191, 6, 245, 229, 213,
197, 181, 165, 149, 37, 117, 69, 85, 101, 53, 133, 21, 5, 244, 228, 212, 196, 180, 164, 148,
36, 116, 68, 84, 100, 52, 132, 207, 4, 243, 227, 211, 195, 179, 163, 147, 35, 115, 67, 83, 99,
51, 131, 19, 3, 242, 226, 210, 194, 178, 162, 146, 34, 114, 66, 82, 98, 50, 130, 223, 2, 241,
225, 209, 193, 177, 161, 49, 33, 81, 65, 113, 97, 145, 129, 17, 1, 240, 224, 208, 192, 176,
160, 48, 32, 80, 64, 112, 96, 144, 128, 239,
];
/// `dstWindow` value that addresses the default palette rather than a window.
/// `SetPalette`/`NSetPalette` take a WindowPtr, and `(WindowPtr)-1` is the
/// long-standing idiom for "the palette to use when no window supplies one" —
/// i.e. the screen's colour environment (Inside Macintosh Volume V, V-166).
const DEFAULT_PALETTE_WINDOW: u32 = 0xFFFF_FFFF;
const PM_ALL_UPDATES: i16 = -0x2000;
const DM_SET_DISPLAY_MODE_REJECT_ERR: i16 = -330;
const DM_640_480_MODE_ID: u32 = 0x80;
const DM_512_342_MODE_ID: u32 = 0x81;
const DM_NATIVE_MODE_ID: u32 = 0x85;
const DM_MODE_LIST_MAGIC: u32 = u32::from_be_bytes(*b"DML1");
const DM_MODE_LIST_ENTRY_STRIDE: u32 = 0x100;
const DM_MODE_LIST_ENTRY_OFFSET: u32 = 0x10;
const DM_MODE_LIST_SWITCH_INFO_OFFSET: u32 = 0x30;
const DM_MODE_LIST_RESOLUTION_INFO_OFFSET: u32 = 0x40;
const DM_MODE_LIST_TIMING_INFO_OFFSET: u32 = 0x60;
const DM_MODE_LIST_DEPTH_BLOCK_OFFSET: u32 = 0x78;
const DM_MODE_LIST_DEPTH_INFO_OFFSET: u32 = 0x90;
const DM_MODE_LIST_VP_BLOCK_OFFSET: u32 = 0xA8;
const DM_MODE_LIST_NAME_OFFSET: u32 = 0xD8;
const SEEDFILL_MAX_PIXELS: usize = 4 * 1024 * 1024;
// OnceLock-cache the tracer env-var lookups. CopyBits/DrawPicture/SetEntries
// fire these helpers thousands of times per session; caching collapses those
// to a single syscall at startup.
static TRACE_MENU_REDRAW: OnceLock<bool> = OnceLock::new();
static TRACE_DIALOG_TEXT: OnceLock<bool> = OnceLock::new();
static TRACE_DIALOG_DRAW: OnceLock<bool> = OnceLock::new();
static TRACE_DIALOG_GWORLD: OnceLock<bool> = OnceLock::new();
static TRACE_DIALOG_PORTS: OnceLock<bool> = OnceLock::new();
static TRACE_DIALOG_PORT_DUMP: OnceLock<bool> = OnceLock::new();
static DUMP_COPYBITS_SRC_PATH: OnceLock<Option<String>> = OnceLock::new();
static TRACE_PALETTE: OnceLock<bool> = OnceLock::new();
static PALETTE_STRICT: OnceLock<bool> = OnceLock::new();
const QD_EXTENSIONS_OPERATION_ROUTES: &[SelectorOperationRoute] =
&include!("generated_qd_extensions_operations.rs");
fn qd_extensions_operation_route(
trap_word: u16,
selector: u32,
) -> Option<&'static SelectorOperationRoute> {
if trap_word != 0xAB1D {
return None;
}
selector_operation_route(QD_EXTENSIONS_OPERATION_ROUTES, selector)
}
const FONT_DISPATCH_OPERATION_ROUTES: &[SelectorOperationRoute] =
&include!("generated_font_dispatch_operations.rs");
fn font_dispatch_operation_route(
trap_word: u16,
selector: u32,
) -> Option<&'static SelectorOperationRoute> {
if trap_word != 0xA854 {
return None;
}
selector_operation_route(FONT_DISPATCH_OPERATION_ROUTES, selector)
}
static PALETTE_AS_GAME_WROTE: OnceLock<bool> = OnceLock::new();
static PICT_SEED_CLUT_DISABLED: OnceLock<bool> = OnceLock::new();
static TRACE_QD_COLORS: OnceLock<bool> = OnceLock::new();
static TRACE_TITLE_DIAG: OnceLock<bool> = OnceLock::new();
static TRACE_GDEVICE_TRAPS: OnceLock<bool> = OnceLock::new();
static TRACE_FONT_TRAPS: OnceLock<bool> = OnceLock::new();
static TRACE_REGION_OPS: OnceLock<bool> = OnceLock::new();
fn trace_menu_redraw_enabled() -> bool {
*TRACE_MENU_REDRAW.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_MENU_REDRAWS").is_some())
}
fn trace_dialog_text_enabled() -> bool {
*TRACE_DIALOG_TEXT.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_TEXT").is_some())
}
fn trace_dialog_draw_enabled() -> bool {
*TRACE_DIALOG_DRAW.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_DRAW").is_some())
}
fn trace_dialog_gworld_enabled() -> bool {
*TRACE_DIALOG_GWORLD
.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_GWORLD").is_some())
}
fn trace_dialog_ports_enabled() -> bool {
*TRACE_DIALOG_PORTS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_PORTS").is_some())
}
fn trace_dialog_port_dump_enabled() -> bool {
*TRACE_DIALOG_PORT_DUMP
.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_PORT_DUMP").is_some())
}
fn dump_copybits_src_path() -> Option<&'static str> {
DUMP_COPYBITS_SRC_PATH
.get_or_init(|| {
std::env::var("SYSTEMLESS_DUMP_COPYBITS_SRC")
.ok()
.map(|value| {
if value.is_empty() || value == "1" {
std::env::temp_dir()
.join("systemless_copybits_src.png")
.display()
.to_string()
} else {
value
}
})
})
.as_deref()
}
fn trace_palette_enabled() -> bool {
*TRACE_PALETTE.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_PALETTE").is_some())
}
fn palette_strict_enabled() -> bool {
*PALETTE_STRICT.get_or_init(|| std::env::var_os("SYSTEMLESS_PALETTE_STRICT").is_some())
}
fn palette_as_game_wrote_enabled() -> bool {
*PALETTE_AS_GAME_WROTE
.get_or_init(|| std::env::var_os("SYSTEMLESS_PALETTE_AS_GAME_WROTE").is_some())
}
/// PICT-CTab seeding is DISABLED by default. The compensator paths that
/// write PICT-embedded CTabs (via `seed_screen_palette_from_picture_clut`
/// and DrawPicture's merge-seed branch) were essentially guessing the
/// scene palette from PICT content when real Mac relies on the
/// application making explicit SetEntries / ActivatePalette calls.
///
/// Opt back in by setting `SYSTEMLESS_PICT_SEED_CLUT_ENABLE=1`.
fn pict_seed_clut_disabled() -> bool {
*PICT_SEED_CLUT_DISABLED
.get_or_init(|| std::env::var_os("SYSTEMLESS_PICT_SEED_CLUT_ENABLE").is_none())
}
fn trace_qd_colors_enabled() -> bool {
*TRACE_QD_COLORS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_QD_COLORS").is_some())
}
fn trace_title_diag_enabled() -> bool {
*TRACE_TITLE_DIAG.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_TITLE_DIAG").is_some())
}
fn trace_gdevice_traps_enabled() -> bool {
*TRACE_GDEVICE_TRAPS
.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_GDEVICE_TRAPS").is_some())
}
fn trace_font_traps_enabled() -> bool {
*TRACE_FONT_TRAPS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_FONT_TRAPS").is_some())
}
fn trace_region_ops_enabled() -> bool {
*TRACE_REGION_OPS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_REGION_OPS").is_some())
}
// Hot-path tracer helpers (CopyBits/DrawPicture/EraseRect/CTab seed fire
// every frame or every PICT).
static TRACE_ERASERECT: OnceLock<bool> = OnceLock::new();
static TRACE_OFFSCREEN_002EAD50: OnceLock<bool> = OnceLock::new();
static TRACE_COPYBITS_ALL: OnceLock<bool> = OnceLock::new();
static TRACE_COPYBITS: OnceLock<bool> = OnceLock::new();
static TRACE_COPYBITS_HUD_PROBE: OnceLock<Option<String>> = OnceLock::new();
static TRACE_COPYBITS_HUD_PROBE_POINTS: OnceLock<Vec<(i16, i16)>> = OnceLock::new();
static TRACE_DRAWPICTURE: OnceLock<bool> = OnceLock::new();
static TRACE_PICT: OnceLock<bool> = OnceLock::new();
static TRACE_FADE_BRANCH: OnceLock<bool> = OnceLock::new();
static TRACE_CTAB_SEED: OnceLock<bool> = OnceLock::new();
fn trace_eraserect_enabled() -> bool {
*TRACE_ERASERECT.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_ERASERECT").is_some())
}
fn trace_offscreen_002ead50_enabled() -> bool {
*TRACE_OFFSCREEN_002EAD50
.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_OFFSCREEN_002EAD50").is_some())
}
fn trace_copybits_all_enabled() -> bool {
*TRACE_COPYBITS_ALL.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_COPYBITS_ALL").is_some())
}
fn trace_copybits_enabled() -> bool {
*TRACE_COPYBITS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_COPYBITS").is_some())
}
fn trace_copybits_hud_probe() -> Option<&'static str> {
TRACE_COPYBITS_HUD_PROBE
.get_or_init(|| {
std::env::var_os("SYSTEMLESS_TRACE_COPYBITS_HUD_PROBE")
.and_then(|os| os.into_string().ok())
})
.as_deref()
}
fn trace_copybits_hud_probe_points() -> &'static [(i16, i16)] {
TRACE_COPYBITS_HUD_PROBE_POINTS
.get_or_init(|| {
let raw = trace_copybits_hud_probe().unwrap_or_default();
let parsed: Vec<(i16, i16)> = raw
.split(';')
.filter_map(|part| {
let (x, y) = part.split_once(',')?;
Some((x.trim().parse().ok()?, y.trim().parse().ok()?))
})
.collect();
if parsed.is_empty() {
vec![(720, 100), (720, 185), (720, 320), (720, 500)]
} else {
parsed
}
})
.as_slice()
}
fn trace_drawpicture_enabled() -> bool {
*TRACE_DRAWPICTURE.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DRAWPICTURE").is_some())
}
// Trace coordinates are relative to pixel storage, and may lie outside it.
fn drawpicture_trace_pixel(
bus: &MacMemoryBus,
mode: (u32, u32, u16, u16, u16),
y: i32,
x: i32,
) -> Option<u32> {
let (base, row_bytes, width, height, depth) = mode;
let row = u32::try_from(y).ok()?;
let col = u32::try_from(x).ok()?;
if row >= u32::from(height) || col >= u32::from(width) {
return None;
}
let bits = u32::from(depth);
if !matches!(bits, 1 | 2 | 4 | 8 | 16 | 32) {
return None;
}
let bit_offset = col.checked_mul(bits)?;
let byte_offset = bit_offset / 8;
let pixel_bytes = (bits / 8).max(1);
if byte_offset.checked_add(pixel_bytes)? > row_bytes {
return None;
}
let address = base
.checked_add(row.checked_mul(row_bytes)?)?
.checked_add(byte_offset)?;
address.checked_add(pixel_bytes - 1)?;
Some(match bits {
1 | 2 | 4 => {
let shift = 8 - bits - bit_offset % 8;
u32::from((bus.read_byte(address) >> shift) & ((1u8 << bits) - 1))
}
8 => u32::from(bus.read_byte(address)),
16 => u32::from(bus.read_word(address)),
32 => bus.read_long(address),
_ => unreachable!(),
})
}
fn trace_pict_inline_enabled() -> bool {
*TRACE_PICT.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_PICT").is_some())
}
fn trace_fade_branch_enabled() -> bool {
*TRACE_FADE_BRANCH.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_FADE_BRANCH").is_some())
}
fn trace_ctab_seed_enabled() -> bool {
*TRACE_CTAB_SEED.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_CTAB_SEED").is_some())
}
fn trace_menu_redraw_rect_intersects(top: i16, left: i16, bottom: i16, right: i16) -> bool {
const MENU_TOP: i16 = 260;
const MENU_LEFT: i16 = 120;
const MENU_BOTTOM: i16 = 390;
const MENU_RIGHT: i16 = 680;
top < MENU_BOTTOM && bottom > MENU_TOP && left < MENU_RIGHT && right > MENU_LEFT
}
fn trace_menu_probe_points() -> [(&'static str, i16, i16); 2] {
[("orb", 337, 220), ("enter_ship", 307, 500)]
}
fn trace_menu_rect_contains_point(
top: i16,
left: i16,
bottom: i16,
right: i16,
y: i16,
x: i16,
) -> bool {
y >= top && y < bottom && x >= left && x < right
}
struct CopyBitsDstFingerprint {
top: [(u8, u32); 3],
idx0_count: u32,
idx255_count: u32,
total: u32,
}
fn copybits_dst_fingerprint(
bus: &MacMemoryBus,
dst_info: &CopyBitmapInfo,
dst_top: i16,
dst_left: i16,
dst_bottom: i16,
dst_right: i16,
) -> CopyBitsDstFingerprint {
let y0 = dst_top.max(dst_info.bounds_top);
let y1 = dst_bottom.min(dst_info.bounds_bottom);
let x0 = dst_left.max(dst_info.bounds_left);
let x1 = dst_right.min(dst_info.bounds_right);
let mut hist = [0u32; 256];
let mut total = 0u32;
if y1 > y0 && x1 > x0 {
for y in y0..y1 {
let dst_y = (y - dst_info.bounds_top) as u32;
let row_base = dst_info.base + dst_y * dst_info.row_bytes;
for x in x0..x1 {
let dst_x = (x - dst_info.bounds_left) as u32;
let b = bus.read_byte(row_base + dst_x);
hist[b as usize] += 1;
total += 1;
}
}
}
let mut pairs: [(u8, u32); 256] = [(0u8, 0u32); 256];
for (i, count) in hist.iter().enumerate() {
pairs[i] = (i as u8, *count);
}
pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
CopyBitsDstFingerprint {
top: [pairs[0], pairs[1], pairs[2]],
idx0_count: hist[0],
idx255_count: hist[255],
total,
}
}
fn decode_text_face_style(raw: u16) -> i16 {
// Style is a bitset byte (IM:I I-171), but callers marshal it in
// either half of the pushed word. MPW C commonly places it in the
// high byte; some hand-written callers use the low byte.
let face = if (raw & 0x00FF) != 0 {
raw & 0x00FF
} else {
raw >> 8
};
face as i16
}
fn encode_text_face_style(face: i16) -> u16 {
// GrafPort.txFace is observed as a Style value in the high byte in
// MPW C layouts; mirror BasiliskII's port record representation.
((face as u16) & 0x00FF) << 8
}
/// ScrollRect geometry for `scroll_color_rows`.
struct ScrollRows {
base: u32,
row_bytes: u32,
/// The rect's (row, byte column) within the pixmap.
origin: (u32, u32),
/// The rect's top-left in port coordinates, for tiling the pattern.
canvas: (i16, i16),
/// Width (bytes) and height of the rect.
size: (i32, i32),
delta: (i16, i16),
background: [u8; 8],
}
impl super::TrapDispatcher {
/// Install a basic QuickDraw bit pattern in a color port without changing
/// the caller-owned color PixPat that was previously installed there.
fn install_port_bit_pixpat(&mut self, bus: &mut MacMemoryBus, offset: u32, pattern: [u8; 8]) {
let port = *self.current_port;
if port == 0 || !self.port_allows_draw_state_memory_sync(bus, port)
|| (bus.read_word(port + 6) & 0xC000) != 0xC000
{
return;
}
let old = bus.read_long(port + offset);
let handle = if self.owned_bit_pixpats.contains(&old)
&& bus.get_alloc_size(old) == Some(4)
&& bus.get_alloc_size(bus.read_long(old)).is_some_and(|size| size >= 28)
{
old
} else {
let record = bus.alloc(28);
let handle = bus.alloc(4);
if record == 0 || handle == 0 {
if record != 0 { bus.free(record); }
if handle != 0 { bus.free(handle); }
return;
}
for i in 0..28 { bus.write_byte(record + i, 0); }
bus.write_long(handle, record);
self.owned_bit_pixpats.insert(handle);
handle
};
let record = bus.read_long(handle);
bus.write_word(record, 0);
bus.write_bytes(record + 20, &pattern);
bus.write_long(port + offset, handle);
}
fn dispose_color_compound_handle(&mut self, bus: &mut MacMemoryBus, handle: u32) {
self.owned_bit_pixpats.remove(&handle);
if bus.get_alloc_size(handle) != Some(4) {
return;
}
let record = bus.read_long(handle);
if bus.get_alloc_size(record).is_none() {
return;
}
// PixPat and CCrsr deliberately share their leading compound-object
// layout: map handle at +2, data at +6, expanded data at +10, and an
// expansion handle at +16. Inside Macintosh Volume V,
// V-55--V-56 and V-63; Imaging With QuickDraw (1994), pp. 4-58 and
// 8-4--8-5. Their disposal routines therefore release the same owned
// handle graph before releasing the record and master pointer.
for offset in [6u32, 10, 16] {
Self::free_memory_handle(bus, bus.read_long(record + offset));
}
Self::free_pixmap_handle(bus, bus.read_long(record + 2));
bus.free(record);
bus.write_long(handle, 0);
bus.free(handle);
self.makergbpat_colors.remove(&handle);
}
fn get_or_create_std_pix_gateway(&mut self, bus: &mut MacMemoryBus) -> u32 {
let unimplemented = self.get_or_create_tool_trap_trampoline(bus, 0xAA6E);
if self.std_pix_gateway == 0 {
self.std_pix_gateway = bus.alloc_synthetic(6);
bus.protect_readonly_code(self.std_pix_gateway, 6);
}
// StdPix is a distinct callable procedure with no A-line identity.
// QuickTime (1993), pp. 3-137--3-139 defines its eight-argument ABI.
// Preserve a unique callable address and fail through the documented
// `_Unimplemented` routine until the operation is implemented, rather
// than exposing a host marker or guessing partial drawing semantics.
bus.write_readonly_code_word(self.std_pix_gateway, 0x4EF9);
bus.write_readonly_code_word(self.std_pix_gateway + 2, (unimplemented >> 16) as u16);
bus.write_readonly_code_word(self.std_pix_gateway + 4, unimplemented as u16);
self.std_pix_gateway
}
pub(super) fn loaded_font_id_for_name(&self, name: &str) -> Option<i16> {
let needle = name.trim();
if needle.is_empty() {
return None;
}
let resources = self.resources.as_ref()?;
for refnum in self.resource_search_order() {
let Some(file) = resources.files.get(&refnum) else {
continue;
};
for ((res_type, res_name), (res_id, _)) in &file.named {
if res_type == b"FOND" && res_name.trim().eq_ignore_ascii_case(needle) {
return Some(*res_id);
}
}
}
None
}
fn loaded_font_name_for_id(&self, font_id: i16) -> Option<&str> {
let resources = self.resources.as_ref()?;
for refnum in self.resource_search_order() {
let Some(file) = resources.files.get(&refnum) else {
continue;
};
for ((res_type, res_name), (res_id, _)) in &file.named {
if res_type == b"FOND" && *res_id == font_id {
return Some(res_name.as_str());
}
}
}
None
}
pub(crate) fn dispatch_quickdraw<C: CpuOps>(
&mut self,
is_tool: bool,
trap_num: u16,
cpu: &mut C,
bus: &mut MacMemoryBus,
) -> Option<Result<()>> {
self.read_tick_count(bus);
if self.process_quickdraw_port_state_attached {
let port = *self.current_port;
self.load_port_draw_state(bus, port);
}
Some(match (is_tool, trap_num) {
// ========== QuickDraw Initialization ==========
// InitGraf ($A86E)
// InitGraf ($A86E): Sets up global QD vars, white/black patterns, screenBits, randSeed
(true, 0x06E) => {
let sp = cpu.read_reg(Register::A7);
let global_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
eprintln!(
"[INITGRAF] global_ptr=${:08X} randSeed_addr=${:08X}",
global_ptr,
global_ptr.wrapping_sub(126)
);
let a5 = cpu.read_reg(Register::A5);
bus.write_long(a5, global_ptr);
let mut write_pat = |offset: i32, bytes: &[u8]| {
let addr = global_ptr.wrapping_add(offset as u32);
bus.write_bytes(addr, bytes);
};
write_pat(-8, &[0x00; 8]);
write_pat(-16, &[0xFF; 8]);
write_pat(-24, &[0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]);
write_pat(-32, &[0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22]);
write_pat(-40, &[0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD]);
// IM:I I-145/I-147 and I-162 list `arrow` as the
// predefined standard arrow Cursor global between
// `dkGray` and `screenBits`. With globalPtr == @thePort,
// reverse QuickDraw globals place it at globalPtr-108.
let (arrow_data, arrow_mask, arrow_hot_v, arrow_hot_h) =
Self::default_arrow_cursor();
let arrow_addr = global_ptr.wrapping_sub(108);
bus.write_bytes(arrow_addr, &arrow_data);
bus.write_bytes(arrow_addr + 32, &arrow_mask);
bus.write_word(arrow_addr + 64, arrow_hot_v as u16);
bus.write_word(arrow_addr + 66, arrow_hot_h as u16);
// Populate qd.screenBits from the runner's authoritative
// screen_mode rather than from low-mem global $083C —
// some apps (e.g. Centaurian 1.2.1's CRT) zero out the
// $083C area as part of their init pass, which would
// otherwise leave qd.screenBits with NIL baseAddr and
// bounds (0,0,0,0). Reading from screen_mode keeps us
// robust against guest low-mem global stomping.
let screen_bits_addr = global_ptr.wrapping_sub(122);
let (screen_base, screen_rb, screen_w, screen_h, _ps) = self.screen_mode;
bus.write_long(screen_bits_addr, screen_base); // baseAddr
bus.write_word(screen_bits_addr + 4, screen_rb as u16); // rowBytes
bus.write_word(screen_bits_addr + 6, 0); // bounds.top
bus.write_word(screen_bits_addr + 8, 0); // bounds.left
bus.write_word(screen_bits_addr + 10, screen_h); // bounds.bottom
bus.write_word(screen_bits_addr + 12, screen_w); // bounds.right
// Mirror the same values back to $083C in case the guest
// re-reads them after the wipe.
let sb_src = crate::memory::globals::addr::SCREEN_BITS;
bus.write_long(sb_src, screen_base);
bus.write_word(sb_src + 4, screen_rb as u16);
bus.write_word(sb_src + 6, 0);
bus.write_word(sb_src + 8, 0);
bus.write_word(sb_src + 10, screen_h);
bus.write_word(sb_src + 12, screen_w);
let sb_top: u16 = 0;
let sb_left: u16 = 0;
let sb_bottom: u16 = screen_h;
let sb_right: u16 = screen_w;
eprintln!(
"[INITGRAF] screenBits: base=${:08X} rowBytes={} bounds=(0,0,{},{})",
screen_base, screen_rb, screen_h, screen_w
);
bus.write_long(global_ptr.wrapping_sub(126), 1); // randSeed
// Allocate + initialise a default screen GrafPort and store
// its pointer in qd.thePort. Real Mac OS's InitGraf creates
// this default port pointing at the screen so apps can
// immediately draw before opening their own GrafPort.
let port_ptr = bus.alloc(108);
let alloc_rgn =
|bus: &mut MacMemoryBus, top: u16, left: u16, bottom: u16, right: u16| {
let ptr = bus.alloc(10);
bus.write_word(ptr, 10);
bus.write_word(ptr + 2, top);
bus.write_word(ptr + 4, left);
bus.write_word(ptr + 6, bottom);
bus.write_word(ptr + 8, right);
let handle = bus.alloc(4);
bus.write_long(handle, ptr);
handle
};
let vis_rgn = alloc_rgn(bus, sb_top, sb_left, sb_bottom, sb_right);
// IM:I I-163: OpenPort/InitPort default clip is the
// infinite QuickDraw rectangle, not screen bounds.
let clip_rgn = alloc_rgn(
bus,
(-32767_i16) as u16,
(-32767_i16) as u16,
32767_u16,
32767_u16,
);
bus.write_word(port_ptr, 0); // device
for i in 0..14 {
bus.write_byte(port_ptr + 2 + i, bus.read_byte(screen_bits_addr + i));
}
for i in 0..8 {
bus.write_byte(port_ptr + 16 + i, bus.read_byte(screen_bits_addr + 6 + i));
}
bus.write_long(port_ptr + 24, vis_rgn);
bus.write_long(port_ptr + 28, clip_rgn);
bus.write_bytes(port_ptr + 32, &[0x00; 8]); // bgPat = white
bus.write_bytes(port_ptr + 40, &[0xFF; 8]); // fillPat = black
bus.write_long(port_ptr + 48, 0); // pnLoc
bus.write_word(port_ptr + 52, 1); // pnSize.v
bus.write_word(port_ptr + 54, 1); // pnSize.h
bus.write_word(port_ptr + 56, 8); // pnMode = patCopy
bus.write_bytes(port_ptr + 58, &[0xFF; 8]); // pnPat = black
bus.write_word(port_ptr + 66, 0); // pnVis
bus.write_word(port_ptr + 68, 0); // txFont = system
bus.write_word(port_ptr + 70, 0); // txFace = plain
bus.write_word(port_ptr + 72, 1); // txMode = srcOr
bus.write_word(port_ptr + 74, 0); // txSize
bus.write_long(port_ptr + 76, 0); // spExtra
bus.write_long(port_ptr + 80, 0x00000021); // fgColor = blackColor
bus.write_long(port_ptr + 84, 0x0000001E); // bkColor = whiteColor
// qd.thePort now points at this port.
bus.write_long(global_ptr, port_ptr);
self.port_draw_states
.insert(port_ptr, PortDrawState::default());
self.set_current_port_state(bus, cpu, port_ptr, None);
eprintln!(
"[INITGRAF] qd.thePort=${:08X} (default screen port)",
port_ptr
);
Ok(())
}
// OpenPort ($A86F)
// OpenPort ($A86F): Allocates visRgn/clipRgn, sets pen defaults, stores as current port
(true, 0x06F) => {
let sp = cpu.read_reg(Register::A7);
let port_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let screen_bits_addr = global_ptr.wrapping_sub(122);
let sb_top = bus.read_word(screen_bits_addr + 6);
let sb_left = bus.read_word(screen_bits_addr + 8);
let sb_bottom = bus.read_word(screen_bits_addr + 10);
let sb_right = bus.read_word(screen_bits_addr + 12);
let alloc_rgn =
|bus: &mut MacMemoryBus, top: u16, left: u16, bottom: u16, right: u16| {
let ptr = bus.alloc(10);
bus.write_word(ptr, 10);
bus.write_word(ptr + 2, top);
bus.write_word(ptr + 4, left);
bus.write_word(ptr + 6, bottom);
bus.write_word(ptr + 8, right);
let handle = bus.alloc(4);
bus.write_long(handle, ptr);
handle
};
let vis_rgn = alloc_rgn(bus, sb_top, sb_left, sb_bottom, sb_right);
// IM:I I-163: OpenPort initializes clipRgn to
// (-32767,-32767,32767,32767).
let clip_rgn = alloc_rgn(
bus,
(-32767_i16) as u16,
(-32767_i16) as u16,
32767_u16,
32767_u16,
);
bus.write_word(port_ptr, 0);
for i in 0..14 {
bus.write_byte(port_ptr + 2 + i, bus.read_byte(screen_bits_addr + i));
}
for i in 0..8 {
bus.write_byte(port_ptr + 16 + i, bus.read_byte(screen_bits_addr + 6 + i));
}
bus.write_long(port_ptr + 24, vis_rgn);
bus.write_long(port_ptr + 28, clip_rgn);
bus.write_bytes(port_ptr + 32, &[0x00; 8]);
bus.write_bytes(port_ptr + 40, &[0xFF; 8]);
bus.write_long(port_ptr + 48, 0);
bus.write_word(port_ptr + 52, 1);
bus.write_word(port_ptr + 54, 1);
self.pn_loc = (0, 0);
self.pn_size = (1, 1);
self.pn_mode = 8;
self.pn_pat = [0xFF; 8];
bus.write_word(port_ptr + 56, 8);
bus.write_bytes(port_ptr + 58, &[0xFF; 8]);
bus.write_word(port_ptr + 66, 0);
// Zero out the GrafPort fields that the caller's stack-
// allocated port memory may have left as garbage. SpaceExtra
// (port+76) is read by draw_char per IM:I I-171 to add per-
// space-character extra advance, so a garbage value would
// randomise text spacing.
bus.write_word(port_ptr + 68, 0); // txFont = system font
bus.write_word(port_ptr + 70, 0); // txFace = plain
bus.write_word(port_ptr + 72, 1); // txMode = srcOr
bus.write_word(port_ptr + 74, 0); // txSize = 0 (use default)
bus.write_long(port_ptr + 76, 0); // spExtra = 0 (Fixed)
bus.write_long(port_ptr + 80, 0x00000021); // fgColor = blackColor
bus.write_long(port_ptr + 84, 0x0000001E); // bkColor = whiteColor
self.port_draw_states
.insert(port_ptr, PortDrawState::default());
self.set_current_port_state(bus, cpu, port_ptr, None);
if trace_dialog_ports_enabled() {
eprintln!("[DIALOG-PORT] OpenPort port=${:08X}", port_ptr);
}
Ok(())
}
// InitPort ($A86D)
// InitPort ($A86D): Like OpenPort, also sets as current port via A5 globals
(true, 0x06D) => {
let sp = cpu.read_reg(Register::A7);
let port_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let screen_bits_addr = global_ptr.wrapping_sub(122);
let is_stack_port = port_ptr >= sp.saturating_sub(0x10000)
&& port_ptr <= sp.saturating_add(0x10000);
bus.write_word(port_ptr, 0);
if !is_stack_port {
for i in 0..14 {
bus.write_byte(port_ptr + 2 + i, bus.read_byte(screen_bits_addr + i));
}
for i in 0..8 {
bus.write_byte(port_ptr + 16 + i, bus.read_byte(screen_bits_addr + 6 + i));
}
bus.write_bytes(port_ptr + 32, &[0x00; 8]);
bus.write_bytes(port_ptr + 40, &[0xFF; 8]);
bus.write_long(port_ptr + 48, 0);
bus.write_word(port_ptr + 52, 1);
bus.write_word(port_ptr + 54, 1);
bus.write_word(port_ptr + 56, 8);
bus.write_bytes(port_ptr + 58, &[0xFF; 8]);
bus.write_word(port_ptr + 66, 0);
bus.write_word(port_ptr + 68, 0);
bus.write_word(port_ptr + 70, 0);
bus.write_word(port_ptr + 72, 1);
bus.write_word(port_ptr + 74, 0);
bus.write_long(port_ptr + 76, 0);
bus.write_long(port_ptr + 80, 0x00000021);
bus.write_long(port_ptr + 84, 0x0000001E);
// IM:I I-164: InitPort does everything OpenPort does
// except allocate visRgn/clipRgn. Reinitialize existing
// region records in place when handles are present.
let vis_handle = bus.read_long(port_ptr + 24);
if vis_handle != 0 {
let vis_ptr = bus.read_long(vis_handle);
if vis_ptr != 0 {
bus.write_word(vis_ptr, 10);
bus.write_word(vis_ptr + 2, bus.read_word(screen_bits_addr + 6));
bus.write_word(vis_ptr + 4, bus.read_word(screen_bits_addr + 8));
bus.write_word(vis_ptr + 6, bus.read_word(screen_bits_addr + 10));
bus.write_word(vis_ptr + 8, bus.read_word(screen_bits_addr + 12));
}
}
let clip_handle = bus.read_long(port_ptr + 28);
if clip_handle != 0 {
let clip_ptr = bus.read_long(clip_handle);
if clip_ptr != 0 {
bus.write_word(clip_ptr, 10);
bus.write_word(clip_ptr + 2, (-32767_i16) as u16);
bus.write_word(clip_ptr + 4, (-32767_i16) as u16);
bus.write_word(clip_ptr + 6, 32767_u16);
bus.write_word(clip_ptr + 8, 32767_u16);
}
}
}
self.port_draw_states
.insert(port_ptr, PortDrawState::default());
self.set_current_port_state(bus, cpu, port_ptr, None);
if trace_dialog_ports_enabled() {
eprintln!(
"[DIALOG-PORT] InitPort port=${:08X} stack_port={}",
port_ptr, is_stack_port
);
}
Ok(())
}
// ========== Port Management ==========
// GetPort ($A874)
// GetPort ($A874): Returns current port pointer
(true, 0x074) => {
let sp = cpu.read_reg(Register::A7);
let port_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let port = self.effective_the_port(bus, cpu.read_reg(Register::A5));
if port_ptr != port {
bus.write_long(port_ptr, port);
}
Ok(())
}
// SetPort ($A873)
// Makes the specified grafPort the current port.
// PROCEDURE SetPort(port: GrafPtr);
// Inside Macintosh Volume I, p. I-165.
(true, 0x073) => {
let sp = cpu.read_reg(Register::A7);
let port = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if trace_dialog_ports_enabled() {
eprintln!(
"[DIALOG-PORT] SetPort pc=${:08X} tick={} port=${:08X}",
cpu.read_reg(Register::PC).wrapping_sub(2),
self.current_tick(),
port
);
}
if port != 0 && !self.port_allows_draw_state_memory_sync(bus, port) {
if trace_dialog_ports_enabled() {
eprintln!("[DIALOG-PORT] SetPort ignored invalid port=${:08X}", port);
}
return Some(Ok(()));
}
// SetPort changes ThePort, not TheGDevice. Color QuickDraw
// code that avoids SetGWorld is expected to pair SetGDevice
// with SetPort for offscreen drawing (Imaging With QuickDraw
// 1994, p. 5-24; Inside Macintosh Volume V, p. V-124).
let current_gdevice = (*self.current_gdevice != 0).then_some(*self.current_gdevice);
self.set_current_port_state(bus, cpu, port, current_gdevice);
Ok(())
}
// SetPortBits / SetPortPix ($A875)
//
// Basic and Color QuickDraw share this trap. SetPortBits copies a
// BitMap into a basic GrafPort, while SetPortPix replaces only the
// portPixMap handle of a CGrafPort. Each operation is documented
// to have no effect on the other kind of port. Inside Macintosh:
// Imaging With QuickDraw (1994), pp. 4-86..4-87.
(true, 0x075) => {
let sp = cpu.read_reg(Register::A7);
let bits_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = self.effective_the_port(bus, cpu.read_reg(Register::A5));
let is_cgraf_port = (bus.read_word(port_ptr + 6) & 0xC000) == 0xC000;
if is_cgraf_port {
bus.write_long(port_ptr + 2, bits_ptr);
} else {
for i in 0..14 {
bus.write_byte(port_ptr + 2 + i, bus.read_byte(bits_ptr + i));
}
}
self.cache_portbits_pixmap_handle(bus, port_ptr + 2, bus.read_long(port_ptr + 2));
if trace_dialog_ports_enabled() {
if is_cgraf_port {
eprintln!(
"[DIALOG-PORT] SetPortPix port=${:08X} pixmap_handle=${:08X}",
port_ptr, bits_ptr
);
} else {
eprintln!(
"[DIALOG-PORT] SetPortBits port=${:08X} bits_ptr=${:08X}",
port_ptr, bits_ptr
);
}
}
Ok(())
}
// PortSize ($A876)
// Changes the size of the current grafPort's portRect.
// PROCEDURE PortSize (width,height: INTEGER);
// Inside Macintosh Volume I, I-165
//
// Only portRect changes: its top-left corner is preserved
// while its dimensions become (width, height). The clipRgn
// and visRgn bounding boxes are left untouched.
(true, 0x076) => {
let sp = cpu.read_reg(Register::A7);
let height = bus.read_word(sp) as i16;
let width = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = self.effective_the_port(bus, cpu.read_reg(Register::A5));
let top = bus.read_word(port_ptr + 16) as i16;
let left = bus.read_word(port_ptr + 18) as i16;
bus.write_word(port_ptr + 20, (top + height) as u16);
bus.write_word(port_ptr + 22, (left + width) as u16);
Ok(())
}
// MovePortTo ($A877)
// PROCEDURE MovePortTo (leftGlobal,topGlobal: INTEGER);
// Inside Macintosh Volume I (1985), p. I-166;
// Imaging With QuickDraw (1994), section "MovePortTo".
//
// IM:I I-166 verbatim: "MovePortTo changes the position of
// the current grafPort's portRect. This does not affect the
// screen; it merely changes the location at which subsequent
// drawing inside the port will appear. ... The leftGlobal
// and topGlobal parameters set the distance between the top
// left corner of portBits.bounds and the top left corner of
// the new portRect. Like PortSize, MovePortTo doesn't change
// the clipRgn or the visRgn, nor does it affect the local
// coordinate system of the grafPort."
//
// Effect: portRect, clipRgn, visRgn, and the bitmap dimensions
// are unchanged. portBits.bounds (or PixMap.bounds for color
// ports) is SHIFTED so that
//
// portRect.topLeft - portBits.bounds.topLeft
// = (leftGlobal, topGlobal).
//
// Equivalently, portBits.bounds.topLeft becomes
// portRect.topLeft - (leftGlobal, topGlobal),
// and portBits.bounds.bottomRight shifts by the same delta
// (bitmap width/height preserved).
//
// BasiliskII-witnessed counter-example for the obvious-but-
// wrong "move portRect, leave bits.bounds" interpretation:
// pre portRect=(100,200,220,360), bits.bounds=(100,200,220,360)
// call MovePortTo(leftGlobal=50, topGlobal=30)
// post portRect=(100,200,220,360) ← UNCHANGED
// bits.bounds=(70,150,190,310) ← topLeft shifted
// verify: 100 - 70 = 30 = topGlobal,
// 200 - 150 = 50 = leftGlobal.
//
// Why this matters for the Window Manager use case: a window's
// portRect typically stays at local (0,0,W,H) regardless of
// where the window sits on the global screen. Moving the
// window updates the local→bitmap mapping (portBits.bounds)
// so the same local coords now draw into different screen
// pixels. The window's internal coordinate system never
// shifts under the application's feet — which is what the
// IM means by "doesn't affect the local coordinate system."
//
// Pascal PROCEDURE protocol:
// sp+0: topGlobal (INTEGER, pushed second, closer to SP)
// sp+2: leftGlobal (INTEGER, pushed first, deeper in stack)
// Trap pops 4 bytes; no function-result slot.
//
// MPW Universal Headers Quickdraw.h declares
// EXTERN_API(void) MovePortTo(short leftGlobal,
// short topGlobal)
// ONEWORDINLINE(0xA877);
//
// Color ports: for CGrafPort (portVersion high bits set),
// portBits is replaced by a PixMapHandle at offset 2; the
// PixMap.bounds at PixMapPtr + 6..14 is shifted by the same
// delta as a GrafPort's portBits.bounds.
(true, 0x077) => {
let sp = cpu.read_reg(Register::A7);
let top_global = bus.read_word(sp) as i16;
let left_global = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = self.effective_the_port(bus, cpu.read_reg(Register::A5));
// IM:I I-166: shift portBits.bounds so that
// portRect.topLeft - bits.bounds.topLeft = (leftGlobal, topGlobal).
let port_rect_top = bus.read_word(port_ptr + 16) as i16;
let port_rect_left = bus.read_word(port_ptr + 18) as i16;
let new_bits_top = port_rect_top.wrapping_sub(top_global);
let new_bits_left = port_rect_left.wrapping_sub(left_global);
let port_version = bus.read_word(port_ptr + 6);
let is_color = (port_version & 0xC000) != 0;
if is_color {
// CGrafPort: portPixMap handle at offset 2 → PixMapPtr.
let pm_handle = bus.read_long(port_ptr + 2);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
let bits_top = bus.read_word(pm_ptr + 6) as i16;
let bits_left = bus.read_word(pm_ptr + 8) as i16;
let bits_bottom = bus.read_word(pm_ptr + 10) as i16;
let bits_right = bus.read_word(pm_ptr + 12) as i16;
let bits_height = bits_bottom.wrapping_sub(bits_top);
let bits_width = bits_right.wrapping_sub(bits_left);
bus.write_word(pm_ptr + 6, new_bits_top as u16);
bus.write_word(pm_ptr + 8, new_bits_left as u16);
bus.write_word(
pm_ptr + 10,
new_bits_top.wrapping_add(bits_height) as u16,
);
bus.write_word(
pm_ptr + 12,
new_bits_left.wrapping_add(bits_width) as u16,
);
}
}
} else {
// GrafPort: portBits.bounds at offsets 8..14.
let bits_top = bus.read_word(port_ptr + 8) as i16;
let bits_left = bus.read_word(port_ptr + 10) as i16;
let bits_bottom = bus.read_word(port_ptr + 12) as i16;
let bits_right = bus.read_word(port_ptr + 14) as i16;
let bits_height = bits_bottom.wrapping_sub(bits_top);
let bits_width = bits_right.wrapping_sub(bits_left);
bus.write_word(port_ptr + 8, new_bits_top as u16);
bus.write_word(port_ptr + 10, new_bits_left as u16);
bus.write_word(port_ptr + 12, new_bits_top.wrapping_add(bits_height) as u16);
bus.write_word(port_ptr + 14, new_bits_left.wrapping_add(bits_width) as u16);
}
Ok(())
}
// SetOrigin ($A878)
// Changes the local coordinate system of the current grafPort.
// Offsets portRect, portBits.bounds, and visRgn by the delta.
// Does NOT offset clipRgn — it "sticks" to the coordinate system.
// PROCEDURE SetOrigin(h, v: INTEGER);
// Inside Macintosh Volume I, I-166
(true, 0x078) => {
self.debug_set_origin_count = self.debug_set_origin_count.saturating_add(1);
let sp = cpu.read_reg(Register::A7);
let v = bus.read_word(sp) as i16;
let h = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = self.effective_the_port(bus, cpu.read_reg(Register::A5));
let top = bus.read_word(port_ptr + 16) as i16;
let left = bus.read_word(port_ptr + 18) as i16;
let bottom = bus.read_word(port_ptr + 20) as i16;
let right = bus.read_word(port_ptr + 22) as i16;
let dh = h - left;
let dv = v - top;
if trace_dialog_ports_enabled() {
eprintln!(
"[DIALOG-PORT] SetOrigin port=${:08X} old=({}, {}) new=({}, {}) delta=({}, {})",
port_ptr, top, left, v, h, dv, dh
);
}
// Update portRect (wrapping arithmetic for 16-bit coordinate space)
bus.write_word(port_ptr + 16, top.wrapping_add(dv) as u16);
bus.write_word(port_ptr + 18, left.wrapping_add(dh) as u16);
bus.write_word(port_ptr + 20, bottom.wrapping_add(dv) as u16);
bus.write_word(port_ptr + 22, right.wrapping_add(dh) as u16);
// Update portBits/portPixMap bounds.
// In a GrafPort, portBits.bounds is at offsets 8-14.
// In a CGrafPort, offsets 8-14 are grafVars/chExtra/pnLocHFrac
// (NOT bitmap bounds), so we must update the PixMap bounds instead.
let port_version = bus.read_word(port_ptr + 6);
let is_color = (port_version & 0xC000) != 0;
if is_color {
// CGrafPort: update the PixMap bounds via the handle at offset 2.
let pm_handle = bus.read_long(port_ptr + 2);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
let bt = bus.read_word(pm_ptr + 6) as i16;
let bl = bus.read_word(pm_ptr + 8) as i16;
let bb = bus.read_word(pm_ptr + 10) as i16;
let br = bus.read_word(pm_ptr + 12) as i16;
bus.write_word(pm_ptr + 6, bt.wrapping_add(dv) as u16);
bus.write_word(pm_ptr + 8, bl.wrapping_add(dh) as u16);
bus.write_word(pm_ptr + 10, bb.wrapping_add(dv) as u16);
bus.write_word(pm_ptr + 12, br.wrapping_add(dh) as u16);
}
}
} else {
// GrafPort: portBits.bounds at offsets 8-14.
let bits_top = bus.read_word(port_ptr + 8) as i16;
let bits_left = bus.read_word(port_ptr + 10) as i16;
let bits_bottom = bus.read_word(port_ptr + 12) as i16;
let bits_right = bus.read_word(port_ptr + 14) as i16;
bus.write_word(port_ptr + 8, bits_top.wrapping_add(dv) as u16);
bus.write_word(port_ptr + 10, bits_left.wrapping_add(dh) as u16);
bus.write_word(port_ptr + 12, bits_bottom.wrapping_add(dv) as u16);
bus.write_word(port_ptr + 14, bits_right.wrapping_add(dh) as u16);
}
// Per IM:I I-166, SetOrigin offsets visRgn but NOT clipRgn.
// "the pen and clipRgn 'stick' to the coordinate system"
// visRgn is at port offset 24; clipRgn at 28 is left unchanged.
let vis_handle = bus.read_long(port_ptr + 24);
if vis_handle != 0 {
let vis_ptr = bus.read_long(vis_handle);
if vis_ptr != 0 {
let rt = bus.read_word(vis_ptr + 2) as i16;
let rl = bus.read_word(vis_ptr + 4) as i16;
let rb = bus.read_word(vis_ptr + 6) as i16;
let rr = bus.read_word(vis_ptr + 8) as i16;
bus.write_word(vis_ptr + 2, rt.wrapping_add(dv) as u16);
bus.write_word(vis_ptr + 4, rl.wrapping_add(dh) as u16);
bus.write_word(vis_ptr + 6, rb.wrapping_add(dv) as u16);
bus.write_word(vis_ptr + 8, rr.wrapping_add(dh) as u16);
}
}
Ok(())
}
// ========== Clipping ==========
// SetClip ($A879)
// Changes the clipping region of the current grafPort to an
// equivalent copy of the given region without changing the port's
// clipRgn handle.
// PROCEDURE SetClip (rgn: RgnHandle);
// Inside Macintosh Volume I, I-167
(true, 0x079) => {
let sp = cpu.read_reg(Register::A7);
let src_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = if *self.current_port != 0 {
*self.current_port
} else {
let a5 = cpu.read_reg(Register::A5);
let global_ptr = if a5 != 0 { bus.read_long(a5) } else { 0 };
if global_ptr != 0 {
bus.read_long(global_ptr)
} else {
bus.read_long(crate::memory::globals::addr::THE_PORT)
}
};
let dst_handle = if port_ptr != 0 {
bus.read_long(port_ptr + 28)
} else {
0
};
if src_handle != 0 && dst_handle != 0 {
let src_ptr = bus.read_long(src_handle);
if src_ptr != 0 {
let size = bus.read_word(src_ptr) as u32;
// SetClip copies the region data into the port-owned
// clip region. Replacing the handle aliases caller
// scratch regions into the port and lets later region
// edits corrupt clipping state.
// Inside Macintosh Volume I, p. I-192
let Some(dst_ptr) = Self::ensure_region_capacity(bus, dst_handle, size)
else {
return Some(Ok(()));
};
for i in 0..size {
bus.write_byte(dst_ptr + i, bus.read_byte(src_ptr + i));
}
if trace_dialog_ports_enabled() {
let top = bus.read_word(src_ptr + 2) as i16;
let left = bus.read_word(src_ptr + 4) as i16;
let bottom = bus.read_word(src_ptr + 6) as i16;
let right = bus.read_word(src_ptr + 8) as i16;
eprintln!(
"[DIALOG-PORT] SetClip port=${:08X} rect=({},{},{},{})",
port_ptr, top, left, bottom, right
);
}
}
}
Ok(())
}
// GetClip ($A87A)
// Changes the given region to an equivalent copy of the current
// grafPort's clipping region without changing the given region's
// handle.
// PROCEDURE GetClip (rgn: RgnHandle);
// Inside Macintosh Volume I, I-167
(true, 0x07A) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = if *self.current_port != 0 {
*self.current_port
} else {
let a5 = cpu.read_reg(Register::A5);
let global_ptr = if a5 != 0 { bus.read_long(a5) } else { 0 };
if global_ptr != 0 {
bus.read_long(global_ptr)
} else {
bus.read_long(crate::memory::globals::addr::THE_PORT)
}
};
let clip_rgn = if port_ptr != 0 {
bus.read_long(port_ptr + 28)
} else {
0
};
if rgn_handle != 0 && clip_rgn != 0 {
let clip_rgn_ptr = bus.read_long(clip_rgn);
if clip_rgn_ptr != 0 {
let rgn_size = bus.read_word(clip_rgn_ptr) as u32;
let Some(dest_ptr) =
Self::ensure_region_capacity(bus, rgn_handle, rgn_size)
else {
return Some(Ok(()));
};
for i in 0..rgn_size {
bus.write_byte(dest_ptr + i, bus.read_byte(clip_rgn_ptr + i));
}
if trace_dialog_ports_enabled() {
let top = bus.read_word(clip_rgn_ptr + 2) as i16;
let left = bus.read_word(clip_rgn_ptr + 4) as i16;
let bottom = bus.read_word(clip_rgn_ptr + 6) as i16;
let right = bus.read_word(clip_rgn_ptr + 8) as i16;
eprintln!(
"[DIALOG-PORT] GetClip port=${:08X} rect=({},{},{},{})",
port_ptr, top, left, bottom, right
);
}
}
}
Ok(())
}
// ClipRect ($A87B)
// Changes the clipping region of the current grafPort to a rectangle equivalent to the given rect.
// PROCEDURE ClipRect (r: Rect);
// Inside Macintosh Volume I, I-167
(true, 0x07B) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let port_ptr = if *self.current_port != 0 {
*self.current_port
} else {
let a5 = cpu.read_reg(Register::A5);
let global_ptr = if a5 != 0 { bus.read_long(a5) } else { 0 };
if global_ptr != 0 {
bus.read_long(global_ptr)
} else {
bus.read_long(crate::memory::globals::addr::THE_PORT)
}
};
let clip_rgn_handle = if port_ptr != 0 {
bus.read_long(port_ptr + 28)
} else {
0
};
if clip_rgn_handle != 0 {
let clip_rgn_ptr = bus.read_long(clip_rgn_handle);
if clip_rgn_ptr != 0 {
bus.write_word(clip_rgn_ptr, 10);
for i in 0..8u32 {
bus.write_byte(clip_rgn_ptr + 2 + i, bus.read_byte(rect_ptr + i));
}
if trace_dialog_ports_enabled() {
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
eprintln!(
"[DIALOG-PORT] ClipRect port=${:08X} rect=({},{},{},{})",
port_ptr, top, left, bottom, right
);
}
}
}
Ok(())
}
// ClosePort / CloseCPort ($A87D); CloseCPort ($AA02)
//
// Per IM:I I-163: "ClosePort releases the memory occupied
// by the given grafPort's visRgn and clipRgn. When you're
// completely through with a grafPort, call this procedure
// and then dispose of the grafPort with the Memory Manager
// procedure DisposPtr ... If ClosePort isn't called
// before a grafPort is disposed of, the memory used by
// the visRgn and clipRgn will be unrecoverable."
//
// Per IM:V V-72: "CloseCPort releases the memory allocated
// to the cGrafPort. It disposes of the visRgn, the
// clipRgn, the bkPixPat, the pnPixPat, the fillPixPat,
// and the grafVars handle. It also disposes of the
// portPixMap, but doesn't dispose of the portPixMap's
// color table (which is really owned by the gDevice).
// If you have placed your own color table into the
// portPixMap, either dispose of it BEFORE calling
// CloseCPort, or store another reference to it for other
// uses."
//
// PROCEDURE ClosePort (port: GrafPtr);
// PROCEDURE CloseCPort (port: CGrafPtr);
// Inside Macintosh Volume I, I-163 (ClosePort)
// Inside Macintosh Volume V, V-72 (CloseCPort)
// Inside Macintosh Volume III line 9399: "ClosePort | A87D"
// Inside Macintosh Volume V V-291 line 20688: "CloseCPort | A87D"
// Universal Interfaces 3.4 Quickdraw.h assigns CloseCPort to
// $AA02. Both forms use this polymorphic implementation; the
// dispatcher inspects the portVersion high bits to distinguish a
// CGrafPort from a GrafPort. The selected 68040 profile gives the
// two slots one default address, while the 604 profile retains
// distinct callable entries.
// Imaging With QuickDraw 1994, 4-66
//
// Stack: SP+0 port GrafPtr/CGrafPtr (4 bytes). Pop 4.
// No result (PROCEDURE).
//
// Systemless follows the IM:I ClosePort + IM:V CloseCPort contracts:
// - always frees visRgn + clipRgn handles
// - for CGrafPorts, also frees bkPixPat/pnPixPat/fillPixPat,
// grafVars, and portPixMap
// - leaves the portPixMap color table allocated (owned by GDevice)
//
// Regression coverage:
// quickdraw::tests::closeport_releases_visrgn_and_cliprgn_and_nils_port_slots
// quickdraw::tests::closeport_consumes_port_argument_and_pops_four_bytes
// quickdraw::tests::closecport_releases_documented_cgrafport_subhandles_and_preserves_portpixmap_colortable
(true, 0x07D) | (true, 0x202) => {
let sp = cpu.read_reg(Register::A7);
let port_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if port_ptr != 0 {
// Release visRgn (offset 24) and clipRgn (offset 28)
for rgn_offset in [24u32, 28u32] {
let rgn_handle = bus.read_long(port_ptr + rgn_offset);
if rgn_handle != 0 {
Self::free_handle_and_target(bus, rgn_handle);
// Nil out the handle in the port to prevent stale access
bus.write_long(port_ptr + rgn_offset, 0);
}
}
// Imaging With QuickDraw 1994 (p. 4-125): CGrafPorts have
// portVersion high bits set to $C000.
if (bus.read_word(port_ptr + 6) & 0xC000) == 0xC000 {
// Dispose documented CGrafPort-owned PixPat handles.
// IM:V V-72: CloseCPort disposes bkPixPat, pnPixPat,
// fillPixPat.
for pixpat_offset in [32u32, 58u32, 62u32] {
let pixpat_handle = bus.read_long(port_ptr + pixpat_offset);
if pixpat_handle != 0 {
self.owned_bit_pixpats.remove(&pixpat_handle);
let pixpat_ptr = bus.read_long(pixpat_handle);
if pixpat_ptr != 0 {
// Free patData (+6) and patXData (+10)
// handles and payloads.
for data_offset in [6u32, 10u32] {
let data_handle = bus.read_long(pixpat_ptr + data_offset);
if data_handle != 0 {
let data_ptr = bus.read_long(data_handle);
if data_ptr != 0 {
bus.free(data_ptr);
}
bus.free(data_handle);
}
}
// Free patMap (+2) including its pmTable.
let pat_map_handle = bus.read_long(pixpat_ptr + 2);
if pat_map_handle != 0 {
let pat_map_ptr = bus.read_long(pat_map_handle);
if pat_map_ptr != 0 {
let ctab_handle = bus.read_long(pat_map_ptr + 42);
if ctab_handle != 0 {
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr != 0 {
bus.free(ctab_ptr);
}
bus.free(ctab_handle);
}
bus.free(pat_map_ptr);
}
bus.free(pat_map_handle);
}
bus.free(pixpat_ptr);
}
bus.free(pixpat_handle);
bus.write_long(port_ptr + pixpat_offset, 0);
}
}
// Free grafVars handle (+8).
let graf_vars_handle = bus.read_long(port_ptr + 8);
if graf_vars_handle != 0 {
let graf_vars_ptr = bus.read_long(graf_vars_handle);
if graf_vars_ptr != 0 {
bus.free(graf_vars_ptr);
}
bus.free(graf_vars_handle);
bus.write_long(port_ptr + 8, 0);
}
// IM:V V-72: CloseCPort disposes the portPixMap handle
// but does NOT dispose its color table.
let port_pixmap_handle = bus.read_long(port_ptr + 2);
if port_pixmap_handle != 0 {
let port_pixmap_ptr = bus.read_long(port_pixmap_handle);
if port_pixmap_ptr != 0 {
// Clear the embedded CLUT link before freeing the
// PixMap record so the record itself never dangles
// into the remaining GDevice-owned table.
bus.write_long(port_pixmap_ptr + 42, 0);
bus.free(port_pixmap_ptr);
}
bus.free(port_pixmap_handle);
}
}
}
// No-op for plain GrafPorts (HashMap::remove returns
// None silently); cleans up CGrafPort tracking.
self.cport_ports.remove(&port_ptr);
self.cport_original_pixmaps.remove(&port_ptr);
self.resolved_port_color_fields.remove(&port_ptr);
self.quickdraw_op_colors
.remove_quickdraw_op_color(port_ptr);
self.quickdraw_hilite_colors
.remove_quickdraw_hilite_color(port_ptr);
Ok(())
}
// ========== Coordinate Transforms ==========
// LocalToGlobal ($A870)
// Converts a point from the current grafPort's local coordinate
// system to global (screen) coordinates.
// PROCEDURE LocalToGlobal(VAR pt: Point);
// Inside Macintosh Volume I, I-192
// Reference: Executor src/quickdraw/qPoint.cpp C_LocalToGlobal
// LocalToGlobal ($A870): subtracts portBits.bounds.topLeft per
// IM:I I-192; handles both GrafPort and CGrafPort.
(true, 0x070) => {
let sp = cpu.read_reg(Register::A7);
let pt_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let (bounds_top, bounds_left) = self.port_bounds_top_left(bus, port);
let v = bus.read_word(pt_ptr) as i16;
let h = bus.read_word(pt_ptr + 2) as i16;
// wrapping_sub matches 68k QuickDraw's signed 16-bit
// wrap-around behaviour.
bus.write_word(pt_ptr, v.wrapping_sub(bounds_top) as u16);
bus.write_word(pt_ptr + 2, h.wrapping_sub(bounds_left) as u16);
Ok(())
}
// GlobalToLocal ($A871)
// Converts a point from global (screen) coordinates to the current
// grafPort's local coordinate system.
// PROCEDURE GlobalToLocal(VAR pt: Point);
// Inside Macintosh Volume I, I-193
// GlobalToLocal ($A871): adds portBits.bounds.topLeft per IM:I
// I-193; handles both GrafPort and CGrafPort.
(true, 0x071) => {
let sp = cpu.read_reg(Register::A7);
let pt_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let (bounds_top, bounds_left) = self.port_bounds_top_left(bus, port);
let v = bus.read_word(pt_ptr) as i16;
let h = bus.read_word(pt_ptr + 2) as i16;
// wrapping_add matches 68k QuickDraw's signed 16-bit
// wrap-around behaviour.
let new_v = v.wrapping_add(bounds_top);
let new_h = h.wrapping_add(bounds_left);
bus.write_word(pt_ptr, new_v as u16);
bus.write_word(pt_ptr + 2, new_h as u16);
if std::env::var_os("SYSTEMLESS_TRACE_GLOBAL_TO_LOCAL").is_some() {
let trap_pc = cpu.read_reg(Register::PC).wrapping_sub(2);
eprintln!(
"[GTOL] pc=${:08X} port=${:08X} bounds_tl=({},{}) global=({},{}) -> local=({},{})",
trap_pc, port, bounds_top, bounds_left, v, h, new_v, new_h
);
}
Ok(())
}
// GrafDevice ($A872)
// Sets the device field of the current GrafPort.
// PROCEDURE GrafDevice(device: INTEGER);
// Inside Macintosh Volume I, I-165
//
// GrafDevice ($A872): Sets device field in port per IM:I I-165
(true, 0x072) => {
let sp = cpu.read_reg(Register::A7);
let device = bus.read_word(sp);
cpu.write_reg(Register::A7, sp + 2);
if *self.current_port != 0 {
bus.write_word(*self.current_port, device);
}
Ok(())
}
// ========== Point Operations ==========
// AddPt ($A87E)
// Adds the coordinates of srcPt to dstPt, returning the result in dstPt.
// PROCEDURE AddPt (srcPt: Point; VAR dstPt: Point);
// Inside Macintosh Volume I, I-193
(true, 0x07E) => {
let sp = cpu.read_reg(Register::A7);
let dst_ptr = bus.read_long(sp);
let src_v = bus.read_word(sp + 4) as i16;
let src_h = bus.read_word(sp + 6) as i16;
cpu.write_reg(Register::A7, sp + 8);
let dst_v = bus.read_word(dst_ptr) as i16;
let dst_h = bus.read_word(dst_ptr + 2) as i16;
bus.write_word(dst_ptr, (dst_v + src_v) as u16);
bus.write_word(dst_ptr + 2, (dst_h + src_h) as u16);
Ok(())
}
// SubPt ($A87F)
// Subtracts the coordinates of srcPt from dstPt, returning the result in dstPt.
// PROCEDURE SubPt (srcPt: Point; VAR dstPt: Point);
// Inside Macintosh Volume I, I-193
(true, 0x07F) => {
let sp = cpu.read_reg(Register::A7);
let dst_ptr = bus.read_long(sp);
let src_v = bus.read_word(sp + 4) as i16;
let src_h = bus.read_word(sp + 6) as i16;
cpu.write_reg(Register::A7, sp + 8);
let dst_v = bus.read_word(dst_ptr) as i16;
let dst_h = bus.read_word(dst_ptr + 2) as i16;
bus.write_word(dst_ptr, (dst_v - src_v) as u16);
bus.write_word(dst_ptr + 2, (dst_h - src_h) as u16);
Ok(())
}
// SetPt ($A880)
// Assigns the two given coordinates to the point pt.
// PROCEDURE SetPt (VAR pt: Point; h,v: INTEGER);
// Inside Macintosh Volume I, I-193
(true, 0x080) => {
let sp = cpu.read_reg(Register::A7);
let v = bus.read_word(sp) as i16;
let h = bus.read_word(sp + 2) as i16;
let pt_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
bus.write_word(pt_ptr, v as u16);
bus.write_word(pt_ptr + 2, h as u16);
Ok(())
}
// ========== Pen State ==========
// PenSize ($A89B)
// Sets the width and height of the pen.
// PROCEDURE PenSize(width, height: INTEGER);
// Inside Macintosh Volume I, I-170
// PenSize ($A89B): Sets pen size (v, h)
(true, 0x09B) => {
let sp = cpu.read_reg(Register::A7);
let height = bus.read_word(sp) as i16;
let width = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
self.pn_size = (height, width);
self.sync_current_port_draw_state(bus);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
Self::push_pict_word(commands, 0x0007); // PnSize
Self::push_pict_word(commands, height as u16);
Self::push_pict_word(commands, width as u16);
}
Ok(())
}
// PenMode ($A89C)
// Sets the transfer mode of the pen for line drawing.
// PROCEDURE PenMode(mode: INTEGER);
// Inside Macintosh Volume I, I-170
// PenMode ($A89C): Sets pen transfer mode
(true, 0x09C) => {
let sp = cpu.read_reg(Register::A7);
let mode = bus.read_word(sp) as i16;
cpu.write_reg(Register::A7, sp + 2);
self.pn_mode = mode;
self.sync_current_port_draw_state(bus);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
Self::push_pict_word(commands, 0x0008); // PnMode
Self::push_pict_word(commands, mode as u16);
}
Ok(())
}
// PenPat ($A89D)
// Sets the pen pattern for subsequent drawing.
// PROCEDURE PenPat(pat: Pattern);
// Inside Macintosh Volume I, I-170
// PenPat ($A89D): Sets pen pattern (8 bytes)
(true, 0x09D) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
for i in 0..8 {
self.pn_pat[i] = bus.read_byte(pat_ptr + i as u32);
}
self.sync_current_port_draw_state(bus);
self.install_port_bit_pixpat(bus, 58, self.pn_pat);
Ok(())
}
// PenNormal ($A89E)
// Resets the pen characteristics to their standard values.
// PROCEDURE PenNormal;
// Inside Macintosh Volume I, I-170
// PenNormal ($A89E): Resets pen to default (1×1, patCopy, black)
(true, 0x09E) => {
self.pn_size = (1, 1);
self.pn_mode = 8;
self.pn_pat = [0xFF; 8];
self.sync_current_port_draw_state(bus);
self.install_port_bit_pixpat(bus, 58, self.pn_pat);
Ok(())
}
// GetPen ($A89A)
// Returns the current pen location in the local coordinates
// of the current grafPort.
// PROCEDURE GetPen(VAR pt: Point);
// Inside Macintosh Volume I, I-169
//
// Regression coverage:
// src/trap/quickdraw.rs::tests::getpen_writes_current_pnloc_to_output_point_and_pops_arg
// src/trap/quickdraw.rs::tests::getpen_reports_local_coordinates_of_current_port
// GetPen ($A89A): Returns pen location as Point per IM:I I-169
(true, 0x09A) => {
let sp = cpu.read_reg(Register::A7);
let pt_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
bus.write_word(pt_ptr, self.pn_loc.0 as u16); // v
bus.write_word(pt_ptr + 2, self.pn_loc.1 as u16); // h
Ok(())
}
// GetPenState ($A898)
// Returns the current pen state in the specified record.
// PROCEDURE GetPenState(VAR pnState: PenState);
// Inside Macintosh Volume I, I-170
(true, 0x098) => {
let sp = cpu.read_reg(Register::A7);
let state_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
bus.write_word(state_ptr, self.pn_loc.0 as u16);
bus.write_word(state_ptr + 2, self.pn_loc.1 as u16);
bus.write_word(state_ptr + 4, self.pn_size.0 as u16);
bus.write_word(state_ptr + 6, self.pn_size.1 as u16);
bus.write_word(state_ptr + 8, self.pn_mode as u16);
for i in 0..8 {
bus.write_byte(state_ptr + 10 + i as u32, self.pn_pat[i]);
}
Ok(())
}
// BackPat ($A87C)
// Sets the background pattern of the current GrafPort.
// PROCEDURE BackPat(pat: Pattern);
// Inside Macintosh Volume I, I-167
// BackPat ($A87C): Sets background pattern
(true, 0x07C) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
for i in 0..8 {
self.bk_pat[i] = bus.read_byte(pat_ptr + i as u32);
}
self.sync_current_port_draw_state(bus);
self.install_port_bit_pixpat(bus, 32, self.bk_pat);
Ok(())
}
// ========== Pen Movement ==========
// MoveTo ($A893)
// MoveTo ($A893): Sets pen location
(true, 0x093) => {
let sp = cpu.read_reg(Register::A7);
let v = bus.read_word(sp) as i16;
let h = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
self.pn_loc = (v, h);
self.sync_current_port_draw_state(bus);
if trace_dialog_text_enabled() {
eprintln!(
"[DIALOG-TEXT] MoveTo current_port=${:08X} pnLoc=({}, {})",
*self.current_port, v, h
);
}
Ok(())
}
// Move ($A894)
// Move ($A894): Moves pen by delta
(true, 0x094) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
let (v0, h0) = self.pn_loc;
self.pn_loc = (v0.saturating_add(dv), h0.saturating_add(dh));
self.sync_current_port_draw_state(bus);
Ok(())
}
// StdLine ($A890) and LineTo ($A891) share direct rasterization,
// recording, and pen advancement; neither re-enters lineProc.
(true, 0x090 | 0x091) => {
let sp = cpu.read_reg(Register::A7);
let v = bus.read_word(sp) as i16;
let h = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
let (v0, h0) = self.pn_loc;
if self.recording_polygon.is_some() {
// During polygon recording, capture vertices but don't draw.
// Inside Macintosh Volume I, I-189
if let Some(ref mut rec) = self.recording_polygon {
if rec.vertices.is_empty() {
rec.vertices.push((v0, h0));
}
rec.vertices.push((v, h));
}
} else {
self.record_region_line(v0, h0, v, h);
if let Err(e) = self.draw_line(cpu, bus, h0, v0, h, v) {
return Some(Err(e));
}
}
self.pn_loc = (v, h);
self.sync_current_port_draw_state(bus);
Ok(())
}
// Line ($A892)
// Line ($A892): Draws line by delta
(true, 0x092) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
let (v0, h0) = self.pn_loc;
let h1 = h0.saturating_add(dh);
let v1 = v0.saturating_add(dv);
if self.recording_polygon.is_some() {
if let Some(ref mut rec) = self.recording_polygon {
if rec.vertices.is_empty() {
rec.vertices.push((v0, h0));
}
rec.vertices.push((v1, h1));
}
} else {
self.record_region_line(v0, h0, v1, h1);
if let Err(e) = self.draw_line(cpu, bus, h0, v0, h1, v1) {
return Some(Err(e));
}
}
self.pn_loc = (v1, h1);
// Mirror the new pen location into the current port's pnLoc
// field (port+48/50) so guest code that reads pnLoc after
// Line sees the post-Line position. IM:I I-169.
self.sync_current_port_draw_state(bus);
Ok(())
}
// ========== Region Operations ==========
// NewRgn ($A8D8)
// Allocates space for a new region, initializes it to the empty
// region (0,0,0,0), and returns a handle to it.
// FUNCTION NewRgn: RgnHandle;
// Inside Macintosh Volume I, I-181
// NewRgn ($A8D8): Allocates 10-byte empty region + handle
(true, 0x0D8) => {
let sp = cpu.read_reg(Register::A7);
let ptr = bus.alloc(10);
bus.write_word(ptr, 10);
let handle = bus.alloc(4);
bus.write_long(handle, ptr);
// Write result into the caller's pre-allocated slot at SP
bus.write_long(sp, handle);
// SP unchanged — no parameters to pop
Ok(())
}
// RectRgn ($A8DF)
// Destroys the previous region structure and replaces it with the
// supplied rectangle.
// PROCEDURE RectRgn(rgn: RgnHandle; r: Rect);
// Imaging With QuickDraw (1994), p. 3-92
(true, 0x0DF) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
let rgn_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let rgn_ptr = bus.read_long(rgn_handle);
for i in 0..8 {
bus.write_byte(rgn_ptr + 2 + i, bus.read_byte(rect_ptr + i));
}
bus.write_word(rgn_ptr, 10);
Ok(())
}
// DisposeRgn ($A8D9)
// PROCEDURE DisposeRgn(rgn: RgnHandle);
// DisposeRgn ($A8D9): Frees region data + handle via bus.free()
(true, 0x0D9) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
if rgn_handle != 0 {
let rgn_ptr = bus.read_long(rgn_handle);
bus.free(rgn_ptr);
bus.free(rgn_handle);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// CopyRgn ($A8DC)
// PROCEDURE CopyRgn(srcRgn, dstRgn: RgnHandle);
// CopyRgn ($A8DC): Copies the full region structure by value
(true, 0x0DC) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if src_handle != 0 && dst_handle != 0 {
let src_ptr = bus.read_long(src_handle);
if src_ptr != 0 {
let size = bus.read_word(src_ptr) as u32;
let Some(dst_ptr) = Self::ensure_region_capacity(bus, dst_handle, size)
else {
return Some(Ok(()));
};
for i in 0..size {
bus.write_byte(dst_ptr + i, bus.read_byte(src_ptr + i));
}
}
}
Ok(())
}
// ========== Text Attributes ==========
// TextFont ($A887)
// Sets the font number for text drawing in the current GrafPort.
// PROCEDURE TextFont(font: INTEGER);
// Inside Macintosh Volume I, I-171
// TextFont ($A887): Sets font ID
(true, 0x087) => {
let sp = cpu.read_reg(Register::A7);
self.tx_font = bus.read_word(sp) as i16;
cpu.write_reg(Register::A7, sp + 2);
self.sync_current_port_draw_state(bus);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_word(commands, 0x0003); // TxFont
pict::recording_push_word(commands, self.tx_font as u16);
}
Ok(())
}
// TextFace ($A888)
// Sets the character style for text drawing in the current GrafPort.
// PROCEDURE TextFace(face: Style);
// Inside Macintosh Volume I, I-171
// TextFace ($A888): Sets style (bold, italic, etc.)
(true, 0x088) => {
let sp = cpu.read_reg(Register::A7);
self.tx_face = decode_text_face_style(bus.read_word(sp));
cpu.write_reg(Register::A7, sp + 2);
self.sync_current_port_draw_state(bus);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_word(commands, 0x0004); // TxFace
commands.extend_from_slice(&[self.tx_face as u8, 0]);
}
Ok(())
}
// TextMode ($A889)
// Sets the transfer mode for text drawing in the current GrafPort.
// PROCEDURE TextMode(mode: INTEGER);
// Inside Macintosh Volume I, I-171
// TextMode ($A889): Sets transfer mode
(true, 0x089) => {
let sp = cpu.read_reg(Register::A7);
self.tx_mode = bus.read_word(sp) as i16;
cpu.write_reg(Register::A7, sp + 2);
self.sync_current_port_draw_state(bus);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_word(commands, 0x0005); // TxMode
pict::recording_push_word(commands, self.tx_mode as u16);
}
Ok(())
}
// TextSize ($A88A)
// Sets the type size for text drawing in the current GrafPort.
// PROCEDURE TextSize(size: INTEGER);
// Inside Macintosh Volume I, I-171
// TextSize ($A88A): Sets point size
(true, 0x08A) => {
let sp = cpu.read_reg(Register::A7);
self.tx_size = bus.read_word(sp) as i16;
cpu.write_reg(Register::A7, sp + 2);
self.sync_current_port_draw_state(bus);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_word(commands, 0x000D); // TxSize
pict::recording_push_word(commands, self.tx_size as u16);
}
Ok(())
}
// InitFonts ($A8FE)
// Per IM:I I-219: "InitFonts initializes the Font
// Manager. If the system font isn't already in memory,
// InitFonts reads it into memory. Call this procedure
// once before all other Font Manager routines or any
// Toolbox routine that will call the Font Manager."
// PROCEDURE InitFonts;
// Inside Macintosh Volume I, I-219
//
// No args, no result. Pop 0 bytes.
//
// HLE compromise: Systemless doesn't load FOND/FONT/NFNT
// resources — text drawing goes through fixed Rust
// glyph tables in trap/font_table.rs (Chicago / Geneva
// / Monaco / system-font 9pt-12pt-9pt set baked at
// build time). The "if system font isn't already in
// memory, read it in" path is unreachable because the
// font table is statically compiled. No-op is correct.
// The Font Manager trio $A901 FMSwapFont / $A902
// RealFont / $A903 SetFontLock (all Partial) carries the same HLE
// rationale — see toolbox.rs:2922+ family rationale
// block for the cross-trap design coherence.
// InitFonts ($A8FE): No args / no result per IM:I I-219 PROCEDURE sig; Font Mgr state is statically baked into trap/font_table.rs Rust glyph tables — no FOND/FONT/NFNT resource loading needed at runtime. Same HLE rationale as the $A901/$A902/$A903 Font Manager trio (see toolbox.rs:2922+ family block). Idempotent — repeated calls are no-ops.
(true, 0x0FE) => Ok(()),
// GetFontInfo ($A88B)
// Returns font information for the current GrafPort's font settings.
// PROCEDURE GetFontInfo(VAR info: FontInfo);
// Inside Macintosh Volume I, I-173
// GetFontInfo ($A88B): Returns ascent, descent, widMax, leading based on tx_size
(true, 0x08B) => {
let sp = cpu.read_reg(Register::A7);
let info_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let (face, scale) = get_font_face_scaled(self.tx_font, self.tx_size);
let metrics = face.metrics;
bus.write_word(info_ptr, (metrics.ascent * scale) as u16);
bus.write_word(info_ptr + 2, (metrics.descent * scale) as u16);
bus.write_word(info_ptr + 4, (metrics.wid_max * scale) as u16);
bus.write_word(info_ptr + 6, (metrics.leading * scale) as u16);
Ok(())
}
// StringWidth ($A88C)
// Returns the width of the given string in pixels.
// FUNCTION StringWidth(s: Str255): INTEGER;
// Inside Macintosh Volume I, I-173
// StringWidth ($A88C): Returns pixel width of Pascal string
(true, 0x08C) => {
let sp = cpu.read_reg(Register::A7);
let str_ptr = bus.read_long(sp);
let mut total_base = 0i32;
let len = bus.read_byte(str_ptr) as u16;
let start_addr = str_ptr + 1;
for i in 0..len {
let ch = bus.read_byte(start_addr + i as u32) as char;
let advance = if let Some((g, _)) = get_glyph(self.tx_font, self.tx_size, ch) {
i32::from(self.glyph_advance(g))
} else {
i32::from(self.missing_glyph_advance())
};
total_base += advance;
}
let total_width = self.proportional_text_width(total_base);
let new_sp = sp + 4;
bus.write_word(new_sp, total_width as u16);
cpu.write_reg(Register::A7, new_sp);
Ok(())
}
// CharWidth ($A88D)
// Returns the width of the given character in pixels.
// FUNCTION CharWidth(ch: CHAR): INTEGER;
// Inside Macintosh Volume I, I-173
// CharWidth ($A88D): Returns pixel width of character
(true, 0x08D) => {
let sp = cpu.read_reg(Register::A7);
let ch = (bus.read_word(sp) & 0xFF) as u8 as char;
let advance = if let Some((g, _)) = get_glyph(self.tx_font, self.tx_size, ch) {
i32::from(self.glyph_advance(g))
} else {
i32::from(self.missing_glyph_advance())
};
let advance = self.proportional_text_width(advance);
bus.write_word(sp + 2, advance as u16);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// TextWidth ($A886)
// Returns the width of the specified text in pixels.
// FUNCTION TextWidth(textBuf: Ptr; firstByte, byteCount: INTEGER): INTEGER;
// Inside Macintosh Volume I, I-173
// TextWidth ($A886): Returns width of text buffer
(true, 0x086) => {
let sp = cpu.read_reg(Register::A7);
let byte_count = bus.read_word(sp) as i16;
let first_byte = bus.read_word(sp + 2) as i16;
let text_buf = bus.read_long(sp + 4);
let mut total_base = 0i32;
let start_addr = text_buf + first_byte as u32;
for i in 0..byte_count {
let ch = bus.read_byte(start_addr + i as u32) as char;
let advance = if let Some((g, _)) = get_glyph(self.tx_font, self.tx_size, ch) {
i32::from(self.glyph_advance(g))
} else {
i32::from(self.missing_glyph_advance())
};
total_base += advance;
}
let total_width = self.proportional_text_width(total_base);
let new_sp = sp + 8;
bus.write_word(new_sp, total_width as u16);
cpu.write_reg(Register::A7, new_sp);
Ok(())
}
// ========== Text Drawing ==========
// DrawChar ($A883)
// Draws the specified character at the current pen location.
// PROCEDURE DrawChar(ch: CHAR);
// Inside Macintosh Volume I, I-172
// DrawChar ($A883): Renders character to framebuffer using built-in font
(true, 0x083) => {
let sp = cpu.read_reg(Register::A7);
let ch = bus.read_word(sp) as u8 as char;
cpu.write_reg(Register::A7, sp + 2);
if trace_dialog_text_enabled() {
eprintln!(
"[DIALOG-TEXT] DrawChar current_port=${:08X} pnLoc=({}, {}) fg=({:04X},{:04X},{:04X}) bg=({:04X},{:04X},{:04X}) mode={} ch={:?}",
*self.current_port,
self.pn_loc.0,
self.pn_loc.1,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.tx_mode,
ch,
);
}
self.draw_char(cpu, bus, ch);
self.refresh_visible_dialog_snapshot_for_port(bus, *self.current_port);
Ok(())
}
// DrawString ($A884)
// Draws the specified string at the current pen location.
// PROCEDURE DrawString(s: Str255);
// Inside Macintosh Volume I, I-172
// DrawString ($A884): Renders Pascal string to framebuffer
(true, 0x084) => {
let sp = cpu.read_reg(Register::A7);
let str_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if trace_dialog_text_enabled() {
let pc = cpu.read_reg(Register::PC);
let len = bus.read_byte(str_ptr) as usize;
let mut bytes = vec![0u8; len];
for (i, byte) in bytes.iter_mut().enumerate() {
*byte = bus.read_byte(str_ptr + 1 + i as u32);
}
eprintln!(
"[DIALOG-TEXT] DrawString pc=${:08X} current_port=${:08X} pnLoc=({}, {}) fg=({:04X},{:04X},{:04X}) bg=({:04X},{:04X},{:04X}) mode={} text=\"{}\"",
pc,
*self.current_port,
self.pn_loc.0,
self.pn_loc.1,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.tx_mode,
String::from_utf8_lossy(&bytes),
);
}
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
let len = usize::from(bus.read_byte(str_ptr));
let text = bus.read_bytes(str_ptr + 1, len);
pict::recording_push_long_text(commands, self.pn_loc.0, self.pn_loc.1, &text);
let mut advance = 0i32;
for &byte in &text {
advance += if let Some((glyph, _)) =
get_glyph(self.tx_font, self.tx_size, byte as char)
{
i32::from(self.glyph_advance(glyph))
} else {
i32::from(self.missing_glyph_advance())
};
}
self.pn_loc.1 = self
.pn_loc
.1
.saturating_add(self.proportional_text_width(advance));
self.sync_current_port_draw_state(bus);
return Some(Ok(()));
}
self.draw_string(cpu, bus, str_ptr);
self.refresh_visible_dialog_snapshot_for_port(bus, *self.current_port);
Ok(())
}
// DrawText ($A885)
// Draws text from an arbitrary buffer starting at firstByte for byteCount bytes.
// PROCEDURE DrawText(textBuf: Ptr; firstByte: INTEGER; byteCount: INTEGER);
// Inside Macintosh Volume I, I-172
// DrawText ($A885): Renders text buffer to framebuffer
(true, 0x085) => {
let sp = cpu.read_reg(Register::A7);
let byte_count = bus.read_word(sp) as i16;
let first_byte = bus.read_word(sp + 2) as i16;
let text_buf = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let start = text_buf + first_byte as u32;
if trace_dialog_text_enabled() {
let pc = cpu.read_reg(Register::PC);
let safe_count = byte_count.max(0) as usize;
let mut bytes = vec![0u8; safe_count];
for (i, byte) in bytes.iter_mut().enumerate() {
*byte = bus.read_byte(start + i as u32);
}
eprintln!(
"[DIALOG-TEXT] DrawText pc=${:08X} current_port=${:08X} pnLoc=({}, {}) fg=({:04X},{:04X},{:04X}) bg=({:04X},{:04X},{:04X}) mode={} text=\"{}\"",
pc,
*self.current_port,
self.pn_loc.0,
self.pn_loc.1,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.tx_mode,
String::from_utf8_lossy(&bytes),
);
}
bus.begin_presentation_text_run(self.tx_mode == 0);
for i in 0..byte_count {
let ch = bus.read_byte(start + i as u32) as char;
self.draw_char(cpu, bus, ch);
}
bus.end_presentation_text_run();
self.refresh_visible_dialog_snapshot_for_port(bus, *self.current_port);
Ok(())
}
// StdText ($A882)
// Low-level text rendering bottleneck.
// PROCEDURE StdText(byteCount: INTEGER; textBuf: Ptr; numer, denom: Point);
// Inside Macintosh Volume I, I-198
// StdText ($A882): Parses all 5 parameters, applies uniform scaling
// to the rendered text path, and processes text for rendering.
(true, 0x082) => {
let sp = cpu.read_reg(Register::A7);
// Pascal calling convention: rightmost param at lowest address
let _denom_v = bus.read_word(sp) as i16;
let _denom_h = bus.read_word(sp + 2) as i16;
let _numer_v = bus.read_word(sp + 4) as i16;
let _numer_h = bus.read_word(sp + 6) as i16;
let text_buf = bus.read_long(sp + 8);
let byte_count = bus.read_word(sp + 12) as i16;
cpu.write_reg(Register::A7, sp + 14);
let saved_tx_size = self.tx_size;
if _numer_h > 0 && _denom_h > 0 {
let scale_num = i32::from(_numer_h);
let scale_den = i32::from(_denom_h);
let scaled =
((i32::from(self.tx_size) * scale_num) + (scale_den / 2)) / scale_den;
self.tx_size = scaled.clamp(1, i32::from(i16::MAX)) as i16;
}
if trace_dialog_text_enabled() {
let pc = cpu.read_reg(Register::PC);
let safe_count = byte_count.max(0) as usize;
let mut bytes = vec![0u8; safe_count];
for (i, byte) in bytes.iter_mut().enumerate() {
*byte = bus.read_byte(text_buf + i as u32);
}
eprintln!(
"[DIALOG-TEXT] StdText pc=${:08X} current_port=${:08X} pnLoc=({}, {}) fg=({:04X},{:04X},{:04X}) bg=({:04X},{:04X},{:04X}) mode={} numer=({}, {}) denom=({}, {}) text=\"{}\"",
pc,
*self.current_port,
self.pn_loc.0,
self.pn_loc.1,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.tx_mode,
_numer_v,
_numer_h,
_denom_v,
_denom_h,
String::from_utf8_lossy(&bytes),
);
}
// Render text using draw_char
bus.begin_presentation_text_run(self.tx_mode == 0);
for i in 0..byte_count {
let ch = bus.read_byte(text_buf + i as u32) as char;
self.draw_char(cpu, bus, ch);
}
bus.end_presentation_text_run();
self.tx_size = saved_tx_size;
self.refresh_visible_dialog_snapshot_for_port(bus, *self.current_port);
Ok(())
}
// SetStdProcs ($A8EA)
// PROCEDURE SetStdProcs(VAR procs: QDProcs);
// Inside Macintosh Volume I, I-197
// Imaging With QuickDraw 1994, 3-130
//
// Fills the 13-field QDProcs record with pointers to the standard
// low-level QuickDraw bottleneck routines. Each field receives the
// stable protected callable gateway for its standard Toolbox trap,
// so pointer comparison and direct JSR use the same identity.
(true, 0x0EA) => {
let sp = cpu.read_reg(Register::A7);
let procs_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
// Trap words for the 13 standard QuickDraw bottlenecks,
// in QDProcs field order (IM:I I-197 + Imaging With QD 1994
// 3-39 layout):
// textProc, lineProc, rectProc, rRectProc, ovalProc,
// arcProc, polyProc, rgnProc, bitsProc, commentProc,
// txMeasProc, getPicProc, putPicProc
const STD_PROC_TRAPS: [u16; 13] = [
0xA882, // StdText
0xA890, // StdLine
0xA8A0, // StdRect
0xA8AF, // StdRRect
0xA8B6, // StdOval
0xA8BD, // StdArc
0xA8C5, // StdPoly
0xA8D1, // StdRgn
0xA8EB, // StdBits
0xA8F1, // StdComment (was $A89F — that's _Unimplemented; fixed per IM:I I-198)
0xA8ED, // StdTxMeas
0xA8EE, // StdGetPic
0xA8F0, // StdPutPic
];
if procs_ptr != 0 {
for (i, trap) in STD_PROC_TRAPS.iter().enumerate() {
let gateway = self.get_or_create_tool_trap_trampoline(bus, *trap);
bus.write_long(procs_ptr + (i as u32) * 4, gateway);
}
}
Ok(())
}
// ========== Rect Operations ==========
// SetRect ($A8A7)
// PROCEDURE SetRect (VAR r: Rect; left, top, right, bottom: INTEGER);
// Inside Macintosh Volume I, I-175
//
// Pascal stack layout (12 bytes popped):
// sp+0 bottom (last pushed, INTEGER)
// sp+2 right (INTEGER)
// sp+4 top (INTEGER)
// sp+6 left (INTEGER)
// sp+8 r-pointer (first pushed, VAR-out 4-byte ptr)
//
// Writes the four INTEGER args verbatim into r's fields.
// Negatives are preserved via the i16→u16 sign-extending
// cast at write_word (no clamping; IM:I-175 is silent on
// the matter), and inverted inputs are written as-is with
// no normalisation.
(true, 0x0A7) => {
let sp = cpu.read_reg(Register::A7);
let bottom = bus.read_word(sp) as i16;
let right = bus.read_word(sp + 2) as i16;
let top = bus.read_word(sp + 4) as i16;
let left = bus.read_word(sp + 6) as i16;
let rect_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
bus.write_word(rect_ptr, top as u16);
bus.write_word(rect_ptr + 2, left as u16);
bus.write_word(rect_ptr + 4, bottom as u16);
bus.write_word(rect_ptr + 6, right as u16);
Ok(())
}
// InsetRect ($A8A9)
// PROCEDURE InsetRect (VAR r: Rect; dh, dv: INTEGER);
// Inside Macintosh Volume I, I-176
//
// Pops 8 bytes; writes (top+dv, left+dh, bottom-dv,
// right-dh) per IM:I-176 with no clamping. On the collapse
// case (e.g. 2*dh > width) IM:I-176 says the result is
// implementation-defined ("set to (0,0,0,0)"); BasiliskII
// instead produces an inverted rect (r.right < r.left) and
// Systemless mirrors BasiliskII by writing the unclamped
// formula verbatim.
(true, 0x0A9) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
bus.write_word(rect_ptr, top.wrapping_add(dv) as u16);
bus.write_word(rect_ptr + 2, left.wrapping_add(dh) as u16);
bus.write_word(rect_ptr + 4, bottom.wrapping_sub(dv) as u16);
bus.write_word(rect_ptr + 6, right.wrapping_sub(dh) as u16);
Ok(())
}
// OffsetRect ($A8A8)
// PROCEDURE OffsetRect (VAR r: Rect; dh, dv: INTEGER);
// Inside Macintosh Volume I, I-174
//
// Pops 8 bytes; mutates VAR-out r in place per IM:I-174
// (top+dv, left+dh, bottom+dv, right+dh). Coordinate
// INTEGER arithmetic wraps at 16 bits. Translation
// preserves width and height, and sequential calls
// compose their translations.
(true, 0x0A8) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
bus.write_word(rect_ptr, top.wrapping_add(dv) as u16);
bus.write_word(rect_ptr + 2, left.wrapping_add(dh) as u16);
bus.write_word(rect_ptr + 4, bottom.wrapping_add(dv) as u16);
bus.write_word(rect_ptr + 6, right.wrapping_add(dh) as u16);
Ok(())
}
// EmptyRect ($A8AE)
// FUNCTION EmptyRect (r: Rect) : BOOLEAN;
// Inside Macintosh Volume I, I-176
//
// Per IM:I-176: "EmptyRect returns TRUE if the given
// rectangle is an empty rectangle or FALSE if not. A
// rectangle is considered empty if the bottom
// coordinate is less than or equal to the top or the
// right coordinate is less than or equal to the left."
//
// The simplest possible Pascal FUNCTION shape in the
// Rect-Ops family — 1 by-value Rect input passed by
// 4-byte const-pointer per MPW pascal calling
// convention (since 8-byte structs exceed the
// direct-push threshold) -> 4 bytes of args popped ->
// result slot at sp+4. The Boolean uses Mac Pascal
// encoding (TRUE = $0100 at the high half of the
// 16-bit slot, FALSE = $0000).
//
// Note the inclusive-equal semantics — `bottom <= top`
// OR `right <= left`, NOT strict `<`. A Rect with
// bottom == top is empty even though every coordinate
// field is finite.
//
// Per IM:I-176's inclusive-`<=` semantics, a degenerate
// horizontal line (right==left), a degenerate vertical
// line (bottom==top), and a strictly inverted rect are all
// empty — distinguishing the correct `<=` OR-of-two-tests
// from a strict-`<` or AND-instead-of-OR misimplementation.
(true, 0x0AE) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
let is_empty = (bottom <= top) || (right <= left);
// Mac Pascal BOOLEAN: TRUE = $0100 (byte 1 in high byte of word)
bus.write_word(sp + 4, if is_empty { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// PtInRect ($A8AD)
// FUNCTION PtInRect(pt: Point; r: Rect): BOOLEAN;
// Inside Macintosh Volume I, I-175
// Imaging With QuickDraw 1994, p. 2-124
//
// Per IM:I-175: "PtInRect determines whether the
// pixel below and to the right of the given coordinate
// point is enclosed in the specified rectangle, and
// returns TRUE if so or FALSE if not."
//
// The QuickDraw "pixel below and to the right"
// semantics mean a Rect (left, top, right, bottom)
// names the half-open pixel range [left, right) x
// [top, bottom): PtInRect((r.left, r.top), r) is TRUE
// while PtInRect((r.right, r.bottom), r) is FALSE —
// the right and bottom edges are EXCLUSIVE.
//
// Pascal calling convention: by-value Point passed as
// 4-byte struct at sp+4 (.v at +0, .h at +2 per
// IM:I-141), by-value Rect passed by 4-byte pointer
// at sp+0 (8-byte Rect struct too large for direct
// push). FUNCTION result Boolean encoded at sp+8 above
// the popped 8 bytes of args, as Mac Pascal Boolean
// (TRUE = $0100, FALSE = $0000).
//
// The half-open semantics make each edge behave
// independently: left and top edges are inclusive, right
// and bottom edges are exclusive, and a degenerate rect
// (e.g. (20,20,20,20)) contains no points per the IM:I-176
// EmptyRect predicate.
(true, 0x0AD) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
let pt_v = bus.read_word(sp + 4) as i16;
let pt_h = bus.read_word(sp + 6) as i16;
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
let in_rect = pt_v >= top && pt_v < bottom && pt_h >= left && pt_h < right;
// Mac Pascal BOOLEAN: TRUE = $0100 (byte 1 in high byte of word)
bus.write_word(sp + 8, if in_rect { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// SectRect ($A8AA)
// FUNCTION SectRect (src1, src2: Rect; VAR dstRect: Rect): BOOLEAN;
// Inside Macintosh Volume I, I-175
//
// Per IM:I-175: "SectRect calculates the rectangle
// that's the intersection of the two given
// rectangles, and returns TRUE if they indeed
// intersect or FALSE if they don't." For non-empty
// overlapping operands the four dstRect fields are
// independently max/min-selected from the source
// Rects:
// dst.top = max(src1.top, src2.top)
// dst.left = max(src1.left, src2.left)
// dst.bottom = min(src1.bottom, src2.bottom)
// dst.right = min(src1.right, src2.right)
// and the FUNCTION result is TRUE iff the resulting
// Rect is non-empty (top < bottom AND left < right).
// Per IM:I-175 the empty-result case clamps dst to
// (0, 0, 0, 0) and returns FALSE.
//
// SectRect ($A8AA)
(true, 0x0AA) => {
let sp = cpu.read_reg(Register::A7);
let dst_ptr = bus.read_long(sp);
let src2_ptr = bus.read_long(sp + 4);
let src1_ptr = bus.read_long(sp + 8);
let s1_top = bus.read_word(src1_ptr) as i16;
let s1_left = bus.read_word(src1_ptr + 2) as i16;
let s1_bottom = bus.read_word(src1_ptr + 4) as i16;
let s1_right = bus.read_word(src1_ptr + 6) as i16;
let s2_top = bus.read_word(src2_ptr) as i16;
let s2_left = bus.read_word(src2_ptr + 2) as i16;
let s2_bottom = bus.read_word(src2_ptr + 4) as i16;
let s2_right = bus.read_word(src2_ptr + 6) as i16;
let d_top = s1_top.max(s2_top);
let d_left = s1_left.max(s2_left);
let d_bottom = s1_bottom.min(s2_bottom);
let d_right = s1_right.min(s2_right);
let intersects = d_top < d_bottom && d_left < d_right;
if intersects {
bus.write_word(dst_ptr, d_top as u16);
bus.write_word(dst_ptr + 2, d_left as u16);
bus.write_word(dst_ptr + 4, d_bottom as u16);
bus.write_word(dst_ptr + 6, d_right as u16);
} else {
bus.write_long(dst_ptr, 0);
bus.write_long(dst_ptr + 4, 0);
}
// Mac Pascal BOOLEAN: TRUE = $0100 (byte 1 in high byte of word)
bus.write_word(sp + 12, if intersects { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 12);
Ok(())
}
// UnionRect ($A8AB)
// PROCEDURE UnionRect (src1, src2: Rect; VAR dstRect: Rect);
// Inside Macintosh Volume I, I-175
//
// Per IM:I-175: "UnionRect calculates the smallest
// rectangle that encloses both of the given rectangles."
// For non-empty operands the four dstRect fields are
// independently min/max-selected from the corresponding
// corner of the two source Rects:
// dst.top = min(src1.top, src2.top)
// dst.left = min(src1.left, src2.left)
// dst.bottom = max(src1.bottom, src2.bottom)
// dst.right = max(src1.right, src2.right)
//
// Per IM:I-176, if EITHER source is empty (bottom <=
// top OR right <= left) the destination receives the
// OTHER (non-empty) rectangle; if BOTH are empty the
// destination is set to (0, 0, 0, 0).
//
// UnionRect ($A8AB)
(true, 0x0AB) => {
let sp = cpu.read_reg(Register::A7);
let dst_ptr = bus.read_long(sp);
let src2_ptr = bus.read_long(sp + 4);
let src1_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
let s1_top = bus.read_word(src1_ptr) as i16;
let s1_left = bus.read_word(src1_ptr + 2) as i16;
let s1_bottom = bus.read_word(src1_ptr + 4) as i16;
let s1_right = bus.read_word(src1_ptr + 6) as i16;
let s2_top = bus.read_word(src2_ptr) as i16;
let s2_left = bus.read_word(src2_ptr + 2) as i16;
let s2_bottom = bus.read_word(src2_ptr + 4) as i16;
let s2_right = bus.read_word(src2_ptr + 6) as i16;
let s1_empty = s1_bottom <= s1_top || s1_right <= s1_left;
let s2_empty = s2_bottom <= s2_top || s2_right <= s2_left;
let (d_top, d_left, d_bottom, d_right) = if s1_empty && s2_empty {
(0, 0, 0, 0)
} else if s1_empty {
(s2_top, s2_left, s2_bottom, s2_right)
} else if s2_empty {
(s1_top, s1_left, s1_bottom, s1_right)
} else {
(
s1_top.min(s2_top),
s1_left.min(s2_left),
s1_bottom.max(s2_bottom),
s1_right.max(s2_right),
)
};
bus.write_word(dst_ptr, d_top as u16);
bus.write_word(dst_ptr + 2, d_left as u16);
bus.write_word(dst_ptr + 4, d_bottom as u16);
bus.write_word(dst_ptr + 6, d_right as u16);
Ok(())
}
// EqualRect ($A8A6)
// FUNCTION EqualRect (rect1, rect2: Rect) : BOOLEAN;
// Inside Macintosh Volume I, I-176
//
// Per IM:I-176: "EqualRect compares the two given
// rectangles and returns TRUE if they're equal or
// FALSE if not. The two rectangles must have identical
// boundary coordinates to be considered equal."
//
// Pascal calling convention: both rect1 and rect2 are
// passed by 4-byte const-pointer (MPW pascal pragma
// marshals 8-byte structs as const-pointers since they
// exceed the direct-push threshold). Args layout: r2
// at sp+0, r1 at sp+4 (Pascal pushes left-to-right
// with the stack growing down, so r1 lands at the
// higher offset). Result: Mac Pascal Boolean at sp+8
// (TRUE = $0100 at the high half of the word,
// FALSE = $0000) with A7 advanced by 8 bytes of args.
//
// EqualRect compares the two Rects field-for-field
// literally per IM:I-176; there is no empty-rect
// normalisation, so two distinct empty rects compare
// unequal.
(true, 0x0A6) => {
let sp = cpu.read_reg(Register::A7);
let r2_ptr = bus.read_long(sp);
let r1_ptr = bus.read_long(sp + 4);
let eq = (0..8).all(|i| bus.read_byte(r1_ptr + i) == bus.read_byte(r2_ptr + i));
// Mac Pascal BOOLEAN: TRUE = $0100 (byte 1 in high byte of word)
bus.write_word(sp + 8, if eq { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// Pt2Rect ($A8AC)
// PROCEDURE Pt2Rect (pt1, pt2: Point; VAR dstRect: Rect);
// Inside Macintosh Volume I, I-175
//
// Per IM:I-175: "Pt2Rect returns the smallest rectangle
// that encloses the two given points." The four
// dstRect fields are independently min/max-selected
// from the two operands' v / h coordinates:
// dst.top = min(pt1.v, pt2.v)
// dst.left = min(pt1.h, pt2.h)
// dst.bottom = max(pt1.v, pt2.v)
// dst.right = max(pt1.h, pt2.h)
//
// Pt2Rect ($A8AC): min(v),min(h),max(v),max(h) per IM:I-175
(true, 0x0AC) => {
let sp = cpu.read_reg(Register::A7);
let dst_ptr = bus.read_long(sp);
let pt2_v = bus.read_word(sp + 4) as i16;
let pt2_h = bus.read_word(sp + 6) as i16;
let pt1_v = bus.read_word(sp + 8) as i16;
let pt1_h = bus.read_word(sp + 10) as i16;
cpu.write_reg(Register::A7, sp + 12);
bus.write_word(dst_ptr, pt1_v.min(pt2_v) as u16);
bus.write_word(dst_ptr + 2, pt1_h.min(pt2_h) as u16);
bus.write_word(dst_ptr + 4, pt1_v.max(pt2_v) as u16);
bus.write_word(dst_ptr + 6, pt1_h.max(pt2_h) as u16);
Ok(())
}
// ========== Appearance Manager ==========
(true, 0x274) if cpu.read_reg(Register::D0) as u16 == 0x15 => {
// RegisterAppearanceClient ($AA74, selector $0015)
// Registers the current application as an Appearance Manager client.
// OSStatus RegisterAppearanceClient(void);
// Apple, Appearance.h (Universal Interfaces 3.4), line 1506.
let sp = cpu.read_reg(Register::A7);
let status = if self.appearance_registered {
-30561i32 // themeProcessRegisteredErr, Apple MacErrors.h
} else {
self.appearance_registered = true;
0
};
bus.write_long(sp, status as u32);
Ok(())
}
(true, 0x274) if cpu.read_reg(Register::D0) as u16 == 0x16 => {
// UnregisterAppearanceClient ($AA74, selector $0016)
// Removes the current application's Appearance Manager registration.
// OSStatus UnregisterAppearanceClient(void);
// Apple, Appearance.h (Universal Interfaces 3.4), line 1518.
let sp = cpu.read_reg(Register::A7);
let status = if self.appearance_registered {
self.appearance_registered = false;
0
} else {
-30562i32 // themeProcessNotRegisteredErr, Apple MacErrors.h
};
bus.write_long(sp, status as u32);
Ok(())
}
(true, 0x274) if cpu.read_reg(Register::D0) as u16 == 4 => {
// SetThemeWindowBackground ($AA74, selector $0004)
// Sets the brush used by the Window Manager to erase a window's content.
// OSStatus SetThemeWindowBackground(WindowRef inWindow, ThemeBrush inBrush, Boolean inUpdate);
// Apple, Appearance.h (Universal Interfaces 3.4), line 1602.
let sp = cpu.read_reg(Register::A7);
let update = bus.read_word(sp) != 0;
let brush = bus.read_word(sp + 2) as i16;
let window = bus.read_long(sp + 4);
let status = if !self.window_list.contains(&window) {
-50i32 // paramErr
} else if !(-2..=53).contains(&brush) || brush == 0 {
-30560i32 // themeInvalidBrushErr, Apple MacErrors.h
} else {
self.window_theme_brushes.insert(window, brush);
if update {
let rect = self.window_port_rect(bus, window);
self.invalidate_window_rect(bus, window, rect);
}
0
};
bus.write_long(sp + 8, status as u32);
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
(true, 0x274) if cpu.read_reg(Register::D0) as u16 == 7 => {
// DrawThemePlacard ($AA74, selector $0007)
// Draws a placard in the supplied rectangle using the current appearance.
// OSStatus DrawThemePlacard(const Rect *inRect, ThemeDrawState inState);
// Apple, Programming With the Appearance Manager (1999), Theme-Compliant Controls.
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp + 4);
let rect = read_rect(bus, rect_ptr);
self.draw_rect(cpu, bus, &rect, ShapeOp::Erase);
self.draw_rect(cpu, bus, &rect, ShapeOp::Frame);
bus.write_long(sp + 8, 0);
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
(true, 0x274) if cpu.read_reg(Register::D0) as u16 == 0x20 => {
// GetThemeMenuItemExtra ($AA74, selector $0020)
// Reports the theme's extra space around a menu item.
// OSStatus GetThemeMenuItemExtra(ThemeMenuItemType inItemType,
// SInt16 *outHeight, SInt16 *outWidth);
// Apple, Appearance.h (Universal Interfaces 3.4), line 1939;
// Mac OS 8.1 Platinum Appearance Manager measurements.
let sp = cpu.read_reg(Register::A7);
let out_width = bus.read_long(sp);
let out_height = bus.read_long(sp + 4);
let item_type = bus.read_word(sp + 8);
let width = match item_type {
0 => Some(4), // kThemeMenuItemPlain
1 => Some(28), // kThemeMenuItemHierarchical
_ => None,
};
let status = if let Some(width) = width {
if out_width == 0 || out_height == 0 {
-50i32 // paramErr
} else {
bus.write_word(out_width, width);
bus.write_word(out_height, 0);
0
}
} else {
-50i32 // paramErr
};
bus.write_long(sp + 10, status as u32);
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// ========== Shape Drawing Commands ==========
// FrameRect ($A8A1)
// FrameRect ($A8A1): Renders rect outline to framebuffer
(true, 0x0A1) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_rect(commands, 0x0030, (r.top, r.left, r.bottom, r.right));
return Some(Ok(()));
}
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rect(cpu, bus, &r, ShapeOp::Frame);
Ok(())
}
// PaintRect ($A8A2)
// PaintRect ($A8A2): Fills with pen pattern
(true, 0x0A2) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_rect(commands, 0x0031, (r.top, r.left, r.bottom, r.right));
return Some(Ok(()));
}
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rect(cpu, bus, &r, ShapeOp::Paint);
Ok(())
}
// EraseRect ($A8A3)
// EraseRect ($A8A3): Fills with background pattern
(true, 0x0A3) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] EraseRect port=${:08X} rect=({},{}..{},{}) bg=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
r.top,
r.left,
r.bottom,
r.right,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.current_tick()
);
}
if trace_eraserect_enabled() {
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let port_version = bus.read_word(port.wrapping_add(6));
let port_base = if (port_version & 0xC000) != 0 {
let pmh = bus.read_long(port.wrapping_add(2));
if pmh != 0 {
let pm = bus.read_long(pmh);
if pm != 0 {
bus.read_long(pm)
} else {
0
}
} else {
0
}
} else {
bus.read_long(port.wrapping_add(2))
};
eprintln!(
"[ERASERECT] rect=({},{}..{},{}) port=${:08X} portBase=${:08X} screenBase=${:08X}",
r.top, r.left, r.bottom, r.right, port, port_base, self.screen_mode.0,
);
}
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rect(cpu, bus, &r, ShapeOp::Erase);
Ok(())
}
// InvertRect ($A8A4)
// InvertRect ($A8A4): XORs pixels
(true, 0x0A4) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rect(cpu, bus, &r, ShapeOp::Invert);
Ok(())
}
// FillRect ($A8A5)
//
// The Fill family extends the OpenRgn-recording shim — per
// IM:I I-184 the fill procedures add to the region being built.
// FillRect ($A8A5): Fills with specified pattern
(true, 0x0A5) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
let mut pat = [0u8; 8];
for (i, byte) in pat.iter_mut().enumerate() {
*byte = bus.read_byte(pat_ptr + i as u32);
}
// Apply fill-black override: substitute the QD `black` global
// pattern with a dithered pattern for games that need it.
if let Some(override_pat) = self.fill_black_override {
if pat == [0xFF; 8] {
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
if pat_ptr == global_ptr.wrapping_sub(16) {
pat = override_pat;
}
}
}
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] FillRect port=${:08X} rect=({},{},{},{}) pat={:02X?} fg=({:04X},{:04X},{:04X}) bg=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
r.top,
r.left,
r.bottom,
r.right,
pat,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.current_tick(),
);
}
self.draw_rect(cpu, bus, &r, ShapeOp::Fill(pat));
Ok(())
}
// FrameOval ($A8B7)
// Draws the outline of the oval that fits inside the specified rectangle.
// PROCEDURE FrameOval(r: Rect);
// Inside Macintosh Volume I, I-177
(true, 0x0B7) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
let spans = Self::compute_oval_spans(r.right - r.left, r.bottom - r.top)
.into_iter()
.map(|(left, right)| (r.left + left, r.left + right))
.collect::<Vec<_>>();
if self.extend_recording_region_from_spans(r.top, &spans) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_oval(cpu, bus, &r, ShapeOp::Frame);
Ok(())
}
// PaintOval ($A8B8)
// Paints the oval that fits inside the specified rectangle with the pen pattern.
// PROCEDURE PaintOval(r: Rect);
// Inside Macintosh Volume I, I-178
(true, 0x0B8) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_oval(cpu, bus, &r, ShapeOp::Paint);
Ok(())
}
// EraseOval ($A8B9)
// Erases the oval that fits inside the specified rectangle with the background pattern.
// PROCEDURE EraseOval(r: Rect);
// Inside Macintosh Volume I, I-178
(true, 0x0B9) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_oval(cpu, bus, &r, ShapeOp::Erase);
Ok(())
}
// InvertOval ($A8BA)
// Inverts the pixels of the oval that fits inside the specified rectangle.
// PROCEDURE InvertOval(r: Rect);
// Inside Macintosh Volume I, I-178
(true, 0x0BA) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_oval(cpu, bus, &r, ShapeOp::Invert);
Ok(())
}
// FillOval ($A8BB)
// Fills the oval that fits inside the specified rectangle with the given pattern.
// PROCEDURE FillOval(r: Rect; pat: Pattern);
// Inside Macintosh Volume I, I-178
(true, 0x0BB) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
let mut pat = [0u8; 8];
for (i, byte) in pat.iter_mut().enumerate() {
*byte = bus.read_byte(pat_ptr + i as u32);
}
self.draw_oval(cpu, bus, &r, ShapeOp::Fill(pat));
Ok(())
}
// FrameRoundRect ($A8B0)
// Draws the outline of the specified round-cornered rectangle.
// PROCEDURE FrameRoundRect(r: Rect; ovalWidth, ovalHeight: INTEGER);
// Inside Macintosh Volume I, I-178
//
// Inside OpenRgn, add the round-rect's exact scanline boundary and
// draw only when the pen is visible. Imaging With QuickDraw (1994), pp. 3-87--3-89,
// requires framed-shape geometry rather than its bounding box.
// FrameRoundRect ($A8B0)
(true, 0x0B0) => {
let sp = cpu.read_reg(Register::A7);
let oval_height = bus.read_word(sp) as i16;
let oval_width = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_round_rect(
commands,
0x0040,
(r.top, r.left, r.bottom, r.right),
oval_width,
oval_height,
);
return Some(Ok(()));
}
let spans = Self::compute_rrect_spans(&r, oval_width, oval_height);
if self.extend_recording_region_from_spans(r.top, &spans) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_round_rect(cpu, bus, &r, oval_width, oval_height, ShapeOp::Frame);
Ok(())
}
// PaintRoundRect ($A8B1)
// Paints the specified round-cornered rectangle with the pen pattern.
// PROCEDURE PaintRoundRect(r: Rect; ovalWidth, ovalHeight: INTEGER);
// Inside Macintosh Volume I, I-178
//
// OpenRgn-recording shim — see FrameRoundRect notes above.
// PaintRoundRect ($A8B1)
(true, 0x0B1) => {
let sp = cpu.read_reg(Register::A7);
let oval_height = bus.read_word(sp) as i16;
let oval_width = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
pict::recording_push_round_rect(
commands,
0x0041,
(r.top, r.left, r.bottom, r.right),
oval_width,
oval_height,
);
return Some(Ok(()));
}
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_round_rect(cpu, bus, &r, oval_width, oval_height, ShapeOp::Paint);
Ok(())
}
// EraseRoundRect ($A8B2)
// Erases the specified round-cornered rectangle with the background pattern.
// PROCEDURE EraseRoundRect(r: Rect; ovalWidth, ovalHeight: INTEGER);
// Inside Macintosh Volume I, I-178
//
// OpenRgn-recording shim — see FrameRoundRect notes above.
// EraseRoundRect ($A8B2)
(true, 0x0B2) => {
let sp = cpu.read_reg(Register::A7);
let oval_height = bus.read_word(sp) as i16;
let oval_width = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_round_rect(cpu, bus, &r, oval_width, oval_height, ShapeOp::Erase);
Ok(())
}
// InvertRoundRect ($A8B3)
// Inverts the pixels of the specified round-cornered rectangle.
// PROCEDURE InvertRoundRect(r: Rect; ovalWidth, ovalHeight: INTEGER);
// Inside Macintosh Volume I, I-178
//
// OpenRgn-recording shim — see FrameRoundRect notes above.
// InvertRoundRect ($A8B3)
(true, 0x0B3) => {
let sp = cpu.read_reg(Register::A7);
let oval_height = bus.read_word(sp) as i16;
let oval_width = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_round_rect(cpu, bus, &r, oval_width, oval_height, ShapeOp::Invert);
Ok(())
}
// FillRoundRect ($A8B4)
// Fills the specified round-cornered rectangle with the given pattern.
// PROCEDURE FillRoundRect(r: Rect; ovalWidth, ovalHeight: INTEGER; pat: Pattern);
// Inside Macintosh Volume I, I-178
//
// OpenRgn-recording shim — see FillRect notes.
// FillRoundRect ($A8B4)
(true, 0x0B4) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
let oval_height = bus.read_word(sp + 4) as i16;
let oval_width = bus.read_word(sp + 6) as i16;
let rect_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
let mut pat = [0u8; 8];
for (i, byte) in pat.iter_mut().enumerate() {
*byte = bus.read_byte(pat_ptr + i as u32);
}
self.draw_round_rect(cpu, bus, &r, oval_width, oval_height, ShapeOp::Fill(pat));
Ok(())
}
// ========== CopyBits ==========
// CopyBits (0xA8EC)
// Copies a bit or pixel image between graphics ports, scaling and clipping to visRgn, clipRgn, and maskRgn.
// PROCEDURE CopyBits (srcBits,dstBits: BitMap; srcRect,dstRect: Rect; mode: INTEGER; maskRgn: RgnHandle);
// Imaging With QuickDraw 1994, 3-112
// CopyBits ($A8EC): Supports packed 1/2/4/8bpp BitMap and PixMap sources, nearest-neighbor scaling, palette translation, transparent mode, and bbox clipping to visRgn/clipRgn/maskRgn; complex transfer modes and non-rectangular region semantics remain incomplete
(true, 0x0EC) => {
self.debug_copy_bits_count = self.debug_copy_bits_count.saturating_add(1);
let sp = cpu.read_reg(Register::A7);
let trap_pc = cpu.read_reg(Register::PC).wrapping_sub(2);
let mask_rgn = bus.read_long(sp);
let mode = bus.read_word(sp + 4) as i16;
let dst_rect_ptr = bus.read_long(sp + 6);
let src_rect_ptr = bus.read_long(sp + 10);
let dst_bits_ptr = bus.read_long(sp + 14);
let src_bits_ptr = bus.read_long(sp + 18);
cpu.write_reg(Register::A7, sp + 22);
// Nil source or destination bitmap pointers are inert. This
// keeps CopyBits from dereferencing placeholder BitMap slots
// that some callers leave empty while probing the blit path.
if src_bits_ptr == 0 || dst_bits_ptr == 0 {
return Some(Ok(()));
}
// The QuickDraw bottleneck is downstream of GrafPort
// clipping. A replacement bitsProc must not get a chance to
// paint through a hidden window (whose visRgn is empty), nor
// through an empty clipRgn. Inside Macintosh Volume I,
// pp. I-158, I-176, and I-197.
// Picture recording ignores the current port's visibility,
// while clipRgn and maskRgn continue to constrain the saved
// image. A hidden window therefore records CopyBits for later
// DrawPicture playback without painting live pixels. Imaging
// With QuickDraw (1994), pp. 7-39--7-42.
if self.copy_bits_fully_clipped_in_current_port(
bus,
dst_bits_ptr,
dst_rect_ptr,
mask_rgn,
self.recording_picture.is_none(),
) {
return Some(Ok(()));
}
// CopyBits is a bottleneck caller: it hands the transfer to the
// current port's grafProcs.bitsProc, which is StdBits unless the
// app replaced it (IM:I I-176 and I-197). Applications that
// colourise an otherwise black-and-white drawing pipeline do
// exactly that — Myst Preview's HyperTint XCMD installs a
// bitsProc on the HyperCard card port, and BasiliskII shows
// HyperCard's 1-bit card blit detouring through it from the
// moment the colour card comes up. Ignoring the slot repaints
// the black-and-white card straight over the colour layer.
//
// Tail-call the guest proc with StdBits' Pascal frame
// (srcBits, srcRect, dstRect, mode, maskRgn — no dstBits, since
// the destination is the port) and let it drive the blit.
if let Some(bits_proc) = self.custom_bits_proc(bus, cpu) {
let return_pc = cpu.read_reg(Register::PC);
let mut frame_sp = cpu.read_reg(Register::A7);
for arg in [src_bits_ptr, src_rect_ptr, dst_rect_ptr] {
frame_sp = frame_sp.wrapping_sub(4);
bus.write_long(frame_sp, arg);
}
frame_sp = frame_sp.wrapping_sub(2);
bus.write_word(frame_sp, mode as u16);
frame_sp = frame_sp.wrapping_sub(4);
bus.write_long(frame_sp, mask_rgn);
self.bits_proc_reentry = Some((bits_proc, frame_sp));
frame_sp = frame_sp.wrapping_sub(4);
bus.write_long(frame_sp, return_pc);
cpu.write_reg(Register::A7, frame_sp);
cpu.write_reg(Register::PC, bits_proc);
return Some(Ok(()));
}
let mut src_info = self.resolve_copy_bitmap(bus, src_bits_ptr);
let mut dst_info = self.resolve_copy_bitmap(bus, dst_bits_ptr);
// Guard against NIL/sentinel destination baseAddr and
// source $FFFFFFFF sentinel. A NIL destination cannot
// receive pixel writes, and a $FFFFFFFF source/destination
// can wrap address math into low RAM.
//
// Note: we intentionally allow src_base == 0 here. Some
// CopyBits callers hand a transient source BitMap with NIL
// baseAddr while still expecting the draw path to proceed
// via accompanying state; treating src=0 as an unconditional
// no-op regresses menu/title rendering.
//
// Inside Macintosh Volume I, I-148 (BitMap structure).
if src_info.base == u32::MAX || dst_info.base == 0 || dst_info.base == u32::MAX {
eprintln!(
"[COPYBITS] skipping no-op: src_base=${:08X} dst_base=${:08X} (NIL baseAddr)",
src_info.base, dst_info.base
);
return Some(Ok(()));
}
if let Some(path) = dump_copybits_src_path() {
if src_info.pixel_size == 8
&& src_info.bounds_bottom > src_info.bounds_top
&& src_info.bounds_right > src_info.bounds_left
{
Self::dump_bitmap_as_png(
bus,
&src_info,
&self.read_port_clut(bus, src_info.ctab_handle),
path,
);
}
}
let src_top = bus.read_word(src_rect_ptr) as i16;
let src_left = bus.read_word(src_rect_ptr + 2) as i16;
let src_bottom = bus.read_word(src_rect_ptr + 4) as i16;
let src_right = bus.read_word(src_rect_ptr + 6) as i16;
let dst_top = bus.read_word(dst_rect_ptr) as i16;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16;
let mode_base = (mode & 0x3F) as u16;
let source_bounds_are_original = src_info.bounds_bottom > src_info.bounds_top
&& src_info.bounds_right > src_info.bounds_left;
let destination_bounds_are_authoritative = dst_info.bounds_bottom
> dst_info.bounds_top
&& dst_info.bounds_right > dst_info.bounds_left;
Self::sanitize_copy_bitmap_bounds(
&mut src_info,
src_top,
src_left,
src_bottom,
src_right,
);
Self::sanitize_copy_bitmap_bounds(
&mut dst_info,
dst_top,
dst_left,
dst_bottom,
dst_right,
);
if self.recording_picture.is_some() {
let mut source_clut = if src_info.pixel_size == 1 {
[[0u16; 3]; 256]
} else {
self.read_port_clut(bus, src_info.ctab_handle)
};
if src_info.pixel_size == 1 {
source_clut[0] = [self.bg_color.0, self.bg_color.1, self.bg_color.2];
source_clut[1] = [self.fg_color.0, self.fg_color.1, self.fg_color.2];
}
if let Some(snapshot) = Self::encode_bitmap_copy_pict(
bus,
src_info,
&source_clut,
(src_top, src_left, src_bottom, src_right),
(dst_top, dst_left, dst_bottom, dst_right),
mode,
) {
if let Some(existing) = self.recording_picture_bitmap.as_mut() {
// Each encoded snapshot has its own ten-byte
// picture header and end opcode. Keep every band
// in one stream, with a single final end opcode.
if existing.last() == Some(&0xff) && snapshot.len() >= 11 {
existing.pop();
existing.extend_from_slice(&snapshot[10..]);
}
} else {
self.recording_picture_bitmap = Some(snapshot);
}
}
return Some(Ok(()));
}
if src_info.row_bytes == 0
|| dst_info.row_bytes == 0
|| src_info.pixel_size == 0
|| dst_info.pixel_size == 0
{
return Some(Ok(()));
}
let screen_copybits_rect = (dst_info.base == self.screen_mode.0).then(|| {
Self::screen_copybits_rect(
&dst_info, src_top, src_left, src_bottom, src_right, dst_top, dst_left,
dst_bottom, dst_right,
)
});
if trace_title_diag_enabled()
&& self.current_tick() >= 68
&& self.current_tick() <= 110
&& dst_info.base == self.screen_mode.0
{
eprintln!(
"[TITLE-DIAG] CopyBits tick={} pc=${:08X} port=${:08X} srcBits=${:08X} dstBits=${:08X} srcBase=${:08X} dstBase=${:08X} srcRect=({},{}..{},{} ) dstRect=({},{}..{},{} ) mode={} srcCTab=${:08X} dstCTab=${:08X}",
self.current_tick(),
trap_pc,
*self.current_port,
src_bits_ptr,
dst_bits_ptr,
src_info.base,
dst_info.base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mode_base,
src_info.ctab_handle,
dst_info.ctab_handle,
);
}
if trace_menu_redraw_enabled()
&& trace_menu_redraw_rect_intersects(dst_top, dst_left, dst_bottom, dst_right)
{
eprintln!(
"[MENU-REDRAW] CopyBits srcBase=${:08X} dstBase=${:08X} mode={} src=({},{}..{},{} ) dst=({},{}..{},{} ) mask=${:08X}",
src_info.base,
dst_info.base,
mode_base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mask_rgn,
);
}
if trace_dialog_draw_enabled() && self.dialog_tracking.is_some() {
eprintln!(
"[DIALOG-DRAW] CopyBits current_port=${:08X} srcBase=${:08X} dstBase=${:08X} mode={} src=({},{}..{},{} ) dst=({},{}..{},{} ) mask=${:08X}",
*self.current_port,
src_info.base,
dst_info.base,
mode_base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mask_rgn,
);
}
if trace_dialog_port_dump_enabled() && self.dialog_tracking.is_some() {
Self::trace_port_snapshot(bus, "CopyBits-current", *self.current_port);
}
if trace_dialog_port_dump_enabled() && self.dialog_tracking.is_some() {
Self::trace_port_snapshot(bus, "CopyBits-current", *self.current_port);
}
if src_bottom <= src_top
|| src_right <= src_left
|| dst_bottom <= dst_top
|| dst_right <= dst_left
{
return Some(Ok(()));
}
// Clip destination to the current port's visRgn and clipRgn
// Per Inside Macintosh Volume I, I-158: CopyBits clips to the
// intersection of visRgn, clipRgn, and the maskRgn parameter,
// but ONLY when the destination bitmap is the current port's bitmap.
// When copying to an offscreen bitmap, port clipping does not apply.
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let (mut clip_t, mut clip_l, mut clip_b, mut clip_r) =
(dst_top, dst_left, dst_bottom, dst_right);
let mut vis_rgn_handle = 0;
let mut clip_rgn_handle = 0;
// Check if destination is the current port's bitmap
let dst_is_port = if port != 0 {
let port_version = bus.read_word(port + 6);
let port_base = if (port_version & 0xC000) == 0xC000 {
// CGrafPort: portPixMap handle at offset 2
let pm_handle = bus.read_long(port + 2);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
Self::offscreen_pixmap_base_ptr(bus, pm_ptr)
} else {
0
}
} else {
// GrafPort: portBits.baseAddr at offset 2
bus.read_long(port + 2)
};
port_base == dst_info.base
} else {
false
};
if dst_is_port && port != 0 {
// Clip to visRgn (GrafPort offset 24)
vis_rgn_handle = bus.read_long(port + 24);
if !Self::clip_rect_to_region_bbox(
bus,
vis_rgn_handle,
&mut clip_t,
&mut clip_l,
&mut clip_b,
&mut clip_r,
) {
return Some(Ok(()));
}
// Clip to clipRgn (GrafPort offset 28)
clip_rgn_handle = bus.read_long(port + 28);
if !Self::clip_rect_to_region_bbox(
bus,
clip_rgn_handle,
&mut clip_t,
&mut clip_l,
&mut clip_b,
&mut clip_r,
) {
return Some(Ok(()));
}
}
if !Self::clip_rect_to_region_bbox(
bus,
mask_rgn,
&mut clip_t,
&mut clip_l,
&mut clip_b,
&mut clip_r,
) {
return Some(Ok(()));
}
// Also clip against destination bitmap bounds
clip_t = clip_t.max(dst_info.bounds_top);
clip_l = clip_l.max(dst_info.bounds_left);
clip_b = clip_b.min(dst_info.bounds_bottom);
clip_r = clip_r.min(dst_info.bounds_right);
// Compute effective copy region after clipping
let eff_width = clip_r - clip_l;
let eff_height = clip_b - clip_t;
if eff_width <= 0 || eff_height <= 0 {
return Some(Ok(()));
}
if let Some(rect) = screen_copybits_rect {
self.copybits_screen_count += 1;
self.note_screen_copybits_rect(
rect.src_top,
rect.src_left,
rect.src_bottom,
rect.src_right,
rect.dst_top,
rect.dst_left,
rect.dst_bottom,
rect.dst_right,
);
self.ensure_dialog_background_saved_for_screen_port(bus, port);
}
let mask_membership =
Self::build_region_membership_cache(bus, mask_rgn, clip_t, clip_b);
let vis_membership =
Self::build_region_membership_cache(bus, vis_rgn_handle, clip_t, clip_b);
let clip_membership =
Self::build_region_membership_cache(bus, clip_rgn_handle, clip_t, clip_b);
// Precompute "no clipping" so per-pixel region checks can
// short-circuit out of the hot loop.
let no_clipping = vis_rgn_handle == 0 && clip_rgn_handle == 0 && mask_rgn == 0;
// Detect "no scaling" so per-pixel scale_coord (mul + div)
// can be replaced with a single addition for the common
// identity case (src == dst dimensions).
let src_w = i32::from(src_right) - i32::from(src_left);
let src_h = i32::from(src_bottom) - i32::from(src_top);
let dst_w = i32::from(dst_right) - i32::from(dst_left);
let dst_h = i32::from(dst_bottom) - i32::from(dst_top);
let no_scaling = src_w == dst_w && src_h == dst_h && src_w > 0 && src_h > 0;
let trace_probes = if trace_menu_redraw_enabled() {
trace_menu_probe_points()
.into_iter()
.filter_map(|(label, probe_y, probe_x)| {
if !trace_menu_rect_contains_point(
clip_t, clip_l, clip_b, clip_r, probe_y, probe_x,
) {
return None;
}
let src_y = Self::scale_coord(
src_top, src_bottom, dst_top, dst_bottom, probe_y,
)? as i16;
let src_x = Self::scale_coord(
src_left, src_right, dst_left, dst_right, probe_x,
)? as i16;
let src_pixel = Self::read_bitmap_pixel(bus, &src_info, src_y, src_x);
let dst_before =
Self::read_bitmap_pixel(bus, &dst_info, probe_y, probe_x);
Some((label, probe_y, probe_x, src_y, src_x, src_pixel, dst_before))
})
.collect::<Vec<_>>()
} else {
Vec::new()
};
let dst_ctab_handle = self.copy_bits_destination_ctab_handle(bus, port, &dst_info);
let src_clut_resolution = matches!(src_info.pixel_size, 2 | 4 | 8)
.then(|| self.read_port_clut_with_provenance(bus, src_info.ctab_handle));
let src_clut = src_clut_resolution.as_ref().map(|(clut, _)| *clut);
let dst_clut_resolution = self.read_indexed_destination_clut_with_provenance(
bus,
dst_ctab_handle,
dst_info.pixel_size,
screen_copybits_rect.is_some(),
);
let dst_clut = dst_clut_resolution.as_ref().map(|(clut, _)| *clut);
let src_ctab_seed = Self::ctab_seed(bus, src_info.ctab_handle);
// Executor's translation gate compares the source PixMap's
// CTab seed against `CTAB_SEED(PIXMAP_TABLE(GD_PMAP(the_gd)))` —
// the GDevice the destination lives on. For a screen-targeted
// blit that's the *main screen* GDevice, not whatever
// `self.current_gdevice` happens to be (the game may have
// SetGDevice'd onto an offscreen GWorld). Look up the seed
// from `main_gdevice_handle`, not `current_gdevice`, so an
// on-screen CopyBits doesn't compare against an offscreen
// GWorld's CTab seed and spuriously translate.
// Imaging With QuickDraw 1994, 7-24 through 7-28 (CopyBits).
let dst_ctab_seed = if dst_ctab_handle == 0 {
Self::ctab_seed(
bus,
Self::gdevice_ctab_handle(bus, self.main_gdevice_handle),
)
} else {
Self::ctab_seed(bus, dst_ctab_handle)
};
// One-shot offscreen dump triggered by SYSTEMLESS_TRACE_OFFSCREEN_002EAD50.
if trace_offscreen_002ead50_enabled() && src_info.base == 0x002EAD50 {
let src_rb = src_info.row_bytes;
eprintln!(
"[OFFSCREEN-002EAD50] tick={} src_rect=({},{}..{},{}) rb={}",
self.current_tick(), src_top, src_left, src_bottom, src_right, src_rb,
);
for row_y in [0i32, 1, 2, 3, 4, 5, 30, 53, 54, 55, 56, 57, 58] {
let mut sample = String::new();
for col in [0u32, 60, 120, 180, 240, 300, 360, 420, 475] {
let addr = src_info
.base
.wrapping_add((row_y as u32).wrapping_mul(src_rb))
.wrapping_add(col);
let idx = bus.read_byte(addr);
sample.push_str(&format!(" x{}={}", col, idx));
}
eprintln!("[OFFSCREEN-002EAD50] y={}:{}", row_y, sample);
}
}
if trace_copybits_all_enabled() {
let palette_details = match (src_clut.as_ref(), dst_clut.as_ref()) {
(Some(src_clut), Some(dst_clut)) => {
let mut parts = Vec::new();
for index in [0usize, 16, 43, 100, 150, 185, 220, 245] {
let s = src_clut[index];
let d = dst_clut[index];
parts.push(format!(
"idx{} src=({:04X},{:04X},{:04X}) dst=({:04X},{:04X},{:04X})",
index, s[0], s[1], s[2], d[0], d[1], d[2]
));
}
parts.join(" | ")
}
_ => String::new(),
};
let sample_points = [
(dst_top, dst_left),
((dst_top + dst_bottom) / 2, (dst_left + dst_right) / 2),
];
let mut sample_details = Vec::new();
for (dy, dx) in sample_points {
let src_sample =
Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, dy)
.zip(Self::scale_coord(
src_left, src_right, dst_left, dst_right, dx,
))
.map(|(sy, sx)| (sy as i16, sx as i16));
if let Some((sy, sx)) = src_sample {
let src_pixel = Self::read_bitmap_pixel(bus, &src_info, sy, sx);
let dst_pixel = Self::read_bitmap_pixel(bus, &dst_info, dy, dx);
let device_rgb = match (dst_info.pixel_size == 8, src_pixel) {
(true, Some(src_pixel)) => self.device_clut[src_pixel as usize],
_ => [0, 0, 0],
};
sample_details.push(format!(
"dst=({dy},{dx}) src=({sy},{sx}) srcPix={src_pixel:?} dstPix={dst_pixel:?} deviceRGB=({:04X},{:04X},{:04X})",
device_rgb[0], device_rgb[1], device_rgb[2]
));
}
}
eprintln!(
"[COPYBITS-ALL] srcBase=${:08X} dstBase=${:08X} screenBase=${:08X} src=({},{}..{},{}) dst=({},{}..{},{}) mode={} srcDepth={} dstDepth={} mask=${:08X} port=${:08X} srcCTab=${:08X} dstInfoCTab=${:08X} dstCTab=${:08X} srcSeed={:?} dstSeed={:?} {}",
src_info.base,
dst_info.base,
self.screen_mode.0,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mode,
src_info.pixel_size,
dst_info.pixel_size,
mask_rgn,
*self.current_port,
src_info.ctab_handle,
dst_info.ctab_handle,
dst_ctab_handle,
src_ctab_seed,
dst_ctab_seed,
sample_details.join(" | "),
);
if !palette_details.is_empty() {
eprintln!("[COPYBITS-ALL] palettes {}", palette_details);
}
}
// CopyBits translates between different indexed depths even
// when an old application leaves the source CTable seed at 0.
// For same-depth copies, preserve Executor's seed gate so a
// zero seed continues to mean that the pixels already carry
// destination-device indices.
// Imaging With QuickDraw 1994, 3-71.
// references/executor/src/quickdraw/qStdBits.cpp
// A device ColorTable (ctFlags high bit set) explicitly
// describes positional device indices. Preserve those
// indices when its seed identifies the destination screen's
// table, even if SetEntries has temporarily changed the
// device RGB entries without changing the logical inverse-
// table baseline. During a recognized full-table fade, the
// same preservation applies while the hardware CLUT is being
// rewritten. A pixMap ColorTable instead associates RGB
// values with source pixels and must be matched. Inside
// Macintosh Volume V (1986), pp. V-57..V-58, V-138,
// V-143..V-145.
let source_ctab_ptr = Self::color_table_ptr(bus, src_info.ctab_handle);
let source_uses_device_ctab =
source_ctab_ptr != 0 && bus.read_word(source_ctab_ptr + 4) & 0x8000 != 0;
let source_is_destination_device = src_ctab_seed.is_some()
&& src_ctab_seed == dst_ctab_seed;
let skip_device_translation_to_screen = src_info.pixel_size == 8
&& dst_ctab_handle == 0
&& source_uses_device_ctab
&& (source_is_destination_device || self.screen_palette_fade_active);
// An all-explicit palette assigns stable device indices, so
// same-depth copies preserve those indices. Packed 2/4-bit
// sources copied into an 8-bit destination cannot preserve
// their indices across the depth change; their RGB values
// must still be matched into the destination CTable.
let skip_explicit_palette_translation = src_info.pixel_size == dst_info.pixel_size
&& self.explicit_palette_ctabs.contains(&src_info.ctab_handle);
// A CTable seed is an invalidation token, not proof that two
// tables contain the same RGB entries. Applications may reuse
// a seed while changing a table in place, and the screen's
// live device CLUT may intentionally differ from the Color
// Manager's logical table during a fade. Compare the
// effective tables before preserving indexed pixels.
let indexed_tables_differ = match (src_clut.as_ref(), dst_clut.as_ref()) {
(Some(src_clut), Some(dst_clut)) => src_clut != dst_clut,
_ => src_ctab_seed != dst_ctab_seed,
};
let indexed_palette_identity_known = src_info.pixel_size == 8
&& dst_info.pixel_size == 8
&& (src_info.ctab_handle == dst_info.ctab_handle
|| matches!(
(src_clut_resolution.as_ref(), dst_clut_resolution.as_ref()),
(Some((src_clut, true)), Some((dst_clut, true)))
if src_clut == dst_clut
)
|| skip_device_translation_to_screen
|| skip_explicit_palette_translation);
let palette_translation = if matches!(src_info.pixel_size, 2 | 4 | 8)
&& matches!(dst_info.pixel_size, 2 | 4 | 8)
&& src_info.ctab_handle != dst_info.ctab_handle
&& (src_info.pixel_size != dst_info.pixel_size || indexed_tables_differ)
&& !skip_device_translation_to_screen
&& !skip_explicit_palette_translation
{
match (src_clut.as_ref(), dst_clut.as_ref()) {
(Some(src_clut), Some(dst_clut)) => Some(self.build_palette_translation(
bus,
src_clut,
dst_clut,
dst_ctab_handle,
src_info.pixel_size,
dst_info.pixel_size,
)),
_ => None,
}
} else {
None
};
let src_clut = src_clut.as_ref();
let dst_clut = dst_clut.as_ref();
let palette_translation = palette_translation.as_ref();
let shared_indexed_pixel_mask = Self::shared_indexed_pixel_mask(
src_info.pixel_size,
dst_info.pixel_size,
src_info.ctab_handle,
dst_ctab_handle,
src_clut,
dst_clut,
);
let transformed_blit = !no_scaling
|| palette_translation.is_some()
|| src_info.pixel_size != dst_info.pixel_size
|| mode_base != 0
|| !no_clipping;
self.add_hle_tick_cost(Self::quickdraw_blit_tick_cost(
eff_width as u32,
eff_height as u32,
src_info.pixel_size,
dst_info.pixel_size,
transformed_blit,
));
let (copy_fg_rgb, copy_bg_rgb) = self.copy_bits_port_draw_colors(bus, port);
// Port/region resolution, diagnostics, and picture/screen
// effects remain at this edge. The shared operation decides
// whether the resolved format, mode, and geometry belong to
// its rectangular byte-aligned or packed srcCopy family.
let row_copy_edge_eligible = !Self::region_is_complex(bus, vis_rgn_handle)
&& !Self::region_is_complex(bus, clip_rgn_handle)
&& !Self::region_is_complex(bus, mask_rgn)
&& trace_copybits_hud_probe().is_none()
&& dump_copybits_src_path().is_none()
&& !trace_copybits_all_enabled()
&& !trace_menu_redraw_enabled()
&& trace_probes.is_empty();
if row_copy_edge_eligible {
use crate::copy_bits::{Indexed8ScalingSelection, RowCopyOutcome};
let indexed8_scaling = Indexed8ScalingSelection::from_adapter_facts(
mask_rgn == 0,
source_bounds_are_original,
destination_bounds_are_authoritative,
indexed_palette_identity_known,
mode as u16,
);
let outcome = resolved_row_copy(
mode_base,
src_info,
dst_info,
[src_top, src_left, src_bottom, src_right].map(i32::from),
[dst_top, dst_left, dst_bottom, dst_right].map(i32::from),
[clip_t, clip_l, clip_b, clip_r].map(i32::from),
palette_translation,
)
.execute_with_indexed8_scaling(bus, indexed8_scaling);
let wrote_rows = match outcome {
RowCopyOutcome::Completed => true,
RowCopyOutcome::WriteFailure { rows_written } => rows_written != 0,
RowCopyOutcome::NoOp | RowCopyOutcome::ReadOrGeometryFailure => {
return Some(Ok(()));
}
RowCopyOutcome::Declined => false,
};
if outcome != RowCopyOutcome::Declined {
if wrote_rows {
if let Some(rect) = screen_copybits_rect {
self.fill_kiosk_letterbox_for_copybits(bus, rect);
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
*self.current_port,
(
clip_t.saturating_sub(dst_info.bounds_top),
clip_l.saturating_sub(dst_info.bounds_left),
clip_b.saturating_sub(dst_info.bounds_top),
clip_r.saturating_sub(dst_info.bounds_left),
),
);
self.refresh_visible_dialog_snapshot_after_bulk_port_draw(
bus,
*self.current_port,
(rect.dst_top, rect.dst_left, rect.dst_bottom, rect.dst_right),
);
}
}
return Some(Ok(()));
}
}
// SYSTEMLESS_TRACE_COPYBITS logs "interesting" CopyBits (mask,
// scale, or translation). SYSTEMLESS_TRACE_COPYBITS_ALL logs
// EVERY CopyBits unconditionally.
let log_copybits = trace_copybits_all_enabled()
|| (trace_copybits_enabled()
&& (mask_rgn != 0
|| src_info.pixel_size != dst_info.pixel_size
|| src_right - src_left != dst_right - dst_left
|| src_bottom - src_top != dst_bottom - dst_top
|| palette_translation.is_some()));
// Per-pixel HUD probe: when SYSTEMLESS_TRACE_COPYBITS_HUD_PROBE
// is set, log src_idx→dst_idx for 8bpp CopyBits writes
// landing at the configured probe coordinates. Used to
// disambiguate "offscreen bitmap already holds the wrong
// index" vs "CopyBits translated a correct src to the wrong
// dst".
let copybits_hud_probe_points = if trace_copybits_hud_probe().is_some()
&& src_info.pixel_size == 8
&& dst_info.pixel_size == 8
{
Some(trace_copybits_hud_probe_points())
} else {
None
};
if log_copybits {
// PC is the post-trap address; subtract 2 to get
// the trap-instruction address that the FB-WRITE-
// DISASM tracer reports. Including it here makes
// it possible to correlate a CopyBits log entry
// with the FB-WRITE-DISASM line that pinpointed
// the same call from the destination side.
let calling_pc = cpu.read_reg(Register::PC).wrapping_sub(2);
eprintln!(
"[COPYBITS] tick={} pc=${:08X} srcBase=${:08X} dstBase=${:08X} src={}bpp dst={}bpp mode={} src=({},{}..{},{} ) dst=({},{}..{},{} ) mask=${:08X} translate={} srcSeed={:?} dstSeed={:?}",
self.current_tick(),
calling_pc,
src_info.base,
dst_info.base,
src_info.pixel_size,
dst_info.pixel_size,
mode_base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mask_rgn,
palette_translation.is_some(),
src_ctab_seed,
dst_ctab_seed,
);
}
if trace_menu_redraw_enabled()
&& trace_menu_redraw_rect_intersects(dst_top, dst_left, dst_bottom, dst_right)
{
eprintln!(
"[MENU-REDRAW] CopyBits ctabs src=${:08X} dstInfo=${:08X} dstEffective=${:08X} srcSeed={:?} dstSeed={:?} translate={}",
src_info.ctab_handle,
dst_info.ctab_handle,
dst_ctab_handle,
src_ctab_seed,
dst_ctab_seed,
palette_translation.is_some(),
);
}
let destination_entry_count =
Self::indexed_ctab_entry_count(dst_info.pixel_size) as usize;
let fg_index = dst_clut.as_ref().map(|clut| {
self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
clut,
copy_fg_rgb,
destination_entry_count,
)
});
let bg_index = dst_clut.as_ref().map(|clut| {
self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
clut,
copy_bg_rgb,
destination_entry_count,
)
});
let transparent_src_indices = if mode_base == 36 {
self.copy_bits_transparent_source_indices(
bus,
src_info.ctab_handle,
src_clut,
copy_bg_rgb,
)
} else {
None
};
// CopyBits must preserve source pixels for overlapping blits.
// Snapshot the touched source rows when src and dst share storage
// so later writes don't affect subsequent reads.
// Both modes depend only on the saved source; retaining the
// destination expression would grow it on repeated copies.
let detail_table = (bus.has_outline_presentation()
&& matches!(mode_base, 0 | 4)
&& src_info.pixel_size == 8
&& dst_info.pixel_size == 8)
.then(|| {
self.copy_bits_source_only_table(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
palette_translation,
if mode_base == 0 { None } else { shared_indexed_pixel_mask },
mode_base,
copy_fg_rgb,
copy_bg_rgb,
)
})
.flatten();
let source_snapshot = if src_info.base == dst_info.base
|| (bus.has_outline_presentation() && src_info.pixel_size == 8)
{
let mut row_start = u32::MAX;
let mut row_end = 0u32;
for dy in clip_t..clip_b {
let Some(src_y) =
Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, dy)
else {
continue;
};
if src_y < i32::from(src_info.bounds_top)
|| src_y >= i32::from(src_info.bounds_bottom)
{
continue;
}
let row = (src_y - i32::from(src_info.bounds_top)) as u32;
row_start = row_start.min(row);
row_end = row_end.max(row);
}
if row_start != u32::MAX {
let row_count = row_end - row_start + 1;
let mut snapshot = vec![0u8; (row_count * src_info.row_bytes) as usize];
// Replace the per-byte snapshot loop with bus.read_bytes
// (slice fast path). Per row: one bounds check + memcpy
// instead of row_bytes × byte reads.
for row in 0..row_count {
let row_base = src_info.base + (row_start + row) * src_info.row_bytes;
let snapshot_offset = (row * src_info.row_bytes) as usize;
let row_data = bus.read_bytes(row_base, src_info.row_bytes as usize);
snapshot
[snapshot_offset..snapshot_offset + src_info.row_bytes as usize]
.copy_from_slice(&row_data);
}
Some((row_start, row_count, {
let mut snapshot: crate::memory::SavedPixels = snapshot.into();
bus.capture_pixel_detail(
&mut snapshot,
0,
src_info.base + row_start * src_info.row_bytes,
(row_count * src_info.row_bytes) as usize,
);
snapshot
}))
} else {
None
}
} else {
None
};
let read_src_byte = |bus: &MacMemoryBus, addr: u32| -> u8 {
if let Some((row_start, row_count, snapshot)) = source_snapshot.as_ref() {
let offset = addr.saturating_sub(src_info.base);
let row = offset / src_info.row_bytes;
if row >= *row_start && row < *row_start + *row_count {
let row_offset = row - *row_start;
let col = offset % src_info.row_bytes;
let snapshot_index = (row_offset * src_info.row_bytes + col) as usize;
if snapshot_index < snapshot.len() {
return snapshot[snapshot_index];
}
}
}
bus.read_byte(addr)
};
// Whole-row path for the commonest shape (see
// copy_bits_src_copy_rows_8bpp): the loop's own preconditions
// for that shape plus identity_blit's diagnostics gates, with
// the table from the function the (8, 8) arm below calls per
// pixel, given the arguments it passes. A region needs its
// spans only if it can still exclude a pixel of the clip.
let vis_test = !no_clipping && Self::region_needs_pixel_test(bus, vis_rgn_handle);
let clip_test = !no_clipping && Self::region_needs_pixel_test(bus, clip_rgn_handle);
let mask_test = !no_clipping && Self::region_needs_pixel_test(bus, mask_rgn);
let rows_copied = mode_base == 0
&& no_scaling
&& src_info.pixel_size == 8
&& dst_info.pixel_size == 8
&& trace_probes.is_empty()
&& copybits_hud_probe_points.is_none()
&& dump_copybits_src_path().is_none()
&& !trace_copybits_all_enabled()
&& !trace_menu_redraw_enabled()
&& (i32::from(clip_b) - i32::from(clip_t))
* (i32::from(clip_r) - i32::from(clip_l))
>= COPY_BITS_ROW_PATH_MIN_PIXELS
&& self
.copy_bits_source_only_table(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
palette_translation,
shared_indexed_pixel_mask,
0,
copy_fg_rgb,
copy_bg_rgb,
)
.is_some_and(|table| {
Self::copy_bits_src_copy_rows_8bpp(
bus,
&src_info,
&dst_info,
(src_top, src_left),
(dst_top, dst_left, dst_w, dst_h),
(clip_t, clip_l, clip_b, clip_r),
[
(vis_test, vis_membership.as_ref()),
(clip_test, clip_membership.as_ref()),
(mask_test, mask_membership.as_ref()),
],
&table,
source_snapshot
.as_ref()
.map(|(first_row, _, pixels)| (*first_row, pixels)),
)
});
// With the rows already written the loop has nothing left to
// do; the screen bookkeeping after it still runs.
let pixel_rows = if rows_copied {
clip_t..clip_t
} else {
clip_t..clip_b
};
for dy in pixel_rows {
// Skip mul/div in scale_coord when not scaling.
let src_y = if no_scaling {
let rel = i32::from(dy) - i32::from(dst_top);
if rel < 0 || rel >= dst_h {
continue;
}
i32::from(src_top) + rel
} else {
let Some(s) =
Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, dy)
else {
continue;
};
s
};
if src_y < i32::from(src_info.bounds_top)
|| src_y >= i32::from(src_info.bounds_bottom)
{
continue;
}
let dst_y = (i32::from(dy) - i32::from(dst_info.bounds_top)) as u32;
for dx in clip_l..clip_r {
// Skip mul/div in scale_coord when not scaling.
let src_x = if no_scaling {
let rel = i32::from(dx) - i32::from(dst_left);
if rel < 0 || rel >= dst_w {
continue;
}
i32::from(src_left) + rel
} else {
let Some(s) =
Self::scale_coord(src_left, src_right, dst_left, dst_right, dx)
else {
continue;
};
s
};
if src_x < i32::from(src_info.bounds_left)
|| src_x >= i32::from(src_info.bounds_right)
{
continue;
}
// Skip the 3 region checks entirely when
// we precomputed that no clipping is in effect.
// The loop bounds already include every region's
// bounding box, so only non-rectangular regions (or
// unreadable ones) need a per-pixel membership test.
if !no_clipping {
if vis_test
&& !Self::region_contains_point_cached(
bus,
vis_rgn_handle,
vis_membership.as_ref(),
dy,
dx,
)
{
continue;
}
if clip_test
&& !Self::region_contains_point_cached(
bus,
clip_rgn_handle,
clip_membership.as_ref(),
dy,
dx,
)
{
continue;
}
if mask_test
&& !Self::region_contains_point_cached(
bus,
mask_rgn,
mask_membership.as_ref(),
dy,
dx,
)
{
continue;
}
}
let dst_x = (i32::from(dx) - i32::from(dst_info.bounds_left)) as u32;
let src_x_off = (src_x - i32::from(src_info.bounds_left)) as u32;
let src_y_off = (src_y - i32::from(src_info.bounds_top)) as u32;
match (src_info.pixel_size, dst_info.pixel_size) {
(src_bits @ (16 | 32), dst_bits @ (1 | 2 | 4 | 8)) => {
let src_addr = src_info.base
+ src_y_off * src_info.row_bytes
+ src_x_off * (src_bits / 8);
let src_rgb = Self::read_rgbdirect_pixel(
|address| read_src_byte(bus, address),
src_addr,
src_bits,
)
.expect("RGBDirect source depth");
if mode_base == 36 && src_rgb == copy_bg_rgb {
continue;
}
let pixels_per_byte = 8 / dst_bits;
let pixel_mask = if dst_bits == 8 {
u8::MAX
} else {
(1u8 << dst_bits) - 1
};
let dst_addr = dst_info.base
+ dst_y * dst_info.row_bytes
+ dst_x / pixels_per_byte;
let dst_shift = 8 - dst_bits - (dst_x % pixels_per_byte) * dst_bits;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte >> dst_shift) & pixel_mask;
let dst_clut = dst_clut.as_ref().expect("indexed destination CLUT");
let dst_rgb = dst_clut[usize::from(dst_pixel)];
let effective_mode = if mode_base == 36 { 0 } else { mode_base };
let Some(result_rgb) = Self::copy_bits_direct_source_mode_rgb(
src_rgb,
dst_rgb,
effective_mode,
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
let mapped = self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
dst_clut,
result_rgb,
1usize << dst_bits,
);
let shifted_mask = pixel_mask << dst_shift;
bus.write_byte(
dst_addr,
(dst_byte & !shifted_mask) | (mapped << dst_shift),
);
}
(src_bits @ (2 | 4), dst_bits) if src_bits == dst_bits => {
let pixels_per_byte = 8 / src_bits;
let pixel_mask = (1u8 << src_bits) - 1;
let src_byte_offset =
src_y_off * src_info.row_bytes + src_x_off / pixels_per_byte;
let src_shift =
8 - src_bits - (src_x_off % pixels_per_byte) * src_bits;
let src_pixel =
(read_src_byte(bus, src_info.base + src_byte_offset)
>> src_shift)
& pixel_mask;
if mode_base == 36
&& transparent_src_indices
.as_ref()
.is_some_and(|indices| indices[src_pixel as usize])
{
continue;
}
let dst_byte_offset =
dst_y * dst_info.row_bytes + dst_x / pixels_per_byte;
let dst_shift = 8 - dst_bits - (dst_x % pixels_per_byte) * dst_bits;
let dst_addr = dst_info.base + dst_byte_offset;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte >> dst_shift) & pixel_mask;
let Some(new_pixel) = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
1usize << dst_bits,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
src_pixel,
dst_pixel,
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
let shifted_mask = pixel_mask << dst_shift;
bus.write_byte(
dst_addr,
(dst_byte & !shifted_mask)
| ((new_pixel & pixel_mask) << dst_shift),
);
}
(src_bits @ (2 | 4), 8) => {
// Indexed PixMap pixels are packed high bit first:
// four 2-bit pixels or two 4-bit pixels per byte.
// Imaging With QuickDraw (1994), pp. 4-5–4-9,
// defines these indexed depths and CopyBits
// performs the source CTable conversion when
// copying into a deeper indexed destination.
let pixels_per_byte = 8 / src_bits;
let src_byte_offset =
src_y_off * src_info.row_bytes + src_x_off / pixels_per_byte;
let shift = 8 - src_bits - (src_x_off % pixels_per_byte) * src_bits;
let mask = (1u8 << src_bits) - 1;
let src_pixel =
(read_src_byte(bus, src_info.base + src_byte_offset) >> shift)
& mask;
if mode_base == 36
&& transparent_src_indices
.as_ref()
.is_some_and(|indices| indices[src_pixel as usize])
{
continue;
}
let dst_addr = dst_info.base + dst_y * dst_info.row_bytes + dst_x;
let Some(dst_pixel) = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
None,
mode_base,
src_pixel,
bus.read_byte(dst_addr),
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
bus.write_byte(dst_addr, dst_pixel);
}
(8, 8) => {
let src_addr =
src_info.base + src_y_off * src_info.row_bytes + src_x_off;
let dst_addr = dst_info.base + dst_y * dst_info.row_bytes + dst_x;
if let Some((row_start, _, snapshot)) = &source_snapshot {
let offset =
(src_addr - src_info.base - row_start * src_info.row_bytes)
as usize;
if detail_table.is_none()
&& bus.transfer_saved_pixel(
dst_addr,
snapshot,
offset,
|bus, src, dst| {
if mode_base == 36
&& transparent_src_indices.as_ref().is_some_and(
|indices| indices[src as usize],
)
{
return dst;
}
self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
src,
dst,
copy_fg_rgb,
copy_bg_rgb,
)
.unwrap_or(dst)
},
)
{
continue;
}
}
let src_pixel = read_src_byte(bus, src_addr);
if mode_base == 36 {
let src_rgb = src_clut.unwrap()[src_pixel as usize];
if transparent_src_indices
.as_ref()
.map_or(false, |indices| indices[src_pixel as usize])
{
if let Some(points) = copybits_hud_probe_points {
if points.iter().any(|&(probe_x, probe_y)| {
dx == probe_x && dy == probe_y
}) {
eprintln!(
"[COPYBITS-HUD] tick={} dx={} dy={} mode={} src_idx={} src_rgb=({:04X},{:04X},{:04X}) transparent=true bg_rgb=({:04X},{:04X},{:04X}) srcBase=${:08X} dstBase=${:08X} srcCTab=${:08X} dstCTab=${:08X} srcSeed={:?} dstSeed={:?}",
self.current_tick(),
dx,
dy,
mode_base,
src_pixel,
src_rgb[0],
src_rgb[1],
src_rgb[2],
copy_bg_rgb[0],
copy_bg_rgb[1],
copy_bg_rgb[2],
src_info.base,
dst_info.base,
src_info.ctab_handle,
dst_ctab_handle,
src_ctab_seed,
dst_ctab_seed,
);
}
}
continue;
}
}
let Some(dst_pixel) = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
src_pixel,
bus.read_byte(dst_addr),
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
if let Some(points) = copybits_hud_probe_points {
if !points
.iter()
.any(|&(probe_x, probe_y)| dx == probe_x && dy == probe_y)
{
if let (Some(table), Some((row_start, _, snapshot))) =
(&detail_table, &source_snapshot)
{
let offset = src_addr
- src_info.base
- row_start * src_info.row_bytes;
bus.copy_saved_pixel(
dst_addr,
snapshot,
offset as usize,
|index| table[index as usize],
);
} else {
bus.write_byte(dst_addr, dst_pixel);
}
continue;
}
{
let src_rgb = src_clut
.map(|c| c[src_pixel as usize])
.unwrap_or([0, 0, 0]);
let dst_rgb = dst_clut
.map(|c| c[dst_pixel as usize])
.unwrap_or([0, 0, 0]);
eprintln!(
"[COPYBITS-HUD] tick={} dx={} dy={} mode={} src_idx={} src_rgb=({:04X},{:04X},{:04X}) dst_idx={} dst_rgb=({:04X},{:04X},{:04X}) translate={} bg_rgb=({:04X},{:04X},{:04X}) srcBase=${:08X} dstBase=${:08X} srcCTab=${:08X} dstCTab=${:08X} srcSeed={:?} dstSeed={:?}",
self.current_tick(),
dx,
dy,
mode_base,
src_pixel,
src_rgb[0],
src_rgb[1],
src_rgb[2],
dst_pixel,
dst_rgb[0],
dst_rgb[1],
dst_rgb[2],
palette_translation.is_some(),
copy_bg_rgb[0],
copy_bg_rgb[1],
copy_bg_rgb[2],
src_info.base,
dst_info.base,
src_info.ctab_handle,
dst_ctab_handle,
src_ctab_seed,
dst_ctab_seed,
);
}
}
if let (Some(table), Some((row_start, _, snapshot))) =
(&detail_table, &source_snapshot)
{
let offset =
src_addr - src_info.base - row_start * src_info.row_bytes;
bus.copy_saved_pixel(
dst_addr,
snapshot,
offset as usize,
|index| table[index as usize],
);
} else {
bus.write_byte(dst_addr, dst_pixel);
}
}
(src_bits @ (16 | 32), dst_bits @ (16 | 32))
if src_bits != dst_bits =>
{
let src_addr = src_info.base
+ src_y_off * src_info.row_bytes
+ src_x_off * (src_bits / 8);
let dst_addr = dst_info.base
+ dst_y * dst_info.row_bytes
+ dst_x * (dst_bits / 8);
let src_rgb = Self::read_rgbdirect_pixel(
|address| read_src_byte(bus, address),
src_addr,
src_bits,
)
.expect("RGBDirect source depth");
if mode_base == 36 && src_rgb == copy_bg_rgb {
continue;
}
let dst_rgb = Self::read_rgbdirect_pixel(
|address| bus.read_byte(address),
dst_addr,
dst_bits,
)
.expect("RGBDirect destination depth");
let effective_mode = if mode_base == 36 { 0 } else { mode_base };
let Some(rgb) = Self::copy_bits_direct_source_mode_rgb(
src_rgb,
dst_rgb,
effective_mode,
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
if dst_bits == 16 {
let packed = ((rgb[0] >> 11) << 10)
| ((rgb[1] >> 11) << 5)
| (rgb[2] >> 11);
bus.write_word(dst_addr, packed);
} else {
bus.write_long(
dst_addr,
(u32::from(rgb[0] >> 8) << 16)
| (u32::from(rgb[1] >> 8) << 8)
| u32::from(rgb[2] >> 8),
);
}
}
(src_bits, dst_bits)
if src_bits >= 8 && dst_bits >= 8 && src_bits == dst_bits =>
{
let bytes_per_pixel = src_bits / 8;
let src_addr = src_info.base
+ src_y_off * src_info.row_bytes
+ src_x_off * bytes_per_pixel;
let dst_addr = dst_info.base
+ dst_y * dst_info.row_bytes
+ dst_x * bytes_per_pixel;
for byte_index in 0..bytes_per_pixel {
let pixel = read_src_byte(bus, src_addr + byte_index);
bus.write_byte(dst_addr + byte_index, pixel);
}
}
(1, 8) => {
let src_byte_offset =
src_y_off * src_info.row_bytes + (src_x_off / 8);
let src_bit = 7 - (src_x_off % 8);
let src_byte = read_src_byte(bus, src_info.base + src_byte_offset);
let src_pixel = (src_byte & (1 << src_bit)) != 0;
let dst_addr = dst_info.base + dst_y * dst_info.row_bytes + dst_x;
let dst_pixel = bus.read_byte(dst_addr);
let dst_clut = dst_clut.unwrap();
let fg_index = fg_index.unwrap();
let bg_index = bg_index.unwrap();
let new_pixel = match mode_base {
0 => Some(if src_pixel { fg_index } else { bg_index }),
1 => src_pixel.then_some(fg_index),
2 => src_pixel
.then(|| Self::inverted_palette_index(dst_clut, dst_pixel)),
3 => src_pixel.then_some(bg_index),
4 => Some(if src_pixel { bg_index } else { fg_index }),
5 => (!src_pixel).then_some(fg_index),
6 => (!src_pixel)
.then(|| Self::inverted_palette_index(dst_clut, dst_pixel)),
7 => (!src_pixel).then_some(bg_index),
36 => src_pixel.then_some(fg_index),
_ => Some(if src_pixel { fg_index } else { bg_index }),
};
if let Some(pixel) = new_pixel {
bus.write_byte(dst_addr, pixel);
}
}
(8, 1) => {
// 8bpp → 1bpp: convert by testing if the 8bpp pixel is
// "dark" (closer to black than white) across RGBColor's
// unsigned 16-bit component range. In the standard Mac CLUT,
// index 255 = black, index 0 = white.
// Imaging With QuickDraw 1994, pp. 4-31–4-34.
let src_addr =
src_info.base + src_y_off * src_info.row_bytes + src_x_off;
let src_pixel = read_src_byte(bus, src_addr);
let src_is_dark = if let Some(clut) = src_clut {
let [r, g, b] = clut[src_pixel as usize];
let lum = (r as u32 + g as u32 + b as u32) / 3;
lum < 0x8000
} else {
// No CLUT: treat high index as dark (Mac convention)
src_pixel >= 128
};
let dst_byte_offset = dst_y * dst_info.row_bytes + (dst_x / 8);
let dst_bit = 7 - (dst_x % 8);
let dst_addr = dst_info.base + dst_byte_offset;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte & (1 << dst_bit)) != 0;
let new_bit = match mode_base {
0 => src_is_dark,
1 => src_is_dark || dst_pixel,
2 => src_is_dark ^ dst_pixel,
3 => !src_is_dark && dst_pixel,
4 => !src_is_dark,
_ => src_is_dark,
};
if new_bit {
bus.write_byte(dst_addr, dst_byte | (1 << dst_bit));
} else {
bus.write_byte(dst_addr, dst_byte & !(1 << dst_bit));
}
}
(1, 1) => {
// 1bpp CopyBits compress uses OR-merge across
// all src pixels that map to this dst pixel.
// Per IM:V V-65: "When CopyBits scales a
// bitmap, it uses an OR operation: if any
// source pixel that maps to a destination
// pixel is set, the destination pixel is set."
let mut src_pixel = {
let src_byte_offset =
src_y_off * src_info.row_bytes + (src_x_off / 8);
let src_bit = 7 - (src_x_off % 8);
let src_byte =
read_src_byte(bus, src_info.base + src_byte_offset);
(src_byte & (1 << src_bit)) != 0
};
if !no_scaling && !src_pixel {
// For compress cases (src_w > dst_w OR
// src_h > dst_h) OR-merge additional
// src pixels that fall within this dst
// pixel's input range. Only sample if
// we haven't already found a set bit.
let src_x_end_opt = Self::scale_coord(
src_left,
src_right,
dst_left,
dst_right,
dx + 1,
);
let src_y_end_opt = Self::scale_coord(
src_top,
src_bottom,
dst_top,
dst_bottom,
dy + 1,
);
let sx_hi = src_x_end_opt.unwrap_or(i32::from(src_right));
let sy_hi = src_y_end_opt.unwrap_or(i32::from(src_bottom));
'or_scan: for sy in src_y..sy_hi {
if sy < i32::from(src_info.bounds_top)
|| sy >= i32::from(src_info.bounds_bottom)
{
continue;
}
let sy_off = (sy - i32::from(src_info.bounds_top)) as u32;
for sx in src_x..sx_hi {
if sx < i32::from(src_info.bounds_left)
|| sx >= i32::from(src_info.bounds_right)
{
continue;
}
let sx_off =
(sx - i32::from(src_info.bounds_left)) as u32;
let off = sy_off * src_info.row_bytes + (sx_off / 8);
let bit = 7 - (sx_off % 8);
let byte = read_src_byte(bus, src_info.base + off);
if (byte & (1 << bit)) != 0 {
src_pixel = true;
break 'or_scan;
}
}
}
}
let dst_byte_offset = dst_y * dst_info.row_bytes + (dst_x / 8);
let dst_bit = 7 - (dst_x % 8);
let dst_addr = dst_info.base + dst_byte_offset;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte & (1 << dst_bit)) != 0;
let new_bit = match mode_base {
0 => src_pixel,
1 => src_pixel || dst_pixel,
2 => src_pixel ^ dst_pixel,
3 => !src_pixel && dst_pixel,
4 => !src_pixel,
5 => !src_pixel || dst_pixel,
6 => !src_pixel ^ dst_pixel,
7 => src_pixel && dst_pixel,
36 => src_pixel || dst_pixel,
_ => src_pixel,
};
if new_bit {
bus.write_byte(dst_addr, dst_byte | (1 << dst_bit));
} else {
bus.write_byte(dst_addr, dst_byte & !(1 << dst_bit));
}
}
_ => {}
}
}
}
if trace_menu_redraw_enabled() {
for (label, probe_y, probe_x, src_y, src_x, src_pixel, dst_before) in
trace_probes
{
let dst_after = Self::read_bitmap_pixel(bus, &dst_info, probe_y, probe_x);
eprintln!(
"[MENU-REDRAW] CopyBits probe={} srcPt=({}, {}) srcPixel={:?} dstBefore={:?} dstAfter={:?}",
label,
src_y,
src_x,
src_pixel,
dst_before,
dst_after,
);
}
}
if dst_info.base == self.screen_mode.0 {
let mut fields: Vec<(&str, String)> = vec![
("mode", mode_base.to_string()),
("src_width", (src_right - src_left).to_string()),
("src_height", (src_bottom - src_top).to_string()),
("dst_top", dst_top.to_string()),
("dst_left", dst_left.to_string()),
("dst_bottom", dst_bottom.to_string()),
("dst_right", dst_right.to_string()),
];
if self.trace_source().is_some() && dst_info.pixel_size == 8 {
let fp = copybits_dst_fingerprint(
bus, &dst_info, dst_top, dst_left, dst_bottom, dst_right,
);
fields.push(("dst_top1_idx", fp.top[0].0.to_string()));
fields.push(("dst_top1_count", fp.top[0].1.to_string()));
fields.push(("dst_top2_idx", fp.top[1].0.to_string()));
fields.push(("dst_top2_count", fp.top[1].1.to_string()));
fields.push(("dst_top3_idx", fp.top[2].0.to_string()));
fields.push(("dst_top3_count", fp.top[2].1.to_string()));
fields.push(("dst_idx0_count", fp.idx0_count.to_string()));
fields.push(("dst_idx255_count", fp.idx255_count.to_string()));
fields.push(("dst_total", fp.total.to_string()));
}
if let Err(err) = self.record_trace_event(
bus,
trap_pc,
"copybits_screen",
Self::trace_field_map(&fields),
true,
) {
return Some(Err(err));
}
}
if let Some(rect) = screen_copybits_rect {
self.fill_kiosk_letterbox_for_copybits(bus, rect);
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
*self.current_port,
(
clip_t.saturating_sub(dst_info.bounds_top),
clip_l.saturating_sub(dst_info.bounds_left),
clip_b.saturating_sub(dst_info.bounds_top),
clip_r.saturating_sub(dst_info.bounds_left),
),
);
self.refresh_visible_dialog_snapshot_after_bulk_port_draw(
bus,
*self.current_port,
(rect.dst_top, rect.dst_left, rect.dst_bottom, rect.dst_right),
);
}
Ok(())
}
// ========== Pixel Operations ==========
// GetPixel ($A865)
//
// FUNCTION GetPixel(h, v: INTEGER): BOOLEAN;
// Inside Macintosh Volume I, p. I-195.
//
// Per IM:I I-195: "GetPixel looks at the pixel associated
// with the given coordinate point and returns TRUE if it's
// black or FALSE if it's white. The selected pixel is
// immediately below and to the right of the point whose
// coordinates are given in h and v, in the local
// coordinates of the current grafPort. There's no
// guarantee that the specified pixel actually belongs to
// the port, however; it may have been drawn by a port
// overlapping the current one. To see if the point indeed
// belongs to the current port, you could call
// PtInRgn(pt, thePort^.visRgn)."
//
// ## Pascal FUNCTION protocol (stack layout)
//
// Caller pre-allocates a 2-byte BOOLEAN result slot,
// pushes h (2 bytes) then v (2 bytes) right-to-left, then
// emits $A865. The trap pops the 4 argument bytes and
// writes the 2-byte Pascal Boolean (0x0100 = TRUE,
// 0x0000 = FALSE — Mac convention: the high byte holds
// the truth value, low byte is padding) into the now-
// top-of-stack result slot. The C wrapper reads the
// result via the Boolean (1-byte) typedef which sees only
// the high byte (0x01 = TRUE / 0x00 = FALSE).
//
// SP+0 v INTEGER (2 bytes)
// SP+2 h INTEGER (2 bytes)
// SP+4 result BOOLEAN slot (2 bytes; trap writes here)
//
// Net externally-observed SP delta across the FUNCTION
// wrapper is zero (4 bytes pushed before, 2 bytes of
// result reserved before, 2 bytes of result popped after).
//
// ## HLE visRgn fast-path (Systemless-specific tightening)
//
// Systemless's HLE additionally short-circuits to FALSE when
// the (h, v) point is outside the port's visRgn rectangle
// before dereferencing the framebuffer. This is a
// narrowing of IM:I I-195's looser contract ("no guarantee
// that the specified pixel actually belongs to the port"),
// intended to keep games that probe pixels deep inside the
// menu bar or window-chrome regions from observing stale
// adjacent-port pixels via the offscreen canvas. Real Mac
// OS QuickDraw delegates this check to the caller via
// PtInRgn; both behaviours coincide for any pixel inside
// the port's visRgn (the common case).
(true, 0x065) => {
let sp = cpu.read_reg(Register::A7);
let v = bus.read_word(sp) as i16;
let h = bus.read_word(sp + 2) as i16;
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
// Per Inside Macintosh, GetPixel returns TRUE only if the pixel
// is within the port's visRgn. Pixels outside (e.g. in the menu
// bar or title bar chrome) must return FALSE.
let vis_rgn_handle = bus.read_long(port + 24);
let in_vis_rgn = if vis_rgn_handle != 0 {
let vis_rgn_ptr = bus.read_long(vis_rgn_handle);
if vis_rgn_ptr != 0 {
let vt = bus.read_word(vis_rgn_ptr + 2) as i16;
let vl = bus.read_word(vis_rgn_ptr + 4) as i16;
let vb = bus.read_word(vis_rgn_ptr + 6) as i16;
let vr = bus.read_word(vis_rgn_ptr + 8) as i16;
v >= vt && v < vb && h >= vl && h < vr
} else {
true
}
} else {
true
};
if !in_vis_rgn {
bus.write_word(sp + 4, 0);
cpu.write_reg(Register::A7, sp + 4);
return Some(Ok(()));
}
// Detect CGrafPort vs GrafPort (same logic as draw_generic_shape)
let port_version = bus.read_word(port + 6);
let is_color = (port_version & 0xC000) != 0;
let (base_addr, row_bytes, pixel_size, bounds_top, bounds_left) = if is_color {
let pm_handle = bus.read_long(port + 2);
let pm_ptr = if pm_handle != 0 {
bus.read_long(pm_handle)
} else {
0
};
if pm_ptr == 0 {
bus.write_word(sp + 4, 0);
cpu.write_reg(Register::A7, sp + 4);
return Some(Ok(()));
}
let base = Self::offscreen_pixmap_base_ptr(bus, pm_ptr);
let rb = (bus.read_word(pm_ptr + 4) & 0x3FFF) as u32;
let top = bus.read_word(pm_ptr + 6) as i16;
let left = bus.read_word(pm_ptr + 8) as i16;
let ps = bus.read_word(pm_ptr + 32);
(base, rb, ps, top, left)
} else {
let base = bus.read_long(port + 2);
let rb = (bus.read_word(port + 6) & 0x3FFF) as u32;
let top = bus.read_word(port + 8) as i16;
let left = bus.read_word(port + 10) as i16;
(base, rb, 1u16, top, left)
};
let dy = (v - bounds_top) as u32;
let dx = (h - bounds_left) as u32;
let pixel_set = if pixel_size == 8 {
let byte_offset = dy * row_bytes + dx;
bus.read_byte(base_addr + byte_offset) != 0
} else if pixel_size >= 16 {
let bpp = pixel_size as u32 / 8;
let byte_offset = dy * row_bytes + dx * bpp;
bus.read_byte(base_addr + byte_offset) != 0
} else {
// 1bpp
let byte_offset = dy * row_bytes + (dx / 8);
let bit = 7 - (dx % 8);
let byte = bus.read_byte(base_addr + byte_offset);
(byte & (1 << bit)) != 0
};
bus.write_word(sp + 4, if pixel_set { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Color Manager ==========
// ForeColor ($A862)
// ForeColor ($A862): Converts legacy QD color constant to RGB and sets fg_color; per IM:I I-173
(true, 0x062) => {
let sp = cpu.read_reg(Register::A7);
let color = bus.read_long(sp);
self.fg_color = Self::legacy_qd_color_to_rgb(color);
self.pm_fg_color = None;
self.sync_current_port_draw_state(bus);
self.resolve_current_port_color_pixels(bus, true, false, false);
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] ForeColor port=${:08X} color=${:08X} rgb=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
color,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.current_tick(),
);
}
if trace_dialog_text_enabled() {
eprintln!(
"[DIALOG-TEXT] ForeColor current_port=${:08X} color=${:08X} rgb=({:04X},{:04X},{:04X})",
*self.current_port,
color,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// BackColor ($A863)
// BackColor ($A863): Converts legacy QD color constant to RGB and sets bg_color; per IM:I I-173
(true, 0x063) => {
let sp = cpu.read_reg(Register::A7);
let color = bus.read_long(sp);
self.bg_color = Self::legacy_qd_color_to_rgb(color);
self.pm_bg_color = None;
self.sync_current_port_draw_state(bus);
self.resolve_current_port_color_pixels(bus, false, true, false);
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] BackColor port=${:08X} color=${:08X} rgb=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
color,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.current_tick()
);
}
if trace_dialog_text_enabled() {
eprintln!(
"[DIALOG-TEXT] BackColor current_port=${:08X} color=${:08X} rgb=({:04X},{:04X},{:04X})",
*self.current_port,
color,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// RGBForeColor ($AA14)
// RGBForeColor ($AA14): Sets fg_color (R, G, B)
(true, 0x214) => {
let sp = cpu.read_reg(Register::A7);
let color_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = bus.read_word(color_ptr);
let g = bus.read_word(color_ptr + 2);
let b = bus.read_word(color_ptr + 4);
self.fg_color = (r, g, b);
self.pm_fg_color = None;
self.sync_current_port_draw_state(bus);
self.resolve_current_port_color_pixels(bus, true, false, true);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
Self::push_pict_word(commands, 0x001A); // RGBFgCol
for component in [r, g, b] {
Self::push_pict_word(commands, component);
}
}
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] RGBForeColor port=${:08X} ptr=${:08X} rgb=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
color_ptr,
r, g, b,
self.current_tick(),
);
}
Ok(())
}
// RGBBackColor ($AA15)
// RGBBackColor ($AA15): Sets bg_color (R, G, B)
(true, 0x215) => {
let sp = cpu.read_reg(Register::A7);
let color_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let r = bus.read_word(color_ptr);
let g = bus.read_word(color_ptr + 2);
let b = bus.read_word(color_ptr + 4);
self.bg_color = (r, g, b);
self.pm_bg_color = None;
self.sync_current_port_draw_state(bus);
self.resolve_current_port_color_pixels(bus, false, true, true);
if let Some((_, _, _, _, _, commands)) = self.recording_picture.as_mut() {
Self::push_pict_word(commands, 0x001B); // RGBBkCol
for component in [r, g, b] {
Self::push_pict_word(commands, component);
}
}
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] RGBBackColor port=${:08X} ptr=${:08X} rgb=({:04X},{:04X},{:04X}) tick={}",
*self.current_port, color_ptr, r, g, b, self.current_tick()
);
}
Ok(())
}
// GetPixPat ($AA0C)
// FUNCTION GetPixPat(patID: INTEGER): PixPatHandle;
// Inside Macintosh Volume V (1986), p. V-73
//
// Per IM:V V-73 verbatim: "The GetPixPat call creates a
// new pixPat data structure, and then uses the
// information in the resource of type 'ppat' and the
// specified ID to initialize the pixPat. The 'ppat'
// resource format is described in the section 'Color
// QuickDraw Resource Formats'. If the resource with the
// specified ID is not found, then this routine returns
// a NIL handle."
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(PixPatHandle) GetPixPat(short patID)
// ONEWORDINLINE(0xAA0C);
//
// Tool-bit Pascal FUNCTION ABI: caller pre-pushes a
// 4-byte PixPatHandle result slot, then pushes the
// 2-byte patID INTEGER. Trap pops the 2-byte argument
// and writes the handle to the 4-byte result slot at
// the post-pop SP (= pre-call SP + 2). Caller pops the
// result slot after the trap returns. Net A7 effect
// across the C-level call is zero.
//
// ## Behaviour shared with BasiliskII System 7.5.3 ROM
//
// (1) Pascal FUNCTION calling convention — A7 net-
// balanced across the C-level call (caller pre-
// push of 4-byte result slot + 2-byte arg + trap-
// side 2-byte arg pop + result-slot write + caller
// post-pop balance).
// (2) Miss-returns-NIL — fictional patID outside the
// Apple-reserved 'ppat' range returns NIL on both
// BasiliskII System 7.5.3 ROM Color QuickDraw and
// Systemless HLE per IM:V V-73 documented behaviour.
//
// ## Behaviour that diverges from BasiliskII
//
// On the present-resource path BasiliskII allocates a
// fresh 28-byte PixPat record initialised from the 'ppat'
// resource bytes per IM:V V-46 layout. Systemless HLE
// returns the master pointer to the raw 'ppat' resource
// bytes wrapped in a handle via find_resource_any +
// get_or_create_resource_handle. Apps that call
// PenPixPat $AA0A / BackPixPat $AA0B / FillCRect $AA0E
// with the handle get the resource bytes directly
// (Systemless's PenPixPat / BackPixPat / FillCRect implems
// inspect the PixPat record's pat1Data field at offset
// +20 for the 8-byte pattern data — this works for ppat
// resources whose 1-bit pattern data is at the
// documented IM:V V-46 layout offset).
//
// ## Status: Stub → Partial promotion
//
// Was previously a Stub returning NIL unconditionally.
// Promoted to Partial during the stub-with-substantive-body
// cleanup. New behavior matches
// the prior $A9B9 GetCursor / $A9B8 GetPattern / $A9BB
// GetIcon / $A9BC GetPicture / $AA1F GetCIcon Stub→Partial
// promotion pattern: route through find_resource_any +
// get_or_create_resource_handle for handle stability
// across repeated calls (apps cache the handle and reuse
// it).
//
// Contract-test coverage in this file (mod tests):
// getpixpat_pascal_function_preserves_stack_across_five_missing_calls
(true, 0x20C) => {
let sp = cpu.read_reg(Register::A7);
let pat_id = bus.read_word(sp) as i16;
let handle = match self.find_or_load_resource_any(bus, *b"ppat", pat_id) {
Some((_, data_ptr)) => {
self.get_or_create_resource_handle(bus, *b"ppat", pat_id, data_ptr)
}
None => 0,
};
bus.write_long(sp + 2, handle);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// ProtectEntry ($AA3D)
// PROCEDURE ProtectEntry (index: INTEGER; protect: BOOLEAN);
// Inside Macintosh Volume V, V-143
//
// Stack (Pascal): SP+0=protect(BOOLEAN, 16-bit), SP+2=index(INTEGER).
// Pops 4. BOOLEAN: high byte != 0 means TRUE.
(true, 0x23D) => {
let sp = cpu.read_reg(Register::A7);
let protect = (bus.read_word(sp) >> 8) != 0;
let index = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
if (0..256).contains(&(index as i32)) {
self.clut_protected[index as usize] = protect;
}
Ok(())
}
// ReserveEntry ($AA3E)
// PROCEDURE ReserveEntry (index: INTEGER; reserve: BOOLEAN);
// Inside Macintosh Volume V, V-143
//
// Stack (Pascal): SP+0=reserve(BOOLEAN, 16-bit), SP+2=index(INTEGER).
// Pops 4.
(true, 0x23E) => {
let sp = cpu.read_reg(Register::A7);
let reserve = (bus.read_word(sp) >> 8) != 0;
let index = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + 4);
if (0..256).contains(&(index as i32)) {
self.clut_reserved[index as usize] = reserve;
}
Ok(())
}
// ========== Color Port Stubs ==========
// OpenCPort ($AA00)
// Allocates space for and initializes a color graphics port.
// PROCEDURE OpenCPort (port: CGrafPtr);
// Imaging With QuickDraw 1994, pp. 4-64 to 4-65; IM:V 1986 p. V-67
// OpenCPort ($AA00): allocates CGrafPort-owned storage, then
// calls InitCPort to initialize defaults.
(true, 0x200) => {
let sp = cpu.read_reg(Register::A7);
let port_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
// OpenCPort allocates storage first, then initializes fields.
self.allocate_cport_storage(port_ptr, bus);
let _ = self.init_cport(port_ptr, bus, true);
self.cport_ports.insert(port_ptr);
self.cport_original_pixmaps
.insert(port_ptr, bus.read_long(port_ptr + 2));
// Set as current port on the active GDevice that seeded the
// port's PixMap. Offscreen code can select a freshly-created
// GDevice before OpenCPort.
let gd_handle = self.active_gdevice_or_main(bus);
self.set_current_port_state(bus, cpu, port_ptr, Some(gd_handle));
if trace_dialog_ports_enabled() {
eprintln!(
"[DIALOG-PORT] OpenCPort port=${:08X} gdh=${:08X}",
port_ptr, gd_handle
);
}
Ok(())
}
// InitCPort ($AA01)
// Initializes an existing color graphics port.
// PROCEDURE InitCPort (port: CGrafPtr);
// Imaging With QuickDraw 1994, p. 4-66; IM:V 1986 p. V-67
// InitCPort ($AA01): does not allocate; initializes an existing
// CGrafPort and returns without action when passed a non-CGrafPort.
(true, 0x201) => {
let sp = cpu.read_reg(Register::A7);
let port_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.init_cport(port_ptr, bus, false) {
self.cport_ports.insert(port_ptr);
self.cport_original_pixmaps
.insert(port_ptr, bus.read_long(port_ptr + 2));
}
if trace_dialog_ports_enabled() {
eprintln!("[DIALOG-PORT] InitCPort port=${:08X}", port_ptr);
}
Ok(())
}
// NewPixMap ($AA03)
// Allocates an initialized PixMap with its own color-table handle.
// FUNCTION NewPixMap: PixMapHandle;
// Imaging With QuickDraw (1994), p. 4-86: copy every field from
// the current device PixMap except its color table.
(true, 0x203) => {
let sp = cpu.read_reg(Register::A7);
let handle = self.allocate_new_pixmap(bus);
bus.write_long(sp, handle);
Ok(())
}
// SetCPortPix ($AA06)
// Sets the portPixMap field of the current CGrafPort.
// PROCEDURE SetCPortPix (pm: PixMapHandle);
// Inside Macintosh Volume V, V-74
// SetCPortPix ($AA06): Writes PixMap handle into port
(true, 0x206) => {
let sp = cpu.read_reg(Register::A7);
let pm_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
if global_ptr == 0 {
return Some(Ok(()));
}
let port = bus.read_long(global_ptr);
if port == 0 {
return Some(Ok(()));
}
bus.write_long(port + 2, pm_handle);
self.cache_portbits_pixmap_handle(bus, port + 2, pm_handle);
// If a seeded title palette is active and the newly attached
// pixmap still carries a canonical ctab, overwrite it with
// the seeded palette so offscreen composition uses the
// correct logical palette.
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 && bus.read_word(pm_ptr + 32) == 8 {
let ctab_handle = bus.read_long(pm_ptr + 42);
let gd_handle = self.ensure_main_gdevice(bus);
if let Some(clut) =
self.active_seeded_screen_clut_for_offscreen_clone(gd_handle, 0)
{
let current_clut = self.read_ctab_handle_clut(bus, ctab_handle);
if Self::uses_canonical_system_8bpp_clut(¤t_clut)
|| Self::uses_scaled_canonical_system_8bpp_clut(¤t_clut)
{
let ctab_ptr = if ctab_handle != 0 {
bus.read_long(ctab_handle)
} else {
0
};
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let _ = self.overwrite_color_table_handle_with_clut(
bus,
ctab_handle,
&clut,
ct_flags,
);
}
}
}
}
Ok(())
}
// MakeRGBPat ($AA0D)
// PROCEDURE MakeRGBPat (ppat: PixPatHandle; myColor: RGBColor);
// Inside Macintosh Volume V (1986), p. V-73 (Color QuickDraw —
// Operations on Pixel Patterns — MakeRGBPat).
//
// Per IM:V V-73 verbatim: "The MakeRGBPat procedure is a new
// call which generates a pixPat that approximates the
// specified color when drawn. [...] For an RGB pattern, the
// patMap^^.bounds always contains (0, 0, 8, 8), and the
// patMap^^.rowBytes equals 2. [...] When MakeRGBPat creates
// a color table, it only fills in the last colorSpec field:
// the other colorSpec values are computed at the time the
// drawing actually takes place, using the current pixel
// depth for the system."
//
// The MPW Universal Headers Quickdraw.h declaration is:
// EXTERN_API(void) MakeRGBPat(PixPatHandle pp,
// const RGBColor *myColor)
// ONEWORDINLINE(0xAA0D);
//
// Tool-bit Pascal PROCEDURE ABI: caller pushes 8 bytes
// (4-byte PixPatHandle + 4-byte RGBColor pointer; RGBColor
// is 6 bytes so it is passed by-ref per MPW Pascal calling
// convention). Trap pops 8 bytes. No FUNCTION result slot.
//
// Behaviour shared with BasiliskII:
// The documented Tool-bit Pascal PROCEDURE pop-8 calling
// convention itself — A7 unchanged across the call after
// the 8-byte arg frame is consumed.
//
// Systemless retains the requested source RGB by PixPatHandle.
// FillCRect resolves it against the destination depth at draw
// time, mirroring the ROM's depth-specific expansion without
// baking the current screen CLUT into the pattern.
//
// Contract-test coverage in this file (mod tests):
// makergbpat_pascal_procedure_preserves_stack_across_five_calls
(true, 0x20D) => {
let sp = cpu.read_reg(Register::A7);
// Pascal argument order places the second argument at SP+0.
let color_ptr = bus.read_long(sp);
let pp_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if pp_handle != 0 && bus.read_long(pp_handle) != 0 && color_ptr != 0 {
let rgb = (
bus.read_word(color_ptr),
bus.read_word(color_ptr + 2),
bus.read_word(color_ptr + 4),
);
self.ensure_makergbpat_backing(bus, pp_handle, rgb);
self.makergbpat_colors.insert(pp_handle, rgb);
}
Ok(())
}
// InitPalettes ($AA90): establish the application's default palette.
// Advanced Color Imaging, "Designating a Default Palette for Your Application".
// PROCEDURE InitPalettes; no stack parameters or result.
(true, 0x290) => {
self.initialize_application_palette(bus);
Ok(())
}
// NewPalette ($AA91)
// Allocates a palette from a color table or fills it with black.
// FUNCTION NewPalette(entries: Integer; srcColors: CTabHandle; srcUsage, srcTolerance: Integer): PaletteHandle;
// Inside Macintosh Volume VI, 20-19
// NewPalette ($AA91): Allocates palette from CTab per IM:VI 20-19
(true, 0x291) => {
let sp = cpu.read_reg(Register::A7);
let src_tolerance = bus.read_word(sp) as i16;
let src_usage = bus.read_word(sp + 2) as i16;
let src_colors = bus.read_long(sp + 4);
let entries = bus.read_word(sp + 8) as i16;
if trace_palette_enabled() {
eprintln!(
"[PALETTE] NewPalette tick={} entries={} src_colors=${:08X} usage={} tolerance={}",
self.current_tick(), entries, src_colors, src_usage, src_tolerance
);
}
let palette = self.create_palette_from_ctab(
bus,
entries as u16,
src_colors,
src_usage,
src_tolerance,
);
bus.write_long(sp + 10, palette);
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// GetNewPalette ($AA92)
// Returns a copy of a 'pltt' resource as a PaletteHandle.
// FUNCTION GetNewPalette(paletteID: Integer): PaletteHandle;
// Inside Macintosh Volume VI, 20-19
// GetNewPalette ($AA92): Copies 'pltt' resource as PaletteHandle per IM:VI 20-19
(true, 0x292) => {
let sp = cpu.read_reg(Register::A7);
let palette_id = bus.read_word(sp) as i16;
let palette = self.copy_palette_resource_exact(bus, palette_id);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] GetNewPalette id={} current_port=${:08X} -> ${:08X}",
palette_id, *self.current_port, palette
);
}
bus.write_long(sp + 2, palette);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// DisposePalette ($AA93)
// Per IM:V V-180: "DisposePalette disposes of a Palette
// object. If the palette has any entries allocated for
// animation on any display device, these entries are
// relinquished prior to deallocation of the object."
// PROCEDURE DisposePalette(srcPalette: PaletteHandle);
// Inside Macintosh Volume V, V-180
// Inside Macintosh Volume VI, 20-20
//
// Stack: SP+0 srcPalette PaletteHandle (4 bytes). Pop 4.
// No result (PROCEDURE).
//
// Trap-doc Notes column was previously mislabeled
// "ScriptUtil | Stub (no-op) | Pops 2 bytes" — that
// mistake collapsed THREE distinct facts into wrong
// values: (a) trap word $AA93 is DisposePalette per
// IM:V V-180 + IM:V V-291 master trap dispatch table
// ($AA93 row) + IM:VI Table C-1 ($AA93 row), NOT
// ScriptUtil — ScriptUtil is at $A8B5 per IM:VI Table
// C-1 ($A8B5 _ScriptUtil row). (b) The impl below has
// been substantive (full palette-handle disposal:
// free guest block, drop palette_updates entry, drop
// window_palettes refs) for many iterations — same
// Stub-mislabel pattern as PlotIcon ($A94B) /
// UpdtControl ($A953) / Draw1Control ($A96D) / Get/
// SetItemCmd ($A84E/F) surfaced during status review.
// (c) The pop count is 4 (PaletteHandle is 4 bytes)
// not 2 — the typo in the prior Notes would not have
// caused real-Mac stack corruption since the impl
// popped 4 correctly, but documentation readers
// grouping by manager would have categorized this as
// Resource Mgr instead of Palette Mgr.
//
// Status promoted Stub (no-op) → Partial because the
// impl frees the guest block + drops palette tracking
// state but does NOT (per IM:V V-180) "relinquish
// animation entries on display devices" — Systemless
// doesn't model per-CLUT-device animation entry
// allocation (single GDevice with no AnimateEntry
// $AA99 / AnimatePalette $AA9A side-effect tracking),
// so the animation-relinquish path is unreachable.
// Future iteration that wires up Palette Mgr animation
// semantics could promote to Complete after
// implementing the relinquish path.
//
// DisposePalette ($AA93): Pops 4 bytes (PaletteHandle) per IM:V V-180 + IM:V V-291 master trap dispatch table + IM:VI Table C-1 PROCEDURE sig; frees guest palette block + drops palette_updates entry + drops window_palettes refs; does NOT model per-CLUT-device animation-entry relinquish path per IM:V V-180 since Systemless has no AnimateEntry $AA99 / AnimatePalette $AA9A side-effect tracking. Was previously mis-labeled as "ScriptUtil | Stub (no-op) | Pops 2 bytes" — typo in trap-doc Notes only; impl was always correct. Same Stub-mislabel-with-substantive-body status issue as PlotIcon $A94B / UpdtControl $A953 / Draw1Control $A96D / SetItemCmd $A84F surfaced during status review.
(true, 0x293) => {
let sp = cpu.read_reg(Register::A7);
let palette = bus.read_long(sp);
if palette != 0 {
let palette_ptr = Self::palette_ptr(bus, palette);
self.clear_palette_tracking(palette);
if palette_ptr != 0 {
bus.free(palette_ptr);
}
bus.free(palette);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ActivatePalette ($AA94)
// Applies the front window's palette to the active device.
// PROCEDURE ActivatePalette(srcWindow: WindowPtr);
// Inside Macintosh Volume VI, 20-20
// ActivatePalette ($AA94): Applies the window's palette to the active GDevice via activate_palette_for_window per IM:VI 20-20
(true, 0x294) => {
let sp = cpu.read_reg(Register::A7);
let window = bus.read_long(sp);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] ActivatePalette(trap) tick={} window=${:08X}",
self.current_tick(), window
);
}
self.activate_associated_palette_for_window(bus, window);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// NSetPalette ($AA95)
// Associates a palette with a window and records update flags.
// PROCEDURE NSetPalette(dstWindow: WindowPtr; srcPalette: PaletteHandle; nUpdates: Integer);
// Inside Macintosh Volume VI, 20-21
// NSetPalette ($AA95): Associates a PaletteHandle with the window and reactivates per IM:VI 20-21.
// Nil windows are a no-op; the trap should not create a key-0
// association or touch device state when dstWindow is NIL.
(true, 0x295) => {
let sp = cpu.read_reg(Register::A7);
let raw_updates = bus.read_word(sp) as i16;
// SetPalette and NSetPalette share $AA95. A Pascal Boolean is
// pushed as a byte in a word-aligned stack slot, leaving the
// other byte unspecified; NSetPalette passes a full Integer.
// Inside Macintosh Volume VI (1991), pp. 20-20–20-21.
let updates = match raw_updates {
PM_NO_UPDATES | PM_BK_UPDATES | PM_FG_UPDATES | PM_ALL_UPDATES => raw_updates,
_ => match bus.read_byte(sp) {
0 => PM_NO_UPDATES,
1 => PM_ALL_UPDATES,
_ => raw_updates,
},
};
let palette = bus.read_long(sp + 2);
let window = bus.read_long(sp + 6);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] NSetPalette window=${:08X} palette=${:08X} updates=${:04X}",
window, palette, updates as u16
);
}
if window == 0 {
cpu.write_reg(Register::A7, sp + 10);
return Some(Ok(()));
}
self.set_window_palette_association(window, palette, updates);
if window == DEFAULT_PALETTE_WINDOW {
// A dstWindow of (WindowPtr)-1 does not name a window: it
// addresses the default palette, the colour environment
// used when no window supplies one. There is no window
// whose activation could later apply it, so it takes
// effect on the device now. Myst Preview's HyperTint XCMD
// sets the screen palette exactly this way and then draws
// its colour layer before any ActivatePalette; matching
// the drawing against a stale device table collapsed the
// island's 254 colours down to 40.
self.apply_palette_to_active_device(
bus,
window,
palette,
" default",
"nsetpalette_default_palette",
);
} else {
self.activate_associated_palette_for_window(bus, window);
}
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// GetPalette ($AA96)
// Returns the palette associated with a window.
// FUNCTION GetPalette(srcWindow: WindowPtr): PaletteHandle;
// Inside Macintosh Volume VI, 20-20
// GetPalette ($AA96): Returns the PaletteHandle associated with srcWindow via exact lookup per IM:VI 20-20
(true, 0x296) => {
let sp = cpu.read_reg(Register::A7);
let window = bus.read_long(sp);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] GetPalette(trap) tick={} window=${:08X} -> handle=${:08X}",
self.current_tick(),
window,
self.window_palette_handle_exact(window)
);
}
bus.write_long(sp + 4, self.window_palette_handle_exact(window));
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// PmForeColor ($AA97)
// Sets the foreground color from the current window's palette.
// PROCEDURE PmForeColor(dstEntry: Integer);
// Inside Macintosh Volume V, V-163
// PmForeColor ($AA97): Sets foreground color from window's palette entry; honours pmExplicit (uses device CLUT) vs tolerant (uses palette RGB) per IM:V V-163
(true, 0x297) => {
let sp = cpu.read_reg(Register::A7);
let entry = bus.read_word(sp) as i16;
if let Some((palette, rgb, usage)) =
self.palette_entry_rgb_for_current_window(bus, entry)
{
let explicit = (usage & PM_EXPLICIT) != 0;
self.fg_color = if explicit {
let index = (entry as usize) & 0xFF;
let [r, g, b] = self.device_clut[index];
(r, g, b)
} else {
(rgb[0], rgb[1], rgb[2])
};
self.pm_fg_color = Some((palette, entry));
self.sync_current_port_draw_state(bus);
if (explicit || (usage & PM_ANIMATED) != 0)
&& *self.current_port != 0
&& (bus.read_word(*self.current_port + 6) & 0xC000) == 0xC000
{
// Explicit entries name a device index directly.
// Animated entries select the distinct device index
// reserved for that palette entry; Systemless' single
// GDevice allocation maps it to the same index.
bus.write_long(*self.current_port + 80, (entry as u16 & 0x00FF) as u32);
*self
.resolved_port_color_fields
.entry(*self.current_port)
.or_default() |= 0x01;
} else {
self.resolve_current_port_color_pixels(bus, true, false, false);
}
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] PmForeColor port=${:08X} entry={} rgb=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
entry,
self.fg_color.0,
self.fg_color.1,
self.fg_color.2,
self.current_tick(),
);
}
}
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// PmBackColor ($AA98)
// Sets the background color from the current window's palette.
// PROCEDURE PmBackColor(dstEntry: Integer);
// Inside Macintosh Volume V, V-163
// PmBackColor ($AA98): Sets background color from window's palette entry; honours pmExplicit vs tolerant usage per IM:V V-163
(true, 0x298) => {
let sp = cpu.read_reg(Register::A7);
let entry = bus.read_word(sp) as i16;
if let Some((palette, rgb, usage)) =
self.palette_entry_rgb_for_current_window(bus, entry)
{
let explicit = (usage & PM_EXPLICIT) != 0;
self.bg_color = if explicit {
let index = (entry as usize) & 0xFF;
let [r, g, b] = self.device_clut[index];
(r, g, b)
} else {
(rgb[0], rgb[1], rgb[2])
};
self.pm_bg_color = Some((palette, entry));
self.sync_current_port_draw_state(bus);
if (explicit || (usage & PM_ANIMATED) != 0)
&& *self.current_port != 0
&& (bus.read_word(*self.current_port + 6) & 0xC000) == 0xC000
{
bus.write_long(*self.current_port + 84, (entry as u16 & 0x00FF) as u32);
*self
.resolved_port_color_fields
.entry(*self.current_port)
.or_default() |= 0x02;
} else {
self.resolve_current_port_color_pixels(bus, false, true, false);
}
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] PmBackColor port=${:08X} entry={} rgb=({:04X},{:04X},{:04X}) tick={}",
*self.current_port,
entry,
self.bg_color.0,
self.bg_color.1,
self.bg_color.2,
self.current_tick(),
);
}
}
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// AnimatePalette ($AA9A)
// Copies a range of colors from a color table into a window palette.
// PROCEDURE AnimatePalette(dstWindow: WindowPtr; srcCTab: CTabHandle; srcIndex, dstEntry, dstLength: Integer);
// Inside Macintosh Volume VI, 20-22
// AnimatePalette ($AA9A): Copies dstLength entries from CTab[srcIndex..] into window palette[dstEntry..]; reactivates after per IM:VI 20-22. Negative span inputs are treated as a no-op.
(true, 0x29A) => {
let sp = cpu.read_reg(Register::A7);
let dst_length = bus.read_word(sp);
let dst_entry = bus.read_word(sp + 2);
let src_index = bus.read_word(sp + 4);
let src_ctab = bus.read_long(sp + 6);
let window = bus.read_long(sp + 10);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] AnimatePalette window=${:08X} srcCTab=${:08X} srcIndex={} dstEntry={} dstLength={}",
window, src_ctab, src_index, dst_entry, dst_length
);
}
// Guard the signed Pascal INTEGER span before the unsigned loop
// logic can treat a negative value as a huge copy count.
if (dst_length as i16) < 0 || (dst_entry as i16) < 0 || (src_index as i16) < 0 {
cpu.write_reg(Register::A7, sp + 14);
return Some(Ok(()));
}
let palette = self.window_palette_handle(window);
let palette_ptr = Self::palette_ptr(bus, palette);
let src_ctab_ptr = if src_ctab != 0 {
bus.read_long(src_ctab)
} else {
0
};
if palette_ptr != 0 && src_ctab_ptr != 0 {
let max_src = u32::from(bus.read_word(src_ctab_ptr + 6)) + 1;
let max_dst = u32::from(Self::palette_entry_count(bus, palette));
for offset in 0..u32::from(dst_length) {
let src = u32::from(src_index) + offset;
let dst = u32::from(dst_entry) + offset;
if src >= max_src || dst >= max_dst {
break;
}
let src_entry = src_ctab_ptr + 8 + src * 8;
let rgb = [
bus.read_word(src_entry + 2),
bus.read_word(src_entry + 4),
bus.read_word(src_entry + 6),
];
let (_, usage, tolerance) = Self::read_palette_color_info(
bus, palette, dst as u16,
)
.unwrap_or(([0, 0, 0], PM_TOLERANT, 0));
Self::write_palette_color_info(
bus,
palette_ptr,
dst,
rgb,
usage,
tolerance,
);
self.install_animated_palette_entry_on_active_device(
bus, window, palette, dst, rgb, usage,
);
}
self.activate_associated_palette_for_window(bus, window);
}
cpu.write_reg(Register::A7, sp + 14);
Ok(())
}
// GetEntryColor ($AA9B)
// Returns the RGB value of a palette entry.
//
// MPW Universal Headers `Palettes.h` declaration:
// EXTERN_API(void) GetEntryColor(PaletteHandle srcPalette,
// short srcEntry, RGBColor *dstRGB) ONEWORDINLINE(0xAA9B);
// PROCEDURE GetEntryColor(srcPalette: PaletteHandle; srcEntry: Integer; VAR dstRGB: RGBColor);
// Inside Macintosh Volume VI, 20-24
// GetEntryColor ($AA9B): Reads RGB at palette[srcEntry] into dstRGB VAR per IM:VI 20-24
(true, 0x29B) => {
let sp = cpu.read_reg(Register::A7);
let rgb_ptr = bus.read_long(sp);
let entry = bus.read_word(sp + 4) as i16;
let palette = bus.read_long(sp + 6);
if palette != 0 && entry >= 0 {
if let Some((rgb, _, _)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
bus.write_word(rgb_ptr, rgb[0]);
bus.write_word(rgb_ptr + 2, rgb[1]);
bus.write_word(rgb_ptr + 4, rgb[2]);
}
}
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// SetEntryColor ($AA9C)
// Updates the RGB value of a palette entry.
// PROCEDURE SetEntryColor(dstPalette: PaletteHandle; dstEntry: Integer; srcRGB: RGBColor);
// Inside Macintosh Volume VI, 20-24
// SetEntryColor ($AA9C): Writes srcRGB into palette[dstEntry] preserving usage/tolerance per IM:VI 20-24
(true, 0x29C) => {
let sp = cpu.read_reg(Register::A7);
let entry = bus.read_word(sp + 4) as i16;
let palette = bus.read_long(sp + 6);
let palette_ptr = Self::palette_ptr(bus, palette);
if palette_ptr != 0 && entry >= 0 {
if let Some((_, usage, tolerance)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
// Only touch the source RGB pointer once the palette
// entry has already been validated. The out-of-range
// path is a no-op and should not depend on the caller's
// RGB pointer being readable.
let rgb_ptr = bus.read_long(sp);
let rgb = [
bus.read_word(rgb_ptr),
bus.read_word(rgb_ptr + 2),
bus.read_word(rgb_ptr + 4),
];
Self::write_palette_color_info(
bus,
palette_ptr,
entry as u32,
rgb,
usage,
tolerance,
);
}
}
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// GetEntryUsage ($AA9D)
// Returns the usage and tolerance values of a palette entry.
//
// MPW Universal Headers `Palettes.h` declaration:
// EXTERN_API(void) GetEntryUsage(PaletteHandle srcPalette,
// short srcEntry, short* dstUsage,
// short* dstTolerance) ONEWORDINLINE(0xAA9D);
// PROCEDURE GetEntryUsage(srcPalette: PaletteHandle; srcEntry: Integer; VAR dstUsage, dstTolerance: Integer);
// Inside Macintosh Volume VI, 20-25
// GetEntryUsage ($AA9D): Reads usage + tolerance for palette[srcEntry] into VARs per IM:VI 20-25
(true, 0x29D) => {
let sp = cpu.read_reg(Register::A7);
let tolerance_ptr = bus.read_long(sp);
let usage_ptr = bus.read_long(sp + 4);
let entry = bus.read_word(sp + 8) as i16;
let palette = bus.read_long(sp + 10);
if let Some((_, usage, tolerance)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
bus.write_word(usage_ptr, usage as u16);
bus.write_word(tolerance_ptr, tolerance as u16);
}
cpu.write_reg(Register::A7, sp + 14);
Ok(())
}
// SetEntryUsage ($AA9E)
// Updates the usage and tolerance values of a palette entry.
//
// MPW Universal Headers `Palettes.h` declaration:
// EXTERN_API(void) SetEntryUsage(PaletteHandle dstPalette,
// short dstEntry, short srcUsage,
// short srcTolerance) ONEWORDINLINE(0xAA9E);
// PROCEDURE SetEntryUsage(dstPalette: PaletteHandle; dstEntry: Integer; srcUsage, srcTolerance: Integer);
// Inside Macintosh Volume VI, 20-25
// SetEntryUsage ($AA9E): Writes usage + tolerance for palette[dstEntry] preserving RGB. Inside Macintosh V/VI documents -1 as a no-change sentinel, but BasiliskII System 7.5.3 writes the pair verbatim; Systemless matches BasiliskII here.
(true, 0x29E) => {
let sp = cpu.read_reg(Register::A7);
let src_tolerance = bus.read_word(sp) as i16;
let src_usage = bus.read_word(sp + 2) as i16;
let entry = bus.read_word(sp + 4) as i16;
let palette = bus.read_long(sp + 6);
let palette_ptr = Self::palette_ptr(bus, palette);
if palette_ptr != 0 && entry >= 0 {
if let Some((rgb, _, _)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
Self::write_palette_color_info(
bus,
palette_ptr,
entry as u32,
rgb,
src_usage,
src_tolerance,
);
}
}
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// CTab2Palette ($AA9F)
// Copies a color table into an existing palette.
// PROCEDURE CTab2Palette(srcCTab: CTabHandle; dstPalette: PaletteHandle; srcUsage, srcTolerance: Integer);
// Inside Macintosh Volume VI, 20-23
// CTab2Palette ($AA9F): Copies CTab entries into dstPalette with given usage + tolerance, resizing dstPalette to match srcCTab first when needed, per IM:VI 20-24
(true, 0x29F) => {
let sp = cpu.read_reg(Register::A7);
let src_tolerance = bus.read_word(sp) as i16;
let src_usage = bus.read_word(sp + 2) as i16;
let palette = bus.read_long(sp + 4);
let src_ctab = bus.read_long(sp + 8);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] CTab2Palette srcCTab=${:08X} dstPalette=${:08X} usage={} tolerance={}",
src_ctab, palette, src_usage, src_tolerance
);
}
self.copy_ctab_to_palette(bus, src_ctab, palette, src_usage, src_tolerance);
cpu.write_reg(Register::A7, sp + 12);
Ok(())
}
// Palette2CTab ($AAA0)
// Copies palette colors into an existing color table.
// PROCEDURE Palette2CTab(srcPalette: PaletteHandle; dstCTab: CTabHandle);
// Inside Macintosh Volume VI, 20-23
// Palette2CTab ($AAA0): Copies palette entries into dstCTab with fresh ct_seed, resizing dstCTab to match srcPalette first when needed, per IM:VI 20-24
(true, 0x2A0) => {
let sp = cpu.read_reg(Register::A7);
let dst_ctab = bus.read_long(sp);
let palette = bus.read_long(sp + 4);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] Palette2CTab srcPalette=${:08X} dstCTab=${:08X}",
palette, dst_ctab
);
}
self.copy_palette_to_ctab(bus, palette, dst_ctab, "Palette2CTab");
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// ========== Scroll ==========
// ScrollRect ($A8EF)
// Shifts pixels within a rectangle by (dh, dv) and returns the
// exposed region in updateRgn.
// PROCEDURE ScrollRect(r: Rect; dh, dv: INTEGER; updateRgn: RgnHandle);
// Imaging With QuickDraw 1994, 3-112
// ScrollRect ($A8EF): Shifts pixels within rect by (dh, dv), fills exposed area, sets updateRgn. Supports 1bpp and 8bpp
(true, 0x0EF) => {
self.debug_scroll_rect_count = self.debug_scroll_rect_count.saturating_add(1);
let sp = cpu.read_reg(Register::A7);
// Stack (Pascal calling convention, pushed right-to-left):
// SP+0 : updateRgn (4 bytes, RgnHandle)
// SP+4 : dv (2 bytes, INTEGER)
// SP+6 : dh (2 bytes, INTEGER)
// SP+8 : rect_ptr (4 bytes, Ptr to Rect)
// Total = 12 bytes
let update_rgn = bus.read_long(sp);
let dv = bus.read_word(sp + 4) as i16;
let dh = bus.read_word(sp + 6) as i16;
let rect_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
self.debug_scroll_rect_last_rect = (top, left, bottom, right);
self.debug_scroll_rect_last_delta = (dh, dv);
self.debug_scroll_rect_last_changed_bytes = 0;
if dh != 0 || dv != 0 {
self.debug_scroll_rect_nonzero_delta_count =
self.debug_scroll_rect_nonzero_delta_count.saturating_add(1);
}
let w = (right - left) as i32;
let h = (bottom - top) as i32;
if w <= 0 || h <= 0 {
return Some(Ok(()));
}
// Resolve port pixel geometry from the dispatcher's
// current_port (kept in sync with the THE_PORT low-mem
// global at 0x09DA by set_current_port_state).
let the_port = *self.current_port;
let port_top;
let port_left;
let base_addr;
let row_bytes_raw;
let is_color;
let rb_word = bus.read_word(the_port + 0x06);
if rb_word & 0xC000 != 0 {
// CGrafPort — portPixMap is a handle at offset +2
is_color = true;
let pm_handle = bus.read_long(the_port + 0x02);
let pm = bus.read_long(pm_handle);
if pm == 0 {
return Some(Ok(()));
}
// Offscreen CGrafPort PixMaps store baseAddr as a
// movable-memory handle. Resolve the handle before
// reading or writing pixels; using the field itself
// would scroll the handle cell rather than the GWorld
// raster. Imaging With QuickDraw (1994), pp. 6-38--6-39.
base_addr = Self::offscreen_pixmap_base_ptr(bus, pm);
row_bytes_raw = bus.read_word(pm + 4) & 0x3FFF;
let bounds_top = bus.read_word(pm + 6) as i16;
let bounds_left = bus.read_word(pm + 8) as i16;
port_top = bounds_top;
port_left = bounds_left;
} else {
// Classic GrafPort — portBits at offset +2
is_color = false;
base_addr = bus.read_long(the_port + 0x02);
row_bytes_raw = bus.read_word(the_port + 0x06);
port_top = bus.read_word(the_port + 0x08) as i16;
port_left = bus.read_word(the_port + 0x0A) as i16;
}
let row_bytes = row_bytes_raw as u32;
self.debug_scroll_rect_last_port = the_port;
self.debug_scroll_rect_last_base = base_addr;
self.debug_scroll_rect_last_row_bytes = row_bytes_raw;
self.debug_scroll_rect_last_port_bounds_top_left = (port_top, port_left);
self.debug_scroll_rect_last_is_color = is_color;
let _bytes_per_pixel: u32 = if is_color { 1 } else { 0 }; // 0 means 1bpp
if base_addr == self.screen_mode.0 {
let mut clip_top = top;
let mut clip_left = left;
let mut clip_bottom = bottom;
let mut clip_right = right;
for offset in [24u32, 28u32] {
let rgn_handle = bus.read_long(the_port.wrapping_add(offset));
if rgn_handle == 0 {
continue;
}
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr == 0 {
continue;
}
let rt = bus.read_word(rgn_ptr + 2) as i16;
let rl = bus.read_word(rgn_ptr + 4) as i16;
let rb = bus.read_word(rgn_ptr + 6) as i16;
let rr = bus.read_word(rgn_ptr + 8) as i16;
clip_top = clip_top.max(rt);
clip_left = clip_left.max(rl);
clip_bottom = clip_bottom.min(rb);
clip_right = clip_right.min(rr);
}
if clip_top >= clip_bottom || clip_left >= clip_right {
return Some(Ok(()));
}
self.ensure_dialog_background_saved_for_screen_port(bus, the_port);
}
// Read rect pixels into temp buffer.
//
// For 1bpp, pixel_row_bytes must cover BYTE-aligned reads
// from `left & ~7` through `right` (rounded up). The
// per-pixel bit lookup below maps buf[0] bit 7 to source
// pixel `left & ~7`, then `left_bit_offset_in_buf` corrects
// for the sub-byte left edge.
let wu = w as u32;
let hu = h as u32;
let left_bit_offset_in_buf = if is_color { 0 } else { (left as u32) & 7 };
let pixel_row_bytes = if is_color {
wu
} else {
(left_bit_offset_in_buf + wu).div_ceil(8)
};
let mut buf = vec![0u8; (pixel_row_bytes * hu) as usize];
for row in 0..hu {
let src_y = (top - port_top) as u32 + row;
for col in 0..pixel_row_bytes {
let src_x_byte =
(left - port_left) as u32 / (if is_color { 1 } else { 8 }) + col;
let addr = base_addr + src_y * row_bytes + src_x_byte;
buf[(row * pixel_row_bytes + col) as usize] = bus.read_byte(addr);
}
}
// Colour ports move whole row spans, carrying their retained
// text row by row; the exposed strip is written per byte.
let scrolled = is_color
&& self.scroll_color_rows(
bus,
ScrollRows {
base: base_addr,
row_bytes,
origin: ((top - port_top) as u32, (left - port_left) as u32),
canvas: (top, left),
size: (w, h),
delta: (dh, dv),
background: self.bk_pat,
},
&buf,
);
if !scrolled {
let mut scroll_pixels: crate::memory::SavedPixels = buf.into();
if is_color {
for row in 0..hu {
let addr = base_addr
+ ((top - port_top) as u32 + row) * row_bytes
+ (left - port_left) as u32;
bus.capture_pixel_detail(
&mut scroll_pixels,
(row * pixel_row_bytes) as usize,
addr,
pixel_row_bytes as usize,
);
}
}
let buf = scroll_pixels;
// BackPat updates the dispatcher-level cache (self.bk_pat).
// sync_port_draw_state mirrors this into classic GrafPort
// memory (+32) for caller visibility, but the cache is the
// canonical source used by drawing routines.
let bg_pat = self.bk_pat;
// Write pixels back shifted by (dh, dv). 8bpp uses per-byte
// iteration (each byte = one pixel). 1bpp uses per-pixel
// iteration so sub-byte horizontal shifts are bit-precise.
if is_color {
for dst_row in 0..h {
let src_row = dst_row - dv as i32;
let dst_canvas_y = (top as i32 + dst_row) as usize;
for dst_col_byte in 0..pixel_row_bytes as i32 {
let src_col = dst_col_byte - dh as i32;
let pixel_byte =
if src_row >= 0 && src_row < h && src_col >= 0 && src_col < w {
buf[(src_row as u32 * pixel_row_bytes + src_col as u32)
as usize]
} else {
// Exposed area uses port.bgPat. 8bpp:
// fg_idx=255 for pattern bit set, bg_idx=0
// otherwise — matches the typical 8bpp CLUT
// black/white layout.
let canvas_x = (left + dst_col_byte as i16) as usize;
let source_is_black =
bg_pat[dst_canvas_y & 7] & (1 << (7 - (canvas_x & 7))) != 0;
if source_is_black {
0xFF
} else {
0x00
}
};
let dy = (top - port_top) as u32 + dst_row as u32;
let dx = (left - port_left) as u32 + dst_col_byte as u32;
let addr = base_addr + dy * row_bytes + dx;
let old = bus.read_byte(addr);
if old != pixel_byte {
self.debug_scroll_rect_changed_byte_count =
self.debug_scroll_rect_changed_byte_count.saturating_add(1);
self.debug_scroll_rect_last_changed_bytes =
self.debug_scroll_rect_last_changed_bytes.saturating_add(1);
}
if src_row >= 0 && src_row < h && src_col >= 0 && src_col < w {
bus.copy_saved_pixel(
addr,
&buf,
(src_row as u32 * pixel_row_bytes + src_col as u32) as usize,
|index| index,
);
} else {
bus.write_byte(addr, pixel_byte);
}
}
}
} else {
for dst_row in 0..h {
let src_row = dst_row - dv as i32;
let dst_canvas_y = (top as i32 + dst_row) as usize;
for dst_col in 0..w {
let src_col = dst_col - dh as i32;
let pixel_bit =
if src_row >= 0 && src_row < h && src_col >= 0 && src_col < w {
// Shift the bit lookup by `left & 7` so that
// src_col=0 maps to source pixel `left`, not
// to the byte-aligned floor.
let src_pixel_in_row = left_bit_offset_in_buf + src_col as u32;
let src_byte_in_row = src_pixel_in_row / 8;
let src_bit_in_byte = 7 - (src_pixel_in_row & 7) as u8;
let buf_byte = buf[(src_row as u32 * pixel_row_bytes
+ src_byte_in_row)
as usize];
(buf_byte >> src_bit_in_byte) & 1
} else {
// Exposed area fills with the port's bgPat
// (per IM:I I-178). The pattern is tiled in
// CANVAS coordinates so adjacent scrolls line
// up.
let canvas_x = (left + dst_col as i16) as usize;
if bg_pat[dst_canvas_y & 7] & (1 << (7 - (canvas_x & 7))) != 0 {
1
} else {
0
}
};
let dy = (top - port_top) as u32 + dst_row as u32;
let dst_pixel_x = (left - port_left) as u32 + dst_col as u32;
let dst_byte_addr = base_addr + dy * row_bytes + dst_pixel_x / 8;
let dst_bit = 7 - (dst_pixel_x & 7) as u8;
let cur = bus.read_byte(dst_byte_addr);
let new = if pixel_bit != 0 {
cur | (1 << dst_bit)
} else {
cur & !(1u8 << dst_bit)
};
if cur != new {
self.debug_scroll_rect_changed_byte_count =
self.debug_scroll_rect_changed_byte_count.saturating_add(1);
self.debug_scroll_rect_last_changed_bytes =
self.debug_scroll_rect_last_changed_bytes.saturating_add(1);
}
bus.write_byte(dst_byte_addr, new);
}
}
}
}
// Set updateRgn to the exposed rectangle.
if update_rgn != 0 {
let rgn_ptr = bus.read_long(update_rgn);
if rgn_ptr != 0 {
// IM:I I-178: updateRgn is set to the vacated area.
// Clamp to the scrolled rect so oversize deltas
// (|dh|>=width, |dv|>=height) produce a full-rect
// update region rather than spilling past bounds.
let (exp_top, exp_left, exp_bottom, exp_right) = if dv > 0 {
let exp_bottom =
(top as i32 + dv as i32).clamp(top as i32, bottom as i32) as i16;
(top, left, exp_bottom, right)
} else if dv < 0 {
let exp_top =
(bottom as i32 + dv as i32).clamp(top as i32, bottom as i32) as i16;
(exp_top, left, bottom, right)
} else if dh > 0 {
let exp_right =
(left as i32 + dh as i32).clamp(left as i32, right as i32) as i16;
(top, left, bottom, exp_right)
} else if dh < 0 {
let exp_left =
(right as i32 + dh as i32).clamp(left as i32, right as i32) as i16;
(top, exp_left, bottom, right)
} else {
(0, 0, 0, 0)
};
// Rectangular region: 10 bytes
bus.write_word(rgn_ptr, 10); // rgnSize
bus.write_word(rgn_ptr + 2, exp_top as u16);
bus.write_word(rgn_ptr + 4, exp_left as u16);
bus.write_word(rgn_ptr + 6, exp_bottom as u16);
bus.write_word(rgn_ptr + 8, exp_right as u16);
}
}
if base_addr == self.screen_mode.0 && self.debug_scroll_rect_last_changed_bytes > 0
{
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
the_port,
(
top.saturating_sub(port_top),
left.saturating_sub(port_left),
bottom.saturating_sub(port_top),
right.saturating_sub(port_left),
),
);
self.refresh_visible_dialog_snapshot_after_bulk_port_draw(
bus,
the_port,
(
top.saturating_sub(port_top),
left.saturating_sub(port_left),
bottom.saturating_sub(port_top),
right.saturating_sub(port_left),
),
);
}
Ok(())
}
// ========== Color QuickDraw / GDevice ==========
// GetDeviceList ($AA29) → GDHandle
// GetDeviceList ($AA29): Returns main GDevice handle, triggers color upgrade
(true, 0x229) => {
let sp = cpu.read_reg(Register::A7);
let gdh = self.ensure_main_gdevice(bus);
bus.write_long(sp, gdh);
Ok(())
}
// GetMaxDevice ($AA27): (Rect) → GDHandle
// FUNCTION GetMaxDevice(globalRect: Rect): GDHandle;
// Inside Macintosh Volume VI 1991, pp. 21-21..21-22:
// returns the deepest device intersecting globalRect.
//
// HLE currently models a single active screen device. An
// intersecting query resolves to that main GDevice handle;
// a rectangle that misses the only screen returns NIL.
(true, 0x227) => {
let sp = cpu.read_reg(Register::A7);
let rect_ptr = bus.read_long(sp);
let gdh = self.ensure_main_gdevice(bus);
let (_, _, screen_w, screen_h, _) = self.screen_mode;
let intersects = if rect_ptr != 0 {
let top = bus.read_word(rect_ptr) as i16;
let left = bus.read_word(rect_ptr + 2) as i16;
let bottom = bus.read_word(rect_ptr + 4) as i16;
let right = bus.read_word(rect_ptr + 6) as i16;
let screen_right = screen_w as i16;
let screen_bottom = screen_h as i16;
top < screen_bottom && left < screen_right && bottom > 0 && right > 0
} else {
false
};
bus.write_long(sp + 4, if intersects { gdh } else { 0 });
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// GetMainDevice (0xAA2A)
// Returns a handle to the gDevice that has the menu bar
// on it (the main screen's GDevice record).
// FUNCTION GetMainDevice: GDHandle;
// Inside Macintosh Volume V (1986), p. V-124
// "The GetMainDevice function returns the handle of
// the gDevice that has the menu bar on it."
// Tool-bit Pascal FUNCTION pop-0 + 4-byte GDHandle result
// slot calling convention: caller pre-pushes a 4-byte
// result slot (A7 -= 4), the trap writes the GDHandle to
// [A7] without popping any argument frame, and the caller
// pops the 4-byte slot afterwards. Net A7 zero across the
// C-level call: pop-0 with a non-NIL GDHandle in the
// result slot.
(true, 0x22A) => {
let sp = cpu.read_reg(Register::A7);
let gdh = self.ensure_main_gdevice(bus);
bus.write_long(sp, gdh);
Ok(())
}
// GetNextDevice ($AA2B): GDHandle → GDHandle
// Imaging With QuickDraw 1994, p.5-28: returns the next GDevice
// in the device list, or NIL if there are no more entries.
// The GDevice structure defines the link field `gdNextGD`
// at offset +30 (Imaging With QuickDraw 1994, p.5-16).
(true, 0x22B) => {
let sp = cpu.read_reg(Register::A7);
let cur_handle = bus.read_long(sp);
// Read gdNextGD from the GDevice record
let next = if cur_handle != 0 {
let gd_ptr = bus.read_long(cur_handle);
if gd_ptr != 0 {
bus.read_long(gd_ptr + 30) // gdNextGD
} else {
0
}
} else {
0
};
if trace_gdevice_traps_enabled() {
eprintln!("[TRAP] GetNextDevice(${:08X}) → ${:08X}", cur_handle, next);
}
bus.write_long(sp + 4, next); // return value
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// TestDeviceAttribute ($AA2C): (GDHandle, INTEGER) → BOOLEAN
// TestDeviceAttribute ($AA2C): Tests individual flag bit
(true, 0x22C) => {
let sp = cpu.read_reg(Register::A7);
let attribute = bus.read_word(sp);
let gd_handle = bus.read_long(sp + 2);
let bit = 1u16.checked_shl(attribute as u32);
let result = if gd_handle != 0 {
let gd_ptr = bus.read_long(gd_handle);
if gd_ptr != 0 {
let flags = bus.read_word(gd_ptr + 20);
let matched = bit.map_or(false, |bit| (flags & bit) != 0);
if trace_gdevice_traps_enabled() {
eprintln!(
"[TRAP] TestDeviceAttribute(gdh=${:08X}, attr={}) flags=${:04X} → {}",
gd_handle, attribute, flags, matched
);
}
if matched {
0x0100u16
} else {
0u16
}
} else {
if trace_gdevice_traps_enabled() {
eprintln!(
"[TRAP] TestDeviceAttribute(gdh=${:08X}, attr={}) → NULL ptr",
gd_handle, attribute
);
}
0u16
}
} else {
if trace_gdevice_traps_enabled() {
eprintln!("[TRAP] TestDeviceAttribute(NULL, attr={})", attribute);
}
0u16
};
bus.write_word(sp + 6, result);
cpu.write_reg(Register::A7, sp + 6);
Ok(())
}
// SetDeviceAttribute ($AA2D)
// Sets an attribute bit in a GDevice record's gdFlags field.
// PROCEDURE SetDeviceAttribute(gdh: GDHandle; attribute: INTEGER; value: BOOLEAN);
// Inside Macintosh Volume V 1986, p. V-124; Imaging With QuickDraw 1994, p. 5-22
// SetDeviceAttribute ($AA2D): Toggles attribute bit in gdFlags ($GDH+20) per IM:V V-124 / Imaging 5-22
(true, 0x22D) => {
let sp = cpu.read_reg(Register::A7);
// Pascal BOOLEAN lives at the HIGH byte of its 2-byte
// stack slot (the even offset); MPW C leaves an
// uninitialised garbage byte at the odd offset. See
// window.rs:813 for the same convention on NewWindow.
// Inside Macintosh Volume V, V-238 (Pascal calling
// convention).
let value = bus.read_byte(sp);
let attribute = bus.read_word(sp + 2);
let gd_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if gd_handle != 0 {
let gd_ptr = bus.read_long(gd_handle);
if gd_ptr != 0 {
if let Some(bit) = 1u16.checked_shl(attribute as u32) {
let mut flags = bus.read_word(gd_ptr + 20);
if value != 0 {
flags |= bit;
} else {
flags &= !bit;
}
bus.write_word(gd_ptr + 20, flags);
}
}
}
Ok(())
}
// GetGDevice (0xAA32)
// Returns a handle to the current gDevice (TheGDevice
// low-mem global).
// FUNCTION GetGDevice: GDHandle;
// Inside Macintosh Volume V (1986), p. V-123
// "The GetGDevice routine returns a handle to the
// current gDevice. ... A handle to the currently
// active device is kept in the global variable
// TheGDevice."
// Tool-bit Pascal FUNCTION pop-0 + 4-byte GDHandle result
// slot calling convention: caller pre-pushes a 4-byte
// result slot, the trap writes the GDHandle to [A7]
// without popping any argument frame, and the caller pops
// the 4-byte slot afterwards: pop-0 with a non-NIL GDHandle
// in the result slot.
(true, 0x232) => {
let sp = cpu.read_reg(Register::A7);
let gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
};
bus.write_long(sp, gdh);
Ok(())
}
// SetGDevice ($AA31): GDHandle → void
// PROCEDURE SetGDevice(gdh: GDHandle);
// Imaging With QuickDraw 1994, p.5-24.
//
// Stores the new device both in our dispatcher and in the
// documented low-mem TheGDevice global ($0CC8) so guest 68k
// code that reads the global directly (instead of calling
// GetGDevice afterwards) sees the update. Without this
// mirror, a SetGDevice-then-deref-low-mem sequence reads
// the old handle and games that walk gdLink/gdNextGD off
// it land on garbage pointers, producing the
// "MOVE.B (A0)+,D2 with A0=NIL" landing pattern we see in
// Centaurian's launch path.
// Imaging With QuickDraw 1994 pp.5-4 and 5-24: TheGDevice keeps
// the current device handle.
(true, 0x231) => {
let sp = cpu.read_reg(Register::A7);
let gdh = bus.read_long(sp);
self.current_gdevice
.with_mut(|current_gdevice| *current_gdevice = gdh);
bus.write_long(0x0CC8, gdh);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// DisposeGDevice ($AA30)
// Disposes of a GDevice record and its associated data structures.
// PROCEDURE DisposeGDevice(gdh: GDHandle);
// Imaging With QuickDraw 1994, p. 5-25
// DisposeGDevice ($AA30): Pops 4 bytes (gdh); does not free the GDevice block (allocator doesn't support free) per Imaging With QuickDraw 1994, 5-25
(true, 0x230) => {
let sp = cpu.read_reg(Register::A7);
let _gdh = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
// Stub: don't actually free since our allocator doesn't support it well
Ok(())
}
// NewGDevice ($AA2F)
// FUNCTION NewGDevice(refNum: INTEGER; mode: LONGINT): GDHandle;
// Imaging With QuickDraw 1994, p. 5-25
// NewGDevice ($AA2F): Allocates a detached GDevice shell with its
// own GDHandle/PixMap/CTab, then applies the minimal InitGDevice
// field writes Systemless models (gdRefNum/gdMode + gdDevType bit).
//
// HLE compromise: Systemless does not emulate real video-driver mode
// programming or insert app-created devices into DeviceList. The
// returned GDevice is a detached shell cloned from the main screen's
// PixMap/CTab shape so callers can inspect a stable, non-NIL record
// without aliasing the main screen device.
(true, 0x22F) => {
let sp = cpu.read_reg(Register::A7);
let mode = bus.read_long(sp);
let ref_num = bus.read_word(sp + 4) as i16;
let gdh = self.allocate_detached_gdevice(bus);
if mode != 0xFFFF_FFFF {
self.init_gdevice_minimal(bus, gdh, ref_num, mode);
}
bus.write_long(sp + 6, gdh);
cpu.write_reg(Register::A7, sp + 6);
Ok(())
}
// Index2Color ($AA34)
// PROCEDURE Index2Color (index: LONGINT; VAR rgb: RGBColor);
// Inside Macintosh Volume V, V-141 (Color Manager — Color
// Manager Routines — Color Conversion)
//
// "The Index2Color routine finds the RGB color corresponding
// to a given color table index. The desired pixel value is
// passed and the corresponding RGB value is returned in
// RGB. The routine takes a longint, which should be a
// pixel value padded with zeros in the high word."
//
// Stack (Pascal): SP+0=rgb_ptr(4), SP+4=index(4). Pops 8.
// No FUNCTION result slot. The absolute RGB read comes from
// the active gDevice's CLUT.
// Index2Color ($AA34): Reads RGB from current GDevice's ctab, IM:V V-141
(true, 0x234) => {
let sp = cpu.read_reg(Register::A7);
// Stack (Pascal): SP+0: rgb ptr (4), SP+4: index (4)
let rgb_ptr = bus.read_long(sp);
let index = bus.read_long(sp + 4) as usize;
// Look up in current GDevice's color table
let the_gdevice = bus.read_long(0x0CC8); // TheGDevice
let gd_ptr = bus.read_long(the_gdevice);
let pixmap_handle = bus.read_long(gd_ptr + 22); // gdPMap
let pixmap_ptr = bus.read_long(pixmap_handle);
let ctab_handle = bus.read_long(pixmap_ptr + 42); // pmTable
let ctab_ptr = bus.read_long(ctab_handle);
let ct_size = bus.read_word(ctab_ptr + 6) as usize; // ctSize = nEntries - 1
if index <= ct_size {
let entry = ctab_ptr + 8 + (index as u32) * 8;
let r = bus.read_word(entry + 2);
let g = bus.read_word(entry + 4);
let b = bus.read_word(entry + 6);
bus.write_word(rgb_ptr, r);
bus.write_word(rgb_ptr + 2, g);
bus.write_word(rgb_ptr + 4, b);
} else {
// Out of range — return black
bus.write_word(rgb_ptr, 0);
bus.write_word(rgb_ptr + 2, 0);
bus.write_word(rgb_ptr + 4, 0);
}
// Pop params: index(4) + rgb(4) = 8 bytes
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// InvertColor ($AA35)
// PROCEDURE InvertColor (VAR theColor: RGBColor);
// Inside Macintosh Volume V, V-141 (Color Manager — Color
// Manager Routines — Color Conversion)
//
// "The InvertColor routine finds the complement of an absolute
// color, using the list of complement procedures in the
// current device record. The default complement procedure
// uses the 1's complement of each component of the requested
// color."
//
// Stack (Pascal): SP+0=rgb_ptr(4). VAR parameter — read RGB
// through the pointer, complement each channel, write back.
// Pops 4. No return value. On a fresh boot this takes the
// default ROM 1's-complement path, producing ~R, ~G, ~B per
// IM:V V-141.
// InvertColor ($AA35): 1's complement of each channel of the VAR RGBColor, IM:V V-141
(true, 0x235) => {
let sp = cpu.read_reg(Register::A7);
let rgb_ptr = bus.read_long(sp);
if rgb_ptr != 0 {
let r = bus.read_word(rgb_ptr);
let g = bus.read_word(rgb_ptr + 2);
let b = bus.read_word(rgb_ptr + 4);
bus.write_word(rgb_ptr, !r);
bus.write_word(rgb_ptr + 2, !g);
bus.write_word(rgb_ptr + 4, !b);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// RealColor ($AA36)
// FUNCTION RealColor (color: RGBColor): BOOLEAN;
// Inside Macintosh Volume V, V-141
//
// "The RealColor routine tells whether a given absolute color
// actually exists in the current device's color table. This
// decision is based on the current resolution of the inverse
// table. For example, if the current iTabRes is four,
// RealColor returns TRUE if there exists a color that exactly
// matches the top four bits of red, green, and blue."
//
// Stack (Pascal): SP+0=rgb_ptr(4). Returns BOOLEAN at SP+4
// ($0100 = TRUE high-byte, $0000 = FALSE). Pops to SP+4.
//
// Systemless uses the default 4-bit resolution: a color is
// "real" iff some entry in device_clut has the same top
// 4 bits per channel. The absolute BOOLEAN return therefore
// depends on the contents of device_clut.
// RealColor ($AA36): TRUE if device_clut has an entry matching top-4-bits-per-channel, IM:V V-141
(true, 0x236) => {
let sp = cpu.read_reg(Register::A7);
let rgb_ptr = bus.read_long(sp);
let want_r = bus.read_word(rgb_ptr) & 0xF000;
let want_g = bus.read_word(rgb_ptr + 2) & 0xF000;
let want_b = bus.read_word(rgb_ptr + 4) & 0xF000;
let mut found = false;
for entry in self.device_clut.iter() {
if (entry[0] & 0xF000) == want_r
&& (entry[1] & 0xF000) == want_g
&& (entry[2] & 0xF000) == want_b
{
found = true;
break;
}
}
bus.write_word(sp + 4, if found { 0x0100 } else { 0x0000 });
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// PaletteDispatch ($AAA2)
// Dispatcher for Palette Manager routines.
//
// MPW's Palette.h emits either MOVEQ/MOVE.W #sel,D0 /
// _PaletteDispatch (selector in D0) -- the real ROM
// convention. Systemless's legacy handler below assumes
// selector on top of stack. Fast-path public D0-based
// selectors so MPW-compiled apps can call them without
// requiring the legacy stack-selector layout.
//
// Inside Macintosh Volume VI:
// - Table C-3 (p. C-11): _PaletteDispatch selector $0002
// is RestoreDeviceClut.
// - Table C-4 (p. C-23/C-24): public selectors include
// $0003 ResizePalette, $0015 PMgrVersion, $0417
// GetPaletteUpdates, $0616 SetPaletteUpdates, $0A13
// SetDepth, $0A14 HasDepth, $1219 GetGray.
//
// Legacy stack-selector compatibility path (below) keeps
// the historical Systemless-internal selector mapping used by
// older test harnesses.
(true, 0x2A2) => {
let sp = cpu.read_reg(Register::A7);
// D0-based MPW fast paths (MOVEQ / MOVE.W to D0,
// then trap).
let d0 = cpu.read_reg(Register::D0);
let d0_selector = Self::palette_dispatch_selector(d0);
if d0 == 0 && bus.read_long(sp + 2) == 0 {
// Entry2Index (public _PaletteDispatch selector $0000)
// FUNCTION Entry2Index(entry: Integer): LongInt;
// Inside Macintosh Volume VI, p. 20-25.
//
// Some 68k callers emit:
// CLR.L -(A7) ; LongInt result slot
// MOVE.W entry,-(A7)
// MOVEQ #0,D0
// _PaletteDispatch
// MOVE.L (A7)+,D0
//
// That puts the entry argument at SP+0 and a cleared
// long result slot at SP+2. Handle it before the legacy
// stack-selector compatibility mapping below, where the
// same small word values historically meant duplicated
// AA90..AAA0 Palette Manager trap selectors.
let entry = bus.read_word(sp) as i16;
let index = self.palette_entry_to_device_index(bus, entry);
bus.write_long(sp + 2, index);
cpu.write_reg(Register::A7, sp + 2);
return Some(Ok(()));
}
if d0_selector == 0x0002 {
// RestoreDeviceClut (public _PaletteDispatch selector $0002)
// PROCEDURE RestoreDeviceClut(gdh: GDHandle);
//
// IM:VI (1991) Table C-3 + Palette Manager chapter
// ("Manipulating Palettes and Color Tables"): selector
// $0002 takes a single GDHandle argument; passing NIL
// restores all screens.
//
// Systemless models a single active CLUT device, so both
// NIL and the main GDevice restore to the canonical
// system 8bpp CLUT.
let gdh = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let main = self.ensure_main_gdevice(bus);
if gdh == 0 || gdh == main {
self.install_application_clut(bus, Self::standard_mac_8bpp_clut());
}
return Some(Ok(()));
}
if d0_selector == 0x0003 {
// ResizePalette (public _PaletteDispatch selector $0003)
// PROCEDURE ResizePalette(srcPalette: PaletteHandle;
// size: Integer);
// Inside Macintosh Volume VI (1991), p. 20-24 and
// selector summary p. 21-28.
//
// MPW-style stack layout omits the selector word:
// SP+0 size (INTEGER)
// SP+2 srcPalette (PaletteHandle)
let size = bus.read_word(sp) as i16;
let palette = bus.read_long(sp + 2);
self.resize_palette(bus, palette, size);
cpu.write_reg(Register::A7, sp + 6);
return Some(Ok(()));
}
if d0_selector == 0x0417 {
// GetPaletteUpdates (public _PaletteDispatch selector $0417)
// FUNCTION GetPaletteUpdates(p: PaletteHandle): Integer;
// Inside Macintosh Volume VI (1991), p. 20-21; Table C-4.
// MPW Universal Headers Palettes.h:
// EXTERN_API(short) GetPaletteUpdates(PaletteHandle p)
// THREEWORDINLINE(0x303C, 0x0417, 0xAAA2);
//
// D0-based MPW calling convention: selector in D0,
// stack holds only the PaletteHandle argument plus the
// 2-byte function result slot.
let palette = bus.read_long(sp);
let updates = self.palette_update_mode(palette);
cpu.write_reg(Register::D0, updates as u16 as u32);
bus.write_word(sp + 4, updates as u16);
cpu.write_reg(Register::A7, sp + 4);
return Some(Ok(()));
}
if d0_selector == 0x0616 {
// SetPaletteUpdates (public _PaletteDispatch selector $0616)
// PROCEDURE SetPaletteUpdates(p: PaletteHandle;
// updates: Integer);
// Inside Macintosh Volume VI (1991), p. 20-21; Table C-4.
// MPW Universal Headers Palettes.h:
// EXTERN_API(void) SetPaletteUpdates(PaletteHandle p,
// short updates)
// THREEWORDINLINE(0x303C, 0x0616, 0xAAA2);
//
// D0-based MPW calling convention: selector in D0,
// stack holds only updates + PaletteHandle.
//
// Record the requested update mode so the public getter
// can return it for this palette handle.
let updates = bus.read_word(sp) as i16;
let palette = bus.read_long(sp + 2);
self.record_palette_updates(palette, updates);
cpu.write_reg(Register::A7, sp + 6);
return Some(Ok(()));
}
if d0_selector == 0x0015 {
// PMgrVersion: returns a short Palette Mgr
// version. No args on stack. Callee just
// populates the 2-byte result slot at SP+0.
bus.write_word(sp, 1);
return Some(Ok(()));
}
if d0_selector == 0x0C19 || d0_selector == 0x1219 {
// GetGray (PaletteDispatch selectors $0C19 and $1219)
// Finds a device-representable intermediate color.
// FUNCTION GetGray(device: GDHandle; backGround: RGBColor;
// VAR foreGround: RGBColor): Boolean;
// Both selector encodings use the same pointer frame:
// SP+0 foreGround (RGBColor *)
// SP+4 backGround (RGBColor *)
// SP+8 device (GDHandle)
// SP+12 Boolean result slot
// Imaging With QuickDraw (1994), pp. 4-81 to 4-82.
let foreground = bus.read_long(sp);
let background = bus.read_long(sp + 4);
let device = bus.read_long(sp + 8);
let mut found = false;
if Self::guest_range_in_ram(bus, foreground, 6)
&& Self::guest_range_in_ram(bus, background, 6)
{
let foreground_rgb = [
bus.read_word(foreground),
bus.read_word(foreground + 2),
bus.read_word(foreground + 4),
];
let background_rgb = [
bus.read_word(background),
bus.read_word(background + 2),
bus.read_word(background + 4),
];
if let Some(intermediate) = self.gdevice_intermediate_color(
bus,
device,
background_rgb,
foreground_rgb,
) {
bus.write_word(foreground, intermediate[0]);
bus.write_word(foreground + 2, intermediate[1]);
bus.write_word(foreground + 4, intermediate[2]);
found = true;
}
}
let boolean = if found { 0x0100 } else { 0 };
bus.write_word(sp + 12, boolean as u16);
cpu.write_reg(Register::D0, boolean);
cpu.write_reg(Register::A7, sp + 12);
return Some(Ok(()));
}
if matches!(d0_selector, 0x040D | 0x040E | 0x040F | 0x0410) {
// SaveFore/SaveBack serialize either direct RGB state
// (value 0) or the GrafVars palette handle plus entry
// index over ColorSpec.rgb (value 1). RestoreFore and
// RestoreBack reverse that overlay.
// Inside Macintosh Volume VI (1991), pp. 20-21 to
// 20-22; Table C-3 selectors $040D-$0410.
let color_ptr = bus.read_long(sp);
if matches!(d0_selector, 0x040D | 0x040E) {
let color = if d0_selector == 0x040D {
self.fg_color
} else {
self.bg_color
};
let palette_color = if d0_selector == 0x040D {
self.pm_fg_color
} else {
self.pm_bg_color
};
if color_ptr != 0 {
if let Some((palette, entry)) = palette_color {
bus.write_word(color_ptr, 1);
bus.write_long(color_ptr + 2, palette);
bus.write_word(color_ptr + 6, entry as u16);
} else {
bus.write_word(color_ptr, 0);
bus.write_word(color_ptr + 2, color.0);
bus.write_word(color_ptr + 4, color.1);
bus.write_word(color_ptr + 6, color.2);
}
}
} else if color_ptr != 0 {
let value = bus.read_word(color_ptr);
let foreground = d0_selector == 0x040F;
if value == 0 {
let color = (
bus.read_word(color_ptr + 2),
bus.read_word(color_ptr + 4),
bus.read_word(color_ptr + 6),
);
if foreground {
self.fg_color = color;
self.pm_fg_color = None;
} else {
self.bg_color = color;
self.pm_bg_color = None;
}
} else if value == 1 {
let palette = bus.read_long(color_ptr + 2);
let entry = bus.read_word(color_ptr + 6) as i16;
if foreground {
self.pm_fg_color = Some((palette, entry));
} else {
self.pm_bg_color = Some((palette, entry));
}
if entry >= 0 {
if let Some((rgb, usage, _tolerance)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
let color = if usage & (PM_EXPLICIT | PM_ANIMATED) != 0 {
let [r, g, b] = self.device_clut[(entry as usize) & 0xFF];
(r, g, b)
} else {
(rgb[0], rgb[1], rgb[2])
};
if foreground {
self.fg_color = color;
} else {
self.bg_color = color;
}
}
}
}
self.sync_current_port_draw_state(bus);
}
cpu.write_reg(Register::A7, sp + 4);
return Some(Ok(()));
}
// HasDepth / SetDepth use THREEWORDINLINE(0x303C, sel, 0xAAA2)
// which emits MOVE.W #sel, D0 then _PaletteDispatch.
// Real ROM convention: selector in D0, no selector word on stack.
// Stack: SP+0=flags(2), SP+2=whichFlags(2), SP+4=depth(2),
// SP+6=gd(4), SP+10=result(2). Imaging With QuickDraw
// 1994 pp.5-33..5-34; IM:VI VI-21-12.
if d0_selector == 0x0A14 {
// HasDepth (D0-based MPW calling convention)
// FUNCTION HasDepth(gd: GDHandle; depth, whichFlags,
// flags: Integer): Integer;
// Imaging With QuickDraw 1994 pp.5-33..5-34
let flags = bus.read_word(sp);
let which_flags = bus.read_word(sp + 2);
let depth = bus.read_word(sp + 4);
let gd = bus.read_long(sp + 6);
let mode_id = self.has_depth_mode_id(bus, gd, depth, which_flags, flags);
bus.write_word(sp + 10, mode_id);
cpu.write_reg(Register::A7, sp + 10);
return Some(Ok(()));
}
if d0_selector == 0x0A13 {
// SetDepth (D0-based MPW calling convention)
// FUNCTION SetDepth(gd: GDHandle; depth, whichFlags,
// flags: Integer): OSErr;
// IM:VI VI-21-12
let flags = bus.read_word(sp);
let which_flags = bus.read_word(sp + 2);
let depth = bus.read_word(sp + 4);
let gd = bus.read_long(sp + 6);
let result = self.set_depth_or_mode(cpu, bus, gd, depth, which_flags, flags);
bus.write_word(sp + 10, result);
cpu.write_reg(Register::A7, sp + 10);
cpu.write_reg(Register::D0, result as i32 as u32);
return Some(Ok(()));
}
let selector = bus.read_word(sp);
match selector {
0x0000 => {
cpu.write_reg(Register::A7, sp + 2);
}
0x0001 => {
let src_tolerance = bus.read_word(sp + 2) as i16;
let src_usage = bus.read_word(sp + 4) as i16;
let src_colors = bus.read_long(sp + 6);
let entries = bus.read_word(sp + 10);
let palette = self.create_palette_from_ctab(
bus,
entries,
src_colors,
src_usage,
src_tolerance,
);
bus.write_long(sp + 12, palette);
cpu.write_reg(Register::A7, sp + 12);
}
0x0002 => {
let palette_id = bus.read_word(sp + 2) as i16;
let palette = self.copy_palette_resource_exact(bus, palette_id);
bus.write_long(sp + 4, palette);
cpu.write_reg(Register::A7, sp + 4);
}
0x0003 => {
let palette = bus.read_long(sp + 2);
if palette != 0 {
let palette_ptr = Self::palette_ptr(bus, palette);
self.palette_updates.remove(&palette);
self.window_palettes
.retain(|_, (handle, _)| *handle != palette);
if palette_ptr != 0 {
bus.free(palette_ptr);
}
bus.free(palette);
}
cpu.write_reg(Register::A7, sp + 6);
}
0x0004 => {
let window = bus.read_long(sp + 2);
self.activate_associated_palette_for_window(bus, window);
cpu.write_reg(Register::A7, sp + 6);
}
0x0005 => {
let updates = bus.read_word(sp + 2) as i16;
let palette = bus.read_long(sp + 4);
let window = bus.read_long(sp + 8);
self.set_window_palette_association(window, palette, updates);
self.activate_associated_palette_for_window(bus, window);
cpu.write_reg(Register::A7, sp + 12);
}
0x0006 => {
let window = bus.read_long(sp + 2);
bus.write_long(sp + 6, self.window_palette_handle(window));
cpu.write_reg(Register::A7, sp + 6);
}
0x000A => {
let dst_length = bus.read_word(sp + 2);
let dst_entry = bus.read_word(sp + 4);
let src_index = bus.read_word(sp + 6);
let src_ctab = bus.read_long(sp + 8);
let window = bus.read_long(sp + 12);
// Guard the signed Pascal INTEGER span before the
// unsigned loop logic can treat a negative value as a
// huge copy count.
if (dst_length as i16) < 0
|| (dst_entry as i16) < 0
|| (src_index as i16) < 0
{
cpu.write_reg(Register::A7, sp + 16);
return Some(Ok(()));
}
let palette = self.window_palette_handle(window);
let palette_ptr = Self::palette_ptr(bus, palette);
let src_ctab_ptr = if src_ctab != 0 {
bus.read_long(src_ctab)
} else {
0
};
if palette_ptr != 0 && src_ctab_ptr != 0 {
let max_src = u32::from(bus.read_word(src_ctab_ptr + 6)) + 1;
let max_dst = u32::from(Self::palette_entry_count(bus, palette));
for offset in 0..u32::from(dst_length) {
let src = u32::from(src_index) + offset;
let dst = u32::from(dst_entry) + offset;
if src >= max_src || dst >= max_dst {
break;
}
let src_entry = src_ctab_ptr + 8 + src * 8;
let rgb = [
bus.read_word(src_entry + 2),
bus.read_word(src_entry + 4),
bus.read_word(src_entry + 6),
];
let (_, usage, tolerance) =
Self::read_palette_color_info(bus, palette, dst as u16)
.unwrap_or(([0, 0, 0], PM_TOLERANT, 0));
Self::write_palette_color_info(
bus,
palette_ptr,
dst,
rgb,
usage,
tolerance,
);
}
self.activate_associated_palette_for_window(bus, window);
}
cpu.write_reg(Register::A7, sp + 16);
}
0x000B => {
let rgb_ptr = bus.read_long(sp + 2);
let entry = bus.read_word(sp + 6) as i16;
let palette = bus.read_long(sp + 8);
if let Some((rgb, _, _)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
bus.write_word(rgb_ptr, rgb[0]);
bus.write_word(rgb_ptr + 2, rgb[1]);
bus.write_word(rgb_ptr + 4, rgb[2]);
}
cpu.write_reg(Register::A7, sp + 12);
}
0x000C => {
let rgb_ptr = bus.read_long(sp + 2);
let entry = bus.read_word(sp + 6) as i16;
let palette = bus.read_long(sp + 8);
let palette_ptr = Self::palette_ptr(bus, palette);
if palette_ptr != 0 && entry >= 0 {
let (_, usage, tolerance) =
Self::read_palette_color_info(bus, palette, entry as u16)
.unwrap_or(([0, 0, 0], PM_TOLERANT, 0));
let rgb = [
bus.read_word(rgb_ptr),
bus.read_word(rgb_ptr + 2),
bus.read_word(rgb_ptr + 4),
];
Self::write_palette_color_info(
bus,
palette_ptr,
entry as u32,
rgb,
usage,
tolerance,
);
}
cpu.write_reg(Register::A7, sp + 12);
}
0x000D => {
let tolerance_ptr = bus.read_long(sp + 2);
let usage_ptr = bus.read_long(sp + 6);
let entry = bus.read_word(sp + 10) as i16;
let palette = bus.read_long(sp + 12);
if let Some((_, usage, tolerance)) =
Self::read_palette_color_info(bus, palette, entry as u16)
{
bus.write_word(usage_ptr, usage as u16);
bus.write_word(tolerance_ptr, tolerance as u16);
}
cpu.write_reg(Register::A7, sp + 16);
}
0x000E => {
let src_tolerance = bus.read_word(sp + 2) as i16;
let src_usage = bus.read_word(sp + 4) as i16;
let entry = bus.read_word(sp + 6) as i16;
let palette = bus.read_long(sp + 8);
let palette_ptr = Self::palette_ptr(bus, palette);
if palette_ptr != 0 && entry >= 0 {
let (rgb, _, _) =
Self::read_palette_color_info(bus, palette, entry as u16)
.unwrap_or(([0, 0, 0], 0, 0));
Self::write_palette_color_info(
bus,
palette_ptr,
entry as u32,
rgb,
src_usage,
src_tolerance,
);
}
cpu.write_reg(Register::A7, sp + 12);
}
0x000F => {
let src_tolerance = bus.read_word(sp + 2) as i16;
let src_usage = bus.read_word(sp + 4) as i16;
let palette = bus.read_long(sp + 6);
let src_ctab = bus.read_long(sp + 10);
self.copy_ctab_to_palette(bus, src_ctab, palette, src_usage, src_tolerance);
cpu.write_reg(Register::A7, sp + 12);
}
0x0010 => {
let dst_ctab = bus.read_long(sp + 2);
let palette = bus.read_long(sp + 6);
self.copy_palette_to_ctab(bus, palette, dst_ctab, "Palette2CTab-alt");
cpu.write_reg(Register::A7, sp + 10);
}
0x0417 => {
// GetPaletteUpdates (legacy stack-selector convention)
// FUNCTION GetPaletteUpdates(p: PaletteHandle): Integer;
// Inside Macintosh Volume VI (1991), p. 20-21; Table C-4.
//
// Stack:
// SP+0 selector ($0417)
// SP+2 p (PaletteHandle)
// SP+6 result slot (Integer)
let palette = bus.read_long(sp + 2);
let updates = self.palette_update_mode(palette);
cpu.write_reg(Register::D0, updates as u16 as u32);
bus.write_word(sp + 6, updates as u16);
cpu.write_reg(Register::A7, sp + 6);
}
0x0616 => {
// SetPaletteUpdates (legacy stack-selector convention)
// PROCEDURE SetPaletteUpdates(p: PaletteHandle;
// updates: Integer);
// Inside Macintosh Volume VI (1991), p. 20-21; Table C-4.
//
// Stack:
// SP+0 selector ($0616)
// SP+2 updates
// SP+4 p (PaletteHandle)
// Record the requested update mode so the public
// getter can return it for this palette handle.
let updates = bus.read_word(sp + 2) as i16;
let palette = bus.read_long(sp + 4);
self.record_palette_updates(palette, updates);
cpu.write_reg(Register::A7, sp + 8);
}
// HasDepth (_PaletteDispatch selector $0A14)
// FUNCTION HasDepth(gd: GDHandle; depth, whichFlags,
// flags: Integer): Integer;
// Inside Macintosh Volume VI, VI-21-12
//
// Stack via PaletteDispatch:
// SP+0 selector ($0A14)
// SP+2 flags
// SP+4 whichFlags
// SP+6 depth
// SP+8 gd (LongInt)
// SP+12 result slot (Integer)
//
// Imaging With QuickDraw 1994 pp.5-33..5-34:
// return 0 when the requested depth is unsupported, and a
// nonzero mode ID when supported.
//
// Systemless exposes the common classic Mac display
// depths as device capabilities. 1bpp, 2bpp, 4bpp, and 8bpp are
// wired to screenBits/screen_mode; other supported depths
// are recorded at the GDevice level without changing the
// backing framebuffer.
0x0A14 => {
let flags = bus.read_word(sp + 2);
let which_flags = bus.read_word(sp + 4);
let depth = bus.read_word(sp + 6);
let gd = bus.read_long(sp + 8);
let mode_id = self.has_depth_mode_id(bus, gd, depth, which_flags, flags);
bus.write_word(sp + 12, mode_id);
cpu.write_reg(Register::A7, sp + 12);
}
// SetDepth (_PaletteDispatch selector $0A13)
// FUNCTION SetDepth(gd: GDHandle; depth, whichFlags,
// flags: Integer): OSErr;
// Inside Macintosh Volume VI, VI-21-12
//
// Stack: same layout as HasDepth (10-byte arg block).
// Result is OSErr (Integer). Systemless updates screenBits
// and screen_mode for the wired 1bpp/2bpp/4bpp/8bpp paths, and
// records other supported depth requests on the GDevice
// without changing the backing framebuffer.
//
0x0A13 => {
let flags = bus.read_word(sp + 2);
let which_flags = bus.read_word(sp + 4);
let depth = bus.read_word(sp + 6);
let gd = bus.read_long(sp + 8);
let result =
self.set_depth_or_mode(cpu, bus, gd, depth, which_flags, flags);
bus.write_word(sp + 12, result);
cpu.write_reg(Register::A7, sp + 12);
cpu.write_reg(Register::D0, result as i32 as u32);
}
_ => {
eprintln!("[TRAP] PaletteDispatch unknown selector=${:04X}", selector);
cpu.write_reg(Register::A7, sp + 2);
}
}
Ok(())
}
// GetForeColor (0xAA19)
// Returns the RGB components of the current port's foreground
// color through a VAR RGBColor pointer (Pascal PROCEDURE pop-4,
// no result slot).
// PROCEDURE GetForeColor (VAR color: RGBColor);
// Inside Macintosh Volume V (1986), p. V-68
(true, 0x219) => {
let sp = cpu.read_reg(Register::A7);
let color_ptr = bus.read_long(sp);
if color_ptr != 0 {
bus.write_word(color_ptr, self.fg_color.0);
bus.write_word(color_ptr + 2, self.fg_color.1);
bus.write_word(color_ptr + 4, self.fg_color.2);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// GetBackColor (0xAA1A)
// Returns the RGB components of the current port's background
// color through a VAR RGBColor pointer (Pascal PROCEDURE pop-4,
// no result slot).
// PROCEDURE GetBackColor (VAR color: RGBColor);
// Inside Macintosh Volume V (1986), p. V-68
(true, 0x21A) => {
let sp = cpu.read_reg(Register::A7);
let color_ptr = bus.read_long(sp);
if color_ptr != 0 {
bus.write_word(color_ptr, self.bg_color.0);
bus.write_word(color_ptr + 2, self.bg_color.1);
bus.write_word(color_ptr + 4, self.bg_color.2);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// GetCTable ($AA18)
// Returns a copy of a standard or resource-backed color table, or NIL if not found.
// FUNCTION GetCTable(ctID: INTEGER): CTabHandle;
// Imaging With QuickDraw 1994, p. 4-92
(true, 0x218) => {
let sp = cpu.read_reg(Register::A7);
let ct_id = bus.read_word(sp) as i16;
if trace_palette_enabled() {
eprintln!(
"[PALETTE] GetCTable id={} current_port=${:08X}",
ct_id, *self.current_port
);
}
let standard_ctable = match ct_id {
1 | 2 | 4 | 8 => Some((ct_id as u16, false)),
// Inside Macintosh: Volume VI (1991), pp. 17-17..17-18:
// pixel depth + 64 selects the enhanced standard color
// table, and must be obtained through GetCTable rather
// than GetResource.
66 => Some((2, true)),
68 => Some((4, true)),
72 => Some((8, true)),
_ => None,
};
let ct_handle = if let Some((depth, enhanced)) = standard_ctable {
self.recent_resource_ctable_fetch = None;
let (std_clut, entry_count) = if enhanced {
Self::standard_mac_enhanced_clut(depth, self.current_hilite_color(bus))
.unwrap()
} else {
Self::standard_mac_indexed_clut(depth).unwrap()
};
let ct_size: u32 = 8 + entry_count as u32 * 8;
let ct_ptr = bus.alloc(ct_size);
// Executor's depth convention (qGWorld.cpp:217,
// qColorutil.cpp bw init at :159): a standard system
// CTab fetched via GetCTable(depth) has ctSeed=depth.
// This lets PICTs authored for the canonical palette
// (also stamped ctSeed=depth) identity-copy via the
// seed-match gates when the destination
// is that same canonical CTab.
// Enhanced tables are derived from the standard table and
// depend on HiliteColor, so they need a fresh seed rather
// than colliding with the canonical depth seed.
let seed = if enhanced {
self.next_color_table_seed()
} else {
depth as u32
};
bus.write_long(ct_ptr, seed);
bus.write_word(ct_ptr + 4, 0); // ctFlags (0 = pixmap color table)
bus.write_word(ct_ptr + 6, entry_count as u16 - 1); // ctSize
for i in 0..entry_count as u32 {
let entry = ct_ptr + 8 + i * 8;
bus.write_word(entry, i as u16);
bus.write_word(entry + 2, std_clut[i as usize][0]);
bus.write_word(entry + 4, std_clut[i as usize][1]);
bus.write_word(entry + 6, std_clut[i as usize][2]);
}
let h = bus.alloc(4);
bus.write_long(h, ct_ptr);
h
} else {
// Try to load 'clut' resource with this ID
let res_type = *b"clut";
if let Some((_, found_ptr)) =
self.find_or_load_resource_any(bus, res_type, ct_id)
{
if trace_palette_enabled() {
let ct_size = usize::from(bus.read_word(found_ptr + 6))
.saturating_add(1)
.min(256);
let sample = |index: usize| -> [u16; 3] {
if index >= ct_size {
return [0, 0, 0];
}
let entry = found_ptr + 8 + (index as u32) * 8;
[
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
]
};
let c0 = sample(0);
let c1 = sample(1);
let c16 = sample(16);
let c42 = sample(42);
let c128 = sample(128);
let c255 = sample(255);
eprintln!(
"[PALETTE] GetCTable id={} -> resource ptr=${:08X} size={} [0]=({:04X},{:04X},{:04X}) [1]=({:04X},{:04X},{:04X}) [16]=({:04X},{:04X},{:04X}) [42]=({:04X},{:04X},{:04X}) [128]=({:04X},{:04X},{:04X}) [255]=({:04X},{:04X},{:04X})",
ct_id,
found_ptr,
ct_size,
c0[0],
c0[1],
c0[2],
c1[0],
c1[1],
c1[2],
c16[0],
c16[1],
c16[2],
c42[0],
c42[1],
c42[2],
c128[0],
c128[1],
c128[2],
c255[0],
c255[1],
c255[2],
);
}
// The 'clut' resource data IS a ColorTable record.
// We need to return a COPY (per IM spec: GetCTable returns a new handle).
let ct_size_val = bus.read_word(found_ptr + 6) as u32; // ctSize
let total = 8 + (ct_size_val + 1) * 8;
let ct_ptr = bus.alloc(total);
for off in 0..total {
let b = bus.read_byte(found_ptr + off);
bus.write_byte(ct_ptr + off, b);
}
bus.write_long(ct_ptr, self.next_color_table_seed());
let h = bus.alloc(4);
bus.write_long(h, ct_ptr);
self.remember_recent_resource_ctable_fetch(ct_id, h);
h
} else {
self.recent_resource_ctable_fetch = None;
if trace_palette_enabled() {
eprintln!("[PALETTE] GetCTable id={} -> not found", ct_id);
}
0
}
};
bus.write_long(sp + 2, ct_handle);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// DisposeCTable ($AA24): CTabHandle → void
// Imaging With QuickDraw 1994 p.4-93: disposes the
// ColorTable record whose handle is passed in `cTable`.
(true, 0x224) => {
let sp = cpu.read_reg(Register::A7);
let ct_handle = bus.read_long(sp);
if ct_handle != 0 {
let ct_ptr = bus.read_long(ct_handle);
bus.free(ct_ptr);
bus.free(ct_handle);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// MakeITable ($AA39)
// Builds an inverse color table from the supplied CTab.
// PROCEDURE MakeITable(cTabH: CTabHandle; iTabH: ITabHandle; res: INTEGER);
// Inside Macintosh Volume V (1986), p. V-142
// MPW Quickdraw.h: EXTERN_API(void) MakeITable(CTabHandle, ITabHandle, short)
// ONEWORDINLINE(0xAA39).
// Stack: SP+0:res(2), SP+2:iTabH(4), SP+6:cTabH(4). Pop 10.
(true, 0x239) => {
let sp = cpu.read_reg(Register::A7);
let res = bus.read_word(sp);
let itab_handle = bus.read_long(sp + 2);
let ctab_handle = bus.read_long(sp + 6);
cpu.write_reg(Register::A7, sp + 10);
self.make_inverse_table(bus, ctab_handle, itab_handle, res);
Ok(())
}
// QDExtensions ($AB1D)
// Dispatches offscreen QuickDraw routines selected by the complete D0 value.
// FUNCTION NewGWorld(VAR offscreenGWorld: GWorldPtr; pixelDepth: INTEGER;
// boundsRect: Rect; cTable: CTabHandle; aGDevice: GDHandle;
// flags: GWorldFlags): QDErr;
// Imaging With QuickDraw (1994), pp. 3-125 to 3-126, 4-102 to 4-103,
// and 6-22 to 6-46.
(true, 0x31D) => {
let sp = cpu.read_reg(Register::A7);
let selector = cpu.read_reg(Register::D0);
let operation = qd_extensions_operation_route(self.current_trap_word, selector);
self.current_selector_operation = operation.map(|route| route.operation_id);
let routine = selector & 0xFFFF;
let param_bytes = (selector >> 16) & 0xFFFF;
match routine {
// NewGWorld ($00160000)
// FUNCTION NewGWorld(VAR offscreenGWorld: GWorldPtr;
// pixelDepth: INTEGER; boundsRect: Rect;
// cTable: CTabHandle; aGDevice: GDHandle;
// flags: GWorldFlags): QDErr;
// Imaging With QuickDraw 1994, 6-22
0x0000 => {
let flags = bus.read_long(sp);
let gdevice_param = bus.read_long(sp + 4);
let ctab_param = bus.read_long(sp + 8);
let bounds_ptr = bus.read_long(sp + 12);
let requested_depth = bus.read_word(sp + 16) as i16;
let gworld_ptr_ptr = bus.read_long(sp + 18);
const NO_NEW_DEVICE_FLAG: u32 = 1 << 1;
let requested_top = bus.read_word(bounds_ptr) as i16;
let requested_left = bus.read_word(bounds_ptr + 2) as i16;
let requested_bottom = bus.read_word(bounds_ptr + 4) as i16;
let requested_right = bus.read_word(bounds_ptr + 6) as i16;
let width =
((requested_right as i32) - (requested_left as i32)).max(1) as u32;
let height =
((requested_bottom as i32) - (requested_top as i32)).max(1) as u32;
let no_new_device = (flags & NO_NEW_DEVICE_FLAG) != 0;
// NewGWorld uses pixelDepth=0 as a "match the intersecting screen
// device" request, but the resulting GWorld uses a local
// coordinate system rooted at (0,0).
// Inside Macintosh Volume VI, 21-13 to 21-15
let main_gdevice = self.ensure_main_gdevice(bus);
let source_gdevice = if requested_depth <= 0 || no_new_device {
if gdevice_param != 0 {
gdevice_param
} else {
main_gdevice
}
} else {
0
};
let depth = if requested_depth <= 0 {
Self::gdevice_pixel_size(bus, source_gdevice).unwrap_or(8)
} else if no_new_device {
Self::gdevice_pixel_size(bus, source_gdevice)
.unwrap_or(requested_depth as u32)
} else {
requested_depth as u32
};
let (top, left, bottom, right) = if requested_depth <= 0 {
(0, 0, height as i16, width as i16)
} else {
(
requested_top,
requested_left,
requested_bottom,
requested_right,
)
};
// Keep offscreen scanlines 16-byte aligned without
// adding padding when the visible width is already
// aligned. Applications can copy complete scanlines
// directly between GWorlds and the screen.
let visible_row_bytes = (width * depth).div_ceil(8);
let row_bytes = visible_row_bytes.div_ceil(16) * 16;
// IM:VI 21-13: noNewDevice uses the supplied GDevice's
// depth and color table; custom cTable requires an
// offscreen device.
let source_ctab_handle = if no_new_device && source_gdevice != 0 {
Self::gdevice_ctab_handle(bus, source_gdevice)
} else if ctab_param != 0 {
ctab_param
} else if source_gdevice != 0 {
Self::gdevice_ctab_handle(bus, source_gdevice)
} else {
0
};
let active_seeded_screen_clut = self
.active_seeded_screen_clut_for_offscreen_clone(
source_gdevice,
ctab_param,
);
let ctab_handle = if no_new_device {
source_ctab_handle
} else if let Some(clut) = active_seeded_screen_clut.as_ref() {
self.allocate_color_table_handle_with_clut(bus, depth, clut, 0x8000)
} else {
self.allocate_gworld_color_table_handle(
bus,
depth,
source_ctab_handle,
0x8000,
)
};
let pixel_buf = bus.alloc(row_bytes * height);
let pixel_buf_handle = bus.alloc(4);
bus.write_long(pixel_buf_handle, pixel_buf);
self.track_handle_ptr(pixel_buf, pixel_buf_handle);
let pixmap = bus.alloc(50);
bus.write_long(pixmap, pixel_buf_handle);
bus.write_word(pixmap + 4, (row_bytes as u16) | 0x8000);
bus.write_word(pixmap + 6, top as u16);
bus.write_word(pixmap + 8, left as u16);
bus.write_word(pixmap + 10, bottom as u16);
bus.write_word(pixmap + 12, right as u16);
bus.write_word(pixmap + 14, 0);
bus.write_word(pixmap + 16, 0);
bus.write_long(pixmap + 18, 0);
bus.write_long(pixmap + 22, 0x00480000);
bus.write_long(pixmap + 26, 0x00480000);
bus.write_word(pixmap + 30, 0);
bus.write_word(pixmap + 32, depth as u16);
bus.write_word(pixmap + 34, 1);
bus.write_word(pixmap + 36, depth as u16);
bus.write_long(pixmap + 38, 0);
bus.write_long(pixmap + 42, ctab_handle); // pmTable
bus.write_long(pixmap + 46, 0);
let pixmap_handle = bus.alloc(4);
bus.write_long(pixmap_handle, pixmap);
let associated_gdevice = if no_new_device {
source_gdevice
} else {
self.create_offscreen_gdevice(
bus,
pixmap_handle,
top,
left,
bottom,
right,
)
};
// Allocate visRgn = bounds rect
let vis_rgn_ptr = bus.alloc(10);
bus.write_word(vis_rgn_ptr, 10);
bus.write_word(vis_rgn_ptr + 2, top as u16);
bus.write_word(vis_rgn_ptr + 4, left as u16);
bus.write_word(vis_rgn_ptr + 6, bottom as u16);
bus.write_word(vis_rgn_ptr + 8, right as u16);
let vis_rgn = bus.alloc(4);
bus.write_long(vis_rgn, vis_rgn_ptr);
// Allocate clipRgn = infinite
let clip_rgn_ptr = bus.alloc(10);
bus.write_word(clip_rgn_ptr, 10);
bus.write_word(clip_rgn_ptr + 2, (-32767_i16) as u16);
bus.write_word(clip_rgn_ptr + 4, (-32767_i16) as u16);
bus.write_word(clip_rgn_ptr + 6, 32767_u16);
bus.write_word(clip_rgn_ptr + 8, 32767_u16);
let clip_rgn = bus.alloc(4);
bus.write_long(clip_rgn, clip_rgn_ptr);
// Build CGrafPort with correct layout
// Imaging With QuickDraw 1994, 4-125
let port = bus.alloc(170);
self.disposed_gworld_portbits.remove(&(port + 2));
bus.write_word(port, 0); // +0 device
bus.write_long(port + 2, pixmap_handle); // +2 portPixMap (handle)
self.cache_portbits_pixmap_handle(bus, port + 2, pixmap_handle);
bus.write_word(port + 6, 0xC000); // +6 portVersion
bus.write_long(port + 8, 0); // +8 grafVars
bus.write_word(port + 12, 0); // +12 chExtra
bus.write_word(port + 14, 0x8000); // +14 pnLocHFrac
bus.write_word(port + 16, top as u16); // +16 portRect.top
bus.write_word(port + 18, left as u16); // +18 portRect.left
bus.write_word(port + 20, bottom as u16); // +20 portRect.bottom
bus.write_word(port + 22, right as u16); // +22 portRect.right
bus.write_long(port + 24, vis_rgn); // +24 visRgn
bus.write_long(port + 28, clip_rgn); // +28 clipRgn
self.init_cgraf_port_defaults(port, bus);
if associated_gdevice != 0 {
self.gworld_devices.insert(port, associated_gdevice);
} else {
self.gworld_devices.remove(&port);
}
self.seed_gworld_pixels_state(pixmap_handle, flags);
if gworld_ptr_ptr != 0 {
bus.write_long(gworld_ptr_ptr, port);
}
if trace_dialog_gworld_enabled() {
let ctab_ptr = if ctab_handle != 0 {
bus.read_long(ctab_handle)
} else {
0
};
let ctab_seed = if ctab_ptr != 0 {
bus.read_long(ctab_ptr)
} else {
0
};
let ctab_entries = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 6).saturating_add(1)
} else {
0
};
eprintln!(
"[DIALOG-GWORLD] NewGWorld port=${:08X} pixmap=${:08X} base=${:08X} bounds=({},{},{},{}) depth={} rowBytes={} flags=${:08X} ctabParam=${:08X} ctab=${:08X} ctabSeed=${:08X} entries={} gdh=${:08X}",
port,
pixmap,
pixel_buf,
top,
left,
bottom,
right,
depth,
row_bytes,
flags,
ctab_param,
ctab_handle,
ctab_seed,
ctab_entries,
associated_gdevice,
);
}
bus.write_word(sp + 22, 0); // noErr
cpu.write_reg(Register::A7, sp + 22);
}
// LockPixels ($00040001)
// FUNCTION LockPixels(pm: PixMapHandle): BOOLEAN;
// Imaging With QuickDraw 1994, 6-26
0x0001 => {
let pmh = bus.read_long(sp);
let locked = self.lock_gworld_pixels(bus, pmh);
bus.write_word(sp + 4, if locked { 0x0100 } else { 0x0000 });
cpu.write_reg(Register::A7, sp + 4);
}
// UnlockPixels ($00040002)
// PROCEDURE UnlockPixels(pm: PixMapHandle);
// Imaging With QuickDraw 1994, 6-27
0x0002 => {
let pmh = bus.read_long(sp);
self.unlock_gworld_pixels(bus, pmh);
cpu.write_reg(Register::A7, sp + 4);
}
// UpdateGWorld ($00160003)
// FUNCTION UpdateGWorld(VAR offscreenGWorld: GWorldPtr;
// pixelDepth: INTEGER; boundsRect: Rect;
// cTable: CTabHandle; aGDevice: GDHandle;
// flags: GWorldFlags): GWorldFlags;
// Imaging With QuickDraw 1994, 6-23
0x0003 => {
let flags = bus.read_long(sp);
let gdevice_param = bus.read_long(sp + 4);
let ctab_param = bus.read_long(sp + 8);
let bounds_ptr = bus.read_long(sp + 12);
let depth_param = bus.read_word(sp + 16) as i16;
let gworld_ptr_ptr = bus.read_long(sp + 18);
const NO_NEW_DEVICE_FLAG: u32 = 1 << 1;
// GWorldFlags output bits - Imaging With QuickDraw 1994, 6-61
const MAP_PIX_FLAG: u32 = 1 << 16; // mapPixBit = 16
const NEW_ROW_BYTES_FLAG: u32 = 1 << 19; // newRowBytesBit = 19
const REALLOC_PIX_FLAG: u32 = 1 << 20; // reallocPixBit = 20
const ALIGN_PIX_FLAG: u32 = 1 << 18; // alignPixBit = 18
const CLIP_PIX_FLAG: u32 = 1 << 28; // clipPixBit = 28
const STRETCH_PIX_FLAG: u32 = 1 << 29; // stretchPixBit = 29
let no_new_device = (flags & NO_NEW_DEVICE_FLAG) != 0;
let requested_top = bus.read_word(bounds_ptr) as i16;
let requested_left = bus.read_word(bounds_ptr + 2) as i16;
let requested_bottom = bus.read_word(bounds_ptr + 4) as i16;
let requested_right = bus.read_word(bounds_ptr + 6) as i16;
let requested_width =
((requested_right as i32) - (requested_left as i32)).max(1) as u32;
let requested_height =
((requested_bottom as i32) - (requested_top as i32)).max(1) as u32;
let port = bus.read_long(gworld_ptr_ptr);
let pixmap_handle = bus.read_long(port + 2);
let pixmap = bus.read_long(pixmap_handle);
let old_ctab_handle = bus.read_long(pixmap + 42);
let old_base = Self::offscreen_pixmap_base_ptr(bus, pixmap);
let stored_base_handle = Self::offscreen_pixmap_base_handle(bus, pixmap);
let old_base_handle = if stored_base_handle != 0 {
stored_base_handle
} else {
self.handle_for_ptr(old_base)
.filter(|&handle| bus.read_long(handle) == old_base)
.unwrap_or(0)
};
let pixels_were_locked = stored_base_handle == 0 && old_base_handle != 0;
let old_rb_raw = bus.read_word(pixmap + 4);
let old_row_bytes = (old_rb_raw & 0x3FFF) as u32;
let old_top = bus.read_word(pixmap + 6) as i16;
let old_left = bus.read_word(pixmap + 8) as i16;
let old_bottom = bus.read_word(pixmap + 10) as i16;
let old_right = bus.read_word(pixmap + 12) as i16;
let old_width = ((old_right as i32) - (old_left as i32)).max(1) as u32;
let old_height = ((old_bottom as i32) - (old_top as i32)).max(1) as u32;
let old_depth = bus.read_word(pixmap + 36) as u32;
let current_gdevice =
self.gworld_devices.get(&port).copied().unwrap_or_default();
let main_gdevice = self.ensure_main_gdevice(bus);
let source_gdevice = if depth_param <= 0 || no_new_device {
if gdevice_param != 0 {
gdevice_param
} else {
main_gdevice
}
} else {
current_gdevice
};
let depth = if depth_param <= 0 {
Self::gdevice_pixel_size(bus, source_gdevice).unwrap_or(old_depth)
} else if no_new_device {
Self::gdevice_pixel_size(bus, source_gdevice)
.unwrap_or(depth_param as u32)
} else {
depth_param as u32
};
// IM:VI 21-13: noNewDevice uses the supplied GDevice's
// depth and color table; custom cTable requires an
// offscreen device.
let source_ctab_handle = if no_new_device && source_gdevice != 0 {
Self::gdevice_ctab_handle(bus, source_gdevice)
} else if ctab_param != 0 {
ctab_param
} else if source_gdevice != 0 {
Self::gdevice_ctab_handle(bus, source_gdevice)
} else {
0
};
let active_seeded_screen_clut = self
.active_seeded_screen_clut_for_offscreen_clone(
source_gdevice,
ctab_param,
);
let (new_top, new_left, new_bottom, new_right) = if depth_param <= 0 {
(0, 0, requested_height as i16, requested_width as i16)
} else {
(
requested_top,
requested_left,
requested_bottom,
requested_right,
)
};
let new_width = ((new_right as i32) - (new_left as i32)).max(1) as u32;
let new_height = ((new_bottom as i32) - (new_top as i32)).max(1) as u32;
let visible_row_bytes = (new_width * depth).div_ceil(8);
let new_row_bytes = visible_row_bytes.div_ceil(16) * 16;
let new_buf_size = new_row_bytes * new_height;
let mut result_flags: u32 = 0;
// If the caller supplies a different color-table handle,
// UpdateGWorld must treat that as a remap request even
// when the ctSeed happens to match. BasiliskII preserves
// the seed convention for copied tables, so comparing the
// seed alone would miss real remaps.
let needs_ctab_sync = source_ctab_handle != old_ctab_handle;
if depth_param <= 0
&& old_width == new_width
&& old_height == new_height
&& (old_top != new_top || old_left != new_left)
{
result_flags |= ALIGN_PIX_FLAG;
}
if new_width != old_width
|| new_height != old_height
|| new_row_bytes != old_row_bytes
|| depth != old_depth
{
// Imaging With QuickDraw 1994 pp. 6-23..6-26:
// UpdateGWorld only updates old pixels when the
// caller asks for clipPix or stretchPix. With no
// preservation flag, "the pixels are not updated";
// if the buffer is reallocated, reallocPix tells
// the caller to reconstruct the image.
let preserve_pixels = (flags & (CLIP_PIX_FLAG | STRETCH_PIX_FLAG)) != 0;
let new_base = bus.alloc(new_buf_size);
// Zero fill first
for i in (0..new_buf_size).step_by(4) {
bus.write_long(new_base + i, 0);
}
if preserve_pixels {
// Approximate clipPix/stretchPix by retaining
// the overlapping source rows; callers still
// see reallocPix/newRowBytes and can redraw
// if they need exact Color QuickDraw scaling.
let copy_rows = old_height.min(new_height);
let copy_bytes_per_row = old_row_bytes.min(new_row_bytes);
for row in 0..copy_rows {
let src = old_base + row * old_row_bytes;
let dst = new_base + row * new_row_bytes;
for b in 0..copy_bytes_per_row {
bus.write_byte(dst + b, bus.read_byte(src + b));
}
}
}
bus.free(old_base);
// Update PixMap fields
if old_base_handle != 0 {
self.untrack_handle_ptr(old_base);
bus.write_long(old_base_handle, new_base);
self.track_handle_ptr(new_base, old_base_handle);
if pixels_were_locked {
bus.write_long(pixmap, new_base);
}
} else {
bus.write_long(pixmap, new_base);
}
bus.write_word(pixmap + 4, (new_row_bytes as u16) | 0x8000); // rowBytes
bus.write_word(pixmap + 32, depth as u16); // pixelSize
bus.write_word(pixmap + 36, depth as u16); // cmpSize
result_flags |= REALLOC_PIX_FLAG;
if new_row_bytes != old_row_bytes {
result_flags |= NEW_ROW_BYTES_FLAG;
}
}
if no_new_device {
bus.write_long(pixmap + 42, source_ctab_handle);
if source_gdevice != 0 {
self.gworld_devices.insert(port, source_gdevice);
}
} else {
let active_ctab_handle = if old_ctab_handle != 0 {
old_ctab_handle
} else {
let allocated =
if let Some(clut) = active_seeded_screen_clut.as_ref() {
self.allocate_color_table_handle_with_clut(
bus, depth, clut, 0x8000,
)
} else {
self.allocate_gworld_color_table_handle(
bus,
depth,
source_ctab_handle,
0x8000,
)
};
bus.write_long(pixmap + 42, allocated);
allocated
};
if let Some(clut) = active_seeded_screen_clut.as_ref() {
let _ = self.overwrite_color_table_handle_with_clut(
bus,
active_ctab_handle,
clut,
0x8000,
);
} else {
let _ = self.overwrite_color_table_handle(
bus,
active_ctab_handle,
depth,
source_ctab_handle,
0x8000,
);
}
if current_gdevice == 0 {
let offscreen_gdevice = self.create_offscreen_gdevice(
bus,
pixmap_handle,
new_top,
new_left,
new_bottom,
new_right,
);
self.gworld_devices.insert(port, offscreen_gdevice);
}
}
if needs_ctab_sync {
result_flags |= MAP_PIX_FLAG;
}
// Update bounds in PixMap
bus.write_word(pixmap + 6, new_top as u16);
bus.write_word(pixmap + 8, new_left as u16);
bus.write_word(pixmap + 10, new_bottom as u16);
bus.write_word(pixmap + 12, new_right as u16);
// Update portRect in CGrafPort
bus.write_word(port + 16, new_top as u16);
bus.write_word(port + 18, new_left as u16);
bus.write_word(port + 20, new_bottom as u16);
bus.write_word(port + 22, new_right as u16);
// Update visRgn to new bounds
let vis_rgn_handle = bus.read_long(port + 24);
if vis_rgn_handle != 0 {
let vis_rgn_ptr = bus.read_long(vis_rgn_handle);
if vis_rgn_ptr != 0 {
bus.write_word(vis_rgn_ptr + 2, new_top as u16);
bus.write_word(vis_rgn_ptr + 4, new_left as u16);
bus.write_word(vis_rgn_ptr + 6, new_bottom as u16);
bus.write_word(vis_rgn_ptr + 8, new_right as u16);
}
}
let attached_gdevice = self.gworld_devices.get(&port).copied().unwrap_or(0);
if attached_gdevice != 0 {
let gd_ptr = bus.read_long(attached_gdevice);
if gd_ptr != 0 {
bus.write_word(gd_ptr + 34, new_top as u16);
bus.write_word(gd_ptr + 36, new_left as u16);
bus.write_word(gd_ptr + 38, new_bottom as u16);
bus.write_word(gd_ptr + 40, new_right as u16);
}
}
if *self.current_port == port {
let current_gdevice = self.gdevice_for_port(bus, port);
self.current_gdevice.with_mut(|selected_gdevice| {
*selected_gdevice = current_gdevice;
});
}
bus.write_long(sp + 22, result_flags);
cpu.write_reg(Register::D0, result_flags);
cpu.write_reg(Register::A7, sp + 22);
}
// DisposeGWorld ($00040004)
// PROCEDURE DisposeGWorld(offscreenGWorld: GWorldPtr);
// Imaging With QuickDraw 1994, 6-25
0x0004 => {
let port = bus.read_long(sp);
self.dispose_gworld_port(cpu, bus, port);
cpu.write_reg(Register::A7, sp + 4);
}
// GetGWorld ($00080005)
// PROCEDURE GetGWorld(VAR port: CGrafPtr; VAR gdh: GDHandle);
// Imaging With QuickDraw 1994, 6-28
0x0005 => {
let gd_ptr = bus.read_long(sp);
let port_ptr = bus.read_long(sp + 4);
let gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
};
if port_ptr != 0 {
bus.write_long(port_ptr, *self.current_port);
}
if gd_ptr != 0 {
bus.write_long(gd_ptr, gdh);
}
if trace_dialog_gworld_enabled() {
eprintln!(
"[DIALOG-GWORLD] GetGWorld port=${:08X} gdh=${:08X}",
*self.current_port, gdh
);
}
cpu.write_reg(Register::A7, sp + 8);
}
// SetGWorld ($00080006)
// PROCEDURE SetGWorld(port: CGrafPtr; gdh: GDHandle);
// Imaging With QuickDraw 1994, 6-29
// SetGWorld internally calls SetPort to update thePort.
// Imaging With QuickDraw 1994, 6-30
0x0006 => {
let new_gd = bus.read_long(sp);
let new_port = bus.read_long(sp + 4);
let gdh = if new_gd != 0 {
new_gd
} else {
self.gdevice_for_port(bus, new_port)
};
if trace_dialog_gworld_enabled() {
eprintln!(
"[DIALOG-GWORLD] SetGWorld port=${:08X} gdh=${:08X}",
new_port, gdh
);
}
self.set_current_port_state(bus, cpu, new_port, Some(gdh));
cpu.write_reg(Register::A7, sp + 8);
}
// CTabChanged ($00040007)
// Notifies Color QuickDraw that a color table has been changed
// directly and its ctSeed needs updating.
// PROCEDURE CTabChanged(ctab: CTabHandle);
// Imaging With QuickDraw 1994, 4-102
0x0007 => {
let ctab_handle = bus.read_long(sp);
self.reseed_color_table_handle(bus, ctab_handle);
cpu.write_reg(Register::A7, sp + 4);
}
// PixPatChanged ($00040008)
// PROCEDURE PixPatChanged(ppat: PixPatHandle);
// Imaging With QuickDraw 1994, 4-103
0x0008 => {
cpu.write_reg(Register::A7, sp + 4);
}
// PortChanged ($00040009)
// PROCEDURE PortChanged(port: GrafPtr);
// Imaging With QuickDraw 1994, 4-103
//
// The app is telling QuickDraw it edited the port's fields
// itself. When the port is a window we track, re-derive the
// window geometry we cache from it — HyperCard resizes its
// card window this way rather than through SizeWindow.
0x0009 => {
let port = bus.read_long(sp);
self.resync_window_geometry_from_port_rect(bus, port);
cpu.write_reg(Register::A7, sp + 4);
}
// GDeviceChanged ($0004000A)
// PROCEDURE GDeviceChanged(gdh: GDHandle);
// Imaging With QuickDraw 1994, 4-103
0x000A => {
cpu.write_reg(Register::A7, sp + 4);
}
// AllowPurgePixels ($0004000B)
0x000B => {
let pmh = bus.read_long(sp);
self.set_gworld_pixels_purgeable(pmh, true);
cpu.write_reg(Register::A7, sp + 4);
}
// NoPurgePixels ($0004000C)
0x000C => {
let pmh = bus.read_long(sp);
self.set_gworld_pixels_purgeable(pmh, false);
cpu.write_reg(Register::A7, sp + 4);
}
// GetPixelsState ($0004000D)
0x000D => {
let pmh = bus.read_long(sp);
bus.write_long(sp + 4, self.gworld_pixels_state(pmh));
cpu.write_reg(Register::A7, sp + 4);
}
// SetPixelsState ($0008000E)
0x000E => {
let state = bus.read_long(sp);
let pmh = bus.read_long(sp + 4);
self.set_gworld_pixels_state(pmh, state);
cpu.write_reg(Register::A7, sp + 8);
}
// GetPixBaseAddr ($0004000F)
// FUNCTION GetPixBaseAddr(pm: PixMapHandle): Ptr;
0x000F | 0x1F18 => {
let mut pmh = bus.read_long(sp);
if (pmh >> 16) == 0x000F {
let shifted_pmh = bus.read_long(sp + 2);
if shifted_pmh != 0 {
pmh = shifted_pmh;
}
}
let pm = if pmh != 0 { bus.read_long(pmh) } else { 0 };
let base_handle = Self::offscreen_pixmap_base_handle(bus, pm);
let base = Self::offscreen_pixmap_base_ptr(bus, pm);
if trace_dialog_gworld_enabled() {
eprintln!(
"[DIALOG-GWORLD] GetPixBaseAddr pmh=${:08X} pm=${:08X} base_handle=${:08X} base=${:08X}",
pmh, pm, base_handle, base
);
}
bus.write_long(sp + 4, base);
cpu.write_reg(Register::A7, sp + 4);
}
// GetGWorldDevice ($00040012)
// FUNCTION GetGWorldDevice(offscreenGWorld: GWorldPtr): GDHandle;
// Inside Macintosh Volume VI (1991), p. 21-18;
// Imaging With QuickDraw (1994), p. 6-33.
// For a regular GrafPort/CGrafPort argument, returns
// the current device rather than MainDevice.
// NewScreenBuffer / NewTempScreenBuffer ($000E0010 / $000E0015)
// FUNCTION NewScreenBuffer(globalRect: Rect; purgeable: Boolean;
// VAR gdh: GDHandle;
// VAR offscreenPixMap: PixMapHandle): QDErr;
// FUNCTION NewTempScreenBuffer(globalRect: Rect; purgeable: Boolean;
// VAR gdh: GDHandle;
// VAR offscreenPixMap: PixMapHandle): QDErr;
// Imaging With QuickDraw (1994), pp. 6-33--6-34.
0x0010 => {
let offscreen_pixmap_out_ptr = bus.read_long(sp);
let gdh_out_ptr = bus.read_long(sp + 4);
let purgeable = bus.read_word(sp + 8) != 0;
let global_rect_ptr = bus.read_long(sp + 10);
let result = self.new_screen_buffer_common(
bus,
global_rect_ptr,
purgeable,
gdh_out_ptr,
offscreen_pixmap_out_ptr,
false,
);
bus.write_word(sp + 14, result as u16);
cpu.write_reg(Register::D0, result);
cpu.write_reg(Register::A7, sp + 14);
}
0x0011 => {
let offscreen_pixmap = bus.read_long(sp);
self.dispose_screen_buffer(bus, offscreen_pixmap);
cpu.write_reg(Register::A7, sp + 4);
}
0x0015 => {
let offscreen_pixmap_out_ptr = bus.read_long(sp);
let gdh_out_ptr = bus.read_long(sp + 4);
let purgeable = bus.read_word(sp + 8) != 0;
let global_rect_ptr = bus.read_long(sp + 10);
let result = self.new_screen_buffer_common(
bus,
global_rect_ptr,
purgeable,
gdh_out_ptr,
offscreen_pixmap_out_ptr,
true,
);
bus.write_word(sp + 14, result as u16);
cpu.write_reg(Register::D0, result);
cpu.write_reg(Register::A7, sp + 14);
}
0x0012 => {
let gworld = bus.read_long(sp);
let current_gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
};
let gdh = self
.gworld_devices
.get(&gworld)
.copied()
.unwrap_or(current_gdh);
if trace_dialog_gworld_enabled() {
eprintln!(
"[DIALOG-GWORLD] GetGWorldDevice port=${:08X} gdh=${:08X}",
gworld, gdh
);
}
bus.write_long(sp + 4, gdh);
cpu.write_reg(Register::A7, sp + 4);
}
// QDDone ($00040013)
// FUNCTION QDDone(port: GrafPtr): Boolean;
// Imaging With QuickDraw 1994, 3-125 to 3-126.
// QDDone reports completion of queued drawing. BasiliskII
// returns TRUE for each query against a live port.
0x0013 => {
let port = bus.read_long(sp);
let done = port != 0;
bus.write_word(sp + 4, if done { 0x0100 } else { 0x0000 });
cpu.write_reg(Register::D0, u32::from(done));
cpu.write_reg(Register::A7, sp + 4);
}
// OffscreenVersion ($00000014)
// function OffscreenVersion: SInt32;
// QuickDraw Reference (Carbon) p. 307;
// QDOffscreen.h declaration.
0x0014 => {
// OffscreenVersion uses a major/minor version word;
// $0100 advertises version 1.0 of 32-Bit QuickDraw.
// Spaceward Ho! checks for at least $0100 before
// enabling its color display path.
let version = 0x0100u32;
bus.write_long(sp, version);
cpu.write_reg(Register::D0, version);
}
// PixMap32Bit ($00040016)
// FUNCTION PixMap32Bit(pmHandle: PixMapHandle): BOOLEAN;
0x0016 => {
let pmh = bus.read_long(sp);
let requires_32bit = if pmh != 0 {
let pm = bus.read_long(pmh);
// QD01 32-Bit QuickDraw defines pmVersion =
// baseAddr32 (4) for 32-bit-addressed PixMaps.
pm != 0 && bus.read_word(pm + 14) == 4
} else {
false
};
bus.write_word(sp + 4, if requires_32bit { 0x0100 } else { 0x0000 });
cpu.write_reg(Register::A7, sp + 4);
}
// GetGWorldPixMap ($00040017)
// FUNCTION GetGWorldPixMap(offscreenGWorld: GWorldPtr): PixMapHandle;
// Imaging With QuickDraw 1994, 6-30
0x0017 => {
let gworld = bus.read_long(sp);
let pmh = if gworld != 0 {
bus.read_long(gworld + 2) // portPixMap handle
} else {
0
};
self.cache_portbits_pixmap_handle(bus, gworld + 2, pmh);
if trace_dialog_gworld_enabled() {
eprintln!(
"[DIALOG-GWORLD] GetGWorldPixMap port=${:08X} pmh=${:08X}",
gworld, pmh
);
}
bus.write_long(sp + 4, pmh);
cpu.write_reg(Register::A7, sp + 4);
}
_ => {
// Unknown selector — use param_bytes to pop stack
eprintln!(
"[TRAP] QDExtensions unknown routine={} params={}",
routine, param_bytes
);
if param_bytes > 0 {
cpu.write_reg(Register::A7, sp + param_bytes);
}
cpu.write_reg(Register::D0, 0);
}
}
Ok(())
}
// Legacy trap aliases (some compilers emit these)
// DisposeGWorld ($AB1F)
// PROCEDURE DisposeGWorld(offscreenGWorld: GWorldPtr);
// Inside Macintosh Volume VI (1991), p. 21-19;
// Imaging With QuickDraw (1994), p. 6-25.
//
// BasiliskII System 7.5.3 does not treat the legacy direct alias
// like the documented public _QDExtensions selector-$0004 path:
// the alias leaves the Pascal argument frame on the stack and
// does not reclaim offscreen-world state. Keep the HLE aligned
// with that measured alias behavior; callers that need the public
// semantics must use _QDExtensions selector $0004.
(true, 0x31F) => Ok(()),
// GetGWorld ($AB1E)
// GetGWorld ($AB1E): Returns current port and GDevice
(true, 0x31E) => {
let sp = cpu.read_reg(Register::A7);
let gd_ptr = bus.read_long(sp);
let port_ptr = bus.read_long(sp + 4);
if port_ptr != 0 {
bus.write_long(port_ptr, *self.current_port);
}
if gd_ptr != 0 {
let gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
};
bus.write_long(gd_ptr, gdh);
}
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// Unknown trap $AB1C — not documented as SetGWorld.
// Per IM:IWQ 1994 pp.6-29..6-30 / IM:VI Table C-3,
// SetGWorld is accessed only via _QDExtensions ($AB1D sel 6).
// $AB1C does not appear in any Apple trap-name table.
// In BasiliskII System 7.5.3, calling $AB1C with a
// (CGrafPtr, GDHandle) stack frame does not update thePort:
// GetPort after the call still returns the prior port.
// We pop 8 bytes to match the observed stack-clean behaviour
// and do not change any port state.
// ($AB1C)
(true, 0x31C) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// LockPixels ($AB04)
// Per IM:VI 17-13 / Imaging With QuickDraw 1994 6-44:
// "You must call LockPixels before drawing to or from
// an offscreen graphics world. ... LockPixels locks
// the offscreen buffer in memory for the duration of
// the drawing. If the offscreen buffer is purgeable
// and has indeed been purged, LockPixels returns FALSE
// to signal that no drawing can be made to the buffer
// memory. At that point, the application should either
// call UpdateGWorld to reallocate the buffer or draw
// directly in the window it represents."
// FUNCTION LockPixels(pm: PixMapHandle): Boolean;
// Inside Macintosh Volume VI, 17-13
//
// Stack: SP+0 pm PixMapHandle (4 bytes), SP+4 result
// Boolean byte in a word-aligned caller slot. Pop 4;
// result at post-pop A7 = pre-call SP+4.
//
// HLE compromise: Systemless doesn't model purgeable
// pixmaps — every PixMap allocated via NewGWorld
// ($AB1D) lives until DisposeGWorld ($AB1E) explicitly
// frees it. So LockPixels always returns TRUE per the
// IM-documented "buffer is locked, drawing can proceed"
// path. Apps that defensively branch `if not
// LockPixels(pm) then UpdateGWorld(...)` always take
// the LockPixels-succeeded branch and proceed to
// CopyBits-from-GWorld correctly.
// LockPixels ($AB04): Pops 4 bytes (PixMapHandle) + writes TRUE to the Boolean result byte per IM:VI 17-13 + Imaging With QuickDraw 6-44 FUNCTION sig. HLE has no purgeable-pixmap axis (every PixMap lives until DisposeGWorld) so always returns TRUE; apps' LockPixels-failure recovery path (UpdateGWorld) never fires but is also unreachable since pixmaps don't get purged.
(true, 0x304) => {
let sp = cpu.read_reg(Register::A7);
let pmh = bus.read_long(sp);
let locked = self.lock_gworld_pixels(bus, pmh);
bus.write_word(sp + 4, if locked { 0x0100 } else { 0x0000 });
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// UnlockPixels ($AB05)
// Per IM:VI 17-13 / Imaging With QuickDraw 1994 6-45:
// "UnlockPixels unlocks the offscreen buffer. Call
// UnlockPixels as soon as the application finishes
// drawing to or from the offscreen pixel map. You
// don't need to call UnlockPixels if LockPixels
// returned FALSE, because LockPixels doesn't lock
// purged pixels. (However, calling UnlockPixels on
// purged pixels does no harm.)"
// PROCEDURE UnlockPixels(pm: PixMapHandle);
// Inside Macintosh Volume VI, 17-13
//
// Stack: SP+0 pm PixMapHandle (4 bytes). Pop 4 bytes.
// No result (PROCEDURE).
//
// LockPixels exposes the fixed pixel pointer through baseAddr;
// UnlockPixels restores the movable handle representation.
// Calling this on NIL or purged pixels remains harmless.
(true, 0x305) => {
let sp = cpu.read_reg(Register::A7);
let pmh = bus.read_long(sp);
self.unlock_gworld_pixels(bus, pmh);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// GetPixDepth ($AB08): PixMapHandle → INTEGER
// GetPixDepth ($AB08): Reads pixelSize from PixMap, except
// for the main-device gdPMap handle where BasiliskII's ROM
// returns 0 instead of the backing PixMap's pixelSize field.
(true, 0x308) => {
let sp = cpu.read_reg(Register::A7);
let pm_handle = bus.read_long(sp);
let depth = if self.main_gdevice_handle != 0 {
let gd_ptr = bus.read_long(self.main_gdevice_handle);
if gd_ptr != 0 && bus.read_long(gd_ptr + 22) == pm_handle {
0u16
} else if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
bus.read_word(pm_ptr + 32)
} else {
8u16
}
} else {
8u16
}
} else if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
bus.read_word(pm_ptr + 32)
} else {
8u16
}
} else {
8u16
};
bus.write_word(sp + 4, depth);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Arc Drawing ==========
// FrameArc ($A8BE)
// PROCEDURE FrameArc(r: Rect; startAngle, arcAngle: INTEGER);
// Inside Macintosh Volume I, I-184
//
// OpenRgn-recording shim. Per IM:I I-184 "Calculations with
// Regions" the arc's outlined region is added when FrameArc is
// called inside OpenRgn; the pen controls drawing. The bbox-approx
// region storage uses the enclosing rect.
// FrameArc ($A8BE): draw_arc(ShapeOp::Frame)
(true, 0x0BE) => {
let sp = cpu.read_reg(Register::A7);
let arc_angle = bus.read_word(sp) as i16;
let start_angle = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_arc(cpu, bus, &r, start_angle, arc_angle, ShapeOp::Frame);
Ok(())
}
// PaintArc ($A8BF)
// PROCEDURE PaintArc(r: Rect; startAngle, arcAngle: INTEGER);
// Inside Macintosh Volume I, I-184
//
// OpenRgn-recording shim — see FrameArc notes above.
// PaintArc ($A8BF): draw_arc(ShapeOp::Paint)
(true, 0x0BF) => {
let sp = cpu.read_reg(Register::A7);
let arc_angle = bus.read_word(sp) as i16;
let start_angle = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_arc(cpu, bus, &r, start_angle, arc_angle, ShapeOp::Paint);
Ok(())
}
// EraseArc ($A8C0)
// PROCEDURE EraseArc(r: Rect; startAngle, arcAngle: INTEGER);
// Inside Macintosh Volume I, I-184
//
// OpenRgn-recording shim — see FrameArc notes above.
// EraseArc ($A8C0): draw_arc(ShapeOp::Erase)
(true, 0x0C0) => {
let sp = cpu.read_reg(Register::A7);
let arc_angle = bus.read_word(sp) as i16;
let start_angle = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_arc(cpu, bus, &r, start_angle, arc_angle, ShapeOp::Erase);
Ok(())
}
// InvertArc ($A8C1)
// PROCEDURE InvertArc(r: Rect; startAngle, arcAngle: INTEGER);
// Inside Macintosh Volume I, I-184
//
// OpenRgn-recording shim — see FrameArc notes above.
// InvertArc ($A8C1): draw_arc(ShapeOp::Invert)
(true, 0x0C1) => {
let sp = cpu.read_reg(Register::A7);
let arc_angle = bus.read_word(sp) as i16;
let start_angle = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_arc(cpu, bus, &r, start_angle, arc_angle, ShapeOp::Invert);
Ok(())
}
// FillArc ($A8C2)
// PROCEDURE FillArc(r: Rect; startAngle, arcAngle: INTEGER; pat: Pattern);
// Inside Macintosh Volume I, I-184
// Stack layout:
// SP+0: pat(4)
// SP+4: arcAngle(2)
// SP+6: startAngle(2)
// SP+8: r(4) → pop 12.
//
// OpenRgn-recording shim — see FillRect notes.
// FillArc ($A8C2): draw_arc(ShapeOp::Fill(pat)); stack is pat_ptr(4)+arcAngle(2)+startAngle(2)+rect_ptr(4)=12, IM:I I-184
(true, 0x0C2) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
let arc_angle = bus.read_word(sp + 4) as i16;
let start_angle = bus.read_word(sp + 6) as i16;
let rect_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
let r = read_rect(bus, rect_ptr);
if self.extend_recording_region(r.top, r.left, r.bottom, r.right) && self.pn_vis < 0 {
return Some(Ok(()));
}
let mut pat = [0u8; 8];
for (i, byte) in pat.iter_mut().enumerate() {
*byte = bus.read_byte(pat_ptr + i as u32);
}
self.draw_arc(cpu, bus, &r, start_angle, arc_angle, ShapeOp::Fill(pat));
Ok(())
}
// ========== Picture Drawing ==========
// DrawPicture ($A8F6)
// PROCEDURE DrawPicture(myPicture: PicHandle; dstRect: Rect);
// SP+0: dstRect(4), SP+4: picHandle(4)
// DrawPicture ($A8F6): Full PICT v1/v2 parser with opcodes in `pict.rs`; supports 1/2/4/8/16/32bpp with dynamic device CLUT color matching
(true, 0x0F6) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let pic_handle = bus.read_long(sp + 4);
let streamed_bytes = match self.prepare_picture_stream(cpu, bus, pic_handle, dst_rect_ptr) {
super::picture_stream::PictureStreamInput::Resident => None,
super::picture_stream::PictureStreamInput::Deferred => return Some(Ok(())),
super::picture_stream::PictureStreamInput::Materialized(bytes) => Some(bytes),
};
if self.begin_picture_callbacks(
cpu,
bus,
pic_handle,
dst_rect_ptr,
streamed_bytes.as_deref(),
) {
return Some(Ok(()));
}
cpu.write_reg(Register::A7, sp + 8);
if streamed_bytes.as_ref().is_some_and(|bytes| bytes.is_empty()) {
return Some(Ok(()));
}
if pic_handle != 0 {
let pic_ptr = bus.read_long(pic_handle);
let dst_top = bus.read_word(dst_rect_ptr) as i16;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16;
// Read current port's pixel storage and bounds for coordinate conversion.
// On a real Mac, DrawPicture draws relative to the current port's local
// coordinate system. The port's bitmap bounds define the mapping from
// local coordinates to pixel memory offsets.
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let port_version = bus.read_word(port.wrapping_add(6));
let is_color = (port_version & 0xC000) != 0;
let (
port_base,
port_rb,
port_bounds_top,
port_bounds_left,
port_w,
port_h,
port_ps,
port_ctab_handle,
) = if is_color {
let pix_map_handle = bus.read_long(port.wrapping_add(2));
let pix_map_ptr = if pix_map_handle != 0 {
bus.read_long(pix_map_handle)
} else {
0
};
if pix_map_ptr != 0 {
// Offscreen PixMap baseAddr is a Handle to pixel
// storage; onscreen PixMap baseAddr is direct.
// Resolve through the helper so DrawPicture writes
// actual pixels rather than clobbering handle cells.
let base = Self::offscreen_pixmap_base_ptr(bus, pix_map_ptr);
let rb = (bus.read_word(pix_map_ptr + 4) & 0x3FFF) as u32;
let bt = bus.read_word(pix_map_ptr + 6) as i16;
let bl = bus.read_word(pix_map_ptr + 8) as i16;
let bb = bus.read_word(pix_map_ptr + 10) as i16;
let br = bus.read_word(pix_map_ptr + 12) as i16;
let ps = bus.read_word(pix_map_ptr + 32);
let cth = bus.read_long(pix_map_ptr + 42); // pmTable
(
base,
rb,
bt,
bl,
(br - bl) as u16,
(bb - bt) as u16,
ps,
cth,
)
} else {
(
self.screen_mode.0,
self.screen_mode.1,
0i16,
0i16,
self.screen_mode.2,
self.screen_mode.3,
self.screen_mode.4,
0u32,
)
}
} else {
let base = bus.read_long(port.wrapping_add(2));
let rb = (bus.read_word(port.wrapping_add(6)) & 0x3FFF) as u32;
let bt = bus.read_word(port.wrapping_add(8)) as i16;
let bl = bus.read_word(port.wrapping_add(10)) as i16;
let bb = bus.read_word(port.wrapping_add(12)) as i16;
let br = bus.read_word(port.wrapping_add(14)) as i16;
// Color QuickDraw draws a basic GrafPort at the main
// screen's actual depth when its baseAddr identifies
// that screen. Match the shape-drawing path instead of
// treating this screen-backed destination as 1bpp.
// Inside Macintosh Volume V, V-122.
let screen_backed = base == self.screen_mode.0
&& rb == self.screen_mode.1
&& matches!(self.screen_mode.4, 2 | 4 | 8);
(
base,
rb,
bt,
bl,
(br - bl) as u16,
(bb - bt) as u16,
if screen_backed { self.screen_mode.4 } else { 1 },
0u32,
)
};
// Read the current port's color table for PICT color remapping.
// DrawPicture should map into the port's logical ColorTable, not the
// transient hardware CLUT state. EV's title art is grayscale PICT
// data rendered while palette fades are in flight; remapping against
// the live hardware palette bakes the instantaneous fade into the
// stored pixels and collapses the image to black/white.
// Imaging With QuickDraw 1994, p. 7-11
let port_clut = self.read_port_clut(bus, port_ctab_handle);
// If dstRect is empty (0,0,0,0), use the picture's own frame
// rect as the destination — matching real Mac DrawPicture behavior.
// Inside Macintosh Volume I, I-190
let (use_top, use_left, use_bottom, use_right) =
if dst_top == 0 && dst_left == 0 && dst_bottom == 0 && dst_right == 0 {
let ft = bus.read_word(pic_ptr + 2) as i16;
let fl = bus.read_word(pic_ptr + 4) as i16;
let fb = bus.read_word(pic_ptr + 6) as i16;
let fr = bus.read_word(pic_ptr + 8) as i16;
(ft, fl, fb, fr)
} else {
(dst_top, dst_left, dst_bottom, dst_right)
};
if !Self::drawpicture_rect_intersects_current_port_clip(
bus, port, use_top, use_left, use_bottom, use_right,
) {
if trace_dialog_draw_enabled() && self.dialog_tracking.is_some() {
if let Some((_, res_type, res_id)) =
self.loaded_handles.get(&pic_handle).copied()
{
eprintln!(
"[DIALOG-DRAW] DrawPicture '{}' {} skipped outside current port clip rect=({},{}..{},{})",
String::from_utf8_lossy(&res_type),
res_id,
use_top,
use_left,
use_bottom,
use_right,
);
} else {
eprintln!(
"[DIALOG-DRAW] DrawPicture skipped outside current port clip rect=({},{}..{},{})",
use_top, use_left, use_bottom, use_right,
);
}
}
return Some(Ok(()));
}
if trace_drawpicture_enabled() {
let res_info = self.loaded_handles.get(&pic_handle).copied();
// Dump first 20 bytes of PICT data to verify integrity
let mut pict_bytes = Vec::new();
for i in 0..20u32 {
pict_bytes.push(bus.read_byte(pic_ptr + i));
}
eprintln!(
"[DRAWPICTURE] handle=${:08X} ptr=${:08X} portBase=${:08X} screenBase=${:08X} rect=({},{}..{},{}) port=${:08X} is_color={} ps={} rb={} res={:?} data={:02X?}",
pic_handle, pic_ptr, port_base, self.screen_mode.0,
use_top, use_left, use_bottom, use_right,
port, is_color, port_ps, port_rb,
res_info.map(|(_, rt, id)| (String::from_utf8_lossy(&rt).to_string(), id)),
pict_bytes,
);
}
if trace_menu_redraw_enabled()
&& trace_menu_redraw_rect_intersects(
use_top, use_left, use_bottom, use_right,
)
{
if let Some((_, res_type, res_id)) =
self.loaded_handles.get(&pic_handle).copied()
{
eprintln!(
"[MENU-REDRAW] DrawPicture '{}' {} handle=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
String::from_utf8_lossy(&res_type),
res_id,
pic_handle,
port_base,
use_top,
use_left,
use_bottom,
use_right,
);
} else {
eprintln!(
"[MENU-REDRAW] DrawPicture handle=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
pic_handle,
port_base,
use_top,
use_left,
use_bottom,
use_right,
);
}
}
if trace_dialog_draw_enabled() && self.dialog_tracking.is_some() {
if let Some((_, res_type, res_id)) =
self.loaded_handles.get(&pic_handle).copied()
{
eprintln!(
"[DIALOG-DRAW] DrawPicture '{}' {} handle=${:08X} current_port=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
String::from_utf8_lossy(&res_type),
res_id,
pic_handle,
*self.current_port,
port_base,
use_top,
use_left,
use_bottom,
use_right,
);
} else {
eprintln!(
"[DIALOG-DRAW] DrawPicture handle=${:08X} current_port=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
pic_handle,
*self.current_port,
port_base,
use_top,
use_left,
use_bottom,
use_right,
);
}
}
if trace_dialog_port_dump_enabled() && self.dialog_tracking.is_some() {
Self::trace_port_snapshot(bus, "DrawPicture-current", *self.current_port);
}
if trace_dialog_port_dump_enabled() && self.dialog_tracking.is_some() {
Self::trace_port_snapshot(bus, "DrawPicture-current", *self.current_port);
}
// Convert dst from port-local coordinates to pixel coordinates
let adj_top = use_top - port_bounds_top;
let adj_left = use_left - port_bounds_left;
let adj_bottom = use_bottom - port_bounds_top;
let adj_right = use_right - port_bounds_left;
if trace_pict_inline_enabled() {
eprintln!(
"[PICT] DrawPicture port=${:08X} portBase=${:08X} portBounds=({},{}..{}W,{}H) adj=({},{}..{},{}) use=({},{}..{},{})",
port, port_base, port_bounds_top, port_bounds_left,
port_w, port_h,
adj_top, adj_left, adj_bottom, adj_right,
use_top, use_left, use_bottom, use_right,
);
}
let port_mode = (port_base, port_rb, port_w, port_h, port_ps);
let dst_clip = Self::drawpicture_current_port_pixel_clip(
bus,
port,
port_bounds_top,
port_bounds_left,
port_w,
port_h,
);
let picture_info = self.loaded_handles.get(&pic_handle).copied();
if trace_title_diag_enabled()
&& self.current_tick() >= 80
&& self.current_tick() <= 110
{
if let Some((_, res_type, res_id)) = picture_info {
eprintln!(
"[TITLE-DIAG] DrawPicture tick={} port=${:08X} base=${:08X} handle=${:08X} type='{}' id={} rect=({},{}..{},{} )",
self.current_tick(),
*self.current_port,
port_base,
pic_handle,
String::from_utf8_lossy(&res_type),
res_id,
use_top,
use_left,
use_bottom,
use_right,
);
} else {
eprintln!(
"[TITLE-DIAG] DrawPicture tick={} port=${:08X} base=${:08X} handle=${:08X} rect=({},{}..{},{} )",
self.current_tick(),
*self.current_port,
port_base,
pic_handle,
use_top,
use_left,
use_bottom,
use_right,
);
}
}
let recent_resource_ctable_fetch = self
.take_recent_drawpicture_resource_ctable_fetch(
port, port_base, port_rb, port_ps,
);
let recent_resource_ctable_clut =
recent_resource_ctable_fetch.as_ref().and_then(|fetch| {
(bus.read_long(fetch.ctab_handle) != 0)
.then(|| self.read_ctab_handle_clut(bus, fetch.ctab_handle))
});
if trace_palette_enabled() {
if let Some(fetch) = recent_resource_ctable_fetch.as_ref() {
eprintln!(
"[PALETTE] DrawPictureUsingFetchedCTable tick={} trap={} port=${:08X} ct_id={} picHandle=${:08X}",
self.current_tick(),
self.trap_count,
port,
fetch.ct_id,
pic_handle,
);
}
}
let streamed_pic_ptr = if let Some(bytes) = streamed_bytes {
let pointer = bus.alloc(bytes.len() as u32);
if pointer == 0 { return Some(Ok(())); }
bus.write_bytes(pointer, &bytes);
Some(pointer)
} else {
self.materialize_recent_spooled_picture(bus, pic_ptr)
};
let draw_pic_ptr = streamed_pic_ptr.unwrap_or(pic_ptr);
let is_screen_picture_target =
port_base == self.screen_mode.0 && port_rb == self.screen_mode.1;
let mut preseeded_screen_from_pict = false;
let mut preseeded_offscreen_from_pict = false;
let mut preseeded_draw_clut: Option<[[u16; 3]; 256]> = None;
if recent_resource_ctable_clut.is_none() {
let peeked_clut =
super::pict::peek_initial_packbits_clut(bus, draw_pic_ptr);
if let Some(peeked_clut) = peeked_clut {
if is_screen_picture_target {
if let Some((raw_pict_array, pict_clut_array)) =
Self::picture_clut_arrays(
&self.color_manager_clut,
&peeked_clut,
)
{
if Self::should_seed_screen_palette_from_pict(
&raw_pict_array,
&self.color_manager_clut,
) && !pict_seed_clut_disabled()
{
self.device_clut.replace(pict_clut_array);
self.color_manager_clut.replace(pict_clut_array);
self.seeded_picture_palette = pict_clut_array;
self.seeded_picture_palette_until_tick =
self.current_tick().saturating_add(48);
self.sync_canonical_offscreen_ctabs_to_clut(
bus,
&pict_clut_array,
);
preseeded_draw_clut = Some(pict_clut_array);
preseeded_screen_from_pict = true;
}
}
} else if port_ps == 8 {
if let Some((raw_pict_array, pict_clut_array)) =
Self::picture_clut_arrays(&port_clut, &peeked_clut)
{
if Self::should_preserve_offscreen_picture_indices_from_pict(
&raw_pict_array,
&port_clut,
&self.color_manager_clut,
) {
if port_ctab_handle != 0 {
let ctab_ptr = bus.read_long(port_ctab_handle);
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let logical_screen_clut = *self.color_manager_clut;
let _ = self.overwrite_color_table_handle_with_clut(
bus,
port_ctab_handle,
&logical_screen_clut,
ct_flags,
);
}
preseeded_draw_clut = Some(raw_pict_array);
preseeded_offscreen_from_pict = true;
} else if Self::should_seed_screen_palette_from_pict(
&raw_pict_array,
&port_clut,
) && !pict_seed_clut_disabled()
{
if port_ctab_handle != 0 {
let ctab_ptr = bus.read_long(port_ctab_handle);
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let _ = self.overwrite_color_table_handle_with_clut(
bus,
port_ctab_handle,
&pict_clut_array,
ct_flags,
);
}
preseeded_draw_clut = Some(pict_clut_array);
preseeded_offscreen_from_pict = true;
}
}
}
}
}
// Always use the stable Color Manager CLUT for PICT rendering.
// Using device_clut during seeded-palette fades would bake
// transient palette indices into the framebuffer that become
// wrong after the palette reverts to standard system colors.
// Inside Macintosh: Imaging With QuickDraw 1994, p. 7-14
let selected_draw_port_clut = recent_resource_ctable_clut
.as_ref()
.or(preseeded_draw_clut.as_ref())
.unwrap_or(&port_clut);
// PICT color matching must only consider indices the
// destination depth can represent. `read_port_clut`
// overlays a short 2/4-bit CTable on the logical 8-bit
// table, so leaving its inherited tail visible lets
// matching choose indices above 3/15; packed writes then
// truncate those indices into unrelated colors.
let packed_draw_port_clut = matches!(port_ps, 1 | 2 | 4).then(|| {
let mut clut = *selected_draw_port_clut;
let entry_count = 1usize << port_ps;
let terminal = clut[entry_count - 1];
clut[entry_count..].fill(terminal);
clut
});
let draw_port_clut = packed_draw_port_clut
.as_ref()
.unwrap_or(selected_draw_port_clut);
if !is_screen_picture_target {
if let (Some(fetch), Some(fetch_clut)) = (
recent_resource_ctable_fetch.as_ref(),
recent_resource_ctable_clut.as_ref(),
) {
self.apply_fetched_ctable_to_offscreen_drawpicture_port(
bus,
port,
port_ctab_handle,
fetch,
fetch_clut,
);
}
}
let picture_bytes = bus
.get_alloc_size(draw_pic_ptr)
.or_else(|| bus.get_alloc_size(pic_ptr))
.unwrap_or(0);
let mut cost_top = i32::from(adj_top).max(0);
let mut cost_left = i32::from(adj_left).max(0);
let mut cost_bottom = i32::from(adj_bottom).min(i32::from(port_h));
let mut cost_right = i32::from(adj_right).min(i32::from(port_w));
if let Some(dst_clip) = dst_clip.as_ref() {
let (clip_top, clip_left, clip_bottom, clip_right) = dst_clip.rect();
cost_top = cost_top.max(clip_top);
cost_left = cost_left.max(clip_left);
cost_bottom = cost_bottom.min(clip_bottom);
cost_right = cost_right.min(clip_right);
}
let cost_width = cost_right.saturating_sub(cost_left);
let cost_height = cost_bottom.saturating_sub(cost_top);
self.add_hle_tick_cost(Self::draw_picture_tick_cost(
cost_width as u32,
cost_height as u32,
picture_bytes,
));
let device_ct_seed =
Self::ctab_seed(bus, self.current_gdevice_ctab_handle(bus)).unwrap_or(0);
let (ok, pict_clut) = super::pict::draw_picture(
bus,
draw_pic_ptr,
adj_top,
adj_left,
adj_bottom,
adj_right,
port_mode,
draw_port_clut,
device_ct_seed,
dst_clip.as_ref(),
);
if trace_palette_enabled() {
let fetch_ctab_handle_nonzero = recent_resource_ctable_fetch
.as_ref()
.map(|f| bus.read_long(f.ctab_handle) != 0)
.unwrap_or(false);
eprintln!(
"[PALETTE] DrawPicture-seed-gate tick={} ok={} port_ps={} port_base=${:08X} screen_base=${:08X} port_rb={} screen_rb={} recent_fetch={} fetch_clut={} ctab_nonzero={} pict_clut={} picHandle=${:08X}",
self.current_tick(), ok, port_ps, port_base,
self.screen_mode.0, port_rb, self.screen_mode.1,
recent_resource_ctable_fetch.is_some(),
recent_resource_ctable_clut.is_some(),
fetch_ctab_handle_nonzero,
pict_clut.is_some(),
pic_handle,
);
}
if ok && port_ps == 8 && is_screen_picture_target {
if let (Some(fetch), Some(fetch_clut)) = (
recent_resource_ctable_fetch.as_ref(),
recent_resource_ctable_clut.as_ref(),
) {
self.seed_screen_palette_from_picture_clut(
bus,
pic_handle,
draw_pic_ptr,
fetch_clut,
Some(fetch.ct_id),
);
} else if !preseeded_screen_from_pict {
if let Some(pict_clut) = pict_clut.as_ref() {
if let Some((raw_pict_array, pict_clut_array)) =
Self::picture_clut_arrays(&self.color_manager_clut, pict_clut)
{
if Self::should_seed_screen_palette_from_pict(
&raw_pict_array,
&self.color_manager_clut,
) && !pict_seed_clut_disabled()
{
if std::env::var_os("SYSTEMLESS_TRACE_CM_WRITE").is_some() {
let cm_before = self.color_manager_clut[0];
let pict0 = pict_clut_array[0];
eprintln!(
"[CM-WRITE] PictSeed@6097 tick={} cm[0]=({:04X},{:04X},{:04X}) <- pict[0]=({:04X},{:04X},{:04X})",
self.current_tick(), cm_before[0], cm_before[1], cm_before[2], pict0[0], pict0[1], pict0[2]
);
}
self.device_clut.replace(pict_clut_array);
self.color_manager_clut.replace(pict_clut_array);
self.seeded_picture_palette = pict_clut_array;
self.seeded_picture_palette_until_tick =
self.current_tick().saturating_add(48);
self.sync_canonical_offscreen_ctabs_to_clut(
bus,
&pict_clut_array,
);
// The first pass just drew against the port's
// pre-seed logical table. Replay the picture
// once against the newly-seeded screen CLUT so
// direct screen draws land the same indices an
// offscreen GWorld + later CopyBits would show.
let device_ct_seed = Self::ctab_seed(
bus,
self.current_gdevice_ctab_handle(bus),
)
.unwrap_or(0);
let _ = super::pict::draw_picture(
bus,
draw_pic_ptr,
adj_top,
adj_left,
adj_bottom,
adj_right,
port_mode,
&self.device_clut,
device_ct_seed,
dst_clip.as_ref(),
);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] SeedFromPicture tick={} picHandle=${:08X} picPtr=${:08X} cm[0]=({:04X},{:04X},{:04X}) cm[1]=({:04X},{:04X},{:04X}) cm[16]=({:04X},{:04X},{:04X}) cm[42]=({:04X},{:04X},{:04X}) cm[128]=({:04X},{:04X},{:04X}) cm[255]=({:04X},{:04X},{:04X})",
self.current_tick(),
pic_handle,
pic_ptr,
self.color_manager_clut[0][0],
self.color_manager_clut[0][1],
self.color_manager_clut[0][2],
self.color_manager_clut[1][0],
self.color_manager_clut[1][1],
self.color_manager_clut[1][2],
self.color_manager_clut[16][0],
self.color_manager_clut[16][1],
self.color_manager_clut[16][2],
self.color_manager_clut[42][0],
self.color_manager_clut[42][1],
self.color_manager_clut[42][2],
self.color_manager_clut[128][0],
self.color_manager_clut[128][1],
self.color_manager_clut[128][2],
self.color_manager_clut[255][0],
self.color_manager_clut[255][1],
self.color_manager_clut[255][2]
);
}
}
}
}
}
} else if ok && port_ps == 8 && !preseeded_offscreen_from_pict {
if let Some(pict_clut) = pict_clut.as_ref() {
if let Some((raw_pict_array, pict_clut_array)) =
Self::picture_clut_arrays(&port_clut, pict_clut)
{
if Self::should_preserve_offscreen_picture_indices_from_pict(
&raw_pict_array,
&port_clut,
&self.color_manager_clut,
) {
if port_ctab_handle != 0 {
let ctab_ptr = bus.read_long(port_ctab_handle);
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let logical_screen_clut = *self.color_manager_clut;
let _ = self.overwrite_color_table_handle_with_clut(
bus,
port_ctab_handle,
&logical_screen_clut,
ct_flags,
);
}
let device_ct_seed =
Self::ctab_seed(bus, self.current_gdevice_ctab_handle(bus))
.unwrap_or(0);
let _ = super::pict::draw_picture(
bus,
draw_pic_ptr,
adj_top,
adj_left,
adj_bottom,
adj_right,
port_mode,
&raw_pict_array,
device_ct_seed,
dst_clip.as_ref(),
);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] PreserveOffscreenPictureIndices tick={} port=${:08X} picHandle=${:08X} rgb16=({:04X},{:04X},{:04X}) rgb42=({:04X},{:04X},{:04X}) rgb128=({:04X},{:04X},{:04X})",
self.current_tick(),
port,
pic_handle,
raw_pict_array[16][0],
raw_pict_array[16][1],
raw_pict_array[16][2],
raw_pict_array[42][0],
raw_pict_array[42][1],
raw_pict_array[42][2],
raw_pict_array[128][0],
raw_pict_array[128][1],
raw_pict_array[128][2],
);
}
} else if Self::should_seed_screen_palette_from_pict(
&raw_pict_array,
&port_clut,
) && !pict_seed_clut_disabled()
{
if port_ctab_handle != 0 {
let ctab_ptr = bus.read_long(port_ctab_handle);
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let _ = self.overwrite_color_table_handle_with_clut(
bus,
port_ctab_handle,
&pict_clut_array,
ct_flags,
);
}
let device_ct_seed =
Self::ctab_seed(bus, self.current_gdevice_ctab_handle(bus))
.unwrap_or(0);
let _ = super::pict::draw_picture(
bus,
draw_pic_ptr,
adj_top,
adj_left,
adj_bottom,
adj_right,
port_mode,
&pict_clut_array,
device_ct_seed,
dst_clip.as_ref(),
);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] SeedOffscreenFromPicture tick={} port=${:08X} ctab=${:08X} picHandle=${:08X} rgb16=({:04X},{:04X},{:04X}) rgb42=({:04X},{:04X},{:04X}) rgb128=({:04X},{:04X},{:04X})",
self.current_tick(),
port,
port_ctab_handle,
pic_handle,
pict_clut_array[16][0],
pict_clut_array[16][1],
pict_clut_array[16][2],
pict_clut_array[42][0],
pict_clut_array[42][1],
pict_clut_array[42][2],
pict_clut_array[128][0],
pict_clut_array[128][1],
pict_clut_array[128][2],
);
}
}
}
}
}
if let Some(streamed_pic_ptr) = streamed_pic_ptr {
bus.free(streamed_pic_ptr);
}
if trace_drawpicture_enabled() {
// Use wide signed coordinates before bounds-checked sampling.
let probe_y = (i32::from(adj_top) + i32::from(adj_bottom)) / 2;
let probe_x = (i32::from(adj_left) + i32::from(adj_right)) / 2;
let probe2_y = i32::from(adj_top) + 10;
let probe2_x = i32::from(adj_left) + 10;
let probe_val = drawpicture_trace_pixel(bus, port_mode, probe_y, probe_x);
let probe2_val = drawpicture_trace_pixel(bus, port_mode, probe2_y, probe2_x);
eprintln!(
"[DRAWPICTURE] result ok={} adj=({},{}..{},{}) port_mode=({:08X},{},{},{},{}) probe@({},{})={:?} probe2@({},{})={:?}",
ok, adj_top, adj_left, adj_bottom, adj_right,
port_mode.0, port_mode.1, port_mode.2, port_mode.3, port_mode.4,
probe_y, probe_x, probe_val,
probe2_y, probe2_x, probe2_val,
);
}
if trace_menu_redraw_enabled() {
let port_info = CopyBitmapInfo {
base: port_base,
row_bytes: port_rb,
bounds_top: port_bounds_top,
bounds_left: port_bounds_left,
bounds_bottom: port_bounds_top + port_h as i16,
bounds_right: port_bounds_left + port_w as i16,
pixel_size: port_ps as u32,
ctab_handle: port_ctab_handle,
};
for (label, probe_y, probe_x) in trace_menu_probe_points() {
if trace_menu_rect_contains_point(
use_top, use_left, use_bottom, use_right, probe_y, probe_x,
) {
eprintln!(
"[MENU-REDRAW] DrawPicture probe={} pixel={:?}",
label,
Self::read_bitmap_pixel(bus, &port_info, probe_y, probe_x),
);
}
}
}
if ok && port_base == self.screen_mode.0 {
self.refresh_dialog_saved_pixels_after_screen_draw_clipped(
bus,
*self.current_port,
(
use_top.saturating_sub(port_bounds_top),
use_left.saturating_sub(port_bounds_left),
use_bottom.saturating_sub(port_bounds_top),
use_right.saturating_sub(port_bounds_left),
),
dst_clip.as_ref(),
);
self.refresh_visible_dialog_snapshot_after_bulk_port_draw(
bus,
*self.current_port,
(
use_top.saturating_sub(port_bounds_top),
use_left.saturating_sub(port_bounds_left),
use_bottom.saturating_sub(port_bounds_top),
use_right.saturating_sub(port_bounds_left),
),
);
}
let _ = ok;
}
Ok(())
}
// OpenPicture ($A8F3)
// Starts recording drawing operations into a picture.
// Drawing commands between OpenPicture and ClosePicture execute
// in the current port and are also saved for later playback.
// FUNCTION OpenPicture(picFrame: Rect): PicHandle;
// Inside Macintosh Volume I, I-189
// OpenPicture ($A8F3): Allocates picture handle, writes header
(true, 0x0F3) => {
let sp = cpu.read_reg(Register::A7);
let frame_ptr = bus.read_long(sp);
let frame_top = bus.read_word(frame_ptr) as i16;
let frame_left = bus.read_word(frame_ptr + 2) as i16;
let frame_bottom = bus.read_word(frame_ptr + 4) as i16;
let frame_right = bus.read_word(frame_ptr + 6) as i16;
// Allocate a minimal Picture header (will be replaced on ClosePicture)
let pic = bus.alloc(12);
let handle = bus.alloc(4);
bus.write_long(handle, pic);
// Write picFrame into the picture header
bus.write_word(pic, 0); // picSize placeholder
bus.write_word(pic + 2, frame_top as u16);
bus.write_word(pic + 4, frame_left as u16);
bus.write_word(pic + 6, frame_bottom as u16);
bus.write_word(pic + 8, frame_right as u16);
self.recording_picture = Some((
handle,
frame_top,
frame_left,
frame_bottom,
frame_right,
Vec::new(),
));
self.recording_picture_bitmap = None;
eprintln!(
"[TRAP] OpenPicture: handle=${:08X} frame=({},{},{},{})",
handle, frame_top, frame_left, frame_bottom, frame_right
);
bus.write_long(sp + 4, handle);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ClosePicture ($A8F4)
// Ends picture recording. Finalizes saved drawing commands; an
// empty recording retains the historical bitmap-snapshot fallback.
// PROCEDURE ClosePicture;
// Inside Macintosh Volume I, I-189
// ClosePicture ($A8F4): Finalizes a PICT v2 command stream
(true, 0x0F4) => {
if let Some((handle, top, left, bottom, right, commands)) =
self.recording_picture.take()
{
let picture = if let Some(mut snapshot) = self.recording_picture_bitmap.take() {
let size = u16::try_from(snapshot.len()).unwrap_or(0);
snapshot[0..2].copy_from_slice(&size.to_be_bytes());
for (index, value) in [top, left, bottom, right].into_iter().enumerate() {
snapshot[2 + index * 2..4 + index * 2].copy_from_slice(&(value as u16).to_be_bytes());
}
Some(snapshot)
} else if commands.is_empty() {
let mut source = self.resolve_copy_bitmap(bus, *self.current_port + 2);
if source.base == 0
|| source.base == u32::MAX
|| source.row_bytes == 0
|| source.pixel_size == 0
{
let (base, row_bytes, width, height, pixel_size) = self.screen_mode;
source = CopyBitmapInfo {
base,
row_bytes,
bounds_top: 0,
bounds_left: 0,
bounds_bottom: height as i16,
bounds_right: width as i16,
pixel_size: u32::from(pixel_size),
ctab_handle: 0,
};
}
let source_clut = if source.ctab_handle != 0 {
self.read_port_clut(bus, source.ctab_handle)
} else {
*self.device_clut
};
Self::encode_bitmap_copy_pict(
bus,
source,
&source_clut,
(top, left, bottom, right),
(top, left, bottom, right),
0,
)
} else {
Some(Self::encode_recorded_picture_pict(
top, left, bottom, right, commands,
))
};
if let Some(picture) = picture {
let old_pic = bus.read_long(handle);
let pic = bus.alloc(picture.len() as u32);
bus.write_bytes(pic, &picture);
bus.write_long(handle, pic);
if old_pic != 0 {
bus.free(old_pic);
}
// A custom putPicProc receives the picture stream;
// the application already owns its size and frame
// header. Tail-call it with the finalized opcode bytes.
let port = *self.current_port;
if picture.len() > 10 && Self::guest_range_in_ram(bus, port, 108)
{
let procs = bus.read_long(port + 104);
if procs != 0 && Self::guest_range_in_ram(bus, procs, 52) {
let proc = bus.read_long(procs + 48);
if proc != 0 && bus.system_trap_gateway(0xA8F0) != Some(proc) {
if picture.len() - 10 > i16::MAX as usize {
self.begin_picture_write(cpu, bus, proc, pic + 10, picture.len() - 10);
return Some(Ok(()));
}
let return_pc = cpu.read_reg(Register::PC);
let mut callback_sp = cpu.read_reg(Register::A7);
callback_sp = callback_sp.wrapping_sub(4);
bus.write_long(callback_sp, pic + 10);
callback_sp = callback_sp.wrapping_sub(2);
bus.write_word(callback_sp, (picture.len() - 10) as u16);
callback_sp = callback_sp.wrapping_sub(4);
bus.write_long(callback_sp, return_pc);
cpu.write_reg(Register::A7, callback_sp);
cpu.write_reg(Register::PC, proc);
}
}
}
eprintln!(
"[TRAP] ClosePicture: finalized {}x{} picture ({} bytes) for handle=${:08X}",
right - left,
bottom - top,
picture.len(),
handle
);
}
}
Ok(())
}
// KillPicture ($A8F5)
// Releases the memory used by the specified picture.
// PROCEDURE KillPicture(myPicture: PicHandle);
// Inside Macintosh Volume I, I-189
//
// KillPicture ($A8F5): Frees picture data + handle per IM:I I-189
(true, 0x0F5) => {
let sp = cpu.read_reg(Register::A7);
let pic_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if pic_handle != 0 {
let pic_ptr = bus.read_long(pic_handle);
if pic_ptr != 0 {
bus.free(pic_ptr);
}
bus.free(pic_handle);
}
Ok(())
}
// ========== Color QuickDraw Extended ==========
// GetCTSeed ($AA28)
// FUNCTION GetCTSeed: LONGINT;
// Inside Macintosh Volume V (1986), p. V-143 (Color
// Manager — Color Table Management — GetCTSeed). MPW
// Universal Headers Quickdraw.h:
// EXTERN_API( long ) GetCTSeed(void) ONEWORDINLINE(0xAA28);
//
// Pop-0 + 4-byte LONGINT result-slot calling convention
// (Tool-bit Pascal FUNCTION): caller pre-pushes a 4-byte
// result slot (A7 -= 4), trap writes the LONGINT word at
// [A7] without popping any argument frame (pop-0), caller
// pops the 4-byte slot (A7 += 4) — net A7 zero across the
// C-level call.
//
// Per IM:V V-143 the returned seed is guaranteed to be
// greater than the predefined constant `minSeed` (= 1023)
// and is intended for use in the ctSeed field of a custom
// color table so the table is recognised as distinct
// during color table translation. Absolute seed values
// differ from BII — BII's ROM Color Manager has its own
// internal counter initialised above minSeed at boot while
// Systemless HLE counts monotonically from 1 via
// `next_color_table_seed`. Both engines share the
// calling convention and the "non-zero return" envelope.
(true, 0x228) => {
let sp = cpu.read_reg(Register::A7);
bus.write_long(sp, self.next_color_table_seed());
Ok(())
}
// QDError ($AA40)
// FUNCTION QDError: INTEGER;
// Inside Macintosh Volume V (1986), p. V-145 (Color Manager
// — Error Handling — QDError); Imaging With QuickDraw
// (1994), pp. 4-94 to 4-95. MPW Universal Headers
// Quickdraw.h: EXTERN_API( short ) QDError(void)
// ONEWORDINLINE(0xAA40).
//
// Pop-0 + 2-byte result-slot calling convention (Tool-bit
// Pascal FUNCTION): caller pre-pushes a 2-byte result slot
// (A7 -= 2), trap writes the INTEGER word at [A7] without
// popping any argument frame, caller pops the 2-byte slot
// (A7 += 2) — net A7 zero across the C-level call.
//
// Per IM:V V-145 QDError returns the error result from the last
// applicable QuickDraw or Color Manager call. The process owns
// that result so a Mixed Mode caller observes errors posted by
// either CPU adapter immediately.
//
// Contract-test coverage in this file (mod tests):
// quickdraw::tests::qderror_returns_noerr_in_function_result_slot_without_stack_pop
// quickdraw::tests::qderror_stub_preserves_general_registers_while_writing_result_slot
// quickdraw::tests::qderror_pascal_function_preserves_stack_across_five_calls
(true, 0x240) => {
let sp = cpu.read_reg(Register::A7);
bus.write_word(sp, *self.quickdraw_error as u16);
Ok(())
}
// SetEntries ($AA3F)
// PROCEDURE SetEntries(start, count: INTEGER; aTable: CSpecArray);
// Inside Macintosh Volume V (1986), p. V-143 (Color Manager —
// Color Manager Routines — SetEntries). MPW Universal Headers
// Quickdraw.h: EXTERN_API(void) SetEntries(short start,
// short count, CSpecArray aTable) ONEWORDINLINE(0xAA3F).
//
// 8-byte on-stack arg frame (Tool-bit Pascal PROCEDURE):
// SP+0: aTable (4-byte CSpecArray pointer, pushed last)
// SP+4: count (2-byte INTEGER, zero-based last index)
// SP+6: start (2-byte INTEGER, pushed first)
// No FUNCTION result slot. Trap pops 8 bytes.
//
// Sequence mode (start >= 0): writes count+1 entries to CLUT
// indices start..start+count; ColorSpec.value fields are
// ignored. Index mode (start == -1): each ColorSpec.value
// names the destination CLUT index.
//
// For the absolute device-CLUT bulk update, BII walks the
// active gDevice's CLUT per IM:V V-143 while Systemless
// updates device_clut and reseeds the current GDevice
// ColorTable.
//
// Contract-test coverage in this file (mod tests):
// quickdraw::tests::setentries_pascal_procedure_preserves_stack_across_five_calls
(true, 0x23F) => {
let sp = cpu.read_reg(Register::A7);
let trap_pc = cpu.read_reg(Register::PC).wrapping_sub(2);
let table_ptr = bus.read_long(sp);
let count = bus.read_word(sp + 4) as i16;
let start = bus.read_word(sp + 6) as i16;
cpu.write_reg(Register::A7, sp + 8);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] SetEntries-call pc=${:08X} a5=${:08X} table=${:08X} start={} count={}",
trap_pc, cpu.read_reg(Register::A5), table_ptr, start, count
);
}
// Apply the palette BEFORE logging so screenshots captured at
// the screen_event_count increment see the updated CLUT.
self.apply_set_entries_with_gdevice(bus, table_ptr, start, count);
let safe_count = if count < 0 { 255 } else { count.min(255) };
// Hour-88 fade trace: when SetEntries writes 0AAA to
// first entry (last fade-down step on Systemless before the
// divergence), enable tracing the next 30 traps to see
// what EV does after the fade step.
if trace_fade_branch_enabled() && safe_count >= 255 && start == 0 {
let first_r = bus.read_word(table_ptr + 2);
if first_r == 0x0AAA {
eprintln!(
"[FADE-TRACE] SetEntries wrote 0AAA at tick={} pc=${:08X}",
self.current_tick(), trap_pc
);
self.fade_trace_remaining = 30;
}
}
if let Err(err) = self.record_trace_event(
bus,
trap_pc,
"set_entries",
Self::trace_palette_field_map(bus, table_ptr, start, safe_count),
true,
) {
return Some(Err(err));
}
Ok(())
}
// GetCIcon ($AA1E)
// FUNCTION GetCIcon(iconID: INTEGER): CIconHandle;
// Inside Macintosh Volume V (1986), p. V-76 (Color QuickDraw —
// Operations on Color Icons — GetCIcon): "allocates a CIcon
// data structure and initializes it using the information in
// the resource of type 'cicn' with the specified ID. It
// returns the handle to the icon's data structure. If the
// specified resource isn't found, a NIL handle is returned."
//
// MPW Universal Headers Icons.h declares:
// EXTERN_API(CIconHandle) GetCIcon(SInt16 iconID)
// ONEWORDINLINE(0xAA1E);
//
// Tool-bit Pascal FUNCTION ABI: caller pre-pushes a 4-byte
// CIconHandle result slot, then pushes a 2-byte iconID
// INTEGER, trap pops the 2-byte arg and writes the handle
// to the 4-byte result slot at the post-pop SP, caller pops
// the slot. Net A7 effect across the C-level call is zero.
//
// Behaviour:
// * Pascal FUNCTION calling convention (A7-balanced
// across the C-level call sequence).
// * Miss-returns-NIL contract per IM:V V-76 ("If the
// specified resource isn't found, a NIL handle is
// returned").
// * Present-resource calls allocate a fresh CIcon copy on
// each hit and seed iconData with a private pixel
// buffer copied from the inline bytes after the
// ColorTable.
(true, 0x21E) => {
let sp = cpu.read_reg(Register::A7);
let icon_id = bus.read_word(sp) as i16;
let params = crate::cursor_manager::evaluate_get_cicon_parameters(icon_id);
let handle = if let Some((_, resource_ptr)) =
self.find_or_load_resource_any(bus, *b"cicn", params.icon_id)
{
let resource_size = bus.get_alloc_size(resource_ptr).unwrap_or(0);
if resource_size == 0 {
0
} else {
let icon_ptr = bus.alloc(resource_size);
if icon_ptr == 0 {
0
} else {
let resource_bytes =
bus.read_bytes(resource_ptr, resource_size as usize);
bus.write_bytes(icon_ptr, &resource_bytes);
let resource_end = icon_ptr.saturating_add(resource_size);
let pm_top = bus.read_word(icon_ptr + 6) as i16;
let pm_bottom = bus.read_word(icon_ptr + 10) as i16;
let icon_h = (pm_bottom - pm_top).max(0) as u32;
let mask_rb = (bus.read_word(icon_ptr + 54) & 0x3FFF) as u32;
let bmap_rb = (bus.read_word(icon_ptr + 68) & 0x3FFF) as u32;
let mask_size = mask_rb * icon_h;
let bmap_size = bmap_rb * icon_h;
let mask_data_ptr = icon_ptr + 82;
let bmap_data_ptr = mask_data_ptr + mask_size;
let ctab_ptr = icon_ptr + 82 + mask_size + bmap_size;
let ctab_header_valid = ctab_ptr
.checked_add(8)
.is_some_and(|end| end <= resource_end);
let ctab_total_bytes = if ctab_header_valid {
let ct_size = bus.read_word(ctab_ptr + 6) as u32;
8 + (ct_size + 1) * 8
} else {
0
};
let ctab_valid = ctab_total_bytes != 0
&& ctab_ptr
.checked_add(ctab_total_bytes)
.is_some_and(|end| end <= resource_end);
let inline_pixel_ptr = if ctab_valid {
ctab_ptr + ctab_total_bytes
} else {
resource_end
};
let pixel_len = resource_end.saturating_sub(inline_pixel_ptr);
let mut allocation_failed = false;
let icon_data_handle = if pixel_len > 0 {
let pixel_ptr = bus.alloc(pixel_len);
if pixel_ptr == 0 {
bus.free(icon_ptr);
allocation_failed = true;
0
} else {
let pixel_bytes =
bus.read_bytes(inline_pixel_ptr, pixel_len as usize);
bus.write_bytes(pixel_ptr, &pixel_bytes);
let pixel_handle = bus.alloc(4);
if pixel_handle == 0 {
bus.free(pixel_ptr);
bus.free(icon_ptr);
allocation_failed = true;
0
} else {
bus.write_long(pixel_handle, pixel_ptr);
self.track_handle_ptr(pixel_ptr, pixel_handle);
pixel_handle
}
}
} else {
let pixel_handle = bus.alloc(4);
if pixel_handle == 0 {
bus.free(icon_ptr);
allocation_failed = true;
0
} else {
bus.write_long(pixel_handle, 0);
pixel_handle
}
};
let icon_pm_table_handle = if icon_data_handle != 0 && ctab_valid {
let ctab_copy_ptr = bus.alloc(ctab_total_bytes);
if ctab_copy_ptr == 0 {
Self::free_handle_and_target(bus, icon_data_handle);
bus.free(icon_ptr);
allocation_failed = true;
0
} else {
let ctab_bytes =
bus.read_bytes(ctab_ptr, ctab_total_bytes as usize);
bus.write_bytes(ctab_copy_ptr, &ctab_bytes);
let ctab_handle = bus.alloc(4);
if ctab_handle == 0 {
bus.free(ctab_copy_ptr);
Self::free_handle_and_target(bus, icon_data_handle);
bus.free(icon_ptr);
allocation_failed = true;
0
} else {
bus.write_long(ctab_handle, ctab_copy_ptr);
self.track_handle_ptr(ctab_copy_ptr, ctab_handle);
ctab_handle
}
}
} else {
0
};
if allocation_failed || (icon_data_handle == 0 && resource_size != 0) {
0
} else {
let icon_data_ptr = bus.read_long(icon_data_handle);
bus.write_long(icon_ptr, icon_data_ptr);
bus.write_long(icon_ptr + 42, icon_pm_table_handle);
bus.write_long(
icon_ptr + 50,
if mask_size == 0 { 0 } else { mask_data_ptr },
);
bus.write_long(
icon_ptr + 64,
if bmap_size == 0 { 0 } else { bmap_data_ptr },
);
bus.write_long(icon_ptr + 78, icon_data_handle);
let icon_handle = bus.alloc(4);
if icon_handle == 0 {
Self::free_handle_and_target(bus, icon_pm_table_handle);
Self::free_handle_and_target(bus, icon_data_handle);
bus.free(icon_ptr);
0
} else {
bus.write_long(icon_handle, icon_ptr);
self.track_handle_ptr(icon_ptr, icon_handle);
icon_handle
}
}
}
}
} else {
0
};
bus.write_long(sp + 2, handle);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// PlotCIcon ($AA1F)
// Draws a color icon in the specified rectangle.
// PROCEDURE PlotCIcon (theRect: Rect; theIcon: CIconHandle);
// More Macintosh Toolbox 1993, p. 5-25
// PlotCIcon ($AA1F): Decodes CIcon (PixMap+iconMask+iconBMap+iconData) and blits scaled into theRect; mask honoured per More Macintosh Toolbox 1993, 5-25
(true, 0x21F) => {
let sp = cpu.read_reg(Register::A7);
let icon_handle = bus.read_long(sp);
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let params = crate::cursor_manager::evaluate_plot_cicon_parameters(
rect_ptr, icon_handle,
);
if params.cicon_handle == 0 {
return Some(Ok(()));
}
let icon_ptr = bus.read_long(params.cicon_handle);
if icon_ptr == 0 {
return Some(Ok(()));
}
if params.rect_ptr == 0 {
return Some(Ok(()));
}
let dst_top = bus.read_word(params.rect_ptr) as i16;
let dst_left = bus.read_word(params.rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(params.rect_ptr + 4) as i16;
let dst_right = bus.read_word(params.rect_ptr + 6) as i16;
// CIcon layout (Inside Macintosh Volume V, V-64):
// 0: iconPMap (PixMap, 50 bytes)
// 50: iconMask (BitMap, 14 bytes)
// 64: iconBMap (BitMap, 14 bytes)
// 78: iconData (Handle, 4 bytes)
// 82: iconMaskData[] (mask bits, then bmap bits)
// Read PixMap fields from iconPMap
let pm_row_bytes = (bus.read_word(icon_ptr + 4) & 0x3FFF) as u32;
let pm_top = bus.read_word(icon_ptr + 6) as i16;
let pm_left = bus.read_word(icon_ptr + 8) as i16;
let pm_bottom = bus.read_word(icon_ptr + 10) as i16;
let pm_right = bus.read_word(icon_ptr + 12) as i16;
let pixel_size = bus.read_word(icon_ptr + 32) as u32;
// Read mask BitMap fields from iconMask
let mask_row_bytes = (bus.read_word(icon_ptr + 54) & 0x3FFF) as u32;
let mask_top = bus.read_word(icon_ptr + 56) as i16;
let mask_left = bus.read_word(icon_ptr + 58) as i16;
let mask_bottom = bus.read_word(icon_ptr + 60) as i16;
let mask_right = bus.read_word(icon_ptr + 62) as i16;
// Read bmap BitMap rowBytes from iconBMap (offset 64+4)
let bmap_row_bytes = (bus.read_word(icon_ptr + 68) & 0x3FFF) as u32;
let icon_h_pre = (pm_bottom - pm_top) as i32;
// Mask data starts at offset 82 in the CIcon record
let mask_data_ptr = icon_ptr + 82;
// Icon pixel data: GetCIcon expands the on-disk cicn into a
// fresh CIcon copy and stores a Handle in iconData (offset
// 78) that points at a private pixel buffer. If a caller
// hands us a raw cicn or a hand-built record with a NIL
// iconData handle, fall back to the inline bytes after the
// ColorTable so the record still paints correctly.
//
// ColorTable header per Imaging With QuickDraw 1994 A-16:
// ctSeed (4) + ctFlags (2) + ctSize (2) = 8 bytes
// then (ctSize+1) entries × 8 bytes each.
let mask_data_size = mask_row_bytes * icon_h_pre as u32;
let bmap_data_size = bmap_row_bytes * icon_h_pre as u32;
let ctab_ptr_for_data = mask_data_ptr + mask_data_size + bmap_data_size;
let ct_size_for_data = bus.read_word(ctab_ptr_for_data + 6) as u32;
let ctab_total_bytes = 8 + (ct_size_for_data + 1) * 8;
let inline_pixel_data_ptr = ctab_ptr_for_data + ctab_total_bytes;
let icon_data_handle = bus.read_long(icon_ptr + 78);
let icon_data_ptr = if icon_data_handle != 0 {
let p = bus.read_long(icon_data_handle);
if p != 0 {
p
} else {
inline_pixel_data_ptr
}
} else {
inline_pixel_data_ptr
};
let icon_h = icon_h_pre;
let icon_w = (pm_right - pm_left) as i32;
let dst_h = (dst_bottom - dst_top) as i32;
let dst_w = (dst_right - dst_left) as i32;
if icon_h <= 0 || icon_w <= 0 || dst_h <= 0 || dst_w <= 0 || icon_data_ptr == 0 {
return Some(Ok(()));
}
// Get current port's pixmap for destination
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
if port == 0 {
return Some(Ok(()));
}
let real_port_version = bus.read_word(port + 6);
let legacy_port_version = bus.read_word(port + 4);
let (
dst_base,
dst_row_bytes,
dst_bounds_top,
dst_bounds_left,
dst_pixel_size,
dst_ctab_handle,
) = if (real_port_version & 0xC000) == 0xC000 {
let pm_handle = bus.read_long(port + 2);
let pm_ptr = bus.read_long(pm_handle);
(
Self::offscreen_pixmap_base_ptr(bus, pm_ptr),
(bus.read_word(pm_ptr + 4) & 0x3FFF) as u32,
bus.read_word(pm_ptr + 6) as i16,
bus.read_word(pm_ptr + 8) as i16,
bus.read_word(pm_ptr + 32) as u32,
bus.read_long(pm_ptr + 42),
)
} else if (legacy_port_version & 0xC000) == 0xC000 {
let pm_handle = bus.read_long(port);
let pm_ptr = bus.read_long(pm_handle);
(
Self::offscreen_pixmap_base_ptr(bus, pm_ptr),
(bus.read_word(pm_ptr + 4) & 0x3FFF) as u32,
bus.read_word(pm_ptr + 6) as i16,
bus.read_word(pm_ptr + 8) as i16,
bus.read_word(pm_ptr + 32) as u32,
bus.read_long(pm_ptr + 42),
)
} else {
let base = bus.read_long(port);
let (screen_base, _, _, _, screen_ps) = self.screen_mode;
let pixel_size = if base == screen_base && screen_ps > 1 {
u32::from(screen_ps)
} else {
1
};
(
base,
(bus.read_word(port + 4) & 0x3FFF) as u32,
bus.read_word(port + 6) as i16,
bus.read_word(port + 8) as i16,
pixel_size,
0,
)
};
let dst_pixel_size = if dst_pixel_size == 0 {
1
} else {
dst_pixel_size
};
// PlotCIcon is defined in terms of QuickDraw transfers and
// therefore observes the current port's visRgn and clipRgn.
// Hidden windows have an empty visRgn; drawing their cached
// controls must not leak directly into the screen PixMap.
// More Macintosh Toolbox 1993, pp. 5-25 to 5-26; Inside
// Macintosh Volume I, p. I-158.
let vis_rgn = bus.read_long(port + 24);
let clip_rgn = bus.read_long(port + 28);
let mut clip_top = dst_top;
let mut clip_left = dst_left;
let mut clip_bottom = dst_bottom;
let mut clip_right = dst_right;
for region in [vis_rgn, clip_rgn] {
if !Self::clip_rect_to_region_bbox(
bus,
region,
&mut clip_top,
&mut clip_left,
&mut clip_bottom,
&mut clip_right,
) {
return Some(Ok(()));
}
}
let vis_membership =
Self::build_region_membership_cache(bus, vis_rgn, clip_top, clip_bottom);
let clip_membership =
Self::build_region_membership_cache(bus, clip_rgn, clip_top, clip_bottom);
if trace_menu_redraw_enabled() {
let abs_top = dst_top + dst_bounds_top;
let abs_left = dst_left + dst_bounds_left;
let abs_bottom = dst_bottom + dst_bounds_top;
let abs_right = dst_right + dst_bounds_left;
if trace_menu_redraw_rect_intersects(abs_top, abs_left, abs_bottom, abs_right) {
if let Some((_, res_type, res_id)) =
self.loaded_handles.get(&icon_handle).copied()
{
eprintln!(
"[MENU-REDRAW] PlotCIcon '{}' {} handle=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
String::from_utf8_lossy(&res_type),
res_id,
icon_handle,
dst_base,
abs_top,
abs_left,
abs_bottom,
abs_right,
);
} else {
eprintln!(
"[MENU-REDRAW] PlotCIcon handle=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
icon_handle,
dst_base,
abs_top,
abs_left,
abs_bottom,
abs_right,
);
}
}
}
if trace_dialog_draw_enabled() && self.dialog_tracking.is_some() {
let abs_top = dst_top + dst_bounds_top;
let abs_left = dst_left + dst_bounds_left;
let abs_bottom = dst_bottom + dst_bounds_top;
let abs_right = dst_right + dst_bounds_left;
if let Some((_, res_type, res_id)) =
self.loaded_handles.get(&icon_handle).copied()
{
eprintln!(
"[DIALOG-DRAW] PlotCIcon '{}' {} handle=${:08X} current_port=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
String::from_utf8_lossy(&res_type),
res_id,
icon_handle,
*self.current_port,
dst_base,
abs_top,
abs_left,
abs_bottom,
abs_right,
);
} else {
eprintln!(
"[DIALOG-DRAW] PlotCIcon handle=${:08X} current_port=${:08X} dstBase=${:08X} rect=({},{}..{},{} )",
icon_handle,
*self.current_port,
dst_base,
abs_top,
abs_left,
abs_bottom,
abs_right,
);
}
}
// Image ColorTables associate RGB colors with ColorSpec.value,
// not the entry position; sparse tables can omit unused pixels.
// Consult the live iconPMap table installed by GetCIcon, falling
// back to the inline resource table for raw CIcon records.
// Inside Macintosh Volume V (1986), Color QuickDraw, "Color
// Tables"; More Macintosh Toolbox (1993), pp. 5-25 to 5-26.
let icon_ctab_handle = bus.read_long(icon_ptr + 42);
let icon_ctab_ptr = if icon_ctab_handle != 0 {
bus.read_long(icon_ctab_handle)
} else {
0
};
let icon_clut = self.read_color_table_ptr_clut(
bus,
if icon_ctab_ptr != 0 { icon_ctab_ptr } else { ctab_ptr_for_data },
);
// Screen-backed color ports retain their own PixMap color
// table, but the pixels are interpreted by the live screen
// device table. Palette activation can therefore make the
// port's table stale. Use the same screen-destination rule as
// CopyBits so PlotCIcon maps colors through the live device.
// Imaging With QuickDraw (1994), pp. 4-55 to 4-59 and 5-28.
let effective_dst_ctab = self.effective_destination_ctab_handle(
dst_base,
dst_row_bytes,
dst_pixel_size,
dst_ctab_handle,
);
let dst_clut = if effective_dst_ctab != 0 {
self.read_port_clut(bus, effective_dst_ctab)
} else {
*self.device_clut
};
// Resolve each source color once per draw. The mapping stays
// local so changes to either guest color table remain visible.
let mut mapped_indices = [None; 256];
for dst_y_local in clip_top..clip_bottom {
let Some(sy) =
Self::scale_coord(pm_top, pm_bottom, dst_top, dst_bottom, dst_y_local)
else {
continue;
};
for dst_x_local in clip_left..clip_right {
if !Self::region_contains_point_cached(
bus,
vis_rgn,
vis_membership.as_ref(),
dst_y_local,
dst_x_local,
) || !Self::region_contains_point_cached(
bus,
clip_rgn,
clip_membership.as_ref(),
dst_y_local,
dst_x_local,
) {
continue;
}
let Some(sx) =
Self::scale_coord(pm_left, pm_right, dst_left, dst_right, dst_x_local)
else {
continue;
};
let Some(mask_y) = Self::scale_coord(
mask_top,
mask_bottom,
dst_top,
dst_bottom,
dst_y_local,
) else {
continue;
};
let Some(mask_x) = Self::scale_coord(
mask_left,
mask_right,
dst_left,
dst_right,
dst_x_local,
) else {
continue;
};
let Some(mask_pixel) = Self::read_packed_bitmap_index(
bus,
mask_data_ptr,
mask_row_bytes,
1,
mask_top,
mask_left,
mask_bottom,
mask_right,
mask_y as i16,
mask_x as i16,
) else {
continue;
};
if mask_pixel == 0 {
continue;
}
let dst_y = i32::from(dst_y_local) - i32::from(dst_bounds_top);
let dst_x = i32::from(dst_x_local) - i32::from(dst_bounds_left);
if dst_y < 0 || dst_x < 0 {
continue;
}
let dst_y = dst_y as u32;
let dst_x = dst_x as u32;
match dst_pixel_size {
8 => {
let Some(src_index) = Self::read_packed_bitmap_index(
bus,
icon_data_ptr,
pm_row_bytes,
pixel_size,
pm_top,
pm_left,
pm_bottom,
pm_right,
sy as i16,
sx as i16,
) else {
continue;
};
let dst_index = *mapped_indices[src_index as usize]
.get_or_insert_with(|| {
let mut rgb = icon_clut[src_index as usize];
// ttSelected darkens the icon before device mapping.
// More Macintosh Toolbox (1993), pp. 5-20 to 5-21.
if (self.icon_transform_override & 0x4000) != 0 {
for component in &mut rgb {
*component /= 2;
}
}
Self::nearest_palette_index(&dst_clut, rgb)
});
bus.write_byte(dst_base + dst_y * dst_row_bytes + dst_x, dst_index);
}
1 => {
let Some(src_index) = Self::read_packed_bitmap_index(
bus,
icon_data_ptr,
pm_row_bytes,
pixel_size,
pm_top,
pm_left,
pm_bottom,
pm_right,
sy as i16,
sx as i16,
) else {
continue;
};
let dst_byte_off = dst_y * dst_row_bytes + dst_x / 8;
let dst_bit = 7 - (dst_x % 8);
let mut dst_byte = bus.read_byte(dst_base + dst_byte_off);
if src_index != 0 {
dst_byte |= 1 << dst_bit;
} else {
dst_byte &= !(1 << dst_bit);
}
bus.write_byte(dst_base + dst_byte_off, dst_byte);
}
_ => {}
}
}
}
if dst_base == self.screen_mode.0 {
let screen_rect = (
clip_top.saturating_sub(dst_bounds_top),
clip_left.saturating_sub(dst_bounds_left),
clip_bottom.saturating_sub(dst_bounds_top),
clip_right.saturating_sub(dst_bounds_left),
);
// Applications can draw color icons into user items before
// entering ModalDialog. Keep the retained dialog image in
// sync just as CopyBits does for screen-backed ports.
self.refresh_dialog_saved_pixels_after_screen_draw(bus, port, screen_rect);
self.refresh_visible_dialog_snapshot_after_bulk_port_draw(
bus, port, screen_rect,
);
}
Ok(())
}
// DisposeCIcon ($AA25)
// Disposes all structures allocated by GetCIcon.
// PROCEDURE DisposeCIcon (theIcon: CIconHandle);
// More Macintosh Toolbox (1993), p. 5-30.
//
// Contract coverage:
// quickdraw::tests::disposecicon_consumes_theicon_ciconhandle_argument
// quickdraw::tests::disposecicon_preserves_nonstack_registers_while_releasing_icondata_handle
// DisposeCIcon ($AA25): Pops 4 bytes (icon handle), releases
// the GetCIcon-allocated iconData handle cached in the fresh
// CIcon copy, frees the private CIcon record itself, and
// detaches the live handle from RecoverHandle without touching
// the source resource payload.
(true, 0x225) => {
let sp = cpu.read_reg(Register::A7);
let icon_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let params = crate::cursor_manager::evaluate_dispose_cicon_parameters(icon_handle);
if params.cicon_handle != 0 {
let icon_ptr = bus.read_long(params.cicon_handle);
if icon_ptr != 0 {
let icon_pm_table_handle = bus.read_long(icon_ptr + 42);
let icon_data_handle = bus.read_long(icon_ptr + 78);
bus.write_long(icon_ptr + 42, 0);
bus.write_long(icon_ptr + 78, 0);
Self::free_handle_and_target(bus, icon_pm_table_handle);
Self::free_handle_and_target(bus, icon_data_handle);
self.untrack_handle_ptr(icon_ptr);
self.forget_resource_handle_index_for_handle(params.cicon_handle);
self.with_resource_manager_mut(|resource_manager| {
resource_manager.loaded_handles.remove(¶ms.cicon_handle);
resource_manager.resource_handle_files.remove(¶ms.cicon_handle);
});
bus.free(icon_ptr);
bus.write_long(params.cicon_handle, 0);
bus.free(params.cicon_handle);
}
}
Ok(())
}
// BitMapToRegion ($A8D7)
// Converts a bitmap to a region.
// FUNCTION BitMapToRegion (region: RgnHandle; bMap: BitMap): OSErr;
// Imaging With QuickDraw 1994, pp. 2-49 to 2-50
//
// Per IM:IWQ 1994 p. 2-49: "The BitMapToRegion function
// converts a given BitMap or PixMap record to a region. ...
// The region parameter must be a valid region handle
// created with the NewRgn function. The old region contents
// are lost. The bMap parameter may be either a BitMap or
// PixMap record. If you pass a PixMap record, its pixel
// depth must be 1." Result codes per p. 2-49: noErr (0),
// pixmapTooDeepErr (-148) when depth > 1, rgnTooBigErr
// (-500) when the conversion would exceed 64 KB.
//
// MPW Universal Headers (Quickdraw.h):
// EXTERN_API(OSErr) BitMapToRegion(RgnHandle region,
// const BitMap *bMap)
// ONEWORDINLINE(0xA8D7);
//
// Stack frame at trap entry (Pascal LR push order with
// result slot pre-allocated above the args):
// sp+0 bMap_ptr (4 bytes, last pushed → shallowest)
// sp+4 rgn_handle (4 bytes, first pushed → deepest)
// sp+8 OSErr result (2 bytes, function-result slot)
// Trap pops 8 argument bytes and writes the OSErr at sp+8.
//
// HLE implementation: derives region topology from 1bpp
// source ink runs by scanning row endpoints, emitting
// y/run-endpoint pairs, and computing the bbox from the
// inked extent. Empty sources collapse to a (0,0,0,0)
// bbox + minimum 10-byte rgnSize ("empty region"). Single-
// rectangle sources take the rectangular-region fast path
// and emit no per-row run data. Non-1bpp parity with Color
// QuickDraw's pixmapTooDeepErr remains a gap.
//
// Contract-test coverage in this file (mod tests):
// trap::quickdraw::tests::bitmaptoregion_*
(true, 0x0D7) => {
let sp = cpu.read_reg(Register::A7);
let bmap_ptr = bus.read_long(sp);
let rgn_handle = bus.read_long(sp + 4);
let result_ptr = sp + 8;
cpu.write_reg(Register::A7, sp + 8);
if rgn_handle != 0 && bmap_ptr != 0 {
let info = self.resolve_copy_bitmap(bus, bmap_ptr);
let wrote_region;
if info.pixel_size == 1 && info.bounds_bottom > info.bounds_top {
let mut data_words = Vec::new();
let mut previous_row = Vec::new();
let mut bbox: Option<(i16, i16, i16, i16)> = None;
let mut rectangle_row = None;
let mut rectangle_candidate = true;
let mut saw_empty_after_content = false;
for y in info.bounds_top..=info.bounds_bottom {
let current_row = if y < info.bounds_bottom {
Self::scan_bitmap_row_endpoints(bus, &info, y)
} else {
Vec::new()
};
if y < info.bounds_bottom && !current_row.is_empty() {
bbox = Some(match bbox {
Some((top, left, bottom, right)) => (
top.min(y),
left.min(current_row[0]),
bottom.max(y + 1),
right.max(*current_row.last().unwrap()),
),
None => {
(y, current_row[0], y + 1, *current_row.last().unwrap())
}
});
if rectangle_row.is_none() {
rectangle_row = Some(current_row.clone());
rectangle_candidate = current_row.len() == 2;
} else if saw_empty_after_content
|| rectangle_row.as_ref() != Some(¤t_row)
{
rectangle_candidate = false;
}
saw_empty_after_content = false;
} else if bbox.is_some() {
saw_empty_after_content = true;
}
let delta = Self::merge_region_endpoints(&previous_row, ¤t_row);
if !delta.is_empty() {
data_words.push(y);
data_words.extend_from_slice(&delta);
data_words.push(REGION_STOP);
}
previous_row = current_row;
}
let wrote = if let Some((top, left, bottom, right)) = bbox {
if rectangle_candidate {
Self::write_region(
bus,
rgn_handle,
Some((top, left, bottom, right)),
&[],
)
} else {
data_words.push(REGION_STOP);
Self::write_region(
bus,
rgn_handle,
Some((top, left, bottom, right)),
&data_words,
)
}
} else {
Self::write_region(bus, rgn_handle, None, &[])
};
if !wrote {
bus.write_word(result_ptr, 0);
return Some(Ok(()));
}
wrote_region = true;
} else {
Self::write_region(bus, rgn_handle, None, &[]);
wrote_region = true;
}
if trace_region_ops_enabled() {
let bbox = Self::region_bbox(bus, rgn_handle);
let size = Self::region_ptr_and_size(bus, rgn_handle)
.map(|(_, size)| size)
.unwrap_or(0);
eprintln!(
"[REGION] tick={} BitMapToRegion bmap=${:08X} rgn=${:08X} base=${:08X} rowBytes={} bounds=({},{}..{},{}) pixelSize={} wrote={} bbox={:?} size={}",
self.current_tick(),
bmap_ptr,
rgn_handle,
info.base,
info.row_bytes,
info.bounds_top,
info.bounds_left,
info.bounds_bottom,
info.bounds_right,
info.pixel_size,
wrote_region,
bbox,
size
);
}
}
// Return noErr
bus.write_word(result_ptr, 0);
Ok(())
}
// ========== Missing QD Stubs ==========
// SetPenState ($A899)
// Sets the pen state to the values in the specified record.
// PROCEDURE SetPenState(pnState: PenState);
// Inside Macintosh Volume I, I-170
(true, 0x099) => {
let sp = cpu.read_reg(Register::A7);
let state_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if state_ptr != 0 {
self.pn_loc = (
bus.read_word(state_ptr) as i16,
bus.read_word(state_ptr + 2) as i16,
);
self.pn_size = (
bus.read_word(state_ptr + 4) as i16,
bus.read_word(state_ptr + 6) as i16,
);
self.pn_mode = bus.read_word(state_ptr + 8) as i16;
for i in 0..8 {
self.pn_pat[i] = bus.read_byte(state_ptr + 10 + i as u32);
}
self.sync_current_port_draw_state(bus);
self.install_port_bit_pixpat(bus, 58, self.pn_pat);
}
Ok(())
}
// GetFontName ($A8FF)
// PROCEDURE GetFontName(fontNum: INTEGER; VAR theName: Str255);
// Inside Macintosh Volume I, I-223
//
// "GetFontName returns in theName the name of the font
// having the font number fontNum. If there's no such font,
// GetFontName returns the empty string."
//
// Stack (Pascal): SP+0=name_ptr(4), SP+4=fontNum(2). Pops 6.
// Names come from src/quickdraw/fonts/mod.rs::FONT_NAMES,
// which mirrors IM:Text Appendix B. Unknown font numbers
// yield a zero-length Pascal string per the IM:I contract.
//
// Regression coverage:
// trap::quickdraw::tests::getfontname_known_font_returns_pascal_name
// trap::quickdraw::tests::getfontname_unknown_font_returns_empty_string
// trap::quickdraw::tests::getfontname_pops_six_bytes
// GetFontName ($A8FF): IM:I I-223; name lookup via FONT_NAMES table; empty string for unknown IDs
(true, 0x0FF) => {
let sp = cpu.read_reg(Register::A7);
let name_ptr = bus.read_long(sp);
let font_num = bus.read_word(sp + 4) as i16;
cpu.write_reg(Register::A7, sp + 6);
if name_ptr != 0 {
let name = font_name_for_id(font_num)
.or_else(|| self.loaded_font_name_for_id(font_num))
.unwrap_or("");
// Str255 length byte is clamped to 255; all recognized
// font names are well under that so the truncate is
// purely defensive.
let len = name.len().min(255) as u8;
bus.write_byte(name_ptr, len);
for (i, b) in name.as_bytes().iter().take(len as usize).enumerate() {
bus.write_byte(name_ptr + 1 + i as u32, *b);
}
}
Ok(())
}
// GetFNum ($A900)
// PROCEDURE GetFNum(fontName: Str255; VAR theNum: INTEGER);
// Inside Macintosh Volume I, I-223
//
// "GetFNum returns in theNum the font number for the font
// having the given fontName. If there's no such font,
// GetFNum returns 0."
//
// Stack (Pascal): SP+0=num_ptr(4), SP+4=name_ptr(4). Pops 8.
// Name lookup is ASCII case-insensitive and trims whitespace,
// matching classic Font Manager behavior. Returns 0 when no
// match — distinguishable from "Chicago" (which is also 0)
// only by the caller also calling GetFontName(0) to verify.
//
// Regression coverage:
// trap::quickdraw::tests::getfnum_known_font_returns_family_id
// trap::quickdraw::tests::getfnum_unknown_font_returns_zero
// trap::quickdraw::tests::getfnum_name_match_is_case_insensitive
// trap::quickdraw::tests::getfnum_pops_eight_bytes
// GetFNum ($A900): IM:I I-223; case-insensitive reverse lookup; 0 for unknown names
(true, 0x100) => {
let sp = cpu.read_reg(Register::A7);
let num_ptr = bus.read_long(sp);
let name_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if num_ptr != 0 {
let mut requested_name: Option<String> = None;
let font_id = if name_ptr != 0 {
// Read Pascal Str255: length byte + chars.
let len = bus.read_byte(name_ptr) as usize;
let mut name_bytes = Vec::with_capacity(len);
for i in 0..len {
name_bytes.push(bus.read_byte(name_ptr + 1 + i as u32));
}
match std::str::from_utf8(&name_bytes) {
Ok(name) => {
requested_name = Some(name.to_string());
font_id_for_name(name)
.or_else(|| self.loaded_font_id_for_name(name))
.unwrap_or(0)
}
Err(_) => 0,
}
} else {
0
};
if trace_font_traps_enabled() {
eprintln!(
"[TRAP] GetFNum({:?}) -> {}",
requested_name.as_deref().unwrap_or("<null>"),
font_id
);
}
bus.write_word(num_ptr, font_id as u16);
}
Ok(())
}
// SetEmptyRgn ($A8DD)
// Destroys the previous structure of the region, then sets it to the empty region (0,0,0,0).
// PROCEDURE SetEmptyRgn(rgn: RgnHandle);
// Inside Macintosh Volume I, I-183
// Reference: a8dd_set_empty_rgn
(true, 0x0DD) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if rgn_handle != 0 {
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr != 0 {
bus.write_word(rgn_ptr, 10);
bus.write_long(rgn_ptr + 2, 0);
bus.write_long(rgn_ptr + 6, 0);
}
}
Ok(())
}
// SetRectRgn ($A8DE)
// Sets region to 10-byte rectangular structure with specified bounds.
// PROCEDURE SetRectRgn(rgn: RgnHandle; left, top, right, bottom: INTEGER);
// Inside Macintosh Volume I, I-183
(true, 0x0DE) => {
let sp = cpu.read_reg(Register::A7);
let bottom = bus.read_word(sp) as i16;
let right = bus.read_word(sp + 2) as i16;
let top = bus.read_word(sp + 4) as i16;
let left = bus.read_word(sp + 6) as i16;
let rgn_handle = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if rgn_handle != 0 {
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr != 0 {
bus.write_word(rgn_ptr, 10);
bus.write_word(rgn_ptr + 2, top as u16);
bus.write_word(rgn_ptr + 4, left as u16);
bus.write_word(rgn_ptr + 6, bottom as u16);
bus.write_word(rgn_ptr + 8, right as u16);
}
}
Ok(())
}
// OpenRgn ($A8DA)
// PROCEDURE OpenRgn;
// Imaging With QuickDraw 1994, 3-87
// Begins recording line and framed-shape outlines into a region;
// Hide the pen while recording; callers may show it again.
(true, 0x0DA) => {
self.recording_region = Some(super::dispatch::RegionRecording::default());
self.pn_vis -= 1;
self.sync_current_port_draw_state(bus);
Ok(())
}
// CloseRgn ($A8DB)
// PROCEDURE CloseRgn(dstRgn: RgnHandle);
// Imaging With QuickDraw 1994, 3-89
// Stops collection of lines and framed shapes, organizes them
// into a region definition, and saves it in dstRgn.
// CloseRgn ($A8DB): Ends region recording and serializes recorded geometry into dstRgn
(true, 0x0DB) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if let Some(recording) = self.recording_region.take() {
self.pn_vis += 1;
self.sync_current_port_draw_state(bus);
if dst_handle != 0 {
if let Some((rows_top, rows)) = Self::recorded_region_rows(&recording) {
Self::write_region_from_rows(bus, dst_handle, rows_top, &rows);
} else {
Self::write_region(bus, dst_handle, None, &[]);
}
}
}
Ok(())
}
// OffsetRgn ($A8E0)
// Shifts region bounding box by (dh, dv).
// PROCEDURE OffsetRgn(rgn: RgnHandle; dh, dv: INTEGER);
// Inside Macintosh Volume I, I-183
(true, 0x0E0) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
let rgn_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
Self::offset_region(bus, rgn_handle, dh, dv);
Ok(())
}
// InsetRgn ($A8E1)
// PROCEDURE InsetRgn(rgn: RgnHandle; dh, dv: INTEGER);
// InsetRgn ($A8E1): Insets bbox by (dh, dv) on all sides per IM:I I-184
(true, 0x0E1) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
let rgn_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
Self::inset_region(bus, rgn_handle, dh, dv);
Ok(())
}
// EmptyRgn ($A8E2)
// FUNCTION EmptyRgn(rgn: RgnHandle): BOOLEAN;
// EmptyRgn ($A8E2): Returns TRUE if bbox has top>=bottom or left>=right
(true, 0x0E2) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
let is_empty = if rgn_handle != 0 {
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr != 0 {
let t = bus.read_word(rgn_ptr + 2) as i16;
let l = bus.read_word(rgn_ptr + 4) as i16;
let b = bus.read_word(rgn_ptr + 6) as i16;
let r = bus.read_word(rgn_ptr + 8) as i16;
b <= t || r <= l
} else {
true
}
} else {
true
};
bus.write_word(sp + 4, if is_empty { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// EqualRgn ($A8E3)
// FUNCTION EqualRgn(rgnA, rgnB: RgnHandle): BOOLEAN;
// Inside Macintosh Volume I, I-183
//
// Returns TRUE iff the two regions have identical sizes,
// shapes, and locations. A region's on-bus layout is:
// rgnSize(2) + rgnBBox(8) + [scanline data...]
// The canonical implementation (ROM / Executor C_EqualRgn at
// qRegion.cpp:1493) compares the full rgnSize bytes of *r1
// vs *r2 with memcmp. Because rgnSize is the first word of
// the region, any size mismatch surfaces in the first word
// of the byte-compare and short-circuits to FALSE.
//
// REGRESSION: the previous implementation lived at the wrong
// dispatch slot (0x0E5, which is really UnionRgn) and only
// compared the 10-byte bbox header. That made it silently
// report two complex regions as equal any time they shared
// the same bounding box — the classic clip/update-region
// staleness bug.
//
// Stack: SP+0=rgnB, SP+4=rgnA, result word at SP+8 (pop 8).
// BOOL convention matches EmptyRgn/PtInRgn/RectInRgn:
// 0x0100 for TRUE, 0x0000 for FALSE.
//
// EqualRgn ($A8E3): Full rgnSize byte compare (Executor C_EqualRgn, IM:I I-183); was at wrong slot + bbox-only prior to 2026-04-12
(true, 0x0E3) => {
let sp = cpu.read_reg(Register::A7);
let rgn_b = bus.read_long(sp);
let rgn_a = bus.read_long(sp + 4);
let equal = if rgn_a != 0 && rgn_b != 0 {
let ptr_a = bus.read_long(rgn_a);
let ptr_b = bus.read_long(rgn_b);
if ptr_a != 0 && ptr_b != 0 {
// memcmp-equivalent: compare rgnSize bytes
// starting at the master pointer. Because the
// first word is rgnSize, a size mismatch trips
// the comparison at byte 0-1.
let size_a = bus.read_word(ptr_a) as u32;
(0..size_a).all(|i| bus.read_byte(ptr_a + i) == bus.read_byte(ptr_b + i))
} else {
ptr_a == ptr_b
}
} else {
rgn_a == rgn_b
};
bus.write_word(sp + 8, if equal { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// SectRgn ($A8E4)
// Calculates the intersection of two regions.
// PROCEDURE SectRgn(srcRgnA, srcRgnB, dstRgn: RgnHandle);
// Inside Macintosh Volume I, I-184
(true, 0x0E4) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_b = bus.read_long(sp + 4);
let src_a = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if src_a != 0 && src_b != 0 && dst_handle != 0 {
Self::write_region_boolean_op(
bus,
dst_handle,
src_a,
src_b,
RegionBooleanOp::Intersection,
);
if trace_region_ops_enabled() {
eprintln!(
"[REGION] tick={} SectRgn a=${:08X} bbox={:?} b=${:08X} bbox={:?} dst=${:08X} bbox={:?} size={}",
self.current_tick(),
src_a,
Self::region_bbox(bus, src_a),
src_b,
Self::region_bbox(bus, src_b),
dst_handle,
Self::region_bbox(bus, dst_handle),
Self::region_ptr_and_size(bus, dst_handle).map(|(_, size)| size).unwrap_or(0)
);
}
}
Ok(())
}
// UnionRgn ($A8E5)
// Calculates the union of two regions.
// PROCEDURE UnionRgn(srcRgnA, srcRgnB, dstRgn: RgnHandle);
// Inside Macintosh Volume I, I-184
(true, 0x0E5) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_b = bus.read_long(sp + 4);
let src_a = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if src_a != 0 && src_b != 0 && dst_handle != 0 {
Self::write_region_boolean_op(
bus,
dst_handle,
src_a,
src_b,
RegionBooleanOp::Union,
);
if trace_region_ops_enabled() {
eprintln!(
"[REGION] tick={} UnionRgn a=${:08X} bbox={:?} b=${:08X} bbox={:?} dst=${:08X} bbox={:?} size={}",
self.current_tick(),
src_a,
Self::region_bbox(bus, src_a),
src_b,
Self::region_bbox(bus, src_b),
dst_handle,
Self::region_bbox(bus, dst_handle),
Self::region_ptr_and_size(bus, dst_handle).map(|(_, size)| size).unwrap_or(0)
);
}
}
Ok(())
}
// DiffRgn ($A8E6)
// Subtracts srcRgnB from srcRgnA and places the difference in dstRgn.
// PROCEDURE DiffRgn(srcRgnA, srcRgnB, dstRgn: RgnHandle);
// Inside Macintosh Volume I, I-184
(true, 0x0E6) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_b = bus.read_long(sp + 4);
let src_a = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if src_a != 0 && dst_handle != 0 {
Self::write_region_boolean_op(
bus,
dst_handle,
src_a,
src_b,
RegionBooleanOp::Difference,
);
if trace_region_ops_enabled() {
eprintln!(
"[REGION] tick={} DiffRgn a=${:08X} bbox={:?} b=${:08X} bbox={:?} dst=${:08X} bbox={:?} size={}",
self.current_tick(),
src_a,
Self::region_bbox(bus, src_a),
src_b,
Self::region_bbox(bus, src_b),
dst_handle,
Self::region_bbox(bus, dst_handle),
Self::region_ptr_and_size(bus, dst_handle).map(|(_, size)| size).unwrap_or(0)
);
}
}
Ok(())
}
// XorRgn ($A8E7)
// Calculates the symmetric difference of two regions.
// PROCEDURE XorRgn(srcRgnA, srcRgnB, dstRgn: RgnHandle);
// Inside Macintosh Volume I, I-185
(true, 0x0E7) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_b = bus.read_long(sp + 4);
let src_a = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if src_a != 0 && src_b != 0 && dst_handle != 0 {
Self::write_region_boolean_op(
bus,
dst_handle,
src_a,
src_b,
RegionBooleanOp::Xor,
);
if trace_region_ops_enabled() {
eprintln!(
"[REGION] tick={} XorRgn a=${:08X} bbox={:?} b=${:08X} bbox={:?} dst=${:08X} bbox={:?} size={}",
self.current_tick(),
src_a,
Self::region_bbox(bus, src_a),
src_b,
Self::region_bbox(bus, src_b),
dst_handle,
Self::region_bbox(bus, dst_handle),
Self::region_ptr_and_size(bus, dst_handle).map(|(_, size)| size).unwrap_or(0)
);
}
}
Ok(())
}
// PtInRgn ($A8E8)
// FUNCTION PtInRgn(pt: Point; rgn: RgnHandle): BOOLEAN;
// PtInRgn ($A8E8): Tests pt inside region via membership cache (differential x-span decode); rectangular short-circuit per IM:I I-185
(true, 0x0E8) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
let pt_v = bus.read_word(sp + 4) as i16;
let pt_h = bus.read_word(sp + 6) as i16;
let in_rgn = Self::region_contains_point(bus, rgn_handle, pt_v, pt_h);
if trace_region_ops_enabled() {
eprintln!(
"[REGION] tick={} PtInRgn pt=({}, {}) rgn=${:08X} bbox={:?} size={} -> {}",
self.current_tick(),
pt_v,
pt_h,
rgn_handle,
Self::region_bbox(bus, rgn_handle),
Self::region_ptr_and_size(bus, rgn_handle)
.map(|(_, size)| size)
.unwrap_or(0),
in_rgn
);
}
bus.write_word(sp + 8, if in_rgn { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// RectInRgn ($A8E9)
// FUNCTION RectInRgn(r: Rect; rgn: RgnHandle): BOOLEAN;
// "Returns TRUE if any pixel enclosed by r lies within rgn."
// Inside Macintosh Volume I, I-185
//
// Stack (Pascal left-to-right push → deepest first):
// SP+0 rgn RgnHandle (4 bytes, shallowest — pushed last)
// SP+4 r Ptr to Rect (4 bytes)
// SP+8 result BOOLEAN slot (2 bytes — caller pre-pushed)
// Pop 8, write result at SP+8 — SP advances to SP+8.
//
// For rectangular regions the bounding-box intersection suffices.
// For complex regions we build a membership cache and check per-row
// span overlap so that donut-shaped regions don't falsely return TRUE
// for points inside the hole. IM:I I-142 documents the region format.
//
// RectInRgn ($A8E9): Rect/region intersection; complex regions use membership cache per IM:I I-185
(true, 0x0E9) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
let rect_ptr = bus.read_long(sp + 4);
let in_rgn = Self::rect_in_rgn(bus, rgn_handle, rect_ptr);
if trace_region_ops_enabled() {
eprintln!(
"[REGION] tick={} RectInRgn rect=({},{}..{},{}) rgn=${:08X} bbox={:?} size={} -> {}",
self.current_tick(),
bus.read_word(rect_ptr) as i16,
bus.read_word(rect_ptr + 2) as i16,
bus.read_word(rect_ptr + 4) as i16,
bus.read_word(rect_ptr + 6) as i16,
rgn_handle,
Self::region_bbox(bus, rgn_handle),
Self::region_ptr_and_size(bus, rgn_handle).map(|(_, size)| size).unwrap_or(0),
in_rgn
);
}
bus.write_word(sp + 8, if in_rgn { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// ========== Std* bottleneck procs (intentional no-ops) ==========
//
// QuickDraw routes every shape-drawing call through a small set of
// "low-level routines" — the bottleneck procs — exposed via the
// grafProcs (B&W: QDProcs) or grafProcs (color: CQDProcs) field of
// the current port. Apps customize drawing by replacing one or
// more proc pointers; the standard procs are what runs when the
// proc slot is NIL OR explicitly equals the standard routine.
//
// Per IM:I I-196..I-198 + Imaging With QuickDraw 1994 3-130..3-139
// each Std* trap is the documented entry point for the
// corresponding bottleneck. On a real Mac the high-level traps
// (FrameRect, PaintRect, EraseRect, FillRect, InvertRect, etc.)
// dispatch THROUGH grafProcs.rectProc — which by default is
// StdRect; an app installing a custom rectProc has its routine
// invoked instead, and the custom routine MAY chain to StdRect
// for the actual drawing.
//
// Standard bottlenecks are callable by applications and by
// custom procedures chaining to the defaults. StdRect and StdBits
// perform drawing; other entries below retain their documented
// implementation limitations.
//
// The Pascal stack convention for these traps follows the
// MPW / Toolbox standard:
// - GrafVerb (an enum) → 1 byte at source level, 2 bytes
// on stack (M68k 16-bit stack alignment)
// - INTEGER → 2 bytes
// - Point (4 bytes) → by VALUE, 4 bytes
// - Rect / BitMap / FontInfo (VAR or by-value Rect-larger-
// than-pointer types) → by REFERENCE, 4-byte pointer
// - PolyHandle / RgnHandle / Handle / Ptr → 4 bytes
//
// Selectors-vs-trap-words: each Std* bottleneck has its own
// trap word (no DispatchManager packaging); selector dispatch
// applies only to higher-level dispatchers like _PaletteDispatch
// or _SCSIDispatch, not to the bottleneck family.
// Standard shape bottlenecks draw directly so custom grafProcs
// can chain here without recursion. GrafVerb occupies the first
// byte of its aligned stack slot. RRect and Arc have two trailing
// integer arguments nearest SP, ahead of the rectangle pointer.
(true, 0x0A0 | 0x0AF | 0x0B6 | 0x0BD) => {
let sp = cpu.read_reg(Register::A7);
let prefix = if matches!(trap_num, 0x0AF | 0x0BD) {
4
} else {
0
};
let rect_ptr = bus.read_long(sp + prefix);
let verb = bus.read_byte(sp + prefix + 4);
let last_argument = bus.read_word(sp) as i16;
let previous_argument = bus.read_word(sp + 2) as i16;
cpu.write_reg(Register::A7, sp + prefix + 6);
if rect_ptr == 0 || !Self::guest_range_in_ram(bus, rect_ptr, 8) {
return Some(Ok(()));
}
let r = read_rect(bus, rect_ptr);
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
let op = match verb {
0 => ShapeOp::Frame,
1 => ShapeOp::Paint,
2 => ShapeOp::Erase,
3 => ShapeOp::Invert,
4 => {
let globals = bus.read_long(cpu.read_reg(Register::A5));
let port = bus.read_long(globals);
let mut pattern = [0xff; 8];
if port != 0 && Self::guest_range_in_ram(bus, port, 108) {
if bus.read_word(port + 6) & 0xc000 == 0xc000 {
if let Some((pat, rgb)) =
self.pixpat_fill_pattern(bus, bus.read_long(port + 62))
{
pattern = pat;
if let Some(rgb) = rgb {
self.fg_color = rgb;
self.bg_color = rgb;
}
}
} else {
bus.read_bytes_into(port + 40, &mut pattern);
}
}
ShapeOp::Fill(pattern)
}
_ => return Some(Ok(())),
};
match trap_num {
0x0AF => self.draw_round_rect(cpu, bus, &r, previous_argument, last_argument, op),
0x0B6 => self.draw_oval(cpu, bus, &r, op),
0x0BD => self.draw_arc(cpu, bus, &r, previous_argument, last_argument, op),
_ => self.draw_rect(cpu, bus, &r, op),
}
self.fg_color = saved_fg;
self.bg_color = saved_bg;
Ok(())
}
// StdPoly ($A8C5)
// PROCEDURE StdPoly(verb: GrafVerb; poly: PolyHandle);
// Inside Macintosh Volume I, I-198 + Imaging With QuickDraw 1994 3-135:
// "The StdPoly procedure draws the polygon specified in the poly
// parameter according to the action specified in the verb parameter."
//
// MPW Universal Headers Quickdraw.h declares the C-callable form
// with the PolyHandle (4-byte handle):
// EXTERN_API(void) StdPoly(GrafVerb verb, PolyHandle poly)
// ONEWORDINLINE(0xA8C5);
//
// Stack frame at trap entry (Pascal LR push, first arg deepest):
// sp+0..3 poly_handle (last pushed → shallowest)
// sp+4..5 verb_word (first pushed → deepest)
// 6-byte total pop, no result slot (PROCEDURE).
//
// Real-Mac semantic: dispatches Frame/Paint/Erase/Invert/Fill verb
// on the polygon's recorded vertex list via the current pen state /
// fill pattern.
//
// Systemless HLE compromise — every high-level QuickDraw polygon trap
// (FramePoly / PaintPoly / ErasePoly / InvertPoly / FillPoly) draws
// directly via the Rust polygon scanline code, bypassing the
// bottleneck dispatch through grafProcs.polyProc. StdPoly itself
// is reachable only via explicit SetStdProcs → JSR-through-slot —
// a non-corpus pattern. Therefore the HLE pops the 6-byte stack
// frame and returns without performing any drawing.
// caller_observable = false because no corpus caller depends on
// StdPoly producing pixels.
//
// BasiliskII divergence: BII's System 7.5 ROM faithfully draws the
// polygon AND mutates A0/A1/D0/D1 during rasterisation. Both
// engines agree on the 6-byte pop; they diverge on pixel side-
// effect and register mutation. The Systemless-only
// register-preservation contract is pinned by
// `stdpoly_stub_preserves_non_stack_registers_in_hle_compromise_path`.
(true, 0x0C5) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 6);
Ok(())
}
// StdRgn ($A8D1)
// PROCEDURE StdRgn(verb: GrafVerb; rgn: RgnHandle);
// Inside Macintosh Volume I, I-198 + Imaging With QuickDraw 1994 3-135:
// "The StdRgn procedure draws the region specified in the rgn
// parameter according to the action specified in the verb parameter."
//
// MPW Universal Headers Quickdraw.h declares the C-callable form
// with the RgnHandle (4-byte handle):
// EXTERN_API(void) StdRgn(GrafVerb verb, RgnHandle rgn)
// ONEWORDINLINE(0xA8D1);
//
// Stack frame at trap entry (Pascal LR push, first arg deepest):
// sp+0..3 rgn_handle (last pushed → shallowest)
// sp+4..5 verb_word (first pushed → deepest)
// 6-byte total pop, no result slot (PROCEDURE).
//
// Real-Mac semantic: dispatches Frame/Paint/Erase/Invert/Fill verb
// on the region's scanline data via the current pen state / fill
// pattern.
//
// Systemless HLE compromise — every high-level QuickDraw region trap
// (FrameRgn / PaintRgn / EraseRgn / InvertRgn / FillRgn) draws
// directly via the Rust region rasteriser, bypassing the
// bottleneck dispatch through grafProcs.rgnProc. StdRgn itself
// is reachable only via explicit SetStdProcs → JSR-through-slot —
// a non-corpus pattern. Therefore the HLE pops the 6-byte stack
// frame and returns without performing any drawing.
// caller_observable = false because no corpus caller depends on
// StdRgn producing pixels.
//
// BasiliskII divergence: BII's System 7.5 ROM faithfully draws the
// region AND mutates A0/A1/D0/D1 during rasterisation. Both
// engines agree on the 6-byte pop; they diverge on pixel side-
// effect and register mutation. The Systemless-only
// register-preservation contract is pinned by
// `stdrgn_stub_preserves_non_stack_registers_in_hle_compromise_path`.
(true, 0x0D1) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 6);
Ok(())
}
// StdBits ($A8EB)
// PROCEDURE StdBits(srcBits: BitMap; srcRect, dstRect: Rect; mode: INTEGER; maskRgn: RgnHandle);
// StdBits ($A8EB): Standard CopyBits bottleneck — defers to copy_bits_common targeting current port's bitmap per IM:I I-176
(true, 0x0EB) => {
let sp = cpu.read_reg(Register::A7);
let mask_rgn = bus.read_long(sp);
let mode = bus.read_word(sp + 4) as i16;
let dst_rect_ptr = bus.read_long(sp + 6);
let src_rect_ptr = bus.read_long(sp + 10);
let src_bits_ptr = bus.read_long(sp + 14);
cpu.write_reg(Register::A7, sp + 18);
let dst_bits_ptr = self.bitmap_ptr_for_port(bus, *self.current_port);
if dst_bits_ptr == 0 {
return Some(Ok(()));
}
if let Err(err) = self.copy_bits_common(
cpu,
bus,
src_bits_ptr,
dst_bits_ptr,
src_rect_ptr,
dst_rect_ptr,
mode,
mask_rgn,
) {
return Some(Err(err));
}
Ok(())
}
// StdPutPic ($A8F0)
// PROCEDURE StdPutPic(dataPtr: Ptr; byteCount: INTEGER);
// Inside Macintosh Volume I, p. I-200; Imaging With QuickDraw
// (1994), pp. 3-138 to 3-139.
// Pascal frame: SP+0..3 = dataPtr (Ptr), SP+4..5 = byteCount, pop 6.
// Real-Mac semantic: emits picture-recording bytes into the
// currently-open picture (between OpenPicture and ClosePicture).
// HLE no-op: Systemless's PICT recording (OpenPicture $A8F3,
// ClosePicture $A8F4) is implemented end-to-end without going
// through the bottleneck. Direct trap calls pop the documented
// 6-byte frame and return noErr in D0 for assembly callers.
(true, 0x0F0) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 6);
cpu.write_reg(Register::D0, 0);
Ok(())
}
// StdComment ($A8F1)
// PROCEDURE StdComment(kind, dataSize: INTEGER; dataHandle: Handle);
// Inside Macintosh Volume I, I-198 + Imaging With QuickDraw 1994 3-137
// Pascal frame: SP+0..1 = kind, SP+2..3 = dataSize,
// SP+4..7 = dataHandle, pop 8.
// Real-Mac semantic: processes a PICT comment opcode emitted
// during DrawPicture playback; default behaviour ignores the
// comment per IM:I I-198 ("StdComment simply ignores the
// comment"). PicComment ($A8F2) is the ENCODER counterpart that
// emits a comment INTO an open picture; StdComment is the
// DECODER hook called during playback.
// HLE no-op: matches IM-canonical "ignore" semantic exactly.
// Systemless's DrawPicture ignores all comment opcodes regardless
// of whether they reach this bottleneck.
// StdComment ($A8F1): Pops 8 bytes (kind INTEGER + dataSize INTEGER + dataHandle Handle); IM-canonical "ignore comment" per IM:I I-198 + Imaging With QD 3-137
(true, 0x0F1) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// StdGetPic ($A8EE)
// PROCEDURE StdGetPic(dataPtr: Ptr; byteCount: INTEGER);
// Inside Macintosh Volume I, p. I-200; Imaging With QuickDraw
// (1994), pp. 3-138 to 3-139.
// Pascal frame: SP+0..3 = dataPtr (Ptr), SP+4..5 = byteCount, pop 6.
// Real-Mac semantic: reads picture-playback bytes during
// DrawPicture — the inverse of StdPutPic. Systemless's DrawPicture
// parses resident PICT bytes directly and has a data-fork
// spooling fallback for the common "10-byte header was just
// read from file" path. Direct StdGetPic trap calls remain a
// no-op that pops the documented frame and returns noErr in D0.
(true, 0x0EE) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 6);
cpu.write_reg(Register::D0, 0);
Ok(())
}
// StdTxMeas ($A8ED)
// FUNCTION StdTxMeas(byteCount: INTEGER; textBuf: Ptr;
// VAR numer, denom: Point;
// VAR info: FontInfo): INTEGER;
// Inside Macintosh Volume I, I-199; Inside Macintosh: Text
// 1993, 3-99..3-100.
//
// Public MPW C declaration (Text 1993):
// pascal short StdTxMeas(short byteCount, const void *textAddr,
// Point *numer, Point *denom,
// FontInfo *info);
//
// Pascal frame: SP+0..3 = info FontInfo ptr,
// SP+4..7 = denom Point ptr,
// SP+8..11 = numer Point ptr,
// SP+12..15 = textBuf,
// SP+16..17 = byteCount, pop 18 + 2-byte
// result slot at SP+18 (caller pre-pushed before args).
//
// Real-Mac semantic: returns the width of scaled or unscaled
// text and writes current-font metrics to `info`; `numer`/`denom`
// may be adjusted on output when the Font Manager cannot fully
// satisfy the scaling request.
//
// Systemless partial HLE:
// * width is measured using the same glyph advances as the
// high-level TextWidth/StringWidth/CharWidth path
// * explicit horizontal numer/denom scaling is applied to the
// returned width
// * `info` mirrors GetFontInfo for the current port font/size
// * `numer`/`denom` are left as supplied, so callers using the
// canonical identity-scaling path (1,1 / 1,1) or scaling
// `info` themselves still get coherent results
//
// The broader output-scaling reconciliation path remains partial,
// and Systemless's direct StdText bottleneck path still doesn't draw
// explicitly scaled text. The common-case measurement behavior is
// nonetheless much more useful than the prior hard-coded zero
// stub.
(true, 0x0ED) => {
let sp = cpu.read_reg(Register::A7);
let info_ptr = bus.read_long(sp);
let denom_ptr = bus.read_long(sp + 4);
let numer_ptr = bus.read_long(sp + 8);
let text_buf = bus.read_long(sp + 12);
let byte_count = bus.read_word(sp + 16) as i16;
let (face, scale) = get_font_face_scaled(self.tx_font, self.tx_size);
let mut total_width = 0i32;
for i in 0..byte_count {
let ch = bus.read_byte(text_buf + i as u32) as char;
let advance =
if let Some((glyph, _)) = get_glyph(self.tx_font, self.tx_size, ch) {
i32::from(self.glyph_advance(glyph) * scale)
} else {
i32::from(self.missing_glyph_advance() * scale)
};
total_width += advance;
}
let numer_h = if numer_ptr != 0 {
bus.read_word(numer_ptr + 2) as i16
} else {
1
};
let denom_h = if denom_ptr != 0 {
bus.read_word(denom_ptr + 2) as i16
} else {
1
};
let scaled_width = if numer_h > 0 && denom_h > 0 {
let numer_i32 = i32::from(numer_h);
let denom_i32 = i32::from(denom_h);
((total_width * numer_i32) + (denom_i32 / 2)) / denom_i32
} else {
total_width
}
.clamp(i32::from(i16::MIN), i32::from(i16::MAX))
as i16;
if info_ptr != 0 {
let metrics = face.metrics;
bus.write_word(info_ptr, (metrics.ascent * scale) as u16);
bus.write_word(info_ptr + 2, (metrics.descent * scale) as u16);
bus.write_word(info_ptr + 4, (metrics.wid_max * scale) as u16);
bus.write_word(info_ptr + 6, (metrics.leading * scale) as u16);
}
// info(4)+denom(4)+numer(4)+textBuf(4)+byteCount(2) = 18 + result(2)
bus.write_word(sp + 18, scaled_width as u16);
cpu.write_reg(Register::A7, sp + 18);
Ok(())
}
// SetStdCProcs ($AA4E)
// PROCEDURE SetStdCProcs(VAR cProcs: CQDProcs);
// Inside Macintosh Volume V, V-77 + V-91 (CQDProcs record layout)
// + Imaging With QuickDraw 1994 7-83
// Pascal frame: SP+0..3 = cProcs ptr (VAR CQDProcs), pop 4.
// Real-Mac semantic: fills textProc..putPicProc with the 13
// standard QuickDraw bottlenecks, writes opcodeProc with the
// default undefined-opcode handler (StdOpcodeProc), writes
// newProc1 with the standard StdPix handler, and leaves the
// remaining reserved newProc2..newProc6 fields NIL. IM:V V-77
// says SetStdCProcs returns a CQDProcs record whose fields point
// to the standard low-level routines; IM:V V-91 / Imaging With
// QuickDraw 4-60..4-61 define opcodeProc plus 6 extension slots
// beyond QDProcs; IWQD 7-82 defines StdOpcodeProc; QuickTime
// (1993) 3-137..3-138 identifies newProc1 as the StdPix entry
// obtained via SetStdCProcs. A BasiliskII 7.5.3 ROM probe
// matches that shape: 15 non-NIL routine pointers followed by
// 5 NIL reserved slots.
//
// Trap-backed fields receive their protected callable gateways.
// StdPix has no A-line identity, so its distinct callable gateway
// remains explicitly nonterminal and reaches `_Unimplemented`.
(true, 0x24E) => {
let sp = cpu.read_reg(Register::A7);
let procs_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if procs_ptr != 0 {
// CQDProcs field order per IM:V V-91 / IWQD 4-60:
// 13 inherited QDProcs slots + opcodeProc + newProc1
// (StdPix) + 5 remaining reserved newProc slots.
// Write the 15 concrete defaults as callable system
// entries, then leave the reserved extension slots NIL.
const STD_COLOR_PROC_TRAPS: [u16; 14] = [
0xA882, // textProc (StdText)
0xA890, // lineProc (StdLine)
0xA8A0, // rectProc (StdRect)
0xA8AF, // rRectProc (StdRRect)
0xA8B6, // ovalProc (StdOval)
0xA8BD, // arcProc (StdArc)
0xA8C5, // polyProc (StdPoly)
0xA8D1, // rgnProc (StdRgn)
0xA8EB, // bitsProc (StdBits)
0xA8F1, // commentProc (StdComment)
0xA8ED, // txMeasProc (StdTxMeas)
0xA8EE, // getPicProc (StdGetPic)
0xA8F0, // putPicProc (StdPutPic)
0xABF8, // opcodeProc (StdOpcodeProc)
];
for (i, trap) in STD_COLOR_PROC_TRAPS.iter().enumerate() {
let gateway = self.get_or_create_tool_trap_trampoline(bus, *trap);
bus.write_long(procs_ptr + (i as u32) * 4, gateway);
}
let std_pix = self.get_or_create_std_pix_gateway(bus);
bus.write_long(procs_ptr + 14 * 4, std_pix); // newProc1 (StdPix)
for i in 15..20u32 {
bus.write_long(procs_ptr + i * 4, 0);
}
}
Ok(())
}
// ========== Polygon ==========
// OpenPoly ($A8CB)
// FUNCTION OpenPoly: PolyHandle;
// Inside Macintosh Volume I, I-189
// OpenPoly ($A8CB): Begins recording polygon vertices
(true, 0x0CB) => {
let sp = cpu.read_reg(Register::A7);
// Allocate a placeholder PolyRec (will be filled by ClosePoly).
let poly = bus.alloc(14);
bus.write_word(poly, 14); // polySize (header only, updated later)
let handle = bus.alloc(4);
bus.write_long(handle, poly);
bus.write_long(sp, handle);
self.recording_polygon = Some(super::dispatch::PolygonRecording {
handle,
vertices: Vec::new(),
});
Ok(())
}
// ClosePoly ($A8CC)
// PROCEDURE ClosePoly;
// Inside Macintosh Volume I, I-189
// ClosePoly ($A8CC): Finishes polygon recording
(true, 0x0CC) => {
if let Some(rec) = self.recording_polygon.take() {
let handle = rec.handle;
let verts = &rec.vertices;
// PolyRec: polySize(2) + polyBBox(8) + polyPoints(4*N)
let data_size = 10 + verts.len() as u32 * 4;
let poly = bus.alloc(data_size);
bus.write_long(handle, poly);
bus.write_word(poly, data_size as u16); // polySize
// Compute bounding box
let (mut min_v, mut min_h) = (i16::MAX, i16::MAX);
let (mut max_v, mut max_h) = (i16::MIN, i16::MIN);
for &(v, h) in verts {
min_v = min_v.min(v);
min_h = min_h.min(h);
max_v = max_v.max(v);
max_h = max_h.max(h);
}
if verts.is_empty() {
min_v = 0;
min_h = 0;
max_v = 0;
max_h = 0;
}
bus.write_word(poly + 2, min_v as u16); // polyBBox.top
bus.write_word(poly + 4, min_h as u16); // polyBBox.left
bus.write_word(poly + 6, max_v as u16); // polyBBox.bottom
bus.write_word(poly + 8, max_h as u16); // polyBBox.right
// Write vertex points
for (i, &(v, h)) in verts.iter().enumerate() {
let off = poly + 10 + i as u32 * 4;
bus.write_word(off, v as u16);
bus.write_word(off + 2, h as u16);
}
}
Ok(())
}
// KillPoly ($A8CD)
// Releases the memory occupied by the given polygon.
// PROCEDURE KillPoly(poly: PolyHandle);
// Inside Macintosh Volume I, I-191
//
// KillPoly ($A8CD): Releases polygon memory per IM:I I-191
(true, 0x0CD) => {
let sp = cpu.read_reg(Register::A7);
let poly_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if poly_handle != 0 {
let poly_ptr = bus.read_long(poly_handle);
if poly_ptr != 0 {
bus.free(poly_ptr);
}
bus.free(poly_handle);
}
Ok(())
}
// OffsetPoly ($A8CE)
// PROCEDURE OffsetPoly(poly: PolyHandle; dh, dv: INTEGER);
// Inside Macintosh Volume I, I-191
// Pascal pushes args left-to-right so the deepest is leftmost:
// dv at SP+0, dh at SP+2, poly at SP+4 (matches OffsetRgn).
// OffsetPoly ($A8CE): Offsets bbox + vertices per IM:I I-191
(true, 0x0CE) => {
let sp = cpu.read_reg(Register::A7);
let dv = bus.read_word(sp) as i16;
let dh = bus.read_word(sp + 2) as i16;
let poly_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if poly_handle != 0 {
let poly_ptr = bus.read_long(poly_handle);
if poly_ptr != 0 {
let size = bus.read_word(poly_ptr) as u32;
let n_points = (size.saturating_sub(10)) / 4;
// Offset bbox
for off in [2u32, 6] {
let v = bus.read_word(poly_ptr + off) as i16;
bus.write_word(poly_ptr + off, v.wrapping_add(dv) as u16);
}
for off in [4u32, 8] {
let h = bus.read_word(poly_ptr + off) as i16;
bus.write_word(poly_ptr + off, h.wrapping_add(dh) as u16);
}
// Offset each vertex
for i in 0..n_points {
let base = poly_ptr + 10 + i * 4;
let v = bus.read_word(base) as i16;
let h = bus.read_word(base + 2) as i16;
bus.write_word(base, v.wrapping_add(dv) as u16);
bus.write_word(base + 2, h.wrapping_add(dh) as u16);
}
}
}
Ok(())
}
// FramePoly ($A8C6)
// PROCEDURE FramePoly(poly: PolyHandle);
// Inside Macintosh Volume I, I-190
// Draws the closing edge from last vertex back to the first per
// IM:I I-189 ("ClosePoly closes the polygon by adding an
// additional line that connects the last point to the first
// point"). OpenRgn-recording shim uses the polygon's stored
// polyBBox (4 words at poly_ptr+2).
// FramePoly ($A8C6): Strokes each polygon edge incl. closing edge; OpenRgn-recording shim folds polyBBox into recording_region per IM:I I-190
(true, 0x0C6) => {
let sp = cpu.read_reg(Register::A7);
let poly_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_poly(bus, poly_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
let verts = self.read_poly_vertices(bus, poly_handle);
let n = verts.len();
if n >= 2 {
for i in 0..n {
let (v0, h0) = verts[i];
let (v1, h1) = verts[(i + 1) % n];
if v0 == v1 && h0 == h1 {
continue; // skip degenerate zero-length closing edge
}
let _ = self.draw_line(cpu, bus, h0, v0, h1, v1);
}
}
Ok(())
}
// PaintPoly ($A8C7)
// PROCEDURE PaintPoly(poly: PolyHandle);
// Inside Macintosh Volume I, I-190
//
// OpenRgn-recording shim — see FramePoly notes above.
// PaintPoly ($A8C7): Fills polygon with current pen pattern (paint verb); OpenRgn-recording shim folds polyBBox into recording_region per IM:I I-190
(true, 0x0C7) => {
let sp = cpu.read_reg(Register::A7);
let poly_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_poly(bus, poly_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_poly(cpu, bus, poly_handle, ShapeOp::Paint);
Ok(())
}
// ErasePoly ($A8C8)
// PROCEDURE ErasePoly(poly: PolyHandle);
// Inside Macintosh Volume I, I-190
//
// OpenRgn-recording shim — see FramePoly notes above.
// ErasePoly ($A8C8): Fills polygon with bgPat (erase verb); OpenRgn-recording shim folds polyBBox into recording_region per IM:I I-190
(true, 0x0C8) => {
let sp = cpu.read_reg(Register::A7);
let poly_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_poly(bus, poly_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_poly(cpu, bus, poly_handle, ShapeOp::Erase);
Ok(())
}
// InvertPoly ($A8C9)
// PROCEDURE InvertPoly(poly: PolyHandle);
// Inside Macintosh Volume I, I-190
//
// OpenRgn-recording shim — see FramePoly notes above.
// InvertPoly ($A8C9): Inverts polygon area (XOR with $FF); OpenRgn-recording shim folds polyBBox into recording_region per IM:I I-190
(true, 0x0C9) => {
let sp = cpu.read_reg(Register::A7);
let poly_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_poly(bus, poly_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_poly(cpu, bus, poly_handle, ShapeOp::Invert);
Ok(())
}
// FillPoly ($A8CA)
// PROCEDURE FillPoly(poly: PolyHandle; pat: Pattern);
// Inside Macintosh Volume I, I-190
// Stack: SP+0: pat(4), SP+4: poly(4) → pop 8.
//
// OpenRgn-recording shim — see FillRect notes.
// FillPoly ($A8CA): Fills polygon with caller-supplied 8-byte Pattern; OpenRgn-recording shim folds polyBBox into recording_region per IM:I I-190
(true, 0x0CA) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
let poly_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if self.extend_recording_region_from_poly(bus, poly_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
let mut pat = [0u8; 8];
for (i, byte) in pat.iter_mut().enumerate() {
*byte = bus.read_byte(pat_ptr + i as u32);
}
self.draw_poly(cpu, bus, poly_handle, ShapeOp::Fill(pat));
Ok(())
}
// ========== Region Drawing ==========
// FrameRgn ($A8D2)
// Draws an outline just inside the specified region.
// PROCEDURE FrameRgn(rgn: RgnHandle);
// Inside Macintosh Volume I, I-186
(true, 0x0D2) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_rgn(bus, rgn_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rgn(cpu, bus, rgn_handle, ShapeOp::Frame);
Ok(())
}
// PaintRgn ($A8D3)
// Paints the specified region with current pen pattern and mode.
// PROCEDURE PaintRgn(rgn: RgnHandle);
// Inside Macintosh Volume I, I-186
(true, 0x0D3) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_rgn(bus, rgn_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rgn(cpu, bus, rgn_handle, ShapeOp::Paint);
Ok(())
}
// EraseRgn ($A8D4)
// PROCEDURE EraseRgn(rgn: RgnHandle);
// Inside Macintosh Volume I, I-192
//
// OpenRgn-recording shim — see FrameRgn notes above.
// EraseRgn ($A8D4): Fills region with bgPat (erase verb); complex regions via differential membership cache; OpenRgn-recording shim folds bbox per IM:I I-192
(true, 0x0D4) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_rgn(bus, rgn_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rgn(cpu, bus, rgn_handle, ShapeOp::Erase);
Ok(())
}
// InvertRgn ($A8D5)
// PROCEDURE InvertRgn(rgn: RgnHandle);
// Inside Macintosh Volume I, I-192
//
// OpenRgn-recording shim — see FrameRgn notes above.
// InvertRgn ($A8D5): Inverts region (invert verb); complex regions via differential membership cache; OpenRgn-recording shim folds bbox per IM:I I-192
(true, 0x0D5) => {
let sp = cpu.read_reg(Register::A7);
let rgn_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if self.extend_recording_region_from_rgn(bus, rgn_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
self.draw_rgn(cpu, bus, rgn_handle, ShapeOp::Invert);
Ok(())
}
// FillRgn ($A8D6)
// PROCEDURE FillRgn(rgn: RgnHandle; pat: Pattern);
// Inside Macintosh Volume I, I-192
//
// Per Pascal left-to-right push convention pat is the last
// parameter, so pat is at SP+0 and rgn at SP+4 — matches
// FillRect / FillOval / FillRoundRect / FillPoly / FillArc.
//
// OpenRgn-recording shim — see FillRect notes.
// FillRgn ($A8D6): Fills region with caller-supplied 8-byte Pattern; complex regions via differential membership cache; OpenRgn-recording shim folds bbox per IM:I I-192
(true, 0x0D6) => {
let sp = cpu.read_reg(Register::A7);
let pat_ptr = bus.read_long(sp);
let rgn_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if self.extend_recording_region_from_rgn(bus, rgn_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
let mut pat = [0u8; 8];
for (i, byte) in pat.iter_mut().enumerate() {
*byte = bus.read_byte(pat_ptr + i as u32);
}
self.draw_rgn(cpu, bus, rgn_handle, ShapeOp::Fill(pat));
Ok(())
}
// ========== Misc QD ==========
// ScalePt ($A8F8)
// Scales a width/height pair from srcRect proportions to
// dstRect proportions. The minimum returned value is (1,1).
// PROCEDURE ScalePt (VAR pt: Point; srcRect, dstRect: Rect);
// Inside Macintosh Volume I, I-195
//
// "A width and height are passed in pt; the horizontal
// component of pt is the width, and its vertical component
// is the height. ScalePt scales these measurements by the
// ratio of dstRect's dimensions to srcRect's dimensions."
//
// Stack: SP+0=dstRect(4), SP+4=srcRect(4), SP+8=pt(4). Pop 12.
//
// Regression coverage:
// scalept_scales_width_and_height_by_rect_ratio
// scalept_minimum_result_is_one_one
// ScalePt ($A8F8): Scales width/height by ratio of dstRect to srcRect; minimum (1,1) per IM:I I-195
(true, 0x0F8) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let src_rect_ptr = bus.read_long(sp + 4);
let pt_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
let pt_v = bus.read_word(pt_ptr) as i16;
let pt_h = bus.read_word(pt_ptr + 2) as i16;
let src_top = bus.read_word(src_rect_ptr) as i16;
let src_left = bus.read_word(src_rect_ptr + 2) as i16;
let src_bottom = bus.read_word(src_rect_ptr + 4) as i16;
let src_right = bus.read_word(src_rect_ptr + 6) as i16;
let dst_top = bus.read_word(dst_rect_ptr) as i16;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16;
let src_w = (src_right - src_left) as i32;
let src_h = (src_bottom - src_top) as i32;
let dst_w = (dst_right - dst_left) as i32;
let dst_h = (dst_bottom - dst_top) as i32;
// Scale dimensions by ratio, clamped to minimum of 1.
let scaled_h = if src_w != 0 {
((pt_h as i32) * dst_w / src_w).max(1)
} else {
(pt_h as i32).max(1)
};
let scaled_v = if src_h != 0 {
((pt_v as i32) * dst_h / src_h).max(1)
} else {
(pt_v as i32).max(1)
};
bus.write_word(pt_ptr, scaled_v as u16);
bus.write_word(pt_ptr + 2, scaled_h as u16);
Ok(())
}
// MapPt ($A8F9)
// Maps a point from srcRect coordinates to dstRect coordinates
// using proportional scaling.
// PROCEDURE MapPt(VAR pt: Point; srcRect, dstRect: Rect);
// Inside Macintosh Volume I, I-196
//
// Regression coverage:
// mappt_maps_point_proportionally_between_rectangles
// mappt_consumes_point_and_rect_arguments
// Stack: SP+0=dstRect(4), SP+4=srcRect(4), SP+8=pt(4)
// MapPt ($A8F9): Proportional point mapping between source and destination rectangles
(true, 0x0F9) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let src_rect_ptr = bus.read_long(sp + 4);
let pt_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
let pt_v = bus.read_word(pt_ptr) as i16;
let pt_h = bus.read_word(pt_ptr + 2) as i16;
let src_top = bus.read_word(src_rect_ptr) as i16;
let src_left = bus.read_word(src_rect_ptr + 2) as i16;
let src_bottom = bus.read_word(src_rect_ptr + 4) as i16;
let src_right = bus.read_word(src_rect_ptr + 6) as i16;
let dst_top = bus.read_word(dst_rect_ptr) as i16;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16;
let src_w = (src_right - src_left) as i32;
let src_h = (src_bottom - src_top) as i32;
let dst_w = (dst_right - dst_left) as i32;
let dst_h = (dst_bottom - dst_top) as i32;
let mapped_h = if src_w != 0 {
dst_left as i32 + (pt_h as i32 - src_left as i32) * dst_w / src_w
} else {
pt_h as i32
};
let mapped_v = if src_h != 0 {
dst_top as i32 + (pt_v as i32 - src_top as i32) * dst_h / src_h
} else {
pt_v as i32
};
bus.write_word(pt_ptr, mapped_v as u16);
bus.write_word(pt_ptr + 2, mapped_h as u16);
Ok(())
}
// MapRect ($A8FA)
// Maps a rectangle from srcRect coordinate space to dstRect coordinate space.
// PROCEDURE MapRect(VAR r: Rect; srcRect, dstRect: Rect);
// Inside Macintosh Volume I, I-197
(true, 0x0FA) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let src_rect_ptr = bus.read_long(sp + 4);
let r_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if r_ptr != 0 && src_rect_ptr != 0 && dst_rect_ptr != 0 {
let r_top = bus.read_word(r_ptr) as i16 as i32;
let r_left = bus.read_word(r_ptr + 2) as i16 as i32;
let r_bottom = bus.read_word(r_ptr + 4) as i16 as i32;
let r_right = bus.read_word(r_ptr + 6) as i16 as i32;
let s_top = bus.read_word(src_rect_ptr) as i16 as i32;
let s_left = bus.read_word(src_rect_ptr + 2) as i16 as i32;
let s_bottom = bus.read_word(src_rect_ptr + 4) as i16 as i32;
let s_right = bus.read_word(src_rect_ptr + 6) as i16 as i32;
let d_top = bus.read_word(dst_rect_ptr) as i16 as i32;
let d_left = bus.read_word(dst_rect_ptr + 2) as i16 as i32;
let d_bottom = bus.read_word(dst_rect_ptr + 4) as i16 as i32;
let d_right = bus.read_word(dst_rect_ptr + 6) as i16 as i32;
let s_w = s_right - s_left;
let s_h = s_bottom - s_top;
let d_w = d_right - d_left;
let d_h = d_bottom - d_top;
let map_h = |h: i32| -> i32 {
if s_w != 0 {
d_left + (h - s_left) * d_w / s_w
} else {
h
}
};
let map_v = |v: i32| -> i32 {
if s_h != 0 {
d_top + (v - s_top) * d_h / s_h
} else {
v
}
};
bus.write_word(r_ptr, map_v(r_top) as u16);
bus.write_word(r_ptr + 2, map_h(r_left) as u16);
bus.write_word(r_ptr + 4, map_v(r_bottom) as u16);
bus.write_word(r_ptr + 6, map_h(r_right) as u16);
}
Ok(())
}
// MapRgn ($A8FB)
// PROCEDURE MapRgn(rgn: RgnHandle; srcRect, dstRect: Rect);
// Inside Macintosh Volume I, I-196
//
// For Systemless's rectangular-region approximation, MapRgn
// applies the same proportional scaling as MapRect to the
// region's bbox. A general implementation would map every
// vertex of the region's polygon outline.
//
// Stack: SP+0=dstRect(4), SP+4=srcRect(4), SP+8=rgn(4).
// Pops 12.
//
// Regression coverage:
// maprgn_maps_region_bbox_proportionally
// maprgn_consumes_region_and_rect_arguments
// MapRgn ($A8FB): Maps region bbox from srcRect to dstRect proportionally; per IM:I I-196
(true, 0x0FB) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let src_rect_ptr = bus.read_long(sp + 4);
let rgn_handle = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if rgn_handle != 0 && src_rect_ptr != 0 && dst_rect_ptr != 0 {
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr != 0 {
let r_top = bus.read_word(rgn_ptr + 2) as i16 as i32;
let r_left = bus.read_word(rgn_ptr + 4) as i16 as i32;
let r_bottom = bus.read_word(rgn_ptr + 6) as i16 as i32;
let r_right = bus.read_word(rgn_ptr + 8) as i16 as i32;
let s_top = bus.read_word(src_rect_ptr) as i16 as i32;
let s_left = bus.read_word(src_rect_ptr + 2) as i16 as i32;
let s_bottom = bus.read_word(src_rect_ptr + 4) as i16 as i32;
let s_right = bus.read_word(src_rect_ptr + 6) as i16 as i32;
let d_top = bus.read_word(dst_rect_ptr) as i16 as i32;
let d_left = bus.read_word(dst_rect_ptr + 2) as i16 as i32;
let d_bottom = bus.read_word(dst_rect_ptr + 4) as i16 as i32;
let d_right = bus.read_word(dst_rect_ptr + 6) as i16 as i32;
let s_w = s_right - s_left;
let s_h = s_bottom - s_top;
let d_w = d_right - d_left;
let d_h = d_bottom - d_top;
let mh = |h: i32| -> i32 {
if s_w != 0 {
d_left + (h - s_left) * d_w / s_w
} else {
h
}
};
let mv = |v: i32| -> i32 {
if s_h != 0 {
d_top + (v - s_top) * d_h / s_h
} else {
v
}
};
bus.write_word(rgn_ptr + 2, mv(r_top) as u16);
bus.write_word(rgn_ptr + 4, mh(r_left) as u16);
bus.write_word(rgn_ptr + 6, mv(r_bottom) as u16);
bus.write_word(rgn_ptr + 8, mh(r_right) as u16);
}
}
Ok(())
}
// MapPoly ($A8FC)
// Maps a polygon from srcRect coordinates to dstRect
// coordinates by mapping every vertex via MapPt logic.
// PROCEDURE MapPoly (poly: PolyHandle; srcRect, dstRect: Rect);
// Inside Macintosh Volume I, I-197
//
// "Given a polygon within srcRect, MapPoly maps it to a
// similarly located polygon within dstRect by calling MapPt
// to map all the points that define the polygon."
//
// Polygon layout: polySize(2) + polyBBox(8) + polyPoints(4×N).
// Stack: SP+0=dstRect(4), SP+4=srcRect(4), SP+8=poly(4). Pop 12.
//
// Regression coverage:
// mappoly_maps_all_vertices_proportionally
// mappoly_consumes_polygon_and_rect_arguments
// MapPoly ($A8FC): Maps all polygon vertices from srcRect to dstRect proportionally; per IM:I I-197
(true, 0x0FC) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let src_rect_ptr = bus.read_long(sp + 4);
let poly_handle = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if poly_handle != 0 {
let poly_ptr = bus.read_long(poly_handle);
if poly_ptr != 0 {
let src_top = bus.read_word(src_rect_ptr) as i16 as i32;
let src_left = bus.read_word(src_rect_ptr + 2) as i16 as i32;
let src_bottom = bus.read_word(src_rect_ptr + 4) as i16 as i32;
let src_right = bus.read_word(src_rect_ptr + 6) as i16 as i32;
let dst_top = bus.read_word(dst_rect_ptr) as i16 as i32;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16 as i32;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16 as i32;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16 as i32;
let src_w = src_right - src_left;
let src_h = src_bottom - src_top;
let dst_w = dst_right - dst_left;
let dst_h = dst_bottom - dst_top;
let size = bus.read_word(poly_ptr) as u32;
// Map bbox (4 words at +2)
let map_h = |h: i16| -> i16 {
if src_w != 0 {
(dst_left + (h as i32 - src_left) * dst_w / src_w) as i16
} else {
h
}
};
let map_v = |v: i16| -> i16 {
if src_h != 0 {
(dst_top + (v as i32 - src_top) * dst_h / src_h) as i16
} else {
v
}
};
// Map bbox
let bb_top = bus.read_word(poly_ptr + 2) as i16;
let bb_left = bus.read_word(poly_ptr + 4) as i16;
let bb_bottom = bus.read_word(poly_ptr + 6) as i16;
let bb_right = bus.read_word(poly_ptr + 8) as i16;
bus.write_word(poly_ptr + 2, map_v(bb_top) as u16);
bus.write_word(poly_ptr + 4, map_h(bb_left) as u16);
bus.write_word(poly_ptr + 6, map_v(bb_bottom) as u16);
bus.write_word(poly_ptr + 8, map_h(bb_right) as u16);
// Map each vertex
let n_points = size.saturating_sub(10) / 4;
for i in 0..n_points {
let base = poly_ptr + 10 + i * 4;
let v = bus.read_word(base) as i16;
let h = bus.read_word(base + 2) as i16;
bus.write_word(base, map_v(v) as u16);
bus.write_word(base + 2, map_h(h) as u16);
}
}
}
Ok(())
}
// EqualPt ($A881)
// Compares two points and returns TRUE if equal, FALSE if not.
// FUNCTION EqualPt (pt1,pt2: Point) : BOOLEAN;
// Inside Macintosh Volume I, I-193
(true, 0x081) => {
let sp = cpu.read_reg(Register::A7);
let pt2_v = bus.read_word(sp) as i16;
let pt2_h = bus.read_word(sp + 2) as i16;
let pt1_v = bus.read_word(sp + 4) as i16;
let pt1_h = bus.read_word(sp + 6) as i16;
let eq = pt1_v == pt2_v && pt1_h == pt2_h;
bus.write_word(sp + 8, if eq { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// HidePen ($A896)
// Decrements the pen visibility counter. When pnVis < 0, drawing
// operations with the pen have no visible effect.
// PROCEDURE HidePen;
// Inside Macintosh Volume I, I-168
//
// Regression coverage:
// src/trap/quickdraw.rs::tests::hidepen_decrements_current_port_pnvis_and_preserves_stack
// HidePen ($A896): Decrements pnVis counter per IM:I I-168
(true, 0x096) => {
self.pn_vis -= 1;
self.sync_current_port_draw_state(bus);
Ok(())
}
// ShowPen ($A897)
// Increments the pen visibility counter. Pen is visible when
// pnVis >= 0 (initial value is 0).
// PROCEDURE ShowPen;
// Inside Macintosh Volume I, I-168
//
// Regression coverage:
// src/trap/quickdraw.rs::tests::showpen_increments_pnvis_and_allows_positive_values
// src/trap/quickdraw.rs::tests::showpen_balances_hidepen_back_to_zero
// ShowPen ($A897): Increments pnVis counter per IM:I I-168
(true, 0x097) => {
self.pn_vis += 1;
self.sync_current_port_draw_state(bus);
Ok(())
}
// DisposPixPat ($AA08)
// Releases a PixPat and its owned data, expanded-data and PixMap handles.
// PROCEDURE DisposPixPat (ppat: PixPatHandle);
// Imaging With QuickDraw (1994), p. 4-91.
// DisposeCCursor ($AA26)
// Releases a color cursor and its owned compound handles.
// PROCEDURE DisposeCCursor (cCrsr: CCrsrHandle);
// Imaging With QuickDraw (1994), pp. 8-26--8-27.
(true, 0x208) | (true, 0x226) => {
let sp = cpu.read_reg(Register::A7);
let handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let _params = crate::cursor_manager::evaluate_dispose_ccursor_parameters(handle);
self.dispose_color_compound_handle(bus, handle);
Ok(())
}
// PenPixPat ($AA0A)
// Sets the pen pixel pattern in the current cGrafPort.
// PROCEDURE PenPixPat (pp: PixPatHandle);
// Inside Macintosh Volume V (1986), p. V-72
//
// "PenPixPat is analogous to PenPat, but uses a multicolor
// pixel pattern. The handle is placed directly into the
// port's pnPixPat field."
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) PenPixPat(PixPatHandle pp) ONEWORDINLINE(0xAA0A);
//
// Tool-bit Pascal PROCEDURE ABI:
// Stack on entry: [SP+0] = pp (4 bytes, PixPatHandle).
// Stack on exit: trap pops 4 bytes; A7 net-balanced
// across the call; no FUNCTION result
// slot is written.
//
// Documented behaviour: when pp != NIL, the PixPat record's
// pat1Data (8 bytes at offset +20) is copied into the
// port's pnPat shadow, and the handle is stored in the
// port's pnPixPat field (+58). When pp == NIL both BII
// System 7.5.3 ROM Color QuickDraw and Systemless HLE take
// an early-exit no-op path before touching pnPixPat: the
// pop is still performed but no port-field write happens.
//
// The NIL early-exit path shares the Pascal PROCEDURE pop-4
// calling convention with BII. The absolute pnPixPat-field
// mutation and pat1Data copy on the non-NIL path requires a
// host-constructed PixPat record whose exact layout differs
// between the two engines.
(true, 0x20A) => {
let sp = cpu.read_reg(Register::A7);
let ppat_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if ppat_handle != 0 {
let ppat_ptr = bus.read_long(ppat_handle);
if ppat_ptr != 0 {
// Copy pat1Data (8 bytes at +20) into pn_pat.
for i in 0..8u32 {
self.pn_pat[i as usize] = bus.read_byte(ppat_ptr + 20 + i);
}
}
// Store handle into port's pnPixPat field (+58).
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port_ptr = bus.read_long(global_ptr);
if port_ptr != 0 {
let old = bus.read_long(port_ptr + 58);
if old != ppat_handle && self.owned_bit_pixpats.contains(&old) {
self.dispose_color_compound_handle(bus, old);
}
bus.write_long(port_ptr + 58, ppat_handle);
}
}
Ok(())
}
// BackPixPat ($AA0B)
// Sets the background pixel pattern in the current cGrafPort.
// PROCEDURE BackPixPat (pp: PixPatHandle);
// Inside Macintosh Volume V (1986), p. V-72
//
// Analogous to BackPat / PenPixPat. Stores the handle into
// the port's bkPixPat field (+32) and copies pat1Data into
// the legacy 8-byte bkPat shadow.
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) BackPixPat(PixPatHandle pp) ONEWORDINLINE(0xAA0B);
//
// Tool-bit Pascal PROCEDURE ABI:
// Stack on entry: [SP+0] = pp (4 bytes, PixPatHandle).
// Stack on exit: trap pops 4 bytes; A7 net-balanced
// across the call; no FUNCTION result
// slot is written.
//
// Documented behaviour: when pp != NIL, the PixPat's
// pat1Data (8 bytes at offset +20) is copied into bk_pat,
// and the handle is stored in the port's bkPixPat field
// (+32). When pp == NIL both BII System 7.5.3 ROM Color
// QuickDraw and Systemless HLE take an early-exit no-op path
// before touching bkPixPat: the pop is still performed
// but no port-field write happens.
//
// The NIL early-exit path shares the Pascal PROCEDURE pop-4
// calling convention with BII.
(true, 0x20B) => {
let sp = cpu.read_reg(Register::A7);
let ppat_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if ppat_handle != 0 {
let ppat_ptr = bus.read_long(ppat_handle);
if ppat_ptr != 0 {
// Copy pat1Data (8 bytes at +20) into bk_pat.
for i in 0..8u32 {
self.bk_pat[i as usize] = bus.read_byte(ppat_ptr + 20 + i);
}
}
// Store handle into the CGrafPort's bkPixPat field (+32).
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port_ptr = bus.read_long(global_ptr);
if port_ptr != 0 {
let old = bus.read_long(port_ptr + 32);
if old != ppat_handle && self.owned_bit_pixpats.contains(&old) {
self.dispose_color_compound_handle(bus, old);
}
bus.write_long(port_ptr + 32, ppat_handle);
}
}
Ok(())
}
// OpColor ($AA21)
// Sets the RGBColor used by addPin, subPin, and blend
// arithmetic transfer modes in the current cGrafPort.
// PROCEDURE OpColor (color: RGBColor);
// Inside Macintosh Volume V (1986), p. V-77
//
// "If the current port is a cGrafPort, the OpColor procedure
// sets the red, green, and blue values used by the AddPin,
// SubPin, and Blend drawing modes. This information is
// actually stored in the grafVars handle in the cGrafPort,
// but you should never need to reference it directly.
// If the current port is a grafPort, OpColor has no effect."
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) OpColor(const RGBColor *color) ONEWORDINLINE(0xAA21);
//
// Tool-bit Pascal PROCEDURE ABI:
// Stack on entry: [SP+0] = color (4 bytes, RGBColor*).
// Stack on exit: trap pops 4 bytes; A7 net-balanced
// across the call; no FUNCTION result
// slot is written.
//
// Documented behaviour: when color != NIL, three RGB words
// (red, green, blue) are read from [color..color+6] and
// stored in the current cGrafPort's grafVars handle. When
// color == NIL the 4-byte pop is still performed but no field
// write happens. Static cGrafPort records without an owned
// grafVars handle use the process-owned per-port index as the
// same live state across attached adapters.
(true, 0x221) => {
let sp = cpu.read_reg(Register::A7);
let rgb_ptr = bus.read_long(sp);
if rgb_ptr != 0 && Self::guest_range_in_ram(bus, rgb_ptr, 6) {
let color = (
bus.read_word(rgb_ptr),
bus.read_word(rgb_ptr + 2),
bus.read_word(rgb_ptr + 4),
);
let port = *self.current_port;
self.write_port_op_color(bus, port, color);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// HiliteColor ($AA22)
// Sets the RGBColor used by the highlight transfer mode in
// the current cGrafPort.
// PROCEDURE HiliteColor(color: RGBColor);
// Inside Macintosh Volume V (1986), p. V-77
//
// "The highlight color is used by all drawing operations that
// use the highlight transfer mode. When a cGrafPort is
// created, its highlight color is initialized from the
// global variable HiliteRGB. The HiliteColor procedure
// allows you to change the highlighting color used by the
// current port. This information is actually stored in the
// grafVars handle in the cGrafPort, but you should never
// need to reference it directly. If the current port is a
// grafPort, HiliteColor has no effect."
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) HiliteColor(const RGBColor *color) ONEWORDINLINE(0xAA22);
//
// Tool-bit Pascal PROCEDURE ABI:
// Stack on entry: [SP+0] = color (4 bytes, RGBColor*).
// Stack on exit: trap pops 4 bytes; A7 net-balanced
// across the call; no FUNCTION result
// slot is written.
//
// Documented behaviour: when color != NIL, three RGB words
// (red, green, blue) are read from [color..color+6] and
// stored in the current cGrafPort's grafVars handle
// (rgbHiliteColor field). Static cGrafPort records without an
// owned grafVars handle use the process-owned per-port index as
// the same live state across attached adapters. When color ==
// NIL both BII System 7.5.3 ROM Color QuickDraw and Systemless
// HLE take an early-exit no-op path before touching grafVars.
// The NIL early-exit path shares the Pascal PROCEDURE pop-4
// calling convention with BII.
(true, 0x222) => {
let sp = cpu.read_reg(Register::A7);
let rgb_ptr = bus.read_long(sp);
if rgb_ptr != 0 && Self::guest_range_in_ram(bus, rgb_ptr, 6) {
let color = (
bus.read_word(rgb_ptr),
bus.read_word(rgb_ptr + 2),
bus.read_word(rgb_ptr + 4),
);
let port = *self.current_port;
self.write_port_hilite_color(bus, port, color);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Stubs — Cursor ==========
// ShieldCursor ($A855)
// PROCEDURE ShieldCursor(shieldRect: Rect; offsetPt: Point);
// Inside Macintosh Volume I, I-474
// Imaging With QuickDraw 1994, p. 8-29
//
// MPW Universal Headers (Quickdraw.h):
//
// EXTERN_API(void) ShieldCursor(const Rect *shieldRect,
// Point offsetPt) ONEWORDINLINE(0xA855);
//
// Pascal LR stack frame at trap entry (first arg deepest):
// sp+0..3 offsetPt (Point by value, last pushed → shallowest)
// sp+4..7 shieldRect (Rect ptr, first pushed → deepest)
// 8-byte total pop, no result slot.
//
// Documented semantics (IM:I I-474): hide cursor when it
// intersects the shielded rectangle (or on mouse movement into
// it), decrement cursor level like HideCursor, and balance
// with ShowCursor.
//
// Systemless tests immediate intersection against the
// host-rendered 16×16 cursor bounds in global screen
// coordinates and applies the documented cursor-level
// decrement when those bounds overlap.
(true, 0x055) => {
let sp = cpu.read_reg(Register::A7);
let offset_v = bus.read_word(sp) as i16;
let offset_h = bus.read_word(sp + 2) as i16;
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let params = crate::cursor_manager::evaluate_shield_cursor_parameters(
rect_ptr, offset_v, offset_h,
);
if params.rect_ptr != 0 {
let shield_rect = (
bus.read_word(params.rect_ptr) as i16,
bus.read_word(params.rect_ptr + 2) as i16,
bus.read_word(params.rect_ptr + 4) as i16,
bus.read_word(params.rect_ptr + 6) as i16,
);
let mouse_pos = self.mouse_position();
let hot_spot = self
.cursor_data()
.map(|(_, _, hot_v, hot_h)| (hot_v, hot_h))
.unwrap_or((0, 0));
if crate::cursor_manager::evaluate_cursor_shield_overlap(
shield_rect,
(params.offset_v, params.offset_h),
mouse_pos,
hot_spot,
) {
self.cursor_state.hide();
}
}
Ok(())
}
// AllocCursor ($AA1D)
// Reallocates cursor memory for use with Color QuickDraw. No-op stub.
// PROCEDURE AllocCursor;
// Inside Macintosh Volume V, V-79
// AllocCursor ($AA1D): No parameters; cursor mem-mgmt is host-side per IM:V V-79
(true, 0x21D) => Ok(()),
// ========== Stubs — Color Manager ==========
// Color2Index ($AA33)
// FUNCTION Color2Index (rgb: RGBColor): LongInt;
// Inside Macintosh Volume V, V-141 (Color Manager — Color
// Manager Routines — Color Conversion)
//
// "The Color2Index routine finds the best available approximation
// to a given absolute color, using the list of search procedures
// in the current device record. It returns a longint, which is a
// pixel value padded with zeros in the high word."
//
// Stack: SP+0: rgb_ptr(4). Return LongInt at SP+4. Pop to SP+4.
//
// Implementation: linear scan of `device_clut` for the entry with
// the smallest sum-of-squared-channel-distances to the requested
// RGB. Real Mac ROMs build a 4-bit (or 5-bit) inverse table for
// O(1) lookup, but a 256-entry linear scan is fast enough for
// Systemless's needs and matches the IM "best available match"
// semantic exactly. The high word of the return is forced to
// zero per the spec.
//
// The Pascal FUNCTION calling convention matches BII, but the
// absolute LONGINT index differs: BII walks the ROM inverse
// table while Systemless does a linear scan.
// Color2Index ($AA33): Linear-scan nearest match against device_clut, skips reserved entries, IM:V V-141
(true, 0x233) => {
let sp = cpu.read_reg(Register::A7);
let rgb_ptr = bus.read_long(sp);
let want_r = bus.read_word(rgb_ptr);
let want_g = bus.read_word(rgb_ptr + 2);
let want_b = bus.read_word(rgb_ptr + 4);
let the_gdevice = bus.read_long(0x0CC8);
let gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else if the_gdevice != 0 {
the_gdevice
} else {
self.main_gdevice_handle
};
let ctab_handle = if gdh != 0 {
Self::gdevice_ctab_handle(bus, gdh)
} else {
0
};
let target_clut = if ctab_handle != 0 && gdh != self.main_gdevice_handle {
self.read_port_clut(bus, ctab_handle)
} else {
*self.device_clut
};
// Use the same `closest_clut_index` helper as DrawPicture /
// CopyBits path so the dst index for a given RGB matches
// across QuickDraw entry points. Linear-scan Euclidean
// diverges from Mac ROM's MakeITable behavior on inputs that
// fall in the same 4-bit cube cell as multiple CLUT entries
// — koji's ModalDialog draw routine hit this and produced
// a different cube index (195 = teal) than BasiliskII (91 =
// pink-purple) for the same dialog colour, with the same
// canonical 8bpp CLUT and the same gamma LUT downstream.
// Routing both paths through one matcher keeps Color2Index
// and the PICT/CopyBits inverse-mapping consistent and
// converges with the Mac ROM behaviour BasiliskII inherits
// from a real ROM image.
//
// Per IM:V V-145, reserved entries are excluded from
// matching: "A reserved entry cannot be matched by another
// client's search procedure, and will never be returned to
// another client by Color2Index". The shared helper doesn't
// currently honour the reserved-entry skip — preserve the
// skip semantic by zeroing reserved entries' RGB before
// matching is overkill; instead, fall back to the linear
// scan when ANY reserved entries exist.
let wanted = [want_r, want_g, want_b];
let any_reserved = self.clut_reserved.iter().any(|&r| r);
let exact_pos = target_clut.iter().enumerate().position(|(i, &e)| {
if any_reserved
&& (gdh == 0 || gdh == self.main_gdevice_handle)
&& self.clut_reserved[i]
{
false
} else {
e == wanted
}
});
let best_idx = if let Some(idx) = exact_pos {
idx
} else if any_reserved && (gdh == 0 || gdh == self.main_gdevice_handle) {
let want_r = want_r as i64;
let want_g = want_g as i64;
let want_b = want_b as i64;
let mut best_idx: usize = 0;
let mut best_dist: i64 = i64::MAX;
for (i, entry) in target_clut.iter().enumerate() {
if self.clut_reserved[i] {
continue;
}
let dr = entry[0] as i64 - want_r;
let dg = entry[1] as i64 - want_g;
let db = entry[2] as i64 - want_b;
let dist = dr * dr + dg * dg + db * db;
if dist < best_dist {
best_dist = dist;
best_idx = i;
if dist == 0 {
break;
}
}
}
best_idx
} else {
super::pict::closest_clut_index(want_r, want_g, want_b, &target_clut) as usize
};
bus.write_long(sp + 4, best_idx as u32);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// GetSubTable ($AA37)
// PROCEDURE GetSubTable(myColors: CTabHandle; iTabRes: INTEGER;
// targetTbl: CTabHandle);
// Inside Macintosh Volume V (1986), p. V-142
// (Color Manager — Color Manager Routines — GetSubTable)
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) GetSubTable(CTabHandle myColors,
// short iTabRes, CTabHandle targetTbl) ONEWORDINLINE(0xAA37);
//
// "The GetSubTable routine takes a ColorTable pointed at by
// myColors, and maps each RGB value into its nearest available
// match for each target table. These best matches are returned
// in the colorSpec.value fields of myColors. The values returned
// are best matches to the RGBColor in targetTbl and the returned
// indices are indices into targetTbl. Best matches are
// calculated using Color2Index and all applicable rules apply.
// A temporary inverse table is built, and then discarded.
// ITabRes controls the resolution of the iTable that is built.
// If targetTbl is NIL, then the current device's color table
// is used, and the device's inverse table is used rather than
// building a new one." (IM:V V-142)
//
// Tool-bit Pascal PROCEDURE (bit 11 set) pop-10 calling
// convention. Caller pushes left-to-right, so the on-stack
// frame is:
// SP+0 : targetTbl (4-byte CTabHandle)
// SP+4 : iTabRes (2-byte INTEGER)
// SP+6 : myColors (4-byte CTabHandle)
// No FUNCTION result slot.
//
// iTabRes is the requested inverse-table resolution (3-5
// bits/channel per IM:V V-138). Systemless does full-precision
// linear-scan Euclidean matching against the supplied
// targetTbl bytes, so iTabRes is recorded for documentation
// but otherwise ignored. BII System 7.5.3 ROM builds a real
// temporary inverse table at the requested resolution and
// calls Color2Index; absolute returned indices may diverge
// from Systemless's for non-trivial CLUTs. The Pascal PROCEDURE
// pop-10 calling convention matches BII.
//
// GetSubTable ($AA37): Group Color2Index over a CTab; NIL targetTbl uses device_clut, IM:V V-142
(true, 0x237) => {
let sp = cpu.read_reg(Register::A7);
let target_handle = bus.read_long(sp);
let _itab_res = bus.read_word(sp + 4);
let my_handle = bus.read_long(sp + 6);
cpu.write_reg(Register::A7, sp + 10);
let my_ptr = if my_handle != 0 {
bus.read_long(my_handle)
} else {
0
};
if my_ptr != 0 {
// Build the target CLUT to match against. NIL targetTbl =
// current device CLUT.
let target_clut: [[u16; 3]; 256] = if target_handle == 0 {
*self.device_clut
} else {
let target_ptr = bus.read_long(target_handle);
if target_ptr == 0 {
*self.device_clut
} else {
let mut clut = [[0u16; 3]; 256];
let target_size = (bus.read_word(target_ptr + 6) as usize).min(255);
for (i, slot) in clut.iter_mut().take(target_size + 1).enumerate() {
let entry = target_ptr + 8 + (i as u32) * 8;
*slot = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
}
// Pad unused slots with a sentinel that won't be
// the closest match for any reasonable RGB query.
for slot in clut.iter_mut().skip(target_size + 1) {
*slot = [0xFFFF, 0x0000, 0xFFFF];
}
clut
}
};
let my_size = (bus.read_word(my_ptr + 6) as usize).min(255);
for i in 0..=my_size {
let entry = my_ptr + 8 + (i as u32) * 8;
let r = bus.read_word(entry + 2);
let g = bus.read_word(entry + 4);
let b = bus.read_word(entry + 6);
let idx = super::pict::closest_clut_index(r, g, b, &target_clut);
bus.write_word(entry, idx as u16);
}
}
Ok(())
}
// AddSearch ($AA3A)
// PROCEDURE AddSearch(searchProc: ProcPtr);
// Inside Macintosh Volume V (1986), p. V-147
// (Color Manager — Custom Search and Complement Procedures — AddSearch).
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) AddSearch(ColorSearchUPP searchProc)
// ONEWORDINLINE(0xAA3A);
//
// Per IM:V V-147 AddSearch allocates an SProcRec via NewHandle
// and links it onto the head of the active gDevice's gdSearchProc
// list. The supplied ProcPtr is later invoked when a Color2Index
// lookup walks the search chain. Systemless does not implement the
// chain (identity color matching is used on a 1bpp grafport host),
// so this is a documented no-op stub that pops the 4-byte ProcPtr
// arg and returns.
//
// Stack: SP+0: searchProc(4). Pop 4. No FUNCTION result slot.
//
// The shared behaviour is the Tool-bit Pascal PROCEDURE pop-4
// calling convention — A7 unchanged across the call regardless
// of the absolute search-chain mutation, which differs between
// engines.
(true, 0x23A) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// AddComp ($AA3B)
// PROCEDURE AddComp(compProc: ProcPtr);
// Inside Macintosh Volume V (1986), p. V-147
// (Color Manager — Custom Search and Complement Procedures — AddComp).
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) AddComp(ColorComplementUPP compProc)
// ONEWORDINLINE(0xAA3B);
//
// Per IM:V V-147 AddComp allocates a CProcRec via NewHandle and
// links it onto the head of the active gDevice's gdCompProc list.
// The supplied ProcPtr is later invoked when an InvertColor /
// Color Manager complement lookup walks the chain. Systemless uses
// the IM:V V-141 default 1's-complement procedure path; custom
// complement procs are not honored, so this is a documented no-op
// stub that pops the 4-byte ProcPtr arg and returns.
//
// Stack: SP+0: compProc(4). Pop 4. No FUNCTION result slot.
//
// The shared behaviour is the Tool-bit Pascal PROCEDURE pop-4
// calling convention.
(true, 0x23B) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// SetClientID ($AA3C)
// PROCEDURE SetClientID(id: INTEGER);
// Inside Macintosh Volume V (1986), p. V-147
// (Color Manager — Custom Search and Complement Procedures — SetClientID).
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) SetClientID(short id) ONEWORDINLINE(0xAA3C);
//
// Per IM:V V-147: "The SetClientID procedure sets the gdID field
// in the current device record to identify this client program to
// its search and complement procedures." The same low-byte ID is
// copied into changed device ColorTable entries by SetEntries.
//
// Stack: SP+0: id(2). Pop 2. No FUNCTION result slot.
//
// The shared behaviour is the Tool-bit Pascal PROCEDURE pop-2
// calling convention.
(true, 0x23C) => {
let sp = cpu.read_reg(Register::A7);
let client_id = bus.read_word(sp);
let gdh = self.active_gdevice_or_main(bus);
if gdh != 0 {
let gd = bus.read_long(gdh);
if gd != 0 {
bus.write_word(gd + 2, client_id);
}
}
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// SaveEntries ($AA49)
// PROCEDURE SaveEntries(srcTable: CTabHandle; resultTable: CTabHandle;
// VAR selection: ReqListRec);
// Inside Macintosh Volume V (1986), p. V-144
// (Color Manager — Color Manager Routines — SaveEntries)
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) SaveEntries(CTabHandle srcTable,
// CTabHandle resultTable, ReqListRec *selection)
// ONEWORDINLINE(0xAA49);
//
// "SaveEntries saves a selection of entries from srcTable into
// resultTable. The entries to be set are enumerated in the
// selection parameter ... If an entry is not present in
// srcTable, then that position of the requestList is set to
// colReqErr ... SaveEntries optionally allows NIL as its source
// color table parameter. If NIL is used, the current device's
// color table is used as the source."
//
// Stack (Pascal PROCEDURE, pop-12): SP+0=selection(4),
// SP+4=resultTable(4), SP+8=srcTable(4). No FUNCTION result
// slot.
//
// ReqListRec layout:
// +0 reqLSize: Integer (count - 1)
// +2 reqLData: ARRAY[0..reqLSize] of INTEGER
//
// For i in 0..=reqLSize: copy src[selection.reqLData[i]] into
// result[i]. If selection.reqLData[i] is out of range in src,
// set selection.reqLData[i] = colReqErr (-1) and leave
// result[i] undefined.
//
// The shared behaviour is the Pascal PROCEDURE pop-12 calling
// convention. Absolute Color Manager state mutation diverges
// between engines (BII walks gDevice CLUT per IM:V V-137..V-138,
// Systemless walks dispatcher-internal device_clut and supplied
// CTab bytes). Contract-test coverage in this file (mod tests):
// saveentries_restoreentries_pascal_procedure_preserves_stack_across_five_calls.
(true, 0x249) => {
let sp = cpu.read_reg(Register::A7);
let selection_ptr = bus.read_long(sp);
let result_handle = bus.read_long(sp + 4);
let src_handle = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if selection_ptr == 0 || result_handle == 0 {
return Some(Ok(()));
}
let result_ptr = bus.read_long(result_handle);
if result_ptr == 0 {
return Some(Ok(()));
}
let req_size = bus.read_word(selection_ptr) as i16;
if req_size < 0 {
return Some(Ok(()));
}
let count = (req_size as usize) + 1;
let result_size = 8 + (count as u32) * 8;
let result_ptr = self.resize_handle_allocation(bus, result_handle, result_size);
if result_ptr == 0 {
return Some(Ok(()));
}
// Source: NIL handle = current device CLUT, else read from
// the CTab pointed to by the handle. When possible, NIL
// source reads through the current GDevice CTab so the
// packed result carries real ColorSpec.value words instead
// of synthesized indices.
let current_ctab_handle = if src_handle == 0 {
self.current_gdevice_ctab_handle(bus)
} else {
0
};
let src_ptr = if src_handle != 0 {
bus.read_long(src_handle)
} else if current_ctab_handle != 0 {
bus.read_long(current_ctab_handle)
} else {
0
};
// src_size is the maximum valid index in the source
// (exclusive bound = src_size + 1 entries).
let src_size: usize = if src_ptr != 0 {
bus.read_word(src_ptr + 6) as usize
} else {
255 // device_clut always has 256 entries
};
// SaveEntries produces a packed ColorTable suitable for
// RestoreEntries. Callers may pass a freshly-created
// zero-length Handle; make the result structurally valid
// before writing entries.
let seed = if src_ptr != 0 {
bus.read_long(src_ptr)
} else {
self.next_color_table_seed()
};
bus.write_long(result_ptr, seed);
bus.write_word(result_ptr + 4, 0);
bus.write_word(result_ptr + 6, req_size as u16);
for i in 0..count {
let req_slot = selection_ptr + 2 + (i as u32) * 2;
let src_idx = bus.read_word(req_slot) as i16;
let result_entry = result_ptr + 8 + (i as u32) * 8;
if src_idx < 0 || (src_idx as usize) > src_size {
// Out of range — mark this slot of selection as
// colReqErr and leave result[i] alone (undefined).
bus.write_word(req_slot, 0xFFFFu16);
continue;
}
let (value, r, g, b) = if src_ptr != 0 {
let src_entry = src_ptr + 8 + (src_idx as u32) * 8;
(
bus.read_word(src_entry),
bus.read_word(src_entry + 2),
bus.read_word(src_entry + 4),
bus.read_word(src_entry + 6),
)
} else {
// From device_clut: synthesize value=index, RGB
// from the live CLUT slot.
let [r, g, b] = self.device_clut[src_idx as usize];
(src_idx as u16, r, g, b)
};
bus.write_word(result_entry, value);
bus.write_word(result_entry + 2, r);
bus.write_word(result_entry + 4, g);
bus.write_word(result_entry + 6, b);
}
Ok(())
}
// RestoreEntries ($AA4A)
// PROCEDURE RestoreEntries(srcTable: CTabHandle; dstTable: CTabHandle;
// VAR selection: ReqListRec);
// Inside Macintosh Volume V (1986), p. V-144
// (Color Manager — Color Manager Routines — RestoreEntries)
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) RestoreEntries(CTabHandle srcTable,
// CTabHandle dstTable, ReqListRec *selection)
// ONEWORDINLINE(0xAA4A);
//
// "RestoreEntries sets a selection of entries from srcTable into
// dstTable, but doesn't rebuild the inverse table. The dstTable
// entries to be set are enumerated in the selection parameter.
// ... If a request is beyond the end of the dstTable, that
// position of the requestList is set to colReqErr ... If
// dstTbl is NIL, or points to the device color table, the
// current device's color table is updated, and the hardware is
// updated to these new colors. The seed is not changed, so no
// invalidation occurs."
//
// Stack (Pascal PROCEDURE, pop-12): SP+0=selection(4),
// SP+4=dstTable(4), SP+8=srcTable(4). No FUNCTION result slot.
//
// For i in 0..=reqLSize: copy src[i] into dst[selection.reqLData[i]].
// Inverse of SaveEntries: SaveEntries packs scattered src into
// packed result; RestoreEntries unpacks packed src into
// scattered dst.
//
// The shared behaviour is the Pascal PROCEDURE pop-12 calling
// convention. Absolute Color Manager state mutation diverges
// between engines (BII walks gDevice CLUT per IM:V V-137..V-138
// and does NOT bump ctSeed; Systemless walks dispatcher-internal
// device_clut and supplied CTab bytes). Contract-test coverage
// in this file (mod tests):
// saveentries_restoreentries_pascal_procedure_preserves_stack_across_five_calls.
(true, 0x24A) => {
let sp = cpu.read_reg(Register::A7);
let selection_ptr = bus.read_long(sp);
let dst_handle = bus.read_long(sp + 4);
let src_handle = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if selection_ptr == 0 || src_handle == 0 {
return Some(Ok(()));
}
let src_ptr = bus.read_long(src_handle);
if src_ptr == 0 {
return Some(Ok(()));
}
let req_size = bus.read_word(selection_ptr) as i16;
if req_size < 0 {
return Some(Ok(()));
}
let count = (req_size as usize) + 1;
// Destination: NIL handle → write into device_clut directly.
let dst_ptr = if dst_handle != 0 {
bus.read_long(dst_handle)
} else {
0
};
let dst_size: usize = if dst_ptr != 0 {
bus.read_word(dst_ptr + 6) as usize
} else {
255
};
let src_size = bus.read_word(src_ptr + 6) as usize;
for i in 0..count {
if i > src_size {
// Source ran out of entries; nothing to copy.
// IM doesn't say to set colReqErr in this case.
break;
}
let req_slot = selection_ptr + 2 + (i as u32) * 2;
let dst_idx = bus.read_word(req_slot) as i16;
if dst_idx < 0 || (dst_idx as usize) > dst_size {
bus.write_word(req_slot, 0xFFFFu16); // colReqErr
continue;
}
let src_entry = src_ptr + 8 + (i as u32) * 8;
let value = bus.read_word(src_entry);
let r = bus.read_word(src_entry + 2);
let g = bus.read_word(src_entry + 4);
let b = bus.read_word(src_entry + 6);
if dst_ptr != 0 {
let dst_entry = dst_ptr + 8 + (dst_idx as u32) * 8;
bus.write_word(dst_entry, value);
bus.write_word(dst_entry + 2, r);
bus.write_word(dst_entry + 4, g);
bus.write_word(dst_entry + 6, b);
} else {
// NIL dstTable → write directly into device_clut.
// Per IM, no ctSeed bump (i.e. don't invalidate
// anything that depends on the inverse table).
self.device_clut.set_entry(dst_idx as usize, [r, g, b]);
}
}
Ok(())
}
// DelSearch ($AA4C)
// Removes a custom search procedure from the active gDevice's chain.
// PROCEDURE DelSearch (searchProc: ProcPtr);
// Inside Macintosh Volume V, V-147
// Stack: SP+0: searchProc(4). Pop 4.
// No-op stub: Systemless uses identity color matching and does not
// maintain a per-device search-procedure chain. Pops 4 bytes.
(true, 0x24C) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// DelComp ($AA4D)
// Removes a custom complement procedure from the active gDevice's chain.
// PROCEDURE DelComp (compProc: ProcPtr);
// Inside Macintosh Volume V, V-147
// Stack: SP+0: compProc(4). Pop 4.
// No-op stub: Systemless uses the default 1's-complement procedure
// and does not maintain a per-device complement-procedure chain.
// Pops 4 bytes.
(true, 0x24D) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Stubs — PixMap / PixPat ==========
// DisposPixMap ($AA04)
// Disposes of a PixMap record and its color table.
// PROCEDURE DisposPixMap (pm: PixMapHandle);
// Inside Macintosh Volume V, V-57
//
// "The DisposPixMap procedure releases all storage allocated
// by NewPixMap. It disposes of the pixMap's color table,
// and of the pixMap itself."
//
// PixMap layout: pmTable (CTabHandle) is at offset +42.
// CloseCPort calls DisposePixMap.
//
// Stack: SP+0: pm_handle(4). Pop 4.
//
// DisposPixMap ($AA04): Frees PixMap record and its color table (pmTable at +42); per IM:V V-57
(true, 0x204) => {
let sp = cpu.read_reg(Register::A7);
let pm_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
// Free the color table (pmTable at offset +42)
let ctab_handle = bus.read_long(pm_ptr + 42);
if ctab_handle != 0 {
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr != 0 {
bus.free(ctab_ptr);
}
bus.free(ctab_handle);
}
// Free the PixMap record itself
bus.free(pm_ptr);
}
// Clear the caller's master pointer so a second dispose
// attempt sees NIL instead of a stale freed handle cell.
bus.write_long(pm_handle, 0);
bus.free(pm_handle);
}
Ok(())
}
// CopyPixMap ($AA05)
// Copies the 50-byte PixMap record and color-table contents, leaving
// the destination with its own color table; baseAddr's image is not copied.
// PROCEDURE CopyPixMap (srcPM,dstPM: PixMapHandle);
// Imaging With QuickDraw 1994, p. 4-86; Inside Macintosh V, V-57
(true, 0x205) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if src_handle != 0 && dst_handle != 0 {
let dst_ptr = bus.read_long(dst_handle);
let src_ptr = bus.read_long(src_handle);
if src_ptr != 0 && dst_ptr != 0 && src_ptr != dst_ptr {
let src_ctab_handle = bus.read_long(src_ptr + 42);
let dst_ctab_handle = bus.read_long(dst_ptr + 42);
let src_ctab_ptr = bus.read_long(src_ctab_handle);
let copied_ctab_handle = if let Some(size) =
bus.get_alloc_size(src_ctab_ptr).filter(|size| *size >= 8)
{
let bytes = bus.read_bytes(src_ctab_ptr, size as usize);
let dst_ctab_ptr = bus.read_long(dst_ctab_handle);
if dst_ctab_handle != src_ctab_handle
&& bus.get_alloc_size(dst_ctab_handle) == Some(4)
&& dst_ctab_ptr != src_ctab_ptr
&& bus.get_alloc_size(dst_ctab_ptr).is_some()
{
let new_ptr =
self.resize_handle_allocation(bus, dst_ctab_handle, size);
if new_ptr != 0 {
bus.write_bytes(new_ptr, &bytes);
Some(dst_ctab_handle)
} else {
None
}
} else {
Self::clone_memory_handle(bus, src_ctab_handle)
}
} else {
None
};
for i in 0..50u32 {
bus.write_byte(dst_ptr + i, bus.read_byte(src_ptr + i));
}
if let Some(ctab_handle) = copied_ctab_handle {
bus.write_long(dst_ptr + 42, ctab_handle);
}
}
}
Ok(())
}
// NewPixPat ($AA07)
// Allocates a PixPat, its PixMap and embedded handles; seeds pat1Data to gray.
// FUNCTION NewPixPat: PixPatHandle;
// Imaging With QuickDraw (1994), pp. 4-88--4-89.
(true, 0x207) => {
let sp = cpu.read_reg(Register::A7);
let pat_map = self.allocate_new_pixmap(bus);
let pat_data = Self::allocate_empty_handle(bus);
let pat_xdata = Self::allocate_empty_handle(bus);
let pat_xmap = Self::allocate_empty_handle(bus);
let rec = bus.alloc(28);
let handle = bus.alloc(4);
if [pat_map, pat_data, pat_xdata, pat_xmap, rec, handle].contains(&0) {
Self::free_pixmap_handle(bus, pat_map);
for nested in [pat_data, pat_xdata, pat_xmap] {
Self::free_memory_handle(bus, nested);
}
if rec != 0 {
bus.free(rec);
}
if handle != 0 {
bus.free(handle);
}
bus.write_long(sp, 0);
return Some(Ok(()));
}
for offset in 0..28u32 {
bus.write_byte(rec + offset, 0);
}
bus.write_word(rec, 1);
bus.write_long(rec + 2, pat_map);
bus.write_long(rec + 6, pat_data);
bus.write_long(rec + 10, pat_xdata);
bus.write_long(rec + 16, pat_xmap);
bus.write_bytes(rec + 20, &[0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]);
bus.write_long(handle, rec);
bus.write_long(sp, handle);
Ok(())
}
// CopyPixPat ($AA09)
// Copies the contents of one PixPat record to another.
// PROCEDURE CopyPixPat(srcPP, dstPP: PixPatHandle);
// Inside Macintosh Volume V (1986), p. V-73
//
// "The CopyPixPat procedure copies the contents of the
// source pixPat to the destination pixPat. It entirely
// copies all fields in the source pixPat, including the
// contents of the data handle, expanded data handle,
// expanded map, pixMap handle, and color table."
//
// MPW Universal Headers Quickdraw.h:
// EXTERN_API(void) CopyPixPat(PixPatHandle srcPP,
// PixPatHandle dstPP)
// ONEWORDINLINE(0xAA09);
//
// Tool-bit Pascal PROCEDURE ABI:
// Stack on entry: [SP+0] = dstPP (4 bytes, second arg per
// Pascal calling convention);
// [SP+4] = srcPP (4 bytes, first arg).
// Stack on exit: trap pops 8 bytes; A7 net-balanced
// across the call; no FUNCTION result
// slot is written.
//
// Documented behaviour: copies the 28-byte PixPat record from
// *srcPP to *dstPP plus all nested owned handle contents.
// Both src/dst handle dereferences are guarded behind non-NIL
// checks.
//
// ## TRAP-WORD SWAP FIX (historical)
// This arm previously matched `(true, 0x208)` and was labeled
// "$AA08 CopyPixPat" — but per IM:V V-291 master trap dispatch
// table line 20693, $AA09 is CopyPixPat. See the swap-fix
// rationale block at the DisposPixPat ($AA08) arm above for
// the full details — both arms were swapped.
(true, 0x209) => {
let sp = cpu.read_reg(Register::A7);
let dst_handle = bus.read_long(sp);
let src_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if src_handle != dst_handle {
if let Some(rgb) = self.makergbpat_colors.get(&src_handle).copied() {
self.makergbpat_colors.insert(dst_handle, rgb);
} else {
self.makergbpat_colors.remove(&dst_handle);
}
}
if src_handle != dst_handle && src_handle != 0 && dst_handle != 0 {
let src_ptr = bus.read_long(src_handle);
let dst_ptr = bus.read_long(dst_handle);
if src_ptr != 0 && dst_ptr != 0 {
let src_pat_map = bus.read_long(src_ptr + 2);
let src_pat_data = bus.read_long(src_ptr + 6);
let src_pat_xdata = bus.read_long(src_ptr + 10);
let src_pat_xmap = bus.read_long(src_ptr + 16);
let cloned_pat_data = Self::clone_memory_handle(bus, src_pat_data);
let cloned_pat_data_ptr = cloned_pat_data
.map(|handle| bus.read_long(handle))
.unwrap_or(0);
let src_pat_data_ptr = cloned_pat_data
.map(|_| bus.read_long(src_pat_data))
.unwrap_or(0);
let cloned_pat_map = Self::clone_pixmap_handle(
bus,
src_pat_map,
src_pat_data_ptr,
cloned_pat_data_ptr,
);
let cloned_pat_xdata = Self::clone_memory_handle(bus, src_pat_xdata);
let cloned_pat_xmap = Self::clone_memory_handle(bus, src_pat_xmap);
let dst_pat_map = bus.read_long(dst_ptr + 2);
let dst_pat_data = bus.read_long(dst_ptr + 6);
let dst_pat_xdata = bus.read_long(dst_ptr + 10);
let dst_pat_xmap = bus.read_long(dst_ptr + 16);
if dst_pat_map != src_pat_map {
Self::free_pixmap_handle(bus, dst_pat_map);
}
if dst_pat_data != src_pat_data {
Self::free_memory_handle(bus, dst_pat_data);
}
if dst_pat_xdata != src_pat_xdata {
Self::free_memory_handle(bus, dst_pat_xdata);
}
if dst_pat_xmap != src_pat_xmap {
Self::free_memory_handle(bus, dst_pat_xmap);
}
for i in 0..28u32 {
bus.write_byte(dst_ptr + i, bus.read_byte(src_ptr + i));
}
if let Some(handle) = cloned_pat_map {
bus.write_long(dst_ptr + 2, handle);
}
if let Some(handle) = cloned_pat_data {
bus.write_long(dst_ptr + 6, handle);
}
if let Some(handle) = cloned_pat_xdata {
bus.write_long(dst_ptr + 10, handle);
}
if let Some(handle) = cloned_pat_xmap {
bus.write_long(dst_ptr + 16, handle);
}
}
}
Ok(())
}
// ========== Stubs — Picture ==========
// OpenCPicture ($AA20)
// Begins recording a new color picture. Stub returns NIL PicHandle.
// FUNCTION OpenCPicture(newHeader: OpenCPicParams): PicHandle;
// Inside Macintosh Volume V, V-89
// Stack: SP+0: header_ptr(4). Return PicHandle at SP+4. Pop to SP+4.
// OpenCPicture ($AA20): Returns NIL PicHandle (color-PICT recording not supported) per IM:V V-89
(true, 0x220) => {
let sp = cpu.read_reg(Register::A7);
bus.write_long(sp + 4, 0);
cpu.write_reg(Register::D0, 0);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Stubs — Mask / Fill ==========
// CalcCMask ($AA4F)
// Builds a mask bitmap from a seed fill in a color source. No-op stub.
// PROCEDURE CalcCMask(srcBits, dstBits: BitMap; srcRect, maskRect: Rect;
// seedRGB: RGBColor; matchProc: ProcPtr;
// matchData: LongInt);
// Imaging With QuickDraw, 3-100
// Stack: SP+0:matchData(4), SP+4:matchProc(4), SP+8:seedRGB(4),
// SP+12:maskRect(4), SP+16:srcRect(4), SP+20:dstBits(4),
// SP+24:srcBits(4). Pop 28.
// CalcCMask ($AA4F): Pops 28 bytes; color seed-fill mask not synthesized per Imaging With QuickDraw 3-100
(true, 0x24F) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 28);
Ok(())
}
// SeedCFill ($AA50)
// Performs a color-seeded flood fill into dstBits. No-op stub.
// PROCEDURE SeedCFill(srcBits, dstBits: BitMap; srcRect, dstRect: Rect;
// seedH, seedV: INTEGER; matchProc: ProcPtr;
// matchData: LongInt);
// Imaging With QuickDraw, 3-101
// Stack: SP+0:matchData(4), SP+4:matchProc(4), SP+8:seedV(2),
// SP+10:seedH(2), SP+12:dstRect(4), SP+16:srcRect(4),
// SP+20:dstBits(4), SP+24:srcBits(4). Pop 28.
// SeedCFill ($AA50): Pops 28 bytes; color flood-fill not implemented per Imaging With QuickDraw 3-101
(true, 0x250) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 28);
Ok(())
}
// ========== Stubs — GDevice ==========
// InitGDevice ($AA2E)
// Initializes a GDevice record to a given display mode.
// PROCEDURE InitGDevice(qdRefNum: INTEGER; mode: LongInt; gdh: GDHandle);
// Imaging With QuickDraw (1994), pp. 5-21 to 5-22.
// Stack: SP+0: gdh(4), SP+4: mode(4), SP+8: qdRefNum(2). Pop 10.
//
// Contract coverage:
// quickdraw::tests::initgdevice_consumes_gdrefnum_mode_and_gdhandle_arguments
// quickdraw::tests::initgdevice_writes_gdrefnum_and_mode_fields_into_target_record
//
// HLE compromise: without a real video driver, Systemless cannot fill
// out mode-specific ROM-backed device state. We therefore model the
// caller-observable subset BasiliskII exposes cleanly to apps that
// inspect the detached record after InitGDevice: gdRefNum, gdMode,
// and the gdDevType bit for black-and-white vs color mode.
// InitGDevice ($AA2E): Pops 10 bytes and writes gdRefNum/gdMode into the target GDevice; updates gdDevType bit 0 for mode 128 (B/W) vs non-128 color modes per Imaging With QuickDraw 1994, 5-21..5-22
(true, 0x22E) => {
let sp = cpu.read_reg(Register::A7);
let gdh = bus.read_long(sp);
let mode = bus.read_long(sp + 4);
let gd_ref_num = bus.read_word(sp + 8) as i16;
if mode != 0xFFFF_FFFF {
self.init_gdevice_minimal(bus, gdh, gd_ref_num, mode);
}
cpu.write_reg(Register::A7, sp + 10);
Ok(())
}
// DeviceLoop ($ABCA)
// PROCEDURE DeviceLoop(drawingRgn: RgnHandle;
// drawingProc: DeviceLoopDrawingUPP;
// userData: LongInt; flags: DeviceLoopFlags);
// Inside Macintosh: Imaging With QuickDraw 1994, pp. 5-29 to 5-30.
// DeviceLoopFlags includes allDevices; when that flag is set,
// DeviceLoop ignores drawingRgn and visits every device in the
// current graphics-device chain.
// MPW Universal Headers Quickdraw.h declares the drawing proc as:
// pascal void (*DeviceLoopDrawingProcPtr)
// (short depth, short deviceFlags, GDHandle targetDevice,
// long userData);
//
// Stack: SP+0 flags(4), SP+4 userData(4), SP+8 drawingProc(4),
// SP+12 drawingRgn(4). Pop 16.
//
// HLE compromise: Systemless honors the current GDevice, and
// when that device is the main screen it walks the linked
// gdNextGD chain to find the first device intersecting the
// drawing region. Offscreen current GWorlds still use the
// current device directly.
(true, 0x3CA) => {
let sp = cpu.read_reg(Register::A7);
let flags = bus.read_long(sp);
let user_data = bus.read_long(sp + 4);
let drawing_proc = bus.read_long(sp + 8);
let drawing_rgn = bus.read_long(sp + 12);
let main_gdevice = self.ensure_main_gdevice(bus);
let current_gdevice = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
main_gdevice
};
let all_devices = (flags & (1 << 2)) != 0;
let drawing_bbox = if all_devices {
None
} else {
Self::region_bbox(bus, drawing_rgn)
};
let intersects_rect = |rect: (i16, i16, i16, i16)| {
drawing_bbox.is_some_and(|(top, left, bottom, right)| {
top < rect.2 && left < rect.3 && bottom > rect.0 && right > rect.1
})
};
let target_devices = if all_devices {
let mut targets = Vec::new();
let mut scan_gdevice = current_gdevice;
while scan_gdevice != 0 {
let gd_ptr = bus.read_long(scan_gdevice);
if gd_ptr == 0 {
break;
}
targets.push((scan_gdevice, gd_ptr));
scan_gdevice = bus.read_long(gd_ptr + 30);
}
targets
} else if current_gdevice == main_gdevice {
let mut scan_gdevice = main_gdevice;
let mut targets = Vec::new();
while scan_gdevice != 0 {
let gd_ptr = bus.read_long(scan_gdevice);
if gd_ptr == 0 {
break;
}
let rect = (
bus.read_word(gd_ptr + 34) as i16,
bus.read_word(gd_ptr + 36) as i16,
bus.read_word(gd_ptr + 38) as i16,
bus.read_word(gd_ptr + 40) as i16,
);
if intersects_rect(rect) {
targets.push((scan_gdevice, gd_ptr));
break;
}
scan_gdevice = bus.read_long(gd_ptr + 30);
}
targets
} else {
let gd_ptr = bus.read_long(current_gdevice);
let rect = if gd_ptr != 0 {
(
bus.read_word(gd_ptr + 34) as i16,
bus.read_word(gd_ptr + 36) as i16,
bus.read_word(gd_ptr + 38) as i16,
bus.read_word(gd_ptr + 40) as i16,
)
} else {
(0, 0, 0, 0)
};
if gd_ptr != 0 && intersects_rect(rect) {
vec![(current_gdevice, gd_ptr)]
} else {
Vec::new()
}
};
if drawing_proc != 0 && !target_devices.is_empty() {
let entry = bus.read_word(drawing_proc);
if entry == 0x4E56 || entry == 0x48E7 || entry == 0x4EF9 || entry == 0x4EFA {
let return_slot = sp.wrapping_add(12);
let return_pc = cpu.read_reg(Register::PC);
if target_devices.len() == 1 {
let (target_gdevice, target_gd_ptr) = target_devices[0];
let depth = Self::gdevice_pixel_size(bus, target_gdevice).unwrap_or(8);
let device_flags = bus.read_word(target_gd_ptr + 20);
let tramp = self.get_or_create_device_loop_trampoline(bus);
bus.write_word(tramp + 6, depth as u16);
bus.write_word(tramp + 10, device_flags);
bus.write_long(tramp + 14, target_gdevice);
bus.write_long(tramp + 20, user_data);
bus.write_long(tramp + 26, drawing_proc);
bus.write_long(tramp + 32, return_slot.wrapping_sub(32));
bus.write_long(return_slot, return_pc);
cpu.write_reg(Register::A7, return_slot);
cpu.write_reg(Register::PC, tramp);
return Some(Ok(()));
}
let trampolines: Vec<u32> =
(0..target_devices.len()).map(|_| bus.alloc(46)).collect();
for (idx, ((target_gdevice, target_gd_ptr), tramp)) in
target_devices.iter().zip(trampolines.iter()).enumerate()
{
let depth = Self::gdevice_pixel_size(bus, *target_gdevice).unwrap_or(8);
let device_flags = bus.read_word(*target_gd_ptr + 20);
let next_trampoline = trampolines.get(idx + 1).copied();
Self::write_device_loop_trampoline(
bus,
*tramp,
depth as u16,
device_flags,
*target_gdevice,
user_data,
drawing_proc,
return_slot,
next_trampoline,
);
}
bus.write_long(return_slot, return_pc);
cpu.write_reg(Register::A7, return_slot);
cpu.write_reg(Register::PC, trampolines[0]);
return Some(Ok(()));
}
}
cpu.write_reg(Register::A7, sp + 16);
Ok(())
}
// ========== Palette / Control / Desktop ==========
// CopyPalette ($AAA1)
// Copies dstLength entries (RGB + usage + tolerance) from
// srcPalette[srcEntry] into dstPalette[dstEntry]. Per IM:VI
// 20-23, NIL handles make the call a no-op, and CopyPalette
// does NOT call ActivatePalette (callers are expected to
// batch palette edits and activate once).
//
// MPW Universal Headers `Palettes.h` declaration:
// EXTERN_API(void) CopyPalette(PaletteHandle srcPalette,
// PaletteHandle dstPalette, short srcEntry,
// short dstEntry, short dstLength) ONEWORDINLINE(0xAAA1);
// PROCEDURE CopyPalette(srcPalette, dstPalette: PaletteHandle;
// srcEntry, dstEntry, dstLength: INTEGER);
// Inside Macintosh Volume VI, 20-23
// Stack: SP+0: dstLength(2), SP+2: dstEntry(2), SP+4: srcEntry(2),
// SP+6: dstPalette(4), SP+10: srcPalette(4). Pop 14.
//
// Regression coverage:
// src/trap/quickdraw.rs::tests::copypalette_pops_fourteen_bytes
// src/trap/quickdraw.rs::tests::copypalette_resizes_destination_when_copy_extends_past_tail
// src/trap/quickdraw.rs::tests::copypalette_copies_requested_range_into_resized_tail
// src/trap/quickdraw.rs::tests::copypalette_nil_source_does_not_mutate_destination
// CopyPalette ($AAA1): Copies dstLength ColorInfo records (RGB + usage + tolerance) from src[srcEntry] to dst[dstEntry]; NIL handles no-op; destination palette grows when dstEntry + dstLength exceeds its prior size, IM:VI 20-23
(true, 0x2A1) => {
let sp = cpu.read_reg(Register::A7);
let dst_length = bus.read_word(sp) as i16;
let dst_entry = bus.read_word(sp + 2) as i16;
let src_entry = bus.read_word(sp + 4) as i16;
let dst_palette = bus.read_long(sp + 6);
let src_palette = bus.read_long(sp + 10);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] CopyPalette srcPalette=${:08X} dstPalette=${:08X} srcEntry={} dstEntry={} dstLength={}",
src_palette, dst_palette, src_entry, dst_entry, dst_length
);
}
cpu.write_reg(Register::A7, sp + 14);
if src_palette == 0
|| dst_palette == 0
|| dst_length <= 0
|| src_entry < 0
|| dst_entry < 0
{
return Some(Ok(()));
}
let required_entries = u32::from(dst_entry as u16) + u32::from(dst_length as u16);
if required_entries > u32::from(Self::palette_entry_count(bus, dst_palette))
&& required_entries <= i16::MAX as u32
{
self.resize_palette(bus, dst_palette, required_entries as i16);
}
let dst_palette_ptr = Self::palette_ptr(bus, dst_palette);
if dst_palette_ptr == 0 {
return Some(Ok(()));
}
let src_count = i32::from(Self::palette_entry_count(bus, src_palette));
let dst_count = i32::from(Self::palette_entry_count(bus, dst_palette));
let length = i32::from(dst_length);
for offset in 0..length {
let s = i32::from(src_entry) + offset;
let d = i32::from(dst_entry) + offset;
if s >= src_count || d >= dst_count {
break;
}
if let Some((rgb, usage, tolerance)) =
Self::read_palette_color_info(bus, src_palette, s as u16)
{
Self::write_palette_color_info(
bus,
dst_palette_ptr,
d as u32,
rgb,
usage,
tolerance,
);
}
}
Ok(())
}
// GetAuxCtl ($AA44)
// FUNCTION GetAuxCtl(theControl: ControlHandle;
// VAR acHndl: AuxCtlHandle): BOOLEAN;
// Macintosh Toolbox Essentials (1992), p. 5-107.
// Stack: SP+0: acHndl_ptr(4), SP+4: theControl(4). Return BOOL at SP+8.
// GetAuxCtl ($AA44): BasiliskII/System 7.5.3 reports TRUE with a
// non-NIL AuxCtlHandle for freshly created controls. Systemless
// mirrors that caller-observable contract for HLE-created
// controls, while still returning NIL/FALSE for untracked or
// already-disposed handles.
(true, 0x244) => {
let sp = cpu.read_reg(Register::A7);
let ctrl_handle = bus.read_long(sp + 4);
let aux_ptr = bus.read_long(sp);
let aux_handle = self
.control_aux_state(ctrl_handle)
.map(|state| state.handle)
.unwrap_or(0);
if aux_ptr != 0 {
bus.write_long(aux_ptr, aux_handle);
}
bus.write_word(sp + 8, if aux_handle != 0 { 0x0100 } else { 0 });
cpu.write_reg(Register::A7, sp + 8);
Ok(())
}
// SetDeskCPat ($AA47)
// Sets the desktop pixel pattern and redraws the desktop in the
// colour Window Manager port (WMgrCPort). If deskPixPat is NIL,
// the standard binary deskPat ('ppat' resource = 16) is used.
// PROCEDURE SetDeskCPat(deskPixPat: PixPatHandle); [Macintosh II]
// Inside Macintosh Volume V (1986), p. V-210
//
// MPW Universal Headers MacWindows.h:
// EXTERN_API(void) SetDeskCPat(PixPatHandle deskPixPat)
// ONEWORDINLINE(0xAA47);
//
// Tool-bit Pascal PROCEDURE ABI: caller pushes the 4-byte
// PixPatHandle argument, trap pops it, no FUNCTION result slot.
// Stack: SP+0: deskPixPat(4). Pop 4.
//
// The absolute side effect differs from BII: BII System 7.5.3
// ROM honours the documented contract and redraws the desktop
// pixel pattern in the WMgrCPort. Systemless runs as a kiosk and
// never renders desktop chrome, so this arm is a true no-op
// (pops 4 bytes and returns). IM:V V-210 itself notes "This
// routine is not for use by applications, and its description is
// only included for informational purposes" — applications are
// not expected to depend on the visible desktop redraw.
//
// The shared behaviour is the Pascal PROCEDURE pop-4 calling
// convention: A7 is unchanged across single and 5-call
// SetDeskCPat(NIL) sequences.
(true, 0x247) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Math / Trig ==========
// PtToAngle ($A8C3)
// PROCEDURE PtToAngle(r: Rect; pt: Point; VAR angle: INTEGER);
// Inside Macintosh Volume I, I-194
//
// "PtToAngle calculates an integer angle between a line from
// the center of the rectangle to the given point and a line
// from the center of the rectangle pointing straight up.
// The angle is in degrees from 0 to 359, measured clockwise
// from 12 o'clock ... If the line to the given point goes
// through the top right corner of the rectangle, the angle
// returned is 45 degrees, even if the rectangle isn't square."
//
// The angle is normalized by the rectangle's aspect ratio so
// corners always land at 45/135/225/315°. Implementation:
// translate the point relative to the rect's center, scale
// dx by the half-width and dy by the half-height to map the
// rect onto a unit square, then atan2 to get the angle from
// up (clockwise).
//
// Stack (Pascal): SP+0=angle_ptr(4), SP+4=pt(4 by value),
// SP+8=r_ptr(4). Pops 12. The 8-byte Rect exceeds MPW
// pascal direct-push threshold and is passed by const-
// pointer; the 4-byte Point fits and is passed by value.
//
// PtToAngle ($A8C3): Returns clockwise-from-up degrees (0-359) of the point relative to rect's center; aspect normalized so rect corners are 45/135/225/315° per IM:I I-194
(true, 0x0C3) => {
let sp = cpu.read_reg(Register::A7);
let angle_ptr = bus.read_long(sp);
let pt_v = bus.read_word(sp + 4) as i16 as f64;
let pt_h = bus.read_word(sp + 6) as i16 as f64;
let r_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if r_ptr != 0 && angle_ptr != 0 {
let top = bus.read_word(r_ptr) as i16 as f64;
let left = bus.read_word(r_ptr + 2) as i16 as f64;
let bottom = bus.read_word(r_ptr + 4) as i16 as f64;
let right = bus.read_word(r_ptr + 6) as i16 as f64;
let cx = (left + right) / 2.0;
let cy = (top + bottom) / 2.0;
let half_w = (right - left) / 2.0;
let half_h = (bottom - top) / 2.0;
// Map the point into a unit square so corners land
// at (±1, ±1) regardless of aspect ratio.
let dx_norm = if half_w > 0.0 {
(pt_h - cx) / half_w
} else {
0.0
};
let dy_norm = if half_h > 0.0 {
(pt_v - cy) / half_h
} else {
0.0
};
// atan2 measured clockwise from up (the +y axis is
// down on the Mac, so use -dy as the "up" component).
let angle_rad = dx_norm.atan2(-dy_norm);
let mut angle_deg = angle_rad.to_degrees().round() as i32;
angle_deg = angle_deg.rem_euclid(360);
bus.write_word(angle_ptr, angle_deg as u16);
}
Ok(())
}
// SlopeFromAngle ($A8BC)
// FUNCTION SlopeFromAngle(angle: INTEGER): Fixed;
// Inside Macintosh Volume I, I-192
//
// "Returns the slope dh/dv of a line forming the given angle
// with the y-axis. Angles are in degrees clockwise from
// 12 o'clock; positive y is down, positive x is right. The
// angle is treated MOD 180. SlopeFromAngle(0) is 0; per IM
// Figure 5, SlopeFromAngle(45) = $FFFF0000 (= -1.0)."
//
// Mathematically: slope = -tan(angle in radians).
//
// Stack: SP+0=angle(2). Returns Fixed(4) at SP+2. Pops to SP+2.
//
// Regression coverage:
// slopefromangle_zero_is_zero
// slopefromangle_45_is_negative_one_fixed
// slopefromangle_135_is_positive_one_fixed
// slopefromangle_treats_angle_mod_180
// SlopeFromAngle ($A8BC): Returns Fixed slope = -tan(angle MOD 180); 0°→0, 45°→-1.0 ($FFFF0000), 90°→saturates to $7FFFFFFF per IM:I I-192
(true, 0x0BC) => {
let sp = cpu.read_reg(Register::A7);
let angle_in = bus.read_word(sp) as i16 as i32;
// Reduce to 0..180.
let mut angle = angle_in % 180;
if angle < 0 {
angle += 180;
}
let slope_fixed: i32 = if angle == 0 {
0
} else if angle == 90 {
0x7FFF_FFFF // saturate to max positive Fixed
} else {
let radians = (angle as f64) * std::f64::consts::PI / 180.0;
let slope = -radians.tan();
let scaled = (slope * 65536.0).round();
if scaled >= i32::MAX as f64 {
i32::MAX
} else if scaled <= i32::MIN as f64 {
i32::MIN
} else {
scaled as i32
}
};
bus.write_long(sp + 2, slope_fixed as u32);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// AngleFromSlope ($A8C4)
// FUNCTION AngleFromSlope(slope: Fixed): INTEGER;
// Inside Macintosh Volume I, I-192
//
// "Inverse of SlopeFromAngle. Returns an angle in 1..180
// (inclusive) that produces the given slope. Per IM:I I-192,
// AngleFromSlope(0) = 180, and the round trip
// AngleFromSlope(SlopeFromAngle(x)) = x is guaranteed
// within one degree."
//
// angle = (180 - atan(slope) * 180/π) MOD 180, then map 0 → 180
//
// Stack: SP+0=slope(4). Returns INTEGER(2) at SP+4. Pops to SP+4.
//
// Regression coverage:
// anglefromslope_zero_returns_180
// anglefromslope_negative_one_returns_45
// anglefromslope_positive_one_returns_135
// slopefromangle_anglefromslope_round_trip
// AngleFromSlope ($A8C4): Inverse of SlopeFromAngle; returns angle in 1..180 (0 maps to 180); round-trip stable within 1° per IM:I I-192
(true, 0x0C4) => {
let sp = cpu.read_reg(Register::A7);
let slope_fixed = bus.read_long(sp) as i32;
let slope = (slope_fixed as f64) / 65536.0;
let angle_deg = 180.0 - slope.atan().to_degrees();
let mut angle = angle_deg.round() as i32 % 180;
if angle <= 0 {
angle += 180;
}
bus.write_word(sp + 4, angle as u16);
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// ========== Color Fill ==========
//
// Systemless does not implement true pixel-pattern tiling yet, so
// the FillC* routines draw the monochrome fallback pattern
// stored in the PixPat's pat1Data field (+20). This matches
// the behavior documented in Imaging With QuickDraw p. 4-81:
// "If the bit depth of the destination is one, or if the
// PixPat's pixMap field is NIL, QuickDraw uses pat1Data as a
// 1-bit fallback pattern." The monochrome path shares the
// existing draw_rect / draw_oval / draw_round_rect /
// draw_arc / draw_rgn / draw_poly + ShapeOp::Fill helpers
// used by the B&W Fill* variants.
// FillCRect ($AA0E)
//
// PROCEDURE FillCRect(r: Rect; pp: PixPatHandle);
//
// Inside Macintosh Volume V (1986), p. V-73 (Color QuickDraw —
// Color Drawing Routines — FillCRect). Per IM:V V-73 verbatim
// contract: fills the interior of the rectangle r with the
// pixel pattern referenced by pp. Imaging With QuickDraw (1994)
// p. 4-81 documents the same Color QuickDraw expansion path.
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(void) FillCRect(const Rect *r, PixPatHandle pp)
// ONEWORDINLINE(0xAA0E);
//
// Tool-bit Pascal PROCEDURE ABI:
// Caller pushes 8 bytes (4-byte Rect pointer at SP+0 +
// 4-byte PixPatHandle at SP+4), trap pops 8 bytes, no
// FUNCTION result slot. A7 net-balanced across the call.
//
// The shared behaviour is the documented Tool-bit Pascal
// PROCEDURE pop-8 calling convention. The absolute pixel-fill
// side effects differ from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw expands the full PixPat record
// per IM:V V-46 (patType / patMap / patData / patXData /
// patXMap deep handle chain) and tiles the rectangle with
// the expanded color pattern. Systemless HLE reads the
// pat1Data field at offset +20 from the PixPat record and
// uses that 8-byte monochrome fallback pattern to fill via
// draw_rect(ShapeOp::Fill(pat)) — the host runtime renders
// only to 1bpp canvases and has no Color QuickDraw
// expansion pipeline.
//
// Contract-test coverage in this file (mod tests):
// fillcrect_pascal_procedure_preserves_stack_across_five_calls
(true, 0x20E) => {
let sp = cpu.read_reg(Register::A7);
let pp_handle = bus.read_long(sp);
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
let r = read_rect(bus, rect_ptr);
let generated_rgb = self.makergbpat_colors.get(&pp_handle).copied();
let raw_filled = if let Some(rgb) = generated_rgb {
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
self.fg_color = rgb;
self.bg_color = rgb;
self.draw_rect(cpu, bus, &r, ShapeOp::Fill([0xFF; 8]));
self.fg_color = saved_fg;
self.bg_color = saved_bg;
true
} else {
self.fill_rect_with_raw_pixpat(bus, &r, pp_handle)
};
if trace_qd_colors_enabled() {
let pp_ptr = if pp_handle != 0 {
bus.read_long(pp_handle)
} else {
0
};
let pat_type = if pp_ptr != 0 {
bus.read_word(pp_ptr)
} else {
0
};
let pat_map = if pp_ptr != 0 {
bus.read_long(pp_ptr + 2)
} else {
0
};
let pat_data = if pp_ptr != 0 {
bus.read_long(pp_ptr + 6)
} else {
0
};
let mut pat1 = [0u8; 8];
if pp_ptr != 0 {
for (i, byte) in pat1.iter_mut().enumerate() {
*byte = bus.read_byte(pp_ptr + 20 + i as u32);
}
}
eprintln!(
"[QD-COLOR] FillCRect port=${:08X} rect=({},{},{},{}) pp=${:08X}->${:08X} patType={} patMap=${:08X} patData=${:08X} pat1={:02X?} raw={}",
*self.current_port,
r.top,
r.left,
r.bottom,
r.right,
pp_handle,
pp_ptr,
pat_type,
pat_map,
pat_data,
pat1,
raw_filled,
);
}
if !raw_filled {
if let Some(pat) = Self::read_pixpat_pat1data(bus, pp_handle) {
self.draw_rect(cpu, bus, &r, ShapeOp::Fill(pat));
}
}
Ok(())
}
// FillCOval ($AA0F)
//
// PROCEDURE FillCOval(r: Rect; pp: PixPatHandle);
//
// Inside Macintosh Volume V (1986), pp. V-67..V-69 (Color
// QuickDraw — Color Drawing Operations — FillCOval). See
// also Imaging With QuickDraw (1994) p. 4-75.
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(void) FillCOval(const Rect *r, PixPatHandle pp)
// ONEWORDINLINE(0xAA0F);
//
// Tool-bit Pascal PROCEDURE ABI:
// Caller pushes 8 bytes (4-byte Rect pointer at SP+0 +
// 4-byte PixPatHandle at SP+4), trap pops 8 bytes, no
// FUNCTION result slot. A7 net-balanced across the call.
//
// The shared behaviour is the documented Tool-bit Pascal
// PROCEDURE pop-8 calling convention. The absolute pixel-fill
// side effects differ from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw expands the full PixPat record
// per IM:V V-46 and tiles the oval with the expanded color
// pattern. Systemless HLE reads pat1Data at offset +20 and
// uses that 8-byte monochrome fallback to fill via
// draw_oval(ShapeOp::Fill(pat)).
//
// Contract-test coverage in this file (mod tests):
// fillcoval_fillcrgn_pascal_procedure_preserves_stack_across_five_calls
(true, 0x20F) => {
let sp = cpu.read_reg(Register::A7);
let pp_handle = bus.read_long(sp);
let rect_ptr = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if let Some((pat, generated_rgb)) = self.pixpat_fill_pattern(bus, pp_handle) {
let r = read_rect(bus, rect_ptr);
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
if let Some(rgb) = generated_rgb {
self.fg_color = rgb;
self.bg_color = rgb;
}
self.draw_oval(cpu, bus, &r, ShapeOp::Fill(pat));
self.fg_color = saved_fg;
self.bg_color = saved_bg;
}
Ok(())
}
// FillCRoundRect ($AA10)
//
// PROCEDURE FillCRoundRect(r: Rect; ovWid, ovHt: INTEGER;
// pp: PixPatHandle);
//
// Inside Macintosh Volume V (1986), pp. V-67..V-69 (Color
// QuickDraw — Color Drawing Operations — FillCRoundRect).
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(void) FillCRoundRect(const Rect *r,
// short ovalWidth, short ovalHeight, PixPatHandle pp)
// ONEWORDINLINE(0xAA10);
//
// Tool-bit Pascal PROCEDURE ABI:
// Caller pushes 12 bytes (4-byte PixPatHandle at SP+0,
// 2-byte ovHt at SP+4, 2-byte ovWid at SP+6, 4-byte Rect
// pointer at SP+8 — Pascal pushes args left-to-right so
// the Rect pointer is pushed first), trap pops 12 bytes,
// no FUNCTION result slot. A7 net-balanced across the call.
//
// The shared behaviour is the documented Tool-bit Pascal
// PROCEDURE pop-12 calling convention. The absolute pixel-fill
// side effects differ from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw expands the full PixPat record
// per IM:V V-46 and tiles the rounded rectangle interior
// with the expanded color pattern. Systemless HLE reads
// pat1Data at offset +20 and uses that 8-byte monochrome
// fallback to fill via draw_round_rect(ShapeOp::Fill(pat)).
//
// Contract-test coverage in this file (mod tests):
// fillcroundrect_fillcarc_pascal_procedure_preserves_stack_across_five_calls
(true, 0x210) => {
let sp = cpu.read_reg(Register::A7);
let pp_handle = bus.read_long(sp);
let oval_height = bus.read_word(sp + 4) as i16;
let oval_width = bus.read_word(sp + 6) as i16;
let rect_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if let Some((pat, generated_rgb)) = self.pixpat_fill_pattern(bus, pp_handle) {
let r = read_rect(bus, rect_ptr);
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
if let Some(rgb) = generated_rgb {
self.fg_color = rgb;
self.bg_color = rgb;
}
self.draw_round_rect(cpu, bus, &r, oval_width, oval_height, ShapeOp::Fill(pat));
self.fg_color = saved_fg;
self.bg_color = saved_bg;
}
Ok(())
}
// FillCArc ($AA11)
//
// PROCEDURE FillCArc(r: Rect; startAngle, arcAngle: INTEGER;
// pp: PixPatHandle);
//
// Inside Macintosh Volume V (1986), pp. V-67..V-69 (Color
// QuickDraw — Color Drawing Operations — FillCArc). See
// also Imaging With QuickDraw (1994) p. 4-76.
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(void) FillCArc(const Rect *r,
// short startAngle, short arcAngle, PixPatHandle pp)
// ONEWORDINLINE(0xAA11);
//
// Tool-bit Pascal PROCEDURE ABI:
// Caller pushes 12 bytes (4-byte PixPatHandle at SP+0,
// 2-byte arcAngle at SP+4, 2-byte startAngle at SP+6,
// 4-byte Rect pointer at SP+8 — Pascal pushes args
// left-to-right so the Rect pointer is pushed first),
// trap pops 12 bytes, no FUNCTION result slot. A7
// net-balanced across the call.
//
// The shared behaviour is the documented Tool-bit Pascal
// PROCEDURE pop-12 calling convention. The absolute pixel-fill
// side effects differ from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw expands the full PixPat record
// per IM:V V-46 and tiles the arc wedge with the expanded
// color pattern. Systemless HLE reads pat1Data at offset +20
// and uses that 8-byte monochrome fallback to fill via
// draw_arc(ShapeOp::Fill(pat)).
//
// Contract-test coverage in this file (mod tests):
// fillcroundrect_fillcarc_pascal_procedure_preserves_stack_across_five_calls
(true, 0x211) => {
let sp = cpu.read_reg(Register::A7);
let pp_handle = bus.read_long(sp);
let arc_angle = bus.read_word(sp + 4) as i16;
let start_angle = bus.read_word(sp + 6) as i16;
let rect_ptr = bus.read_long(sp + 8);
cpu.write_reg(Register::A7, sp + 12);
if let Some((pat, generated_rgb)) = self.pixpat_fill_pattern(bus, pp_handle) {
let r = read_rect(bus, rect_ptr);
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
if let Some(rgb) = generated_rgb {
self.fg_color = rgb;
self.bg_color = rgb;
}
self.draw_arc(cpu, bus, &r, start_angle, arc_angle, ShapeOp::Fill(pat));
self.fg_color = saved_fg;
self.bg_color = saved_bg;
}
Ok(())
}
// FillCRgn ($AA12)
//
// PROCEDURE FillCRgn(rgn: RgnHandle; pp: PixPatHandle);
//
// Inside Macintosh Volume V (1986), pp. V-67..V-69 (Color
// QuickDraw — Color Drawing Operations — FillCRgn). See
// also Imaging With QuickDraw (1994) p. 4-77.
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(void) FillCRgn(RgnHandle rgn, PixPatHandle pp)
// ONEWORDINLINE(0xAA12);
//
// Tool-bit Pascal PROCEDURE ABI:
// Caller pushes 8 bytes (4-byte RgnHandle at SP+0 +
// 4-byte PixPatHandle at SP+4), trap pops 8 bytes, no
// FUNCTION result slot. A7 net-balanced across the call.
//
// The shared behaviour is the documented Tool-bit Pascal
// PROCEDURE pop-8 calling convention. The absolute pixel-fill
// side effects differ from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw expands the full PixPat record
// per IM:V V-46 and tiles the region with the expanded
// color pattern. Systemless HLE reads pat1Data at offset +20
// and uses that 8-byte monochrome fallback to fill via
// draw_rgn(ShapeOp::Fill(pat)).
//
// Contract-test coverage in this file (mod tests):
// fillcoval_fillcrgn_pascal_procedure_preserves_stack_across_five_calls
(true, 0x212) => {
let sp = cpu.read_reg(Register::A7);
let pp_handle = bus.read_long(sp);
let rgn_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if self.extend_recording_region_from_rgn(bus, rgn_handle) && self.pn_vis < 0 {
return Some(Ok(()));
}
let raw_filled = self.fill_rgn_with_raw_pixpat(bus, rgn_handle, pp_handle);
if !raw_filled {
if let Some((pat, generated_rgb)) = self.pixpat_fill_pattern(bus, pp_handle) {
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
if let Some(rgb) = generated_rgb {
self.fg_color = rgb;
self.bg_color = rgb;
}
self.draw_rgn(cpu, bus, rgn_handle, ShapeOp::Fill(pat));
self.fg_color = saved_fg;
self.bg_color = saved_bg;
}
}
Ok(())
}
// FillCPoly ($AA13)
//
// Per IM:V 1986 p. V-69 (Color QuickDraw — Color Drawing
// Operations — FillCPoly): "FillCPoly fills the polygon
// with the pixel pattern referenced by ppat."
//
// PROCEDURE FillCPoly(poly: PolyHandle; pp: PixPatHandle);
//
// Inside Macintosh Volume V (1986), p. V-69 (Color
// QuickDraw — Color Drawing Operations — FillCPoly). See
// also Imaging With QuickDraw (1994) p. 4-76.
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(void) FillCPoly(PolyHandle poly, PixPatHandle pp)
// ONEWORDINLINE(0xAA13);
//
// Tool-bit Pascal PROCEDURE ABI:
// Caller pushes 8 bytes (4-byte PolyHandle at SP+0 +
// 4-byte PixPatHandle at SP+4), trap pops 8 bytes, no
// FUNCTION result slot. A7 net-balanced across the call.
//
// The shared behaviour is the documented Tool-bit Pascal
// PROCEDURE pop-8 calling convention. The absolute pixel-fill
// side effects differ from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw expands the full PixPat record
// per IM:V V-46 and rasterises the polygon interior tiled
// with the expanded color pattern. Systemless HLE reads
// pat1Data at offset +20 and uses that 8-byte monochrome
// fallback to fill via draw_poly(ShapeOp::Fill(pat)).
//
// Contract-test coverage in this file (mod tests):
// fillcpoly_pascal_procedure_preserves_stack_across_five_calls
(true, 0x213) => {
let sp = cpu.read_reg(Register::A7);
let pp_handle = bus.read_long(sp);
let poly_handle = bus.read_long(sp + 4);
cpu.write_reg(Register::A7, sp + 8);
if let Some((pat, generated_rgb)) = self.pixpat_fill_pattern(bus, pp_handle) {
let saved_fg = self.fg_color;
let saved_bg = self.bg_color;
if let Some(rgb) = generated_rgb {
self.fg_color = rgb;
self.bg_color = rgb;
}
self.draw_poly(cpu, bus, poly_handle, ShapeOp::Fill(pat));
self.fg_color = saved_fg;
self.bg_color = saved_bg;
}
Ok(())
}
// ========== Color Pixel ==========
// SetCPixel ($AA16)
//
// Per IM:V 1986 p. V-70 (Color QuickDraw Routines —
// SetCPixel): "The SetCPixel function sets the pixel at
// the specified position to the pixel value that most
// closely matches the specified RGB."
//
// PROCEDURE SetCPixel (h,v: INTEGER; cPix: RGBColor);
//
// MPW Universal Headers Quickdraw.h declares the C-level
// glue (Pascal records larger than 4 bytes are passed by
// pointer to the trap; the Pascal by-value semantics are
// honoured by the compiler-emitted temporary copy):
// EXTERN_API(void) SetCPixel(short h, short v, const RGBColor *cPix) ONEWORDINLINE(0xAA16);
//
// Tool-bit Pascal PROCEDURE ABI: caller pushes an 8-byte
// arg frame consisting of 4-byte cPix pointer at SP+0,
// 2-byte v INTEGER at SP+4, 2-byte h INTEGER at SP+6;
// trap pops 8 bytes, no FUNCTION result slot. The shared
// behaviour is the pop-8 calling convention itself: A7
// unchanged across the call. The absolute pixel-set side
// effect differs from BII — BII writes the best-match
// CLUT index into the screen pixMap byte via the device
// CLUT, while Systemless HLE walks its own port pixMap +
// device_clut (different default CLUT initialisation).
// NIL cPix pointer exits early after the 8-byte pop;
// out-of-bounds (h, v) coords clip silently.
//
// Contract-test coverage in this file (mod tests):
// setcpixel_getcpixel_pascal_procedure_preserves_stack_across_five_calls
(true, 0x216) => {
let sp = cpu.read_reg(Register::A7);
let cpix_ptr = bus.read_long(sp);
let v = bus.read_word(sp + 4) as i16;
let h = bus.read_word(sp + 6) as i16;
cpu.write_reg(Register::A7, sp + 8);
if cpix_ptr == 0 {
return Some(Ok(()));
}
let rgb = [
bus.read_word(cpix_ptr),
bus.read_word(cpix_ptr + 2),
bus.read_word(cpix_ptr + 4),
];
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
if port == 0 {
return Some(Ok(()));
}
if let Some(info) = self.resolve_pixel_target(bus, port, h, v) {
if info.base == self.screen_mode.0 {
self.ensure_dialog_background_saved_for_screen_port(bus, port);
}
self.write_cpixel(bus, &info, rgb);
if info.base == self.screen_mode.0 {
let screen_v = info.dy.min(i16::MAX as u32) as i16;
let screen_h = info.dx.min(i16::MAX as u32) as i16;
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
port,
(screen_v, screen_h, screen_v + 1, screen_h + 1),
);
}
}
Ok(())
}
// GetCPixel ($AA17)
//
// Per IM:V 1986 p. V-69 (Color QuickDraw Routines —
// GetCPixel): "The GetCPixel function returns the RGB of
// the pixel at the specified position in the current
// port."
//
// PROCEDURE GetCPixel (h,v: INTEGER; VAR cPix: RGBColor);
//
// MPW Universal Headers Quickdraw.h declares the C-level
// glue:
// EXTERN_API(void) GetCPixel(short h, short v, RGBColor *cPix) ONEWORDINLINE(0xAA17);
//
// Tool-bit Pascal PROCEDURE ABI: caller pushes an 8-byte
// arg frame consisting of 4-byte VAR cPix pointer at
// SP+0, 2-byte v INTEGER at SP+4, 2-byte h INTEGER at
// SP+6; trap pops 8 bytes, no FUNCTION result slot. The
// result RGBColor is written via the VAR pointer
// parameter. The shared behaviour is the pop-8 calling
// convention itself: A7 unchanged across the call. The
// absolute RGB-read return value differs from BII — BII
// reads the screen pixMap byte through the device CLUT,
// while Systemless HLE reads its own port pixMap byte
// through device_clut (different default CLUT
// initialisation). NIL VAR pointer exits early after the
// 8-byte pop; out-of-bounds (h, v) returns black ([0, 0, 0]).
//
// Contract-test coverage in this file (mod tests):
// setcpixel_getcpixel_pascal_procedure_preserves_stack_across_five_calls
(true, 0x217) => {
let sp = cpu.read_reg(Register::A7);
let cpix_ptr = bus.read_long(sp);
let v = bus.read_word(sp + 4) as i16;
let h = bus.read_word(sp + 6) as i16;
cpu.write_reg(Register::A7, sp + 8);
if cpix_ptr == 0 {
return Some(Ok(()));
}
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let rgb = if port != 0 {
self.resolve_pixel_target(bus, port, h, v)
.map(|info| self.read_cpixel(bus, &info))
.unwrap_or([0, 0, 0])
} else {
[0, 0, 0]
};
bus.write_word(cpix_ptr, rgb[0]);
bus.write_word(cpix_ptr + 2, rgb[1]);
bus.write_word(cpix_ptr + 4, rgb[2]);
Ok(())
}
// ========== Stubs — Color Cursors ==========
// GetCCursor ($AA1B)
//
// FUNCTION GetCCursor(crsrID: INTEGER): CCrsrHandle;
//
// Inside Macintosh Volume V (1986), p. V-74 (Color
// QuickDraw — Operations on Color Cursors — GetCCursor).
// Cross-referenced as Inside Macintosh: Imaging With
// QuickDraw (1994), p. 8-26.
//
// Per IM:V V-74 verbatim: "The GetCCursor call creates a
// new CCrsr data structure, then initializes it using the
// information in the resource of type 'crsr' with the
// specified ID. ... If the resource with the specified ID
// isn't found, then this routine returns a NIL handle."
//
// MPW Universal Headers Quickdraw.h declares:
// EXTERN_API(CCrsrHandle) GetCCursor(short crsrID)
// ONEWORDINLINE(0xAA1B);
//
// ABI (Tool-bit Pascal FUNCTION): caller pre-pushes a
// 4-byte CCrsrHandle result slot, then pushes a 2-byte
// crsrID INTEGER. Trap pops the 2-byte argument and
// writes the handle to the 4-byte result slot at the
// post-pop SP (= caller's pre-call SP+2). Caller pops the
// 4-byte slot after the trap returns. Net A7 effect
// across the C-level call is zero.
//
// Status: Partial. Valid compiled 'crsr' resources are
// promoted to live CCrsr records with PixMapHandle,
// pixel-data Handle, and ColorTable Handle fields. Malformed
// synthetic resources fall back to a Resource Manager handle so
// legacy tests and non-rendering callers still receive a non-NIL
// present-resource result.
//
// Behaviour shared with BasiliskII:
// (1) Pascal FUNCTION calling convention — A7 unchanged
// across the C-level call sequence.
// (2) Miss-returns-NIL contract per IM:V V-74.
//
// Diverges from BII on the byte contents of the
// dereferenced CCrsr record on the present-resource path.
//
// Contract-test coverage in this file (mod tests):
// getccursor_returns_handle_for_present_crsr_resource
// getccursor_missing_resource_returns_nil
// getccursor_pascal_function_preserves_stack_across_five_missing_calls
(true, 0x21B) => {
let sp = cpu.read_reg(Register::A7);
let crsr_id = bus.read_word(sp) as i16;
let params = crate::cursor_manager::evaluate_get_ccursor_parameters(crsr_id);
let handle = match self.find_or_load_resource_any(bus, *b"crsr", params.cursor_id) {
Some((_, data_ptr)) => self
.promote_compiled_crsr_resource(bus, data_ptr)
.unwrap_or_else(|| {
self.get_or_create_resource_handle(bus, *b"crsr", params.cursor_id, data_ptr)
}),
None => 0,
};
bus.write_long(sp + 2, handle);
cpu.write_reg(Register::A7, sp + 2);
Ok(())
}
// SetCCursor ($AA1C)
// Changes the current cursor to the given color cursor.
// PROCEDURE SetCCursor(cCrsr: CCrsrHandle);
// Inside Macintosh Volume V, V-80
// Stack: SP+0: cCrsr(4). Pop 4.
// SetCCursor ($AA1C): Pops 4 bytes (cCrsr) and installs the
// cursor image into dispatcher state; host renders the cursor
// itself per IM:V V-80.
(true, 0x21C) => {
let sp = cpu.read_reg(Register::A7);
let crsr_handle = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
let params = crate::cursor_manager::evaluate_set_ccursor_parameters(crsr_handle);
if params.cursor_handle != 0 {
let crsr_ptr = bus.read_long(params.cursor_handle);
if crsr_ptr != 0 {
if let Some(cursor) = self.cursor_image_from_ccrsr(bus, crsr_ptr) {
self.cursor_state.install(cursor);
}
}
}
Ok(())
}
// ========== Mask Operations ==========
// CopyMask ($A817)
// PROCEDURE CopyMask(srcBits, maskBits, dstBits: BitMap;
// srcRect, maskRect, dstRect: Rect);
// Inside Macintosh Volume IV, IV-33
// Where mask bits are 1, the source bit is copied to the
// destination; where mask bits are 0, the destination is
// left unchanged. Source and mask must be the same size;
// destination may have a different size; CopyMask scales the
// source image to fit the destination.
// Stack: SP+0: dstRect(4), SP+4: maskRect(4), SP+8: srcRect(4),
// SP+12: dstBits(4), SP+16: maskBits(4), SP+20: srcBits(4). Pop 24.
// Deep masks and direct-color transfers share CopyDeepMask semantics.
(true, 0x017) => {
let sp = cpu.read_reg(Register::A7);
let dst_rect_ptr = bus.read_long(sp);
let mask_rect_ptr = bus.read_long(sp + 4);
let src_rect_ptr = bus.read_long(sp + 8);
let dst_bits_ptr = bus.read_long(sp + 12);
let mask_bits_ptr = bus.read_long(sp + 16);
let src_bits_ptr = bus.read_long(sp + 20);
cpu.write_reg(Register::A7, sp + 24);
let src_info = self.resolve_copy_bitmap(bus, src_bits_ptr);
let mask_info = self.resolve_copy_bitmap(bus, mask_bits_ptr);
let dst_info = self.resolve_copy_bitmap(bus, dst_bits_ptr);
if mask_info.pixel_size != 1
|| !matches!(src_info.pixel_size, 1 | 2 | 4 | 8)
|| !matches!(dst_info.pixel_size, 1 | 8)
{
return Some(self.copy_deep_mask_transfer(
bus, src_bits_ptr, mask_bits_ptr, dst_bits_ptr,
src_rect_ptr, mask_rect_ptr, dst_rect_ptr, 0, 0,
));
}
let src_top = bus.read_word(src_rect_ptr) as i16;
let src_left = bus.read_word(src_rect_ptr + 2) as i16;
let src_bottom = bus.read_word(src_rect_ptr + 4) as i16;
let src_right = bus.read_word(src_rect_ptr + 6) as i16;
let mask_top = bus.read_word(mask_rect_ptr) as i16;
let mask_left = bus.read_word(mask_rect_ptr + 2) as i16;
let mask_bottom = bus.read_word(mask_rect_ptr + 4) as i16;
let mask_right = bus.read_word(mask_rect_ptr + 6) as i16;
let dst_top = bus.read_word(dst_rect_ptr) as i16;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16;
// Indexed pixels are meaningful only through their source
// color table. CopyMask uses that table for source color
// information and the current GDevice's table for destination
// color information; the destination PixMap's table is not
// authoritative. Imaging With QuickDraw (1994), pp. 4-31 and
// 3-119--3-120. In particular, equal ctSeed values do not make
// raw indices interchangeable when the tables contain
// different colors.
let dst_ctab_handle =
self.copy_bits_destination_ctab_handle(bus, *self.current_port, &dst_info);
let src_clut = matches!(src_info.pixel_size, 2 | 4 | 8)
.then(|| self.read_port_clut(bus, src_info.ctab_handle));
let screen_destination = dst_info.base == self.screen_mode.0
&& dst_info.row_bytes == self.screen_mode.1
&& dst_info.pixel_size == u32::from(self.screen_mode.4);
let dst_clut = self.read_indexed_destination_clut(
bus,
dst_ctab_handle,
dst_info.pixel_size,
screen_destination,
);
let palette_translation = match (src_clut.as_ref(), dst_clut.as_ref()) {
(Some(src_clut), Some(dst_clut)) if src_clut != dst_clut => {
Some(self.build_palette_translation(
bus,
src_clut,
dst_clut,
dst_ctab_handle,
src_info.pixel_size,
dst_info.pixel_size,
))
}
_ => None,
};
if src_bottom <= src_top
|| src_right <= src_left
|| mask_bottom <= mask_top
|| mask_right <= mask_left
|| dst_bottom <= dst_top
|| dst_right <= dst_left
{
return Some(Ok(()));
}
let clip_t = dst_top.max(dst_info.bounds_top);
let clip_l = dst_left.max(dst_info.bounds_left);
let clip_b = dst_bottom.min(dst_info.bounds_bottom);
let clip_r = dst_right.min(dst_info.bounds_right);
if clip_b <= clip_t || clip_r <= clip_l {
return Some(Ok(()));
}
let src_w = i32::from(src_right) - i32::from(src_left);
let src_h = i32::from(src_bottom) - i32::from(src_top);
let mask_w = i32::from(mask_right) - i32::from(mask_left);
let mask_h = i32::from(mask_bottom) - i32::from(mask_top);
let dst_w = i32::from(dst_right) - i32::from(dst_left);
let dst_h = i32::from(dst_bottom) - i32::from(dst_top);
let no_src_scaling = src_w == dst_w && src_h == dst_h && src_w > 0 && src_h > 0;
let no_mask_scaling =
mask_w == dst_w && mask_h == dst_h && mask_w > 0 && mask_h > 0;
// The overwhelmingly common indexed CopyMask shape is an
// unscaled 8-bit sprite gated by a 1-bit mask. The generic
// loop below deliberately supports every admitted depth and
// scaling combination, but pays for two bounds/depth
// dispatches per destination pixel through
// `read_bitmap_pixel`. Prove that the clipped source and mask
// spans are wholly in bounds, then fetch each span once per
// row and store each opaque run as one span. Span stores fall
// back to byte stores while framebuffer tracing or watchpoints
// are active; palette translation is unchanged.
let clipped_width = i32::from(clip_r) - i32::from(clip_l);
let clipped_height = i32::from(clip_b) - i32::from(clip_t);
let src_clip_top = i32::from(src_top) + (i32::from(clip_t) - i32::from(dst_top));
let src_clip_left = i32::from(src_left) + (i32::from(clip_l) - i32::from(dst_left));
let src_clip_bottom = src_clip_top + clipped_height;
let src_clip_right = src_clip_left + clipped_width;
let mask_clip_top = i32::from(mask_top) + (i32::from(clip_t) - i32::from(dst_top));
let mask_clip_left =
i32::from(mask_left) + (i32::from(clip_l) - i32::from(dst_left));
let mask_clip_bottom = mask_clip_top + clipped_height;
let mask_clip_right = mask_clip_left + clipped_width;
let buffered_geometry_valid = src_info.pixel_size == 8
&& mask_info.pixel_size == 1
&& dst_info.pixel_size == 8
&& no_src_scaling
&& no_mask_scaling
&& src_clip_top >= i32::from(src_info.bounds_top)
&& src_clip_left >= i32::from(src_info.bounds_left)
&& src_clip_bottom <= i32::from(src_info.bounds_bottom)
&& src_clip_right <= i32::from(src_info.bounds_right)
&& mask_clip_top >= i32::from(mask_info.bounds_top)
&& mask_clip_left >= i32::from(mask_info.bounds_left)
&& mask_clip_bottom <= i32::from(mask_info.bounds_bottom)
&& mask_clip_right <= i32::from(mask_info.bounds_right);
let buffered_spans_disjoint = if buffered_geometry_valid {
let width = clipped_width as u32;
let height = clipped_height as u32;
let src_row = (src_clip_top - i32::from(src_info.bounds_top)) as u32;
let src_col = (src_clip_left - i32::from(src_info.bounds_left)) as u32;
let mask_row = (mask_clip_top - i32::from(mask_info.bounds_top)) as u32;
let mask_col = (mask_clip_left - i32::from(mask_info.bounds_left)) as u32;
let dst_row = (i32::from(clip_t) - i32::from(dst_info.bounds_top)) as u32;
let dst_col = (i32::from(clip_l) - i32::from(dst_info.bounds_left)) as u32;
let mask_first_byte = mask_col / 8;
let mask_first_bit = mask_col % 8;
let mask_byte_count = (mask_first_bit + width).div_ceil(8);
let accessed_span = |base: u32,
row_bytes: u32,
first_row: u32,
first_col: u32,
rows: u32,
bytes: u32|
-> Option<(u64, u64)> {
if rows == 0 || bytes == 0 || first_col.checked_add(bytes)? > row_bytes {
return None;
}
let start = u64::from(base)
+ u64::from(first_row) * u64::from(row_bytes)
+ u64::from(first_col);
let end = u64::from(base)
+ u64::from(first_row.checked_add(rows - 1)?) * u64::from(row_bytes)
+ u64::from(first_col)
+ u64::from(bytes);
(end <= u64::from(u32::MAX) + 1).then_some((start, end))
};
let src_span = accessed_span(
src_info.base,
src_info.row_bytes,
src_row,
src_col,
height,
width,
);
let mask_span = accessed_span(
mask_info.base,
mask_info.row_bytes,
mask_row,
mask_first_byte,
height,
mask_byte_count,
);
let dst_span = accessed_span(
dst_info.base,
dst_info.row_bytes,
dst_row,
dst_col,
height,
width,
);
match (src_span, mask_span, dst_span) {
(Some(src), Some(mask), Some(dst)) => {
let disjoint = |a: (u64, u64), b: (u64, u64)| a.1 <= b.0 || b.1 <= a.0;
disjoint(src, dst) && disjoint(mask, dst)
}
_ => false,
}
} else {
false
};
let row_buffered_8bpp_mask = buffered_geometry_valid && buffered_spans_disjoint;
if row_buffered_8bpp_mask {
let width = clipped_width as usize;
let src_col = (src_clip_left - i32::from(src_info.bounds_left)) as u32;
let mask_col = (mask_clip_left - i32::from(mask_info.bounds_left)) as u32;
let dst_col = (clip_l - dst_info.bounds_left) as u32;
let mask_first_byte = mask_col / 8;
let mask_first_bit = (mask_col % 8) as usize;
let mask_byte_count = (mask_first_bit + width).div_ceil(8);
let mut source_row = vec![0u8; width];
let mut mask_row = vec![0u8; mask_byte_count];
for dy in clip_t..clip_b {
let relative_y = i32::from(dy) - i32::from(clip_t);
let src_row =
(src_clip_top + relative_y - i32::from(src_info.bounds_top)) as u32;
let mask_row_index =
(mask_clip_top + relative_y - i32::from(mask_info.bounds_top)) as u32;
let dst_row = (dy - dst_info.bounds_top) as u32;
bus.read_bytes_into(
src_info.base + src_row * src_info.row_bytes + src_col,
&mut source_row,
);
bus.read_bytes_into(
mask_info.base + mask_row_index * mask_info.row_bytes + mask_first_byte,
&mut mask_row,
);
let dst_row_base = dst_info.base + dst_row * dst_info.row_bytes + dst_col;
if let Some(translation) = palette_translation.as_ref() {
for pixel in &mut source_row {
*pixel = translation[*pixel as usize];
}
}
// Store each run of opaque pixels as one span. On a
// presented screen row that is one presentation
// update per run rather than per pixel, with the
// same result as storing the pixels one at a time;
// transparent pixels are not touched.
let opaque = |column: usize| {
let mask_bit = mask_first_bit + column;
mask_row[mask_bit / 8] & (1 << (7 - mask_bit % 8)) != 0
};
let mut column = 0;
while column < width {
if !opaque(column) {
column += 1;
continue;
}
let start = column;
while column < width && opaque(column) {
column += 1;
}
bus.write_bytes(
dst_row_base + start as u32,
&source_row[start..column],
);
}
}
return Some(Ok(()));
}
for dy in clip_t..clip_b {
let sy = if no_src_scaling {
i32::from(src_top) + (i32::from(dy) - i32::from(dst_top))
} else {
let Some(sy) =
Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, dy)
else {
continue;
};
sy
} as i16;
let my = if no_mask_scaling {
i32::from(mask_top) + (i32::from(dy) - i32::from(dst_top))
} else {
let Some(my) =
Self::scale_coord(mask_top, mask_bottom, dst_top, dst_bottom, dy)
else {
continue;
};
my
} as i16;
for dx in clip_l..clip_r {
let sx = if no_src_scaling {
i32::from(src_left) + (i32::from(dx) - i32::from(dst_left))
} else {
let Some(sx) =
Self::scale_coord(src_left, src_right, dst_left, dst_right, dx)
else {
continue;
};
sx
} as i16;
let mx = if no_mask_scaling {
i32::from(mask_left) + (i32::from(dx) - i32::from(dst_left))
} else {
let Some(mx) =
Self::scale_coord(mask_left, mask_right, dst_left, dst_right, dx)
else {
continue;
};
mx
} as i16;
let Some(mask_pixel) = Self::read_bitmap_pixel(bus, &mask_info, my, mx)
else {
continue;
};
if mask_pixel == 0 {
continue; // transparent — leave dst alone
}
let Some(src_pixel) = Self::read_bitmap_pixel(bus, &src_info, sy, sx)
else {
continue;
};
let row = (dy - dst_info.bounds_top) as u32;
let col = (dx - dst_info.bounds_left) as u32;
match dst_info.pixel_size {
1 => {
let addr = dst_info.base + row * dst_info.row_bytes + (col / 8);
let bit = 7 - (col % 8);
let byte = bus.read_byte(addr);
// src_pixel is 0 or 255 from
// read_bitmap_pixel's 1bpp branch (or
// an 8bpp value if dst is 8bpp). For
// 1bpp dst, a non-zero src bit sets,
// a zero src bit clears.
let new_byte = if src_pixel != 0 {
byte | (1 << bit)
} else {
byte & !(1 << bit)
};
bus.write_byte(addr, new_byte);
}
8 => {
let dst_pixel = palette_translation
.as_ref()
.map_or(src_pixel, |translation| {
translation[src_pixel as usize]
});
bus.write_byte(
dst_info.base + row * dst_info.row_bytes + col,
dst_pixel,
);
}
_ => {} // 16/32 bpp not yet supported
}
}
}
Ok(())
}
// CopyDeepMask ($AA51)
// PROCEDURE CopyDeepMask(srcBits, maskBits, dstBits: BitMap;
// srcRect, maskRect, dstRect: Rect;
// mode: INTEGER; maskRgn: RgnHandle);
// Imaging With QuickDraw, 3-36
// Combines CopyBits with CopyMask using a deep mask:
// where mask bits are set, the source bit is copied to the
// destination via `mode`; where mask bits are clear, the
// destination is left unchanged. maskRgn optionally
// further clips the destination (NIL = no clip).
// Stack: SP+0: maskRgn(4), SP+4: mode(2), SP+6: dstRect(4),
// SP+10: maskRect(4), SP+14: srcRect(4), SP+18: dstBits(4),
// SP+22: maskBits(4), SP+26: srcBits(4). Pop 30.
// Reuses the same mask-gated pixel loop as CopyMask ($A817),
// but maps destination pixels back through srcRect and
// maskRect so differing dstRect dimensions scale like CopyBits.
// The `mode` parameter is honored for indexed and direct-color
// destinations. A one-bit mask gates the transfer, while a deep
// mask blends source and destination RGB components according to
// the mask's own components per Imaging With QuickDraw,
// pp. 3-120--3-122.
(true, 0x251) => {
let sp = cpu.read_reg(Register::A7);
let mask_rgn = bus.read_long(sp);
let mode = bus.read_word(sp + 4) as i16;
let dst_rect_ptr = bus.read_long(sp + 6);
let mask_rect_ptr = bus.read_long(sp + 10);
let src_rect_ptr = bus.read_long(sp + 14);
let dst_bits_ptr = bus.read_long(sp + 18);
let mask_bits_ptr = bus.read_long(sp + 22);
let src_bits_ptr = bus.read_long(sp + 26);
cpu.write_reg(Register::A7, sp + 30);
self.copy_deep_mask_transfer(
bus, src_bits_ptr, mask_bits_ptr, dst_bits_ptr,
src_rect_ptr, mask_rect_ptr, dst_rect_ptr, mode, mask_rgn,
)
}
// ========== Text / Font ==========
// MeasureText ($A837)
// PROCEDURE MeasureText(count: INTEGER; textAddr, charLocs: Ptr);
// Inside Macintosh Volume IV (1986), p. IV-32
//
// "MeasureText takes a `count`-byte string of text starting
// at `textAddr` and fills `charLocs` with `count + 1`
// INTEGERs giving the horizontal pixel offsets of each
// character from the starting point. The first integer is
// always 0, and the last is the total width of the text."
//
// Stack: SP+0=charLocs(4), SP+4=textAddr(4), SP+8=count(2).
// Pops 10.
// MeasureText ($A837): Writes count+1 horizontal pixel offsets into charLocs (cumulative glyph advances scaled to current tx_size); first offset is 0 per IM:IV IV-32
(true, 0x037) => {
let sp = cpu.read_reg(Register::A7);
let char_locs = bus.read_long(sp);
let text_addr = bus.read_long(sp + 4);
let count = bus.read_word(sp + 8) as i16;
cpu.write_reg(Register::A7, sp + 10);
if char_locs != 0 {
let (_face, scale) = get_font_face_scaled(self.tx_font, self.tx_size);
let mut offset: i16 = 0;
bus.write_word(char_locs, 0);
if text_addr != 0 && count > 0 {
for i in 0..(count as u32) {
let ch = bus.read_byte(text_addr + i) as char;
let advance =
if let Some((g, _)) = get_glyph(self.tx_font, self.tx_size, ch) {
self.glyph_advance(g) * scale
} else {
self.missing_glyph_advance() * scale
};
offset = offset.saturating_add(advance);
bus.write_word(char_locs + (i + 1) * 2, offset as u16);
}
}
}
Ok(())
}
// CharExtra ($AA23)
// PROCEDURE CharExtra(extra: Fixed);
// Inside Macintosh Volume V (1986), p. V-77 (Color QuickDraw —
// Color Drawing Routines — CharExtra). Per the verbatim
// contract: "The CharExtra procedure sets the cGrafPort's
// charExtra field, which specifies the number of pixels by
// which to widen every character excluding the space character
// in a line of text. The charExtra field is stored in a
// compressed format based on the txSize field, so you must set
// txSize before calling CharExtra. The initial charExtra
// setting is 0. CharExtra will accept a negative number.
// CharExtra has no effect on grafPorts."
//
// MPW Universal Headers QuickdrawText.h:
// EXTERN_API(void) CharExtra(Fixed extra) ONEWORDINLINE(0xAA23);
//
// Tool-bit Pascal PROCEDURE pop-4 ABI: caller pushes the 4-byte
// Fixed argument, trap pops it (no FUNCTION result slot is
// written, A7 unchanged across the call). The shape is
// identical to $AA47 SetDeskCPat / $AA0A PenPixPat /
// $AA0B BackPixPat / $AA21 OpColor / $AA22 HiliteColor.
//
// The absolute side effect differs from BII: BasiliskII System
// 7.5.3 ROM Color QuickDraw honours the documented contract on
// a CGrafPort (writes the Fixed value into the charExtra field
// in compressed format based on txSize per IM:V V-77) and is a
// documented pure no-op on a regular GrafPort. Systemless's HLE
// stores the value in dispatcher-internal `char_extra` state
// regardless of port type. The two engines still share the
// Pascal PROCEDURE pop-4 calling convention itself.
//
// Stack: SP+0=extra(Fixed, 4). Pops 4.
//
// draw_char applies the integer portion to each non-space glyph;
// spaces use the GrafPort's separate SpaceExtra value.
(true, 0x223) => {
let sp = cpu.read_reg(Register::A7);
let extra_fixed = bus.read_long(sp) as i32;
cpu.write_reg(Register::A7, sp + 4);
self.char_extra = extra_fixed;
Ok(())
}
// FontMetrics ($A835)
// PROCEDURE FontMetrics(VAR theMetrics: FMetricRec);
// Inside Macintosh Volume IV (1986), p. IV-32
//
// Per IM:IV IV-32: "FontMetrics is similar to the QuickDraw
// procedure GetFontInfo except that it returns fixed-point
// values for greater accuracy in high-resolution printing."
// The procedure populates the caller's FMetricRec with the
// ascent/descent/leading/widMax for the current font as
// Fixed16.16 values, plus a handle to the font's global
// width table.
//
// FMetricRec record layout (20 bytes total — IM:IV IV-32):
// +0 ascent Fixed base line to top
// +4 descent Fixed base line to bottom
// +8 leading Fixed leading between lines
// +12 widMax Fixed maximum character width
// +16 wTabHandle Handle handle to global width table
//
// MPW Universal Headers Fonts.h declaration:
// EXTERN_API(void) FontMetrics(FMetricRecPtr theMetrics)
// ONEWORDINLINE(0xA835)
//
// Pascal PROCEDURE stack frame (caller perspective):
// sp+0..3 theMetrics FMetricRecPtr (last/only push)
// 4-byte pop, no function-result slot reserved
//
// BII-vs-Systemless divergence on wTabHandle: per IM:IV IV-32
// "A handle to the global width table is returned by the
// FontMetrics procedure." BasiliskII System 7.5.3 ROM
// populates wTabHandle with a real handle to the system's
// global width table (allocated in the system heap per
// IM:IV IV-33). Systemless does not model the global width
// table and writes NIL (0) verbatim. The shared contract is
// "wTabHandle field is overwritten" (the sentinel does not
// survive); the exact handle value is engine-specific.
//
// Contract-test coverage in this file (mod tests):
// tests::fontmetrics_writes_fixed_ascent_descent_leading_widmax
// tests::fontmetrics_consumes_fmetricrecptr_argument_and_pops_four_bytes
(true, 0x035) => {
let sp = cpu.read_reg(Register::A7);
let rec_ptr = bus.read_long(sp);
cpu.write_reg(Register::A7, sp + 4);
if rec_ptr != 0 {
let (face, scale) = get_font_face_scaled(self.tx_font, self.tx_size);
let metrics = face.metrics;
// Convert i16 pixel values to Fixed16.16 by shifting
// the integer into the high word.
let to_fixed = |v: i16| -> u32 { (v as i32 as u32) << 16 };
bus.write_long(rec_ptr, to_fixed(metrics.ascent * scale));
bus.write_long(rec_ptr + 4, to_fixed(metrics.descent * scale));
bus.write_long(rec_ptr + 8, to_fixed(metrics.leading * scale));
bus.write_long(rec_ptr + 12, to_fixed(metrics.wid_max * scale));
// wTabHandle: not modeled — leave NIL.
bus.write_long(rec_ptr + 16, 0);
}
Ok(())
}
// SetFScaleDisable ($A834)
// Enables or disables font scaling in the Font Manager's
// bitmapped-font selection path.
// PROCEDURE SetFScaleDisable(fontScaleDisable: BOOLEAN);
// Inside Macintosh Volume IV (1986), p. IV-32; Inside Macintosh:
// Text (1993), pp. 4-38 and 4-59.
//
// Per IM:IV IV-32: "SetFScaleDisable lets you disable or enable
// font scaling. If fontScaleDisable is TRUE, font scaling is
// disabled and the Font Manager returns an unscaled font with
// more space around the characters; if it's FALSE, the Font
// Manager scales fonts. To ensure compatibility with existing
// applications, the Font Manager defaults to scaling fonts."
// The assembly-language note on the same page states the trap
// mutates the FScaleDisable low-memory global directly; IM:III
// (1985) p. III-227 records the global at byte address $0A63
// ("nonzero to disable font scaling, byte"). MPW exposes the
// global via TWOWORDINLINE accessors:
// LMGetFScaleDisable() = MOVE.B $0A63, D0 (0x1EB8 0x0A63)
// LMSetFScaleDisable(v) = MOVE.B v, $0A63 (0x11DF 0x0A63)
//
// Pascal PROCEDURE protocol (caller perspective):
// Stack on entry: SP+0: fontScaleDisable(2) — the BOOLEAN
// argument encoded as a 2-byte word with the value byte in
// the HIGH byte (MPW Pascal BOOLEAN convention). The trap
// pops 2 bytes; no function-result slot is reserved.
//
// Byte-write semantic: the real System 7.5 ROM writes the raw
// Pascal BOOLEAN high byte verbatim to $0A63 — TRUE becomes
// the byte value 0x01 (not a normalised 0xFF) and FALSE becomes
// 0x00. Systemless mirrors this exact byte by reading SP+0
// directly (no normalisation). BasiliskII System 7.5.3 ROM
// follows the same convention.
//
// Note: per IM:IV IV-32 "setting the global variable
// FScaleDisable is insufficient" — the real Font Manager also
// flushes width caches and resets internal scaling state. The
// Systemless HLE does not model those secondary effects because
// the visible-state contract surfaces (LMGetFScaleDisable, the
// byte at $0A63) match BII exactly.
//
// Regression coverage:
// tests::setfscaledisable_true_writes_one_byte_verbatim_to_fscale_disable_global
// tests::setfscaledisable_false_writes_zero_byte_to_fscale_disable_global
// tests::setfscaledisable_consumes_two_byte_boolean_argument_and_balances_stack
// SetFScaleDisable ($A834): Writes FScaleDisable low-mem global ($0A63); per IM:IV IV-32
(true, 0x034) => {
let sp = cpu.read_reg(Register::A7);
// Pascal BOOLEAN at SP+0 (MPW convention: value byte in
// the high byte of the 2-byte stack slot).
let fscale_disable_byte = bus.read_byte(sp);
cpu.write_reg(Register::A7, sp + 2);
bus.write_byte(0x0A63, fscale_disable_byte);
Ok(())
}
// GetMaskTable ($A836)
// Returns in A0 a pointer to QuickDraw's internal mask table.
// Inside Macintosh Volume IV (1986), pp. IV-25..IV-26:
// "The function GetMaskTable, accessible only from
// assembly language, returns in register A0 a pointer
// to a ROM table containing the following useful masks:
// 16 right masks, 16 left masks, 16 bit masks."
// Per IM:IV trap-macro summary (p. IV-26): on entry — none;
// on exit — A0: ptr to mask table in ROM. The trap consumes
// no stack arguments and reserves no result slot — the
// Pascal FUNCTION protocol is NOT used.
//
// MPW Universal Headers Quickdraw.h declares it as:
// #pragma parameter __A0 GetMaskTable
// EXTERN_API( Ptr ) GetMaskTable(void) ONEWORDINLINE(0xA836);
// matching the register-return convention from IM:IV.
//
// Systemless lazily allocates a 96-byte copy of the documented
// table on first call and caches the address in
// `mask_table_addr`. The bytes match IM:IV's exact ROM
// layout, so any caller that walks the three 16-word
// sub-tables (right masks, left masks, bit masks) sees the
// same values it would on real Mac ROM.
//
// Contract coverage:
// src/trap/quickdraw.rs::tests::getmasktable_writes_non_nil_pointer_to_a0_and_preserves_stack
// src/trap/quickdraw.rs::tests::getmasktable_table_contents_match_inside_macintosh_iv_layout
(true, 0x036) => {
let addr = match self.mask_table_addr {
Some(a) => a,
None => {
let a = bus.alloc(96);
// Right masks (IM:IV IV-25)
const RIGHT: [u16; 16] = [
0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800, 0xFC00, 0xFE00, 0xFF00,
0xFF80, 0xFFC0, 0xFFE0, 0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE,
];
// Left masks (IM:IV IV-25)
const LEFT: [u16; 16] = [
0xFFFF, 0x7FFF, 0x3FFF, 0x1FFF, 0x0FFF, 0x07FF, 0x03FF, 0x01FF, 0x00FF,
0x007F, 0x003F, 0x001F, 0x000F, 0x0007, 0x0003, 0x0001,
];
// Bit masks (IM:IV IV-25)
const BIT: [u16; 16] = [
0x8000, 0x4000, 0x2000, 0x1000, 0x0800, 0x0400, 0x0200, 0x0100, 0x0080,
0x0040, 0x0020, 0x0010, 0x0008, 0x0004, 0x0002, 0x0001,
];
for (i, w) in RIGHT
.iter()
.chain(LEFT.iter())
.chain(BIT.iter())
.enumerate()
{
bus.write_word(a + (i as u32) * 2, *w);
}
self.mask_table_addr = Some(a);
a
}
};
cpu.write_reg(Register::A0, addr);
Ok(())
}
// _FontDispatch (0xA854)
// Dispatches outline and font-cache management routines.
// Selector ABI: signed 8-bit MOVEQ immediate in D0; routine-specific Pascal parameters remain on the stack.
// Inside Macintosh: Text (1993), 4-56, 4-60–4-66.
(true, 0x054) => {
let sp = cpu.read_reg(Register::A7);
let selector = cpu.read_reg(Register::D0);
let operation = font_dispatch_operation_route(self.current_trap_word, selector);
self.current_selector_operation = operation.map(|route| route.operation_id);
let routine = selector & 0xFFFF;
match routine {
// $0000 IsOutline (numer Point + denom Point → Boolean)
// Stack: SP+0 denom Point (4) + SP+4 numer Point (4)
// + SP+8 result BOOLEAN (2). Pop 8; result at sp+8.
// Returns FALSE — no outline fonts in HLE.
0x0000 => {
bus.write_word(sp + 8, 0); // FALSE
cpu.write_reg(Register::A7, sp + 8);
cpu.write_reg(Register::D0, 0);
Ok(())
}
// $0001 SetOutlinePreferred (Boolean) — pop the 2-byte Boolean slot and persist the preference
0x0001 => {
self.outline_preferred = bus.read_byte(sp) != 0;
cpu.write_reg(Register::A7, sp + 2);
cpu.write_reg(Register::D0, 0);
Ok(())
}
// $0008 OutlineMetrics (8 args → OSErr)
// Pascal frame per IM:VI 12-19:
// byteCount INTEGER + textPtr Ptr + numer Point +
// denom Point + VAR yMax INTEGER + VAR yMin INTEGER +
// awArray FixedPtr + lsbArray FixedPtr +
// boundsArray RectPtr → OSErr
// Total args: 2+4+4+4+4+4+4+4+4 = 34 bytes; pop 34 + 2 result.
0x0008 => {
// Returns resNotFound (-192) — no outline fonts
// exist to measure, per IM:VI 12-19 OutlineMetrics
// "works on TrueType fonts only".
bus.write_word(sp + 34, (-192i16) as u16);
cpu.write_reg(Register::A7, sp + 34);
cpu.write_reg(Register::D0, (-192i32) as u32);
Ok(())
}
// $0009 GetOutlinePreferred (→ Boolean) — write the 1-byte Boolean result into the return slot
0x0009 => {
let value = if self.outline_preferred { 1 } else { 0 };
bus.write_byte(sp, value as u8);
cpu.write_reg(Register::D0, value as u32);
Ok(())
}
// $000A SetPreserveGlyph (Boolean) — pop the 2-byte Boolean slot and persist the preference
0x000A => {
self.preserve_glyph = bus.read_byte(sp) != 0;
cpu.write_reg(Register::A7, sp + 2);
cpu.write_reg(Register::D0, 0);
Ok(())
}
// $000B GetPreserveGlyph (→ Boolean) — write the 1-byte Boolean result into the return slot
0x000B => {
let value = if self.preserve_glyph { 1 } else { 0 };
bus.write_byte(sp, value as u8);
cpu.write_reg(Register::D0, value as u32);
Ok(())
}
// $000C FlushFonts (→ OSErr) — no args
0x000C => {
bus.write_word(sp, 0); // noErr
cpu.write_reg(Register::D0, 0);
Ok(())
}
// Unknown selector — defensive no-op + noErr
_ => {
cpu.write_reg(Register::D0, 0);
Ok(())
}
}
}
// ========== Stubs — Selector-Based Dispatchers ==========
// NQDMisc ($ABC3)
// Selector-based dispatcher for QuickDraw picture-comment misc
// codes. Selector 6 is the SetGrayLevel path.
// Imaging With QuickDraw 1994, p. B-40.
// Register calling convention: selector in D0, data pointer in A0.
// No Pascal stack frame is consumed on the selector-6 path.
(true, 0x3C3) => {
cpu.write_reg(Register::D0, 0);
Ok(())
}
// DragDispatch ($ABED). System 7 Finder probes the manager with
// private selector $C301 (Boolean, Ptr -> OSErr). There is no
// booted Drag Manager in this HLE, so report unimpErr and let the
// caller use its non-drag path. Universal Interfaces 3.4,
// Traps.h, names $ABED as DragDispatch.
(true, 0x3ED) if matches!(cpu.read_reg(Register::D0), 1 | 2) => {
// InstallTrackingHandler / InstallReceiveHandler each take
// three pointers. Report the unavailable Drag Manager so
// callers can use their non-drag interaction path. Apple
// Universal Interfaces Drag.h, selectors $0001 and $0002.
let sp = cpu.read_reg(Register::A7);
bus.write_word(sp + 12, (-4i16) as u16); // unimpErr
cpu.write_reg(Register::A7, sp + 12);
Ok(())
}
(true, 0x3ED) if cpu.read_reg(Register::D0) == 0xC301 => {
let sp = cpu.read_reg(Register::A7);
bus.write_word(sp + 6, (-4i16) as u16); // unimpErr
cpu.write_reg(Register::A7, sp + 6);
cpu.write_reg(Register::D0, (-4i32) as u32);
Ok(())
}
// DisplayDispatch ($ABEB)
// Selector-based dispatcher for the Display Manager. Abuse 1.01
// enumerates active screen devices here. Systemless models one active
// screen GDevice, so return that handle for first-screen and NIL for
// next-screen. The OSErr-returning selectors below write the return
// code to both D0 and the documented stack result slot.
(true, 0x3EB) => {
let sp = cpu.read_reg(Register::A7);
match cpu.read_reg(Register::D0) as u16 {
// DMGetFirstScreenDevice(Boolean flags) -> GDHandle.
0 => {
let gdh = self.ensure_main_gdevice(bus);
bus.write_long(sp + 2, gdh);
cpu.write_reg(Register::A7, sp + 2);
}
// DMGetNextScreenDevice(GDHandle, Boolean flags) -> GDHandle.
1 => {
bus.write_long(sp + 6, 0);
cpu.write_reg(Register::A7, sp + 6);
}
// DMGetDisplayIDByGDevice(GDHandle, DisplayIDType *, Boolean)
// -> OSErr. Display IDs remain stable while a device is
// attached; the single-display model uses ID 1, matching
// the native PowerPC Display Manager path.
// Apple's Optimizing Display Modes and Window Buffers
// (2007), p. 26.
0x051F => {
let fail_to_main = bus.read_word(sp) != 0;
let display_id_ptr = bus.read_long(sp + 2);
let requested_gdh = bus.read_long(sp + 6);
let main_gdh = self.ensure_main_gdevice(bus);
let result =
if display_id_ptr != 0 && (requested_gdh == main_gdh || fail_to_main) {
bus.write_long(display_id_ptr, 1);
0
} else {
-50i16
};
bus.write_word(sp + 10, result as u16);
cpu.write_reg(Register::A7, sp + 10);
cpu.write_reg(Register::D0, result as i32 as u32);
}
// DMNewDisplayModeList(DisplayIDType, UInt32, UInt32,
// DMListIndexType *, DMListType *)
// -> OSErr. Universal Interfaces 3.4.1 Displays.h models
// the list as opaque and exposes entries through selector
// $37; advertise the active single-screen indexed mode.
0x0A36 => {
let list_out = bus.read_long(sp);
let count_out = bus.read_long(sp + 4);
let display_id = bus.read_long(sp + 16);
let result = if display_id != 1 || list_out == 0 || count_out == 0 {
-50i16
} else {
let mut geometries = vec![
(DM_512_342_MODE_ID, 512, 342),
(DM_640_480_MODE_ID, 640, 480),
];
if !matches!(self.native_screen_geometry, (512, 342) | (640, 480)) {
geometries.push((
DM_NATIVE_MODE_ID,
self.native_screen_geometry.0,
self.native_screen_geometry.1,
));
}
let list_size = DM_MODE_LIST_ENTRY_STRIDE * geometries.len() as u32;
let list = bus.alloc(list_size);
if list == 0 {
-108i16 // memFullErr
} else {
bus.fill_zeros(list, list_size);
let (screen_base, _, _, _, pixel_size) = self.screen_mode;
bus.write_long(list, DM_MODE_LIST_MAGIC);
bus.write_long(list + 4, display_id);
bus.write_long(list + 8, geometries.len() as u32);
let wrote_all = geometries.iter().enumerate().all(
|(index, (mode, width, height))| {
Self::write_display_mode_list_entry(
bus,
list + index as u32 * DM_MODE_LIST_ENTRY_STRIDE,
*mode,
*width,
*height,
pixel_size,
screen_base,
)
.is_some()
},
);
if wrote_all {
bus.write_long(count_out, geometries.len() as u32);
bus.write_long(list_out, list);
0
} else {
bus.free(list);
-50i16
}
}
};
bus.write_word(sp + 20, result as u16);
cpu.write_reg(Register::A7, sp + 20);
cpu.write_reg(Register::D0, result as i32 as u32);
}
// DMDisposeList(DMListType) -> OSErr.
0x022C => {
let list = bus.read_long(sp);
let result = if bus.read_long(list) == DM_MODE_LIST_MAGIC {
bus.free(list);
0
} else {
-50i16
};
bus.write_word(sp + 4, result as u16);
cpu.write_reg(Register::A7, sp + 4);
cpu.write_reg(Register::D0, result as i32 as u32);
}
0x0A37 => {
let user_data = bus.read_long(sp);
let callback = bus.read_long(sp + 4);
let item_index = bus.read_long(sp + 12);
let list = bus.read_long(sp + 16);
if callback == 0
|| bus.read_long(list) != DM_MODE_LIST_MAGIC
|| item_index >= bus.read_long(list + 8)
{
bus.write_word(sp + 20, (-50i16) as u16);
cpu.write_reg(Register::A7, sp + 20);
cpu.write_reg(Register::D0, (-50i32) as u32);
} else {
// DMGetIndexedDisplayModeFromList calls the iterator
// as (userData, itemIndex, entry). Return through a
// tiny cleanup thunk so both RTS and RTD-style UPPs
// resume with the DisplayDispatch result slot atop
// the caller's stack.
let resume_sp = sp + 20;
let return_pc = self
.current_trap_caller
.unwrap_or_else(|| cpu.read_reg(Register::PC));
let cleanup = bus.alloc(12);
if cleanup == 0 {
bus.write_word(resume_sp, (-108i16) as u16);
cpu.write_reg(Register::A7, resume_sp);
cpu.write_reg(Register::D0, (-108i32) as u32);
} else {
bus.write_word(cleanup, 0x2E7C); // MOVEA.L #resume_sp,A7
bus.write_long(cleanup + 2, resume_sp);
bus.write_word(cleanup + 6, 0x4EF9); // JMP return_pc
bus.write_long(cleanup + 8, return_pc);
bus.write_word(resume_sp, 0);
bus.write_long(sp + 16, user_data);
bus.write_long(sp + 12, item_index);
bus.write_long(
sp + 8,
list
+ item_index * DM_MODE_LIST_ENTRY_STRIDE
+ DM_MODE_LIST_ENTRY_OFFSET,
);
bus.write_long(sp + 4, cleanup);
cpu.write_reg(Register::A7, sp + 4);
cpu.write_reg(Register::PC, callback);
self.preserve_auto_pop_pc_once = self.current_trap_caller.is_some();
cpu.write_reg(Register::D0, 0);
}
}
}
// DMBeginConfigureDisplays(Handle *displayState) -> OSErr.
// BasiliskII returns the main GDevice handle as the begin
// token and stores the same handle through *displayState.
0x0206 => {
let display_state_ptr = bus.read_long(sp);
let display_state = self.ensure_main_gdevice(bus);
if display_state_ptr != 0 {
bus.write_long(display_state_ptr, display_state);
}
bus.write_word(sp + 4, display_state as u16);
cpu.write_reg(Register::A7, sp + 4);
cpu.write_reg(Register::D0, display_state as i16 as i32 as u32);
}
// DMEndConfigureDisplays(Handle displayState) -> OSErr.
0x0207 => {
bus.write_word(sp + 4, 0);
cpu.write_reg(Register::A7, sp + 4);
cpu.write_reg(Register::D0, 0);
}
// DMSetMainDisplay(GDHandle newMainDevice, Handle displayState) -> OSErr.
0x0410 => {
let new_main = bus.read_long(sp + 4);
if new_main != 0 {
self.main_gdevice_handle = new_main;
self.current_gdevice
.with_mut(|current_gdevice| *current_gdevice = new_main);
bus.write_long(0x08A4, new_main); // MainDevice
bus.write_long(0x0CC8, new_main);
}
bus.write_word(sp + 8, 0);
cpu.write_reg(Register::A7, sp + 8);
cpu.write_reg(Register::D0, 0);
}
// DMSetDisplayMode(GDHandle, UInt32 mode, UInt32 *depthMode,
// UInt32 reserved, Handle displayState) -> OSErr.
// Abuse uses this after accepting the 640x480/256-colour
// switch dialog. The single-screen HLE keeps the active
// framebuffer, writes the selected device mode to depthMode
// for nonzero requests, and routes mode 0 through the
// BasiliskII rejection path that leaves depthMode alone,
// keeps the main GDevice gdMode unchanged, and does not
// run the framebuffer-reset helper.
0x0A11 => {
let depth_mode_ptr = bus.read_long(sp + 8);
let mode = bus.read_long(sp + 12);
let gdh = bus.read_long(sp + 16);
let gd = if gdh != 0 { bus.read_long(gdh) } else { 0 };
let result = if mode == 0 || self.display_mode_geometry(mode).is_none() {
DM_SET_DISPLAY_MODE_REJECT_ERR
} else {
let (width, height) = self
.display_mode_geometry(mode)
.expect("validated display mode has geometry");
let requested_depth = (depth_mode_ptr != 0)
.then(|| bus.read_long(depth_mode_ptr) as u16)
.and_then(crate::display::classic_pixel_size)
.unwrap_or(8);
if self.do_setdepth_with_geometry(
cpu,
bus,
requested_depth,
width,
height,
) {
let depth_mode = crate::display::classic_depth_mode(requested_depth)
.expect("validated display depth has a Video.h mode");
if depth_mode_ptr != 0 {
bus.write_long(depth_mode_ptr, u32::from(depth_mode));
}
if gd != 0 {
bus.write_long(gd + 42, u32::from(depth_mode));
}
0
} else {
-108i16 // memFullErr
}
};
bus.write_word(sp + 20, result as u16);
cpu.write_reg(Register::A7, sp + 20);
cpu.write_reg(Register::D0, result as i32 as u32);
}
// DMCheckDisplayMode(..., UInt32 *switchFlags, ..., Boolean *modeOk)
// -> OSErr. Single-screen model: every 8bpp-style request
// we expose is switchable now.
0x0C12 => {
let mode_ok_ptr = bus.read_long(sp);
let switch_flags_ptr = bus.read_long(sp + 8);
let depth_mode = bus.read_long(sp + 12) as u16;
let mode = bus.read_long(sp + 16);
let supported = self.display_mode_geometry(mode).is_some()
&& crate::display::classic_pixel_size(depth_mode).is_some();
if switch_flags_ptr != 0 {
bus.write_long(switch_flags_ptr, if supported { 1 } else { 2 });
}
if mode_ok_ptr != 0 {
bus.write_byte(mode_ok_ptr, u8::from(supported));
}
bus.write_word(sp + 24, 0);
cpu.write_reg(Register::A7, sp + 24);
cpu.write_reg(Register::D0, 0);
}
// DMGetDisplayMode(GDHandle theDevice, VDSwitchInfoPtr switchInfo)
// -> OSErr. VDSwitchInfoRec layout from Video.h:
// csMode.w, csData.l, csPage.w, csBaseAddr.l, csReserved.l.
// Video.h defines csMode as the active depth-mode token;
// csData is the separate timing/display-mode ID. Systemless
// returns its guest framebuffer base so callers that use
// the returned pointer stay inside emulated RAM.
0x043E => {
let switch_info = bus.read_long(sp);
let device_gdh = bus.read_long(sp + 4);
let gdh = if device_gdh != 0 {
device_gdh
} else {
self.ensure_main_gdevice(bus)
};
let gd = if gdh != 0 { bus.read_long(gdh) } else { 0 };
let current_depth_mode = if gd != 0 {
bus.read_long(gd + 42)
} else {
crate::display::classic_depth_mode(self.screen_mode.4)
.map(u32::from)
.unwrap_or(0)
};
if switch_info != 0 {
let mut screen_base = self.screen_mode.0;
if screen_base == 0 {
let gd = bus.read_long(gdh);
let pm_handle = bus.read_long(gd + 22);
let pm = bus.read_long(pm_handle);
screen_base = bus.read_long(pm);
self.screen_mode = (
screen_base,
REFERENCE_MACHINE_PROFILE.screen_row_bytes(),
REFERENCE_MACHINE_PROFILE.screen_width,
REFERENCE_MACHINE_PROFILE.screen_height,
REFERENCE_MACHINE_PROFILE.screen_depth,
);
}
bus.write_word(switch_info, current_depth_mode as u16);
bus.write_long(
switch_info + 2,
Self::display_mode_id_for_geometry(
self.screen_mode.2,
self.screen_mode.3,
),
);
bus.write_word(switch_info + 6, 0);
bus.write_long(switch_info + 8, screen_base);
bus.write_long(switch_info + 12, 0);
}
bus.write_word(sp + 8, 0);
cpu.write_reg(Register::A7, sp + 8);
cpu.write_reg(Register::D0, 0);
}
_ => {
let arg_bytes = u32::from((cpu.read_reg(Register::D0) as u16) >> 8) * 2;
if arg_bytes != 0 {
bus.write_word(sp + arg_bytes, (-50i16) as u16); // paramErr
cpu.write_reg(Register::A7, sp + arg_bytes);
} else {
cpu.write_reg(Register::A7, sp + 2);
}
}
}
Ok(())
}
// _StdOpcodeProc / StdOpcode ($ABF8).
// void StdOpcode(const Rect *fromRect, const Rect *toRect, UInt16 opcode, SInt16 version).
// Pascal void frame: fromRect(4) + toRect(4) + opcode(2) + version(2) = 12 bytes; no result.
// Universal Interfaces 3.4 Quickdraw.h:632,4243-4247; Traps.h:938.
(true, 0x3F8) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 12);
Ok(())
}
// ========== Stubs — Miscellaneous ==========
// GetCWMgrPort ($AA48)
// Returns the Window Manager's CGrafPort in the VAR parameter.
// On Color QuickDraw systems the Window Manager port is the
// CGrafPort-backed WMgrCPort; this HLE returns a separate
// color-port clone so callers do not alias the low-memory
// WMgrPort record.
// PROCEDURE GetCWMgrPort(VAR wMgrCPort: CGrafPtr);
// Macintosh Toolbox Essentials (1992), pp. 4-113 to 4-114.
// Stack: SP+0: wMgrCPort_ptr(4). Pop 4.
//
// Contract coverage:
// quickdraw::tests::getcwmgrport_writes_wmgrcport_pointer_and_consumes_argument
// quickdraw::tests::getcwmgrport_nil_var_pointer_is_safe_and_still_pops_argument
// GetCWMgrPort ($AA48): Writes the color Window Manager port clone via VAR ptr.
(true, 0x248) => {
let sp = cpu.read_reg(Register::A7);
let var_ptr = bus.read_long(sp);
if var_ptr != 0 {
let wmgr_port = self.ensure_color_window_manager_port(bus);
bus.write_long(var_ptr, wmgr_port);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// UpdatePixMap ($AA38)
// Updates a PixMap in place after the underlying ColorTable changes.
// The legacy ROM patch is effectively a no-op RTS; only the
// caller-observable wrapper behaviour is modelled.
// PROCEDURE UpdatePixMap(pmHandle: PixMapHandle);
// Inside Macintosh Volume V, V-58
// Stack: SP+0: pmHandle(4). Leave A7 unchanged.
// UpdatePixMap ($AA38): no PixMap contents are mutated in HLE.
(true, 0x238) => Ok(()),
// Unimplemented ($A89F)
// Vector reached when an unimplemented trap is called. No-op stub —
// callers expect no stack adjustment.
// Inside Macintosh Volume I, I-89
// Unimplemented ($A89F): Vector for unimplemented traps; returns
// noErr with no stack adjustment so probes that compare against
// this address don't crash per IM:I I-89
(true, 0x09F) => {
cpu.write_reg(Register::D0, 0);
Ok(())
}
// Layout ($A8F7)
// The January 1997 Mac OS SDK's Traps.h names this slot `_Layout`
// at line 216. Older trap tables list A8F7 as RESERVED, but
// BasiliskII returns D0 = -64 here, so Systemless mirrors that
// behavior.
(true, 0x0F7) => {
cpu.write_reg(Register::D0, (-64i32) as u32);
Ok(())
}
// ========== More Stubs ==========
// ScrnBitMap ($A833)
// Return the current screen BitMap record.
//
// FUNCTION ScrnBitMap: BitMap; $A833
//
// Per IM:IV IV-21 "ScrnBitMap is a low-level routine that
// returns the current screen BitMap record." Per IM:I I-163
// QuickDraw's `screenBits` global describes the entire
// active screen with baseAddr pointing at the screen's
// frame buffer, rowBytes giving the byte stride per row,
// and bounds = (0, 0, screen_height, screen_width).
//
// MPW Universal Headers do NOT expose ScrnBitMap as an
// ordinary FUNCTION declaration because normal Pascal/C
// code reads `screenBits` (a QuickDraw global) directly
// rather than invoking the trap. Callers that DO use the
// trap declare an inline-A-line thunk:
//
// pascal void kx_ScrnBitMap(BitMap *bm) = { 0xA833 };
//
// Pascal FUNCTION-result-by-structure stack layout:
// sp+0..3 result_ptr (Ptr to caller-allocated 14-byte
// BitMap, shallowest = pushed last)
// 4-byte arg pop, no separate result slot (the trap writes
// through result_ptr). No registers consumed.
//
// BitMap record (14 bytes) written by ScrnBitMap:
// offset 0..3 baseAddr Ptr to screen frame buffer
// offset 4..5 rowBytes bytes per row (high bit clear
// for 1bpp BitMap, set for PixMap)
// offset 6..7 bounds.top (0)
// offset 8..9 bounds.left (0)
// offset 10..11 bounds.bottom (screen height)
// offset 12..13 bounds.right (screen width)
//
// Systemless HLE reads dispatcher `screen_mode = (base, row,
// width, height, depth)` and writes those values into the
// caller-provided buffer. BII reads the System 7.5
// QuickDraw globals and writes its own baseAddr/rowBytes
// pair. Both engines agree on the bounds and the 4-byte
// stack pop, and both overwrite the caller's baseAddr/rowBytes
// fields (they are not left at any sentinel value).
//
// Contract-test coverage in this file (mod tests):
// quickdraw::tests::scrnbitmap_writes_current_screen_bitmap_record_to_result_pointer
// quickdraw::tests::scrnbitmap_overwrites_pre_poisoned_sentinel_fields_with_screen_bitmap_record
// quickdraw::tests::scrnbitmap_consumes_result_pointer_argument_and_pops_4_bytes
// ScrnBitMap ($A833): Writes the current screen `BitMap` record from dispatcher `screen_mode` into the caller-provided result buffer; 14-byte BitMap layout per IM:IV IV-21 + IM:I I-163
(true, 0x033) => {
let sp = cpu.read_reg(Register::A7);
let result_ptr = bus.read_long(sp);
let (base_addr, row_bytes, width, height, _) = self.screen_mode;
if result_ptr != 0 {
bus.write_long(result_ptr, base_addr);
bus.write_word(result_ptr + 4, row_bytes as u16);
bus.write_word(result_ptr + 6, 0);
bus.write_word(result_ptr + 8, 0);
bus.write_word(result_ptr + 10, height);
bus.write_word(result_ptr + 12, width);
}
cpu.write_reg(Register::A7, sp + 4);
Ok(())
}
// CalcMask ($A838)
// PROCEDURE CalcMask (srcPtr, dstPtr: Ptr;
// srcRow, dstRow, height, words: INTEGER);
// Inside Macintosh Volume IV (1986), p. IV-22:
// "Given a source bit image, CalcMask computes a destination
// bit image with 1's only in the pixels where paint could not
// leak from any of the outer edges, like the MacPaint lasso
// tool. Calls to CalcMask are not clipped to the current
// port and are not stored into QuickDraw pictures."
//
// MPW Universal Headers (Quickdraw.h):
// EXTERN_API(void) CalcMask(const void *srcPtr, void *dstPtr,
// short srcRow, short dstRow,
// short height, short words)
// ONEWORDINLINE(0xA838);
//
// Pascal LR push order (first arg deepest):
// sp+0..1 words (last pushed → shallowest)
// sp+2..3 height
// sp+4..5 dstRow
// sp+6..7 srcRow
// sp+8..11 dstPtr
// sp+12..15 srcPtr (first pushed → deepest)
// 16-byte total pop, no result slot (PROCEDURE).
//
// BII-vs-Systemless divergence: BII System 7.5.3 ROM walks the src
// bit image and writes the lasso-style mask into dst per IM:IV
// IV-22. Systemless HLE is a no-op stub because masks are not
// modeled at the QuickDraw bottleneck-proc layer (high-level
// CopyMask reads/writes the bitmap directly via Rust code).
// The only shared, verifiable behaviour is the 16-byte pop
// discipline; IM:IV IV-22 explicitly disclaims clipping, so
// the src/dst mask contents are not comparable.
//
// Contract-test coverage in this file (mod tests):
// src/trap/quickdraw.rs::tests::calcmask_consumes_16_byte_argument_frame
// src/trap/quickdraw.rs::tests::calcmask_five_call_composition_pops_eighty_bytes_total
(true, 0x038) => {
let sp = cpu.read_reg(Register::A7);
cpu.write_reg(Register::A7, sp + 16);
Ok(())
}
// SeedFill ($A839)
// PROCEDURE SeedFill (srcPtr, dstPtr: Ptr;
// srcRow, dstRow, height, words,
// seedH, seedV: INTEGER);
// Inside Macintosh Volume IV (1986), p. IV-22:
// "Given a source bit image, SeedFill computes a destination
// bit image with 1's only in the pixels where paint can leak
// from the starting seed point, like the MacPaint paint-
// bucket tool. SeedH and seedV specify horizontal and
// vertical offsets, in pixels, from the beginning of the
// data pointed to by dstPtr, determining how far into the
// destination bit image filling should begin. Calls to
// SeedFill are not clipped to the current port and are not
// stored into QuickDraw pictures."
//
// MPW Universal Headers (Quickdraw.h):
// EXTERN_API(void) SeedFill(const void *srcPtr, void *dstPtr,
// short srcRow, short dstRow,
// short height, short words,
// short seedH, short seedV)
// ONEWORDINLINE(0xA839);
//
// Pascal LR push order (first arg deepest):
// sp+0..1 seedV (last pushed → shallowest)
// sp+2..3 seedH
// sp+4..5 words
// sp+6..7 height
// sp+8..9 dstRow
// sp+10..11 srcRow
// sp+12..15 dstPtr
// sp+16..19 srcPtr (first pushed → deepest)
// 20-byte total pop, no result slot (PROCEDURE).
//
// Systemless implements the default 1-bit paint-bucket mask:
// contiguous pixels equal to the source seed bit are written as
// 1s in dst, with all other bits in the requested rectangle
// cleared. The call is raw-bitmap based, not port clipped.
//
// Contract-test coverage in this file (mod tests):
// src/trap/quickdraw.rs::tests::seedfill_consumes_20_byte_argument_frame
// src/trap/quickdraw.rs::tests::seedfill_five_call_composition_pops_one_hundred_bytes_total
// src/trap/quickdraw.rs::tests::seedfill_writes_contiguous_matching_region_mask
// src/trap/quickdraw.rs::tests::seedfill_seed_outside_rect_clears_destination_mask
(true, 0x039) => {
let sp = cpu.read_reg(Register::A7);
let seed_v = bus.read_word(sp) as i16;
let seed_h = bus.read_word(sp + 2) as i16;
let words = bus.read_word(sp + 4) as i16;
let height = bus.read_word(sp + 6) as i16;
let dst_row = bus.read_word(sp + 8) as i16;
let src_row = bus.read_word(sp + 10) as i16;
let dst_ptr = bus.read_long(sp + 12);
let src_ptr = bus.read_long(sp + 16);
Self::seed_fill_1bpp_mask(
bus, src_ptr, dst_ptr, src_row, dst_row, height, words, seed_h, seed_v,
);
cpu.write_reg(Register::A7, sp + 20);
Ok(())
}
// AnimateEntry ($AA99)
// Changes the RGB value of dstEntry in the palette associated
// with dstWindow to srcRGB. Any device indexes reserved for
// the entry are updated immediately (via activate_palette_for_
// window). Single-entry variant of AnimatePalette.
// PROCEDURE AnimateEntry(dstWindow: WindowPtr; dstEntry: INTEGER;
// srcRGB: RGBColor);
// Inside Macintosh Volume V, V-159
// Stack: SP+0: srcRGB_ptr(4), SP+4: dstEntry(2), SP+6: dstWindow(4). Pops 10.
// AnimateEntry ($AA99): Writes the supplied RGB to the window's palette ColorInfo (preserving usage/tolerance) then calls activate_palette_for_window; out-of-range or missing-palette is a no-op, IM:V V-159
(true, 0x299) => {
let sp = cpu.read_reg(Register::A7);
let src_rgb_ptr = bus.read_long(sp);
let dst_entry = bus.read_word(sp + 4) as i16;
let window = bus.read_long(sp + 6);
cpu.write_reg(Register::A7, sp + 10);
if src_rgb_ptr == 0 || dst_entry < 0 {
return Some(Ok(()));
}
let palette = self.window_palette_handle(window);
let palette_ptr = Self::palette_ptr(bus, palette);
if palette_ptr == 0 {
return Some(Ok(()));
}
let entries = Self::palette_entry_count(bus, palette);
if (dst_entry as u16) >= entries {
return Some(Ok(()));
}
let rgb = [
bus.read_word(src_rgb_ptr),
bus.read_word(src_rgb_ptr + 2),
bus.read_word(src_rgb_ptr + 4),
];
let (_, usage, tolerance) = Self::read_palette_color_info(
bus,
palette,
dst_entry as u16,
)
.unwrap_or(([0, 0, 0], PM_TOLERANT, 0));
Self::write_palette_color_info(
bus,
palette_ptr,
dst_entry as u32,
rgb,
usage,
tolerance,
);
self.install_animated_palette_entry_on_active_device(
bus,
window,
palette,
dst_entry as u32,
rgb,
usage,
);
self.activate_associated_palette_for_window(bus, window);
Ok(())
}
_ => return None,
})
}
/// OpenCPort-specific allocation for CGrafPort-owned storage.
/// Imaging With QuickDraw 1994 pp. 4-64 to 4-65:
/// OpenCPort allocates storage, then calls InitCPort.
fn allocate_cport_storage(&mut self, port: u32, bus: &mut MacMemoryBus) {
let gd_handle = self.active_gdevice_or_main(bus);
let gd_ptr = bus.read_long(gd_handle);
// Read GDevice rect for region initialization.
let gd_top = bus.read_word(gd_ptr + 34) as i16;
let gd_left = bus.read_word(gd_ptr + 36) as i16;
let gd_bottom = bus.read_word(gd_ptr + 38) as i16;
let gd_right = bus.read_word(gd_ptr + 40) as i16;
// Read GDevice's PixMap to seed the newly allocated port PixMap.
let gd_pmap_handle = bus.read_long(gd_ptr + 22);
let gd_pmap = bus.read_long(gd_pmap_handle);
// Allocate a new PixMap, copying fields from the GDevice's PixMap.
let pixmap = bus.alloc(50);
for i in 0..50u32 {
bus.write_byte(pixmap + i, bus.read_byte(gd_pmap + i));
}
let pixmap_handle = bus.alloc(4);
bus.write_long(pixmap_handle, pixmap);
self.cache_portbits_pixmap_handle(bus, port + 2, pixmap_handle);
// Allocate visRgn = GDevice rect
let vis_rgn_ptr = bus.alloc(10);
bus.write_word(vis_rgn_ptr, 10); // rgnSize
bus.write_word(vis_rgn_ptr + 2, gd_top as u16);
bus.write_word(vis_rgn_ptr + 4, gd_left as u16);
bus.write_word(vis_rgn_ptr + 6, gd_bottom as u16);
bus.write_word(vis_rgn_ptr + 8, gd_right as u16);
let vis_rgn = bus.alloc(4);
bus.write_long(vis_rgn, vis_rgn_ptr);
// Allocate clipRgn = infinite rect (-32767..32767)
let clip_rgn_ptr = bus.alloc(10);
bus.write_word(clip_rgn_ptr, 10);
bus.write_word(clip_rgn_ptr + 2, (-32767_i16) as u16);
bus.write_word(clip_rgn_ptr + 4, (-32767_i16) as u16);
bus.write_word(clip_rgn_ptr + 6, 32767_u16);
bus.write_word(clip_rgn_ptr + 8, 32767_u16);
let clip_rgn = bus.alloc(4);
bus.write_long(clip_rgn, clip_rgn_ptr);
// Mark as CGrafPort and install allocated handles.
bus.write_word(port + 6, 0xC000); // +6 portVersion high bits set
bus.write_long(port + 2, pixmap_handle); // +2 portPixMap
bus.write_long(port + 24, vis_rgn); // +24 visRgn
bus.write_long(port + 28, clip_rgn); // +28 clipRgn
}
/// Initialize an existing CGrafPort with default values.
/// Imaging With QuickDraw 1994 p. 4-66:
/// InitCPort does not allocate storage and no-ops on non-CGrafPorts.
fn init_cport(
&mut self,
port: u32,
bus: &mut MacMemoryBus,
allow_seeded_clut_clone: bool,
) -> bool {
if (bus.read_word(port + 6) & 0xC000) != 0xC000 {
return false;
}
let pixmap_handle = bus.read_long(port + 2);
let vis_rgn = bus.read_long(port + 24);
let clip_rgn = bus.read_long(port + 28);
if pixmap_handle == 0 || vis_rgn == 0 || clip_rgn == 0 {
return false;
}
let pixmap = bus.read_long(pixmap_handle);
let vis_rgn_ptr = bus.read_long(vis_rgn);
let clip_rgn_ptr = bus.read_long(clip_rgn);
if pixmap == 0 || vis_rgn_ptr == 0 || clip_rgn_ptr == 0 {
return false;
}
let gd_handle = self.active_gdevice_or_main(bus);
let gd_ptr = bus.read_long(gd_handle);
// Read GDevice rect for portRect and visRgn.
let gd_top = bus.read_word(gd_ptr + 34) as i16;
let gd_left = bus.read_word(gd_ptr + 36) as i16;
let gd_bottom = bus.read_word(gd_ptr + 38) as i16;
let gd_right = bus.read_word(gd_ptr + 40) as i16;
// Copy the current device PixMap into the existing port PixMap.
let gd_pmap_handle = bus.read_long(gd_ptr + 22);
let gd_pmap = bus.read_long(gd_pmap_handle);
for i in 0..50u32 {
bus.write_byte(pixmap + i, bus.read_byte(gd_pmap + i));
}
if allow_seeded_clut_clone {
if let Some(clut) = self.active_seeded_screen_clut_for_offscreen_clone(gd_handle, 0) {
let depth = bus.read_word(pixmap + 32) as u32;
let ctab_handle =
self.allocate_color_table_handle_with_clut(bus, depth, &clut, 0x8000);
bus.write_long(pixmap + 42, ctab_handle);
}
}
// Reinitialize visRgn to the current-device bounds.
bus.write_word(vis_rgn_ptr, 10);
bus.write_word(vis_rgn_ptr + 2, gd_top as u16);
bus.write_word(vis_rgn_ptr + 4, gd_left as u16);
bus.write_word(vis_rgn_ptr + 6, gd_bottom as u16);
bus.write_word(vis_rgn_ptr + 8, gd_right as u16);
// Reinitialize clipRgn to QuickDraw's infinite rectangle.
bus.write_word(clip_rgn_ptr, 10);
bus.write_word(clip_rgn_ptr + 2, (-32767_i16) as u16);
bus.write_word(clip_rgn_ptr + 4, (-32767_i16) as u16);
bus.write_word(clip_rgn_ptr + 6, 32767_u16);
bus.write_word(clip_rgn_ptr + 8, 32767_u16);
// CGrafPort field layout per Imaging With QuickDraw 1994, 4-125.
bus.write_word(port, 0); // +0 device
bus.write_long(port + 2, pixmap_handle); // +2 portPixMap (handle)
bus.write_word(port + 6, 0xC000); // +6 portVersion
bus.write_long(port + 8, 0); // +8 grafVars (handle) - not modeled yet
bus.write_word(port + 12, 0); // +12 chExtra
bus.write_word(port + 14, 0x8000); // +14 pnLocHFrac (0.5 fixed)
// portRect = GDevice rect
bus.write_word(port + 16, gd_top as u16); // +16 portRect.top
bus.write_word(port + 18, gd_left as u16); // +18 portRect.left
bus.write_word(port + 20, gd_bottom as u16); // +20 portRect.bottom
bus.write_word(port + 22, gd_right as u16); // +22 portRect.right
self.cache_portbits_pixmap_handle(bus, port + 2, pixmap_handle);
bus.write_long(port + 24, vis_rgn); // +24 visRgn
bus.write_long(port + 28, clip_rgn); // +28 clipRgn
self.init_cgraf_port_defaults(port, bus);
true
}
fn active_gdevice_or_main(&mut self, bus: &mut MacMemoryBus) -> u32 {
if Self::gdevice_pixmap_handle(bus, *self.current_gdevice) != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
}
}
fn normalized_itable_resolution(bus: &MacMemoryBus, gdh: u32, requested_res: u16) -> u16 {
let device_res = if requested_res == 0 && gdh != 0 {
let gd = bus.read_long(gdh);
if gd != 0 {
bus.read_word(gd + 10)
} else {
0
}
} else {
requested_res
};
if (3..=5).contains(&device_res) {
device_res
} else {
4
}
}
fn inverse_table_byte_count(res: u16) -> usize {
1usize << (usize::from(res) * 3)
}
fn build_inverse_table_bytes(clut: &[[u16; 3]; 256], res: u16) -> Vec<u8> {
if res == 4 && Self::uses_standard_mac_4bpp_gworld_clut(clut) {
return Self::standard_mac_4bpp_gworld_itable().to_vec();
}
if res == 4 && Self::uses_canonical_system_8bpp_clut(clut) {
return Self::standard_mac_8bpp_itable().to_vec();
}
let entries = Self::inverse_table_byte_count(res);
let mut table = vec![0u8; entries];
let res_bits = u32::from(res);
let mask = (1u32 << res_bits) - 1;
let shift = 16u32 - res_bits;
let centre = 1u32 << (15u32 - res_bits);
for cell in 0u32..entries as u32 {
let qb = cell & mask;
let qg = (cell >> res_bits) & mask;
let qr = (cell >> (res_bits * 2)) & mask;
let cr = ((qr << shift) | centre) as i64;
let cg = ((qg << shift) | centre) as i64;
let cb = ((qb << shift) | centre) as i64;
let mut best_idx = 0u8;
let mut best_dist = i64::MAX;
for (idx, entry) in clut.iter().enumerate() {
let dr = cr - i64::from(entry[0]);
let dg = cg - i64::from(entry[1]);
let db = cb - i64::from(entry[2]);
let dist = dr * dr + dg * dg + db * db;
if dist < best_dist {
best_dist = dist;
best_idx = idx as u8;
}
}
table[cell as usize] = best_idx;
}
table
}
fn cached_inverse_table_bytes(&mut self, clut: &[[u16; 3]; 256], res: u16) -> Vec<u8> {
if let Some(pos) = self
.inverse_table_cache
.iter()
.position(|entry| entry.res == res && entry.clut == *clut)
{
let entry = self.inverse_table_cache.remove(pos);
let bytes = entry.bytes.clone();
self.inverse_table_cache.push(entry);
return bytes;
}
let bytes = Self::build_inverse_table_bytes(clut, res);
self.inverse_table_cache.push(InverseTableCacheEntry {
res,
clut: *clut,
bytes: bytes.clone(),
});
if self.inverse_table_cache.len() > INVERSE_TABLE_CACHE_LIMIT {
self.inverse_table_cache.remove(0);
}
bytes
}
fn usable_itable_handle(bus: &mut MacMemoryBus, handle: u32) -> u32 {
if handle == 0 || bus.get_alloc_size(handle).is_none() {
return 0;
}
let ptr = bus.read_long(handle);
if ptr != 0 {
if bus.get_alloc_size(ptr).is_some() {
return handle;
}
return 0;
}
let ptr = bus.alloc(0);
bus.write_long(handle, ptr);
handle
}
fn ensure_gdevice_itable_handle(bus: &mut MacMemoryBus, gdh: u32) -> u32 {
if gdh == 0 {
return 0;
}
let gd = bus.read_long(gdh);
if gd == 0 {
return 0;
}
let existing = bus.read_long(gd + 6);
if Self::usable_itable_handle(bus, existing) != 0 {
return existing;
}
let ptr = bus.alloc(0);
let handle = bus.alloc(4);
bus.write_long(handle, ptr);
bus.write_long(gd + 6, handle);
handle
}
fn make_inverse_table(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
itab_handle: u32,
requested_res: u16,
) {
let mut current_gdh = 0;
let target_handle = if itab_handle != 0 {
Self::usable_itable_handle(bus, itab_handle)
} else {
current_gdh = self.active_gdevice_or_main(bus);
Self::ensure_gdevice_itable_handle(bus, current_gdh)
};
if target_handle == 0 {
return;
}
let explicit_ctab = Self::color_table_ptr(bus, ctab_handle) != 0;
if !explicit_ctab || requested_res == 0 {
current_gdh = self.active_gdevice_or_main(bus);
}
let effective_ctab_handle = if explicit_ctab {
ctab_handle
} else {
Self::gdevice_ctab_handle(bus, current_gdh)
};
let clut = self.read_ctab_handle_clut(bus, effective_ctab_handle);
let seed = Self::ctab_seed(bus, effective_ctab_handle).unwrap_or(0);
let res = Self::normalized_itable_resolution(bus, current_gdh, requested_res);
let table = self.cached_inverse_table_bytes(&clut, res);
let record_size = 6 + table.len() as u32;
let mut ptr = bus.read_long(target_handle);
if ptr == 0 {
ptr = bus.alloc(record_size);
bus.write_long(target_handle, ptr);
} else {
ptr = self.resize_handle_allocation(bus, target_handle, record_size);
}
if ptr == 0 {
return;
}
bus.write_long(ptr, seed);
bus.write_word(ptr + 4, res);
bus.write_bytes(ptr + 6, &table);
}
fn extend_recording_bbox(
recording: &mut super::dispatch::RegionRecording,
top: i16,
left: i16,
bottom: i16,
right: i16,
) {
recording.bbox = Some(match recording.bbox {
Some((current_top, current_left, current_bottom, current_right)) => (
current_top.min(top),
current_left.min(left),
current_bottom.max(bottom),
current_right.max(right),
),
None => (top, left, bottom, right),
});
}
fn add_recording_rows(
recording: &mut super::dispatch::RegionRecording,
rows_top: i16,
rows: &[Vec<i16>],
) {
for (row_index, row) in rows.iter().enumerate() {
if row.is_empty() {
continue;
}
let y = rows_top + row_index as i16;
let left = row[0];
let right = *row.last().unwrap();
let current = recording.filled_rows.entry(y).or_default();
*current = Self::union_region_rows(current, row);
Self::extend_recording_bbox(recording, y, left, y + 1, right);
}
}
fn record_region_rect_boundary(
recording: &mut super::dispatch::RegionRecording,
top: i16,
left: i16,
bottom: i16,
right: i16,
) {
if bottom <= top || right <= left {
return;
}
recording.outline_segments.extend([
((top, left), (top, right)),
((top, right), (bottom, right)),
((bottom, right), (bottom, left)),
((bottom, left), (top, left)),
]);
Self::extend_recording_bbox(recording, top, left, bottom, right);
}
/// While OpenRgn..CloseRgn is in progress, rectangular drawing
/// primitives contribute their mathematical boundary and skip the actual
/// framebuffer write. Returns true if recording is active.
pub(crate) fn extend_recording_region(
&mut self,
top: i16,
left: i16,
bottom: i16,
right: i16,
) -> bool {
if let Some(recording) = self.recording_region.as_mut() {
Self::record_region_rect_boundary(recording, top, left, bottom, right);
true
} else {
false
}
}
/// Add exact scanline boundaries for a framed QuickDraw shape to the
/// active region. Each span is recorded as a one-row closed loop, which
/// preserves QuickDraw's even-odd boundary organization while avoiding a
/// lossy bounding-box substitution for curved shapes.
fn extend_recording_region_from_spans(&mut self, top: i16, spans: &[(i16, i16)]) -> bool {
let Some(recording) = self.recording_region.as_mut() else {
return false;
};
for (row_index, &(left, right)) in spans.iter().enumerate() {
if right <= left {
continue;
}
let Ok(row_offset) = i16::try_from(row_index) else {
break;
};
let y = top.saturating_add(row_offset);
Self::record_region_rect_boundary(recording, y, left, y.saturating_add(1), right);
}
true
}
pub(crate) fn record_region_line(&mut self, v0: i16, h0: i16, v1: i16, h1: i16) -> bool {
if let Some(recording) = self.recording_region.as_mut() {
recording.outline_segments.push(((v0, h0), (v1, h1)));
Self::extend_recording_bbox(recording, v0.min(v1), h0.min(h1), v0.max(v1), h0.max(h1));
true
} else {
false
}
}
/// Dereference a PolyHandle and add its actual boundary to the open
/// region. Recording only the polyBBox is not equivalent: concave
/// polygons (for example, a starburst) would turn into solid rectangles
/// and overwrite unrelated drawing when the resulting region is painted.
/// NIL handles and empty polygons still report the recording state so the
/// caller uses pen visibility to decide whether drawing is visible.
pub(crate) fn extend_recording_region_from_poly(
&mut self,
bus: &mut MacMemoryBus,
poly_handle: u32,
) -> bool {
if self.recording_region.is_none() {
return false;
}
if poly_handle == 0 {
return true;
}
let poly_ptr = bus.read_long(poly_handle);
if poly_ptr == 0 {
return true;
}
let vertices = self.read_poly_vertices(bus, poly_handle);
if vertices.len() >= 2 {
let recording = self.recording_region.as_mut().unwrap();
for index in 0..vertices.len() {
let start = vertices[index];
let end = vertices[(index + 1) % vertices.len()];
if start != end {
recording.outline_segments.push((start, end));
}
}
let (mut top, mut left) = vertices[0];
let (mut bottom, mut right) = vertices[0];
for &(v, h) in &vertices[1..] {
top = top.min(v);
left = left.min(h);
bottom = bottom.max(v);
right = right.max(h);
}
Self::extend_recording_bbox(recording, top, left, bottom, right);
}
true
}
/// Dereference a RgnHandle and extend the recording region by the
/// region's stored bbox (4 words at rgn_ptr+2). NIL handles and empty
/// regions just report the recording state without mutating the bbox.
/// Returns true if recording is active (caller should skip the draw).
pub(crate) fn extend_recording_region_from_rgn(
&mut self,
bus: &mut MacMemoryBus,
rgn_handle: u32,
) -> bool {
if self.recording_region.is_none() {
return false;
}
let Some((top, left, bottom, right)) = Self::region_bbox(bus, rgn_handle) else {
return true;
};
if bottom <= top || right <= left {
return true;
}
let rows = Self::region_rows_for_band(bus, rgn_handle, top, bottom);
if let Some(recording) = self.recording_region.as_mut() {
Self::add_recording_rows(recording, top, &rows);
}
true
}
pub(crate) fn init_cgraf_port_defaults(&mut self, port: u32, bus: &mut MacMemoryBus) {
bus.write_long(port + 32, 0); // +32 bkPixPat
// rgbFgColor = black (0,0,0)
bus.write_word(port + 36, 0); // +36 rgbFgColor.red
bus.write_word(port + 38, 0); // +38 rgbFgColor.green
bus.write_word(port + 40, 0); // +40 rgbFgColor.blue
// rgbBkColor = white (0xFFFF, 0xFFFF, 0xFFFF)
bus.write_word(port + 42, 0xFFFF); // +42 rgbBkColor.red
bus.write_word(port + 44, 0xFFFF); // +44 rgbBkColor.green
bus.write_word(port + 46, 0xFFFF); // +46 rgbBkColor.blue
// pnLoc = (0,0)
bus.write_word(port + 48, 0); // +48 pnLoc.v
bus.write_word(port + 50, 0); // +50 pnLoc.h
// pnSize = (1,1)
bus.write_word(port + 52, 1); // +52 pnSize.v
bus.write_word(port + 54, 1); // +54 pnSize.h
bus.write_word(port + 56, 8); // +56 pnMode (patCopy)
bus.write_long(port + 58, 0); // +58 pnPixPat
bus.write_long(port + 62, 0); // +62 fillPixPat
bus.write_word(port + 66, 0); // +66 pnVis
bus.write_word(port + 68, 0); // +68 txFont
bus.write_word(port + 70, 0); // +70 txFace
bus.write_word(port + 72, 1); // +72 txMode (srcOr)
bus.write_word(port + 74, 0); // +74 txSize
bus.write_long(port + 76, 0); // +76 spExtra
bus.write_long(port + 80, 0x00000021); // +80 fgColor (blackColor=33)
bus.write_long(port + 84, 0x0000001E); // +84 bkColor (whiteColor=30)
bus.write_word(port + 88, 0); // +88 colrBit
bus.write_word(port + 90, 0); // +90 patStretch
bus.write_long(port + 92, 0); // +92 picSave
bus.write_long(port + 96, 0); // +96 rgnSave
bus.write_long(port + 100, 0); // +100 polySave
bus.write_long(port + 104, 0); // +104 grafProcs
self.quickdraw_hilite_colors
.remove_quickdraw_hilite_color(port);
self.port_draw_states.insert(port, PortDrawState::default());
}
/// Allocate the main GDevice in guest memory if not yet done.
pub fn ensure_main_gdevice(&mut self, bus: &mut MacMemoryBus) -> u32 {
if self.main_gdevice_handle != 0 {
return self.main_gdevice_handle;
}
let (screen_base, row_bytes, screen_width, screen_height, screen_depth) = self.screen_mode;
let direct = matches!(screen_depth, 16 | 32);
let (screen_clut, color_count) = if direct {
([[0; 3]; 256], 1)
} else {
Self::standard_mac_indexed_clut(screen_depth)
.expect("main screen uses a supported depth")
};
// Allocate the screen's indexed ColorTable.
// ColorTable record: ctSeed(4) + ctFlags(2) + ctSize(2) + ctTable(n*8)
// Inside Macintosh Volume V, V-48, V-135
let ct_size: u32 = 8 + color_count as u32 * 8;
let ctab = bus.alloc(ct_size);
// Executor's C_NewGWorld (qGWorld.cpp:217) initialises the
// GDevice-backing CTab with `CTAB_SEED(ctab) = (int32_t)depth`
// — a deterministic seed that matches the authoring convention
// games use for PICTs targeting the standard N-bpp palette.
// EV's landing PICT (and most other canonical-palette PICTs)
// ship with ctSeed=8 (depth). Initialising here with 8 lets the
// PICT seed-match identity gate fire without remap on
// those authored-for-standard PICTs.
// A direct PixMap uses a one-entry dummy table; QD13 initializes its
// seed to the number of meaningful component bits. GDevice tables keep
// the device flag even when the pixels themselves are direct RGB.
let seed = match screen_depth {
16 => 15,
32 => 24,
_ => screen_depth,
};
bus.write_long(ctab, u32::from(seed));
bus.write_word(ctab + 4, 0x8000); // ctFlags (+4, 2 bytes): bit 15 = device color table
bus.write_word(ctab + 6, color_count as u16 - 1); // ctSize: entries - 1
for i in 0..color_count as u32 {
let entry = ctab + 8 + i * 8;
// The standard 8-bit device table's auxiliary primary and gray
// ramps are explicit device-index colors. Lower-depth standard
// tables contain no auxiliary explicit range.
// Inside Macintosh Volume V (1986), pp. V-157..V-160;
// Imaging With QuickDraw (1994), Table 4-6, p. 4-93.
let usage = if screen_depth == 8 && (215..=254).contains(&i) {
(PM_EXPLICIT as u16) << 8
} else {
0
};
bus.write_word(entry, usage); // client ID plus Palette Manager usage
bus.write_word(entry + 2, screen_clut[i as usize][0]);
bus.write_word(entry + 4, screen_clut[i as usize][1]);
bus.write_word(entry + 6, screen_clut[i as usize][2]);
}
let ctab_handle = bus.alloc(4);
bus.write_long(ctab_handle, ctab);
// Allocate the main screen PixMap.
// PixMap record: Imaging With QuickDraw 1994, p.4-5
let pixmap = bus.alloc(50);
bus.write_long(pixmap, screen_base); // baseAddr (+0)
bus.write_word(pixmap + 4, (row_bytes as u16) | 0x8000);
bus.write_word(pixmap + 6, 0); // bounds.top (+6)
bus.write_word(pixmap + 8, 0); // bounds.left (+8)
bus.write_word(pixmap + 10, screen_height);
bus.write_word(pixmap + 12, screen_width);
bus.write_word(pixmap + 14, 0); // pmVersion (+14)
bus.write_word(pixmap + 16, 0); // packType (+16)
bus.write_long(pixmap + 18, 0); // packSize (+18)
bus.write_long(pixmap + 22, 0x00480000); // hRes (+22) = 72.0 fixed
bus.write_long(pixmap + 26, 0x00480000); // vRes (+26) = 72.0 fixed
let (pixel_type, component_count, component_size) = match screen_depth {
16 => (16, 3, 5),
32 => (16, 3, 8),
_ => (0, 1, screen_depth),
};
bus.write_word(pixmap + 30, pixel_type);
bus.write_word(pixmap + 32, screen_depth);
bus.write_word(pixmap + 34, component_count);
bus.write_word(pixmap + 36, component_size);
bus.write_long(pixmap + 38, 0); // planeBytes (+38)
bus.write_long(pixmap + 42, ctab_handle); // pmTable (+42) = CTabHandle
bus.write_long(pixmap + 46, 0); // pmReserved (+46)
let pixmap_handle = bus.alloc(4);
bus.write_long(pixmap_handle, pixmap);
// Allocate GDevice record (50 bytes)
let gd = bus.alloc(50);
bus.write_word(gd, 0); // gdRefNum
bus.write_word(gd + 2, 0); // gdID
bus.write_word(gd + 4, if direct { 2 } else { 0 }); // directType / clutType
bus.write_long(gd + 6, 0); // gdITable
bus.write_word(gd + 10, 4); // gdResPref
bus.write_long(gd + 12, 0); // gdSearchProc
bus.write_long(gd + 16, 0); // gdCompProc
// gdFlags per Inside Macintosh: Imaging with QuickDraw
// bit 0 = gdDevType (1=color), bit 10 = ramInit, bit 11 = mainScreen,
// bit 12 = allInit, bit 13 = screenDevice, bit 15 = screenActive
let flags: u16 = (1 << 0) | (1 << 10) | (1 << 11) | (1 << 12) | (1 << 13) | (1 << 15);
bus.write_word(gd + 20, flags); // gdFlags
bus.write_long(gd + 22, pixmap_handle); // gdPMap
bus.write_long(gd + 26, 0); // gdRefCon
bus.write_long(gd + 30, 0); // gdNextGD = NULL (end of chain)
bus.write_word(gd + 34, 0); // gdRect.top
bus.write_word(gd + 36, 0); // gdRect.left
bus.write_word(gd + 38, screen_height);
bus.write_word(gd + 40, screen_width);
// Video.h depth-mode tokens are distinct from PixMap pixelSize and
// Display Manager timing IDs. Imaging With QuickDraw (1994),
// pp. 5-33--5-35, permits the HasDepth mode to be passed to SetDepth.
let depth_mode = crate::display::classic_depth_mode(screen_depth)
.expect("validated screen depth has a classic Video.h mode");
bus.write_long(gd + 42, u32::from(depth_mode));
let gd_handle = bus.alloc(4);
bus.write_long(gd_handle, gd);
self.main_gdevice_handle = gd_handle;
if *self.current_gdevice == 0 {
self.current_gdevice
.with_mut(|current_gdevice| *current_gdevice = gd_handle);
}
gd_handle
}
fn allocate_detached_gdevice(&mut self, bus: &mut MacMemoryBus) -> u32 {
let main_gdh = self.ensure_main_gdevice(bus);
let main_gd = bus.read_long(main_gdh);
let main_pmh = bus.read_long(main_gd + 22);
let main_pm = bus.read_long(main_pmh);
let main_ctab_handle = bus.read_long(main_pm + 42);
let main_ctab = bus.read_long(main_ctab_handle);
let ctab_entries = u32::from(bus.read_word(main_ctab + 6)) + 1;
let ctab_size = 8 + ctab_entries * 8;
let new_ctab = bus.alloc(ctab_size);
for off in 0..ctab_size {
bus.write_byte(new_ctab + off, bus.read_byte(main_ctab + off));
}
let new_ctab_handle = bus.alloc(4);
bus.write_long(new_ctab_handle, new_ctab);
let new_pm = bus.alloc(50);
for off in 0..50 {
bus.write_byte(new_pm + off, bus.read_byte(main_pm + off));
}
bus.write_long(new_pm + 42, new_ctab_handle);
let new_pmh = bus.alloc(4);
bus.write_long(new_pmh, new_pm);
let new_gd = bus.alloc(50);
bus.write_word(new_gd, 0); // gdRefNum
bus.write_word(new_gd + 2, 0); // gdID
bus.write_word(new_gd + 4, 0); // gdType
bus.write_long(new_gd + 6, 0); // gdITable
bus.write_word(new_gd + 10, 4); // gdResPref
bus.write_long(new_gd + 12, 0); // gdSearchProc
bus.write_long(new_gd + 16, 0); // gdCompProc
bus.write_word(new_gd + 20, 0); // gdFlags
bus.write_long(new_gd + 22, new_pmh); // gdPMap
bus.write_long(new_gd + 26, 0); // gdRefCon
bus.write_long(new_gd + 30, 0); // gdNextGD
for off in [34, 36, 38, 40] {
bus.write_word(new_gd + off, bus.read_word(main_gd + off));
}
bus.write_long(new_gd + 42, 128); // default B/W mode per IWQD 5-25
let new_gdh = bus.alloc(4);
bus.write_long(new_gdh, new_gd);
new_gdh
}
fn init_gdevice_minimal(&self, bus: &mut MacMemoryBus, gdh: u32, gd_ref_num: i16, mode: u32) {
if gdh == 0 {
return;
}
let gd = bus.read_long(gdh);
if gd == 0 {
return;
}
bus.write_word(gd, gd_ref_num as u16);
bus.write_long(gd + 42, mode);
// IWQD 5-25: mode 128 is the default black-and-white mode; other
// non-driver modes expose color via gdDevType. Preserve other flags.
let mut flags = bus.read_word(gd + 20);
flags &= !1;
if mode != 128 && mode != 0xFFFF_FFFF {
flags |= 1;
}
bus.write_word(gd + 20, flags);
}
fn gdevice_depth_flags(&mut self, bus: &mut MacMemoryBus, gdh: u32) -> Option<(u32, u16)> {
let gdh = if gdh == 0 {
self.ensure_main_gdevice(bus)
} else {
gdh
};
let gd = bus.read_long(gdh);
(gd != 0).then(|| (gdh, bus.read_word(gd + 20)))
}
fn supported_depth_personality(
depth_or_mode: u16,
which_flags: u16,
flags: u16,
current_flags: u16,
) -> Option<(u16, bool)> {
let depth = Self::supported_depth_from_mode(depth_or_mode)?;
let is_color = if which_flags & 1 != 0 {
flags & 1 != 0
} else {
match depth {
1 => false,
16 | 32 => true,
_ => current_flags & 1 != 0,
}
};
if (depth == 1 && is_color) || (matches!(depth, 16 | 32) && !is_color) {
return None;
}
let fixed_mask = which_flags & !1;
if current_flags & fixed_mask != flags & fixed_mask {
return None;
}
Some((depth, is_color))
}
fn has_depth_mode_id(
&mut self,
bus: &mut MacMemoryBus,
gdh: u32,
depth_or_mode: u16,
which_flags: u16,
flags: u16,
) -> u16 {
let Some((_, current_flags)) = self.gdevice_depth_flags(bus, gdh) else {
return 0;
};
Self::supported_depth_personality(depth_or_mode, which_flags, flags, current_flags)
.and_then(|(depth, _)| crate::display::classic_depth_mode(depth))
.unwrap_or(0)
}
fn supported_depth_from_mode(depth_or_mode: u16) -> Option<u16> {
crate::display::classic_pixel_size(depth_or_mode)
}
fn palette_dispatch_selector(d0: u32) -> u16 {
let low_word = (d0 & 0xFFFF) as u16;
// MPW's THREEWORDINLINE emits MOVE.W #selector,D0, which preserves
// D0's high word. Prefer the documented public selector in the low
// word before trying the alternate packed-long form.
if Self::is_public_palette_dispatch_selector(low_word) || d0 <= 0xFFFF {
return low_word;
}
// IM:VI Table C-3 lists _PaletteDispatch selectors as packed words:
// the high byte is the argument-frame byte count and the low byte is
// the routine selector (for example, SetDepth is $0A13). Some 68k
// callers place the same two fields in a longword D0 value, such as
// $000A0013. Normalize both encodings to the documented table value.
(((d0 >> 8) & 0xFF00) | (d0 & 0x00FF)) as u16
}
fn is_public_palette_dispatch_selector(selector: u16) -> bool {
matches!(
selector,
0x0002
| 0x0003
| 0x0015
| 0x040D
| 0x040E
| 0x040F
| 0x0410
| 0x0417
| 0x0616
| 0x0A13
| 0x0A14
| 0x0C19
| 0x1219
)
}
fn closest_available_color(target: [u16; 3], colors: &[[u16; 3]]) -> Option<usize> {
colors
.iter()
.enumerate()
.min_by_key(|(_, color)| {
let dr = i64::from(color[0]) - i64::from(target[0]);
let dg = i64::from(color[1]) - i64::from(target[1]);
let db = i64::from(color[2]) - i64::from(target[2]);
dr * dr + dg * dg + db * db
})
.map(|(index, _)| index)
}
fn quantize_direct_component(component: u16, bits: u16) -> u16 {
if bits >= 16 {
return component;
}
let levels = (1u32 << bits) - 1;
let level = (u32::from(component) * levels + 0x7FFF) / 0xFFFF;
((level * 0xFFFF + levels / 2) / levels) as u16
}
/// Return the best device-representable color strictly between the two
/// requested colors. GetGray leaves the foreground unchanged when device
/// quantization cannot produce a distinguishable third color.
///
/// Imaging With QuickDraw (1994), pp. 4-81 to 4-82.
fn gdevice_intermediate_color(
&mut self,
bus: &mut MacMemoryBus,
device: u32,
background: [u16; 3],
foreground: [u16; 3],
) -> Option<[u16; 3]> {
let device = if device != 0 {
device
} else if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
};
if !Self::guest_range_in_ram(bus, device, 4) {
return None;
}
let gd = bus.read_long(device);
if !Self::guest_range_in_ram(bus, gd, 46) {
return None;
}
let pixmap_handle = bus.read_long(gd + 22);
if !Self::guest_range_in_ram(bus, pixmap_handle, 4) {
return None;
}
let pixmap = bus.read_long(pixmap_handle);
if !Self::guest_range_in_ram(bus, pixmap, 46) {
return None;
}
let midpoint = [
((u32::from(background[0]) + u32::from(foreground[0])) / 2) as u16,
((u32::from(background[1]) + u32::from(foreground[1])) / 2) as u16,
((u32::from(background[2]) + u32::from(foreground[2])) / 2) as u16,
];
let pixel_type = bus.read_word(pixmap + 30);
let pixel_size = bus.read_word(pixmap + 32);
if pixel_type == 16 || pixel_size > 8 {
let component_bits = bus.read_word(pixmap + 36).clamp(1, 16);
let quantize = |rgb: [u16; 3]| {
[
Self::quantize_direct_component(rgb[0], component_bits),
Self::quantize_direct_component(rgb[1], component_bits),
Self::quantize_direct_component(rgb[2], component_bits),
]
};
let candidate = quantize(midpoint);
return (candidate != quantize(background) && candidate != quantize(foreground))
.then_some(candidate);
}
let ctab_handle = bus.read_long(pixmap + 42);
if !Self::guest_range_in_ram(bus, ctab_handle, 4) {
return None;
}
let ctab = bus.read_long(ctab_handle);
if !Self::guest_range_in_ram(bus, ctab, 8) {
return None;
}
let depth_entries = if pixel_size < 8 {
1usize << pixel_size
} else {
256
};
let last_entry = bus.read_word(ctab + 6) as i16;
if last_entry < 0 {
return None;
}
let entries = (last_entry as usize + 1).min(depth_entries).min(256);
let entries_base = ctab.checked_add(8)?;
if entries == 0 || !Self::guest_range_in_ram(bus, entries_base, (entries * 8) as u32) {
return None;
}
let colors: Vec<[u16; 3]> = (0..entries)
.map(|index| {
let entry = entries_base + index as u32 * 8;
[
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
]
})
.collect();
let background_index = Self::closest_available_color(background, &colors)?;
let foreground_index = Self::closest_available_color(foreground, &colors)?;
let midpoint_index = Self::closest_available_color(midpoint, &colors)?;
(midpoint_index != background_index && midpoint_index != foreground_index)
.then_some(colors[midpoint_index])
}
fn record_gdevice_depth_mode(
&mut self,
bus: &mut MacMemoryBus,
gdh: u32,
depth: u16,
is_color: bool,
) {
let gdh = if gdh != 0 {
gdh
} else {
self.ensure_main_gdevice(bus)
};
let gd = bus.read_long(gdh);
if gd == 0 {
return;
}
let Some(mode) = crate::display::classic_depth_mode(depth) else {
return;
};
bus.write_long(gd + 42, u32::from(mode));
let mut flags = bus.read_word(gd + 20);
flags &= !1;
if is_color {
flags |= 1;
}
bus.write_word(gd + 20, flags);
}
fn set_depth_or_mode<C: CpuOps>(
&mut self,
cpu: &mut C,
bus: &mut MacMemoryBus,
gdh: u32,
depth_or_mode: u16,
which_flags: u16,
flags: u16,
) -> u16 {
let Some((gdh, current_flags)) = self.gdevice_depth_flags(bus, gdh) else {
return (-50i16) as u16; // paramErr
};
let Some((depth, is_color)) =
Self::supported_depth_personality(depth_or_mode, which_flags, flags, current_flags)
else {
return (-50i16) as u16; // paramErr
};
let applied = if matches!(depth, 1 | 2 | 4 | 8) {
if depth == 8 {
if let Some((width, height)) = self.display_mode_geometry(u32::from(depth_or_mode))
{
self.do_setdepth_with_geometry_and_personality(
cpu, bus, depth, width, height, is_color,
)
} else {
self.do_setdepth_with_personality(cpu, bus, depth, is_color)
}
} else {
self.do_setdepth_with_personality(cpu, bus, depth, is_color)
}
} else {
true
};
if !applied {
return (-108i16) as u16; // memFullErr
}
self.record_gdevice_depth_mode(bus, gdh, depth, is_color);
0
}
fn palette_ptr(bus: &MacMemoryBus, palette_handle: u32) -> u32 {
if palette_handle == 0 {
return 0;
}
bus.read_long(palette_handle)
}
fn palette_entry_count(bus: &MacMemoryBus, palette_handle: u32) -> u16 {
let palette_ptr = Self::palette_ptr(bus, palette_handle);
if palette_ptr == 0 {
return 0;
}
bus.read_word(palette_ptr)
}
fn palette_color_info_ptr(palette_ptr: u32, entry: u32) -> u32 {
palette_ptr + PALETTE_HEADER_SIZE + entry * PALETTE_COLOR_INFO_SIZE
}
fn read_palette_color_info(
bus: &MacMemoryBus,
palette_handle: u32,
entry: u16,
) -> Option<([u16; 3], i16, i16)> {
let palette_ptr = Self::palette_ptr(bus, palette_handle);
let entries = Self::palette_entry_count(bus, palette_handle);
if palette_ptr == 0 || entry >= entries {
return None;
}
let color_info = Self::palette_color_info_ptr(palette_ptr, u32::from(entry));
Some((
[
bus.read_word(color_info),
bus.read_word(color_info + 2),
bus.read_word(color_info + 4),
],
bus.read_word(color_info + 6) as i16,
bus.read_word(color_info + 8) as i16,
))
}
fn write_palette_color_info(
bus: &mut MacMemoryBus,
palette_ptr: u32,
entry: u32,
rgb: [u16; 3],
usage: i16,
tolerance: i16,
) {
let color_info = Self::palette_color_info_ptr(palette_ptr, entry);
bus.write_word(color_info, rgb[0]);
bus.write_word(color_info + 2, rgb[1]);
bus.write_word(color_info + 4, rgb[2]);
bus.write_word(color_info + 6, usage as u16);
bus.write_word(color_info + 8, tolerance as u16);
bus.write_word(color_info + 10, 0);
bus.write_word(color_info + 12, 0);
bus.write_word(color_info + 14, 0);
}
fn create_palette_from_ctab(
&mut self,
bus: &mut MacMemoryBus,
entries: u16,
src_colors: u32,
src_usage: i16,
src_tolerance: i16,
) -> u32 {
let palette_ptr =
bus.alloc(PALETTE_HEADER_SIZE + u32::from(entries) * PALETTE_COLOR_INFO_SIZE);
bus.write_word(palette_ptr, entries);
for offset in (2..PALETTE_HEADER_SIZE).step_by(2) {
bus.write_word(palette_ptr + offset, 0);
}
let src_ctab_ptr = if src_colors != 0 {
bus.read_long(src_colors)
} else {
0
};
let src_ctab_entries = if src_ctab_ptr != 0 {
u32::from(bus.read_word(src_ctab_ptr + 6)) + 1
} else {
0
};
for index in 0..u32::from(entries) {
let rgb = if index < src_ctab_entries {
let ctab_entry = src_ctab_ptr + 8 + index * 8;
[
bus.read_word(ctab_entry + 2),
bus.read_word(ctab_entry + 4),
bus.read_word(ctab_entry + 6),
]
} else {
[0, 0, 0]
};
Self::write_palette_color_info(bus, palette_ptr, index, rgb, src_usage, src_tolerance);
}
let palette_handle = bus.alloc(4);
bus.write_long(palette_handle, palette_ptr);
self.palette_updates.insert(palette_handle, PM_ALL_UPDATES);
palette_handle
}
fn resize_handle_allocation(
&mut self,
bus: &mut MacMemoryBus,
handle: u32,
new_size: u32,
) -> u32 {
if handle == 0 {
return 0;
}
let old_ptr = bus.read_long(handle);
if old_ptr == 0 {
return 0;
}
let old_size = bus.get_alloc_size(old_ptr).unwrap_or(0);
let aligned_old = (old_size + 3) & !3;
let aligned_new = (new_size + 3) & !3;
if old_size == new_size || aligned_new <= aligned_old {
bus.set_alloc_size(old_ptr, new_size);
return old_ptr;
}
let new_ptr = bus.alloc(new_size);
if new_ptr == 0 && new_size != 0 {
return 0;
}
let copy_len = old_size.min(new_size) as usize;
if copy_len > 0 {
let bytes = bus.read_bytes(old_ptr, copy_len);
bus.write_bytes(new_ptr, &bytes);
}
bus.free(old_ptr);
bus.write_long(handle, new_ptr);
let tracked_handle = self.untrack_handle_ptr(old_ptr).is_some();
if tracked_handle {
self.track_handle_ptr(new_ptr, handle);
}
self.with_resource_manager_mut(|resource_manager| {
if let Some(entry) = resource_manager.loaded_handles.get_mut(&handle) {
entry.0 = new_ptr;
}
if let Some(resources) = resource_manager.resources.as_mut() {
for file in resources.files.values_mut() {
for ptr in file.loaded.values_mut() {
if *ptr == old_ptr {
*ptr = new_ptr;
}
}
for (_id, ptr) in file.named.values_mut() {
if *ptr == old_ptr {
*ptr = new_ptr;
}
}
}
}
});
new_ptr
}
fn resize_palette(&mut self, bus: &mut MacMemoryBus, palette_handle: u32, new_size: i16) {
if palette_handle == 0 || new_size < 0 {
return;
}
let old_palette_ptr = Self::palette_ptr(bus, palette_handle);
if old_palette_ptr == 0 {
return;
}
let old_entries = u32::from(Self::palette_entry_count(bus, palette_handle));
let new_entries = new_size as u32;
if old_entries == new_entries {
return;
}
let new_palette_ptr =
bus.alloc(PALETTE_HEADER_SIZE + new_entries * PALETTE_COLOR_INFO_SIZE);
bus.write_word(new_palette_ptr, new_entries as u16);
for offset in (2..PALETTE_HEADER_SIZE).step_by(2) {
bus.write_word(new_palette_ptr + offset, 0);
}
let preserved = old_entries.min(new_entries);
for index in 0..preserved {
if let Some((rgb, usage, tolerance)) =
Self::read_palette_color_info(bus, palette_handle, index as u16)
{
Self::write_palette_color_info(bus, new_palette_ptr, index, rgb, usage, tolerance);
}
}
for index in preserved..new_entries {
Self::write_palette_color_info(bus, new_palette_ptr, index, [0, 0, 0], PM_COURTEOUS, 0);
}
bus.write_long(palette_handle, new_palette_ptr);
bus.free(old_palette_ptr);
}
fn color_table_ptr(bus: &MacMemoryBus, ctab_handle: u32) -> u32 {
if ctab_handle == 0 {
return 0;
}
bus.read_long(ctab_handle)
}
fn color_table_entry_count(bus: &MacMemoryBus, ctab_handle: u32) -> u32 {
let ctab_ptr = Self::color_table_ptr(bus, ctab_handle);
if ctab_ptr == 0 {
return 0;
}
u32::from(bus.read_word(ctab_ptr + 6)) + 1
}
fn resize_color_table(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
entries: u32,
) -> u32 {
self.resize_handle_allocation(bus, ctab_handle, 8 + entries.saturating_mul(8))
}
pub(crate) fn ensure_color_table_capacity(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
entries: u32,
) -> u32 {
let ctab_ptr = Self::color_table_ptr(bus, ctab_handle);
if ctab_ptr == 0 {
return 0;
}
let required_size = 8 + entries.saturating_mul(8);
let Some(current_size) = bus.get_alloc_size(ctab_ptr) else {
return 0;
};
if current_size >= required_size {
return ctab_ptr;
}
self.resize_handle_allocation(bus, ctab_handle, required_size)
}
fn copy_ctab_to_palette(
&mut self,
bus: &mut MacMemoryBus,
src_ctab: u32,
palette: u32,
src_usage: i16,
src_tolerance: i16,
) {
let src_ctab_ptr = Self::color_table_ptr(bus, src_ctab);
if src_ctab_ptr == 0 || palette == 0 {
return;
}
let entries = Self::color_table_entry_count(bus, src_ctab).min(256);
if u32::from(Self::palette_entry_count(bus, palette)) != entries {
self.resize_palette(bus, palette, entries as i16);
}
let palette_ptr = Self::palette_ptr(bus, palette);
if palette_ptr == 0 {
return;
}
for offset in 0..entries {
let ctab_entry = src_ctab_ptr + 8 + offset * 8;
let rgb = [
bus.read_word(ctab_entry + 2),
bus.read_word(ctab_entry + 4),
bus.read_word(ctab_entry + 6),
];
Self::write_palette_color_info(bus, palette_ptr, offset, rgb, src_usage, src_tolerance);
}
}
fn copy_palette_to_ctab(
&mut self,
bus: &mut MacMemoryBus,
palette: u32,
dst_ctab: u32,
trace_label: &str,
) {
let entries = u32::from(Self::palette_entry_count(bus, palette));
if entries == 0 || dst_ctab == 0 {
return;
}
if Self::color_table_entry_count(bus, dst_ctab) != entries {
self.resize_color_table(bus, dst_ctab, entries);
}
let dst_ctab_ptr = Self::color_table_ptr(bus, dst_ctab);
if dst_ctab_ptr == 0 {
return;
}
let palette_seed = self.next_color_table_seed();
bus.write_long(dst_ctab_ptr, palette_seed);
self.trace_ctab_seed_write(dst_ctab_ptr, palette_seed, trace_label);
bus.write_word(dst_ctab_ptr + 4, 0);
bus.write_word(dst_ctab_ptr + 6, entries.saturating_sub(1) as u16);
let all_explicit = (0..entries).all(|offset| {
Self::read_palette_color_info(bus, palette, offset as u16)
.is_some_and(|(_, usage, _)| usage & PM_EXPLICIT != 0)
});
if all_explicit {
self.explicit_palette_ctabs.insert(dst_ctab);
} else {
self.explicit_palette_ctabs.remove(&dst_ctab);
}
for offset in 0..entries {
if let Some((rgb, _, _)) = Self::read_palette_color_info(bus, palette, offset as u16) {
let ctab_entry = dst_ctab_ptr + 8 + offset * 8;
bus.write_word(ctab_entry, offset as u16);
bus.write_word(ctab_entry + 2, rgb[0]);
bus.write_word(ctab_entry + 4, rgb[1]);
bus.write_word(ctab_entry + 6, rgb[2]);
}
}
}
fn copy_palette_resource_from_ptr(
&mut self,
bus: &mut MacMemoryBus,
palette_id: i16,
resource_ptr: u32,
) -> u32 {
if resource_ptr == 0 {
return 0;
}
let entries = u32::from(bus.read_word(resource_ptr));
let byte_size = PALETTE_HEADER_SIZE + entries * PALETTE_COLOR_INFO_SIZE;
let palette_ptr = bus.alloc(byte_size);
for offset in 0..byte_size {
bus.write_byte(palette_ptr + offset, bus.read_byte(resource_ptr + offset));
}
for offset in (2..PALETTE_HEADER_SIZE).step_by(2) {
bus.write_word(palette_ptr + offset, 0);
}
let palette_handle = bus.alloc(4);
bus.write_long(palette_handle, palette_ptr);
self.palette_updates.insert(palette_handle, PM_ALL_UPDATES);
if trace_palette_enabled() {
let resource_size = bus.get_alloc_size(resource_ptr).unwrap_or(0);
eprintln!(
"[PALETTE] copy_resource id={} resource=${:08X} size={} entries={} handle=${:08X}",
palette_id, resource_ptr, resource_size, entries, palette_handle
);
let preview = entries.min(8);
for index in 0..preview {
let color_info = Self::palette_color_info_ptr(palette_ptr, index);
eprintln!(
"[PALETTE] entry[{}] rgb=({:04X},{:04X},{:04X}) usage=${:04X} tol={}",
index,
bus.read_word(color_info),
bus.read_word(color_info + 2),
bus.read_word(color_info + 4),
bus.read_word(color_info + 6),
bus.read_word(color_info + 8) as i16,
);
}
}
palette_handle
}
pub(crate) fn copy_palette_resource(&mut self, bus: &mut MacMemoryBus, palette_id: i16) -> u32 {
// Load-on-demand, not find-only: since lazy resource seeding, a
// 'pltt' that no one has touched yet sits in the map with a NULL
// pointer (an IM-style empty handle), and the find-only lookup
// reports it missing. An application that probes its palette
// during launch gets NIL and exits. Same conversion GetCTable
// ('clut') and the Sound Manager already received.
let resource_ptr = self
.find_or_load_resource_any(bus, *b"pltt", palette_id)
.map(|(_, ptr)| ptr)
.or_else(|| {
(palette_id != 0)
.then(|| {
self.find_or_load_resource_any(bus, *b"pltt", 0)
.map(|(_, ptr)| ptr)
})
.flatten()
})
.unwrap_or(0);
self.copy_palette_resource_from_ptr(bus, palette_id, resource_ptr)
}
pub(crate) fn copy_palette_resource_exact(
&mut self,
bus: &mut MacMemoryBus,
palette_id: i16,
) -> u32 {
let resource_ptr = self
.find_or_load_resource_any(bus, *b"pltt", palette_id)
.map(|(_, ptr)| ptr)
.unwrap_or(0);
self.copy_palette_resource_from_ptr(bus, palette_id, resource_ptr)
}
pub(crate) fn initialize_application_palette(&mut self, bus: &mut MacMemoryBus) {
if self.window_palette_handle_exact(PALETTE_DEFAULT_WINDOW) != 0 {
return;
}
// Get1Resource semantics: never pick a palette from an unrelated open file.
let mut palette = 0;
for refnum in [self.current_resource_refnum(), 0] {
if let Some((_, ptr)) = self.find_or_load_resource_in_file(bus, refnum, *b"pltt", 0) {
let entries = u32::from(bus.read_word(ptr));
let size = PALETTE_HEADER_SIZE + entries * PALETTE_COLOR_INFO_SIZE;
if bus
.get_alloc_size(ptr)
.is_some_and(|available| available >= size)
{
palette = self.copy_palette_resource_from_ptr(bus, 0, ptr);
let palette_ptr = Self::palette_ptr(bus, palette);
for index in 0..entries {
let entry = Self::palette_color_info_ptr(palette_ptr, index);
for offset in [10, 12, 14] {
bus.write_word(entry + offset, 0);
}
}
break;
}
}
}
if palette == 0 {
palette = self.create_palette_from_ctab(bus, 2, 0, 0, 0);
let ptr = Self::palette_ptr(bus, palette);
Self::write_palette_color_info(bus, ptr, 0, [0xffff; 3], 0, 0);
}
if palette != 0 {
self.window_palettes
.insert(PALETTE_DEFAULT_WINDOW, (palette, PM_ALL_UPDATES));
}
}
fn window_palette_handle(&self, window: u32) -> u32 {
self.window_palettes
.get(&window)
.or_else(|| self.window_palettes.get(&PALETTE_DEFAULT_WINDOW))
.map(|(palette, _)| *palette)
.unwrap_or(0)
}
fn window_palette_handle_exact(&self, window: u32) -> u32 {
self.window_palettes
.get(&window)
.map(|(palette, _)| *palette)
.unwrap_or(0)
}
fn apply_palette_to_active_device(
&mut self,
bus: &mut MacMemoryBus,
window: u32,
palette_handle: u32,
trace_label: &str,
trace_seed_label: &str,
) {
let palette_ptr = Self::palette_ptr(bus, palette_handle);
if palette_ptr == 0 {
return;
}
// Activating a palette can assign its colors to different device
// indices than the source ColorTable. DrawPicture must then match
// against the destination table, not a preceding GetCTable result.
// Imaging With QuickDraw (1994), pp. 3-117, 7-44.
self.recent_resource_ctable_fetch = None;
let palette_entries = usize::from(Self::palette_entry_count(bus, palette_handle)).min(256);
let current_clut = *self.device_clut;
// Palette activation changes only the cells claimed by this palette.
// Resetting every other cell to the standard table reinterprets pixels
// already drawn by visible background windows, even though their
// palettes did not request or receive a redraw.
let mut updated_clut = current_clut;
self.palette_device_indices
.retain(|(palette, _), _| *palette != palette_handle);
let mut claimed = [false; 256];
// Cells this activation assigned to palette entries (excludes the
// reserved endpoints unless an entry actually maps to them).
let mut installed = [false; 256];
// Color QuickDraw keeps the white and black endpoints available for
// its standard drawing operations. Tolerant white and black entries
// may share those exact cells; other tolerant colors may not consume
// them. Inside Macintosh Volume V (1986), V-162.
claimed[0] = true;
claimed[255] = true;
// Preserve the existing behavior for explicit and animated entries,
// which either name or reserve a device index. Record those claims
// before allocating ordinary tolerant colors so a tolerant entry
// cannot displace a fixed-index request that appears later in the
// palette.
for index in 0..palette_entries {
let color_info = Self::palette_color_info_ptr(palette_ptr, index as u32);
let usage = bus.read_word(color_info + 6) as i16;
// Usage decides how a palette entry claims its device slot
// (IM: Advanced Color Imaging 1995, pp. 1-12..1-14):
//
// - PURE pmExplicit names device slot `index` WITHOUT
// requesting a color: the entry means "whatever that slot
// currently holds", so activation must leave the slot's RGB
// alone.
// - pmExplicit combined with pmTolerant (or pmAnimated) pins
// the palette's color AT that exact slot: "slot `index`,
// holding this RGB". Full-screen applications install a
// complete custom palette this way -- 256 explicit-tolerant
// entries, entry i claiming slot i -- so their pre-indexed
// artwork displays through their own table. Skipping those
// entries leaves the device on the standard table, and
// every pixel drawn with the application's indices shows
// the wrong colors.
//
// Only the pure-explicit case keeps the device value; the
// combined cases fall through to the ordinary install below.
if usage == PM_COURTEOUS {
let requested = [
bus.read_word(color_info),
bus.read_word(color_info + 2),
bus.read_word(color_info + 4),
];
let device_index = super::pict::closest_clut_index(
requested[0],
requested[1],
requested[2],
¤t_clut,
);
self.palette_device_indices
.insert((palette_handle, index as u16), device_index);
continue;
}
if usage & PM_EXPLICIT != 0 && usage & (PM_TOLERANT | PM_ANIMATED) == 0 {
continue;
}
if usage & PM_EXPLICIT == 0 && usage & PM_TOLERANT != 0 {
continue;
}
let device_index = index & 0xFF;
updated_clut[device_index] = [
bus.read_word(color_info),
bus.read_word(color_info + 2),
bus.read_word(color_info + 4),
];
claimed[device_index] = true;
installed[device_index] = true;
self.palette_device_indices
.insert((palette_handle, index as u16), device_index as u8);
}
// Tolerant colors are allocated unique device indices in palette
// order. Their palette positions are logical entry numbers, not CLUT
// indices. The selected cell changes only when its current color is
// farther away than the entry tolerance. Inside Macintosh Volume V
// (1986), V-160..V-162; Volume VI (1991), 20-9 and 20-15.
for index in 0..palette_entries {
let color_info = Self::palette_color_info_ptr(palette_ptr, index as u32);
let usage = bus.read_word(color_info + 6) as i16;
if usage & PM_TOLERANT == 0 || usage & PM_EXPLICIT != 0 {
continue;
}
let requested = [
bus.read_word(color_info),
bus.read_word(color_info + 2),
bus.read_word(color_info + 4),
];
let tolerance = bus.read_word(color_info + 8);
let endpoint = if requested == [0xFFFF; 3] && current_clut[0] == requested {
Some(0usize)
} else if requested == [0; 3] && current_clut[255] == requested {
Some(255usize)
} else {
None
};
let device_index = endpoint.or_else(|| {
PM_8BPP_ALLOCATION_ORDER
.iter()
.map(|&candidate| usize::from(candidate))
.find(|&candidate| !claimed[candidate])
});
let Some(device_index) = device_index else {
// Unsatisfied requests fall back to courteous matching.
continue;
};
claimed[device_index] = true;
installed[device_index] = true;
self.palette_device_indices
.insert((palette_handle, index as u16), device_index as u8);
let present = current_clut[device_index];
let difference = requested
.into_iter()
.zip(present)
.map(|(wanted, have)| wanted.abs_diff(have))
.max()
.unwrap_or(0);
if difference > tolerance {
updated_clut[device_index] = requested;
}
}
// The Palette Manager compares requests with the device's own
// ColorTable (gdPMap^^.pmTable), not with a private shadow. Some
// applications clear that table directly and then call
// ActivatePalette to force every requested color back in (The
// Tinies zeroes entries 1..254 before each activation). An installed
// cell whose guest RGB no longer matches therefore needs the
// ordinary reinstall, even though the host shadow is unchanged.
// Inside Macintosh Volume V (1986), V-160..V-162.
let guest_table_stale = {
let gdh = self.active_gdevice_or_main(bus);
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
let ctab_ptr = if ctab_handle != 0 {
bus.read_long(ctab_handle)
} else {
0
};
ctab_ptr != 0 && {
let entries = Self::color_table_entry_count(bus, ctab_handle).min(256) as usize;
(0..entries).any(|index| {
let entry = ctab_ptr + 8 + (index as u32) * 8;
installed[index]
&& [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
] != updated_clut[index]
})
}
};
let color_environment_changed = updated_clut != current_clut || guest_table_stale;
self.device_clut.replace(updated_clut);
if color_environment_changed {
// A palette that only matches existing device colors must not
// publish a transient hardware fade as the color-matching table.
// In particular, the default courteous white/black palette can
// activate while SetEntries has faded the screen to black.
self.color_manager_clut.replace(updated_clut);
let active_window = if window == DEFAULT_PALETTE_WINDOW {
self.front_window
} else {
window
};
self.invalidate_windows_for_palette_change(bus, active_window);
}
if trace_palette_enabled() {
eprintln!(
"[PALETTE] ActivatePalette{} window=${:08X} palette=${:08X} entries={}",
trace_label, window, palette_handle, palette_entries
);
for index in 0..palette_entries.min(8) {
let rgb = self.device_clut[index];
eprintln!(
"[PALETTE] device[{}]=({:04X},{:04X},{:04X})",
index, rgb[0], rgb[1], rgb[2]
);
}
for index in [15usize, 31, 63, 127, 255] {
let rgb = self.device_clut[index];
eprintln!(
"[PALETTE] device[{}]=({:04X},{:04X},{:04X})",
index, rgb[0], rgb[1], rgb[2]
);
}
}
// No changed device cells means no guest ColorTable update or seed change.
if !color_environment_changed {
return;
}
let gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.ensure_main_gdevice(bus)
};
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
let ctab_ptr = if ctab_handle != 0 {
bus.read_long(ctab_handle)
} else {
0
};
if ctab_ptr == 0 {
return;
}
let seed = self.next_color_table_seed();
bus.write_long(ctab_ptr, seed);
self.trace_ctab_seed_write(ctab_ptr, seed, trace_seed_label);
bus.write_word(ctab_ptr + 4, 0x8000);
// Palette activation changes the colours, not the device table's
// extent. Lower-depth indexed devices have fewer than 256 entries;
// writing a full 8-bit table overwrites the adjacent PixMap/GDevice.
// Imaging With QuickDraw (1994), pp. 4-56–4-57 (ctSize).
let entries = Self::color_table_entry_count(bus, ctab_handle).min(256) as usize;
for (index, rgb) in self.device_clut.iter().enumerate().take(entries) {
let entry = ctab_ptr + 8 + (index as u32) * 8;
bus.write_word(entry, index as u16);
bus.write_word(entry + 2, rgb[0]);
bus.write_word(entry + 4, rgb[1]);
bus.write_word(entry + 6, rgb[2]);
}
}
fn install_animated_palette_entry_on_active_device(
&mut self,
bus: &mut MacMemoryBus,
window: u32,
palette_handle: u32,
entry: u32,
rgb: [u16; 3],
usage: i16,
) {
// AnimateEntry and AnimatePalette change the device cells reserved by
// pmAnimated entries immediately. A pmExplicit entry still observes
// its existing device cell during ordinary palette activation, so the
// animation traps must update the changed cell before reactivation.
// Windows can share a palette. Animation through either association
// changes the same active device cells, while an unrelated background
// palette must not change the front window's color environment.
// Inside Macintosh Volume V (1986), V-164; Volume VI (1991), 20-13.
if usage & PM_ANIMATED == 0
|| window == 0
|| self.window_palette_handle(self.front_window) != palette_handle
|| self.window_palette_handle_exact(window) != palette_handle
{
return;
}
let device_index = (entry as usize) & 0xFF;
self.device_clut.set_entry(device_index, rgb);
self.color_manager_clut.set_entry(device_index, rgb);
// Animation changes a device cell before palette activation. Publish
// that cell now: activation may correctly find no further changes,
// but subsequent indexed drawing still needs the new guest table.
let gdh = self.active_gdevice_or_main(bus);
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
if ctab_handle == 0
|| device_index >= Self::color_table_entry_count(bus, ctab_handle) as usize
{
return;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return;
}
let entry = ctab_ptr + 8 + device_index as u32 * 8;
let previous = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
if previous != rgb {
bus.write_word(entry + 2, rgb[0]);
bus.write_word(entry + 4, rgb[1]);
bus.write_word(entry + 6, rgb[2]);
let seed = self.next_color_table_seed();
bus.write_long(ctab_ptr, seed);
self.trace_ctab_seed_write(ctab_ptr, seed, "animate_palette_entry");
}
}
pub(crate) fn set_window_palette_association(
&mut self,
window: u32,
palette: u32,
updates: i16,
) {
if palette == 0 {
self.window_palettes.remove(&window);
} else {
self.window_palettes.insert(window, (palette, updates));
self.record_palette_updates(palette, updates);
}
}
fn clear_palette_tracking(&mut self, palette: u32) {
if palette == 0 {
return;
}
self.palette_updates.remove(&palette);
self.palette_device_indices
.retain(|(handle, _), _| *handle != palette);
self.window_palettes
.retain(|_, (handle, _)| *handle != palette);
}
fn record_palette_updates(&mut self, palette: u32, updates: i16) {
if palette != 0 {
self.palette_updates.insert(palette, updates);
}
}
fn palette_update_mode(&self, palette: u32) -> i16 {
self.palette_updates.get(&palette).copied().unwrap_or(0)
}
fn invalidate_windows_for_palette_change(
&mut self,
bus: &mut MacMemoryBus,
active_window: u32,
) {
let windows = self.window_list.to_vec();
for window in windows {
let palette = self.window_palette_handle_exact(window);
if palette == 0 {
continue;
}
let updates = self.palette_update_mode(palette);
let is_foreground = window == active_window;
let requests_update = match updates {
PM_ALL_UPDATES => true,
PM_FG_UPDATES => is_foreground,
PM_BK_UPDATES => !is_foreground,
PM_NO_UPDATES => false,
_ => false,
};
if requests_update {
self.invalidate_entire_visible_window(bus, window);
}
}
}
pub(crate) fn activate_palette_for_window(&mut self, bus: &mut MacMemoryBus, window: u32) {
if window == 0 || window != self.front_window {
return;
}
let palette_handle = self.window_palette_handle(window);
self.apply_palette_to_active_device(
bus,
window,
palette_handle,
"",
"activate_palette_for_window",
);
}
/// Trap-facing activation path that requires an exact window-to-palette
/// association instead of falling back to the default-window palette.
pub(crate) fn activate_associated_palette_for_window(
&mut self,
bus: &mut MacMemoryBus,
window: u32,
) {
if window == 0 {
return;
}
let palette_handle = self.window_palette_handle_exact(window);
if window != self.front_window
&& (palette_handle == 0
|| palette_handle != self.window_palette_handle(self.front_window))
{
return;
}
if palette_handle == 0 {
// A window without an associated palette supplies no new color
// requests. The default palette keeps basic colors available,
// but activation does not replace every device cell with the
// standard 256-color table: those cells may still display pixels
// drawn by other windows. Inside Macintosh Volume V (1986),
// V-160–V-162; Volume VI (1991), 20-15–20-16.
return;
}
self.apply_palette_to_active_device(
bus,
window,
palette_handle,
" exact",
"activate_associated_palette_for_window",
);
}
fn palette_entry_rgb_for_current_window(
&self,
bus: &MacMemoryBus,
entry: i16,
) -> Option<(u32, [u16; 3], i16)> {
if entry < 0 {
return None;
}
let palette_handle = self.window_palette_handle(*self.current_port);
if palette_handle == 0 {
return None;
}
let (rgb, usage, _tolerance) =
Self::read_palette_color_info(bus, palette_handle, entry as u16)?;
Some((palette_handle, rgb, usage))
}
fn palette_entry_to_device_index(&self, bus: &MacMemoryBus, entry: i16) -> u32 {
if entry < 0 {
return 0;
}
if let Some((palette, rgb, usage)) = self.palette_entry_rgb_for_current_window(bus, entry) {
if (usage & PM_EXPLICIT) != 0 {
return u32::from((entry as u16) & 0x00FF);
}
if let Some(index) = self
.palette_device_indices
.get(&(palette, entry as u16))
.copied()
{
return u32::from(index);
}
return u32::from(super::pict::closest_clut_index(
rgb[0],
rgb[1],
rgb[2],
&self.device_clut,
));
}
u32::from((entry as u16) & 0x00FF)
}
/// Overlay the entries of a guest ColorTable on the current Color Manager
/// CLUT. A ColorSpec is four consecutive big-endian words: the logical
/// index followed by red, green, and blue. Reading the contiguous array in
/// one operation avoids four memory-bus dispatches for every entry while
/// still consulting guest memory on every call. The latter is important:
/// applications may animate or directly modify an offscreen ColorTable.
fn read_color_table_ptr_clut(&self, bus: &MacMemoryBus, ctab_ptr: u32) -> [[u16; 3]; 256] {
let entry_count = usize::from(bus.read_word(ctab_ptr.wrapping_add(6)).min(255)) + 1;
let byte_count = entry_count * 8;
let mut entries = [0u8; 256 * 8];
bus.read_bytes_into(ctab_ptr.wrapping_add(8), &mut entries[..byte_count]);
// Treat guest ColorTables as overrides on top of the Color Manager CLUT.
// Some scratch/offscreen tables do not populate every logical index;
// zero-filling the rest would collapse unrelated indices to black.
let mut clut = *self.color_manager_clut;
// Device ColorTables are addressed by entry position. Their
// ColorSpec.value low byte is a Color Manager client ID, not a pixel
// index; the high byte retains per-entry flags. Inside Macintosh
// Volume V (1986), pp. V-142..V-143.
let device_table = (bus.read_word(ctab_ptr.wrapping_add(4)) & 0x8000) != 0;
for (position, entry) in entries[..byte_count].chunks_exact(8).enumerate() {
let value = u16::from_be_bytes([entry[0], entry[1]]) as usize;
let red = u16::from_be_bytes([entry[2], entry[3]]);
let green = u16::from_be_bytes([entry[4], entry[5]]);
let blue = u16::from_be_bytes([entry[6], entry[7]]);
let index = if device_table {
position
} else {
value.min(255)
};
clut[index] = [red, green, blue];
}
clut
}
/// Read a 256-entry CLUT from a CTabHandle in guest memory.
/// Falls back to the Color Manager shadow if the handle is NULL.
/// Imaging With QuickDraw 1994, p. 4-82
fn read_port_clut_with_provenance(
&self,
bus: &MacMemoryBus,
ctab_handle: u32,
) -> ([[u16; 3]; 256], bool) {
if ctab_handle == 0 {
return (*self.color_manager_clut, true);
}
let handle_is_mapped = bus.is_guest_address_mapped(ctab_handle, 4);
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return (*self.color_manager_clut, false);
}
// Preserve the legacy total-read result even for a malformed or
// partially mapped table. Provenance qualifies only whether that
// result may establish raw index identity for the new reducer.
let clut = self.read_color_table_ptr_clut(bus, ctab_ptr);
let entry_count = u32::from(bus.read_word(ctab_ptr.wrapping_add(6)).min(255)) + 1;
let table_len = 8usize + entry_count as usize * 8;
let known = handle_is_mapped && bus.is_guest_address_mapped(ctab_ptr, table_len);
(clut, known)
}
pub(crate) fn read_port_clut(&self, bus: &MacMemoryBus, ctab_handle: u32) -> [[u16; 3]; 256] {
self.read_port_clut_with_provenance(bus, ctab_handle).0
}
fn read_indexed_destination_clut(
&self,
bus: &MacMemoryBus,
ctab_handle: u32,
pixel_size: u32,
screen_destination: bool,
) -> Option<[[u16; 3]; 256]> {
self.read_indexed_destination_clut_with_provenance(
bus,
ctab_handle,
pixel_size,
screen_destination,
)
.map(|(clut, _)| clut)
}
fn read_indexed_destination_clut_with_provenance(
&self,
bus: &MacMemoryBus,
mut ctab_handle: u32,
pixel_size: u32,
screen_destination: bool,
) -> Option<([[u16; 3]; 256], bool)> {
if !matches!(pixel_size, 1 | 2 | 4 | 8) {
return None;
}
if screen_destination && ctab_handle == 0 && self.main_gdevice_handle != 0 {
ctab_handle = Self::gdevice_ctab_handle(bus, self.main_gdevice_handle);
}
let (mut clut, known) = if pixel_size == 1 {
let mut monochrome = [[0u16; 3]; 256];
monochrome[0] = [0xFFFF, 0xFFFF, 0xFFFF];
(monochrome, true)
} else {
// CopyBits uses the destination GDevice's ColorTable for indexed
// color matching. The private Color Manager and physical display
// CLUTs have separate bookkeeping roles and cannot replace that
// guest table. Imaging With QuickDraw (1994), p. 3-117.
self.read_port_clut_with_provenance(bus, ctab_handle)
};
if pixel_size < 8 {
let entry_count = 1usize << pixel_size;
let terminal = clut[entry_count - 1];
clut[entry_count..].fill(terminal);
}
Some((clut, known))
}
pub(super) fn read_ctab_handle_clut(
&self,
bus: &MacMemoryBus,
ctab_handle: u32,
) -> [[u16; 3]; 256] {
if ctab_handle == 0 {
return *self.color_manager_clut;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return *self.color_manager_clut;
}
self.read_color_table_ptr_clut(bus, ctab_ptr)
}
pub(super) fn uses_canonical_system_8bpp_clut(clut: &[[u16; 3]; 256]) -> bool {
clut[0] == [0xFFFF, 0xFFFF, 0xFFFF]
&& clut[1] == [0xFFFF, 0xFFFF, 0xCCCC]
&& clut[16] == [0xFFFF, 0x9999, 0x3333]
&& clut[42] == [0xCCCC, 0xCCCC, 0xFFFF]
&& clut[128] == [0x6666, 0x6666, 0x9999]
&& clut[255] == [0, 0, 0]
}
fn uses_scaled_canonical_system_8bpp_clut(clut: &[[u16; 3]; 256]) -> bool {
let sample0 = clut[0];
if sample0[0] != sample0[1] || sample0[1] != sample0[2] {
return false;
}
let scale = sample0[0] as f64 / 65535.0;
if !(0.0..=1.0).contains(&scale) {
return false;
}
let expected = Self::standard_mac_8bpp_clut();
for index in [0usize, 1, 16, 42, 128, 255] {
for channel in 0..3 {
let want = (f64::from(expected[index][channel]) * scale).round() as i32;
let got = i32::from(clut[index][channel]);
if (got - want).abs() > 0x0200 {
return false;
}
}
}
true
}
fn pict_clut_is_dense_grayscale(clut: &[[u16; 3]; 256]) -> bool {
let grayscale_entries = clut
.iter()
.take(192)
.filter(|rgb| rgb[0] == rgb[1] && rgb[1] == rgb[2] && rgb[0] != 0)
.count();
grayscale_entries >= 96
}
/// Counts CTab entries whose RGB is non-zero. A sparse PICT CTab
/// (only a handful of populated slots, the rest zeros from handle
/// allocation) is not a full-scene palette and shouldn't be
/// installed wholesale as the screen palette — the zero slots
/// would paint black where the game expected its current colours.
fn pict_clut_populated_count(clut: &[[u16; 3]; 256]) -> usize {
clut.iter()
.filter(|rgb| !(rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0))
.count()
}
fn picture_clut_arrays(
base_clut: &[[u16; 3]; 256],
pict_clut: &[[u16; 3]],
) -> Option<([[u16; 3]; 256], [[u16; 3]; 256])> {
// Palette Manager merge semantics: start from the active logical
// table and overlay only entries the PICT actually specifies. The
// raw zero-padded table remains available for the dense-grayscale
// gate so sparse PICT CTabs do not look like full scene palettes.
let mut raw_pict_array = [[0u16; 3]; 256];
let mut merged = *base_clut;
let mut had_nonzero = false;
for (index, rgb) in pict_clut.iter().take(256).enumerate() {
raw_pict_array[index] = *rgb;
if !(rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0) {
merged[index] = *rgb;
had_nonzero = true;
}
}
had_nonzero.then_some((raw_pict_array, merged))
}
fn should_seed_screen_palette_from_pict(
pict_clut: &[[u16; 3]; 256],
_current_clut: &[[u16; 3]; 256],
) -> bool {
// Seed the screen palette from a PICT's embedded CTab ONLY when:
// (a) the PICT's CTab is NOT dense grayscale. Grayscale PICTs
// (e.g. EV title resource 8100) rely on later SetEntries
// fades to become their intended coloured presentation on
// Basilisk. Seeding from the grayscale would lock the
// title into gray and regress earlier frames. The palette
// investigation established this as the hard constraint.
// (b) the PICT CTab has at least 16 populated entries. The
// lower threshold works because the DrawPicture
// seeding call-site now MERGES non-zero entries into the
// current CLUT instead of wholesale-replacing it — so a
// PICT with 32 populated entries only overwrites those
// 32 indices, preserving the rest. That admits
// small panel-style PICTs (EV's landing-scene
// composition draws the panel as multiple small PICTs)
// while still rejecting near-empty CTabs (3-entry
// sparse-grayscale test fixtures).
//
// Imaging With QuickDraw 1994, 7-14 (picture-with-palette
// semantics); Inside Macintosh Volume VI 20-12 (Palette
// Manager merge semantics).
!Self::pict_clut_is_dense_grayscale(pict_clut)
&& Self::pict_clut_populated_count(pict_clut) >= 16
}
fn should_preserve_offscreen_picture_indices_from_pict(
pict_clut: &[[u16; 3]; 256],
current_clut: &[[u16; 3]; 256],
logical_screen_clut: &[[u16; 3]; 256],
) -> bool {
// Some games draw a full-scene PICT into an offscreen GWorld before
// installing the palette that belongs to that picture, then blit the
// raw 8-bit indices after SetEntries. Matching the PICT's colors
// against the currently-active stale port CTab bakes the wrong index
// values into the offscreen buffer. Raw indices are valid only when
// every populated PICT entry already names the same visible color at
// that index in the logical screen palette. Otherwise ordinary Color
// Manager translation is required; preserving unrelated PICT indices
// corrupts sprite colors. Indexed hardware exposes the high byte of
// each RGB component. Imaging With QuickDraw (1994), pp. 4-13, 7-14.
if Self::uses_canonical_system_8bpp_clut(logical_screen_clut)
|| Self::uses_scaled_canonical_system_8bpp_clut(logical_screen_clut)
{
return false;
}
// If the offscreen port has already inherited the current screen
// palette, normal Color Manager translation is the real-Mac path.
// Raw-index preservation is only for stale offscreen CTabs that will
// be blitted after a different screen palette is installed.
if current_clut == logical_screen_clut {
return false;
}
!Self::pict_clut_is_dense_grayscale(pict_clut)
&& Self::pict_clut_populated_count(pict_clut) >= 64
&& pict_clut
.iter()
.zip(logical_screen_clut)
.filter(|(picture, _)| **picture != [0, 0, 0])
.all(|(picture, screen)| picture.iter().zip(screen).all(|(p, s)| p >> 8 == s >> 8))
}
fn scale_clut(clut: &[[u16; 3]; 256], scale: f64) -> [[u16; 3]; 256] {
let clamped_scale = scale.clamp(0.0, 1.0);
let mut scaled = [[0u16; 3]; 256];
for (index, rgb) in clut.iter().enumerate() {
scaled[index] = [
(f64::from(rgb[0]) * clamped_scale)
.round()
.clamp(0.0, 65535.0) as u16,
(f64::from(rgb[1]) * clamped_scale)
.round()
.clamp(0.0, 65535.0) as u16,
(f64::from(rgb[2]) * clamped_scale)
.round()
.clamp(0.0, 65535.0) as u16,
];
}
scaled
}
fn screen_palette_brightness_scale(clut: &[[u16; 3]; 256]) -> f64 {
let [r, g, b] = clut[0];
if r != g || g != b {
return 1.0;
}
(f64::from(r) / 65535.0).clamp(0.0, 1.0)
}
fn seeded_picture_palette_until_tick_for_seed(
&self,
extend_by_ticks: u32,
preserve_active_window: bool,
) -> u32 {
if preserve_active_window
&& self.current_tick() < self.seeded_picture_palette_until_tick
&& !Self::uses_canonical_system_8bpp_clut(&self.seeded_picture_palette)
{
self.seeded_picture_palette_until_tick
} else {
self.current_tick().saturating_add(extend_by_ticks)
}
}
fn remember_recent_resource_ctable_fetch(&mut self, ct_id: i16, ctab_handle: u32) {
self.recent_resource_ctable_fetch = Some(RecentColorTableFetch {
ct_id,
ctab_handle,
port: *self.current_port,
tick: self.current_tick(),
});
if trace_palette_enabled() {
eprintln!(
"[PALETTE] RememberGetCTable tick={} trap={} port=${:08X} ct_id={} handle=${:08X}",
self.current_tick(), self.trap_count, *self.current_port, ct_id, ctab_handle,
);
}
}
fn take_recent_drawpicture_resource_ctable_fetch(
&mut self,
port: u32,
_port_base: u32,
_port_rb: u32,
port_ps: u16,
) -> Option<RecentColorTableFetch> {
let recent = self.recent_resource_ctable_fetch?;
let stale = self.current_tick() > recent.tick.saturating_add(1);
if stale {
self.recent_resource_ctable_fetch = None;
return None;
}
let eligible = port_ps == 8 && port == recent.port;
if eligible {
return self.recent_resource_ctable_fetch.take();
}
None
}
fn apply_fetched_ctable_to_offscreen_drawpicture_port(
&mut self,
bus: &mut MacMemoryBus,
port: u32,
port_ctab_handle: u32,
fetch: &RecentColorTableFetch,
clut: &[[u16; 3]; 256],
) {
if port_ctab_handle != 0 {
let ctab_ptr = bus.read_long(port_ctab_handle);
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let _ =
self.overwrite_color_table_handle_with_clut(bus, port_ctab_handle, clut, ct_flags);
}
let entries = Self::color_table_entry_count(bus, fetch.ctab_handle);
let current_screen_is_application_palette =
!Self::uses_canonical_system_8bpp_clut(&self.color_manager_clut)
&& !Self::uses_scaled_canonical_system_8bpp_clut(&self.color_manager_clut);
if entries < 16 || !current_screen_is_application_palette {
return;
}
self.install_application_clut(bus, *clut);
self.seeded_picture_palette = *clut;
self.seeded_picture_palette_until_tick =
self.seeded_picture_palette_until_tick_for_seed(64, true);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] PublishFetchedCTableForOffscreenDrawPicture tick={} port=${:08X} ct_id={} entries={} ctab=${:08X} device[8]=({:04X},{:04X},{:04X}) device[9]=({:04X},{:04X},{:04X})",
self.current_tick(),
port,
fetch.ct_id,
entries,
port_ctab_handle,
self.device_clut[8][0],
self.device_clut[8][1],
self.device_clut[8][2],
self.device_clut[9][0],
self.device_clut[9][1],
self.device_clut[9][2],
);
}
}
fn seed_screen_palette_from_picture_clut(
&mut self,
bus: &mut MacMemoryBus,
pic_handle: u32,
pic_ptr: u32,
clut: &[[u16; 3]; 256],
fetched_ct_id: Option<i16>,
) {
// Diagnostic gate; when SYSTEMLESS_PICT_SEED_CLUT_ENABLE is unset,
// skip the seed from a PICT CTab / fetched-CTable.
if pict_seed_clut_disabled() {
return;
}
let scale = Self::screen_palette_brightness_scale(&self.device_clut);
self.device_clut.replace(if palette_as_game_wrote_enabled() {
*clut
} else {
Self::scale_clut(clut, scale)
});
self.color_manager_clut.replace(*clut);
self.seeded_picture_palette = *clut;
self.seeded_picture_palette_until_tick =
self.seeded_picture_palette_until_tick_for_seed(48, true);
self.sync_canonical_offscreen_ctabs_to_clut(bus, clut);
if trace_palette_enabled() {
let event = match fetched_ct_id {
Some(ct_id) => format!("SeedFromFetchedCTable({ct_id})"),
None => "SeedFromTitleClut".to_string(),
};
eprintln!(
"[PALETTE] {} tick={} picHandle=${:08X} picPtr=${:08X} scale={:.3} cm[0]=({:04X},{:04X},{:04X}) cm[1]=({:04X},{:04X},{:04X}) cm[16]=({:04X},{:04X},{:04X}) cm[42]=({:04X},{:04X},{:04X}) cm[128]=({:04X},{:04X},{:04X}) cm[255]=({:04X},{:04X},{:04X})",
event,
self.current_tick(),
pic_handle,
pic_ptr,
scale,
self.color_manager_clut[0][0],
self.color_manager_clut[0][1],
self.color_manager_clut[0][2],
self.color_manager_clut[1][0],
self.color_manager_clut[1][1],
self.color_manager_clut[1][2],
self.color_manager_clut[16][0],
self.color_manager_clut[16][1],
self.color_manager_clut[16][2],
self.color_manager_clut[42][0],
self.color_manager_clut[42][1],
self.color_manager_clut[42][2],
self.color_manager_clut[128][0],
self.color_manager_clut[128][1],
self.color_manager_clut[128][2],
self.color_manager_clut[255][0],
self.color_manager_clut[255][1],
self.color_manager_clut[255][2]
);
}
}
fn canonical_table_brightness_scale(bus: &MacMemoryBus, table_ptr: u32) -> Option<f64> {
let white_entry = table_ptr + 2;
let white = bus.read_word(white_entry);
let green = bus.read_word(white_entry + 2);
let blue = bus.read_word(white_entry + 4);
if white != green || green != blue {
return None;
}
Some(f64::from(white) / 65535.0)
}
pub(super) fn ctab_seed(bus: &MacMemoryBus, ctab_handle: u32) -> Option<u32> {
if ctab_handle == 0 {
return None;
}
let ctab_ptr = bus.read_long(ctab_handle);
(ctab_ptr != 0).then(|| bus.read_long(ctab_ptr))
}
fn next_color_table_seed(&mut self) -> u32 {
let seed = self.next_ct_seed;
self.next_ct_seed = self.next_ct_seed.wrapping_add(1);
if self.next_ct_seed == 0 {
self.next_ct_seed = 1;
}
if trace_ctab_seed_enabled() {
eprintln!(
"[CTAB-SEED] tick={} next_ct_seed -> {}",
self.current_tick(), seed,
);
}
seed
}
/// When `SYSTEMLESS_TRACE_CTAB_SEED=1`, logs a seed write to a CTab at
/// `ctab_ptr` from a named code path. Paired with the counter-only
/// trace in `next_color_table_seed`. Together they let a post-process
/// correlate "seed S was allocated at tick T" with "seed S was
/// written to CTab at ptr P at tick T+k by code path L", resolving
/// ambiguity when the same seed value appears at multiple CTabs
/// (notably when seed inheritance gives the same seed to the
/// GDevice and an offscreen GWorld).
fn trace_ctab_seed_write(&self, ctab_ptr: u32, seed: u32, label: &str) {
if trace_ctab_seed_enabled() {
eprintln!(
"[CTAB-SEED-WRITE] tick={} label={} ctab_ptr=${:08X} seed={}",
self.current_tick(), label, ctab_ptr, seed,
);
}
}
fn reseed_color_table_handle(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
) -> Option<u32> {
if ctab_handle == 0 {
return None;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return None;
}
// Executor's depth-convention preservation (qGWorld.cpp:217):
// when the post-update CTab content is byte-identical to the
// standard N-bpp palette, keep `seed = depth` so PICTs
// authored against that canonical palette (also stamped with
// seed=depth) hit the identity-copy gate without
// closest-match remap. Only 8bpp is handled here — that's
// the depth EV and Marathon both run in, and the only depth
// whose canonical palette matters for PICT identity-copy.
// Without this, every SetEntries/CTabChanged bumps the seed
// to a fresh counter value even after a fade has returned the
// palette to canonical, and PICTs authored for the standard
// palette remap unnecessarily.
let seed = if Self::ctab_is_canonical_8bpp(bus, ctab_ptr) {
8
} else {
self.next_color_table_seed()
};
bus.write_long(ctab_ptr, seed);
self.trace_ctab_seed_write(ctab_ptr, seed, "reseed_color_table_handle");
Some(seed)
}
/// Returns true when the 256-entry CTab at `ctab_ptr` matches the
/// standard Mac 8bpp system palette byte-for-byte. Read-only; used
/// by `reseed_color_table_handle` to preserve the depth-convention
/// seed for canonical CTabs. A 256-entry read is cheap compared to
/// the CopyBits/DrawPicture hot paths and is only called on
/// CTabChanged/SetEntries cleanup (bounded by the number of
/// palette events, not per-pixel).
fn ctab_is_canonical_8bpp(bus: &MacMemoryBus, ctab_ptr: u32) -> bool {
// ctSize field (entries - 1). Must be 255 for an 8bpp CTab.
if bus.read_word(ctab_ptr + 6) != 255 {
return false;
}
let std = Self::standard_mac_8bpp_clut();
for i in 0..256u32 {
let entry = ctab_ptr + 8 + i * 8;
let r = bus.read_word(entry + 2);
let g = bus.read_word(entry + 4);
let b = bus.read_word(entry + 6);
if [r, g, b] != std[i as usize] {
return false;
}
}
true
}
pub(super) fn gdevice_ctab_handle(bus: &MacMemoryBus, gdh: u32) -> u32 {
let pm_handle = Self::gdevice_pixmap_handle(bus, gdh);
if pm_handle == 0 {
return 0;
}
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr == 0 {
return 0;
}
let Some(ctab_handle_addr) = pm_ptr.checked_add(42) else {
return 0;
};
bus.read_long(ctab_handle_addr)
}
fn gdevice_pixmap_handle(bus: &MacMemoryBus, gdh: u32) -> u32 {
if gdh == 0 {
return 0;
}
let gd = bus.read_long(gdh);
if gd == 0 {
return 0;
}
let Some(pm_handle_addr) = gd.checked_add(22) else {
return 0;
};
let pm_handle = bus.read_long(pm_handle_addr);
if pm_handle == 0 {
return 0;
}
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr == 0 {
return 0;
}
pm_handle
}
fn gdevice_pixel_size(bus: &MacMemoryBus, gdh: u32) -> Option<u32> {
if gdh == 0 {
return None;
}
let gd = bus.read_long(gdh);
if gd == 0 {
return None;
}
let pm_handle = bus.read_long(gd.checked_add(22)?);
if pm_handle == 0 {
return None;
}
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr == 0 {
return None;
}
Some(bus.read_word(pm_ptr.checked_add(32)?) as u32)
}
fn get_or_create_device_loop_trampoline(&mut self, bus: &mut MacMemoryBus) -> u32 {
if self.device_loop_trampoline != 0 {
return self.device_loop_trampoline;
}
let tramp = bus.alloc(42);
bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
bus.write_word(tramp + 4, 0x3F3C); // MOVE.W #imm,-(SP)
bus.write_word(tramp + 8, 0x3F3C); // MOVE.W #imm,-(SP)
bus.write_word(tramp + 12, 0x2F3C); // MOVE.L #imm,-(SP)
bus.write_word(tramp + 18, 0x2F3C); // MOVE.L #imm,-(SP)
bus.write_word(tramp + 24, 0x4EB9); // JSR abs.L
bus.write_word(tramp + 30, 0x2E7C); // MOVEA.L #imm,A7
bus.write_word(tramp + 36, 0x4CDF); // MOVEM.L (SP)+,regs
bus.write_word(tramp + 38, 0x0F0F); // D0-D3/A0-A3
bus.write_word(tramp + 40, 0x4E75); // RTS
self.device_loop_trampoline = tramp;
tramp
}
fn write_device_loop_trampoline(
bus: &mut MacMemoryBus,
tramp: u32,
depth: u16,
device_flags: u16,
target_gdevice: u32,
user_data: u32,
drawing_proc: u32,
return_slot: u32,
next_trampoline: Option<u32>,
) {
bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
bus.write_word(tramp + 4, 0x3F3C); // MOVE.W #imm,-(SP)
bus.write_word(tramp + 6, depth); // depth
bus.write_word(tramp + 8, 0x3F3C); // MOVE.W #imm,-(SP)
bus.write_word(tramp + 10, device_flags); // deviceFlags
bus.write_word(tramp + 12, 0x2F3C); // MOVE.L #imm,-(SP)
bus.write_long(tramp + 14, target_gdevice); // targetDevice
bus.write_word(tramp + 18, 0x2F3C); // MOVE.L #imm,-(SP)
bus.write_long(tramp + 20, user_data); // userData
bus.write_word(tramp + 24, 0x4EB9); // JSR abs.L
bus.write_long(tramp + 26, drawing_proc); // drawingProc
bus.write_word(tramp + 30, 0x2E7C); // MOVEA.L #imm,A7
bus.write_long(tramp + 32, return_slot.wrapping_sub(32));
bus.write_word(tramp + 36, 0x4CDF); // MOVEM.L (SP)+,regs
bus.write_word(tramp + 38, 0x0F0F); // D0-D3/A0-A3
match next_trampoline {
Some(next) => {
bus.write_word(tramp + 40, 0x4EF9); // JMP abs.L
bus.write_long(tramp + 42, next);
}
None => {
bus.write_word(tramp + 40, 0x4E75); // RTS
}
}
}
fn pixmap_ptr_from_handle(bus: &MacMemoryBus, pm_handle: u32) -> Option<u32> {
if pm_handle == 0 || pm_handle == u32::MAX || bus.get_alloc_size(pm_handle) != Some(4) {
return None;
}
let pm_ptr = bus.read_long(pm_handle);
(pm_ptr != 0 && bus.get_alloc_size(pm_ptr).is_some()).then_some(pm_ptr)
}
fn cached_copy_bitmap_from_pixmap(
bus: &MacMemoryBus,
pm_ptr: u32,
) -> Option<CachedCopyBitmapInfo> {
if pm_ptr == 0 || bus.get_alloc_size(pm_ptr).is_none() {
return None;
}
Some(CachedCopyBitmapInfo {
base: Self::offscreen_pixmap_base_ptr(bus, pm_ptr),
row_bytes: (bus.read_word(pm_ptr + 4) & 0x3FFF) as u32,
bounds_top: bus.read_word(pm_ptr + 6) as i16,
bounds_left: bus.read_word(pm_ptr + 8) as i16,
bounds_bottom: bus.read_word(pm_ptr + 10) as i16,
bounds_right: bus.read_word(pm_ptr + 12) as i16,
pixel_size: bus.read_word(pm_ptr + 32) as u32,
ctab_handle: bus.read_long(pm_ptr + 42),
})
}
fn cache_portbits_pixmap_handle(&mut self, bus: &MacMemoryBus, bits_ptr: u32, pm_handle: u32) {
if bits_ptr == 0 {
return;
}
if let Some(pm_ptr) = Self::pixmap_ptr_from_handle(bus, pm_handle) {
if let Some(info) = Self::cached_copy_bitmap_from_pixmap(bus, pm_ptr) {
self.disposed_gworld_portbits.insert(bits_ptr, info);
}
}
}
pub(super) fn offscreen_pixmap_base_handle(bus: &MacMemoryBus, pm_ptr: u32) -> u32 {
if pm_ptr == 0 {
return 0;
}
let base_field = bus.read_long(pm_ptr);
if base_field == 0 {
return 0;
}
// Imaging With QuickDraw 1994 pp. 6-38..6-39: an offscreen PixMap's
// baseAddr stores a movable-memory handle, while an onscreen PixMap's
// baseAddr stores the direct pixel pointer.
if bus.get_alloc_size(base_field) == Some(4) {
base_field
} else {
0
}
}
/// ScrollRect's move for a colour port, a row span at a time. The moved
/// spans go through `copy_detail_rows`, which carries retained text as
/// the per-pixel copy would (it snapshots every source row first, so the
/// overlap is exact in any direction); the exposed strip then takes the
/// background pattern byte by byte. `pixels` is the rect as read before
/// the scroll, `size.0` bytes per row. Returns false, having written
/// nothing, when the row copy declines.
fn scroll_color_rows(
&mut self,
bus: &mut MacMemoryBus,
scroll: ScrollRows,
pixels: &[u8],
) -> bool {
let ScrollRows {
base,
row_bytes,
origin: (y0, x0),
canvas: (top, left),
size: (w, h),
delta: (dh, dv),
background,
} = scroll;
let (dh, dv) = (i32::from(dh), i32::from(dv));
let moved_len = (w - dh.abs()).max(0) as usize;
let (src_col, dst_col) = if dh >= 0 { (0, dh) } else { (-dh, 0) };
let address = |row: i32, col: i32| base + (y0 + row as u32) * row_bytes + x0 + col as u32;
let mut rows = Vec::new();
let mut moved = Vec::new();
if moved_len > 0 {
for dst_row in 0..h {
let src_row = dst_row - dv;
if (0..h).contains(&src_row) {
rows.push((address(src_row, src_col), address(dst_row, dst_col)));
moved.extend_from_slice(
&pixels[(src_row * w + src_col) as usize..][..moved_len],
);
}
}
}
if rows.is_empty() {
return false;
}
let mut changed: u64 = rows
.iter()
.zip(moved.chunks_exact(moved_len))
.map(|(&(_, to), new)| {
let old = bus.read_bytes(to, moved_len);
old.iter().zip(new).filter(|(old, new)| old != new).count() as u64
})
.sum();
if !bus.copy_detail_rows(&rows, &moved, moved_len, None) {
if bus.presentation.is_some() {
return false;
}
// Without retained text the moved spans are plain stores.
for (&(_, to), row) in rows.iter().zip(moved.chunks_exact(moved_len)) {
bus.write_bytes(to, row);
}
}
for dst_row in 0..h {
let src_row = dst_row - dv;
let canvas_y = (i32::from(top) + dst_row) as usize;
for dst_col_byte in 0..w {
if (0..h).contains(&src_row) && (0..w).contains(&(dst_col_byte - dh)) {
continue;
}
let canvas_x = (left + dst_col_byte as i16) as usize;
let byte = if background[canvas_y & 7] & (1 << (7 - (canvas_x & 7))) != 0 {
0xFF
} else {
0x00
};
let addr = address(dst_row, dst_col_byte);
if bus.read_byte(addr) != byte {
changed += 1;
}
bus.write_byte(addr, byte);
}
}
self.debug_scroll_rect_changed_byte_count =
self.debug_scroll_rect_changed_byte_count.saturating_add(changed);
self.debug_scroll_rect_last_changed_bytes =
self.debug_scroll_rect_last_changed_bytes.saturating_add(changed as _);
true
}
pub(super) fn offscreen_pixmap_base_ptr(bus: &MacMemoryBus, pm_ptr: u32) -> u32 {
if pm_ptr == 0 {
return 0;
}
let base_field = bus.read_long(pm_ptr);
if base_field == 0 {
return 0;
}
if bus.get_alloc_size(base_field) == Some(4) {
bus.read_long(base_field)
} else {
base_field
}
}
fn indexed_ctab_entry_count(depth: u32) -> u32 {
match depth {
0 => 1,
1..=7 => 1u32 << depth,
_ => 256,
}
}
fn allocate_color_table_handle(
&mut self,
bus: &mut MacMemoryBus,
depth: u32,
source_ctab_handle: u32,
ct_flags: u16,
) -> u32 {
let entry_count = Self::indexed_ctab_entry_count(depth);
let ctab_ptr = bus.alloc(8 + entry_count * 8);
let ctab_handle = bus.alloc(4);
bus.write_long(ctab_handle, ctab_ptr);
self.overwrite_color_table_handle(bus, ctab_handle, depth, source_ctab_handle, ct_flags);
ctab_handle
}
fn allocate_gworld_color_table_handle(
&mut self,
bus: &mut MacMemoryBus,
depth: u32,
source_ctab_handle: u32,
ct_flags: u16,
) -> u32 {
if depth == 4 && source_ctab_handle == 0 {
return self.allocate_color_table_handle_with_clut(
bus,
depth,
&Self::standard_mac_4bpp_gworld_clut(),
ct_flags,
);
}
self.allocate_color_table_handle(bus, depth, source_ctab_handle, ct_flags)
}
fn allocate_color_table_handle_with_clut(
&mut self,
bus: &mut MacMemoryBus,
depth: u32,
clut: &[[u16; 3]; 256],
ct_flags: u16,
) -> u32 {
let entry_count = Self::indexed_ctab_entry_count(depth);
let ctab_ptr = bus.alloc(8 + entry_count * 8);
let ctab_handle = bus.alloc(4);
bus.write_long(ctab_handle, ctab_ptr);
let _ = self.overwrite_color_table_handle_with_clut(bus, ctab_handle, clut, ct_flags);
ctab_handle
}
pub(crate) fn install_application_clut(
&mut self,
bus: &mut MacMemoryBus,
clut: [[u16; 3]; 256],
) {
self.device_clut.replace(clut);
self.color_manager_clut.replace(clut);
let gdh = self.ensure_main_gdevice(bus);
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
let ctab_ptr = if ctab_handle != 0 {
bus.read_long(ctab_handle)
} else {
0
};
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let _ = self.overwrite_color_table_handle_with_clut(bus, ctab_handle, &clut, ct_flags);
self.sync_canonical_offscreen_ctabs_to_clut(bus, &clut);
}
fn overwrite_color_table_handle(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
depth: u32,
source_ctab_handle: u32,
ct_flags: u16,
) -> Option<u32> {
if ctab_handle == 0 {
return None;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return None;
}
let entry_capacity = bus.get_alloc_size(ctab_ptr).unwrap_or(0).saturating_sub(8) / 8;
let entry_count = Self::indexed_ctab_entry_count(depth).min(entry_capacity.max(1));
let clut = if source_ctab_handle == 0 {
Self::standard_mac_indexed_clut(depth as u16)
.map(|(clut, _)| clut)
.unwrap_or_else(|| self.read_ctab_handle_clut(bus, 0))
} else {
self.read_ctab_handle_clut(bus, source_ctab_handle)
};
// Mirror canonical-CLUT -> seed=depth precedence in
// `overwrite_color_table_handle_with_clut` for the variant
// that takes a source CTab handle. When the resulting content
// equals the standard N-bpp palette, Executor's depth
// convention (qGWorld.cpp:217) requires ctSeed = depth.
// Only active for 8bpp; other depths retain counter semantics.
let new_is_canonical_8 = depth == 8 && clut == Self::standard_mac_8bpp_clut();
let (seed, label) = if new_is_canonical_8 {
(8u32, "overwrite_color_table_handle/canonical=8")
} else {
(self.next_color_table_seed(), "overwrite_color_table_handle")
};
bus.write_long(ctab_ptr, seed);
self.trace_ctab_seed_write(ctab_ptr, seed, label);
bus.write_word(ctab_ptr + 4, ct_flags);
bus.write_word(ctab_ptr + 6, (entry_count - 1) as u16);
for index in 0..entry_count {
let entry = ctab_ptr + 8 + index * 8;
let rgb = clut[index as usize];
bus.write_word(entry, index as u16);
bus.write_word(entry + 2, rgb[0]);
bus.write_word(entry + 4, rgb[1]);
bus.write_word(entry + 6, rgb[2]);
}
Some(seed)
}
fn overwrite_color_table_handle_with_clut(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
clut: &[[u16; 3]; 256],
ct_flags: u16,
) -> Option<u32> {
if ctab_handle == 0 {
return None;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return None;
}
let entry_capacity = bus.get_alloc_size(ctab_ptr).unwrap_or(0).saturating_sub(8) / 8;
let entry_count = 256u32.min(entry_capacity.max(1));
// Executor's ROMlib_copy_ctab (qColorutil.cpp:139-149) moves the
// whole source CTab buffer, ctSeed included, so an offscreen
// GWorld whose CTab content comes from the current GDevice ends
// up sharing the GDevice's seed. Systemless used to unconditionally
// allocate a fresh seed here, which broke the CopyBits 8→8 gate
// (quickdraw.rs:1971-1988) even when the offscreen CLUT was
// byte-identical to the GDevice CLUT. Inherit the GDevice CTab
// seed when the supplied `clut` matches the current GDevice's
// CTab CLUT exactly; fall back to a fresh seed otherwise.
let gdh_ctab_handle = self.current_gdevice_ctab_handle(bus);
let gdh_seed = Self::ctab_seed(bus, gdh_ctab_handle).unwrap_or(0);
let new_is_canonical = *clut == Self::standard_mac_8bpp_clut();
let seed = if new_is_canonical {
// Executor qGWorld.cpp:217 depth convention: a CTab
// initialised with the canonical N-bpp palette carries
// ctSeed=N. Applies regardless of what was at this handle
// before.
8
} else if gdh_seed != 0 && self.read_ctab_handle_clut(bus, gdh_ctab_handle) == *clut {
// Executor ROMlib_copy_ctab (qColorutil.cpp:139-149)
// semantics: an offscreen CTab whose content matches
// the GDevice's inherits the GDevice seed.
gdh_seed
} else {
self.next_color_table_seed()
};
bus.write_long(ctab_ptr, seed);
self.trace_ctab_seed_write(
ctab_ptr,
seed,
if new_is_canonical {
"overwrite_with_clut/canonical=8"
} else if seed == gdh_seed {
"overwrite_with_clut/inherited"
} else {
"overwrite_with_clut/fresh"
},
);
bus.write_word(ctab_ptr + 4, ct_flags);
bus.write_word(ctab_ptr + 6, (entry_count - 1) as u16);
for index in 0..entry_count {
let entry = ctab_ptr + 8 + index * 8;
let rgb = clut[index as usize];
bus.write_word(entry, index as u16);
bus.write_word(entry + 2, rgb[0]);
bus.write_word(entry + 4, rgb[1]);
bus.write_word(entry + 6, rgb[2]);
}
Some(seed)
}
fn sync_canonical_offscreen_ctabs_to_clut(
&mut self,
bus: &mut MacMemoryBus,
clut: &[[u16; 3]; 256],
) {
let screen_ctab_handle = if self.main_gdevice_handle != 0 {
Self::gdevice_ctab_handle(bus, self.main_gdevice_handle)
} else {
0
};
// Sort port iteration so iteration order is deterministic across
// runs. HashMap.keys()/HashSet.iter() return in randomized order;
// the loop below writes CLUTs into guest memory, so iteration
// order can subtly affect what the game reads later.
let mut all_ports: Vec<u32> = self
.gworld_devices
.keys()
.copied()
.chain(self.cport_ports.iter().copied())
.collect();
all_ports.sort_unstable();
for port in all_ports {
let pixmap_handle = bus.read_long(port + 2);
if pixmap_handle == 0 {
continue;
}
let pixmap_ptr = bus.read_long(pixmap_handle);
if pixmap_ptr == 0 || bus.read_word(pixmap_ptr + 32) != 8 {
continue;
}
let ctab_handle = bus.read_long(pixmap_ptr + 42);
if ctab_handle == 0 || ctab_handle == screen_ctab_handle {
continue;
}
let current_clut = self.read_ctab_handle_clut(bus, ctab_handle);
if current_clut == *clut
|| (!Self::uses_canonical_system_8bpp_clut(¤t_clut)
&& !Self::uses_scaled_canonical_system_8bpp_clut(¤t_clut))
{
continue;
}
let ctab_ptr = bus.read_long(ctab_handle);
let ct_flags = if ctab_ptr != 0 {
bus.read_word(ctab_ptr + 4)
} else {
0x8000
};
let _ = self.overwrite_color_table_handle_with_clut(bus, ctab_handle, clut, ct_flags);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] SyncOffscreenCtab tick={} port=${:08X} ctab=${:08X} rgb16=({:04X},{:04X},{:04X}) rgb42=({:04X},{:04X},{:04X}) rgb128=({:04X},{:04X},{:04X})",
self.current_tick(),
port,
ctab_handle,
clut[16][0],
clut[16][1],
clut[16][2],
clut[42][0],
clut[42][1],
clut[42][2],
clut[128][0],
clut[128][1],
clut[128][2],
);
}
// Record per-port sync events so the trap-sequence diff sees the
// same sync_offscreen_ctab events the reference recorder emits.
let _ = self.record_trace_event(
bus,
0,
"sync_offscreen_ctab",
Self::trace_field_map(&[
("port", format!("{:08X}", port)),
("ctab", format!("{:08X}", ctab_handle)),
(
"rgb16",
format!(
"{:04X},{:04X},{:04X}",
clut[16][0], clut[16][1], clut[16][2]
),
),
(
"rgb42",
format!(
"{:04X},{:04X},{:04X}",
clut[42][0], clut[42][1], clut[42][2]
),
),
(
"rgb128",
format!(
"{:04X},{:04X},{:04X}",
clut[128][0], clut[128][1], clut[128][2]
),
),
]),
false,
);
}
}
fn create_offscreen_gdevice(
&mut self,
bus: &mut MacMemoryBus,
pixmap_handle: u32,
top: i16,
left: i16,
bottom: i16,
right: i16,
) -> u32 {
let gd = bus.alloc(50);
bus.write_word(gd, 0);
bus.write_word(gd + 2, 0);
bus.write_word(gd + 4, 0);
bus.write_long(gd + 6, 0);
bus.write_word(gd + 10, 4);
bus.write_long(gd + 12, 0);
bus.write_long(gd + 16, 0);
// Color offscreen device, initialized in RAM, but not a screen device.
// Inside Macintosh Volume VI, 21-14 to 21-15
bus.write_word(gd + 20, (1 << 0) | (1 << 10) | (1 << 12));
bus.write_long(gd + 22, pixmap_handle);
bus.write_long(gd + 26, 0);
bus.write_long(gd + 30, 0);
bus.write_word(gd + 34, top as u16);
bus.write_word(gd + 36, left as u16);
bus.write_word(gd + 38, bottom as u16);
bus.write_word(gd + 40, right as u16);
bus.write_long(gd + 42, 0);
let gd_handle = bus.alloc(4);
bus.write_long(gd_handle, gd);
let pixmap = bus.read_long(pixmap_handle);
let ctab_handle = if pixmap != 0 {
bus.read_long(pixmap + 42)
} else {
0
};
let itable_handle = Self::ensure_gdevice_itable_handle(bus, gd_handle);
self.make_inverse_table(bus, ctab_handle, itable_handle, 4);
gd_handle
}
fn new_screen_buffer_common(
&mut self,
bus: &mut MacMemoryBus,
global_rect_ptr: u32,
purgeable: bool,
gdh_out_ptr: u32,
offscreen_pixmap_out_ptr: u32,
use_temp_mem: bool,
) -> u32 {
let _ = use_temp_mem;
if global_rect_ptr == 0 || gdh_out_ptr == 0 || offscreen_pixmap_out_ptr == 0 {
return (-50i32) as u32;
}
let top = bus.read_word(global_rect_ptr) as i16;
let left = bus.read_word(global_rect_ptr + 2) as i16;
let bottom = bus.read_word(global_rect_ptr + 4) as i16;
let right = bus.read_word(global_rect_ptr + 6) as i16;
let width = ((right as i32) - (left as i32)).max(1) as u32;
let height = ((bottom as i32) - (top as i32)).max(1) as u32;
let gdh = self.ensure_main_gdevice(bus);
let gd = bus.read_long(gdh);
let gd_pm_handle = if gd != 0 { bus.read_long(gd + 22) } else { 0 };
let gd_pm_ptr = if gd_pm_handle != 0 {
bus.read_long(gd_pm_handle)
} else {
0
};
if gd_pm_ptr == 0 {
return C_NO_MEM_ERR;
}
let depth = bus.read_word(gd_pm_ptr + 32) as u32;
let ctab_handle = bus.read_long(gd_pm_ptr + 42);
let row_bytes = (width * depth).div_ceil(32) * 4;
let pixel_bytes = row_bytes.saturating_mul(height);
let pixel_buf = bus.alloc(pixel_bytes);
if pixel_buf == 0 && pixel_bytes > 0 {
return C_NO_MEM_ERR;
}
let pixel_buf_handle = bus.alloc(4);
if pixel_buf_handle == 0 {
return C_NO_MEM_ERR;
}
bus.write_long(pixel_buf_handle, pixel_buf);
self.track_handle_ptr(pixel_buf, pixel_buf_handle);
let pixmap = bus.alloc(50);
if pixmap == 0 {
return C_NO_MEM_ERR;
}
bus.write_long(pixmap, pixel_buf_handle);
bus.write_word(pixmap + 4, (row_bytes as u16) | 0x8000);
bus.write_word(pixmap + 6, top as u16);
bus.write_word(pixmap + 8, left as u16);
bus.write_word(pixmap + 10, bottom as u16);
bus.write_word(pixmap + 12, right as u16);
bus.write_word(pixmap + 14, 0);
bus.write_word(pixmap + 16, 0);
bus.write_long(pixmap + 18, 0);
bus.write_long(pixmap + 22, 0x00480000);
bus.write_long(pixmap + 26, 0x00480000);
bus.write_word(pixmap + 30, 0);
bus.write_word(pixmap + 32, depth as u16);
bus.write_word(pixmap + 34, 1);
bus.write_word(pixmap + 36, depth as u16);
bus.write_long(pixmap + 38, 0);
bus.write_long(pixmap + 42, ctab_handle);
bus.write_long(pixmap + 46, 0);
let pixmap_handle = bus.alloc(4);
if pixmap_handle == 0 {
return C_NO_MEM_ERR;
}
bus.write_long(pixmap_handle, pixmap);
self.gworld_pixel_states
.set_quickdraw_pixel_state(pixmap_handle, if purgeable { 1 << 6 } else { 0 });
bus.write_long(gdh_out_ptr, gdh);
bus.write_long(offscreen_pixmap_out_ptr, pixmap_handle);
0
}
fn dispose_screen_buffer(&mut self, bus: &mut MacMemoryBus, offscreen_pixmap: u32) {
if offscreen_pixmap == 0 {
return;
}
let pixmap_ptr = bus.read_long(offscreen_pixmap);
if pixmap_ptr != 0 {
let pixel_buf = Self::offscreen_pixmap_base_ptr(bus, pixmap_ptr);
let stored_pixel_buf_handle = Self::offscreen_pixmap_base_handle(bus, pixmap_ptr);
let pixel_buf_handle = if stored_pixel_buf_handle != 0 {
stored_pixel_buf_handle
} else {
self.handle_for_ptr(pixel_buf)
.filter(|&handle| bus.read_long(handle) == pixel_buf)
.unwrap_or(0)
};
if pixel_buf_handle != 0 {
self.untrack_handle_ptr(pixel_buf);
Self::free_handle_and_target(bus, pixel_buf_handle);
} else {
if pixel_buf != 0 {
bus.free(pixel_buf);
}
}
bus.write_long(offscreen_pixmap, 0);
bus.free(pixmap_ptr);
}
// Pixel-state entries are process-owned but non-owning. The native
// adapter may still retain a local record for this PixMapHandle, so
// disposal cannot remove shared state until process-wide liveness is
// proven. Allocation ownership remains local to this adapter.
bus.free(offscreen_pixmap);
}
pub(super) fn current_gdevice_ctab_handle(&self, bus: &MacMemoryBus) -> u32 {
let gdh = if *self.current_gdevice != 0 {
*self.current_gdevice
} else {
self.main_gdevice_handle
};
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
if ctab_handle != 0 || gdh == self.main_gdevice_handle || self.main_gdevice_handle == 0 {
ctab_handle
} else {
Self::gdevice_ctab_handle(bus, self.main_gdevice_handle)
}
}
fn active_seeded_screen_clut_for_offscreen_clone(
&self,
source_gdevice: u32,
explicit_ctab_handle: u32,
) -> Option<[[u16; 3]; 256]> {
if explicit_ctab_handle != 0
|| source_gdevice != self.main_gdevice_handle
|| self.current_tick() >= self.seeded_picture_palette_until_tick
|| Self::uses_canonical_system_8bpp_clut(&self.seeded_picture_palette)
{
None
} else {
Some(self.seeded_picture_palette)
}
}
fn free_handle_and_target(bus: &mut MacMemoryBus, handle: u32) {
if handle == 0 {
return;
}
let ptr = bus.read_long(handle);
if ptr != 0 {
bus.free(ptr);
}
// Clear the master pointer cell before releasing it so a later
// RecoverHandle scan cannot rediscover a stale owner for the same
// payload address.
bus.write_long(handle, 0);
bus.free(handle);
}
fn seed_gworld_pixels_state(&mut self, pmh: u32, newgworld_flags: u32) {
if pmh == 0 {
return;
}
const PIX_PURGE: u32 = 1 << 0;
const KEEP_LOCAL: u32 = 1 << 3;
const PIXELS_PURGEABLE: u32 = 1 << 6;
let mut state = 0;
if (newgworld_flags & PIX_PURGE) != 0 {
state |= PIXELS_PURGEABLE;
}
if (newgworld_flags & KEEP_LOCAL) != 0 {
state |= KEEP_LOCAL;
}
self.gworld_pixel_states
.set_quickdraw_pixel_state(pmh, state);
}
fn gworld_pixels_state(&self, pmh: u32) -> u32 {
self.gworld_pixel_states.quickdraw_pixel_state(pmh)
}
fn set_gworld_pixels_state(&mut self, pmh: u32, state: u32) {
if pmh == 0 {
return;
}
const KEEP_LOCAL: u32 = 1 << 3;
const PIXELS_PURGEABLE: u32 = 1 << 6;
const PIXELS_LOCKED: u32 = 1 << 7;
let existing = self.gworld_pixels_state(pmh);
let masked = state & (KEEP_LOCAL | PIXELS_PURGEABLE | PIXELS_LOCKED);
let preserved = existing & !(PIXELS_PURGEABLE | PIXELS_LOCKED);
self.gworld_pixel_states
.set_quickdraw_pixel_state(pmh, preserved | masked);
}
fn set_gworld_pixels_purgeable(&mut self, pmh: u32, purgeable: bool) {
if pmh == 0 {
return;
}
const PIXELS_PURGEABLE: u32 = 1 << 6;
let mut state = self.gworld_pixels_state(pmh);
if purgeable {
state |= PIXELS_PURGEABLE;
} else {
state &= !PIXELS_PURGEABLE;
}
self.set_gworld_pixels_state(pmh, state);
}
fn lock_gworld_pixels(&mut self, bus: &mut MacMemoryBus, pmh: u32) -> bool {
if pmh == 0 {
return true;
}
let pm = bus.read_long(pmh);
if pm != 0 {
let base_handle = Self::offscreen_pixmap_base_handle(bus, pm);
if base_handle != 0 {
let base = bus.read_long(base_handle);
if base == 0 {
return false;
}
self.track_handle_ptr(base, base_handle);
bus.write_long(pm, base);
}
}
const PIXELS_LOCKED: u32 = 1 << 7;
let state = self.gworld_pixels_state(pmh) | PIXELS_LOCKED;
self.set_gworld_pixels_state(pmh, state);
true
}
fn unlock_gworld_pixels(&mut self, bus: &mut MacMemoryBus, pmh: u32) {
if pmh == 0 {
return;
}
let pm = bus.read_long(pmh);
if pm != 0 {
let base = Self::offscreen_pixmap_base_ptr(bus, pm);
let base_handle = self.handle_for_ptr(base)
.filter(|&handle| bus.read_long(handle) == base)
.unwrap_or(0);
if base_handle != 0 {
bus.write_long(pm, base_handle);
}
}
const PIXELS_LOCKED: u32 = 1 << 7;
let state = self.gworld_pixels_state(pmh) & !PIXELS_LOCKED;
self.set_gworld_pixels_state(pmh, state);
}
fn dispose_gworld_port<C: CpuOps>(&mut self, cpu: &mut C, bus: &mut MacMemoryBus, port: u32) {
if port == 0 {
return;
}
let attached_gdevice = self.gworld_devices.remove(&port).unwrap_or(0);
let pixmap_handle = bus.read_long(port + 2);
// The shared state registry does not own the PixMap allocation. Leave
// this entry intact because the native adapter may still represent the
// same handle; disposal ownership is intentionally out of scope.
let owns_attached_gdevice = if attached_gdevice != 0 {
let gd_ptr = bus.read_long(attached_gdevice);
gd_ptr
.checked_add(22)
.map(|addr| bus.read_long(addr) == pixmap_handle)
.unwrap_or(false)
} else {
false
};
if *self.current_port == port {
let main_gdevice = self.ensure_main_gdevice(bus);
let fallback_port = self.ensure_color_window_manager_port(bus);
self.set_current_port_state(bus, cpu, fallback_port, Some(main_gdevice));
} else if owns_attached_gdevice && attached_gdevice == *self.current_gdevice {
let main_gdevice = self.ensure_main_gdevice(bus);
if *self.current_port != 0 {
self.set_current_port_state(bus, cpu, *self.current_port, Some(main_gdevice));
} else {
self.current_gdevice
.with_mut(|current_gdevice| *current_gdevice = main_gdevice);
}
}
// IM:VI 1991 p. 21-19 / IWQD 1994 p. 6-25: DisposeGWorld tears down
// the offscreen port structure and any GDevice created for it. Keep
// the PixMap / color table / pixel image allocations alive as the HLE
// compatibility compromise: some games retain those raw guest pointers
// after disposal, and eagerly recycling them aliases later scratch
// buffers into stale restore paths.
if pixmap_handle != 0 {
// Compatibility path for stale `&gworld->portBits` pointers:
// preserve a mapping from the disposed `port+2` address to the
// still-live PixMap pointer so resolve_copy_bitmap can recover.
self.cache_portbits_pixmap_handle(bus, port + 2, pixmap_handle);
}
Self::free_handle_and_target(bus, bus.read_long(port + 24));
Self::free_handle_and_target(bus, bus.read_long(port + 28));
if owns_attached_gdevice {
let gd_ptr = bus.read_long(attached_gdevice);
if gd_ptr != 0 {
bus.free(gd_ptr);
}
bus.free(attached_gdevice);
}
bus.free(port);
self.cport_ports.remove(&port);
self.cport_original_pixmaps.remove(&port);
if self.manual_cport_presented_port == port {
self.manual_cport_presented_port = 0;
self.manual_cport_screen_witness.clear();
}
self.port_draw_states.remove(&port);
self.resolved_port_color_fields.remove(&port);
self.quickdraw_op_colors.remove_quickdraw_op_color(port);
self.quickdraw_hilite_colors
.remove_quickdraw_hilite_color(port);
}
pub(super) fn effective_destination_ctab_handle(
&self,
base: u32,
row_bytes: u32,
pixel_size: u32,
ctab_handle: u32,
) -> u32 {
if base == self.screen_mode.0
&& row_bytes == self.screen_mode.1
&& pixel_size == u32::from(self.screen_mode.4)
{
0
} else {
ctab_handle
}
}
fn copy_bits_destination_ctab_handle(
&self,
bus: &MacMemoryBus,
current_port: u32,
dst_info: &CopyBitmapInfo,
) -> u32 {
let current_device_ctab_handle = self.current_gdevice_ctab_handle(bus);
if current_device_ctab_handle == 0 {
return dst_info.ctab_handle;
}
// Keep the screen sentinel so indexed destination lookup can resolve
// the main GDevice ColorTable at the point of color matching. It may
// fall back to the private Color Manager shadow only when no usable
// guest screen table exists.
if dst_info.base == self.screen_mode.0
&& dst_info.row_bytes == self.screen_mode.1
&& dst_info.pixel_size == u32::from(self.screen_mode.4)
{
return 0;
}
// For non-screen destinations: QuickDraw uses the current GDevice
// for palette mapping when the destination is the current port.
// If we're blitting into some other PixMap (for example, copying
// an offscreen world while the offscreen port is current), use
// that destination bitmap's table instead.
let current_bits_ptr = self.bitmap_ptr_for_port(bus, current_port);
if current_bits_ptr != 0 {
let current_info = self.resolve_copy_bitmap(bus, current_bits_ptr);
let dst_is_current_port = current_info.base == dst_info.base
&& current_info.row_bytes == dst_info.row_bytes
&& current_info.bounds_top == dst_info.bounds_top
&& current_info.bounds_left == dst_info.bounds_left
&& current_info.bounds_bottom == dst_info.bounds_bottom
&& current_info.bounds_right == dst_info.bounds_right
&& current_info.pixel_size == dst_info.pixel_size;
if dst_is_current_port {
return current_device_ctab_handle;
}
}
{
self.effective_destination_ctab_handle(
dst_info.base,
dst_info.row_bytes,
dst_info.pixel_size,
dst_info.ctab_handle,
)
}
}
pub(crate) fn set_current_port_state<C: CpuOps>(
&mut self,
bus: &mut MacMemoryBus,
cpu: &mut C,
port: u32,
gdh: Option<u32>,
) {
self.save_current_port_draw_state();
let resolved_gdh = gdh.unwrap_or_else(|| self.gdevice_for_port(bus, port));
self
.current_port
.with_mut(|current_port| *current_port = port);
self.current_gdevice
.with_mut(|current_gdevice| *current_gdevice = resolved_gdh);
// Re-selecting a port re-arms QDDone for that port.
self.qddone_seen_ports.remove(&port);
bus.write_long(crate::memory::globals::addr::THE_PORT, port);
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
if global_ptr != 0 {
bus.write_long(global_ptr, port);
}
if port != 0 {
self.restore_port_draw_state(bus, port);
}
}
fn gdevice_for_port(&mut self, bus: &mut MacMemoryBus, port: u32) -> u32 {
if port == 0 {
return 0;
}
self.gworld_devices
.get(&port)
.copied()
.unwrap_or_else(|| self.ensure_main_gdevice(bus))
}
fn save_current_port_draw_state(&mut self) {
if *self.current_port == 0 {
return;
}
self.port_draw_states
.insert(*self.current_port, self.current_draw_state());
}
pub(crate) fn current_draw_state(&self) -> PortDrawState {
PortDrawState {
fg_color: self.fg_color,
bg_color: self.bg_color,
pm_fg_color: self.pm_fg_color,
pm_bg_color: self.pm_bg_color,
bk_pat: self.bk_pat,
pn_loc: self.pn_loc,
pn_size: self.pn_size,
pn_mode: self.pn_mode,
pn_pat: self.pn_pat,
pn_vis: self.pn_vis,
tx_font: self.tx_font,
tx_face: self.tx_face,
tx_mode: self.tx_mode,
tx_size: self.tx_size,
}
}
fn restore_port_draw_state(&mut self, bus: &mut MacMemoryBus, port: u32) {
if self.load_port_draw_state(bus, port) {
self.port_draw_states
.insert(port, self.current_draw_state());
return;
}
if !self.port_allows_draw_state_memory_sync(bus, port) {
return;
}
let state = self
.port_draw_states
.get(&port)
.copied()
.unwrap_or_default();
self.fg_color = state.fg_color;
self.bg_color = state.bg_color;
self.pm_fg_color = state.pm_fg_color;
self.pm_bg_color = state.pm_bg_color;
self.bk_pat = state.bk_pat;
self.pn_loc = state.pn_loc;
self.pn_size = state.pn_size;
self.pn_mode = state.pn_mode;
self.pn_pat = state.pn_pat;
self.pn_vis = state.pn_vis;
self.tx_font = state.tx_font;
self.tx_face = state.tx_face;
self.tx_mode = state.tx_mode;
self.tx_size = state.tx_size;
// SetPort selects an existing record; initialization belongs to
// OpenPort/InitPort. Restoring cached host state must not overwrite
// guest fields when this record cannot be decoded as a CGrafPort.
}
fn write_port_op_color(&mut self, bus: &mut MacMemoryBus, port: u32, color: (u16, u16, u16)) {
let port_range_mapped = port.checked_add(14).is_some_and(|end| {
end <= bus.ram_size()
|| (port..end).all(|address| bus.is_foreign_ordinary_sparse_address(address))
});
if port == 0 || !port_range_mapped || (bus.read_word(port + 6) & 0xC000) != 0xC000 {
return;
}
let graf_vars_handle = bus.read_long(port + 8);
if Self::handle_points_to_guest_range(bus, graf_vars_handle, 6) {
let graf_vars = bus.read_long(graf_vars_handle);
bus.write_word(graf_vars, color.0);
bus.write_word(graf_vars + 2, color.1);
bus.write_word(graf_vars + 4, color.2);
}
// Keep a process-owned per-port index for static records without a
// valid GrafVars handle. A valid guest GrafVars record remains the
// authoritative read path above.
self.quickdraw_op_colors
.set_quickdraw_op_color(port, color);
}
/// Read the current Color QuickDraw port's highlight color. A valid
/// guest GrafVars record is authoritative; static ports use the
/// process-owned per-port fallback, then the default HiliteRGB value.
/// Inside Macintosh: Imaging With QuickDraw (1994), pp. 4-62 and 4-64.
pub(crate) fn current_hilite_color(&self, bus: &MacMemoryBus) -> (u16, u16, u16) {
self.hilite_color_for_port(bus, *self.current_port)
}
pub(crate) fn hilite_color_for_port(&self, bus: &MacMemoryBus, port: u32) -> (u16, u16, u16) {
self.port_hilite_color_from_graf_vars(bus, port)
.or_else(|| self.quickdraw_hilite_colors.quickdraw_hilite_color(port))
.unwrap_or(DEFAULT_QUICKDRAW_HILITE_COLOR)
}
fn port_hilite_color_from_graf_vars(
&self,
bus: &MacMemoryBus,
port: u32,
) -> Option<(u16, u16, u16)> {
let port_range_mapped = port.checked_add(14).is_some_and(|end| {
end <= bus.ram_size()
|| (port..end).all(|address| bus.is_foreign_ordinary_sparse_address(address))
});
if port == 0
|| !port_range_mapped
|| (bus.read_word(port + 6) & 0xC000) != 0xC000
{
return None;
}
let graf_vars_handle = bus.read_long(port + 8);
if !Self::handle_points_to_guest_range(bus, graf_vars_handle, 12) {
return None;
}
let graf_vars = bus.read_long(graf_vars_handle);
Some((
bus.read_word(graf_vars + 6),
bus.read_word(graf_vars + 8),
bus.read_word(graf_vars + 10),
))
}
pub(super) fn write_port_hilite_color(
&mut self,
bus: &mut MacMemoryBus,
port: u32,
color: (u16, u16, u16),
) {
let port_range_mapped = port.checked_add(14).is_some_and(|end| {
end <= bus.ram_size()
|| (port..end).all(|address| bus.is_foreign_ordinary_sparse_address(address))
});
if port == 0 || !port_range_mapped || (bus.read_word(port + 6) & 0xC000) != 0xC000 {
return;
}
let graf_vars_handle = bus.read_long(port + 8);
if Self::handle_points_to_guest_range(bus, graf_vars_handle, 12) {
let graf_vars = bus.read_long(graf_vars_handle);
bus.write_word(graf_vars + 6, color.0);
bus.write_word(graf_vars + 8, color.1);
bus.write_word(graf_vars + 10, color.2);
}
// Keep a process-owned per-port index for static records without a
// valid GrafVars handle. A valid guest GrafVars record remains the
// authoritative read path above.
self.quickdraw_hilite_colors
.set_quickdraw_hilite_color(port, color);
}
fn capture_port_region(
bus: &MacMemoryBus,
port: u32,
offset: u32,
) -> Option<super::dispatch::PortRegionSnapshot> {
let handle = bus.read_long(port + offset);
if !Self::guest_range_in_ram(bus, handle, 4) {
return None;
}
let ptr = bus.read_long(handle);
if !Self::guest_range_in_ram(bus, ptr, 2) {
return None;
}
let len = u32::from(bus.read_word(ptr));
if len < 10 || !Self::guest_range_in_ram(bus, ptr, len) {
return None;
}
let bytes = (0..len).map(|i| bus.read_byte(ptr + i)).collect();
Some(super::dispatch::PortRegionSnapshot { handle, bytes })
}
pub(crate) fn capture_current_port_state(
&self,
bus: &MacMemoryBus,
) -> super::dispatch::PortStateSnapshot {
let port = *self.current_port;
let mut port_state_bytes = [0; 56];
if Self::guest_range_in_ram(bus, port.wrapping_add(32), port_state_bytes.len() as u32) {
for (i, byte) in port_state_bytes.iter_mut().enumerate() {
*byte = bus.read_byte(port + 32 + i as u32);
}
}
super::dispatch::PortStateSnapshot {
port,
gdevice: *self.current_gdevice,
draw_state: self.current_draw_state(),
port_state_bytes,
resolved_color_fields: self.resolved_port_color_fields.get(&port).copied(),
vis_region: Self::capture_port_region(bus, port, 24),
clip_region: Self::capture_port_region(bus, port, 28),
}
}
fn restore_port_region(
bus: &mut MacMemoryBus,
port: u32,
offset: u32,
region: &super::dispatch::PortRegionSnapshot,
) {
bus.write_long(port + offset, region.handle);
let Some(ptr) = Self::ensure_region_capacity(bus, region.handle, region.bytes.len() as u32)
else {
return;
};
for (i, byte) in region.bytes.iter().copied().enumerate() {
bus.write_byte(ptr + i as u32, byte);
}
}
pub(crate) fn restore_current_port_state<C: CpuOps>(
&mut self,
bus: &mut MacMemoryBus,
cpu: &mut C,
snapshot: &super::dispatch::PortStateSnapshot,
) {
self.set_current_port_state(bus, cpu, snapshot.port, Some(snapshot.gdevice));
self.fg_color = snapshot.draw_state.fg_color;
self.bg_color = snapshot.draw_state.bg_color;
self.pm_fg_color = snapshot.draw_state.pm_fg_color;
self.pm_bg_color = snapshot.draw_state.pm_bg_color;
self.bk_pat = snapshot.draw_state.bk_pat;
self.pn_loc = snapshot.draw_state.pn_loc;
self.pn_size = snapshot.draw_state.pn_size;
self.pn_mode = snapshot.draw_state.pn_mode;
self.pn_pat = snapshot.draw_state.pn_pat;
self.pn_vis = snapshot.draw_state.pn_vis;
self.tx_font = snapshot.draw_state.tx_font;
self.tx_face = snapshot.draw_state.tx_face;
self.tx_mode = snapshot.draw_state.tx_mode;
self.tx_size = snapshot.draw_state.tx_size;
self.port_draw_states
.insert(snapshot.port, snapshot.draw_state);
self.sync_port_draw_state(bus, snapshot.port);
for (i, byte) in snapshot.port_state_bytes.iter().copied().enumerate() {
bus.write_byte(snapshot.port + 32 + i as u32, byte);
}
// The saved fgColor/bgColor words and their interpretation must travel
// together. A user-item callback can resolve a legacy blackColor (33)
// into a pixel; retaining that flag after restoring 33 would draw CLUT
// entry 33 instead of black.
if let Some(fields) = snapshot.resolved_color_fields {
self.resolved_port_color_fields
.insert(snapshot.port, fields);
} else {
self.resolved_port_color_fields.remove(&snapshot.port);
}
if let Some(region) = &snapshot.vis_region {
Self::restore_port_region(bus, snapshot.port, 24, region);
}
if let Some(region) = &snapshot.clip_region {
Self::restore_port_region(bus, snapshot.port, 28, region);
}
}
pub(crate) fn prepare_dialog_user_item_port_state<C: CpuOps>(
&mut self,
bus: &mut MacMemoryBus,
cpu: &mut C,
dialog_ptr: u32,
) -> super::dispatch::PortStateSnapshot {
self.set_current_port_state(bus, cpu, dialog_ptr, None);
// Capture the live port state for every callback. In particular,
// visRgn changes when a dialog moves from hidden to visible. Reusing
// the first callback's snapshot would restore an empty hidden-window
// region and clip every later userItem draw. Each callback's matching
// restore keeps its drawing-state changes isolated without carrying
// stale Window Manager regions across callbacks.
// Inside Macintosh Volume I, I-405; Macintosh Toolbox Essentials,
// pp. 6-141 to 6-143.
let snapshot = self.capture_current_port_state(bus);
self.restore_current_port_state(bus, cpu, &snapshot);
snapshot
}
fn load_port_draw_state(&mut self, bus: &MacMemoryBus, port: u32) -> bool {
if port == 0 {
return false;
}
let port_version = bus.read_word(port + 6);
if (port_version & 0xC000) != 0xC000 {
if !self.known_port(port) || !self.port_allows_draw_state_memory_sync(bus, port) {
return false;
}
let state = self.port_draw_states.get(&port).copied().unwrap_or_default();
self.fg_color = state.fg_color;
self.bg_color = state.bg_color;
self.pm_fg_color = state.pm_fg_color;
self.pm_bg_color = state.pm_bg_color;
self.bk_pat = state.bk_pat;
self.pn_loc = state.pn_loc;
self.pn_size = state.pn_size;
self.pn_mode = state.pn_mode;
self.pn_pat = state.pn_pat;
self.pn_vis = state.pn_vis;
self.tx_font = bus.read_word(port + 68) as i16;
self.tx_face = decode_text_face_style(bus.read_word(port + 70));
self.tx_mode = bus.read_word(port + 72) as i16;
self.tx_size = bus.read_word(port + 74) as i16;
return true;
}
if !self.known_port(port) && !Self::looks_like_cgraf_port(bus, port) {
return false;
}
let cached = self
.port_draw_states
.get(&port)
.copied()
.unwrap_or_default();
self.fg_color = (
bus.read_word(port + 36),
bus.read_word(port + 38),
bus.read_word(port + 40),
);
self.bg_color = (
bus.read_word(port + 42),
bus.read_word(port + 44),
bus.read_word(port + 46),
);
self.pm_fg_color = cached.pm_fg_color;
self.pm_bg_color = cached.pm_bg_color;
self.bk_pat = cached.bk_pat;
self.pn_loc = (
bus.read_word(port + 48) as i16,
bus.read_word(port + 50) as i16,
);
self.pn_size = (
bus.read_word(port + 52) as i16,
bus.read_word(port + 54) as i16,
);
self.pn_mode = bus.read_word(port + 56) as i16;
self.pn_pat = cached.pn_pat;
self.pn_vis = bus.read_word(port + 66) as i16;
self.tx_font = bus.read_word(port + 68) as i16;
self.tx_face = decode_text_face_style(bus.read_word(port + 70));
self.tx_mode = bus.read_word(port + 72) as i16;
self.tx_size = bus.read_word(port + 74) as i16;
true
}
fn copy_bits_port_draw_colors(&self, bus: &MacMemoryBus, port: u32) -> ([u16; 3], [u16; 3]) {
if port != 0 {
let port_version = bus.read_word(port + 6);
if (port_version & 0xC000) == 0xC000 {
return (
[
bus.read_word(port + 36),
bus.read_word(port + 38),
bus.read_word(port + 40),
],
[
bus.read_word(port + 42),
bus.read_word(port + 44),
bus.read_word(port + 46),
],
);
}
if let Some(state) = self.port_draw_states.get(&port) {
return (
[state.fg_color.0, state.fg_color.1, state.fg_color.2],
[state.bg_color.0, state.bg_color.1, state.bg_color.2],
);
}
}
(
[self.fg_color.0, self.fg_color.1, self.fg_color.2],
[self.bg_color.0, self.bg_color.1, self.bg_color.2],
)
}
/// Apply the side effects of `SetDepth(depth)` from the Graphics
/// Devices Manager. Updates ScrnBase, screenBits, the QD globals
/// copy of screenBits, the main GDevice PixMap, and
/// `self.screen_mode`, then clears the active framebuffer.
///
/// Imaging With QuickDraw 1994 pp. 5-34..5-35: SetDepth changes
/// the pixel depth and color/B&W mode of the requested device.
/// Systemless currently wires this for the depths its screen renderer
/// supports directly: 1bpp B&W plus 2bpp, 4bpp, and 8bpp indexed color.
/// Returns false without changing the display mode when the target color
/// tables cannot be grown safely.
#[cfg(test)]
pub(crate) fn do_setdepth<C: CpuOps>(
&mut self,
cpu: &mut C,
bus: &mut MacMemoryBus,
depth: u16,
) -> bool {
self.do_setdepth_with_personality(cpu, bus, depth, depth > 1)
}
fn do_setdepth_with_personality<C: CpuOps>(
&mut self,
cpu: &mut C,
bus: &mut MacMemoryBus,
depth: u16,
is_color: bool,
) -> bool {
// SetDepth changes pixel depth and color personality on the current
// device; a prior Display Manager timing switch remains active.
// Imaging With QuickDraw (1994), pp. 5-34--5-35.
self.do_setdepth_with_geometry_and_personality(
cpu,
bus,
depth,
self.screen_mode.2,
self.screen_mode.3,
is_color,
)
}
fn standard_screen_depth_clut(depth: u16, is_color: bool) -> Option<([[u16; 3]; 256], usize)> {
let (mut clut, entry_count) = Self::standard_mac_indexed_clut(depth)?;
if !is_color {
let last = u32::try_from(entry_count.checked_sub(1)?).ok()?;
for (index, color) in clut.iter_mut().take(entry_count).enumerate() {
let index = u32::try_from(index).ok()?;
let component = ((last - index) * u32::from(u16::MAX) / last) as u16;
*color = [component; 3];
}
} else if depth == 2 {
// The standard 2-bit color screen table uses its spare entry for
// the System 7 highlight green; the grayscale personality keeps
// all four entries on the white-to-black ramp. Inside Macintosh:
// Volume VI (1991), pp. 17-17--17-18.
(clut, _) = Self::standard_mac_enhanced_clut(2, (0, 0x8000, 0))?;
}
Some((clut, entry_count))
}
pub(super) fn do_setdepth_with_geometry<C: CpuOps>(
&mut self,
cpu: &mut C,
bus: &mut MacMemoryBus,
depth: u16,
width: u16,
height: u16,
) -> bool {
self.do_setdepth_with_geometry_and_personality(cpu, bus, depth, width, height, depth > 1)
}
fn do_setdepth_with_geometry_and_personality<C: CpuOps>(
&mut self,
cpu: &mut C,
bus: &mut MacMemoryBus,
depth: u16,
width: u16,
height: u16,
is_color: bool,
) -> bool {
let Some(mut row_bytes) = Self::row_bytes_for_depth(width, depth) else {
return false;
};
// A mode switch at the same depth can retain the display device's
// backing pitch even when fewer pixels are visible. Preserve the
// existing stride so direct framebuffer writers and ScreenBits agree.
if depth == self.screen_mode.4
&& (width, height) == self.native_screen_geometry
{
row_bytes = row_bytes.max(self.screen_mode.1);
}
let ram_size = bus.ram_size();
let color_screen_base = ram_size - crate::memory::bus::display_reservation_bytes();
let Some((_, entry_count)) = Self::standard_screen_depth_clut(depth, is_color) else {
return false;
};
if !self.preflight_setdepth_color_tables(bus, color_screen_base, entry_count) {
return false;
}
bus.write_long(0x0824, color_screen_base); // ScrnBase
bus.write_word(crate::memory::globals::addr::SCREEN_ROW, row_bytes as u16);
let sb = crate::memory::globals::addr::SCREEN_BITS;
bus.write_long(sb, color_screen_base);
bus.write_word(sb + 4, row_bytes as u16);
bus.write_word(sb + 6, 0);
bus.write_word(sb + 8, 0);
bus.write_word(sb + 10, height);
bus.write_word(sb + 12, width);
// Also update the QD globals copy of screenBits.
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
if global_ptr != 0 {
let sb = global_ptr.wrapping_sub(122);
bus.write_long(sb, color_screen_base);
bus.write_word(sb + 4, row_bytes as u16);
bus.write_word(sb + 6, 0);
bus.write_word(sb + 8, 0);
bus.write_word(sb + 10, height);
bus.write_word(sb + 12, width);
}
self.sync_main_gdevice_geometry(bus, width, height, row_bytes, depth, is_color);
self.install_standard_depth_clut(bus, depth, is_color);
self.sync_screen_backed_cgrafports_depth(
bus,
color_screen_base,
row_bytes,
depth,
is_color,
);
// System 7.5.3 clears an 8bpp mode to 0xFF, as covered by the strict
// SetDepth oracle. Packed 1/2/4bpp modes clear to index 0; in the
// standard low-depth tables that is white.
let clear_byte = if depth == 8 { 0xFF } else { 0x00 };
for i in 0..(row_bytes * u32::from(height)) {
bus.write_byte(color_screen_base + i, clear_byte);
}
self.screen_mode = (color_screen_base, row_bytes, width, height, depth);
true
}
fn row_bytes_for_depth(width: u16, depth: u16) -> Option<u32> {
match depth {
1 => Some(u32::from(width).div_ceil(8)),
2 => Some(u32::from(width).div_ceil(4).next_multiple_of(2)),
4 => Some(u32::from(width).div_ceil(2).next_multiple_of(2)),
8 => Some(u32::from(width)),
_ => None,
}
}
fn display_mode_geometry(&self, mode: u32) -> Option<(u16, u16)> {
match mode {
DM_512_342_MODE_ID => Some((512, 342)),
// Display Manager timing/display-mode ID observed from BasiliskII
// when games request the 640x480 switch. This occupies `csData`,
// separate from the Video.h depth token in `csMode`.
DM_640_480_MODE_ID => Some((640, 480)),
// Default 800x600 timing/display-mode ID used by the single-screen HLE.
DM_NATIVE_MODE_ID => Some(self.native_screen_geometry),
_ => None,
}
}
fn display_mode_id_for_geometry(width: u16, height: u16) -> u32 {
match (width, height) {
(512, 342) => DM_512_342_MODE_ID,
(640, 480) => DM_640_480_MODE_ID,
_ => DM_NATIVE_MODE_ID,
}
}
fn write_display_mode_list_entry(
bus: &mut MacMemoryBus,
entry_base: u32,
mode: u32,
width: u16,
height: u16,
pixel_size: u16,
screen_base: u32,
) -> Option<()> {
let row_bytes = Self::row_bytes_for_depth(width, pixel_size)?;
let depth_mode = crate::display::classic_depth_mode(pixel_size)?;
let entry = entry_base + DM_MODE_LIST_ENTRY_OFFSET;
let switch_info = entry_base + DM_MODE_LIST_SWITCH_INFO_OFFSET;
let resolution = entry_base + DM_MODE_LIST_RESOLUTION_INFO_OFFSET;
let timing = entry_base + DM_MODE_LIST_TIMING_INFO_OFFSET;
let depth_block = entry_base + DM_MODE_LIST_DEPTH_BLOCK_OFFSET;
let depth_info = entry_base + DM_MODE_LIST_DEPTH_INFO_OFFSET;
let vp_block = entry_base + DM_MODE_LIST_VP_BLOCK_OFFSET;
let name = entry_base + DM_MODE_LIST_NAME_OFFSET;
bus.write_long(entry + 4, switch_info);
bus.write_long(entry + 8, resolution);
bus.write_long(entry + 12, timing);
bus.write_long(entry + 16, depth_block);
bus.write_long(entry + 20, 1);
bus.write_long(entry + 24, name);
bus.write_word(switch_info, depth_mode);
bus.write_long(switch_info + 2, mode);
bus.write_long(switch_info + 8, screen_base);
bus.write_long(resolution + 4, mode);
bus.write_long(resolution + 8, u32::from(width));
bus.write_long(resolution + 12, u32::from(height));
bus.write_long(resolution + 16, 60 << 16);
bus.write_long(resolution + 20, u32::from(depth_mode));
bus.write_long(timing, mode);
bus.write_long(timing + 16, 0b111);
bus.write_long(depth_block, 1);
bus.write_long(depth_block + 4, depth_info);
bus.write_long(depth_info, switch_info);
bus.write_long(depth_info + 4, vp_block);
bus.write_word(vp_block + 4, row_bytes as u16);
bus.write_word(vp_block + 6, 0);
bus.write_word(vp_block + 8, 0);
bus.write_word(vp_block + 10, height);
bus.write_word(vp_block + 12, width);
bus.write_long(vp_block + 22, 72 << 16);
bus.write_long(vp_block + 26, 72 << 16);
bus.write_word(vp_block + 32, pixel_size);
bus.write_word(vp_block + 34, 1);
bus.write_word(vp_block + 36, pixel_size);
let mode_name = if pixel_size <= 8 {
format!("{} x {}, {} Colors", width, height, 1u32 << pixel_size)
} else {
format!("{} x {}, {}-bit Color", width, height, pixel_size)
};
let mode_name = mode_name.as_bytes();
let name_len = mode_name.len().min(31);
bus.write_byte(name, name_len as u8);
bus.write_bytes(name + 1, &mode_name[..name_len]);
Some(())
}
fn sync_main_gdevice_geometry(
&mut self,
bus: &mut MacMemoryBus,
width: u16,
height: u16,
row_bytes: u32,
depth: u16,
is_color: bool,
) {
let gdh = self.ensure_main_gdevice(bus);
let gd = bus.read_long(gdh);
if gd == 0 {
return;
}
let pm_handle = bus.read_long(gd + 22);
let pm = if pm_handle != 0 {
bus.read_long(pm_handle)
} else {
0
};
if pm != 0 {
bus.write_word(pm + 4, 0x8000 | row_bytes as u16);
bus.write_word(pm + 6, 0);
bus.write_word(pm + 8, 0);
bus.write_word(pm + 10, height);
bus.write_word(pm + 12, width);
bus.write_word(pm + 32, depth);
bus.write_word(pm + 34, 1);
bus.write_word(pm + 36, depth);
let ctab_handle = bus.read_long(pm + 42);
let ctab = if ctab_handle != 0 {
bus.read_long(ctab_handle)
} else {
0
};
if ctab != 0 {
bus.write_long(ctab, u32::from(depth));
if matches!(depth, 1 | 2 | 4 | 8) {
bus.write_word(ctab + 6, (1u16 << depth) - 1);
}
}
}
let mut flags = bus.read_word(gd + 20);
flags &= !0x0001;
if is_color {
flags |= 0x0001;
}
bus.write_word(gd + 20, flags);
bus.write_word(gd + 34, 0);
bus.write_word(gd + 36, 0);
bus.write_word(gd + 38, height);
bus.write_word(gd + 40, width);
}
fn install_standard_depth_clut(&mut self, bus: &mut MacMemoryBus, depth: u16, is_color: bool) {
let Some((clut, entry_count)) = Self::standard_screen_depth_clut(depth, is_color) else {
return;
};
self.device_clut.replace(clut);
self.color_manager_clut.replace(clut);
let gdh = self.ensure_main_gdevice(bus);
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
let ctab_ptr = self.ensure_color_table_capacity(bus, ctab_handle, entry_count as u32);
if ctab_ptr == 0 {
return;
}
bus.write_long(ctab_ptr, u32::from(depth));
bus.write_word(ctab_ptr + 6, entry_count as u16 - 1);
for (index, rgb) in clut.iter().enumerate().take(entry_count) {
let entry = ctab_ptr + 8 + index as u32 * 8;
bus.write_word(entry, index as u16);
bus.write_word(entry + 2, rgb[0]);
bus.write_word(entry + 4, rgb[1]);
bus.write_word(entry + 6, rgb[2]);
}
}
fn sync_screen_backed_cgrafports_depth(
&mut self,
bus: &mut MacMemoryBus,
screen_base: u32,
row_bytes: u32,
depth: u16,
is_color: bool,
) {
let Some((clut, entry_count)) = Self::standard_screen_depth_clut(depth, is_color) else {
return;
};
let mut ports = self.cport_ports.iter().copied().collect::<Vec<_>>();
ports.extend(self.window_list.windows());
ports.extend([*self.current_port, self.front_window]);
ports.sort_unstable();
ports.dedup();
for port in ports {
if port == 0 || (bus.read_word(port + 6) & 0xC000) != 0xC000 {
continue;
}
let pixmap_handle = bus.read_long(port + 2);
let pixmap = bus.read_long(pixmap_handle);
if pixmap == 0
|| (Self::offscreen_pixmap_base_ptr(bus, pixmap) & 0x3FFF_FFFF) != screen_base
{
continue;
}
let ctab_handle = bus.read_long(pixmap + 42);
let ctab = self.ensure_color_table_capacity(bus, ctab_handle, entry_count as u32);
if ctab == 0 {
continue;
}
bus.write_word(pixmap + 4, 0x8000 | row_bytes as u16);
bus.write_word(pixmap + 32, depth);
bus.write_word(pixmap + 34, 1);
bus.write_word(pixmap + 36, depth);
bus.write_long(ctab, u32::from(depth));
bus.write_word(ctab + 6, entry_count as u16 - 1);
for (index, rgb) in clut.iter().enumerate().take(entry_count) {
let entry = ctab + 8 + index as u32 * 8;
bus.write_word(entry, index as u16);
bus.write_word(entry + 2, rgb[0]);
bus.write_word(entry + 4, rgb[1]);
bus.write_word(entry + 6, rgb[2]);
}
}
}
fn preflight_setdepth_color_tables(
&mut self,
bus: &mut MacMemoryBus,
screen_base: u32,
entry_count: usize,
) -> bool {
let main_gdh = self.ensure_main_gdevice(bus);
let main_ctab_handle = Self::gdevice_ctab_handle(bus, main_gdh);
if Self::color_table_ptr(bus, main_ctab_handle) == 0 {
return false;
}
let mut ctab_handles = vec![main_ctab_handle];
let mut ports = self.cport_ports.iter().copied().collect::<Vec<_>>();
ports.extend(self.window_list.windows());
ports.extend([*self.current_port, self.front_window]);
ports.sort_unstable();
ports.dedup();
for port in ports {
if port == 0 || (bus.read_word(port + 6) & 0xC000) != 0xC000 {
continue;
}
let pixmap_handle = bus.read_long(port + 2);
let pixmap = bus.read_long(pixmap_handle);
if pixmap == 0
|| (Self::offscreen_pixmap_base_ptr(bus, pixmap) & 0x3FFF_FFFF) != screen_base
{
continue;
}
let ctab_handle = bus.read_long(pixmap + 42);
if Self::color_table_ptr(bus, ctab_handle) != 0 {
ctab_handles.push(ctab_handle);
}
}
ctab_handles.sort_unstable();
ctab_handles.dedup();
ctab_handles.into_iter().all(|ctab_handle| {
self.ensure_color_table_capacity(bus, ctab_handle, entry_count as u32) != 0
})
}
pub(super) fn sync_current_port_draw_state(&mut self, bus: &mut MacMemoryBus) {
if *self.current_port == 0 {
return;
}
if !self.port_allows_draw_state_memory_sync(bus, *self.current_port) {
return;
}
let state = self.current_draw_state();
self.port_draw_states.insert(*self.current_port, state);
self.sync_port_draw_state(bus, *self.current_port);
}
pub(super) fn resolve_current_port_color_pixels(
&mut self,
bus: &mut MacMemoryBus,
foreground: bool,
background: bool,
use_screen_itable: bool,
) {
let port = *self.current_port;
if port == 0
|| !self.port_allows_draw_state_memory_sync(bus, port)
|| (bus.read_word(port + 6) & 0xC000) != 0xC000
{
return;
}
// A CGrafPort's fgColor/bkColor fields contain pixels resolved for
// that port's destination. An offscreen PixMap can retain a color
// table whose indices differ from the live, animated screen palette;
// resolving every RGB color through the device table writes a valid
// screen index with the wrong meaning into the offscreen buffer.
// Imaging With QuickDraw 1994, pp. 4-82 and 4-95.
let pixmap_handle = bus.read_long(port + 2);
let pixmap = if pixmap_handle != 0 {
bus.read_long(pixmap_handle)
} else {
0
};
let (resolution_clut, screen_itable) = if pixmap != 0 {
let base = Self::offscreen_pixmap_base_ptr(bus, pixmap);
let row_bytes = (bus.read_word(pixmap + 4) & 0x3FFF) as u32;
let pixel_size = bus.read_word(pixmap + 32);
let screen_backed = base == self.screen_mode.0
&& row_bytes == self.screen_mode.1
&& pixel_size == self.screen_mode.4;
if screen_backed {
(*self.device_clut, pixel_size == 8)
} else {
(self.read_port_clut(bus, bus.read_long(pixmap + 42)), false)
}
} else {
(*self.device_clut, self.screen_mode.4 == 8)
};
let logical_screen_clut = *self.color_manager_clut;
if foreground {
let rgb = [self.fg_color.0, self.fg_color.1, self.fg_color.2];
let pixel = if use_screen_itable && screen_itable {
// The screen GDevice's inverse table follows its logical
// ColorTable, not the independently animated video DAC.
// Inside Macintosh: Advanced Color Imaging, "Inverse Tables".
Self::screen_itable_index(&logical_screen_clut, rgb)
} else {
Self::nearest_palette_index(&resolution_clut, rgb)
};
bus.write_long(port + 80, u32::from(pixel));
*self.resolved_port_color_fields.entry(port).or_default() |= 0x01;
}
if background {
let rgb = [self.bg_color.0, self.bg_color.1, self.bg_color.2];
let pixel = if use_screen_itable && screen_itable {
Self::screen_itable_index(&logical_screen_clut, rgb)
} else {
Self::nearest_palette_index(&resolution_clut, rgb)
};
bus.write_long(port + 84, u32::from(pixel));
*self.resolved_port_color_fields.entry(port).or_default() |= 0x02;
}
}
fn sync_port_draw_state(&self, bus: &mut MacMemoryBus, port: u32) {
if port == 0 {
return;
}
if !self.port_allows_draw_state_memory_sync(bus, port) {
return;
}
let port_version = bus.read_word(port + 6);
let is_cgrafport = (port_version & 0xC000) == 0xC000;
// Offsets 36-46: rgbFgColor/rgbBkColor in CGrafPort only.
// In a basic GrafPort these bytes are bkPat/fillPat, so only
// write RGB values when the port really is a CGrafPort.
// Inside Macintosh Volume V, V-48 (CGrafPort record).
if is_cgrafport {
bus.write_word(port + 36, self.fg_color.0);
bus.write_word(port + 38, self.fg_color.1);
bus.write_word(port + 40, self.fg_color.2);
bus.write_word(port + 42, self.bg_color.0);
bus.write_word(port + 44, self.bg_color.1);
bus.write_word(port + 46, self.bg_color.2);
} else {
// Classic GrafPort layout keeps bkPat at +32 and pnPat at +58
// (IM:I I-148). Keep those fields synchronized so callers that
// inspect the port record observe BackPat/PenPat updates.
for (i, byte) in self.bk_pat.iter().enumerate() {
bus.write_byte(port + 32 + i as u32, *byte);
}
for (i, byte) in self.pn_pat.iter().enumerate() {
bus.write_byte(port + 58 + i as u32, *byte);
}
}
// Offsets 48+: pnLoc, pnSize, pnMode, pnVis, txFont, txFace,
// txMode, txSize are at the same offsets in both GrafPort and
// CGrafPort. Inside Macintosh Volume I, I-148.
bus.write_word(port + 48, self.pn_loc.0 as u16);
bus.write_word(port + 50, self.pn_loc.1 as u16);
bus.write_word(port + 52, self.pn_size.0 as u16);
bus.write_word(port + 54, self.pn_size.1 as u16);
bus.write_word(port + 56, self.pn_mode as u16);
bus.write_word(port + 66, self.pn_vis as u16);
bus.write_word(port + 68, self.tx_font as u16);
bus.write_word(port + 70, encode_text_face_style(self.tx_face));
bus.write_word(port + 72, self.tx_mode as u16);
bus.write_word(port + 74, self.tx_size as u16);
if !is_cgrafport {
let fg_legacy = if self.fg_color == (0, 0, 0) {
0x00000021
} else if self.fg_color == (0xFFFF, 0xFFFF, 0xFFFF) {
0x0000001E
} else {
0
};
let bg_legacy = if self.bg_color == (0, 0, 0) {
0x00000021
} else if self.bg_color == (0xFFFF, 0xFFFF, 0xFFFF) {
0x0000001E
} else {
0
};
bus.write_long(port + 80, fg_legacy);
bus.write_long(port + 84, bg_legacy);
}
// A CGrafPort's fgColor/bkColor fields are resolved pixel values,
// independent from rgbFgColor/rgbBkColor. Applications and the Color
// Manager may update those pixels directly, so unrelated pen or text
// synchronization must preserve them. Inside Macintosh Volume V,
// pp. V-48 and V-163.
}
pub(crate) fn known_port(&self, port: u32) -> bool {
self.port_draw_states.contains_key(&port)
|| self.cport_ports.contains(&port)
|| self.gworld_devices.contains_key(&port)
|| self.window_list.contains(&port)
|| self.front_window == port
|| self
.window_stack
.iter()
.any(|(window, _, _, _)| *window == port)
}
fn port_allows_draw_state_memory_sync(&self, bus: &MacMemoryBus, port: u32) -> bool {
if !Self::guest_range_in_ram(bus, port, 88) {
return false;
}
if self.known_port(port) {
return true;
}
!Self::looks_like_68k_entry_point(bus, port)
}
fn guest_range_in_ram(bus: &MacMemoryBus, addr: u32, len: u32) -> bool {
addr.checked_add(len)
.is_some_and(|end| end <= bus.ram_size())
}
fn looks_like_68k_entry_point(bus: &MacMemoryBus, addr: u32) -> bool {
if !Self::guest_range_in_ram(bus, addr, 2) {
return false;
}
match bus.read_word(addr) {
// Common procedure starts and jump-table stubs. A GrafPort's
// first word is the device field, so accepting one of these as
// a port would let QuickDraw state writes corrupt executable
// memory when an app accidentally passes a proc pointer.
0x4EF9 | // JMP absolute long
0x4EFA | // JMP PC-relative
0x4EB9 | // JSR absolute long
0x4E56 | // LINK
0x48E7 | // MOVEM predecrement
0xA9F0 | // LoadSeg
0x3F3C => true, // MOVE.W #imm,-(SP) jump-table glue
op if (op & 0xF000) == 0x6000 => true, // BRA/BSR/Bcc
_ => false,
}
}
fn handle_points_to_guest_range(bus: &MacMemoryBus, handle: u32, min_len: u32) -> bool {
if !Self::guest_range_in_ram(bus, handle, 4) {
return false;
}
let ptr = bus.read_long(handle);
ptr != 0 && Self::guest_range_in_ram(bus, ptr, min_len)
}
fn sane_bitmap_geometry(row_bytes: u16, top: i16, left: i16, bottom: i16, right: i16) -> bool {
let row_bytes = row_bytes & 0x3FFF;
row_bytes > 0 && row_bytes <= 8192 && bottom >= top && right >= left
}
fn looks_like_cgraf_port(bus: &MacMemoryBus, port: u32) -> bool {
if !Self::guest_range_in_ram(bus, port, 92) {
return false;
}
if (bus.read_word(port + 6) & 0xC000) != 0xC000 {
return false;
}
let pixmap_handle = bus.read_long(port + 2);
if !Self::handle_points_to_guest_range(bus, pixmap_handle, 50) {
return false;
}
let pixmap = bus.read_long(pixmap_handle);
Self::sane_bitmap_geometry(
bus.read_word(pixmap + 4),
bus.read_word(pixmap + 6) as i16,
bus.read_word(pixmap + 8) as i16,
bus.read_word(pixmap + 10) as i16,
bus.read_word(pixmap + 12) as i16,
)
}
fn bitmap_ptr_for_port(&self, bus: &MacMemoryBus, port: u32) -> u32 {
if port == 0 {
return 0;
}
let port_version = bus.read_word(port + 6);
if (port_version & 0xC000) == 0xC000 {
let pixmap_handle = bus.read_long(port + 2);
if pixmap_handle != 0 {
return bus.read_long(pixmap_handle);
}
return 0;
}
port + 2
}
fn materialize_recent_spooled_picture(
&mut self,
bus: &mut MacMemoryBus,
pic_ptr: u32,
) -> Option<u32> {
let pic_size = usize::from(bus.read_word(pic_ptr));
if pic_size <= 10 {
return None;
}
let frame_top = bus.read_word(pic_ptr + 2) as i16;
let frame_left = bus.read_word(pic_ptr + 4) as i16;
let frame_bottom = bus.read_word(pic_ptr + 6) as i16;
let frame_right = bus.read_word(pic_ptr + 8) as i16;
let frame_height = i32::from(frame_bottom) - i32::from(frame_top);
let frame_width = i32::from(frame_right) - i32::from(frame_left);
if frame_bottom <= frame_top
|| frame_right <= frame_left
|| frame_height > 8192
|| frame_width > 8192
{
return None;
}
let recent = self.recent_file_read.clone()?;
if recent.buffer != pic_ptr || recent.bytes_read != 10 {
return None;
}
let file = self.vfs.get(&recent.filename)?;
// Large spooled PICT files are delimited by EndOfPicture, not by the
// 16-bit picSize field. QuickDraw intentionally reads until that
// opcode. Inside Macintosh Volume V, V-92.
let materialized_size =
super::pict::picture_stream_len(file.get(recent.start..)?).unwrap_or(pic_size);
let file_end = recent.start.checked_add(materialized_size)?;
if file_end > file.len() {
return None;
}
let loaded_header = bus.read_bytes(pic_ptr, 10);
if file.get(recent.start..recent.start + 10)? != loaded_header.as_slice() {
return None;
}
let materialized = bus.alloc(materialized_size as u32);
if materialized == 0 {
return None;
}
bus.write_bytes(materialized, &file[recent.start..file_end]);
self.file_positions.insert(recent.ref_num, file_end);
self.recent_file_read = Some(super::dispatch::RecentFileRead {
ref_num: recent.ref_num,
filename: recent.filename.clone(),
buffer: materialized,
start: recent.start,
bytes_read: materialized_size,
});
if trace_drawpicture_enabled() {
eprintln!(
"[DRAWPICTURE] materialized spooled PICT ref={} file=\"{}\" offset={} size={} temp=${:08X}",
recent.ref_num, recent.filename, recent.start, materialized_size, materialized
);
}
Some(materialized)
}
fn sanitize_copy_bitmap_bounds(
info: &mut CopyBitmapInfo,
rect_top: i16,
rect_left: i16,
rect_bottom: i16,
rect_right: i16,
) {
if info.bounds_bottom > info.bounds_top && info.bounds_right > info.bounds_left {
return;
}
if rect_bottom <= rect_top || rect_right <= rect_left {
return;
}
info.bounds_top = rect_top;
info.bounds_left = rect_left;
info.bounds_bottom = rect_bottom;
info.bounds_right = rect_right;
}
fn inert_copy_bitmap_info() -> CopyBitmapInfo {
CopyBitmapInfo {
base: u32::MAX,
row_bytes: 0,
bounds_top: 0,
bounds_left: 0,
bounds_bottom: 0,
bounds_right: 0,
pixel_size: 0,
ctab_handle: 0,
}
}
/// Byte mapping for source-only `srcCopy` and `notSrcCopy` modes.
/// Both ignore the destination even across indexed color spaces. `None`
/// leaves unsupported or skipped transfers to the general pixel path.
#[allow(clippy::too_many_arguments)]
fn copy_bits_source_only_table(
&self,
bus: &MacMemoryBus,
dst_ctab_handle: u32,
src_clut: Option<&[[u16; 3]; 256]>,
dst_clut: Option<&[[u16; 3]; 256]>,
palette_translation: Option<&[u8; 256]>,
shared_indexed_pixel_mask: Option<u8>,
mode_base: u16,
fg_rgb: [u16; 3],
bg_rgb: [u16; 3],
) -> Option<[u8; 256]> {
if !matches!(mode_base, 0 | 4) {
return None;
}
let mut table = [0u8; 256];
for (source, entry) in (0..=u8::MAX).zip(table.iter_mut()) {
*entry = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
source,
0,
fg_rgb,
bg_rgb,
)?;
}
Some(table)
}
/// Intersect `spans` (sorted, disjoint, half-open destination x ranges)
/// with one decoded region row, into `out` (sorted, disjoint). `edges`
/// are the sorted x positions where membership toggles, read the way
/// `endpoints_contain_point` reads them: consecutive pairs bound covered
/// spans, and an odd trailing edge means the row stays inside to the
/// right. A single merge walk over the two sorted sequences.
fn intersect_spans_with_region_row(
spans: &[(i32, i32)],
edges: &[i16],
out: &mut Vec<(i32, i32)>,
) {
out.clear();
let mut pairs = edges.chunks(2).map(|pair| {
let start = i32::from(pair[0]);
let end = pair
.get(1)
.map_or(i32::from(i16::MAX) + 1, |&edge| i32::from(edge));
(start, end)
});
let mut spans = spans.iter().copied();
let (mut pair, mut span) = (pairs.next(), spans.next());
while let (Some((pair_start, pair_end)), Some((span_start, span_end))) = (pair, span) {
let lo = pair_start.max(span_start);
let hi = pair_end.min(span_end);
if lo < hi {
out.push((lo, hi));
}
if pair_end < span_end {
pair = pairs.next();
} else {
span = spans.next();
}
}
}
/// Whole-row transfer for the commonest CopyBits shape: 8-bit source to
/// 8-bit destination, `srcCopy`, unscaled. An existing full source
/// snapshot preserves overlap and outline detail exactly as the pixel
/// loop does; otherwise source reads retain the original row path.
///
/// For that shape every written destination pixel is `table[source
/// pixel]` (`copy_bits_source_only_table`, derived from the same per-pixel
/// mode function the pixel loop calls). A plain row uses one bus read,
/// one table pass and one bus write per covered span. A saved source
/// retains the ordered per-pixel detail writes, but also avoids repeated
/// coordinate, region and transfer-mode evaluation. The bus's slice
/// primitives keep `write_byte`'s guards (read-only code, tracing, the
/// idle-proof write journal). A region that needs a per-pixel test is
/// honoured through its decoded row spans -- the same
/// `RegionMembershipCache` rows `region_contains_point_cached` consults.
///
/// Row and column selection reproduce the pixel loop's: a destination row
/// is skipped when its source row lies outside the source bounds, and the
/// column extent is the clip extent cut to the destination rect and to
/// the source bounds.
///
/// Returns `true` once every pixel the pixel loop would have written has
/// been written. Returns `false` *without writing anything* when the
/// transfer is not eligible -- a tested region whose rows are not all
/// decoded, or a clip extent outside the destination bounds -- so the
/// caller can fall back to the loop with no half-copied destination.
#[allow(clippy::too_many_arguments)]
fn copy_bits_src_copy_rows_8bpp(
bus: &mut MacMemoryBus,
src_info: &CopyBitmapInfo,
dst_info: &CopyBitmapInfo,
(src_top, src_left): (i16, i16),
(dst_top, dst_left, dst_w, dst_h): (i16, i16, i32, i32),
(clip_t, clip_l, clip_b, clip_r): (i16, i16, i16, i16),
regions: [(bool, Option<&RegionMembershipCache>); 3],
table: &[u8; 256],
source_snapshot: Option<(u32, &crate::memory::SavedPixels)>,
) -> bool {
// The pixel loop indexes destination rows and columns relative to
// the destination bounds without checking them; only take that on
// when the clip band provably lies inside.
if clip_t < dst_info.bounds_top
|| clip_b > dst_info.bounds_bottom
|| clip_l < dst_info.bounds_left
|| clip_r > dst_info.bounds_right
{
return false;
}
// Every region that needs a per-pixel test must have the whole clip
// band decoded; a missing row would send the loop to its uncached
// `region_contains_point` scan, which this path does not replicate.
let mut tested: [Option<&RegionMembershipCache>; 3] = [None; 3];
for ((needed, cache), slot) in regions.into_iter().zip(tested.iter_mut()) {
if !needed {
continue;
}
let Some(cache) = cache else {
return false;
};
let first = i32::from(clip_t) - i32::from(cache.top);
let last = i32::from(clip_b) - i32::from(cache.top);
if first < 0 || last > cache.rows.len() as i32 {
return false;
}
*slot = Some(cache);
}
// Column extent in destination coordinates: the clip cut to the
// destination rect, then to the source bounds through the fixed
// destination-to-source shift of an unscaled copy.
let shift = i32::from(src_left) - i32::from(dst_left);
let x_lo = i32::from(clip_l)
.max(i32::from(dst_left))
.max(i32::from(src_info.bounds_left) - shift);
let x_hi = i32::from(clip_r)
.min(i32::from(dst_left) + dst_w)
.min(i32::from(src_info.bounds_right) - shift);
if x_hi <= x_lo {
// The loop would write no pixel either.
return true;
}
// Preflight every selected source row before writing. The caller's
// full snapshot normally covers this band; an incomplete snapshot
// must decline without partially copying the destination. Checking
// the full column interval is conservative for rows with holes.
if let Some((first_row, pixels)) = source_snapshot {
for dy in clip_t..clip_b {
let rel = i32::from(dy) - i32::from(dst_top);
if rel < 0 || rel >= dst_h {
continue;
}
let src_y = i32::from(src_top) + rel;
if src_y < i32::from(src_info.bounds_top)
|| src_y >= i32::from(src_info.bounds_bottom)
{
continue;
}
let row = (src_y - i32::from(src_info.bounds_top)) as u32;
let Some(row) = row.checked_sub(first_row) else {
return false;
};
let end = u64::from(row) * u64::from(src_info.row_bytes)
+ (x_hi + shift - i32::from(src_info.bounds_left)) as u64;
if end > pixels.len() as u64 {
return false;
}
}
}
let identity = table
.iter()
.enumerate()
.all(|(index, &value)| index == usize::from(value));
let mut row = vec![0u8; (x_hi - x_lo) as usize];
let mut spans: Vec<(i32, i32)> = Vec::with_capacity(4);
let mut next: Vec<(i32, i32)> = Vec::with_capacity(4);
// Plan every span first: (source, destination, length, offset of
// the source in the snapshot when there is one), in write order.
let mut plan: Vec<(u32, u32, usize, Option<usize>)> = Vec::new();
for dy in clip_t..clip_b {
let rel = i32::from(dy) - i32::from(dst_top);
if rel < 0 || rel >= dst_h {
continue;
}
let src_y = i32::from(src_top) + rel;
if src_y < i32::from(src_info.bounds_top) || src_y >= i32::from(src_info.bounds_bottom)
{
continue;
}
spans.clear();
spans.push((x_lo, x_hi));
for cache in tested.iter().flatten() {
let edges = &cache.rows[(i32::from(dy) - i32::from(cache.top)) as usize];
Self::intersect_spans_with_region_row(&spans, edges, &mut next);
std::mem::swap(&mut spans, &mut next);
if spans.is_empty() {
break;
}
}
let src_row = src_info.base
+ (src_y - i32::from(src_info.bounds_top)) as u32 * src_info.row_bytes;
let dst_row = dst_info.base
+ (i32::from(dy) - i32::from(dst_info.bounds_top)) as u32 * dst_info.row_bytes;
for &(start, end) in &spans {
let src_addr = src_row + (start + shift - i32::from(src_info.bounds_left)) as u32;
let dst_addr = dst_row + (start - i32::from(dst_info.bounds_left)) as u32;
let snapshot_offset = source_snapshot.map(|(first_row, _)| {
let source_row = (src_y - i32::from(src_info.bounds_top)) as u32;
(u64::from(source_row - first_row) * u64::from(src_info.row_bytes)
+ (start + shift - i32::from(src_info.bounds_left)) as u64)
as usize
});
plan.push((src_addr, dst_addr, (end - start) as usize, snapshot_offset));
}
}
let table_map = (!identity).then_some(table);
// From a snapshot, every span's source comes from the snapshot, never
// live memory (the copy may overlap itself), so one snapshot span
// copy covers the whole copy in the loop's order.
if let Some((_, pixels)) = source_snapshot {
if bus.has_outline_presentation() && !plan.is_empty() {
let spans: Vec<(u32, usize, usize)> = plan
.iter()
.map(|&(_, destination, len, offset)| {
(destination, offset.expect("snapshot offset"), len)
})
.collect();
if bus.copy_saved_spans(&spans, pixels, table_map) {
return true;
}
}
}
for (src_addr, dst_addr, len, snapshot_offset) in plan {
let bytes = &mut row[..len];
if let (Some((_, pixels)), Some(offset)) = (source_snapshot, snapshot_offset) {
// Keep the pixel loop's immutable source, palette map,
// write order, and outline-detail transfer. Only its
// per-pixel geometry and mode evaluation are avoided.
for i in 0..bytes.len() {
bus.copy_saved_pixel(dst_addr + i as u32, pixels, offset + i, |index| {
table[index as usize]
});
}
continue;
}
if bus.has_outline_presentation() {
// Each span reads its source after the spans before it are
// written, so each is its own span copy.
bus.read_bytes_into(src_addr, bytes);
if bus.copy_detail_spans(&[(src_addr, dst_addr, len)], bytes, table_map) {
continue;
}
}
let detail = bus
.has_outline_presentation()
.then(|| bus.save_pixel_bytes(src_addr, bytes.len()));
bus.read_bytes_into(src_addr, bytes);
if !identity {
for byte in bytes.iter_mut() {
*byte = table[usize::from(*byte)];
}
}
if let Some(detail) = detail {
for i in 0..bytes.len() {
bus.copy_saved_pixel(dst_addr + i as u32, &detail, i, |index| {
table[index as usize]
});
}
} else {
bus.write_bytes(dst_addr, bytes);
}
}
true
}
fn copy_bits_common<C: CpuOps>(
&mut self,
cpu: &mut C,
bus: &mut MacMemoryBus,
src_bits_ptr: u32,
dst_bits_ptr: u32,
src_rect_ptr: u32,
dst_rect_ptr: u32,
mode: i16,
mask_rgn: u32,
) -> Result<()> {
let mut src_info = self.resolve_copy_bitmap(bus, src_bits_ptr);
let mut dst_info = self.resolve_copy_bitmap(bus, dst_bits_ptr);
if let Some(path) = dump_copybits_src_path() {
if src_info.pixel_size == 8
&& src_info.bounds_bottom > src_info.bounds_top
&& src_info.bounds_right > src_info.bounds_left
{
Self::dump_bitmap_as_png(
bus,
&src_info,
&self.read_port_clut(bus, src_info.ctab_handle),
path,
);
}
}
let src_top = bus.read_word(src_rect_ptr) as i16;
let src_left = bus.read_word(src_rect_ptr + 2) as i16;
let src_bottom = bus.read_word(src_rect_ptr + 4) as i16;
let src_right = bus.read_word(src_rect_ptr + 6) as i16;
let dst_top = bus.read_word(dst_rect_ptr) as i16;
let dst_left = bus.read_word(dst_rect_ptr + 2) as i16;
let dst_bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let dst_right = bus.read_word(dst_rect_ptr + 6) as i16;
let mode_base = (mode & 0x3F) as u16;
let source_bounds_are_original = src_info.bounds_bottom > src_info.bounds_top
&& src_info.bounds_right > src_info.bounds_left;
let destination_bounds_are_authoritative = dst_info.bounds_bottom > dst_info.bounds_top
&& dst_info.bounds_right > dst_info.bounds_left;
Self::sanitize_copy_bitmap_bounds(&mut src_info, src_top, src_left, src_bottom, src_right);
Self::sanitize_copy_bitmap_bounds(&mut dst_info, dst_top, dst_left, dst_bottom, dst_right);
if trace_menu_redraw_enabled()
&& trace_menu_redraw_rect_intersects(dst_top, dst_left, dst_bottom, dst_right)
{
eprintln!(
"[MENU-REDRAW] CopyBits srcBase=${:08X} dstBase=${:08X} mode={} src=({},{}..{},{} ) dst=({},{}..{},{} ) mask=${:08X}",
src_info.base,
dst_info.base,
mode_base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mask_rgn,
);
}
if trace_dialog_draw_enabled() && self.dialog_tracking.is_some() {
eprintln!(
"[DIALOG-DRAW] CopyBits current_port=${:08X} srcBase=${:08X} dstBase=${:08X} mode={} src=({},{}..{},{} ) dst=({},{}..{},{} ) mask=${:08X}",
*self.current_port,
src_info.base,
dst_info.base,
mode_base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mask_rgn,
);
}
if trace_dialog_port_dump_enabled() && self.dialog_tracking.is_some() {
Self::trace_port_snapshot(bus, "CopyBits-current", *self.current_port);
}
if trace_dialog_port_dump_enabled() && self.dialog_tracking.is_some() {
Self::trace_port_snapshot(bus, "CopyBits-current", *self.current_port);
}
if src_bottom <= src_top
|| src_right <= src_left
|| dst_bottom <= dst_top
|| dst_right <= dst_left
{
return Ok(());
}
// Clip destination to the current port's visRgn and clipRgn,
// but only when the destination is the current port's bitmap.
// Per Inside Macintosh Volume I, I-158.
let a5 = cpu.read_reg(Register::A5);
let global_ptr = bus.read_long(a5);
let port = bus.read_long(global_ptr);
let (mut clip_t, mut clip_l, mut clip_b, mut clip_r) =
(dst_top, dst_left, dst_bottom, dst_right);
let mut vis_rgn_handle = 0;
let mut clip_rgn_handle = 0;
let dst_is_port = if port != 0 {
let port_version = bus.read_word(port + 6);
let port_base = if (port_version & 0xC000) == 0xC000 {
let pm_handle = bus.read_long(port + 2);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
Self::offscreen_pixmap_base_ptr(bus, pm_ptr)
} else {
0
}
} else {
bus.read_long(port + 2)
};
port_base == dst_info.base
} else {
false
};
if dst_is_port && port != 0 {
vis_rgn_handle = bus.read_long(port + 24);
if !Self::clip_rect_to_region_bbox(
bus,
vis_rgn_handle,
&mut clip_t,
&mut clip_l,
&mut clip_b,
&mut clip_r,
) {
return Ok(());
}
clip_rgn_handle = bus.read_long(port + 28);
if !Self::clip_rect_to_region_bbox(
bus,
clip_rgn_handle,
&mut clip_t,
&mut clip_l,
&mut clip_b,
&mut clip_r,
) {
return Ok(());
}
}
if !Self::clip_rect_to_region_bbox(
bus,
mask_rgn,
&mut clip_t,
&mut clip_l,
&mut clip_b,
&mut clip_r,
) {
return Ok(());
}
clip_t = clip_t.max(dst_info.bounds_top);
clip_l = clip_l.max(dst_info.bounds_left);
clip_b = clip_b.min(dst_info.bounds_bottom);
clip_r = clip_r.min(dst_info.bounds_right);
let eff_width = clip_r - clip_l;
let eff_height = clip_b - clip_t;
if eff_width <= 0 || eff_height <= 0 {
return Ok(());
}
if dst_info.base == self.screen_mode.0 {
self.ensure_dialog_background_saved_for_screen_port(bus, port);
}
let mask_membership = Self::build_region_membership_cache(bus, mask_rgn, clip_t, clip_b);
let vis_membership =
Self::build_region_membership_cache(bus, vis_rgn_handle, clip_t, clip_b);
let clip_membership =
Self::build_region_membership_cache(bus, clip_rgn_handle, clip_t, clip_b);
// The copy rect was clipped to each region's bounding box above, so
// only a region with scan-line data can still exclude a pixel; a
// rectangular region needs no per-pixel test (and, uncached, that
// test re-read the region header for every pixel).
let vis_test = Self::region_needs_pixel_test(bus, vis_rgn_handle);
let clip_test = Self::region_needs_pixel_test(bus, clip_rgn_handle);
let mask_test = Self::region_needs_pixel_test(bus, mask_rgn);
let trace_probes = if trace_menu_redraw_enabled() {
trace_menu_probe_points()
.into_iter()
.filter_map(|(label, probe_y, probe_x)| {
if !trace_menu_rect_contains_point(
clip_t, clip_l, clip_b, clip_r, probe_y, probe_x,
) {
return None;
}
let src_y =
Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, probe_y)?
as i16;
let src_x =
Self::scale_coord(src_left, src_right, dst_left, dst_right, probe_x)?
as i16;
let src_pixel = Self::read_bitmap_pixel(bus, &src_info, src_y, src_x);
let dst_before = Self::read_bitmap_pixel(bus, &dst_info, probe_y, probe_x);
Some((label, probe_y, probe_x, src_y, src_x, src_pixel, dst_before))
})
.collect::<Vec<_>>()
} else {
Vec::new()
};
let dst_ctab_handle = self.copy_bits_destination_ctab_handle(bus, port, &dst_info);
let src_clut_resolution = matches!(src_info.pixel_size, 2 | 4 | 8)
.then(|| self.read_port_clut_with_provenance(bus, src_info.ctab_handle));
let src_clut = src_clut_resolution.as_ref().map(|(clut, _)| *clut);
let screen_destination = dst_info.base == self.screen_mode.0
&& dst_info.row_bytes == self.screen_mode.1
&& dst_info.pixel_size == u32::from(self.screen_mode.4);
let dst_clut_resolution = self.read_indexed_destination_clut_with_provenance(
bus,
dst_ctab_handle,
dst_info.pixel_size,
screen_destination,
);
let dst_clut = dst_clut_resolution.as_ref().map(|(clut, _)| *clut);
let src_ctab_seed = Self::ctab_seed(bus, src_info.ctab_handle);
let dst_ctab_seed = Self::ctab_seed(bus, dst_ctab_handle);
let indexed_tables_differ = match (src_clut.as_ref(), dst_clut.as_ref()) {
(Some(src_clut), Some(dst_clut)) => src_clut != dst_clut,
_ => src_ctab_seed != dst_ctab_seed,
};
let indexed_palette_identity_known = src_info.pixel_size == 8
&& dst_info.pixel_size == 8
&& (src_info.ctab_handle == dst_info.ctab_handle
|| matches!(
(src_clut_resolution.as_ref(), dst_clut_resolution.as_ref()),
(Some((src_clut, true)), Some((dst_clut, true))) if src_clut == dst_clut
));
let palette_translation = if matches!(src_info.pixel_size, 2 | 4 | 8)
&& matches!(dst_info.pixel_size, 2 | 4 | 8)
&& src_info.ctab_handle != dst_info.ctab_handle
&& (src_info.pixel_size != dst_info.pixel_size || indexed_tables_differ)
{
match (src_clut.as_ref(), dst_clut.as_ref()) {
(Some(src_clut), Some(dst_clut)) => Some(self.build_palette_translation(
bus,
src_clut,
dst_clut,
dst_ctab_handle,
src_info.pixel_size,
dst_info.pixel_size,
)),
_ => None,
}
} else {
None
};
let src_clut = src_clut.as_ref();
let dst_clut = dst_clut.as_ref();
let palette_translation = palette_translation.as_ref();
let shared_indexed_pixel_mask = Self::shared_indexed_pixel_mask(
src_info.pixel_size,
dst_info.pixel_size,
src_info.ctab_handle,
dst_ctab_handle,
src_clut,
dst_clut,
);
let (copy_fg_rgb, copy_bg_rgb) = self.copy_bits_port_draw_colors(bus, port);
if trace_copybits_enabled()
&& (mask_rgn != 0
|| src_info.pixel_size != dst_info.pixel_size
|| src_right - src_left != dst_right - dst_left
|| src_bottom - src_top != dst_bottom - dst_top
|| palette_translation.is_some())
{
eprintln!(
"[COPYBITS] src={}bpp dst={}bpp mode={} src=({},{}..{},{} ) dst=({},{}..{},{} ) mask=${:08X} translate={} srcSeed={:?} dstSeed={:?}",
src_info.pixel_size,
dst_info.pixel_size,
mode_base,
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
mask_rgn,
palette_translation.is_some(),
src_ctab_seed,
dst_ctab_seed,
);
}
let destination_entry_count = Self::indexed_ctab_entry_count(dst_info.pixel_size) as usize;
let fg_index = dst_clut.as_ref().map(|clut| {
self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
clut,
copy_fg_rgb,
destination_entry_count,
)
});
let bg_index = dst_clut.as_ref().map(|clut| {
self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
clut,
copy_bg_rgb,
destination_entry_count,
)
});
let transparent_src_indices = if mode_base == 36 {
self.copy_bits_transparent_source_indices(
bus,
src_info.ctab_handle,
src_clut,
copy_bg_rgb,
)
} else {
None
};
// no_scaling precompute, same pattern as the primary CopyBits path.
// Skips mul/div in scale_coord when src/dst dimensions match.
let src_w = i32::from(src_right) - i32::from(src_left);
let src_h = i32::from(src_bottom) - i32::from(src_top);
let dst_w = i32::from(dst_right) - i32::from(dst_left);
let dst_h = i32::from(dst_bottom) - i32::from(dst_top);
let no_scaling = src_w == dst_w && src_h == dst_h && src_w > 0 && src_h > 0;
let transformed_blit = !no_scaling
|| palette_translation.is_some()
|| src_info.pixel_size != dst_info.pixel_size
|| mode_base != 0
|| vis_rgn_handle != 0
|| clip_rgn_handle != 0
|| mask_rgn != 0;
self.add_hle_tick_cost(Self::quickdraw_blit_tick_cost(
eff_width as u32,
eff_height as u32,
src_info.pixel_size,
dst_info.pixel_size,
transformed_blit,
));
// StdBits resolves the current-port destination at this edge, then
// submits the same pure rectangular request as CopyBits. Complex
// region spans and diagnostic probes remain on the legacy path.
let row_copy_edge_eligible = !Self::region_is_complex(bus, vis_rgn_handle)
&& !Self::region_is_complex(bus, clip_rgn_handle)
&& !Self::region_is_complex(bus, mask_rgn)
&& trace_probes.is_empty();
let shared_rows_written = if row_copy_edge_eligible {
use crate::copy_bits::{Indexed8ScalingSelection, RowCopyOutcome};
let indexed8_scaling = Indexed8ScalingSelection::from_adapter_facts(
mask_rgn == 0,
source_bounds_are_original,
destination_bounds_are_authoritative,
indexed_palette_identity_known,
mode as u16,
);
match resolved_row_copy(
mode_base,
src_info,
dst_info,
[src_top, src_left, src_bottom, src_right].map(i32::from),
[dst_top, dst_left, dst_bottom, dst_right].map(i32::from),
[clip_t, clip_l, clip_b, clip_r].map(i32::from),
palette_translation,
)
.execute_with_indexed8_scaling(bus, indexed8_scaling)
{
RowCopyOutcome::Completed => true,
RowCopyOutcome::WriteFailure { rows_written } if rows_written != 0 => true,
RowCopyOutcome::WriteFailure { .. }
| RowCopyOutcome::NoOp
| RowCopyOutcome::ReadOrGeometryFailure => return Ok(()),
RowCopyOutcome::Declined => false,
}
} else {
false
};
// Source-only modes can map saved detail without combining it with
// irrelevant destination detail.
let detail_table = (bus.has_outline_presentation()
&& matches!(mode_base, 0 | 4)
&& src_info.pixel_size == 8
&& dst_info.pixel_size == 8)
.then(|| {
self.copy_bits_source_only_table(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
palette_translation,
if mode_base == 0 { None } else { shared_indexed_pixel_mask },
mode_base,
copy_fg_rgb,
copy_bg_rgb,
)
})
.flatten();
let source_snapshot = if !shared_rows_written && (src_info.base == dst_info.base
|| (bus.has_outline_presentation() && src_info.pixel_size == 8))
{
let mut row_start = u32::MAX;
let mut row_end = 0u32;
for dy in clip_t..clip_b {
let src_y = if no_scaling {
let rel = i32::from(dy) - i32::from(dst_top);
if rel < 0 || rel >= dst_h {
continue;
}
i32::from(src_top) + rel
} else {
let Some(s) = Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, dy)
else {
continue;
};
s
};
if src_y < i32::from(src_info.bounds_top)
|| src_y >= i32::from(src_info.bounds_bottom)
{
continue;
}
let row = (src_y - i32::from(src_info.bounds_top)) as u32;
row_start = row_start.min(row);
row_end = row_end.max(row);
}
if row_start != u32::MAX {
let row_count = row_end - row_start + 1;
let mut snapshot = vec![0u8; (row_count * src_info.row_bytes) as usize];
// Bulk per-row snapshot.
for row in 0..row_count {
let row_base = src_info.base + (row_start + row) * src_info.row_bytes;
let snapshot_offset = (row * src_info.row_bytes) as usize;
let row_data = bus.read_bytes(row_base, src_info.row_bytes as usize);
snapshot[snapshot_offset..snapshot_offset + src_info.row_bytes as usize]
.copy_from_slice(&row_data);
}
Some((row_start, row_count, {
let mut snapshot: crate::memory::SavedPixels = snapshot.into();
bus.capture_pixel_detail(
&mut snapshot,
0,
src_info.base + row_start * src_info.row_bytes,
(row_count * src_info.row_bytes) as usize,
);
snapshot
}))
} else {
None
}
} else {
None
};
let read_src_byte = |bus: &MacMemoryBus, addr: u32| -> u8 {
if let Some((row_start, row_count, snapshot)) = source_snapshot.as_ref() {
let offset = addr.saturating_sub(src_info.base);
let row = offset / src_info.row_bytes;
if row >= *row_start && row < *row_start + *row_count {
let row_offset = row - *row_start;
let col = offset % src_info.row_bytes;
let snapshot_index = (row_offset * src_info.row_bytes + col) as usize;
if snapshot_index < snapshot.len() {
return snapshot[snapshot_index];
}
}
}
bus.read_byte(addr)
};
// Whole-row path for the commonest shape (see
// copy_bits_src_copy_rows_8bpp). The gates mirror the loop's own
// preconditions for that shape; the table comes from the function the
// (8, 8) arm below calls per pixel, with the arguments it passes. The
// area floor keeps blits smaller than the table from paying for it.
let rows_copied = shared_rows_written
|| (mode_base == 0
&& no_scaling
&& src_info.pixel_size == 8
&& dst_info.pixel_size == 8
&& trace_probes.is_empty()
&& (i32::from(clip_b) - i32::from(clip_t))
* (i32::from(clip_r) - i32::from(clip_l))
>= COPY_BITS_ROW_PATH_MIN_PIXELS
&& self
.copy_bits_source_only_table(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
palette_translation,
None,
0,
copy_fg_rgb,
copy_bg_rgb,
)
.is_some_and(|table| {
Self::copy_bits_src_copy_rows_8bpp(
bus,
&src_info,
&dst_info,
(src_top, src_left),
(dst_top, dst_left, dst_w, dst_h),
(clip_t, clip_l, clip_b, clip_r),
[
(vis_test, vis_membership.as_ref()),
(clip_test, clip_membership.as_ref()),
(mask_test, mask_membership.as_ref()),
],
&table,
source_snapshot
.as_ref()
.map(|(first_row, _, pixels)| (*first_row, pixels)),
)
}));
// With the rows already written the loop has nothing left to do; the
// screen bookkeeping after it still runs.
let pixel_rows = if rows_copied {
clip_t..clip_t
} else {
clip_t..clip_b
};
for dy in pixel_rows {
let src_y = if no_scaling {
let rel = i32::from(dy) - i32::from(dst_top);
if rel < 0 || rel >= dst_h {
continue;
}
i32::from(src_top) + rel
} else {
let Some(s) = Self::scale_coord(src_top, src_bottom, dst_top, dst_bottom, dy)
else {
continue;
};
s
};
if src_y < i32::from(src_info.bounds_top) || src_y >= i32::from(src_info.bounds_bottom)
{
continue;
}
let dst_y = (i32::from(dy) - i32::from(dst_info.bounds_top)) as u32;
for dx in clip_l..clip_r {
let src_x = if no_scaling {
let rel = i32::from(dx) - i32::from(dst_left);
if rel < 0 || rel >= dst_w {
continue;
}
i32::from(src_left) + rel
} else {
let Some(s) = Self::scale_coord(src_left, src_right, dst_left, dst_right, dx)
else {
continue;
};
s
};
if src_x < i32::from(src_info.bounds_left)
|| src_x >= i32::from(src_info.bounds_right)
{
continue;
}
if vis_test
&& !Self::region_contains_point_cached(
bus,
vis_rgn_handle,
vis_membership.as_ref(),
dy,
dx,
)
{
continue;
}
if clip_test
&& !Self::region_contains_point_cached(
bus,
clip_rgn_handle,
clip_membership.as_ref(),
dy,
dx,
)
{
continue;
}
if mask_test
&& !Self::region_contains_point_cached(
bus,
mask_rgn,
mask_membership.as_ref(),
dy,
dx,
)
{
continue;
}
let dst_x = (i32::from(dx) - i32::from(dst_info.bounds_left)) as u32;
let src_x_off = (src_x - i32::from(src_info.bounds_left)) as u32;
let src_y_off = (src_y - i32::from(src_info.bounds_top)) as u32;
match (src_info.pixel_size, dst_info.pixel_size) {
(src_bits @ (16 | 32), dst_bits @ (1 | 2 | 4 | 8)) => {
let src_addr = src_info.base
+ src_y_off * src_info.row_bytes
+ src_x_off * (src_bits / 8);
let src_rgb = Self::read_rgbdirect_pixel(
|address| read_src_byte(bus, address),
src_addr,
src_bits,
)
.expect("RGBDirect source depth");
if mode_base == 36 && src_rgb == copy_bg_rgb {
continue;
}
let pixels_per_byte = 8 / dst_bits;
let pixel_mask = if dst_bits == 8 {
u8::MAX
} else {
(1u8 << dst_bits) - 1
};
let dst_addr =
dst_info.base + dst_y * dst_info.row_bytes + dst_x / pixels_per_byte;
let dst_shift = 8 - dst_bits - (dst_x % pixels_per_byte) * dst_bits;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte >> dst_shift) & pixel_mask;
let dst_clut = dst_clut.as_ref().expect("indexed destination CLUT");
let dst_rgb = dst_clut[usize::from(dst_pixel)];
let effective_mode = if mode_base == 36 { 0 } else { mode_base };
let Some(result_rgb) = Self::copy_bits_direct_source_mode_rgb(
src_rgb,
dst_rgb,
effective_mode,
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
let mapped = self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
dst_clut,
result_rgb,
1usize << dst_bits,
);
let shifted_mask = pixel_mask << dst_shift;
bus.write_byte(
dst_addr,
(dst_byte & !shifted_mask) | (mapped << dst_shift),
);
}
(src_bits @ (2 | 4), dst_bits) if src_bits == dst_bits => {
let pixels_per_byte = 8 / src_bits;
let pixel_mask = (1u8 << src_bits) - 1;
let src_byte_offset =
src_y_off * src_info.row_bytes + src_x_off / pixels_per_byte;
let src_shift = 8 - src_bits - (src_x_off % pixels_per_byte) * src_bits;
let src_pixel = (read_src_byte(bus, src_info.base + src_byte_offset)
>> src_shift)
& pixel_mask;
if mode_base == 36
&& transparent_src_indices
.as_ref()
.is_some_and(|indices| indices[src_pixel as usize])
{
continue;
}
let dst_byte_offset = dst_y * dst_info.row_bytes + dst_x / pixels_per_byte;
let dst_shift = 8 - dst_bits - (dst_x % pixels_per_byte) * dst_bits;
let dst_addr = dst_info.base + dst_byte_offset;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte >> dst_shift) & pixel_mask;
let Some(new_pixel) = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
1usize << dst_bits,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
src_pixel,
dst_pixel,
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
let shifted_mask = pixel_mask << dst_shift;
bus.write_byte(
dst_addr,
(dst_byte & !shifted_mask) | ((new_pixel & pixel_mask) << dst_shift),
);
}
(src_bits @ (2 | 4), 8) => {
let pixels_per_byte = 8 / src_bits;
let src_byte_offset =
src_y_off * src_info.row_bytes + src_x_off / pixels_per_byte;
let shift = 8 - src_bits - (src_x_off % pixels_per_byte) * src_bits;
let mask = (1u8 << src_bits) - 1;
let src_pixel =
(read_src_byte(bus, src_info.base + src_byte_offset) >> shift) & mask;
if mode_base == 36
&& transparent_src_indices
.as_ref()
.is_some_and(|indices| indices[src_pixel as usize])
{
continue;
}
let dst_addr = dst_info.base + dst_y * dst_info.row_bytes + dst_x;
let Some(dst_pixel) = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
None,
mode_base,
src_pixel,
bus.read_byte(dst_addr),
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
bus.write_byte(dst_addr, dst_pixel);
}
(8, 8) => {
let src_addr = src_info.base + src_y_off * src_info.row_bytes + src_x_off;
let dst_addr = dst_info.base + dst_y * dst_info.row_bytes + dst_x;
if let Some((row_start, _, snapshot)) = &source_snapshot {
let offset = (src_addr - src_info.base - row_start * src_info.row_bytes)
as usize;
if detail_table.is_none()
&& bus.transfer_saved_pixel(
dst_addr,
snapshot,
offset,
|bus, src, dst| {
if mode_base == 36
&& transparent_src_indices
.as_ref()
.is_some_and(|indices| indices[src as usize])
{
return dst;
}
self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
src,
dst,
copy_fg_rgb,
copy_bg_rgb,
)
.unwrap_or(dst)
},
)
{
continue;
}
}
let src_pixel = read_src_byte(bus, src_addr);
if mode_base == 36
&& transparent_src_indices
.as_ref()
.map_or(false, |indices| indices[src_pixel as usize])
{
continue;
}
let Some(dst_pixel) = self.copy_bits_color_source_mode_pixel(
bus,
dst_ctab_handle,
src_clut,
dst_clut,
256,
palette_translation,
shared_indexed_pixel_mask,
mode_base,
src_pixel,
bus.read_byte(dst_addr),
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
if let (Some(table), Some((row_start, _, snapshot))) =
(&detail_table, &source_snapshot)
{
let offset = src_addr - src_info.base - row_start * src_info.row_bytes;
bus.copy_saved_pixel(dst_addr, snapshot, offset as usize, |index| {
table[index as usize]
});
} else {
bus.write_byte(dst_addr, dst_pixel);
}
}
(src_bits @ (16 | 32), dst_bits @ (16 | 32)) if src_bits != dst_bits => {
let src_addr = src_info.base
+ src_y_off * src_info.row_bytes
+ src_x_off * (src_bits / 8);
let dst_addr =
dst_info.base + dst_y * dst_info.row_bytes + dst_x * (dst_bits / 8);
let src_rgb = Self::read_rgbdirect_pixel(
|address| read_src_byte(bus, address),
src_addr,
src_bits,
)
.expect("RGBDirect source depth");
if mode_base == 36 && src_rgb == copy_bg_rgb {
continue;
}
let dst_rgb = Self::read_rgbdirect_pixel(
|address| bus.read_byte(address),
dst_addr,
dst_bits,
)
.expect("RGBDirect destination depth");
let effective_mode = if mode_base == 36 { 0 } else { mode_base };
let Some(rgb) = Self::copy_bits_direct_source_mode_rgb(
src_rgb,
dst_rgb,
effective_mode,
copy_fg_rgb,
copy_bg_rgb,
) else {
continue;
};
if dst_bits == 16 {
let packed =
((rgb[0] >> 11) << 10) | ((rgb[1] >> 11) << 5) | (rgb[2] >> 11);
bus.write_word(dst_addr, packed);
} else {
bus.write_long(
dst_addr,
(u32::from(rgb[0] >> 8) << 16)
| (u32::from(rgb[1] >> 8) << 8)
| u32::from(rgb[2] >> 8),
);
}
}
(src_bits, dst_bits)
if src_bits >= 8 && dst_bits >= 8 && src_bits == dst_bits =>
{
let bytes_per_pixel = src_bits / 8;
let src_addr = src_info.base
+ src_y_off * src_info.row_bytes
+ src_x_off * bytes_per_pixel;
let dst_addr =
dst_info.base + dst_y * dst_info.row_bytes + dst_x * bytes_per_pixel;
for byte_index in 0..bytes_per_pixel {
let pixel = read_src_byte(bus, src_addr + byte_index);
bus.write_byte(dst_addr + byte_index, pixel);
}
}
(1, 8) => {
let src_byte_offset = src_y_off * src_info.row_bytes + (src_x_off / 8);
let src_bit = 7 - (src_x_off % 8);
let src_byte = read_src_byte(bus, src_info.base + src_byte_offset);
let src_pixel = (src_byte & (1 << src_bit)) != 0;
let dst_addr = dst_info.base + dst_y * dst_info.row_bytes + dst_x;
let dst_pixel = bus.read_byte(dst_addr);
let dst_clut = dst_clut.unwrap();
let fg_index = fg_index.unwrap();
let bg_index = bg_index.unwrap();
let new_pixel = match mode_base {
0 => Some(if src_pixel { fg_index } else { bg_index }),
1 => src_pixel.then_some(fg_index),
2 => {
src_pixel.then(|| Self::inverted_palette_index(dst_clut, dst_pixel))
}
3 => src_pixel.then_some(bg_index),
4 => Some(if src_pixel { bg_index } else { fg_index }),
5 => (!src_pixel).then_some(fg_index),
6 => (!src_pixel)
.then(|| Self::inverted_palette_index(dst_clut, dst_pixel)),
7 => (!src_pixel).then_some(bg_index),
36 => src_pixel.then_some(fg_index),
_ => Some(if src_pixel { fg_index } else { bg_index }),
};
if let Some(pixel) = new_pixel {
bus.write_byte(dst_addr, pixel);
}
}
(1, 1) => {
let src_byte_offset = src_y_off * src_info.row_bytes + (src_x_off / 8);
let src_bit = 7 - (src_x_off % 8);
let src_byte = read_src_byte(bus, src_info.base + src_byte_offset);
let src_pixel = (src_byte & (1 << src_bit)) != 0;
let dst_byte_offset = dst_y * dst_info.row_bytes + (dst_x / 8);
let dst_bit = 7 - (dst_x % 8);
let dst_addr = dst_info.base + dst_byte_offset;
let dst_byte = bus.read_byte(dst_addr);
let dst_pixel = (dst_byte & (1 << dst_bit)) != 0;
let new_bit = match mode_base {
0 => src_pixel,
1 => src_pixel || dst_pixel,
2 => src_pixel ^ dst_pixel,
3 => !src_pixel && dst_pixel,
4 => !src_pixel,
5 => !src_pixel || dst_pixel,
6 => !src_pixel ^ dst_pixel,
7 => src_pixel && dst_pixel,
36 => src_pixel || dst_pixel,
_ => src_pixel,
};
if new_bit {
bus.write_byte(dst_addr, dst_byte | (1 << dst_bit));
} else {
bus.write_byte(dst_addr, dst_byte & !(1 << dst_bit));
}
}
_ => {}
}
}
}
if trace_menu_redraw_enabled() {
for (label, probe_y, probe_x, src_y, src_x, src_pixel, dst_before) in trace_probes {
let dst_after = Self::read_bitmap_pixel(bus, &dst_info, probe_y, probe_x);
eprintln!(
"[MENU-REDRAW] CopyBits probe={} srcPt=({}, {}) srcPixel={:?} dstBefore={:?} dstAfter={:?}",
label,
src_y,
src_x,
src_pixel,
dst_before,
dst_after,
);
}
}
if dst_info.base == self.screen_mode.0 {
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
*self.current_port,
(
clip_t.saturating_sub(dst_info.bounds_top),
clip_l.saturating_sub(dst_info.bounds_left),
clip_b.saturating_sub(dst_info.bounds_top),
clip_r.saturating_sub(dst_info.bounds_left),
),
);
self.refresh_visible_dialog_snapshot_after_bulk_port_draw(
bus,
*self.current_port,
(
clip_t.saturating_sub(dst_info.bounds_top),
clip_l.saturating_sub(dst_info.bounds_left),
clip_b.saturating_sub(dst_info.bounds_top),
clip_r.saturating_sub(dst_info.bounds_left),
),
);
}
Ok(())
}
fn note_screen_copybits_rect(
&mut self,
src_top: i16,
src_left: i16,
src_bottom: i16,
src_right: i16,
dst_top: i16,
dst_left: i16,
dst_bottom: i16,
dst_right: i16,
) {
let src_width = src_right.saturating_sub(src_left);
let src_height = src_bottom.saturating_sub(src_top);
let dst_width = dst_right.saturating_sub(dst_left);
let dst_height = dst_bottom.saturating_sub(dst_top);
if src_width <= 0 || src_height <= 0 || dst_width <= 0 || dst_height <= 0 {
return;
}
let (_, _, screen_width, screen_height, _) = self.screen_mode;
let min_width = (screen_width as i16 / 2).max(1);
let min_height = (screen_height as i16 / 2).max(1);
if dst_width < min_width || dst_height < min_height {
return;
}
self.last_screen_copybits_rect = Some(ScreenCopyBitsRect {
src_top,
src_left,
src_bottom,
src_right,
dst_top,
dst_left,
dst_bottom,
dst_right,
});
}
fn screen_copybits_rect(
dst_info: &CopyBitmapInfo,
src_top: i16,
src_left: i16,
src_bottom: i16,
src_right: i16,
dst_top: i16,
dst_left: i16,
dst_bottom: i16,
dst_right: i16,
) -> ScreenCopyBitsRect {
// A screen-backed window PixMap expresses CopyBits destinations in
// port-local coordinates. Its bounds origin maps those coordinates
// onto the physical framebuffer; screen bookkeeping and letterbox
// fills must therefore remove that origin. Inside Macintosh Volume I
// (1985), pp. I-148 and I-166.
ScreenCopyBitsRect {
src_top,
src_left,
src_bottom,
src_right,
dst_top: dst_top.saturating_sub(dst_info.bounds_top),
dst_left: dst_left.saturating_sub(dst_info.bounds_left),
dst_bottom: dst_bottom.saturating_sub(dst_info.bounds_top),
dst_right: dst_right.saturating_sub(dst_info.bounds_left),
}
}
fn fill_kiosk_letterbox_for_copybits(&self, bus: &mut MacMemoryBus, rect: ScreenCopyBitsRect) {
let src_width = rect.src_right.saturating_sub(rect.src_left);
let src_height = rect.src_bottom.saturating_sub(rect.src_top);
let dst_width = rect.dst_right.saturating_sub(rect.dst_left);
let dst_height = rect.dst_bottom.saturating_sub(rect.dst_top);
if src_width != dst_width || src_height != dst_height {
return;
}
let destination = (rect.dst_top, rect.dst_left, rect.dst_bottom, rect.dst_right);
// A crawl or animation repeats the same blit every frame. When the
// fill's inputs match the last fill and nothing outside the
// destination has changed since, the margins are still uniform and
// already hold what the fill would write.
// The cheap inputs are compared first: a sprite game blits many small
// rectangles whose destinations never match the last fill.
let repeat = self.kiosk_letterbox_filled.get().is_some_and(
|((held_destination, hidden, mode, black), mark)| {
held_destination == destination
&& hidden == self.menu_bar_hidden
&& mode == self.screen_mode
&& black == self.kiosk_black_index()
&& self.kiosk_margins_unchanged_since(bus, mark, destination)
},
);
if repeat {
return;
}
// CopyBits owns only its destination rectangle; a large centered blit
// may still be an overlay within a larger application composition.
// On indexed color screens, require uniform exposed bands before
// replacing them with kiosk-stage black. Imaging With QuickDraw
// (1994), pp. 3-112 to 3-114.
if self.screen_mode.4 == 8 && !self.kiosk_stage_margins_are_uniform(bus, destination) {
return;
}
// Run after the blit so overlapping screen-to-screen copies cannot
// lose source pixels while the margins are cleared.
let filled = self.fill_kiosk_stage_around_rect(bus, destination);
let held = if filled {
let key = (
destination,
self.menu_bar_hidden,
self.screen_mode,
self.kiosk_black_index(),
);
bus.screen_mark().map(|mark| (key, mark))
} else {
None
};
self.kiosk_letterbox_filled.set(held);
}
/// Address of a replacement `grafProcs.bitsProc` on the current port, or
/// `None` when the standard StdBits bottleneck is in force.
///
/// `grafProcs` is the last field of both GrafPort and CGrafPort, at offset
/// 104 (IM:I I-155; IM:V V-77), and `bitsProc` is the ninth of the thirteen
/// QDProcs slots, at offset 32 within the record (IM:I I-197). SetStdProcs
/// and SetStdCProcs fill that slot with the protected StdBits gateway,
/// which means "the standard proc" and must not be called back into.
///
/// Returns `None` while we are nested inside a previous tail call, so a
/// custom proc that completes its work by calling CopyBits again gets the
/// real blit instead of being handed back to itself.
fn custom_bits_proc<C: CpuOps>(&self, bus: &MacMemoryBus, cpu: &C) -> Option<u32> {
let port = *self.current_port;
if port == 0 || !Self::guest_range_in_ram(bus, port, 108) {
return None;
}
let graf_procs = bus.read_long(port + 104);
if graf_procs == 0 || !Self::guest_range_in_ram(bus, graf_procs, 36) {
return None;
}
let bits_proc = bus.read_long(graf_procs + 32);
if bits_proc == 0 || bus.system_trap_gateway(0xA8EB) == Some(bits_proc) {
return None;
}
if let Some((active_proc, active_sp)) = self.bits_proc_reentry {
if active_proc == bits_proc && cpu.read_reg(Register::A7) <= active_sp {
return None;
}
}
Some(bits_proc)
}
fn copy_bits_fully_clipped_in_current_port(
&self,
bus: &MacMemoryBus,
dst_bits_ptr: u32,
dst_rect_ptr: u32,
mask_rgn: u32,
include_visibility: bool,
) -> bool {
let port = *self.current_port;
if port == 0 || !Self::guest_range_in_ram(bus, port, 32) {
return false;
}
let port_version = bus.read_word(port + 6);
let port_base = if (port_version & 0xC000) == 0xC000 {
let pixmap_handle = bus.read_long(port + 2);
let pixmap = (pixmap_handle != 0).then(|| bus.read_long(pixmap_handle));
pixmap
.filter(|&pixmap| pixmap != 0)
.map(|pixmap| Self::offscreen_pixmap_base_ptr(bus, pixmap))
.unwrap_or(0)
} else {
bus.read_long(port + 2)
};
if port_base != self.resolve_copy_bitmap(bus, dst_bits_ptr).base {
return false;
}
let mut top = bus.read_word(dst_rect_ptr) as i16;
let mut left = bus.read_word(dst_rect_ptr + 2) as i16;
let mut bottom = bus.read_word(dst_rect_ptr + 4) as i16;
let mut right = bus.read_word(dst_rect_ptr + 6) as i16;
let visibility = include_visibility.then(|| bus.read_long(port + 24));
for region in [visibility, Some(bus.read_long(port + 28)), Some(mask_rgn)]
.into_iter()
.flatten()
{
if !Self::clip_rect_to_region_bbox(
bus,
region,
&mut top,
&mut left,
&mut bottom,
&mut right,
) {
return true;
}
}
false
}
pub(super) fn resolve_copy_bitmap(&self, bus: &MacMemoryBus, bits_ptr: u32) -> CopyBitmapInfo {
if bits_ptr == 0 || !Self::guest_range_in_ram(bus, bits_ptr, 14) {
return Self::inert_copy_bitmap_info();
}
let normalize_base = |base: u32| -> u32 {
if base == 0 || base == u32::MAX {
return base;
}
if base < bus.ram_size() {
return base;
}
// Classic QuickDraw callers sometimes hand CopyBits a baseAddr
// with high-byte tag bits while the actual pixel buffer lives in
// low 24-bit RAM. If the full 32-bit address is unmapped but the
// low 24-bit address is valid RAM, prefer the stripped address.
// This avoids sampling unmapped zeroes for legacy/non-clean blits.
let stripped = base & 0x00FF_FFFF;
if stripped < bus.ram_size() {
return stripped;
}
base
};
let raw_word = bus.read_word(bits_ptr + 4);
// CopyBits identifies parameter "shape" using the high bits of the
// word at offset +4 from a BitMap-style argument:
// - bit15 set => PixMap
// - bit14 set => treat baseAddr as handle (cGrafPort portBits path)
// See "RowBytes Revealed II" (Apple DTS, 1993) and IM QuickDraw docs.
//
// Systemless previously only recognized the 0xC000 cGrafPort case. Some
// real-world callers (including game blitters) hand arguments whose
// bit14 is set without the full 0xC000 signature; QuickDraw still
// applies the handle-dereference rule there, so mirror that behavior.
if (raw_word & 0x4000) != 0 && (raw_word & 0xC000) != 0xC000 {
let handle_like = normalize_base(bus.read_long(bits_ptr));
if let Some(pm_ptr) = Self::pixmap_ptr_from_handle(bus, handle_like) {
if let Some(info) = Self::cached_copy_bitmap_from_pixmap(bus, pm_ptr) {
return CopyBitmapInfo {
base: normalize_base(info.base),
row_bytes: info.row_bytes,
bounds_top: info.bounds_top,
bounds_left: info.bounds_left,
bounds_bottom: info.bounds_bottom,
bounds_right: info.bounds_right,
pixel_size: info.pixel_size,
ctab_handle: info.ctab_handle,
};
}
}
}
if (raw_word & 0xC000) == 0xC000 {
let pm_handle = normalize_base(bus.read_long(bits_ptr));
let direct_pm_ptr = Self::pixmap_ptr_from_handle(bus, pm_handle);
let direct_info =
direct_pm_ptr.and_then(|pm_ptr| Self::cached_copy_bitmap_from_pixmap(bus, pm_ptr));
let cached_info = self.disposed_gworld_portbits.get(&bits_ptr).copied();
let resolved_info = direct_info.or(cached_info);
let Some(info) = resolved_info else {
return CopyBitmapInfo {
base: u32::MAX,
row_bytes: 0,
bounds_top: 0,
bounds_left: 0,
bounds_bottom: 0,
bounds_right: 0,
pixel_size: 0,
ctab_handle: 0,
};
};
return CopyBitmapInfo {
base: normalize_base(info.base),
row_bytes: info.row_bytes,
bounds_top: info.bounds_top,
bounds_left: info.bounds_left,
bounds_bottom: info.bounds_bottom,
bounds_right: info.bounds_right,
pixel_size: info.pixel_size,
ctab_handle: info.ctab_handle,
};
}
if (raw_word & 0x8000) != 0 {
if !Self::guest_range_in_ram(bus, bits_ptr, 46) {
return Self::inert_copy_bitmap_info();
}
return CopyBitmapInfo {
base: normalize_base(Self::offscreen_pixmap_base_ptr(bus, bits_ptr)),
row_bytes: (raw_word & 0x3FFF) as u32,
bounds_top: bus.read_word(bits_ptr + 6) as i16,
bounds_left: bus.read_word(bits_ptr + 8) as i16,
bounds_bottom: bus.read_word(bits_ptr + 10) as i16,
bounds_right: bus.read_word(bits_ptr + 12) as i16,
pixel_size: bus.read_word(bits_ptr + 32) as u32,
ctab_handle: bus.read_long(bits_ptr + 42),
};
}
let base = normalize_base(bus.read_long(bits_ptr));
let (screen_base, _, _, _, screen_ps) = self.screen_mode;
// A legacy GrafPort can pass a BitMap-shaped portBits whose baseAddr
// identifies the color screen, even when its rowBytes still describes
// a 1-bit port. CopyBits targets the screen device in that case; use
// its actual stride and depth. Imaging With QuickDraw (1994), 3-116,
// describes CopyBits translation between bitmap and pixel-map depths.
let raw_row_bytes = (raw_word & 0x3FFF) as u32;
let screen_backed = base == screen_base && screen_ps > 1;
let (pixel_size, ctab_handle, row_bytes) = if screen_backed {
(
screen_ps as u32,
Self::gdevice_ctab_handle(bus, self.main_gdevice_handle),
self.screen_mode.1,
)
} else {
(1, 0, raw_row_bytes)
};
CopyBitmapInfo {
base,
row_bytes,
bounds_top: bus.read_word(bits_ptr + 6) as i16,
bounds_left: bus.read_word(bits_ptr + 8) as i16,
bounds_bottom: bus.read_word(bits_ptr + 10) as i16,
bounds_right: bus.read_word(bits_ptr + 12) as i16,
pixel_size,
ctab_handle,
}
}
fn push_pict_word(bytes: &mut Vec<u8>, value: u16) {
bytes.extend_from_slice(&value.to_be_bytes());
}
fn push_pict_long(bytes: &mut Vec<u8>, value: u32) {
bytes.extend_from_slice(&value.to_be_bytes());
}
fn push_packbits_literal_row(bytes: &mut Vec<u8>, row: &[u8]) {
let mut packed = Vec::with_capacity(row.len() + row.len().div_ceil(128));
for chunk in row.chunks(128) {
packed.push((chunk.len() - 1) as u8);
packed.extend_from_slice(chunk);
}
if row.len() > 250 {
Self::push_pict_word(bytes, packed.len() as u16);
} else {
bytes.push(packed.len() as u8);
}
bytes.extend_from_slice(&packed);
}
fn encode_recorded_picture_pict(
top: i16,
left: i16,
bottom: i16,
right: i16,
commands: Vec<u8>,
) -> Vec<u8> {
pict::finish_recording((top, left, bottom, right), commands)
}
fn encode_bitmap_copy_pict(
bus: &MacMemoryBus,
source: CopyBitmapInfo,
source_clut: &[[u16; 3]; 256],
source_rect: (i16, i16, i16, i16),
dest_rect: (i16, i16, i16, i16),
mode: i16,
) -> Option<Vec<u8>> {
let (src_top, src_left, src_bottom, src_right) = source_rect;
let (dst_top, dst_left, dst_bottom, dst_right) = dest_rect;
let src_width = u32::try_from(i32::from(src_right) - i32::from(src_left)).ok()?;
let src_height = u32::try_from(i32::from(src_bottom) - i32::from(src_top)).ok()?;
let width = u32::try_from(i32::from(dst_right) - i32::from(dst_left)).ok()?;
let height = u32::try_from(i32::from(dst_bottom) - i32::from(dst_top)).ok()?;
if width == 0 || height == 0 {
return None;
}
if src_width == 0 || src_height == 0 {
return None;
}
let pixel_size = u16::try_from(source.pixel_size).ok()?;
if !matches!(pixel_size, 1 | 2 | 4 | 8) {
return None;
}
let row_bytes = (width * u32::from(pixel_size))
.div_ceil(8)
.next_multiple_of(2);
let color_count = 1usize << pixel_size;
let mut picture = Vec::with_capacity(
10 + 1 + 46 + 8 + color_count * 8 + 18 + (row_bytes as usize + 6) * height as usize,
);
Self::push_pict_word(&mut picture, 0); // patched after encoding
for value in [dst_top, dst_left, dst_bottom, dst_right] {
Self::push_pict_word(&mut picture, value as u16);
}
picture.push(0x98); // PICT v1 PackBitsRect
Self::push_pict_word(&mut picture, 0x8000 | row_bytes as u16);
for value in [0i16, 0, height as i16, width as i16] {
Self::push_pict_word(&mut picture, value as u16);
}
Self::push_pict_word(&mut picture, 0); // pmVersion
Self::push_pict_word(&mut picture, 0); // packType
Self::push_pict_long(&mut picture, 0); // packSize
Self::push_pict_long(&mut picture, 0x0048_0000); // hRes
Self::push_pict_long(&mut picture, 0x0048_0000); // vRes
Self::push_pict_word(&mut picture, 0); // pixelType: indexed
Self::push_pict_word(&mut picture, pixel_size);
Self::push_pict_word(&mut picture, 1); // cmpCount
Self::push_pict_word(&mut picture, pixel_size); // cmpSize
Self::push_pict_long(&mut picture, 0); // planeBytes
Self::push_pict_long(&mut picture, 0); // pmTable
Self::push_pict_long(&mut picture, 0); // pmReserved
Self::push_pict_long(&mut picture, 0); // ctSeed
Self::push_pict_word(&mut picture, 0x8000); // implicit ColorSpec indices
Self::push_pict_word(&mut picture, (color_count - 1) as u16);
for index in 0..color_count {
Self::push_pict_word(&mut picture, index as u16);
for component in source_clut[index] {
Self::push_pict_word(&mut picture, component);
}
}
for value in [0i16, 0, height as i16, width as i16] {
Self::push_pict_word(&mut picture, value as u16);
}
for value in [dst_top, dst_left, dst_bottom, dst_right] {
Self::push_pict_word(&mut picture, value as u16);
}
Self::push_pict_word(&mut picture, mode as u16);
let pixels_per_byte = 8 / u32::from(pixel_size);
let pixel_mask = if pixel_size == 8 {
u8::MAX
} else {
(1u8 << pixel_size) - 1
};
let mut row = vec![0u8; row_bytes as usize];
for y in 0..height {
row.fill(0);
for x in 0..width {
let source_y = src_top.saturating_add((y * src_height / height) as i16);
let source_x = src_left.saturating_add((x * src_width / width) as i16);
let source_pixel =
Self::read_bitmap_pixel(bus, &source, source_y, source_x).unwrap_or_default();
let pixel = if pixel_size == 1 {
u8::from(source_pixel != 0)
} else {
source_pixel & pixel_mask
};
let byte_index = (x / pixels_per_byte) as usize;
let shift =
8 - u32::from(pixel_size) - (x % pixels_per_byte) * u32::from(pixel_size);
row[byte_index] |= pixel << shift;
}
if row_bytes < 8 {
picture.extend_from_slice(&row);
} else {
Self::push_packbits_literal_row(&mut picture, &row);
}
}
picture.push(0xFF); // EndOfPicture
let picture_size = u16::try_from(picture.len()).unwrap_or(0);
picture[0..2].copy_from_slice(&picture_size.to_be_bytes());
Some(picture)
}
fn read_bitmap_pixel(bus: &MacMemoryBus, info: &CopyBitmapInfo, y: i16, x: i16) -> Option<u8> {
if y < info.bounds_top
|| y >= info.bounds_bottom
|| x < info.bounds_left
|| x >= info.bounds_right
{
return None;
}
let row = (y - info.bounds_top) as u32;
let col = (x - info.bounds_left) as u32;
match info.pixel_size {
8 => Some(bus.read_byte(info.base + row * info.row_bytes + col)),
bits @ (2 | 4) => {
let pixels_per_byte = 8 / bits;
let byte = bus.read_byte(info.base + row * info.row_bytes + col / pixels_per_byte);
let shift = 8 - bits - (col % pixels_per_byte) * bits;
Some((byte >> shift) & ((1u8 << bits) - 1))
}
1 => {
let addr = info.base + row * info.row_bytes + (col / 8);
let bit = 7 - (col % 8);
let byte = bus.read_byte(addr);
Some(if (byte & (1 << bit)) != 0 { 255 } else { 0 })
}
_ => None,
}
}
fn read_bitmap_raw_pixel(
bus: &MacMemoryBus,
info: &CopyBitmapInfo,
y: i16,
x: i16,
) -> Option<u32> {
if y < info.bounds_top
|| y >= info.bounds_bottom
|| x < info.bounds_left
|| x >= info.bounds_right
{
return None;
}
let row = u32::try_from(i32::from(y) - i32::from(info.bounds_top)).ok()?;
let col = u32::try_from(i32::from(x) - i32::from(info.bounds_left)).ok()?;
let row_base = info.base.checked_add(row.checked_mul(info.row_bytes)?)?;
match info.pixel_size {
1 | 2 | 4 => {
let pixels_per_byte = 8 / info.pixel_size;
let byte = bus.read_byte(row_base.checked_add(col.checked_div(pixels_per_byte)?)?);
let shift = 8 - info.pixel_size - (col % pixels_per_byte) * info.pixel_size;
Some(u32::from((byte >> shift) & ((1u8 << info.pixel_size) - 1)))
}
8 => Some(u32::from(bus.read_byte(row_base.checked_add(col)?))),
16 => Some(u32::from(
bus.read_word(row_base.checked_add(col.checked_mul(2)?)?),
)),
32 => Some(bus.read_long(row_base.checked_add(col.checked_mul(4)?)?)),
_ => None,
}
}
fn write_bitmap_raw_pixel(
bus: &mut MacMemoryBus,
info: &CopyBitmapInfo,
y: i16,
x: i16,
pixel: u32,
) -> bool {
if y < info.bounds_top
|| y >= info.bounds_bottom
|| x < info.bounds_left
|| x >= info.bounds_right
{
return false;
}
let Some(row) = u32::try_from(i32::from(y) - i32::from(info.bounds_top)).ok() else {
return false;
};
let Some(col) = u32::try_from(i32::from(x) - i32::from(info.bounds_left)).ok() else {
return false;
};
let Some(row_base) = info
.base
.checked_add(row.saturating_mul(info.row_bytes))
else {
return false;
};
match info.pixel_size {
1 | 2 | 4 => {
let pixels_per_byte = 8 / info.pixel_size;
let Some(addr) = row_base.checked_add(col / pixels_per_byte) else {
return false;
};
let shift = 8 - info.pixel_size - (col % pixels_per_byte) * info.pixel_size;
let value_mask = (1u8 << info.pixel_size) - 1;
let field_mask = value_mask << shift;
let byte = bus.read_byte(addr);
bus.write_byte(
addr,
(byte & !field_mask) | (((pixel as u8) & value_mask) << shift),
);
true
}
8 => {
bus.write_byte(row_base + col, pixel as u8);
true
}
16 => {
bus.write_word(row_base + col.saturating_mul(2), pixel as u16);
true
}
32 => {
bus.write_long(row_base + col.saturating_mul(4), pixel);
true
}
_ => false,
}
}
fn bitmap_pixel_rgb(
_bus: &MacMemoryBus,
info: &CopyBitmapInfo,
pixel: u32,
clut: Option<&[[u16; 3]; 256]>,
) -> Option<[u16; 3]> {
match info.pixel_size {
1 => Some(if pixel == 0 {
[0xFFFF, 0xFFFF, 0xFFFF]
} else {
[0, 0, 0]
}),
2 | 4 | 8 => clut?.get(usize::try_from(pixel).ok()?).copied(),
16 => {
let packed = pixel as u16;
let expand5 = |component: u16| {
(component << 11) | (component << 6) | (component << 1) | (component >> 4)
};
Some([
expand5((packed >> 10) & 0x1F),
expand5((packed >> 5) & 0x1F),
expand5(packed & 0x1F),
])
}
32 => {
// 32-bit PixMaps carry an unused byte followed by R, G, B.
Some([
((pixel >> 16) as u8 as u16) * 0x0101,
((pixel >> 8) as u8 as u16) * 0x0101,
(pixel as u8 as u16) * 0x0101,
])
}
_ => None,
}
}
fn bitmap_rgb_to_pixel(
info: &CopyBitmapInfo,
rgb: [u16; 3],
clut: Option<&[[u16; 3]; 256]>,
) -> Option<u32> {
match info.pixel_size {
1 => {
let white_distance = u64::from(0xFFFFu16.saturating_sub(rgb[0])).pow(2)
+ u64::from(0xFFFFu16.saturating_sub(rgb[1])).pow(2)
+ u64::from(0xFFFFu16.saturating_sub(rgb[2])).pow(2);
let black_distance = u64::from(rgb[0]).pow(2)
+ u64::from(rgb[1]).pow(2)
+ u64::from(rgb[2]).pow(2);
Some(u32::from(black_distance <= white_distance))
}
depth @ (2 | 4 | 8) => Some(u32::from(Self::nearest_palette_index_with_entry_count(
clut?,
rgb,
1usize << depth,
))),
16 => Some(u32::from(
((rgb[0] >> 11) << 10) | ((rgb[1] >> 11) << 5) | (rgb[2] >> 11),
)),
32 => Some(
(u32::from(rgb[0] >> 8) << 16)
| (u32::from(rgb[1] >> 8) << 8)
| u32::from(rgb[2] >> 8),
),
_ => None,
}
}
fn blend_deep_mask_rgb(source: [u16; 3], destination: [u16; 3], mask: [u16; 3]) -> [u16; 3] {
std::array::from_fn(|component| {
let source = u64::from(source[component]);
let destination = u64::from(destination[component]);
let mask = u64::from(mask[component]);
((source * (u64::from(u16::MAX) - mask) + destination * mask + 32_767)
/ u64::from(u16::MAX)) as u16
})
}
fn deep_mask_boolean_pixel(source: u32, destination: u32, depth: u32, mode: u16) -> u32 {
let mask = match depth {
1 | 2 | 4 | 8 => (1u32 << depth) - 1,
16 => u32::from(u16::MAX),
32 => u32::MAX,
_ => 0,
};
match mode {
0 => source,
1 => source | destination,
2 => source ^ destination,
3 => (!source) & destination & mask,
4 => (!source) & mask,
5 => ((!source) & mask) | destination,
6 => ((!source) & mask) ^ destination,
7 => source & destination,
_ => source,
}
}
fn read_packed_bitmap_index(
bus: &MacMemoryBus,
base: u32,
row_bytes: u32,
pixel_size: u32,
bounds_top: i16,
bounds_left: i16,
bounds_bottom: i16,
bounds_right: i16,
y: i16,
x: i16,
) -> Option<u8> {
if base == 0
|| row_bytes == 0
|| y < bounds_top
|| y >= bounds_bottom
|| x < bounds_left
|| x >= bounds_right
{
return None;
}
let row = (y - bounds_top) as u32;
let col = (x - bounds_left) as u32;
match pixel_size {
1 => {
let byte = bus.read_byte(base + row * row_bytes + col / 8);
let shift = 7 - (col % 8);
Some((byte >> shift) & 0x01)
}
2 => {
let byte = bus.read_byte(base + row * row_bytes + col / 4);
let shift = 6 - (col % 4) * 2;
Some((byte >> shift) & 0x03)
}
4 => {
let byte = bus.read_byte(base + row * row_bytes + col / 2);
let shift = 4 - (col % 2) * 4;
Some((byte >> shift) & 0x0F)
}
8 => Some(bus.read_byte(base + row * row_bytes + col)),
_ => None,
}
}
pub(super) fn seed_fill_1bpp_mask(
bus: &mut MacMemoryBus,
src_ptr: u32,
dst_ptr: u32,
src_row: i16,
dst_row: i16,
height: i16,
words: i16,
seed_h: i16,
seed_v: i16,
) -> bool {
if src_ptr == 0 || dst_ptr == 0 || src_row <= 0 || dst_row <= 0 || height <= 0 || words <= 0
{
return false;
}
let width = (words as usize).saturating_mul(16);
let width_bytes = (words as usize).saturating_mul(2);
let height = height as usize;
let src_row = src_row as usize;
let dst_row = dst_row as usize;
if width == 0 || width_bytes == 0 || src_row < width_bytes || dst_row < width_bytes {
return false;
}
let Some(pixel_count) = width.checked_mul(height) else {
return false;
};
if pixel_count > SEEDFILL_MAX_PIXELS {
return false;
}
let Some(src_len) = Self::raw_1bpp_image_len(src_row, height, width_bytes) else {
return false;
};
let Some(dst_len) = Self::raw_1bpp_image_len(dst_row, height, width_bytes) else {
return false;
};
if !Self::guest_range_in_ram(bus, src_ptr, src_len)
|| !Self::guest_range_in_ram(bus, dst_ptr, dst_len)
{
return false;
}
let mut source = Vec::with_capacity(pixel_count);
for y in 0..height {
for x in 0..width {
source.push(Self::raw_1bpp_bit(bus, src_ptr, src_row, y, x));
}
}
for y in 0..height {
let row_addr = dst_ptr + (y * dst_row) as u32;
for byte in 0..width_bytes {
bus.write_byte(row_addr + byte as u32, 0);
}
}
if seed_h < 0 || seed_v < 0 || seed_h as usize >= width || seed_v as usize >= height {
return true;
}
let seed_x = seed_h as usize;
let seed_y = seed_v as usize;
let seed_value = source[seed_y * width + seed_x];
let mut seen = vec![false; pixel_count];
let mut stack = vec![(seed_x, seed_y)];
while let Some((x, y)) = stack.pop() {
let index = y * width + x;
if seen[index] {
continue;
}
seen[index] = true;
if source[index] != seed_value {
continue;
}
Self::set_raw_1bpp_bit(bus, dst_ptr, dst_row, y, x, true);
if x > 0 {
stack.push((x - 1, y));
}
if x + 1 < width {
stack.push((x + 1, y));
}
if y > 0 {
stack.push((x, y - 1));
}
if y + 1 < height {
stack.push((x, y + 1));
}
}
true
}
fn raw_1bpp_image_len(row_bytes: usize, height: usize, width_bytes: usize) -> Option<u32> {
if height == 0 {
return Some(0);
}
let len = height
.checked_sub(1)?
.checked_mul(row_bytes)?
.checked_add(width_bytes)?;
u32::try_from(len).ok()
}
fn raw_1bpp_bit(bus: &MacMemoryBus, base: u32, row_bytes: usize, y: usize, x: usize) -> bool {
let addr = base + (y * row_bytes + x / 8) as u32;
let bit = 7 - (x % 8);
(bus.read_byte(addr) & (1u8 << bit)) != 0
}
fn set_raw_1bpp_bit(
bus: &mut MacMemoryBus,
base: u32,
row_bytes: usize,
y: usize,
x: usize,
value: bool,
) {
let addr = base + (y * row_bytes + x / 8) as u32;
let mask = 1u8 << (7 - (x % 8));
let byte = bus.read_byte(addr);
bus.write_byte(addr, if value { byte | mask } else { byte & !mask });
}
fn region_ptr_and_size(bus: &MacMemoryBus, rgn_handle: u32) -> Option<(u32, u32)> {
if rgn_handle == 0 {
return None;
}
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr == 0 {
return None;
}
Some((rgn_ptr, u32::from(bus.read_word(rgn_ptr))))
}
pub(crate) fn region_bbox(bus: &MacMemoryBus, rgn_handle: u32) -> Option<(i16, i16, i16, i16)> {
let (rgn_ptr, _) = Self::region_ptr_and_size(bus, rgn_handle)?;
let top = bus.read_word(rgn_ptr + 2) as i16;
let left = bus.read_word(rgn_ptr + 4) as i16;
let bottom = bus.read_word(rgn_ptr + 6) as i16;
let right = bus.read_word(rgn_ptr + 8) as i16;
(bottom > top && right > left).then_some((top, left, bottom, right))
}
fn clip_rect_to_region_bbox(
bus: &MacMemoryBus,
rgn_handle: u32,
clip_t: &mut i16,
clip_l: &mut i16,
clip_b: &mut i16,
clip_r: &mut i16,
) -> bool {
if rgn_handle == 0 {
return true;
}
let Some((top, left, bottom, right)) = Self::region_bbox(bus, rgn_handle) else {
return false;
};
*clip_t = (*clip_t).max(top);
*clip_l = (*clip_l).max(left);
*clip_b = (*clip_b).min(bottom);
*clip_r = (*clip_r).min(right);
*clip_b > *clip_t && *clip_r > *clip_l
}
/// Whether a region can exclude pixels that lie inside its bounding
/// box. A region whose data is only the 10-byte header is exactly its
/// bounding rectangle (Inside Macintosh Volume I, I-141), so a caller
/// that already clipped to that rectangle can skip the per-pixel
/// membership test. An unreadable region keeps the test, which then
/// rejects every pixel as before.
fn region_needs_pixel_test(bus: &MacMemoryBus, rgn_handle: u32) -> bool {
if rgn_handle == 0 {
return false;
}
match Self::region_ptr_and_size(bus, rgn_handle) {
Some((_, rgn_size)) => rgn_size > REGION_HEADER_SIZE,
None => true,
}
}
pub(super) fn region_is_complex(bus: &MacMemoryBus, rgn_handle: u32) -> bool {
let Some((_, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return false;
};
rgn_size > REGION_HEADER_SIZE
}
fn drawpicture_rect_intersects_current_port_clip(
bus: &MacMemoryBus,
port: u32,
top: i16,
left: i16,
bottom: i16,
right: i16,
) -> bool {
if port == 0 || bottom <= top || right <= left {
return false;
}
for region_offset in [24u32, 28u32] {
let rgn_handle = bus.read_long(port.wrapping_add(region_offset));
if rgn_handle == 0 {
continue;
}
let Some((rgn_top, rgn_left, rgn_bottom, rgn_right)) =
Self::region_bbox(bus, rgn_handle)
else {
return false;
};
if top >= rgn_bottom || bottom <= rgn_top || left >= rgn_right || right <= rgn_left {
return false;
}
}
true
}
pub(crate) fn drawpicture_current_port_pixel_clip(
bus: &MacMemoryBus,
port: u32,
bounds_top: i16,
bounds_left: i16,
port_w: u16,
port_h: u16,
) -> Option<super::pict::DstClip> {
if port == 0 {
return None;
}
let mut clip_top = 0i32;
let mut clip_left = 0i32;
let mut clip_bottom = i32::from(port_h);
let mut clip_right = i32::from(port_w);
let mut regions = Vec::new();
let bounds_bottom = bounds_top.saturating_add(port_h as i16);
let bounds_right = bounds_left.saturating_add(port_w as i16);
for region_offset in [24u32, 28u32] {
let rgn_handle = bus.read_long(port.wrapping_add(region_offset));
if rgn_handle == 0 {
continue;
}
let Some((rgn_top, rgn_left, rgn_bottom, rgn_right)) =
Self::region_bbox(bus, rgn_handle)
else {
return Some(super::pict::DstClip::new((0, 0, 0, 0), Vec::new()));
};
let region_top = i32::from(rgn_top) - i32::from(bounds_top);
let region_left = i32::from(rgn_left) - i32::from(bounds_left);
let region_bottom = i32::from(rgn_bottom) - i32::from(bounds_top);
let region_right = i32::from(rgn_right) - i32::from(bounds_left);
clip_top = clip_top.max(region_top);
clip_left = clip_left.max(region_left);
clip_bottom = clip_bottom.min(region_bottom);
clip_right = clip_right.min(region_right);
let clipped_top = rgn_top.max(bounds_top);
let clipped_left = rgn_left.max(bounds_left);
let clipped_bottom = rgn_bottom.min(bounds_bottom);
let clipped_right = rgn_right.min(bounds_right);
if clipped_bottom <= clipped_top || clipped_right <= clipped_left {
return Some(super::pict::DstClip::new((0, 0, 0, 0), Vec::new()));
}
let Some((_, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return Some(super::pict::DstClip::new((0, 0, 0, 0), Vec::new()));
};
if rgn_size <= REGION_HEADER_SIZE {
regions.push(super::pict::DstClipRegion::rectangular(
i32::from(clipped_top) - i32::from(bounds_top),
i32::from(clipped_left) - i32::from(bounds_left),
i32::from(clipped_bottom) - i32::from(bounds_top),
i32::from(clipped_right) - i32::from(bounds_left),
));
continue;
}
let Some(cache) =
Self::build_region_membership_cache(bus, rgn_handle, clipped_top, clipped_bottom)
else {
return Some(super::pict::DstClip::new((0, 0, 0, 0), Vec::new()));
};
let rows = cache
.rows
.into_iter()
.map(|row| {
row.into_iter()
.map(|edge| i32::from(edge) - i32::from(bounds_left))
.collect()
})
.collect();
regions.push(super::pict::DstClipRegion::complex(
i32::from(clipped_top) - i32::from(bounds_top),
i32::from(clipped_left) - i32::from(bounds_left),
i32::from(clipped_bottom) - i32::from(bounds_top),
i32::from(clipped_right) - i32::from(bounds_left),
rows,
));
}
Some(super::pict::DstClip::new(
(clip_top, clip_left, clip_bottom, clip_right),
regions,
))
}
fn ensure_region_capacity(bus: &mut MacMemoryBus, rgn_handle: u32, size: u32) -> Option<u32> {
if rgn_handle == 0 {
return None;
}
let current_ptr = bus.read_long(rgn_handle);
if current_ptr != 0 {
match bus.get_alloc_size(current_ptr) {
Some(current_size) if current_size >= size => return Some(current_ptr),
None => return Some(current_ptr),
_ => {}
}
}
let new_ptr = bus.alloc(size);
if new_ptr == 0 {
return None;
}
bus.write_long(rgn_handle, new_ptr);
// Regions are relocatable blocks. QuickDraw region operations may
// move their backing storage, while the handle remains stable
// (Imaging With QuickDraw, 1994, pp. 3-91–3-92). Once the master
// pointer names the replacement, release the superseded allocation.
bus.free(current_ptr);
Some(new_ptr)
}
fn write_region(
bus: &mut MacMemoryBus,
rgn_handle: u32,
bbox: Option<(i16, i16, i16, i16)>,
data_words: &[i16],
) -> bool {
if rgn_handle == 0 {
return false;
}
let is_rectangular = data_words.is_empty();
let size = if is_rectangular {
REGION_HEADER_SIZE
} else {
REGION_HEADER_SIZE + (data_words.len() as u32 * 2)
};
let Some(rgn_ptr) = Self::ensure_region_capacity(bus, rgn_handle, size) else {
return false;
};
bus.write_word(rgn_ptr, size as u16);
if let Some((top, left, bottom, right)) = bbox {
bus.write_word(rgn_ptr + 2, top as u16);
bus.write_word(rgn_ptr + 4, left as u16);
bus.write_word(rgn_ptr + 6, bottom as u16);
bus.write_word(rgn_ptr + 8, right as u16);
} else {
bus.write_long(rgn_ptr + 2, 0);
bus.write_long(rgn_ptr + 6, 0);
}
for (index, word) in data_words.iter().enumerate() {
bus.write_word(
rgn_ptr + REGION_HEADER_SIZE + (index as u32 * 2),
*word as u16,
);
}
true
}
fn region_band_height(top: i16, bottom: i16) -> usize {
(i32::from(bottom) - i32::from(top)).max(0) as usize
}
fn region_row_index(y: i16, top: i16) -> usize {
(i32::from(y) - i32::from(top)) as usize
}
pub(super) fn region_rows_for_band(
bus: &MacMemoryBus,
rgn_handle: u32,
top: i16,
bottom: i16,
) -> Vec<Vec<i16>> {
let height = Self::region_band_height(top, bottom);
let mut rows = vec![Vec::new(); height];
if height == 0 {
return rows;
}
let Some((rgn_ptr, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return rows;
};
let rgn_top = bus.read_word(rgn_ptr + 2) as i16;
let rgn_left = bus.read_word(rgn_ptr + 4) as i16;
let rgn_bottom = bus.read_word(rgn_ptr + 6) as i16;
let rgn_right = bus.read_word(rgn_ptr + 8) as i16;
if rgn_bottom <= rgn_top || rgn_right <= rgn_left {
return rows;
}
let overlap_top = top.max(rgn_top);
let overlap_bottom = bottom.min(rgn_bottom);
if overlap_bottom <= overlap_top {
return rows;
}
if rgn_size <= REGION_HEADER_SIZE {
for y in overlap_top..overlap_bottom {
rows[Self::region_row_index(y, top)] = vec![rgn_left, rgn_right];
}
return rows;
}
if let Some(cache) =
Self::build_region_membership_cache(bus, rgn_handle, overlap_top, overlap_bottom)
{
let start = Self::region_row_index(overlap_top, top);
for (offset, row) in cache.rows.into_iter().enumerate() {
rows[start + offset] = row;
}
}
rows
}
#[inline]
fn intervals_to_endpoints(intervals: Vec<(i16, i16)>) -> Vec<i16> {
region_rows::intervals_to_endpoints(intervals)
}
#[inline]
fn intersect_region_rows(lhs: &[i16], rhs: &[i16]) -> Vec<i16> {
region_rows::intersect_rows(lhs, rhs)
}
#[inline]
fn union_region_rows(lhs: &[i16], rhs: &[i16]) -> Vec<i16> {
region_rows::union_rows(lhs, rhs)
}
#[inline]
fn combine_region_rows(lhs: &[i16], rhs: &[i16], op: RegionBooleanOp) -> Vec<i16> {
region_rows::combine_rows(lhs, rhs, op)
}
fn quantize_region_edge(edge: f64) -> i16 {
Self::clamp_region_coord((edge - 0.5).ceil() as i32)
}
fn recorded_outline_rows(
segments: &[((i16, i16), (i16, i16))],
top: i16,
bottom: i16,
) -> Vec<Vec<i16>> {
let height = Self::region_band_height(top, bottom);
let mut rows = vec![Vec::new(); height];
if height == 0 || segments.is_empty() {
return rows;
}
for y32 in i32::from(top)..i32::from(bottom) {
let y = y32 as i16;
let scan_y = f64::from(y) + 0.5;
let mut crossings = Vec::new();
for &((v0, h0), (v1, h1)) in segments {
if v0 == v1 {
continue;
}
let y0 = f64::from(v0);
let y1 = f64::from(v1);
let min_y = y0.min(y1);
let max_y = y0.max(y1);
if scan_y < min_y || scan_y >= max_y {
continue;
}
let x0 = f64::from(h0);
let x1 = f64::from(h1);
let t = (scan_y - y0) / (y1 - y0);
crossings.push(x0 + t * (x1 - x0));
}
crossings.sort_by(|lhs, rhs| lhs.partial_cmp(rhs).unwrap());
let intervals = crossings
.chunks_exact(2)
.filter_map(|pair| {
let left = Self::quantize_region_edge(pair[0].min(pair[1]));
let right = Self::quantize_region_edge(pair[0].max(pair[1]));
(left < right).then_some((left, right))
})
.collect::<Vec<_>>();
rows[Self::region_row_index(y, top)] = Self::intervals_to_endpoints(intervals);
}
rows
}
fn recorded_region_rows(
recording: &super::dispatch::RegionRecording,
) -> Option<(i16, Vec<Vec<i16>>)> {
let (top, _, bottom, _) = recording.bbox?;
if bottom <= top {
return None;
}
let mut rows = vec![Vec::new(); Self::region_band_height(top, bottom)];
for (&y, row) in recording.filled_rows.iter() {
if y < top || y >= bottom {
continue;
}
let index = Self::region_row_index(y, top);
rows[index] = Self::union_region_rows(&rows[index], row);
}
let outline_rows = Self::recorded_outline_rows(&recording.outline_segments, top, bottom);
for (row, outline_row) in rows.iter_mut().zip(outline_rows.iter()) {
*row = Self::union_region_rows(row, outline_row);
}
Some((top, rows))
}
pub(super) fn write_region_from_rows(
bus: &mut MacMemoryBus,
rgn_handle: u32,
rows_top: i16,
rows: &[Vec<i16>],
) -> bool {
let mut bbox: Option<(i16, i16, i16, i16)> = None;
for (row_index, row) in rows.iter().enumerate() {
if row.is_empty() {
continue;
}
let y = Self::clamp_region_coord(i32::from(rows_top) + row_index as i32);
let next_y = Self::clamp_region_coord(i32::from(y) + 1);
let left = row[0];
let right = *row.last().unwrap();
bbox = Some(match bbox {
Some((top, current_left, bottom, current_right)) => (
top,
current_left.min(left),
bottom.max(next_y),
current_right.max(right),
),
None => (y, left, next_y, right),
});
}
let Some((top, left, bottom, right)) = bbox else {
return Self::write_region(bus, rgn_handle, None, &[]);
};
let first_row = &rows[Self::region_row_index(top, rows_top)];
let rectangular = first_row.len() == 2
&& first_row[0] == left
&& first_row[1] == right
&& (i32::from(top)..i32::from(bottom)).all(|y32| {
let y = y32 as i16;
rows[Self::region_row_index(y, rows_top)] == *first_row
});
if rectangular {
return Self::write_region(bus, rgn_handle, Some((top, left, bottom, right)), &[]);
}
let mut data_words = Vec::new();
let mut previous_row = Vec::new();
for y32 in i32::from(top)..=i32::from(bottom) {
let y = y32 as i16;
let current_row = if y < bottom {
rows[Self::region_row_index(y, rows_top)].clone()
} else {
Vec::new()
};
let delta = Self::merge_region_endpoints(&previous_row, ¤t_row);
if !delta.is_empty() {
data_words.push(y);
data_words.extend(delta);
data_words.push(REGION_STOP);
}
previous_row = current_row;
}
data_words.push(REGION_STOP);
Self::write_region(
bus,
rgn_handle,
Some((top, left, bottom, right)),
&data_words,
)
}
pub(super) fn write_region_boolean_op(
bus: &mut MacMemoryBus,
dst_handle: u32,
src_a: u32,
src_b: u32,
op: RegionBooleanOp,
) -> bool {
let bbox_a = Self::region_bbox(bus, src_a);
let bbox_b = Self::region_bbox(bus, src_b);
let band = match op {
RegionBooleanOp::Intersection => {
let (Some(a), Some(b)) = (bbox_a, bbox_b) else {
return Self::write_region(bus, dst_handle, None, &[]);
};
let top = a.0.max(b.0);
let bottom = a.2.min(b.2);
if bottom <= top {
return Self::write_region(bus, dst_handle, None, &[]);
}
(top, bottom)
}
RegionBooleanOp::Difference => {
let Some(a) = bbox_a else {
return Self::write_region(bus, dst_handle, None, &[]);
};
(a.0, a.2)
}
RegionBooleanOp::Union | RegionBooleanOp::Xor => match (bbox_a, bbox_b) {
(Some(a), Some(b)) => (a.0.min(b.0), a.2.max(b.2)),
(Some(a), None) => (a.0, a.2),
(None, Some(b)) => (b.0, b.2),
(None, None) => return Self::write_region(bus, dst_handle, None, &[]),
},
};
let (top, bottom) = band;
if bottom <= top {
return Self::write_region(bus, dst_handle, None, &[]);
}
let rows_a = Self::region_rows_for_band(bus, src_a, top, bottom);
let rows_b = Self::region_rows_for_band(bus, src_b, top, bottom);
let rows = rows_a
.iter()
.zip(rows_b.iter())
.map(|(lhs, rhs)| Self::combine_region_rows(lhs, rhs, op))
.collect::<Vec<_>>();
Self::write_region_from_rows(bus, dst_handle, top, &rows)
}
pub(super) fn offset_region(bus: &mut MacMemoryBus, rgn_handle: u32, dh: i16, dv: i16) {
let Some((rgn_ptr, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return;
};
if rgn_size < REGION_HEADER_SIZE {
return;
}
for offset in [2u32, 6u32] {
let value = bus.read_word(rgn_ptr + offset) as i16;
bus.write_word(rgn_ptr + offset, value.wrapping_add(dv) as u16);
}
for offset in [4u32, 8u32] {
let value = bus.read_word(rgn_ptr + offset) as i16;
bus.write_word(rgn_ptr + offset, value.wrapping_add(dh) as u16);
}
if rgn_size <= REGION_HEADER_SIZE {
return;
}
let region_end = rgn_ptr + rgn_size;
let mut cursor = rgn_ptr + REGION_HEADER_SIZE;
while cursor + 2 <= region_end {
let y = bus.read_word(cursor) as i16;
if y == REGION_STOP {
break;
}
bus.write_word(cursor, y.wrapping_add(dv) as u16);
cursor += 2;
while cursor + 2 <= region_end {
let edge = bus.read_word(cursor) as i16;
if edge == REGION_STOP {
cursor += 2;
break;
}
bus.write_word(cursor, edge.wrapping_add(dh) as u16);
cursor += 2;
}
}
}
#[inline]
fn clamp_region_coord(value: i32) -> i16 {
region_rows::clamp_coord(value)
}
#[inline]
pub(super) fn inset_region_row(row: &[i16], dh: i16) -> Vec<i16> {
region_rows::inset_row(row, dh)
}
fn inset_region(bus: &mut MacMemoryBus, rgn_handle: u32, dh: i16, dv: i16) {
let Some((rgn_ptr, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return;
};
if rgn_size < REGION_HEADER_SIZE {
return;
}
let top = bus.read_word(rgn_ptr + 2) as i16;
let left = bus.read_word(rgn_ptr + 4) as i16;
let bottom = bus.read_word(rgn_ptr + 6) as i16;
let right = bus.read_word(rgn_ptr + 8) as i16;
if bottom <= top || right <= left {
let _ = Self::write_region(bus, rgn_handle, None, &[]);
return;
}
let new_top = Self::clamp_region_coord(i32::from(top) + i32::from(dv));
let new_left = Self::clamp_region_coord(i32::from(left) + i32::from(dh));
let new_bottom = Self::clamp_region_coord(i32::from(bottom) - i32::from(dv));
let new_right = Self::clamp_region_coord(i32::from(right) - i32::from(dh));
if new_bottom <= new_top || new_right <= new_left {
let _ = Self::write_region(bus, rgn_handle, None, &[]);
return;
}
if rgn_size <= REGION_HEADER_SIZE {
let _ = Self::write_region(
bus,
rgn_handle,
Some((new_top, new_left, new_bottom, new_right)),
&[],
);
return;
}
let src_rows = Self::region_rows_for_band(bus, rgn_handle, top, bottom);
let horizontal_rows = src_rows
.iter()
.map(|row| Self::inset_region_row(row, dh))
.collect::<Vec<_>>();
let source_top = i32::from(top);
let source_bottom = i32::from(bottom);
let radius = i32::from(dv).abs();
let mut rows = Vec::with_capacity(Self::region_band_height(new_top, new_bottom));
for y in i32::from(new_top)..i32::from(new_bottom) {
if dv >= 0 {
let first_source_y = y - radius;
let last_source_y = y + radius;
if first_source_y < source_top || last_source_y >= source_bottom {
rows.push(Vec::new());
continue;
}
let mut combined: Option<Vec<i16>> = None;
for source_y in first_source_y..=last_source_y {
let source_row = &horizontal_rows[(source_y - source_top) as usize];
combined = Some(match combined {
Some(current) => Self::intersect_region_rows(¤t, source_row),
None => source_row.clone(),
});
if combined.as_ref().is_some_and(Vec::is_empty) {
break;
}
}
rows.push(combined.unwrap_or_default());
} else {
let first_source_y = (y - radius).max(source_top);
let last_source_y = (y + radius).min(source_bottom - 1);
if first_source_y > last_source_y {
rows.push(Vec::new());
continue;
}
let mut combined = Vec::new();
for source_y in first_source_y..=last_source_y {
let source_row = &horizontal_rows[(source_y - source_top) as usize];
combined = Self::union_region_rows(&combined, source_row);
}
rows.push(combined);
}
}
let _ = Self::write_region_from_rows(bus, rgn_handle, new_top, &rows);
}
#[inline]
fn merge_region_endpoints(lhs: &[i16], rhs: &[i16]) -> Vec<i16> {
region_rows::merge_endpoints(lhs, rhs)
}
#[inline]
pub(super) fn endpoints_contain_point(endpoints: &[i16], x: i16) -> bool {
region_rows::endpoints_contain_point(endpoints, x)
}
fn scan_bitmap_row_endpoints(bus: &MacMemoryBus, info: &CopyBitmapInfo, y: i16) -> Vec<i16> {
let mut endpoints = Vec::new();
let row = (y - info.bounds_top) as u32;
let row_base = info.base + row * info.row_bytes;
let mut in_run = false;
for x in info.bounds_left..info.bounds_right {
let col = (x - info.bounds_left) as u32;
let byte = bus.read_byte(row_base + (col / 8));
let bit = 7 - (col % 8);
let pixel_is_set = (byte & (1 << bit)) != 0;
if pixel_is_set && !in_run {
endpoints.push(x);
in_run = true;
} else if !pixel_is_set && in_run {
endpoints.push(x);
in_run = false;
}
}
if in_run {
endpoints.push(info.bounds_right);
}
endpoints
}
pub(super) fn build_region_membership_cache(
bus: &MacMemoryBus,
rgn_handle: u32,
top: i16,
bottom: i16,
) -> Option<RegionMembershipCache> {
let (rgn_ptr, rgn_size) = Self::region_ptr_and_size(bus, rgn_handle)?;
if rgn_size <= REGION_HEADER_SIZE || bottom <= top {
return None;
}
let region_end = rgn_ptr + rgn_size;
let mut cursor = rgn_ptr + REGION_HEADER_SIZE;
if cursor + 2 > region_end {
return None;
}
let mut next_change_y = bus.read_word(cursor) as i16;
cursor += 2;
let mut active = Vec::new();
let mut rows = Vec::with_capacity(Self::region_band_height(top, bottom));
for y32 in i32::from(top)..i32::from(bottom) {
let y = y32 as i16;
while next_change_y != REGION_STOP && next_change_y <= y {
let mut delta = Vec::new();
loop {
if cursor + 2 > region_end {
return None;
}
let value = bus.read_word(cursor) as i16;
cursor += 2;
if value == REGION_STOP {
break;
}
delta.push(value);
}
active = Self::merge_region_endpoints(&active, &delta);
if cursor + 2 > region_end {
return None;
}
next_change_y = bus.read_word(cursor) as i16;
cursor += 2;
}
rows.push(active.clone());
}
Some(RegionMembershipCache { top, rows })
}
pub(crate) fn region_contains_point(
bus: &MacMemoryBus,
rgn_handle: u32,
y: i16,
x: i16,
) -> bool {
let Some((top, left, bottom, right)) = Self::region_bbox(bus, rgn_handle) else {
return false;
};
if y < top || y >= bottom || x < left || x >= right {
return false;
}
let Some((_, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return false;
};
if rgn_size <= REGION_HEADER_SIZE {
return true;
}
let Some(cache) = Self::build_region_membership_cache(bus, rgn_handle, y, y + 1) else {
return false;
};
cache
.rows
.first()
.map(|row| Self::endpoints_contain_point(row, x))
.unwrap_or(false)
}
/// RectInRgn helper — tests whether any pixel in `rect_ptr` lies inside
/// `rgn_handle`. For rectangular regions a bounding-box intersection is
/// sufficient. For complex regions we build a per-row membership cache and
/// scan each row in the overlap band for a span that overlaps the rect's
/// horizontal extent.
///
/// IM:I I-185 — "Returns TRUE if any pixel enclosed by r lies within rgn."
fn rect_in_rgn(bus: &MacMemoryBus, rgn_handle: u32, rect_ptr: u32) -> bool {
if rgn_handle == 0 || rect_ptr == 0 {
return false;
}
let Some((rgn_ptr, rgn_size)) = Self::region_ptr_and_size(bus, rgn_handle) else {
return false;
};
let rt = bus.read_word(rect_ptr) as i16;
let rl = bus.read_word(rect_ptr + 2) as i16;
let rb = bus.read_word(rect_ptr + 4) as i16;
let rr = bus.read_word(rect_ptr + 6) as i16;
// Empty rect → no pixels to test
if rb <= rt || rr <= rl {
return false;
}
let gt = bus.read_word(rgn_ptr + 2) as i16;
let gl = bus.read_word(rgn_ptr + 4) as i16;
let gb = bus.read_word(rgn_ptr + 6) as i16;
let gr = bus.read_word(rgn_ptr + 8) as i16;
// Bounding-box intersection fast-out
if rt >= gb || rb <= gt || rl >= gr || rr <= gl {
return false;
}
// Rectangular region: bbox test is exact
if rgn_size <= REGION_HEADER_SIZE {
return true;
}
// Complex region: check each row in the overlap band for a span that
// covers at least one x in [rl, rr).
let top = rt.max(gt);
let bottom = rb.min(gb);
let Some(cache) = Self::build_region_membership_cache(bus, rgn_handle, top, bottom) else {
// Cache build failed — fall back to bbox result
return true;
};
let left = rl.max(gl);
let right = rr.min(gr);
for row in &cache.rows {
// A row has an active span overlapping [left, right) iff the
// toggle count at `left` is odd (point is inside) OR there is a
// toggle before `right` (a span starts before right and inside
// the rect starts at or before right).
//
// The endpoints list is sorted. We scan it with the even/odd
// rule. If we are inside at `left`, the row qualifies. If we
// are outside at `left` but there is a toggle in (left, right),
// that toggle starts a new span inside the rect → qualifies.
let mut inside = false;
for &edge in row.iter() {
if edge >= right {
break;
}
if edge >= left {
// A toggle edge that lies inside the rect: if we are
// currently outside we are entering a span → qualifies.
if !inside {
return true;
}
inside = !inside;
} else {
inside = !inside;
}
}
if inside {
// Still inside at `left` (or re-entered before `right`)
return true;
}
}
false
}
/// `#[inline]` — called per pixel × 3 in the CopyBits inner loop
/// (vis_rgn, clip_rgn, mask_rgn checks). The hot-path early-out
/// (`rgn_handle == 0 → true`) is what we want LLVM to fold across the
/// whole inner loop.
#[inline]
pub(super) fn region_contains_point_cached(
bus: &MacMemoryBus,
rgn_handle: u32,
cache: Option<&RegionMembershipCache>,
y: i16,
x: i16,
) -> bool {
if rgn_handle == 0 {
return true;
}
if let Some(cache) = cache {
let row = y - cache.top;
if row >= 0 && (row as usize) < cache.rows.len() {
return Self::endpoints_contain_point(&cache.rows[row as usize], x);
}
}
Self::region_contains_point(bus, rgn_handle, y, x)
}
fn trace_port_snapshot(bus: &MacMemoryBus, label: &str, port: u32) {
if port == 0 {
eprintln!("[DIALOG-PORT-DUMP] {} port=$00000000", label);
return;
}
let port_version = bus.read_word(port + 6);
let port_rect = (
bus.read_word(port + 16) as i16,
bus.read_word(port + 18) as i16,
bus.read_word(port + 20) as i16,
bus.read_word(port + 22) as i16,
);
let vis_rgn = Self::region_bbox(bus, bus.read_long(port + 24));
let clip_rgn = Self::region_bbox(bus, bus.read_long(port + 28));
let pm_handle = bus.read_long(port + 2);
let pm_ptr = if pm_handle != 0 {
bus.read_long(pm_handle)
} else {
0
};
eprintln!(
"[DIALOG-PORT-DUMP] {} port=${:08X} version=${:04X} portRect=({},{},{},{}) vis={:?} clip={:?} pnLoc=({}, {}) txFont={} txFace=${:04X} txMode={} txSize={} fgRGB=({:04X},{:04X},{:04X}) bgRGB=({:04X},{:04X},{:04X}) fgLegacy=${:08X} bgLegacy=${:08X}",
label,
port,
port_version,
port_rect.0,
port_rect.1,
port_rect.2,
port_rect.3,
vis_rgn,
clip_rgn,
bus.read_word(port + 48) as i16,
bus.read_word(port + 50) as i16,
bus.read_word(port + 68),
bus.read_word(port + 70),
bus.read_word(port + 72),
bus.read_word(port + 74),
bus.read_word(port + 36),
bus.read_word(port + 38),
bus.read_word(port + 40),
bus.read_word(port + 42),
bus.read_word(port + 44),
bus.read_word(port + 46),
bus.read_long(port + 80),
bus.read_long(port + 84),
);
if pm_ptr != 0 {
eprintln!(
"[DIALOG-PORT-DUMP] {} pixMapHandle=${:08X} pixMap=${:08X} base=${:08X} rowBytes=${:04X} bounds=({},{},{},{}) pixelSize={} ctab=${:08X}",
label,
pm_handle,
pm_ptr,
Self::offscreen_pixmap_base_ptr(bus, pm_ptr),
bus.read_word(pm_ptr + 4),
bus.read_word(pm_ptr + 6) as i16,
bus.read_word(pm_ptr + 8) as i16,
bus.read_word(pm_ptr + 10) as i16,
bus.read_word(pm_ptr + 12) as i16,
bus.read_word(pm_ptr + 32),
bus.read_long(pm_ptr + 42),
);
} else {
eprintln!(
"[DIALOG-PORT-DUMP] {} pixMapHandle=${:08X} pixMap=$00000000",
label, pm_handle,
);
}
}
fn dump_bitmap_as_png(
bus: &MacMemoryBus,
info: &CopyBitmapInfo,
clut: &[[u16; 3]; 256],
path: &str,
) {
let width = (info.bounds_right - info.bounds_left) as u32;
let height = (info.bounds_bottom - info.bounds_top) as u32;
if width == 0 || height == 0 {
return;
}
let img = image::RgbImage::from_fn(width, height, |x, y| {
let addr = info.base + y * info.row_bytes + x;
let pixel = bus.read_byte(addr);
let rgb = clut[pixel as usize];
image::Rgb([
(rgb[0] >> 8) as u8,
(rgb[1] >> 8) as u8,
(rgb[2] >> 8) as u8,
])
});
let _ = img.save(path);
}
fn scale_coord(
src_start: i16,
src_end: i16,
dst_start: i16,
dst_end: i16,
dst_coord: i16,
) -> Option<i32> {
let src_span = i32::from(src_end) - i32::from(src_start);
let dst_span = i32::from(dst_end) - i32::from(dst_start);
if src_span <= 0 || dst_span <= 0 {
return None;
}
let rel = i32::from(dst_coord) - i32::from(dst_start);
if rel < 0 || rel >= dst_span {
return None;
}
// Valid signed QuickDraw bounds can span 65,535 cells. Their product
// exceeds i32 even when the final mapped coordinate is representable.
let offset = i64::from(rel) * i64::from(src_span) / i64::from(dst_span);
i32::try_from(i64::from(src_start) + offset).ok()
}
pub(crate) fn nearest_palette_index(clut: &[[u16; 3]; 256], rgb: [u16; 3]) -> u8 {
Self::nearest_palette_index_with_entry_count(clut, rgb, 256)
}
fn nearest_palette_index_with_entry_count(
clut: &[[u16; 3]; 256],
rgb: [u16; 3],
entry_count: usize,
) -> u8 {
let entry_count = entry_count.clamp(1, 256);
let terminal_index = entry_count - 1;
// QuickDraw's inverse tables reserve exact white/black for the first
// and last CLUT entries when the endpoints are white/black, rather
// than returning an arbitrary duplicate color-cube entry. During
// fade-to-black steps entry 0 can temporarily equal black too; keep
// canonical black drawing pinned to entry 255 in that collapsed case.
// Imaging With QuickDraw 1994, p. 4-82
// references/executor/src/quickdraw/qColorMgr.cpp (MakeITable)
if rgb == [0, 0, 0] && clut[terminal_index] == [0, 0, 0] {
return terminal_index as u8;
}
if rgb == [0xFFFF, 0xFFFF, 0xFFFF] && clut[0] == [0xFFFF, 0xFFFF, 0xFFFF] {
return 0;
}
if rgb == clut[terminal_index] {
return terminal_index as u8;
}
if rgb == clut[0] {
return 0;
}
if let Some((index, _)) = clut[..entry_count]
.iter()
.enumerate()
.find(|(_, entry)| **entry == rgb)
{
return index as u8;
}
let mut best_index = 0u8;
let mut best_distance = u64::MAX;
for (index, entry) in clut[..entry_count].iter().enumerate() {
let dr = i64::from(entry[0]) - i64::from(rgb[0]);
let dg = i64::from(entry[1]) - i64::from(rgb[1]);
let db = i64::from(entry[2]) - i64::from(rgb[2]);
let distance = (dr * dr + dg * dg + db * db) as u64;
if distance < best_distance {
best_distance = distance;
best_index = index as u8;
}
}
best_index
}
pub(super) fn build_palette_translation(
&self,
bus: &MacMemoryBus,
src_clut: &[[u16; 3]; 256],
dst_clut: &[[u16; 3]; 256],
dst_ctab_handle: u32,
src_pixel_size: u32,
dst_pixel_size: u32,
) -> [u8; 256] {
let mut translation = [0u8; 256];
let dst_entry_count = Self::indexed_ctab_entry_count(dst_pixel_size) as usize;
if src_pixel_size == 4
&& dst_pixel_size == 8
&& Self::uses_standard_mac_4bpp_gworld_clut(src_clut)
&& Self::uses_canonical_system_8bpp_clut(dst_clut)
{
// System 7.5.3 Color2Index results for the default 4-bit
// NewGWorld CTable while the standard 8-bit main GDevice is
// current. The screen GDevice's inverse table differs from a
// full-precision Euclidean search for blue, green, and light
// gray because MakeITable uses ROM propagation and tie-breaking.
//
// Inside Macintosh Volume V, pp. V-137 and V-142
const STANDARD_4_TO_8: [u8; 16] = [
0, 5, 23, 216, 32, 176, 236, 192, 227, 203, 137, 94, 43, 249, 252, 255,
];
translation[..16].copy_from_slice(&STANDARD_4_TO_8);
return translation;
}
for (index, rgb) in src_clut.iter().enumerate() {
translation[index] = if index < dst_entry_count && dst_clut[index] == *rgb {
index as u8
} else {
self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
dst_clut,
*rgb,
dst_entry_count,
)
};
}
translation
}
fn colorize_src_copy_rgb(src_rgb: [u16; 3], fg_rgb: [u16; 3], bg_rgb: [u16; 3]) -> [u16; 3] {
let mut out = [0u16; 3];
for component in 0..3 {
let src = u32::from(src_rgb[component]);
let fg = u32::from(fg_rgb[component]);
let bg = u32::from(bg_rgb[component]);
out[component] = ((((0xFFFF - src) * fg) + (src * bg) + 0x7FFF) / 0xFFFF) as u16;
}
out
}
fn colorize_src_or_rgb(src_rgb: [u16; 3], fg_rgb: [u16; 3], dst_rgb: [u16; 3]) -> [u16; 3] {
// Black source applies the foreground, white source preserves the
// destination, and intermediate source colors interpolate between
// them. Imaging With QuickDraw (1994), pp. 4-32..4-34.
Self::colorize_src_copy_rgb(src_rgb, fg_rgb, dst_rgb)
}
fn colorize_not_src_or_rgb(src_rgb: [u16; 3], fg_rgb: [u16; 3], dst_rgb: [u16; 3]) -> [u16; 3] {
// Black source preserves the destination, white source applies the
// foreground, and intermediate source colors interpolate between
// them. Imaging With QuickDraw (1994), pp. 4-32..4-34.
Self::colorize_src_copy_rgb(src_rgb, dst_rgb, fg_rgb)
}
fn copy_bits_color_source_mode_pixel(
&self,
bus: &MacMemoryBus,
dst_ctab_handle: u32,
src_clut: Option<&[[u16; 3]; 256]>,
dst_clut: Option<&[[u16; 3]; 256]>,
dst_entry_count: usize,
palette_translation: Option<&[u8; 256]>,
shared_indexed_pixel_mask: Option<u8>,
mode_base: u16,
src_pixel: u8,
dst_pixel: u8,
fg_rgb: [u16; 3],
bg_rgb: [u16; 3],
) -> Option<u8> {
if let Some(pixel_mask) = shared_indexed_pixel_mask {
if let Some(pixel) =
Self::indexed_boolean_transfer(src_pixel, dst_pixel, mode_base, pixel_mask)
{
return Some(pixel);
}
}
// Across different indexed color spaces, Color QuickDraw applies
// current foreground/background colors for Boolean source modes and
// leaves destination pixels untouched for the table's white/black
// preserve cases.
// Imaging With QuickDraw 1994, p. 4-33.
let raw_source = || {
palette_translation
.map(|translation| translation[src_pixel as usize])
.unwrap_or(src_pixel)
};
let (Some(src_clut), Some(dst_clut)) = (src_clut, dst_clut) else {
return Some(raw_source());
};
let src_rgb = src_clut[src_pixel as usize];
let dst_rgb = dst_clut[dst_pixel as usize];
let is_black = src_rgb == [0, 0, 0];
let is_white = src_rgb == [0xFFFF, 0xFFFF, 0xFFFF];
let map_rgb = |rgb| {
self.palette_index_for_rgb_with_entry_count(
bus,
dst_ctab_handle,
dst_clut,
rgb,
dst_entry_count,
)
};
match mode_base {
0 => Some(raw_source()),
1 => (!is_white).then(|| map_rgb(Self::colorize_src_or_rgb(src_rgb, fg_rgb, dst_rgb))),
2 => is_black.then(|| Self::inverted_palette_index(dst_clut, dst_pixel)),
3 => (!is_white).then(|| map_rgb(Self::colorize_src_or_rgb(src_rgb, bg_rgb, dst_rgb))),
4 => Some(map_rgb(Self::colorize_src_copy_rgb(
src_rgb, bg_rgb, fg_rgb,
))),
5 => (!is_black)
.then(|| map_rgb(Self::colorize_not_src_or_rgb(src_rgb, fg_rgb, dst_rgb))),
6 => is_white.then(|| Self::inverted_palette_index(dst_clut, dst_pixel)),
7 => (!is_black)
.then(|| map_rgb(Self::colorize_not_src_or_rgb(src_rgb, bg_rgb, dst_rgb))),
_ => Some(raw_source()),
}
}
fn indexed_boolean_transfer(
src_pixel: u8,
dst_pixel: u8,
mode_base: u16,
pixel_mask: u8,
) -> Option<u8> {
// A shared indexed color space makes the pixel value itself the
// Boolean operand. Mask complemented results to the active depth.
// Imaging With QuickDraw (1994), pp. 4-32--4-34.
let src_pixel = src_pixel & pixel_mask;
let dst_pixel = dst_pixel & pixel_mask;
let result = match mode_base {
0 => src_pixel,
1 => src_pixel | dst_pixel,
2 => src_pixel ^ dst_pixel,
3 => !src_pixel & dst_pixel,
4 => !src_pixel,
5 => !src_pixel | dst_pixel,
6 => !src_pixel ^ dst_pixel,
7 => src_pixel & dst_pixel,
_ => return None,
};
Some(result & pixel_mask)
}
fn shared_indexed_pixel_mask(
src_pixel_size: u32,
dst_pixel_size: u32,
src_ctab_handle: u32,
dst_ctab_handle: u32,
src_clut: Option<&[[u16; 3]; 256]>,
dst_clut: Option<&[[u16; 3]; 256]>,
) -> Option<u8> {
// Equal explicit ColorTables describe the same indexed color space;
// null tables instead inherit a device context and cannot establish
// that relationship by themselves.
if src_pixel_size != dst_pixel_size
|| !matches!(src_pixel_size, 2 | 4 | 8)
|| src_ctab_handle == 0
|| dst_ctab_handle == 0
|| (src_ctab_handle != dst_ctab_handle && src_clut != dst_clut)
{
return None;
}
Some(if src_pixel_size == 8 {
u8::MAX
} else {
(1u8 << src_pixel_size) - 1
})
}
fn copy_bits_direct_source_mode_rgb(
src_rgb: [u16; 3],
dst_rgb: [u16; 3],
mode_base: u16,
fg_rgb: [u16; 3],
bg_rgb: [u16; 3],
) -> Option<[u16; 3]> {
let is_black = src_rgb == [0, 0, 0];
let is_white = src_rgb == [0xFFFF, 0xFFFF, 0xFFFF];
match mode_base {
0 => Some(src_rgb),
1 => (!is_white).then(|| Self::colorize_src_or_rgb(src_rgb, fg_rgb, dst_rgb)),
2 => is_black.then(|| {
[
0xFFFF - dst_rgb[0],
0xFFFF - dst_rgb[1],
0xFFFF - dst_rgb[2],
]
}),
3 => (!is_white).then(|| Self::colorize_src_or_rgb(src_rgb, bg_rgb, dst_rgb)),
4 => Some(Self::colorize_src_copy_rgb(src_rgb, bg_rgb, fg_rgb)),
5 => (!is_black).then(|| Self::colorize_not_src_or_rgb(src_rgb, fg_rgb, dst_rgb)),
6 => is_white.then(|| {
[
0xFFFF - dst_rgb[0],
0xFFFF - dst_rgb[1],
0xFFFF - dst_rgb[2],
]
}),
7 => (!is_black).then(|| Self::colorize_not_src_or_rgb(src_rgb, bg_rgb, dst_rgb)),
_ => Some(src_rgb),
}
}
fn read_rgbdirect_pixel(
read_byte: impl Fn(u32) -> u8,
address: u32,
pixel_size: u32,
) -> Option<[u16; 3]> {
match pixel_size {
16 => {
let packed = u16::from_be_bytes([read_byte(address), read_byte(address + 1)]);
let expand5 = |component: u16| {
(component << 11) | (component << 6) | (component << 1) | (component >> 4)
};
Some([
expand5((packed >> 10) & 0x1F),
expand5((packed >> 5) & 0x1F),
expand5(packed & 0x1F),
])
}
32 => {
let red = u16::from(read_byte(address + 1));
let green = u16::from(read_byte(address + 2));
let blue = u16::from(read_byte(address + 3));
Some([(red << 8) | red, (green << 8) | green, (blue << 8) | blue])
}
_ => None,
}
}
fn inverted_palette_index(dst_clut: &[[u16; 3]; 256], pixel: u8) -> u8 {
let rgb = dst_clut[pixel as usize];
Self::nearest_palette_index(
dst_clut,
[0xFFFF - rgb[0], 0xFFFF - rgb[1], 0xFFFF - rgb[2]],
)
}
/// Convert classic ForeColor/BackColor constants to RGB.
/// Inside Macintosh Volume I (1985), pp. I-173 to I-174.
fn legacy_qd_color_to_rgb(color: u32) -> (u16, u16, u16) {
match color {
30 => (0xFFFF, 0xFFFF, 0xFFFF), // whiteColor
33 => (0, 0, 0), // blackColor
// Color QuickDraw uses canonical RGB values for the classic
// ForeColor/BackColor constants rather than pure primaries.
// greenColor (341) uses 0x8000 for green to match System 7.5.3
// ROM rather than Executor's diverging 0x64AF.
69 => (0xFC00, 0xF37D, 0x052F), // yellowColor
// System 7.5.3 normalizes 139 to the same cGrafPort fgColor and
// rgbFgColor as the documented magentaColor constant 137. The
// extra legacy color-plane bit must not turn into CLUT index 139.
137 | 139 => (0xF2D7, 0x0856, 0x84EC), // magentaColor
205 => (0xDD6B, 0x08C2, 0x06A2), // redColor
273 => (0x0241, 0xAB54, 0xEAFF), // cyanColor
341 => (0x0000, 0x8000, 0x11B0), // greenColor
409 => (0x0000, 0x0000, 0xD400), // blueColor
_ => {
let idx = (color as usize) & 0xFF;
let [r, g, b] = Self::standard_mac_8bpp_clut()[idx];
(r, g, b)
}
}
}
fn set_entries_request_in_range(
bus: &MacMemoryBus,
table_ptr: u32,
start: i16,
count: i16,
) -> bool {
// Systemless currently models an 8-bit indexed screen CLUT. Per
// Inside Macintosh Volume V, V-143, any out-of-range SetEntries
// request fails atomically: nothing in the device table changes.
if count < 0 || count > 255 {
return false;
}
if start >= 0 {
let end = start as i32 + count as i32;
return end <= 255;
}
if start != -1 {
return false;
}
for i in 0..=(count as u32) {
let value = bus.read_word(table_ptr + i * 8) as i16;
if !(0..=255).contains(&value) {
return false;
}
}
true
}
/// Apply CLUT updates from a ColorSpec array (hardware only).
/// Used by low-level video CLUT APIs (e.g. _Control cscSetEntries),
/// which bypass the Color Manager and write directly to the video
/// hardware CLUT without touching the GDevice's in-memory ColorTable.
/// Each ColorSpec is 8 bytes: value(2) + red(2) + green(2) + blue(2).
/// Inside Macintosh Volume V, V-143
/// Designing Cards and Drivers 2nd Ed 1990, p. 216
fn apply_color_table_updates(
&mut self,
bus: &mut MacMemoryBus,
ctab_handle: u32,
table_ptr: u32,
start: i16,
count: i16,
client_id: Option<u16>,
) -> Option<u32> {
if !Self::set_entries_request_in_range(bus, table_ptr, start, count) {
return None;
}
if ctab_handle == 0 {
return None;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return None;
}
let num_entries = (count + 1) as u32;
for i in 0..num_entries {
let entry_addr = table_ptr + i * 8;
let value = bus.read_word(entry_addr) as i16;
let r = bus.read_word(entry_addr + 2);
let g = bus.read_word(entry_addr + 4);
let b = bus.read_word(entry_addr + 6);
let idx = if start < 0 {
value as usize
} else {
(start as usize) + i as usize
};
if idx < 256 {
let ct_entry = ctab_ptr + 8 + (idx as u32) * 8;
// High-level Color Manager SetEntries stores the current
// GDevice client ID in every changed ColorSpec.value; the
// caller's value is only a destination index in index mode.
// Inside Macintosh Volume V, V-143.
let value = client_id
.map(|id| (bus.read_word(ct_entry) & 0xFF00) | (id & 0x00FF))
.unwrap_or(idx as u16);
bus.write_word(ct_entry, value);
bus.write_word(ct_entry + 2, r);
bus.write_word(ct_entry + 4, g);
bus.write_word(ct_entry + 6, b);
}
}
self.reseed_color_table_handle(bus, ctab_handle)
}
pub(crate) fn apply_set_entries(
&mut self,
bus: &mut MacMemoryBus,
table_ptr: u32,
start: i16,
count: i16,
) {
if !Self::set_entries_request_in_range(bus, table_ptr, start, count) {
return;
}
self.apply_set_entries_to_device_clut_unchecked(bus, table_ptr, start, count);
// Note: color_manager_clut is NOT updated here. Low-level video
// driver SetEntries only changes the hardware CLUT for palette
// animation. QuickDraw's index mapping (ITable) stays stable.
}
fn apply_set_entries_to_device_clut_unchecked(
&mut self,
bus: &mut MacMemoryBus,
table_ptr: u32,
start: i16,
count: i16,
) {
let num_entries = (count + 1) as u32;
// Low-level SetEntries always targets the screen's hardware CLUT,
// regardless of the current GrafPort.
// On real Mac OS, the video driver SetEntries operates on the
// screen device even when an offscreen GWorld is current.
// Inside Macintosh Volume V, V-143
let target_gdh = if self.main_gdevice_handle != 0 {
self.main_gdevice_handle
} else {
self.palette_target_gdevice_handle(bus)
};
let target_is_screen = target_gdh == 0 || target_gdh == self.main_gdevice_handle;
let trace_palette = trace_palette_enabled();
let mut first_spec = None;
let mut last_spec = None;
for i in 0..num_entries {
let entry_addr = table_ptr + i * 8;
let value = bus.read_word(entry_addr) as i16;
let r = bus.read_word(entry_addr + 2);
let g = bus.read_word(entry_addr + 4);
let b = bus.read_word(entry_addr + 6);
if trace_palette {
let spec = (value, r, g, b);
if first_spec.is_none() {
first_spec = Some(spec);
}
last_spec = Some(spec);
}
let idx = if start < 0 {
value as usize
} else {
(start as usize) + i as usize
};
if idx < 256 && target_is_screen {
// Per Inside Macintosh Volume V, V-141: "If any of the
// requested entries are protected ... a protection error
// is returned, and nothing happens." Reserved entries
// can only be changed by the owning client (gdID match);
// for Systemless's single-client model, treat them as
// protected to preserve palette-animation slots.
if !self.clut_protected[idx] && !self.clut_reserved[idx] {
self.device_clut.set_entry(idx, [r, g, b]);
}
}
}
if trace_palette && target_is_screen {
let [r0, g0, b0] = self.device_clut[0];
let [r1, g1, b1] = self.device_clut[1];
let [r16, g16, b16] = self.device_clut[16];
let [r42, g42, b42] = self.device_clut[42];
let [r128, g128, b128] = self.device_clut[128];
let [r255, g255, b255] = self.device_clut[255];
if let (Some((first_value, fr, fg, fb)), Some((last_value, lr, lg, lb))) =
(first_spec, last_spec)
{
eprintln!(
"[PALETTE] SetEntries tick={} start={} count={} table=${:08X} first=value:{} rgb=({:04X},{:04X},{:04X}) last=value:{} rgb=({:04X},{:04X},{:04X}) device[0]=({:04X},{:04X},{:04X}) device[1]=({:04X},{:04X},{:04X}) device[16]=({:04X},{:04X},{:04X}) device[42]=({:04X},{:04X},{:04X}) device[128]=({:04X},{:04X},{:04X}) device[255]=({:04X},{:04X},{:04X}) cm[0]=({:04X},{:04X},{:04X}) cm[1]=({:04X},{:04X},{:04X}) cm[16]=({:04X},{:04X},{:04X}) cm[42]=({:04X},{:04X},{:04X}) cm[128]=({:04X},{:04X},{:04X}) cm[255]=({:04X},{:04X},{:04X})",
self.current_tick(),
start,
count,
table_ptr,
first_value,
fr,
fg,
fb,
last_value,
lr,
lg,
lb,
r0,
g0,
b0,
r1,
g1,
b1,
r16,
g16,
b16,
r42,
g42,
b42,
r128,
g128,
b128,
r255,
g255,
b255,
self.color_manager_clut[0][0],
self.color_manager_clut[0][1],
self.color_manager_clut[0][2],
self.color_manager_clut[1][0],
self.color_manager_clut[1][1],
self.color_manager_clut[1][2],
self.color_manager_clut[16][0],
self.color_manager_clut[16][1],
self.color_manager_clut[16][2],
self.color_manager_clut[42][0],
self.color_manager_clut[42][1],
self.color_manager_clut[42][2],
self.color_manager_clut[128][0],
self.color_manager_clut[128][1],
self.color_manager_clut[128][2],
self.color_manager_clut[255][0],
self.color_manager_clut[255][1],
self.color_manager_clut[255][2]
);
}
}
}
/// Apply CLUT updates via the Color Manager (high-level).
/// Used by SetEntries ($AA3F), which updates both the hardware
/// CLUT (device_clut) AND the GDevice's in-memory ColorTable.
/// This ensures that QuickDraw operations (DrawPicture, CopyBits)
/// that remap colors against the GDevice palette see the correct
/// palette, while the screen also displays using that same palette.
/// Inside Macintosh Volume V, V-143
pub(crate) fn apply_set_entries_with_gdevice(
&mut self,
bus: &mut MacMemoryBus,
table_ptr: u32,
start: i16,
count: i16,
) {
self.apply_set_entries_with_gdevice_mode(
bus,
table_ptr,
start,
count,
palette_strict_enabled(),
);
}
fn apply_set_entries_with_gdevice_mode(
&mut self,
bus: &mut MacMemoryBus,
table_ptr: u32,
start: i16,
count: i16,
strict_palette: bool,
) {
if !Self::set_entries_request_in_range(bus, table_ptr, start, count) {
return;
}
let target_is_screen = self.set_entries_target_is_screen(bus);
if target_is_screen {
self.display_gamma
.set_implicit(crate::display::default_display_gamma());
}
let incoming_default_palette = start == 0
&& (count == 255 || count == 254)
&& Self::table_looks_like_scaled_canonical_system_8bpp(bus, table_ptr);
// Extend the seeded_picture_palette window whenever a scaled-
// canonical SetEntries fires against a non-canonical cm[]. An
// active fade keeps device_clut tracking cm[] regardless of fade
// duration; once the game stops fading (no scaled-canonical
// SetEntries for 48+ ticks) the window expires naturally and the
// next scene's SetEntries / SeedFromPicture can publish a fresh
// cm[] without being blocked by the prior scene's palette.
// Inside Macintosh Volume V, V-143.
let preserve_seeded_picture_palette = target_is_screen
&& incoming_default_palette
&& self.current_tick() < self.seeded_picture_palette_until_tick
&& !Self::uses_canonical_system_8bpp_clut(&self.seeded_picture_palette);
if preserve_seeded_picture_palette && !strict_palette && !palette_as_game_wrote_enabled() {
self.screen_palette_fade_active = true;
if let Some(scale) = Self::canonical_table_brightness_scale(bus, table_ptr) {
self.device_clut.replace(Self::scale_clut(&self.seeded_picture_palette, scale));
}
// Extend the window so consecutive fade-up/-down SetEntries
// (which may run 60+ ticks for a single scene transition)
// all get the scene-palette preservation. Window resets to
// tick + 64 on each fire; once fades stop, the window
// expires within 64 ticks and the gate re-opens for the
// next scene.
//
// 64 chosen empirically: +48 (the previous fixed
// window) expires during EV's landing fade-up and lets
// the final SetEntries publish canonical over cm[].
// +48 left frame 13 at 69.26%; +64 also leaves it at
// 69.26% but lifts 11/12 by 3 points each and 14/15 by
// 2 points each (more consistent within-scene
// preservation). +96 and +128 both regressed 11/12/13
// by ~4 points (old scene palette leaks into new scene's
// canonical fade-ups). +64 is the safe maximum that
// avoids cross-scene leakage.
self.seeded_picture_palette_until_tick = self.current_tick().saturating_add(64);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] PreserveSeededPicture tick={} table=${:08X} until_tick={} device[0]=({:04X},{:04X},{:04X}) device[1]=({:04X},{:04X},{:04X}) device[42]=({:04X},{:04X},{:04X}) device[128]=({:04X},{:04X},{:04X}) device[255]=({:04X},{:04X},{:04X})",
self.current_tick(),
table_ptr,
self.seeded_picture_palette_until_tick,
self.device_clut[0][0],
self.device_clut[0][1],
self.device_clut[0][2],
self.device_clut[1][0],
self.device_clut[1][1],
self.device_clut[1][2],
self.device_clut[42][0],
self.device_clut[42][1],
self.device_clut[42][2],
self.device_clut[128][0],
self.device_clut[128][1],
self.device_clut[128][2],
self.device_clut[255][0],
self.device_clut[255][1],
self.device_clut[255][2]
);
}
if std::env::var_os("SYSTEMLESS_TRACE_CM_WRITE").is_some() {
let cm_before = self.color_manager_clut[0];
let seed = self.seeded_picture_palette[0];
eprintln!(
"[CM-WRITE] PreserveSeeded@13177 tick={} cm[0]=({:04X},{:04X},{:04X}) <- seeded[0]=({:04X},{:04X},{:04X})",
self.current_tick(), cm_before[0], cm_before[1], cm_before[2], seed[0], seed[1], seed[2]
);
}
self.color_manager_clut.replace(self.seeded_picture_palette);
return;
}
let is_full_replace = start == 0 && (count == 255 || count == 254);
let previous_frame_was_dimmed =
Self::clut_is_dimmed_derivative_of(&self.device_clut, &self.color_manager_clut);
// Normal path: install the supplied RGB values into device_clut
// unconditionally. Per Inside Macintosh Volume V, V-143 the caller's
// table values MUST land in the hardware CLUT — Systemless must not
// second-guess the caller with a "looks like a fade" bypass that
// substitutes a scaled `color_manager_clut`.
//
if target_is_screen {
self.apply_set_entries_to_device_clut_unchecked(bus, table_ptr, start, count);
}
// Publish `device_clut → color_manager_clut` only on a full-replace
// SetEntries (start=0, count=255) that represents a fresh palette
// install. Static dark scene palettes still need to publish so
// DrawPicture / CopyBits color matching uses the new palette, but
// true brightness fades of the already-published palette must not.
//
// Partial updates (palette animation cycling a few slots) MUST NOT
// publish — publishing them would lock the inverse-table baseline
// to transient animation values and corrupt sprite color matching.
//
// Mid-fade frames (full-replace that are just a uniform scale of the
// current logical palette) MUST NOT publish — publishing them would
// lock cm to a dimmed transient and produce washed-out color
// matching.
//
// Fade code commonly derives each frame from the logical palette, but
// low-intensity integer rounding can stop looking like one uniform
// scale near black. Once a genuine scaled frame has started a fade,
// keep later component-wise-dimmer frames transient as well. The
// stable Color Manager table remains the inverse-table baseline used
// to draw the next scene while the hardware CLUT is dark.
let transient_fade_table = !strict_palette
&& is_full_replace
&& (Self::table_uniform_scale_of_clut(bus, table_ptr, &self.color_manager_clut)
.is_some_and(|scale| scale < 0.999)
|| (previous_frame_was_dimmed
&& Self::table_is_dimmed_derivative_of_clut(
bus,
table_ptr,
&self.color_manager_clut,
)));
if target_is_screen && is_full_replace {
// Only a full-table update of the screen GDevice can put the
// screen hardware into this transient-fade state. Offscreen
// palette installs must never affect screen CopyBits decisions.
self.screen_palette_fade_active = transient_fade_table;
}
// In sequence mode, ColorSpec.value is ignored; it is commonly filled
// with a repeated Color Manager client ID. The RGB fields still replace
// the corresponding hardware entries. Inside Macintosh Volume V
// (1986), pp. V-142..V-143.
if target_is_screen && is_full_replace && !transient_fade_table {
if std::env::var_os("SYSTEMLESS_TRACE_CM_WRITE").is_some() {
let cm_before = self.color_manager_clut[0];
let dev0 = self.device_clut[0];
eprintln!(
"[CM-WRITE] PublishCm@13220 tick={} cm[0]=({:04X},{:04X},{:04X}) <- device[0]=({:04X},{:04X},{:04X})",
self.current_tick(), cm_before[0], cm_before[1], cm_before[2], dev0[0], dev0[1], dev0[2]
);
}
self.color_manager_clut.replace(*self.device_clut);
if trace_palette_enabled() {
eprintln!(
"[PALETTE] PublishCm tick={} — fresh full palette install cm[0]=({:04X},{:04X},{:04X}) cm[255]=({:04X},{:04X},{:04X})",
self.current_tick(),
self.color_manager_clut[0][0],
self.color_manager_clut[0][1],
self.color_manager_clut[0][2],
self.color_manager_clut[255][0],
self.color_manager_clut[255][1],
self.color_manager_clut[255][2]
);
}
}
// Also update the GDevice's in-memory ColorTable so QuickDraw
// color remapping (e.g. DrawPicture) uses the same palette.
let gdh = self.set_entries_target_gdevice_handle(bus);
if gdh == 0 {
return;
}
let ctab_handle = Self::gdevice_ctab_handle(bus, gdh);
let gd = bus.read_long(gdh);
let client_id = (gd != 0).then(|| bus.read_word(gd + 2));
let _ =
self.apply_color_table_updates(bus, ctab_handle, table_ptr, start, count, client_id);
}
fn set_entries_target_gdevice_handle(&self, bus: &MacMemoryBus) -> u32 {
self.palette_target_gdevice_handle(bus)
}
fn set_entries_target_is_screen(&self, bus: &MacMemoryBus) -> bool {
let target_gdh = self.set_entries_target_gdevice_handle(bus);
target_gdh == 0 || target_gdh == self.main_gdevice_handle
}
fn palette_target_gdevice_handle(&self, bus: &MacMemoryBus) -> u32 {
if *self.current_gdevice != 0 {
*self.current_gdevice
} else if self.main_gdevice_handle != 0 {
self.main_gdevice_handle
} else {
bus.read_long(0x0CC8) // TheGDevice
}
}
fn table_looks_like_scaled_canonical_system_8bpp(bus: &MacMemoryBus, table_ptr: u32) -> bool {
let samples = [
(0usize, [0xFFFF, 0xFFFF, 0xFFFF]),
(1usize, [0xFFFF, 0xFFFF, 0xCCCC]),
(16usize, [0xFFFF, 0x9999, 0x3333]),
(42usize, [0xCCCC, 0xCCCC, 0xFFFF]),
(128usize, [0x6666, 0x6666, 0x9999]),
(255usize, [0, 0, 0]),
];
let entry0 = table_ptr;
let sample0 = [
bus.read_word(entry0 + 2),
bus.read_word(entry0 + 4),
bus.read_word(entry0 + 6),
];
if sample0[0] != sample0[1] || sample0[1] != sample0[2] {
return false;
}
let scale = sample0[0] as f64 / 65535.0;
if !(0.0..=1.0).contains(&scale) {
return false;
}
samples.into_iter().all(|(index, expected)| {
let entry = table_ptr + (index as u32) * 8;
let actual = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
actual
.into_iter()
.zip(expected)
.all(|(a, e)| (f64::from(a) - f64::from(e) * scale).abs() <= 0x0400 as f64)
})
}
fn table_uniform_scale_of_clut(
bus: &MacMemoryBus,
table_ptr: u32,
clut: &[[u16; 3]; 256],
) -> Option<f64> {
let sample_indices = [0usize, 1, 16, 42, 128, 255];
let mut scale: Option<f64> = None;
for index in sample_indices {
let entry = table_ptr + (index as u32) * 8;
let actual = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
let expected = clut[index];
for channel in 0..3 {
let base = expected[channel];
let got = actual[channel];
if base == 0 {
if got > 0x0200 {
return None;
}
continue;
}
let candidate = f64::from(got) / f64::from(base);
if !(0.0..=1.05).contains(&candidate) {
return None;
}
if let Some(existing) = scale {
let want = (f64::from(base) * existing).round() as i32;
if (i32::from(got) - want).abs() > 0x0300 {
return None;
}
} else {
scale = Some(candidate);
}
}
}
scale
}
fn clut_is_dimmed_derivative_of(
candidate: &[[u16; 3]; 256],
baseline: &[[u16; 3]; 256],
) -> bool {
let mut visibly_dimmed = false;
for (candidate_rgb, baseline_rgb) in candidate.iter().zip(baseline) {
for channel in 0..3 {
let got = candidate_rgb[channel];
let base = baseline_rgb[channel];
if got > base.saturating_add(0x0200) {
return false;
}
if base >= 0x1000 && got.saturating_add(0x0200) < base {
visibly_dimmed = true;
}
}
}
visibly_dimmed
}
fn table_is_dimmed_derivative_of_clut(
bus: &MacMemoryBus,
table_ptr: u32,
baseline: &[[u16; 3]; 256],
) -> bool {
let mut candidate = [[0u16; 3]; 256];
for (index, rgb) in candidate.iter_mut().enumerate() {
let entry = table_ptr + (index as u32) * 8;
*rgb = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
}
Self::clut_is_dimmed_derivative_of(&candidate, baseline)
}
fn palette_exact_match_index(
bus: &MacMemoryBus,
ctab_handle: u32,
rgb: [u16; 3],
entry_count: usize,
) -> Option<u8> {
if ctab_handle == 0 {
return None;
}
let ctab_ptr = bus.read_long(ctab_handle);
if ctab_ptr == 0 {
return None;
}
let entry_count = entry_count.clamp(1, 256) as u32;
let ct_size = bus.read_word(ctab_ptr + 6) as u32;
let device_table = bus.read_word(ctab_ptr + 4) & 0x8000 != 0;
for i in 0..=ct_size.min(entry_count - 1) {
let entry = ctab_ptr + 8 + i * 8;
// Device ColorTables are positional: the entry ordinal is the
// pixel value, while image tables use ColorSpec.value. Inside
// Macintosh Volume V (1986), pp. V-57--V-58.
let value = if device_table {
i as u16
} else {
bus.read_word(entry)
};
let entry_rgb = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
if entry_rgb == rgb && u32::from(value) < entry_count {
return Some(value as u8);
}
}
None
}
fn palette_index_for_rgb(
&self,
bus: &MacMemoryBus,
ctab_handle: u32,
clut: &[[u16; 3]; 256],
rgb: [u16; 3],
) -> u8 {
self.palette_index_for_rgb_with_entry_count(bus, ctab_handle, clut, rgb, 256)
}
fn palette_index_for_rgb_with_entry_count(
&self,
bus: &MacMemoryBus,
ctab_handle: u32,
clut: &[[u16; 3]; 256],
rgb: [u16; 3],
entry_count: usize,
) -> u8 {
let screen_ctab_handle = if self.main_gdevice_handle != 0 {
Self::gdevice_ctab_handle(bus, self.main_gdevice_handle)
} else {
0
};
if ctab_handle != 0 && ctab_handle != screen_ctab_handle {
Self::palette_exact_match_index(bus, ctab_handle, rgb, entry_count).unwrap_or_else(
|| Self::nearest_palette_index_with_entry_count(clut, rgb, entry_count),
)
} else {
Self::nearest_palette_index_with_entry_count(clut, rgb, entry_count)
}
}
fn copy_bits_transparent_source_indices(
&self,
bus: &MacMemoryBus,
ctab_handle: u32,
src_clut: Option<&[[u16; 3]; 256]>,
bg_rgb: [u16; 3],
) -> Option<[bool; 256]> {
let clut = src_clut?;
let mut indices = [false; 256];
// IM: Imaging With QuickDraw 1994, p. 4-39: transparent mode
// preserves the destination when the source pixel equals the current
// background color.
let bg_index = self.palette_index_for_rgb(bus, ctab_handle, clut, bg_rgb);
indices[usize::from(bg_index)] = true;
// BasiliskII/System 7.5.3 evidence from Blade's indexed GWorld
// sprites shows source index 0 also acting as the matte hole even
// when its CLUT entry is black and the current background is white.
// Keep the documented background-color rule above and add the indexed
// PixMap matte convention here for 8bpp transparent CopyBits.
indices[0] = true;
Some(indices)
}
/// Resolve the physical pixel target for SetCPixel/GetCPixel at (h,v).
/// Returns the byte offset of the pixel together with the underlying
/// pixmap layout. Returns None when the coordinate is outside the
/// pixmap bounds (so writes are clipped safely) or when the port has
/// no backing bitmap/pixmap.
///
/// Inside Macintosh Volume V, V-37 (PixMap layout)
/// Inside Macintosh Volume I, I-148 (GrafPort / BitMap layout)
fn resolve_pixel_target(
&self,
bus: &MacMemoryBus,
port: u32,
h: i16,
v: i16,
) -> Option<PixelTarget> {
let port_version = bus.read_word(port + 6);
let is_color = (port_version & 0xC000) != 0;
let (base, row_bytes, pixel_size, top, left, bottom, right, ctab_handle) = if is_color {
let pm_handle = bus.read_long(port + 2);
if pm_handle == 0 {
return None;
}
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr == 0 {
return None;
}
(
Self::offscreen_pixmap_base_ptr(bus, pm_ptr),
(bus.read_word(pm_ptr + 4) & 0x3FFF) as u32,
bus.read_word(pm_ptr + 32),
bus.read_word(pm_ptr + 6) as i16,
bus.read_word(pm_ptr + 8) as i16,
bus.read_word(pm_ptr + 10) as i16,
bus.read_word(pm_ptr + 12) as i16,
bus.read_long(pm_ptr + 42),
)
} else {
(
bus.read_long(port + 2),
(bus.read_word(port + 6) & 0x3FFF) as u32,
1u16,
bus.read_word(port + 8) as i16,
bus.read_word(port + 10) as i16,
bus.read_word(port + 12) as i16,
bus.read_word(port + 14) as i16,
0u32,
)
};
if base == 0 {
return None;
}
if h < left || h >= right || v < top || v >= bottom {
return None;
}
for offset in [24u32, 28u32] {
let rgn_handle = bus.read_long(port.wrapping_add(offset));
if rgn_handle == 0 {
continue;
}
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr == 0 {
continue;
}
let rt = bus.read_word(rgn_ptr + 2) as i16;
let rl = bus.read_word(rgn_ptr + 4) as i16;
let rb = bus.read_word(rgn_ptr + 6) as i16;
let rr = bus.read_word(rgn_ptr + 8) as i16;
if v < rt || v >= rb || h < rl || h >= rr {
return None;
}
}
let dy = (v - top) as u32;
let dx = (h - left) as u32;
Some(PixelTarget {
base,
row_bytes,
pixel_size,
dx,
dy,
ctab_handle,
})
}
/// Read the 8-byte monochrome fallback pattern (pat1Data at +20)
/// from a PixPatHandle. Returns None when the handle or its master
/// pointer is NIL so callers can skip the draw safely.
///
/// The PixPat record layout is documented at NewPixPat ($AA07) and
/// in Inside Macintosh Volume V, V-51; pat1Data lives at the record
/// offset 20 as a raw Pattern (8 bytes) used by QuickDraw whenever
/// the destination is 1bpp or the PixMap field is NIL.
/// Imaging With QuickDraw 1994, p. 4-81
fn read_pixpat_pat1data(bus: &MacMemoryBus, pp_handle: u32) -> Option<[u8; 8]> {
if pp_handle == 0 {
return None;
}
let pp_ptr = bus.read_long(pp_handle);
if pp_ptr == 0 {
return None;
}
let mut pat = [0u8; 8];
for (i, slot) in pat.iter_mut().enumerate() {
*slot = bus.read_byte(pp_ptr + 20 + i as u32);
}
Some(pat)
}
fn allocate_new_pixmap(&mut self, bus: &mut MacMemoryBus) -> u32 {
let gd_handle = self.ensure_main_gdevice(bus);
let gd_ptr = bus.read_long(gd_handle);
let gd_pmap_handle = bus.read_long(gd_ptr + 22);
let gd_pmap = bus.read_long(gd_pmap_handle);
// NewPixMap allocates the PixMap handle before its color table.
// Imaging With QuickDraw (1994), pp. 4-85--4-86.
let pm_ptr = bus.alloc(50);
let handle = bus.alloc(4);
if pm_ptr == 0 || handle == 0 {
if pm_ptr != 0 {
bus.free(pm_ptr);
}
if handle != 0 {
bus.free(handle);
}
return 0;
}
bus.write_long(handle, pm_ptr);
for offset in 0..50u32 {
bus.write_byte(pm_ptr + offset, bus.read_byte(gd_pmap + offset));
}
let depth = bus.read_word(pm_ptr + 32) as u32;
let source_ctab_handle = bus.read_long(pm_ptr + 42);
let ctab_handle = if let Some(clut) =
self.active_seeded_screen_clut_for_offscreen_clone(gd_handle, 0)
{
self.allocate_color_table_handle_with_clut(bus, depth, &clut, 0x8000)
} else {
self.allocate_color_table_handle(bus, depth, source_ctab_handle, 0x8000)
};
if ctab_handle == 0 {
bus.free(pm_ptr);
bus.free(handle);
return 0;
}
bus.write_long(pm_ptr + 42, ctab_handle);
handle
}
fn allocate_empty_handle(bus: &mut MacMemoryBus) -> u32 {
let ptr = bus.alloc(0);
let handle = bus.alloc(4);
if ptr == 0 || handle == 0 {
if ptr != 0 {
bus.free(ptr);
}
if handle != 0 {
bus.free(handle);
}
return 0;
}
bus.write_long(handle, ptr);
handle
}
fn clone_memory_handle(bus: &mut MacMemoryBus, source_handle: u32) -> Option<u32> {
if bus.get_alloc_size(source_handle) != Some(4) {
return None;
}
let source = bus.read_long(source_handle);
let size = bus.get_alloc_size(source)?;
let destination = bus.alloc(size);
for offset in 0..size {
bus.write_byte(destination + offset, bus.read_byte(source + offset));
}
let destination_handle = bus.alloc(4);
bus.write_long(destination_handle, destination);
Some(destination_handle)
}
fn clone_pixmap_handle(
bus: &mut MacMemoryBus,
source_handle: u32,
source_data: u32,
cloned_data: u32,
) -> Option<u32> {
let destination_handle = Self::clone_memory_handle(bus, source_handle)?;
let source = bus.read_long(source_handle);
let destination = bus.read_long(destination_handle);
if source_data != 0 && bus.read_long(source) == source_data && cloned_data != 0 {
bus.write_long(destination, cloned_data);
}
let source_ctab_handle = bus.read_long(source + 42);
if let Some(destination_ctab_handle) = Self::clone_memory_handle(bus, source_ctab_handle) {
bus.write_long(destination + 42, destination_ctab_handle);
}
Some(destination_handle)
}
fn free_memory_handle(bus: &mut MacMemoryBus, handle: u32) {
if bus.get_alloc_size(handle) != Some(4) {
return;
}
let ptr = bus.read_long(handle);
if bus.get_alloc_size(ptr).is_some() {
bus.free(ptr);
}
bus.free(handle);
}
fn free_pixmap_handle(bus: &mut MacMemoryBus, handle: u32) {
if bus.get_alloc_size(handle) != Some(4) {
return;
}
let ptr = bus.read_long(handle);
if bus.get_alloc_size(ptr).is_some() {
Self::free_memory_handle(bus, bus.read_long(ptr + 42));
bus.free(ptr);
}
bus.free(handle);
}
fn ensure_makergbpat_backing(
&self,
bus: &mut MacMemoryBus,
pp_handle: u32,
rgb: (u16, u16, u16),
) {
let pp_ptr = bus.read_long(pp_handle);
if pp_ptr == 0 {
return;
}
let pat_data_handle = if bus.read_long(pp_ptr + 6) != 0 {
bus.read_long(pp_ptr + 6)
} else {
let handle = bus.alloc(4);
bus.write_long(pp_ptr + 6, handle);
handle
};
let pat_data = if pat_data_handle != 0 && bus.read_long(pat_data_handle) != 0 {
bus.read_long(pat_data_handle)
} else {
let data = bus.alloc(16);
if pat_data_handle != 0 {
bus.write_long(pat_data_handle, data);
}
data
};
if pat_data != 0 {
for row in 0..8u32 {
bus.write_byte(pat_data + row * 2, 0xFF);
bus.write_byte(pat_data + row * 2 + 1, 0);
}
}
let pat_map_handle = if bus.read_long(pp_ptr + 2) != 0 {
bus.read_long(pp_ptr + 2)
} else {
let handle = bus.alloc(4);
bus.write_long(pp_ptr + 2, handle);
handle
};
let pat_map = if pat_map_handle != 0 && bus.read_long(pat_map_handle) != 0 {
bus.read_long(pat_map_handle)
} else {
let map = bus.alloc(50);
if pat_map_handle != 0 {
bus.write_long(pat_map_handle, map);
}
map
};
if pat_map == 0 {
return;
}
let ctab_handle = if bus.read_long(pat_map + 42) != 0 {
bus.read_long(pat_map + 42)
} else {
let handle = bus.alloc(4);
bus.write_long(pat_map + 42, handle);
handle
};
let ctab = if ctab_handle != 0 && bus.read_long(ctab_handle) != 0 {
bus.read_long(ctab_handle)
} else {
let table = bus.alloc(24);
if ctab_handle != 0 {
bus.write_long(ctab_handle, table);
}
table
};
bus.fill_zeros(pat_map, 50);
bus.write_long(pat_map, pat_data);
bus.write_word(pat_map + 4, 0x8002);
bus.write_word(pat_map + 6, 0);
bus.write_word(pat_map + 8, 0);
bus.write_word(pat_map + 10, 8);
bus.write_word(pat_map + 12, 8);
bus.write_long(pat_map + 16, 72 << 16);
bus.write_long(pat_map + 20, 72 << 16);
bus.write_word(pat_map + 32, 1);
bus.write_word(pat_map + 34, 1);
bus.write_word(pat_map + 36, 1);
bus.write_long(pat_map + 42, ctab_handle);
if ctab != 0 {
bus.fill_zeros(ctab, 24);
bus.write_word(ctab + 4, 0x8000);
bus.write_word(ctab + 6, 1);
bus.write_word(ctab + 8, 0);
bus.write_word(ctab + 10, 0xFFFF);
bus.write_word(ctab + 12, 0xFFFF);
bus.write_word(ctab + 14, 0xFFFF);
bus.write_word(ctab + 16, 1);
bus.write_word(ctab + 18, rgb.0);
bus.write_word(ctab + 20, rgb.1);
bus.write_word(ctab + 22, rgb.2);
}
bus.write_word(pp_ptr + 14, 0);
}
fn pixpat_fill_pattern(
&self,
bus: &MacMemoryBus,
pp_handle: u32,
) -> Option<([u8; 8], Option<(u16, u16, u16)>)> {
if let Some(rgb) = self.makergbpat_colors.get(&pp_handle).copied() {
Some(([0xFF; 8], Some(rgb)))
} else {
Self::read_pixpat_pat1data(bus, pp_handle).map(|pat| (pat, None))
}
}
fn read_raw_pixpat_color_table(
&self,
bus: &MacMemoryBus,
table_ptr: u32,
) -> Option<[[u16; 3]; 256]> {
if table_ptr == 0 {
return None;
}
let count = usize::from(bus.read_word(table_ptr + 6)).saturating_add(1);
if count == 0 || count > 256 {
return None;
}
// Device color tables reserve ColorSpec.value for the Color Manager;
// their pixel values are implicit from each entry's ordinal position.
// Inside Macintosh Volume V (1986), "Color QuickDraw Resource Formats".
let uses_implicit_values = (bus.read_word(table_ptr + 4) & 0x8000) != 0;
let mut clut = *self.device_clut;
for ordinal in 0..count {
let entry = table_ptr + 8 + ordinal as u32 * 8;
let value = if uses_implicit_values {
ordinal
} else {
usize::from(bus.read_word(entry))
};
if value < 256 {
clut[value] = [
bus.read_word(entry + 2),
bus.read_word(entry + 4),
bus.read_word(entry + 6),
];
}
}
Some(clut)
}
fn raw_pixpat_pixel_value(
bus: &MacMemoryBus,
data_ptr: u32,
row_bytes: u32,
pixel_size: u16,
x: u32,
y: u32,
) -> Option<u8> {
let row = data_ptr + y.checked_mul(row_bytes)?;
match pixel_size {
1 => {
let byte = bus.read_byte(row + x / 8);
Some((byte >> (7 - (x & 7))) & 1)
}
2 => {
let byte = bus.read_byte(row + x / 4);
Some((byte >> (6 - 2 * (x & 3))) & 0x03)
}
4 => {
let byte = bus.read_byte(row + x / 2);
if x & 1 == 0 {
Some(byte >> 4)
} else {
Some(byte & 0x0F)
}
}
8 => Some(bus.read_byte(row + x)),
_ => None,
}
}
pub(super) fn decode_raw_pixpat(
&self,
bus: &MacMemoryBus,
pp_handle: u32,
) -> Option<RawPixPat> {
if pp_handle == 0 {
return None;
}
let pp_ptr = bus.read_long(pp_handle);
if pp_ptr == 0 {
return None;
}
// Compiled 'ppat' resources keep offsets from the PixPat record;
// NewPixPat/MakeRGBPat records keep live handles and deliberately
// remain on their existing paths.
let pat_map_offset = bus.read_long(pp_ptr + 2);
let pat_data_offset = bus.read_long(pp_ptr + 6);
if !(28..=0x10000).contains(&pat_map_offset)
|| !(pat_map_offset + 50..=0x200000).contains(&pat_data_offset)
{
return None;
}
let pat_map_ptr = pp_ptr + pat_map_offset;
let read_map = |base_offset: u32| {
let row_bytes = u32::from(bus.read_word(pat_map_ptr + base_offset) & 0x3FFF);
let top = bus.read_word(pat_map_ptr + base_offset + 2) as i16;
let left = bus.read_word(pat_map_ptr + base_offset + 4) as i16;
let bottom = bus.read_word(pat_map_ptr + base_offset + 6) as i16;
let right = bus.read_word(pat_map_ptr + base_offset + 8) as i16;
let pixel_size = bus.read_word(pat_map_ptr + base_offset + 28);
let table_offset = bus.read_long(pat_map_ptr + base_offset + 38);
(
row_bytes,
top,
left,
bottom,
right,
pixel_size,
table_offset,
)
};
let map_valid = |candidate: &(u32, i16, i16, i16, i16, u16, u32)| {
let (row_bytes, top, left, bottom, right, pixel_size, table_offset) = *candidate;
row_bytes != 0
&& bottom > top
&& right > left
&& matches!(pixel_size, 1 | 2 | 4 | 8)
&& table_offset != 0
&& table_offset <= 0x200000
};
let raw_map = read_map(0);
let live_map = read_map(4);
let (row_bytes, top, left, bottom, right, pixel_size, table_offset) = if map_valid(&raw_map)
{
raw_map
} else if map_valid(&live_map) {
live_map
} else {
return None;
};
let clut = self.read_raw_pixpat_color_table(bus, pp_ptr + table_offset)?;
Some(RawPixPat {
data_ptr: pp_ptr + pat_data_offset,
row_bytes,
width: i32::from(right) - i32::from(left),
height: i32::from(bottom) - i32::from(top),
pixel_size,
clut,
})
}
pub(super) fn raw_pixpat_index_at(
bus: &MacMemoryBus,
pixpat: &RawPixPat,
y: i16,
x: i16,
) -> Option<u8> {
let tile_x = i32::from(x).rem_euclid(pixpat.width) as u32;
let tile_y = i32::from(y).rem_euclid(pixpat.height) as u32;
Self::raw_pixpat_pixel_value(
bus,
pixpat.data_ptr,
pixpat.row_bytes,
pixpat.pixel_size,
tile_x,
tile_y,
)
}
fn fill_rect_with_raw_pixpat(
&mut self,
bus: &mut MacMemoryBus,
r: &Rect,
pp_handle: u32,
) -> bool {
macro_rules! reject {
($($arg:tt)*) => {{
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] FillCRect raw PixPat reject pp=${:08X}: {}",
pp_handle,
format_args!($($arg)*),
);
}
return false;
}};
}
if self.pn_vis < 0 || pp_handle == 0 {
return self.pn_vis < 0;
}
let pp_ptr = bus.read_long(pp_handle);
if pp_ptr == 0 {
reject!("nil master pointer");
}
// 'ppat' resources store offsets from the start of the PixPat
// resource instead of live Handles. NewPixPat-created records store
// actual handles here; those continue down the pat1Data fallback path.
let pat_map_offset = bus.read_long(pp_ptr + 2);
let pat_data_offset = bus.read_long(pp_ptr + 6);
if !(28..=0x10000).contains(&pat_map_offset)
|| !(pat_map_offset + 50..=0x200000).contains(&pat_data_offset)
{
reject!(
"unsupported offsets patMap=${:08X} patData=${:08X}",
pat_map_offset,
pat_data_offset
);
}
let pat_map_ptr = pp_ptr + pat_map_offset;
let pat_data_ptr = pp_ptr + pat_data_offset;
let read_map = |base_offset: u32| {
let row_bytes = u32::from(bus.read_word(pat_map_ptr + base_offset) & 0x3FFF);
let top = bus.read_word(pat_map_ptr + base_offset + 2) as i16;
let left = bus.read_word(pat_map_ptr + base_offset + 4) as i16;
let bottom = bus.read_word(pat_map_ptr + base_offset + 6) as i16;
let right = bus.read_word(pat_map_ptr + base_offset + 8) as i16;
let pixel_size = bus.read_word(pat_map_ptr + base_offset + 28);
let table_offset = bus.read_long(pat_map_ptr + base_offset + 38);
(
row_bytes,
top,
left,
bottom,
right,
pixel_size,
table_offset,
)
};
let map_valid = |candidate: &(u32, i16, i16, i16, i16, u16, u32)| {
let (row_bytes, top, left, bottom, right, pixel_size, table_offset) = *candidate;
row_bytes != 0
&& i32::from(bottom) > i32::from(top)
&& i32::from(right) > i32::from(left)
&& matches!(pixel_size, 1 | 2 | 4 | 8)
&& table_offset != 0
&& table_offset <= 0x200000
};
// Raw 'ppat' resources store the pattern map without baseAddr
// (rowBytes at +0). GetPixPat-expanded records can hold a full
// live PixMap with baseAddr inserted (rowBytes at +4). Accept both.
let raw_map = read_map(0);
let live_map = read_map(4);
let (src_row_bytes, src_top, src_left, src_bottom, src_right, src_pixel_size, table_offset) =
if map_valid(&raw_map) {
raw_map
} else if map_valid(&live_map) {
live_map
} else {
let (row_bytes, top, left, bottom, right, pixel_size, table_offset) = raw_map;
reject!(
"invalid source map raw(rowBytes={} bounds=({},{},{},{}) pixelSize={} table=${:08X}) live(rowBytes={} bounds=({},{},{},{}) pixelSize={} table=${:08X})",
row_bytes,
top,
left,
bottom,
right,
pixel_size,
table_offset,
live_map.0,
live_map.1,
live_map.2,
live_map.3,
live_map.4,
live_map.5,
live_map.6,
);
};
let src_height = i32::from(src_bottom) - i32::from(src_top);
let src_width = i32::from(src_right) - i32::from(src_left);
if table_offset == 0 || table_offset > 0x200000 {
reject!("invalid table offset ${:08X}", table_offset);
}
let Some(src_clut) = self.read_raw_pixpat_color_table(bus, pp_ptr + table_offset) else {
reject!("invalid color table at offset ${:08X}", table_offset);
};
let port = *self.current_port;
if port == 0 {
reject!("no current port");
}
let port_version = bus.read_word(port.wrapping_add(6));
if (port_version & 0xC000) == 0 {
reject!(
"current port ${:08X} is not a CGrafPort version=${:04X}",
port,
port_version
);
}
let pix_map_handle = bus.read_long(port.wrapping_add(2));
if pix_map_handle == 0 {
reject!("current port has nil PixMap handle");
}
let pix_map_ptr = bus.read_long(pix_map_handle);
if pix_map_ptr == 0 {
reject!("current port PixMap handle has nil master pointer");
}
let dst_base = Self::offscreen_pixmap_base_ptr(bus, pix_map_ptr);
let dst_row_bytes = u32::from(bus.read_word(pix_map_ptr + 4) & 0x3FFF);
let bounds_top = bus.read_word(pix_map_ptr + 6) as i16;
let bounds_left = bus.read_word(pix_map_ptr + 8) as i16;
let bounds_bottom = bus.read_word(pix_map_ptr + 10) as i16;
let bounds_right = bus.read_word(pix_map_ptr + 12) as i16;
let dst_pixel_size = bus.read_word(pix_map_ptr + 32);
if dst_pixel_size != 8 || dst_base == 0 || dst_row_bytes == 0 {
reject!(
"unsupported destination base=${:08X} rowBytes={} pixelSize={}",
dst_base,
dst_row_bytes,
dst_pixel_size
);
}
let is_screen_port = dst_base == self.screen_mode.0
&& dst_row_bytes == self.screen_mode.1
&& dst_pixel_size == self.screen_mode.4;
let dst_height = i32::from(bounds_bottom) - i32::from(bounds_top);
let dst_width = i32::from(bounds_right) - i32::from(bounds_left);
let rect_height = i32::from(r.bottom) - i32::from(r.top);
let rect_width = i32::from(r.right) - i32::from(r.left);
let fills_destination_bounds = r.top <= bounds_top
&& r.left <= bounds_left
&& r.bottom >= bounds_bottom
&& r.right >= bounds_right;
let fills_hidden_menu_screen_bounds = self.menu_bar_hidden
&& is_screen_port
&& port == self.front_window
&& dst_height == self.screen_mode.3 as i32
&& dst_width == self.screen_mode.2 as i32
&& rect_height >= dst_height.saturating_sub(1)
&& rect_width >= dst_width.saturating_sub(2)
&& r.top <= bounds_top
&& r.left <= bounds_left
&& r.bottom <= bounds_bottom
&& r.right <= bounds_right;
let skips_region_clip = fills_destination_bounds || fills_hidden_menu_screen_bounds;
let (fill_top, fill_left, fill_bottom, fill_right) = if fills_hidden_menu_screen_bounds {
(bounds_top, bounds_left, bounds_bottom, bounds_right)
} else {
(r.top, r.left, r.bottom, r.right)
};
let mut clip_top = bounds_top;
let mut clip_left = bounds_left;
let mut clip_bottom = bounds_bottom;
let mut clip_right = bounds_right;
let mut trace_vis = None;
let mut trace_clip = None;
if !skips_region_clip {
let vis_rgn_handle = bus.read_long(port.wrapping_add(24));
if vis_rgn_handle != 0 {
let vis_rgn_ptr = bus.read_long(vis_rgn_handle);
if vis_rgn_ptr != 0 {
let vt = bus.read_word(vis_rgn_ptr + 2) as i16;
let vl = bus.read_word(vis_rgn_ptr + 4) as i16;
let vb = bus.read_word(vis_rgn_ptr + 6) as i16;
let vr = bus.read_word(vis_rgn_ptr + 8) as i16;
trace_vis = Some((vt, vl, vb, vr));
clip_top = clip_top.max(vt);
clip_left = clip_left.max(vl);
clip_bottom = clip_bottom.min(vb);
clip_right = clip_right.min(vr);
}
}
let clip_rgn_handle = bus.read_long(port.wrapping_add(28));
if clip_rgn_handle != 0 {
let clip_rgn_ptr = bus.read_long(clip_rgn_handle);
if clip_rgn_ptr != 0 {
let ct = bus.read_word(clip_rgn_ptr + 2) as i16;
let cl = bus.read_word(clip_rgn_ptr + 4) as i16;
let cb = bus.read_word(clip_rgn_ptr + 6) as i16;
let cr = bus.read_word(clip_rgn_ptr + 8) as i16;
trace_clip = Some((ct, cl, cb, cr));
clip_top = clip_top.max(ct);
clip_left = clip_left.max(cl);
clip_bottom = clip_bottom.min(cb);
clip_right = clip_right.min(cr);
}
}
}
// Expand into the destination port's logical ColorTable. The hardware
// CLUT can be transiently dimmed while the stored pixel indexes must
// retain their colors, as with DrawPicture above.
// Imaging With QuickDraw (1994), pp. 4-12..4-14 and 4-23.
let dst_clut = self.read_port_clut(bus, bus.read_long(pix_map_ptr + 42));
let mut src_to_dst = [0u8; 256];
for (value, dst) in src_to_dst.iter_mut().enumerate() {
let rgb = src_clut[value];
*dst = super::pict::closest_clut_index(rgb[0], rgb[1], rgb[2], &dst_clut);
}
let top = fill_top.max(clip_top);
let left = fill_left.max(clip_left);
let bottom = fill_bottom.min(clip_bottom);
let right = fill_right.min(clip_right);
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] FillCRect raw PixPat geometry dst_bounds=({},{},{},{}) vis={:?} clip_rgn={:?} combined=({},{},{},{}) final=({},{},{},{}) full_bounds={} base=${:08X} rowBytes={}",
bounds_top,
bounds_left,
bounds_bottom,
bounds_right,
trace_vis,
trace_clip,
clip_top,
clip_left,
clip_bottom,
clip_right,
top,
left,
bottom,
right,
fills_destination_bounds,
dst_base,
dst_row_bytes,
);
}
if bottom <= top || right <= left {
return true;
}
if is_screen_port {
self.ensure_dialog_background_saved_for_screen_port(bus, port);
}
for y in top..bottom {
let dy = (y - bounds_top) as u32;
let tile_y = i32::from(y).rem_euclid(src_height) as u32;
for x in left..right {
let dx = (x - bounds_left) as u32;
if dx >= dst_row_bytes {
continue;
}
let tile_x = i32::from(x).rem_euclid(src_width) as u32;
let Some(src_value) = Self::raw_pixpat_pixel_value(
bus,
pat_data_ptr,
src_row_bytes,
src_pixel_size,
tile_x,
tile_y,
) else {
continue;
};
bus.write_byte(
dst_base + dy * dst_row_bytes + dx,
src_to_dst[usize::from(src_value)],
);
}
}
if is_screen_port {
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
port,
(
top.saturating_sub(bounds_top),
left.saturating_sub(bounds_left),
bottom.saturating_sub(bounds_top),
right.saturating_sub(bounds_left),
),
);
}
true
}
fn fill_rgn_with_raw_pixpat(
&mut self,
bus: &mut MacMemoryBus,
rgn_handle: u32,
pp_handle: u32,
) -> bool {
macro_rules! reject {
($($arg:tt)*) => {{
if trace_qd_colors_enabled() {
eprintln!(
"[QD-COLOR] FillCRgn raw PixPat reject pp=${:08X}: {}",
pp_handle,
format_args!($($arg)*),
);
}
return false;
}};
}
if self.pn_vis < 0 || pp_handle == 0 || rgn_handle == 0 {
return self.pn_vis < 0;
}
let Some(pixpat) = self.decode_raw_pixpat(bus, pp_handle) else {
return false;
};
let rgn_ptr = bus.read_long(rgn_handle);
if rgn_ptr == 0 {
reject!("nil region pointer");
}
let rgn_size = bus.read_word(rgn_ptr) as u32;
let bbox = Rect {
top: bus.read_word(rgn_ptr + 2) as i16,
left: bus.read_word(rgn_ptr + 4) as i16,
bottom: bus.read_word(rgn_ptr + 6) as i16,
right: bus.read_word(rgn_ptr + 8) as i16,
};
if bbox.bottom <= bbox.top || bbox.right <= bbox.left {
return true;
}
let port = *self.current_port;
if port == 0 {
reject!("no current port");
}
let port_version = bus.read_word(port.wrapping_add(6));
if (port_version & 0xC000) == 0 {
reject!(
"current port ${:08X} is not a CGrafPort version=${:04X}",
port,
port_version
);
}
let pix_map_handle = bus.read_long(port.wrapping_add(2));
if pix_map_handle == 0 {
reject!("current port has nil PixMap handle");
}
let pix_map_ptr = bus.read_long(pix_map_handle);
if pix_map_ptr == 0 {
reject!("current port PixMap handle has nil master pointer");
}
let dst_base = Self::offscreen_pixmap_base_ptr(bus, pix_map_ptr);
let dst_row_bytes = u32::from(bus.read_word(pix_map_ptr + 4) & 0x3FFF);
let bounds_top = bus.read_word(pix_map_ptr + 6) as i16;
let bounds_left = bus.read_word(pix_map_ptr + 8) as i16;
let bounds_bottom = bus.read_word(pix_map_ptr + 10) as i16;
let bounds_right = bus.read_word(pix_map_ptr + 12) as i16;
let dst_pixel_size = bus.read_word(pix_map_ptr + 32);
if dst_pixel_size != 8 || dst_base == 0 || dst_row_bytes == 0 {
reject!(
"unsupported destination base=${:08X} rowBytes={} pixelSize={}",
dst_base,
dst_row_bytes,
dst_pixel_size
);
}
let is_screen_port = dst_base == self.screen_mode.0
&& dst_row_bytes == self.screen_mode.1
&& dst_pixel_size == self.screen_mode.4;
let mut clip_top = bounds_top;
let mut clip_left = bounds_left;
let mut clip_bottom = bounds_bottom;
let mut clip_right = bounds_right;
let vis_rgn_handle = bus.read_long(port.wrapping_add(24));
if vis_rgn_handle != 0 {
let vis_rgn_ptr = bus.read_long(vis_rgn_handle);
if vis_rgn_ptr != 0 {
let vt = bus.read_word(vis_rgn_ptr + 2) as i16;
let vl = bus.read_word(vis_rgn_ptr + 4) as i16;
let vb = bus.read_word(vis_rgn_ptr + 6) as i16;
let vr = bus.read_word(vis_rgn_ptr + 8) as i16;
clip_top = clip_top.max(vt);
clip_left = clip_left.max(vl);
clip_bottom = clip_bottom.min(vb);
clip_right = clip_right.min(vr);
}
}
let clip_rgn_handle = bus.read_long(port.wrapping_add(28));
if clip_rgn_handle != 0 {
let clip_rgn_ptr = bus.read_long(clip_rgn_handle);
if clip_rgn_ptr != 0 {
let ct = bus.read_word(clip_rgn_ptr + 2) as i16;
let cl = bus.read_word(clip_rgn_ptr + 4) as i16;
let cb = bus.read_word(clip_rgn_ptr + 6) as i16;
let cr = bus.read_word(clip_rgn_ptr + 8) as i16;
clip_top = clip_top.max(ct);
clip_left = clip_left.max(cl);
clip_bottom = clip_bottom.min(cb);
clip_right = clip_right.min(cr);
}
}
let dst_clut = self.read_port_clut(bus, bus.read_long(pix_map_ptr + 42));
let mut src_to_dst = [0u8; 256];
for (value, dst) in src_to_dst.iter_mut().enumerate() {
let rgb = pixpat.clut[value];
*dst = super::pict::closest_clut_index(rgb[0], rgb[1], rgb[2], &dst_clut);
}
let top = bbox.top.max(clip_top);
let left = bbox.left.max(clip_left);
let bottom = bbox.bottom.min(clip_bottom);
let right = bbox.right.min(clip_right);
if bottom <= top || right <= left {
return true;
}
if is_screen_port {
self.ensure_dialog_background_saved_for_screen_port(bus, port);
}
let cache = if rgn_size > 10 {
Self::build_region_membership_cache(bus, rgn_handle, bbox.top, bbox.bottom)
} else {
None
};
for y in top..bottom {
let dy = (y - bounds_top) as u32;
let tile_y = i32::from(y).rem_euclid(pixpat.height) as u32;
if let Some(cache) = &cache {
let row_idx = (y - cache.top) as usize;
if row_idx >= cache.rows.len() {
continue;
}
for interval in cache.rows[row_idx].chunks_exact(2) {
let seg_left = interval[0].max(left);
let seg_right = interval[1].min(right);
for x in seg_left..seg_right {
let dx = (x - bounds_left) as u32;
if dx >= dst_row_bytes {
continue;
}
let tile_x = i32::from(x).rem_euclid(pixpat.width) as u32;
let Some(src_value) = Self::raw_pixpat_pixel_value(
bus,
pixpat.data_ptr,
pixpat.row_bytes,
pixpat.pixel_size,
tile_x,
tile_y,
) else {
continue;
};
bus.write_byte(
dst_base + dy * dst_row_bytes + dx,
src_to_dst[usize::from(src_value)],
);
}
}
} else {
for x in left..right {
let dx = (x - bounds_left) as u32;
if dx >= dst_row_bytes {
continue;
}
let tile_x = i32::from(x).rem_euclid(pixpat.width) as u32;
let Some(src_value) = Self::raw_pixpat_pixel_value(
bus,
pixpat.data_ptr,
pixpat.row_bytes,
pixpat.pixel_size,
tile_x,
tile_y,
) else {
continue;
};
bus.write_byte(
dst_base + dy * dst_row_bytes + dx,
src_to_dst[usize::from(src_value)],
);
}
}
}
if is_screen_port {
self.refresh_dialog_saved_pixels_after_screen_draw(
bus,
port,
(
top.saturating_sub(bounds_top),
left.saturating_sub(bounds_left),
bottom.saturating_sub(bounds_top),
right.saturating_sub(bounds_left),
),
);
}
true
}
/// CLUT used for SetCPixel/GetCPixel pixel matching. Per Inside
/// Macintosh Volume V, V-70, both traps must consult the "current
/// device's CLUT", which maps to `device_clut` — the live hardware
/// CLUT that SetEntries/AnimateEntry mutate. The port's own ctab
/// (when present and distinct from the main device) overrides that.
fn cpixel_clut(&self, bus: &MacMemoryBus, ctab_handle: u32) -> [[u16; 3]; 256] {
if ctab_handle == 0 {
return *self.device_clut;
}
let screen_ctab_handle = if self.main_gdevice_handle != 0 {
Self::gdevice_ctab_handle(bus, self.main_gdevice_handle)
} else {
0
};
if ctab_handle == screen_ctab_handle {
return *self.device_clut;
}
self.read_ctab_handle_clut(bus, ctab_handle)
}
/// Write an RGBColor to the pixel described by `target`. Indexed
/// pixmaps go through the current device CLUT (Color Manager best
/// match); direct pixmaps pack the RGB components into a 16- or
/// 32-bit pixel value.
/// Imaging With QuickDraw 1994, p. 4-73
fn write_cpixel(&self, bus: &mut MacMemoryBus, target: &PixelTarget, rgb: [u16; 3]) {
let byte_offset = match target.pixel_size {
1 => target.dy * target.row_bytes + target.dx / 8,
8 => target.dy * target.row_bytes + target.dx,
16 => target.dy * target.row_bytes + target.dx * 2,
32 => target.dy * target.row_bytes + target.dx * 4,
_ => return,
};
let addr = target.base + byte_offset;
match target.pixel_size {
1 => {
// Mac 1bpp convention: bit 0 = white, bit 1 = black.
let bit = 7 - (target.dx % 8);
let mask = 1u8 << bit;
let luminance = (u32::from(rgb[0]) + u32::from(rgb[1]) + u32::from(rgb[2])) / 3;
let current = bus.read_byte(addr);
let new = if luminance < 0x8000 {
current | mask
} else {
current & !mask
};
bus.write_byte(addr, new);
}
8 => {
let clut = self.cpixel_clut(bus, target.ctab_handle);
let index = self.palette_index_for_rgb(bus, target.ctab_handle, &clut, rgb);
bus.write_byte(addr, index);
}
16 => {
// Direct 16bpp: 1 alpha bit + 5-5-5 RGB.
let r5 = u32::from(rgb[0] >> 11) & 0x1F;
let g5 = u32::from(rgb[1] >> 11) & 0x1F;
let b5 = u32::from(rgb[2] >> 11) & 0x1F;
let packed = ((r5 << 10) | (g5 << 5) | b5) as u16;
bus.write_word(addr, packed);
}
32 => {
// Direct 32bpp: 8 bits alpha + 8-8-8 RGB.
let r8 = u32::from(rgb[0] >> 8);
let g8 = u32::from(rgb[1] >> 8);
let b8 = u32::from(rgb[2] >> 8);
bus.write_long(addr, (r8 << 16) | (g8 << 8) | b8);
}
_ => {}
}
}
/// Read an RGBColor from the pixel described by `target`. Indexed
/// pixmaps look the stored pixel value up in the current device
/// CLUT; direct pixmaps unpack the packed pixel into 48-bit RGB.
/// Imaging With QuickDraw 1994, p. 4-80
fn read_cpixel(&self, bus: &MacMemoryBus, target: &PixelTarget) -> [u16; 3] {
let byte_offset = match target.pixel_size {
1 => target.dy * target.row_bytes + target.dx / 8,
8 => target.dy * target.row_bytes + target.dx,
16 => target.dy * target.row_bytes + target.dx * 2,
32 => target.dy * target.row_bytes + target.dx * 4,
_ => return [0, 0, 0],
};
let addr = target.base + byte_offset;
match target.pixel_size {
1 => {
let bit = 7 - (target.dx % 8);
let byte = bus.read_byte(addr);
if (byte & (1 << bit)) != 0 {
[0, 0, 0]
} else {
[0xFFFF, 0xFFFF, 0xFFFF]
}
}
8 => {
let index = bus.read_byte(addr) as usize;
let clut = self.cpixel_clut(bus, target.ctab_handle);
clut[index]
}
16 => {
let packed = bus.read_word(addr);
// Expand 5-5-5 to full 16-bit channels by bit-replication.
let r5 = (packed >> 10) & 0x1F;
let g5 = (packed >> 5) & 0x1F;
let b5 = packed & 0x1F;
let expand5 = |c: u16| (c << 11) | (c << 6) | (c << 1) | (c >> 4);
[expand5(r5), expand5(g5), expand5(b5)]
}
32 => {
let packed = bus.read_long(addr);
let r8 = ((packed >> 16) & 0xFF) as u16;
let g8 = ((packed >> 8) & 0xFF) as u16;
let b8 = (packed & 0xFF) as u16;
[(r8 << 8) | r8, (g8 << 8) | g8, (b8 << 8) | b8]
}
_ => [0, 0, 0],
}
}
/// Read portBits.bounds.topLeft from either a GrafPort or CGrafPort.
/// GrafPort: portBits (BitMap) is inline at +2, bounds at +8..+14.
/// CGrafPort: portPixMap (handle) at +2; bounds are in the PixMap record.
/// Imaging With QuickDraw 1994, p. 4-125 (CGrafPort layout)
/// Inside Macintosh Volume I, I-148 (GrafPort layout)
pub(crate) fn port_bounds_top_left(&self, bus: &MacMemoryBus, port: u32) -> (i16, i16) {
if port == 0 {
return (0, 0);
}
let port_version = bus.read_word(port + 6);
let is_color = (port_version & 0xC000) != 0;
if is_color {
let pm_handle = bus.read_long(port + 2);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
return (
bus.read_word(pm_ptr + 6) as i16,
bus.read_word(pm_ptr + 8) as i16,
);
}
}
(0, 0)
} else {
(
bus.read_word(port + 8) as i16,
bus.read_word(port + 10) as i16,
)
}
}
pub(crate) fn port_bounds_rect(&self, bus: &MacMemoryBus, port: u32) -> (i16, i16, i16, i16) {
if port == 0 {
return (0, 0, 0, 0);
}
let port_version = bus.read_word(port + 6);
let is_color = (port_version & 0xC000) != 0;
if is_color {
let pm_handle = bus.read_long(port + 2);
if pm_handle != 0 {
let pm_ptr = bus.read_long(pm_handle);
if pm_ptr != 0 {
return (
bus.read_word(pm_ptr + 6) as i16,
bus.read_word(pm_ptr + 8) as i16,
bus.read_word(pm_ptr + 10) as i16,
bus.read_word(pm_ptr + 12) as i16,
);
}
}
(0, 0, 0, 0)
} else {
(
bus.read_word(port + 8) as i16,
bus.read_word(port + 10) as i16,
bus.read_word(port + 12) as i16,
bus.read_word(port + 14) as i16,
)
}
}
pub(crate) fn effective_the_port(&self, bus: &MacMemoryBus, a5: u32) -> u32 {
if a5 != 0 {
let global_ptr = bus.read_long(a5);
if global_ptr != 0 {
let app_port = bus.read_long(global_ptr);
if app_port != 0 {
return app_port;
}
}
}
if *self.current_port != 0 {
*self.current_port
} else {
bus.read_long(crate::memory::globals::addr::THE_PORT)
}
}
fn promote_compiled_crsr_resource(
&mut self,
bus: &mut MacMemoryBus,
resource_ptr: u32,
) -> Option<u32> {
let crsr_type = bus.read_word(resource_ptr);
if crsr_type != 0x8001 && crsr_type != 0x8000 {
return None;
}
let map_offset = bus.read_long(resource_ptr + 2);
let data_offset = bus.read_long(resource_ptr + 6);
if map_offset < 96 || data_offset <= map_offset {
return None;
}
// Compiled 'crsr' resources embed a full PixMap record, with baseAddr
// at +0 and pmTable still stored as a resource-relative offset.
// Inside Macintosh Volume V, V-74
let raw_pixmap = resource_ptr + map_offset;
let raw_row_bytes = bus.read_word(raw_pixmap + 4);
let row_bytes = u32::from(raw_row_bytes & 0x3FFF);
let top = bus.read_word(raw_pixmap + 6) as i16;
let left = bus.read_word(raw_pixmap + 8) as i16;
let bottom = bus.read_word(raw_pixmap + 10) as i16;
let right = bus.read_word(raw_pixmap + 12) as i16;
let height = bottom.saturating_sub(top).max(0) as u32;
if row_bytes == 0 || height == 0 {
return None;
}
let table_offset = bus.read_long(raw_pixmap + 42);
let pixel_data_len = if table_offset > data_offset {
table_offset - data_offset
} else {
row_bytes.saturating_mul(height)
}
.max(1);
let pixel_data_ptr = bus.alloc(pixel_data_len);
for i in 0..pixel_data_len {
bus.write_byte(
pixel_data_ptr + i,
bus.read_byte(resource_ptr + data_offset + i),
);
}
let pixel_data_handle = bus.alloc(4);
bus.write_long(pixel_data_handle, pixel_data_ptr);
let ctab_handle = if table_offset != 0 && table_offset > data_offset {
let raw_ctab = resource_ptr + table_offset;
let ct_size = u32::from(bus.read_word(raw_ctab + 6)).min(255);
let ctab_len = 8 + (ct_size + 1) * 8;
let ctab_ptr = bus.alloc(ctab_len);
for i in 0..ctab_len {
bus.write_byte(ctab_ptr + i, bus.read_byte(raw_ctab + i));
}
let handle = bus.alloc(4);
bus.write_long(handle, ctab_ptr);
handle
} else {
0
};
let pixmap_ptr = bus.alloc(50);
let pixmap_handle = bus.alloc(4);
bus.write_long(pixmap_handle, pixmap_ptr);
bus.write_long(pixmap_ptr, pixel_data_ptr);
bus.write_word(pixmap_ptr + 4, raw_row_bytes);
bus.write_word(pixmap_ptr + 6, top as u16);
bus.write_word(pixmap_ptr + 8, left as u16);
bus.write_word(pixmap_ptr + 10, bottom as u16);
bus.write_word(pixmap_ptr + 12, right as u16);
for off in 14u32..50u32 {
bus.write_byte(pixmap_ptr + off, bus.read_byte(raw_pixmap + off));
}
bus.write_long(pixmap_ptr + 42, ctab_handle);
let crsr_ptr = bus.alloc(96);
let crsr_handle = bus.alloc(4);
bus.write_long(crsr_handle, crsr_ptr);
bus.write_word(crsr_ptr, crsr_type);
bus.write_long(crsr_ptr + 2, pixmap_handle);
bus.write_long(crsr_ptr + 6, pixel_data_handle);
bus.write_long(crsr_ptr + 10, 0);
bus.write_word(crsr_ptr + 14, 0);
bus.write_long(crsr_ptr + 16, 0);
for i in 20..96u32 {
bus.write_byte(crsr_ptr + i, bus.read_byte(resource_ptr + i));
}
Some(crsr_handle)
}
fn cursor_image_from_ccrsr(&self, bus: &MacMemoryBus, crsr_ptr: u32) -> Option<CursorImage> {
if crsr_ptr == 0 {
return None;
}
let mut mono_data = [0u8; 32];
for (i, byte) in mono_data.iter_mut().enumerate() {
*byte = bus.read_byte(crsr_ptr + 20 + i as u32);
}
let mut mono_mask = [0u8; 32];
for (i, byte) in mono_mask.iter_mut().enumerate() {
*byte = bus.read_byte(crsr_ptr + 52 + i as u32);
}
let hot_v = bus.read_word(crsr_ptr + 84) as i16;
let hot_h = bus.read_word(crsr_ptr + 86) as i16;
let crsr_type = bus.read_word(crsr_ptr);
if crsr_type != 0x8001 {
return Some(CursorImage::mono(mono_data, mono_mask, hot_v, hot_h));
}
let pixmap_handle = bus.read_long(crsr_ptr + 2);
let pixel_handle = bus.read_long(crsr_ptr + 6);
if pixmap_handle == 0 || pixel_handle == 0 {
return Some(CursorImage::mono(mono_data, mono_mask, hot_v, hot_h));
}
let pixmap_ptr = bus.read_long(pixmap_handle);
let pixel_data_ptr = bus.read_long(pixel_handle);
if pixmap_ptr == 0 || pixel_data_ptr == 0 {
return Some(CursorImage::mono(mono_data, mono_mask, hot_v, hot_h));
}
let row_bytes = u32::from(bus.read_word(pixmap_ptr + 4) & 0x3FFF);
let top = bus.read_word(pixmap_ptr + 6) as i16;
let left = bus.read_word(pixmap_ptr + 8) as i16;
let bottom = bus.read_word(pixmap_ptr + 10) as i16;
let right = bus.read_word(pixmap_ptr + 12) as i16;
let width = right.saturating_sub(left).max(0) as u16;
let height = bottom.saturating_sub(top).max(0) as u16;
let pixel_size = bus.read_word(pixmap_ptr + 32);
if row_bytes == 0 || width == 0 || height == 0 || width > 128 || height > 128 {
return Some(CursorImage::mono(mono_data, mono_mask, hot_v, hot_h));
}
let pixels_argb = self.decode_cursor_pixels_argb(
bus,
pixel_data_ptr,
row_bytes,
width,
height,
pixel_size,
bus.read_long(pixmap_ptr + 42),
)?;
Some(CursorImage::Color {
width,
height,
pixels_argb,
mask: mono_mask,
hot_v,
hot_h,
mono_data,
mono_mask,
})
}
fn decode_cursor_pixels_argb(
&self,
bus: &MacMemoryBus,
base: u32,
row_bytes: u32,
width: u16,
height: u16,
pixel_size: u16,
ctab_handle: u32,
) -> Option<Vec<u32>> {
let mut pixels = Vec::with_capacity(width as usize * height as usize);
let clut = self.read_ctab_handle_clut(bus, ctab_handle);
for row in 0..height as u32 {
for col in 0..width as u32 {
let argb = match pixel_size {
1 => {
let byte = bus.read_byte(base + row * row_bytes + col / 8);
let index = (byte >> (7 - (col % 8))) & 1;
display::clut_to_argb(&clut, index)
}
2 => {
let byte = bus.read_byte(base + row * row_bytes + col / 4);
let index = (byte >> (6 - (col % 4) * 2)) & 0x03;
display::clut_to_argb(&clut, index)
}
4 => {
let byte = bus.read_byte(base + row * row_bytes + col / 2);
let index = if (col & 1) == 0 {
(byte >> 4) & 0x0F
} else {
byte & 0x0F
};
display::clut_to_argb(&clut, index)
}
8 => {
let index = bus.read_byte(base + row * row_bytes + col);
display::clut_to_argb(&clut, index)
}
16 => {
let packed = bus.read_word(base + row * row_bytes + col * 2);
let r5 = (packed >> 10) & 0x1F;
let g5 = (packed >> 5) & 0x1F;
let b5 = packed & 0x1F;
let expand5 = |c: u16| ((c << 3) | (c >> 2)) as u32;
0xFF00_0000 | (expand5(r5) << 16) | (expand5(g5) << 8) | expand5(b5)
}
32 => bus.read_long(base + row * row_bytes + col * 4) | 0xFF00_0000,
_ => return None,
};
pixels.push(argb);
}
}
Some(pixels)
}
}
#[cfg(test)]
mod tests;