Skip to main content

pdf/edit/
form.rs

1// edit::form -- filling in the fields of an interactive form (ISO 32000-1, 12.7) and flattening
2// them into their pages.
3//
4// set_field finds a terminal field by its full name (the partial names of the parents joined by
5// dots), checks the value against the field's kind and gives the field its /V and each widget
6// a new normal appearance (appear.rs) or, for buttons, its /AS:
7//
8//   Text(s)          a text field (MaxLen counts characters), an editable combo box
9//   Choice(values)   a list box or combo box: export values or the texts shown (/Opt), several
10//                    only with MultiSelect; a radio button group or check box: the export
11//                    value or state name of the button to turn on (none: all off)
12//   Check(on)        a check box
13//
14// A text field's /RV is dropped (it would show the old value), the AcroForm's /XFA too (Acrobat
15// would show the XFA data instead).  A form with NeedAppearances gets the appearances of all its
16// fields with the first value set, and the flag goes (as Acrobat saves): a viewer would else
17// make them again in the /DA font and lose what a fallback font shows.  Read-only fields are filled as any other (Field::read_only
18// says which they are); signature fields and push buttons take no value.  JavaScript (format,
19// calculate, /AA) is not run.
20//
21// The text is set in the font of /DA from the form's /DR when it has every character (a simple
22// font: its encoding; an embedded subset only for the codes it has widths for).  Otherwise the
23// whole text takes fonts of the FontSource (set_fonts; SystemFonts by default): a sans-serif
24// substitute of the /DA font for Latin, Greek and Cyrillic, and one of the language for other
25// scripts (kana ja, hangul ko, Han after set_lang or the document's /Lang, else zh-Hans; Arabic,
26// Hebrew, Thai, Indic and others by their language, then the usual families of Windows, macOS
27// and Linux for the script), each the first that has the characters it is for; embedded as
28// subsets in the update, once for all its appearances.  /DA itself stays as it is.  Drawing
29// (widget_ap) makes appearances from the same parts, in the /DA font alone.
30//
31// flatten draws each visible widget's appearance into its page (a form XObject after the page's
32// content, which is wrapped in q .. Q; under the widget's /OC as marked content) and takes the
33// widget off the page and the field out of the form, parents left without kids too; flattening
34// every field removes the AcroForm.  Signature fields stay.  Fields whose appearance is missing
35// or that NeedAppearances asks for get one first, from the value they have (/V inherited too,
36// /I choosing among options of one export value); their values do not change, and an
37// appearance that cannot be made again stays as it is.  A form with NeedAppearances keeps the
38// flag when one of its fields' appearances cannot be made.
39//
40// set_field and flatten are transactions: when they fail, the update is as it was (the objects
41// they added gone, those they changed as before).
42//
43// Fields are indirect objects (12.7.3.1); one that is not is changed inside the object that
44// holds it.
45
46use super::Update;
47use crate::appear::{self, Color, Da, Face, Frame, Text};
48use crate::font::FontData;
49use crate::read::font::Font;
50use crate::read::{Dict, Error, FontQuery, Name, Object, Ref, SystemFonts};
51use alloc::collections::{BTreeMap, BTreeSet};
52use alloc::format;
53use alloc::rc::Rc;
54use alloc::string::String;
55use alloc::vec;
56use alloc::vec::Vec;
57
58/// a value for Update::set_field
59#[derive(Clone, Copy, Debug, PartialEq)]
60pub enum FieldValue<'a> {
61    Text(&'a str),
62    Check(bool),
63    Choice(&'a [&'a str]),
64}
65
66const FF_MULTILINE: u32 = 1 << 12;
67const FF_PASSWORD: u32 = 1 << 13;
68const FF_NO_TOGGLE_OFF: u32 = 1 << 14;
69const FF_RADIO: u32 = 1 << 15;
70const FF_PUSH: u32 = 1 << 16;
71const FF_COMBO: u32 = 1 << 17;
72const FF_EDIT: u32 = 1 << 18;
73const FF_MULTISELECT: u32 = 1 << 21;
74const FF_COMB: u32 = 1 << 24;
75const FF_UNISON: u32 = 1 << 25;
76
77/// the nodes of the field tree one walk visits, and how deep it goes
78const MAX_NODES: usize = 1 << 20;
79const MAX_DEPTH: u32 = 64;
80/// the most fallback fonts one update embeds
81const MAX_FALLBACKS: usize = 8;
82/// the characters of a value whose fonts are looked for (what appear.rs shows at most)
83const MAX_SHOWN: usize = 32 * 1024;
84
85/// one step from an indirect object to a direct one inside it
86#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
87enum Step {
88    Key(Name),
89    Index(usize),
90}
91
92/// where a dictionary is: an indirect object, or a path inside one
93#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
94struct Loc {
95    holder: Ref,
96    path: Vec<Step>,
97}
98
99impl Loc {
100    fn of(r: Ref) -> Loc {
101        Loc { holder: r, path: Vec::new() }
102    }
103
104    fn child(&self, key: &str, i: usize) -> Loc {
105        let mut path = self.path.clone();
106        path.push(Step::Key(Name(key.as_bytes().to_vec())));
107        path.push(Step::Index(i));
108        Loc { holder: self.holder, path }
109    }
110
111    fn key(&self, key: &str) -> Loc {
112        let mut path = self.path.clone();
113        path.push(Step::Key(Name(key.as_bytes().to_vec())));
114        Loc { holder: self.holder, path }
115    }
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119enum Kind {
120    Text,
121    Check,
122    Radio,
123    Push,
124    Combo,
125    List,
126    Sig,
127    Unknown,
128}
129
130/// a terminal field as a walk finds it
131#[derive(Clone)]
132struct Found {
133    name: String,
134    loc: Loc,
135    dict: Dict,
136    kind: Kind,
137    ff: u32,
138    /// inherited /DA, /Q, /V and /MaxLen
139    da: Option<Vec<u8>>,
140    q: Option<i64>,
141    v: Object,
142    max_len: Option<i64>,
143    /// the widgets: the field itself when it is its only one
144    widgets: Vec<(Loc, Dict)>,
145    /// the array that holds the field and its place there
146    slot: (Loc, usize),
147}
148
149impl Update<'_> {
150    /// where fallback fonts come from (SystemFonts by default)
151    pub fn set_fonts(&mut self, fonts: Rc<dyn crate::read::FontSource>) {
152        self.fonts = Some(fonts);
153    }
154
155    /// the language of Han characters in values (zh-Hans, zh-Hant, ja, ko; else the
156    /// document's /Lang)
157    pub fn set_lang(&mut self, lang: &str) {
158        self.lang = Some(String::from(lang));
159    }
160
161    // ------------------------------------------------------------------ locations
162
163    fn root(&self) -> Result<Ref, Error> {
164        self.doc.trailer().get("Root").and_then(Object::as_ref).ok_or(Error::Damaged("no catalog to change"))
165    }
166
167    /// the object at a location (resolved)
168    fn load(&self, loc: &Loc) -> Object {
169        let mut cur = self.get(loc.holder);
170        for s in &loc.path {
171            cur = match (s, &cur) {
172                (Step::Key(k), Object::Dict(d)) => d.get_bytes(&k.0).cloned().unwrap_or_default(),
173                (Step::Key(k), Object::Stream(st)) => st.dict.get_bytes(&k.0).cloned().unwrap_or_default(),
174                (Step::Index(i), Object::Array(a)) => a.get(*i).cloned().unwrap_or_default(),
175                _ => Object::Null,
176            };
177            cur = match cur {
178                Object::Ref(r) => self.resolve(&Object::Ref(r)),
179                o => o,
180            };
181        }
182        cur
183    }
184
185    /// the object at a location becomes `v` (the indirect object holding it is written again)
186    fn store(&mut self, loc: &Loc, v: Object) -> Result<(), Error> {
187        if loc.path.is_empty() {
188            return match self.get(loc.holder) {
189                Object::Stream(s) => {
190                    let Object::Dict(d) = v else { return Err(Error::Invalid("a stream replaced by another object")) };
191                    let mut s = *s;
192                    s.dict = d;
193                    self.set(loc.holder, Object::Stream(alloc::boxed::Box::new(s)))
194                }
195                _ => self.set(loc.holder, v),
196            };
197        }
198        let mut top = self.get(loc.holder);
199        put(&mut top, &loc.path, v, 0)?;
200        self.set(loc.holder, top)
201    }
202
203    /// several stores, each object that holds some of them loaded and written once (a field
204    /// of many direct widgets)
205    fn store_all(&mut self, list: Vec<(Loc, Object)>) -> Result<(), Error> {
206        let mut groups: BTreeMap<Ref, Vec<(Vec<Step>, Object)>> = BTreeMap::new();
207        for (loc, v) in list {
208            groups.entry(loc.holder).or_default().push((loc.path, v));
209        }
210        for (holder, items) in groups {
211            let mut top = self.get(holder);
212            for (path, v) in items {
213                if !path.is_empty() {
214                    put(&mut top, &path, v, 0)?;
215                    continue;
216                }
217                top = match (top, v) {
218                    (Object::Stream(mut s), Object::Dict(d)) => {
219                        s.dict = d;
220                        Object::Stream(s)
221                    }
222                    (_, v) => v,
223                };
224            }
225            self.set(holder, top)?;
226        }
227        Ok(())
228    }
229
230    /// widget i of a field as it is now: the field's new dictionary when the field is its
231    /// widget, else the dictionary the walk found
232    fn widget_now(f: &Found, i: usize, field_now: &Dict) -> Dict {
233        if f.widgets[i].0 == f.loc { field_now.clone() } else { f.widgets[i].1.clone() }
234    }
235
236    // ------------------------------------------------------------------ the field tree
237
238    /// the AcroForm and where it is
239    fn acroform(&self) -> Option<(Loc, Dict)> {
240        let root = self.root().ok()?;
241        let cat = self.dict(&Object::Ref(root));
242        match cat.get("AcroForm")? {
243            Object::Ref(r) => Some((Loc::of(*r), self.dict(&Object::Ref(*r)))),
244            Object::Dict(d) => Some((Loc::of(root).key("AcroForm"), d.clone())),
245            _ => None,
246        }
247    }
248
249    /// every terminal field
250    fn walk(&self) -> Vec<Found> {
251        let Some((aloc, form)) = self.acroform() else { return Vec::new() };
252        let roots = match self.resolve(form.get("Fields").unwrap_or(&Object::Null)) {
253            Object::Array(a) => a,
254            _ => return Vec::new(),
255        };
256        let fields_loc = aloc.key("Fields");
257        // (object, location, slot, parent's name, FT, Ff, DA, Q, V, MaxLen, depth)
258        type Node = (Object, Loc, (Loc, usize), String, Option<Vec<u8>>, Option<u32>, Option<Vec<u8>>, Option<i64>, Object, Option<i64>, u32);
259        let fields_ref = form.get("Fields").and_then(Object::as_ref);
260        let array_loc = |l: &Loc, key: &str, r: Option<Ref>| match r {
261            Some(r) => Loc::of(r),
262            None => l.key(key),
263        };
264        let froot = array_loc(&aloc, "Fields", fields_ref);
265        let mut stack: Vec<Node> = roots
266            .iter()
267            .enumerate()
268            .rev()
269            .map(|(i, o)| {
270                let loc = match o.as_ref() {
271                    Some(r) => Loc::of(r),
272                    None => match fields_ref {
273                        Some(fr) => Loc { holder: fr, path: vec![Step::Index(i)] },
274                        None => fields_loc.child_index(i),
275                    },
276                };
277                (o.clone(), loc, (froot.clone(), i), String::new(), None, None, None, None, Object::Null, None, 0)
278            })
279            .collect();
280        let mut out = Vec::new();
281        let mut seen = BTreeSet::new();
282        let mut n = 0;
283        while let Some((o, loc, slot, parent, ft, ff, da, q, v, max_len, depth)) = stack.pop() {
284            n += 1;
285            if n > MAX_NODES || depth > MAX_DEPTH {
286                break;
287            }
288            if let Some(r) = o.as_ref() {
289                if !seen.insert(r) {
290                    continue;
291                }
292            }
293            let d = self.dict(&o);
294            if d.is_empty() {
295                continue;
296            }
297            let name = match self.resolve(d.get("T").unwrap_or(&Object::Null)) {
298                Object::String(t) if parent.is_empty() => crate::read::text_string(&t),
299                Object::String(t) => format!("{parent}.{}", crate::read::text_string(&t)),
300                _ => parent.clone(),
301            };
302            let ft = d.name("FT").map(<[u8]>::to_vec).or(ft);
303            let ff = self.resolve(d.get("Ff").unwrap_or(&Object::Null)).as_int().map(|f| f as u32).or(ff);
304            let da = self.resolve(d.get("DA").unwrap_or(&Object::Null)).as_bytes().map(<[u8]>::to_vec).or(da);
305            let q = self.resolve(d.get("Q").unwrap_or(&Object::Null)).as_int().or(q);
306            let v = match d.get("V") {
307                Some(x) => self.resolve(x),
308                None => v,
309            };
310            let max_len = self.resolve(d.get("MaxLen").unwrap_or(&Object::Null)).as_int().or(max_len);
311            let kids_ref = d.get("Kids").and_then(Object::as_ref);
312            let kids = match self.resolve(d.get("Kids").unwrap_or(&Object::Null)) {
313                Object::Array(a) => a,
314                _ => Vec::new(),
315            };
316            let kid_loc = |i: usize, k: &Object| match k.as_ref() {
317                Some(r) => Loc::of(r),
318                None => match kids_ref {
319                    Some(kr) => Loc { holder: kr, path: vec![Step::Index(i)] },
320                    None => loc.child("Kids", i),
321                },
322            };
323            let kids_array = array_loc(&loc, "Kids", kids_ref);
324            let field_kids: Vec<usize> = (0..kids.len()).filter(|&i| self.dict(&kids[i]).contains("T")).collect();
325            if !field_kids.is_empty() {
326                for &i in field_kids.iter().rev() {
327                    if kids[i].as_ref().is_some_and(|r| seen.contains(&r)) {
328                        continue;
329                    }
330                    stack.push((kids[i].clone(), kid_loc(i, &kids[i]), (kids_array.clone(), i), name.clone(), ft.clone(), ff, da.clone(), q, v.clone(), max_len, depth + 1));
331                }
332                continue;
333            }
334            let flags = ff.unwrap_or(0);
335            let kind = match ft.as_deref() {
336                Some(b"Tx") => Kind::Text,
337                Some(b"Btn") if flags & FF_PUSH != 0 => Kind::Push,
338                Some(b"Btn") if flags & FF_RADIO != 0 => Kind::Radio,
339                Some(b"Btn") => Kind::Check,
340                Some(b"Ch") if flags & FF_COMBO != 0 => Kind::Combo,
341                Some(b"Ch") => Kind::List,
342                Some(b"Sig") => Kind::Sig,
343                _ => Kind::Unknown,
344            };
345            let widgets = if kids.is_empty() {
346                vec![(loc.clone(), d.clone())]
347            } else {
348                kids.iter().enumerate().take(1 << 16).map(|(i, k)| (kid_loc(i, k), self.dict(k))).filter(|(_, wd)| !wd.is_empty()).collect()
349            };
350            out.push(Found { name, loc, dict: d, kind, ff: flags, da, q, v, max_len, widgets, slot });
351        }
352        out
353    }
354
355    fn find(&self, name: &str) -> Result<Found, Error> {
356        self.walk().into_iter().find(|f| f.name == name).ok_or(Error::Invalid("no field of that name"))
357    }
358
359    // ------------------------------------------------------------------ filling in
360
361    /// fill in a field (see the head of edit/form.rs); when it fails, the update is as it was
362    pub fn set_field(&mut self, name: &str, value: FieldValue) -> Result<(), Error> {
363        self.transaction(|u| u.set_field_now(name, value))
364    }
365
366    fn set_field_now(&mut self, name: &str, value: FieldValue) -> Result<(), Error> {
367        let f = self.find(name)?;
368        match f.kind {
369            Kind::Text => {
370                let FieldValue::Text(s) = value else { return Err(Error::Invalid("a text field takes text")) };
371                self.fill_text(&f, s, false)?;
372            }
373            Kind::Combo | Kind::List => {
374                let one;
375                let values: &[&str] = match value {
376                    FieldValue::Choice(v) => v,
377                    FieldValue::Text(s) => {
378                        one = [s];
379                        &one
380                    }
381                    FieldValue::Check(_) => return Err(Error::Invalid("a choice field takes a choice")),
382                };
383                let (chosen, custom) = self.choose(&f, values)?;
384                self.apply_choice(&f, &chosen, custom, false)?;
385            }
386            Kind::Check | Kind::Radio => self.fill_button(&f, value)?,
387            Kind::Push => return Err(Error::Invalid("a push button takes no value")),
388            Kind::Sig => return Err(Error::Invalid("a signature field is signed, not filled in")),
389            Kind::Unknown => return Err(Error::Invalid("a field of no known kind")),
390        }
391        if !self.filled {
392            self.filled = true;
393            if let Some((_, form)) = self.acroform() {
394                // NeedAppearances: every other field gets its appearance now and the flag goes
395                // (as Acrobat saves), or a viewer would make them again in the /DA font and lose
396                // what a fallback font shows
397                let need = self.resolve(form.get("NeedAppearances").unwrap_or(&Object::Null)).as_bool() == Some(true);
398                // the flag stays when a field's appearance cannot be made
399                let mut all_made = true;
400                if need {
401                    for f in self.walk() {
402                        if f.name != name && self.refresh(&f, true).is_err() {
403                            all_made = false;
404                        }
405                    }
406                }
407                if let Some((aloc, mut form)) = self.acroform() {
408                    let xfa = form.remove("XFA").is_some();
409                    let na = all_made && form.remove("NeedAppearances").is_some();
410                    if xfa || na {
411                        self.store(&aloc, Object::Dict(form))?;
412                    }
413                }
414            }
415        }
416        Ok(())
417    }
418
419    /// a text field's value `s` (with `keep`: the appearances alone, of the value it has)
420    fn fill_text(&mut self, f: &Found, s: &str, keep: bool) -> Result<(), Error> {
421        let mut d = self.dict_at(&f.loc);
422        if !keep {
423            if let Some(max) = f.max_len {
424                if max >= 0 && s.chars().count() as i64 > max {
425                    return Err(Error::Invalid("longer than the field's MaxLen"));
426                }
427            }
428            d.insert("V", text_obj(s));
429            d.remove("RV");
430            self.store(&f.loc, Object::Dict(d.clone()))?;
431        }
432        let max_len = f.max_len.and_then(|m| u32::try_from(m).ok());
433        let mut batch = Vec::new();
434        for i in 0..f.widgets.len() {
435            let wd = Self::widget_now(f, i, &d);
436            let t = Text {
437                value: s,
438                q: 0,
439                multiline: f.ff & FF_MULTILINE != 0,
440                password: f.ff & FF_PASSWORD != 0,
441                comb: (f.ff & FF_COMB != 0 && f.ff & (FF_MULTILINE | FF_PASSWORD) == 0).then_some(max_len).flatten(),
442            };
443            let ap = self.text_ap(f, &wd, &t, None)?;
444            batch.push((f.widgets[i].0.clone(), Object::Dict(with_ap(wd, ap))));
445        }
446        self.store_all(batch)
447    }
448
449    /// the dictionary at a location as the update has it now
450    fn dict_at(&self, loc: &Loc) -> Dict {
451        match self.load(loc) {
452            Object::Dict(d) => d,
453            Object::Stream(s) => s.dict,
454            _ => Dict::new(),
455        }
456    }
457
458    /// the options of a choice field: (export value, text shown)
459    fn options(&self, d: &Dict) -> Vec<(String, String)> {
460        options_of(self, d)
461    }
462
463    /// the options `values` name: their places in /Opt, or a combo box's own text
464    fn choose(&self, f: &Found, values: &[&str]) -> Result<(Vec<usize>, Option<String>), Error> {
465        let opts = self.options(&f.dict);
466        if values.len() > 1 && f.ff & FF_MULTISELECT == 0 {
467            return Err(Error::Invalid("several values for a field without MultiSelect"));
468        }
469        let mut chosen: Vec<usize> = Vec::new();
470        let mut custom = None;
471        for v in values {
472            match opts.iter().position(|o| o.0 == *v).or_else(|| opts.iter().position(|o| o.1 == *v)) {
473                Some(i) => chosen.push(i),
474                None if f.kind == Kind::Combo && f.ff & FF_EDIT != 0 && values.len() == 1 => custom = Some(String::from(*v)),
475                None => return Err(Error::Invalid("a value the field does not offer")),
476            }
477        }
478        chosen.sort_unstable();
479        chosen.dedup();
480        Ok((chosen, custom))
481    }
482
483    /// a choice field's options at `chosen` (or a combo box's own text) as its value and
484    /// appearances (with `keep`: the appearances alone)
485    fn apply_choice(&mut self, f: &Found, chosen: &[usize], custom: Option<String>, keep: bool) -> Result<(), Error> {
486        let opts = self.options(&f.dict);
487        let chosen: Vec<usize> = chosen.iter().copied().filter(|&i| i < opts.len()).collect();
488        let mut d = self.dict_at(&f.loc);
489        if !keep {
490            let exports: Vec<Object> = chosen.iter().map(|&i| text_obj(&opts[i].0)).collect();
491            match (&custom, exports.len()) {
492                (Some(c), _) => {
493                    d.insert("V", text_obj(c));
494                }
495                (None, 0) => {
496                    d.remove("V");
497                }
498                (None, 1) => {
499                    d.insert("V", exports[0].clone());
500                }
501                _ => {
502                    d.insert("V", Object::Array(exports));
503                }
504            }
505            if f.kind == Kind::List && custom.is_none() && !chosen.is_empty() {
506                d.insert("I", Object::Array(chosen.iter().map(|&i| Object::Int(i as i64)).collect()));
507            } else {
508                d.remove("I");
509            }
510            self.store(&f.loc, Object::Dict(d.clone()))?;
511        }
512        let shown: String = match &custom {
513            Some(c) => c.clone(),
514            None => chosen.first().map(|&i| opts[i].1.clone()).unwrap_or_default(),
515        };
516        let texts: Vec<String> = opts.iter().map(|o| o.1.clone()).collect();
517        let top = self.resolve(f.dict.get("TI").unwrap_or(&Object::Null)).as_int().and_then(|t| usize::try_from(t).ok()).unwrap_or(0).min(texts.len());
518        let mut batch = Vec::new();
519        for i in 0..f.widgets.len() {
520            let wd = Self::widget_now(f, i, &d);
521            let ap = if f.kind == Kind::List {
522                self.text_ap(f, &wd, &Text { value: "", q: 0, multiline: false, password: false, comb: None }, Some((&texts, &chosen, top)))?
523            } else {
524                self.text_ap(f, &wd, &Text { value: &shown, q: 0, multiline: false, password: false, comb: None }, None)?
525            };
526            batch.push((f.widgets[i].0.clone(), Object::Dict(with_ap(wd, ap))));
527        }
528        self.store_all(batch)
529    }
530
531    /// the on state of a button widget: its /AP /N state other than Off, else the export value
532    /// of /Opt for the widget's place
533    fn on_state(&self, wd: &Dict, i: usize, opts: &[(String, String)]) -> Option<Vec<u8>> {
534        let ap = self.dict(wd.get("AP").unwrap_or(&Object::Null));
535        if let Object::Dict(n) = self.resolve(ap.get("N").unwrap_or(&Object::Null)) {
536            if let Some((k, _)) = n.iter().find(|(k, _)| k.0 != b"Off") {
537                return Some(k.0.clone());
538            }
539        }
540        opts.get(i).map(|o| o.0.as_bytes().to_vec())
541    }
542
543    fn fill_button(&mut self, f: &Found, value: FieldValue) -> Result<(), Error> {
544        let opts = self.options(&f.dict);
545        // a check box widget without a state of its own is on as /Yes
546        let states: Vec<Option<Vec<u8>>> = f.widgets.iter().enumerate().map(|(i, (_, wd))| self.on_state(wd, i, &opts).or_else(|| (f.kind == Kind::Check).then(|| b"Yes".to_vec()))).collect();
547        // the state to turn on (None: all off)
548        let want: Option<Vec<u8>> = match value {
549            FieldValue::Check(true) if f.kind == Kind::Check => Some(states.iter().flatten().next().cloned().unwrap_or_else(|| b"Yes".to_vec())),
550            FieldValue::Check(true) => return Err(Error::Invalid("a radio button group takes the value of the button to turn on")),
551            FieldValue::Check(false) => None,
552            FieldValue::Choice([]) => None,
553            FieldValue::Choice([v]) => {
554                let by_opt = opts.iter().position(|o| o.0 == *v).and_then(|i| states.get(i).cloned().flatten());
555                let by_name = states.iter().flatten().find(|s| s.as_slice() == v.as_bytes()).cloned();
556                Some(by_opt.or(by_name).ok_or(Error::Invalid("a value none of the buttons has"))?)
557            }
558            FieldValue::Choice(_) => return Err(Error::Invalid("one value for a button field")),
559            FieldValue::Text(_) => return Err(Error::Invalid("a button takes Check or Choice")),
560        };
561        if want.is_none() && f.kind == Kind::Radio && f.ff & FF_NO_TOGGLE_OFF != 0 {
562            return Err(Error::Invalid("a radio button group with NoToggleToOff"));
563        }
564        let mut d = self.dict_at(&f.loc);
565        d.insert("V", Object::Name(Name(want.clone().unwrap_or_else(|| b"Off".to_vec()))));
566        self.store(&f.loc, Object::Dict(d.clone()))?;
567        let mut turned = false;
568        let mut batch = Vec::new();
569        for i in 0..f.widgets.len() {
570            let mut wd = Self::widget_now(f, i, &d);
571            let on = match (&want, &states[i]) {
572                (Some(w), Some(s)) if w == s => !(turned && f.kind == Kind::Radio && f.ff & FF_UNISON == 0),
573                _ => false,
574            };
575            turned |= on;
576            let state = if on { want.clone().unwrap_or_default() } else { b"Off".to_vec() };
577            wd.insert("AS", Object::Name(Name(state.clone())));
578            // a widget without the appearance of its state gets both
579            let ap = self.dict(wd.get("AP").unwrap_or(&Object::Null));
580            let has = match self.resolve(ap.get("N").unwrap_or(&Object::Null)) {
581                Object::Dict(n) => n.contains(core::str::from_utf8(&state).unwrap_or("Off")),
582                _ => false,
583            };
584            if !has {
585                if let Some(on_name) = states[i].clone() {
586                    let n = self.button_aps(f, &wd, &on_name)?;
587                    let mut apd = Dict::new();
588                    apd.insert("N", Object::Dict(n));
589                    wd.insert("AP", Object::Dict(apd));
590                }
591            }
592            batch.push((f.widgets[i].0.clone(), Object::Dict(wd)));
593        }
594        self.store_all(batch)
595    }
596
597    /// the appearances a check box's or radio button's widgets lack, their /AS from the value
598    /// where they have none; the value stays
599    fn button_refresh(&mut self, f: &Found) -> Result<(), Error> {
600        let opts = self.options(&f.dict);
601        let v = f.v.as_name().map(<[u8]>::to_vec);
602        let mut batch = Vec::new();
603        for (i, (wloc, wd)) in f.widgets.iter().enumerate() {
604            if self.dict(wd.get("AP").unwrap_or(&Object::Null)).contains("N") {
605                continue;
606            }
607            let Some(on) = self.on_state(wd, i, &opts).or_else(|| (f.kind == Kind::Check).then(|| b"Yes".to_vec())) else { continue };
608            let mut wd = wd.clone();
609            let n = self.button_aps(f, &wd, &on)?;
610            let mut apd = Dict::new();
611            apd.insert("N", Object::Dict(n));
612            wd.insert("AP", Object::Dict(apd));
613            if !wd.contains("AS") {
614                let state = if v.as_deref() == Some(on.as_slice()) { on } else { b"Off".to_vec() };
615                wd.insert("AS", Object::Name(Name(state)));
616            }
617            batch.push((wloc.clone(), Object::Dict(wd)));
618        }
619        self.store_all(batch)
620    }
621
622    // ------------------------------------------------------------------ appearances
623
624    fn frame(&self, wd: &Dict) -> Frame {
625        frame_of(self, wd)
626    }
627
628    fn da(&self, f: &Found, wd: &Dict, form: &Dict) -> Da {
629        da_of(self, wd, f.da.clone(), form)
630    }
631
632    /// a text field's, combo box's or list box's normal appearance, as a new stream
633    fn text_ap(&mut self, f: &Found, wd: &Dict, t: &Text, list: Option<(&[String], &[usize], usize)>) -> Result<Ref, Error> {
634        let form = self.acroform().map(|a| a.1).unwrap_or_default();
635        let frame = self.frame(wd);
636        let da = self.da(f, wd, &form);
637        let q = self.resolve(wd.get("Q").unwrap_or(&Object::Null)).as_int().or(f.q).or_else(|| self.resolve(form.get("Q").unwrap_or(&Object::Null)).as_int()).unwrap_or(0).clamp(0, 2) as u8;
638        let t = Text { q, ..*t };
639        let all: String = match list {
640            Some((opts, _, top)) => opts.iter().skip(top).take(appear::MAX_LIST_ROWS).map(String::as_str).collect::<Vec<_>>().join(" "),
641            None if t.password => "*".into(),
642            None => String::from(t.value),
643        };
644        // the /DA font, when it has every character
645        let (da_font, codes, _) = da_codes(self, &form, &da, None);
646        let mut resources = Dict::new();
647        let mut fonts_res = Dict::new();
648        let covers = all.chars().filter(|c| !matches!(c, '\n' | '\r')).all(|c| codes.contains_key(&c));
649        let ap = match covers {
650            true => {
651                fonts_res.insert_bytes(&da.font, da_font.clone().unwrap_or_else(|| Object::Dict(standard_font(b"Helvetica"))));
652                let map = |c: char| codes.get(&c).copied();
653                let mut face = Face::Simple { name: &da.font, map: &map };
654                build(&frame, &da, &mut face, &t, list)
655            }
656            false => {
657                let base = da_font.as_ref().map(|o| self.dict(o)).and_then(|d| d.name("BaseFont").map(|b| String::from_utf8_lossy(b).into_owned())).unwrap_or_else(|| "Helvetica".into());
658                let pick = self.fallbacks(&all, &base)?;
659                let names: Vec<Vec<u8>> = (0..self.fallback_fonts.len()).map(|i| format!("JF{i}").into_bytes()).collect();
660                for &i in &pick {
661                    fonts_res.insert_bytes(&names[i], Object::Ref(self.fallback_meta[i].1[0]));
662                }
663                let mut face = Face::Shaped { names: &names, fonts: &mut self.fallback_fonts, pick: &pick };
664                build(&frame, &da, &mut face, &t, list)
665            }
666        };
667        resources.insert("Font", Object::Dict(fonts_res));
668        self.add_form(&ap, resources)
669    }
670
671    /// the appearances of a check box or radio button that lacks them: << /on .. /Off .. >>
672    fn button_aps(&mut self, f: &Found, wd: &Dict, on: &[u8]) -> Result<Dict, Error> {
673        let form = self.acroform().map(|a| a.1).unwrap_or_default();
674        let frame = self.frame(wd);
675        let da = self.da(f, wd, &form);
676        let mk = self.dict(wd.get("MK").unwrap_or(&Object::Null));
677        let ca = self.resolve(mk.get("CA").unwrap_or(&Object::Null)).as_bytes().and_then(|b| b.first().copied()).unwrap_or(if f.kind == Kind::Radio { b'l' } else { b'4' });
678        let round = f.kind == Kind::Radio;
679        let res = Dict::new();
680        let on_ap = appear::check(&frame, &da, ca, true, round);
681        let off_ap = appear::check(&frame, &da, ca, false, round);
682        let on_ref = self.add_form(&on_ap, res.clone())?;
683        let off_ref = self.add_form(&off_ap, res)?;
684        let mut n = Dict::new();
685        n.insert_bytes(on, Object::Ref(on_ref));
686        n.insert("Off", Object::Ref(off_ref));
687        Ok(n)
688    }
689
690    /// an appearance as a form XObject of the update
691    fn add_form(&mut self, ap: &appear::Ap, resources: Dict) -> Result<Ref, Error> {
692        let mut d = Dict::new();
693        d.insert("Type", Object::name("XObject"));
694        d.insert("Subtype", Object::name("Form"));
695        d.insert("BBox", nums(&ap.bbox));
696        if let Some(m) = &ap.matrix {
697            d.insert("Matrix", nums(m));
698        }
699        d.insert("Resources", Object::Dict(resources));
700        self.add_stream(d, &ap.content)
701    }
702
703    /// fonts of the FontSource for `text` (the update's fallbacks, loaded once): their places
704    /// in self.fallback, the Latin one first
705    fn fallbacks(&mut self, text: &str, base: &str) -> Result<Vec<usize>, Error> {
706        let lower = base.to_ascii_lowercase();
707        let bold = lower.contains("bold");
708        let italic = lower.contains("italic") || lower.contains("oblique");
709        let serif = lower.contains("times") || lower.contains("serif") && !lower.contains("sans") || lower.contains("roman");
710        let han = self.han_lang(text);
711        let mut langs: Vec<Option<String>> = vec![None];
712        for c in text.chars().take(MAX_SHOWN) {
713            let l = script_lang(c, &han);
714            if !langs.contains(&l) {
715                langs.push(l);
716            }
717        }
718        let source: Rc<dyn crate::read::FontSource> = match &self.fonts {
719            Some(s) => s.clone(),
720            None => {
721                let s: Rc<dyn crate::read::FontSource> = Rc::new(SystemFonts::new());
722                self.fonts = Some(s.clone());
723                s
724            }
725        };
726        let mut pick = Vec::new();
727        for l in &langs {
728            // the characters this font is for
729            let chars: String = text.chars().take(MAX_SHOWN).filter(|&c| script_lang(c, &han) == *l && !c.is_whitespace()).collect();
730            // the font's own name (and its language), then families of every system; a font the
731            // update has already serves when it has these characters
732            let mut tries: Vec<(&str, Option<&str>)> = vec![(base, l.as_deref())];
733            for f in script_families(l.as_deref()) {
734                tries.push((f, None));
735            }
736            for (n, lang) in tries {
737                let key = format!("{n}|{bold}|{italic}|{serif}|{}", lang.unwrap_or(""));
738                if let Some(i) = self.fallback_meta.iter().position(|k| k.0 == key) {
739                    if !appear::missing(&self.fallback_fonts, &[i], &chars) {
740                        pick.push(i);
741                        break;
742                    }
743                    continue;
744                }
745                if self.fallback_fonts.len() >= MAX_FALLBACKS {
746                    break;
747                }
748                let q = FontQuery { name: n, family: None, bold, italic, serif, fixed: false, symbolic: false, text: lang.is_none(), lang };
749                let Some((data, face)) = source.find(&q) else { continue };
750                let Ok(fd) = FontData::parse(data, face) else { continue };
751                if appear::missing(core::slice::from_ref(&fd), &[0], &chars) {
752                    continue;
753                }
754                let refs = [self.take()?, self.take()?, self.take()?, self.take()?, self.take()?];
755                self.fallback_meta.push((key, refs));
756                self.fallback_fonts.push(fd);
757                pick.push(self.fallback_fonts.len() - 1);
758                break;
759            }
760        }
761        if pick.is_empty() || appear::missing(&self.fallback_fonts, &pick, text) {
762            return Err(Error::Invalid("no font for the characters of the value"));
763        }
764        Ok(pick)
765    }
766
767    /// the language of Han characters: kana make them Japanese, hangul Korean, else set_lang,
768    /// the document's /Lang, zh-Hans
769    fn han_lang(&self, text: &str) -> String {
770        if text.chars().any(|c| matches!(c as u32, 0x3040..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F)) {
771            return "ja".into();
772        }
773        if text.chars().any(|c| matches!(c as u32, 0xAC00..=0xD7AF | 0x1100..=0x11FF | 0x3130..=0x318F)) {
774            return "ko".into();
775        }
776        let l = self.lang.clone().or_else(|| self.doc.language()).unwrap_or_default().to_ascii_lowercase();
777        if l.starts_with("ja") {
778            "ja".into()
779        } else if l.starts_with("ko") {
780            "ko".into()
781        } else if l.starts_with("zh-hant") || l.starts_with("zh-tw") || l.starts_with("zh-hk") || l.starts_with("zh-mo") {
782            "zh-Hant".into()
783        } else {
784            "zh-Hans".into()
785        }
786    }
787
788    // ------------------------------------------------------------------ flattening
789
790    /// draw the fields (all, or those named and their kids) into their pages and take them out
791    /// of the form; when it fails, the update is as it was
792    pub fn flatten(&mut self, names: Option<&[&str]>) -> Result<(), Error> {
793        self.transaction(|u| u.flatten_now(names))
794    }
795
796    fn flatten_now(&mut self, names: Option<&[&str]>) -> Result<(), Error> {
797        let Some((_, form)) = self.acroform() else { return Ok(()) };
798        let need = self.resolve(form.get("NeedAppearances").unwrap_or(&Object::Null)).as_bool() == Some(true);
799        let all = self.walk();
800        let chosen: Vec<&Found> = all
801            .iter()
802            .filter(|f| f.kind != Kind::Sig)
803            .filter(|f| names.is_none_or(|ns| ns.iter().any(|n| f.name == *n || f.name.starts_with(&format!("{n}.")))))
804            .collect();
805        if chosen.is_empty() {
806            return Ok(());
807        }
808        // appearances first where they are missing or NeedAppearances asks for them
809        for f in &chosen {
810            self.refresh(f, need)?;
811        }
812        let pages: Vec<(usize, Ref)> = self.doc.pages().iter().enumerate().filter_map(|(i, p)| p.obj.map(|r| (i, r))).collect();
813        let mut on_page: BTreeMap<Ref, usize> = BTreeMap::new();
814        for &(i, pr) in &pages {
815            let pd = self.dict(&Object::Ref(pr));
816            if let Object::Array(a) = self.resolve(pd.get("Annots").unwrap_or(&Object::Null)) {
817                for r in a.iter().take(1 << 16).filter_map(Object::as_ref) {
818                    on_page.entry(r).or_insert(i);
819                }
820            }
821        }
822        // per page: the widgets taken off it and the appearances drawn
823        let mut drop: BTreeMap<usize, BTreeSet<Ref>> = BTreeMap::new();
824        let mut draw: BTreeMap<usize, Vec<(Ref, [f64; 6], Option<Object>)>> = BTreeMap::new();
825        for f in &chosen {
826            for (wloc, _) in &f.widgets {
827                let wd = self.dict_at(wloc);
828                let wref = if wloc.path.is_empty() { Some(wloc.holder) } else { None };
829                let page = wd.get("P").and_then(Object::as_ref).and_then(|r| self.doc.page_of(r)).or_else(|| wref.and_then(|r| on_page.get(&r).copied()));
830                let Some(page) = page else { continue };
831                if let Some(r) = wref {
832                    drop.entry(page).or_default().insert(r);
833                }
834                let flags = self.resolve(wd.get("F").unwrap_or(&Object::Null)).as_int().unwrap_or(0);
835                if flags & (2 | 32) != 0 {
836                    continue;
837                }
838                let Some((ap, m)) = self.placed(&wd)? else { continue };
839                // drawn under the widget's optional content, as it was shown
840                draw.entry(page).or_default().push((ap, m, wd.get("OC").cloned()));
841            }
842        }
843        for &(i, pr) in &pages {
844            let gone = drop.remove(&i).unwrap_or_default();
845            let list = draw.remove(&i).unwrap_or_default();
846            if !gone.is_empty() || !list.is_empty() {
847                self.draw_into(i, pr, &list, &gone)?;
848            }
849        }
850        // the fields out of the form
851        if names.is_none() && all.iter().all(|f| f.kind != Kind::Sig) {
852            let root = self.root()?;
853            let mut cat = self.dict(&Object::Ref(root));
854            cat.remove("AcroForm");
855            self.set(root, Object::Dict(cat))?;
856            return Ok(());
857        }
858        let slots: Vec<(Loc, usize)> = chosen.iter().map(|f| f.slot.clone()).collect();
859        self.unlink(slots)?;
860        // parents left without kids go too (a walk sees one as a field of its own)
861        for _ in 0..MAX_DEPTH {
862            let empty: Vec<(Loc, usize)> = self
863                .walk()
864                .into_iter()
865                .filter(|f| matches!(self.resolve(f.dict.get("Kids").unwrap_or(&Object::Null)), Object::Array(a) if a.is_empty()))
866                .map(|f| f.slot)
867                .collect();
868            if empty.is_empty() {
869                break;
870            }
871            self.unlink(empty)?;
872        }
873        Ok(())
874    }
875
876    /// fields out of the arrays that hold them (Fields, Kids); arrays inside others first, so
877    /// the places of their paths still hold
878    fn unlink(&mut self, slots: Vec<(Loc, usize)>) -> Result<(), Error> {
879        let mut by_array: BTreeMap<Loc, Vec<usize>> = BTreeMap::new();
880        for (loc, i) in slots {
881            by_array.entry(loc).or_default().push(i);
882        }
883        let mut arrays: Vec<(Loc, Vec<usize>)> = by_array.into_iter().collect();
884        arrays.sort_by_key(|(l, _)| core::cmp::Reverse(l.path.len()));
885        for (loc, mut idx) in arrays {
886            idx.sort_unstable();
887            idx.dedup();
888            if let Object::Array(mut a) = self.load(&loc) {
889                for &i in idx.iter().rev() {
890                    if i < a.len() {
891                        a.remove(i);
892                    }
893                }
894                self.store(&loc, Object::Array(a))?;
895            }
896        }
897        Ok(())
898    }
899
900    /// a field's appearances made again where they are missing (or all of them with
901    /// NeedAppearances), from its value
902    fn refresh(&mut self, f: &Found, need: bool) -> Result<(), Error> {
903        let missing = f.widgets.iter().any(|(_, wd)| !self.dict(wd.get("AP").unwrap_or(&Object::Null)).contains("N"));
904        if !missing && !need {
905            return Ok(());
906        }
907        let r = self.transaction(|u| match f.kind {
908            Kind::Text => {
909                let s = f.v.as_bytes().map(crate::read::text_string).unwrap_or_default();
910                u.fill_text(f, &s, true)
911            }
912            Kind::Combo | Kind::List => {
913                let (chosen, custom) = current_choice(u, &f.dict, &f.v, f.kind == Kind::Combo);
914                u.apply_choice(f, &chosen, custom, true)
915            }
916            Kind::Check | Kind::Radio if missing => u.button_refresh(f),
917            _ => Ok(()),
918        });
919        // an appearance that is there stays when a new one cannot be made
920        if r.is_err() && !missing {
921            return Ok(());
922        }
923        r
924    }
925
926    /// a widget's normal appearance (its /AS state's) and the matrix that puts it on /Rect
927    /// (Algorithm 8.1)
928    fn placed(&mut self, wd: &Dict) -> Result<Option<(Ref, [f64; 6])>, Error> {
929        let Some(rect) = self.resolve(wd.get("Rect").unwrap_or(&Object::Null)).as_rect() else { return Ok(None) };
930        let ap = self.dict(wd.get("AP").unwrap_or(&Object::Null));
931        let Some(n) = ap.get("N").cloned() else { return Ok(None) };
932        let stream = n.as_ref().is_some_and(|r| self.is_stream(r));
933        let sref = match self.resolve(&n) {
934            Object::Dict(states) if !stream => {
935                let Some(st) = wd.name("AS") else { return Ok(None) };
936                match states.get_bytes(st).and_then(Object::as_ref) {
937                    Some(r) => r,
938                    None => return Ok(None),
939                }
940            }
941            _ => match n.as_ref() {
942                Some(r) => r,
943                None => return Ok(None),
944            },
945        };
946        let sd = self.dict(&Object::Ref(sref));
947        let num4 = |o: &Object| self.resolve(o).as_rect();
948        let Some(bbox) = sd.get("BBox").and_then(num4) else { return Ok(None) };
949        let m: [f64; 6] = match self.resolve(sd.get("Matrix").unwrap_or(&Object::Null)) {
950            Object::Array(a) if a.len() >= 6 => {
951                let v: Vec<f64> = a.iter().take(6).map(|x| self.resolve(x).as_f64().unwrap_or(0.0)).collect();
952                [v[0], v[1], v[2], v[3], v[4], v[5]]
953            }
954            _ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
955        };
956        // a stream without /Subtype /Form cannot be drawn with Do: it gets one
957        if !sd.is("Subtype", "Form") {
958            if let Object::Stream(mut s) = self.get(sref) {
959                s.dict.insert("Type", Object::name("XObject"));
960                s.dict.insert("Subtype", Object::name("Form"));
961                self.set(sref, Object::Stream(s))?;
962            }
963        }
964        let pts = [(bbox[0], bbox[1]), (bbox[2], bbox[1]), (bbox[2], bbox[3]), (bbox[0], bbox[3])];
965        let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
966        for (x, y) in pts {
967            let (tx, ty) = (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]);
968            x0 = x0.min(tx);
969            y0 = y0.min(ty);
970            x1 = x1.max(tx);
971            y1 = y1.max(ty);
972        }
973        let (bw, bh) = (x1 - x0, y1 - y0);
974        let sx = if bw.abs() > 1e-9 { (rect[2] - rect[0]) / bw } else { 1.0 };
975        let sy = if bh.abs() > 1e-9 { (rect[3] - rect[1]) / bh } else { 1.0 };
976        let fit = [sx, 0.0, 0.0, sy, rect[0] - x0 * sx, rect[1] - y0 * sy];
977        Ok(fit.iter().all(|v| v.is_finite()).then_some((sref, fit)))
978    }
979
980    /// page i: its content wrapped in q .. Q with the appearances drawn after it, the widgets
981    /// `gone` off its /Annots
982    fn draw_into(&mut self, i: usize, pr: Ref, list: &[(Ref, [f64; 6], Option<Object>)], gone: &BTreeSet<Ref>) -> Result<(), Error> {
983        let mut pd = self.dict(&Object::Ref(pr));
984        if !gone.is_empty() {
985            if let Object::Array(a) = self.resolve(pd.get("Annots").unwrap_or(&Object::Null)) {
986                let keep: Vec<Object> = a.into_iter().filter(|o| o.as_ref().is_none_or(|r| !gone.contains(&r))).collect();
987                if keep.is_empty() {
988                    pd.remove("Annots");
989                } else {
990                    pd.insert("Annots", Object::Array(keep));
991                }
992            }
993        }
994        if !list.is_empty() {
995            // the resources the page has (inherited ones too) and the appearances
996            let mut res = match pd.get("Resources") {
997                Some(o) => self.dict(o),
998                None => self.doc.pages().get(i).map(|p| p.resources.clone()).unwrap_or_default(),
999            };
1000            let mut xo = self.dict(res.get("XObject").unwrap_or(&Object::Null));
1001            let mut props = self.dict(res.get("Properties").unwrap_or(&Object::Null));
1002            let props_had = props.len();
1003            let mut body = Vec::new();
1004            let (mut k, mut p) = (0usize, 0usize);
1005            for (r, m, oc) in list {
1006                let mut name = format!("JFx{k}");
1007                while xo.contains(&name) {
1008                    k += 1;
1009                    name = format!("JFx{k}");
1010                }
1011                k += 1;
1012                xo.insert(&name, Object::Ref(*r));
1013                if let Some(oc) = oc {
1014                    let mut pn = format!("JFoc{p}");
1015                    while props.contains(&pn) {
1016                        p += 1;
1017                        pn = format!("JFoc{p}");
1018                    }
1019                    p += 1;
1020                    props.insert(&pn, oc.clone());
1021                    body.extend_from_slice(b"/OC ");
1022                    crate::obj::name(&mut body, pn.as_bytes());
1023                    body.extend_from_slice(b" BDC\n");
1024                }
1025                body.extend_from_slice(b"q\n");
1026                crate::obj::operands(&mut body, m);
1027                body.extend_from_slice(b" cm\n");
1028                crate::obj::name(&mut body, name.as_bytes());
1029                body.extend_from_slice(b" Do\nQ\n");
1030                if oc.is_some() {
1031                    body.extend_from_slice(b"EMC\n");
1032                }
1033            }
1034            res.insert("XObject", Object::Dict(xo));
1035            if props.len() > props_had {
1036                res.insert("Properties", Object::Dict(props));
1037            }
1038            pd.insert("Resources", Object::Dict(res));
1039            let open = self.add_stream(Dict::new(), b"q\n")?;
1040            let mut close = b"Q\n".to_vec();
1041            close.extend_from_slice(&body);
1042            let close = self.add_stream(Dict::new(), &close)?;
1043            let mut contents = vec![Object::Ref(open)];
1044            match pd.get("Contents").cloned() {
1045                Some(Object::Ref(r)) => match self.get(r) {
1046                    Object::Array(a) => contents.extend(a),
1047                    _ => contents.push(Object::Ref(r)),
1048                },
1049                Some(Object::Array(a)) => contents.extend(a),
1050                _ => {}
1051            }
1052            contents.push(Object::Ref(close));
1053            pd.insert("Contents", Object::Array(contents));
1054        }
1055        self.set(pr, Object::Dict(pd))
1056    }
1057}
1058
1059// ---------------------------------------------------------------------- shared with drawing
1060
1061/// where appearances read objects from: the document, or an update of it
1062pub(crate) trait Src {
1063    fn res(&self, o: &Object) -> Object;
1064    fn document(&self) -> &crate::read::Document;
1065}
1066
1067impl Src for Update<'_> {
1068    fn res(&self, o: &Object) -> Object {
1069        self.resolve(o)
1070    }
1071    fn document(&self) -> &crate::read::Document {
1072        self.doc
1073    }
1074}
1075
1076impl Src for crate::read::Document {
1077    fn res(&self, o: &Object) -> Object {
1078        self.resolve(o)
1079    }
1080    fn document(&self) -> &crate::read::Document {
1081        self
1082    }
1083}
1084
1085/// the value under a key, resolved
1086fn val(s: &dyn Src, d: &Dict, k: &str) -> Object {
1087    s.res(d.get(k).unwrap_or(&Object::Null))
1088}
1089
1090/// the dictionary under a key (a stream's), resolved; empty when it is none
1091fn sub(s: &dyn Src, d: &Dict, k: &str) -> Dict {
1092    match val(s, d, k) {
1093        Object::Dict(d) => d,
1094        Object::Stream(st) => st.dict,
1095        _ => Dict::new(),
1096    }
1097}
1098
1099/// the widget's frame: /Rect, /MK, /BS or /Border
1100fn frame_of(s: &dyn Src, wd: &Dict) -> Frame {
1101    let r = val(s, wd, "Rect").as_rect().unwrap_or([0.0; 4]);
1102    let mut fr = Frame::new(r[2] - r[0], r[3] - r[1]);
1103    let mk = sub(s, wd, "MK");
1104    fr.rotate = val(s, &mk, "R").as_int().map_or(0, |v| v.rem_euclid(360) as u16);
1105    let color = |k: &str| match val(s, &mk, k) {
1106        Object::Array(a) => Color(a.iter().take(4).filter_map(|x| s.res(x).as_f64()).collect()),
1107        _ => Color::default(),
1108    };
1109    fr.bg = color("BG");
1110    fr.bc = color("BC");
1111    let bs = sub(s, wd, "BS");
1112    if !bs.is_empty() {
1113        fr.width = val(s, &bs, "W").as_f64().unwrap_or(1.0);
1114        fr.style = bs.name("S").and_then(|n| n.first().copied()).unwrap_or(b'S');
1115        if let Object::Array(a) = val(s, &bs, "D") {
1116            fr.dash = a.iter().take(16).filter_map(|x| s.res(x).as_f64()).collect();
1117        }
1118    } else if let Object::Array(a) = val(s, wd, "Border") {
1119        fr.width = a.get(2).map(|x| s.res(x)).and_then(|x| x.as_f64()).unwrap_or(1.0);
1120        if let Some(Object::Array(dash)) = a.get(3).map(|x| s.res(x)) {
1121            fr.style = b'D';
1122            fr.dash = dash.iter().take(16).filter_map(|x| s.res(x).as_f64()).collect();
1123        }
1124    }
1125    fr
1126}
1127
1128/// /DA of the widget, else the field's (inherited), else the form's
1129fn da_of(s: &dyn Src, wd: &Dict, field: Option<Vec<u8>>, form: &Dict) -> Da {
1130    let own = val(s, wd, "DA").as_bytes().map(<[u8]>::to_vec);
1131    let da = own.or(field).or_else(|| val(s, form, "DA").as_bytes().map(<[u8]>::to_vec));
1132    let mut d = da.map(|b| appear::parse_da(&b)).unwrap_or_default();
1133    if d.font.is_empty() {
1134        d.font = b"Helv".to_vec();
1135    }
1136    d
1137}
1138
1139/// what a font has codes for: each character's code, the code's length and its width
1140pub(crate) type Codes = BTreeMap<char, (u32, u8, f64)>;
1141
1142/// the codes of the fonts drawing has made appearances with, by their object (made once each)
1143#[derive(Default)]
1144pub(crate) struct CodeCache(core::cell::RefCell<BTreeMap<Ref, Rc<Codes>>>);
1145
1146/// the /DA font of the form's /DR and the characters it has codes for; without the font in
1147/// /DR, Helvetica in WinAnsiEncoding.  Also the work it took (the codes looked at), none when
1148/// `cache` had them
1149fn da_codes(s: &dyn Src, form: &Dict, da: &Da, cache: Option<&CodeCache>) -> (Option<Object>, Rc<Codes>, u64) {
1150    let dr = sub(s, form, "DR");
1151    let fonts = sub(s, &dr, "Font");
1152    let Some(o) = fonts.get_bytes(&da.font).cloned() else {
1153        let m = (32u8..=255).filter_map(|c| char::from_u32(crate::read::tables::WINANSI[c as usize] as u32).and_then(|ch| appear::helvetica(ch).map(|v| (ch, v)))).collect();
1154        return (None, Rc::new(m), 256);
1155    };
1156    if let (Some(c), Some(r)) = (cache, o.as_ref()) {
1157        if let Some(m) = c.0.borrow().get(&r) {
1158            return (Some(o), m.clone(), 0);
1159        }
1160    }
1161    let fd = match s.res(&o) {
1162        Object::Dict(d) => d,
1163        _ => return (Some(o), Rc::new(BTreeMap::new()), 0),
1164    };
1165    let font = Font::load(s.document(), &fd);
1166    // an embedded subset has the glyphs it has widths for
1167    let subset = fd.name("BaseFont").is_some_and(|b| b.len() > 7 && b[6] == b'+' && b[..6].iter().all(u8::is_ascii_uppercase));
1168    let (m, work): (Codes, u64) = match font.simple_codes() {
1169        Some(m) => (m.into_iter().map(|(c, (k, w))| (c, (k as u32, 1, w))).filter(|(_, (_, _, w))| !subset || *w > 0.0).collect(), 256),
1170        None => (font.composite_codes().unwrap_or_default(), 65_536 + 256),
1171    };
1172    let m = Rc::new(m);
1173    if let (Some(c), Some(r)) = (cache, o.as_ref()) {
1174        let mut c = c.0.borrow_mut();
1175        if c.len() < 256 {
1176            c.insert(r, m.clone());
1177        }
1178    }
1179    (Some(o), m, work)
1180}
1181
1182/// a choice field's chosen options: /I when its places are options that /V names (two options
1183/// may share an export value), else those /V names, and a combo box's own text
1184fn current_choice(s: &dyn Src, field: &Dict, v: &Object, combo: bool) -> (Vec<usize>, Option<String>) {
1185    let opts = options_of(s, field);
1186    let text_of = |o: &Object| o.as_bytes().map(crate::read::text_string);
1187    let values: Vec<String> = match v {
1188        Object::Array(a) => a.iter().filter_map(|x| text_of(&s.res(x))).collect(),
1189        o => text_of(o).into_iter().collect(),
1190    };
1191    let mut idx: Vec<usize> = match val(s, field, "I") {
1192        Object::Array(a) => a.iter().take(1 << 16).filter_map(|x| s.res(x).as_int()).filter_map(|i| usize::try_from(i).ok()).collect(),
1193        _ => Vec::new(),
1194    };
1195    idx.sort_unstable();
1196    idx.dedup();
1197    let named = |i: usize| opts.get(i).is_some_and(|o| values.iter().any(|v| *v == o.0 || *v == o.1));
1198    if !idx.is_empty() && idx.len() == values.len() && idx.iter().all(|&i| named(i)) {
1199        return (idx, None);
1200    }
1201    let mut chosen: Vec<usize> = values.iter().filter_map(|v| opts.iter().position(|o| &o.0 == v).or_else(|| opts.iter().position(|o| &o.1 == v))).collect();
1202    chosen.sort_unstable();
1203    chosen.dedup();
1204    let custom = (combo && chosen.is_empty()).then(|| values.first().cloned()).flatten();
1205    (chosen, custom)
1206}
1207
1208/// a field as its widget leads to it: the terminal field's dictionary and what it and its
1209/// parents give (FT, Ff, V, DA, Q)
1210struct Up {
1211    field: Dict,
1212    ft: Option<Vec<u8>>,
1213    ff: u32,
1214    v: Object,
1215    da: Option<Vec<u8>>,
1216    q: Option<i64>,
1217    max_len: Option<i64>,
1218}
1219
1220fn field_of(s: &dyn Src, wd: &Dict) -> Up {
1221    let mut up = Up { field: Dict::new(), ft: None, ff: 0, v: Object::Null, da: None, q: None, max_len: None };
1222    let (mut ff, mut v) = (None, None);
1223    let mut cur = wd.clone();
1224    let mut found = false;
1225    for _ in 0..MAX_DEPTH {
1226        if !found && (cur.contains("T") || cur.contains("FT")) {
1227            up.field = cur.clone();
1228            found = true;
1229        }
1230        if up.ft.is_none() {
1231            up.ft = cur.name("FT").map(<[u8]>::to_vec);
1232        }
1233        if ff.is_none() {
1234            ff = val(s, &cur, "Ff").as_int();
1235        }
1236        if v.is_none() {
1237            v = cur.get("V").map(|o| s.res(o));
1238        }
1239        if up.da.is_none() {
1240            up.da = val(s, &cur, "DA").as_bytes().map(<[u8]>::to_vec);
1241        }
1242        if up.q.is_none() {
1243            up.q = val(s, &cur, "Q").as_int();
1244        }
1245        if up.max_len.is_none() {
1246            up.max_len = val(s, &cur, "MaxLen").as_int();
1247        }
1248        let p = sub(s, &cur, "Parent");
1249        if p.is_empty() {
1250            break;
1251        }
1252        cur = p;
1253    }
1254    if !found {
1255        up.field = wd.clone();
1256    }
1257    up.ff = ff.unwrap_or(0) as u32;
1258    up.v = v.unwrap_or_default();
1259    up
1260}
1261
1262/// the options of a choice field: (export value, text shown)
1263fn options_of(s: &dyn Src, d: &Dict) -> Vec<(String, String)> {
1264    match val(s, d, "Opt") {
1265        Object::Array(a) => a
1266            .iter()
1267            .take(1 << 16)
1268            .filter_map(|x| match s.res(x) {
1269                Object::String(b) => {
1270                    let t = crate::read::text_string(&b);
1271                    Some((t.clone(), t))
1272                }
1273                Object::Array(p) => {
1274                    let e = p.first().map(|o| s.res(o)).and_then(|o| o.as_bytes().map(crate::read::text_string))?;
1275                    let shown = p.get(1).map(|o| s.res(o)).and_then(|o| o.as_bytes().map(crate::read::text_string)).unwrap_or_else(|| e.clone());
1276                    Some((e, shown))
1277                }
1278                _ => None,
1279            })
1280            .collect(),
1281        _ => Vec::new(),
1282    }
1283}
1284
1285/// what drawing shows for a widget (`wref` its object) of a field without a normal appearance,
1286/// or with NeedAppearances (`need`): the appearance made from the field's value in the /DA font
1287/// (the characters it lacks left out), its resources and the work its font's codes took.  Check
1288/// boxes and radio buttons only when they have no appearance at all.
1289pub(crate) fn widget_ap(doc: &crate::read::Document, wd: &Dict, wref: Option<Ref>, need: bool, cache: &CodeCache) -> Option<(appear::Ap, Dict, u64)> {
1290    let s: &dyn Src = doc;
1291    let has = sub(s, wd, "AP").contains("N");
1292    if has && !need {
1293        return None;
1294    }
1295    let up = field_of(s, wd);
1296    let form = {
1297        let cat = doc.catalog();
1298        sub(s, &cat, "AcroForm")
1299    };
1300    let frame = frame_of(s, wd);
1301    let da = da_of(s, wd, up.da.clone(), &form);
1302    let q = up.q.or_else(|| val(s, &form, "Q").as_int()).unwrap_or(0).clamp(0, 2) as u8;
1303    let mut fonts_res = Dict::new();
1304    let mut work = 0;
1305    let ap = match up.ft.as_deref() {
1306        Some(b"Btn") if has || up.ff & FF_PUSH != 0 => return None,
1307        Some(b"Btn") => {
1308            let radio = up.ff & FF_RADIO != 0;
1309            let mk = sub(s, wd, "MK");
1310            let ca = val(s, &mk, "CA").as_bytes().and_then(|b| b.first().copied()).unwrap_or(if radio { b'l' } else { b'4' });
1311            let v = up.v.as_name().filter(|n| *n != b"Off");
1312            let on = match wd.name("AS") {
1313                Some(a) => a != b"Off",
1314                // the widget is the field: on with its value
1315                None if wd.contains("T") || wd.contains("FT") => v.is_some(),
1316                // a kid: on when the value is its state (its place in /Opt, or that place's export
1317                // value); a radio button that says neither is off
1318                None => {
1319                    let kids = match val(s, &up.field, "Kids") {
1320                        Object::Array(a) => a,
1321                        _ => Vec::new(),
1322                    };
1323                    let at = wref.and_then(|r| kids.iter().take(1 << 16).position(|k| k.as_ref() == Some(r)));
1324                    let opts = options_of(s, &up.field);
1325                    match (v, at) {
1326                        (Some(v), Some(i)) if !opts.is_empty() => v == format!("{i}").as_bytes() || opts.get(i).is_some_and(|o| o.0.as_bytes() == v),
1327                        (Some(_), _) => !radio,
1328                        (None, _) => false,
1329                    }
1330                }
1331            };
1332            appear::check(&frame, &da, ca, on, radio)
1333        }
1334        Some(b"Tx") | Some(b"Ch") => {
1335            let (da_font, codes, w) = da_codes(s, &form, &da, Some(cache));
1336            work = w;
1337            fonts_res.insert_bytes(&da.font, da_font.unwrap_or_else(|| Object::Dict(standard_font(b"Helvetica"))));
1338            let map = |c: char| codes.get(&c).copied();
1339            let mut face = Face::Simple { name: &da.font, map: &map };
1340            let text_of = |o: &Object| o.as_bytes().map(crate::read::text_string);
1341            if up.ft.as_deref() == Some(b"Tx") {
1342                let value = text_of(&up.v).unwrap_or_default();
1343                let max_len = up.max_len.and_then(|m| u32::try_from(m).ok());
1344                let t = Text {
1345                    value: &value,
1346                    q,
1347                    multiline: up.ff & FF_MULTILINE != 0,
1348                    password: up.ff & FF_PASSWORD != 0,
1349                    comb: (up.ff & FF_COMB != 0 && up.ff & (FF_MULTILINE | FF_PASSWORD) == 0).then_some(max_len).flatten(),
1350                };
1351                appear::text_field(&frame, &da, &mut face, &t)
1352            } else {
1353                let opts = options_of(s, &up.field);
1354                let (chosen, custom) = current_choice(s, &up.field, &up.v, up.ff & FF_COMBO != 0);
1355                if up.ff & FF_COMBO != 0 {
1356                    let shown = chosen.first().map(|&i| opts[i].1.clone()).or(custom).unwrap_or_default();
1357                    appear::text_field(&frame, &da, &mut face, &Text { value: &shown, q, multiline: false, password: false, comb: None })
1358                } else {
1359                    let texts: Vec<String> = opts.iter().map(|o| o.1.clone()).collect();
1360                    let top = val(s, &up.field, "TI").as_int().and_then(|t| usize::try_from(t).ok()).unwrap_or(0).min(texts.len());
1361                    appear::list_box(&frame, &da, &mut face, &texts, &chosen, top)
1362                }
1363            }
1364        }
1365        _ => return None,
1366    };
1367    let mut res = Dict::new();
1368    res.insert("Font", Object::Dict(fonts_res));
1369    Some((ap, res, work))
1370}
1371
1372/// `v` into `top` along `path`
1373fn put(top: &mut Object, path: &[Step], v: Object, depth: usize) -> Result<(), Error> {
1374    let Some((first, rest)) = path.split_first() else {
1375        *top = v;
1376        return Ok(());
1377    };
1378    let slot = match (first, top) {
1379        (Step::Key(k), Object::Dict(d)) => d.map_mut().entry(k.clone()).or_insert(Object::Null),
1380        (Step::Key(k), Object::Stream(s)) => s.dict.map_mut().entry(k.clone()).or_insert(Object::Null),
1381        (Step::Index(i), Object::Array(a)) if *i < a.len() => &mut a[*i],
1382        _ => return Err(Error::Invalid("a field's place changed")),
1383    };
1384    if !rest.is_empty() && matches!(slot, Object::Ref(_)) {
1385        return Err(Error::Invalid("a field's place changed"));
1386    }
1387    put(slot, rest, v, depth + 1)
1388}
1389
1390impl Loc {
1391    fn child_index(&self, i: usize) -> Loc {
1392        let mut path = self.path.clone();
1393        path.push(Step::Index(i));
1394        Loc { holder: self.holder, path }
1395    }
1396}
1397
1398impl Dict {
1399    pub(crate) fn insert_bytes(&mut self, key: &[u8], v: Object) {
1400        self.map_mut().insert(Name(key.to_vec()), v);
1401    }
1402}
1403
1404/// a widget's /AP becomes << /N ap >>
1405fn with_ap(mut wd: Dict, ap: Ref) -> Dict {
1406    let mut apd = Dict::new();
1407    apd.insert("N", Object::Ref(ap));
1408    wd.insert("AP", Object::Dict(apd));
1409    wd
1410}
1411
1412/// the appearance of a field: a list box, else a text field (combo boxes too)
1413fn build(frame: &Frame, da: &Da, face: &mut Face, t: &Text, list: Option<(&[String], &[usize], usize)>) -> appear::Ap {
1414    match list {
1415        Some((opts, chosen, top)) => appear::list_box(frame, da, face, opts, chosen, top),
1416        None => appear::text_field(frame, da, face, t),
1417    }
1418}
1419
1420/// one of the 14 standard fonts in WinAnsiEncoding (ZapfDingbats in its own)
1421fn standard_font(name: &[u8]) -> Dict {
1422    let mut d = Dict::new();
1423    d.insert("Type", Object::name("Font"));
1424    d.insert("Subtype", Object::name("Type1"));
1425    d.insert("BaseFont", Object::Name(Name(name.to_vec())));
1426    if name != b"ZapfDingbats" && name != b"Symbol" {
1427        d.insert("Encoding", Object::name("WinAnsiEncoding"));
1428    }
1429    d
1430}
1431
1432fn nums(v: &[f64]) -> Object {
1433    Object::Array(v.iter().map(|&x| if x.abs() < 1e15 && x == (x as i64) as f64 { Object::Int(x as i64) } else { Object::Real(x) }).collect())
1434}
1435
1436/// a text string: PDFDocEncoding when it has every character, else UTF-16BE
1437pub(crate) fn text_obj(s: &str) -> Object {
1438    let table = &crate::read::tables::PDFDOC;
1439    let mut b = Vec::with_capacity(s.len());
1440    for ch in s.chars() {
1441        let u = ch as u32;
1442        match (0..256usize).find(|&i| table[i] as u32 == u && (u != 0 || i == 0)) {
1443            Some(i) if u != 0xFEFF => b.push(i as u8),
1444            _ => {
1445                let mut out = vec![0xFE, 0xFF];
1446                for unit in s.encode_utf16() {
1447                    out.extend_from_slice(&unit.to_be_bytes());
1448                }
1449                return Object::String(out);
1450            }
1451        }
1452    }
1453    if b.len() >= 2 && (b[0] == 0xFE && b[1] == 0xFF || b[0] == 0xFF && b[1] == 0xFE) {
1454        let mut out = vec![0xFE, 0xFF];
1455        for unit in s.encode_utf16() {
1456            out.extend_from_slice(&unit.to_be_bytes());
1457        }
1458        return Object::String(out);
1459    }
1460    Object::String(b)
1461}
1462
1463/// the language whose fonts have a character (None: Latin, Greek, Cyrillic and the common
1464/// characters)
1465fn script_lang(c: char, han: &str) -> Option<String> {
1466    let u = c as u32;
1467    let l = match u {
1468        0x0590..=0x05FF | 0xFB1D..=0xFB4F => "he",
1469        0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => "ar",
1470        0x0700..=0x074F => "syr",
1471        0x0780..=0x07BF => "dv",
1472        0x0900..=0x097F => "hi",
1473        0x0980..=0x09FF => "bn",
1474        0x0A00..=0x0A7F => "pa",
1475        0x0A80..=0x0AFF => "gu",
1476        0x0B00..=0x0B7F => "or",
1477        0x0B80..=0x0BFF => "ta",
1478        0x0C00..=0x0C7F => "te",
1479        0x0C80..=0x0CFF => "kn",
1480        0x0D00..=0x0D7F => "ml",
1481        0x0D80..=0x0DFF => "si",
1482        0x0E00..=0x0E7F => "th",
1483        0x0E80..=0x0EFF => "lo",
1484        0x0F00..=0x0FFF => "bo",
1485        0x1000..=0x109F => "my",
1486        0x10A0..=0x10FF => "ka",
1487        0x0530..=0x058F => "hy",
1488        0x1200..=0x139F => "am",
1489        0x1780..=0x17FF => "km",
1490        0x3040..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F => "ja",
1491        0xAC00..=0xD7AF | 0x1100..=0x11FF | 0x3130..=0x318F => "ko",
1492        0x2E80..=0x2FDF | 0x3000..=0x303F | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0xFF00..=0xFF65 | 0x20000..=0x3FFFF => return Some(String::from(han)),
1493        _ => return None,
1494    };
1495    Some(String::from(l))
1496}
1497
1498/// families of Windows, macOS and Linux to try for a script's language (None: Latin, Greek,
1499/// Cyrillic), after the font's own name
1500fn script_families(lang: Option<&str>) -> Vec<&'static str> {
1501    let own: &[&str] = match lang {
1502        None => &["Liberation Sans", "Arial", "Helvetica", "DejaVu Sans", "Noto Sans"],
1503        Some("ar") => &["Noto Sans Arabic", "Noto Sans Arabic UI", "Noto Naskh Arabic", "Segoe UI", "Arial", "Tahoma", "Geeza Pro", "DejaVu Sans"],
1504        Some("he") => &["Noto Sans Hebrew", "Arial", "Segoe UI", "Arial Hebrew", "DejaVu Sans"],
1505        Some("th") => &["Noto Sans Thai", "Noto Sans Thai UI", "Leelawadee UI", "Tahoma", "Thonburi"],
1506        Some("lo") => &["Noto Sans Lao", "Leelawadee UI", "Lao Sangam MN"],
1507        Some("km") => &["Noto Sans Khmer", "Leelawadee UI", "Khmer Sangam MN"],
1508        Some("my") => &["Noto Sans Myanmar", "Myanmar Text", "Myanmar Sangam MN"],
1509        Some("hi") => &["Noto Sans Devanagari", "Nirmala UI", "Mangal", "Kohinoor Devanagari"],
1510        Some("bn") => &["Noto Sans Bengali", "Nirmala UI", "Vrinda", "Kohinoor Bangla"],
1511        Some("pa") => &["Noto Sans Gurmukhi", "Nirmala UI", "Raavi"],
1512        Some("gu") => &["Noto Sans Gujarati", "Nirmala UI", "Shruti"],
1513        Some("or") => &["Noto Sans Oriya", "Nirmala UI", "Kalinga"],
1514        Some("ta") => &["Noto Sans Tamil", "Nirmala UI", "Latha", "Tamil Sangam MN"],
1515        Some("te") => &["Noto Sans Telugu", "Nirmala UI", "Gautami"],
1516        Some("kn") => &["Noto Sans Kannada", "Nirmala UI", "Tunga"],
1517        Some("ml") => &["Noto Sans Malayalam", "Nirmala UI", "Kartika"],
1518        Some("si") => &["Noto Sans Sinhala", "Nirmala UI", "Iskoola Pota"],
1519        Some("bo") => &["Noto Serif Tibetan", "Microsoft Himalaya", "Kailasa"],
1520        Some("ka") => &["Noto Sans Georgian", "Sylfaen", "DejaVu Sans"],
1521        Some("hy") => &["Noto Sans Armenian", "Sylfaen", "DejaVu Sans"],
1522        Some("am") => &["Noto Sans Ethiopic", "Nyala", "Kefa"],
1523        Some("syr") => &["Noto Sans Syriac", "Estrangelo Edessa"],
1524        Some("dv") => &["Noto Sans Thaana", "MV Boli"],
1525        Some(_) => &[],
1526    };
1527    let mut v = own.to_vec();
1528    v.extend_from_slice(&["Noto Sans", "DejaVu Sans", "Arial Unicode MS", "Segoe UI"]);
1529    v
1530}