use std::{
borrow::Cow,
hash::{
Hash,
Hasher,
},
};
use freya_core::prelude::Color;
use freya_engine::prelude::{
Canvas,
Font,
FontCollection,
Paint,
Paragraph,
ParagraphBuilder,
ParagraphStyle,
SkRect,
TextBlob,
TextStyle,
};
use rio_vt::selection::SelectionRange;
use rustc_hash::FxHasher;
use tiny_cache::FifoCache;
use torin::prelude::Area;
use crate::{
cell::TermCell,
colors::map_ansi_color,
url::link_ranges,
};
pub(crate) enum CachedRow {
TextBlobs(Vec<(TextBlob, Color)>),
Paragraph(Paragraph),
}
pub(crate) struct Renderer<'a> {
pub canvas: &'a Canvas,
pub paint: &'a mut Paint,
pub font: &'a Font,
pub font_collection: &'a mut FontCollection,
pub row_cache: &'a mut FifoCache<u64, CachedRow>,
pub area: Area,
pub char_width: f32,
pub line_height: f32,
pub baseline_offset: f32,
pub foreground: Color,
pub background: Color,
pub selection_color: Color,
pub font_families: &'a [Cow<'static, str>],
pub font_size: f32,
pub selection: Option<SelectionRange>,
pub display_offset: usize,
}
impl Renderer<'_> {
pub fn render_background(&mut self) {
self.paint.set_color(self.background);
self.canvas.draw_rect(
SkRect::new(
self.area.min_x(),
self.area.min_y(),
self.area.max_x(),
self.area.max_y(),
),
self.paint,
);
}
pub fn render_row(&mut self, row_idx: usize, row: &[TermCell], y: f32) {
self.render_cell_backgrounds(row, y);
self.render_text_row(row, y);
self.render_hyperlink_underlines(row, y);
self.render_selection(row_idx, row.len(), y);
}
pub fn render_cursor(&mut self, cell: &TermCell, y: f32, cursor_col: usize) {
let left = self.area.min_x() + (cursor_col as f32) * self.char_width;
let right = left + self.char_width.max(1.0);
let bottom = y + self.line_height.max(1.0);
self.paint.set_color(self.foreground);
self.canvas.draw_rect(
SkRect::new(left, y.round(), right, bottom.round()),
self.paint,
);
let glyph = match cell.character {
'\0' | '\t' => ' ',
character => character,
};
let mut buf = [0u8; 4];
let content: &str = glyph.encode_utf8(&mut buf);
self.paint.set_color(self.background);
if let Some(blob) = TextBlob::from_pos_text_h(content, &[0.0], 0.0, self.font) {
self.canvas
.draw_text_blob(&blob, (left, y + self.baseline_offset), self.paint);
}
}
pub fn render_scrollbar(
&mut self,
scroll_offset: usize,
total_scrollback: usize,
rows_count: usize,
) {
let viewport_height = self.area.height();
let total_rows = rows_count + total_scrollback;
let total_content_height = total_rows as f32 * self.line_height;
let scrollbar_height = (viewport_height * viewport_height / total_content_height).max(20.0);
let track_height = viewport_height - scrollbar_height;
let scroll_ratio = scroll_offset as f32 / total_scrollback as f32;
let thumb_y = self.area.min_y() + track_height * (1.0 - scroll_ratio);
let scrollbar_x = self.area.max_x() - 4.0;
let corner_radius = 2.0;
self.paint.set_anti_alias(true);
self.paint.set_color(Color::from_argb(50, 0, 0, 0));
self.canvas.draw_round_rect(
SkRect::new(
scrollbar_x,
self.area.min_y(),
self.area.max_x(),
self.area.max_y(),
),
corner_radius,
corner_radius,
self.paint,
);
self.paint.set_color(Color::from_argb(60, 255, 255, 255));
self.canvas.draw_round_rect(
SkRect::new(
scrollbar_x,
thumb_y,
self.area.max_x(),
thumb_y + scrollbar_height,
),
corner_radius,
corner_radius,
self.paint,
);
}
fn render_cell_backgrounds(&mut self, row: &[TermCell], y: f32) {
let mut run_start: Option<(usize, Color)> = None;
let mut col = 0;
while col < row.len() {
let cell = &row[col];
if cell.wide_spacer {
col += 1;
continue;
}
let cell_bg = if cell.inverse {
map_ansi_color(cell.foreground, self.foreground, self.background)
} else {
map_ansi_color(cell.background, self.foreground, self.background)
};
let end_col = if cell.wide { col + 2 } else { col + 1 };
if cell_bg != self.background {
match &run_start {
Some((_, color)) if *color == cell_bg => {}
Some((start, color)) => {
self.fill_cells(*start, col, *color, y);
run_start = Some((col, cell_bg));
}
None => {
run_start = Some((col, cell_bg));
}
}
} else if let Some((start, color)) = run_start.take() {
self.fill_cells(start, col, color, y);
}
col = end_col;
}
if let Some((start, color)) = run_start {
self.fill_cells(start, col, color, y);
}
}
fn fill_cells(&mut self, start: usize, end: usize, color: Color, y: f32) {
let left = self.area.min_x() + (start as f32) * self.char_width;
let right = self.area.min_x() + (end as f32) * self.char_width;
self.paint.set_color(color);
self.canvas.draw_rect(
SkRect::new(left, y.round(), right, (y + self.line_height).round()),
self.paint,
);
}
fn render_hyperlink_underlines(&mut self, row: &[TermCell], y: f32) {
let underline_y = (y + self.line_height - 2.0).round();
self.paint.set_color(self.foreground);
for (start, end) in link_ranges(row) {
let left = self.area.min_x() + (start as f32) * self.char_width;
let right = self.area.min_x() + (end as f32) * self.char_width;
self.canvas.draw_rect(
SkRect::new(left, underline_y, right, underline_y + 1.0),
self.paint,
);
}
}
fn render_selection(&mut self, row_idx: usize, row_len: usize, y: f32) {
let Some(range) = self.selection else {
return;
};
let offset = self.display_offset as i64;
let start_row = range.start.row.0 as i64 + offset;
let end_row = range.end.row.0 as i64 + offset;
let row_i = row_idx as i64;
if row_i < start_row || row_i > end_row {
return;
}
let sel_start = if row_i == start_row {
range.start.col.0
} else {
0
};
let sel_end = if row_i == end_row {
(range.end.col.0 + 1).min(row_len)
} else {
row_len
};
if sel_start >= sel_end {
return;
}
let left = self.area.min_x() + (sel_start as f32) * self.char_width;
let right = self.area.min_x() + (sel_end as f32) * self.char_width;
self.paint.set_color(self.selection_color);
self.canvas.draw_rect(
SkRect::new(left, y.round(), right, (y + self.line_height).round()),
self.paint,
);
}
fn render_text_row(&mut self, row: &[TermCell], y: f32) {
let mut hasher = FxHasher::default();
self.font.typeface().unique_id().hash(&mut hasher);
self.font_size.to_bits().hash(&mut hasher);
self.char_width.to_bits().hash(&mut hasher);
self.font_families.hash(&mut hasher);
let mut needs_fallback = false;
let mut text = String::new();
for cell in row.iter() {
if cell.wide_spacer {
continue;
}
write_cell_text(cell, &mut text);
let cell_fg = self.cell_foreground(cell);
text.hash(&mut hasher);
cell_fg.hash(&mut hasher);
if !needs_fallback {
needs_fallback = cell.wide
|| (!text.is_ascii() && self.font.text_to_glyphs_vec(&text).contains(&0));
}
}
let cache_key = hasher.finish();
let text_y = y + self.baseline_offset;
let area_min_x = self.area.min_x();
if let Some(cached) = self.row_cache.get(&cache_key) {
match cached {
CachedRow::TextBlobs(blobs) => {
for (blob, color) in blobs {
self.paint.set_color(*color);
self.canvas
.draw_text_blob(blob, (area_min_x, text_y), self.paint);
}
}
CachedRow::Paragraph(paragraph) => {
paragraph.paint(self.canvas, (area_min_x, y));
}
}
} else if needs_fallback {
self.render_paragraph(row, y, cache_key);
} else {
self.render_textblob(row, text_y, cache_key);
}
}
fn cell_foreground(&self, cell: &TermCell) -> Color {
map_ansi_color(
if cell.inverse {
cell.background
} else {
cell.foreground
},
self.foreground,
self.background,
)
}
fn render_textblob(&mut self, row: &[TermCell], text_y: f32, cache_key: u64) {
let mut current_color: Option<Color> = None;
let mut glyphs = String::new();
let mut glyph_positions: Vec<f32> = Vec::new();
let mut blobs: Vec<(TextBlob, Color)> = Vec::new();
let mut text = String::new();
for (col_idx, cell) in row.iter().enumerate() {
if cell.wide_spacer {
continue;
}
let cell_fg = self.cell_foreground(cell);
write_cell_text(cell, &mut text);
let x = (col_idx as f32) * self.char_width;
if current_color != Some(cell_fg) {
if let Some(prev_color) = current_color {
self.flush_blob(&glyphs, &glyph_positions, text_y, &mut blobs, prev_color);
glyphs.clear();
glyph_positions.clear();
}
current_color = Some(cell_fg);
}
for _ in text.chars() {
glyph_positions.push(x);
}
glyphs.push_str(&text);
}
if let Some(color) = current_color
&& !glyphs.is_empty()
{
self.flush_blob(&glyphs, &glyph_positions, text_y, &mut blobs, color);
}
self.row_cache
.insert(cache_key, CachedRow::TextBlobs(blobs));
}
fn flush_blob(
&mut self,
glyphs: &str,
glyph_positions: &[f32],
text_y: f32,
blobs: &mut Vec<(TextBlob, Color)>,
color: Color,
) {
if let Some(blob) = TextBlob::from_pos_text_h(glyphs, glyph_positions, 0.0, self.font) {
self.paint.set_color(color);
self.canvas
.draw_text_blob(&blob, (self.area.min_x(), text_y), self.paint);
blobs.push((blob, color));
}
}
fn render_paragraph(&mut self, row: &[TermCell], row_y: f32, cache_key: u64) {
let mut text_style = TextStyle::new();
text_style.set_font_size(self.font_size);
text_style.set_font_families(self.font_families);
text_style.set_color(self.foreground);
let mut builder =
ParagraphBuilder::new(&ParagraphStyle::default(), self.font_collection.clone());
let mut text = String::new();
for cell in row.iter() {
if cell.wide_spacer {
continue;
}
let mut cell_style = text_style.clone();
cell_style.set_color(self.cell_foreground(cell));
builder.push_style(&cell_style);
write_cell_text(cell, &mut text);
builder.add_text(text.as_str());
}
let mut paragraph = builder.build();
paragraph.layout(f32::MAX);
paragraph.paint(self.canvas, (self.area.min_x(), row_y));
self.row_cache
.insert(cache_key, CachedRow::Paragraph(paragraph));
}
}
fn write_cell_text(cell: &TermCell, text: &mut String) {
text.clear();
text.push(match cell.character {
'\0' | '\t' => ' ',
character => character,
});
text.extend(&cell.zerowidth);
}