1package wayland
2
3import (
4 "os"
5 "slices"
6
7 "github.com/bnema/go-wayland-bindings/server/wayland"
8 "github.com/bnema/neferwl/internal/ports"
9 "github.com/bnema/purego-libwayland/server"
10)
11
12func registerGlobals(d *server.Display, o Options, s *Server) error {
13 for _, register := range []func() error{
14 func() error { return registerXDG(d, s) },
15 func() error { return registerLayer(d, s) },
16 func() error {
17 // Advertise only with the production owner gate and authoritative
18 // backend proof/barrier channels. Standalone adapters cannot claim
19 // protection from composed-frame submission alone.
20 if s.securityController == nil || s.channels.SecurityChanges == nil || s.channels.SecurityEvents == nil {
21 return nil
22 }
23 return registerSessionLock(d, s)
24 },
25 func() error { return registerXDGOutput(d, s) },
26 func() error { return registerOutputManagement(d, s) },
27 func() error { return registerWorkspaces(d, s) },
28 func() error { return registerForeignToplevel(d, s) },
29 func() error { return registerExtForeignToplevel(d, s) },
30 func() error { return registerDecoration(d, s) },
31 func() error { return registerDialog(d, s) },
32 func() error { return registerScale(d, s) },
33 func() error { return registerCursorShape(d, s) },
34 func() error { return registerDMABuf(d, s, o.DMABuf) },
35 func() error { return registerSinglePixelBuffer(d, s) },
36 func() error { return registerPointerConstraints(d, s) },
37 func() error { return registerPointerGestures(d, s) },
38 func() error { return registerTearing(d, s) },
39 func() error { return registerColorManagement(d, s) },
40 func() error { return registerColorRepresentation(d, s) },
41 func() error { return registerPresentationConstraints(d, s) },
42 func() error { return registerPresentation(d, s) },
43 func() error { return registerSyncobj(d, s) },
44 func() error { return registerInhibit(d, s) },
45 func() error { return registerIdle(d, s) },
46 func() error { return registerCapture(d, s) },
47 func() error { return registerExclusion(d, s) },
48 func() error { return registerSecurityContext(d, s) },
49 func() error { return registerActivation(d, s) },
50 func() error { return registerForeign(d, s) },
51 func() error { return registerVirtualKeyboard(d, s) },
52 func() error { return registerTextInput(d, s) },
53 func() error { return registerInputMethod(d, s) },
54 func() error {
55 return wayland.NewCompositorGlobal(d, 6, func(c server.Client, v, id uint32) { wayland.NewCompositor(c, int32(v), id, compositor{s}) })
56 },
57 func() error {
58 return wayland.NewSubcompositorGlobal(d, 1, func(c server.Client, v, id uint32) {
59 wayland.NewSubcompositor(c, int32(v), id, subcompositor{s})
60 })
61 },
62 func() error {
63 return wayland.NewShmGlobal(d, 1, func(c server.Client, v, id uint32) {
64 r, e := wayland.NewShm(c, int32(v), id, shm{s})
65 if e == nil {
66 r.SendFormat(0)
67 r.SendFormat(1)
68 }
69 })
70 },
71 func() error {
72 return wayland.NewSeatGlobal(d, 8, func(c server.Client, v, id uint32) {
73 r, e := wayland.NewSeat(c, int32(v), id, seat{s})
74 if e == nil {
75 capabilities := uint32(wayland.SeatCapabilityPointer)
76 if s.seat.keymapFD >= 0 {
77 capabilities |= uint32(wayland.SeatCapabilityKeyboard)
78 }
79 r.SendCapabilities(capabilities)
80 if v >= 2 {
81 r.SendName("seat0")
82 }
83 }
84 })
85 },
86 func() error { return registerInputTimestamps(d, s) },
87 func() error { return registerClipboard(d, s) },
88 func() error { return registerFixes(d) },
89 func() error { return registerAlphaModifier(d, s) },
90 } {
91 if err := register(); err != nil {
92 return err
93 }
94 }
95 return nil
96}
97
98// registerFixes advertises wl_fixes: clients can destroy their registry,
99// and acknowledge removed globals (v2, libwayland 1.26+).
100func registerFixes(d *server.Display) error {
101 version := int32(1)
102 if server.AckGlobalRemove(nil, nil, 0) {
103 version = 2
104 }
105 return wayland.NewFixesGlobal(d, version, func(c server.Client, v, id uint32) {
106 _, _ = wayland.NewFixes(c, int32(v), id, fixes{})
107 })
108}
109
110type fixes struct{}
111
112func (fixes) Destroy(*wayland.Fixes) {}
113func (fixes) DestroyRegistry(_ *wayland.Fixes, r *wayland.Registry) {
114 if r != nil && r.Resource != nil {
115 r.Destroy()
116 }
117}
118func (fixes) AckGlobalRemove(f *wayland.Fixes, r *wayland.Registry, name uint32) {
119 if r != nil {
120 server.AckGlobalRemove(f.Resource, r.Resource, name)
121 }
122}
123
124type compositor struct{ server *Server }
125
126func (c compositor) CreateSurface(r *wayland.Compositor, id uint32) {
127 state := &surface{server: c.server, bufferScale: 1, inputAll: true}
128 if w, err := wayland.NewSurface(r.Client(), r.Version(), id, state); err == nil {
129 c.server.nextSurface++
130 state.identity = c.server.nextSurface
131 state.wl = w
132 c.server.surfaces[w.Resource] = state
133 state.sendScale()
134 w.OnDestroy = func() { delete(c.server.surfaces, w.Resource); state.Destroy(w) }
135 }
136}
137func (c compositor) CreateRegion(r *wayland.Compositor, id uint32) {
138 state := ®ion{}
139 if w, err := wayland.NewRegion(r.Client(), r.Version(), id, state); err == nil {
140 c.server.regions[w.Resource] = state
141 w.OnDestroy = func() { delete(c.server.regions, w.Resource) }
142 }
143}
144func (compositor) Release(*wayland.Compositor) {}
145
146type subcompositor struct{ server *Server }
147
148func (subcompositor) Destroy(*wayland.Subcompositor) {}
149func (c subcompositor) GetSubsurface(r *wayland.Subcompositor, id uint32, w, parent *wayland.Surface) {
150 if w == nil || parent == nil {
151 return
152 }
153 state, up := c.server.surfaces[w.Resource], c.server.surfaces[parent.Resource]
154 if state == nil || up == nil {
155 return
156 }
157 if state.kind != roleNone && state.kind != roleSubsurface || state.sub.role != nil {
158 r.PostError(uint32(wayland.SubcompositorErrorBadSurface), "surface already has role")
159 return
160 }
161 // A surface cannot be its own ancestor.
162 for p := up; p != nil; p = p.sub.parent {
163 if p == state {
164 r.PostError(uint32(wayland.SubcompositorErrorBadParent), "parent is a descendant")
165 return
166 }
167 }
168 sub, err := wayland.NewSubsurface(r.Client(), 1, id, subsurface{state})
169 if err != nil {
170 return
171 }
172 state.kind = roleSubsurface
173 state.role = func(bool) {}
174 state.sub = subState{role: sub, parent: up, children: state.sub.children, layout: state.sub.layout, pendingLayout: state.sub.pendingLayout, synced: true}
175 up.sub.children = append(up.sub.children, state)
176 up.sub.pendingLayout = append(append([]childLayout(nil), up.sub.pendingLayout...), childLayout{child: state})
177 // The child follows its root window's output and scale.
178 state.sendScale()
179 up.emitInput()
180 sub.OnDestroy = func() {
181 if state.sub.role != sub {
182 return
183 }
184 state.sub.role = nil
185 state.role = nil
186 state.detach()
187 }
188}
189
190// Subsurfaces are drawn as their own commits arrive (desynchronized): the
191// synchronized mode's cached state is not implemented.
192type subsurface struct{ surface *surface }
193
194func (subsurface) Destroy(*wayland.Subsurface) {}
195func (s subsurface) SetPosition(_ *wayland.Subsurface, x, y int32) {
196 p := s.surface.sub.parent
197 if p == nil {
198 return
199 }
200 p.sub.pendingLayout = append([]childLayout(nil), p.sub.pendingLayout...)
201 for i := range p.sub.pendingLayout {
202 item := &p.sub.pendingLayout[i]
203 if item.child == s.surface {
204 item.x, item.y = int(x), int(y)
205 break
206 }
207 }
208}
209func (s subsurface) PlaceAbove(r *wayland.Subsurface, sibling *wayland.Surface) {
210 s.restack(r, sibling, true)
211}
212func (s subsurface) PlaceBelow(r *wayland.Subsurface, sibling *wayland.Surface) {
213 s.restack(r, sibling, false)
214}
215func (s subsurface) SetSync(*wayland.Subsurface) { s.surface.sub.synced = true }
216func (s subsurface) SetDesync(*wayland.Subsurface) {
217 was := s.surface.effectivelySynced()
218 s.surface.sub.synced = false
219 if was && !s.surface.effectivelySynced() {
220 s.surface.flushDesync()
221 }
222}
223
224// restack changes only the pending layout of the parent.
225func (s subsurface) restack(r *wayland.Subsurface, sibling *wayland.Surface, above bool) {
226 me := s.surface
227 p := me.sub.parent
228 if p == nil || sibling == nil {
229 return
230 }
231 other := me.server.surfaces[sibling.Resource]
232 if other == me || other == nil || other != p && other.sub.parent != p {
233 r.PostError(uint32(wayland.SubsurfaceErrorBadSurface), "not a sibling or the parent")
234 return
235 }
236 list := append([]childLayout(nil), p.sub.pendingLayout...)
237 var item childLayout
238 for _, entry := range list {
239 if entry.child == me {
240 item = entry
241 break
242 }
243 }
244 list = removeLayout(list, me)
245 at := len(list)
246 if other == p {
247 item.below = !above
248 if above {
249 for i, entry := range list {
250 if !entry.below {
251 at = i
252 break
253 }
254 }
255 }
256 } else {
257 for i, entry := range list {
258 if entry.child == other {
259 at, item.below = i, entry.below
260 if above {
261 at++
262 }
263 break
264 }
265 }
266 }
267 list = append(list, childLayout{})
268 copy(list[at+1:], list[at:])
269 list[at] = item
270 p.sub.pendingLayout = list
271}
272
273// region stores the exact union of added rectangles.
274type region struct{ rects []ports.Rect }
275
276func (*region) Destroy(*wayland.Region) {}
277func (g *region) Add(_ *wayland.Region, x, y, w, h int32) {
278 if w > 0 && h > 0 {
279 g.rects = append(g.rects, ports.Rect{X: int(x), Y: int(y), W: int(w), H: int(h)})
280 }
281}
282func (g *region) Subtract(_ *wayland.Region, x, y, w, h int32) {
283 if w <= 0 || h <= 0 {
284 return
285 }
286 cut := ports.Rect{X: int(x), Y: int(y), W: int(w), H: int(h)}
287 var out []ports.Rect
288 for _, r := range g.rects {
289 i := intersectRect(r, cut)
290 if i.W == 0 {
291 out = append(out, r)
292 continue
293 }
294 for _, piece := range []ports.Rect{
295 {X: r.X, Y: r.Y, W: r.W, H: i.Y - r.Y},
296 {X: r.X, Y: i.Y + i.H, W: r.W, H: r.Y + r.H - i.Y - i.H},
297 {X: r.X, Y: i.Y, W: i.X - r.X, H: i.H},
298 {X: i.X + i.W, Y: i.Y, W: r.X + r.W - i.X - i.W, H: i.H},
299 } {
300 if piece.W > 0 && piece.H > 0 {
301 out = append(out, piece)
302 }
303 }
304 }
305 g.rects = out
306}
307
308type shm struct{ server *Server }
309
310func (h shm) CreatePool(r *wayland.Shm, id uint32, fd int, size int32) {
311 file := os.NewFile(uintptr(fd), "wl_shm_pool")
312 if size <= 0 || !fileHolds(file, int64(size)) {
313 file.Close()
314 r.PostError(uint32(wayland.ShmErrorInvalidFd), "invalid pool size")
315 return
316 }
317 h.server.nextPool++
318 state := &pool{id: h.server.nextPool, file: file, size: size, shm: r, server: h.server}
319 p, err := wayland.NewShmPool(r.Client(), 1, id, state)
320 if err != nil {
321 file.Close()
322 return
323 }
324 p.OnDestroy = func() {
325 state.destroyed = true
326 if state.refs == 0 {
327 state.file.Close()
328 }
329 }
330}
331func (shm) Release(*wayland.Shm) {}
332
333// fileHolds reports whether the file has at least size bytes.
334func fileHolds(f *os.File, size int64) bool {
335 st, err := f.Stat()
336 return err == nil && st.Size() >= size
337}
338
339// pool is a wl_shm pool. neferwl never maps it: renderers map the file
340// and read the pixels when they draw (ports.SHMBuffer).
341type pool struct {
342 id uint64
343 file *os.File
344 size int32
345 shm *wayland.Shm
346 server *Server
347 refs int
348 destroyed bool
349}
350
351func (p *pool) CreateBuffer(r *wayland.ShmPool, id uint32, offset, width, height, stride int32, format uint32) {
352 if format != uint32(wayland.ShmFormatArgb8888) && format != uint32(wayland.ShmFormatXrgb8888) {
353 p.shm.PostError(uint32(wayland.ShmErrorInvalidFormat), "unsupported format")
354 return
355 }
356 if width <= 0 || height <= 0 || int64(stride) < int64(width)*4 || offset < 0 || stride <= 0 || int64(offset)+int64(height-1)*int64(stride)+int64(width)*4 > int64(p.size) {
357 p.shm.PostError(uint32(wayland.ShmErrorInvalidStride), "invalid buffer dimensions")
358 return
359 }
360 state := &buffer{pool: p, offset: int(offset), width: int(width), height: int(height), stride: int(stride), format: format}
361 b, err := wayland.NewBuffer(r.Client(), 1, id, state)
362 if err != nil {
363 return
364 }
365 p.refs++
366 p.server.buffers[b.Resource] = state
367 b.OnDestroy = func() {
368 delete(p.server.buffers, b.Resource)
369 p.refs--
370 if p.destroyed && p.refs == 0 {
371 p.file.Close()
372 }
373 }
374}
375func (p *pool) Destroy(*wayland.ShmPool) {}
376func (p *pool) Resize(r *wayland.ShmPool, size int32) {
377 if size <= p.size {
378 p.shm.PostError(uint32(wayland.ShmErrorInvalidFd), "pool must grow")
379 return
380 }
381 if !fileHolds(p.file, int64(size)) {
382 p.shm.PostError(uint32(wayland.ShmErrorInvalidFd), "cannot resize pool")
383 return
384 }
385 p.size = size
386}
387
388type buffer struct {
389 pool *pool
390 offset, width, height, stride int
391 format uint32
392}
393
394func (*buffer) Destroy(*wayland.Buffer) {}
395
396func (b *buffer) size() (int, int) { return b.width, b.height }
397
398// clientBuffer is a wl_buffer's content source: wl_shm, linux-dmabuf or
399// single-pixel buffers.
400type clientBuffer interface {
401 // content returns what the renderer draws; false means the client
402 // broke its buffer (a truncated shm file).
403 content(ports.WindowID) (ports.SurfaceContent, bool)
404 size() (int, int)
405}
406
407// addBuffer tracks a buffer until the client destroys it.
408// A buffer that owns resources implements close() to release them.
409func (s *Server) addBuffer(r *wayland.Buffer, b clientBuffer) {
410 s.buffers[r.Resource] = b
411 r.OnDestroy = func() {
412 delete(s.buffers, r.Resource)
413 if c, ok := b.(interface{ close() }); ok {
414 c.close()
415 }
416 }
417}
418
419// content points the renderer at the pool; a file shrunk below the buffer
420// is refused.
421func (b *buffer) content(id ports.WindowID) (ports.SurfaceContent, bool) {
422 if !fileHolds(b.pool.file, int64(b.offset+(b.height-1)*b.stride+b.width*4)) {
423 return ports.SurfaceContent{}, false
424 }
425 shm := &ports.SHMBuffer{Pool: b.pool.id, File: b.pool.file, Offset: b.offset, Stride: b.stride}
426 return ports.SurfaceContent{ID: id, Width: b.width, Height: b.height, Opaque: b.format == uint32(wayland.ShmFormatXrgb8888), SHM: shm}, true
427}
428
429type seat struct{ server *Server }
430
431func (h seat) GetPointer(r *wayland.Seat, id uint32) {
432 p, err := wayland.NewPointer(r.Client(), r.Version(), id, pointer(h))
433 if err != nil {
434 return
435 }
436 s := h.server
437 s.seat.pointers[r.Client()] = append(s.seat.pointers[r.Client()], p)
438 p.OnDestroy = func() {
439 delete(s.seat.enters, p.Resource)
440 // Subscribed timestamps objects become inert with the device.
441 delete(s.seat.pointerStamps, p.Resource)
442 // Copy on write: callers may be ranging over the old list (see
443 // clientPointers).
444 list := slices.DeleteFunc(slices.Clone(s.seat.pointers[r.Client()]), func(x *wayland.Pointer) bool { return x == p })
445 if len(list) == 0 {
446 delete(s.seat.pointers, r.Client())
447 } else {
448 s.seat.pointers[r.Client()] = list
449 }
450 }
451 if s.hasPointerFocus(r.Client()) {
452 if surf, _, x, y := s.pointerSurface(s.seat.pointerFocus, s.seat.pointerX, s.seat.pointerY); surf != nil {
453 s.serial++
454 s.seat.enters[p.Resource] = s.serial
455 p.SendEnter(s.serial, surf, server.FixedFromFloat(x), server.FixedFromFloat(y))
456 pointerFrame(p)
457 }
458 }
459}
460func (h seat) GetKeyboard(r *wayland.Seat, id uint32) {
461 k, err := wayland.NewKeyboard(r.Client(), r.Version(), id, keyboard{})
462 if err != nil {
463 return
464 }
465 s := h.server
466 k.OnDestroy = func() {
467 delete(s.seat.keyStamps, k.Resource)
468 // Copy on write: callers may be ranging over the old list (see
469 // clientKeyboards).
470 list := slices.DeleteFunc(slices.Clone(s.seat.keyboards[r.Client()]), func(x *wayland.Keyboard) bool { return x == k })
471 if len(list) == 0 {
472 delete(s.seat.keyboards, r.Client())
473 } else {
474 s.seat.keyboards[r.Client()] = list
475 }
476 }
477 if s.seat.keymapFD < 0 {
478 return
479 }
480 s.seat.keyboards[r.Client()] = append(s.seat.keyboards[r.Client()], k)
481 fd, size := s.currentKeymap()
482 k.SendKeymap(uint32(wayland.KeyboardKeymapFormatXkbV1), fd, size)
483 if r.Version() >= 4 {
484 k.SendRepeatInfo(int32(s.seat.repeatRate), int32(s.seat.repeatDelay))
485 }
486 if surf, _ := s.focusTarget(s.seat.focused); surf != nil && surf.Client() == r.Client() {
487 s.serial++
488 k.SendEnter(s.serial, surf, []byte{})
489 s.sendModifiers(k)
490 }
491}
492func (seat) GetTouch(r *wayland.Seat, id uint32) {
493 wayland.NewTouch(r.Client(), r.Version(), id, touch{})
494}
495func (seat) Release(*wayland.Seat) {}
496
497type keyboard struct{}
498
499func (keyboard) Release(*wayland.Keyboard) {}
500
501type touch struct{}
502
503func (touch) Release(*wayland.Touch) {}