rust_widgets 2.8.4

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Application lifecycle management — foreground/background state tracking,
//! state save/restore, and lifecycle event notification.

use crate::compat::Instant;
#[cfg(all(feature = "serde", widgets_unstripped))]
use serde::{Deserialize, Serialize};

/// Application lifecycle states
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(all(feature = "serde", widgets_unstripped), derive(Serialize, Deserialize))]
pub enum AppLifecycleState {
    /// Application is starting up
    Starting,
    /// Application is running in foreground
    Foreground,
    /// Application is running in background
    Background,
    /// Application is being suspended
    Suspended,
    /// Application is terminating
    Terminating,
}

impl AppLifecycleState {
    /// Returns `true` if the application is actively processing user input
    /// in the foreground.
    pub fn is_active(&self) -> bool {
        matches!(self, AppLifecycleState::Foreground)
    }

    /// Returns `true` if the application's UI is visible to the user
    /// (either starting up or in the foreground).
    pub fn is_visible(&self) -> bool {
        matches!(self, AppLifecycleState::Foreground | AppLifecycleState::Starting)
    }
}

/// Lifecycle event that listeners can subscribe to
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LifecycleEvent {
    /// Application is about to enter the foreground
    WillEnterForeground,
    /// Application has entered the foreground
    DidEnterForeground,
    /// Application is about to enter the background
    WillEnterBackground,
    /// Application has entered the background
    DidEnterBackground,
    /// Application is about to terminate
    WillTerminate,
    /// System memory warning received
    MemoryWarning,
    /// State has been restored from a previous session
    StateRestored,
}

/// Callback type for lifecycle events
pub type LifecycleCallback = Box<dyn FnMut(LifecycleEvent) + Send>;

// ── Serializable snapshot for state save/restore ─────────────

/// Upper bound on a restorable `total_background_secs`.
///
/// `Duration::from_secs_f64` panics above `u64::MAX` seconds; this bound is a little
/// under that so the conversion is always in range, and it is used to reject an
/// implausible persisted value with a field-tagged error rather than a panic.
#[cfg(all(feature = "serde_json", feature = "serde", widgets_unstripped))]
const MAX_BACKGROUND_SECS: f64 = (u64::MAX as f64) / 2.0;

/// Intermediate serializable representation of the lifecycle state.
#[derive(Debug, Clone)]
#[cfg_attr(all(feature = "serde", widgets_unstripped), derive(Serialize, Deserialize))]
struct LifecycleSnapshot {
    state: AppLifecycleState,
    total_background_secs: f64,
}

// ── AppLifecycle ─────────────────────────────────────────────

/// Application lifecycle manager.
///
/// Tracks the current lifecycle state, elapsed foreground/background time,
/// and notifies registered listeners on state transitions.
///
/// # Example
///
/// ```rust
/// use rust_widgets::app::lifecycle::{AppLifecycle, AppLifecycleState, LifecycleEvent};
///
/// let mut lc = AppLifecycle::new();
/// assert!(lc.state().is_visible());
///
/// lc.transition(AppLifecycleState::Foreground);
/// assert!(lc.state().is_active());
/// ```
pub struct AppLifecycle {
    state: AppLifecycleState,
    started_at: Instant,
    background_entry: Option<Instant>,
    total_background_duration: std::time::Duration,
    listeners: Vec<LifecycleCallback>,
}

impl AppLifecycle {
    /// Create a new lifecycle manager in the [`Starting`](AppLifecycleState::Starting) state.
    pub fn new() -> Self {
        Self {
            state: AppLifecycleState::Starting,
            started_at: Instant::now(),
            background_entry: None,
            total_background_duration: std::time::Duration::ZERO,
            listeners: Vec::new(),
        }
    }

