Drawing in GTK+

The topic of how GTK+ draws the content of a window is a fairly complex one; it involves drilling down from GtkWidget, to GdkWindow, to Cairo, to the windowing system currently in use. This task can seem somewhat daunting, even for people that are familiar with the GTK+ API from an application development standpoint, so I decided to write down a quick introduction of how GTK+ draws, going from widgets, to windows, to surfaces, to native windowing resources.

How it starts

GTK+ always draws because something asked it to. This request may come from the windowing system — for instance, because the window manager presented your application window to the user, or because the user resized it — but more often it’ll come from a widget updating its contents. Let’s say, a progress bar going from 50% to 60%; or a label, changing its text; or a spinner, doing a new iteration. This request invalidates the backing GdkWindow of the widget — which usually it’s the GdkWindow of the top-level GtkWindow that contains the widget. Each invalidation carries with itself the region of the window to be invalidated (the “damage”), so that when we get to actually drawing, we know which parts of the window need to be updated, and we can avoid drawing outside of the damaged areas.

Race the clock

The first invalidation will start the “frame clock”; this clock is an object that keeps track of each phase inside a frame, like painting windows, laying out widgets, or processing the event queue. This allows GTK+ to be synchronized to things like the windowing system compositor, and to avoid performing unnecessary work that won’t be seen by the user — for instance, drawing something at 1000 frames per second when your display can only run at 60 Hz.

Once the clock reaches the “paint” phase, we process all the scheduled updates on a window; this will cause a GDK_EXPOSE event to be emitted. The GDK_EXPOSE event contains the GdkWindow that needs to be updated, and the union of all the invalidated areas. It’s important to note that, by and large, only top level windows will receive a GDK_EXPOSE event; for historical reasons, though, some widgets may apply a particular event mask that will cause GDK_EXPOSE events to be delivered to them as well. You should not write code that depends on that, and if you have legacy code ported from older versions of GTK+ 2.x you should really consider dropping the GDK_EXPOSURE_MASK from the event mask.

Rendering

GTK+ takes the window and invalidated region out of the GDK_EXPOSE event and figures out which top level widget they belong to. Once that’s found, GTK+ will begin the actual rendering process. First of all, GTK+ will ask the GdkWindow to create a buffer where to draw the contents of the window; the buffer is going to be clipped to the region that needs to be drawn, and will be cleared with the background color of the window. GDK will create a “drawing context” — a transient object that keeps track of things like OpenGL and Cairo drawing. Then, GTK+ will ask the widget to draw itself using a Cairo context. For leaf widgets this means drawing themeselves on that context; for container widgets, this additionally means recursing through all their children. At the end of this process, GTK+ will end the frame by telling GDK to take the buffer that contains all the rendered widgets and use it to replace the current contents of the window. GDK will then ask the windowing system to present the window to the user, whenever it’s more appropriate.

Changing History

The process outlined above has various caveats, and the code that deals with invalidation and validation of windows inside GDK is fairly complex; it also has a long history, which means that its API is littered by the headstones of ages past.

Before GTK+ 3.0, for instance, you were supposed to handle the “expose” events yourself, and create a Cairo context to draw on a widget by using gdk_cairo_create(); this has long since been unnecessary, because the GtkWidget::draw virtual function already provides us with a Cairo context with which to draw. The gdk_cairo_create() function, though, has been deprecated in GTK+ 3.22, and should not be used in newly written code; if you need a Cairo context you should create a similar Cairo surface, call cairo_create() on it, and then use the surface as the source for the Cairo context that GTK+ provides to you when drawing a widget. On the other hand, if you were using gdk_cairo_create() to draw on a top-level, native GdkWindow in response to a GDK_EXPOSE event then you should use the newly added gdk_window_begin_draw_frame(), gdk_window_end_draw_frame(), and GdkDrawingContext API instead.

Shaping Future

The internals of the drawing code in GTK+ have been progressively updated over the years, to cope with things like new windowing systems, as well as other rendering API. It’s fairly certain that they will change again, especially when it comes to improving the rendering performance. Many of the changes that may seem arbitrary are, in reality, stepping stones towards reducing the time spent inside the toolkit in each frame, and leave more time to the application logic.

This Week in GTK+ – 5

In this last week, GTK+ has seen 35 commits, with 3140 lines added and 2353 lines removed.

Planning and Status
  • The GTK+ hackfest starts today; topics include: CSS, layout management, portals for sandboxing, and GDK.
  • Matthias Clasen and Alex Larsson are working on an initial implementation of the “portal” for opening files in a sandboxed application.
