Build your own Paint
Follow with gitGoing further
EN/FR
04

Chapter 4 / 11

A window

We add our first dependency to open a window and keep showing the canvas in it.

Duration35 min
Concepts
  • crates
  • cargo add
  • Cargo.lock
  • render loop
  • expect
  • match on a Result

Until now, to see what we drew, we had to run the program and then open a file. This chapter changes that: we open a real window and show our canvas in it.

The content of the window: a red rectangle, a blue disc and a black line on a white background

The drawing itself barely changes. What changes is the structure of the program. Instead of drawing once and stopping, it will run in a loop, redraw the image dozens of times per second and react to the keyboard. That loop is what will let us draw with the mouse in the next chapter.

Adding a dependency#

Opening a window means talking to the operating system, and each system has its own way of doing it: Windows, macOS and Linux have nothing in common at that level. That kind of work is beyond the scope of this tutorial; it would fit better in a future course on systems programming. So we'll use a library, what Rust calls a crate.

Crates published by the community are on crates.io. The one we'll use is called minifb, for "mini framebuffer". It does exactly what we need and not much more: open a window, show an array of pixels in it, and tell us what the keyboard and mouse are doing. And it expects pixels in exactly the 0x00RRGGBB format, one u32 per pixel, the same as our canvas.

To add it to the project:

Terminal
cargo add minifb@0.29.0

The @0.29.0 pins the version. Without it, Cargo would take the latest one, which might have changed since this tutorial was written. With it, you're sure to have exactly the same one as me.

The command added a line to Cargo.toml:

Cargo.tomlTOML
[dependencies]
minifb = "0.29.0"

It also filled in Cargo.lock, which was almost empty until now. minifb itself depends on other crates, which depend on other crates, and Cargo.lock records the exact version of each one. You don't need to edit it, but keep it in git: it's what guarantees the project will build the same way on another machine.

The first build will take longer than usual, while Cargo downloads and compiles all these dependencies. The next ones will be fast, it only recompiles what changed.

Pitfall

On Linux, minifb needs a few system libraries to talk to the display server. If the build fails with errors mentioning xkbcommon or wayland, install them. On Debian and Ubuntu:

Terminal
sudo apt install libxkbcommon-dev libwayland-cursor0 libwayland-dev

On macOS and Windows, there's nothing to install.

The documentation of every crate is generated automatically and published on docs.rs. Get into the habit of taking a look: you'll find every available function there, with its parameters and often an example.

The size of the window#

The width and height of the window will be used in several places. Rather than writing 1080 and 720 everywhere, we put them in constants, in a new file src/config.rs:

src/config.rsRust
pub const WIDTH: usize = 1080;
pub const HEIGHT: usize = 720;

Unlike let, a constant must always have its type written out. By convention, its name is in uppercase.

Opening the window#

Replace src/main.rs with this beginning:

src/main.rsRust
mod canvas;
mod color;
mod config;
mod image;
#[allow(dead_code)] // Vec2 comes back in chapter 5.
mod vec2;

use minifb::{Key, KeyRepeat, Window, WindowOptions};

use canvas::Canvas;
use color::{WHITE, rgb_to_u32};
use config::{HEIGHT, WIDTH};
use image::Image;

fn main() {
    let mut window = Window::new("Paint", WIDTH, HEIGHT, WindowOptions::default())
        .expect("could not open the window");

    // ...
}

use minifb::{...} imports what we need from the crate, exactly as we import from our own modules. For an external crate, you write its name directly, without crate::.

Window::new takes the window title, its size, and some options. WindowOptions::default() gives the default options, which suit us fine. Opening a window can fail (no screen, no display server…), so Window::new returns a Result. The .expect(...) says: if it's an error, stop the program with this message.

Rust behavior

When a function returns a Result, there are three main ways to deal with it. match, to handle both cases yourself. ?, to send the error up to the caller. Or expect("message"), which returns the value if everything is fine and stops the program otherwise, with the message and the original error. There's also unwrap(), which does the same without a message.

Stopping the program may seem harsh, but it's the right choice when you can't carry on anyway. If the window doesn't open, our app has no reason to exist. On the other hand, for an error you can recover from, like an image that fails to save, we'll use a match. And that's why main no longer returns a Result: we don't use ? in it anymore.

The render loop#

Here's the heart of the program. It replaces the // ...:

