use crate::document::{CounterSnapshot, PageBox, PageStart};
use crate::dom::ElementId;
use crate::style::{
AutomaticInitial, CounterProperties, CounterRequest, FOOTNOTE_COUNTER, INITIAL_COUNTER_VALUE,
MarginLocation, PAGE_COUNTER, PAGES_COUNTER, StyleError,
};
use std::sync::Arc;
pub(super) struct PageCounters {
pages: Vec<PageValues>,
}
struct PageValues {
context: CounterSnapshot,
margins: Vec<(MarginLocation, CounterSnapshot)>,
}
impl PageCounters {
pub(super) fn new(page_boxes: &[Arc<PageBox>]) -> Self {
let contexts: Vec<_> = page_boxes
.iter()
.map(|page| page.counters.with_implicit_increment(PAGE_COUNTER))
.collect();
let mut pages: Vec<_> = sequence(
&contexts,
vec![(Arc::from(PAGE_COUNTER), INITIAL_COUNTER_VALUE)],
)
.into_iter()
.map(|context| PageValues {
context,
margins: Vec::new(),
})
.collect();
for location in MarginLocation::ALL {
let (indices, contexts): (Vec<usize>, Vec<CounterProperties>) = page_boxes
.iter()
.enumerate()
.filter_map(|(index, page)| {
page.margins
.iter()
.find(|margin| margin.margin.location == location)
.map(|margin| (index, margin.margin.style.counters.clone()))
})
.unzip();
if contexts.iter().all(CounterProperties::is_empty) {
continue;
}
for (index, values) in indices.into_iter().zip(sequence(&contexts, Vec::new())) {
pages[index].margins.push((location, values));
}
}
Self { pages }
}
pub(super) fn page(&self, page: usize, location: Option<MarginLocation>) -> i128 {
let values = &self.pages[page];
location
.and_then(|location| values.margin(location))
.and_then(|margin| margin.value(PAGE_COUNTER))
.or_else(|| values.context.value(PAGE_COUNTER))
.expect("the page context instantiates the page counter")
}
pub(super) fn text(
&self,
page: usize,
location: MarginLocation,
request: &CounterRequest,
document: &CounterSnapshot,
) -> Result<crate::style::Representation, StyleError> {
let values = &self.pages[page];
let name = request.name.as_ref();
values
.page_context(location, name)
.unwrap_or(document)
.text(request)
}
pub(super) fn starts(
&self,
page_boxes: &[Arc<PageBox>],
elements: Vec<Option<(ElementId, bool)>>,
) -> Vec<(ElementId, PageStart)> {
let footnotes: Vec<_> = page_boxes
.iter()
.map(|page| page.counters.named(FOOTNOTE_COUNTER))
.collect();
let margins_read_document = page_boxes.iter().enumerate().any(|(page, page_box)| {
page_box.margins.iter().any(|margin| {
margin.margin.content.counter_requests().any(|request| {
self.pages[page]
.page_context(margin.margin.location, &request.name)
.is_none()
})
})
});
if !margins_read_document && footnotes.iter().all(CounterProperties::is_empty) {
return Vec::new();
}
elements
.into_iter()
.zip(footnotes)
.enumerate()
.filter_map(|(page, (element, footnote))| {
let (element, inside) = element?;
Some((
element,
PageStart {
page,
inside,
footnote,
automatic: Vec::new(),
},
))
})
.collect()
}
}
impl PageValues {
fn margin(&self, location: MarginLocation) -> Option<&CounterSnapshot> {
self.margins
.iter()
.find(|(margin, _)| *margin == location)
.map(|(_, values)| values)
}
fn page_context(&self, location: MarginLocation, name: &str) -> Option<&CounterSnapshot> {
self.margin(location)
.filter(|margin| margin.value(name).is_some())
.or_else(|| self.context.value(name).is_some().then_some(&self.context))
}
}
fn sequence(
contexts: &[CounterProperties],
mut counters: Vec<(Arc<str>, i128)>,
) -> Vec<CounterSnapshot> {
let counted = |name: &Arc<str>| name.as_ref() != PAGES_COUNTER;
contexts
.iter()
.enumerate()
.map(|(index, properties)| {
for reset in properties.reset.iter().filter(|reset| counted(&reset.name)) {
let value = reset
.value
.unwrap_or_else(|| automatic(&contexts[index..], &reset.name));
*counter(&mut counters, &reset.name) = value;
}
for change in properties
.increment
.iter()
.filter(|change| counted(&change.name))
{
let value = counter(&mut counters, &change.name);
*value = value.saturating_add(change.value);
}
for change in properties.set.iter().filter(|change| counted(&change.name)) {
*counter(&mut counters, &change.name) = change.value;
}
CounterSnapshot::new(counters.clone())
})
.collect()
}
fn counter<'c>(counters: &'c mut Vec<(Arc<str>, i128)>, name: &Arc<str>) -> &'c mut i128 {
let index = counters
.iter()
.position(|(counter, _)| counter == name)
.unwrap_or_else(|| {
counters.push((name.clone(), INITIAL_COUNTER_VALUE));
counters.len() - 1
});
&mut counters[index].1
}
fn automatic(contexts: &[CounterProperties], name: &str) -> i128 {
let mut initial = AutomaticInitial::default();
for (index, properties) in contexts.iter().enumerate() {
if index > 0
&& properties
.reset
.iter()
.any(|reset| reset.name.as_ref() == name)
{
break;
}
let increment = properties
.increment
.iter()
.filter(|change| change.name.as_ref() == name)
.fold(INITIAL_COUNTER_VALUE, |sum, change| {
sum.saturating_add(change.value)
});
let set = properties
.set
.iter()
.rev()
.find(|change| change.name.as_ref() == name)
.map(|change| change.value);
initial.update(increment, set);
}
initial.value()
}