use crate::pdf::core::ContentStream;
use crate::page_layout::PageLayout;
pub struct LayoutState {
pub layout: PageLayout,
pub current_y: f32,
pub pages: Vec<ContentStream>,
pub current_font_size: f32,
pub centering: bool,
pub raggedleft: bool,
pub noindent: bool,
pub current_page_footnotes: Vec<(usize, String)>,
pub all_footnotes: Vec<Vec<(usize, String)>>,
}
impl LayoutState {
pub fn new(layout: PageLayout) -> Self {
Self::with_encoding(layout, true)
}
pub fn with_encoding(layout: PageLayout, embedded_unicode: bool) -> Self {
Self {
layout,
current_y: layout.content_top(),
pages: vec![ContentStream::with_encoding(embedded_unicode)],
current_font_size: 11.0,
centering: false,
raggedleft: false,
noindent: false,
current_page_footnotes: Vec::new(),
all_footnotes: Vec::new(),
}
}
pub fn current_stream(&mut self) -> &mut ContentStream {
self.pages.last_mut().unwrap()
}
pub fn left_margin(&self) -> f32 {
self.layout.margin_left
}
pub fn content_width(&self) -> f32 {
self.layout.content_width()
}
pub fn content_bottom(&self) -> f32 {
self.layout.margin_bottom
}
pub fn content_top(&self) -> f32 {
self.layout.content_top()
}
pub fn line_height(&self, font_size: f32) -> f32 {
font_size + 4.0
}
pub fn available_height(&self) -> f32 {
self.current_y - self.content_bottom()
}
pub fn would_fit(&self, height: f32) -> bool {
height <= self.available_height()
}
pub fn advance(&mut self, height: f32) {
self.current_y -= height;
}
pub fn new_page(&mut self) {
let embedded = self.pages.last().map(|p| p.embedded_unicode()).unwrap_or(true);
self.all_footnotes.push(std::mem::take(&mut self.current_page_footnotes));
self.pages.push(ContentStream::with_encoding(embedded));
self.current_y = self.content_top();
}
pub fn ensure_space(&mut self, required_height: f32) {
if !self.would_fit(required_height) {
self.new_page();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_layout_state_initial() {
let layout = PageLayout::a4_portrait();
let state = LayoutState::new(layout);
assert_eq!(state.pages.len(), 1);
assert_eq!(state.current_y, layout.content_top());
assert!(state.would_fit(layout.content_height()));
}
#[test]
fn test_new_page() {
let layout = PageLayout::a4_portrait();
let mut state = LayoutState::new(layout);
state.new_page();
assert_eq!(state.pages.len(), 2);
assert_eq!(state.current_y, layout.content_top());
}
#[test]
fn test_ensure_space() {
let layout = PageLayout::a4_portrait();
let mut state = LayoutState::new(layout);
state.current_y = state.content_bottom() + 10.0;
state.ensure_space(20.0); assert_eq!(state.pages.len(), 2);
assert_eq!(state.current_y, layout.content_top());
}
}