DEV Community

Cover image for I built a pure-Go GUI library that does nothing when nothing happens
bankai-tensei
bankai-tensei

Posted on Edited on AI-assisted

I built a pure-Go GUI library that does nothing when nothing happens

The gowaku logo: the word gowaku in lowercase, with a blue dot inside the o

Introduction

I am building gowaku, a UI library for writing desktop apps in Go. For example, you can build a screen like this.

A screen built with gowaku, with a list of sessions on the left and a chat on the right showing tool results, a diff and a code block

In the previous article I described how Nople, an editor built with gowaku, opens a 10 GB file. This article explains what is inside gowaku, the foundation Nople is built on.

The title, "does nothing when nothing happens", is the idea at the center of gowaku's design. If you open a window and leave it alone, it uses no CPU. If you press one button, it recomputes only the parts that button affects. That sounds obvious, but carrying it through all the way was not easy.

First I walk through the mechanisms that make this idea work. For speed, I show numbers compared with Gio and Cogent Core, two other UI libraries for Go. After that, I cover how gowaku calls the OS and the GPU without cgo, and how it handles Japanese input and typesetting. At the end I go over where gowaku loses to Gio and what it cannot do.

Note: the comparison numbers in this article come from writing programs with the same content in gowaku, Gio and Cogent Core, and running them on the same machine. The details are in docs/BENCH.md.

What gowaku code looks like

Before getting into how it works, here is what the code looks like. You write the UI declaratively, as a tree of widgets, in a shape close to Flutter.

func (s *counterState) Build(ctx gowaku.BuildContext) gowaku.Widget {
    return basic.Center{Child: basic.VStack(
        basic.Text{Content: fmt.Sprintf("count: %d", s.n)},
        control.Button{
            Label:   "Add",
            OnPress: func() { s.SetState(func() { s.n++ }) },
        },
    )}
}
Enter fullscreen mode Exit fullscreen mode

A widget is a plain struct that works as its zero value. It is created on every Build and thrown away right after. The objects that stay in the tree and hold state live separately, inside the library. In this article I call them elements.

To change state, you call SetState. Everything that follows depends on one fact: the library knows which element's state changed.

1. When nothing happens, draw no frames

Some UIs redraw the whole screen every frame. Game loops and immediate mode GUIs often work this way. They draw even when nothing has changed, so an open window keeps using the CPU and the GPU. That is a poor fit for apps like editors and tools, which stay open for a long time.

gowaku's event loop sits blocked in the OS call that waits for the next event. It draws a frame in only two cases:

  • Something changed. For example, SetState was called or the window was resized.
  • An animation is running.

Every animation runs through a single mechanism called Ticker. When no Ticker is running, the loop stays blocked. The blinking caret in a text field is redrawn only at the moment it turns on and the moment it turns off. So even when a text field has focus, gowaku draws only 2 frames per second.

Sometimes you want to change the UI from another goroutine while the loop is blocked. For that, you call gowaku.Post(fn). Post queues the function and wakes the blocked loop. How it wakes the loop depends on the OS. On Windows it uses PostMessageW, and on X11 and Wayland it uses a pipe to itself. On macOS it posts an event.

Here is the CPU and GPU use of a window that nobody is touching, in the three libraries:

gowaku Gio Cogent Core
Idle CPU (%) 0.00 0.03 2.40
Idle GPU (%) 0.00 0.00 1.26

Gio also draws only when it needs to, so there is almost no difference here. The difference shows up in how much work each library does when something changes. The next section explains how gowaku reduces that work.

2. Recompute only what changed

A frame in gowaku has three stages: build, layout and paint. I made every stage process only what changed.

Build. Calling SetState marks the element that holds that state as dirty. At the start of a frame, gowaku rebuilds only the dirty elements, from parent to child. If a rebuilt widget has the same type and the same key as before, the elements below it are reused as they are.

Layout. When a parent fixes an element's size, the element's own size does not change, however its contents change. gowaku treats such elements as boundaries and stops relayout there. When only a color changes, it skips the layout stage entirely.

Paint. If you wrap widgets in a RepaintBoundary widget, the drawing commands inside it are recorded into a layer of their own. When the contents change, only that layer is recorded again. Every other layer reuses its recording from the previous frame.

Diagram of an element tree, colored to show what build, layout and paint each recompute in the frame after one button press

