PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Reconcile button export values with current form authoring modules
FredAppsb07a012cd741
diff --cc ROADMAP.mdindex 3bf3cc0bb,f5de8044e..b65b677da--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -522,3 -734,17 +734,21 @@@ Newest first: the date, what moved, an- **2026-10-12 (M8):** Redaction cleans indirect and form structure references, preserving surviving form tags.- **2026-10-13 (M7):** Edit a PDF ▸ Add content: Header and footer, Watermark and Background open an Add / Update / Remove menu (Update and Remove enabled only when the document has that mark), as Acrobat's Watermark control does. The catalogue gains `ToolItem::actions`, so any tool can list more commands (#1192).++ - **2026-10-18 (M8, #1350):** Published the history-preserving integration; simplified the inherited-form resource guard for Rust 1.96 Clippy. Formatting, 64 redaction tests, scoped Clippy, layering, assets and the scoped wasm check pass locally. CI remains pending; estimates unchanged.++ - 2026-10-18: M11 / #3227: mark target-version compatibility partial; document the unchecked newer-content limitation.++ - **2026-10-18 (PR #3227 integration):** M11: integrate upstream b0e5c6eb; retain partial target-version compatibility claims and effective-version reporting, correcting the borrowed version parser lifetime. Scope and estimates unchanged.++ - **2026-10-12 (i18n):** Albanian (`sq`, Shqip) added: 2,343-entry catalog, month and weekday names, Preferences entry; not yet reviewed by a native speaker.++ - **2026-10-21 (M4, #3865):** A new bookmark records where the reader is: the top-left of the selected text, or the top of the window, as `/XYZ left top null` (zoom kept), instead of the page top (`Edit::AddBookmark` takes `left` and `top`; `bookmark_add` takes `top` and `left`; `PageInfo::xyz_for_view`).++ - **2026-10-18 (renderer, hayro patches 19/35):** A mesh shading (types 4–7) is sampled over its own triangles instead of the whole path: a BricsCAD plan with 310 one-triangle `sh` fills took 2 s per 1024 px tile at every zoom (and hit the 20 s watchdog on a busy machine); now about 70 ms, so zooming into dense topology drawings stays fluid. Estimates unchanged.++ - **2026-10-22 (PR #3227 integration):** M11: integrate upstream `80b7d215`; retain partial target-version compatibility and upstream content-boundary and image-size regression coverage. Scope and estimates unchanged.++++## Button export-value refresh (2026-10-30)++++PR #1952 retains per-widget checkbox/radio export-value editing in the split form-authoring and Prepare modules. Caption editing remains supported. Tests cover preserved appearances and selection, invalid/locked refusals, data-format round trips, and Apply/Cancel/Undo. Current-head hosted validation is pending; feature estimates are unchanged.diff --cc crates/automation/src/forms.rsindex 6089d5a36,1c1e3c337..1c0684f95--- a/crates/automation/src/forms.rs+++ b/crates/automation/src/forms.rs@@@ -232,10 -232,20 +232,23 @@@ impl Automationif !f.actions.unsupported.is_empty() {o.insert("unsupported_scripts".into(), json!(f.actions.unsupported));}+ if matches!(f.kind, FormFieldKind::CheckBox | FormFieldKind::Radio) {+ o.insert("export_values".into(), json!((0..f.widgets.len()).map(|i| f.export_of(i)).collect::<Vec<_>>()));+ }match f.kind {+ FormFieldKind::PushButton => {+ o.insert("caption".into(), json!(w.and_then(|w| w.caption.as_deref()).unwrap_or_default()));+ o.insert(+ "captions".into(),+ json!(+ f.widgets+ .iter()+ .enumerate()+ .map(|(i, w)| { json!({"widget": i.saturating_add(1), "caption": w.caption.as_deref().unwrap_or_default()}) })+ .collect::<Vec<_>>()+ ),+ );+ }FormFieldKind::Radio => {o.insert("options".into(), json!((0..f.widgets.len()).filter_map(|i| f.export_of(i)).collect::<Vec<_>>()));}@@@ -329,9 -356,70 +359,70 @@@Ok(out)}+ /// A table of text fields: `rect` (points from the top-left of the displayed page) divided+ /// into rows and columns, one field per cell, as one undo step.+ pub(crate) fn form_add_field_table(&mut self, a: &Args) -> Result<Value> {+ use pdfcraft_engine::field_table::{self, FieldTable, MAX_COLUMNS, TableColumn, TableError};+ let page = self.page(a)?;+ let rect = a+ .get("rect")+ .and_then(Value::as_array)+ .and_then(|r| r.iter().map(Value::as_f64).collect::<Option<Vec<f64>>>())+ .and_then(|r| <[f64; 4]>::try_from(r).ok())+ .ok_or_else(|| bad("rect must be 4 numbers"))?;+ let names = a.get("names").map(|_| a.strs("names")).transpose()?;+ let widths = match a.get("widths") {+ None => None,+ Some(v) => Some(+ v.as_array()+ .and_then(|w| w.iter().map(Value::as_f64).collect::<Option<Vec<f64>>>())+ .ok_or_else(|| bad("widths must be an array of numbers"))?,+ ),+ };+ // A negative count is no count: the table refuses it with its own words.+ let counts = [a.opt_int("columns")?.map(|n| usize::try_from(n).unwrap_or(0)), names.as_ref().map(Vec::len), widths.as_ref().map(Vec::len)];+ let mut given = counts.into_iter().flatten();+ let columns = given.next().unwrap_or(1);+ if given.any(|n| n != columns) {+ return Err(bad("columns, names and widths must agree on the number of columns"));+ }+ // Before anything is sized by it.+ if !(1..=MAX_COLUMNS).contains(&columns) {+ return Err(bad(TableError::Columns.to_string()));+ }+ let (edit, fields) = {+ let doc = self.doc(a)?;+ let base = field_table::free_base(doc.form.iter().map(|f| f.name.as_str()));+ let mut table = FieldTable::new(rect, &base);+ table.rows = usize::try_from(a.int("rows")?).unwrap_or(0);+ table.columns = (0..columns)+ .map(|c| TableColumn {+ pattern: names.as_ref().and_then(|n| n.get(c)).map_or_else(|| field_table::column_pattern(&base, c + 1), |p| (*p).to_owned()),+ width: widths.as_ref().and_then(|w| w.get(c)).copied().unwrap_or(1.0),+ })+ .collect();+ table.row_gap = a.opt_num("row_gap")?.unwrap_or(0.0);+ table.column_gap = a.opt_num("column_gap")?.unwrap_or(0.0);+ table.first_row = a.opt_int("first_row")?.map_or(1, |n| usize::try_from(n).unwrap_or(usize::MAX));+ let info = doc.info.pages.get(page).ok_or_else(|| bad(format!("page {} does not exist", page + 1)))?;+ let edit = field_table::edit(&table, page, info, &doc.form).map_err(|e| bad(e.to_string()))?;+ // The names the batch adds, in the order it adds them.+ let fields: Vec<String> = match &edit {+ Edit::Batch { edits, .. } => {+ edits.iter().filter_map(|e| if let Edit::AddField { name, .. } = e { name.clone() } else { None }).collect()+ }+ _ => Vec::new(),+ };+ (edit, fields)+ };+ let mut out = self.apply(a, edit)?;+ out["fields"] = json!(fields);+ Ok(out)+ }+pub(crate) fn form_set_props(&mut self, a: &Args) -> Result<Value> {- if a.get("widget").is_some() && a.get("export_value").is_none() {- return Err(bad("widget requires export_value"));- if a.get("widget").is_some() && a.get("caption").is_none() {- return Err(bad("widget requires caption"));++ if a.get("widget").is_some() && a.get("caption").is_none() && a.get("export_value").is_none() {++ return Err(bad("widget requires caption or export_value"));}let single = a.opt_str("field")?;let bulk = a.get("fields").is_some();@@@ -350,7 -438,7 +441,7 @@@return Err(bad(format!("field {name:?} is listed more than once")));}}- for key in ["name", "rect", "rotation", "export_value", "widget"] {- for key in ["name", "rect", "rotation", "caption", "widget"] {++ for key in ["name", "rect", "rotation", "caption", "export_value", "widget"] {if a.get(key).is_some() {return Err(bad(format!("{key} applies to one field; use field instead of fields")));}@@@ -402,17 -502,17 +505,26 @@@};Ok(FieldProps {rect,+ export_value: a+ .opt_str("export_value")?+ .map(|value| -> Result<_> {+ let index = a.opt_int("widget")?.unwrap_or(1);+ let index =+ usize::try_from(index).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| bad("widget must be a positive 1-based index"))?;+ Ok((index, value.to_owned()))+ })+ .transpose()?,name: a.opt_str("name")?.map(str::to_owned),tooltip: a.opt_str("tooltip")?.map(str::to_owned),+ caption: a+ .opt_str("caption")?+ .map(|caption| -> Result<_> {+ let wi = a.opt_int("widget")?.unwrap_or(1);+ let wi =+ usize::try_from(wi).ok().and_then(|wi| wi.checked_sub(1)).ok_or_else(|| bad("widget must be a positive 1-based index"))?;+ Ok((wi, caption.to_owned()))+ })+ .transpose()?,read_only: a.opt_bool("read_only")?,required: a.opt_bool("required")?,multiline: a.opt_bool("multiline")?,diff --cc crates/automation/src/tools.rsindex a3a9723dd,53c4582af..308db977d--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@@ -379,9 -474,9 +474,10 @@@ pub fn tools() -> Vec<ToolDef>"field": { "type": "string", "description": "The field's current name." },"fields": { "type": "array", "items": { "type": "string" }, "minItems": 1, "maxItems": 1000, "uniqueItems": true, "description": "Apply the same changes to these fields in one atomic edit. Use either field or fields." },"name": { "type": "string" },- "export_value": { "type": "string", "minLength": 1, "description": "Checkbox/radio export value; not Off; at most 4096 UTF-8 bytes." },- "widget": { "type": "integer", "minimum": 1, "description": "1-based widget for export_value (default 1)." },"tooltip": { "type": "string" },++ "export_value": { "type": "string", "description": "Checkbox/radio export value; preserves appearance states and selection. Requires a single field." },+ "caption": { "type": "string", "description": "Normal push-button label; an empty string clears it. Requires a single field." },- "widget": { "type": "integer", "minimum": 1, "description": "Widget whose caption changes (1-based, default 1). Requires caption. See form_fields.captions." },++ "widget": { "type": "integer", "minimum": 1, "description": "Widget whose caption or export value changes (1-based, default 1). Requires caption or export_value. See form_fields.captions and export_values." },"read_only": { "type": "boolean" },"required": { "type": "boolean" },"multiline": { "type": "boolean" },diff --cc crates/forms/README.mdindex bc8e19fc9,93b65bd14..71edbb830--- a/crates/forms/README.md+++ b/crates/forms/README.md@@@ -76,3 -108,3 +108,7 @@@ Rich-text values and exact appearance mexecution and FDF/XFDF exchange are integrated through the engine; this crate providesfield actions and native AF rules. `/MK /R` rotation (0, 90, 180, 270) is drawn into theappearance.++++## Button export values++++`FieldProps::export_value` edits a zero-based widget's `/Opt` value while preserving appearance names, `/AP`, `/AS`, `/V` and `/DV`. Widgets sharing an on-state remain consistent. Export-only changes do not regenerate appearances. Invalid indices, empty/Off values and ambiguous/conflicting mappings are rejected. `Field::export_values` resolves selected states for data export.diff --cc crates/forms/src/author/edit.rsindex 000000000,54a05f3db..66cc53e7cmode 000000,100644..100644--- a/crates/forms/src/author/edit.rs+++ b/crates/forms/src/author/edit.rs@@@ -1,0 -1,567 +1,609 @@@+ use super::join::{check_join, join_radio_group};+ use super::look::{BorderStyle, da_string, patch_da, patch_widget_look, redraw_widgets};+ use super::tree::{ancestor_sets, attach, check_place, child_named, clash, detach, ensure_form, inherited, name_parts, own_inherited};+ use super::{Dict, Document, Field, FieldKind, FieldProps, FormError, MIN_FIELD_SIDE, ObjRef, Object, PdfString, fields, flags, invalid};++ /// Swap width and height, keeping the center. `None` when that is not a usable widget.+ fn swapped_around_center(r: [f64; 4]) -> Option<[f64; 4]> {+ if !r.iter().all(|v| v.is_finite()) {+ return None;+ }+ let (x0, y0, x1, y1) = (r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3]));+ let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);+ let (nw, nh) = (y1 - y0, x1 - x0);+ let out = [cx - nw / 2.0, cy - nh / 2.0, cx + nw / 2.0, cy + nh / 2.0];+ (out.iter().all(|v| v.is_finite()) && out[2] - out[0] >= MIN_FIELD_SIDE && out[3] - out[1] >= MIN_FIELD_SIDE).then_some(out)+ }++ /// Re-point a choice field's `/I`, positions in `/Opt`, at the new list `exports` after `/Opt` was+ /// replaced (ISO 32000-2 §12.7.5.4): the positions of the selected `values` still offered. `kept`+ /// are the old `/I` positions carried into the new list, which tell apart options sharing an+ /// export value; a selected value none of them covers takes its first position, by `set_value`'s+ /// rule. Returns them.+ fn repoint_selection(d: &mut Dict, values: &[String], exports: &[String], kept: &[usize]) -> Vec<usize> {+ let mut indices: Vec<usize> = kept.iter().copied().filter(|&i| exports.get(i).is_some_and(|e| values.contains(e))).collect();+ for v in values {+ if !indices.iter().any(|&i| exports.get(i) == Some(v)) {+ indices.extend(exports.iter().position(|e| e == v));+ }+ }+ indices.sort_unstable();+ indices.dedup();+ if indices.is_empty() {+ d.remove(b"I");+ } else {+ d.set(b"I".to_vec(), Object::Array(indices.iter().map(|&i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect()));+ }+ indices+ }++ /// The positions in `/Opt` that a choice field's `/I` holds, those below `count`.+ fn selected_indices(doc: &Document, field: ObjRef, count: usize) -> Vec<usize> {+ let Some(i) = doc.get(field).as_dict().and_then(|d| d.get(b"I").cloned()) else {+ return Vec::new();+ };+ let positions = doc.resolve(&i);+ positions.as_array().map(|a| a.iter().filter_map(|o| usize::try_from(o.as_int()?).ok()).filter(|&n| n < count).collect()).unwrap_or_default()+ }++ /// The items (export value, display text) "Sort items" orders: the new `props.options`, or else+ /// the field's own, whose selection, `/I` included, moves with them.+ fn items_to_sort(doc: &Document, f: &Field, props: &FieldProps) -> (Vec<(String, String)>, Vec<usize>) {+ match &props.options {+ Some(o) => (o.iter().map(|x| (x.clone(), x.clone())).collect(), Vec::new()),+ None => (f.options.clone(), selected_indices(doc, f.obj, f.options.len())),+ }+ }++ /// Sort a choice field's items (export value, display text) by display text, ignoring case, and+ /// write them as `/Opt`; export values stay with their items. Returns the export values in their+ /// new order and the `old` positions carried through the sort.+ fn write_sorted_opt(d: &mut Dict, items: &[(String, String)], old: &[usize]) -> (Vec<String>, Vec<usize>) {+ let mut order: Vec<usize> = (0..items.len()).collect();+ order.sort_by_key(|&i| items.get(i).map(|(_, display)| display.to_lowercase()));+ let sorted: Vec<&(String, String)> = order.iter().filter_map(|&i| items.get(i)).collect();+ let opt = sorted+ .iter()+ .map(|(e, disp)| {+ if e == disp {+ Object::String(PdfString::text(disp))+ } else {+ Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(disp))])+ }+ })+ .collect();+ d.set(b"Opt".to_vec(), Object::Array(opt));+ let carried = old.iter().filter_map(|o| order.iter().position(|i| i == o)).collect();+ (sorted.into_iter().map(|(e, _)| e.clone()).collect(), carried)+ }+++/// Build /Opt before modifying the document, preserving appearance states and selection.++fn button_export_options(f: &Field, index: usize, value: &str) -> Result<Vec<Object>, FormError> {++ if !matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) {++ return invalid("only check boxes and radio buttons have an export value");++ }++ if value.is_empty() || value == "Off" || value.len() > 4096 {++ return invalid("export value must be non-empty, at most 4096 bytes, and not Off");++ }++ let widget = f.widgets.get(index).ok_or_else(|| FormError::Invalid("button widget index is out of range".into()))?;++ let state = widget.on_state.as_deref().ok_or_else(|| FormError::Invalid("button has no on appearance state".into()))?;++ if !f.options.is_empty() && f.options.len() != f.widgets.len() {++ return invalid("button export options do not match its widgets");++ }++ let previous = f.export_of(index);++ let mut out = Vec::with_capacity(f.widgets.len());++ for (i, w) in f.widgets.iter().enumerate() {++ let export = f.export_of(i).ok_or_else(|| FormError::Invalid("button has no on appearance state".into()))?;++ let same_state = w.on_state.as_deref() == Some(state);++ if !same_state && (export == value || w.on_state.as_deref() == Some(value)) {++ return invalid("export value conflicts with another button choice");++ }++ if same_state && Some(export) != previous {++ return invalid("widgets with the same appearance state have conflicting export values");++ }++ out.push(Object::String(PdfString::text(if same_state { value } else { export })));++ }++ Ok(out)++}+++ /// Change a field's properties (General and Options tabs) and redraw it.+ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<String, FormError> {+ if props.font_size.is_some_and(|size| !size.is_finite() || size < 0.0) {+ return invalid("font size must be a finite, non-negative number");+ }+ if let Some(patch) = &props.appearance {+ if props.look.is_some() {+ return invalid("give an appearance patch or a complete look, not both");+ }+ patch.validate()?;+ }+ let all = fields(doc);+ let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?.clone();++ let export_options = props.export_value.as_ref().map(|(index, value)| button_export_options(&f, *index, value)).transpose()?;++ if props.export_value.is_some() && props.options.is_some() {++ return invalid("give export_value or options, not both");++ }+ // Refuse a wrong type/index before any other requested property is written.+ if let Some((wi, _)) = &props.caption {+ if f.kind != FieldKind::PushButton {+ return invalid("only push buttons have a caption");+ }+ if f.widgets.get(*wi).is_none() {+ return invalid(format!("{name} has no widget {}", wi.saturating_add(1)));+ }+ }+ // Validated before anything is written, so a refused rotation leaves the document unchanged.+ // `Some(Some(rect))`: the widget's axis changes and it gets the swapped rectangle.+ let mut rotated_rect: Option<Option<[f64; 4]>> = None;+ if let Some((wi, rot)) = props.rotation {+ if !matches!(rot, 0 | 90 | 180 | 270) {+ return invalid("rotation must be 0, 90, 180 or 270 degrees");+ }+ let Some(w) = f.widgets.get(wi) else {+ return invalid(format!("{name} has no widget {}", wi.saturating_add(1)));+ };+ let axis_change = (w.rotation % 180 == 0) != (rot % 180 == 0);+ rotated_rect = Some(None);+ if axis_change && props.rect.is_none() {+ let Some(rect) = swapped_around_center(w.rect) else { return invalid("the field is too small") };+ rotated_rect = Some(Some(rect));+ }+ }+ // A locked field only takes unlocking (Acrobat greys its properties out).+ if f.locked() && props.locked != Some(false) && *props != (FieldProps { locked: props.locked, ..FieldProps::default() }) {+ return invalid(format!("{name} is locked: unlock it first"));+ }++ if let Some(options) = export_options.as_ref()++ && *props == (FieldProps { export_value: props.export_value.clone(), ..FieldProps::default() })++ {++ doc.update_dict(f.obj, |d| d.set(b"Opt".to_vec(), Object::Array(options.clone())))?;++ return Ok(name.to_string());++ }+ if let Some(lock) = props.locked {+ for w in &f.widgets {+ let flags = doc.get(w.obj).as_dict().and_then(|d| d.get(b"F").and_then(|v| doc.resolve(v).as_int())).unwrap_or(0);+ let v = if lock { flags | 128 } else { flags & !128 };+ doc.update_dict(w.obj, |d| d.set(b"F".to_vec(), Object::Int(v)))?;+ }+ if *props == (FieldProps { locked: props.locked, ..FieldProps::default() }) {+ return Ok(name.to_string());+ }+ }+ if let Some(acts) = &props.actions {+ crate::set_field_actions(doc, name, acts)?;+ }+ // A radio button renamed to another radio group's name joins that group (#4949). The other+ // properties are written first, to this field, and its buttons then move.+ let (new_name, join) = rename_field(doc, &all, &f, name, props)?;+ // The new default appearance when the size or the look changes.+ let size = props.font_size.unwrap_or_else(|| crate::appearance::parse_da(&f.da).size);+ let new_da = match &props.look {+ Some(l) => da_string(l.font, size, l.text),+ None => patch_da(&f.da, props.font_size, &props.appearance.unwrap_or_default()),+ };+ if props.look.is_some() || props.appearance.is_some_and(|p| p.font.is_some()) {+ ensure_form(doc)?;+ }+ let mut ff = f.flags;+ let mut set_flag = |flag: u32, on: Option<bool>| {+ if let Some(on) = on {+ if on {+ ff |= flag;+ } else {+ ff &= !flag;+ }+ }+ };+ set_flag(flags::READ_ONLY, props.read_only);+ set_flag(flags::REQUIRED, props.required);+ if f.kind == FieldKind::Text {+ set_flag(flags::MULTILINE, props.multiline);+ }+ for (flag, on) in &props.flags {+ set_flag(*flag, Some(*on));+ }+ // A comb spreads a fixed number of characters across the field: it needs a limit and+ // excludes multi-line, password, file selection and scrolling (ISO 32000-2 Table 229).+ if f.kind == FieldKind::Text && ff & flags::COMB != 0 {+ let limit = match props.max_len {+ Some(m) => m,+ None => f.max_len,+ };+ if limit.is_none_or(|m| m == 0) {+ return invalid("a comb of characters needs a character limit");+ }+ ff &= !(flags::MULTILINE | flags::PASSWORD | flags::FILE_SELECT);+ }+ if let Some(q) = props.quadding+ && !(0..=2).contains(&q)+ {+ return invalid("alignment is 0 (left), 1 (centre) or 2 (right)");+ }+ if props.options.as_ref().is_some_and(Vec::is_empty) && matches!(f.kind, FieldKind::Combo | FieldKind::List) {+ return invalid("a list needs at least one option");+ }+ if props.check_style.is_some() && !matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) {+ return invalid("only check boxes and radio buttons have a check style");+ }+ let mut list_picked = None;+ let (sort_items, old_selection) = items_to_sort(doc, &f, props);+ let parent_default = ancestor_sets(doc, f.obj, b"DV");+ doc.update_dict(f.obj, |d| {+ d.set(b"Ff".to_vec(), Object::Int(ff as i64));+ if let Some(t) = &props.tooltip {+ if t.is_empty() {+ d.remove(b"TU");+ } else {+ d.set(b"TU".to_vec(), PdfString::text(t));+ }+ }+ if let Some(m) = props.max_len {+ match m {+ Some(m) => d.set(b"MaxLen".to_vec(), Object::Int(m as i64)),+ None => {+ d.remove(b"MaxLen");+ }+ }+ }+ // The export values in `/Opt` order once it is rewritten, for re-pointing `/I`.+ let mut new_exports: Option<Vec<String>> = None;+ let mut kept = Vec::new();++ if let Some(options) = &export_options {++ d.set(b"Opt".to_vec(), Object::Array(options.clone()));++ }+ if let Some(opts) = &props.options {+ d.set(b"Opt".to_vec(), Object::Array(opts.iter().map(|o| Object::String(PdfString::text(o))).collect()));+ new_exports = Some(opts.clone());+ }+ // "Sort items": the list itself is kept in order (export values stay with their items).+ if ff & flags::SORT != 0 && matches!(f.kind, FieldKind::Combo | FieldKind::List) {+ let (exports, carried) = write_sorted_opt(d, &sort_items, &old_selection);+ new_exports = Some(exports);+ kept = carried;+ }+ if let Some(exports) = &new_exports+ && matches!(f.kind, FieldKind::Combo | FieldKind::List)+ {+ list_picked = Some((repoint_selection(d, &f.value, exports, &kept), exports.len()));+ }+ if let Some(q) = props.quadding {+ d.set(b"Q".to_vec(), Object::Int(q));+ }+ match &props.default_value {+ // Buttons name their default state; text and choices hold a string.+ Some(Some(v)) if matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) => d.set(b"DV".to_vec(), Object::Name(crate::name_bytes(v))),+ Some(Some(v)) => d.set(b"DV".to_vec(), PdfString::text(v)),+ // `/DV` is inheritable: with an ancestor's in place, removing the field's own would+ // bring that one back, so the field keeps an empty default of its own instead.+ Some(None) if parent_default && matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) => {+ d.set(b"DV".to_vec(), Object::Name(b"Off".to_vec()))+ }+ Some(None) if parent_default => d.set(b"DV".to_vec(), PdfString::text("")),+ Some(None) => {+ d.remove(b"DV");+ }+ None => {}+ }+ if props.font_size.is_some() || props.look.is_some() || props.appearance.is_some_and(|p| p.font.is_some() || p.text.is_some()) {+ d.set(b"DA".to_vec(), PdfString::literal(new_da.clone().into_bytes()));+ }+ })?;+ if props.appearance.is_some() || (props.font_size.is_some() && props.look.is_none()) {+ let patch = &props.appearance.unwrap_or_default();+ for w in &f.widgets {+ patch_widget_look(doc, w, patch)?;+ // A widget's own /DA overrides its field's /DA. Patch that override separately+ // rather than replacing its font or colour with the first widget's defaults.+ if w.obj != f.obj && (props.font_size.is_some() || patch.font.is_some() || patch.text.is_some()) {+ let da = doc+ .get(w.obj)+ .as_dict()+ .and_then(|d| d.get(b"DA").cloned())+ .map(|v| doc.resolve(&v))+ .and_then(|v| v.as_string().map(|s| s.to_text()));+ if let Some(da) = da {+ let da = patch_da(&da, props.font_size, patch);+ doc.update_dict(w.obj, |d| d.set(b"DA".to_vec(), PdfString::literal(da.into_bytes())))?;+ }+ }+ }+ }+ apply_widget_style_props(doc, &f, name, props)?;+ if props.format.is_some() || props.validate.is_some() || props.calculate.is_some() {+ if !matches!(f.kind, FieldKind::Text | FieldKind::Combo) {+ return invalid("only text fields and drop-down lists have format, validate and calculate scripts");+ }+ let mut aa = doc+ .get(f.obj)+ .as_dict()+ .and_then(|d| d.get(b"AA").cloned())+ .map(|a| doc.resolve(&a))+ .and_then(|a| a.as_dict().cloned())+ .unwrap_or_default();+ let action = |js: &str| -> Object {+ let mut a = Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), PdfString::literal(js.as_bytes().to_vec()));+ Object::Dict(a)+ };+ if let Some(fm) = &props.format {+ aa.remove(b"F");+ aa.remove(b"K");+ if let Some((fjs, kjs)) = crate::af::format_js(fm) {+ if !fjs.is_empty() {+ aa.set(b"F".to_vec(), action(&fjs));+ }+ aa.set(b"K".to_vec(), action(&kjs));+ }+ }+ if let Some(v) = &props.validate {+ aa.remove(b"V");+ if let Some(js) = crate::af::validate_js(v) {+ aa.set(b"V".to_vec(), action(&js));+ }+ }+ if let Some(c) = &props.calculate {+ aa.remove(b"C");+ if let Some(js) = crate::af::calculate_js(c) {+ aa.set(b"C".to_vec(), action(&js));+ }+ crate::calc_order::keep_listed(doc, f.obj, *c != crate::af::Calculate::None)?;+ }+ doc.update_dict(f.obj, |d| {+ if aa.is_empty() {+ d.remove(b"AA");+ } else {+ d.set(b"AA".to_vec(), Object::Dict(aa));+ }+ })?;+ }+ let only = apply_late_widget_props(doc, &f, props, &new_da, rotated_rect)?;+ scroll_list(doc, f.obj, list_picked)?;+ redraw_or_join(doc, &f, name, &new_name, join.as_ref(), only)?;+ if props.calculate.is_some() {+ crate::recalculate(doc)?;+ }+ Ok(new_name)+ }++ /// Apply a new name from `props`: rename the field, move it under the parents a full name+ /// names, or, for a radio button named after another radio group, pick that group to join.+ /// Returns the field's new full name and the group it joins.+ fn rename_field(doc: &mut Document, all: &[Field], f: &Field, name: &str, props: &FieldProps) -> Result<(String, Option<Field>), FormError> {+ let mut new_name = name.to_string();+ let mut join = None;+ if let Some(n) = props.name.as_deref().map(str::trim).filter(|n| *n != f.name) {+ // A full name under the same parents only renames the field's own part (the editor+ // shows nested fields by their full name): it isn't moved, so it keeps its place and+ // goes on inheriting from its parents.+ let n = match (n.rsplit_once('.'), f.name.rsplit_once('.')) {+ (Some((parents, own)), Some((current, _))) if parents == current => own,+ _ => n,+ };+ let full = match f.name.rsplit_once('.') {+ Some((parents, _)) if !n.contains('.') => format!("{parents}.{n}"),+ _ => n.to_string(),+ };+ let group = all.iter().find(|x| x.obj != f.obj && x.kind == FieldKind::Radio && x.name == full);+ if let Some(group) = group.filter(|_| f.kind == FieldKind::Radio) {+ check_join(doc, f, group)?;+ join = Some(group.clone());+ new_name = full;+ } else if n.contains('.') {+ // A full name: the field moves under the parent fields it names (#2696).+ let parts = name_parts(n)?;+ if let Some(why) = all.iter().filter(|x| x.obj != f.obj).find_map(|x| clash(n, &x.name)) {+ return invalid(why);+ }+ let af = ensure_form(doc)?;+ // Checked before anything changes, so a refused move leaves the field as it was.+ let add = inherited(doc, f.obj);+ check_place(doc, af, f.obj, &parts, &add)?;+ // From here a failure (a write that `check_place` couldn't foresee) would leave the+ // field half moved in `doc`. The engine runs every edit on a copy of the document and+ // keeps it only when the edit succeeds (`Session::apply`), so the open document never+ // sees that.+ own_inherited(doc, f.obj, &add)?;+ detach(doc, f.obj)?;+ attach(doc, af, f.obj, &parts)?;+ new_name = n.to_string();+ } else {+ if n.is_empty() {+ return invalid("field names can't be empty");+ }+ // Rename the terminal part (the field's own /T). The parents' part stays, so the name+ // that must be free is the full one: `MASTER.a` renamed to `b` takes `MASTER.b` (ISO+ // 32000-2 §12.7.4.2). The field itself is no clash when it keeps its own name.+ let prefix = f.name.rsplit_once('.').map(|(p, _)| format!("{p}.")).unwrap_or_default();+ new_name = format!("{prefix}{n}");+ if let Some(why) = all.iter().filter(|x| x.obj != f.obj).find_map(|x| clash(&new_name, &x.name)) {+ return invalid(why);+ }+ // A node of that name beside it that isn't a terminal field, such as a parent+ // field left empty by a move.+ let af = ensure_form(doc)?;+ let parent = doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent"));+ if child_named(doc, af, parent, n).is_some_and(|r| r != f.obj) {+ return invalid(format!("a field named {new_name:?} already exists"));+ }+ doc.update_dict(f.obj, |d| d.set(b"T".to_vec(), PdfString::text(n)))?;+ }+ // Calculations read the field by its new name, unless another field keeps the old one.+ if all.iter().filter(|x| x.name == f.name).count() == 1 {+ rename_in_calculations(doc, all, &f.name, &new_name)?;+ }+ }+ Ok((new_name, join))+ }++ fn apply_widget_style_props(doc: &mut Document, f: &Field, name: &str, props: &FieldProps) -> Result<(), FormError> {+ if let Some(l) = &props.look {+ let arr = |c: [f64; 3]| Object::Array(c.iter().map(|v| Object::Real(v.clamp(0.0, 1.0))).collect());+ for w in &f.widgets {+ // Resolved first: an indirect /MK keeps its mark, rotation and other entries.+ let mut mk = doc.get(w.obj).as_dict().and_then(|d| d.get(b"MK").map(|m| doc.resolve(m).as_dict().cloned())).flatten().unwrap_or_default();+ doc.update_dict(w.obj, |d| {+ match l.border {+ Some(c) => mk.set(b"BC".to_vec(), arr(c)),+ None => {+ mk.remove(b"BC");+ }+ }+ match l.fill {+ Some(c) => mk.set(b"BG".to_vec(), arr(c)),+ None => {+ mk.remove(b"BG");+ }+ }+ d.set(b"MK".to_vec(), Object::Dict(mk));+ let mut bs = Dict::new();+ bs.set(b"W".to_vec(), Object::Real(l.width.clamp(0.0, 12.0)));+ bs.set(b"S".to_vec(), Object::name(l.style.code()));+ if l.style == BorderStyle::Dashed {+ bs.set(b"D".to_vec(), Object::Array(vec![Object::Int(3)]));+ }+ d.set(b"BS".to_vec(), Object::Dict(bs));+ })?;+ }+ }+ if let Some(style) = props.check_style {+ for w in &f.widgets {+ // Resolved first: an indirect /MK keeps its colours.+ let mut mk = doc.get(w.obj).as_dict().and_then(|d| d.get(b"MK").map(|m| doc.resolve(m).as_dict().cloned())).flatten().unwrap_or_default();+ mk.set(b"CA".to_vec(), PdfString::text(style.code()));+ doc.update_dict(w.obj, |d| d.set(b"MK".to_vec(), Object::Dict(mk)))?;+ }+ }+ if let Some((wi, r)) = props.rect {+ let w = f.widgets.get(wi).ok_or_else(|| FormError::Invalid(format!("{name} has no widget {}", wi + 1)))?;+ let r = [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])];+ if !r.iter().all(|v| v.is_finite()) || r[2] - r[0] < MIN_FIELD_SIDE || r[3] - r[1] < MIN_FIELD_SIDE {+ return invalid("the field is too small");+ }+ doc.update_dict(w.obj, |d| d.set(b"Rect".to_vec(), Object::Array(r.iter().map(|v| Object::Real(*v)).collect())))?;+ }+ Ok(())+ }++ /// Redraw the edited widgets. A radio button joining another group (`join`) is redrawn under its+ /// old name `name` first; then its buttons move, and only they are redrawn as `new_name`, so the+ /// group's own buttons keep their appearances.+ fn redraw_or_join(doc: &mut Document, f: &Field, name: &str, new_name: &str, join: Option<&Field>, only: Option<usize>) -> Result<(), FormError> {+ if let Some(group) = join {+ redraw_widgets(doc, name, only)?;+ join_radio_group(doc, f, group)?;+ let moved: Vec<usize> = fields(doc)+ .into_iter()+ .find(|g| g.name == new_name)+ .map(|g| g.widgets.iter().enumerate().filter(|(_, w)| f.widgets.iter().any(|m| m.obj == w.obj)).map(|(i, _)| i).collect())+ .unwrap_or_default();+ for index in moved {+ redraw_widgets(doc, new_name, Some(index))?;+ }+ Ok(())+ } else {+ redraw_widgets(doc, new_name, only)+ }+ }++ /// A list box scrolls, as for a new value, so its first row is still an option and the+ /// selection is in view. Its rows are measured with the edited font size and rectangle.+ fn scroll_list(doc: &mut Document, field: ObjRef, list_picked: Option<(Vec<usize>, usize)>) -> Result<(), FormError> {+ if let Some((picked, count)) = list_picked+ && let Some(g) = fields(doc).into_iter().find(|g| g.obj == field)+ {+ if let Some((old, new)) = crate::values::list_scroll(&g, &picked, count)+ && old != new+ {+ doc.update_dict(field, |d| d.set(b"TI".to_vec(), Object::Int(i64::try_from(new).unwrap_or(0))))?;+ }+ crate::values::scroll_widgets(doc, &g, &picked, count)?;+ }+ Ok(())+ }++ fn apply_late_widget_props(+ doc: &mut Document,+ f: &Field,+ props: &FieldProps,+ new_da: &str,+ rotated_rect: Option<Option<[f64; 4]>>,+ ) -> Result<Option<usize>, FormError> {+ // A complete look replaces widget /DA overrides. Partial changes were patched above+ // against each override, including size-only changes that keep its font and colour.+ if props.look.is_some() {+ for w in &f.widgets {+ if w.obj != f.obj {+ doc.update_dict(w.obj, |d| {+ if d.contains(b"DA") {+ d.set(b"DA".to_vec(), PdfString::literal(new_da.to_owned().into_bytes()));+ }+ })?;+ }+ }+ }+ if let (Some((wi, rot)), Some(swapped)) = (props.rotation, rotated_rect)+ && let Some(w) = f.widgets.get(wi)+ {+ if let Some(rect) = swapped {+ doc.update_dict(w.obj, |d| d.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect())))?;+ }+ let mut mk = doc.get(w.obj).as_dict().and_then(|d| d.get(b"MK").map(|m| doc.resolve(m).as_dict().cloned())).flatten().unwrap_or_default();+ if rot == 0 {+ mk.remove(b"R");+ } else {+ mk.set(b"R".to_vec(), Object::Int(rot));+ }+ doc.update_dict(w.obj, |d| {+ if mk.is_empty() {+ d.remove(b"MK");+ } else {+ d.set(b"MK".to_vec(), Object::Dict(mk));+ }+ })?;+ }+ if let Some((wi, caption)) = &props.caption+ && let Some(w) = f.widgets.get(*wi)+ {+ // Copy an indirect/shared MK before patching it; colours, icons, rotation and+ // unknown entries belong to this widget, and other owners keep their old label.+ let mut mk = doc.get(w.obj).as_dict().and_then(|d| d.get(b"MK").map(|m| doc.resolve(m).as_dict().cloned())).flatten().unwrap_or_default();+ mk.set(b"CA".to_vec(), PdfString::text(caption));+ doc.update_dict(w.obj, |d| d.set(b"MK".to_vec(), Object::Dict(mk)))?;+ }+ // A label-only edit must not replace another widget's custom appearances.+ let only = props.caption.as_ref().filter(|_| *props == (FieldProps { caption: props.caption.clone(), ..Default::default() })).map(|(wi, _)| *wi);+ Ok(only)+ }++ /// Name field `old` `new` in each field's Calculate script that reads it+ /// ([`crate::af::rename_in_calculation`]).+ fn rename_in_calculations(doc: &mut Document, all: &[Field], old: &str, new: &str) -> Result<(), FormError> {+ let aa_of =+ |doc: &Document, r: ObjRef| doc.get(r).as_dict().and_then(|d| d.get(b"AA").map(|a| doc.resolve(a))).and_then(|a| a.as_dict().cloned());+ for f in all {+ // The script is the field's, or its only widget's when the field has none, as+ // `actions_of` reads it.+ let only_widget = || match f.widgets.as_slice() {+ [w] => aa_of(doc, w.obj).map(|aa| (w.obj, aa)),+ _ => None,+ };+ let Some((owner, mut aa)) = aa_of(doc, f.obj).map(|aa| (f.obj, aa)).or_else(only_widget) else { continue };+ let Some(mut action) = aa.get(b"C").and_then(|a| doc.resolve(a).as_dict().cloned()) else { continue };+ let js = match action.get(b"JS").map(|js| doc.resolve(js)).as_deref() {+ Some(Object::String(s)) => s.to_text(),+ // A stream that isn't UTF-8 reads with replacement characters, which must not be+ // written back in place of what it holds.+ Some(Object::Stream(s)) => match s.decoded().ok().and_then(|b| String::from_utf8(b).ok()) {+ Some(js) => js,+ None => continue,+ },+ _ => continue,+ };+ let Some(js) = crate::af::rename_in_calculation(&js, old, new) else { continue };+ action.set(b"JS".to_vec(), PdfString::text(&js));+ aa.set(b"C".to_vec(), Object::Dict(action));+ doc.update_dict(owner, |d| d.set(b"AA".to_vec(), Object::Dict(aa)))?;+ }+ Ok(())+ }diff --cc crates/forms/src/tests.rsindex 074df0d3b,ac414af2a..5d05659cf--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@@ -2144,19 -3261,2098 +3261,2154 @@@ fn document_scripts_read_each_name_treeassert_eq!(document_scripts_named(&doc), [("init".to_string(), "var ready = true;".to_string())]);}+ /// #3470: a form whose writer left the appearances to the viewer. Field A has an empty one,+ /// B none, C its own (`(old C)`), D is a combo without one, E a check box with states, F a list+ /// box without one, and G only a down appearance (`/D`, no `/N`).+ fn left_to_the_viewer(need_appearances: bool) -> Document {+ let flag = if need_appearances { "/NeedAppearances true " } else { "" };+ document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 13 0 R 14 0 R] >>".into(),+ format!("<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 13 0 R 14 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>"),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (a) /V (Value A) /DA (/Helv 12 Tf 0 g) /Rect [50 700 350 720] /P 3 0 R /AP << /N 11 0 R >> >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (b) /V (Value B) /DA (/Helv 12 Tf 0 g) /Rect [50 650 350 670] /P 3 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (c) /V (Value C) /DA (/Helv 12 Tf 0 g) /Rect [50 600 350 620] /P 3 0 R /AP << /N 12 0 R >> >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Ch /Ff 131072 /T (d) /Opt [(Red) (Blue)] /V (Blue) /DA (/Helv 12 Tf 0 g) /Rect [50 550 350 570] /P 3 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T (e) /V /Yes /AS /Yes /Rect [400 700 415 715] /P 3 0 R /AP << /N << /Yes 11 0 R /Off 11 0 R >> >> >>".into(),+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(),+ "<< /Length 18 >>\nstream\nBT (old C) Tj ET\nendstream".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Ch /T (f) /Opt [(Green) (Grey)] /V (Green) /DA (/Helv 12 Tf 0 g) /Rect [50 450 350 520] /P 3 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (g) /V (Value G) /DA (/Helv 12 Tf 0 g) /Rect [50 400 350 420] /P 3 0 R /AP << /D 11 0 R >> >>".into(),+ ])+ }++ /// #3470: with `/NeedAppearances`, every text and choice widget of the display copy is drawn+ /// from its value, its own appearance or not; buttons keep their states, and the document+ /// itself is untouched.+ #[test]+ fn need_appearances_draws_every_text_and_choice_field_in_the_display_copy() {+ let doc = left_to_the_viewer(true);+ let copy = with_field_appearances(&doc).expect("fields to draw");+ let all = fields(©);+ for (name, value) in+ [("a", "(Value A) Tj"), ("b", "(Value B) Tj"), ("c", "(Value C) Tj"), ("d", "(Blue) Tj"), ("f", "(Green) Tj"), ("g", "(Value G) Tj")]+ {+ let shown = ap(©, &field(&all, name).widgets[0]);+ assert!(shown.contains(value), "{name}: {shown}");+ }+ let e = |d: &Document| d.get(field(&fields(d), "e").widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());+ assert_eq!(e(©), e(&doc), "the check box keeps its states");+ let original = fields(&doc);+ assert_eq!(ap(&doc, &field(&original, "a").widgets[0]).trim_end(), "q\nQ", "the document keeps its own appearances");+ assert!(doc.get(field(&original, "b").widgets[0].obj).as_dict().is_some_and(|w| !w.contains(b"AP")));+ }++ /// #3470: without `/NeedAppearances`, only widgets with no normal appearance are drawn; an+ /// appearance the file has, even an empty one, is the file's. A form with all of them needs no+ /// copy.+ #[test]+ fn without_need_appearances_only_missing_appearances_are_drawn() {+ let doc = left_to_the_viewer(false);+ let copy = with_field_appearances(&doc).expect("b, d, f and g have none");+ let all = fields(©);+ assert_eq!(ap(©, &field(&all, "a").widgets[0]).trim_end(), "q\nQ");+ assert!(ap(©, &field(&all, "b").widgets[0]).contains("(Value B) Tj"));+ assert_eq!(ap(©, &field(&all, "c").widgets[0]).trim_end(), "BT (old C) Tj ET");+ assert!(ap(©, &field(&all, "d").widgets[0]).contains("(Blue) Tj"));+ assert!(ap(©, &field(&all, "f").widgets[0]).contains("(Green) Tj"));+ assert!(ap(©, &field(&all, "g").widgets[0]).contains("(Value G) Tj"), "a down appearance alone is no normal one");+ assert!(with_field_appearances(©).is_none(), "every widget has one now");+ }++ /// #3470: refreshing the display copy redraws only the widgets whose inputs changed. Typing in+ /// one field of a form that leaves every appearance to the viewer otherwise redrew all of them.+ #[test]+ fn the_field_appearance_cache_redraws_only_what_changed() {+ let mut doc = left_to_the_viewer(true);+ let mut cache = FieldAppearanceCache::default();+ with_field_appearances_cached(&doc, &mut cache).expect("fields to draw");+ let drawn = cache.builds();+ assert_eq!(drawn, 6, "a, b, c, d, f and g");+ with_field_appearances_cached(&doc, &mut cache).expect("fields to draw");+ assert_eq!((cache.builds(), cache.hits()), (drawn, drawn), "nothing changed, nothing redrawn");++ set_value(&mut doc, "b", &FieldValue::Text("Typed".into())).unwrap();+ let copy = with_field_appearances_cached(&doc, &mut cache).expect("fields to draw");+ assert_eq!(cache.builds(), drawn + 1, "only b is redrawn");+ assert!(ap(©, &field(&fields(©), "b").widgets[0]).contains("(Typed) Tj"), "and shows its new value");+ assert!(ap(©, &field(&fields(©), "a").widgets[0]).contains("(Value A) Tj"), "a reuses its drawing");+ }++ /// #3470: each kind of input a field's drawing depends on invalidates its cached appearance when+ /// it changes, wherever it lives: the parent field's value, the form's `/DA`, an indirect `/MK`+ /// and a `/DR` font. Field H is a parent with one kid widget; I is a plain field.+ #[test]+ fn the_field_appearance_cache_sees_every_input() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>".into(),+ "<< /Fields [5 0 R 7 0 R] /NeedAppearances true /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 8 0 R >> >> >>".into(),+ "<< /FT /Tx /T (h) /V (Kid value) /Kids [6 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [50 700 350 720] /P 3 0 R /MK 9 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (i) /V (Plain) /Rect [50 650 350 670] /P 3 0 R >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ "<< /BG [1 1 1] >>".into(),+ ]);+ let r = |n: u32| pdfcraft_cos::ObjRef::new(n, 0);+ let mut cache = FieldAppearanceCache::default();+ let mut redraw = |doc: &Document| {+ let before = cache.builds();+ let copy = with_field_appearances_cached(doc, &mut cache).expect("fields to draw");+ (cache.builds() - before, copy)+ };+ assert_eq!(redraw(&doc).0, 2);+ assert_eq!(redraw(&doc).0, 0, "unchanged");++ doc.update_dict(r(5), |d| d.set(b"V".to_vec(), Object::String(PdfString::text("New value")))).unwrap();+ let (n, copy) = redraw(&doc);+ assert_eq!(n, 1, "the parent's value: only its kid");+ assert!(ap(©, &field(&fields(©), "h").widgets[0]).contains("(New value) Tj"));++ doc.update_dict(r(9), |d| d.set(b"BG".to_vec(), Object::Array(vec![Object::Int(1), Object::Int(0), Object::Int(0)]))).unwrap();+ let (n, copy) = redraw(&doc);+ assert_eq!(n, 1, "the kid's indirect /MK");+ assert!(ap(©, &field(&fields(©), "h").widgets[0]).contains("1 0 0 rg"), "the new background");++ doc.update_dict(r(4), |d| d.set(b"DA".to_vec(), Object::String(PdfString::text("/Helv 9 Tf 0 g")))).unwrap();+ let (n, copy) = redraw(&doc);+ assert_eq!(n, 2, "the form's /DA: both fields");+ assert!(ap(©, &field(&fields(©), "i").widgets[0]).contains("/Helv 9 Tf"));++ doc.update_dict(r(8), |d| d.set(b"BaseFont".to_vec(), Object::Name(b"Courier".to_vec()))).unwrap();+ assert_eq!(redraw(&doc).0, 2, "a /DR font: both fields");+ }++ /// #3470: an indirect `/DR` and an indirect `/Font` inside it are inputs too, with a font written+ /// directly into the `/Font` dictionary, and so is the form's `/DA` when it is an indirect string.+ #[test]+ fn the_field_appearance_cache_sees_indirect_resources() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),+ "<< /Fields [5 0 R] /NeedAppearances true /DA 8 0 R /DR 6 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (i) /V (Plain) /Rect [50 650 350 670] /P 3 0 R >>".into(),+ "<< /Font 7 0 R >>".into(),+ "<< /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >>".into(),+ "(/Helv 12 Tf 0 g)".into(),+ ]);+ let r = |n: u32| pdfcraft_cos::ObjRef::new(n, 0);+ let mut cache = FieldAppearanceCache::default();+ let mut redraw = |doc: &Document| {+ let before = cache.builds();+ with_field_appearances_cached(doc, &mut cache).expect("a field to draw");+ cache.builds() - before+ };+ assert_eq!(redraw(&doc), 1);+ assert_eq!(redraw(&doc), 0);+ let courier = || {+ let mut f = Dict::new();+ f.set(b"Type".to_vec(), Object::Name(b"Font".to_vec()));+ f.set(b"Subtype".to_vec(), Object::Name(b"Type1".to_vec()));+ f.set(b"BaseFont".to_vec(), Object::Name(b"Courier".to_vec()));+ Object::Dict(f)+ };+ doc.update_dict(r(7), |d| d.set(b"Helv".to_vec(), courier())).unwrap();+ assert_eq!(redraw(&doc), 1, "the indirect /Font dictionary");+ doc.update_dict(r(6), |d| {+ let mut fonts = Dict::new();+ fonts.set(b"Helv".to_vec(), courier());+ d.set(b"Font".to_vec(), Object::Dict(fonts));+ })+ .unwrap();+ assert_eq!(redraw(&doc), 1, "the indirect /DR");+ doc.set(r(8), Object::String(PdfString::text("/Helv 9 Tf 0 g")));+ assert_eq!(redraw(&doc), 1, "the form's indirect /DA");+ }++ #[test]+ fn page_walk_skips_repeated_and_cyclic_kids_without_queueing_them() {+ let mut doc = fixture();+ let root = ObjRef { num: 2, generation: 0 };+ let page = ObjRef { num: 3, generation: 0 };+ // A cycle back to the root, then the page 128 times over.+ let mut kids = vec![Object::Ref(root)];+ kids.extend(std::iter::repeat_n(Object::Ref(page), 128));+ doc.update_dict(root, |d| d.set(b"Kids".to_vec(), Object::Array(kids))).unwrap();+ let mut walk = PageWalk::new(&doc, root);+ assert_eq!(walk.next(), Some(page));+ assert!(walk.pending.len() <= 2, "repeated kids retained {} pending entries", walk.pending.len());+ assert_eq!(walk.next(), None);+ assert_eq!(page_refs(&doc), [page]);+ }++ /// A Calculate script naming thousands of fields is merged with the field's other reads in one+ /// pass, not by searching the names so far for each one.+ #[test]+ fn a_script_reading_many_fields_merges_its_reads_in_one_pass() {+ use crate::calc_order::NAMES_COMPARED;+ let mut doc = one_page();+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &NewField::Text { multiline: false }, Some("total")).unwrap();+ let n = 2_000;+ let script: String = (0..n).map(|i| format!("getField(\"f{i}\").value + ")).collect::<String>() + "0";+ set_field_script(&mut doc, "total", "calculate", Some(&format!("event.value = {script};"))).unwrap();+ NAMES_COMPARED.with(|c| c.set(0));+ let order = calculation_order(&doc, &fields(&doc));+ assert_eq!(order.fields[0].reads.len(), n);+ let compared = NAMES_COMPARED.with(std::cell::Cell::get);+ assert!(compared <= 4 * n, "{compared} names compared for {n} reads");+ }++ /// 300 fields and 300 document scripts that all name one 1 MiB JavaScript stream.+ fn repeated_script_references() -> Document {+ use pdfcraft_cos::Stream;+ let dict = |entries: Vec<(&[u8], Object)>| -> Object { Object::Dict(entries.into_iter().map(|(k, v)| (k.to_vec(), v)).collect()) };+ let mut doc = Document::new_empty();+ let js = doc.add(Stream::flate(pdfcraft_cos::Dict::new(), &vec![b'x'; 1 << 20]));+ let action = doc.add(dict(vec![(b"S", Object::Name(b"JavaScript".to_vec())), (b"JS", Object::Ref(js))]));+ let fields: Vec<Object> = (0..300)+ .map(|i| {+ Object::Ref(doc.add(dict(vec![+ (b"FT", Object::Name(b"Tx".to_vec())),+ (b"T", Object::String(pdfcraft_cos::PdfString::literal(format!("f{i}")))),+ (b"Rect", Object::Array([0, 0, 10, 10].map(Object::from).to_vec())),+ (b"AA", dict(vec![(b"C", Object::Ref(action))])),+ ])))+ })+ .collect();+ let names: Vec<Object> =+ (0..300).flat_map(|i| [Object::String(pdfcraft_cos::PdfString::literal(format!("s{i:03}"))), Object::Ref(action)]).collect();+ let catalog = doc.add(dict(vec![+ (b"Type", Object::Name(b"Catalog".to_vec())),+ (b"AcroForm", dict(vec![(b"Fields", Object::Array(fields))])),+ (b"Names", dict(vec![(b"JavaScript", dict(vec![(b"Names", Object::Array(names))]))])),+ ]));+ doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(catalog));+ doc+ }++ #[test]+ fn repeated_script_references_share_one_decode_budget() {+ let doc = repeated_script_references();+ let limit = MAX_SCRIPT_BYTES;+ let named: usize = document_scripts_named(&doc).iter().map(|(_, js)| js.len()).sum();+ assert!(named > 0 && named <= limit, "{named} bytes of document scripts");+ let all = fields(&doc);+ assert_eq!(all.len(), 300);+ let calculate: usize = all.iter().filter_map(|f| f.actions.scripts.calculate.as_ref()).map(String::len).sum();+ assert!(calculate > 0 && calculate <= limit, "{calculate} bytes of field scripts");+ }++ /// A widget listed many times, by one field's `/Kids` or by a `/Kids` array several fields share,+ /// is read once: the first field to list it owns it.+ #[test]+ fn a_widget_listed_repeatedly_is_read_once() {+ let kids = "7 0 R ".repeat(500);+ let doc = document(&[+ "<< /Type /Catalog /Pages 4 0 R /AcroForm << /Fields [2 0 R 3 0 R] >> >>".into(),+ "<< /FT /Tx /T (a) /Kids 6 0 R >>".into(),+ "<< /FT /Tx /T (b) /Kids 6 0 R >>".into(),+ "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".into(),+ "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 100 100] /Annots [7 0 R] >>".into(),+ format!("[{kids}]"),+ "<< /Type /Annot /Subtype /Widget /Parent 2 0 R /Rect [0 0 10 10] >>".into(),+ ]);+ let all = fields(&doc);+ let widgets: Vec<usize> = all.iter().map(|f| f.widgets.len()).collect();+ assert_eq!(widgets, [1, 0], "{:?}", all.iter().map(|f| &f.name).collect::<Vec<_>>());+ }++ /// A field of a kind that isn't read doesn't claim the widget it shares with a field that is.+ #[test]+ fn a_skipped_field_leaves_its_widget_to_the_next() {+ let doc = document(&[+ "<< /Type /Catalog /Pages 4 0 R /AcroForm << /Fields [2 0 R 3 0 R] >> >>".into(),+ "<< /FT /Zz /T (odd) /Kids [6 0 R] >>".into(),+ "<< /FT /Tx /T (b) /Kids [6 0 R] >>".into(),+ "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".into(),+ "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 100 100] /Annots [6 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 3 0 R /Rect [0 0 10 10] >>".into(),+ ]);+ let all = fields(&doc);+ let widgets: Vec<(&str, usize)> = all.iter().map(|f| (f.name.as_str(), f.widgets.len())).collect();+ assert_eq!(widgets, [("b", 1)]);+ }++ /// #2696: a dotted name is a full name. `MASTER.first` is a field `first` under a parent field+ /// `MASTER` (a partial name can't contain a period, ISO 32000-2 §12.7.4.2); a second `MASTER.`+ /// name joins that parent; renaming to a dotted name moves the field, keeping what it inherited;+ /// and a name that would make one field both hold a value and hold fields is refused.+ #[test]+ fn dotted_field_names_are_made_with_parent_fields() {+ let mut doc = fixture();+ let top = |doc: &Document| {+ let root = doc.root().unwrap();+ let af = doc.get(root).as_dict().and_then(|d| d.reference(b"AcroForm")).unwrap();+ doc.get(af).as_dict().and_then(|d| d.get(b"Fields").and_then(|o| o.as_array().map(|a| a.len()))).unwrap()+ };+ let own_name = |doc: &Document, f: &Field| doc.get(f.obj).as_dict().and_then(|d| d.get(b"T").and_then(text_of));+ let parent_of = |doc: &Document, f: &Field| doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();+ let text = NewField::Text { multiline: false };+ let before = top(&doc);+ assert_eq!(add_field(&mut doc, 0, [50.0, 300.0, 200.0, 320.0], &text, Some("MASTER.account_firstname")).unwrap(), "MASTER.account_firstname");+ add_field(&mut doc, 0, [50.0, 260.0, 200.0, 280.0], &text, Some("MASTER.street1")).unwrap();+ assert_eq!(top(&doc), before + 1, "one parent field at the top");+ let saved = reopen(&doc);+ let all = fields(&saved);+ let (a, b) = (field(&all, "MASTER.account_firstname"), field(&all, "MASTER.street1"));+ assert_eq!(own_name(&saved, b).as_deref(), Some("street1"), "the field's own name has no period");+ let master = parent_of(&saved, a);+ assert_eq!(parent_of(&saved, b), master, "both under one MASTER");+ assert_eq!(saved.get(master).as_dict().and_then(|d| d.get(b"T").and_then(text_of)).as_deref(), Some("MASTER"));++ // Renaming to a dotted name moves the field: zip joins the existing address parent.+ assert_eq!(set_props(&mut doc, "zip", &FieldProps { name: Some("address.zip".into()), ..FieldProps::default() }).unwrap(), "address.zip");+ assert_eq!(top(&doc), before, "zip left the top");+ let all = fields(&doc);+ let (zip, city) = (field(&all, "address.zip"), field(&all, "address.city"));+ assert_eq!(parent_of(&doc, zip), parent_of(&doc, city));+ assert_eq!(zip.max_len, Some(5), "its own settings move with it");++ // What a moved field inherited stays; what a new field would inherit from a parent it+ // joins doesn't apply to it.+ let address = parent_of(&doc, city);+ doc.update_dict(address, |d| {+ d.set(b"Ff".to_vec(), Object::Int(flags::READ_ONLY as i64));+ d.set(b"V".to_vec(), Object::String(PdfString::literal(b"Springfield".to_vec())));+ })+ .unwrap();+ let city = field(&fields(&doc), "address.city").clone();+ assert!(city.read_only() && city.value == ["Springfield"]);+ set_props(&mut doc, "address.city", &FieldProps { name: Some("billing.city".into()), ..FieldProps::default() }).unwrap();+ let moved = field(&fields(&doc), "billing.city").clone();+ assert!(moved.read_only() && moved.value == ["Springfield"], "the moved field keeps what it inherited");+ // A parent's value, reset value or length limit would pass to a new field under it (review+ // on #2957), and a field can't turn them off: such a parent takes no new field.+ let street = |doc: &mut Document| add_field(doc, 0, [300.0, 300.0, 450.0, 320.0], &text, Some("address.street"));+ for (key, value) in [+ (&b"V"[..], Object::String(PdfString::literal(b"x".to_vec()))),+ (b"DV", Object::String(PdfString::literal(b"x".to_vec()))),+ (b"MaxLen", Object::Int(3)),+ ] {+ doc.update_dict(address, |d| {+ for k in [&b"V"[..], b"DV", b"MaxLen"] {+ d.remove(k);+ }+ d.set(key.to_vec(), value);+ })+ .unwrap();+ let mut copy = doc.clone();+ assert!(street(&mut copy).is_err(), "address holds /{}", String::from_utf8_lossy(key));+ }+ doc.update_dict(address, |d| {+ d.remove(b"MaxLen");+ })+ .unwrap();+ street(&mut doc).unwrap();+ let new = field(&fields(&doc), "address.street").clone();+ assert!(!new.read_only(), "a new field doesn't take its parent's flags");+ assert!(new.value.iter().all(|v| v.is_empty()) && new.max_len.is_none(), "nor a value or length limit: {:?} {:?}", new.value, new.max_len);++ // A parent left empty by a move isn't a terminal field, but its name is still taken.+ add_field(&mut doc, 0, [300.0, 340.0, 450.0, 360.0], &text, Some("box.only")).unwrap();+ set_props(&mut doc, "box.only", &FieldProps { name: Some("elsewhere.only".into()), ..FieldProps::default() }).unwrap();+ assert!(fields(&doc).iter().all(|f| !f.name.starts_with("box")), "box holds no field now");+ let mut copy = doc.clone();+ assert!(add_field(&mut copy, 0, [300.0, 380.0, 450.0, 400.0], &text, Some("box")).is_err(), "a new field named box");+ let mut copy = doc.clone();+ assert!(set_props(&mut copy, "name", &FieldProps { name: Some("box".into()), ..FieldProps::default() }).is_err(), "a rename to box");+ // Under it, the name is free: the empty parent takes a field again.+ add_field(&mut doc, 0, [300.0, 380.0, 450.0, 400.0], &text, Some("box.again")).unwrap();+ // Only a whole path that exists can be taken: under box.sub, made new, "again" is free.+ add_field(&mut doc, 0, [300.0, 420.0, 450.0, 440.0], &text, Some("box.sub.again")).unwrap();+ // A field holding its own value may join a parent holding one; and the parents a new path+ // makes are new, even where an existing field has the name of a later part.+ doc.update_dict(address, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"x".to_vec())))).unwrap();+ set_props(&mut doc, "billing.city", &FieldProps { name: Some("address.city".into()), ..FieldProps::default() }).unwrap();+ assert_eq!(field(&fields(&doc), "address.city").value, ["Springfield"]);+ add_field(&mut doc, 0, [300.0, 460.0, 450.0, 480.0], &text, Some("nope.address.x")).unwrap();+ // Renaming the last part: to its own name is no change; to an empty parent's name beside it+ // is taken.+ assert_eq!(set_props(&mut doc, "address.city", &FieldProps { name: Some("city".into()), ..FieldProps::default() }).unwrap(), "address.city");+ doc.update_dict(address, |d| {+ d.remove(b"V");+ })+ .unwrap();+ add_field(&mut doc, 0, [300.0, 500.0, 450.0, 520.0], &text, Some("address.grp.x")).unwrap();+ set_props(&mut doc, "address.grp.x", &FieldProps { name: Some("elsewhere.x".into()), ..FieldProps::default() }).unwrap();+ assert!(+ set_props(&mut doc.clone(), "address.city", &FieldProps { name: Some("grp".into()), ..FieldProps::default() }).is_err(),+ "address.grp is taken"+ );+ // A move the destination refuses leaves the field where it was (review on #2957): it was+ // taken out of the tree before the destination was checked, and stayed out.+ doc.update_dict(address, |d| d.set(b"MaxLen".to_vec(), Object::Int(3))).unwrap();+ let at_top = top(&doc);+ assert!(set_props(&mut doc, "name", &FieldProps { name: Some("address.name".into()), ..FieldProps::default() }).is_err());+ assert_eq!(top(&doc), at_top, "name is still in the form's /Fields");+ // Nor is what it inherits copied onto it first (review on #2957): src.f inherits /V from src.+ add_field(&mut doc, 0, [300.0, 540.0, 450.0, 560.0], &text, Some("src.f")).unwrap();+ let f = field(&fields(&doc), "src.f").obj;+ let src = doc.get(f).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();+ doc.update_dict(src, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"inh".to_vec())))).unwrap();+ assert!(set_props(&mut doc, "src.f", &FieldProps { name: Some("address.f".into()), ..FieldProps::default() }).is_err());+ assert!(!doc.get(f).as_dict().unwrap().contains(b"V"), "src.f still only inherits its value");+ // What it inherits counts as its own where it goes: with /V on address and no /MaxLen,+ // src.f moves, keeping its value.+ doc.update_dict(address, |d| {+ d.remove(b"MaxLen");+ d.set(b"V".to_vec(), Object::String(PdfString::literal(b"x".to_vec())));+ })+ .unwrap();+ set_props(&mut doc, "src.f", &FieldProps { name: Some("address.f".into()), ..FieldProps::default() }).unwrap();+ assert_eq!(field(&fields(&doc), "address.f").value, ["inh"]);+ doc.update_dict(address, |d| {+ d.remove(b"V");+ })+ .unwrap();+ doc.update_dict(address, |d| {+ d.remove(b"MaxLen");+ })+ .unwrap();++ invalid_dotted_field_names_are_rejected(&mut doc, &text);+ }++ fn invalid_dotted_field_names_are_rejected(doc: &mut Document, text: &NewField) {+ for bad in ["MASTER", "MASTER.street1.x", "MASTER..x", ".x", "x.", "MASTER. "] {+ assert!(add_field(doc, 0, [300.0, 200.0, 450.0, 220.0], text, Some(bad)).is_err(), "{bad:?}");+ assert!(set_props(doc, "name", &FieldProps { name: Some(bad.into()), ..FieldProps::default() }).is_err(), "{bad:?}");+ }+ let deep = vec!["p"; 33].join(".");+ assert!(add_field(doc, 0, [300.0, 200.0, 450.0, 220.0], text, Some(&deep)).is_err(), "too deep");+ assert!(set_props(doc, "name", &FieldProps { name: Some("MASTER.street1".into()), ..FieldProps::default() }).is_err(), "taken");+ }++ /// Review on #2957: a parent left empty by a move keeps its name from the next default name+ /// (`Text1` after `Text1.x` moved away); and a full name that keeps the parents is a plain+ /// rename, so the field stays in its place among its parent's /Kids and keeps inheriting.+ #[test]+ fn empty_parents_and_same_parent_renames() {+ let mut doc = fixture();+ let text = NewField::Text { multiline: false };+ let auto = |doc: &mut Document, y: f64| add_field(doc, 0, [50.0, y, 200.0, y + 20.0], &text, None);+ let mut copy = doc.clone();+ let first = auto(&mut copy, 100.0).unwrap();+ add_field(&mut doc, 0, [50.0, 140.0, 200.0, 160.0], &text, Some(&format!("{first}.x"))).unwrap();+ set_props(&mut doc, &format!("{first}.x"), &FieldProps { name: Some("other.x".into()), ..FieldProps::default() }).unwrap();+ assert!(fields(&doc).iter().all(|f| !f.name.starts_with(&first)), "{first} is an empty parent now");+ let next = auto(&mut doc, 100.0).expect("a default name the empty parent doesn't hold");+ assert_ne!(next, first);++ let all = fields(&doc);+ let city = field(&all, "address.city").obj;+ let address = doc.get(city).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();+ doc.update_dict(address, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"Springfield".to_vec())))).unwrap();+ let kids = |doc: &Document| doc.get(address).as_dict().and_then(|d| d.get(b"Kids").and_then(|o| o.as_array().cloned())).unwrap();+ let before = kids(&doc);+ assert_eq!(+ set_props(&mut doc, "address.city", &FieldProps { name: Some("address.town".into()), ..FieldProps::default() }).unwrap(),+ "address.town"+ );+ assert_eq!(kids(&doc), before, "same place among the kids");+ assert!(!doc.get(city).as_dict().unwrap().contains(b"V"), "still inherits its value rather than owning a copy");+ assert_eq!(field(&fields(&doc), "address.town").value, ["Springfield"]);+ }++ /// Review on #2957: spaces in a typed name. The ends of the whole name are dropped, as Acrobat+ /// does when a field is renamed; a space beside a period stays in the part it belongs to (`a. b`+ /// is `b` with a leading space under `a`), as Acrobat keeps it and as ISO 32000-2 §12.7.4.2+ /// allows: only a period is barred from a partial name.+ #[test]+ fn a_typed_name_loses_its_ends_but_keeps_spaces_beside_periods() {+ let mut doc = fixture();+ let own_name = |doc: &Document, full: &str| {+ let all = fields(doc);+ doc.get(field(&all, full).obj).as_dict().and_then(|d| d.get(b"T").and_then(text_of))+ };+ let text = NewField::Text { multiline: false };+ assert_eq!(add_field(&mut doc, 0, [50.0, 300.0, 200.0, 320.0], &text, Some(" plain ")).unwrap(), "plain");+ assert_eq!(add_field(&mut doc, 0, [50.0, 260.0, 200.0, 280.0], &text, Some("a. b")).unwrap(), "a. b");+ assert_eq!(add_field(&mut doc, 0, [50.0, 220.0, 200.0, 240.0], &text, Some("c .d")).unwrap(), "c .d");+ assert_eq!(set_props(&mut doc, "zip", &FieldProps { name: Some(" e. f ".into()), ..FieldProps::default() }).unwrap(), "e. f");+ let saved = reopen(&doc);+ assert_eq!(own_name(&saved, "plain").as_deref(), Some("plain"));+ assert_eq!(own_name(&saved, "a. b").as_deref(), Some(" b"));+ assert_eq!(own_name(&saved, "c .d").as_deref(), Some("d"));+ assert_eq!(own_name(&saved, "e. f").as_deref(), Some(" f"));+ let parent = |full: &str| {+ let all = fields(&saved);+ let p = saved.get(field(&all, full).obj).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();+ saved.get(p).as_dict().and_then(|d| d.get(b"T").and_then(text_of))+ };+ assert_eq!(parent("c .d").as_deref(), Some("c "), "the space before the period is the parent's");+ assert_eq!(parent("e. f").as_deref(), Some("e"));+ // A part that is only spaces is still empty.+ assert!(add_field(&mut doc, 0, [300.0, 300.0, 450.0, 320.0], &text, Some("g. .h")).is_err());+ }++ /// The form's `/DR /Font` entries, resolved through an indirect `/DR` or `/Font`.+ fn dr_fonts(doc: &Document) -> Dict {+ let af = acroform(doc).unwrap();+ let dr = doc.resolve(af.get(b"DR").unwrap());+ doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap()).as_dict().cloned().unwrap()+ }++ /// #3441: Acrobat shows nothing in a text field it redraws after typing when the field's `/DR`+ /// font is a dictionary written inline. A form PdfCraft makes holds each font as its own object.+ #[test]+ fn a_new_form_holds_its_fonts_as_objects() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ ]);+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();+ let doc = reopen(&doc);+ let fonts = dr_fonts(&doc);+ for (name, base) in [("Helv", "Helvetica"), ("TiRo", "Times-Roman"), ("Cour", "Courier")] {+ let r = fonts.reference(name.as_bytes()).unwrap_or_else(|| panic!("{name} is an object: {fonts:?}"));+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont")), Some(base.as_bytes()));+ }+ }++ /// #3441: a form saved earlier with inline `/DR` fonts gets them as objects once a field is+ /// added, saying the same; an indirect `/Font` dictionary stays the object it was.+ #[test]+ fn inline_form_fonts_become_objects_and_an_indirect_font_dictionary_stays_one() {+ for indirect in [false, true] {+ let font = "/Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> /Mine << /Type /Font /Subtype /Type1 /BaseFont /Symbol >>";+ let (fonts_entry, extra) =+ if indirect { ("6 0 R".to_string(), vec![format!("<< {font} >>")]) } else { (format!("<< {font} >>"), Vec::new()) };+ let mut objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ format!("<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font {fonts_entry} >> >>"),+ "null".into(),+ ];+ objs.extend(extra);+ let mut doc = document(&objs);+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();+ let doc = reopen(&doc);+ let fonts = dr_fonts(&doc);+ for (name, base) in [("Helv", "Helvetica"), ("Mine", "Symbol"), ("TiRo", "Times-Roman")] {+ let r = fonts.reference(name.as_bytes()).unwrap_or_else(|| panic!("{name} is an object (indirect {indirect}): {fonts:?}"));+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont")), Some(base.as_bytes()), "{name} says the same");+ }+ let dr = doc.resolve(acroform(&doc).unwrap().get(b"DR").unwrap());+ assert_eq!(dr.as_dict().unwrap().reference(b"Font").is_some(), indirect, "the /Font dictionary keeps its form");+ }+ }++ /// #3441: an indirect `/DR` stays the object it is, and a form whose three standard fonts are+ /// all already there (inline) still gets them as objects, though none is added.+ #[test]+ fn an_indirect_resource_dictionary_and_a_complete_inline_set_are_handled() {+ let inline = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";+ let all = format!(+ "/Helv {inline} /TiRo << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> /Cour << /Type /Font /Subtype /Type1 /BaseFont /Courier >>"+ );+ for indirect_dr in [false, true] {+ let dr = if indirect_dr { "5 0 R".to_string() } else { format!("<< /Font << {all} >> >>") };+ let doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ format!("<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR {dr} >>"),+ format!("<< /Font << {all} >> >>"),+ ]);+ let mut doc = doc;+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();+ let doc = reopen(&doc);+ let fonts = dr_fonts(&doc);+ for name in ["Helv", "TiRo", "Cour"] {+ assert!(fonts.reference(name.as_bytes()).is_some(), "{name} is an object (indirect /DR {indirect_dr}): {fonts:?}");+ }+ assert_eq!(acroform(&doc).unwrap().reference(b"DR").is_some(), indirect_dr, "/DR keeps its form");+ }+ }++ /// #3441: fonts the form already has are its own, not replaced by the standard ones: an inline+ /// `/Helv` that is Arial becomes an object that is still Arial, a `/TiRo` object stays that+ /// object, and a form needing no change leaves its `/DR` object unwritten. The fonts PdfCraft+ /// adds use WinAnsi, as Acrobat's do.+ #[test]+ fn existing_form_fonts_are_kept_and_an_unchanged_resource_dictionary_is_not_rewritten() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ "<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Arial >> /TiRo 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Times-Bold >>".into(),+ ]);+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();+ let doc = reopen(&doc);+ let fonts = dr_fonts(&doc);+ let font = |name: &str| doc.get(fonts.reference(name.as_bytes()).unwrap()).as_dict().cloned().unwrap();+ assert_eq!(font("Helv").name(b"BaseFont"), Some(&b"Arial"[..]), "the form's own Helv");+ assert_eq!(fonts.reference(b"TiRo"), Some(pdfcraft_cos::ObjRef::new(5, 0)), "the same object");+ assert_eq!(font("Cour").name(b"Encoding"), Some(&b"WinAnsiEncoding"[..]));++ // Every font an object already, /DR an object: adding a field leaves /DR as it was.+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ "<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR 5 0 R >>".into(),+ "<< /Font << /Helv 6 0 R /TiRo 6 0 R /Cour 6 0 R >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ ]);+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();+ assert!(!doc.modified_objects().contains(&5), "/DR unchanged: {:?}", doc.modified_objects());+ }++ /// #3441, exhaustively: every way a form's `/DR` may hold its fonts. `/DR` missing, inline or an+ /// object; its `/Font` missing, inline, an object or not a dictionary; `/Helv` missing, inline,+ /// an object, a reference to nothing, `null` or a number; and a font of the form's own, inline or+ /// an object. After a field is added, whatever the shape:+ /// - no font is a dictionary written inline;+ /// - a font that was an object is the same object, and one that was inline says the same as an+ /// object;+ /// - a `/DR` or `/Font` that was an object (and a dictionary) still is one;+ /// - an entry that is not a dictionary (`null`, a number, a reference to nothing) is left alone;+ /// - Helv, TiRo and Cour are there.+ #[test]+ fn every_shape_of_form_fonts_ends_as_objects() {+ let mut cases = 0;+ for dr_shape in ["missing", "inline", "object"] {+ for font_shape in ["missing", "inline", "object", "number"] {+ for helv in ["missing", "inline", "object", "dangling", "null", "number"] {+ for mine in ["missing", "inline", "object"] {+ let case = FontShapeCase::new(dr_shape, font_shape, helv, mine);+ if !case.is_valid() {+ continue;+ }+ cases += 1;+ assert_font_shape_case(&case);+ }+ }+ }+ }+ assert_eq!(cases, 1 + 2 * (2 + 2 * 6 * 3), "every shape was tried");+ }++ struct FontShapeCase<'a> {+ dr: &'a str,+ fonts: &'a str,+ helv: &'a str,+ mine: &'a str,+ description: String,+ }++ impl<'a> FontShapeCase<'a> {+ fn new(dr: &'a str, fonts: &'a str, helv: &'a str, mine: &'a str) -> Self {+ Self { dr, fonts, helv, mine, description: format!("/DR {dr}, /Font {fonts}, /Helv {helv}, /Mine {mine}") }+ }++ fn is_valid(&self) -> bool {+ let only_default_dr = self.dr == "missing" && self.fonts == "missing" && self.helv == "missing" && self.mine == "missing";+ let invalid_fonts = matches!(self.fonts, "missing" | "number") && (self.helv != "missing" || self.mine != "missing");+ !(self.dr == "missing" && !only_default_dr || invalid_fonts)+ }+ }++ fn assert_font_shape_case(case: &FontShapeCase<'_>) {+ let mut doc = font_shape_document(case);+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name"))+ .unwrap_or_else(|e| panic!("{}: {e}", case.description));+ let doc = reopen(&doc);+ let acro = acroform(&doc).unwrap();+ let dr = doc.resolve(acro.get(b"DR").unwrap_or_else(|| panic!("{}: no /DR", case.description)));+ let fonts = dr_fonts(&doc);+ assert_font_entries_are_references(&fonts, &case.description);+ assert_required_form_fonts(&fonts, &case.description);+ assert_requested_font_shapes(&doc, &acro, &dr, &fonts, case);+ }++ fn font_shape_document(case: &FontShapeCase<'_>) -> Document {+ let mut entries = String::new();+ match case.helv {+ "inline" => entries += &format!("/Helv {} ", form_font("Arial")),+ "object" => entries += "/Helv 7 0 R ",+ "dangling" => entries += "/Helv 99 0 R ",+ "null" => entries += "/Helv null ",+ "number" => entries += "/Helv 3 ",+ _ => {}+ }+ match case.mine {+ "inline" => entries += &format!("/Mine {} ", form_font("Symbol")),+ "object" => entries += "/Mine 8 0 R ",+ _ => {}+ }+ let fonts_value = match case.fonts {+ "inline" => format!("<< {entries}>>"),+ "object" => "6 0 R".into(),+ "number" => "7".into(),+ _ => String::new(),+ };+ let dr_dict = if fonts_value.is_empty() { "<< >>".to_string() } else { format!("<< /Font {fonts_value} >>") };+ let dr_value = match case.dr {+ "inline" => dr_dict.clone(),+ "object" => "5 0 R".into(),+ _ => String::new(),+ };+ let acroform = if dr_value.is_empty() { "<< /Fields [] >>".to_string() } else { format!("<< /Fields [] /DR {dr_value} >>") };+ document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ acroform,+ if case.dr == "object" { dr_dict } else { "null".into() },+ if case.fonts == "object" { format!("<< {entries}>>") } else { "null".into() },+ form_font("Helvetica-Oblique"),+ form_font("ZapfDingbats"),+ ])+ }++ fn form_font(base: &str) -> String {+ format!("<< /Type /Font /Subtype /Type1 /BaseFont /{base} >>")+ }++ fn assert_font_entries_are_references(fonts: &Dict, description: &str) {+ for (name, value) in fonts.iter() {+ assert!(value.as_dict().is_none(), "{description}: {} is inline", String::from_utf8_lossy(name));+ }+ }++ fn assert_required_form_fonts(fonts: &Dict, description: &str) {+ for name in ["Helv", "TiRo", "Cour"] {+ assert!(fonts.contains(name.as_bytes()), "{description}: no {name}");+ }+ }++ fn assert_requested_font_shapes(doc: &Document, acro: &Dict, dr: &Object, fonts: &Dict, case: &FontShapeCase<'_>) {+ let base = |name: &[u8]| fonts.reference(name).and_then(|r| doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont").map(<[u8]>::to_vec)));+ match case.helv {+ "inline" => assert_eq!(base(b"Helv").as_deref(), Some(&b"Arial"[..]), "{}", case.description),+ "object" => assert_eq!(fonts.reference(b"Helv"), Some(pdfcraft_cos::ObjRef::new(7, 0)), "{}", case.description),+ "dangling" => assert_eq!(fonts.reference(b"Helv"), Some(pdfcraft_cos::ObjRef::new(99, 0)), "{}", case.description),+ "null" => assert_eq!(fonts.get(b"Helv"), Some(&Object::Null), "{}", case.description),+ "number" => assert_eq!(fonts.get(b"Helv"), Some(&Object::Int(3)), "{}", case.description),+ _ => assert_eq!(base(b"Helv").as_deref(), Some(&b"Helvetica"[..]), "{}", case.description),+ }+ match case.mine {+ "inline" => assert_eq!(base(b"Mine").as_deref(), Some(&b"Symbol"[..]), "{}", case.description),+ "object" => assert_eq!(fonts.reference(b"Mine"), Some(pdfcraft_cos::ObjRef::new(8, 0)), "{}", case.description),+ _ => assert!(!fonts.contains(b"Mine"), "{}", case.description),+ }+ if case.dr == "object" {+ assert_eq!(acro.reference(b"DR"), Some(pdfcraft_cos::ObjRef::new(5, 0)), "{}: /DR stays its object", case.description);+ }+ if case.fonts == "object" {+ assert_eq!(dr.as_dict().unwrap().reference(b"Font"), Some(pdfcraft_cos::ObjRef::new(6, 0)), "{}: /Font stays its object", case.description);+ }+ }++ /// #3441 (review follow-up): filling a field converts the form's inline `/DR` fonts, so a form+ /// an earlier PdfCraft made works in Acrobat once it has been filled here. Nothing is added. A+ /// form a signature covers keeps `/DR` as the signer saw it, and a form whose fonts are objects+ /// already leaves its `/DR` object unwritten.+ #[test]+ fn filling_a_field_makes_inline_form_fonts_objects_unless_the_form_is_signed() {+ let inline = "/Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";+ let form = |signed: bool, dr: &str| {+ let sig = if signed { "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /V 7 0 R /Rect [0 0 0 0] /P 3 0 R >>" } else { "null" };+ let fields = if signed { "[5 0 R 6 0 R]" } else { "[5 0 R]" };+ document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),+ format!("<< /Fields {fields} /DA (/Helv 0 Tf 0 g) /DR {dr} >>"),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),+ sig.into(),+ "<< /Type /Sig /Filter /Adobe.PPKLite /Contents <00> >>".into(),+ "<< /Font << /Helv 9 0 R >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ ])+ };+ let mut doc = form(false, &format!("<< /Font << {inline} >> >>"));+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();+ let doc = reopen(&doc);+ let fonts = dr_fonts(&doc);+ assert!(fonts.reference(b"Helv").is_some(), "Helv became an object: {fonts:?}");+ assert_eq!(fonts.len(), 1, "nothing added: {fonts:?}");+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);++ let mut doc = form(true, &format!("<< /Font << {inline} >> >>"));+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();+ let doc = reopen(&doc);+ assert!(dr_fonts(&doc).get(b"Helv").is_some_and(|h| h.as_dict().is_some()), "a signed form keeps /DR as it was");++ // An empty signature field signs nothing: the form is converted as an unsigned one.+ let mut doc = form(true, &format!("<< /Font << {inline} >> >>"));+ doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| {+ d.remove(b"V");+ })+ .unwrap();+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();+ assert!(dr_fonts(&reopen(&doc)).reference(b"Helv").is_some(), "an unsigned signature field doesn't hold /DR back");++ let mut doc = form(false, "8 0 R");+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();+ assert!(!doc.modified_objects().contains(&8), "/DR unchanged: {:?}", doc.modified_objects());+ }++ /// #3441 (review follow-up): a signature value held by a parent field signs its kid too (`/V` is+ /// inheritable, ISO 32000-2 Table 226), so the form still counts as signed and keeps its `/DR`.+ #[test]+ fn a_signature_value_on_a_parent_field_keeps_the_form_fonts_as_signed() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 8 0 R] >>".into(),+ "<< /Fields [5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >> >> >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),+ "<< /FT /Sig /T (sig) /V 7 0 R /Kids [8 0 R] >>".into(),+ "<< /Type /Sig /Filter /Adobe.PPKLite /Contents <00> >>".into(),+ "<< /Type /Annot /Subtype /Widget /T (s1) /Parent 6 0 R /Rect [0 0 0 0] /P 3 0 R >>".into(),+ ]);+ let kid = pdfcraft_cos::ObjRef::new(8, 0);+ assert!(fields(&doc).iter().any(|f| f.obj == kid && f.kind == FieldKind::Signature), "the kid is the signature field");+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();+ let doc = reopen(&doc);+ assert!(dr_fonts(&doc).get(b"Helv").is_some_and(|h| h.as_dict().is_some()), "an inherited signature value keeps /DR as it was");+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);+ }++ /// #3441 (review follow-up): a catalog that holds `/AcroForm` as a direct dictionary gets its+ /// inline `/DR` fonts converted too when a field is filled.+ #[test]+ fn filling_a_field_converts_inline_fonts_of_a_direct_form_dictionary() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >> >> >> >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),+ ]);+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();+ let doc = reopen(&doc);+ let fonts = dr_fonts(&doc);+ assert!(fonts.reference(b"Helv").is_some(), "Helv became an object: {fonts:?}");+ assert_eq!(fonts.len(), 1, "nothing added: {fonts:?}");+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);+ }++ /// #3926 / #3943 review: a password value can be inherited from an ancestor field or sit on a+ /// separate widget. Clearing removes both; an ancestor's value shared with a non-password field+ /// stays for that field, and the password field gets an empty value of its own instead.+ #[test]+ fn inherited_and_widget_password_values_are_cleared() {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 9 0 R 11 0 R] >>".into(), // 3+ "<< /Fields [5 0 R 8 0 R 10 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 4+ "<< /T (acct) /FT /Tx /Ff 8192 /V (secret1) /Kids [6 0 R] >>".into(), // 5 flag and value inherited+ "<< /Type /Annot /Subtype /Widget /T (pin) /Parent 5 0 R /Rect [50 700 150 720] /P 3 0 R >>".into(), // 6+ "<< /Type /Annot /Subtype /Widget /Parent 8 0 R /V (secret3) /Rect [50 650 150 670] /P 3 0 R >>".into(), // 7 value on the widget+ "<< /FT /Tx /T (code) /Ff 8192 /Kids [7 0 R] >>".into(), // 8+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw) /Ff 8192 /Parent 10 0 R /Rect [50 600 150 620] /P 3 0 R >>".into(), // 9+ "<< /T (grp) /V (shared2) /Kids [9 0 R 11 0 R] >>".into(), // 10 shared with a plain field+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (plain) /Parent 10 0 R /Rect [50 550 150 570] /P 3 0 R >>".into(), // 11+ ];+ let mut doc = document(&objs);+ assert!(has_password_values(&doc));+ let value = |doc: &Document, n: &str| fields(doc).into_iter().find(|f| f.name == n).map(|f| f.value).unwrap_or_default();+ assert_eq!(value(&doc, "acct.pin"), ["secret1"], "inherited before");+ assert_eq!(clear_password_values(&mut doc).unwrap(), 3);+ assert!(!has_password_values(&doc));+ for n in ["acct.pin", "code", "grp.pw"] {+ assert!(value(&doc, n).iter().all(|v| v.is_empty()), "{n} cleared");+ }+ assert_eq!(value(&doc, "grp.plain"), ["shared2"], "the shared value stays for the plain field");+ let has_v = |doc: &Document, n: u32| doc.get(pdfcraft_cos::ObjRef { num: n, generation: 0 }).as_dict().is_some_and(|d| d.get(b"V").is_some());+ assert!(!has_v(&doc, 5), "an ancestor only password fields inherit from loses its value");+ assert!(!has_v(&doc, 7), "a widget's value is removed");+ assert!(has_v(&doc, 10), "a shared ancestor keeps its value");+ }++ /// #3943 review: a cleared password field saves as Acrobat saves it (black-box test). One with a+ /// default value gets it back, and its appearance shows as many masking characters as the+ /// default has, not as the typed password had; one without is left empty and draws none. The+ /// default value and the scripts stay, and a field already at its default needs no clearing.+ #[test]+ fn a_cleared_password_field_returns_to_its_default_value() {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R] >>".into(), // 3+ "<< /Fields [6 0 R 7 0 R 8 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(), // 4+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), // 5+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw) /Ff 8192 /DV (DEF-1) /V (NEWPASS-77777) /AA << /K << /S /JavaScript /JS (1;) >> >> /Rect [50 700 250 720] /P 3 0 R >>".into(), // 6+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw3) /Ff 8192 /V (PW3-TYPED-9) /Rect [50 650 250 670] /P 3 0 R >>".into(), // 7+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (blank) /Ff 8192 /V [()] /Rect [50 600 250 620] /P 3 0 R >>".into(), // 8 holds nothing (an empty string in an array)+ ];+ let mut doc = document(&objs);+ assert_eq!(clear_password_values(&mut doc).unwrap(), 2);+ let all = fields(&doc);+ let (pw, pw3) = (field(&all, "pw"), field(&all, "pw3"));+ assert_eq!(pw.value, ["DEF-1"], "back to its default");+ assert_eq!(pw.default, ["DEF-1"], "the default stays");+ assert!(pw.actions.scripts.keystroke.is_some(), "the scripts stay");+ assert!(pw3.value.iter().all(|v| v.is_empty()), "no default: empty");+ let shown = ap(&doc, &pw.widgets[0]);+ assert!(shown.contains("(*****)") && !shown.contains("NEWPASS") && !shown.contains("******"), "{shown}");+ let shown3 = ap(&doc, &pw3.widgets[0]);+ assert!(!shown3.contains('*') && !shown3.contains("PW3"), "{shown3}");+ assert!(!has_password_values(&doc), "a field at its default holds no typed password");+ assert_eq!(clear_password_values(&mut doc).unwrap(), 0);+ }++ /// #3943 review: the quick check that skips forms without a Password field still sees one whose+ /// widget is only on the page, not listed in `/Fields`; one that inherits the flag from a parent+ /// that is not listed either; and one deeper in the field tree whose widget is on no page. Each+ /// is alone in its own document, so each path of the check is needed.+ #[test]+ fn a_password_field_missing_from_the_field_list_is_still_cleared() {+ let form = |fields: &str, annots: &str, rest: &[&str]| {+ let mut objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),+ format!("<< /Fields [{fields}] /DA (/Helv 0 Tf 0 g) >>"),+ ];+ objs.extend(rest.iter().map(|o| o.to_string()));+ document(&objs)+ };+ let page_only =+ form("", "5 0 R", &["<< /Type /Annot /Subtype /Widget /FT /Tx /T (pin) /Ff 8192 /V (secret5) /Rect [50 700 150 720] /P 3 0 R >>"]);+ let inherited = form(+ "",+ "5 0 R",+ &[+ "<< /Type /Annot /Subtype /Widget /T (kid) /Parent 6 0 R /Rect [50 650 150 670] /P 3 0 R >>",+ "<< /FT /Tx /T (acct) /Ff 8192 /V (secret6) /Kids [5 0 R] >>",+ ],+ );+ let off_page = form(+ "5 0 R",+ "",+ &[+ "<< /T (grp) /Kids [6 0 R] >>",+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (hidden) /Ff 8192 /V (secret7) /Parent 5 0 R /Rect [0 0 0 0] >>",+ ],+ );+ for (what, mut doc) in [("page only", page_only), ("inherited", inherited), ("on no page", off_page)] {+ assert!(has_password_values(&doc), "{what}");+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1, "{what}");+ assert!(fields(&doc).iter().all(|f| f.value.iter().all(|v| v.is_empty())), "{what}: {:?}", fields(&doc));+ }+ }++ /// A password field nested beyond depth 32 (e.g. depth 35) is recognized by `has_password_flag`+ /// and `has_password_values`, matching the field tree walk limit of 64.+ #[test]+ fn a_password_field_nested_beyond_depth_32_is_recognized() {+ let target_depth = 35;+ let leaf_obj_num = 5 + target_depth;+ let mut objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),+ ];+ for d in 0..target_depth {+ let obj_num = 5 + d;+ let next_obj_num = obj_num + 1;+ let parent_entry = if d == 0 { String::new() } else { format!(" /Parent {} 0 R", obj_num - 1) };+ objs.push(format!("<< /T (node{d}) /Kids [{next_obj_num} 0 R]{parent_entry} >>"));+ }+ objs.push(format!(+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pass) /Ff 8192 /V (secret35) /Parent {} 0 R /Rect [50 600 150 620] /P 3 0 R >>",+ leaf_obj_num - 1+ ));+ let mut doc = document(&objs);+ assert!(has_password_flag(&doc));+ assert!(has_password_values(&doc));+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1);+ assert!(!has_password_values(&doc));+ }++ /// A password field whose widget is reachable through a page's Annots and whose inherited Password+ /// flag is deeper than 32 levels is recognized by `has_password_flag`.+ #[test]+ fn a_page_widget_inheriting_password_flag_beyond_depth_32_is_recognized() {+ let target_depth = 35;+ let leaf_obj_num = 5 + target_depth;+ let mut objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ format!("<< /Type /Page /Parent 2 0 R /Annots [{leaf_obj_num} 0 R] >>"),+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),+ ];+ for d in 0..target_depth {+ let obj_num = 5 + d;+ let next_obj_num = obj_num + 1;+ let parent_entry = if d == 0 { String::new() } else { format!(" /Parent {} 0 R", obj_num - 1) };+ let ff_entry = if d == 0 { " /Ff 8192" } else { "" };+ objs.push(format!("<< /T (node{d}){ff_entry} /Kids [{next_obj_num} 0 R]{parent_entry} >>"));+ }+ objs.push(format!(+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pass) /V (secret_chain) /Parent {} 0 R /Rect [50 600 150 620] /P 3 0 R >>",+ leaf_obj_num - 1+ ));+ let mut doc = document(&objs);+ assert!(has_password_flag(&doc));+ assert!(has_password_values(&doc));+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1);+ assert!(!has_password_values(&doc));+ }++ /// #4018: a value that doesn't fit its box at the field's font size is reported (it is drawn cut+ /// at the box). An auto-sized field shrinks to fit, and a short or empty value fits.+ #[test]+ fn a_value_wider_or_taller_than_its_box_is_reported() {+ let long = "Doe, Jane (represented by John Doe)";+ let field = |name: &str, rect: &str, extra: &str, value: &str| {+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /V ({value}) /Rect [{rect}] /P 3 0 R {extra} >>")+ };+ let doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] >>".into(),+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ field("single", "50 700 190 718", "", long),+ field("multi", "50 650 190 668", "/Ff 4096", long),+ field("auto", "50 600 190 618", "/DA (/Helv 0 Tf 0 g)", long),+ field("wide", "50 550 350 568", "", long),+ field("short", "50 500 190 518", "/Ff 4096", "Ada"),+ ]);+ let overflow = |name: &str| {+ let f = fields(&doc).into_iter().find(|f| f.name == name).unwrap();+ appearance::value_overflow(&doc, &f, &f.widgets[0])+ };+ match overflow("single") {+ Some(appearance::Overflow::Wide { width, room, size }) => {+ assert_eq!(size, 12.0);+ assert!((width - 201.4).abs() < 1.0 && room < 140.0, "{width} in {room}");+ }+ other => panic!("single: {other:?}"),+ }+ assert_eq!(overflow("multi"), Some(appearance::Overflow::Tall { lines: 2, room: 1, size: 12.0 }));+ assert_eq!(overflow("auto"), None, "auto size shrinks to fit");+ assert_eq!(overflow("wide"), None);+ assert_eq!(overflow("short"), None);+ }++ /// #4018: a single line taller than its box is cut at the top and bottom, and a character wider+ /// than a multiline box is a line of its own that is still cut at the sides; both are reported.+ /// An empty value draws nothing, so nothing is cut however small the box.+ #[test]+ fn a_line_taller_than_its_box_or_a_character_wider_than_it_is_reported() {+ let field = |name: &str, rect: &str, extra: &str, value: &str| {+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /V ({value}) /Rect [{rect}] /P 3 0 R {extra} >>")+ };+ let doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] >>".into(),+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ field("low", "50 700 190 708", "", "Ada"),+ field("comb", "50 650 190 658", "/Ff 16777216 /MaxLen 5", "Ada"),+ field("narrow", "50 500 56 560", "/Ff 4096", "WW"),+ field("roomy", "50 400 190 418", "", "Ada"),+ field("empty", "50 350 190 358", "", ""),+ field("empty-multi", "50 300 190 304", "/Ff 4096", ""),+ ]);+ let overflow = |name: &str| {+ let f = fields(&doc).into_iter().find(|f| f.name == name).unwrap();+ appearance::value_overflow(&doc, &f, &f.widgets[0])+ };+ for name in ["low", "comb"] {+ match overflow(name) {+ Some(o @ appearance::Overflow::High { height, room, size }) => {+ assert_eq!(size, 12.0);+ assert!((height - 11.1).abs() < 0.01 && room <= 8.0, "{name}: {height} in {room}");+ assert!(o.to_string().starts_with("the value does not fit: 11.1 pt high at 12 pt"), "{o}");+ }+ other => panic!("{name}: {other:?}"),+ }+ }+ match overflow("narrow") {+ Some(appearance::Overflow::Wide { width, room, size }) => {+ assert_eq!(size, 12.0);+ assert!(width > room && (width - 11.32).abs() < 0.1, "{width} in {room}");+ }+ other => panic!("narrow: {other:?}"),+ }+ assert_eq!(overflow("roomy"), None);+ assert_eq!(overflow("empty"), None);+ assert_eq!(overflow("empty-multi"), None);+ }++ /// Check boxes, radio buttons and push buttons whose file gives them no appearance, a comb field,+ /// a combo box and a list box, for the display copy.+ fn left_buttons() -> Document {+ let widget = |n: &str, rest: &str| format!("<< /Type /Annot /Subtype /Widget /T ({n}) /F 4 /P 3 0 R {rest} >>");+ document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R] >>".into(),+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ widget("i", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 g) /MK << /CA (4) /BC [0 0 0] >> /Rect [50 700 74 724]"), // 6+ widget("j", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 0 1 rg) /MK << /CA (l) /BC [0 0 0] >> /Rect [100 700 124 724]"),+ widget("k", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) /BC [0 0 0] >> /Rect [150 700 174 724]"),+ widget("l", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 9 Tf 0 g) /MK << /CA (H) /BC [0 0 0] /BG [1 1 0] >> /Rect [200 700 224 724]"),+ widget("off", "/FT /Btn /V /Off /AS /Off /DA (/ZaDb 0 Tf 0 g) /MK << /CA (4) /BC [0 0 0] >> /Rect [250 700 274 724]"), // 10+ widget("radio", "/FT /Btn /Ff 32768 /V /A /AS /A /DA (/ZaDb 0 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [300 700 324 724]"),+ widget(+ "o",+ "/FT /Btn /Ff 65536 /DA (/Helv 12 Tf 0 g) /MK << /CA (Press me) /BG [0.8 0.8 0.8] /BC [0 0 0] >> /BS << /W 2 /S /B >> /Rect [50 600 170 624]",+ ),+ widget("own", "/FT /Btn /V /Yes /AS /Yes /MK << /CA (4) /BC [0 0 0] >> /Rect [350 700 374 724] /AP << /N << /Yes 19 0 R /Off 19 0 R >> >>"),+ widget("half", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 g) /MK << /CA (8) >> /Rect [400 700 424 724] /AP << /N << /Off 19 0 R >> >>"),+ widget("bad", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb nan Tf 1 x rg) /MK << /CA 42 /BC [(no) /Name] /BG 7 >> /BS << /W -3 >> /Rect [450 700 474 724]"), // 15+ widget("d", "/FT /Tx /Ff 16777216 /MaxLen 6 /V (ABC123) /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 1] >> /Rect [50 500 170 524]"),+ widget("m", "/FT /Ch /Ff 131072 /Opt [(Apple) (Banana)] /V (Banana) /Q 2 /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [50 400 170 424]"),+ widget("n", "/FT /Ch /Opt [(One) (Two)] /V (Two) /DA (/Helv 11 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [200 400 320 460]"),+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(), // 19+ ])+ }++ /// The appearance stream of widget `w` in `state` (a check box's `/AP /N /<state>`).+ fn state_ap(doc: &Document, w: &Widget, state: &str) -> String {+ let wd = doc.get(w.obj).as_dict().cloned().unwrap();+ let ap = doc.resolve(wd.get(b"AP").unwrap()).as_dict().cloned().unwrap();+ let n = doc.resolve(ap.get(b"N").unwrap()).as_dict().cloned().unwrap();+ let r = n.reference(state.as_bytes()).expect("the state's appearance");+ let Object::Stream(s) = &*doc.get(r) else { panic!("a stream") };+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()+ }++ /// The decoded appearance PdfCraft would save for text or choice field `name` of `doc`.+ fn saved_look(doc: &Document, name: &str) -> String {+ let all = fields(doc);+ let f = field(&all, name);+ String::from_utf8_lossy(&appearance::field_appearance(doc, f, &f.widgets[0], &f.value).decoded().unwrap()).into_owned()+ }++ /// ISO 32000-2 Table 192 and 12.7.5.2.3: a check box with no appearance shows its `/MK /BC`+ /// border and, when on, its caption `/MK /CA` as a ZapfDingbats character in the `/DA` colour,+ /// sized to the box when the `/DA` size is 0.+ #[test]+ fn check_boxes_without_an_appearance_show_their_caption_symbol() {+ let doc = left_buttons();+ let copy = with_field_appearances(&doc).expect("buttons to draw");+ let all = fields(©);+ for (name, symbol, colour) in [("i", "(4) Tj", "0 g"), ("j", "(l) Tj", "0 0 1 rg"), ("k", "(8) Tj", "1 0 0 rg"), ("l", "(H) Tj", "0 g")] {+ let shown = state_ap(©, &field(&all, name).widgets[0], "Yes");+ assert!(shown.contains(symbol), "{name}: {shown}");+ assert!(shown.contains(&format!("{colour}\n")), "{name} in its colour: {shown}");+ assert!(shown.contains("0 0 0 RG\n1 w\n0.5 0.5 23 23 re S"), "{name} has its border: {shown}");+ }+ // A /DA size is kept; the automatic one fills the box inside the border.+ let l = state_ap(©, &field(&all, "l").widgets[0], "Yes");+ assert!(l.contains("/ZaDb 9 Tf") && l.contains("1 1 0 rg\n0 0 24 24 re f"), "{l}");+ let i = state_ap(©, &field(&all, "i").widgets[0], "Yes");+ let size: f64 = i.split("/ZaDb ").nth(1).and_then(|s| s.split(' ').next()).and_then(|s| s.parse().ok()).unwrap();+ assert!((18.0..=26.0).contains(&size), "{size}");+ let w = copy.get(field(&all, "i").widgets[0].obj);+ let ap = copy.resolve(w.as_dict().unwrap().get(b"AP").unwrap());+ let n = copy.resolve(ap.as_dict().unwrap().get(b"N").unwrap());+ let Object::Stream(s) = &*copy.get(n.as_dict().unwrap().reference(b"Yes").unwrap()) else { panic!() };+ let font = s.dict.get(b"Resources").and_then(|r| r.as_dict()).and_then(|r| r.get(b"Font")).and_then(|f| f.as_dict()).and_then(|f| f.get(b"ZaDb"));+ assert_eq!(font.and_then(|f| f.as_dict()).and_then(|f| f.name(b"BaseFont")), Some(&b"ZapfDingbats"[..]), "a standard-14 font, no program");+ }++ /// An Off check box shows only its border, a radio button without a caption a dot (`l`), a box+ /// whose file has only an Off look gets an on look, and one with its own look keeps it.+ #[test]+ fn button_states_without_an_appearance() {+ let doc = left_buttons();+ let copy = with_field_appearances(&doc).expect("buttons to draw");+ let all = fields(©);+ let off = state_ap(©, &field(&all, "off").widgets[0], "Off");+ assert!(off.contains("re S") && !off.contains("Tj"), "{off}");+ assert!(state_ap(©, &field(&all, "radio").widgets[0], "A").contains("(l) Tj"));+ assert!(state_ap(©, &field(&all, "half").widgets[0], "Yes").contains("(8) Tj"));+ let own = |d: &Document| d.get(field(&fields(d), "own").widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());+ assert_eq!(own(©), own(&doc), "a check box with its own look keeps it");+ // Nonsense in /MK, /DA and /BS: the default symbol, no border, and no panic.+ let bad = state_ap(©, &field(&all, "bad").widgets[0], "Yes");+ assert!(bad.contains("(4) Tj") && !bad.contains("re S"), "{bad}");+ // The document itself is untouched.+ assert!(doc.get(field(&fields(&doc), "i").widgets[0].obj).as_dict().is_some_and(|w| !w.contains(b"AP")));+ }++ /// Table 192 and Table 168: a push button with no appearance shows its `/MK /BG` background, its+ /// beveled `/MK /BC` border in the `/BS` width, and its caption `/MK /CA` centred.+ #[test]+ fn push_buttons_without_an_appearance_show_their_caption_and_frame() {+ let copy = with_field_appearances(&left_buttons()).expect("buttons to draw");+ let shown = ap(©, &field(&fields(©), "o").widgets[0]);+ for part in ["0.8 0.8 0.8 rg\n0 0 120 24 re f", "0 0 0 RG\n2 w\n1 1 118 22 re S", "1 g\n", "0.5 g\n", "(Press me) Tj", "/Helv 12.00 Tf"] {+ assert!(shown.contains(part), "{part}: {shown}");+ }+ }++ /// ISO 32000-2 Table 228, Comb: the field is divided into MaxLen equally spaced positions, and a+ /// bordered comb field shows them: MaxLen - 1 lines in the border colour, in its saved look too.+ #[test]+ fn comb_fields_show_their_cells() {+ let mut doc = left_buttons();+ let shown = saved_look(&doc, "d");+ let lines: Vec<&str> = shown.lines().filter(|l| l.ends_with(" l") && l.contains(" 1 m ")).collect();+ assert_eq!(lines, ["20 1 m 20 23 l", "40 1 m 40 23 l", "60 1 m 60 23 l", "80 1 m 80 23 l", "100 1 m 100 23 l"], "{shown}");+ assert!(shown.contains("0 0 1 RG\n1 w\n20 1 m"), "in the border colour: {shown}");+ // Past the cap no lines, and a huge MaxLen is no trouble; without a border, none either.+ let r = field(&fields(&doc), "d").widgets[0].obj;+ doc.update_dict(r, |w| w.set(b"MaxLen".to_vec(), Object::Int(1 << 40))).unwrap();+ let huge = saved_look(&doc, "d");+ assert!(!huge.contains(" 1 m ") && huge.contains("(A) Tj"), "{huge}");+ doc.update_dict(r, |w| {+ w.set(b"MaxLen".to_vec(), Object::Int(6));+ w.remove(b"MK");+ })+ .unwrap();+ let plain = saved_look(&doc, "d");+ assert!(!plain.contains(" m ") && plain.contains("(A) Tj"), "{plain}");+ }++ /// Check boxes and radio buttons with an `/MK` look and appearances of their own, in a form that+ /// sets `/NeedAppearances` (`need`) or not.+ fn mk_buttons(need: bool) -> Document {+ let flag = if need { "/NeedAppearances true " } else { "" };+ let widget = |n: &str, rest: &str| format!("<< /Type /Annot /Subtype /Widget /FT /Btn /T ({n}) /F 4 /P 3 0 R {rest} >>");+ let states = |on: &str| format!("/AP << /N << /{on} 15 0 R /Off 16 0 R >> >>");+ document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] >>".into(),+ format!(+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>"+ ),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ widget("check", &format!("/V /Yes /AS /Yes /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [50 700 74 724] {}", states("Yes"))), // 6+ widget("cross", &format!("/V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) >> /Rect [100 700 124 724] {}", states("Yes"))),+ widget("diamond", &format!("/V /Yes /AS /Yes /MK << /CA (u) /BG [1 1 0] >> /Rect [150 700 174 724] {}", states("Yes"))),+ widget("square", &format!("/V /Yes /AS /Yes /MK << /CA (n) >> /Rect [200 700 224 724] {}", states("Yes"))),+ widget("star", &format!("/V /Yes /AS /Yes /MK << /CA (H) >> /Rect [250 700 274 724] {}", states("Yes"))), // 10+ widget("off", &format!("/V /Off /AS /Off /MK << /BC [0 0 0] /CA (4) >> /Rect [300 700 324 724] {}", states("Yes"))),+ widget("radio", &format!("/Ff 32768 /V /B /MK << /BC [0 0 1] /CA (l) >> /Rect [350 700 374 724] {}", states("B"))),+ widget("plain", &format!("/V /Yes /AS /Yes /Rect [400 700 424 724] {}", states("Yes"))),+ widget(+ "odd",+ &format!(+ "/V /Yes /AS /Yes /DA (/ZaDb nan Tf 1 x rg) /MK << /CA 42 /BC [(no) /Name] /BG 7 >> /BS << /W -3 >> /Rect [450 700 474 724] {}",+ states("Yes")+ ),+ ),+ "<< /Length 24 >>\nstream\n0 g 4 4 16 16 re f\nendstream".into(), // 15: a filled square+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(),+ ])+ }++ /// ISO 32000-2 Table 224 (`/NeedAppearances`) and Table 192 (`/MK /CA`): a form that leaves its+ /// appearances to the viewer shows each check box and radio button with an `/MK` drawn from it,+ /// over the appearance the file carries: the caption's ZapfDingbats symbol in the `/DA` colour+ /// when on, only the border when off. A widget with no `/MK` keeps its own; the file is untouched.+ #[test]+ fn need_appearances_draws_check_boxes_and_radio_buttons_from_their_captions() {+ let doc = mk_buttons(true);+ let copy = with_field_appearances(&doc).expect("buttons to draw");+ let all = fields(©);+ for (name, state, symbol, colour) in [+ ("check", "Yes", "(4) Tj", "0 g"),+ ("cross", "Yes", "(8) Tj", "1 0 0 rg"),+ ("diamond", "Yes", "(u) Tj", "0 g"),+ ("square", "Yes", "(n) Tj", "0 g"),+ ("star", "Yes", "(H) Tj", "0 g"),+ ("radio", "B", "(l) Tj", "0 g"),+ ] {+ let shown = state_ap(©, &field(&all, name).widgets[0], state);+ assert!(shown.contains(symbol) && shown.contains(&format!("{colour}\n")), "{name}: {shown}");+ assert!(!shown.contains("4 4 16 16 re f"), "{name} is not the file's filled square: {shown}");+ }+ let check = state_ap(©, &field(&all, "check").widgets[0], "Yes");+ assert!(check.contains("0 0 0 RG\n1 w\n0.5 0.5 23 23 re S"), "the /BC border: {check}");+ assert!(state_ap(©, &field(&all, "diamond").widgets[0], "Yes").contains("1 1 0 rg\n0 0 24 24 re f"), "the /BG background");+ assert!(state_ap(©, &field(&all, "radio").widgets[0], "B").contains("0 0 1 RG"), "the radio's own border");+ let off = state_ap(©, &field(&all, "off").widgets[0], "Off");+ assert!(off.contains("re S") && !off.contains("Tj"), "off: only the border: {off}");+ // Nonsense in /MK, /DA and /BS: the default check, no border, and no panic.+ let odd = state_ap(©, &field(&all, "odd").widgets[0], "Yes");+ assert!(odd.contains("(4) Tj") && !odd.contains("re S"), "{odd}");+ let own = |d: &Document, name: &str| d.get(field(&fields(d), name).widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());+ assert_eq!(own(©, "plain"), own(&doc, "plain"), "a box without /MK keeps its own look");+ assert_eq!(state_ap(&doc, &field(&fields(&doc), "check").widgets[0], "Yes").trim_end(), "0 g 4 4 16 16 re f", "the file is untouched");+ }++ /// Without `/NeedAppearances` the file's own check box and radio button appearances are shown+ /// as they are, `/MK` or not: no copy is needed.+ #[test]+ fn without_need_appearances_buttons_keep_their_own_appearances() {+ assert!(with_field_appearances(&mk_buttons(false)).is_none());+ }++ /// A form for filling many values at once: two summed fields and their calculated total, a+ /// name two field dictionaries share, a check box, a radio group, a list and a read-only field.+ fn batch_form() -> Document {+ let tx = |name: &str, y: u32, rest: &str| {+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [50 {y} 250 {}] /P 3 0 R {rest} >>", y + 20)+ };+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 12 0 R 13 0 R 14 0 R 17 0 R] >>".into(),+ "<< /Fields [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 14 0 R 17 0 R] /CO [7 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 15 0 R >> >> >>"+ .into(),+ tx("a", 700, "/V (1)"),+ tx("b", 660, ""),+ tx("total", 620, r#"/AA << /C << /S /JavaScript /JS (AFSimple_Calculate\("SUM", new Array\("a", "b"\)\);) >> >>"#),+ tx("dup", 580, ""),+ tx("dup", 540, ""),+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T (agree) /V /Off /AS /Off /Rect [300 700 315 715] /P 3 0 R >>".into(),+ "<< /FT /Btn /T (size) /Ff 49152 /Kids [12 0 R 13 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 11 0 R /AS /Off /Rect [300 650 315 665] /P 3 0 R /AP << /N << /S 16 0 R /Off 16 0 R >> >> >>"+ .into(),+ "<< /Type /Annot /Subtype /Widget /Parent 11 0 R /AS /Off /Rect [330 650 345 665] /P 3 0 R /AP << /N << /L 16 0 R /Off 16 0 R >> >> >>"+ .into(),+ "<< /Type /Annot /Subtype /Widget /FT /Ch /T (country) /Ff 131072 /Opt [[(ca) (Canada)] [(fr) (France)]] /Rect [300 600 450 620] /P 3 0 R >>"+ .into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ "<< /Length 0 >>\nstream\n\nendstream".into(),+ tx("locked", 500, "/Ff 1 /V (kept)"),+ ];+ document(&objs)+ }++ /// What a filled form shows: every field as read, and each widget's drawn appearance.+ fn filled(doc: &Document) -> (Vec<Field>, Vec<String>) {+ let all = fields(doc);+ let looks = all+ .iter()+ .flat_map(|f| &f.widgets)+ .map(|w| {+ let wd = doc.get(w.obj).as_dict().cloned().unwrap_or_default();+ let n = wd.get(b"AP").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().and_then(|a| a.get(b"N").cloned()));+ match n.map(|n| doc.resolve(&n)) {+ Some(n) => match &*n {+ Object::Stream(s) => String::from_utf8_lossy(&s.decoded().unwrap_or_default()).into_owned(),+ other => format!("{other:?}").chars().filter(|c| !c.is_ascii_digit()).collect(),+ },+ None => String::new(),+ }+ })+ .collect();+ (all, looks)+ }++ /// Filling values in one batch leaves the form as filling them one by one does: the values,+ /// the twin of a shared name, the calculated total and every widget's appearance; a name given+ /// twice ends with its last value, and is checked against the value it took earlier in the batch;+ /// and each value fails as it would on its own.+ #[test]+ fn set_values_fills_as_set_value_does_one_by_one() {+ let values: Vec<(String, FieldValue)> = vec![+ ("a".into(), FieldValue::Text("2".into())),+ ("b".into(), FieldValue::Text("3".into())),+ ("dup".into(), FieldValue::Text("shared".into())),+ ("agree".into(), FieldValue::Check(true)),+ ("size".into(), FieldValue::Radio(Some("L".into()))),+ ("country".into(), FieldValue::Choice(vec!["fr".into()])),+ ("nowhere".into(), FieldValue::Text("x".into())),+ ("locked".into(), FieldValue::Text("changed".into())),+ ("size".into(), FieldValue::Radio(Some("XL".into()))),+ ("dup".into(), FieldValue::Text("again".into())),+ ("a".into(), FieldValue::Text("10".into())),+ // Refused only because the batch already selected L: the group keeps one selected.+ ("size".into(), FieldValue::Radio(None)),+ ];+ let mut one_by_one = batch_form();+ let expected: Vec<Result<(), FormError>> = values.iter().map(|(n, v)| set_value(&mut one_by_one, n, v)).collect();+ let mut batch = batch_form();+ let results = set_values(&mut batch, &values).expect("recalculates");+ assert_eq!(results, expected);+ assert_eq!(+ results.iter().filter(|r| r.is_err()).count(),+ 4,+ "the unknown name, the read-only field, the unknown option and clearing the group fail: {results:?}"+ );+ let (all, looks) = filled(&batch);+ assert_eq!((all.clone(), looks), filled(&one_by_one));+ assert_eq!(field(&all, "total").value, ["13"], "recalculated once, after the last value");+ assert!(all.iter().filter(|f| f.name == "dup").all(|f| f.value == ["again"]), "both dup fields take the last value");+ // And as saved.+ assert_eq!(filled(&reopen(&batch)), filled(&reopen(&one_by_one)));+ }++ /// A form without fields refuses each value, and an empty batch changes nothing.+ #[test]+ fn set_values_without_a_form_or_values() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R >>".into(),+ ]);+ let r = set_values(&mut doc, &[("a".into(), FieldValue::Text("1".into()))]).unwrap();+ assert_eq!(r, vec![Err(FormError::NoForm)]);+ let mut form = batch_form();+ assert_eq!(set_values(&mut form, &[]).unwrap(), Vec::new());+ assert!(!form.is_modified());+ // Nothing filled, nothing recalculated: the total stays as the file has it.+ let r = set_values(&mut form, &[("nowhere".into(), FieldValue::Text("1".into()))]).unwrap();+ assert_eq!(r, vec![Err(FormError::NoSuchField("nowhere".into()))]);+ assert!(field(&fields(&form), "total").value.is_empty() && !form.is_modified());+ }++ /// Filling many fields reads the form a fixed number of times, not once or twice per field+ /// (which took minutes to open a form with thousands of fields whose XFA data was filled in+ /// elsewhere).+ #[test]+ fn set_values_reads_the_form_once_not_per_value() {+ let n: u32 = 60;+ let mut objs: Vec<String> =+ vec!["<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into()];+ let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", i + 5)).collect();+ objs.push(format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", kids.join(" ")));+ objs.push(format!("<< /Fields [{}] /DA (/Helv 10 Tf 0 g) >>", kids.join(" ")));+ for i in 0..n {+ objs.push(format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (f{i}) /Rect [50 {y} 250 {top}] /P 3 0 R >>", y = 10 * i, top = 10 * i + 10));+ }+ let mut doc = document(&objs);+ let values: Vec<(String, FieldValue)> = (0..n).map(|i| (format!("f{i}"), FieldValue::Text(format!("v{i}")))).collect();+ let before = form_reads();+ let results = set_values(&mut doc, &values).unwrap();+ let reads = form_reads() - before;+ assert!(results.iter().all(Result::is_ok));+ // One reading to fill, one to recalculate.+ assert!(reads <= 2, "{reads} readings of the form for {n} values");+ assert!(fields(&doc).iter().all(|f| f.value == [format!("v{}", &f.name[1..])]));+ // A name filled again is read again, once: f0 and f1 again cost one more reading.+ let again: Vec<(String, FieldValue)> = ["f0", "f1", "f0", "f1"].iter().map(|n| (n.to_string(), FieldValue::Text("w".into()))).collect();+ let before = form_reads();+ assert!(set_values(&mut doc, &again).unwrap().iter().all(Result::is_ok));+ let reads = form_reads() - before;+ assert_eq!(reads, 3, "one to fill, one when f0 comes again, one to recalculate");+ }++ /// A radio group `size` with the buttons Small (on), Medium and Large, a per-widget `/Opt`, and+ /// the group's buttons in the calculation order; and a text field `name` with two widgets.+ fn radio_group_form() -> Document {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 10 0 R 11 0 R] >>".into(), // 3+ "<< /Fields [5 0 R 9 0 R] /DA (/Helv 0 Tf 0 g) /CO [7 0 R] >>".into(), // 4+ "<< /FT /Btn /Ff 49152 /T (size) /V /S /Opt [(small) (medium) (large)] /Kids [6 0 R 7 0 R 8 0 R] >>".into(), // 5+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [50 700 64 714] /P 3 0 R /AS /S /AP << /N << /S 12 0 R /Off 12 0 R >> >> >>".into(), // 6+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [80 700 94 714] /P 3 0 R /AS /Off /AP << /N << /M 12 0 R /Off 12 0 R >> >> >>".into(), // 7+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [110 700 124 714] /P 3 0 R /AS /Off /AP << /N << /L 12 0 R /Off 12 0 R >> >> >>".into(), // 8+ "<< /FT /Tx /T (name) /V (Ann) /Kids [10 0 R 11 0 R] >>".into(), // 9+ "<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [50 600 250 620] /P 3 0 R >>".into(), // 10+ "<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [300 600 500 620] /P 3 0 R >>".into(), // 11+ "<< /Length 0 >>\nstream\n\nendstream".into(), // 12+ ];+ document(&objs)+ }++ fn annots(doc: &Document) -> Vec<u32> {+ let p = page_refs(doc)[0];+ let a = doc.resolve(doc.get(p).as_dict().unwrap().get(b"Annots").unwrap());+ a.as_array().unwrap().iter().map(|o| o.as_ref().unwrap().num).collect()+ }++ #[test]+ fn deleting_one_radio_button_keeps_the_group_and_its_other_buttons() {+ let mut doc = radio_group_form();+ delete_widget(&mut doc, "size", 1).unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let size = field(&all, "size");+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [6, 8], "only Medium is gone");+ assert_eq!(size.value, ["S"], "the group keeps its choice");+ // The per-widget /Opt loses Medium's entry, so the others keep their export values.+ assert_eq!((size.export_of(0), size.export_of(1)), (Some("small"), Some("large")));+ assert_eq!(annots(&doc), [6, 8, 10, 11], "the button left the page");+ let co = doc.resolve(doc.get(ObjRef::new(4, 0)).as_dict().unwrap().get(b"CO").unwrap()).as_array().cloned().unwrap();+ assert!(co.is_empty(), "and the calculation order");+ assert!(field(&all, "name").widgets.len() == 2, "other fields are untouched");+ }++ #[test]+ fn deleting_the_chosen_radio_button_turns_the_group_off() {+ let mut doc = radio_group_form();+ delete_widget(&mut doc, "size", 0).unwrap();+ let all = fields(&reopen(&doc));+ let size = field(&all, "size");+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [7, 8]);+ assert!(size.value.is_empty(), "no button is on any more: {:?}", size.value);+ assert_eq!((size.export_of(0), size.export_of(1)), (Some("medium"), Some("large")));+ }++ #[test]+ fn deleting_the_chosen_radio_button_turns_the_group_off_when_a_twin_is_not_shown_on() {+ // Medium shares Small's on-state name but shows Off: once Small is gone, no button shows+ // the group's /V, so the group must not keep reporting it.+ let mut doc = radio_group_form();+ let twin = ObjRef::new(7, 0);+ let blank = Object::Ref(ObjRef::new(12, 0));+ let mut n = Dict::new();+ n.set(b"S".to_vec(), blank.clone());+ n.set(b"Off".to_vec(), blank);+ let mut ap = Dict::new();+ ap.set(b"N".to_vec(), Object::Dict(n));+ let mut w = doc.get(twin).as_dict().cloned().unwrap();+ w.set(b"AP".to_vec(), Object::Dict(ap));+ doc.set(twin, Object::Dict(w));+ delete_widget(&mut doc, "size", 0).unwrap();+ let all = fields(&reopen(&doc));+ let size = field(&all, "size");+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [7, 8]);+ assert!(size.value.is_empty(), "no button shows S any more: {:?}", size.value);+ }++ #[test]+ fn deleting_the_default_radio_button_clears_the_default_too() {+ // The group is off, but Reset would put back Small, which no button has once it is gone.+ let mut doc = radio_group_form();+ let size = ObjRef::new(5, 0);+ let mut d = doc.get(size).as_dict().cloned().unwrap();+ d.set(b"V".to_vec(), Object::name("Off"));+ d.set(b"DV".to_vec(), Object::name("S"));+ doc.set(size, Object::Dict(d));+ delete_widget(&mut doc, "size", 0).unwrap();+ let doc = reopen(&doc);+ let dv = doc.get(size).as_dict().and_then(|d| d.get(b"DV").cloned());+ assert_eq!(dv, Some(Object::name("Off")));+ // A default another button still has stays.+ let mut doc = radio_group_form();+ let mut d = doc.get(size).as_dict().cloned().unwrap();+ d.set(b"DV".to_vec(), Object::name("S"));+ doc.set(size, Object::Dict(d));+ delete_widget(&mut doc, "size", 1).unwrap();+ assert_eq!(doc.get(size).as_dict().and_then(|d| d.get(b"DV").cloned()), Some(Object::name("S")));+ }++ #[test]+ fn deleting_one_copy_of_a_field_keeps_the_field_and_its_value() {+ let mut doc = radio_group_form();+ delete_widget(&mut doc, "name", 0).unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let name = field(&all, "name");+ assert_eq!((name.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), name.value.clone()), (vec![11], vec!["Ann".to_string()]));+ assert_eq!(annots(&doc), [6, 7, 8, 11]);+ // The last widget takes the field with it, as deleting the field does.+ let mut doc = doc;+ delete_widget(&mut doc, "name", 0).unwrap();+ let doc = reopen(&doc);+ assert!(!fields(&doc).iter().any(|f| f.name == "name"));+ assert_eq!(annots(&doc), [6, 7, 8]);+ }++ #[test]+ fn deleting_a_radio_button_without_its_parent_link_takes_it_out_of_the_group() {+ // A damaged file: the group lists Medium in its /Kids, but Medium has no /Parent.+ for parent in [None, Some(Object::Ref(ObjRef::new(9, 0)))] {+ let mut doc = radio_group_form();+ let medium = ObjRef::new(7, 0);+ let mut w = doc.get(medium).as_dict().cloned().unwrap();+ w.remove(b"Parent");+ if let Some(p) = parent.clone() {+ w.set(b"Parent".to_vec(), p);+ }+ doc.set(medium, Object::Dict(w));+ delete_widget(&mut doc, "size", 1).unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(field(&all, "size").widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [6, 8], "/Parent {parent:?}");+ let kids = doc.resolve(doc.get(ObjRef::new(5, 0)).as_dict().unwrap().get(b"Kids").unwrap()).as_array().cloned().unwrap();+ assert!(!kids.iter().any(|k| k.as_ref() == Some(medium)), "/Parent {parent:?}: {kids:?}");+ assert_eq!(field(&all, "name").widgets.len(), 2, "/Parent {parent:?}: the other field is untouched");+ assert_eq!(annots(&doc), [6, 8, 10, 11]);+ }+ }++ #[test]+ fn deleting_a_widget_that_is_not_there_changes_nothing() {+ let mut doc = radio_group_form();+ assert_eq!(delete_widget(&mut doc, "size", 3), Err(FormError::Invalid("size has no widget 4".into())));+ assert_eq!(delete_widget(&mut doc, "nope", 0), Err(FormError::NoSuchField("nope".into())));+ assert_eq!(delete_widget(&mut doc, "size", usize::MAX), Err(FormError::Invalid(format!("size has no widget {}", usize::MAX))));+ assert_eq!(field(&fields(&doc), "size").widgets.len(), 3);+ }+ /// Two new radio groups on one page, "Group1" (export `a`) and "Group2" (export `b`).+ fn two_radio_groups(a: &str, b: &str) -> Document {+ let mut doc = one_page();+ let radio = |export: &str| NewField::Radio { group: None, export: export.into() };+ assert_eq!(add_field(&mut doc, 0, [50.0, 600.0, 64.0, 614.0], &radio(a), None).unwrap(), "Group1");+ assert_eq!(add_field(&mut doc, 0, [80.0, 600.0, 94.0, 614.0], &radio(b), None).unwrap(), "Group2");+ doc+ }++ fn rename_to(doc: &mut Document, from: &str, to: &str) -> Result<String, FormError> {+ set_props(doc, from, &FieldProps { name: Some(to.into()), ..FieldProps::default() })+ }++ fn page_widgets(doc: &Document) -> Vec<ObjRef> {+ let page = page_refs(doc)[0];+ let annots = doc.get(page).as_dict().unwrap().get(b"Annots").cloned().unwrap();+ doc.resolve(&annots).as_array().unwrap().iter().filter_map(|o| o.as_ref()).collect()+ }++ /// #4949: a radio button given its group's name is one of the group's buttons, so the group can+ /// be built up by naming buttons alike, as in Acrobat.+ #[test]+ fn a_radio_button_renamed_to_a_groups_name_joins_the_group() {+ let mut doc = two_radio_groups("Yes", "No");+ set_value(&mut doc, "Group1", &FieldValue::Radio(Some("Yes".into()))).unwrap();+ let before = page_widgets(&doc);+ assert_eq!(rename_to(&mut doc, "Group2", "Group1").unwrap(), "Group1");+ assert_eq!(page_widgets(&doc), before, "the buttons stay on the page where they were");+ let mut doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(all.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["Group1"]);+ let group = field(&all, "Group1");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Yes", "No"]);+ assert_eq!(group.value, ["Yes"], "the group keeps its value");+ assert_eq!(group.widgets.iter().map(|w| w.state.clone()).collect::<Vec<_>>(), [Some("Yes".into()), Some("Off".into())]);+ assert_eq!(page_widgets(&doc), group.widgets.iter().map(|w| w.obj).collect::<Vec<_>>());+ // Choosing the moved button turns the other off: they are one group.+ set_value(&mut doc, "Group1", &FieldValue::Radio(Some("No".into()))).unwrap();+ let group = field(&fields(&doc), "Group1").clone();+ assert_eq!(group.widgets.iter().map(|w| w.state.clone()).collect::<Vec<_>>(), [Some("Off".into()), Some("No".into())]);+ }++ /// Joining redraws only the buttons that moved: the group's own keep their appearances, which may+ /// be custom ones a redraw would replace.+ #[test]+ fn joining_a_group_leaves_its_own_buttons_appearances_as_they_are() {+ let mut doc = two_radio_groups("Yes", "No");+ let own = field(&fields(&doc), "Group1").widgets[0].obj;+ let look = |doc: &Document| doc.get(own).as_dict().and_then(|d| d.get(b"AP").cloned());+ let before = look(&doc);+ assert!(before.is_some());+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ assert_eq!(look(&doc), before);+ let group = field(&fields(&doc), "Group1").clone();+ assert!(group.widgets[1].on_state.as_deref() == Some("No"), "the moved button is drawn with its states");+ }++ /// A joining button whose export value a button of the group already has takes the next free+ /// "ChoiceN", in its appearance states too, so the two can be chosen apart.+ #[test]+ fn a_joining_radio_button_with_a_taken_export_value_takes_a_free_one() {+ let mut doc = two_radio_groups("Choice1", "Choice1");+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let group = field(&all, "Group1");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Choice1", "Choice2"]);+ let moved = doc.get(group.widgets[1].obj).as_dict().unwrap().clone();+ let normal = doc.resolve(moved.get(b"AP").unwrap()).as_dict().unwrap().get(b"N").cloned().unwrap();+ let normal = doc.resolve(&normal).as_dict().unwrap().clone();+ assert!(normal.contains(b"Choice2") && !normal.contains(b"Choice1"));+ }++ /// A group whose `/Kids` is an indirect array keeps its own buttons when another joins it.+ #[test]+ fn a_group_with_indirect_kids_keeps_its_buttons_when_joined() {+ let mut doc = two_radio_groups("Yes", "No");+ let group = field(&fields(&doc), "Group1").obj;+ let kids = doc.get(group).as_dict().unwrap().get(b"Kids").cloned().unwrap();+ let held = doc.add(kids);+ doc.update_dict(group, |d| d.set(b"Kids".to_vec(), Object::Ref(held))).unwrap();+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(field(&all, "Group1").widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Yes", "No"]);+ }++ /// Buttons of the joining group that share an export value (a button repeated on another page,+ /// on together) still share it after the join, under one fresh name.+ #[test]+ fn joining_radio_buttons_that_share_a_value_keep_sharing_it() {+ let mut doc = two_radio_groups("Choice1", "Choice1");+ let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();+ let mut p = pdfcraft_cos::Dict::new();+ p.set(b"Type".to_vec(), Object::name("Page"));+ p.set(b"Parent".to_vec(), Object::Ref(pages));+ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 600.into(), 800.into()]));+ let r = doc.add(Object::Dict(p));+ doc.update_dict(pages, |d| {+ let mut kids = d.get(b"Kids").unwrap().as_array().unwrap().clone();+ kids.push(Object::Ref(r));+ d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));+ d.set(b"Kids".to_vec(), Object::Array(kids));+ })+ .unwrap();+ assert_eq!(duplicate_field(&mut doc, "Group2", &[1]).unwrap(), 1);+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let doc = reopen(&doc);+ let all = fields(&doc);+ let group = field(&all, "Group1");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["Choice1", "Choice2", "Choice2"]);+ }++ /// One page holding radio fields that are each their own only widget, as other writers make+ /// one-button groups: `(name, export value, x)`.+ fn merged_radios(specs: &[(&str, &str, f64)]) -> Document {+ let mut doc = one_page();+ let page = page_refs(&doc)[0];+ let af = crate::author::ensure_form(&mut doc).unwrap();+ let mut made = Vec::new();+ for &(name, state, x) in specs {+ let look = doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), b"0 g".to_vec())));+ let mut n = pdfcraft_cos::Dict::new();+ n.set(state.as_bytes().to_vec(), Object::Ref(look));+ n.set(b"Off".to_vec(), Object::Ref(look));+ let mut ap = pdfcraft_cos::Dict::new();+ ap.set(b"N".to_vec(), Object::Dict(n));+ let mut d = pdfcraft_cos::Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name("Widget"));+ d.set(b"FT".to_vec(), Object::name("Btn"));+ d.set(b"Ff".to_vec(), Object::Int(i64::from(flags::RADIO)));+ d.set(b"T".to_vec(), pdfcraft_cos::PdfString::text(name));+ d.set(b"Rect".to_vec(), Object::Array(vec![x.into(), 600.into(), (x + 14.0).into(), 614.into()]));+ d.set(b"P".to_vec(), Object::Ref(page));+ d.set(b"AP".to_vec(), Object::Dict(ap));+ d.set(b"AS".to_vec(), Object::name("Off"));+ let r = doc.add(Object::Dict(d));+ doc.update_dict(af, |a| {+ let mut list = a.get(b"Fields").and_then(|l| l.as_array().cloned()).unwrap_or_default();+ list.push(Object::Ref(r));+ a.set(b"Fields".to_vec(), Object::Array(list));+ })+ .unwrap();+ made.push(r);+ }+ doc.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Array(made.iter().map(|r| Object::Ref(*r)).collect()))).unwrap();+ doc+ }++ /// A radio field that is its own (only) widget, as other writers make one-button groups, can+ /// both join a group and be joined.+ #[test]+ fn radio_fields_that_are_their_own_widget_join_and_are_joined() {+ let mut doc = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ assert_eq!(rename_to(&mut doc, "other", "solo").unwrap(), "solo");+ let doc = reopen(&doc);+ let all = fields(&doc);+ assert_eq!(all.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["solo"]);+ let group = field(&all, "solo");+ assert_eq!(group.widgets.iter().filter_map(|w| w.on_state.clone()).collect::<Vec<_>>(), ["A", "B"]);+ // The joined field's widget became a kid; the moved one shed its field entries.+ let kids: Vec<ObjRef> = group.widgets.iter().map(|w| w.obj).collect();+ assert!(!kids.contains(&group.obj));+ let moved = doc.get(group.widgets[1].obj).as_dict().unwrap().clone();+ assert!(!moved.contains(b"T") && !moved.contains(b"FT") && moved.reference(b"Parent") == Some(group.obj));+ let mut on_page = page_widgets(&doc);+ on_page.sort();+ let mut kids = kids;+ kids.sort();+ assert_eq!(on_page, kids, "the page lists the widgets, not the field");+ }++ /// A group that is its own only widget keeps its button's actions when another button joins+ /// it: the new widget takes `/A` and the widget triggers of `/AA`, and the field keeps its own.+ #[test]+ fn a_joined_merged_groups_button_keeps_its_actions() {+ let mut doc = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ let solo = field(&fields(&doc), "solo").obj;+ let js = |code: &str| {+ let mut a = pdfcraft_cos::Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), pdfcraft_cos::PdfString::text(code));+ Object::Dict(a)+ };+ let mut aa = pdfcraft_cos::Dict::new();+ aa.set(b"Fo".to_vec(), js("focus();"));+ aa.set(b"V".to_vec(), js("validate();"));+ let aa = doc.add(Object::Dict(aa));+ doc.update_dict(solo, |d| {+ d.set(b"A".to_vec(), js("up();"));+ d.set(b"AA".to_vec(), Object::Ref(aa));+ })+ .unwrap();+ rename_to(&mut doc, "other", "solo").unwrap();+ let doc = reopen(&doc);+ assert_eq!(+ field_actions(&doc, "solo").unwrap(),+ [(Trigger::MouseUp, FieldAction::JavaScript("up();".into())), (Trigger::OnFocus, FieldAction::JavaScript("focus();".into()))]+ );+ let group = field(&fields(&doc), "solo").clone();+ let fd = doc.get(group.obj).as_dict().unwrap().clone();+ let field_aa = doc.resolve(fd.get(b"AA").unwrap()).as_dict().unwrap().clone();+ assert!(!fd.contains(b"A") && field_aa.contains(b"V") && !field_aa.contains(b"Fo"), "the field keeps only its own trigger");+ let wd = doc.get(group.widgets[0].obj).as_dict().unwrap().clone();+ let widget_aa = doc.resolve(wd.get(b"AA").unwrap()).as_dict().unwrap().clone();+ assert!(widget_aa.contains(b"Fo") && !widget_aa.contains(b"V"));+ }++ /// A joining button that was its own field keeps its widget triggers and drops the field's.+ #[test]+ fn a_joining_merged_button_sheds_its_fields_triggers() {+ let mut doc = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ let other = field(&fields(&doc), "other").obj;+ let js = |code: &str| {+ let mut a = pdfcraft_cos::Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), pdfcraft_cos::PdfString::text(code));+ Object::Dict(a)+ };+ let mut aa = pdfcraft_cos::Dict::new();+ aa.set(b"U".to_vec(), js("up();"));+ aa.set(b"V".to_vec(), js("validate();"));+ aa.set(b"C".to_vec(), js("calc();"));+ let aa = doc.add(Object::Dict(aa));+ doc.update_dict(other, |d| d.set(b"AA".to_vec(), Object::Ref(aa))).unwrap();+ rename_to(&mut doc, "other", "solo").unwrap();+ let doc = reopen(&doc);+ let group = field(&fields(&doc), "solo").clone();+ let moved = group.widgets.iter().find(|w| w.on_state.as_deref() == Some("B")).unwrap();+ let wd = doc.get(moved.obj).as_dict().unwrap().clone();+ let widget_aa = doc.resolve(wd.get(b"AA").unwrap()).as_dict().unwrap().clone();+ assert!(widget_aa.contains(b"U") && !widget_aa.contains(b"V") && !widget_aa.contains(b"C"), "only the widget's trigger stays");+ let mut once = merged_radios(&[("solo", "A", 50.0), ("other", "B", 80.0)]);+ let other = field(&fields(&once), "other").obj;+ let mut aa = pdfcraft_cos::Dict::new();+ aa.set(b"V".to_vec(), js("validate();"));+ once.update_dict(other, |d| d.set(b"AA".to_vec(), Object::Dict(aa))).unwrap();+ rename_to(&mut once, "other", "solo").unwrap();+ let once = reopen(&once);+ let group = field(&fields(&once), "solo").clone();+ let moved = group.widgets.iter().find(|w| w.on_state.as_deref() == Some("B")).unwrap();+ let wd = once.get(moved.obj).as_dict().unwrap().clone();+ assert!(!wd.contains(b"AA"), "a widget left with no trigger has no /AA");+ }++ /// However many "ChoiceN" names a group already uses, a joining button with a clashing export+ /// value gets a free one, so the two buttons can still be chosen apart.+ #[test]+ fn a_joining_button_gets_a_free_export_value_when_choice_names_run_long() {+ let mut doc = two_radio_groups("Choice1", "Choice1");+ let group = field(&fields(&doc), "Group1").clone();+ let model = doc.get(group.widgets[0].obj).as_dict().unwrap().clone();+ let look = doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), b"0 g".to_vec())));+ let mut kids = vec![Object::Ref(group.widgets[0].obj)];+ for i in 2..=10_000 {+ let mut n = pdfcraft_cos::Dict::new();+ n.set(format!("Choice{i}").into_bytes(), Object::Ref(look));+ n.set(b"Off".to_vec(), Object::Ref(look));+ let mut ap = pdfcraft_cos::Dict::new();+ ap.set(b"N".to_vec(), Object::Dict(n));+ let mut w = model.clone();+ w.set(b"AP".to_vec(), Object::Dict(ap));+ w.remove(b"P");+ kids.push(Object::Ref(doc.add(Object::Dict(w))));+ }+ doc.update_dict(group.obj, |d| d.set(b"Kids".to_vec(), Object::Array(kids))).unwrap();+ rename_to(&mut doc, "Group2", "Group1").unwrap();+ let group = field(&fields(&doc), "Group1").clone();+ let states: Vec<String> = group.widgets.iter().filter_map(|w| w.on_state.clone()).collect();+ assert_eq!(states.len(), 10_001);+ assert_eq!(states.last().map(String::as_str), Some("Choice10001"));+ }++ /// Only a radio button joins by name: other clashes are refused as before, and a locked group+ /// isn't changed.+ #[test]+ fn joining_by_name_is_only_for_radio_buttons_and_unlocked_groups() {+ let mut doc = two_radio_groups("Yes", "No");+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &NewField::Text { multiline: false }, Some("note")).unwrap();+ assert!(rename_to(&mut doc, "note", "Group1").is_err(), "a text field doesn't join a radio group");+ assert!(rename_to(&mut doc, "Group2", "note").is_err(), "a radio button doesn't join a text field");+ set_props(&mut doc, "Group1", &FieldProps { locked: Some(true), ..FieldProps::default() }).unwrap();+ assert!(rename_to(&mut doc, "Group2", "Group1").is_err(), "a locked group");+ assert_eq!(fields(&doc).len(), 3);+ }++ /// `/I` of field `name`: the selected positions in `/Opt`, or `None` when absent.+ fn selection_indices(doc: &Document, name: &str) -> Option<Vec<i64>> {+ let f = field(&fields(doc), name).clone();+ let d = doc.get(f.obj).as_dict().cloned().unwrap();+ d.get(b"I").map(|i| doc.resolve(i).as_array().unwrap().iter().map(|o| o.as_int().unwrap()).collect())+ }++ #[test]+ fn changing_a_lists_options_repoints_its_selected_indices() {+ let mut doc = one_page();+ let list =+ add_field(&mut doc, 0, [50.0, 600.0, 250.0, 680.0], &NewField::List { options: vec!["A".into(), "B".into(), "C".into()], multi: true }, None)+ .unwrap();+ set_value(&mut doc, &list, &FieldValue::Choice(vec!["C".into(), "B".into()])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![1, 2]));+ let f = field(&fields(&doc), &list).clone();+ doc.update_dict(f.obj, |d| d.set(b"TI".to_vec(), Object::Int(2))).unwrap();+ // Removing A moves B and C up one place.+ let opts = |o: &[&str]| FieldProps { options: Some(o.iter().map(|s| s.to_string()).collect()), ..FieldProps::default() };+ set_props(&mut doc, &list, &opts(&["B", "C", "D"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![0, 1]));+ // Removing B leaves only C selected; the top row would point past the end.+ set_props(&mut doc, &list, &opts(&["C"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![0]));+ assert_eq!(top_row(&doc, f.obj), Some(0), "the list scrolls back to its only row");+ // No selected value is offered any more.+ set_props(&mut doc, &list, &opts(&["X", "Y"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), None);+ let doc = reopen(&doc);+ assert_eq!(selection_indices(&doc, &list), None);+ }++ fn top_row(doc: &Document, obj: ObjRef) -> Option<i64> {+ doc.get(obj).as_dict().and_then(|d| d.get(b"TI")).and_then(|o| o.as_int())+ }++ #[test]+ fn shrinking_a_lists_options_scrolls_a_widget_with_its_own_top_row() {+ let objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [7 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ "<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E) (F)] /V (F) /I [5] /Kids [7 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /TI 5 /Rect [50 700 250 720] /P 3 0 R >>".into(),+ ];+ let mut doc = document(&objs);+ let widget = ObjRef::new(7, 0);+ set_props(&mut doc, "pick", &FieldProps { options: Some(vec!["F".into(), "A".into()]), ..FieldProps::default() }).unwrap();+ assert_eq!(selection_indices(&doc, "pick"), Some(vec![0]));+ // The widget's own /TI is read before the field's; row 5 no longer exists.+ assert_eq!(top_row(&doc, widget), Some(0), "the widget scrolls to F, now row 0");+ let doc = reopen(&doc);+ assert_eq!(top_row(&doc, widget), Some(0));+ }++ #[test]+ fn each_widget_with_its_own_top_row_scrolls_by_itself() {+ // Widget 7 shows from the field's top row; widget 8 keeps its own /TI 4.+ let objs = |v: &str| -> Vec<String> {+ vec![+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ format!("<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E) (F)] {v} /Kids [7 0 R 8 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /Rect [50 700 250 740] /P 3 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /TI 4 /Rect [50 600 250 620] /P 3 0 R >>".into(),+ ]+ };+ let (first, other) = (ObjRef::new(7, 0), ObjRef::new(8, 0));+ // The options shrink: the first widget already shows A, the other's row 4 is gone.+ let mut doc = document(&objs("/V (A) /I [0]"));+ set_props(&mut doc, "pick", &FieldProps { options: Some(vec!["A".into(), "B".into()]), ..FieldProps::default() }).unwrap();+ assert_eq!(top_row(&doc, first), None);+ assert_eq!(top_row(&reopen(&doc), other), Some(0), "options: the other widget scrolls to A");+ // A new value the first widget already shows, below the other's view.+ let mut doc = document(&objs("/V (B) /I [1]"));+ set_value(&mut doc, "pick", &FieldValue::Choice(vec!["A".into()])).unwrap();+ assert_eq!(top_row(&doc, ObjRef::new(6, 0)), None, "the field's top row did not move");+ assert_eq!(top_row(&reopen(&doc), other), Some(0), "value: the other widget scrolls to A");+ }++ /// A list box's top row is chosen with the font size set in the same edit: at the larger size+ /// fewer rows fit, so it scrolls further to keep the selection in view.+ #[test]+ fn a_list_boxs_top_row_follows_a_font_size_changed_with_its_items() {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ "<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E)] /V (C) /I [2] /Type /Annot /Subtype /Widget /Rect [50 700 250 740] /P 3 0 R >>".into(),+ ]);+ let items = ["Z", "A", "B", "C", "D"].map(String::from).to_vec();+ set_props(&mut doc, "pick", &FieldProps { options: Some(items), font_size: Some(20.0), ..FieldProps::default() }).unwrap();+ let doc = reopen(&doc);+ let g = field(&fields(&doc), "pick").clone();+ let w = &g.widgets[0];+ let rows = w.list.unwrap();+ let shown = rows.top..rows.top + rows.visible(w.rect[3] - w.rect[1]);+ assert!(shown.contains(&3), "C is row 3; rows {shown:?} show");+ }++ #[test]+ fn sorting_a_combo_boxs_items_repoints_its_selected_index() {+ let mut doc = one_page();+ let combo = add_field(+ &mut doc,+ 0,+ [50.0, 600.0, 250.0, 620.0],+ &NewField::Combo { options: vec!["Pear".into(), "apple".into(), "Fig".into()], editable: false },+ None,+ )+ .unwrap();+ set_value(&mut doc, &combo, &FieldValue::Choice(vec!["Pear".into()])).unwrap();+ assert_eq!(selection_indices(&doc, &combo), Some(vec![0]));+ set_props(&mut doc, &combo, &FieldProps { flags: vec![(flags::SORT, true)], ..FieldProps::default() }).unwrap();+ // apple, Fig, Pear: the selection follows Pear to the end.+ assert_eq!(selection_indices(&doc, &combo), Some(vec![2]));+ assert_eq!(field(&fields(&doc), &combo).value, vec!["Pear".to_string()]);+ }++ #[test]+ fn sorting_keeps_which_of_two_items_with_one_export_value_is_selected() {+ let mut doc = one_page();+ let list = add_field(&mut doc, 0, [50.0, 600.0, 250.0, 680.0], &NewField::List { options: vec!["a".into()], multi: false }, None).unwrap();+ let f = field(&fields(&doc), &list).clone();+ let item = |e: &str, shown: &str| Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(shown))]);+ // Zeta and Alpha both export "x"; `/I` says Zeta is the one selected.+ doc.update_dict(f.obj, |d| {+ d.set(b"Opt".to_vec(), Object::Array(vec![item("x", "Zeta"), item("x", "Alpha"), item("y", "Mid")]));+ d.set(b"V".to_vec(), PdfString::text("x"));+ d.set(b"I".to_vec(), Object::Array(vec![Object::Int(0)]));+ })+ .unwrap();+ set_props(&mut doc, &list, &FieldProps { flags: vec![(flags::SORT, true)], ..FieldProps::default() }).unwrap();+ // Alpha, Mid, Zeta: the selection follows Zeta, not the first item exporting "x".+ assert_eq!(selection_indices(&doc, &list), Some(vec![2]));+ }++ #[test]+ fn clearing_a_kids_default_does_not_bring_back_its_parents() {+ let mut doc = fixture();+ let all = fields(&doc);+ let city = field(&all, "address.city").clone();+ let parent = doc.get(city.obj).as_dict().unwrap().reference(b"Parent").unwrap();+ doc.update_dict(parent, |d| d.set(b"DV".to_vec(), PdfString::text("Main St"))).unwrap();+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(Some("Elm".into())), ..FieldProps::default() }).unwrap();+ assert_eq!(field(&fields(&doc), "address.city").default, ["Elm"]);+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ let mut doc = reopen(&doc);+ let f = field(&fields(&doc), "address.city").clone();+ assert!(f.default.iter().all(String::is_empty), "no default, not the parent's: {:?}", f.default);+ let own = doc.get(f.obj).as_dict().and_then(|d| d.get(b"DV")).and_then(|o| o.as_string()).map(PdfString::to_text);+ assert_eq!(own.as_deref(), Some(""), "the kid holds an empty default of its own");+ set_value(&mut doc, "address.city", &FieldValue::Text("Oak".into())).unwrap();+ reset(&mut doc, None).unwrap();+ assert!(field(&fields(&doc), "address.city").value.iter().all(String::is_empty), "reset clears it");+ // Without a parent default, clearing still removes the key.+ set_props(&mut doc, "name", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ let name = field(&fields(&doc), "name").clone();+ assert!(doc.get(name.obj).as_dict().unwrap().get(b"DV").is_none());+ }++ #[test]+ fn clearing_a_kids_value_does_not_bring_back_its_parents() {+ // A text kid, then a list box kid, under a parent with both a value and a default.+ for (ft, set) in [("/FT /Tx", FieldValue::Text("Oak".into())), ("/FT /Ch /Opt [(Main St) (Oak)]", FieldValue::Choice(vec!["Oak".into()]))] {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),+ format!("<< /T (address) {ft} /V (Main St) /DV (Main St) /Kids [6 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /Rect [10 10 110 60] /P 3 0 R >>".into(),+ ]);+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ set_value(&mut doc, "address.city", &set).unwrap();+ assert_eq!(field(&fields(&doc), "address.city").value, ["Oak"], "{ft}");+ reset(&mut doc, None).unwrap();+ let doc = reopen(&doc);+ let f = field(&fields(&doc), "address.city").clone();+ assert!(f.value.iter().all(String::is_empty), "{ft}: reset leaves it empty, not the parent's: {:?}", f.value);+ let mut doc = doc;+ set_value(&mut doc, "address.city", &set).unwrap();+ let clear = if ft.contains("Ch") { FieldValue::Choice(Vec::new()) } else { FieldValue::Text(String::new()) };+ set_value(&mut doc, "address.city", &clear).unwrap();+ let f = field(&fields(&reopen(&doc)), "address.city").clone();+ if ft.contains("Ch") {+ assert!(f.value.is_empty(), "{ft}: clearing leaves no choice selected: {:?}", f.value);+ } else {+ assert!(f.value.iter().all(String::is_empty), "{ft}: clearing leaves it empty: {:?}", f.value);+ }+ }+ }++ #[test]+ fn clearing_a_buttons_default_under_a_parent_with_one_leaves_it_off() {+ // A check box, then a radio button (flags 49152, inherited from the parent).+ for flags in ["", "/Ff 49152"] {+ let mut doc = document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),+ format!("<< /T (opts) /FT /Btn {flags} /DV /Yes /Kids [6 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /T (a) /Parent 5 0 R /V /Off /AS /Off /Rect [10 10 25 25] /P 3 0 R /AP << /N << /Yes 7 0 R /Off 7 0 R >> >> >>".into(),+ "<< /Length 0 >>+ stream++ endstream".into(),+ ]);+ let kind = field(&fields(&doc), "opts.a").kind;+ assert_eq!(kind == FieldKind::Radio, !flags.is_empty());+ set_props(&mut doc, "opts.a", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();+ let f = field(&fields(&doc), "opts.a").clone();+ assert_eq!(doc.get(f.obj).as_dict().and_then(|d| d.get(b"DV")).and_then(|o| o.as_name()), Some(&b"Off"[..]), "{kind:?}");+ let on = if kind == FieldKind::Radio { FieldValue::Radio(Some("Yes".into())) } else { FieldValue::Check(true) };+ set_value(&mut doc, "opts.a", &on).unwrap();+ assert_eq!(field(&fields(&doc), "opts.a").value, ["Yes"]);+ reset(&mut doc, None).unwrap();+ let f = field(&fields(&doc), "opts.a").clone();+ assert!(f.value.iter().all(String::is_empty), "{kind:?}: reset leaves it off, not the parent's Yes: {:?}", f.value);+ }+ }++++#[test]++fn editing_button_export_values_preserves_selection_and_appearance() {++ let mut doc = fixture();++ set_value(&mut doc, "size", &FieldValue::Radio(Some("S".into()))).unwrap();++ let before = field(&fields(&doc), "size").clone();++ let appearances: Vec<_> = before.widgets.iter().map(|w| doc.get(w.obj).as_dict().unwrap().get(b"AP").cloned()).collect();++ set_props(&mut doc, "size", &FieldProps { export_value: Some((0, "Small å".into())), ..Default::default() }).unwrap();++ let after = field(&fields(&doc), "size").clone();++ assert_eq!(after.value, before.value);++ assert_eq!(after.default, before.default);++ assert_eq!(after.widgets, before.widgets);++ assert_eq!(after.export_of(0), Some("Small å"));++ assert_eq!(after.export_of(1), before.export_of(1));++ assert_eq!(after.export_values(), vec!["Small å"]);++ assert_eq!(appearances, after.widgets.iter().map(|w| doc.get(w.obj).as_dict().unwrap().get(b"AP").cloned()).collect::<Vec<_>>());++ let mut saved = reopen(&doc);++ assert_eq!(field(&fields(&saved), "size").export_of(0), Some("Small å"));++ set_value(&mut saved, "size", &FieldValue::Radio(Some("Small å".into()))).unwrap();++ reset(&mut saved, None).unwrap();++ assert_eq!(field(&fields(&saved), "size").value, before.default);++++ set_value(&mut doc, "agree", &FieldValue::Check(true)).unwrap();++ set_props(&mut doc, "agree", &FieldProps { export_value: Some((0, "Accepted".into())), ..Default::default() }).unwrap();++ let check = field(&fields(&doc), "agree").clone();++ assert_eq!(check.value, vec!["Yes"]);++ assert_eq!(check.export_values(), vec!["Accepted"]);++ assert_eq!(field(&fields(&reopen(&doc)), "agree").export_of(0), Some("Accepted"));++}++++#[test]++fn invalid_button_export_edits_leave_document_unchanged() {++ let mut doc = fixture();++ let before = write_incremental(&doc, &SaveOptions::default()).unwrap();++ for (field_name, index, value) in [("size", 99, "new"), ("size", 0, ""), ("size", 0, "Off"), ("size", 0, "L"), ("name", 0, "new")] {++ assert!(set_props(&mut doc, field_name, &FieldProps { export_value: Some((index, value.into())), ..Default::default() }).is_err());++ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);++ }++}+++#[test]+fn locked_button_export_edits_leave_the_document_unchanged() {+ for name in ["agree", "size"] {+ let mut doc = fixture();+ set_props(&mut doc, name, &FieldProps { locked: Some(true), ..Default::default() }).unwrap();+ let before = write_incremental(&doc, &SaveOptions::default()).unwrap();+ let error = set_props(+ &mut doc,+ name,+ &FieldProps { export_value: Some((0, "Changed".into())), tooltip: Some("Must not change".into()), ..Default::default() },+ )+ .unwrap_err();+ assert!(error.to_string().contains("locked"));+ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);+ }+}diff --cc crates/ui-egui/src/i18n/ar.tsvindex 848afbe29,3e6d73552..6506d2733--- a/crates/ui-egui/src/i18n/ar.tsv+++ b/crates/ui-egui/src/i18n/ar.tsv@@@ -2709,4 -2775,61 +2775,62 @@@ certificate Version الإصدا�Make properties default جعل الخصائص افتراضيةPages selected الصفحات المحددةPage properties خصائص الصفحة+ Create & Edit الإنشاء والتحرير+ Review & Compare المراجعة والمقارنة+ Forms & Signatures النماذج والتوقيعات+ Protect & Standardize الحماية والتوحيد القياسي+ Customize & Automate التخصيص والأتمتة+ No tools match your search. لا توجد أدوات تطابق بحثك.+ Expand all tools توسيع كل الأدوات+ Collapse all tools طي كل الأدوات+ Attach a file… إرفاق ملف…+ Delete attachment حذف المرفق+ Attaching files is not available on the web yet إرفاق الملفات غير متاح على الويب بعد+ Attach {name} إرفاق {name}+ Delete attachment {key} حذف المرفق {key}+ Bulleted list قائمة نقطية+ Numbered list قائمة مرقمة+ Alignment المحاذاة+ Superscript نص مرتفع+ Subscript نص منخفض+ Paragraph spacing تباعد الفقرات+ Less أقل+ Other options خيارات أخرى+ Thumbnail size حجم الصور المصغرة+ Smaller thumbnails تصغير الصور المصغرة+ Larger thumbnails تكبير الصور المصغرة+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment إعادة تشكيل التعليق++ # Prepare a form ▸ Text field table+ Add text field table إضافة جدول حقول نصية+ Text field table جدول حقول نصية+ Text Field Table جدول حقول نصية+ Columns الأعمدة+ Row spacing المسافة بين الصفوف+ Column spacing المسافة بين الأعمدة+ First row number رقم الصف الأول+ Column widths عروض الأعمدة+ Distribute evenly توزيع بالتساوي+ Field names أسماء الحقول+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N أو {row} هو رقم الصف، و{col} رقم العمود، و{seq} رقم الخلية. إذا لم يوجد أي منها، يُضاف رقم الصف في النهاية.+ Column {n} العمود {n}+ Add fields إضافة الحقول+ the rows are too short: make the area taller, or use fewer rows or less row spacing الصفوف قصيرة جدًا: اجعل المنطقة أطول، أو استخدم صفوفًا أقل أو مسافة أقل بين الصفوف+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing أحد الأعمدة ضيق جدًا: اجعل المنطقة أعرض، أو امنح العمود عرضًا أكبر، أو استخدم أعمدة أقل أو مسافة أقل بين الأعمدة+ field names can't contain a period: {name} لا يمكن أن تحتوي أسماء الحقول على نقطة: {name}+ two cells would both be named {name} ستحمل خليتان الاسم نفسه {name}+ a field named {name} already exists يوجد حقل باسم {name} بالفعل++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today اليوم+ @plural {n} reply|{n} replies {n} رد|{n} رد|{n} ردّان|{n} ردود|{n} ردًا|{n} رد++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools أدوات الصفحات+ Insert pages from a file after the selection… إدراج صفحات من ملف بعد التحديد…+ Rotate the selected pages counterclockwise تدوير الصفحات المحددة عكس اتجاه عقارب الساعة+ Rotate the selected pages clockwise تدوير الصفحات المحددة باتجاه عقارب الساعة+ Extract the selected pages… استخراج الصفحات المحددة…+ Delete the selected pages حذف الصفحات المحددة+ Export value قيمة التصديرdiff --cc crates/ui-egui/src/i18n/bg.tsvindex 0baabfaaa,ec0339f18..34ee45220--- a/crates/ui-egui/src/i18n/bg.tsv+++ b/crates/ui-egui/src/i18n/bg.tsv@@@ -2395,4 -2461,62 +2461,63 @@@ animation effects Off Изключен�Make properties default Задаване като свойства по подразбиранеPages selected Избрани странициPage properties Свойства на страницата+ Create & Edit Създаване и редактиране+ Review & Compare Преглед и сравнение+ Forms & Signatures Формуляри и подписи+ Protect & Standardize Защита и стандартизация+ Customize & Automate Персонализиране и автоматизация+ No tools match your search. Няма инструменти, отговарящи на търсенето.+ Expand all tools Разгъване на всички инструменти+ Collapse all tools Свиване на всички инструменти+ Attach a file… Прикачване на файл…+ Delete attachment Изтриване на прикачения файл+ Attaching files is not available on the web yet Прикачването на файлове още не е налично в уеб версията+ Attach {name} Прикачване на {name}+ Delete attachment {key} Изтриване на прикачения файл {key}+ Font Шрифт+ Bulleted list Списък с водещи символи+ Numbered list Номериран списък+ Alignment Подравняване+ Superscript Горен индекс+ Subscript Долен индекс+ Paragraph spacing Разстояние между абзаците+ Less По-малко+ Other options Други опции+ Thumbnail size Размер на миниатюрите+ Smaller thumbnails По-малки миниатюри+ Larger thumbnails По-големи миниатюри+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Промяна на формата на коментара++ # Prepare a form ▸ Text field table+ Add text field table Добави таблица от текстови полета+ Text field table Таблица от текстови полета+ Text Field Table Таблица от текстови полета+ Columns Колони+ Row spacing Разстояние между редовете+ Column spacing Разстояние между колоните+ First row number Номер на първия ред+ Column widths Ширини на колоните+ Distribute evenly Разпредели равномерно+ Field names Имена на полетата+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N или {row} е номерът на реда, {col} – на колоната, {seq} – на клетката. Без тях номерът на реда се добавя накрая.+ Column {n} Колона {n}+ Add fields Добави полета+ the rows are too short: make the area taller, or use fewer rows or less row spacing редовете са твърде ниски: направете областта по-висока или използвайте по-малко редове или по-малко разстояние между тях+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing колона е твърде тясна: направете областта по-широка, дайте ѝ повече място или използвайте по-малко колони или по-малко разстояние между тях+ field names can't contain a period: {name} имената на полетата не може да съдържат точка: {name}+ two cells would both be named {name} две клетки биха имали едно и също име {name}+ a field named {name} already exists вече съществува поле с име {name}++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Днес+ @plural {n} reply|{n} replies {n} отговор|{n} отговора++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Инструменти за страници+ Insert pages from a file after the selection… Вмъкване на страници от файл след избраното…+ Rotate the selected pages counterclockwise Завъртане на избраните страници обратно на часовниковата стрелка+ Rotate the selected pages clockwise Завъртане на избраните страници по часовниковата стрелка+ Extract the selected pages… Извличане на избраните страници…+ Delete the selected pages Изтриване на избраните страници+ Export value Стойност за експортиранеdiff --cc crates/ui-egui/src/i18n/cs.tsvindex e3602b09e,ed6d051b5..a99c62623--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@@ -2506,4 -2572,295 +2572,296 @@@ animation effects Off VypnutMake properties default Nastavit vlastnosti jako výchozíPages selected Vybrané stránkyPage properties Vlastnosti stránky+ Create & Edit Vytváření a úpravy+ Review & Compare Revize a porovnání+ Forms & Signatures Formuláře a podpisy+ Protect & Standardize Ochrana a standardizace+ Customize & Automate Přizpůsobení a automatizace+ No tools match your search. Hledání neodpovídá žádný nástroj.+ Expand all tools Rozbalit všechny nástroje+ Collapse all tools Sbalit všechny nástroje+ Attach a file… Připojit soubor…+ Delete attachment Odstranit přílohu+ Attaching files is not available on the web yet Připojování souborů zatím na webu není k dispozici+ Attach {name} Připojit {name}+ Delete attachment {key} Odstranit přílohu {key}+ Font Písmo+ Bulleted list Odrážkový seznam+ Numbered list Číslovaný seznam+ Alignment Zarovnání+ Superscript Horní index+ Subscript Dolní index+ Paragraph spacing Mezera mezi odstavci+ Less Méně+ Other options Další možnosti+ Thumbnail size Velikost miniatur+ Smaller thumbnails Menší miniatury+ Larger thumbnails Větší miniatury+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Změnit tvar komentáře++ # What the layers below word for themselves (engine `WORDINGS` lists): accessibility findings and+ # the saved report, PDF/A problems, signature details and the changes they name, pages to print,+ # history labels. Terms: timestamp = "časové razítko", timestamp authority = "autorita časových+ # razítek", signer = "podepisující osoba", byte range = "rozsah bajtů".+ A font isn't embedded Písmo není vložené+ A {} action isn't allowed Akce {} není povolena+ A {} annotation has additional actions Anotace {} má další akce+ A {} annotation has no appearance stream Anotace {} nemá datový proud vzhledu+ A {} annotation isn't set to print, or is hidden Anotace {} není nastavena k tisku nebo je skrytá+ Accessibility Report Zpráva o přístupnosti+ Change Author Změnit: Autor+ Change Keywords Změnit: Klíčová slova+ Change Subject Změnit: Předmět+ Change Title Změnit: Název+ Create links Vytvořit odkazy+ Detailed Report Podrobná zpráva+ DeviceCMYK is used, but the PDF/A output intent isn't a CMYK profile Je použit DeviceCMYK, ale výstupní záměr PDF/A není profil CMYK+ DeviceRGB is used, but the PDF/A output intent isn't an RGB profile Je použit DeviceRGB, ale výstupní záměr PDF/A není profil RGB+ Field "{}" on page {p} has no description (tooltip) Pole „{}“ na stránce {p} nemá popis (popisek nástroje)+ Filename Název souboru+ Flatten Fill & Sign Sloučit Vyplnit a podepsat se stránkou+ Font (unnamed) on page {p} doesn't map its characters to Unicode Písmo (bez názvu) na stránce {p} nemapuje své znaky na Unicode+ Font {} on page {p} doesn't map its characters to Unicode Písmo {} na stránce {p} nemapuje své znaky na Unicode+ Form field on page {p} isn't tagged Formulářové pole na stránce {p} není označkované+ H{n} follows an H{d}; headings should not skip levels H{n} následuje po H{d}; nadpisy by neměly přeskakovat úrovně+ No document language is set Není nastaven jazyk dokumentu+ No page has text: the document appears to be images of pages Žádná stránka nemá text: dokument se zdá být tvořen obrázky stránek+ Page {p} doesn't tab in structure order Stránka {p} nepřechází tabulátorem v pořadí struktury+ Page {p}: {n} untagged content item Stránka {p}: neoznačkované položky obsahu: {n}+ Page {p}: {n} untagged content items Stránka {p}: neoznačkované položky obsahu: {n}+ Page {} has additional actions Stránka {} má další akce+ PdfCraft can't check this signature yet: {}. PdfCraft zatím nedokáže tento podpis ověřit: {}.+ Report created Zpráva vytvořena+ Rule Name Název pravidla+ Save as {level} Uložit jako {level}+ Signature is invalid Podpis je neplatný+ Signature is valid Podpis je platný+ Signature validity is unknown Platnost podpisu je neznámá+ Signing time is from the clock on the signer's computer. Čas podpisu pochází z hodin v počítači podepisující osoby.+ The ECDSA signature is not in canonical DER (trailing bytes, padding or a missing sign byte); it was read anyway. Podpis ECDSA není v kanonickém DER (přebytečné bajty, výplň nebo chybějící bajt znaménka); přesto byl načten.+ The ECDSA signature is the raw r and s values instead of a DER sequence; it was read anyway. Podpis ECDSA tvoří holé hodnoty r a s místo sekvence DER; přesto byl načten.+ The RSA signature value does not have the length of the key's modulus (leading zero bytes dropped or added); it was read anyway. Hodnota podpisu RSA nemá délku modulu klíče (úvodní nulové bajty chybí nebo přebývají); přesto byla načtena.+ The RSA signature's DigestInfo has no NULL parameter (older signers write it so); it was read anyway. DigestInfo podpisu RSA nemá parametr NULL (starší podepisovací programy jej tak zapisují); přesto byl načten.+ The certificate of {} does not allow this many CA certificates below it (path length), so it is not used to vouch for {}. Certifikát {} nepovoluje pod sebou tolik certifikátů CA (délka cesty), proto se nepoužije k ručení za {}.+ The certificate of {} is not a CA certificate that may issue certificates, so it is not used to vouch for {}. Certifikát {} není certifikát CA, který smí vydávat certifikáty, proto se nepoužije k ručení za {}.+ The certificate of {} has critical extensions PdfCraft does not recognize, so it is not used to vouch for {}. Certifikát {} má kritická rozšíření, která PdfCraft nezná, proto se nepoužije k ručení za {}.+ The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}. Certifikát {} nebyl v době podpisu platný, proto se nepoužije k ručení za {}.+ The checker found problems which may prevent the document from being fully accessible. Kontrola našla problémy, které mohou bránit plné přístupnosti dokumentu.+ The document has been altered or corrupted since the signature was applied. Dokument byl od připojení podpisu změněn nebo poškozen.+ The document has been altered or corrupted since the timestamp was applied. Dokument byl od připojení časového razítka změněn nebo poškozen.+ The document has been altered since this signature was applied in ways it does not permit ({}). Dokument byl od připojení tohoto podpisu změněn způsobem, který podpis nepovoluje ({}).+ The document has been altered since this timestamp was applied in ways it does not permit ({}). Dokument byl od připojení tohoto časového razítka změněn způsobem, který razítko nepovoluje ({}).+ The document has been modified since this signature was applied, but the changes are permitted ({}). Dokument byl od připojení tohoto podpisu upraven, ale změny jsou povolené ({}).+ The document has been modified since this timestamp was applied, but the changes are permitted ({}). Dokument byl od připojení tohoto časového razítka upraven, ale změny jsou povolené ({}).+ The document has no tags (structure tree) Dokument nemá tagy (strom struktury)+ The document has no title Dokument nemá název+ The document isn't marked as tagged (MarkInfo Marked) Dokument není označen jako označkovaný (MarkInfo Marked)+ The document isn't tagged, so none of its content is Dokument není označkovaný, a tak není označkovaný ani žádný jeho obsah+ The document's embedded revocation information shows that the signer's certificate has not been revoked. Informace o odvolání vložené v dokumentu ukazují, že certifikát podepisující osoby nebyl odvolán.+ The embedded timestamp token is valid and its authority is trusted; trusted time is {}. Vložené časové razítko je platné a jeho autorita je důvěryhodná; důvěryhodný čas je {}.+ The font {} isn't embedded Písmo {} není vložené+ The metadata doesn't identify the file as {} Metadata neoznačují soubor jako {}+ The security settings don't allow screen readers to read the text Nastavení zabezpečení nedovoluje čtečkám obrazovky číst text+ The signature algorithm and the SignerInfo's digest algorithm name different hashes; the signature was made with the SignerInfo's. Algoritmus podpisu a algoritmus otisku v SignerInfo uvádějí různé hashe; podpis byl vytvořen tím ze SignerInfo.+ The signature carries an unverified timestamp ({}): the timestamp authority is not in your list of trusted certificates, so the signing time claimed by the signer is used instead. Podpis nese neověřené časové razítko ({}): autorita časových razítek není ve vašem seznamu důvěryhodných certifikátů, proto se místo něj použije čas podpisu uvedený podepisující osobou.+ The signature contents are not hexadecimal. Obsah podpisu není šestnáctkový.+ The signature could not be checked ({}). Podpis nebylo možné zkontrolovat ({}).+ The signature could not be read ({}). Podpis nebylo možné načíst ({}).+ The signature could not be verified ({}). Podpis nebylo možné ověřit ({}).+ The signature has no valid byte range. Podpis nemá platný rozsah bajtů.+ The signature includes an embedded timestamp. Podpis obsahuje vložené časové razítko.+ The signature is BER-encoded (indefinite lengths) rather than DER; it was read leniently. Podpis je kódován v BER (neurčité délky) místo DER; byl načten benevolentně.+ The signature uses the legacy adbe.x509.rsa_sha1 format. Podpis používá zastaralý formát adbe.x509.rsa_sha1.+ The signature value does not match the signer's certificate: the signature is corrupt. Hodnota podpisu neodpovídá certifikátu podepisující osoby: podpis je poškozený.+ The signature's byte range does not exclude exactly its contents. Rozsah bajtů podpisu nevynechává přesně jeho obsah.+ The signature's byte range does not match the file. Rozsah bajtů podpisu neodpovídá souboru.+ The signature's timestamp token could not be verified ({}). Časové razítko podpisu nebylo možné ověřit ({}).+ The signature's timestamp token does not cover the signature value. Časové razítko podpisu nepokrývá hodnotu podpisu.+ The signed content is a constructed (segmented) OCTET STRING, as BER allows; it was read anyway. Podepsaný obsah je složený (segmentovaný) OCTET STRING, jak BER dovoluje; přesto byl načten.+ The signer's certificate does not allow digital signatures (its key usage has neither digital signature nor non-repudiation). Certifikát podepisující osoby nepovoluje digitální podpisy (jeho použití klíče nezahrnuje digitální podpis ani nepopiratelnost).+ The signer's certificate has been revoked ({}). Certifikát podepisující osoby byl odvolán ({}).+ The signer's certificate has critical extensions PdfCraft does not recognize ({}). Certifikát podepisující osoby má kritická rozšíření, která PdfCraft nezná ({}).+ The signer's certificate is not in the signature. Certifikát podepisující osoby není v podpisu.+ The signer's certificate is not issued for signing documents (its extended key usage has no document-signing purpose). Certifikát podepisující osoby není vydán k podepisování dokumentů (jeho rozšířené použití klíče nezahrnuje podepisování dokumentů).+ The signer's certificate was not valid at the time of signing. Certifikát podepisující osoby nebyl v době podpisu platný.+ The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates. Identita podepisující osoby je neznámá, protože není ve vašem seznamu důvěryhodných certifikátů a žádný z jejích nadřazených certifikátů není důvěryhodný.+ The signer's identity is valid. Identita podepisující osoby je platná.+ The timestamp authority's certificate was not valid at the time of timestamping. Certifikát autority časových razítek nebyl v době vystavení razítka platný.+ The timestamp authority's certificate is not issued for time stamping. Certifikát autority časových razítek není vystaven pro vydávání časových razítek.+ The timestamp contents are not hexadecimal. Obsah časového razítka není šestnáctkový.+ The timestamp has no valid byte range. Časové razítko nemá platný rozsah bajtů.+ The timestamp token could not be read ({}). Časové razítko nebylo možné načíst ({}).+ The timestamp token is valid and its authority is trusted. Časové razítko je platné a jeho autorita je důvěryhodná.+ The timestamp token is valid, but the timestamp authority is not in your list of trusted certificates. Časové razítko je platné, ale autorita časových razítek není ve vašem seznamu důvěryhodných certifikátů.+ The timestamp's byte range does not exclude exactly its contents. Rozsah bajtů časového razítka nevynechává přesně jeho obsah.+ The timestamp's byte range does not match the file. Rozsah bajtů časového razítka neodpovídá souboru.+ The window shows the file name, not the title (Initial View > Show) Okno zobrazuje název souboru, ne název dokumentu (Počáteční zobrazení > Zobrazit)+ This document has not been modified since this signature was applied. Tento dokument nebyl od připojení tohoto podpisu upraven.+ This document has not been modified since this timestamp was applied. Tento dokument nebyl od připojení tohoto časového razítka upraven.+ This signature uses RIPEMD-160, a legacy 160-bit hash algorithm that is no longer recommended for signatures. It still validates, but it should not be relied on. Tento podpis používá RIPEMD-160, zastaralý 160bitový hashovací algoritmus, který se už pro podpisy nedoporučuje. Podpis se stále ověří, ale nelze na něj spoléhat.+ This signature uses SHA-1, a weak hash algorithm: collisions in it have been demonstrated. It still validates because many documents signed years ago use it, but it should not be relied on. Tento podpis používá SHA-1, slabý hashovací algoritmus, u kterého byly prokázány kolize. Stále se ověří, protože jej používá mnoho dokumentů podepsaných před lety, ale nelze na něj spoléhat.+ Unsigned signature field Nepodepsané podpisové pole+ alternate text hides an annotation inside it alternativní text skrývá anotaci uvnitř+ alternate text on an element with no page content alternativní text u prvku bez obsahu stránky+ comments komentáře+ document security store úložiště zabezpečení dokumentu+ document structure struktura dokumentu+ form fill vyplnění formuláře+ its alternate text is inside another element's and will never be read jeho alternativní text je uvnitř alternativního textu jiného prvku a nikdy nebude přečten+ links odkazy+ metadata metadata+ no alternate text chybí alternativní text+ no header cells (TH) chybí buňky záhlaví (TH)+ no summary chybí souhrn+ not in a TR není v TR+ not in a Table, THead, TBody or TFoot není v Table, THead, TBody ani TFoot+ not in an L (list) není v L (seznam)+ not in an LI (list item) není v LI (položka seznamu)+ other changes jiné změny+ page content obsah stránek+ page {n} is out of range (1–{count}) stránka {n} je mimo rozsah (1–{count})+ pages added or removed přidané nebo odebrané stránky+ rows have between {min} and {max} columns řádky mají {min} až {max} sloupců+ the first heading is an H{n}; headings should not skip levels první nadpis je H{n}; nadpisy by neměly přeskakovat úrovně+ the signed version could not be read podepsanou verzi nebylo možné načíst+ {n} pages and no bookmarks Počet stránek: {n}, žádné záložky+ {page} is not a page number or label {page} není číslo ani označení stránky+ {ty} element on page {p}: {what} Prvek {ty} na stránce {p}: {what}+ {ty} element: {what} Prvek {ty}: {what}+ {} annotation on page {p} isn't tagged Anotace {} na stránce {p} není označkovaná+ {} annotations aren't allowed Anotace {} nejsou povoleny+ … and {n} more … a další ({n})++ # Labels other catalogs carry (shared buttons, tooltips with key caps, the folder picker).+ on page {label} na stránce {label}+ of z+ Add the PDFs to combine Přidejte soubory PDF ke sloučení+ Added the first {n} PDFs in {folder} Přidány první soubory PDF ze složky {folder} (počet: {n})+ Always Vždy+ Automatically Automaticky+ Choose a file… Vybrat soubor…+ Choose a folder… Vybrat složku…+ Choose… Vybrat…+ Color Barva+ Comment Komentář+ Comment and review Komentovat a revidovat+ Copied to clipboard Zkopírováno do schránky+ Copy to clipboard Kopírovat do schránky+ Create folder Vytvořit složku+ Disabled Vypnuto+ Document properties (⌘D) Vlastnosti dokumentu (⌘D)+ Drop PDFs or folders here, or choose them. Přetáhněte sem soubory PDF nebo složky, nebo je vyberte.+ Duplicate Duplikovat+ Enabled Zapnuto+ Error Chyba+ Every PDF in the folder Všechny soubory PDF ve složce+ Every PDF in the folder and the folders inside it Všechny soubory PDF ve složce a jejích podsložkách+ Folder Složka+ Help… Nápověda…+ Import Importovat+ Information Informace+ Loading… Načítání…+ Mouse wheel scroll speed Rychlost posouvání kolečkem myši+ Move Přesunout+ Never Nikdy+ New bookmark (⌘B) Nová záložka (⌘B)+ Next Další+ Next (⌘G) Další (⌘G)+ No PDFs found in {folder} Ve složce {folder} nebyly nalezeny žádné soubory PDF+ No results Žádné výsledky+ On Zapnuto+ Open a PDF (⌘O) Otevřít PDF (⌘O)+ Open folder Otevřít složku+ Organize Uspořádat+ Page {n} Stránka {n}+ Page {n} of {total} Stránka {n} z {total}+ Paste Vložit+ Previous Předchozí+ Previous (⇧⌘G) Předchozí (⇧⌘G)+ Print (⌘P) Tisk (⌘P)+ Refresh Obnovit+ Rotate view clockwise (⇧⌘+) Otočit zobrazení po směru hodinových ručiček (⇧⌘+)+ Save changes? Uložit změny?+ Save file Uložit soubor+ Search results Výsledky hledání+ Select all Vybrat vše+ Success Hotovo+ System Podle systému+ The password must have at least 6 characters. Heslo musí mít alespoň 6 znaků.+ The standard fonts can't draw “{c}” ({code}). Only Western European characters can be added as text for now. Standardní písma nedokážou vykreslit „{c}“ ({code}). Jako text lze zatím přidat jen západoevropské znaky.+ This file changed on disk. Reload it to see the new version; your unsaved changes will be lost. Tento soubor se na disku změnil. Načtěte ho znovu, abyste viděli novou verzi; neuložené změny budou ztraceny.+ Theme Motiv+ Warning Upozornění+ Zoom in (⌘+) Přiblížit (⌘+)+ Zoom in / out (also pinch or ⌘-scroll) Přiblížit / oddálit (také sevřením prstů nebo posouváním s ⌘)+ Zoom out (⌘−) Oddálit (⌘−)+ @plural {n} comment|{n} comments {n} komentář|{n} komentáře|{n} komentářů+ @plural {n} file|{n} files {n} soubor|{n} soubory|{n} souborů+ @plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků+ theme Appearance Vzhled++ # The date picker's weekday heads.+ calendar weekday Su Ne+ calendar weekday Mo Po+ calendar weekday Tu Út+ calendar weekday We St+ calendar weekday Th Čt+ calendar weekday Fr Pá+ calendar weekday Sa So++ # A certificate's fields in the certificate viewer.+ certificate Issued to Vydáno pro+ certificate Issued by Vydal+ certificate Valid from Platný od+ certificate Valid to Platný do+ certificate Intended usage Zamýšlené použití+ certificate Serial number Sériové číslo+ certificate Issuer Vydavatel+ certificate Validity starts Začátek platnosti+ certificate Validity ends Konec platnosti+ certificate Public key Veřejný klíč+ certificate Basic constraints Základní omezení+ certificate Key usage Použití klíče+ certificate Self-signed Samopodepsaný+ certificate SHA-1 digest Otisk SHA-1+ certificate SHA-256 digest Otisk SHA-256+ certificate Version Verze+ The signature's signed attributes have no content type, which CMS requires; it was read anyway. Podepsané atributy podpisu neobsahují typ obsahu, který CMS vyžaduje; přesto byl podpis načten.+ This signature uses an RSA key shorter than 2048 bits, which is no longer considered strong enough for signatures. It still validates, but it should not be relied on. Tento podpis používá klíč RSA kratší než 2048 bitů, který už se pro podpisy nepovažuje za dostatečně silný. Ověření stále projde, ale nelze se na něj spoléhat.+ The signature's signed attributes have no message digest, so the signature does not cover the document. Podepsané atributy podpisu neobsahují otisk zprávy, takže se podpis na dokument nevztahuje.+ The signature's signed attributes name a content type other than data, so it is not a signature of the document. Podepsané atributy podpisu uvádějí jiný typ obsahu než data, takže nejde o podpis dokumentu.+ Remove {standard} identification Odebrat identifikaci {standard}++ # Prepare a form ▸ Text field table+ Add text field table Přidat tabulku textových polí+ Text field table Tabulka textových polí+ Text Field Table Tabulka textových polí+ Columns Sloupce+ Row spacing Mezera mezi řádky+ Column spacing Mezera mezi sloupci+ First row number Číslo prvního řádku+ Column widths Šířky sloupců+ Distribute evenly Rozložit rovnoměrně+ Field names Názvy polí+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N nebo {row} je číslo řádku, {col} číslo sloupce a {seq} číslo buňky. Bez nich se číslo řádku přidá na konec.+ Column {n} Sloupec {n}+ Add fields Přidat pole+ the rows are too short: make the area taller, or use fewer rows or less row spacing řádky jsou příliš nízké: zvětšete výšku oblasti nebo použijte méně řádků či menší mezeru mezi řádky+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing sloupec je příliš úzký: rozšiřte oblast, dejte sloupci více místa nebo použijte méně sloupců či menší mezeru mezi sloupci+ field names can't contain a period: {name} názvy polí nesmějí obsahovat tečku: {name}+ two cells would both be named {name} dvě buňky by se jmenovaly {name}+ a field named {name} already exists pole s názvem {name} už existuje++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Dnes+ @plural {n} reply|{n} replies {n} odpověď|{n} odpovědi|{n} odpovědí++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Nástroje stránek+ Insert pages from a file after the selection… Vložit stránky ze souboru za výběr…+ Rotate the selected pages counterclockwise Otočit vybrané stránky proti směru hodinových ručiček+ Rotate the selected pages clockwise Otočit vybrané stránky po směru hodinových ručiček+ Extract the selected pages… Extrahovat vybrané stránky…+ Delete the selected pages Odstranit vybrané stránky+ Export value Exportní hodnotadiff --cc crates/ui-egui/src/i18n/de.tsvindex 71d2c7e42,8586a21d4..cdc647ede--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@@ -2433,4 -2499,62 +2499,63 @@@ animation effects Off AuMake properties default Eigenschaften als Standard festlegenPages selected Ausgewählte SeitenPage properties Seiteneigenschaften+ Create & Edit Erstellen & Bearbeiten+ Review & Compare Prüfen & Vergleichen+ Forms & Signatures Formulare & Signaturen+ Protect & Standardize Schützen & Standardisieren+ Customize & Automate Anpassen & Automatisieren+ No tools match your search. Keine Werkzeuge entsprechen Ihrer Suche.+ Expand all tools Alle Werkzeuge ausklappen+ Collapse all tools Alle Werkzeuge einklappen+ Attach a file… Datei anhängen…+ Delete attachment Anhang löschen+ Attaching files is not available on the web yet Dateien anhängen ist im Web noch nicht verfügbar+ Attach {name} {name} anhängen+ Delete attachment {key} Anhang {key} löschen+ Font Schrift+ Bulleted list Aufzählung+ Numbered list Nummerierte Liste+ Alignment Ausrichtung+ Superscript Hochgestellt+ Subscript Tiefgestellt+ Paragraph spacing Absatzabstand+ Less Weniger+ Other options Weitere Optionen+ Thumbnail size Miniaturgröße+ Smaller thumbnails Kleinere Miniaturen+ Larger thumbnails Größere Miniaturen+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Kommentar umformen++ # Prepare a form ▸ Text field table+ Add text field table Textfeldtabelle hinzufügen+ Text field table Textfeldtabelle+ Text Field Table Textfeldtabelle+ Columns Spalten+ Row spacing Zeilenabstand+ Column spacing Spaltenabstand+ First row number Erste Zeilennummer+ Column widths Spaltenbreiten+ Distribute evenly Gleichmäßig verteilen+ Field names Feldnamen+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N oder {row} ist die Zeilennummer, {col} die Spaltennummer, {seq} die Zellennummer. Ohne eines davon steht die Zeilennummer am Ende.+ Column {n} Spalte {n}+ Add fields Felder hinzufügen+ the rows are too short: make the area taller, or use fewer rows or less row spacing die Zeilen sind zu niedrig: Mach den Bereich höher oder verwende weniger Zeilen oder weniger Zeilenabstand+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing eine Spalte ist zu schmal: Mach den Bereich breiter, gib der Spalte mehr Breite oder verwende weniger Spalten oder weniger Spaltenabstand+ field names can't contain a period: {name} Feldnamen dürfen keinen Punkt enthalten: {name}+ two cells would both be named {name} zwei Zellen hätten beide den Namen {name}+ a field named {name} already exists ein Feld namens {name} ist bereits vorhanden++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Heute+ @plural {n} reply|{n} replies {n} Antwort|{n} Antworten++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Seitenwerkzeuge+ Insert pages from a file after the selection… Seiten aus einer Datei nach der Auswahl einfügen…+ Rotate the selected pages counterclockwise Ausgewählte Seiten gegen den Uhrzeigersinn drehen+ Rotate the selected pages clockwise Ausgewählte Seiten im Uhrzeigersinn drehen+ Extract the selected pages… Ausgewählte Seiten extrahieren…+ Delete the selected pages Ausgewählte Seiten löschen+ Export value Exportwertdiff --cc crates/ui-egui/src/i18n/el.tsvindex 768504b72,e3eac77ca..f809f9812--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@@ -2438,4 -2504,62 +2504,63 @@@ animation effects Off Ανενεργ�Make properties default Ορισμός ιδιοτήτων ως προεπιλογήPages selected Επιλεγμένες σελίδεςPage properties Ιδιότητες σελίδας+ Create & Edit Δημιουργία και επεξεργασία+ Review & Compare Αναθεώρηση και σύγκριση+ Forms & Signatures Φόρμες και υπογραφές+ Protect & Standardize Προστασία και τυποποίηση+ Customize & Automate Προσαρμογή και αυτοματοποίηση+ No tools match your search. Κανένα εργαλείο δεν ταιριάζει με την αναζήτησή σας.+ Expand all tools Ανάπτυξη όλων των εργαλείων+ Collapse all tools Σύμπτυξη όλων των εργαλείων+ Attach a file… Επισύναψη αρχείου…+ Delete attachment Διαγραφή συνημμένου+ Attaching files is not available on the web yet Η επισύναψη αρχείων δεν είναι ακόμη διαθέσιμη στον ιστό+ Attach {name} Επισύναψη {name}+ Delete attachment {key} Διαγραφή συνημμένου {key}+ Font Γραμματοσειρά+ Bulleted list Λίστα με κουκκίδες+ Numbered list Αριθμημένη λίστα+ Alignment Στοίχιση+ Superscript Εκθέτης+ Subscript Δείκτης+ Paragraph spacing Απόσταση παραγράφων+ Less Λιγότερα+ Other options Άλλες επιλογές+ Thumbnail size Μέγεθος μικρογραφιών+ Smaller thumbnails Μικρότερες μικρογραφίες+ Larger thumbnails Μεγαλύτερες μικρογραφίες+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Αλλαγή σχήματος σχολίου++ # Prepare a form ▸ Text field table+ Add text field table Προσθήκη πίνακα πεδίων κειμένου+ Text field table Πίνακας πεδίων κειμένου+ Text Field Table Πίνακας πεδίων κειμένου+ Columns Στήλες+ Row spacing Απόσταση γραμμών+ Column spacing Απόσταση στηλών+ First row number Αριθμός πρώτης γραμμής+ Column widths Πλάτη στηλών+ Distribute evenly Ομοιόμορφη κατανομή+ Field names Ονόματα πεδίων+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. Το N ή το {row} είναι ο αριθμός γραμμής, το {col} ο αριθμός στήλης και το {seq} ο αριθμός κελιού. Χωρίς κανένα από αυτά, ο αριθμός γραμμής μπαίνει στο τέλος.+ Column {n} Στήλη {n}+ Add fields Προσθήκη πεδίων+ the rows are too short: make the area taller, or use fewer rows or less row spacing οι γραμμές είναι πολύ χαμηλές: κάντε την περιοχή ψηλότερη ή χρησιμοποιήστε λιγότερες γραμμές ή μικρότερη απόσταση γραμμών+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing μια στήλη είναι πολύ στενή: κάντε την περιοχή φαρδύτερη, δώστε στη στήλη περισσότερο πλάτος ή χρησιμοποιήστε λιγότερες στήλες ή μικρότερη απόσταση στηλών+ field names can't contain a period: {name} τα ονόματα πεδίων δεν μπορούν να περιέχουν τελεία: {name}+ two cells would both be named {name} δύο κελιά θα είχαν το ίδιο όνομα {name}+ a field named {name} already exists υπάρχει ήδη πεδίο με όνομα {name}++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Σήμερα+ @plural {n} reply|{n} replies {n} απάντηση|{n} απαντήσεις++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Εργαλεία σελίδων+ Insert pages from a file after the selection… Εισαγωγή σελίδων από αρχείο μετά την επιλογή…+ Rotate the selected pages counterclockwise Περιστροφή των επιλεγμένων σελίδων αριστερόστροφα+ Rotate the selected pages clockwise Περιστροφή των επιλεγμένων σελίδων δεξιόστροφα+ Extract the selected pages… Εξαγωγή των επιλεγμένων σελίδων…+ Delete the selected pages Διαγραφή των επιλεγμένων σελίδων+ Export value Τιμή εξαγωγήςdiff --cc crates/ui-egui/src/i18n/es.tsvindex 73c4d01e4,0d4e505a7..4255a650d--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@@ -2573,3 -2662,221 +2662,222 @@@ animation effects Off Desactivado# Historical snapshot notice bar (View signed version / View revision).You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original. Estás viendo la versión firmada de «{from}» (revisión {rev}). Es una instantánea: los cambios aquí no afectarán al original.You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original. Estás viendo la revisión {rev} de «{from}». Es una instantánea: los cambios aquí no afectarán al original.+ Attach a file… Adjuntar un archivo…+ Delete attachment Eliminar adjunto+ Attaching files is not available on the web yet Adjuntar archivos aún no está disponible en la web+ Attach {name} Adjuntar {name}+ Delete attachment {key} Eliminar adjunto {key}+ Thumbnail size Tamaño de las miniaturas+ Smaller thumbnails Miniaturas más pequeñas+ Larger thumbnails Miniaturas más grandes+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Cambiar la forma del comentario++ #+ # Keys the other catalogs carry that this one was missing, so Spanish covers the bundled key union+ # the way Lithuanian and Vietnamese do (`lithuanian_covers_bundled_catalog_keys_including_dynamic_dialog_labels`).+ # Same clean-room rule as the header: written from the plain meaning of the English label, reusing+ # the vocabulary already in this file (ID digital, marcador, Acercar / alejar, Portapapeles).+ #+ # The date picker.+ calendar date January enero+ calendar date February febrero+ calendar date March marzo+ calendar date April abril+ calendar date May mayo+ calendar date June junio+ calendar date July julio+ calendar date August agosto+ calendar date September septiembre+ calendar date October octubre+ calendar date November noviembre+ calendar date December diciembre+ calendar weekday Mo Lu+ calendar weekday Tu Ma+ calendar weekday We Mi+ calendar weekday Th Ju+ calendar weekday Fr Vi+ calendar weekday Sa Sá+ calendar weekday Su Do+ #+ # Certificate details, in their own context beside the plain labels.+ certificate Issued to Emitido a+ certificate Issued by Emitido por+ certificate Issuer Emisor+ certificate Serial number Número de serie+ certificate Version Versión+ certificate Public key Clave pública+ certificate Key usage Uso de la clave+ certificate Intended usage Uso previsto+ certificate Basic constraints Restricciones básicas+ certificate Self-signed Autofirmado+ certificate Valid from Válido desde+ certificate Valid to Válido hasta+ certificate Validity starts La validez empieza+ certificate Validity ends La validez termina+ certificate SHA-1 digest Huella SHA-1+ certificate SHA-256 digest Huella SHA-256+ #+ # What a certificate's key may be used for (X.509 key usage), as the details list them.+ Digital Signature Firma digital+ Non-Repudiation No repudio+ Key Encipherment Cifrado de claves+ Data Encipherment Cifrado de datos+ Key Agreement Acuerdo de claves+ Certificate Signing Firma de certificados+ CRL Signing Firma de CRL+ Encipher Only Solo cifrado+ Decipher Only Solo descifrado+ #+ # Signatures, revisions and digital IDs.+ {who}, certificate issued by {issuer}. {who}, certificado emitido por {issuer}.+ {who}, certificate issued by an unknown issuer. {who}, certificado emitido por un emisor desconocido.+ Rev. {rev}: Signed by {name} Rev. {rev}: Firmado por {name}+ Rev. {rev}: Signed by an unknown signer Rev. {rev}: Firmado por un firmante desconocido+ Rev. {rev}: Certified by {name} Rev. {rev}: Certificado por {name}+ Rev. {rev}: Certified by an unknown signer Rev. {rev}: Certificado por un firmante desconocido+ Unsigned signature field: {name} Campo de firma sin firmar: {name}+ Choose a digital ID. Elige un ID digital.+ There is no folder to save the digital ID in. No hay ninguna carpeta donde guardar el ID digital.+ #+ # Passwords.+ The password is incorrect. La contraseña es incorrecta.+ The password must have at least 6 characters. La contraseña debe tener al menos 6 caracteres.+ The password must have at least 8 characters. La contraseña debe tener al menos 8 caracteres.+ The passwords do not match. Las contraseñas no coinciden.+ Only the document's owner can change its security (open it with the permissions password) Solo el propietario del documento puede cambiar su seguridad (ábrelo con la contraseña de permisos)+ #+ # Counts.+ @plural {n} byte|{n} bytes {n} byte|{n} bytes+ @plural {n} pixel|{n} pixels {n} píxel|{n} píxeles+ @plural {n} file|{n} files {n} archivo|{n} archivos+ @plural {n} comment|{n} comments {n} comentario|{n} comentarios+ @plural {n} result|{n} results {n} resultado|{n} resultados+ @plural {n} image optimized|{n} images optimized {n} imagen optimizada|{n} imágenes optimizadas+ @plural {n} item discarded|{n} items discarded {n} elemento descartado|{n} elementos descartados+ @plural Delete {n} field|Delete {n} fields Eliminar {n} campo|Eliminar {n} campos+ #+ # Combining PDFs from a folder.+ Add the PDFs to combine Añade los PDF que vas a combinar+ Drop PDFs or folders here, or choose them. Suelta aquí PDF o carpetas, o elígelos.+ Every PDF in the folder Todos los PDF de la carpeta+ Every PDF in the folder and the folders inside it Todos los PDF de la carpeta y de las carpetas que contiene+ Added the first {n} PDFs in {folder} Se han añadido los primeros {n} PDF de {folder}+ No PDFs found in {folder} No se ha encontrado ningún PDF en {folder}+ #+ # Panels, rendering and notices.+ Panel layout could not be restored: {error} No se ha podido restaurar la disposición de los paneles: {error}+ Panel move was not applied: {error} No se ha aplicado el movimiento del panel: {error}+ Rendering… Renderizando…+ Still rendering — this page is unusually complex… Sigue renderizando: esta página es excepcionalmente compleja…+ Loading… Cargando…+ This file changed on disk. Reload it to see the new version; your unsaved changes will be lost. Este archivo cambió en el disco. Recárgalo para ver la versión nueva; se perderán los cambios sin guardar.+ Text recognition isn't installed: its models are missing (run `cargo xtask models`, or set PDFCRAFT_MODELS). El reconocimiento de texto no está instalado: faltan sus modelos (ejecuta `cargo xtask models` o define PDFCRAFT_MODELS).+ Cut and stack needs Two-sided: Off. Print single-sided sheets. Cortar y apilar necesita «A doble cara: Desactivado». Imprime hojas a una cara.+ Error Error+ Warning Advertencia+ Information Información+ Success Correcto+ #+ # Asking for something, and choosing it.+ Enter a name. Introduce un nombre.+ Enter a page number Introduce un número de página+ Enter a URL Introduce una URL+ Enter the field names Introduce los nombres de los campos+ Choose… Elegir…+ Choose a file… Elegir un archivo…+ Choose a folder… Elegir una carpeta…+ Create folder Crear carpeta+ Open folder Abrir carpeta+ Save file Guardar archivo+ Save changes? ¿Guardar los cambios?+ #+ # Settings and their values.+ Theme Tema+ theme Appearance Aspecto+ System Sistema+ English Inglés+ Always Siempre+ Never Nunca+ Automatically Automáticamente+ On Activado+ Enabled Activado+ Disabled Desactivado+ Mouse wheel scroll speed Velocidad de desplazamiento de la rueda del ratón+ Margins (in) Márgenes (pulg.)+ #+ # Labels and commands the catalogs name on their own.+ Color Color+ Folder Carpeta+ Comment Comentario+ Comment and review Comentar y revisar+ Creator Creador+ Producer Productor+ Organize Organizar+ Import Importar+ Move Mover+ Duplicate Duplicar+ Paste Pegar+ Select all Seleccionar todo+ Refresh Actualizar+ Next Siguiente+ Previous Anterior+ of de+ No results Sin resultados+ Search results Resultados de la búsqueda+ Copy to clipboard Copiar al portapapeles+ Copied to clipboard Copiado al portapapeles+ Help… Ayuda…+ on page {label} en la página {label}+ Page {n} Página {n}+ Page {n} of {total} Página {n} de {total}+ #+ # Tooltips that spell their shortcut out.+ Open a PDF (⌘O) Abrir un PDF (⌘O)+ Print (⌘P) Imprimir (⌘P)+ Document properties (⌘D) Propiedades del documento (⌘D)+ New bookmark (⌘B) Nuevo marcador (⌘B)+ Next (⌘G) Siguiente (⌘G)+ Previous (⇧⌘G) Anterior (⇧⌘G)+ Zoom in (⌘+) Acercar (⌘+)+ Zoom out (⌘−) Alejar (⌘−)+ Zoom in / out (also pinch or ⌘-scroll) Acercar / alejar (también con pellizco o ⌘ + desplazamiento)+ Rotate view clockwise (⇧⌘+) Girar la vista a la derecha (⇧⌘+)+ Save (M4) Guardar (M4)++ # Prepare a form ▸ Text field table+ Add text field table Añadir tabla de campos de texto+ Text field table Tabla de campos de texto+ Text Field Table Tabla de campos de texto+ Columns Columnas+ Row spacing Espacio entre filas+ Column spacing Espacio entre columnas+ First row number Número de la primera fila+ Column widths Anchos de columna+ Distribute evenly Repartir por igual+ Field names Nombres de los campos+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N o {row} es el número de fila, {col} el de columna y {seq} el de celda. Si no hay ninguno, el número de fila va al final.+ Column {n} Columna {n}+ Add fields Añadir campos+ a table has 1 to {max} rows una tabla tiene de 1 a {max} filas+ a table has 1 to {max} columns una tabla tiene de 1 a {max} columnas+ the first row number can be at most {max} el número de la primera fila puede ser como mucho {max}+ the area, the spacing and the column widths must be numbers, the spacing 0 or more and each width more than 0 el área, el espaciado y los anchos de columna deben ser números, el espaciado 0 o más y cada ancho mayor que 0+ the rows are too short: make the area taller, or use fewer rows or less row spacing las filas son demasiado bajas: haz el área más alta o usa menos filas o menos espacio entre filas+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing una columna es demasiado estrecha: haz el área más ancha, dale más anchura a la columna o usa menos columnas o menos espacio entre columnas+ field names can't contain a period: {name} los nombres de campo no pueden contener un punto: {name}+ two cells would both be named {name} dos celdas se llamarían {name}+ a field named {name} already exists ya existe un campo llamado {name}++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Hoy+ @plural {n} reply|{n} replies {n} respuesta|{n} respuestas++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Herramientas de página+ Insert pages from a file after the selection… Insertar páginas de un archivo después de la selección…+ Rotate the selected pages counterclockwise Girar las páginas seleccionadas en sentido antihorario+ Rotate the selected pages clockwise Girar las páginas seleccionadas en sentido horario+ Extract the selected pages… Extraer las páginas seleccionadas…+ Delete the selected pages Eliminar las páginas seleccionadas++ Export value Valor de exportacióndiff --cc crates/ui-egui/src/i18n/fr.tsvindex 39e3a460f,61c8b5171..59175685a--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@@ -2432,4 -2498,328 +2498,329 @@@ animation effects Off DésactivéMake properties default Définir comme propriétés par défautPages selected Pages sélectionnéesPage properties Propriétés de la page+ Create & Edit Créer et modifier+ Review & Compare Réviser et comparer+ Forms & Signatures Formulaires et signatures+ Protect & Standardize Protéger et normaliser+ Customize & Automate Personnaliser et automatiser+ No tools match your search. Aucun outil ne correspond à votre recherche.+ Expand all tools Développer tous les outils+ Collapse all tools Réduire tous les outils+ Attach a file… Joindre un fichier…+ Delete attachment Supprimer la pièce jointe+ Attaching files is not available on the web yet Joindre des fichiers n'est pas encore disponible sur le web+ Attach {name} Joindre {name}+ Delete attachment {key} Supprimer la pièce jointe {key}+ Font Police+ Bulleted list Liste à puces+ Numbered list Liste numérotée+ Alignment Alignement+ Superscript Exposant+ Subscript Indice+ Paragraph spacing Espacement des paragraphes+ Less Moins+ Other options Autres options+ Thumbnail size Taille des vignettes+ Smaller thumbnails Réduire les vignettes+ Larger thumbnails Agrandir les vignettes+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Modifier la forme du commentaire+ on page {label} à la page {label}+ A font isn't embedded Une police n'est pas incorporée+ A {} action isn't allowed Une action {} n'est pas autorisée+ A {} annotation has additional actions Une annotation {} contient des actions supplémentaires+ A {} annotation has no appearance stream Une annotation {} n'a pas de flux d'apparence+ A {} annotation isn't set to print, or is hidden Une annotation {} n'est pas réglée pour l'impression, ou est masquée+ Accessibility Report Rapport d'accessibilité+ Add the PDFs to combine Ajoutez les PDF à combiner+ Added the first {n} PDFs in {folder} Les {n} premiers PDF de {folder} ont été ajoutés+ Always Toujours+ Automatically Automatiquement+ CRL Signing Signature de LCR+ Certificate Signing Signature de certificats+ Certificate authority Autorité de certification+ Change Author Modifier l'auteur+ Change Keywords Modifier les mots-clés+ Change Subject Modifier le sujet+ Change Title Modifier le titre+ Choose a digital ID. Choisissez un ID numérique.+ Choose a file… Choisir un fichier…+ Choose a folder… Choisir un dossier…+ Choose… Choisir…+ Color Couleur+ Comment Commentaire+ Comment and review Commenter et réviser+ Copied to clipboard Copié dans le presse-papiers+ Copy to clipboard Copier dans le presse-papiers+ Create folder Créer un dossier+ Create links Créer des liens+ Creator Application+ Cut and stack needs Two-sided: Off. Print single-sided sheets. Couper et empiler exige Recto verso : Désactivé. Imprimez des feuilles en recto seul.+ Data Encipherment Chiffrement des données+ Decipher Only Déchiffrement seul+ Detailed Report Rapport détaillé+ DeviceCMYK is used, but the PDF/A output intent isn't a CMYK profile DeviceCMYK est utilisé, mais l'intention de sortie PDF/A n'est pas un profil CMJN+ DeviceRGB is used, but the PDF/A output intent isn't an RGB profile DeviceRGB est utilisé, mais l'intention de sortie PDF/A n'est pas un profil RVB+ Digital Signature Signature numérique+ Disabled Désactivé+ Document properties (⌘D) Propriétés du document (⌘D)+ Drop PDFs or folders here, or choose them. Déposez des PDF ou des dossiers ici, ou choisissez-les.+ Duplicate Dupliquer+ Enabled Activé+ Encipher Only Chiffrement seul+ End entity Entité finale+ English Anglais+ Enter a URL Saisissez une URL+ Enter a name. Saisissez un nom.+ Enter a page number Saisissez un numéro de page+ Enter the field names Saisissez les noms des champs+ Error Erreur+ Every PDF in the folder Tous les PDF du dossier+ Every PDF in the folder and the folders inside it Tous les PDF du dossier et de ses sous-dossiers+ Field "{}" on page {p} has no description (tooltip) Le champ « {} » de la page {p} n'a pas de description (info-bulle)+ Filename Nom du fichier+ Flatten Fill & Sign Aplatir Remplir et signer+ Folder Dossier+ Font (unnamed) on page {p} doesn't map its characters to Unicode La police (sans nom) de la page {p} n'associe pas ses caractères à Unicode+ Font {} on page {p} doesn't map its characters to Unicode La police {} de la page {p} n'associe pas ses caractères à Unicode+ Form field on page {p} isn't tagged Un champ de formulaire de la page {p} n'est pas balisé+ Help… Aide…+ H{n} follows an H{d}; headings should not skip levels H{n} suit H{d} ; les niveaux de titre ne doivent pas être sautés+ Import Importer+ Information Information+ Key Agreement Accord de clé+ Key Encipherment Chiffrement de clé+ Loading… Chargement…+ Margins (in) Marges (pouces)+ Move Déplacer+ Never Jamais+ New bookmark (⌘B) Nouveau signet (⌘B)+ Next Suivant+ Next (⌘G) Suivant (⌘G)+ No PDFs found in {folder} Aucun PDF trouvé dans {folder}+ No document language is set Aucune langue de document n'est définie+ No page has text: the document appears to be images of pages Aucune page ne contient de texte : le document semble être constitué d'images de pages+ No results Aucun résultat+ Non-Repudiation Non-répudiation+ On Activé+ Only the document's owner can change its security (open it with the permissions password) Seul le propriétaire du document peut modifier sa protection (ouvrez-le avec le mot de passe d'autorisations)+ Open a PDF (⌘O) Ouvrir un PDF (⌘O)+ Open folder Ouvrir le dossier+ Organize Organiser+ Page {n} Page {n}+ Page {n} of {total} Page {n} sur {total}+ Page {p} doesn't tab in structure order La page {p} ne se parcourt pas dans l'ordre de la structure+ Page {p}: {n} untagged content item Page {p} : {n} élément de contenu non balisé+ Page {p}: {n} untagged content items Page {p} : {n} éléments de contenu non balisés+ Page {} has additional actions La page {} contient des actions supplémentaires+ Panel layout could not be restored: {error} Impossible de restaurer la disposition des panneaux : {error}+ Panel move was not applied: {error} Le déplacement du panneau n'a pas été appliqué : {error}+ Paste Coller+ PdfCraft can't check this signature yet: {}. PdfCraft ne peut pas encore contrôler cette signature : {}.+ Previous Précédent+ Previous (⇧⌘G) Précédent (⇧⌘G)+ Print (⌘P) Imprimer (⌘P)+ Producer Producteur du PDF+ Refresh Actualiser+ Rendering… Rendu en cours…+ Report created Rapport créé+ Rev. {rev}: Certified by an unknown signer Rév. {rev} : certifié par un signataire inconnu+ Rev. {rev}: Certified by {name} Rév. {rev} : certifié par {name}+ Rev. {rev}: Signed by an unknown signer Rév. {rev} : signé par un signataire inconnu+ Rev. {rev}: Signed by {name} Rév. {rev} : signé par {name}+ Rotate view clockwise (⇧⌘+) Pivoter l'affichage vers la droite (⇧⌘+)+ Rule Name Nom de la règle+ Save (M4) Enregistrer (M4)+ Save as {level} Enregistrer comme {level}+ Save changes? Enregistrer les modifications ?+ Save file Enregistrer le fichier+ Search results Résultats de la recherche+ Select all Tout sélectionner+ Signature is invalid La signature n'est pas valide+ Signature is valid La signature est valide+ Signature validity is unknown La validité de la signature est inconnue+ Signing time is from the clock on the signer's computer. L'heure de signature provient de l'horloge de l'ordinateur du signataire.+ Still rendering — this page is unusually complex… Rendu toujours en cours : cette page est exceptionnellement complexe…+ Success Succès+ System Système+ Text recognition isn't installed: its models are missing (run `cargo xtask models`, or set PDFCRAFT_MODELS). La reconnaissance de texte n'est pas installée : ses modèles sont absents (exécutez `cargo xtask models`, ou définissez PDFCRAFT_MODELS).+ The ECDSA signature is not in canonical DER (trailing bytes, padding or a missing sign byte); it was read anyway. La signature ECDSA n'est pas en DER canonique (octets en trop, bourrage ou octet de signe manquant) ; elle a tout de même été lue.+ The ECDSA signature is the raw r and s values instead of a DER sequence; it was read anyway. La signature ECDSA est constituée des valeurs brutes r et s au lieu d'une séquence DER ; elle a tout de même été lue.+ The RSA signature value does not have the length of the key's modulus (leading zero bytes dropped or added); it was read anyway. La valeur de la signature RSA n'a pas la longueur du module de la clé (octets nuls de tête supprimés ou ajoutés) ; elle a tout de même été lue.+ The RSA signature's DigestInfo has no NULL parameter (older signers write it so); it was read anyway. Le DigestInfo de la signature RSA n'a pas de paramètre NULL (d'anciens outils de signature l'écrivent ainsi) ; il a tout de même été lu.+ The certificate of {} does not allow this many CA certificates below it (path length), so it is not used to vouch for {}. Le certificat de {} n'autorise pas autant de certificats d'AC en dessous de lui (longueur du chemin) : il n'est donc pas utilisé pour se porter garant de {}.+ The certificate of {} is not a CA certificate that may issue certificates, so it is not used to vouch for {}. Le certificat de {} n'est pas un certificat d'AC autorisé à émettre des certificats : il n'est donc pas utilisé pour se porter garant de {}.+ The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}. Le certificat de {} n'était pas valide au moment de la signature : il n'est donc pas utilisé pour se porter garant de {}.+ The checker found problems which may prevent the document from being fully accessible. Le vérificateur a trouvé des problèmes qui peuvent empêcher le document d'être entièrement accessible.+ The document has been altered or corrupted since the signature was applied. Le document a été modifié ou corrompu depuis l'application de la signature.+ The document has been altered or corrupted since the timestamp was applied. Le document a été modifié ou corrompu depuis l'application de l'horodatage.+ The document has been altered since this signature was applied in ways it does not permit ({}). Le document a été modifié depuis l'application de cette signature d'une manière qu'elle n'autorise pas ({}).+ The document has been altered since this timestamp was applied in ways it does not permit ({}). Le document a été modifié depuis l'application de cet horodatage d'une manière qu'il n'autorise pas ({}).+ The document has been modified since this signature was applied, but the changes are permitted ({}). Le document a été modifié depuis l'application de cette signature, mais les modifications sont autorisées ({}).+ The document has been modified since this timestamp was applied, but the changes are permitted ({}). Le document a été modifié depuis l'application de cet horodatage, mais les modifications sont autorisées ({}).+ The document has no tags (structure tree) Le document n'a aucune balise (arbre de structure)+ The document has no title Le document n'a pas de titre+ The document isn't marked as tagged (MarkInfo Marked) Le document n'est pas indiqué comme balisé (MarkInfo Marked)+ The document isn't tagged, so none of its content is Le document n'est pas balisé, son contenu non plus+ The document's embedded revocation information shows that the signer's certificate has not been revoked. Les informations de révocation incorporées au document montrent que le certificat du signataire n'a pas été révoqué.+ The embedded timestamp token is valid and its authority is trusted; trusted time is {}. Le jeton d'horodatage incorporé est valide et son autorité est approuvée ; l'heure de confiance est {}.+ The font {} isn't embedded La police {} n'est pas incorporée+ The metadata doesn't identify the file as {} Les métadonnées n'identifient pas le fichier comme {}+ The password is incorrect. Le mot de passe est incorrect.+ The password must have at least 6 characters. Le mot de passe doit comporter au moins 6 caractères.+ The passwords do not match. Les mots de passe ne correspondent pas.+ The security settings don't allow screen readers to read the text Les paramètres de protection ne permettent pas aux lecteurs d'écran de lire le texte+ The signature algorithm and the SignerInfo's digest algorithm name different hashes; the signature was made with the SignerInfo's. L'algorithme de signature et l'algorithme d'empreinte du SignerInfo désignent des hachages différents ; la signature a été faite avec celui du SignerInfo.+ The signature carries an unverified timestamp ({}): the timestamp authority is not in your list of trusted certificates, so the signing time claimed by the signer is used instead. La signature comporte un horodatage non vérifié ({}) : l'autorité d'horodatage ne figure pas dans votre liste de certificats approuvés ; c'est donc l'heure de signature déclarée par le signataire qui est utilisée.+ The signature contents are not hexadecimal. Le contenu de la signature n'est pas hexadécimal.+ The signature could not be checked ({}). La signature n'a pas pu être contrôlée ({}).+ The signature could not be read ({}). La signature n'a pas pu être lue ({}).+ The signature could not be verified ({}). La signature n'a pas pu être vérifiée ({}).+ The signature has no valid byte range. La signature n'a pas de plage d'octets valide.+ The signature includes an embedded timestamp. La signature comprend un horodatage incorporé.+ The signature is BER-encoded (indefinite lengths) rather than DER; it was read leniently. La signature est codée en BER (longueurs indéfinies) plutôt qu'en DER ; elle a été lue avec tolérance.+ The signature uses the legacy adbe.x509.rsa_sha1 format. La signature utilise l'ancien format adbe.x509.rsa_sha1.+ The signature value does not match the signer's certificate: the signature is corrupt. La valeur de la signature ne correspond pas au certificat du signataire : la signature est corrompue.+ The signature's byte range does not exclude exactly its contents. La plage d'octets de la signature n'exclut pas exactement son contenu.+ The signature's byte range does not match the file. La plage d'octets de la signature ne correspond pas au fichier.+ The signature's timestamp token could not be verified ({}). Le jeton d'horodatage de la signature n'a pas pu être vérifié ({}).+ The signature's timestamp token does not cover the signature value. Le jeton d'horodatage de la signature ne couvre pas la valeur de la signature.+ The signed content is a constructed (segmented) OCTET STRING, as BER allows; it was read anyway. Le contenu signé est une OCTET STRING construite (segmentée), comme le BER l'autorise ; il a tout de même été lu.+ The signer's certificate does not allow digital signatures (its key usage has neither digital signature nor non-repudiation). Le certificat du signataire n'autorise pas les signatures numériques (son usage de la clé ne comprend ni la signature numérique ni la non-répudiation).+ The signer's certificate has been revoked ({}). Le certificat du signataire a été révoqué ({}).+ The signer's certificate has critical extensions PdfCraft does not recognize ({}). Le certificat du signataire comporte des extensions critiques que PdfCraft ne reconnaît pas ({}).+ The signer's certificate is not in the signature. Le certificat du signataire ne figure pas dans la signature.+ The signer's certificate is not issued for signing documents (its extended key usage has no document-signing purpose). Le certificat du signataire n'est pas émis pour signer des documents (son usage étendu de la clé n'inclut pas la signature de documents).+ The signer's certificate was not valid at the time of signing. Le certificat du signataire n'était pas valide au moment de la signature.+ The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates. L'identité du signataire est inconnue car elle n'a pas été incluse dans votre liste de certificats approuvés et aucun de ses certificats parents n'est un certificat approuvé.+ The signer's identity is valid. L'identité du signataire est valide.+ The timestamp authority's certificate was not valid at the time of timestamping. Le certificat de l'autorité d'horodatage n'était pas valide au moment de l'horodatage.+ The timestamp contents are not hexadecimal. Le contenu de l'horodatage n'est pas hexadécimal.+ The timestamp has no valid byte range. L'horodatage n'a pas de plage d'octets valide.+ The timestamp token could not be read ({}). Le jeton d'horodatage n'a pas pu être lu ({}).+ The timestamp token is valid and its authority is trusted. Le jeton d'horodatage est valide et son autorité est approuvée.+ The timestamp token is valid, but the timestamp authority is not in your list of trusted certificates. Le jeton d'horodatage est valide, mais l'autorité d'horodatage ne figure pas dans votre liste de certificats approuvés.+ The timestamp's byte range does not exclude exactly its contents. La plage d'octets de l'horodatage n'exclut pas exactement son contenu.+ The timestamp's byte range does not match the file. La plage d'octets de l'horodatage ne correspond pas au fichier.+ The window shows the file name, not the title (Initial View > Show) La fenêtre affiche le nom du fichier et non le titre (Affichage initial > Afficher)+ Theme Thème+ There is no folder to save the digital ID in. Il n'y a aucun dossier où enregistrer l'ID numérique.+ This document has not been modified since this signature was applied. Ce document n'a pas été modifié depuis l'application de cette signature.+ This document has not been modified since this timestamp was applied. Ce document n'a pas été modifié depuis l'application de cet horodatage.+ This signature uses RIPEMD-160, a legacy 160-bit hash algorithm that is no longer recommended for signatures. It still validates, but it should not be relied on. Cette signature utilise RIPEMD-160, un ancien algorithme de hachage de 160 bits qui n'est plus recommandé pour les signatures. Elle reste valide, mais il ne faut pas s'y fier.+ This signature uses SHA-1, a weak hash algorithm: collisions in it have been demonstrated. It still validates because many documents signed years ago use it, but it should not be relied on. Cette signature utilise SHA-1, un algorithme de hachage faible : des collisions ont été démontrées. Elle reste valide car de nombreux documents signés il y a des années l'utilisent, mais il ne faut pas s'y fier.+ Unsigned signature field Champ de signature non signé+ Unsigned signature field: {name} Champ de signature non signé : {name}+ Warning Avertissement+ Zoom in (⌘+) Zoom avant (⌘+)+ Zoom in / out (also pinch or ⌘-scroll) Zoom avant / arrière (aussi pincer ou ⌘-défilement)+ Zoom out (⌘−) Zoom arrière (⌘−)+ alternate text hides an annotation inside it le texte de remplacement masque une annotation qu'il contient+ alternate text on an element with no page content texte de remplacement sur un élément sans contenu de page+ comments commentaires+ document security store magasin de sécurité du document+ document structure structure du document+ form fill remplissage de formulaire+ its alternate text is inside another element's and will never be read son texte de remplacement est contenu dans celui d'un autre élément et ne sera jamais lu+ links liens+ metadata métadonnées+ no alternate text pas de texte de remplacement+ no header cells (TH) pas de cellules d'en-tête (TH)+ no summary pas de résumé+ not in a TR pas dans un TR+ not in a Table, THead, TBody or TFoot pas dans un Table, THead, TBody ou TFoot+ not in an L (list) pas dans un L (liste)+ not in an LI (list item) pas dans un LI (élément de liste)+ of sur+ other changes autres modifications+ page content contenu de la page+ page {n} is out of range (1–{count}) la page {n} est hors de l'intervalle (1–{count})+ pages added or removed pages ajoutées ou supprimées+ rows have between {min} and {max} columns les lignes comptent entre {min} et {max} colonnes+ the first heading is an H{n}; headings should not skip levels le premier titre est un H{n} ; les niveaux de titre ne doivent pas être sautés+ the signed version could not be read la version signée n'a pas pu être lue+ {n} pages and no bookmarks {n} pages et aucun signet+ {page} is not a page number or label {page} n'est ni un numéro de page ni une étiquette de page+ {ty} element on page {p}: {what} Élément {ty} de la page {p} : {what}+ {ty} element: {what} Élément {ty} : {what}+ {who}, certificate issued by an unknown issuer. {who}, certificat émis par un émetteur inconnu.+ {who}, certificate issued by {issuer}. {who}, certificat émis par {issuer}.+ {} annotation on page {p} isn't tagged Une annotation {} de la page {p} n'est pas balisée+ {} annotations aren't allowed Les annotations {} ne sont pas autorisées+ … and {n} more … et {n} autres+ @plural Delete {n} field|Delete {n} fields Supprimer {n} champ|Supprimer {n} champs+ @plural {n} byte|{n} bytes {n} octet|{n} octets+ @plural {n} comment|{n} comments {n} commentaire|{n} commentaires+ @plural {n} file|{n} files {n} fichier|{n} fichiers+ @plural {n} image optimized|{n} images optimized {n} image optimisée|{n} images optimisées+ @plural {n} item discarded|{n} items discarded {n} élément ignoré|{n} éléments ignorés+ @plural {n} pixel|{n} pixels {n} pixel|{n} pixels+ @plural {n} result|{n} results {n} résultat|{n} résultats+ calendar date April avril+ calendar date August août+ calendar date December décembre+ calendar date February février+ calendar date January janvier+ calendar date July juillet+ calendar date June juin+ calendar date March mars+ calendar date May mai+ calendar date November novembre+ calendar date October octobre+ calendar date September septembre+ calendar weekday Fr Ve+ calendar weekday Mo Lu+ calendar weekday Sa Sa+ calendar weekday Su Di+ calendar weekday Th Je+ calendar weekday Tu Ma+ calendar weekday We Me+ certificate Basic constraints Contraintes de base+ certificate Intended usage Usage prévu+ certificate Issued by Émis par+ certificate Issued to Émis pour+ certificate Issuer Émetteur+ certificate Key usage Usage de la clé+ certificate Public key Clé publique+ certificate SHA-1 digest Empreinte SHA-1+ certificate SHA-256 digest Empreinte SHA-256+ certificate Self-signed Auto-signé+ certificate Serial number Numéro de série+ certificate Valid from Valide à partir du+ certificate Valid to Valide jusqu'au+ certificate Validity ends Fin de validité+ certificate Validity starts Début de validité+ certificate Version Version++ # Prepare a form ▸ Text field table+ Add text field table Ajouter un tableau de champs de texte+ Text field table Tableau de champs de texte+ Text Field Table Tableau de champs de texte+ Columns Colonnes+ Row spacing Espacement des lignes+ Column spacing Espacement des colonnes+ First row number Numéro de la première ligne+ Column widths Largeurs des colonnes+ Distribute evenly Répartir uniformément+ Field names Noms des champs+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N ou {row} est le numéro de ligne, {col} le numéro de colonne, {seq} le numéro de cellule. Sans aucun d'eux, le numéro de ligne est ajouté à la fin.+ Column {n} Colonne {n}+ Add fields Ajouter les champs+ the rows are too short: make the area taller, or use fewer rows or less row spacing les lignes sont trop basses : agrandissez la zone en hauteur, ou utilisez moins de lignes ou un espacement des lignes plus petit+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing une colonne est trop étroite : élargissez la zone, donnez-lui plus de largeur, ou utilisez moins de colonnes ou un espacement des colonnes plus petit+ field names can't contain a period: {name} les noms de champ ne peuvent pas contenir de point : {name}+ two cells would both be named {name} deux cellules porteraient le nom {name}+ a field named {name} already exists un champ nommé {name} existe déjà++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Aujourd'hui+ @plural {n} reply|{n} replies {n} réponse|{n} réponses++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Outils de page+ Insert pages from a file after the selection… Insérer des pages d'un fichier après la sélection…+ Rotate the selected pages counterclockwise Faire pivoter les pages sélectionnées dans le sens antihoraire+ Rotate the selected pages clockwise Faire pivoter les pages sélectionnées dans le sens horaire+ Extract the selected pages… Extraire les pages sélectionnées…+ Delete the selected pages Supprimer les pages sélectionnées+ Export value Valeur d’exportationdiff --cc crates/ui-egui/src/i18n/hu.tsvindex 30d291d91,6b37b9169..ae09671c0--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@@ -2431,4 -2497,62 +2497,63 @@@ animation effects Off KMake properties default Tulajdonságok beállítása alapértelmezettkéntPages selected Kijelölt oldalakPage properties Oldaltulajdonságok+ Create & Edit Létrehozás és szerkesztés+ Review & Compare Áttekintés és összehasonlítás+ Forms & Signatures Űrlapok és aláírások+ Protect & Standardize Védelem és szabványosítás+ Customize & Automate Testreszabás és automatizálás+ No tools match your search. Egy eszköz sem felel meg a keresésnek.+ Expand all tools Az összes eszköz kibontása+ Collapse all tools Az összes eszköz összecsukása+ Attach a file… Fájl csatolása…+ Delete attachment Melléklet törlése+ Attaching files is not available on the web yet Fájlok csatolása a weben még nem érhető el+ Attach {name} {name} csatolása+ Delete attachment {key} {key} melléklet törlése+ Font Betűtípus+ Bulleted list Felsorolás+ Numbered list Számozott lista+ Alignment Igazítás+ Superscript Felső index+ Subscript Alsó index+ Paragraph spacing Bekezdéstávolság+ Less Kevesebb+ Other options Egyéb beállítások+ Thumbnail size Bélyegképek mérete+ Smaller thumbnails Kisebb bélyegképek+ Larger thumbnails Nagyobb bélyegképek+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Megjegyzés alakjának módosítása++ # Prepare a form ▸ Text field table+ Add text field table Szövegmező-táblázat hozzáadása+ Text field table Szövegmező-táblázat+ Text Field Table Szövegmező-táblázat+ Columns Oszlopok+ Row spacing Sorköz+ Column spacing Oszlopköz+ First row number Első sor száma+ Column widths Oszlopszélességek+ Distribute evenly Egyenletes elosztás+ Field names Mezőnevek+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. Az N vagy a {row} a sor száma, a {col} az oszlopé, a {seq} a cellaé. Ha egyik sincs, a sor száma a végére kerül.+ Column {n} {n}. oszlop+ Add fields Mezők hozzáadása+ the rows are too short: make the area taller, or use fewer rows or less row spacing a sorok túl alacsonyak: növeld a terület magasságát, vagy használj kevesebb sort vagy kisebb sorközt+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing egy oszlop túl keskeny: szélesítsd a területet, adj több helyet az oszlopnak, vagy használj kevesebb oszlopot vagy kisebb oszlopközt+ field names can't contain a period: {name} a mezőnevek nem tartalmazhatnak pontot: {name}+ two cells would both be named {name} két cella neve is {name} lenne+ a field named {name} already exists már van {name} nevű mező++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Ma+ @plural {n} reply|{n} replies {n} válasz|{n} válasz++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Oldaleszközök+ Insert pages from a file after the selection… Oldalak beszúrása fájlból a kijelölés után…+ Rotate the selected pages counterclockwise A kijelölt oldalak forgatása az óramutató járásával ellentétesen+ Rotate the selected pages clockwise A kijelölt oldalak forgatása az óramutató járásával megegyezően+ Extract the selected pages… A kijelölt oldalak kibontása…+ Delete the selected pages A kijelölt oldalak törlése+ Export value Exportértékdiff --cc crates/ui-egui/src/i18n/it.tsvindex 3528ce851,20729bae6..9ecf3c9d4--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@@ -2644,4 -2710,82 +2710,83 @@@ certificate Key usage Utilizzo chiavcertificate Self-signed Autofirmatocertificate SHA-1 digest Impronta SHA-1certificate SHA-256 digest Impronta SHA-256+ Create & Edit Crea e modifica+ Review & Compare Revisione e confronto+ Forms & Signatures Moduli e firme+ Protect & Standardize Proteggi e standardizza+ Customize & Automate Personalizza e automatizza+ No tools match your search. Nessuno strumento corrisponde alla ricerca.+ Expand all tools Espandi tutti gli strumenti+ Collapse all tools Comprimi tutti gli strumenti+ Attach a file… Allega un file…+ Delete attachment Elimina allegato+ Attaching files is not available on the web yet Allegare file non è ancora disponibile sul web+ Attach {name} Allega {name}+ Delete attachment {key} Elimina allegato {key}+ Font Carattere+ Bulleted list Elenco puntato+ Numbered list Elenco numerato+ Alignment Allineamento+ Superscript Apice+ Subscript Pedice+ Paragraph spacing Spaziatura paragrafi+ Less Meno+ Other options Altre opzioni+ Thumbnail size Dimensione miniature+ Smaller thumbnails Miniature più piccole+ Larger thumbnails Miniature più grandi+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Modifica la forma del commento++ # Entries the other catalogs had and Italian lacked (2026-10-21)+ The password must have at least 8 characters. La password deve contenere almeno 8 caratteri.++ # Entries from #1523 that the catalog lacked.+ Color Colore+ Comment Commento+ Error Errore+ Next Avanti+ On Attivo+ Rotate view clockwise (⇧⌘+) Ruota la vista in senso orario (⇧⌘+)+ Save (M4) Salva (M4)+ Save changes? Salvare le modifiche?+ System Sistema+ Zoom in / out (also pinch or ⌘-scroll) Ingrandisci / riduci (anche con il pizzico o ⌘+scorrimento)+ of di++ # Prepare a form ▸ Text field table+ Add text field table Aggiungi tabella di campi di testo+ Text field table Tabella di campi di testo+ Text Field Table Tabella di campi di testo+ Columns Colonne+ Row spacing Spaziatura tra le righe+ Column spacing Spaziatura tra le colonne+ First row number Numero della prima riga+ Column widths Larghezze delle colonne+ Distribute evenly Distribuisci uniformemente+ Field names Nomi dei campi+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N o {row} è il numero di riga, {col} quello di colonna, {seq} quello di cella. Senza nessuno di essi, il numero di riga va alla fine.+ Column {n} Colonna {n}+ Add fields Aggiungi campi+ a table has 1 to {max} rows una tabella ha da 1 a {max} righe+ a table has 1 to {max} columns una tabella ha da 1 a {max} colonne+ the first row number can be at most {max} il numero della prima riga può essere al massimo {max}+ the area, the spacing and the column widths must be numbers, the spacing 0 or more and each width more than 0 l'area, la spaziatura e le larghezze delle colonne devono essere numeri, la spaziatura 0 o più e ogni larghezza maggiore di 0+ the rows are too short: make the area taller, or use fewer rows or less row spacing le righe sono troppo basse: rendi l'area più alta oppure usa meno righe o meno spaziatura tra le righe+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing una colonna è troppo stretta: rendi l'area più larga, dai più spazio alla colonna oppure usa meno colonne o meno spaziatura tra le colonne+ field names can't contain a period: {name} i nomi dei campi non possono contenere un punto: {name}+ two cells would both be named {name} due celle si chiamerebbero entrambe {name}+ a field named {name} already exists esiste già un campo chiamato {name}++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Oggi+ @plural {n} reply|{n} replies {n} risposta|{n} risposte++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Strumenti pagina+ Insert pages from a file after the selection… Inserisci pagine da un file dopo la selezione…+ Rotate the selected pages counterclockwise Ruota le pagine selezionate in senso antiorario+ Rotate the selected pages clockwise Ruota le pagine selezionate in senso orario+ Extract the selected pages… Estrai le pagine selezionate…+ Delete the selected pages Elimina le pagine selezionate+ Export value Valore di esportazionediff --cc crates/ui-egui/src/i18n/ja.tsvindex 5e5b3c061,1ed4d43b6..303403359--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@@ -2432,4 -2498,62 +2498,63 @@@ animation effects Off オ�Make properties default プロパティをデフォルトに設定Pages selected 選択したページPage properties ページのプロパティ+ Create & Edit 作成と編集+ Review & Compare レビューと比較+ Forms & Signatures フォームと署名+ Protect & Standardize 保護と標準化+ Customize & Automate カスタマイズと自動化+ No tools match your search. 検索に一致するツールはありません。+ Expand all tools すべてのツールを展開+ Collapse all tools すべてのツールを折りたたむ+ Attach a file… ファイルを添付…+ Delete attachment 添付ファイルを削除+ Attaching files is not available on the web yet Web 版ではまだファイルを添付できません+ Attach {name} {name} を添付+ Delete attachment {key} 添付ファイル {key} を削除+ Font フォント+ Bulleted list 箇条書き+ Numbered list 番号付きリスト+ Alignment 配置+ Superscript 上付き+ Subscript 下付き+ Paragraph spacing 段落間隔+ Less 折りたたむ+ Other options その他のオプション+ Thumbnail size サムネイルのサイズ+ Smaller thumbnails サムネイルを小さく+ Larger thumbnails サムネイルを大きく+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment コメントの形状を変更++ # Prepare a form ▸ Text field table+ Add text field table テキストフィールドの表を追加+ Text field table テキストフィールドの表+ Text Field Table テキストフィールドの表+ Columns 列+ Row spacing 行の間隔+ Column spacing 列の間隔+ First row number 最初の行番号+ Column widths 列の幅+ Distribute evenly 均等に配分+ Field names フィールド名+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N または {row} は行番号、{col} は列番号、{seq} はセル番号です。どれもない場合は、行番号が末尾に付きます。+ Column {n} 列 {n}+ Add fields フィールドを追加+ the rows are too short: make the area taller, or use fewer rows or less row spacing 行の高さが足りません: 範囲を高くするか、行数または行の間隔を減らしてください+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing 列の幅が足りません: 範囲を広げるか、その列の幅を増やすか、列数または列の間隔を減らしてください+ field names can't contain a period: {name} フィールド名にピリオドは使えません: {name}+ two cells would both be named {name} 2 つのセルが同じ名前 {name} になります+ a field named {name} already exists {name} という名前のフィールドは既にあります++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today 今日+ @plural {n} reply|{n} replies {n} 件の返信++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools ページツール+ Insert pages from a file after the selection… 選択範囲の後にファイルからページを挿入…+ Rotate the selected pages counterclockwise 選択したページを反時計回りに回転+ Rotate the selected pages clockwise 選択したページを時計回りに回転+ Extract the selected pages… 選択したページを抽出…+ Delete the selected pages 選択したページを削除+ Export value 書き出し値diff --cc crates/ui-egui/src/i18n/kk.tsvindex 8b6d48509,9022c3591..76ef21cd4--- a/crates/ui-egui/src/i18n/kk.tsv+++ b/crates/ui-egui/src/i18n/kk.tsv@@@ -2430,4 -2496,62 +2496,63 @@@ animation effects Off Өшірул�Make properties default Қасиеттерді әдепкі етуPages selected Таңдалған беттерPage properties Бет қасиеттері+ Create & Edit Жасау және өңдеу+ Review & Compare Шолу және салыстыру+ Forms & Signatures Пішіндер және қолтаңбалар+ Protect & Standardize Қорғау және стандарттау+ Customize & Automate Баптау және автоматтандыру+ No tools match your search. Іздеуге сәйкес құралдар жоқ.+ Expand all tools Барлық құралдарды жаю+ Collapse all tools Барлық құралдарды жию+ Attach a file… Файл тіркеу…+ Delete attachment Тіркемені жою+ Attaching files is not available on the web yet Вебте файл тіркеу әзірге қолжетімсіз+ Attach {name} {name} тіркеу+ Delete attachment {key} {key} тіркемесін жою+ Font Қаріп+ Bulleted list Таңбалауыш тізім+ Numbered list Нөмірленген тізім+ Alignment Туралау+ Superscript Жоғарғы индекс+ Subscript Төменгі индекс+ Paragraph spacing Абзац аралығы+ Less Азырақ+ Other options Басқа параметрлер+ Thumbnail size Нобай өлшемі+ Smaller thumbnails Кішірек нобайлар+ Larger thumbnails Үлкенірек нобайлар+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Пікір пішінін өзгерту++ # Prepare a form ▸ Text field table+ Add text field table Мәтін өрістерінің кестесін қосу+ Text field table Мәтін өрістерінің кестесі+ Text Field Table Мәтін өрістерінің кестесі+ Columns Бағандар+ Row spacing Жолдар аралығы+ Column spacing Бағандар аралығы+ First row number Бірінші жол нөмірі+ Column widths Баған ендері+ Distribute evenly Біркелкі бөлу+ Field names Өріс атаулары+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N немесе {row} — жол нөмірі, {col} — баған нөмірі, {seq} — ұяшық нөмірі. Олардың ешқайсысы болмаса, жол нөмірі соңына қосылады.+ Column {n} {n}-баған+ Add fields Өрістерді қосу+ the rows are too short: make the area taller, or use fewer rows or less row spacing жолдар тым аласа: аймақты биіктетіңіз немесе жолдар санын не жолдар аралығын азайтыңыз+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing баған тым тар: аймақты кеңейтіңіз, бағанға көбірек ен беріңіз немесе бағандар санын не бағандар аралығын азайтыңыз+ field names can't contain a period: {name} өріс атауларында нүкте болмауы керек: {name}+ two cells would both be named {name} екі ұяшықтың да атауы {name} болар еді+ a field named {name} already exists {name} атты өріс бар++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Бүгін+ @plural {n} reply|{n} replies {n} жауап|{n} жауап++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Бет құралдары+ Insert pages from a file after the selection… Таңдаудан кейін файлдан беттер кірістіру…+ Rotate the selected pages counterclockwise Таңдалған беттерді сағат тіліне қарсы бұру+ Rotate the selected pages clockwise Таңдалған беттерді сағат тілімен бұру+ Extract the selected pages… Таңдалған беттерді шығарып алу…+ Delete the selected pages Таңдалған беттерді жою+ Export value Экспорт мәніdiff --cc crates/ui-egui/src/i18n/lt.tsvindex fadb2509c,43749f4ec..ab208e3b3--- a/crates/ui-egui/src/i18n/lt.tsv+++ b/crates/ui-egui/src/i18n/lt.tsv@@@ -2683,4 -2764,57 +2764,58 @@@ key Space TarpaThe password must have at least 6 characters. Slaptažodį turi sudaryti bent 6 simboliai.This file changed on disk. Reload it to see the new version; your unsaved changes will be lost. Šis failas diske pasikeitė. Įkelkite jį iš naujo, kad pamatytumėte naują versiją; neįrašyti pakeitimai bus prarasti.theme Appearance Išvaizda+ Attach a file… Pridėti failą…+ Delete attachment Ištrinti priedą+ Attaching files is not available on the web yet Failų pridėjimas žiniatinklyje dar negalimas+ Attach {name} Pridėti {name}+ Delete attachment {key} Ištrinti priedą {key}+ Bulleted list Sąrašas su ženkleliais+ Numbered list Numeruotas sąrašas+ Alignment Lygiuotė+ Superscript Viršutinis indeksas+ Subscript Apatinis indeksas+ Paragraph spacing Tarpas tarp pastraipų+ Less Mažiau+ Other options Kitos parinktys+ Thumbnail size Miniatiūrų dydis+ Smaller thumbnails Mažesnės miniatiūros+ Larger thumbnails Didesnės miniatiūros+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Keisti komentaro formą++ # Prepare a form ▸ Text field table+ Add text field table Pridėti teksto laukų lentelę+ Text field table Teksto laukų lentelė+ Text Field Table Teksto laukų lentelė+ Columns Stulpeliai+ Row spacing Tarpas tarp eilučių+ Column spacing Tarpas tarp stulpelių+ First row number Pirmosios eilutės numeris+ Column widths Stulpelių pločiai+ Distribute evenly Paskirstyti tolygiai+ Field names Laukų pavadinimai+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N arba {row} – eilutės numeris, {col} – stulpelio numeris, {seq} – langelio numeris. Jei nė vieno nėra, eilutės numeris pridedamas gale.+ Column {n} Stulpelis {n}+ Add fields Pridėti laukus+ the rows are too short: make the area taller, or use fewer rows or less row spacing eilutės per žemos: padidinkite srities aukštį arba naudokite mažiau eilučių ar mažesnį tarpą tarp jų+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing stulpelis per siauras: praplatinkite sritį, skirkite stulpeliui daugiau pločio arba naudokite mažiau stulpelių ar mažesnį tarpą tarp jų+ field names can't contain a period: {name} laukų pavadinimuose negali būti taško: {name}+ two cells would both be named {name} du langeliai būtų pavadinti {name}+ a field named {name} already exists laukas pavadinimu {name} jau yra+ a table has 1 to {max} rows lentelėje gali būti nuo 1 iki {max} eilučių+ a table has 1 to {max} columns lentelėje gali būti nuo 1 iki {max} stulpelių+ the first row number can be at most {max} pirmosios eilutės numeris gali būti ne didesnis nei {max}+ the area, the spacing and the column widths must be numbers, the spacing 0 or more and each width more than 0 sritis, tarpai ir stulpelių pločiai turi būti skaičiai, tarpai – 0 arba daugiau, o kiekvienas plotis – daugiau nei 0++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Šiandien+ @plural {n} reply|{n} replies {n} atsakymas|{n} atsakymai|{n} atsakymų++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Puslapių įrankiai+ Insert pages from a file after the selection… Įterpti puslapius iš failo po pasirinkimo…+ Rotate the selected pages counterclockwise Pasukti pasirinktus puslapius prieš laikrodžio rodyklę+ Rotate the selected pages clockwise Pasukti pasirinktus puslapius pagal laikrodžio rodyklę+ Extract the selected pages… Išskleisti pasirinktus puslapius…+ Delete the selected pages Ištrinti pasirinktus puslapius+ Export value Eksporto reikšmėdiff --cc crates/ui-egui/src/i18n/pl.tsvindex 0b1edda70,963d71758..92af29dbe--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@@ -2408,4 -2474,182 +2474,183 @@@ animation effects Off WyłączonMake properties default Ustaw właściwości jako domyślnePages selected Zaznaczone stronyPage properties Właściwości strony+ Create & Edit Tworzenie i edycja+ Review & Compare Recenzja i porównanie+ Forms & Signatures Formularze i podpisy+ Protect & Standardize Ochrona i standaryzacja+ Customize & Automate Dostosowanie i automatyzacja+ No tools match your search. Żadne narzędzie nie pasuje do wyszukiwania.+ Expand all tools Rozwiń wszystkie narzędzia+ Collapse all tools Zwiń wszystkie narzędzia+ Attach a file… Dołącz plik…+ Delete attachment Usuń załącznik+ Attaching files is not available on the web yet Dołączanie plików nie jest jeszcze dostępne w wersji webowej+ Attach {name} Dołącz {name}+ Delete attachment {key} Usuń załącznik {key}+ Font Czcionka+ Bulleted list Lista punktowana+ Numbered list Lista numerowana+ Alignment Wyrównanie+ Superscript Indeks górny+ Subscript Indeks dolny+ Paragraph spacing Odstęp między akapitami+ Less Mniej+ Other options Inne opcje+ Thumbnail size Rozmiar miniatur+ Smaller thumbnails Mniejsze miniatury+ Larger thumbnails Większe miniatury+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Zmień kształt komentarza++ # Signature validation: what a signature's details say and the changes after signing they name+ # (pdfcraft_engine::sign::pdf::WORDINGS and kind::ALL).+ The signature has no valid byte range. Podpis nie ma prawidłowego zakresu bajtów.+ The signature's byte range does not match the file. Zakres bajtów podpisu nie odpowiada plikowi.+ The signature's byte range does not exclude exactly its contents. Zakres bajtów podpisu nie pomija dokładnie jego zawartości.+ The signature contents are not hexadecimal. Zawartość podpisu nie jest zapisana szesnastkowo.+ The signature could not be read ({}). Nie udało się odczytać podpisu ({}).+ PdfCraft can't check this signature yet: {}. PdfCraft nie potrafi jeszcze sprawdzić tego podpisu: {}.+ The signature uses the legacy adbe.x509.rsa_sha1 format. Podpis używa przestarzałego formatu adbe.x509.rsa_sha1.+ The signature is BER-encoded (indefinite lengths) rather than DER; it was read leniently. Podpis jest zakodowany w BER (długości nieokreślone), a nie w DER; odczytano go z tolerancją.+ The signed content is a constructed (segmented) OCTET STRING, as BER allows; it was read anyway. Podpisana treść jest złożonym (segmentowanym) OCTET STRING, na co pozwala BER; mimo to ją odczytano.+ The RSA signature value does not have the length of the key's modulus (leading zero bytes dropped or added); it was read anyway. Wartość podpisu RSA nie ma długości modułu klucza (pominięte lub dodane początkowe bajty zerowe); mimo to ją odczytano.+ The RSA signature's DigestInfo has no NULL parameter (older signers write it so); it was read anyway. DigestInfo podpisu RSA nie ma parametru NULL (tak zapisują go starsze programy); mimo to go odczytano.+ The ECDSA signature is not in canonical DER (trailing bytes, padding or a missing sign byte); it was read anyway. Podpis ECDSA nie jest w kanonicznym DER (nadmiarowe bajty końcowe, dopełnienie lub brak bajtu znaku); mimo to go odczytano.+ The ECDSA signature is the raw r and s values instead of a DER sequence; it was read anyway. Podpis ECDSA zawiera surowe wartości r i s zamiast sekwencji DER; mimo to go odczytano.+ The signature algorithm and the SignerInfo's digest algorithm name different hashes; the signature was made with the SignerInfo's. Algorytm podpisu i algorytm skrótu w SignerInfo wskazują różne funkcje skrótu; podpis złożono funkcją wskazaną w SignerInfo.+ This signature uses SHA-1, a weak hash algorithm: collisions in it have been demonstrated. It still validates because many documents signed years ago use it, but it should not be relied on. Ten podpis używa SHA-1, słabej funkcji skrótu, dla której wykazano kolizje. Podpis nadal przechodzi weryfikację, bo używa jej wiele dokumentów podpisanych przed laty, ale nie należy na nim polegać.+ This signature uses RIPEMD-160, a legacy 160-bit hash algorithm that is no longer recommended for signatures. It still validates, but it should not be relied on. Ten podpis używa RIPEMD-160, przestarzałej 160-bitowej funkcji skrótu, której nie zaleca się już do podpisów. Podpis nadal przechodzi weryfikację, ale nie należy na nim polegać.+ The document has been altered or corrupted since the signature was applied. Dokument został zmieniony lub uszkodzony po złożeniu podpisu.+ The signer's certificate is not in the signature. Podpis nie zawiera certyfikatu podpisującego.+ The signature value does not match the signer's certificate: the signature is corrupt. Wartość podpisu nie pasuje do certyfikatu podpisującego: podpis jest uszkodzony.+ The signature could not be checked ({}). Nie udało się sprawdzić podpisu ({}).+ The signature could not be verified ({}). Nie udało się zweryfikować podpisu ({}).+ This document has not been modified since this signature was applied. Dokument nie był modyfikowany od złożenia tego podpisu.+ The document has been modified since this signature was applied, but the changes are permitted ({}). Dokument zmodyfikowano po złożeniu tego podpisu, ale zmiany są dozwolone ({}).+ The document has been altered since this signature was applied in ways it does not permit ({}). Dokument zmieniono po złożeniu tego podpisu w sposób, na który podpis nie pozwala ({}).+ The signer's certificate was not valid at the time of signing. Certyfikat podpisującego nie był ważny w chwili podpisania.+ The signer's certificate does not allow digital signatures (its key usage has neither digital signature nor non-repudiation). Certyfikat podpisującego nie pozwala na podpisy cyfrowe (jego użycie klucza nie obejmuje ani podpisu cyfrowego, ani niezaprzeczalności).+ The signer's certificate is not issued for signing documents (its extended key usage has no document-signing purpose). Certyfikat podpisującego nie jest wystawiony do podpisywania dokumentów (jego rozszerzone użycie klucza nie obejmuje podpisywania dokumentów).+ The signer's certificate has critical extensions PdfCraft does not recognize ({}). Certyfikat podpisującego ma rozszerzenia krytyczne, których PdfCraft nie rozpoznaje ({}).+ The certificate of {} is not a CA certificate that may issue certificates, so it is not used to vouch for {}. Certyfikat podmiotu {} nie jest certyfikatem urzędu certyfikacji, który może wystawiać certyfikaty, dlatego nie poświadcza certyfikatu {}.+ The certificate of {} has critical extensions PdfCraft does not recognize, so it is not used to vouch for {}. Certyfikat podmiotu {} ma rozszerzenia krytyczne, których PdfCraft nie rozpoznaje, dlatego nie poświadcza certyfikatu {}.+ The certificate of {} does not allow this many CA certificates below it (path length), so it is not used to vouch for {}. Certyfikat podmiotu {} nie dopuszcza tylu certyfikatów urzędów certyfikacji poniżej siebie (długość ścieżki), dlatego nie poświadcza certyfikatu {}.+ The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}. Certyfikat podmiotu {} nie był ważny w chwili podpisania, dlatego nie poświadcza certyfikatu {}.+ The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates. Tożsamość podpisującego jest nieznana, ponieważ jego certyfikatu nie ma na liście zaufanych certyfikatów i żaden z certyfikatów nadrzędnych nie jest zaufany.+ The signer's identity is valid. Tożsamość podpisującego jest prawidłowa.+ The signature includes an embedded timestamp. Podpis zawiera osadzony znacznik czasu.+ Signing time is from the clock on the signer's computer. Czas podpisania pochodzi z zegara komputera podpisującego.+ The signature's timestamp token does not cover the signature value. Token znacznika czasu nie obejmuje wartości podpisu.+ The signature's timestamp token could not be verified ({}). Nie udało się zweryfikować tokenu znacznika czasu podpisu ({}).+ The embedded timestamp token is valid and its authority is trusted; trusted time is {}. Osadzony token znacznika czasu jest prawidłowy, a jego urząd jest zaufany; zaufany czas to {}.+ The signature carries an unverified timestamp ({}): the timestamp authority is not in your list of trusted certificates, so the signing time claimed by the signer is used instead. Podpis zawiera niezweryfikowany znacznik czasu ({}): urzędu znacznika czasu nie ma na liście zaufanych certyfikatów, dlatego użyto czasu podpisania podanego przez podpisującego.+ The signer's certificate has been revoked ({}). Certyfikat podpisującego został unieważniony ({}).+ The document's embedded revocation information shows that the signer's certificate has not been revoked. Osadzone w dokumencie informacje o unieważnieniach potwierdzają, że certyfikat podpisującego nie został unieważniony.+ The timestamp has no valid byte range. Znacznik czasu nie ma prawidłowego zakresu bajtów.+ The timestamp's byte range does not match the file. Zakres bajtów znacznika czasu nie odpowiada plikowi.+ The timestamp's byte range does not exclude exactly its contents. Zakres bajtów znacznika czasu nie pomija dokładnie jego zawartości.+ The timestamp contents are not hexadecimal. Zawartość znacznika czasu nie jest zapisana szesnastkowo.+ The timestamp token could not be read ({}). Nie udało się odczytać tokenu znacznika czasu ({}).+ The document has been altered or corrupted since the timestamp was applied. Dokument został zmieniony lub uszkodzony po dodaniu znacznika czasu.+ The timestamp authority's certificate was not valid at the time of timestamping. Certyfikat urzędu znacznika czasu nie był ważny w chwili oznaczania czasem.+ The timestamp authority's certificate is not issued for time stamping. Certyfikat urzędu znakowania czasem nie jest wystawiony do znakowania czasem.+ This document has not been modified since this timestamp was applied. Dokument nie był modyfikowany od dodania tego znacznika czasu.+ The document has been modified since this timestamp was applied, but the changes are permitted ({}). Dokument zmodyfikowano po dodaniu tego znacznika czasu, ale zmiany są dozwolone ({}).+ The document has been altered since this timestamp was applied in ways it does not permit ({}). Dokument zmieniono po dodaniu tego znacznika czasu w sposób, na który znacznik nie pozwala ({}).+ The timestamp token is valid and its authority is trusted. Token znacznika czasu jest prawidłowy, a jego urząd jest zaufany.+ The timestamp token is valid, but the timestamp authority is not in your list of trusted certificates. Token znacznika czasu jest prawidłowy, ale urzędu znacznika czasu nie ma na liście zaufanych certyfikatów.+ Unsigned signature field Niepodpisane pole podpisu+ Signature is valid Podpis jest prawidłowy+ Signature validity is unknown Ważność podpisu jest nieznana+ Signature is invalid Podpis jest nieprawidłowy+ page content zawartość stron+ form fill wypełnianie formularzy+ comments komentarze+ document security store magazyn zabezpieczeń dokumentu+ metadata metadane+ links łącza+ document structure struktura dokumentu+ pages added or removed dodane lub usunięte strony+ other changes inne zmiany+ the signed version could not be read nie udało się odczytać podpisanej wersji++ # The rest of the interface the Polish catalog lacked.+ Auto ({percent}%) Automatycznie ({percent}%)+ Auto follows the system's text size. Pages always render at the display's full resolution. Tryb automatyczny dopasowuje się do rozmiaru tekstu w systemie. Strony są zawsze renderowane w pełnej rozdzielczości ekranu.+ Check the pages Sprawdź strony+ Collapse all Zwiń wszystko+ Discard this text (Esc) Odrzuć ten tekst (Esc)+ Done adding text Zakończ dodawanie tekstu+ Drawing scale changes. Use Actual size for full-scale plans. Skala rysunku się zmieni. Do planów w pełnej skali użyj opcji Rzeczywisty rozmiar.+ Expand all Rozwiń wszystko+ Files are combined in the order shown. Drag them to change it. Pliki są łączone w pokazanej kolejności. Przeciągnij je, aby ją zmienić.+ Fill colour Kolor wypełnienia+ Fill colour: none Kolor wypełnienia: brak+ For page sizes and margins. Dotyczy rozmiarów stron i marginesów.+ Grid view Widok siatki+ Import list… Importuj listę…+ Interface size Rozmiar interfejsu+ List view Widok listy+ Margins Marginesy+ Match page at 100% Dopasuj stronę w skali 100%+ Multiple words or phrases Wiele słów lub fraz+ New bookmarks from structure Nowe zakładki ze struktury+ No fill Bez wypełnienia+ Offset from centre Przesunięcie od środka+ One word or phrase per line Jedno słowo lub fraza w wierszu+ PDF page: {size} Strona PDF: {size}+ PDF scale: {scale}% Skala PDF: {scale}%+ Pages: {k} of {n} Strony: {k} z {n}+ Preview unavailable: {e} Podgląd niedostępny: {e}+ Printer paper and scaling may differ. Check driver settings. Papier i skalowanie w drukarce mogą się różnić. Sprawdź ustawienia sterownika.+ Remove page Usuń stronę+ Remove {n} pages Usuń strony ({n})+ Some bookmarks are not shown here: the panel lists a limited number, nested a limited depth. Niektóre zakładki nie są tu widoczne: panel pokazuje ograniczoną ich liczbę i ograniczoną głębokość zagnieżdżenia.+ Switch to List view to change the pages it takes. Przełącz na widok listy, aby zmienić strony, które obejmuje.+ The document's security settings don't allow copying text and images Ustawienia zabezpieczeń dokumentu nie pozwalają kopiować tekstu i obrazów+ {n} word(s) or phrase(s) Słowa lub frazy: {n}+ You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original. Wyświetlasz rewizję {rev} dokumentu „{from}”. To migawka: zmiany wprowadzone tutaj nie wpłyną na oryginał.+ You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original. Wyświetlasz podpisaną wersję dokumentu „{from}” (rewizja {rev}). To migawka: zmiany wprowadzone tutaj nie wpłyną na oryginał.+ # Untranslated: English text until a translator fills these in.+ Float panel Float panel+ Move to group Move to group+ Panels Panels+ Resize panel window Resize panel window+ Resize panels Resize panels+ The signature's signed attributes have no content type, which CMS requires; it was read anyway. The signature's signed attributes have no content type, which CMS requires; it was read anyway.+ The signature's signed attributes have no message digest, so the signature does not cover the document. The signature's signed attributes have no message digest, so the signature does not cover the document.+ The signature's signed attributes name a content type other than data, so it is not a signature of the document. The signature's signed attributes name a content type other than data, so it is not a signature of the document.+ This signature uses an RSA key shorter than 2048 bits, which is no longer considered strong enough for signatures. It still validates, but it should not be relied on. This signature uses an RSA key shorter than 2048 bits, which is no longer considered strong enough for signatures. It still validates, but it should not be relied on.++ # Prepare a form ▸ Text field table+ Add text field table Dodaj tabelę pól tekstowych+ Text field table Tabela pól tekstowych+ Text Field Table Tabela pól tekstowych+ Columns Kolumny+ Row spacing Odstęp między wierszami+ Column spacing Odstęp między kolumnami+ First row number Numer pierwszego wiersza+ Column widths Szerokości kolumn+ Distribute evenly Rozłóż równomiernie+ Field names Nazwy pól+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N lub {row} to numer wiersza, {col} numer kolumny, a {seq} numer komórki. Bez żadnego z nich numer wiersza trafia na koniec.+ Column {n} Kolumna {n}+ Add fields Dodaj pola+ the rows are too short: make the area taller, or use fewer rows or less row spacing wiersze są za niskie: powiększ obszar w pionie albo użyj mniej wierszy lub mniejszego odstępu między wierszami+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing kolumna jest za wąska: poszerz obszar, daj kolumnie więcej miejsca albo użyj mniej kolumn lub mniejszego odstępu między kolumnami+ field names can't contain a period: {name} nazwy pól nie mogą zawierać kropki: {name}+ two cells would both be named {name} dwie komórki miałyby nazwę {name}+ a field named {name} already exists pole o nazwie {name} już istnieje++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Dzisiaj+ @plural {n} reply|{n} replies {n} odpowiedź|{n} odpowiedzi|{n} odpowiedzi++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Narzędzia stron+ Insert pages from a file after the selection… Wstaw strony z pliku po zaznaczeniu…+ Rotate the selected pages counterclockwise Obróć zaznaczone strony w lewo+ Rotate the selected pages clockwise Obróć zaznaczone strony w prawo+ Extract the selected pages… Wyodrębnij zaznaczone strony…+ Delete the selected pages Usuń zaznaczone strony+ Export value Wartość eksportowadiff --cc crates/ui-egui/src/i18n/pt-br.tsvindex 038a73a3f,c34ae83bc..45d00348b--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@@ -2446,4 -2512,333 +2512,334 @@@ animation effects Off DesativadoMake properties default Tornar propriedades padrãoPages selected Páginas selecionadasPage properties Propriedades da página+ Create & Edit Criar e editar+ Review & Compare Revisar e comparar+ Forms & Signatures Formulários e assinaturas+ Protect & Standardize Proteger e padronizar+ Customize & Automate Personalizar e automatizar+ No tools match your search. Nenhuma ferramenta corresponde à pesquisa.+ Expand all tools Expandir todas as ferramentas+ Collapse all tools Recolher todas as ferramentas+ Attach a file… Anexar um arquivo…+ Delete attachment Excluir anexo+ Attaching files is not available on the web yet Anexar arquivos ainda não está disponível na web+ Attach {name} Anexar {name}+ Delete attachment {key} Excluir anexo {key}++ # Remaining keys from the current catalog union, translated from their English meaning (2026-10-21).+ on page {label} na página {label}+ A font isn't embedded Uma fonte não está incorporada+ A {} action isn't allowed A ação {} não é permitida+ A {} annotation has additional actions A anotação {} tem ações adicionais+ A {} annotation has no appearance stream A anotação {} não tem fluxo de aparência+ A {} annotation isn't set to print, or is hidden A anotação {} não está configurada para impressão ou está oculta+ Accessibility Report Relatório de acessibilidade+ Add the PDFs to combine Adicione os PDFs que deseja combinar+ Added the first {n} PDFs in {folder} Os primeiros {n} PDFs de {folder} foram adicionados+ Always Sempre+ Automatically Automaticamente+ CRL Signing Assinatura de CRL+ Certificate Signing Assinatura de certificado+ Change Author Alterar autor+ Change Keywords Alterar palavras-chave+ Change Subject Alterar assunto+ Change Title Alterar título+ Choose a digital ID. Escolha uma identidade digital.+ Choose a file… Escolher um arquivo…+ Choose a folder… Escolher uma pasta…+ Choose… Escolher…+ Color Cor+ Comment Comentário+ Comment and review Comentar e revisar+ Copied to clipboard Copiado para a área de transferência+ Copy to clipboard Copiar para a área de transferência+ Create folder Criar pasta+ Create links Criar links+ Creator Criador+ Cut and stack needs Two-sided: Off. Print single-sided sheets. Recortar e empilhar requer Frente e verso: desativado. Imprima em folhas de um só lado.+ Data Encipherment Criptografia de dados+ Decipher Only Somente descriptografia+ Detailed Report Relatório detalhado+ DeviceCMYK is used, but the PDF/A output intent isn't a CMYK profile O DeviceCMYK está em uso, mas o perfil de saída do PDF/A não é um perfil CMYK+ DeviceRGB is used, but the PDF/A output intent isn't an RGB profile O DeviceRGB está em uso, mas o perfil de saída do PDF/A não é um perfil RGB+ Digital Signature Assinatura digital+ Disabled Desativado+ Document properties (⌘D) Propriedades do documento (⌘D)+ Drop PDFs or folders here, or choose them. Solte PDFs ou pastas aqui, ou selecione-os.+ Duplicate Duplicar+ Enabled Ativado+ Encipher Only Somente criptografia+ English Inglês+ Enter a URL Informe uma URL+ Enter a name. Informe um nome.+ Enter a page number Informe o número da página+ Enter the field names Informe os nomes dos campos+ Error Erro+ Every PDF in the folder Todos os PDFs da pasta+ Every PDF in the folder and the folders inside it Todos os PDFs da pasta e de suas subpastas+ Field "{}" on page {p} has no description (tooltip) O campo "{}" na página {p} não tem descrição (dica de ferramenta)+ Filename Nome do arquivo+ Flatten Fill & Sign Achatar Preencher e assinar+ Folder Pasta+ Font Fonte+ Bulleted list Lista com marcadores+ Numbered list Lista numerada+ Alignment Alinhamento+ Superscript Sobrescrito+ Subscript Subscrito+ Paragraph spacing Espaçamento entre parágrafos+ Less Menos+ Other options Outras opções+ Thumbnail size Tamanho das miniaturas+ Smaller thumbnails Miniaturas menores+ Larger thumbnails Miniaturas maiores+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Alterar a forma do comentário+ Font (unnamed) on page {p} doesn't map its characters to Unicode A fonte (sem nome) na página {p} não mapeia seus caracteres para Unicode+ Font {} on page {p} doesn't map its characters to Unicode A fonte {} na página {p} não mapeia seus caracteres para Unicode+ Form field on page {p} isn't tagged O campo de formulário na página {p} não está marcado com tag+ Help… Ajuda…+ H{n} follows an H{d}; headings should not skip levels H{n} vem depois de H{d}; os títulos não devem pular níveis+ Import Importar+ Information Informações+ Key Agreement Acordo de chaves+ Key Encipherment Cifragem de chaves+ Loading… Carregando…+ Mouse wheel scroll speed Velocidade de rolagem da roda do mouse+ Move Mover+ Never Nunca+ New bookmark (⌘B) Novo marcador (⌘B)+ Next Próximo+ Next (⌘G) Próximo (⌘G)+ No PDFs found in {folder} Nenhum PDF encontrado em {folder}+ No document language is set Nenhum idioma foi definido para o documento+ No page has text: the document appears to be images of pages Nenhuma página contém texto: o documento parece ser composto por imagens de páginas+ No results Nenhum resultado+ Non-Repudiation Não repúdio+ On Ativado+ Only the document's owner can change its security (open it with the permissions password) Somente o proprietário do documento pode alterar sua segurança (abra-o com a senha de permissões)+ Open a PDF (⌘O) Abrir um PDF (⌘O)+ Open folder Abrir pasta+ Organize Organizar+ Page {n} Página {n}+ Page {n} of {total} Página {n} de {total}+ Page {p} doesn't tab in structure order A ordem de tabulação da página {p} não segue a ordem da estrutura+ Page {p}: {n} untagged content item Página {p}: {n} item de conteúdo sem tag+ Page {p}: {n} untagged content items Página {p}: {n} itens de conteúdo sem tag+ Page {} has additional actions A página {} tem ações adicionais+ Panel layout could not be restored: {error} Não foi possível restaurar o layout dos painéis: {error}+ Panel move was not applied: {error} A movimentação do painel não foi aplicada: {error}+ Paste Colar+ PdfCraft can't check this signature yet: {}. O PdfCraft ainda não pode verificar esta assinatura: {}.+ Previous Anterior+ Previous (⇧⌘G) Anterior (⇧⌘G)+ Print (⌘P) Imprimir (⌘P)+ Producer Produtor+ Refresh Atualizar+ Rendering… Renderizando…+ Report created Relatório criado+ Rev. {rev}: Certified by an unknown signer Rev. {rev}: certificada por um signatário desconhecido+ Rev. {rev}: Certified by {name} Rev. {rev}: certificada por {name}+ Rev. {rev}: Signed by an unknown signer Rev. {rev}: assinada por um signatário desconhecido+ Rev. {rev}: Signed by {name} Rev. {rev}: assinada por {name}+ Rotate view clockwise (⇧⌘+) Girar a visualização no sentido horário (⇧⌘+)+ Rule Name Nome da regra+ Save (M4) Salvar (M4)+ Save as {level} Salvar como {level}+ Save changes? Salvar as alterações?+ Save file Salvar arquivo+ Search results Resultados da pesquisa+ Select all Selecionar tudo+ Signature is invalid A assinatura é inválida+ Signature is valid A assinatura é válida+ Signature validity is unknown A validade da assinatura é desconhecida+ Signing time is from the clock on the signer's computer. O horário da assinatura vem do relógio do computador do signatário.+ Still rendering — this page is unusually complex… Ainda renderizando — esta página é excepcionalmente complexa…+ Success Sucesso+ System Sistema+ Text recognition isn't installed: its models are missing (run `cargo xtask models`, or set PDFCRAFT_MODELS). O reconhecimento de texto não está instalado: faltam os modelos (execute `cargo xtask models` ou defina PDFCRAFT_MODELS).+ The ECDSA signature is not in canonical DER (trailing bytes, padding or a missing sign byte); it was read anyway. A assinatura ECDSA não está no formato DER canônico (há bytes excedentes, preenchimento ou falta o byte de sinal); mesmo assim, ela foi lida.+ The ECDSA signature is the raw r and s values instead of a DER sequence; it was read anyway. A assinatura ECDSA contém os valores brutos de r e s em vez de uma sequência DER; mesmo assim, ela foi lida.+ The RSA signature value does not have the length of the key's modulus (leading zero bytes dropped or added); it was read anyway. O valor da assinatura RSA não tem o mesmo comprimento do módulo da chave (bytes zero iniciais foram removidos ou adicionados); mesmo assim, ele foi lido.+ The RSA signature's DigestInfo has no NULL parameter (older signers write it so); it was read anyway. O DigestInfo da assinatura RSA não tem o parâmetro NULL (assinantes mais antigos o incluem); mesmo assim, ele foi lido.+ The certificate of {} does not allow this many CA certificates below it (path length), so it is not used to vouch for {}. O certificado de {} não permite essa quantidade de certificados de AC abaixo dele (comprimento do caminho), então não é usado para atestar a validade de {}.+ The certificate of {} is not a CA certificate that may issue certificates, so it is not used to vouch for {}. O certificado de {} não é um certificado de AC autorizado a emitir certificados, então não é usado para atestar a validade de {}.+ The certificate of {} has critical extensions PdfCraft does not recognize, so it is not used to vouch for {}. The certificate of {} has critical extensions PdfCraft does not recognize, so it is not used to vouch for {}.+ The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}. O certificado de {} não era válido no momento da assinatura, então não é usado para atestar a validade de {}.+ The checker found problems which may prevent the document from being fully accessible. A verificação encontrou problemas que podem impedir que o documento seja totalmente acessível.+ The document has been altered or corrupted since the signature was applied. O documento foi alterado ou corrompido desde que a assinatura foi aplicada.+ The document has been altered or corrupted since the timestamp was applied. O documento foi alterado ou corrompido desde que o carimbo de data e hora foi aplicado.+ The document has been altered since this signature was applied in ways it does not permit ({}). O documento foi alterado de maneiras não permitidas ({}), depois que esta assinatura foi aplicada.+ The document has been altered since this timestamp was applied in ways it does not permit ({}). O documento foi alterado de maneiras não permitidas ({}), depois que este carimbo de data e hora foi aplicado.+ The document has been modified since this signature was applied, but the changes are permitted ({}). O documento foi modificado depois que esta assinatura foi aplicada, mas as alterações são permitidas ({}).+ The document has been modified since this timestamp was applied, but the changes are permitted ({}). O documento foi modificado depois que este carimbo de data e hora foi aplicado, mas as alterações são permitidas ({}).+ The document has no tags (structure tree) O documento não tem tags (árvore de estrutura)+ The document has no title O documento não tem título+ The document isn't marked as tagged (MarkInfo Marked) O documento não está marcado como etiquetado (MarkInfo Marked)+ The document isn't tagged, so none of its content is O documento não está etiquetado, portanto nenhum conteúdo está+ The document's embedded revocation information shows that the signer's certificate has not been revoked. As informações de revogação incorporadas ao documento indicam que o certificado do signatário não foi revogado.+ The embedded timestamp token is valid and its authority is trusted; trusted time is {}. O token de carimbo de data e hora incorporado é válido e sua autoridade é confiável; o horário confiável é {}.+ The font {} isn't embedded A fonte {} não está incorporada+ The metadata doesn't identify the file as {} Os metadados não identificam o arquivo como {}+ The password is incorrect. A senha está incorreta.+ The password must have at least 6 characters. A senha deve ter pelo menos 6 caracteres.+ The password must have at least 8 characters. A senha deve ter pelo menos 8 caracteres.+ The passwords do not match. As senhas não correspondem.+ The security settings don't allow screen readers to read the text As configurações de segurança não permitem que leitores de tela leiam o texto+ The signature algorithm and the SignerInfo's digest algorithm name different hashes; the signature was made with the SignerInfo's. O algoritmo de assinatura e o algoritmo de resumo do SignerInfo indicam hashes diferentes; a assinatura foi feita com o hash indicado pelo SignerInfo.+ The signature carries an unverified timestamp ({}): the timestamp authority is not in your list of trusted certificates, so the signing time claimed by the signer is used instead. A assinatura contém um carimbo de data e hora não verificado ({}): a autoridade de carimbo de data e hora não está na sua lista de certificados confiáveis, então será usado o horário de assinatura informado pelo signatário.+ The signature contents are not hexadecimal. O conteúdo da assinatura não está em hexadecimal.+ The signature could not be checked ({}). Não foi possível verificar a assinatura ({}).+ The signature could not be read ({}). Não foi possível ler a assinatura ({}).+ The signature could not be verified ({}). Não foi possível validar a assinatura ({}).+ The signature has no valid byte range. A assinatura não tem um intervalo de bytes válido.+ The signature includes an embedded timestamp. A assinatura inclui um carimbo de data e hora incorporado.+ The signature is BER-encoded (indefinite lengths) rather than DER; it was read leniently. A assinatura está codificada em BER (comprimentos indefinidos), e não em DER; ela foi lida de forma permissiva.+ The signature uses the legacy adbe.x509.rsa_sha1 format. A assinatura usa o formato legado adbe.x509.rsa_sha1.+ The signature value does not match the signer's certificate: the signature is corrupt. O valor da assinatura não corresponde ao certificado do signatário: a assinatura está corrompida.+ The signature's byte range does not exclude exactly its contents. O intervalo de bytes da assinatura não exclui exatamente o conteúdo dela.+ The signature's byte range does not match the file. O intervalo de bytes da assinatura não corresponde ao arquivo.+ The signature's timestamp token could not be verified ({}). Não foi possível validar o token de carimbo de data e hora da assinatura ({}).+ The signature's timestamp token does not cover the signature value. O token de carimbo de data e hora da assinatura não abrange o valor da assinatura.+ The signed content is a constructed (segmented) OCTET STRING, as BER allows; it was read anyway. O conteúdo assinado é uma OCTET STRING construída (segmentada), como permite o BER; mesmo assim, foi lido.+ The signer's certificate does not allow digital signatures (its key usage has neither digital signature nor non-repudiation). O certificado do signatário não permite assinaturas digitais (o uso da chave não inclui assinatura digital nem não repúdio).+ The signer's certificate has been revoked ({}). O certificado do signatário foi revogado ({}).+ The signer's certificate has critical extensions PdfCraft does not recognize ({}). O certificado do signatário tem extensões críticas que o PdfCraft não reconhece ({}).+ The signer's certificate is not in the signature. O certificado do signatário não está incluído na assinatura.+ The signer's certificate is not issued for signing documents (its extended key usage has no document-signing purpose). O certificado do signatário não foi emitido para assinar documentos (o uso estendido da chave não inclui essa finalidade).+ The signer's certificate was not valid at the time of signing. O certificado do signatário não era válido no momento da assinatura.+ The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates. A identidade do signatário é desconhecida porque não foi incluída na sua lista de certificados confiáveis e nenhum dos certificados na cadeia acima dela é confiável.+ The signer's identity is valid. A identidade do signatário é válida.+ The timestamp authority's certificate was not valid at the time of timestamping. O certificado da autoridade de carimbo de data e hora não era válido no momento da emissão do carimbo.+ The timestamp authority's certificate is not issued for time stamping. The timestamp authority's certificate is not issued for time stamping.+ The timestamp contents are not hexadecimal. O conteúdo do carimbo de data e hora não está em hexadecimal.+ The timestamp has no valid byte range. O carimbo de data e hora não tem um intervalo de bytes válido.+ The timestamp token could not be read ({}). Não foi possível ler o token de carimbo de data e hora ({}).+ The timestamp token is valid and its authority is trusted. O token de carimbo de data e hora é válido e sua autoridade é confiável.+ The timestamp token is valid, but the timestamp authority is not in your list of trusted certificates. O token de carimbo de data e hora é válido, mas a autoridade não está na sua lista de certificados confiáveis.+ The timestamp's byte range does not exclude exactly its contents. O intervalo de bytes do carimbo de data e hora não exclui exatamente o conteúdo dele.+ The timestamp's byte range does not match the file. O intervalo de bytes do carimbo de data e hora não corresponde ao arquivo.+ The window shows the file name, not the title (Initial View > Show) A janela exibe o nome do arquivo, e não o título (Exibição inicial > Mostrar)+ Theme Tema+ There is no folder to save the digital ID in. Não há uma pasta para salvar a identidade digital.+ This document has not been modified since this signature was applied. Este documento não foi modificado desde que esta assinatura foi aplicada.+ This document has not been modified since this timestamp was applied. Este documento não foi modificado desde que este carimbo de data e hora foi aplicado.+ This file changed on disk. Reload it to see the new version; your unsaved changes will be lost. Este arquivo foi alterado no disco. Recarregue-o para ver a nova versão; suas alterações não salvas serão perdidas.+ This signature uses RIPEMD-160, a legacy 160-bit hash algorithm that is no longer recommended for signatures. It still validates, but it should not be relied on. Esta assinatura usa RIPEMD-160, um algoritmo de hash legado de 160 bits que não é mais recomendado para assinaturas. Ela ainda é validada, mas não deve ser considerada confiável.+ This signature uses SHA-1, a weak hash algorithm: collisions in it have been demonstrated. It still validates because many documents signed years ago use it, but it should not be relied on. Esta assinatura usa SHA-1, um algoritmo de hash fraco para o qual já foram demonstradas colisões. Ela ainda é validada porque muitos documentos assinados há anos o utilizam, mas não deve ser considerada confiável.+ Unsigned signature field Campo de assinatura não assinado+ Unsigned signature field: {name} Campo de assinatura não assinado: {name}+ Warning Aviso+ Zoom in (⌘+) Ampliar (⌘+)+ Zoom in / out (also pinch or ⌘-scroll) Ampliar / reduzir (também com pinça ou rolagem com ⌘)+ Zoom out (⌘−) Reduzir (⌘−)+ alternate text hides an annotation inside it o texto alternativo oculta uma anotação em seu interior+ alternate text on an element with no page content texto alternativo em um elemento sem conteúdo na página+ comments comentários+ document security store repositório de segurança do documento+ document structure estrutura do documento+ form fill preenchimento de formulário+ its alternate text is inside another element's and will never be read seu texto alternativo está dentro do texto de outro elemento e nunca será lido+ links links+ metadata metadados+ no alternate text sem texto alternativo+ no header cells (TH) sem células de cabeçalho (TH)+ no summary sem resumo+ not in a TR fora de uma TR+ not in a Table, THead, TBody or TFoot fora de uma Table, THead, TBody ou TFoot+ not in an L (list) fora de uma L (lista)+ not in an LI (list item) fora de um LI (item de lista)+ of de+ other changes outras alterações+ page content conteúdo da página+ page {n} is out of range (1–{count}) a página {n} está fora do intervalo (1–{count})+ pages added or removed páginas adicionadas ou removidas+ rows have between {min} and {max} columns as linhas têm entre {min} e {max} colunas+ the first heading is an H{n}; headings should not skip levels o primeiro título é H{n}; os títulos não devem pular níveis+ the signed version could not be read não foi possível ler a versão assinada+ {n} pages and no bookmarks {n} páginas e nenhum marcador+ {page} is not a page number or label {page} não é um número nem um rótulo de página+ {ty} element on page {p}: {what} elemento {ty} na página {p}: {what}+ {ty} element: {what} elemento {ty}: {what}+ {who}, certificate issued by an unknown issuer. {who}, certificado emitido por uma autoridade desconhecida.+ {who}, certificate issued by {issuer}. {who}, certificado emitido por {issuer}.+ {} annotation on page {p} isn't tagged A anotação {} na página {p} não está marcada com tag+ {} annotations aren't allowed As anotações {} não são permitidas+ … and {n} more … e mais {n}+ @plural Delete {n} field|Delete {n} fields Excluir {n} campo|Excluir {n} campos+ @plural {n} byte|{n} bytes {n} byte|{n} bytes+ @plural {n} comment|{n} comments {n} comentário|{n} comentários+ @plural {n} file|{n} files {n} arquivo|{n} arquivos+ @plural {n} image optimized|{n} images optimized {n} imagem otimizada|{n} imagens otimizadas+ @plural {n} item discarded|{n} items discarded {n} item descartado|{n} itens descartados+ @plural {n} pixel|{n} pixels {n} pixel|{n} pixels+ @plural {n} result|{n} results {n} resultado|{n} resultados+ calendar weekday Fr Sex+ calendar weekday Mo Seg+ calendar weekday Sa Sáb+ calendar weekday Su Dom+ calendar weekday Th Qui+ calendar weekday Tu Ter+ calendar weekday We Qua+ certificate Basic constraints Restrições básicas+ certificate Intended usage Uso pretendido+ certificate Issued by Emitido por+ certificate Issued to Emitido para+ certificate Issuer Emissor+ certificate Key usage Uso da chave+ certificate Public key Chave pública+ certificate SHA-1 digest Resumo SHA-1+ certificate SHA-256 digest Resumo SHA-256+ certificate Self-signed Autoassinado+ certificate Serial number Número de série+ certificate Valid from Válido desde+ certificate Valid to Válido até+ certificate Validity ends Fim da validade+ certificate Validity starts Início da validade+ certificate Version Versão+ theme Appearance Aparência+ # Untranslated: English text until a translator fills these in.+ The signature's signed attributes have no content type, which CMS requires; it was read anyway. The signature's signed attributes have no content type, which CMS requires; it was read anyway.+ This signature uses an RSA key shorter than 2048 bits, which is no longer considered strong enough for signatures. It still validates, but it should not be relied on. This signature uses an RSA key shorter than 2048 bits, which is no longer considered strong enough for signatures. It still validates, but it should not be relied on.+ The signature's signed attributes have no message digest, so the signature does not cover the document. The signature's signed attributes have no message digest, so the signature does not cover the document.+ The signature's signed attributes name a content type other than data, so it is not a signature of the document. The signature's signed attributes name a content type other than data, so it is not a signature of the document.+ Remove {standard} identification Remove {standard} identification++ # Prepare a form ▸ Text field table+ Add text field table Adicionar tabela de campos de texto+ Text field table Tabela de campos de texto+ Text Field Table Tabela de campos de texto+ Columns Colunas+ Row spacing Espaçamento entre linhas+ Column spacing Espaçamento entre colunas+ First row number Número da primeira linha+ Column widths Larguras das colunas+ Distribute evenly Distribuir igualmente+ Field names Nomes dos campos+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N ou {row} é o número da linha, {col} o da coluna e {seq} o da célula. Sem nenhum deles, o número da linha vai no final.+ Column {n} Coluna {n}+ Add fields Adicionar campos+ the rows are too short: make the area taller, or use fewer rows or less row spacing as linhas estão baixas demais: deixe a área mais alta ou use menos linhas ou menos espaçamento entre linhas+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing uma coluna está estreita demais: deixe a área mais larga, dê mais largura à coluna ou use menos colunas ou menos espaçamento entre colunas+ field names can't contain a period: {name} nomes de campo não podem conter ponto: {name}+ two cells would both be named {name} duas células teriam o nome {name}+ a field named {name} already exists já existe um campo chamado {name}++ # Prepare a form ▸ Text field table: limits (AI-assisted, not separately native-reviewed)+ a table has 1 to {max} rows uma tabela tem de 1 a {max} linhas+ a table has 1 to {max} columns uma tabela tem de 1 a {max} colunas+ the first row number can be at most {max} o número da primeira linha pode ser no máximo {max}+ the area, the spacing and the column widths must be numbers, the spacing 0 or more and each width more than 0 a área, o espaçamento e as larguras das colunas devem ser números, o espaçamento 0 ou mais e cada largura maior que 0++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Hoje+ @plural {n} reply|{n} replies {n} resposta|{n} respostas++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Ferramentas de página+ Insert pages from a file after the selection… Inserir páginas de um arquivo após a seleção…+ Rotate the selected pages counterclockwise Girar as páginas selecionadas no sentido anti-horário+ Rotate the selected pages clockwise Girar as páginas selecionadas no sentido horário+ Extract the selected pages… Extrair as páginas selecionadas…+ Delete the selected pages Excluir as páginas selecionadas+ Export value Valor de exportaçãodiff --cc crates/ui-egui/src/i18n/ru.tsvindex f83fe8826,274232d58..c56e30982--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@@ -2345,4 -2411,62 +2411,63 @@@ animation effects Off Вык�Make properties default Сделать свойства стандартнымиPages selected Выделенные страницыPage properties Свойства страницы+ Create & Edit Создание и редактирование+ Review & Compare Рецензирование и сравнение+ Forms & Signatures Формы и подписи+ Protect & Standardize Защита и стандартизация+ Customize & Automate Настройка и автоматизация+ No tools match your search. Нет инструментов, соответствующих запросу.+ Expand all tools Развернуть все инструменты+ Collapse all tools Свернуть все инструменты+ Attach a file… Прикрепить файл…+ Delete attachment Удалить вложение+ Attaching files is not available on the web yet Прикрепление файлов в веб-версии пока недоступно+ Attach {name} Прикрепить {name}+ Delete attachment {key} Удалить вложение {key}+ Font Шрифт+ Bulleted list Маркированный список+ Numbered list Нумерованный список+ Alignment Выравнивание+ Superscript Надстрочный+ Subscript Подстрочный+ Paragraph spacing Интервал между абзацами+ Less Меньше+ Other options Другие параметры+ Thumbnail size Размер миниатюр+ Smaller thumbnails Уменьшить миниатюры+ Larger thumbnails Увеличить миниатюры+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Изменить форму комментария++ # Prepare a form ▸ Text field table+ Add text field table Добавить таблицу текстовых полей+ Text field table Таблица текстовых полей+ Text Field Table Таблица текстовых полей+ Columns Столбцы+ Row spacing Интервал между строками+ Column spacing Интервал между столбцами+ First row number Номер первой строки+ Column widths Ширина столбцов+ Distribute evenly Распределить равномерно+ Field names Имена полей+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N или {row} — номер строки, {col} — номер столбца, {seq} — номер ячейки. Если их нет, номер строки добавляется в конец.+ Column {n} Столбец {n}+ Add fields Добавить поля+ the rows are too short: make the area taller, or use fewer rows or less row spacing строки слишком низкие: увеличьте высоту области, уменьшите число строк или интервал между ними+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing столбец слишком узкий: расширьте область, отдайте столбцу больше ширины, уменьшите число столбцов или интервал между ними+ field names can't contain a period: {name} имена полей не могут содержать точку: {name}+ two cells would both be named {name} две ячейки получили бы одно имя {name}+ a field named {name} already exists поле с именем {name} уже существует++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Сегодня+ @plural {n} reply|{n} replies {n} ответ|{n} ответа|{n} ответов++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Инструменты страниц+ Insert pages from a file after the selection… Вставить страницы из файла после выделения…+ Rotate the selected pages counterclockwise Повернуть выбранные страницы против часовой стрелки+ Rotate the selected pages clockwise Повернуть выбранные страницы по часовой стрелке+ Extract the selected pages… Извлечь выбранные страницы…+ Delete the selected pages Удалить выбранные страницы+ Export value Значение экспортаdiff --cc crates/ui-egui/src/i18n/sl.tsvindex 4a8763a8d,420e6a599..672065adf--- a/crates/ui-egui/src/i18n/sl.tsv+++ b/crates/ui-egui/src/i18n/sl.tsv@@@ -2437,4 -2503,62 +2503,63 @@@ animation effects Off IzklopljenMake properties default Nastavi lastnosti kot privzetePages selected Izbrane straniPage properties Lastnosti strani+ Create & Edit Ustvarjanje in urejanje+ Review & Compare Pregled in primerjava+ Forms & Signatures Obrazci in podpisi+ Protect & Standardize Zaščita in standardizacija+ Customize & Automate Prilagajanje in avtomatizacija+ No tools match your search. Iskanju ne ustreza nobeno orodje.+ Expand all tools Razširi vsa orodja+ Collapse all tools Strni vsa orodja+ Attach a file… Priloži datoteko…+ Delete attachment Izbriši prilogo+ Attaching files is not available on the web yet Prilaganje datotek na spletu še ni na voljo+ Attach {name} Priloži {name}+ Delete attachment {key} Izbriši prilogo {key}+ Font Pisava+ Bulleted list Označen seznam+ Numbered list Oštevilčen seznam+ Alignment Poravnava+ Superscript Nadpisano+ Subscript Podpisano+ Paragraph spacing Razmik med odstavki+ Less Manj+ Other options Druge možnosti+ Thumbnail size Velikost sličic+ Smaller thumbnails Manjše sličice+ Larger thumbnails Večje sličice+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Spremeni obliko komentarja++ # Prepare a form ▸ Text field table+ Add text field table Dodaj tabelo besedilnih polj+ Text field table Tabela besedilnih polj+ Text Field Table Tabela besedilnih polj+ Columns Stolpci+ Row spacing Razmik med vrsticami+ Column spacing Razmik med stolpci+ First row number Številka prve vrstice+ Column widths Širine stolpcev+ Distribute evenly Enakomerno porazdeli+ Field names Imena polj+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N ali {row} je številka vrstice, {col} številka stolpca in {seq} številka celice. Brez njih se številka vrstice doda na konec.+ Column {n} Stolpec {n}+ Add fields Dodaj polja+ the rows are too short: make the area taller, or use fewer rows or less row spacing vrstice so prenizke: povečajte višino območja ali uporabite manj vrstic ali manjši razmik med vrsticami+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing stolpec je preozek: razširite območje, stolpcu dajte več širine ali uporabite manj stolpcev ali manjši razmik med stolpci+ field names can't contain a period: {name} imena polj ne smejo vsebovati pike: {name}+ two cells would both be named {name} dve celici bi imeli enako ime {name}+ a field named {name} already exists polje z imenom {name} že obstaja++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Danes+ @plural {n} reply|{n} replies {n} odgovor|{n} odgovora|{n} odgovori|{n} odgovorov++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Orodja za strani+ Insert pages from a file after the selection… Vstavi strani iz datoteke za izborom…+ Rotate the selected pages counterclockwise Zavrti izbrane strani v nasprotni smeri urnega kazalca+ Rotate the selected pages clockwise Zavrti izbrane strani v smeri urnega kazalca+ Extract the selected pages… Izvleci izbrane strani…+ Delete the selected pages Izbriši izbrane strani+ Export value Izvozna vrednostdiff --cc crates/ui-egui/src/i18n/te.tsvindex 789798557,7f339989e..16f750da4--- a/crates/ui-egui/src/i18n/te.tsv+++ b/crates/ui-egui/src/i18n/te.tsv@@@ -2341,4 -2407,62 +2407,63 @@@ animation effects Off ఆఫ�Make properties default లక్షణాలను డిఫాల్ట్గా చేయిPages selected ఎంచుకున్న పేజీలుPage properties పేజీ లక్షణాలు+ Create & Edit సృష్టించు & సవరించు+ Review & Compare సమీక్షించు & పోల్చు+ Forms & Signatures ఫారమ్లు & సంతకాలు+ Protect & Standardize రక్షించు & ప్రామాణీకరించు+ Customize & Automate అనుకూలీకరించు & ఆటోమేట్ చేయి+ No tools match your search. మీ శోధనకు సరిపోలే సాధనాలు లేవు.+ Expand all tools అన్ని సాధనాలను విస్తరించు+ Collapse all tools అన్ని సాధనాలను కుదించు+ Attach a file… ఫైల్ను జోడించు…+ Delete attachment జోడింపును తొలగించు+ Attaching files is not available on the web yet వెబ్లో ఫైల్లను జోడించడం ఇంకా అందుబాటులో లేదు+ Attach {name} {name}ను జోడించు+ Delete attachment {key} జోడింపు {key}ను తొలగించు+ Font ఫాంట్+ Bulleted list బుల్లెట్ జాబితా+ Numbered list సంఖ్యల జాబితా+ Alignment అమరిక+ Superscript సూపర్స్క్రిప్ట్+ Subscript సబ్స్క్రిప్ట్+ Paragraph spacing పేరా అంతరం+ Less తక్కువ+ Other options ఇతర ఎంపికలు+ Thumbnail size థంబ్నెయిల్ పరిమాణం+ Smaller thumbnails చిన్న థంబ్నెయిల్లు+ Larger thumbnails పెద్ద థంబ్నెయిల్లు+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment వ్యాఖ్య ఆకారాన్ని మార్చు++ # Prepare a form ▸ Text field table+ Add text field table టెక్స్ట్ ఫీల్డ్ పట్టిక జోడించు+ Text field table టెక్స్ట్ ఫీల్డ్ పట్టిక+ Text Field Table టెక్స్ట్ ఫీల్డ్ పట్టిక+ Columns నిలువు వరుసలు+ Row spacing వరుసల మధ్య దూరం+ Column spacing నిలువు వరుసల మధ్య దూరం+ First row number మొదటి వరుస సంఖ్య+ Column widths నిలువు వరుసల వెడల్పులు+ Distribute evenly సమానంగా పంచు+ Field names ఫీల్డ్ పేర్లు+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N లేదా {row} వరుస సంఖ్య, {col} నిలువు వరుస సంఖ్య, {seq} గడి సంఖ్య. వీటిలో ఏదీ లేకపోతే, వరుస సంఖ్య చివర చేరుతుంది.+ Column {n} నిలువు వరుస {n}+ Add fields ఫీల్డ్లు జోడించు+ the rows are too short: make the area taller, or use fewer rows or less row spacing వరుసలు చాలా తక్కువ ఎత్తులో ఉన్నాయి: ప్రాంతాన్ని ఎత్తుగా చేయండి, లేదా తక్కువ వరుసలు లేదా తక్కువ వరుస దూరం వాడండి+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing ఒక నిలువు వరుస చాలా ఇరుకుగా ఉంది: ప్రాంతాన్ని వెడల్పు చేయండి, ఆ నిలువు వరుసకు ఎక్కువ వెడల్పు ఇవ్వండి, లేదా తక్కువ నిలువు వరుసలు లేదా తక్కువ దూరం వాడండి+ field names can't contain a period: {name} ఫీల్డ్ పేర్లలో చుక్క ఉండకూడదు: {name}+ two cells would both be named {name} రెండు గడులకూ {name} అనే పేరు వస్తుంది+ a field named {name} already exists {name} అనే ఫీల్డ్ ఇప్పటికే ఉంది++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today ఈరోజు+ @plural {n} reply|{n} replies {n} ప్రత్యుత్తరం|{n} ప్రత్యుత్తరాలు++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools పేజీ సాధనాలు+ Insert pages from a file after the selection… ఎంపిక తర్వాత ఫైల్ నుండి పేజీలను చొప్పించు…+ Rotate the selected pages counterclockwise ఎంచుకున్న పేజీలను అపసవ్య దిశలో తిప్పు+ Rotate the selected pages clockwise ఎంచుకున్న పేజీలను సవ్య దిశలో తిప్పు+ Extract the selected pages… ఎంచుకున్న పేజీలను సంగ్రహించు…+ Delete the selected pages ఎంచుకున్న పేజీలను తొలగించు+ Export value ఎగుమతి విలువdiff --cc crates/ui-egui/src/i18n/tr.tsvindex ad106a380,a2ecaea17..5f84355d3--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@@ -2428,4 -2494,62 +2494,63 @@@ animation effects Off Kapal�Make properties default Özellikleri varsayılan yapPages selected Seçilen sayfalarPage properties Sayfa özellikleri+ Create & Edit Oluştur ve Düzenle+ Review & Compare İncele ve Karşılaştır+ Forms & Signatures Formlar ve İmzalar+ Protect & Standardize Koru ve Standartlaştır+ Customize & Automate Özelleştir ve Otomatikleştir+ No tools match your search. Aramanızla eşleşen araç yok.+ Expand all tools Tüm araçları genişlet+ Collapse all tools Tüm araçları daralt+ Attach a file… Dosya ekle…+ Delete attachment Eki sil+ Attaching files is not available on the web yet Dosya eklemek web'de henüz kullanılamıyor+ Attach {name} {name} ekle+ Delete attachment {key} {key} ekini sil+ Font Yazı tipi+ Bulleted list Madde işaretli liste+ Numbered list Numaralı liste+ Alignment Hizalama+ Superscript Üst simge+ Subscript Alt simge+ Paragraph spacing Paragraf aralığı+ Less Daha az+ Other options Diğer seçenekler+ Thumbnail size Küçük resim boyutu+ Smaller thumbnails Küçük resimleri küçült+ Larger thumbnails Küçük resimleri büyüt+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Yorumun şeklini değiştir++ # Prepare a form ▸ Text field table+ Add text field table Metin alanı tablosu ekle+ Text field table Metin alanı tablosu+ Text Field Table Metin alanı tablosu+ Columns Sütunlar+ Row spacing Satır aralığı+ Column spacing Sütun aralığı+ First row number İlk satır numarası+ Column widths Sütun genişlikleri+ Distribute evenly Eşit dağıt+ Field names Alan adları+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N veya {row} satır numarası, {col} sütun numarası, {seq} hücre numarasıdır. Hiçbiri yoksa satır numarası sona eklenir.+ Column {n} Sütun {n}+ Add fields Alanları ekle+ the rows are too short: make the area taller, or use fewer rows or less row spacing satırlar çok kısa: alanı uzatın ya da daha az satır veya daha az satır aralığı kullanın+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing bir sütun çok dar: alanı genişletin, sütuna daha fazla yer verin ya da daha az sütun veya daha az sütun aralığı kullanın+ field names can't contain a period: {name} alan adları nokta içeremez: {name}+ two cells would both be named {name} iki hücrenin de adı {name} olurdu+ a field named {name} already exists {name} adlı bir alan zaten var++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Bugün+ @plural {n} reply|{n} replies {n} yanıt++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Sayfa araçları+ Insert pages from a file after the selection… Seçimin ardından dosyadan sayfa ekle…+ Rotate the selected pages counterclockwise Seçili sayfaları saat yönünün tersine döndür+ Rotate the selected pages clockwise Seçili sayfaları saat yönünde döndür+ Extract the selected pages… Seçili sayfaları ayıkla…+ Delete the selected pages Seçili sayfaları sil+ Export value Dışa aktarma değeridiff --cc crates/ui-egui/src/i18n/uk.tsvindex 68b3fb8f5,9c7686883..4395a0383--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@@ -2454,4 -2520,62 +2520,63 @@@ animation effects Off Вимкнен�Make properties default Зробити властивості типовимиPages selected Вибрані сторінкиPage properties Властивості сторінки+ Create & Edit Створення й редагування+ Review & Compare Рецензування й порівняння+ Forms & Signatures Форми й підписи+ Protect & Standardize Захист і стандартизація+ Customize & Automate Налаштування й автоматизація+ No tools match your search. Немає інструментів, що відповідають пошуку.+ Expand all tools Розгорнути всі інструменти+ Collapse all tools Згорнути всі інструменти+ Attach a file… Прикріпити файл…+ Delete attachment Видалити вкладення+ Attaching files is not available on the web yet Прикріплення файлів у веб-версії поки недоступне+ Attach {name} Прикріпити {name}+ Delete attachment {key} Видалити вкладення {key}+ Font Шрифт+ Bulleted list Маркований список+ Numbered list Нумерований список+ Alignment Вирівнювання+ Superscript Надрядковий+ Subscript Підрядковий+ Paragraph spacing Інтервал між абзацами+ Less Менше+ Other options Інші параметри+ Thumbnail size Розмір мініатюр+ Smaller thumbnails Зменшити мініатюри+ Larger thumbnails Збільшити мініатюри+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Змінити форму коментаря++ # Prepare a form ▸ Text field table+ Add text field table Додати таблицю текстових полів+ Text field table Таблиця текстових полів+ Text Field Table Таблиця текстових полів+ Columns Стовпці+ Row spacing Інтервал між рядками+ Column spacing Інтервал між стовпцями+ First row number Номер першого рядка+ Column widths Ширина стовпців+ Distribute evenly Розподілити рівномірно+ Field names Імена полів+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N або {row} — номер рядка, {col} — номер стовпця, {seq} — номер клітинки. Якщо їх немає, номер рядка додається в кінці.+ Column {n} Стовпець {n}+ Add fields Додати поля+ the rows are too short: make the area taller, or use fewer rows or less row spacing рядки занадто низькі: збільште висоту області, зменште кількість рядків або інтервал між ними+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing стовпець занадто вузький: розширте область, дайте стовпцю більше ширини, зменште кількість стовпців або інтервал між ними+ field names can't contain a period: {name} імена полів не можуть містити крапку: {name}+ two cells would both be named {name} дві клітинки мали б однакове ім'я {name}+ a field named {name} already exists поле з іменем {name} уже існує++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Сьогодні+ @plural {n} reply|{n} replies {n} відповідь|{n} відповіді|{n} відповідей++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Інструменти сторінок+ Insert pages from a file after the selection… Вставити сторінки з файлу після виділення…+ Rotate the selected pages counterclockwise Повернути вибрані сторінки проти годинникової стрілки+ Rotate the selected pages clockwise Повернути вибрані сторінки за годинниковою стрілкою+ Extract the selected pages… Витягнути вибрані сторінки…+ Delete the selected pages Видалити вибрані сторінки+ Export value Значення експортуdiff --cc crates/ui-egui/src/i18n/vi.tsvindex 74b97670f,973ba870e..99eb14e8b--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@@ -2686,3 -2772,55 +2772,56 @@@ key Space Spac# Historical snapshot notice bar (View signed version / View revision).You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original. Bạn đang xem phiên bản đã ký của “{from}” (bản sửa đổi {rev}). Đây là ảnh nhanh: các thay đổi ở đây không được áp dụng đến bản gốc.You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original. Bạn đang xem bản sửa đổi {rev} của “{from}”. Đây là ảnh nhanh: các thay đổi ở đây không được áp dụng đến bản gốc.+ Attach a file… Đính kèm tệp…+ Delete attachment Xóa tệp đính kèm+ Attaching files is not available on the web yet Chưa thể đính kèm tệp trên web+ Attach {name} Đính kèm {name}+ Delete attachment {key} Xóa tệp đính kèm {key}+ Thumbnail size Kích thước hình thu nhỏ+ Smaller thumbnails Giảm kích thước hình thu nhỏ+ Larger thumbnails Tăng kích thước hình thu nhỏ+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment Đổi hình dạng nhận xét++ # AI-assisted additions for reading printer options off the GUI thread (#1818) (2026-10-16); not reviewed by a native speaker.+ Reading the printer's settings… Đang đọc cài đặt của máy in…++ # Prepare a form ▸ Text field table+ Add text field table Thêm bảng trường văn bản+ Text field table Bảng trường văn bản+ Text Field Table Bảng trường văn bản+ Columns Cột+ Row spacing Khoảng cách hàng+ Column spacing Khoảng cách cột+ First row number Số hàng đầu tiên+ Column widths Độ rộng cột+ Distribute evenly Phân bố đều+ Field names Tên trường+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N hoặc {row} là số hàng, {col} là số cột, {seq} là số ô. Nếu không có cái nào, số hàng được thêm vào cuối.+ Column {n} Cột {n}+ Add fields Thêm các trường+ the rows are too short: make the area taller, or use fewer rows or less row spacing các hàng quá thấp: hãy làm vùng cao hơn, hoặc dùng ít hàng hơn hay khoảng cách hàng nhỏ hơn+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing một cột quá hẹp: hãy làm vùng rộng hơn, cho cột thêm độ rộng, hoặc dùng ít cột hơn hay khoảng cách cột nhỏ hơn+ field names can't contain a period: {name} tên trường không được chứa dấu chấm: {name}+ two cells would both be named {name} hai ô sẽ cùng có tên {name}+ a field named {name} already exists đã có trường tên {name}+ a table has 1 to {max} rows một bảng có từ 1 đến {max} hàng+ a table has 1 to {max} columns một bảng có từ 1 đến {max} cột+ the first row number can be at most {max} số hàng đầu tiên tối đa là {max}+ the area, the spacing and the column widths must be numbers, the spacing 0 or more and each width more than 0 vùng, khoảng cách và độ rộng cột phải là số, khoảng cách từ 0 trở lên và mỗi độ rộng lớn hơn 0++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today Hôm nay++ # AI-assisted additions for restoring the last view (#1767) (2026-10-16); not reviewed by a native speaker.+ Restore the last view (page, zoom and page display) when a document is opened again Khôi phục chế độ xem gần nhất (trang, thu phóng và hiển thị trang) khi mở lại tài liệu+ @plural {n} reply|{n} replies {n} câu trả lời++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools Công cụ trang+ Insert pages from a file after the selection… Chèn trang từ tệp sau vùng chọn…+ Rotate the selected pages counterclockwise Xoay các trang đã chọn ngược chiều kim đồng hồ+ Rotate the selected pages clockwise Xoay các trang đã chọn theo chiều kim đồng hồ+ Extract the selected pages… Trích xuất các trang đã chọn…+ Delete the selected pages Xóa các trang đã chọn++ Export value Giá trị xuấtdiff --cc crates/ui-egui/src/i18n/zh-hans.tsvindex e78d5cee1,d77c8f642..608a73839--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@@ -2396,4 -2462,62 +2462,63 @@@ animation effects Off �Make properties default 将属性设为默认Pages selected 选定的页面Page properties 页面属性+ Create & Edit 创建和编辑+ Review & Compare 审阅和比较+ Forms & Signatures 表单和签名+ Protect & Standardize 保护和标准化+ Customize & Automate 自定义和自动化+ No tools match your search. 没有与搜索匹配的工具。+ Expand all tools 展开所有工具+ Collapse all tools 折叠所有工具+ Attach a file… 附加文件…+ Delete attachment 删除附件+ Attaching files is not available on the web yet 网页版尚不支持附加文件+ Attach {name} 附加 {name}+ Delete attachment {key} 删除附件 {key}+ Font 字体+ Bulleted list 项目符号列表+ Numbered list 编号列表+ Alignment 对齐+ Superscript 上标+ Subscript 下标+ Paragraph spacing 段落间距+ Less 收起+ Other options 其他选项+ Thumbnail size 缩略图大小+ Smaller thumbnails 缩小缩略图+ Larger thumbnails 放大缩略图+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment 更改注释形状++ # Prepare a form ▸ Text field table+ Add text field table 添加文本字段表格+ Text field table 文本字段表格+ Text Field Table 文本字段表格+ Columns 列+ Row spacing 行间距+ Column spacing 列间距+ First row number 起始行号+ Column widths 列宽+ Distribute evenly 平均分布+ Field names 字段名称+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N 或 {row} 表示行号,{col} 表示列号,{seq} 表示单元格序号。如果都没有,行号加在末尾。+ Column {n} 第 {n} 列+ Add fields 添加字段+ the rows are too short: make the area taller, or use fewer rows or less row spacing 行太矮:请增加区域高度,或减少行数或行间距+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing 某列太窄:请加宽区域、给该列更多宽度,或减少列数或列间距+ field names can't contain a period: {name} 字段名称不能包含句点:{name}+ two cells would both be named {name} 两个单元格的名称都会是 {name}+ a field named {name} already exists 已存在名为 {name} 的字段++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today 今天+ @plural {n} reply|{n} replies {n} 条回复++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools 页面工具+ Insert pages from a file after the selection… 在所选内容后插入文件中的页面…+ Rotate the selected pages counterclockwise 逆时针旋转所选页面+ Rotate the selected pages clockwise 顺时针旋转所选页面+ Extract the selected pages… 提取所选页面…+ Delete the selected pages 删除所选页面+ Export value 导出值diff --cc crates/ui-egui/src/i18n/zh-hant.tsvindex c4deda451,ce3b939f1..25939791f--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@@ -2382,4 -2448,62 +2448,63 @@@ animation effects Off �Make properties default 將內容設為預設Pages selected 選取的頁面Page properties 頁面屬性+ Create & Edit 建立與編輯+ Review & Compare 審閱與比較+ Forms & Signatures 表單與簽名+ Protect & Standardize 保護與標準化+ Customize & Automate 自訂與自動化+ No tools match your search. 沒有符合搜尋的工具。+ Expand all tools 展開所有工具+ Collapse all tools 摺疊所有工具+ Attach a file… 附加檔案…+ Delete attachment 刪除附件+ Attaching files is not available on the web yet 網頁版尚不支援附加檔案+ Attach {name} 附加 {name}+ Delete attachment {key} 刪除附件 {key}+ Font 字型+ Bulleted list 項目符號清單+ Numbered list 編號清單+ Alignment 對齊+ Superscript 上標+ Subscript 下標+ Paragraph spacing 段落間距+ Less 收起+ Other options 其他選項+ Thumbnail size 縮圖大小+ Smaller thumbnails 縮小縮圖+ Larger thumbnails 放大縮圖+ # Lines, connected lines and polygons reshaped by their ends and corners (M5).+ Reshape comment 變更註解形狀++ # Prepare a form ▸ Text field table+ Add text field table 新增文字欄位表格+ Text field table 文字欄位表格+ Text Field Table 文字欄位表格+ Columns 欄+ Row spacing 列間距+ Column spacing 欄間距+ First row number 起始列號+ Column widths 欄寬+ Distribute evenly 平均分配+ Field names 欄位名稱+ N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last. N 或 {row} 代表列號,{col} 代表欄號,{seq} 代表儲存格序號。若都沒有,列號會加在結尾。+ Column {n} 第 {n} 欄+ Add fields 新增欄位+ the rows are too short: make the area taller, or use fewer rows or less row spacing 列太矮:請加高區域,或減少列數或列間距+ a column is too narrow: make the area wider, give the column more of it, or use fewer columns or less column spacing 某欄太窄:請加寬區域、給該欄更多寬度,或減少欄數或欄間距+ field names can't contain a period: {name} 欄位名稱不能包含句點:{name}+ two cells would both be named {name} 兩個儲存格的名稱都會是 {name}+ a field named {name} already exists 已有名為 {name} 的欄位++ # Date picker: Today button (#4274) (AI-assisted, not separately native-reviewed)+ Today 今天+ @plural {n} reply|{n} replies {n} 則回覆++ # Pages panel: the Page tools menu (#4415) (AI-assisted, not separately native-reviewed)+ Page tools 頁面工具+ Insert pages from a file after the selection… 在所選內容後插入檔案中的頁面…+ Rotate the selected pages counterclockwise 逆時針旋轉所選頁面+ Rotate the selected pages clockwise 順時針旋轉所選頁面+ Extract the selected pages… 擷取所選頁面…+ Delete the selected pages 刪除所選頁面+ Export value 匯出值diff --cc crates/ui-egui/src/tools/prepare/draft.rsindex 000000000,c6f9bf445..994fbaa8bmode 000000,100644..100644--- a/crates/ui-egui/src/tools/prepare/draft.rs+++ b/crates/ui-egui/src/tools/prepare/draft.rs@@@ -1,0 -1,297 +1,300 @@@+ use super::{Calculate, FieldLook, FieldProps, FormField, FormFieldKind, Format, Validate};++ // ───────────────────────────────────────────────────────────────────────── Field Properties++ impl crate::PdfCraftApp {+ /// Open Field Properties for a field of the active document.+ pub fn open_field_props(&mut self, name: &str, widget: usize) {+ let Some((index, id)) = self.active_ids() else { return };+ let names = self.views[index].prepare.names();+ if names.len() > 1 && names.iter().any(|n| n == name) {+ let draft = self.session.get(id).map_or(Err("The document is no longer open."), |doc| crate::bulk_fields::Draft::new(doc, names));+ match draft {+ Ok(draft) => {+ self.field_props = None;+ self.bulk_field_props = Some(draft);+ self.dialog = Some(crate::Dialog::BulkFieldProps);+ }+ Err(why) => self.notify_tr(why),+ }+ return;+ }+ self.bulk_field_props = None;+ let Some(f) = self.session.get(id).and_then(|d| d.form.iter().find(|f| f.name == name).cloned()) else { return };+ let mut d = FieldDraft::new(&f, widget);+ d.look = self.session.get(id).and_then(|doc| doc.field_look(name));+ d.check_style = self.session.get(id).and_then(|doc| doc.field_check_style(name));+ if let Some(o) = d.original.as_mut() {+ o.look = d.look;+ o.check_style = d.check_style;+ }+ let others: Vec<String> =+ self.session.get(id).map(|doc| doc.form.iter().filter(|x| x.name != name).map(|x| x.name.clone()).collect()).unwrap_or_default();+ d.others = others.clone();+ d.actions = self.session.get(id).map(|doc| doc.field_actions(name)).unwrap_or_default();+ d.chained = self.session.get(id).map(|doc| doc.field_action_chains(name)).unwrap_or_default();+ if let Some(o) = d.original.as_mut() {+ o.others = others;+ o.actions = d.actions.clone();+ }+ self.field_props = Some(d);+ self.dialog = Some(crate::Dialog::FieldProps);+ }+ }++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum FieldTab {+ General,+ Appearance,+ Position,+ Options,+ Format,+ Validate,+ Calculate,+ Actions,+ }++ /// Actions tab: the "Select Action" choices.+ pub const ACTION_KINDS: [&str; 8] = [+ "Run a JavaScript",+ "Open a web link",+ "Reset a form",+ "Execute a menu item",+ "Go to a page view",+ "Show a field",+ "Hide a field",+ "Submit a form",+ ];++ /// Actions tab: the action being added.+ #[derive(Clone, Debug, PartialEq)]+ pub struct ActionDraft {+ pub trigger: pdfcraft_engine::FieldTrigger,+ pub kind: usize,+ /// The script, URL, field names (comma-separated), menu item or page number.+ pub text: String,+ }++ impl Default for ActionDraft {+ fn default() -> Self {+ ActionDraft { trigger: pdfcraft_engine::FieldTrigger::MouseUp, kind: 0, text: String::new() }+ }+ }++ impl ActionDraft {+ pub fn action(&self) -> Result<pdfcraft_engine::FieldAction, String> {+ use pdfcraft_engine::FieldAction as A;+ let t = self.text.trim();+ let names = || t.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect::<Vec<_>>();+ Ok(match self.kind {+ 0 => A::JavaScript(self.text.clone()),+ 1 if !t.is_empty() => A::Uri(t.to_string()),+ 2 => A::Reset(names()),+ 3 => A::Named(if t.is_empty() { "Print".into() } else { t.to_string() }),+ 4 => A::GoTo(t.parse::<usize>().ok().filter(|p| *p >= 1).ok_or("Enter a page number")? - 1),+ 5 if !t.is_empty() => A::ShowHide { fields: names(), hide: false },+ 6 if !t.is_empty() => A::ShowHide { fields: names(), hide: true },+ 7 if !t.is_empty() => A::Submit(t.to_string()),+ 1 | 7 => return Err("Enter a URL".into()),+ _ => return Err("Enter the field names".into()),+ })+ }+ }++ /// The Field Properties dialog's working copy.+ #[derive(Clone, Debug, PartialEq)]+ pub struct FieldDraft {+ pub field: String,+ pub kind: FormFieldKind,+ pub widget: usize,+ pub tab: FieldTab,+ pub name: String,+ pub tooltip: String,+ pub caption: String,+ pub read_only: bool,+ pub required: bool,+ pub multiline: bool,+ pub limit: bool,+ pub max_len: usize,+ pub options: Vec<String>,+ pub new_option: String,+ /// `/Ff` as edited on the Options tab.+ pub flags: u32,+ /// Field Properties ▸ General ▸ Locked.+ pub locked: bool,+ /// `/Q`: 0 left, 1 centre, 2 right.+ pub quadding: i64,+ /// `/DV` (text and choices), or the default state (buttons: empty = off).+ pub default: String,+ /// Check boxes and radio buttons: this widget's "on" state (export value).+ pub on_state: String,++ pub export_value: String,+ /// 0 = auto.+ pub font_size: f64,+ /// Left, bottom, width, height in points.+ pub position: [f64; 4],+ /// `/MK /R`: 0, 90, 180 or 270 degrees counterclockwise.+ pub rotation: i64,+ pub look: Option<FieldLook>,+ /// Check boxes and radio buttons: the mark when on (Options tab).+ pub check_style: Option<pdfcraft_engine::CheckStyle>,+ pub format: Format,+ pub validate: Validate,+ pub calculate: Calculate,+ /// Every other field's name (the Calculate tab picks from them).+ pub others: Vec<String>,+ /// Actions tab: each trigger's action, and the one being added.+ pub actions: Vec<(pdfcraft_engine::FieldTrigger, pdfcraft_engine::FieldAction)>,+ pub new_action: ActionDraft,+ /// Actions tab: the trigger whose script `new_action` is editing (Edit), if any.+ pub editing: Option<pdfcraft_engine::FieldTrigger>,+ /// Actions tab: how many actions the document chains after each trigger's first one. They are+ /// kept when that first action is replaced.+ pub chained: Vec<(pdfcraft_engine::FieldTrigger, usize)>,+ pub(super) original: Box<Option<FieldDraft>>,+ }++ pub(crate) fn da_size(da: &str) -> f64 {+ let mut previous = "";+ let mut size = 0.0;+ for token in da.split_whitespace() {+ if token == "Tf" {+ size = previous.parse::<f64>().ok().filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(0.0);+ }+ previous = token;+ }+ size+ }++ pub(crate) fn da_font(da: &str) -> &str {+ let (mut two_back, mut previous, mut font) = ("", "", "Helv");+ for token in da.split_whitespace() {+ if token == "Tf" {+ font = two_back.trim_start_matches('/');+ }+ two_back = previous;+ previous = token;+ }+ font+ }++ impl FieldDraft {+ pub fn new(f: &FormField, widget: usize) -> Self {+ let r = f.widgets.get(widget).map(|w| w.rect).unwrap_or_default();+ let mut d = FieldDraft {+ field: f.name.clone(),+ kind: f.kind,+ widget,+ tab: FieldTab::General,+ // The full name: a dotted name moves the field under those parent fields (#2696).+ name: f.name.clone(),+ tooltip: f.tooltip.clone().unwrap_or_default(),+ caption: f.widgets.get(widget).and_then(|w| w.caption.clone()).unwrap_or_default(),+ read_only: f.read_only(),+ required: f.has(pdfcraft_engine::field_flags::REQUIRED),+ multiline: f.has(pdfcraft_engine::field_flags::MULTILINE),+ limit: f.max_len.is_some(),+ max_len: f.max_len.unwrap_or(0),+ options: f.options.iter().map(|(_, d)| d.clone()).collect(),+ new_option: String::new(),+ flags: f.flags,+ locked: f.locked(),+ quadding: f.quadding,+ default: f.default.first().cloned().unwrap_or_default(),+ on_state: f.widgets.get(widget).and_then(|w| w.on_state.clone()).unwrap_or_default(),++ export_value: f.export_of(widget).unwrap_or_default().to_string(),+ font_size: da_size(&f.da),+ position: [r[0], r[1], r[2] - r[0], r[3] - r[1]],+ rotation: f.widgets.get(widget).map(|w| w.rotation).unwrap_or(0),+ look: None,+ check_style: None,+ format: f.actions.format.clone(),+ validate: f.actions.validate.clone(),+ calculate: f.actions.calculate.clone(),+ others: Vec::new(),+ actions: Vec::new(),+ new_action: ActionDraft::default(),+ editing: None,+ chained: Vec::new(),+ original: Box::new(None),+ };+ d.original = Box::new(Some(d.clone()));+ d+ }++ pub fn title(&self) -> &'static str {+ match self.kind {+ FormFieldKind::Text => "Text Field Properties",+ FormFieldKind::CheckBox => "Check Box Properties",+ FormFieldKind::Radio => "Radio Button Properties",+ FormFieldKind::Combo => "Dropdown Properties",+ FormFieldKind::List => "List Box Properties",+ FormFieldKind::PushButton => "Button Properties",+ FormFieldKind::Signature => "Digital Signature Properties",+ }+ }++ pub(super) fn tabs(&self) -> Vec<(FieldTab, &'static str)> {+ let mut t = vec![(FieldTab::General, "General"), (FieldTab::Appearance, "Appearance"), (FieldTab::Position, "Position")];+ if self.kind != FormFieldKind::Signature {+ t.push((FieldTab::Options, "Options"));+ }+ if matches!(self.kind, FormFieldKind::Text | FormFieldKind::Combo) {+ t.extend([(FieldTab::Format, "Format"), (FieldTab::Validate, "Validate"), (FieldTab::Calculate, "Calculate")]);+ }+ t.push((FieldTab::Actions, "Actions"));+ t+ }++ /// The properties that changed (`None` when nothing did).+ pub fn props(&self) -> Option<FieldProps> {+ let o = self.original.as_ref().as_ref()?;+ let ch = |a: bool, b: bool| (a != b).then_some(a);+ let p = FieldProps {+ name: (self.name.trim() != o.name).then(|| self.name.trim().to_string()),+ tooltip: (self.tooltip != o.tooltip).then(|| self.tooltip.clone()),+ caption: (self.caption != o.caption).then(|| (self.widget, self.caption.clone())),+ read_only: ch(self.read_only, o.read_only),+ required: ch(self.required, o.required),+ multiline: ch(self.multiline, o.multiline),+ max_len: ((self.limit, self.max_len) != (o.limit, o.max_len)).then_some((self.limit && self.max_len > 0).then_some(self.max_len)),+ options: (self.options != o.options).then(|| self.options.clone()),++ export_value: (self.export_value != o.export_value).then(|| (self.widget, self.export_value.clone())),+ font_size: ((self.font_size - o.font_size).abs() > 1e-6).then_some(self.font_size),+ rect: (self.position != o.position).then(|| {+ let [x, y, w, h] = self.position;+ (self.widget, [x, y, x + w.max(4.0), y + h.max(4.0)])+ }),+ rotation: (self.rotation != o.rotation).then_some((self.widget, self.rotation)),+ look: (self.look != o.look).then_some(self.look).flatten(),+ appearance: None,+ check_style: (self.check_style != o.check_style).then_some(self.check_style).flatten(),+ format: (self.format != o.format).then(|| self.format.clone()),+ validate: (self.validate != o.validate).then(|| self.validate.clone()),+ calculate: (self.calculate != o.calculate).then(|| self.calculate.clone()),+ flags: OPTION_FLAGS.iter().filter(|b| (self.flags ^ o.flags) & **b != 0).map(|b| (*b, self.flags & b != 0)).collect(),+ quadding: (self.quadding != o.quadding).then_some(self.quadding),+ locked: ch(self.locked, o.locked),+ actions: (self.actions != o.actions).then(|| self.actions.clone()),+ default_value: (self.default != o.default).then(|| (!self.default.is_empty()).then(|| self.default.clone())),+ };+ (p != FieldProps::default()).then_some(p)+ }+ }++ /// The `/Ff` bits the Options tab edits.+ const OPTION_FLAGS: [u32; 10] = {+ use pdfcraft_engine::field_flags as ff;+ [+ ff::DO_NOT_SCROLL,+ ff::RICH_TEXT,+ ff::PASSWORD,+ ff::FILE_SELECT,+ ff::DO_NOT_SPELL_CHECK,+ ff::COMB,+ ff::SORT,+ ff::EDIT,+ ff::MULTI_SELECT,+ ff::COMMIT_ON_SEL_CHANGE,+ ]+ };diff --cc crates/ui-egui/src/tools/prepare/properties.rsindex 000000000,f922143f6..fd7442070mode 000000,100644..100644--- a/crates/ui-egui/src/tools/prepare/properties.rs+++ b/crates/ui-egui/src/tools/prepare/properties.rs@@@ -1,0 -1,332 +1,335 @@@+ use super::draft::{FieldDraft, FieldTab};+ use super::tabs::{actions_tab, calculate_tab, format_tab, validate_tab};+ use super::{BorderStyle, FieldFont, FormFieldKind, theme, widgets};++ /// A check box for a `/Ff` bit (`inverted`: checked when the bit is clear).+ fn flag_box(ui: &mut egui::Ui, flags: &mut u32, bit: u32, inverted: bool, label: &str) {+ let mut on = (*flags & bit != 0) != inverted;+ if ui.add(widgets::checkbox(&mut on, label)).changed() {+ if on != inverted {+ *flags |= bit;+ } else {+ *flags &= !bit;+ }+ }+ }++ /// Shared PDF `/Q` picker for text and choice-field Options.+ fn alignment(ui: &mut egui::Ui, quadding: &mut i64) {+ ui.label(tl!("Alignment:"));+ craft_ui::ComboBox::from_id_salt("quadding")+ .selected_text(tl!(match (*quadding).clamp(0, 2) {+ 1 => "Center",+ 2 => "Right",+ _ => "Left",+ }))+ .show_ui(ui, |ui| {+ for (q, label) in [(0, tl!("Left")), (1, tl!("Center")), (2, tl!("Right"))] {+ ui.selectable_value(quadding, q, label);+ }+ });+ }++ /// Draw Field Properties; returns (apply, cancel).+ pub(crate) fn body(ui: &mut egui::Ui, d: &mut FieldDraft, t: &crate::theme::Tokens) -> (bool, bool) {+ use crate::widgets;+ ui.set_width(600.0);+ ui.label(egui::RichText::new(tl!(d.title())).font(theme::semibold(18.0)));+ ui.add_space(6.0);+ ui.horizontal_wrapped(|ui| {+ for (tab, label) in d.tabs() {+ if widgets::mode_tab(ui, tl!(label), d.tab == tab).clicked() {+ d.tab = tab;+ }+ }+ });+ ui.separator();+ ui.add_space(6.0);+ let mut enter = false;+ // A locked field keeps its properties until it is unlocked (Acrobat greys them out).+ let was_locked = d.original.as_ref().as_ref().is_some_and(|o| o.locked) && d.locked;+ if was_locked {+ ui.label(egui::RichText::new(tl!("This field is locked. Unlock it to change its properties.")).small().color(t.text_muted));+ }+ ui.scope(|ui| {+ if was_locked {+ ui.disable();+ }+ match d.tab {+ FieldTab::General => {+ egui::Grid::new("field-general").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| {+ let l = ui.label(tl!("Name:"));+ let r = ui.add(crate::widgets::line(&mut d.name).desired_width(340.0)).labelled_by(l.id);+ enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));+ ui.end_row();+ let l = ui.label(tl!("Tooltip:"));+ ui.add(crate::widgets::line(&mut d.tooltip).desired_width(340.0)).labelled_by(l.id);+ ui.end_row();+ });+ ui.add_space(12.0);+ widgets::section_title(ui, tl!("Common Properties"));+ ui.add(widgets::checkbox(&mut d.read_only, tl!("Read Only")));+ ui.add(widgets::checkbox(&mut d.required, tl!("Required")));+ }+ FieldTab::Appearance => {+ egui::Grid::new("field-appearance").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| {+ ui.label(tl!("Font Size:"));+ let mut auto = d.font_size == 0.0;+ ui.horizontal(|ui| {+ if ui.add(widgets::checkbox(&mut auto, tl!("Auto"))).changed() {+ d.font_size = if auto { 0.0 } else { 12.0 };+ }+ ui.add_enabled(+ !auto,+ egui::DragValue::new(&mut d.font_size).range(2.0..=100.0).clamp_existing_to_range(false).speed(0.25).suffix(" pt"),+ );+ });+ ui.end_row();+ if let Some(l) = d.look.as_mut() {+ ui.label(tl!("Font:"));+ craft_ui::ComboBox::from_id_salt("field-font").selected_text(l.font.label()).show_ui(ui, |ui| {+ for f in FieldFont::ALL {+ ui.selectable_value(&mut l.font, f, f.label());+ }+ });+ ui.end_row();+ ui.label(tl!("Text Color:"));+ if let Some(c) = crate::comments::swatch_grid(ui, Some(l.text)) {+ l.text = c;+ }+ ui.end_row();+ }+ });+ if let Some(l) = d.look.as_mut() {+ widgets::section_title(ui, tl!("Borders and Colors"));+ egui::Grid::new("field-borders").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {+ for (index, (label, slot)) in+ [(tl!("Border Color:"), &mut l.border), (tl!("Fill Color:"), &mut l.fill)].into_iter().enumerate()+ {+ ui.label(label);+ ui.push_id(("field-color", index), |ui| {+ ui.horizontal(|ui| {+ let mut none = slot.is_none();+ if ui.add(widgets::checkbox(&mut none, tl!("No color"))).changed() {+ *slot = if none { None } else { Some([0.0; 3]) };+ }+ if let Some(c) = crate::comments::swatch_grid(ui, *slot) {+ *slot = Some(c);+ }+ });+ });+ ui.end_row();+ }+ ui.label(tl!("Line Thickness:"));+ let thick = |w: f64| {+ if w <= 1.0 {+ tl!("Thin")+ } else if w <= 2.0 {+ tl!("Medium")+ } else {+ tl!("Thick")+ }+ };+ craft_ui::ComboBox::from_id_salt("field-width").selected_text(thick(l.width)).show_ui(ui, |ui| {+ for (w, label) in [(1.0, tl!("Thin")), (2.0, tl!("Medium")), (3.0, tl!("Thick"))] {+ ui.selectable_value(&mut l.width, w, label);+ }+ });+ ui.end_row();+ ui.label(tl!("Line Style:"));+ craft_ui::ComboBox::from_id_salt("field-style").selected_text(tl!(l.style.label())).show_ui(ui, |ui| {+ for s in BorderStyle::ALL {+ ui.selectable_value(&mut l.style, s, tl!(s.label()));+ }+ });+ ui.end_row();+ });+ }+ }+ FieldTab::Position => {+ egui::Grid::new("field-position").num_columns(4).spacing([12.0, 10.0]).show(ui, |ui| {+ for (i, label) in [tl!("Left:"), tl!("Bottom:"), tl!("Width:"), tl!("Height:")].into_iter().enumerate() {+ ui.label(label);+ let range = if i < 2 { -14_400.0..=14_400.0 } else { 4.0..=14_400.0 };+ ui.add(egui::DragValue::new(&mut d.position[i]).range(range).speed(0.5).suffix(" pt"));+ if i % 2 == 1 {+ ui.end_row();+ }+ }+ });+ ui.label(egui::RichText::new(tl!("Points from the page's bottom-left corner.")).small().color(t.text_faint));+ ui.add_space(8.0);+ ui.horizontal(|ui| {+ let l = ui.label(tl!("Rotation:"));+ let before = d.rotation;+ craft_ui::ComboBox::from_id_salt("field-rotation")+ .selected_text(format!("{}°", d.rotation))+ .show_ui(ui, |ui| {+ for r in [0, 90, 180, 270] {+ if ui.selectable_value(&mut d.rotation, r, format!("{r}°")).changed() && (before % 180 == 0) != (r % 180 == 0) {+ // Keep the same center. set_props skips its own swap when the rect changed too.+ let [x, y, w, h] = d.position;+ let (cx, cy) = (x + w / 2.0, y + h / 2.0);+ d.position = [cx - h / 2.0, cy - w / 2.0, h, w];+ }+ }+ })+ .response+ .labelled_by(l.id);+ });+ }+ FieldTab::Format => format_tab(ui, d, t),+ FieldTab::Validate => validate_tab(ui, d),+ FieldTab::Calculate => calculate_tab(ui, d, t),+ FieldTab::Actions => actions_tab(ui, d, t),+ FieldTab::Options => match d.kind {+ FormFieldKind::PushButton => {+ ui.horizontal(|ui| {+ let l = ui.label(tl!("Label"));+ ui.add(crate::widgets::line(&mut d.caption).desired_width(340.0)).labelled_by(l.id);+ });+ }+ FormFieldKind::Text => {+ use pdfcraft_engine::field_flags as ff;+ egui::Grid::new("text-options").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {+ alignment(ui, &mut d.quadding);+ ui.end_row();+ let l = ui.label(tl!("Default Value:"));+ ui.add(crate::widgets::line(&mut d.default).desired_width(260.0)).labelled_by(l.id);+ ui.end_row();+ });+ ui.add_space(6.0);+ ui.add(widgets::checkbox(&mut d.multiline, tl!("Multi-line")));+ flag_box(ui, &mut d.flags, ff::DO_NOT_SCROLL, true, tl!("Scroll long text"));+ flag_box(ui, &mut d.flags, ff::RICH_TEXT, false, tl!("Allow Rich Text Formatting"));+ ui.horizontal(|ui| {+ ui.add(widgets::checkbox(&mut d.limit, tl!("Limit of")));+ ui.add_enabled(d.limit, egui::DragValue::new(&mut d.max_len).range(0..=10_000));+ ui.label(tl!("characters"));+ });+ flag_box(ui, &mut d.flags, ff::PASSWORD, false, tl!("Password"));+ flag_box(ui, &mut d.flags, ff::FILE_SELECT, false, tl!("Field is used for file selection"));+ flag_box(ui, &mut d.flags, ff::DO_NOT_SPELL_CHECK, true, tl!("Check spelling"));+ ui.horizontal(|ui| {+ flag_box(ui, &mut d.flags, ff::COMB, false, tl!("Comb of"));+ if d.flags & ff::COMB != 0 {+ d.limit = true;+ d.multiline = false;+ d.flags &= !(ff::PASSWORD | ff::FILE_SELECT);+ if d.max_len == 0 {+ d.max_len = 10;+ }+ }+ ui.add_enabled(d.flags & ff::COMB != 0, egui::DragValue::new(&mut d.max_len).range(1..=500));+ ui.label(tl!("characters"));+ });+ }+ FormFieldKind::CheckBox | FormFieldKind::Radio => {+ use pdfcraft_engine::field_flags as ff;+ let on = d.on_state.clone();- ui.label(crate::i18n::fmt(tl!("Export Value: {on}"), &[("on", &on)]));++ ui.horizontal(|ui| {++ let label = ui.label(tl!("Export value"));++ ui.text_edit_singleline(&mut d.export_value).labelled_by(label.id);++ });+ let mut checked = !d.default.is_empty() && d.default == on;+ let label =+ if d.kind == FormFieldKind::CheckBox { tl!("Check box is checked by default") } else { tl!("Button is checked by default") };+ if ui.add(widgets::checkbox(&mut checked, label)).changed() {+ d.default = if checked { on } else { String::new() };+ }+ if let Some(style) = d.check_style.as_mut() {+ ui.horizontal(|ui| {+ let l = ui.label(tl!(if d.kind == FormFieldKind::CheckBox { "Check Box Style:" } else { "Button Style:" }));+ craft_ui::ComboBox::from_id_salt("check-style")+ .selected_text(tl!(style.label()))+ .show_ui(ui, |ui| {+ for s in pdfcraft_engine::CheckStyle::ALL {+ ui.selectable_value(style, s, tl!(s.label()));+ }+ })+ .response+ .labelled_by(l.id);+ });+ }+ if d.kind == FormFieldKind::Radio {+ flag_box(ui, &mut d.flags, ff::RADIOS_IN_UNISON, false, tl!("Buttons with the same name and value are selected in unison"));+ }+ }+ _ => {+ ui.horizontal(|ui| alignment(ui, &mut d.quadding));+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ let l = ui.label(tl!("Item:"));+ let r = ui.add(crate::widgets::line(&mut d.new_option).desired_width(240.0)).labelled_by(l.id);+ let typed = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));+ if (widgets::pill_button(ui, tl!("Add"), false).clicked() || typed) && !d.new_option.trim().is_empty() {+ d.options.push(d.new_option.trim().to_string());+ d.new_option.clear();+ }+ });+ ui.add_space(6.0);+ widgets::section_title(ui, tl!("Item List"));+ let mut remove = None;+ let mut up = None;+ egui::ScrollArea::vertical().max_height(140.0).show(ui, |ui| {+ for (i, o) in d.options.iter().enumerate() {+ ui.horizontal(|ui| {+ ui.label(o);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if ui.small_button(tl!("Delete")).on_hover_text(crate::i18n::fmt(tl!("Delete {o}"), &[("o", o)])).clicked() {+ remove = Some(i);+ }+ if i > 0 && ui.small_button(tl!("Up")).clicked() {+ up = Some(i);+ }+ });+ });+ }+ });+ if let Some(i) = remove {+ d.options.remove(i);+ }+ if let Some(i) = up {+ d.options.swap(i - 1, i);+ }+ if d.options.is_empty() {+ ui.label(egui::RichText::new(tl!("Add the choices people pick from.")).color(t.text_muted));+ }+ use pdfcraft_engine::field_flags as ff;+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ ui.label(tl!("Default:"));+ let shown = if d.default.is_empty() { tl!("(none)").to_string() } else { d.default.clone() };+ craft_ui::ComboBox::from_id_salt("choice-default").selected_text(shown).show_ui(ui, |ui| {+ ui.selectable_value(&mut d.default, String::new(), tl!("(none)"));+ for o in d.options.clone() {+ ui.selectable_value(&mut d.default, o.clone(), o);+ }+ });+ });+ flag_box(ui, &mut d.flags, ff::SORT, false, tl!("Sort items"));+ if d.kind == FormFieldKind::Combo {+ flag_box(ui, &mut d.flags, ff::EDIT, false, tl!("Allow user to enter custom text"));+ flag_box(ui, &mut d.flags, ff::DO_NOT_SPELL_CHECK, true, tl!("Check spelling"));+ } else {+ flag_box(ui, &mut d.flags, ff::MULTI_SELECT, false, tl!("Multiple selection"));+ }+ flag_box(ui, &mut d.flags, ff::COMMIT_ON_SEL_CHANGE, false, tl!("Commit selected value immediately"));+ }+ },+ }+ });+ ui.add_space(8.0);+ ui.add(widgets::checkbox(&mut d.locked, tl!("Locked")));+ ui.add_space(6.0);+ let (mut apply, mut cancel) = (enter, false);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if widgets::pill_button(ui, tl!("OK"), true).clicked() {+ apply = true;+ }+ if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ cancel = true;+ }+ });+ (apply, cancel)+ }diff --cc crates/ui-egui/tests/it/prepare.rsindex 000000000,6ce727a71..53aa7b973mode 000000,100644..100644--- a/crates/ui-egui/tests/it/prepare.rs+++ b/crates/ui-egui/tests/it/prepare.rs@@@ -1,0 -1,1355 +1,1398 @@@+ //! Prepare a form in the real shell (egui_kittest): field tools, placing, selecting, moving,+ //! Field Properties and deleting.++ use egui::Pos2;+ use egui::accesskit::Role;+ use egui_kittest::Harness;+ use egui_kittest::kittest::{Queryable, by};+ use pdfcraft_engine::field_table::TableColumn;+ use pdfcraft_ui_egui::{Dialog, PdfCraftApp, QuickTool};++ fn harness() -> Harness<'static, PdfCraftApp> {+ harness_with("form.pdf", include_bytes!("../data/form.pdf").to_vec())+ }++ fn harness_with(name: &'static str, bytes: Vec<u8>) -> Harness<'static, PdfCraftApp> {+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| {+ cc.egui_ctx.options_mut(|options| options.warn_on_id_clash = true);+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes(name, None, bytes).unwrap();+ app.set_option("zoom", "150").unwrap();+ app+ });+ crate::support::settle(&mut h);+ h+ }++ /// A point on page 1 at (x, y) points from its top-left.+ fn at(h: &Harness<'static, PdfCraftApp>, x: f32, y: f32) -> Pos2 {+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let k = r.width() / 300.0;+ r.min + egui::vec2(x * k, y * k)+ }++ fn drag(h: &mut Harness<'static, PdfCraftApp>, a: Pos2, b: Pos2) {+ h.hover_at(a);+ h.run_steps(1);+ h.drag_at(a);+ h.run_steps(1);+ for k in 1..=4 {+ h.hover_at(a + (b - a) * (k as f32 / 4.0));+ h.run_steps(1);+ }+ h.drop_at(b);+ h.run_steps(4);+ }++ fn names(h: &Harness<'static, PdfCraftApp>) -> Vec<String> {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().form.iter().map(|f| f.name.clone()).collect()+ }++ fn rect_of(h: &Harness<'static, PdfCraftApp>, name: &str) -> [f64; 4] {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == name).unwrap().widgets[0].rect+ }++ #[test]+ fn placing_moving_editing_and_deleting_a_field() {+ let mut h = harness();+ let before = names(&h).len();+ assert!(h.state_mut().execute("form.add.text"));+ h.run_steps(2);+ h.get_by_label("Prepare a form");+ // Drag out a text field in the empty lower part of the page.+ let (a, b) = (at(&h, 40.0, 300.0), at(&h, 200.0, 322.0));+ drag(&mut h, a, b);+ let all = names(&h);+ assert_eq!(all.len(), before + 1, "{all:?}");+ assert_eq!(all.last().map(String::as_str), Some("Text1"));+ assert_eq!(h.state().quick_tool, QuickTool::Select, "back to Select after one field");+ h.run_steps(2);+ assert_eq!(h.state().views[0].prepare.selected.as_ref().map(|s| s.0.as_str()), Some("Text1"), "the new field is selected");+ let r = rect_of(&h, "Text1");+ assert!((r[2] - r[0] - 160.0).abs() < 2.0 && (r[3] - r[1] - 22.0).abs() < 2.0, "{r:?}");+ // Move it 20 pt right.+ let c = at(&h, 120.0, 311.0);+ let d = c + egui::vec2(at(&h, 20.0, 0.0).x - at(&h, 0.0, 0.0).x, 0.0);+ drag(&mut h, c, d);+ let m = rect_of(&h, "Text1");+ assert!((m[0] - r[0] - 20.0).abs() < 1.5, "moved: {r:?} → {m:?}");+ // Field Properties: rename and make it required (one undo step).+ h.state_mut().execute("form.field.properties");+ h.run_steps(2);+ h.get_by_label("Text Field Properties");+ {+ let d = h.state_mut().field_props.as_mut().expect("open");+ d.name = "email".into();+ d.required = true;+ }+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert!(names(&h).contains(&"email".to_string()));+ {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!(doc.can_undo(), Some("Change field properties"));+ assert!(doc.form.iter().find(|f| f.name == "email").unwrap().has(pdfcraft_engine::field_flags::REQUIRED));+ assert_eq!(s.views[0].prepare.selected.as_ref().map(|s| s.0.as_str()), Some("email"));+ }+ // Delete removes the selected field.+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert_eq!(names(&h).len(), before);+ // A click with the check box tool places a default-size one.+ h.state_mut().execute("form.add.checkbox");+ h.run_steps(1);+ let p = at(&h, 40.0, 250.0);+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ h.run_steps(4);+ let r = rect_of(&h, "Check Box1");+ assert_eq!((r[2] - r[0], r[3] - r[1]), (14.0, 14.0));+ }++ /// The arrow keys nudge the selected field a point, Shift and an arrow ten points (#2608), as they+ /// do for a selected object or image and as dragging it does. One press is one undo step, the page+ /// does not turn with them, and the field stays selected for the next press.+ #[test]+ fn arrow_keys_nudge_the_selected_field_instead_of_turning_the_page() {+ let mut h = harness();+ h.state_mut().execute("form.add.text");+ h.run_steps(1);+ // A click places a default-size text field and selects it.+ let p = at(&h, 40.0, 250.0);+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ h.run_steps(4);+ let id = h.state().views[0].id;+ let name = h.state().views[0].prepare.selected.clone().expect("the placed field is selected").0;+ let near = |a: f64, b: f64| (a - b).abs() < 0.01;+ let before = rect_of(&h, &name);+ h.key_press(egui::Key::ArrowRight);+ h.run_steps(2);+ let right = rect_of(&h, &name);+ assert!(near(right[0], before[0] + 1.0) && near(right[2], before[2] + 1.0), "{before:?} → {right:?}");+ assert!(near(right[2] - right[0], before[2] - before[0]), "moved, not resized");+ assert_eq!(h.state().session.get(id).unwrap().can_undo(), Some("Change field properties"));+ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::ArrowUp);+ h.run_steps(2);+ let up = rect_of(&h, &name);+ assert!(near(up[1], right[1] + 10.0) && near(up[3], right[3] + 10.0), "{right:?} → {up:?}");+ h.key_press(egui::Key::ArrowDown);+ h.run_steps(2);+ h.key_press(egui::Key::ArrowLeft);+ h.run_steps(2);+ let back = rect_of(&h, &name);+ assert!(near(back[0], up[0] - 1.0) && near(back[1], up[1] - 1.0), "{up:?} → {back:?}");+ assert!(h.state().views[0].prepare.selected.is_some(), "it stays selected for the next nudge");+ assert_eq!(h.state().views[0].current, 0, "the arrows moved the field, not the page");+ }++ #[test]+ fn format_validate_and_calculate_tabs() {+ use pdfcraft_engine::form_scripts::{Calculate, Format, Validate};+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Format").click();+ h.run_steps(2);+ h.get_by_label("Select format category:");+ {+ let d = h.state_mut().field_props.as_mut().unwrap();+ d.format = Format::Number { decimals: 2, sep: 0, neg: 0, currency: "$".into(), prepend: true };+ d.validate = Validate::Range { min: Some(0.0), max: None };+ d.calculate = Calculate::Notation("name".into());+ }+ h.run_steps(2);+ h.get_by_label_contains("Example: -$1,234.50");+ h.get_by_label("Calculate").click();+ h.run_steps(2);+ h.get_by_label("Simplified field notation:");+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "city").unwrap().clone();+ assert!(matches!(f.actions.format, Format::Number { decimals: 2, .. }));+ assert_eq!(f.actions.validate, Validate::Range { min: Some(0.0), max: None });+ assert_eq!(f.actions.calculate, Calculate::Notation("name".into()));+ }++ /// Renaming a field in Field Properties renames it in the formulas that read it, in the same undo+ /// step, and says how many changed.+ #[test]+ fn renaming_a_field_says_how_many_calculations_now_use_the_new_name() {+ use pdfcraft_engine::form_scripts::Calculate;+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ let rename = |h: &mut Harness<'static, PdfCraftApp>, from: &str, to: &str| {+ h.state_mut().open_field_props(from, 0);+ h.run_steps(2);+ h.state_mut().field_props.as_mut().expect("open").name = to.into();+ h.get_by_label("OK").click();+ h.run_steps(3);+ };+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.state_mut().field_props.as_mut().expect("open").calculate = Calculate::Notation("name * 2".into());+ h.get_by_label("OK").click();+ h.run_steps(3);+ let calculation = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "city").unwrap().actions.calculate.clone()+ };+ h.state_mut().toast = None;+ rename(&mut h, "name", "full_name");+ assert_eq!(calculation(&h), Calculate::Notation("full_name * 2".into()));+ assert_eq!(h.state().toast.as_ref().map(|t| t.0.as_str()), Some("1 calculation now uses the new name."));+ h.state_mut().toast = None;+ rename(&mut h, "city", "town");+ assert!(names(&h).contains(&"town".to_string()));+ assert_eq!(h.state().toast, None, "no formula reads the calculated field itself");+ h.state_mut().execute("edit.undo");+ h.state_mut().execute("edit.undo");+ h.run_steps(2);+ assert!(names(&h).contains(&"name".to_string()));+ assert_eq!(calculation(&h), Calculate::Notation("name * 2".into()), "undone with the rename");+ }++ #[test]+ fn appearance_tab_restyles_the_field() {+ use pdfcraft_engine::{BorderStyle, FieldFont};+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Appearance").click();+ h.run_steps(2);+ h.get_by_label("Line Style:");+ fn no_grid_id_warning(shape: &egui::Shape) -> bool {+ match shape {+ egui::Shape::Vec(shapes) => shapes.iter().all(no_grid_id_warning),+ egui::Shape::Text(text) => !text.galley.job.text.contains("Grid ID"),+ _ => true,+ }+ }+ // Check egui's actual painted diagnostics, rather than reproducing the ID formula.+ assert!(h.output().shapes.iter().all(|shape| no_grid_id_warning(&shape.shape)), "palette grids must not share an ID");+ let before = h.state().field_props.as_ref().unwrap().look.unwrap();+ assert_eq!(h.get_all_by_label("No color").count(), 2);+ h.get_all_by_label("No color").next().unwrap().click();+ h.run_steps(2);+ let border = h.state().field_props.as_ref().unwrap().look.as_ref().unwrap().border;+ assert_eq!(border, if before.border.is_some() { None } else { Some([0.0; 3]) });+ assert_eq!(h.state().field_props.as_ref().unwrap().look.as_ref().unwrap().fill, before.fill);+ h.get_all_by_label("No color").nth(1).unwrap().click();+ h.run_steps(2);+ let look = h.state().field_props.as_ref().unwrap().look.as_ref().unwrap();+ assert_eq!(look.border, border);+ assert_eq!(look.fill, if before.fill.is_some() { None } else { Some([0.0; 3]) });+ {+ let d = h.state_mut().field_props.as_mut().unwrap();+ let l = d.look.as_mut().expect("a look");+ l.style = BorderStyle::Dashed;+ l.font = FieldFont::Courier;+ l.fill = Some([1.0, 1.0, 0.8]);+ }+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ let l = s.session.get(s.views[0].id).unwrap().field_look("city").unwrap();+ assert_eq!((l.style, l.font, l.fill), (BorderStyle::Dashed, FieldFont::Courier, Some([1.0, 1.0, 0.8])));+ }++ #[test]+ fn appearance_tab_keeps_auto_font_size() {+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Appearance").click();+ h.run_steps(2);+ h.state_mut().field_props.as_mut().unwrap().font_size = 0.0;+ h.run_steps(3);+ assert_eq!(h.state().field_props.as_ref().unwrap().font_size, 0.0, "Auto (0) must survive a frame");+ }++ #[test]+ fn position_tab_rotates_a_field() {+ let mut h = harness();+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ let widget = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "city").unwrap();+ f.widgets[0].clone()+ };+ let before = widget(&h);+ assert_eq!(before.rotation, 0);+ assert!(h.state().field_props.as_ref().unwrap().props().is_none(), "an unchanged draft is not an edit");+ h.get_by_label("Position").click();+ h.run_steps(2);+ h.get_by_label("Rotation:");+ h.state_mut().field_props.as_mut().unwrap().rotation = 90;+ assert!(h.state().field_props.as_ref().unwrap().props().is_some());+ h.get_by_label("OK").click();+ h.run_steps(3);+ let turned = widget(&h);+ assert_eq!(turned.rotation, 90);+ let [x0, y0, x1, y1] = before.rect;+ let (cx, cy, w, ht) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, x1 - x0, y1 - y0);+ let expect = [cx - ht / 2.0, cy - w / 2.0, cx + ht / 2.0, cy + w / 2.0];+ assert!(turned.rect.iter().zip(expect).all(|(a, b)| (a - b).abs() < 0.05), "{:?} vs {expect:?}", turned.rect);+ h.state_mut().execute("edit.undo");+ h.run_steps(3);+ let back = widget(&h);+ assert_eq!(back.rotation, 0);+ assert!(back.rect.iter().zip(before.rect).all(|(a, b)| (a - b).abs() < 0.05), "{:?} vs {:?}", back.rect, before.rect);+ }++ #[test]+ fn options_tab_sets_the_check_box_style() {+ // #94: Check Box Style on the Options tab.+ use pdfcraft_engine::CheckStyle;+ let mut h = harness();+ h.state_mut().apply_edit(pdfcraft_engine::Edit::AddField {+ page: 0,+ rect: [40.0, 300.0, 56.0, 316.0],+ kind: pdfcraft_engine::NewField::CheckBox,+ name: Some("agree".into()),+ });+ h.state_mut().open_field_props("agree", 0);+ h.run_steps(2);+ h.get_by_label("Options").click();+ h.run_steps(2);+ h.get_by_label("Check Box Style:");+ assert_eq!(h.state().field_props.as_ref().unwrap().check_style, Some(CheckStyle::Check));+ h.state_mut().field_props.as_mut().unwrap().check_style = Some(CheckStyle::Cross);+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ assert_eq!(s.session.get(s.views[0].id).unwrap().field_check_style("agree"), Some(CheckStyle::Cross));+ }++ #[test]+ fn button_label_is_editable_without_renaming_the_field() {+ use pdfcraft_engine::{Edit, NewField};+ let mut h = harness();+ // The byte comparisons below must not vary with the save's /ModDate.+ let session = &mut h.state_mut().session;+ *session = std::mem::take(session).with_clock(|| 1_700_000_000);+ h.state_mut().apply_edit(Edit::AddField {+ page: 0,+ rect: [40.0, 300.0, 190.0, 330.0],+ kind: NewField::Button { caption: String::new() },+ name: Some("clear_button".into()),+ });+ h.state_mut().open_field_props("clear_button", 0);+ h.run_steps(2);+ h.get_by_label("Options").click();+ h.run_steps(2);+ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Label").click();+ h.run_steps(1);+ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Label").type_text("Clear Form");+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);++ let app = h.state();+ let id = app.views[0].id;+ let field = app.session.get(id).unwrap().form.iter().find(|f| f.name == "clear_button").unwrap();+ let bytes = app.session.save_bytes(id).unwrap();+ let doc = pdfcraft_cos::Document::open(bytes).unwrap();+ let widget = doc.get(field.widgets[0].obj);+ let mk = doc.resolve(widget.as_dict().unwrap().get(b"MK").unwrap());+ assert_eq!(doc.resolve(mk.as_dict().unwrap().get(b"CA").unwrap()).as_string().unwrap().to_text(), "Clear Form");+ assert_eq!(app.session.get(id).unwrap().can_undo(), Some("Change field properties"));++ // Read the existing label back, and leave both Cancel and an unchanged OK harmless.+ let before = app.session.save_bytes(id).unwrap();+ h.state_mut().open_field_props("clear_button", 0);+ h.run_steps(2);+ h.get_by_label("Options").click();+ h.run_steps(2);+ assert_eq!(h.state().field_props.as_ref().unwrap().caption, "Clear Form");+ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Label").click();+ h.run_steps(1);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Label").type_text("Discard this");+ h.run_steps(2);+ h.get_by_label("Cancel").click();+ h.run_steps(2);+ assert_eq!(h.state().session.save_bytes(id).unwrap(), before);+ h.state_mut().open_field_props("clear_button", 0);+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(2);+ assert_eq!(h.state().session.save_bytes(id).unwrap(), before);+ }++ #[test]+ fn dropdown_alignment_is_editable_and_preserved() {+ choice_alignment(pdfcraft_engine::NewField::Combo { options: vec!["One".into(), "Two".into()], editable: false }, "Center", 1);+ }++ #[test]+ fn list_box_alignment_is_editable_and_preserved() {+ choice_alignment(pdfcraft_engine::NewField::List { options: vec!["One".into(), "Two".into()], multi: true }, "Left", 0);+ }++ fn choice_alignment(kind: pdfcraft_engine::NewField, label: &str, quadding: i64) {+ use pdfcraft_engine::{Edit, FieldProps, FieldValue};+ let mut h = harness();+ h.state_mut().apply_edit(Edit::AddField { page: 0, rect: [40.0, 260.0, 240.0, 310.0], kind, name: Some("aligned_choice".into()) });+ h.state_mut()+ .apply_edit(Edit::SetFieldProps { name: "aligned_choice".into(), props: Box::new(FieldProps { quadding: Some(2), ..Default::default() }) });+ h.state_mut().apply_edit(Edit::SetFieldValue { name: "aligned_choice".into(), value: FieldValue::Choice(vec!["Two".into()]) });+ let field = |h: &Harness<'static, PdfCraftApp>| {+ let app = h.state();+ app.session.get(app.views[0].id).unwrap().form.iter().find(|f| f.name == "aligned_choice").unwrap().clone()+ };+ let original = field(&h);+ h.state_mut().open_field_props("aligned_choice", 0);+ h.run_steps(2);+ h.get_by_label("Options").click();+ h.run_steps(2);+ h.get_by_label("Alignment:");+ // The imported right alignment is displayed and unchanged until a choice is made.+ h.get_by_value("Right").click();+ h.run_steps(2);+ h.get_by_label(label).click();+ h.run_steps(2);+ h.get_by_label("Cancel").click();+ h.run_steps(2);+ assert_eq!(field(&h).quadding, 2, "cancel keeps the existing /Q");+ h.state_mut().open_field_props("aligned_choice", 0);+ h.run_steps(2);+ h.get_by_label("Options").click();+ h.run_steps(2);+ h.get_by_value("Right").click();+ h.run_steps(2);+ h.get_by_label(label).click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ let changed = field(&h);+ assert_eq!(changed.quadding, quadding);+ assert_eq!((changed.options, changed.value, changed.flags), (original.options, original.value, original.flags));+ let app = h.state();+ let id = app.views[0].id;+ assert_eq!(app.session.get(id).unwrap().can_undo(), Some("Change field properties"));+ let bytes = app.session.save_bytes(id).unwrap();+ let mut reopened = pdfcraft_engine::Session::new();+ let reopened_id = reopened.open("saved.pdf", None, bytes, None).unwrap();+ assert_eq!(reopened.get(reopened_id).unwrap().form.iter().find(|f| f.name == "aligned_choice").unwrap().quadding, quadding);+ h.state_mut().execute("edit.undo");+ h.run_steps(3);+ assert_eq!(field(&h).quadding, 2);+ h.state_mut().execute("edit.redo");+ h.run_steps(3);+ assert_eq!(field(&h).quadding, quadding);+ }++ #[test]+ fn options_tab_sets_flags_alignment_and_defaults() {+ use pdfcraft_engine::field_flags as ff;+ let mut h = harness();+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Options").click();+ h.run_steps(2);+ h.get_by_label("Check spelling").click();+ h.get_by_label("Password").click();+ h.run_steps(1);+ {+ let d = h.state_mut().field_props.as_mut().unwrap();+ d.quadding = 2;+ d.default = "Paris".into();+ }+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "city").cloned().unwrap();+ assert!(f.has(ff::PASSWORD) && f.has(ff::DO_NOT_SPELL_CHECK), "{:b}", f.flags);+ assert_eq!((f.quadding, f.default.clone()), (2, vec!["Paris".to_string()]));+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Change field properties"));+ }++ #[test]+ fn the_fields_panel_orders_tabs_manually() {+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.state_mut().set_option("panel", "fields").unwrap();+ h.run_steps(3);+ let order = |h: &Harness<'static, PdfCraftApp>| -> Vec<String> {+ let s = h.state();+ let form = &s.session.get(s.views[0].id).unwrap().form;+ let mut v: Vec<(usize, String)> = form.iter().filter_map(|f| f.widgets.iter().map(|w| w.tab).min().map(|t| (t, f.name.clone()))).collect();+ v.sort();+ v.into_iter().map(|x| x.1).collect()+ };+ let before = order(&h);+ assert!(before.len() >= 2);+ let second = before[1].clone();+ h.get_by_label(&format!("Earlier in tab order: {second}")).click();+ h.run_steps(3);+ let after = order(&h);+ assert_eq!(after[0], second, "{before:?} → {after:?}");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Set tab order"));+ }++ #[test]+ fn duplicating_a_field_onto_every_page() {+ let mut h = harness();+ h.state_mut().apply_edit(pdfcraft_engine::Edit::InsertBlankPage { at: 1, width: 300.0, height: 400.0 });+ h.state_mut().execute("form.prepare");+ h.run_steps(3);+ let (n, p) = {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "city").unwrap();+ (doc.info.pages.len(), pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen").center())+ };+ assert!(n >= 2, "the fixture has {n} pages");+ h.hover_at(p);+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });+ h.run_steps(3);+ h.get_by_label("Duplicate…").click();+ h.run_steps(2);+ h.get_by_label("Duplicate Field");+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "city").unwrap();+ let mut pages: Vec<usize> = f.widgets.iter().filter_map(|w| w.page).collect();+ pages.sort();+ assert_eq!(pages, (0..n).collect::<Vec<_>>());+ assert_eq!(doc.can_undo(), Some("Duplicate field"));+ }++ #[test]+ fn aligning_distributing_and_sizing_several_fields() {+ use pdfcraft_ui_egui::prepare::{Arrange, arrange};+ let mut h = harness();+ for (name, x, y, w) in [("a", 20.0, 300.0, 60.0), ("b", 120.0, 280.0, 80.0), ("c", 260.0, 260.0, 30.0)] {+ h.state_mut().apply_edit(pdfcraft_engine::Edit::AddField {+ page: 0,+ rect: [x, y, x + w, y + 20.0],+ kind: pdfcraft_engine::NewField::Text { multiline: false },+ name: Some(name.into()),+ });+ }+ h.run_steps(2);+ let form = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(h.state().views[0].id).unwrap().form.as_ref().clone();+ let rect = |h: &Harness<'static, PdfCraftApp>, n: &str| form(h).iter().find(|f| f.name == n).unwrap().widgets[0].rect;+ let a = ("a".to_string(), 0);+ let others = vec![("b".to_string(), 0), ("c".to_string(), 0)];+ // Align tops with a.+ let e = arrange(&form(&h), &a, &others, Arrange::AlignTop).unwrap();+ h.state_mut().apply_edit(e);+ assert!(["b", "c"].iter().all(|n| rect(&h, n)[3] == 320.0));+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Align fields"));+ // Distribute horizontally: equal gaps between a, b and c.+ let e = arrange(&form(&h), &a, &others, Arrange::DistributeH).unwrap();+ h.state_mut().apply_edit(e);+ let (ra, rb, rc) = (rect(&h, "a"), rect(&h, "b"), rect(&h, "c"));+ assert!(((rb[0] - ra[2]) - (rc[0] - rb[2])).abs() < 1e-6, "{ra:?} {rb:?} {rc:?}");+ // Same width as a.+ let e = arrange(&form(&h), &a, &others, Arrange::SameWidth).unwrap();+ h.state_mut().apply_edit(e);+ assert!(["b", "c"].iter().all(|n| (rect(&h, n)[2] - rect(&h, n)[0] - 60.0).abs() < 1e-6));+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Match field sizes"));+ assert!(arrange(&form(&h), &a, &[("b".into(), 0)], Arrange::DistributeV).is_none(), "distributing needs three");+ }++ #[test]+ fn deleting_several_selected_fields_and_detecting_fields_from_the_panel() {+ let mut h = harness();+ for (name, x) in [("a", 20.0), ("b", 120.0), ("c", 220.0)] {+ h.state_mut().apply_edit(pdfcraft_engine::Edit::AddField {+ page: 0,+ rect: [x, 300.0, x + 60.0, 320.0],+ kind: pdfcraft_engine::NewField::Text { multiline: false },+ name: Some(name.into()),+ });+ }+ assert!(h.state_mut().execute("form.prepare"));+ h.run_steps(2);+ // #93: field detection is in the panel, not only run when a form has no fields.+ h.get_by_label("Detect form fields");+ // #95: Delete removes every selected field, as one undoable step.+ {+ let p = &mut h.state_mut().views[0].prepare;+ p.selected = Some(("a".into(), 0));+ p.also = vec![("b".into(), 0), ("c".into(), 0)];+ }+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ let left = names(&h);+ assert!(!["a", "b", "c"].iter().any(|n| left.iter().any(|l| l == n)), "{left:?}");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Delete 3 fields"));+ assert!(h.state().views[0].prepare.selected.is_none() && h.state().views[0].prepare.also.is_empty());+ }++ #[test]+ fn preview_fills_the_form_and_locked_fields_keep_their_properties() {+ let mut h = harness();+ assert!(h.state_mut().execute("form.prepare"));+ h.run_steps(2);+ assert!(h.state().is_preparing());+ h.get_by_label("Preview").click();+ h.run_steps(2);+ assert!(!h.state().is_preparing(), "Preview fills the form");+ h.get_by_label("Edit fields").click();+ h.run_steps(2);+ assert!(h.state().is_preparing());+ // Lock a field: its properties are then greyed out until unlocked.+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Locked").click();+ h.run_steps(1);+ h.get_by_label("OK").click();+ h.run_steps(3);+ let locked = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "city").unwrap().locked()+ };+ assert!(locked(&h));+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label_contains("This field is locked");+ h.get_by_label("Locked").click();+ h.run_steps(1);+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert!(!locked(&h));+ }++ #[test]+ fn image_fields_take_a_picture_when_clicked() {+ let mut h = harness();+ assert!(h.state_mut().execute("form.add.image"));+ h.run_steps(2);+ let (a, b) = (at(&h, 40.0, 220.0), at(&h, 140.0, 290.0));+ drag(&mut h, a, b);+ assert_eq!(names(&h).last().map(String::as_str), Some("Image1"));+ // A picture to choose (the picker is bypassed in tests).+ let path = std::env::temp_dir().join(format!("pdfcraft-image-field-{}.png", std::process::id()));+ image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])).save(&path).unwrap();+ h.state_mut().save_override = Some(path.to_string_lossy().into_owned());+ // Fill it in as a reader would.+ h.get_by_label("Preview").click();+ h.run_steps(2);+ let c = at(&h, 90.0, 255.0);+ h.hover_at(c);+ h.run_steps(1);+ h.drag_at(c);+ h.run_steps(1);+ h.drop_at(c);+ h.run_steps(4);+ let s = h.state();+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Set the image of Image1"));+ }++ #[test]+ fn actions_tab_adds_and_removes_actions() {+ use pdfcraft_engine::{FieldAction, FieldTrigger};+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Actions").click();+ h.run_steps(2);+ h.get_by_label("Select Trigger:");+ h.get_by_label("No actions");+ {+ let d = h.state_mut().field_props.as_mut().unwrap();+ d.new_action.trigger = FieldTrigger::OnBlur;+ d.new_action.kind = 1;+ d.new_action.text = "https://example.org".into();+ }+ h.run_steps(3);+ h.get_by_label("Add").click();+ h.run_steps(2);+ h.get_by_label("Open a web link: https://example.org");+ {+ let d = h.state_mut().field_props.as_mut().unwrap();+ d.new_action.trigger = FieldTrigger::MouseUp;+ d.new_action.kind = 0;+ d.new_action.text = "app.alert('x')".into();+ }+ h.run_steps(3);+ h.get_by_label("Add").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ let acts = s.session.get(s.views[0].id).unwrap().field_actions("city");+ assert_eq!(+ acts,+ [+ (FieldTrigger::MouseUp, FieldAction::JavaScript("app.alert('x')".into())),+ (FieldTrigger::OnBlur, FieldAction::Uri("https://example.org".into()))+ ]+ );+ }++ #[test]+ fn actions_tab_edits_the_script_of_an_existing_action() {+ use pdfcraft_engine::{FieldAction, FieldTrigger};+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ let script = "if (event.value > 10) {\n app.alert('Too many');\n}";+ let actions = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().field_actions("city")+ };+ let open = |h: &mut Harness<'static, PdfCraftApp>| {+ h.state_mut().open_field_props("city", 0);+ h.run_steps(2);+ h.get_by_label("Actions").click();+ h.run_steps(2);+ };+ // A script on Mouse Up and a link on Blur, saved with the field.+ open(&mut h);+ for (trigger, kind, text) in [(FieldTrigger::MouseUp, 0, script), (FieldTrigger::OnBlur, 1, "https://example.org")] {+ let d = h.state_mut().field_props.as_mut().unwrap();+ d.new_action = pdfcraft_ui_egui::prepare::ActionDraft { trigger, kind, text: text.into() };+ h.run_steps(3);+ h.get_by_label("Add").click();+ h.run_steps(2);+ }+ h.get_by_label("OK").click();+ h.run_steps(3);+ let saved = actions(&h);+ // Edit shows the script exactly as stored; Discard leaves everything as it was.+ open(&mut h);+ h.get_all_by_label("Edit").last().unwrap().click();+ h.run_steps(2);+ h.get_by_label("Edit Action");+ assert_eq!(h.state().field_props.as_ref().unwrap().new_action.text, script);+ h.state_mut().field_props.as_mut().unwrap().new_action.text = "app.alert('changed');".into();+ h.run_steps(2);+ h.get_by_label("Discard").click();+ h.run_steps(2);+ h.get_by_label("Add an Action");+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert_eq!(actions(&h), saved);+ // Update replaces that script only: same trigger, the link untouched.+ open(&mut h);+ h.get_all_by_label("Edit").last().unwrap().click();+ h.run_steps(2);+ h.state_mut().field_props.as_mut().unwrap().new_action.text = "app.alert('changed');".into();+ h.run_steps(2);+ h.get_by_label("Update").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert_eq!(+ actions(&h),+ [+ (FieldTrigger::MouseUp, FieldAction::JavaScript("app.alert('changed');".into())),+ (FieldTrigger::OnBlur, FieldAction::Uri("https://example.org".into()))+ ]+ );+ }++ /// One page with a push button "go": Mouse Up runs a script with a link chained after it, On Blur+ /// runs another script.+ fn chained_action_fixture() -> Vec<u8> {+ pdf_of(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) >> >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",+ "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",+ "<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (go) /Rect [20 300 100 320] /P 3 0 R /A 5 0 R /AA << /Bl << /S /JavaScript /JS (this.dirty = true;) >> >> >>",+ "<< /S /JavaScript /JS (app.alert\\(1\\);) /Next 6 0 R >>",+ "<< /S /URI /URI (https://example.org) >>",+ ])+ }++ /// A PDF of `objs`, numbered from 1, with the first as its catalog.+ fn pdf_of(objs: &[&str]) -> Vec<u8> {+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offs = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offs.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let x = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offs {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());+ out+ }++ /// Two one-button radio groups placed apart on page 1: "Group1" (export `A`) and "Group2" (`B`).+ fn two_radio_groups_fixture() -> Vec<u8> {+ let widget = |parent: u32, x: u32, state: &str| {+ format!(+ "<< /Type /Annot /Subtype /Widget /Parent {parent} 0 R /Rect [{x} 300 {} 314] /P 3 0 R /AS /Off /AP << /N << /{state} 8 0 R /Off 8 0 R >> >> >>",+ x + 14+ )+ };+ let (a, b) = (widget(4, 40, "A"), widget(6, 120, "B"));+ pdf_of(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] >> >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 7 0 R] >>",+ "<< /FT /Btn /Ff 49152 /T (Group1) /Kids [5 0 R] >>",+ &a,+ "<< /FT /Btn /Ff 49152 /T (Group2) /Kids [7 0 R] >>",+ &b,+ "<< /Length 3 >>\nstream\n0 g\nendstream",+ ])+ }++ /// #4949: renaming a radio button to another group's name moves it into that group, after the+ /// group's own buttons. The moved button stays the selected one, so a nudge moves it and not the+ /// group's first button, and undo and redo take the rename and the nudge back and forth.+ #[test]+ fn a_radio_button_joining_a_group_by_name_stays_selected() {+ let mut h = harness_with("radios.pdf", two_radio_groups_fixture());+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ let rects = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ let form = &s.session.get(s.views[0].id).unwrap().form;+ form.iter().flat_map(|f| f.widgets.iter().map(|w| w.rect)).collect::<Vec<_>>()+ };+ let start = rects(&h);+ h.state_mut().open_field_props("Group2", 0);+ h.run_steps(2);+ h.state_mut().field_props.as_mut().expect("open").name = "Group1".into();+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert_eq!(names(&h), ["Group1"]);+ assert_eq!(h.state().views[0].prepare.selected, Some(("Group1".to_string(), 1)), "the moved button");+ h.key_press(egui::Key::ArrowRight);+ h.run_steps(2);+ let nudged = rects(&h);+ assert_eq!(nudged[0], start[0], "the group's own button stays");+ assert!((nudged[1][0] - start[1][0] - 1.0).abs() < 0.01, "{:?} → {:?}", start[1], nudged[1]);+ h.state_mut().execute("edit.undo");+ h.state_mut().execute("edit.undo");+ h.run_steps(2);+ assert_eq!(names(&h), ["Group1", "Group2"]);+ assert_eq!(rects(&h), start);+ h.state_mut().execute("edit.redo");+ h.state_mut().execute("edit.redo");+ h.run_steps(2);+ assert_eq!(names(&h), ["Group1"]);+ assert_eq!(rects(&h), nudged);+ }++ #[test]+ fn actions_tab_shows_a_chain_and_keeps_it_when_the_first_action_is_replaced() {+ use egui_kittest::kittest::NodeT;+ use pdfcraft_engine::FieldTrigger;+ let mut h = harness_with("chain.pdf", chained_action_fixture());+ h.state_mut().execute("form.prepare");+ h.run_steps(2);+ let open = |h: &mut Harness<'static, PdfCraftApp>| {+ h.state_mut().open_field_props("go", 0);+ h.run_steps(2);+ h.get_by_label("Actions").click();+ h.run_steps(2);+ };+ open(&mut h);+ h.get_by_label("Run a JavaScript, then 1 more action");+ // The menu bar's Edit menu and the Edit tab come first; the rows' follow (Mouse Up, On Blur).+ assert_eq!(h.get_all_by_label("Edit").count(), 4);+ h.get_all_by_label("Edit").nth(2).unwrap().click();+ h.run_steps(2);+ assert_eq!(h.state().field_props.as_ref().unwrap().editing, Some(FieldTrigger::MouseUp));+ // While one script is open, no other Edit can overwrite it.+ assert!(h.get_all_by_label("Edit").skip(2).all(|n| n.accesskit_node().is_disabled()));+ h.get_by_label("Discard").click();+ h.run_steps(2);+ assert!(h.get_all_by_label("Edit").skip(2).all(|n| !n.accesskit_node().is_disabled()));+ // Replace the Mouse Up script with a link: the chained link stays after it.+ {+ let d = h.state_mut().field_props.as_mut().unwrap();+ d.actions.retain(|(t, _)| *t != FieldTrigger::MouseUp);+ d.new_action = pdfcraft_ui_egui::prepare::ActionDraft { trigger: FieldTrigger::MouseUp, kind: 1, text: "https://example.com".into() };+ }+ h.run_steps(3);+ h.get_by_label("Add").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ open(&mut h);+ h.get_by_label("Open a web link: https://example.com, then 1 more action");+ }++ /// Text field table: pick the tool and drag out an area in the empty lower part of page 1, 200 by+ /// 120 points from (40, 240) as displayed. The table's window opens for it.+ fn draw_table(h: &mut Harness<'static, PdfCraftApp>) {+ assert!(h.state_mut().execute("form.add.text_table"));+ h.run_steps(2);+ let (a, b) = (at(h, 40.0, 240.0), at(h, 240.0, 360.0));+ drag(h, a, b);+ assert_eq!(h.state().dialog, Some(Dialog::FieldTable));+ }++ fn columns(patterns: &[(&str, f64)]) -> Vec<TableColumn> {+ patterns.iter().map(|(p, w)| TableColumn { pattern: (*p).to_owned(), width: *w }).collect()+ }++ #[test]+ fn a_text_field_table_is_drawn_set_up_and_added_in_one_step() {+ let mut h = harness();+ let before = names(&h);+ draw_table(&mut h);+ assert_eq!(h.state().quick_tool, QuickTool::Select, "back to Select once the area is drawn");+ {+ let s = h.state_mut();+ let id = s.views[0].id;+ let d = s.field_table_draft.as_mut().expect("the table's window is open");+ assert_eq!((d.doc, d.page), (id, 0));+ let r = d.table.rect;+ assert!([40.0, 240.0, 240.0, 360.0].iter().zip(r).all(|(w, g)| (w - g).abs() < 0.5), "drawn as displayed: {r:?}");+ d.table.rows = 2;+ d.table.columns = columns(&[("desc_N", 3.0), ("price_N", 1.0)]);+ }+ h.run_steps(2);+ h.get_by_label("Add fields").click();+ h.run_steps(3);+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some()), (None, false), "added, the window closes");+ let added: Vec<_> = names(&h).into_iter().filter(|n| !before.contains(n)).collect();+ assert_eq!(added, ["desc_1", "price_1", "desc_2", "price_2"]);+ // 150 and 50 points wide, 60 high, the first row at the top: user space has y up from 400.+ let r = rect_of(&h, "desc_1");+ assert!([40.0, 100.0, 190.0, 160.0].iter().zip(r).all(|(w, g)| (w - g).abs() < 0.5), "{r:?}");+ let r = rect_of(&h, "price_2");+ assert!([190.0, 40.0, 240.0, 100.0].iter().zip(r).all(|(w, g)| (w - g).abs() < 0.5), "{r:?}");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Add text field table"));+ h.state_mut().execute("edit.undo");+ h.run_steps(2);+ assert_eq!(names(&h), before, "one undo takes the whole table back");+ }++ #[test]+ fn a_table_whose_names_are_taken_stays_open_saying_so() {+ let mut h = harness();+ draw_table(&mut h);+ h.get_by_label("Add fields").click();+ h.run_steps(3);+ assert!(names(&h).contains(&"Table1_4".to_owned()), "{:?}", names(&h));+ // The next table takes the next free names on its own.+ draw_table(&mut h);+ assert_eq!(h.state().field_table_draft.as_ref().unwrap().table.columns[0].pattern, "Table2_N");+ // Named like the first, it can't be added: the window says why and keeps what was set up.+ h.state_mut().field_table_draft.as_mut().unwrap().table.columns[0].pattern = "Table1_N".into();+ h.run_steps(2);+ let count = names(&h).len();+ h.get_by_label("a field named \"Table1_1\" already exists");+ h.get_by_label("Add fields").click();+ h.run_steps(3);+ assert_eq!(names(&h).len(), count, "nothing added");+ assert_eq!(h.state().dialog, Some(Dialog::FieldTable), "still open");+ // Escape closes it, adding nothing.+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some(), names(&h).len()), (None, false, count));+ }++ /// Enter commits a number being typed. It used to add the table there and then, before the rest+ /// of it was set up.+ #[test]+ fn enter_in_a_number_field_does_not_add_the_table() {+ let mut h = harness();+ let before = names(&h).len();+ draw_table(&mut h);+ let rows = h.query_all(by().role(Role::SpinButton)).next().map(|n| n.rect()).expect("the Rows field");+ h.hover_at(rows.center());+ h.drag_at(rows.center());+ h.run_steps(1);+ h.drop_at(rows.center());+ h.run_steps(2);+ h.key_press(egui::Key::Backspace);+ h.event(egui::Event::Text("6".into()));+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert_eq!(names(&h).len(), before, "nothing added");+ assert_eq!(h.state().field_table_draft.as_ref().map(|d| d.table.rows), Some(6), "the number is in, the window open");+ }++ /// With 26 or more columns each pair of columns has less than twice the least share a divider+ /// keeps, and dragging one panicked in `f64::clamp`.+ #[test]+ fn dragging_a_column_divider_between_many_columns() {+ let mut h = harness();+ draw_table(&mut h);+ h.state_mut().field_table_draft.as_mut().unwrap().table.columns = columns(&[("c{c}_N", 1.0); 30]);+ h.run_steps(2);+ let (above, below) = (h.get_by_label("Distribute evenly").rect(), h.get_by_label("Field names").rect());+ let p = egui::pos2(above.center().x - 120.0, (above.bottom() + below.top()) / 2.0);+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ for dx in [-10.0, -20.0] {+ h.hover_at(p + egui::vec2(dx, 0.0));+ h.run_steps(1);+ }+ h.drop_at(p + egui::vec2(-20.0, 0.0));+ h.run_steps(2);+ let widths: Vec<f64> = h.state().field_table_draft.as_ref().unwrap().table.columns.iter().map(|c| c.width).collect();+ assert!(widths.iter().any(|w| (w - 1.0).abs() > 1e-9), "a divider moved: {widths:?}");+ assert!((widths.iter().sum::<f64>() - 30.0).abs() < 1e-9 && widths.iter().all(|w| *w > 0.0), "{widths:?}");+ }++ #[test]+ fn the_table_window_closes_when_its_document_is_left() {+ let mut h = harness();+ let blank = pdfcraft_engine::Session::new().create_blank(300.0, 400.0, 1).unwrap().to_vec();+ h.state_mut().open_bytes("other.pdf", None, blank).unwrap();+ h.state_mut().active = Some(0);+ h.run_steps(4);+ let before = names(&h).len();+ draw_table(&mut h);+ // The other document's tab is still in reach of the pointer: choosing it closes the window.+ let tab = h.get_all_by_label("other.pdf").next().map(|n| n.rect()).expect("its tab");+ h.hover_at(tab.center());+ h.run_steps(1);+ h.drag_at(tab.center());+ h.run_steps(1);+ h.drop_at(tab.center());+ h.run_steps(3);+ assert_eq!(h.state().active, Some(1));+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some()), (None, false));+ h.state_mut().active = Some(0);+ h.run_steps(2);+ assert_eq!(names(&h).len(), before, "nothing added to either document");+ // So does leaving Prepare a form.+ draw_table(&mut h);+ h.state_mut().left_open = false;+ h.run_steps(2);+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some()), (None, false));+ }++ /// With its panel closed after the tool was picked, the form is still prepared and a table can be+ /// drawn: its window opens Prepare a form again, which it belongs to. Drawing sends the tool back+ /// to Select, so the window used to close itself at once, nothing being prepared any more.+ #[test]+ fn a_table_drawn_with_the_panel_closed_opens_it_again() {+ let mut h = harness();+ let before = names(&h).len();+ assert!(h.state_mut().execute("form.add.text_table"));+ h.run_steps(2);+ h.state_mut().left_open = false;+ h.run_steps(2);+ assert!(h.state().is_preparing(), "the picked tool keeps the form prepared");+ let (a, b) = (at(&h, 40.0, 240.0), at(&h, 240.0, 360.0));+ drag(&mut h, a, b);+ h.run_steps(3);+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some()), (Some(Dialog::FieldTable), true), "the window stays open");+ assert!(h.state().left_open && h.state().is_preparing(), "Prepare a form is open again");+ h.get_by_label("Add fields").click();+ h.run_steps(3);+ assert!(names(&h).len() > before, "the table is added");+ }++ /// The window belongs to the page as it was when it opened: rotated (or moved, deleted, undone)+ /// under it, the page would put the area the table was set up for somewhere else.+ #[test]+ fn the_table_window_closes_when_the_document_changes_under_it() {+ let mut h = harness();+ let before = names(&h);+ draw_table(&mut h);+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }));+ h.run_steps(2);+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some()), (None, false), "closed by the rotation");+ assert_eq!(names(&h), before, "nothing added");+ }++ /// Escape in a name field leaves the field, as it does in any field; it closed the window too,+ /// and the column setup with it.+ #[test]+ fn escape_in_a_name_field_leaves_the_field_not_the_table() {+ let mut h = harness();+ draw_table(&mut h);+ // The app's own text boxes (zoom, page number) are inputs too: take the one in the window.+ let field = h.get_by_role_and_label(Role::TextInput, "Column 1").rect();+ h.hover_at(field.center());+ h.drag_at(field.center());+ h.run_steps(1);+ h.drop_at(field.center());+ h.run_steps(2);+ h.event(egui::Event::Text("x".into()));+ h.run_steps(1);+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert_eq!(h.state().dialog, Some(Dialog::FieldTable), "still open");+ assert_eq!(h.state().field_table_draft.as_ref().map(|d| d.table.columns[0].pattern.as_str()), Some("Table1_Nx"), "what was typed stays");+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert_eq!((h.state().dialog, h.state().field_table_draft.is_some()), (None, false), "a second Escape closes it");+ }++ /// A click puts the default 180 × 110 table's corner at the pointer; near the page's edges it is+ /// moved in so that all of it is on the page (here 5 pt from the right, 100 pt from the bottom).+ #[test]+ fn a_table_clicked_near_the_page_edge_stays_on_the_page() {+ let mut h = harness();+ assert!(h.state_mut().execute("form.add.text_table"));+ h.run_steps(2);+ let p = at(&h, 295.0, 300.0);+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ h.run_steps(3);+ let r = h.state().field_table_draft.as_ref().expect("the table's window").table.rect;+ assert!([120.0, 290.0, 300.0, 400.0].iter().zip(r).all(|(w, g)| (w - g).abs() < 0.5), "on the 300 × 400 page: {r:?}");+ }++ /// Prepare a form ▸ Calculation order opens as a page of its own, with the form still being+ /// prepared, says when nothing calculates, and Back returns to Prepare a form.+ #[test]+ fn the_calculation_order_is_a_page_of_prepare_a_form() {+ use pdfcraft_ui_egui::LeftPanel;+ let mut h = harness();+ h.state_mut().execute("form.prepare");+ h.run_steps(3);+ assert!(h.query_by_label("Field list").is_some());+ h.get_by_label("Calculation order").click();+ h.run_steps(3);+ assert_eq!(h.state().left, LeftPanel::CalculationOrder);+ assert!(h.state().is_preparing(), "the fields stay editable, so a row can select one");+ // The page replaces the Prepare a form tools.+ assert!(h.query_by_label("Field list").is_none());+ assert!(h.query_by_label_contains("No field in this form calculates its value yet").is_some());+ h.get_by_label("Back to Prepare a form").click();+ h.run_steps(3);+ assert_eq!(h.state().left, LeftPanel::Tool("form"));+ assert!(h.query_by_label("Field list").is_some());+ assert!(h.query_by_label("Back to Prepare a form").is_none());+ // Opened from Preview, the page edits the fields again.+ h.get_by_label("Preview").click();+ h.run_steps(3);+ assert!(h.state().form_preview);+ h.get_by_label("Calculation order").click();+ h.run_steps(3);+ assert!(h.state().is_preparing() && !h.state().form_preview, "Preview ends, so a row can select its field");+ // Opened (from ⌘K) while the page grid shows, the grid closes and the page shows.+ h.state_mut().execute("page.organize");+ h.run_steps(3);+ assert!(h.state().views[0].organize);+ h.state_mut().execute("form.calculation_order");+ h.run_steps(3);+ assert!(!h.state().views[0].organize);+ assert!(h.query_by_label_contains("No field in this form calculates its value yet").is_some());+ }++ /// Prepare a form ▸ Calculation order: a card says which field shows an old value and why, each+ /// row shows its field's value as the field does, the selected field's arrows, Alt+↑ and a drag+ /// move it, Fix order puts each field after the fields it reads and the card's Undo takes that+ /// back, every change is one undo step, and a row selects its field.+ #[test]+ fn the_calculation_order_is_moved_dragged_and_fixed() {+ use egui::{Key, Modifiers};+ use pdfcraft_engine::form_scripts::{CalcOp, Calculate, Format};+ use pdfcraft_engine::{Edit, FieldProps, FieldValue, NewField};+ let mut h = harness();+ for (i, name) in ["qty", "sub", "total", "other"].into_iter().enumerate() {+ let y = 200.0 + 30.0 * i as f64;+ let kind = NewField::Text { multiline: false };+ h.state_mut().apply_edit(Edit::AddField { page: 0, rect: [20.0, y, 120.0, y + 20.0], kind, name: Some(name.into()) });+ }+ let calculate = |name: &str, c: Calculate| Edit::SetFieldProps {+ name: name.into(),+ props: Box::new(FieldProps { calculate: Some(c), ..Default::default() }),+ };+ // Defined backwards: total, which reads sub, calculates first.+ h.state_mut().apply_edit(calculate("total", Calculate::Simple { op: CalcOp::Sum, fields: vec!["sub".into()] }));+ h.state_mut().apply_edit(calculate("sub", Calculate::Notation("qty * 2".into())));+ h.state_mut().apply_edit(calculate("other", Calculate::Notation("qty + 1".into())));+ // other shows its value as currency.+ let currency = Format::Number { decimals: 2, sep: 0, neg: 0, currency: "$".into(), prepend: true };+ h.state_mut()+ .apply_edit(Edit::SetFieldProps { name: "other".into(), props: Box::new(FieldProps { format: Some(currency), ..Default::default() }) });+ h.state_mut().apply_edit(Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("3".into()) });+ h.state_mut().execute("form.prepare");+ h.run_steps(3);+ h.get_by_label("Calculation order").click();+ h.run_steps(3);+ let order = |h: &Harness<'static, PdfCraftApp>| -> Vec<String> {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().calculation_order().fields.into_iter().map(|f| f.name).collect()+ };+ let undo_label = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(h.state().views[0].id).unwrap().can_undo().map(str::to_owned);+ assert_eq!(order(&h), ["total", "sub", "other"]);+ // The card says what is wrong, and each row shows its value as the field does: total+ // calculated before sub, so it still has sub's old value.+ assert!(h.query_by_label("1 field shows an old value").is_some());+ assert!(h.query_by_label("total calculates before sub, which it reads.").is_some());+ for row in ["1. total: 0", "2. sub: 6", "3. other: $4.00"] {+ assert!(h.query_by_label(row).is_some(), "{row}");+ }+ // The selected field's arrows move it.+ assert!(h.query_by_label("Later in calculation order: total").is_none(), "arrows only on the selected field or the one pointed at");+ h.get_by_label("1. total: 0").click();+ h.run_steps(3);+ h.get_by_label("Later in calculation order: total").click();+ h.run_steps(3);+ assert_eq!(order(&h), ["sub", "total", "other"]);+ assert_eq!(undo_label(&h).as_deref(), Some("Set calculation order"));+ // Alt+↑ moves it back.+ h.key_press_modifiers(Modifiers::ALT, Key::ArrowUp);+ h.run_steps(3);+ assert_eq!(order(&h), ["total", "sub", "other"]);+ // Dragging other onto the first row puts it first.+ let from = h.get_by_label("3. other: $4.00").rect().center();+ let to = h.get_by_label("1. total: 6").rect().center();+ h.hover_at(from);+ h.run_steps(1);+ h.drag_at(from);+ h.run_steps(1);+ for k in 1..=4 {+ h.hover_at(from + (to - from) * (k as f32 / 4.0));+ h.run_steps(1);+ }+ h.drop_at(to);+ h.run_steps(4);+ assert_eq!(order(&h), ["other", "total", "sub"]);+ // Fix order moves only total, after sub, and the card says the order is right.+ h.get_by_label("Fix order").click();+ h.run_steps(3);+ assert_eq!(order(&h), ["other", "sub", "total"]);+ assert_eq!(undo_label(&h).as_deref(), Some("Set calculation order"));+ assert!(h.query_by_label("Every field calculates after the fields it reads.").is_some());+ assert!(h.query_by_label("Fix order").is_none());+ // Its Undo takes Fix order back.+ h.get_by_label("Undo").click();+ h.run_steps(3);+ assert_eq!(order(&h), ["other", "total", "sub"]);+ // A row selects its field.+ h.get_by_label("3. sub: 6").click();+ h.run_steps(2);+ assert_eq!(h.state().views[0].prepare.selected.as_ref().map(|s| s.0.as_str()), Some("sub"));+ }++ /// Fields that read each other get a card of their own, which Fix order leaves alone, and its+ /// link opens the first one's formula.+ #[test]+ fn a_loop_has_its_own_card_that_opens_the_formula() {+ use pdfcraft_engine::form_scripts::Calculate;+ use pdfcraft_engine::{Edit, FieldProps, NewField};+ use pdfcraft_ui_egui::prepare::FieldTab;+ let mut h = harness();+ for (i, (name, formula)) in [("a", "b + 1"), ("b", "a + 1")].into_iter().enumerate() {+ let y = 200.0 + 30.0 * i as f64;+ let kind = NewField::Text { multiline: false };+ h.state_mut().apply_edit(Edit::AddField { page: 0, rect: [20.0, y, 120.0, y + 20.0], kind, name: Some(name.into()) });+ let props = Box::new(FieldProps { calculate: Some(Calculate::Notation(formula.into())), ..Default::default() });+ h.state_mut().apply_edit(Edit::SetFieldProps { name: name.into(), props });+ }+ h.state_mut().execute("form.prepare");+ h.run_steps(3);+ h.get_by_label("Calculation order").click();+ h.run_steps(3);+ assert!(h.query_by_label("a and b read each other").is_some());+ assert!(h.query_by_label("Every field outside a loop calculates after the fields it reads.").is_some());+ assert!(h.query_by_label("Fix order").is_none(), "no order fixes a loop");+ h.get_by_label("Edit a's formula").click();+ h.run_steps(3);+ let draft = h.state().field_props.as_ref().map(|d| (d.field.clone(), d.tab));+ assert_eq!(draft, Some(("a".to_owned(), FieldTab::Calculate)));+ }++ /// A radio group `shirt` of three buttons, S, M and L, with L chosen, while preparing the form.+ fn radio_group_harness() -> Harness<'static, PdfCraftApp> {+ let mut h = harness();+ for (x, export) in [(20.0, "S"), (60.0, "M"), (100.0, "L")] {+ h.state_mut().apply_edit(pdfcraft_engine::Edit::AddField {+ page: 0,+ rect: [x, 300.0, x + 14.0, 314.0],+ kind: pdfcraft_engine::NewField::Radio { group: Some("shirt".into()), export: export.into() },+ name: Some("shirt".into()),+ });+ }+ h.state_mut()+ .apply_edit(pdfcraft_engine::Edit::SetFieldValue { name: "shirt".into(), value: pdfcraft_engine::FieldValue::Radio(Some("L".into())) });+ assert!(h.state_mut().execute("form.prepare"));+ h.run_steps(3);+ h+ }++ fn buttons(h: &Harness<'static, PdfCraftApp>) -> (Vec<String>, Vec<String>) {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "shirt").expect("the group is still there");+ (f.widgets.iter().filter_map(|w| w.on_state.clone()).collect(), f.value.clone())+ }++ /// #4609: Delete removes the one radio button clicked, not its whole group, as in Acrobat.+ #[test]+ fn deleting_one_radio_button_keeps_the_rest_of_its_group() {+ let mut h = radio_group_harness();+ assert_eq!(buttons(&h).0, ["S", "M", "L"]);+ let p = {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "shirt").unwrap();+ pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 1).expect("on screen").center()+ };+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ h.run_steps(3);+ assert_eq!(h.state().views[0].prepare.selected, Some(("shirt".into(), 1)), "the middle button is selected");+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert_eq!(buttons(&h), (vec!["S".into(), "L".into()], vec!["L".into()]), "only M is gone; L stays chosen");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), Some("Delete field"));+ h.state_mut().execute("edit.undo");+ h.run_steps(2);+ assert_eq!(buttons(&h).0, ["S", "M", "L"]);+ }++ /// Two buttons of one group selected together both go, whichever was selected first.+ #[test]+ fn deleting_two_radio_buttons_of_a_group_at_once() {+ let mut h = radio_group_harness();+ {+ let p = &mut h.state_mut().views[0].prepare;+ p.selected = Some(("shirt".into(), 0));+ p.also = vec![("shirt".into(), 2)];+ }+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert_eq!(buttons(&h), (vec!["M".into()], vec![]), "M is left, and nothing is chosen");+ // Selecting every button deletes the group.+ {+ let p = &mut h.state_mut().views[0].prepare;+ p.selected = Some(("shirt".into(), 0));+ }+ h.key_press(egui::Key::Delete);+ h.run_steps(3);+ assert!(!names(&h).iter().any(|n| n == "shirt"));+ }++++#[test]++fn button_export_properties_apply_cancel_and_undo() {++ fn retype(h: &mut Harness<'static, PdfCraftApp>, value: &str) {++ use egui::accesskit::Role;++ h.get_by_role_and_label(Role::TextInput, "Export value").click();++ h.run_steps(1);++ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);++ h.get_by_role_and_label(Role::TextInput, "Export value").type_text(value);++ h.run_steps(2);++ }++ let mut h = harness();++ h.state_mut().execute("form.prepare");++ h.run_steps(2);++ h.state_mut().open_field_props("agree", 0);++ h.run_steps(2);++ h.get_by_label("Options").click();++ h.run_steps(2);++ let original = h.state().field_props.as_ref().unwrap().export_value.clone();++ retype(&mut h, "Accepted");++ h.get_by_label("Cancel").click();++ h.run_steps(2);++ h.state_mut().open_field_props("agree", 0);++ h.run_steps(2);++ assert_eq!(h.state().field_props.as_ref().unwrap().export_value, original);++ h.get_by_label("Options").click();++ h.run_steps(2);++ retype(&mut h, "Accepted");++ h.get_by_label("OK").click();++ h.run_steps(3);++ {++ let s = h.state();++ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "agree").unwrap();++ assert_eq!(f.export_of(0), Some("Accepted"));++ }++ h.state_mut().execute("edit.undo");++ h.run_steps(3);++ {++ let s = h.state();++ let f = s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "agree").unwrap();++ assert_eq!(f.export_of(0), Some(original.as_str()));++ }++}diff --cc crates/xfdf/src/fdf.rsindex 000000000,34b59017d..ceb4ad99emode 000000,100644..100644--- a/crates/xfdf/src/fdf.rs+++ b/crates/xfdf/src/fdf.rs@@@ -1,0 -1,516 +1,516 @@@+ use super::common::{MAX_DEPTH, SUBTYPES, rect_strict, text_of};+ use super::xfdf::{add_popup, apply_values, find_by_name, place};+ use super::*;++ fn pdf_string(s: &str) -> Vec<u8> {+ let mut v = Vec::new();+ pdfcraft_cos::serialize(&Object::String(PdfString::text(s)), &mut v);+ v+ }++ // Keep aliases as aliases instead of expanding a shared graph once per use. References are+ // queued, not followed recursively, so cycles and long indirect chains cost linear work.+ pub(crate) const MAX_FDF_OBJECTS: usize = 100_000;++ pub(crate) const MAX_FDF_BYTES: usize = 64 * 1024 * 1024;++ /// Direct values stay borrowed: `Document::resolve` would deep-clone them. Only+ /// indirect values need an owner, and annotation bodies are never retained in discovery.+ enum FdfValue<'a> {+ Borrowed(&'a Object),+ Indirect(std::sync::Arc<Object>),+ }++ impl<'a> FdfValue<'a> {+ fn resolve(doc: &Document, value: &'a Object) -> Self {+ match value {+ Object::Ref(_) => Self::Indirect(doc.resolve(value)),+ _ => Self::Borrowed(value),+ }+ }++ fn object(&self) -> &Object {+ match self {+ Self::Borrowed(value) => value,+ Self::Indirect(value) => value.as_ref(),+ }+ }+ }++ struct FdfCopy<'a> {+ doc: &'a Document,+ objects: Vec<Object>,+ numbers: HashMap<ObjRef, u32>,+ pending: Vec<(ObjRef, usize)>,+ nodes: usize,+ bytes: usize,+ }++ impl<'a> FdfCopy<'a> {+ fn new(doc: &'a Document) -> Self {+ Self { doc, objects: Vec::new(), numbers: HashMap::new(), pending: Vec::new(), nodes: MAX_FDF_OBJECTS, bytes: MAX_FDF_BYTES }+ }++ fn charge(&mut self, bytes: usize) -> Result<(), DataError> {+ self.bytes = self.bytes.checked_sub(bytes).ok_or(DataError::ExportLimit("64 MiB data"))?;+ Ok(())+ }++ fn slot(&mut self) -> Result<(usize, u32), DataError> {+ if self.objects.len() >= MAX_FDF_OBJECTS {+ return Err(DataError::ExportLimit("100,000 objects"));+ }+ // Object 1 is the FDF root; arena indices start at object 2. The arena is capped above.+ let index = self.objects.len();+ let number = index as u32 + 2;+ self.charge(100)?; // indirect-object and xref overhead+ self.objects.push(Object::Null);+ Ok((index, number))+ }++ fn dict(&mut self, dict: &Dict, depth: usize) -> Result<Dict, DataError> {+ if dict.len() > self.nodes {+ return Err(DataError::ExportLimit("100,000 values"));+ }+ let mut out = Dict::new();+ for (key, value) in dict.iter() {+ self.dict_entry(&mut out, key, value, depth + 1)?;+ }+ Ok(out)+ }++ fn dict_entry(&mut self, out: &mut Dict, key: &[u8], value: &Object, depth: usize) -> Result<(), DataError> {+ self.charge(key.len().saturating_mul(3).saturating_add(2))?;+ let value = self.copy(value, depth)?;+ out.set(key.to_vec(), value);+ Ok(())+ }++ /// Skip source-document links and appearances without cloning their values. The+ /// dictionary and every retained entry are charged before any owned copy is made.+ fn annotation_dict(&mut self, dict: &Dict) -> Result<Dict, DataError> {+ self.charge_value(0)?;+ let mut out = Dict::new();+ for (key, value) in dict.iter() {+ if matches!(key.as_slice(), b"P" | b"AP" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") {+ continue;+ }+ self.dict_entry(&mut out, key, value, 1)?;+ }+ Ok(out)+ }++ fn charge_value(&mut self, depth: usize) -> Result<(), DataError> {+ if depth > MAX_DEPTH {+ return Err(DataError::ExportLimit("64 direct nesting levels"));+ }+ self.nodes = self.nodes.checked_sub(1).ok_or(DataError::ExportLimit("100,000 values"))?;+ // Includes delimiters, spacing and even the longest finite f64 in plain decimal form.+ self.charge(330)?;+ Ok(())+ }++ fn is_source_page(&self, dict: &Dict) -> Result<bool, DataError> {+ let Some(value) = dict.get(b"Type") else { return Ok(false) };+ let mut value = FdfValue::Borrowed(value);+ let mut seen = HashSet::new();+ for hops in 0..=MAX_DEPTH {+ match value.object() {+ Object::Name(name) => return Ok(matches!(name.as_slice(), b"Page" | b"Pages")),+ Object::Ref(reference) => {+ if self.doc.generation(reference.num) != reference.generation || !seen.insert(*reference) {+ return Ok(false);+ }+ if hops == MAX_DEPTH {+ return Err(DataError::ExportLimit("64 Type reference levels"));+ }+ value = FdfValue::Indirect(self.doc.get(*reference));+ }+ _ => return Ok(false),+ }+ }+ Err(DataError::ExportLimit("64 Type reference levels"))+ }++ fn copy(&mut self, value: &Object, depth: usize) -> Result<Object, DataError> {+ self.charge_value(depth)?;+ Ok(match value {+ Object::Ref(source) => {+ let number = if let Some(number) = self.numbers.get(source) {+ *number+ } else {+ let (index, number) = self.slot()?;+ self.numbers.insert(*source, number);+ self.pending.push((*source, index));+ number+ };+ Object::Ref(ObjRef::new(number, 0))+ }+ Object::Array(values) => {+ if values.len() > self.nodes {+ return Err(DataError::ExportLimit("100,000 values"));+ }+ let mut out = Vec::new();+ for value in values {+ out.push(self.copy(value, depth + 1)?);+ }+ Object::Array(out)+ }+ // Source page links must not drag page contents or the page tree into an FDF.+ Object::Dict(dict) if self.is_source_page(dict)? => Object::Null,+ Object::Dict(dict) => Object::Dict(self.dict(dict, depth)?),+ Object::String(s) => {+ self.charge(s.bytes.len().saturating_mul(4))?;+ value.clone()+ }+ Object::Name(name) => {+ self.charge(name.len().saturating_mul(3))?;+ value.clone()+ }+ // A PDF stream can only be an indirect object, never a dictionary/array value.+ Object::Stream(_) => return Err(DataError::Malformed("FDF export encountered a direct stream".into())),+ other => other.clone(),+ })+ }++ fn finish(&mut self, doc: &Document) -> Result<(), DataError> {+ let mut cursor = 0;+ while let Some((source, index)) = self.pending.get(cursor).copied() {+ // ISO 32000-2 §7.3.10: an absent or stale reference denotes null. Keep reader+ // errors distinct so damaged objects cannot be silently lost during export.+ let value = if doc.generation(source.num) != source.generation {+ std::sync::Arc::new(Object::Null)+ } else {+ match doc.try_get(source.num) {+ Ok(value) => value,+ Err(pdfcraft_cos::CosError::MissingObject(_)) => std::sync::Arc::new(Object::Null),+ Err(error) => return Err(error.into()),+ }+ };+ let copied = match &*value {+ Object::Stream(stream) => {+ self.charge(stream.raw.len())?;+ Object::Stream(pdfcraft_cos::Stream { dict: self.dict(&stream.dict, 0)?, raw: stream.raw.clone() })+ }+ other => self.copy(other, 0)?,+ };+ let slot = self.objects.get_mut(index).ok_or_else(|| DataError::Malformed("FDF object slot is missing".into()))?;+ *slot = copied;+ cursor += 1;+ }+ Ok(())+ }+ }++ /// FDF with field values and/or comments (appearances are not carried). Each comment is an+ /// indirect object of the FDF, so a reply's `/IRT` can point at its parent's object there+ /// (§12.7.8.3.1). Nested values are copied and renumbered, including shared or cyclic graphs.+ /// Source `/Page` and `/Pages` dictionaries become null at every copy depth.+ /// Refuses exports above the object, value, direct-depth or data budget instead of losing data.+ pub fn export_fdf(doc: &Document, comments: bool, fields: bool, file: &str) -> Result<Vec<u8>, DataError> {+ let mut copy = FdfCopy::new(doc);+ copy.charge(file.len().saturating_mul(8))?;+ let mut body: Vec<u8> = b"<< /FDF << ".to_vec();+ // Comment dictionaries, written after the root as objects 2, 3, …+ if fields {+ body.extend_from_slice(b"/Fields [");+ for f in pdfcraft_forms::fields(doc) {+ if matches!(f.kind, FieldKind::PushButton | FieldKind::Signature) {+ continue;+ }+ // Field dictionary, /T string and /V scalar/array, plus every emitted list+ // entry. Other field kinds emit only their first value (or a default).+ let field_nodes = if matches!(f.kind, FieldKind::List) && f.value.len() > 1 { f.value.len().saturating_add(3) } else { 3 };+ copy.nodes = copy.nodes.checked_sub(field_nodes).ok_or(DataError::ExportLimit("100,000 values"))?;+ copy.charge(f.name.len().saturating_mul(8).saturating_add(100))?;+ for value in &f.value {+ copy.charge(value.len().saturating_mul(8).saturating_add(100))?;+ }+ body.extend_from_slice(b"<< /T ");+ body.extend(pdf_string(&f.name));+ body.extend_from_slice(b" /V ");+ match f.kind {+ FieldKind::CheckBox | FieldKind::Radio => {- let v = f.value.first().cloned().unwrap_or_else(|| "Off".into());++ let v = f.export_values().first().cloned().unwrap_or_else(|| "Off".into());+ pdfcraft_cos::serialize(&Object::Name(pdfcraft_forms::name_bytes(&v)), &mut body);+ }+ FieldKind::List if f.value.len() > 1 => {+ pdfcraft_cos::serialize(&Object::Array(f.value.iter().map(|v| Object::String(PdfString::text(v))).collect()), &mut body);+ }+ _ => body.extend(pdf_string(f.value.first().map(String::as_str).unwrap_or(""))),+ }+ body.extend_from_slice(b" >> ");+ }+ body.extend_from_slice(b"] ");+ }+ if comments {+ // Keep the page/array owners once. Handles retain positions, never annotation+ // bodies: the document cache can evict and reparse even a repeated source reference.+ let pages = pdfcraft_model::pages(doc);+ let mut arrays = Vec::new();+ let mut picked: Vec<(Option<ObjRef>, usize, usize)> = Vec::new();+ for (pi, page) in pages.iter().enumerate() {+ let owner = page.dict.get(b"Annots").map(|value| FdfValue::resolve(doc, value));+ let before = picked.len();+ if let Some(values) = owner.as_ref().and_then(|owner| owner.object().as_array()) {+ for (ai, a) in values.iter().enumerate() {+ let value = FdfValue::resolve(doc, a);+ let Some(d) = value.object().as_dict() else { continue };+ if d.name(b"Subtype").is_some_and(|sub| SUBTYPES.iter().any(|(s, _)| s.as_bytes() == sub)) {+ if picked.len() >= MAX_FDF_OBJECTS {+ return Err(DataError::ExportLimit("100,000 comments"));+ }+ picked.push((a.as_ref(), pi, ai));+ }+ }+ }+ // Empty/unselected arrays need no owner. Resolve subsequent pages only after+ // this page passes the cap, rather than loading them all before discovery.+ arrays.push(if picked.len() > before { owner } else { None });+ }+ let mut numbers = HashMap::new();+ for (source, _, _) in &picked {+ let (_, number) = copy.slot()?;+ if let Some(source) = source {+ numbers.insert(*source, number);+ }+ }+ copy.numbers = numbers.clone();+ let count = picked.len();+ for (index, (_, pi, ai)) in picked.into_iter().enumerate() {+ let annotation = arrays+ .get(pi)+ .and_then(Option::as_ref)+ .and_then(|owner| owner.object().as_array())+ .and_then(|values| values.get(ai))+ .ok_or_else(|| DataError::Malformed("FDF annotation slot is missing".into()))?;+ let value = FdfValue::resolve(doc, annotation);+ let d = value.object().as_dict().ok_or_else(|| DataError::Malformed("FDF comment is not a dictionary".into()))?;+ // A reply points at its parent's object in this FDF; a parent that isn't exported+ // leaves the reply unthreaded.+ let irt = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| numbers.get(&r)).copied();+ let mut d = copy.annotation_dict(d)?;+ if let Some(num) = irt {+ d.set(b"IRT".to_vec(), Object::Ref(ObjRef::new(num, 0)));+ }+ d.set(b"Page".to_vec(), Object::Int(pi as i64));+ let slot = copy.objects.get_mut(index).ok_or_else(|| DataError::Malformed("FDF comment slot is missing".into()))?;+ *slot = Object::Dict(d);+ }+ body.extend_from_slice(b"/Annots [");+ for i in 0..count {+ let _ = write!(body, "{} 0 R ", i + 2);+ }+ body.extend_from_slice(b"] ");+ }+ body.extend_from_slice(b"/F ");+ body.extend(pdf_string(file));+ body.extend_from_slice(b" >> >>");+ copy.finish(doc)?;+ let mut out = b"%FDF-1.2\n%\xE2\xE3\xCF\xD3\n".to_vec();+ let mut offsets = Vec::with_capacity(copy.objects.len() + 1);+ offsets.push(out.len());+ out.extend_from_slice(b"1 0 obj\n");+ out.extend(body);+ out.extend_from_slice(b"\nendobj\n");+ for (i, object) in copy.objects.into_iter().enumerate() {+ offsets.push(out.len());+ let _ = writeln!(out, "{} 0 obj", i + 2);+ pdfcraft_cos::serialize(&object, &mut out);+ out.extend_from_slice(b"\nendobj\n");+ }+ let xref = out.len();+ let _ = write!(out, "xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1);+ for o in offsets {+ let _ = writeln!(out, "{o:010} 00000 n ");+ }+ let _ = write!(out, "trailer\n<< /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n");+ Ok(out)+ }++ /// What one FDF import may copy out of the file. A field tree or comment that repeats a reference+ /// level after level would otherwise expand a small file into millions of values.+ const MAX_FDF_IMPORT_VALUES: usize = 1_000_000;++ pub(crate) struct ImportBudget {+ values: usize,+ bytes: usize,+ }++ impl ImportBudget {+ pub(crate) fn new() -> Self {+ Self { values: MAX_FDF_IMPORT_VALUES, bytes: MAX_FDF_BYTES }+ }++ fn spend(&mut self, values: usize, bytes: usize) -> Result<(), DataError> {+ match (self.values.checked_sub(values), self.bytes.checked_sub(bytes)) {+ (Some(v), Some(b)) => {+ (self.values, self.bytes) = (v, b);+ Ok(())+ }+ _ => Err(DataError::Malformed(format!(+ "the file expands to more than {MAX_FDF_IMPORT_VALUES} values or {} MiB of text",+ MAX_FDF_BYTES >> 20+ ))),+ }+ }+ }++ /// Copy an object out of another document, resolving references. A reference back to an object+ /// being copied becomes null.+ fn deep(src: &Document, o: &Object, depth: usize, path: &mut Vec<ObjRef>, budget: &mut ImportBudget) -> Result<Object, DataError> {+ budget.spend(1, 0)?;+ if depth > 16 {+ return Ok(Object::Null);+ }+ Ok(match o {+ Object::Ref(r) => {+ if path.contains(r) {+ return Ok(Object::Null);+ }+ path.push(*r);+ let copy = deep(src, &src.get(*r), depth + 1, path, budget);+ path.pop();+ copy?+ }+ Object::Array(a) => Object::Array(a.iter().map(|x| deep(src, x, depth + 1, path, budget)).collect::<Result<_, _>>()?),+ Object::Dict(d) => {+ Object::Dict(d.iter().map(|(k, v)| Ok((k.clone(), deep(src, v, depth + 1, path, budget)?))).collect::<Result<_, DataError>>()?)+ }+ Object::Stream(_) => Object::Null,+ Object::String(s) => {+ budget.spend(0, s.bytes.len())?;+ o.clone()+ }+ Object::Name(n) => {+ budget.spend(0, n.len())?;+ o.clone()+ }+ other => other.clone(),+ })+ }++ /// Read an FDF field tree. A field listed again beneath itself is skipped.+ pub(crate) fn walk_fdf(+ fdf: &Document,+ list: &[Object],+ prefix: &str,+ out: &mut Vec<(String, Vec<String>)>,+ depth: usize,+ path: &mut Vec<ObjRef>,+ budget: &mut ImportBudget,+ ) -> Result<(), DataError> {+ if depth > 32 {+ return Ok(());+ }+ for f in list {+ budget.spend(1, 0)?;+ let held;+ let field = match f {+ Object::Ref(r) if path.contains(r) => continue,+ Object::Ref(r) => {+ held = fdf.get(*r);+ &*held+ }+ direct => direct,+ };+ let Some(d) = field.as_dict() else { continue };+ let Some(t) = d.get(b"T").and_then(|t| fdf.resolve(t).as_string().map(|s| s.to_text())) else { continue };+ let full = if prefix.is_empty() { t } else { format!("{prefix}.{t}") };+ budget.spend(0, full.len())?;+ if let Some(v) = d.get(b"V").map(|v| fdf.resolve(v)) {+ let vals: Vec<String> = match &*v {+ Object::String(s) => vec![s.to_text()],+ Object::Name(n) => vec![pdfcraft_forms::name_text(n)],+ Object::Array(a) => {+ budget.spend(a.len(), 0)?;+ a.iter().filter_map(|x| fdf.resolve(x).as_string().map(|s| s.to_text())).collect()+ }+ _ => Vec::new(),+ };+ budget.spend(vals.len(), vals.iter().map(String::len).fold(0, usize::saturating_add))?;+ out.push((full.clone(), vals));+ }+ if let Some(kids) = d.get(b"Kids").map(|k| fdf.resolve(k))+ && let Some(kids) = kids.as_array()+ {+ let entered = f.as_ref().map(|r| path.push(r)).is_some();+ let walked = walk_fdf(fdf, kids, &full, out, depth + 1, path, budget);+ if entered {+ path.pop();+ }+ walked?;+ }+ }+ Ok(())+ }++ pub(crate) fn fdf_body(fdf: &Document) -> Result<Dict, DataError> {+ let root = fdf.root().ok_or_else(|| DataError::Malformed("no /Root".into()))?;+ fdf.get(root)+ .as_dict()+ .and_then(|d| d.get(b"FDF").cloned())+ .map(|f| fdf.resolve(&f))+ .and_then(|f| f.as_dict().cloned())+ .ok_or(DataError::UnknownFormat)+ }++ pub(crate) fn import_fdf(doc: &mut Document, bytes: &[u8]) -> Result<Report, DataError> {+ let fdf = Document::open(std::sync::Arc::new(bytes.to_vec())).map_err(|e| DataError::Malformed(e.to_string()))?;+ let body = fdf_body(&fdf)?;+ let mut report = Report::default();+ let mut budget = ImportBudget::new();+ // Fields (with /Kids for hierarchical names).+ let mut values = Vec::new();+ if let Some(list) = body.get(b"Fields").map(|f| fdf.resolve(f)).and_then(|f| f.as_array().cloned()) {+ walk_fdf(&fdf, &list, "", &mut values, 0, &mut Vec::new(), &mut budget)?;+ }+ // Comments: parents first, then replies (whose /IRT needs the parent's new reference).+ let pages: Vec<ObjRef> = pdfcraft_model::pages(doc).iter().map(|p| p.obj).collect();+ let mut placed: HashMap<ObjRef, ObjRef> = HashMap::new();+ let mut later: HashMap<ObjRef, (Option<ObjRef>, Option<String>)> = HashMap::new();+ for a in body.get(b"Annots").map(|a| fdf.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {+ let Some(mut src) = fdf.resolve(&a).as_dict().cloned() else { continue };+ // The parent is another comment: link it below rather than copying it in.+ let irt = src.get(b"IRT").cloned();+ src.remove(b"IRT");+ // The pop-up is an annotation of its own (/Popup shall be an indirect reference, ISO+ // 32000-2 Table 172): copied in, it would become a direct dictionary. A new one is+ // placed on the page below, as the XFDF import does.+ let popup = src.get(b"Popup").map(|p| fdf.resolve(p)).and_then(|p| p.as_dict().cloned());+ src.remove(b"Popup");+ let mut path: Vec<ObjRef> = a.as_ref().into_iter().collect();+ let Object::Dict(mut d) = deep(&fdf, &Object::Dict(src), 0, &mut path, &mut budget)? else { continue };+ let Some(page) = d.get(b"Page").and_then(Object::as_int).and_then(|p| usize::try_from(p).ok()).and_then(|p| pages.get(p).copied()) else {+ continue;+ };+ if !d.name(b"Subtype").is_some_and(|s| SUBTYPES.iter().any(|(x, _)| x.as_bytes() == s)) {+ continue;+ }+ d.remove(b"Page");+ d.set(b"P".to_vec(), Object::Ref(page));+ let r = place(doc, page, d)?;+ later.remove(&r);+ if let Some(rect) = popup.as_ref().and_then(|p| rect_strict(&fdf, p.get(b"Rect"))) {+ let open = popup.as_ref().and_then(|p| p.get(b"Open")).is_some_and(|o| matches!(&*fdf.resolve(o), Object::Bool(true)));+ add_popup(doc, page, r, &rect, open)?;+ }+ if let Some(fr) = a.as_ref() {+ placed.insert(fr, r);+ }+ if let Some(irt) = irt {+ let parent_name = fdf.resolve(&irt).as_dict().and_then(|p| text_of(&fdf, p, b"NM"));+ later.insert(r, (irt.as_ref(), parent_name));+ }+ report.comments += 1;+ }+ for (r, (parent_obj, parent_name)) in later {+ // The parent imported from this file, else one already in the document with its name.+ let parent = parent_obj.and_then(|p| placed.get(&p).copied()).or_else(|| parent_name.and_then(|nm| find_by_name(doc, &nm)));+ if let Some(parent) = parent.filter(|p| *p != r) {+ doc.update_dict(r, |d| d.set(b"IRT".to_vec(), Object::Ref(parent)))?;+ }+ }+ apply_values(doc, &values, &mut report);+ Ok(report)+ }diff --cc crates/xfdf/src/xfdf.rsindex 000000000,a5881adf2..06ad9f34emode 000000,100644..100644--- a/crates/xfdf/src/xfdf.rs+++ b/crates/xfdf/src/xfdf.rs@@@ -1,0 -1,536 +1,536 @@@+ use super::common::{+ FLAGS, MAX_DEPTH, SUBTYPES, arr, check_form_xml_depth, csv, esc, hex, n, nums_of, parse_form_xml, parse_hex, quad_has_area, rect_strict, text_of,+ walk_xfdf,+ };+ use super::*;++ // ── export ──────────────────────────────────────────────────────────────────────────────────++ /// Every comment as an XFDF element (one line per comment, replies included).+ fn xfdf_annots(doc: &Document, out: &mut String) {+ let pages = pdfcraft_model::pages(doc);+ // NM of every annotation, for inreplyto.+ let mut names: HashMap<ObjRef, String> = HashMap::new();+ for p in &pages {+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {+ if let Some(r) = a.as_ref()+ && let Some(nm) = doc.get(r).as_dict().and_then(|d| text_of(doc, d, b"NM"))+ {+ names.insert(r, nm);+ }+ }+ }+ for (pi, p) in pages.iter().enumerate() {+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {+ let Some(d) = doc.resolve(&a).as_dict().cloned() else { continue };+ let Some(sub) = d.name(b"Subtype") else { continue };+ let Some((_, tag)) = SUBTYPES.iter().find(|(s, _)| s.as_bytes() == sub) else { continue };+ let mut attrs = format!(" page=\"{pi}\"");+ let rect = nums_of(doc, d.get(b"Rect"));+ if rect.len() == 4 {+ let _ = write!(+ attrs,+ " rect=\"{},{},{},{}\"",+ n(rect[0].min(rect[2])),+ n(rect[1].min(rect[3])),+ n(rect[0].max(rect[2])),+ n(rect[1].max(rect[3]))+ );+ }+ for (key, attr) in [+ (&b"NM"[..], "name"),+ (b"T", "title"),+ (b"Subj", "subject"),+ (b"M", "date"),+ (b"CreationDate", "creationdate"),+ (b"RT", "replyType"),+ (b"State", "state"),+ (b"StateModel", "statemodel"),+ (b"Name", "icon"),+ ] {+ if let Some(v) = text_of(doc, &d, key) {+ let _ = write!(attrs, " {attr}=\"{}\"", esc(&v));+ }+ }+ let flags = d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);+ let fl: Vec<&str> = FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect();+ let _ = write!(attrs, " flags=\"{}\"", fl.join(","));+ if let Some(c) = hex(&nums_of(doc, d.get(b"C"))) {+ let _ = write!(attrs, " color=\"{c}\"");+ }+ if let Some(c) = hex(&nums_of(doc, d.get(b"IC"))) {+ let _ = write!(attrs, " interior-color=\"{c}\"");+ }+ if let Some(o) = d.get(b"CA").and_then(|o| doc.resolve(o).as_f64()) {+ let _ = write!(attrs, " opacity=\"{}\"", n(o));+ }+ if let Some(w) = d.get(b"BS").and_then(|b| doc.resolve(b).as_dict().and_then(|b| b.get(b"W").and_then(Object::as_f64))) {+ let _ = write!(attrs, " width=\"{}\"", n(w));+ }+ let quads = nums_of(doc, d.get(b"QuadPoints"));+ if !quads.is_empty() {+ let _ = write!(attrs, " coords=\"{}\"", quads.iter().map(|v| n(*v)).collect::<Vec<_>>().join(","));+ }+ let l = nums_of(doc, d.get(b"L"));+ if l.len() == 4 {+ let _ = write!(attrs, " start=\"{},{}\" end=\"{},{}\"", n(l[0]), n(l[1]), n(l[2]), n(l[3]));+ }+ if let Some(le) = d.get(b"LE").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned())+ && le.len() == 2+ {+ let name = |o: &Object| o.as_name().map(|x| String::from_utf8_lossy(x).into_owned()).unwrap_or_else(|| "None".into());+ let _ = write!(attrs, " head=\"{}\" tail=\"{}\"", esc(&name(&le[0])), esc(&name(&le[1])));+ }+ // A callout: its leader path, text-box inset, intent and (single-name) line ending.+ let cl = nums_of(doc, d.get(b"CL"));+ if cl.len() == 4 || cl.len() == 6 {+ let _ = write!(attrs, " callout=\"{}\"", cl.iter().map(|v| n(*v)).collect::<Vec<_>>().join(","));+ let rd = nums_of(doc, d.get(b"RD"));+ if rd.len() == 4 {+ let _ = write!(attrs, " fringe=\"{}\"", rd.iter().map(|v| n(*v)).collect::<Vec<_>>().join(","));+ }+ if let Some(it) = d.get(b"IT").map(|o| doc.resolve(o)).and_then(|o| o.as_name().map(|x| String::from_utf8_lossy(x).into_owned())) {+ let _ = write!(attrs, " intent=\"{}\"", esc(&it));+ }+ if let Some(le) = d.get(b"LE").map(|o| doc.resolve(o)).and_then(|o| o.as_name().map(|x| String::from_utf8_lossy(x).into_owned())) {+ let _ = write!(attrs, " head=\"{}\"", esc(&le));+ }+ }+ if let Some(irt) = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| names.get(&r)) {+ let _ = write!(attrs, " inreplyto=\"{}\"", esc(irt));+ }+ let _ = write!(out, "<{tag}{attrs}>");+ if let Some(c) = text_of(doc, &d, b"Contents") {+ let _ = write!(out, "<contents>{}</contents>", esc(&c));+ }+ if let Some(da) = text_of(doc, &d, b"DA") {+ let _ = write!(out, "<defaultappearance>{}</defaultappearance>", esc(&da));+ }+ let ink = d.get(b"InkList").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();+ if !ink.is_empty() {+ out.push_str("<inklist>");+ for g in ink {+ let v = nums_of(doc, Some(&g));+ let pts: Vec<String> = v.as_chunks::<2>().0.iter().map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect();+ let _ = write!(out, "<gesture>{}</gesture>", pts.join(";"));+ }+ out.push_str("</inklist>");+ }+ // Polygon and polyline points (XFDF `<vertices>`: `x,y;x,y;…`).+ let vertices = nums_of(doc, d.get(b"Vertices"));+ let pts: Vec<String> = vertices.as_chunks::<2>().0.iter().map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect();+ if !pts.is_empty() {+ let _ = write!(out, "<vertices>{}</vertices>", pts.join(";"));+ }+ if let Some(pd) = d.get(b"Popup").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()) {+ let r = nums_of(doc, pd.get(b"Rect"));+ if r.len() == 4 {+ let open = matches!(pd.get(b"Open"), Some(Object::Bool(true)));+ let _ = write!(+ out,+ "<popup page=\"{pi}\" rect=\"{},{},{},{}\" open=\"{}\"/>",+ n(r[0]),+ n(r[1]),+ n(r[2]),+ n(r[3]),+ if open { "yes" } else { "no" }+ );+ }+ }+ let _ = writeln!(out, "</{tag}>");+ }+ }+ }++ /// Field values as nested XFDF `<field>` elements.+ fn xfdf_fields(doc: &Document, out: &mut String) {+ #[derive(Default)]+ struct Node {+ values: Vec<String>,+ kids: Vec<(String, Node)>,+ }+ let mut root = Node::default();+ for f in pdfcraft_forms::fields(doc) {+ if matches!(f.kind, FieldKind::PushButton | FieldKind::Signature) {+ continue;+ }+ let mut node = &mut root;+ // One `<field>` level per part of the name, but no more levels than the import reads+ // back. A `/T` can hold periods of its own, so a name can split into far more parts than+ // the field tree has levels: nesting every part wrote a file the import refuses and, for+ // a long enough name, recursed in `write_node` until the stack overflowed. The parts past+ // the last level stay together in the deepest element's name, and the import joins them+ // back with periods into the same full name.+ for part in f.name.splitn(MAX_DEPTH, '.') {+ let i = match node.kids.iter().position(|(k, _)| k == part) {+ Some(i) => i,+ None => {+ node.kids.push((part.to_string(), Node::default()));+ node.kids.len() - 1+ }+ };+ node = &mut node.kids[i].1;+ }+ node.values = match f.kind {+ FieldKind::CheckBox | FieldKind::Radio if f.value.is_empty() => vec!["Off".into()],- _ => f.value.clone(),++ _ => f.export_values(),+ };+ }+ fn write_node(name: &str, node: &Node, out: &mut String) {+ let _ = write!(out, "<field name=\"{}\">", esc(name));+ for v in &node.values {+ let _ = write!(out, "<value>{}</value>", esc(v));+ }+ for (k, kid) in &node.kids {+ write_node(k, kid, out);+ }+ out.push_str("</field>\n");+ }+ for (k, kid) in &root.kids {+ write_node(k, kid, out);+ }+ }++ /// XFDF with the document's comments and/or field values.+ pub fn export_xfdf(doc: &Document, comments: bool, fields: bool, file: &str) -> String {+ let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\">\n");+ if comments {+ out.push_str("<annots>\n");+ xfdf_annots(doc, &mut out);+ out.push_str("</annots>\n");+ }+ if fields {+ out.push_str("<fields>\n");+ xfdf_fields(doc, &mut out);+ out.push_str("</fields>\n");+ }+ let _ = writeln!(out, "<f href=\"{}\"/>", esc(file));+ out.push_str("</xfdf>\n");+ out+ }++ // ── import ──────────────────────────────────────────────────────────────────────────────────++ /// Set the values of fields named in `values` (full names), counting what took.+ pub(crate) fn apply_values(doc: &mut Document, values: &[(String, Vec<String>)], report: &mut Report) {+ let all = pdfcraft_forms::fields(doc);+ for (name, vals) in values {+ let Some(f) = all.iter().find(|f| &f.name == name) else { continue };+ let first = vals.first().cloned().unwrap_or_default();+ let v = match f.kind {+ FieldKind::Text => FieldValue::Text(first),+ FieldKind::CheckBox => FieldValue::Check(!first.is_empty() && first != "Off"),+ FieldKind::Radio => FieldValue::Radio((!first.is_empty() && first != "Off").then_some(first)),+ // XML, CSV and text hold a multi-select list's values in one cell, joined by ", "+ // (as export_data writes them); split it unless the whole cell is one option.+ FieldKind::List if f.has(pdfcraft_forms::flags::MULTI_SELECT) && vals.len() == 1 && !f.options.iter().any(|(e, _)| *e == first) => {+ FieldValue::Choice(first.split(", ").filter(|v| !v.is_empty()).map(str::to_string).collect())+ }+ FieldKind::Combo | FieldKind::List => FieldValue::Choice(vals.iter().filter(|v| !v.is_empty()).cloned().collect()),+ FieldKind::PushButton | FieldKind::Signature => continue,+ };+ // Read-only fields still take imported data, as in Acrobat.+ let ro = f.read_only();+ if ro {+ let _ = doc.update_dict(f.obj, |d| d.set(b"Ff".to_vec(), Object::Int((f.flags & !pdfcraft_forms::flags::READ_ONLY) as i64)));+ }+ match pdfcraft_forms::set_value(doc, name, &v) {+ Ok(()) => report.fields += 1,+ Err(_) => report.rejected.push(name.clone()),+ }+ if ro {+ let _ = doc.update_dict(f.obj, |d| d.set(b"Ff".to_vec(), Object::Int(f.flags as i64)));+ }+ }+ }++ /// A new annotation dictionary from an XFDF element.+ fn annot_from_xml(node: roxmltree::Node, subtype: &str, page_ref: ObjRef) -> Option<Dict> {+ let mut d = Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name(subtype));+ d.set(b"P".to_vec(), Object::Ref(page_ref));+ let rect = csv(node.attribute("rect")?);+ if rect.len() != 4 {+ return None;+ }+ d.set(b"Rect".to_vec(), arr(&rect));+ for (attr, key) in [+ ("name", &b"NM"[..]),+ ("title", b"T"),+ ("subject", b"Subj"),+ ("date", b"M"),+ ("creationdate", b"CreationDate"),+ ("state", b"State"),+ ("statemodel", b"StateModel"),+ ] {+ if let Some(v) = node.attribute(attr) {+ d.set(key.to_vec(), PdfString::text(v));+ }+ }+ if let Some(v) = node.attribute("replyType") {+ d.set(b"RT".to_vec(), Object::name(if v.eq_ignore_ascii_case("group") { "Group" } else { "R" }));+ }+ if let Some(v) = node.attribute("icon") {+ d.set(b"Name".to_vec(), Object::name(v));+ }+ let flags: i64 = node+ .attribute("flags")+ .unwrap_or("print")+ .split(',')+ .filter_map(|f| FLAGS.iter().find(|(_, s)| s.eq_ignore_ascii_case(f.trim())).map(|x| x.0))+ .fold(0, |bits, flag| bits | flag);+ d.set(b"F".to_vec(), Object::Int(flags));+ if let Some(c) = node.attribute("color").and_then(parse_hex) {+ d.set(b"C".to_vec(), arr(&c));+ }+ if let Some(c) = node.attribute("interior-color").and_then(parse_hex) {+ d.set(b"IC".to_vec(), arr(&c));+ }+ if let Some(o) = node.attribute("opacity").and_then(|o| o.parse::<f64>().ok()) {+ d.set(b"CA".to_vec(), Object::Real(o.clamp(0.0, 1.0)));+ }+ if let Some(w) = node.attribute("width").and_then(|w| w.parse::<f64>().ok()) {+ let mut bs = Dict::new();+ bs.set(b"W".to_vec(), Object::Real(w.max(0.0)));+ bs.set(b"S".to_vec(), Object::name("S"));+ d.set(b"BS".to_vec(), Object::Dict(bs));+ }+ if let Some(q) = node.attribute("coords") {+ d.set(b"QuadPoints".to_vec(), arr(&csv(q)));+ }+ if let (Some(s), Some(e)) = (node.attribute("start"), node.attribute("end")) {+ let (s, e) = (csv(s), csv(e));+ if s.len() == 2 && e.len() == 2 {+ d.set(b"L".to_vec(), arr(&[s[0], s[1], e[0], e[1]]));+ }+ }+ if node.attribute("head").is_some() || node.attribute("tail").is_some() {+ d.set(+ b"LE".to_vec(),+ Object::Array(vec![Object::name(node.attribute("head").unwrap_or("None")), Object::name(node.attribute("tail").unwrap_or("None"))]),+ );+ }+ if let Some(cl) = node.attribute("callout").map(csv).filter(|c| c.len() == 4 || c.len() == 6) {+ d.set(b"CL".to_vec(), arr(&cl));+ if let Some(rd) = node.attribute("fringe").map(csv).filter(|r| r.len() == 4) {+ d.set(b"RD".to_vec(), arr(&rd));+ }+ d.set(b"IT".to_vec(), Object::name(node.attribute("intent").unwrap_or("FreeTextCallout")));+ // A callout's /LE is one name, not the head/tail pair of a line.+ match node.attribute("head") {+ Some(h) => d.set(b"LE".to_vec(), Object::name(h)),+ None => {+ d.remove(b"LE");+ }+ }+ }+ for child in node.children().filter(|c| c.is_element()) {+ match child.tag_name().name() {+ "contents" => {+ d.set(b"Contents".to_vec(), PdfString::text(&child.text().unwrap_or("").replace("\r\n", "\r").replace('\n', "\r")));+ }+ "defaultappearance" => {+ d.set(b"DA".to_vec(), PdfString::literal(child.text().unwrap_or("").as_bytes().to_vec()));+ }+ "inklist" => {+ let list: Vec<Object> = child+ .children()+ .filter(|g| g.has_tag_name("gesture"))+ .map(|g| arr(&g.text().unwrap_or("").split(';').flat_map(|p| csv(p).into_iter()).collect::<Vec<_>>()))+ .collect();+ d.set(b"InkList".to_vec(), Object::Array(list));+ }+ "vertices" => {+ // Whole x,y pairs only; a stray trailing number is dropped.+ let mut v = csv(child.text().unwrap_or(""));+ v.truncate(v.len() - v.len() % 2);+ if !v.is_empty() {+ d.set(b"Vertices".to_vec(), arr(&v));+ }+ }+ _ => {}+ }+ }+ Some(d)+ }++ /// Put an annotation dictionary on a page, replacing one with the same `/NM`. Returns its+ /// reference.+ /// `/F` bits an imported file may not set on a redaction mark: Invisible, Hidden, NoView — so a+ /// mark it brings in is always drawn for the user to review before content is removed.+ const REDACT_UNSEEN: i64 = 1 | 2 | 32;++ /// `/F` Locked (ISO 32000-2 Table 167): the user protected this annotation from change.+ pub(crate) const LOCKED: i64 = 128;++ /// An existing annotation an import must never replace, move or unlock: one the user locked, a+ /// redaction mark (replacing it would drop the region the user marked to remove), or a form+ /// widget or field (replacing it would set the field's value and policy around the form setter).+ fn import_protected(doc: &Document, x: &Dict) -> bool {+ let flags = x.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);+ flags & LOCKED != 0 || matches!(x.name(b"Subtype"), Some(b"Redact" | b"Widget")) || x.contains(b"FT")+ }++ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result<ObjRef, DataError> {+ // A redaction mark the import carries is always made visible: clear any Invisible/Hidden/NoView+ // flag so it cannot remove content the user never sees.+ if d.name(b"Subtype") == Some(b"Redact".as_slice()) {+ let f = d.int(b"F").unwrap_or(0);+ if f & REDACT_UNSEEN != 0 {+ d.set(b"F".to_vec(), Object::Int(f & !REDACT_UNSEEN));+ }+ // Its review outline is drawn opaque, and from the area it removes: applying a mark+ // without usable /QuadPoints removes its /Rect, which the outline is then drawn from.+ d.remove(b"CA");+ d.remove(b"ca");+ let quads_drawable = d.get(b"QuadPoints").and_then(Object::as_array).is_some_and(|q| {+ let v: Vec<f64> = q.iter().filter_map(Object::as_f64).filter(|v| v.is_finite()).collect();+ let (quads, rest) = v.as_chunks::<8>();+ v.len() == q.len() && rest.is_empty() && !quads.is_empty() && quads.iter().all(quad_has_area)+ });+ if !quads_drawable {+ // Quads the outline can't draw, or any quad that encloses no area, are replaced by the+ // /Rect's, or dropped when there is no usable /Rect either; such a mark then removes+ // nothing.+ match rect_strict(doc, d.get(b"Rect")) {+ Some([x0, y0, x1, y1]) => {+ let (l, r, b, t) = (x0.min(x1), x0.max(x1), y0.min(y1), y0.max(y1));+ d.set(b"QuadPoints".to_vec(), arr(&[l, t, r, t, l, b, r, b]));+ }+ _ => {+ d.remove(b"QuadPoints");+ }+ }+ }+ }+ let nm = d.get(b"NM").and_then(|n| n.as_string().map(|s| s.to_text()));+ let annots: Vec<Object> = doc+ .get(page_ref)+ .as_dict()+ .and_then(|p| p.get(b"Annots").cloned())+ .map(|a| doc.resolve(&a))+ .and_then(|a| a.as_array().cloned())+ .unwrap_or_default();+ let mut kept = Vec::new();+ let mut removed: Vec<ObjRef> = Vec::new();+ // Never let a same-name import replace a protected annotation (`import_protected`): keep it,+ // and add the imported dict beside it under no name of its own.+ let mut clash = false;+ for a in annots {+ let existing = a.as_ref().and_then(|r| doc.get(r).as_dict().cloned());+ let same = nm.is_some() && existing.as_ref().and_then(|x| x.get(b"NM").and_then(|n| doc.resolve(n).as_string().map(|s| s.to_text()))) == nm;+ if same && existing.as_ref().is_some_and(|x| import_protected(doc, x)) {+ clash = true;+ kept.push(a);+ } else if same {+ removed.extend(a.as_ref());+ } else {+ kept.push(a);+ }+ }+ if clash {+ d.remove(b"NM");+ }+ // The replaced note's pop-up goes with it; otherwise it stays on the page pointing at a note that is no longer there.+ kept.retain(|a| {+ let Some(x) = a.as_ref().map(|r| doc.get(r)).and_then(|o| o.as_dict().cloned()) else { return true };+ x.name(b"Subtype") != Some(b"Popup".as_slice()) || x.reference(b"Parent").is_none_or(|p| !removed.contains(&p))+ });+ // Keep the replaced comment's identity: replies and review statuses not included in a+ // partial import still point at it through /IRT. Allocating a new object would detach+ // those comments and leave their parent outside the page's annotation list.+ let r = match removed.first().copied() {+ Some(r) => {+ doc.set(r, Object::Dict(d));+ r+ }+ None => doc.add(Object::Dict(d)),+ };+ // Our own appearance where we can draw one; others keep none (viewers draw a default).+ let _ = pdfcraft_annot::set_appearance(doc, r);+ kept.push(Object::Ref(r));+ doc.update_dict(page_ref, |p| p.set(b"Annots".to_vec(), Object::Array(kept)))?;+ Ok(r)+ }++ /// A pop-up window for the comment `parent`, on its page.+ pub(crate) fn add_popup(doc: &mut Document, page: ObjRef, parent: ObjRef, rect: &[f64], open: bool) -> Result<(), DataError> {+ let mut p = Dict::new();+ p.set(b"Type".to_vec(), Object::name("Annot"));+ p.set(b"Subtype".to_vec(), Object::name("Popup"));+ p.set(b"Rect".to_vec(), arr(rect));+ p.set(b"Parent".to_vec(), Object::Ref(parent));+ p.set(b"Open".to_vec(), Object::Bool(open));+ let pr = doc.add(Object::Dict(p));+ doc.update_dict(parent, |d| d.set(b"Popup".to_vec(), Object::Ref(pr)))?;+ doc.update_dict(page, |pd| {+ if let Some(Object::Array(a)) = pd.get_mut(b"Annots") {+ a.push(Object::Ref(pr));+ }+ })?;+ Ok(())+ }++ pub(crate) fn import_xfdf(doc: &mut Document, text: &str) -> Result<Report, DataError> {+ check_form_xml_depth(text)?;+ let xml = parse_form_xml(text).map_err(|e| DataError::Malformed(e.to_string()))?;+ let root = xml.root_element();+ if root.tag_name().name() != "xfdf" {+ return Err(DataError::UnknownFormat);+ }+ let mut report = Report::default();+ let pages: Vec<ObjRef> = pdfcraft_model::pages(doc).iter().map(|p| p.obj).collect();+ // Comments: parents first, then replies (whose /IRT needs the parent's reference).+ let mut by_name: HashMap<String, ObjRef> = HashMap::new();+ let mut later: HashMap<ObjRef, String> = HashMap::new();+ if let Some(annots) = root.children().find(|c| c.has_tag_name("annots")) {+ for node in annots.children().filter(|c| c.is_element()) {+ let tag = node.tag_name().name().to_ascii_lowercase();+ let Some((subtype, _)) = SUBTYPES.iter().find(|(_, t)| *t == tag) else { continue };+ let Some(page) = node.attribute("page").and_then(|p| p.parse::<usize>().ok()).and_then(|p| pages.get(p).copied()) else { continue };+ let Some(d) = annot_from_xml(node, subtype, page) else { continue };+ let r = place(doc, page, d)?;+ // A later same-name record replaces this comment, including its reply relation.+ later.remove(&r);+ if let Some(nm) = node.attribute("name") {+ by_name.insert(nm.to_string(), r);+ }+ if let Some(irt) = node.attribute("inreplyto") {+ later.insert(r, irt.to_string());+ }+ // A pop-up window.+ if let Some(pop) = node.children().find(|c| c.has_tag_name("popup"))+ && let Some(rect) = pop.attribute("rect").map(csv).filter(|r| r.len() == 4)+ {+ add_popup(doc, page, r, &rect, pop.attribute("open") == Some("yes"))?;+ }+ report.comments += 1;+ }+ }+ for (r, irt) in later {+ if let Some(parent) = by_name.get(&irt).copied().or_else(|| find_by_name(doc, &irt)) {+ doc.update_dict(r, |d| d.set(b"IRT".to_vec(), Object::Ref(parent)))?;+ }+ }+ // Fields.+ if let Some(fields) = root.children().find(|c| c.has_tag_name("fields")) {+ let mut values = Vec::new();+ walk_xfdf(fields, "", &mut values, 0)?;+ apply_values(doc, &values, &mut report);+ }+ Ok(report)+ }++ pub(crate) fn find_by_name(doc: &Document, nm: &str) -> Option<ObjRef> {+ for p in pdfcraft_model::pages(doc) {+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {+ if let Some(r) = a.as_ref()+ && doc.get(r).as_dict().and_then(|d| text_of(doc, d, b"NM")).as_deref() == Some(nm)+ {+ return Some(r);+ }+ }+ }+ None+ }