1
# Copyright (C) 2003-2004, 2010 by the gtk2-perl team (see the file AUTHORS for
4
# This library is free software; you can redistribute it and/or modify it under
5
# the terms of the GNU Library General Public License as published by the Free
6
# Software Foundation; either version 2.1 of the License, or (at your option)
9
# This library is distributed in the hope that it will be useful, but WITHOUT
10
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11
# FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for
14
# You should have received a copy of the GNU Library General Public License
15
# along with this library; if not, write to the Free Software Foundation, Inc.,
16
# 59 Temple Place - Suite 330, Boston, MA 02111-1307 USA.
21
package Glib::Object::Subclass;
23
our $VERSION = '0.03';
29
Glib::Object::Subclass - register a perl class as a GObject class
33
use Glib::Object::Subclass
34
Some::Base::Class::, # parent class, derived from Glib::Object
36
something_changed => {
37
class_closure => sub { do_something_fun () },
38
flags => [qw(run-first)],
42
some_existing_signal => \&class_closure_override,
45
Glib::ParamSpec->string (
47
'Some String Property',
48
'This property is a string that is used as an example',
50
[qw/readable writable/]
56
This module allows you to create your own GObject classes, which is useful
57
to e.g. implement your own Gtk2 widgets.
59
It doesn't "export" anything into your namespace, but acts more like
60
a pragmatic module that modifies your class to make it work as a
63
You may be wondering why you can't just bless a Glib::Object into a
64
different package and add some subs. Well, if you aren't interested
65
in object parameters, signals, or having your new class interoperate
66
transparently with other GObject-based modules (e.g., Gtk2 and friends),
67
then you can just re-bless.
69
However, a GObject's signals, properties, virtual functions, and GInterface
70
implementations are specific to its GObjectClass. If you want to create
71
a new GObject which was a derivative of GtkDrawingArea, but adds a new
72
signal, you must create a new GObjectClass to which to add the new signal.
73
If you don't, then I<all> of the GtkDrawingAreas in your application
74
will get that new signal!
76
Thus, the only way to create a new signal or object property in the
77
Perl bindings for Glib is to register a new subclass with the GLib type
78
system via Glib::Type::register_object().
79
The Glib::Object::Subclass module is a Perl-developer-friendly interface
80
to this bit of paradigm mismatch.
84
This module works similar to the C<use base> pragma in that it registers
85
the current package as a subclass of some other class (which must be a
86
GObjectClass implemented either in C or some other language).
88
The pragma requires at least one argument, the parent class name. The
89
remaining arguments are key/value pairs, in any order, all optional:
93
=item - properties => []
95
Add object properties; see L</PROPERTIES>.
99
Add or override signals; see L</SIGNALS> and L</OVERRIDING BASE METHODS>.
101
=item - interfaces => []
103
Add GInterfaces to your class; see L</INTERFACES>.
107
(Actually, these parameters are all passed straight through to
108
Glib::Type::register_object(), adding __PACKAGE__ (the current package name)
109
as the name of the new child class.)
111
=head2 OBJECT METHODS AND FUNCTIONS
113
The following methods are either added to your class on request (not
114
yet implemented), or by default unless your own class implements them
115
itself. This means that all these methods and functions will get sensible
116
default implementations unless explicitly overwritten by you (by defining
119
Except for C<new>, all of the following are I<functions> and no
120
I<methods>. That means that you should I<not> call the superclass
121
method. Instead, the GObject system will call these functions per class as
122
required, emulating normal inheritance.
126
=item $class->new (attr => value, ...)
128
The default constructor just calls C<Glib::Object::new>, which allows you
129
to set properties on the newly created object. This is done because many
130
C<new> methods inherited by Gtk2 or other libraries don't have C<new>
131
methods suitable for subclassing.
133
=item INIT_INSTANCE $self [not a method]
135
C<INIT_INSTANCE> is called on each class in the hierarchy as the object is
136
being created (i.e., from C<Glib::Object::new> or our default C<new>). Use
137
this function to initialize any member data. The default implementation
138
will leave the object untouched.
142
=item GET_PROPERTY $self, $pspec [not a method]
144
=item SET_PROPERTY $self, $pspec, $newval [not a method]
146
C<GET_PROPERTY> and C<SET_PROPERTY> are called whenever somebody does
147
C<< $object->get ($propname) >> or C<< $object->set ($propname => $newval) >>
148
(from other languages, too). The default implementations hold property
149
values in the object hash, equivalent to
152
my ($self, $pspec) = @_;
153
my $pname = $pspec->get_name;
154
return (exists $self->{$pname} ? $self->{$pname}
155
: $pspec->get_default_value); # until set
158
my ($self, $pspec, $newval) = @_;
159
$self->{$pspec->get_name} = $newval;
162
Because C<< $pspec->get_name >> converts hyphens to underscores, a property
163
C<"line-style"> is in the hash as C<line_style>.
165
These methods let you store/fetch properties in any way you need to. They
166
don't have to be in the hash, you can calculate something, read a file,
169
Most often you'll write your own C<SET_PROPERTY> so you can take action when
170
a property changes, like redraw or resize a widget. Eg.
173
my ($self, $pspec, $newval) = @_;
174
my $pname = $pspec->get_name
175
$self->{$pname} = $newval; # ready for default GET_PROPERTY
177
if ($pname eq 'line_style') {
178
$self->queue_draw; # redraw with new lines
182
Care must be taken with boxed non-reference-counted types such as
183
C<Gtk2::Gdk::Color>. In C<SET_PROPERTY> the C<$newval> is generally good
184
only for the duration of the call. Use C<copy> or similar if keeping it
185
longer (see L<Glib::Boxed>). In C<GET_PROPERTY> the returned memory must
186
last long enough to reach the caller, which generally means returning a
187
field, not a newly created object (which is destroyed with the scalar
190
C<GET_PROPERTY> is different from a C get_property method in that the
191
perl method returns the retrieved value. For symmetry, the C<$newval>
192
and C<$pspec> args on C<SET_PROPERTY> are swapped from the C usage.
194
=item FINALIZE_INSTANCE $self [not a method]
196
C<FINALIZE_INSTANCE> is called as the GObject is being finalized, that is,
197
as it is being really destroyed. This is independent of the more common
198
DESTROY on the perl object; in fact, you must I<NOT> override C<DESTROY>
199
(it's not useful to you, in any case, as it is being called multiple
202
Use this hook to release anything you have to clean up manually.
203
FINALIZE_INSTANCE will be called for each perl instance, in reverse order
206
The default finalizer does nothing.
208
=item $object->DESTROY [DO NOT OVERWRITE]
210
Don't I<ever> overwrite C<DESTROY>, use C<FINALIZE_INSTANCE> instead.
212
The DESTROY method of all perl classes derived from GTypes is
213
implemented in the Glib module and (ab-)used for its own internal
214
purposes. Overwriting it is not useful as it will be called
215
I<multiple> times, and often long before the object actually gets
216
destroyed. Overwriting might be very harmful to your program, so I<never>
217
do that. Especially watch out for other classes in your ISA tree.
223
*new = \&Glib::Object::new;
226
# we seem to be imported by classes using classes which use us.
227
# ignore anything that doesn't look like a registration attempt.
228
return unless @_ > 1;
230
my ($self, $superclass, %arg) = @_;
233
Glib::Type->register_object(
238
# ensure that we have a perlish new(). the old version of this
239
# code used a CHECK block to put a new() in if we didn't already
240
# have one in the package, but it may be too late to run a CHECK
241
# block when we get here. so, we use the old-fashioned way...
242
unshift @{ $class."::ISA" }, __PACKAGE__;
249
To create gobject properties, supply a list of Glib::ParamSpec objects as the
250
value for the key 'properties'. There are lots of different paramspec
251
constructors, documented in the C API reference's Parameters and Values page,
252
as well as L<Glib::ParamSpec>.
254
As of Glib 1.060, you can also specify explicit getters and setters for your
255
properties at creation time. The default values in your properties are also
256
honored if you don't set anything else. See Glib::Type::register_object in
257
L<Glib::Type> for an example.
261
Creating new signals for your new object is easy. Just provide a hash
262
of signal names and signal descriptions under the key 'signals'. Each
263
signal description is also a hash, with a few expected keys. All the
264
keys are allowed to default.
268
=item flags => GSignalFlags
270
If not present, assumed to be 'run-first'.
272
=item param_types => reference to a list of package names
274
If not present, assumed to be empty (no parameters).
276
=item class_closure => reference to a subroutine to call as the class closure.
278
may also be a string interpreted as the name of a subroutine to call, but you
279
should be very very very careful about that.
281
If not present, the library will attempt to call the method named
282
"do_signal_name" for the signal "signal_name" (uses underscores).
284
You'll want to be careful not to let this handler method be a publically
285
callable method, or one that has the name name as something that emits the
286
signal. Due to the funky ways in which Glib is different from Perl, the
287
class closures I<should not> inherit through normal perl inheritance.
289
=item return_type => package name for return value.
291
If undefined or not present, the signal expects no return value. if defined,
292
the signal is expected to return a value; flags must be set such that the
293
signal does not run only first (at least use 'run-last').
295
=item accumulator => signal return value accumulator
297
quoting the Glib manual: "The signal accumulator is a special callback function
298
that can be used to collect return values of the various callbacks that are
299
called during a signal emission."
301
If not specified, the default accumulator is used, and you just get the
302
return value of the last handler to run.
304
Accumulators are not really documented very much in the C reference, and
305
the perl interface here is slightly different, so here's an inordinate amount
306
of detail for this arcane feature:
308
The accumulator function is called for every handler as
310
($cont, $acc) = &$func ($invocation_hint, $acc, $ret)
312
$invocation_hint is an anonymous hash (including the signal name); $acc is
313
the current accumulated return value; $ret is the value from the most recent
316
The two return values are a boolean C<$cont> for whether signal emission
317
should continue (false to stop); and a new C<$acc> accumulated return value.
318
(This is different from the C version, which writes through a return_accu.)
322
=head1 OVERRIDING BASE METHODS
324
GLib pulls some fancy tricks with function pointers to implement methods
325
in C. This is not very language-binding-friendly, as you might guess.
327
However, as described above, every signal allows a "class closure"; you
328
may override thie class closure with your own function, and you can chain
329
from the overridden method to the original. This serves to implement
330
virtual overrides for language bindings.
332
So, to override a method, you supply a subroutine reference instead of a
333
signal description hash as the value for the name of the existing signal
334
in the "signals" hash described in L</SIGNALS>.
336
# override some important widget methods:
337
use Glib::Object::Subclass
340
expose_event => \&expose_event,
341
configure_event => \&configure_event,
342
button_press_event => \&button_press_event,
343
button_release_event => \&button_release_event,
344
motion_notify_event => \&motion_notify_event,
345
# note the choice of names here... see the discussion.
346
size_request => \&do_size_request,
349
It's important to note that the handlers you supply for these are
350
class-specific, and that normal perl method inheritance rules are not
351
followed to invoke them from within the library. However, perl code can
352
still find them! Therefore it's rather important that you choose your
353
handlers' names carefully, avoiding any public interfaces that you might
354
call from perl. Case in point, since size_request is a widget method, i
355
chose do_size_request as the override handler.
359
GObject supports only single inheritance; in place of multiple inheritance,
360
GObject uses GInterfaces. In the Perl bindings we have mostly masqueraded
361
this with multiple inheritance (that is, simply adding the GInterface class
362
to the @ISA of the implementing class), but in deriving new objects the
363
facade breaks and the magic leaks out.
365
In order to derive an object that implements a GInterface, you have to tell
366
the GLib type system you want your class to include a GInterface. To do
367
this, simply pass a list of package names through the "interfaces" key;
368
this will add these packages to your @ISA, and cause perl to invoke methods
369
that you must provide.
371
package Mup::MultilineEntry;
372
use Glib::Object::Subclass
374
interfaces => [ 'Gtk2::CellEditable' ],
377
# perl will now invoke these methods, which are part of the
378
# GtkCellEditable GInterface, when somebody invokes the
379
# corresponding lower-case methods on your objects.
380
sub START_EDITING { warn "start editing\n"; }
381
sub EDITING_DONE { warn "editing done\n"; }
382
sub REMOVE_WIDGET { warn "remove widget\n"; }
386
GObject - http://developer.gnome.org/doc/API/2.0/gobject/
390
Marc Lehmann E<lt>schmorp@schmorp.deE<gt>, muppet E<lt>scott at asofyet dot orgE<gt>
392
=head1 COPYRIGHT AND LICENSE
394
Copyright 2003-2004, 2010 by muppet and the gtk2-perl team
396
This library is free software; you can redistribute it and/or modify
397
it under the terms of the Lesser General Public License (LGPL). For
398
more information, see http://www.fsf.org/licenses/lgpl.txt