use std::{collections::HashMap, rc::Rc};
use gpui::{App, Font, Global, Pixels, px};
#[cfg(test)]
mod tests;
pub(super) const TABLE_CHARS: usize = 4096;
const LIGATURE_SAMPLES: &[&str] = &[
"-> => <- <= >= != == === !== <> :: ::: ... .. // /* */ /// <!-- --> && || ++ -- ** |> <|",
"fi fl ffi ffl www 0x 0o 0b 1x #{ ${ #[ ]# ;; ?? ?. .= := =: =~ !~ ~> <~ ~~ ## ### __ <<= >>=",
"{\"key\": [1, -2.5e-3, true, null], 'x': \"https://example.com/a?b=c&d=e#f\"}",
];
#[derive(Clone, Debug, PartialEq)]
pub(super) struct MonospaceWidths {
widths: Vec<Pixels>,
}
impl MonospaceWidths {
pub(super) fn detect(
mut glyph_starts: impl FnMut(&str) -> Vec<Pixels>,
mut measure: impl FnMut(&str) -> Pixels,
) -> Option<Self> {
let widths = glyph_starts(&"0".repeat(TABLE_CHARS));
let increasing = widths.windows(2).all(|pair| pair[0] < pair[1]);
if widths.len() != TABLE_CHARS + 1 || widths[0] != px(0.) || !increasing {
return None;
}
let this = Self { widths };
let printable: String = (b' '..=b'~').map(char::from).collect();
if glyph_starts(&printable) != this.widths[..=printable.len()] {
return None;
}
let lengths = (1..=16).chain([31, 64, 100, 255, 256, 1000, 1023, TABLE_CHARS]);
let counted = lengths.flat_map(|len| {
[
"0".repeat(len),
printable.chars().cycle().take(len).collect::<String>(),
]
});
let singles = printable.chars().map(String::from);
let pairs = printable.chars().map(|first| {
printable
.chars()
.flat_map(|second| [first, second])
.collect::<String>()
});
let ligatures = LIGATURE_SAMPLES.iter().map(|sample| sample.to_string());
counted
.chain(singles)
.chain(pairs)
.chain(ligatures)
.all(|sample| this.width(sample.len()) == Some(measure(&sample)))
.then_some(this)
}
pub(super) fn cached(
font: &Font,
font_size: Pixels,
glyph_starts: impl FnMut(&str) -> Vec<Pixels>,
measure: impl FnMut(&str) -> Pixels,
cx: &mut App,
) -> Option<Rc<Self>> {
let key = (font.clone(), f32::from(font_size).to_bits());
let cache = cx.default_global::<MonospaceCache>();
cache
.0
.entry(key)
.or_insert_with(|| Self::detect(glyph_starts, measure).map(Rc::new))
.clone()
}
pub(super) fn width(&self, chars: usize) -> Option<Pixels> {
self.widths.get(chars).copied()
}
}
#[derive(Default)]
struct MonospaceCache(HashMap<(Font, u32), Option<Rc<MonospaceWidths>>>);
impl Global for MonospaceCache {}
pub(super) fn is_printable_ascii(text: &str) -> bool {
text.bytes().all(|byte| matches!(byte, b' '..=b'~'))
}