Skip to main content

mgui_app_lifecycle/
lib.rs

1//! 应用级功能生命周期事件。
2//!
3//! `mgui-core` 负责 UI 节点生命周期:Element 挂载/卸载、`State::dispose`、
4//! RenderObject 引用释放。**UI 子树消失不等于业务功能结束**:切页签和关页签都会
5//! 卸载子树,但前者可能只需暂停,后者要 stop/dispose 会话。
6//!
7//! 本 crate 只提供带类型的 feature 身份、事件与队列;不替 App 做策略决策。
8//! 播放器、网络流、音频设备、文件句柄这类会话必须由 App/服务层持有,在 drain
9//! 事件后自行决定 `activate` / `deactivate` / `close` 的具体动作。
10
11#![forbid(unsafe_code)]
12
13use std::cell::RefCell;
14use std::collections::VecDeque;
15
16/// 功能身份。与裸 `usize` / nav id 区分,避免把任意整数误当成 feature。
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub struct FeatureKey(usize);
19
20impl FeatureKey {
21    pub const fn new(value: usize) -> Self {
22        Self(value)
23    }
24
25    pub const fn get(self) -> usize {
26        self.0
27    }
28}
29
30impl From<usize> for FeatureKey {
31    fn from(value: usize) -> Self {
32        Self(value)
33    }
34}
35
36/// 功能生命周期事件。
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38pub enum FeatureEvent {
39    /// 功能页成为当前页;App 决定是否恢复/续播。
40    Activated(FeatureKey),
41    /// 功能页被切走;子树会卸载,但功能未必结束。
42    Deactivated(FeatureKey),
43    /// 功能入口被关闭;App 决定 stop / dispose,以及是否保留 view 句柄。
44    Closed(FeatureKey),
45}
46
47/// 多生产者 / 单消费者事件队列。
48///
49/// 不用 `Cell<Option<_>>`:同一帧关多个功能时后写会覆盖先写,资源就漏停了。
50/// 控件回调只持有 `Rc<FeatureLifecycle>`;App 每帧 `drain()` 后统一处理。
51#[derive(Default)]
52pub struct FeatureLifecycle {
53    pending: RefCell<VecDeque<FeatureEvent>>,
54}
55
56impl FeatureLifecycle {
57    pub fn new() -> Self {
58        Self::default()
59    }
60
61    pub fn post(&self, event: FeatureEvent) {
62        self.pending.borrow_mut().push_back(event);
63    }
64
65    pub fn drain(&self) -> Vec<FeatureEvent> {
66        self.pending.borrow_mut().drain(..).collect()
67    }
68
69    pub fn len(&self) -> usize {
70        self.pending.borrow().len()
71    }
72
73    pub fn is_empty(&self) -> bool {
74        self.pending.borrow().is_empty()
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn events_are_drained_once_in_order() {
84        let bus = FeatureLifecycle::new();
85        let a = FeatureKey::new(28);
86        let b = FeatureKey::new(29);
87        assert!(bus.is_empty());
88
89        bus.post(FeatureEvent::Deactivated(a));
90        bus.post(FeatureEvent::Activated(b));
91        bus.post(FeatureEvent::Closed(a));
92        assert_eq!(bus.len(), 3);
93
94        assert_eq!(
95            bus.drain(),
96            vec![FeatureEvent::Deactivated(a), FeatureEvent::Activated(b), FeatureEvent::Closed(a),]
97        );
98        assert!(bus.is_empty());
99        assert!(bus.drain().is_empty(), "事件只能被消费一次");
100    }
101}