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