From 2af5fa5fb04edb7d6eb50c5e0a124a65eb1bf719 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 22:52:14 -0600 Subject: [PATCH 1/2] feat(mobile): type in iOS's own text field on iPhones and iPads The Capture form's and the Assistant's fields open a bar docked above the soft keyboard with UIKit's own text field, as Android's do with its own: paste, suggestions, autocorrection, dictation and the password manager. --- apps/rustgis-mobile/README.md | 5 +- apps/rustgis-mobile/src/ios.rs | 52 +++- apps/rustgis-mobile/src/ios/entry.rs | 411 +++++++++++++++++++++++++++ docs/user-guide/assistant.md | 2 +- docs/user-guide/field-work.md | 11 +- 5 files changed, 470 insertions(+), 11 deletions(-) create mode 100644 apps/rustgis-mobile/src/ios/entry.rs diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index c2373c6511..1f73a9907c 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -97,7 +97,7 @@ Rust calls Java and never the other way: each frame the app collects what happen A phone starts in the touch interface: the map, with a Layers button at its top-right corner, a bar of large buttons under it (Add Data, Capture, the AI Assistant once a provider is set up, More) and sheets that rise over the map. Until then, **Set Up the Assistant** in the More sheet is the only -trace of the Assistant, and with its extension off there is none; its sheet types into Android's +trace of the Assistant, and with its extension off there is none; its sheet types into the system's own text field and stands full or half up, with a strip and Stop while it works ([AI Assistant › On a phone](../../docs/user-guide/assistant.md#on-a-phone)). The Layers sheet switches between the project's maps and layouts when it has more than one, shows and hides layers, zooms to one and @@ -420,6 +420,7 @@ cp parcels.gpkg "$(xcrun simctl get_app_container booted org.rustgis.mobile data | Position | Core Location, best accuracy. Asked the first time (`NSLocationWhenInUseUsageDescription`); positions start once the user allows them. Refused, now or later in Settings, the app says so and stops asking | | Out of sight | Recording a track turns on background location updates (the app's `location` background mode in `Info.plist`), with iOS's indicator that an app is using the location. Positions found out of sight wait, at most 200,000, as on Android | | Camera | `UIImagePickerController`: the photo is written as a JPEG to `Library/Application Support/photos`. A device without a camera (the Simulator) says so | +| Typing | The Capture form's fields and the Assistant's are typed into iOS's own text field, in a bar docked above the soft keyboard (`src/ios/entry.rs`): a `UITextField`, or a `UITextView` for several lines, with paste, suggestions, autocorrection, dictation and, for a key, the password manager. What it holds is sent as it changes; Done, a tap beside it, Return on a single line, the keyboard being put away and the phone being turned close it (the keyboard of winit's window doesn't turn while it is up). Fields the desktop interface draws are typed through winit's own, below | | Soft keyboard | winit's own (`UIKeyInput`): letters, Backspace and Return reach the form. The room the keyboard takes comes from UIKit's keyboard notices and keeps the field above it. Return reaches the form as the Enter key: winit 0.30 hands it on as the character `"\n"`, which egui takes for no key, so winit's view is given a subclass whose `insertText:` keeps Return for the shell, which gives egui an Enter. Each field then does what it does with Enter: a single-line one ends typing, and a dialog's text box takes Enter as its button (Shift+Enter there starts a new line, which the soft keyboard can't type) | | 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 | @@ -427,7 +428,7 @@ cp parcels.gpkg "$(xcrun simctl get_app_container booted org.rustgis.mobile data | 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 +`src/ios.rs`, with its `ios/entry.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`, a few of UIKit's calls are unsafe in `objc2`, and libSystem's `os_proc_available_memory` is diff --git a/apps/rustgis-mobile/src/ios.rs b/apps/rustgis-mobile/src/ios.rs index c0665387bd..9e72958864 100644 --- a/apps/rustgis-mobile/src/ios.rs +++ b/apps/rustgis-mobile/src/ios.rs @@ -12,6 +12,8 @@ // each block says why it holds. #![expect(unsafe_code, reason = "Objective-C classes, the few UIKit calls objc2 marks unsafe and one libSystem function; see each SAFETY")] +mod entry; + use crate::shell; use eframe::egui; use objc2::rc::Retained; @@ -31,7 +33,7 @@ use objc2_ui_kit::{ UIViewController, UIWindow, UIWindowDidBecomeVisibleNotification, UIWindowScene, UIWindowSceneDelegate, }; use objc2_uniform_type_identifiers::UTTypeItem; -use rustgis_engine::platform::{Event, Fix, Platform}; +use rustgis_engine::platform::{Event, Fix, Platform, TextEntry}; use rustgis_ui_egui::i18n; use std::cell::{Cell, RefCell}; use std::path::{Path, PathBuf}; @@ -712,19 +714,23 @@ define_class!( let Some(window) = key_window(mtm).map(|window| window.frame()) else { return }; let bottom = window.origin.y + window.size.height; // Only a keyboard across the window takes room from it: a floating one beside a window - // in Split View or Stage Manager takes none. + // in Split View or Stage Manager takes none, nor one floating over it, clear of its bottom. let height = frame .map(|f| { let across = f.origin.x < window.origin.x + window.size.width && f.origin.x + f.size.width > window.origin.x; - if across { (bottom - f.origin.y).clamp(0.0, window.size.height) } else { 0.0 } + let docked = f.origin.y + f.size.height >= bottom - 1.0; + if across && docked { (bottom - f.origin.y).clamp(0.0, window.size.height) } else { 0.0 } }) .unwrap_or(0.0); self.ivars().height.set(height); + // An open text field is put above it by the next frame ([`Ios::place_entry`]). + wake(mtm); } #[unsafe(method(keyboardHidden:))] fn hidden(&self, _notification: &NSNotification) { self.ivars().height.set(0.0); + wake(self.mtm()); } } ); @@ -1012,6 +1018,8 @@ pub struct Ios { location: Retained, located: Retained, keyboard: Retained, + /// The text field of iOS's own that is open, or was last (UIKit holds its delegate weakly). + entry: RefCell>>, memory: Retained, /// A file to save being written, until its export picker shows. saving: RefCell>, @@ -1036,6 +1044,7 @@ struct Saving { impl Drop for Ios { fn drop(&mut self) { + self.close_entry(); let center = NSNotificationCenter::defaultCenter(); // SAFETY: removes the observers `KeyboardObserver::new` and `MemoryObserver::new` added. unsafe { @@ -1069,6 +1078,7 @@ impl Ios { location, located, keyboard: KeyboardObserver::new(mtm), + entry: RefCell::new(None), saving: RefCell::new(None), presenting: RefCell::new(None), } @@ -1160,6 +1170,27 @@ impl Ios { } } + /// Keeps the text field of iOS's own that is open above the soft keyboard, which comes, goes + /// and changes height. Closes it as the window turns: what it holds has been told, and a tap + /// opens it again. Lets go of one that closed. Asked each frame (`take_events`). + fn place_entry(&self) { + let Some(entry) = self.entry.borrow().clone() else { return }; + match entry.window().filter(|window| entry.is_open() && !entry.turned(window)) { + Some(window) => entry.place(&window, self.keyboard.ivars().height.get()), + // Closed already, this does nothing but let go of it. + None => self.close_entry(), + } + } + + /// Closes the text field of iOS's own that is open, if one is. + fn close_entry(&self) { + // Taken first: closing calls back into UIKit, which must not find it borrowed. + let open = self.entry.borrow_mut().take(); + if let Some(entry) = open { + entry.close(); + } + } + /// The window's view controller on top, to show a picker over. fn presenter(&self) -> Result, String> { let window = key_window(self.mtm).ok_or_else(|| i18n::fmt("RustGIS has no window to show the picker over yet.", &[]))?; @@ -1319,9 +1350,24 @@ impl Platform for Ios { self.present(&presenter, &picker, true) } + fn enters_text(&self) -> bool { + true + } + + fn enter_text(&self, entry: &TextEntry) -> Result<(), String> { + // One opened while another is open replaces it, which closes first. + self.close_entry(); + let window = key_window(self.mtm).ok_or_else(|| i18n::fmt("RustGIS has no window to type in yet.", &[]))?; + let height = || self.keyboard.ivars().height.get(); + let opened = entry::Entry::open(self.mtm, self.shared.clone(), &window, entry, &height)?; + self.entry.replace(Some(opened)); + Ok(()) + } + fn take_events(&self) -> Vec { self.check_presented(); self.show_export(); + self.place_entry(); self.shared.events.lock().unwrap_or_else(|e| e.into_inner()).take() } } diff --git a/apps/rustgis-mobile/src/ios/entry.rs b/apps/rustgis-mobile/src/ios/entry.rs new file mode 100644 index 0000000000..e5122369c3 --- /dev/null +++ b/apps/rustgis-mobile/src/ios/entry.rs @@ -0,0 +1,411 @@ +//! The text field of iOS's own that a field of the front end's opens +//! ([`Platform::enter_text`](rustgis_engine::platform::Platform::enter_text)): a bar docked above +//! the soft keyboard, with what the field is for, a `UITextField` (a `UITextView` for several +//! lines) and Done. It gives UIKit's own typing: paste, suggestions, autocorrection, dictation and +//! the password manager. +//! +//! What it holds is sent as it changes ([`Typed::Text`]), and once more as it closes where that +//! is new (closing ends a word still being composed, and takes a correction UIKit was offering). +//! Done, a tap beside the bar, Return on a single line, the keyboard being put away and the phone +//! being turned close it. + +use super::{Shared, safe_area, wake}; +use objc2::rc::Retained; +use objc2::runtime::{Bool, NSObject, NSObjectProtocol, ProtocolObject, Sel}; +use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; +use objc2_foundation::{NSObject as Object, NSPoint, NSRange, NSRect, NSSize, NSString}; +use objc2_ui_kit::{ + NSObjectUIAccessibility, UIButton, UIButtonType, UIColor, UIControl, UIControlEvents, UIControlState, UIFont, UIKeyboardType, UILabel, + UIScrollViewDelegate, UITextAutocapitalizationType, UITextAutocorrectionType, UITextBorderStyle, UITextContentTypePassword, + UITextField, UITextFieldDelegate, UITextInput, UITextView, UITextViewDelegate, UIView, UIWindow, +}; +use rustgis_engine::platform::{Event, TextEntry, TextKind, Typed}; +use rustgis_ui_egui::i18n; +use std::cell::{Cell, RefCell}; +use std::sync::Arc; + +/// The bar's margin and the gap between its parts, in points. +const GAP: f64 = 10.0; +/// The height of its label. +const LABEL: f64 = 20.0; +/// The height of a single line and of Done, and the height of several lines. +const LINE: f64 = 40.0; +const LINES: f64 = 110.0; +/// The width of Done. +const DONE: f64 = 72.0; + +/// What is typed into. +enum Input { + Line(Retained), + Lines(Retained), +} + +impl Input { + /// The view placed in the bar and given the keyboard, whichever it is. + fn view(&self) -> &UIView { + match self { + Input::Line(field) => field, + Input::Lines(view) => view, + } + } + + /// All it holds, a word still being composed included. + fn text(&self) -> String { + match self { + Input::Line(field) => field.text().map(|t| t.to_string()).unwrap_or_default(), + Input::Lines(view) => view.text().to_string(), + } + } +} + +pub(super) struct EntryIvars { + shared: Arc, + /// The front end's name for the field ([`TextEntry::id`]). + id: String, + /// What the front end was last told it holds. + sent: RefCell, + closed: Cell, + /// It is being closed: UIKit's callbacks as it lets go of the keyboard don't close it again. + closing: Cell, + /// What is typed is hidden, and let go of once it is told. + secret: bool, + /// What the bar was last laid out for: the window's size, its safe area and the keyboard. + placed: Cell>, + /// Whether the window was wider than tall as it opened. + wide: bool, + /// Under the bar, over the window: a tap on it closes the field. + beside: Retained, + bar: Retained, + label: Retained, + done: Retained, + input: Input, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and this class doesn't implement Drop. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "RustGISTextEntry"] + #[ivars = EntryIvars] + pub(super) struct Entry; + + unsafe impl NSObjectProtocol for Entry {} + + unsafe impl UIScrollViewDelegate for Entry {} + + unsafe impl UITextFieldDelegate for Entry { + #[unsafe(method(textFieldShouldReturn:))] + fn returned(&self, _field: &UITextField) -> bool { + self.close(); + false + } + + /// A secret's change is made here, not by UIKit, which empties a hidden field on the first + /// one after it opens: a key changed by a character would be replaced by it. + #[unsafe(method(textField:shouldChangeCharactersInRange:replacementString:))] + fn change_line(&self, field: &UITextField, range: NSRange, with: &NSString) -> bool { + if self.ivars().secret { + let held = field.text().unwrap_or_default(); + // UIKit raises on a range past the end, which a hidden field it has emptied may give. + let (start, end) = (range.location.min(held.length()), range.location.saturating_add(range.length).min(held.length())); + let range = NSRange::new(start, end - start); + field.setText(Some(&held.stringByReplacingCharactersInRange_withString(range, with))); + self.report(); + } + !self.ivars().secret + } + + #[unsafe(method(textFieldDidEndEditing:))] + fn line_ended(&self, _field: &UITextField) { + self.close(); + } + } + + unsafe impl UITextViewDelegate for Entry { + #[unsafe(method(textViewDidChange:))] + fn lines_changed(&self, _view: &UITextView) { + self.report(); + } + + #[unsafe(method(textViewDidEndEditing:))] + fn lines_ended(&self, _view: &UITextView) { + self.close(); + } + } + + impl Entry { + #[unsafe(method(changed:))] + fn changed(&self, _sender: &Object) { + self.report(); + } + + #[unsafe(method(done:))] + fn done(&self, _sender: &Object) { + self.close(); + } + } +); + +impl Entry { + /// Opens the field over `window`, above a soft keyboard `keyboard` points tall, and gives it + /// the keyboard. An error when it can't: nothing is left on the screen. + pub(super) fn open( + mtm: MainThreadMarker, + shared: Arc, + window: &UIWindow, + entry: &TextEntry, + keyboard: &dyn Fn() -> f64, + ) -> Result, String> { + let input = + input(mtm, entry).ok_or_else(|| i18n::fmt("The text box wasn't opened: this system doesn't hide what is typed in it.", &[]))?; + let this = Self::alloc(mtm).set_ivars(EntryIvars { + shared, + id: entry.id.clone(), + sent: RefCell::new(entry.value.clone()), + closed: Cell::new(false), + closing: Cell::new(false), + secret: entry.kind == TextKind::Secret, + placed: Cell::new(None), + wide: wide(window), + beside: UIControl::new(mtm), + bar: UIView::new(mtm), + label: UILabel::new(mtm), + done: UIButton::buttonWithType(UIButtonType::System, mtm), + input, + }); + // SAFETY: NSObject's `init` on a freshly allocated object. + let this: Retained = unsafe { msg_send![super(this), init] }; + let parts = this.ivars(); + parts.label.setText(Some(&NSString::from_str(&entry.label))); + // VoiceOver says what the field is for, and leaves out what is under the bar. + parts.input.view().setAccessibilityLabel(Some(&NSString::from_str(&entry.label)), mtm); + parts.bar.setAccessibilityViewIsModal(true, mtm); + // SAFETY: a font and a color UIKit gives, set on a label made here. + unsafe { + parts.label.setFont(Some(&UIFont::systemFontOfSize(13.0))); + parts.label.setTextColor(Some(&UIColor::secondaryLabelColor())); + } + parts.done.setTitle_forState(Some(&NSString::from_str(&entry.done)), UIControlState::Normal); + parts.bar.setBackgroundColor(Some(&UIColor::systemBackgroundColor())); + // SAFETY: the actions are this class's own methods, taking the sender. UIKit holds targets + // and delegates weakly: `Ios` holds this while it is open. + unsafe { + parts.done.addTarget_action_forControlEvents(Some(&this), sel!(done:), UIControlEvents::TouchUpInside); + parts.beside.addTarget_action_forControlEvents(Some(&this), sel!(done:), UIControlEvents::TouchDown); + match &parts.input { + Input::Line(field) => { + field.addTarget_action_forControlEvents(Some(&this), sel!(changed:), UIControlEvents::EditingChanged); + field.setDelegate(Some(ProtocolObject::from_ref(&*this))); + } + Input::Lines(view) => view.setDelegate(Some(ProtocolObject::from_ref(&*this))), + } + } + for part in [&*parts.label as &UIView, parts.input.view(), &parts.done] { + parts.bar.addSubview(part); + } + // In the window, not in winit's view: that takes the keyboard (`UIKeyInput`), and UIKit hands + // it on to it when a field inside it lets go, so it would stay up. + window.addSubview(&parts.beside); + window.addSubview(&parts.bar); + this.place(window, keyboard()); + if !parts.input.view().becomeFirstResponder() { + // Not open, so no close is told: the caller is told it couldn't be opened. + parts.closed.set(true); + this.remove(); + return Err(i18n::fmt("The text box couldn't be opened just now: try again.", &[])); + } + // The keyboard's height is known once it is asked for. + this.place(window, keyboard()); + Ok(this) + } + + /// The window it is in, while it is in one. + pub(super) fn window(&self) -> Option> { + self.ivars().bar.window() + } + + /// Whether it is still on the screen. + pub(super) fn is_open(&self) -> bool { + !self.ivars().closed.get() + } + + /// Whether `window` was turned since it opened. The soft keyboard of winit's window doesn't turn + /// while it is up (winit's own doesn't either), so there is nothing to lay the bar out above. + pub(super) fn turned(&self, window: &UIWindow) -> bool { + self.ivars().wide != wide(window) + } + + /// Lays the bar out over `window`, above the soft keyboard or, with none up (a hardware + /// keyboard), above the safe area's bottom. + pub(super) fn place(&self, window: &UIWindow, keyboard: f64) { + let parts = self.ivars(); + let (size, safe) = (window.bounds().size, safe_area(window)); + let now = [size.width, size.height, safe.left, safe.top, safe.right, safe.bottom, keyboard]; + if parts.placed.replace(Some(now)) == Some(now) { + return; + } + let tall = if matches!(parts.input, Input::Lines(_)) { LINES } else { LINE }; + // The safe area of winit's window stays as it was before the phone was turned, with what + // the camera takes of a side still at the top: a wide window keeps clear of it on both sides. + let side = if wide(window) { safe.top } else { 0.0 }; + let (left, right) = (safe.left.max(side).max(0.0) + GAP, safe.right.max(side).max(0.0) + GAP); + // Never above the window's top, where a short window (a phone held sideways) leaves little + // room: several lines are then fewer. + let room = (size.height - keyboard.max(safe.bottom) - safe.top).max(LABEL + 3.0 * GAP + LINE); + let tall = tall.min(room - LABEL - 3.0 * GAP); + let height = LABEL + tall + 3.0 * GAP; + let width = (size.width - left - right - DONE - GAP).max(0.0); + let rect = |x: f64, y: f64, w: f64, h: f64| NSRect::new(NSPoint::new(x, y), NSSize::new(w, h)); + parts.beside.setFrame(rect(0.0, 0.0, size.width, size.height)); + parts.bar.setFrame(rect(0.0, size.height - keyboard.max(safe.bottom) - height, size.width, height)); + parts.label.setFrame(rect(left, GAP, width + GAP + DONE, LABEL)); + parts.input.view().setFrame(rect(left, LABEL + 2.0 * GAP, width, tall)); + parts.done.setFrame(rect(left + width + GAP, LABEL + 2.0 * GAP, DONE, LINE)); + } + + /// Tells the front end what the field holds, where that is new. + fn report(&self) { + let parts = self.ivars(); + if parts.closed.get() { + return; + } + let text = parts.input.text(); + if *parts.sent.borrow() == text { + return; + } + parts.sent.replace(text.clone()); + parts.shared.add(Event::Typed(Typed::Text { id: parts.id.clone(), text })); + wake(self.mtm()); + } + + /// Takes the field away: the last of what it holds is told, then that it closed. Once: letting + /// go of the keyboard calls this again. + pub(super) fn close(&self) { + let parts = self.ivars(); + if parts.closed.get() || parts.closing.replace(true) { + return; + } + // Both may change the text, the second by taking a correction offered: told before the close. + match &parts.input { + Input::Line(field) => field.unmarkText(), + Input::Lines(view) => view.unmarkText(), + } + parts.input.view().resignFirstResponder(); + self.report(); + parts.closed.set(true); + self.remove(); + parts.shared.add(Event::Typed(Typed::Closed { id: parts.id.clone(), failed: None })); + wake(self.mtm()); + } + + /// Takes the bar off the screen, and lets go of a secret. + fn remove(&self) { + let parts = self.ivars(); + parts.bar.removeFromSuperview(); + parts.beside.removeFromSuperview(); + if parts.secret + && let Input::Line(field) = &parts.input + { + field.setText(None); + parts.sent.take(); + } + } +} + +fn wide(window: &UIWindow) -> bool { + let size = window.bounds().size; + size.width > size.height +} + +/// The view `entry` is typed into, holding its value. A single line's value that has line breaks +/// (a value read from a file) is typed in several, as a `UITextField` would lose them. `None` for +/// a secret that can't be hidden. +fn input(mtm: MainThreadMarker, entry: &TextEntry) -> Option { + let value = NSString::from_str(&entry.value); + let font = UIFont::systemFontOfSize(17.0); + let lines = match entry.kind { + TextKind::Lines => true, + TextKind::Plain => entry.value.contains(['\n', '\r']), + TextKind::Secret | TextKind::Number => false, + }; + if lines { + let view = UITextView::new(mtm); + view.setFont(Some(&font)); + view.setText(Some(&value)); + // Nothing else shows where the box is. + view.setBackgroundColor(Some(&UIColor::secondarySystemBackgroundColor())); + return Some(Input::Lines(view)); + } + let field = UITextField::new(mtm); + field.setFont(Some(&font)); + field.setBorderStyle(UITextBorderStyle::RoundedRect); + match entry.kind { + TextKind::Secret => { + if !set_secure(&field) { + return None; + } + // SAFETY: a content type UIKit defines, an NSString. + set_object(&field, sel!(setTextContentType:), unsafe { UITextContentTypePassword }); + set_choice(&field, sel!(setAutocorrectionType:), UITextAutocorrectionType::No.0); + set_choice(&field, sel!(setAutocapitalizationType:), UITextAutocapitalizationType::None.0); + } + // Digits first, with signs, points and letters a key away: a pasted 1e3 stays whole, and + // a number that can't be read is refused by the front end, not dropped here. + TextKind::Number => { + set_choice(&field, sel!(setKeyboardType:), UIKeyboardType::NumbersAndPunctuation.0); + set_choice(&field, sel!(setAutocorrectionType:), UITextAutocorrectionType::No.0); + } + TextKind::Plain | TextKind::Lines => {} + } + field.setText(Some(&value)); + Some(Input::Line(field)) +} + +// How a field is typed into (`UITextInputTraits`). UITextField answers these by forwarding them, +// having no methods of their names, and objc2's check of a message (with debug assertions on) +// aborts on a method it doesn't find: they are sent as they are, each once the field says it +// answers it. + +/// `objc_msgSend` for a setter taking one `T`. +fn setter() -> unsafe extern "C-unwind" fn(&UITextField, Sel, T) { + // SAFETY: objc_msgSend is called as the method it finds is declared; the callers below give + // the type of that method's argument, an integer, a BOOL or an object pointer. + unsafe { + std::mem::transmute::(objc2::ffi::objc_msgSend) + } +} + +/// Hides what is typed into `field`. Whether it does now. +fn set_secure(field: &UITextField) -> bool { + let (set, get) = (sel!(setSecureTextEntry:), sel!(isSecureTextEntry)); + if !field.respondsToSelector(set) || !field.respondsToSelector(get) { + return false; + } + // SAFETY: objc_msgSend, for a method that takes nothing and gives a BOOL. + let ask = unsafe { + std::mem::transmute:: Bool>( + objc2::ffi::objc_msgSend, + ) + }; + // SAFETY: the field answers both, the first taking a BOOL and the second giving one. + unsafe { + setter::()(field, set, Bool::YES); + ask(field, get).as_bool() + } +} + +/// Sets a choice (an `NSInteger`) of how `field` is typed into. +fn set_choice(field: &UITextField, set: Sel, choice: isize) { + if field.respondsToSelector(set) { + // SAFETY: the field answers it, and the setters this is given take an NSInteger. + unsafe { setter::()(field, set, choice) }; + } +} + +/// Sets an object of how `field` is typed into. +fn set_object(field: &UITextField, set: Sel, object: &NSString) { + if field.respondsToSelector(set) { + // SAFETY: the field answers it, and the setter this is given takes an NSString. + unsafe { setter::<&NSString>()(field, set, object) }; + } +} diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 0db61af743..d54ad9fc4b 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -51,7 +51,7 @@ From the command line, `rustgis-cli ask` sends one request (see In the [touch interface](field-work.md#the-touch-interface) nothing of the assistant shows until a provider is set up: **Set Up the Assistant**, in the More sheet, chooses the provider, its model and its key. Then the bar has an **Assistant** button, which opens the conversation in a sheet. -Tap the message box to type in Android's own text field (with its paste, suggestions and +Tap the message box to type in the phone's own text field (with its paste, suggestions and dictation), then **Send**. The sheet stands half up, to see the map with the conversation, or full for reading and typing: the arrow beside its **×** switches, and a swipe up or down on its heading moves it a step. Lowered while the assistant works, a strip over the bar says what it is doing and diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index f83351cc1c..1bd33bf424 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -105,11 +105,12 @@ The form has a field for each of the layer's attributes, and follows the layer's - A date field has a calendar button, with **Today** and, for a date and time, **Now**. Both are in UTC. -While you type in a field, the sheet stays above the soft keyboard. On Android, tapping a text or -number field opens Android's own text box above the keyboard, so paste, suggestions, glide typing -and dictation work there. The form shows the value as you type. **Done**, the keyboard's Done key, -Back or a tap outside the box closes it. Text copied in RustGIS goes on Android's clipboard too, -where other apps can paste it. +While you type in a field, the sheet stays above the soft keyboard. Tapping a text or number field +opens the phone's own text box above the keyboard (Android's, or iOS's on an iPhone or iPad), so +paste, suggestions, glide typing and dictation work there. The form shows the value as you type. +**Done**, the keyboard's Done or Return key, Android's Back or a tap outside the box closes it, as +turning an iPhone does: what you typed is kept, and a tap opens the box again. Text copied in +RustGIS goes on Android's clipboard too, where other apps can paste it. ### Photos From 1abec0b50ef207cbd0f3232754ede1a511ed7d7e Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 07:02:40 -0600 Subject: [PATCH 2/2] fix(mobile): a hidden field keeps its value and caret, and a name or address is kept as typed iOS's text field put the caret at the end after a change in the middle of a secret, so the next characters went there, and its line breaks could be lost: the value is kept apart from what the field shows. A model's name and a provider's address were given capitals and corrections, on Android too. --- apps/rustgis-mobile/README.md | 2 +- .../java/org/rustgis/mobile/MainActivity.java | 6 +- apps/rustgis-mobile/src/ios/entry.rs | 78 ++++++++----- apps/rustgis-mobile/src/lib.rs | 2 + apps/rustgis-mobile/src/typed.rs | 108 ++++++++++++++++++ crates/engine/src/platform.rs | 6 +- crates/ui-touch/src/assistant.rs | 11 +- docs/user-guide/field-work.md | 7 +- 8 files changed, 182 insertions(+), 38 deletions(-) create mode 100644 apps/rustgis-mobile/src/typed.rs diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 1f73a9907c..62ac380505 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -420,7 +420,7 @@ cp parcels.gpkg "$(xcrun simctl get_app_container booted org.rustgis.mobile data | Position | Core Location, best accuracy. Asked the first time (`NSLocationWhenInUseUsageDescription`); positions start once the user allows them. Refused, now or later in Settings, the app says so and stops asking | | Out of sight | Recording a track turns on background location updates (the app's `location` background mode in `Info.plist`), with iOS's indicator that an app is using the location. Positions found out of sight wait, at most 200,000, as on Android | | Camera | `UIImagePickerController`: the photo is written as a JPEG to `Library/Application Support/photos`. A device without a camera (the Simulator) says so | -| Typing | The Capture form's fields and the Assistant's are typed into iOS's own text field, in a bar docked above the soft keyboard (`src/ios/entry.rs`): a `UITextField`, or a `UITextView` for several lines, with paste, suggestions, autocorrection, dictation and, for a key, the password manager. What it holds is sent as it changes; Done, a tap beside it, Return on a single line, the keyboard being put away and the phone being turned close it (the keyboard of winit's window doesn't turn while it is up). Fields the desktop interface draws are typed through winit's own, below | +| Typing | The Capture form's fields and the Assistant's are typed into iOS's own text field, in a bar docked above the soft keyboard (`src/ios/entry.rs`): a `UITextField`, or a `UITextView` for several lines, with paste, suggestions, autocorrection, dictation and, for a key, the password manager. A model's name and a provider's address are kept as typed, with neither suggestions nor corrections (on Android too). What it holds is sent as it changes; Done, a tap beside it, Return on a single line, the keyboard's own key that puts it away and the phone being turned close it (the keyboard of winit's window doesn't turn while it is up). Fields the desktop interface draws are typed through winit's own, below | | Soft keyboard | winit's own (`UIKeyInput`): letters, Backspace and Return reach the form. The room the keyboard takes comes from UIKit's keyboard notices and keeps the field above it. Return reaches the form as the Enter key: winit 0.30 hands it on as the character `"\n"`, which egui takes for no key, so winit's view is given a subclass whose `insertText:` keeps Return for the shell, which gives egui an Enter. Each field then does what it does with Enter: a single-line one ends typing, and a dialog's text box takes Enter as its button (Shift+Enter there starts a new line, which the soft keyboard can't type) | | 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 | diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index cde3c85f95..007cb7ab19 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -523,7 +523,7 @@ public void takePhoto() { * 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. + * is "plain", "lines", "verbatim", "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. @@ -584,6 +584,10 @@ private android.app.Dialog textEntry(final String id, String value, String label | android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); field.setMaxLines(6); break; + case "verbatim": + field.setInputType(text | android.text.InputType.TYPE_TEXT_VARIATION_URI + | android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + break; default: field.setInputType(text | android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); } diff --git a/apps/rustgis-mobile/src/ios/entry.rs b/apps/rustgis-mobile/src/ios/entry.rs index e5122369c3..c485c0f07f 100644 --- a/apps/rustgis-mobile/src/ios/entry.rs +++ b/apps/rustgis-mobile/src/ios/entry.rs @@ -6,10 +6,11 @@ //! //! What it holds is sent as it changes ([`Typed::Text`]), and once more as it closes where that //! is new (closing ends a word still being composed, and takes a correction UIKit was offering). -//! Done, a tap beside the bar, Return on a single line, the keyboard being put away and the phone -//! being turned close it. +//! Done, a tap beside the bar, Return on a single line, the keyboard's own key that puts it away +//! and the phone being turned close it. use super::{Shared, safe_area, wake}; +use crate::typed::{changed, hidden, replaced, several_lines}; use objc2::rc::Retained; use objc2::runtime::{Bool, NSObject, NSObjectProtocol, ProtocolObject, Sel}; use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; @@ -17,7 +18,8 @@ use objc2_foundation::{NSObject as Object, NSPoint, NSRange, NSRect, NSSize, NSS use objc2_ui_kit::{ NSObjectUIAccessibility, UIButton, UIButtonType, UIColor, UIControl, UIControlEvents, UIControlState, UIFont, UIKeyboardType, UILabel, UIScrollViewDelegate, UITextAutocapitalizationType, UITextAutocorrectionType, UITextBorderStyle, UITextContentTypePassword, - UITextField, UITextFieldDelegate, UITextInput, UITextView, UITextViewDelegate, UIView, UIWindow, + UITextField, UITextFieldDelegate, UITextInput, UITextSmartDashesType, UITextSmartInsertDeleteType, UITextSmartQuotesType, + UITextSpellCheckingType, UITextView, UITextViewDelegate, UIView, UIWindow, }; use rustgis_engine::platform::{Event, TextEntry, TextKind, Typed}; use rustgis_ui_egui::i18n; @@ -101,16 +103,18 @@ define_class!( } /// A secret's change is made here, not by UIKit, which empties a hidden field on the first - /// one after it opens: a key changed by a character would be replaced by it. + /// one after it opens: a key changed by a character would be replaced by it. The value is + /// the one kept here, as its field shows another for it ([`hidden`]). #[unsafe(method(textField:shouldChangeCharactersInRange:replacementString:))] fn change_line(&self, field: &UITextField, range: NSRange, with: &NSString) -> bool { if self.ivars().secret { - let held = field.text().unwrap_or_default(); - // UIKit raises on a range past the end, which a hidden field it has emptied may give. - let (start, end) = (range.location.min(held.length()), range.location.saturating_add(range.length).min(held.length())); - let range = NSRange::new(start, end - start); - field.setText(Some(&held.stringByReplacingCharactersInRange_withString(range, with))); - self.report(); + let (value, caret) = replaced(&self.ivars().sent.borrow(), range.location, range.length, &with.to_string()); + field.setText(Some(&NSString::from_str(&hidden(&value)))); + // Setting the text puts the caret at its end. + if let Some(at) = field.positionFromPosition_offset(&field.beginningOfDocument(), caret as isize) { + field.setSelectedTextRange(field.textRangeFromPosition_toPosition(&at, &at).as_deref()); + } + self.tell(value); } !self.ivars().secret } @@ -270,7 +274,15 @@ impl Entry { return; } let text = parts.input.text(); - if *parts.sent.borrow() == text { + if changed(parts.secret, &parts.sent.borrow(), &text) { + self.tell(text); + } + } + + /// Tells the front end it holds `text`, where that is new. + fn tell(&self, text: String) { + let parts = self.ivars(); + if parts.closed.get() || *parts.sent.borrow() == text { return; } parts.sent.replace(text.clone()); @@ -321,19 +333,16 @@ fn wide(window: &UIWindow) -> bool { /// (a value read from a file) is typed in several, as a `UITextField` would lose them. `None` for /// a secret that can't be hidden. fn input(mtm: MainThreadMarker, entry: &TextEntry) -> Option { - let value = NSString::from_str(&entry.value); let font = UIFont::systemFontOfSize(17.0); - let lines = match entry.kind { - TextKind::Lines => true, - TextKind::Plain => entry.value.contains(['\n', '\r']), - TextKind::Secret | TextKind::Number => false, - }; - if lines { + if several_lines(entry.kind, &entry.value) { let view = UITextView::new(mtm); view.setFont(Some(&font)); - view.setText(Some(&value)); + view.setText(Some(&NSString::from_str(&entry.value))); // Nothing else shows where the box is. view.setBackgroundColor(Some(&UIColor::secondarySystemBackgroundColor())); + if entry.kind == TextKind::Verbatim { + keep_as_typed(&view); + } return Some(Input::Lines(view)); } let field = UITextField::new(mtm); @@ -355,9 +364,11 @@ fn input(mtm: MainThreadMarker, entry: &TextEntry) -> Option { set_choice(&field, sel!(setKeyboardType:), UIKeyboardType::NumbersAndPunctuation.0); set_choice(&field, sel!(setAutocorrectionType:), UITextAutocorrectionType::No.0); } + TextKind::Verbatim => keep_as_typed(&field), TextKind::Plain | TextKind::Lines => {} } - field.setText(Some(&value)); + let shown = if entry.kind == TextKind::Secret { hidden(&entry.value) } else { entry.value.clone() }; + field.setText(Some(&NSString::from_str(&shown))); Some(Input::Line(field)) } @@ -367,25 +378,21 @@ fn input(mtm: MainThreadMarker, entry: &TextEntry) -> Option { // answers it. /// `objc_msgSend` for a setter taking one `T`. -fn setter() -> unsafe extern "C-unwind" fn(&UITextField, Sel, T) { +fn setter() -> unsafe extern "C-unwind" fn(&UIView, Sel, T) { // SAFETY: objc_msgSend is called as the method it finds is declared; the callers below give // the type of that method's argument, an integer, a BOOL or an object pointer. - unsafe { - std::mem::transmute::(objc2::ffi::objc_msgSend) - } + unsafe { std::mem::transmute::(objc2::ffi::objc_msgSend) } } /// Hides what is typed into `field`. Whether it does now. -fn set_secure(field: &UITextField) -> bool { +fn set_secure(field: &UIView) -> bool { let (set, get) = (sel!(setSecureTextEntry:), sel!(isSecureTextEntry)); if !field.respondsToSelector(set) || !field.respondsToSelector(get) { return false; } // SAFETY: objc_msgSend, for a method that takes nothing and gives a BOOL. let ask = unsafe { - std::mem::transmute:: Bool>( - objc2::ffi::objc_msgSend, - ) + std::mem::transmute:: Bool>(objc2::ffi::objc_msgSend) }; // SAFETY: the field answers both, the first taking a BOOL and the second giving one. unsafe { @@ -394,8 +401,19 @@ fn set_secure(field: &UITextField) -> bool { } } +/// Has nothing typed into `field` put in another's place: no capital at the start, correction, +/// curly quote or long dash. +fn keep_as_typed(field: &UIView) { + set_choice(field, sel!(setAutocorrectionType:), UITextAutocorrectionType::No.0); + set_choice(field, sel!(setAutocapitalizationType:), UITextAutocapitalizationType::None.0); + set_choice(field, sel!(setSpellCheckingType:), UITextSpellCheckingType::No.0); + set_choice(field, sel!(setSmartQuotesType:), UITextSmartQuotesType::No.0); + set_choice(field, sel!(setSmartDashesType:), UITextSmartDashesType::No.0); + set_choice(field, sel!(setSmartInsertDeleteType:), UITextSmartInsertDeleteType::No.0); +} + /// Sets a choice (an `NSInteger`) of how `field` is typed into. -fn set_choice(field: &UITextField, set: Sel, choice: isize) { +fn set_choice(field: &UIView, set: Sel, choice: isize) { if field.respondsToSelector(set) { // SAFETY: the field answers it, and the setters this is given take an NSInteger. unsafe { setter::()(field, set, choice) }; @@ -403,7 +421,7 @@ fn set_choice(field: &UITextField, set: Sel, choice: isize) { } /// Sets an object of how `field` is typed into. -fn set_object(field: &UITextField, set: Sel, object: &NSString) { +fn set_object(field: &UIView, set: Sel, object: &NSString) { if field.respondsToSelector(set) { // SAFETY: the field answers it, and the setter this is given takes an NSString. unsafe { setter::<&NSString>()(field, set, object) }; diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index f1e7c25d64..1c9d8b3f5d 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -22,6 +22,8 @@ mod vaultanswer; #[cfg(target_os = "ios")] mod ios; +#[cfg(any(target_os = "ios", test))] +mod typed; #[cfg(target_os = "ios")] pub use ios::main as ios_main; diff --git a/apps/rustgis-mobile/src/typed.rs b/apps/rustgis-mobile/src/typed.rs new file mode 100644 index 0000000000..b384e202c1 --- /dev/null +++ b/apps/rustgis-mobile/src/typed.rs @@ -0,0 +1,108 @@ +//! What a text field of iOS's own does to the text it holds, apart from UIKit (`ios/entry.rs`). + +use rustgis_engine::platform::TextKind; + +/// Whether `value` is typed in several lines: a `UITextField` loses a value's line breaks. A +/// secret's are kept apart from what its field shows ([`hidden`]). +pub(crate) fn several_lines(kind: TextKind, value: &str) -> bool { + match kind { + TextKind::Lines => true, + TextKind::Plain | TextKind::Verbatim | TextKind::Number => value.contains(line_break), + TextKind::Secret => false, + } +} + +/// What UIKit may take for the end of a line. +fn line_break(c: char) -> bool { + matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}') +} + +/// What a hidden field is given to show in place of `value`: as long, so a place in it is the same +/// place in the value, with nothing in it the field would take out. +pub(crate) fn hidden(value: &str) -> String { + value.chars().map(|c| if line_break(c) { ' ' } else { c }).collect() +} + +/// Whether a field showing `shown` was changed since it was told to hold `value`. A secret's shows +/// its value in another form ([`hidden`]). +pub(crate) fn changed(secret: bool, value: &str, shown: &str) -> bool { + if secret { hidden(value) != shown } else { value != shown } +} + +/// `value` with the `length` UTF-16 units at `start` (an `NSRange`, of any size) replaced by +/// `with`, and the place after it. A range cutting a character in two takes it whole. +pub(crate) fn replaced(value: &str, start: usize, length: usize, with: &str) -> (String, usize) { + let end = start.saturating_add(length); + let (mut before, mut after, mut at) = (String::new(), String::new(), 0usize); + for c in value.chars() { + let next = at.saturating_add(c.len_utf16()); + // A change of no length between a character's two units goes before it. + if next <= start { + before.push(c); + } else if at >= end || (length == 0 && next > start) { + after.push(c); + } + at = next; + } + let caret = before.encode_utf16().count().saturating_add(with.encode_utf16().count()); + (format!("{before}{with}{after}"), caret) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_value_is_changed_at_its_range_and_the_caret_follows() { + let change = |start, length, with| replaced("saved-key", start, length, with); + assert_eq!(change(9, 0, "x"), ("saved-keyx".into(), 10)); + assert_eq!(change(2, 0, "XY"), ("saXYved-key".into(), 4)); + assert_eq!(change(0, 0, "p"), ("psaved-key".into(), 1)); + assert_eq!(change(8, 1, ""), ("saved-ke".into(), 8)); + assert_eq!(change(0, 9, "new"), ("new".into(), 3)); + // Past the end, or of any size: nothing is lost that the range doesn't hold. + assert_eq!(change(50, 3, "x"), ("saved-keyx".into(), 10)); + assert_eq!(change(5, usize::MAX, "!"), ("saved!".into(), 6)); + assert_eq!(replaced("", usize::MAX, usize::MAX, "a"), ("a".into(), 1)); + } + + #[test] + fn a_range_is_in_utf16_and_takes_a_character_whole() { + // 😀 is two units: a place after it is 3. + assert_eq!(replaced("a😀b", 3, 0, "x"), ("a😀xb".into(), 4)); + assert_eq!(replaced("a😀b", 1, 2, ""), ("ab".into(), 1)); + assert_eq!(replaced("a😀b", 1, 1, "x"), ("axb".into(), 2)); + assert_eq!(replaced("a😀b", 2, 1, "x"), ("axb".into(), 2)); + assert_eq!(replaced("a😀b", 2, 0, "x"), ("ax😀b".into(), 2)); + } + + #[test] + fn a_hidden_value_is_as_long_and_has_no_line_breaks() { + for value in ["", "key", "a\nb\r\nc", "a\u{2028}b\u{85}", "😀\n"] { + let shown = hidden(value); + assert_eq!(shown.encode_utf16().count(), value.encode_utf16().count(), "{value:?}"); + assert!(!shown.contains(line_break), "{value:?}"); + } + // A key with a line break in it, changed by a character, keeps the line break. + assert_eq!(replaced("a\nb", 3, 0, "c").0, "a\nbc"); + } + + #[test] + fn a_field_is_changed_when_it_shows_another_value() { + assert!(!changed(false, "a", "a") && changed(false, "a", "b")); + // A secret's stand-in is the value told before, and what it isn't is a change. + assert!(!changed(true, "a\nb", "a b") && changed(true, "a\nb", "a bc") && changed(true, "key", "")); + // The same text in a field that isn't a secret is another value. + assert!(changed(false, "a\nb", "a b")); + } + + #[test] + fn a_single_line_with_line_breaks_is_typed_in_several() { + assert!(several_lines(TextKind::Lines, "")); + for kind in [TextKind::Plain, TextKind::Verbatim, TextKind::Number] { + assert!(!several_lines(kind, "1 2")); + assert!(several_lines(kind, "1\n2") && several_lines(kind, "1\r2")); + } + assert!(!several_lines(TextKind::Secret, "a\nb"), "a secret is never shown in several lines"); + } +} diff --git a/crates/engine/src/platform.rs b/crates/engine/src/platform.rs index db08ca738b..a2da2098e3 100644 --- a/crates/engine/src/platform.rs +++ b/crates/engine/src/platform.rs @@ -62,6 +62,9 @@ pub enum TextKind { Plain, /// Text of several lines: the keyboard's Return starts a new one. Lines, + /// A line kept as it is typed (an address, a name a service knows something by): no capital + /// put at its start, nothing corrected. + Verbatim, /// A password or key: hidden as it is typed, and offered to the system's password manager. Secret, /// A number, with the keyboard for numbers. @@ -69,11 +72,12 @@ pub enum TextKind { } impl TextKind { - /// The word a shell's own half reads it by (`plain`, `lines`, `secret`, `number`). + /// The word a shell's own half reads it by (`plain`, `lines`, `verbatim`, `secret`, `number`). pub fn word(self) -> &'static str { match self { TextKind::Plain => "plain", TextKind::Lines => "lines", + TextKind::Verbatim => "verbatim", TextKind::Secret => "secret", TextKind::Number => "number", } diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index a7638d9757..c52348ddb4 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -709,8 +709,8 @@ fn field(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, field: let id = format!("assistant:setting:{}", state.entries); state.entries += 1; let (label, kind) = match field { - Field::Model => (tl!("The model's name"), TextKind::Plain), - Field::Address => (tl!("The provider's address"), TextKind::Plain), + Field::Model => (tl!("The model's name"), TextKind::Verbatim), + Field::Address => (tl!("The provider's address"), TextKind::Verbatim), _ => (tl!("The provider's API key"), TextKind::Secret), }; let provider = app.assistant.config().map(|c| c.provider.clone()).unwrap_or_default(); @@ -1212,6 +1212,13 @@ mod tests { raise(&held.ctx, Height::Full); held.frame(Vec::new()); assert!(held.find("Enter an API key.").is_some()); + // The model's name and the address are what the provider knows them by: kept as typed. + for value in ["gpt-test", provider::preset("openai").map(|p| p.base_url).unwrap()] { + let place = held.find(value).unwrap().center(); + held.touch(&[place]); + let entry = asked.borrow().last().cloned().expect("the system's text field"); + assert_eq!((entry.kind, entry.value.as_str()), (TextKind::Verbatim, value)); + } let key = held.find("paste the provider's key here").unwrap().center(); held.touch(&[key]); let entry = asked.borrow().last().cloned().expect("the system's text field"); diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 1bd33bf424..0a639b998d 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -108,9 +108,10 @@ The form has a field for each of the layer's attributes, and follows the layer's While you type in a field, the sheet stays above the soft keyboard. Tapping a text or number field opens the phone's own text box above the keyboard (Android's, or iOS's on an iPhone or iPad), so paste, suggestions, glide typing and dictation work there. The form shows the value as you type. -**Done**, the keyboard's Done or Return key, Android's Back or a tap outside the box closes it, as -turning an iPhone does: what you typed is kept, and a tap opens the box again. Text copied in -RustGIS goes on Android's clipboard too, where other apps can paste it. +**Done**, the keyboard's Done key (Return on an iPhone, where the box has one line), Android's Back +or a tap outside the box closes it, as turning an iPhone does: what you typed is kept, and a tap +opens the box again. Text copied in RustGIS goes on Android's clipboard too, where other apps can +paste it. ### Photos