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

Chapter 10 / 11

Saving

We save the drawing to an image file, without the toolbar or the selection, and without overwriting previous files.

Duration30 min
Concepts
  • loop returning a value
  • format!
  • Path
  • io::Result
  • reusing code

Our app can draw, move and color shapes. One thing is missing: keeping the result. Since chapter 4, the S key takes a screenshot of the window into screenshot.ppm. But that screenshot has two flaws: you can see the toolbar, the blue outline of the selection and the color picker if it's open, and each new screenshot overwrites the previous one.

In this chapter, we replace it with a real export: only the shapes, on a white background, in a new file each time, export_1.ppm, then export_2.ppm, and so on.

Here's the same scene in the window, then in the exported file:

The window: three shapes, the toolbar in the top-right corner, and the green circle selected with its blue outline
The exported file: the same three shapes on a white background, with no toolbar and no selection outline

Good news: we already have almost everything. We know how to draw shapes on a canvas, turn a canvas into an image, and save an image as PPM. All that's left is to put these pieces together.

Drawing without the interface#

To get an image without the toolbar, we can't reuse the app's canvas: the interface is already drawn on it. So we create a second canvas, just for the export, and draw only the shapes on it.

Add this method at the end of the impl App block, in src/app.rs:

src/app.rsRust
/// Saves the drawing (without the interface) to the first free
/// `export_N.ppm` file and returns its name.
pub fn export_ppm(&self) -> io::Result<String> {
    let mut canvas = Canvas::new(self.canvas.width, self.canvas.height);
    for shape in &self.shapes {
        shape.draw(&mut canvas);
    }

    let path = next_free_path("export", "ppm");
    Image::from_canvas(&canvas).save_ppm(&path)?;
    Ok(path)
}

The new canvas has the same size as the app's, and it's white from the moment it's created, as we decided in chapter 3. We draw the shapes on it, and only them: no preview, no selection outline, no buttons.

Then we look for a free file name with next_free_path, which we write right after, then turn the canvas into an image and save it, with the functions from chapters 2 and 3.

Saving can fail, hence the ? that sends the error up, and the io::Result<String> return type. If everything goes well, the method returns the name of the file, so we can print it.

The method takes &self and not &mut self: exporting doesn't modify the app, we only read the list of shapes.

We need three imports at the top of src/app.rs. io for the return type, Path to check whether a file exists, and Image for saving:

src/app.rsRust
use std::io;
use std::path::Path;

use minifb::{Key, KeyRepeat, MouseButton, MouseMode, Window};

use crate::action::Action;
use crate::canvas::Canvas;
use crate::color::{GRAY, WHITE};
use crate::image::Image;
use crate::shapes::{Shape, Tool, shape_under};
use crate::ui::{ColorPicker, Toolbar};
use crate::vec2::Vec2;

Finding a free name#

To avoid overwriting previous exports, we try names one by one: export_1.ppm, then export_2.ppm, and so on, until we find one that doesn't exist yet.

This function doesn't depend on the app, so it goes at the end of the file, outside the impl block. It isn't pub: only this file uses it.

Your turn

Complete the loop in next_free_path. On each pass, if the file candidate doesn't exist, the loop stops and the function returns that name. Otherwise, we move on to the next number.

  • Path::new(&candidate).exists() is true if the file already exists;
  • loop is an endless loop, which you leave with break;
  • in Rust, break can give the loop a value: break candidate; stops the loop, and the loop is then worth candidate.
src/app.rsRust
/// First `{prefix}_{n}.{ext}` file name that does not exist yet.
fn next_free_path(prefix: &str, ext: &str) -> String {
    let mut n = 1;
    loop {
        let candidate = format!("{prefix}_{n}.{ext}");
        todo!()
    }
}
Solution
src/app.rsRust
/// First `{prefix}_{n}.{ext}` file name that does not exist yet.
fn next_free_path(prefix: &str, ext: &str) -> String {
    let mut n = 1;
    loop {
        let candidate = format!("{prefix}_{n}.{ext}");
        if !Path::new(&candidate).exists() {
            break candidate;
        }
        n += 1;
    }
}

format! works like println!, but instead of printing the text, it returns it as a String. With prefix set to "export" and ext set to "ppm", we get export_1.ppm, export_2.ppm…

The loop is the last expression of the function, without a semicolon. So its value, the one given by break candidate, is the value returned by the function.

Pitfall

