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