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