sealed-surface 0.2.0

Non-extractable data surface: tables and timeseries as glyphs, never DOM text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Public render entry.

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;

/// Inputs for one frame.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FrameRequest {
    /// Window. `origin_*` scrolls; pixmap is the visible remainder, capped.
    pub viewport: Viewport,
    /// Optional pointer for hover fill + tooltip PNG (pixmap space).
    pub pointer: Option<Pointer>,
    /// Optional caption. Painted as glyphs. Included in host text **only** when copyable.
    pub caption: Option<String>,
    /// Host column widths in pixels. `None` measures from the viewed grid.
    /// Extra entries are ignored; missing columns are measured.
    pub column_widths: Option<Vec<u32>>,
}

impl FrameRequest {
    /// Full default origin, no pointer, measured columns.
    #[must_use]
    pub fn full(viewport: Viewport) -> Self {
        Self {
            viewport,
            pointer: None,
            caption: None,
            column_widths: None,
        }
    }

    /// Pointer in pixmap space (hover + tooltip).
    #[must_use]
    pub fn pointer(mut self, pointer: Pointer) -> Self {
        self.pointer = Some(pointer);
        self
    }

    /// Caption painted as glyphs (host text only when copyable).
    #[must_use]
    pub fn caption(mut self, caption: impl Into<String>) -> Self {
        self.caption = Some(caption.into());
        self
    }

    /// Host-provided column widths (pixels). Missing columns are measured.
    #[must_use]
    pub fn column_widths(mut self, widths: Vec<u32>) -> Self {
        self.column_widths = Some(widths);
        self
    }
}

/// One painted frame plus the host leak surface.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Frame {
    /// PNG bytes (`image/png`).
    pub png: Vec<u8>,
    /// Hit index in the same pixel space as `png` (visible cells only).
    pub hits: HitMap,
    /// Strings the host may emit. Empty of cell values when sealed.
    pub host: HostProjection,
    /// Tooltip PNG when `pointer` hit a data cell. Never a JSON value.
    pub tooltip_png: Option<Vec<u8>>,
    /// Grid after the lens (redacted cells have no original scalars).
    pub viewed: Grid,
    /// Full table width (scrollbars). Independent of the viewport.
    pub content_width: u32,
    /// Full table height (scrollbars). Independent of the viewport.
    pub content_height: u32,
    /// First visible data-row index (viewed grid).
    pub visible_row_start: u32,
    /// Exclusive end of visible data-row indices.
    pub visible_row_end: u32,
}

/// Stateful renderer.
#[derive(Debug, Clone)]
pub struct Surface {
    mode: SurfaceMode,
    lens: LicenseLens,
    theme: Theme,
}

impl Surface {
    /// Construct.
    #[must_use]
    pub fn new(mode: SurfaceMode, lens: LicenseLens) -> Self {
        Self {
            mode,
            lens,
            theme: Theme::default(),
        }
    }

    /// Replace mode (same painter).
    pub fn set_mode(&mut self, mode: SurfaceMode) {
        self.mode = mode;
    }

    /// Current mode.
    #[must_use]
    pub const fn mode(&self) -> SurfaceMode {
        self.mode
    }

    /// Replace lens.
    pub fn set_lens(&mut self, lens: LicenseLens) {
        self.lens = lens;
    }

    /// Current lens.
    #[must_use]
    pub fn lens(&self) -> &LicenseLens {
        &self.lens
    }

    /// Override theme.
    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
    }

    /// Current theme.
    #[must_use]
    pub const fn theme(&self) -> Theme {
        self.theme
    }

    /// Paint a timeseries ([`crate::SeriesLayout`]) with the same seal contract.
    ///
    /// # Errors
    ///
    /// Empty layout or raster failure.
    pub fn render_series(
        &self,
        layout: &crate::SeriesLayout,
        request: &FrameRequest,
    ) -> Result<Frame, Error> {
        crate::chart::render_timeseries(self, layout, request)
    }

    /// Content size and column widths after the lens, without painting.
    #[must_use]
    pub fn metrics(&self, grid: &Grid) -> TableMetrics {
        let viewed = self.lens.apply(grid);
        layout::metrics(&viewed, self.lens.style.glyph_str(), None)
    }

    /// Apply lens, paint the **visible window**, encode PNG, build host projection.
    ///
    /// # Errors
    ///
    /// Invalid grid (via lens output), raster failure, or PNG encode failure.
    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),
        )
    }
}