Notable changes
  • Emmanuele Bassi merged his branch for simplifying the GdkWindow drawing entry points; this branch introduced a few new functions and a GdkDrawingContext class, while deprecating the old gdk_window_begin_paint* family of functions; gdk_window_end_paint(); gdk_cairo_create(); and gtk_widget_send_expose().
  • Tristan Van Berkom worked on fixing the fallout from the introduction of the new content sizing properties in GtkScrolledWindow, and ensured that the sizing requests are consistent.
Bugs fixed
  • Bug 767312 gtk_widget_path_append_for_widget() misses classes unless gtk_widget_get_style_context() has been called
  • Bug 79229 GtkScale with a big number of digits and value pos set to GTK_POS_TOP/BOTTOM is panted incorrectly
  • Bug 118959 GtkScale value ‘-0’
  • Bug 710471 Make gtk_scrolled_window_remove() smart
  • Bug 767310 High-contrast theme doesn’t show focus rectangle in default button
  • Bug 766860 tiled (snapped, half-maximized) windows in Wayland aren’t GDK_WINDOW_STATE_TILED
  • Bug 766675 Add appropriate frame drawing API to GdkWindow
Get Involved

Interested in working on GTK+? Look at the list of bugs for newcomers and join the IRC channel #gtk+ on irc.gnome.org.

This Week in GTK+ – 4

In this last week, GTK+ has seen 55 commits, with 2378 lines added and 1493 lines removed.

Planning and Status
  • Carlos Soriano has been working on further experiments on the new path bar widget in various topic branches.
  • Emmanuele Bassi has been working on a new API for simplifying the drawing entry points inside GtkWidget, in preparation for the new rendering API inside GSK.
Notable changes
  • Timm Bäder added an accessible representation for GtkStack to only show the current visible child in accessibility tools.
  • Matthias Clasen added a warning in case we emit the GtkWidget::draw call on a widget without an allocation; this is not supposed to happen, and a warning allows tracking badly behaving widgets.
  • Lapo Calamandrei fixed Adwaita with regards to menu items, info bars, and the caret color of selectable lables.
  • Matthias Clasen deprecated the GtkSizeGroup:ignore-hidden property, and documented it as broken; sizing of invisible widgets is not really possible, as they lack access to windowing system and style resources. It is recommended to use a GtkStack, instead, to reserve space for hidden widgets.
  • A new GDK device source type, GDK_SOURCE_TRACKPOINT, has been added to represent Trackpoint/point stick pointing devices; this new device type can be used to implement device-specific behavior in widgets.
  • CSS text styling properties can now be used on the value and marks of a GtkScale and GtkProgressbar widgets.
  • Georges Basile Stavracas Neto implemented the max-content-width and max-content-height properties in GtkScrolledWindow; Tristan Van Berkom fixed long-standing sizing issues with the existing min-content-width and min-content-height properties.
Bugs fixed
  • Bug 745622 Selected text not highlighted in GtkInfoBar
  • Bug 767058 GtkInfoBar: right-click/context menu all white
  • Bug 767052 Wayland: Iconifying a modal dialog makes the app unusable
  • Bug 767100 Add an input source type for trackpoints
  • Bug 767108 Separators not correctly placed in GtkPopover
  • Bug 767093 wayland: Provide information about scroll devices
  • Bug 753202 change cursor for click scrolling
  • Bug 767165 Update docs for availability of GDK_GRAB_FAILED
  • Bug 742281 GtkScrolledWindow should have max-content-height and max-content-width properties
  • Bug 674215 regression with updating tooltips
  • Bug 556254 Test properties of type GObject in the ‘object’ test
  • Bug 708148 gtk_tree_view_get_path_at_pos mistakenly identifies column of initial pixels
  • Bug 765595 Modal popover does not close when focus leaves it
  • Bug 766569 Better size requisition for GTK_SCROLL_NATURAL children
  • Bug 767238 Fix long standing regression in min-content-width/min-content-height
Get Involved

Interested in working on GTK+? Look at the list of bugs for newcomers and join the IRC channel #gtk+ on irc.gnome.org.

This Week in GTK+ – 3

In this last week, GTK+ has seen 26 commits, with 5081 lines added and 3618 lines removed.

Planning and Status
Notable changes
  • The documentation has seen various improvements, notably in the CSS reference and the GTK+ 2.x → 3.x migration guide.
  • Matthias Clasen added a section to the API reference that maps the release notes in the README file; this section will be used as the starting point for the migration guide from 3.x to future major releases of GTK+.
  • The gtk-builder-tool utility, which allows to validate, simplify, preview, or inspect a UI description file now leaves the GtkDialog:border-width property alone when simplifying the properties set to a default value.
