1api(3)                User Contributed Perl Documentation               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 pre‐
13       dictable 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 prin‐
16       ciples.
17

DESCRIPTION

19       The canonical documentation is the C API reference at http://devel
20       oper.gnome.org/doc/API/gtk/ and http://developer.gnome.org/doc/API/gdk/
21
22       There are two main sections: 'BINDING BASICS' describes the principles
23       on which the bindings work; understanding these can lead you to guess
24       the proper syntax to use for any given function described in the C API
25       reference.  The second section lists various specific points of differ‐
26       ence which don't necessarily correspond with what you expect; this sec‐
27       tion is in three main parts: missing methods, renamed methods, and dif‐
28       ferent call signatures.
29

BINDING BASICS

31       We avoid deprecated APIs.  Many functions refer to C concepts which are
32       alien to the bindings.  Many things have replacements.
33
34       Deprecated Stuff Isn't Bound
35
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 Gtk‐
38       Text 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 circum‐
41       stances.  If you really need access to these old widgets, search the
42       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
52       The namespaces of the C libraries are mapped to perl packages according
53       to scope, although in some cases the distinction may seem rather arbi‐
54       trary:
55
56        g_ => Glib  (the Glib module - distributed separately)
57        gtk_ => Gtk2
58        gdk_ => Gtk2::Gdk
59        gdk_pixbuf_ => Gtk2::Gdk::Pixbuf
60        pango_ => Gtk2::Pango
61
62       Objects get their own namespaces, in a way, as the concept of the GType
63       is completely replaced in the perl bindings by the perl package name.
64       This goes for GBoxed, GObject, and even things like Glib::String and
65       Glib::Int (which are needed for specifying column types in the
66       Gtk2::TreeModel).  (Flags and enums are special -- see below.)
67
68        GtkButton => Gtk2::Button
69        GdkPixbuf => Gtk2::Gdk::Pixbuf
70        GtkScrolledWindow => Gtk2::ScrolledWindow
71        PangoFontDescription => Gtk2::Pango::FontDescription
72
73       With this package mapping and perl's built-in method lookup, the bind‐
74       ings can do object casting for you.  This gives us a rather comfortably
75       object-oriented syntax, using normal perl syntax semantics:
76
77         in C:
78           GtkWidget * b;
79           b = gtk_check_button_new_with_mnemonic ("_Something");
80           gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (b), TRUE);
81           gtk_widget_show (b);
82
83         in perl:
84           my $b = Gtk2::CheckButton->new ('_Something');
85           $b->set_active (1);
86           $b->show;
87
88       You see from this that constructors for most widgets which allow
89       mnemonics will use mnemonics by default in their "new" methods.  For
90       those who don't guess this right off, Gtk2::Button->new_with_mnemonic
91       is also available.  Cast macros are not necessary, and your code is a
92       lot shorter.
93
94       Flags and Enums
95
96       Constants are handled as strings, because it's much more readable than
97       numbers, and because it's automagical thanks to the GType system.  Con‐
98       stants are referred to by their nicknames; basically, strip the common
99       prefix, lower-case it, and optionally convert '_' to '-':
100
101         GTK_WINDOW_TOPLEVEL => 'toplevel'
102         GTK_BUTTONS_OK_CANCEL => 'ok-cancel' (or 'ok_cancel')
103
104       Flags are a special case.  You can't (sensibly) bitwise-or these
105       string-constants, so you provide a reference to an array of them
106       instead.  Anonymous arrays are useful here, and an empty anonymous
107       array is a simple way to say 'no flags'.
108
109         FOO_BAR_BAZ ⎪ FOO_BAR_QUU ⎪ FOO_BAR_QUUX => [qw/baz quu qux/]
110         0 => []
111
112       In some cases you need to see if a bit is set in a bitfield; methods
113       returning flags therefore return an overloaded object.  See Glib for
114       more details on which operations are allowed on these flag objects, but
115       here is a quick example:
116
117        in C:
118         /* event->state is a bitfield */
119         if (event->state & GDK_CONTROL_MASK) g_printerr ("control was down\n");
120
121        in perl:
122         # $event->state is a special object
123         warn "control was down\n" if $event->state & "control-mask";
124
125       But this also works:
126
127         warn "control was down\n" if $event->state * "control-mask";
128         warn "control was down\n" if $event->state >= "control-mask";
129         warn "control and shift were down\n"
130                                   if $event->state >= ["control-mask", "shift-mask"];
131
132       And treating it as an array of strings (as in older versions) is still
133       supported:
134
135         warn "control was down\n" if grep /control-mask/, @{ $event->state };
136
137       The gtk stock item stuff is a little different -- the GTK_STOCK_* con‐
138       stants are actually macros which evaluate to strings, so they aren't
139       handled by the mechanism described above; you just specify the string,
140       e.g., GTK_STOCK_OK => 'gtk-ok'. The full list of stock items can be
141       found at http://devel
142       oper.gnome.org/doc/API/2.0/gtk/gtk-Stock-Items.html
143
144       Memory Handling
145
146       The functions for ref'ing and unref'ing objects and free'ing boxed
147       structures are not even mapped to perl, because it's all handled
148       automagically by the bindings.  I could write a treatise on how we're
149       handling reference counts and object lifetimes, but all you need to
150       know as perl developer is that it's handled for you, and the object
151       will be alive so long as you have a perl scalar pointing to it or the
152       object is referenced in another way, e.g. from a container.
153
154       Miscellaneous
155
156       In C you can only return one value from a function, and it is a common
157       practice to modify pointers passed in to simulate returning multiple
158       values.  In perl, you can return lists; any functions which modify
159       arguments have been changed to return them instead.  A common idiom in
160       gtk is returning gboolean, and modifying several arguments if the func‐
161       tion returns TRUE; for such functions, the perl wrapper just returns an
162       empty list on failure.
163
164         in C:  foo_get_baz_and_quux (foo, &baz, &quux);
165         in perl:  ($baz, $quux) = $foo->get_baz_and_quux;
166
167       Most things that take or return a GList, GSList, or array of values
168       will use native perl arrays (or the argument stack) instead.
169
170       You don't need to specify string lengths, although string length param‐
171       eters should still be available for functions dealing with binary
172       strings. You can always use "substr" to pass different parts of a
173       string.
174
175       Anything that uses GError in C will "croak" on failure, setting $@ to a
176       magical exception object, which is overloaded to print as the returned
177       error message.  The ideology here is that GError is to be used for run‐
178       time exceptions, and "croak" is how you do that in perl.  You can catch
179       a croak very easily by wrapping the function in an eval:
180
181          eval {
182             my $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file ($filename);
183             $image->set_from_pixbuf ($pixbuf);
184          };
185          if ($@) {
186             print "$@\n"; # prints the possibly-localized error message
187             if (Glib::Error::matches ($@, 'Gtk2::Gdk::Pixbuf::Error',
188                                           'unknown-format')) {
189                change_format_and_try_again ();
190             } elsif (Glib::Error::matches ($@, 'Glib::File::Error', 'noent')) {
191                change_source_dir_and_try_again ();
192             } else {
193                # don't know how to handle this
194                die $@;
195             }
196          }
197
198       This has the added advantage of letting you bunch things together as
199       you would with a try/throw/catch block in C++ -- you get cleaner code.
200       By using Glib::Error exception objects, you don't have to rely on
201       string matching on a possibly localized error message; you can match
202       errors by explicit and predictable conditions.  See Glib::Error for
203       more information.
204
205       Use normal perl callback/closure tricks with callbacks.  The most com‐
206       mon use you'll have for callbacks is with the Glib signal_connect
207       method:
208
209         $widget->signal_connect (event => \&event_handler, $user_data);
210         $button->signal_connect (clicked => sub { warn "hi!\n" });
211
212       Note that the $user_data is optional, and with perl closures, you don't
213       often need it.
214
215       A major change from gtk-perl (the bindings for Gtk+-1.x) is that call‐
216       backs take their arguments in the order proscribed by the C documenta‐
217       tion, and only one value is available for user data.  gtk-perl allowed
218       you to pass multiple values for user_data, and always brought in the
219       user_data immediately after the instance reference; this proved to be
220       rather confusing, and did not follow the C API reference, so we decided
221       not to do that for gtk2-perl.
222