Don't forget the n += 1. Without it, if export_1.ppm already exists, the loop tests the same name forever: the app freezes, with no error message. The compiler can't spot it for you, it's the kind of bug you only find by running the program, and only on the second export.

Hooking up the S key#

The S key took the screenshot in main.rs. We move it into handle_keys, at the end, after the if mouse_down { return; }: we don't want to export while dragging a shape.

src/app.rsRust
if pressed(Key::S) {
    match self.export_ppm() {
        Ok(path) => println!("saved to {path}"),
        Err(e) => eprintln!("could not save the image: {e}"),
    }
}

It's the same match as in chapter 4: on success, we print the name of the file, and on error, we print it to the error output without stopping the app.

In src/main.rs, delete the old screenshot block, as well as the imports that are no longer used, KeyRepeat and Image. Here's the full file. This is its final version:

src/main.rsRust
mod action;
mod app;
mod canvas;
mod color;
mod config;
mod image;
mod shapes;
mod ui;
mod vec2;

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

use app::App;
use config::{HEIGHT, WIDTH};

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

    let mut app = App::new(WIDTH, HEIGHT);

    while window.is_open() && !window.is_key_down(Key::Escape) {
        app.update(&window);
        app.render();
        window
            .update_with_buffer(&app.canvas().pixels, WIDTH, HEIGHT)
            .expect("could not update the window");
    }
}

The whole app now lives in App. main only opens the window and runs the loop.

Terminal
cargo run

Draw a few shapes, select one, open the color picker, then press S. The terminal prints:

Output
saved to export_1.ppm

Open the file: you'll find your shapes on a white background, with no buttons, no picker, no blue outline. Press S again: this time, it's export_2.ppm. The first file hasn't been touched.

Exercises#

  1. In most programs, you save with Ctrl+S (or Cmd+S on a Mac). Make S export only if Ctrl or Cmd is held. In minifb, these keys are called Key::LeftCtrl, Key::RightCtrl, Key::LeftSuper and Key::RightSuper.

  2. Exporting an empty drawing isn't very useful. If no shape has been drawn, save nothing and print nothing to save in the terminal instead.

  3. Bonus: instead of numbering the files, put the time in the name, for example export_1795000000.ppm. The number is the number of seconds since January 1, 1970, which you get with std::time::SystemTime. Since two exports in the same second would have the same name, keep next_free_path for that case anyway.

Solutions

1. We check that one of the control keys is held at the same time. For that, is_key_down is the right function: we want to know whether the key is held, not whether it was just pressed.

src/app.rsRust
let ctrl = window.is_key_down(Key::LeftCtrl)
    || window.is_key_down(Key::RightCtrl)
    || window.is_key_down(Key::LeftSuper)
    || window.is_key_down(Key::RightSuper);

if ctrl && pressed(Key::S) {
    // ...
}

2. At the start of the S key branch, or at the start of export_ppm. In handle_keys, it's the simplest:

src/app.rsRust
if pressed(Key::S) {
    if self.shapes.is_empty() {
        println!("nothing to save");
    } else {
        match self.export_ppm() {
            Ok(path) => println!("saved to {path}"),
            Err(e) => eprintln!("could not save the image: {e}"),
        }
    }
}

3. In export_ppm, we compute the number of seconds, then pass it as the prefix to next_free_path:

src/app.rsRust
let seconds = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)
    .map(|d| d.as_secs())
    .unwrap_or(0);
let path = next_free_path(&format!("export_{seconds}"), "ppm");

duration_since can fail if the computer's clock is set before 1970. It doesn't happen in practice, but Rust makes you plan for it: we then use 0. The first file is called export_1795000000_1.ppm, the second one in the same second export_1795000000_2.ppm.

Recap#

  • To export without the interface, we draw the shapes alone on a separate canvas, then reuse Image::from_canvas and save_ppm.
  • format! builds a String the way println! builds a line of text.
  • Path::new(name).exists() tells whether a file already exists.
  • loop is an endless loop, and break value leaves it while giving it a value.
  • A method that modifies nothing takes &self, and an operation that can fail returns a Result, which you handle with ? or match.
Following along with git?

This chapter matches the tag ch10-export. It's the final version of the code, identical to the master branch.

The app's code is done. In chapter 11, we step back a little to look at what we built, before moving on to ideas for going further.

On this page

  1. Drawing without the interface
  2. Finding a free name
  3. Hooking up the S key
  4. Exercises
  5. Recap
← PreviousChapter 9ColorsContentsNext →Chapter 11Wrap-up

Build your own Paint

A tutorial by theZackD

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