use crate::error::Error;
use crate::host::{ClipboardPayload, HostProjection, HostText};
use crate::layout::{
self, HitMap, Pointer, TableGeom, TableMetrics, Viewport, HEADER_H, PAD, ROW_H,
};
use crate::lens::LicenseLens;
use crate::mode::SurfaceMode;
use crate::model::{CellValue, Grid};
use crate::raster::Pixmap;
use crate::theme::Theme;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FrameRequest {
pub viewport: Viewport,
pub pointer: Option<Pointer>,
pub caption: Option<String>,
pub column_widths: Option<Vec<u32>>,
}
impl FrameRequest {
#[must_use]
pub fn full(viewport: Viewport) -> Self {
Self {
viewport,
pointer: None,
caption: None,
column_widths: None,
}
}
#[must_use]
pub fn pointer(mut self, pointer: Pointer) -> Self {
self.pointer = Some(pointer);
self
}
#[must_use]
pub fn caption(mut self, caption: impl Into<String>) -> Self {
self.caption = Some(caption.into());
self
}
#[must_use]
pub fn column_widths(mut self, widths: Vec<u32>) -> Self {
self.column_widths = Some(widths);
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Frame {
pub png: Vec<u8>,
pub hits: HitMap,
pub host: HostProjection,
pub tooltip_png: Option<Vec<u8>>,
pub viewed: Grid,
pub content_width: u32,
pub content_height: u32,
pub visible_row_start: u32,
pub visible_row_end: u32,
}
#[derive(Debug, Clone)]
pub struct Surface {
mode: SurfaceMode,
lens: LicenseLens,
theme: Theme,
}
impl Surface {
#[must_use]
pub fn new(mode: SurfaceMode, lens: LicenseLens) -> Self {
Self {
mode,
lens,
theme: Theme::default(),
}
}
pub fn set_mode(&mut self, mode: SurfaceMode) {
self.mode = mode;
}
#[must_use]
pub const fn mode(&self) -> SurfaceMode {
self.mode
}
pub fn set_lens(&mut self, lens: LicenseLens) {
self.lens = lens;
}
#[must_use]
pub fn lens(&self) -> &LicenseLens {
&self.lens
}
pub fn set_theme(&mut self, theme: Theme) {
self.theme = theme;
}
#[must_use]
pub const fn theme(&self) -> Theme {
self.theme
}
pub fn render_series(
&self,
layout: &crate::SeriesLayout,
request: &FrameRequest,
) -> Result<Frame, Error> {
crate::chart::render_timeseries(self, layout, request)
}
#[must_use]
pub fn metrics(&self, grid: &Grid) -> TableMetrics {
let viewed = self.lens.apply(grid);
layout::metrics(&viewed, self.lens.style.glyph_str(), None)
}
pub fn render(&self, grid: &Grid, request: &FrameRequest) -> Result<Frame, Error> {
let viewed = self.lens.apply(grid);
let placeholder = self.lens.style.glyph_str();
let override_w = request.column_widths.as_deref();
let geom = layout::layout_visible(&viewed, placeholder, request.viewport, override_w);
let mut pm = Pixmap::new(geom.pixmap_w, geom.pixmap_h, self.theme.background)?;
self.paint_table(&mut pm, &viewed, &geom, placeholder, request.pointer);
if let Some(caption) = &request.caption {
pm.text(
PAD,
1,
caption,
self.theme.accent,
geom.pixmap_w.saturating_sub(PAD),
);
}
let png = pm.to_png()?;
let hits = HitMap { boxes: geom.boxes };
let tooltip_png = match request.pointer {
Some(p) => self.tooltip_png(&viewed, &hits, p, placeholder)?,
None => None,
};
let host = self.host_projection(&viewed, request, geom.first_row, geom.row_end);
Ok(Frame {
png,
hits,
host,
tooltip_png,
viewed,
content_width: geom.content_width,
content_height: geom.content_height,
visible_row_start: geom.first_row,
visible_row_end: geom.row_end,
})
}
fn paint_table(
&self,
pm: &mut Pixmap,
grid: &Grid,
geom: &TableGeom,
placeholder: &str,
pointer: Option<Pointer>,
) {
let hover = pointer.and_then(|p| {
geom.boxes
.iter()
.rev()
.find(|b| b.contains(p.x, p.y))
.copied()
});
let mut buf = String::with_capacity(32);
for b in &geom.boxes {
if b.header {
let Some(col) = grid.columns.get(b.col_index as usize) else {
continue;
};
pm.fill_rect(b.x, b.y, b.w, b.h, self.theme.header);
pm.text(
b.x.saturating_add(4),
b.y.saturating_add(6),
&col.header,
self.theme.accent,
b.w.saturating_sub(8),
);
continue;
}
let Some(row) = b.row_index.and_then(|ri| grid.rows.get(ri as usize)) else {
continue;
};
let Some(cell) = row.cells.get(b.col_index as usize) else {
continue;
};
let is_hover = hover.is_some_and(|h| {
h.row_index == b.row_index && h.col_index == b.col_index && !h.header
});
let fill = if matches!(cell, CellValue::Redacted) {
self.theme.redacted
} else if is_hover {
self.theme.hover
} else {
self.theme.background
};
pm.fill_rect(b.x, b.y, b.w, b.h, fill);
buf.clear();
let color = if matches!(cell, CellValue::Redacted) {
cell.write_paint(&mut buf, placeholder);
self.theme.redacted_text
} else {
cell.write_paint(&mut buf, placeholder);
self.theme.text
};
pm.text(
b.x.saturating_add(4),
b.y.saturating_add(5),
&buf,
color,
b.w.saturating_sub(8),
);
}
self.paint_gridlines(pm, geom);
}
fn paint_gridlines(&self, pm: &mut Pixmap, geom: &TableGeom) {
let table_w: u32 = geom.col_widths.iter().copied().sum();
let body_top = PAD + HEADER_H;
let last_y = {
let y = i64::from(body_top) + i64::from(geom.row_end) * i64::from(ROW_H)
- i64::from(geom.origin_y);
y.clamp(
i64::from(body_top),
i64::from(geom.pixmap_h.saturating_sub(1)),
) as u32
};
if let Some((x, w)) = clip_hline(PAD, table_w, geom.origin_x, geom.pixmap_w) {
pm.hline(x, PAD, w, self.theme.grid);
if body_top < geom.pixmap_h {
pm.hline(
x,
body_top.min(geom.pixmap_h.saturating_sub(1)),
w,
self.theme.grid,
);
}
}
let v_h = last_y.saturating_sub(PAD).max(1);
let mut x_content = PAD;
for wcol in &geom.col_widths {
if let Some((x, _)) = clip_vline(x_content, geom.origin_x, geom.pixmap_w) {
pm.vline(
x,
PAD,
v_h.min(geom.pixmap_h.saturating_sub(PAD)),
self.theme.grid,
);
}
x_content = x_content.saturating_add(*wcol);
}
if let Some((x, _)) = clip_vline(x_content, geom.origin_x, geom.pixmap_w) {
pm.vline(
x,
PAD,
v_h.min(geom.pixmap_h.saturating_sub(PAD)),
self.theme.grid,
);
}
for ri in geom.first_row..=geom.row_end {
let y =
i64::from(body_top) + i64::from(ri) * i64::from(ROW_H) - i64::from(geom.origin_y);
if y < i64::from(body_top) || y >= i64::from(geom.pixmap_h) {
continue;
}
if let Some((x, w)) = clip_hline(PAD, table_w, geom.origin_x, geom.pixmap_w) {
pm.hline(x, y as u32, w, self.theme.grid);
}
}
}
fn tooltip_png(
&self,
grid: &Grid,
hits: &HitMap,
pointer: Pointer,
placeholder: &str,
) -> Result<Option<Vec<u8>>, Error> {
let Some(hit) = hits.at(pointer.x, pointer.y) else {
return Ok(None);
};
if hit.kind != crate::layout::HitKind::Cell {
return Ok(None);
}
let Some(ri) = hit.row_index else {
return Ok(None);
};
let Some(row) = grid.rows.get(ri as usize) else {
return Ok(None);
};
let Some(cell) = row.cells.get(hit.col_index as usize) else {
return Ok(None);
};
let Some(col) = grid.columns.get(hit.col_index as usize) else {
return Ok(None);
};
let mut body = String::new();
cell.write_paint(&mut body, placeholder);
let label = format!("{}: {body}", col.header);
let tw = font_width_padded(&label);
let mut pm = Pixmap::new(tw.max(40), 22, self.theme.tooltip)?;
pm.fill_rect(0, 0, pm.width(), 1, self.theme.accent);
pm.text(6, 7, &label, self.theme.text, pm.width().saturating_sub(8));
Ok(Some(pm.to_png()?))
}
fn host_projection(
&self,
viewed: &Grid,
request: &FrameRequest,
row_start: u32,
row_end: u32,
) -> HostProjection {
if self.mode.is_sealed() {
return HostProjection::sealed();
}
let mut text_nodes = Vec::new();
if let Some(caption) = &request.caption {
text_nodes.push(HostText {
kind: "caption",
text: caption.clone(),
});
}
let mut tsv = String::new();
for (i, col) in viewed.columns.iter().enumerate() {
if i > 0 {
tsv.push('\t');
}
tsv.push_str(&col.header);
}
tsv.push('\n');
let start = row_start as usize;
let end = (row_end as usize).min(viewed.rows.len());
for row in viewed.rows.get(start..end).unwrap_or(&[]) {
for (i, cell) in row.cells.iter().enumerate() {
if i > 0 {
tsv.push('\t');
}
if let Some(s) = cell.copy_str() {
tsv.push_str(&s);
}
}
tsv.push('\n');
}
HostProjection {
text_nodes,
clipboard: Some(ClipboardPayload::Tsv(tsv)),
}
}
}
fn clip_hline(content_x: u32, span: u32, origin: u32, pixmap_w: u32) -> Option<(u32, u32)> {
let x1 = content_x as i64 - origin as i64;
let x2 = x1 + span as i64;
let vis_x1 = x1.max(0);
let vis_x2 = x2.min(pixmap_w as i64);
if vis_x2 <= vis_x1 {
return None;
}
Some((vis_x1 as u32, (vis_x2 - vis_x1) as u32))
}
fn clip_vline(content_x: u32, origin: u32, pixmap_w: u32) -> Option<(u32, u32)> {
let x = content_x as i64 - origin as i64;
if x < 0 || x >= pixmap_w as i64 {
return None;
}
Some((x as u32, 1))
}
fn font_width_padded(s: &str) -> u32 {
crate::font::measure(s).saturating_add(16).max(48)
}
impl Default for Surface {
fn default() -> Self {
Self::new(
SurfaceMode::Sealed,
LicenseLens::from_tier(crate::AccessTier::Public),
)
}
}