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