Debian Codegraph @

src/canvas/components/time_series/vendored/canvas.rs

raw symbols SCIP
1 //! Vendored from <https://github.com/fdehau/tui-rs/blob/fafad6c96109610825aad89c4bba5253e01101ed/src/widgets/canvas/mod.rs>
2 //! and <https://github.com/ratatui/ratatui/blob/65c520245aa20e99e64d9ffcb2062a4502a699ea/ratatui-widgets/src/canvas.rs>.
3 //!
4 //! The main thing this is pulled in for is overriding how `BrailleGrid`'s draw
5 //! logic works, as changing it is needed in order to draw all datasets in only
6 //! one layer back in [`super::TimeChart::render`]. More specifically,
7 //! the current implementation in ratatui `|=`s all the cells together if they
8 //! overlap, but since we are smashing all the layers together which may have
9 //! different colours, we instead just _replace_ whatever was in that cell
10 //! with the newer colour + character.
11 //!
12 //! See <https://github.com/ClementTsang/bottom/pull/918> and <https://github.com/ClementTsang/bottom/pull/937> for the
13 //! original motivation.
14
15 use ratatui::{
16 buffer::Buffer,
17 layout::Rect,
18 prelude::BlockExt,
19 style::{Color, Style},
20 symbols::Marker,
21 text::Line,
22 widgets::{
23 Block, Widget,
24 canvas::{Line as CanvasLine, Points},
25 },
26 };
27 use ratatui_core::symbols::{
28 braille::BRAILLE,
29 pixel::{OCTANTS, QUADRANTS, SEXTANTS},
30 };
31
32 use super::grid::{CharGrid, Grid, HalfBlockGrid, PatternGrid};
33
34 /// Interface for all shapes that may be drawn on a Canvas widget.
35 pub trait Shape {
36 fn draw(&self, painter: &mut Painter<'_, '_>);
37 }
38
39 impl Shape for CanvasLine {
40 fn draw(&self, painter: &mut Painter<'_, '_>) {
41 let (x1, y1) = match painter.get_point(self.x1, self.y1) {
42 Some(c) => c,
43 None => return,
44 };
45 let (x2, y2) = match painter.get_point(self.x2, self.y2) {
46 Some(c) => c,
47 None => return,
48 };
49 let (dx, x_range) = if x2 >= x1 {
50 (x2 - x1, x1..=x2)
51 } else {
52 (x1 - x2, x2..=x1)
53 };
54 let (dy, y_range) = if y2 >= y1 {
55 (y2 - y1, y1..=y2)
56 } else {
57 (y1 - y2, y2..=y1)
58 };
59
60 if dx == 0 {
61 for y in y_range {
62 painter.paint(x1, y, self.color);
63 }
64 } else if dy == 0 {
65 for x in x_range {
66 painter.paint(x, y1, self.color);
67 }
68 } else if dy < dx {
69 if x1 > x2 {
70 draw_line_low(painter, x2, y2, x1, y1, self.color);
71 } else {
72 draw_line_low(painter, x1, y1, x2, y2, self.color);
73 }
74 } else if y1 > y2 {
75 draw_line_high(painter, x2, y2, x1, y1, self.color);
76 } else {
77 draw_line_high(painter, x1, y1, x2, y2, self.color);
78 }
79 }
80 }
81
82 fn draw_line_low(
83 painter: &mut Painter<'_, '_>, x1: usize, y1: usize, x2: usize, y2: usize, color: Color,
84 ) {
85 let dx = (x2 - x1) as isize;
86 let dy = (y2 as isize - y1 as isize).abs();
87 let mut d = 2 * dy - dx;
88 let mut y = y1;
89 for x in x1..=x2 {
90 painter.paint(x, y, color);
91 if d > 0 {
92 y = if y1 > y2 {
93 y.saturating_sub(1)
94 } else {
95 y.saturating_add(1)
96 };
97 d -= 2 * dx;
98 }
99 d += 2 * dy;
100 }
101 }
102
103 fn draw_line_high(
104 painter: &mut Painter<'_, '_>, x1: usize, y1: usize, x2: usize, y2: usize, color: Color,
105 ) {
106 let dx = (x2 as isize - x1 as isize).abs();
107 let dy = (y2 - y1) as isize;
108 let mut d = 2 * dx - dy;
109 let mut x = x1;
110 for y in y1..=y2 {
111 painter.paint(x, y, color);
112 if d > 0 {
113 x = if x1 > x2 {
114 x.saturating_sub(1)
115 } else {
116 x.saturating_add(1)
117 };
118 d -= 2 * dy;
119 }
120 d += 2 * dx;
121 }
122 }
123
124 impl Shape for Points<'_> {
125 fn draw(&self, painter: &mut Painter<'_, '_>) {
126 for (x, y) in self.coords {
127 if let Some((x, y)) = painter.get_point(*x, *y) {
128 painter.paint(x, y, self.color);
129 }
130 }
131 }
132 }
133
134 /// Label to draw some text on the canvas
135 #[derive(Debug, Clone)]
136 pub struct Label<'a> {
137 x: f64,
138 y: f64,
139 spans: Line<'a>,
140 }
141
142 #[derive(Debug)]
143 pub struct Painter<'a, 'b> {
144 context: &'a mut Context<'b>,
145 resolution: (f64, f64),
146 }
147
148 impl Painter<'_, '_> {
149 /// Convert the (x, y) coordinates to location of a point on the grid.
150 pub fn get_point(&self, x: f64, y: f64) -> Option<(usize, usize)> {
151 let [left, right] = self.context.x_bounds;
152 let [bottom, top] = self.context.y_bounds;
153 if x < left || x > right || y < bottom || y > top {
154 return None;
155 }
156 let width = right - left;
157 let height = top - bottom;
158 if width <= 0.0 || height <= 0.0 {
159 return None;
160 }
161 let x = ((x - left) * (self.resolution.0 - 1.0) / width).round() as usize;
162 let y = ((top - y) * (self.resolution.1 - 1.0) / height).round() as usize;
163 Some((x, y))
164 }
165
166 /// Paint a point of the grid.
167 pub fn paint(&mut self, x: usize, y: usize, color: Color) {
168 self.context.grid.paint(x, y, color);
169 }
170 }
171
172 impl<'a, 'b> From<&'a mut Context<'b>> for Painter<'a, 'b> {
173 fn from(context: &'a mut Context<'b>) -> Painter<'a, 'b> {
174 let resolution = context.grid.resolution();
175 Painter {
176 context,
177 resolution,
178 }
179 }
180 }
181
182 /// Holds the state of the Canvas when painting to it.
183 #[derive(Debug)]
184 pub struct Context<'a> {
185 x_bounds: [f64; 2],
186 y_bounds: [f64; 2],
187 grid: Box<dyn Grid>,
188 dirty: bool,
189 labels: Vec<Label<'a>>,
190 }
191
192 impl<'a> Context<'a> {
193 pub fn new(
194 width: u16, height: u16, x_bounds: [f64; 2], y_bounds: [f64; 2], marker: Marker,
195 ) -> Context<'a> {
196 let grid = Self::marker_to_grid(width, height, marker);
197
198 Context {
199 x_bounds,
200 y_bounds,
201 grid,
202 dirty: false,
203 labels: Vec::new(),
204 }
205 }
206
207 fn marker_to_grid(width: u16, height: u16, marker: Marker) -> Box<dyn Grid> {
208 match marker {
209 Marker::Dot => Box::new(CharGrid::new(width, height, '•')),
210 Marker::Block => Box::new(CharGrid::new(width, height, '█').apply_color_to_bg()),
211 Marker::Bar => Box::new(CharGrid::new(width, height, '▄')),
212 Marker::Braille => Box::new(PatternGrid::<2, 4>::new(width, height, &BRAILLE)),
213 Marker::HalfBlock => Box::new(HalfBlockGrid::new(width, height)),
214 Marker::Quadrant => Box::new(PatternGrid::<2, 2>::new(width, height, &QUADRANTS)),
215 Marker::Sextant => Box::new(PatternGrid::<2, 3>::new(width, height, &SEXTANTS)),
216 Marker::Octant => Box::new(PatternGrid::<2, 4>::new(width, height, &OCTANTS)),
217 // Fall back to braille if not supported.
218 _ => Box::new(PatternGrid::<2, 4>::new(width, height, &BRAILLE)),
219 }
220 }
221
222 /// Draw any object that may implement the Shape trait
223 pub fn draw<S>(&mut self, shape: &S)
224 where
225 S: Shape,
226 {
227 self.dirty = true;
228 let mut painter = Painter::from(self);
229 shape.draw(&mut painter);
230 }
231 }
232
233 /// The Canvas widget may be used to draw more detailed figures using braille
234 /// patterns (each cell can have a braille character in 8 different positions).
235 pub struct Canvas<'a, F>
236 where
237 F: Fn(&mut Context<'_>),
238 {
239 block: Option<Block<'a>>,
240 x_bounds: [f64; 2],
241 y_bounds: [f64; 2],
242 paint_func: Option<F>,
243 background_color: Color,
244 marker: Marker,
245 }
246
247 impl<'a, F> Default for Canvas<'a, F>
248 where
249 F: Fn(&mut Context<'_>),
250 {
251 fn default() -> Canvas<'a, F> {
252 Canvas {
253 block: None,
254 x_bounds: [0.0, 0.0],
255 y_bounds: [0.0, 0.0],
256 paint_func: None,
257 background_color: Color::Reset,
258 marker: Marker::Braille,
259 }
260 }
261 }
262
263 impl<'a, F> Canvas<'a, F>
264 where
265 F: Fn(&mut Context<'_>),
266 {
267 pub fn x_bounds(mut self, bounds: [f64; 2]) -> Canvas<'a, F> {
268 self.x_bounds = bounds;
269 self
270 }
271
272 pub fn y_bounds(mut self, bounds: [f64; 2]) -> Canvas<'a, F> {
273 self.y_bounds = bounds;
274 self
275 }
276
277 /// Store the closure that will be used to draw to the Canvas
278 pub fn paint(mut self, f: F) -> Canvas<'a, F> {
279 self.paint_func = Some(f);
280 self
281 }
282
283 pub fn background_color(mut self, color: Color) -> Canvas<'a, F> {
284 self.background_color = color;
285 self
286 }
287
288 /// Change the type of points used to draw the shapes. By default, the
289 /// braille patterns are used as they provide a more fine-grained result,
290 /// but you might want to use the simple dot or block instead if the
291 /// targeted terminal does not support those symbols.
292 pub fn marker(mut self, marker: Marker) -> Canvas<'a, F> {
293 self.marker = marker;
294 self
295 }
296 }
297
298 impl<F> Widget for Canvas<'_, F>
299 where
300 F: Fn(&mut Context<'_>),
301 {
302 fn render(self, area: Rect, buf: &mut Buffer) {
303 Widget::render(&self, area, buf);
304 }
305 }
306
307 impl<F> Widget for &Canvas<'_, F>
308 where
309 F: Fn(&mut Context<'_>),
310 {
311 fn render(self, area: Rect, buf: &mut Buffer) {
312 self.block.as_ref().render(area, buf);
313 let canvas_area = self.block.inner_if_some(area);
314 if canvas_area.is_empty() {
315 return;
316 }
317
318 buf.set_style(canvas_area, Style::default().bg(self.background_color));
319
320 let width = canvas_area.width as usize;
321
322 let Some(ref painter) = self.paint_func else {
323 return;
324 };
325
326 // Create a blank context that match the size of the canvas
327 let mut ctx = Context::new(
328 canvas_area.width,
329 canvas_area.height,
330 self.x_bounds,
331 self.y_bounds,
332 self.marker,
333 );
334 // Paint to this context
335 painter(&mut ctx);
336 // ctx.finish(); // Not needed, we have no layers.
337
338 // Instead, paint whatever is in the ctx.
339 let layer = ctx.grid.save();
340
341 for (index, layer_cell) in layer.contents.iter().enumerate() {
342 let (x, y) = (
343 (index % width) as u16 + canvas_area.left(),
344 (index / width) as u16 + canvas_area.top(),
345 );
346
347 if let Some(cell) = buf.cell_mut((x, y)) {
348 if let Some(symbol) = layer_cell.symbol {
349 cell.set_char(symbol);
350 }
351 if let Some(fg) = layer_cell.fg {
352 cell.set_fg(fg);
353 }
354 if let Some(bg) = layer_cell.bg {
355 cell.set_bg(bg);
356 }
357 }
358 }
359
360 // Reset the grid and mark as non-dirty.
361 ctx.grid.reset();
362 ctx.dirty = false;
363
364 // Finally draw the labels
365 let left = self.x_bounds[0];
366 let right = self.x_bounds[1];
367 let top = self.y_bounds[1];
368 let bottom = self.y_bounds[0];
369 let width = (self.x_bounds[1] - self.x_bounds[0]).abs();
370 let height = (self.y_bounds[1] - self.y_bounds[0]).abs();
371 let resolution = {
372 let width = f64::from(canvas_area.width - 1);
373 let height = f64::from(canvas_area.height - 1);
374 (width, height)
375 };
376 for label in ctx
377 .labels
378 .iter()
379 .filter(|l| l.x >= left && l.x <= right && l.y <= top && l.y >= bottom)
380 {
381 let x = ((label.x - left) * resolution.0 / width) as u16 + canvas_area.left();
382 let y = ((top - label.y) * resolution.1 / height) as u16 + canvas_area.top();
383 buf.set_line(x, y, &label.spans, canvas_area.right() - x);
384 }
385 }
386 }