1package app
2
3import (
4 "bufio"
5 "context"
6 "errors"
7 "os"
8 "runtime"
9 "sync"
10 "time"
11
12 "github.com/bnema/neferwl/internal/adapters/captureallow"
13 "github.com/bnema/neferwl/internal/adapters/clock"
14 "github.com/bnema/neferwl/internal/adapters/config"
15 "github.com/bnema/neferwl/internal/adapters/drm"
16 "github.com/bnema/neferwl/internal/adapters/headlessinput"
17 "github.com/bnema/neferwl/internal/adapters/launcher"
18 "github.com/bnema/neferwl/internal/adapters/libinput"
19 "github.com/bnema/neferwl/internal/adapters/logging"
20 "github.com/bnema/neferwl/internal/adapters/powerkey"
21 "github.com/bnema/neferwl/internal/adapters/sched"
22 "github.com/bnema/neferwl/internal/adapters/screensaver"
23 "github.com/bnema/neferwl/internal/adapters/sessionsecurity"
24 "github.com/bnema/neferwl/internal/adapters/statefile"
25 "github.com/bnema/neferwl/internal/adapters/vulkan"
26 "github.com/bnema/neferwl/internal/adapters/watchdog"
27 "github.com/bnema/neferwl/internal/adapters/wayland"
28 "github.com/bnema/neferwl/internal/adapters/workspaceid"
29 "github.com/bnema/neferwl/internal/adapters/xkb"
30 "github.com/bnema/neferwl/internal/adapters/xwayland"
31 "github.com/bnema/neferwl/internal/core"
32 "github.com/bnema/neferwl/internal/ports"
33 "github.com/bnema/zerowrap"
34)
35
36// session holds the dependencies assembleSession acquired and wired; run
37// starts them. The session owns hw, curs and xdisplay (released by close)
38// until run ends; the keymap and the wayland server own themselves.
39type session struct {
40 opts Options
41 log zerowrap.Logger
42
43 clock ports.Clock
44 security *sessionsecurity.Gate
45 p *pipes
46 sizes [][2]int
47 path string
48
49 hw *drmBackend
50 km *xkb.Keymap
51 core *core.Core
52 dmabuf ports.DMABufSupport
53 wsIDs *workspaceid.IDs
54 captureAllow *captureallow.Store
55 server *wayland.Server
56 childEnv []string
57 statePath string
58 xdisplay *xwayland.Display
59 child *launcher.Launcher
60 curs *cursors
61
62 newRenderer func(w, h int) (ports.Renderer, error)
63}
64
65// assembleSession acquires and wires every dependency in startup order and
66// starts no long-lived worker.
67//
68// Invariant: wayland.New is the last fallible step. *wayland.Server has no
69// Close: its sockets are released only by Server.Run. Every later step
70// (statefile.Path, openXwayland, launcher.New, newCursors) degrades with a
71// warning or nil instead of failing. A failure therefore releases exactly
72// the DRM backend and the keymap (abort); nothing else is owned yet.
73func assembleSession(ctx context.Context, opts Options) (s *session, err error) {
74 s = &session{opts: opts, log: logging.For(ctx, "app"), clock: clock.System{}, security: &sessionsecurity.Gate{}}
75 defer func() {
76 if err != nil {
77 s.abort()
78 s = nil
79 }
80 }()
81 log := s.log
82 s.sizes = opts.Sizes
83 if len(s.sizes) == 0 {
84 s.sizes = [][2]int{{1920, 1080}}
85 }
86 if opts.Backend == "drm" {
87 if s.hw, err = openDRM(ctx, opts.Config); err != nil {
88 return s, err
89 }
90 }
91 s.p = newPipes(s.hw != nil)
92 // core() carries channels only; the gate, clock and terminal flag are
93 // explicit core.Options.
94 if s.core, err = core.New(opts.Config, s.p.core(), core.Options{Security: s.security, Clock: s.clock, Terminal: !opts.NoTerminal}); err != nil {
95 return s, err
96 }
97 if s.km, err = xkb.New(xkb.RMLVO{Layout: opts.Config.Keyboard.Layout, Variant: opts.Config.Keyboard.Variant, Options: opts.Config.Keyboard.Options}); err != nil {
98 return s, err
99 }
100 runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
101 // Every output renders on the same GPU: its formats are the clients'.
102 s.dmabuf = vulkan.Probe()
103 log.Info().Int("formats", len(s.dmabuf.Formats)).Msg("dmabuf")
104 // One launch prefix for ext-workspace ids and the state file.
105 s.wsIDs = workspaceid.New()
106 // The path is fixed: a config key would let a program of the same user
107 // widen who may capture.
108 // Production: the fixed path, a root-owned file. Only tests set a path,
109 // and an owner for it.
110 captureAllowLog := logging.For(ctx, "captureallow")
111 if opts.captureAllowPath != "" {
112 s.captureAllow = captureallow.NewStoreOwnedBy(opts.captureAllowPath, opts.captureAllowOwner, captureAllowLog)
113 } else {
114 s.captureAllow = captureallow.NewStore(captureallow.DefaultPath, captureAllowLog)
115 }
116 if s.server, err = wayland.New(wayland.Options{
117 CaptureAllow: s.captureAllow,
118 WorkspaceIDs: s.wsIDs,
119 Security: s.security,
120 RuntimeDir: runtimeDir,
121 DMABuf: s.dmabuf,
122 SyncobjNode: renderNode(s.dmabuf.Device),
123 Keymap: s.km.String(),
124 RepeatRate: opts.Config.Keyboard.RepeatRate,
125 RepeatDelay: opts.Config.Keyboard.RepeatDelay,
126 }, s.p.wayland(), logging.For(ctx, "wayland")); err != nil {
127 return s, err
128 }
129 log.Info().Str("WAYLAND_DISPLAY", s.server.SocketName()).Msg("listening")
130 s.childEnv = launcher.ChildEnv(os.Environ(), s.server.SocketName(), runtimeDir, cursorSize())
131 statePath, serr := statefile.Path(runtimeDir, s.server.SocketName())
132 if serr != nil {
133 log.Warn().Err(serr).Msg("state file disabled")
134 } else {
135 s.statePath = statePath
136 s.childEnv = append(s.childEnv, statefile.Env+"="+statePath)
137 }
138 if s.xdisplay = openXwayland(ctx, opts, s.childEnv, logging.For(ctx, "xwayland")); s.xdisplay != nil {
139 s.childEnv = append(s.childEnv, "DISPLAY="+s.xdisplay.Name())
140 }
141 s.child = launcher.New(s.childEnv, s.security, logging.For(ctx, "launcher"))
142 s.curs = newCursors(s.clock, opts.Config.Cursor.HideAfter)
143 s.path = opts.ConfigPath
144 if s.path == "" {
145 s.path = config.DefaultPath()
146 }
147 renderLog := logging.For(ctx, "render")
148 if s.hw != nil {
149 s.newRenderer = newVulkanRenderer(renderLog, false, false)
150 } else {
151 s.newRenderer = newVulkanRenderer(renderLog, true, opts.ScreenshotRaw)
152 }
153 return s, nil
154}
155
156// abort releases what assembly acquired before ownership passed on: the DRM
157// backend and the keymap. It runs only when assembly fails, before
158// anything else is owned.
159func (s *session) abort() {
160 if s.hw != nil {
161 s.hw.close()
162 }
163 if s.km != nil {
164 s.km.Close()
165 }
166}
167
168// close releases what the session owns after its workers have joined. The
169// keymap and the wayland server are not here: the input goroutine and
170// Server.Run own them.
171func (s *session) close() {
172 s.curs.stop()
173 if s.xdisplay != nil {
174 s.xdisplay.Close()
175 }
176 if s.hw != nil {
177 s.hw.close()
178 }
179}
180
181// newVulkanRenderer returns the concrete Vulkan renderer factory. Virtual
182// outputs have no display to list modifiers, so a headless renderer is told
183// it drives one: without it a real GPU refuses the HDR targets and the
184// output falls back to SDR. readback makes the HDR targets readable
185// (HDRPixels). These settings are Vulkan-only and not on ports.Renderer.
186func newVulkanRenderer(log zerowrap.Logger, virtual, readback bool) func(w, h int) (ports.Renderer, error) {
187 return func(w, h int) (ports.Renderer, error) {
188 r, err := vulkan.New(w, h)
189 if err != nil {
190 return nil, err
191 }
192 r.SetLogger(log)
193 log.Info().Str("queue_priority", r.QueuePriority()).Msg("vulkan queue")
194 r.SetVirtualOutput(virtual)
195 if readback {
196 r.SetHDRReadback(true)
197 }
198 return r, nil
199 }
200}
201
202// run starts the workers and waits for the session to end; it releases the
203// session's resources after every worker has joined.
204func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent)) error {
205 defer s.close()
206 ctx, cancel := context.WithCancel(ctx)
207 defer cancel()
208 opts, log, p, hw, km, security := s.opts, s.log, s.p, s.hw, s.km, s.security
209 childEnv, curs, xdisplay, statePath := s.childEnv, s.curs, s.xdisplay, s.statePath
210 server, captureAllow, c, child, wsIDs, dmabuf, sizes, path := s.server, s.captureAllow, s.core, s.child, s.wsIDs, s.dmabuf, s.sizes, s.path
211 if opts.Session {
212 launcher.ExportSession(ctx, childEnv, logging.For(ctx, "launcher"))
213 launcher.NotifyReady(os.Getenv("NOTIFY_SOCKET"), logging.For(ctx, "launcher"))
214 defer launcher.UnexportSession(childEnv, logging.For(ctx, "launcher"))
215 }
216 if inject != nil {
217 inject(p.input)
218 }
219 var workers sync.WaitGroup
220 workers.Add(8)
221 done := make(chan error, 8)
222 go func() {
223 defer workers.Done()
224 done <- config.Watch(ctx, path, p.watched, logging.For(ctx, "config"))
225 }()
226 if p.scales != nil {
227 workers.Add(1)
228 go func() {
229 defer workers.Done()
230 core.PersistScales(ctx, p.scales, config.ScaleStore{Path: path}, launcher.NewNotifier(ctx, childEnv, logging.For(ctx, "launcher")), s.clock, time.Second)
231 }()
232 }
233 workers.Add(1)
234 go func() {
235 defer workers.Done()
236 relayConfig(ctx, opts.Config, p.watched, p.filtered, p.keymaps, p.deviceConfigs, curs, p.commands, logging.For(ctx, "config"))
237 }()
238 script := make(chan string)
239 go func() {
240 defer workers.Done()
241 if hw != nil {
242 // Core sends the first layout once DRM reports the outputs.
243 var layout ports.Layout
244 select {
245 case layout = <-p.layouts:
246 case <-ctx.Done():
247 km.Close()
248 return
249 }
250 done <- safe("input", func() error {
251 if opts.Config.Performance.Realtime {
252 runtime.LockOSThread()
253 // Let this dedicated thread exit with its scheduling policy.
254 schedLog := logging.For(ctx, "sched")
255 if err := sched.Realtime(schedLog); err != nil {
256 schedLog.Warn().Err(err).Msg("input scheduling")
257 }
258 }
259 return libinput.Run(ctx, libinput.Options{
260 Security: security,
261 Seat: hw.seat,
262 SeatName: hw.seat.Name(),
263 Keymap: km,
264 Keymaps: p.keymaps,
265 Layout: layout,
266 Layouts: p.layouts,
267 Constraints: p.constraints,
268 DeviceConfig: opts.Config.InputDevicesConfig,
269 DeviceConfigs: p.deviceConfigs,
270 Active: hw.seat.Subscribe(),
271 MoveCursor: curs.move,
272 Log: logging.For(ctx, "input"),
273 LogMotion: logging.Enabled(ctx, "input-motion"),
274 LogKeys: logging.Enabled(ctx, "input-keys"),
275 }, p.input)
276 })
277 return
278 }
279 if err := headlessinput.RunSecure(ctx, km, p.keymaps, script, p.input, p.layouts, func(o string, x, y float64) { curs.move(o, x, y, true) }, logging.For(ctx, "input"), security); err != nil && !errors.Is(err, context.Canceled) {
280 select {
281 case done <- err:
282 case <-ctx.Done():
283 }
284 }
285 }()
286 if opts.Script != nil {
287 go func() { <-ctx.Done(); _ = opts.Script.Close() }()
288 go func() {
289 defer close(script)
290 scanner := bufio.NewScanner(opts.Script)
291 for scanner.Scan() {
292 select {
293 case <-ctx.Done():
294 return
295 case script <- scanner.Text():
296 }
297 }
298 if err := scanner.Err(); err != nil {
299 log.Warn().Err(err).Msg("reading input script")
300 }
301 }()
302 } else {
303 close(script)
304 }
305 go func() { defer workers.Done(); done <- server.Run(ctx) }()
306 if dir := logging.Dir(ctx); dir != "" {
307 workers.Add(1)
308 go func() {
309 defer workers.Done()
310 watchdog.Run(ctx, func() []watchdog.Probe {
311 probes := []watchdog.Probe{
312 {Name: "wayland", Ping: func() { server.Ping(ctx) }},
313 {Name: "core", Ping: func() { c.Ping(ctx) }},
314 }
315 if hw != nil {
316 probes = append(probes, hw.watchdogProbes()...)
317 }
318 return probes
319 }, watchdog.Options{Dir: dir, Every: time.Second, Timeout: 3 * time.Second, Log: logging.For(ctx, "app")})
320 }()
321 }
322 go func() {
323 defer workers.Done()
324 // Without a watch the allowlist stays as loaded: restart to apply.
325 if err := captureAllow.Run(ctx); err != nil {
326 log.Warn().Err(err).Msg("capture allowlist not watched, restart to apply changes")
327 }
328 }()
329 go func() { defer workers.Done(); done <- child.Run(ctx, p.spawn) }()
330 go func() { defer workers.Done(); done <- c.Run(ctx) }()
331 if xdisplay != nil {
332 workers.Add(1)
333 // X11 failing leaves the Wayland session running; Run logs why.
334 go func() { defer workers.Done(); _ = xdisplay.Run(ctx) }()
335 }
336 if statePath != "" {
337 workers.Add(1)
338 go func() {
339 defer workers.Done()
340 if err := statefile.Run(ctx, statePath, p.states, wsIDs, logging.For(ctx, "statefile")); err != nil {
341 // Scripts lose their state; the session goes on.
342 log.Warn().Err(err).Msg("state file disabled")
343 }
344 }()
345 }
346 go func() {
347 defer workers.Done()
348 consumeScenes(ctx, p.scenes, p.configErrors, opts.testScenes, p.renderScenes)
349 }()
350 workers.Add(1)
351 go func() { defer workers.Done(); relayPresented(ctx, p.flips, p.presented, p.frames) }()
352
353 go func() {
354 defer workers.Done()
355 outputIO := p.outputs(security)
356 apply := newOutputApply(core.NewOutputOverrides(opts.Config, hw == nil), logging.For(ctx, "app"))
357 if hw != nil {
358 done <- safe("output", func() error {
359 want := func(cfg ports.Config) drm.Want {
360 w := wantFromConfig(cfg)
361 w.Sampled = dmabuf.Formats
362 w.TraceFlips = logging.Enabled(ctx, "drm-flip")
363 return w
364 }
365 return hw.runOutputs(ctx, want, opts.Config, apply, outputIO, curs, s.newRenderer, logging.For(ctx, "drm"))
366 })
367 return
368 }
369 done <- runHeadless(ctx, headlessOptions{sizes: sizes, shots: opts.ScreenshotDir, hdr: opts.HeadlessHDR, raw: opts.ScreenshotRaw}, apply, outputIO, curs, s.newRenderer, logging.For(ctx, "render"))
370 }()
371
372 if hw != nil {
373 workers.Add(1)
374 go func() { defer workers.Done(); done <- safe("seat", func() error { return hw.seat.Run(ctx) }) }()
375 // Only a real session serves the session bus: headless runs would take
376 // the name from the desktop they run in.
377 workers.Add(1)
378 go func() {
379 defer workers.Done()
380 reports := screensaver.Reports{Held: p.idleInhibited, Activity: p.idleActivity}
381 screensaver.Serve(ctx, "", reports, busRetry, logging.For(ctx, "screensaver"))
382 }()
383 // The same goes for the system bus: logind's locks keep the power
384 // keys from acting before a bind sees them.
385 workers.Add(1)
386 go func() {
387 defer workers.Done()
388 powerkey.Serve(ctx, "", busRetry, logging.For(ctx, "powerkey"))
389 }()
390 }
391 var result error
392 select {
393 case <-ctx.Done():
394 if errors.Is(context.Cause(ctx), errTimeout) {
395 log.Info().Str("reason", "timeout").Dur("after", opts.Timeout).Msg("stopping")
396 }
397 case result = <-done:
398 log.Info().AnErr("cause", result).Msg("stopping")
399 }
400 cancel()
401 workers.Wait()
402 // The wayland server has stopped: no request can be queued any more.
403 drainCaptures(ctx, p.captures, nil)
404 // A keymap the input goroutine never took is still ours to free.
405 select {
406 case km := <-p.keymaps:
407 km.Close()
408 default:
409 }
410 for len(done) > 0 {
411 err := <-done
412 if result == nil && err != nil {
413 result = err
414 }
415 }
416 if errors.Is(result, core.ErrQuit) || errors.Is(result, libinput.ErrEmergencyQuit) {
417 return nil
418 }
419 return result
420}