PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge origin/main into fix/radio-join-group-by-name
KenM76969cad099d01
diff --cc crates/forms/src/author/edit.rsindex 1b8caee92,d61cfe28f..0ffb8eb3e--- a/crates/forms/src/author/edit.rs+++ b/crates/forms/src/author/edit.rs@@@ -1,7 -1,6 +1,7 @@@-use super::look::{BorderStyle, da_string, patch_da, patch_widget_look, redraw_widgets};+use super::join::{check_join, join_radio_group};- use super::look::{BorderStyle, da_string, patch_da, patch_widget_look, redraw_widgets};++use super::look::{BorderStyle, da_string, patch_da, patch_widget_look, redraw_field, redraw_widgets};use super::tree::{attach, check_place, child_named, clash, detach, ensure_form, inherited, name_parts, own_inherited};- use super::*;+ 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]> {@@@ -71,71 -70,7 +71,9 @@@ pub fn set_props(doc: &mut Document, naif let Some(acts) = &props.actions {crate::set_field_actions(doc, name, acts)?;}- let mut new_name = name.to_string();- let new_name = rename_field(doc, &all, &f, name, props)?;+ // 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 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)?;- }- }++ 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 {@@@ -354,6 -245,127 +248,152 @@@}})?;}+ let only = apply_late_widget_props(doc, &f, props, &new_da, rotated_rect)?;- redraw_widgets(doc, &new_name, only)?;++ redraw_or_join(doc, &f, name, &new_name, join.as_ref(), 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> {++/// 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,+ };- if n.contains('.') {++ 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)++ 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 the whole group is redrawn as `new_name`.++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)?;++ redraw_field(doc, new_name)++ } else {++ redraw_widgets(doc, new_name, only)++ }++}+++ 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/author/join.rsindex d6fe51e49,000000000..e9fedbd65mode 100644,000000..100644--- a/crates/forms/src/author/join.rs+++ b/crates/forms/src/author/join.rs@@@ -1,129 -1,0 +1,129 @@@+//! Renaming a radio button to an existing radio group's name makes it a button of that group+//! (#4949): radio buttons are one group when they are widgets of one field (ISO 32000-2+//! §12.7.5.2.4), and a button's export value is the name of its "on" appearance state.++use std::collections::{HashMap, HashSet};++use super::lifecycle::{drop_from_calculation_order, split_merged, split_triggers};+use super::tree::{detach, list_of};- use super::*;++use super::{Dict, Document, Field, FormError, ObjRef, Object, invalid};++/// The keys a field that is also its own widget sheds when it becomes only a widget. Its `/AA`+/// keeps only the widget's own triggers.+const FIELD_ONLY_KEYS: [&[u8]; 15] = [b"T", b"FT", b"Kids", b"Ff", b"V", b"DV", b"Opt", b"TU", b"TM", b"MaxLen", b"Q", b"DS", b"RV", b"TI", b"I"];++/// Whether `field` holds `/Opt`, which its buttons' export values index (ISO 32000-2 §12.7.5.2).+fn has_opt(doc: &Document, field: ObjRef) -> bool {+ doc.get(field).as_dict().is_some_and(|d| d.contains(b"Opt"))+}++/// Refuse what [`join_radio_group`] can't do, before anything is written.+pub(super) fn check_join(doc: &Document, f: &Field, target: &Field) -> Result<(), FormError> {+ for x in [f, target] {+ if has_opt(doc, x.obj) {+ return invalid(format!("{} lists its export values in /Opt, so its buttons can't move between groups", x.name));+ }+ if x.widgets.is_empty() {+ return invalid(format!("{} has no button", x.name));+ }+ }+ if target.locked() {+ return invalid(format!("{} is locked: unlock it first", target.name));+ }+ Ok(())+}++/// Move every button of radio field `f` into radio field `target`. Each keeps its export value+/// unless a button of `target` already has it; then it takes the first free "ChoiceN", as a+/// button added to a group does, and buttons of `f` that shared a value still share the new one. A moved button shows selected only if it is `target`'s+/// selected value. `f` leaves the form; its own value and field-level properties go with it,+/// and `target`'s stay. Call [`check_join`] first.+pub(super) fn join_radio_group(doc: &mut Document, f: &Field, target: &Field) -> Result<(), FormError> {+ let theirs: HashSet<String> = target.widgets.iter().filter_map(|w| w.on_state.clone()).collect();+ let mut taken = theirs.clone();+ taken.extend(f.widgets.iter().filter_map(|w| w.on_state.clone()));+ // The group's value counts only when one of its buttons has it.+ let selected = target.value.first().filter(|v| theirs.contains(*v)).cloned();+ // Each clashing value of `f` gets one fresh name, shared by every button that had it. Of+ // `taken.len() + 1` names at least one is free, so the search always ends in one.+ let mut renamed: HashMap<String, String> = HashMap::new();+ for old in f.widgets.iter().filter_map(|w| w.on_state.as_deref()).filter(|s| theirs.contains(*s)) {+ if renamed.contains_key(old) {+ continue;+ }+ let Some(fresh) = (1..=taken.len().saturating_add(1)).map(|i| format!("Choice{i}")).find(|c| !taken.contains(c)) else {+ return invalid(format!("no free export value for {old}"));+ };+ taken.insert(fresh.clone());+ renamed.insert(old.to_owned(), fresh);+ }+ // A group that is its own one button gets a field with a separate widget first, so it can+ // hold more than one.+ if let [only] = target.widgets.as_slice()+ && only.obj == target.obj+ {+ split_merged(doc, target, only)?;+ }+ detach(doc, f.obj)?;+ // `f` is no longer a field, even when it stays on as a widget.+ drop_from_calculation_order(doc, |r| r == f.obj)?;+ let mut kids = Vec::with_capacity(f.widgets.len());+ for w in &f.widgets {+ let mut d = doc.get(w.obj).as_dict().cloned().unwrap_or_default();+ if w.obj == f.obj {+ for k in FIELD_ONLY_KEYS {+ d.remove(k);+ }+ let aa = d.get(b"AA").and_then(|a| doc.resolve(a).as_dict().cloned());+ match aa.as_ref().map(split_triggers) {+ Some((Some(widget_aa), _)) => d.set(b"AA".to_vec(), Object::Dict(widget_aa)),+ Some((None, _)) => {+ d.remove(b"AA");+ }+ None => {}+ }+ }+ let mut state = w.on_state.clone();+ if let Some(old) = w.on_state.as_deref()+ && let Some(fresh) = renamed.get(old)+ && rename_state(doc, &mut d, old, fresh)+ {+ state = Some(fresh.clone());+ }+ let on = state.is_some() && state == selected;+ let shown = match (&state, on) {+ (Some(s), true) => Object::Name(crate::name_bytes(s)),+ _ => Object::name("Off"),+ };+ d.set(b"AS".to_vec(), shown);+ d.set(b"Parent".to_vec(), Object::Ref(target.obj));+ doc.set(w.obj, Object::Dict(d));+ kids.push(Object::Ref(w.obj));+ }+ // `/Kids` may be an indirect array: read through it so the group's own buttons stay.+ let mut list = list_of(doc, target.obj, b"Kids");+ list.extend(kids);+ doc.update_dict(target.obj, |d| d.set(b"Kids".to_vec(), Object::Array(list)))?;+ Ok(())+}++/// Rename the appearance state `old` to `new` in the widget dictionary `d` (`/AP` `/N`, `/D`,+/// `/R`). A shared `/AP` or state dictionary is copied into `d` rather than renamed for its other+/// users. Whether `/N` had the state: when it didn't, nothing is changed.+fn rename_state(doc: &Document, d: &mut Dict, old: &str, new: &str) -> bool {+ let (old, new) = (crate::name_bytes(old), crate::name_bytes(new));+ let Some(mut ap) = d.get(b"AP").and_then(|a| doc.resolve(a).as_dict().cloned()) else { return false };+ let states = |ap: &Dict, key: &[u8]| ap.get(key).and_then(|s| doc.resolve(s).as_dict().cloned());+ if !states(&ap, b"N").is_some_and(|n| n.contains(&old)) {+ return false;+ }+ for key in [&b"N"[..], b"D", b"R"] {+ let Some(mut sub) = states(&ap, key) else { continue };+ if let Some(v) = sub.remove(&old) {+ sub.set(new.clone(), v);+ ap.set(key.to_vec(), Object::Dict(sub));+ }+ }+ d.set(b"AP".to_vec(), Object::Dict(ap));+ true+}diff --cc crates/ui-egui/src/dialogs.rsindex 2421af657,c21604a4d..8d21b50dd--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1552,10 -1721,16 +1727,16 @@@ fn finish_redactions_and_fields(app: &m));}}- app.views[i].prepare.selected = Some((name, d.widget));+ app.views[i].prepare.selected = Some((name, index));}}- if props_now && let Some(d) = app.comment_props.take() {+ }++ /// Edits built from the dialog's drafts.+ fn finish_edits(app: &mut PdfCraftApp, dialog: Dialog, req: &mut Pending) {+ if req.props_now+ && let Some(d) = app.comment_props.take()+ {let mut edits = crate::comment_props::edits(&d);match edits.len() {0 => {}