home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / perl5 / Glib / Object / Subclass.pm
Encoding:
Perl POD Document  |  2005-07-01  |  13.7 KB  |  374 lines

  1. # Copyright (C) 2003-2004 by the gtk2-perl team (see the file AUTHORS for
  2. # the full list)
  3. # This library is free software; you can redistribute it and/or modify it under
  4. # the terms of the GNU Library General Public License as published by the Free
  5. # Software Foundation; either version 2.1 of the License, or (at your option)
  6. # any later version.
  7. # This library is distributed in the hope that it will be useful, but WITHOUT
  8. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. # FOR A PARTICULAR PURPOSE.  See the GNU Library General Public License for
  10. # more details.
  11. # You should have received a copy of the GNU Library General Public License
  12. # along with this library; if not, write to the Free Software Foundation, Inc.,
  13. # 59 Temple Place - Suite 330, Boston, MA  02111-1307  USA.
  14. #
  15. # $Header: /cvsroot/gtk2-perl/gtk2-perl-xs/Glib/Subclass.pm,v 1.13 2005/07/02 00:35:15 pcg Exp $
  16. #
  17.  
  18. package Glib::Object::Subclass;
  19.  
  20. our $VERSION = '0.03';
  21.  
  22. use Glib;
  23.  
  24. =head1 NAME
  25.  
  26. Glib::Object::Subclass - register a perl class as a GObject class
  27.  
  28. =head1 SYNOPSIS
  29.  
  30.   use Glib::Object::Subclass
  31.      Some::Base::Class::,   # parent class, derived from Glib::Object
  32.      signals => {
  33.             something_changed => {
  34.                class_closure => sub { do_something_fun () },
  35.                flags         => [qw(run-first)],
  36.                return_type   => undef,
  37.                param_types   => [],
  38.             },
  39.             some_existing_signal => \&class_closure_override,
  40.      },
  41.      properties => [
  42.         Glib::ParamSpec->string (
  43.            'some_string',
  44.            'Some String Property',
  45.            'This property is a string that is used as an example',
  46.            'default value',
  47.            [qw/readable writable/]
  48.         ),
  49.      ];
  50.  
  51. =head1 DESCRIPTION
  52.  
  53. This module allows you to create your own GObject classes, which is useful
  54. to e.g. implement your own Gtk2 widgets.
  55.  
  56. It doesn't "export" anything into your namespace, but acts more like
  57. a pragmatic module that modifies your class to make it work as a
  58. GObject class.
  59.  
  60. You may be wondering why you can't just bless a Glib::Object into a
  61. different package and add some subs.  Well, if you aren't interested 
  62. in object parameters, signals, or having your new class interoperate
  63. transparently with other GObject-based modules (e.g., Gtk2 and friends),
  64. then you can just re-bless.
  65.  
  66. However, a GObject's signals, properties, virtual functions, and GInterface
  67. implementations are specific to its GObjectClass.  If you want to create
  68. a new GObject which was a derivative of GtkDrawingArea, but adds a new
  69. signal, you must create a new GObjectClass to which to add the new signal.
  70. If you don't, then I<all> of the GtkDrawingAreas in your application
  71. will get that new signal!
  72.  
  73. Thus, the only way to create a new signal or object property in the
  74. Perl bindings for Glib is to register a new subclass with the GLib type
  75. system via Glib::Type::register_object().
  76. The Glib::Object::Subclass module is a Perl-developer-friendly interface
  77. to this bit of paradigm mismatch.
  78.  
  79. =head2 USAGE
  80.  
  81. This module works similar to the C<use base> pragma in that it registers
  82. the current package as a subclass of some other class (which must be a
  83. GObjectClass implemented either in C or some other language).
  84.  
  85. The pragma requires at least one argument, the parent class name.  The
  86. remaining arguments are key/value pairs, in any order, all optional:
  87.  
  88. =over
  89.  
  90. =item - properties => []
  91.  
  92. Add object properties; see L</PROPERTIES>.
  93.  
  94. =item - signals => {}
  95.  
  96. Add or override signals; see L</SIGNALS> and L</OVERRIDING BASE METHODS>.
  97.  
  98. =item - interfaces => []
  99.  
  100. Add GInterfaces to your class; see L</INTERFACES>.
  101.  
  102. =back
  103.  
  104. (Actually, these parameters are all passed straight through to
  105. Glib::Type::register_object(), adding __PACKAGE__ (the current package name)
  106. as the name of the new child class.)
  107.  
  108. =head2 OBJECT METHODS AND FUNCTIONS
  109.  
  110. The following methods are either added to your class on request (not
  111. yet implemented), or by default unless your own class implements them
  112. itself. This means that all these methods and functions will get sensible
  113. default implementations unless explicitly overwritten by you (by defining
  114. your own version).
  115.  
  116. Except for C<new>, all of the following are I<functions> and no
  117. I<methods>. That means that you should I<not> call the superclass
  118. method. Instead, the GObject system will call these functions per class as
  119. required, emulating normal inheritance.
  120.  
  121. =over 4
  122.  
  123. =item $class->new (attr => value, ...)
  124.  
  125. The default constructor just calls C<Glib::Object::new>, which allows you
  126. to set properties on the newly created object. This is done because many
  127. C<new> methods inherited by Gtk2 or other libraries don't have C<new>
  128. methods suitable for subclassing.
  129.  
  130. =item INIT_INSTANCE $self                                 [not a method]
  131.  
  132. C<INIT_INSTANCE> is called on each class in the hierarchy as the object is
  133. being created (i.e., from C<Glib::Object::new> or our default C<new>). Use
  134. this function to initialize any member data. The default implementation
  135. will leave the object untouched.
  136.  
  137. =cut
  138.  
  139. =item GET_PROPERTY $self, $pspec                          [not a method]
  140.  
  141. Get a property value, see C<SET_PROPERTY>.
  142.  
  143. The default implementation looks like this:
  144.  
  145.    my ($self, $pspec) = @_;
  146.    return ($self->{$pspec->get_name} || $pspec->get_default_value);
  147.  
  148. =item SET_PROPERTY $self, $pspec, $newval                 [not a method]
  149.  
  150. C<GET_PROPERTY> and C<SET_PROPERTY> are called whenever somebody does
  151. C<< $object->get ($propname) >> or C<< $object->set ($propname => $newval) >>
  152. (from other languages, too). This is your hook that allows you to
  153. store/fetch properties in any way you need to (maybe you have to calculate
  154. something or read a file).
  155.  
  156. C<GET_PROPERTY> is different from a C get_property method in that the
  157. perl method returns the retrieved value. For symmetry, the C<$newval>
  158. and C<$pspec> args on C<SET_PROPERTY> are swapped from the C usage. The
  159. default get and set methods store property data in the object as hash
  160. values named for the parameter name.
  161.  
  162. The default C<SET_PROPERTY> looks like this:
  163.  
  164.    my ($self, $pspec, $newval) = @_;
  165.    $self->{$pspec->get_name} = $newval;
  166.  
  167. =item FINALIZE_INSTANCE $self                             [not a method]
  168.  
  169. C<FINALIZE_INSTANCE> is called as the GObject is being finalized, that is,
  170. as it is being really destroyed.  This is independent of the more common
  171. DESTROY on the perl object; in fact, you must I<NOT> override C<DESTROY>
  172. (it's not useful to you, in any case, as it is being called multiple
  173. times!).
  174.  
  175. Use this hook to release anything you have to clean up manually.
  176. FINALIZE_INSTANCE will be called for each perl instance, in reverse order
  177. of construction.
  178.  
  179. The default finalizer does nothing.
  180.  
  181. =item $object->DESTROY           [DO NOT OVERWRITE]
  182.  
  183. Don't I<ever> overwrite C<DESTROY>, use C<FINALIZE_INSTANCE> instead.
  184.  
  185. The DESTROY method of all perl classes derived from GTypes is
  186. implemented in the Glib module and (ab-)used for its own internal
  187. purposes. Overwriting it is not useful as it will be called
  188. I<multiple> times, and often long before the object actually gets
  189. destroyed.  Overwriting might be very harmful to your program, so I<never>
  190. do that.  Especially watch out for other classes in your ISA tree.
  191.  
  192. =back
  193.  
  194. =cut
  195.  
  196. *new = \&Glib::Object::new;
  197.  
  198. sub import {
  199.    # we seem to be imported by classes using classes which use us.
  200.    # ignore anything that doesn't look like a registration attempt.
  201.    return unless @_ > 1;
  202.  
  203.    my ($self, $superclass, %arg) = @_;
  204.    my $class = caller;
  205.  
  206.    Glib::Type->register_object(
  207.       $superclass, $class,
  208.       %arg,
  209.    );
  210.  
  211.    # ensure that we have a perlish new().  the old version of this
  212.    # code used a CHECK block to put a new() in if we didn't already
  213.    # have one in the package, but it may be too late to run a CHECK
  214.    # block when we get here.  so, we use the old-fashioned way...
  215.    unshift @{ $class."::ISA" }, __PACKAGE__;
  216. }
  217.  
  218. 1;
  219.  
  220. =head1 PROPERTIES
  221.  
  222. To create gobject properties, supply a list of Glib::ParamSpec objects as the
  223. value for the key 'properties'.  There are lots of different paramspec
  224. constructors, documented in the C API reference's Parameters and Values page,
  225. as well as L<Glib::ParamSpec>.
  226.  
  227. As of Glib 1.060, you can also specify explicit getters and setters for your
  228. properties at creation time.  The default values in your properties are also
  229. honored if you don't set anything else.  See Glib::Type::register_object in
  230. L<Glib::Type> for an example.
  231.  
  232. =head1 SIGNALS
  233.  
  234. Creating new signals for your new object is easy.  Just provide a hash
  235. of signal names and signal descriptions under the key 'signals'.  Each
  236. signal description is also a hash, with a few expected keys.  All the 
  237. keys are allowed to default.
  238.  
  239. =over
  240.  
  241. =item flags => GSignalFlags
  242.  
  243. If not present, assumed to be 'run-first'.
  244.  
  245. =item param_types => reference to a list of package names
  246.  
  247. If not present, assumed to be empty (no parameters).
  248.  
  249. =item class_closure => reference to a subroutine to call as the class closure.
  250.  
  251. may also be a string interpreted as the name of a subroutine to call, but you
  252. should be very very very careful about that.
  253.  
  254. If not present, the library will attempt to call the method named
  255. "do_signal_name" for the signal "signal_name" (uses underscores).
  256.  
  257. You'll want to be careful not to let this handler method be a publically
  258. callable method, or one that has the name name as something that emits the
  259. signal.  Due to the funky ways in which Glib is different from Perl, the
  260. class closures I<should not> inherit through normal perl inheritance.
  261.  
  262. =item return_type => package name for return value.
  263.  
  264. If undefined or not present, the signal expects no return value.  if defined,
  265. the signal is expected to return a value; flags must be set such that the
  266. signal does not run only first (at least use 'run-last').
  267.  
  268. =item accumulator => signal return value accumulator
  269.  
  270. quoting the Glib manual: "The signal accumulator is a special callback function
  271. that can be used to collect return values of the various callbacks that are
  272. called during a signal emission."
  273.  
  274. If not specified, the default accumulator is used, and you just get the 
  275. return value of the last handler to run.
  276.  
  277. Accumulators are not really documented very much in the C reference, and
  278. the perl interface here is slightly different, so here's an inordinate amount
  279. of detail for this arcane feature:
  280.  
  281. The accumulator function is called for every handler.  It is given three
  282. arguments: the signal invocation hint as an anonymous hash (containing the
  283. signal name, notably); the current accumulated return value; and the value
  284. returned by the most recent handler.  The accumulator must return two values:
  285. a boolean value determining whether signal emission should continue (false
  286. stops the emission), and the new value for the accumulated return value.
  287. (This is different from the C version, which writes through the return_accu.)
  288.  
  289. =back
  290.  
  291. =head1 OVERRIDING BASE METHODS
  292.  
  293. GLib pulls some fancy tricks with function pointers to implement methods
  294. in C.  This is not very language-binding-friendly, as you might guess.
  295.  
  296. However, as described above, every signal allows a "class closure"; you
  297. may override thie class closure with your own function, and you can chain
  298. from the overridden method to the original.  This serves to implement
  299. virtual overrides for language bindings.
  300.  
  301. So, to override a method, you supply a subroutine reference instead of a
  302. signal description hash as the value for the name of the existing signal
  303. in the "signals" hash described in L</SIGNALS>.
  304.  
  305.   # override some important widget methods:
  306.   use Glib::Object::Subclass
  307.         Gtk2::Widget::,
  308.     signals => {
  309.         expose_event => \&expose_event,
  310.         configure_event => \&configure_event,
  311.         button_press_event => \&button_press_event,
  312.         button_release_event => \&button_release_event,
  313.         motion_notify_event => \&motion_notify_event,
  314.         # note the choice of names here... see the discussion.
  315.         size_request => \&do_size_request,
  316.     }
  317.  
  318. It's important to note that the handlers you supply for these are
  319. class-specific, and that normal perl method inheritance rules are not
  320. followed to invoke them from within the library.  However, perl code can
  321. still find them!  Therefore it's rather important that you choose your
  322. handlers' names carefully, avoiding any public interfaces that you might
  323. call from perl.  Case in point, since size_request is a widget method, i
  324. chose do_size_request as the override handler.
  325.  
  326. =head1 INTERFACES
  327.  
  328. GObject supports only single inheritance; in place of multiple inheritance,
  329. GObject uses GInterfaces.  In the Perl bindings we have mostly masqueraded
  330. this with multiple inheritance (that is, simply adding the GInterface class
  331. to the @ISA of the implementing class), but in deriving new objects the
  332. facade breaks and the magic leaks out.
  333.  
  334. In order to derive an object that implements a GInterface, you have to tell
  335. the GLib type system you want your class to include a GInterface.  To do
  336. this, simply pass a list of package names through the "interfaces" key;
  337. this will add these packages to your @ISA, and cause perl to invoke methods
  338. that you must provide.
  339.  
  340.   package Mup::MultilineEntry;
  341.   use Glib::Object::Subclass
  342.       'Gtk2::TextView',
  343.       interfaces => [ 'Gtk2::CellEditable' ],
  344.       ;
  345.  
  346.   # perl will now invoke these methods, which are part of the
  347.   # GtkCellEditable GInterface, when somebody invokes the
  348.   # corresponding lower-case methods on your objects.
  349.   sub START_EDITING { warn "start editing\n"; }
  350.   sub EDITING_DONE { warn "editing done\n"; }
  351.   sub REMOVE_WIDGET { warn "remove widget\n"; }
  352.  
  353. =head1 SEE ALSO
  354.  
  355.   GObject - http://developer.gnome.org/doc/API/2.0/gobject/
  356.  
  357. =head1 AUTHORS
  358.  
  359. Marc Lehmann E<lt>schmorp@schmorp.deE<gt>, muppet E<lt>scott at asofyet dot orgE<gt>
  360.  
  361. =head1 COPYRIGHT AND LICENSE
  362.  
  363. Copyright 2003-2004 by muppet and the gtk2-perl team
  364.  
  365. This library is free software; you can redistribute it and/or modify
  366. it under the terms of the Lesser General Public License (LGPL).  For 
  367. more information, see http://www.fsf.org/licenses/lgpl.txt
  368.  
  369. =cut
  370.  
  371.