rust_widgets 2.0.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! iOS platform trait implementation.
//!
//! Implements the `Platform` contract for iOS mobile devices. This is a
//! state-driven backend: every widget is recorded in `BackendState<IosHandleKind>`
//! and the trait defaults cover anything the host cannot supply.
//!
//! # BLUE15: the host no longer builds UIKit controls
//!
//! This backend used to instantiate a real `UIView` per logical widget —
//! `UIButton`, `UILabel`, `UISwitch`, `UITextField`, `UITableView`, … — and then
//! forward every state mutation to the live object. Under the self-drawn strategy
//! that is exactly the duplication BLUE15 removes: the library paints every
//! `WidgetKind`, and the host owes the widget layer a **window** and a **drawing
//! surface** (rules #55/#56). A per-kind `create_*` here had no OS object to map
//! onto, so the control creators and the view registry that existed only to serve
//! them are gone (rule #59: delete means delete).
//!
//! What survives is the platform-facing part the library cannot replace: the
//! window lifecycle, the runtime loop, `UIPrintInteractionController`-backed facts
//! reported honestly (see `spawn_print_job`), the clipboard, IME flags,
//! accessibility names, and the injectable menu / widget-trigger queues.
//!
//! ## Menu / status-bar semantics (iOS)
//!
//! iOS has no desktop `MenuBar`/`StatusBar` chrome. These handles are modelled
//! as **in-process data**: kind-constrained parents, textual payload, and
//! injectable trigger events. They are intentionally *not* advertised as native
//! menu capability (`capabilities().native_menu == false`) and never attached to
//! a UIKit view. Apps that need UIKit contextual menus should build them from the
//! same data instead of treating these handles as native menus.

use super::types::{IosHandleKind, IosMobilePlatform};
use crate::core::PlatformFamily;
use crate::platform::{
    DropEvent, Platform, PlatformCapabilities, WidgetTriggerEvent, WidgetTriggerKind,
};
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;

