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
5 changes: 4 additions & 1 deletion apps/rustgis-mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ own was used outside the area) is said, as a later package from the same phone r
| HTTPS trust | The bundled Mozilla roots, not the device's certificates; the session says so once (`rustgis_data::http`) |
| Folders | Settings, app data and the cache are in the app's internal storage, set once at start-up (`rustgis_data::dirs::set_root`) |
| GeoLibre tools, GDAL formats, DuckDB | Not available: a phone can't run their programs. `rustgis_data::RUNS_PROGRAMS` is false on Android and iOS, so no program is looked for, and each place they would appear says so: a file read through GDAL or a DuckDB database is refused with the reason (convert it on a computer), the SQL pane says why it can't query, and the Geoprocessing pane shows a card in place of the GeoLibre tools. Add Data's Database… stays: its PostGIS, MySQL and SQL Server connections need no program. The app is built without the engine's `geolibre` feature |
| 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` |
Expand Down Expand Up @@ -405,12 +406,14 @@ cp parcels.gpkg "$(xcrun simctl get_app_container booted org.rustgis.mobile data
| Folders | Settings, app data and the cache are in `Library/Application Support` |
| Picked copies | Kept in `picked/`, as on Android: data and projects open from their copies and are edited there. The folder is left out of the device's backups (`NSURLIsExcludedFromBackupKey`), as the documents are the user's elsewhere. Remove Unused Copies removes those the project doesn't name, as on Android |
| Plain HTTP | App Transport Security is off for every host (`NSAllowsArbitraryLoads`): a project's tile layers and services may be any `http://` server, not known when the app is built, so a list of exceptions can't name them. The App Review notes say so |
| Memory limits | What `os_proc_available_memory` says is left stands for the app's limit at start, and is asked again for each job; 1.5 GiB where it says nothing. A memory warning drops the tile and drawing caches, as on Android |
| Plugins | None can be installed, and the registry isn't fetched: App Review doesn't let an app download code that adds to what it does (guideline 2.5.2), and a plugin, from the registry or a file, is such code. Each way of installing one says so (`rustgis_plugins::INSTALLS`). A later build could carry plugins reviewed with the app |

`src/ios.rs` is the one module of the app with `unsafe` code beyond Android's `no_mangle`, an
exception to the workspace's rule allowed by `#![expect(unsafe_code)]` on the module: UIKit's
delegates are Objective-C classes made with `objc2`'s `define_class!`, which needs `unsafe impl`,
and a few of UIKit's calls are unsafe in `objc2`. Each block says why it holds.
a few of UIKit's calls are unsafe in `objc2`, and libSystem's `os_proc_available_memory` is
declared there. Each block says why it holds.

Two things winit 0.30 doesn't do on iOS 27 are done in `src/ios.rs`:

