use super::PaintParts;
use crate::model::control::Equation;
use std::cell::RefCell;
use std::collections::HashMap;
const FLOW_CAPACITY: usize = 16 * 1024;
const PAINT_CAPACITY: usize = 4 * 1024;
#[derive(PartialEq, Eq, Hash)]
struct EquationKey {
script: String,
font_name: String,
version_info: String,
font_size: u32,
attr: u32,
eqedit: u32,
color: u32,
baseline: i16,
width: u32,
height: u32,
size_protect: bool,
treat_as_char: bool,
host_frame_seal: Option<([u8; 32], bool)>,
legacy_source_frame_seal: Option<[u8; 32]>,
}
impl EquationKey {
fn new(equation: &Equation) -> Self {
Self {
legacy_source_frame_seal: equation.legacy_source_frame_seal,
script: equation.script.clone(),
font_name: equation.font_name.clone(),
version_info: equation.version_info.clone(),
font_size: equation.font_size,
attr: equation.attr,
eqedit: equation.eqedit,
color: equation.color,
baseline: equation.baseline,
width: equation.common.width,
height: equation.common.height,
size_protect: equation.common.size_protect,
treat_as_char: equation.common.treat_as_char,
host_frame_seal: equation
.unpositioned_host_frame_seal
.as_ref()
.map(|seal| (seal.signature, seal.legacy_layout)),
}
}
}
thread_local! {
static FLOW_METRICS: RefCell<HashMap<EquationKey, (u32, u32, i32)>> =
RefCell::new(HashMap::new());
static PAINT_PARTS: RefCell<HashMap<(EquationKey, u64), PaintParts>> =
RefCell::new(HashMap::new());
}
fn insert_bounded<K: Eq + std::hash::Hash, V>(
cache: &mut HashMap<K, V>,
capacity: usize,
key: K,
value: V,
) {
if cache.len() >= capacity {
cache.clear();
}
cache.insert(key, value);
}
pub(super) fn flow_metrics(
equation: &Equation,
compute: impl Fn(&Equation) -> (u32, u32, i32),
) -> (u32, u32, i32) {
let key = EquationKey::new(equation);
if let Some(metrics) = FLOW_METRICS.with(|cache| cache.borrow().get(&key).copied()) {
return metrics;
}
let metrics = compute(equation);
FLOW_METRICS.with(|cache| {
insert_bounded(&mut cache.borrow_mut(), FLOW_CAPACITY, key, metrics);
});
metrics
}
pub(super) fn paint_parts(
equation: &Equation,
dpi: f64,
compute: impl Fn(&Equation, f64) -> PaintParts,
) -> PaintParts {
let key = (EquationKey::new(equation), dpi.to_bits());
if let Some(parts) = PAINT_PARTS.with(|cache| cache.borrow().get(&key).cloned()) {
return parts;
}
let parts = compute(equation, dpi);
PAINT_PARTS.with(|cache| {
insert_bounded(&mut cache.borrow_mut(), PAINT_CAPACITY, key, parts.clone());
});
parts
}