~novakane/agertu

agertu/src/Backend.zig -rw-r--r-- 25.2 KiB
9ea83d8fHugo Machet build: Bump to version 2.0.0-dev 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
// This file is part of agertu
//
// Copyright (C) 2021-2022 Hugo Machet
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");
const assert = std.debug.assert;
const builtin = @import("builtin");
const fmt = std.fmt;
const mem = std.mem;
const os = std.os;

const fcft = @import("fcft");
const pixman = @import("pixman");
const wayland = @import("wayland");
const wl = wayland.client.wl;
const zwlr = wayland.client.zwlr;
const zriver = wayland.client.zriver;

const Config = @import("Config.zig");
const decorations = @import("decorations.zig");
const util = @import("util.zig");
const Backend = @This();

const log = std.log.scoped(.backend);

const Output = struct {
    backend: *Backend,

    wl_output: *wl.Output,
    wl_name: u32,

    river_output_status: *zriver.OutputStatusV1 = undefined,

    surface: ?*Surface = null,

    focused_tags: u32 = 0,
    view_tags: u32 = 0,
    urgent_tags: u32 = 0,

    font: *fcft.Font,
    image: ?*pixman.Image = null,

    configured: bool = false,

    render_scheduled: bool = false,

    fn init(output: *Output, backend: *Backend, wl_output: *wl.Output, wl_name: u32) !void {
        output.* = .{
            .backend = backend,
            .wl_output = wl_output,
            .wl_name = wl_name,
            .font = try decorations.get_fcft_fonts(backend.config.fonts),
        };
    }

    fn deinit(output: *Output) void {
        if (output.surface) |surface| {
            surface.deinit();
            util.gpa.destroy(surface);
        }
        output.font.destroy();
        output.river_output_status.destroy();
        output.wl_output.release();
    }

    fn get_output_status(output: *Output) !void {
        output.river_output_status =
            try output.backend.river_status_manager.?.getRiverOutputStatus(output.wl_output);
        output.river_output_status.setListener(*Output, output_status_listener, output);
        output.configured = true;
    }

    /// If a surface already exists use it, else initialize a new one.
    fn update_surface(output: *Output) !void {
        if (output.surface) |_| {
            try output.render();
            try output.schedule_and_commit();
        } else {
            const surface = try util.gpa.create(Surface);
            errdefer util.gpa.destroy(surface);
            output.surface = surface;
            try output.surface.?.init(output);
        }
    }

    fn schedule_and_commit(output: *Output) !void {
        const surface = output.surface.?;
        if (!surface.configured) {
            log.warn("surface is not configured", .{});
            return;
        }

        if (output.backend.next_buffer) |pending| {
            if (output.render_scheduled) {
                if (surface.wl_surface) |wl_surface| {
                    wl_surface.attach(pending.wl_buffer, 0, 0);
                    wl_surface.damageBuffer(0, 0, pending.width, pending.height);

                    var now: os.timespec = undefined;
                    os.clock_gettime(os.CLOCK.MONOTONIC, &now) catch {
                        @panic("CLOCK_MONOTONIC not supported");
                    };
                    surface.last_frame = now;

                    wl_surface.commit();
                }

                output.render_scheduled = false;

                output.backend.next_buffer = try output.backend.get_next_buffer(
                    output.backend.shm.?,
                    surface.width,
                    surface.height,
                );

                if (output.backend.next_buffer) |next| {
                    assert(next.busy);
                    output.image = next.pixman_image;
                } else {
                    log.err("no buffer available", .{});
                    return;
                }
            }
        } else {
            output.backend.next_buffer = try output.backend.get_next_buffer(
                output.backend.shm.?,
                surface.width,
                surface.height,
            );

            if (output.backend.next_buffer) |buf| {
                assert(buf.busy);
                output.image = buf.pixman_image;
            } else {
                log.err("no buffer available", .{});
                return;
            }
        }
    }

    /// Draw and commit a frame.
    fn render(output: *Output) !void {
        const cfg = output.backend.config;
        const surface = output.surface.?;
        const pix = output.image orelse return error.PixmanImageEmpty;

        // Now the surface is configured and has a buffer, we can safely draw on it.
        // Then attach to the buffer, damage the buffer and finally commit our surface.
        //
        // Render the background surface.
        try decorations.draw_bordered_rectangle(
            pix,
            0,
            0,
            @intCast(u16, surface.width),
            @intCast(u16, surface.height),
            cfg.surface_borders_size,
            cfg.surface_background_color,
            cfg.surface_borders_color,
        );

        // Render the tags square.
        try output.render_tags(pix, cfg.tags_square_size, cfg.tags_borders_size, cfg.tags_margins);

        output.render_scheduled = true;
    }

    /// Render a bordered square for each tags with or without a number
    /// text inside it.
    fn render_tags(
        output: *Output,
        image: *pixman.Image,
        square_size: u16,
        borders_size: u16,
        margins: u16,
    ) !void {
        const cfg = output.backend.config;

        var i: u32 = 0;
        while (i < cfg.tags_amount) : (i += 1) {
            // Tags state.
            const focused = (output.focused_tags & (@as(u32, 1) << @intCast(u5, i))) != 0;
            const urgent = (output.urgent_tags & (@as(u32, 1) << @intCast(u5, i))) != 0;
            const occupied = (output.view_tags & (@as(u32, 1) << @intCast(u5, i))) != 0;

            const tag_background_color = blk: {
                if (focused) break :blk cfg.tags_focused_background_color;
                if (urgent) break :blk cfg.tags_urgent_background_color;
                if (occupied) break :blk cfg.tags_occupied_background_color;
                break :blk cfg.tags_background_color;
            };

            const tag_borders_color = blk: {
                if (focused) break :blk cfg.tags_focused_borders_color;
                if (urgent) break :blk cfg.tags_urgent_borders_color;
                if (occupied) break :blk cfg.tags_occupied_borders_color;
                break :blk cfg.tags_border_colors;
            };

            // Total size of a tag.
            const tag_width: u32 = square_size + margins;

            // Starting point of all tags.
            const x_start: i16 = @intCast(i16, cfg.surface_borders_size + margins);
            // Starting point of each tag square.
            const x_square: i16 = x_start + @intCast(i16, i * tag_width);

            // Render the bordered square.
            try decorations.draw_bordered_rectangle(
                image,
                x_square,
                x_start,
                square_size,
                square_size,
                borders_size,
                tag_background_color,
                tag_borders_color,
            );

            // Render the tag number inside the square.
            if (cfg.tags_number_text) {
                var x_text: i32 = x_start + @intCast(i32, margins + borders_size + i * tag_width);
                const y_text: i32 = @intCast(
                    i32,
                    cfg.surface_borders_size + tag_width / 2 + @intCast(u32, output.font.ascent),
                );

                const foreground = blk: {
                    if (focused) break :blk cfg.tags_focused_foreground_color;
                    if (urgent) break :blk cfg.tags_urgent_foreground_color;
                    if (occupied) break :blk cfg.tags_occupied_foreground_color;
                    break :blk cfg.tags_foreground_color;
                };

                var buf: [2]u8 = undefined;
                var tag_number = try fmt.bufPrint(buf[0..], "{}", .{i + 1});
                try decorations.draw_bytes(
                    tag_number,
                    output.font,
                    image,
                    foreground,
                    &x_text,
                    y_text,
                );
            }
        }
    }

    fn output_listener(_: *wl.Output, event: wl.Output.Event, output: *Output) void {
        switch (event) {
            .done => output.configured = true,
            else => {},
        }
    }

    fn handle_focused_tags(output: *Output, tags: u32) void {
        output.focused_tags = tags;
        output.update_surface() catch return;
    }

    fn handle_view_tags(output: *Output, tags: *wl.Array) void {
        output.view_tags = 0;
        for (tags.slice(u32)) |tag| {
            output.view_tags |= tag;
        }
        // Only update if the surface already exists.
        if (output.surface != null) output.update_surface() catch return;
    }

    fn handle_urgent_tags(output: *Output, tags: u32) void {
        const old_tags = output.urgent_tags;
        output.urgent_tags = tags;
        // Only display the popup if the urgent tags are not already focused.
        if (output.urgent_tags != output.focused_tags) {
            // Only display the popup when tags become urgent, not when
            // it loses urgency.
            const diff = old_tags ^ output.urgent_tags;
            if ((diff & output.urgent_tags) > 0) {
                output.update_surface() catch return;
            }
        }
    }

    fn output_status_listener(
        _: *zriver.OutputStatusV1,
        event: zriver.OutputStatusV1.Event,
        output: *Output,
    ) void {
        switch (event) {
            .focused_tags => |ev| output.handle_focused_tags(ev.tags),
            .view_tags => |ev| output.handle_view_tags(ev.tags),
            .urgent_tags => |ev| output.handle_urgent_tags(ev.tags),
        }
    }
};

