| 1 | //! Vendored [starting from here](https://github.com/ratatui/ratatui/blob/65c520245aa20e99e64d9ffcb2062a4502a699ea/ratatui-widgets/src/canvas.rs#L322). |
| 2 | |
| 3 | use std::{fmt::Debug, iter::zip}; |
| 4 | |
| 5 | use itertools::Itertools; |
| 6 | use ratatui::{style::Color, symbols}; |
| 7 | |
| 8 | /// A single layer of the canvas. |
| 9 | /// |
| 10 | /// This allows the canvas to be drawn in multiple layers. This is useful if you |
| 11 | /// want to draw multiple shapes on the canvas in specific order. |
| 12 | /// |
| 13 | /// **NOTE**: In the vendored version, we don't ever actually want to do this. |
| 14 | #[derive(Debug)] |
| 15 | pub(super) struct Layer { |
| 16 | pub(super) contents: Vec<LayerCell>, |
| 17 | } |
| 18 | |
| 19 | /// A cell within a layer. |
| 20 | /// |
| 21 | /// If a [`Context`] contains multiple layers, then the symbol, foreground, and |
| 22 | /// background colors for a character will be determined by the top-most layer |
| 23 | /// that provides a value for that character. For example, a chart drawn with |
| 24 | /// [`Marker::Block`] may provide the background color, and a later chart drawn |
| 25 | /// with [`Marker::Braille`] may provide the symbol and foreground color. |
| 26 | #[derive(Debug)] |
| 27 | pub(super) struct LayerCell { |
| 28 | pub(super) symbol: Option<char>, |
| 29 | pub(super) fg: Option<Color>, |
| 30 | pub(super) bg: Option<Color>, |
| 31 | } |
| 32 | |
| 33 | /// A grid of cells that can be painted on. |
| 34 | /// |
| 35 | /// The grid represents a particular screen region measured in rows and columns. |
| 36 | /// The underlying resolution of the grid might exceed the number of rows and |
| 37 | /// columns. For example, a grid of Braille patterns will have a resolution of |
| 38 | /// 2x4 dots per cell. This means that a grid of 10x10 cells will have a |
| 39 | /// resolution of 20x40 dots. |
| 40 | pub(super) trait Grid: Debug { |
| 41 | /// Get the resolution of the grid in number of dots. |
| 42 | /// |
| 43 | /// This doesn't have to be the same as the number of rows and columns of |
| 44 | /// the grid. For example, a grid of Braille patterns will have a |
| 45 | /// resolution of 2x4 dots per cell. This means that a grid of 10x10 |
| 46 | /// cells will have a resolution of 20x40 dots. |
| 47 | fn resolution(&self) -> (f64, f64); |
| 48 | /// Paint a point of the grid. |
| 49 | /// |
| 50 | /// The point is expressed in number of dots starting at the origin of the |
| 51 | /// grid in the top left corner. Note that this is not the same as the |
| 52 | /// `(x, y)` coordinates of the canvas. |
| 53 | fn paint(&mut self, x: usize, y: usize, color: Color); |
| 54 | /// Save the current state of the [`Grid`] as a layer to be rendered |
| 55 | fn save(&self) -> Layer; |
| 56 | /// Reset the grid to its initial state |
| 57 | fn reset(&mut self); |
| 58 | } |
| 59 | |
| 60 | /// The pattern and colour of a `PatternGrid` cell. |
| 61 | #[derive(Copy, Clone, Debug, Default)] |
| 62 | struct PatternCell { |
| 63 | /// The pattern of a grid character. |
| 64 | /// |
| 65 | /// The pattern is stored in the lower bits in a row-major order. For |
| 66 | /// instance, for a 2x4 pattern marker, bits 0 to 7 of this field should |
| 67 | /// represent the following pseudo-pixels: |
| 68 | /// |
| 69 | /// | 0 1 | |
| 70 | /// | 2 3 | |
| 71 | /// | 4 5 | |
| 72 | /// | 6 7 | |
| 73 | pattern: u8, |
| 74 | /// The color of a cell only supports foreground colors for now as there's |
| 75 | /// no way to individually set the background color of each pseudo-pixel |
| 76 | /// in a pattern character. |
| 77 | color: Option<Color>, |
| 78 | } |
| 79 | |
| 80 | /// The `PatternGrid` is a grid made up of cells each containing a `W`x`H` |
| 81 | /// pattern character. |
| 82 | /// |
| 83 | /// This makes it possible to draw shapes with a resolution of e.g. 2x4 (Braille |
| 84 | /// or Unicode octant) per cell. |
| 85 | /// Font support for the relevant pattern character is required. If your |
| 86 | /// terminal or font does not support the relevant Unicode block, you will see |
| 87 | /// Unicode replacement characters (�) instead. |
| 88 | /// |
| 89 | /// This grid type only supports a single foreground colour for each `W`x`H` |
| 90 | /// pattern character. There is no way to set the individual colour of each |
| 91 | /// pseudo-pixel. |
| 92 | #[derive(Debug)] |
| 93 | pub(super) struct PatternGrid<const W: usize, const H: usize> { |
| 94 | /// Width of the grid in number of terminal columns |
| 95 | width: u16, |
| 96 | /// Height of the grid in number of terminal rows |
| 97 | height: u16, |
| 98 | /// Pattern and color of the cells. |
| 99 | cells: Vec<PatternCell>, |
| 100 | /// Lookup table mapping patterns to characters. |
| 101 | char_table: &'static [char], |
| 102 | } |
| 103 | |
| 104 | impl<const W: usize, const H: usize> PatternGrid<W, H> { |
| 105 | /// Statically check that the dimension of the pattern is supported. |
| 106 | const _PATTERN_DIMENSION_CHECK: usize = u8::BITS as usize - W * H; |
| 107 | |
| 108 | /// Create a new `PatternGrid` with the given width and height measured in |
| 109 | /// terminal columns and rows respectively. |
| 110 | pub(super) fn new(width: u16, height: u16, char_table: &'static [char]) -> Self { |
| 111 | // Cause a static error if the pattern doesn't fit within 8 bits. |
| 112 | let _ = Self::_PATTERN_DIMENSION_CHECK; |
| 113 | |
| 114 | let length = usize::from(width) * usize::from(height); |
| 115 | Self { |
| 116 | width, |
| 117 | height, |
| 118 | cells: vec![PatternCell::default(); length], |
| 119 | char_table, |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | impl<const W: usize, const H: usize> Grid for PatternGrid<W, H> { |
| 125 | fn resolution(&self) -> (f64, f64) { |
| 126 | ( |
| 127 | f64::from(self.width) * W as f64, |
| 128 | f64::from(self.height) * H as f64, |
| 129 | ) |
| 130 | } |
| 131 | |
| 132 | fn paint(&mut self, x: usize, y: usize, color: Color) { |
| 133 | let index = y |
| 134 | .saturating_div(H) |
| 135 | .saturating_mul(self.width as usize) |
| 136 | .saturating_add(x.saturating_div(W)); |
| 137 | |
| 138 | // The ratatui/tui-rs implementation; this gives a more merged |
| 139 | // look, but it also makes it a bit harder to read in some cases. |
| 140 | // |
| 141 | // using get_mut here because we are indexing the vector with usize values |
| 142 | // and we want to make sure we don't panic if the index is out of bounds |
| 143 | // if let Some(cell) = self.cells.get_mut(index) { |
| 144 | // cell.pattern |= 1u8 << ((x % W) + W * (y % H)); |
| 145 | // cell.color = Some(color); |
| 146 | // } |
| 147 | |
| 148 | // Custom implementation do distinguish between lines better. |
| 149 | if let Some(cell) = self.cells.get_mut(index) { |
| 150 | if let Some(curr_color) = &mut cell.color { |
| 151 | if *curr_color != color { |
| 152 | // If the colour doesn't match, then reset the colour and cell. |
| 153 | *curr_color = color; |
| 154 | cell.pattern = 1u8 << ((x % W) + W * (y % H)); |
| 155 | } else { |
| 156 | // If it does match, then combine it with the previous underlying cell. |
| 157 | cell.pattern |= 1u8 << ((x % W) + W * (y % H)); |
| 158 | } |
| 159 | } else { |
| 160 | // If there's no color then just assume it's a brand new cell. |
| 161 | cell.color = Some(color); |
| 162 | cell.pattern = 1u8 << ((x % W) + W * (y % H)); |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | fn save(&self) -> Layer { |
| 168 | let contents = self |
| 169 | .cells |
| 170 | .iter() |
| 171 | .map(|&cell| { |
| 172 | let symbol = match cell.pattern { |
| 173 | // Skip rendering blank patterns to allow layers underneath |
| 174 | // to show through. |
| 175 | 0 => None, |
| 176 | idx => Some(self.char_table[idx as usize]), |
| 177 | }; |
| 178 | |
| 179 | LayerCell { |
| 180 | symbol, |
| 181 | fg: cell.color, |
| 182 | // Patterns only affect foreground. |
| 183 | bg: None, |
| 184 | } |
| 185 | }) |
| 186 | .collect(); |
| 187 | |
| 188 | Layer { contents } |
| 189 | } |
| 190 | |
| 191 | fn reset(&mut self) { |
| 192 | self.cells.fill_with(Default::default); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // impl Grid for BrailleGrid { |
| 197 | // fn resolution(&self) -> (f64, f64) { |
| 198 | // (f64::from(self.width) * 2.0, f64::from(self.height) * 4.0) |
| 199 | // } |
| 200 | // |
| 201 | // fn paint(&mut self, x: usize, y: usize, color: Color) { |
| 202 | // // Note the braille array corresponds to: |
| 203 | // // ``` |
| 204 | // // ⠁⠈ |
| 205 | // // ⠂⠐ |
| 206 | // // ⠄⠠ |
| 207 | // // ⡀⢀ |
| 208 | // // ``` |
| 209 | // const BLANK: u16 = 0x2800; |
| 210 | // const DOTS: [[u16; 2]; 4] = [ |
| 211 | // [0x0001, 0x0008], |
| 212 | // [0x0002, 0x0010], |
| 213 | // [0x0004, 0x0020], |
| 214 | // [0x0040, 0x0080], |
| 215 | // ]; |
| 216 | // |
| 217 | // let index = y / 4 * self.width as usize + x / 2; |
| 218 | // |
| 219 | // // The ratatui/tui-rs implementation; this gives a more merged |
| 220 | // // look, but it also makes it a bit harder to read in some cases. |
| 221 | // |
| 222 | // // if let Some(c) = self.utf16_code_points.get_mut(index) { |
| 223 | // // *c |= DOTS[y % 4][x % 2]; |
| 224 | // // } |
| 225 | // // if let Some(c) = self.colors.get_mut(index) { |
| 226 | // // *c = color; |
| 227 | // // } |
| 228 | // |
| 229 | // // Custom implementation to distinguish between lines better. |
| 230 | // if let Some(curr_color) = self.colors.get_mut(index) { |
| 231 | // if *curr_color != color { |
| 232 | // *curr_color = color; |
| 233 | // if let Some(cell) = self.utf16_code_points.get_mut(index) { |
| 234 | // *cell = BLANK | DOTS[y % 4][x % 2]; |
| 235 | // } |
| 236 | // } else if let Some(cell) = self.utf16_code_points.get_mut(index) |
| 237 | // { *cell |= DOTS[y % 4][x % 2]; |
| 238 | // } |
| 239 | // } |
| 240 | // } |
| 241 | // |
| 242 | // fn save(&self) -> Layer { |
| 243 | // let string = |
| 244 | // String::from_utf16(&self.utf16_code_points).expect("valid UTF-16 data"); |
| 245 | // // the background color is always reset for braille patterns |
| 246 | // let colors = self.colors.iter().map(|c| (*c, |
| 247 | // Color::Reset)).collect(); Layer { string, colors } |
| 248 | // } |
| 249 | // |
| 250 | // fn reset(&mut self) { |
| 251 | // self.utf16_code_points.fill(BLANK); |
| 252 | // self.colors.fill(Color::Reset); |
| 253 | // } |
| 254 | // } |
| 255 | |
| 256 | /// The `CharGrid` is a grid made up of cells each containing a single |
| 257 | /// character. |
| 258 | /// |
| 259 | /// This makes it possible to draw shapes with a resolution of 1x1 dots per |
| 260 | /// cell. This is useful when you want to draw shapes with a low resolution. |
| 261 | #[derive(Debug)] |
| 262 | pub(super) struct CharGrid { |
| 263 | /// Width of the grid in number of terminal columns |
| 264 | width: u16, |
| 265 | /// Height of the grid in number of terminal rows |
| 266 | height: u16, |
| 267 | /// The color of each cell |
| 268 | cells: Vec<Option<Color>>, |
| 269 | |
| 270 | /// The character to use for every cell - e.g. a block, dot, etc. |
| 271 | cell_char: char, |
| 272 | |
| 273 | /// If true, apply the color to the background as well as the foreground. |
| 274 | /// This is used for [`Marker::Block`], so that it will overwrite any |
| 275 | /// previous foreground character, but also leave a background that can |
| 276 | /// be overlaid with an additional foreground character. |
| 277 | apply_color_to_bg: bool, |
| 278 | } |
| 279 | |
| 280 | impl CharGrid { |
| 281 | /// Create a new `CharGrid` with the given width and height measured in |
| 282 | /// terminal columns and rows respectively. |
| 283 | pub(super) fn new(width: u16, height: u16, cell_char: char) -> Self { |
| 284 | let length = usize::from(width) * usize::from(height); |
| 285 | Self { |
| 286 | width, |
| 287 | height, |
| 288 | cells: vec![None; length], |
| 289 | cell_char, |
| 290 | apply_color_to_bg: false, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub(super) fn apply_color_to_bg(self) -> Self { |
| 295 | Self { |
| 296 | apply_color_to_bg: true, |
| 297 | ..self |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | impl Grid for CharGrid { |
| 303 | fn resolution(&self) -> (f64, f64) { |
| 304 | (f64::from(self.width), f64::from(self.height)) |
| 305 | } |
| 306 | |
| 307 | fn paint(&mut self, x: usize, y: usize, color: Color) { |
| 308 | let index = y.saturating_mul(self.width as usize).saturating_add(x); |
| 309 | // using get_mut here because we are indexing the vector with usize values |
| 310 | // and we want to make sure we don't panic if the index is out of bounds |
| 311 | if let Some(c) = self.cells.get_mut(index) { |
| 312 | *c = Some(color); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | fn save(&self) -> Layer { |
| 317 | Layer { |
| 318 | contents: self |
| 319 | .cells |
| 320 | .iter() |
| 321 | .map(|&color| LayerCell { |
| 322 | symbol: color.map(|_| self.cell_char), |
| 323 | fg: color, |
| 324 | bg: color.filter(|_| self.apply_color_to_bg), |
| 325 | }) |
| 326 | .collect(), |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | fn reset(&mut self) { |
| 331 | self.cells.fill(None); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | /// The `HalfBlockGrid` is a grid made up of cells each containing a half block |
| 336 | /// character. |
| 337 | /// |
| 338 | /// In terminals, each character is usually twice as tall as it is wide. Unicode |
| 339 | /// has a couple of vertical half block characters, the upper half block '▀' and |
| 340 | /// lower half block '▄' which take up half the height of a normal character but |
| 341 | /// the full width. Together with an empty space ' ' and a full block '█', we |
| 342 | /// can effectively double the resolution of a single cell. In addition, because |
| 343 | /// each character can have a foreground and background color, we can control |
| 344 | /// the color of the upper and lower half of each cell. This allows us to draw |
| 345 | /// shapes with a resolution of 1x2 "pixels" per cell. |
| 346 | /// |
| 347 | /// This allows for more flexibility than the `PatternGrid` which only supports |
| 348 | /// a single foreground color for each 2x4 dots cell, and the `CharGrid` which |
| 349 | /// only supports a single character for each cell. |
| 350 | #[derive(Debug)] |
| 351 | |
| 352 | pub(super) struct HalfBlockGrid { |
| 353 | /// Width of the grid in number of terminal columns |
| 354 | width: u16, |
| 355 | /// Height of the grid in number of terminal rows |
| 356 | height: u16, |
| 357 | /// Represents a single color for each "pixel" arranged in column, row order |
| 358 | pixels: Vec<Vec<Option<Color>>>, |
| 359 | } |
| 360 | |
| 361 | impl HalfBlockGrid { |
| 362 | /// Create a new `HalfBlockGrid` with the given width and height measured in |
| 363 | /// terminal columns and rows respectively. |
| 364 | pub(super) fn new(width: u16, height: u16) -> Self { |
| 365 | Self { |
| 366 | width, |
| 367 | height, |
| 368 | pixels: vec![vec![None; width as usize]; (height as usize) * 2], |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | impl Grid for HalfBlockGrid { |
| 374 | fn resolution(&self) -> (f64, f64) { |
| 375 | (f64::from(self.width), f64::from(self.height) * 2.0) |
| 376 | } |
| 377 | |
| 378 | fn paint(&mut self, x: usize, y: usize, color: Color) { |
| 379 | self.pixels[y][x] = Some(color); |
| 380 | } |
| 381 | |
| 382 | fn save(&self) -> Layer { |
| 383 | // Given that we store the pixels in a grid, and that we want to use 2 pixels |
| 384 | // arranged vertically to form a single terminal cell, which can be |
| 385 | // either empty, upper half block, lower half block or full block, we |
| 386 | // need examine the pixels in vertical pairs to decide what character to |
| 387 | // print in each cell. So these are the 4 states we use to represent each |
| 388 | // cell: |
| 389 | // |
| 390 | // 1. upper: reset, lower: reset => ' ' fg: reset / bg: reset |
| 391 | // 2. upper: reset, lower: color => '▄' fg: lower color / bg: reset |
| 392 | // 3. upper: color, lower: reset => '▀' fg: upper color / bg: reset |
| 393 | // 4. upper: color, lower: color => '▀' fg: upper color / bg: lower color |
| 394 | // |
| 395 | // Note that because the foreground reset color (i.e. default foreground color) |
| 396 | // is usually not the same as the background reset color (i.e. default |
| 397 | // background color), we need to swap around the colors for that state |
| 398 | // (2 reset/color). |
| 399 | // |
| 400 | // When the upper and lower colors are the same, we could continue to use an |
| 401 | // upper half block, but we choose to use a full block instead. This |
| 402 | // allows us to write unit tests that treat the cell as a single |
| 403 | // character instead of two half block characters. |
| 404 | |
| 405 | // first we join each adjacent row together to get an iterator that contains |
| 406 | // vertical pairs of pixels, with the lower row being the first element |
| 407 | // in the pair |
| 408 | let vertical_color_pairs = self |
| 409 | .pixels |
| 410 | .iter() |
| 411 | .tuples() |
| 412 | .flat_map(|(upper_row, lower_row)| zip(upper_row, lower_row)); |
| 413 | |
| 414 | // Then we determine the character to print for each pair, along with the color |
| 415 | // of the foreground and background. |
| 416 | let contents = vertical_color_pairs |
| 417 | .map(|(upper, lower)| { |
| 418 | let (symbol, fg, bg) = match (upper, lower) { |
| 419 | (None, None) => (None, None, None), |
| 420 | (None, Some(lower)) => (Some(symbols::half_block::LOWER), Some(*lower), None), |
| 421 | (Some(upper), None) => (Some(symbols::half_block::UPPER), Some(*upper), None), |
| 422 | (Some(upper), Some(lower)) if lower == upper => { |
| 423 | (Some(symbols::half_block::FULL), Some(*upper), Some(*lower)) |
| 424 | } |
| 425 | (Some(upper), Some(lower)) => { |
| 426 | (Some(symbols::half_block::UPPER), Some(*upper), Some(*lower)) |
| 427 | } |
| 428 | }; |
| 429 | LayerCell { symbol, fg, bg } |
| 430 | }) |
| 431 | .collect(); |
| 432 | |
| 433 | Layer { contents } |
| 434 | } |
| 435 | |
| 436 | fn reset(&mut self) { |
| 437 | self.pixels.fill(vec![None; self.width as usize]); |
| 438 | } |
| 439 | } |