main f2d166b

session.go RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 25

Tags 10

↑↓ moveenter openesc close