impl Platform for IosMobilePlatform {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn backend_name(&self) -> &'static str {
        "ios-state-backend"
    }

    fn family(&self) -> PlatformFamily {
        PlatformFamily::Mobile
    }

    /// Reads `MemTotal` from `/proc/meminfo` via [`os_probes`].
    fn total_memory_mb(&self) -> Option<u64> {
        crate::platform::os_probes::total_memory_mb()
    }

    /// Reports whether any battery in `/sys/class/power_supply` is discharging.
    fn is_on_battery(&self) -> bool {
        crate::platform::os_probes::is_on_battery()
    }

    /// Samples RSS over VmSize for this process from `/proc/self/status`.
    fn process_memory_utilization(&self) -> Option<f32> {
        crate::platform::os_probes::process_memory_utilization()
    }

    /// Estimates CPU load as thread count over twice the available cores.
    fn process_cpu_utilization(&self) -> Option<f32> {
        crate::platform::os_probes::process_cpu_utilization()
    }

    /// iOS printing goes through `UIPrintInteractionController`, not a spooler
    /// command, so this state backend cannot submit a job file.
    fn spawn_print_job(&self, _job_file: &std::path::Path) -> Result<(), String> {
        Err("iOS printing requires UIPrintInteractionController (not bound)".to_string())
    }

    /// iOS uses the same AppKit-style accelerator symbols as macOS (`⌘⇧Z`).
    fn shortcut_style(&self) -> crate::shortcut::PlatformShortcutStyle {
        crate::shortcut::PlatformShortcutStyle::Mac
    }

    #[cfg(feature = "mobile-api")]
    fn mobile_extension(&self) -> Option<&dyn crate::platform::types::MobilePlatformExtension> {
        Some(self)
    }

    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities {
            dpi_scaling: true,
            ime: true,
            accessibility: true,
            native_menu: false,
            typed_widget_trigger: true,
        }
    }

    fn init(&self) {
        let _ = self.ios_runtime_marker();
        self.runtime.initialized.store(true, Ordering::SeqCst);
    }

    fn run(&self) {
        if !self.runtime.initialized.load(Ordering::SeqCst) {
            self.init();
        }
        // iOS state backend uses polling loop for deterministic behavior.
        self.runtime.running.store(true, Ordering::SeqCst);
        while self.runtime.running.load(Ordering::SeqCst) {
            thread::sleep(Duration::from_millis(16));
        }
    }

    fn quit(&self) {
        self.runtime.running.store(false, Ordering::SeqCst);
    }

    fn destroy_widget(&self, widget_id: u64) -> bool {
        // The state record is the authority on whether the widget existed.
        let existed = self.state.destroy_widget(widget_id);

        // Drop the per-widget list storage for both list-backed widgets. Each lock
        // is released at the end of its statement so no two guards are held at once.

        // Drop the menu bookkeeping that names this widget: attached menu-bar
        // ownership, membership in a parent menu's child list, and any queued
        // trigger that would otherwise fire for a widget that no longer exists.
        let mut menus = self.menus.lock().expect("ios menus lock poisoned");
        menus.attached_menu_bar.retain(|_window, menu_bar| *menu_bar != widget_id);
        let destroyed_children = menus.menu_children.remove(&widget_id);
        menus.menu_children.retain(|_parent, children| {
            children.retain(|child| *child != widget_id);
            !children.is_empty()
        });
        menus.pending_menu_events.retain(|queued| *queued != widget_id);
        drop(menus);

        // A destroyed `Menu` owns child menu items that were only reachable
        // through it; cascade the teardown so those items are not orphaned.
        for child in destroyed_children.into_iter().flatten() {
            self.destroy_widget(child);
        }

        existed
    }

    // ─── Window ───

    /// Creates the host window and records it.
    ///
    /// The window is the one OS object this backend creates. Under self-drawing the
    /// *controls* are the library's job (BLUE15 #55/#56), but a window is not: iOS
    /// requires a real `UIWindow` to have a place to draw into at all, which is why
    /// `native::create_ui_window` exists.
    ///
    /// Calling it is what makes the FFI helper live rather than orphaned. It is
    /// gated on the real iOS target, because the helper is compiled only there; the
    /// backend's state machine still runs on every host so its tests stay
    /// executable, and that is why the call is inside a `cfg` rather than around it.
    /// The UIKit handle is deliberately **not** stored: no control mutator needs it,
    /// and the library paints through the surface attached via
    /// `MobilePlatformExtension::attach_to_native_view`.
    fn create_window(&self, title: &str, x: i32, y: i32, width: u32, height: u32) -> u64 {
        let id = self.insert_widget(IosHandleKind::Window, title, x, y, width, height);

        #[cfg(all(target_os = "ios", feature = "ios-uikit-ffi"))]
        if let Some(mtm) = objc2::MainThreadMarker::new() {
            // The window must exist for the surface to have a superview. Dropping the
            // `Retained<UIWindow>` is correct: UIKit owns it from
            // `makeKeyAndVisible()`, and leaking the Rust handle would keep a
            // reference past the app's lifetime.
            let _window = super::native::create_ui_window(mtm, title, x, y, width, height);
        }

        id
    }

    fn set_widget_text(&self, widget_id: u64, text: &str) {
        let _ = self.state.set_text(widget_id, text);
    }

    fn set_widget_geometry(&self, widget_id: u64, x: i32, y: i32, width: u32, height: u32) {
        self.state.set_geometry(widget_id, x, y, width, height);
    }

    fn set_widget_ime_enabled(&self, widget_id: u64, enabled: bool) -> bool {
        self.state.set_ime_enabled(widget_id, enabled)
    }

    fn is_widget_ime_enabled(&self, widget_id: u64) -> bool {
        self.state.ime_enabled(widget_id)
    }

    fn set_widget_accessibility_name(&self, widget_id: u64, name: &str) -> bool {
        self.state.set_accessibility_name(widget_id, name)
    }

    fn get_widget_accessibility_name(&self, widget_id: u64) -> String {
        self.state.accessibility_name(widget_id)
    }

    fn set_clipboard_text(&self, text: &str) -> bool {
        self.state.set_clipboard_text(text)
    }

    fn get_clipboard_text(&self) -> String {
        self.state.clipboard_text()
    }

    fn begin_drag(&self, source_widget_id: u64, mime: &str, payload: &[u8]) -> bool {
        self.state.begin_drag(source_widget_id, mime, payload)
    }

    fn poll_drop_event(&self) -> Option<DropEvent> {
        self.state.pop_drop_event()
    }

    fn inject_drop_event(&self, event: DropEvent) -> bool {
        self.state.inject_drop_event(event)
    }

    // ─── Menu Bar / Menu / Menu Item ───
    //
    // iOS has no desktop menu chrome, and no native menu protocol either. These
    // handles are an in-process data model: MenuBar is owned by a Window, Menu
    // belongs to a MenuBar/Menu, and MenuItem belongs to a Menu. Triggers are
    // delivered through the injectable `pending_menu_events` queue, so the library's
    // own menu widget can report activations; `capabilities().native_menu` stays
    // false, because no OS menu object is created.
    //
    // They survive the self-drawing change for the same reason the window does: the
    // host owns the menu *identity* an OS menu surface would need, while the library
    // paints the menu *appearance*.

    fn create_menu_bar(&self, parent: u64, x: i32, y: i32, width: u32, height: u32) -> u64 {
        if !matches!(self.kind_of(parent), Some(IosHandleKind::Window)) {
            return 0;
        }
        self.insert_widget(IosHandleKind::MenuBar, "MenuBar", x, y, width, height)
    }

    fn create_menu(&self, parent: u64, text: &str, x: i32, y: i32, width: u32, height: u32) -> u64 {
        // A menu hangs off a menu bar or another menu.
        if !matches!(self.kind_of(parent), Some(IosHandleKind::MenuBar) | Some(IosHandleKind::Menu))
        {
            return 0;
        }
        self.insert_widget(IosHandleKind::Menu, text, x, y, width, height)
    }

    fn attach_menu_bar_to_window(&self, window: u64, menu_bar: u64) -> bool {
        if !matches!(self.kind_of(window), Some(IosHandleKind::Window)) {
            return false;
        }
        if !matches!(self.kind_of(menu_bar), Some(IosHandleKind::MenuBar)) {
            return false;
        }
        let mut menus = self.menus.lock().expect("ios menus lock poisoned");
        menus.attached_menu_bar.insert(window, menu_bar);
        true
    }

    fn menu_add_item(&self, parent_menu: u64, text: &str, _shortcut: Option<&str>) -> u64 {
        if !matches!(self.kind_of(parent_menu), Some(IosHandleKind::Menu)) {
            return 0;
        }
        let id = self.insert_widget(IosHandleKind::MenuItem, text, 0, 0, 0, 0);

        let mut menus = self.menus.lock().expect("ios menus lock poisoned");
        menus.menu_children.entry(parent_menu).or_default().push(id);

        id
    }

    fn poll_menu_triggered(&self) -> Option<u64> {
        self.menus.lock().expect("ios menus lock poisoned").pending_menu_events.pop_front()
    }

    fn inject_menu_trigger(&self, menu_item_id: u64) -> bool {
        if !matches!(self.kind_of(menu_item_id), Some(IosHandleKind::MenuItem)) {
            return false;
        }
        self.menus
            .lock()
            .expect("ios menus lock poisoned")
            .pending_menu_events
            .push_back(menu_item_id);
        true
    }

    // ─── Widget Trigger Events ───

    fn poll_widget_triggered(&self) -> Option<u64> {
        self.poll_widget_trigger_event().map(|event| event.widget_id)
    }

    fn poll_widget_trigger_event(&self) -> Option<WidgetTriggerEvent> {
        self.state.pop_widget_event()
    }

    fn inject_widget_trigger_event(&self, widget_id: u64, kind: WidgetTriggerKind) -> bool {
        if self.kind_of(widget_id).is_none() {
            return false;
        }
        self.state.push_widget_event(WidgetTriggerEvent { widget_id, kind });
        true
    }

    // ─── Tool Bar / Status Bar ───

    // ─── Message Box ───

    // ─── Dialogs (state-only on iOS) ───

    // ─── Spin Box ───

    // ─── List View ───

    // ─── Show / Hide ───

    fn show_widget(&self, widget_id: u64) {
        self.state.set_visible(widget_id, true);
    }

    fn hide_widget(&self, widget_id: u64) {
        self.state.set_visible(widget_id, false);
    }

    // ─── Enabled / Visible ───

    fn set_widget_enabled(&self, widget_id: u64, enabled: bool) {
        self.state.set_enabled(widget_id, enabled);
    }

    fn is_widget_enabled(&self, widget_id: u64) -> bool {
        self.state.enabled(widget_id)
    }

    fn set_widget_visible(&self, widget_id: u64, visible: bool) {
        self.state.set_visible(widget_id, visible);
    }

    fn is_widget_visible(&self, widget_id: u64) -> bool {
        self.state.visible(widget_id)
    }
}

