1use 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#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct FontId {
20 family: String,
21}
22
23impl FontId {
24 pub fn family(&self) -> &str {
26 &self.family
27 }
28}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum FontError {
33 EmptyData,
35 InvalidData,
37 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
53static NEXT_STYLE_GENERATION: AtomicU64 = AtomicU64::new(1);
56
57fn next_style_generation() -> u64 {
58 NEXT_STYLE_GENERATION.fetch_add(1, Ordering::Relaxed)
59}
60
61pub type TextRuntimeHandle = Rc<TextRuntime>;
63
64pub 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 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 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 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 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 pub fn style_generation(&self) -> u64 {
150 self.style_generation.get()
151 }
152
153 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
182pub 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
190pub fn set_default_text_runtime(runtime: TextRuntimeHandle) {
192 DEFAULT_RUNTIME.with(|cell| *cell.borrow_mut() = Some(runtime));
193}
194
195pub 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
213pub 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 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}