Debian Codegraph @

docs/devguide/introspection_porting.rst

raw
1 ============================
2 Introspection Porting Guide
3 ============================
4
5 .. attention::
6 The pygtkcompat package has been deprecated since PyGObject 3.48.
7 The functionality has been removed since PyGObject 3.52.
8
9 .. contents::
10 :local:
11
12 Beginning
13 =========
14
15 Starting with PyGObject 3.1.92 there's a module called pygtkcompat which will make it easier to
16 port an application from PyGTK.
17
18 There are two different approaches to porting your application from PyGTK to gobject-introspection:
19
20 1. Using a PyGTK compatibility layer (pygtkcompat)
21 2. Using a shell script which converts the callsites (``pygi-convert.sh``)
22
23 There are advantages and disadvantages with both:
24
25 1. Using pygtkcompat makes it possible to focus on porting to Gtk 3.x while not changing anything
26 else, users and developers can keep on using the software as before.
27 2. Using pygtkcompat allows you to support both Gtk 2.x and Gtk 3.x with the same code base
28 3. Using ``pygi-convert.sh`` you can avoid using any layers and use the supported API directly
29
30 Using pygtkcompat
31 -----------------
32
33 The pygtkcompat module provides a PyGTK compatible API on top of gobject-introspection which makes
34 it possible to run your application on top of **both** PyGTK and gobject-introspection at the same
35 time.
36
37 Before using it you should port your application to using latest API, available 2.24, for instance::
38
39 widget.window should be widget.get_window()
40 container.child should be container.get_child()
41 widget.flags() & gtk.REALIZED should be container.get_realized()
42
43 and so on.
44
45 Once an application has been updated to the latest PyGTK API, you can then import pygtkcompat and
46 enable the parts you need. For instance, to enable PyGTK compatible API on top of the Gtk 3.0
47 typelib, use the following:
48
49 .. code-block:: python
50
51 from gi import pygtkcompat
52
53 pygtkcompat.enable()
54 pygtkcompat.enable_gtk(version='3.0')
55
56 That's it, if you're lucky enough and you're not using any strange/weird apis you should be able
57 to run your application. If you want an app to be compatible with both PyGTK and PyGI, you can use
58 the following technique:
59
60 .. code-block:: python
61
62 try:
63 from gi import pygtkcompat
64 except ImportError:
65 pygtkcompat = None
66
67 if pygtkcompat is not None:
68 pygtkcompat.enable()
69 pygtkcompat.enable_gtk(version='3.0')
70
71 import gtk
72
73 .. note::
74
75 Porting the application from 2 to 3 is best covered in
76 https://docs.gtk.org/gtk3/migrating-2to3.html. That usually includes things
77 such as change expose-event to draw and do drawing with cairo.
78
79 How does PyGI work?
80 ===================
81
82 Initial GI support was added to pygobject in version 2.19.0 (August 2009), but the entire
83 GI/pygobject/annotations stack really only stabilized in version 2.28, so that in practice you
84 will need at least this version and the corresponding latest upstream releases of GTK and other
85 libraries you want to use.
86
87 pygobject provides a ``gi.repository`` module namespace which generates virtual Python modules
88 from installed typelibs on the fly. For example, if you have the GIR for GTK 3 installed, you
89 can do:
90
91 .. code-block:: console
92
93 $ python -c 'from gi.repository import Gtk; print Gtk'
94 <gi.module.DynamicModule 'Gtk' from '/usr/lib/girepository-1.0/Gtk-3.0.typelib'>
95
96 and use it just like any other Python module.
97
98 Absolutely unexpected first example:
99
100 .. code-block:: console
101
102 $ python -c 'from gi.repository import Gtk; Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, "Hello World").run()'
103
104 Let's look at the corresponding C declaration:
105
106 .. code-block:: c
107
108 GtkWidget* gtk_message_dialog_new (GtkWindow *parent, GtkDialogFlags flags, GtkMessageType type, GtkButtonsType buttons, const gchar *message_format, ...);
109
110 and the C call:
111
112 .. code-block:: c
113
114 GtkMessageDialog* msg = gtk_message_dialog_new (NULL, 0, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "Hello World");
115 msg.run()
116
117 So what do we see here?
118
119 1. The C API by and large remains valid in Python (and other languages using the GI bindings),
120 in particular the structure, order, and data types of arguments. There are a few exceptions
121 which are mostly due to the different way Python works, and in some cases to make it easier to
122 write code in Python; see below for details. But this means that you can (and should) use the
123 normal API documentation for the C API of the library. Devhelp is your friend!
124
125 2. As Python is a proper object oriented language, pygobject (and in fact the GI typelib already)
126 expose a GObject API as proper classes, objects, methods, and attributes. I. e. in Python you
127 write
128
129 .. code-block:: python
130
131 button = Gtk.Button()
132 button.set_label("foo")
133
134 instead of the C gobject syntax
135
136 .. code-block:: c
137
138 GtkWidget* button = gtk_button_new(...);
139 gtk_button_set_label(button, "foo");
140
141 The class names in the typelib (and thus in Python) are derived from the actual class names
142 stated in the C library (like ``GtkButton``), except that the common namespace prefix (``Gtk``
143 here) is stripped, as it becomes the name of the module.
144
145 3. Global constants would be a heavy namespace clutter in Python, and thus pygobject exposes them
146 in a namespaced fashion as well. I. e. if the ``MessageDialog`` constructor expects a constant
147 of type ``GtkMessageType``, then by above namespace split this becomes a Python class
148 ``Gtk.MessageType`` with the individual constants as attributes, e. g. ``Gtk.MessageType.INFO``.
149
150 4. Data types are converted in a rather obvious fashion. E. g. when the C API expects an ``int*``
151 array pointer, you can supply a normal Python array ``[0, 1, 2]``. A Python string ``"foo"``
152 will match a ``gchar*``, Pythons ``None`` matches ``NULL``, etc. So the GObject API actually
153 translates quite naturally into a real OO language like Python, and after some time of getting
154 used to above transformation rules, you should have no trouble translating the C API
155 documentation into their Python equivalents. When in doubt, you can always look for the precise
156 names, data types, etc. in the .gir instead, which shows the API broken by class, method, enum,
157 etc, with the exact names and namespaces as they are exposed in Python.
158
159 As I mentioned above, this is in no way restricted to GTK, GNOME, or UI. For example, if you
160 handle any kind of hardware and hotplugging, you almost certainly want to query udev, which
161 provides a nice glib integration (with signals) through the gudev library. This example lists all
162 block devices (i. e. hard drives, USB sticks, etc.):
163
164 .. code-block:: pycon
165
166 >>> from gi.repository import GUdev
167 >>> c = GUdev.Client()
168 >>> for dev in c.query_by_subsystem("block"):
169 ... print dev.get_device_file()
170 ...
171 /dev/sda
172 /dev/sda1
173 /dev/sda2
174 [...]
175
176 See `the GUDevClient documentation
177 <http://www.kernel.org/pub/linux/utils/kernel/hotplug/gudev/GUdevClient.html#g-udev-client-query-by-subsystem>`_
178 for the corresponding C API. GI is not even restricted to GObject, you can annotate any non-OO
179 function based API with it. E. g. there is already a ``/usr/share/gir-1.0/xlib-2.0.gir``
180 (although it's horribly incomplete). These will behave as normal functions in Python (or other
181 languages) as well.
182
183 Differences to the C API
184 ========================
185
186 The structure of method arguments is by and large the same in C and in GI/Python. There are some
187 notable exceptions which you must be aware of:
188
189 Constructors
190 ------------
191
192 The biggest one is constructors. There is actually two ways of calling one:
193
194 * Use the real constructor implementation from the library. Unlike in normal Python you need to
195 explicitly specify the constructor name:
196
197 .. code-block:: python
198
199 Gtk.Button.new()
200 Gtk.Button.new_with_label("foo")
201
202 * Use the standard GObject constructor and pass in the initial property values as named arguments:
203
204 .. code-block:: python
205
206 Gtk.Button(label="foo", use_underline=True)
207
208 The second is actually the recommended one, as it makes the meaning of the arguments more explicit,
209 and also underlines the GObject best practice that a constructor should do nothing more than to
210 initialize properties. But otherwise it's pretty much a matter of taste which one you use.
211
212 Passing arrays
213 --------------
214
215 Unlike C, higher level languages know how long an array is, while in the C API you need to specify
216 that explicitly, either by terminating them with ``NULL`` or explicitly giving the length of the
217 array in a separate argument. Which one is used is already specified in the annotations and thus
218 in the typelib, so Python can automatically provide the right format without the developer needing
219 to append an extra ``None`` or a separate len(my_array) argument.
220
221 For example, in C you have
222
223 .. code-block:: c
224
225 gtk_icon_theme_set_search_path (GtkIconTheme *icon_theme, const gchar *path[], gint n_elements)
226
227 In Python you can just call this as
228
229 .. code-block:: python
230
231 my_icon_theme.set_search_path(['/foo', '/bar'])
232
233 and don't need to worry about the array size.
234
235 Output arguments
236 ----------------
237
238 C functions can't return more than one argument, so they often use pointers which the function
239 then fills out. Conversely, Python doesn't know about pointers, but can easily return more than
240 one value as a tuple. The annotations already describe which arguments are "out" arguments, so in
241 Python they become part of the return tuple: first one is the "real" return value, and then all
242 out arguments in the same order as they appear in the declaration. For example:
243
244 .. code-block:: c
245
246 GdkWindow* gdk_window_get_pointer (GdkWindow *window, gint *x, gint *y, GdkModifierType *mask)
247
248 In Python you would call this like
249
250 .. code-block:: python
251
252 x, y, mask = mywindow.get_pointer()
253
254 The Python help system shows the correct input, output and return argument expectations:
255
256 .. code-block:: pycon
257
258 >>> from gi.repository import Gdk
259 >>> help(Gdk.Window.get_pointer)
260 Help on function get_pointer:
261
262 get_pointer(*args, **kwargs)
263 get_pointer(self) -> x:int, y:int, mask:Gdk.ModifierType
264
265 GDestroyNotify
266 --------------
267
268 Some GLib/GTK functions take a callback method and an extra ``user_data`` argument that is passed
269 to the callback. In C they often also take a ``GDestroyNotify`` function which is run once all
270 callbacks are done, in order to free the memory of user_data. As Python has automatic memory
271 management, pygobject will take care of all this by itself, so you simply don't specify the
272 GDestroyNotify argument. For example:
273
274 .. code-block:: c
275
276 void gtk_enumerate_printers (GtkPrinterFunc func, gpointer user_data, GDestroyNotify destroy, gboolean wait)
277
278 In Python you call this as
279
280 .. code-block:: python
281
282 Gtk.enumerate_printers(my_callback, my_user_data, True)
283
284 Non-introspectable functions/methods
285 ------------------------------------
286
287 When you work with PyGI for a longer time, you'll inevitably stumble over a method that simply
288 doesn't exist in the bindings. These usually are marked with ``introspectable="0"`` in the GIR.
289
290 In the best case this is because there are some missing annotations in the library which don't
291 have a safe default, so GI disables these to prevent crashes. They usually come along with a
292 corresponding warning message from g-ir-scanner, and it's usually quite easy to fix these.
293
294 Another common case are functions which take a variable number of arguments, such as
295 ``gtk_cell_area_add_with_properties()``. Varargs cannot be handled safely by libgirepository. In
296 these cases there are often alternatives available (such as ``gtk_cell_area_cell_set_property()``).
297 For other cases libraries now often have a ``..._v()`` counterpart which takes a list instead of
298 variable arguments.
299
300 Threads
301 =======
302
303 For using threads with PyGObject, please see: `Threads/Concurrency with Python and the GNOME
304 Platform <./Projects(2f)PyGObject(2f)Threading.html>`_
305
306 Overrides
307 =========
308
309 A specialty of pygobject is the possibility of replacing functions, methods, or classes of the
310 introspected library with custom code, called "overrides". As the goal is to stay very close to
311 the original API, they should be used and written sparsely, though. One major use case is to
312 provide replacements for unintrospectable methods. For example, ``Gtk.Menu.popup()`` is not
313 introspectable in GTK, but the GTK override implements this method in terms of
314 ``Gtk.Menu.popup_for_device()``, so in this case the override actually helps to get closer to the
315 original API again. Another important case is automatic data type conversion, most prominently to
316 allow passing unicode objects to methods which expect an UTF-8 encoded ``gchar*``. This also
317 actually helps to prevent workarounds in application code and maintain a clean API. Thirdly,
318 overrides are useful if they help to massively ease development. For example it is quite laborious
319 to do GDBus calls or GVariant constructions with the native Gio/GLib API. pygobject offers
320 convenience overrides to make these a lot simpler and more Pythonic, but of course without
321 actually breaking the original API.
322
323 Overrides should be quite easy to understand. In general you should not even be required to know
324 about it, as most of them really just fix stuff to work as expected. :-)
325
326 Porting from PyGTK 2 to PyGI GTK 3
327 ===================================
328
329 Note that this is really two migrations in one step, but is recommended as GTK2 still has a lot of
330 breakage with PyGI. It is recommended to port applications to PyGI/GTK+ 3 first, then port to
331 Python 3 as an additional step if Python 3 support is desired. Otherwise you can end up with a
332 conflated and hard to track set of changes. See the `GTK2 → GTK3 migration documentation
333 <https://docs.gtk.org/gtk3/migrating-2to3.html>`_.
334
335 If we compare the PyGTK vs. PyGI code for a "Hello" message box, we see that it's actually very
336 similar in structure:
337
338 .. code-block:: console
339
340 $ python -c 'import gtk; gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, "Hello World").run()'
341
342 vs.
343
344 .. code-block:: console
345
346 $ python -c 'from gi.repository import Gtk; Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, "Hello World").run()'
347
348 So PyGTK also does the representation of the C functions as proper classes and methods, thus if
349 you port from PyGTK to PyGI, the structure by and large remains the same.
350
351 Step 1: The Great Renaming
352 --------------------------
353
354 The biggest part in terms of volume of code changed is basically just a renaming exercise. E. g.
355 ``gtk.*`` now becomes ``Gtk.*``, and ``gtk.MESSAGE_INFO`` becomes ``Gtk.MessageType.INFO``.
356 Likewise, the imports need to be updated: ``import gtk`` becomes ``from gi.repository import Gtk``.
357
358 Fortunately this is is a mechanical task which can be automated. The `pygobject git tree
359 <https://gitlab.gnome.org/GNOME/pygobject>`_ has a script `pygi-convert.sh
360 <https://gitlab.gnome.org/GNOME/pygobject/blob/master/tools/pygi-convert.sh>`_ which is a long
361 list of perl -pe 's/old/new/' string replacements.
362
363 It's really blunt, but surprisingly effective, and for small applications chances are that it will
364 already produce something which actually runs. Note that this script is in no way finished, and
365 should be considered a collaborative effort amongst porters. So if you have something which should
366 be added there, please don't hesitate to open a bug or ping on IRC (#python on irc.gnome.org)).
367 We will be happy to improve the script.
368
369 When you just run ``pygi-convert.sh`` in your project tree, it will work on all ``*.py`` files.
370 If you have other Python code there which is named differently (such as ``bin/myprogram``), you
371 should run it once more with all these file names as argument.
372
373 * Make sure you don't keep using the static bindings for a library that we are using through
374 introspection. That would cause wrappers from both bindings be mixed and compatibility issues
375 would arise.
376
377 Step 2: Wash, rinse, repeat
378 ---------------------------
379
380 Once the mechanical renamings are out of the way, the tedious and laborious part starts. As Python
381 does not have a concept of "compile-time check" and can't even check that called methods exist or
382 that you pass the right number of parameters, you now have to enter a loop of "start your
383 program", "click around until it breaks", "fix it", "goto 1".
384
385 The necessary changes here are really hard to generalize, as they highly depend on what your
386 program actually does, and this will also involve the GTK 2 → 3 parts. One thing that comes up a
387 lot are ``pack_start()``/``pack_end()`` calls. In PyGTK they have default values for ``expand``,
388 ``start``, and ``padding`` attributes, but as GTK does not have them, you won't have them in PyGI
389 either (see `bgo#558620 - Add default values
390 <https://bugzilla.gnome.org/show_bug.cgi?id=558620>`_).
391
392 .. warning::
393
394 Note that you can't do a migration halfway: If you try to import both ``gtk`` and
395 ``gi.repository.Gtk``, you'll get nothing but program hangs and crashes, as you are trying to
396 work with the same library in two different ways. You can mix static and GI bindings of
397 *different* libraries though, such as ``dbus-python`` and ``gi.repository.Gtk``.
398
399 If your application uses plugins, you can use libpeas. It is a GObject plugins library that
400 support C, Python and Javascript languages though introspection.
401
402 Step 3: Packaging changes
403 -------------------------
404
405 After you have your code running with PyGI and committed it to your branch and released it, you
406 need to update the dependencies of your distro package for PyGI. You should grep your code for
407 "gi.repository" and collect a list of all imported typelibs, and then translate them into the
408 appropriate package name. For example, if you import "Gtk, Notify, Gudev" you need to add
409 dependencies to the packages which ship them:
410
411 * Debian/Ubuntu ship them in separate packages named ``gir<GI_ABI_version>-<libraryname>-<library_ABI_version>``,
412 so in this example ``gir1.2-gtk-3.0``, ``gir1.2-notify-0.7``, and ``gir1.2-gudev-1.0``. You
413 can find out with e. g. ``dpkg -S /usr/lib/girepository-1.0/Gtk-3.0.typelib``.
414 * Fedora ships the typelibs together with the shared libraries, so in this example ``gtk3``,
415 ``libgudev1``, ``libnotify``. You can find out with e. g.
416 ``rpm -qf /usr/lib/girepository-1.0/Gtk-3.0.typelib``.
417
418 At the same time you should drop the old static bindings, like python-gtk2, python-notify, etc.
419
420 Finally you should also bump the version of the pygobject dependency to (>= 2.28) to ensure that
421 you run with a reasonably bug free PyGI.
422
423 Examples
424 ========
425
426 * pygobject's git tree has a very comprehensive `gtk-demo
427 <https://gitlab.gnome.org/GNOME/pygobject/tree/master/examples/demo>`_ showing off pretty much
428 all available GTK widgets in PyGI
429 * Examples of previously done pygtk → pyGI ports:
430
431 * Apport: http://bazaar.launchpad.net/~apport-hackers/apport/trunk/revision/1801
432 * Jockey: http://bazaar.launchpad.net/~jockey-hackers/jockey/trunk/revision/679
433 * system-config-printer: https://git.fedorahosted.org/cgit/system-config-printer.git/log/?h=pygi
434 * gtimelog: http://bazaar.launchpad.net/~gtimelog-dev/gtimelog/trunk/revision/181 (this is
435 interesting because it makes the code work with *both* PyGTK and PyGI, whichever is available)
436
437 Comments
438 ========
439
440 * What versions of the python packages do we need, and how do we get the for different
441 distributions (gentoo, deb-based, rpm-based...?)
442 * Can we just fallback to import gtk, gdk.... if we detect old enough python packages, or do we
443 need to perform other workarounds?
444
445 One of the biggest challenges in porting is that all of the constants have changed names. The
446 above ``pygi-convert.sh`` script gives a good idea about what the new names are, but if you have
447 any problems, refer to the relevant .gir file directly. For example, if your old code says
448 "gtk.TREE_VIEW_COLUMN_AUTOSIZE" and you're not sure what the new code should be, search in
449 /usr/share/gir-1.0/Gtk-2.0.gir for "COLUMN_AUTOSIZE", and you'll find some code that looks like
450 this:
451
452 .. code-block:: xml
453
454 <enumeration name="TreeViewColumnSizing"
455 glib:type-name="GtkTreeViewColumnSizing"
456 glib:get-type="gtk_tree_view_column_sizing_get_type"
457 c:type="GtkTreeViewColumnSizing">
458 <member name="grow_only"
459 value="0"
460 c:identifier="GTK_TREE_VIEW_COLUMN_GROW_ONLY"
461 glib:nick="grow-only"/>
462 <member name="autosize"
463 value="1"
464 c:identifier="GTK_TREE_VIEW_COLUMN_AUTOSIZE"
465 glib:nick="autosize"/>
466 <member name="fixed"
467 value="2"
468 c:identifier="GTK_TREE_VIEW_COLUMN_FIXED"
469 glib:nick="fixed"/>
470 </enumeration>
471
472 Looking at that, you can determine the new constant name. It starts with "Gtk", then a period,
473 then the enumeration name ("TreeViewColumnSizing"), then another period, then the member name in
474 ALL CAPS ("AUTOSIZE"). So, this tells you to change "gtk.TREE_VIEW_COLUMN_AUTOSIZE" into
475 "Gtk.TreeViewColumnSizing.AUTOSIZE"
476
477 Problems
478 ========
479
480 * Listening to signals: if you are listening a signal like "size-allocate" and when you print the
481 allocation you get as the type GdkRectangle instead of CairoRectangleInt, the way to fix it is
482 by overriding the signal instead of listening to it.