-
Notifications
You must be signed in to change notification settings - Fork 5
/
objc.lua
295 lines (267 loc) · 9.78 KB
/
objc.lua
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
#!/usr/bin/env luajit
local ffi = require("ffi")
local C = ffi.C
---@alias cdata userdata C types returned from FFI
---@alias id cdata Objective-C object
---@alias Class cdata Objective-C Class
---@alias SEL cdata Objective-C Selector
---@alias Method cdata Objective-C Method
ffi.cdef([[
// types
typedef signed char BOOL;
typedef double CGFloat;
typedef long NSInteger;
typedef unsigned long NSUInteger;
typedef struct objc_class *Class;
typedef struct objc_object *id;
typedef struct objc_selector *SEL;
typedef struct objc_method *Method;
typedef struct objc_property *objc_property_t;
typedef id (*IMP) (id, SEL, ...);
typedef struct CGPoint { CGFloat x; CGFloat y; } CGPoint;
typedef struct CGSize { CGFloat width; CGFloat height; } CGSize;
typedef struct CGRect { CGPoint origin; CGSize size; } CGRect;
// API
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types);
Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes);
Class objc_lookUpClass(const char *name);
Class object_getClass(id obj);
Method class_getClassMethod(Class cls, SEL name);
Method class_getInstanceMethod(Class cls, SEL name);
SEL sel_registerName(const char *str);
char * method_copyArgumentType(Method m, unsigned int index);
char * method_copyReturnType(Method m);
const char * class_getName(Class cls);
const char * object_getClassName(id obj);
const char * sel_getName(SEL sel);
objc_property_t class_getProperty(Class cls, const char *name);
unsigned int method_getNumberOfArguments(Method m);
void free(void *ptr);
void objc_msgSend(void);
void objc_registerClassPair(Class cls);
]])
ffi.load("/usr/lib/libobjc.A.dylib", true)
local type_encoding = setmetatable({
["c"] = "char",
["i"] = "int",
["s"] = "short",
["l"] = "long",
["q"] = "NSInteger",
["C"] = "unsigned char",
["I"] = "unsigned int",
["S"] = "unsigned short",
["L"] = "unsigned long",
["Q"] = "NSUInteger",
["f"] = "float",
["d"] = "double",
["B"] = "BOOL",
["v"] = "void",
["*"] = "char*",
["@"] = "id",
["#"] = "Class",
[":"] = "SEL",
["^"] = "void*",
["?"] = "void",
["r*"] = "char*",
}, {
__index = function(_, k)
assert(type(k) == "string" and #k > 2)
local first_letter = k:sub(1, 1)
if first_letter == "{" or first_letter == "(" then -- named struct or union
return assert(select(3, k:find("%" .. first_letter .. "(%a+)=")))
end
end,
__newindex = nil, -- read only table
})
---convert a NULL pointer to nil
---@param p cdata pointer
---@return cdata | nil
local function ptr(p)
if p == nil then return nil else return p end
end
---return a Class from name or object
---@param name string | Class | id
---@return Class
local function cls(name)
assert(name)
if ffi.istype("id", name) then
return assert(ptr(C.object_getClass(name))) -- get class from object
end
if type(name) == "cdata" and ffi.istype("Class", name) then
return name -- already a Class
end
assert(type(name) == "string")
return assert(ptr(C.objc_lookUpClass(name)))
end
---return SEL from name
---@param name string | SEL
---@param num_args? integer
---@return SEL
local function sel(name, num_args)
assert(name)
if type(name) == "cdata" and ffi.istype("SEL", name) then
return name -- already a SEL
end
assert(type(name) == "string")
if num_args and num_args > 0 and name:sub(-1) ~= "_" then
name = name .. "_"
end
local name, count = name:gsub("_", ":")
if num_args then assert(count == num_args) end
return C.sel_registerName(name) -- pointer is never NULL
end
---call a method for a SEL on a Class or object
---@param receiver string | Class | id the class or object
---@param selector string | SEL name of method
---@param ...? any additional method parameters
---@return any
local function msgSend(receiver, selector, ...)
---return Method for Class or object and SEL
---@param receiver Class | id
---@param selector SEL
---@return Method?
local function getMethod(receiver, selector)
-- return method for Class or object and SEL
if ffi.istype("Class", receiver) then
return assert(ptr(C.class_getClassMethod(receiver, selector)))
elseif ffi.istype("id", receiver) then
return assert(ptr(C.class_getInstanceMethod(cls(receiver), selector)))
end
assert(false, "receiver not a Class or object")
end
---convert a Lua variable to a C type if needed
---@param lua_var any
---@param c_type string
---@return cdata | any
local function convert(lua_var, c_type)
if type(lua_var) == "string" then
if c_type == "SEL" then
-- print("creating SEL from " .. lua_var)
return sel(lua_var)
elseif c_type == "char*" then
-- print("creating char* from " .. lua_var)
return ffi.cast(c_type, lua_var)
end
elseif type(lua_var) == "cdata" and c_type == "id" and ffi.istype("Class", lua_var) then
-- sometimes method signatures use id instead of Class
-- print("casting " .. tostring(lua_var) .. " to id")
return ffi.cast(c_type, lua_var)
end
return lua_var -- no conversion necessary
end
if type(receiver) == "string" then receiver = cls(receiver) end
local selector = sel(selector)
local method = getMethod(receiver, selector)
local call_args = { receiver, selector, ... }
local char_ptr = assert(ptr(C.method_copyReturnType(method)))
local objc_type = ffi.string(char_ptr)
C.free(char_ptr)
local c_type = assert(type_encoding[objc_type])
local signature = {}
table.insert(signature, c_type)
table.insert(signature, "(*)(")
local num_method_args = C.method_getNumberOfArguments(method)
assert(num_method_args == #call_args)
for i = 1, num_method_args do
char_ptr = assert(ptr(C.method_copyArgumentType(method, i - 1)))
objc_type = ffi.string(char_ptr)
C.free(char_ptr)
c_type = assert(type_encoding[objc_type])
table.insert(signature, c_type)
call_args[i] = convert(call_args[i], c_type)
if i < num_method_args then table.insert(signature, ",") end
end
table.insert(signature, ")")
local signature = table.concat(signature)
-- print(receiver, selector, signature)
return ffi.cast(signature, C.objc_msgSend)(unpack(call_args))
end
---load a Framework
---@param framework string framework name without the '.framework' extension
local function loadFramework(framework)
-- on newer versions of MacOS this is a broken symbolic link, but dlopen() still succeeds
ffi.load(string.format("/System/Library/Frameworks/%s.framework/%s", framework, framework), true)
end
---create a new custom class from an optional base class
---@param name string name of new class
---@param super_class? string | Class parent class, or NSObject if omitted
---@return Class
local function newClass(name, super_class)
assert(name and type(name) == "string")
local super_class = cls(super_class or "NSObject")
local class = assert(ptr(C.objc_allocateClassPair(super_class, name, 0)))
C.objc_registerClassPair(class)
return class
end
---add a method to a custom class
---@param class string | Class class created with newClass()
---@param selector string | SEL name of method
---@types string Objective-C type encoded method arguments and return type
---@func function lua callback function for method implementation
local function addMethod(class, selector, types, func)
assert(type(func) == "function")
assert(type(types) == "string")
local class = cls(class)
local selector = sel(selector)
local signature = {}
table.insert(signature, type_encoding[types:sub(1, 1)]) -- return type
table.insert(signature, "(*)(") -- anonymous function
for i = 2, #types do
table.insert(signature, type_encoding[types:sub(i, i)])
if i < #types then table.insert(signature, ",") end
end
table.insert(signature, ")")
local signature = table.concat(signature)
-- print(class, selector, signature, types)
local imp = ffi.cast("IMP", ffi.cast(signature, func))
assert(C.class_addMethod(class, selector, imp, types) == 1)
end
local objc = setmetatable({
Class = cls,
SEL = sel,
addMethod = addMethod,
loadFramework = loadFramework,
msgSend = msgSend,
newClass = newClass,
ptr = ptr,
}, {
__index = function(_, name)
-- use key to lookup class by name
return cls(name)
end
})
ffi.metatype("struct objc_selector", {
__tostring = function(selector)
return ffi.string(assert(ptr(C.sel_getName(selector))))
end
})
ffi.metatype("struct objc_class", {
__tostring = function(class)
return ffi.string(assert(ptr(C.class_getName(class))))
end,
__index = function(class, selector)
return function(self, ...)
assert(class == self)
return msgSend(self, sel(selector, select("#", ...)), ...)
end
end
})
ffi.metatype("struct objc_object", {
__tostring = function(class)
return ffi.string(assert(ptr(C.object_getClassName(class))))
end,
__index = function(object, selector)
if ptr(C.class_getProperty(cls(object), selector)) then
return msgSend(object, sel(selector))
end
return function(self, ...)
assert(object == self)
return msgSend(self, sel(selector, select("#", ...)), ...)
end
end,
__newindex = function(object, selector, value)
selector = string.format('set%s%s:', selector:sub(1, 1):upper(), selector:sub(2))
msgSend(object, sel(selector), value) -- propertyName to setPropertyName
end
})
return objc