mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-19 02:26:48 +00:00
## What this changes Part of #1429. The form in that report keeps pages it shows on demand as **page templates**: the name dictionary's `/Templates` tree names pages kept out of the page tree, and `/Pages` names visible ones (ISO 32000-2 §7.7.4). Until now their fields were listed as unplaced, and the form's JavaScript could not reach them, so buttons that add a page or show a section did nothing. - **organize**: `templates`, `spawn_template` and `set_template_hidden`. - A spawned page is a copy of the template page. - With renaming, its fields become fields of their own under `P<page>.<template>.<name>`. - Without renaming, its widgets join the template's fields and share their values. A template field that is its own widget is split into field + widget first. - Hiding a template takes its page out of the tree, keeps what it inherited (MediaBox, Resources, …) and refuses to hide the last page. - **js**: `this.templates`, `getTemplate(name)`, `Template.name`, `Template.hidden` (setting it shows or hides the page), `Template.spawn(nPage, bRename, bOverlay)` and `spawnPageFromTemplate`, with positional or named arguments and the documented defaults (0 / true / true). Non-number pages are clamped. - **engine**: new `Edit::SpawnTemplate` and `Edit::SetTemplateHidden`. - Both are checked against the assemble permission and applied in the same undo step as the script's field changes. - Only a button's or the console's script may change the pages. A field's own scripts (format, keystroke, validate, calculate) are told so on the console. - At most 100 template pages per script run, because each spawn copies the document. A loop that asks for more stops there with one console note. - **automation**: `page_templates` (read-only), `page_template_spawn` and `page_template_set_hidden`. - Undo labels translated in all 34 catalogues. Not in this PR: - `bOverlay` true (laying a template over an existing page). The script is told so on the console once and nothing changes. - `createTemplate` / `removeTemplate`. - An Organize-panel UI for templates. - `numPages` is not updated inside the running script. - Mouse Up actions on radio buttons and checkboxes (the other half of #1429) are in the open #2546. ## How you verified it - [x] `cargo fmt --check` - [x] clippy with `-D warnings` on the crates I changed (organize, js, engine, automation, ui-egui) - [x] tests pass on the crates I changed | Crate | Result | |---|---| | organize | 188 passed | | js | 97 passed | | engine lib | 382 passed | | engine it | 21 passed | | automation | 45 + 282 passed | | ui-egui i18n | 65 passed | - [x] `cargo xtask layers`, `cargo xtask assets` and `cargo xtask parity` **Tests.** - organize has 9 unit tests: listing, renamed and shared spawns, appending past the end, show/hide, the last page and unknown names refused, hostile template trees, repeated unrenamed copies, and inherited attributes kept when hiding. - js has 5 tests: listing, `spawn` defaults, both argument forms, `hidden` read back, and clamping. - engine has 5 integration tests: one undo step, renamed and shared spawns surviving save + reopen, overlay noted, field scripts refused, and the 100-page budget. - automation has 2 tool tests. Each behaviour was seen failing by reverting it: - no renaming - no field sharing - no MediaBox fallback - hidden page dropping inherited attributes - no budget - field scripts allowed to spawn - requests not applied - wrong default flags Under a loaded machine `tests::xfa_model::a_slow_engine_start_does_not_count_against_the_script` (an existing timing test) failed once and passes on its own. It is not touched here. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests, unless it is provably infallible with a comment saying why - [x] No indexing or slicing with input-derived positions; checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded - Name trees are capped at 4096 names. - Field walks are capped at 32 levels and 100 000 nodes, with seen-sets. - Spawns are capped at 100 per script run. - Template names are clipped and charged to the script's output budget. - [x] No `unsafe` - [x] Any crash this fixes has a small synthetic regression test (no crash fixed; the hostile-tree test covers cyclic and malformed `/Templates`) ## Provenance - [x] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated - [x] No font files committed here - [x] No GPL/AGPL code copied in - [x] Behaviour comes from the specification or black-box observation, **not** from reading another implementation's source. The sources are ISO 32000-2 §7.7.4 and §12.7.6 and the public Acrobat JavaScript API reference for `Template`/`spawnPageFromTemplate`. - [x] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes (no new assets) ## Security - [x] `--root` confinement still holds on every path, including ones reached by nested tool dispatch (the new tools take a document id, no paths) - [x] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated - [x] No new outbound network access ## Parity and reach - [x] `parity/acrobat-features.toml` updated: `organize.page-templates` is now `partial`, with notes on what is still missing - [x] Reachable headlessly through an `automation` tool (`page_templates`, `page_template_spawn`, `page_template_set_hidden`, and `js_run` for scripts) - [x] Docs updated if this changes a documented behaviour (crate doc comments) ## Anything a reviewer should look at first - `share_fields_with_originals` in `crates/organize/src/import/fields.rs`: how an unrenamed copy's widgets are reparented onto the template's fields. When a template field is its own widget, it is split into a field with two widget kids. - The 100-page budget per script run in `crates/engine/src/js.rs`. Each spawn copies the document, so a `for` loop over `spawn` in a hostile form is bounded there.
328 lines
13 KiB
Rust
328 lines
13 KiB
Rust
use super::model::{DocInfo, FieldState, FieldType, Request};
|
|
use super::run::MAX_ARRAY_LENGTH;
|
|
use super::{
|
|
Arc, BTreeSet, Context, FunctionObjectBuilder, JsArray, JsError, JsFunction, JsNativeError, JsResult, JsString, JsValue, Message, NativeFunction,
|
|
RefCell, xfa,
|
|
};
|
|
|
|
pub(crate) struct Host {
|
|
pub(crate) event_name: String,
|
|
pub(crate) fields: Arc<Vec<FieldState>>,
|
|
pub(crate) icons: Vec<(super::JsObject, u64)>,
|
|
pub(crate) objects: std::collections::HashMap<(String, Option<u64>, u64), super::JsObject>,
|
|
pub(crate) field_keys: std::collections::HashSet<(String, Option<u64>, u64)>,
|
|
pub(crate) changed: BTreeSet<usize>,
|
|
pub(crate) formatted: BTreeSet<usize>,
|
|
pub(crate) alerts: Vec<Message>,
|
|
pub(crate) console: Vec<String>,
|
|
pub(crate) requests: Vec<Request>,
|
|
pub(crate) doc: DocInfo,
|
|
pub(crate) calculations: Vec<(usize, String)>,
|
|
pub(crate) calculate_depth: usize,
|
|
pub(crate) calculation_evaluations: usize,
|
|
pub(crate) calculation_limit_exceeded: bool,
|
|
pub(crate) calculation_work: usize,
|
|
pub(crate) current_event: JsValue,
|
|
pub(crate) reset_calls: usize,
|
|
pub(crate) reset_limit_exceeded: bool,
|
|
/// Bytes of text kept in alerts, console lines and requests, against [`xfa::MAX_PAYLOAD`].
|
|
pub(crate) kept: usize,
|
|
/// Bytes of text the script has added to the fields' values and colours, net of what it
|
|
/// replaced, against [`xfa::MAX_PAYLOAD`]: each assignment alone is capped, so without this
|
|
/// many fields could each hold a maximal array.
|
|
pub(crate) retained: usize,
|
|
/// Alerts, console lines and requests the limits left out.
|
|
pub(crate) dropped: usize,
|
|
/// Layers a script turned on or off (`ocg.state`), by their places in [`DocInfo::layers`].
|
|
pub(crate) layers_changed: BTreeSet<usize>,
|
|
}
|
|
|
|
impl Host {
|
|
/// Room for `bytes` more bytes of kept text: charged when there is, a drop counted when not.
|
|
fn room(&mut self, bytes: usize) -> bool {
|
|
match self.kept.checked_add(bytes).filter(|k| *k <= xfa::MAX_PAYLOAD) {
|
|
Some(k) => {
|
|
self.kept = k;
|
|
true
|
|
}
|
|
None => {
|
|
self.dropped = self.dropped.saturating_add(1);
|
|
false
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Keep message `m`, its text and title charged to the run's byte budget, up to
|
|
/// [`xfa::MAX_ALERTS`] messages.
|
|
pub(crate) fn alert(&mut self, m: Message) {
|
|
if self.alerts.len() >= xfa::MAX_ALERTS {
|
|
self.dropped = self.dropped.saturating_add(1);
|
|
} else if self.room(m.bytes()) {
|
|
self.alerts.push(m);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn print(&mut self, m: String) {
|
|
if self.console.len() >= xfa::MAX_CONSOLE {
|
|
self.dropped = self.dropped.saturating_add(1);
|
|
} else if self.room(m.len()) {
|
|
self.console.push(m);
|
|
}
|
|
}
|
|
|
|
/// Record `r`, its names and URLs cut to a message's length, up to [`xfa::MAX_EFFECTS`]
|
|
/// requests and the run's byte budget.
|
|
pub(crate) fn request(&mut self, r: Request) -> bool {
|
|
if self.requests.len() >= xfa::MAX_EFFECTS {
|
|
self.dropped = self.dropped.saturating_add(1);
|
|
return false;
|
|
}
|
|
let r = match r {
|
|
Request::Reset(names) => Request::Reset(names.into_iter().map(xfa::clip).collect()),
|
|
Request::LaunchUrl(u) => Request::LaunchUrl(xfa::clip(u)),
|
|
Request::Submit(u) => Request::Submit(xfa::clip(u)),
|
|
Request::Focus(n) => Request::Focus(xfa::clip(n)),
|
|
Request::OpenDoc(p) => Request::OpenDoc(xfa::clip(p)),
|
|
// Template names are looked up exactly, so they are never clipped: a cut name could
|
|
// name another template. Their whole length is charged below.
|
|
Request::FocusField { name, object_id } => Request::FocusField { name: xfa::clip(name), object_id },
|
|
other => other,
|
|
};
|
|
let bytes = match &r {
|
|
Request::Reset(names) => names.iter().fold(0usize, |n, s| n.saturating_add(s.len()).saturating_add(std::mem::size_of::<String>())),
|
|
Request::LaunchUrl(u) | Request::Submit(u) | Request::Focus(u) | Request::OpenDoc(u) => u.len(),
|
|
Request::SpawnTemplate { name, .. } | Request::SetTemplateHidden { name, .. } | Request::OpenAttachment { name, .. } => name.len(),
|
|
Request::FocusField { name, .. } => name.len(),
|
|
_ => 0,
|
|
};
|
|
let kept = self.room(bytes);
|
|
if kept {
|
|
self.requests.push(r);
|
|
}
|
|
kept
|
|
}
|
|
}
|
|
|
|
pub(crate) type Shared = RefCell<Host>;
|
|
|
|
/// The host state, installed before scripts run.
|
|
pub(crate) fn host(ctx: &Context) -> JsResult<&Shared> {
|
|
ctx.get_data::<Shared>().ok_or_else(|| error("the script host is not set up"))
|
|
}
|
|
|
|
pub(crate) fn s(v: &str) -> JsValue {
|
|
JsValue::from(JsString::from(v))
|
|
}
|
|
|
|
pub(crate) fn text(v: &JsValue, ctx: &mut Context) -> JsResult<String> {
|
|
if v.is_undefined() || v.is_null() {
|
|
return Ok(String::new());
|
|
}
|
|
Ok(v.to_string(ctx)?.to_std_string_escaped())
|
|
}
|
|
|
|
/// [`text`] cut to a message's length ([`xfa::clip`]), without first copying all of a longer
|
|
/// string.
|
|
pub(crate) fn text_line(v: &JsValue, ctx: &mut Context) -> JsResult<String> {
|
|
if v.is_undefined() || v.is_null() {
|
|
return Ok(String::new());
|
|
}
|
|
let js = v.to_string(ctx)?;
|
|
// Two UTF-16 units per character at most: the clip still sees more than a line's worth.
|
|
let keep = xfa::MAX_LINE.saturating_add(1).saturating_mul(2);
|
|
let js = if js.len() > keep { js.get(..keep).unwrap_or_default() } else { js };
|
|
Ok(xfa::clip(js.to_std_string_escaped()))
|
|
}
|
|
|
|
pub(crate) fn arg(args: &[JsValue], i: usize) -> JsValue {
|
|
args.get(i).cloned().unwrap_or_default()
|
|
}
|
|
|
|
pub(crate) fn error(msg: impl Into<String>) -> JsError {
|
|
JsNativeError::typ().with_message(msg.into()).into()
|
|
}
|
|
|
|
/// A JavaScript number for a text value that reads as one, as Acrobat's `field.value` gives.
|
|
pub(crate) fn as_number(t: &str) -> Option<f64> {
|
|
let t = t.trim();
|
|
if t.is_empty() || t.starts_with('+') || t.len() > 1 && t.starts_with('0') && !t.starts_with("0.") {
|
|
return None;
|
|
}
|
|
t.parse::<f64>().ok().filter(|v| v.is_finite())
|
|
}
|
|
|
|
pub(crate) fn function(ctx: &mut Context, f: NativeFunction) -> JsFunction {
|
|
FunctionObjectBuilder::new(ctx.realm(), f).build()
|
|
}
|
|
|
|
/// Format exactly the escaped UTF-8 representation used by `text`, refusing a
|
|
/// write before it exceeds the remaining aggregate budget. No full Rust copy of
|
|
/// an oversized JavaScript string is made just to discover its byte length.
|
|
pub(crate) fn text_with_budget(v: &JsValue, ctx: &mut Context, remaining: usize, limit_error: &str) -> JsResult<String> {
|
|
use std::fmt::Write;
|
|
if v.is_undefined() || v.is_null() {
|
|
return Ok(String::new());
|
|
}
|
|
let js = v.to_string(ctx)?;
|
|
let exceeded = || error(limit_error);
|
|
// Every UTF-16 unit contributes at least one byte in the escaped UTF-8 output.
|
|
if js.len() > remaining {
|
|
return Err(exceeded());
|
|
}
|
|
struct BoundedText {
|
|
text: String,
|
|
limit: usize,
|
|
}
|
|
impl std::fmt::Write for BoundedText {
|
|
fn write_str(&mut self, text: &str) -> std::fmt::Result {
|
|
if self.text.len().checked_add(text.len()).is_none_or(|len| len > self.limit) {
|
|
return Err(std::fmt::Error);
|
|
}
|
|
self.text.push_str(text);
|
|
Ok(())
|
|
}
|
|
}
|
|
let mut out = BoundedText { text: String::new(), limit: remaining };
|
|
write!(&mut out, "{}", js.display_escaped()).map_err(|_| exceeded())?;
|
|
Ok(out.text)
|
|
}
|
|
|
|
pub(crate) fn strings(v: &JsValue, ctx: &mut Context) -> JsResult<Vec<String>> {
|
|
if let Some(o) = v.as_object()
|
|
&& o.is_array()
|
|
{
|
|
let a = JsArray::from_object(o.clone())?;
|
|
let n = a.length(ctx)?;
|
|
if n > MAX_ARRAY_LENGTH {
|
|
return Err(error(format!("array length exceeds {MAX_ARRAY_LENGTH}")));
|
|
}
|
|
let mut out = Vec::new();
|
|
let mut remaining = xfa::MAX_PAYLOAD;
|
|
for i in 0..n {
|
|
let x = a.get(i, ctx)?;
|
|
let value = text_with_budget(&x, ctx, remaining, "string array byte limit exceeded")?;
|
|
remaining = remaining.saturating_sub(value.len());
|
|
out.push(value);
|
|
}
|
|
return Ok(out);
|
|
}
|
|
Ok(if v.is_undefined() || v.is_null() {
|
|
Vec::new()
|
|
} else {
|
|
vec![text_with_budget(v, ctx, xfa::MAX_PAYLOAD, "string array byte limit exceeded")?]
|
|
})
|
|
}
|
|
|
|
pub(crate) fn colour(c: Option<&[String]>, ctx: &mut Context) -> JsValue {
|
|
match c {
|
|
None => JsArray::from_iter([s("T")], ctx).into(),
|
|
Some(parts) => {
|
|
let vals: Vec<JsValue> =
|
|
parts.iter().enumerate().map(|(i, p)| if i == 0 { s(p) } else { JsValue::from(p.parse::<f64>().unwrap_or(0.0)) }).collect();
|
|
JsArray::from_iter(vals, ctx).into()
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── field objects ───────────────────────────────────────────────────────────────────────────
|
|
|
|
pub(crate) type FieldKey = (JsString, Option<u64>, u64);
|
|
|
|
/// PDF identities survive renames; name-only synthetic fields retain name lookup semantics.
|
|
pub(crate) fn field_cache_key(name: &str, id: Option<u64>, token: u64) -> (String, Option<u64>, u64) {
|
|
(if id.is_some() { String::new() } else { name.to_string() }, id, token)
|
|
}
|
|
|
|
fn field_index(ctx: &Context, name: &FieldKey) -> JsResult<usize> {
|
|
let n = name.0.to_std_string_escaped();
|
|
host(ctx)?
|
|
.borrow()
|
|
.fields
|
|
.iter()
|
|
.position(|f| name.1.map_or(f.name == n, |id| f.object_id == Some(id) && f.instance_id == name.2))
|
|
.ok_or_else(|| error(format!("no field named {n}")))
|
|
}
|
|
|
|
pub(crate) fn read(ctx: &Context, name: &FieldKey) -> JsResult<FieldState> {
|
|
let i = field_index(ctx, name)?;
|
|
Ok(host(ctx)?.borrow().fields[i].clone())
|
|
}
|
|
|
|
pub(crate) fn write(ctx: &Context, name: &FieldKey, change: impl FnOnce(&mut FieldState)) -> JsResult<()> {
|
|
let i = field_index(ctx, name)?;
|
|
let mut h = host(ctx)?.borrow_mut();
|
|
let field = Arc::make_mut(&mut h.fields).get_mut(i).ok_or_else(|| error("the field is no longer available"))?;
|
|
change(field);
|
|
h.changed.insert(i);
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn value_of(f: &FieldState, ctx: &mut Context) -> JsValue {
|
|
match f.kind {
|
|
FieldType::CheckBox | FieldType::RadioButton => s(f.value.first().map_or("Off", String::as_str)),
|
|
FieldType::ListBox if f.value.len() > 1 => {
|
|
let vals: Vec<JsValue> = f.value.iter().map(|v| s(v)).collect();
|
|
JsArray::from_iter(vals, ctx).into()
|
|
}
|
|
_ => {
|
|
let v = f.single();
|
|
as_number(&v).map_or_else(|| s(&v), JsValue::from)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Bytes of text in `v`, counting each string's heap size and its handle.
|
|
pub(crate) fn text_bytes(v: &[String]) -> usize {
|
|
v.iter().fold(0usize, |n, t| n.saturating_add(t.len()).saturating_add(std::mem::size_of::<String>()))
|
|
}
|
|
|
|
/// Charge the replacement of the text `old` selects from field `name` with `new_bytes` of text to
|
|
/// the run's retained-text budget; an assignment the budget has no room for is an error and
|
|
/// charges nothing.
|
|
pub(crate) fn charge(ctx: &Context, name: &FieldKey, old: impl FnOnce(&FieldState) -> usize, new_bytes: usize) -> JsResult<()> {
|
|
let i = field_index(ctx, name)?;
|
|
let mut h = host(ctx)?.borrow_mut();
|
|
let freed = old(&h.fields[i]);
|
|
let total = h.retained.saturating_sub(freed).saturating_add(new_bytes);
|
|
if total > xfa::MAX_PAYLOAD {
|
|
return Err(error(format!("the fields' values and colours hold more than {} bytes of text", xfa::MAX_PAYLOAD)));
|
|
}
|
|
h.retained = total;
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn kind_of(ctx: &Context, name: &FieldKey) -> JsResult<FieldType> {
|
|
let i = field_index(ctx, name)?;
|
|
Ok(host(ctx)?.borrow().fields[i].kind)
|
|
}
|
|
|
|
/// What a field of `kind` keeps of the values assigned to it.
|
|
pub(crate) fn value_for(kind: FieldType, vals: Vec<String>) -> Vec<String> {
|
|
match kind {
|
|
FieldType::CheckBox | FieldType::RadioButton => vals.into_iter().filter(|v| v != "Off" && !v.is_empty()).take(1).collect(),
|
|
FieldType::ListBox => vals,
|
|
_ => vals.into_iter().take(1).collect(),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn set_value(f: &mut FieldState, vals: Vec<String>) {
|
|
f.value = value_for(f.kind, vals);
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod string_budget_review_tests {
|
|
use super::*;
|
|
#[test]
|
|
fn escaped_text_budget_counts_exact_utf8_bytes() {
|
|
let mut ctx = Context::default();
|
|
for (script, bytes) in [("'ascii'", 5), ("'é'", 2), ("'😀'", 4), ("'\\uD800'", 6)] {
|
|
let value = ctx.eval(boa_engine::Source::from_bytes(script)).unwrap();
|
|
let expected = text(&value, &mut ctx).unwrap();
|
|
assert_eq!(expected.len(), bytes);
|
|
assert_eq!(text_with_budget(&value, &mut ctx, bytes, "text limit").unwrap(), expected);
|
|
assert!(text_with_budget(&value, &mut ctx, bytes - 1, "text limit").is_err());
|
|
}
|
|
assert_eq!(text_with_budget(&JsValue::null(), &mut ctx, 0, "text limit").unwrap(), "");
|
|
}
|
|
}
|