1Gtk2::api(3)          User Contributed Perl Documentation         Gtk2::api(3)
2
3
4

NAME

6       Gtk2::api - Mapping the Gtk+ C API to perl
7

ABSTRACT

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

DESCRIPTION

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

BINDING BASICS

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 it's usually
192       friendliest to avoid circularities in the first place, either by using
193       weak references in the userdata, or possibly locating a parent
194       dynamically with "$widget->get_ancestor".
195
196       A major change from gtk-perl (the bindings for Gtk+-1.x) is that
197       callbacks take their arguments in the order proscribed by the C
198       documentation, and only one value is available for user data.  gtk-perl
199       allowed you to pass multiple values for user_data, and always brought
200       in the user_data immediately after the instance reference; this proved
201       to be rather confusing, and did not follow the C API reference, so we
202       decided not to do that for gtk2-perl.
203
204   Miscellaneous
205       In C you can only return one value from a function, and it is a common
206       practice to modify pointers passed in to simulate returning multiple
207       values.  In perl, you can return lists; any functions which modify
208       arguments have been changed to return them instead.  A common idiom in
209       gtk is returning gboolean, and modifying several arguments if the
210       function returns TRUE; for such functions, the perl wrapper just
211       returns an empty list on failure.
212
213         in C:  foo_get_baz_and_quux (foo, &baz, &quux);
214         in perl:  ($baz, $quux) = $foo->get_baz_and_quux;
215
216       Most things that take or return a GList, GSList, or array of values
217       will use native perl arrays (or the argument stack) instead.
218
219       You don't need to specify string lengths, although string length
220       parameters should still be available for functions dealing with binary
221       strings. You can always use "substr" to pass different parts of a
222       string.
223
224       Anything that uses GError in C will "croak" on failure, setting $@ to a
225       magical exception object, which is overloaded to print as the returned
226       error message.  The ideology here is that GError is to be used for
227       runtime exceptions, and "croak" is how you do that in perl.  You can
228       catch a croak very easily by wrapping the function in an eval:
229
230          eval {
231             my $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file ($filename);
232             $image->set_from_pixbuf ($pixbuf);
233          };
234          if ($@) {
235             print "$@\n"; # prints the possibly-localized error message
236             if (Glib::Error::matches ($@, 'Gtk2::Gdk::Pixbuf::Error',
237                                           'unknown-format')) {
238                change_format_and_try_again ();
239             } elsif (Glib::Error::matches ($@, 'Glib::File::Error', 'noent')) {
240                change_source_dir_and_try_again ();
241             } else {
242                # don't know how to handle this
243                die $@;
244             }
245          }
246
247       This has the added advantage of letting you bunch things together as
248       you would with a try/throw/catch block in C++ -- you get cleaner code.
249       By using Glib::Error exception objects, you don't have to rely on
250       string matching on a possibly localized error message; you can match
251       errors by explicit and predictable conditions.  See Glib::Error for
252       more information.
253

MISSING METHODS

255       g_object_ref   => no replacement
256       g_object_unref => no replacement
257       g_boxed_free   => no replacement
258           The bindings do automatic memory management. You should never need
259           to use these.
260
261       gtk_timeout_add    => Glib::Timeout->add
262       gtk_timeout_remove => Glib::Source->remove
263       gtk_idle_add       => Glib::Idle->add
264       gtk_idle_remove    => Glib::Source->remove
265       gtk_input_add      => Glib::IO->add_watch
266       gtk_input_remove   => Glib::Source->remove
267           The gtk_* functions are deprecated in favor of the g_* ones.
268           Gtk2::Helper has a wrapper for Glib::IO->add_watch which makes it
269           behave more like gtk_input_add.
270
271       gtk_accel_group_from_accel_closure => no replacement
272           Because of the use of Perl subroutine references in place of
273           GClosures, there is no way to preserve at the Perl level the one-
274           to-one mapping between GtkAccelGroups and GClosures.  Without that
275           mapping, this function is useless.
276

RENAMED METHODS

278       gtk_aspect_frame_set     => $aspect_frame->set_params
279           Avoid a clash with $gobject->set.
280

DIFFERENT CALL SIGNATURES OR SEMANTICS

