]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/windows/windows.factor
io.encodings.utf16n: merge with io.encodings.utf16
[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.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 : mouse-scroll ( wParam -- array )
440     >lo-hi [ -80 /f ] map ;
441
442 : mouse-event>gesture ( uMsg -- button )
443     key-modifiers swap message>button
444     [ <button-down> ] [ <button-up> ] if ;
445
446 :: prepare-mouse ( hWnd uMsg wParam lParam -- button coordinate world )
447     uMsg mouse-event>gesture
448     lParam >lo-hi
449     hWnd window ;
450
451 : set-capture ( hwnd -- )
452     mouse-captured get [
453         drop
454     ] [
455         [ SetCapture drop ] keep
456         mouse-captured namespaces:set
457     ] if ;
458
459 : release-capture ( -- )
460     ReleaseCapture win32-error=0/f
461     mouse-captured off ;
462
463 : handle-app-command ( hWnd uMsg wParam lParam -- )
464     GET_APPCOMMAND_LPARAM
465     {
466         { APPCOMMAND_BROWSER_BACKWARD [ pick window left-action send-action ] }
467         { APPCOMMAND_BROWSER_FORWARD [ pick window right-action send-action ] }
468         [ drop ]
469     } case 3drop ;
470
471 : handle-wm-buttondown ( hWnd uMsg wParam lParam -- )
472     [
473         over set-capture
474         dup message>button drop nc-buttons get remove! drop
475     ] 2dip prepare-mouse send-button-down ;
476
477 : handle-wm-buttonup ( hWnd uMsg wParam lParam -- )
478     mouse-captured get [ release-capture ] when
479     pick message>button drop dup nc-buttons get member? [
480         nc-buttons get remove! 5drop
481     ] [
482         drop prepare-mouse send-button-up
483     ] if ;
484
485 : make-TRACKMOUSEEVENT ( hWnd -- alien )
486     TRACKMOUSEEVENT new
487         swap >>hwndTrack
488         TRACKMOUSEEVENT c:heap-size >>cbSize ;
489
490 : handle-wm-mousemove ( hWnd uMsg wParam lParam -- )
491     2nip
492     over make-TRACKMOUSEEVENT
493         TME_LEAVE >>dwFlags
494         0 >>dwHoverTime
495     TrackMouseEvent win32-error=0/f
496     >lo-hi swap window move-hand fire-motion ;
497
498 :: handle-wm-mousewheel ( hWnd uMsg wParam lParam -- )
499     wParam mouse-scroll hand-loc get-global hWnd window send-scroll ;
500
501 : handle-wm-cancelmode ( hWnd uMsg wParam lParam -- )
502     ! message sent if windows needs application to stop dragging
503     4drop release-capture ;
504
505 : handle-wm-mouseleave ( hWnd uMsg wParam lParam -- )
506     ! message sent if mouse leaves main application
507     4drop forget-rollover ;
508
509 : system-background-color ( -- color )
510     COLOR_BTNFACE GetSysColor RGB>color ;
511
512 : ?make-glass ( world hwnd -- )
513     over window-controls>> textured-background swap member-eq? [
514         composition-enabled? [
515             full-window-margins DwmExtendFrameIntoClientArea check-hresult
516             T{ rgba f 0.0 0.0 0.0 0.0 }
517         ] [ drop system-background-color ] if >>background-color
518         drop
519     ] [ 2drop ] if ;
520
521 : handle-wm-dwmcompositionchanged ( hWnd uMsg wParam lParam -- )
522     3drop [ window ] keep ?make-glass ;
523
524 SYMBOL: wm-handlers
525
526 : add-wm-handler ( quot: ( hWnd Msg wParam lParam -- LRESULT ) wm -- )
527     dup array?
528     [ [ execute( -- wm ) add-wm-handler ] with each ]
529     [ wm-handlers get-global set-at ] if ;
530
531 : remove-wm-handler ( wm -- )
532     wm-handlers get-global delete-at ;
533
534 wm-handlers [
535     H{
536         ${ WM_CLOSE [ handle-wm-close 0 ] }
537         ! ${ WM_NCCREATE [ [ 3drop EnableNonClientDpiScaling drop ] [ DefWindowProc ] 4bi ] }
538         ! ${ WM_GETDPISCALEDSIZE [ DefWindowProc ] }
539         ! ${ WM_DPICHANGED [ DefWindowProc ] }
540         ${ WM_PAINT [ 4dup handle-wm-paint DefWindowProc ] }
541
542         ${ WM_SIZE [ handle-wm-size 0 ] }
543         ${ WM_MOVE [ handle-wm-move 0 ] }
544
545         { ${ WM_CHAR WM_SYSCHAR } [ 4dup handle-wm-char DefWindowProc ] }
546         { ${ WM_KEYDOWN WM_SYSKEYDOWN } [ 4dup handle-wm-keydown DefWindowProc ] }
547         { ${ WM_KEYUP WM_SYSKEYUP } [ 4dup handle-wm-keyup DefWindowProc ] }
548
549         ${ WM_SYSCOMMAND [ handle-wm-syscommand ] }
550         ${ WM_SETFOCUS [ handle-wm-set-focus 0 ]  }
551         ${ WM_KILLFOCUS [ handle-wm-kill-focus 0 ] }
552
553         ${ WM_APPCOMMAND [ handle-app-command 0 ] }
554
555         { ${ WM_LBUTTONDOWN WM_MBUTTONDOWN WM_RBUTTONDOWN } [ handle-wm-buttondown 0 ] }
556         { ${ WM_LBUTTONUP WM_MBUTTONUP WM_RBUTTONUP } [ handle-wm-buttonup 0 ] }
557         ${ WM_DWMCOMPOSITIONCHANGED [ handle-wm-dwmcompositionchanged 0 ] }
558
559         {
560             ${
561                 WM_NCLBUTTONDOWN WM_NCMBUTTONDOWN WM_NCRBUTTONDOWN
562                 WM_NCLBUTTONUP WM_NCMBUTTONUP WM_NCRBUTTONUP
563             } [ 4dup handle-wm-ncbutton DefWindowProc ]
564         }
565
566         { ${ WM_EXITMENULOOP WM_EXITSIZEMOVE } [ nc-buttons get-global delete-all DefWindowProc ] }
567
568         ${ WM_MOUSEMOVE [ handle-wm-mousemove 0 ] }
569         ${ WM_MOUSEWHEEL [ handle-wm-mousewheel 0 ] }
570         ${ WM_CANCELMODE [ handle-wm-cancelmode 0 ] }
571         ${ WM_MOUSELEAVE [ handle-wm-mouseleave 0 ] }
572     } expand-keys-set-at
573 ] initialize
574
575 SYMBOL: trace-messages?
576
577 ! return 0 if you handle the message, else just let DefWindowProc return its val
578 : ui-wndproc ( -- object )
579     c:uint { c:void* c:uint WPARAM LPARAM } stdcall [
580         pick wm-handlers get-global at*
581         [ flush call( hWnd Msg wParam lParam -- result ) ] [ drop DefWindowProc ] if
582     ] alien-callback ;
583
584 : peek-message? ( msg -- ? ) f 0 0 PM_REMOVE PeekMessage zero? ;
585
586 M: windows-ui-backend do-events
587     msg-obj get-global
588     dup peek-message? [ drop ui-wait ] [
589         [ TranslateMessage drop ]
590         [ DispatchMessage drop ] bi
591     ] if ;
592
593 :: register-window-class ( class-name-ptr -- )
594     WNDCLASSEX new f GetModuleHandle
595     class-name-ptr pick GetClassInfoEx 0 = [
596         WNDCLASSEX c:heap-size >>cbSize
597         flags{ CS_HREDRAW CS_VREDRAW CS_OWNDC } >>style
598         ui-wndproc >>lpfnWndProc
599         0 >>cbClsExtra
600         0 >>cbWndExtra
601         f GetModuleHandle >>hInstance
602         f GetModuleHandle "APPICON" native-string>alien LoadIcon >>hIcon
603         f IDC_ARROW MAKEINTRESOURCE LoadCursor >>hCursor
604
605         class-name-ptr >>lpszClassName
606         RegisterClassEx win32-error=0/f
607     ] [ drop ] if ;
608
609 : adjust-RECT ( RECT style ex-style -- )
610     ! [ 0 ] dip GetDpiForSystem AdjustWindowRectExForDpi win32-error=0/f ;
611     [ 0 ] dip AdjustWindowRectEx win32-error=0/f ;
612
613 : make-RECT ( world -- RECT )
614     [ window-loc>> ] [ dim>> ] bi <RECT> ;
615
616 : default-position-RECT ( RECT -- RECT' )
617     dup get-RECT-width/height
618         [ CW_USEDEFAULT + >>right ] dip
619         CW_USEDEFAULT + >>bottom
620         CW_USEDEFAULT >>left
621         CW_USEDEFAULT >>top ;
622
623 : make-adjusted-RECT ( rect style ex-style -- RECT )
624     [
625         make-RECT
626         dup get-RECT-top-left [ zero? ] both? swap
627         dup
628     ] 2dip adjust-RECT
629     swap [ default-position-RECT ] when ;
630
631 : get-window-class ( -- class-name )
632     class-name-ptr [
633         dup expired? [ drop "Factor-window" utf16n malloc-string ] when
634         dup register-window-class
635         dup
636     ] change-global ;
637
638 : get-device-caps ( handle -- x y )
639     GetDC
640     [ LOGPIXELSX GetDeviceCaps ]
641     [ LOGPIXELSY GetDeviceCaps ] bi ;
642
643 : get-default-device-caps ( -- x y )
644     f get-device-caps ;
645
646 :: create-window ( rect style ex-style -- hwnd )
647     rect style ex-style make-adjusted-RECT
648     [ get-window-class f ] dip
649     [
650         [ ex-style ] 2dip
651         flags{ WS_CLIPSIBLINGS WS_CLIPCHILDREN } style bitor
652     ] dip get-RECT-dimensions
653     f f f GetModuleHandle f CreateWindowEx dup win32-error=0/f ;
654
655 : show-window ( hWnd -- )
656     dup SW_SHOW ShowWindow drop ! always succeeds
657     dup SetForegroundWindow drop
658     SetFocus drop ;
659
660 : init-win32-ui ( -- )
661     V{ } clone nc-buttons set-global
662     MSG malloc-struct msg-obj set-global
663     GetDoubleClickTime milliseconds double-click-timeout set-global ;
664
665 : cleanup-win32-ui ( -- )
666     class-name-ptr [ [ [ f UnregisterClass drop ] [ free ] bi ] when* f ] change-global
667     msg-obj [ [ free ] when* f ] change-global ;
668
669 : get-dc ( world -- )
670     handle>> dup hWnd>> GetDC dup win32-error=0/f >>hDC drop ;
671
672 : get-rc ( world -- )
673     handle>> dup hDC>> dup wglCreateContext dup win32-error=0/f
674     [ wglMakeCurrent win32-error=0/f ] keep >>hRC drop ;
675
676 : set-pixel-format ( pixel-format hdc -- )
677     swap handle>>
678     PIXELFORMATDESCRIPTOR new SetPixelFormat win32-error=0/f ;
679
680 : setup-gl ( world -- )
681     [ get-dc ] keep
682     [ swap [ handle>> hDC>> set-pixel-format ] [ get-rc ] bi ]
683     with-world-pixel-format ;
684
685 : disable-close-button ( hwnd -- )
686     0 GetSystemMenu
687     SC_CLOSE MF_BYCOMMAND MF_GRAYED bitor EnableMenuItem drop ;
688
689 : ?disable-close-button ( world hwnd -- )
690     swap window-controls>> close-button swap member? not
691     [ disable-close-button ] [ drop ] if ;
692
693 M: windows-ui-backend (open-window)
694     [
695         dup
696         [ ] [ world>style ] [ world>ex-style ] tri create-window
697         [ ?make-glass ]
698         [ ?disable-close-button ]
699         [ [ f f ] dip f f <win> >>handle setup-gl ] 2tri
700     ]
701     [ dup handle>> hWnd>> register-window ]
702     [ handle>> hWnd>> show-window ] tri ;
703
704 ! https://github.com/factor/factor/issues/2173
705 ! ignore timeout (error 258)
706 M: win-base select-gl-context
707     [ hDC>> ] [ hRC>> ] bi wglMakeCurrent win32-error=0/f-ignore-timeout
708     GdiFlush win32-error=0/f ;
709
710 M: win-base flush-gl-context
711     hDC>> SwapBuffers win32-error=0/f ;
712
713 ! Windows 32-bit bitmaps don't actually use the alpha byte of
714 ! each pixel; it's left as zero
715
716 : (make-opaque) ( byte-array -- byte-array' )
717     [ length 4 /i ]
718     [ '[ 255 swap 4 * 3 + _ set-nth ] each ]
719     [ ] tri ;
720
721 : (opaque-pixels) ( world -- pixels )
722     [ handle>> bits>> ] [ dim>> ] bi bitmap>byte-array (make-opaque) ;
723
724 M: windows-ui-backend raise-window*
725     handle>> [ hWnd>> SetFocus drop ] when* ;
726
727 M: windows-ui-backend set-title
728     handle>>
729     dup title>> [ free ] when*
730     swap utf16n malloc-string
731     [ >>title ]
732     [ [ hWnd>> WM_SETTEXT 0 ] dip alien-address SendMessage drop ] bi ;
733
734 M: windows-ui-backend (with-ui)
735     [
736         init-clipboard
737         init-win32-ui
738         start-ui
739         event-loop
740     ] [ cleanup-win32-ui ] finally ;
741
742 M: windows-ui-backend beep
743     0 MessageBeep drop ;
744
745 M: windows-ui-backend system-alert
746     [ f ] 2dip swap MB_OK MessageBox drop ;
747
748 : fullscreen-RECT ( hwnd -- RECT )
749     MONITOR_DEFAULTTONEAREST MonitorFromWindow
750     MONITORINFOEX new
751         MONITORINFOEX c:heap-size >>cbSize
752     [ GetMonitorInfo win32-error=0/f ] keep rcMonitor>> ;
753
754 : client-area>RECT ( hwnd -- RECT )
755     RECT new
756     [ GetClientRect win32-error=0/f ]
757     [ >c-ptr POINT cast-array [ ClientToScreen drop ] with each ]
758     [ nip ] 2tri ;
759
760 : hwnd>RECT ( hwnd -- RECT )
761     RECT new [ GetWindowRect win32-error=0/f ] keep ;
762
763 M: windows-ui-backend (grab-input)
764     0 ShowCursor drop
765     hWnd>> client-area>RECT ClipCursor drop ;
766
767 M: windows-ui-backend (ungrab-input)
768     drop
769     f ClipCursor drop
770     1 ShowCursor drop ;
771
772 CONSTANT: fullscreen-flags flags{ WS_CAPTION WS_BORDER WS_THICKFRAME }
773
774 : enter-fullscreen ( world -- )
775     handle>> hWnd>>
776     {
777         [
778             GWL_STYLE GetWindowLong
779             fullscreen-flags unmask
780         ]
781         [ GWL_STYLE rot SetWindowLong win32-error=0/f ]
782         [
783             HWND_TOP
784             over hwnd>RECT get-RECT-dimensions
785             SWP_FRAMECHANGED
786             SetWindowPos win32-error=0/f
787         ]
788         [ SW_MAXIMIZE ShowWindow win32-error=0/f ]
789     } cleave ;
790
791 : exit-fullscreen ( world -- )
792     [ handle>> hWnd>> ] [ world>style ] bi
793     {
794         [ [ GWL_STYLE ] dip SetWindowLong win32-error=0/f ]
795         [
796             drop
797             f
798             over hwnd>RECT get-RECT-dimensions
799             flags{ SWP_NOMOVE SWP_NOSIZE SWP_NOZORDER SWP_FRAMECHANGED }
800             SetWindowPos win32-error=0/f
801         ]
802         [ drop SW_RESTORE ShowWindow win32-error=0/f ]
803     } 2cleave ;
804
805 : ensure-null-terminated ( str -- str' )
806     dup ?last 0 = [ "\0" append ] unless ; inline
807
808 : add-tray-icon ( title -- )
809     NIM_ADD
810     NOTIFYICONDATA new
811         NOTIFYICONDATA heap-size >>cbSize
812         NOTIFYICON_VERSION_4 over timeout-version>> uVersion<<
813         NIF_TIP NIF_ICON bitor >>uFlags
814         world get handle>> hWnd>> >>hWnd
815         f GetModuleHandle "APPICON" native-string>alien LoadIcon >>hIcon
816         rot ensure-null-terminated utf8 encode >>szTip
817         Shell_NotifyIcon win32-error=0/f ;
818
819 : remove-tray-icon ( -- )
820     NIM_DELETE
821     NOTIFYICONDATA new
822         NOTIFYICONDATA heap-size >>cbSize
823         world get handle>> hWnd>> >>hWnd
824     Shell_NotifyIcon win32-error=0/f ;
825
826 M: windows-ui-backend (set-fullscreen)
827     [ enter-fullscreen ] [ exit-fullscreen ] if ;
828
829 M: windows-ui-backend (fullscreen?)
830     handle>> hWnd>>
831     [ hwnd>RECT ] [ fullscreen-RECT ] bi
832     [ get-RECT-dimensions 2array 2nip ] same? ;
833
834 M:: windows-ui-backend resize-window ( world dim -- )
835     world handle>> hWnd>>
836     world window-loc>> dim <RECT> dup
837     world world>style
838     world world>ex-style
839     adjust-RECT get-RECT-dimensions FALSE
840     MoveWindow win32-error=0/f ;
841
842 M: windows-ui-backend ui-backend-available?
843     t ;
844
845 windows-ui-backend ui-backend set-global