Expand Down
74 changes: 73 additions & 1 deletion apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
* empty; time in milliseconds since 1970; elapsed in
* nanoseconds since boot, from getElapsedRealtimeNanos)
* 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
* failed text what went wrong, to show the user
*/
Expand All @@ -50,6 +51,11 @@ public class MainActivity extends NativeActivity {
*/
private static final int MOST_EVENTS = 200_000;
private static final int COPY_BUFFER = 1 << 16;
/**
* The least time between takeEvents' questions whether Android is low on memory: under the 5 s
* an idle window waits between its calls (src/android.rs), so each of those asks.
*/
private static final long MEMORY_LOOK_MILLIS = 4_000;
/** Shared by every activity/copy worker for this process, including activity recreation. */
private static final String COPY_OWNER = java.util.UUID.randomUUID().toString();

Expand Down Expand Up @@ -84,7 +90,7 @@ public class MainActivity extends NativeActivity {
/** The user is being asked for leave to use the location, and hasn't answered. */
private boolean asking;
/** The activity is in sight (between onStart and onStop). */
private boolean started;
private volatile boolean started;
/** A picker for opening is shown and has not answered (written on the main thread). */
private volatile boolean picking;
/** The photo the camera app is writing, until it answers (the main thread's alone). */
Expand All @@ -94,6 +100,9 @@ public class MainActivity extends NativeActivity {
private boolean saveProject;
/** A project is being written back to its document (set on the main thread, cleared by its worker). */
private volatile boolean writing;
/** When takeEvents last asked whether Android is low on memory, and its answer (its thread's alone). */
private long memoryLooked;
private boolean memoryLow;

@Override
protected void onCreate(android.os.Bundle saved) {
Expand Down Expand Up @@ -710,8 +719,71 @@ private void saveFailed(boolean project, String name, String reason) {
add((project ? "project-save-failed\t" : "failed\t") + name + " wasn't saved: " + reason);
}

/**
* What Android allows, in bytes, as "total free": the memory it has (totalMem), and how much
* of it is free before it counts itself low and ends processes (availMem less threshold).
* Empty when it can't say. Called from any thread. (getMemoryClass isn't asked: it bounds the
* Java heap, and the engine's memory is native.)
*/
public String memory() {
android.app.ActivityManager.MemoryInfo info = memoryInfo();
return info == null ? "" : info.totalMem + " " + Math.max(0, info.availMem - info.threshold);
}

private android.app.ActivityManager.MemoryInfo memoryInfo() {
android.app.ActivityManager manager = (android.app.ActivityManager) getSystemService(ACTIVITY_SERVICE);
if (manager == null) {
return null;
}
android.app.ActivityManager.MemoryInfo info = new android.app.ActivityManager.MemoryInfo();
manager.getMemoryInfo(info);
return info;
}

/**
* Android 14 and later tell an app in use nothing when memory runs short (no onLowMemory, no
* "running" trim level), so it is asked while the app is in sight, at most every
* MEMORY_LOOK_MILLIS: each time it is found to have turned low is a "low-memory" event.
*/
private void lookAtMemory() {
long now = android.os.SystemClock.elapsedRealtime();
if (!started || now - memoryLooked < MEMORY_LOOK_MILLIS) {
return;
}
memoryLooked = now;
android.app.ActivityManager.MemoryInfo info = memoryInfo();
boolean low = info != null && info.lowMemory;
if (low && !memoryLow) {
add("low-memory");
}
memoryLow = low;
}

/**
* The warnings Android 13 and earlier give a running app, passed on while it is in sight. Out
* of sight (a track being recorded) it draws no frames to take them, and would drop what it
* is about to draw once back.
*/
@Override
public void onTrimMemory(int level) {

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.

The doc comment above says warnings for an app out of sight "aren't passed on", but this method has no started check. onLowMemory below does have one. Android only sends the TRIM_MEMORY_RUNNING_* levels to an app in use, so the behaviour is probably right, but the comment describes a guard that isn't in the code. Either add the same started check here as in onLowMemory, so both work the same way, or reword the comment to say the levels already limit it.

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.

Fixed in 2b2eb98: onTrimMemory checks started, as onLowMemory does, and the comment says why.

super.onTrimMemory(level);
if (started && (level == TRIM_MEMORY_RUNNING_LOW || level == TRIM_MEMORY_RUNNING_CRITICAL)) {
add("low-memory");
}
}

/** The system as a whole is out of memory (Android 13 and earlier), said while in sight. */
@Override
public void onLowMemory() {
super.onLowMemory();
if (started) {
add("low-memory");
}
}

/** What happened since the last call, oldest first, one event to a line. */
public String takeEvents() {
lookAtMemory();
String why = refusal.getAndSet(null);
if (why != null) {
keepLocatingRefused();
Expand Down
20 changes: 19 additions & 1 deletion apps/rustgis-mobile/src/android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ impl shell::Phone for Phone {
fn picking(&self) -> bool {
Phone::picking(self)
}

/// The activity looks at Android's memory when asked what happened, so an idle window asks.
fn idle_look(&self) -> Option<u64> {
Some(5000)
}
}

/// Points the app's folders (`rustgis_data::dirs`) at the app's own storage: Android has no
Expand All @@ -44,8 +49,21 @@ fn set_folders(app: &AndroidApp) -> Option<std::path::PathBuf> {
fn android_main(android: AndroidApp) {
android_logger::init_once(android_logger::Config::default().with_max_level(log::LevelFilter::Info).with_tag("rustgis"));
let folders = set_folders(&android);
let mut app = shell::front_end(folders.as_deref());
let phone = Phone::new(&android);
// Before anything plans a job: the limits follow what Android allows, with the browser's
// floors. Without the activity's Java half nothing says what that is, and the stand-in
// figure keeps this a phone.
let said = match &phone {
Ok(phone) => phone.plan_memory(),
Err(_) => {
rustgis_engine::data::memory::set_phone(shell::MEMORY_UNSAID, || None);
false
}
};
let mut app = shell::front_end(folders.as_deref());
if !said {
shell::say_memory_unsaid(&mut app);
}
// The app's external files folder (`/sdcard/Android/data/org.rustgis.mobile/files`), where
// `adb push` can put files.
let pushed = shell::pushed(android.external_data_path(), &mut app);
Expand Down
89 changes: 81 additions & 8 deletions apps/rustgis-mobile/src/ios.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//! reference to a delegate, so [`Ios`] holds each one for as long as it is wanted.
// UIKit's delegates are Objective-C classes declared here, and a few of its calls are unsafe;
// each block says why it holds.
#![expect(unsafe_code, reason = "Objective-C classes and the few UIKit calls objc2 marks unsafe; see each SAFETY")]
#![expect(unsafe_code, reason = "Objective-C classes, the few UIKit calls objc2 marks unsafe and one libSystem function; see each SAFETY")]

use crate::shell;
use eframe::egui;
Expand All @@ -24,11 +24,11 @@ use objc2_core_location::{
};
use objc2_foundation::{NSArray, NSError, NSHomeDirectory, NSNotification, NSNotificationCenter, NSString, NSURL, NSValue};
use objc2_ui_kit::{
NSValueUIGeometryExtensions, UIApplication, UIDocumentPickerDelegate, UIDocumentPickerViewController, UIImage, UIImagePickerController,
UIImagePickerControllerDelegate, UIImagePickerControllerInfoKey, UIImagePickerControllerOriginalImage,
UIImagePickerControllerSourceType, UIKeyboardFrameEndUserInfoKey, UIKeyboardWillChangeFrameNotification,
UIKeyboardWillHideNotification, UINavigationControllerDelegate, UIScene, UISceneDelegate, UIViewController, UIWindow,
UIWindowDidBecomeVisibleNotification, UIWindowScene, UIWindowSceneDelegate,
NSValueUIGeometryExtensions, UIApplication, UIApplicationDidReceiveMemoryWarningNotification, UIDocumentPickerDelegate,
UIDocumentPickerViewController, UIImage, UIImagePickerController, UIImagePickerControllerDelegate, UIImagePickerControllerInfoKey,
UIImagePickerControllerOriginalImage, UIImagePickerControllerSourceType, UIKeyboardFrameEndUserInfoKey,
UIKeyboardWillChangeFrameNotification, UIKeyboardWillHideNotification, UINavigationControllerDelegate, UIScene, UISceneDelegate,
UIViewController, UIWindow, UIWindowDidBecomeVisibleNotification, UIWindowScene, UIWindowSceneDelegate,
};
use objc2_uniform_type_identifiers::UTTypeItem;
use rustgis_engine::platform::{Event, Fix, Platform};
Expand Down Expand Up @@ -745,6 +745,68 @@ impl KeyboardObserver {
}
}

define_class!(
// SAFETY: NSObject has no subclassing requirements, and this class doesn't implement Drop.
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "RustGISMemoryObserver"]
#[ivars = Arc<Shared>]
struct MemoryObserver;

impl MemoryObserver {
#[unsafe(method(memoryWarning:))]
fn warned(&self, _notification: &NSNotification) {
self.ivars().add(Event::LowMemory);
wake(self.mtm());
}
}
);

impl MemoryObserver {
fn new(mtm: MainThreadMarker, shared: Arc<Shared>) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(shared);
// SAFETY: NSObject's `init` on a freshly allocated object.
let this: Retained<Self> = unsafe { msg_send![super(this), init] };
let center = NSNotificationCenter::defaultCenter();
// SAFETY: the selector is this class's own method, taking the notification; the observer
// is removed in `Ios`'s Drop, and lives as long as it.
unsafe {
center.addObserver_selector_name_object(
&this,
sel!(memoryWarning:),
Some(UIApplicationDidReceiveMemoryWarningNotification),
None,
);
}
this
}
}

// SAFETY: libSystem's function (`<os/proc.h>`, iOS 13 and later): no arguments, any thread.
unsafe extern "C" {
/// The bytes the app may still take before iOS ends it for passing its limit; 0 where iOS
/// doesn't say (and once the app is at its limit).
safe fn os_proc_available_memory() -> usize;
}

/// Tells the engine what iOS allows (`rustgis_data::memory::set_phone`): what the system says is
/// left at start, while the app holds little, stands for its limit, and is asked again each time a
/// job plans. Where it says nothing at start, [`shell::MEMORY_UNSAID`] stands in, with nothing
/// known to be free. Returns whether iOS said.
fn plan_memory() -> bool {
let left = || os_proc_available_memory() as u64;
let start = left();
let taken = if start > 0 {
rustgis_engine::data::memory::set_phone(start, move || Some(left()))
} else {
rustgis_engine::data::memory::set_phone(shell::MEMORY_UNSAID, || None)
};
if !taken {
log::warn!("the memory limits were read before iOS's were set");
}
start > 0
}

thread_local! {
/// The app's window scene, once UIKit has connected it ([`SceneDelegate`]).
static SCENE: RefCell<Option<Retained<UIWindowScene>>> = const { RefCell::new(None) };
Expand Down Expand Up @@ -950,6 +1012,7 @@ pub struct Ios {
location: Retained<CLLocationManager>,
located: Retained<LocationDelegate>,
keyboard: Retained<KeyboardObserver>,
memory: Retained<MemoryObserver>,
/// A file to save being written, until its export picker shows.
saving: RefCell<Option<Saving>>,
/// The picker last presented, and when, until it is seen shown or declined
Expand All @@ -973,8 +1036,12 @@ struct Saving {

impl Drop for Ios {
fn drop(&mut self) {
// SAFETY: removes the observer `KeyboardObserver::new` added.
unsafe { NSNotificationCenter::defaultCenter().removeObserver(&self.keyboard) };
let center = NSNotificationCenter::defaultCenter();
// SAFETY: removes the observers `KeyboardObserver::new` and `MemoryObserver::new` added.
unsafe {
center.removeObserver(&self.keyboard);
center.removeObserver(&self.memory);
}
}
}

Expand All @@ -994,6 +1061,7 @@ impl Ios {
Ios {
mtm,
writing_back: Arc::default(),
memory: MemoryObserver::new(mtm, shared.clone()),
shared,
folders,
picker: RefCell::new(None),
Expand Down Expand Up @@ -1345,7 +1413,12 @@ pub fn main() {
std::mem::forget(WindowWatcher::start(mtm));
let folders = folders();
let made = std::fs::create_dir_all(&folders.support).is_ok() && rustgis_engine::data::dirs::set_root(folders.support.clone());
// Before anything plans a job.
let said = plan_memory();
let mut app = shell::front_end(made.then_some(folders.support.as_path()));
if !said {
shell::say_memory_unsaid(&mut app);
}
// The app's Documents folder: files put there from a computer (Finder, `xcrun simctl`) are
// opened once the window is up, as on Android.
let documents = PathBuf::from(NSHomeDirectory().to_string()).join("Documents");
Expand Down
Loading
Loading