GTK 3.99.2

The GTK 3.99.2 release continues the topics from 3.99.1: api cleanup, new and polished demos, better documentation. You can see the details here.

One small note on the topic of documentation is that we are relying on some unreleased gtk-doc features. Therefore, we now include gtk-doc as a subproject in the gtk release tarball. If you are a distributor, don’t be surprised that building GTK installs gtk-doc tools now.

The big news in this snapshot is our work on exposing the power of the new GL-based rendering stack a bit more.

Warmup: Shadertoy

gtk4-demo includes a Shadertoy demo now.

The demo using a GtkGLArea widget to run GLSL snipplets that are compatible with the ones found on shadertoy.com. Many of the examples found there will work, if you paste them into the editor of this demo.

This is fun, but somewhat limited. The GLSL is confined to its ‘sandbox’, the GtkGLArea widget, which is using GL api to compile and use the shaders.

Shaders as first-class objects

This is not our first attempt to make a shadertoy lookalike. When we first looked at it, we thought that we would make a shader abstraction that applications could use. We put it to the side when it turned out that making it work across different renderers and backends would require us to write our own shader compiler—too much work.

But after our shadertoy success, we revisited the idea of shaders as first-class objects, with more modest goals: We use GLSL, and don’t attempt to make the shaders work with anything but the OpenGL renderer.

In 3.99.2, we now have:

With these pieces in place, we made a demo that shows various uses of shaders. It is maybe a bit overloaded, and some of the effects are a bit over-the-top, but it gets the point across: you can use shaders in your widgets.

 

What we haven’t done yet is adding widgets that have shader support built-in. The demo showcases a few likely candidates:

A shader paintable. As you may recall, GdkPaintable is a very flexible interface for anything that can ‘paint’. Shaders certainly qualify. The GskShaderPaintable in gtk-demo uses a shader without input textures to just produce pixels, and we add it to a GtkPicture widget to make it appear in the widget tree.

A shader bin. This is a very simple container that can use shaders to draw effects on top of a child widget. It works with shaders that take a single input texture (for the child widget).

A shader stack. This is a stack-like container that shows one of many child widgets, and uses a shader for the transition whenever the visible child changes. It works with shaders that expect two input textures (for the old and new active child).

Thankfully, making custom widgets is a lot easier in GTK 4 than it used to be, so the render node API should be enough to get you started on some fun experiments. You can of course take the gtk4-demo code as a starting point.

You can debug it

Apart from widgets, the shader support is fully integrated. The GTK inspector can handle shader nodes like any other render nodes, you can serialize them and e.g. load the resulting file in gtk4-node-editor:

If you need to see the input that GTK sends to the shader compiler,  setting the environment variable

GDK_DEBUG=shaders

can be helpful.

Whats next?

After this GL adventure we’ll now focus on landing more of the new accessibility infrastructure.

GtkColumnView

One thing that I left unfinished in my recent series on list views and models in GTK 4 is a detailed look at GtkColumnView. This will easily be the most complicated part of the series. We are entering into the heartland of GtkTreeView—anything aiming to replace most its features will be a complicated beast.

Overview

As we did for GtkListView, we’ll start with a high-level overview and with a picture.

If you look back at the listview picture, you’ll remember that we use a list item factory to create a widget for each item in our model that needs to be displayed.

In a column view, we need multiple widgets for each item—one for each column. The way we do this is by giving each column its own list item factory. Whenever we need to display a new item, we combine the widgets from each columns factory into a row for the new item.

Internally, the column view is actually using a list view to hold the rows. This is nice in that all the things I explained in the previous post about item reuse and about how to use list item factories apply just the same.

Of course, some things are different. For example, the column view has organize the size allocation so that the widgets in all rows line up to form proper columns.

Note: Just like GtkListView, the colum view only creates widgets for the segment of the model that is currently in view, so it shares the vertical scalability. The same is not true in the horizontal direction—every row is fully populated with a widget for each column, even if they are out of view to the left or right. So if you add lots of columns, things will get slow.

Titles, and other complications

The column objects contain other data as well, such as titles. The column view is using those to display a header for each column. If the column view is marked as reorderable, you can rearrange the columns by drag-and-drop of the the header widgets. And if the columns are marked as resizable, you can drag the border between two columns to resize them.

