Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-window

Source of release 0.6.3

0.6.3 / src / window / macos / events.lucb

#==============================================================================================
#
#   events - The AppKit event callbacks
#
#   DESCRIPTION:
#       AppKit invokes these methods synchronously while the main thread pumps events. Queued
#       events retain no NSEvent/NSNotification objects. AppKit's text service may allocate its
#       own composition state while interpreting a key event.
#
#==============================================================================================

func close_callback(object: void*, selector: void*, sender: void*) -> bool:
    _ = selector
    _ = sender
    if let state = get_state(object):
        state.close_requested = true
    return false

func resize_callback(object: void*, selector: void*, notification: void*):
    _ = selector
    _ = notification
    if let state = get_state(object):
        push_event(state, input.Event(kind = input.EventKind.resized))
        invoke_redraw(state)

func focus_callback(object: void*, selector: void*, notification: void*):
    _ = notification
    if let state = get_state(object):
        let gained = selector == sel("windowDidBecomeKey:")
        if not gained:
            mac_clear_marked(state)
            state.primary_down = false
            state.pointer_inside = false
        push_event(state, input.Event(kind = input.EventKind.focus_gained if gained else input.EventKind.focus_lost))

func view_accepts(object: void*, selector: void*) -> bool:
    _ = object
    _ = selector
    return true

func modifiers(flags: u64) -> input.Modifiers:
    return input.Modifiers(shift = (flags & (1 << 17)) != 0, control = (flags & (1 << 18)) != 0, alt = (flags & (1 << 19)) != 0, super = (flags & (1 << 20)) != 0, caps_lock = (flags & (1 << 16)) != 0)

func key_callback(object: void*, selector: void*, native: void*):
    _ = selector
    let state = get_state(object) else return
    let native_type = msg_uint(native, sel("type"))
    var event = input.Event(kind = input.EventKind.modifiers_changed)
    event.modifiers = modifiers(msg_uint(native, sel("modifierFlags")))
    event.key = physical_key(msg_key(native, sel("keyCode")))
    if native_type == 10 or native_type == 11:
        event.kind = input.EventKind.key_down if native_type == 10 else input.EventKind.key_up
        event.repeated = msg_bool(native, sel("isARepeat"))
    # Composition navigation belongs to AppKit until the marked text is committed.
    let composing = state.marked_text != none
    if not composing:
        push_event(state, event)
    if native_type == 10 and state.text_input and not event.modifiers.super and not event.modifiers.control:
        let array_class = objc_getClass("NSArray") else return
        let events = msg_one_object(array_class, sel("arrayWithObject:"), native) else return
        msg_object(object, sel("interpretKeyEvents:"), events)

func pointer_callback(object: void*, selector: void*, native: void*):
    _ = selector
    let state = get_state(object) else return
    let native_type = msg_uint(native, sel("type"))
    let position = msg_convert(object, sel("convertPoint:fromView:"), msg_point(native, sel("locationInWindow")), none)
    var event = input.Event(kind = input.EventKind.pointer_moved, x = position.x, y = position.y)
    event.modifiers = modifiers(msg_uint(native, sel("modifierFlags")))
    if native_type == 8:
        event.kind = input.EventKind.pointer_entered
    elif native_type == 9:
        state.pointer_inside = false
        push_event(state, input.Event(kind = input.EventKind.pointer_left))
        return
    elif native_type == 1 or native_type == 3 or native_type == 25:
        event.kind = input.EventKind.pointer_down
        event.button = (u32)msg_uint(native, sel("buttonNumber"))
    elif native_type == 2 or native_type == 4 or native_type == 26:
        event.kind = input.EventKind.pointer_up
        event.button = (u32)msg_uint(native, sel("buttonNumber"))
    elif native_type == 22:
        event.kind = input.EventKind.scroll
        event.scroll_x = msg_double(native, sel("scrollingDeltaX"))
        event.scroll_y = msg_double(native, sel("scrollingDeltaY"))
        event.scroll_unit = input.ScrollUnit.points if msg_bool(native, sel("hasPreciseScrollingDeltas")) else input.ScrollUnit.lines
    elif native_type == 30:
        # NSEventTypeMagnify: the pinch's magnification change since the last event.
        event.kind = input.EventKind.magnify
        event.scroll_y = msg_double(native, sel("magnification"))
        event.scroll_unit = input.ScrollUnit.points
    elif native_type == 24:
        # NSEventTypeTabletProximity: which end of which tool came near, or left.
        mac_proximity(state, native)
        return
    # Tablet points (NSEventTypeTabletPoint, or a mouse event of subtype 1) carry
    # the pen's pressure, tilt, rotation and wheel; a mouse event of subtype 2
    # carries a proximity change. Everything else is the mouse's.
    let pointing = (native_type >= 1 and native_type <= 7) or native_type == 25 or native_type == 26 or native_type == 27
    if native_type == 23 or pointing:
        let subtype = msg_uint(native, sel("subtype")) if pointing else 1
        if subtype == 2:
            mac_proximity(state, native)
        if subtype == 1:
            let tilt = msg_point(native, sel("tilt"))
            event = mac_pen(event, input.PointerKind.eraser if state.mac_eraser else input.PointerKind.pen, msg_float(native, sel("pressure")), tilt.x, tilt.y,
                            msg_float(native, sel("rotation")), msg_float(native, sel("tangentialPressure")))
    let bounds = msg_rect(object, sel("bounds"))
    state.pointer_inside = position.x >= 0.0 and position.y >= 0.0 and position.x < bounds.size.width and position.y < bounds.size.height
    if event.button == 0:
        if event.kind == input.EventKind.pointer_down: state.primary_down = true
        if event.kind == input.EventKind.pointer_up: state.primary_down = false
    push_event(state, event)

