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
444
445
446
//! Table geometry and hit testing.
//!
//! Layout is **viewport-clipped**. Column widths are a separate measure pass so
//! scrolling does not reflow. Hit boxes exist only for on-screen cells.

use crate::model::{ColumnId, Grid, RowId};

/// Hard cap on one pixmap axis. Hosts that need more should tile.
pub const MAX_PIXMAP_AXIS: u32 = 8192;

/// Pixel viewport. `origin_*` is the scroll; `width`/`height` is the window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Viewport {
    /// Horizontal scroll in content pixels (header + body).
    pub origin_x: u32,
    /// Vertical scroll in **body** pixels (header is sticky).
    pub origin_y: u32,
    /// Window width in pixels.
    pub width: u32,
    /// Window height in pixels.
    pub height: u32,
}

impl Default for Viewport {
    fn default() -> Self {
        Self::window(960, 360)
    }
}

impl Viewport {
    /// Window at origin `(0, 0)`.
    #[must_use]
    pub const fn window(width: u32, height: u32) -> Self {
        Self {
            origin_x: 0,
            origin_y: 0,
            width,
            height,
        }
    }

    /// Set scroll origins (body `origin_y`, table `origin_x`).
    #[must_use]
    pub const fn scrolled(mut self, origin_x: u32, origin_y: u32) -> Self {
        self.origin_x = origin_x;
        self.origin_y = origin_y;
        self
    }

    /// Clamp origins so they do not run past [`TableMetrics`] content.
    #[must_use]
    pub fn clamp_to(mut self, metrics: &TableMetrics) -> Self {
        let max_x = metrics.content_width.saturating_sub(1);
        let body = metrics.row_count.saturating_mul(metrics.row_height);
        self.origin_x = self.origin_x.min(max_x);
        self.origin_y = self.origin_y.min(body);
        self
    }

    /// Pan by signed pixels, then [`Self::clamp_to`].
    #[must_use]
    pub fn scroll_by(self, dx: i32, dy: i32, metrics: &TableMetrics) -> Self {
        let nx = (i64::from(self.origin_x) + i64::from(dx)).max(0) as u32;
        let ny = (i64::from(self.origin_y) + i64::from(dy)).max(0) as u32;
        self.scrolled(nx, ny).clamp_to(metrics)
    }
}

/// Pointer in **pixmap** (window) pixel space.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pointer {
    /// X.
    pub x: u32,
    /// Y.
    pub y: u32,
}

impl Pointer {
    /// Construct.
    #[must_use]
    pub const fn new(x: u32, y: u32) -> Self {
        Self { x, y }
    }
}

/// What a pixel hit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HitKind {
    /// Column header.
    Header,
    /// Data cell.
    Cell,
    /// Timeseries sample. `Hit.col_index` is series index; `row_index` is point index.
    Sample,
    /// X-axis tick (index in `col_index`).
    TickX,
    /// Y-axis tick (index in `col_index`).
    TickY,
}

/// Opaque hit. **No values.**
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Hit {
    /// Row id (0 for header hits).
    pub row: RowId,
    /// Column id.
    pub col: ColumnId,
    /// Row index in the view grid (`None` on header).
    pub row_index: Option<u32>,
    /// Column index.
    pub col_index: u32,
    /// Kind.
    pub kind: HitKind,
}

/// Axis-aligned box used for paint and hit tests (pixmap space).
#[derive(Debug, Clone, Copy)]
pub(crate) struct CellBox {
    pub row_index: Option<u32>,
    pub col_index: u32,
    pub row: RowId,
    pub col: ColumnId,
    pub x: u32,
    pub y: u32,
    pub w: u32,
    pub h: u32,
    pub header: bool,
    pub kind: HitKind,
}

impl CellBox {
    pub(crate) fn contains(self, x: u32, y: u32) -> bool {
        x >= self.x
            && y >= self.y
            && x < self.x.saturating_add(self.w)
            && y < self.y.saturating_add(self.h)
    }

    pub(crate) fn hit(self) -> Hit {
        Hit {
            row: self.row,
            col: self.col,
            row_index: self.row_index,
            col_index: self.col_index,
            kind: self.kind,
        }
    }
}

/// Spatial index of the **visible** window only.
#[derive(Debug, Clone, Default)]
pub struct HitMap {
    pub(crate) boxes: Vec<CellBox>,
}

impl HitMap {
    /// Hit at pixmap pixel, last-drawn wins (cells over empty chrome).
    #[must_use]
    pub fn at(&self, x: u32, y: u32) -> Option<Hit> {
        self.boxes
            .iter()
            .rev()
            .find(|b| b.contains(x, y))
            .map(|b| b.hit())
    }

