Providing GActions in a library

Yes, it’s possible to provide GActions in a library, to have more code re-use across similar applications (a recurrent topic on this blog and the work that I do in GNOME).

Tepl (Text editor product line) provides GActions in its public API. It’s nothing new, it’s been there since several years, but at the time when I added those GActions in Tepl I remember that I was quite excited with the achievement 🙂 Let’s take a quick look.

GActions in a library

GAction represents an action that the user can do in an application, it’s usually present in a menu item or a button. It’s not just a function to launch, it’s a little more involved than that.

Overall, providing GActions in a library can be done quite naturally, once the library provides a framework for the application.

TeplApplication and TeplApplicationWindow both provide GActions in their public API. They are namespaced with the "tepl-" prefix, to avoid conflicts with other libraries or the application; so the full name of the GActions are "app.tepl-something" or "win.tepl-something". And all the GActions are documented in the class description.

Note that TeplApplication and TeplApplicationWindow are not subclasses of GtkApplication and GtkApplicationWindow, because several libraries might want to extend those GTK classes and an application needs to be able to use all those extensions at the same time. A nice solution that doesn’t require to hold a new object in the application: use this design pattern that I’ve already described on my blog.

Sharing best-practices

If you know or if you’ve implemented kinda the same in another library, I’m interested to hear about it. To see how it’s handled elsewhere, to have more code examples to be inspired by.

Next topic

Providing GSettings in a library. Done in another project. Topic for a next blog post 😉

2 thoughts on “Providing GActions in a library”

  1. One thing I’ve been doing in many places is to implement GActionGroup from widgets so that it doesn’t require traversing to the root to activating actions. It’s also handy when dealing with multi-document interfaces.

    Of course, because it’s all macros it only works from C.

    https://gitlab.gnome.org/GNOME/libdazzle/blob/master/src/actions/dzl-action-group.h

    The other thing that is sort of annoying in GTK 3 is that adding the group to the GtkActionMuxer takes an extra reference. In GTK 4, this will be much nicer since you can install actions on the GtkWidgetClass directly.

Leave a Reply

Your email address will not be published. Required fields are marked *