screencopy.go RawHistoryFolder

1package wayland
2
3import (
4	"image"
5	"math"
6	"os"
7	"time"
8
9	"github.com/bnema/go-wayland-bindings/server/wayland"
10	wlr "github.com/bnema/go-wayland-bindings/server/wlrscreencopy"
11	"github.com/bnema/neferwl/internal/ports"
12	"github.com/bnema/purego-libwayland/server"
13	"golang.org/x/sys/unix"
14)
15
16// maxCaptureInflight caps accepted captures that the backend has not completed
17// yet, across all clients. Destroying a client frame or resource does not
18// release its slot: only the backend completion does.
19const maxCaptureInflight = ports.MaxCaptureInflight
20
21// The renderer's scene and wl_output modes are already in physical orientation;
22// this compositor does not advertise rotated wl_output transforms.
23func captureRegion(o *output, logical image.Rectangle) image.Rectangle {
24	if o == nil {
25		return image.Rectangle{}
26	}
27	scale := o.place.Scale
28	if scale <= 0 {
29		scale = 1
30	}
31	p := image.Rect(int(math.Floor(float64(logical.Min.X)*scale)), int(math.Floor(float64(logical.Min.Y)*scale)), int(math.Ceil(float64(logical.Max.X)*scale)), int(math.Ceil(float64(logical.Max.Y)*scale)))
32	return p.Intersect(image.Rect(0, 0, o.place.Info.Width, o.place.Info.Height))
33}
34func captureTime(t time.Time) (uint32, uint32, uint32) {
35	sec := uint64(t.Unix())
36	return uint32(sec >> 32), uint32(sec), uint32(t.Nanosecond())
37}
38func registerCapture(d *server.Display, s *Server) error {
39	if err := wlr.NewZwlrScreencopyManagerV1Global(d, 3, func(c server.Client, v, id uint32) {
40		_, _ = wlr.NewZwlrScreencopyManagerV1(c, int32(v), id, screencopyManager{s})
41	}); err != nil {
42		return err
43	}
44	return registerImageCopy(d, s)
45}
46
47type screencopyManager struct{ s *Server }
48
49func (screencopyManager) Destroy(*wlr.ZwlrScreencopyManagerV1) {}
50func (m screencopyManager) CaptureOutput(r *wlr.ZwlrScreencopyManagerV1, id uint32, cursor int32, out *wayland.Output) {
51	o := m.s.outputOf(out)
52	if o == nil {
53		m.create(r, id, cursor, nil, image.Rectangle{})
54		return
55	}
56	m.create(r, id, cursor, o, image.Rect(0, 0, o.place.Info.Width, o.place.Info.Height))
57}
58func (m screencopyManager) CaptureOutputRegion(r *wlr.ZwlrScreencopyManagerV1, id uint32, cursor int32, out *wayland.Output, x, y, w, h int32) {
59	o := m.s.outputOf(out)
60	if w <= 0 || h <= 0 {
61		m.create(r, id, cursor, o, image.Rectangle{})
62		return
63	}
64	m.create(r, id, cursor, o, captureRegion(o, image.Rect(int(x), int(y), int64Clamp(int64(x)+int64(w)), int64Clamp(int64(y)+int64(h)))))
65}
66func int64Clamp(x int64) int {
67	if x > int64(^uint(0)>>1) {
68		return int(^uint(0) >> 1)
69	}
70	return int(x)
71}
72func (m screencopyManager) create(r *wlr.ZwlrScreencopyManagerV1, id uint32, cursor int32, o *output, rect image.Rectangle) {
73	state := &screencopyFrame{s: m.s, o: o, region: rect, cursor: cursor != 0}
74	f, err := wlr.NewZwlrScreencopyFrameV1(r.Client(), r.Version(), id, state)
75	if err != nil {
76		return
77	}
78	state.res = f
79	if rect.Empty() {
80		f.SendFailed()
81		state.used = true
82		return
83	}
84	f.SendBuffer(uint32(wayland.ShmFormatXrgb8888), uint32(rect.Dx()), uint32(rect.Dy()), uint32(rect.Dx()*4))
85	if f.Version() >= 3 {
86		f.SendBufferDone()
87	}
88}
89
90type screencopyFrame struct {
91	s            *Server
92	res          *wlr.ZwlrScreencopyFrameV1
93	o            *output
94	region       image.Rectangle
95	cursor, used bool
96	replyID      uint64
97}
98
99func (f *screencopyFrame) Destroy(*wlr.ZwlrScreencopyFrameV1)                   { delete(f.s.captureReplies, f.replyID) }
100func (f *screencopyFrame) Copy(_ *wlr.ZwlrScreencopyFrameV1, b *wayland.Buffer) { f.copy(b, false) }
101func (f *screencopyFrame) CopyWithDamage(_ *wlr.ZwlrScreencopyFrameV1, b *wayland.Buffer) {
102	f.copy(b, true)
103}
104func (f *screencopyFrame) copy(b *wayland.Buffer, damage bool) {
105	if f.used {
106		f.res.PostError(uint32(wlr.ZwlrScreencopyFrameV1ErrorAlreadyUsed), "frame already used")
107		return
108	}
109	f.used = true
110	if f.o == nil || f.region.Empty() || f.s.outputByNameExact(f.o.name()) != f.o {
111		f.res.SendFailed()
112		return
113	}
114	if !f.s.validCaptureBuffer(b, f.region, uint32(wayland.ShmFormatXrgb8888)) {
115		f.res.PostError(uint32(wlr.ZwlrScreencopyFrameV1ErrorInvalidBuffer), "invalid shm buffer")
116		return
117	}
118	id, ok := f.s.requestCapture(f.o, f.region, f.cursor, b, uint32(wayland.ShmFormatXrgb8888), func(done ports.CaptureDone) {
119		if done.Err != nil {
120			f.res.SendFailed()
121			return
122		}
123		f.res.SendFlags(0)
124		if damage && f.res.Version() >= 2 {
125			f.res.SendDamage(0, 0, uint32(f.region.Dx()), uint32(f.region.Dy()))
126		}
127		hi, lo, ns := captureTime(done.Time)
128		f.res.SendReady(hi, lo, ns)
129	}, f.res.Resource, captureTag{taken: ports.CaptureFrameTaken{Output: f.o.name(), Region: logicalRegion(f.o, f.region)}})
130	f.replyID = id
131	if !ok {
132		f.res.SendFailed()
133	}
134}
135
136// validCaptureBuffer checks the advertised shm constraints before any request is queued.
137func (s *Server) validCaptureBuffer(b *wayland.Buffer, rect image.Rectangle, format uint32) bool {
138	if b == nil {
139		return false
140	}
141	buf, ok := s.buffers[b.Resource].(*buffer)
142	return ok && (format == uint32(wayland.ShmFormatArgb8888) || format == uint32(wayland.ShmFormatXrgb8888)) && buf.width == rect.Dx() && buf.height == rect.Dy() && buf.stride >= rect.Dx()*4 && buf.format == format && fileHolds(buf.pool.file, int64(buf.offset)+int64(buf.height-1)*int64(buf.stride)+int64(buf.width)*4)
143}
144
145// logicalRegion is a physical region of an output as the logical rectangle
146// core marks: zero for the whole output, else the region's bounds rounded
147// outwards to logical pixels.
148func logicalRegion(o *output, phys image.Rectangle) ports.Rect {
149	scale := o.place.Scale
150	if scale <= 0 {
151		scale = 1
152	}
153	if phys == image.Rect(0, 0, o.place.Info.Width, o.place.Info.Height) {
154		return ports.Rect{}
155	}
156	x0, y0 := int(math.Floor(float64(phys.Min.X)/scale)), int(math.Floor(float64(phys.Min.Y)/scale))
157	x1, y1 := int(math.Ceil(float64(phys.Max.X)/scale)), int(math.Ceil(float64(phys.Max.Y)/scale))
158	return ports.Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}
159}
160
161// captureTag says what a capture is for the renderer: the registered session
162// (0 for wlr-screencopy), the exclusion fence and the workspace. taken is
163// what core is told of the frame (ports.CaptureFrameTaken): the compositor
164// shows an indicator for every capture, whatever the client or protocol.
165type captureTag struct {
166	session   uint64
167	exclude   bool
168	revision  uint64
169	workspace uint64
170	offscreen bool
171	taken     ports.CaptureFrameTaken
172}
173
174// requestCapture duplicates the pool descriptor, so destroying the wl_buffer
175// cannot invalidate a capture in flight.
176func (s *Server) requestCapture(o *output, rect image.Rectangle, cursor bool, b *wayland.Buffer, format uint32, reply func(ports.CaptureDone), life *server.Resource, tag captureTag) (uint64, bool) {
177	if o == nil || b == nil || s.channels.Captures == nil || s.channels.Captured == nil || s.outputByNameExact(o.name()) != o {
178		return 0, false
179	}
180	if !s.validCaptureBuffer(b, rect, format) {
181		s.log.Debug().Str("output", o.name()).Stringer("region", rect).Uint32("format", format).Msg("capture buffer rejected")
182		return 0, false
183	}
184	if len(s.captureInflight) >= maxCaptureInflight {
185		s.log.Debug().Str("output", o.name()).Int("inflight", len(s.captureInflight)).Msg("capture refused: too many captures in flight")
186		return 0, false
187	}
188	// An ext frame (tag.session set) rides on the session's resolution.
189	if life == nil || (tag.session != 0 && !s.mayCaptureFrame(life.Client())) || (tag.session == 0 && !s.mayCapture(life.Client())) {
190		s.log.Debug().Str("output", o.name()).Msg("capture refused: client may not capture")
191		return 0, false
192	}
193	buf := s.buffers[b.Resource].(*buffer)
194	fd, err := unix.Dup(int(buf.pool.file.Fd()))
195	if err != nil {
196		s.log.Warn().Err(err).Str("output", o.name()).Msg("capture: dup shm fd")
197		return 0, false
198	}
199	s.nextCapture++
200	id := s.nextCapture
201	s.captureInflight[id] = struct{}{}
202	start := time.Now()
203	taken := tag.taken
204	taken.Session = tag.session
205	s.captureReplies[id] = func(done ports.CaptureDone) {
206		if done.Err == nil {
207			// Whatever became of the client's frame object, its buffer holds
208			// an image now: the indicator lasts CaptureFlash from here.
209			s.emit(taken)
210		}
211		ev := s.log.Debug()
212		if done.Err != nil {
213			ev = s.log.Info().Err(done.Err)
214		}
215		ev.Uint64("id", id).Str("output", done.Output).Dur("took", time.Since(start)).Bool("delivered", life.Alive()).Msg("capture done")
216		if life.Alive() {
217			reply(done)
218		}
219	}
220	req := ports.CaptureRequest{ID: id, Output: o.name(), Region: rect, Cursor: cursor, Dst: ports.SHMBuffer{File: os.NewFile(uintptr(fd), "capture"), Offset: buf.offset}, Width: buf.width, Height: buf.height, Stride: buf.stride, Format: buf.format, Session: tag.session, Exclude: tag.exclude, CaptureRevision: tag.revision, Workspace: tag.workspace, OffScreen: tag.offscreen, Indicate: true}
221	select {
222	case s.channels.Captures <- req:
223		s.log.Debug().Uint64("id", id).Str("output", o.name()).Stringer("region", rect).Uint32("format", format).Bool("cursor", cursor).Msg("capture requested")
224		// The indicator is on screen while the frame is rendered.
225		s.emit(taken)
226		return id, true
227	default:
228		delete(s.captureReplies, id)
229		delete(s.captureInflight, id)
230		req.Dst.File.Close()
231		s.log.Debug().Str("output", o.name()).Msg("capture refused: request queue full")
232		return 0, false
233	}
234}
235func (s *Server) forwardCaptured(ctxDone <-chan struct{}) {
236	for {
237		select {
238		case <-ctxDone:
239			return
240		case <-s.display.Stopped():
241			return
242		case done, ok := <-s.channels.Captured:
243			if !ok {
244				return
245			}
246			if !s.display.Do(func() {
247				delete(s.captureInflight, done.ID)
248				if fn := s.captureReplies[done.ID]; fn != nil {
249					delete(s.captureReplies, done.ID)
250					fn(done)
251				}
252				s.maybeLocked()
253			}) {
254				return
255			}
256		}
257	}
258}

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 23

Tags 10

↑↓ moveenter openesc close