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