From 2a3f748c98fbd0cfa475adfa0b960ad74d622d7a Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 18:45:39 -0600 Subject: [PATCH 1/2] feat(mobile): type into Android's own text field from the Capture form A NativeActivity hands its window's touches and keys to Rust, so egui's fields on Android get no paste, suggestions, glide typing or dictation. The Platform trait gains enter_text (a default that does nothing, so the desktop, the browser and iOS are unchanged): Android opens an EditText in a window of its own, docked above the soft keyboard, and sends its text back as an event on each change and again when it closes. The Capture form draws its text and number fields as boxes that open it. Text copied in RustGIS also goes on Android's clipboard. --- apps/rustgis-mobile/README.md | 8 +- .../java/org/rustgis/mobile/MainActivity.java | 213 +++++++++++++++++ apps/rustgis-mobile/src/android.rs | 8 +- apps/rustgis-mobile/src/phone.rs | 40 +++- apps/rustgis-mobile/src/shell.rs | 40 ++++ apps/rustgis-web/src/web.rs | 2 + crates/engine/src/platform.rs | 141 ++++++++++- crates/ui-egui/src/lib.rs | 8 + crates/ui-touch/src/lib.rs | 222 +++++++++++++++++- docs/user-guide/field-work.md | 6 +- 10 files changed, 670 insertions(+), 18 deletions(-) diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 52f2fad9ce..0c4629de35 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -84,6 +84,12 @@ Rust calls Java and never the other way: each frame the app collects what happen the More sheet, removes the picks the project in the window names no file of, once the user has seen how many and how large and agreed; a pick goes whole, so a Shapefile's `.dbf` goes only with its `.shp`. It runs off the window's thread, with Cancel. +- **Typing.** `NativeActivity` hands its window's touches and keys to Rust, so a text field in + that window gets none of Android's typing (paste, suggestions, dictation). A Capture field is + drawn as a box instead, and tapping it opens an `EditText` in a window of its own, docked above + the keyboard (`enterText`): its text comes back as a `text` event on each change, the form + showing it as it is typed, and `text-closed` when it closes. Text copied in RustGIS goes on + Android's clipboard too (`copyText`). Fields the desktop interface draws still use egui's own. - **Not yet.** Choosing a folder (Add Folder, a Zarr store) says it isn't available. ## The touch interface @@ -237,7 +243,7 @@ own was used outside the area) is said, as a later package from the same phone r | Memory limits | The app tells the engine what Android allows (`rustgis_data::memory::set_phone`): `ActivityManager.MemoryInfo`'s `totalMem` in place of the computer's memory, and `availMem` less `threshold` as what is free, asked again for each job. (`getMemoryClass` bounds only the Java heap; the engine's memory is native.) Where the browser's floor is lower than the desktop's, the phone takes it; the Undo budget is planned from what is free at start, and the threads' scratch memory is the browser's. On a low-memory warning the app drops the tile and drawing caches: `onTrimMemory` and `onLowMemory` through Android 13, and, as Android 14 and later send an app in use neither, `MemoryInfo.lowMemory`, asked every five seconds while the app is in sight (an idle window wakes that often to ask) | | Recovery copies | The first foreground edit submits a recovery copy in app-private storage immediately. Edits within two seconds of a submission are grouped into a copy due at the end of that interval. When the exit hook runs, it submits the latest edit immediately and gives the writer up to two seconds to finish. Suspending or destroying the Android activity can skip this hook, so edits still waiting to be submitted can be lost. The next launch offers the last complete copy, if one exists. | | Preferences, the keychain | Not wired up yet | -| Soft keyboard | It opens for a text field, and the touch interface keeps the field above it. `NativeActivity`'s text input is still poor (no suggestions, no composing): a real app moves to `GameActivity` | +| Soft keyboard | It opens for a text field, and the touch interface keeps the field above it. The Capture form's fields are typed into Android's own text box (see Typing above), with suggestions, composing, paste and dictation. Fields the desktop interface draws still get `NativeActivity`'s poor text input (no suggestions, no composing) | ## What phase 0 found diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index 3b60bffc18..b4fc89b80f 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -37,6 +37,10 @@ * stopped positioning ended without being asked to * low-memory Android is short of memory * photo name path a photo the camera took, in the app's photos folder + * text id text what a text field (enterText) holds now, its backslashes, + * tabs and line breaks written \\, \t, \n and \r + * text-closed id [reason] a text field closed, or (with reason) couldn't be opened + * copy-failed reason copied text that couldn't be put on Android's clipboard * failed text what went wrong, to show the user */ public class MainActivity extends NativeActivity { @@ -103,6 +107,16 @@ public class MainActivity extends NativeActivity { /** When takeEvents last asked whether Android is low on memory, and its answer (its thread's alone). */ private long memoryLooked; private boolean memoryLow; + /** Whether the Rust side draws on a light ground (barsLight): the text field's colours follow it. */ + private volatile boolean light = true; + /** The text field open over the app (enterText), while it is (the main thread's alone). */ + private android.app.Dialog entry; + /** + * The latest "text" event of a text field and that field's id, until takeEvents or the field's + * closing hands it over (guarded by events): only the latest is kept, as each has all its text. + */ + private String typedId; + private String typed; @Override protected void onCreate(android.os.Bundle saved) { @@ -131,6 +145,7 @@ protected void onCreate(android.os.Bundle saved) { * the Rust side says which whenever its theme changes. */ public void barsLight(final boolean light) { + this.light = light; runOnUiThread(() -> { if (android.os.Build.VERSION.SDK_INT >= 30) { android.view.WindowInsetsController bars = getWindow().getInsetsController(); @@ -395,6 +410,9 @@ protected void onDestroy() { if (current == this) { current = null; } + if (entry != null) { + entry.dismiss(); + } stopLocating(); stopService(new Intent(this, TrackService.class)); super.onDestroy(); @@ -444,6 +462,197 @@ public void takePhoto() { }); } + /** + * Opens a text field of Android's for a field the Rust side draws, docked above the soft + * keyboard, in a window of its own: NativeActivity hands its window's touches and keys to the + * Rust side, so a field there would get none. It gives Android's typing: paste, suggestions, + * glide typing, dictation, and a password manager for a "secret". What it holds is sent as a + * "text" event each time it changes, and "text-closed" when it closes (Done, Back, or a tap + * beside it, which goes no further). One opened while another is open replaces it. The kind + * is "plain", "lines", "secret" or "number"; done is the label of its button. + */ + public void enterText(final String id, final String value, final String label, final String kind, final String done) { + // Counted until it closes: the Rust side keeps looking for what is typed meanwhile. + synchronized (events) { + asked++; + } + runOnUiThread(() -> { + // Its own close is said by its listener. + if (entry != null) { + entry.dismiss(); + } + try { + entry = textEntry(id, value, label, kind, done); + entry.show(); + } catch (RuntimeException e) { + entry = null; + add("text-closed\t" + id + "\t" + oneField(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage())); + answered(); + } + }); + } + + /** The window of a text field (enterText), not yet shown. */ + private android.app.Dialog textEntry(final String id, String value, String label, String kind, String done) { + final android.app.Dialog dialog = new android.app.Dialog(this, light + ? android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar + : android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + android.content.Context themed = dialog.getContext(); + final int pad = Math.round(12 * getResources().getDisplayMetrics().density); + android.widget.LinearLayout panel = new android.widget.LinearLayout(themed); + panel.setOrientation(android.widget.LinearLayout.VERTICAL); + panel.setPadding(pad, pad, pad, pad); + android.widget.TextView title = new android.widget.TextView(themed); + title.setText(label); + panel.addView(title); + android.widget.LinearLayout row = new android.widget.LinearLayout(themed); + row.setOrientation(android.widget.LinearLayout.HORIZONTAL); + row.setGravity(android.view.Gravity.CENTER_VERTICAL); + android.widget.EditText field = new android.widget.EditText(themed); + int text = android.text.InputType.TYPE_CLASS_TEXT; + switch (kind) { + case "secret": + field.setInputType(text | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); + field.setAutofillHints(android.view.View.AUTOFILL_HINT_PASSWORD); + field.setImportantForAutofill(android.view.View.IMPORTANT_FOR_AUTOFILL_YES); + break; + case "number": + // The keyboard for numbers, without the filter that would come with it: it drops + // what isn't a digit, sign or point (the "e" of a pasted 1e3 would leave 13). The + // Rust side reads the number and refuses one it can't. + field.setInputType(text); + field.setRawInputType(android.text.InputType.TYPE_CLASS_NUMBER + | android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL | android.text.InputType.TYPE_NUMBER_FLAG_SIGNED); + break; + case "lines": + field.setInputType(text | android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE + | android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); + field.setMaxLines(6); + break; + default: + field.setInputType(text | android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); + } + // A form's field isn't a sign-in: the password manager is offered for a secret alone. + if (!kind.equals("secret")) { + field.setImportantForAutofill(android.view.View.IMPORTANT_FOR_AUTOFILL_NO); + } + field.setText(value); + field.setSelection(field.length()); + // The keyboard keeps to its own strip in landscape too, with the form in sight above it. + field.setImeOptions(android.view.inputmethod.EditorInfo.IME_ACTION_DONE + | android.view.inputmethod.EditorInfo.IME_FLAG_NO_FULLSCREEN); + field.setOnEditorActionListener((view, action, key) -> { + if (action == android.view.inputmethod.EditorInfo.IME_ACTION_DONE) { + dialog.dismiss(); + return true; + } + return false; + }); + field.addTextChangedListener(new android.text.TextWatcher() { + @Override + public void beforeTextChanged(CharSequence was, int start, int count, int after) {} + + @Override + public void onTextChanged(CharSequence now, int start, int before, int count) {} + + @Override + public void afterTextChanged(android.text.Editable now) { + typed(id, now.toString()); + } + }); + row.addView(field, new android.widget.LinearLayout.LayoutParams(0, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 1f)); + android.widget.Button finish = new android.widget.Button(themed); + finish.setText(done); + finish.setOnClickListener(view -> dialog.dismiss()); + row.addView(finish); + panel.addView(row); + dialog.setContentView(panel); + dialog.setCanceledOnTouchOutside(true); + dialog.setOnDismissListener(closed -> { + if (entry == dialog) { + entry = null; + } + synchronized (events) { + if (typed != null && id.equals(typedId)) { + events.add(typed); + typed = null; + } + events.add("text-closed\t" + id); + asked--; + } + }); + android.view.Window window = dialog.getWindow(); + if (window != null) { + window.setGravity(android.view.Gravity.BOTTOM); + window.setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT); + // The form stays in sight behind it, the value it shows changing as it is typed. + window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND); + window.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE + | android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + android.content.res.TypedArray colours = themed.obtainStyledAttributes(new int[] {android.R.attr.colorBackground}); + window.setBackgroundDrawable(new android.graphics.drawable.ColorDrawable( + colours.getColor(0, light ? android.graphics.Color.WHITE : android.graphics.Color.BLACK))); + colours.recycle(); + } + // Drawn edge to edge (Android 15 and later), it keeps above the keyboard and the + // navigation bar itself. + if (android.os.Build.VERSION.SDK_INT >= 30) { + panel.setOnApplyWindowInsetsListener((view, insets) -> { + android.graphics.Insets room = insets.getInsets(android.view.WindowInsets.Type.navigationBars() + | android.view.WindowInsets.Type.displayCutout() | android.view.WindowInsets.Type.ime()); + view.setPadding(pad + room.left, pad, pad + room.right, pad + room.bottom); + return insets; + }); + } + field.requestFocus(); + return dialog; + } + + /** Keeps what the text field {@code id} holds now as its "text" event, the one before it of another field handed over first. */ + private void typed(String id, String text) { + StringBuilder line = new StringBuilder("text\t").append(id).append('\t'); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + switch (c) { + case '\\': line.append("\\\\"); break; + case '\t': line.append("\\t"); break; + case '\n': line.append("\\n"); break; + case '\r': line.append("\\r"); break; + default: line.append(c); + } + } + synchronized (events) { + if (typed != null && !id.equals(typedId)) { + events.add(typed); + } + typedId = id; + typed = line.toString(); + } + } + + /** Puts text copied in the Rust side's window on Android's clipboard, for other apps. */ + public void copyText(final String text) { + // Counted until it is done: the Rust side keeps looking until a failure has reached it. + synchronized (events) { + asked++; + } + runOnUiThread(() -> { + try { + android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE); + if (clipboard == null) { + add("copy-failed\tthis device has no clipboard service"); + } else { + clipboard.setPrimaryClip(ClipData.newPlainText("RustGIS", text)); + } + } catch (RuntimeException e) { + // Too large for Android to pass on, say: the Rust side's own clipboard still has it. + add("copy-failed\t" + oneField(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage())); + } finally { + answered(); + } + }); + } + /** Asks the user for files with the system's picker; each arrives as a "picked" event. */ public void pick(final String purpose) { runOnUiThread(() -> { @@ -790,6 +999,10 @@ public String takeEvents() { add("failed\t" + why); } synchronized (events) { + if (typed != null) { + events.add(typed); + typed = null; + } String taken = events.take(); // Every notice waiting has been handed over: the copies they name are said. if (events.isEmpty()) { diff --git a/apps/rustgis-mobile/src/android.rs b/apps/rustgis-mobile/src/android.rs index b916d3e8f5..3f3ddefb87 100644 --- a/apps/rustgis-mobile/src/android.rs +++ b/apps/rustgis-mobile/src/android.rs @@ -1,5 +1,5 @@ -//! The Android app: a `NativeActivity` whose Java half ([`Phone`]) shows the system's pickers, -//! finds the device's position and asks the camera. +//! The Android app: a `NativeActivity` whose Java half ([`Phone`]) shows the system's pickers +//! and text fields, finds the device's position and asks the camera. use crate::phone::Phone; use crate::shell; @@ -31,6 +31,10 @@ impl shell::Phone for Phone { fn idle_look(&self) -> Option { Some(5000) } + + fn copy_text(&self, text: &str) { + Phone::copy_text(self, text); + } } /// Points the app's folders (`rustgis_data::dirs`) at the app's own storage: Android has no diff --git a/apps/rustgis-mobile/src/phone.rs b/apps/rustgis-mobile/src/phone.rs index bc1322c768..b9608fc0c7 100644 --- a/apps/rustgis-mobile/src/phone.rs +++ b/apps/rustgis-mobile/src/phone.rs @@ -1,5 +1,6 @@ -//! Android as a [`Platform`]: the system's file picker (the Storage Access Framework), asked for -//! through the activity's Java half (`java/org/rustgis/mobile/MainActivity.java`). +//! Android as a [`Platform`]: the system's file picker (the Storage Access Framework), its +//! position, camera and text fields, asked for through the activity's Java half +//! (`java/org/rustgis/mobile/MainActivity.java`). //! //! Rust calls Java and never the other way: what happened is collected with `takeEvents`, so the //! library exports nothing but `android_main`. @@ -8,7 +9,7 @@ use crate::shell; use jni::objects::{JObject, JString}; use jni::refs::Global; use jni::{JValue, JavaVM, jni_sig, jni_str}; -use rustgis_engine::platform::{Event, Platform}; +use rustgis_engine::platform::{Event, Platform, TextEntry}; use rustgis_ui_egui::i18n; use std::cell::RefCell; use std::sync::Arc; @@ -105,6 +106,18 @@ impl Phone { self.java(|env, activity| env.call_method(activity, jni_str!("picking"), jni_sig!(() -> boolean), &[])?.z()).unwrap_or(false) } + /// Puts `text` on the system's clipboard. A refusal is logged: the window's own clipboard + /// still has it. + pub fn copy_text(&self, text: &str) { + let asked = self.java(|env, activity| { + let text = env.new_string(text)?; + env.call_method(activity, jni_str!("copyText"), jni_sig!((text: JString) -> void), &[JValue::Object(&text)])?.v() + }); + if let Err(e) = asked { + log::warn!("{e}"); + } + } + /// Whether something asked for is still to be reported: the window keeps asking while it is. pub fn busy(&self) -> bool { self.java(|env, activity| env.call_method(activity, jni_str!("busy"), jni_sig!(() -> boolean), &[])?.z()).unwrap_or(false) @@ -177,6 +190,27 @@ impl Platform for Phone { self.java(|env, activity| env.call_method(activity, jni_str!("takePhoto"), jni_sig!(() -> void), &[])?.v()) } + fn enters_text(&self) -> bool { + true + } + + fn enter_text(&self, entry: &TextEntry) -> Result<(), String> { + self.java(|env, activity| { + let id = env.new_string(&entry.id)?; + let value = env.new_string(&entry.value)?; + let label = env.new_string(&entry.label)?; + let kind = env.new_string(entry.kind.word())?; + let done = env.new_string(&entry.done)?; + env.call_method( + activity, + jni_str!("enterText"), + jni_sig!((id: JString, value: JString, label: JString, kind: JString, done: JString) -> void), + &[JValue::Object(&id), JValue::Object(&value), JValue::Object(&label), JValue::Object(&kind), JValue::Object(&done)], + )? + .v() + }) + } + fn take_events(&self) -> Vec { let lines = self.java(|env, activity| { let taken = env.call_method(activity, jni_str!("takeEvents"), jni_sig!(() -> JString), &[])?.l()?; diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 095dec630f..03c2ef91e9 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -57,6 +57,12 @@ pub trait Phone: Platform { fn take_return(&self) -> bool { false } + + /// Puts `text`, copied in the window, on the system's clipboard too, where other apps can + /// paste it. The default does nothing: the window's own clipboard keeps it (iOS). + fn copy_text(&self, text: &str) { + let _ = text; + } } /// What a service couldn't do, kept until the next frame says it in the window (a service has @@ -253,6 +259,20 @@ impl App

