]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/windows/windows.factor
ui.backend.windows: support horizontal scroll wheel
[factor.git] / basis / ui / backend / windows / windows.factor
1 ! Copyright (C) 2005, 2006 Doug Coleman.
2 ! Portions copyright (C) 2007, 2010 Slava Pestov.
3 ! See https://factorcode.org/license.txt for BSD license.
4 USING: accessors alien alien.c-types alien.data alien.strings
5 arrays ascii assocs assocs.extras byte-arrays calendar classes
6 classes.struct colors combinators continuations io io.crlf
7 io.encodings.string io.encodings.utf16 io.encodings.utf8 kernel
8 libc literals make math math.bitwise namespaces sequences sets
9 specialized-arrays strings threads ui ui.backend ui.clipboards
10 ui.event-loop ui.gadgets ui.gadgets.private ui.gadgets.worlds
11 ui.gestures ui.pixel-formats ui.private windows.dwmapi
12 windows.errors windows.gdi32 windows.kernel32 windows.messages
13 windows.offscreen windows.ole32 windows.opengl32 windows.shell32
14 windows.types windows.user32 ;
15 FROM: unicode => upper-surrogate? under-surrogate? ;
16 SPECIALIZED-ARRAY: POINT
17 QUALIFIED-WITH: alien.c-types c
18 IN: ui.backend.windows
19
20 SINGLETON: windows-ui-backend
21
22 TUPLE: win-base hDC hRC ;
23 TUPLE: win < win-base hWnd world title ;
24 C: <win> win
25
26 <PRIVATE
27
28 CONSTANT: perm-attribs { $ WGL_SUPPORT_OPENGL_ARB 1 }
29
30 CONSTANT: attrib-table H{
31     { double-buffered { $ WGL_DOUBLE_BUFFER_ARB 1 } }
32     { stereo { $ WGL_STEREO_ARB 1 } }
33     { offscreen { $ WGL_DRAW_TO_BITMAP_ARB 1 } }
34     { fullscreen { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
35     { windowed { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
36     { accelerated { $ WGL_ACCELERATION_ARB $ WGL_FULL_ACCELERATION_ARB } }
37     { software-rendered { $ WGL_ACCELERATION_ARB $ WGL_NO_ACCELERATION_ARB } }
38     { backing-store { $ WGL_SWAP_METHOD_ARB $ WGL_SWAP_COPY_ARB } }
39     { color-float { $ WGL_TYPE_RGBA_FLOAT_ARB 1 } }
40     { color-bits { $ WGL_COLOR_BITS_ARB } }
41     { red-bits { $ WGL_RED_BITS_ARB } }
42     { green-bits { $ WGL_GREEN_BITS_ARB } }
43     { blue-bits { $ WGL_BLUE_BITS_ARB } }
44     { alpha-bits { $ WGL_ALPHA_BITS_ARB } }
45     { accum-bits { $ WGL_ACCUM_BITS_ARB } }
46     { accum-red-bits { $ WGL_ACCUM_RED_BITS_ARB } }
47     { accum-green-bits { $ WGL_ACCUM_GREEN_BITS_ARB } }
48     { accum-blue-bits { $ WGL_ACCUM_BLUE_BITS_ARB } }
49     { accum-alpha-bits { $ WGL_ACCUM_ALPHA_BITS_ARB } }
50     { depth-bits { $ WGL_DEPTH_BITS_ARB } }
51     { stencil-bits { $ WGL_STENCIL_BITS_ARB } }
52     { aux-buffers { $ WGL_AUX_BUFFERS_ARB } }
53     { sample-buffers { $ WGL_SAMPLE_BUFFERS_ARB } }
54     { samples { $ WGL_SAMPLES_ARB } }
55 }
56
57 : has-wglChoosePixelFormatARB? ( world -- ? )
58     drop f ;
59
60 : arb-make-pixel-format ( world attributes -- pf )
61     [ handle>> hDC>> ] dip
62     perm-attribs attrib-table pixel-format-attributes>int-array
63     f 1 { c:int c:int }
64     [ wglChoosePixelFormatARB win32-error=0/f ] with-out-parameters drop ;
65
66 CONSTANT: pfd-flag-map H{
67     { double-buffered $ PFD_DOUBLEBUFFER }
68     { stereo $ PFD_STEREO }
69     { offscreen $ PFD_DRAW_TO_BITMAP }
70     { fullscreen $ PFD_DRAW_TO_WINDOW }
71     { windowed $ PFD_DRAW_TO_WINDOW }
72     { backing-store $ PFD_SWAP_COPY }
73     { software-rendered $ PFD_GENERIC_FORMAT }
74 }
75
76 : >pfd-flag ( attribute -- value )
77     pfd-flag-map at [ ] [ 0 ] if* ;
78
79 : >pfd-flags ( attributes -- flags )
80     [ >pfd-flag ] [ bitor ] map-reduce
81     PFD_SUPPORT_OPENGL bitor ;
82
83 : attr-value ( attributes name -- value )
84     [ instance? ] curry find nip
85     [ value>> ] [ 0 ] if* ;
86
87 : >pfd ( attributes -- pfd )
88     [ PIXELFORMATDESCRIPTOR new ] dip
89     {
90         [ drop PIXELFORMATDESCRIPTOR c:heap-size >>nSize ]
91         [ drop 1 >>nVersion ]
92         [ >pfd-flags >>dwFlags ]
93         [ drop PFD_TYPE_RGBA >>iPixelType ]
94         [ color-bits attr-value >>cColorBits ]
95         [ red-bits attr-value >>cRedBits ]
96         [ green-bits attr-value >>cGreenBits ]
97         [ blue-bits attr-value >>cBlueBits ]
98         [ alpha-bits attr-value >>cAlphaBits ]
99         [ accum-bits attr-value >>cAccumBits ]
100         [ accum-red-bits attr-value >>cAccumRedBits ]
101         [ accum-green-bits attr-value >>cAccumGreenBits ]
102         [ accum-blue-bits attr-value >>cAccumBlueBits ]
103         [ accum-alpha-bits attr-value >>cAccumAlphaBits ]
104         [ depth-bits attr-value >>cDepthBits ]
105         [ stencil-bits attr-value >>cStencilBits ]
106         [ aux-buffers attr-value >>cAuxBuffers ]
107         [ drop PFD_MAIN_PLANE >>dwLayerMask ]
108     } cleave ;
109
110 : pfd-make-pixel-format ( world attributes -- pf )
111     [ handle>> hDC>> ] [ >pfd ] bi*
112     ChoosePixelFormat dup win32-error=0/f ;
113
114 M: windows-ui-backend (make-pixel-format)
115     over has-wglChoosePixelFormatARB?
116     [ arb-make-pixel-format ] [ pfd-make-pixel-format ] if ;
117
118 M: windows-ui-backend (free-pixel-format)
119     drop ;
120
121 PRIVATE>
122
123 : GET_APPCOMMAND_LPARAM ( lParam -- appCommand )
124     hi-word FAPPCOMMAND_MASK lo-word bitnot bitand ; inline
125
126 : enum-clipboard ( -- seq )
127     0
128     [ EnumClipboardFormats win32-error dup dup 0 > ]
129     [ ]
130     produce 2nip ;
131
132 : with-clipboard ( quot -- )
133     f OpenClipboard win32-error=0/f
134     call
135     CloseClipboard win32-error=0/f ; inline
136
137 : paste ( -- str )
138     [
139         CF_UNICODETEXT IsClipboardFormatAvailable zero? [
140             ! nothing to paste
141             ""
142         ] [
143             CF_UNICODETEXT GetClipboardData dup win32-error=0/f
144             dup GlobalLock dup win32-error=0/f
145             GlobalUnlock win32-error=0/f
146             alien>native-string
147         ] if
148     ] with-clipboard
149     crlf>lf ;
150
151 : copy ( str -- )
152     lf>crlf [
153         native-string>alien
154         EmptyClipboard win32-error=0/f
155         GMEM_MOVEABLE over length 1 + GlobalAlloc
156             dup win32-error=0/f
157
158         dup GlobalLock dup win32-error=0/f
159         rot binary-object memcpy
160         dup GlobalUnlock win32-error=0/f
161         CF_UNICODETEXT swap SetClipboardData win32-error=0/f
162     ] with-clipboard ;
163
164 TUPLE: pasteboard ;
165 C: <pasteboard> pasteboard
166
167 M: pasteboard clipboard-contents drop paste ;
168 M: pasteboard set-clipboard-contents drop copy ;
169
170 : init-clipboard ( -- )
171     <pasteboard> clipboard set-global
172     <clipboard> selection set-global ;
173
174 SYMBOLS: msg-obj class-name-ptr mouse-captured ;
175
176 CONSTANT: window-control>style
177     H{
178         { close-button 0 }
179         { textured-background 0 }
180         { minimize-button $ WS_MINIMIZEBOX }
181         { maximize-button $ WS_MAXIMIZEBOX }
182         { resize-handles $ WS_THICKFRAME }
183         { small-title-bar $ WS_CAPTION }
184         { normal-title-bar $ WS_CAPTION }
185         { dialog-window 0 }
186     }
187
188 CONSTANT: window-control>ex-style
189     H{
190         { close-button 0 }
191         { textured-background 0 }
192         { minimize-button 0 }
193         { maximize-button 0 }
194         { resize-handles $ WS_EX_WINDOWEDGE }
195         { small-title-bar flags{ WS_EX_TOOLWINDOW WS_EX_TOPMOST } }
196         { normal-title-bar $ WS_EX_APPWINDOW }
197         { dialog-window 0 }
198     }
199
200 : needs-sysmenu? ( controls -- ? )
201     { close-button minimize-button maximize-button } intersects? ;
202
203 : has-titlebar? ( controls -- ? )
204     { small-title-bar normal-title-bar } intersects? ;
205
206 : world>style ( world -- n )
207     window-controls>>
208     [ window-control>style symbols>flags ]
209     [ needs-sysmenu? [ WS_SYSMENU bitor ] when ]
210     [ has-titlebar? [ WS_POPUP bitor ] unless ] tri ;
211
212 : world>ex-style ( world -- n )
213     window-controls>> window-control>ex-style symbols>flags ;
214
215 : get-RECT-top-left ( RECT -- x y )
216     [ left>> ] [ top>> ] bi ;
217
218 : get-RECT-width/height ( RECT -- width height )
219     [ [ right>> ] [ left>> ] bi - ]
220     [ [ bottom>> ] [ top>> ] bi - ] bi ;
221
222 : get-RECT-dimensions ( RECT -- x y width height )
223     [ get-RECT-top-left ] [ get-RECT-width/height ] bi ;
224
225 : handle-wm-paint ( hWnd uMsg wParam lParam -- )
226     ! wParam and lParam are unused
227     ! only paint if width/height both > 0
228     3drop window t >>active? relayout-1 yield ;
229
230 : handle-wm-size ( hWnd uMsg wParam lParam -- )
231     2nip
232     [ lo-word ] keep hi-word 2array
233     dup { 0 0 } = [ 2drop ] [ swap window [ dim<< ] [ drop ] if* ] if ;
234
235 : handle-wm-move ( hWnd uMsg wParam lParam -- )
236     2nip
237     [ lo-word ] keep hi-word 2array
238     swap window [ window-loc<< ] [ drop ] if* ;
239
240 CONSTANT: wm-keydown-codes
241     H{
242         { 8 "BACKSPACE" }
243         { 9 "TAB" }
244         { 13 "RET" }
245         { 27 "ESC" }
246         { 33 "PAGE_UP" }
247         { 34 "PAGE_DOWN" }
248         { 35 "END" }
249         { 36 "HOME" }
250         { 37 "LEFT" }
251         { 38 "UP" }
252         { 39 "RIGHT" }
253         { 40 "DOWN" }
254         { 45 "INSERT" }
255         { 46 "DELETE" }
256         { 112 "F1" }
257         { 113 "F2" }
258         { 114 "F3" }
259         { 115 "F4" }
260         { 116 "F5" }
261         { 117 "F6" }
262         { 118 "F7" }
263         { 119 "F8" }
264         { 120 "F9" }
265         { 121 "F10" }
266         { 122 "F11" }
267         { 123 "F12" }
268     }
269
270 : key-state-down? ( key -- ? )
271     GetKeyState 16 bit? ;
272
273 : left-shift? ( -- ? ) VK_LSHIFT key-state-down? ;
274 : left-ctrl? ( -- ? ) VK_LCONTROL key-state-down? ;
275 : left-alt? ( -- ? ) VK_LMENU key-state-down? ;
276 : right-shift? ( -- ? ) VK_RSHIFT key-state-down? ;
277 : right-ctrl? ( -- ? ) VK_RCONTROL key-state-down? ;
278 : right-alt? ( -- ? ) VK_RMENU key-state-down? ;
279 : shift? ( -- ? ) left-shift? right-shift? or ;
280 : ctrl? ( -- ? ) left-ctrl? right-ctrl? or ;
281 : alt? ( -- ? ) left-alt? right-alt? or ;
282 : caps-lock? ( -- ? ) VK_CAPITAL GetKeyState zero? not ;
283
284 : key-modifiers ( -- seq )
285     [
286         shift? [ S+ , ] when
287         ctrl? [ C+ , ] when
288         alt? [ A+ , ] when
289     ] { } make [ empty? not ] keep f ? ;
290
291 CONSTANT: exclude-keys-wm-keydown
292     H{
293         { 16 "SHIFT" }
294         { 17 "CTRL" }
295         { 18 "ALT" }
296         { 20 "CAPS-LOCK" }
297     }
298
299 ! Values are ignored
300 CONSTANT: exclude-keys-wm-char
301     H{
302         { 8 "BACKSPACE" }
303         { 9 "TAB" }
304         { 13 "RET" }
305         { 27 "ESC" }
306     }
307
308 : exclude-key-wm-keydown? ( n -- ? )
309     exclude-keys-wm-keydown key? ;
310
311 : exclude-key-wm-char? ( n -- ? )
312     exclude-keys-wm-char key? ;
313
314 : keystroke>gesture ( n -- mods sym )
315     wm-keydown-codes at* [ key-modifiers swap ] [ drop f f ] if ;
316
317 : send-key-gesture ( sym action? quot hWnd -- )
318     [ [ key-modifiers ] 3dip call ] dip
319     window propagate-key-gesture ; inline
320
321 : send-key-down ( sym action? hWnd -- )
322     [ [ <key-down> ] ] dip send-key-gesture ;
323
324 : send-key-up ( sym action? hWnd -- )
325     [ [ <key-up> ] ] dip send-key-gesture ;
326
327 : key-sym ( wParam -- string/f )
328     wm-keydown-codes at ; inline
329
330 :: (handle-wm-keydown/up) ( hWnd uMsg wParam lParam send-key-down/up -- )
331     wParam exclude-key-wm-keydown? [
332         wParam key-sym [
333             t hWnd send-key-down/up execute( sym action? hWnd -- )
334         ] [
335             256 <byte-array> :> keyboard-state
336             4 <byte-array> :> chars
337             lParam -16 shift 0xff bitand :> scan-code
338             keyboard-state GetKeyboardState win32-error=0/f
339             VK_CONTROL VK_CAPITAL [ 0 swap keyboard-state set-nth ] bi@
340             wParam scan-code keyboard-state chars 2 0 ToUnicode
341             1 <=  [
342                 1 chars nth 8 shift 0 chars nth bitor
343             ] [
344                 3 chars nth 8 shift 2 chars nth bitor ! dead-key
345             ] if
346             1string f hWnd send-key-down/up execute( sym action? hWnd -- )
347         ] if*
348     ] unless ; inline
349
350 : handle-wm-keydown ( hWnd uMsg wParam lParam -- )
351     \ send-key-down (handle-wm-keydown/up) ;
352
353 SYMBOL: upper-surrogate-wm-char
354
355 :: handle-wm-char ( hWnd uMsg wParam lParam -- )
356     wParam exclude-key-wm-char? [
357         ctrl? alt? xor [ ! enable AltGr combination inputs
358             wParam {
359                 { [ dup upper-surrogate? ] [
360                       upper-surrogate-wm-char set-global
361                 ] }
362                 { [ dup under-surrogate? ] [
363                     drop
364                     upper-surrogate-wm-char get-global [
365                         wParam "" 2sequence
366                         utf16n encode utf16n decode hWnd window user-input
367                     ] when*
368                 ] }
369                 [ 1string hWnd window user-input
370                   f upper-surrogate-wm-char set-global ]
371             } cond
372         ] unless
373     ] unless ;
374
375 : handle-wm-keyup ( hWnd uMsg wParam lParam -- )
376     \ send-key-up (handle-wm-keydown/up) ;
377
378 :: set-window-active ( hwnd uMsg wParam lParam ? -- n )
379     ? hwnd window active?<<
380     hwnd uMsg wParam lParam DefWindowProc ;
381
382 : handle-wm-syscommand ( hWnd uMsg wParam lParam -- n )
383     {
384         { [ over SC_MINIMIZE = ] [ f set-window-active ] }
385         { [ over SC_RESTORE = ] [ t set-window-active ] }
386         { [ over SC_MAXIMIZE = ] [ t set-window-active ] }
387         { [ dup alpha? ] [ 4drop 0 ] }
388         [ DefWindowProc ]
389     } cond ;
390
391 : cleanup-window ( handle -- )
392     dup title>> [ free ] when*
393     dup hRC>> wglDeleteContext win32-error=0/f
394     dup hWnd>> swap hDC>> ReleaseDC win32-error=0/f ;
395
396 M: windows-ui-backend (close-window)
397     dup hWnd>> unregister-window
398     dup cleanup-window
399     hWnd>> DestroyWindow win32-error=0/f ;
400
401 : handle-wm-close ( hWnd uMsg wParam lParam -- )
402     3drop window ungraft ;
403
404 : handle-wm-set-focus ( hWnd uMsg wParam lParam -- )
405     3drop window [ focus-world ] when* ;
406
407 : handle-wm-kill-focus ( hWnd uMsg wParam lParam -- )
408     3drop window [ unfocus-world ] when* ;
409
410 : message>button ( uMsg -- button down? )
411     {
412         { WM_LBUTTONDOWN   [ 1 t ] }
413         { WM_LBUTTONUP     [ 1 f ] }
414         { WM_MBUTTONDOWN   [ 2 t ] }
415         { WM_MBUTTONUP     [ 2 f ] }
416         { WM_RBUTTONDOWN   [ 3 t ] }
417         { WM_RBUTTONUP     [ 3 f ] }
418
419         { WM_NCLBUTTONDOWN [ 1 t ] }
420         { WM_NCLBUTTONUP   [ 1 f ] }
421         { WM_NCMBUTTONDOWN [ 2 t ] }
422         { WM_NCMBUTTONUP   [ 2 f ] }
423         { WM_NCRBUTTONDOWN [ 3 t ] }
424         { WM_NCRBUTTONUP   [ 3 f ] }
425     } case ;
426
427 ! If the user clicks in the window border ("non-client area")
428 ! Windows sends us an NC[LMR]BUTTONDOWN message; but if the
429 ! mouse is subsequently released outside the NC area, we receive
430 ! a [LMR]BUTTONUP message and Factor can get confused. So we
431 ! ignore BUTTONUP's that are a result of an NC*BUTTONDOWN.
432 SYMBOL: nc-buttons
433
434 : handle-wm-ncbutton ( hWnd uMsg wParam lParam -- )
435     2drop nip
436     message>button nc-buttons get
437     swap [ push ] [ remove! drop ] if ;
438
439 : mouse-scroll ( wParam -- array )
440     >lo-hi [ -80 /f ] map ;
441
442 : mouse-horizontal-scroll ( wParam -- direction )
443     hi-word 80 /f 0 2array ;
444
445 : mouse-event>gesture ( uMsg -- button )
446     key-modifiers swap message>button
447     [ <button-down> ] [ <button-up> ] if ;
448
449 :: prepare-mouse ( hWnd uMsg wParam lParam -- button coordinate world )
450     uMsg mouse-event>gesture
451     lParam >lo-hi
452     hWnd window ;
453
454 : set-capture ( hwnd -- )
455     mouse-captured get [
456         drop
457     ] [
458         [ SetCapture drop ] keep
459         mouse-captured namespaces:set
460     ] if ;
461
462 : release-capture ( -- )
463     ReleaseCapture win32-error=0/f
464     mouse-captured off ;
465
466 : handle-app-command ( hWnd uMsg wParam lParam -- )
467     GET_APPCOMMAND_LPARAM
468     {
469         { APPCOMMAND_BROWSER_BACKWARD [ pick window left-action send-action ] }
470         { APPCOMMAND_BROWSER_FORWARD [ pick window right-action send-action ] }
471         [ drop ]
472     } case 3drop ;
473
474 : handle-wm-buttondown ( hWnd uMsg wParam lParam -- )
475     [
476         over set-capture
477         dup message>button drop nc-buttons get remove! drop
478     ] 2dip prepare-mouse send-button-down ;
479
480 : handle-wm-buttonup ( hWnd uMsg wParam lParam -- )
481     mouse-captured get [ release-capture ] when
482     pick message>button drop dup nc-buttons get member? [
483         nc-buttons get remove! 5drop
484     ] [
485         drop prepare-mouse send-button-up
486     ] if ;
487
488 : make-TRACKMOUSEEVENT ( hWnd -- alien )
489     TRACKMOUSEEVENT new
490         swap >>hwndTrack
491         TRACKMOUSEEVENT c:heap-size >>cbSize ;
492
493 : handle-wm-mousemove ( hWnd uMsg wParam lParam -- )
494     2nip
495     over make-TRACKMOUSEEVENT
496         TME_LEAVE >>dwFlags
497         0 >>dwHoverTime
498     TrackMouseEvent win32-error=0/f
499     >lo-hi swap window move-hand fire-motion ;
500
501 : (handle-mousewheel) ( direction hWnd -- )
502     hand-loc get-global swap window send-scroll ; inline
503
504 :: handle-wm-mousewheel ( hWnd uMsg wParam lParam -- )
505     wParam mouse-scroll hWnd (handle-mousewheel) ;
506
507 :: handle-wm-mousehwheel ( hWnd uMsg wParam lParam -- )
508     wParam mouse-horizontal-scroll hWnd (handle-mousewheel) ;
509
510 : handle-wm-cancelmode ( hWnd uMsg wParam lParam -- )
511     ! message sent if windows needs application to stop dragging
512     4drop release-capture ;
513
514 : handle-wm-mouseleave ( hWnd uMsg wParam lParam -- )
515     ! message sent if mouse leaves main application
516     4drop forget-rollover ;
517
518 : system-background-color ( -- color )
519     COLOR_BTNFACE GetSysColor RGB>color ;
520
521 : ?make-glass ( world hwnd -- )
522     over window-controls>> textured-background swap member-eq? [
523         composition-enabled? [
524             full-window-margins DwmExtendFrameIntoClientArea check-hresult
525             T{ rgba f 0.0 0.0 0.0 0.0 }
526         ] [ drop system-background-color ] if >>background-color
527         drop
528     ] [ 2drop ] if ;
529
530 : handle-wm-dwmcompositionchanged ( hWnd uMsg wParam lParam -- )
531     3drop [ window ] keep ?make-glass ;
532
533 SYMBOL: wm-handlers
534
535 : add-wm-handler ( quot: ( hWnd Msg wParam lParam -- LRESULT ) wm -- )
536     dup array?
537     [ [ execute( -- wm ) add-wm-handler ] with each ]
538     [ wm-handlers get-global set-at ] if ;
539
540 : remove-wm-handler ( wm -- )
541     wm-handlers get-global delete-at ;
542
543 wm-handlers [
544     H{
545         ${ WM_CLOSE [ handle-wm-close 0 ] }
546         ! ${ WM_NCCREATE [ [ 3drop EnableNonClientDpiScaling drop ] [ DefWindowProc ] 4bi ] }
547         ! ${ WM_GETDPISCALEDSIZE [ DefWindowProc ] }
548         ! ${ WM_DPICHANGED [ DefWindowProc ] }
549         ${ WM_PAINT [ 4dup handle-wm-paint DefWindowProc ] }
550
551         ${ WM_SIZE [ handle-wm-size 0 ] }
552         ${ WM_MOVE [ handle-wm-move 0 ] }
553
554         { ${ WM_CHAR WM_SYSCHAR } [ 4dup handle-wm-char DefWindowProc ] }
555         { ${ WM_KEYDOWN WM_SYSKEYDOWN } [ 4dup handle-wm-keydown DefWindowProc ] }
556         { ${ WM_KEYUP WM_SYSKEYUP } [ 4dup handle-wm-keyup DefWindowProc ] }
557
558         ${ WM_SYSCOMMAND [ handle-wm-syscommand ] }
559         ${ WM_SETFOCUS [ handle-wm-set-focus 0 ]  }
560         ${ WM_KILLFOCUS [ handle-wm-kill-focus 0 ] }
561
562         ${ WM_APPCOMMAND [ handle-app-command 0 ] }
563
564         { ${ WM_LBUTTONDOWN WM_MBUTTONDOWN WM_RBUTTONDOWN } [ handle-wm-buttondown 0 ] }
565         { ${ WM_LBUTTONUP WM_MBUTTONUP WM_RBUTTONUP } [ handle-wm-buttonup 0 ] }
566         ${ WM_DWMCOMPOSITIONCHANGED [ handle-wm-dwmcompositionchanged 0 ] }
567
568         {
569             ${
570                 WM_NCLBUTTONDOWN WM_NCMBUTTONDOWN WM_NCRBUTTONDOWN
571                 WM_NCLBUTTONUP WM_NCMBUTTONUP WM_NCRBUTTONUP
572             } [ 4dup handle-wm-ncbutton DefWindowProc ]
573         }
574
575         { ${ WM_EXITMENULOOP WM_EXITSIZEMOVE } [ nc-buttons get-global delete-all DefWindowProc ] }
576
577         ${ WM_MOUSEMOVE [ handle-wm-mousemove 0 ] }
578         ${ WM_MOUSEWHEEL [ handle-wm-mousewheel 0 ] }
579         ${ WM_MOUSEHWHEEL [ handle-wm-mousehwheel 0 ] }
580         ${ WM_CANCELMODE [ handle-wm-cancelmode 0 ] }
581         ${ WM_MOUSELEAVE [ handle-wm-mouseleave 0 ] }
582     } expand-keys-set-at
583 ] initialize
584
585 SYMBOL: trace-messages?
586
587 ! return 0 if you handle the message, else just let DefWindowProc return its val
588 : ui-wndproc ( -- object )
589     c:uint { c:void* c:uint WPARAM LPARAM } stdcall [
590         pick wm-handlers get-global at*
591         [ flush call( hWnd Msg wParam lParam -- result ) ] [ drop DefWindowProc ] if
592     ] alien-callback ;
593
594 : peek-message? ( msg -- ? ) f 0 0 PM_REMOVE PeekMessage zero? ;
595
596 M: windows-ui-backend do-events
597     msg-obj get-global
598     dup peek-message? [ drop ui-wait ] [
599         [ TranslateMessage drop ]
600         [ DispatchMessage drop ] bi
601     ] if ;
602
603 :: register-window-class ( class-name-ptr -- )
604     WNDCLASSEX new f GetModuleHandle
605     class-name-ptr pick GetClassInfoEx 0 = [
606         WNDCLASSEX c:heap-size >>cbSize
607         flags{ CS_HREDRAW CS_VREDRAW CS_OWNDC } >>style
608         ui-wndproc >>lpfnWndProc
609         0 >>cbClsExtra
610         0 >>cbWndExtra
611         f GetModuleHandle >>hInstance
612         f GetModuleHandle "APPICON" native-string>alien LoadIcon >>hIcon
613         f IDC_ARROW MAKEINTRESOURCE LoadCursor >>hCursor
614
615         class-name-ptr >>lpszClassName
616         RegisterClassEx win32-error=0/f
617     ] [ drop ] if ;
618
619 : adjust-RECT ( RECT style ex-style -- )
620     ! [ 0 ] dip GetDpiForSystem AdjustWindowRectExForDpi win32-error=0/f ;
621     [ 0 ] dip AdjustWindowRectEx win32-error=0/f ;
622
623 : make-RECT ( world -- RECT )
624     [ window-loc>> ] [ dim>> ] bi <RECT> ;
625
626 : default-position-RECT ( RECT -- RECT' )
627     dup get-RECT-width/height
628         [ CW_USEDEFAULT + >>right ] dip
629         CW_USEDEFAULT + >>bottom
630         CW_USEDEFAULT >>left
631         CW_USEDEFAULT >>top ;
632
633 : make-adjusted-RECT ( rect style ex-style -- RECT )
634     [
635         make-RECT
636         dup get-RECT-top-left [ zero? ] both? swap
637         dup
638     ] 2dip adjust-RECT
639     swap [ default-position-RECT ] when ;
640
641 : get-window-class ( -- class-name )
642     class-name-ptr [
643         dup expired? [ drop "Factor-window" utf16n malloc-string ] when
644         dup register-window-class
645         dup
646     ] change-global ;
647
648 : get-device-caps ( handle -- x y )
649     GetDC
650     [ LOGPIXELSX GetDeviceCaps ]
651     [ LOGPIXELSY GetDeviceCaps ] bi ;
652
653 : get-default-device-caps ( -- x y )
654     f get-device-caps ;
655
656 :: create-window ( rect style ex-style -- hwnd )
657     rect style ex-style make-adjusted-RECT
658     [ get-window-class f ] dip
659     [
660         [ ex-style ] 2dip
661         flags{ WS_CLIPSIBLINGS WS_CLIPCHILDREN } style bitor
662     ] dip get-RECT-dimensions
663     f f f GetModuleHandle f CreateWindowEx dup win32-error=0/f ;
664
665 : show-window ( hWnd -- )
666     dup SW_SHOW ShowWindow drop ! always succeeds
667     dup SetForegroundWindow drop
668     SetFocus drop ;
669
670 : init-win32-ui ( -- )
671     V{ } clone nc-buttons set-global
672     MSG malloc-struct msg-obj set-global
673     GetDoubleClickTime milliseconds double-click-timeout set-global ;
674
675 : cleanup-win32-ui ( -- )
676     class-name-ptr [ [ [ f UnregisterClass drop ] [ free ] bi ] when* f ] change-global
677     msg-obj [ [ free ] when* f ] change-global ;
678
679 : get-dc ( world -- )
680     handle>> dup hWnd>> GetDC dup win32-error=0/f >>hDC drop ;
681
682 : get-rc ( world -- )
683     handle>> dup hDC>> dup wglCreateContext dup win32-error=0/f
684     [ wglMakeCurrent win32-error=0/f ] keep >>hRC drop ;
685
686 : set-pixel-format ( pixel-format hdc -- )
687     swap handle>>
688     PIXELFORMATDESCRIPTOR new SetPixelFormat win32-error=0/f ;
689
690 : setup-gl ( world -- )
691     [ get-dc ] keep
692     [ swap [ handle>> hDC>> set-pixel-format ] [ get-rc ] bi ]
693     with-world-pixel-format ;
694
695 : disable-close-button ( hwnd -- )
696     0 GetSystemMenu
697     SC_CLOSE MF_BYCOMMAND MF_GRAYED bitor EnableMenuItem drop ;
698
699 : ?disable-close-button ( world hwnd -- )
700     swap window-controls>> close-button swap member? not
701     [ disable-close-button ] [ drop ] if ;
702
703 M: windows-ui-backend (open-window)
704     [
705         dup
706         [ ] [ world>style ] [ world>ex-style ] tri create-window
707         [ ?make-glass ]
708         [ ?disable-close-button ]
709         [ [ f f ] dip f f <win> >>handle setup-gl ] 2tri
710     ]
711     [ dup handle>> hWnd>> register-window ]
712     [ handle>> hWnd>> show-window ] tri ;
713
714 ! https://github.com/factor/factor/issues/2173
715 ! ignore timeout (error 258)
716 M: win-base select-gl-context
717     [ hDC>> ] [ hRC>> ] bi wglMakeCurrent win32-error=0/f-ignore-timeout
718     GdiFlush win32-error=0/f ;
719
720 M: win-base flush-gl-context
721     hDC>> SwapBuffers win32-error=0/f ;
722
723 ! Windows 32-bit bitmaps don't actually use the alpha byte of
724 ! each pixel; it's left as zero
725
726 : (make-opaque) ( byte-array -- byte-array' )
727     [ length 4 /i ]
728     [ '[ 255 swap 4 * 3 + _ set-nth ] each ]
729     [ ] tri ;
730
731 : (opaque-pixels) ( world -- pixels )
732     [ handle>> bits>> ] [ dim>> ] bi bitmap>byte-array (make-opaque) ;
733
734 M: windows-ui-backend raise-window*
735     handle>> [ hWnd>> SetFocus drop ] when* ;
736
737 M: windows-ui-backend set-title
738     handle>>
739     dup title>> [ free ] when*
740     swap utf16n malloc-string
741     [ >>title ]
742     [ [ hWnd>> WM_SETTEXT 0 ] dip alien-address SendMessage drop ] bi ;
743
744 M: windows-ui-backend (with-ui)
745     [
746         init-clipboard
747         init-win32-ui
748         start-ui
749         event-loop
750     ] [ cleanup-win32-ui ] finally ;
751
752 M: windows-ui-backend beep
753     0 MessageBeep drop ;
754
755 M: windows-ui-backend system-alert
756     [ f ] 2dip swap MB_OK MessageBox drop ;
757
758 : fullscreen-RECT ( hwnd -- RECT )
759     MONITOR_DEFAULTTONEAREST MonitorFromWindow
760     MONITORINFOEX new
761         MONITORINFOEX c:heap-size >>cbSize
762     [ GetMonitorInfo win32-error=0/f ] keep rcMonitor>> ;
763
764 : client-area>RECT ( hwnd -- RECT )
765     RECT new
766     [ GetClientRect win32-error=0/f ]
767     [ >c-ptr POINT cast-array [ ClientToScreen drop ] with each ]
768     [ nip ] 2tri ;
769
770 : hwnd>RECT ( hwnd -- RECT )
771     RECT new [ GetWindowRect win32-error=0/f ] keep ;
772
773 M: windows-ui-backend (grab-input)
774     0 ShowCursor drop
775     hWnd>> client-area>RECT ClipCursor drop ;
776
777 M: windows-ui-backend (ungrab-input)
778     drop
779     f ClipCursor drop
780     1 ShowCursor drop ;
781
782 CONSTANT: fullscreen-flags flags{ WS_CAPTION WS_BORDER WS_THICKFRAME }
783
784 : enter-fullscreen ( world -- )
785     handle>> hWnd>>
786     {
787         [
788             GWL_STYLE GetWindowLong
789             fullscreen-flags unmask
790         ]
791         [ GWL_STYLE rot SetWindowLong win32-error=0/f ]
792         [
793             HWND_TOP
794             over hwnd>RECT get-RECT-dimensions
795             SWP_FRAMECHANGED
796             SetWindowPos win32-error=0/f
797         ]
798         [ SW_MAXIMIZE ShowWindow win32-error=0/f ]
799     } cleave ;
800
801 : exit-fullscreen ( world -- )
802     [ handle>> hWnd>> ] [ world>style ] bi
803     {
804         [ [ GWL_STYLE ] dip SetWindowLong win32-error=0/f ]
805         [
806             drop
807             f
808             over hwnd>RECT get-RECT-dimensions
809             flags{ SWP_NOMOVE SWP_NOSIZE SWP_NOZORDER SWP_FRAMECHANGED }
810             SetWindowPos win32-error=0/f
811         ]
812         [ drop SW_RESTORE ShowWindow win32-error=0/f ]
813     } 2cleave ;
814
815 : ensure-null-terminated ( str -- str' )
816     dup ?last 0 = [ "\0" append ] unless ; inline
817
818 : add-tray-icon ( title -- )
819     NIM_ADD
820     NOTIFYICONDATA new
821         NOTIFYICONDATA heap-size >>cbSize
822         NOTIFYICON_VERSION_4 over timeout-version>> uVersion<<
823         NIF_TIP NIF_ICON bitor >>uFlags
824         world get handle>> hWnd>> >>hWnd
825         f GetModuleHandle "APPICON" native-string>alien LoadIcon >>hIcon
826         rot ensure-null-terminated utf8 encode >>szTip
827         Shell_NotifyIcon win32-error=0/f ;
828
829 : remove-tray-icon ( -- )
830     NIM_DELETE
831     NOTIFYICONDATA new
832         NOTIFYICONDATA heap-size >>cbSize
833         world get handle>> hWnd>> >>hWnd
834     Shell_NotifyIcon win32-error=0/f ;
835
836 M: windows-ui-backend (set-fullscreen)
837     [ enter-fullscreen ] [ exit-fullscreen ] if ;
838
839 M: windows-ui-backend (fullscreen?)
840     handle>> [
841         hWnd>>
842         [ hwnd>RECT ] [ fullscreen-RECT ] bi
843         [ get-RECT-dimensions 2array 2nip ] same?
844     ] [
845         [ "windows-ui-backend no hWnd" print ] with-global
846         f
847     ] if* ;
848
849 M:: windows-ui-backend resize-window ( world dim -- )
850     world handle>> hWnd>>
851     world window-loc>> dim <RECT> dup
852     world world>style
853     world world>ex-style
854     adjust-RECT get-RECT-dimensions FALSE
855     MoveWindow win32-error=0/f ;
856
857 M: windows-ui-backend ui-backend-available?
858     t ;
859
860 windows-ui-backend ui-backend set-global