const Surface = struct {
    wl_surface: ?*wl.Surface = null,
    layer_surface: ?*zwlr.LayerSurfaceV1 = null,

    width: u31 = 0,
    height: u31 = 0,

    /// Time when the wl_surface is commited.
    last_frame: os.timespec = undefined,

    configured: bool = false,

    fn init(surface: *Surface, output: *Output) !void {
        const wl_surface = try output.backend.compositor.?.createSurface();
        const layer_surface = try output.backend.layer_shell.?.getLayerSurface(
            wl_surface,
            output.wl_output,
            .overlay,
            "agertu",
        );

        const cfg = output.backend.config;
        surface.* = .{
            .wl_surface = wl_surface,
            .layer_surface = layer_surface,
            .width = @intCast(u31, cfg.tags_amount * cfg.tags_square_size +
                (cfg.tags_amount + 1) * cfg.tags_margins + 2 * cfg.surface_borders_size),
            .height = @intCast(u31, (cfg.tags_square_size + 2 * cfg.tags_margins) +
                (2 * cfg.surface_borders_size)),
        };

        // Configure the layer_surface.
        const anchors = parse_anchors(cfg.surface_anchors) catch |err| switch (err) {
            error.InvalidAnchors => {
                log.err("{s}: Must be `<int>:<int>:<int>:<int>`", .{err});
                return;
            },
            else => return err,
        };
        const margins = try parse_margins(cfg.surface_margins);

        if (surface.layer_surface) |layer| {
            layer.setListener(*Output, layer_surface_listener, output);
            layer.setSize(surface.width, surface.height);
            layer.setAnchor(anchors);
            layer.setMargin(margins[0], margins[1], margins[2], margins[3]);
        }

        // Create an empty region so the compositor knows that the surface is not
        // interested in pointer events.
        const region = try output.backend.compositor.?.createRegion();
        surface.wl_surface.?.setInputRegion(region);
        region.destroy();

        // We need to commit the empty surface first so we can receive a configure event
        // with width and height requested for our surface.
        surface.wl_surface.?.commit();
    }

    pub fn deinit(surface: *Surface) void {
        if (surface.layer_surface) |layer_surface| layer_surface.destroy();
        if (surface.wl_surface) |wl_surface| wl_surface.destroy();
        surface.layer_surface = null;
        surface.wl_surface = null;
    }

    fn layer_surface_listener(
        _: *zwlr.LayerSurfaceV1,
        event: zwlr.LayerSurfaceV1.Event,
        output: *Output,
    ) void {
        const surface = output.surface.?;
        switch (event) {
            .configure => |data| {
                surface.configured = true;
                surface.layer_surface.?.ackConfigure(data.serial);

                surface.width = @truncate(u31, data.width);
                surface.height = @truncate(u31, data.height);

                output.schedule_and_commit() catch return;
                output.render() catch return;
            },
            .closed => {
                surface.deinit();
                util.gpa.destroy(surface);
                output.surface = null;
            },
        }
    }

    /// Parse a string in the format "top:right:bottom:left", e.g. "1:1:0:0".
    fn parse_anchors(s: []const u8) anyerror!zwlr.LayerSurfaceV1.Anchor {
        if (s.len != 7) return error.InvalidAnchors;

        if (s[1] != ':' or s[3] != ':' or s[5] != ':') return error.InvalidAnchors;

        if (s[0] != '0' and s[0] != '1') return error.InvalidAnchors;
        if (s[2] != '0' and s[2] != '1') return error.InvalidAnchors;
        if (s[4] != '0' and s[4] != '1') return error.InvalidAnchors;
        if (s[6] != '0' and s[6] != '1') return error.InvalidAnchors;

        return zwlr.LayerSurfaceV1.Anchor{
            .top = s[0] == '1',
            .right = s[2] == '1',
            .bottom = s[4] == '1',
            .left = s[6] == '1',
        };
    }

    /// Parse a string in the format "top:right:bottom:left", e.g. "10:5:0:0".
    fn parse_margins(s: []const u8) ![4]i32 {
        var ret: [4]i32 = .{ 0, 0, 0, 0 };
        var it = mem.tokenize(u8, s, ":");
        var i: usize = 0;
        while (it.next()) |anchor| : (i += 1) {
            ret[i] = try fmt.parseInt(i32, anchor, 10);
        }

        return [4]i32{ ret[0], ret[1], ret[2], ret[3] };
    }
};

