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