Debian Codegraph @

shiny/driver/mtldriver/mtldriver.go

raw symbols SCIP
1 // Copyright 2019 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 && cgo
6
7 // Package mtldriver provides a Metal driver for accessing a screen.
8 //
9 // At this time, the Metal API is used only to present the final pixels
10 // to the screen. All rendering is performed on the CPU via the image/draw
11 // algorithms. Future work is to use mtl.Buffer, mtl.Texture, etc., and
12 // do more of the rendering work on the GPU.
13 package mtldriver
14
15 import (
16 "runtime"
17 "unsafe"
18
19 "dmitri.shuralyov.com/gpu/mtl"
20 "github.com/go-gl/glfw/v3.3/glfw"
21 "golang.org/x/exp/shiny/driver/internal/errscreen"
22 "golang.org/x/exp/shiny/driver/mtldriver/internal/appkit"
23 "golang.org/x/exp/shiny/driver/mtldriver/internal/coreanim"
24 "golang.org/x/exp/shiny/screen"
25 "golang.org/x/mobile/event/key"
26 "golang.org/x/mobile/event/mouse"
27 "golang.org/x/mobile/event/paint"
28 "golang.org/x/mobile/event/size"
29 )
30
31 func init() {
32 runtime.LockOSThread()
33 }
34
35 // Main is called by the program's main function to run the graphical
36 // application.
37 //
38 // It calls f on the Screen, possibly in a separate goroutine, as some OS-
39 // specific libraries require being on 'the main thread'. It returns when f
40 // returns.
41 func Main(f func(screen.Screen)) {
42 if err := main(f); err != nil {
43 f(errscreen.Stub(err))
44 }
45 }
46
47 func main(f func(screen.Screen)) error {
48 device, err := mtl.CreateSystemDefaultDevice()
49 if err != nil {
50 return err
51 }
52 err = glfw.Init()
53 if err != nil {
54 return err
55 }
56 defer glfw.Terminate()
57 glfw.WindowHint(glfw.ClientAPI, glfw.NoAPI)
58 {
59 // TODO(dmitshur): Delete this when https://github.com/go-gl/glfw/issues/272 is resolved.
60 // Post an empty event from the main thread before it can happen in a non-main thread,
61 // to work around https://github.com/glfw/glfw/issues/1649.
62 glfw.PostEmptyEvent()
63 }
64 var (
65 done = make(chan struct{})
66 newWindowCh = make(chan newWindowReq, 1)
67 releaseWindowCh = make(chan releaseWindowReq, 1)
68 )
69 go func() {
70 f(&screenImpl{
71 newWindowCh: newWindowCh,
72 })
73 close(done)
74 glfw.PostEmptyEvent() // Break main loop out of glfw.WaitEvents so it can receive on done.
75 }()
76 for {
77 select {
78 case <-done:
79 return nil
80 case req := <-newWindowCh:
81 w, err := newWindow(device, releaseWindowCh, req.opts)
82 req.respCh <- newWindowResp{w, err}
83 case req := <-releaseWindowCh:
84 req.window.Destroy()
85 req.respCh <- struct{}{}
86 default:
87 glfw.WaitEvents()
88 }
89 }
90 }
91
92 type newWindowReq struct {
93 opts *screen.NewWindowOptions
94 respCh chan newWindowResp
95 }
96
97 type newWindowResp struct {
98 w screen.Window
99 err error
100 }
101
102 type releaseWindowReq struct {
103 window *glfw.Window
104 respCh chan struct{}
105 }
106
107 // newWindow creates a new GLFW window.
108 // It must be called on the main thread.
109 func newWindow(device mtl.Device, releaseWindowCh chan releaseWindowReq, opts *screen.NewWindowOptions) (screen.Window, error) {
110 width, height := optsSize(opts)
111 window, err := glfw.CreateWindow(width, height, opts.GetTitle(), nil, nil)
112 if err != nil {
113 return nil, err
114 }
115
116 ml := coreanim.MakeMetalLayer()
117 ml.SetDevice(device)
118 ml.SetPixelFormat(mtl.PixelFormatBGRA8UNorm)
119 ml.SetMaximumDrawableCount(3)
120 ml.SetDisplaySyncEnabled(true)
121 cv := appkit.NewWindow(unsafe.Pointer(window.GetCocoaWindow())).ContentView()
122 cv.SetLayer(ml)
123 cv.SetWantsLayer(true)
124
125 w := &windowImpl{
126 device: device,
127 window: window,
128 releaseWindowCh: releaseWindowCh,
129 ml: ml,
130 cq: device.MakeCommandQueue(),
131 }
132
133 // Set callbacks.
134 framebufferSizeCallback := func(_ *glfw.Window, width, height int) {
135 w.Send(size.Event{
136 WidthPx: width,
137 HeightPx: height,
138 // TODO(dmitshur): ppp,
139 })
140 w.Send(paint.Event{External: true})
141 }
142 window.SetFramebufferSizeCallback(framebufferSizeCallback)
143 window.SetCursorPosCallback(func(_ *glfw.Window, x, y float64) {
144 const scale = 2 // TODO(dmitshur): compute dynamically
145 w.Send(mouse.Event{X: float32(x * scale), Y: float32(y * scale)})
146 })
147 window.SetMouseButtonCallback(func(_ *glfw.Window, b glfw.MouseButton, a glfw.Action, mods glfw.ModifierKey) {
148 btn := glfwMouseButton(b)
149 if btn == mouse.ButtonNone {
150 return
151 }
152 const scale = 2 // TODO(dmitshur): compute dynamically
153 x, y := window.GetCursorPos()
154 w.Send(mouse.Event{
155 X: float32(x * scale), Y: float32(y * scale),
156 Button: btn,
157 Direction: glfwMouseDirection(a),
158 // TODO(dmitshur): set Modifiers
159 })
160 })
161 window.SetKeyCallback(func(_ *glfw.Window, k glfw.Key, _ int, a glfw.Action, mods glfw.ModifierKey) {
162 code := glfwKeyCode(k)
163 if code == key.CodeUnknown {
164 return
165 }
166 w.Send(key.Event{
167 Code: code,
168 Direction: glfwKeyDirection(a),
169 // TODO(dmitshur): set Modifiers
170 })
171 })
172 // TODO(dmitshur): set CharModsCallback to catch text (runes) that are typed,
173 // and perhaps try to unify key pressed + character typed into single event
174 window.SetCloseCallback(func(*glfw.Window) {
175 w.lifecycler.SetDead(true)
176 w.lifecycler.SendEvent(w, nil)
177 })
178
179 // TODO(dmitshur): more fine-grained tracking of whether window is visible and/or focused
180 w.lifecycler.SetDead(false)
181 w.lifecycler.SetVisible(true)
182 w.lifecycler.SetFocused(true)
183 w.lifecycler.SendEvent(w, nil)
184
185 // Send the initial size and paint events.
186 width, height = window.GetFramebufferSize()
187 framebufferSizeCallback(window, width, height)
188
189 return w, nil
190 }
191
192 func optsSize(opts *screen.NewWindowOptions) (width, height int) {
193 width, height = 1024/2, 768/2
194 if opts != nil {
195 if opts.Width > 0 {
196 width = opts.Width
197 }
198 if opts.Height > 0 {
199 height = opts.Height
200 }
201 }
202 return width, height
203 }
204
205 func glfwMouseButton(button glfw.MouseButton) mouse.Button {
206 switch button {
207 case glfw.MouseButtonLeft:
208 return mouse.ButtonLeft
209 case glfw.MouseButtonRight:
210 return mouse.ButtonRight
211 case glfw.MouseButtonMiddle:
212 return mouse.ButtonMiddle
213 default:
214 return mouse.ButtonNone
215 }
216 }
217
218 func glfwMouseDirection(action glfw.Action) mouse.Direction {
219 switch action {
220 case glfw.Press:
221 return mouse.DirPress
222 case glfw.Release:
223 return mouse.DirRelease
224 default:
225 panic("unreachable")
226 }
227 }
228
229 func glfwKeyCode(k glfw.Key) key.Code {
230 // TODO(dmitshur): support more keys
231 switch k {
232 case glfw.KeyEnter:
233 return key.CodeReturnEnter
234 case glfw.KeyEscape:
235 return key.CodeEscape
236 default:
237 return key.CodeUnknown
238 }
239 }
240
241 func glfwKeyDirection(action glfw.Action) key.Direction {
242 switch action {
243 case glfw.Press:
244 return key.DirPress
245 case glfw.Release:
246 return key.DirRelease
247 case glfw.Repeat:
248 return key.DirNone
249 default:
250 panic("unreachable")
251 }
252 }