diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 49a64f97c9..52f2fad9ce 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -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` | @@ -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`: diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index 5e25d88bac..3b60bffc18 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -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 */ @@ -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(); @@ -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). */ @@ -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) { @@ -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) { + 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(); diff --git a/apps/rustgis-mobile/src/android.rs b/apps/rustgis-mobile/src/android.rs index 874fdd1bda..b916d3e8f5 100644 --- a/apps/rustgis-mobile/src/android.rs +++ b/apps/rustgis-mobile/src/android.rs @@ -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 { + Some(5000) + } } /// Points the app's folders (`rustgis_data::dirs`) at the app's own storage: Android has no @@ -44,8 +49,21 @@ fn set_folders(app: &AndroidApp) -> Option { 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); diff --git a/apps/rustgis-mobile/src/ios.rs b/apps/rustgis-mobile/src/ios.rs index 448ba5707c..44b390c675 100644 --- a/apps/rustgis-mobile/src/ios.rs +++ b/apps/rustgis-mobile/src/ios.rs @@ -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; @@ -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}; @@ -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] + 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) -> Retained { + let this = Self::alloc(mtm).set_ivars(shared); + // SAFETY: NSObject's `init` on a freshly allocated object. + let this: Retained = 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 (``, 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>> = const { RefCell::new(None) }; @@ -950,6 +1012,7 @@ pub struct Ios { location: Retained, located: Retained, keyboard: Retained, + memory: Retained, /// A file to save being written, until its export picker shows. saving: RefCell>, /// The picker last presented, and when, until it is seen shown or declined @@ -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); + } } } @@ -994,6 +1061,7 @@ impl Ios { Ios { mtm, writing_back: Arc::default(), + memory: MemoryObserver::new(mtm, shared.clone()), shared, folders, picker: RefCell::new(None), @@ -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"); diff --git a/apps/rustgis-mobile/src/phone.rs b/apps/rustgis-mobile/src/phone.rs index e849451450..bc1322c768 100644 --- a/apps/rustgis-mobile/src/phone.rs +++ b/apps/rustgis-mobile/src/phone.rs @@ -4,17 +4,19 @@ //! Rust calls Java and never the other way: what happened is collected with `takeEvents`, so the //! library exports nothing but `android_main`. +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_ui_egui::i18n; use std::cell::RefCell; +use std::sync::Arc; use winit::platform::android::activity::AndroidApp; /// The phone, through its activity. pub struct Phone { - activity: Global>, + activity: Arc>>, /// Why the activity last couldn't be asked what happened, until it can be again: said once, /// not every frame. unreachable: RefCell>, @@ -40,7 +42,7 @@ impl Phone { }) }) .map_err(|e| i18n::fmt("Android's Java side can't be reached: {error}", &[("error", &e.to_string())]))?; - let phone = Phone { activity, unreachable: RefCell::new(None) }; + let phone = Phone { activity: Arc::new(activity), unreachable: RefCell::new(None) }; let owner = phone.java(|env, activity| { let token = env.call_method(activity, jni_str!("copyOwner"), jni_sig!(() -> JString), &[])?.l()?; env.cast_local::(token)?.try_to_string(env) @@ -49,6 +51,19 @@ impl Phone { Ok(phone) } + /// Tells the engine what Android allows (`rustgis_data::memory::set_phone`): the memory it + /// has, and, asked again each time a job plans, what is free of it. Where Android doesn't say + /// at start, [`shell::MEMORY_UNSAID`] stands in. Returns whether Android said. + pub fn plan_memory(&self) -> bool { + let activity = self.activity.clone(); + let total = memory(&activity).map(|(total, _)| total).filter(|total| *total > 0); + let free = move || memory(&activity).map(|(_, free)| free); + if !rustgis_engine::data::memory::set_phone(total.unwrap_or(shell::MEMORY_UNSAID), free) { + log::warn!("the memory limits were read before Android's were set"); + } + total.is_some() + } + /// Runs `call` with the Java environment and the activity, on this thread. fn java(&self, call: impl FnOnce(&mut jni::Env, &JObject) -> jni::errors::Result) -> Result { JavaVM::singleton() @@ -96,6 +111,21 @@ impl Phone { } } +/// The memory Android has and what is free of it (`MainActivity.memory`), from any thread; `None` +/// when it can't say. +fn memory(activity: &JObject) -> Option<(u64, u64)> { + let text = JavaVM::singleton() + .and_then(|vm| { + vm.attach_current_thread(|env| -> jni::errors::Result { + let said = env.call_method(activity, jni_str!("memory"), jni_sig!(() -> JString), &[])?.l()?; + env.cast_local::(said)?.try_to_string(env) + }) + }) + .ok()?; + let (total, free) = text.split_once(' ')?; + Some((total.parse().ok()?, free.parse().ok()?)) +} + impl Platform for Phone { fn pick_files(&self, purpose: &str) -> Result<(), String> { self.java(|env, activity| { diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 6875b7e5c2..095dec630f 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -15,6 +15,15 @@ use std::sync::{Arc, Mutex}; /// it: long enough for the keyboard to finish closing. const KEYBOARD_SETTLES: std::time::Duration = std::time::Duration::from_millis(1500); +/// The memory the limits plan with where a phone's system doesn't say what it allows: 1.5 GiB, +/// what a small phone can give an app. +pub const MEMORY_UNSAID: u64 = 1536 << 20; + +/// Says, in the window, that the limits plan with [`MEMORY_UNSAID`]. +pub fn say_memory_unsaid(app: &mut RustGisApp) { + app.session.warn(tl!("This device didn't say how much memory RustGIS may use, so its limits plan for 1.5 GiB.")); +} + /// What the shell asks of a phone beyond [`Platform`]. pub trait Phone: Platform { /// The room the system's bars, a camera cutout and the soft keyboard take at the window's @@ -36,6 +45,13 @@ pub trait Phone: Platform { self.busy() } + /// How often (milliseconds) a window with nothing else to look for looks again, for a phone + /// that reports only when asked and can't wake the window (Android's memory). `None`, the + /// default: the phone wakes it. + fn idle_look(&self) -> Option { + None + } + /// Whether the soft keyboard's Return was pressed since the last frame, where the system /// passes it on as no key egui knows (iOS). The shell gives egui an Enter for it. fn take_return(&self) -> bool { @@ -236,6 +252,7 @@ impl App

