Debian Codegraph @

shiny/driver/gldriver/cocoa.go

raw symbols SCIP
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build darwin && !ios
6
7 package gldriver
8
9 /*
10 #cgo CFLAGS: -x objective-c -DGL_SILENCE_DEPRECATION
11 #cgo LDFLAGS: -framework Cocoa -framework OpenGL
12 #include <OpenGL/gl3.h>
13 #import <Carbon/Carbon.h> // for HIToolbox/Events.h
14 #import <Cocoa/Cocoa.h>
15 #include <pthread.h>
16 #include <stdint.h>
17 #include <stdlib.h>
18
19 void startDriver();
20 void stopDriver();
21 void makeCurrentContext(uintptr_t ctx);
22 void flushContext(uintptr_t ctx);
23 uintptr_t doNewWindow(int width, int height, char* title);
24 void doShowWindow(uintptr_t id);
25 void doCloseWindow(uintptr_t id);
26 uint64_t threadID();
27 */
28 import "C"
29
30 import (
31 "errors"
32 "fmt"
33 "log"
34 "runtime"
35 "unsafe"
36
37 "golang.org/x/exp/shiny/driver/internal/lifecycler"
38 "golang.org/x/exp/shiny/screen"
39 "golang.org/x/mobile/event/key"
40 "golang.org/x/mobile/event/mouse"
41 "golang.org/x/mobile/event/paint"
42 "golang.org/x/mobile/event/size"
43 "golang.org/x/mobile/geom"
44 "golang.org/x/mobile/gl"
45 )
46
47 const useLifecycler = true
48
49 // TODO: change this to true, after manual testing on OS X.
50 const handleSizeEventsAtChannelReceive = false
51
52 var initThreadID C.uint64_t
53
54 func init() {
55 // Lock the goroutine responsible for initialization to an OS thread.
56 // This means the goroutine running main (and calling startDriver below)
57 // is locked to the OS thread that started the program. This is
58 // necessary for the correct delivery of Cocoa events to the process.
59 //
60 // A discussion on this topic:
61 // https://groups.google.com/forum/#!msg/golang-nuts/IiWZ2hUuLDA/SNKYYZBelsYJ
62 runtime.LockOSThread()
63 initThreadID = C.threadID()
64 }
65
66 func newWindow(opts *screen.NewWindowOptions) (uintptr, error) {
67 width, height := optsSize(opts)
68
69 title := C.CString(opts.GetTitle())
70 defer C.free(unsafe.Pointer(title))
71
72 return uintptr(C.doNewWindow(C.int(width), C.int(height), title)), nil
73 }
74
75 func initWindow(w *windowImpl) {
76 w.glctx, w.worker = gl.NewContext()
77 }
78
79 func showWindow(w *windowImpl) {
80 C.doShowWindow(C.uintptr_t(w.id))
81 }
82
83 //export preparedOpenGL
84 func preparedOpenGL(id, ctx, vba uintptr) {
85 theScreen.mu.Lock()
86 w := theScreen.windows[id]
87 theScreen.mu.Unlock()
88
89 w.ctx = ctx
90 go drawLoop(w, vba)
91 }
92
93 func closeWindow(id uintptr) {
94 C.doCloseWindow(C.uintptr_t(id))
95 }
96
97 var mainCallback func(screen.Screen)
98
99 func main(f func(screen.Screen)) error {
100 if tid := C.threadID(); tid != initThreadID {
101 log.Fatalf("gldriver.Main called on thread %d, but gldriver.init ran on %d", tid, initThreadID)
102 }
103
104 mainCallback = f
105 C.startDriver()
106 return nil
107 }
108
109 //export driverStarted
110 func driverStarted() {
111 go func() {
112 mainCallback(theScreen)
113 C.stopDriver()
114 }()
115 }
116
117 //export drawgl
118 func drawgl(id uintptr) {
119 theScreen.mu.Lock()
120 w := theScreen.windows[id]
121 theScreen.mu.Unlock()
122
123 if w == nil {
124 return // closing window
125 }
126
127 // TODO: is this necessary?
128 w.lifecycler.SetVisible(true)
129 w.lifecycler.SendEvent(w, w.glctx)
130
131 w.Send(paint.Event{External: true})
132 <-w.drawDone
133 }
134
135 // drawLoop is the primary drawing loop.
136 //
137 // After Cocoa has created an NSWindow and called prepareOpenGL,
138 // it starts drawLoop on a locked goroutine to handle OpenGL calls.
139 //
140 // The screen is drawn every time a paint.Event is received, which can be
141 // triggered either by the user or by Cocoa via drawgl (for example, when
142 // the window is resized).
143 func drawLoop(w *windowImpl, vba uintptr) {
144 runtime.LockOSThread()
145 C.makeCurrentContext(C.uintptr_t(w.ctx.(uintptr)))
146
147 // Starting in OS X 10.11 (El Capitan), the vertex array is
148 // occasionally getting unbound when the context changes threads.
149 //
150 // Avoid this by binding it again.
151 C.glBindVertexArray(C.GLuint(vba))
152 if errno := C.glGetError(); errno != 0 {
153 panic(fmt.Sprintf("gldriver: glBindVertexArray failed: %d", errno))
154 }
155
156 workAvailable := w.worker.WorkAvailable()
157
158 // TODO(crawshaw): exit this goroutine on Release.
159 for {
160 select {
161 case <-workAvailable:
162 w.worker.DoWork()
163 case <-w.publish:
164 loop:
165 for {
166 select {
167 case <-workAvailable:
168 w.worker.DoWork()
169 default:
170 break loop
171 }
172 }
173 C.flushContext(C.uintptr_t(w.ctx.(uintptr)))
174 w.publishDone <- screen.PublishResult{}
175 }
176 }
177 }
178
179 //export setGeom
180 func setGeom(id uintptr, ppp float32, widthPx, heightPx int) {
181 theScreen.mu.Lock()
182 w := theScreen.windows[id]
183 theScreen.mu.Unlock()
184
185 if w == nil {
186 return // closing window
187 }
188
189 sz := size.Event{
190 WidthPx: widthPx,
191 HeightPx: heightPx,
192 WidthPt: geom.Pt(float32(widthPx) / ppp),
193 HeightPt: geom.Pt(float32(heightPx) / ppp),
194 PixelsPerPt: ppp,
195 }
196
197 if !handleSizeEventsAtChannelReceive {
198 w.szMu.Lock()
199 w.sz = sz
200 w.szMu.Unlock()
201 }
202
203 w.Send(sz)
204 }
205
206 //export windowClosing
207 func windowClosing(id uintptr) {
208 sendLifecycle(id, (*lifecycler.State).SetDead, true)
209 }
210
211 func sendWindowEvent(id uintptr, e interface{}) {
212 theScreen.mu.Lock()
213 w := theScreen.windows[id]
214 theScreen.mu.Unlock()
215
216 if w == nil {
217 return // closing window
218 }
219 w.Send(e)
220 }
221
222 var mods = [...]struct {
223 flags uint32
224 code uint16
225 mod key.Modifiers
226 }{
227 // Left and right variants of modifier keys have their own masks,
228 // but they are not documented. These were determined empirically.
229 {1<<17 | 0x102, C.kVK_Shift, key.ModShift},
230 {1<<17 | 0x104, C.kVK_RightShift, key.ModShift},
231 {1<<18 | 0x101, C.kVK_Control, key.ModControl},
232 {33<<13 | 0x100, C.kVK_RightControl, key.ModControl},
233 {1<<19 | 0x120, C.kVK_Option, key.ModAlt},
234 {1<<19 | 0x140, C.kVK_RightOption, key.ModAlt},
235 {1<<20 | 0x108, C.kVK_Command, key.ModMeta},
236 {1<<20 | 0x110, 0x36 /* kVK_RightCommand */, key.ModMeta},
237 }
238
239 func cocoaMods(flags uint32) (m key.Modifiers) {
240 for _, mod := range mods {
241 if flags&mod.flags == mod.flags {
242 m |= mod.mod
243 }
244 }
245 return m
246 }
247
248 func cocoaMouseDir(ty int32) mouse.Direction {
249 switch ty {
250 case C.NSLeftMouseDown, C.NSRightMouseDown, C.NSOtherMouseDown:
251 return mouse.DirPress
252 case C.NSLeftMouseUp, C.NSRightMouseUp, C.NSOtherMouseUp:
253 return mouse.DirRelease
254 default: // dragged
255 return mouse.DirNone
256 }
257 }
258
259 func cocoaMouseButton(button int32) mouse.Button {
260 switch button {
261 case 0:
262 return mouse.ButtonLeft
263 case 1:
264 return mouse.ButtonRight
265 case 2:
266 return mouse.ButtonMiddle
267 default:
268 return mouse.ButtonNone
269 }
270 }
271
272 //export mouseEvent
273 func mouseEvent(id uintptr, x, y, dx, dy float32, ty, button int32, flags uint32) {
274 cmButton := mouse.ButtonNone
275 switch ty {
276 default:
277 cmButton = cocoaMouseButton(button)
278 case C.NSMouseMoved, C.NSLeftMouseDragged, C.NSRightMouseDragged, C.NSOtherMouseDragged:
279 // No-op.
280 case C.NSScrollWheel:
281 // Note that the direction of scrolling is inverted by default
282 // on OS X by the "natural scrolling" setting. At the Cocoa
283 // level this inversion is applied to trackpads and mice behind
284 // the scenes, and the value of dy goes in the direction the OS
285 // wants scrolling to go.
286 //
287 // This means the same trackpad/mouse motion on OS X and Linux
288 // can produce wheel events in opposite directions, but the
289 // direction matches what other programs on the OS do.
290 //
291 // If we wanted to expose the physical device motion in the
292 // event we could use [NSEvent isDirectionInvertedFromDevice]
293 // to know if "natural scrolling" is enabled.
294 //
295 // TODO: On a trackpad, a scroll can be a drawn-out affair with a
296 // distinct beginning and end. Should the intermediate events be
297 // DirNone?
298 //
299 // TODO: handle horizontal scrolling
300 button := mouse.ButtonWheelUp
301 if dy < 0 {
302 dy = -dy
303 button = mouse.ButtonWheelDown
304 }
305 e := mouse.Event{
306 X: x,
307 Y: y,
308 Button: button,
309 Direction: mouse.DirStep,
310 Modifiers: cocoaMods(flags),
311 }
312 for delta := int(dy); delta != 0; delta-- {
313 sendWindowEvent(id, e)
314 }
315 return
316 }
317 sendWindowEvent(id, mouse.Event{
318 X: x,
319 Y: y,
320 Button: cmButton,
321 Direction: cocoaMouseDir(ty),
322 Modifiers: cocoaMods(flags),
323 })
324 }
325
326 //export keyEvent
327 func keyEvent(id uintptr, runeVal rune, dir uint8, code uint16, flags uint32) {
328 sendWindowEvent(id, key.Event{
329 Rune: cocoaRune(runeVal),
330 Direction: key.Direction(dir),
331 Code: cocoaKeyCode(code),
332 Modifiers: cocoaMods(flags),
333 })
334 }
335
336 //export flagEvent
337 func flagEvent(id uintptr, flags uint32) {
338 for _, mod := range mods {
339 if flags&mod.flags == mod.flags && lastFlags&mod.flags != mod.flags {
340 keyEvent(id, -1, C.NSKeyDown, mod.code, flags)
341 }
342 if lastFlags&mod.flags == mod.flags && flags&mod.flags != mod.flags {
343 keyEvent(id, -1, C.NSKeyUp, mod.code, flags)
344 }
345 }
346 lastFlags = flags
347 }
348
349 var lastFlags uint32
350
351 func sendLifecycle(id uintptr, setter func(*lifecycler.State, bool), val bool) {
352 theScreen.mu.Lock()
353 w := theScreen.windows[id]
354 theScreen.mu.Unlock()
355
356 if w == nil {
357 return
358 }
359 setter(&w.lifecycler, val)
360 w.lifecycler.SendEvent(w, w.glctx)
361 }
362
363 func sendLifecycleAll(dead bool) {
364 windows := []*windowImpl{}
365
366 theScreen.mu.Lock()
367 for _, w := range theScreen.windows {
368 windows = append(windows, w)
369 }
370 theScreen.mu.Unlock()
371
372 for _, w := range windows {
373 w.lifecycler.SetFocused(false)
374 w.lifecycler.SetVisible(false)
375 if dead {
376 w.lifecycler.SetDead(true)
377 }
378 w.lifecycler.SendEvent(w, w.glctx)
379 }
380 }
381
382 //export lifecycleDeadAll
383 func lifecycleDeadAll() { sendLifecycleAll(true) }
384
385 //export lifecycleHideAll
386 func lifecycleHideAll() { sendLifecycleAll(false) }
387
388 //export lifecycleVisible
389 func lifecycleVisible(id uintptr, val bool) {
390 sendLifecycle(id, (*lifecycler.State).SetVisible, val)
391 }
392
393 //export lifecycleFocused
394 func lifecycleFocused(id uintptr, val bool) {
395 sendLifecycle(id, (*lifecycler.State).SetFocused, val)
396 }
397
398 // cocoaRune marks the Carbon/Cocoa private-range unicode rune representing
399 // a non-unicode key event to -1, used for Rune in the key package.
400 //
401 // http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/CORPCHAR.TXT
402 func cocoaRune(r rune) rune {
403 if '\uE000' <= r && r <= '\uF8FF' {
404 return -1
405 }
406 return r
407 }
408
409 // cocoaKeyCode converts a Carbon/Cocoa virtual key code number
410 // into the standard keycodes used by the key package.
411 //
412 // To get a sense of the key map, see the diagram on
413 //
414 // http://boredzo.org/blog/archives/2007-05-22/virtual-key-codes
415 func cocoaKeyCode(vkcode uint16) key.Code {
416 switch vkcode {
417 case C.kVK_ANSI_A:
418 return key.CodeA
419 case C.kVK_ANSI_B:
420 return key.CodeB
421 case C.kVK_ANSI_C:
422 return key.CodeC
423 case C.kVK_ANSI_D:
424 return key.CodeD
425 case C.kVK_ANSI_E:
426 return key.CodeE
427 case C.kVK_ANSI_F:
428 return key.CodeF
429 case C.kVK_ANSI_G:
430 return key.CodeG
431 case C.kVK_ANSI_H:
432 return key.CodeH
433 case C.kVK_ANSI_I:
434 return key.CodeI
435 case C.kVK_ANSI_J:
436 return key.CodeJ
437 case C.kVK_ANSI_K:
438 return key.CodeK
439 case C.kVK_ANSI_L:
440 return key.CodeL
441 case C.kVK_ANSI_M:
442 return key.CodeM
443 case C.kVK_ANSI_N:
444 return key.CodeN
445 case C.kVK_ANSI_O:
446 return key.CodeO
447 case C.kVK_ANSI_P:
448 return key.CodeP
449 case C.kVK_ANSI_Q:
450 return key.CodeQ
451 case C.kVK_ANSI_R:
452 return key.CodeR
453 case C.kVK_ANSI_S:
454 return key.CodeS
455 case C.kVK_ANSI_T:
456 return key.CodeT
457 case C.kVK_ANSI_U:
458 return key.CodeU
459 case C.kVK_ANSI_V:
460 return key.CodeV
461 case C.kVK_ANSI_W:
462 return key.CodeW
463 case C.kVK_ANSI_X:
464 return key.CodeX
465 case C.kVK_ANSI_Y:
466 return key.CodeY
467 case C.kVK_ANSI_Z:
468 return key.CodeZ
469 case C.kVK_ANSI_1:
470 return key.Code1
471 case C.kVK_ANSI_2:
472 return key.Code2
473 case C.kVK_ANSI_3:
474 return key.Code3
475 case C.kVK_ANSI_4:
476 return key.Code4
477 case C.kVK_ANSI_5:
478 return key.Code5
479 case C.kVK_ANSI_6:
480 return key.Code6
481 case C.kVK_ANSI_7:
482 return key.Code7
483 case C.kVK_ANSI_8:
484 return key.Code8
485 case C.kVK_ANSI_9:
486 return key.Code9
487 case C.kVK_ANSI_0:
488 return key.Code0
489 // TODO: move the rest of these codes to constants in key.go
490 // if we are happy with them.
491 case C.kVK_Return:
492 return key.CodeReturnEnter
493 case C.kVK_Escape:
494 return key.CodeEscape
495 case C.kVK_Delete:
496 return key.CodeDeleteBackspace
497 case C.kVK_Tab:
498 return key.CodeTab
499 case C.kVK_Space:
500 return key.CodeSpacebar
501 case C.kVK_ANSI_Minus:
502 return key.CodeHyphenMinus
503 case C.kVK_ANSI_Equal:
504 return key.CodeEqualSign
505 case C.kVK_ANSI_LeftBracket:
506 return key.CodeLeftSquareBracket
507 case C.kVK_ANSI_RightBracket:
508 return key.CodeRightSquareBracket
509 case C.kVK_ANSI_Backslash:
510 return key.CodeBackslash
511 // 50: Keyboard Non-US "#" and ~
512 case C.kVK_ANSI_Semicolon:
513 return key.CodeSemicolon
514 case C.kVK_ANSI_Quote:
515 return key.CodeApostrophe
516 case C.kVK_ANSI_Grave:
517 return key.CodeGraveAccent
518 case C.kVK_ANSI_Comma:
519 return key.CodeComma
520 case C.kVK_ANSI_Period:
521 return key.CodeFullStop
522 case C.kVK_ANSI_Slash:
523 return key.CodeSlash
524 case C.kVK_CapsLock:
525 return key.CodeCapsLock
526 case C.kVK_F1:
527 return key.CodeF1
528 case C.kVK_F2:
529 return key.CodeF2
530 case C.kVK_F3:
531 return key.CodeF3
532 case C.kVK_F4:
533 return key.CodeF4
534 case C.kVK_F5:
535 return key.CodeF5
536 case C.kVK_F6:
537 return key.CodeF6
538 case C.kVK_F7:
539 return key.CodeF7
540 case C.kVK_F8:
541 return key.CodeF8
542 case C.kVK_F9:
543 return key.CodeF9
544 case C.kVK_F10:
545 return key.CodeF10
546 case C.kVK_F11:
547 return key.CodeF11
548 case C.kVK_F12:
549 return key.CodeF12
550 // 70: PrintScreen
551 // 71: Scroll Lock
552 // 72: Pause
553 // 73: Insert
554 case C.kVK_Home:
555 return key.CodeHome
556 case C.kVK_PageUp:
557 return key.CodePageUp
558 case C.kVK_ForwardDelete:
559 return key.CodeDeleteForward
560 case C.kVK_End:
561 return key.CodeEnd
562 case C.kVK_PageDown:
563 return key.CodePageDown
564 case C.kVK_RightArrow:
565 return key.CodeRightArrow
566 case C.kVK_LeftArrow:
567 return key.CodeLeftArrow
568 case C.kVK_DownArrow:
569 return key.CodeDownArrow
570 case C.kVK_UpArrow:
571 return key.CodeUpArrow
572 case C.kVK_ANSI_KeypadClear:
573 return key.CodeKeypadNumLock
574 case C.kVK_ANSI_KeypadDivide:
575 return key.CodeKeypadSlash
576 case C.kVK_ANSI_KeypadMultiply:
577 return key.CodeKeypadAsterisk
578 case C.kVK_ANSI_KeypadMinus:
579 return key.CodeKeypadHyphenMinus
580 case C.kVK_ANSI_KeypadPlus:
581 return key.CodeKeypadPlusSign
582 case C.kVK_ANSI_KeypadEnter:
583 return key.CodeKeypadEnter
584 case C.kVK_ANSI_Keypad1:
585 return key.CodeKeypad1
586 case C.kVK_ANSI_Keypad2:
587 return key.CodeKeypad2
588 case C.kVK_ANSI_Keypad3:
589 return key.CodeKeypad3
590 case C.kVK_ANSI_Keypad4:
591 return key.CodeKeypad4
592 case C.kVK_ANSI_Keypad5:
593 return key.CodeKeypad5
594 case C.kVK_ANSI_Keypad6:
595 return key.CodeKeypad6
596 case C.kVK_ANSI_Keypad7:
597 return key.CodeKeypad7
598 case C.kVK_ANSI_Keypad8:
599 return key.CodeKeypad8
600 case C.kVK_ANSI_Keypad9:
601 return key.CodeKeypad9
602 case C.kVK_ANSI_Keypad0:
603 return key.CodeKeypad0
604 case C.kVK_ANSI_KeypadDecimal:
605 return key.CodeKeypadFullStop
606 case C.kVK_ANSI_KeypadEquals:
607 return key.CodeKeypadEqualSign
608 case C.kVK_F13:
609 return key.CodeF13
610 case C.kVK_F14:
611 return key.CodeF14
612 case C.kVK_F15:
613 return key.CodeF15
614 case C.kVK_F16:
615 return key.CodeF16
616 case C.kVK_F17:
617 return key.CodeF17
618 case C.kVK_F18:
619 return key.CodeF18
620 case C.kVK_F19:
621 return key.CodeF19
622 case C.kVK_F20:
623 return key.CodeF20
624 // 116: Keyboard Execute
625 case C.kVK_Help:
626 return key.CodeHelp
627 // 118: Keyboard Menu
628 // 119: Keyboard Select
629 // 120: Keyboard Stop
630 // 121: Keyboard Again
631 // 122: Keyboard Undo
632 // 123: Keyboard Cut
633 // 124: Keyboard Copy
634 // 125: Keyboard Paste
635 // 126: Keyboard Find
636 case C.kVK_Mute:
637 return key.CodeMute
638 case C.kVK_VolumeUp:
639 return key.CodeVolumeUp
640 case C.kVK_VolumeDown:
641 return key.CodeVolumeDown
642 // 130: Keyboard Locking Caps Lock
643 // 131: Keyboard Locking Num Lock
644 // 132: Keyboard Locking Scroll Lock
645 // 133: Keyboard Comma
646 // 134: Keyboard Equal Sign
647 // ...: Bunch of stuff
648 case C.kVK_Control:
649 return key.CodeLeftControl
650 case C.kVK_Shift:
651 return key.CodeLeftShift
652 case C.kVK_Option:
653 return key.CodeLeftAlt
654 case C.kVK_Command:
655 return key.CodeLeftGUI
656 case C.kVK_RightControl:
657 return key.CodeRightControl
658 case C.kVK_RightShift:
659 return key.CodeRightShift
660 case C.kVK_RightOption:
661 return key.CodeRightAlt
662 // TODO key.CodeRightGUI
663 default:
664 return key.CodeUnknown
665 }
666 }
667
668 func surfaceCreate() error {
669 return errors.New("gldriver: surface creation not implemented on darwin")
670 }