use crate::appearance::Appearance;
use crate::error::Error;
use crate::host::{ClipboardPayload, HostProjection, HostText};
use crate::layout::{self, HitMap, Pointer, TableGeom, TableMetrics, Viewport};
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,
appearance: Appearance,
}
impl Surface {
#[must_use]
pub fn new(mode: SurfaceMode, lens: LicenseLens) -> Self {
Self {
mode,
lens,
appearance: Appearance::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.appearance.theme = theme;
self.appearance.chart = crate::appearance::ChartStyle::from_theme(&theme);
}
#[must_use]
pub const fn theme(&self) -> Theme {
self.appearance.theme
}
pub fn set_appearance(&mut self, appearance: Appearance) {
self.appearance = appearance;
}
#[must_use]
pub const fn appearance(&self) -> Appearance {
self.appearance
}
pub fn set_type_scale(&mut self, scale: crate::appearance::TypeScale) {
self.appearance.type_scale = scale;
}
pub fn render_series(
&self,
layout: &crate::SeriesLayout,
request: &FrameRequest,
) -> Result<Frame, Error> {
crate::chart::render_timeseries(self, layout, request)
}
pub fn render_scatter(
&self,
layout: &crate::SeriesLayout,
request: &FrameRequest,
) -> Result<Frame, Error> {
crate::chart::render_scatter_plot(self, layout, request)
}
pub fn render_tree(
&self,
layout: &crate::TreeLayout,
request: &FrameRequest,
) -> Result<Frame, Error> {
crate::tree::render_tree(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,
self.appearance.type_scale,
)
}
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,
self.appearance.type_scale,
);
let mut pm = Pixmap::new(
geom.pixmap_w,
geom.pixmap_h,
self.appearance.theme.background,
)?;
self.paint_table(&mut pm, &viewed, &geom, placeholder, request.pointer);
if let Some(caption) = &request.caption {
pm.text_scaled(
geom.pad,
1,
caption,
self.appearance.theme.accent,
geom.pixmap_w.saturating_sub(geom.pad),
self.appearance.type_scale,
);
}
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);
let theme = self.appearance.theme;
let scale = self.appearance.type_scale;
let inset = scale.pixel().saturating_mul(2).max(2);
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, theme.header);
pm.text_scaled(
b.x.saturating_add(inset),
b.y.saturating_add(scale.pixel().saturating_mul(3)),
&col.header,
theme.accent,
b.w.saturating_sub(inset * 2),
scale,
);
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) {
theme.redacted
} else if is_hover {
theme.hover
} else {
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);
theme.redacted_text
} else {
cell.write_paint(&mut buf, placeholder);
theme.text
};
pm.text_scaled(
b.x.saturating_add(inset),
b.y.saturating_add(scale.pixel().saturating_mul(2)),
&buf,
color,
b.w.saturating_sub(inset * 2),
scale,
);
}
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 pad = geom.pad;
let body_top = pad + geom.header_h;
let grid = self.appearance.theme.grid;
let last_y = {
let y = i64::from(body_top) + i64::from(geom.row_end) * i64::from(geom.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, grid);
if body_top < geom.pixmap_h {
pm.hline(x, body_top.min(geom.pixmap_h.saturating_sub(1)), w, 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)), 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)), grid);
}
for ri in geom.first_row..=geom.row_end {
let y = i64::from(body_top) + i64::from(ri) * i64::from(geom.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, 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 scale = self.appearance.type_scale;
let tw = crate::font::measure(&label, scale)
.saturating_add(16)
.max(48);
let th = scale.row_height().saturating_add(4).max(22);
let mut pm = Pixmap::new(tw.max(40), th, self.appearance.theme.tooltip)?;
pm.fill_rect(0, 0, pm.width(), 1, self.appearance.theme.accent);
pm.text_scaled(
6,
scale.pixel().saturating_mul(2),
&label,
self.appearance.theme.text,
pm.width().saturating_sub(8),
scale,
);
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))
}
impl Default for Surface {
fn default() -> Self {
Self::new(
SurfaceMode::Sealed,
LicenseLens::from_tier(crate::AccessTier::Public),
)
}
}