Skip to content

ProCraft for Android: An Android native painting app written in Rust

Rust

feat(gallery): PDF import, a layer a page with Page Assist on

Josh396946cd52ec
diff --git a/apps/procraft-android/android/app/src/main/AndroidManifest.xml b/apps/procraft-android/android/app/src/main/AndroidManifest.xml
index 88a40db..1317db8 100644
--- a/apps/procraft-android/android/app/src/main/AndroidManifest.xml
+++ b/apps/procraft-android/android/app/src/main/AndroidManifest.xml
@@ -30,6 +30,7 @@
<data android:mimeType="application/zip" />
<data android:mimeType="image/*" />
<data android:mimeType="application/x-photoshop" />
+ <data android:mimeType="application/pdf" />
</intent-filter>
</activity>
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.kt
index 4901726..123847f 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,6 +1397,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
newFromModel(uri, name)
} 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") {
+ importPdf(uri, name)
} else if (head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()) {
val ok = withContext(Dispatchers.IO) {
val dir = store.newFolder(galleryDir)
@@ -1409,6 +1411,61 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /**
+ * A PDF from [uri] made into a new artwork named after its file: each page a layer ("Page 1"
+ * at the bottom), drawn on white at [PDF_DPI] (the long side kept within [PDF_MOST_SIDE]) and
+ * fitted to the first page's size, with Page Assist on; a message says why if it can't be.
+ */
+ private suspend fun importPdf(uri: android.net.Uri, name: String?) {
+ val app = getApplication<Application>()
+ val outcome = withContext(Dispatchers.IO) {
+ val pages = File(app.cacheDir, "pdf-${System.nanoTime()}").apply { mkdirs() }
+ val dir = store.newFolder(galleryDir)
+ try {
+ app.contentResolver.openFileDescriptor(uri, "r")?.use { fd ->
+ android.graphics.pdf.PdfRenderer(fd).use { pdf ->
+ if (pdf.pageCount == 0) return@use io.github.artcraftandroid.procraft.core.PagesOutcome.Unreadable
+ // the canvas: the first page's size at the resolution, within the most side
+ val (w, h) = pdf.openPage(0).use { p ->
+ val scale = minOf(PDF_DPI / 72f, PDF_MOST_SIDE / maxOf(p.width, p.height).toFloat())
+ (p.width * scale).roundToInt().coerceAtLeast(1) to (p.height * scale).roundToInt().coerceAtLeast(1)
+ }
+ val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ for (i in 0 until pdf.pageCount) {
+ pdf.openPage(i).use { p ->
+ bitmap.eraseColor(android.graphics.Color.WHITE)
+ // each page fitted into the canvas, in its middle
+ val s = minOf(w / p.width.toFloat(), h / p.height.toFloat())
+ val m = android.graphics.Matrix().apply {
+ postScale(s, s)
+ postTranslate((w - p.width * s) / 2f, (h - p.height * s) / 2f)
+ }
+ p.render(bitmap, null, m, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
+ }
+ File(pages, "page-${i + 1}.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ bitmap.recycle()
+ io.github.artcraftandroid.procraft.core.importPages(
+ pages.path, pdf.pageCount.toUInt(), w.toUInt(), h.toUInt(), PDF_DPI, dir.path,
+ name?.substringBeforeLast('.')?.trim().orEmpty(),
+ )
+ }
+ } ?: io.github.artcraftandroid.procraft.core.PagesOutcome.Unreadable
+ } catch (e: Exception) {
+ android.util.Log.e("ProCraft", "importing a PDF", e)
+ io.github.artcraftandroid.procraft.core.PagesOutcome.Unreadable
+ } finally {
+ pages.deleteRecursively()
+ }.also { if (it != io.github.artcraftandroid.procraft.core.PagesOutcome.Imported) dir.deleteRecursively() }
+ }
+ when (outcome) {
+ io.github.artcraftandroid.procraft.core.PagesOutcome.Imported -> refreshGallery()
+ is io.github.artcraftandroid.procraft.core.PagesOutcome.TooManyPages ->
+ message = "This PDF has more pages than a canvas its size can hold as layers (${outcome.most})."
+ io.github.artcraftandroid.procraft.core.PagesOutcome.Unreadable -> message = "This PDF can't be opened."
+ }
+ }
+
/** A layered PSD from [uri] made into a new artwork, named after its file; a message says why if it can't be. */
private suspend fun importPsd(uri: android.net.Uri, name: String?) {
val app = getApplication<Application>()
@@ -5633,6 +5690,10 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
private const val SELECTION_THRESHOLD = "selectionThreshold"
private const val DROP_THRESHOLD = "dropThreshold"
+ /** A PDF's pages come in at this resolution, their long side at most [PDF_MOST_SIDE] pixels. */
+ private const val PDF_DPI = 300f
+ private const val PDF_MOST_SIDE = 4096
+
/** How long the band offers Continue filling after a drop. */
private const val DROP_BAND_MS = 2_500L
diff --git a/apps/procraft-android/src/project.rs b/apps/procraft-android/src/project.rs
index c6469ac..f16dd97 100644
--- a/apps/procraft-android/src/project.rs
+++ b/apps/procraft-android/src/project.rs
@@ -776,6 +776,91 @@ pub(crate) fn straight_alpha(rgba: &[u8]) -> Vec<u8> {
out
}
+/// How bringing in a document's pages went.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
+pub enum PagesOutcome {
+ Imported,
+ /// More pages than a canvas their size holds as layers (`most`).
+ TooManyPages {
+ most: u32,
+ },
+ /// A page couldn't be read.
+ Unreadable,
+}
+
+/// Makes an artwork named `name` in the folder `dir` from `count` pages, each a `width` x `height`
+/// PNG `page-N.png` (N from 1) in the folder `pages`: a layer each, "Page N", the first at the
+/// bottom, with Page Assist on and `dpi` its resolution. Used for a PDF's pages.
+#[uniffi::export]
+pub fn import_pages(
+ pages: String,
+ count: u32,
+ width: u32,
+ height: u32,
+ dpi: f32,
+ dir: String,
+ name: String,
+) -> PagesOutcome {
+ use procraft_engine::document::Layer;
+ let (w, h) = (
+ width.clamp(1, procraft_engine::document::MAX_CANVAS_EDGE),
+ height.clamp(1, procraft_engine::document::MAX_CANVAS_EDGE),
+ );
+ let most = Document::new(w, h).layer_cap();
+ if count as usize > most {
+ return PagesOutcome::TooManyPages { most: u32::try_from(most).unwrap_or(u32::MAX) };
+ }
+ let mut layers = Vec::new();
+ let mut pixels = Vec::new();
+ for n in 1..=count.max(1) {
+ let id = LayerId(u64::from(n));
+ match read_png(&Path::new(&pages).join(format!("page-{n}.png")), w, h) {
+ Ok(rgba) => pixels.push((id, rgba)),
+ Err(e) => {
+ log::error!("a page: {e}");
+ return PagesOutcome::Unreadable;
+ }
+ }
+ layers.push(Layer {
+ id,
+ name: format!("Page {n}"),
+ visible: true,
+ opacity: 1.0,
+ blend: BlendMode::Normal,
+ alpha_lock: false,
+ clipped: false,
+ locked: false,
+ reference: false,
+ kind: LayerKind::Paint,
+ parent: None,
+ collapsed: false,
+ text: None,
+ private: false,
+ assisted: false,
+ });
+ }
+ let mut doc = Document::from_layers(w, h, layers, LayerId(1));
+ if dpi.is_finite() && dpi > 0.0 {
+ doc.dpi = dpi.clamp(1.0, 9999.0);
+ }
+ doc.animation = Some(procraft_engine::animation::Animation { pages: true, ..Default::default() });
+ let name =
+ if name.trim().is_empty() { "Untitled Artwork".to_owned() } else { name.trim().chars().take(256).collect() };
+ // the first page is the gallery's thumbnail until the artwork is opened
+ let first = pixels.first().map(|(_, p)| thumbnail(p, w, h, THUMBNAIL_SIDE));
+ let session = CanvasSession::with_document(doc, name, pixels);
+ if let Err(e) = session.save(dir.clone()) {
+ log::error!("saving imported pages: {e}");
+ return PagesOutcome::Unreadable;
+ }
+ if let Some((tw, th, thumb)) = first
+ && let Err(e) = write_atomically(&Path::new(&dir).join("thumbnail.png"), |p| write_png(p, tw, th, &thumb, &[]))
+ {
+ log::error!("imported pages' thumbnail: {e}");
+ }
+ PagesOutcome::Imported
+}
+
/// How bringing in a PSD went.
#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
pub enum PsdOutcome {
diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rs
index 1fab8d8..7a46ab6 100644
--- a/apps/procraft-android/src/tests.rs
+++ b/apps/procraft-android/src/tests.rs
@@ -2708,3 +2708,47 @@ fn a_layer_shown_alone_hides_the_others_until_solo_ends() {
assert_eq!(s.solo(), None);
assert_eq!(pixel(&s, 20, 50), [0, 0, 0, 255]);
}
+
+#[test]
+fn a_documents_pages_come_in_as_page_layers() {
+ let dir = std::env::temp_dir().join(format!("procraft-pages-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let (w, h) = (6, 4);
+ for (n, v) in [(1, 200u8), (2, 40u8)] {
+ let rgba: Vec<u8> = std::iter::repeat_n([v, v, v, 255], (w * h) as usize).flatten().collect();
+ crate::project::write_png(&dir.join(format!("page-{n}.png")), w, h, &rgba, &[]).unwrap();
+ }
+ let art = dir.join("art");
+ let outcome = crate::project::import_pages(
+ dir.to_string_lossy().into_owned(),
+ 2,
+ w,
+ h,
+ 300.0,
+ art.to_string_lossy().into_owned(),
+ "Comic".into(),
+ );
+ assert_eq!(outcome, crate::project::PagesOutcome::Imported);
+ assert!(art.join("thumbnail.png").exists());
+ let s = CanvasSession::open(art.to_string_lossy().into_owned()).unwrap();
+ assert_eq!(s.name(), "Comic");
+ let names: Vec<String> = s.layers().iter().map(|l| l.name.clone()).collect();
+ // listed top first: the first page at the bottom
+ assert_eq!(names, ["Page 2", "Page 1"]);
+ assert!(s.animation_settings().is_some_and(|a| a.pages));
+ // a page missing
+ assert_eq!(
+ crate::project::import_pages(
+ dir.to_string_lossy().into_owned(),
+ 3,
+ w,
+ h,
+ 300.0,
+ dir.join("bad").to_string_lossy().into_owned(),
+ String::new()
+ ),
+ crate::project::PagesOutcome::Unreadable
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}