summaryrefslogtreecommitdiff
path: root/src/objc.zig
blob: d9cad5f0a7dbfe03ce0441fcaf81fc0881271fc8 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//! Just enough of the Objective-C runtime to drive AppKit from Zig.
//! arm64 only: x86_64 would need objc_msgSend_stret for the struct returns.
const std = @import("std");

pub const id = ?*anyopaque;
pub const SEL = ?*anyopaque;

pub const NSRange = extern struct { location: usize = 0, length: usize = 0 };
pub const NSPoint = extern struct { x: f64 = 0, y: f64 = 0 };
pub const NSSize = extern struct { width: f64 = 0, height: f64 = 0 };
pub const NSRect = extern struct { origin: NSPoint = .{}, size: NSSize = .{} };

extern fn objc_msgSend() void;
extern fn objc_msgSendSuper() void;
extern fn objc_getClass(name: [*:0]const u8) id;
extern fn sel_registerName(name: [*:0]const u8) SEL;
extern fn objc_allocateClassPair(superclass: id, name: [*:0]const u8, extra_bytes: usize) id;
extern fn objc_registerClassPair(cls: id) void;
extern fn class_addMethod(cls: id, name: SEL, imp: *const anyopaque, types: [*:0]const u8) bool;

pub fn class(name: [*:0]const u8) id {
    return objc_getClass(name) orelse std.debug.panic("no class {s}", .{name});
}

pub fn sel(name: [*:0]const u8) SEL {
    return sel_registerName(name);
}

/// objc_msgSend has no prototype of its own: it must be called as the method's exact C
/// signature. Arguments therefore need concrete types (`@as(usize, 1)`, not `1`).
fn Fn(comptime R: type, comptime Recv: type, comptime Args: type) type {
    const a = @typeInfo(Args).@"struct".fields;
    return switch (a.len) {
        0 => fn (Recv, SEL) callconv(.c) R,
        1 => fn (Recv, SEL, a[0].type) callconv(.c) R,
        2 => fn (Recv, SEL, a[0].type, a[1].type) callconv(.c) R,
        3 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type) callconv(.c) R,
        4 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type) callconv(.c) R,
        6 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type, a[4].type, a[5].type) callconv(.c) R,
        9 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type, a[4].type, a[5].type, a[6].type, a[7].type, a[8].type) callconv(.c) R,
        10 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type, a[4].type, a[5].type, a[6].type, a[7].type, a[8].type, a[9].type) callconv(.c) R,
        else => @compileError("msg: add an arm for more arguments"),
    };
}

/// `[target name:args…]`
pub fn msg(comptime R: type, target: id, name: [*:0]const u8, args: anytype) R {
    const f: *const Fn(R, id, @TypeOf(args)) = @ptrCast(&objc_msgSend);
    return @call(.auto, f, .{ target, sel(name) } ++ args);
}

/// `[super name:args…]`, from inside a method of a subclass of `superclass`.
pub fn msgSuper(comptime R: type, self: id, superclass: [*:0]const u8, name: [*:0]const u8, args: anytype) R {
    const Super = extern struct { receiver: id, super_class: id };
    const f: *const Fn(R, *const Super, @TypeOf(args)) = @ptrCast(&objc_msgSendSuper);
    return @call(.auto, f, .{ &Super{ .receiver = self, .super_class = class(superclass) }, sel(name) } ++ args);
}

pub const Method = struct { name: [*:0]const u8, imp: *const anyopaque, types: [*:0]const u8 };

/// Define and register a class at run time.
pub fn subclass(superclass: [*:0]const u8, name: [*:0]const u8, methods: []const Method) id {
    const cls = objc_allocateClassPair(class(superclass), name, 0) orelse std.debug.panic("class {s} exists", .{name});
    for (methods) |m| _ = class_addMethod(cls, sel(m.name), m.imp, m.types);
    objc_registerClassPair(cls);
    return cls;
}

/// `[[Class alloc] init]`, owned by the caller.
pub fn new(class_name: [*:0]const u8) id {
    return msg(id, msg(id, class(class_name), "alloc", .{}), "init", .{});
}

const NSUTF8StringEncoding: usize = 4;

/// An autoreleased NSString.
pub fn str(s: []const u8) id {
    const raw = msg(id, class("NSString"), "alloc", .{});
    const ns = msg(id, raw, "initWithBytes:length:encoding:", .{ s.ptr, s.len, NSUTF8StringEncoding });
    return msg(id, ns, "autorelease", .{});
}

/// The NSString's UTF-8, valid for as long as the string is.
pub fn utf8(ns: id) []const u8 {
    const p = msg(?[*]const u8, ns, "UTF8String", .{}) orelse return "";
    const len = msg(usize, ns, "lengthOfBytesUsingEncoding:", .{NSUTF8StringEncoding});
    return p[0..len];
}