This is the chapter where our program becomes a drawing app. You press the mouse button, drag, and a gray rectangle follows the cursor. You let go, and the rectangle is added to the drawing, in its real color. You can draw as many as you like.
To get there, the program has to remember quite a few things from one frame to the next: the rectangles already drawn, the position of the mouse, what we're currently doing. We'll start by organizing all of that properly, before main becomes unreadable.
Organizing the app's state#
Until now, all our variables lived in main. That was fine while there were three of them. But this chapter adds several, and the next ones will add more. So we'll create a struct that holds all of the app's state, with methods to update it and draw it. main will only have to open the window and run the loop.
Here's the struct, in a new file src/app.rs. Don't type it in just yet: we'll go over each field, and the full file is a bit further down.
/// All the state of the application.
pub struct App {
canvas: Canvas,
rects: Vec<Rect>,
action: Action,
color: u32,
mouse: Vec2,
was_down: bool,
}canvas: the canvas we draw on, which used to be a variable inmain.rects: the rectangles already drawn. AVecthat grows with each new rectangle.action: what we're currently doing with the mouse. We'll come back to it.color: the color of new rectangles. Fixed for now, we'll be able to choose it in chapter 9.mouse: the position of the mouse on this frame.was_down: whether the button was held down on the previous frame.
Notice that no field is pub. The rest of the program doesn't need to touch the app's state directly: it goes through its methods. So that main can still show the canvas, we give it read-only access:
pub fn canvas(&self) -> &Canvas {
&self.canvas
}The method returns a reference &Canvas: main can look at the canvas, but can neither modify it nor keep it.
Vec2 is back#
We're going to handle mouse positions and rectangle corners, which is exactly why we wrote Vec2 in chapter 1. In main.rs, remove the #[allow(dead_code)] above mod vec2;. The compiler then points out the parts of Vec2 that aren't used:
warning: methods `dot`, `length`, and `normalize` are never used
warning: function `longest` is never usednormalize and longest were only there to try out Vec2 in the terminal in chapter 1, the app itself doesn't need them. Rather than deleting them, we keep them, and tell the compiler it's on purpose by putting the attribute directly on each of them in src/vec2.rs:
/// Returns a vector of length 1 pointing in the same direction.
/// Fails for the zero vector, which has no direction.
#[allow(dead_code)] // Chapter 1 exercise, not used by the app itself.
pub fn normalize(self) -> Result<Vec2, String> {
// ...
}/// Returns the longest vector of the slice, or `None` if it is empty.
#[allow(dead_code)] // Chapter 1 exercise, not used by the app itself.
pub fn longest(points: &[Vec2]) -> Option<Vec2> {
// ...
}The warnings about dot and length go away too: they're only used by these two functions, and the compiler considers that whatever a function marked allow(dead_code) uses is still in use.
We also need one small addition to Vec2. minifb gives the mouse position as a (f32, f32) tuple, and we want a Vec2. Add this to src/vec2.rs:
impl From<(f32, f32)> for Vec2 {
fn from((x, y): (f32, f32)) -> Vec2 {
Vec2::new(x, y)
}
}From is Rust's standard trait for conversions. Implementing it for (f32, f32) lets us write Vec2::from((3.0, 4.0)). Notice the (x, y) parameter: you can destructure a tuple right in the parameter list, without going through an intermediate variable.
Rectangles#
Our rectangles need a position, a size and a color. In chapter 6, we'll add circles and lines, so we set up a shapes module to hold them. Create the folder src/shapes/ with two files. First src/shapes/mod.rs:
mod rect;
pub use rect::Rect;When a module is a folder, it's the mod.rs file that represents it. It declares the rect submodule, which will be in src/shapes/rect.rs, and pub use makes it available directly as shapes::Rect, instead of shapes::rect::Rect.
Then src/shapes/rect.rs:
use crate::canvas::Canvas;
use crate::vec2::Vec2;
#[derive(Clone, Copy, Debug)]
pub struct Rect {
/// Top-left corner.
pub pos: Vec2,
pub size: Vec2,
pub color: u32,
}
impl Rect {
pub fn new(x: f32, y: f32, w: f32, h: f32, color: u32) -> Rect {
Rect {
pos: Vec2::new(x, y),
size: Vec2::new(w, h),
color,
}
}
pub fn draw(&self, canvas: &mut Canvas) {
canvas.fill_rect(
self.pos.x as usize,
self.pos.y as usize,
self.size.x as usize,
self.size.y as usize,
self.color,
);
}
}A rectangle is described by its top-left corner, pos, and its size, size, both as Vec2. We keep them as f32, like the mouse position, and only convert to usize when drawing, since that's what fill_rect expects. as usize simply drops the decimal part.
What's left is building a rectangle from a mouse drag. We know the point where the drag started and the one where the mouse is. They're two opposite corners of the rectangle, but we don't know which ones: you can drag to the right or to the left, down or up.
Solution
/// Builds the rectangle between two opposite corners, in any order.
pub fn from_points(a: Vec2, b: Vec2, color: u32) -> Rect {
Rect::new(
a.x.min(b.x),
a.y.min(b.y),
(a.x - b.x).abs(),
(a.y - b.y).abs(),
color,
)
}Whichever way you drag, you get the same rectangle. Without min and abs, dragging up and to the left would give a negative size, and fill_rect would draw nothing.
Reading the mouse#
minifb gives us two pieces of information about the mouse: where it is, and which buttons are held down. Here's the beginning of the update method, called at each frame:
pub fn update(&mut self, window: &Window) {
self.mouse = window
.get_mouse_pos(MouseMode::Clamp)
.map(Vec2::from)
.unwrap_or(Vec2::ZERO);
let down = window.get_mouse_down(MouseButton::Left);
// ...
}get_mouse_pos returns an Option<(f32, f32)>: None when minifb doesn't know where the mouse is. MouseMode::Clamp asks for the position to be kept within the window's bounds if the mouse leaves it, so we never get negative or too-large coordinates.
Then we chain two Option methods. map(Vec2::from) transforms what's inside the Option, if there's something: Some((x, y)) becomes Some(Vec2), and None stays None. Notice that we pass Vec2::from without parentheses: it's the function itself we give to map, so it can call it. Then unwrap_or(Vec2::ZERO) takes the value out of the Option, or uses Vec2::ZERO if there wasn't one.
get_mouse_down(MouseButton::Left) simply answers true or false: is the left button held down right now?
Pressing and releasing#
Knowing that the button is held down isn't enough. What we care about are two precise moments: when you press, to remember where the rectangle starts, and when you release, to add it to the drawing. To detect them, we compare the state of the button on this frame with the one on the previous frame, stored in was_down:
| Previous frame | This frame | What just happened |
|---|---|---|
| released | held | just pressed |
| held | held | dragging |
| held | released | just released |
| released | released | nothing |
That's exactly what the end of update does:
// Compare with the previous frame to detect press and release.
if down && !self.was_down {
self.on_press(self.mouse);
}
if !down && self.was_down {
self.on_release(self.mouse);
}
self.was_down = down;At the end, we remember the current state of the button for the next frame. It's the same idea as is_key_pressed for the keyboard in chapter 4, except minifb doesn't do it for us with the mouse.
Remembering what we're doing#
Between pressing and releasing, we need to remember that we're drawing a rectangle, and where we started. We could use a drawing boolean and a start variable, but start would make no sense when we're not drawing. Rust offers something better, with an enum whose variants can carry data. Create src/action.rs:
use crate::vec2::Vec2;
/// What the user is doing with the mouse button held down.
#[derive(Clone, Copy, Debug)]
pub enum Action {
Idle,
/// Drawing a new shape, from the point where the drag started.
Drawing {
start: Vec2,
},
}An enum is a type that can take one value out of several variants. Here, either we're doing nothing (Idle), or we're drawing (Drawing). And when we're drawing, the variant holds the starting point. You can't have a starting point without drawing, or the other way around: the absurd combination simply can't be written. In chapters 7 and 9, we'll add other variants for moving shapes and picking colors.
On press, we start drawing:
/// The mouse button was just pressed: start drawing.
fn on_press(&mut self, p: Vec2) {
self.action = Action::Drawing { start: p };
}On release, if we were drawing, we add the rectangle, then go back to Idle:
/// The mouse button was just released.
fn on_release(&mut self, p: Vec2) {
if let Action::Drawing { start } = self.action
&& start != p
{
self.rects.push(Rect::from_points(start, p, self.color));
}
self.action = Action::Idle;
}if let Action::Drawing { start } = self.action checks that self.action is indeed the Drawing variant, and if so, takes the starting point out into a start variable. The && start != p adds a condition: we don't add a rectangle if the mouse didn't move, since it would have zero size. The != works because Vec2 derives PartialEq.
Chaining an if let and a condition with && has only been possible since Rust 1.88. That's why we asked for that version in chapter 0. Before, you had to nest two ifs.
Drawing the app#
What's left is the method that draws everything, called at each frame:
/// Redraws everything on the canvas.
pub fn render(&mut self) {
self.canvas.clear(WHITE);
for rect in &self.rects {
rect.draw(&mut self.canvas);
}
// Preview of the rectangle being drawn.
if let Action::Drawing { start } = self.action {
Rect::from_points(start, self.mouse, GRAY).draw(&mut self.canvas);
}
}We clear, draw all the rectangles already drawn, then, if we're drawing, a gray rectangle between the starting point and the current mouse position. That's the preview: it changes at each frame, since the mouse moves, but it's never added to rects. It disappears by itself on the next frame, when we clear everything.
Add the preview color to src/color.rs, below WHITE:
pub const GRAY: u32 = 0x00888888;Functions waiting for their turn#
Rectangles use fill_rect, but nothing uses fill_circle and draw_line in canvas.rs anymore. The compiler says so. They'll be back in chapter 6, so we do the same as for normalize: add #[allow(dead_code)] // Used again in chapter 6. right above each of them in src/canvas.rs.
The main loop#
Here's the full src/app.rs, with the imports at the top of the file:
use minifb::{MouseButton, MouseMode, Window};
use crate::action::Action;
use crate::canvas::Canvas;
use crate::color::{GRAY, WHITE, rgb_to_u32};
use crate::shapes::Rect;
use crate::vec2::Vec2;
/// All the state of the application.
pub struct App {
canvas: Canvas,
rects: Vec<Rect>,
action: Action,
color: u32,
mouse: Vec2,
was_down: bool,
}
impl App {
pub fn new(width: usize, height: usize) -> App {
App {
canvas: Canvas::new(width, height),
rects: Vec::new(),
action: Action::Idle,
color: rgb_to_u32(50, 120, 220),
mouse: Vec2::ZERO,
was_down: false,
}
}
pub fn canvas(&self) -> &Canvas {
&self.canvas
}
/// Reads the mouse and updates the state.
pub fn update(&mut self, window: &Window) {
self.mouse = window
.get_mouse_pos(MouseMode::Clamp)
.map(Vec2::from)
.unwrap_or(Vec2::ZERO);
let down = window.get_mouse_down(MouseButton::Left);
// Compare with the previous frame to detect press and release.
if down && !self.was_down {
self.on_press(self.mouse);
}
if !down && self.was_down {
self.on_release(self.mouse);
}
self.was_down = down;
}
/// The mouse button was just pressed: start drawing.
fn on_press(&mut self, p: Vec2) {
self.action = Action::Drawing { start: p };
}
/// The mouse button was just released.
fn on_release(&mut self, p: Vec2) {
if let Action::Drawing { start } = self.action
&& start != p
{
self.rects.push(Rect::from_points(start, p, self.color));
}
self.action = Action::Idle;
}
/// Redraws everything on the canvas.
pub fn render(&mut self) {
self.canvas.clear(WHITE);
for rect in &self.rects {
rect.draw(&mut self.canvas);
}
// Preview of the rectangle being drawn.
if let Action::Drawing { start } = self.action {
Rect::from_points(start, self.mouse, GRAY).draw(&mut self.canvas);
}
}
}new builds the app in its starting state: a white canvas, no rectangles, nothing in progress. on_press and on_release aren't pub: only update calls them.
And main.rs, which doesn't have much left to do:
mod action;
mod app;
mod canvas;
mod color;
mod config;
mod image;
mod shapes;
mod vec2;
use minifb::{Key, KeyRepeat, Window, WindowOptions};
use app::App;
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 app = App::new(WIDTH, HEIGHT);
while window.is_open() && !window.is_key_down(Key::Escape) {
app.update(&window);
app.render();
if window.is_key_pressed(Key::S, KeyRepeat::No) {
match Image::from_canvas(app.canvas()).save_ppm("screenshot.ppm") {
Ok(()) => println!("saved to screenshot.ppm"),
Err(e) => eprintln!("could not save the image: {e}"),
}
}
window
.update_with_buffer(&app.canvas().pixels, WIDTH, HEIGHT)
.expect("could not update the window");
}
}We declare the three new modules, action, app and shapes, and mod vec2; no longer has its attribute. The loop comes down to three steps: update the app, draw it, and show the result. The S screenshot is still there, it now uses app.canvas().
cargo runClick somewhere in the window, hold the button and move the mouse: a gray rectangle follows the cursor. Let go, and it turns blue. Try dragging in every direction, up, to the left: the rectangle is always well formed. And a single click without moving adds nothing.
Exercises#
-
Add a shortcut to clear everything: pressing N empties the list of rectangles. Hint:
updatealready receives the window, and aVechas aclearmethod. -
Add a basic undo: pressing Z removes the last rectangle drawn.
-
Bonus: instead of a filled gray rectangle, show the preview as an outline, with four lines. You can remove the
#[allow(dead_code)]fromdraw_line, since it's used again.
Solutions
1. In update, after reading the mouse. You need to add Key and KeyRepeat to the minifb import at the top of app.rs:
if window.is_key_pressed(Key::N, KeyRepeat::No) {
self.rects.clear();
}2. pop removes the last element of a Vec. It returns an Option (empty if the list was), which we can ignore here:
if window.is_key_pressed(Key::Z, KeyRepeat::No) {
self.rects.pop();
}For a real undo, with the ability to redo, you need to keep a history. It's one of the ideas in Going further.
3. We compute the preview rectangle, then draw its four sides:
if let Action::Drawing { start } = self.action {
let r = Rect::from_points(start, self.mouse, GRAY);
let (x0, y0) = (r.pos.x as i32, r.pos.y as i32);
let (x1, y1) = (x0 + r.size.x as i32, y0 + r.size.y as i32);
self.canvas.draw_line(x0, y0, x1, y0, GRAY);
self.canvas.draw_line(x1, y0, x1, y1, GRAY);
self.canvas.draw_line(x1, y1, x0, y1, GRAY);
self.canvas.draw_line(x0, y1, x0, y0, GRAY);
}Recap#
- An
Appstruct groups all of the app's state, with private fields andupdateandrendermethods.mainonly runs the loop. - To know when a button has just been pressed or released, we compare its state with the one on the previous frame.
- An
enumwhose variants carry data describes a state with no absurd combination possible:Drawing { start }only exists while we're drawing. Option::maptransforms the content of anOption, andunwrap_ortakes the value out with a default.- The
Fromtrait describes a conversion from one type to another. - You can borrow two different fields of a struct at the same time, one for reading and the other for writing, but you can't borrow the whole struct for writing while one of its fields is borrowed.
In chapter 6, we add circles and lines, and choose the tool with the keyboard.