Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

feat: (desktop implementation) sign with a digital ID and check a document's signatures (#17)

Josh62f378abccc4
diff --git a/README.md b/README.md
index faf619e..b9979bd 100644
--- a/README.md
+++ b/README.md
@@ -208,6 +208,7 @@ PdfCraft for Android is in beta.
| Read aloud with the phone's voice, the words marked as they're read, and a full player | ✅ |
| Comments: notes, voice comments, highlight, underline, strikethrough, drawing (snap to shape), text; the Comment List and threads | ✅ |
| Forms, and Fill & Sign: text, marks and a drawn or imported signature | ✅ |
+| Digital signatures: sign with a digital ID (a .p12 / .pfx file, or one made in the app), check a document's signatures, trust signers | ✅ |
| Edit PDF: edit text, add text and images, move, resize and turn pictures | ✅ · cropping a picture ⬜ |
| Organize and crop pages | ✅ |
| Compress, combine, set password, create PDF (images, text, office documents), scan | ✅ |
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt
index 0514687..c01ca1a 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt
@@ -86,6 +86,8 @@ class MainActivity : ComponentActivity() {
FilePickKind.Combine -> pickMany.launch(arrayOf("application/pdf", "image/*", "text/plain") + OFFICE_TYPES)
FilePickKind.Create -> pickMany.launch(arrayOf("image/*", "text/plain", "application/pdf") + OFFICE_TYPES)
FilePickKind.Insert, FilePickKind.Open -> pickOne.launch(arrayOf("application/pdf"))
+ // .p12 / .pfx: providers type them as PKCS #12, or not at all
+ FilePickKind.DigitalId -> pickOne.launch(arrayOf("application/x-pkcs12", "application/pkcs12", "application/octet-stream"))
}
}
}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DigitalIds.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DigitalIds.kt
new file mode 100644
index 0000000..d7a8860
--- /dev/null
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/DigitalIds.kt
@@ -0,0 +1,119 @@
+package io.github.artcraftandroid.pdfcraft.engine
+
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import io.github.artcraftandroid.pdfcraft.core.DigitalIdInfo
+import java.io.File
+import org.json.JSONArray
+import org.json.JSONObject
+
+/** A digital ID the app keeps for signing: its file and what its certificate says. Times are seconds since 1970. */
+data class DigitalId(
+ val file: File,
+ val name: String,
+ val issuer: String,
+ val email: String?,
+ val validFrom: Long,
+ val validTo: Long,
+ val selfSigned: Boolean,
+ val sha256: String,
+) {
+ fun expired(nowMs: Long = System.currentTimeMillis()) = nowMs / 1000 > validTo
+ fun notYetValid(nowMs: Long = System.currentTimeMillis()) = nowMs / 1000 < validFrom
+}
+
+/**
+ * The digital IDs (.p12 / .pfx files) the reader added or made, copied into the app's private
+ * files with a small JSON list of their certificates. Their passwords are never kept: signing
+ * asks for one each time.
+ */
+class DigitalIds(dir: File) {
+ private val root = File(dir, "digital-ids").apply { mkdirs() }
+ private val index = File(root, "ids.json")
+ private val lock = Any()
+
+ var all by mutableStateOf(load())
+ private set
+
+ /** Keep a copy of the ID file [source] (its certificate described by [info]); one with the same certificate is replaced. */
+ fun add(source: File, info: DigitalIdInfo): DigitalId = synchronized(lock) {
+ val target = File(root, fileKey(info.sha256) + ".p12")
+ if (source.canonicalPath != target.canonicalPath) source.copyTo(target, overwrite = true)
+ val id = DigitalId(target, info.name, info.issuer, info.email, info.validFrom, info.validTo, info.selfSigned, info.sha256)
+ all = all.filter { it.sha256 != info.sha256 } + id
+ save()
+ id
+ }
+
+ fun remove(id: DigitalId) = synchronized(lock) {
+ id.file.delete()
+ all = all.filter { it.sha256 != id.sha256 }
+ save()
+ }
+
+ private fun load(): List<DigitalId> = runCatching {
+ if (!index.isFile) return@runCatching emptyList()
+ val a = JSONArray(index.readText())
+ (0 until a.length()).mapNotNull { i ->
+ val o = a.optJSONObject(i) ?: return@mapNotNull null
+ val file = File(root, o.optString("file"))
+ if (!file.isFile) return@mapNotNull null
+ DigitalId(
+ file, o.optString("name"), o.optString("issuer"), o.optString("email").ifEmpty { null },
+ o.optLong("validFrom"), o.optLong("validTo"), o.optBoolean("selfSigned"), o.optString("sha256"),
+ )
+ }
+ }.getOrDefault(emptyList())
+
+ private fun save() {
+ val a = JSONArray()
+ for (id in all) {
+ a.put(
+ JSONObject().put("file", id.file.name).put("name", id.name).put("issuer", id.issuer).put("email", id.email ?: "")
+ .put("validFrom", id.validFrom).put("validTo", id.validTo).put("selfSigned", id.selfSigned).put("sha256", id.sha256),
+ )
+ }
+ writeAtomically(index, a.toString())
+ }
+}
+
+/**
+ * The signers' certificates the reader chose to trust (DER files in the app's private files): the
+ * engine is given them at start, and a signature by one of them validates as trusted.
+ */
+class TrustedCertificates(dir: File) {
+ private val root = File(dir, "trusted").apply { mkdirs() }
+
+ /** Bumped on every change, for what shows whether a signer is trusted. */
+ var version by mutableStateOf(0)
+ private set
+
+ fun files(): List<File> = root.listFiles { f -> f.isFile && f.extension == "cer" }.orEmpty().sortedBy { it.name }
+
+ fun contains(sha256: String) = File(root, fileKey(sha256) + ".cer").isFile
+
+ fun add(der: ByteArray, sha256: String) {
+ File(root, fileKey(sha256) + ".cer").writeBytes(der)
+ version++
+ }
+
+ fun remove(sha256: String) {
+ File(root, fileKey(sha256) + ".cer").delete()
+ version++
+ }
+}
+
+/** A certificate fingerprint (hex, any spacing) as a file name. */
+private fun fileKey(sha256: String) = sha256.filter { it.isLetterOrDigit() }.lowercase().ifEmpty { "id" }
+
+private fun writeAtomically(file: File, text: String) {
+ runCatching {
+ val tmp = File(file.parentFile, file.name + ".tmp")
+ tmp.writeText(text)
+ if (!tmp.renameTo(file)) {
+ file.delete()
+ tmp.renameTo(file)
+ }
+ }
+}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppRoot.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppRoot.kt
index 2d24189..51cf3c6 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppRoot.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppRoot.kt
@@ -58,6 +58,10 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.artcraftandroid.pdfcraft.ui.home.HomeRoot
import io.github.artcraftandroid.pdfcraft.ui.home.SettingsScreen
+import io.github.artcraftandroid.pdfcraft.ui.viewer.CertSignScreen
+import io.github.artcraftandroid.pdfcraft.ui.viewer.CreateIdScreen
+import io.github.artcraftandroid.pdfcraft.ui.viewer.IdPasswordDialog
+import io.github.artcraftandroid.pdfcraft.ui.viewer.SignFieldChoiceDialog
import io.github.artcraftandroid.pdfcraft.ui.viewer.SignaturePadScreen
import io.github.artcraftandroid.pdfcraft.ui.viewer.ViewerScreen
@@ -104,6 +108,8 @@ fun AppRoot(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage: () ->
if (doc == null) vm.fileSheet?.let { (r, recent) -> io.github.artcraftandroid.pdfcraft.ui.home.FileSheet(vm, r, recent) { vm.fileSheet = null } }
vm.toolScreen?.let { ToolScreenHost(vm, it) }
vm.signaturePad?.let { SignaturePadScreen(vm, it, onPickSignatureImage) }
+ vm.certSign?.let { CertSignScreen(vm, it) }
+ if (vm.idCreate) CreateIdScreen(vm)
if (vm.settingsOpen) SettingsScreen(vm)
if (vm.showLicences) LicencesScreen(vm)
@@ -111,6 +117,8 @@ fun AppRoot(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage: () ->
SnackbarHost(snackbar, Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(bottom = 72.dp, start = 8.dp, end = 8.dp))
vm.passwordRequest?.let { PasswordDialog(vm, it) }
+ vm.idImport?.let { IdPasswordDialog(vm, it) }
+ vm.signFieldChoice?.let { (d, w) -> SignFieldChoiceDialog(vm, d, w) }
if (vm.authorPrompt) {
var name by remember { mutableStateOf("") }
PdfDialog(
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.kt
index 28e43ff..7b81ffb 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
@@ -90,6 +90,14 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
viewModelScope.launch {
application.engine.await().onSuccess { engine = it }.onFailure { engineProblem = it.userMessage }
refreshRecents()
+ // the signers the reader trusts, before any signature is checked
+ // (a document opened from another app meanwhile is checked again)
+ engine?.let { eng ->
+ if (withContext(Dispatchers.IO) { trustedCerts.files().isNotEmpty() }) {
+ runCatching { applyTrust(eng) }
+ document?.let { loadSignatures(eng, it) }
+ }
+ }
}
}
@@ -178,6 +186,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
// a file left in Reading Mode reopens in it, unless it was opened for a tool
readingMode = recent?.reading == true && pendingTool == null
document = doc
+ if (doc.info.signed) announceSignatures(doc)
startPendingTool(doc)
pendingPage = recent?.lastPage?.takeIf { it in 0 until info.pages.size }
pendingSpot = recent?.takeIf { pendingPage != null && it.lastX >= 0f && it.lastY >= 0f }?.let { Triple(it.lastX, it.lastY, it.lastZoom) }
@@ -336,6 +345,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
doc.links = runCatching {
eng.command { (0 until doc.info.pages.size).associateWith { p -> links(doc.id, p.toUInt()) } }
}.getOrDefault(emptyMap())
+ loadSignatures(eng, doc)
}
/**
@@ -415,6 +425,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
editImage = null
editMode = io.github.artcraftandroid.pdfcraft.ui.viewer.EditMode.Select
}
+ if (certPlacing === doc) certPlacing = null
doc.controller.tool = ViewerTool.None
}
@@ -1142,6 +1153,257 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ // ---- Digital signatures: signing with a digital ID, and what a document's signatures say ----
+
+ /** The digital IDs the reader added or made (lazy: the engine's start may need them first). */
+ val digitalIds by lazy { io.github.artcraftandroid.pdfcraft.engine.DigitalIds(app.filesDir) }
+
+ /** The signers the reader chose to trust, given to the engine when it starts. */
+ val trustedCerts by lazy { io.github.artcraftandroid.pdfcraft.engine.TrustedCertificates(app.filesDir) }
+
+ /** The document a digital signature's box is being drawn on (Sign ▸ Sign with a digital ID). */
+ var certPlacing by mutableStateOf<OpenDocument?>(null)
+
+ /** Sign with a digital ID, open for where the signature goes. */
+ var certSign by mutableStateOf<io.github.artcraftandroid.pdfcraft.ui.viewer.CertTarget?>(null)
+
+ /** Why the last signing failed (a wrong password), shown on the Sign screen. */
+ var certSignError by mutableStateOf<String?>(null)
+
+ /** The digital ID chosen on the Sign screen. */
+ var chosenId by mutableStateOf<io.github.artcraftandroid.pdfcraft.engine.DigitalId?>(null)
+
+ /** A picked digital ID file, waiting for its password. */
+ var idImport by mutableStateOf<io.github.artcraftandroid.pdfcraft.ui.viewer.IdImport?>(null)
+ private set
+
+ /** Create a digital ID is open. */
+ var idCreate by mutableStateOf(false)
+
+ /** An empty signature field was tapped: draw a signature there, or sign it with a digital ID. */
+ var signFieldChoice by mutableStateOf<Pair<OpenDocument, io.github.artcraftandroid.pdfcraft.core.WidgetInfo>?>(null)
+
+ /** Draw the box for a new digital signature on [doc], in Fill & Sign. */
+ fun startCertPlacing(doc: OpenDocument) {
+ if (!doc.info.readOnlyReason.isNullOrEmpty()) {
+ tell("This document can't be changed, so it can't be signed.")
+ return
+ }
+ if (doc.controller.tool != ViewerTool.FillSign) enterTool(doc, ViewerTool.FillSign)
+ doc.controller.signPanel = false
+ selectedFill = null
+ certPlacing = doc
+ }
+
+ /** The box was drawn: on to choosing the ID. */
+ fun placeCert(doc: OpenDocument, page: Int, rect: FloatArray) {
+ certPlacing = null
+ openCertSign(io.github.artcraftandroid.pdfcraft.ui.viewer.CertTarget(doc, null, page, rect))
+ }
+
+ fun signFieldWithId(doc: OpenDocument, w: io.github.artcraftandroid.pdfcraft.core.WidgetInfo) {
+ openCertSign(io.github.artcraftandroid.pdfcraft.ui.viewer.CertTarget(doc, w.field, w.page.toInt(), null))
+ }
+
+ /** A drawn (Fill & Sign) signature in signature field [w], as a tap on it did before digital IDs. */
+ fun drawSignatureInField(doc: OpenDocument, w: io.github.artcraftandroid.pdfcraft.core.WidgetInfo) {
+ signaturePad = io.github.artcraftandroid.pdfcraft.ui.viewer.SignaturePad(false, doc, PagePoint(w.page.toInt(), (w.rect[0] + w.rect[2]) / 2f - 40f, (w.rect[1] + w.rect[3]) / 2f - 10f))
+ }
+
+ private fun openCertSign(t: io.github.artcraftandroid.pdfcraft.ui.viewer.CertTarget) {
+ certSignError = null
+ val ids = digitalIds.all
+ if (chosenId !in ids) chosenId = ids.lastOrNull()
+ certSign = t
+ }
+
+ fun pickDigitalId() = pickFiles(FilePickKind.DigitalId)
+
+ /** The digital ID file's password: add it (when the password opens it), or give up (null). */
+ fun answerIdImport(password: String?) {
+ val imp = idImport ?: return
+ idImport = null
+ if (password == null) {
+ imp.file.delete()
+ return
+ }
+ viewModelScope.launch {
+ try {
+ val info = withContext(Dispatchers.IO) { io.github.artcraftandroid.pdfcraft.core.digitalIdInfo(imp.file.absolutePath, password) }
+ val problem = info.problem
+ if (problem != null) {
+ imp.file.delete()
+ tell("This digital ID can't sign documents. $problem")
+ return@launch
+ }
+ val id = withContext(Dispatchers.IO) { digitalIds.add(imp.file, info) }
+ imp.file.delete()
+ chosenId = id
+ tell("Added ${id.name}'s digital ID")
+ } catch (e: MobileException.WrongPassword) {
+ idImport = io.github.artcraftandroid.pdfcraft.ui.viewer.IdImport(imp.file, imp.name, wrong = true)
+ } catch (e: MobileException) {
+ imp.file.delete()
+ tell("PdfCraft can't use this file as a digital ID: ${e.userMessage}")
+ }
+ }
+ }
+
+ /** Make a self-signed digital ID (2048-bit RSA, valid 5 years) and choose it. */
+ fun createDigitalId(name: String, email: String, organization: String, password: String) {
+ val eng = engine ?: return
+ viewModelScope.launch {
+ busy = "Creating your digital ID…"
+ val tmp = File(getApplication<Application>().cacheDir, "new-id-${System.nanoTime()}.p12")
+ try {
+ eng.tool("sign_id_create", mapOf(
+ "name" to name.trim(), "email" to email.trim().ifEmpty { null }, "organization" to organization.trim().ifEmpty { null },
+ "password" to password, "path" to tmp.absolutePath,
+ ))
+ val info = withContext(Dispatchers.IO) { io.github.artcraftandroid.pdfcraft.core.digitalIdInfo(tmp.absolutePath, password) }
+ chosenId = withContext(Dispatchers.IO) { digitalIds.add(tmp, info) }
+ idCreate = false
+ tell("Digital ID created")
+ } catch (e: MobileException) {
+ tell(toolMessage(e, "sign_id_create"))
+ } finally {
+ tmp.delete()
+ busy = null
+ }
+ }
+ }
+
+ fun removeDigitalId(id: io.github.artcraftandroid.pdfcraft.engine.DigitalId) {
+ digitalIds.remove(id)
+ if (chosenId == id) chosenId = digitalIds.all.lastOrNull()
+ }
+
+ /**
+ * Sign [t]'s document with [id]: the engine signs it as it is now (with any changes not yet
+ * saved) and the signed file replaces the working copy, then goes back where it came from.
+ */
+ fun signWithId(
+ t: io.github.artcraftandroid.pdfcraft.ui.viewer.CertTarget,
+ id: io.github.artcraftandroid.pdfcraft.engine.DigitalId,
+ password: String,
+ look: io.github.artcraftandroid.pdfcraft.ui.viewer.CertLook,
+ reason: String,
+ location: String,
+ ) {
+ val eng = engine ?: return
+ val doc = t.doc
+ viewModelScope.launch {
+ busy = "Signing…"
+ try {
+ val args = mutableMapOf<String, Any?>(
+ "doc" to doc.id, "id" to id.file.absolutePath, "password" to password, "out" to doc.file.absolutePath,
+ "reason" to reason.trim().ifEmpty { null }, "location" to location.trim().ifEmpty { null },
+ )
+ if (t.field != null) {
+ args["field"] = t.field
+ } else {
+ args["page"] = t.page + 1
+ args["rect"] = t.rect?.map { it.toDouble() }
+ }
+ when (look) {
+ io.github.artcraftandroid.pdfcraft.ui.viewer.CertLook.Name -> Unit
+ io.github.artcraftandroid.pdfcraft.ui.viewer.CertLook.Typed -> args["graphic"] = mapOf("text" to id.name)
+ io.github.artcraftandroid.pdfcraft.ui.viewer.CertLook.Drawn -> args["graphic"] = mapOf("image" to signatures.signature.absolutePath)
+ }
+ eng.tool("sign_document", args)
+ certSign = null
+ certSignError = null
+ if (doc.controller.tool == ViewerTool.FillSign) leaveTool(doc)
+ refresh(doc)
+ // the working copy is signed; the original gets it now, or a copy does
+ doc.notWrittenBack = true
+ if (save(doc, quiet = true)) {
+ tell("Signed and saved")
+ } else {
+ tell("Signed, but ${doc.name} can't be changed where it is. Save a copy to keep the signed file.", "Save a copy") { saveCopyAs(doc) }
+ }
+ } catch (e: MobileException) {
+ val m = toolMessage(e, "sign_document")
+ certSignError = if (m.contains("password is incorrect", ignoreCase = true)) "The password is incorrect." else m
+ } finally {
+ busy = null
+ }
+ }
+ }
+
+ /** A tool's refusal without the tool's name in front, as a sentence. */
+ private fun toolMessage(e: Throwable, tool: String): String =
+ e.userMessage.removePrefix("$tool: ").replaceFirstChar { it.uppercase() }.let { if (it.endsWith(".")) it else "$it." }
+
+ /** What the document's signatures say (only asked for when it has signatures or signature fields). */
+ private suspend fun loadSignatures(eng: Engine, doc: OpenDocument) {
+ if (!doc.info.signed && doc.widgets.none { it.kind == "signature" }) {
+ doc.signatures = emptyList()
+ return
+ }
+ doc.signatures = runCatching { io.github.artcraftandroid.pdfcraft.ui.viewer.parseSignatures(eng.tool("sign_list", mapOf("doc" to doc.id))) }.getOrDefault(emptyList())
+ }
+
+ /** On opening a signed document: whether its signatures hold, with the details a tap away. */
+ private fun announceSignatures(doc: OpenDocument) {
+ val signed = doc.signatures.filter { it.signed }
+ if (signed.isEmpty()) return
+ val one = signed.singleOrNull()
+ val text = when {
+ signed.any { it.status == "invalid" } -> if (one != null) "This document's signature is invalid." else "At least one signature in this document is invalid."
+ signed.all { it.status == "valid" } -> if (one != null) "Signed by ${one.signer ?: "an unknown signer"}. The signature is valid." else "All ${signed.size} signatures are valid."
+ one != null -> "Signed by ${one.signer ?: "an unknown signer"}. The document hasn't changed since, but the signer isn't verified."
+ else -> "Signed. Some of the signers aren't verified."
+ }
+ tell(text, "Details") { doc.controller.sheet = io.github.artcraftandroid.pdfcraft.ui.viewer.ViewerSheet.Signatures }
+ }
+
+ /** Show signature [s] on its page, flashing its box. */
+ fun showSignature(doc: OpenDocument, s: io.github.artcraftandroid.pdfcraft.ui.viewer.SignatureEntry) {
+ val page = s.page ?: return
+ val rect = s.rect ?: return
+ doc.viewer.goToPage(page, (rect[1] - 60f).coerceAtLeast(0f))
+ viewModelScope.launch {
+ delay(250)
+ doc.linkFlash = LinkFlash(page, rect)
+ delay(600)
+ doc.linkFlash = null
+ }
+ }
+
+ /** Trust the certificate that made signature [s], on this device: signatures by it then validate. */
+ fun trustSigner(doc: OpenDocument, s: io.github.artcraftandroid.pdfcraft.ui.viewer.SignatureEntry) {
+ val eng = engine ?: return
+ val sha = s.cert?.sha256 ?: return
+ viewModelScope.launch {
+ try {
+ val der = eng.command { signerCertificate(doc.id, s.field) } ?: return@launch
+ withContext(Dispatchers.IO) { trustedCerts.add(der, sha) }
+ applyTrust(eng)
+ loadSignatures(eng, doc)
+ tell("${s.signer ?: "This signer"} is trusted on this device")
+ } catch (e: MobileException) {
+ tell(e.userMessage)
+ }
+ }
+ }
+
+ fun untrustSigner(doc: OpenDocument, s: io.github.artcraftandroid.pdfcraft.ui.viewer.SignatureEntry) {
+ val eng = engine ?: return
+ val sha = s.cert?.sha256 ?: return
+ viewModelScope.launch {
+ withContext(Dispatchers.IO) { trustedCerts.remove(sha) }
+ runCatching { applyTrust(eng) }
+ loadSignatures(eng, doc)
+ }
+ }
+
+ /** Give the engine the trusted signers' certificates (it revalidates open documents). */
+ private suspend fun applyTrust(eng: Engine) {
+ val paths = withContext(Dispatchers.IO) { trustedCerts.files().map { it.absolutePath } }
+ eng.tool("sign_trust", mapOf("clear" to true, "paths" to paths))
+ }
+
// ---- Edit PDF ----------------------------------------------------------------------------
var editMode by mutableStateOf(io.github.artcraftandroid.pdfcraft.ui.viewer.EditMode.Select)
@@ -1462,7 +1724,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
"checkbox" -> fillField(doc, w.field, !w.on)
"radio" -> w.export?.let { fillField(doc, w.field, it) }
"text", "combo", "list" -> fieldEdit = io.github.artcraftandroid.pdfcraft.ui.viewer.FieldEdit(doc, w)
- "signature" -> signaturePad = io.github.artcraftandroid.pdfcraft.ui.viewer.SignaturePad(false, doc, PagePoint(at.page, (w.rect[0] + w.rect[2]) / 2f - 40f, (w.rect[1] + w.rect[3]) / 2f - 10f))
+ // a signed field shows its signature's details; an empty one, a drawn or a digital signature
+ "signature" -> if (doc.signatures.any { it.field == w.field && it.signed }) {
+ doc.controller.sheet = io.github.artcraftandroid.pdfcraft.ui.viewer.ViewerSheet.Signatures
+ } else {
+ signFieldChoice = doc to w
+ }
"button" -> pressButton(doc, w)
else -> return false
}
@@ -1555,6 +1822,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
}
}
FilePickKind.Open -> open(uris.first())
+ FilePickKind.DigitalId -> viewModelScope.launch {
+ val uri = uris.first()
+ val picked = withContext(Dispatchers.IO) { runCatching { copyIn(uri) }.getOrNull() }
+ if (picked == null) tell("That file couldn't be read.")
+ else idImport = io.github.artcraftandroid.pdfcraft.ui.viewer.IdImport(picked, picked.name, wrong = false)
+ }
}
}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt
index 5934a5f..9cc8a63 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/OpenDocument.kt
@@ -58,6 +58,9 @@ class OpenDocument(
/** The comments, refreshed when the document changes (tapping one selects it). */
var comments: List<io.github.artcraftandroid.pdfcraft.core.CommentInfo> = emptyList()
+ /** Its signatures and signature fields with what validating them found, refreshed when the document changes. */
+ var signatures by mutableStateOf<List<io.github.artcraftandroid.pdfcraft.ui.viewer.SignatureEntry>>(emptyList())
+
/** The form fields' widgets, refreshed when the document changes. */
var widgets: List<io.github.artcraftandroid.pdfcraft.core.WidgetInfo> = emptyList()
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.kt
index 83955e9..40862fb 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
@@ -495,7 +495,7 @@ fun CombineScreen(vm: AppViewModel) {
data class PickedFile(val uri: android.net.Uri, val name: String, val size: Long?)
/** What a file picker was opened for. */
-enum class FilePickKind { Combine, Create, Insert, Open }
+enum class FilePickKind { Combine, Create, Insert, Open, DigitalId }
/**
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/DigitalSign.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/DigitalSign.kt
new file mode 100644
index 0000000..c6fd23b
--- /dev/null
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/DigitalSign.kt
@@ -0,0 +1,558 @@
+package io.github.artcraftandroid.pdfcraft.ui.viewer
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.PathEffect
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import io.github.artcraftandroid.pdfcraft.engine.DigitalId
+import io.github.artcraftandroid.pdfcraft.ui.AppViewModel
+import io.github.artcraftandroid.pdfcraft.ui.BarIcon
+import io.github.artcraftandroid.pdfcraft.ui.LucideIcons
+import io.github.artcraftandroid.pdfcraft.ui.OpenDocument
+import io.github.artcraftandroid.pdfcraft.ui.PdfDialog
+import io.github.artcraftandroid.pdfcraft.ui.PdfField
+import io.github.artcraftandroid.pdfcraft.ui.PdfSheet
+import io.github.artcraftandroid.pdfcraft.ui.SheetDivider
+import io.github.artcraftandroid.pdfcraft.ui.SheetRow
+import io.github.artcraftandroid.pdfcraft.ui.SheetTitle
+import io.github.artcraftandroid.pdfcraft.ui.pdfColors
+import io.github.artcraftandroid.pdfcraft.ui.safeTopPadding
+import java.text.DateFormat
+import java.util.Date
+import org.json.JSONObject
+
+// Digital signatures: signing with a digital ID (a certificate in a .p12 / .pfx file, or one made
+// here), and what the signatures in a document say. The engine signs (PAdES, incrementally) and
+// validates; these are the screens around it.
+
+/** A signer's certificate, as a signature's details show it. */
+data class SignerCert(val name: String, val issuer: String, val validTo: String?, val sha256: String, val selfSigned: Boolean)
+
+/** One signature field and what validating it found (the engine's `sign_list`). */
+data class SignatureEntry(
+ val field: String,
+ val signed: Boolean,
+ /** `valid`, `unknown` (intact, but the signer isn't trusted), `invalid` or `unsigned`. */
+ val status: String,
+ val signer: String?,
+ val date: String?,
+ val reason: String?,
+ val location: String?,
+ /** 0-based, for a visible signature or field. */
+ val page: Int?,
+ /** Points from the page's top-left, for a visible one. */
+ val rect: FloatArray?,
+ /** Certification level (1 no changes, 2 form filling, 3 comments too), for a certifying signature. */
+ val certify: Int?,
+ /** Changes since signing: `none`, `allowed` or `disallowed`, and what they were. */
+ val modification: String,
+ val changes: List<String>,
+ /** The engine's explanation, sentence by sentence. */
+ val details: List<String>,
+ val cert: SignerCert?,
+)
+
+private fun JSONObject.text(key: String): String? = if (!has(key) || isNull(key)) null else optString(key).trim().takeIf { it.isNotEmpty() }
+
+private fun JSONObject.strings(key: String): List<String> =
+ optJSONArray(key)?.let { a -> (0 until a.length()).mapNotNull { i -> a.optString(i).takeIf { it.isNotBlank() } } }.orEmpty()
+
+/** The signatures `sign_list` returned. */
+fun parseSignatures(o: JSONObject): List<SignatureEntry> {
+ val list = o.optJSONArray("signatures") ?: return emptyList()
+ return (0 until list.length()).mapNotNull { i ->
+ val s = list.optJSONObject(i) ?: return@mapNotNull null
+ val cert = s.optJSONObject("certificate")?.let { c ->
+ SignerCert(c.text("name") ?: c.text("subject") ?: "", c.text("issuer") ?: "", c.text("valid_to"), c.text("sha256") ?: "", c.optBoolean("self_signed"))
+ }
+ val rect = s.optJSONArray("rect")?.takeIf { it.length() == 4 }?.let { r -> FloatArray(4) { r.optDouble(it).toFloat() } }
+ SignatureEntry(
+ field = s.optString("field"),
+ signed = s.optBoolean("signed"),
+ status = s.text("status") ?: "unsigned",
+ signer = s.text("signer") ?: cert?.name?.takeIf { it.isNotEmpty() },
+ date = s.text("date"),
+ reason = s.text("reason"),
+ location = s.text("location"),
+ page = if (s.isNull("page")) null else s.optInt("page", 0).takeIf { it >= 1 }?.minus(1),
+ rect = rect,
+ certify = if (s.isNull("certify")) null else s.optInt("certify", 0).takeIf { it in 1..3 },
+ modification = s.text("modification") ?: "none",
+ changes = s.strings("changes"),
+ details = s.strings("details"),
+ cert = cert,
+ )
+ }
+}
+
+/** Where a digital signature goes: an empty signature field, or a box drawn on page [page]. */
+class CertTarget(val doc: OpenDocument, val field: String?, val page: Int, val rect: FloatArray?)
+
+/** What a digital signature shows on the page beside the signer's details. */
+enum class CertLook(val label: String) { Name("Name only"), Typed("Typed name"), Drawn("My signature") }
+
+/** A digital ID file picked to add, waiting for its password ([wrong]: the last one didn't open it). */
+class IdImport(val file: java.io.File, val name: String, val wrong: Boolean)
+
+/** A signature's status in a few words, for the list and the message on opening. */
+fun SignatureEntry.statusLabel(): String = when {
+ !signed -> "Not signed yet"
+ status == "valid" -> "Valid"
+ status == "invalid" -> "Invalid"
+ else -> "Signer not verified"
+}
+
+private val ValidGreen = Color(0xFF12805C)
+private val UnknownAmber = Color(0xFFE68619)
+
+@Composable
+private fun statusIcon(s: SignatureEntry): Pair<androidx.compose.ui.graphics.vector.ImageVector, Color> = when {
+ !s.signed -> LucideIcons.CircleDashed to pdfColors.icon
+ s.status == "valid" -> LucideIcons.ShieldCheck to ValidGreen
+ s.status == "invalid" -> LucideIcons.CircleX to pdfColors.red
+ else -> LucideIcons.TriangleAlert to UnknownAmber
+}
+
+/**
+ * Drawing where a digital signature goes (Fill & Sign ▸ Sign ▸ Sign with a digital ID): drag a
+ * box with one finger (two still scroll and zoom), or tap for a box of the usual size there.
+ */
+@Composable
+fun CertPlaceLayer(vm: AppViewModel, doc: OpenDocument) {
+ val c = pdfColors
+ var start by remember { mutableStateOf<Offset?>(null) }
+ var end by remember { mutableStateOf<Offset?>(null) }
+ Box(
+ Modifier.fillMaxSize().toolGestures(
+ doc,
+ onDown = { start = it; end = it },
+ onMove = { end = it },
+ onUp = { p, moved ->
+ val s = start
+ start = null
+ end = null
+ // the hint's Cancel was tapped (it sits over this layer): nothing to place
+ if (vm.certPlacing !== doc) return@toolGestures
+ val at = s?.let { doc.viewer.screenToPage(it) } ?: return@toolGestures
+ val page = doc.info.pages.getOrNull(at.page) ?: return@toolGestures
+ val pw = page.width
+ val ph = page.height
+ val rect = if (moved) {
+ // the far corner in the same page's points, kept on that page
+ val ppp = doc.viewer.pixelsPerPoint(at.page).coerceAtLeast(0.01f)
+ val x1 = (at.x + (p.x - s.x) / ppp).coerceIn(0f, pw)
+ val y1 = (at.y + (p.y - s.y) / ppp).coerceIn(0f, ph)
+ floatArrayOf(minOf(at.x, x1), minOf(at.y, y1), maxOf(at.x, x1), maxOf(at.y, y1))
+ } else {
+ null
+ }
+ vm.placeCert(doc, at.page, fitSignatureBox(rect, at.x, at.y, pw, ph))
+ },
+ onCancel = { start = null; end = null },
+ ),
+ ) {
+ val s = start
+ val e = end
+ if (s != null && e != null) {
+ Canvas(Modifier.fillMaxSize()) {
+ val tl = Offset(minOf(s.x, e.x), minOf(s.y, e.y))
+ val size = Size(kotlin.math.abs(e.x - s.x), kotlin.math.abs(e.y - s.y))
+ drawRect(c.accent.copy(alpha = 0.12f), tl, size)
+ drawRect(c.accent, tl, size, style = Stroke(2.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(6.dp.toPx(), 4.dp.toPx()))))
+ }
+ }
+ val top = with(LocalDensity.current) { doc.viewer.padTop.toDp() }
+ Row(
+ Modifier.align(Alignment.TopCenter).padding(top = top + 12.dp, start = 16.dp, end = 16.dp)
+ .clip(RoundedCornerShape(8.dp)).background(c.surface).padding(start = 16.dp, end = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text("Drag a box where the signature goes", color = c.text, fontSize = 14.sp, modifier = Modifier.weight(1f, fill = false))
+ TextButton(onClick = { vm.certPlacing = null }) { Text("Cancel", color = c.accent) }
+ }
+ }
+}
+
+/** The signature box: [rect] when it is big enough, else one of the usual size around ([x], [y]); kept on the page. */
+internal fun fitSignatureBox(rect: FloatArray?, x: Float, y: Float, pageW: Float, pageH: Float): FloatArray {
+ if (rect != null && rect[2] - rect[0] >= 40f && rect[3] - rect[1] >= 16f) return rect
+ val w = minOf(180f, pageW)
+ val h = minOf(54f, pageH)
+ val cx = rect?.let { (it[0] + it[2]) / 2f } ?: x
+ val cy = rect?.let { (it[1] + it[3]) / 2f } ?: y
+ val left = (cx - w / 2f).coerceIn(0f, pageW - w)
+ val top = (cy - h / 2f).coerceIn(0f, pageH - h)
+ return floatArrayOf(left, top, left + w, top + h)
+}
+
+/**
+ * Sign with a digital ID: choose the ID (or add or create one), how the signature looks, an
+ * optional reason and place, then the ID's password signs and saves the document.
+ */
+@Composable
+fun CertSignScreen(vm: AppViewModel, target: CertTarget) {
+ val c = pdfColors
+ androidx.activity.compose.BackHandler { vm.certSign = null }
+ val ids = vm.digitalIds.all
+ val chosen = vm.chosenId?.takeIf { it in ids }
+ val hasDrawn = remember(vm.signaturesChanged) { vm.signatures.signature.isFile }
+ var look by remember { mutableStateOf(CertLook.Name) }
+ var reason by remember { mutableStateOf("") }
+ var location by remember { mutableStateOf("") }
+ var password by remember(chosen) { mutableStateOf("") }
+ val unusable = chosen?.let { idProblem(it) }
+ val canSign = chosen != null && unusable == null
+ fun sign() {
+ if (chosen != null && canSign) vm.signWithId(target, chosen, password, if (look == CertLook.Drawn && !hasDrawn) CertLook.Name else look, reason, location)
+ }
+ Column(Modifier.fillMaxSize().background(c.surface).pointerInput(Unit) { detectTapGestures() }.safeTopPadding().navigationBarsPadding().imePadding()) {
+ Row(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
+ TextButton(onClick = { vm.certSign = null }) { Text("Cancel", color = c.accent) }
+ Text("Sign with a digital ID", color = c.text, fontWeight = FontWeight.SemiBold, fontSize = 17.sp, modifier = Modifier.weight(1f), textAlign = TextAlign.Center, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ TextButton(onClick = ::sign, enabled = canSign) { Text("Sign", color = if (canSign) c.accent else c.textSecondary, fontWeight = FontWeight.SemiBold) }
+ }
+ SheetDivider(inset = 0.dp)
+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
+ Section("Digital ID")
+ if (ids.isEmpty()) {
+ Text(
+ "You don't have a digital ID yet. Add the .p12 or .pfx file you were given, or create one for yourself.",
+ color = c.textSecondary, fontSize = 14.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp),
+ )
+ }
+ for (id in ids) IdRow(vm, id, selected = id == chosen) { vm.chosenId = id }
+ SheetRow(LucideIcons.FolderOpen, "Add a digital ID file", { vm.pickDigitalId() })
+ SheetRow(LucideIcons.Plus, "Create a digital ID", { vm.idCreate = true })
+ SheetDivider(vertical = 6.dp)
+
+ Section("Appearance")
+ Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (l in CertLook.entries) {
+ val enabled = l != CertLook.Drawn || hasDrawn
+ Chip(l.label, look == l, enabled) { look = l }
+ }
+ }
+ Text(
+ when (look) {
+ CertLook.Name -> "Your name and the date in the box."
+ CertLook.Typed -> "Your name in a script font, with your name and the date beside it."
+ CertLook.Drawn -> if (hasDrawn) "Your saved Fill & Sign signature, with your name and the date beside it." else "Make a signature in Fill & Sign first."
+ },
+ color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
+ )
+ SheetDivider(vertical = 6.dp)
+
+ Section("Reason (optional)")
+ Box(Modifier.padding(horizontal = 16.dp)) { PdfField(reason, { reason = it }, "For example: I approve this document", keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next)) }
+ Spacer(Modifier.height(12.dp))
+ Section("Location (optional)")
+ Box(Modifier.padding(horizontal = 16.dp)) { PdfField(location, { location = it }, "City or place", keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next)) }
+ Spacer(Modifier.height(12.dp))
+
+ if (chosen != null) {
+ Section("Password for ${chosen.name}")
+ Box(Modifier.padding(horizontal = 16.dp)) {
+ PdfField(
+ password, { password = it; vm.certSignError = null }, "Digital ID password", password = true, error = vm.certSignError != null,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
+ keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { sign() }),
+ )
+ }
+ }
+ (vm.certSignError ?: unusable)?.let { Text(it, color = c.red, fontSize = 14.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)) }
+ Text(
+ "Signing saves the document. Anyone who opens it can check that it hasn't changed since; changes made after signing are listed with the signature.",
+ color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),
+ )
+ }
+ }
+}
+
+/** Why [id] can't sign now, if it can't. */
+private fun idProblem(id: DigitalId): String? = when {
+ id.expired() -> "This digital ID expired on ${shortDate(id.validTo * 1000)}."
+ id.notYetValid() -> "This digital ID isn't valid until ${shortDate(id.validFrom * 1000)}."
+ else -> null
+}
+
+private fun shortDate(ms: Long): String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(ms))
+
+@Composable
+private fun Section(title: String) {
+ Text(title, color = pdfColors.textSecondary, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 10.dp, bottom = 6.dp))
+}
+
+@Composable
+private fun Chip(label: String, selected: Boolean, enabled: Boolean, onClick: () -> Unit) {
+ val c = pdfColors
+ Text(
+ label,
+ color = when {
+ !enabled -> c.textSecondary.copy(alpha = 0.5f)
+ selected -> c.accent
+ else -> c.text
+ },
+ fontSize = 14.sp,
+ fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
+ maxLines = 1,
+ modifier = Modifier.clip(RoundedCornerShape(16.dp)).background(if (selected) c.pressed else Color.Transparent)
+ .clickable(enabled = enabled, onClick = onClick).padding(horizontal = 14.dp, vertical = 8.dp),
+ )
+}
+
+/** A digital ID to choose: whose it is, who issued it and until when, and Remove. */
+@Composable
+private fun IdRow(vm: AppViewModel, id: DigitalId, selected: Boolean, onClick: () -> Unit) {
+ val c = pdfColors
+ var confirm by remember { mutableStateOf(false) }
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable(onClick = onClick).padding(start = 16.dp, end = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Icon(if (selected) LucideIcons.CircleDot else LucideIcons.Circle, null, tint = if (selected) c.accent else c.icon, modifier = Modifier.size(24.dp))
+ Spacer(Modifier.width(12.dp))
+ Column(Modifier.weight(1f).padding(vertical = 8.dp)) {
+ Text(id.name, color = c.text, fontSize = 16.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ val by = if (id.selfSigned) "Self-signed" else "Issued by ${id.issuer}"
+ val until = idProblem(id) ?: "Valid until ${shortDate(id.validTo * 1000)}"
+ Text("$by · $until", color = if (idProblem(id) != null) c.red else c.textSecondary, fontSize = 13.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ BarIcon(LucideIcons.Trash2, "Remove ${id.name}'s digital ID", { confirm = true }, size = 40.dp)
+ }
+ if (confirm) {
+ PdfDialog(
+ onDismiss = { confirm = false }, title = "Remove digital ID?", confirm = "Remove", destructive = true,
+ onConfirm = { confirm = false; vm.removeDigitalId(id) },
+ ) { Text("${id.name}'s digital ID is removed from PdfCraft. Documents already signed with it keep their signatures.", color = c.text, fontSize = 14.sp) }
+ }
+}
+
+/** The password of a digital ID file being added. */
+@Composable
+fun IdPasswordDialog(vm: AppViewModel, imp: IdImport) {
+ val c = pdfColors
+ var pw by remember(imp) { mutableStateOf("") }
+ val focus = remember { androidx.compose.ui.focus.FocusRequester() }
+ androidx.compose.runtime.LaunchedEffect(imp) { runCatching { focus.requestFocus() } }
+ PdfDialog(onDismiss = { vm.answerIdImport(null) }, title = "Digital ID password", confirm = "Add", onConfirm = { vm.answerIdImport(pw) }) {
+ Text("Enter the password that protects ${imp.name}.", color = c.text, fontSize = 14.sp)
+ Spacer(Modifier.height(14.dp))
+ PdfField(
+ pw, { pw = it }, "Password", error = imp.wrong, password = true, focus = focus,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
+ keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { vm.answerIdImport(pw) }),
+ )
+ if (imp.wrong) Text("The password is incorrect.", color = c.red, fontSize = 13.sp, modifier = Modifier.padding(top = 8.dp))
+ }
+}
+
+/** Create a digital ID: a self-signed certificate made on the phone, saved with a password. */
+@Composable
+fun CreateIdScreen(vm: AppViewModel) {
+ val c = pdfColors
+ androidx.activity.compose.BackHandler { vm.idCreate = false }
+ var name by remember { mutableStateOf(vm.toolPrefs.author) }
+ var email by remember { mutableStateOf("") }
+ var organization by remember { mutableStateOf("") }
+ var password by remember { mutableStateOf("") }
+ var again by remember { mutableStateOf("") }
+ val problem = when {
+ name.isBlank() -> null
+ password.isNotEmpty() && password.length < 6 -> "The password needs at least 6 characters."
+ again.isNotEmpty() && again != password -> "The passwords don't match."
+ else -> null
+ }
+ val ok = name.isNotBlank() && password.length >= 6 && again == password
+ Column(Modifier.fillMaxSize().background(c.surface).pointerInput(Unit) { detectTapGestures() }.safeTopPadding().navigationBarsPadding().imePadding()) {
+ Row(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
+ TextButton(onClick = { vm.idCreate = false }) { Text("Cancel", color = c.accent) }
+ Text("Create a digital ID", color = c.text, fontWeight = FontWeight.SemiBold, fontSize = 17.sp, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
+ TextButton(onClick = { vm.createDigitalId(name, email, organization, password) }, enabled = ok) {
+ Text("Create", color = if (ok) c.accent else c.textSecondary, fontWeight = FontWeight.SemiBold)
+ }
+ }
+ SheetDivider(inset = 0.dp)
+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
+ Text(
+ "A digital ID made here is self-signed: a document you sign with it shows any change made after you signed, but nobody else vouches that it's you. " +
+ "For that, use the ID file an organisation or a certificate authority gives you.",
+ color = c.textSecondary, fontSize = 14.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
+ )
+ Section("Name")
+ Box(Modifier.padding(horizontal = 16.dp)) { PdfField(name, { name = it }, "Your name") }
+ Section("Email (optional)")
+ Box(Modifier.padding(horizontal = 16.dp)) { PdfField(email, { email = it }, "[email protected]", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)) }
+ Section("Organisation (optional)")
+ Box(Modifier.padding(horizontal = 16.dp)) { PdfField(organization, { organization = it }, "Company or organisation") }
+ Section("Password")
+ Box(Modifier.padding(horizontal = 16.dp)) {
+ PdfField(password, { password = it }, "At least 6 characters", password = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
+ }
+ Spacer(Modifier.height(10.dp))
+ Box(Modifier.padding(horizontal = 16.dp)) {
+ PdfField(again, { again = it }, "The password again", password = true, error = again.isNotEmpty() && again != password, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done))
+ }
+ problem?.let { Text(it, color = c.red, fontSize = 14.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)) }
+ Text(
+ "PdfCraft doesn't keep the password and can't recover it: you type it each time you sign.",
+ color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp),
+ )
+ }
+ }
+}
+
+/** Tapping an empty signature field: draw a signature there, or sign it with a digital ID. */
+@Composable
+fun SignFieldChoiceDialog(vm: AppViewModel, doc: OpenDocument, field: io.github.artcraftandroid.pdfcraft.core.WidgetInfo) {
+ PdfDialog(onDismiss = { vm.signFieldChoice = null }, title = null, confirm = null, dismiss = null, list = true) {
+ SheetRow(LucideIcons.Signature, "Add your signature", { vm.signFieldChoice = null; vm.drawSignatureInField(doc, field) })
+ SheetRow(LucideIcons.ShieldCheck, "Sign with a digital ID", { vm.signFieldChoice = null; vm.signFieldWithId(doc, field) })
+ }
+}
+
+/**
+ * Signatures (More ▸ Signatures): each signature field with whether its signature is valid, who
+ * signed and when, and on tap the details (certificate, changes since signing, the engine's
+ * explanation), Trust this signer, and Sign for an empty field.
+ */
+@Composable
+fun SignaturesSheet(vm: AppViewModel, doc: OpenDocument) {
+ val c = pdfColors
+ val ctl = doc.controller
+ fun close() {
+ ctl.sheet = ViewerSheet.None
+ }
+ // read so Trust redraws the list
+ vm.trustedCerts.version
+ var open by remember { mutableStateOf<String?>(null) }
+ PdfSheet(onDismiss = ::close, maxHeightFraction = 0.85f) {
+ SheetTitle("Signatures")
+ Column(Modifier.verticalScroll(rememberScrollState())) {
+ val list = doc.signatures
+ if (list.isEmpty()) {
+ Text("This document has no signatures.", color = c.textSecondary, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp))
+ }
+ for (s in list) {
+ val (icon, tint) = statusIcon(s)
+ Row(
+ Modifier.fillMaxWidth().clickable { open = if (open == s.field) null else s.field }.padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.Top,
+ ) {
+ Icon(icon, null, tint = tint, modifier = Modifier.padding(top = 2.dp).size(24.dp))
+ Spacer(Modifier.width(12.dp))
+ Column(Modifier.weight(1f)) {
+ Text(if (s.signed) s.signer ?: "Unknown signer" else "Empty signature field", color = c.text, fontSize = 16.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ val sub = listOfNotNull(
+ s.statusLabel(),
+ if (s.certify != null && s.signed) "Certified" else null,
+ pdfDateLabel(s.date),
+ s.page?.let { "Page ${it + 1}" }.takeIf { !s.signed },
+ ).joinToString(" · ")
+ Text(sub, color = if (s.status == "invalid") c.red else c.textSecondary, fontSize = 13.sp)
+ if (open == s.field) SignatureDetails(vm, doc, s)
+ }
+ Icon(if (open == s.field) LucideIcons.ChevronUp else LucideIcons.ChevronDown, null, tint = c.icon, modifier = Modifier.size(20.dp))
+ }
+ SheetDivider()
+ }
+ SheetRow(LucideIcons.ShieldCheck, "Add a digital signature", { close(); vm.startCertPlacing(doc) })
+ Spacer(Modifier.height(8.dp))
+ }
+ }
+}
+
+@Composable
+private fun SignatureDetails(vm: AppViewModel, doc: OpenDocument, s: SignatureEntry) {
+ val c = pdfColors
+ @Composable
+ fun line(label: String, value: String?) {
+ if (value.isNullOrBlank()) return
+ Text("$label: $value", color = c.text, fontSize = 14.sp, modifier = Modifier.padding(top = 6.dp))
+ }
+ Column(Modifier.padding(top = 4.dp)) {
+ if (s.signed) {
+ line("Reason", s.reason)
+ line("Location", s.location)
+ s.cert?.let { cert ->
+ line("Certificate", if (cert.selfSigned) "self-signed" else "issued by ${cert.issuer}")
+ line("Valid until", pdfDateLabel(cert.validTo))
+ }
+ s.certify?.let {
+ line("Certified", when (it) { 1 -> "no changes allowed"; 2 -> "form filling allowed"; else -> "form filling and comments allowed" })
+ }
+ line(
+ "Changes since signing",
+ when (s.modification) {
+ "none" -> "none"
+ "allowed" -> "allowed ones" + if (s.changes.isEmpty()) "" else " (${s.changes.joinToString("; ")})"
+ else -> "some that aren't allowed" + if (s.changes.isEmpty()) "" else " (${s.changes.joinToString("; ")})"
+ },
+ )
+ for (d in s.details) Text("• $d", color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp))
+ } else {
+ Text("Nobody has signed this field yet.", color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp))
+ }
+ Row(Modifier.padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (s.page != null && s.rect != null) {
+ TextButton(onClick = { doc.controller.sheet = ViewerSheet.None; vm.showSignature(doc, s) }) { Text("Go to it", color = c.accent) }
+ }
+ val sha = s.cert?.sha256
+ if (s.signed && sha != null) {
+ if (vm.trustedCerts.contains(sha)) {
+ TextButton(onClick = { vm.untrustSigner(doc, s) }) { Text("Stop trusting", color = c.accent) }
+ } else if (s.status == "unknown") {
+ TextButton(onClick = { vm.trustSigner(doc, s) }) { Text("Trust this signer", color = c.accent) }
+ }
+ }
+ if (!s.signed) {
+ TextButton(onClick = {
+ doc.controller.sheet = ViewerSheet.None
+ doc.widgets.firstOrNull { it.field == s.field }?.let { vm.signFieldWithId(doc, it) }
+ }) { Text("Sign", color = c.accent) }
+ }
+ }
+ }
+}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/FillSign.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/FillSign.kt
index be013f8..f80abbc 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/FillSign.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/FillSign.kt
@@ -176,7 +176,10 @@ fun SignPanel(vm: AppViewModel, doc: OpenDocument, onDismiss: () -> Unit) {
}
}
}
- Spacer(Modifier.height(30.dp))
+ Spacer(Modifier.height(14.dp))
+ // a certificate-based signature, which the reference's phone app doesn't have
+ SheetRow(LucideIcons.ShieldCheck, "Sign with a digital ID", { onDismiss(); vm.startCertPlacing(doc) }, chevron = true)
+ Spacer(Modifier.height(10.dp))
}
}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Forms.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Forms.kt
index f9e7e80..d6d0762 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Forms.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Forms.kt
@@ -188,8 +188,10 @@ fun FieldTopBar(actions: FieldActions) {
/** Every fillable field tinted light blue on the page, as the reference marks them. */
fun androidx.compose.ui.graphics.drawscope.DrawScope.drawFieldTints(doc: OpenDocument) {
+ // a signed signature field is done: no tint over the signature
+ val signed = doc.signatures.filter { it.signed }.mapTo(HashSet()) { it.field }
for (w in doc.widgets) {
- if (w.readOnly || w.rect.size < 4 || w.kind == "button") continue
+ if (w.readOnly || w.rect.size < 4 || w.kind == "button" || (w.kind == "signature" && w.field in signed)) continue
val page = w.page.toInt()
val a = doc.viewer.pageToScreen(page, w.rect[0], w.rect[1])
val b = doc.viewer.pageToScreen(page, w.rect[2], w.rect[3])
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt
index ee35226..f8eaadf 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/Tools.kt
@@ -102,7 +102,7 @@ fun ToolLayer(vm: AppViewModel, doc: OpenDocument) {
if (doc.controller.commentMode == CommentMode.Voice) vm.startVoice(doc, p) else vm.notePrompt = NotePrompt(doc, p)
}
ViewerTool.Text -> TapLayer(doc) { p -> vm.textPrompt = TextPrompt(doc, p) }
- ViewerTool.FillSign -> FillSignLayer(vm, doc)
+ ViewerTool.FillSign -> if (vm.certPlacing === doc) CertPlaceLayer(vm, doc) else FillSignLayer(vm, doc)
else -> Unit
}
}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerController.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerController.kt
index aede9d3..9b5f0a8 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerController.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerController.kt
@@ -36,7 +36,7 @@ enum class TextMarkup { Highlight, Underline, Strikethrough }
enum class CommentMode { Text, Voice }
/** What the bottom sheet over the viewer shows. */
-enum class ViewerSheet { None, More, ViewSettings, Attachments, Bookmarks, Comments, MoreTools }
+enum class ViewerSheet { None, More, ViewSettings, Attachments, Bookmarks, Comments, MoreTools, Signatures }
/**
* The viewer's own state for one document, beside the page view ([ViewerState]): whether the
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt
index 00060c8..0892b98 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt
@@ -395,6 +395,7 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {
ViewerSheet.Attachments -> AttachmentsSheet(vm, doc)
ViewerSheet.Comments -> Unit
ViewerSheet.MoreTools -> MoreToolsSheet(vm, doc)
+ ViewerSheet.Signatures -> SignaturesSheet(vm, doc)
ViewerSheet.None -> Unit
}
}
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerSheets.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerSheets.kt
index b4aee91..6f051f0 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerSheets.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerSheets.kt
@@ -110,6 +110,7 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {
if (doc.info.attachments > 0u) SheetRow(LucideIcons.Paperclip, "Attachments", { ctl.sheet = ViewerSheet.Attachments }, chevron = true)
SheetRow(LucideIcons.Bookmark, "Bookmarks & Table of Contents", { ctl.sheet = ViewerSheet.Bookmarks }, chevron = true)
SheetRow(LucideIcons.MessagesSquare, "Comment List", { ctl.sheet = ViewerSheet.Comments }, chevron = true)
+ SheetRow(LucideIcons.ShieldCheck, "Signatures", { ctl.sheet = ViewerSheet.Signatures }, chevron = true)
SheetRow(
if (bookmarked) LucideIcons.BookmarkMinus else LucideIcons.BookmarkPlus,
if (bookmarked) "Remove bookmark" else "Add bookmark",
@@ -379,16 +380,19 @@ fun pdfDateLabel(s: String?): String? {
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(t))
}
-/** The moment a PDF date names (`D:20261011171900Z`, `D:20261011171900-06'00'`, or the engine's `2026-10-11 17:19`). */
+/**
+ * The moment a PDF date names (`D:20261011171900Z`, `D:20261011171900-06'00'`, the engine's
+ * `2026-10-11 17:19`, or a certificate's `2031.10.19 13:59:58 UTC`).
+ */
fun pdfDateMillis(s: String?): Long? {
if (s == null) return null
- val m = Regex("""(\d{4})[-/]?(\d{2})?[-/]?(\d{2})?[ T]?(\d{2})?:?(\d{2})?:?(\d{2})?(Z|[+-]\d{2}'?\d{2}'?)?""").find(s) ?: return null
+ val m = Regex("""(\d{4})[-/.]?(\d{2})?[-/.]?(\d{2})?[ T]?(\d{2})?:?(\d{2})?:?(\d{2})? ?(Z|UTC|[+-]\d{2}'?\d{2}'?)?""").find(s) ?: return null
val g = m.groupValues
// with a time zone the moment is exact and shows in the phone's local time; without one, as written
val tz = g[7]
val zone = when {
tz.isEmpty() -> java.util.TimeZone.getDefault()
- tz == "Z" -> java.util.TimeZone.getTimeZone("UTC")
+ tz == "Z" || tz == "UTC" -> java.util.TimeZone.getTimeZone("UTC")
else -> java.util.TimeZone.getTimeZone("GMT" + tz.substring(0, 3) + ":" + tz.filter { it.isDigit() }.drop(2).padEnd(2, '0').take(2))
}
val cal = java.util.Calendar.getInstance(zone)
diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/PdfDateTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/PdfDateTest.kt
index 32831d0..e1403b1 100644
--- a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/PdfDateTest.kt
+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/PdfDateTest.kt
@@ -32,6 +32,12 @@ class PdfDateTest {
return java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.MEDIUM, java.text.DateFormat.SHORT).format(cal.time)
}
+ @Test
+ fun aCertificateDateShowsInLocalTime() {
+ // the engine writes certificate validity as "2031.10.19 13:59:58 UTC"
+ assertEquals(label(2031, 10, 19, 7, 59), pdfDateLabel("2031.10.19 13:59:58 UTC"))
+ }
+
@Test
fun aUtcDateShowsInLocalTime() {
// 03:28 UTC on the 12th is 21:28 on the 11th six hours west
diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/SignatureBoxTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/SignatureBoxTest.kt
new file mode 100644
index 0000000..a870f27
--- /dev/null
+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/SignatureBoxTest.kt
@@ -0,0 +1,31 @@
+package io.github.artcraftandroid.pdfcraft.ui
+
+import io.github.artcraftandroid.pdfcraft.ui.viewer.fitSignatureBox
+import org.junit.Assert.assertArrayEquals
+import org.junit.Test
+
+class SignatureBoxTest {
+ @Test
+ fun aDraggedBoxBigEnoughIsKept() {
+ val r = floatArrayOf(100f, 200f, 300f, 260f)
+ assertArrayEquals(r, fitSignatureBox(r, 0f, 0f, 612f, 792f), 0.001f)
+ }
+
+ @Test
+ fun aTapGivesTheUsualBoxCentredThere() {
+ assertArrayEquals(floatArrayOf(210f, 373f, 390f, 427f), fitSignatureBox(null, 300f, 400f, 612f, 792f), 0.001f)
+ }
+
+ @Test
+ fun aSmallBoxGrowsAroundItsCentre() {
+ assertArrayEquals(floatArrayOf(210f, 373f, 390f, 427f), fitSignatureBox(floatArrayOf(290f, 395f, 310f, 405f), 0f, 0f, 612f, 792f), 0.001f)
+ }
+
+ @Test
+ fun theBoxStaysOnThePage() {
+ // tapped in the bottom-right corner: pushed back inside
+ assertArrayEquals(floatArrayOf(432f, 738f, 612f, 792f), fitSignatureBox(null, 610f, 790f, 612f, 792f), 0.001f)
+ // a page smaller than the usual box: the box is the page
+ assertArrayEquals(floatArrayOf(0f, 0f, 100f, 40f), fitSignatureBox(null, 50f, 20f, 100f, 40f), 0.001f)
+ }
+}
diff --git a/apps/pdfcraft-android/src/lib.rs b/apps/pdfcraft-android/src/lib.rs
index 6536524..3d79ae6 100644
--- a/apps/pdfcraft-android/src/lib.rs
+++ b/apps/pdfcraft-android/src/lib.rs
@@ -166,6 +166,53 @@ pub fn file_thumbnail(path: String, max_side: u32) -> Result<RenderedImage, Mobi
Ok(RenderedImage { width: out.width, height: out.height, rgba: out.rgba.to_vec() })
}
+/// A digital ID file's certificate, as the app lists the IDs it can sign with.
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct DigitalIdInfo {
+ /// Whose it is (the certificate's common name, else its whole subject).
+ pub name: String,
+ pub issuer: String,
+ pub email: Option<String>,
+ /// When it starts and stops being valid (seconds since 1970).
+ pub valid_from: i64,
+ pub valid_to: i64,
+ pub self_signed: bool,
+ /// The certificate's SHA-256 fingerprint (hex), which tells IDs apart.
+ pub sha256: String,
+ /// Why it can't sign documents, if it can't (its key usage doesn't allow it).
+ pub problem: Option<String>,
+}
+
+/// The largest digital ID file read: real ones are a few kilobytes.
+const MAX_ID_FILE: u64 = 1 << 20;
+
+/// What the digital ID file (.p12 / .pfx) at absolute path `path` holds, unlocked with
+/// `password`: a wrong password is [`MobileError::WrongPassword`].
+#[uniffi::export]
+pub fn digital_id_info(path: String, password: String) -> Result<DigitalIdInfo, MobileError> {
+ use pdfcraft_engine::sign::{SignError, pkcs12};
+ let size = std::fs::metadata(&path).map_err(|e| MobileError::Command(format!("{path}: {e}")))?.len();
+ if size > MAX_ID_FILE {
+ return Err(MobileError::Command("this is not a digital ID file (it is too large)".into()));
+ }
+ let bytes = std::fs::read(&path).map_err(|e| MobileError::Command(format!("{path}: {e}")))?;
+ let id = pkcs12::open(&bytes, &password).map_err(|e| match e {
+ SignError::WrongPassword => MobileError::WrongPassword,
+ e => MobileError::Command(e.to_string()),
+ })?;
+ let c = &id.certificate;
+ Ok(DigitalIdInfo {
+ name: c.display_name(),
+ issuer: c.issuer.display(),
+ email: c.subject.email().map(str::to_string),
+ valid_from: c.not_before.unix(),
+ valid_to: c.not_after.unix(),
+ self_signed: c.is_self_signed(),
+ sha256: c.fingerprint(),
+ problem: c.signing_problem().map(|d| d.message),
+ })
+}
+
/// The engine version (`0.6.0`).
#[uniffi::export]
pub fn engine_version() -> String {
@@ -677,6 +724,12 @@ impl MobileSession {
std::fs::write(&path, wav).map_err(|e| MobileError::Command(format!("{path}: {e}")))
}
+ /// The certificate (DER) that signed signature field `field`, if it is signed: what the app
+ /// saves when the reader chooses to trust that signer.
+ pub fn signer_certificate(&self, doc: u64, field: String) -> Result<Option<Vec<u8>>, MobileError> {
+ self.with_doc(doc, |d| d.signatures.iter().find(|s| s.signed && s.field == field).and_then(|s| s.certificate.as_ref()).map(|c| c.raw.clone()))
+ }
+
/// Every visible widget of the document's form fields, page by page.
pub fn widgets(&self, doc: u64) -> Result<Vec<WidgetInfo>, MobileError> {
use pdfcraft_engine::{FormFieldKind as K, field_flags as fl};
diff --git a/apps/pdfcraft-android/src/tests.rs b/apps/pdfcraft-android/src/tests.rs
index 9a44c4c..d625ecf 100644
--- a/apps/pdfcraft-android/src/tests.rs
+++ b/apps/pdfcraft-android/src/tests.rs
@@ -364,3 +364,50 @@ fn reading_blocks_split_paragraphs_and_map_characters_to_glyphs() {
let range = TextRange { page: 0, start: second.glyph_of_char[0], end: second.glyph_of_char[5] + 1 };
assert_eq!(s.text_of(doc, range).unwrap(), "Second");
}
+
+#[test]
+fn signs_with_a_digital_id_and_trusts_its_signer() {
+ let s = MobileSession::new();
+ let dir = scratch();
+ let id = dir.join("me.p12").to_string_lossy().into_owned();
+ let made = json!({ "name": "Test Signer", "email": "[email protected]", "password": "secret1", "path": id });
+ s.execute("sign_id_create".into(), made.to_string()).unwrap();
+ // the file's certificate, and a wrong password told apart
+ let info = digital_id_info(id.clone(), "secret1".into()).unwrap();
+ assert_eq!(info.name, "Test Signer");
+ assert_eq!(info.email.as_deref(), Some("[email protected]"));
+ assert!(info.self_signed && info.valid_to > info.valid_from && info.problem.is_none());
+ assert_eq!(info.sha256.replace(' ', "").len(), 64);
+ assert!(matches!(digital_id_info(id.clone(), "wrong".into()), Err(MobileError::WrongPassword)));
+ let junk = dir.join("junk.p12");
+ std::fs::write(&junk, b"not a digital id").unwrap();
+ assert!(matches!(digital_id_info(junk.to_string_lossy().into_owned(), "x".into()), Err(MobileError::Command(_))));
+
+ // signing writes the signed file over the working copy the document was opened from
+ let path = blank_pdf(1);
+ let doc = s.open(path.clone(), None).unwrap().id;
+ assert!(s.signer_certificate(doc, "Signature1".into()).unwrap().is_none());
+ let args =
+ json!({ "doc": doc, "id": id, "password": "secret1", "page": 1, "rect": [72, 72, 252, 122], "graphic": { "text": "Test" }, "out": path });
+ let out: Value = serde_json::from_str(&s.execute("sign_document".into(), args.to_string()).unwrap()).unwrap();
+ let field = out["signature"]["field"].as_str().unwrap().to_string();
+ assert_eq!(out["signature"]["status"], "unknown");
+ let info = s.document(doc).unwrap();
+ assert!(info.signed && !info.dirty && info.undo.is_none());
+ assert_eq!(std::fs::read(&path).unwrap().len() as u64, out["bytes"].as_u64().unwrap());
+
+ // trusting the signer's certificate makes the signature valid
+ let cert = s.signer_certificate(doc, field).unwrap().unwrap();
+ let cer = dir.join("signer.cer");
+ std::fs::write(&cer, &cert).unwrap();
+ s.execute("sign_trust".into(), json!({ "paths": [cer.to_string_lossy()] }).to_string()).unwrap();
+ let list: Value = serde_json::from_str(&s.execute("sign_list".into(), json!({ "doc": doc }).to_string()).unwrap()).unwrap();
+ assert_eq!(list["all_valid"], true);
+
+ // an edit after signing is saved incrementally: the signature stays valid
+ s.execute("comment_add".into(), json!({ "doc": doc, "page": 1, "type": "note", "at": [300, 300], "contents": "after" }).to_string()).unwrap();
+ s.execute("doc_save".into(), json!({ "doc": doc }).to_string()).unwrap();
+ let list: Value = serde_json::from_str(&s.execute("sign_list".into(), json!({ "doc": doc }).to_string()).unwrap()).unwrap();
+ assert_eq!(list["signatures"][0]["status"], "valid");
+ assert_eq!(list["signatures"][0]["modification"], "allowed");
+}