<commit_before>! Copyright (C) 2005, 2006 <NAME>.
! Portions copyright (C) 2007, 2010 <NAME>.
! See http://factorcode.org/license.txt for BSD license.
USING: accessors alien alien.data alien.strings arrays ascii assocs
calendar classes classes.struct colors combinators continuations fry
io io.crlf io.encodings.utf16n kernel libc literals locals make math
math.bitwise namespaces sequences sets specialized-arrays strings
threads ui ui.backend ui.clipboards ui.event-loop ui.gadgets
ui.gadgets.private ui.gadgets.worlds ui.gestures ui.pixel-formats
ui.private windows.dwmapi windows.errors windows.gdi32
windows.kernel32 windows.messages windows.offscreen windows.opengl32
windows.types windows.user32 assocs.extras byte-arrays
io.encodings.string ;
FROM: unicode => upper-surrogate? under-surrogate? ;
SPECIALIZED-ARRAY: POINT
QUALIFIED-WITH: alien.c-types c
IN: ui.backend.windows

SINGLETON: windows-ui-backend

TUPLE: win-base hDC hRC ;
TUPLE: win < win-base hWnd world title ;
C: <win> win

<PRIVATE

CONSTANT: perm-attribs { $ WGL_SUPPORT_OPENGL_ARB 1 }