#[cfg(all(test, not(alloc_frugal)))]
mod tests {
    use super::*;

    #[test]
    fn ios_platform_window_creation() {
        let platform = IosMobilePlatform::new();
        platform.init();

        let window_id = platform.create_window("Test Window", 0, 0, 320, 568);
        assert_ne!(window_id, 0);

        assert_eq!(platform.backend_name(), "ios-state-backend");
        assert_eq!(platform.family(), PlatformFamily::Mobile);
    }

    /// A control id must never address something the host did not create.
    ///
    /// This replaces a test that asserted the opposite — that a `create_button` under
    /// a valid window produced a live id — because the host no longer builds
    /// controls. Asserting `0` for both a bad *and* a good parent is what makes the
    /// answer meaningful: the id is absent, not merely parent-sensitive.
    #[test]
    fn control_members_report_absence_for_every_parent() {
        let platform = IosMobilePlatform::new();
        platform.init();

        assert_eq!(platform.create_button(999, "Button", 0, 0, 80, 44), 0);

        let window_id = platform.create_window("Window", 0, 0, 320, 568);
        assert_ne!(window_id, 0);
        assert_eq!(platform.create_button(window_id, "Button", 0, 0, 80, 44), 0);
    }

    /// The list/combo data members are gone with the controls that backed them, so
    /// their trait defaults must report failure rather than accept writes into a
    /// model nothing can read.
    #[test]
    fn list_and_combo_data_members_report_failure() {
        let platform = IosMobilePlatform::new();
        platform.init();

        let window_id = platform.create_window("Window", 0, 0, 320, 568);
        assert!(!platform.list_box_add_item(window_id, "Item 1"));
        assert!(!platform.list_box_clear_items(window_id));
        assert!(!platform.combo_box_add_item(window_id, "Item 1"));
        assert_eq!(platform.combo_box_item_count(window_id), 0);
    }