const Buffer = struct {
    wl_buffer: ?*wl.Buffer = null,
    data: []align(std.mem.page_size) u8 = undefined,
    pixman_image: ?*pixman.Image = null,

    width: u31 = 0,
    height: u31 = 0,

    busy: bool = false,

    fn init(buffer: *Buffer, shm: *wl.Shm, width: u31, height: u31) !void {
        const stride = width * 4;
        const size: u31 = stride * height;

        // Open a memory backed file.
        const fd = try create_shm_fd();
        defer os.close(fd);

        try os.ftruncate(fd, size);

        // mmap the memory file, to be used by the pximan image.
        const data = mem.bytesAsSlice(
            u8,
            try os.mmap(null, size, os.PROT.READ | os.PROT.WRITE, os.MAP.SHARED, fd, 0),
        );
        errdefer os.munmap(data);

        // Create a Wayland shm buffer for the same memory file.
        const pool = try shm.createPool(fd, size);
        defer pool.destroy();

        const wl_buffer = try pool.createBuffer(0, width, height, stride, .argb8888);
        errdefer wl_buffer.destroy();
        wl_buffer.setListener(*Buffer, buffer_listener, buffer);

        // Create the pixman image.
        const pixman_image = pixman.Image.createBitsNoClear(
            .a8r8g8b8,
            @intCast(c_int, width),
            @intCast(c_int, height),
            @ptrCast([*c]u32, data),
            @intCast(c_int, stride),
        );
        errdefer _ = pixman_image.unref();

        // The pixman image and the Wayland buffer now share the same memory.
        buffer.* = .{
            .wl_buffer = wl_buffer,
            .data = data,
            .pixman_image = pixman_image,
            .width = width,
            .height = height,
        };
    }

    fn deinit(buffer: *Buffer) void {
        if (buffer.pixman_image) |pix| _ = pix.unref();
        if (buffer.wl_buffer) |wl_buffer| wl_buffer.destroy();
        os.munmap(buffer.data);
    }

    fn buffer_listener(_: *wl.Buffer, event: wl.Buffer.Event, buffer: *Buffer) void {
        switch (event) {
            // Buffer is no longer used by the compositor. The client is free to reuse
            // or destroy this buffer and its backing storage.
            .release => {
                assert(buffer.busy);
                buffer.busy = false;
            },
        }
    }

    fn create_shm_fd() !os.fd_t {
        switch (builtin.target.os.tag) {
            .linux => {
                return os.memfd_createZ("agertu-shm-buffer-pool", os.linux.MFD_CLOEXEC);
            },
            .freebsd => {
                const freebsd = struct {
                    const MFD_CLOEXEC = 1;
                    extern fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int;
                };

                const ret = freebsd.memfd_create("agertu-shm-buffer-pool", freebsd.MFD_CLOEXEC);
                switch (os.errno(ret)) {
                    .SUCCESS => return ret,
                    .BADF => unreachable,
                    .INVAL => unreachable,
                    .NFILE => return error.SystemFdQuotaExceeded,
                    .MFILE => return error.ProcessFdQuotaExceeded,
                    else => |err| return os.unexpectedErrno(err),
                }
            },
            else => @compileError("target OS not supported"),
        }
    }
};

