Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-window

Source of release 0.6.2

0.6.2 / src / window / windows / events.lucb

#==============================================================================================
#
#   events - The Win32 window-procedure event translation
#
#   DESCRIPTION:
#       The Win32 window procedure and its translation of messages into portable events.
#
#==============================================================================================

# mark: The window procedure and event translation ============================================

extern func GetKeyState(key: i32) -> i16
extern func SetCapture(window: void*) -> void*?
extern func ReleaseCapture() -> i32
extern func ScreenToClient(window: void*, point: WinPoint*) -> i32
extern func ClientToScreen(window: void*, point: WinPoint*) -> i32
extern func GetMessageTime() -> i32

## MOUSEMOVEPOINT: a merged pointer position, in 16-bit screen pixels.
extern struct WinMovePoint:
    x: i32
    y: i32
    time: u32
    extra: usize

extern func GetMouseMovePointsEx(size: u32, point: WinMovePoint*, buffer: WinMovePoint*, count: i32, resolution: u32) -> i32

## TRACKMOUSEEVENT uses the native pointer alignment on each Windows target.
struct WinMouseTracking:
    var size: u32
    var flags: u32
    var window: void*
    var hover_time: u32

extern func TrackMouseEvent(tracking: WinMouseTracking*) -> i32

func win_modifiers() -> input.Modifiers:
    return input.Modifiers(shift = key_down(16), control = key_down(17), alt = key_down(18), super = key_down(91) or key_down(92),
                           caps_lock = ((u16)GetKeyState(20) & 1) != 0)

## Whether virtual key `key` is held: bit 15 of GetKeyState's state. Read as
## bits, not as a sign, and through a local, so a compiler that leaves the
## bits above a 16-bit C result undefined cannot misread it.
func key_down(key: i32) -> bool:
    let state: i16 = GetKeyState(key)
    return ((u16)state & 0x8000) != 0

func signed_half(value: isize) -> i32:
    let half = (i32)(value & 65535)
    return half - 65536 if half >= 32768 else half

# Hardware scan positions, independent of the active keyboard layout.
let win_scan_keys: u16[64] = [0, 41, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 45, 46, 42, 43,
                              20, 26, 8, 21, 23, 28, 24, 12, 18, 19, 47, 48, 40, 224, 4, 22,
                              7, 9, 10, 11, 13, 14, 15, 51, 52, 53, 225, 49, 29, 27, 6, 25,
                              5, 17, 16, 54, 55, 56, 229, 0, 226, 44, 57, 58, 59, 60, 61, 62]

func win_key(value: isize) -> input.Key:
    let scan = (usize)((value >> 16) & 255)
    let extended = (value & 16777216) != 0
    if extended:
        match scan:
            29: return input.Key.right_control
            56: return input.Key.right_alt
            71: return input.Key.home
            72: return input.Key.up
            73: return input.Key.page_up
            75: return input.Key.left
            77: return input.Key.right
            79: return input.Key.end
            80: return input.Key.down
            81: return input.Key.page_down
            83: return input.Key.delete
            91: return input.Key.left_super
            92: return input.Key.right_super
            _: return input.Key.unknown
    if scan < win_scan_keys.length:
        return (input.Key)win_scan_keys[scan]
    if scan >= 64 and scan <= 68:
        return (input.Key)(u16)(scan - 64 + 63)
    if scan == 87: return input.Key.f11
    if scan == 88: return input.Key.f12
    return input.Key.unknown