If you payed attention, you may now wonder how this resizing goes together with the fact that the cells in the rows can be arbitrary widgets which expect to have at least their minimum size available for drawing their content. The answer is that we are using another new feature of the GTK 4 rendering machinery: Widgets can control how drawing outside their boundaries (by child widgets) is treated, with

 gtk_widget_set_overflow (cell, GTK_OVERFLOW_HIDDEN)

Sorting, selections, and the quest for treeview parity

Since we want to match GtkTreeview, feature-wise, we are not done yet. Another thing that users like to do in tree views is to click on headers, to sort the content by that column. GtkColumnView headers allow this, too.

You may remember from the last post that sorting is done by wrapping your data in a GtkSortListModel, and giving it a suitable sorter object. Since we want to have a different sort order, depending on what column header you clicked, we give each column its own sorter, which you can set with

gtk_column_view_column_set_sorter (column, sorter)

But how do we get the right sorter from the column you just clicked, and attach it to the sort model? Keep in mind that the sort model is not going to be the outmost model that we pass to the column view, since that is always a selection model, so the column view can’t just switch the sorter on the sort list model on its own.

The solution we’ve come up with is to make the column view provide a sorter that internally uses the column sorters, with

gtk_column_view_get_sorter (view)

You can give this sorter to your sort model once, when you set up your model, and then things will automagically updates when the user clicks on column headers to activate different column sorters.

This sounds complicated, but it works surprisingly well. A nice benefit of this approach is that we can actually sort by more than one column at a time—since we have all the column sorters available, and we know which one you clicked last.

Selection handling is easy, by comparison. It works just the same as it does in GtkListView.

Summary

GtkColumnView is a complex widget, but I hope this series of posts will  make it a little easier to start using it.

On list models

In the previous post, I promised to take a deeper look at list models and what GTK 4 offers in this area. Lets start be taking a look at the GListModel interface:

struct _GListModelInterface
{
  GTypeInterface g_iface;

  GType    (* get_item_type) (GListModel *list);
  guint    (* get_n_items)   (GListModel *list);
  gpointer (* get_item)      (GListModel *list,
                              guint       position);
};

An important part of implementing the interface is that you need to emit
the ::items-changed signal when required, using the helper function that
GLib has for this purpose:

void g_list_model_items_changed (GListModel *list,
                                 guint       position,
                                 guint       removed,
                                 guint       added)

A few things to note about this interface:

  • It is very minimal; which makes it easy to implement
  • The API is in terms of positions and only deals with changes in list membership—keeping track of changes to the items themselves is up to you

A list model zoo

GTK ships a sizable collection of list model implementations. Under closer inspection, they fall into several distinct groups.

List model construction kit

The first group is what could be called the list model construction kit: models that let you build new models by modifying or combining models that you already have.

The first model in this group, GtkSliceListModel, take a slice of an existing model, given by an offset and a size, and makes a new model containing just those items. This is useful if you want to present a big list in a paged view—the forward and back buttons will simply increase or decrease the offset by the size. A slice model can also be used to incrementally populate a list, by making the slice bigger over time. GTK is using this technique in some places.

The next model in this group, GtkFlattenListModel, takes several list models and combines them into one. Since this is all about list models, the models to combine are handed to the flatten model in the form of a list model of list models. This is useful whenever you need to combine data from multiple sources, as for example GTK does for the paper sizes in the print dialog.

Paper size list in print dialog
A flattened list

Note that the original models continue to exist behind the flatten model, and their updates will be propagated by the flatten list model, as expected.

Sometimes, you have your data in a list model, but it is not quite in the right form. In this case, you can use a GtkMapListModel replace every item in the original model with different one.

Concrete models

GTK and its dependencies include a number of concrete models for the types of data that we deal with ourselves.

The first example here are Pango objects that are implementing the list model interface for their data: PangoFontMap is a list model of PangoFontFamily objects, and PangoFontFamily is a list model of PangoFontFace objects. The font chooser is using these models.

font chooser dialog
A Pango list model

The next example are the GtkDirectoryList and GtkBookmarkList objects that will be used in the file chooser to represent directory contents and bookmarks. An interesting detail about these is that they both need to do IO to populate their content, and they do it asynchronously to avoid blocking the UI for extended times.