{ self.app.position = None; } Event::LowMemory => self.app.release_memory(), + // The Capture form takes it (`rustgis_ui_touch`). + Event::Typed(typed) => { + if let rustgis_engine::platform::Typed::Closed { failed: Some(error), .. } = &typed { + self.app.session.notify(i18n::fmt("The text box couldn't be opened: {error}", &[("error", error)]), true); + } + self.app.typed.push(typed); + } + Event::CopyFailed(error) => self.app.session.notify( + i18n::fmt( + "The text copied wasn't put on the system's clipboard, so other apps can't paste it: {error}", + &[("error", &error)], + ), + true, + ), Event::Failed(text) => self.app.session.notify(text, true), } } @@ -607,6 +627,11 @@ fn use_picker( photographing.borrow_mut().photo_asked(); Ok(()) })); + // Where the phone has text fields of its own, the touch interface's fields open one. + if phone.enters_text() { + let typist = phone.clone(); + app.services.enter_text = Some(Box::new(move |entry| typist.enter_text(entry))); + } } impl eframe::App for App

{ @@ -636,6 +661,21 @@ impl eframe::App for App

{ } ui.painter().rect_filled(ctx.viewport_rect(), 0.0, tokens.pane); ui.scope_builder(egui::UiBuilder::new().max_rect(ctx.content_rect()), |ui| self.app.ui(ui)); + // Text copied in the window goes on the system's clipboard as well, for other apps. + if let Some(phone) = &self.phone { + let copied: Vec = ctx.output(|o| { + o.commands + .iter() + .filter_map(|c| match c { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }) + .collect() + }); + for text in copied { + phone.copy_text(&text); + } + } // A second picker asked for while one was up was refused: what the front end kept for // the first is put back, so its file is read as it was asked for. if self.refused_picker.replace(false) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e0c7628e58..086bd25d8f 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1289,6 +1289,8 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e take_photo: None, // A text field's Paste: the page reads the clipboard (Firefox and Safari show a Paste // button to confirm, Chrome asks once); only over HTTPS, where the browser offers it. + // The browser gives egui's own fields its typing: no text field of its own is needed. + enter_text: None, read_clipboard: clipboard().map(|clipboard| -> Box>)> { Box::new(move |slot| { let (clipboard, ctx) = (clipboard.clone(), clipboard_ctx.clone()); diff --git a/crates/engine/src/platform.rs b/crates/engine/src/platform.rs index 5fb9a8d001..db08ca738b 100644 --- a/crates/engine/src/platform.rs +++ b/crates/engine/src/platform.rs @@ -1,5 +1,5 @@ //! What a phone provides that a computer's window doesn't: the system's file picker, the device's -//! position and the camera. A mobile shell implements [`Platform`] for its system; a front end +//! position, the camera and its own text fields. A mobile shell implements [`Platform`] for its system; a front end //! asks through it and collects what happened with [`Platform::take_events`], as nothing here //! waits for the user. @@ -55,6 +55,92 @@ pub struct Fix { pub elapsed_realtime_nanos: Option, } +/// How a system's text field takes what is typed into it ([`Platform::enter_text`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextKind { + /// A line of text. + Plain, + /// Text of several lines: the keyboard's Return starts a new one. + Lines, + /// A password or key: hidden as it is typed, and offered to the system's password manager. + Secret, + /// A number, with the keyboard for numbers. + Number, +} + +impl TextKind { + /// The word a shell's own half reads it by (`plain`, `lines`, `secret`, `number`). + pub fn word(self) -> &'static str { + match self { + TextKind::Plain => "plain", + TextKind::Lines => "lines", + TextKind::Secret => "secret", + TextKind::Number => "number", + } + } +} + +/// A text field of the system's, asked for by a front end that draws its own field as a box +/// showing the value ([`Platform::enter_text`]). +#[derive(Clone, Debug, PartialEq)] +pub struct TextEntry { + /// The front end's own name for the field, returned with what is typed. + pub id: String, + /// What the field holds as it opens. + pub value: String, + /// What the field is for, shown with it. + pub label: String, + /// How it takes text. + pub kind: TextKind, + /// The label of the button that closes it, in the user's language. + pub done: String, +} + +/// What a system's text field sent back ([`Platform::enter_text`]). +#[derive(Clone, Debug, PartialEq)] +pub enum Typed { + /// The field `id` holds `text` now: sent as it changes, so nothing typed is lost however + /// the field closes. + Text { + /// The [`TextEntry::id`] it was opened with. + id: String, + /// All of its text. + text: String, + }, + /// The field `id` closed (Done, Back, a tap beside it); its last text came before this. + Closed { + /// The [`TextEntry::id`] it was opened with. + id: String, + /// Why it closed without opening, as the system said; `None` when it was open. + failed: Option, + }, +} + +/// Reads a field's text as a shell writes it on one line: a backslash, a tab and a line break +/// written `\\`, `\t`, `\n` and `\r`. A backslash before anything else is kept as it is. +fn unescape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + Some('t') => out.push('\t'), + Some('\\') => out.push('\\'), + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + /// What the system did since the front end last asked. #[derive(Clone, Debug, PartialEq)] pub enum Event { @@ -115,6 +201,10 @@ pub enum Event { Stopped, /// The system is short of memory: what can be made again is to be dropped. LowMemory, + /// A system's text field sent back what it holds, or closed ([`Platform::enter_text`]). + Typed(Typed), + /// Text copied in the window couldn't be put on the system's clipboard, for the reason given. + CopyFailed(String), /// Something went wrong: the text is for the user. Failed(String), } @@ -122,9 +212,11 @@ pub enum Event { impl Event { /// Reads an event a shell passed as one line of tab-separated fields (`picked`, `cancelled`, /// `ended`, `saved`, `project-saved`, `project-save-failed`, `project-document`, - /// `write-back-failed`, `photo`, `position`, `stopped`, `low-memory`, `failed`). A `picked` - /// line may end with the document it can write back to. Unrecognized lines become failures - /// that quote the line. A position is + /// `write-back-failed`, `photo`, `position`, `stopped`, `low-memory`, `text`, `text-closed`, + /// `copy-failed`, `failed`). A `picked` line may end with the document it can write back to. A + /// `text` line is the field's id, then its text with its backslashes, tabs and line breaks + /// escaped (`\\`, `\t`, `\n`, `\r`); a `text-closed` line may end with why the field didn't + /// open. Unrecognized lines become failures that quote the line. A position is /// `position`, longitude, latitude, accuracy (empty when unknown), optionally its time in /// milliseconds since 1970, then optionally the monotonic fix time in nanoseconds since boot. pub fn parse(line: &str) -> Event { @@ -151,6 +243,12 @@ impl Event { ["photo", name, path] if !path.is_empty() => Event::Photo { name: name.to_string(), path: PathBuf::from(path) }, ["stopped"] => Event::Stopped, ["low-memory"] => Event::LowMemory, + ["text", id, text] if !id.is_empty() => Event::Typed(Typed::Text { id: id.to_string(), text: unescape(text) }), + ["text-closed", id] if !id.is_empty() => Event::Typed(Typed::Closed { id: id.to_string(), failed: None }), + ["text-closed", id, why @ ..] if !id.is_empty() && !why.concat().is_empty() => { + Event::Typed(Typed::Closed { id: id.to_string(), failed: Some(why.join("\t")) }) + } + ["copy-failed", why @ ..] if !why.is_empty() => Event::CopyFailed(why.join("\t")), // A name is the user's own text and may hold a tab: the rest of the line is the name. ["saved", name @ ..] if !name.is_empty() => Event::Saved { name: name.join("\t") }, ["project-saved", name @ ..] if !name.is_empty() => Event::ProjectSave(Ok(name.join("\t"))), @@ -235,6 +333,22 @@ pub trait Platform { /// taken. fn take_photo(&self) -> Result<(), String>; + /// Whether [`Platform::enter_text`] opens a text field of the system's. Where it doesn't, the + /// front end types into its own fields. + fn enters_text(&self) -> bool { + false + } + + /// Opens a text field of the system's for `entry`, docked above the soft keyboard: what it + /// holds arrives as [`Typed::Text`] each time it changes, then [`Typed::Closed`] when it + /// closes. It gives the system's typing (paste, suggestions, dictation, a password manager + /// for a [`TextKind::Secret`]), which a field drawn by the front end may not get. One opened + /// while another is open replaces it, which closes first. `Ok` means it was asked for. + fn enter_text(&self, entry: &TextEntry) -> Result<(), String> { + let _ = entry; + Err("this system has no text field for RustGIS to open".into()) + } + /// What happened since the last call, oldest first. fn take_events(&self) -> Vec; } @@ -326,6 +440,18 @@ mod tests { assert_eq!(Event::parse("saved\tmy\tmap.png"), Event::Saved { name: "my\tmap.png".into() }); assert_eq!(Event::parse("project-saved\tmy\tproject.rgis"), Event::ProjectSave(Ok("my\tproject.rgis".into()))); assert_eq!(Event::parse("project-save-failed\tPicker cancelled"), Event::ProjectSave(Err("Picker cancelled".into()))); + // A text field's text, its tabs, line breaks and backslashes escaped on the line. + assert_eq!( + Event::parse("text\tcapture:1:name\tTwo\\nlines\\tand a tab, C:\\\\x, \\q kept"), + Event::Typed(Typed::Text { id: "capture:1:name".into(), text: "Two\nlines\tand a tab, C:\\x, \\q kept".into() }) + ); + assert_eq!(Event::parse("text\tkey\t"), Event::Typed(Typed::Text { id: "key".into(), text: String::new() })); + assert_eq!(Event::parse("text-closed\tkey"), Event::Typed(Typed::Closed { id: "key".into(), failed: None })); + assert_eq!( + Event::parse("text-closed\tkey\tno window"), + Event::Typed(Typed::Closed { id: "key".into(), failed: Some("no window".into()) }) + ); + assert_eq!(Event::parse("copy-failed\ttoo large"), Event::CopyFailed("too large".into())); // A failure's text is kept whole, tabs and all. assert_eq!(Event::parse("failed\ta.gpkg wasn't opened:\tno room"), Event::Failed("a.gpkg wasn't opened:\tno room".into())); } @@ -354,6 +480,13 @@ mod tests { "position\t10\t20\t3\t-5", "position\t10\t20\t3\t1\t-2", "position\t10\t20\t3\t1\t2\t3", + "text\tkey", + "text\t\tvalue", + "text\tkey\ta\tb", + "text-closed", + "text-closed\t", + "text-closed\tkey\t", + "copy-failed", ] { match Event::parse(line) { Event::Failed(text) => assert!(text.ends_with(line), "{text}"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47c33d56f4..400a2e27de 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -526,6 +526,10 @@ pub struct Services { /// which may ask the user first), for a text field's Paste; `None` where the window sends /// it (the desktop) or the browser can't read it (a page not served over HTTPS). pub read_clipboard: Option>)>>, + /// Opens a text field of the system's for a field an interface draws as a box showing its + /// value (a phone's, `rustgis_engine::platform::Platform::enter_text`): what is typed arrives + /// in [`RustGisApp::typed`]. `None` where the interface's own fields take the system's typing. + pub enter_text: Option Result<(), String>>>, /// Signs in to an ArcGIS portal (its address and an OAuth client id, either blank for ArcGIS /// Online and RustGIS's own app) in a pop-up window, putting who signed in, or why not, in the /// slot (the browser; the desktop runs `arcgis.signIn`). @@ -1488,6 +1492,9 @@ pub struct RustGisApp { /// Photos the camera took ([`Services::take_photo`]), by where they were written, until an /// interface takes them. pub photos: Vec, + /// What the system's text fields sent back ([`Services::enter_text`]), oldest first, until + /// an interface takes it. + pub typed: Vec, /// How many positions were dropped from [`RustGisApp::fixes`] past [`FIXES_KEPT`] since an /// interface last took them: the interface says so when a track or an average missed them. pub fixes_dropped: usize, @@ -1798,6 +1805,7 @@ impl RustGisApp { fixes: std::collections::VecDeque::new(), keep_locating: false, photos: Vec::new(), + typed: Vec::new(), fixes_dropped: 0, said_low_memory: false, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index b9d7696e86..6ca4d33ffa 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -20,6 +20,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use egui::{Align, Color32, CornerRadius, Layout, Rect, RichText, Sense, Stroke, Ui, Vec2}; +use rustgis_ui_egui::rustgis_engine::platform::{TextEntry, TextKind, Typed}; use rustgis_ui_egui::theme::Tokens; use rustgis_ui_egui::{RustGisApp, i18n, icons, tl}; use serde_json::{Value, json}; @@ -89,6 +90,13 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { track::take(app, &ctx); // What Remove Unused Copies found or removed, off the window's thread. copies::poll(app, &ctx); + // What the system's text field sent back goes in the Capture form's field it was opened for. + if !app.typed.is_empty() { + let mut state = form(&ctx); + let typed = std::mem::take(&mut app.typed); + state.take_typed(app, typed); + set_form(&ctx, state); + } // With positioning off (Hide My Position, or Android ending it), an average being taken // stops: the sheet no longer shows it, and positions from before would mix into the next. if !app.locate { @@ -502,6 +510,24 @@ struct Form { /// The height of the window the sheet was last drawn in: when it changes (the soft keyboard /// came or went), the field being typed in is scrolled back into view. window: f32, + /// The system's text field open for one of the fields ([`Services::enter_text`]), until it + /// closes. + /// + /// [`Services::enter_text`]: rustgis_ui_egui::Services::enter_text + entering: Option, + /// How many times the system's text field was opened: each opening's id is its own. + entries: u64, +} + +/// The system's text field open for a field of the Capture form. +#[derive(Clone, Debug, PartialEq)] +struct Entering { + /// The id it was opened with ([`entry_id`]). + id: String, + /// The layer whose field it is, by `Layer::instance_id`. + instance: u64, + /// The field's name. + field: String, } impl Form { @@ -521,6 +547,46 @@ impl Form { } self } + + /// Takes what the system's text field sent back: the text of the one this form opened goes + /// in its field as it changes, until it closes, while Capture still adds to that field's layer + /// and the layer still has the field. Text that no longer has its field is said, once, and + /// what follows it let go. What an earlier opening sends (its close, arriving after the field + /// was opened again) belongs to no field here. + fn take_typed(&mut self, app: &mut RustGisApp, typed: Vec) { + for typed in typed { + let Some(open) = self.entering.clone() else { continue }; + match typed { + Typed::Text { id, text } if id == open.id => { + let here = capture_layer(app, self).filter(|t| t.instance == open.instance && self.shown == Some(t.instance)); + let has_field = + here.and_then(|t| app.session.map().layer(t.id)).is_some_and(|l| l.dataset.field_index(&open.field).is_some()); + if has_field { + self.values.insert(open.field, text); + } else { + self.entering = None; + app.session.notify( + i18n::fmt( + "What was typed for {field} wasn't kept: Capture no longer adds to its layer, or the layer no longer has the field.", + &[("field", &open.field)], + ), + true, + ); + } + } + Typed::Closed { id, .. } if id == open.id => self.entering = None, + _ => {} + } + } + } +} + +/// The id the system's text field is opened with for the form's field `index` of the layer +/// `instance` (`Layer::instance_id`), the `n`th time it was opened: an answer for one layer's +/// field never fills another's, nor an earlier opening's close ends a later one. No name of the +/// user's goes in it, so it never holds a tab, which would end it on the event's line. +fn entry_id(instance: u64, index: usize, n: u64) -> String { + format!("capture:{instance}:{index}:{n}") } impl Form { @@ -1232,15 +1298,41 @@ fn capture_fields(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, target: &Target (FieldType::DateTime, None) => tl!("a date and time").to_string(), _ => String::new(), }; - let edit = egui::TextEdit::singleline(value) - .hint_text(hint) - .font(egui::FontId::proportional(15.0)) - .margin(egui::Margin::symmetric(8, 10)); // A date field keeps room for the button that opens its calendar. let room = if dated { ui.available_width() - TARGET - ui.spacing().item_spacing.x } else { ui.available_width() }; - let typed = ui.add_sized([room.max(TARGET), TARGET - 6.0], edit); - if typed.gained_focus() || (typed.has_focus() && resized) { - typed.scroll_to_me(Some(Align::Center)); + let size = Vec2::new(room.max(TARGET), TARGET - 6.0); + if let Some(enter) = &app.services.enter_text { + // Typed into the system's own field (a phone's, docked above its keyboard), + // which gives its paste, suggestions and dictation: this one shows the value. + let open = state.entering.as_ref().is_some_and(|e| e.instance == target.instance && e.field == field.name); + if entry_box(ui, t, size, value, &hint, open).clicked() { + let id = entry_id(target.instance, i, state.entries); + let kind = match field.ty { + FieldType::Integer | FieldType::Double => TextKind::Number, + _ => TextKind::Plain, + }; + let entry = TextEntry { + id: id.clone(), + value: value.clone(), + label: label.clone(), + kind, + done: tl!("Done").to_string(), + }; + state.entries += 1; + match enter(&entry) { + Ok(()) => state.entering = Some(Entering { id, instance: target.instance, field: field.name.clone() }), + Err(e) => app.session.notify(e, true), + } + } + } else { + let edit = egui::TextEdit::singleline(value) + .hint_text(hint) + .font(egui::FontId::proportional(15.0)) + .margin(egui::Margin::symmetric(8, 10)); + let typed = ui.add_sized(size, edit); + if typed.gained_focus() || (typed.has_focus() && resized) { + typed.scroll_to_me(Some(Align::Center)); + } } if dated { let open = state.calendar.as_ref().is_some_and(|(name, _)| name == &field.name); @@ -1283,6 +1375,25 @@ fn capture_fields(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, target: &Target } } +/// A field drawn as a box showing its `value` (or `hint` while it is empty) that is typed into +/// with the system's text field, opened when it is tapped: outlined in the accent colour while +/// that field is `open` for it. +fn entry_box(ui: &mut Ui, t: &Tokens, size: Vec2, value: &str, hint: &str, open: bool) -> egui::Response { + let (rect, response) = ui.allocate_exact_size(size, Sense::click()); + response.widget_info(|| egui::WidgetInfo::text_edit(ui.is_enabled(), value, value, hint)); + if ui.is_rect_visible(rect) { + let stroke = if open { Stroke::new(2.0, t.accent) } else { Stroke::new(1.0, t.input_border) }; + ui.painter().rect(rect, CornerRadius::same(4), t.input, stroke, egui::StrokeKind::Inside); + let (text, color) = if value.is_empty() { (hint, t.text_dim) } else { (value, t.text) }; + let mut layout = egui::text::LayoutJob::simple_singleline(text.to_owned(), egui::FontId::proportional(15.0), color); + layout.wrap = egui::text::TextWrapping::truncate_at_width((rect.width() - 16.0).max(0.0)); + let galley = ui.painter().layout_job(layout); + let at = egui::pos2(rect.left() + 8.0, rect.center().y - galley.size().y / 2.0); + ui.painter().galley(at, galley, color); + } + response +} + /// The Capture sheet's buttons for the device's position: Go to My Position and Average, or, /// while an average is being taken, what it holds, Use Average and Cancel. fn position_buttons(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context, width: f32) { @@ -2323,6 +2434,103 @@ mod tests { assert!(!app.keep_locating); } + /// On a phone with text fields of its own, a Capture field is a box that opens one when + /// tapped, with the field's value, label and kind; what is typed there fills the field as it + /// changes, and goes with the feature added. An answer for another field, or an earlier + /// opening's close arriving after the field was opened again, fills or ends nothing; text for + /// a field whose layer Capture no longer adds to is said, not kept. + #[test] + fn a_field_typed_into_with_the_systems_text_field_fills_the_feature() { + let ctx = egui::Context::default(); + let mut app = RustGisApp::with_sample(); + let cities = target(&mut app, GeometryType::Point); + run(&mut app, "edit.addField", json!({"layer": cities.id, "name": "note", "type": "text"})); + let index = app.session.map().layer(cities.id).unwrap().dataset.field_index("note").unwrap(); + let asked: std::rc::Rc>> = Default::default(); + let asking = asked.clone(); + app.services.enter_text = Some(Box::new(move |entry| { + asking.borrow_mut().push(entry.clone()); + Ok(()) + })); + set_form(&ctx, Form { shown: Some(cities.instance), values: [("note".to_string(), "Old".to_string())].into(), ..Form::default() }); + // The field's box is beside its label, which says where it is: on a tall window, as the + // field added comes after the layer's own. + let screen = Rect::from_min_size(egui::Pos2::ZERO, Vec2::new(411.0, 2400.0)); + set_sheet(&ctx, Sheet::Capture); + let mut label = None; + for _ in 0..3 { + let output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| chrome(&mut app, ui)); + label = label.or_else(|| { + output.shapes.iter().find_map(|painted| match &painted.shape { + egui::epaint::Shape::Text(text) if text.galley.text() == "note" => Some(text.visual_bounding_rect()), + _ => None, + }) + }); + output.drop_without_applying_deltas(); + } + let label = label.expect("the field's label is drawn"); + // Every frame on the same window: egui finds what a press is on by the frame before it. + let draw = |app: &mut RustGisApp| { + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| chrome(app, ui)) + .drop_without_applying_deltas(); + }; + let tap = |app: &mut RustGisApp| { + draw(app); + let at = egui::pos2(label.left() + 160.0, label.center().y); + for pressed in [true, false] { + let events = vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ]; + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + ctx.run_ui(input, |ui| chrome(app, ui)).drop_without_applying_deltas(); + } + }; + tap(&mut app); + let first = entry_id(cities.instance, index, 0); + assert_eq!( + *asked.borrow(), + vec![TextEntry { id: first.clone(), value: "Old".into(), label: "note".into(), kind: TextKind::Plain, done: "Done".into() }] + ); + assert_eq!(form(&ctx).entering.map(|e| e.id), Some(first.clone())); + // Typed: each change fills the field; another field's answer fills nothing. + app.typed.push(Typed::Text { id: first.clone(), text: "Lan".into() }); + app.typed.push(Typed::Text { id: entry_id(cities.instance + 1, index, 0), text: "Elsewhere".into() }); + draw(&mut app); + assert_eq!(form(&ctx).values.get("note").map(String::as_str), Some("Lan")); + // Opened again before the first one's close arrived: that close ends nothing, and the + // second one's text still fills the field. + tap(&mut app); + let second = entry_id(cities.instance, index, 1); + assert_eq!(asked.borrow().last().map(|e| (e.id.clone(), e.value.clone())), Some((second.clone(), "Lan".into()))); + app.typed.push(Typed::Closed { id: first, failed: None }); + app.typed.push(Typed::Text { id: second.clone(), text: "Lantern\tpost".into() }); + app.typed.push(Typed::Closed { id: second.clone(), failed: None }); + app.typed.push(Typed::Text { id: second, text: "After it closed".into() }); + draw(&mut app); + let state = form(&ctx); + assert!(app.typed.is_empty()); + assert_eq!(state.entering, None); + assert_eq!(state.values.get("note").map(String::as_str), Some("Lantern\tpost")); + assert!(add_point(&mut app, cities.id, &state)); + let layer = app.session.map().layer(cities.id).unwrap(); + assert_eq!(layer.dataset.value(layer.dataset.features.len() - 1, index).to_string(), "Lantern\tpost"); + // Capture adds to another layer while the box is open: what is typed is said, not kept. + tap(&mut app); + let third = asked.borrow().last().unwrap().id.clone(); + let polygons = target(&mut app, GeometryType::Polygon); + let mark = app.session.notice_mark(); + app.typed.push(Typed::Text { id: third, text: "Lost".into() }); + draw(&mut app); + let state = form(&ctx); + assert_eq!(state.shown, Some(polygons.instance)); + assert!(!state.values.values().any(|v| v == "Lost")); + assert_eq!(state.entering, None); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("What was typed for note wasn't kept: Capture no longer adds to its layer"), "{said:?}"); + } + #[test] fn a_photo_taken_goes_with_the_next_feature_or_to_the_feature_being_edited() { let ctx = egui::Context::default(); diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 7514f2312f..8a1a58acd7 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -102,7 +102,11 @@ The form has a field for each of the layer's attributes, and follows the layer's - A date field has a calendar button, with **Today** and, for a date and time, **Now**. Both are in UTC. -While you type in a field, the sheet stays above the soft keyboard. +While you type in a field, the sheet stays above the soft keyboard. On Android, tapping a text or +number field opens Android's own text box above the keyboard, so paste, suggestions, glide typing +and dictation work there. The form shows the value as you type. **Done**, the keyboard's Done key, +Back or a tap outside the box closes it. Text copied in RustGIS goes on Android's clipboard too, +where other apps can paste it. ### Photos From 946df8c8f1c32cdb293092861e5e0c29f544eb74 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 21:54:51 -0600 Subject: [PATCH 2/2] fix(mobile): a copy that can't reach Android's clipboard is said, and an empty error still closes the text box Review of #3001: a refused JNI call for a copy was only logged; it now gives the same notice as a copy Android refused. An exception with an empty message named no reason, so the text box's close was never read. --- .../java/org/rustgis/mobile/MainActivity.java | 3 +- apps/rustgis-mobile/src/android.rs | 4 +- apps/rustgis-mobile/src/phone.rs | 14 +++-- apps/rustgis-mobile/src/shell.rs | 52 ++++++++++++++----- apps/rustgis-web/src/web.rs | 4 +- 5 files changed, 52 insertions(+), 25 deletions(-) diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index b4fc89b80f..276caf1b63 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -486,7 +486,8 @@ public void enterText(final String id, final String value, final String label, f entry.show(); } catch (RuntimeException e) { entry = null; - add("text-closed\t" + id + "\t" + oneField(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage())); + String why = e.getMessage(); + add("text-closed\t" + id + "\t" + oneField(why == null || why.isEmpty() ? e.getClass().getSimpleName() : why)); answered(); } }); diff --git a/apps/rustgis-mobile/src/android.rs b/apps/rustgis-mobile/src/android.rs index 3f3ddefb87..63020207e5 100644 --- a/apps/rustgis-mobile/src/android.rs +++ b/apps/rustgis-mobile/src/android.rs @@ -32,8 +32,8 @@ impl shell::Phone for Phone { Some(5000) } - fn copy_text(&self, text: &str) { - Phone::copy_text(self, text); + fn copy_text(&self, text: &str) -> Result<(), String> { + Phone::copy_text(self, text) } } diff --git a/apps/rustgis-mobile/src/phone.rs b/apps/rustgis-mobile/src/phone.rs index b9608fc0c7..a6f89b2e26 100644 --- a/apps/rustgis-mobile/src/phone.rs +++ b/apps/rustgis-mobile/src/phone.rs @@ -106,16 +106,14 @@ impl Phone { self.java(|env, activity| env.call_method(activity, jni_str!("picking"), jni_sig!(() -> boolean), &[])?.z()).unwrap_or(false) } - /// Puts `text` on the system's clipboard. A refusal is logged: the window's own clipboard - /// still has it. - pub fn copy_text(&self, text: &str) { - let asked = self.java(|env, activity| { + /// Puts `text` on the system's clipboard. An error says why Android couldn't be asked (the + /// window's own clipboard still has the text); a refusal of Android's is reported later, as + /// `copy-failed`. + pub fn copy_text(&self, text: &str) -> Result<(), String> { + self.java(|env, activity| { let text = env.new_string(text)?; env.call_method(activity, jni_str!("copyText"), jni_sig!((text: JString) -> void), &[JValue::Object(&text)])?.v() - }); - if let Err(e) = asked { - log::warn!("{e}"); - } + }) } /// Whether something asked for is still to be reported: the window keeps asking while it is. diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 03c2ef91e9..dfa703ad1d 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -59,9 +59,11 @@ pub trait Phone: Platform { } /// Puts `text`, copied in the window, on the system's clipboard too, where other apps can - /// paste it. The default does nothing: the window's own clipboard keeps it (iOS). - fn copy_text(&self, text: &str) { + /// paste it; an error says why it couldn't be asked. The default does nothing: the window's + /// own clipboard keeps it (iOS). + fn copy_text(&self, text: &str) -> Result<(), String> { let _ = text; + Ok(()) } } @@ -266,13 +268,7 @@ impl App

{ } self.app.typed.push(typed); } - Event::CopyFailed(error) => self.app.session.notify( - i18n::fmt( - "The text copied wasn't put on the system's clipboard, so other apps can't paste it: {error}", - &[("error", &error)], - ), - true, - ), + Event::CopyFailed(error) => copy_failed(&mut self.app, &error), Event::Failed(text) => self.app.session.notify(text, true), } } @@ -672,9 +668,7 @@ impl eframe::App for App