display: *wl.Display = undefined,
registry: *wl.Registry = undefined,

compositor: ?*wl.Compositor = null,
shm: ?*wl.Shm = null,
layer_shell: ?*zwlr.LayerShellV1 = null,
river_status_manager: ?*zriver.StatusManagerV1 = null,

outputs: std.SinglyLinkedList(Output) = .{},

pool: std.AutoHashMapUnmanaged(u32, Buffer) = .{},
next_buffer: ?*Buffer = null,

config: Config = undefined,

initialized: bool = false,

pub fn init(backend: *Backend, config: Config) !void {
    backend.* = .{
        .display = wl.Display.connect(null) catch {
            util.fatal(.backend, "failed to connect to Wayland compositor", .{});
        },
        .registry = try backend.display.getRegistry(),
        .config = config,
    };

    backend.registry.setListener(*Backend, registry_listener, backend);

    const errno = backend.display.roundtrip();
    if (errno != .SUCCESS) {
        util.fatal(.backend, "initial roundtrip failed: E{s}", .{@tagName(errno)});
    }

    if (backend.compositor == null) fatal_not_advertised(wl.Compositor);
    if (backend.shm == null) fatal_not_advertised(wl.Shm);
    if (backend.layer_shell == null) fatal_not_advertised(zwlr.LayerShellV1);

    try backend.init_pool_buffer(2);

    if (backend.display.roundtrip() == .SUCCESS) backend.initialized = true;
}