I measured how much this helps, in gowaku alone. I put n cards on screen next to one small widget whose color changes. The table below shows how long one frame took when only that widget's color changed. The time covers build, layout and recording the drawing commands. It does not include sending them to the GPU.

n = 1,000 n = 10,000 n = 100,000
Rebuild only one (with layer) 0.40 µs 0.35 µs 0.37 µs
Rebuild only one (without layer) 54 µs 661 µs 8.9 ms
Rebuild everything 483 µs 4.5 ms 45 ms

The first row wraps the changing widget in a layer. The time stays the same no matter how many elements surround it.

The second row has no layer. Build and layout still cost only one element, but recording the drawing commands starts over for everything, so the time grows in proportion to n.

The third row is gowaku itself rebuilding everything, for comparison. It is not a measurement of any other library. At 100,000 elements it takes 45 ms, which does not fit in one 60 fps frame (16.7 ms). Memory is also allocated 700,000 times per frame.

When a library rebuilds everything, this cost grows with the number of elements. In a small UI you will not notice. In a table with thousands of rows or a long document, you start to feel lag on every keystroke. That lag is what I wanted to avoid in gowaku.

You can reproduce this measurement by running go test ./widgets/basic -bench BenchmarkFrame_OneOfN in the repository.

3. Build only what is visible

Recomputing only what changed is not enough if you build all 1 million rows in the first place. So lists, tables, trees and the editor build only the rows visible on screen. Even in a table with 1 million rows, a frame handles a few dozen rows.

In a list where rows have different heights, you need to find quickly which row sits at a given position. gowaku keeps the sums of the heights in a tree, so the lookup takes time proportional to the logarithm of the row count. Rows that have not been measured yet get an estimated height as a placeholder, which is replaced with the real height when the row comes on screen.

More rows bring one more problem: the precision of the scroll position. As I mentioned in the previous article, a float32 can represent 1-pixel steps only up to about 16.78 million pixels. With 32-pixel rows, scrolling starts to stutter around row 520,000. At 100 million rows, the wheel no longer moves anything. That is why gowaku keeps the scroll position as a float64.

For the comparison with Gio and Cogent Core, I scrolled a list of 10,000 rows, not 1 million. 10,000 rows is what I built with the same content and measured in all three libraries. gowaku and Gio both top out at the display's refresh rate of 60 fps. So the difference shows in CPU use. Cogent Core did not reach 60 fps. The results:

gowaku Gio Cogent Core
Frame rate (fps) 60.0 60.0 53.9
CPU (%) 9.1 12.7 28.7

4. Batch drawing and send it to the GPU

Once the amount of computation is down, what is left is the amount of drawing. A desktop UI is, more or less, a collection of small rounded rectangles and text. gowaku puts both rectangles and text into one large instance array and sends it to the GPU in a small number of draw calls.

This batching works because rounded rectangles, borders, gradients, shadows, text and images are all expressed as the same thing: one quad. The shader draws each kind differently.

Diagram: rounded rectangles, borders, shadows, text and images each become one quad in a single instance array, which goes to the GPU in a few draw calls, where the shader draws each kind its own way

Rounded corners and shadows are computed with distance functions (SDF). A shadow is drawn as a blurred rounded rectangle approximated by a formula, so no separate blur pass is needed. A glyph is rasterized the first time it is used and placed in a texture called an atlas. After that, drawing it only means referring to its coordinates in the atlas.

With 100 widgets animating at the same time, compared with Gio and Cogent Core, the results were:

gowaku Gio Cogent Core
Frame rate (fps) 59.0 60.1 31.9
CPU (%) 7.8 44.4 69.4

CPU use is about one sixth of Gio's. However, the conditions in this comparison are not fully equal. Gio has no shadow blur, so the Gio version of the test program stacks semi-transparent rounded rectangles instead.

5. Call the OS and the GPU from pure Go

From here on, the topic is not speed. gowaku does not use cgo. Running go build produces a single binary. Running GOOS=linux go build on a Windows PC produces the Linux build too.

