Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge origin/main into fix/choice-index-follows-options

KenM7668e78e788621
diff --cc crates/forms/src/author/edit.rs
index 01780ce6b,d61cfe28f..d163923e7
--- a/crates/forms/src/author/edit.rs
+++ b/crates/forms/src/author/edit.rs
@@@ -366,6 -245,127 +270,144 @@@ pub fn set_props(doc: &mut Document, na
}
})?;
}
+ let only = apply_late_widget_props(doc, &f, props, &new_da, rotated_rect)?;
++ scroll_list(doc, f.obj, list_picked)?;
+ redraw_widgets(doc, &new_name, only)?;
+ if props.calculate.is_some() {
+ crate::recalculate(doc)?;
+ }
+ Ok(new_name)
+ }
+
+ fn rename_field(doc: &mut Document, all: &[Field], f: &Field, name: &str, props: &FieldProps) -> Result<String, FormError> {
+ let mut new_name = name.to_string();
+ 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,
+ };
+ 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)
+ }
+
+ 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(())
+ }
+
++/// 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() {
diff --cc crates/forms/src/values.rs
index 7f02c6e81,37df5502d..c52af7b13
--- a/crates/forms/src/values.rs
+++ b/crates/forms/src/values.rs
@@@ -1,6 -1,9 +1,9 @@@
use super::appearances::{declares_pdfa, need_appearances};
use super::read::{acroform, field_flags, fields, page_refs};
- use super::*;
+ use super::{
- Dict, Document, Field, FieldEvent, FieldKind, FieldValue, FormError, NoScripts, ObjRef, Object, PdfString, Scripts, af, appearance, author,
- calc_order, flags, invalid, name_obj, scripting,
++ Dict, Document, Field, FieldEvent, FieldKind, FieldValue, FormError, NoScripts, ObjRef, Object, PdfString, Scripts, Widget, af, appearance,
++ author, calc_order, flags, invalid, name_obj, scripting,
+ };
// ── writing ─────────────────────────────────────────────────────────────────────────────────