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