use super::grid::Merge;
use super::styles::{Color, Dxf, Edge, Line};
use crate::word::docx::parse;
use roxmltree::Node;
const BAND_TINT: f32 = 0.8;
const DARK_BAND_TINT: f32 = 0.6;
const GREY_BAND_TINT: f32 = 0.85;
const LINE_TINT: f32 = 0.4;
const TEXT_SHADE: f32 = -0.25;
const FAMILY: u32 = 7;
const DARK_1: u8 = 1;
const LIGHT_1: u8 = 0;
const ACCENT_1: u8 = 4;
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct TableStyle {
pub(crate) range: Merge,
header_rows: u32,
total_rows: u32,
kind: Kind,
color: u32,
row_stripes: bool,
col_stripes: bool,
first_col: bool,
last_col: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
LightLines,
LightHeader,
LightGrid,
MediumLines,
MediumBody,
MediumGrid,
}
pub(crate) fn read(xml: &str, header_rows: u32) -> Option<TableStyle> {
let doc = parse(xml).ok()?;
let table = doc.root_element();
let info = table
.children()
.find(|node| node.tag_name().name() == "tableStyleInfo")?;
let (kind, color) = kind(info.attribute("name")?)?;
let on = |node: Node<'_, '_>, name| matches!(node.attribute(name), Some("1" | "true"));
let count = |name| table.attribute(name).and_then(|value| value.parse::<u32>().ok());
Some(TableStyle {
range: table.attribute("ref").and_then(super::sheet::range)?,
header_rows,
total_rows: count("totalsRowCount").unwrap_or(0),
kind,
color,
row_stripes: on(info, "showRowStripes"),
col_stripes: on(info, "showColumnStripes"),
first_col: on(info, "showFirstColumn"),
last_col: on(info, "showLastColumn"),
})
}
fn kind(name: &str) -> Option<(Kind, u32)> {
let (family, number) = if let Some(number) = name.strip_prefix("TableStyleLight") {
("light", number)
} else {
("medium", name.strip_prefix("TableStyleMedium")?)
};
let number = number.parse::<u32>().ok().filter(|number| *number >= 1)?;
let (group, color) = ((number - 1) / FAMILY, (number - 1) % FAMILY);
let kind = match (family, group) {
("light", 0) => Kind::LightLines,
("light", 1) => Kind::LightHeader,
("light", 2) => Kind::LightGrid,
("medium", 0 | 2) => Kind::MediumLines,
("medium", 1) => Kind::MediumBody,
("medium", 3) => Kind::MediumGrid,
_ => return None,
};
Some((kind, color))
}
impl TableStyle {
fn paint(&self, tint: f32) -> Color {
let index = if self.color == 0 {
DARK_1
} else {
ACCENT_1 + u8::try_from(self.color - 1).unwrap_or(0)
};
Color::Theme(index, tint)
}
fn band_tint(&self) -> f32 {
if self.color == 0 { GREY_BAND_TINT } else { BAND_TINT }
}
pub(crate) fn cell(&self, (row, col): (u32, u32)) -> Option<Dxf> {
let range = self.range;
if !(range.top..=range.bottom).contains(&row) || !(range.left..=range.right).contains(&col) {
return None;
}
let header = row < range.top + self.header_rows;
let total = self.total_rows > 0 && row + self.total_rows > range.bottom;
let body_row = row - range.top - self.header_rows.min(row - range.top);
let banded = !header && !total && self.row_stripes && body_row.is_multiple_of(2);
let col_banded = !header && !total && self.col_stripes && (col - range.left).is_multiple_of(2);
let edges = Edges {
top: row == range.top,
bottom: row == range.bottom,
left: col == range.left,
right: col == range.right,
};
let mut dxf = self.whole(edges);
if col_banded || banded {
self.band(&mut dxf);
}
if (self.first_col && col == range.left) || (self.last_col && col == range.right) {
dxf.bold = Some(true);
}
if header {
self.header(&mut dxf);
}
if total {
dxf.bold = Some(true);
dxf.borders[2] = Some(edge(Line::Double, self.paint(0.0)));
}
Some(dxf)
}
fn whole(&self, edges: Edges) -> Dxf {
let mut dxf = Dxf::default();
let color = self.paint(0.0);
let (outline, inside_h, inside_v) = match self.kind {
Kind::LightLines => {
if self.color != 0 {
dxf.color = Some(self.paint(TEXT_SHADE));
}
(Some(([false, false, true, true], color)), None, None)
}
Kind::LightHeader => (Some(([true; 4], color)), None, None),
Kind::LightGrid => (Some(([true; 4], color)), Some(color), Some(color)),
Kind::MediumLines => {
let line = self.paint(LINE_TINT);
(Some(([true; 4], line)), Some(line), None)
}
Kind::MediumBody => {
let white = Color::Theme(LIGHT_1, 0.0);
dxf.fill = Some(self.paint(self.band_tint()));
(Some(([true; 4], white)), Some(white), Some(white))
}
Kind::MediumGrid => {
let line = self.paint(LINE_TINT);
dxf.fill = Some(self.paint(self.band_tint()));
(Some(([true; 4], line)), Some(line), Some(line))
}
};
let at_edge = [edges.left, edges.right, edges.top, edges.bottom];
for side in 0..4 {
let inside = if side < 2 { inside_v } else { inside_h };
let color = match outline {
Some((sides, color)) if at_edge[side] && sides[side] => Some(color),
_ if !at_edge[side] => inside,
_ => None,
};
dxf.borders[side] = color.map(|color| edge(Line::Solid, color));
}
dxf
}
fn band(&self, dxf: &mut Dxf) {
match self.kind {
Kind::LightHeader => {
dxf.borders[2] = Some(edge(Line::Solid, self.paint(0.0)));
dxf.borders[3] = Some(edge(Line::Solid, self.paint(0.0)));
}
Kind::MediumBody | Kind::MediumGrid => {
let tint = if self.color == 0 {
DARK_BAND_TINT + 0.1
} else {
DARK_BAND_TINT
};
dxf.fill = Some(self.paint(tint));
}
Kind::LightLines | Kind::LightGrid | Kind::MediumLines => dxf.fill = Some(self.paint(self.band_tint())),
}
}
fn header(&self, dxf: &mut Dxf) {
dxf.bold = Some(true);
match self.kind {
Kind::LightHeader | Kind::MediumLines | Kind::MediumBody => {
dxf.fill = Some(self.paint(0.0));
dxf.color = Some(Color::Theme(LIGHT_1, 0.0));
}
Kind::LightLines | Kind::LightGrid => {
dxf.fill = None;
dxf.borders[3] = Some(edge(Line::Solid, self.paint(0.0)));
}
Kind::MediumGrid => dxf.fill = None,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Edges {
top: bool,
bottom: bool,
left: bool,
right: bool,
}
fn edge(line: Line, color: Color) -> Edge {
Edge {
line,
width_px: if line == Line::Double { 3.0 } else { 1.0 },
color: Some(color),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn table(info: &str) -> TableStyle {
read(
&format!(
r#"<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ref="B2:D5"><tableStyleInfo {info}/></table>"#
),
1,
)
.unwrap()
}
#[test]
fn medium_2_has_a_blue_header_and_banded_rows() {
let style = table(r#"name="TableStyleMedium2" showRowStripes="1""#);
let header = style.cell((1, 1)).unwrap();
assert_eq!(header.fill, Some(Color::Theme(ACCENT_1, 0.0)));
assert_eq!(header.color, Some(Color::Theme(LIGHT_1, 0.0)));
assert_eq!(header.bold, Some(true));
let first = style.cell((2, 2)).unwrap();
assert_eq!(first.fill, Some(Color::Theme(ACCENT_1, BAND_TINT)));
assert_eq!(style.cell((3, 2)).unwrap().fill, None);
assert!(style.cell((0, 1)).is_none());
assert!(style.cell((2, 4)).is_none());
}
#[test]
fn dark_and_unknown_styles_are_left_out() {
let xml = |name: &str| {
format!(
r#"<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ref="A1:B2"><tableStyleInfo name="{name}"/></table>"#
)
};
assert!(read(&xml("TableStyleDark1"), 1).is_none());
assert!(read(&xml("MyStyle"), 1).is_none());
assert!(read(&xml("TableStyleLight1"), 1).is_some());
}
}