Skip to main content

mgui_text/
runtime.rs

1//! 应用持有的文本运行时配置(0.7 M2)。
2//!
3//! 字体栈、行高与 DPR 不再由散落的线程局部标量担任真值;这里给出应用可持有、
4//! 可替换的句柄。栅格/图集仍由 `text::with_font` 的单线程 FontState 提供,
5//! 但 shaped-line 缓存 key 折入 [`TextRuntime::style_generation`],因此不同
6//! 运行时的配置不会互相命中。
7
8use std::cell::{Cell, RefCell};
9use std::rc::Rc;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::Arc;
12
13use crate::text::{with_font, DEFAULT_FONT_STACK};
14use mgui_core::cache_stats::CacheInvalidationReason;
15
16/// 由 [`TextRuntime::register_font`] 注入的字体标识。`family()` 可直接拼进 CSS 字体栈,
17/// 例如 `format!("{}, {}", id.family(), runtime.font_stack())`。
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct FontId {
20    family: String,
21}
22
23impl FontId {
24    /// 注册字体在 fontique 集合中的 family 名。
25    pub fn family(&self) -> &str {
26        &self.family
27    }
28}
29
30/// 字体注册失败原因。错误不写日志、不吞掉:调用方必须显式处理。
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum FontError {
33    /// 传入字节为空。
34    EmptyData,
35    /// fontique 未从字节中识别出任何字体(不是合法的 TTF/OTF/WOFF 数据)。
36    InvalidData,
37    /// 字体已注册,但没有可查询的 family 名。
38    MissingFamily,
39}
40
41impl std::fmt::Display for FontError {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            Self::EmptyData => f.write_str("字体数据为空"),
45            Self::InvalidData => f.write_str("字体数据无法识别"),
46            Self::MissingFamily => f.write_str("字体缺少 family 名"),
47        }
48    }
49}
50
51impl std::error::Error for FontError {}
52
53/// 跨运行时唯一的样式 generation 源。shaped-line/raster 缓存被多个运行时共享,
54/// 如果两个运行时各自从 1 开始编号,数值相同的 generation 会误命中彼此的缓存。
55static NEXT_STYLE_GENERATION: AtomicU64 = AtomicU64::new(1);
56
57fn next_style_generation() -> u64 {
58    NEXT_STYLE_GENERATION.fetch_add(1, Ordering::Relaxed)
59}
60
61/// 应用持有的文本运行时句柄。多窗口共享同一句柄;不为每个窗口复制 atlas。
62pub type TextRuntimeHandle = Rc<TextRuntime>;
63
64/// 文本运行时的配置快照。句柄可通过 `Rc` 在应用装配层与窗口之间共享。
65pub struct TextRuntime {
66    font_stack: RefCell<String>,
67    line_height: Cell<f32>,
68    dpr: Cell<f32>,
69    style_generation: Cell<u64>,
70}
71
72impl std::fmt::Debug for TextRuntime {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("TextRuntime")
75            .field("font_stack", &self.font_stack.borrow())
76            .field("line_height", &self.line_height.get())
77            .field("dpr", &self.dpr.get())
78            .field("style_generation", &self.style_generation.get())
79            .finish()
80    }
81}
82
83fn normalize_line_height(v: f32) -> f32 {
84    if v.is_finite() && v > 0.0 {
85        v
86    } else {
87        1.2
88    }
89}
90
91impl TextRuntime {
92    /// 创建默认运行时:默认字体栈、行高 1.2、DPR 1.0。
93    pub fn new() -> TextRuntimeHandle {
94        Rc::new(Self {
95            font_stack: RefCell::new(DEFAULT_FONT_STACK.to_string()),
96            line_height: Cell::new(1.2),
97            dpr: Cell::new(1.0),
98            style_generation: Cell::new(next_style_generation()),
99        })
100    }
101
102    /// 创建显式配置的运行时。空字体栈回落到 [`DEFAULT_FONT_STACK`]。
103    pub fn with_config(font_stack: impl Into<String>, line_height: f32) -> TextRuntimeHandle {
104        let runtime = Self::new();
105        runtime.set_font_stack(font_stack);
106        runtime.set_line_height(line_height);
107        runtime
108    }
109
110    pub fn set_font_stack(&self, stack: impl Into<String>) {
111        let next = stack.into();
112        let next = if next.trim().is_empty() { DEFAULT_FONT_STACK.to_string() } else { next };
113        let mut current = self.font_stack.borrow_mut();
114        if *current != next {
115            *current = next;
116            self.style_generation.set(next_style_generation());
117            mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
118        }
119    }
120
121    pub fn font_stack(&self) -> String {
122        self.font_stack.borrow().clone()
123    }
124
125    /// 设置字号倍数行高;≤0 或非有限值回落到 1.2。值未变化时 generation 不动。
126    pub fn set_line_height(&self, line_height: f32) {
127        let v = normalize_line_height(line_height);
128        if self.line_height.get().to_bits() != v.to_bits() {
129            self.line_height.set(v);
130            self.style_generation.set(next_style_generation());
131            mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
132        }
133    }
134
135    pub fn line_height(&self) -> f32 {
136        self.line_height.get()
137    }
138
139    /// DPR 只影响栅格分辨率,已进入 shaped-line/raster key,不推进样式 generation。
140    pub fn set_dpr(&self, dpr: f32) {
141        self.dpr.set(if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 });
142    }
143
144    pub fn dpr(&self) -> f32 {
145        self.dpr.get()
146    }
147
148    /// 字体栈/行高变化计数;进入 shaped-line 与富文本缓存 key。
149    pub fn style_generation(&self) -> u64 {
150        self.style_generation.get()
151    }
152
153    /// 从内存字节注册字体到当前运行时共享的 parley/fontique 字体集合。
154    ///
155    /// 注册只依赖“字体字节 + 集合”,不依赖当前字体栈,因此可以先用返回的
156    /// [`FontId::family`] 拼出新字体栈再 `set_font_stack`。注册成功后推进
157    /// style generation,让所有 shaped-line 缓存按新 key 失效;已有图集 glyph
158    /// 不受影响,不做无谓的 atlas 清空。
159    pub fn register_font(&self, data: &[u8]) -> Result<FontId, FontError> {
160        if data.is_empty() {
161            return Err(FontError::EmptyData);
162        }
163        let family = with_font(|fs| {
164            let blob = parley::fontique::Blob::new(Arc::new(data.to_vec()));
165            let registered = fs.font_cx.collection.register_fonts(blob, None);
166            let Some((family_id, _)) = registered.first() else {
167                return Err(FontError::InvalidData);
168            };
169            fs.font_cx.collection.family(*family_id).map(|info| info.name().to_string()).ok_or(FontError::MissingFamily)
170        })?;
171        self.style_generation.set(next_style_generation());
172        mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
173        Ok(FontId { family })
174    }
175}
176
177thread_local! {
178    static DEFAULT_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
179    static ACTIVE_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
180}
181
182/// 当前线程默认运行时。旧自由函数只写这个实例,不会污染显式 scope。
183pub fn default_text_runtime() -> TextRuntimeHandle {
184    DEFAULT_RUNTIME.with(|cell| {
185        let mut opt = cell.borrow_mut();
186        opt.get_or_insert_with(TextRuntime::new).clone()
187    })
188}
189
190/// 替换当前线程默认运行时;已创建的应用仍持有自己的句柄,不受影响。
191pub fn set_default_text_runtime(runtime: TextRuntimeHandle) {
192    DEFAULT_RUNTIME.with(|cell| *cell.borrow_mut() = Some(runtime));
193}
194
195/// 当前生效的运行时:优先 scope,其次线程默认。
196pub fn current_text_runtime() -> TextRuntimeHandle {
197    ACTIVE_RUNTIME.with(|active| {
198        if let Some(runtime) = active.borrow().as_ref() {
199            return runtime.clone();
200        }
201        default_text_runtime()
202    })
203}
204
205struct ActiveRuntimeGuard(Option<TextRuntimeHandle>);
206
207impl Drop for ActiveRuntimeGuard {
208    fn drop(&mut self) {
209        ACTIVE_RUNTIME.with(|cell| *cell.borrow_mut() = self.0.take());
210    }
211}
212
213/// 在指定运行时中执行构建/布局/paint;嵌套 scope 在退出后恢复上一层。
214pub fn with_text_runtime<R>(runtime: &TextRuntimeHandle, f: impl FnOnce() -> R) -> R {
215    let previous = ACTIVE_RUNTIME.with(|cell| cell.borrow_mut().replace(Rc::clone(runtime)));
216    let _guard = ActiveRuntimeGuard(previous);
217    f()
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::text::{text_line_height, DEFAULT_FONT_STACK};
224
225    #[test]
226    fn register_font_rejects_empty_data() {
227        let runtime = TextRuntime::new();
228        assert_eq!(runtime.register_font(&[]), Err(FontError::EmptyData));
229    }
230
231    #[test]
232    fn register_font_rejects_invalid_bytes() {
233        let runtime = TextRuntime::new();
234        assert_eq!(runtime.register_font(b"not a font"), Err(FontError::InvalidData));
235    }
236
237    #[test]
238    fn register_font_advances_generation_and_exposes_family() {
239        // 1.* 的发布目标是 Windows;系统字体是正向路径的确定性夹具。
240        let path = r"C:\Windows\Fonts\arial.ttf";
241        let data = std::fs::read(path).unwrap_or_else(|e| panic!("需要系统字体 {path}: {e}"));
242        let runtime = TextRuntime::new();
243        let before = runtime.style_generation();
244        let id = runtime.register_font(&data).expect("系统字体应可注册");
245        assert!(!id.family().is_empty(), "注册的字体必须暴露可入栈的 family 名");
246        assert!(runtime.style_generation() > before, "注册字体必须推进 generation 以失效 shaped-line 缓存");
247    }
248
249    #[test]
250    fn scoped_runtime_configuration_is_isolated() {
251        let a = TextRuntime::with_config("monospace", 1.1);
252        let b = TextRuntime::with_config("serif", 1.4);
253        let outside = text_line_height();
254        with_text_runtime(&a, || {
255            assert_eq!(text_line_height(), 1.1);
256            with_text_runtime(&b, || assert_eq!(text_line_height(), 1.4));
257            assert_eq!(text_line_height(), 1.1);
258        });
259        assert_eq!(text_line_height(), outside);
260    }
261
262    #[test]
263    fn style_generation_bumps_only_on_style_change() {
264        let runtime = TextRuntime::new();
265        let initial = runtime.style_generation();
266        runtime.set_font_stack("monospace");
267        let after_font = runtime.style_generation();
268        assert!(after_font > initial, "字体栈变化必须推进 generation");
269        runtime.set_font_stack("monospace");
270        assert_eq!(runtime.style_generation(), after_font, "同值设置不得推进 generation");
271        runtime.set_line_height(1.5);
272        let after_height = runtime.style_generation();
273        assert!(after_height > after_font, "行高变化必须推进 generation");
274        runtime.set_dpr(2.0);
275        assert_eq!(runtime.style_generation(), after_height, "DPR 不推进样式 generation");
276        assert_eq!(runtime.dpr(), 2.0);
277    }
278
279    #[test]
280    fn distinct_runtimes_never_share_a_style_generation() {
281        let a = TextRuntime::new();
282        let b = TextRuntime::new();
283        assert_ne!(a.style_generation(), b.style_generation());
284        a.set_line_height(1.5);
285        assert_ne!(a.style_generation(), b.style_generation());
286        b.set_line_height(1.5);
287        assert_ne!(a.style_generation(), b.style_generation());
288    }
289
290    #[test]
291    fn empty_font_stack_falls_back_to_default() {
292        let runtime = TextRuntime::with_config("", 1.2);
293        assert_eq!(runtime.font_stack(), DEFAULT_FONT_STACK);
294    }
295}