{ self.locating = false; self.app.position = None; } + Event::LowMemory => self.app.release_memory(), Event::Failed(text) => self.app.session.notify(text, true), } } @@ -298,7 +315,7 @@ impl App

{ } else if self.locating { Some(1000) } else { - None + phone.idle_look() }; } @@ -628,7 +645,7 @@ impl eframe::App for App

{ } // Something of the phone's is still to arrive (a picked file, a position): look again. // A picker or a save asked for in this frame counts too: the poll was set before it. - if self.poll.is_none() && self.phone.as_ref().is_some_and(|phone| phone.busy()) { + if self.poll.is_none_or(|wait| wait > 250) && self.phone.as_ref().is_some_and(|phone| phone.busy()) { self.poll = Some(250); } if let Some(wait) = self.poll { @@ -855,8 +872,9 @@ mod tests { use serde_json::{Value, json}; use std::cell::Cell; + /// A phone that is busy once asked for a file, and reports the events put in it. #[derive(Default)] - struct FakePhone(Cell); + struct FakePhone(Cell, RefCell>); impl Platform for FakePhone { fn pick_files(&self, _: &str) -> Result<(), String> { self.0.set(true); @@ -875,7 +893,7 @@ mod tests { Ok(()) } fn take_events(&self) -> Vec { - Vec::new() + self.1.take() } } impl Phone for FakePhone { @@ -886,6 +904,56 @@ mod tests { fn busy(&self) -> bool { self.0.get() } + fn idle_look(&self) -> Option { + Some(5000) + } + } + + /// The phone's low-memory warnings reach the front end: the tile cache and the drawing copy + /// of a layer switched off go (a drawn layer's stays), it is said once however often it + /// comes, and an idle window looks again as often as the phone asks. + #[test] + fn a_low_memory_warning_drops_caches_and_is_said_once() { + use rustgis_engine::render::rustgis_tiles::cache; + + let mut app = RustGisApp::with_sample(); + let layers = &mut app.session.map_mut().layers; + assert!(layers.len() >= 2); + layers[0].visible = false; + layers[1].visible = true; + for layer in layers.iter_mut().take(2) { + layer.projected(); + assert!(layer.is_cached("mercator")); + } + let (clears, mark) = (cache::clears(), app.session.notice_mark()); + let phone = Rc::new(FakePhone::default()); + phone.1.borrow_mut().extend([Event::LowMemory, Event::LowMemory]); + let mut window = App { + app, + pushed: Vec::new(), + poll: None, + locating: false, + keeping: false, + keyboard: None, + typing: None, + bars_light: None, + phone: Some(phone), + inbox: Inbox::default(), + refusals: Refusals::default(), + asked: Asked::default(), + kept: Rc::default(), + refused_picker: Rc::default(), + waiting: Vec::new(), + problems: Problems::default(), + reading: Arc::default(), + }; + window.take_phone_events(&egui::Context::default(), &mut egui::RawInput::default()); + assert!(cache::clears() > clears); + let layers = &window.app.session.map().layers; + assert_eq!([layers[0].is_cached("mercator"), layers[1].is_cached("mercator")], [false, true]); + let said = window.app.session.notices_since(mark).iter().filter(|n| n.text.contains("low on memory")).count(); + assert_eq!(said, 1); + assert_eq!(window.poll, Some(5000)); } #[test] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 384218bd9e..c9eb5a6321 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1618,8 +1618,11 @@ fn union_all<'a>(polys: impl IntoIterator>) -> Mult const MAX_BUFFER_VERTICES: usize = 2_000_000; /// Retained ordinary output/selector storage, separate from overlay complexity. Temporary /// geometry on each worker and the already loaded input are additional to this allowance. The -/// browser's budget, and the fewest bytes [`max_buffer_bytes`] allows on the desktop. -const MAX_BUFFER_BYTES: usize = if cfg!(target_arch = "wasm32") { 128 << 20 } else { 512 << 20 }; +/// browser's budget, and the fewest bytes [`max_buffer_bytes`] allows on the desktop (a phone: +/// [`BROWSER_BUFFER_BYTES`]). +const MAX_BUFFER_BYTES: usize = if cfg!(target_arch = "wasm32") { BROWSER_BUFFER_BYTES } else { 512 << 20 }; +/// The budget in the browser, and the fewest bytes [`max_buffer_bytes`] allows on a phone. +const BROWSER_BUFFER_BYTES: usize = 128 << 20; /// The most bytes [`max_buffer_bytes`] allows, however much memory the computer has. const BUFFER_BYTES_CEILING: usize = 8 << 30; /// Drain results regularly instead of keeping a second whole-layer result array. @@ -1630,10 +1633,12 @@ const MAX_SELECTOR_CHECKS: usize = 50_000_000; const BUFFER_STORAGE_ERROR: &str = "Buffer output or distance selectors exceed their memory budget; select fewer features"; /// Buffer's retained-storage budget on this computer: on the desktop a quarter of its memory, from -/// [`MAX_BUFFER_BYTES`] up to [`BUFFER_BYTES_CEILING`] (#1291 step 2); fixed in the browser. +/// [`MAX_BUFFER_BYTES`] (a phone: [`BROWSER_BUFFER_BYTES`]) up to [`BUFFER_BYTES_CEILING`] +/// (#1291 step 2); fixed in the browser. /// Less once RustGIS holds more than half the memory, never below the floor ([`rustgis_data::memory::planned`], #2431). pub fn max_buffer_bytes() -> usize { - rustgis_data::memory::planned(MAX_BUFFER_BYTES, BUFFER_BYTES_CEILING, 1) + let floor = if rustgis_data::memory::on_phone() { BROWSER_BUFFER_BYTES } else { MAX_BUFFER_BYTES }; + rustgis_data::memory::planned(floor, BUFFER_BYTES_CEILING, 1) } /// [`BUFFER_STORAGE_ERROR`] with the budget it ran out of, so a run refused here but not on a diff --git a/crates/analysis/tests/phone_memory.rs b/crates/analysis/tests/phone_memory.rs new file mode 100644 index 0000000000..d4cc51082f --- /dev/null +++ b/crates/analysis/tests/phone_memory.rs @@ -0,0 +1,41 @@ +//! The memory limits of a phone (`rustgis_data::memory::set_phone`), in a test binary of its own: +//! the setting is the whole process's. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use rustgis_analysis::max_buffer_bytes; +use rustgis_analysis::warp::Grid; +use rustgis_data::memory; +use rustgis_data::raster::{self, Crs}; + +static FREE: AtomicU64 = AtomicU64::new(1 << 30); + +#[test] +fn a_phones_limits_follow_what_its_system_allows_and_has_free() { + let allowed: u64 = 1536 << 20; + assert!(memory::set_phone(allowed, || Some(FREE.load(Ordering::Relaxed)))); + assert!(!memory::set_phone(8 << 30, || None), "said once"); + assert_eq!((memory::physical(), memory::source()), (Some(allowed), "phone")); + + // 1 GiB free: a quarter of what is allowed, where the desktop's floors would ask for more. + assert!(raster::SAMPLES_FLOOR as u64 * 8 > allowed / 4); + assert_eq!(raster::max_samples() as u64 * 8, allowed / 4); + assert_eq!(max_buffer_bytes() as u64, allowed / 4); + assert_eq!(memory::undo_history() as u64, allowed / 4); + + // 300 MiB free, asked again: little is left past what is kept for drawing, so the limits are + // the browser's floors. + FREE.store(300 << 20, Ordering::Relaxed); + assert_eq!(memory::available(), Some(300 << 20)); + assert_eq!(raster::max_samples(), raster::BROWSER_SAMPLES); + assert_eq!(max_buffer_bytes(), 128 << 20); + assert_eq!(memory::undo_history(), 256 << 20, "Undo follows what is free too"); + assert_eq!(memory::thread_scratch(), memory::SCRATCH_FLOOR); + + // A grid of 64 million cells, within the desktop's floor, is refused with the way out. + let crs = Crs::from_epsg(3857).unwrap(); + let grid = |cell: f64| Grid::snapped(crs, [0.0, 0.0, 8000.0, 8000.0], (cell, cell), (0.0, 0.0)); + let refused = grid(1.0).unwrap_err(); + assert!(refused.ends_with("more than this computer's 32000000: give a larger cellSize or a smaller extent"), "{refused}"); + assert_eq!(grid(2.0).map(|g| (g.width, g.height)), Ok((4000, 4000))); +} diff --git a/crates/data/src/memory.rs b/crates/data/src/memory.rs index e673a09856..28eb675ed6 100644 --- a/crates/data/src/memory.rs +++ b/crates/data/src/memory.rs @@ -7,6 +7,9 @@ //! asked for; [`scaled`] takes it as an argument, so tests pass fixed amounts. Most limits plan for //! what is left once the process holds more than half the memory ([`planned`], #2431 fix 3), so //! they can be lower later in a session, never below their floors. +//! +//! A phone ([`set_phone`]) plans the same way from what its system allows, which its app says in +//! place of the memory read here, and takes the browser's floors where those are lower. use std::sync::atomic::{AtomicU64, Ordering}; @@ -22,13 +25,15 @@ pub const SHARE: u64 = 4; /// On the desktop, [`OVERRIDE`] set to a positive whole number of bytes replaces the memory read, /// a container's limit included, for tests and to reproduce a smaller computer; any other value is /// ignored. [`source`] says which one was used. +/// +/// On a phone it is the figure its app gave ([`set_phone`]), unless [`OVERRIDE`] is set. pub fn physical() -> Option { reading().0 } /// Where [`physical`]'s figure came from: `"override"` ([`OVERRIDE`]), `"container"` (a /// control-group limit, a container's or a service's such as systemd's `MemoryMax`, lower than -/// the computer's memory), `"computer"`, or `"unknown"` (the browser, +/// the computer's memory), `"computer"`, `"phone"` ([`set_phone`]), or `"unknown"` (the browser, /// a fuzzing build, or memory that couldn't be read), so a leftover override doesn't change the /// limits unnoticed. pub fn source() -> &'static str { @@ -52,6 +57,44 @@ fn reading() -> (Option, &'static str) { } } +/// What a phone's system allows RustGIS ([`set_phone`]). +#[cfg(not(target_arch = "wasm32"))] +struct Phone { + /// The bytes it plans with, in place of the device's memory. + allowed: u64, + /// The bytes free now; `None` when the system can't say. + free: Box Option + Send + Sync>, +} + +/// The phone's allowance, or that there is none: settled by [`set_phone`] or by the first read of +/// the memory, whichever comes first. +#[cfg(not(target_arch = "wasm32"))] +static PHONE: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// Says RustGIS runs on a phone, for the phone app to call once, before anything asks for a limit. +/// The limits then plan with `allowed` bytes in place of the memory read here ([`physical`]): +/// what the system lets the app use where it says (iOS), else the device's memory (Android). They +/// plan for no more than `free` says is free each time it is asked +/// ([`available`]; any thread asks). Where the browser's floor is lower than the desktop's, they +/// take it ([`on_phone`]). Returns whether it took: not for no bytes, a second call, or once the +/// memory has been read. +#[cfg(not(target_arch = "wasm32"))] +pub fn set_phone(allowed: u64, free: impl Fn() -> Option + Send + Sync + 'static) -> bool { + allowed > 0 && PHONE.set(Some(Phone { allowed, free: Box::new(free) })).is_ok() +} + +/// Whether a phone's app said what its system allows (`set_phone`, which the browser lacks). +pub fn on_phone() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + matches!(PHONE.get(), Some(Some(_))) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + /// The environment variable that replaces the memory [`physical`] reads. pub const OVERRIDE: &str = "RUSTGIS_MEMORY_BYTES"; @@ -61,13 +104,19 @@ fn overridden(value: Option<&str>) -> Option { value?.trim().parse::().ok().filter(|m| *m > 0) } -/// The memory to plan for: the override when it is set, else physical memory, or a control-group -/// limit (a container's, or a service's such as systemd's `MemoryMax`) when that is lower. +/// The memory to plan for: the override when it is set, else what a phone's system allows, else +/// physical memory, or a control-group limit (a container's, or a service's such as systemd's +/// `MemoryMax`) when that is lower. #[cfg(all(not(fuzzing), not(target_arch = "wasm32")))] fn read() -> (Option, &'static str) { + // Settled first, so a phone's app can't say what it allows once this has read without it. + let phone = PHONE.get_or_init(|| None); if let Some(m) = overridden(std::env::var(OVERRIDE).ok().as_deref()) { return (Some(m), "override"); } + if let Some(phone) = phone { + return (Some(phone.allowed), "phone"); + } let Some(mut s) = sysinfo::System::new().ok() else { return (None, "unknown") }; s.refresh_memory_specifics(sysinfo::MemoryRefreshKind::nothing().with_ram()); let Some(total) = Some(s.total_memory()).filter(|m| *m > 0) else { return (None, "unknown") }; @@ -94,16 +143,26 @@ pub const SCRATCH_CEILING: usize = 4 << 30; /// The scratch memory work's threads (a tool's, a GeoTIFF read's) may take together beyond one /// thread's: on the desktop a sixteenth of the computer's memory, on top of the quarter the input /// and output limits plan for, from [`SCRATCH_FLOOR`] up to [`SCRATCH_CEILING`] (#1291 step 2). It -/// bounds the threads a high thread setting starts ([`crate::threads`]). +/// bounds the threads a high thread setting starts ([`crate::threads`]). A phone ([`on_phone`]) +/// takes [`SCRATCH_FLOOR`], as the browser does: this is asked while drawing, too often to ask the +/// system what is free, and a phone's whole figure isn't free to take. pub fn thread_scratch() -> usize { + if on_phone() { + return SCRATCH_FLOOR; + } scaled(physical().map(|m| m / 4), SCRATCH_FLOOR, SCRATCH_CEILING, 1) } /// Feature storage kept only by undo and redo snapshots. On the desktop the history can use /// a quarter of physical memory, from 256 MiB up to 4 GiB. The browser and unknown hosts use -/// the floor. +/// the floor. A phone ([`on_phone`]) plans it from what is free too ([`planned`]), when a +/// session starts. pub fn undo_history() -> usize { - scaled(physical(), 256 << 20, usize::try_from(4_u64 << 30).unwrap_or(usize::MAX), 1) + let (floor, ceiling) = (256 << 20, usize::try_from(4_u64 << 30).unwrap_or(usize::MAX)); + if on_phone() { + return planned(floor, ceiling, 1); + } + scaled(physical(), floor, ceiling, 1) } /// The memory RustGIS plans to hold on a computer with `memory` bytes (`None`: not known), what the @@ -160,12 +219,14 @@ pub fn margin(memory: u64) -> u64 { /// /// Memory RustGIS freed that its allocator keeps for reuse still counts as used here. On macOS /// the system counts pages programs are using as available too, so this rarely bounds anything -/// there. +/// there. On a phone it is what the app says its system has free ([`set_phone`]). pub fn available() -> Option { #[cfg(all(not(fuzzing), not(target_arch = "wasm32")))] { - if source() != "computer" { - return None; + match source() { + "computer" => {} + "phone" => return PHONE.get().and_then(Option::as_ref).and_then(|phone| (phone.free)()), + _ => return None, } let mut s = sysinfo::System::new().ok()?; s.refresh_memory_specifics(sysinfo::MemoryRefreshKind::nothing().with_ram()); @@ -313,5 +374,9 @@ mod tests { let first = physical(); assert!(first.is_none_or(|m| m >= 64 << 20), "{first:?}"); assert_eq!(physical(), first); + // Once read, a phone's allowance comes too late, and changes nothing. + assert!(!set_phone(1 << 30, || None)); + assert!(!on_phone()); + assert_eq!(physical(), first); } } diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 49232a0828..5016eb5ec8 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -87,7 +87,7 @@ fn no_memory(w: usize, h: usize) -> DataError { /// overview is chosen. pub const BROWSER_SAMPLES: usize = 32_000_000; /// The fewest samples [`max_samples`] allows: 120 million (480 MB) on the desktop, and -/// [`BROWSER_SAMPLES`] (its limit) in the browser. +/// [`BROWSER_SAMPLES`] (its limit) in the browser. A phone takes the browser's ([`samples_floor`]). #[cfg(not(target_arch = "wasm32"))] pub const SAMPLES_FLOOR: usize = 120_000_000; #[cfg(target_arch = "wasm32")] @@ -95,12 +95,18 @@ pub const SAMPLES_FLOOR: usize = BROWSER_SAMPLES; /// The most [`max_samples`] allows, however much memory the computer has: a billion (4 GB). pub const SAMPLES_CEILING: usize = 1_000_000_000; +/// The fewest samples [`max_samples`] allows here: [`SAMPLES_FLOOR`], or on a phone +/// ([`crate::memory::on_phone`]) the browser's [`BROWSER_SAMPLES`]. +pub fn samples_floor() -> usize { + if crate::memory::on_phone() { BROWSER_SAMPLES } else { SAMPLES_FLOOR } +} + /// Most samples (pixels × bands) held in memory: on the desktop, as many as a quarter of the /// computer's memory holds at 8 bytes each (a sample takes 4, and reading briefly needs about -/// twice that), from [`SAMPLES_FLOOR`] up to [`SAMPLES_CEILING`] (#1291 step 2, #1318). +/// twice that), from [`samples_floor`] up to [`SAMPLES_CEILING`] (#1291 step 2, #1318). /// Less once RustGIS holds more than half the memory, never below the floor ([`crate::memory::planned`], #2431). pub fn max_samples() -> usize { - crate::memory::planned(SAMPLES_FLOOR, SAMPLES_CEILING, 8) + crate::memory::planned(samples_floor(), SAMPLES_CEILING, 8) } // Shared by the elevation readers ([`hgt`], [`dted`]) and pictures read at a step. diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index b254554922..e2fc3b9f66 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -132,7 +132,7 @@ impl Shape { } /// The most samples a cell-by-cell command reads whole of a file, and holds of a result: -/// [`rustgis_data::raster::SAMPLES_FLOOR`], what any desktop reads whole, or under test what +/// [`rustgis_data::raster::samples_floor`], what any desktop (or any phone) reads whole, or under test what /// [`BLOCKS_PAST`] sets on this thread. Not the computer's own limit, which follows what it has /// free: the permission check and the run decide the same way however that changes between them. fn whole_limit() -> usize { @@ -140,7 +140,7 @@ fn whole_limit() -> usize { if let Some(max) = BLOCKS_PAST.with(std::cell::Cell::get) { return max; } - rustgis_data::raster::SAMPLES_FLOOR + rustgis_data::raster::samples_floor() } #[cfg(test)] @@ -263,7 +263,7 @@ pub(crate) fn affordable(need: u64) -> bool { return need <= max; } let budget = memory::share(memory::physical(), memory::held(), memory::available()); - need <= budget.unwrap_or((rustgis_data::raster::SAMPLES_FLOOR as u64).saturating_mul(4)) + need <= budget.unwrap_or((rustgis_data::raster::samples_floor() as u64).saturating_mul(4)) } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6d01ab221f..07a6d66ec1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1841,6 +1841,17 @@ impl Session { self.project.map_mut() } + /// Drops what is kept only to draw again sooner, for a system short of memory (a phone says + /// so): the tile and drawing caches ([`render::release_memory`]), and the drawing copies of + /// the layers switched off. Each is made or fetched again when next wanted; layers, results + /// and Undo history are kept. + pub fn release_memory(&mut self) { + crate::render::release_memory(); + for layer in self.project.maps.iter_mut().flat_map(|map| &mut map.layers).filter(|layer| !layer.visible) { + layer.clear_cache(); + } + } + /// Whether a Zarr layer on the active map that follows the time slider is waiting for its /// step to be read off the frame ([`Session::zarr_off_frame`]): playing holds its next step. pub fn zarr_waiting(&self) -> bool { diff --git a/crates/engine/src/platform.rs b/crates/engine/src/platform.rs index a8296bd0cb..5fb9a8d001 100644 --- a/crates/engine/src/platform.rs +++ b/crates/engine/src/platform.rs @@ -113,6 +113,8 @@ pub enum Event { /// Positioning ended without [`Platform::locate`] turning it off (leave refused or taken /// away, no way to find a position): the reason comes as an [`Event::Failed`]. Stopped, + /// The system is short of memory: what can be made again is to be dropped. + LowMemory, /// Something went wrong: the text is for the user. Failed(String), } @@ -120,9 +122,9 @@ 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`, `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`, `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 /// `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 { @@ -148,6 +150,7 @@ impl Event { ["ended", purpose] => Event::Ended { purpose: purpose.to_string() }, ["photo", name, path] if !path.is_empty() => Event::Photo { name: name.to_string(), path: PathBuf::from(path) }, ["stopped"] => Event::Stopped, + ["low-memory"] => Event::LowMemory, // 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"))), @@ -304,6 +307,7 @@ mod tests { Event::Photo { name: "photo-1.jpg".into(), path: PathBuf::from("/data/photos/photo-1.jpg") } ); assert_eq!(Event::parse("stopped"), Event::Stopped); + assert_eq!(Event::parse("low-memory"), Event::LowMemory); assert_eq!( Event::parse("position\t-83.92\t35.96\t4.5"), Event::Position(Fix { lon: -83.92, lat: 35.96, accuracy: Some(4.5), time: None, elapsed_realtime_nanos: None }) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 3cb95fe74e..5b64f115d9 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -287,10 +287,10 @@ fn with_pictures(f: impl FnOnce(&mut Vec) -> R) -> R { PICTURES.with_borrow_mut(f) } -/// Forgets the pictures kept on this test thread, for a test of what else a frame keeps. -#[cfg(test)] -pub(crate) fn clear() { - PICTURES.take(); +/// Forgets the pictures kept between frames ([`crate::release_memory`]; in a test, those of its +/// thread). +pub(crate) fn release() { + with_pictures(|kept| *kept = Vec::new()); } /// How a frame draws, from [`plan`]. diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs index bf7f60389d..c39c9864e9 100644 --- a/crates/render/src/layer_meshes.rs +++ b/crates/render/src/layer_meshes.rs @@ -111,6 +111,8 @@ struct Meshes { /// The scenes being drawn ([`Scene`]), by number, with the clock when each began. drawing: Vec<(u64, u64)>, scenes: u64, + /// The clock at the last [`release`]. + released: u64, } impl Meshes { @@ -147,7 +149,8 @@ pub(crate) fn bytes_of(cmds: &[DrawCmd]) -> usize { /// The kept meshes, shared by the threads that draw scenes (the UI's and the one that draws a /// view once it settles). #[cfg(not(test))] -static MESHES: std::sync::Mutex = std::sync::Mutex::new(Meshes { kept: Vec::new(), clock: 0, drawing: Vec::new(), scenes: 0 }); +static MESHES: std::sync::Mutex = + std::sync::Mutex::new(Meshes { kept: Vec::new(), clock: 0, drawing: Vec::new(), scenes: 0, released: 0 }); /// Runs `f` on the kept meshes. #[cfg(not(test))] @@ -169,6 +172,17 @@ fn with_meshes(f: impl FnOnce(&mut Meshes) -> R) -> R { MESHES.with_borrow_mut(f) } +/// Drops every kept mesh ([`crate::release_memory`]), those a scene being drawn has used too: a +/// scene shares its meshes' data, so what it draws stays while it does. Until the scenes begun +/// before this are done, [`keep`] keeps nothing, so one still drawing brings nothing back. +pub(crate) fn release() { + with_meshes(|m| { + m.kept = Vec::new(); + m.clock += 1; + m.released = m.clock; + }); +} + /// A scene being drawn, from [`Scene::begin`] until it is dropped (when the scene is done, /// stopped or failed): while it lasts, no mesh a scene being drawn has used goes, though another /// scene drawn at the same time (on the UI's thread and a worker's) keeps meshes too. @@ -244,6 +258,10 @@ fn keep_within(max: usize, layer: u64, look: LayerLook, made: Made, rows: &[bool return; } with_meshes(|m| { + // Not while a scene from before the last release is drawing: this may be its mesh. + if m.drawing.iter().any(|(_, began)| *began < m.released) { + return; + } // What goes for this one, worked out before anything goes: the layer's meshes of another // look (they no longer match), the one of this view, and past `VIEWS` its oldest; none // that a scene being drawn uses. @@ -355,7 +373,7 @@ mod tests { /// (`frame_cache`) doesn't draw the layers under it. A frame drawn on the CPU instead fails /// the test. fn scene(m: &mut Map, view: &View) -> GpuScene { - crate::frame_cache::clear(); + crate::frame_cache::release(); match render_backend(m, view, Backend::Gpu) { Some(RenderOutput::Gpu(s)) => s, _ => panic!("no GPU scene"), @@ -387,6 +405,21 @@ mod tests { } } + /// A scene stopped by a memory warning may still be drawing: what it makes after the release + /// isn't kept, and a scene begun once it is done keeps again. + #[test] + fn a_release_is_not_undone_by_a_scene_begun_before_it() { + super::clear(); + let (mut m, _, _, view) = two_layers(); + let stopped = Scene::begin(); + release(); + scene(&mut m, &view); + assert_eq!(kept_bytes(), 0); + drop(stopped); + scene(&mut m, &view); + assert!(kept_bytes() > 0); + } + /// A scene of the same view after one layer was restyled takes the other's mesh, shared /// with the last scene, and tessellates the restyled one again: the same commands, vertex for /// vertex, as a scene drawn with nothing kept. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index bc664ca170..426475cad9 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -53,6 +53,16 @@ pub use tiles::{Live, live as live_tiles}; pub use rustgis_tiles; pub use tiles::{draws_pictures as tile_draws_pictures, source_layers as tile_source_layers, spec as tile_spec, style_view}; +/// Drops what is kept only to draw again sooner, for a system short of memory: the tile cache +/// with everything read through it ([`rustgis_tiles::cache::clear`]), and the pictures and meshes +/// kept from one frame to the next. Each is made or fetched again when next wanted. +pub fn release_memory() { + rustgis_tiles::cache::clear(); + frame_cache::release(); + layer_meshes::release(); + tile_mesh::release(); +} + /// Natural Earth 1:110m sample data (public domain), fetched by `build.rs` from rustgis-assets. /// The countries in another worldview are downloaded when one is chosen, never built in. pub mod sample_data { diff --git a/crates/render/src/tile_mesh.rs b/crates/render/src/tile_mesh.rs index 9d7d6c4d63..36493c9903 100644 --- a/crates/render/src/tile_mesh.rs +++ b/crates/render/src/tile_mesh.rs @@ -376,6 +376,13 @@ fn lock() -> MutexGuard<'static, Store> { S.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) } +/// Drops the kept meshes ([`crate::release_memory`]); one a scene draws is shared with it. +pub(crate) fn release() { + let mut s = lock(); + s.entries = HashMap::new(); + s.bytes = 0; +} + /// The meshes of `tiles` (bottom first) for `style`'s `source` at `level`, each kept once made /// (while its tile and the style are, and within a memory budget; one made while the sprite was /// on its way until it has arrived); `None` for one that is no vector tile, or not made diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b5f8fa0d35..8202922537 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1392,6 +1392,20 @@ impl RustGisApp { } self.fixes.push_back(fix); } + + /// The system is short of memory (a phone says so): drops what is kept only to draw again + /// sooner ([`Session::release_memory`], the map's drapes, and its textures and buffers on the + /// graphics card), and says so the first time. + pub fn release_memory(&mut self) { + // The map first: it stops the frames being drawn, which would keep more. + self.map.release_memory(); + self.session.release_memory(); + if !std::mem::replace(&mut self.said_low_memory, true) { + self.session.warn(tl!( + "The device is low on memory: RustGIS dropped the map tiles and drawings it kept to draw faster. They are made or downloaded again when needed." + )); + } + } } /// Whether `fix` replaces the shown position: not when it is older, nor when it is much less @@ -1477,6 +1491,8 @@ pub struct RustGisApp { /// 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, + /// Whether [`RustGisApp::release_memory`] has said so, which it does once. + said_low_memory: bool, /// Watches linked local files for changes made outside RustGIS and offers Reload Data /// (the desktop app; see [`diskwatch`]). Off for tests, unless one turns it on (as `ui_shot`'s /// `watchFiles` does). @@ -1783,6 +1799,7 @@ impl RustGisApp { keep_locating: false, photos: Vec::new(), fixes_dropped: 0, + said_low_memory: false, #[cfg(not(target_arch = "wasm32"))] watch_files: false, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index f84f174dbb..b186fe1033 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -600,6 +600,34 @@ impl MapView { let live = self.frame_times.back().is_some_and(|t| *t > now - 0.5); live.then(|| self.frame_times.iter().filter(|t| **t > now - 1.0).count()) } + /// Drops what the map keeps only to draw sooner, for a system short of memory: the moving + /// globe's and tilted map's drapes, and what [`MapView::drop_gpu`] does. + pub(crate) fn release_memory(&mut self) { + self.drape.clear(); + self.tilt_drape.clear(); + self.drop_gpu(); + // A frame drawn mid-motion, finished or stopped, would put back the drawing copies of + // its map when taken: it is let go untaken. + let relay = self.motion_frame.relay.clone(); + self.motion_frame = Default::default(); + self.motion_frame.relay = relay; + self.motion_dropped = false; + } + + /// Drops the GPU renderer's scenes, textures and buffers (the renderer itself too): a frame + /// drawn on the GPU after this makes them again. + pub(crate) fn drop_gpu(&mut self) { + self.gpu_renderer = None; + self.gpu_frame = None; + // (No live GPU scene is left to keep the tile key for.) + self.live_rev = None; + self.split_gpu = None; + for target in [&self.gpu_target, &self.gpu_target_split] { + *target.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + self.invalidate(); + } + /// Forces a re-render on the next frame; also drops the GPU frame (the backend toggle /// relies on it). pub fn invalidate(&mut self) { @@ -799,15 +827,7 @@ pub(crate) fn leave_gpu_if_out_of_memory(app: &mut RustGisApp) { return; } app.map.gpu_enabled = false; - app.map.gpu_renderer = None; - app.map.gpu_frame = None; - // (No live GPU scene is left to keep the tile key for.) - app.map.live_rev = None; - app.map.split_gpu = None; - for target in [&app.map.gpu_target, &app.map.gpu_target_split] { - *target.lock().unwrap_or_else(|e| e.into_inner()) = None; - } - app.map.invalidate(); + app.map.drop_gpu(); app.session.notify( tl!( "The graphics card ran out of memory, so the map is now drawn without it (CPU), which is slower. Click CPU in the status bar to try the graphics card again, with a smaller window or fewer layers." diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 39b726b1d5..4d200e285c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1728,12 +1728,18 @@ computer's memory, or on Linux the lowest memory limit of the control groups Rus own and those above it (set by a container runtime, or by systemd's `MemoryMax` for a service), when it is lower: each plans for a quarter of it, never below the web app's fixed limits and never above a ceiling. `limits.memorySource` says what they follow: `computer`, `container` (such a limit, lower than the computer's memory), -`override` or `unknown`. For tests, or to reproduce a smaller computer, set the environment +`phone`, `override` or `unknown`. For tests, or to reproduce a smaller computer, set the environment variable `RUSTGIS_MEMORY_BYTES` to the memory in bytes (such as `8589934592` for 8 GiB) before starting RustGIS: it replaces the memory read from the computer and any container limit, and the command line says so on every run. It isn't a way to go faster: a value above the computer's memory raises every limit past what it has, and a large job can then run out of memory. +On a phone the limits plan the same way from what its system allows: on Android, the memory the +device has, and no more than is free before Android starts ending processes; on iOS, what iOS says +the app may still use. Where the web app's floor is lower (`rasterSamples`, `bufferBytes`), a +phone takes it. There `undoBytes` plans for what is free too, once as RustGIS starts, and +`threadScratchBytes` is the web app's 256 MiB (see [Memory](field-work.md#memory)). + The limits below other than `threadScratchBytes`, `undoBytes` and `projectBytes` plan for less when memory is short, never below their floors. They plan for the smallest of three figures: - a quarter of the memory; diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 29d203473e..7514f2312f 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -61,6 +61,18 @@ Formats read through GDAL, DuckDB databases and the GeoLibre tools need programs run: the app says so where they would appear. Convert such data on a computer first. Database connections (PostGIS, MySQL, SQL Server) work on a phone too, as they need no program. +## Memory + +A phone gives an app much less memory than a computer, and ends one that takes too much. RustGIS +plans each job from what the system allows and has free at the time (see +[the limits](analysis.md#analysis-workflows)), so a raster that opens whole on a computer can open +at a lower resolution on a phone, and a tool's output can be refused there. RustGIS says so either +way; a refused tool says what to change, such as giving a larger cell size or a smaller extent. + +When the system warns that memory is short, RustGIS drops the map tiles and drawings it keeps to +draw faster, and says so once. Layers, results and Undo history are kept. Tiles from the web are +downloaded again when the map needs them, so offline they stay blank until there is a network. + ## Capturing features **Capture** adds features to one of the map's point, line or polygon layers. A cross marks the