ProCraft for Android: An Android native painting app written in Rust
Rust
feat(import): a Krita preset's texture becomes the brush's paper grain
Josh01b58ec0f3ac
diff --git a/apps/procraft-android/src/brush_files.rs b/apps/procraft-android/src/brush_files.rsindex b985696..ceda818 100644--- a/apps/procraft-android/src/brush_files.rs+++ b/apps/procraft-android/src/brush_files.rs@@ -250,21 +250,27 @@ fn csp_brush(c: &procraft_engine::csp::CspBrush) -> Brush {b.spacing = Brush::spacing_within_reach(spacing);}b.shape.rotation = c.angle;- // its texture, the first of its pictures that lets paint through anywhere (one may be blank):- // paper the stroke paints through, at the picture's own size times its scale- let paper = c.texture.as_ref().and_then(|t| {- t.pngs.iter().find_map(|png| {- let source = gray_texture(png, t.reverse).filter(|s| s.pixels.iter().any(|&v| v > 0))?;- Some((source, decode_png(png)?.0, t))- })+ if let Some(t) = &c.texture {+ paper(&mut b, &t.pngs, t.reverse, t.density.unwrap_or(1.0), t.scale.unwrap_or(1.0));+ }+ b+}++/// Gives `b` another app's texture as its grain, paper the stroke paints through: the first of+/// `pngs` that lets paint through anywhere (one may be blank), dark letting it through if+/// `inverted`, showing `depth` strongly, tiled at the picture's own size times `scale`. Nothing if+/// none of them will do.+fn paper(b: &mut Brush, pngs: &[Vec<u8>], inverted: bool, depth: f32, scale: f32) {+ let found = pngs.iter().find_map(|png| {+ let source = gray_texture(png, inverted).filter(|s| s.pixels.iter().any(|&v| v > 0))?;+ Some((source, decode_png(png)?.0))});- if let Some((source, width, t)) = paper {+ if let Some((source, width)) = found {b.grain.image = None;b.grain.source = Some(source);- b.grain.depth = t.density.unwrap_or(1.0);- b.set_setting("grain_scale", width as f32 * t.scale.unwrap_or(1.0) / procraft_engine::studio::MAX_GRAIN_SCALE);+ b.grain.depth = depth.clamp(0.0, 1.0);+ b.set_setting("grain_scale", width as f32 * scale / procraft_engine::studio::MAX_GRAIN_SCALE);}- b}/// A brush of a GIMP generated brush: round with its hardness and how round it is, or its square@@ -327,6 +333,9 @@ fn krita_brush(k: &procraft_engine::krita::KritaBrush) -> Brush {if k.pressure_opacity {b.pressure_opacity = 1.0;}+ if let Some(t) = &k.texture {+ paper(&mut b, std::slice::from_ref(&t.png), t.invert, t.strength, t.scale);+ }b}diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex d3fd885..ca746f8 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -2855,7 +2855,7 @@ fn a_corpus_of_real_brush_files_imports_draws_and_round_trips() {// the preview left out: drawn again each timelet read = |b: &[u8]| brushfile::read(b).map(|f| BrushFile { thumbnail: None, ..f });let mut failures = Vec::new();- let mut brushes = 0;+ let (mut brushes, mut grained) = (0, 0);for path in &files {let Some(s) = session(64, 64) else { return };let bytes = std::fs::read(path).unwrap();@@ -2873,6 +2873,15 @@ fn a_corpus_of_real_brush_files_imports_draws_and_round_trips() {let count = if kind == "brush" { 1 } else { s.brush_library()[set as usize].brushes.len() as u32 };for i in 0..count {brushes += 1;+ if s.shared+ .lock()+ .library+ .get(set as usize)+ .and_then(|l| l.brushes.get(i as usize))+ .is_some_and(|b| b.grain.source.is_some())+ {+ grained += 1;+ }let at = format!("{} #{}", path.display(), i + 1);let drawn =s.brush_preview(set, i, 200, 60).is_some_and(|p| p.rgba.as_chunks::<4>().0.iter().any(|px| px[3] > 0));@@ -2896,7 +2905,7 @@ fn a_corpus_of_real_brush_files_imports_draws_and_round_trips() {}}}- eprintln!("{} files, {brushes} brushes", files.len());+ eprintln!("{} files, {brushes} brushes, {grained} with a grain of their own", files.len());assert!(failures.is_empty(), "{} failed:\n{}", failures.len(), failures.join("\n"));}@@ -3013,7 +3022,14 @@ fn a_moving_gif_comes_in_as_held_frames() {#[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>"#;+ // its texture: a 100 px picture, half white, kept as the base64 of its base64+ let px: Vec<u8> = (0..100 * 100).flat_map(|i| if i % 100 < 50 { [255; 4] } else { [0, 0, 0, 255] }).collect();+ let paper = procraft_engine::base64::encode(+ procraft_engine::base64::encode(&crate::project::rgba_png(100, 100, &px)).as_bytes(),+ );+ let xml = format!(+ 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><param name="Texture/Pattern/Enabled"><![CDATA[true]]></param><param name="Texture/Pattern/Pattern"><![CDATA[{paper}]]></param><param name="Texture/Pattern/Scale"><![CDATA[0.5]]></param><param name="Texture/Pattern/Strength"><![CDATA[0.7]]></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);@@ -3034,4 +3050,7 @@ fn a_krita_preset_becomes_a_round_brush_with_its_settings() {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());+ // the texture as paper grain: 70 % strong, its 100 px tiles at half size+ assert!(b.grain.source.is_some());+ assert_eq!((b.grain.depth, b.grain.scale), (0.7, 50.0));}diff --git a/crates/engine/src/krita.rs b/crates/engine/src/krita.rsindex 2cfd228..ab13888 100644--- a/crates/engine/src/krita.rs+++ b/crates/engine/src/krita.rs@@ -19,6 +19,18 @@ pub struct KritaBrush {/// Whether pen pressure changes the size and the opacity.pub pressure_size: bool,pub pressure_opacity: bool,+ /// The texture it paints through, if it has one.+ pub texture: Option<KritaTexture>,+}++/// A preset's texture: its picture (a PNG), its scale (1 the picture's own size), how strongly it+/// shows (0 to 1) and whether it is inverted.+#[derive(Clone, Debug, PartialEq)]+pub struct KritaTexture {+ pub png: Vec<u8>,+ pub scale: f32,+ pub strength: f32,+ pub invert: bool,}/// What a preset's tip is.@@ -39,6 +51,7 @@ const MOST_TIP_BYTES: usize = 256 << 20;const MOST_TEXT: usize = 16 << 20;/// The side a drawn rectangular tip is made at.const DRAWN_SIDE: usize = 128;+const PNG: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];/// 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> {@@ -57,6 +70,28 @@ pub fn read_preset(kpp: &[u8], file: &dyn Fn(&str) -> Option<Vec<u8>>) -> Option};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 });+ let flag = |name: &str| param(name).is_some_and(|v| v == "true");+ let value = |name: &str| param(name).and_then(|v| v.parse::<f32>().ok()).filter(|v| v.is_finite());+ // the texture's picture: in the preset, as the base64 of its base64; else one it names+ let embedded = || {+ let once = crate::base64::decode(¶m("Texture/Pattern/Pattern")?.split_whitespace().collect::<String>())?;+ if once.starts_with(&PNG) {+ return Some(once);+ }+ crate::base64::decode(&String::from_utf8_lossy(&once).split_whitespace().collect::<String>())+ };+ let texture = flag("Texture/Pattern/Enabled")+ .then(|| embedded().filter(|p| p.starts_with(&PNG)).or_else(|| file(¶m("Texture/Pattern/Name")?)))+ .flatten()+ .map(|png| KritaTexture {+ png,+ scale: value("Texture/Pattern/Scale").filter(|s| *s > 0.0).unwrap_or(1.0),+ strength: value("Texture/Pattern/Strength")+ .or_else(|| value("Texture/Strength/Value"))+ .unwrap_or(1.0)+ .clamp(0.0, 1.0),+ invert: flag("Texture/Pattern/Invert"),+ });Some(KritaBrush {name: root.attribute("name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Krita Brush").to_owned(),tip,@@ -64,6 +99,7 @@ pub fn read_preset(kpp: &[u8], file: &dyn Fn(&str) -> Option<Vec<u8>>) -> Optionangle: 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"),+ texture,})}@@ -82,22 +118,31 @@ pub fn read_bundle(bytes: &[u8]) -> Option<(String, Vec<KritaBrush>)> {.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; each preset has its own- // copy, so all of them together may be only so big (round tips after that)+ // a tip or texture named by a preset: in the brushes or patterns folder, by its file name; each+ // preset has its own copy, so all of them together may be only so big (round tips and no+ // textures after that)let left = std::cell::Cell::new(MOST_TIP_BYTES);+ let take = |n: usize| left.get().checked_sub(n).map(|l| left.set(l)).is_some();let file = |wanted: &str| {let wanted = wanted.rsplit(['/', '\\']).next().unwrap_or(wanted).to_ascii_lowercase();let name = names.iter().find(|n| {- n.starts_with("brushes/") && n.rsplit('/').next().is_some_and(|f| f.to_ascii_lowercase() == wanted)+ (n.starts_with("brushes/") || n.starts_with("patterns/"))+ && n.rsplit('/').next().is_some_and(|f| f.to_ascii_lowercase() == wanted)})?;- left.set(left.get().checked_sub(zip.size(name)?)?);- zip.read(name)+ take(zip.size(name)?).then(|| zip.read(name)).flatten()};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))+ .map(|mut p| {+ // its texture counts as well (one the bundle had, twice over: a rough budget)+ if p.texture.as_ref().is_some_and(|t| !take(t.png.len())) {+ p.texture = None;+ }+ p+ }).collect();(!presets.is_empty()).then_some((title, presets))}@@ -165,7 +210,7 @@ fn rectangle(ratio: f32, hfade: f32, vfade: f32) -> AbrTip {/// 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][..]) {+ if png.get(..8) != Some(&PNG[..]) {return out;}let mut at = 8usize;@@ -291,6 +336,45 @@ mod tests {assert!(matches!(b.tip, KritaTip::Round { .. }));}+ #[test]+ fn a_texture_comes_from_the_preset_itself_or_the_bundle() {+ let round = r#"<Brush type="auto_brush"><MaskGenerator type="circle"/></Brush>"#;+ let with = |params: &str| {+ let xml = preset("Pencil", round, true);+ xml.replace("</Preset>", &format!("{params}</Preset>"))+ };+ let param =+ |name: &str, value: &str| format!(r#"<param type="string" name="{name}"><![CDATA[{value}]]></param>"#);+ let picture = [&PNG[..], b"rest of a picture"].concat();+ // kept in the preset as the base64 of its base64+ let twice = crate::base64::encode(crate::base64::encode(&picture).as_bytes());+ let xml = with(+ &[+ param("Texture/Pattern/Enabled", "true"),+ param("Texture/Pattern/Pattern", &twice),+ param("Texture/Pattern/Scale", "0.35"),+ param("Texture/Pattern/Strength", "0.8"),+ param("Texture/Pattern/Invert", "true"),+ ]+ .concat(),+ );+ let t = read_preset(&kpp(&xml), &|_| None).unwrap().texture.unwrap();+ assert_eq!((t.png, t.scale, t.strength, t.invert), (picture.clone(), 0.35, 0.8, true));+ // turned off: none+ let off = with(&[param("Texture/Pattern/Enabled", "false"), param("Texture/Pattern/Pattern", &twice)].concat());+ assert_eq!(read_preset(&kpp(&off), &|_| None).unwrap().texture, None);+ // not in the preset: the one it names, from the bundle's patterns+ let named =+ with(&[param("Texture/Pattern/Enabled", "true"), param("Texture/Pattern/Name", "paper.png")].concat());+ let mut z = ZipWriter::new();+ z.add("mimetype", b"application/x-krita-resourcebundle");+ z.add("patterns/Paper.png", &picture);+ z.add("paintoppresets/pencil.kpp", &kpp(&named));+ let (_, presets) = read_bundle(&z.finish()).unwrap();+ let t = presets[0].texture.as_ref().unwrap();+ assert_eq!((&t.png, t.scale, t.strength, t.invert), (&picture, 1.0, 1.0, false));+ }+#[test]fn other_files_and_damaged_ones_are_not_brushes() {assert!(read_preset(b"nothing", &|_| None).is_none());