    #[cfg(all(feature = "serde_json", feature = "serde", widgets_unstripped))]
    #[test]
    fn ios_platform_state_serialization() {
        let platform = IosMobilePlatform::new();
        platform.init();

        let _window_id = platform.create_window("Window", 0, 0, 320, 568);
        let result = platform.serialize_state();
        assert!(result.is_ok());
    }

    #[test]
    fn ios_platform_reports_explicit_mobile_capabilities() {
        let platform = IosMobilePlatform::new();
        let caps = platform.capabilities();

        assert_eq!(platform.family(), PlatformFamily::Mobile);
        assert!(caps.dpi_scaling);
        assert!(caps.ime);
        assert!(caps.accessibility);
        assert!(!caps.native_menu);
        assert!(caps.typed_widget_trigger);
    }

    /// The host must create **no** control: the library paints every `WidgetKind`,
    /// so a `create_*` that answered with a live id would announce a capability the
    /// backend does not have (BLUE15 #55/#56). The trait defaults report `0`, and
    /// this pins that — a regression here would mean a control was reintroduced.
    #[test]
    fn host_creates_no_controls_only_a_window() {
        let platform = IosMobilePlatform::new();
        platform.init();

        let window = platform.create_window("Window", 0, 0, 320, 568);
        assert_ne!(window, 0, "the window is the one primitive the host owns");
        assert_eq!(platform.kind_of(window), Some(IosHandleKind::Window));

        // Every control member now inherits the trait default, which reports that
        // this host provides no such primitive rather than inventing an id.
        assert_eq!(platform.create_button(window, "OK", 0, 0, 80, 44), 0);
        assert_eq!(platform.create_label(window, "hi", 0, 0, 80, 44), 0);
        assert_eq!(platform.create_list_box(window, 0, 0, 320, 120), 0);
        assert_eq!(platform.create_combo_box(window, 0, 0, 160, 44), 0);
    }

    #[test]
    fn ios_platform_capabilities_describe_a_self_drawn_host() {
        let platform = IosMobilePlatform::new();
        let caps = platform.capabilities();

        // iOS ships no native menu bar; the menu model is in-process bookkeeping,
        // which is why the capability is advertised as `false`.
        assert!(!caps.native_menu);
        assert!(caps.typed_widget_trigger);
    }
}