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