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