    /// Transition to a new state and notify listeners of any events that
    /// should fire as a result of the transition.
    ///
    /// The method emits the appropriate pair of `Will*` / `Did*` events
    /// based on the old and new state.
    pub fn transition(&mut self, new_state: AppLifecycleState) {
        let old_state = self.state;
        if old_state == new_state {
            return;
        }

        // Track time spent in background. `Background` and `Suspended` are both
        // background intervals: `total_background_duration` and `deserialize_state`
        // already count `Suspended` as background, so the transition must accumulate
        // and (re)start the interval consistently for both. The old code only started
        // an entry on `new_state == Background` and only accumulated on
        // `old_state == Background`, so `Foreground -> Suspended` never started an
        // entry, `Background -> Suspended` took the old entry and started none, and
        // `Suspended -> Foreground` cleared the entry without accumulating it — each
        // losing the suspended interval. Treating the two states uniformly means an
        // interval is started when entering either and accumulated exactly once when
        // leaving either.
        let was_background =
            matches!(old_state, AppLifecycleState::Background | AppLifecycleState::Suspended);
        let is_background =
            matches!(new_state, AppLifecycleState::Background | AppLifecycleState::Suspended);
        if was_background {
            if let Some(entry) = self.background_entry.take() {
                self.total_background_duration += entry.elapsed();
            }
        }
        // Start a fresh interval on entering a background state, and clear it when
        // leaving both, so no stale entry survives into a foreground state.
        self.background_entry = if is_background { Some(Instant::now()) } else { None };

        self.state = new_state;

        // Emit lifecycle events based on the transition.
        match (old_state, new_state) {
            (AppLifecycleState::Background, AppLifecycleState::Foreground)
            | (AppLifecycleState::Suspended, AppLifecycleState::Foreground)
            | (AppLifecycleState::Starting, AppLifecycleState::Foreground) => {
                self.fire(LifecycleEvent::WillEnterForeground);
                self.fire(LifecycleEvent::DidEnterForeground);
            }
            (AppLifecycleState::Foreground, AppLifecycleState::Background) => {
                self.fire(LifecycleEvent::WillEnterBackground);
                self.fire(LifecycleEvent::DidEnterBackground);
            }
            (AppLifecycleState::Foreground, AppLifecycleState::Suspended) => {
                self.fire(LifecycleEvent::WillEnterBackground);
                self.fire(LifecycleEvent::DidEnterBackground);
            }
            (_, AppLifecycleState::Terminating) => {
                self.fire(LifecycleEvent::WillTerminate);
            }
            _ => {}
        }
    }

    /// Return the current lifecycle state.
    pub fn state(&self) -> AppLifecycleState {
        self.state
    }

    /// How long the application has been running (wall-clock time since
    /// construction or since the state was last restored).
    pub fn uptime(&self) -> std::time::Duration {
        self.started_at.elapsed()
    }

    /// Total accumulated time the application has spent in the background.
    pub fn total_background_duration(&self) -> std::time::Duration {
        let active = self.background_entry.map_or(std::time::Duration::ZERO, |entry| {
            if self.state == AppLifecycleState::Background
                || self.state == AppLifecycleState::Suspended
            {
                entry.elapsed()
            } else {
                std::time::Duration::ZERO
            }
        });
        self.total_background_duration + active
    }

    /// Register a lifecycle event listener.
    ///
    /// The callback will be invoked for every lifecycle event the manager emits.
    pub fn add_listener(&mut self, callback: LifecycleCallback) {
        self.listeners.push(callback);
    }

    /// Notify all registered listeners of a lifecycle event.
    fn fire(&mut self, event: LifecycleEvent) {
        for cb in &mut self.listeners {
            cb(event);
        }
    }

    /// Serialize current lifecycle state to a JSON string for persistence.
    ///
    /// The serialized data can later be passed to [`deserialize_state`](Self::deserialize_state)
    /// to restore the background-duration accounting. Listeners are **not**
    /// serialized because they are code (not data).
    #[cfg(all(feature = "serde_json", feature = "serde", widgets_unstripped))]
    pub fn serialize_state(&self) -> Result<String, String> {
        let snapshot = LifecycleSnapshot {
            state: self.state,
            total_background_secs: self.total_background_duration().as_secs_f64(),
        };
        serde_json::to_string(&snapshot).map_err(|e| {
            format!("lifecycle snapshot could not be serialized to JSON (serde_json failed): {e}")
        })
    }

