]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/windows/windows.factor
factor: Make source files/resources 644 instead of 755.
[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 ;
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 action? )
325     {
326         {
327             [ dup LETTER? ]
328             [ shift? caps-lock? xor [ CHAR: a + CHAR: A - ] unless 1string f ]
329         }
330         { [ dup digit? ] [ 1string f ] }
331         [ wm-keydown-codes at t ]
332     } cond ;
333
334 :: handle-wm-keydown ( hWnd uMsg wParam lParam -- )
335     wParam exclude-key-wm-keydown? [
336         wParam key-sym over [
337             dup ctrl? alt? xor or [
338                 hWnd send-key-down
339             ] [ 2drop ] if
340         ] [ 2drop ] if
341     ] unless ;
342
343 :: handle-wm-char ( hWnd uMsg wParam lParam -- )
344     wParam exclude-key-wm-char? [
345         ctrl? alt? xor [
346             wParam 1string
347             [ f hWnd send-key-down ]
348             [ hWnd window user-input ] bi
349         ] unless
350     ] unless ;
351
352 :: handle-wm-keyup ( hWnd uMsg wParam lParam -- )
353     wParam exclude-key-wm-keydown? [
354         wParam key-sym over [
355             hWnd send-key-up
356         ] [ 2drop ] if
357     ] unless ;
358
359 :: set-window-active ( hwnd uMsg wParam lParam ? -- n )
360     ? hwnd window active?<<
361     hwnd uMsg wParam lParam DefWindowProc ;
362
363 : handle-wm-syscommand ( hWnd uMsg wParam lParam -- n )
364     {
365         { [ over SC_MINIMIZE = ] [ f set-window-active ] }
366         { [ over SC_RESTORE = ] [ t set-window-active ] }
367         { [ over SC_MAXIMIZE = ] [ t set-window-active ] }
368         { [ dup alpha? ] [ 4drop 0 ] }
369         [ DefWindowProc ]
370     } cond ;
371
372 : cleanup-window ( handle -- )
373     dup title>> [ free ] when*
374     dup hRC>> wglDeleteContext win32-error=0/f
375     dup hWnd>> swap hDC>> ReleaseDC win32-error=0/f ;
376
377 M: windows-ui-backend (close-window)
378     dup hWnd>> unregister-window
379     dup cleanup-window
380     hWnd>> DestroyWindow win32-error=0/f ;
381
382 : handle-wm-close ( hWnd uMsg wParam lParam -- )
383     3drop window ungraft ;
384
385 : handle-wm-set-focus ( hWnd uMsg wParam lParam -- )
386     3drop window [ focus-world ] when* ;
387
388 : handle-wm-kill-focus ( hWnd uMsg wParam lParam -- )
389     3drop window [ unfocus-world ] when* ;
390
391 : message>button ( uMsg -- button down? )
392     {
393         { WM_LBUTTONDOWN   [ 1 t ] }
394         { WM_LBUTTONUP     [ 1 f ] }
395         { WM_MBUTTONDOWN   [ 2 t ] }
396         { WM_MBUTTONUP     [ 2 f ] }
397         { WM_RBUTTONDOWN   [ 3 t ] }
398         { WM_RBUTTONUP     [ 3 f ] }
399
400         { WM_NCLBUTTONDOWN [ 1 t ] }
401         { WM_NCLBUTTONUP   [ 1 f ] }
402         { WM_NCMBUTTONDOWN [ 2 t ] }
403         { WM_NCMBUTTONUP   [ 2 f ] }
404         { WM_NCRBUTTONDOWN [ 3 t ] }
405         { WM_NCRBUTTONUP   [ 3 f ] }
406     } case ;
407
408 ! If the user clicks in the window border ("non-client area")
409 ! Windows sends us an NC[LMR]BUTTONDOWN message; but if the
410 ! mouse is subsequently released outside the NC area, we receive
411 ! a [LMR]BUTTONUP message and Factor can get confused. So we
412 ! ignore BUTTONUP's that are a result of an NC*BUTTONDOWN.
413 SYMBOL: nc-buttons
414
415 : handle-wm-ncbutton ( hWnd uMsg wParam lParam -- )
416     2drop nip
417     message>button nc-buttons get
418     swap [ push ] [ remove! drop ] if ;
419
420 : mouse-scroll ( wParam -- array )
421     >lo-hi [ -80 /f ] map ;
422
423 : mouse-event>gesture ( uMsg -- button )
424     key-modifiers swap message>button
425     [ <button-down> ] [ <button-up> ] if ;
426
427 :: prepare-mouse ( hWnd uMsg wParam lParam -- button coordinate world )
428     uMsg mouse-event>gesture
429     lParam >lo-hi
430     hWnd window ;
431
432 : set-capture ( hwnd -- )
433     mouse-captured get [
434         drop
435     ] [
436         [ SetCapture drop ] keep
437         mouse-captured namespaces:set
438     ] if ;
439
440 : release-capture ( -- )
441     ReleaseCapture win32-error=0/f
442     mouse-captured off ;
443
444 : handle-app-command ( hWnd uMsg wParam lParam -- )
445     GET_APPCOMMAND_LPARAM
446     {
447         { APPCOMMAND_BROWSER_BACKWARD [ pick window left-action send-action ] }
448         { APPCOMMAND_BROWSER_FORWARD [ pick window right-action send-action ] }
449         [ drop ]
450     } case 3drop ;
451
452 : handle-wm-buttondown ( hWnd uMsg wParam lParam -- )
453     [
454         over set-capture
455         dup message>button drop nc-buttons get remove! drop
456     ] 2dip prepare-mouse send-button-down ;
457
458 : handle-wm-buttonup ( hWnd uMsg wParam lParam -- )
459     mouse-captured get [ release-capture ] when
460     pick message>button drop dup nc-buttons get member? [
461         nc-buttons get remove! 5drop
462     ] [
463         drop prepare-mouse send-button-up
464     ] if ;
465
466 : make-TRACKMOUSEEVENT ( hWnd -- alien )
467     TRACKMOUSEEVENT <struct>
468         swap >>hwndTrack
469         TRACKMOUSEEVENT c:heap-size >>cbSize ;
470
471 : handle-wm-mousemove ( hWnd uMsg wParam lParam -- )
472     2nip
473     over make-TRACKMOUSEEVENT
474         TME_LEAVE >>dwFlags
475         0 >>dwHoverTime
476     TrackMouseEvent drop
477     >lo-hi swap window move-hand fire-motion ;
478
479 :: handle-wm-mousewheel ( hWnd uMsg wParam lParam -- )
480     wParam mouse-scroll hand-loc get-global hWnd window send-scroll ;
481
482 : handle-wm-cancelmode ( hWnd uMsg wParam lParam -- )
483     ! message sent if windows needs application to stop dragging
484     4drop release-capture ;
485
486 : handle-wm-mouseleave ( hWnd uMsg wParam lParam -- )
487     ! message sent if mouse leaves main application
488     4drop forget-rollover ;
489
490 : system-background-color ( -- color )
491     COLOR_BTNFACE GetSysColor RGB>color ;
492
493 : ?make-glass ( world hwnd -- )
494     over window-controls>> textured-background swap member-eq? [
495         composition-enabled? [
496             full-window-margins DwmExtendFrameIntoClientArea drop
497             T{ rgba f 0.0 0.0 0.0 0.0 }
498         ] [ drop system-background-color ] if >>background-color
499         drop
500     ] [ 2drop ] if ;
501
502 : handle-wm-dwmcompositionchanged ( hWnd uMsg wParam lParam -- )
503     3drop [ window ] keep ?make-glass ;
504
505 SYMBOL: wm-handlers
506
507 : add-wm-handler ( quot: ( hWnd Msg wParam lParam -- LRESULT ) wm -- )
508     dup array?
509     [ [ execute( -- wm ) add-wm-handler ] with each ]
510     [ wm-handlers get-global set-at ] if ;
511
512 : remove-wm-handler ( wm -- )
513     wm-handlers get-global delete-at ;
514
515 wm-handlers [
516     H{
517         ${ WM_CLOSE [ handle-wm-close 0 ] }
518         ${ WM_PAINT [ 4dup handle-wm-paint DefWindowProc ] }
519
520         ${ WM_SIZE [ handle-wm-size 0 ] }
521         ${ WM_MOVE [ handle-wm-move 0 ] }
522
523         { ${ WM_CHAR WM_SYSCHAR } [ 4dup handle-wm-char DefWindowProc ] }
524         { ${ WM_KEYDOWN WM_SYSKEYDOWN } [ 4dup handle-wm-keydown DefWindowProc ] }
525         { ${ WM_KEYUP WM_SYSKEYUP } [ 4dup handle-wm-keyup DefWindowProc ] }
526
527         ${ WM_SYSCOMMAND [ handle-wm-syscommand ] }
528         ${ WM_SETFOCUS [ handle-wm-set-focus 0 ]  }
529         ${ WM_KILLFOCUS [ handle-wm-kill-focus 0 ] }
530
531         ${ WM_APPCOMMAND [ handle-app-command 0 ] }
532
533         { ${ WM_LBUTTONDOWN WM_MBUTTONDOWN WM_RBUTTONDOWN } [ handle-wm-buttondown 0 ] }
534         { ${ WM_LBUTTONUP WM_MBUTTONUP WM_RBUTTONUP } [ handle-wm-buttonup 0 ] }
535         ${ WM_DWMCOMPOSITIONCHANGED [ handle-wm-dwmcompositionchanged 0 ] }
536
537         {
538             ${
539                 WM_NCLBUTTONDOWN WM_NCMBUTTONDOWN WM_NCRBUTTONDOWN
540                 WM_NCLBUTTONUP WM_NCMBUTTONUP WM_NCRBUTTONUP
541             } [ 4dup handle-wm-ncbutton DefWindowProc ]
542         }
543
544         { ${ WM_EXITMENULOOP WM_EXITSIZEMOVE } [ nc-buttons get-global delete-all DefWindowProc ] }
545
546         ${ WM_MOUSEMOVE [ handle-wm-mousemove 0 ] }
547         ${ WM_MOUSEWHEEL [ handle-wm-mousewheel 0 ] }
548         ${ WM_CANCELMODE [ handle-wm-cancelmode 0 ] }
549         ${ WM_MOUSELEAVE [ handle-wm-mouseleave 0 ] }
550     } expand-keys-set-at
551 ] initialize
552
553 SYMBOL: trace-messages?
554
555 ! return 0 if you handle the message, else just let DefWindowProc return its val
556 : ui-wndproc ( -- object )
557     c:uint { c:void* c:uint WPARAM LPARAM } stdcall [
558         pick wm-handlers get-global at*
559         [ flush call( hWnd Msg wParam lParam -- result ) ] [ drop DefWindowProc ] if
560     ] alien-callback ;
561
562 : peek-message? ( msg -- ? ) f 0 0 PM_REMOVE PeekMessage zero? ;
563
564 M: windows-ui-backend do-events
565     msg-obj get-global
566     dup peek-message? [ drop ui-wait ] [
567         [ TranslateMessage drop ]
568         [ DispatchMessage drop ] bi
569     ] if ;
570
571 :: register-window-class ( class-name-ptr -- )
572     WNDCLASSEX <struct> f GetModuleHandle
573     class-name-ptr pick GetClassInfoEx 0 = [
574         WNDCLASSEX c:heap-size >>cbSize
575         flags{ CS_HREDRAW CS_VREDRAW CS_OWNDC } >>style
576         ui-wndproc >>lpfnWndProc
577         0 >>cbClsExtra
578         0 >>cbWndExtra
579         f GetModuleHandle >>hInstance
580         f GetModuleHandle "APPICON" native-string>alien LoadIcon >>hIcon
581         f IDC_ARROW MAKEINTRESOURCE LoadCursor >>hCursor
582
583         class-name-ptr >>lpszClassName
584         RegisterClassEx win32-error=0/f
585     ] [ drop ] if ;
586
587 : adjust-RECT ( RECT style ex-style -- )
588     [ 0 ] dip AdjustWindowRectEx win32-error=0/f ;
589
590 : make-RECT ( world -- RECT )
591     [ window-loc>> ] [ dim>> ] bi <RECT> ;
592
593 : default-position-RECT ( RECT -- RECT' )
594     dup get-RECT-width/height
595         [ CW_USEDEFAULT + >>right ] dip
596         CW_USEDEFAULT + >>bottom
597         CW_USEDEFAULT >>left
598         CW_USEDEFAULT >>top ;
599
600 : make-adjusted-RECT ( rect style ex-style -- RECT )
601     [
602         make-RECT
603         dup get-RECT-top-left [ zero? ] both? swap
604         dup
605     ] 2dip adjust-RECT
606     swap [ default-position-RECT ] when ;
607
608 : get-window-class ( -- class-name )
609     class-name-ptr [
610         dup expired? [ drop "Factor-window" utf16n malloc-string ] when
611         dup register-window-class
612         dup
613     ] change-global ;
614
615 :: create-window ( rect style ex-style -- hwnd )
616     rect style ex-style make-adjusted-RECT
617     [ get-window-class f ] dip
618     [
619         [ ex-style ] 2dip
620         WS_CLIPSIBLINGS WS_CLIPCHILDREN bitor style bitor
621     ] dip get-RECT-dimensions
622     f f f GetModuleHandle f CreateWindowEx dup win32-error=0/f ;
623
624 : show-window ( hWnd -- )
625     dup SW_SHOW ShowWindow drop ! always succeeds
626     dup SetForegroundWindow drop
627     SetFocus drop ;
628
629 : init-win32-ui ( -- )
630     V{ } clone nc-buttons set-global
631     MSG malloc-struct msg-obj set-global
632     GetDoubleClickTime milliseconds double-click-timeout set-global ;
633
634 : cleanup-win32-ui ( -- )
635     class-name-ptr [ [ [ f UnregisterClass drop ] [ free ] bi ] when* f ] change-global
636     msg-obj [ [ free ] when* f ] change-global ;
637
638 : get-dc ( world -- )
639     handle>> dup hWnd>> GetDC dup win32-error=0/f >>hDC drop ;
640
641 : get-rc ( world -- )
642     handle>> dup hDC>> dup wglCreateContext dup win32-error=0/f
643     [ wglMakeCurrent win32-error=0/f ] keep >>hRC drop ;
644
645 : set-pixel-format ( pixel-format hdc -- )
646     swap handle>>
647     PIXELFORMATDESCRIPTOR <struct> SetPixelFormat win32-error=0/f ;
648
649 : setup-gl ( world -- )
650     [ get-dc ] keep
651     [ swap [ handle>> hDC>> set-pixel-format ] [ get-rc ] bi ]
652     with-world-pixel-format ;
653
654 : disable-close-button ( hwnd -- )
655     0 GetSystemMenu
656     SC_CLOSE MF_BYCOMMAND MF_GRAYED bitor EnableMenuItem drop ;
657
658 : ?disable-close-button ( world hwnd -- )
659     swap window-controls>> close-button swap member? not
660     [ disable-close-button ] [ drop ] if ;
661
662 M: windows-ui-backend (open-window)
663     [
664         dup
665         [ ] [ world>style ] [ world>ex-style ] tri create-window
666         [ ?make-glass ]
667         [ ?disable-close-button ]
668         [ [ f f ] dip f f <win> >>handle setup-gl ] 2tri
669     ]
670     [ dup handle>> hWnd>> register-window ]
671     [ handle>> hWnd>> show-window ] tri ;
672
673 M: win-base select-gl-context
674     [ hDC>> ] [ hRC>> ] bi wglMakeCurrent win32-error=0/f
675     GdiFlush drop ;
676
677 M: win-base flush-gl-context
678     hDC>> SwapBuffers win32-error=0/f ;
679
680 ! Windows 32-bit bitmaps don't actually use the alpha byte of
681 ! each pixel; it's left as zero
682
683 : (make-opaque) ( byte-array -- byte-array' )
684     [ length 4 /i ]
685     [ '[ 255 swap 4 * 3 + _ set-nth ] each ]
686     [ ] tri ;
687
688 : (opaque-pixels) ( world -- pixels )
689     [ handle>> bits>> ] [ dim>> ] bi bitmap>byte-array (make-opaque) ;
690
691 M: windows-ui-backend raise-window*
692     handle>> [ hWnd>> SetFocus drop ] when* ;
693
694 M: windows-ui-backend set-title
695     handle>>
696     dup title>> [ free ] when*
697     swap utf16n malloc-string
698     [ >>title ]
699     [ [ hWnd>> WM_SETTEXT 0 ] dip alien-address SendMessage drop ] bi ;
700
701 M: windows-ui-backend (with-ui)
702     [
703         init-clipboard
704         init-win32-ui
705         start-ui
706         event-loop
707     ] [ cleanup-win32-ui ] [ ] cleanup ;
708
709 M: windows-ui-backend beep
710     0 MessageBeep drop ;
711
712 M: windows-ui-backend system-alert
713     [ f ] 2dip swap MB_OK MessageBox drop ;
714
715 : fullscreen-RECT ( hwnd -- RECT )
716     MONITOR_DEFAULTTONEAREST MonitorFromWindow
717     MONITORINFOEX <struct>
718         MONITORINFOEX c:heap-size >>cbSize
719     [ GetMonitorInfo win32-error=0/f ] keep rcMonitor>> ;
720
721 : client-area>RECT ( hwnd -- RECT )
722     RECT <struct>
723     [ GetClientRect win32-error=0/f ]
724     [ >c-ptr POINT cast-array [ ClientToScreen drop ] with each ]
725     [ nip ] 2tri ;
726
727 : hwnd>RECT ( hwnd -- RECT )
728     RECT <struct> [ GetWindowRect win32-error=0/f ] keep ;
729
730 M: windows-ui-backend (grab-input)
731     0 ShowCursor drop
732     hWnd>> client-area>RECT ClipCursor drop ;
733
734 M: windows-ui-backend (ungrab-input)
735     drop
736     f ClipCursor drop
737     1 ShowCursor drop ;
738
739 CONSTANT: fullscreen-flags flags{ WS_CAPTION WS_BORDER WS_THICKFRAME }
740
741 : enter-fullscreen ( world -- )
742     handle>> hWnd>>
743     {
744         [
745             GWL_STYLE GetWindowLong
746             fullscreen-flags unmask
747         ]
748         [ GWL_STYLE rot SetWindowLong win32-error=0/f ]
749         [
750             HWND_TOP
751             over hwnd>RECT get-RECT-dimensions
752             SWP_FRAMECHANGED
753             SetWindowPos win32-error=0/f
754         ]
755         [ SW_MAXIMIZE ShowWindow win32-error=0/f ]
756     } cleave ;
757
758 : exit-fullscreen ( world -- )
759     [ handle>> hWnd>> ] [ world>style ] bi
760     {
761         [ [ GWL_STYLE ] dip SetWindowLong win32-error=0/f ]
762         [
763             drop
764             f
765             over hwnd>RECT get-RECT-dimensions
766             flags{ SWP_NOMOVE SWP_NOSIZE SWP_NOZORDER SWP_FRAMECHANGED }
767             SetWindowPos win32-error=0/f
768         ]
769         [ drop SW_RESTORE ShowWindow win32-error=0/f ]
770     } 2cleave ;
771
772 M: windows-ui-backend (set-fullscreen)
773     [ enter-fullscreen ] [ exit-fullscreen ] if ;
774
775 M: windows-ui-backend (fullscreen?)
776     handle>> hWnd>>
777     [ hwnd>RECT ] [ fullscreen-RECT ] bi
778     [ get-RECT-dimensions 2array 2nip ] same? ;
779
780 M:: windows-ui-backend resize-window ( world dim -- )
781     world handle>> hWnd>>
782     world window-loc>> dim <RECT> dup
783     world world>style
784     world world>ex-style
785     adjust-RECT get-RECT-dimensions FALSE
786     MoveWindow win32-error=0/f ;
787
788 M: windows-ui-backend ui-backend-available?
789     t ;
790
791 windows-ui-backend ui-backend set-global