ProCraft for Android: An Android native painting app written in Rust
Rust
feat(import): GIMP brushes and pipes as brushes, moving GIFs as held frames
Josh8f52f86a73a1
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.ktindex d600b7a..e76d50e 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt@@ -1397,7 +1397,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {message = "This palette can't be read."} else if (name != null && isModelName(name)) {newFromModel(uri, name)- } else if (name != null && name.endsWith(".abr", ignoreCase = true)) {+ } else if (name != null && isTipFile(name)) {val bytes = withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() }if (bytes == null || !addAbr(bytes, name)) message = "This file has no brushes in it."} else if (head != null && String(head, Charsets.ISO_8859_1) == "8BPS") {@@ -2361,11 +2361,28 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {fun insertPicture(uri: android.net.Uri, private: Boolean = false) {val s = session ?: returnclosePanels()- if (getApplication<Application>().contentResolver.getType(uri)?.startsWith("video/") == true) {+ val resolver = getApplication<Application>().contentResolver+ val type = resolver.getType(uri)+ if (type?.startsWith("video/") == true) {insertFrames(uri, private)return}viewModelScope.launch {+ // a moving GIF: its frames, as a video's (a still one is a picture)+ if (type == "image/gif" || withContext(Dispatchers.IO) { fileName(uri) }?.endsWith(".gif", ignoreCase = true) == true) {+ val bytes = withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() }+ val done = bytes?.let { withContext(Dispatchers.Default) { runCatching { s.insertGifFrames(it, private) }.getOrNull() } }+ if (done != null) {+ if (done.added == 0u) {+ message = if (done.full) noRoom() else "This picture can't be opened."+ return@launch+ }+ refresh()+ showNotice("Frames saved to timeline")+ if (done.full) message = noRoom()+ return@launch+ }+ }val image = withContext(Dispatchers.IO) { decodePicture(uri, io.github.artcraftandroid.procraft.ui.CanvasSpace.p3) }if (image == null) {message = "This picture can't be opened."@@ -3174,7 +3191,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {runCatching { getApplication<Application>().contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull()} ?: return@launchval name = withContext(Dispatchers.IO) { fileName(uri) }- val added = if (name?.endsWith(".abr", ignoreCase = true) == true) addAbr(bytes, name) else addBrushes(bytes)+ val added = if (name != null && isTipFile(name)) addAbr(bytes, name) else addBrushes(bytes)if (!added) message = "This file has no brushes in it."}}@@ -3224,6 +3241,9 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {return true}+ /** Whether a file named [name] holds brush tips: Photoshop's, or GIMP's brushes and pipes. */+ private fun isTipFile(name: String) = TIP_EXTENSIONS.any { name.endsWith(".$it", ignoreCase = true) }+/** Brush files kept while no canvas was open, added now. */private fun addPendingBrushes(s: CanvasSession) {val files = pendingBrushDir.listFiles()?.sortedBy { it.name } ?: return@@ -5842,6 +5862,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** Brush and brush set files, as other painting apps share them. */const val BRUSH_EXTENSION = "brush"const val BRUSH_SET_EXTENSION = "brushset"+ /** Files of brush tips to make brushes of: Photoshop's, GIMP's brushes and pipes. */+ val TIP_EXTENSIONS = listOf("abr", "gbr", "gih")val PACKAGE_LABEL = PACKAGE_EXTENSION.replaceFirstChar(Char::titlecase)/** What the gallery's Share offers, in order: still pictures, then animations. */diff --git a/apps/procraft-android/src/brush_files.rs b/apps/procraft-android/src/brush_files.rsindex 09b09f2..0feb256 100644--- a/apps/procraft-android/src/brush_files.rs+++ b/apps/procraft-android/src/brush_files.rs@@ -107,11 +107,11 @@ impl CanvasSession {Some(at as u32)}- /// Adds the sampled tips of a Photoshop brush file (`bytes`) as brushes in a set of their own- /// named `name` (else "Imported") at the top of the library: each tip its shape, with the- /// file's spacing. Returns the set, or none if the file holds no tips.+ /// Adds the sampled tips of a Photoshop brush file or a GIMP brush or pipe (`bytes`) as brushes+ /// in a set of their own named `name` (else "Imported") at the top of the library: each tip its+ /// shape, with the file's spacing. Returns the set, or none if the file holds no tips.pub fn import_abr(&self, bytes: Vec<u8>, name: String) -> Option<u32> {- let tips = procraft_engine::abr::read(&bytes)?;+ let tips = procraft_engine::abr::read(&bytes).or_else(|| procraft_engine::gbr::read(&bytes))?;let brushes: Vec<Brush> = tips.iter().map(|t| {diff --git a/apps/procraft-android/src/clipboard.rs b/apps/procraft-android/src/clipboard.rsindex 37f369e..1671c80 100644--- a/apps/procraft-android/src/clipboard.rs+++ b/apps/procraft-android/src/clipboard.rs@@ -5,6 +5,17 @@ use procraft_engine::document::LayerId;use crate::layers::ThumbnailImage;use crate::{CanvasSession, State};+/// What bringing in a moving picture's frames did: how many came in as layers, and whether the+/// canvas ran out of room for more.+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Record)]+pub struct FramesInserted {+ pub added: u32,+ pub full: bool,+}++/// The most frames brought in from one moving picture.+const MOST_FRAMES: usize = 999;+impl State {/// The current layer's pixels within the selection (all of it without one).fn selected_pixels(&mut self) -> Option<Vec<u8>> {@@ -120,6 +131,54 @@ impl CanvasSession {self.add_picture(&premultiplied, true, private)}+ /// The frames of the animated GIF `bytes` as layers above the current one, each fitted to the+ /// canvas, for as many as there is room: Animation Assist comes on (unless it is on already),+ /// and each frame is held for as long as the file shows it at the animation's frame rate.+ /// None if it isn't a GIF of more than one frame (a still picture: insert it as one).+ pub fn insert_gif_frames(&self, bytes: Vec<u8>, private: bool) -> Option<FramesInserted> {+ if procraft_engine::gif::frame_count(&bytes) < 2 {+ return None;+ }+ let fps = {+ let st = self.shared.lock();+ st.doc.animation.as_ref().map_or(procraft_engine::animation::Animation::default().fps, |a| a.fps).max(1)+ };+ let (width, height) = procraft_engine::gif::size(&bytes)?;+ let mut held: Vec<(LayerId, u32)> = Vec::new();+ let mut full = false;+ procraft_engine::gif::frames(&bytes, |rgba, ms| {+ let mut image = ThumbnailImage { width, height, rgba: rgba.to_vec() };+ // straight to premultiplied+ for px in image.rgba.as_chunks_mut::<4>().0 {+ let a = u16::from(px[3]);+ for c in px.iter_mut().take(3) {+ *c = ((u16::from(*c) * a + 127) / 255) as u8;+ }+ }+ let Some(id) = self.add_picture(&image, true, private) else {+ full = true;+ return false;+ };+ // shown for as many of the animation's frames as its time takes+ let shown = ((f64::from(ms) * f64::from(fps) / 1000.0).round() as u32).max(1);+ held.push((LayerId(id), shown - 1));+ held.len() < MOST_FRAMES+ })?;+ if held.is_empty() {+ return Some(FramesInserted { added: 0, full });+ }+ let assisted = self.shared.lock().doc.animation.as_ref().is_some_and(|a| !a.pages);+ if !assisted {+ self.set_animation_assist(true);+ }+ if let Some(a) = self.shared.lock().doc.animation.as_mut() {+ for &(id, n) in &held {+ a.set_hold(id, n);+ }+ }+ Some(FramesInserted { added: held.len() as u32, full })+ }+/// Mirrors every layer of the canvas, left to right or (not `horizontal`) top to bottom, as/// one undo step.pub fn flip_canvas(&self, horizontal: bool) {diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex 836729f..97e0a7b 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -2936,3 +2936,68 @@ fn changes(a: &procraft_engine::brushfile::BrushFile, b: &procraft_engine::brush}out.join(", ")}++#[test]+fn a_gimp_brush_becomes_a_brush_with_its_spacing() {+ let s = CanvasSession::new(64, 64);+ // version 2: header, size, grey, the magic word, 40% spacing, the name, a 4 × 4 image+ let name = b"Charcoal\0";+ let mut file = Vec::new();+ for v in [28 + name.len() as u32, 2, 4, 4, 1] {+ file.extend_from_slice(&v.to_be_bytes());+ }+ file.extend_from_slice(b"GIMP");+ file.extend_from_slice(&40u32.to_be_bytes());+ file.extend_from_slice(name);+ file.extend((0..16).map(|i| (i * 16) as u8));+ let set = s.import_abr(file, "Charcoal pack".to_owned()).unwrap();+ let library = s.brush_library();+ let set = &library[set as usize];+ assert_eq!(set.name, "Charcoal pack");+ assert_eq!(set.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Charcoal"]);+}++#[test]+fn a_moving_gif_comes_in_as_held_frames() {+ let Some(s) = session(8, 8) else { return };+ // a 2 × 2 GIF of two frames, red for 0.2 s then blue for 0.1 s (no compression: each index a+ // code of 3 bits after a clear code)+ let frame = |index: u8, centiseconds: u8| {+ let mut f = vec![0x21, 0xF9, 4, 0, centiseconds, 0, 0, 0, 0x2C, 0, 0, 0, 0, 2, 0, 2, 0, 0, 2];+ // clear (4), the index twice, clear, twice more, end (5), 3 bits each, low bits first+ let codes = [4u32, index.into(), index.into(), 4, index.into(), index.into(), 5];+ let (mut data, mut acc, mut bits) = (Vec::new(), 0u32, 0);+ for c in codes {+ acc |= c << bits;+ bits += 3;+ while bits >= 8 {+ data.push(acc as u8);+ acc >>= 8;+ bits -= 8;+ }+ }+ data.push(acc as u8);+ f.push(data.len() as u8);+ f.extend(data);+ f.push(0);+ f+ };+ let mut gif = b"GIF89a".to_vec();+ gif.extend_from_slice(&[2, 0, 2, 0, 0x81, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0]);+ gif.extend(frame(0, 20));+ gif.extend(frame(1, 10));+ gif.push(0x3B);+ let before = s.shared.lock().doc.layers().len();+ let done = s.insert_gif_frames(gif, false).unwrap();+ assert_eq!(done, crate::clipboard::FramesInserted { added: 2, full: false });+ assert_eq!(s.shared.lock().doc.layers().len(), before + 2);+ // Animation Assist is on; at 15 frames a second, 0.2 s is three frames: held two more+ let animation = s.shared.lock().doc.animation.clone().unwrap();+ assert!(!animation.pages);+ let holds: Vec<u32> = animation.holds.iter().map(|h| h.1).collect();+ assert_eq!(holds, [2, 1]);+ // the top frame is blue, filling the canvas+ assert_eq!(pixel(&s, 4, 4), [0, 0, 255, 255]);+ // a still picture isn't taken+ assert_eq!(s.insert_gif_frames(b"GIF89a".to_vec(), false), None);+}diff --git a/crates/engine/src/gbr.rs b/crates/engine/src/gbr.rsnew file mode 100644index 0000000..3db8e17--- /dev/null+++ b/crates/engine/src/gbr.rs@@ -0,0 +1,133 @@+//! Reading GIMP brushes: a brush (`.gbr`, versions 1 and 2) is a header, its name and its image+//! (grey, how much each pixel paints; or RGBA, whose alpha paints); a pipe (`.gih`) is a name+//! line, a line of its parameters and its brushes one after another. Each image is read as the+//! tips ABR files give.++use crate::abr::AbrTip;++/// The largest tip side read, pixels.+const MOST_SIDE: u32 = 5000;+/// The most brushes read from a pipe.+const MOST_IN_PIPE: usize = 256;++/// The tips in a GIMP brush or pipe file, in order; none if it is neither.+pub fn read(bytes: &[u8]) -> Option<Vec<AbrTip>> {+ if let Some((tip, _)) = brush(bytes) {+ return Some(vec![tip]);+ }+ pipe(bytes)+}++/// A brush at the start of `bytes`, and how many bytes it takes.+fn brush(bytes: &[u8]) -> Option<(AbrTip, usize)> {+ let word = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes);+ let header = word(0)? as usize;+ let version = word(4)?;+ let (width, height, depth) = (word(8)?, word(12)?, word(16)?);+ // version 2 has the magic word and the spacing (per cent of the size) after the depth+ let spacing = match version {+ 1 if header >= 20 => None,+ 2 | 3 if header >= 28 && bytes.get(20..24)? == b"GIMP" => Some(word(24)? as f32 / 100.0),+ _ => return None,+ };+ if width == 0 || height == 0 || width > MOST_SIDE || height > MOST_SIDE || !(depth == 1 || depth == 4) {+ return None;+ }+ let fixed = if version == 1 { 20 } else { 28 };+ let name = bytes.get(fixed..header)?;+ let name = String::from_utf8_lossy(name.split(|&b| b == 0).next().unwrap_or_default()).trim().to_owned();+ let size = width as usize * height as usize * depth as usize;+ let image = bytes.get(header..header.checked_add(size)?)?;+ let pixels = if depth == 1 { image.to_vec() } else { image.iter().skip(3).step_by(4).copied().collect() };+ let tip = AbrTip { name, spacing: spacing.filter(|s| *s > 0.0), width, height, pixels };+ Some((tip, header + size))+}++/// A pipe: its name, a line starting with how many brushes it has, then the brushes.+fn pipe(bytes: &[u8]) -> Option<Vec<AbrTip>> {+ let first = bytes.iter().position(|&b| b == b'\n')?;+ let second = first + 1 + bytes.get(first + 1..)?.iter().position(|&b| b == b'\n')?;+ let name = String::from_utf8_lossy(bytes.get(..first)?).trim().to_owned();+ let line = String::from_utf8_lossy(bytes.get(first + 1..second)?).into_owned();+ let count: usize = line.split_whitespace().next()?.parse().ok()?;+ let mut at = second + 1;+ let mut tips = Vec::new();+ for n in 1..=count.min(MOST_IN_PIPE) {+ let Some((mut tip, used)) = brush(bytes.get(at..)?) else { break };+ // the pipe's name for its only brush; numbered for those with none of their own+ if count == 1 {+ tip.name = name.clone();+ } else if tip.name.is_empty() {+ tip.name = format!("{name} {n}");+ }+ tips.push(tip);+ at += used;+ }+ (!tips.is_empty()).then_some(tips)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn gbr(version: u32, name: &str, width: u32, height: u32, depth: u32, spacing: u32) -> Vec<u8> {+ let fixed: u32 = if version == 1 { 20 } else { 28 };+ let header = fixed + name.len() as u32 + 1;+ let mut out = Vec::new();+ for v in [header, version, width, height, depth] {+ out.extend_from_slice(&v.to_be_bytes());+ }+ if version == 2 {+ out.extend_from_slice(b"GIMP");+ out.extend_from_slice(&spacing.to_be_bytes());+ }+ out.extend_from_slice(name.as_bytes());+ out.push(0);+ for i in 0..width * height {+ if depth == 1 {+ out.push((i * 40) as u8);+ } else {+ out.extend_from_slice(&[255, 0, 0, (i * 40) as u8]);+ }+ }+ out+ }++ #[test]+ fn a_brush_reads_with_its_name_spacing_and_image() {+ let tips = read(&gbr(2, "Pencil", 3, 2, 1, 25)).unwrap();+ assert_eq!(tips.len(), 1);+ let t = &tips[0];+ assert_eq!((t.name.as_str(), t.spacing, t.width, t.height), ("Pencil", Some(0.25), 3, 2));+ assert_eq!(t.pixels, [0, 40, 80, 120, 160, 200]);+ // a colour brush paints by its alpha; version 1 has no spacing+ let t = &read(&gbr(1, "Old", 2, 2, 4, 0)).unwrap()[0];+ assert_eq!((t.spacing, t.pixels.as_slice()), (None, &[0, 40, 80, 120][..]));+ }++ #[test]+ fn a_pipe_reads_each_brush() {+ let mut file = b"Leaves\n2 ncells:2 cellwidth:3 cellheight:2 step:100 dim:1 rank0:2 sel0:random\n".to_vec();+ file.extend(gbr(2, "", 3, 2, 1, 50));+ file.extend(gbr(2, "Leaf", 3, 2, 4, 50));+ let tips = read(&file).unwrap();+ let names: Vec<&str> = tips.iter().map(|t| t.name.as_str()).collect();+ assert_eq!(names, ["Leaves 1", "Leaf"]);+ assert_eq!(tips[1].spacing, Some(0.5));+ }++ #[test]+ fn other_files_and_damaged_ones_are_not_brushes() {+ assert!(read(b"nothing at all").is_none());+ assert!(read(&gbr(2, "Huge", 6000, 1, 1, 10)[..40]).is_none());+ let good = gbr(2, "Pencil", 3, 2, 1, 25);+ crate::damaged::survives("GIMP brush", &good, |b| {+ let _ = read(b);+ });+ let mut pipe = b"Leaves\n1 ncells:1\n".to_vec();+ pipe.extend(&good);+ crate::damaged::survives("GIMP pipe", &pipe, |b| {+ let _ = read(b);+ });+ }+}diff --git a/crates/engine/src/gif.rs b/crates/engine/src/gif.rsnew file mode 100644index 0000000..ff80016--- /dev/null+++ b/crates/engine/src/gif.rs@@ -0,0 +1,470 @@+//! Reading animated GIFs: each frame drawn over the canvas as the frames before it left it (kept,+//! cleared to nothing, or put back as it was), with how long it shows. A damaged file gives the+//! frames before the damage.++/// The most pixels a GIF's canvas may have.+const MOST_PIXELS: u64 = 4096 * 4096;+/// Frames shown for at most a hundredth of a second play, as browsers play them, at this.+const SHORTEST_MS: u32 = 100;++/// The canvas's size, if `bytes` is a GIF of a size read here.+pub fn size(bytes: &[u8]) -> Option<(u32, u32)> {+ screen(bytes)+}++/// How many frames the GIF `bytes` has (none if it isn't one), without decoding them.+pub fn frame_count(bytes: &[u8]) -> usize {+ let mut count = 0;+ walk(bytes, |_, _| {+ count += 1;+ Some(())+ });+ count+}++/// Gives `frame` each frame of the GIF `bytes` in order (straight RGBA, the canvas's size, and how+/// long it shows, ms) until it returns false. The canvas's size and how many frames it was given,+/// or none if it isn't a GIF.+pub fn frames(bytes: &[u8], mut frame: impl FnMut(&[u8], u32) -> bool) -> Option<(u32, u32, usize)> {+ let (w, h) = screen(bytes)?;+ let (wu, hu) = (w as usize, h as usize);+ let mut canvas = vec![0u8; wu * hu * 4];+ let mut given = 0;+ let mut stopped = false;+ walk(bytes, |image, data| {+ if stopped {+ return None;+ }+ let indices = lzw(data, image.min_code, usize::from(image.width) * usize::from(image.height))?;+ let before = (image.disposal == 3).then(|| canvas.clone());+ draw(&mut canvas, wu, hu, &image, &indices);+ given += 1;+ let ms = if image.delay <= 1 { SHORTEST_MS } else { u32::from(image.delay) * 10 };+ if !frame(&canvas, ms) {+ stopped = true;+ return None;+ }+ match (image.disposal, before) {+ (2, _) => clear(&mut canvas, wu, hu, &image),+ (3, Some(b)) => canvas = b,+ _ => {}+ }+ Some(())+ });+ Some((w, h, given))+}++/// A frame's place, palette and how it shows (from the control block before it).+struct Image<'a> {+ left: u16,+ top: u16,+ width: u16,+ height: u16,+ interlaced: bool,+ palette: &'a [u8],+ min_code: u8,+ transparent: Option<u8>,+ delay: u16,+ disposal: u8,+}++/// The canvas's size, if `bytes` is a GIF of a size read here.+fn screen(bytes: &[u8]) -> Option<(u32, u32)> {+ let mut r = Reader { b: bytes, at: 0 };+ let sig = r.take(6)?;+ if sig != b"GIF87a" && sig != b"GIF89a" {+ return None;+ }+ let (w, h) = (u32::from(r.u16()?), u32::from(r.u16()?));+ (w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MOST_PIXELS).then_some((w, h))+}++/// Calls `each` with every frame and its compressed data, in order, until the end, damage, or+/// `each` giving none.+fn walk<'a>(bytes: &'a [u8], mut each: impl FnMut(Image<'a>, &[u8]) -> Option<()>) {+ if screen(bytes).is_none() {+ return;+ }+ let mut r = Reader { b: bytes, at: 10 };+ let mut go = || -> Option<()> {+ let packed = r.u8()?;+ r.take(2)?;+ let global = if packed & 0x80 != 0 { Some(r.take(3 << ((packed & 7) + 1))?) } else { None };+ let (mut transparent, mut delay, mut disposal) = (None, 0, 0);+ loop {+ match r.u8()? {+ 0x21 => {+ let label = r.u8()?;+ let block = r.blocks()?;+ if label == 0xF9 && block.len() >= 4 {+ let flags = *block.first()?;+ disposal = (flags >> 2) & 7;+ delay = u16::from_le_bytes([*block.get(1)?, *block.get(2)?]);+ transparent = (flags & 1 != 0).then_some(*block.get(3)?);+ }+ }+ 0x2C => {+ let (left, top, width, height) = (r.u16()?, r.u16()?, r.u16()?, r.u16()?);+ let packed = r.u8()?;+ let local = if packed & 0x80 != 0 { Some(r.take(3 << ((packed & 7) + 1))?) } else { None };+ let min_code = r.u8()?;+ let data = r.blocks()?;+ let palette = local.or(global)?;+ let image = Image {+ left,+ top,+ width,+ height,+ interlaced: packed & 0x40 != 0,+ palette,+ min_code,+ transparent,+ delay,+ disposal,+ };+ each(image, &data)?;+ // a control block is for the next frame only+ (transparent, delay, disposal) = (None, 0, 0);+ }+ _ => return None,+ }+ }+ };+ let _ = go();+}++/// Draws a frame's colours over the canvas (its transparent ones leave what is there).+fn draw(canvas: &mut [u8], w: usize, h: usize, image: &Image<'_>, indices: &[u8]) {+ let (fw, fh) = (usize::from(image.width), usize::from(image.height));+ // interlaced: every eighth row from 0, every eighth from 4, every fourth from 2, the rest+ let rows: Vec<usize> = if image.interlaced {+ (0..fh).step_by(8).chain((4..fh).step_by(8)).chain((2..fh).step_by(4)).chain((1..fh).step_by(2)).collect()+ } else {+ (0..fh).collect()+ };+ for (i, row) in rows.into_iter().enumerate() {+ let y = usize::from(image.top) + row;+ if y >= h {+ continue;+ }+ for col in 0..fw {+ let x = usize::from(image.left) + col;+ let Some(&index) = indices.get(i * fw + col) else { return };+ if x >= w || Some(index) == image.transparent {+ continue;+ }+ let at = usize::from(index) * 3;+ if let (Some(&[r, g, b]), Some(px)) =+ (image.palette.get(at..at + 3), canvas.get_mut((y * w + x) * 4..(y * w + x) * 4 + 4))+ {+ px.copy_from_slice(&[r, g, b, 255]);+ }+ }+ }+}++/// Clears a frame's place to nothing.+fn clear(canvas: &mut [u8], w: usize, h: usize, image: &Image<'_>) {+ let (x0, y0) = (usize::from(image.left).min(w), usize::from(image.top).min(h));+ let (x1, y1) = ((x0 + usize::from(image.width)).min(w), (y0 + usize::from(image.height)).min(h));+ for y in y0..y1 {+ if let Some(row) = canvas.get_mut((y * w + x0) * 4..(y * w + x1) * 4) {+ row.fill(0);+ }+ }+}++/// The colour indices `data` holds (LZW, codes from `min_code + 1` bits growing to 12), `count` of+/// them: short data padded with the first colour.+fn lzw(data: &[u8], min_code: u8, count: usize) -> Option<Vec<u8>> {+ if !(1..=11).contains(&min_code) {+ return None;+ }+ const NONE: u16 = u16::MAX;+ let clear = 1u16 << min_code;+ let end = clear + 1;+ // each code: the code before its last colour, its last colour, and its first+ let mut prefix = vec![NONE; 4096];+ let mut suffix = vec![0u8; 4096];+ let mut first = vec![0u8; 4096];+ for c in 0..clear {+ let c8 = (c & 0xFF) as u8;+ *suffix.get_mut(usize::from(c))? = c8;+ *first.get_mut(usize::from(c))? = c8;+ }+ let mut out = Vec::with_capacity(count);+ let (mut next, mut size, mut prev) = (end + 1, u32::from(min_code) + 1, None::<u16>);+ let (mut acc, mut bits, mut at) = (0u32, 0u32, 0usize);+ let mut string = Vec::with_capacity(4096);+ 'codes: while out.len() < count {+ while bits < size {+ let Some(&byte) = data.get(at) else { break 'codes };+ acc |= u32::from(byte) << bits;+ bits += 8;+ at += 1;+ }+ let code = (acc & ((1 << size) - 1)) as u16;+ acc >>= size;+ bits -= size;+ if code == clear {+ (next, size, prev) = (end + 1, u32::from(min_code) + 1, None);+ continue;+ }+ if code == end {+ break;+ }+ let Some(p) = prev else {+ if code >= clear {+ break;+ }+ out.push((code & 0xFF) as u8);+ prev = Some(code);+ continue;+ };+ // a code not yet made is the one before with its own first colour again+ let (start, tail) = if code < next {+ (code, None)+ } else if code == next {+ (p, Some(*first.get(usize::from(p))?))+ } else {+ break;+ };+ string.clear();+ string.extend(tail);+ let mut c = start;+ loop {+ string.push(*suffix.get(usize::from(c))?);+ if c < clear {+ break;+ }+ c = *prefix.get(usize::from(c))?;+ if c == NONE || string.len() > 4096 {+ break 'codes;+ }+ }+ out.extend(string.iter().rev().take(count - out.len()));+ if next < 4096 {+ let n = usize::from(next);+ *prefix.get_mut(n)? = p;+ *suffix.get_mut(n)? = *first.get(usize::from(start))?;+ *first.get_mut(n)? = *first.get(usize::from(p))?;+ next += 1;+ if u32::from(next) == 1 << size && size < 12 {+ size += 1;+ }+ }+ prev = Some(code);+ }+ out.resize(count, 0);+ Some(out)+}++struct Reader<'a> {+ b: &'a [u8],+ at: usize,+}++impl<'a> Reader<'a> {+ fn take(&mut self, n: usize) -> Option<&'a [u8]> {+ let s = self.b.get(self.at..self.at.checked_add(n)?)?;+ self.at += n;+ Some(s)+ }++ fn u8(&mut self) -> Option<u8> {+ self.take(1)?.first().copied()+ }++ fn u16(&mut self) -> Option<u16> {+ let b = self.take(2)?;+ Some(u16::from_le_bytes([*b.first()?, *b.get(1)?]))+ }++ /// Sub-blocks (each a length, then that many bytes) up to an empty one, joined.+ fn blocks(&mut self) -> Option<Vec<u8>> {+ let mut out = Vec::new();+ loop {+ let n = usize::from(self.u8()?);+ if n == 0 {+ return Some(out);+ }+ out.extend_from_slice(self.take(n)?);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// LZW codes for `indices` (no compression: a clear code before every few, so the code size+ /// stays `min + 1`), packed as a GIF packs them.+ fn compress(indices: &[u8], min: u8) -> Vec<u8> {+ let clear = 1u32 << min;+ let size = u32::from(min) + 1;+ let mut codes = vec![clear];+ for (i, &v) in indices.iter().enumerate() {+ if i > 0 && i % ((1 << size) - clear as usize - 2).max(1) == 0 {+ codes.push(clear);+ }+ codes.push(u32::from(v));+ }+ codes.push(clear + 1);+ let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0u32);+ for c in codes {+ acc |= c << bits;+ bits += size;+ while bits >= 8 {+ out.push((acc & 0xFF) as u8);+ acc >>= 8;+ bits -= 8;+ }+ }+ if bits > 0 {+ out.push(acc as u8);+ }+ out+ }++ fn blocks(data: &[u8]) -> Vec<u8> {+ let mut out = Vec::new();+ for chunk in data.chunks(255) {+ out.push(chunk.len() as u8);+ out.extend_from_slice(chunk);+ }+ out.push(0);+ out+ }++ /// A 4 × 2 GIF of red, green, blue and white: frame 1 all red, frame 2 a green square at+ /// (1, 0) whose second pixel is transparent, shown for 0.5 s then cleared, frame 3 blue at+ /// (3, 1).+ fn sample() -> Vec<u8> {+ let mut g = b"GIF89a".to_vec();+ g.extend_from_slice(&[4, 0, 2, 0, 0x81, 0, 0]);+ g.extend_from_slice(&[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255]);+ let frame = |g: &mut Vec<u8>, control: [u8; 4], place: [u16; 4], indices: &[u8]| {+ g.extend_from_slice(&[0x21, 0xF9, 4]);+ g.extend_from_slice(&control);+ g.push(0);+ g.push(0x2C);+ for v in place {+ g.extend_from_slice(&v.to_le_bytes());+ }+ g.push(0);+ g.push(2);+ g.extend(blocks(&compress(indices, 2)));+ };+ frame(&mut g, [0, 10, 0, 0], [0, 0, 4, 2], &[0; 8]);+ frame(&mut g, [(2 << 2) | 1, 50, 0, 3], [1, 0, 2, 1], &[1, 3]);+ frame(&mut g, [0, 0, 0, 0], [3, 1, 1, 1], &[2]);+ g.push(0x3B);+ g+ }++ fn px(f: &[u8], x: usize, y: usize) -> [u8; 4] {+ let i = (y * 4 + x) * 4;+ [f[i], f[i + 1], f[i + 2], f[i + 3]]+ }++ #[test]+ fn frames_build_on_each_other_and_show_for_their_time() {+ let g = sample();+ assert_eq!(frame_count(&g), 3);+ let mut seen = Vec::new();+ assert_eq!(+ frames(&g, |f, ms| {+ seen.push((f.to_vec(), ms));+ true+ }),+ Some((4, 2, 3))+ );+ let (red, green, blue) = ([255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]);+ // a tenth of a second; the green over the red, its transparent pixel leaving the red+ assert_eq!(seen[0].1, 100);+ assert_eq!((px(&seen[1].0, 1, 0), px(&seen[1].0, 2, 0), px(&seen[1].0, 0, 0)), (green, red, red));+ assert_eq!(seen[1].1, 500);+ // then cleared to nothing where it was; a frame with no time plays at a tenth of a second+ assert_eq!((px(&seen[2].0, 1, 0), px(&seen[2].0, 3, 1), px(&seen[2].0, 0, 1)), ([0; 4], blue, red));+ assert_eq!(seen[2].1, 100);+ // stopping early+ let mut n = 0;+ assert_eq!(+ frames(&g, |_, _| {+ n += 1;+ false+ })+ .map(|f| f.2),+ Some(1)+ );+ }++ /// LZW as GIF encoders write it: strings grow in the table, and so do the codes.+ fn encode(indices: &[u8], min: u8) -> Vec<u8> {+ let clear = 1u32 << min;+ let mut table = std::collections::HashMap::new();+ let (mut next, mut size) = (clear + 2, u32::from(min) + 1);+ let mut codes = vec![(clear, size)];+ let mut w: Option<u32> = None;+ for &c in indices {+ let Some(p) = w else {+ w = Some(u32::from(c));+ continue;+ };+ if let Some(&code) = table.get(&(p, c)) {+ w = Some(code);+ continue;+ }+ codes.push((p, size));+ if next < 4096 {+ table.insert((p, c), next);+ if next == 1 << size && size < 12 {+ size += 1;+ }+ next += 1;+ }+ w = Some(u32::from(c));+ }+ codes.extend(w.map(|p| (p, size)));+ codes.push((clear + 1, size));+ let (mut out, mut acc, mut bits) = (Vec::new(), 0u64, 0u32);+ for (c, n) in codes {+ acc |= u64::from(c) << bits;+ bits += n;+ while bits >= 8 {+ out.push((acc & 0xFF) as u8);+ acc >>= 8;+ bits -= 8;+ }+ }+ if bits > 0 {+ out.push(acc as u8);+ }+ out+ }++ #[test]+ fn codes_longer_than_the_first_size_decode() {+ // repeating runs: the table fills with longer strings and the codes grow past 3 bits+ let indices: Vec<u8> = (0..2000).map(|i| (i / 7 % 4) as u8).collect();+ let data = encode(&indices, 2);+ assert!(data.len() < indices.len() / 4, "{} bytes", data.len());+ assert_eq!(lzw(&data, 2, indices.len()).unwrap(), indices);+ // eight-bit colours+ let indices: Vec<u8> = (0..5000u32).map(|i| ((i * 37) % 251) as u8).collect();+ assert_eq!(lzw(&encode(&indices, 8), 8, indices.len()).unwrap(), indices);+ }++ #[test]+ fn other_files_and_damaged_ones_are_refused_or_cut_short() {+ assert_eq!(frame_count(b"not a picture"), 0);+ assert!(frames(b"GIF89a\0\0\0\0", |_, _| true).is_none());+ let g = sample();+ // cut in its last frame: the two before it come+ assert_eq!(frames(&g[..g.len() - 6], |_, _| true).map(|f| f.2), Some(2));+ crate::damaged::survives("GIF", &g, |b| {+ let _ = frames(b, |_, _| true);+ let _ = frame_count(b);+ });+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 72963f0..888291f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -18,7 +18,9 @@ pub mod document;pub mod environment;pub mod fill;pub mod formats;+pub mod gbr;pub mod geom;+pub mod gif;pub mod gltf;pub mod guide;pub mod icc;