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};
11
12use crate::text::DEFAULT_FONT_STACK;
13use mgui_core::cache_stats::CacheInvalidationReason;
14
15/// 跨运行时唯一的样式 generation 源。shaped-line/raster 缓存被多个运行时共享,
16/// 如果两个运行时各自从 1 开始编号,数值相同的 generation 会误命中彼此的缓存。
17static NEXT_STYLE_GENERATION: AtomicU64 = AtomicU64::new(1);
18
19fn next_style_generation() -> u64 {
20    NEXT_STYLE_GENERATION.fetch_add(1, Ordering::Relaxed)
21}
22
23/// 应用持有的文本运行时句柄。多窗口共享同一句柄;不为每个窗口复制 atlas。
24pub type TextRuntimeHandle = Rc<TextRuntime>;
25
26/// 文本运行时的配置快照。句柄可通过 `Rc` 在应用装配层与窗口之间共享。
27pub struct TextRuntime {
28    font_stack: RefCell<String>,
29    line_height: Cell<f32>,
30    dpr: Cell<f32>,
31    style_generation: Cell<u64>,
32}
33
34impl std::fmt::Debug for TextRuntime {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("TextRuntime")
37            .field("font_stack", &self.font_stack.borrow())
38            .field("line_height", &self.line_height.get())
39            .field("dpr", &self.dpr.get())
40            .field("style_generation", &self.style_generation.get())
41            .finish()
42    }
43}
44
45fn normalize_line_height(v: f32) -> f32 {
46    if v.is_finite() && v > 0.0 {
47        v
48    } else {
49        1.2
50    }
51}
52
53impl TextRuntime {
54    /// 创建默认运行时:默认字体栈、行高 1.2、DPR 1.0。
55    pub fn new() -> TextRuntimeHandle {
56        Rc::new(Self {
57            font_stack: RefCell::new(DEFAULT_FONT_STACK.to_string()),
58            line_height: Cell::new(1.2),
59            dpr: Cell::new(1.0),
60            style_generation: Cell::new(next_style_generation()),
61        })
62    }
63
64    /// 创建显式配置的运行时。空字体栈回落到 [`DEFAULT_FONT_STACK`]。
65    pub fn with_config(font_stack: impl Into<String>, line_height: f32) -> TextRuntimeHandle {
66        let runtime = Self::new();
67        runtime.set_font_stack(font_stack);
68        runtime.set_line_height(line_height);
69        runtime
70    }
71
72    pub fn set_font_stack(&self, stack: impl Into<String>) {
73        let next = stack.into();
74        let next = if next.trim().is_empty() { DEFAULT_FONT_STACK.to_string() } else { next };
75        let mut current = self.font_stack.borrow_mut();
76        if *current != next {
77            *current = next;
78            self.style_generation.set(next_style_generation());
79            mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
80        }
81    }
82
83    pub fn font_stack(&self) -> String {
84        self.font_stack.borrow().clone()
85    }
86
87    /// 设置字号倍数行高;≤0 或非有限值回落到 1.2。值未变化时 generation 不动。
88    pub fn set_line_height(&self, line_height: f32) {
89        let v = normalize_line_height(line_height);
90        if self.line_height.get().to_bits() != v.to_bits() {
91            self.line_height.set(v);
92            self.style_generation.set(next_style_generation());
93            mgui_core::frame::note_cache_invalidation(CacheInvalidationReason::Font);
94        }
95    }
96
97    pub fn line_height(&self) -> f32 {
98        self.line_height.get()
99    }
100
101    /// DPR 只影响栅格分辨率,已进入 shaped-line/raster key,不推进样式 generation。
102    pub fn set_dpr(&self, dpr: f32) {
103        self.dpr.set(if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 });
104    }
105
106    pub fn dpr(&self) -> f32 {
107        self.dpr.get()
108    }
109
110    /// 字体栈/行高变化计数;进入 shaped-line 与富文本缓存 key。
111    pub fn style_generation(&self) -> u64 {
112        self.style_generation.get()
113    }
114}
115
116thread_local! {
117    static DEFAULT_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
118    static ACTIVE_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
119}
120
121/// 当前线程默认运行时。旧自由函数只写这个实例,不会污染显式 scope。
122pub fn default_text_runtime() -> TextRuntimeHandle {
123    DEFAULT_RUNTIME.with(|cell| {
124        let mut opt = cell.borrow_mut();
125        opt.get_or_insert_with(TextRuntime::new).clone()
126    })
127}
128
129/// 替换当前线程默认运行时;已创建的应用仍持有自己的句柄,不受影响。
130pub fn set_default_text_runtime(runtime: TextRuntimeHandle) {
131    DEFAULT_RUNTIME.with(|cell| *cell.borrow_mut() = Some(runtime));
132}
133
134/// 当前生效的运行时:优先 scope,其次线程默认。
135pub fn current_text_runtime() -> TextRuntimeHandle {
136    ACTIVE_RUNTIME.with(|active| {
137        if let Some(runtime) = active.borrow().as_ref() {
138            return runtime.clone();
139        }
140        default_text_runtime()
141    })
142}
143
144struct ActiveRuntimeGuard(Option<TextRuntimeHandle>);
145
146impl Drop for ActiveRuntimeGuard {
147    fn drop(&mut self) {
148        ACTIVE_RUNTIME.with(|cell| *cell.borrow_mut() = self.0.take());
149    }
150}
151
152/// 在指定运行时中执行构建/布局/paint;嵌套 scope 在退出后恢复上一层。
153pub fn with_text_runtime<R>(runtime: &TextRuntimeHandle, f: impl FnOnce() -> R) -> R {
154    let previous = ACTIVE_RUNTIME.with(|cell| cell.borrow_mut().replace(Rc::clone(runtime)));
155    let _guard = ActiveRuntimeGuard(previous);
156    f()
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::text::{text_line_height, DEFAULT_FONT_STACK};
163
164    #[test]
165    fn scoped_runtime_configuration_is_isolated() {
166        let a = TextRuntime::with_config("monospace", 1.1);
167        let b = TextRuntime::with_config("serif", 1.4);
168        let outside = text_line_height();
169        with_text_runtime(&a, || {
170            assert_eq!(text_line_height(), 1.1);
171            with_text_runtime(&b, || assert_eq!(text_line_height(), 1.4));
172            assert_eq!(text_line_height(), 1.1);
173        });
174        assert_eq!(text_line_height(), outside);
175    }
176
177    #[test]
178    fn style_generation_bumps_only_on_style_change() {
179        let runtime = TextRuntime::new();
180        let initial = runtime.style_generation();
181        runtime.set_font_stack("monospace");
182        let after_font = runtime.style_generation();
183        assert!(after_font > initial, "字体栈变化必须推进 generation");
184        runtime.set_font_stack("monospace");
185        assert_eq!(runtime.style_generation(), after_font, "同值设置不得推进 generation");
186        runtime.set_line_height(1.5);
187        let after_height = runtime.style_generation();
188        assert!(after_height > after_font, "行高变化必须推进 generation");
189        runtime.set_dpr(2.0);
190        assert_eq!(runtime.style_generation(), after_height, "DPR 不推进样式 generation");
191        assert_eq!(runtime.dpr(), 2.0);
192    }
193
194    #[test]
195    fn distinct_runtimes_never_share_a_style_generation() {
196        let a = TextRuntime::new();
197        let b = TextRuntime::new();
198        assert_ne!(a.style_generation(), b.style_generation());
199        a.set_line_height(1.5);
200        assert_ne!(a.style_generation(), b.style_generation());
201        b.set_line_height(1.5);
202        assert_ne!(a.style_generation(), b.style_generation());
203    }
204
205    #[test]
206    fn empty_font_stack_falls_back_to_default() {
207        let runtime = TextRuntime::with_config("", 1.2);
208        assert_eq!(runtime.font_stack(), DEFAULT_FONT_STACK);
209    }
210}