Chapter 1 - An empty window

Updated February 23rd 2024

Goals

The intent of this section is to create a blank canvas that we later can draw upon.

An empty window

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)

That’s it! Let’s look at the code:

Code

package main

import (
    "gioui.org/app"
)

func main() {
    go func() {
        // create new window
        w := app.NewWindow()

        // listen for events in the window
        for {
            w.NextEvent()
        }
    }()
    app.Main()
}

Comments

The code looks simple enough, right? Still, let’s take the time to to look at what’s going on.

  1. 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.

  2. The event loop in the goroutine

    • The event loop is the for { w.NextEvent() } loop. As described in the docs, w.NextEvent 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.

  3. 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.


Next chapter View it on GitHub