The last model in this group is a little less concrete: GtkStringList is a simple list model wrapper around the all-too-common string arrays. An example where this kind of list model will be frequently used is with GtkDropDown. This is so common that GtkDropDown has a convenience constructor that takes a string array and creates the GtkStringList for you:

GtkWidget *
    gtk_drop_down_new_from_strings (const char * const * strings)

Selection

The next group of models extends GListModel with a new interface: GtkSelectionModel. For each item in the underlying model, a GtkSelectionModel maintains the information whether it is selected or not.

We won’t discuss the interface in detail, since  it is unlikely that you need to implement it yourself, but the most important points are:

gboolean gtk_selection_model_is_selected (GtkSelectionModel *model)
                                          guint              pos)
GtkBitset *
       gtk_selection_model_get_selection (GtkSelectionModel *model)

So you can get the selection information for an individual item, or as a whole, in the form of a bitset. Of course, there is also a ::selection-changed signal that works in a very similar way to the ::items-changed signal of GListModel.

GTK has three GtkSelectionModel implementations: GtkSingleSelection, GtkMultiSelection and GtkNoSelection, which differ in the number of items that can be simultaneously selected (1, many, or 0).

The GtkGridView colors demo shows a multi-selection in action, with rubberbanding:

 

You are very likely to encounter selection models when working with GTK’s new list widgets, since they all expect their models to be selection models.

The big ones

The last group of models I want to mention are the ones doing the typical operations you expect in lists: filtering and sorting. The models are GtkFilterListModel and GtkSortListModel. The both use auxiliary objects to implement their operations: GtkFilter and GtkSorter. Both of these have subclasses to handle common cases: sorting and filtering strings or numbers, or using callbacks.

We have spent considerable effort on these two models in the run-up to GTK 3.99, and made them do their work incrementally, to avoid blocking the UI for extended times when working with big models.

The GtkListView words demo show interactive filtering of a list of 500.000 words:

The leftovers

There are some more list model implementations in GTK that do not fit neatly in any of the above groups, such as GtkTreeListModel, GtkSelectionFilterModel or GtkShortcutController. I’ll skip these today.

Models everywhere

I’ll finish with a brief list of GTK APIs that return list models:

  • gdk_display_get_monitors
  • gtk_widget_observe_children
  • gtk_widget_observe_controllers
  • gtk_constraint_layout_observe_constraints
  • gtk_constraint_layout_observe_guides
  • gtk_file_chooser_get_files
  • gtk_drop_down_get_model
  • gtk_list_view_get_model
  • gtk_grid_view_get_model
  • gtk_column_view_get_model
  • gtk_column_view_get_columns
  • gtk_window_get_toplevels
  • gtk_assistant_get_pages
  • gtk_stack_get_pages
  • gtk_notebook_get_pages

In summary, list models are everywhere in GTK 4. They are flexible and fun, you should use them!

A primer on GtkListView

Some of the early adopters of GTK4 have pointed out that the new list widgets are not the easiest to learn. In particular,  GtkExpression and GtkBuilderListItemFactory are hard to wrap your head around. That is not too surprising – a full list widget, with columns, and selections and sorting, and tree structure, etc is a complicated beast.

But lets see if we can unpack things one-by-one, and make it all more understandable.

Overview

Lets start with a high-level view of the relevant components and their interactions: the model, the list item factory and the list view.

They are the three things that occur when we create a list view:

view = gtk_list_view_new (model, factory);

The models we use are GListModels. These always contain GObjects, so you will have to provide your data in the form of objects. This is a first notable difference from GtkTreeview, which is using GtkTreeModels directly containing basic types.

For some simple cases, GTK provides ready-made models, such as GtkStringList. But in general, you will have to make your own model. Thankfully, GListModel is a much simpler interface than GtkTreeModel, so this is not too hard.

The responsibility of the list item factory is to produce a row widget and connect it to an item in the model, whenever the list view needs it.

The list view will create a few more rows than it needs to fill its visible area, to get a better estimate for the size of the scrollbars, and in order to have some “buffer”for when you decide to scroll the view.

