use std::fmt::Write as _;
use super::recognise::{MAX_DECIMALS, MAX_PATTERN, TIME_FORMATS};
use super::{
CalculateFunction, FieldBehaviour, FieldTrigger, NegativeStyle, NumberFormat, PercentFormat, RangeValidate,
SeparatorStyle, SimpleCalculate, SpecialFormat,
};
pub const MAX_WRITTEN_SCRIPT: usize = 32 * 1024;
impl FieldBehaviour {
#[must_use]
pub fn helper_calls(&self) -> Option<Vec<(FieldTrigger, String)>> {
let both = |format: String, keystroke: String| {
vec![(FieldTrigger::Format, format), (FieldTrigger::Keystroke, keystroke)]
};
let calls = match self {
Self::NumberFormat(f) => {
let args = number_args(f)?;
both(
format!("AFNumber_Format({args});"),
format!("AFNumber_Keystroke({args});"),
)
}
Self::PercentFormat(f) => both(percent_format(*f)?, percent_keystroke(*f)?),
Self::DateFormat(p) => {
let pattern = pattern(&p.pattern)?;
both(
format!("AFDate_FormatEx({pattern});"),
format!("AFDate_KeystrokeEx({pattern});"),
)
}
Self::TimeFormat(p) => {
if let Some(i) = TIME_FORMATS.iter().position(|t| *t == p.pattern) {
both(format!("AFTime_Format({i});"), format!("AFTime_Keystroke({i});"))
} else {
let pattern = pattern(&p.pattern)?;
both(
format!("AFTime_FormatEx({pattern});"),
format!("AFTime_KeystrokeEx({pattern});"),
)
}
}
Self::SpecialFormat(kind) => {
let i = special_index(*kind);
both(format!("AFSpecial_Format({i});"), format!("AFSpecial_Keystroke({i});"))
}
Self::RangeValidate(r) => vec![(FieldTrigger::Validate, range_call(r)?)],
Self::SimpleCalculate(c) => vec![(FieldTrigger::Calculate, calculate_call(c)?)],
};
calls
.iter()
.all(|(_, script)| script.len() <= MAX_WRITTEN_SCRIPT)
.then_some(calls)
}
}
fn number_args(f: &NumberFormat) -> Option<String> {
Some(format!(
"{}, {}, {}, 0, {}, {}",
decimals(f.decimals)?,
separator_index(f.separator),
negative_index(f.negative),
literal(&f.currency),
f.prepend
))
}
fn percent_format(f: PercentFormat) -> Option<String> {
let (decimals, separator) = (decimals(f.decimals)?, separator_index(f.separator));
Some(if f.prepend {
format!("AFPercent_Format({decimals}, {separator}, true);")
} else {
format!("AFPercent_Format({decimals}, {separator});")
})
}
fn percent_keystroke(f: PercentFormat) -> Option<String> {
Some(format!(
"AFPercent_Keystroke({}, {});",
decimals(f.decimals)?,
separator_index(f.separator)
))
}
fn range_call(r: &RangeValidate) -> Option<String> {
let bound = |b: Option<f64>| match b {
Some(n) => number(n).map(|n| format!("true, {n}")),
None => Some("false, 0".to_owned()),
};
Some(format!("AFRange_Validate({}, {});", bound(r.min)?, bound(r.max)?))
}
fn calculate_call(c: &SimpleCalculate) -> Option<String> {
if c.fields.is_empty() {
return None;
}
let names: Vec<String> = c.fields.iter().map(|n| literal(n)).collect();
Some(format!(
"AFSimple_Calculate(\"{}\", new Array ({}));",
function_name(c.function),
names.join(", ")
))
}
fn decimals(n: u8) -> Option<u8> {
(f64::from(n) <= MAX_DECIMALS).then_some(n)
}
fn number(n: f64) -> Option<String> {
n.is_finite().then(|| format!("{n}"))
}
fn pattern(p: &str) -> Option<String> {
(!p.is_empty() && p.chars().count() <= MAX_PATTERN).then(|| literal(p))
}
fn literal(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if needs_escape(c) => {
let _ = if u32::from(c) <= 0xFF {
write!(out, "\\x{:02x}", u32::from(c))
} else {
write!(out, "\\u{:04x}", u32::from(c))
};
}
c => out.push(c),
}
}
out.push('"');
out
}
fn needs_escape(c: char) -> bool {
c.is_control()
|| matches!(
c,
'\u{ad}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{206f}' | '\u{feff}'
)
}
const fn separator_index(s: SeparatorStyle) -> u8 {
match s {
SeparatorStyle::CommaDot => 0,
SeparatorStyle::Dot => 1,
SeparatorStyle::DotComma => 2,
SeparatorStyle::Comma => 3,
SeparatorStyle::ApostropheDot => 4,
}
}
const fn negative_index(s: NegativeStyle) -> u8 {
match s {
NegativeStyle::Minus => 0,
NegativeStyle::Red => 1,
NegativeStyle::Parentheses => 2,
NegativeStyle::RedParentheses => 3,
}
}
const fn special_index(kind: SpecialFormat) -> u8 {
match kind {
SpecialFormat::Zip => 0,
SpecialFormat::ZipPlus4 => 1,
SpecialFormat::Phone => 2,
SpecialFormat::Ssn => 3,
}
}
const fn function_name(f: CalculateFunction) -> &'static str {
match f {
CalculateFunction::Sum => "SUM",
CalculateFunction::Average => "AVG",
CalculateFunction::Product => "PRD",
CalculateFunction::Minimum => "MIN",
CalculateFunction::Maximum => "MAX",
}
}
#[cfg(test)]
mod tests {
use super::super::recognise::recognise;
use super::*;
use crate::forms::behaviour::DatePattern;
fn calls(b: &FieldBehaviour) -> Vec<(FieldTrigger, String)> {
b.helper_calls().unwrap_or_default()
}
fn reads_back(b: &FieldBehaviour) -> bool {
let written = calls(b);
!written.is_empty() && written.iter().all(|(t, s)| recognise(s, *t).is_some())
}
#[test]
fn a_number_format_is_acrobats_call_for_its_format_and_its_keystroke() {
let b = FieldBehaviour::NumberFormat(NumberFormat {
decimals: 2,
separator: SeparatorStyle::CommaDot,
negative: NegativeStyle::Minus,
currency: "$".into(),
prepend: true,
});
assert_eq!(
calls(&b),
[
(
FieldTrigger::Format,
r#"AFNumber_Format(2, 0, 0, 0, "$", true);"#.to_owned()
),
(
FieldTrigger::Keystroke,
r#"AFNumber_Keystroke(2, 0, 0, 0, "$", true);"#.to_owned()
),
]
);
assert_eq!(recognise(&calls(&b)[0].1, FieldTrigger::Format), Some(b));
}
#[test]
fn the_other_helpers_are_written_in_acrobats_spelling() {
let at = |b: &FieldBehaviour, i: usize| calls(b)[i].1.clone();
let percent = FieldBehaviour::PercentFormat(PercentFormat {
decimals: 1,
separator: SeparatorStyle::DotComma,
prepend: false,
});
let date = FieldBehaviour::DateFormat(DatePattern {
pattern: "mm/dd/yyyy".into(),
});
let time = FieldBehaviour::TimeFormat(DatePattern {
pattern: "h:MM tt".into(),
});
let custom_time = FieldBehaviour::TimeFormat(DatePattern {
pattern: "HH.MM".into(),
});
let special = FieldBehaviour::SpecialFormat(SpecialFormat::Phone);
let range = FieldBehaviour::RangeValidate(RangeValidate {
min: Some(0.0),
max: Some(99.5),
});
let open = FieldBehaviour::RangeValidate(RangeValidate {
min: None,
max: Some(-1.0),
});
let sum = FieldBehaviour::SimpleCalculate(SimpleCalculate {
function: CalculateFunction::Sum,
fields: vec!["a".into(), "b.c".into()],
});
assert_eq!(
[
at(&percent, 0),
at(&percent, 1),
at(&date, 0),
at(&date, 1),
at(&time, 0),
at(&custom_time, 0),
at(&special, 0),
at(&special, 1),
at(&range, 0),
at(&open, 0),
at(&sum, 0),
],
[
"AFPercent_Format(1, 2);",
"AFPercent_Keystroke(1, 2);",
r#"AFDate_FormatEx("mm/dd/yyyy");"#,
r#"AFDate_KeystrokeEx("mm/dd/yyyy");"#,
"AFTime_Format(1);",
r#"AFTime_FormatEx("HH.MM");"#,
"AFSpecial_Format(2);",
"AFSpecial_Keystroke(2);",
"AFRange_Validate(true, 0, true, 99.5);",
"AFRange_Validate(false, 0, true, -1);",
r#"AFSimple_Calculate("SUM", new Array ("a", "b.c"));"#,
]
);
assert!(
[&percent, &date, &time, &custom_time, &special, &range, &open, &sum]
.into_iter()
.all(reads_back)
);
}
#[test]
fn a_name_with_quotes_backslashes_and_line_breaks_reads_back_as_the_same_name() {
let names = [
"say \"hi\"",
"back\\slash",
"two\nlines\r",
"tab\t",
"\u{1}ctl",
"é ü 日本",
];
let b = FieldBehaviour::SimpleCalculate(SimpleCalculate {
function: CalculateFunction::Maximum,
fields: names.iter().map(|n| (*n).to_owned()).collect(),
});
let script = &calls(&b)[0].1;
assert_eq!(recognise(script, FieldTrigger::Calculate), Some(b));
assert!(!script.contains('\n') && !script.contains('\r'));
}
#[test]
fn hostile_text_is_written_as_escapes_only_and_reads_back() {
let hostile = [
"\0",
"a\u{2028}b\u{2029}c\u{85}d",
"\u{202e}rtl\u{202c}\u{feff}\u{200b}\u{ad}",
"\"); app.alert(\"x\"); (\"",
"\\\"; evil(); //",
"line\nbreak\r\n",
"\u{1f600} \u{10ffff}",
];
for text in hostile {
let behaviours = [
FieldBehaviour::NumberFormat(NumberFormat {
decimals: 0,
separator: SeparatorStyle::CommaDot,
negative: NegativeStyle::Minus,
currency: text.to_owned(),
prepend: false,
}),
FieldBehaviour::DateFormat(DatePattern {
pattern: text.to_owned(),
}),
FieldBehaviour::SimpleCalculate(SimpleCalculate {
function: CalculateFunction::Sum,
fields: vec![text.to_owned(), "b".to_owned()],
}),
];
for b in behaviours {
for (trigger, script) in calls(&b) {
assert!(!script.chars().any(needs_escape), "{script:?} holds a raw character");
assert_eq!(recognise(&script, trigger), Some(b.clone()));
}
}
}
}
#[test]
fn what_cannot_be_read_back_is_not_written() {
let too_precise = FieldBehaviour::NumberFormat(NumberFormat {
decimals: 21,
separator: SeparatorStyle::CommaDot,
negative: NegativeStyle::Minus,
currency: String::new(),
prepend: false,
});
let empty_pattern = FieldBehaviour::DateFormat(DatePattern { pattern: String::new() });
let nan = FieldBehaviour::RangeValidate(RangeValidate {
min: Some(f64::NAN),
max: None,
});
let nothing = FieldBehaviour::SimpleCalculate(SimpleCalculate {
function: CalculateFunction::Sum,
fields: Vec::new(),
});
let huge = FieldBehaviour::SimpleCalculate(SimpleCalculate {
function: CalculateFunction::Sum,
fields: vec!["x".repeat(MAX_WRITTEN_SCRIPT)],
});
assert!(
[too_precise, empty_pattern, nan, nothing, huge]
.iter()
.all(|b| b.helper_calls().is_none())
);
}
}