use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::text::DEFAULT_FONT_STACK;
use mgui_core::cache_stats::CacheInvalidationReason;
static NEXT_STYLE_GENERATION: AtomicU64 = AtomicU64::new(1);
fn next_style_generation() -> u64 {
NEXT_STYLE_GENERATION.fetch_add(1, Ordering::Relaxed)
}
pub type TextRuntimeHandle = Rc<TextRuntime>;
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 {
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()),
})
}
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()
}
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()
}
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()
}
pub fn style_generation(&self) -> u64 {
self.style_generation.get()
}
}
thread_local! {
static DEFAULT_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
static ACTIVE_RUNTIME: RefCell<Option<TextRuntimeHandle>> = const { RefCell::new(None) };
}
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));
}
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());
}
}
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 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);
}
}