pub fn deinit(backend: *Backend) void {
    var it = backend.pool.valueIterator();
    while (it.next()) |buf| {
        buf.deinit();
    }
    backend.pool.deinit(util.gpa);

    if (backend.compositor) |compositor| compositor.destroy();
    if (backend.shm) |shm| shm.destroy();
    if (backend.layer_shell) |layer_shell| layer_shell.destroy();
    if (backend.river_status_manager) |status_mgr| status_mgr.destroy();

    while (backend.outputs.popFirst()) |node| {
        node.data.deinit();
        util.gpa.destroy(node);
    }

    backend.registry.destroy();
    backend.display.disconnect();

    backend.* = undefined;
}

fn init_pool_buffer(backend: *Backend, comptime n: usize) !void {
    var key: u32 = 0;
    while (key < n) : (key += 1) {
        try backend.pool.putNoClobber(util.gpa, key, Buffer{});
    }
}

fn get_next_buffer(backend: Backend, shm: *wl.Shm, width: u31, height: u31) !?*Buffer {
    var it = backend.pool.valueIterator();
    while (it.next()) |buf| {
        if (buf.busy) continue;
        if (buf.wl_buffer == null) {
            try buf.init(shm, width, height);
        }

        if (buf.width != width or buf.height != height) {
            buf.deinit();
            try buf.init(shm, width, height);
        }

        buf.busy = true;
        return buf;
    }

    return null;
}