func win_callback(native: void*, message: u32, word: usize, value: isize) -> isize:
    if message == 129:
        # CREATESTRUCTW begins with the application-supplied pointer.
        let state = *(State**)(void*)value
        state.native = native
        _ = SetWindowLongPtrW(native, -21, (isize)(void*)state)
        return DefWindowProcW(native, message, word, value)
    let stored = GetWindowLongPtrW(native, -21)
    if stored == 0:
        return DefWindowProcW(native, message, word, value)
    let state = (State*)(void*)stored
    if state.destroyed:
        return DefWindowProcW(native, message, word, value)
    if message == 32 and (value & 65535) == 1:
        _ = SetCursor(state.native_cursor)
        return 1
    if message == 16:
        state.close_requested = true
        return 0
    if message == 5:
        push_event(state, input.Event(kind = input.EventKind.resized))
        invoke_redraw(state)
    elif message == 7 or message == 8:
        state.pending_surrogate = 0
        push_event(state, input.Event(kind = input.EventKind.focus_gained if message == 7 else input.EventKind.focus_lost))
    elif message == 258:
        # WM_CHAR supplies UTF-16, including surrogate pairs and AltGr text.
        if state.text_input:
            push_utf16(state, (u16)word)
        return 0
    elif message == 265:
        # WM_UNICHAR probes support with UNICODE_NOCHAR, then supplies UTF-32.
        if word == 0xFFFF:
            return 1
        if state.text_input and word <= 0x10FFFF:
            push_scalar(state, (u32)word)
        return 0
    elif message == 736:
        let rect = (WinRect*)(void*)value
        _ = SetWindowPos(native, none, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, 20)
        push_event(state, input.Event(kind = input.EventKind.resized))
        return 0
    elif message == 256 or message == 257 or message == 260 or message == 261:
        let key_modifiers = win_modifiers()
        let key = win_key(value)
        let down = message == 256 or message == 260
        push_event(state, input.Event(kind = input.EventKind.key_down if down else input.EventKind.key_up,
                                      key = key, modifiers = key_modifiers, repeated = down and (value & 1073741824) != 0))
        if (u16)key >= 224 or key == input.Key.caps_lock:
            push_event(state, input.Event(kind = input.EventKind.modifiers_changed, modifiers = key_modifiers))
    # Let DefWindowProc retain system shortcuts such as Alt+F4.
    elif message == 675:
        # WM_MOUSELEAVE disarms tracking; the next move starts a new interval.
        state.pointer_tracking = false
        push_event(state, input.Event(kind = input.EventKind.pointer_left))
        return 0
    elif win_pointer_message(message):
        if win_pointer(state, native, message, word):
            return 0
    elif message >= 512 and message <= 526:
        var point = WinPoint(x = signed_half(value), y = signed_half(value >> 16))
        let scrolling = message == 522 or message == 526
        if scrolling:
            _ = ScreenToClient(native, &point)
        let dpi = GetDpiForWindow(native)
        let scale = (f64)dpi / 96.0 if dpi > 0 else 1.0
        var event = input.Event(kind = input.EventKind.pointer_moved, modifiers = win_modifiers(), x = (f64)point.x / scale, y = (f64)point.y / scale)
        # A touch's (or a pen without Windows Ink handling) promoted mouse message.
        event.pointer_kind = win_promoted_kind((usize)GetMessageExtraInfo())
        if message == 512:
            push_merged_moves(state, native, point, (word & 19) != 0, scale, event.modifiers)
        if message == 512 and not state.pointer_tracking:
            var tracking = WinMouseTracking(size = (u32)memory.size_of(WinMouseTracking), flags = 2, window = native)
            state.pointer_tracking = TrackMouseEvent(&tracking) != 0
            var entered = event
            entered.kind = input.EventKind.pointer_entered
            push_event(state, entered)
        if scrolling:
            event.kind = input.EventKind.scroll
            let delta = (f64)signed_half((isize)(word >> 16)) / 120.0
            # WM_MOUSEHWHEEL is positive toward the right of the document.
            # Portable deltas describe content movement, matching AppKit.
            event.scroll_x = -delta if message == 526 else 0.0
            event.scroll_y = delta if message == 522 else 0.0
            event.scroll_unit = input.ScrollUnit.lines
        elif message != 512:
            let down = message == 513 or message == 516 or message == 519 or message == 523
            let up = message == 514 or message == 517 or message == 520 or message == 524
            if not down and not up:
                return DefWindowProcW(native, message, word, value)
            event.kind = input.EventKind.pointer_down if down else input.EventKind.pointer_up
            event.button = 0 if message <= 514 else (1 if message <= 517 else (2 if message <= 520 else (u32)(word >> 16) + 2))
            if down:
                _ = SetCapture(native)
            elif (word & 115) == 0:
                _ = ReleaseCapture()
        push_event(state, event)
        return 0
    return DefWindowProcW(native, message, word, value)

## Win32 merges pointer moves: while the loop is busy only the latest reaches
## it, and a fast brush circle becomes a polygon. With a button held, the
## positions merged since the last move come back from GetMouseMovePointsEx
## and are queued, oldest first, before the current one.
func push_merged_moves(state: State*, native: void*, client: WinPoint, held: bool, scale: f64, held_keys: input.Modifiers):
    var screen = client
    _ = ClientToScreen(native, &screen)
    let known = state.move_known
    let last_x = state.move_x
    let last_y = state.move_y
    let last_time = state.move_time
    state.move_known = true
    state.move_x = screen.x
    state.move_y = screen.y
    state.move_time = (u32)GetMessageTime()
    if not held or not known:
        return
    var current = WinMovePoint(x = screen.x & 65535, y = screen.y & 65535, time = state.move_time, extra = 0)
    var merged: WinMovePoint[64]
    # GMMP_USE_DISPLAY_POINTS. The message time is when the merged move was read,
    # often a timer tick (~15.6 ms) after the history's time for that point, so
    # the exact lookup can miss (-1); a zero time matches the newest entry there.
    var found = GetMouseMovePointsEx((u32)memory.size_of(WinMovePoint), &current, &merged[0], 64, 1)
    if found < 1:
        var any_time = WinMovePoint(x = screen.x & 65535, y = screen.y & 65535, time = 0, extra = 0)
        found = GetMouseMovePointsEx((u32)memory.size_of(WinMovePoint), &any_time, &merged[0], 64, 1)
    if found < 1:
        return
    # The history's own time for this point: a merged move is stamped when it
    # is read, later than the points it merged, so that stamp would cut them.
    state.move_time = merged[0].time
    # Newest first: the first entry is the current move; stop at the one last
    # delivered (its position at its time), or anything older.
    var count: i32 = 1
    while count < found:
        let entry = merged[(usize)count]
        let x = entry.x - 65536 if entry.x > 32767 else entry.x
        let y = entry.y - 65536 if entry.y > 32767 else entry.y
        if entry.time < last_time or (entry.time == last_time and x == last_x and y == last_y):
            break
        count += 1
    var index = count - 1
    while index >= 1:
        let entry = merged[(usize)index]
        var position = WinPoint(x = entry.x - 65536 if entry.x > 32767 else entry.x, y = entry.y - 65536 if entry.y > 32767 else entry.y)
        _ = ScreenToClient(native, &position)
        push_event(state, input.Event(kind = input.EventKind.pointer_moved, modifiers = held_keys, x = (f64)position.x / scale, y = (f64)position.y / scale))
        index -= 1