#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HeaderFooterItem {
pub item_type: String,
pub font_name: String,
pub font_size: Option<i64>,
pub font_color: String,
pub text: Option<String>,
}
impl HeaderFooterItem {
pub const LEFT: &'static str = "L";
pub const CENTER: &'static str = "C";
pub const RIGHT: &'static str = "R";
pub const REPLACE_LIST: [(&str, &str); 9] = [
("\n", "_x000D_"),
("&[Page]", "&P"),
("&[Pages]", "&N"),
("&[Date]", "&D"),
("&[Time]", "&T"),
("&[Path]", "&Z"),
("&[File]", "&F"),
("&[Tab]", "&A"),
("&[Picture]", "&G"),
];
pub fn new(item_type: &str) -> Self {
HeaderFooterItem {
item_type: item_type.to_string(),
font_name: "Calibri,Regular".to_string(),
font_size: None,
font_color: "000000".to_string(),
text: None,
}
}
pub fn has_text(&self) -> bool {
self.text.as_deref().is_some_and(|t| !t.is_empty())
}
pub fn to_header_string(&self) -> String {
let Some(text) = self.text.as_deref().filter(|t| !t.is_empty()) else {
return String::new();
};
let mut parts: Vec<String> = vec![
format!("&{}", self.item_type),
format!("&\"{}\"", self.font_name),
];
if let Some(size) = self.font_size {
parts.push(format!("&{size}"));
}
parts.push(format!("&K{}", self.font_color));
let mut text = text.to_string();
for (old, new) in HeaderFooterItem::REPLACE_LIST {
text = text.replace(old, new);
}
parts.push(text);
parts.concat()
}
pub fn set_from_header_string(&mut self, item_array: &[String]) {
let mut text_array: Vec<String> = Vec::new();
for (position, raw) in item_array.iter().enumerate() {
let (item, separated) = if position == 0 {
match raw.strip_prefix(self.item_type.as_str()) {
Some(rest) => (rest.to_string(), false),
None => continue,
}
} else {
(raw.clone(), true)
};
if item.is_empty() {
continue;
}
if !text_array.is_empty() {
text_array.push(format!("&{item}"));
} else if let Some(stripped) = item.strip_prefix('"') {
self.font_name = stripped.replace('"', "");
} else if let Some(color) = item.strip_prefix('K') {
if color.len() >= 6 {
self.font_color = color[..6].to_string();
text_array.push(color[6..].to_string());
} else {
text_array.push(format!("&{item}"));
}
} else if let Ok(size) = item.parse::<i64>() {
self.font_size = Some(size);
} else if separated {
text_array.push(format!("&{item}"));
} else {
text_array.push(item);
}
}
self.text = Some(text_array.concat());
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderFooter {
pub left_header: HeaderFooterItem,
pub center_header: HeaderFooterItem,
pub right_header: HeaderFooterItem,
pub left_footer: HeaderFooterItem,
pub center_footer: HeaderFooterItem,
pub right_footer: HeaderFooterItem,
}
impl Default for HeaderFooter {
fn default() -> Self {
HeaderFooter {
left_header: HeaderFooterItem::new(HeaderFooterItem::LEFT),
center_header: HeaderFooterItem::new(HeaderFooterItem::CENTER),
right_header: HeaderFooterItem::new(HeaderFooterItem::RIGHT),
left_footer: HeaderFooterItem::new(HeaderFooterItem::LEFT),
center_footer: HeaderFooterItem::new(HeaderFooterItem::CENTER),
right_footer: HeaderFooterItem::new(HeaderFooterItem::RIGHT),
}
}
}
impl HeaderFooter {
pub fn new() -> Self {
HeaderFooter::default()
}
pub fn has_header(&self) -> bool {
self.left_header.has_text() || self.center_header.has_text() || self.right_header.has_text()
}
pub fn has_footer(&self) -> bool {
self.left_footer.has_text() || self.center_footer.has_text() || self.right_footer.has_text()
}
pub fn header_string(&self) -> String {
let mut parts = Vec::new();
for item in [&self.left_header, &self.center_header, &self.right_header] {
if item.has_text() {
parts.push(item.to_header_string());
}
}
parts.concat()
}
pub fn footer_string(&self) -> String {
let mut parts = Vec::new();
for item in [&self.left_footer, &self.center_footer, &self.right_footer] {
if item.has_text() {
parts.push(item.to_header_string());
}
}
parts.concat()
}
pub fn set_header(&mut self, item: &str) {
let items = split_header(item);
let (left, center, right) = section_bounds(&items);
if let Some(fields) = left {
self.left_header.set_from_header_string(&fields);
}
if let Some(fields) = center {
self.center_header.set_from_header_string(&fields);
}
if let Some(fields) = right {
self.right_header.set_from_header_string(&fields);
}
}
pub fn set_footer(&mut self, item: &str) {
let items = split_header(item);
let (left, center, right) = section_bounds(&items);
if let Some(fields) = left {
self.left_footer.set_from_header_string(&fields);
}
if let Some(fields) = center {
self.center_footer.set_from_header_string(&fields);
}
if let Some(fields) = right {
self.right_footer.set_from_header_string(&fields);
}
}
}
fn split_header(item: &str) -> Vec<String> {
const SENTINEL: &str = "#DOUBLEAMP#";
let guarded = item.replace("&&", SENTINEL);
guarded
.split('&')
.map(|part| part.replace(SENTINEL, "&&"))
.collect()
}
pub type SectionSpans = (
Option<Vec<String>>,
Option<Vec<String>>,
Option<Vec<String>>,
);
fn section_bounds(items: &[String]) -> SectionSpans {
let find = |marker: &str| items.iter().position(|item| item.starts_with(marker));
let left = find(HeaderFooterItem::LEFT);
let center = find(HeaderFooterItem::CENTER);
let right = find(HeaderFooterItem::RIGHT);
let order = [
(HeaderFooterItem::LEFT, left),
(HeaderFooterItem::CENTER, center),
(HeaderFooterItem::RIGHT, right),
];
let mut spans: SectionSpans = (None, None, None);
for (position, (marker, at)) in order.into_iter().enumerate() {
let Some(at) = at else {
continue;
};
let next = order[position + 1..]
.iter()
.filter_map(|(_, other)| *other)
.filter(|stop| *stop > at)
.min()
.unwrap_or(items.len());
let mut fields = vec![items[at].clone()];
if at + 1 < next {
fields.extend_from_slice(&items[at + 1..next]);
}
debug_assert!(fields[0].starts_with(marker));
let slot = match marker {
HeaderFooterItem::LEFT => &mut spans.0,
HeaderFooterItem::CENTER => &mut spans.1,
_ => &mut spans.2,
};
*slot = Some(fields);
}
spans
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_header_footer_writes_nothing() {
let hf = HeaderFooter::new();
assert!(!hf.has_header());
assert!(!hf.has_footer());
assert_eq!(hf.header_string(), "");
assert_eq!(hf.footer_string(), "");
}
#[test]
fn round_trips_plain_text() {
let mut hf = HeaderFooter::new();
hf.set_header("&L&Left text");
assert!(hf.has_header());
assert_eq!(hf.left_header.text, Some("&Left text".to_string()));
let rendered = hf.header_string();
assert!(rendered.starts_with("&L&\"Calibri,Regular\""));
assert!(rendered.contains("Left text"));
}
#[test]
fn parses_sections() {
let mut hf = HeaderFooter::new();
hf.set_header("&L&left&C¢re&R&right");
assert_eq!(hf.left_header.text, Some("&left".to_string()));
assert_eq!(hf.center_header.text, Some("¢re".to_string()));
assert_eq!(hf.right_header.text, Some("&right".to_string()));
let rendered = hf.header_string();
assert!(rendered.starts_with("&L"));
assert!(rendered.contains("centre"));
assert!(rendered.ends_with("&right"));
}
#[test]
fn font_and_colour_codes_are_parsed() {
let mut item = HeaderFooterItem::new(HeaderFooterItem::LEFT);
item.set_from_header_string(&[
"L".to_string(),
"\"Arial\"".to_string(),
"12".to_string(),
"KFF0000".to_string(),
"text".to_string(),
]);
assert_eq!(item.font_name, "Arial");
assert_eq!(item.font_size, Some(12));
assert_eq!(item.font_color, "FF0000");
assert_eq!(item.text, Some("&text".to_string()));
}
#[test]
fn a_marker_glued_to_its_text_is_a_section() {
let mut hf = HeaderFooter::new();
hf.set_header("&Lleft");
assert_eq!(hf.left_header.text.as_deref(), Some("left"));
assert!(hf.has_header());
}
#[test]
fn a_glued_marker_keeps_the_codes_that_follow_it() {
let mut hf = HeaderFooter::new();
hf.set_header("&C&\"Calibri,Regular\"&K000000Regional report");
assert_eq!(hf.center_header.text.as_deref(), Some("Regional report"));
assert_eq!(hf.center_header.font_name, "Calibri,Regular");
assert_eq!(hf.center_header.font_color, "000000");
}
#[test]
fn three_glued_sections_are_all_found() {
let mut hf = HeaderFooter::new();
hf.set_header("&Lleft text&Cmiddle&Rright");
assert_eq!(hf.left_header.text.as_deref(), Some("left text"));
assert_eq!(hf.center_header.text.as_deref(), Some("middle"));
assert_eq!(hf.right_header.text.as_deref(), Some("right"));
}
#[test]
fn a_glued_footer_with_page_numbers_round_trips() {
let mut hf = HeaderFooter::new();
hf.set_footer("&RPage &P of &N");
assert_eq!(hf.right_footer.text.as_deref(), Some("Page &P of &N"));
assert!(hf.footer_string().contains("&P"));
assert!(hf.footer_string().contains("&N"));
}
#[test]
fn the_writers_own_output_reads_back() {
let rendered = HeaderFooterItem {
text: Some("Regional report".to_string()),
..HeaderFooterItem::new(HeaderFooterItem::CENTER)
}
.to_header_string();
let mut hf = HeaderFooter::new();
hf.set_header(&rendered);
assert_eq!(hf.center_header.text.as_deref(), Some("Regional report"));
let mut again = HeaderFooter::new();
again.set_header(&hf.header_string());
assert_eq!(again.center_header.text.as_deref(), Some("Regional report"));
assert!(again.has_header());
}
#[test]
fn long_forms_are_expanded_on_output() {
let mut item = HeaderFooterItem::new(HeaderFooterItem::RIGHT);
item.text = Some("Page &[Page] of &[Pages]".to_string());
let rendered = item.to_header_string();
assert!(rendered.contains("&P"));
assert!(rendered.contains("&N"));
assert!(!rendered.contains("&[Page]"));
}
#[test]
fn newlines_become_x000d() {
let mut item = HeaderFooterItem::new(HeaderFooterItem::CENTER);
item.text = Some("a\nb".to_string());
assert!(item.to_header_string().contains("_x000D_"));
}
#[test]
fn footer_uses_its_own_sections() {
let mut hf = HeaderFooter::new();
hf.set_footer("&L&only footer");
assert!(hf.has_footer());
assert!(!hf.has_header());
assert_eq!(hf.left_footer.text, Some("&only footer".to_string()));
assert!(hf.footer_string().contains("only footer"));
}
}