Since chapter 5, all our shapes have been the same blue. In this chapter, we add a fourth button to the toolbar, which shows the current color. Clicking it opens a color picker: a vertical bar with every hue, and a big square to choose whether the color is vivid or pale, light or dark. Click the button again to close it.
It's the same kind of picker as in most drawing programs. To build it, we first need to understand another way of describing a color.
Another way to describe a color#
Until now, we described a color with three numbers: the amount of red, green and blue. That's what the screen and our canvas understand, but it's not very natural for choosing a color. If you want a slightly paler orange, which numbers should you change? Hard to say.
The HSV model describes the same color differently, with three numbers that better match the way we think:
- the hue: which color, around the circle red, yellow, green, cyan, blue, magenta, and back to red. It's measured in degrees, from 0 to 360: 0 for red, 120 for green, 240 for blue;
- the saturation: whether the color is vivid or washed out. From 0 (gray) to 1 (the pure color);
- the value: whether it's light or dark. From 0 (black) to 1 (full brightness).
Our picker follows exactly this split. The vertical bar chooses the hue, and the big square chooses the saturation (from left to right) and the value (from bottom to top).
Since the canvas only understands RGB, we need a function that converts an HSV color into a u32. Add it at the end of src/color.rs:
/// Converts a color from HSV (hue in degrees, saturation and value in [0, 1]).
pub fn hsv_to_u32(h: f32, s: f32, v: f32) -> u32 {
let h = h.rem_euclid(360.0);
let c = s * v;
let h1 = h / 60.0;
let x = c * (1.0 - (h1 % 2.0 - 1.0).abs());
let m = v - c;
let (r, g, b) = match h1 as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
rgb_to_u32(
((r + m) * 255.0) as u8,
((g + m) * 255.0) as u8,
((b + m) * 255.0) as u8,
)
}It's the standard conversion formula, we won't prove it. But here's the idea, so the lines aren't a mystery.
The first line brings the hue back between 0 and 360, in case we pass it, say, 370, which is the same hue as 10: rem_euclid(360.0) is the remainder of the division by 360.
The hue circle is then split into six parts of 60 degrees. h1 says which part we're in (from 0 to 5) and how far along that part we are. In each part, one of the three components is at its maximum (c), one is at zero, and the third (x) changes gradually to go from one color to the next. For example, between 0 and 60 degrees, we go from red to yellow: red stays at its maximum, blue at zero, and green rises little by little.
The match picks the right order depending on the part. It returns a tuple of three numbers, which we destructure right away into r, g and b. Finally, m adds the same amount to all three components, which lightens the color. The components are between 0 and 1, so we multiply them by 255 to turn them into bytes.
The picker#
The picker is part of the interface, so it goes in the ui module. Create src/ui/color_picker.rs:
use crate::canvas::Canvas;
use crate::color::{BLACK, WHITE, hsv_to_u32};
use crate::shapes::Rect;
use crate::vec2::Vec2;
const SIZE: f32 = 360.0;
const BAR_WIDTH: f32 = 20.0;
const GAP: f32 = 20.0;
const MARGIN: f32 = 20.0;
/// An HSV color picker: a vertical hue bar and a saturation/value square.
pub struct ColorPicker {
pub open: bool,
/// In degrees, [0, 360).
hue: f32,
/// In [0, 1].
sat: f32,
/// In [0, 1].
val: f32,
hue_bar: Rect,
sv_square: Rect,
}The picker remembers whether it's open, the chosen color as hue, saturation and value, and the position of its two areas: the bar and the square. Only open is pub, because the app will need to open and close it. The rest is the picker's own business: we access it through methods.
Declare the new module in src/ui/mod.rs:
mod color_picker;
mod toolbar;
pub use color_picker::ColorPicker;
pub use toolbar::Toolbar;Placing the two areas#
impl ColorPicker {
pub fn new(canvas_width: f32, canvas_height: f32) -> ColorPicker {
let bar_x = canvas_width - MARGIN - BAR_WIDTH;
let top = (canvas_height - SIZE) / 2.0;
ColorPicker {
open: false,
hue: 0.0,
sat: 0.0,
val: 0.0,
hue_bar: Rect::new(bar_x, top, BAR_WIDTH, SIZE, WHITE),
sv_square: Rect::new(bar_x - GAP - SIZE, top, SIZE, SIZE, WHITE),
}
}
pub fn color(&self) -> u32 {
hsv_to_u32(self.hue, self.sat, self.val)
}
}The bar sits against the right edge of the window, with a margin, and the square just to its left. Both are centered vertically. They're 360 pixels tall: one pixel per degree of hue for the bar.
The picker starts closed, with a value of 0, that is, black. color gives the chosen color, converted to a u32.
We reuse Rect to describe the two areas, as for the buttons in chapter 8. That gives us contains for free. Add two methods that tell whether a point is on one of the areas, only when the picker is open:
pub fn is_on_hue_bar(&self, p: Vec2) -> bool {
self.open && self.hue_bar.contains(p)
}
pub fn is_on_sv_square(&self, p: Vec2) -> bool {
self.open && self.sv_square.contains(p)
}Choosing with the mouse#
When you click or drag on the bar, the height of the mouse gives the hue: at the very top, 0 degrees, at the very bottom, 360.
/// Sets the hue from the mouse height on the bar.
pub fn pick_hue(&mut self, p: Vec2) {
let t = (p.y - self.hue_bar.pos.y) / self.hue_bar.size.y;
self.hue = t.clamp(0.0, 0.999) * 360.0;
}t says where the mouse is along the height of the bar: 0 at the top, 1 at the bottom. If you drag and the mouse leaves the bar, t can become negative or larger than 1. clamp brings it back within the limits, so the hue stays valid even when you go too far. We stop just short of 1, at 0.999, so the hue stays below 360.
Solution
/// Sets saturation (horizontal) and value (vertical) from the mouse.
pub fn pick_sat_val(&mut self, p: Vec2) {
let local = p - self.sv_square.pos;
self.sat = (local.x / self.sv_square.size.x).clamp(0.0, 1.0);
self.val = 1.0 - (local.y / self.sv_square.size.y).clamp(0.0, 1.0);
}local is the mouse position relative to the corner of the square. We divide by the size to get a number between 0 and 1, and for the value, we take 1.0 - ... so it decreases going down.
Drawing the picker#
Last method, and the longest. It draws the bar, the square, and a small cursor on each, to show the chosen color.
pub fn draw(&self, canvas: &mut Canvas) {
if !self.open {
return;
}
// Hue bar: one hue per row.
self.hue_bar.draw_outline(canvas, 2.0, BLACK);
let Rect { pos, size, .. } = self.hue_bar;
let rows = size.y as usize;
for row in 0..rows {
let hue = row as f32 / rows as f32 * 360.0;
let color = hsv_to_u32(hue, 1.0, 1.0);
canvas.fill_rect(
pos.x as usize,
pos.y as usize + row,
size.x as usize,
1,
color,
);
}
// Saturation/value square for the current hue.
self.sv_square.draw_outline(canvas, 2.0, BLACK);
let Rect { pos, size, .. } = self.sv_square;
let (w, h) = (size.x as i32, size.y as i32);
for i in 0..w {
let s = i as f32 / w as f32;
for j in 0..h {
let v = 1.0 - j as f32 / h as f32;
canvas.put_pixel(
pos.x as i32 + i,
pos.y as i32 + j,
hsv_to_u32(self.hue, s, v),
);
}
}
// Cursor on the square.
let cursor = pos + Vec2::new(self.sat * size.x, (1.0 - self.val) * size.y);
let (cx, cy) = (cursor.x as usize, cursor.y as usize);
canvas.fill_circle(cx, cy, 10, BLACK);
canvas.fill_circle(cx, cy, 9, WHITE);
canvas.fill_circle(cx, cy, 7, self.color());
// Cursor on the hue bar.
let bar = self.hue_bar;
let hx = bar.pos.x as usize;
let hy = (bar.pos.y + self.hue / 360.0 * bar.size.y) as usize;
canvas.fill_circle(hx, hy, 10, BLACK);
canvas.fill_circle(hx, hy, 8, hsv_to_u32(self.hue, 1.0, 1.0));
}When the picker is closed, we draw nothing.
The bar: each row of pixels gets a hue, from 0 at the top to 360 at the bottom, with saturation and value at their maximum to get the most vivid colors. We draw each row as a rectangle one pixel tall.
let Rect { pos, size, .. } = self.hue_bar; is struct destructuring: it takes the pos and size fields out into two variables of the same name, and the .. ignores the other fields. It saves us from writing self.hue_bar.pos and self.hue_bar.size everywhere.
The square: for each pixel, the saturation depends on the column and the value on the row, with the hue chosen in the bar. So the square changes color when you change the hue. That's 360 × 360, almost 130,000 pixels computed at each frame when the picker is open, but for our small app, that's no problem.
The cursors: on the square, three stacked discs, black, white and then the chosen color, so the cursor stands out whatever the color underneath. On the bar, a black disc and a disc of the hue, placed on the left edge of the bar, at the height of the chosen hue.
The color button#
In src/ui/toolbar.rs, we add a button next to the tools. It's not in the tool_buttons array, since it isn't a tool: it gets its own field.
/// The buttons in the top-right corner: one per tool, plus the color button.
pub struct Toolbar {
pub tool_buttons: [(Tool, Rect); 3],
pub color_button: Rect,
}In new, it goes to the right of the other three, 60 pixels from the edge. That's the space we left free in chapter 8:
Toolbar {
tool_buttons: [
(Tool::Rect, button(canvas_width - 230.0)),
(Tool::Circle, button(canvas_width - 180.0)),
(Tool::Line, button(canvas_width - 130.0)),
],
color_button: button(canvas_width - 60.0),
}draw now receives the current color, to show it in the button. At the end of draw, after the loop over the tools:
pub fn draw(&self, canvas: &mut Canvas, active_tool: Tool, current_color: u32) {
// ...
self.color_button.draw_outline(canvas, 6.0, BLACK);
self.color_button.draw_outline(canvas, 3.0, LIGHT_GRAY);
Rect {
color: current_color,
..self.color_button
}
.draw(canvas);
}Two borders, a thick black one and then a thinner gray one on top, for a two-tone frame. Then the button itself, filled with the current color: we reuse the button's rectangle, only changing its color, with the .. syntax from chapter 7.
Hooking up the picker#
In src/action.rs, two new variants, for when we drag on the bar or on the square:
PickingHue,
PickingSatVal,In src/app.rs, the app now has a picker. Replace the Toolbar import with use crate::ui::{ColorPicker, Toolbar};, and add a picker: ColorPicker field, just before color. We no longer need rgb_to_u32 in this file, remove it from the crate::color import.
In new, the starting color is no longer the fixed blue from chapter 5, but the picker's. So we need to create the picker before the rest:
pub fn new(width: usize, height: usize) -> App {
let picker = ColorPicker::new(width as f32, height as f32);
App {
// ...
toolbar: Toolbar::new(width as f32),
color: picker.color(),
picker,
// ...
}
}color: picker.color() reads the picker's color, then picker moves it into the app. The order matters: once picker has been moved into the struct, the variable can no longer be used, so we couldn't call picker.color() after that. Writing picker on its own is shorthand for picker: picker, as for the other fields.
In on_press, two more cases: a click on the color button opens or closes the picker, and a click on the bar or the square starts choosing. We test them before the shapes, since the picker is drawn on top:
if self.toolbar.color_button.contains(p) {
self.picker.open = !self.picker.open;
} else if let Some(tool) = self.toolbar.tool_at(p) {
self.tool = tool;
} else if self.picker.is_on_hue_bar(p) {
self.action = Action::PickingHue;
} else if self.picker.is_on_sv_square(p) {
self.action = Action::PickingSatVal;
} else if let Some(i) = shape_under(&self.shapes, p) {
// ...!self.picker.open is the opposite of the current value: open becomes closed, and closed becomes open.
In on_drag, two more arms in the match, and the color update:
/// 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::PickingHue => self.picker.pick_hue(p),
Action::PickingSatVal => self.picker.pick_sat_val(p),
Action::Idle | Action::Drawing { .. } => {}
}
if self.picker.open {
self.color = self.picker.color();
}
}As long as the button is held and the picker is open, we copy the picker's color into self.color at each frame. That's the color the app uses for new shapes and for the color button.
Finally, in render, we pass the color to the toolbar, then draw the picker last of all, on top of everything else:
self.toolbar.draw(&mut self.canvas, self.tool, self.color);
self.picker.draw(&mut self.canvas);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};
use crate::shapes::{Shape, Tool, shape_under};
use crate::ui::{ColorPicker, Toolbar};
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>,
toolbar: Toolbar,
picker: ColorPicker,
color: u32,
mouse: Vec2,
was_down: bool,
}
impl App {
pub fn new(width: usize, height: usize) -> App {
let picker = ColorPicker::new(width as f32, height as f32);
App {
canvas: Canvas::new(width, height),
shapes: Vec::new(),
tool: Tool::Rect,
action: Action::Idle,
selected: None,
toolbar: Toolbar::new(width as f32),
color: picker.color(),
picker,
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) {
self.action = Action::Idle;
if self.toolbar.color_button.contains(p) {
self.picker.open = !self.picker.open;
} else if let Some(tool) = self.toolbar.tool_at(p) {
self.tool = tool;
} else if self.picker.is_on_hue_bar(p) {
self.action = Action::PickingHue;
} else if self.picker.is_on_sv_square(p) {
self.action = Action::PickingSatVal;
} 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 };
}
}
/// 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::PickingHue => self.picker.pick_hue(p),
Action::PickingSatVal => self.picker.pick_sat_val(p),
Action::Idle | Action::Drawing { .. } => {}
}
if self.picker.open {
self.color = self.picker.color();
}
}
/// 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);
}
self.toolbar.draw(&mut self.canvas, self.tool, self.color);
self.picker.draw(&mut self.canvas);
}
}The full src/ui/color_picker.rs file
use crate::canvas::Canvas;
use crate::color::{BLACK, WHITE, hsv_to_u32};
use crate::shapes::Rect;
use crate::vec2::Vec2;
const SIZE: f32 = 360.0;
const BAR_WIDTH: f32 = 20.0;
const GAP: f32 = 20.0;
const MARGIN: f32 = 20.0;
/// An HSV color picker: a vertical hue bar and a saturation/value square.
pub struct ColorPicker {
pub open: bool,
/// In degrees, [0, 360).
hue: f32,
/// In [0, 1].
sat: f32,
/// In [0, 1].
val: f32,
hue_bar: Rect,
sv_square: Rect,
}
impl ColorPicker {
pub fn new(canvas_width: f32, canvas_height: f32) -> ColorPicker {
let bar_x = canvas_width - MARGIN - BAR_WIDTH;
let top = (canvas_height - SIZE) / 2.0;
ColorPicker {
open: false,
hue: 0.0,
sat: 0.0,
val: 0.0,
hue_bar: Rect::new(bar_x, top, BAR_WIDTH, SIZE, WHITE),
sv_square: Rect::new(bar_x - GAP - SIZE, top, SIZE, SIZE, WHITE),
}
}
pub fn color(&self) -> u32 {
hsv_to_u32(self.hue, self.sat, self.val)
}
pub fn is_on_hue_bar(&self, p: Vec2) -> bool {
self.open && self.hue_bar.contains(p)
}
pub fn is_on_sv_square(&self, p: Vec2) -> bool {
self.open && self.sv_square.contains(p)
}
/// Sets the hue from the mouse height on the bar.
pub fn pick_hue(&mut self, p: Vec2) {
let t = (p.y - self.hue_bar.pos.y) / self.hue_bar.size.y;
self.hue = t.clamp(0.0, 0.999) * 360.0;
}
/// Sets saturation (horizontal) and value (vertical) from the mouse.
pub fn pick_sat_val(&mut self, p: Vec2) {
let local = p - self.sv_square.pos;
self.sat = (local.x / self.sv_square.size.x).clamp(0.0, 1.0);
self.val = 1.0 - (local.y / self.sv_square.size.y).clamp(0.0, 1.0);
}
pub fn draw(&self, canvas: &mut Canvas) {
if !self.open {
return;
}
// Hue bar: one hue per row.
self.hue_bar.draw_outline(canvas, 2.0, BLACK);
let Rect { pos, size, .. } = self.hue_bar;
let rows = size.y as usize;
for row in 0..rows {
let hue = row as f32 / rows as f32 * 360.0;
let color = hsv_to_u32(hue, 1.0, 1.0);
canvas.fill_rect(
pos.x as usize,
pos.y as usize + row,
size.x as usize,
1,
color,
);
}
// Saturation/value square for the current hue.
self.sv_square.draw_outline(canvas, 2.0, BLACK);
let Rect { pos, size, .. } = self.sv_square;
let (w, h) = (size.x as i32, size.y as i32);
for i in 0..w {
let s = i as f32 / w as f32;
for j in 0..h {
let v = 1.0 - j as f32 / h as f32;
canvas.put_pixel(
pos.x as i32 + i,
pos.y as i32 + j,
hsv_to_u32(self.hue, s, v),
);
}
}
// Cursor on the square.
let cursor = pos + Vec2::new(self.sat * size.x, (1.0 - self.val) * size.y);
let (cx, cy) = (cursor.x as usize, cursor.y as usize);
canvas.fill_circle(cx, cy, 10, BLACK);
canvas.fill_circle(cx, cy, 9, WHITE);
canvas.fill_circle(cx, cy, 7, self.color());
// Cursor on the hue bar.
let bar = self.hue_bar;
let hx = bar.pos.x as usize;
let hy = (bar.pos.y + self.hue / 360.0 * bar.size.y) as usize;
canvas.fill_circle(hx, hy, 10, BLACK);
canvas.fill_circle(hx, hy, 8, hsv_to_u32(self.hue, 1.0, 1.0));
}
}cargo runThe color button appears to the right of the tools, black to start with. So new shapes are black. Click the button: the picker opens. Click or drag on the bar to choose a hue, then in the square to choose its shade. The button takes the chosen color, and so do the shapes you draw next. Click the button again to close the picker.
Exercises#
-
Add a keyboard shortcut, the P key, that opens or closes the picker, like clicking the color button.
-
Make choosing a color also change the color of the selected shape, if there is one. You'll need a
set_colormethod onShape. -
Bonus: add a small palette of six ready-made colors, below the toolbar. Clicking a color in the palette picks it directly, without going through the picker.
Solutions
1. In handle_keys, with the other keys:
if pressed(Key::P) {
self.picker.open = !self.picker.open;
}2. In src/shapes/mod.rs, a method that changes the color, whatever the shape:
pub fn set_color(&mut self, color: u32) {
match self {
Shape::Rect(r) => r.color = color,
Shape::Circle(c) => c.color = color,
Shape::Line(l) => l.color = color,
}
}Then in on_drag, where we update the color:
if self.picker.open {
self.color = self.picker.color();
if let Some(i) = self.selected {
self.shapes[i].set_color(self.color);
}
}Clicking in the picker doesn't deselect the shape, since those clicks are handled before the ones on shapes in on_press. So you can select a shape, open the picker and recolor it live.
3. In Toolbar, an array of six small color squares, filled in new. The swatch closure places them side by side, below the buttons:
pub palette: [Rect; 6],let swatch = |i: f32, color: u32| Rect::new(canvas_width - 230.0 + i * 35.0, 75.0, 25.0, 25.0, color);
// in Toolbar { ... }:
palette: [
swatch(0.0, rgb_to_u32(0, 0, 0)),
swatch(1.0, rgb_to_u32(220, 50, 50)),
swatch(2.0, rgb_to_u32(240, 160, 30)),
swatch(3.0, rgb_to_u32(50, 170, 80)),
swatch(4.0, rgb_to_u32(50, 120, 220)),
swatch(5.0, rgb_to_u32(150, 70, 190)),
],You need to import rgb_to_u32 at the top of toolbar.rs. To draw them, at the end of draw:
for swatch in &self.palette {
swatch.draw_outline(canvas, 2.0, LIGHT_GRAY);
swatch.draw(canvas);
}And in on_press, one more case, before the tools:
} else if let Some(swatch) = self.toolbar.palette.iter().find(|s| s.contains(p)) {
self.color = swatch.color;
} else if let Some(tool) = self.toolbar.tool_at(p) {find goes through the palette and returns the first square that contains the point, or None. Careful: if the picker is open, the color chosen from the palette will be replaced by the picker's on the next drag. The simplest fix is to close the picker at the same time, with self.picker.open = false;.
Recap#
- The HSV model describes a color by its hue, saturation and value. It's more natural for choosing a color, and we convert it to RGB to display it.
clampbrings a number back between two limits. We use it so that a mouse leaving an area still gives a valid value.- A
matchcan return a tuple, which you destructure right away:let (r, g, b) = match ... { ... };. let Rect { pos, size, .. } = rect;takes fields of a struct out into variables.- Once a variable has been moved into a struct, it can no longer be used: you have to use it before.
In chapter 10, we save the drawing to an image file, without the toolbar or the picker.