mgui-app-lifecycle 0.6.0

应用级功能生命周期事件与队列:Activated / Deactivated / Closed,零依赖
Documentation
//! 应用级功能生命周期事件。
//!
//! `mgui-core` 负责 UI 节点生命周期:Element 挂载/卸载、`State::dispose`、
//! RenderObject 引用释放。**UI 子树消失不等于业务功能结束**:切页签和关页签都会
//! 卸载子树,但前者可能只需暂停,后者要 stop/dispose 会话。
//!
//! 本 crate 只提供带类型的 feature 身份、事件与队列;不替 App 做策略决策。
//! 播放器、网络流、音频设备、文件句柄这类会话必须由 App/服务层持有,在 drain
//! 事件后自行决定 `activate` / `deactivate` / `close` 的具体动作。

#![forbid(unsafe_code)]

use std::cell::RefCell;
use std::collections::VecDeque;

/// 功能身份。与裸 `usize` / nav id 区分,避免把任意整数误当成 feature。
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FeatureKey(usize);

impl FeatureKey {
    pub const fn new(value: usize) -> Self {
        Self(value)
    }

    pub const fn get(self) -> usize {
        self.0
    }
}

impl From<usize> for FeatureKey {
    fn from(value: usize) -> Self {
        Self(value)
    }
}

/// 功能生命周期事件。
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FeatureEvent {
    /// 功能页成为当前页;App 决定是否恢复/续播。
    Activated(FeatureKey),
    /// 功能页被切走;子树会卸载,但功能未必结束。
    Deactivated(FeatureKey),
    /// 功能入口被关闭;App 决定 stop / dispose,以及是否保留 view 句柄。
    Closed(FeatureKey),
}

/// 多生产者 / 单消费者事件队列。
///
/// 不用 `Cell<Option<_>>`:同一帧关多个功能时后写会覆盖先写,资源就漏停了。
/// 控件回调只持有 `Rc<FeatureLifecycle>`;App 每帧 `drain()` 后统一处理。
#[derive(Default)]
pub struct FeatureLifecycle {
    pending: RefCell<VecDeque<FeatureEvent>>,
}

impl FeatureLifecycle {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn post(&self, event: FeatureEvent) {
        self.pending.borrow_mut().push_back(event);
    }

    pub fn drain(&self) -> Vec<FeatureEvent> {
        self.pending.borrow_mut().drain(..).collect()
    }

    pub fn len(&self) -> usize {
        self.pending.borrow().len()
    }

    pub fn is_empty(&self) -> bool {
        self.pending.borrow().is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn events_are_drained_once_in_order() {
        let bus = FeatureLifecycle::new();
        let a = FeatureKey::new(28);
        let b = FeatureKey::new(29);
        assert!(bus.is_empty());

        bus.post(FeatureEvent::Deactivated(a));
        bus.post(FeatureEvent::Activated(b));
        bus.post(FeatureEvent::Closed(a));
        assert_eq!(bus.len(), 3);

        assert_eq!(
            bus.drain(),
            vec![FeatureEvent::Deactivated(a), FeatureEvent::Activated(b), FeatureEvent::Closed(a),]
        );
        assert!(bus.is_empty());
        assert!(bus.drain().is_empty(), "事件只能被消费一次");
    }
}