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