1// Package selection is the layer-shell capture selector, drawn with NeferGUI.
2//
3// Select opens one transparent overlay layer surface on every output. Each
4// dims everything except the dragged region, draws thin accent lines and a
5// size label, and the first decision from any of them is returned. It needs no
6// screenshot: the live compositor shows through the transparent surface.
7//
8// One overlay per output: every monitor is selectable at once. A Wayland
9// client cannot hold exclusive keyboard focus on several surfaces, so the first
10// output's overlay is keyboard-exclusive and the others take the keyboard on
11// demand (on click). Each overlay is a separate layer surface on its own
12// Wayland connection, with its own model on its own owner loop; they share only
13// a first-decision-wins session.
14package selection
15
16import (
17 "context"
18 _ "embed"
19 "errors"
20 "fmt"
21 "image"
22 "sync"
23
24 "github.com/bnema/neferclient"
25
26 "github.com/bnema/nefercap/internal/adapters/layerui"
27 "github.com/bnema/nefercap/internal/adapters/uistyle"
28 "github.com/bnema/nefercap/internal/core"
29 "github.com/bnema/nefercap/internal/ports"
30)
31
32//go:embed style.css
33var styleSheet string
34
35// DefaultFPS is the recording frame rate assigned to record selections.
36const DefaultFPS = 30
37
38// namespace is an opaque role hint for the compositor, not an authorization.
39const namespace = "nefercap-selector"
40
41// MaxOutputs is the most outputs one selection covers: one per digit key.
42const MaxOutputs = 9
43
44// ErrTooManyOutputs reports more outputs than MaxOutputs. Nothing is opened.
45var ErrTooManyOutputs = errors.New("selection: too many outputs")
46
47var errNoOutputs = fmt.Errorf("selection: no outputs to select: %w", ports.ErrOutputNotFound)
48
49// Selector shows the layer-shell selection overlay.
50type Selector struct {
51 mode ports.Mode
52 video ports.VideoSettings
53 workspaces []ports.Workspace
54 grid bool
55 toggle bool
56 noIndicator bool
57 backdrops map[uint32]image.Image // frozen screens by output ID
58 frozen bool // the accepted selection showed the frozen screen
59}
60
61var _ ports.Selector = (*Selector)(nil)
62
63// New returns a selector for mode. Record selections carry video; a zero FPS
64// becomes DefaultFPS. workspaces is ext-workspace metadata: the W key is
65// offered only for the Active workspace with a valid (nonzero) ID on the output
66// an overlay covers. Other workspaces are never offered and nothing is
67// invented when no workspace qualifies; a NeferWL recording of that workspace
68// keeps following it when the user switches away. grid is the initial state of the
69// whole-monitor guides; the G key toggles them per overlay. The caller assigns
70// Selection.Path. The first output passed to Select opens first, so the caller
71// orders outputs to put the preferred one first.
72func New(mode ports.Mode, video ports.VideoSettings, workspaces []ports.Workspace, grid bool) *Selector {
73 if video.FPS == 0 {
74 video.FPS = DefaultFPS
75 }
76 return &Selector{mode: mode, video: video, workspaces: append([]ports.Workspace(nil), workspaces...), grid: grid}
77}
78
79// WithCapabilities adapts the selector to the compositor: W is offered only
80// when it has workspaces, and record mode says so when it cannot show a
81// recording indicator. Without it the selector assumes nothing is missing.
82func (s *Selector) WithCapabilities(c ports.Capabilities) *Selector {
83 s.noIndicator = !c.Exclusion
84 if !c.Workspaces {
85 s.workspaces = nil
86 }
87 return s
88}
89
90// maxBackdrop is the largest side NeferGUI accepts for one image.
91const maxBackdrop = 4096
92
93// CanBackdrop reports whether an output of this physical mode can show a
94// frozen frame. A larger output must stay live: freeze only the others.
95func CanBackdrop(o ports.Output) bool {
96 return o.Width > 0 && o.Height > 0 && max(o.Width, o.Height) <= maxBackdrop
97}
98
99// WithBackdrops draws each output's frozen frame under its overlay instead of
100// the live screen; outputs without a frame stay live. A frame larger than
101// CanBackdrop allows is an error. The frames are copied, so the caller may
102// release them once this returns.
103func (s *Selector) WithBackdrops(frames map[uint32]ports.Frame) (*Selector, error) {
104 s.backdrops = make(map[uint32]image.Image, len(frames))
105 for id, f := range frames {
106 if f.Width > maxBackdrop || f.Height > maxBackdrop {
107 return s, fmt.Errorf("selection: frozen frame of output %d is %dx%d, at most %d per side", id, f.Width, f.Height, maxBackdrop)
108 }
109 s.backdrops[id] = backdropImage(f)
110 }
111 return s, nil
112}
113
114// backdropImage converts a validated frame to an opaque image. NRGBA is the
115// format NeferGUI uploads without another conversion.
116func backdropImage(f ports.Frame) *image.NRGBA {
117 img := image.NewNRGBA(image.Rect(0, 0, f.Width, f.Height))
118 for y := range f.Height {
119 src, dst := f.Row(y), img.Pix[y*img.Stride:]
120 for x := 0; x+3 < len(src); x += 4 {
121 dst[x], dst[x+1], dst[x+2], dst[x+3] = src[x+2], src[x+1], src[x], 0xff
122 }
123 }
124 return img
125}
126
127// Frozen reports whether the last accepted selection still showed the frozen
128// screen, so its screenshot must come from the frozen copy. It is false after
129// F switched to the live screen, and when there were no backdrops.
130func (s *Selector) Frozen() bool { return s.frozen }
131
132// AllowToggle lets Tab switch between screenshot and record selection. The
133// starting mode is New's; the target selection is kept across a switch.
134func (s *Selector) AllowToggle() *Selector {
135 s.toggle = true
136 return s
137}
138
139// Select blocks until the user accepts a selection (true), aborts with Escape
140// (false, nil) or ctx ends or the window system fails (error). One overlay
141// opens on every output at once, so the whole desktop is selectable without
142// reopening. The first decision from any overlay wins and ends all of them:
143// Select returns only after every overlay's Wayland session has closed, so an
144// accepted selection never races a window that is still mapped. The compositor
145// may still be processing that teardown, so a caller must confirm through a
146// fresh capture connection before capturing. Select creates no capture path or
147// directory and fails with ErrTooManyOutputs rather than dropping outputs. One
148// goroutine at a time.
149//
150// Keyboard: outputs[0] takes exclusive keyboard focus; the other overlays take
151// it on demand, which compositors grant when the pointer clicks them. Digits
152// 1..9 pick that whole monitor from whichever overlay has the keyboard.
153func (s *Selector) Select(ctx context.Context, outputs []ports.Output) (ports.Selection, bool, error) {
154 if err := ctx.Err(); err != nil {
155 return ports.Selection{}, false, err
156 }
157 if len(outputs) == 0 {
158 return ports.Selection{}, false, errNoOutputs
159 }
160 if len(outputs) > MaxOutputs {
161 return ports.Selection{}, false, fmt.Errorf("%w: %d outputs, at most %d", ErrTooManyOutputs, len(outputs), MaxOutputs)
162 }
163 sheet, remove, err := uistyle.Write(styleSheet, "nefercap-selector-*.css")
164 if err != nil {
165 return ports.Selection{}, false, fmt.Errorf("selection: %w", err)
166 }
167 defer remove()
168
169 child, cancel := context.WithCancel(ctx)
170 defer cancel()
171 sess := newSession(cancel)
172 sess.canFreeze = len(s.backdrops) > 0
173 s.frozen = false
174 // Build every model and the complete wakes slice before any overlay
175 // starts: a running overlay reads sess.wakes on Tab or F.
176 models := make([]*model, len(outputs))
177 for i := range outputs {
178 m := newModel(s.mode, outputs, i, sess, s.grid)
179 m.setWorkspaces(s.workspaces)
180 m.noIndicator = s.noIndicator
181 m.backdrop = s.backdrops[outputs[i].ID]
182 // Every overlay has a wake: Tab on another overlay and the key
183 // effects both redraw through it.
184 m.wake, m.anim = make(chan struct{}, 1), newAnimator()
185 if s.toggle {
186 m.toggle = true
187 }
188 if s.toggle || sess.canFreeze {
189 sess.wakes = append(sess.wakes, m.wake)
190 }
191 m.footerText = footerText(m.mode, m.footerKind, m.footerWorkspace, m.toggle, m.noIndicator, m.freezeHint())
192 models[i] = m
193 }
194 var wg sync.WaitGroup
195 for i, m := range models {
196 wg.Add(1)
197 go func() {
198 defer wg.Done()
199 fx, stop := context.WithCancel(child)
200 var anim sync.WaitGroup
201 anim.Go(func() { m.anim.run(fx, m.wake) })
202 err := run(child, sheet, m)
203 stop()
204 anim.Wait()
205 sess.runEnded(ctx, outputs[i].Name, err)
206 }()
207 }
208 wg.Wait()
209 s.backdrops = nil // every overlay ended: nothing draws them any more
210 result, ok, err := sess.outcome(ctx)
211 if err != nil || !ok {
212 return ports.Selection{}, false, err
213 }
214 s.frozen = sess.acceptedFrozen()
215 return s.selectionFor(sess.acceptedMode(), result), true, nil
216}
217
218// run shows one overlay on its own output until the context ends.
219func run(ctx context.Context, sheet string, m *model) error {
220 kb := neferclient.KeyboardOnDemand
221 if m.index == 0 {
222 kb = neferclient.KeyboardExclusive
223 }
224 return layerui.Run(ctx, layerui.Config{
225 Layer: layerConfig(m.outputs[m.index].Name, kb),
226 Styles: sheet,
227 Wake: m.wake,
228 OnResize: m.resize,
229 OnInput: m.input,
230 }, m, view)
231}
232
233// layerConfig is one overlay: every edge, above windows, the given keyboard
234// mode, and an exclusive zone of -1 so no bar shifts it.
235func layerConfig(output string, keyboard neferclient.KeyboardMode) neferclient.LayerConfig {
236 return neferclient.LayerConfig{
237 Output: output,
238 Namespace: namespace,
239 Level: neferclient.LayerOverlay,
240 Anchors: neferclient.AnchorTop | neferclient.AnchorBottom | neferclient.AnchorLeft | neferclient.AnchorRight,
241 Keyboard: keyboard,
242 ExclusiveZone: -1,
243 }
244}
245
246// selection converts an accepted pick to a port selection through the core
247// rules: a monitor and a workspace carry a zero Region (a workspace's geometry
248// comes live from the compositor, identified by WorkspaceID), a dragged region
249// keeps its explicit output-local geometry.
250func (s *Selector) selection(r core.PickResult) ports.Selection {
251 return s.selectionFor(s.mode, r)
252}
253
254func (s *Selector) selectionFor(mode ports.Mode, r core.PickResult) ports.Selection {
255 sel := ports.Selection{Mode: mode, Target: r.Target()}
256 if mode == ports.Record {
257 sel.Video = s.video
258 }
259 return sel
260}