For now, once a shape is drawn, it's stuck. If you put it in the wrong place, too bad. In this chapter, we'll be able to click on a shape to select it: it will get a blue outline. By holding the button down, we'll drag it somewhere else. And with the Delete key, we'll erase it.
There's a bit of geometry, to tell whether the mouse is on a shape. And above all, there's a question that seems harmless: how does the app remember which shape is selected? The answer takes us to the heart of what makes Rust different from other languages.
Is the mouse on the shape?#
Before selecting a shape, we need to know which one was clicked. We'll give each shape a contains method, which answers a simple question: is this point inside the shape?
For the rectangle, it's straightforward. The point has to be between the left and right edges, and between the top and bottom edges. Add this to src/shapes/rect.rs, between from_points and draw:
pub fn contains(&self, p: Vec2) -> bool {
p.x >= self.pos.x
&& p.x < self.pos.x + self.size.x
&& p.y >= self.pos.y
&& p.y < self.pos.y + self.size.y
}Solution
pub fn contains(&self, p: Vec2) -> bool {
(p - self.center).length() <= self.radius
}p - self.center is the vector going from the center to the point, and its length is the distance between them. It's the same calculation as for the radius in from_points.
The case of the line#
The line takes a bit more thought. It's only one pixel thick: if we required clicking exactly on it, it would be impossible to hit. So we'll accept the click if the mouse is close to the line, within 5 pixels.
So we need the distance between the mouse and the line. The idea: we look for the point on the line closest to the mouse, then measure the distance between the two.
To locate a point on the line, we use a number t, which says where we are along the line: 0 at the starting point, 1 at the end point, 0.5 right in the middle. The matching point is start + u * t, where u is the vector going from the start to the end.
To find the t of the point closest to the mouse, we use the dot product, dot, written in chapter 1. We said it would come in handy, and this is where. If v is the vector going from the start to the mouse, v.dot(u) / u.dot(u) tells how far the mouse "goes" in the direction of the line, on the same scale as t. You don't need to prove the formula to use it: it's the standard recipe for this calculation.
One detail remains. If the mouse is beyond one of the ends, this calculation gives a t smaller than 0 or larger than 1, that is, a point outside the line. In that case, the closest point is simply the end. That's what clamp(0.0, 1.0) does: it brings the number back between 0 and 1.
Here's what it looks like, in src/shapes/line.rs:
/// How close (in pixels) the mouse must be to a line to select it.
const HIT_DISTANCE: f32 = 5.0;
// ...
impl Line {
// ...
/// True if `p` is close to the segment: we project `p` on the segment,
/// keep the projection between both ends, and measure the distance.
pub fn contains(&self, p: Vec2) -> bool {
let u = self.end - self.start;
let v = p - self.start;
let uu = u.dot(u);
let t = if uu == 0.0 {
0.0
} else {
(v.dot(u) / uu).clamp(0.0, 1.0)
};
let closest = self.start + u * t;
(p - closest).length() <= HIT_DISTANCE
}
}The HIT_DISTANCE constant goes at the very top of the file, below the use lines, and the method goes in the impl Line block. The if uu == 0.0 handles a line whose two ends are in the same place: u is then zero, so is uu, and we can't divide by zero. In that case, the closest point is simply the starting point, so t = 0.
As with draw, Shape picks the right method with a match. Add this to the impl Shape block in src/shapes/mod.rs:
pub fn contains(&self, p: Vec2) -> bool {
match self {
Shape::Rect(r) => r.contains(p),
Shape::Circle(c) => c.contains(p),
Shape::Line(l) => l.contains(p),
}
}Which shape is under the mouse?#
When several shapes overlap, which one do we select? The one you see, the one on top. And since shapes are drawn in the order of the list, the one on top is the last one. So we have to search starting from the end. Add this function at the end of src/shapes/mod.rs, outside the impl block:
/// Index of the topmost shape under `p`. Shapes drawn last are on top,
/// so we search from the end of the list.
pub fn shape_under(shapes: &[Shape], p: Vec2) -> Option<usize> {
for (i, shape) in shapes.iter().enumerate().rev() {
if shape.contains(p) {
return Some(i);
}
}
None
}iter() goes through the shapes, enumerate() adds each one's number in the list, and rev() reverses the order. So the loop gets (i, shape) pairs, from the last shape to the first. As soon as we find one that contains the point, we return its number. If we reach the end without finding one, we return None.
The function returns a number, an index, and not the shape itself. This choice matters, we'll get to it right away.
Remembering the selected shape#
The app needs to know which shape is selected, from one frame to the next, to draw its blue outline and to know which one to delete. Add a field to App, in src/app.rs, and its starting value in new:
/// Index of the selected shape in `shapes`. We store an index and not a
/// reference: a reference would borrow `shapes` for as long as the
/// selection exists, and we could no longer modify the list.
selected: Option<usize>,selected: None,Option, because there isn't always a selected shape. usize, because we remember the shape's position in the list.
Moving a shape#
When you press the mouse button, there are now two possibilities: if you click on a shape, you select it and you're going to move it. Otherwise, you draw a new shape, as before. Add a variant to enum Action, in src/action.rs:
/// Moving the shape at `index`; `last` is the mouse position at the previous frame.
Moving {
index: usize,
last: Vec2,
},While moving, we remember which shape we're moving, and where the mouse was on the previous frame. At each frame, we'll move the shape by as much as the mouse has moved since.
on_press chooses between the two possibilities:
/// The mouse button was just pressed: decide what this drag will do.
fn on_press(&mut self, p: Vec2) {
if let Some(i) = shape_under(&self.shapes, p) {
self.selected = Some(i);
self.action = Action::Moving { index: i, last: p };
} else {
self.selected = None;
self.action = Action::Drawing { start: p };
}
}Clicking on empty space deselects the shape and starts a drawing, as in most programs. Remember to import shape_under at the top of app.rs: use crate::shapes::{Shape, Tool, shape_under};.
We now need a method called at each frame while the button is held, to move the shape along. In update, between detecting the press and detecting the release:
if down {
self.on_drag(self.mouse);
}And the method itself:
/// The mouse button is held down.
fn on_drag(&mut self, p: Vec2) {
match &mut self.action {
Action::Moving { index, last } => {
self.shapes[*index].translate(p - *last);
*last = p;
}
Action::Idle | Action::Drawing { .. } => {}
}
}We match on &mut self.action, a mutable reference. As a result, index and last are mutable references to the variant's fields too. To read their value, we put a star in front: *index, *last. And *last = p changes the field directly inside self.action, so the next frame starts from the new position.
p - *last is how far the mouse moved since the previous frame. We move the shape by that much. The second arm, Action::Idle | Action::Drawing { .. }, groups the other two cases, where there's nothing to do. The | means "or", and { .. } means "whatever's inside".
Notice that we borrow self.action for writing while using self.shapes. That's allowed, they're two different fields, as in chapter 5.
Why move the shape by a small offset at each frame, instead of giving it a new position directly? Because each shape has its own idea of its "position". For a rectangle, it's its top-left corner. For a circle, its center. For a line, there are two points. An offset, on the other hand, applies the same way to all of them: we add the same vector to every point of the shape.
Solution
/// Moves the shape by `delta`.
pub fn translate(&mut self, delta: Vec2) {
match self {
Shape::Rect(r) => r.pos = r.pos + delta,
Shape::Circle(c) => c.center = c.center + delta,
Shape::Line(l) => {
l.start = l.start + delta;
l.end = l.end + delta;
}
}
}The rectangle has only one point to move, its corner: its size doesn't change. Same for the circle's center. The line has two points, both have to move, hence the braces to put two statements in the same arm.
Showing the selection#
The selected shape has to be visible. We'll give it a blue border. Add the color to src/color.rs:
pub const SELECTION_BLUE: u32 = 0x00378ADD;The trick for the border is very simple: we draw a slightly bigger version of the shape, in blue, before drawing the shape itself on top. Only the blue edge sticks out.
For the rectangle, we add a draw_outline method to src/shapes/rect.rs, which draws a rectangle bigger by thickness pixels on each side:
/// Draws a border around the rectangle by filling a slightly bigger
/// rectangle. Call it before `draw` so the rectangle covers the middle.
pub fn draw_outline(&self, canvas: &mut Canvas, thickness: f32, color: u32) {
let t = Vec2::new(thickness, thickness);
Rect {
pos: self.pos - t,
size: self.size + t * 2.0,
color,
}
.draw(canvas);
}The corner moves back by thickness up and to the left, and the size grows by twice thickness, once for each side. We build this rectangle and draw it right away, without storing it in a variable.
Then, in src/shapes/mod.rs, a method that decides what to do depending on the shape. Also add use crate::color::SELECTION_BLUE; at the top of the file:
/// Draws a blue highlight around the shape. Call it before `draw`.
pub fn draw_selection(&self, canvas: &mut Canvas) {
match self {
Shape::Rect(r) => r.draw_outline(canvas, 3.0, SELECTION_BLUE),
Shape::Circle(c) => Circle {
radius: c.radius + 3.0,
color: SELECTION_BLUE,
..*c
}
.draw(canvas),
Shape::Line(l) => {
// A thick line: the same line shifted by one pixel around.
for dx in -1..=1 {
for dy in -1..=1 {
let offset = Vec2::new(dx as f32, dy as f32);
Line::from_points(l.start + offset, l.end + offset, SELECTION_BLUE)
.draw(canvas);
}
}
for end in [l.start, l.end] {
canvas.fill_circle(end.x as usize, end.y as usize, 5, SELECTION_BLUE);
}
}
}
}For the circle, we draw a blue circle with a slightly larger radius. The ..*c syntax means: for all the fields we didn't write, take the ones from circle c. Here, it only covers the center, but it's very handy when a struct has many fields and you only change a few.
For the line, there's no inside to surround. So we draw a thicker blue line underneath, by drawing the same line nine times, shifted by one pixel in each direction. Then we add a small blue disc at each end, so you can clearly see where it starts and where it ends.
All that's left is to call it in render. For each shape, we need to know whether it's the selected one, so we need its number. We use enumerate again:
for (i, shape) in self.shapes.iter().enumerate() {
if self.selected == Some(i) {
shape.draw_selection(&mut self.canvas);
}
shape.draw(&mut self.canvas);
}self.selected == Some(i) is only true if a shape is selected and it's number i.
Deleting the selected shape#
Last feature: Delete erases the selected shape. We also accept Backspace, the key that deletes to the left, because many keyboards, Mac keyboards in particular, don't have a separate Delete key. It happens in handle_keys, which now needs to know whether the mouse button is held. Change its signature, and its call in update:
fn handle_keys(&mut self, window: &Window, mouse_down: bool) {self.handle_keys(window, down);Then add this at the end of handle_keys:
// Not while dragging: the index stored in `Action::Moving` must stay valid.
if mouse_down {
return;
}
if (pressed(Key::Delete) || pressed(Key::Backspace))
&& let Some(i) = self.selected.take()
{
self.shapes.remove(i);
}self.selected.take() does two things at once: it returns what selected held, and sets it back to None. That's exactly what we want: once the shape is deleted, nothing is selected anymore. Then remove(i) takes the shape out of the list, and all the ones after it move back one place.
The full code#
Here's the full src/app.rs:
use minifb::{Key, KeyRepeat, MouseButton, MouseMode, Window};
use crate::action::Action;
use crate::canvas::Canvas;
use crate::color::{GRAY, WHITE, rgb_to_u32};
use crate::shapes::{Shape, Tool, shape_under};
use crate::vec2::Vec2;
/// All the state of the application.
pub struct App {
canvas: Canvas,
shapes: Vec<Shape>,
tool: Tool,
action: Action,
/// Index of the selected shape in `shapes`. We store an index and not a
/// reference: a reference would borrow `shapes` for as long as the
/// selection exists, and we could no longer modify the list.
selected: Option<usize>,
color: u32,
mouse: Vec2,
was_down: bool,
}
impl App {
pub fn new(width: usize, height: usize) -> App {
App {
canvas: Canvas::new(width, height),
shapes: Vec::new(),
tool: Tool::Rect,
action: Action::Idle,
selected: None,
color: rgb_to_u32(50, 120, 220),
mouse: Vec2::ZERO,
was_down: false,
}
}
pub fn canvas(&self) -> &Canvas {
&self.canvas
}
/// Reads the keyboard and 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);
self.handle_keys(window, down);
// Compare with the previous frame to detect press and release.
if down && !self.was_down {
self.on_press(self.mouse);
}
if down {
self.on_drag(self.mouse);
}
if !down && self.was_down {
self.on_release(self.mouse);
}
self.was_down = down;
}
fn handle_keys(&mut self, window: &Window, mouse_down: bool) {
let pressed = |key| window.is_key_pressed(key, KeyRepeat::No);
if pressed(Key::R) {
self.tool = Tool::Rect;
}
if pressed(Key::C) {
self.tool = Tool::Circle;
}
if pressed(Key::L) {
self.tool = Tool::Line;
}
// Not while dragging: the index stored in `Action::Moving` must stay valid.
if mouse_down {
return;
}
if (pressed(Key::Delete) || pressed(Key::Backspace))
&& let Some(i) = self.selected.take()
{
self.shapes.remove(i);
}
}
/// The mouse button was just pressed: decide what this drag will do.
fn on_press(&mut self, p: Vec2) {
if let Some(i) = shape_under(&self.shapes, p) {
self.selected = Some(i);
self.action = Action::Moving { index: i, last: p };
} else {
self.selected = None;
self.action = Action::Drawing { start: p };
}
}
/// The mouse button is held down.
fn on_drag(&mut self, p: Vec2) {
match &mut self.action {
Action::Moving { index, last } => {
self.shapes[*index].translate(p - *last);
*last = p;
}
Action::Idle | Action::Drawing { .. } => {}
}
}
/// The mouse button was just released.
fn on_release(&mut self, p: Vec2) {
if let Action::Drawing { start } = self.action
&& start != p
{
let shape = Shape::from_points(self.tool, start, p, self.color);
self.shapes.push(shape);
}
self.action = Action::Idle;
}
/// Redraws everything on the canvas.
pub fn render(&mut self) {
self.canvas.clear(WHITE);
for (i, shape) in self.shapes.iter().enumerate() {
if self.selected == Some(i) {
shape.draw_selection(&mut self.canvas);
}
shape.draw(&mut self.canvas);
}
// Preview of the shape being drawn.
if let Action::Drawing { start } = self.action {
Shape::from_points(self.tool, start, self.mouse, GRAY).draw(&mut self.canvas);
}
}
}on_release hasn't changed: at the end of a move, the action isn't Drawing, so we add nothing and simply go back to Idle.
The full src/shapes/mod.rs file
mod circle;
mod line;
mod rect;
pub use circle::Circle;
pub use line::Line;
pub use rect::Rect;
use crate::canvas::Canvas;
use crate::color::SELECTION_BLUE;
use crate::vec2::Vec2;
/// The drawing tool currently selected.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Tool {
Rect,
Circle,
Line,
}
/// A shape of the drawing.
#[derive(Clone, Copy, Debug)]
pub enum Shape {
Rect(Rect),
Circle(Circle),
Line(Line),
}
impl Shape {
/// Builds the shape drawn with `tool` by dragging the mouse from `a` to `b`.
pub fn from_points(tool: Tool, a: Vec2, b: Vec2, color: u32) -> Shape {
match tool {
Tool::Rect => Shape::Rect(Rect::from_points(a, b, color)),
Tool::Circle => Shape::Circle(Circle::from_points(a, b, color)),
Tool::Line => Shape::Line(Line::from_points(a, b, color)),
}
}
pub fn contains(&self, p: Vec2) -> bool {
match self {
Shape::Rect(r) => r.contains(p),
Shape::Circle(c) => c.contains(p),
Shape::Line(l) => l.contains(p),
}
}
pub fn draw(&self, canvas: &mut Canvas) {
match self {
Shape::Rect(r) => r.draw(canvas),
Shape::Circle(c) => c.draw(canvas),
Shape::Line(l) => l.draw(canvas),
}
}
/// Draws a blue highlight around the shape. Call it before `draw`.
pub fn draw_selection(&self, canvas: &mut Canvas) {
match self {
Shape::Rect(r) => r.draw_outline(canvas, 3.0, SELECTION_BLUE),
Shape::Circle(c) => Circle {
radius: c.radius + 3.0,
color: SELECTION_BLUE,
..*c
}
.draw(canvas),
Shape::Line(l) => {
// A thick line: the same line shifted by one pixel around.
for dx in -1..=1 {
for dy in -1..=1 {
let offset = Vec2::new(dx as f32, dy as f32);
Line::from_points(l.start + offset, l.end + offset, SELECTION_BLUE)
.draw(canvas);
}
}
for end in [l.start, l.end] {
canvas.fill_circle(end.x as usize, end.y as usize, 5, SELECTION_BLUE);
}
}
}
}
/// Moves the shape by `delta`.
pub fn translate(&mut self, delta: Vec2) {
match self {
Shape::Rect(r) => r.pos = r.pos + delta,
Shape::Circle(c) => c.center = c.center + delta,
Shape::Line(l) => {
l.start = l.start + delta;
l.end = l.end + delta;
}
}
}
}
/// Index of the topmost shape under `p`. Shapes drawn last are on top,
/// so we search from the end of the list.
pub fn shape_under(shapes: &[Shape], p: Vec2) -> Option<usize> {
for (i, shape) in shapes.iter().enumerate().rev() {
if shape.contains(p) {
return Some(i);
}
}
None
}cargo runDraw a few shapes, making them overlap. Click on one of them: it gets a blue outline. Hold the button and move the mouse: it follows. When two shapes overlap, it's the one on top that gets picked. Click on empty space to deselect, or press Delete to erase the selected shape. For lines, no need to aim at the exact pixel: a click a few pixels away is enough.
Exercises#
-
Add a D key that deselects the shape, without erasing anything.
-
Move the selected shape by one pixel with the arrow keys, to place it precisely. This time, we want the shape to keep moving if you hold the arrow down, like a letter repeating in a word processor: that's what
KeyRepeat::Yesdoes. -
Bonus: add an F key that brings the selected shape to the front, on top of all the others. Watch out for the index: once the shape has moved in the list,
selectedmust still point to it.
Solutions
1. In handle_keys, after the if mouse_down { return; }:
if pressed(Key::D) {
self.selected = None;
}2. We can't use the pressed closure, which asks for KeyRepeat::No. So we call is_key_pressed directly, still after the if mouse_down { return; } so we don't move a shape while dragging it with the mouse:
if let Some(i) = self.selected {
let mut delta = Vec2::ZERO;
if window.is_key_pressed(Key::Left, KeyRepeat::Yes) {
delta.x -= 1.0;
}
if window.is_key_pressed(Key::Right, KeyRepeat::Yes) {
delta.x += 1.0;
}
if window.is_key_pressed(Key::Up, KeyRepeat::Yes) {
delta.y -= 1.0;
}
if window.is_key_pressed(Key::Down, KeyRepeat::Yes) {
delta.y += 1.0;
}
self.shapes[i].translate(delta);
}3. The shape on top is the last one in the list. We take it out of its place with remove, which returns it, then put it back at the end with push. Its index is now the last one in the list:
if pressed(Key::F)
&& let Some(i) = self.selected
{
let shape = self.shapes.remove(i);
self.shapes.push(shape);
self.selected = Some(self.shapes.len() - 1);
}Without the last line, selected would point to the shape that took its old place, and the blue outline would jump to another shape.
Recap#
- Each shape can tell whether a point is inside it with
contains. For the line, we look for the point on the line closest to the mouse, and accept the click if it's within a few pixels. - We look for the shape under the mouse starting from the end of the list, because the last shape drawn is the one on top.
- We remember the selected shape by its index in the list. A reference would lock the list for as long as it exists: Rust forbids modifying a
Vecwhile you hold a&mutreference to one of its elements. - An index doesn't borrow anything, but it can become wrong if the list changes. It's up to us to keep it valid.
- A
matchon&mutgives mutable references to the contents of the variants. You read and change the value with*. Option::takereturns the content of anOptionand sets it back toNone.
In chapter 8, we add a toolbar with buttons, to switch tools with the mouse.