Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
fix: scans keep their orientation, find the page more reliably, and can be cropped and named (#12)
Josh5732d6edc7f1
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.ktindex a81bd4c..32ebe09 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt@@ -1516,6 +1516,9 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {/** The pages scanned so far. */val scanPages = androidx.compose.runtime.mutableStateListOf<ScanPage>()++ /** The scan's file name (without .pdf), set when its first page is taken and changeable before saving. */+ var scanName by mutableStateOf("")private var shotFile: File? = nullprivate var retakeIndex: Int? = null@@ -1799,7 +1802,15 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {val r = retakeIndexretakeIndex = nullif (r != null && r in scanPages.indices) scanPages[r] = page else scanPages.add(page)+ if (scanName.isBlank()) scanName = "Scan " + java.text.SimpleDateFormat("yyyy-MM-dd HH.mm.ss", java.util.Locale.US).format(java.util.Date())if (toolScreen != ToolScreen.Scan) toolScreen = ToolScreen.Scan+ // the document's edges in the photo, shown on the page and moved in Crop; the whole+ // photo is kept when none are found+ val found = engine?.let { eng -> runCatching { eng.tool("photo_find_document", mapOf("path" to f.absolutePath)) }.getOrNull() }+ ?.takeIf { it.optBoolean("found") }?.optJSONArray("corners")?.takeIf { it.length() == 8 }+ ?.let { a -> FloatArray(8) { a.optDouble(it).toFloat() } }+ val at = scanPages.indexOfFirst { it.file == f }+ if (found != null && at >= 0) scanPages[at] = scanPages[at].copy(corners = found, found = found)}}@@ -1820,20 +1831,28 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {fun discardScan() {scanPages.forEach { it.file.delete() }scanPages.clear()+ scanName = ""insertScanAt = nulltoolScreen = null}/** Save the scanned pages as a PDF with [filter]'s look (or insert them where Organize asked). */fun saveScan(filter: ScanFilter) = job("Saving scan…") { eng ->- val paths = scanPages.map { it.file.absolutePath }+ val pages = scanPages.toList()+ val paths = pages.map { it.file.absolutePath }val created = eng.tool("doc_create", mapOf("from" to "images", "paths" to paths, "name" to "Scan"))val id = created.optLong("doc")try {- // every page is straightened (Original keeps its look); pages whose edges can't be found keep the whole photo- for (p in 1..paths.size) {- busy = "Cleaning up page $p of ${paths.size}…"- runCatching { eng.tool("page_enhance_camera", mapOf("doc" to id, "page" to p, "mode" to filter.mode, "level" to filter.level)) }+ // each page keeps the part inside its corners, straightened, with the look; a whole+ // photo in Original stays as it was taken+ val sizes = eng.tool("doc_info", mapOf("doc" to id)).optJSONArray("pages")+ for ((i, page) in pages.withIndex()) {+ if (page.corners.contentEquals(ScanPage.WHOLE) && filter == ScanFilter.Original) continue+ val size = sizes?.optJSONObject(i) ?: continue+ val (w, h) = size.optDouble("width") to size.optDouble("height")+ val corners = page.corners.mapIndexed { k, v -> v * if (k % 2 == 0) w else h }+ busy = "Cleaning up page ${i + 1} of ${pages.size}…"+ runCatching { eng.tool("page_enhance_camera", mapOf("doc" to id, "page" to i + 1, "corners" to corners, "mode" to filter.mode, "level" to filter.level)) }}// the scan's words become text, searchable and selectable, when text recognition is installedwithContext(Dispatchers.IO) { runCatching { eng.prepareOcrModels(getApplication()) } }@@ -1845,14 +1864,16 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {eng.tool("doc_save", mapOf("doc" to id, "path" to out.absolutePath, "full" to true))val target = insertScanAtinsertScanAt = null+ val chosen = scanName.trim()scanPages.forEach { it.file.delete() }scanPages.clear()+ scanName = ""toolScreen = nullif (target != null) {runTool(target.first, "page_insert_file", mapOf("path" to out.absolutePath, "at" to target.second))} else {val stamp = java.text.SimpleDateFormat("yyyy-MM-dd HH.mm.ss", java.util.Locale.US).format(java.util.Date())- val name = "Scan $stamp.pdf"+ val name = DocumentFiles.safeName(chosen.ifEmpty { "Scan $stamp" })val uri = withContext(Dispatchers.IO) { files.saveToDownloads(out, name).also { out.delete() } }tell("Saved as $name in Downloads")open(uri)diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.ktindex 44da357..83955e9 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ToolScreens.kt@@ -64,6 +64,7 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.ImageBitmapimport androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.clipPathimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalDensity@@ -645,8 +646,16 @@ fun CropScreen(vm: AppViewModel, doc: OpenDocument) {}-/** A scanned page: the photo's file and its thumbnail. */-data class ScanPage(val file: java.io.File, val thumb: ImageBitmap)+/**+ * A scanned page: the photo's file, its thumbnail (as taken) and the part of it kept: [corners]+ * as shares of the photo's width and height (x1, y1 … x4, y4 from the top left, clockwise), the+ * whole photo when No crop was chosen or no edges were found. [found] is what Auto-detect found.+ */+data class ScanPage(val file: java.io.File, val thumb: ImageBitmap, val corners: FloatArray = WHOLE, val found: FloatArray? = null) {+ companion object {+ val WHOLE = floatArrayOf(0f, 0f, 1f, 0f, 1f, 1f, 0f, 1f)+ }+}/** The looks a scan can have, and how the engine's camera clean-up gives each. */enum class ScanFilter(val label: String, val mode: String, val level: Int) {@@ -657,23 +666,49 @@ enum class ScanFilter(val label: String, val mode: String, val level: Int) {LightText("Light text", "bw", 60),}-/** Scan: pages taken with the camera, reviewed (retake, delete, look), then saved as a PDF. */+/** Scan: pages taken with the camera, reviewed (name, retake, crop, delete, look), then saved as a PDF. */@Composablefun ScanScreen(vm: AppViewModel) {val c = pdfColorsval pages = vm.scanPagesvar filter by remember { mutableStateOf(ScanFilter.AutoColor) }var current by remember { mutableStateOf(0) }+ var cropping by remember { mutableStateOf<java.io.File?>(null) }+ var naming by remember { mutableStateOf(false) }LaunchedEffect(Unit) { if (pages.isEmpty()) vm.takeScanPhoto() }+ // a page just taken is the one shown+ var seen by remember { mutableStateOf(pages.size) }+ LaunchedEffect(pages.size) {+ if (pages.size > seen) current = pages.lastIndex+ seen = pages.size+ }+ val croppingAt = pages.indexOfFirst { it.file == cropping }+ if (croppingAt >= 0) {+ ScanCrop(pages[croppingAt], onDone = { pages[croppingAt] = pages[croppingAt].copy(corners = it); cropping = null }, onCancel = { cropping = null })+ return+ }ToolScaffold(if (pages.isEmpty()) "Scan" else "Page ${current.coerceAtMost(pages.lastIndex) + 1} of ${pages.size}",{ vm.discardScan() },"Save PDF", pages.isNotEmpty(), { vm.saveScan(filter) },) {+ // the new file's name, changeable before it's saved (not when the pages go into an open document)+ if (vm.insertScanAt == null && vm.scanName.isNotBlank()) {+ Row(+ Modifier.fillMaxWidth().clickable { naming = true }.padding(horizontal = 16.dp, vertical = 10.dp).semantics { contentDescription = "File name: ${vm.scanName}. Change" },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(LucideIcons.FileText, null, tint = c.icon, modifier = Modifier.size(20.dp))+ Spacer(Modifier.width(12.dp))+ Text(vm.scanName, color = c.text, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))+ Spacer(Modifier.width(12.dp))+ Icon(LucideIcons.Pencil, null, tint = c.icon, modifier = Modifier.size(20.dp))+ }+ }Box(Modifier.weight(1f).fillMaxWidth().background(c.desk), contentAlignment = Alignment.Center) {val page = pages.getOrNull(current.coerceAtMost(pages.lastIndex))if (page != null) {- Image(page.thumb, null, modifier = Modifier.fillMaxSize().padding(16.dp), contentScale = ContentScale.Fit)+ ScanPhoto(page.thumb, page.corners, Modifier.fillMaxSize())} else {Text("Take a photo of each page", color = c.textSecondary)}@@ -696,7 +731,106 @@ fun ScanScreen(vm: AppViewModel) {}Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceEvenly) {TextButton(onClick = { vm.retakeScan(current) }, enabled = pages.isNotEmpty()) { Text("Retake", color = c.accent) }+ TextButton(onClick = { cropping = pages.getOrNull(current.coerceAtMost(pages.lastIndex))?.file }, enabled = pages.isNotEmpty()) { Text("Crop", color = c.accent) }TextButton(onClick = { if (pages.isNotEmpty()) { pages.removeAt(current.coerceAtMost(pages.lastIndex)); current = (current - 1).coerceAtLeast(0) } }, enabled = pages.isNotEmpty()) { Text("Delete", color = c.accent) }}}+ if (naming) {+ var name by remember { mutableStateOf(vm.scanName) }+ PdfDialog(+ onDismiss = { naming = false }, title = "File name",+ confirm = "OK", confirmEnabled = name.isNotBlank(), onConfirm = { vm.scanName = name.trim(); naming = false },+ ) {+ PdfField(name, { name = it }, "File name")+ }+ }+}++/**+ * Crop one scanned page: drag the corners onto the document's, or take what Auto-detect found,+ * or the whole photo (No crop).+ */+@Composable+private fun ScanCrop(page: ScanPage, onDone: (FloatArray) -> Unit, onCancel: () -> Unit) {+ val c = pdfColors+ var corners by remember(page.file) { mutableStateOf(page.corners) }+ ToolScaffold("Crop", onCancel, "Done", true, { onDone(corners) }) {+ Box(Modifier.weight(1f).fillMaxWidth().background(c.desk)) {+ ScanPhoto(page.thumb, corners, Modifier.fillMaxSize(), onMove = { corners = it })+ }+ Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceEvenly) {+ TextButton(onClick = { page.found?.let { corners = it } }, enabled = page.found != null) { Text("Auto-detect", color = if (page.found != null) c.accent else c.textSecondary) }+ TextButton(onClick = { corners = ScanPage.WHOLE }) { Text("No crop", color = c.accent) }+ }+ }+}++/** Whether [q] (x1, y1 … x4, y4) is a convex quadrilateral, its corners going round one way. */+private fun convexQuad(q: FloatArray): Boolean {+ var sign = 0+ for (i in 0 until 4) {+ val (ax, ay) = q[2 * i] to q[2 * i + 1]+ val (bx, by) = q[2 * ((i + 1) % 4)] to q[2 * ((i + 1) % 4) + 1]+ val (cx, cy) = q[2 * ((i + 2) % 4)] to q[2 * ((i + 2) % 4) + 1]+ val cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx)+ val s = if (cross > 1e-6f) 1 else if (cross < -1e-6f) -1 else return false+ if (sign != 0 && s != sign) return false+ sign = s+ }+ return true+}++/**+ * A scanned page's photo, fitted, with the part kept outlined and the rest dimmed: [corners] as+ * shares of the photo. With [onMove], each corner has a handle to drag (the shape stays a convex+ * four-sided one, as straightening needs).+ */+@Composable+private fun ScanPhoto(thumb: ImageBitmap, corners: FloatArray, modifier: Modifier = Modifier, onMove: ((FloatArray) -> Unit)? = null) {+ val c = pdfColors+ val density = LocalDensity.current+ BoxWithConstraints(modifier) {+ // room around the photo for the handles+ val pad = with(density) { (if (onMove != null) 24.dp else 16.dp).toPx() }+ val k = minOf((constraints.maxWidth - 2 * pad) / thumb.width, (constraints.maxHeight - 2 * pad) / thumb.height).coerceAtLeast(0.01f)+ val (iw, ih) = thumb.width * k to thumb.height * k+ val origin = Offset((constraints.maxWidth - iw) / 2f, (constraints.maxHeight - ih) / 2f)+ val latest = androidx.compose.runtime.rememberUpdatedState(corners)+ val point = { q: FloatArray, i: Int -> Offset(origin.x + q[2 * i] * iw, origin.y + q[2 * i + 1] * ih) }+ val drag = if (onMove == null) Modifier else Modifier.pointerInput(thumb, iw, ih) {+ var held = -1+ detectDragGestures(+ onDragStart = { p ->+ val q = latest.value+ held = (0..3).minByOrNull { (point(q, it) - p).getDistance() }?.takeIf { (point(q, it) - p).getDistance() < 48.dp.toPx() } ?: -1+ },+ onDragEnd = { held = -1 },+ onDragCancel = { held = -1 },+ ) { change, d ->+ if (held < 0) return@detectDragGestures+ change.consume()+ val q = latest.value.copyOf()+ q[2 * held] = (q[2 * held] + d.x / iw).coerceIn(0f, 1f)+ q[2 * held + 1] = (q[2 * held + 1] + d.y / ih).coerceIn(0f, 1f)+ if (convexQuad(q)) onMove(q)+ }+ }+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize().then(drag)) {+ drawImage(thumb, dstOffset = IntOffset(origin.x.roundToInt(), origin.y.roundToInt()), dstSize = androidx.compose.ui.unit.IntSize(iw.roundToInt().coerceAtLeast(1), ih.roundToInt().coerceAtLeast(1)))+ val quad = androidx.compose.ui.graphics.Path().apply {+ (0..3).forEach { i -> point(corners, i).let { if (i == 0) moveTo(it.x, it.y) else lineTo(it.x, it.y) } }+ close()+ }+ clipPath(quad, androidx.compose.ui.graphics.ClipOp.Difference) {+ drawRect(Color.Black.copy(alpha = 0.5f), origin, Size(iw, ih))+ }+ drawPath(quad, c.accent, style = Stroke(2.dp.toPx()))+ if (onMove != null) {+ for (i in 0..3) {+ drawCircle(Color.White, 11.dp.toPx(), point(corners, i))+ drawCircle(c.accent, 11.dp.toPx(), point(corners, i), style = Stroke(2.5.dp.toPx()))+ }+ }+ }+ }}diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex 8970194..7bc0c85 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -243,6 +243,17 @@ impl Automation {out["detected"] = json!(given.is_none());out}+ "photo_find_document" => {+ let path = self.resolve(a.str("path")?, false)?;+ let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;+ match pdfcraft_engine::camera::find_document_in_photo(&bytes) {+ Some(q) => {+ let r = |v: f64| (v * 10_000.0).round() / 10_000.0;+ json!({ "found": true, "corners": q.iter().flat_map(|&[x, y]| [r(x), r(y)]).collect::<Vec<f64>>() })+ }+ None => json!({ "found": false }),+ }+ }"page_delete" => {let pages = self.pages(&a, "pages")?;self.apply(&a, Edit::DeletePages { pages })?diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex b91b7b8..d9e07db 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -198,6 +198,9 @@ pub fn tools() -> Vec<ToolDef> {}),&["doc", "page"],)),+ t("photo_find_document", "Find a document in a photo", "Scan: the corners of the document (a sheet, a card, a receipt) in the photo at path (JPEG or PNG), before it becomes a page, so they can be shown and adjusted: corners [x1, y1, … x4, y4] as shares (0–1) of the photo's width and height the way it was taken (its EXIF orientation applied), top-left, top-right, bottom-right, bottom-left. found is false when no document's edges convince.")+ .ro()+ .with(schema(json!({ "path": { "type": "string" } }), &["path"])),t("page_delete", "Delete pages", "Delete pages. Undoable until saved.").destructive().cmd("page.delete")diff --git a/crates/engine/src/camera.rs b/crates/engine/src/camera.rsindex 69318a8..fe5818b 100644--- a/crates/engine/src/camera.rs+++ b/crates/engine/src/camera.rs@@ -89,6 +89,29 @@ pub fn warp(rgba: &[u8], width: u32, height: u32, quad: [Point; 4]) -> Result<Wa/// The long side, in pixels, a page is rendered at to look for the document's edges.const DETECT_SIDE: f32 = 1200.0;+/// Photos larger than this are not decoded to look for a document (hundreds of MB).+const MAX_PHOTO_PIXELS: u64 = 64 << 20;++/// Scan: the corners of the document in a photo file's bytes (JPEG, PNG), before it becomes a+/// page, so they can be shown and moved. As shares of the photo's width and height (0–1) the+/// way it was taken (its EXIF Orientation applied): top-left, top-right, bottom-right,+/// bottom-left. `None` when the photo can't be read or no document's edges convince.+pub fn find_document_in_photo(bytes: &[u8]) -> Option<[Point; 4]> {+ use image::ImageDecoder;+ let mut decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;+ let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);+ let (w, h) = decoder.dimensions();+ if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PHOTO_PIXELS {+ return None;+ }+ let mut photo = image::DynamicImage::from_decoder(decoder).ok()?;+ photo.apply_orientation(orientation);+ let side = DETECT_SIDE as u32;+ let small = if photo.width().max(photo.height()) > side { photo.thumbnail(side, side) } else { photo };+ let (sw, sh) = (small.width(), small.height());+ let quad = crate::camera_edges::detect_document(small.to_rgba8().as_raw(), sw, sh)?;+ Some(quad.map(|[x, y]| [(x / sw as f64).clamp(0.0, 1.0), (y / sh as f64).clamp(0.0, 1.0)]))+}impl Session {/// Enhance ▸ Camera image: the corners of the photographed document on page `page`@@ -263,6 +286,60 @@ mod tests {assert!(out.rgb.iter().all(|&v| v == 255));}+ /// A JPEG photo of a light sheet (corners in stored pixels) on a dark table, tagged with EXIF+ /// `orientation` (1: as stored; 6: shown turned 90° clockwise, as phones store portrait shots).+ fn sheet_photo(w: u32, h: u32, sheet: [Point; 4], orientation: u8) -> Vec<u8> {+ let q = order_quad(sheet).unwrap();+ let inside = |x: f64, y: f64| {+ (0..4).all(|i| {+ let (a, b) = (q[i], q[(i + 1) % 4]);+ (b[0] - a[0]) * (y - a[1]) - (b[1] - a[1]) * (x - a[0]) >= 0.0+ })+ };+ let img =+ image::RgbImage::from_fn(w, h, |x, y| image::Rgb(if inside(x as f64 + 0.5, y as f64 + 0.5) { [240, 238, 232] } else { [70, 60, 50] }));+ let mut jpeg = Vec::new();+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90).encode_image(&img).unwrap();+ if orientation == 1 {+ return jpeg;+ }+ let mut exif = b"Exif\0\0II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();+ exif.extend_from_slice(&[orientation, 0, 0, 0, 0, 0, 0, 0]);+ let mut out = jpeg[..2].to_vec();+ out.extend_from_slice(&[0xff, 0xe1]);+ out.extend_from_slice(&((exif.len() + 2) as u16).to_be_bytes());+ out.extend_from_slice(&exif);+ out.extend_from_slice(&jpeg[2..]);+ out+ }++ fn assert_near(found: Option<[Point; 4]>, want: [Point; 4]) {+ let found = found.expect("the sheet should be found");+ for (f, w) in found.iter().zip(want.iter()) {+ assert!((f[0] - w[0]).abs() <= 0.012 && (f[1] - w[1]).abs() <= 0.012, "found {found:?}, want {want:?}");+ }+ }++ #[test]+ fn finds_the_sheet_in_a_photo_the_way_it_was_taken() {+ let sheet = [[200.0, 150.0], [1000.0, 120.0], [1050.0, 780.0], [150.0, 800.0]];+ assert_near(find_document_in_photo(&sheet_photo(1200, 900, sheet, 1)), sheet.map(|[x, y]| [x / 1200.0, y / 900.0]));+ // Tagged "turned 90° clockwise", the photo is 900 × 1200 as taken: a stored point (x, y)+ // shows at (900 − y, x), and the corners are named as they show.+ let shown = order_quad(sheet.map(|[x, y]| [(900.0 - y) / 900.0, x / 1200.0])).unwrap();+ assert_near(find_document_in_photo(&sheet_photo(1200, 900, sheet, 6)), shown);+ }++ #[test]+ fn a_photo_without_a_document_or_not_a_photo_is_none() {+ let blank = image::RgbImage::from_pixel(300, 200, image::Rgb([90, 90, 90]));+ let mut jpeg = Vec::new();+ image::codecs::jpeg::JpegEncoder::new(&mut jpeg).encode_image(&blank).unwrap();+ assert_eq!(find_document_in_photo(&jpeg), None);+ assert_eq!(find_document_in_photo(b"not a picture"), None);+ assert_eq!(find_document_in_photo(&[]), None);+ }+#[test]fn bad_corners_and_rasters_are_errors_not_panics() {let src = raster(10, 10, |_, _| [0, 0, 0]);diff --git a/crates/engine/src/camera_edges.rs b/crates/engine/src/camera_edges.rsindex 7084dd5..ecff80e 100644--- a/crates/engine/src/camera_edges.rs+++ b/crates/engine/src/camera_edges.rs@@ -4,22 +4,27 @@//! caller falls back to corners the user places.//!//! Steps: shrink the picture to [`WORK`] pixels on its long side, blur it, take Sobel gradients-//! and keep thin, strong edges; vote for lines (a Hough transform that only votes along each-//! edge's own gradient direction, give or take a few degrees); pair two near-horizontal with two near-vertical lines; keep-//! the quadrilaterals whose four sides lie on edges, and choose the largest.+//! and keep thin edges; vote for lines (a Hough transform that only votes along each edge's own+//! gradient direction, give or take a few degrees, each edge pixel counting about the same, so a+//! long faint sheet edge outvotes shorter, darker lines of text); take the strongest+//! near-horizontal and near-vertical lines separately (text lines would otherwise take every+//! place); pair two of each; keep the quadrilaterals whose four sides lie on edges, and choose+//! the largest.use pdfcraft_geom::perspective::{Point, order_quad};/// The working size: the long side of the shrunken picture, in pixels.const WORK: usize = 400;-/// The most lines tried (strongest first).-const MAX_LINES: usize = 24;+/// The most lines tried of each direction, near-horizontal and near-vertical (strongest first).+const MAX_LINES: usize = 16;/// A side counts when at least this share of it lies on a matching edge.const MIN_SUPPORT: f64 = 0.55;/// A document fills at least this share of the picture.const MIN_AREA: f64 = 0.12;/// How far (share of the picture's size) a corner may lie outside the picture.const MARGIN: f64 = 0.02;+/// The faintest gradient that is an edge (Sobel, on 0–255 grey): below it is noise and grain.+const EDGE_FLOOR: f32 = 24.0;/// A grey picture, row-major, read with bounds checks.struct Grey {@@ -115,11 +120,13 @@ fn edges(g: &Grey) -> Vec<Option<Edge>> {grad.push(Edge { mag: gx.hypot(gy), dir: gy.atan2(gx) });}}- // The threshold: a share of the 98th percentile, never below a faint-edge floor.+ // The threshold: a small share of the 98th percentile, never below a faint-edge floor. The+ // percentile is often black text on the sheet; white paper on a light desk is a far weaker+ // edge, and must still count.let mut mags: Vec<f32> = grad.iter().map(|e| e.mag).filter(|m| m.is_finite()).collect();mags.sort_by(f32::total_cmp);let p98 = mags.get(mags.len() * 98 / 100).copied().unwrap_or(0.0);- let threshold = (0.25 * p98).max(24.0);+ let threshold = (0.08 * p98).max(EDGE_FLOOR);let mag = |x: isize, y: isize| -> f32 {if x < 0 || y < 0 || x >= g.w as isize || y >= g.h as isize {return 0.0;@@ -148,38 +155,62 @@ struct Line {}/// The strongest lines through the edges: each edge votes for the lines within 6° of its own-/// normal, weighted by its strength; peaks are taken strongest first, clearing their-/// neighbourhood.+/// normal, a faint one about half as much as a clear one (so a line's votes mostly say how long+/// it is), dark-to-light and light-to-dark edges apart (the two edges of a line of text are one+/// of each, and never add up to one long line); peaks are taken strongest first, clearing their+/// neighbourhood, up to [`MAX_LINES`] near-horizontal and as many near-vertical ones.fn hough(edges: &[Option<Edge>], w: usize, h: usize) -> Vec<Line> {const STEPS: usize = 180;let diag = ((w * w + h * h) as f64).sqrt().ceil() as usize;let rows = 2 * diag + 1;- let mut acc = vec![0.0f32; STEPS * rows];+ // Cell (side, θ, ρ): side 0 has the gradient along the normal (cos θ, sin θ), side 1 against it.+ let cell = |side: usize, t: usize, r: usize| (side * STEPS + t) * rows + r;+ let mut acc = vec![0.0f32; 2 * STEPS * rows];let trig: Vec<(f64, f64)> = (0..STEPS).map(|t| (t as f64).to_radians()).map(|a| (a.cos(), a.sin())).collect();for (i, e) in edges.iter().enumerate() {let Some(e) = e else { continue };let (x, y) = ((i % w) as f64, (i / w) as f64);- let normal = (e.dir as f64).to_degrees().rem_euclid(180.0).round() as isize;+ let dir = (e.dir as f64).to_degrees().rem_euclid(360.0).round() as isize;+ let (normal, side) = (dir.rem_euclid(STEPS as isize), usize::from(dir.rem_euclid(360) >= STEPS as isize));// ±6°: a jagged (aliased) edge's local gradient leans towards the axes.for t in normal - 6..=normal + 6 {+ // past 0° or 180° the normal turns round, and the gradient is on its other side+ let side = if (0..STEPS as isize).contains(&t) { side } else { 1 - side };let t = t.rem_euclid(STEPS as isize) as usize;let Some(&(c, s)) = trig.get(t) else { continue };let r = (x * c + y * s).round() as isize + diag as isize;- if let Some(cell) = usize::try_from(r).ok().and_then(|r| acc.get_mut(t * rows + r)) {- *cell += e.mag;+ if let Some(v) = usize::try_from(r).ok().filter(|&r| r < rows).and_then(|r| acc.get_mut(cell(side, t, r))) {+ *v += (e.mag / (2.0 * EDGE_FLOOR)).clamp(0.5, 1.0);}}}- let mut lines = Vec::new();+ // A line between two of the 1° steps spreads its votes over neighbouring ρ (a 300 px edge+ // half a degree off by 2–3 px): each line is scored by the votes within ±2 px of it, so a+ // slightly slanted sheet edge isn't outvoted by text lines that happen to fall on a step.+ let mut acc: Vec<f32> = (0..2 * STEPS * rows)+ .map(|i| {+ let (row, r) = (i / rows, i % rows);+ (r.saturating_sub(2)..=(r + 2).min(rows - 1)).filter_map(|q| acc.get(row * rows + q)).sum()+ })+ .collect();+ let mut lines: Vec<Line> = Vec::new();+ let (mut flat, mut upright) = (0, 0);let first = acc.iter().copied().fold(0.0f32, f32::max);- while lines.len() < MAX_LINES {+ while flat < MAX_LINES || upright < MAX_LINES {let Some((best, &v)) = acc.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)) else { break };if v <= 0.0 || v < 0.08 * first {break;}- let (t, r) = (best / rows, best % rows);- lines.push(Line { theta: (t as f64).to_radians(), rho: r as f64 - diag as f64 });- // Clear ±6° and ±6 px around the peak (θ wraps, flipping ρ's sign).+ let (t, r) = ((best / rows) % STEPS, best % rows);+ let line = Line { theta: (t as f64).to_radians(), rho: r as f64 - diag as f64 };+ // a direction that has its fill only clears the peak+ let count = if is_flat(&line) { &mut flat } else { &mut upright };+ if *count < MAX_LINES {+ *count += 1;+ lines.push(line);+ }+ // Clear ±6° and ±6 px around the peak, on both sides (a thin rule has an edge of each+ // on the same line; θ wraps, flipping ρ's sign).for dt in -6isize..=6 {let tt = t as isize + dt;let (tt, flip) = if tt < 0 {@@ -191,8 +222,11 @@ fn hough(edges: &[Option<Edge>], w: usize, h: usize) -> Vec<Line> {};let rr = if flip { 2 * diag as isize - r as isize } else { r as isize };for dr in -6isize..=6 {- if let Some(cell) = usize::try_from(rr + dr).ok().filter(|&q| q < rows).and_then(|q| acc.get_mut(tt as usize * rows + q)) {- *cell = 0.0;+ let Some(q) = usize::try_from(rr + dr).ok().filter(|&q| q < rows) else { continue };+ for side in 0..2 {+ if let Some(v) = acc.get_mut(cell(side, tt as usize, q)) {+ *v = 0.0;+ }}}}@@ -200,6 +234,11 @@ fn hough(edges: &[Option<Edge>], w: usize, h: usize) -> Vec<Line> {lines}+/// A line whose normal is within 45° of vertical: near-horizontal.+fn is_flat(l: &Line) -> bool {+ (l.theta.to_degrees() - 90.0).abs() <= 45.0+}+fn intersect(a: Line, b: Line) -> Option<Point> {let (c1, s1, c2, s2) = (a.theta.cos(), a.theta.sin(), b.theta.cos(), b.theta.sin());let det = c1 * s2 - s1 * c2;@@ -313,10 +352,8 @@ fn refine(q: [Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[/// The convex quadrilateral of two near-horizontal and two near-vertical lines whose four sides/// all lie on edges, scored by its area times the square of its sides' mean support.fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[Point; 4]> {- // A normal within 45° of vertical makes a near-horizontal line.- let flat = |l: &&Line| (l.theta.to_degrees() - 90.0).abs() <= 45.0;- let horizontal: Vec<&Line> = lines.iter().filter(flat).collect();- let vertical: Vec<&Line> = lines.iter().filter(|l| !flat(l)).collect();+ let horizontal: Vec<&Line> = lines.iter().filter(|l| is_flat(l)).collect();+ let vertical: Vec<&Line> = lines.iter().filter(|l| !is_flat(l)).collect();let (fw, fh) = (w as f64, h as f64);let (mx, my) = (MARGIN * fw, MARGIN * fh);let mut best: Option<(f64, [Point; 4])> = None;@@ -491,6 +528,84 @@ mod tests {assert_eq!(detect_document(&img, 900, 1200), None);}+ /// Corners close to the picture's edges: the sheet nearly fills the frame, as when a page is+ /// photographed close up.+ const CLOSE: [Point; 4] = [[40.0, 50.0], [860.0, 40.0], [870.0, 1160.0], [30.0, 1170.0]];++ #[test]+ fn a_sheet_filling_almost_the_whole_picture() {+ assert_near(detect_document(&photo_boxed(900, 1200, CLOSE, 240.0, 95.0, false), 900, 1200), CLOSE, 6.0);+ // Its top edge 1–2 % from the picture's: twelve lines of text must not take its place.+ let closer = [[15.0, 20.0], [885.0, 12.0], [890.0, 1185.0], [10.0, 1190.0]];+ assert_near(detect_document(&photo_boxed(900, 1200, closer, 240.0, 95.0, false), 900, 1200), closer, 6.0);+ }++ #[test]+ fn white_paper_on_a_light_desk() {+ // The sheet's edges are far fainter than its black text.+ assert_near(detect_document(&photo_boxed(900, 1200, SHEET, 245.0, 200.0, false), 900, 1200), SHEET, 6.0);+ }++ #[test]+ fn a_form_is_found_by_its_sheet_not_its_ruled_box() {+ for (sheet, desk) in [(SHEET, 205.0), (SHEET, 90.0), (CLOSE, 120.0)] {+ assert_near(detect_document(&photo_boxed(900, 1200, sheet, 240.0, desk, true), 900, 1200), sheet, 6.0);+ }+ }++ /// [`photo`] with text, plus (when `boxed`) a form's thick ruled box over most of the sheet.+ fn photo_boxed(w: u32, h: u32, sheet: [Point; 4], paper: f32, desk: f32, boxed: bool) -> Vec<u8> {+ let base = photo(w, h, sheet, paper, |_, _| desk, true, 5.0);+ if !boxed {+ return base;+ }+ let at = |u: f64, v: f64| -> Point {+ let top = [sheet[0][0] + (sheet[1][0] - sheet[0][0]) * u, sheet[0][1] + (sheet[1][1] - sheet[0][1]) * u];+ let bot = [sheet[3][0] + (sheet[2][0] - sheet[3][0]) * u, sheet[3][1] + (sheet[2][1] - sheet[3][1]) * u];+ [top[0] + (bot[0] - top[0]) * v, top[1] + (bot[1] - top[1]) * v]+ };+ let outer = [at(0.07, 0.08), at(0.93, 0.08), at(0.93, 0.92), at(0.07, 0.92)];+ let inner = [at(0.075, 0.084), at(0.925, 0.084), at(0.925, 0.916), at(0.075, 0.916)];+ let mut out = base;+ for y in 0..h {+ for x in 0..w {+ let (fx, fy) = (x as f64 + 0.5, y as f64 + 0.5);+ if inside(&outer, fx, fy) && !inside(&inner, fx, fy) {+ let i = ((y * w + x) * 4) as usize;+ out[i..i + 3].copy_from_slice(&[25, 25, 25]);+ }+ }+ }+ out+ }++ #[test]+ fn thin_lines_of_text_do_not_take_the_sheets_edge() {+ // Eighteen thin lines of text and a title, the sheet's top edge slanting between two of+ // the 1° steps: each line's two edges must not add up to outvote the sheet's one.+ let sheet = [[156.0, 180.0], [744.0, 150.0], [798.0, 1032.0], [102.0, 1074.0]];+ let mut img = photo(900, 1200, sheet, 236.0, |_, _| 85.0, false, 4.0);+ let at = |u: f64, v: f64| -> Point {+ let top = [sheet[0][0] + (sheet[1][0] - sheet[0][0]) * u, sheet[0][1] + (sheet[1][1] - sheet[0][1]) * u];+ let bot = [sheet[3][0] + (sheet[2][0] - sheet[3][0]) * u, sheet[3][1] + (sheet[2][1] - sheet[3][1]) * u];+ [top[0] + (bot[0] - top[0]) * v, top[1] + (bot[1] - top[1]) * v]+ };+ let mut bars = vec![[at(0.1, 0.07), at(0.6, 0.07), at(0.6, 0.1), at(0.1, 0.1)]];+ for k in 0..18 {+ let (v, u1) = (0.16 + k as f64 * 0.042, if k % 5 == 4 { 0.55 } else { 0.9 });+ bars.push([at(0.1, v), at(u1, v), at(u1, v + 0.012), at(0.1, v + 0.012)]);+ }+ for y in 0..1200u32 {+ for x in 0..900u32 {+ if bars.iter().any(|b| inside(b, x as f64 + 0.5, y as f64 + 0.5)) {+ let i = ((y * 900 + x) * 4) as usize;+ img[i..i + 3].copy_from_slice(&[40, 40, 45]);+ }+ }+ }+ assert_near(detect_document(&img, 900, 1200), sheet, 6.0);+ }+#[test]fn bad_input_is_none_not_a_panic() {assert_eq!(detect_document(&[], 0, 0), None);diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex c9a0a45..658adaa 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -3584,12 +3584,21 @@ impl Session {/// A new document with one page per image (PNG, JPEG).pub fn create_from_images(&self, images: &[(String, Vec<u8>)]) -> Result<Arc<Vec<u8>>, EditError> {- self.write_new(&pdfcraft_create::from_images(images)?)+ self.create_from_images_with_resolution(images, ImageResolution::Embedded)}- /// Create image pages at embedded resolution or a fixed dpi, without resampling.+ /// Create image pages at embedded resolution or a fixed dpi, without resampling. A phone+ /// photo stored sideways (EXIF Orientation) becomes a page the way it was taken: a portrait+ /// sheet makes a portrait page.pub fn create_from_images_with_resolution(&self, images: &[(String, Vec<u8>)], resolution: ImageResolution) -> Result<Arc<Vec<u8>>, EditError> {- self.write_new(&pdfcraft_create::from_images_with_resolution(images, resolution)?)+ let upright: Vec<(String, Vec<u8>)> = images+ .iter()+ .map(|(name, bytes)| match upright_image::upright(bytes) {+ std::borrow::Cow::Owned(turned) => (name.clone(), turned),+ std::borrow::Cow::Borrowed(_) => (name.clone(), bytes.clone()),+ })+ .collect();+ self.write_new(&pdfcraft_create::from_images_with_resolution(&upright, resolution)?)}/// A new document from plain text (US Letter, 11 pt Helvetica). Text Helvetica can't draw isdiff --git a/crates/engine/src/upright_image.rs b/crates/engine/src/upright_image.rsindex dc2b9cd..e28bb51 100644--- a/crates/engine/src/upright_image.rs+++ b/crates/engine/src/upright_image.rs@@ -112,6 +112,21 @@ mod tests {assert!(matches!(upright(b"\xff\xd8 not a jpeg"), Cow::Borrowed(_)));}+ #[test]+ fn a_phone_photo_made_into_a_pdf_is_a_page_the_way_it_was_taken() {+ // Stored 60 × 20 px at 144 × 72 dpi (30 × 20 pt), shown turned: a 20 × 30 pt page.+ let mut session = crate::Session::new();+ let made = [+ session.create_from_images(&[("scan.jpg".into(), phone_jpeg(6, 144))]).unwrap(),+ session.create_from_images_with_resolution(&[("scan.jpg".into(), phone_jpeg(6, 144))], crate::ImageResolution::Embedded).unwrap(),+ ];+ for bytes in made {+ let id = session.open_new("scan.pdf", bytes).unwrap();+ let page = &session.get(id).unwrap().info.pages[0];+ assert!((page.width - 20.0).abs() < 0.01 && (page.height - 30.0).abs() < 0.01, "{} x {}", page.width, page.height);+ }+ }+#[test]fn a_phone_photo_used_as_a_custom_stamp_is_embedded_upright() {let mut session = crate::Session::new();