PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M6.2: check boxes with non-UTF-8 state names show their mark when clicked (#536)
Chen Taof78f74164ca4
diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rsindex f13f53f8c..fc4e36d21 100644--- a/crates/forms/src/appearance.rs+++ b/crates/forms/src/appearance.rs@@ -331,7 +331,7 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_namelet s = width.min(height);let mark = check_mark(style, width / 2.0, height / 2.0, s);let mut nd = Dict::new();- nd.set(on_name.as_bytes().to_vec(), form(format!("{frame_c}{mark}")));+ nd.set(crate::name_bytes(on_name), form(format!("{frame_c}{mark}")));nd.set(b"Off".to_vec(), form(frame_c));let mut ap = Dict::new();ap.set(b"N".to_vec(), Object::Dict(nd));diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rsindex d51abda73..fd0133283 100644--- a/crates/forms/src/author.rs+++ b/crates/forms/src/author.rs@@ -809,7 +809,7 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S}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(v)),+ 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)),Some(None) => {d.remove(b"DV");diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rsindex 8d99b62cd..d86850319 100644--- a/crates/forms/src/lib.rs+++ b/crates/forms/src/lib.rs@@ -204,11 +204,49 @@ pub enum FieldValue {fn text_of(o: &Object) -> Option<String> {match o {Object::String(s) => Some(s.to_text()),- Object::Name(n) => Some(String::from_utf8_lossy(n).into_owned()),+ Object::Name(n) => Some(name_text(n)),_ => None,}}+/// A name object's bytes as text that [`name_bytes`] turns back into the same bytes. UTF-8 names+/// read as themselves; other bytes (Shift-JIS check box states such as 「はい」 in Japanese+/// forms) and `#` are written `#XX`, as in PDF name syntax.+pub fn name_text(bytes: &[u8]) -> String {+ let escape = |b: u8| format!("#{b:02X}");+ match std::str::from_utf8(bytes) {+ Ok(s) => s.replace('#', "#23"),+ Err(_) => bytes.iter().map(|&b| if (0x21..=0x7e).contains(&b) && b != b'#' { char::from(b).to_string() } else { escape(b) }).collect(),+ }+}++/// The bytes of the name written as `text` by [`name_text`] (`#XX` is the byte XX).+pub fn name_bytes(text: &str) -> Vec<u8> {+ let b = text.as_bytes();+ let mut out = Vec::with_capacity(b.len());+ let mut i = 0;+ while let Some(&c) = b.get(i) {+ let hex = |j: usize| b.get(j).and_then(|h| char::from(*h).to_digit(16));+ match (c, hex(i + 1), hex(i + 2)) {+ // Both digits are below 16, so the byte fits.+ (b'#', Some(hi), Some(lo)) => {+ out.push(u8::try_from(hi * 16 + lo).unwrap_or(b'#'));+ i += 3;+ }+ _ => {+ out.push(c);+ i += 1;+ }+ }+ }+ out+}++/// A name object from text written by [`name_text`].+fn name_obj(text: &str) -> Object {+ Object::Name(name_bytes(text))+}+/// At most this many `/State` entries of a set-layer-visibility action are read.const MAX_LAYER_STATE: usize = 1024;@@ -654,13 +692,13 @@ fn walk(.map(|ap| doc.resolve(ap)).and_then(|ap| ap.as_dict().and_then(|a| a.get(b"N").cloned())).and_then(|n| doc.resolve(&n).as_dict().cloned())- .and_then(|n| n.iter().map(|(k, _)| String::from_utf8_lossy(k).into_owned()).find(|k| k != "Off"));+ .and_then(|n| n.iter().map(|(k, _)| name_text(k)).find(|k| k != "Off"));Some(Widget {obj: w,page: page_of.get(&w).copied(),rect: [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])],on_state: on_state.filter(|_| matches!(kind, FieldKind::CheckBox | FieldKind::Radio)),- state: wd.name(b"AS").map(|s| String::from_utf8_lossy(s).into_owned()),+ state: wd.name(b"AS").map(name_text),tab: usize::MAX,locked: annot_flags & 128 != 0,hidden: annot_flags & (2 | 32) != 0,@@ -893,7 +931,7 @@ fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut/// Check boxes and radio buttons: `/V` on the field, `/AS` on each widget.fn set_states(doc: &mut Document, f: &Field, on: Option<&str>) -> Result<(), FormError> {let v = on.unwrap_or("Off");- doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), Object::name(v)))?;+ doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), name_obj(v)))?;for w in &f.widgets {let state = match (on, w.on_state.as_deref()) {(Some(c), Some(s)) if c == s => s,@@ -906,7 +944,7 @@ fn set_states(doc: &mut Document, f: &Field, on: Option<&str>) -> Result<(), Forlet ap = appearance::check_box_states(doc, w, f.kind, &on_name);doc.update_dict(w.obj, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;}- doc.update_dict(w.obj, |d| d.set(b"AS".to_vec(), Object::name(state)))?;+ doc.update_dict(w.obj, |d| d.set(b"AS".to_vec(), name_obj(state)))?;}Ok(())}diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rsindex 38fcfd8d5..8e846edb7 100644--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@ -185,6 +185,46 @@ fn check_boxes_and_radios_switch_states() {assert!(field(&fields(&doc), "agree").value.is_empty());}+#[test]+fn check_boxes_keep_non_utf8_state_names() {+ // Japanese forms often name a check box's on state 「はい」 in Shift-JIS: ticking it has to+ // write those exact bytes to /AS and /V, or no appearance matches and no mark shows.+ 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] >>".into(),+ "<< /Fields [5 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T (agree) /AS /Off /Rect [50 700 56 706] /P 3 0 R /AP << /N << /Off 6 0 R /#82#CD#82#A2 7 0 R >> >> >>".into(),+ "<< /Length 0 >>\nstream\n\nendstream".into(),+ "<< /Length 0 >>\nstream\n\nendstream".into(),+ ];+ let sjis_hai: &[u8] = b"\x82\xcd\x82\xa2";+ let mut doc = document(&objs);+ let all = fields(&doc);+ assert_eq!(field(&all, "agree").widgets[0].on_state.as_deref(), Some("#82#CD#82#A2"));+ set_value(&mut doc, "agree", &FieldValue::Check(true)).unwrap();+ let doc = reopen(&doc);+ let f = field(&fields(&doc), "agree").clone();+ let wd = doc.get(f.widgets[0].obj).as_dict().cloned().unwrap();+ assert_eq!(wd.name(b"AS"), Some(sjis_hai));+ assert_eq!(doc.get(f.obj).as_dict().unwrap().name(b"V"), Some(sjis_hai));+ assert_eq!(f.value, ["#82#CD#82#A2"]);+ let mut doc = doc;+ set_value(&mut doc, "agree", &FieldValue::Check(false)).unwrap();+ assert_eq!(doc.get(f.widgets[0].obj).as_dict().unwrap().name(b"AS"), Some(&b"Off"[..]));+}++#[test]+fn name_text_round_trips() {+ for bytes in [&b"Yes"[..], b"\x82\xcd\x82\xa2", "はい".as_bytes(), b"A#1", b"a b", b"", b"\xff#\x00"] {+ assert_eq!(name_bytes(&name_text(bytes)), bytes, "{bytes:?}");+ }+ assert_eq!(name_text("はい".as_bytes()), "はい");+ assert_eq!(name_text(b"A#1"), "A#231");+ // Malformed escapes stay as they are.+ assert_eq!(name_bytes("#G1#4"), b"#G1#4");+}+#[test]fn choices_accept_exports_or_display_text() {let mut doc = fixture();diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rsindex e52e2318d..190080611 100644--- a/crates/xfdf/src/lib.rs+++ b/crates/xfdf/src/lib.rs@@ -152,7 +152,7 @@ fn nums_of(doc: &Document, o: Option<&Object>) -> Vec<f64> {fn text_of(doc: &Document, d: &Dict, k: &[u8]) -> Option<String> {d.get(k).and_then(|o| match &*doc.resolve(o) {Object::String(s) => Some(s.to_text()),- Object::Name(n) => Some(String::from_utf8_lossy(n).into_owned()),+ Object::Name(n) => Some(pdfcraft_forms::name_text(n)),_ => None,})}@@ -370,7 +370,7 @@ pub fn export_fdf(doc: &Document, comments: bool, fields: bool, file: &str) -> Vmatch f.kind {FieldKind::CheckBox | FieldKind::Radio => {let v = f.value.first().cloned().unwrap_or_else(|| "Off".into());- pdfcraft_cos::serialize(&Object::Name(v.into_bytes()), &mut body);+ 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);@@ -759,7 +759,7 @@ fn walk_fdf(fdf: &Document, list: &[Object], prefix: &str, out: &mut Vec<(Stringif 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![String::from_utf8_lossy(n).into_owned()],+ Object::Name(n) => vec![pdfcraft_forms::name_text(n)],Object::Array(a) => a.iter().filter_map(|x| fdf.resolve(x).as_string().map(|s| s.to_text())).collect(),_ => Vec::new(),};diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rsindex 10b179818..ca1debe49 100644--- a/crates/xfdf/src/tests.rs+++ b/crates/xfdf/src/tests.rs@@ -132,6 +132,49 @@ fn fdf_round_trips_values_and_comments() {assert_eq!(comment_view(&dst), comment_view(&src), "replies keep their thread");}+/// One page with a check box whose on state is the Shift-JIS name 「はい」 (`/#82#CD#82#A2`).+fn shift_jis_check_box() -> Document {+ let objs = [+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>",+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>",+ "<< /Fields [5 0 R] >>",+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T (agree) /V /Off /AS /Off /Rect [50 700 64 714] /P 3 0 R /AP << /N << /Off 6 0 R /#82#CD#82#A2 6 0 R >> >> >>",+ "<< /Length 0 >>\nstream\n\nendstream",+ ];+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ 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{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ Document::open(Arc::new(out)).unwrap()+}++#[test]+fn non_utf8_check_box_states_round_trip() {+ let sjis_hai: &[u8] = b"\x82\xcd\x82\xa2";+ let mut src = shift_jis_check_box();+ set_value(&mut src, "agree", &FieldValue::Check(true)).unwrap();+ // FDF writes the state's own bytes, not its #XX text.+ let fdf = export_fdf(&src, false, true, "form.pdf");+ let name: &[u8] = b"/#82#CD#82#A2";+ assert!(fdf.windows(name.len()).any(|w| w == name), "{}", String::from_utf8_lossy(&fdf));+ for data in [fdf, export_xfdf(&src, false, true, "form.pdf").into_bytes()] {+ let mut dst = shift_jis_check_box();+ assert_eq!(import(&mut dst, &data).unwrap().fields, 1);+ assert_eq!(values(&dst), values(&src));+ let w = fields(&dst).into_iter().next().unwrap().widgets[0].obj;+ assert_eq!(dst.get(w).as_dict().unwrap().name(b"AS"), Some(sjis_hai));+ }+}+/// Who each comment replies to, by name, with its review state.fn threads(doc: &Document) -> Vec<(Option<String>, Option<String>, Option<String>)> {summaries(doc).into_iter().map(|s| (s.name, s.in_reply_to, s.state)).collect()