1api(3) User Contributed Perl Documentation api(3)
2
3
4
6 Gtk2::api - Mapping the Gtk+ C API to perl
7
9 The Gtk2 module attempts to stick as close as is reasonable to the C
10 API, to minimize the need to maintain documentation which is nearly a
11 copy of the C API reference documentation. However, the world is not
12 perfect, and the mappings between C and perl are not as clean and
13 predictable as you might wish. Thus, this page described the basics of
14 how to map the C API to the perl API, and lists various points in the
15 API which follow neither the C API documentation nor the mapping
16 principles.
17
19 The canonical documentation is the C API reference at
20 http://developer.gnome.org/doc/API/gtk/ and
21 http://developer.gnome.org/doc/API/gdk/
22
23 There are two main sections: 'BINDING BASICS' describes the principles
24 on which the bindings work; understanding these can lead you to guess
25 the proper syntax to use for any given function described in the C API
26 reference. The second section lists various specific points of
27 difference which don't necessarily correspond with what you expect;
28 this section is in three main parts: missing methods, renamed methods,
29 and different call signatures.
30
32 We avoid deprecated APIs. Many functions refer to C concepts which are
33 alien to the bindings. Many things have replacements.
34
35 Deprecated Stuff Isn't Bound
36 Things that were marked as deprecated at gtk+ 2.0.0 do not appear in
37 the bindings. This means that gtk+-1.x's GtkCList, GtkTree, and
38 GtkText are not available. The notable exception is GtkList, which is
39 available solely in support of GtkCombo (which was itself replaced by
40 GtkComboBox in 2.4); it should not be used under any other
41 circumstances. If you really need access to these old widgets, search
42 the web for "Gtk2::Deprecated".
43
44 Some other things were deprecated during the gtk+ 2.x series, e.g.
45 GtkOptionMenu was deprecated in favor of GtkComboBox in 2.4. Things
46 that were marked as deprecated during the 2.x series will not be
47 removed, basically because older versions do not have the replacements,
48 and removing them would break backward compatibility.
49
50 Namespaces and Objects
51 The namespaces of the C libraries are mapped to perl packages according
52 to scope, although in some cases the distinction may seem rather
53 arbitrary:
54
55 g_ => Glib (the Glib module - distributed separately)
56 gtk_ => Gtk2
57 gdk_ => Gtk2::Gdk
58 gdk_pixbuf_ => Gtk2::Gdk::Pixbuf
59 pango_ => Gtk2::Pango
60
61 Objects get their own namespaces, in a way, as the concept of the GType
62 is completely replaced in the perl bindings by the perl package name.
63 This goes for GBoxed, GObject, and even things like Glib::String and
64 Glib::Int (which are needed for specifying column types in the
65 Gtk2::TreeModel). (Flags and enums are special -- see below.)
66
67 GtkButton => Gtk2::Button
68 GdkPixbuf => Gtk2::Gdk::Pixbuf
69 GtkScrolledWindow => Gtk2::ScrolledWindow
70 PangoFontDescription => Gtk2::Pango::FontDescription
71
72 With this package mapping and perl's built-in method lookup, the
73 bindings can do object casting for you. This gives us a rather
74 comfortably object-oriented syntax, using normal perl syntax semantics:
75
76 in C:
77 GtkWidget * b;
78 b = gtk_check_button_new_with_mnemonic ("_Something");
79 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (b), TRUE);
80 gtk_widget_show (b);
81
82 in perl:
83 my $b = Gtk2::CheckButton->new ('_Something');
84 $b->set_active (1);
85 $b->show;
86
87 You see from this that constructors for most widgets which allow
88 mnemonics will use mnemonics by default in their "new" methods. For
89 those who don't guess this right off, Gtk2::Button->new_with_mnemonic
90 is also available. Cast macros are not necessary, and your code is a
91 lot shorter.
92
93 Flags and Enums
94 Constants are handled as strings, because it's much more readable than
95 numbers, and because it's automagical thanks to the GType system.
96 Constants are referred to by their nicknames; basically, strip the
97 common prefix, lower-case it, and optionally convert '_' to '-':
98
99 GTK_WINDOW_TOPLEVEL => 'toplevel'
100 GTK_BUTTONS_OK_CANCEL => 'ok-cancel' (or 'ok_cancel')
101
102 Flags are a special case. You can't (sensibly) bitwise-or these
103 string-constants, so you provide a reference to an array of them
104 instead. Anonymous arrays are useful here, and an empty anonymous
105 array is a simple way to say 'no flags'.
106
107 FOO_BAR_BAZ | FOO_BAR_QUU | FOO_BAR_QUUX => [qw/baz quu qux/]
108 0 => []
109
110 In some cases you need to see if a bit is set in a bitfield; methods
111 returning flags therefore return an overloaded object. See Glib for
112 more details on which operations are allowed on these flag objects, but
113 here is a quick example:
114
115 in C:
116 /* event->state is a bitfield */
117 if (event->state & GDK_CONTROL_MASK) g_printerr ("control was down\n");
118
119 in perl:
120 # $event->state is a special object
121 warn "control was down\n" if $event->state & "control-mask";
122
123 But this also works:
124
125 warn "control was down\n" if $event->state * "control-mask";
126 warn "control was down\n" if $event->state >= "control-mask";
127 warn "control and shift were down\n"
128 if $event->state >= ["control-mask", "shift-mask"];
129
130 And treating it as an array of strings (as in older versions) is still
131 supported:
132
133 warn "control was down\n" if grep /control-mask/, @{ $event->state };
134
135 The gtk stock item stuff is a little different -- the GTK_STOCK_*
136 constants are actually macros which evaluate to strings, so they aren't
137 handled by the mechanism described above; you just specify the string,
138 e.g., GTK_STOCK_OK => 'gtk-ok'. The full list of stock items can be
139 found at
140 http://developer.gnome.org/doc/API/2.0/gtk/gtk-Stock-Items.html
141
142 Memory Handling
143 The functions for ref'ing and unref'ing objects and free'ing boxed
144 structures are not even mapped to perl, because it's all handled
145 automagically by the bindings. I could write a treatise on how we're
146 handling reference counts and object lifetimes, but all you need to
147 know as perl developer is that it's handled for you, and the object
148 will be alive so long as you have a perl scalar pointing to it or the
149 object is referenced in another way, e.g. from a container.
150
151 The only thing you have to be careful about is the lifespan of non
152 reference counted structures, which means most things derived from
153 "Glib::Boxed". If it comes from a signal callback it might be good
154 only until you return, or if it's the insides of another object then it
155 might be good only while that object lives. If in doubt you can
156 "copy". Structs from "copy" or "new" are yours and live as long as
157 referred to from Perl.
158
159 Callbacks
160 Use normal perl callback/closure tricks with callbacks. The most
161 common use you'll have for callbacks is with the Glib "signal_connect"
162 method:
163
164 $widget->signal_connect (event => \&event_handler, $user_data);
165 $button->signal_connect (clicked => sub { warn "hi!\n" });
166
167 $user_data is optional, and with perl closures you don't often need it
168 (see "Persistent variables with closures" in perlsub).
169
170 The userdata is held in a scalar, initialized from what you give in
171 "signal_connect" etc. It's passed to the callback in usual Perl "call
172 by reference" style which means the callback can modify its last
173 argument, ie. $_[-1], to modify the held userdata. This is a little
174 subtle, but you can use it for some "state" associated with the
175 connection.
176
177 $widget->signal_connect (activate => \&my_func, 1);
178 sub my_func {
179 print "activation count: $_[-1]\n";
180 $_[-1] ++;
181 }
182
183 Because the held userdata is a new scalar there's no change to the
184 variable (etc) you originally passed to "signal_connect".
185
186 If you have a parent object in the userdata (or closure) you have to be
187 careful about circular references preventing parent and child being
188 destroyed. See "Two-Phased Garbage Collection" in perlobj about this
189 generally. In Gtk2-Perl toplevel widgets like "Gtk2::Window" always
190 need an explicit "$widget->destroy" so their "destroy" signal is a good
191 place to break circular references. But for other widgets using weak
192 references to avoid circularities in the first place is usually
193 friendliest.
194
195 A major change from gtk-perl (the bindings for Gtk+-1.x) is that
196 callbacks take their arguments in the order proscribed by the C
197 documentation, and only one value is available for user data. gtk-perl
198 allowed you to pass multiple values for user_data, and always brought
199 in the user_data immediately after the instance reference; this proved
200 to be rather confusing, and did not follow the C API reference, so we
201 decided not to do that for gtk2-perl.
202
203 Miscellaneous
204 In C you can only return one value from a function, and it is a common
205 practice to modify pointers passed in to simulate returning multiple
206 values. In perl, you can return lists; any functions which modify
207 arguments have been changed to return them instead. A common idiom in
208 gtk is returning gboolean, and modifying several arguments if the
209 function returns TRUE; for such functions, the perl wrapper just
210 returns an empty list on failure.
211
212 in C: foo_get_baz_and_quux (foo, &baz, &quux);
213 in perl: ($baz, $quux) = $foo->get_baz_and_quux;
214
215 Most things that take or return a GList, GSList, or array of values
216 will use native perl arrays (or the argument stack) instead.
217
218 You don't need to specify string lengths, although string length
219 parameters should still be available for functions dealing with binary
220 strings. You can always use "substr" to pass different parts of a
221 string.
222
223 Anything that uses GError in C will "croak" on failure, setting $@ to a
224 magical exception object, which is overloaded to print as the returned
225 error message. The ideology here is that GError is to be used for
226 runtime exceptions, and "croak" is how you do that in perl. You can
227 catch a croak very easily by wrapping the function in an eval:
228
229 eval {
230 my $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file ($filename);
231 $image->set_from_pixbuf ($pixbuf);
232 };
233 if ($@) {
234 print "$@\n"; # prints the possibly-localized error message
235 if (Glib::Error::matches ($@, 'Gtk2::Gdk::Pixbuf::Error',
236 'unknown-format')) {
237 change_format_and_try_again ();
238 } elsif (Glib::Error::matches ($@, 'Glib::File::Error', 'noent')) {
239 change_source_dir_and_try_again ();
240 } else {
241 # don't know how to handle this
242 die $@;
243 }
244 }
245
246 This has the added advantage of letting you bunch things together as
247 you would with a try/throw/catch block in C++ -- you get cleaner code.
248 By using Glib::Error exception objects, you don't have to rely on
249 string matching on a possibly localized error message; you can match
250 errors by explicit and predictable conditions. See Glib::Error for
251 more information.
252
254 g_object_ref => no replacement
255 g_object_unref => no replacement
256 g_boxed_free => no replacement
257 The bindings do automatic memory management. You should never need
258 to use these.
259
260 gtk_timeout_add => Glib::Timeout->add
261 gtk_timeout_remove => Glib::Source->remove
262 gtk_idle_add => Glib::Idle->add
263 gtk_idle_remove => Glib::Source->remove
264 gtk_input_add => Glib::IO->add_watch
265 gtk_input_remove => Glib::Source->remove
266 The gtk_* functions are deprecated in favor of the g_* ones.
267 Gtk2::Helper has a wrapper for Glib::IO->add_watch which makes it
268 behave more like gtk_input_add.
269
270 gtk_accel_group_from_accel_closure => no replacement
271 Because of the use of Perl subroutine references in place of
272 GClosures, there is no way to preserve at the Perl level the one-
273 to-one mapping between GtkAccelGroups and GClosures. Without that
274 mapping, this function is useless.
275
277 gtk_aspect_frame_set => $aspect_frame->set_params
278 Avoid a clash with $gobject->set.
279
281 As a general rule function that take a pair of parameters, a list and
282 the number of elements in that list, will normally omit the number of
283 elements and just accept a variable number of arguments that will be
284 converted into the list and number of elements. In many instances
285 parameters have been reordered so that this will work. See below for
286 exceptions and specific cases that are not detailed in the generated
287 Perl API reference.
288
289 Gtk2::ScrollBar vs. GtkScrollbar
290 These classes were incorrectly written with a capital "B" in
291 version 1.00 and below. They have been renamed in version 1.01 and
292 the old way to write them is deprecated, but supported.
293
294 Gtk2::ItemFactory::create_items
295 The n_entries parameter has been ommited and callback_data is
296 accepted as the first parameter. All parameters after that are
297 considered to be entries.
298
299 Gtk2::List::insert_items
300 Position and items parameters flipped order so that an open ended
301 parameter list could be used. "$list->insert_items($position,
302 $item1, $item2, ...)" (Note that GtkList and GtkListItem are
303 deprecated and only included because GtkCombo still makes use of
304 them, they are subject to removal at any point so you should not
305 utilize them unless absolutely necessary.)
306
307 Gtk2::Notebook::append_page
308 Gtk2::Notebook::prepend_page
309 Gtk2::Notebook::insert_page
310 The C API for these functions requires a GtkWidget for the
311 tab_label, since you can set any widget you like to be the tab
312 label. However, the most common use is a plain Gtk2::Label; so
313 these three functions will stringify anything passed to tab_label
314 that's not a GtkWidget and wrap a Gtk2::Label around it for you.
315
316 Note that the "_menu" versions of these functions do not do this.
317
318 Gtk2::AccelGroup::connect
319 Gtk2::AccelGroup::disconnect
320 Where a GClosure is wanted by the C stuff, a perl subroutine
321 reference suffices. However, because of this, there are a few
322 subtle differences in sematics. a GClosure may be connected to
323 only one GtkAccelGroup; however, a perl subroutine may be connected
324 to many GtkAccelGroups (because at the binding level, a new
325 GClosure is created on each call to ->connect). Thus,
326 $accel_group->disconnect will disconnect the first group it finds
327 to be connected to the given perl subroutine. To disconnect all
328 groups attached to a subroutine, you can call disconnect with the
329 same subroutine reference (or name) until it stops returning true.
330
331 Gtk2::Clipboard::set_with_data
332 Gtk2::Clipboard::set_with_owner
333 In C, these functions take an array of GtkTargetEntries and the
334 number of elements in that array as the second and third
335 parameters. In Perl, the number of target entries is implied by
336 the number of items on the stack, and the target entries are
337 supplied as a list at the end of the parameter list:
338
339 $clipboard->set_with_data (\&get_func, \&clear_func, $user_data,
340 @target_entries);
341 $clipboard->set_with_owner (\&get_func, \&clear_func, $owner,
342 @target_entries);
343
345 The canonical documentation is the C API reference at
346 http://developer.gnome.org/doc/API/gtk/ and
347 http://developer.gnome.org/doc/API/gdk/
348
349 Gtk2 includes a full suite of automatically-generated API reference POD
350 for the Perl API -- see Gtk2::index for the starting point.
351
352 There should be a similar document for Glib --- link to it here when it
353 exists.
354
356 muppet <scott at asofyet dot org>
357
359 Copyright (C) 2003 by the gtk2-perl team (see the file AUTHORS for the
360 full list)
361
362 This library is free software; you can redistribute it and/or modify it
363 under the terms of the GNU Library General Public License as published
364 by the Free Software Foundation; either version 2.1 of the License, or
365 (at your option) any later version.
366
367 This library is distributed in the hope that it will be useful, but
368 WITHOUT ANY WARRANTY; without even the implied warranty of
369 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
370 Library General Public License for more details.
371
372 You should have received a copy of the GNU Library General Public
373 License along with this library; if not, write to the Free Software
374 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307
375 USA.
376
377
378
379perl v5.12.0 2008-10-22 api(3)