Bugs fixed
  • Bug 759037 GtkInfoBar: documentation not updated wrt background colors and message types
  • Bug 747206 gtktextview: note on how to get line spacing between two paragraphs
  • Bug 766643 Frozen windows when unmapped with pending configure event
  • Bug 766122 Re-used filechooser displays $pwd half of the time when shown
  • Bug 766878 placesview: Do not mark icon name as translatable
  • Bug 764203 Default background color for the ‘textview border’ node
Get Involved

Interested in working on GTK+? Look at the list of bugs for newcomers and join the IRC channel #gtk+ on irc.gnome.org.

This Week in GTK+ – 2

In this last week, GTK+ has seen 90 commits, with 8502 lines added and 7914 lines removed.

Planning and Status
  • Matthias Clasen updated the GTK+ road map entry for a “tab strip” GtkStack controller widget with his prototype branch.
Notable changes
  • Matthias Clasen and Lapo Calamandrei commited some CSS changes to GtkScale that were required in order to cover all possible cases of marks on all sides. Additionally, the value node GtkScale uses when it displays a value was missing from the documentation, and has now been added.
  • Debarshi Ray fixed some allocation issues with GTK_POLICY_NEVER in GtkScrolledWindow discovered while working on libvte.
  • Matthias Clasen added two new cursor names, context-menu and no-drop, to the list of CSS cursor names supported by GTK; the cursors are provided by Adwaita.
  • Matthew Waters fixed GDK to use the thread-safe Wayland dispatch API; this is especially useful in case multiple threads are polling the Wayland file descriptor.
  • Olivier Fourdan worked on allowing the Wayland backend to try and return sensible values when asking GDK on which monitor a window is displayed; this is still a work in progress, and may require protocol extensions to avoid guesswork that can lead to false positives.
  • Ondrej Holy worked on GIO, GVFS, and GTK+ to ensure that cold-plugged drives would be appropriately detected as removable in the side bar for the file selection dialog.
  • Javier Jardón finally updated GTK+ to use upstream gettext, instead of the macro and build files modified by GLib.
Bugs fixed
  • Bug 373745 Do not use AM_GLIB_DEFINE_LOCALEDIR(GTK_LOCALEDIR) and use gettext instead
  • Bug 766405 Stack shows incorrect frame in widget factory on wayland
  • Bug 763852 gdk/wayland: event source is not multi-thread aware
  • Bug 766314 Spurious leave-notify event after touch up
  • Bug 766442 Broken drag & drop between windows
  • Bug 766440 Scale slider button has stopped discerning & rendering appropriately for scales with vs without marks
  • Bug 766566 Wayland: gdk_screen_get_monitor_at_window() unreliable under Wayland
  • Bug 766336 Crash when selecting rows with rubberbanding
  • Bug 765924 Improve external drives detection
  • Bug 766642 Switches in HeaderBars Are Badly Integrated
  • Bug 766737 stack: Only map children when necessary
  • Bug 766323 GTKPopover gives warnings if visible when reparented
  • Bug 766782 OpenGL in broadway leads to segmentation fault
Get Involved

Interested in working on GTK+? Look at the list of bugs for newcomers and join the IRC channel #gtk+ on irc.gnome.org.

Cursors in GTK+

History

Cursors have traditionally been a big mess in Linux.

The X11 cursor font has been passed down to us from times immemorial, and given us gems such as gumby () or trek (). Unfortunately for us, this state of affairs was frozen into the GDK api with the GdkCursorType enumeration and the gdk_cursor_new() function.

Later on, the Xcursor library came around. It invented its own image format for storing cursors and brought us cursor themes, but didn’t do anything to answer the question “What cursors should my cursor theme provide ?”

Since there is no official list of recommended cursor names, cursor themes frequently provide all the variants of cursor names that have been spotted in the wild. As an example, here is the list of cursors included in the oxygen cursor theme. If you are wondering, the hex strings in this list are a clever trick of Xcursor to retrofit themed cursors underneath core X11 applications that use cursors from the cursor font mentioned above.

CSS to the rescue

About a year ago, we decided to finally improve the GTK+ cursor story. Thankfully, the CSS3 spec contains a decent list of cursor names that can be reasonably expected to be available across platforms.

Standard cursorsSince the GdkCursorType enumeration contains too much nonsense and is not easily extensible, we decided to make gdk_cursor_new_from_name() the recommended API for obtaining cursors. The documentation for this function now lists the CSS cursor names (follow the link above to see it), and the cursor handling code in the various GDK backends tries hard to give you meaningful cursors for all of these names.

