Switching tools with R, C and L works, but you have to know the shortcuts. In this chapter, we add three buttons in the top-right corner of the window, one per tool, each with a small icon. Clicking a button picks the tool, and the button of the active tool gets a black border.
The keyboard shortcuts stay, of course. We're just adding a second way to choose.
A button, really, is a rectangle that we draw, and on which we check whether the mouse clicked. We already have everything we need: Rect can draw itself, draw a border, and tell whether a point is inside. This chapter is mostly a matter of organization.
A module for the interface#
The buttons aren't shapes of the drawing, they're part of the interface. We put them in a new module, ui (for user interface), which will also hold the color picker in chapter 9. Create the folder src/ui/ with a file src/ui/mod.rs:
mod toolbar;
pub use toolbar::Toolbar;It's the same idea as shapes/mod.rs: the module declares its toolbar submodule and makes Toolbar available as ui::Toolbar. Don't forget to declare the module in src/main.rs, with the others:
mod shapes;
mod ui;
mod vec2;The toolbar#
Create src/ui/toolbar.rs. We start with the struct:
use crate::canvas::Canvas;
use crate::color::{BLACK, DARK_GRAY, LIGHT_GRAY, WHITE};
use crate::shapes::{Rect, Shape, Tool};
use crate::vec2::Vec2;
const BUTTON_SIZE: f32 = 40.0;
const TOP: f32 = 20.0;
/// The buttons in the top-right corner, one per tool.
pub struct Toolbar {
pub tool_buttons: [(Tool, Rect); 3],
}[(Tool, Rect); 3] is an array of three elements, and each element is a (Tool, Rect) tuple: a tool and the rectangle of its button. Unlike a Vec, an array has a fixed size, written in its type. That's perfect here: we have three tools, no more, no less.
We could have written three fields, rect_button, circle_button and line_button. But then we'd have had to write the drawing code three times, and the click check three times. With an array, we write a single loop.
We also need three new colors for the buttons. Add them to src/color.rs, next to the others:
pub const BLACK: u32 = 0x00000000;
pub const LIGHT_GRAY: u32 = 0x00AAAAAA;
pub const DARK_GRAY: u32 = 0x00444444;Placing the buttons#
impl Toolbar {
pub fn new(canvas_width: f32) -> Toolbar {
let button = |x: f32| Rect::new(x, TOP, BUTTON_SIZE, BUTTON_SIZE, WHITE);
Toolbar {
tool_buttons: [
(Tool::Rect, button(canvas_width - 230.0)),
(Tool::Circle, button(canvas_width - 180.0)),
(Tool::Line, button(canvas_width - 130.0)),
],
}
}
}The three buttons only differ in their horizontal position. Rather than writing Rect::new(..., TOP, BUTTON_SIZE, BUTTON_SIZE, WHITE) three times, we create a button closure that takes x and makes the button, like the one in chapter 6 that tested the keys.
The positions are computed from the right edge of the window: we receive its width, and place the buttons 230, 180 and 130 pixels from that edge, 50 pixels apart for 40-pixel buttons. If we ever change the size of the window, the toolbar stays stuck to the right. We leave some room to the right of the buttons: chapter 9 will put the color button there.
Which button was clicked?#
Solution
/// The tool whose button is under `p`, if any.
pub fn tool_at(&self, p: Vec2) -> Option<Tool> {
for (tool, button) in &self.tool_buttons {
if button.contains(p) {
return Some(*tool);
}
}
None
}for (tool, button) in &self.tool_buttons goes through the array without taking it, thanks to the &. Each tuple is destructured into two variables, which are references: tool is a &Tool. To return the tool itself, we write *tool. That works because Tool is Copy: we return a copy.
Drawing the buttons#
pub fn draw(&self, canvas: &mut Canvas, active_tool: Tool) {
for (tool, button) in &self.tool_buttons {
if *tool == active_tool {
button.draw_outline(canvas, 6.0, BLACK);
} else {
button.draw_outline(canvas, 3.0, LIGHT_GRAY);
}
button.draw(canvas);
tool_icon(*tool, button).draw(canvas);
}
}For each button, we first draw a border, with the draw_outline method we wrote in chapter 7 for the selection: black and thick for the active tool, gray and thin for the others. Then the white background of the button on top, then the icon.
The comparison *tool == active_tool is possible because Tool derives PartialEq. We added it in chapter 6 without using it, and this is where it comes in.
The icons#
For the icons, no need for images: the icon of a tool is a small shape drawn with that tool. We already have Shape::from_points, which builds a shape from two points, so we just need to pick the right ones. Add this function at the end of the file, after the impl block:
/// The icon of a tool is simply a small shape drawn with that tool.
fn tool_icon(tool: Tool, button: &Rect) -> Shape {
let (a, b) = match tool {
Tool::Rect => (Vec2::new(8.0, 12.0), Vec2::new(32.0, 28.0)),
Tool::Circle => (Vec2::new(20.0, 20.0), Vec2::new(32.0, 20.0)),
Tool::Line => (Vec2::new(8.0, 32.0), Vec2::new(32.0, 8.0)),
};
Shape::from_points(tool, button.pos + a, button.pos + b, DARK_GRAY)
}The match returns a tuple of two points, which we destructure right away into a and b. These points are given relative to the corner of the button, which is 40 pixels wide: for the rectangle, from (8, 12) to (32, 28), a 24 by 16 rectangle in the middle of the button. For the circle, the center (20, 20) and a point on the edge 12 pixels away. For the line, a diagonal. We add button.pos to switch to window coordinates.
The function isn't pub: only this file uses it, the rest of the program doesn't need to know about it.
Hooking the toolbar into the app#
In src/app.rs, add the import, the field and its starting value:
use crate::ui::Toolbar;toolbar: Toolbar,toolbar: Toolbar::new(width as f32),Two things are left to do: react to clicks on the buttons, and draw them.
For clicks, it happens in on_press. A click can now land on a button, on a shape, or on empty space. We test the buttons first:
/// The mouse button was just pressed: decide what this drag will do.
fn on_press(&mut self, p: Vec2) {
self.action = Action::Idle;
if let Some(tool) = self.toolbar.tool_at(p) {
self.tool = tool;
} else 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 };
}
}We first set the action back to Idle. If the click lands on a button, we switch tools and that's it: the action stays Idle, so dragging the mouse after clicking a button draws nothing.
For drawing, we add one line at the very end of render, after the preview:
self.toolbar.draw(&mut self.canvas, self.tool);Here's the full src/ui/toolbar.rs file:
use crate::canvas::Canvas;
use crate::color::{BLACK, DARK_GRAY, LIGHT_GRAY, WHITE};
use crate::shapes::{Rect, Shape, Tool};
use crate::vec2::Vec2;
const BUTTON_SIZE: f32 = 40.0;
const TOP: f32 = 20.0;
/// The buttons in the top-right corner, one per tool.
pub struct Toolbar {
pub tool_buttons: [(Tool, Rect); 3],
}
impl Toolbar {
pub fn new(canvas_width: f32) -> Toolbar {
let button = |x: f32| Rect::new(x, TOP, BUTTON_SIZE, BUTTON_SIZE, WHITE);
Toolbar {
tool_buttons: [
(Tool::Rect, button(canvas_width - 230.0)),
(Tool::Circle, button(canvas_width - 180.0)),
(Tool::Line, button(canvas_width - 130.0)),
],
}
}
/// The tool whose button is under `p`, if any.
pub fn tool_at(&self, p: Vec2) -> Option<Tool> {
for (tool, button) in &self.tool_buttons {
if button.contains(p) {
return Some(*tool);
}
}
None
}
pub fn draw(&self, canvas: &mut Canvas, active_tool: Tool) {
for (tool, button) in &self.tool_buttons {
if *tool == active_tool {
button.draw_outline(canvas, 6.0, BLACK);
} else {
button.draw_outline(canvas, 3.0, LIGHT_GRAY);
}
button.draw(canvas);
tool_icon(*tool, button).draw(canvas);
}
}
}
/// The icon of a tool is simply a small shape drawn with that tool.
fn tool_icon(tool: Tool, button: &Rect) -> Shape {
let (a, b) = match tool {
Tool::Rect => (Vec2::new(8.0, 12.0), Vec2::new(32.0, 28.0)),
Tool::Circle => (Vec2::new(20.0, 20.0), Vec2::new(32.0, 20.0)),
Tool::Line => (Vec2::new(8.0, 32.0), Vec2::new(32.0, 8.0)),
};
Shape::from_points(tool, button.pos + a, button.pos + b, DARK_GRAY)
}cargo runThe three buttons appear in the top-right corner, with the rectangle one outlined in black. Click the circle button: the black border moves to it, and you're now drawing circles. The R, C and L keys still work, and the border follows when you switch tools with the keyboard too, since the toolbar is redrawn at each frame with the current tool.
Exercises#
-
Move the toolbar to the left edge of the window, with the buttons stacked vertically instead of side by side.
-
Add a fourth button, "clear all", to the left of the other three. It isn't a tool: clicking it empties the list of shapes. For its icon, draw a cross with two lines.
-
Bonus: when the mouse hovers over a button, draw its border in dark gray instead of light gray, to show it can be clicked. You'll need to pass the mouse position to
draw.
Solutions
1. Only new changes. The buttons keep the same horizontal position, and it's their vertical position that varies. You need a closure that takes y instead of x:
pub fn new(_canvas_width: f32) -> Toolbar {
let button = |y: f32| Rect::new(20.0, y, BUTTON_SIZE, BUTTON_SIZE, WHITE);
Toolbar {
tool_buttons: [
(Tool::Rect, button(20.0)),
(Tool::Circle, button(70.0)),
(Tool::Line, button(120.0)),
],
}
}The window width is no longer used. The _ in front of canvas_width tells the compiler it's on purpose, and avoids a warning.
2. One more field in Toolbar, initialized in new with clear_button: button(canvas_width - 280.0):
pub struct Toolbar {
pub tool_buttons: [(Tool, Rect); 3],
pub clear_button: Rect,
}At the end of draw, its drawing, with a cross:
let b = self.clear_button;
b.draw_outline(canvas, 3.0, LIGHT_GRAY);
b.draw(canvas);
let (x0, y0) = (b.pos.x as i32 + 10, b.pos.y as i32 + 10);
let (x1, y1) = (x0 + 20, y0 + 20);
canvas.draw_line(x0, y0, x1, y1, DARK_GRAY);
canvas.draw_line(x0, y1, x1, y0, DARK_GRAY);And in on_press in app.rs, one more case, first:
if self.toolbar.clear_button.contains(p) {
self.shapes.clear();
self.selected = None;
} else if let Some(tool) = self.toolbar.tool_at(p) {
// ...You also need to set selected back to None: otherwise, it would keep the index of a shape that no longer exists.
3. draw receives the mouse position, and picks the border color depending on whether the mouse is on the button:
pub fn draw(&self, canvas: &mut Canvas, active_tool: Tool, mouse: Vec2) {
for (tool, button) in &self.tool_buttons {
if *tool == active_tool {
button.draw_outline(canvas, 6.0, BLACK);
} else if button.contains(mouse) {
button.draw_outline(canvas, 3.0, DARK_GRAY);
} else {
button.draw_outline(canvas, 3.0, LIGHT_GRAY);
}
button.draw(canvas);
tool_icon(*tool, button).draw(canvas);
}
}In render, the call becomes self.toolbar.draw(&mut self.canvas, self.tool, self.mouse);.
Recap#
- A button is a
Rectthat we draw and on which we test clicks withcontains. - An array
[T; N]has a fixed size, known at compile time. Storing the buttons in an array lets us draw them and test clicks with a single loop. for (a, b) in &arraygoes through an array of tuples without taking it, and destructures each tuple into two references.- A function without
pubcan only be used in its own file. - What's drawn last shows up on top. What's on top should also be tested first when you click.
In chapter 9, we add a color button that opens a picker, so we can finally draw in something other than blue.