    /// Number of recorded boxes (visible cells + headers). Tests / diagnostics.
    #[must_use]
    pub fn len(&self) -> usize {
        self.boxes.len()
    }

    /// True when no boxes were recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.boxes.is_empty()
    }
}

pub(crate) const PAD: u32 = 8;
pub(crate) const ROW_H: u32 = 18;
pub(crate) const HEADER_H: u32 = 20;
pub(crate) const CHAR_W: u32 = 6;
pub(crate) const CELL_PAD_X: u32 = 8;
pub(crate) const MIN_COL: u32 = 56;
pub(crate) const MAX_COL: u32 = 240;

/// Content size and column widths. Does not depend on the viewport.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TableMetrics {
    /// Full table width including padding.
    pub content_width: u32,
    /// Full table height including padding and header.
    pub content_height: u32,
    /// Per-column pixel widths (content, no pad).
    pub col_widths: Vec<u32>,
    /// Body row height.
    pub row_height: u32,
    /// Sticky header height.
    pub header_height: u32,
    /// Outer padding.
    pub pad: u32,
    /// Data row count.
    pub row_count: u32,
    /// Column count.
    pub col_count: u32,
}

impl TableMetrics {
    /// Y of the first body pixel in content space (header bottom).
    #[must_use]
    pub fn body_top(&self) -> u32 {
        self.pad.saturating_add(self.header_height)
    }

    /// Maximum `origin_x` a host should send (inclusive).
    #[must_use]
    pub fn max_origin_x(&self) -> u32 {
        self.content_width.saturating_sub(1)
    }

    /// Maximum `origin_y` (body pixels) a host should send.
    #[must_use]
    pub fn max_origin_y(&self) -> u32 {
        self.row_count.saturating_mul(self.row_height)
    }

    /// Column widths with `index` set to `width` (clamped to ≥ 8px).
    #[must_use]
    pub fn resize_column(&self, index: usize, width: u32) -> Vec<u32> {
        let mut widths = self.col_widths.clone();
        if let Some(slot) = widths.get_mut(index) {
            *slot = width.max(8);
        }
        widths
    }

    /// Metrics after a column resize (content width recomputed).
    #[must_use]
    pub fn with_resized_column(&self, index: usize, width: u32) -> Self {
        let col_widths = self.resize_column(index, width);
        let content_width = col_widths
            .iter()
            .copied()
            .fold(0u32, u32::saturating_add)
            .saturating_add(self.pad.saturating_mul(2))
            .max(1);
        Self {
            content_width,
            col_widths,
            ..self.clone()
        }
    }
}

pub(crate) struct TableGeom {
    pub pixmap_w: u32,
    pub pixmap_h: u32,
    pub content_width: u32,
    pub content_height: u32,
    pub col_widths: Vec<u32>,
    pub boxes: Vec<CellBox>,
    pub first_row: u32,
    pub row_end: u32,
    pub origin_x: u32,
    pub origin_y: u32,
}

pub(crate) fn measure_col_widths(
    grid: &Grid,
    placeholder: &str,
    override_w: Option<&[u32]>,
) -> Vec<u32> {
    let n = grid.columns.len();
    let mut col_widths = Vec::with_capacity(n);
    let mut buf = String::with_capacity(32);
    for (ci, col) in grid.columns.iter().enumerate() {
        if let Some(w) = override_w.and_then(|ws| ws.get(ci)).copied() {
            col_widths.push(w.max(8));
            continue;
        }
        let mut max_chars = col.header.chars().count();
        for row in &grid.rows {
            if let Some(cell) = row.cells.get(ci) {
                buf.clear();
                cell.write_paint(&mut buf, placeholder);
                max_chars = max_chars.max(buf.chars().count());
            }
        }
        let w =
            ((max_chars as u32).saturating_mul(CHAR_W) + CELL_PAD_X * 2).clamp(MIN_COL, MAX_COL);
        col_widths.push(w);
    }
    col_widths
}

pub(crate) fn content_size(n_rows: u32, col_widths: &[u32]) -> (u32, u32) {
    let content_w = col_widths
        .iter()
        .copied()
        .fold(0u32, u32::saturating_add)
        .saturating_add(PAD.saturating_mul(2))
        .max(1);
    let content_h = PAD
        .saturating_add(HEADER_H)
        .saturating_add(n_rows.saturating_mul(ROW_H))
        .saturating_add(PAD)
        .max(1);
    (content_w, content_h)
}

