ProCraft for Android: An Android native painting app written in Rust
Rust
feat(import): Krita presets and bundles as brushes
Joshcc3c0a0d618b
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 e76d50e..773e5a1 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,9 +1397,9 @@ 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 && isTipFile(name)) {+ } else if (name != null && isOtherBrushFile(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."+ if (bytes == null || !addOtherBrushes(bytes, name)) message = "This file has no brushes in it."} else if (head != null && String(head, Charsets.ISO_8859_1) == "8BPS") {importPsd(uri, name)} else if (head != null && String(head, Charsets.ISO_8859_1) == "%PDF") {@@ -3191,27 +3191,27 @@ 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 != null && isTipFile(name)) addAbr(bytes, name) else addBrushes(bytes)+ val added = if (name != null && isOtherBrushFile(name)) addOtherBrushes(bytes, name) else addBrushes(bytes)if (!added) message = "This file has no brushes in it."}}/**- * A Photoshop brush file's tips [bytes] as a set of brushes named after the file [name] (shown),+ * Another app's brushes [bytes] as a set of brushes named after the file [name] (shown),* or, with no canvas open, kept until one opens; false if the file has none.*/- private suspend fun addAbr(bytes: ByteArray, name: String): Boolean {+ private suspend fun addOtherBrushes(bytes: ByteArray, name: String): Boolean {val setName = name.substringBeforeLast('.').trim()val s = sessionif (s == null) {withContext(Dispatchers.IO) {pendingBrushDir.mkdirs()- File(pendingBrushDir, "${System.nanoTime()}-${setName.replace(Regex("[^A-Za-z0-9 _-]"), "_")}.abr").writeBytes(bytes)+ File(pendingBrushDir, "${System.nanoTime()}-${setName.replace(Regex("[^A-Za-z0-9 _-]"), "_")}.other").writeBytes(bytes)}message = "Brushes will be added to the library when a canvas opens."return true}- val set = withContext(Dispatchers.Default) { s.importAbr(bytes, setName) } ?: return false+ val set = withContext(Dispatchers.Default) { s.importOtherBrushes(bytes, setName) } ?: return falseshownSet = set.toInt()libraryChanged()return true@@ -3241,16 +3241,17 @@ 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) }+ /** Whether a file named [name] holds another app's brushes (see [OTHER_BRUSH_EXTENSIONS]). */+ private fun isOtherBrushFile(name: String) = OTHER_BRUSH_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 } ?: returnvar any = falsefor (f in files) {- val abr = f.name.endsWith(".abr")- runCatching { if (abr) s.importAbr(f.readBytes(), f.nameWithoutExtension.substringAfter('-')) else s.importBrushes(f.readBytes()) }.getOrNull()?.let {+ // another app's (kept as .abr by earlier versions)+ val other = f.name.endsWith(".other") || f.name.endsWith(".abr")+ runCatching { if (other) s.importOtherBrushes(f.readBytes(), f.nameWithoutExtension.substringAfter('-')) else s.importBrushes(f.readBytes()) }.getOrNull()?.let {shownSet = it.toInt()any = true}@@ -5862,8 +5863,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")+ /** Other apps' brush files: Photoshop's, GIMP's brushes and pipes, Krita's presets and bundles. */+ val OTHER_BRUSH_EXTENSIONS = listOf("abr", "gbr", "gih", "kpp", "bundle")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 0feb256..663ed6e 100644--- a/apps/procraft-android/src/brush_files.rs+++ b/apps/procraft-android/src/brush_files.rs@@ -107,23 +107,12 @@ impl CanvasSession {Some(at as u32)}- /// 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).or_else(|| procraft_engine::gbr::read(&bytes))?;- let brushes: Vec<Brush> = tips- .iter()- .map(|t| {- let mut b = Brush { name: t.name.clone(), ..Brush::round_pen() };- b.shape.image = None;- b.shape.source = Source::new(fitted(t));- if let Some(spacing) = t.spacing {- b.spacing = spacing.clamp(0.01, 10.0);- }- b- })- .collect();+ /// Adds the brushes in another app's file (`bytes`): a Photoshop brush file's sampled tips, a+ /// GIMP brush or pipe, or a Krita preset or bundle. They go in a set of their own named `name`+ /// (a bundle's own name first; else "Imported") at the top of the library, each with the+ /// file's shape and spacing. Returns the set, or none if the file holds none.+ pub fn import_other_brushes(&self, bytes: Vec<u8>, name: String) -> Option<u32> {+ let (name, brushes) = other_brushes(&bytes, name)?;if brushes.is_empty() {return None;}@@ -214,6 +203,93 @@ fn fitted(t: &procraft_engine::abr::AbrTip) -> Vec<u8> {out}+/// The brushes in another app's file, with the set's name (a bundle's own, else `name`).+fn other_brushes(bytes: &[u8], name: String) -> Option<(String, Vec<Brush>)> {+ use procraft_engine::krita;+ if let Some(tips) = procraft_engine::abr::read(bytes).or_else(|| procraft_engine::gbr::read(bytes)) {+ return Some((name, tips.iter().map(tip_brush).collect()));+ }+ if let Some((title, presets)) = krita::read_bundle(bytes) {+ let name = if title.trim().is_empty() { name } else { title };+ return Some((name, presets.iter().map(krita_brush).collect()));+ }+ // a preset alone has no images of its own: one it names comes round+ let preset = krita::read_preset(bytes, &|_| None)?;+ Some((name, vec![krita_brush(&preset)]))+}++/// A brush of a sampled tip: its shape, with its spacing.+fn tip_brush(t: &procraft_engine::abr::AbrTip) -> Brush {+ let mut b = Brush { name: t.name.clone(), ..Brush::round_pen() };+ b.shape.image = None;+ b.shape.source = Source::new(fitted(t));+ if let Some(spacing) = t.spacing {+ b.spacing = spacing.clamp(0.01, 10.0);+ }+ b+}++/// A brush of a Krita preset: its tip (round, or an image), spacing, angle, and what pressure+/// changes.+fn krita_brush(k: &procraft_engine::krita::KritaBrush) -> Brush {+ use procraft_engine::krita::KritaTip;+ let image = match &k.tip {+ KritaTip::Round { .. } => None,+ KritaTip::Image(t) => Some(fitted(t)),+ KritaTip::Png(png) => png_tip(png).map(|t| fitted(&t)),+ };+ let mut b = match image {+ Some(pixels) => {+ let mut b = Brush { name: k.name.clone(), ..Brush::round_pen() };+ b.shape.image = None;+ b.shape.source = Source::new(pixels);+ b+ }+ None => Brush { name: k.name.clone(), ..Brush::round_pen() },+ };+ if let KritaTip::Round { hardness, roundness } = k.tip {+ b.hardness = hardness.clamp(0.0, 1.0);+ b.shape.roundness = roundness.clamp(0.01, 1.0);+ }+ if let Some(spacing) = k.spacing {+ b.spacing = spacing.clamp(0.01, 10.0);+ }+ b.shape.rotation = k.angle;+ if !k.pressure_size {+ b.pressure_size = 0.0;+ }+ if k.pressure_opacity {+ b.pressure_opacity = 1.0;+ }+ b+}++/// A PNG tip as a grey one: dark, opaque pixels paint.+fn png_tip(png: &[u8]) -> Option<procraft_engine::abr::AbrTip> {+ let (w, h, channels, buf) = decode_png(png)?;+ let pixels: Vec<u8> = buf+ .chunks_exact(channels.max(1))+ .take(w * h)+ .map(|px| {+ let get = |k: usize| u32::from(px.get(k).copied().unwrap_or(0));+ let (grey, alpha) = match channels {+ 1 => (get(0), 255),+ 2 => (get(0), get(1)),+ 3 => ((get(0) * 299 + get(1) * 587 + get(2) * 114) / 1000, 255),+ _ => ((get(0) * 299 + get(1) * 587 + get(2) * 114) / 1000, get(3)),+ };+ ((255 - grey.min(255)) * alpha / 255) as u8+ })+ .collect();+ (pixels.len() == w * h).then(|| procraft_engine::abr::AbrTip {+ name: String::new(),+ spacing: None,+ width: w as u32,+ height: h as u32,+ pixels,+ })+}+fn brush_from(file: &BrushFile) -> Brush {// only the curves the file has (a control without one doesn't follow the pressure)let mut b = Brush { name: file.name.clone(), pressure_curves: Default::default(), ..Brush::round_pen() };diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex 97e0a7b..2c49c96 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -2817,12 +2817,12 @@ fn a_photoshop_brush_files_tips_become_a_set() {file.extend_from_slice(&(body.len() as u32).to_be_bytes());file.extend_from_slice(&body);let s = CanvasSession::new(64, 64);- assert_eq!(s.import_abr(file, "Chalk".into()), Some(0));+ assert_eq!(s.import_other_brushes(file, "Chalk".into()), Some(0));let library = s.brush_library();let set = library.first().unwrap();assert_eq!(set.name, "Chalk");assert_eq!(set.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Tip"]);- assert_eq!(s.import_abr(b"nothing".to_vec(), String::new()), None);+ assert_eq!(s.import_other_brushes(b"nothing".to_vec(), String::new()), None);}/// Real brush files, when a folder of them is given (`BRUSH_CORPUS=folder`, never committed):@@ -2856,7 +2856,8 @@ fn a_corpus_of_real_brush_files_imports_draws_and_round_trips() {let Some(s) = session(64, 64) else { return };let bytes = std::fs::read(path).unwrap();let kind = extension(path);- let set = if kind == "abr" { s.import_abr(bytes, "Corpus".to_owned()) } else { s.import_brushes(bytes) };+ let set =+ if kind == "abr" { s.import_other_brushes(bytes, "Corpus".to_owned()) } else { s.import_brushes(bytes) };let Some(set) = set else {failures.push(format!("{}: not imported", path.display()));continue;@@ -2950,7 +2951,7 @@ fn a_gimp_brush_becomes_a_brush_with_its_spacing() {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 set = s.import_other_brushes(file, "Charcoal pack".to_owned()).unwrap();let library = s.brush_library();let set = &library[set as usize];assert_eq!(set.name, "Charcoal pack");@@ -3001,3 +3002,29 @@ fn a_moving_gif_comes_in_as_held_frames() {// a still picture isn't takenassert_eq!(s.insert_gif_frames(b"GIF89a".to_vec(), false), None);}++#[test]+fn a_krita_preset_becomes_a_round_brush_with_its_settings() {+ let s = CanvasSession::new(64, 64);+ let xml = r#"<Preset paintopid="paintbrush" name="Soft Round"><param name="PressureSize"><![CDATA[false]]></param><param name="brush_definition"><![CDATA[<Brush type="auto_brush" spacing="0.2" useAutoSpacing="0"><MaskGenerator type="circle" ratio="0.5" hfade="0.25" vfade="0.25"/></Brush>]]></param></Preset>"#;+ let chunk = |kind: &[u8], data: &[u8]| {+ let mut out = (data.len() as u32).to_be_bytes().to_vec();+ out.extend_from_slice(kind);+ out.extend_from_slice(data);+ out.extend_from_slice(&[0; 4]);+ out+ };+ let mut kpp = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];+ kpp.extend(chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]));+ let mut text = b"preset\0".to_vec();+ text.extend_from_slice(xml.as_bytes());+ kpp.extend(chunk(b"tEXt", &text));+ kpp.extend(chunk(b"IEND", &[]));+ let set = s.import_other_brushes(kpp, "Krita".to_owned()).unwrap() as usize;+ let st = s.shared.lock();+ let b = &st.library[set].brushes[0];+ assert_eq!(b.name, "Soft Round");+ assert!((b.spacing - 0.2).abs() < 1e-6 && (b.hardness - 0.25).abs() < 1e-6 && b.shape.roundness == 0.5);+ assert_eq!(b.pressure_size, 0.0);+ assert!(b.shape.source.is_none());+}diff --git a/crates/engine/src/abr.rs b/crates/engine/src/abr.rsindex a37ca48..0349059 100644--- a/crates/engine/src/abr.rs+++ b/crates/engine/src/abr.rs@@ -4,7 +4,7 @@//! read; computed (round) tips have no image and are left out./// One brush tip from the file.-#[derive(Debug, PartialEq)]+#[derive(Clone, Debug, PartialEq)]pub struct AbrTip {pub name: String,/// Space between stamps, as a share of the tip's size, if the file gives it.diff --git a/crates/engine/src/krita.rs b/crates/engine/src/krita.rsnew file mode 100644index 0000000..67020b0--- /dev/null+++ b/crates/engine/src/krita.rs@@ -0,0 +1,299 @@+//! Reading Krita brushes: a preset (`.kpp`) is a PNG whose `preset` text holds the brush's+//! settings as XML, its tip either drawn from a few numbers (an auto brush) or an image it names;+//! a bundle (`.bundle`) is a zip of presets (`paintoppresets/`) and the images they name+//! (`brushes/`: GIMP brushes, PNGs, ABR files).++use crate::abr::AbrTip;+use crate::xml::{self, Element};+use crate::zip::ZipReader;++/// A brush as a Krita preset has it.+#[derive(Clone, Debug, PartialEq)]+pub struct KritaBrush {+ pub name: String,+ pub tip: KritaTip,+ /// Space between stamps as a share of the size, if the preset sets it (not automatic).+ pub spacing: Option<f32>,+ /// The tip's own angle, radians.+ pub angle: f32,+ /// Whether pen pressure changes the size and the opacity.+ pub pressure_size: bool,+ pub pressure_opacity: bool,+}++/// What a preset's tip is.+#[derive(Clone, Debug, PartialEq)]+pub enum KritaTip {+ /// A round tip: its edge (0 soft to 1 hard) and how round it is (1 a circle).+ Round { hardness: f32, roundness: f32 },+ /// A grey image (white paints).+ Image(AbrTip),+ /// A PNG to read as one (dark and opaque paints).+ Png(Vec<u8>),+}++/// The most presets read from a bundle.+const MOST_PRESETS: usize = 512;+/// The most a text chunk inflates to.+const MOST_TEXT: usize = 16 << 20;+/// The side a drawn rectangular tip is made at.+const DRAWN_SIDE: usize = 128;++/// The preset in `kpp`, its tip images looked up by file name with `file`; none if it isn't one.+pub fn read_preset(kpp: &[u8], file: &dyn Fn(&str) -> Option<Vec<u8>>) -> Option<KritaBrush> {+ let text = png_text(kpp).into_iter().find(|(k, _)| k == "preset")?.1;+ let root = xml::parse(&text)?;+ if root.name != "Preset" {+ return None;+ }+ let param = |name: &str| {+ root.all("param").into_iter().find(|p| p.attribute("name") == Some(name)).map(|p| p.text.trim().to_owned())+ };+ let definition = param("brush_definition").and_then(|d| xml::parse(&d));+ let brush = definition.as_ref().and_then(|d| d.find("Brush"));+ let number = |e: Option<&Element>, key: &str| {+ e.and_then(|e| e.attribute(key)).and_then(|v| v.trim().parse::<f32>().ok()).filter(|v| v.is_finite())+ };+ let automatic = brush.and_then(|b| b.attribute("useAutoSpacing")).is_some_and(|v| v == "1" || v == "true");+ let tip = brush.and_then(|b| tip(b, file)).unwrap_or(KritaTip::Round { hardness: 1.0, roundness: 1.0 });+ Some(KritaBrush {+ name: root.attribute("name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Krita Brush").to_owned(),+ tip,+ spacing: if automatic { None } else { number(brush, "spacing").filter(|s| *s > 0.0) },+ angle: number(brush, "angle").unwrap_or(0.0),+ pressure_size: param("PressureSize").is_none_or(|v| v == "true"),+ pressure_opacity: param("PressureOpacity").is_some_and(|v| v == "true"),+ })+}++/// The presets in a bundle, in its order, with its name; none if it isn't one.+pub fn read_bundle(bytes: &[u8]) -> Option<(String, Vec<KritaBrush>)> {+ let zip = ZipReader::new(bytes)?;+ let names: Vec<String> = zip.names().map(str::to_owned).collect();+ let is_bundle = zip.read("mimetype").is_some_and(|m| m.starts_with(b"application/x-krita-resourcebundle"))+ || names.iter().any(|n| n == "META-INF/manifest.xml");+ if !is_bundle {+ return None;+ }+ let title = zip+ .read("meta.xml")+ .and_then(|m| xml::parse(&String::from_utf8_lossy(&m)))+ .and_then(|m| ["title", "name"].iter().find_map(|k| m.find(k).map(|e| e.text.trim().to_owned())))+ .filter(|t| !t.is_empty())+ .unwrap_or_default();+ // a tip named by a preset: in the brushes folder, by its file name+ let file = |wanted: &str| {+ let wanted = wanted.rsplit(['/', '\\']).next().unwrap_or(wanted).to_ascii_lowercase();+ names+ .iter()+ .find(|n| {+ n.starts_with("brushes/") && n.rsplit('/').next().is_some_and(|f| f.to_ascii_lowercase() == wanted)+ })+ .and_then(|n| zip.read(n))+ };+ let presets: Vec<KritaBrush> = names+ .iter()+ .filter(|n| n.starts_with("paintoppresets/") && n.to_ascii_lowercase().ends_with(".kpp"))+ .take(MOST_PRESETS)+ .filter_map(|n| read_preset(&zip.read(n)?, &file))+ .collect();+ (!presets.is_empty()).then_some((title, presets))+}++/// The tip a `Brush` element describes.+fn tip(brush: &Element, file: &dyn Fn(&str) -> Option<Vec<u8>>) -> Option<KritaTip> {+ let number = |e: &Element, key: &str, or: f32| {+ e.attribute(key).and_then(|v| v.trim().parse::<f32>().ok()).filter(|v| v.is_finite()).unwrap_or(or)+ };+ match brush.attribute("type")? {+ "auto_brush" => {+ let mask = brush.find("MaskGenerator")?;+ let ratio = number(mask, "ratio", 1.0).clamp(0.01, 1.0);+ // the fades: the share of the radius that is solid (1 hard)+ let (hfade, vfade) =+ (number(mask, "hfade", 1.0).clamp(0.0, 1.0), number(mask, "vfade", 1.0).clamp(0.0, 1.0));+ if mask.attribute("type") == Some("rect") {+ return Some(KritaTip::Image(rectangle(ratio, hfade, vfade)));+ }+ Some(KritaTip::Round { hardness: (hfade + vfade) / 2.0, roundness: ratio })+ }+ _ => {+ let name = brush.attribute("filename")?;+ let bytes = file(name)?;+ let lower = name.to_ascii_lowercase();+ if lower.ends_with(".png") {+ Some(KritaTip::Png(bytes))+ } else if lower.ends_with(".abr") {+ let tips = crate::abr::read(&bytes)?;+ let wanted = brush.attribute("name");+ let at = tips.iter().position(|t| Some(t.name.as_str()) == wanted).unwrap_or(0);+ tips.into_iter().nth(at).map(KritaTip::Image)+ } else {+ crate::gbr::read(&bytes)?.into_iter().next().map(KritaTip::Image)+ }+ }+ }+}++/// A rectangular tip drawn: `ratio` as tall as it is wide, solid to `hfade` and `vfade` of the way+/// out, fading to the edge.+fn rectangle(ratio: f32, hfade: f32, vfade: f32) -> AbrTip {+ let n = DRAWN_SIDE;+ let height = ((n as f32 * ratio).round() as usize).max(1);+ let edge = |t: f32, solid: f32| {+ if t <= solid {+ 1.0+ } else if solid >= 1.0 {+ 0.0+ } else {+ ((1.0 - t) / (1.0 - solid)).clamp(0.0, 1.0)+ }+ };+ let mut pixels = Vec::with_capacity(n * height);+ for y in 0..height {+ let ty = ((y as f32 + 0.5) / height as f32 * 2.0 - 1.0).abs();+ for x in 0..n {+ let tx = ((x as f32 + 0.5) / n as f32 * 2.0 - 1.0).abs();+ pixels.push((edge(tx, hfade) * edge(ty, vfade) * 255.0).round() as u8);+ }+ }+ AbrTip { name: String::new(), spacing: None, width: n as u32, height: height as u32, pixels }+}++/// A PNG's text chunks (`tEXt`, `zTXt`, `iTXt`), keyword and text; none if it isn't a PNG.+pub fn png_text(png: &[u8]) -> Vec<(String, String)> {+ let mut out = Vec::new();+ if png.get(..8) != Some(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A][..]) {+ return out;+ }+ let mut at = 8usize;+ while let Some(len) = png.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes) {+ let Some(kind) = png.get(at + 4..at + 8) else { break };+ let len = len as usize;+ let Some(data) = png.get(at + 8..(at + 8).saturating_add(len)) else { break };+ at = at.saturating_add(12).saturating_add(len);+ let (keyword, rest) = match data.iter().position(|&b| b == 0) {+ Some(z) => (+ String::from_utf8_lossy(data.get(..z).unwrap_or_default()).into_owned(),+ data.get(z + 1..).unwrap_or_default(),+ ),+ None => continue,+ };+ let text = match kind {+ b"tEXt" => Some(rest.iter().map(|&b| char::from(b)).collect()),+ b"zTXt" => rest.get(1..).and_then(inflate),+ b"iTXt" => {+ // compressed or not, the method, then the language and translated keyword+ let (Some(&compressed), Some(body)) = (rest.first(), rest.get(2..)) else { continue };+ let mut parts = body.splitn(3, |&b| b == 0);+ let (_, _, text) = (parts.next(), parts.next(), parts.next().unwrap_or_default());+ if compressed == 1 { inflate(text) } else { Some(String::from_utf8_lossy(text).into_owned()) }+ }+ b"IEND" => break,+ _ => None,+ };+ if let Some(t) = text {+ out.push((keyword, t));+ }+ }+ out+}++fn inflate(data: &[u8]) -> Option<String> {+ let bytes = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, MOST_TEXT).ok()?;+ Some(String::from_utf8_lossy(&bytes).into_owned())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::zip::ZipWriter;++ fn chunk(kind: &[u8], data: &[u8]) -> Vec<u8> {+ let mut out = (data.len() as u32).to_be_bytes().to_vec();+ out.extend_from_slice(kind);+ out.extend_from_slice(data);+ out.extend_from_slice(&[0; 4]);+ out+ }++ /// A preset's PNG: no picture to speak of, its XML in a compressed text chunk.+ fn kpp(xml: &str) -> Vec<u8> {+ let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];+ png.extend(chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0]));+ png.extend(chunk(b"tEXt", b"version\x005.0"));+ let mut z = b"preset\0\0".to_vec();+ z.extend(miniz_oxide::deflate::compress_to_vec_zlib(xml.as_bytes(), 6));+ png.extend(chunk(b"zTXt", &z));+ png.extend(chunk(b"IEND", &[]));+ png+ }++ fn preset(name: &str, brush: &str, pressure_size: bool) -> String {+ format!(+ r#"<Preset paintopid="paintbrush" name="{name}"><param type="string" name="PressureSize"><![CDATA[{pressure_size}]]></param><param type="string" name="PressureOpacity"><![CDATA[true]]></param><param type="string" name="brush_definition"><![CDATA[{brush}]]></param></Preset>"#+ )+ }++ #[test]+ fn an_auto_brush_preset_reads_as_a_round_tip() {+ let brush = r#"<Brush type="auto_brush" spacing="0.15" angle="0.5" useAutoSpacing="0"><MaskGenerator type="circle" diameter="40" ratio="0.5" hfade="0.2" vfade="0.4"/></Brush>"#;+ let b = read_preset(&kpp(&preset("Soft Ellipse", brush, false)), &|_| None).unwrap();+ assert_eq!(b.name, "Soft Ellipse");+ assert_eq!(b.spacing, Some(0.15));+ assert_eq!(b.angle, 0.5);+ assert!(!b.pressure_size && b.pressure_opacity);+ match b.tip {+ KritaTip::Round { hardness, roundness } => assert!((hardness - 0.3).abs() < 1e-6 && roundness == 0.5),+ t => panic!("{t:?}"),+ }+ // a rectangle is drawn, solid in the middle and gone at the edge+ let rect = r#"<Brush type="auto_brush" useAutoSpacing="1"><MaskGenerator type="rect" ratio="1" hfade="0.5" vfade="0.5"/></Brush>"#;+ let b = read_preset(&kpp(&preset("Square", rect, true)), &|_| None).unwrap();+ assert_eq!(b.spacing, None);+ let KritaTip::Image(t) = b.tip else { panic!() };+ assert_eq!(t.pixels[64 * 128 + 64], 255);+ assert!(t.pixels[64 * 128] < 10);+ }++ #[test]+ fn a_bundle_reads_its_presets_and_the_tips_they_name() {+ // a GIMP brush 2 × 1 for the tip+ let mut gbr = Vec::new();+ for v in [28u32 + 1, 2, 2, 1, 1] {+ gbr.extend_from_slice(&v.to_be_bytes());+ }+ gbr.extend_from_slice(b"GIMP");+ gbr.extend_from_slice(&10u32.to_be_bytes());+ gbr.push(0);+ gbr.extend_from_slice(&[255, 128]);+ let mut z = ZipWriter::new();+ z.add("mimetype", b"application/x-krita-resourcebundle");+ z.add("META-INF/manifest.xml", b"<manifest/>");+ z.add("meta.xml", b"<meta><dc:title>Charcoals</dc:title></meta>");+ z.add("brushes/Charcoal.gbr", &gbr);+ let named = r#"<Brush type="gbr_brush" filename="charcoal.gbr" spacing="0.3"/>"#;+ z.add("paintoppresets/charcoal.kpp", &kpp(&preset("Charcoal", named, true)));+ z.add("paintoppresets/broken.kpp", b"not a preset");+ let (title, presets) = read_bundle(&z.finish()).unwrap();+ assert_eq!(title, "Charcoals");+ assert_eq!(presets.len(), 1);+ let KritaTip::Image(t) = &presets[0].tip else { panic!("{:?}", presets[0].tip) };+ assert_eq!((t.width, t.height, t.pixels.as_slice()), (2, 1, &[255, 128][..]));+ assert_eq!(presets[0].spacing, Some(0.3));+ // a tip that isn't there: round+ let missing = r#"<Brush type="gbr_brush" filename="gone.gbr"/>"#;+ let b = read_preset(&kpp(&preset("Gone", missing, true)), &|_| None).unwrap();+ assert!(matches!(b.tip, KritaTip::Round { .. }));+ }++ #[test]+ fn other_files_and_damaged_ones_are_not_brushes() {+ assert!(read_preset(b"nothing", &|_| None).is_none());+ assert!(read_bundle(b"nothing").is_none());+ let good = kpp(&preset("Ink", r#"<Brush type="auto_brush"><MaskGenerator type="circle"/></Brush>"#, true));+ crate::damaged::survives("Krita preset", &good, |b| {+ let _ = read_preset(b, &|_| None);+ });+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 888291f..4222231 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -27,6 +27,7 @@ pub mod icc;pub mod input;pub mod jpeg;pub mod keyed;+pub mod krita;pub mod library;pub mod mesh;pub mod motion;@@ -45,4 +46,5 @@ pub mod transform;pub mod usd;pub mod view;pub mod warp;+pub mod xml;pub mod zip;diff --git a/crates/engine/src/xml.rs b/crates/engine/src/xml.rsnew file mode 100644index 0000000..371ecd6--- /dev/null+++ b/crates/engine/src/xml.rs@@ -0,0 +1,235 @@+//! A small, forgiving XML reader for the settings other painting apps keep as XML: elements with+//! their attributes, text and children. What it can't make sense of ends the document there.++/// An element: its name (with any prefix), attributes, text (CDATA included) and children.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Element {+ pub name: String,+ pub attributes: Vec<(String, String)>,+ pub text: String,+ pub children: Vec<Element>,+}++/// How deep elements may nest.+const MOST_DEPTH: usize = 256;++impl Element {+ /// The attribute `name` (a prefixed one matches by the part after its prefix).+ pub fn attribute(&self, name: &str) -> Option<&str> {+ self.attributes.iter().find(|(k, _)| local(k) == name).map(|(_, v)| v.as_str())+ }++ /// The first child named `name` (by the part after any prefix).+ pub fn child(&self, name: &str) -> Option<&Element> {+ self.children.iter().find(|c| local(&c.name) == name)+ }++ /// The first element named `name` here or anywhere below, depth first.+ pub fn find(&self, name: &str) -> Option<&Element> {+ let mut stack = vec![self];+ while let Some(e) = stack.pop() {+ if local(&e.name) == name {+ return Some(e);+ }+ stack.extend(e.children.iter().rev());+ }+ None+ }++ /// Every element named `name` here and below, in document order.+ pub fn all(&self, name: &str) -> Vec<&Element> {+ let mut out = Vec::new();+ let mut stack = vec![self];+ while let Some(e) = stack.pop() {+ if local(&e.name) == name {+ out.push(e);+ }+ stack.extend(e.children.iter().rev());+ }+ out+ }+}++fn local(name: &str) -> &str {+ name.rsplit_once(':').map_or(name, |(_, l)| l)+}++/// The root element of `text`; none if there is none.+pub fn parse(text: &str) -> Option<Element> {+ let mut stack: Vec<Element> = Vec::new();+ let mut root = None;+ let mut rest = text;+ // closes the innermost open element into its parent (or as the root)+ let close = |stack: &mut Vec<Element>, root: &mut Option<Element>| {+ if let Some(done) = stack.pop() {+ match stack.last_mut() {+ Some(parent) => parent.children.push(done),+ None => *root = root.take().or(Some(done)),+ }+ }+ };+ while !rest.is_empty() && root.is_none() {+ let Some(lt) = rest.find('<') else {+ if let Some(top) = stack.last_mut() {+ top.text.push_str(&unescape(rest));+ }+ break;+ };+ if lt > 0+ && let Some(top) = stack.last_mut()+ {+ top.text.push_str(&unescape(rest.get(..lt)?));+ }+ rest = rest.get(lt..)?;+ if let Some(after) = rest.strip_prefix("<![CDATA[") {+ let (data, more) = after.split_once("]]>").unwrap_or((after, ""));+ if let Some(top) = stack.last_mut() {+ top.text.push_str(data);+ }+ rest = more;+ } else if let Some(after) = rest.strip_prefix("<!--") {+ rest = after.split_once("-->").map_or("", |(_, m)| m);+ } else if rest.starts_with("<?") || rest.starts_with("<!") {+ rest = rest.split_once('>').map_or("", |(_, m)| m);+ } else if let Some(after) = rest.strip_prefix("</") {+ rest = after.split_once('>').map_or("", |(_, m)| m);+ close(&mut stack, &mut root);+ } else {+ let (tag, more) = split_tag(rest.get(1..)?)?;+ rest = more;+ let closed = tag.trim_end().ends_with('/');+ let tag = tag.trim_end().trim_end_matches('/');+ let name_end = tag.find(|c: char| c.is_whitespace()).unwrap_or(tag.len());+ let element = Element {+ name: tag.get(..name_end)?.to_owned(),+ attributes: attributes(tag.get(name_end..)?),+ ..Element::default()+ };+ if stack.len() >= MOST_DEPTH {+ return None;+ }+ stack.push(element);+ if closed {+ close(&mut stack, &mut root);+ }+ }+ }+ // an unfinished document: what it has, closed+ while root.is_none() && !stack.is_empty() {+ close(&mut stack, &mut root);+ }+ root+}++/// A tag's inside up to its `>` (not one in a quoted value), and what follows.+fn split_tag(s: &str) -> Option<(&str, &str)> {+ let mut quote = None;+ for (i, c) in s.char_indices() {+ match (quote, c) {+ (None, '"' | '\'') => quote = Some(c),+ (Some(q), _) if c == q => quote = None,+ (None, '>') => return Some((s.get(..i)?, s.get(i + 1..)?)),+ _ => {}+ }+ }+ None+}++/// `name="value"` pairs (or with single quotes).+fn attributes(mut s: &str) -> Vec<(String, String)> {+ let mut out = Vec::new();+ loop {+ s = s.trim_start();+ let Some(eq) = s.find('=') else { break };+ let name = s.get(..eq).unwrap_or_default().trim().to_owned();+ let after = s.get(eq + 1..).unwrap_or_default().trim_start();+ let Some(q) = after.chars().next().filter(|c| *c == '"' || *c == '\'') else { break };+ let body = after.get(1..).unwrap_or_default();+ let Some(end) = body.find(q) else { break };+ out.push((name, unescape(body.get(..end).unwrap_or_default())));+ s = body.get(end + 1..).unwrap_or_default();+ }+ out+}++/// Text with its entities (named and numbered) put back.+pub fn unescape(s: &str) -> String {+ if !s.contains('&') {+ return s.to_owned();+ }+ let mut out = String::with_capacity(s.len());+ let mut rest = s;+ while let Some(amp) = rest.find('&') {+ out.push_str(rest.get(..amp).unwrap_or_default());+ let after = rest.get(amp + 1..).unwrap_or_default();+ let Some(semi) = after.find(';').filter(|&n| n <= 10) else {+ out.push('&');+ rest = after;+ continue;+ };+ let entity = after.get(..semi).unwrap_or_default();+ let ch = match entity {+ "lt" => Some('<'),+ "gt" => Some('>'),+ "amp" => Some('&'),+ "quot" => Some('"'),+ "apos" => Some('\''),+ _ => entity+ .strip_prefix("#x")+ .or_else(|| entity.strip_prefix("#X"))+ .and_then(|h| u32::from_str_radix(h, 16).ok())+ .or_else(|| entity.strip_prefix('#').and_then(|d| d.parse().ok()))+ .and_then(char::from_u32),+ };+ match ch {+ Some(c) => out.push(c),+ None => {+ out.push('&');+ out.push_str(entity);+ out.push(';');+ }+ }+ rest = after.get(semi + 1..).unwrap_or_default();+ }+ out.push_str(rest);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn elements_attributes_text_and_cdata_read() {+ let doc = r#"<?xml version="1.0"?>+<!-- a preset -->+<Preset paintopid="paintbrush" name="Ink & Wash">+ <param type="string" name="OpacityValue"><![CDATA[0.5]]></param>+ <param name='brush_definition'><![CDATA[<Brush type="auto_brush"><MaskGenerator ratio="1"/></Brush>]]></param>+ <empty/>+ <dc:title>Café <set></dc:title>+</Preset>"#;+ let root = parse(doc).unwrap();+ assert_eq!((root.name.as_str(), root.attribute("name")), ("Preset", Some("Ink & Wash")));+ let params = root.all("param");+ assert_eq!(params.len(), 2);+ assert_eq!(params[0].text, "0.5");+ let inner = parse(¶ms[1].text).unwrap();+ assert_eq!(inner.find("MaskGenerator").and_then(|m| m.attribute("ratio")), Some("1"));+ assert_eq!(root.child("title").map(|t| t.text.as_str()), Some("Café <set>"));+ assert!(root.child("empty").is_some());+ }++ #[test]+ fn broken_documents_give_what_they_have() {+ let root = parse("<a x=\"1\"><b>text").unwrap();+ assert_eq!(root.child("b").map(|b| b.text.as_str()), Some("text"));+ assert_eq!(parse("no markup"), None);+ assert_eq!(unescape("a &bogus; b & c"), "a &bogus; b & c");+ let deep = "<a>".repeat(1000);+ assert_eq!(parse(&deep), None);+ crate::damaged::survives("XML", br#"<a k="v"><b><![CDATA[x]]></b>&<!-- c --></a>"#, |b| {+ let _ = parse(&String::from_utf8_lossy(b));+ });+ }+}