1use std::{
3 collections::VecDeque,
4 fmt::{self, Debug, Display},
5};
6
7use rustc_hash::FxHashMap as HashMap;
8
9use super::cell::Cell;
10use crate::{Digested, common::dimension::Dimension, state::Stored, token::Token, tokens::Tokens};
11
12pub type Row = Template;
14#[derive(Debug, Clone, Default, PartialEq)]
15pub enum Align {
16 #[default]
17 Left,
18 Center,
19 Right,
20 Justify,
21 Char(String),
23}
24impl Align {
25 pub fn char_code(&self) -> char {
26 match self {
27 Align::Right => 'r',
28 Align::Left => 'l',
29 Align::Center => 'c',
30 Align::Justify => 'p',
31 Align::Char(_) => 'c', }
33 }
34 pub fn name(&self) -> String {
35 match self {
36 Align::Right => "right".to_string(),
37 Align::Left => "left".to_string(),
38 Align::Center => "center".to_string(),
39 Align::Justify => "justify".to_string(),
40 Align::Char(ch) => format!("char:{ch}"),
41 }
42 }
43}
44impl From<char> for Align {
45 fn from(c: char) -> Align {
46 match c {
47 'l' => Align::Left,
48 'r' => Align::Right,
49 'c' => Align::Center,
50 'p' => Align::Justify,
51 _ => Align::default(), }
53 }
54}
55
56#[derive(Debug, Copy, Clone, PartialEq)]
58pub enum Axis {
59 Column,
60 Row,
61}
62impl Axis {
63 pub fn name(&self) -> &'static str {
65 match self {
66 Axis::Column => "column",
67 Axis::Row => "row",
68 }
69 }
70 pub fn marker_name(&self) -> &'static str {
72 match self {
73 Axis::Column => "row",
74 Axis::Row => "column",
75 }
76 }
77}
78
79#[derive(Debug, Copy, Clone, PartialEq)]
80pub enum ColumnSpec {
81 Integer, Empty, Unknown, Text, MultiText, Math, MathAltText, D, Graphics, }
92impl ColumnSpec {
93 pub fn difference_heuristic(&self, other: &ColumnSpec) -> f64 {
95 use ColumnSpec::*;
96 match self {
97 Empty => match other {
98 Empty => 0.0,
99 Math => 0.05,
100 Integer => 0.05,
101 Text => 0.05,
102 Unknown => 0.05,
103 MathAltText => 0.05,
104 _ => 0.75,
105 },
106 Math => match other {
107 Empty => 0.05,
108 Math => 0.0,
109 Integer => 0.1,
110 MathAltText => 0.2,
111 _ => 0.75,
112 },
113 Integer => match other {
114 Empty => 0.05,
115 Math => 0.1,
116 Integer => 0.0,
117 MathAltText => 0.2,
118 _ => 0.75,
119 },
120 Text => match other {
121 Empty => 0.05,
122 Text => 0.0,
123 MathAltText => 0.2,
124 _ => 0.75, },
126 MultiText => match other {
127 Empty => 0.05,
128 MultiText => 0.0,
129 MathAltText => 0.2,
130 _ => 0.75, },
132 Unknown => match other {
133 Empty => 0.05,
134 Unknown => 0.0,
135 MathAltText => 0.2,
136 _ => 0.75,
137 },
138 MathAltText => match other {
139 Empty => 0.05,
140 Math => 0.2,
141 Integer => 0.2,
142 Text => 0.2,
143 Unknown => 0.2,
144 MathAltText => 0.0,
145 _ => 0.75,
146 },
147 D => match other {
148 D => 0.0,
149 _ => 0.75,
150 },
151 Graphics => match other {
152 Graphics => 0.0,
153 _ => 0.75,
154 },
155 }
156 }
157}
158impl Display for ColumnSpec {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 match self {
161 ColumnSpec::Integer => write!(f, "i"),
162 ColumnSpec::Empty => write!(f, "_"),
163 ColumnSpec::Unknown => write!(f, "?"),
164 ColumnSpec::Text => write!(f, "t"),
165 ColumnSpec::MultiText => write!(f, "tt"),
166 ColumnSpec::Math => write!(f, "m"),
167 ColumnSpec::MathAltText => write!(f, "mx"),
168 ColumnSpec::D => write!(f, "d"),
169 ColumnSpec::Graphics => write!(f, "g"),
170 }
171 }
172}
173
174#[derive(Debug, Copy, Clone, PartialEq)]
175pub enum BorderSpec {
176 Top,
177 Bottom,
178 Left,
179 Right,
180}
181impl BorderSpec {
182 pub fn of_letter(c: char) -> Option<BorderSpec> {
184 match c {
185 't' | 'T' => Some(BorderSpec::Top),
186 'b' | 'B' => Some(BorderSpec::Bottom),
187 'l' | 'L' => Some(BorderSpec::Left),
188 'r' | 'R' => Some(BorderSpec::Right),
189 _ => None,
190 }
191 }
192}
193
194#[derive(Debug, Clone, Default)]
195pub struct TemplateConfig {
196 pub repeating: Option<bool>,
197 pub pseudorow: Option<bool>,
198 pub non_repeating: usize,
199 pub repeated: Vec<Cell>,
200 pub reversion: Option<Tokens>,
201 pub columns: Option<Vec<Cell>>,
202 pub tokens: Option<Vec<Token>>,
203 pub save_before: Option<VecDeque<Token>>,
204 pub save_between: Option<VecDeque<Token>>,
205}
206
207#[derive(Debug, Clone, Default, PartialEq)]
208pub struct Template {
209 repeating: bool,
210 pseudorow: bool,
211 non_repeating: usize,
212 repeated: Vec<Cell>,
213 reversion: Option<Tokens>,
214 columns: Vec<Cell>,
215 pub tokens: Vec<Token>,
216 padding: Option<Dimension>,
217 pub top_padding: Option<Dimension>,
218 pub bottom_padding: Option<Dimension>,
219 pub before: VecDeque<Digested>,
220 pub after: VecDeque<Digested>,
221 save_before: VecDeque<Token>,
222 save_between: VecDeque<Token>,
223 disabled_intercolumn: bool,
224 pub cached_width: Option<Dimension>,
225 pub cached_height: Option<Dimension>,
226 pub cached_depth: Option<Dimension>,
227 pub x: Option<Dimension>,
228 pub y: Option<Dimension>,
229 pub properties: HashMap<String, Stored>,
233}
234
235impl Display for Template {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Alignment[]",) }
237}
238impl Template {
239 pub fn new(config: TemplateConfig) -> Self {
240 let repeating = config.repeating.unwrap_or(false) || !config.repeated.is_empty();
241 let pseudorow = config.pseudorow.unwrap_or(false);
242 let mut columns = config.columns.unwrap_or_default();
243 let mut repeated = config.repeated;
244 let non_repeating = columns.len();
245 let save_before = config.save_before.unwrap_or_default();
246 let save_between = config.save_between.unwrap_or_default(); for column in columns.iter_mut() {
248 column.empty = true;
249 }
250 for v in repeated.iter_mut() {
251 v.empty = true;
252 }
253
254 Template {
255 columns,
256 pseudorow,
257 repeating,
258 repeated,
259 non_repeating,
260 save_before,
261 save_between,
262 disabled_intercolumn: false,
263 before: VecDeque::new(),
264 after: VecDeque::new(),
265 padding: None,
266 top_padding: None,
267 bottom_padding: None,
268 cached_width: None,
269 cached_height: None,
270 cached_depth: None,
271 x: None,
272 y: None,
273 reversion: config.reversion,
274 tokens: config.tokens.unwrap_or_default(),
275 properties: rustc_hash::FxHashMap::default(),
276 }
277 }
278 pub fn set_reversion(&mut self, tks: Tokens) { self.reversion = Some(tks); }
279 pub fn set_repeating(&mut self) { self.repeating = true; }
280 pub fn repeat_past_columns(&mut self, cell: Cell) {
283 self.repeating = true;
284 self.non_repeating = self.columns.len();
285 self.repeated = vec![Cell { empty: true, ..cell }];
286 }
287 pub fn set_padding(&mut self, d: Dimension) { self.padding = Some(d); }
288 pub fn get_padding(&self) -> Option<&Dimension> { self.padding.as_ref() }
289
290 pub fn disable_intercolumn(&mut self) {
294 if !self.columns.is_empty() || !self.repeated.is_empty() {
295 self.disabled_intercolumn = true;
296 }
297 }
298
299 pub fn finish(&mut self) {
302 let last = if self.repeating {
303 self.repeated.last_mut()
304 } else {
305 self.columns.last_mut()
306 };
307 if let Some(prev) = last
308 && !self.disabled_intercolumn
309 {
310 let mut after = prev.after.take().unwrap_or_default().unlist();
314 after.push(T_CS!("\\lx@intercol"));
315 prev.after = Some(Tokens::new(after));
316 prev.has_intercol_after = true;
317 }
318 }
319
320 pub fn has_pending_prefix(&self) -> bool { !self.save_before.is_empty() }
323
324 pub fn add_before_column(&mut self, mut new: VecDeque<Token>) {
326 let current_sb = self.save_before.drain(..);
327 new.extend(current_sb);
328 self.save_before = new; }
330 pub fn add_after_column(&mut self, new: Vec<Token>) {
333 if let Some(current_column) = self.columns.last_mut() {
334 let current_after = current_column.after.take().unwrap_or_default().unlist();
335 let own = current_column.suffix_at.unwrap_or(0);
336 current_column.suffix_at = Some(1 + new.len() + own);
337 current_column.after = Some(Tokens!(T_CS!("\\lx@column@trimright"), new, current_after));
338 }
339 }
340
341 pub fn add_between_column(&mut self, tokens: Vec<Token>) {
343 if let Some(current_column) = self.columns.last_mut() {
344 let mut combined = Vec::new();
345 let current_after = current_column.after.take().unwrap_or_default().unlist();
346 combined.extend(current_after);
347 if !self.disabled_intercolumn {
349 combined.push(T_CS!("\\lx@intercol"));
350 }
351 combined.extend(tokens);
352 current_column.after = Some(Tokens::new(combined));
353 } else {
354 self.save_between.extend(tokens);
355 }
356 }
357
358 pub fn add_column(&mut self, mut col: Cell) {
360 if let Some(prev) = if self.repeating {
362 self.repeated.last_mut()
363 } else {
364 self.columns.last_mut()
365 } && !self.disabled_intercolumn
366 {
367 let mut after = prev.after.take().unwrap_or_default().unlist();
368 after.push(T_CS!("\\lx@intercol"));
369 prev.after = Some(Tokens::new(after));
370 prev.has_intercol_after = true;
371 }
372 let mut before = Vec::new();
374 if !self.save_between.is_empty() {
375 before.extend(self.save_between.clone());
376 }
377 let has_intercol_before = !self.disabled_intercolumn;
379 if has_intercol_before {
380 before.push(T_CS!("\\lx@intercol"));
381 }
382 self.disabled_intercolumn = false;
384
385 if let Some(prop_before) = col.before {
386 before.extend(prop_before.unlist());
387 }
388 let prefix_at = before.len();
389 if !self.save_before.is_empty() {
390 before.extend(self.save_before.clone());
391 before.push(T_CS!("\\ignorespaces"));
395 }
396 col.before = if !before.is_empty() {
397 Some(Tokens::new(before))
398 } else {
399 None
400 };
401 col.prefix_at = Some(prefix_at);
402 col.has_intercol_before = has_intercol_before;
403 let mut after = vec![T_CS!("\\lx@column@trimright")];
404 if let Some(prop_after) = col.after {
405 after.extend(prop_after.unlist());
406 }
407 col.suffix_at = Some(1);
409 col.after = if after.is_empty() {
410 None
411 } else {
412 Some(Tokens::new(after))
413 };
414 col.empty = true;
415 self.save_between = VecDeque::new();
416 self.save_before = VecDeque::new();
417
418 if self.repeating {
419 self.non_repeating = self.columns.len();
420 self.repeated.push(col);
421 } else {
422 self.columns.push(col);
423 }
424 }
425
426 pub fn get_column_mut(&mut self, n: usize) -> Option<&mut Cell> {
427 let all_columns = self.columns.len();
428 if (n > all_columns) && self.repeating {
429 let rep = &self.repeated;
430 let m = rep.len();
431 if m > 0 {
432 for i in all_columns..n {
433 let dup = rep[(i - self.non_repeating) % m].clone();
434 self.columns.push(dup);
435 }
436 }
437 }
438 if n > 0 {
439 self.columns.get_mut(n - 1)
440 } else {
441 None
442 }
443 }
444
445 pub fn get_columns(&self) -> &[Cell] { &self.columns }
446 pub fn get_columns_mut(&mut self) -> &mut Vec<Cell> { &mut self.columns }
447 pub fn get_repeated_mut(&mut self) -> &mut Vec<Cell> { &mut self.repeated }
448 pub fn set_pseudo(&mut self) { self.pseudorow = true; }
449 pub fn unset_pseudo(&mut self) { self.pseudorow = false; }
450 pub fn is_pseudo(&self) -> bool { self.pseudorow }
451
452 pub fn has_explicit_tags(&self) -> bool {
458 self.properties.contains_key("tags")
459 && matches!(self.properties.get("reset"), Some(Stored::Bool(true)))
460 }
461}
462
463pub const TAGGED_ROW_ATTRIBUTE: &str = "_tagged";
467
468pub const NUMBER_ROW_PROPERTY: &str = "_number_row";
473
474#[cfg(test)]
475mod tests {
476 use super::*;
477
478 #[test]
479 fn align_default_is_left() {
480 assert_eq!(Align::default(), Align::Left);
481 }
482
483 #[test]
484 fn align_char_code() {
485 assert_eq!(Align::Left.char_code(), 'l');
486 assert_eq!(Align::Right.char_code(), 'r');
487 assert_eq!(Align::Center.char_code(), 'c');
488 assert_eq!(Align::Justify.char_code(), 'p');
489 assert_eq!(Align::Char(".".to_string()).char_code(), 'c');
491 }
492
493 #[test]
494 fn align_name() {
495 assert_eq!(Align::Left.name(), "left");
496 assert_eq!(Align::Right.name(), "right");
497 assert_eq!(Align::Center.name(), "center");
498 assert_eq!(Align::Justify.name(), "justify");
499 assert_eq!(Align::Char(".".to_string()).name(), "char:.");
500 }
501
502 #[test]
503 fn align_from_char_basic() {
504 assert_eq!(Align::from('l'), Align::Left);
505 assert_eq!(Align::from('r'), Align::Right);
506 assert_eq!(Align::from('c'), Align::Center);
507 assert_eq!(Align::from('p'), Align::Justify);
508 }
509
510 #[test]
511 fn align_from_char_unknown_is_default() {
512 assert_eq!(Align::from('x'), Align::Left);
514 assert_eq!(Align::from('?'), Align::Left);
515 }
516
517 #[test]
518 fn axis_name() {
519 assert_eq!(Axis::Column.name(), "column");
520 assert_eq!(Axis::Row.name(), "row");
521 }
522
523 #[test]
524 fn axis_marker_name_is_inverse() {
525 assert_eq!(Axis::Column.marker_name(), "row");
529 assert_eq!(Axis::Row.marker_name(), "column");
530 }
531
532 #[test]
533 fn column_spec_display_chars() {
534 assert_eq!(format!("{}", ColumnSpec::Integer), "i");
535 assert_eq!(format!("{}", ColumnSpec::Empty), "_");
536 assert_eq!(format!("{}", ColumnSpec::Unknown), "?");
537 assert_eq!(format!("{}", ColumnSpec::Text), "t");
538 assert_eq!(format!("{}", ColumnSpec::MultiText), "tt");
539 assert_eq!(format!("{}", ColumnSpec::Math), "m");
540 assert_eq!(format!("{}", ColumnSpec::MathAltText), "mx");
541 assert_eq!(format!("{}", ColumnSpec::D), "d");
542 assert_eq!(format!("{}", ColumnSpec::Graphics), "g");
543 }
544
545 #[test]
546 fn column_spec_difference_heuristic_self_is_zero() {
547 assert_eq!(
549 ColumnSpec::Empty.difference_heuristic(&ColumnSpec::Empty),
550 0.0
551 );
552 assert_eq!(
553 ColumnSpec::Math.difference_heuristic(&ColumnSpec::Math),
554 0.0
555 );
556 assert_eq!(
557 ColumnSpec::Integer.difference_heuristic(&ColumnSpec::Integer),
558 0.0
559 );
560 assert_eq!(
561 ColumnSpec::Text.difference_heuristic(&ColumnSpec::Text),
562 0.0
563 );
564 assert_eq!(ColumnSpec::D.difference_heuristic(&ColumnSpec::D), 0.0);
565 assert_eq!(
566 ColumnSpec::Graphics.difference_heuristic(&ColumnSpec::Graphics),
567 0.0
568 );
569 }
570
571 #[test]
572 fn column_spec_difference_heuristic_incompatible_is_large() {
573 assert_eq!(
575 ColumnSpec::Graphics.difference_heuristic(&ColumnSpec::Math),
576 0.75
577 );
578 assert_eq!(ColumnSpec::D.difference_heuristic(&ColumnSpec::Text), 0.75);
579 }
580}