use std::{
hash::{Hash, Hasher},
ops::Range,
sync::Arc,
};
use gpui_kit::{
Font, FontId, FontWeight, GlyphId, Hsla, LineLayout, Pixels, Point, SharedString, TextRun,
Window, black, point, px,
};
use rustc_hash::{FxHashMap, FxHasher};
const KEEP_FRAMES: u64 = 120;
const SWEEP_EVERY: u64 = 60;
struct Entry {
text: Box<str>,
layout: Arc<LineLayout>,
last_frame: u64,
}
const NUMERIC: &str = "0123456789.,-+ ";
const NUMERIC_OPTIONAL: &str = ":";
#[derive(Clone, Copy)]
struct NumericGlyph {
font_id: FontId,
glyph_id: GlyphId,
advance: Pixels,
}
struct NumericTable {
glyphs: [Option<NumericGlyph>; 128],
ascent: Pixels,
descent: Pixels,
}
impl NumericTable {
fn build(shape: impl Fn(&str) -> Arc<LineLayout>) -> Option<Self> {
let mut glyphs = [None; 128];
let mut metrics = None;
for ch in NUMERIC.chars() {
let layout = shape(ch.encode_utf8(&mut [0; 4]));
glyphs[ch as usize] = Some(Self::glyph(&layout)?);
metrics.get_or_insert((layout.ascent, layout.descent));
}
for ch in NUMERIC_OPTIONAL.chars() {
glyphs[ch as usize] = Self::glyph(&shape(ch.encode_utf8(&mut [0; 4])));
}
let (ascent, descent) = metrics?;
Some(Self {
glyphs,
ascent,
descent,
})
}
fn glyph(layout: &LineLayout) -> Option<NumericGlyph> {
let [run] = layout.runs.as_slice() else {
return None;
};
let [glyph] = run.glyphs.as_slice() else {
return None;
};
Some(NumericGlyph {
font_id: run.font_id,
glyph_id: glyph.id,
advance: layout.width,
})
}
fn layout(&self, text: &str, font_size: Pixels, arena: &mut GlyphArena) -> Option<NumericLine> {
if !text
.bytes()
.all(|byte| self.glyphs.get(byte as usize).is_some_and(Option::is_some))
{
return None;
}
let start = arena.len();
let mut x = px(0.);
for byte in text.bytes() {
let glyph = self.glyphs[byte as usize].expect("checked above");
arena.push((glyph.font_id, glyph.glyph_id, x));
x += glyph.advance;
}
Some(NumericLine {
glyphs: start..arena.len(),
width: x,
ascent: self.ascent,
descent: self.descent,
font_size,
})
}
}
pub(crate) type GlyphArena = Vec<(FontId, GlyphId, Pixels)>;
pub(crate) struct NumericLine {
glyphs: Range<usize>,
width: Pixels,
ascent: Pixels,
descent: Pixels,
font_size: Pixels,
}
pub(crate) enum TextLayout {
Shaped(Arc<LineLayout>),
Numeric(NumericLine),
}
impl TextLayout {
pub fn width(&self) -> Pixels {
match self {
Self::Shaped(layout) => layout.width,
Self::Numeric(line) => line.width,
}
}
pub fn ascent_descent(&self) -> (Pixels, Pixels) {
match self {
Self::Shaped(layout) => (layout.ascent, layout.descent),
Self::Numeric(line) => (line.ascent, line.descent),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct TextStats {
hits: u64,
misses: u64,
numeric: u64,
entries: usize,
bold_entries: usize,
}
impl TextStats {
pub fn hits(&self) -> u64 {
self.hits
}
pub fn misses(&self) -> u64 {
self.misses
}
pub fn numeric(&self) -> u64 {
self.numeric
}
pub fn entries(&self) -> usize {
self.entries
}
pub fn bold_entries(&self) -> usize {
self.bold_entries
}
fn add(&mut self, other: TextStats) {
self.hits += other.hits;
self.misses += other.misses;
self.numeric += other.numeric;
self.entries += other.entries;
self.bold_entries += other.bold_entries;
}
}
pub(crate) struct TextCache {
entries: FxHashMap<u64, Entry>,
frame: u64,
font: Option<Font>,
font_size: Pixels,
ellipsis: Option<Arc<LineLayout>>,
numeric: Option<Option<NumericTable>>,
stats: TextStats,
}
impl Default for TextCache {
fn default() -> Self {
Self {
entries: FxHashMap::default(),
frame: 0,
font: None,
font_size: px(0.),
ellipsis: None,
numeric: None,
stats: TextStats::default(),
}
}
}
impl TextCache {
pub fn begin_frame(&mut self, font: &Font, font_size: Pixels) {
if self.font.as_ref() != Some(font) || self.font_size != font_size {
self.entries.clear();
self.ellipsis = None;
self.numeric = None;
self.font = Some(font.clone());
self.font_size = font_size;
}
self.frame += 1;
if self.frame % SWEEP_EVERY == 0 {
let frame = self.frame;
self.entries
.retain(|_, entry| entry.last_frame + KEEP_FRAMES >= frame);
}
}
fn shape(&self, text: &str, window: &Window) -> Arc<LineLayout> {
let runs = [TextRun {
len: text.len(),
font: self.font.clone().expect("begin_frame sets the font"),
color: black(),
background_color: None,
underline: None,
strikethrough: None,
}];
window
.text_system()
.layout_line(text, self.font_size, &runs, None)
}
pub fn layout(&mut self, text: &str, window: &Window, arena: &mut GlyphArena) -> TextLayout {
if self.numeric.is_none() {
self.numeric = Some(NumericTable::build(|text| self.shape(text, window)));
}
if let Some(layout) = self
.numeric
.as_ref()
.and_then(|table| table.as_ref())
.and_then(|table| table.layout(text, self.font_size, arena))
{
self.stats.numeric += 1;
return TextLayout::Numeric(layout);
}
let mut hasher = FxHasher::default();
text.hash(&mut hasher);
let key = hasher.finish();
if let Some(entry) = self.entries.get_mut(&key)
&& &*entry.text == text
{
entry.last_frame = self.frame;
self.stats.hits += 1;
return TextLayout::Shaped(entry.layout.clone());
}
self.stats.misses += 1;
let layout = self.shape(text, window);
self.entries.insert(
key,
Entry {
text: text.into(),
layout: layout.clone(),
last_frame: self.frame,
},
);
TextLayout::Shaped(layout)
}
pub fn ellipsis(&mut self, window: &Window) -> Arc<LineLayout> {
if self.ellipsis.is_none() {
self.ellipsis = Some(self.shape("…", window));
}
self.ellipsis.clone().expect("set above")
}
pub fn stats(&self) -> TextStats {
TextStats {
entries: self.entries.len(),
..self.stats
}
}
}
#[derive(Default)]
struct IconPaths {
entries: FxHashMap<u64, IconPath>,
}
struct IconPath {
path: SharedString,
last_frame: u64,
}
impl IconPaths {
fn get(&mut self, path: &str, frame: u64) -> SharedString {
let mut hasher = FxHasher::default();
path.hash(&mut hasher);
let key = hasher.finish();
match self.entries.get_mut(&key) {
Some(entry) if entry.path.as_ref() == path => {
entry.last_frame = frame;
entry.path.clone()
}
_ => {
let shared = SharedString::from(path.to_owned());
self.entries.insert(
key,
IconPath {
path: shared.clone(),
last_frame: frame,
},
);
shared
}
}
}
fn sweep(&mut self, frame: u64) {
self.entries
.retain(|_, entry| entry.last_frame + KEEP_FRAMES >= frame);
}
}
struct WeightCache {
weight: FontWeight,
cache: TextCache,
last_frame: u64,
}
#[derive(Default)]
pub(crate) struct TextCaches {
regular: TextCache,
by_weight: Vec<WeightCache>,
icon_paths: IconPaths,
frame: u64,
}
impl TextCaches {
pub fn begin_frame(&mut self, font: &Font, font_size: Pixels) {
self.frame += 1;
self.regular.begin_frame(font, font_size);
if self.frame % SWEEP_EVERY == 0 {
let frame = self.frame;
self.by_weight
.retain(|cache| cache.last_frame + KEEP_FRAMES >= frame);
self.icon_paths.sweep(frame);
}
}
pub fn icon_path(&mut self, path: &str) -> SharedString {
self.icon_paths.get(path, self.frame)
}
pub fn regular(&mut self) -> &mut TextCache {
&mut self.regular
}
#[inline]
pub fn for_weight(&mut self, weight: Option<FontWeight>) -> &mut TextCache {
match weight {
None => &mut self.regular,
Some(weight) => self.weighted(weight),
}
}
fn weighted(&mut self, weight: FontWeight) -> &mut TextCache {
let Some(font) = self
.regular
.font
.as_ref()
.filter(|font| font.weight != weight)
else {
return &mut self.regular;
};
let ix = match self
.by_weight
.iter()
.position(|cache| cache.weight == weight)
{
Some(ix) => ix,
None => {
self.by_weight.push(WeightCache {
weight,
cache: TextCache::default(),
last_frame: 0,
});
self.by_weight.len() - 1
}
};
let cache = &mut self.by_weight[ix];
if cache.last_frame != self.frame {
cache.last_frame = self.frame;
let font = Font {
weight,
..font.clone()
};
cache.cache.begin_frame(&font, self.regular.font_size);
}
&mut cache.cache
}
pub fn stats(&self) -> TextStats {
let mut stats = self.regular.stats();
for cache in &self.by_weight {
let weighted = cache.cache.stats();
stats.add(TextStats {
bold_entries: weighted.entries,
..weighted
});
}
stats
}
}
pub(crate) struct TextItem {
pub origin: Point<Pixels>,
pub layout: TextLayout,
pub max_width: Pixels,
pub color: Hsla,
pub ellipsis: Option<Arc<LineLayout>>,
}
pub(crate) fn paint_text(
item: &TextItem,
arena: &GlyphArena,
ellipsis: &LineLayout,
line_height: Pixels,
window: &mut Window,
) {
match &item.layout {
TextLayout::Shaped(layout) => paint_glyphs(
item,
layout
.runs
.iter()
.flat_map(|run| run.glyphs.iter().map(move |glyph| (run.font_id, glyph)))
.map(|(font_id, glyph)| Glyph {
font_id,
glyph_id: glyph.id,
x: glyph.position.x,
y: glyph.position.y,
is_emoji: glyph.is_emoji,
}),
Metrics {
width: layout.width,
ascent: layout.ascent,
descent: layout.descent,
font_size: layout.font_size,
},
ellipsis,
line_height,
window,
),
TextLayout::Numeric(line) => paint_glyphs(
item,
arena[line.glyphs.clone()]
.iter()
.map(|(font_id, glyph_id, x)| Glyph {
font_id: *font_id,
glyph_id: *glyph_id,
x: *x,
y: px(0.),
is_emoji: false,
}),
Metrics {
width: line.width,
ascent: line.ascent,
descent: line.descent,
font_size: line.font_size,
},
ellipsis,
line_height,
window,
),
}
}
struct Glyph {
font_id: FontId,
glyph_id: GlyphId,
x: Pixels,
y: Pixels,
is_emoji: bool,
}
struct Metrics {
width: Pixels,
ascent: Pixels,
descent: Pixels,
font_size: Pixels,
}
fn paint_glyphs(
item: &TextItem,
glyphs: impl Iterator<Item = Glyph>,
metrics: Metrics,
ellipsis: &LineLayout,
line_height: Pixels,
window: &mut Window,
) {
let padding_top = (line_height - metrics.ascent - metrics.descent) / 2.;
let baseline_y = item.origin.y + padding_top + metrics.ascent;
let truncate = metrics.width > item.max_width;
if truncate && item.max_width < ellipsis.width {
return;
}
let limit = if truncate {
item.max_width - ellipsis.width
} else {
metrics.width
};
let mut cut_x = metrics.width;
let mut glyphs = glyphs.peekable();
while let Some(glyph) = glyphs.next() {
let end = glyphs.peek().map_or(metrics.width, |next| next.x);
if truncate && end > limit {
cut_x = glyph.x;
break;
}
let origin = point(item.origin.x + glyph.x, baseline_y + glyph.y);
if glyph.is_emoji {
let _ = window.paint_emoji(origin, glyph.font_id, glyph.glyph_id, metrics.font_size);
} else {
let _ = window.paint_glyph(
origin,
glyph.font_id,
glyph.glyph_id,
metrics.font_size,
item.color,
);
}
}
if truncate {
for run in &ellipsis.runs {
for glyph in &run.glyphs {
let origin = point(
item.origin.x + cut_x + glyph.position.x,
baseline_y + glyph.position.y,
);
let _ = window.paint_glyph(
origin,
run.font_id,
glyph.id,
ellipsis.font_size,
item.color,
);
}
}
}
}