Still, the OS and GPU APIs are C and C++ APIs. To call them directly from Go, gowaku does the following on each OS:

  • Windows (Direct3D 11, Win32): The D3D11 API is made of COM interfaces. A COM object points to a table of function pointers (a vtable), so gowaku takes function addresses from that table and calls them with syscall.SyscallN.
  • Linux (Vulkan, X11, Wayland): gowaku opens the system's shared libraries (the Vulkan loader, libX11, libwayland-client) with purego, gets the function addresses and calls them. The calls for each Wayland protocol are Go code generated from the XML definitions.
  • macOS (Metal, AppKit): gowaku calls the Objective-C runtime through purego.

The shaders for D3D11 and Vulkan are compiled ahead of time from one HLSL source and embedded in the binary. For Metal, the same shaders are ported to the Metal shading language. The OS driver compiles those at startup. On every OS, users need no shader compiler on their machine.

Without cgo, builds are faster. In exchange, I had to write each call to an OS API myself. Screen reader support took the most effort. For UI Automation on Windows, I had to implement COM objects on the Go side.

6. Japanese input and typesetting

In gowaku, I did not add Japanese support afterward. I built it into the design from the start.

First, input. While the IME is converting, the composition string is shown in place, inside the text field. gowaku also receives the clause boundaries from the OS, and draws the clause being converted differently from the others. The candidate window appears at the start of that clause. This display works on Windows, macOS and Wayland.

Typesetting follows the W3C JLReq (Requirements for Japanese Text Layout).

  • It never starts a line with a closing bracket, a Japanese comma or period, or a small kana. It never ends a line with an opening bracket.
  • It tightens the space between consecutive punctuation.
  • It inserts a quarter-em space between Japanese and Western text.
  • It supports ruby. When the ruby is longer than its base text, it controls how the ruby overhangs the neighboring characters.
  • It can display vertical text, and you can also type in vertical text.

The opening of Botchan set horizontally and vertically with ruby, next to a text field for typing vertically

Vertical text works by thinking of layout in two directions: the direction along a line and the direction in which lines stack. The caret, the selection and the position of the IME candidate window all go through the same coordinate transform. Because of that, there is very little code written only for vertical text.

Tests run without a window

To close the part about internals, a word about testing.

Libraries that use the GPU tend to be hard to test. gowaku also has an implementation that does the same computation as the GPU shaders on the CPU. Tests use it, so they can compare output pixel by pixel on CI machines with no window and no GPU.

App tests work the same way. Inside go test, you can find a button by its label and press it, type text, advance time and take screenshots. The clock is virtual, so a test that waits for an animation to finish runs instantly.

Where gowaku loses to Gio

In the comparisons so far, Gio's numbers were close to gowaku's on many items. On the following points, though, gowaku loses to Gio.

  • It uses more memory. Scrolling 10,000 rows, gowaku uses 240 MB and Gio uses 159 MB. Parsing the Japanese font alone takes about 40 MB of gowaku's heap.
  • The binary is a little larger. For a minimal app, gowaku is 7.7 MB and Gio is 6.4 MB.
  • It occasionally misses a frame. Running 100 animations for 8 seconds, a single frame takes as long as two frames 2 to 6 times. The 99th percentile of the frame interval is 33.3 ms for gowaku and 18.0 ms for Gio. I do not know the cause yet.
  • It follows a resize more coarsely. During a resize, gowaku receives 50 size changes per second and Gio receives 60.

What it cannot do

Apart from winning or losing on numbers, there are things gowaku cannot do yet.

  • It does not run on mobile or the web. Only the desktop is supported.
  • The version is 0.3.0. The API will still change.

Summary

To sum up what this article covered:

  • When nothing happens, it draws no frames. Idle CPU is 0 %.
  • It rebuilds only what changed. With a layer around it, changing one element out of 100,000 costs 0.4 µs, regardless of the count.
  • It builds only what is visible. The scroll position is a float64, so it moves in 1-pixel steps even at 100 million rows.
  • It puts drawing into one array and sends it to the GPU.
  • It does not use cgo. go build alone produces binaries for all three OSes.
  • Japanese input and typesetting were built into the design from the start.

You can try the widget gallery in one command (no cgo or C compiler needed):

go run github.com/bankai-tensei/gowaku/examples/gallery@latest
Enter fullscreen mode Exit fullscreen mode

There are more than 100 widgets, and you can see screenshots of them in the catalog or on the website. If you want to see a real app running on it, try Nople, the editor I built with gowaku.

Top comments (0)