    /// Restore lifecycle state from previously serialized JSON data.
    ///
    /// The returned [`AppLifecycle`] starts in the state recorded in the
    /// snapshot, and its `started_at` clock is reset to the current time
    /// (so [`uptime`](Self::uptime) measures the time since restoration).
    #[cfg(all(feature = "serde_json", feature = "serde", widgets_unstripped))]
    pub fn deserialize_state(data: &str) -> Result<Self, String> {
        let snapshot: LifecycleSnapshot = serde_json::from_str(data).map_err(|e| {
            format!(
                "lifecycle state ({} bytes) is not valid LifecycleSnapshot JSON: {e}",
                data.len()
            )
        })?;
        // Validate before `Duration::from_secs_f64`, which panics (it does not return an
        // error) for a negative, NaN, or too-large input. A persisted snapshot is
        // untrusted data — `{"state":"Foreground","total_background_secs":-1}` used to
        // abort the process — so a bad value is reported as a field-tagged `Err` instead.
        let secs = snapshot.total_background_secs;
        if !secs.is_finite() {
            return Err(format!(
                "lifecycle field 'total_background_secs' must be finite, got {secs}; refusing to \
                 restore the snapshot"
            ));
        }
        if secs < 0.0 {
            return Err(format!(
                "lifecycle field 'total_background_secs' must not be negative, got {secs}; \
                 refusing to restore the snapshot"
            ));
        }
        if secs > MAX_BACKGROUND_SECS {
            return Err(format!(
                "lifecycle field 'total_background_secs' is too large ({secs} exceeds the \
                 supported maximum of {MAX_BACKGROUND_SECS}); refusing to restore the snapshot"
            ));
        }
        let mut lc = Self {
            state: snapshot.state,
            started_at: Instant::now(),
            background_entry: None,
            total_background_duration: std::time::Duration::from_secs_f64(secs),
            listeners: Vec::new(),
        };
        // If the snapshot was in a background/suspended state, start tracking
        // the new background interval from now.
        if snapshot.state == AppLifecycleState::Background
            || snapshot.state == AppLifecycleState::Suspended
        {
            lc.background_entry = Some(Instant::now());
        }
        lc.fire(LifecycleEvent::StateRestored);
        Ok(lc)
    }

    /// Emit a synthetic [`LifecycleEvent::MemoryWarning`] to all listeners.
    /// This is typically called by the platform when the system is low on memory.
    pub fn emit_memory_warning(&mut self) {
        self.fire(LifecycleEvent::MemoryWarning);
    }
}

crate::impl_default_via_new!(AppLifecycle);

