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