282       As a general rule function that take a pair of parameters, a list and
283       the number of elements in that list, will normally omit the number of
284       elements and just accept a variable number of arguments that will be
285       converted into the list and number of elements.  In many instances
286       parameters have been reordered so that this will work.  See below for
287       exceptions and specific cases that are not detailed in the generated
288       Perl API reference.
289
290       Gtk2::ScrollBar vs. GtkScrollbar
291           These classes were incorrectly written with a capital "B" in
292           version 1.00 and below.  They have been renamed in version 1.01 and
293           the old way to write them is deprecated, but supported.
294
295       Gtk2::ItemFactory::create_items
296           The n_entries parameter has been omitted and callback_data is
297           accepted as the first parameter. All parameters after that are
298           considered to be entries.
299
300       Gtk2::List::insert_items
301           Position and items parameters flipped order so that an open ended
302           parameter list could be used. "$list->insert_items($position,
303           $item1, $item2, ...)"  (Note that GtkList and GtkListItem are
304           deprecated and only included because GtkCombo still makes use of
305           them, they are subject to removal at any point so you should not
306           utilize them unless absolutely necessary.)
307
308       Gtk2::Notebook::append_page
309       Gtk2::Notebook::prepend_page
310       Gtk2::Notebook::insert_page
311           The C API for these functions requires a GtkWidget for the
312           tab_label, since you can set any widget you like to be the tab
313           label.  However, the most common use is a plain Gtk2::Label; so
314           these three functions will stringify anything passed to tab_label
315           that's not a GtkWidget and wrap a Gtk2::Label around it for you.
316
317           Note that the "_menu" versions of these functions do not do this.
318
319       Gtk2::AccelGroup::connect
320       Gtk2::AccelGroup::disconnect
321           Where a GClosure is wanted by the C stuff, a perl subroutine
322           reference suffices.  However, because of this, there are a few
323           subtle differences in semantics.  a GClosure may be connected to
324           only one GtkAccelGroup; however, a perl subroutine may be connected
325           to many GtkAccelGroups (because at the binding level, a new
326           GClosure is created on each call to ->connect).  Thus,
327           $accel_group->disconnect will disconnect the first group it finds
328           to be connected to the given perl subroutine.  To disconnect all
329           groups attached to a subroutine, you can call disconnect with the
330           same subroutine reference (or name) until it stops returning true.
331
332       Gtk2::Clipboard::set_with_data
333       Gtk2::Clipboard::set_with_owner
334           In C, these functions take an array of GtkTargetEntries and the
335           number of elements in that array as the second and third
336           parameters.  In Perl, the number of target entries is implied by
337           the number of items on the stack, and the target entries are
338           supplied as a list at the end of the parameter list:
339
340            $clipboard->set_with_data (\&get_func, \&clear_func, $user_data,
341                                       @target_entries);
342            $clipboard->set_with_owner (\&get_func, \&clear_func, $owner,
343                                        @target_entries);
344

SEE ALSO

346       The canonical documentation is the C API reference at
347       http://developer.gnome.org/doc/API/gtk/ and
348       http://developer.gnome.org/doc/API/gdk/
349
350       Gtk2 includes a full suite of automatically-generated API reference POD
351       for the Perl API -- see Gtk2::index for the starting point.
352
353       There should be a similar document for Glib --- link to it here when it
354       exists.
355

AUTHOR

357       muppet <scott at asofyet dot org>
358
360       Copyright (C) 2003, 2009 by the gtk2-perl team (see the file AUTHORS
361       for the full list)
362
363       This library is free software; you can redistribute it and/or modify it
364       under the terms of the GNU Library General Public License as published
365       by the Free Software Foundation; either version 2.1 of the License, or
366       (at your option) any later version.
367
368       This library is distributed in the hope that it will be useful, but
369       WITHOUT ANY WARRANTY; without even the implied warranty of
370       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
371       Library General Public License for more details.
372
373       You should have received a copy of the GNU Library General Public
374       License along with this library; if not, write to the Free Software
375       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
376       02110-1301  USA.
377
378
379
380perl v5.32.1                      2021-01-27                      Gtk2::api(3)
Impressum