| 1 | #[cfg(feature = "tty")] |
| 2 | use crossterm::style::{Stylize, style}; |
| 3 | use unicode_segmentation::UnicodeSegmentation; |
| 4 | use unicode_width::UnicodeWidthStr; |
| 5 | |
| 6 | use super::content_split::{measure_text_width, split_line}; |
| 7 | #[cfg(feature = "tty")] |
| 8 | use crate::style::{map_attribute, map_color}; |
| 9 | use crate::{cell::Cell, row::Row, style::CellAlignment, table::Table, utils::ColumnDisplayInfo}; |
| 10 | |
| 11 | pub fn delimiter(cell: &Cell, info: &ColumnDisplayInfo, table: &Table) -> char { |
| 12 | // Determine, which delimiter should be used |
| 13 | if let Some(delimiter) = cell.delimiter { |
| 14 | delimiter |
| 15 | } else if let Some(delimiter) = info.delimiter { |
| 16 | delimiter |
| 17 | } else if let Some(delimiter) = table.delimiter { |
| 18 | delimiter |
| 19 | } else { |
| 20 | ' ' |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | /// Returns the formatted content of the table. |
| 25 | /// The content is organized in the following structure |
| 26 | /// |
| 27 | /// tc stands for table content and represents the returned value |
| 28 | /// ``` text |
| 29 | /// column1 column2 |
| 30 | /// row1 tc[0][0][0] tc[0][0][1] <-line1 |
| 31 | /// tc[0][1][0] tc[0][1][1] <-line2 |
| 32 | /// tc[0][2][0] tc[0][2][1] <-line3 |
| 33 | /// |
| 34 | /// row2 tc[1][0][0] tc[1][0][1] <-line1 |
| 35 | /// tc[1][1][0] tc[1][1][1] <-line2 |
| 36 | /// tc[1][2][0] tc[1][2][1] <-line3 |
| 37 | /// ``` |
| 38 | /// |
| 39 | /// The strings for each row will be padded and aligned according to their respective column. |
| 40 | pub fn format_content(table: &Table, display_info: &[ColumnDisplayInfo]) -> Vec<Vec<Vec<String>>> { |
| 41 | // The content of the whole table |
| 42 | let mut table_content = Vec::with_capacity(table.rows.len() + 1); |
| 43 | |
| 44 | // Format table header if it exists |
| 45 | if let Some(header) = table.header() { |
| 46 | table_content.push(format_row(header, display_info, table)); |
| 47 | } |
| 48 | |
| 49 | for row in table.rows.iter() { |
| 50 | table_content.push(format_row(row, display_info, table)); |
| 51 | } |
| 52 | table_content |
| 53 | } |
| 54 | |
| 55 | pub fn format_row( |
| 56 | row: &Row, |
| 57 | display_infos: &[ColumnDisplayInfo], |
| 58 | table: &Table, |
| 59 | ) -> Vec<Vec<String>> { |
| 60 | // The content of this specific row |
| 61 | let mut temp_row_content = Vec::with_capacity(display_infos.len()); |
| 62 | |
| 63 | let mut cell_iter = row.cells.iter(); |
| 64 | // Now iterate over all cells and handle them according to their alignment |
| 65 | for info in display_infos.iter() { |
| 66 | if info.is_hidden { |
| 67 | cell_iter.next(); |
| 68 | continue; |
| 69 | } |
| 70 | |
| 71 | // Each cell is divided into several lines divided by newline |
| 72 | // Every line that's too long will be split into multiple lines |
| 73 | let mut cell_lines = Vec::new(); |
| 74 | |
| 75 | // Check if the row has as many cells as the table has columns. |
| 76 | // If that's not the case, create a new cell with empty spaces. |
| 77 | let Some(cell) = cell_iter.next() else { |
| 78 | cell_lines.push(" ".repeat(info.width().into())); |
| 79 | temp_row_content.push(cell_lines); |
| 80 | continue; |
| 81 | }; |
| 82 | |
| 83 | // The delimiter is configurable, determine which one should be used for this cell. |
| 84 | let delimiter = delimiter(cell, info, table); |
| 85 | |
| 86 | // Iterate over each line and split it into multiple lines if necessary. |
| 87 | // Newlines added by the user will be preserved. |
| 88 | for line in cell.content.iter() { |
| 89 | if measure_text_width(line) > info.content_width.into() { |
| 90 | let mut parts = split_line(line, info, delimiter); |
| 91 | cell_lines.append(&mut parts); |
| 92 | } else { |
| 93 | cell_lines.push(line.into()); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // Remove all unneeded lines of this cell, if the row's height is capped to a certain |
| 98 | // amount of lines and there're too many lines in this cell. |
| 99 | // This then truncates and inserts a '...' string at the end of the last line to indicate |
| 100 | // that the cell has been truncated. |
| 101 | if let Some(lines) = row.max_height |
| 102 | && cell_lines.len() > lines |
| 103 | { |
| 104 | // We already have to many lines. Cut off the surplus lines. |
| 105 | let _ = cell_lines.split_off(lines); |
| 106 | |
| 107 | // Directly access the last line. |
| 108 | let last_line = cell_lines |
| 109 | .get_mut(lines - 1) |
| 110 | .expect("We know it's this long."); |
| 111 | |
| 112 | // Truncate any ansi codes, as the following cutoff might break ansi code |
| 113 | // otherwise anyway. This could be handled smarter, but it's simple and just works. |
| 114 | #[cfg(feature = "custom_styling")] |
| 115 | { |
| 116 | let stripped = console::strip_ansi_codes(last_line).to_string(); |
| 117 | *last_line = stripped; |
| 118 | } |
| 119 | |
| 120 | let max_width: usize = info.content_width.into(); |
| 121 | let indicator_width = table.truncation_indicator.width(); |
| 122 | |
| 123 | let mut truncate_at = 0; |
| 124 | // Start the accumulated_width with the indicator_width, which is the minimum width |
| 125 | // we may show anyway. |
| 126 | let mut accumulated_width = indicator_width; |
| 127 | let mut full_string_fits = false; |
| 128 | |
| 129 | // Leave these print statements in here in case we ever have to debug this annoying |
| 130 | // stuff again. |
| 131 | //println!("\nSTART:"); |
| 132 | //println!("\nMax width: {max_width}, Indicator width: {indicator_width}"); |
| 133 | //println!("Full line hex: {last_line}"); |
| 134 | //println!( |
| 135 | // "Full line hex: {}", |
| 136 | // last_line |
| 137 | // .as_bytes() |
| 138 | // .iter() |
| 139 | // .map(|byte| format!("{byte:02x}")) |
| 140 | // .collect::<Vec<String>>() |
| 141 | // .join(", ") |
| 142 | //); |
| 143 | |
| 144 | // Iterate through the UTF-8 graphemes. |
| 145 | // Check the `split_long_word` inline function docs to see why we're using |
| 146 | // graphemes. |
| 147 | // **Note:** The `index` here is the **byte** index. So we cannot just |
| 148 | // String::truncate afterwards. We have to convert to a byte vector to perform |
| 149 | // the truncation first. |
| 150 | let mut grapheme_iter = last_line.grapheme_indices(true).peekable(); |
| 151 | while let Some((index, grapheme)) = grapheme_iter.next() { |
| 152 | // Leave these print statements in here in case we ever have to debug this |
| 153 | // annoying stuff again |
| 154 | //println!( |
| 155 | // "Current index: {index}, Next grapheme: {grapheme} (width: {})", |
| 156 | // grapheme.width() |
| 157 | //); |
| 158 | //println!( |
| 159 | // "Next grapheme hex: {}", |
| 160 | // grapheme |
| 161 | // .as_bytes() |
| 162 | // .iter() |
| 163 | // .map(|byte| format!("{byte:02x}")) |
| 164 | // .collect::<Vec<String>>() |
| 165 | // .join(", ") |
| 166 | //); |
| 167 | |
| 168 | // Immediately save where to truncate in case this grapheme doesn't fit. |
| 169 | // The index is just before the current grapheme actually starts. |
| 170 | truncate_at = index; |
| 171 | // Check if the next grapheme would break the boundary of the allowed line |
| 172 | // length. |
| 173 | let new_width = accumulated_width + grapheme.width(); |
| 174 | //println!( |
| 175 | // "Next width: {new_width}/{max_width} ({accumulated_width} + {})", |
| 176 | // grapheme.width() |
| 177 | //); |
| 178 | if new_width > max_width { |
| 179 | //println!( |
| 180 | // "Breaking: {:?}", |
| 181 | // accumulated_width + grapheme.width() > max_width |
| 182 | //); |
| 183 | break; |
| 184 | } |
| 185 | |
| 186 | // The grapheme seems to fit. Save the index and check the next one. |
| 187 | accumulated_width += grapheme.width(); |
| 188 | |
| 189 | // This is a special case. |
| 190 | // We reached the last char, meaning that full last line + the indicator fit. |
| 191 | if grapheme_iter.peek().is_none() { |
| 192 | full_string_fits = true |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // Only do any truncation logic if the line doesn't fit. |
| 197 | if !full_string_fits { |
| 198 | // Truncate the string at the byte index just behind the last valid grapheme |
| 199 | // and overwrite the last line with the new truncated string. |
| 200 | let mut last_line_bytes = last_line.clone().into_bytes(); |
| 201 | last_line_bytes.truncate(truncate_at); |
| 202 | let new_last_line = |
| 203 | String::from_utf8(last_line_bytes).expect("We cut at an exact char boundary"); |
| 204 | *last_line = new_last_line; |
| 205 | } |
| 206 | |
| 207 | // Push the truncation indicator. |
| 208 | last_line.push_str(&table.truncation_indicator); |
| 209 | } |
| 210 | |
| 211 | // Iterate over all generated lines of this cell and align them |
| 212 | let cell_lines = cell_lines |
| 213 | .iter() |
| 214 | .map(|line| align_line(table, info, cell, line.to_string())); |
| 215 | |
| 216 | temp_row_content.push(cell_lines.collect()); |
| 217 | } |
| 218 | |
| 219 | // Right now, we have a different structure than desired. |
| 220 | // The content is organized by `row->cell->line`. |
| 221 | // We want to remove the cell from our datastructure, since this makes the next step a lot |
| 222 | // easier. In the end it should look like this: `row->lines->column`. |
| 223 | // To achieve this, we calculate the max amount of lines for the current row. |
| 224 | // Afterwards, we iterate over each cell and convert the current structure to the desired one. |
| 225 | // This step basically transforms this: |
| 226 | // tc[0][0][0] tc[0][1][0] |
| 227 | // tc[0][0][1] tc[0][1][1] |
| 228 | // tc[0][0][2] This part of the line is missing |
| 229 | // |
| 230 | // to this: |
| 231 | // tc[0][0][0] tc[0][0][1] |
| 232 | // tc[0][1][0] tc[0][1][1] |
| 233 | // tc[0][2][0] tc[0][2][1] <- Now filled with placeholder (spaces) |
| 234 | let max_lines = temp_row_content.iter().map(Vec::len).max().unwrap_or(0); |
| 235 | let mut row_content = Vec::with_capacity(max_lines * display_infos.len()); |
| 236 | |
| 237 | // Each column should have `max_lines` for this row. |
| 238 | // Cells content with fewer lines will simply be topped up with empty strings. |
| 239 | for index in 0..max_lines { |
| 240 | let mut line = Vec::with_capacity(display_infos.len()); |
| 241 | let mut cell_iter = temp_row_content.iter(); |
| 242 | |
| 243 | for info in display_infos.iter() { |
| 244 | if info.is_hidden { |
| 245 | continue; |
| 246 | } |
| 247 | |
| 248 | let cell = cell_iter.next().unwrap(); |
| 249 | match cell.get(index) { |
| 250 | // The current cell has content for this line. Append it |
| 251 | Some(content) => line.push(content.clone()), |
| 252 | // The current cell doesn't have content for this line. |
| 253 | // Fill with a placeholder (empty spaces) |
| 254 | None => line.push(" ".repeat(info.width().into())), |
| 255 | } |
| 256 | } |
| 257 | row_content.push(line); |
| 258 | } |
| 259 | |
| 260 | row_content |
| 261 | } |
| 262 | |
| 263 | /// Apply the alignment for a column. Alignment can be either Left/Right/Center. |
| 264 | /// In every case all lines will be exactly the same character length `info.width - padding long` |
| 265 | /// This is needed, so we can simply insert it into the border frame later on. |
| 266 | /// Padding is applied in this function as well. |
| 267 | #[allow(unused_variables)] |
| 268 | fn align_line(table: &Table, info: &ColumnDisplayInfo, cell: &Cell, mut line: String) -> String { |
| 269 | let content_width = info.content_width; |
| 270 | let remaining: usize = usize::from(content_width).saturating_sub(measure_text_width(&line)); |
| 271 | |
| 272 | // Apply the styling before aligning the line, if the user requests it. |
| 273 | // That way non-delimiter whitespaces won't have stuff like underlines. |
| 274 | #[cfg(feature = "tty")] |
| 275 | if table.should_style() && table.style_text_only { |
| 276 | line = style_line(line, cell); |
| 277 | } |
| 278 | |
| 279 | // Determine the alignment of the column cells. |
| 280 | // Cell settings overwrite the columns Alignment settings. |
| 281 | // Default is Left |
| 282 | let alignment = if let Some(alignment) = cell.alignment { |
| 283 | alignment |
| 284 | } else if let Some(alignment) = info.cell_alignment { |
| 285 | alignment |
| 286 | } else { |
| 287 | CellAlignment::Left |
| 288 | }; |
| 289 | |
| 290 | // Apply left/right/both side padding depending on the alignment of the column |
| 291 | match alignment { |
| 292 | CellAlignment::Left => { |
| 293 | line += &" ".repeat(remaining); |
| 294 | } |
| 295 | CellAlignment::Right => { |
| 296 | line = " ".repeat(remaining) + &line; |
| 297 | } |
| 298 | CellAlignment::Center => { |
| 299 | let left_padding = (remaining as f32 / 2f32).ceil() as usize; |
| 300 | let right_padding = (remaining as f32 / 2f32).floor() as usize; |
| 301 | line = " ".repeat(left_padding) + &line + &" ".repeat(right_padding); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | line = pad_line(&line, info); |
| 306 | |
| 307 | #[cfg(feature = "tty")] |
| 308 | if table.should_style() && !table.style_text_only { |
| 309 | return style_line(line, cell); |
| 310 | } |
| 311 | |
| 312 | line |
| 313 | } |
| 314 | |
| 315 | /// Apply the column's padding to this line |
| 316 | fn pad_line(line: &str, info: &ColumnDisplayInfo) -> String { |
| 317 | let mut padded_line = String::new(); |
| 318 | |
| 319 | padded_line += &" ".repeat(info.padding.0.into()); |
| 320 | padded_line += line; |
| 321 | padded_line += &" ".repeat(info.padding.1.into()); |
| 322 | |
| 323 | padded_line |
| 324 | } |
| 325 | |
| 326 | #[cfg(feature = "tty")] |
| 327 | fn style_line(line: String, cell: &Cell) -> String { |
| 328 | // Just return the line, if there's no need to style. |
| 329 | if cell.fg.is_none() && cell.bg.is_none() && cell.attributes.is_empty() { |
| 330 | return line; |
| 331 | } |
| 332 | |
| 333 | let mut content = style(line); |
| 334 | |
| 335 | // Apply text color |
| 336 | if let Some(color) = cell.fg { |
| 337 | content = content.with(map_color(color)); |
| 338 | } |
| 339 | |
| 340 | // Apply background color |
| 341 | if let Some(color) = cell.bg { |
| 342 | content = content.on(map_color(color)); |
| 343 | } |
| 344 | |
| 345 | for attribute in cell.attributes.iter() { |
| 346 | content = content.attribute(map_attribute(*attribute)); |
| 347 | } |
| 348 | |
| 349 | content.to_string() |
| 350 | } |