]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/windows/windows.factor
move windows error handling to windows.errors and update usages.
[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 ;
14 IN: ui.backend.windows
15
16 SINGLETON: windows-ui-backend
17
18 : lo-word ( wparam -- lo ) <short> *short ; inline
19 : hi-word ( wparam -- hi ) -16 shift lo-word ; inline
20 : >lo-hi ( WORD -- array ) [ lo-word ] [ hi-word ] bi 2array ;
21
22 : crlf>lf ( str -- str' )
23     CHAR: \r swap remove ;
24
25 : lf>crlf ( str -- str' )
26     [ [ dup CHAR: \n = [ CHAR: \r , ] when , ] each ] "" make ;
27
28 : enum-clipboard ( -- seq )
29     0
30     [ EnumClipboardFormats win32-error dup dup 0 > ]
31     [ ]
32     produce 2nip ;
33
34 : with-clipboard ( quot -- )
35     f OpenClipboard win32-error=0/f
36     call
37     CloseClipboard win32-error=0/f ; inline
38
39 : paste ( -- str )
40     [
41         CF_UNICODETEXT IsClipboardFormatAvailable zero? [
42             ! nothing to paste
43             ""
44         ] [
45             CF_UNICODETEXT GetClipboardData dup win32-error=0/f
46             dup GlobalLock dup win32-error=0/f
47             GlobalUnlock win32-error=0/f
48             utf16n alien>string
49         ] if
50     ] with-clipboard
51     crlf>lf ;
52
53 : copy ( str -- )
54     lf>crlf [
55         utf16n string>alien
56         EmptyClipboard win32-error=0/f
57         GMEM_MOVEABLE over length 1+ GlobalAlloc
58             dup win32-error=0/f
59     
60         dup GlobalLock dup win32-error=0/f
61         swapd byte-array>memory
62         dup GlobalUnlock win32-error=0/f
63         CF_UNICODETEXT swap SetClipboardData win32-error=0/f
64     ] with-clipboard ;
65
66 TUPLE: pasteboard ;
67 C: <pasteboard> pasteboard
68
69 M: pasteboard clipboard-contents drop paste ;
70 M: pasteboard set-clipboard-contents drop copy ;
71
72 : init-clipboard ( -- )
73     <pasteboard> clipboard set-global
74     <clipboard> selection set-global ;
75
76 TUPLE: win-base hDC hRC ;
77 TUPLE: win < win-base hWnd world title ;
78 TUPLE: win-offscreen < win-base hBitmap bits ;
79 C: <win> win
80 C: <win-offscreen> win-offscreen
81
82 SYMBOLS: msg-obj class-name-ptr mouse-captured ;
83
84 : style ( -- n ) WS_OVERLAPPEDWINDOW ; inline
85 : ex-style ( -- n ) WS_EX_APPWINDOW WS_EX_WINDOWEDGE bitor ; inline
86
87 : get-RECT-top-left ( RECT -- x y )
88     [ RECT-left ] keep RECT-top ;
89
90 : get-RECT-dimensions ( RECT -- x y width height )
91     [ get-RECT-top-left ] keep
92     [ RECT-right ] keep [ RECT-left - ] keep
93     [ RECT-bottom ] keep RECT-top - ;
94
95 : handle-wm-paint ( hWnd uMsg wParam lParam -- )
96     #! wParam and lParam are unused
97     #! only paint if width/height both > 0
98     3drop window relayout-1 yield ;
99
100 : handle-wm-size ( hWnd uMsg wParam lParam -- )
101     2nip
102     [ lo-word ] keep hi-word 2array
103     dup { 0 0 } = [ 2drop ] [ swap window (>>dim) ] if ;
104
105 : handle-wm-move ( hWnd uMsg wParam lParam -- )
106     2nip
107     [ lo-word ] keep hi-word 2array
108     swap window (>>window-loc) ;
109
110 CONSTANT: wm-keydown-codes
111     H{
112         { 8 "BACKSPACE" }
113         { 9 "TAB" }
114         { 13 "RET" }
115         { 27 "ESC" }
116         { 33 "PAGE_UP" }
117         { 34 "PAGE_DOWN" }
118         { 35 "END" }
119         { 36 "HOME" }
120         { 37 "LEFT" }
121         { 38 "UP" }
122         { 39 "RIGHT" }
123         { 40 "DOWN" }
124         { 45 "INSERT" }
125         { 46 "DELETE" }
126         { 112 "F1" }
127         { 113 "F2" }
128         { 114 "F3" }
129         { 115 "F4" }
130         { 116 "F5" }
131         { 117 "F6" }
132         { 118 "F7" }
133         { 119 "F8" }
134         { 120 "F9" }
135         { 121 "F10" }
136         { 122 "F11" }
137         { 123 "F12" }
138     }
139
140 : key-state-down? ( key -- ? )
141     GetKeyState 16 bit? ;
142
143 : left-shift? ( -- ? ) VK_LSHIFT key-state-down? ;
144 : left-ctrl? ( -- ? ) VK_LCONTROL key-state-down? ;
145 : left-alt? ( -- ? ) VK_LMENU key-state-down? ;
146 : right-shift? ( -- ? ) VK_RSHIFT key-state-down? ;
147 : right-ctrl? ( -- ? ) VK_RCONTROL key-state-down? ;
148 : right-alt? ( -- ? ) VK_RMENU key-state-down? ;
149 : shift? ( -- ? ) left-shift? right-shift? or ;
150 : ctrl? ( -- ? ) left-ctrl? right-ctrl? or ;
151 : alt? ( -- ? ) left-alt? right-alt? or ;
152 : caps-lock? ( -- ? ) VK_CAPITAL GetKeyState zero? not ;
153
154 : key-modifiers ( -- seq )
155     [
156         shift? [ S+ , ] when
157         ctrl? [ C+ , ] when
158         alt? [ A+ , ] when
159     ] { } make [ empty? not ] keep f ? ;
160
161 CONSTANT: exclude-keys-wm-keydown
162     H{
163         { 16 "SHIFT" }
164         { 17 "CTRL" }
165         { 18 "ALT" }
166         { 20 "CAPS-LOCK" }
167     }
168
169 ! Values are ignored
170 CONSTANT: exclude-keys-wm-char
171     H{
172         { 8 "BACKSPACE" }
173         { 9 "TAB" }
174         { 13 "RET" }
175         { 27 "ESC" }
176     }
177
178 : exclude-key-wm-keydown? ( n -- ? )
179     exclude-keys-wm-keydown key? ;
180
181 : exclude-key-wm-char? ( n -- ? )
182     exclude-keys-wm-char key? ;
183
184 : keystroke>gesture ( n -- mods sym )
185     wm-keydown-codes at* [ key-modifiers swap ] [ drop f f ] if ;
186
187 : send-key-gesture ( sym action? quot hWnd -- )
188     [ [ key-modifiers ] 3dip call ] dip
189     window propagate-key-gesture ; inline
190
191 : send-key-down ( sym action? hWnd -- )
192     [ [ <key-down> ] ] dip send-key-gesture ;
193
194 : send-key-up ( sym action? hWnd -- )
195     [ [ <key-up> ] ] dip send-key-gesture ;
196
197 : key-sym ( wParam -- string/f action? )
198     {
199         {
200             [ dup LETTER? ]
201             [ shift? caps-lock? xor [ CHAR: a + CHAR: A - ] unless 1string f ]
202         }
203         { [ dup digit? ] [ 1string f ] }
204         [ wm-keydown-codes at t ]
205     } cond ;
206
207 :: handle-wm-keydown ( hWnd uMsg wParam lParam -- )
208     wParam exclude-key-wm-keydown? [
209         wParam key-sym over [
210             dup ctrl? alt? xor or [
211                 hWnd send-key-down
212             ] [ 2drop ] if
213         ] [ 2drop ] if
214     ] unless ;
215
216 :: handle-wm-char ( hWnd uMsg wParam lParam -- )
217     wParam exclude-key-wm-char? [
218         ctrl? alt? xor [
219             wParam 1string
220             [ f hWnd send-key-down ]
221             [ hWnd window user-input ] bi
222         ] unless
223     ] unless ;
224
225 :: handle-wm-keyup ( hWnd uMsg wParam lParam -- )
226     wParam exclude-key-wm-keydown? [
227         wParam key-sym over [
228             hWnd send-key-up
229         ] [ 2drop ] if
230     ] unless ;
231
232 :: set-window-active ( hwnd uMsg wParam lParam ? -- n )
233     ? hwnd window (>>active?)
234     hwnd uMsg wParam lParam DefWindowProc ;
235
236 : handle-wm-syscommand ( hWnd uMsg wParam lParam -- n )
237     {
238         { [ over SC_MINIMIZE = ] [ f set-window-active ] }
239         { [ over SC_RESTORE = ] [ t set-window-active ] }
240         { [ over SC_MAXIMIZE = ] [ t set-window-active ] }
241         { [ dup alpha? ] [ 4drop 0 ] }
242         { [ t ] [ DefWindowProc ] }
243     } cond ;
244
245 : cleanup-window ( handle -- )
246     dup title>> [ free ] when*
247     dup hRC>> wglDeleteContext win32-error=0/f
248     dup hWnd>> swap hDC>> ReleaseDC win32-error=0/f ;
249
250 M: windows-ui-backend (close-window)
251     dup hWnd>> unregister-window
252     dup cleanup-window
253     hWnd>> DestroyWindow win32-error=0/f ;
254
255 : handle-wm-close ( hWnd uMsg wParam lParam -- )
256     3drop window ungraft ;
257
258 : handle-wm-set-focus ( hWnd uMsg wParam lParam -- )
259     3drop window [ focus-world ] when* ;
260
261 : handle-wm-kill-focus ( hWnd uMsg wParam lParam -- )
262     3drop window [ unfocus-world ] when* ;
263
264 : message>button ( uMsg -- button down? )
265     {
266         { WM_LBUTTONDOWN   [ 1 t ] }
267         { WM_LBUTTONUP     [ 1 f ] }
268         { WM_MBUTTONDOWN   [ 2 t ] }
269         { WM_MBUTTONUP     [ 2 f ] }
270         { WM_RBUTTONDOWN   [ 3 t ] }
271         { WM_RBUTTONUP     [ 3 f ] }
272
273         { WM_NCLBUTTONDOWN [ 1 t ] }
274         { WM_NCLBUTTONUP   [ 1 f ] }
275         { WM_NCMBUTTONDOWN [ 2 t ] }
276         { WM_NCMBUTTONUP   [ 2 f ] }
277         { WM_NCRBUTTONDOWN [ 3 t ] }
278         { WM_NCRBUTTONUP   [ 3 f ] }
279     } case ;
280
281 ! If the user clicks in the window border ("non-client area")
282 ! Windows sends us an NC[LMR]BUTTONDOWN message; but if the
283 ! mouse is subsequently released outside the NC area, we receive
284 ! a [LMR]BUTTONUP message and Factor can get confused. So we
285 ! ignore BUTTONUP's that are a result of an NC*BUTTONDOWN.
286 SYMBOL: nc-buttons
287
288 : handle-wm-ncbutton ( hWnd uMsg wParam lParam -- )
289     2drop nip
290     message>button nc-buttons get
291     swap [ push ] [ delete ] if ;
292
293 : mouse-wheel ( wParam -- array ) >lo-hi [ sgn neg ] map ;
294
295 : mouse-event>gesture ( uMsg -- button )
296     key-modifiers swap message>button
297     [ <button-down> ] [ <button-up> ] if ;
298
299 :: prepare-mouse ( hWnd uMsg wParam lParam -- button coordinate world )
300     uMsg mouse-event>gesture
301     lParam >lo-hi
302     hWnd window ;
303
304 : set-capture ( hwnd -- )
305     mouse-captured get [
306         drop
307     ] [
308         [ SetCapture drop ] keep
309         mouse-captured set
310     ] if ;
311
312 : release-capture ( -- )
313     ReleaseCapture win32-error=0/f
314     mouse-captured off ;
315
316 : handle-wm-buttondown ( hWnd uMsg wParam lParam -- )
317     [
318         over set-capture
319         dup message>button drop nc-buttons get delete
320     ] 2dip prepare-mouse send-button-down ;
321
322 : handle-wm-buttonup ( hWnd uMsg wParam lParam -- )
323     mouse-captured get [ release-capture ] when
324     pick message>button drop dup nc-buttons get member? [
325         nc-buttons get delete 4drop
326     ] [
327         drop prepare-mouse send-button-up
328     ] if ;
329
330 : make-TRACKMOUSEEVENT ( hWnd -- alien )
331     "TRACKMOUSEEVENT" <c-object> [ set-TRACKMOUSEEVENT-hwndTrack ] keep
332     "TRACKMOUSEEVENT" heap-size over set-TRACKMOUSEEVENT-cbSize ;
333
334 : handle-wm-mousemove ( hWnd uMsg wParam lParam -- )
335     2nip
336     over make-TRACKMOUSEEVENT
337     TME_LEAVE over set-TRACKMOUSEEVENT-dwFlags
338     0 over set-TRACKMOUSEEVENT-dwHoverTime
339     TrackMouseEvent drop
340     >lo-hi swap window move-hand fire-motion ;
341
342 :: handle-wm-mousewheel ( hWnd uMsg wParam lParam -- )
343     wParam mouse-wheel hand-loc get hWnd window send-wheel ;
344
345 : handle-wm-cancelmode ( hWnd uMsg wParam lParam -- )
346     #! message sent if windows needs application to stop dragging
347     4drop release-capture ;
348
349 : handle-wm-mouseleave ( hWnd uMsg wParam lParam -- )
350     #! message sent if mouse leaves main application 
351     4drop forget-rollover ;
352
353 SYMBOL: wm-handlers
354
355 H{ } clone wm-handlers set-global
356
357 : add-wm-handler ( quot wm -- )
358     dup array?
359     [ [ execute( -- wm ) add-wm-handler ] with each ]
360     [ wm-handlers get-global set-at ] if ;
361
362 [ handle-wm-close 0                  ] WM_CLOSE add-wm-handler
363 [ 4dup handle-wm-paint DefWindowProc ] WM_PAINT add-wm-handler
364
365 [ handle-wm-size 0 ] WM_SIZE add-wm-handler
366 [ handle-wm-move 0 ] WM_MOVE add-wm-handler
367
368 [ 4dup handle-wm-keydown DefWindowProc ] { WM_KEYDOWN WM_SYSKEYDOWN } add-wm-handler
369 [ 4dup handle-wm-char DefWindowProc    ] { WM_CHAR WM_SYSCHAR }       add-wm-handler
370 [ 4dup handle-wm-keyup DefWindowProc   ] { WM_KEYUP WM_SYSKEYUP }     add-wm-handler
371
372 [ handle-wm-syscommand   ] WM_SYSCOMMAND add-wm-handler
373 [ handle-wm-set-focus 0  ] WM_SETFOCUS add-wm-handler
374 [ handle-wm-kill-focus 0 ] WM_KILLFOCUS add-wm-handler
375
376 [ handle-wm-buttondown 0 ] WM_LBUTTONDOWN add-wm-handler
377 [ handle-wm-buttondown 0 ] WM_MBUTTONDOWN add-wm-handler
378 [ handle-wm-buttondown 0 ] WM_RBUTTONDOWN add-wm-handler
379 [ handle-wm-buttonup 0   ] WM_LBUTTONUP   add-wm-handler
380 [ handle-wm-buttonup 0   ] WM_MBUTTONUP   add-wm-handler
381 [ handle-wm-buttonup 0   ] WM_RBUTTONUP   add-wm-handler
382
383 [ 4dup handle-wm-ncbutton DefWindowProc ]
384 { WM_NCLBUTTONDOWN WM_NCMBUTTONDOWN WM_NCRBUTTONDOWN
385 WM_NCLBUTTONUP WM_NCMBUTTONUP WM_NCRBUTTONUP }
386 add-wm-handler
387
388 [ nc-buttons get-global delete-all DefWindowProc ]
389 { WM_EXITSIZEMOVE WM_EXITMENULOOP } add-wm-handler
390
391 [ handle-wm-mousemove 0  ] WM_MOUSEMOVE  add-wm-handler
392 [ handle-wm-mousewheel 0 ] WM_MOUSEWHEEL add-wm-handler
393 [ handle-wm-cancelmode 0 ] WM_CANCELMODE add-wm-handler
394 [ handle-wm-mouseleave 0 ] WM_MOUSELEAVE add-wm-handler
395
396 SYMBOL: trace-messages?
397
398 ! return 0 if you handle the message, else just let DefWindowProc return its val
399 : ui-wndproc ( -- object )
400     "uint" { "void*" "uint" "long" "long" } "stdcall" [
401         pick
402         trace-messages? get-global [ dup windows-message-name name>> print flush ] when
403         wm-handlers get-global at* [ call ] [ drop DefWindowProc ] if
404      ] alien-callback ;
405
406 : peek-message? ( msg -- ? ) f 0 0 PM_REMOVE PeekMessage zero? ;
407
408 M: windows-ui-backend do-events
409     msg-obj get-global
410     dup peek-message? [ drop ui-wait ] [
411         [ TranslateMessage drop ]
412         [ DispatchMessage drop ] bi
413     ] if ;
414
415 : register-wndclassex ( -- class )
416     "WNDCLASSEX" <c-object>
417     f GetModuleHandle
418     class-name-ptr get-global
419     pick GetClassInfoEx zero? [
420         "WNDCLASSEX" heap-size over set-WNDCLASSEX-cbSize
421         { CS_HREDRAW CS_VREDRAW CS_OWNDC } flags over set-WNDCLASSEX-style
422         ui-wndproc over set-WNDCLASSEX-lpfnWndProc
423         0 over set-WNDCLASSEX-cbClsExtra
424         0 over set-WNDCLASSEX-cbWndExtra
425         f GetModuleHandle over set-WNDCLASSEX-hInstance
426         f GetModuleHandle "fraptor" utf16n string>alien LoadIcon
427         over set-WNDCLASSEX-hIcon
428         f IDC_ARROW LoadCursor over set-WNDCLASSEX-hCursor
429
430         class-name-ptr get-global over set-WNDCLASSEX-lpszClassName
431         RegisterClassEx dup win32-error=0/f
432     ] when ;
433
434 : adjust-RECT ( RECT -- )
435     style 0 ex-style AdjustWindowRectEx win32-error=0/f ;
436
437 : make-RECT ( world -- RECT )
438     [ window-loc>> ] [ dim>> ] bi <RECT> ;
439
440 : default-position-RECT ( RECT -- )
441     dup get-RECT-dimensions [ 2drop ] 2dip
442     CW_USEDEFAULT + pick set-RECT-bottom
443     CW_USEDEFAULT + over set-RECT-right
444     CW_USEDEFAULT over set-RECT-left
445     CW_USEDEFAULT swap set-RECT-top ;
446
447 : make-adjusted-RECT ( rect -- RECT )
448     make-RECT
449     dup get-RECT-top-left [ zero? ] both? swap
450     dup adjust-RECT
451     swap [ dup default-position-RECT ] when ;
452
453 : create-window ( rect -- hwnd )
454     make-adjusted-RECT
455     [ class-name-ptr get-global f ] dip
456     [
457         [ ex-style ] 2dip
458         { WS_CLIPSIBLINGS WS_CLIPCHILDREN style } flags
459     ] dip get-RECT-dimensions
460     f f f GetModuleHandle f CreateWindowEx dup win32-error=0/f ;
461
462 : show-window ( hWnd -- )
463     dup SW_SHOW ShowWindow drop ! always succeeds
464     dup SetForegroundWindow drop
465     SetFocus drop ;
466
467 : init-win32-ui ( -- )
468     V{ } clone nc-buttons set-global
469     "MSG" malloc-object msg-obj set-global
470     "Factor-window" utf16n malloc-string class-name-ptr set-global
471     register-wndclassex drop
472     GetDoubleClickTime milliseconds double-click-timeout set-global ;
473
474 : cleanup-win32-ui ( -- )
475     class-name-ptr get-global [ dup f UnregisterClass drop free ] when*
476     msg-obj get-global [ free ] when*
477     f class-name-ptr set-global
478     f msg-obj set-global ;
479
480 : setup-pixel-format ( hdc flags -- )
481     32 make-pfd [ ChoosePixelFormat dup win32-error=0/f ] 2keep
482     swapd SetPixelFormat win32-error=0/f ;
483
484 : get-dc ( hWnd -- hDC ) GetDC dup win32-error=0/f ;
485
486 : get-rc ( hDC -- hRC )
487     dup wglCreateContext dup win32-error=0/f
488     [ wglMakeCurrent win32-error=0/f ] keep ;
489
490 : setup-gl ( hwnd -- hDC hRC )
491     get-dc dup windowed-pfd-dwFlags setup-pixel-format dup get-rc ;
492
493 M: windows-ui-backend (open-window) ( world -- )
494     [ create-window [ setup-gl ] keep ] keep
495     [ f <win> ] keep
496     [ swap hWnd>> register-window ] 2keep
497     dupd (>>handle)
498     hWnd>> show-window ;
499
500 M: win-base select-gl-context ( handle -- )
501     [ hDC>> ] [ hRC>> ] bi wglMakeCurrent win32-error=0/f
502     GdiFlush drop ;
503
504 M: win-base flush-gl-context ( handle -- )
505     hDC>> SwapBuffers win32-error=0/f ;
506
507 : setup-offscreen-gl ( dim -- hDC hRC hBitmap bits )
508     make-offscreen-dc-and-bitmap [
509         [ dup offscreen-pfd-dwFlags setup-pixel-format ]
510         [ get-rc ] bi
511     ] 2dip ;
512
513 M: windows-ui-backend (open-offscreen-buffer) ( world -- )
514     dup dim>> setup-offscreen-gl <win-offscreen>
515     >>handle drop ;
516
517 M: windows-ui-backend (close-offscreen-buffer) ( handle -- )
518     [ hDC>> DeleteDC drop ]
519     [ hBitmap>> DeleteObject drop ] bi ;
520
521 ! Windows 32-bit bitmaps don't actually use the alpha byte of
522 ! each pixel; it's left as zero
523
524 : (make-opaque) ( byte-array -- byte-array' )
525     [ length 4 /i ]
526     [ '[ 255 swap 4 * 3 + _ set-nth ] each ]
527     [ ] tri ;
528
529 : (opaque-pixels) ( world -- pixels )
530     [ handle>> bits>> ] [ dim>> ] bi bitmap>byte-array (make-opaque) ;
531
532 M: windows-ui-backend offscreen-pixels ( world -- alien w h )
533     [ (opaque-pixels) ] [ dim>> first2 ] bi ;
534
535 M: windows-ui-backend raise-window* ( world -- )
536     handle>> [ hWnd>> SetFocus drop ] when* ;
537
538 M: windows-ui-backend set-title ( string world -- )
539     handle>>
540     dup title>> [ free ] when*
541     swap utf16n malloc-string
542     [ >>title ]
543     [ [ hWnd>> WM_SETTEXT 0 ] dip alien-address SendMessage drop ] bi ;
544
545 M: windows-ui-backend (with-ui)
546     [
547         [
548             init-clipboard
549             init-win32-ui
550             start-ui
551             event-loop
552         ] [ cleanup-win32-ui ] [ ] cleanup
553     ] ui-running ;
554
555 M: windows-ui-backend beep ( -- )
556     0 MessageBeep drop ;
557
558 windows-ui-backend ui-backend set-global
559
560 [ "ui.tools" ] main-vocab-hook set-global