Skip to main content

sealed_surface/
surface.rs

1//! Public render entry.
2
3use crate::appearance::Appearance;
4use crate::error::Error;
5use crate::host::{ClipboardPayload, HostProjection, HostText};
6use crate::layout::{self, HitMap, Pointer, TableGeom, TableMetrics, Viewport};
7use crate::lens::LicenseLens;
8use crate::mode::SurfaceMode;
9use crate::model::{CellValue, Grid};
10use crate::raster::Pixmap;
11use crate::theme::Theme;
12
13/// Inputs for one frame.
14#[derive(Debug, Clone)]
15#[non_exhaustive]
16pub struct FrameRequest {
17    /// Window. `origin_*` scrolls; pixmap is the visible remainder, capped.
18    pub viewport: Viewport,
19    /// Optional pointer for hover fill + tooltip PNG (pixmap space).
20    pub pointer: Option<Pointer>,
21    /// Optional caption. Painted as glyphs. Included in host text **only** when copyable.
22    pub caption: Option<String>,
23    /// Host column widths in pixels. `None` measures from the viewed grid.
24    /// Extra entries are ignored; missing columns are measured.
25    pub column_widths: Option<Vec<u32>>,
26}
27
28impl FrameRequest {
29    /// Full default origin, no pointer, measured columns.
30    #[must_use]
31    pub fn full(viewport: Viewport) -> Self {
32        Self {
33            viewport,
34            pointer: None,
35            caption: None,
36            column_widths: None,
37        }
38    }
39
40    /// Pointer in pixmap space (hover + tooltip).
41    #[must_use]
42    pub fn pointer(mut self, pointer: Pointer) -> Self {
43        self.pointer = Some(pointer);
44        self
45    }
46
47    /// Caption painted as glyphs (host text only when copyable).
48    #[must_use]
49    pub fn caption(mut self, caption: impl Into<String>) -> Self {
50        self.caption = Some(caption.into());
51        self
52    }
53
54    /// Host-provided column widths (pixels). Missing columns are measured.
55    #[must_use]
56    pub fn column_widths(mut self, widths: Vec<u32>) -> Self {
57        self.column_widths = Some(widths);
58        self
59    }
60}
61
62/// One painted frame plus the host leak surface.
63#[derive(Debug, Clone)]
64#[non_exhaustive]
65pub struct Frame {
66    /// PNG bytes (`image/png`).
67    pub png: Vec<u8>,
68    /// Hit index in the same pixel space as `png` (visible cells only).
69    pub hits: HitMap,
70    /// Strings the host may emit. Empty of cell values when sealed.
71    pub host: HostProjection,
72    /// Tooltip PNG when `pointer` hit a data cell. Never a JSON value.
73    pub tooltip_png: Option<Vec<u8>>,
74    /// Grid after the lens (redacted cells have no original scalars).
75    pub viewed: Grid,
76    /// Full table width (scrollbars). Independent of the viewport.
77    pub content_width: u32,
78    /// Full table height (scrollbars). Independent of the viewport.
79    pub content_height: u32,
80    /// First visible data-row index (viewed grid).
81    pub visible_row_start: u32,
82    /// Exclusive end of visible data-row indices.
83    pub visible_row_end: u32,
84}
85
86/// Stateful renderer.
87#[derive(Debug, Clone)]
88pub struct Surface {
89    mode: SurfaceMode,
90    lens: LicenseLens,
91    appearance: Appearance,
92}
93
94impl Surface {
95    /// Construct (compact 5×7 default appearance).
96    #[must_use]
97    pub fn new(mode: SurfaceMode, lens: LicenseLens) -> Self {
98        Self {
99            mode,
100            lens,
101            appearance: Appearance::default(),
102        }
103    }
104
105    /// Replace mode (same painter).
106    pub fn set_mode(&mut self, mode: SurfaceMode) {
107        self.mode = mode;
108    }
109
110    /// Current mode.
111    #[must_use]
112    pub const fn mode(&self) -> SurfaceMode {
113        self.mode
114    }
115
116    /// Replace lens.
117    pub fn set_lens(&mut self, lens: LicenseLens) {
118        self.lens = lens;
119    }
120
121    /// Current lens.
122    #[must_use]
123    pub fn lens(&self) -> &LicenseLens {
124        &self.lens
125    }
126
127    /// Override theme (keeps type scale and chart style).
128    pub fn set_theme(&mut self, theme: Theme) {
129        self.appearance.theme = theme;
130        self.appearance.chart = crate::appearance::ChartStyle::from_theme(&theme);
131    }
132
133    /// Current theme.
134    #[must_use]
135    pub const fn theme(&self) -> Theme {
136        self.appearance.theme
137    }
138
139    /// Replace the full look.
140    pub fn set_appearance(&mut self, appearance: Appearance) {
141        self.appearance = appearance;
142    }
143
144    /// Current look.
145    #[must_use]
146    pub const fn appearance(&self) -> Appearance {
147        self.appearance
148    }
149
150    /// Glyph / cell metrics only.
151    pub fn set_type_scale(&mut self, scale: crate::appearance::TypeScale) {
152        self.appearance.type_scale = scale;
153    }
154
155    /// Paint a timeseries ([`crate::SeriesLayout`]) with the same seal contract.
156    ///
157    /// # Errors
158    ///
159    /// Empty layout or raster failure.
160    pub fn render_series(
161        &self,
162        layout: &crate::SeriesLayout,
163        request: &FrameRequest,
164    ) -> Result<Frame, Error> {
165        crate::chart::render_timeseries(self, layout, request)
166    }
167
168    /// Scatter: same samples as [`Self::render_series`], unconnected markers.
169    ///
170    /// # Errors
171    ///
172    /// Empty layout or raster failure.
173    pub fn render_scatter(
174        &self,
175        layout: &crate::SeriesLayout,
176        request: &FrameRequest,
177    ) -> Result<Frame, Error> {
178        crate::chart::render_scatter_plot(self, layout, request)
179    }
180
181    /// Squarified treemap ([`crate::TreeLayout`]).
182    ///
183    /// # Errors
184    ///
185    /// Raster failure or empty mass after the lens (still paints an empty well).
186    pub fn render_tree(
187        &self,
188        layout: &crate::TreeLayout,
189        request: &FrameRequest,
190    ) -> Result<Frame, Error> {
191        crate::tree::render_tree(self, layout, request)
192    }
193
194    /// Content size and column widths after the lens, without painting.
195    #[must_use]
196    pub fn metrics(&self, grid: &Grid) -> TableMetrics {
197        let viewed = self.lens.apply(grid);
198        layout::metrics(
199            &viewed,
200            self.lens.style.glyph_str(),
201            None,
202            self.appearance.type_scale,
203        )
204    }
205
206    /// Apply lens, paint the **visible window**, encode PNG, build host projection.
207    ///
208    /// # Errors
209    ///
210    /// Invalid grid (via lens output), raster failure, or PNG encode failure.
211    pub fn render(&self, grid: &Grid, request: &FrameRequest) -> Result<Frame, Error> {
212        let viewed = self.lens.apply(grid);
213        let placeholder = self.lens.style.glyph_str();
214        let override_w = request.column_widths.as_deref();
215        let geom = layout::layout_visible(
216            &viewed,
217            placeholder,
218            request.viewport,
219            override_w,
220            self.appearance.type_scale,
221        );
222
223        let mut pm = Pixmap::new(
224            geom.pixmap_w,
225            geom.pixmap_h,
226            self.appearance.theme.background,
227        )?;
228        self.paint_table(&mut pm, &viewed, &geom, placeholder, request.pointer);
229
230        if let Some(caption) = &request.caption {
231            pm.text_scaled(
232                geom.pad,
233                1,
234                caption,
235                self.appearance.theme.accent,
236                geom.pixmap_w.saturating_sub(geom.pad),
237                self.appearance.type_scale,
238            );
239        }
240
241        let png = pm.to_png()?;
242        let hits = HitMap { boxes: geom.boxes };
243
244        let tooltip_png = match request.pointer {
245            Some(p) => self.tooltip_png(&viewed, &hits, p, placeholder)?,
246            None => None,
247        };
248
249        let host = self.host_projection(&viewed, request, geom.first_row, geom.row_end);
250
251        Ok(Frame {
252            png,
253            hits,
254            host,
255            tooltip_png,
256            viewed,
257            content_width: geom.content_width,
258            content_height: geom.content_height,
259            visible_row_start: geom.first_row,
260            visible_row_end: geom.row_end,
261        })
262    }
263
264    fn paint_table(
265        &self,
266        pm: &mut Pixmap,
267        grid: &Grid,
268        geom: &TableGeom,
269        placeholder: &str,
270        pointer: Option<Pointer>,
271    ) {
272        let hover = pointer.and_then(|p| {
273            geom.boxes
274                .iter()
275                .rev()
276                .find(|b| b.contains(p.x, p.y))
277                .copied()
278        });
279
280        let mut buf = String::with_capacity(32);
281        let theme = self.appearance.theme;
282        let scale = self.appearance.type_scale;
283        let inset = scale.pixel().saturating_mul(2).max(2);
284        for b in &geom.boxes {
285            if b.header {
286                let Some(col) = grid.columns.get(b.col_index as usize) else {
287                    continue;
288                };
289                pm.fill_rect(b.x, b.y, b.w, b.h, theme.header);
290                pm.text_scaled(
291                    b.x.saturating_add(inset),
292                    b.y.saturating_add(scale.pixel().saturating_mul(3)),
293                    &col.header,
294                    theme.accent,
295                    b.w.saturating_sub(inset * 2),
296                    scale,
297                );
298                continue;
299            }
300            let Some(row) = b.row_index.and_then(|ri| grid.rows.get(ri as usize)) else {
301                continue;
302            };
303            let Some(cell) = row.cells.get(b.col_index as usize) else {
304                continue;
305            };
306            let is_hover = hover.is_some_and(|h| {
307                h.row_index == b.row_index && h.col_index == b.col_index && !h.header
308            });
309            let fill = if matches!(cell, CellValue::Redacted) {
310                theme.redacted
311            } else if is_hover {
312                theme.hover
313            } else {
314                theme.background
315            };
316            pm.fill_rect(b.x, b.y, b.w, b.h, fill);
317            buf.clear();
318            let color = if matches!(cell, CellValue::Redacted) {
319                cell.write_paint(&mut buf, placeholder);
320                theme.redacted_text
321            } else {
322                cell.write_paint(&mut buf, placeholder);
323                theme.text
324            };
325            pm.text_scaled(
326                b.x.saturating_add(inset),
327                b.y.saturating_add(scale.pixel().saturating_mul(2)),
328                &buf,
329                color,
330                b.w.saturating_sub(inset * 2),
331                scale,
332            );
333        }
334
335        self.paint_gridlines(pm, geom);
336    }
337
338    fn paint_gridlines(&self, pm: &mut Pixmap, geom: &TableGeom) {
339        let table_w: u32 = geom.col_widths.iter().copied().sum();
340        let pad = geom.pad;
341        let body_top = pad + geom.header_h;
342        let grid = self.appearance.theme.grid;
343        let last_y = {
344            let y = i64::from(body_top) + i64::from(geom.row_end) * i64::from(geom.row_h)
345                - i64::from(geom.origin_y);
346            y.clamp(
347                i64::from(body_top),
348                i64::from(geom.pixmap_h.saturating_sub(1)),
349            ) as u32
350        };
351
352        if let Some((x, w)) = clip_hline(pad, table_w, geom.origin_x, geom.pixmap_w) {
353            pm.hline(x, pad, w, grid);
354            if body_top < geom.pixmap_h {
355                pm.hline(x, body_top.min(geom.pixmap_h.saturating_sub(1)), w, grid);
356            }
357        }
358
359        let v_h = last_y.saturating_sub(pad).max(1);
360        let mut x_content = pad;
361        for wcol in &geom.col_widths {
362            if let Some((x, _)) = clip_vline(x_content, geom.origin_x, geom.pixmap_w) {
363                pm.vline(x, pad, v_h.min(geom.pixmap_h.saturating_sub(pad)), grid);
364            }
365            x_content = x_content.saturating_add(*wcol);
366        }
367        if let Some((x, _)) = clip_vline(x_content, geom.origin_x, geom.pixmap_w) {
368            pm.vline(x, pad, v_h.min(geom.pixmap_h.saturating_sub(pad)), grid);
369        }
370
371        for ri in geom.first_row..=geom.row_end {
372            let y = i64::from(body_top) + i64::from(ri) * i64::from(geom.row_h)
373                - i64::from(geom.origin_y);
374            if y < i64::from(body_top) || y >= i64::from(geom.pixmap_h) {
375                continue;
376            }
377            if let Some((x, w)) = clip_hline(pad, table_w, geom.origin_x, geom.pixmap_w) {
378                pm.hline(x, y as u32, w, grid);
379            }
380        }
381    }
382
383    fn tooltip_png(
384        &self,
385        grid: &Grid,
386        hits: &HitMap,
387        pointer: Pointer,
388        placeholder: &str,
389    ) -> Result<Option<Vec<u8>>, Error> {
390        let Some(hit) = hits.at(pointer.x, pointer.y) else {
391            return Ok(None);
392        };
393        if hit.kind != crate::layout::HitKind::Cell {
394            return Ok(None);
395        }
396        let Some(ri) = hit.row_index else {
397            return Ok(None);
398        };
399        let Some(row) = grid.rows.get(ri as usize) else {
400            return Ok(None);
401        };
402        let Some(cell) = row.cells.get(hit.col_index as usize) else {
403            return Ok(None);
404        };
405        let Some(col) = grid.columns.get(hit.col_index as usize) else {
406            return Ok(None);
407        };
408        let mut body = String::new();
409        cell.write_paint(&mut body, placeholder);
410        let label = format!("{}: {body}", col.header);
411        let scale = self.appearance.type_scale;
412        let tw = crate::font::measure(&label, scale)
413            .saturating_add(16)
414            .max(48);
415        let th = scale.row_height().saturating_add(4).max(22);
416        let mut pm = Pixmap::new(tw.max(40), th, self.appearance.theme.tooltip)?;
417        pm.fill_rect(0, 0, pm.width(), 1, self.appearance.theme.accent);
418        pm.text_scaled(
419            6,
420            scale.pixel().saturating_mul(2),
421            &label,
422            self.appearance.theme.text,
423            pm.width().saturating_sub(8),
424            scale,
425        );
426        Ok(Some(pm.to_png()?))
427    }
428
429    fn host_projection(
430        &self,
431        viewed: &Grid,
432        request: &FrameRequest,
433        row_start: u32,
434        row_end: u32,
435    ) -> HostProjection {
436        if self.mode.is_sealed() {
437            return HostProjection::sealed();
438        }
439        let mut text_nodes = Vec::new();
440        if let Some(caption) = &request.caption {
441            text_nodes.push(HostText {
442                kind: "caption",
443                text: caption.clone(),
444            });
445        }
446        let mut tsv = String::new();
447        for (i, col) in viewed.columns.iter().enumerate() {
448            if i > 0 {
449                tsv.push('\t');
450            }
451            tsv.push_str(&col.header);
452        }
453        tsv.push('\n');
454        let start = row_start as usize;
455        let end = (row_end as usize).min(viewed.rows.len());
456        for row in viewed.rows.get(start..end).unwrap_or(&[]) {
457            for (i, cell) in row.cells.iter().enumerate() {
458                if i > 0 {
459                    tsv.push('\t');
460                }
461                if let Some(s) = cell.copy_str() {
462                    tsv.push_str(&s);
463                }
464            }
465            tsv.push('\n');
466        }
467        HostProjection {
468            text_nodes,
469            clipboard: Some(ClipboardPayload::Tsv(tsv)),
470        }
471    }
472}
473
474fn clip_hline(content_x: u32, span: u32, origin: u32, pixmap_w: u32) -> Option<(u32, u32)> {
475    let x1 = content_x as i64 - origin as i64;
476    let x2 = x1 + span as i64;
477    let vis_x1 = x1.max(0);
478    let vis_x2 = x2.min(pixmap_w as i64);
479    if vis_x2 <= vis_x1 {
480        return None;
481    }
482    Some((vis_x1 as u32, (vis_x2 - vis_x1) as u32))
483}
484
485fn clip_vline(content_x: u32, origin: u32, pixmap_w: u32) -> Option<(u32, u32)> {
486    let x = content_x as i64 - origin as i64;
487    if x < 0 || x >= pixmap_w as i64 {
488        return None;
489    }
490    Some((x as u32, 1))
491}
492
493impl Default for Surface {
494    fn default() -> Self {
495        Self::new(
496            SurfaceMode::Sealed,
497            LicenseLens::from_tier(crate::AccessTier::Public),
498        )
499    }
500}