diff --git a/src/rust_typeset.rs b/src/rust_typeset.rs index a7600f6..bbebc18 100644 --- a/src/rust_typeset.rs +++ b/src/rust_typeset.rs @@ -13,6 +13,7 @@ use genpdf::fonts; use texrra_core::math_list::{math_choice_variant, math_style_command}; use texrra_core::{MathClass, MathListContext, MathStyle, MathStyleCommand, math_expr::is_cjk}; mod box_font; +mod columns; mod document; mod engine; mod frontend; diff --git a/src/rust_typeset/columns.rs b/src/rust_typeset/columns.rs new file mode 100644 index 0000000..f0f5253 --- /dev/null +++ b/src/rust_typeset/columns.rs @@ -0,0 +1,83 @@ +//! Column/page cursor for two-column body layout. +//! +//! The cursor owns the vertical position inside a column and performs the +//! column-then-page transitions. It is intentionally independent of block +//! kinds so the page builder can share one transition rule for paragraphs, +//! lists, equations, and tables. + +#![allow(dead_code)] + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ColumnCursor { + pub page: usize, + pub column: usize, + pub y: i64, + pub columns: usize, + pub column_top: i64, + pub page_goal: i64, +} + +impl ColumnCursor { + pub(crate) fn new(columns: usize, column_top: i64, page_goal: i64) -> Self { + Self { + page: 0, + column: 0, + y: column_top, + columns: columns.max(1), + column_top, + page_goal, + } + } + + /// Returns true when the height no longer fits and the cursor moved to the + /// next column or page. The caller is responsible for starting a new page + /// when reports true. + pub(crate) fn advance(&mut self, height: i64) -> bool { + if self.y.saturating_add(height) <= self.page_goal { + self.y = self.y.saturating_add(height); + return false; + } + if self.column + 1 < self.columns { + self.column += 1; + self.y = self.column_top; + } else { + self.page += 1; + self.column = 0; + self.y = self.column_top; + } + true + } + + pub(crate) fn moved_to_page(&self, previous_page: usize) -> bool { + self.page != previous_page + } +} + +#[cfg(test)] +mod tests { + use super::ColumnCursor; + + #[test] + fn advance_keeps_the_cursor_in_the_current_column_while_it_fits() { + let mut cursor = ColumnCursor::new(2, 25, 100); + assert!(!cursor.advance(40)); + assert_eq!((cursor.page, cursor.column, cursor.y), (0, 0, 65)); + } + + #[test] + fn advance_switches_to_the_second_column_on_overflow() { + let mut cursor = ColumnCursor::new(2, 25, 100); + assert!(!cursor.advance(60)); + assert!(cursor.advance(20)); + assert_eq!((cursor.page, cursor.column, cursor.y), (0, 1, 25)); + } + + #[test] + fn advance_starts_a_new_page_after_the_last_column() { + let mut cursor = ColumnCursor::new(2, 25, 100); + assert!(!cursor.advance(50)); + assert!(cursor.advance(60)); + assert!(cursor.advance(80)); + assert_eq!((cursor.page, cursor.column, cursor.y), (1, 0, 25)); + } +}