mgui-text 1.1.0

平台无关文本服务:parley 排版 / swash 字形栅格化 / glyph atlas / TextField 布局
Documentation
//! 应用持有的文本运行时配置(0.7 M2)。
//!
//! 字体栈、行高与 DPR 不再由散落的线程局部标量担任真值;这里给出应用可持有、
//! 可替换的句柄。栅格/图集仍由 `text::with_font` 的单线程 FontState 提供,
//! 但 shaped-line 缓存 key 折入 [`TextRuntime::style_generation`],因此不同
//! 运行时的配置不会互相命中。

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use crate::text::{with_font, DEFAULT_FONT_STACK};
use mgui_core::cache_stats::CacheInvalidationReason;

/// 由 [`TextRuntime::register_font`] 注入的字体标识。`family()` 可直接拼进 CSS 字体栈,
/// 例如 `format!("{}, {}", id.family(), runtime.font_stack())`。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FontId {
    family: String,
}

impl FontId {
    /// 注册字体在 fontique 集合中的 family 名。
    pub fn family(&self) -> &str {
        &self.family
    }
}

/// 字体注册失败原因。错误不写日志、不吞掉:调用方必须显式处理。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FontError {
    /// 传入字节为空。
    EmptyData,
    /// fontique 未从字节中识别出任何字体(不是合法的 TTF/OTF/WOFF 数据)。
    InvalidData,
    /// 字体已注册,但没有可查询的 family 名。
    MissingFamily,
}

impl std::fmt::Display for FontError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyData => f.write_str("字体数据为空"),
            Self::InvalidData => f.write_str("字体数据无法识别"),
            Self::MissingFamily => f.write_str("字体缺少 family 名"),
        }
    }
}

impl std::error::Error for FontError {}

/// 跨运行时唯一的样式 generation 源。shaped-line/raster 缓存被多个运行时共享,
/// 如果两个运行时各自从 1 开始编号,数值相同的 generation 会误命中彼此的缓存。
static NEXT_STYLE_GENERATION: AtomicU64 = AtomicU64::new(1);

fn next_style_generation() -> u64 {
    NEXT_STYLE_GENERATION.fetch_add(1, Ordering::Relaxed)
}

/// 应用持有的文本运行时句柄。多窗口共享同一句柄;不为每个窗口复制 atlas。
pub type TextRuntimeHandle = Rc<TextRuntime>;

/// 文本运行时的配置快照。句柄可通过 `Rc` 在应用装配层与窗口之间共享。
pub struct TextRuntime {
    font_stack: RefCell<String>,
    line_height: Cell<f32>,
    dpr: Cell<f32>,
    style_generation: Cell<u64>,
}

impl std::fmt::Debug for TextRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextRuntime")
            .field("font_stack", &self.font_stack.borrow())
            .field("line_height", &self.line_height.get())
            .field("dpr", &self.dpr.get())
            .field("style_generation", &self.style_generation.get())
            .finish()
    }
}

fn normalize_line_height(v: f32) -> f32 {
    if v.is_finite() && v > 0.0 {
        v
    } else {
        1.2
    }
}

impl TextRuntime {
    /// 创建默认运行时:默认字体栈、行高 1.2、DPR 1.0。
    pub fn new() -> TextRuntimeHandle {
        Rc::new(Self {
            font_stack: RefCell::new(DEFAULT_FONT_STACK.to_string()),
            line_height: Cell::new(1.2),
            dpr: Cell::new(1.0),
            style_generation: Cell::new(next_style_generation()),
        })
    }

    /// 创建显式配置的运行时。空字体栈回落到 [`DEFAULT_FONT_STACK`]。
    pub fn with_config(font_stack: impl Into<String>, line_height: f32) -> TextRuntimeHandle {
        let runtime = Self::new();
        runtime.set_font_stack(font_stack);
        runtime.set_line_height(line_height);
        runtime
    }

    pub fn set_font_stack(&self, stack: impl Into<String>) {
        let next = stack.into();
        let next = if next.trim().is_empty() { DEFAULT_FONT_STACK.to_string() } else { next };
        let mut current = self.font_stack.borrow_mut();
        if *current != next {
            *current = next;
            self.style_generation.set(next_style_generation());
            mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
        }
    }

    pub fn font_stack(&self) -> String {
        self.font_stack.borrow().clone()
    }

    /// 设置字号倍数行高;≤0 或非有限值回落到 1.2。值未变化时 generation 不动。
    pub fn set_line_height(&self, line_height: f32) {
        let v = normalize_line_height(line_height);
        if self.line_height.get().to_bits() != v.to_bits() {
            self.line_height.set(v);
            self.style_generation.set(next_style_generation());
            mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
        }
    }

    pub fn line_height(&self) -> f32 {
        self.line_height.get()
    }

    /// DPR 只影响栅格分辨率,已进入 shaped-line/raster key,不推进样式 generation。
    pub fn set_dpr(&self, dpr: f32) {
        self.dpr.set(if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 });
    }

    pub fn dpr(&self) -> f32 {
        self.dpr.get()
    }

    /// 字体栈/行高变化计数;进入 shaped-line 与富文本缓存 key。
    pub fn style_generation(&self) -> u64 {
        self.style_generation.get()
    }

    /// 从内存字节注册字体到当前运行时共享的 parley/fontique 字体集合。
    ///
    /// 注册只依赖“字体字节 + 集合”,不依赖当前字体栈,因此可以先用返回的
    /// [`FontId::family`] 拼出新字体栈再 `set_font_stack`。注册成功后推进
    /// style generation,让所有 shaped-line 缓存按新 key 失效;已有图集 glyph
    /// 不受影响,不做无谓的 atlas 清空。
    pub fn register_font(&self, data: &[u8]) -> Result<FontId, FontError> {
        if data.is_empty() {
            return Err(FontError::EmptyData);
        }
        let family = with_font(|fs| {
            let blob = parley::fontique::Blob::new(Arc::new(data.to_vec()));
            let registered = fs.font_cx.collection.register_fonts(blob, None);
            let Some((family_id, _)) = registered.first() else {
                return Err(FontError::InvalidData);
            };
            fs.font_cx.collection.family(*family_id).map(|info| info.name().to_string()).ok_or(FontError::MissingFamily)
        })?;
        self.style_generation.set(next_style_generation());
        mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
        Ok(FontId { family })
    }
}