On some platforms (such as X11 with a random cursor theme), we may have to fall back to the default arrow cursor if a certain cursor is not present in the theme. As part of this general overhaul of the cursor code, the Windows backend grew support for cursor themes.

GTK+ itself is now using gdk_cursor_new_from_name() exclusively, with the standard cursor names. And gtk3-demo includes a demo that shows all the standard cursors and lets you try them out. The screenshot above shows it.

The changes described here went into GTK+ 3.18, which was released about 9 months ago.

What you should do in your application

Most likely, you don’t have to do anything! GTK+ widgets use suitable cursors all by themselves, and you can benefit from that without any extra work.

If your application is creating its own cursors for whatever reason, you should check carefully if one of the standard cursors shown above is suitable for you. Using a standard cursor ensures that you will get a suitable cursor regardless of the platform your application is running on and regardless of the cursor theme the user has chosen.

Please use gdk_cursor_new_from_name() to generate your themed cursor, since this is now the preferred API for this task.

This Week in GTK+ – 1

What’s up with GTK+ for the week of 9 May 2016 – 15 May 2016

In this last week, GTK+ has seen 51 commits, with 5375 lines added and 4970 lines removed.

Planning and Status

The 3.22 development cycle is picking up pace while we go through the items of the Roadmap.

Notable changes
  • Olivier Fourdan fixed scroll event handling in GtkMenu, to ensure that it behaves consistently on X11 and Wayland with regards to smooth and discrete scrolling
  • The list of available protocols in the Connect to Server help popover is now populated using the list of supported schemes in GVFS, thanks to Georges Basile Stavracas Neto
  • Benjamin Otte has pushed a commit that lets GtkWidget emit the style-updated signal on unrealized widgets instead of delaying until realization; the original behavior was the result of an older optimization to avoid too many invalidations during construction, but the style system has improved over the years.
  • Timm Bäder pushed various clean up commits over various widgets, like GtkListBox, GtkStack, and GtkToolbar.
Bugs fixed
  • Bug 766166 key bindings in gtk.css are ignored
  • Bug 766207 Fix build on pre-C99 compilers
  • Bug 765939 [Wayland] very slow scrolling in GtkMenu using the touchpad
  • Bug 756570 gtkplacesview no longer provides guidance on address formats
  • Bug 766120 Scale draw_value() align changed from centre/right (H/V) to left, causing significant visual regression
  • Bug 766233 Crash when server does not support XI2
  • Bug 766175 Translation of quotes may misinterpreted by GTK sidebar
  • Bug 765700 GtkPaned use causes “How does the code know the size to allocate?”
  • Bug 682080 Gtk:ERROR:gtktoolbar.c:2271:logical_to_physical: assertion failed: (logical == 0)
  • Bug 766458 widget: fix GtkLabelAccessible NULL links.
Get Involved

Interested in working on GTK+? Look at the list of bugs for newcomers and join the IRC channel #gtk+ on irc.gnome.org.

This Week in GTK – 0

In order to improve the communication between the GTK team and the rest of the GNOME platform, as well as application developers, we’re going to start writing weekly status reports on what happens in GTK and the rest of the core GNOME platform.

These reports are heavily inspired by the ones that the Servo team writes.

You can expect a weekly post on this blog every Monday; we’ll look at notable changes; new contributors; new features or deprecations; and scheduled events.

If you have questions, as usual, direct them to the GTK development mailing list.

Have fun!

Hello, World! (Reprise)

Hi all, and welcome back to the GTK+ development blog.

We’ve neglected this blog for a while, after the 3.0 release, but we think it’s kind of important to have a place where to talk about GTK+ (and the rest of the core GNOME platform), how it’s changing, and where it’s going.

Going forward, we are not going to use this blog for announcements — though if you want the, you can simply subscribe to the gnome-announcement mailing list. Instead, we are going to use this space to present what is happening in GTK+; to discuss the road map; to spotlight some new feature, and maybe some old one that is not well known.

Stay tuned, and as usual: have fun!

Newly designed gtk.org now up and running!

Originally, the website for http://www.gtk.org was going to be updated in line with the release for GTK+ 3.0 but there were a few set backs and more review needed. Finally, it’s up and running thanks to a lot of help from Devin Samarin and comments from the GTK+ community.

We have more plans to improve things on the website such as business support around GTK+ which is not really obvious enough on the current website. As part of the updates to the new website, we now list more recently established maintainers of the toolkit (seen on the Development page).