Skip to main content

graphics_chart/
graphics_chart.rs

1//! A pane of real text with charts between its rows, the charts as a
2//! progressive enhancement: every viewer gets a working cells rendering, and
3//! a viewer with real graphics draws a line and area chart over the same
4//! cells. The viewer scrolls both with its own motion, so the plugin keeps
5//! no scroll offset and paints once for both kinds of viewer.
6//!
7//! Manifest (`bundle/standard-plugin.json`):
8//!
9//! ```json
10//! {
11//!   "apiVersion": 2, "kind": "ui", "id": "graphics-chart", "version": "0.1.0",
12//!   "module": "graphics_chart.wasm",
13//!   "surfaces": [{ "id": "usage", "anchor": "pane", "title": "Usage", "model": "cells" }],
14//!   "commands": [{ "id": "open", "title": "Open usage", "opens": "usage" }],
15//!   "grants": {}
16//! }
17//! ```
18#![no_std]
19
20use standard_plugin::prelude::*;
21use standard_plugin::{Rect, Rgba, Shapes, view};
22
23/// The row fixed at the top: a title.
24const TITLE_ROWS: u32 = 1;
25/// The rows a chart covers.
26const CHART_ROWS: u32 = 6;
27/// A service's rows: its name, its chart, and a blank row after them.
28const SERVICE_ROWS: u32 = 1 + CHART_ROWS + 1;
29const SERVICES: u32 = 30;
30/// The samples each chart shows.
31const SAMPLES: u32 = 48;
32
33#[standard_plugin::ui]
34struct Usage {
35    pane: Surface<Cells>,
36}
37
38/// Service `service`'s sample `index`, from 0 to 1: sample data for this
39/// example.
40fn sample(service: u32, index: u32) -> f32 {
41    let phase = (service * 7 + index * 3) % 32;
42    let wave = if phase < 16 { phase } else { 32 - phase };
43    wave as f32 / 16.0
44}
45
46/// A chart in cells: one column of blocks per column, which every viewer
47/// can show.
48fn paint_cells(pane: &mut Surface<Cells>, service: u32, place: Rect) {
49    const BLOCKS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
50    let style = Style::fg(Colour::ACCENT);
51    for col in 0..place.w {
52        let index = col * SAMPLES / place.w.max(1);
53        let eighths = (sample(service, index) * (place.h * 8) as f32) as u32;
54        for row in 0..place.h {
55            let from_bottom = place.h - 1 - row;
56            let here = eighths.saturating_sub(from_bottom * 8).min(8);
57            if here > 0 {
58                let block = BLOCKS[here as usize - 1];
59                pane.put(place.x + col, place.y + row, block, style);
60            }
61        }
62    }
63}
64
65/// The same chart in pixels: an area under a line, in the viewer's accent
66/// colour and transparent everywhere else.
67fn paint_pixels(canvas: &mut Surface<Pixels>, service: u32, accent: u32) {
68    let (width, height) = canvas.size();
69    let (r, g, b) = ((accent >> 16) as u8, (accent >> 8) as u8, accent as u8);
70    let (line, area) = (Rgba::rgb(r, g, b), Rgba::new(r, g, b, 64));
71    let point = |index: u32| {
72        let x = (index * (width - 1) / (SAMPLES - 1)) as i32;
73        let y = ((1.0 - sample(service, index)) * (height - 1) as f32) as i32;
74        (x, y)
75    };
76    for x in 0..width {
77        let index = (x * (SAMPLES - 1) / width.max(1)).min(SAMPLES - 2);
78        let (from, to) = (point(index), point(index + 1));
79        let run = (to.0 - from.0).max(1);
80        let y = from.1 + (to.1 - from.1) * (x as i32 - from.0) / run;
81        canvas.fill_rect(Area::new(x as i32, y, 1, height - y as u32), area);
82    }
83    for index in 0..SAMPLES - 1 {
84        canvas.line(point(index), point(index + 1), line);
85    }
86}
87
88impl Usage {
89    /// Paints the whole surface: the cells every viewer shows, then the
90    /// charts over them where this viewer has graphics. The data changed or
91    /// the buffer is new, so this runs on an event, and never per frame.
92    fn paint(&mut self) {
93        let (cols, rows) = self.pane.size();
94        if rows == 0 {
95            // No geometry yet: a resize will follow.
96            return;
97        }
98        let accent = view::theme().accent;
99        self.pane.clear();
100        self.pane.text(1, 0, "Usage", Style::fg(Colour::FG).bold());
101        for service in 0..SERVICES {
102            let top = TITLE_ROWS + service * SERVICE_ROWS;
103            let name = format!("Service {}", service + 1);
104            self.pane.text(1, top, &name, Style::fg(Colour::FG));
105            let place = Rect::new(1, top + 1, cols.saturating_sub(2), CHART_ROWS);
106            paint_cells(&mut self.pane, service, place);
107            // Runs only where the viewer shows real graphics. Elsewhere the
108            // cells just painted are the chart, and nothing else is needed.
109            let _ = self.pane.draw_graphic(service, place, |canvas| {
110                paint_pixels(canvas, service, accent);
111            });
112        }
113        let _ = self.pane.commit();
114    }
115}
116
117impl UiPlugin for Usage {
118    fn activate(_cx: &mut Context) -> Self {
119        let pane = Surface::new("usage");
120        let _ = pane.set_scroll(Some(
121            Scroll::rows(TITLE_ROWS + SERVICES * SERVICE_ROWS).fixed(TITLE_ROWS, 0),
122        ));
123        let mut usage = Self { pane };
124        usage.paint();
125        usage
126    }
127
128    /// Nothing moves on its own, so nothing happens per frame.
129    fn frame(&mut self, _frame: &Frame) {}
130
131    fn event(&mut self, event: Event, cx: &mut Context) {
132        match event {
133            // A new, empty buffer, and perhaps a new cell pixel size. The
134            // theme's accent colours the image, so a new theme repaints too,
135            // and a viewer that gains or loses graphics gets the other paint.
136            Event::Resize { .. } | Event::ThemeChanged | Event::CapabilitiesChanged => {
137                self.paint();
138                cx.request_frame();
139            }
140            _ => {}
141        }
142    }
143}