Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion apps/rustgis-mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
214 changes: 214 additions & 0 deletions apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -444,6 +462,198 @@ 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;
String why = e.getMessage();
add("text-closed\t" + id + "\t" + oneField(why == null || why.isEmpty() ? e.getClass().getSimpleName() : why));
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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This English text reaches the user through copy_failed in a notice, and Java can't use tl!, so it stays English in every language. Existing Java messages (such as "This device has no file picker") already do this, so the PR follows a precedent rather than adding a new gap. A cleaner fix is to send a short code such as no-clipboard and map it to a translated string on the Rust side in shell.rs.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

} 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()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Twin of the empty-message case fixed in enterText (a0b9736): here an exception whose message is "" (not null) passes through as an empty reason, so copy-failed\t reaches Rust. Event::parse accepts it, and the user gets the notice "...system's clipboard...: " with a blank reason. The notice still fires, so nothing is lost; this is the wording of the reason only. Treating an empty message like a missing one matches the enterText fix:

Suggested change
add("copy-failed\t" + oneField(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
add("copy-failed\t" + oneField(e.getMessage() == null || e.getMessage().isEmpty() ? e.getClass().getSimpleName() : e.getMessage()));

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

} 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(() -> {
Expand Down Expand Up @@ -790,6 +1000,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()) {
Expand Down
8 changes: 6 additions & 2 deletions apps/rustgis-mobile/src/android.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -31,6 +31,10 @@ impl shell::Phone for Phone {
fn idle_look(&self) -> Option<u64> {
Some(5000)
}

fn copy_text(&self, text: &str) -> Result<(), String> {
Phone::copy_text(self, text)
}
}

/// Points the app's folders (`rustgis_data::dirs`) at the app's own storage: Android has no
Expand Down
38 changes: 35 additions & 3 deletions apps/rustgis-mobile/src/phone.rs
Original file line number Diff line number Diff line change
@@ -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`.
Expand All @@ -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;
Expand Down Expand Up @@ -105,6 +106,16 @@ 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. 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()
})
}

/// 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)
Expand Down Expand Up @@ -177,6 +188,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<Event> {
let lines = self.java(|env, activity| {
let taken = env.call_method(activity, jni_str!("takeEvents"), jni_sig!(() -> JString), &[])?.l()?;
Expand Down
Loading
Loading