Once you do scroll, we don’t necessarily need to ask the factory to make more rows —we can recycle the rows that are being scrolled out of view on the other end.

Thankfully, all of this happens automatically behind the scenes. All you have to do is provide a list item factory.

Creating items

GTK offers two different approaches for creating items. You can either do it manually, with GtkSignalListItemFactory, or you can instantiate your row widgets from a ui file, using GtkBuilderListItemFactory.

The manual approach is easier to understand, so lets look at that first.

factory = gtk_signal_list_item_factory_new ();
g_signal_connect (factory, "setup", setup_listitem_cb, NULL);
g_signal_connect (factory, "bind", bind_listitem_cb, NULL);

The “setup” signal is emitted when the factory needs to create a new row widget, “bind” is emitted when a row widget needs to be connected to an item from the model.

Both of these signals take a GtkListItem as argument, which is a wrapper object that lets you get at the model item (with gtk_list_item_get_item()) and also lets you deliver the new row widget (with gtk_list_item_set_child()).

static void
setup_listitem_cb (GtkListItemFactory *factory,
                   GtkListItem        *list_item)
{
  GtkWidget *label = gtk_label_new ("");
  gtk_list_item_set_child (list_item, label);
}

Typically, your rows will be more complicated than a single label. You can create complex widgets and group them in containers, as needed.

static void
bind_listitem_cb (GtkListItemFactory *factory,
                  GtkListItem        *list_item)
{
  GtkWidget *label;
  MyObject *obj;

  label = gtk_list_item_get_child (list_item);
  obj = gtk_list_item_get_item (list_item);
  gtk_label_set_label (GTK_LABEL (label),
                       my_object_get_string (obj));
}

If your “bind” handler connects to signals on the item or does other things that require cleanup, you can use the “unbind” signal to do that cleanup. The “setup” signal has a similar counterpart called “teardown”.

The builder way

Our “setup” handler is basically a recipe for creating a small widget hierarchy. GTK has a more declarative way of doing this: GtkBuilder ui files. That is the way GtkBuilderListItemFactory works: you give it a ui file, and it instantiates that ui file whenever it needs to create a row.

ui = "<interface><template class="GtkListItem">...";
bytes = g_bytes_new_static (ui, strlen (ui));
gtk_builder_list_item_factory_new_from_bytes (scope, bytes);

You might now be wondering: Wait a minute, you are parsing an xml file for each of the thousands of items in my model, isn’t that expensive?

There are two answers to this concern:

  • We are not literally parsing the xml for each item; we parse it once, store the callback sequence, and replay it later.
  • The  most expensive part of GtkBuilder is actually not the xml parsing, but the creation of objects; recycling rows helps for this.

It is relatively easy to see how a ui file can replace the “setup” handler, but what about “bind”? In the example above, the bind callback was getting properties of the item (the MyObject:string property) and using their values to set properties of the widgets (the GtkLabel:label property). In other words, the “bind” handler is doing property bindings. For simplicity, we just created a one-time binding here, but we could have just as well used g_object_bind_property() to create a lasting binding.

GtkBuilder ui files can set up property bindings between objects, but there is one problem: The model item is not ‘present’ in the ui file, it only gets associated with the row widget later on, at “bind” time.

This is where GtkExpression comes in. At its core, GtkExpression is a way to describe bindings between objects that don’t necessarily exist yet.  In our case, what we want to achieve is:

label->label = list_item->item->string

Unfortunately, this gets a little more clumsy when it is turned into xml as part of our ui file:

<interface>
  <template class="GtkListItem">
    <property name="child">
      <object class="GtkLabel">
        <binding name="label">
          <lookup name="string">
            <lookup name="item">GtkListItem</lookup>
          </lookup>
        </binding>
      </object>
    </property>
  </template>
</interface>

Remember that the classname (GtkListItem) in a ui template is used as the “this” pointer referring to the object that is being instantiated.

So, <lookup name=”item”>GtkListItem</lookup> means: the value of the “item” property of the list item that is created. <lookup name=”string”> means: the “string” property of that object. And <binding name=”label”> says to set the “label” property of the widget to the value of that property.

Due to the way expressions work, all of this will be reevaluated when the list item factory sets the “item” property on the list item to a new value, which is exactly what we need to make recycling of row widgets work.

