use super::*;
#[must_use]
pub(crate) fn estimate_table_text_width(text: &str, font_size: f32, is_bold: bool) -> f32 {
let weight_scale: f32 = if is_bold { 1.08 } else { 1.0 };
let mut best_line_w: f32 = 0.0;
for line in text.split('\n') {
let mut line_w: f32 = 0.0;
for ch in line.chars() {
let factor: f32 = if !ch.is_ascii() {
1.15
} else if matches!(
ch,
'i' | 'l' | 'I' | '1' | '.' | ',' | ':' | ';' | '|' | '!' | '\'' | ' '
) {
0.38
} else if ch.is_ascii_uppercase() || matches!(ch, 'w' | 'm' | '@' | '%' | '#' | '&') {
0.76
} else {
0.60
};
line_w += font_size * factor * weight_scale;
}
if line_w > best_line_w {
best_line_w = line_w;
}
}
best_line_w
}
#[must_use]
pub(crate) fn compute_table_column_widths(
headers: &[String],
rows: &[Vec<String>],
header_font: f32,
body_font: f32,
) -> (Vec<f32>, f32) {
let mut col_count: usize = headers.len();
for row in rows.iter() {
if row.len() > col_count {
col_count = row.len();
}
}
if col_count == 0 {
return (Vec::new(), 0.0);
}
let mut widths: Vec<f32> = Vec::with_capacity(col_count);
let mut total: f32 = 0.0;
for ci in 0..col_count {
let mut max_text_w: f32 = headers
.get(ci)
.map(|height_val: &String| {
estimate_table_text_width(height_val.as_str(), header_font, true)
})
.unwrap_or(0.0);
for row in rows.iter() {
if let Some(cell) = row.get(ci) {
let cell_w: f32 = estimate_table_text_width(cell.as_str(), body_font, false);
if cell_w > max_text_w {
max_text_w = cell_w;
}
}
}
let col_w: f32 = (max_text_w + TABLE_CELL_H_PAD_ALLOWANCE)
.clamp(TABLE_COL_MIN_WIDTH, TABLE_COL_MAX_WIDTH);
widths.push(col_w);
total += col_w;
}
(widths, total)
}