systemless 0.120.0

High-Level Emulation for classic Macintosh applications
Documentation
//! Typed QuickDraw Graphics Device Manager dispatch for PowerPC imports.

use super::*;

pub(super) struct PpcGraphicsDeviceDispatchContext<'a> {
    pub(super) binding: &'a PpcImportBinding,
    pub(super) cpu: &'a mut PpcCpu,
    pub(super) memory: &'a mut PpcSectionMem,
    pub(super) process_memory_manager: &'a mut ProcessNativeMemoryManager,
    pub(super) heap_cursor: &'a mut u32,
    pub(super) heap_limit: u32,
    pub(super) last_mem_error: &'a mut i16,
    pub(super) handles: &'a mut Vec<PpcHandleRecord>,
    pub(super) gworlds: &'a mut [PpcGWorldRecord],
    pub(super) current_gdevice: &'a mut u32,
    pub(super) toolbox_startup: &'a mut PpcToolboxStartupState,
    pub(super) screen_clut: &'a mut [[u16; 3]; 256],
    pub(super) color_manager_clut: &'a mut [[u16; 3]; 256],
}

pub(super) fn dispatch_graphics_device_import(
    context: PpcGraphicsDeviceDispatchContext<'_>,
) -> Option<PpcImportAction> {
    let PpcGraphicsDeviceDispatchContext {
        binding,
        cpu,
        memory,
        process_memory_manager,
        heap_cursor,
        heap_limit,
        last_mem_error,
        handles,
        gworlds,
        current_gdevice,
        toolbox_startup,
        screen_clut,
        color_manager_clut,
    } = context;

    match binding.dispatcher_target {
        PpcImportDispatcherTarget::GetGDevice => Some(PpcImportAction::Return(*current_gdevice)),
        PpcImportDispatcherTarget::SetGDevice => {
            if cpu.gpr[3] != 0 {
                *current_gdevice = cpu.gpr[3];
                ppc_register_gdevice(toolbox_startup, cpu.gpr[3]);
            }
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::GDeviceChanged => {
            // Apple QuickDraw Reference (2007), p. 223: a changed pmTable
            // requires GDeviceChanged; edited table contents additionally
            // require CTabChanged. Preserve the table's seed and hardware CLUT.
            let device = cpu.gpr[3];
            if let Some(record) = ppc_current_gdevice_record(memory, device) {
                ppc_register_gdevice(toolbox_startup, device);
                if let Some(table) = ppc_gdevice_ctable_handle(memory, device) {
                    if device == PPC_MAIN_GDEVICE {
                        // Main-screen Color2Index uses this logical snapshot;
                        // other devices read their current table directly.
                        if let Some(updated) =
                            ppc_read_ctable_clut(memory, table, color_manager_clut)
                        {
                            *color_manager_clut = updated;
                        }
                    }
                    let table_seed = memory
                        .read_u32_be(table)
                        .filter(|&ptr| ptr != 0)
                        .and_then(|ptr| memory.read_u32_be(ptr));
                    let inverse = record
                        .checked_add(6)
                        .and_then(|field| memory.read_u32_be(field))
                        .filter(|&handle| handle != 0)
                        .and_then(|handle| memory.read_u32_be(handle))
                        .filter(|&ptr| ptr != 0);
                    if let (Some(seed), Some(inverse)) = (table_seed, inverse) {
                        // A mismatched seed marks an existing inverse table stale.
                        // Rebuilding remains the normal MakeITable operation.
                        let _ = memory.write_u32_be(inverse, !seed);
                    }
                }
            }
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::GetDeviceList | PpcImportDispatcherTarget::GetMainDevice => {
            Some(PpcImportAction::Return(PPC_MAIN_GDEVICE))
        }
        PpcImportDispatcherTarget::GetMaxDevice => {
            let device = ppc_read_rect(memory, cpu.gpr[3])
                .filter(|&(top, left, bottom, right)| {
                    // Inside Macintosh: Imaging With QuickDraw (1994),
                    // pp. 5-27–5-28: GetMaxDevice considers only graphics
                    // devices intersecting the supplied global rectangle.
                    bottom > 0
                        && right > 0
                        && top < ppc_main_screen_height() as i16
                        && left < ppc_main_screen_width() as i16
                })
                .map_or(0, |_| PPC_MAIN_GDEVICE);
            Some(PpcImportAction::Return(device))
        }
        PpcImportDispatcherTarget::GetNextDevice => Some(PpcImportAction::Return(0)),
        PpcImportDispatcherTarget::DeviceLoop => {
            // DeviceLoop (InterfaceLib)
            // Visits each distinct video device intersecting the drawing region.
            // PROCEDURE DeviceLoop(drawingRgn: RgnHandle;
            //   drawingProc: DeviceLoopDrawingProcPtr; userData: LongInt;
            //   flags: DeviceLoopFlags);
            // Inside Macintosh: Imaging With QuickDraw (1994), pp. 5-29--5-30, 5-35.
            let region = cpu.gpr[3];
            let drawing_proc = cpu.gpr[4];
            let user_data = cpu.gpr[5];
            let all_devices = cpu.gpr[6] & (1 << 2) != 0;
            let device_handle = if *current_gdevice == 0 {
                PPC_MAIN_GDEVICE
            } else {
                *current_gdevice
            };
            let device = memory.read_u32_be(device_handle).filter(|&ptr| ptr != 0);
            let intersects = device
                .and_then(|ptr| ppc_read_rect(memory, ptr + 34))
                .zip(ppc_read_rgn_bbox(memory, region))
                .is_some_and(|(device_rect, region_rect)| {
                    device_rect.0 < region_rect.2
                        && device_rect.1 < region_rect.3
                        && device_rect.2 > region_rect.0
                        && device_rect.3 > region_rect.1
                });
            if drawing_proc == 0 || device.is_none() || (!all_devices && !intersects) {
                return Some(PpcImportAction::ReturnPreserve);
            }
            let device = device?;
            let pixmap = memory
                .read_u32_be(device + 22)
                .and_then(|handle| memory.read_u32_be(handle));
            let depth = pixmap
                .and_then(|ptr| memory.read_u16_be(ptr + 32))
                .unwrap_or(0);
            let device_flags = memory.read_u16_be(device + 20).unwrap_or(0);
            let callback = ppc_resolve_callback_target(memory, drawing_proc, cpu.gpr[2], None)?;
            let final_pc = cpu.lr;
            let restore_rtoc = cpu.gpr[2];
            install_powerpc_call_arguments(
                cpu,
                memory,
                &[
                    u32::from(depth),
                    u32::from(device_flags),
                    device_handle,
                    user_data,
                ],
            )?;
            GuestCallEffect::call_guest(
                GuestCallRequest::new(GuestCallTarget {
                    isa: GuestIsa::PowerPc,
                    entry: callback.entry,
                    rtoc: callback.rtoc,
                }),
                GuestCallContinuation::to_powerpc(
                    PPC_GUEST_CALL_RETURN_PC,
                    final_pc,
                    restore_rtoc,
                    PpcNativeReturnGpr3::Preserve,
                ),
            )
            .into_ppc_import_action()
        }
        PpcImportDispatcherTarget::TestDeviceAttribute => Some(PpcImportAction::Return(
            ppc_test_device_attribute(cpu, memory),
        )),
        PpcImportDispatcherTarget::SetDeviceAttribute => {
            ppc_set_device_attribute(cpu, memory);
            Some(PpcImportAction::ReturnPreserve)
        }
        PpcImportDispatcherTarget::HasDepth => {
            // Imaging With QuickDraw (1994), pp. 5-33--5-34: return a
            // nonzero mode ID only when the requested device, pixel depth,
            // and color mode can be imposed by SetDepth.
            Some(PpcImportAction::Return(ppc_has_depth(cpu, memory)))
        }
        PpcImportDispatcherTarget::SetDepth => {
            let mut allocator = PpcProcessAllocatorView {
                memory_manager: process_memory_manager,
            };
            Some(PpcImportAction::Return(ppc_i16_result(ppc_set_depth(
                cpu,
                Some(&mut allocator),
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
                gworlds,
                toolbox_startup,
                screen_clut,
                color_manager_clut,
            ))))
        }
        PpcImportDispatcherTarget::QuickDrawCompatibility(
            PpcQuickDrawCompatibilityOperation::NewGDevice,
        ) => {
            let handle = ppc_process_alloc_handle(
                process_memory_manager,
                memory,
                heap_cursor,
                last_mem_error,
                handles,
                62,
                true,
            );
            *last_mem_error = if handle == 0 {
                PPC_MEM_FULL_ERR
            } else {
                PPC_NO_ERR
            };
            ppc_register_gdevice(toolbox_startup, handle);
            Some(PpcImportAction::Return(handle))
        }
        PpcImportDispatcherTarget::QuickDrawCompatibility(
            PpcQuickDrawCompatibilityOperation::DisposeGDevice,
        ) => {
            toolbox_startup.active_device_palettes.remove(&cpu.gpr[3]);
            toolbox_startup
                .known_gdevices
                .retain(|&gdevice| gdevice != cpu.gpr[3]);
            toolbox_startup.clut_protected_by_device.remove(&cpu.gpr[3]);
            toolbox_startup.clut_reserved_by_device.remove(&cpu.gpr[3]);
            toolbox_startup
                .palette_allocations
                .retain(|allocation| allocation.gdevice != cpu.gpr[3]);
            let mut allocator = PpcProcessAllocatorView {
                memory_manager: process_memory_manager,
            };
            let _ = allocator.dispose_handle(
                memory,
                heap_cursor,
                heap_limit,
                last_mem_error,
                handles,
                cpu.gpr[3],
            );
            Some(PpcImportAction::ReturnPreserve)
        }
        _ => None,
    }
}