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