chiark / gitweb /
Proxies may now have "weak" references to the foreign object
[clg] / glib / gtype.lisp
1 ;; Common Lisp bindings for GTK+ v2.x
2 ;; Copyright 2000-2005 Espen S. Johnsen <espen@users.sf.net>
3 ;;
4 ;; Permission is hereby granted, free of charge, to any person obtaining
5 ;; a copy of this software and associated documentation files (the
6 ;; "Software"), to deal in the Software without restriction, including
7 ;; without limitation the rights to use, copy, modify, merge, publish,
8 ;; distribute, sublicense, and/or sell copies of the Software, and to
9 ;; permit persons to whom the Software is furnished to do so, subject to
10 ;; the following conditions:
11 ;;
12 ;; The above copyright notice and this permission notice shall be
13 ;; included in all copies or substantial portions of the Software.
14 ;;
15 ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 ;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 ;; CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 ;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 ;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
23 ;; $Id: gtype.lisp,v 1.40 2006-02-06 11:52:24 espen Exp $
24
25 (in-package "GLIB")
26
27 (use-prefix "g")
28
29 ;; Initialize the glib type system
30 (defbinding type-init () nil)
31 (type-init)
32
33 (deftype type-number () '(unsigned 32))
34
35 (deftype gtype () 'symbol)
36
37 (defmethod alien-type ((type (eql 'gtype)) &rest args)
38   (declare (ignore type args))
39   (alien-type 'type-number))
40
41 (defmethod size-of ((type (eql 'gtype)) &rest args)
42   (declare (ignore type args))
43   (size-of 'type-number))
44
45 (defmethod to-alien-form (gtype (type (eql 'gtype)) &rest args)
46   (declare (ignore type args))
47   `(find-type-number ,gtype t)) 
48
49 (defmethod to-alien-function ((type (eql 'gtype)) &rest args)
50   (declare (ignore type args))
51   #'(lambda (gtype)
52       (find-type-number gtype t)))
53
54 (defmethod from-alien-form (type-number (type (eql 'gtype)) &rest args)
55   (declare (ignore type args))
56   `(type-from-number ,type-number)) 
57
58 (defmethod from-alien-function ((type (eql 'gtype)) &rest args)
59   (declare (ignore type args))
60   #'(lambda (type-number)
61       (type-from-number type-number)))
62
63 (defmethod writer-function ((type (eql 'gtype)) &rest args)
64   (declare (ignore type args))
65   (let ((writer (writer-function 'type-number)))
66     #'(lambda (gtype location &optional (offset 0))
67         (funcall writer (find-type-number gtype t) location offset))))
68
69 (defmethod reader-function ((type (eql 'gtype)) &rest args)
70   (declare (ignore type args))
71   (let ((reader (reader-function 'type-number)))
72     #'(lambda (location &optional (offset 0))
73         (type-from-number (funcall reader location offset)))))
74
75
76 (eval-when (:compile-toplevel :load-toplevel :execute)
77   (defclass type-query (struct)
78     ((type-number :allocation :alien :type type-number)
79      (name :allocation :alien :type string)
80      (class-size :allocation :alien :type unsigned-int)
81      (instance-size :allocation :alien :type unsigned-int))
82     (:metaclass struct-class)))
83
84
85 (defbinding type-query (type) nil
86   ((find-type-number type t) type-number)
87   ((make-instance 'type-query) type-query :return))
88
89 (defun type-instance-size (type)
90   (slot-value (type-query type) 'instance-size))
91
92 (defun type-class-size (type)
93   (slot-value (type-query type) 'class-size))
94
95 (defbinding type-class-ref (type) pointer
96   ((find-type-number type t) type-number))
97
98 (defbinding type-class-unref (type) nil
99   ((find-type-number type t) type-number))
100
101 (defbinding type-class-peek (type) pointer
102   ((find-type-number type t) type-number))
103
104
105 ;;;; Mapping between lisp types and glib types
106
107 (defvar *registered-types* ())
108 (defvar *registered-type-aliases* ())
109 (defvar *lisp-type-to-type-number* (make-hash-table))
110 (defvar *type-number-to-lisp-type* (make-hash-table))
111
112 (defbinding %type-from-name () type-number
113   (name string))
114
115 (defun type-number-from-glib-name (name &optional (error-p t))
116   (let ((type-number (%type-from-name name)))
117     (cond
118      ((not (zerop type-number)) type-number)
119      (error-p (error "Invalid gtype name: ~A" name)))))
120
121 (defun register-type (type id)
122   (pushnew (cons type id) *registered-types* :key #'car)
123   (let ((type-number 
124          (typecase id
125            (string (type-number-from-glib-name id))
126            (symbol (funcall id)))))
127        (setf (gethash type *lisp-type-to-type-number*) type-number)
128        (setf (gethash type-number *type-number-to-lisp-type*) type)
129        type-number))
130
131 (defun register-type-alias (type alias)
132   (pushnew (cons type alias) *registered-type-aliases* :key #'car)
133   (setf 
134    (gethash type *lisp-type-to-type-number*)
135    (find-type-number alias t)))
136
137 (defun reinitialize-all-types ()
138   (clrhash *lisp-type-to-type-number*)
139   (clrhash *type-number-to-lisp-type*)
140   (type-init) ; initialize the glib type system
141   (mapc #'(lambda (type) 
142             (register-type (car type) (cdr type)))
143         *registered-types*)
144   (mapc #'(lambda (type) 
145             (register-type-alias (car type) (cdr type)))
146         *registered-type-aliases*))
147
148 (pushnew 'reinitialize-all-types 
149   #+cmu *after-save-initializations*
150   #+sbcl *init-hooks*)
151
152 #+cmu
153 (pushnew 'system::reinitialize-global-table ; we shouldn't have to do this?
154  *after-save-initializations*)
155
156
157 (defun find-type-number (type &optional error-p)
158   (etypecase type
159     (integer type)
160     (string (type-number-from-glib-name type error-p))
161     (symbol
162      (or
163       (gethash type *lisp-type-to-type-number*)
164       (and error-p (error "Type not registered: ~A" type))))
165     (class (find-type-number (class-name type) error-p))))
166  
167 (defun type-from-number (type-number &optional error)
168   (multiple-value-bind (type found)
169       (gethash type-number *type-number-to-lisp-type*)
170     (if found
171         type
172       (let ((name (find-foreign-type-name type-number)))
173         (cond
174          ((and name (not (= (type-number-from-glib-name name nil) type-number)))
175           ;; This is a hack because GdkEvent seems to be registered
176           ;; multiple times
177           (type-from-number (type-number-from-glib-name name)))
178          ((and error name)
179           (error "Type number not registered: ~A (~A)" type-number name))
180          ((and error)
181           (error "Invalid type number: ~A" type-number)))))))
182
183 (defbinding (find-foreign-type-name "g_type_name") (type) (copy-of string)
184   ((find-type-number type t) type-number))
185
186 (defun type-number-of (object)
187   (find-type-number (type-of object) t))
188
189 (eval-when (:compile-toplevel :load-toplevel :execute)
190   (defvar *type-initializers* ())
191   (defun %find-types-in-library (pathname prefixes ignore)
192     (let ((process (run-program
193                     "/usr/bin/nm" (list "--defined-only" "-D" (namestring (truename pathname)))
194                     :output :stream :wait nil)))
195       (unwind-protect
196           (loop 
197            as symbol = (let ((line (read-line (process-output process) nil)))
198                          (when line (subseq line 11)))                    
199            while symbol
200            when (and
201                  (> (length symbol) 9)
202                  (or 
203                   (not prefixes)
204                   (some #'(lambda (prefix)
205                             (and
206                              (> (length symbol) (length prefix))
207                              (string= prefix symbol :end2 (length prefix))))
208                         (mklist prefixes)))
209                  (string= "_get_type" symbol :start2 (- (length symbol) 9))
210                  (not (member symbol ignore :test #'string=)))
211            collect symbol)
212         (process-close process)))))
213
214
215 (defmacro init-types-in-library (filename &key prefix ignore)
216   (let ((names (%find-types-in-library filename prefix ignore)))
217     `(progn
218        ,@(mapcar #'(lambda (name)
219                      `(progn
220                         (defbinding (,(intern name) ,name) () type-number)
221                         (,(intern name))
222                         (pushnew ',(intern name) *type-initializers*)))
223                  names))))
224
225 (defun find-type-init-function (type-number)
226   (loop
227    for type-init in *type-initializers*
228    when (= type-number (funcall type-init))
229    do (return type-init)))
230
231 (defun register-type-as (type-number)
232   (or 
233    (find-type-init-function type-number)
234    (find-foreign-type-name type-number)
235    (error "Unknown type-number: ~A" type-number)))
236
237 (defun default-type-init-name (type)
238   (find-symbol (format nil "~A_~A_get_type" 
239                 (package-prefix *package*)
240                 (substitute #\_ #\- (string-downcase type)))))
241
242
243 (eval-when (:compile-toplevel :load-toplevel :execute)
244   (defclass type-info (struct)
245     ((class-size :allocation :alien :type (unsigned 16) :initarg :class-size)
246      (base-init :allocation :alien :type pointer)
247      (base-finalize :allocation :alien :type pointer)
248      (class-init :allocation :alien :type pointer)
249      (class-finalize :allocation :alien :type pointer)
250      (class-data :allocation :alien :type pointer)
251      (instance-size :allocation :alien :type (unsigned 16) 
252                     :initarg :instance-size)
253      (n-preallocs :allocation :alien :type (unsigned 16))
254      (instance-init :allocation :alien :type pointer)
255      (value-table :allocation :alien :type pointer))
256     (:metaclass struct-class)))
257
258 (defbinding %type-register-static () type-number
259   (parent-type type-number)
260   (name string)
261   (info type-info)
262   (0 unsigned-int))
263
264 (defun register-new-type (type parent &optional foreign-name)
265   (let ((parent-info (type-query parent)))
266     (with-slots ((parent-number type-number) class-size instance-size) parent-info
267       (let ((type-number 
268              (%type-register-static 
269               parent-number
270               (or foreign-name (default-alien-type-name type))
271               (make-instance 'type-info :class-size class-size :instance-size instance-size))))
272        (setf (gethash type *lisp-type-to-type-number*) type-number)
273        (setf (gethash type-number *type-number-to-lisp-type*) type)
274        type-number))))
275
276
277
278 ;;;; Metaclass for subclasses of ginstance
279
280 (eval-when (:compile-toplevel :load-toplevel :execute)
281   (defclass ginstance-class (proxy-class)
282     ((gtype :initarg :gtype :initform nil :reader ginstance-class-gtype))))
283
284
285 (defmethod compute-foreign-size ((class ginstance-class))
286   (type-instance-size (find-type-number (class-name class))))
287
288 (defmethod finalize-inheritance ((class ginstance-class))
289   (call-next-method)
290   (let* ((class-name (class-name class))
291          (super (most-specific-proxy-superclass class))
292          (gtype (or 
293                  (first (ginstance-class-gtype class))
294                  (default-alien-type-name class-name)))
295          (type-number
296           (or 
297            (find-type-number class-name)
298            (if (or (symbolp gtype) (type-number-from-glib-name gtype nil))
299                (register-type class-name gtype)
300              (register-new-type class-name (class-name super) gtype)))))
301     (unless (eq (class-name super) (supertype type-number))
302       (warn "~A is the super type for ~A in the gobject type system."
303        (supertype type-number) class-name))))
304
305 (defmethod validate-superclass ((class ginstance-class) (super standard-class))
306   (subtypep (class-name super) 'ginstance))
307
308
309 ;;;; Superclass for wrapping types in the glib type system
310
311 (eval-when (:compile-toplevel :load-toplevel :execute)
312   (defclass ginstance (proxy)
313     (;(class :allocation :alien :type pointer :offset 0)
314      )
315     (:metaclass proxy-class)
316     (:size #.(size-of 'pointer))))
317
318 (defun %type-number-of-ginstance (location)
319   (let ((class (sap-ref-sap location 0)))
320     (sap-ref-32 class 0)))
321
322 (defmethod make-proxy-instance :around ((class ginstance-class) location &rest initargs)
323   (declare (ignore class))
324   (let ((class (labels ((find-known-class (type-number)
325                           (or
326                            (find-class (type-from-number type-number) nil)
327                            (unless (zerop type-number)
328                              (find-known-class (type-parent type-number))))))
329                  (find-known-class (%type-number-of-ginstance location)))))
330     ;; Note that chancing the class argument must not alter "the
331     ;; ordered set of applicable methods" as specified in the
332     ;; Hyperspec
333     (if class
334         (apply #'call-next-method class location initargs)
335       (error "Object at ~A has an unkown type number: ~A"
336        location (%type-number-of-ginstance location)))))
337
338 (defmethod make-proxy-instance ((class ginstance-class) location &rest initargs)
339   (declare (ignore initargs))
340   (reference-foreign class location)
341   ;; Since we make an explicit reference to the foreign object, we
342   ;; always have to release it when the proxy is garbage collected
343   ;; and therefor ignore the weak-p argument.
344   (call-next-method class location :weak nil))
345
346 (defmethod invalidate-instance ((instance ginstance))
347   (declare (ignore instance))
348   ;; A ginstance should never be invalidated since it is ref counted
349   nil)
350
351 (defmethod copy-from-alien-form (location (class ginstance-class) &rest args)
352   (declare (ignore location class args))
353   (error "Doing copy-from-alien on a ref. counted class is most certainly an error, but if it really is what you want you should use REFERENCE-FOREIGN on the returned instance instead."))
354
355 (defmethod copy-from-alien-function ((class ginstance-class) &rest args)
356   (declare (ignore class args))  
357   (error "Doing copy-from-alien on a ref. counted class is most certainly an error, but if it really is what you want you should use REFERENCE-FOREIGN on the returned instance instead."))
358
359 (defmethod reader-function ((class ginstance-class) &rest args)
360   (declare (ignore args))
361   #'(lambda (location &optional (offset 0))
362       (ensure-proxy-instance class (sap-ref-sap location offset))))
363
364
365 ;;;; Registering fundamental types
366
367 (register-type 'nil "void")
368 (register-type 'pointer "gpointer")
369 (register-type 'char "gchar")
370 (register-type 'unsigned-char "guchar")
371 (register-type 'boolean "gboolean")
372 (register-type 'int "gint")
373 (register-type-alias 'integer 'int)
374 (register-type-alias 'fixnum 'int)
375 (register-type 'unsigned-int "guint")
376 (register-type 'long "glong")
377 (register-type 'unsigned-long "gulong")
378 (register-type 'single-float "gfloat")
379 (register-type 'double-float "gdouble")
380 (register-type 'pathname "gchararray")
381 (register-type 'string "gchararray")
382
383
384 ;;;; Introspection of type information
385
386 (defvar *derivable-type-info* (make-hash-table))
387
388 (defun register-derivable-type (type id expander &optional dependencies)
389   (register-type type id)
390   (let ((type-number (register-type type id)))
391     (setf 
392      (gethash type-number *derivable-type-info*) 
393      (list expander dependencies))))
394
395 (defun find-type-info (type)
396   (dolist (super (cdr (type-hierarchy type)))
397     (let ((info (gethash super *derivable-type-info*)))
398       (return-if info))))
399
400 (defun expand-type-definition (type forward-p options)
401   (let ((expander (first (find-type-info type))))
402     (funcall expander (find-type-number type t) forward-p options)))
403
404 (defbinding type-parent (type) type-number
405   ((find-type-number type t) type-number))
406
407 (defun supertype (type)
408   (type-from-number (type-parent type)))
409
410 (defbinding %type-interfaces (type) pointer
411   ((find-type-number type t) type-number)
412   (n-interfaces unsigned-int :out))
413
414 (defun type-interfaces (type)
415   (multiple-value-bind (array length) (%type-interfaces type)
416     (unwind-protect
417         (map-c-vector 'list #'identity array 'type-number length)
418       (deallocate-memory array))))
419
420 (defun implements (type)
421   (mapcar #'type-from-number (type-interfaces type)))
422
423 (defun type-hierarchy (type)
424   (let ((type-number (find-type-number type t)))
425     (unless (= type-number 0)
426       (cons type-number (type-hierarchy (type-parent type-number))))))
427   
428 (defbinding (type-is-p "g_type_is_a") (type super) boolean
429   ((find-type-number type) type-number)
430   ((find-type-number super) type-number))
431
432 (defbinding %type-children () pointer
433   (type-number type-number)
434   (num-children unsigned-int :out))
435
436 (defun map-subtypes (function type &optional prefix)
437   (let ((type-number (find-type-number type t)))
438     (multiple-value-bind (array length) (%type-children type-number)
439       (unwind-protect
440           (map-c-vector
441            'nil
442            #'(lambda (type-number)
443                (when (or
444                       (not prefix)
445                       (string-prefix-p prefix (find-foreign-type-name type-number)))
446                  (funcall function type-number))
447                (map-subtypes function type-number prefix))
448            array 'type-number length)
449         (deallocate-memory array)))))
450
451 (defun find-types (prefix)
452   (let ((type-list nil))
453     (maphash
454      #'(lambda (type-number expander)
455          (declare (ignore expander))
456          (map-subtypes
457           #'(lambda (type-number)
458               (pushnew type-number type-list))
459           type-number prefix))
460      *derivable-type-info*)
461     type-list))
462
463 (defun find-type-dependencies (type)
464   (let ((list-dependencies (second (find-type-info type))))
465     (when list-dependencies
466       (funcall list-dependencies (find-type-number type t)))))
467
468 (defun %sort-types-topologicaly (types)
469   (let ((partial-sorted
470          (sort
471           (mapcar 
472            #'(lambda (type)
473                (cons type (remove-if #'(lambda (dep)
474                                          (not (find dep types)))
475                                      (find-type-dependencies type))))
476            types)
477           #'(lambda (type1 type2) (type-is-p type2 type1)) :key #'car))
478         (sorted ()))
479
480     (loop
481      as tmp = partial-sorted then (or (rest tmp) partial-sorted)
482      while tmp
483      do (destructuring-bind (type . dependencies) (first tmp)
484           (cond
485            ((every #'(lambda (dep)
486                        (assoc dep sorted))
487                    dependencies)
488             (push (cons type nil) sorted) ; no forward definition needed
489             (setq partial-sorted (delete type partial-sorted :key #'first)))
490            ((some #'(lambda (dep)
491                       (find type (find-type-dependencies dep)))
492                   dependencies)
493             (push (cons type t) sorted) ; forward definition needed
494             (setq partial-sorted (delete type partial-sorted :key #'first))))))
495     (nreverse sorted)))
496
497
498 (defun expand-type-definitions (prefix &optional args)
499   (flet ((type-options (type-number)
500            (let ((name (find-foreign-type-name type-number)))
501              (cdr (assoc name args :test #'string=)))))
502
503    (let ((type-list
504           (delete-if
505            #'(lambda (type-number)
506                (let ((name (find-foreign-type-name type-number)))
507                  (or
508                   (getf (type-options type-number) :ignore)
509                   (find-if
510                    #'(lambda (options)
511                        (and
512                         (string-prefix-p (first options) name)
513                         (getf (cdr options) :ignore-prefix)
514                         (not (some
515                               #'(lambda (exception)
516                                   (string= name exception))
517                               (getf (cdr options) :except)))))
518                    args))))
519            (find-types prefix))))
520
521      (dolist (type-number type-list)
522        (let ((name (find-foreign-type-name type-number)))
523          (register-type
524           (getf (type-options type-number) :type (default-type-name name))
525           (register-type-as type-number))))
526
527      (let ((sorted-type-list (%sort-types-topologicaly type-list)))
528        `(progn
529           ,@(mapcar
530              #'(lambda (pair)
531                  (destructuring-bind (type . forward-p) pair
532                    (expand-type-definition type forward-p (type-options type))))
533              sorted-type-list)
534           ,@(mapcar
535              #'(lambda (pair)
536                  (destructuring-bind (type . forward-p) pair
537                    (when forward-p
538                      (expand-type-definition type nil (type-options type)))))
539              sorted-type-list))))))
540
541 (defmacro define-types-by-introspection (prefix &rest args)
542   (expand-type-definitions prefix args))
543
544
545 ;;;; Initialize all non static types in GObject
546
547 (init-types-in-library #.(concatenate 'string (pkg-config:pkg-variable "glib-2.0" "libdir") "/libgobject-2.0.so"))