thread_local! {
    static DEFAULT_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
    static ACTIVE_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
}

/// 当前线程默认运行时。旧自由函数只写这个实例,不会污染显式 scope。
pub fn default_text_runtime() -> TextRuntimeHandle {
    DEFAULT_RUNTIME.with(|cell| {
        let mut opt = cell.borrow_mut();
        opt.get_or_insert_with(TextRuntime::new).clone()
    })
}

/// 替换当前线程默认运行时;已创建的应用仍持有自己的句柄,不受影响。
pub fn set_default_text_runtime(runtime: TextRuntimeHandle) {
    DEFAULT_RUNTIME.with(|cell| *cell.borrow_mut() = Some(runtime));
}

/// 当前生效的运行时:优先 scope,其次线程默认。
pub fn current_text_runtime() -> TextRuntimeHandle {
    ACTIVE_RUNTIME.with(|active| {
        if let Some(runtime) = active.borrow().as_ref() {
            return runtime.clone();
        }
        default_text_runtime()
    })
}

struct ActiveRuntimeGuard(Option<TextRuntimeHandle>);

impl Drop for ActiveRuntimeGuard {
    fn drop(&mut self) {
        ACTIVE_RUNTIME.with(|cell| *cell.borrow_mut() = self.0.take());
    }
}

/// 在指定运行时中执行构建/布局/paint;嵌套 scope 在退出后恢复上一层。
pub fn with_text_runtime<R>(runtime: &TextRuntimeHandle, f: impl FnOnce() -> R) -> R {
    let previous = ACTIVE_RUNTIME.with(|cell| cell.borrow_mut().replace(Rc::clone(runtime)));
    let _guard = ActiveRuntimeGuard(previous);
    f()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::text::{text_line_height, DEFAULT_FONT_STACK};

    #[test]
    fn register_font_rejects_empty_data() {
        let runtime = TextRuntime::new();
        assert_eq!(runtime.register_font(&[]), Err(FontError::EmptyData));
    }

    #[test]
    fn register_font_rejects_invalid_bytes() {
        let runtime = TextRuntime::new();
        assert_eq!(runtime.register_font(b"not a font"), Err(FontError::InvalidData));
    }

    #[test]
    fn register_font_advances_generation_and_exposes_family() {
        // 1.* 的发布目标是 Windows;系统字体是正向路径的确定性夹具。
        let path = r"C:\Windows\Fonts\arial.ttf";
        let data = std::fs::read(path).unwrap_or_else(|e| panic!("需要系统字体 {path}: {e}"));
        let runtime = TextRuntime::new();
        let before = runtime.style_generation();
        let id = runtime.register_font(&data).expect("系统字体应可注册");
        assert!(!id.family().is_empty(), "注册的字体必须暴露可入栈的 family 名");
        assert!(runtime.style_generation() > before, "注册字体必须推进 generation 以失效 shaped-line 缓存");
    }

    #[test]
    fn scoped_runtime_configuration_is_isolated() {
        let a = TextRuntime::with_config("monospace", 1.1);
        let b = TextRuntime::with_config("serif", 1.4);
        let outside = text_line_height();
        with_text_runtime(&a, || {
            assert_eq!(text_line_height(), 1.1);
            with_text_runtime(&b, || assert_eq!(text_line_height(), 1.4));
            assert_eq!(text_line_height(), 1.1);
        });
        assert_eq!(text_line_height(), outside);
    }

    #[test]
    fn style_generation_bumps_only_on_style_change() {
        let runtime = TextRuntime::new();
        let initial = runtime.style_generation();
        runtime.set_font_stack("monospace");
        let after_font = runtime.style_generation();
        assert!(after_font > initial, "字体栈变化必须推进 generation");
        runtime.set_font_stack("monospace");
        assert_eq!(runtime.style_generation(), after_font, "同值设置不得推进 generation");
        runtime.set_line_height(1.5);
        let after_height = runtime.style_generation();
        assert!(after_height > after_font, "行高变化必须推进 generation");
        runtime.set_dpr(2.0);
        assert_eq!(runtime.style_generation(), after_height, "DPR 不推进样式 generation");
        assert_eq!(runtime.dpr(), 2.0);
    }

    #[test]
    fn distinct_runtimes_never_share_a_style_generation() {
        let a = TextRuntime::new();
        let b = TextRuntime::new();
        assert_ne!(a.style_generation(), b.style_generation());
        a.set_line_height(1.5);
        assert_ne!(a.style_generation(), b.style_generation());
        b.set_line_height(1.5);
        assert_ne!(a.style_generation(), b.style_generation());
    }

    #[test]
    fn empty_font_stack_falls_back_to_default() {
        let runtime = TextRuntime::with_config("", 1.2);
        assert_eq!(runtime.font_stack(), DEFAULT_FONT_STACK);
    }
}