/// REF: https://github.com/ifreund/waylock/blob/master/src/Lock.zig#L184
/// This function does the following:
///  1. Dispatch buffered wayland events to their listener callbacks.
///  2. Prepare the wayland connection for reading.
///  3. Send all buffered wayland requests to the server.
/// After this function has been called, either wl.Display.readEvents() or
/// wl.Display.cancelRead() read must be called.
pub fn flush_wayland_and_prepare_read(backend: *Backend) void {
    while (!backend.display.prepareRead()) {
        const errno = backend.display.dispatchPending();
        if (errno != .SUCCESS) {
            util.fatal(.backend, "failed to dispatch pending wayland events: E{s}", .{@tagName(errno)});
        }
    }

    while (true) {
        const errno = backend.display.flush();
        switch (errno) {
            .SUCCESS => return,
            .PIPE => {
                // libwayland uses this error to indicate that the wayland server
                // closed its side of the wayland socket. We want to continue to
                // read any buffered messages from the server though as there is
                // likely a protocol error message we'd like libwayland to log.
                _ = backend.display.readEvents();
                util.fatal(.backend, "connection to wayland server unexpectedly terminated", .{});
            },
            .AGAIN => {
                // The socket buffer is full, so wait for it to become writable again.
                var wayland_out = [_]os.pollfd{.{
                    .fd = backend.display.getFd(),
                    .events = os.POLL.OUT,
                    .revents = 0,
                }};
                _ = os.poll(&wayland_out, -1) catch |err| {
                    util.fatal(.backend, "poll() failed: {s}", .{@errorName(err)});
                };
                // No need to check for POLLHUP/POLLERR here, just fall
                // through to the next flush() to handle them in one place.
            },
            else => {
                util.fatal(.backend, "failed to flush wayland requests: E{s}", .{@tagName(errno)});
            },
        }
    }
}

fn registry_listener(registry: *wl.Registry, event: wl.Registry.Event, backend: *Backend) void {
    backend.registry_event(registry, event) catch |err| switch (err) {
        error.OutOfMemory => {
            log.err("out of memory", .{});
            return;
        },
        else => return,
    };
}

fn registry_event(backend: *Backend, registry: *wl.Registry, event: wl.Registry.Event) !void {
    switch (event) {
        .global => |ev| {
            if (std.cstr.cmp(ev.interface, wl.Compositor.getInterface().name) == 0) {
                backend.compositor = try registry.bind(ev.name, wl.Compositor, 4);
            } else if (std.cstr.cmp(ev.interface, wl.Shm.getInterface().name) == 0) {
                backend.shm = try registry.bind(ev.name, wl.Shm, 1);
            } else if (std.cstr.cmp(ev.interface, wl.Output.getInterface().name) == 0) {
                if (ev.version < 4) fatal_version(wl.Output, ev.version, 4);

                const wl_output = try registry.bind(ev.name, wl.Output, 4);
                errdefer wl_output.release();

                const node = try util.gpa.create(std.SinglyLinkedList(Output).Node);
                errdefer util.gpa.destroy(node);

                try node.data.init(backend, wl_output, ev.name);
                backend.outputs.prepend(node);

                if (backend.river_status_manager) |_| try node.data.get_output_status();
            } else if (std.cstr.cmp(ev.interface, zwlr.LayerShellV1.getInterface().name) == 0) {
                if (ev.version < 3) fatal_version(zwlr.LayerShellV1, ev.version, 3);
                backend.layer_shell = try registry.bind(ev.name, zwlr.LayerShellV1, 4);
            } else if (std.cstr.cmp(ev.interface, zriver.StatusManagerV1.getInterface().name) == 0) {
                backend.river_status_manager =
                    try registry.bind(ev.name, zriver.StatusManagerV1, 2);
            }
        },
        .global_remove => |ev| {
            var it = backend.outputs.first;
            while (it) |node| : (it = node.next) {
                if (node.data.wl_name == ev.name) {
                    node.data.deinit();
                    backend.outputs.remove(node);
                    break;
                }
            }
        },
    }
}

fn fatal_version(comptime Global: type, found_version: u32, req_version: u32) noreturn {
    util.fatal(
        .backend,
        "the advertised {s} version is too old({d}). Version {d} is required",
        .{ Global.getInterface().name, found_version, req_version },
    );
}

fn fatal_not_advertised(comptime Global: type) noreturn {
    util.fatal(.backend, "{s} not advertised", .{Global.getInterface().name});
}