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
feat: form buttons run their scripts and script alerts show (#30)
Josh49cdab1e5739
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.ktindex 8579f6d..a7f71af 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@@ -146,6 +146,12 @@ fun AppRoot(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage: () ->Text(stringResource(R.string.root_open_link_body, shown), color = c.text, fontSize = 14.sp)}}+ // a form script's alert, as the form words it+ vm.scriptAlerts.firstOrNull()?.let { message ->+ PdfDialog(onDismiss = vm::dismissScriptAlert, title = null, confirm = stringResource(R.string.common_ok), onConfirm = vm::dismissScriptAlert, dismiss = null) {+ Text(message, color = c.text, fontSize = 14.sp)+ }+ }vm.confirmDeleteAllBookmarks?.let { d ->PdfDialog(onDismiss = { vm.confirmDeleteAllBookmarks = null }, title = stringResource(R.string.root_delete_bookmarks_title),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 c63d494..d78d323 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@@ -56,6 +56,9 @@ data class Message(val text: String, val actionLabel: String? = null, val action/** A document waiting for its password before it opens. */data class PasswordRequest(val uri: Uri, val file: File, val wrong: Boolean)+/** Script alerts waiting at once, at most. */+private const val MAX_SCRIPT_ALERTS = 20+/** The app's state: the engine, the open document, Home's lists, and the messages. */class AppViewModel(app: Application) : AndroidViewModel(app) {private val application = app as PdfcraftApplication@@ -1783,8 +1786,8 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {/*** A form button: does what its release action says, as far as a reader does on a phone:- * clear the form (or the fields it names), open a web address after asking, or go to a page.- * Scripts and sending the form online aren't run.+ * clear the form (or the fields it names), open a web address after asking, go to a page, or+ * run its script. Sending the form online isn't done.*/private fun pressButton(doc: OpenDocument, w: io.github.artcraftandroid.pdfcraft.core.WidgetInfo) {val eng = engine ?: return@@ -1801,13 +1804,56 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {act.has("url") -> linkPrompt = act.optString("url")act.has("page") -> doc.viewer.goToPage((act.optInt("page") - 1).coerceIn(0, doc.pageCount - 1))act.has("submit") -> tell(text(R.string.msg_button_submit))- act.has("javascript") -> tell(text(R.string.msg_button_script))+ act.has("javascript") -> runTool(doc, "js_run", mapOf("field" to w.field, "script" to act.optString("javascript"))) { scriptOutput(doc, it) }}}}fun fillField(doc: OpenDocument, field: String, value: Any) {- runTool(doc, "form_fill", mapOf("values" to mapOf(field to value)))+ val eng = engine ?: return+ viewModelScope.launch {+ try {+ val r = eng.tool("form_fill", mapOf("doc" to doc.id, "values" to mapOf(field to value)))+ refresh(doc)+ scriptOutput(doc, r)+ } catch (e: MobileException) {+ // the field refused the value (its format, or its own script's check): said in a+ // dialog, in the form's own words+ showScriptAlert(e.userMessage)+ }+ }+ }++ /** What a form's scripts said (their alerts), shown one at a time. */+ val scriptAlerts = androidx.compose.runtime.mutableStateListOf<String>()++ private fun showScriptAlert(message: String) {+ // a script that alerts in a loop can't queue dialogs without end+ if (message.isNotBlank() && scriptAlerts.size < MAX_SCRIPT_ALERTS) scriptAlerts.add(message)+ }++ fun dismissScriptAlert() {+ if (scriptAlerts.isNotEmpty()) scriptAlerts.removeAt(0)+ }++ /**+ * What a form's scripts said and asked of the viewer, from a tool's result: alerts are shown, a+ * page is shown, a web address asks first and printing prints; sending the form online isn't done.+ */+ private fun scriptOutput(doc: OpenDocument, r: JSONObject) {+ // a script that failed: kept out of sight, as the reference keeps it, but in the log+ r.optString("error").takeIf { it.isNotEmpty() && it != "null" }?.let { android.util.Log.w("PdfCraft", "form script: $it") }+ r.optJSONArray("alerts")?.let { a -> for (i in 0 until a.length()) showScriptAlert(a.optString(i)) }+ val requests = r.optJSONArray("requests") ?: return+ for (i in 0 until requests.length()) {+ val q = requests.optJSONObject(i) ?: continue+ when {+ q.has("page") -> doc.viewer.goToPage((q.optInt("page") - 1).coerceIn(0, doc.pageCount - 1))+ q.has("url") -> linkPrompt = q.optString("url")+ q.has("print") -> print(doc)+ q.has("submit") -> tell(text(R.string.msg_button_submit))+ }+ }}/** Move to the next (or previous) fillable text or choice field in reading order. */diff --git a/apps/pdfcraft-android/android/app/src/main/res/values-es/strings.xml b/apps/pdfcraft-android/android/app/src/main/res/values-es/strings.xmlindex 8364cfd..adc15ee 100644--- a/apps/pdfcraft-android/android/app/src/main/res/values-es/strings.xml+++ b/apps/pdfcraft-android/android/app/src/main/res/values-es/strings.xml@@ -1072,7 +1072,6 @@<!-- Messages: forms --><string name="msg_form_cleared">Formulario borrado</string><string name="msg_button_submit">Este botón envía el formulario por internet, algo que PdfCraft no hace.</string>- <string name="msg_button_script">Este botón ejecuta un script, algo que PdfCraft no ejecuta.</string><!-- Words remembered from form fields, offered while typing. --><string name="msg_suggestions_cleared">Sugerencias borradas</string>diff --git a/apps/pdfcraft-android/android/app/src/main/res/values/strings.xml b/apps/pdfcraft-android/android/app/src/main/res/values/strings.xmlindex b54b7f0..0137410 100644--- a/apps/pdfcraft-android/android/app/src/main/res/values/strings.xml+++ b/apps/pdfcraft-android/android/app/src/main/res/values/strings.xml@@ -1073,7 +1073,6 @@<!-- Messages: forms --><string name="msg_form_cleared">Form cleared</string><string name="msg_button_submit">This button sends the form online, which PdfCraft doesn\'t do.</string>- <string name="msg_button_script">This button runs a script, which PdfCraft doesn\'t run.</string><!-- Words remembered from form fields, offered while typing. --><string name="msg_suggestions_cleared">Suggestions cleared</string>diff --git a/apps/pdfcraft-android/src/tests.rs b/apps/pdfcraft-android/src/tests.rsindex 4732440..e541d65 100644--- a/apps/pdfcraft-android/src/tests.rs+++ b/apps/pdfcraft-android/src/tests.rs@@ -411,3 +411,33 @@ fn signs_with_a_digital_id_and_trusts_its_signer() {assert_eq!(list["signatures"][0]["status"], "valid");assert_eq!(list["signatures"][0]["modification"], "allowed");}++/// A form's scripts run through the calls the app makes: filling a field recalculates a scripted+/// total and returns its alert, and a button's script (from `form_actions`) runs with `js_run`.+#[test]+fn form_scripts_run_when_fields_are_filled_and_buttons_pressed() {+ let s = MobileSession::new();+ let doc = s.open(blank_pdf(1), None).unwrap().id;+ let run = |tool: &str, args: Value| -> Value { serde_json::from_str(&s.execute(tool.into(), args.to_string()).unwrap()).unwrap() };+ for (i, name) in ["a", "b", "total"].into_iter().enumerate() {+ let y = 100 + 30 * i;+ run("form_add_field", json!({"doc": doc, "page": 1, "type": "text", "rect": [200, y, 360, y + 20], "name": name}));+ }+ run("form_add_field", json!({"doc": doc, "page": 1, "type": "button", "rect": [200, 200, 360, 224], "name": "double", "caption": "Double a"}));+ let sum = "event.value = Number(this.getField(\"a\").value) + Number(this.getField(\"b\").value); if (event.value > 9) app.alert(\"Big\");";+ run("form_set_script", json!({"doc": doc, "field": "total", "event": "calculate", "script": sum}));+ let double = "var a = this.getField(\"a\"); a.value = Number(a.value) * 2; app.alert(\"a is now \" + a.value);";+ run("form_set_script", json!({"doc": doc, "field": "double", "event": "mouse_up", "script": double}));+ let total = |s: &MobileSession| s.widgets(doc).unwrap().into_iter().find(|w| w.field == "total").and_then(|w| w.value);++ run("form_fill", json!({"doc": doc, "values": {"a": "2"}}));+ let filled = run("form_fill", json!({"doc": doc, "values": {"b": "3"}}));+ assert_eq!(total(&s).as_deref(), Some("5"), "{filled}");+ let actions = run("form_actions", json!({"doc": doc, "field": "double"}));+ let script = actions["actions"][0]["javascript"].as_str().unwrap().to_owned();+ let pressed = run("js_run", json!({"doc": doc, "field": "double", "script": script}));+ assert_eq!(pressed["alerts"], json!(["a is now 4"]), "{pressed}");+ assert_eq!(total(&s).as_deref(), Some("7"));+ let big = run("form_fill", json!({"doc": doc, "values": {"b": "8"}}));+ assert_eq!(big["alerts"], json!(["Big"]), "{big}");+}diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rsindex 01dcc4f..88598c2 100644--- a/crates/automation/src/a11y.rs+++ b/crates/automation/src/a11y.rs@@ -650,7 +650,7 @@ impl Automation {}}-fn request_json(r: &pdfcraft_engine::js::Request) -> Value {+pub(crate) fn request_json(r: &pdfcraft_engine::js::Request) -> Value {use pdfcraft_engine::js::Request as R;match r {R::Reset(n) => json!({ "reset": n }),diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex 65e754d..765adf0 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -1311,6 +1311,15 @@ impl Automation {if !doc.edit_notices.is_empty() {out["warnings"] = json!(doc.edit_notices.iter().map(ToString::to_string).collect::<Vec<_>>());}+ // What the form's scripts said or asked of the viewer during the edit (a calculation's+ // alert, a page to show): returned for the front end to show, not left for later.+ let js = self.session.take_js_output(id);+ if !js.alerts.is_empty() {+ out["alerts"] = json!(js.alerts);+ }+ if !js.requests.is_empty() {+ out["requests"] = json!(js.requests.iter().map(a11y::request_json).collect::<Vec<_>>());+ }Ok(out)}diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex b3763f9..8232975 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -343,7 +343,7 @@ pub fn tools() -> Vec<ToolDef> {t("form_fill","Fill in form fields",- "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists. Appearances are regenerated so every viewer shows the values. A value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.",+ "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists. Appearances are regenerated so every viewer shows the values. A value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value. Alerts the form's scripts raise while filling are returned in `alerts`, and what they ask of the viewer (a page, a web address, printing) in `requests`; a value a field's own script refuses fails with that script's message.",).with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])),t("form_reset", "Clear form", "Reset fields to their default values: all of them, or only those listed. Undoable.")diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rsindex a6dd1c4..dd85a59 100644--- a/crates/automation/tests/it/automation.rs+++ b/crates/automation/tests/it/automation.rs@@ -4567,6 +4567,31 @@ fn form_formats_and_calculations_through_tools() {));}+/// A fill returns what the form's scripts said and asked for: a calculation's alert and the page+/// it shows come back with the result, and a value a validate script refuses fails with its alert.+#[test]+fn form_fill_returns_what_the_scripts_said() {+ let dir = workdir("formalerts");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ for (i, name) in ["qty", "total", "age"].into_iter().enumerate() {+ let y = 20 + 30 * i;+ ok(&mut a, "form_add_field", json!({ "doc": doc, "page": 1, "type": "text", "rect": [20, y, 180, y + 22], "name": name }));+ }+ let discount = "var q = Number(getField(\"qty\").value); if (q > 9) { app.alert(\"Ten or more: ask for a discount.\"); this.pageNum = 0; } event.value = q * 2;";+ ok(&mut a, "form_set_script", json!({ "doc": doc, "field": "total", "event": "calculate", "script": discount }));+ let age = "if (Number(event.value) > 120) { app.alert(\"That age is too high.\"); event.rc = false; }";+ ok(&mut a, "form_set_script", json!({ "doc": doc, "field": "age", "event": "validate", "script": age }));+ let small = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "qty": "3" } }));+ assert!(small.get("alerts").is_none() && small.get("requests").is_none(), "{small}");+ let big = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "qty": "12" } }));+ assert_eq!(big["alerts"], json!(["Ten or more: ask for a discount."]), "{big}");+ assert_eq!(big["requests"], json!([{ "page": 1 }]), "{big}");+ let refused = a.call("form_fill", &json!({ "doc": doc, "values": { "age": "150" } }));+ assert!(matches!(&refused, Err(e) if e.to_string().contains("That age is too high.")), "{refused:?}");+ std::fs::remove_dir_all(dir).unwrap();+}+/// Renaming a field renames it in the formulas that read it: a sum dropped the field, notation/// read it as 0 and a script kept a stale value.#[test]