## A proximity event: the tool's end that came near (NSPointingDeviceType 3
## is the eraser), kept for the tablet points that follow.
func mac_proximity(state: State*, native: void*):
    let entering = msg_bool(native, sel("isEnteringProximity"))
    state.mac_eraser = mac_pointing_kind(msg_uint(native, sel("pointingDeviceType")), entering) == input.PointerKind.eraser

## The pointer kind for NSPointingDeviceType `device` coming near (or leaving).
func mac_pointing_kind(device: u64, entering: bool) -> input.PointerKind:
    if not entering:
        return input.PointerKind.pen
    return input.PointerKind.eraser if device == 3 else input.PointerKind.pen

## `event` with a tablet point's values: AppKit's pressure 0..1, tilt as -1..1
## per axis with y up (scaled as Qt does, to about the 60 degrees tablets
## reach, y turned to point down the screen), rotation in degrees
## counter-clockwise, and the airbrush wheel's tangential pressure.
func mac_pen(event: input.Event, kind: input.PointerKind, pressure: f32, tilt_x: f64, tilt_y: f64, rotation: f32, tangential: f32) -> input.Event:
    var pen = event
    pen.pointer_kind = kind
    pen.pressure = math.clamp((f64)pressure, 0.0, 1.0) if math.is_finite((f64)pressure) else 0.0
    pen.tilt_x = math.clamp(tilt_x * 60.0, -90.0, 90.0) if math.is_finite(tilt_x) else 0.0
    pen.tilt_y = math.clamp(-tilt_y * 60.0, -90.0, 90.0) if math.is_finite(tilt_y) else 0.0
    var turned = 360.0 - (f64)rotation if math.is_finite((f64)rotation) else 0.0
    turned -= math.floor(turned / 360.0) * 360.0
    pen.rotation = turned
    pen.tangential = math.clamp((f64)tangential, -1.0, 1.0) if math.is_finite((f64)tangential) else 0.0
    return input.with_pen_angles(pen)

test "a macOS tablet point reads as a pen with its tilt in degrees, y down the screen":
    let base = input.Event(kind = input.EventKind.pointer_moved, x = 10.0, y = 20.0)
    let pen = mac_pen(base, input.PointerKind.pen, 0.5, 0.5, 0.5, 90.0, 0.25)
    assert(pen.pointer_kind == input.PointerKind.pen and pen.pressure == 0.5 and pen.x == 10.0)
    assert(pen.tilt_x == 30.0 and pen.tilt_y == -30.0)
    # Leaning right and up the screen: between 270 and 360.
    assert(pen.azimuth > 270.0 and pen.azimuth < 360.0 and pen.altitude < 60.0)
    assert(pen.rotation == 270.0 and pen.tangential == 0.25)
    let flat = mac_pen(base, input.PointerKind.eraser, 2.0, 0.0, 0.0, -30.0, -3.0)
    assert(flat.pointer_kind == input.PointerKind.eraser and flat.pressure == 1.0 and flat.altitude == 90.0)
    assert(flat.rotation == 30.0 and flat.tangential == -1.0)

test "the eraser end is known from its proximity event":
    assert(mac_pointing_kind(3, true) == input.PointerKind.eraser)
    assert(mac_pointing_kind(1, true) == input.PointerKind.pen)
    assert(mac_pointing_kind(3, false) == input.PointerKind.pen)

## Hardware positions from the macOS HIToolbox virtual-key table. Zero slots
## deliberately remain unknown (including keypad/international keys for now).
let key_positions: u16[128] = [
    4, 22, 7, 9, 11, 10, 29, 27, 6, 25, 0, 5, 20, 26, 8, 21,
    28, 23, 30, 31, 32, 33, 35, 34, 46, 38, 36, 45, 37, 39, 48, 18,
    24, 47, 12, 19, 40, 15, 13, 52, 14, 51, 49, 54, 56, 17, 16, 55,
    43, 44, 53, 42, 0, 41, 231, 227, 225, 57, 226, 224, 229, 230, 228, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    62, 63, 64, 60, 65, 66, 0, 68, 0, 0, 0, 0, 0, 67, 0, 69,
    0, 0, 0, 74, 75, 76, 61, 77, 59, 78, 58, 80, 79, 81, 82, 0,
]

func physical_key(code: u16) -> input.Key:
    # HIToolbox kVK_ANSI_KeypadEnter is an Enter action, like Linux/Windows.
    if code == 76:
        return input.Key.enter
    if code >= key_positions.length:
        return input.Key.unknown
    return (input.Key)key_positions[code]

test "both Return and keypad Enter submit controls":
    assert(physical_key(36) == input.Key.enter)
    assert(physical_key(76) == input.Key.enter)