src/main.rsRust
let mut canvas = Canvas::new(WIDTH, HEIGHT);

while window.is_open() && !window.is_key_down(Key::Escape) {
    // Each frame, we clear the canvas and draw everything again.
    canvas.clear(WHITE);
    canvas.fill_rect(100, 100, 240, 160, rgb_to_u32(220, 50, 50));
    canvas.fill_circle(600, 250, 120, rgb_to_u32(50, 120, 220));
    canvas.draw_line(50, 650, 1030, 400, rgb_to_u32(0, 0, 0));

    window
        .update_with_buffer(&canvas.pixels, WIDTH, HEIGHT)
        .expect("could not update the window");
}

The loop runs as long as the window is open and the Escape key isn't pressed. Each pass through the loop produces one image, what we call a frame. By default, minifb runs the loop at 250 frames per second at most.

At each frame, we clear the canvas, redraw everything, then update_with_buffer sends our pixels to the window. That same function also takes care of collecting what happened since the previous frame: keys pressed, mouse movements, a click on the close button. It's thanks to it that is_open and is_key_down give up-to-date answers on the next pass.

Redrawing an image that doesn't move dozens of times per second may seem pointless, and here, it kind of is. But from the next chapter on, the image will change with the mouse, and this will be the simplest way to always show the right state: we don't ask ourselves what changed, we redraw everything. For an image this size, it's no problem at all performance-wise.

A screenshot#

We still have the code that writes PPM files, it would be a shame not to use it anymore. We'll save the content of the window when you press S. Add this inside the loop, right before update_with_buffer:

src/main.rsRust
if window.is_key_pressed(Key::S, KeyRepeat::No) {
    // ...
}

is_key_pressed returns true only on the frame where the key has just been pressed. KeyRepeat::No says we don't want automatic repetition if you hold it down, like when you hold a letter in a word processor.

Pitfall

There are two functions that look very much alike. is_key_down answers "is the key held down right now?": it's true on every frame as long as your finger is on it. is_key_pressed answers "has the key just been pressed?": it's true only once per press. With is_key_down for the screenshot, half a second of pressing would save the file more than a hundred times. For Escape, on the other hand, is_key_down is just right: we only want to know whether to stop.

Your turn

Replace the // ... with a match on the result of saving. If everything went fine, print saved to screenshot.ppm. If there's an error, print could not save the image: followed by the error, with eprintln! instead of println!. eprintln! writes to the error output, a separate channel that terminals display as usual, but that tools can tell apart from ordinary messages.

src/main.rsRust
if window.is_key_pressed(Key::S, KeyRepeat::No) {
    match Image::from_canvas(&canvas).save_ppm("screenshot.ppm") {
        Ok(()) => todo!(),
        Err(e) => todo!(),
    }
}
Solution
src/main.rsRust
if window.is_key_pressed(Key::S, KeyRepeat::No) {
    match Image::from_canvas(&canvas).save_ppm("screenshot.ppm") {
        Ok(()) => println!("saved to screenshot.ppm"),
        Err(e) => eprintln!("could not save the image: {e}"),
    }
}

With this match, a saving error doesn't stop the program: we print the problem and the window stays open. That's the difference with the expect of Window::new.

Running it#

Here's the full main.rs:

src/main.rsRust
mod canvas;
mod color;
mod config;
mod image;
#[allow(dead_code)] // Vec2 comes back in chapter 5.
mod vec2;

use minifb::{Key, KeyRepeat, Window, WindowOptions};

use canvas::Canvas;
use color::{WHITE, rgb_to_u32};
use config::{HEIGHT, WIDTH};
use image::Image;

fn main() {
    let mut window = Window::new("Paint", WIDTH, HEIGHT, WindowOptions::default())
        .expect("could not open the window");

    let mut canvas = Canvas::new(WIDTH, HEIGHT);

    while window.is_open() && !window.is_key_down(Key::Escape) {
        // Each frame, we clear the canvas and draw everything again.
        canvas.clear(WHITE);
        canvas.fill_rect(100, 100, 240, 160, rgb_to_u32(220, 50, 50));
        canvas.fill_circle(600, 250, 120, rgb_to_u32(50, 120, 220));
        canvas.draw_line(50, 650, 1030, 400, rgb_to_u32(0, 0, 0));

        if window.is_key_pressed(Key::S, KeyRepeat::No) {
            match Image::from_canvas(&canvas).save_ppm("screenshot.ppm") {
                Ok(()) => println!("saved to screenshot.ppm"),
                Err(e) => eprintln!("could not save the image: {e}"),
            }
        }

        window
            .update_with_buffer(&canvas.pixels, WIDTH, HEIGHT)
            .expect("could not update the window");
    }
}
Terminal
cargo run