{ }) .collect() }); - for text in copied { - phone.copy_text(&text); - } + copy_out(&mut self.app, phone.as_ref(), copied); } // A second picker asked for while one was up was refused: what the front end kept for // the first is put back, so its file is read as it was asked for. @@ -906,6 +900,24 @@ pub fn run( ) } +/// Puts the text copied in the window on the system's clipboard; a copy the phone couldn't be +/// asked to take is said, as one it refused is ([`Event::CopyFailed`]). +fn copy_out(app: &mut RustGisApp, phone: &impl Phone, copied: Vec) { + for text in copied { + if let Err(error) = phone.copy_text(&text) { + copy_failed(app, &error); + } + } +} + +/// Says that text copied in the window didn't reach the system's clipboard. +fn copy_failed(app: &mut RustGisApp, error: &str) { + app.session.notify( + i18n::fmt("The text copied wasn't put on the system's clipboard, so other apps can't paste it: {error}", &[("error", error)]), + true, + ); +} + #[cfg(test)] mod tests { use super::*; @@ -947,6 +959,9 @@ mod tests { fn idle_look(&self) -> Option { Some(5000) } + fn copy_text(&self, text: &str) -> Result<(), String> { + if text == "refused" { Err("no clipboard".into()) } else { Ok(()) } + } } /// The phone's low-memory warnings reach the front end: the tile cache and the drawing copy @@ -996,6 +1011,19 @@ mod tests { assert_eq!(window.poll, Some(5000)); } + /// A copy the phone couldn't be asked to take is said once; one it took says nothing. + #[test] + fn a_copy_that_cannot_reach_the_clipboard_is_said() { + let mut app = RustGisApp::with_sample(); + let before = app.session.notice_mark(); + copy_out(&mut app, &FakePhone::default(), vec!["taken".into()]); + assert!(app.session.notices_since(before).is_empty()); + copy_out(&mut app, &FakePhone::default(), vec!["refused".into(), "taken".into()]); + let said = app.session.notices_since(before); + assert_eq!(said.len(), 1); + assert!(said[0].text.contains("system's clipboard") && said[0].text.contains("no clipboard")); + } + #[test] fn same_frame_refused_picker_restores_the_options_of_the_admitted_request() { let mut app = RustGisApp::with_sample(); diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 086bd25d8f..5795b04377 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1287,10 +1287,10 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e save_project: None, // The browser's camera isn't asked yet (a phone's shell asks its own). take_photo: None, - // A text field's Paste: the page reads the clipboard (Firefox and Safari show a Paste - // button to confirm, Chrome asks once); only over HTTPS, where the browser offers it. // The browser gives egui's own fields its typing: no text field of its own is needed. enter_text: None, + // A text field's Paste: the page reads the clipboard (Firefox and Safari show a Paste + // button to confirm, Chrome asks once); only over HTTPS, where the browser offers it. read_clipboard: clipboard().map(|clipboard| -> Box>)> { Box::new(move |slot| { let (clipboard, ctx) = (clipboard.clone(), clipboard_ctx.clone());