//! Paint with a finger, built from a view: a canvas that fills the window, //! and under it the palette and an eraser, the brush sizes, and Undo, Redo //! and Clear. The drawing is the app's own pixels, which the view's //! `` shows; each stroke sends only the rectangle it touched. //! //! The drawing is kept in the app's own folder as an uncompressed BMP, so //! that Files and other programs can read it: it is saved a second after the //! last change, and when the app is left, and read back when it starts. Each //! stroke can be undone and redone, and so can Clear. #![no_std] #![no_main] extern crate alloc; use alloc::rc::Rc; use alloc::vec::Vec; use core::cell::RefCell; use pinnacle_gfx::{Canvas, Color, Rect}; use pinnacle_locale::{t, tf}; use pinnacle_rt::fs; use pinnacle_ui::{App, Event, theme}; use pinnacle_view::{IntoView, SCALE, Screen, Signal, View, el, signal}; const PALETTE: [(&str, Color); 6] = [ ("#eceff3", Color::rgb(0xec, 0xef, 0xf3)), ("#4c9aff", Color::rgb(0x4c, 0x9a, 0xff)), ("#3fb97a", Color::rgb(0x3f, 0xb9, 0x7a)), ("#e6b42e", Color::rgb(0xe6, 0xb4, 0x2e)), ("#e05a4f", Color::rgb(0xe0, 0x5a, 0x4f)), ("#8f6cf0", Color::rgb(0x8f, 0x6c, 0xf0)), ]; /// The brushes' radii in window pixels, and how big each one's dot is drawn /// on its button (logical pixels). The second is the one Paint starts with. const SIZES: [(i32, i32); 4] = [(4, 6), (8, 12), (16, 20), (32, 30)]; /// The drawing, in the app's own folder. const PICTURE: &str = "app:/drawing.bmp"; /// How long after the last change the drawing is saved. const SAVE_AFTER_MS: u64 = 1000; /// The file is written and read this much at a time. const CHUNK: usize = 4 << 20; /// How many steps can be undone, and how many bytes they may hold together: /// a Clear holds the whole drawing. const UNDO_STEPS: usize = 50; const UNDO_BYTES: usize = 32 << 20; /// A finger on the canvas, where the view saw it (logical pixels from /// the canvas's corner). #[derive(Clone, Copy)] enum Touch { Down(f32, f32), Move(f32, f32), Up, } /// What the view asks for. #[derive(Clone, Copy, PartialEq)] enum Ask { Colour(usize), Eraser, Size(usize), Undo, Redo, Clear, } /// What the bar shows: the colour and size chosen, whether the eraser is, /// and whether there is something to undo or redo. #[derive(Clone)] struct Choices { colour: Signal, erasing: Signal, size: Signal, can_undo: Signal, can_redo: Signal, } impl Choices { /// Undo and Redo, usable when there is a step for them. fn follow(&self, history: &History) { self.can_undo.set(!history.undo.is_empty()); self.can_redo.set(!history.redo.is_empty()); } } /// The ring round a chosen control, or none. fn ring(chosen: bool) -> &'static str { if chosen { "var(--m-text)" } else { "transparent" } } /// The canvas over the bar. The bar is three groups, which share a line on /// a wide window and wrap onto two on a narrow one: the swatches, round by /// their aspect ratio, and the eraser; the brush sizes, each a dot as big as /// it draws; and Undo, Redo and Clear. What is chosen is ringed. fn page( choices: &Choices, revision: Signal, touches: Rc>>, ask: &Signal>, ) -> View { let touch = |f: fn(&pinnacle_view::Event) -> Touch| { let touches = touches.clone(); move |e: &pinnacle_view::Event| { touches.borrow_mut().push(f(e)); e.prevent_default(); } }; let canvas = el("canvas") .attr("data-name", "canvas") .attr("data-revision", move || alloc::format!("{}", revision.get())) .attr("style", "flex: 1; display: block; min-height: 0") .on("pointerdown", touch(|e| Touch::Down(e.x, e.y))) .on("pointermove", touch(|e| Touch::Move(e.x, e.y))) .on("pointerup", touch(|_| Touch::Up)); // A button of the eraser's and the last group, with its text. let action = |name: &'static str, label: &'static str, what: Ask| { let ask = ask.clone(); el("button") .class("m-button") .attr("type", "button") .attr("data-name", name) .on("click", move |_| ask.set(Some(what))) .child(label) }; let group = || { el("div").attr( "style", "display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 10px", ) }; let mut colours = group(); for (i, (css, _)) in PALETTE.iter().enumerate() { let (c, ask) = (choices.clone(), ask.clone()); colours = colours.child( el("button") .attr("type", "button") .attr("data-name", alloc::format!("swatch-{i}")) .attr( "aria-label", tf("Colour {}", &[alloc::format!("{}", i + 1).as_str()]), ) .attr("style", move || { let around = ring(c.colour.get() == i && !c.erasing.get()); alloc::format!( "width: 44px; aspect-ratio: 1; border-radius: 50%; padding: 0; \ background: {css}; border: 3px solid {around}" ) }) .on("click", move |_| ask.set(Some(Ask::Colour(i)))), ); } let erasing = choices.erasing.clone(); colours = colours.child( action("eraser", t("Eraser"), Ask::Eraser) .attr( "aria-pressed", move || if erasing.get() { "true" } else { "false" }, ) .attr("style", { let erasing = choices.erasing.clone(); move || alloc::format!("border: 3px solid {}", ring(erasing.get())) }), ); let mut sizes = group(); for (i, (_, dot)) in SIZES.iter().enumerate() { let (size, ask) = (choices.size.clone(), ask.clone()); let label = tf("Brush size {}", &[alloc::format!("{}", i + 1).as_str()]); sizes = sizes.child( el("button") .attr("type", "button") .attr("data-name", alloc::format!("size-{i}")) .attr("aria-label", label) .attr("style", move || { alloc::format!( "width: 44px; aspect-ratio: 1; border-radius: 50%; padding: 0; \ background: var(--m-bg); border: 3px solid {}; \ display: flex; align-items: center; justify-content: center", ring(size.get() == i) ) }) .on("click", move |_| ask.set(Some(Ask::Size(i)))) .child(el("span").attr( "style", alloc::format!( "width: {dot}px; aspect-ratio: 1; border-radius: 50%; background: var(--m-text)" ), )), ); } let (can_undo, can_redo) = (choices.can_undo.clone(), choices.can_redo.clone()); let actions = group() .child(action("undo", t("Undo"), Ask::Undo).attr("disabled", move || !can_undo.get())) .child(action("redo", t("Redo"), Ask::Redo).attr("disabled", move || !can_redo.get())) .child(action("clear", t("Clear"), Ask::Clear)); let bar = el("div") .attr( "style", "flex: none; display: flex; flex-wrap: wrap; align-items: center; justify-content: center; \ gap: 12px 24px; padding: 12px 16px; background: var(--m-surface); \ border-top: 1px solid var(--m-border)", ) .child(colours) .child(sizes) .child(actions); el("main") .attr("style", "height: 100vh; display: flex; flex-direction: column") .child(canvas) .child(bar) .into_view() } /// The drawing: its pixels, at least as big as the canvas is in the window. /// It only grows: turning the screen keeps what is drawn off the canvas /// now, for when it is turned back. struct Drawing { pixels: Vec, width: i32, height: i32, } impl Drawing { fn blank(width: i32, height: i32) -> Drawing { let (width, height) = (width.max(0), height.max(0)); Drawing { pixels: alloc::vec![theme::BACKGROUND.0; (width * height) as usize], width, height, } } fn bounds(&self) -> Rect { Rect::new(0, 0, self.width, self.height) } fn is_blank(&self) -> bool { self.pixels.iter().all(|&p| p == theme::BACKGROUND.0) } /// Grows to cover `width` × `height`, what is drawn staying where it is. /// Returns whether it grew. fn cover(&mut self, width: i32, height: i32) -> bool { if width <= self.width && height <= self.height { return false; } let mut grown = Drawing::blank(width.max(self.width), height.max(self.height)); grown.put(self.bounds(), &self.pixels); *self = grown; true } /// The pixels of `r`, a row after another. fn take(&self, r: Rect) -> Vec { let mut out = Vec::with_capacity((r.width * r.height) as usize); for row in r.y..r.bottom() { let from = (row * self.width + r.x) as usize; out.extend_from_slice(&self.pixels[from..from + r.width as usize]); } out } /// Puts `pixels` (as [`Drawing::take`] gives them) into `r`. fn put(&mut self, r: Rect, pixels: &[u32]) { for row in 0..r.height { let to = ((r.y + row) * self.width + r.x) as usize; let from = (row * r.width) as usize; self.pixels[to..to + r.width as usize].copy_from_slice(&pixels[from..from + r.width as usize]); } } /// Dabs of the brush from `from` to `to` (canvas pixels): the /// rectangle they touched. fn stroke(&mut self, from: (i32, i32), to: (i32, i32), radius: i32, color: Color) -> Rect { let (w, h) = (self.width as u32, self.height as u32); let mut canvas = Canvas::new(&mut self.pixels, w, h); let ((px, py), (x, y)) = (from, to); // Half a brush radius apart at most. let steps = ((x - px).abs().max((y - py).abs()) / (radius / 2).max(1)).max(1); for s in 0..=steps { let (sx, sy) = (px + (x - px) * s / steps, py + (y - py) * s / steps); canvas.fill_circle(sx, sy, radius, color); } Rect::new( px.min(x) - radius, py.min(y) - radius, (x - px).abs() + 2 * radius, (y - py).abs() + 2 * radius, ) .intersect(&self.bounds()) } /// The drawing as a BMP: 24 bits a pixel, uncompressed, the bottom row /// first, each row padded to four bytes, as every reader of BMP takes. fn bmp(&self) -> Vec { let row = (self.width as usize * 3).next_multiple_of(4); let size = 54 + row * self.height as usize; let mut out = Vec::with_capacity(size); let u32le = |out: &mut Vec, v: u32| out.extend_from_slice(&v.to_le_bytes()); out.extend_from_slice(b"BM"); u32le(&mut out, size as u32); u32le(&mut out, 0); u32le(&mut out, 54); // The info header: its size, the width and height, one plane of 24 // bits, no compression, the pixels' size, 72 dpi, no palette. u32le(&mut out, 40); u32le(&mut out, self.width as u32); u32le(&mut out, self.height as u32); out.extend_from_slice(&1u16.to_le_bytes()); out.extend_from_slice(&24u16.to_le_bytes()); u32le(&mut out, 0); u32le(&mut out, (row * self.height as usize) as u32); u32le(&mut out, 2835); u32le(&mut out, 2835); u32le(&mut out, 0); u32le(&mut out, 0); for y in (0..self.height).rev() { let start = out.len(); let from = (y * self.width) as usize; for &p in &self.pixels[from..from + self.width as usize] { out.extend_from_slice(&[p as u8, (p >> 8) as u8, (p >> 16) as u8]); } out.resize(start + row, 0); } out } /// A drawing from a BMP of 24 or 32 bits a pixel, uncompressed, its rows /// either way up: what [`Drawing::bmp`] writes, and what most programs do. fn from_bmp(bytes: &[u8]) -> Option { let u16at = |at: usize| Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?)); let u32at = |at: usize| Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)); if bytes.get(0..2)? != b"BM" || u32at(30)? != 0 { return None; } let (offset, width, height) = (u32at(10)? as usize, u32at(18)? as i32, u32at(22)? as i32); let (bytes_per_pixel, top_down) = (u16at(28)? as usize / 8, height < 0); let height = height.abs(); if !(3..=4).contains(&bytes_per_pixel) || !(1..=8192).contains(&width) || !(1..=8192).contains(&height) { return None; } let row = (width as usize * bytes_per_pixel).next_multiple_of(4); let pixels = bytes.get(offset..offset + row * height as usize)?; let mut drawing = Drawing::blank(width, height); for (i, line) in pixels.chunks_exact(row).enumerate() { let y = if top_down { i } else { height as usize - 1 - i }; let to = &mut drawing.pixels[y * width as usize..(y + 1) * width as usize]; for (p, bgr) in to.iter_mut().zip(line.chunks_exact(bytes_per_pixel)) { *p = Color::rgb(bgr[2], bgr[1], bgr[0]).0; } } Some(drawing) } } /// The drawing kept in the folder, if there is one Paint can read. fn load() -> Option { let size = fs::stat(PICTURE)?.size as usize; let mut bytes = Vec::with_capacity(size); while bytes.len() < size { let piece = fs::read_at(PICTURE, bytes.len() as u64, CHUNK.min(size - bytes.len()))?; if piece.is_empty() { break; } bytes.extend_from_slice(&piece); } let drawing = Drawing::from_bmp(&bytes); if drawing.is_none() { pinnacle_rt::println!("paint: could not read the drawing"); } drawing } /// Writes the drawing out, a piece at a time; a blank one is removed /// instead, so that the folder holds no empty picture. fn save(drawing: &Drawing) { if drawing.is_blank() { fs::remove(PICTURE); pinnacle_rt::println!("paint: saved, blank"); return; } let bytes = drawing.bmp(); // Writing at an offset leaves what was beyond the end: a smaller // picture goes into a fresh file. if fs::stat(PICTURE).is_some_and(|s| s.size as usize > bytes.len()) { fs::remove(PICTURE); } let written = bytes .chunks(CHUNK) .enumerate() .all(|(i, piece)| fs::write_at(PICTURE, (i * CHUNK) as u64, piece)); if written { pinnacle_rt::println!("paint: saved {}x{}", drawing.width, drawing.height); } else { pinnacle_rt::println!("paint: could not save the drawing"); } } /// A step that can be undone: a rectangle of the drawing, and its pixels as /// they were on the step's other side. Undoing it swaps the two, which /// makes it the step that redoes it. struct Step { rect: Rect, pixels: Vec, } /// The steps to undo, the last one last, and the ones undone, to redo. #[derive(Default)] struct History { undo: Vec, redo: Vec, } impl History { /// A new step: the ones undone cannot be redone after it, and the /// oldest go once there are too many, or they hold too much. fn push(&mut self, step: Step) { self.redo.clear(); self.undo.push(step); let bytes = |h: &History| h.undo.iter().map(|s| s.pixels.len() * 4).sum::(); while self.undo.len() > 1 && (self.undo.len() > UNDO_STEPS || bytes(self) > UNDO_BYTES) { self.undo.remove(0); } } /// Undoes the last step (`back`), or redoes the last undone: returns /// whether there was one. fn step(&mut self, drawing: &mut Drawing, back: bool) -> bool { let (from, to) = if back { (&mut self.undo, &mut self.redo) } else { (&mut self.redo, &mut self.undo) }; let Some(mut step) = from.pop() else { return false; }; let now = drawing.take(step.rect); drawing.put(step.rect, &step.pixels); step.pixels = now; to.push(step); true } } /// A stroke being drawn: the drawing as it was before it, and the /// rectangle it has touched so far. struct Stroke { before: Vec, touched: Rect, } /// Ends a stroke being drawn, if any, as a step that can be undone. fn finish(stroke: &mut Option, drawing: &Drawing, history: &mut History) -> bool { let Some(s) = stroke.take() else { return false; }; if s.touched.is_empty() { return false; } let before = Drawing { pixels: s.before, width: drawing.width, height: drawing.height, }; history.push(Step { rect: s.touched, pixels: before.take(s.touched), }); true } /// Draws the screen, the canvas's part from the drawing, and records where /// the canvas is. fn draw(screen: &mut Screen, app: &mut App, drawing: &Drawing, place: &mut Rect, all: bool) -> Option { let mut canvas = app.canvas(); screen.draw_with(&mut canvas, all, &mut |name, canvas, rect| { if name == "canvas" { *place = rect; let (w, h) = (rect.width.min(drawing.width), rect.height.min(drawing.height)); for row in 0..h { let from = (row * drawing.width) as usize; let line = &drawing.pixels[from..from + w as usize]; canvas.blit(line, w, 1, rect.x, rect.y + row); } } }) } /// Draws the whole window afresh, the drawing grown to the canvas first. fn draw_all(screen: &mut Screen, app: &mut App, drawing: &mut Drawing, place: &mut Rect) { draw(screen, app, drawing, place, true); if drawing.cover(place.width, place.height) { draw(screen, app, drawing, place, true); } app.present_all(); screen.announce("paint: button "); } #[unsafe(no_mangle)] fn main(_argument: u64) -> u64 { let mut app = App::new("Paint"); let mut screen = Screen::new(app.width, app.height); let choices = Choices { colour: signal(1usize), erasing: signal(false), size: signal(1usize), can_undo: signal(false), can_redo: signal(false), }; let revision = signal(0u32); let ask: Signal> = signal(None); let touches: Rc>> = Rc::default(); screen.mount(page(&choices, revision.clone(), touches.clone(), &ask)); // Where the canvas is in the window, from the first frame on. let mut place = Rect::new(0, 0, 0, 0); let mut drawing = match load() { Some(d) => { pinnacle_rt::println!("paint: opened {}x{}", d.width, d.height); d } None => Drawing::blank(0, 0), }; draw_all(&mut screen, &mut app, &mut drawing, &mut place); pinnacle_rt::println!("paint: drawn"); let mut history = History::default(); let mut stroke: Option = None; let mut last: Option<(i32, i32)> = None; // When the drawing is to be saved: some time after its last change. let mut save_at: Option = None; loop { match app.next_event(save_at) { Event::Input(e) => { screen.input(&e); let asked = ask.get_untracked(); if asked.is_some() { ask.set(None); } let mut changed = false; match asked { Some(Ask::Colour(i)) => { choices.colour.set(i); choices.erasing.set(false); pinnacle_rt::println!("paint: colour {i}"); } Some(Ask::Eraser) => { choices.erasing.set(true); pinnacle_rt::println!("paint: eraser"); } Some(Ask::Size(i)) => { choices.size.set(i); pinnacle_rt::println!("paint: size {i}"); } Some(Ask::Undo | Ask::Redo) => { changed |= finish(&mut stroke, &drawing, &mut history); let back = asked == Some(Ask::Undo); if history.step(&mut drawing, back) { changed = true; revision.set(revision.get_untracked() + 1); pinnacle_rt::println!("paint: {}", if back { "undone" } else { "redone" }); } } Some(Ask::Clear) => { changed |= finish(&mut stroke, &drawing, &mut history); last = None; if !drawing.is_blank() { // The whole drawing, as it was, to undo it with. let blank = Drawing::blank(drawing.width, drawing.height); let before = core::mem::replace(&mut drawing, blank); history.push(Step { rect: before.bounds(), pixels: before.pixels, }); changed = true; revision.set(revision.get_untracked() + 1); pinnacle_rt::println!("paint: cleared"); } } None => {} } // The strokes go into the drawing, and straight to the // window: only the rectangle each touched is sent. let (radius, _) = SIZES[choices.size.get_untracked()]; let color = if choices.erasing.get_untracked() { theme::BACKGROUND } else { PALETTE[choices.colour.get_untracked()].1 }; let mut touched: Option = None; for t in touches.borrow_mut().drain(..) { let at = |x: f32, y: f32| ((x * SCALE) as i32, (y * SCALE) as i32); let (from, to) = match t { Touch::Down(x, y) => { changed |= finish(&mut stroke, &drawing, &mut history); stroke = Some(Stroke { before: drawing.pixels.clone(), touched: Rect::default(), }); (at(x, y), at(x, y)) } Touch::Move(x, y) => match last { Some(p) => (p, at(x, y)), None => continue, }, Touch::Up => { last = None; changed |= finish(&mut stroke, &drawing, &mut history); continue; } }; last = Some(to); let r = drawing.stroke(from, to, radius, color); if let Some(s) = &mut stroke { s.touched = s.touched.union(&r); } touched = Some(touched.map_or(r, |t| t.union(&r))); } if changed { save_at = Some(pinnacle_rt::time() + SAVE_AFTER_MS); choices.follow(&history); } let mut area = draw(&mut screen, &mut app, &drawing, &mut place, false); if let Some(r) = touched { let r = Rect::new(r.x + place.x, r.y + place.y, r.width, r.height).intersect(&place); let mut canvas = app.canvas(); canvas.set_clip(r); for row in r.y..r.bottom() { let from = ((row - place.y) * drawing.width + (r.x - place.x)) as usize; canvas.blit( &drawing.pixels[from..from + r.width as usize], r.width, 1, r.x, row, ); } area = Some(area.map_or(r, |a| a.union(&r))); } if let Some(area) = area { app.present(area); } } Event::Timeout => { save(&drawing); save_at = None; } Event::Shown(false) => { // Leaving the app saves the drawing, as the moment after a // stroke does. let due = save_at.take().is_some(); if finish(&mut stroke, &drawing, &mut history) | due { choices.follow(&history); save(&drawing); } last = None; } Event::Shown(true) | Event::Resized => { // A new window size: the drawing grows to the canvas, and // keeps what the canvas no longer shows. screen.resize(app.width, app.height); if finish(&mut stroke, &drawing, &mut history) { choices.follow(&history); save_at = Some(pinnacle_rt::time() + SAVE_AFTER_MS); } last = None; draw_all(&mut screen, &mut app, &mut drawing, &mut place); } Event::Preferences => { // The bar again, in the language chosen now; the canvas // may have changed size with the text. if finish(&mut stroke, &drawing, &mut history) { choices.follow(&history); save_at = Some(pinnacle_rt::time() + SAVE_AFTER_MS); } last = None; screen.restyle(); screen.mount(page(&choices, revision.clone(), touches.clone(), &ask)); draw_all(&mut screen, &mut app, &mut drawing, &mut place); } Event::Closed => { if finish(&mut stroke, &drawing, &mut history) || save_at.is_some() { save(&drawing); } return 0; } _ => {} } } }