Skip to main content

cksk/
groups.rs

1//! Group boards: the service lists at room-readable type, laid out on the
2//! shared grid. One board shows a fixed set of groups; rows are big enough to
3//! read across a room, so a large estate spans several boards instead of one
4//! dense screen.
5
6use tiny_skia::Pixmap;
7
8use crate::chrome::{self, Fonts, Header, HEADER_H};
9use crate::layout::{self, BODY, MARGIN, SMALL, XS};
10use crate::model::Endpoint;
11
12/// Twelve rows fill a 1080p column: head 56 + 12*70 + pad 16 = 912 of 938.
13const ROW_H: f32 = 70.0;
14const GROUP_HEAD_H: f32 = 56.0;
15const CARD_PAD: f32 = 16.0;
16const GROUP_GAP: f32 = 20.0;
17pub const ROWS_PER_COLUMN: usize = 12;
18
19/// Where one chunk (a group, or one continuation chunk of a large group) lands.
20pub struct Placement {
21    /// Index into the chunk list that was packed.
22    pub chunk: usize,
23    pub col: usize,
24    pub y: f32,
25    pub h: f32,
26}
27
28/// Rows a column holds at this pixmap height. Twelve at 1080p; a shorter kiosk
29/// (or a preview at another size) gets fewer, so no page silently drops a card
30/// that cannot fit the band.
31pub fn rows_per_column(height: f32) -> usize {
32    let (top, bottom) = band(height);
33    let usable = bottom - top - GROUP_HEAD_H - CARD_PAD + GROUP_GAP;
34    ((usable / ROW_H).floor() as usize).clamp(1, ROWS_PER_COLUMN)
35}
36
37/// Split `idxs` of one group into column-sized chunks (the last one may be shorter).
38pub fn chunk_group(idxs: &[usize], rows: usize) -> Vec<Vec<usize>> {
39    idxs.chunks(rows.max(1)).map(|c| c.to_vec()).collect()
40}
41
42/// All chunks of `groups` with their titled continuations, biggest first (the order
43/// the packer consumes them in so a large group claims room instead of packing late).
44pub fn chunks_of(groups: &[(String, Vec<usize>)], rows: usize) -> Vec<(String, Vec<usize>)> {
45    let mut chunks: Vec<(String, Vec<usize>)> = Vec::new();
46    for (gname, idxs) in groups {
47        let parts = chunk_group(idxs, rows);
48        let n = parts.len().max(1);
49        for (k, part) in parts.into_iter().enumerate() {
50            let title = if n == 1 {
51                gname.to_uppercase()
52            } else {
53                format!("{} · {}/{}", gname.to_uppercase(), k + 1, n)
54            };
55            chunks.push((title, part));
56        }
57    }
58    chunks.sort_by_key(|(_, idxs)| std::cmp::Reverse(idxs.len()));
59    chunks
60}
61
62/// Greedy shortest-column packing of `chunks` between `top` and `bottom`.
63/// Returns the placements plus every chunk that fit no column (dropped, never clipped).
64pub fn pack(
65    chunks: &[(String, Vec<usize>)],
66    cols: usize,
67    top: f32,
68    bottom: f32,
69) -> (Vec<Placement>, Vec<usize>) {
70    let cols = cols.max(1);
71    let mut col_y = vec![top; cols];
72    let mut placements = Vec::new();
73    let mut dropped = Vec::new();
74    for (ci, (_, idxs)) in chunks.iter().enumerate() {
75        let h = card_height(idxs.len());
76        let mut best: Option<usize> = None;
77        for (c, y) in col_y.iter().enumerate() {
78            if y + h > bottom {
79                continue;
80            }
81            if best.is_none_or(|b| *y < col_y[b]) {
82                best = Some(c);
83            }
84        }
85        match best {
86            Some(c) => {
87                placements.push(Placement {
88                    chunk: ci,
89                    col: c,
90                    y: col_y[c],
91                    h,
92                });
93                col_y[c] += h + GROUP_GAP;
94            }
95            None => dropped.push(ci),
96        }
97    }
98    (placements, dropped)
99}
100
101fn card_height(rows: usize) -> f32 {
102    GROUP_HEAD_H + rows as f32 * ROW_H + CARD_PAD
103}
104
105/// The vertical band every group board draws into, for a given pixmap height.
106pub fn band(height: f32) -> (f32, f32) {
107    (HEADER_H + XS, height - MARGIN)
108}
109
110/// Filter `eps` down to the `want` groups, in `want` order. Missing or empty groups
111/// vanish silently, so a board never renders an empty card.
112pub fn select_groups(eps: &[Endpoint], want: &[&str]) -> Vec<(String, Vec<usize>)> {
113    let mut out = Vec::new();
114    for name in want {
115        let idxs: Vec<usize> = eps
116            .iter()
117            .enumerate()
118            .filter(|(_, e)| e.group == *name)
119            .map(|(i, _)| i)
120            .collect();
121        if !idxs.is_empty() {
122            out.push((name.to_string(), idxs));
123        }
124    }
125    out
126}
127
128/// Render pre-selected `groups` into `cols` columns, greediest-shortest-column first.
129/// A group larger than one column splits into titled continuation chunks; a chunk that
130/// fits no column is skipped gracefully -- a board shows what fits, never a clipped card.
131/// Returns the indices of every endpoint actually drawn, so callers can prove coverage.
132pub fn render_groups(
133    pm: &mut Pixmap,
134    eps: &[Endpoint],
135    fonts: &Fonts,
136    hdr: &Header,
137    groups: &[(String, Vec<usize>)],
138    cols: usize,
139) -> Vec<usize> {
140    let w = pm.width() as f32;
141    let h = pm.height() as f32;
142    if cols == 0 {
143        return Vec::new();
144    }
145
146    chrome::fill_rect(pm, 0.0, 0.0, w, h, chrome::BG);
147    chrome::render_header(pm, fonts, hdr);
148
149    let (top, bottom) = band(h);
150    let band_rect = layout::Rect {
151        x: MARGIN,
152        y: top,
153        w: w - 2.0 * MARGIN,
154        h: bottom - top,
155    };
156    let columns = band_rect.columns(cols);
157    let col_w = columns[0].w;
158
159    let chunks = chunks_of(groups, rows_per_column(h));
160    let (placements, dropped) = pack(&chunks, cols, top, bottom);
161    if !dropped.is_empty() {
162        eprintln!(
163            "cksk: {} chunk(s) do not fit this board at {w}x{h}; they are dropped. \
164             The page planner must leave more room.",
165            dropped.len()
166        );
167    }
168
169    let mut drawn = Vec::new();
170    for p in placements {
171        let (title, idxs) = &chunks[p.chunk];
172        let x = columns[p.col].x;
173        let y = p.y;
174        let card_h = p.h;
175
176        chrome::rounded_rect(pm, x, y, col_w, card_h, 16.0, chrome::CARD);
177
178        // Card header: title + count share one SMALL line top.
179        let head_top = y + 12.0;
180        layout::line(
181            pm,
182            &fonts.sans,
183            title,
184            layout::Rect {
185                x: x + CARD_PAD,
186                y,
187                w: col_w - 2.0 * CARD_PAD,
188                h: GROUP_HEAD_H,
189            },
190            head_top,
191            SMALL,
192            chrome::ACCENT,
193        );
194        layout::line_right(
195            pm,
196            &fonts.mono,
197            &idxs.len().to_string(),
198            layout::Rect {
199                x: x + CARD_PAD,
200                y,
201                w: col_w - 2.0 * CARD_PAD,
202                h: GROUP_HEAD_H,
203            },
204            head_top,
205            SMALL,
206            chrome::FAINT,
207        );
208        chrome::fill_rect(
209            pm,
210            x + CARD_PAD,
211            y + GROUP_HEAD_H,
212            col_w - 2.0 * CARD_PAD,
213            2.0,
214            chrome::CARD_LINE,
215        );
216
217        // Rows: name + latency share one line top; history strip below.
218        let inner = layout::Rect {
219            x: x + CARD_PAD,
220            y,
221            w: col_w - 2.0 * CARD_PAD,
222            h: card_h,
223        };
224        for (ri, &ei) in idxs.iter().enumerate() {
225            let e = &eps[ei];
226            let ry = y + GROUP_HEAD_H + ri as f32 * ROW_H;
227            let name_top = ry + 12.0;
228            let dot = match e.up() {
229                Some(true) => chrome::GREEN,
230                Some(false) => chrome::RED,
231                None => chrome::AMBER,
232            };
233            layout::dot(
234                pm,
235                inner.x + 10.0,
236                name_top,
237                layout::Face {
238                    font: &fonts.sans,
239                    size: BODY.size,
240                    sample: 'H',
241                },
242                8.0,
243                dot,
244            );
245
246            let lat = match e.latency_ms() {
247                Some(ms) if ms >= 1000.0 => format!("{:.2} s", ms / 1000.0),
248                Some(ms) => format!("{} ms", ms.round() as i64),
249                None => "—".to_string(),
250            };
251            layout::line_right(pm, &fonts.mono, &lat, inner, name_top, SMALL, chrome::MUTED);
252
253            let name_x = inner.x + 30.0;
254            let lat_w = chrome::text_width(&fonts.mono, &lat, SMALL.size);
255            let name_max = inner.w - 30.0 - lat_w - 12.0;
256            let name = chrome::truncate(&fonts.sans, &e.name, BODY.size, name_max);
257            chrome::text(
258                pm,
259                &fonts.sans,
260                &name,
261                name_x,
262                layout::baseline(&fonts.sans, name_top, BODY.size),
263                BODY.size,
264                chrome::TEXT,
265            );
266
267            let strip = layout::Rect {
268                x: name_x,
269                y: name_top + BODY.lh + XS,
270                w: inner.w - 30.0,
271                h: 8.0,
272            };
273            let hist = e.history(48);
274            if hist.is_empty() {
275                chrome::fill_rect(pm, strip.x, strip.y, strip.w, strip.h, chrome::HIST_NONE);
276            } else {
277                let n = hist.len() as f32;
278                let seg = (strip.w / n).max(2.0);
279                for (k, ok) in hist.iter().enumerate() {
280                    let sx = strip.x + k as f32 * seg;
281                    let c = if *ok {
282                        chrome::GREEN
283                    } else {
284                        chrome::HIST_DOWN
285                    };
286                    chrome::fill_rect(pm, sx, strip.y, (seg - 1.0).max(1.0), strip.h, c);
287                }
288            }
289            drawn.push(ei);
290        }
291    }
292    drawn
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    fn groups(n: &[usize]) -> Vec<(String, Vec<usize>)> {
300        n.iter()
301            .enumerate()
302            .map(|(g, &rows)| (format!("g{g}"), (0..rows).collect()))
303            .collect()
304    }
305
306    #[test]
307    fn pack_drops_nothing_when_the_page_was_planned_for_the_band() {
308        let (top, bottom) = band(1080.0);
309        // 30 + 24 + 25 rows: three pages worth of whole groups across three columns.
310        for page in [
311            groups(&[30]),
312            groups(&[9, 13, 1, 2]),
313            groups(&[3, 2, 2, 10, 7]),
314        ] {
315            let chunks = chunks_of(&page, rows_per_column(1080.0));
316            let (placements, dropped) = pack(&chunks, 3, top, bottom);
317            assert!(dropped.is_empty(), "dropped {dropped:?} for {page:?}");
318            assert_eq!(placements.len(), chunks.len());
319        }
320    }
321
322    #[test]
323    fn pack_reports_a_chunk_that_fits_no_column() {
324        let chunks = chunks_of(&groups(&[12, 12, 12, 12]), 12);
325        let (placements, dropped) = pack(&chunks, 3, 0.0, 1000.0);
326        assert_eq!(placements.len(), 3);
327        assert_eq!(dropped.len(), 1);
328    }
329}