pub(crate) fn metrics(grid: &Grid, placeholder: &str, override_w: Option<&[u32]>) -> TableMetrics {
    let col_widths = measure_col_widths(grid, placeholder, override_w);
    let n_rows = grid.rows.len() as u32;
    let (content_width, content_height) = content_size(n_rows, &col_widths);
    TableMetrics {
        content_width,
        content_height,
        col_count: col_widths.len() as u32,
        col_widths,
        row_height: ROW_H,
        header_height: HEADER_H,
        pad: PAD,
        row_count: n_rows,
    }
}

pub(crate) fn layout_visible(
    grid: &Grid,
    placeholder: &str,
    viewport: Viewport,
    override_w: Option<&[u32]>,
) -> TableGeom {
    let col_widths = measure_col_widths(grid, placeholder, override_w);
    let n_rows = grid.rows.len() as u32;
    let (content_width, content_height) = content_size(n_rows, &col_widths);

    let origin_x = viewport.origin_x.min(content_width.saturating_sub(1));
    let body_h = n_rows.saturating_mul(ROW_H);
    let origin_y = viewport.origin_y.min(body_h);

    let remain_w = content_width.saturating_sub(origin_x).max(1);
    let remain_h = PAD
        .saturating_add(HEADER_H)
        .saturating_add(body_h.saturating_sub(origin_y))
        .saturating_add(PAD)
        .max(1);
    let pixmap_w = viewport.width.clamp(1, MAX_PIXMAP_AXIS).min(remain_w);
    let pixmap_h = viewport.height.clamp(1, MAX_PIXMAP_AXIS).min(remain_h);

    let body_top = PAD + HEADER_H;
    let first_row = origin_y / ROW_H;
    let mut row_end = first_row;
    if n_rows > 0 && pixmap_h > body_top {
        let visible_body = pixmap_h.saturating_sub(body_top);
        let skip_px = origin_y % ROW_H;
        let rows_fit = visible_body
            .saturating_add(skip_px)
            .saturating_add(ROW_H.saturating_sub(1))
            / ROW_H;
        row_end = first_row.saturating_add(rows_fit).min(n_rows);
    } else if n_rows > 0 && pixmap_h > PAD {
        row_end = first_row.saturating_add(1).min(n_rows);
    }

    let mut boxes = Vec::new();
    let mut x_content = PAD;
    for (ci, col) in grid.columns.iter().enumerate() {
        let w = col_widths[ci];
        if let Some((x, vis_w)) = clip_axis(x_content, w, origin_x, pixmap_w) {
            boxes.push(CellBox {
                row_index: None,
                col_index: ci as u32,
                row: RowId(0),
                col: col.id,
                x,
                y: PAD,
                w: vis_w,
                h: HEADER_H,
                header: true,
                kind: HitKind::Header,
            });
        }
        x_content = x_content.saturating_add(w);
    }

    for ri in first_row..row_end {
        let Some(row) = grid.rows.get(ri as usize) else {
            break;
        };
        let y_pm = body_top as i64 + i64::from(ri) * i64::from(ROW_H) - i64::from(origin_y);
        let y_bottom = y_pm + i64::from(ROW_H);
        let vis_y1 = y_pm.max(i64::from(body_top)).max(0);
        let vis_y2 = y_bottom.min(i64::from(pixmap_h));
        if vis_y2 <= vis_y1 {
            continue;
        }
        let mut x_content = PAD;
        for (ci, col) in grid.columns.iter().enumerate() {
            let w = col_widths[ci];
            if let Some((x, vis_w)) = clip_axis(x_content, w, origin_x, pixmap_w) {
                boxes.push(CellBox {
                    row_index: Some(ri),
                    col_index: ci as u32,
                    row: row.id,
                    col: col.id,
                    x,
                    y: vis_y1 as u32,
                    w: vis_w,
                    h: (vis_y2 - vis_y1) as u32,
                    header: false,
                    kind: HitKind::Cell,
                });
            }
            x_content = x_content.saturating_add(w);
        }
    }

    TableGeom {
        pixmap_w,
        pixmap_h,
        content_width,
        content_height,
        col_widths,
        boxes,
        first_row,
        row_end,
        origin_x,
        origin_y,
    }
}

/// Map a content-space span onto the pixmap. `None` if fully off-screen.
fn clip_axis(content_x: u32, span: u32, origin: u32, pixmap: 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 as i64);
    if vis_x2 <= vis_x1 {
        return None;
    }
    Some((vis_x1 as u32, (vis_x2 - vis_x1) as u32))
}