MISSING METHODS

224       g_object_ref   => no replacement
225       g_object_unref => no replacement
226       g_boxed_free   => no replacement
227           The bindings do automatic memory management. You should never need
228           to use these.
229
230       gtk_timeout_add    => Glib::Timeout->add
231       gtk_timeout_remove => Glib::Source->remove
232       gtk_idle_add       => Glib::Idle->add
233       gtk_idle_remove    => Glib::Source->remove
234       gtk_input_add      => Glib::IO->add_watch
235       gtk_input_remove   => Glib::Source->remove
236           The gtk_* functions are deprecated in favor of the g_* ones.
237           Gtk2::Helper has a wrapper for Glib::IO->add_watch which makes it
238           behave more like gtk_input_add.
239
240       gtk_accel_group_from_accel_closure => no replacement
241           Because of the use of Perl subroutine references in place of GClo‐
242           sures, there is no way to preserve at the Perl level the one-to-one
243           mapping between GtkAccelGroups and GClosures.  Without that map‐
244           ping, this function is useless.
245

RENAMED METHODS

247       gtk_aspect_frame_set     => $aspect_frame->set_params
248           Avoid a clash with $gobject->set.
249

DIFFERENT CALL SIGNATURES OR SEMANTICS

251       As a general rule function that take a pair of parameters, a list and
252       the number of elements in that list, will normally omit the number of
253       elements and just accept a variable number of arguments that will be
254       converted into the list and number of elements.  In many instances
255       parameters have been reordered so that this will work.  See below for
256       exceptions and specific cases that are not detailed in the generated
257       Perl API reference.
258
259       Gtk2::ScrollBar vs. GtkScrollbar
260           These classes were incorrectly written with a capital "B" in ver‐
261           sion 1.00 and below.  They have been renamed in version 1.01 and
262           the old way to write them is deprecated, but supported.
263
264       Gtk2::ItemFactory::create_items
265           The n_entries parameter has been ommited and callback_data is
266           accepted as the first parameter. All parameters after that are con‐
267           sidered to be entries.
268
269       Gtk2::List::insert_items
270           Position and items parameters flipped order so that an open ended
271           parameter list could be used. "$list->insert_items($position,
272           $item1, $item2, ...)"  (Note that GtkList and GtkListItem are dep‐
273           recated and only included because GtkCombo still makes use of them,
274           they are subject to removal at any point so you should not utilize
275           them unless absolutely necessary.)
276
277       Gtk2::Notebook::append_page
278       Gtk2::Notebook::prepend_page
279       Gtk2::Notebook::insert_page
280           The C API for these functions requires a GtkWidget for the
281           tab_label, since you can set any widget you like to be the tab
282           label.  However, the most common use is a plain Gtk2::Label; so
283           these three functions will stringify anything passed to tab_label
284           that's not a GtkWidget and wrap a Gtk2::Label around it for you.
285
286           Note that the "_menu" versions of these functions do not do this.
287
288       Gtk2::AccelGroup::connect
289       Gtk2::AccelGroup::disconnect
290           Where a GClosure is wanted by the C stuff, a perl subroutine refer‐
291           ence suffices.  However, because of this, there are a few subtle
292           differences in sematics.  a GClosure may be connected to only one
293           GtkAccelGroup; however, a perl subroutine may be connected to many
294           GtkAccelGroups (because at the binding level, a new GClosure is
295           created on each call to ->connect).  Thus, $accel_group->disconnect
296           will disconnect the first group it finds to be connected to the
297           given perl subroutine.  To disconnect all groups attached to a sub‐
298           routine, you can call disconnect with the same subroutine reference
299           (or name) until it stops returning true.
300
301       Gtk2::Clipboard::set_with_data
302       Gtk2::Clipboard::set_with_owner
303           In C, these functions take an array of GtkTargetEntries and the
304           number of elements in that array as the second and third parame‐
305           ters.  In Perl, the number of target entries is implied by the num‐
306           ber of items on the stack, and the target entries are supplied as a
307           list at the end of the parameter list:
308
309            $clipboard->set_with_data (\&get_func, \&clear_func, $user_data,
310                                       @target_entries);
311            $clipboard->set_with_owner (\&get_func, \&clear_func, $owner,
312                                        @target_entries);
313

SEE ALSO

315       The canonical documentation is the C API reference at http://devel
316       oper.gnome.org/doc/API/gtk/ and http://developer.gnome.org/doc/API/gdk/
317
318       Gtk2 includes a full suite of automatically-generated API reference POD
319       for the Perl API -- see Gtk2::index for the starting point.
320
321       There should be a similar document for Glib --- link to it here when it
322       exists.
323

AUTHOR

325       muppet <scott at asofyet dot org>
326
328       Copyright (C) 2003 by the gtk2-perl team (see the file AUTHORS for the
329       full list)
330
331       This library is free software; you can redistribute it and/or modify it
332       under the terms of the GNU Library General Public License as published
333       by the Free Software Foundation; either version 2.1 of the License, or
334       (at your option) any later version.
335
336       This library is distributed in the hope that it will be useful, but
337       WITHOUT ANY WARRANTY; without even the implied warranty of MER‐
338       CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library
339       General Public License for more details.
340
341       You should have received a copy of the GNU Library General Public
342       License along with this library; if not, write to the Free Software
343       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307
344       USA.
345
346
347
348perl v5.8.8                       2007-03-18                            api(3)
Impressum