aboutsummaryrefslogtreecommitdiff
path: root/src/object/interface.zig
blob: 3098c4609df9383b083b4e067c4459cbb456f964 (plain)
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
const std = @import("std");
const wayland = @import("../root.zig");
const wl = wayland.wl;

pub fn Init(T: type) type {
    return struct {
        const Self = @This();

        pub fn default(
            self: *Self,
            ctx: wayland.Context,
        ) !void {
            const parent: *T = @alignCast(@fieldParentPtr("init", self));

            parent.* = .{
                .handle = try ctx.display.registry.add_object(
                    ctx.allocator,
                    wayland.Object.from_self(parent),
                ),
            };
        }

        pub fn with(
            self: *Self,
            ctx: wayland.Context,
            values: T,
        ) !void {
            const parent: *T = @alignCast(@fieldParentPtr("init", self));
            parent.* = values;
            parent.handle = try ctx.display.registry.add_object(
                ctx.allocator,
                wayland.Object.from_self(parent),
            );
        }
    };
}

pub fn Global(T: type) type {
    return struct {
        const Self = @This();

        pub const init = Self { };
        var instances: std.ArrayListUnmanaged(*T) = .empty;

        comptime register: fn (ctx: wayland.Context) ?wayland.Object.Ref = reg,

        pub fn reg(ctx: wayland.Context) ?wayland.Object.Ref {
            const interface = ctx.allocator.create(T) catch return null;
            interface.init.default(ctx) catch return null;

            instances.append(ctx.allocator, interface) catch return null;
            return interface.handle;
        }

        pub fn as_slice(self: *Self) []*T {
            _ = self;
            return instances.items;
        }

        pub fn get(self: *Self, index: usize) ?*T {
            _ = self;
            if (index >= instances.items.len) {
                return null;
            }
            return instances.items[index];
        }
    };
}