Expert level confusion

GtkBuilderListItemFactory and GtkExpression can get really confusing when you nest things—list item factories can be constructed in ui files themselves, and they can get given their own UI files as a property, so you end up with constructions like

<object class="GtkListView">
  <property name="factory">
    <object class="GtkBuilderListItemFactory">
      <property name="bytes"><![CDATA[
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<template class="GtkListItem">
  <property name="child">
  ...
]]>
      </property>
    </object>
  </property>
...

This can be confusing even to GTK experts.

My advice would be avoid this when starting out with GtkListView—you don’t have to create the list item factory in the UI file, and you can specify its UI template as a resource instead of embedding it directly.

Going deeper

Everything we’ve described here today applies to grid views as well, with minimal adjustments.

So far, we’ve focused on the view side of things. There’s a lot to say about models too.

And then there is the column view, which deserves a post of its own.

GTK 3.99.1

It has been a month since we released GTK 3.99, high time for another snapshot. Here it is: https://download.gnome.org/sources/gtk/3.99/gtk-3.99.1.tar.xz

This snapshot is focused on polish and completion.

Loose ends

We’ve tied up a number of loose ends in our APIs.

The most user-visible change was probably the simplification of the button class hierarchy. Instead of deriving GtkCheckButton from GtkToggleButton, they are now two independent widgets, and they both can be grouped to be mutually exclusive (aka as “radio group”). In this new setup, GtkRadioButton is not really needed anymore, and therefore gone.

The API of our new list widgets (GtkListView and GtkGridView) has seen some small tweaks as well. We are now explicitly requiring the models to be of type GtkSelectionModel, to make it clear that the widgets handle selections.  And we’ve gotten rid of the extra “with_factory” constructors, and just take a nullable factory argument in new(), leaving us with

GtkWidget * gtk_list_view_new (GtkSelectionModel  *model,
                               GtkListItemFactory *factory);

As more of an  API cleanup, we’ve dropped all the defines for CSS style classes – which style classes our widgets support is defined in their documentation, and these extra defines were not really well-defined or useful.

Our theme is now rounding the corners of the frame that is drawn by GtkFrame widgets. This required us to make frames clip their children – not really an API change, but a behavior change that is worth mentioning.

More demos

A lot of effort has gone into gtk4-demo over the past month.

We have modernized the source code highlighting. We are now using the highlight commandline utility. Among other things, this allows us to have syntax highlighting for xml and css, as well as dark theme support.

Highlighting XML in a dark theme
Highlighting

The list of demos has better filtering and a better appearance. The new look is one of a few predefined list styles that Adwaita supports now: rich list, navigation sidebar and data table.

 

Rich List list style
Rich List
Navigation Sidebar list style
Navigation Sidebar
Data Table list style
Data Table

We have dropped a few outdated demos from gtk4-demo, and polished many of the existing ones. Here is how our Drag-and-Drop demo looks now:

Drag-and-Drop demo
Drag-and-Drop demo

A number of new demos have been added as well. Here is the new demo for layout managers and transformations:

Performance, and other bugs

Many bugs have been squashed; thanks to our eager testers and bug reporters.

A long-standing issue that we finally tracked down recently caused our GL renderer to get clipping wrong in the presence of non-trivial projective transformations. This has now been corrected (and the result can be seen in the transformation demo above).

As part of the highlighting improvements that have been mentioned before, gtk_text_view_buffer_insert_markup() has been made much faster. This improvement only happened because the highlight utility can produce Pango markup. Kudos to whoever implemented that!

Another performance problem that we’ve addressed is the loading time of the font chooser dialog on systems with many fonts. We are now populating the font list incrementally. Apart from this change, the investigation has led to performance improvements in fontconfig and Pango that will benefit any user of those libraries.

Can I port already?

The answer is: yes!

Now is a great time to take a look at GTK4, start porting your app, and give us feedback on our APIs, new and old. We are also eager to see what ideas you have for using GTK4 in unexpected ways – the few demos we’ve shown above can maybe give you some inspiration.

Whats next?

We are looking to land the at-spi backend for our new accessibility interfaces soon; it should be included in the next GTK snapshot.