-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
api.py
2320 lines (1891 loc) · 92.4 KB
/
api.py
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections.abc
import decimal
import enum
import inspect
import threading
import weakref
from ctypes import (
CFUNCTYPE,
POINTER,
Array,
Structure,
Union,
addressof,
byref,
c_bool,
c_char_p,
c_int,
c_uint,
c_uint8,
c_ulong,
c_void_p,
cast,
py_object,
sizeof,
string_at,
)
from .runtime import (
SEL,
Class,
add_ivar,
add_method,
ensure_bytes,
get_class,
get_ivar,
libc,
libobjc,
objc_block,
objc_id,
objc_property_attribute_t,
object_isClass,
send_message,
send_super,
set_ivar,
)
from .types import (
compound_value_for_sequence,
ctype_for_type,
ctypes_for_method_encoding,
encoding_for_ctype,
register_ctype_for_type,
)
__all__ = [
"Block",
"NSArray",
"NSData",
"NSDecimalNumber",
"NSDictionary",
"NSMutableArray",
"NSMutableDictionary",
"NSNumber",
"NSObject",
"NSObjectProtocol",
"NSString",
"ObjCBlock",
"ObjCClass",
"ObjCInstance",
"ObjCMetaClass",
"ObjCProtocol",
"Protocol",
"at",
"for_objcclass",
"get_type_for_objcclass_map",
"ns_from_py",
"objc_classmethod",
"objc_const",
"objc_ivar",
"objc_method",
"objc_property",
"objc_rawmethod",
"py_from_ns",
"register_type_for_objcclass",
"type_for_objcclass",
"unregister_type_for_objcclass",
]
# Dictionary to keep references to Python objects which are stored in declared
# properties or dynamically created attributes of Objective-C objects. This ensures that
# the Python objects are not destroyed if they are otherwise no Python references left.
_keep_alive_objects = {}
def encoding_from_annotation(f, offset=1):
argspec = inspect.getfullargspec(inspect.unwrap(f))
encoding = [argspec.annotations.get("return", ObjCInstance), ObjCInstance, SEL]
for varname in argspec.args[offset:]:
encoding.append(argspec.annotations.get(varname, ObjCInstance))
return encoding
class ObjCMethod:
"""An unbound Objective-C method. This is Rubicon's high-level equivalent
of :class:`~rubicon.objc.runtime.Method`.
:class:`ObjCMethod` objects normally don't need to be used directly. To call
a method on an Objective-C object, you should use the method call syntax
supported by :class:`ObjCInstance`, or the
:func:`~rubicon.objc.runtime.send_message` function.
.. note::
This is *not* the same class as the one used for *bound* Objective-C
methods, as returned from :meth:`ObjCInstance.__getattr__`. Currently,
Rubicon doesn't provide any documented way to get an unbound
:class:`ObjCMethod` object for an instance method of an
:class:`ObjCClass`.
"""
def __init__(self, method):
"""The constructor takes a :class:`~rubicon.objc.runtime.Method`
object, whose information is used to create an :class:`ObjCMethod`.
This can be used to call or introspect a
:class:`~rubicon.objc.runtime.Method` pointer received from the
Objective-C runtime.
"""
self.selector = libobjc.method_getName(method)
self.name = self.selector.name
self.encoding = libobjc.method_getTypeEncoding(method)
self.restype, *self.imp_argtypes = ctypes_for_method_encoding(self.encoding)
assert self.imp_argtypes[:2] == [objc_id, SEL]
self.method_argtypes = self.imp_argtypes[2:]
def __repr__(self):
return f"<ObjCMethod: {self.name} {self.encoding}>"
def __call__(self, receiver, *args, convert_args=True, convert_result=True):
"""Call the method on an object with the given arguments.
The passed arguments are automatically converted to the expected
argument types as needed:
* :class:`enum.Enum` objects are replaced by their
:attr:`~enum.Enum.value` before further conversion
* For parameters that expect a block, Python callables are converted to
:class:`Block`\\s
* For parameters that expect an Objective-C object, Python objects are
converted using :func:`ns_from_py`
* For parameters that expect a C structure, Python sequences are
converted using
:func:`~rubicon.objc.types.compound_value_for_sequence`.
* Finally, :mod:`ctypes` applies its normal function argument
conversions.
The above argument conversions (except those performed by :mod:`ctypes`)
can be disabled by setting the ``convert_args`` keyword argument to
``False``.
If the method returns an Objective-C object, it is automatically
converted to an :class:`ObjCInstance`. This conversion can be disabled
by setting the ``convert_result`` keyword argument to ``False``, in
which case the object is returned as a raw
:class:`~rubicon.objc.runtime.objc_id` value.
The ``_cmd`` selector argument does *not* need to be passed in manually
--- the method's :attr:`selector` is automatically added between the
receiver and the method arguments.
"""
if len(args) != len(self.method_argtypes):
raise TypeError(
f"Method {self.name} takes {len(args)} arguments, but got {len(self.method_argtypes)} arguments"
)
if convert_args:
converted_args = []
for argtype, arg in zip(self.method_argtypes, args):
if isinstance(arg, enum.Enum):
# Convert Python enum objects to their values
arg = arg.value
if issubclass(argtype, objc_block):
if arg is None:
# allow for 'nil' block args, which some objc methods accept
arg = ns_from_py(arg)
elif callable(arg) and not isinstance(
arg, Block
): # <-- guard against someone someday making Block callable
# Note: We need to keep the temp. Block instance
# around at least until the objc method is called.
# _as_parameter_ is used in the actual ctypes marshalling below.
arg = Block(arg)
# ^ For blocks at this point either arg is a Block instance
# (making use of _as_parameter_), is None, or if it isn't either of
# those two, an ArgumentError will be raised below.
elif issubclass(argtype, objc_id):
# Convert Python objects to Foundation objects
arg = ns_from_py(arg)
elif isinstance(arg, collections.abc.Sequence) and issubclass(
argtype, (Structure, Array)
):
arg = compound_value_for_sequence(arg, argtype)
converted_args.append(arg)
else:
converted_args = args
result = send_message(
receiver,
self.selector,
*converted_args,
restype=self.restype,
argtypes=self.method_argtypes,
)
if not convert_result:
return result
# Convert result to python type if it is a instance or class pointer.
if self.restype is not None and issubclass(self.restype, objc_id):
result = ObjCInstance(result)
# Mark for release if we acquire ownership of an object. Do not autorelease here because
# we might retain a Python reference while the Obj-C reference goes out of scope.
if self.name.startswith((b"alloc", b"new", b"copy", b"mutableCopy")):
result._needs_release = True
return result
class ObjCPartialMethod:
_sentinel = object()
def __init__(self, name_start):
super().__init__()
self.name_start = name_start
self.methods = {} # Initialized in ObjCClass._load_methods
def __repr__(self):
return f"{type(self).__module__}.{type(self).__qualname__}({self.name_start!r})"
def __call__(self, receiver, first_arg=_sentinel, **kwargs):
if first_arg is ObjCPartialMethod._sentinel:
if kwargs:
raise TypeError("Missing first (positional) argument")
args = []
rest = frozenset()
else:
args = [first_arg]
# Add "" to rest to indicate that the method takes arguments
rest = frozenset(kwargs) | frozenset(("",))
try:
name, order = self.methods[rest]
except KeyError:
raise ValueError(
f"No method was found starting with {self.name_start!r} and with keywords {set(kwargs)}\nKnown keywords are:\n"
+ "\n".join(repr(keywords) for keywords in self.methods)
)
meth = receiver.objc_class._cache_method(name)
args += [kwargs[name] for name in order]
return meth(receiver, *args)
class ObjCBoundMethod:
"""This represents an Objective-C method (an IMP) which has been bound to
some id which will be passed as the first parameter to the method.
"""
def __init__(self, method, receiver):
"""Initialize with a method and ObjCInstance or ObjCClass object."""
self.method = method
if type(receiver) == Class:
self.receiver = cast(receiver, objc_id)
else:
self.receiver = receiver
def __repr__(self):
return f"{type(self).__module__}.{type(self).__qualname__}({self.method}, {self.receiver})"
def __call__(self, *args, **kwargs):
"""Call the method with the given arguments."""
return self.method(self.receiver, *args, **kwargs)
def convert_method_arguments(encoding, args):
"""Used to convert Objective-C method arguments to Python values before
passing them on to the Python-defined method.
"""
new_args = []
for e, a in zip(encoding[3:], args):
if issubclass(e, (objc_id, ObjCInstance)):
new_args.append(ObjCInstance(a))
else:
new_args.append(a)
return new_args
class objc_method:
"""Exposes the decorated method as an Objective-C instance method in a
custom class or protocol.
In a custom Objective-C class, decorating a method with :func:`@objc_method
<objc_method>` makes it available to Objective-C: a corresponding
Objective-C method is created in the new Objective-C class, whose
implementation calls the decorated Python method. The Python method receives
all arguments (including ``self``) from the Objective-C method call, and its
return value is passed back to Objective-C.
In a custom Objective-C protocol, the behavior is similar, but the method
body is ignored, since Objective-C protocol methods have no implementations.
By convention, the method body in this case should be empty (``pass``).
(Since the method is never called, you could put any other code there as
well, but doing so is misleading and discouraged.)
"""
def __init__(self, py_method):
super().__init__()
self.py_method = py_method
self.encoding = encoding_from_annotation(py_method)
def __call__(self, objc_self, objc_cmd, *args):
py_self = ObjCInstance(objc_self)
args = convert_method_arguments(self.encoding, args)
result = self.py_method(py_self, *args)
if self.encoding[0] is not None and issubclass(
self.encoding[0], (objc_id, ObjCInstance)
):
result = ns_from_py(result)
if result is not None:
result = result.ptr
if isinstance(result, c_void_p):
return result.value
else:
return result
def class_register(self, class_ptr, attr_name):
name = attr_name.replace("_", ":")
add_method(class_ptr, name, self, self.encoding)
def protocol_register(self, proto_ptr, attr_name):
name = attr_name.replace("_", ":")
types = b"".join(encoding_for_ctype(ctype_for_type(tp)) for tp in self.encoding)
libobjc.protocol_addMethodDescription(proto_ptr, SEL(name), types, True, True)
class objc_classmethod:
"""Exposes the decorated method as an Objective-C class method in a custom
class or protocol.
This decorator behaves exactly like :func:`@objc_method <objc_method>`,
except that the decorated method becomes a class method, so it is exposed
on the Objective-C class rather than its instances.
"""
def __init__(self, py_method):
super().__init__()
self.py_method = py_method
self.encoding = encoding_from_annotation(py_method)
def __call__(self, objc_cls, objc_cmd, *args):
py_cls = ObjCClass(objc_cls)
args = convert_method_arguments(self.encoding, args)
result = self.py_method(py_cls, *args)
if self.encoding[0] is not None and issubclass(
self.encoding[0], (objc_id, ObjCInstance)
):
result = ns_from_py(result)
if result is not None:
result = result.ptr
if isinstance(result, c_void_p):
return result.value
else:
return result
def class_register(self, class_ptr, attr_name):
name = attr_name.replace("_", ":")
add_method(libobjc.object_getClass(class_ptr), name, self, self.encoding)
def protocol_register(self, proto_ptr, attr_name):
name = attr_name.replace("_", ":")
types = b"".join(encoding_for_ctype(ctype_for_type(tp)) for tp in self.encoding)
libobjc.protocol_addMethodDescription(proto_ptr, SEL(name), types, True, False)
class objc_ivar:
"""Defines an ivar in a custom Objective-C class.
If you want to store additional data on a custom Objective-C class, it is
recommended to use properties (:func:`objc_property`) instead of ivars.
Properties are a more modern and high-level Objective-C feature, which
automatically deal with reference counting for objects, and creation of
getters and setters.
The ivar type may be any :mod:`ctypes` type.
Unlike properties, the contents of an ivar cannot be accessed or modified
using Python attribute syntax. Instead, the :func:`get_ivar` and
:func:`set_ivar` functions need to be used.
"""
def __init__(self, vartype):
self.vartype = vartype
def class_register(self, class_ptr, attr_name):
return add_ivar(class_ptr, attr_name, self.vartype)
def protocol_register(self, proto_ptr, attr_name):
raise TypeError("Objective-C protocols cannot have ivars")
class objc_property:
"""Defines a property in a custom Objective-C class or protocol.
This class should be called in the body of an Objective-C subclass or
protocol, for example:
.. code-block:: python
class MySubclass(NSObject):
counter = objc_property(NSInteger)
The property type may be any :mod:`ctypes` type, as well as any of the
Python types accepted by :func:`~rubicon.objc.types.ctype_for_type`.
Defining a property automatically defines a corresponding getter and setter.
Following standard Objective-C naming conventions, for a property ``name``
the getter is called ``name`` and the setter is called ``setName:``.
In a custom Objective-C class, implementations for the getter and setter are
also generated, which store the property's value in an ivar called
``_name``. If the property has an object type, the generated setter keeps
the stored object retained, and releases it when it is replaced.
In a custom Objective-C protocol, only the metadata for the property is
generated.
If ``weak`` is ``True``, the property will be created as a weak property.
When assigning an object to it, the reference count of the object will not
be increased. When the object is deallocated, the property value is set to
None. Weak properties are only supported for Objective-C or Python object
types.
"""
def __init__(self, vartype=objc_id, weak=False):
super().__init__()
self.vartype = ctype_for_type(vartype)
self.weak = weak
self._is_py_object = issubclass(self.vartype, py_object)
self._is_objc_object = issubclass(self.vartype, objc_id)
# Weakly referenced Python objects are still stored in strong ivars.
# Check here if we need a weak or strong ivar.
self._ivar_weak = self.weak and not self._is_py_object
if self.weak and not (self._is_py_object or self._is_objc_object):
raise TypeError(
"Incompatible type for ivar {!r}: Weak properties are only supported "
"for Objective-C or Python object types".format(vartype)
)
def _get_property_attributes(self):
attrs = [
# Type: vartype
objc_property_attribute_t(b"T", encoding_for_ctype(self.vartype)),
]
if self._is_objc_object:
reference = b"W" if self.weak else b"&"
attrs.append(objc_property_attribute_t(reference, b""))
return (objc_property_attribute_t * len(attrs))(*attrs)
def class_register(self, class_ptr, attr_name):
ivar_name = "_" + attr_name
add_ivar(class_ptr, ivar_name, self.vartype)
# Implementation note:
# 1. Objective-C objects are stored as strong or weak references in the
# ivar if the property was declared as strong or weak, respectively.
# In case of strong properties, we retain the object when storing it
# in the ivar and release it when the ivar is changed.
# 2. Python objects are wrapped as `ctypes.py_object` which are then
# always stored as a strong reference in the ivar. Since this does
# not increase the reference count of the Python object itself, we
# keep a reference to it in `_keep_alive_objects`. For weak
# properties, we store a Python `wearef` to the object instead. This
# weakref is similarly kept alive.
def _objc_getter(objc_self, _cmd):
value = get_ivar(objc_self, ivar_name, weak=self._ivar_weak)
# ctypes complains when a callback returns a "boxed" primitive type,
# so we have to manually unbox it. If the data object has a value
# attribute and is not a structure or union, assume that it is a
# primitive and unbox it.
if not isinstance(value, (Structure, Union)):
try:
value = value.value
except AttributeError:
pass
if self.weak and self._is_py_object:
# Unpack the Python weakref.
value = value()
return value
def _objc_setter(objc_self, _cmd, new_value):
if self._is_py_object and self.weak:
# Don't store the object itself but only a Python weakref.
new_value = weakref.ref(new_value)
if not isinstance(new_value, self.vartype):
# If vartype is a primitive, then new_value may be unboxed. If
# that is the case, box it manually.
new_value = self.vartype(new_value)
if self._is_objc_object and not self.weak:
# If vartype is objc_id, retrieve the old object stored in the
# ivar to release it later.
old_value = get_ivar(objc_self, ivar_name, weak=self.weak)
if new_value.value == old_value.value:
# Old and new value are the same, nothing to do.
return
set_ivar(objc_self, ivar_name, new_value, weak=self._ivar_weak)
# Perform reference management.
if self._is_objc_object and not self.weak:
if old_value:
# If the old value is a non-null Objective-C object, release it.
send_message(old_value, "release", restype=None, argtypes=[])
if new_value:
# Retain the object on the Objective-C side.
send_message(new_value, "retain", restype=objc_id, argtypes=[])
elif self._is_py_object:
# Retain the Python object in dictionary, this replaces any
# previous entry for this property.
_keep_alive_objects[(objc_self.value, self)] = new_value.value
setter_name = "set" + attr_name[0].upper() + attr_name[1:] + ":"
add_method(
class_ptr,
attr_name,
_objc_getter,
[self.vartype, ObjCInstance, SEL],
)
add_method(
class_ptr,
setter_name,
_objc_setter,
[None, ObjCInstance, SEL, self.vartype],
)
attrs = self._get_property_attributes()
libobjc.class_addProperty(class_ptr, ensure_bytes(attr_name), attrs, len(attrs))
def dealloc_callback(self, objc_self, attr_name):
ivar_name = "_" + attr_name
if self._ivar_weak:
# Clean up weak reference.
set_ivar(objc_self, ivar_name, self.vartype(None), weak=True)
elif self._is_objc_object:
# If the old value is a non-null object, release it. There is no
# need to set the actual ivar to nil.
old_value = get_ivar(objc_self, ivar_name, weak=self.weak)
send_message(old_value, "release", restype=None, argtypes=[])
# Remove any Python objects that are kept alive.
_keep_alive_objects.pop((objc_self.value, self), None)
def protocol_register(self, proto_ptr, attr_name):
attrs = self._get_property_attributes()
libobjc.protocol_addProperty(
proto_ptr, ensure_bytes(attr_name), attrs, len(attrs), True, True
)
class objc_rawmethod:
"""Exposes the decorated method as an Objective-C instance method in a
custom class, with fewer convenience features than :func:`objc_method`.
This decorator behaves similarly to :func:`@objc_method <objc_method>`.
However, unlike with :func:`objc_method`, no automatic conversions are
performed (aside from those by :mod:`ctypes`). This means that all parameter
and return types must be provided as :mod:`ctypes` types (no
:func:`~rubicon.objc.types.ctype_for_type` conversion is performed), all
arguments are passed in their raw form as received from :mod:`ctypes`, and
the return value must be understood by :mod:`ctypes`.
In addition, the implicit ``_cmd`` parameter is exposed to the Python
method, which is not the case when using :func:`objc_method`. This means
that the decorated Python method must always have an additional ``_cmd``
parameter after ``self``; if it is missing, there will be errors at runtime
due to mismatched argument counts. Like ``self``, ``_cmd`` never needs to be
annotated, and any annotations on it are ignored.
"""
def __init__(self, py_method):
super().__init__()
self.py_method = py_method
self.encoding = encoding_from_annotation(py_method, offset=2)
def __call__(self, *args, **kwargs):
return self.py_method(*args, **kwargs)
def class_register(self, class_ptr, attr_name):
name = attr_name.replace("_", ":")
add_method(class_ptr, name, self, self.encoding)
def protocol_register(self, proto_ptr, attr_name):
raise TypeError(
"Protocols cannot have method implementations, "
"use objc_method instead of objc_rawmethod"
)
_type_for_objcclass_map = {}
def type_for_objcclass(objcclass):
"""Look up the :class:`ObjCInstance` subclass used to represent instances
of the given Objective-C class in Python.
If the exact Objective-C class is not registered, each superclass is also
checked, defaulting to :class:`ObjCInstance` if none of the classes in the
superclass chain is registered. Afterwards, all searched superclasses are
registered for the :class:`ObjCInstance` subclass that was found. (This
speeds up future lookups, and ensures that previously computed mappings are
not changed by unrelated registrations.)
This method is mainly intended for internal use by Rubicon, but is exposed
in the public API for completeness.
"""
if isinstance(objcclass, ObjCClass):
objcclass = objcclass.ptr
superclass = objcclass
traversed_classes = []
pytype = ObjCInstance
while superclass.value is not None:
try:
pytype = _type_for_objcclass_map[superclass.value]
except KeyError:
traversed_classes.append(superclass)
superclass = libobjc.class_getSuperclass(superclass)
else:
break
for cls in traversed_classes:
register_type_for_objcclass(pytype, cls)
return pytype
def register_type_for_objcclass(pytype, objcclass):
"""Register a conversion from an Objective-C class to an
:class:`ObjCInstance` subclass.
After a call of this function, when Rubicon wraps an Objective-C object that
is an instance of ``objcclass`` (or a subclass), the Python object will have
the class ``pytype`` rather than :class:`ObjCInstance`. See
:func:`type_for_objcclass` for a full description of the lookup process.
.. warning::
This function should only be called if no instances of ``objcclass`` (or
a subclass) have been wrapped by Rubicon yet. If the function is called
later, it will not fully take effect: the types of existing instances do
not change, and mappings for subclasses of ``objcclass`` are not
updated.
"""
if isinstance(objcclass, ObjCClass):
objcclass = objcclass.ptr
_type_for_objcclass_map[objcclass.value] = pytype
def unregister_type_for_objcclass(objcclass):
"""Unregister a conversion from an Objective-C class to an
:class:`ObjCInstance` subclass.
.. warning::
This function should only be called if no instances of ``objcclass`` (or
a subclass) have been wrapped by Rubicon yet. If the function is called
later, it will not fully take effect: the types of existing instances do
not change, and mappings for subclasses of ``objcclass`` are not
removed.
"""
if isinstance(objcclass, ObjCClass):
objcclass = objcclass.ptr
del _type_for_objcclass_map[objcclass.value]
def get_type_for_objcclass_map():
"""Get a copy of all currently registered :class:`ObjCInstance` subclasses
as a mapping.
Keys are Objective-C class addresses as :class:`int`\\s.
"""
return dict(_type_for_objcclass_map)
def for_objcclass(objcclass):
"""Decorator for registering a conversion from an Objective-C class to an
:class:`ObjCInstance` subclass.
This is equivalent to calling :func:`register_type_for_objcclass` on
the decorated class.
"""
def _for_objcclass(pytype):
register_type_for_objcclass(pytype, objcclass)
return pytype
return _for_objcclass
class ObjCInstance:
"""Python wrapper for an Objective-C instance."""
# Cache dictionary containing every currently existing ObjCInstance object,
# with the key being the memory address (as an integer) of the Objective-C
# object that it wraps. Because this is a weak value dictionary, entries are
# automatically removed if the ObjCInstance is no longer referenced from
# Python. (The object may still have references in Objective-C, and a new
# ObjCInstance might be created for it if it is wrapped again later.)
_cached_objects = weakref.WeakValueDictionary()
# A re-entrant thread lock moderating access to
# ObjCInstance._cached_objects. When creating new instances, there is a time
# gap between determining there has been a cache miss, and the addition of a
# new instance into the cache. This leaves a gap where a separate thread
# could wrap the same pointer, and creating a second wrapper; whichever
# wrapper is written to the cache first will be overwritten by the second.
# This probably won't cause any observable problems - both instances will be
# valid wrappers around the same memory address, but it's memory that we
# don't need to allocate. The lock is re-entrant because allocating an
# instance can cause the creation of additional instances, especially at
# time of bootstrapping.
#
# Refs #251.
_instance_lock = threading.RLock()
@property
def objc_class(self):
"""The Objective-C object's class, as an :class:`ObjCClass`."""
# This property is used inside __getattr__, so any attribute accesses must be done through
# super(...).__getattribute__ to prevent infinite recursion.
try:
return super(ObjCInstance, type(self)).__getattribute__(self, "_objc_class")
except AttributeError:
# This assumes that objects never change their class after they are
# seen by Rubicon. There are two reasons why this may not be true:
#
# 1. Objective-C runtime provides a function object_setClass that
# can change an object's class after creation, and some code
# manipulates objects' isa pointers directly (although the latter
# is no longer officially supported by Apple). This is not
# commonly done in practice, and even then it is usually only
# done during object creation/initialization, so it's basically
# safe to assume that an object's class will never change after
# it's been wrapped in an ObjCInstance.
# 2. If a memory address is freed by the Objective-C runtime, and
# then re-allocated by an object of a different type, but the
# Python ObjCInstance wrapper persists, Python will assume the
# object is still of the old type. If a new ObjCInstance wrapper
# for the same pointer is re-created, a check is performed to
# ensure the type hasn't changed; this problem only affects
# pre-existing Python wrappers. If this occurs, it probably
# indicates an issue with the retain count on the Python side (as
# the Objective-C runtime shouldn't be able to dispose of an
# object if Python still has a handle to it). If this *does*
# happen, it will manifest as objects appearing to be the wrong
# type, and/or objects having the wrong list of attributes
# available. Refs #249.
super(ObjCInstance, type(self)).__setattr__(
self, "_objc_class", ObjCClass(libobjc.object_getClass(self))
)
return super(ObjCInstance, type(self)).__getattribute__(self, "_objc_class")
@staticmethod
def _associated_attr_key_for_name(name):
return SEL(f"rubicon.objc.py_attr.{name}")
def __new__(cls, object_ptr, _name=None, _bases=None, _ns=None):
"""The constructor accepts an :class:`~rubicon.objc.runtime.objc_id` or
anything that can be cast to one, such as a :class:`~ctypes.c_void_p`,
or an existing :class:`ObjCInstance`.
:class:`ObjCInstance` objects are cached --- this means that for every
Objective-C object there can be at most one :class:`ObjCInstance` object
at any time. Rubicon will automatically create new
:class:`ObjCInstance`\\s or return existing ones as needed.
The returned object's Python class is not always exactly
:class:`ObjCInstance`. For example, if the passed pointer refers to a
class or a metaclass, an instance of :class:`ObjCClass` or
:class:`ObjCMetaClass` is returned as appropriate. Additional custom
:class:`ObjCInstance` subclasses may be defined and registered using
:func:`register_type_for_objcclass`. Creating an :class:`ObjCInstance`
from a ``nil`` pointer returns ``None``.
Rubicon currently does not perform any automatic memory management on
the Objective-C object wrapped in an :class:`ObjCInstance`. It is the
user's responsibility to ``retain`` and ``release`` wrapped objects as
needed, like in Objective-C code without automatic reference counting.
"""
# Make sure that object_ptr is wrapped in an objc_id.
if not isinstance(object_ptr, objc_id):
object_ptr = cast(object_ptr, objc_id)
# If given a nil pointer, return None.
if not object_ptr.value:
return None
with ObjCInstance._instance_lock:
try:
# If an ObjCInstance already exists for the Objective-C object,
# reuse it instead of creating a second ObjCInstance for the
# same object.
cached = cls._cached_objects[object_ptr.value]
# In a high-churn environment, it is possible for an object to
# be deallocated, and the same memory address be re-used on the
# Objective-C side, but the Python wrapper object for the
# original instance has *not* been cleaned up. In that
# situation, an attempt to wrap the *new* Objective-C object
# instance will cause a false positive cache hit; returning a
# Python object that has a class that doesn't match the class of
# the new instance.
#
# To prevent this, when we get a cache hit on an ObjCInstance,
# use the raw Objective-C API on the pointer to get the current
# class of the object referred to by the pointer. If there's a
# discrepancy, purge the cache for the memory address, and
# re-create the object.
#
# We do this both when the type *is* ObjCInstance (the case when
# instantiating a literal ObjCInstance()), and when type is an
# ObjCClass instance (e.g., ObjClass("Example"), which is the
# type of a directly instantiated instance of Example.
#
# We *don't* do this when the type *is* ObjCClass,
# ObjCMetaClass, as there's a race condition on startup -
# retrieving `.objc_class` causes the creation of ObjCClass
# objects, which will cause cache hits trying to re-use existing
# ObjCClass objects. However, ObjCClass instances generally
# won't be recycled or reused, so that should be safe to exclude
# from the cache freshness check.
#
# One edge case with this approach: if the old and new
# Objective-C objects have the same class, they won't be
# identified as a stale object, and they'll re-use the same
# Python wrapper. This effectively means id(obj) isn't a
# reliable instance identifier... but (a) this won't be a common
# case; (b) this flaw exists in pure Python and Objective-C as
# well, because default object identity is tied to memory
# allocation; and (c) the stale wrapper will *work*, because
# it's the correct class.
#
# Refs #249.
if cls == ObjCInstance or isinstance(cls, ObjCInstance):
cached_class_name = ensure_bytes(cached.objc_class.name)
current_class_name = libobjc.class_getName(
libobjc.object_getClass(object_ptr)
)
if cached_class_name != current_class_name:
# There has been a cache hit, but the object is a different class.
# Purge the cache for this address, and treat it as a cache miss.
del cls._cached_objects[object_ptr.value]
raise KeyError(object_ptr.value)
return cached
except KeyError:
pass
# If the given pointer points to a class, return an ObjCClass instead (if we're not already creating one).
if not issubclass(cls, ObjCClass) and object_isClass(object_ptr):
return ObjCClass(object_ptr)
# Otherwise, create a new ObjCInstance.
if issubclass(cls, type):
# Special case for ObjCClass to pass on the class name, bases and namespace to the type constructor.
self = super().__new__(cls, _name, _bases, _ns)
else:
if isinstance(object_ptr, objc_block):
cls = ObjCBlockInstance
else:
cls = type_for_objcclass(libobjc.object_getClass(object_ptr))
self = super().__new__(cls)
super(ObjCInstance, type(self)).__setattr__(self, "ptr", object_ptr)
super(ObjCInstance, type(self)).__setattr__(
self, "_as_parameter_", object_ptr
)
super(ObjCInstance, type(self)).__setattr__(self, "_needs_release", False)
if isinstance(object_ptr, objc_block):
super(ObjCInstance, type(self)).__setattr__(
self, "block", ObjCBlock(object_ptr)
)
# Store new object in the dictionary of cached objects, keyed
# by the (integer) memory address pointed to by the object_ptr.
cls._cached_objects[object_ptr.value] = self
return self
def release(self):
"""Manually decrement the reference count of the corresponding objc
object.
The objc object is sent a dealloc message when its reference
count reaches 0. Calling this method manually should not be
necessary, unless the object was explicitly ``retain``\\ed
before. Objects returned from ``.alloc().init...(...)`` and
similar calls are released automatically by Rubicon when the
corresponding Python object is deallocated.
"""
self._needs_release = False
send_message(self, "release", restype=objc_id, argtypes=[])
def autorelease(self):
"""Decrements the receiver’s reference count at the end of the current
autorelease pool block.
The objc object is sent a dealloc message when its reference
count reaches 0. If called, the object will not be released when
the Python object is deallocated.
"""
self._needs_release = False
result = send_message(self, "autorelease", restype=objc_id, argtypes=[])
return ObjCInstance(result)
def __del__(self):
"""Release the corresponding objc instance if we own it, i.e., if it
was returned by by a method starting with 'alloc', 'new', 'copy', or
'mutableCopy' and it wasn't already explicitly released by calling
:meth:`release` or :meth:`autorelease`."""
if self._needs_release:
send_message(self, "release", restype=objc_id, argtypes=[])
def __str__(self):
"""Get a human-readable representation of ``self``.
By default, ``self.description`` converted to a Python string is
returned. If ``self.description`` is ``nil``,
``self.debugDescription`` converted to a Python is returned
instead. If that is also ``nil``, ``repr(self)`` is returned as
a fallback.
"""
desc = self.description
if desc is not None:
return str(desc)
desc = self.debugDescription
if desc is not None:
return str(desc)
return repr(self)
def __repr__(self):
"""Get a debugging representation of ``self``, which includes the
Objective-C object's address, class, and ``debugDescription``."""
return (
f"<{type(self).__module__}.{type(self).__qualname__} {id(self):#x}: "
f"{self.objc_class.name} at {self.ptr.value:#x}: {self.debugDescription}>"
)
def __getattr__(self, name):
"""Allows accessing Objective-C properties and methods using Python