CONSTANT: attrib-table H{
    { double-buffered { $ WGL_DOUBLE_BUFFER_ARB 1 } }
    { stereo { $ WGL_STEREO_ARB 1 } }
    { offscreen { $ WGL_DRAW_TO_BITMAP_ARB 1 } }
    { fullscreen { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
    { windowed { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
    { accelerated { $ WGL_ACCELERATION_ARB $ WGL_FULL_ACCELERATION_ARB } }
    { software-rendered { $ WGL_ACCELERATION_ARB $ WGL_NO_ACCELERATION_ARB } }
    { backing-store { $ WGL_SWAP_METHOD_ARB $ WGL_SWAP_COPY_ARB } }
    { color-float { $ WGL_TYPE_RGBA_FLOAT_ARB 1 } }
    { color-bits { $ WGL_COLOR_BITS_ARB } }
    { red-bits { $ WGL_RED_BITS_ARB } }
    { green-bits { $ WGL_GREEN_BITS_ARB } }
    { blue-bits { $ WGL_BLUE_BITS_ARB } }
    { alpha-bits { $ WGL_ALPHA_BITS_ARB } }
    { accum-bits { $ WGL_ACCUM_BITS_ARB } }
    { accum-red-bits { $ WGL_ACCUM_RED_BITS_ARB } }
    { accum-green-bits { $ WGL_ACCUM_GREEN_BITS_ARB } }
    { accum-blue-bits { $ WGL_ACCUM_BLUE_BITS_ARB } }
    { accum-alpha-bits { $ WGL_ACCUM_ALPHA_BITS_ARB } }
    { depth-bits { $ WGL_DEPTH_BITS_ARB } }
    { stencil-bits { $ WGL_STENCIL_BITS_ARB } }
    { aux-buffers { $ WGL_AUX_BUFFERS_ARB } }
    { sample-buffers { $ WGL_SAMPLE_BUFFERS_ARB } }
    { samples { $ WGL_SAMPLES_ARB } }
}

: has-wglChoosePixelFormatARB? ( world -- ? )
    drop f ;

: arb-make-pixel-format ( world attributes -- pf )
    [ handle>> hDC>> ] dip
    perm-attribs attrib-table pixel-format-attributes>int-array
    f 1 { c:int c:int }
    [ wglChoosePixelFormatARB win32-error=0/f ] with-out-parameters drop ;

CONSTANT: pfd-flag-map H{
    { double-buffered $ PFD_DOUBLEBUFFER }
    { stereo $ PFD_STEREO }
    { offscreen $ PFD_DRAW_TO_BITMAP }
    { fullscreen $ PFD_DRAW_TO_WINDOW }
    { windowed $ PFD_DRAW_TO_WINDOW }
    { backing-store $ PFD_SWAP_COPY }
    { software-rendered $ PFD_GENERIC_FORMAT }
}

: >pfd-flag ( attribute -- value )
    pfd-flag-map at [ ] [ 0 ] if* ;

: >pfd-flags ( attributes -- flags )
    [ >pfd-flag ] [ bitor ] map-reduce
    PFD_SUPPORT_OPENGL bitor ;

: attr-value ( attributes name -- value )
    [ instance? ] curry find nip
    [ value>> ] [ 0 ] if* ;

: >pfd ( attributes -- pfd )
    [ PIXELFORMATDESCRIPTOR <struct> ] dip
    {
        [ drop PIXELFORMATDESCRIPTOR c:heap-size >>nSize ]
        [ drop 1 >>nVersion ]
        [ >pfd-flags >>dwFlags ]
        [ drop PFD_TYPE_RGBA >>iPixelType ]
        [ color-bits attr-value >>cColorBits ]
        [ red-bits attr-value >>cRedBits ]
        [ green-bits attr-value >>cGreenBits ]
        [ blue-bits attr-value >>cBlueBits ]
        [ alpha-bits attr-value >>cAlphaBits ]
        [ accum-bits attr-value >>cAccumBits ]
        [ accum-red-bits attr-value >>cAccumRedBits ]
        [ accum-green-bits attr-value >>cAccumGreenBits ]
        [ accum-blue-bits attr-value >>cAccumBlueBits ]
        [ accum-alpha-bits attr-value >>cAccumAlphaBits ]
        [ depth-bits attr-value >>cDepthBits ]
        [ stencil-bits attr-value >>cStencilBits ]
        [ aux-buffers attr-value >>cAuxBuffers ]
        [ drop PFD_MAIN_PLANE >>dwLayerMask ]
    } cleave ;

: pfd-make-pixel-format ( world attributes -- pf )
    [ handle>> hDC>> ] [ >pfd ] bi*
    ChoosePixelFormat dup win32-error=0/f ;

M: windows-ui-backend (make-pixel-format)
    over has-wglChoosePixelFormatARB?
    [ arb-make-pixel-format ] [ pfd-make-pixel-format ] if ;

M: windows-ui-backend (free-pixel-format)
    drop ;

PRIVATE>

: GET_APPCOMMAND_LPARAM ( lParam -- appCommand )
    hi-word FAPPCOMMAND_MASK lo-word bitnot bitand ; inline

: enum-clipboard ( -- seq )
    0
    [ EnumClipboardFormats win32-error dup dup 0 > ]
    [ ]
    produce 2nip ;

: with-clipboard ( quot -- )
    f OpenClipboard win32-error=0/f
    call
    CloseClipboard win32-error=0/f ; inline

: paste ( -- str )
    [
        CF_UNICODETEXT IsClipboardFormatAvailable zero? [
            ! nothing to paste
            ""
        ] [
            CF_UNICODETEXT GetClipboardData dup win32-error=0/f
            dup GlobalLock dup win32-error=0/f
            GlobalUnlock win32-error=0/f
            alien>native-string
        ] if
    ] with-clipboard
    crlf>lf ;

: copy ( str -- )
    lf>crlf [
        native-string>alien
        EmptyClipboard win32-error=0/f
        GMEM_MOVEABLE over length 1 + GlobalAlloc
            dup win32-error=0/f

        dup GlobalLock dup win32-error=0/f
        rot binary-object memcpy
        dup GlobalUnlock win32-error=0/f
        CF_UNICODETEXT swap SetClipboardData win32-error=0/f
    ] with-clipboard ;

TUPLE: pasteboard ;
C: <pasteboard> pasteboard

M: pasteboard clipboard-contents drop paste ;
M: pasteboard set-clipboard-contents drop copy ;

: init-clipboard ( -- )
    <pasteboard> clipboard set-global
    <clipboard> selection set-global ;

SYMBOLS: msg-obj class-name-ptr mouse-captured ;

CONSTANT: window-control>style
    H{
        { close-button 0 }
        { textured-background 0 }
        { minimize-button $ WS_MINIMIZEBOX }
        { maximize-button $ WS_MAXIMIZEBOX }
        { resize-handles $ WS_THICKFRAME }
        { small-title-bar $ WS_CAPTION }
        { normal-title-bar $ WS_CAPTION }
        { dialog-window 0 }
    }

CONSTANT: window-control>ex-style
    H{
        { close-button 0 }
        { textured-background 0 }
        { minimize-button 0 }
        { maximize-button 0 }
        { resize-handles $ WS_EX_WINDOWEDGE }
        { small-title-bar flags{ WS_EX_TOOLWINDOW WS_EX_TOPMOST } }
        { normal-title-bar $ WS_EX_APPWINDOW }
        { dialog-window 0 }
    }

: needs-sysmenu? ( controls -- ? )
    { close-button minimize-button maximize-button } intersects? ;

: has-titlebar? ( controls -- ? )
    { small-title-bar normal-title-bar } intersects? ;

: world>style ( world -- n )
    window-controls>>
    [ window-control>style symbols>flags ]
    [ needs-sysmenu? [ WS_SYSMENU bitor ] when ]
    [ has-titlebar? [ WS_POPUP bitor ] unless ] tri ;

: world>ex-style ( world -- n )
    window-controls>> window-control>ex-style symbols>flags ;

: get-RECT-top-left ( RECT -- x y )
    [ left>> ] [ top>> ] bi ;

: get-RECT-width/height ( RECT -- width height )
    [ [ right>> ] [ left>> ] bi - ]
    [ [ bottom>> ] [ top>> ] bi - ] bi ;

: get-RECT-dimensions ( RECT -- x y width height )
    [ get-RECT-top-left ] [ get-RECT-width/height ] bi ;

: handle-wm-paint ( hWnd uMsg wParam lParam -- )
    ! wParam and lParam are unused
    ! only paint if width/height both > 0
    3drop window t >>active? relayout-1 yield ;

: handle-wm-size ( hWnd uMsg wParam lParam -- )
    2nip
    [ lo-word ] keep hi-word 2array
    dup { 0 0 } = [ 2drop ] [ swap window [ dim<< ] [ drop ] if* ] if ;

: handle-wm-move ( hWnd uMsg wParam lParam -- )
    2nip
    [ lo-word ] keep hi-word 2array
    swap window [ window-loc<< ] [ drop ] if* ;

CONSTANT: wm-keydown-codes
    H{
        { 8 "BACKSPACE" }
        { 9 "TAB" }
        { 13 "RET" }
        { 27 "ESC" }
        { 33 "PAGE_UP" }
        { 34 "PAGE_DOWN" }
        { 35 "END" }
        { 36 "HOME" }
        { 37 "LEFT" }
        { 38 "UP" }
        { 39 "RIGHT" }
        { 40 "DOWN" }
        { 45 "INSERT" }
        { 46 "DELETE" }
        { 112 "F1" }
        { 113 "F2" }
        { 114 "F3" }
        { 115 "F4" }
        { 116 "F5" }
        { 117 "F6" }
        { 118 "F7" }
        { 119 "F8" }
        { 120 "F9" }
        { 121 "F10" }
        { 122 "F11" }
        { 123 "F12" }
    }

: key-state-down? ( key -- ? )
    GetKeyState 16 bit? ;

: left-shift? ( -- ? ) VK_LSHIFT key-state-down? ;
: left-ctrl? ( -- ? ) VK_LCONTROL key-state-down? ;
: left-alt? ( -- ? ) VK_LMENU key-state-down? ;
: right-shift? ( -- ? ) VK_RSHIFT key-state-down? ;
: right-ctrl? ( -- ? ) VK_RCONTROL key-state-down? ;
: right-alt? ( -- ? ) VK_RMENU key-state-down? ;
: shift? ( -- ? ) left-shift? right-shift? or ;
: ctrl? ( -- ? ) left-ctrl? right-ctrl? or ;
: alt? ( -- ? ) left-alt? right-alt? or ;
: caps-lock? ( -- ? ) VK_CAPITAL GetKeyState zero? not ;

: key-modifiers ( -- seq )
    [
        shift? [ S+ , ] when
        ctrl? [ C+ , ] when
        alt? [ A+ , ] when
    ] { } make [ empty? not ] keep f ? ;

CONSTANT: exclude-keys-wm-keydown
    H{
        { 16 "SHIFT" }
        { 17 "CTRL" }
        { 18 "ALT" }
        { 20 "CAPS-LOCK" }
    }

! Values are ignored
CONSTANT: exclude-keys-wm-char
    H{
        { 8 "BACKSPACE" }
        { 9 "TAB" }
        { 13 "RET" }
        { 27 "ESC" }
    }

: exclude-key-wm-keydown? ( n -- ? )
    exclude-keys-wm-keydown key? ;

: exclude-key-wm-char? ( n -- ? )
    exclude-keys-wm-char key? ;

: keystroke>gesture ( n -- mods sym )
    wm-keydown-codes at* [ key-modifiers swap ] [ drop f f ] if ;

: send-key-gesture ( sym action? quot hWnd -- )
    [ [ key-modifiers ] 3dip call ] dip
    window propagate-key-gesture ; inline

: send-key-down ( sym action? hWnd -- )
    [ [ <key-down> ] ] dip send-key-gesture ;

: send-key-up ( sym action? hWnd -- )
    [ [ <key-up> ] ] dip send-key-gesture ;

: key-sym ( wParam -- string/f )
    wm-keydown-codes at ; inline

:: (handle-wm-keydown/up) ( hWnd uMsg wParam lParam send-key-down/up -- )
    wParam exclude-key-wm-keydown? [
        wParam key-sym [
            t hWnd send-key-down/up execute( sym action? hWnd -- )
        ] [
            256 <byte-array> :> keyboard-state
            4 <byte-array> :> chars
            lParam -16 shift 0xff bitand :> scan-code
            keyboard-state GetKeyboardState win32-error=0/f
            VK_CONTROL VK_CAPITAL [ 0 swap keyboard-state set-nth ] bi@
            wParam scan-code keyboard-state chars 2 0 ToUnicode dup win32-error=0/f
            1 <=  [
                1 chars nth 8 shift 0 chars nth bitor
            ] [
                3 chars nth 8 shift 2 chars nth bitor ! dead-key
            ] if
            1string f hWnd send-key-down/up execute( sym action? hWnd -- )
        ] if*
    ] unless ; inline

: handle-wm-keydown ( hWnd uMsg wParam lParam -- )
    \ send-key-down (handle-wm-keydown/up) ;

SYMBOL: upper-surrogate-wm-char<commit_msg>ui.backend.windows: ToUnicode can return 0 and it's not an error that should crash Factor.<commit_after>! Copyright (C) 2005, 2006 <NAME>.
! Portions copyright (C) 2007, 2010 <NAME>.
! See http://factorcode.org/license.txt for BSD license.
USING: accessors alien alien.data alien.strings arrays ascii assocs
calendar classes classes.struct colors combinators continuations fry
io io.crlf io.encodings.utf16n kernel libc literals locals make math
math.bitwise namespaces sequences sets specialized-arrays strings
threads ui ui.backend ui.clipboards ui.event-loop ui.gadgets
ui.gadgets.private ui.gadgets.worlds ui.gestures ui.pixel-formats
ui.private windows.dwmapi windows.errors windows.gdi32
windows.kernel32 windows.messages windows.offscreen windows.opengl32
windows.types windows.user32 assocs.extras byte-arrays
io.encodings.string ;
FROM: unicode => upper-surrogate? under-surrogate? ;
SPECIALIZED-ARRAY: POINT
QUALIFIED-WITH: alien.c-types c
IN: ui.backend.windows

SINGLETON: windows-ui-backend

TUPLE: win-base hDC hRC ;
TUPLE: win < win-base hWnd world title ;
C: <win> win

<PRIVATE

CONSTANT: perm-attribs { $ WGL_SUPPORT_OPENGL_ARB 1 }

CONSTANT: attrib-table H{
    { double-buffered { $ WGL_DOUBLE_BUFFER_ARB 1 } }
    { stereo { $ WGL_STEREO_ARB 1 } }
    { offscreen { $ WGL_DRAW_TO_BITMAP_ARB 1 } }
    { fullscreen { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
    { windowed { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
    { accelerated { $ WGL_ACCELERATION_ARB $ WGL_FULL_ACCELERATION_ARB } }
    { software-rendered { $ WGL_ACCELERATION_ARB $ WGL_NO_ACCELERATION_ARB } }
    { backing-store { $ WGL_SWAP_METHOD_ARB $ WGL_SWAP_COPY_ARB } }
    { color-float { $ WGL_TYPE_RGBA_FLOAT_ARB 1 } }
    { color-bits { $ WGL_COLOR_BITS_ARB } }
    { red-bits { $ WGL_RED_BITS_ARB } }
    { green-bits { $ WGL_GREEN_BITS_ARB } }
    { blue-bits { $ WGL_BLUE_BITS_ARB } }
    { alpha-bits { $ WGL_ALPHA_BITS_ARB } }
    { accum-bits { $ WGL_ACCUM_BITS_ARB } }
    { accum-red-bits { $ WGL_ACCUM_RED_BITS_ARB } }
    { accum-green-bits { $ WGL_ACCUM_GREEN_BITS_ARB } }
    { accum-blue-bits { $ WGL_ACCUM_BLUE_BITS_ARB } }
    { accum-alpha-bits { $ WGL_ACCUM_ALPHA_BITS_ARB } }
    { depth-bits { $ WGL_DEPTH_BITS_ARB } }
    { stencil-bits { $ WGL_STENCIL_BITS_ARB } }
    { aux-buffers { $ WGL_AUX_BUFFERS_ARB } }
    { sample-buffers { $ WGL_SAMPLE_BUFFERS_ARB } }
    { samples { $ WGL_SAMPLES_ARB } }
}

: has-wglChoosePixelFormatARB? ( world -- ? )
    drop f ;

: arb-make-pixel-format ( world attributes -- pf )
    [ handle>> hDC>> ] dip
    perm-attribs attrib-table pixel-format-attributes>int-array
    f 1 { c:int c:int }
    [ wglChoosePixelFormatARB win32-error=0/f ] with-out-parameters drop ;

CONSTANT: pfd-flag-map H{
    { double-buffered $ PFD_DOUBLEBUFFER }
    { stereo $ PFD_STEREO }
    { offscreen $ PFD_DRAW_TO_BITMAP }
    { fullscreen $ PFD_DRAW_TO_WINDOW }
    { windowed $ PFD_DRAW_TO_WINDOW }
    { backing-store $ PFD_SWAP_COPY }
    { software-rendered $ PFD_GENERIC_FORMAT }
}

: >pfd-flag ( attribute -- value )
    pfd-flag-map at [ ] [ 0 ] if* ;

: >pfd-flags ( attributes -- flags )
    [ >pfd-flag ] [ bitor ] map-reduce
    PFD_SUPPORT_OPENGL bitor ;

: attr-value ( attributes name -- value )
    [ instance? ] curry find nip
    [ value>> ] [ 0 ] if* ;

: >pfd ( attributes -- pfd )
    [ PIXELFORMATDESCRIPTOR <struct> ] dip
    {
        [ drop PIXELFORMATDESCRIPTOR c:heap-size >>nSize ]
        [ drop 1 >>nVersion ]
        [ >pfd-flags >>dwFlags ]
        [ drop PFD_TYPE_RGBA >>iPixelType ]
        [ color-bits attr-value >>cColorBits ]
        [ red-bits attr-value >>cRedBits ]
        [ green-bits attr-value >>cGreenBits ]
        [ blue-bits attr-value >>cBlueBits ]
        [ alpha-bits attr-value >>cAlphaBits ]
        [ accum-bits attr-value >>cAccumBits ]
        [ accum-red-bits attr-value >>cAccumRedBits ]
        [ accum-green-bits attr-value >>cAccumGreenBits ]
        [ accum-blue-bits attr-value >>cAccumBlueBits ]
        [ accum-alpha-bits attr-value >>cAccumAlphaBits ]
        [ depth-bits attr-value >>cDepthBits ]
        [ stencil-bits attr-value >>cStencilBits ]
        [ aux-buffers attr-value >>cAuxBuffers ]
        [ drop PFD_MAIN_PLANE >>dwLayerMask ]
    } cleave ;

: pfd-make-pixel-format ( world attributes -- pf )
    [ handle>> hDC>> ] [ >pfd ] bi*
    ChoosePixelFormat dup win32-error=0/f ;

M: windows-ui-backend (make-pixel-format)
    over has-wglChoosePixelFormatARB?
    [ arb-make-pixel-format ] [ pfd-make-pixel-format ] if ;

M: windows-ui-backend (free-pixel-format)
    drop ;

PRIVATE>

: GET_APPCOMMAND_LPARAM ( lParam -- appCommand )
    hi-word FAPPCOMMAND_MASK lo-word bitnot bitand ; inline

: enum-clipboard ( -- seq )
    0
    [ EnumClipboardFormats win32-error dup dup 0 > ]
    [ ]
    produce 2nip ;

: with-clipboard ( quot -- )
    f OpenClipboard win32-error=0/f
    call
    CloseClipboard win32-error=0/f ; inline

: paste ( -- str )
    [
        CF_UNICODETEXT IsClipboardFormatAvailable zero? [
            ! nothing to paste
            ""
        ] [
            CF_UNICODETEXT GetClipboardData dup win32-error=0/f
            dup GlobalLock dup win32-error=0/f
            GlobalUnlock win32-error=0/f
            alien>native-string
        ] if
    ] with-clipboard
    crlf>lf ;

: copy ( str -- )
    lf>crlf [
        native-string>alien
        EmptyClipboard win32-error=0/f
        GMEM_MOVEABLE over length 1 + GlobalAlloc
            dup win32-error=0/f

        dup GlobalLock dup win32-error=0/f
        rot binary-object memcpy
        dup GlobalUnlock win32-error=0/f
        CF_UNICODETEXT swap SetClipboardData win32-error=0/f
    ] with-clipboard ;

TUPLE: pasteboard ;
C: <pasteboard> pasteboard

M: pasteboard clipboard-contents drop paste ;
M: pasteboard set-clipboard-contents drop copy ;

: init-clipboard ( -- )
    <pasteboard> clipboard set-global
    <clipboard> selection set-global ;

SYMBOLS: msg-obj class-name-ptr mouse-captured ;

CONSTANT: window-control>style
    H{
        { close-button 0 }
        { textured-background 0 }
        { minimize-button $ WS_MINIMIZEBOX }
        { maximize-button $ WS_MAXIMIZEBOX }
        { resize-handles $ WS_THICKFRAME }
        { small-title-bar $ WS_CAPTION }
        { normal-title-bar $ WS_CAPTION }
        { dialog-window 0 }
    }

CONSTANT: window-control>ex-style
    H{
        { close-button 0 }
        { textured-background 0 }
        { minimize-button 0 }
        { maximize-button 0 }
        { resize-handles $ WS_EX_WINDOWEDGE }
        { small-title-bar flags{ WS_EX_TOOLWINDOW WS_EX_TOPMOST } }
        { normal-title-bar $ WS_EX_APPWINDOW }
        { dialog-window 0 }
    }

: needs-sysmenu? ( controls -- ? )
    { close-button minimize-button maximize-button } intersects? ;

: has-titlebar? ( controls -- ? )
    { small-title-bar normal-title-bar } intersects? ;

: world>style ( world -- n )
    window-controls>>
    [ window-control>style symbols>flags ]
    [ needs-sysmenu? [ WS_SYSMENU bitor ] when ]
    [ has-titlebar? [ WS_POPUP bitor ] unless ] tri ;

: world>ex-style ( world -- n )
    window-controls>> window-control>ex-style symbols>flags ;

: get-RECT-top-left ( RECT -- x y )
    [ left>> ] [ top>> ] bi ;

: get-RECT-width/height ( RECT -- width height )
    [ [ right>> ] [ left>> ] bi - ]
    [ [ bottom>> ] [ top>> ] bi - ] bi ;

: get-RECT-dimensions ( RECT -- x y width height )
    [ get-RECT-top-left ] [ get-RECT-width/height ] bi ;

: handle-wm-paint ( hWnd uMsg wParam lParam -- )
    ! wParam and lParam are unused
    ! only paint if width/height both > 0
    3drop window t >>active? relayout-1 yield ;

: handle-wm-size ( hWnd uMsg wParam lParam -- )
    2nip
    [ lo-word ] keep hi-word 2array
    dup { 0 0 } = [ 2drop ] [ swap window [ dim<< ] [ drop ] if* ] if ;

: handle-wm-move ( hWnd uMsg wParam lParam -- )
    2nip
    [ lo-word ] keep hi-word 2array
    swap window [ window-loc<< ] [ drop ] if* ;

CONSTANT: wm-keydown-codes
    H{
        { 8 "BACKSPACE" }
        { 9 "TAB" }
        { 13 "RET" }
        { 27 "ESC" }
        { 33 "PAGE_UP" }
        { 34 "PAGE_DOWN" }
        { 35 "END" }
        { 36 "HOME" }
        { 37 "LEFT" }
        { 38 "UP" }
        { 39 "RIGHT" }
        { 40 "DOWN" }
        { 45 "INSERT" }
        { 46 "DELETE" }
        { 112 "F1" }
        { 113 "F2" }
        { 114 "F3" }
        { 115 "F4" }
        { 116 "F5" }
        { 117 "F6" }
        { 118 "F7" }
        { 119 "F8" }
        { 120 "F9" }
        { 121 "F10" }
        { 122 "F11" }
        { 123 "F12" }
    }

: key-state-down? ( key -- ? )
    GetKeyState 16 bit? ;

: left-shift? ( -- ? ) VK_LSHIFT key-state-down? ;
: left-ctrl? ( -- ? ) VK_LCONTROL key-state-down? ;
: left-alt? ( -- ? ) VK_LMENU key-state-down? ;
: right-shift? ( -- ? ) VK_RSHIFT key-state-down? ;
: right-ctrl? ( -- ? ) VK_RCONTROL key-state-down? ;
: right-alt? ( -- ? ) VK_RMENU key-state-down? ;
: shift? ( -- ? ) left-shift? right-shift? or ;
: ctrl? ( -- ? ) left-ctrl? right-ctrl? or ;
: alt? ( -- ? ) left-alt? right-alt? or ;
: caps-lock? ( -- ? ) VK_CAPITAL GetKeyState zero? not ;

: key-modifiers ( -- seq )
    [
        shift? [ S+ , ] when
        ctrl? [ C+ , ] when
        alt? [ A+ , ] when
    ] { } make [ empty? not ] keep f ? ;

CONSTANT: exclude-keys-wm-keydown
    H{
        { 16 "SHIFT" }
        { 17 "CTRL" }
        { 18 "ALT" }
        { 20 "CAPS-LOCK" }
    }

! Values are ignored
CONSTANT: exclude-keys-wm-char
    H{
        { 8 "BACKSPACE" }
        { 9 "TAB" }
        { 13 "RET" }
        { 27 "ESC" }
    }

: exclude-key-wm-keydown? ( n -- ? )
    exclude-keys-wm-keydown key? ;

: exclude-key-wm-char? ( n -- ? )
    exclude-keys-wm-char key? ;

: keystroke>gesture ( n -- mods sym )
    wm-keydown-codes at* [ key-modifiers swap ] [ drop f f ] if ;

: send-key-gesture ( sym action? quot hWnd -- )
    [ [ key-modifiers ] 3dip call ] dip
    window propagate-key-gesture ; inline

: send-key-down ( sym action? hWnd -- )
    [ [ <key-down> ] ] dip send-key-gesture ;

: send-key-up ( sym action? hWnd -- )
    [ [ <key-up> ] ] dip send-key-gesture ;

: key-sym ( wParam -- string/f )
    wm-keydown-codes at ; inline

:: (handle-wm-keydown/up) ( hWnd uMsg wParam lParam send-key-down/up -- )
    wParam exclude-key-wm-keydown? [
        wParam key-sym [
            t hWnd send-key-down/up execute( sym action? hWnd -- )
        ] [
            256 <byte-array> :> keyboard-state
            4 <byte-array> :> chars
            lParam -16 shift 0xff bitand :> scan-code
            keyboard-state GetKeyboardState win32-error=0/f
            VK_CONTROL VK_CAPITAL [ 0 swap keyboard-state set-nth ] bi@
            wParam scan-code keyboard-state chars 2 0 ToUnicode
            1 <=  [
                1 chars nth 8 shift 0 chars nth bitor
            ] [
                3 chars nth 8 shift 2 chars nth bitor ! dead-key
            ] if
            1string f hWnd send-key-down/up execute( sym action? hWnd -- )
        ] if*
    ] unless ; inline

: handle-wm-keydown ( hWnd uMsg wParam lParam -- )
    \ send-key-down (handle-wm-keydown/up) ;

SYMBOL: upper-surrogate-wm-char
{'fraction_non_alphanumeric': 0.1304328284417277, 'fraction_numerical': 0.019236819632343027, 'mean_word_length': 2.2354224225679804, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 207, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '236365', 'n_tokens_mistral': 8478, 'n_tokens_neox': 8092, 'n_words': 1706}