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