Chapter 1 - An empty window
Updated to Gio 0.71 as of August 30th 2024
Goals
The intent of this section is to create a blank canvas that we later can draw upon.
Outline
The code does three main things:
- Imports Gio
- Creates and calls a goroutine that:
- Creates a new window, called
w
- Starts a never-ending loop that waits for Events in the window (no Event will ever occur in this example)
- Creates a new window, called
That’s it! Let’s look at the code:
Code
package main
import (
"gioui.org/app"
)
func main() {
go func() {
// create new window
w := new(app.Window)
// listen for events in the window
for {
w.Event()
}
}()
app.Main()
}
Comments
The code looks simple enough, right? Still, let’s take the time to to look at what’s going on.
-
We import
gioui.org/app
. What’s that?Looking at the docs we find:
Package app provides a platform-independent interface to operating system functionality for running graphical user interfaces.
This is good news. Gio takes care of all the platform dependent stuff for us. I routinely code on Windows and MacOS. Gio just works. GioUI.org lists even more, iOS and Android included.
This is deeper than you might realize. Even if your app today is single-platform, your skillset is now multi-platform. “We should port to Mac.” Consider it done! “Hot startup seeking app and desktop experts.” No problem. “Who here knows tvOS?” You do! “The pilot died, can anyone land this plane?!” OK, maybe not that last one but the point still stands. The diversity of Gio is nothing less than amazing.
-
We create an
app.Window
using new(), the standard Go way of allocates memory for our variable and returns it’s pointer (or address). It’s effectively the same as writingvar w app.Window
, but we stick to the former since that is how Gio docs are written. -
The event loop in the goroutine
-
The event loop is the
for { wEvent() }
loop. As described in the docs, w.Event simply blocks until an event is received from the window. For now we just let it listen without doing anything with the events it receives. Later we’ll start reacting to them.From app.main we learn:
Because Main is also blocking on some platforms, the event loop of a Window must run in a goroutine.
-
A goroutine with no name (i.e. an anonymous function) is created and runs the event loop. Since it’s in a goroutine it will spin concurrently with the rest of the program.
go func { // ... }()
Jeremy Bytes writes well about anonymous functions. They’re useful in many contexts, not only with Gio.
-
-
Start it by calling
app.Main()
From app.Main documentation:The Main function must be called from a program’s main function, to hand over control of the main thread to operating systems that need it.