use super::{format_number, NumberFormat};
use crate::model::{
control::{AutoNumber, AutoNumberType, Control},
paragraph::Paragraph,
};
pub(crate) fn number_text(number: u16, format: u8, user_symbol: char) -> String {
if format == 0x81 {
if user_symbol == '\0' {
String::new()
} else {
user_symbol.to_string().repeat(usize::from(number))
}
} else {
format_number(number, NumberFormat::from_hwp_format(format))
}
}
pub(crate) fn page_number_display(number: &AutoNumber, value: u32) -> Option<String> {
let digits = if number.format == 0 {
value.to_string()
} else {
number_text(
u16::try_from(value).ok()?,
number.format,
number.user_symbol,
)
};
let mut text = String::new();
if number.prefix_char != '\0' {
text.push(number.prefix_char);
}
text.push_str(&digits);
if number.suffix_char != '\0' {
text.push(number.suffix_char);
}
Some(text)
}
pub(crate) fn supported_format(format: u8) -> bool {
format <= 16 || matches!(format, 0x80 | 0x81)
}
pub(crate) fn leading(
paragraphs: &[Paragraph],
kind: AutoNumberType,
) -> Option<(usize, &AutoNumber)> {
paragraphs.first().and_then(|paragraph| {
paragraph
.controls
.iter()
.enumerate()
.zip(paragraph.control_text_positions())
.find_map(|((index, control), position)| match control {
Control::AutoNumber(auto)
if position == 0
&& auto.number_type == kind
&& supported_format(auto.format) =>
{
Some((index, auto))
}
_ => None,
})
})
}
pub(crate) struct FormattedMarker {
pub text: String,
pub language_index: usize,
}
pub(crate) fn formatted(
paragraphs: &[Paragraph],
kind: AutoNumberType,
number: u16,
number_shape: u32,
before: u16,
after: u16,
) -> FormattedMarker {
let (number_text, prefix, suffix) = if let Some((_, auto)) = leading(paragraphs, kind) {
(
number_text(number, auto.format, auto.user_symbol),
auto.prefix_char,
auto.suffix_char,
)
} else {
(
number_text(number, number_shape as u8, '\0'),
char::from_u32(u32::from(before)).unwrap_or('\0'),
char::from_u32(u32::from(after))
.filter(|&c| c != '\0')
.unwrap_or(')'),
)
};
let language_index = number_text
.chars()
.next()
.map(super::style_resolver::detect_lang_category)
.unwrap_or(0);
let mut text = String::new();
if prefix != '\0' {
text.push(prefix);
}
text.push_str(&number_text);
if suffix != '\0' {
text.push(suffix);
}
FormattedMarker {
text,
language_index,
}
}
pub(crate) fn text(
paragraphs: &[Paragraph],
kind: AutoNumberType,
number: u16,
number_shape: u32,
before: u16,
after: u16,
) -> String {
formatted(paragraphs, kind, number, number_shape, before, after).text
}