Repository navigation
Expand file tree
/
Copy pathobjc.lisp
More file actions
1803 lines (1530 loc) · 72 KB
/
Copy pathobjc.lisp
File metadata and controls
1803 lines (1530 loc) · 72 KB
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
;;;; P1: The Objective-C to Lisp Bridge with Transparent Layer
;;; Copyright (C) 2025-2026 The Calendrical System
;;; SPDX-License-Identifier: 0BSD
;;; Objective-C to Lisp Binding with Transparent Layer
;;; Dependencies:
;;; (ql:quickload '(:alexandria :anaphora :cffi :cffi-libffi :closer-mop :float-features :log4cl :split-sequence :trivial-main-thread))
;;; Packages:
;;; OBJC: Main Package
;;; OBJC-CLASS: For Class Definitions
;;; OBJC-META: For Metaclass Definitions
;;; OBJC-INSTANCETYPE: For instancetype Definitions
;;; OBJC-METHOD: For Obj-C -> Lisp Generic Function Methods
;;; OBJC-PROP: Obj-C Properties -> Lisp Slot Names
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (find-package "OBJC")
(make-package "OBJC" :use (list (find-package "CL")
(find-package "CFFI")
(find-package "ANAPHORA"))))
(dolist (pak '("OBJC-CLASS" "OBJC-META" "OBJC-INSTANCETYPE" "OBJC-METHOD" "OBJC-PROP"))
(unless (find-package pak)
(make-package pak :use (list (find-package "OBJC"))))))
;;;; Foreign Libraries
(in-package "OBJC")
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-foreign-library cocoa
(:darwin (:framework "Cocoa")))
(define-foreign-library foundation
(:darwin (:framework "Foundation")))
(define-foreign-library appkit
(:darwin (:framework "AppKit"))))
(use-foreign-library foundation)
(use-foreign-library cocoa)
(use-foreign-library appkit)
;; Raw Bindings (objc-raw.lisp) is needed from here
;;;; P2: Name Translator
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *special-words*
'("NS" "CG" "UTF8" "UI" "URL" "HTML" "PDF" "PNG" "RTFD" "RTF" "TIFF"))
(defvar *special-translations*
'(("NS-OBJECT" . "NSObject")))
(macrolet ((def-translate-from (pkg-name)
`(defmethod cffi:translate-name-from-foreign
(name (package (eql (find-package ,pkg-name))) &optional varp)
(aif (car (rassoc name *special-translations* :test #'equal))
(multiple-value-bind (sym status)
(intern (if varp (concatenate 'simple-string "*" it "*") it)
package)
(unless (member status '(:inherited :external))
(export sym package))
sym)
;; From CFFI source code
(let ((name (reduce #'(lambda (s1 s2)
(concatenate 'simple-string s1 "-" s2))
(mapcar #'string-upcase
(cffi::collapse-prefix
(cffi::split-if #'(lambda (ch)
(or (upper-case-p ch)
(digit-char-p ch)))
(nsubstitute #\. #\: name))
*special-words*)))))
(when varp
(setq name (concatenate 'simple-string "*" name "*")))
(multiple-value-bind (sym status)
(intern name package)
(unless (member status '(:inherited :external))
(export sym package))
sym)))))
(def-translate-to (pkg-name &optional upper-initial-p)
`(defmethod cffi:translate-name-to-foreign
(name (package (eql (find-package ,pkg-name))) &optional varp)
(or (cdr (assoc (symbol-name name) *special-translations* :test #'string=))
(let ((name (translate-camelcase-name name
:special-words *special-words*
:upper-initial-p ,upper-initial-p)))
(do ((i 0 (1+ i)))
((= i (length name)))
(when (eql (char name i) #\.)
(setf (char name i) #\:)
(when (> (length name) (1+ i))
(setf (char name (1+ i))
(char-downcase (char name (1+ i)))))))
(when varp
(setq name (subseq name 1 (1- (length name)))))
(if (uiop:string-prefix-p "ns" name)
(concatenate 'string "NS" (subseq name 2))
name))))))
(def-translate-from "OBJC")
(def-translate-from "OBJC-CLASS")
(def-translate-from "OBJC-META")
(def-translate-from "OBJC-METHOD")
(def-translate-from "OBJC-PROP")
(def-translate-to "OBJC")
(def-translate-to "OBJC-CLASS" t)
(def-translate-to "OBJC-META" t)
(def-translate-to "OBJC-METHOD")
(def-translate-to "OBJC-PROP"))
(defun parse-selector-name-to-arglist (str)
(mapcar (lambda (name)
(translate-name-from-foreign name (find-package "OBJC-METHOD")))
(split-sequence:split-sequence #\: str :remove-empty-subseqs t)))
(dolist (name '("NSObject" "NSProtocol"
"NSNumber" "NSValue"
"NSString" "NSMutableString" "NSArray" "NSMutableArray"
"NSSet" "NSMutableSet" "NSDictionary" "NSMutableDictionary"
"NSApplication" "NSWorkspace" "NSPasteboard" "NSPasteboardItem"
"NSDocument" "NSDocumentController" "NSPersistentDocument"
"NSUserDefaultsController"
"NSFilePromiseProvider" "NSFilePromiseReceiver"
"NSView" "NSControl" "NSCell" "NSActionCell"
"NSGridView" "NSGridCell" "NSGridColumn" "NSGridRow"
"NSSplitView" "NSStackView" "NSTabView"
"NSScrollView" "NSScroller" "NSClipView" "NSRulerView" "NSRulerMarker"
"NSWindow"))
(translate-name-from-foreign name (find-package "OBJC-CLASS"))
(translate-name-from-foreign name (find-package "OBJC-META")))
(translate-name-from-foreign "Protocol" (find-package "OBJC-META"))
;;;; P3: Obj-C type encoding
;;; Giving a objc type encoding,
;;; know the corresponding lisp type for method specifiers,
;;; know the corresponding C type for auto-translating method call and return value
;;; https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Type-encoding.html
(defvar *objc-types-map*
'((:objc #\c :c :char :lisp character)
(:objc #\i :c :int :lisp fixnum)
(:objc #\s :c :short :lisp fixnum)
(:objc #\l :c :long :lisp fixnum)
(:objc #\q :c :long-long :lisp integer)
(:objc #\C :c :uchar :lisp character)
(:objc #\I :c :uint :lisp fixnum)
(:objc #\S :c :ushort :lisp fixnum)
(:objc #\L :c :ulong :lisp fixnum)
(:objc #\Q :c :unsigned-long-long :lisp integer)
(:objc #\f :c :float :lisp single-float)
(:objc #\d :c :double :lisp double-float)
;; Due to a bug of CFFI, #\B should be :int instead of :bool
(:objc #\B :c :int :lisp t)
(:objc #\* :c :string :lisp string)
(:objc #\@ :c objc-id :lisp t)
(:objc #\# :c objc-class :lisp objc-class)
(:objc #\: :c selector :lisp selector)
(:objc #\{ :c :struct :lisp struct)
(:objc #\v :c :void :lisp t)
))
(defun parse-objc-type-encoding-to-lisp (char-or-str)
(let ((char (if (stringp char-or-str)
(char (string-left-trim '(#\r #\n #\N #\o #\O #\R #\V) char-or-str) 0)
char-or-str)))
(find-class
(aif (find-if (lambda (lst) (eql char (getf lst :objc)))
*objc-types-map*)
(let ((lisp-type (getf it :lisp)))
(if (eq lisp-type 'struct)
;; (translate-name-from-foreign
;; (subseq char-or-str 1 (position #\= char-or-str))
;; (find-package "OBJC"))
t
lisp-type))
t))))
(defun parse-objc-type-encoding-to-c (char-or-str)
(let ((char (if (stringp char-or-str)
(char (string-left-trim '(#\r #\n #\N #\o #\O #\R #\V) char-or-str) 0)
char-or-str)))
(aif (find-if (lambda (lst) (eql char (getf lst :objc)))
*objc-types-map*)
(let ((c-type (getf it :c)))
(if (eq c-type :struct)
(let ((struct-type (translate-name-from-foreign
(subseq char-or-str 1 (position #\= char-or-str))
(find-package "OBJC"))))
(if (member struct-type '(_-ns-range cg-size cg-rect cg-point))
(list :struct struct-type)
:pointer))
c-type))
:pointer)))
(defun parse-c-type-to-objc-encoding (c-type)
(aif (find-if (lambda (lst) (eq c-type (getf lst :c)))
*objc-types-map*)
(getf it :objc)
(if (subtypep c-type 'objc-object)
#\@
#\?)))
(defun parse-lisp-type-to-c (lisp-type)
(aif (find-if (lambda (lst) (and (not (eq (getf lst :lisp) t))
(subtypep lisp-type (find-class (getf lst :lisp)))))
*objc-types-map*)
(getf it :c)
(if (subtypep lisp-type (find-class 'objc-object))
'objc-id
:pointer)))
(defun parse-lisp-type-to-objc-encoding (lisp-type)
(aif (find-if (lambda (lst) (subtypep lisp-type (find-class (getf lst :lisp))))
*objc-types-map*)
(getf it :objc)
#\?))
(export '(parse-lisp-type-to-c
parse-lisp-type-to-objc-encoding
parse-objc-type-encoding-to-c
parse-objc-type-encoding-to-lisp
parse-c-type-to-objc-encoding))
;;;; P4: The Obj-C Object
(defclass objc-object ()
((obj :initarg :objc-object
:accessor objc-obj))
(:metaclass standard-class))
(defmethod initialize-instance ((instance objc-object) &rest initargs)
(apply #'shared-initialize instance t initargs)
(when (and (not (slot-boundp instance 'obj))
(typep (class-of instance) 'objc-object))
(setf (objc-obj instance)
(objc-raw::class-create-instance (objc-obj (class-of instance)) 0))))
(export '(objc-obj objc-object obj objc-instancetype))
;;; Obj-C Selector
(defclass selector (objc-object #-ecl function)
((name :type string
:initarg :name
:accessor selector-name))
(:metaclass c2mop:funcallable-standard-class))
(defmethod print-object ((obj selector) stream)
(print-unreadable-object (obj stream :type t :identity t)
(princ (selector-name obj) stream)))
(defmethod initialize-instance ((selector selector) &key name objc-object)
(cond (objc-object
(setf (objc-obj selector) objc-object
(selector-name selector) (objc-raw::sel-get-name objc-object)))
(name
(setf (selector-name selector) name
(objc-obj selector) (objc-raw::sel-register-name name)))
(t (error "One of initarg must be provided: :NAME or :OBJC-OBJECT")))
(c2mop:set-funcallable-instance-function
selector
(lambda (object &rest args)
(apply (ensure-objc-method (object-get-class object) selector)
object
args))))
(define-foreign-type objc-selector-type () ()
(:actual-type :pointer)
(:simple-parser selector))
(defmethod translate-from-foreign (ptr (type objc-selector-type))
(make-instance 'selector :objc-object ptr))
(defmethod translate-to-foreign (obj (type objc-selector-type))
(objc-obj obj))
(defmethod expand-from-foreign (ptr (type objc-selector-type))
`(make-instance 'selector :objc-object ,ptr))
(defmethod expand-to-foreign (obj (type objc-selector-type))
`(objc-obj ,obj))
(export '(selector selector-name name objc-selector-type))
;;;; P5: Obj-C Property <=> Slot Definition
(defclass objc-property-slot (c2mop:standard-direct-slot-definition)
((property-name :initarg :property-name)
(getter-name :initarg :getter-name)
(setter-name :initarg :setter-name)
(read-only-p :initarg :read-only-p)
(return-type :initarg :return-type)
(ivar-name :initarg :ivar-name)
(copy-p :initarg :copy-p)
(retain-p :initarg :retain-p)
(non-atomic-p :initarg :non-atomic-p)
(dynamic-p :initarg :dynamic-p)
(weak-p :initarg :weak-p)
(gc-p :initarg :gc-p)
(from-objc :initform nil
:initarg :from-objc)
(lisp-only :initform nil
:initarg :lisp-only))
(:documentation
"properties ::= {(name [[attributes]])}*
attributes ::= {:return-type ret-type} | ; T
{:getter-name name} | ; G
{:setter-name name} | ; S
{:ivar-name name} | ; V
{:read-only-p boolean} | ; R
{:copy-p boolean} | ; C
{:retain-p boolean} | ; &
{:non-atomic-p boolean} | ; N
{:dynamic-p boolean} | ; D
{:weak-p boolean} | ; W
{:gc-p boolean} | ; P
{:from-objc boolean}
"))
(defclass objc-property (c2mop:standard-effective-slot-definition)
((property-name :initarg :property-name)
(getter-name :initarg :getter-name)
(setter-name :initarg :setter-name)
(read-only-p :initarg :read-only-p)
(return-type :initarg :return-type)
(ivar-name :initarg :ivar-name)
(copy-p :initarg :copy-p)
(retain-p :initarg :retain-p)
(non-atomic-p :initarg :non-atomic-p)
(dynamic-p :initarg :dynamic-p)
(weak-p :initarg :weak-p)
(gc-p :initarg :gc-p)))
(defmethod print-object ((obj objc-property) stream)
(print-unreadable-object (obj stream :type t)
(with-slots (property-name return-type read-only-p) obj
(when read-only-p
(princ "(readonly) " stream))
(format stream "~A ~A"
(class-name (parse-objc-type-encoding-to-lisp return-type))
property-name))))
;;; Foreign structure to be used
(defcstruct objc-property-attribute
(:name :string)
(:value :string))
(export '(objc-property-slot objc-property objc-property-attribute))
;;;; P6: The Obj-C Class
;;; Foreign Type
(define-foreign-type objc-class-type () ()
(:actual-type :pointer)
(:simple-parser objc-class))
(defmethod translate-from-foreign (ptr (type objc-class-type))
(if (null-pointer-p ptr)
nil
(ensure-objc-class ptr)))
(defmethod translate-to-foreign (obj (type objc-class-type))
(objc-obj obj))
(defmethod expand-from-foreign (ptr (type objc-class-type))
(alexandria:with-unique-names (ptr-var)
`(let ((,ptr-var ,ptr))
(if (null-pointer-p ,ptr-var)
nil
(ensure-objc-class ,ptr-var)))))
(defmethod expand-to-foreign (obj (type objc-class-type))
`(objc-obj ,obj))
;;; Lisp Class Metaobjects & Methods
(defclass objc-class (standard-class objc-object)
((objc-class-name :initarg :objc-class-name
:accessor objc-class-name)
(auto-bind-properties :initform t
:initarg :auto-bind-properties)
(auto-register-methods :initform t
:initarg :auto-register-methods)))
(defclass objc-metaclass (objc-class) ())
(defmethod c2mop:validate-superclass ((c1 objc-class) (c2 standard-class)) t)
;;; Obj-C instancetype
(defclass objc-instancetype (standard-class objc-object) ())
(defmethod c2mop:validate-superclass ((c1 objc-instancetype) (c2 standard-class)) t)
(export '(objc-class objc-metaclass objc-instancetype objc-class-type))
;;;; P7: Obj-C property => Lisp slot converter
(defmethod c2mop:direct-slot-definition-class ((class objc-class) &rest initargs)
(declare (ignore initargs))
(find-class 'objc-property-slot))
(defmethod c2mop:effective-slot-definition-class ((class objc-class) &rest initargs)
(declare (ignore initargs))
(find-class 'objc-property))
;; --- Helper ---
(defun objc-property-default-setter-name (property-name)
(let ((name (copy-seq property-name)))
(setf (char name 0)
(char-upcase (char name 0)))
(concatenate 'string "set" name)))
(export 'objc-property-default-setter-name)
;; --- END helper ---
(defmethod c2mop:compute-effective-slot-definition :around ((class objc-class) name slots)
(let ((slot (car slots))
(class-ptr (slot-value class 'obj)))
(unless (typep slot 'objc-property-slot)
(return-from c2mop:compute-effective-slot-definition (call-next-method)))
(with-slots (property-name getter-name setter-name read-only-p return-type
ivar-name copy-p retain-p non-atomic-p dynamic-p weak-p gc-p
from-objc lisp-only)
slot
(when lisp-only
(return-from c2mop:compute-effective-slot-definition (call-next-method)))
(if from-objc
(let* ((prop-name (or property-name
(translate-to-foreign property-name "OBJC-PROP")))
(prop (objc-raw::class-get-property class-ptr prop-name)))
(assert (not (null-pointer-p prop)))
(make-instance
'objc-property
:name name
:initform (c2mop:slot-definition-initform slot)
:initfunction (c2mop:slot-definition-initfunction slot)
:type (c2mop:slot-definition-type slot)
:allocation (c2mop:slot-definition-allocation slot)
:initargs (c2mop:slot-definition-initargs slot)
:documentation (documentation slot t)
:property-name prop-name
:getter-name (or (objc-raw::property-copy-attribute-value prop "G")
prop-name)
:setter-name (or (objc-raw::property-copy-attribute-value prop "S")
(objc-property-default-setter-name prop-name))
:read-only-p (objc-raw::property-copy-attribute-value prop "R")
:return-type (parse-objc-type-encoding-to-c
(objc-raw::property-copy-attribute-value prop "T"))
:ivar-name (objc-raw::property-copy-attribute-value prop "V")
:copy-p (objc-raw::property-copy-attribute-value prop "C")
:retain-p (objc-raw::property-copy-attribute-value prop "&")
:non-atomic-p (objc-raw::property-copy-attribute-value prop "N")
:dynamic-p (objc-raw::property-copy-attribute-value prop "D")
:weak-p (objc-raw::property-copy-attribute-value prop "W")
:gc-p (objc-raw::property-copy-attribute-value prop "P")))
(let (prop-plist)
(unless property-name
(setf property-name (translate-name-to-foreign name (find-package "OBJC-PROP"))))
(push (list :name "T" :value return-type) prop-plist)
(when getter-name (push (list :name "G" :value getter-name) prop-plist))
(when setter-name (push (list :name "S" :value getter-name) prop-plist))
(when ivar-name (push (list :name "V" :value ivar-name) prop-plist))
(when read-only-p (push (list :name "R" :value nil) prop-plist))
(when copy-p (push (list :name "C" :value nil) prop-plist))
(when retain-p (push (list :name "&" :value nil) prop-plist))
(when non-atomic-p (push (list :name "N" :value nil) prop-plist))
(when dynamic-p (push (list :name "D" :value nil) prop-plist))
(when weak-p (push (list :name "W" :value nil) prop-plist))
(when gc-p (push (list :name "P" :value nil) prop-plist))
(let ((len (length prop-plist)))
(with-foreign-object (attr '(:struct objc-property-attribute) len)
(dotimes (i len)
(setf (mem-aref attr '(:struct objc-property-attribute) i)
(nth i prop-plist)))
(objc-raw::class-add-property class-ptr property-name attr len)))
(make-instance
'objc-property
:name name
:initform (c2mop:slot-definition-initform slot)
:initfunction (c2mop:slot-definition-initfunction slot)
:type (c2mop:slot-definition-type slot)
:allocation (c2mop:slot-definition-allocation slot)
:initargs (c2mop:slot-definition-initargs slot)
:documentation (documentation slot t)
:property-name property-name
:getter-name (or getter-name property-name)
:setter-name (or setter-name (objc-property-default-setter-name property-name))
:read-only-p read-only-p
:return-type return-type
:ivar-name ivar-name
:copy-p copy-p
:retain-p retain-p
:non-atomic-p non-atomic-p
:dynamic-p dynamic-p
:weak-p weak-p
:gc-p gc-p))))))
(defmethod c2mop:slot-boundp-using-class
:around ((class objc-class) (object objc-object) (slot objc-property))
(declare (ignore class))
(if (slot-boundp slot 'getter-name) t
(call-next-method)))
(defmethod c2mop:slot-value-using-class
:around ((class objc-class) (object objc-object) (slot objc-property))
(declare (ignore class))
(if (slot-boundp slot 'getter-name)
(with-slots (property-name getter-name return-type) slot
(let ((sel (objc-raw::sel-get-uid getter-name)))
(if (objc-raw::class-responds-to-selector (objc-obj class) sel)
(eval (list 'foreign-funcall
"objc_msgSend"
:pointer (slot-value object 'obj)
:pointer sel
return-type))
(error "Cannot resolve Obj-C property getter for ~A: ~A does not respond to ~A"
property-name
object
getter-name))))
(call-next-method)))
(defmethod (setf c2mop:slot-value-using-class)
:around (new-value (class objc-class) (object objc-object) (slot objc-property))
(if (slot-boundp slot 'setter-name)
(with-slots (property-name setter-name read-only-p return-type) slot
(if read-only-p
(error "Obj-C property ~A for ~A is read-only"
property-name
object)
(let ((sel (objc-raw::sel-get-uid setter-name)))
(if (objc-raw::class-responds-to-selector (objc-obj class) sel)
(eval (list 'foreign-funcall
"objc_msgSend"
:pointer (slot-value object 'obj)
:pointer sel
return-type new-value))
(error "Cannot resolve Obj-C property setter for ~A: ~A does not respond to ~A"
property-name
object
setter-name))))
new-value)
(call-next-method)))
;;;; P8: Obj-C class => Lisp class converter
(defvar *not-registered-classes* nil
"A list of objc-class objects that are allocated but yet not registered in Obj-C runtime.")
;; --- Helper ---
(defun class-ptr-symbol (ptr)
(declare (inline class-ptr-symbol))
(let ((name (objc-raw::class-get-name ptr)))
(if (objc-raw::class-is-meta-class ptr)
(translate-name-from-foreign name (find-package "OBJC-META"))
(translate-name-from-foreign name (find-package "OBJC-CLASS")))))
(export 'class-ptr-symbol)
;; --- Helper ---
(defun instancetype-ptr-symbol (ptr)
(declare (inline instancetype-ptr-symbol))
(intern (format nil "~16R" (pointer-address ptr)) "OBJC-INSTANCETYPE"))
(export 'instancetype-ptr-symbol)
;; --- Helper ---
(defun compute-slot-specs-for-properties (class-ptr)
(with-foreign-object (out-count :uint)
(let* ((props-ptr (objc-raw::class-copy-property-list class-ptr out-count))
(len (mem-aref out-count :uint 0)))
(unwind-protect
(loop for i below len
for prop = (mem-aref props-ptr :pointer i)
for prop-name = (objc-raw::property-get-name prop)
for slot-name = (translate-name-from-foreign prop-name
(find-package "OBJC-PROP"))
collect (list :name slot-name
:property-name prop-name
:from-objc t))
(foreign-free props-ptr)))))
;; --- END Helper ---
(defmethod c2mop:ensure-class-using-class :around ((class objc-object) name &rest args &key metaclass)
(if (subtypep metaclass 'objc-class)
(apply #'c2mop:ensure-class-using-class nil name args)
(return-from c2mop:ensure-class-using-class (call-next-method))))
(defmethod c2mop:ensure-class-using-class
:around ((class null) name &rest args
&key direct-superclasses direct-slots metaclass
objc-class-name objc-object
(auto-bind-properties t) (auto-register-methods t)
;; Recursive process args, which should be removed before call-next-method
instance-class)
;; Pass if it is not intended as an Obj-C class
(unless (subtypep metaclass 'objc-class)
(return-from c2mop:ensure-class-using-class (call-next-method)))
;; instancetype
(when (and objc-object
(not (objc-raw::class-is-meta-class (objc-raw::object-get-class objc-object))))
(return-from c2mop:ensure-class-using-class
(c2mop:ensure-class (instancetype-ptr-symbol objc-object)
:objc-object objc-object
:metaclass 'objc-instancetype)))
;; class
(let (class-ptr)
;; If called with existing class
(when (and objc-object (not (null-pointer-p objc-object)))
(setq class-ptr objc-object))
;; Resolve names
(if class-ptr
(unless objc-class-name
(setq objc-class-name
(objc-raw::class-get-name class-ptr)))
(unless objc-class-name
(setq objc-class-name (translate-name-to-foreign name (find-package "OBJC-CLASS")))))
;; Try to find the class that possibly existed in Obj-C runtime
(when (or (null class-ptr) (null-pointer-p class-ptr))
(aif (find-if (lambda (cls)
(string= (objc-raw::class-get-name (objc-obj cls)) objc-class-name))
*not-registered-classes*)
(if (subtypep metaclass 'objc-metaclass)
(error "Obj-C doesn't allow subclassing metaclass directly.~%Subclassing a normal class and get its paired metaclass instead.")
(progn (log:warn "Redefining Obj-C class ~A before registration, dispose previously allocated class pair."
objc-class-name)
(objc-raw::objc-dispose-class-pair (objc-obj it))
(alexandria:deletef *not-registered-classes* it)))
(if (subtypep metaclass 'objc-metaclass)
(let ((ptr (objc-raw::objc-get-meta-class objc-class-name)))
(unless (null-pointer-p ptr)
(setq class-ptr ptr)))
(let ((ptr (objc-raw::objc-lookup-class objc-class-name)))
(unless (null-pointer-p ptr)
(if (objc-raw::class-is-meta-class ptr)
(error "Found a metaclass when calling objc_lookUpClass(~A).~%There may be a class that is allocated but yet not registered, and is not controlled by the lisp side.~%This is an unspecified behavior and you cannot relying on this anymore."
objc-class-name)
(setq class-ptr ptr)))))))
;; Let's rock & roll
(if class-ptr
;; Bind existing class to Lisp
(progn
(if (objc-raw::class-is-meta-class class-ptr)
;; Obj-C Metaclass
(progn
;; Put MetaClass into our package arbitrarily
(let ((new-name (intern (symbol-name name) "OBJC-META")))
(setq name new-name))
(log:debug "Loading Obj-C Meta Class ~A into ~S" objc-class-name name)
(setq direct-superclasses
(let ((instance-super (objc-raw::class-get-superclass
(or instance-class
(objc-raw::objc-lookup-class objc-class-name)))))
(when instance-class
(remf args :instance-class))
(if (null-pointer-p instance-super)
(list (find-class 'objc-class))
(let ((instance-super-meta (objc-raw::objc-get-meta-class
(objc-raw::class-get-name instance-super))))
(list (c2mop:ensure-class (class-ptr-symbol instance-super-meta)
:objc-object instance-super-meta
:metaclass 'objc-metaclass)))))
metaclass (find-class 'objc-metaclass)))
;; Normal class
(progn
(log:debug "Loading Obj-C Normal Class ~A into ~S" objc-class-name name)
(setq direct-superclasses
(let ((super-ptr (objc-raw::class-get-superclass class-ptr)))
(if (null-pointer-p super-ptr)
(list (find-class 'objc-object))
(list (let ((super-name (class-ptr-symbol super-ptr)))
(or (find-class super-name nil)
(c2mop:ensure-class super-name
:objc-object super-ptr
:metaclass 'objc-class))))))
metaclass
(let* ((meta-ptr (objc-raw::objc-get-meta-class objc-class-name))
(meta-name (class-ptr-symbol meta-ptr)))
(or (find-class meta-name nil)
(c2mop:ensure-class (class-ptr-symbol meta-ptr)
:objc-object meta-ptr
:metaclass 'objc-metaclass))))))
;; Bind Obj-C property to Lisp slot
(when auto-bind-properties
(setq direct-slots
(nconc direct-slots (compute-slot-specs-for-properties class-ptr))))
;; Done
(let ((class (apply #'call-next-method class name
:direct-superclasses direct-superclasses
:direct-slots direct-slots
:metaclass metaclass
:objc-class-name objc-class-name
:objc-object class-ptr
args)))
;;; For automatic Obj-C method => Lisp method binding
(when auto-register-methods
(with-foreign-object (out-count :uint)
(setf (mem-aref out-count :uint 0) 0)
(let* ((ptr (objc-raw::class-copy-method-list class-ptr out-count))
(len (mem-aref out-count :uint 0)))
(unwind-protect
(loop for i below len
for method-ptr = (mem-aref ptr :pointer i)
do (ensure-objc-method class method-ptr))
(foreign-free ptr)))))
class))
;; Defining new Obj-C class from Lisp
(let* ((super-ptr (aif (find-if (lambda (class) (typep class 'objc-class))
direct-superclasses)
(objc-obj it)
(null-pointer)))
(class-ptr (progn
(log:debug "Subclassing Obj-C class ~A based on ~A into ~S"
objc-class-name
(objc-raw::class-get-name super-ptr)
name)
(objc-raw::objc-allocate-class-pair super-ptr objc-class-name 0)))
(meta-ptr (objc-raw::object-get-class class-ptr))
(metaclass (c2mop:ensure-class (class-ptr-symbol meta-ptr)
:objc-object meta-ptr
:instance-class class-ptr
:metaclass 'objc-class)))
(when auto-bind-properties
(setq direct-slots
(nconc direct-slots (compute-slot-specs-for-properties class-ptr))))
(let ((cls (apply #'call-next-method class name
:direct-superclasses direct-superclasses
:direct-slots direct-slots
:metaclass metaclass
:objc-class-name objc-class-name
:objc-object class-ptr
args)))
(push cls *not-registered-classes*)
cls)))))
(defmethod c2mop:finalize-inheritance :after ((class objc-class))
(objc-raw::objc-register-class-pair (objc-obj class))
(alexandria:deletef *not-registered-classes* class))
;;;; P9: Helper Functions
(defun ensure-objc-class (object)
;; Basically just a typecase
(cond ((pointerp object)
(if (objc-raw::class-is-meta-class (objc-raw::object-get-class object))
;; class
(let ((name (class-ptr-symbol object)))
(or (find-class name nil)
(c2mop:ensure-class (class-ptr-symbol object)
:objc-object object
:metaclass 'objc-class)))
;; instancetype
(c2mop:ensure-class (instancetype-ptr-symbol object)
:objc-object object
:metaclass 'objc-instancetype)))
((typep object 'objc-class)
object)
((symbolp object)
(or (find-class object nil)
(foreign-funcall
"objc_lookUpClass"
:string (translate-name-to-foreign object (find-package "OBJC-CLASS"))
objc-class)))
((stringp object)
(or (find-class
(translate-name-from-foreign object (find-package "OBJC-CLASS"))
nil)
(foreign-funcall "objc_lookUpClass" :string object objc-class)))
(t (error "Invalid argument: ~A" object))))
(defun ensure-objc-meta-class (object)
(cond ((pointerp object)
(ensure-objc-class object))
((typep object 'objc-metaclass)
object)
((typep object 'objc-class)
(ensure-objc-class (objc-raw::object-get-class (objc-obj object))))
((symbolp object)
(or (find-class object nil)
(objc-get-meta-class
(translate-name-to-foreign object (find-package "OBJC-META")))))
((stringp object)
(or (find-class
(translate-name-from-foreign object (find-package "OBJC-META"))
nil)
(objc-get-meta-class object)))
(t (error "Invalid argument: ~A" object))))
(export '(ensure-objc-class ensure-objc-meta-class))
;;;; P10: Obj-C Object (the objc `id') foreign translator
(define-foreign-type objc-object-type () ()
(:actual-type :pointer)
(:simple-parser objc-id))
(defgeneric translate-from-objc-id (class pointer)
(:method ((class objc-object) pointer)
(make-instance class :objc-object pointer))
(:method ((class objc-instancetype) pointer)
(let* ((instance (objc-raw::object-get-class pointer))
(class (foreign-funcall "object_getClass" :pointer instance objc-class)))
(make-instance class :objc-object instance))))
(defgeneric translate-to-objc-id (object)
(:method ((object objc-object))
(when object (objc-obj object) (null-pointer))))
(defmethod translate-from-foreign (ptr (type objc-object-type))
(unless (null-pointer-p ptr)
(let ((class (foreign-funcall "object_getClass" :pointer ptr objc-class)))
(translate-from-objc-id class ptr))))
(defmethod translate-to-foreign (obj (type objc-object-type))
(translate-to-objc-id obj))
(defmethod expand-from-foreign (ptr (type objc-object-type))
(alexandria:with-unique-names (ptr-var)
`(let ((,ptr-var ,ptr))
(unless (null-pointer-p ,ptr-var)
(let ((class (foreign-funcall "object_getClass" :pointer ,ptr-var objc-class)))
(translate-from-objc-id class ,ptr-var))))))
(defmethod expand-to-foreign (obj (type objc-object-type))
`(translate-to-objc-id ,obj))
(export '(translate-from-objc-id translate-to-objc-id objc-object-type))
;;;; P11: Wrapper for some class-info query functions
(macrolet ((copy-list-ptrs (func var)
`(with-foreign-object (out-count :uint)
(setf (mem-aref out-count :uint 0) 0)
(let* ((ptr (,func (ensure-objc-class ,var) out-count))
(len (mem-aref out-count :uint 0))
(arr (make-array len :fill-pointer 0)))
(unwind-protect
(progn
(dotimes (i len)
(vector-push (mem-aref ptr :pointer i) arr))
arr)
(foreign-free ptr))))))
(defun class-ivar-list-pointers (class)
(copy-list-ptrs class-copy-ivar-list class))
(defun class-property-list-pointers (class)
(copy-list-ptrs class-copy-property-list class))
(defun class-method-list-pointers (class)
(copy-list-ptrs class-copy-method-list class)))
(export '(class-ivar-list-pointers class-property-list-pointers class-method-list-pointers))
;;;; P12: The Obj-C Method
;;; Foreign Type
(define-foreign-type objc-method-type () ()
(:actual-type :pointer)
(:simple-parser objc-method))
(defmethod translate-from-foreign (ptr (type objc-method-type))
(translate-to-objc-method ptr))
(defmethod translate-to-foreign (obj (type objc-method-type))
(objc-obj obj))
(defmethod expand-from-foreign (ptr (type objc-method-type))
`(translate-to-objc-method ,ptr))
(defmethod expand-to-foreign (obj (type objc-method-type))
`(objc-obj ,obj))
;;; defclass
(defclass objc-method (standard-method objc-object)
((selector :initarg :selector)
(return-type :initarg :return-type)))
;;; Convert to method
(defun translate-to-objc-method (ptr)
(unless (null-pointer-p ptr)
(let* ((sel (make-instance 'selector :objc-object (objc-raw::method-get-name ptr)))
(arg-nums (objc-raw::method-get-number-of-arguments ptr))
(lambda-list (mapcar (lambda (sym)
(gentemp (concatenate 'string (symbol-name sym) "-") "OBJC-METHOD"))
(last (parse-selector-name-to-arglist (selector-name sel)) (- arg-nums 2))))
(type-encodings (loop for i from 2 below arg-nums
collect (objc-raw::method-copy-argument-type ptr i)))
(specializers (loop for type in type-encodings
collect (parse-objc-type-encoding-to-lisp type)))
(foreign-types (loop for type in type-encodings
collect (parse-objc-type-encoding-to-c type)))
(ret-type (parse-objc-type-encoding-to-c (objc-raw::method-copy-return-type ptr)))
(gf-proto (c2mop:class-prototype (find-class 'standard-generic-function)))
(method-proto (c2mop:class-prototype (find-class 'objc-method)))
(lambda-exp `(lambda (objc-object ,@lambda-list)
(foreign-funcall "method_invoke"
:pointer (objc-obj objc-object)
:pointer ,ptr
,@(mapcan #'list foreign-types lambda-list)
,ret-type))))
(multiple-value-bind (form initargs)
(c2mop:make-method-lambda gf-proto method-proto lambda-exp nil)
(values (apply #'make-instance
'objc-method
:function (compile nil form)
:lambda-list (cons 'objc-object lambda-list)
:specializers (cons (find-class 'objc-object) specializers)
:qualifiers nil
:selector sel
:return-type ret-type
:objc-object ptr
initargs)
lambda-exp)))))
;;; Convert to Generic Function
(defun ensure-objc-method (class object)
"Name can be a string, symbol, selector or cffi pointer of the method"
(setq class (ensure-objc-class class))
(let (name sel)
(typecase object
(selector (setq sel object
name (translate-name-from-foreign
(selector-name sel) (find-package "OBJC-METHOD"))))
(string (setq sel (make-instance 'selector :name object)
name (translate-name-from-foreign object (find-package "OBJC-METHOD"))))
(symbol (setq sel (make-instance
'selector
:name (translate-to-foreign object (find-package "OBJC-METHOD")))
name object))
(t (if (pointerp object)
(setq sel (make-instance 'selector :objc-object (objc-raw::method-get-name object))
name (translate-name-from-foreign
(selector-name sel) (find-package "OBJC-METHOD")))
(error "Wrong type of argument: ~A" object))))
(if (fboundp name) name
(let ((method-ptr (foreign-funcall "class_getInstanceMethod"
objc-class class
selector sel
:pointer)))
(assert (not (null-pointer-p method-ptr)))
(log:debug "Registering Obj-C method function" name)
(let ((gf (ensure-generic-function name)))
(add-method gf (translate-to-objc-method method-ptr))
gf)))))
;;; Defining new method
;;; FIXME: Redefining old method will not flush some method cache at the Lisp side
(defmacro define-objc-method (name-and-options return-type args &body body)
(multiple-value-bind (body decls)
(alexandria:parse-body body)
(let (lisp-name
selector-name
arg-and-types)
(if (listp name-and-options)
(setq lisp-name (first name-and-options)
selector-name (second name-and-options))
(setq lisp-name name-and-options
selector-name (translate-name-to-foreign lisp-name (find-package "OBJC"))))
(setq arg-and-types (append (list (first args)) '((_cmd selector)) (rest args)))
(let* ((objc-arg-types (let ((types (make-array (1+ (length arg-and-types)) :element-type 'character :fill-pointer 0)))
(vector-push (parse-c-type-to-objc-encoding return-type) types)
(dolist (arg arg-and-types)
(vector-push (parse-c-type-to-objc-encoding (second arg)) types))
types))
(c-arg-types (loop for arg in arg-and-types
collect (list (first arg) (parse-lisp-type-to-c (second arg)))))
(class-name (ensure-objc-class (second (first args))))
(class-obj (objc-obj class-name)))
`(let ((sel (make-instance 'selector :name ,selector-name)))
(defcallback ,lisp-name ,return-type ,c-arg-types
,(if decls (append decls '((ignorable _cmd)))
'(declare (ignorable _cmd)))
,@body)
(objc-raw::class-replace-method ,class-obj (objc-obj sel) (callback ,lisp-name) ,objc-arg-types)
(ensure-objc-method ,class-name (objc-raw::class-get-instance-method ,class-obj (objc-obj sel))))))))
(export '(objc-method-type objc-method translate-to-objc-method define-objc-method ensure-objc-method))
;;; ---
(c2mop:finalize-inheritance (find-class 'objc-method))
)
;;; --- From now on the basic runtime is ready, and the code below is not forcibly evaluated in compile time ---
;;;; P13: The Obj-C Runtime
;;; Other Obj-C Runtime Types
(defctype objc-ivar :pointer)
(defctype objc-property :pointer)
(defctype objc-imp :pointer) ;; void (*)(void) IMP (self, selector, ...)