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