A 1080 × 720 window opens, with a red rectangle, a blue disc and a black line. The terminal stays quiet. Press S, and it prints:

Output
saved to screenshot.ppm

The file screenshot.ppm contains exactly what the window shows. Close the window or press Escape to quit.

Exercises#

  1. Make the red square bounce off the edges of the window. You need its position and its speed in variables declared before the loop, which you update at each frame. When it hits an edge, flip the speed in that direction.

  2. Move the blue disc with the arrow keys. This time, we want it to keep moving as long as the key is held: is_key_down is the right function. The arrows are called Key::Left, Key::Right, Key::Up and Key::Down.

  3. Bonus: each time B is pressed, change the background color to the next one in a list of colors, and go back to the first after the last.

Solutions

1. The position and speed are declared with let mut before the loop, so they survive from one frame to the next:

src/main.rsRust
let (mut x, mut y) = (100, 100);
let (mut vx, mut vy) = (2, 1);
let size = 60;

while window.is_open() && !window.is_key_down(Key::Escape) {
    x += vx;
    y += vy;
    if x <= 0 || x + size >= WIDTH as i32 {
        vx = -vx;
    }
    if y <= 0 || y + size >= HEIGHT as i32 {
        vy = -vy;
    }

    canvas.clear(WHITE);
    canvas.fill_rect(x as usize, y as usize, size as usize, size as usize, rgb_to_u32(220, 50, 50));
    // ...
}

x, y and the speed are i32, because the speed becomes negative when the square heads back the other way. We only convert them to usize when drawing, since that's what fill_rect expects. The loop runs fast, at 250 frames per second: a speed of 2 pixels per frame is already 500 pixels per second.

2. We test each arrow, and move the center by a few pixels on each frame where it's held:

src/main.rsRust
let (mut cx, mut cy) = (600, 250);

while window.is_open() && !window.is_key_down(Key::Escape) {
    let speed = 2;
    if window.is_key_down(Key::Left) {
        cx -= speed;
    }
    if window.is_key_down(Key::Right) {
        cx += speed;
    }
    if window.is_key_down(Key::Up) {
        cy -= speed;
    }
    if window.is_key_down(Key::Down) {
        cy += speed;
    }

    canvas.clear(WHITE);
    canvas.fill_circle(cx as usize, cy as usize, 120, rgb_to_u32(50, 120, 220));
    // ...
}

The top of the window is y = 0: to go up, we decrease y. As in exercise 1, the position is an i32 for the calculations and converted to usize for drawing.

3. An array of colors and an index. The % (remainder of the division) brings the index back to 0 after the last element:

src/main.rsRust
let backgrounds = [WHITE, rgb_to_u32(255, 240, 200), rgb_to_u32(200, 230, 255)];
let mut current = 0;

while window.is_open() && !window.is_key_down(Key::Escape) {
    if window.is_key_pressed(Key::B, KeyRepeat::No) {
        current = (current + 1) % backgrounds.len();
    }

    canvas.clear(backgrounds[current]);
    // ...
}

Recap#

  • A crate is a Rust library. You add it with cargo add, preferably pinning the version, and Cargo.lock freezes the versions of all the dependencies.
  • The documentation of every crate is on docs.rs.
  • expect stops the program if a Result is an error. We keep it for errors we can't recover from, and use match for the others.
  • A graphical app runs in a loop: at each frame, we read the input, redraw everything, and display it.
  • is_key_down is true as long as the key is held, is_key_pressed only once per press.
Following along with git?

This chapter matches the tag ch04-window.

In chapter 5, the mouse comes into play: we click, we drag, and a rectangle appears before our eyes.

On this page

  1. Adding a dependency
  2. The size of the window
  3. Opening the window
  4. The render loop
  5. A screenshot
  6. Running it
  7. Exercises
  8. Recap
← PreviousChapter 3Drawing shapesContentsNext →Chapter 5The mouse

Build your own Paint

A tutorial by theZackD

The code on GitHubFound a mistake? Open an issueCode under the MIT license