use std::collections::{BTreeMap, BTreeSet};
use super::contents::{any_content, visit_contents_mut};
use super::field_code::{
self, ADVANCE_LEFT, ADVANCE_RIGHT, CHAR_FORMAT, FORM_DROP_DOWN, FORM_TEXT, FORMAT,
MERGE_FORMAT, PAGE_POSITION, PICTURE, REF_FULL, REF_LINK, REF_PATTERN, REF_RELATIVE,
STYLE_LAST, STYLE_NUMBER,
};
use super::links::{Hyperlink, LinkMark};
use super::{
Block, CodePart, CodeRun, Content, DateField, DocProperty, FileNameField, IfField, NumberRef,
PageRef, Run, StyleRef, TextCase, paragraphs_mut,
};
use crate::params::{MAX_FIELD_DEPTH, TEXT_BUFFER_MARK_LENGTH};
use crate::props::CodeFormat;
use crate::reader::PartReader;
use crate::warnings::Limit;
use f_office_units::Length;
#[cfg(test)]
mod tests;
fn computed_field(code: &str, saved: Option<&str>) -> Option<Content> {
let date = |default: &str| {
Content::Date(Box::new(DateField {
picture: picture_switch(code).unwrap_or_else(|| default.to_owned()),
stored: String::new(),
}))
};
match field_code::kind(code)?.to_ascii_uppercase().as_str() {
"PAGE" => Some(Content::PageNumber),
"NUMPAGES" => Some(Content::PageCount),
"DATE" => Some(date(crate::dates::DATE_PICTURE)),
"TIME" => Some(date(crate::dates::TIME_PICTURE)),
"SAVEDATE" | "PRINTDATE" => match picture_switch(code) {
Some(_) => Some(date(crate::dates::DATE_PICTURE)),
None => saved.map(date),
},
"DOCPROPERTY" => property_name(code).map(|name| {
Content::DocProperty(Box::new(DocProperty {
name,
picture: picture_switch(code),
stored: String::new(),
}))
}),
"FILENAME" => file_name_case(code).map(|case| {
Content::FileName(Box::new(FileNameField {
case,
stored: String::new(),
}))
}),
"STYLEREF" => style_ref(code).map(|s| Content::StyleRef(Box::new(s))),
"PAGEREF" => page_ref(code).map(|p| Content::PageRef(Box::new(p))),
"REF" => number_ref(code).map(|field| Content::NumberRef(Box::new(field))),
"IF" => Some(Content::If(Box::new(IfField {
parts: Vec::new(),
stored: String::new(),
}))),
"ADVANCE" => advance(code).map(Content::Advance),
_ => None,
}
}
fn advance(code: &str) -> Option<Length> {
let mut words = field_code::words_after_kind(code);
let mut by = Length::ZERO;
let mut any = false;
while let Some(word) = words.next() {
let sign = if ADVANCE_RIGHT.is(word) {
1
} else if ADVANCE_LEFT.is(word) {
-1
} else {
return None;
};
let thousandths = f_office_units::measure::decimal_thousandths(words.next()?)?;
let units = f_office_units::checked_div_round(
thousandths.checked_mul(sign * Length::UNITS_PER_POINT)?,
f_office_units::scale::THOUSANDTHS,
)?;
by = by.checked_add(Length::from_units(units))?;
any = true;
}
any.then_some(by)
}
fn number_ref(code: &str) -> Option<NumberRef> {
use crate::numbering::ReferenceKind;
let kinds = [
(REF_PATTERN, ReferenceKind::Pattern),
(REF_RELATIVE, ReferenceKind::Relative),
(REF_FULL, ReferenceKind::Full),
];
let mut words = field_code::words_after_kind(code);
let bookmark = field_code::word_argument(words.next()?);
if bookmark.is_empty() || bookmark.starts_with('\\') {
return None;
}
let mut kind = None;
while let Some(word) = words.next() {
if let Some((_, of)) = kinds.iter().find(|(switch, _)| switch.is(word)) {
kind = Some(*of);
continue;
}
let keeps_number = REF_LINK.is(word)
|| (FORMAT.is(word)
&& words
.next()
.is_some_and(|format| field_code::is_format(format, &[MERGE_FORMAT])));
if !keeps_number {
return None;
}
}
Some(NumberRef {
bookmark: bookmark.to_owned(),
kind,
stored: String::new(),
code: None,
})
}
fn file_name_case(code: &str) -> Option<TextCase> {
let mut case = TextCase::AsIs;
let mut words = field_code::words_after_kind(code);
while let Some(word) = words.next() {
if !FORMAT.is(word) {
return None;
}
let format = words.next().unwrap_or_default();
if let Some(named) = TextCase::of(format) {
case = named;
} else if !field_code::is_format(format, &[CHAR_FORMAT, MERGE_FORMAT]) {
return None;
}
}
Some(case)
}
fn property_name(code: &str) -> Option<String> {
let name = field_code::quoted_argument(field_code::after_kind(code)).text;
(!name.is_empty() && !name.starts_with('\\')).then(|| name.to_owned())
}
fn page_ref(code: &str) -> Option<PageRef> {
let mut words = field_code::words_after_kind(code);
let bookmark = field_code::word_argument(words.next()?);
if bookmark.is_empty() || bookmark.starts_with('\\') {
return None;
}
if words.any(|word| PAGE_POSITION.is(word)) {
return None;
}
Some(PageRef {
bookmark: bookmark.to_owned(),
stored: String::new(),
code: None,
})
}
fn style_ref(code: &str) -> Option<StyleRef> {
let argument = field_code::quoted_argument(field_code::after_kind(code));
let (style, switches) = (argument.text, argument.rest);
if argument.unclosed || style.is_empty() {
return None;
}
let (mut last, mut number) = (false, false);
let mut switches = switches.split_whitespace();
while let Some(switch) = switches.next() {
if STYLE_LAST.is(switch) {
last = true;
} else if STYLE_NUMBER.is(switch) {
number = true;
} else if FORMAT.is(switch) {
let format = switches.next().unwrap_or_default();
if !field_code::is_format(format, &[CHAR_FORMAT, MERGE_FORMAT]) {
return None;
}
} else {
return None;
}
}
Some(StyleRef {
style: style.to_owned(),
last,
number,
stored: String::new(),
})
}
pub(super) fn picture_switch(code: &str) -> Option<String> {
PICTURE.after_first(code).map(field_code::escaped_argument)
}
#[must_use]
pub fn refers_to_pages(blocks: &[Block]) -> bool {
any_content(blocks, &mut |content| {
matches!(
content,
Content::PageCount | Content::PageRef(_) | Content::NumberRef(_)
)
})
}
#[must_use]
pub fn refers_to_pages_and_numbers(blocks: &[Block]) -> bool {
let (mut pages, mut numbers) = (false, false);
any_content(blocks, &mut |content| {
pages |= matches!(content, Content::PageRef(_));
numbers |= matches!(content, Content::NumberRef(_));
pages && numbers
})
}
#[must_use]
pub fn refers_to_styles(blocks: &[Block]) -> bool {
any_content(blocks, &mut |content| {
matches!(content, Content::StyleRef(_))
})
}
pub(super) fn keep_stored_properties(blocks: &mut [Block]) {
for run in paragraphs_mut(blocks)
.into_iter()
.flat_map(|paragraph| paragraph.runs.iter_mut())
{
let stored: usize = run
.content
.iter()
.map(|content| match content {
Content::DocProperty(property) => property.stored.encode_utf16().count(),
_ => 0,
})
.sum();
run.buffer_only.characters = run.buffer_only.characters.saturating_sub(stored);
}
visit_contents_mut(blocks, &mut |content| {
if let Content::DocProperty(property) = content {
let stored = std::mem::take(&mut property.stored);
*content = Content::Text(stored);
}
});
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Updates {
#[default]
Computed,
References,
Live,
LiveNumbers,
WithoutResult,
PageFields,
}
impl Updates {
fn result_direction(self, value: &Content, code_rtl: Option<bool>) -> Option<bool> {
if !matches!(value, Content::PageNumber | Content::PageCount) {
return None;
}
match self {
Self::Live | Self::LiveNumbers | Self::PageFields => Some(true),
Self::Computed | Self::References | Self::WithoutResult => code_rtl,
}
}
const fn updates_file_name(self) -> bool {
matches!(self, Self::Live | Self::LiveNumbers)
}
fn updates(self, value: &Content, stored: bool) -> bool {
if matches!(value, Content::NumberRef(_)) {
return self == Self::References;
}
if matches!(value, Content::StyleRef(field) if field.number) {
return self == Self::LiveNumbers;
}
let field_if = matches!(value, Content::If(_));
match self {
Self::Live | Self::LiveNumbers => true,
Self::Computed | Self::References => !field_if,
Self::WithoutResult => !stored && !field_if,
Self::PageFields => {
let on_page = matches!(
value,
Content::PageNumber
| Content::PageCount
| Content::PageRef(_)
| Content::StyleRef(_)
);
on_page || field_if || !stored
}
}
}
}
pub(super) fn resolve_fields(reader: &mut PartReader, blocks: &mut [Block], updates: Updates) {
let mut bookmarks = BTreeSet::new();
any_content(blocks, &mut |content| {
if let Content::Bookmark(name) = content {
bookmarks.insert(name.clone());
}
false
});
let mut paragraphs = paragraphs_mut(blocks);
let mut fields = Fields {
stored: stored_results(paragraphs.iter().flat_map(|p| &p.runs)),
bookmarks,
updates,
saved_date: reader.saved_date_picture(),
..Fields::default()
};
for (index, run) in paragraphs
.iter_mut()
.flat_map(|p| p.runs.iter_mut())
.enumerate()
{
fields.run = index;
let content = std::mem::take(&mut run.content);
let simple = content
.iter()
.any(|item| matches!(item, Content::FieldCode(_)))
&& content
.iter()
.any(|item| matches!(item, Content::FieldSeparate));
fields.run_rtl = (!simple).then(|| run.props.rtl.unwrap_or(false));
fields.result_rtl = None;
let codes = content
.iter()
.any(|item| matches!(item, Content::FieldCode(_)));
fields.run_code = (!simple && codes).then(|| CodeRun {
style: run.style.clone(),
props: run.props.clone(),
});
fields.result_format = None;
run.buffer_only.characters += crate::buffers::field_characters(&content);
let before = fields.open_marks();
for item in content {
fields.push(item, &mut run.content);
}
run.links.append(&mut fields.links);
let after = fields.open_marks();
run.buffer_only.open += after;
run.buffer_only.held += before.min(after);
run.buffer_only.characters += std::mem::take(&mut fields.stored_characters);
if fields.result_rtl.is_some() {
run.props.field_rtl = fields.result_rtl;
}
if std::mem::take(&mut fields.form_text) {
run.props.form_text = Some(true);
}
run.code_format = fields
.result_format
.take()
.map(Box::new)
.or(run.code_format.take());
}
let formats: BTreeMap<usize, &CodeFormat> = fields
.check_boxes
.iter()
.filter_map(|(run, field)| fields.check_box_formats.get(field).map(|f| (*run, f)))
.collect();
if !formats.is_empty() {
for (index, run) in paragraphs
.iter_mut()
.flat_map(|p| p.runs.iter_mut())
.enumerate()
{
if let Some(format) = formats.get(&index)
&& run.code_format.is_none()
{
run.code_format = Some(Box::new((*format).clone()));
}
}
}
reader.limit_reached_times(Limit::FieldDepth, fields.too_deep);
}
fn stored_results<'r>(runs: impl Iterator<Item = &'r Run>) -> Vec<String> {
let mut stored = Vec::new();
let mut open: Vec<(usize, bool)> = Vec::new();
for item in runs.flat_map(|run| &run.content) {
match item {
Content::FieldBegin => {
open.push((stored.len(), false));
stored.push(String::new());
}
Content::FieldSeparate => {
if let Some(field) = open.last_mut() {
field.1 = true;
}
}
Content::FieldEnd => {
open.pop();
}
Content::Text(text) => {
let result = open
.last()
.filter(|field| field.1)
.and_then(|field| stored.get_mut(field.0));
if let Some(result) = result {
result.push_str(text);
}
}
_ => {}
}
}
stored
}
#[derive(Default)]
struct Fields {
open: Vec<Field>,
too_deep_open: usize,
too_deep: u32,
stored: Vec<String>,
bookmarks: BTreeSet<String>,
stored_characters: usize,
begun: usize,
updates: Updates,
saved_date: Option<&'static str>,
run_rtl: Option<bool>,
result_rtl: Option<bool>,
run_code: Option<CodeRun>,
result_format: Option<CodeFormat>,
form_text: bool,
run: usize,
check_boxes: Vec<(usize, usize)>,
check_box_formats: BTreeMap<usize, CodeFormat>,
links: Vec<LinkMark>,
}
fn merges_format(code: &str) -> bool {
let mut words = field_code::words_after_kind(code);
while let Some(word) = words.next() {
if FORMAT.is(word)
&& words
.next()
.is_some_and(|format| field_code::is_format(format, &[MERGE_FORMAT]))
{
return true;
}
}
false
}
fn shows(open: &[Field]) -> bool {
!open.iter().any(|field| {
matches!(
field.state,
FieldState::Code | FieldState::Pending(_) | FieldState::Replaced
)
})
}
struct Field {
code: String,
parts: Vec<CodePart>,
index: usize,
state: FieldState,
check_box: bool,
drop_down: Option<String>,
locked: bool,
code_rtl: Option<bool>,
code_run: Option<CodeRun>,
linked: bool,
}
enum FieldState {
Code,
Kept,
Pending(Box<Content>),
Replaced,
}
impl Field {
fn is_form_text(&self) -> bool {
field_code::kind(&self.code).is_some_and(|kind| kind.eq_ignore_ascii_case(FORM_TEXT))
}
fn value_format(&self, value: &Content) -> Option<CodeFormat> {
let formatted = matches!(
value,
Content::PageNumber | Content::PageCount | Content::StyleRef(_) | Content::FileName(_)
);
if formatted && !merges_format(&self.code) {
self.code_run.as_ref().map(|code| {
let format = CodeFormat::of(&code.props);
if matches!(value, Content::StyleRef(_)) {
format.with_style(code.style.clone())
} else {
format
}
})
} else {
None
}
}
fn result_state(&self, value: Option<Content>) -> FieldState {
if self.check_box {
FieldState::Replaced
} else {
value.map_or(FieldState::Kept, |value| {
FieldState::Pending(Box::new(value))
})
}
}
fn take_value(
&mut self,
stored: &[String],
(updates, saved): (Updates, Option<&str>),
bookmarks: &BTreeSet<String>,
) -> Option<Content> {
if let Some(entry) = self.drop_down.take()
&& field_code::kind(&self.code)
.is_some_and(|kind| kind.eq_ignore_ascii_case(FORM_DROP_DOWN))
{
return Some(Content::Text(entry));
}
let mut value = computed_field(&self.code, saved)?;
if let Content::NumberRef(field) = &value {
let text_shown = field.kind.is_none() && bookmarks.contains(&field.bookmark);
if text_shown || self.locked || updates != Updates::References {
return None;
}
}
if self.locked && matches!(value, Content::StyleRef(_)) {
return None;
}
if matches!(value, Content::FileName(_)) && (self.locked || !updates.updates_file_name()) {
return None;
}
let stored = || stored.get(self.index).cloned().unwrap_or_default();
match &mut value {
Content::Date(date) => date.stored = stored(),
Content::DocProperty(property) => property.stored = stored(),
Content::FileName(file_name) => file_name.stored = stored(),
Content::StyleRef(style_ref) => style_ref.stored = stored(),
Content::PageRef(page_ref) => {
page_ref.stored = stored();
page_ref.code.clone_from(&self.code_run);
}
Content::NumberRef(reference) => {
reference.stored = stored();
reference.code.clone_from(&self.code_run);
}
Content::If(field_if) => {
field_if.parts = std::mem::take(&mut self.parts);
field_if.stored = stored();
}
_ => {}
}
Some(value)
}
}
impl Fields {
fn open_marks(&self) -> usize {
self.open
.iter()
.map(|field| match field.state {
FieldState::Code => TEXT_BUFFER_MARK_LENGTH,
FieldState::Kept | FieldState::Pending(_) | FieldState::Replaced => {
2 * TEXT_BUFFER_MARK_LENGTH
}
})
.sum()
}
fn coding(&mut self) -> Option<&mut Field> {
self.open
.iter_mut()
.rev()
.find(|field| matches!(field.state, FieldState::Code))
}
fn push(&mut self, item: Content, out: &mut Vec<Content>) {
let begins_too_deep =
matches!(item, Content::FieldBegin) && self.open.len() >= MAX_FIELD_DEPTH;
if begins_too_deep || self.too_deep_open > 0 {
self.push_too_deep(item, out);
return;
}
match item {
Content::FieldBegin => {
self.open.push(Field {
code: String::new(),
parts: Vec::new(),
index: self.begun,
state: FieldState::Code,
check_box: false,
drop_down: None,
locked: false,
code_rtl: None,
code_run: None,
linked: false,
});
self.begun += 1;
}
Content::FieldLock => {
self.lock();
}
Content::FieldCode(code) => self.code(code),
Content::CheckBox(_) => self.check_box(item, out),
Content::DropDown(entry) => {
if let Some(field) = self.open.last_mut() {
field.drop_down = Some(entry);
}
}
Content::FieldSeparate => self.separate(out),
Content::FieldEnd => self.end(out),
other => self.result(other, out),
}
}
fn push_too_deep(&mut self, item: Content, out: &mut Vec<Content>) {
match item {
Content::FieldBegin => {
self.too_deep_open += 1;
self.too_deep = self.too_deep.saturating_add(1);
self.begun += 1;
}
Content::FieldEnd => self.too_deep_open = self.too_deep_open.saturating_sub(1),
Content::FieldLock
| Content::DropDown(_)
| Content::FieldCode(_)
| Content::FieldSeparate => {}
other => self.result(other, out),
}
}
fn code(&mut self, code: String) {
let in_own_code = self
.open
.last()
.is_some_and(|field| matches!(field.state, FieldState::Code));
if in_own_code {
let run_rtl = self.run_rtl;
if let Some(field) = self.open.last_mut() {
field.code_rtl = field.code_rtl.or(run_rtl);
if field.code_run.is_none()
|| (field.code.trim().is_empty() && !code.trim().is_empty())
{
field.code_run.clone_from(&self.run_code);
}
field.code.push_str(&code);
field.parts.push(CodePart::Text(code));
}
} else if self.in_code() {
self.code_content(Content::Text(code));
}
}
fn separate(&mut self, out: &mut Vec<Content>) {
let updates = self.updates;
if let Some(field) = self.open.last_mut() {
let stored = self
.stored
.get(field.index)
.is_some_and(|text| !text.is_empty());
let value = field
.take_value(&self.stored, (updates, self.saved_date), &self.bookmarks)
.filter(|value| updates.updates(value, stored));
field.state = field.result_state(value);
}
if let Some((field, outer)) = self.open.split_last_mut()
&& matches!(field.state, FieldState::Kept | FieldState::Pending(_))
&& shows(outer)
{
out.push(Content::FieldMark);
if let Some(link) = Hyperlink::of_code(&field.code) {
field.linked = true;
self.links.push(LinkMark::Start(Box::new(link)));
}
}
}
fn end(&mut self, out: &mut Vec<Content>) {
let ended = self.open.pop();
if let Some(field) = ended.as_ref().filter(|field| field.check_box)
&& let Some(code) = &field.code_run
{
self.check_box_formats
.insert(field.index, CodeFormat::of(&code.props).with_own_color());
}
let shown = shows(&self.open);
let mut linked = false;
if let Some(field) = ended {
linked = field.linked;
linked |= self.show_value(field, shown, out);
}
if linked {
self.links.push(LinkMark::End);
}
if shown {
out.push(Content::FieldMark);
}
}
fn show_value(&mut self, mut field: Field, shown: bool, out: &mut Vec<Content>) -> bool {
let without_separator = matches!(field.state, FieldState::Code);
let value = match std::mem::replace(&mut field.state, FieldState::Replaced) {
FieldState::Code => field.take_value(
&self.stored,
(self.updates, self.saved_date),
&self.bookmarks,
),
FieldState::Pending(value) => Some(*value),
FieldState::Kept | FieldState::Replaced => None,
};
let Some(value) = value else {
return false;
};
let value_format = field.value_format(&value);
if let Some(outer) = self.coding() {
outer.parts.push(CodePart::Field(value));
return false;
}
let direction = self.updates.result_direction(&value, field.code_rtl);
self.result_rtl = direction.or(self.result_rtl);
self.result_format = value_format.or(self.result_format.take());
let mut linked = false;
if without_separator && shown {
out.push(Content::FieldMark);
if let Some(link) = Hyperlink::of_code(&field.code) {
self.links.push(LinkMark::Start(Box::new(link)));
linked = true;
}
}
out.push(value);
linked
}
fn lock(&mut self) {
if let Some(field) = self.open.last_mut() {
field.locked = true;
}
}
fn check_box(&mut self, item: Content, out: &mut Vec<Content>) {
let nested = self
.open
.iter()
.rev()
.skip(1)
.any(|field| matches!(field.state, FieldState::Code));
if let Some(field) = self.open.last_mut() {
field.check_box = true;
if !nested {
self.check_boxes.push((self.run, field.index));
out.push(item);
}
}
}
fn in_code(&self) -> bool {
self.open
.iter()
.any(|field| matches!(field.state, FieldState::Code))
}
fn result(&mut self, item: Content, out: &mut Vec<Content>) {
if matches!(item, Content::Bookmark(_)) {
out.push(item);
return;
}
if self.in_code() {
self.code_content(item);
return;
}
let updates = self.updates;
let replacing = self
.open
.iter_mut()
.find(|f| matches!(f.state, FieldState::Pending(_) | FieldState::Replaced));
let Some(field) = replacing else {
if matches!(item, Content::Text(_)) && self.open.iter().any(Field::is_form_text) {
self.form_text = true;
}
out.push(item);
return;
};
if let FieldState::Pending(value) =
std::mem::replace(&mut field.state, FieldState::Replaced)
{
self.stored_characters += self
.stored
.get(field.index)
.map_or(0, |text| text.encode_utf16().count());
let direction = updates.result_direction(&value, field.code_rtl);
self.result_rtl = direction.or(self.result_rtl);
self.result_format = field.value_format(&value).or(self.result_format.take());
out.push(*value);
}
}
fn code_content(&mut self, item: Content) {
let Some(last) = self.open.last_mut() else {
return;
};
let part = match &mut last.state {
FieldState::Code => {
if let Content::Text(text) = &item {
last.code.push_str(text);
last.parts.push(CodePart::Text(text.clone()));
}
return;
}
FieldState::Kept => match item {
Content::Text(text) => CodePart::Text(text),
_ => return,
},
FieldState::Pending(_) => {
let FieldState::Pending(value) =
std::mem::replace(&mut last.state, FieldState::Replaced)
else {
return;
};
CodePart::Field(*value)
}
FieldState::Replaced => return,
};
if let Some(field) = self.coding() {
field.parts.push(part);
}
}
}