]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/windows/windows.factor
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / basis / ui / backend / windows / windows.factor
1 ! Copyright (C) 2005, 2006 Doug Coleman.
2 ! Portions copyright (C) 2007, 2009 Slava Pestov.
3 ! See http://factorcode.org/license.txt for BSD license.
4 USING: alien alien.c-types alien.strings arrays assocs ui ui.private
5 ui.gadgets ui.gadgets.private ui.backend ui.clipboards
6 ui.gadgets.worlds ui.gestures ui.event-loop io kernel math
7 math.vectors namespaces make sequences strings vectors words
8 windows.kernel32 windows.gdi32 windows.user32 windows.opengl32
9 windows.messages windows.types windows.offscreen windows.nt
10 threads libc combinators fry combinators.short-circuit continuations
11 command-line shuffle opengl ui.render math.bitwise locals
12 accessors math.rectangles math.order calendar ascii
13 io.encodings.utf16n windows.errors literals ui.pixel-formats 
14 ui.pixel-formats.private memoize classes struct-arrays ;
15 IN: ui.backend.windows
16
17 SINGLETON: windows-ui-backend
18
19 TUPLE: win-base hDC hRC ;
20 TUPLE: win < win-base hWnd world title ;
21 TUPLE: win-offscreen < win-base hBitmap bits ;
22 C: <win> win
23 C: <win-offscreen> win-offscreen
24
25 <PRIVATE
26
27 PIXEL-FORMAT-ATTRIBUTE-TABLE: WGL_ARB { $ WGL_SUPPORT_OPENGL_ARB 1 } H{
28     { double-buffered { $ WGL_DOUBLE_BUFFER_ARB 1 } }
29     { stereo { $ WGL_STEREO_ARB 1 } }
30     { offscreen { $ WGL_DRAW_TO_BITMAP_ARB 1 } }
31     { fullscreen { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
32     { windowed { $ WGL_DRAW_TO_WINDOW_ARB 1 } }
33     { accelerated { $ WGL_ACCELERATION_ARB $ WGL_FULL_ACCELERATION_ARB } }
34     { software-rendered { $ WGL_ACCELERATION_ARB $ WGL_NO_ACCELERATION_ARB } }
35     { backing-store { $ WGL_SWAP_METHOD_ARB $ WGL_SWAP_COPY_ARB } }
36     { color-float { $ WGL_TYPE_RGBA_FLOAT_ARB 1 } }
37     { color-bits { $ WGL_COLOR_BITS_ARB } }
38     { red-bits { $ WGL_RED_BITS_ARB } }
39     { green-bits { $ WGL_GREEN_BITS_ARB } }
40     { blue-bits { $ WGL_BLUE_BITS_ARB } }
41     { alpha-bits { $ WGL_ALPHA_BITS_ARB } }
42     { accum-bits { $ WGL_ACCUM_BITS_ARB } }
43     { accum-red-bits { $ WGL_ACCUM_RED_BITS_ARB } }
44     { accum-green-bits { $ WGL_ACCUM_GREEN_BITS_ARB } }
45     { accum-blue-bits { $ WGL_ACCUM_BLUE_BITS_ARB } }
46     { accum-alpha-bits { $ WGL_ACCUM_ALPHA_BITS_ARB } }
47     { depth-bits { $ WGL_DEPTH_BITS_ARB } }
48     { stencil-bits { $ WGL_STENCIL_BITS_ARB } }
49     { aux-buffers { $ WGL_AUX_BUFFERS_ARB } }
50     { sample-buffers { $ WGL_SAMPLE_BUFFERS_ARB } }
51     { samples { $ WGL_SAMPLES_ARB } }
52 }
53
54 : has-wglChoosePixelFormatARB? ( world -- ? )
55     drop f ;
56
57 : arb-make-pixel-format ( world attributes -- pf )
58     [ handle>> hDC>> ] dip >WGL_ARB-int-array f 1 0 <int> 0 <int>
59     [ wglChoosePixelFormatARB win32-error=0/f ] 2keep drop *int ;
60
61 : arb-pixel-format-attribute ( pixel-format attribute -- value )
62     >WGL_ARB
63     [ drop f ] [
64         [ [ world>> handle>> hDC>> ] [ handle>> ] bi 0 1 ] dip
65         first <int> 0 <int>
66         [ wglGetPixelFormatAttribivARB win32-error=0/f ]
67         keep *int
68     ] if-empty ;
69
70 CONSTANT: pfd-flag-map H{
71     { double-buffered $ PFD_DOUBLEBUFFER }
72     { stereo $ PFD_STEREO }
73     { offscreen $ PFD_DRAW_TO_BITMAP }
74     { fullscreen $ PFD_DRAW_TO_WINDOW }
75     { windowed $ PFD_DRAW_TO_WINDOW }
76     { backing-store $ PFD_SWAP_COPY }
77     { software-rendered $ PFD_GENERIC_FORMAT }
78 }
79
80 : >pfd-flag ( attribute -- value )
81     pfd-flag-map at [ ] [ 0 ] if* ;
82
83 : >pfd-flags ( attributes -- flags )
84     [ >pfd-flag ] [ bitor ] map-reduce
85     PFD_SUPPORT_OPENGL bitor ;
86
87 : attr-value ( attributes name -- value )
88     [ instance? ] curry find nip
89     [ value>> ] [ 0 ] if* ;
90
91 : >pfd ( attributes -- pfd )
92     "PIXELFORMATDESCRIPTOR" <c-object>
93     "PIXELFORMATDESCRIPTOR" heap-size over set-PIXELFORMATDESCRIPTOR-nSize
94     1 over set-PIXELFORMATDESCRIPTOR-nVersion
95     over >pfd-flags over set-PIXELFORMATDESCRIPTOR-dwFlags
96     PFD_TYPE_RGBA over set-PIXELFORMATDESCRIPTOR-iPixelType
97     over color-bits attr-value over set-PIXELFORMATDESCRIPTOR-cColorBits
98     over red-bits attr-value over set-PIXELFORMATDESCRIPTOR-cRedBits
99     over green-bits attr-value over set-PIXELFORMATDESCRIPTOR-cGreenBits
100     over blue-bits attr-value over set-PIXELFORMATDESCRIPTOR-cBlueBits
101     over alpha-bits attr-value over set-PIXELFORMATDESCRIPTOR-cAlphaBits
102     over accum-bits attr-value over set-PIXELFORMATDESCRIPTOR-cAccumBits
103     over accum-red-bits attr-value over set-PIXELFORMATDESCRIPTOR-cAccumRedBits
104     over accum-green-bits attr-value over set-PIXELFORMATDESCRIPTOR-cAccumGreenBits
105     over accum-blue-bits attr-value over set-PIXELFORMATDESCRIPTOR-cAccumBlueBits
106     over accum-alpha-bits attr-value over set-PIXELFORMATDESCRIPTOR-cAccumAlphaBits
107     over depth-bits attr-value over set-PIXELFORMATDESCRIPTOR-cDepthBits
108     over stencil-bits attr-value over set-PIXELFORMATDESCRIPTOR-cStencilBits
109     over aux-buffers attr-value over set-PIXELFORMATDESCRIPTOR-cAuxBuffers
110     PFD_MAIN_PLANE over set-PIXELFORMATDESCRIPTOR-dwLayerMask
111     nip ;
112
113 : pfd-make-pixel-format ( world attributes -- pf )
114     [ handle>> hDC>> ] [ >pfd ] bi*
115     ChoosePixelFormat dup win32-error=0/f ;
116
117 : get-pfd ( pixel-format -- pfd )
118     [ world>> handle>> hDC>> ] [ handle>> ] bi
119     "PIXELFORMATDESCRIPTOR" heap-size
120     "PIXELFORMATDESCRIPTOR" <c-object>
121     [ DescribePixelFormat win32-error=0/f ] keep ;
122
123 : pfd-flag? ( pfd flag -- ? )
124     [ PIXELFORMATDESCRIPTOR-dwFlags ] dip bitand c-bool> ;
125
126 : (pfd-pixel-format-attribute) ( pfd attribute -- value )
127     {
128         { double-buffered [ PFD_DOUBLEBUFFER pfd-flag? ] }
129         { stereo [ PFD_STEREO pfd-flag? ] }
130         { offscreen [ PFD_DRAW_TO_BITMAP pfd-flag? ] }
131         { fullscreen [ PFD_DRAW_TO_WINDOW pfd-flag? ] }
132         { windowed [ PFD_DRAW_TO_WINDOW pfd-flag? ] }
133         { software-rendered [ PFD_GENERIC_FORMAT pfd-flag? ] }
134         { color-bits [ PIXELFORMATDESCRIPTOR-cColorBits ] }
135         { red-bits [ PIXELFORMATDESCRIPTOR-cRedBits ] }
136         { green-bits [ PIXELFORMATDESCRIPTOR-cGreenBits ] }
137         { blue-bits [ PIXELFORMATDESCRIPTOR-cBlueBits ] }
138         { alpha-bits [ PIXELFORMATDESCRIPTOR-cAlphaBits ] }
139         { accum-bits [ PIXELFORMATDESCRIPTOR-cAccumBits ] }
140         { accum-red-bits [ PIXELFORMATDESCRIPTOR-cAccumRedBits ] }
141         { accum-green-bits [ PIXELFORMATDESCRIPTOR-cAccumGreenBits ] }
142         { accum-blue-bits [ PIXELFORMATDESCRIPTOR-cAccumBlueBits ] }
143         { accum-alpha-bits [ PIXELFORMATDESCRIPTOR-cAccumAlphaBits ] }
144         { depth-bits [ PIXELFORMATDESCRIPTOR-cDepthBits ] }
145         { stencil-bits [ PIXELFORMATDESCRIPTOR-cStencilBits ] }
146         { aux-buffers [ PIXELFORMATDESCRIPTOR-cAuxBuffers ] }
147         [ 2drop f ]
148     } case ;
149
150 : pfd-pixel-format-attribute ( pixel-format attribute -- value )
151     [ get-pfd ] dip (pfd-pixel-format-attribute) ;
152
153 M: windows-ui-backend (make-pixel-format)
154     over has-wglChoosePixelFormatARB?
155     [ arb-make-pixel-format ] [ pfd-make-pixel-format ] if ;
156
157 M: windows-ui-backend (free-pixel-format)
158     drop ;
159
160 M: windows-ui-backend (pixel-format-attribute)
161     over world>> has-wglChoosePixelFormatARB?
162     [ arb-pixel-format-attribute ] [ pfd-pixel-format-attribute ] if ;
163
164 PRIVATE>
165
166 : lo-word ( wparam -- lo ) <short> *short ; inline
167 : hi-word ( wparam -- hi ) -16 shift lo-word ; inline
168 : >lo-hi ( WORD -- array ) [ lo-word ] [ hi-word ] bi 2array ;
169
170 : crlf>lf ( str -- str' )
171     CHAR: \r swap remove ;
172
173 : lf>crlf ( str -- str' )
174     [ [ dup CHAR: \n = [ CHAR: \r , ] when , ] each ] "" make ;
175
176 : enum-clipboard ( -- seq )
177     0
178     [ EnumClipboardFormats win32-error dup dup 0 > ]
179     [ ]
180     produce 2nip ;
181
182 : with-clipboard ( quot -- )
183     f OpenClipboard win32-error=0/f
184     call
185     CloseClipboard win32-error=0/f ; inline
186
187 : paste ( -- str )
188     [
189         CF_UNICODETEXT IsClipboardFormatAvailable zero? [
190             ! nothing to paste
191             ""
192         ] [
193             CF_UNICODETEXT GetClipboardData dup win32-error=0/f
194             dup GlobalLock dup win32-error=0/f
195             GlobalUnlock win32-error=0/f
196             utf16n alien>string
197         ] if
198     ] with-clipboard
199     crlf>lf ;
200
201 : copy ( str -- )
202     lf>crlf [
203         utf16n string>alien
204         EmptyClipboard win32-error=0/f
205         GMEM_MOVEABLE over length 1+ GlobalAlloc
206             dup win32-error=0/f
207     
208         dup GlobalLock dup win32-error=0/f
209         swapd byte-array>memory
210         dup GlobalUnlock win32-error=0/f
211         CF_UNICODETEXT swap SetClipboardData win32-error=0/f
212     ] with-clipboard ;
213
214 TUPLE: pasteboard ;
215 C: <pasteboard> pasteboard
216
217 M: pasteboard clipboard-contents drop paste ;
218 M: pasteboard set-clipboard-contents drop copy ;
219
220 : init-clipboard ( -- )
221     <pasteboard> clipboard set-global
222     <clipboard> selection set-global ;
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-window-class ( class-name-ptr -- )
558     "WNDCLASSEX" <c-object> f GetModuleHandle
559     class-name-ptr pick GetClassInfoEx 0 = [
560         "WNDCLASSEX" heap-size over set-WNDCLASSEX-cbSize
561         { CS_HREDRAW CS_VREDRAW CS_OWNDC } flags over set-WNDCLASSEX-style
562         ui-wndproc over set-WNDCLASSEX-lpfnWndProc
563         0 over set-WNDCLASSEX-cbClsExtra
564         0 over set-WNDCLASSEX-cbWndExtra
565         f GetModuleHandle over set-WNDCLASSEX-hInstance
566         f GetModuleHandle "fraptor" utf16n string>alien LoadIcon
567         over set-WNDCLASSEX-hIcon
568         f IDC_ARROW LoadCursor over set-WNDCLASSEX-hCursor
569
570         class-name-ptr over set-WNDCLASSEX-lpszClassName
571         RegisterClassEx win32-error=0/f
572     ] [ drop ] if ;
573
574 : adjust-RECT ( RECT -- )
575     style 0 ex-style AdjustWindowRectEx win32-error=0/f ;
576
577 : make-RECT ( world -- RECT )
578     [ window-loc>> ] [ dim>> ] bi <RECT> ;
579
580 : default-position-RECT ( RECT -- )
581     dup get-RECT-dimensions [ 2drop ] 2dip
582     CW_USEDEFAULT + pick set-RECT-bottom
583     CW_USEDEFAULT + over set-RECT-right
584     CW_USEDEFAULT over set-RECT-left
585     CW_USEDEFAULT swap set-RECT-top ;
586
587 : make-adjusted-RECT ( rect -- RECT )
588     make-RECT
589     dup get-RECT-top-left [ zero? ] both? swap
590     dup adjust-RECT
591     swap [ dup default-position-RECT ] when ;
592
593 : get-window-class ( -- class-name )
594     class-name-ptr [
595         dup expired? [ drop "Factor-window" utf16n malloc-string ] when
596         dup register-window-class
597         dup
598     ] change-global ;
599
600 : create-window ( rect -- hwnd )
601     make-adjusted-RECT
602     [ get-window-class f ] dip
603     [
604         [ ex-style ] 2dip
605         { WS_CLIPSIBLINGS WS_CLIPCHILDREN style } flags
606     ] dip get-RECT-dimensions
607     f f f GetModuleHandle f CreateWindowEx dup win32-error=0/f ;
608
609 : show-window ( hWnd -- )
610     dup SW_SHOW ShowWindow drop ! always succeeds
611     dup SetForegroundWindow drop
612     SetFocus drop ;
613
614 : init-win32-ui ( -- )
615     V{ } clone nc-buttons set-global
616     "MSG" malloc-object msg-obj set-global
617     GetDoubleClickTime milliseconds double-click-timeout set-global ;
618
619 : cleanup-win32-ui ( -- )
620     class-name-ptr [ [ [ f UnregisterClass drop ] [ free ] bi ] when* f ] change-global
621     msg-obj [ [ free ] when* f ] change-global ;
622
623 : get-dc ( world -- )
624     handle>> dup hWnd>> GetDC dup win32-error=0/f >>hDC drop ;
625
626 : get-rc ( world -- )
627     handle>> dup hDC>> dup wglCreateContext dup win32-error=0/f
628     [ wglMakeCurrent win32-error=0/f ] keep >>hRC drop ;
629
630 : set-pixel-format ( pixel-format hdc -- )
631     swap handle>>
632     "PIXELFORMATDESCRIPTOR" <c-object> SetPixelFormat win32-error=0/f ;
633
634 : setup-gl ( world -- )
635     [ get-dc ] keep
636     [ swap [ handle>> hDC>> set-pixel-format ] [ get-rc ] bi ]
637     with-world-pixel-format ;
638
639 M: windows-ui-backend (open-window) ( world -- )
640     [ dup create-window [ f f ] dip f f <win> >>handle setup-gl ]
641     [ dup handle>> hWnd>> register-window ]
642     [ handle>> hWnd>> show-window ] tri ;
643
644 M: win-base select-gl-context ( handle -- )
645     [ hDC>> ] [ hRC>> ] bi wglMakeCurrent win32-error=0/f
646     GdiFlush drop ;
647
648 M: win-base flush-gl-context ( handle -- )
649     hDC>> SwapBuffers win32-error=0/f ;
650
651 : setup-offscreen-gl ( world -- )
652     dup [ handle>> ] [ dim>> ] bi make-offscreen-dc-and-bitmap
653     [ >>hDC ] [ >>hBitmap ] [ >>bits ] tri* drop [
654         swap [ handle>> hDC>> set-pixel-format ] [ get-rc ] bi
655     ] with-world-pixel-format ;
656
657 M: windows-ui-backend (open-offscreen-buffer) ( world -- )
658     win-offscreen new >>handle
659     setup-offscreen-gl ;
660
661 M: windows-ui-backend (close-offscreen-buffer) ( handle -- )
662     [ hDC>> DeleteDC drop ]
663     [ hBitmap>> DeleteObject drop ] bi ;
664
665 ! Windows 32-bit bitmaps don't actually use the alpha byte of
666 ! each pixel; it's left as zero
667
668 : (make-opaque) ( byte-array -- byte-array' )
669     [ length 4 /i ]
670     [ '[ 255 swap 4 * 3 + _ set-nth ] each ]
671     [ ] tri ;
672
673 : (opaque-pixels) ( world -- pixels )
674     [ handle>> bits>> ] [ dim>> ] bi bitmap>byte-array (make-opaque) ;
675
676 M: windows-ui-backend offscreen-pixels ( world -- alien w h )
677     [ (opaque-pixels) ] [ dim>> first2 ] bi ;
678
679 M: windows-ui-backend raise-window* ( world -- )
680     handle>> [ hWnd>> SetFocus drop ] when* ;
681
682 M: windows-ui-backend set-title ( string world -- )
683     handle>>
684     dup title>> [ free ] when*
685     swap utf16n malloc-string
686     [ >>title ]
687     [ [ hWnd>> WM_SETTEXT 0 ] dip alien-address SendMessage drop ] bi ;
688
689 M: windows-ui-backend (with-ui)
690     [
691         [
692             init-clipboard
693             init-win32-ui
694             start-ui
695             event-loop
696         ] [ cleanup-win32-ui ] [ ] cleanup
697     ] ui-running ;
698
699 M: windows-ui-backend beep ( -- )
700     0 MessageBeep drop ;
701
702 : fullscreen-RECT ( hwnd -- RECT )
703     MONITOR_DEFAULTTONEAREST MonitorFromWindow
704     "MONITORINFOEX" <c-object> dup length over set-MONITORINFOEX-cbSize
705     [ GetMonitorInfo win32-error=0/f ] keep MONITORINFOEX-rcMonitor ;
706
707 : client-area>RECT ( hwnd -- RECT )
708     "RECT" <c-object>
709     [ GetClientRect win32-error=0/f ]
710     [ "POINT" byte-array>struct-array [ ClientToScreen drop ] with each ]
711     [ nip ] 2tri ;
712
713 : hwnd>RECT ( hwnd -- RECT )
714     "RECT" <c-object> [ GetWindowRect win32-error=0/f ] keep ;
715
716 M: windows-ui-backend (grab-input) ( handle -- )
717     0 ShowCursor drop
718     hWnd>> client-area>RECT ClipCursor drop ;
719
720 M: windows-ui-backend (ungrab-input) ( handle -- )
721     drop
722     f ClipCursor drop
723     1 ShowCursor drop ;
724
725 : fullscreen-flags ( -- n )
726     { WS_CAPTION WS_BORDER WS_THICKFRAME } flags ; inline
727
728 : enter-fullscreen ( world -- )
729     handle>> hWnd>>
730     {
731         [
732             GWL_STYLE GetWindowLong
733             fullscreen-flags unmask
734         ]
735         [ GWL_STYLE rot SetWindowLong win32-error=0/f ]
736         [
737             HWND_TOP
738             over hwnd>RECT get-RECT-dimensions
739             SWP_FRAMECHANGED
740             SetWindowPos win32-error=0/f
741         ]
742         [ SW_MAXIMIZE ShowWindow win32-error=0/f ]
743     } cleave ;
744
745 : exit-fullscreen ( world -- )
746     handle>> hWnd>>
747     {
748         [
749             GWL_STYLE GetWindowLong
750             fullscreen-flags bitor
751         ]
752         [ GWL_STYLE rot SetWindowLong win32-error=0/f ]
753         [
754             f
755             over hwnd>RECT get-RECT-dimensions
756             { SWP_NOMOVE SWP_NOSIZE SWP_NOZORDER SWP_FRAMECHANGED } flags
757             SetWindowPos win32-error=0/f
758         ]
759         [ SW_RESTORE ShowWindow win32-error=0/f ]
760     } cleave ;
761
762 M: windows-ui-backend (set-fullscreen) ( ? world -- )
763     [ enter-fullscreen ] [ exit-fullscreen ] if ;
764
765 M: windows-ui-backend (fullscreen?) ( world -- ? )
766     [ handle>> hWnd>> hwnd>RECT ]
767     [ handle>> hWnd>> fullscreen-RECT ] bi
768     [ get-RECT-dimensions 2array 2nip ] bi@ = ;
769
770 windows-ui-backend ui-backend set-global
771
772 [ "ui.tools" ] main-vocab-hook set-global