// ═══════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::sync::Arc;
    use core::sync::atomic::{AtomicUsize, Ordering};
    use core::time::Duration;

    // ── 1. State transitions ──────────────────────────────────

    #[test]
    fn test_state_transitions() {
        let mut lc = AppLifecycle::new();
        assert_eq!(lc.state(), AppLifecycleState::Starting);
        assert!(lc.state().is_visible());
        assert!(!lc.state().is_active());

        lc.transition(AppLifecycleState::Foreground);
        assert_eq!(lc.state(), AppLifecycleState::Foreground);
        assert!(lc.state().is_active());
        assert!(lc.state().is_visible());

        lc.transition(AppLifecycleState::Background);
        assert_eq!(lc.state(), AppLifecycleState::Background);
        assert!(!lc.state().is_active());
        assert!(!lc.state().is_visible());

        lc.transition(AppLifecycleState::Suspended);
        assert_eq!(lc.state(), AppLifecycleState::Suspended);
        assert!(!lc.state().is_active());
        assert!(!lc.state().is_visible());

        lc.transition(AppLifecycleState::Terminating);
        assert_eq!(lc.state(), AppLifecycleState::Terminating);
    }

    // ── 2. Transition to same state is a no-op ────────────────

    #[test]
    fn test_same_state_transition_noop() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);
        let call_count = Arc::new(AtomicUsize::new(0));
        let count = Arc::clone(&call_count);
        lc.add_listener(Box::new(move |_| {
            count.fetch_add(1, Ordering::SeqCst);
        }));
        // Transition to foreground again — should be a no-op.
        lc.transition(AppLifecycleState::Foreground);
        assert_eq!(call_count.load(Ordering::SeqCst), 0);
    }

    // ── 3. Listener notification ──────────────────────────────

    #[test]
    fn test_listener_notification() {
        let mut lc = AppLifecycle::new();
        let events = Arc::new(std::sync::Mutex::new(Vec::new()));
        let ev = Arc::clone(&events);
        lc.add_listener(Box::new(move |e| {
            ev.lock().unwrap().push(e);
        }));

        lc.transition(AppLifecycleState::Foreground);
        lc.transition(AppLifecycleState::Background);
        lc.transition(AppLifecycleState::Terminating);

        let recorded = events.lock().unwrap();
        assert_eq!(recorded.len(), 5);
        assert_eq!(recorded[0], LifecycleEvent::WillEnterForeground);
        assert_eq!(recorded[1], LifecycleEvent::DidEnterForeground);
        assert_eq!(recorded[2], LifecycleEvent::WillEnterBackground);
        assert_eq!(recorded[3], LifecycleEvent::DidEnterBackground);
        assert_eq!(recorded[4], LifecycleEvent::WillTerminate);
    }

    // ── 4. Serialization roundtrip ────────────────────────────

    #[test]
    fn test_serialization_roundtrip() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);

        // Add some background time. The state semantics are deterministic, but
        // `total_background_duration` is measured from `Instant` deltas, so two
        // back-to-back transitions can land in the same clock tick and record zero
        // — which is what made this assertion scheduler-dependent. Sleeping is the
        // same convention `test_background_duration_accumulates` uses.
        lc.transition(AppLifecycleState::Background);
        std::thread::sleep(Duration::from_millis(5));
        lc.transition(AppLifecycleState::Foreground);

        let json = lc.serialize_state().expect("serialize_state should succeed");
        let restored =
            AppLifecycle::deserialize_state(&json).expect("deserialize_state should succeed");

        // State should match.
        assert_eq!(restored.state(), AppLifecycleState::Foreground);

        // Total background should be greater than zero.
        assert!(restored.total_background_duration() > Duration::ZERO);
    }

    // ── 5. Uptime tracking ────────────────────────────────────

    #[test]
    fn test_uptime_increases() {
        let lc = AppLifecycle::new();
        let u1 = lc.uptime();
        std::thread::sleep(Duration::from_millis(10));
        let u2 = lc.uptime();
        assert!(u2 >= u1 + Duration::from_millis(5));
    }

    // ── 6. Background duration accumulation ───────────────────

    #[test]
    fn test_background_duration_accumulates() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);
        assert_eq!(lc.total_background_duration(), Duration::ZERO);

        lc.transition(AppLifecycleState::Background);
        std::thread::sleep(Duration::from_millis(10));
        lc.transition(AppLifecycleState::Foreground);

        let bg = lc.total_background_duration();
        assert!(bg >= Duration::from_millis(5));
        // Transitioning again should accumulate further.
        lc.transition(AppLifecycleState::Background);
        std::thread::sleep(Duration::from_millis(5));
        lc.transition(AppLifecycleState::Foreground);
        let bg2 = lc.total_background_duration();
        assert!(bg2 > bg);
    }

    // ── 7. Memory warning notification ────────────────────────

    #[test]
    fn test_memory_warning() {
        let mut lc = AppLifecycle::new();
        let warned = Arc::new(AtomicUsize::new(0));
        let w = Arc::clone(&warned);
        lc.add_listener(Box::new(move |e| {
            if e == LifecycleEvent::MemoryWarning {
                w.fetch_add(1, Ordering::SeqCst);
            }
        }));
        lc.emit_memory_warning();
        assert_eq!(warned.load(Ordering::SeqCst), 1);
    }

    // ── 8. Deserialize preserves state across roundtrips ────────

    #[test]
    fn test_deserialize_preserves_state() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);
        let json = lc.serialize_state().unwrap();

        let d = AppLifecycle::deserialize_state(&json).unwrap();
        assert_eq!(d.state(), AppLifecycleState::Foreground);
        assert!(d.state().is_active());
        assert!(d.state().is_visible());

        // Also test that deserialize resets the clock.
        // uptime at deserialized instance should be near zero.
        assert!(d.uptime() < Duration::from_millis(100));
    }

    // ── 9. N-S-71: deserialize validates the background-seconds field ──

    /// A negative `total_background_secs` must be rejected, not panic.
    ///
    /// `Duration::from_secs_f64` panics on a negative input, so
    /// `{"state":"Foreground","total_background_secs":-1}` aborted the process when a
    /// persisted snapshot was restored. The field is validated first and reported as a
    /// Result::Err naming the field.
    #[test]
    fn deserialize_rejects_negative_background_secs() {
        let result =
            AppLifecycle::deserialize_state(r#"{"state":"Foreground","total_background_secs":-1}"#);
        let error = result.err().expect("a negative duration must be rejected, not accepted");
        assert!(
            error.contains("total_background_secs"),
            "the error must name the offending field: {error}"
        );
    }

    /// A non-finite `total_background_secs` (NaN/infinity) must be rejected, not panic.
    #[test]
    fn deserialize_rejects_non_finite_background_secs() {
        // `serde_json` will not parse `NaN`/`inf` from a bare JSON literal, so build the
        // out-of-range value via the largest finite spelling that still overflows the
        // conversion.
        let result = AppLifecycle::deserialize_state(
            r#"{"state":"Foreground","total_background_secs":1e308}"#,
        );
        let error = result.err().expect("an out-of-range duration must be rejected, not accepted");
        assert!(
            error.contains("total_background_secs"),
            "the error must name the offending field: {error}"
        );
    }

    /// Zero and an ordinary value must round-trip without being rejected.
    #[test]
    fn deserialize_accepts_zero_and_a_normal_duration() {
        let zero = AppLifecycle::deserialize_state(
            r#"{"state":"Foreground","total_background_secs":0.0}"#,
        )
        .expect("zero must be accepted");
        assert_eq!(zero.total_background_duration(), Duration::ZERO);

        let normal = AppLifecycle::deserialize_state(
            r#"{"state":"Foreground","total_background_secs":12.5}"#,
        )
        .expect("a normal duration must be accepted");
        assert_eq!(normal.total_background_duration(), Duration::from_secs_f64(12.5));
    }

    // ── 10. N-S-72: Suspended is a background interval like Background ──

    /// The transition sequence Foreground -> Suspended -> Foreground must accumulate the
    /// suspended interval, so time spent suspended counts as background.
    #[test]
    fn suspended_counts_as_background_time() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);
        assert_eq!(lc.total_background_duration(), Duration::ZERO);

        lc.transition(AppLifecycleState::Suspended);
        std::thread::sleep(Duration::from_millis(10));
        // While suspended the live interval must be counted.
        assert!(lc.total_background_duration() >= Duration::from_millis(5));

        lc.transition(AppLifecycleState::Foreground);
        let after = lc.total_background_duration();
        assert!(after >= Duration::from_millis(5), "the suspended interval must be accumulated");
    }

    /// Background -> Suspended must not lose the background interval, and must start a
    /// fresh interval for the suspended period (which is accumulated on leaving).
    #[test]
    fn background_to_suspended_keeps_both_intervals() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);

        lc.transition(AppLifecycleState::Background);
        std::thread::sleep(Duration::from_millis(8));
        lc.transition(AppLifecycleState::Suspended);
        std::thread::sleep(Duration::from_millis(8));
        lc.transition(AppLifecycleState::Foreground);

        let total = lc.total_background_duration();
        assert!(
            total >= Duration::from_millis(12),
            "both the background and the suspended intervals must be counted, got {total:?}"
        );
    }

    /// A foreground state must never leave a background interval running.
    #[test]
    fn a_foreground_state_has_no_open_interval() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);
        lc.transition(AppLifecycleState::Background);
        lc.transition(AppLifecycleState::Foreground);
        // Asleep time in the foreground must not accrue background.
        let before = lc.total_background_duration();
        std::thread::sleep(Duration::from_millis(10));
        assert_eq!(lc.total_background_duration(), before);
    }

    /// A snapshot taken while Suspended restores with a live interval, so post-restore
    /// time is counted as background (matching Background's behaviour).
    #[test]
    fn deserialize_from_suspended_tracks_background() {
        let mut lc = AppLifecycle::new();
        lc.transition(AppLifecycleState::Foreground);
        lc.transition(AppLifecycleState::Suspended);
        std::thread::sleep(Duration::from_millis(5));
        let json = lc.serialize_state().unwrap();

        let restored =
            AppLifecycle::deserialize_state(&json).expect("a suspended snapshot restores");
        assert_eq!(restored.state(), AppLifecycleState::Suspended);
        assert!(
            restored.total_background_duration() > Duration::ZERO,
            "a restored suspended state must keep counting background time"
        );
    }
}