]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/windows/windows.factor
Updating code to use with-out-parameters
[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.c-types 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 windows.kernel32
9 windows.gdi32 windows.user32 windows.opengl32 windows.messages
10 windows.types windows.offscreen windows.nt threads libc combinators
11 fry combinators.short-circuit continuations command-line shuffle
12 opengl ui.render math.bitwise locals accessors math.rectangles
13 math.order calendar ascii sets io.encodings.utf16n
14 windows.errors literals ui.pixel-formats
15 ui.pixel-formats.private memoize classes colors
16 specialized-arrays classes.struct alien.data ;
17 FROM: namespaces => set ;
18 SPECIALIZED-ARRAY: POINT
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 { int 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 <int> { 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 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 heap-size
125     PIXELFORMATDESCRIPTOR <struct>
126     [ DescribePixelFormat win32-error=0/f ] keep ;
127
128 : pfd-flag? ( pfd flag -- ? )
129     [ dwFlags>> ] dip bitand 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 : lo-word ( wparam -- lo ) <short> *short ; inline
172 : hi-word ( wparam -- hi ) -16 shift lo-word ; inline
173 : >lo-hi ( WORD -- array ) [ lo-word ] [ hi-word ] bi 2array ;
174 : GET_APPCOMMAND_LPARAM ( lParam -- appCommand )
175     hi-word FAPPCOMMAND_MASK lo-word bitnot bitand ; inline
176
177 : crlf>lf ( str -- str' )
178     CHAR: \r swap remove ;
179
180 : lf>crlf ( str -- str' )
181     [ [ dup CHAR: \n = [ CHAR: \r , ] when , ] each ] "" make ;
182
183 : enum-clipboard ( -- seq )
184     0
185     [ EnumClipboardFormats win32-error dup dup 0 > ]
186     [ ]
187     produce 2nip ;
188
189 : with-clipboard ( quot -- )
190     f OpenClipboard win32-error=0/f
191     call
192     CloseClipboard win32-error=0/f ; inline
193
194 : paste ( -- str )
195     [
196         CF_UNICODETEXT IsClipboardFormatAvailable zero? [
197             ! nothing to paste
198             ""
199         ] [
200             CF_UNICODETEXT GetClipboardData dup win32-error=0/f
201             dup GlobalLock dup win32-error=0/f
202             GlobalUnlock win32-error=0/f
203             utf16n alien>string
204         ] if
205     ] with-clipboard
206     crlf>lf ;
207
208 : copy ( str -- )
209     lf>crlf [
210         utf16n string>alien
211         EmptyClipboard win32-error=0/f
212         GMEM_MOVEABLE over length 1 + GlobalAlloc
213             dup win32-error=0/f
214     
215         dup GlobalLock dup win32-error=0/f
216         rot binary-object memcpy
217         dup GlobalUnlock win32-error=0/f
218         CF_UNICODETEXT swap SetClipboardData win32-error=0/f
219     ] with-clipboard ;
220
221 TUPLE: pasteboard ;
222 C: <pasteboard> pasteboard
223
224 M: pasteboard clipboard-contents drop paste ;
225 M: pasteboard set-clipboard-contents drop copy ;
226
227 : init-clipboard ( -- )
228     <pasteboard> clipboard set-global
229     <clipboard> selection set-global ;
230
231 SYMBOLS: msg-obj class-name-ptr mouse-captured ;
232
233 CONSTANT: window-control>style
234     H{
235         { close-button 0 }
236         { textured-background 0 }
237         { minimize-button $ WS_MINIMIZEBOX }
238         { maximize-button $ WS_MAXIMIZEBOX }
239         { resize-handles $ WS_THICKFRAME }
240         { small-title-bar $ WS_CAPTION }
241         { normal-title-bar $ WS_CAPTION }
242     }
243
244 CONSTANT: window-control>ex-style
245     H{
246         { close-button 0 }
247         { textured-background 0 }
248         { minimize-button 0 }
249         { maximize-button 0 }
250         { resize-handles $ WS_EX_WINDOWEDGE }
251         { small-title-bar $ WS_EX_TOOLWINDOW }
252         { normal-title-bar $ WS_EX_APPWINDOW }
253     }
254
255 : needs-sysmenu? ( controls -- ? )
256     { close-button minimize-button maximize-button } intersects? ;
257
258 : has-titlebar? ( controls -- ? )
259     { small-title-bar normal-title-bar } intersects? ;
260
261 : world>style ( world -- n )
262     window-controls>>
263     [ window-control>style symbols>flags ]
264     [ needs-sysmenu? [ WS_SYSMENU bitor ] when ]
265     [ has-titlebar? [ WS_POPUP bitor ] unless ] tri ;
266
267 : world>ex-style ( world -- n )
268     window-controls>> window-control>ex-style symbols>flags ;
269
270 : get-RECT-top-left ( RECT -- x y )
271     [ left>> ] [ top>> ] bi ;
272
273 : get-RECT-width/height ( RECT -- width height )
274     [ [ right>> ] [ left>> ] bi - ]
275     [ [ bottom>> ] [ top>> ] bi - ] bi ;
276
277 : get-RECT-dimensions ( RECT -- x y width height )
278     [ get-RECT-top-left ] [ get-RECT-width/height ] bi ;
279
280 : handle-wm-paint ( hWnd uMsg wParam lParam -- )
281     #! wParam and lParam are unused
282     #! only paint if width/height both > 0
283     3drop window relayout-1 yield ;
284
285 : handle-wm-size ( hWnd uMsg wParam lParam -- )
286     2nip
287     [ lo-word ] keep hi-word 2array
288     dup { 0 0 } = [ 2drop ] [ swap window [ dim<< ] [ drop ] if* ] if ;
289
290 : handle-wm-move ( hWnd uMsg wParam lParam -- )
291     2nip
292     [ lo-word ] keep hi-word 2array
293     swap window [ window-loc<< ] [ drop ] if* ;
294
295 CONSTANT: wm-keydown-codes
296     H{
297         { 8 "BACKSPACE" }
298         { 9 "TAB" }
299         { 13 "RET" }
300         { 27 "ESC" }
301         { 33 "PAGE_UP" }
302         { 34 "PAGE_DOWN" }
303         { 35 "END" }
304         { 36 "HOME" }
305         { 37 "LEFT" }
306         { 38 "UP" }
307         { 39 "RIGHT" }
308         { 40 "DOWN" }
309         { 45 "INSERT" }
310         { 46 "DELETE" }
311         { 112 "F1" }
312         { 113 "F2" }
313         { 114 "F3" }
314         { 115 "F4" }
315         { 116 "F5" }
316         { 117 "F6" }
317         { 118 "F7" }
318         { 119 "F8" }
319         { 120 "F9" }
320         { 121 "F10" }
321         { 122 "F11" }
322         { 123 "F12" }
323     }
324
325 : key-state-down? ( key -- ? )
326     GetKeyState 16 bit? ;
327
328 : left-shift? ( -- ? ) VK_LSHIFT key-state-down? ;
329 : left-ctrl? ( -- ? ) VK_LCONTROL key-state-down? ;
330 : left-alt? ( -- ? ) VK_LMENU key-state-down? ;
331 : right-shift? ( -- ? ) VK_RSHIFT key-state-down? ;
332 : right-ctrl? ( -- ? ) VK_RCONTROL key-state-down? ;
333 : right-alt? ( -- ? ) VK_RMENU key-state-down? ;
334 : shift? ( -- ? ) left-shift? right-shift? or ;
335 : ctrl? ( -- ? ) left-ctrl? right-ctrl? or ;
336 : alt? ( -- ? ) left-alt? right-alt? or ;
337 : caps-lock? ( -- ? ) VK_CAPITAL GetKeyState zero? not ;
338
339 : key-modifiers ( -- seq )
340     [
341         shift? [ S+ , ] when
342         ctrl? [ C+ , ] when
343         alt? [ A+ , ] when
344     ] { } make [ empty? not ] keep f ? ;
345
346 CONSTANT: exclude-keys-wm-keydown
347     H{
348         { 16 "SHIFT" }
349         { 17 "CTRL" }
350         { 18 "ALT" }
351         { 20 "CAPS-LOCK" }
352     }
353
354 ! Values are ignored
355 CONSTANT: exclude-keys-wm-char
356     H{
357         { 8 "BACKSPACE" }
358         { 9 "TAB" }
359         { 13 "RET" }
360         { 27 "ESC" }
361     }
362
363 : exclude-key-wm-keydown? ( n -- ? )
364     exclude-keys-wm-keydown key? ;
365
366 : exclude-key-wm-char? ( n -- ? )
367     exclude-keys-wm-char key? ;
368
369 : keystroke>gesture ( n -- mods sym )
370     wm-keydown-codes at* [ key-modifiers swap ] [ drop f f ] if ;
371
372 : send-key-gesture ( sym action? quot hWnd -- )
373     [ [ key-modifiers ] 3dip call ] dip
374     window propagate-key-gesture ; inline
375
376 : send-key-down ( sym action? hWnd -- )
377     [ [ <key-down> ] ] dip send-key-gesture ;
378
379 : send-key-up ( sym action? hWnd -- )
380     [ [ <key-up> ] ] dip send-key-gesture ;
381
382 : key-sym ( wParam -- string/f action? )
383     {
384         {
385             [ dup LETTER? ]
386             [ shift? caps-lock? xor [ CHAR: a + CHAR: A - ] unless 1string f ]
387         }
388         { [ dup digit? ] [ 1string f ] }
389         [ wm-keydown-codes at t ]
390     } cond ;
391
392 :: handle-wm-keydown ( hWnd uMsg wParam lParam -- )
393     wParam exclude-key-wm-keydown? [
394         wParam key-sym over [
395             dup ctrl? alt? xor or [
396                 hWnd send-key-down
397             ] [ 2drop ] if
398         ] [ 2drop ] if
399     ] unless ;
400
401 :: handle-wm-char ( hWnd uMsg wParam lParam -- )
402     wParam exclude-key-wm-char? [
403         ctrl? alt? xor [
404             wParam 1string
405             [ f hWnd send-key-down ]
406             [ hWnd window user-input ] bi
407         ] unless
408     ] unless ;
409
410 :: handle-wm-keyup ( hWnd uMsg wParam lParam -- )
411     wParam exclude-key-wm-keydown? [
412         wParam key-sym over [
413             hWnd send-key-up
414         ] [ 2drop ] if
415     ] unless ;
416
417 :: set-window-active ( hwnd uMsg wParam lParam ? -- n )
418     ? hwnd window active?<<
419     hwnd uMsg wParam lParam DefWindowProc ;
420
421 : handle-wm-syscommand ( hWnd uMsg wParam lParam -- n )
422     {
423         { [ over SC_MINIMIZE = ] [ f set-window-active ] }
424         { [ over SC_RESTORE = ] [ t set-window-active ] }
425         { [ over SC_MAXIMIZE = ] [ t set-window-active ] }
426         { [ dup alpha? ] [ 4drop 0 ] }
427         { [ t ] [ DefWindowProc ] }
428     } cond ;
429
430 : cleanup-window ( handle -- )
431     dup title>> [ free ] when*
432     dup hRC>> wglDeleteContext win32-error=0/f
433     dup hWnd>> swap hDC>> ReleaseDC win32-error=0/f ;
434
435 M: windows-ui-backend (close-window)
436     dup hWnd>> unregister-window
437     dup cleanup-window
438     hWnd>> DestroyWindow win32-error=0/f ;
439
440 : handle-wm-close ( hWnd uMsg wParam lParam -- )
441     3drop window ungraft ;
442
443 : handle-wm-set-focus ( hWnd uMsg wParam lParam -- )
444     3drop window [ focus-world ] when* ;
445
446 : handle-wm-kill-focus ( hWnd uMsg wParam lParam -- )
447     3drop window [ unfocus-world ] when* ;
448
449 : message>button ( uMsg -- button down? )
450     {
451         { WM_LBUTTONDOWN   [ 1 t ] }
452         { WM_LBUTTONUP     [ 1 f ] }
453         { WM_MBUTTONDOWN   [ 2 t ] }
454         { WM_MBUTTONUP     [ 2 f ] }
455         { WM_RBUTTONDOWN   [ 3 t ] }
456         { WM_RBUTTONUP     [ 3 f ] }
457
458         { WM_NCLBUTTONDOWN [ 1 t ] }
459         { WM_NCLBUTTONUP   [ 1 f ] }
460         { WM_NCMBUTTONDOWN [ 2 t ] }
461         { WM_NCMBUTTONUP   [ 2 f ] }
462         { WM_NCRBUTTONDOWN [ 3 t ] }
463         { WM_NCRBUTTONUP   [ 3 f ] }
464     } case ;
465
466 ! If the user clicks in the window border ("non-client area")
467 ! Windows sends us an NC[LMR]BUTTONDOWN message; but if the
468 ! mouse is subsequently released outside the NC area, we receive
469 ! a [LMR]BUTTONUP message and Factor can get confused. So we
470 ! ignore BUTTONUP's that are a result of an NC*BUTTONDOWN.
471 SYMBOL: nc-buttons
472
473 : handle-wm-ncbutton ( hWnd uMsg wParam lParam -- )
474     2drop nip
475     message>button nc-buttons get
476     swap [ push ] [ remove! drop ] if ;
477
478 : mouse-scroll ( wParam -- array )
479     >lo-hi [ -80 /f ] map ;
480
481 : mouse-event>gesture ( uMsg -- button )
482     key-modifiers swap message>button
483     [ <button-down> ] [ <button-up> ] if ;
484
485 :: prepare-mouse ( hWnd uMsg wParam lParam -- button coordinate world )
486     uMsg mouse-event>gesture
487     lParam >lo-hi
488     hWnd window ;
489
490 : set-capture ( hwnd -- )
491     mouse-captured get [
492         drop
493     ] [
494         [ SetCapture drop ] keep
495         mouse-captured set
496     ] if ;
497
498 : release-capture ( -- )
499     ReleaseCapture win32-error=0/f
500     mouse-captured off ;
501
502 : handle-app-command ( hWnd uMsg wParam lParam -- )
503     GET_APPCOMMAND_LPARAM
504     {
505         { APPCOMMAND_BROWSER_BACKWARD [ pick window left-action send-action ] }
506         { APPCOMMAND_BROWSER_FORWARD [ pick window right-action send-action ] }
507         [ drop ]
508     } case 3drop ;
509     
510 : handle-wm-buttondown ( hWnd uMsg wParam lParam -- )
511     [
512         over set-capture
513         dup message>button drop nc-buttons get remove! drop
514     ] 2dip prepare-mouse send-button-down ;
515
516 : handle-wm-buttonup ( hWnd uMsg wParam lParam -- )
517     mouse-captured get [ release-capture ] when
518     pick message>button drop dup nc-buttons get member? [
519         nc-buttons get remove! drop 4drop
520     ] [
521         drop prepare-mouse send-button-up
522     ] if ;
523
524 : make-TRACKMOUSEEVENT ( hWnd -- alien )
525     TRACKMOUSEEVENT <struct>
526         swap >>hwndTrack
527         TRACKMOUSEEVENT heap-size >>cbSize ;
528
529 : handle-wm-mousemove ( hWnd uMsg wParam lParam -- )
530     2nip
531     over make-TRACKMOUSEEVENT
532         TME_LEAVE >>dwFlags
533         0 >>dwHoverTime
534     TrackMouseEvent drop
535     >lo-hi swap window move-hand fire-motion ;
536
537 :: handle-wm-mousewheel ( hWnd uMsg wParam lParam -- )
538     wParam mouse-scroll hand-loc get hWnd window send-scroll ;
539
540 : handle-wm-cancelmode ( hWnd uMsg wParam lParam -- )
541     #! message sent if windows needs application to stop dragging
542     4drop release-capture ;
543
544 : handle-wm-mouseleave ( hWnd uMsg wParam lParam -- )
545     #! message sent if mouse leaves main application 
546     4drop forget-rollover ;
547
548 : system-background-color ( -- color )
549     COLOR_BTNFACE GetSysColor RGB>color ;
550
551 : ?make-glass ( world hwnd -- )
552     over window-controls>> textured-background swap member-eq? [
553         composition-enabled? [
554             full-window-margins DwmExtendFrameIntoClientArea drop
555             T{ rgba f 0.0 0.0 0.0 0.0 }
556         ] [ drop system-background-color ] if >>background-color
557         drop
558     ] [ 2drop ] if ;
559
560 : handle-wm-dwmcompositionchanged ( hWnd uMsg wParam lParam -- )
561     3drop [ window ] keep ?make-glass ;
562
563 SYMBOL: wm-handlers
564
565 H{ } clone wm-handlers set-global
566
567 : add-wm-handler ( quot wm -- )
568     dup array?
569     [ [ execute( -- wm ) add-wm-handler ] with each ]
570     [ wm-handlers get-global set-at ] if ;
571
572 [ handle-wm-close 0                  ] WM_CLOSE add-wm-handler
573 [ 4dup handle-wm-paint DefWindowProc ] WM_PAINT add-wm-handler
574
575 [ handle-wm-size 0 ] WM_SIZE add-wm-handler
576 [ handle-wm-move 0 ] WM_MOVE add-wm-handler
577
578 [ 4dup handle-wm-keydown DefWindowProc ] { WM_KEYDOWN WM_SYSKEYDOWN } add-wm-handler
579 [ 4dup handle-wm-char DefWindowProc    ] { WM_CHAR WM_SYSCHAR }       add-wm-handler
580 [ 4dup handle-wm-keyup DefWindowProc   ] { WM_KEYUP WM_SYSKEYUP }     add-wm-handler
581
582 [ handle-wm-syscommand   ] WM_SYSCOMMAND add-wm-handler
583 [ handle-wm-set-focus 0  ] WM_SETFOCUS add-wm-handler
584 [ handle-wm-kill-focus 0 ] WM_KILLFOCUS add-wm-handler
585
586 [ handle-app-command 0 ] WM_APPCOMMAND add-wm-handler
587
588 [ handle-wm-buttondown 0 ] WM_LBUTTONDOWN add-wm-handler
589 [ handle-wm-buttondown 0 ] WM_MBUTTONDOWN add-wm-handler
590 [ handle-wm-buttondown 0 ] WM_RBUTTONDOWN add-wm-handler
591 [ handle-wm-buttonup 0   ] WM_LBUTTONUP   add-wm-handler
592 [ handle-wm-buttonup 0   ] WM_MBUTTONUP   add-wm-handler
593 [ handle-wm-buttonup 0   ] WM_RBUTTONUP   add-wm-handler
594 [ handle-wm-dwmcompositionchanged 0   ] WM_DWMCOMPOSITIONCHANGED add-wm-handler
595
596 [ 4dup handle-wm-ncbutton DefWindowProc ]
597 { WM_NCLBUTTONDOWN WM_NCMBUTTONDOWN WM_NCRBUTTONDOWN
598 WM_NCLBUTTONUP WM_NCMBUTTONUP WM_NCRBUTTONUP }
599 add-wm-handler
600
601 [ nc-buttons get-global delete-all DefWindowProc ]
602 { WM_EXITSIZEMOVE WM_EXITMENULOOP } add-wm-handler
603
604 [ handle-wm-mousemove 0  ] WM_MOUSEMOVE  add-wm-handler
605 [ handle-wm-mousewheel 0 ] WM_MOUSEWHEEL add-wm-handler
606 [ handle-wm-cancelmode 0 ] WM_CANCELMODE add-wm-handler
607 [ handle-wm-mouseleave 0 ] WM_MOUSELEAVE add-wm-handler
608
609 SYMBOL: trace-messages?
610
611 ! return 0 if you handle the message, else just let DefWindowProc return its val
612 : ui-wndproc ( -- object )
613     uint { void* uint long long } stdcall [
614         pick
615         trace-messages? get-global [ dup windows-message-name name>> print flush ] when
616         wm-handlers get-global at* [ call ] [ 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 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" utf16n 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 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-array-cast [ 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     dup handle>> hWnd>>
836     {
837         [ GWL_STYLE rot world>style SetWindowLong win32-error=0/f ]
838         [
839             f
840             over hwnd>RECT get-RECT-dimensions
841             flags{ SWP_NOMOVE SWP_NOSIZE SWP_NOZORDER SWP_FRAMECHANGED }
842             SetWindowPos win32-error=0/f
843         ]
844         [ SW_RESTORE ShowWindow win32-error=0/f ]
845     } cleave ;
846
847 M: windows-ui-backend (set-fullscreen) ( ? world -- )
848     [ enter-fullscreen ] [ exit-fullscreen ] if ;
849
850 M: windows-ui-backend (fullscreen?) ( world -- ? )
851     [ handle>> hWnd>> hwnd>RECT ]
852     [ handle>> hWnd>> fullscreen-RECT ] bi
853     [ get-RECT-dimensions 2array 2nip ] bi@ = ;
854
855 windows-ui-backend ui-backend set-global
856
857 [ "ui.tools" ] main-vocab-hook set-global