mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-10 13:01:29 +00:00
Merge pull request #6710 from storytold/merge/forms-links-text2
Land forms, links, find and redaction-save fixes (#4496, #4532, #3567, #3773, #4470, #4474, #4497, #5658)
This commit is contained in:
52 files changed
+4239
-268
No files matched your search
Generated
+1
@@ -4706,6 +4706,7 @@ dependencies = [
|
||||
"skrifa 0.44.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -310,8 +310,35 @@ impl Automation {
|
||||
json!((0..f.widgets.len()).filter(|&i| f.widget_on(i)).map(|i| i.saturating_add(1)).collect::<Vec<_>>()),
|
||||
);
|
||||
}
|
||||
// A check box whose kids have different on states (ISO 32000-2 §12.7.5.2.3):
|
||||
// which one is ticked, and the names form_fill takes to tick each. One option
|
||||
// per distinct on state: kids sharing a state tick together (EXAMPLE 2), so
|
||||
// their `/Opt` exports are not separate choices. Exports name the options
|
||||
// unless two states share one (Table 230 allows it) or an export would tick
|
||||
// another state (form_fill reads a name as an on state first); then the
|
||||
// states do.
|
||||
FormFieldKind::CheckBox => {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let states: Vec<&str> = f.widgets.iter().filter_map(|w| w.on_state.as_deref()).filter(|s| seen.insert(*s)).collect();
|
||||
if states.len() > 1 {
|
||||
let mut exports = std::collections::HashSet::new();
|
||||
let by_export = states.iter().all(|s| {
|
||||
let e = f.export_for_state(s);
|
||||
exports.insert(e) && f.state_for(e) == Some(*s)
|
||||
});
|
||||
let name = |s: &str| if by_export { f.export_for_state(s).to_owned() } else { s.to_owned() };
|
||||
// The ticked kid is the one whose `/AS` is its on state: §12.7.5.2.3
|
||||
// makes `/AS` decide where it and `/V` differ.
|
||||
let on = (0..f.widgets.len()).find(|&i| f.widget_on(i)).and_then(|i| f.widgets.get(i)?.on_state.as_deref());
|
||||
o.insert("options".into(), json!(states.iter().map(|s| name(s)).collect::<Vec<_>>()));
|
||||
o.insert("checked".into(), json!(on.map(name)));
|
||||
}
|
||||
}
|
||||
FormFieldKind::Combo | FormFieldKind::List => {
|
||||
o.insert("options".into(), f.options.iter().map(|(e, d)| json!({ "value": e, "label": d })).collect());
|
||||
// The selected options as 1-based positions in `options`: two options can share
|
||||
// an export value, and `value` alone does not tell them apart.
|
||||
o.insert("selected".into(), json!(f.selected.iter().map(|i| i.saturating_add(1)).collect::<Vec<_>>()));
|
||||
o.insert("multi_select".into(), json!(f.has(field_flags::MULTI_SELECT)));
|
||||
o.insert("editable".into(), json!(f.has(field_flags::EDIT)));
|
||||
}
|
||||
|
||||
@@ -77,7 +77,8 @@ impl Automation {
|
||||
|
||||
pub(crate) fn link_list(&self, a: &Args) -> Result<Value> {
|
||||
let doc = self.doc(a)?;
|
||||
let targets: std::collections::HashMap<(usize, usize), &LinkTarget> = doc.info.links.iter().map(|t| ((t.page, t.index), &t.target)).collect();
|
||||
let viewed: std::collections::HashMap<(usize, usize), &pdfcraft_render::Link> =
|
||||
doc.info.links.iter().map(|t| ((t.page, t.index), t)).collect();
|
||||
let items: Vec<Value> = doc
|
||||
.links()
|
||||
.iter()
|
||||
@@ -85,14 +86,49 @@ impl Automation {
|
||||
// The link's page may be one the viewer could not read (#2660): rect unchanged then.
|
||||
let rect = crate::view_rect(&doc.info, l.page, l.rect.map(|x| x as f32));
|
||||
let mut v = json!({ "page": l.page + 1, "index": l.index + 1, "rect": rect, "visible": l.style.visible });
|
||||
let link = viewed.get(&(l.page, l.index));
|
||||
// Where the link is active when that isn't its whole rect: its /QuadPoints
|
||||
// (ISO 32000-2 Table 176), as the bounding box of each quadrilateral.
|
||||
if let Some(link) = link.filter(|k| !k.quads.is_empty()) {
|
||||
let areas: Vec<Value> = link
|
||||
.quads
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let (xs, ys) = ([q[0], q[2], q[4], q[6]], [q[1], q[3], q[5], q[7]]);
|
||||
let fold = |v: [f32; 4], f: fn(f32, f32) -> f32, start: f32| v.into_iter().fold(start, f);
|
||||
let box_ = [
|
||||
fold(xs, f32::min, f32::MAX),
|
||||
fold(ys, f32::min, f32::MAX),
|
||||
fold(xs, f32::max, f32::MIN),
|
||||
fold(ys, f32::max, f32::MIN),
|
||||
];
|
||||
json!(crate::view_rect(&doc.info, l.page, box_))
|
||||
})
|
||||
.collect();
|
||||
v["active_areas"] = json!(areas);
|
||||
}
|
||||
// Where an in-document link goes, as the viewer resolves it: named destinations
|
||||
// included, with the position on the page.
|
||||
let target = targets.get(&(l.page, l.index)).and_then(|t| match t {
|
||||
let target = link.and_then(|t| match &t.target {
|
||||
LinkTarget::Page(page, view) => Some((*page, view)),
|
||||
_ => None,
|
||||
});
|
||||
match (&l.action, target) {
|
||||
(LinkAction::Uri(u), _) => v["url"] = json!(u),
|
||||
(LinkAction::Uri(u), _) => {
|
||||
v["url"] = json!(u);
|
||||
// A relative address, resolved against the catalog's /URI /Base
|
||||
// (ISO 32000-2 Table 211): what the viewer offers to open. That is the
|
||||
// address inspection kept, which stays raw once its text budget is spent;
|
||||
// resolve afresh only for a link inspection did not list.
|
||||
let opened = match link.map(|t| &t.target) {
|
||||
Some(LinkTarget::Uri(kept)) => Some(kept.clone()),
|
||||
Some(_) => None,
|
||||
None => pdfcraft_render::resolve_uri(doc.info.uri_base.as_deref(), u),
|
||||
};
|
||||
if let Some(opened) = opened.filter(|o| o != u) {
|
||||
v["resolved_url"] = json!(opened);
|
||||
}
|
||||
}
|
||||
(action, Some((page, view))) => {
|
||||
v["to_page"] = json!(page + 1);
|
||||
if let Some(d) = doc.info.pages.get(page).and_then(|p| crate::destination(view, p)) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use pdfcraft_engine::{
|
||||
Edit, HIDDEN, Hidden, NewAnnotation, REDACT_MAX_WORDS, REDACT_VALIDATORS, REDACTION_CODE_SETS, RedactPattern, RedactRegex, RedactValidator,
|
||||
RedactionCodeSet, Shape, Style, find_pattern, rect_quad, redact_word_list,
|
||||
RedactionCodeSet, Shape, Style, find_pattern, rect_quad, redact_word_list, redacted_file_name,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -200,6 +200,8 @@ impl Automation {
|
||||
let after = self.doc(a)?.redaction_marks();
|
||||
out["applied"] = json!(before - after);
|
||||
out["marks_pending"] = json!(after);
|
||||
// The name to save the redacted copy under, as Save does in the app.
|
||||
out["save_as"] = json!(redacted_file_name(&self.doc(a)?.name));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -508,13 +508,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc", "from", "to"],
|
||||
)),
|
||||
t("form_fields", "List form fields", "Every interactive form field: name, type (text, checkbox, radio, combo, list, button, signature), value, options, page, rect (top-left-origin points) and rotation (0, 90, 180 or 270 degrees counterclockwise), read-only and required flags. A calculated field includes calculate: {op, fields} or {notation} as form_set_props takes them, or {script} for a custom Calculate script (set with form_set_script). Push buttons include caption (first widget's normal label) and captions [{widget, caption}] for all widgets (1-based). Radio groups include on_widgets, the 1-based numbers of the buttons that are on (buttons sharing an option tell apart only there).")
|
||||
t("form_fields", "List form fields", "Every interactive form field: name, type (text, checkbox, radio, combo, list, button, signature), value, options, page, rect (top-left-origin points) and rotation (0, 90, 180 or 270 degrees counterclockwise), read-only and required flags. A calculated field includes calculate: {op, fields} or {notation} as form_set_props takes them, or {script} for a custom Calculate script (set with form_set_script). Push buttons include caption (first widget's normal label) and captions [{widget, caption}] for all widgets (1-based). Radio groups include on_widgets, the 1-based numbers of the buttons that are on (buttons sharing an option tell apart only there). A check box whose widgets have different on states also lists them as options, and which one is checked (null when none). Combo and list boxes include selected: the 1-based positions in options of the selected ones, which tells apart options that share an export value.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"form_fill",
|
||||
"Fill in form fields",
|
||||
"Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.",
|
||||
"Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.",
|
||||
)
|
||||
.with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])),
|
||||
t("form_reset", "Clear form", "Reset fields to their default values: all of them, or only those listed. Undoable.")
|
||||
@@ -678,7 +678,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"redact_apply",
|
||||
"Apply redactions",
|
||||
"Apply the redaction marks (all, or those on pages): text, images, vectors, comments and form fields under them are removed for good and boxes are drawn in their place. A verification pass fails the operation if anything readable remains. Undoable until saved; the saved file no longer contains the content.",
|
||||
"Apply the redaction marks (all, or those on pages): text, images, vectors, comments and form fields under them are removed for good and boxes are drawn in their place. A verification pass fails the operation if anything readable remains. Undoable until saved; the saved file no longer contains the content. The result's save_as is the document's name with _Redacted before the extension (contract.pdf gives contract_Redacted.pdf; a name that already ends in _Redacted is unchanged); pass it to doc_save as path to save under that name.",
|
||||
)
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "pages": pages("whose marks to apply (default: all)") }), &["doc"])),
|
||||
@@ -824,7 +824,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("content_delete", "Delete added content", "Delete an added item (page, index from content_list). Undoable.")
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 } }), &["doc", "page", "index"])),
|
||||
t("link_list", "List links", "Every link: page, 1-based index (for link_edit/link_delete), rect (points from the top-left of the page), and where it goes (url, or to_page with its zoom). With text_links: true, also the web and email addresses written as plain page text with no link over them, which the viewer opens on a click: page, rects (one per line), url, and blocked (why it won't open) when the link check refuses it. Only http, https and mailto addresses are found. At most 100 pages are read per call, from text_links_from (default 1); text_links_next_page then gives the page to continue from.")
|
||||
t("link_list", "List links", "Every link: page, 1-based index (for link_edit/link_delete), rect (points from the top-left of the page), and where it goes (url, or to_page with its zoom). A relative url also has resolved_url, the address resolved against the document's base URI (catalog /URI /Base); a link active only in its /QuadPoints has active_areas, one rect per quadrilateral. With text_links: true, also the web and email addresses written as plain page text with no link over them, which the viewer opens on a click: page, rects (one per line), url, and blocked (why it won't open) when the link check refuses it. Only http, https and mailto addresses are found. At most 100 pages are read per call, from text_links_from (default 1); text_links_next_page then gives the page to continue from.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "text_links": { "type": "boolean" }, "text_links_from": { "type": "integer", "minimum": 1 } }), &["doc"])),
|
||||
t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. Named destinations are reported but not applied. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in.")
|
||||
|
||||
@@ -2263,6 +2263,93 @@ fn text_links_leave_out_addresses_on_hidden_layers() {
|
||||
assert_eq!(created["created"], json!(["https://example.com/shown", "https://example.com/layered"]), "{created}");
|
||||
}
|
||||
|
||||
/// Table 211), and a link with `/QuadPoints` is active only there (§12.5.6.5, Table 176): both as
|
||||
/// link_list and doc_info report them.
|
||||
#[test]
|
||||
fn links_resolve_relative_addresses_and_report_their_quad_points() {
|
||||
let dir = workdir("link-base-quads");
|
||||
let objs: Vec<&str> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /URI << /Base (https://example.com/base/) >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [72 700 300 716] /Border [0 0 0] /A << /S /URI /URI (page.html) >> >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [72 670 300 686] /QuadPoints [72 670 120 670 120 686 72 686] /Border [0 0 0] /A << /S /URI /URI (https://example.org/q) >> >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [72 640 300 656] /Border [0 0 0] /A << /S /URI /URI (javascript:alert\\(1\\)) >> >>",
|
||||
];
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join("links.pdf"), pdf).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "links.pdf" }))["doc"].as_u64().unwrap();
|
||||
let links = ok(&mut a, "link_list", json!({ "doc": doc }));
|
||||
let [relative, quads, script] = [&links["links"][0], &links["links"][1], &links["links"][2]];
|
||||
assert_eq!(
|
||||
(relative["url"].clone(), relative["resolved_url"].clone()),
|
||||
(json!("page.html"), json!("https://example.com/base/page.html")),
|
||||
"{links}"
|
||||
);
|
||||
assert_eq!(relative.get("active_areas"), None, "{links}");
|
||||
// 792 − 686 = 106 points from the top: only the first word, not the whole rect.
|
||||
assert_eq!(quads["active_areas"], json!([[72.0, 106.0, 120.0, 122.0]]), "{links}");
|
||||
assert_eq!(quads.get("resolved_url"), None, "an absolute address is not resolved");
|
||||
// A base never turns a script into a web address.
|
||||
assert_eq!((script["url"].clone(), script.get("resolved_url")), (json!("javascript:alert(1)"), None), "{links}");
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
assert_eq!(info["links"][0]["target"]["uri"], "https://example.com/base/page.html", "{info}");
|
||||
}
|
||||
|
||||
/// Once inspection's text budget is spent, a relative address stays raw, and the viewer opens it
|
||||
/// as written: `link_list` reports that address, not a second resolution against `/URI /Base`.
|
||||
#[test]
|
||||
fn link_list_reports_the_address_the_viewer_opens_past_the_text_budget() {
|
||||
let dir = workdir("link-base-budget");
|
||||
// Each link spends what the base adds to its address; well past 16 MiB of it in all.
|
||||
let base = format!("https://example.com/{}/", "b".repeat(8000));
|
||||
let count = (16 << 20) / base.len() + 20;
|
||||
let annots = "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /Border [0 0 0] /A 4 0 R >> ".repeat(count);
|
||||
let catalog = format!("<< /Type /Catalog /Pages 2 0 R /URI << /Base ({base}) >> >>");
|
||||
let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>");
|
||||
let objs = [catalog.as_str(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>", page.as_str(), "<< /S /URI /URI (p.html) >>"];
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join("links.pdf"), pdf).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "links.pdf" }))["doc"].as_u64().unwrap();
|
||||
let listed = ok(&mut a, "link_list", json!({ "doc": doc }));
|
||||
let links = listed["links"].as_array().unwrap();
|
||||
assert_eq!(links.len(), count);
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
let opened = info["links"].as_array().unwrap();
|
||||
assert_eq!(opened.len(), count);
|
||||
let resolved = format!("{base}p.html");
|
||||
assert_eq!(links[0]["resolved_url"], json!(resolved), "the first links resolve");
|
||||
assert_eq!(opened[0]["target"]["uri"], json!(resolved));
|
||||
// Past the budget the viewer keeps (and opens) the raw address; the listing says so.
|
||||
let last = count - 1;
|
||||
assert_eq!(opened[last]["target"]["uri"], json!("p.html"));
|
||||
assert_eq!((links[last]["url"].clone(), links[last].get("resolved_url")), (json!("p.html"), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmarks_from_structure_through_tools() {
|
||||
let dir = workdir("bookmarks-structure");
|
||||
@@ -3091,6 +3178,113 @@ fn form_fill_picks_one_of_radio_buttons_sharing_an_on_state() {
|
||||
assert!(matches!(a.call("form_fill", &json!({ "doc": doc, "values": { "pick": bad } })), Err(ToolError::InvalidArgs(_))), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `form_fill` ticks one kid of a check box whose kids have different on states by naming it
|
||||
/// (ISO 32000-2 §12.7.5.2.3, Table 230), and `form_fields` lists the names and the ticked one.
|
||||
#[test]
|
||||
fn form_fill_ticks_one_kid_of_a_check_box_by_its_on_state() {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>",
|
||||
"<< /FT /Btn /T (pair) /V /Off /Kids [6 0 R 7 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [10 250 26 266] /P 3 0 R /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [40 250 56 266] /P 3 0 R /AP << /N << /B 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Length 0 >>\nstream\n\nendstream",
|
||||
];
|
||||
let dir = workdir("check-box-kids");
|
||||
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
|
||||
let before = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
assert_eq!((&before["fields"][0]["options"], &before["fields"][0]["checked"]), (&json!(["A", "B"]), &Value::Null), "{before}");
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": "A" } }));
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": "B" } }));
|
||||
let after = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
assert_eq!((&after["fields"][0]["value"], &after["fields"][0]["checked"]), (&json!(true), &json!("B")), "{after}");
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": false } }));
|
||||
assert_eq!(ok(&mut a, "form_fields", json!({ "doc": doc }))["fields"][0]["checked"], Value::Null);
|
||||
}
|
||||
|
||||
/// The options `form_fields` reports fill back through `form_fill` to the kid they name, also
|
||||
/// where one kid's `/Opt` export is the other kid's on state: B exports `(A)`, and filling `A`
|
||||
/// still ticks the kid whose on state is A (ISO 32000-2 §12.7.5.2.3, Table 230).
|
||||
#[test]
|
||||
fn form_fill_round_trips_the_reported_options_of_a_check_box_with_a_crossed_export() {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>",
|
||||
"<< /FT /Btn /T (pair) /V /Off /Opt [(x) (A)] /Kids [6 0 R 7 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [10 250 26 266] /P 3 0 R /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [40 250 56 266] /P 3 0 R /AP << /N << /B 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Length 0 >>
|
||||
stream
|
||||
|
||||
endstream",
|
||||
];
|
||||
let dir = workdir("check-box-crossed-export-fill");
|
||||
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
|
||||
let before = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
let options = before["fields"][0]["options"].clone();
|
||||
assert_eq!(options, json!(["A", "B"]), "{before}");
|
||||
for option in ["A", "B"] {
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "pair": option } }));
|
||||
let after = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
assert_eq!(after["fields"][0]["checked"], json!(option), "filling {option}: {after}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `form_fields` on a check box's kids: one option per distinct on state, named by its `/Opt`
|
||||
/// export unless two states share one, and `checked` follows the kid whose `/AS` is on, which
|
||||
/// ISO 32000-2 §12.7.5.2.3 makes decide where `/AS` and `/V` differ.
|
||||
#[test]
|
||||
fn form_fields_lists_a_check_box_by_on_state_and_reports_the_kid_that_is_on() {
|
||||
// Each kid is (on state, /AS).
|
||||
let listed = |name: &str, field: &str, (sa, asa): (&str, &str), (sb, asb): (&str, &str)| {
|
||||
let kid = |on: &str, state: &str, x: u32| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /{state} /Rect [{x} 250 {} 266] /P 3 0 R /AP << /N << /{on} 8 0 R /Off 8 0 R >> >> >>",
|
||||
x + 16
|
||||
)
|
||||
};
|
||||
let (wa, wb) = (kid(sa, asa, 10), kid(sb, asb, 40));
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>",
|
||||
field,
|
||||
&wa,
|
||||
&wb,
|
||||
"<< /Length 0 >>\nstream\n\nendstream",
|
||||
];
|
||||
let dir = workdir(name);
|
||||
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
|
||||
let r = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
(r["fields"][0]["options"].clone(), r["fields"][0]["checked"].clone())
|
||||
};
|
||||
// Kids sharing the on state Yes tick together, whatever their exports: not two options.
|
||||
let shared =
|
||||
listed("check-box-shared-state", "<< /FT /Btn /T (pair) /V /Off /Opt [(x) (y)] /Kids [6 0 R 7 0 R] >>", ("Yes", "Off"), ("Yes", "Off"));
|
||||
assert_eq!(shared, (Value::Null, Value::Null));
|
||||
// /V names B, but A's /AS is on: A is the one ticked.
|
||||
let differ = listed("check-box-as-wins", "<< /FT /Btn /T (pair) /V /B /Kids [6 0 R 7 0 R] >>", ("A", "A"), ("B", "Off"));
|
||||
assert_eq!(differ, (json!(["A", "B"]), json!("A")));
|
||||
// Two on states with one export: the states name the options.
|
||||
let same = listed("check-box-same-export", "<< /FT /Btn /T (pair) /V /B /Opt [(x) (x)] /Kids [6 0 R 7 0 R] >>", ("A", "Off"), ("B", "B"));
|
||||
assert_eq!(same, (json!(["A", "B"]), json!("B")));
|
||||
// B's export is A's on state, so naming it would tick A: the states name the options.
|
||||
let crossed = listed("check-box-crossed-export", "<< /FT /Btn /T (pair) /V /B /Opt [(x) (A)] /Kids [6 0 R 7 0 R] >>", ("A", "Off"), ("B", "B"));
|
||||
assert_eq!(crossed, (json!(["A", "B"]), json!("B")));
|
||||
}
|
||||
|
||||
/// A form whose fields are only page widgets (the `/Fields` list is empty) still lists, fills and
|
||||
/// resets through the tools, and the leniency shows up as a repair note.
|
||||
#[test]
|
||||
@@ -5162,6 +5356,28 @@ fn redacting_through_tools() {
|
||||
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_redactions_proposes_the_name_with_redacted() {
|
||||
let dir = workdir("redact-save-as");
|
||||
std::fs::write(dir.join("memo.txt"), "Call 555-123-4567 today").unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let made = ok(&mut a, "doc_create", json!({ "from": "text", "path": "memo.txt" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "doc_save", json!({ "doc": made, "path": "contract.pdf" }));
|
||||
let original = std::fs::read(dir.join("contract.pdf")).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "contract.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "redact_mark", json!({ "doc": doc, "pattern": "phone" }));
|
||||
let r = ok(&mut a, "redact_apply", json!({ "doc": doc }));
|
||||
assert_eq!(r["save_as"], "contract_Redacted.pdf");
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": r["save_as"] }));
|
||||
assert_eq!(std::fs::read(dir.join("contract.pdf")).unwrap(), original, "the opened file is left as it was");
|
||||
let bytes = std::fs::read(dir.join("contract_Redacted.pdf")).unwrap();
|
||||
assert!(!bytes.windows(4).any(|w| w == b"4567"), "the copy has no trace of the number");
|
||||
// Redacting the redacted copy again proposes the same name, with one suffix.
|
||||
let copy = ok(&mut a, "doc_open", json!({ "path": "contract_Redacted.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "redact_mark", json!({ "doc": copy, "find": "today" }));
|
||||
assert_eq!(ok(&mut a, "redact_apply", json!({ "doc": copy }))["save_as"], "contract_Redacted.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacting_with_a_caller_regex_through_tools() {
|
||||
let dir = workdir("redact-regex");
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! `text_find` on a ligature glyph named in the encoding and on a word divided by a hyphen at a
|
||||
//! line end.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A fresh directory for one test.
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pdfcraft-find-text-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One page: `of<fi>ce` in a Helvetica whose code 128 is named `/fi`, and `exam-` at the end of
|
||||
/// one line with `ple` starting the next.
|
||||
fn find_pdf() -> Vec<u8> {
|
||||
let body = "BT /F2 14 Tf 90 700 Td (of\\200ce) Tj ET\nBT /F1 14 Tf 90 650 Td (exam-) Tj 0 -16 Td (ple) Tj ET\n";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>".to_string(),
|
||||
format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [128 /fi] >> >>"
|
||||
.to_string(),
|
||||
];
|
||||
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());
|
||||
out
|
||||
}
|
||||
|
||||
/// "office" finds the ligature, and "example" both halves of the divided word, highlighted line by
|
||||
/// line; the hyphenated form is still found as written.
|
||||
#[test]
|
||||
fn text_find_matches_ligatures_and_words_divided_at_a_line_end() {
|
||||
let dir = tmp("forms");
|
||||
std::fs::write(dir.join("find.pdf"), find_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "find.pdf" }))["doc"].as_u64().unwrap();
|
||||
let find = |a: &mut Automation, q: &str| ok(a, "text_find", json!({ "doc": doc, "query": q }));
|
||||
|
||||
let office = find(&mut a, "office");
|
||||
assert_eq!(office["count"], 1, "{office}");
|
||||
let rects = office["matches"][0]["rects"].as_array().unwrap();
|
||||
assert_eq!(rects.len(), 1);
|
||||
assert!((rects[0][0].as_f64().unwrap() - 90.0).abs() < 0.5, "from the left edge of the o: {rects:?}");
|
||||
|
||||
let example = find(&mut a, "example");
|
||||
assert_eq!(example["count"], 1, "{example}");
|
||||
assert_eq!(example["matches"][0]["text"], "exam-\nple");
|
||||
let rects = example["matches"][0]["rects"].as_array().unwrap();
|
||||
assert_eq!(rects.len(), 2, "one highlight on each line: {rects:?}");
|
||||
let top = |k: usize| rects[k][1].as_f64().unwrap();
|
||||
assert!(top(1) > top(0) + 10.0, "the second on the next line down: {rects:?}");
|
||||
|
||||
for q in ["exam-ple", "Exam- ple", "exam-"] {
|
||||
assert_eq!(find(&mut a, q)["count"], 1, "{q}");
|
||||
}
|
||||
assert_eq!(find(&mut a, "examples")["count"], 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Which options a list box has selected, through the tool table (ISO 32000-2 Table 234, `/I`).
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn tool(a: &mut Automation, name: &str, args: Value) -> Value {
|
||||
match a.call(name, &args).unwrap().remove(0) {
|
||||
Content::Json(value) => value,
|
||||
other => panic!("expected JSON: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF of the given objects (numbered from 1).
|
||||
fn pdf_of(objs: &[&str]) -> Vec<u8> {
|
||||
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());
|
||||
out
|
||||
}
|
||||
|
||||
fn open(test: &str) -> (Automation, u64, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-list-selection-{test}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let bytes = pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (D_dup) /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] /V (1) /I [1] /Rect [50 250 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (H_twovals) /Opt [[(TW) (Taiwan)] [(JP) (Japan)] [(US) (United States)]] /V [(TW) (JP)] /Rect [50 150 200 220] /P 3 0 R /F 4 >>",
|
||||
]);
|
||||
std::fs::write(dir.join("choice.pdf"), bytes).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let id = tool(&mut a, "doc_open", json!({ "path": "choice.pdf" }))["doc"].as_u64().unwrap();
|
||||
(a, id, dir)
|
||||
}
|
||||
|
||||
fn field(a: &mut Automation, doc: u64, name: &str) -> Value {
|
||||
let all = tool(a, "form_fields", json!({ "doc": doc }));
|
||||
all["fields"].as_array().unwrap().iter().find(|f| f["name"] == name).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Two options share the export value `1`: `selected` says which one `/I` picks, and filling the
|
||||
/// field with an option's label picks that option.
|
||||
#[test]
|
||||
fn form_fields_reports_which_of_two_options_with_one_export_value_is_selected() {
|
||||
let (mut a, doc, dir) = open("dup");
|
||||
let d = field(&mut a, doc, "D_dup");
|
||||
assert_eq!(d["value"], "1");
|
||||
assert_eq!(d["selected"], json!([2]), "One-B, the second option: {d}");
|
||||
tool(&mut a, "form_fill", json!({ "doc": doc, "values": { "D_dup": "One-A" } }));
|
||||
let d = field(&mut a, doc, "D_dup");
|
||||
assert_eq!((d["value"].clone(), d["selected"].clone()), (json!("1"), json!([1])), "{d}");
|
||||
tool(&mut a, "form_fill", json!({ "doc": doc, "values": { "D_dup": "One-B" } }));
|
||||
let d = field(&mut a, doc, "D_dup");
|
||||
assert_eq!(d["selected"], json!([2]));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A list box without MultiSelect given `/V [(TW) (JP)]` reports Taiwan alone (ISO 32000-2
|
||||
/// Table 233: "at most one item shall be selected"), and filling it writes one value.
|
||||
#[test]
|
||||
fn form_fields_reports_one_value_for_a_single_select_list_given_two() {
|
||||
let (mut a, doc, dir) = open("twovals");
|
||||
let h = field(&mut a, doc, "H_twovals");
|
||||
assert_eq!((h["value"].clone(), h["selected"].clone()), (json!("TW"), json!([1])), "{h}");
|
||||
tool(&mut a, "form_fill", json!({ "doc": doc, "values": { "H_twovals": "United States" } }));
|
||||
let h = field(&mut a, doc, "H_twovals");
|
||||
assert_eq!((h["value"].clone(), h["selected"].clone()), (json!("US"), json!([3])), "{h}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -9,8 +9,10 @@ mod batch;
|
||||
mod batch_failures;
|
||||
mod batch_secrets;
|
||||
mod button_caption;
|
||||
mod find_text;
|
||||
mod form_bulk;
|
||||
mod hostile_args;
|
||||
mod list_selection;
|
||||
mod model_3d;
|
||||
mod model_render;
|
||||
mod optimize_content_boundaries;
|
||||
|
||||
@@ -132,6 +132,7 @@ pub use pdfcraft_redact::codes::{CODE_SETS as REDACTION_CODE_SETS, CodeSet as Re
|
||||
pub use pdfcraft_redact::patterns::{
|
||||
MAX_WORDS as REDACT_MAX_WORDS, PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern, word_list as redact_word_list,
|
||||
};
|
||||
pub use pdfcraft_redact::redacted_file_name;
|
||||
pub use pdfcraft_redact::sanitize::{HIDDEN, Hidden};
|
||||
pub use pdfcraft_redact::user_regex::{UserRegex as RedactRegex, VALIDATORS as REDACT_VALIDATORS, Validator as RedactValidator};
|
||||
pub use pdfcraft_sign as sign;
|
||||
|
||||
@@ -1051,6 +1051,8 @@ mod tests {
|
||||
flags: 0,
|
||||
max_len: None,
|
||||
options: Vec::new(),
|
||||
selected: Vec::new(),
|
||||
single_value_is_array: false,
|
||||
da: String::new(),
|
||||
quadding: 0,
|
||||
tooltip: None,
|
||||
|
||||
@@ -858,11 +858,15 @@ fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String]
|
||||
size = rows.size;
|
||||
let line = rows.row;
|
||||
let mut y = height - rows.inset;
|
||||
for (export, display) in f.options.iter().skip(rows.top) {
|
||||
// The field's own selection (its `/I`) when these are its values; values it doesn't
|
||||
// hold yet select by export value alone.
|
||||
let picked = if values == f.value.as_slice() { f.selected.clone() } else { crate::selected_options(&f.options, values, None) };
|
||||
for (i, (_, display)) in f.options.iter().enumerate().skip(rows.top) {
|
||||
if y - line < 0.0 {
|
||||
break;
|
||||
}
|
||||
if values.contains(export) {
|
||||
// Both sources list positions in ascending order.
|
||||
if picked.binary_search(&i).is_ok() {
|
||||
c.push_str(&format!("0.6 0.75 0.86 rg\n{} {} {} {} re f\n", n(bw), n(y - line), n(width - 2.0 * bw), n(line)));
|
||||
}
|
||||
show(pad, y - line + size * 0.25, display);
|
||||
|
||||
+88
-7
@@ -42,10 +42,11 @@ mod values;
|
||||
|
||||
pub use appearances::{FieldAppearanceCache, declares_pdfa, need_appearances, undrawn_fields, with_field_appearances, with_field_appearances_cached};
|
||||
pub(crate) use read::page_refs;
|
||||
pub use read::selected_options;
|
||||
pub use read::{Fields, acroform, adopted_page_fields, fields, fields_with_adopted};
|
||||
#[cfg(test)]
|
||||
use read::{MAX_SCRIPT_BYTES, PageWalk, enumerate, form_reads};
|
||||
use read::{script, script_budget};
|
||||
use read::{first_by_export, script, script_budget};
|
||||
pub use tab_order::{TabOrder, move_in_tab_order, set_tab_order, tab_orders};
|
||||
#[cfg(test)]
|
||||
use values::has_password_flag;
|
||||
@@ -159,6 +160,14 @@ pub struct Field {
|
||||
pub max_len: Option<usize>,
|
||||
/// Choice options: (export value, display text).
|
||||
pub options: Vec<(String, String)>,
|
||||
/// Combo and list boxes: the selected options, as ascending positions in `options` (see
|
||||
/// [`selected_options`]). Two options can share an export value, so `value` alone can't say
|
||||
/// which of them is selected. Empty for other kinds.
|
||||
pub selected: Vec<usize>,
|
||||
/// A list box without MultiSelect whose `/V` is an array (a value of one option is a string,
|
||||
/// ISO 32000-2 Table 233): `value` holds its first entry only, and picking that option again
|
||||
/// writes the value as one string rather than leaving the array.
|
||||
pub single_value_is_array: bool,
|
||||
/// Default appearance string (`/DA`, inherited from the form if absent).
|
||||
pub da: String,
|
||||
/// Quadding: 0 left, 1 centred, 2 right.
|
||||
@@ -252,18 +261,75 @@ impl Field {
|
||||
&& self.widgets.iter().position(|x| sharing(x) && x.state.is_none()) == Some(i)
|
||||
}
|
||||
|
||||
/// The value that gives this check box the stored value `value` (`/V`, `/DV`, imported or
|
||||
/// script data): the on state it names (or whose `/Opt` export it is), so that of kids with
|
||||
/// different on states the right one turns on (ISO 32000-2 §12.7.5.2.3, Table 230); checked
|
||||
/// for any other value but Off, unchecked for none.
|
||||
pub fn check_box_value(&self, value: Option<&str>) -> FieldValue {
|
||||
match value.filter(|v| !v.is_empty() && *v != "Off") {
|
||||
Some(v) => self.state_for(v).map_or(FieldValue::Check(true), |s| FieldValue::Text(s.to_owned())),
|
||||
None => FieldValue::Check(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Combo and list boxes: this field's option positions `picked` as positions in `other`'s
|
||||
/// options, in the same order. Same-name twins are one field (ISO 32000-2 §12.7.3.1) but can
|
||||
/// list their options in different orders, and a value given by position is read in the first
|
||||
/// twin's options. `None` when an option picked has no match in `other`.
|
||||
pub fn positions_in(&self, other: &Field, picked: &[usize]) -> Option<Vec<usize>> {
|
||||
option_positions_in(picked, &self.options, &other.options)
|
||||
}
|
||||
|
||||
/// Combo and list boxes: the selected options in the order the value names them (`/V` keeps
|
||||
/// the order they were picked in), so the last is the latest pick.
|
||||
pub fn picked_in_order(&self) -> Vec<usize> {
|
||||
let mut out: Vec<usize> = Vec::with_capacity(self.selected.len());
|
||||
let mut taken: std::collections::HashSet<usize> = std::collections::HashSet::with_capacity(self.selected.len());
|
||||
let mut unpicked = self.selected_by_export();
|
||||
for v in &self.value {
|
||||
if let Some(i) = unpicked.get_mut(v.as_str()).and_then(std::collections::VecDeque::pop_front) {
|
||||
taken.insert(i);
|
||||
out.push(i);
|
||||
}
|
||||
}
|
||||
// Positions `/I` holds beyond what the value names (none while the two agree).
|
||||
out.extend(self.selected.iter().copied().filter(|i| !taken.contains(i)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The value as one string: text, the state name, or the selected display texts.
|
||||
pub fn display_value(&self) -> String {
|
||||
match self.kind {
|
||||
FieldKind::Combo | FieldKind::List => self
|
||||
.value
|
||||
.iter()
|
||||
.map(|v| self.options.iter().find(|(e, _)| e == v).map_or(v.clone(), |(_, d)| d.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
FieldKind::Combo | FieldKind::List => {
|
||||
// Each value as the selected option it names (options can share an export
|
||||
// value), in the value's order; past those, the first option exporting it.
|
||||
let mut unpicked = self.selected_by_export();
|
||||
let first = first_by_export(&self.options);
|
||||
self.value
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let i =
|
||||
unpicked.get_mut(v.as_str()).and_then(std::collections::VecDeque::pop_front).or_else(|| first.get(v.as_str()).copied());
|
||||
i.and_then(|i| self.options.get(i)).map_or(v.clone(), |(_, d)| d.clone())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
_ => self.value.join(", "),
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected positions grouped by the export value of their option, each group
|
||||
/// ascending, so a value takes the next selected option exporting it in one lookup.
|
||||
fn selected_by_export(&self) -> std::collections::HashMap<&str, std::collections::VecDeque<usize>> {
|
||||
let mut out: std::collections::HashMap<&str, std::collections::VecDeque<usize>> = std::collections::HashMap::new();
|
||||
for &i in &self.selected {
|
||||
if let Some((e, _)) = self.options.get(i) {
|
||||
out.entry(e.as_str()).or_default().push_back(i);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A value to put in a field.
|
||||
@@ -281,6 +347,10 @@ pub enum FieldValue {
|
||||
Widget(usize),
|
||||
/// Combo box or list box: export values (several only for multi-select lists).
|
||||
Choice(Vec<String>),
|
||||
/// Combo box or list box: options by their zero-based position in `/Opt` (as `/I` numbers
|
||||
/// them), which tells apart options that share an export value. Several only for
|
||||
/// multi-select lists; `/V` takes them in this order.
|
||||
ChoiceIndices(Vec<usize>),
|
||||
}
|
||||
|
||||
// ── reading ─────────────────────────────────────────────────────────────────────────────────
|
||||
@@ -334,3 +404,14 @@ fn name_obj(text: &str) -> Object {
|
||||
fn invalid<T>(m: impl Into<String>) -> Result<T, FormError> {
|
||||
Err(FormError::Invalid(m.into()))
|
||||
}
|
||||
|
||||
/// The positions in `target` of the options at positions `picked` in `source`, in the same order:
|
||||
/// each goes to `target`'s first not yet taken option with the same export value and text, so two
|
||||
/// options sharing both stay apart. `None` when one has no such option in `target`.
|
||||
pub(crate) fn option_positions_in(picked: &[usize], source: &[(String, String)], target: &[(String, String)]) -> Option<Vec<usize>> {
|
||||
let mut free: std::collections::HashMap<(&str, &str), std::collections::VecDeque<usize>> = std::collections::HashMap::new();
|
||||
for (i, (e, d)) in target.iter().enumerate() {
|
||||
free.entry((e.as_str(), d.as_str())).or_default().push_back(i);
|
||||
}
|
||||
picked.iter().map(|&p| source.get(p).and_then(|(e, d)| free.get_mut(&(e.as_str(), d.as_str()))).and_then(|q| q.pop_front())).collect()
|
||||
}
|
||||
@@ -243,6 +243,69 @@ fn values_of(doc: &Document, o: Option<&Object>, budget: &mut DecodeBudget) -> V
|
||||
}
|
||||
}
|
||||
|
||||
/// A choice field's `/I` (ISO 32000-2 Table 234) as option positions, when it is usable: an array
|
||||
/// of integers "sorted in ascending order", each naming one of `count` options. `None` when it is
|
||||
/// absent or anything in it is not (a non-integer, a position out of range, out of order or
|
||||
/// repeated), so the field falls back to `/V`.
|
||||
pub(crate) fn listed_indices(doc: &Document, d: &Dict, count: usize) -> Option<Vec<usize>> {
|
||||
let listed = doc.resolve(d.get(b"I")?);
|
||||
let entries = listed.as_array()?;
|
||||
// Strictly ascending positions below `count` number at most `count`.
|
||||
if entries.len() > count {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<usize> = Vec::with_capacity(entries.len());
|
||||
for e in entries {
|
||||
let i = usize::try_from(doc.resolve(e).as_int()?).ok().filter(|&i| i < count)?;
|
||||
if out.last().is_some_and(|&last| last >= i) {
|
||||
return None;
|
||||
}
|
||||
out.push(i);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The options a choice field shows selected, as ascending positions in `options`, given its
|
||||
/// values (`/V`) and its usable `/I` ([`listed_indices`]).
|
||||
///
|
||||
/// `/I` decides when it names the same export values as `/V`: it "shall be used when two or more
|
||||
/// elements in the Opt array have different names but the same export value", and "if the items
|
||||
/// identified by this entry differ from those in the V entry …, the V entry shall be used" (ISO
|
||||
/// 32000-2 Table 234). Otherwise each value selects the first option with that export value, as
|
||||
/// the writer numbers `/I` when it is given only an export value, so a pick keeps showing the same
|
||||
/// option when `/I` is lost. A value no option exports selects nothing.
|
||||
pub fn selected_options(options: &[(String, String)], values: &[String], listed: Option<&[usize]>) -> Vec<usize> {
|
||||
if let Some(listed) = listed {
|
||||
// The same items, each as many times: `/V [(1) (1)]` names two items, which an `/I [1]`
|
||||
// naming one doesn't, so `/V` decides then.
|
||||
let mut named: Vec<&str> = values.iter().map(String::as_str).collect();
|
||||
named.sort_unstable();
|
||||
let exports: Option<Vec<&str>> = listed.iter().map(|&i| options.get(i).map(|(e, _)| e.as_str())).collect();
|
||||
if let Some(mut exports) = exports {
|
||||
exports.sort_unstable();
|
||||
if exports == named {
|
||||
return listed.to_vec();
|
||||
}
|
||||
}
|
||||
}
|
||||
let first = first_by_export(options);
|
||||
let mut out: Vec<usize> = values.iter().filter_map(|v| first.get(v.as_str()).copied()).collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Each export value in `options` with the position of the first option exporting it, so
|
||||
/// matching values against options takes one pass over each rather than one over the options per
|
||||
/// value (a file can hold many of both).
|
||||
pub(crate) fn first_by_export(options: &[(String, String)]) -> std::collections::HashMap<&str, usize> {
|
||||
let mut first: std::collections::HashMap<&str, usize> = std::collections::HashMap::with_capacity(options.len());
|
||||
for (i, (e, _)) in options.iter().enumerate() {
|
||||
first.entry(e.as_str()).or_insert(i);
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
fn nums(doc: &Document, o: Option<&Object>) -> Option<Vec<f64>> {
|
||||
let o = doc.resolve(o?);
|
||||
o.as_array()?.iter().map(|x| doc.resolve(x).as_f64()).collect()
|
||||
@@ -676,16 +739,36 @@ fn walk(
|
||||
Object::Array(pair) if pair.len() >= 2 => Some((text_of(&doc.resolve(&pair[0]))?, text_of(&doc.resolve(&pair[1]))?)),
|
||||
other => text_of(other).map(|t| (t.clone(), t)),
|
||||
})
|
||||
.collect();
|
||||
.collect::<Vec<(String, String)>>();
|
||||
let mut value = values_of(doc, inh.v.as_ref(), &mut seen.values);
|
||||
// A list box without MultiSelect selects one option: "if clear, at most one item shall be
|
||||
// selected" (ISO 32000-2 Table 233). Given an array /V or /DV anyway, it holds the first
|
||||
// value only, and shows and resets to it; the file keeps its entries until the field is filled.
|
||||
let mut default = values_of(doc, inh.dv.as_ref(), &mut seen.values);
|
||||
let single = kind == FieldKind::List && ff & flags::MULTI_SELECT == 0;
|
||||
let single_value_is_array = single && inh.v.as_ref().is_some_and(|v| doc.resolve(v).as_array().is_some());
|
||||
if single {
|
||||
value.truncate(1);
|
||||
default.truncate(1);
|
||||
}
|
||||
let mut selected = match kind {
|
||||
FieldKind::Combo | FieldKind::List => selected_options(&options, &value, listed_indices(doc, d, options.len()).as_deref()),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if single {
|
||||
selected.truncate(1);
|
||||
}
|
||||
out.push(Field {
|
||||
name: inh.name.clone(),
|
||||
obj: r,
|
||||
kind,
|
||||
value: values_of(doc, inh.v.as_ref(), &mut seen.values),
|
||||
default: values_of(doc, inh.dv.as_ref(), &mut seen.values),
|
||||
value,
|
||||
default,
|
||||
flags: ff,
|
||||
max_len: inh.max_len,
|
||||
options,
|
||||
selected,
|
||||
single_value_is_array,
|
||||
da: inh.da.clone().unwrap_or_else(|| "/Helv 0 Tf 0 g".into()),
|
||||
quadding: inh.q.unwrap_or(0),
|
||||
tooltip: d.get(b"TU").and_then(|o| text_of(&doc.resolve(o))),
|
||||
|
||||
@@ -140,7 +140,7 @@ pub(crate) fn apply_changes(doc: &mut Document, changes: &[FieldChange], except:
|
||||
{
|
||||
let value = match f.kind {
|
||||
FieldKind::Text => FieldValue::Text(v.first().cloned().unwrap_or_default()),
|
||||
FieldKind::CheckBox => FieldValue::Check(!v.is_empty()),
|
||||
FieldKind::CheckBox => f.check_box_value(v.first().map(String::as_str)),
|
||||
FieldKind::Radio => FieldValue::Radio(v.first().cloned()),
|
||||
FieldKind::Combo | FieldKind::List => FieldValue::Choice(v.clone()),
|
||||
_ => continue,
|
||||
|
||||
@@ -6547,6 +6547,338 @@ fn a_read_only_button_is_not_turned_on_by_number() {
|
||||
assert_eq!(on_widgets(&doc, "r").0, [false, false, true]);
|
||||
}
|
||||
|
||||
/// Two check box fields of two kids each: `pair` with the on states `A` and `B` (and `/DV /B`),
|
||||
/// `same` with `Yes` twice.
|
||||
fn check_box_kids() -> Document {
|
||||
let kid = |parent: usize, x: u32, state: &str| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /Parent {parent} 0 R /AS /Off /Rect [{x} 700 {} 715] /P 3 0 R /AP << /N << /{state} 10 0 R /Off 11 0 R >> >> >>",
|
||||
x + 15
|
||||
)
|
||||
};
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R] >>".into(), // 3
|
||||
"<< /Fields [5 0 R 12 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 4
|
||||
"<< /FT /Btn /T (pair) /V /Off /DV /B /Kids [6 0 R 7 0 R] >>".into(), // 5
|
||||
kid(5, 100, "A"), // 6
|
||||
kid(5, 200, "B"), // 7
|
||||
kid(12, 100, "Yes"), // 8
|
||||
kid(12, 200, "Yes"), // 9
|
||||
"<< /Length 0 >>\nstream\n\nendstream".into(), // 10
|
||||
"<< /Length 0 >>\nstream\n\nendstream".into(), // 11
|
||||
"<< /FT /Btn /T (same) /V /Off /Kids [8 0 R 9 0 R] >>".into(), // 12
|
||||
];
|
||||
document(&objs)
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.7.5.2.3: a check box field's `/V` is the on state of its kid that is on, and
|
||||
/// its kids can have different on states (Table 230). Naming `B` ticks `B` and clears `A`;
|
||||
/// "checked" keeps the kid that is on; a reset goes back to `/DV /B`. Kids sharing `Yes` tick
|
||||
/// together (EXAMPLE 2).
|
||||
#[test]
|
||||
fn check_box_kids_with_different_on_states_tick_one_at_a_time() {
|
||||
let mut doc = check_box_kids();
|
||||
set_value(&mut doc, "pair", &FieldValue::Text("A".into())).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![true, false], vec!["A".to_string()]));
|
||||
set_value(&mut doc, "pair", &FieldValue::Text("B".into())).unwrap();
|
||||
let mut doc = reopen(&doc);
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, true], vec!["B".to_string()]), "B, after a save");
|
||||
set_value(&mut doc, "pair", &FieldValue::Check(true)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair").0, [false, true], "checked keeps the kid that is on");
|
||||
set_value(&mut doc, "pair", &FieldValue::Check(false)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, false], vec![]));
|
||||
set_value(&mut doc, "pair", &FieldValue::Check(true)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair").0, [true, false], "from off, checked takes the first kid");
|
||||
reset(&mut doc, None).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, true], vec!["B".to_string()]), "reset goes back to /DV /B");
|
||||
// Kids sharing an on state tick and untick together.
|
||||
set_value(&mut doc, "same", &FieldValue::Text("Yes".into())).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "same"), (vec![true, true], vec!["Yes".to_string()]));
|
||||
set_value(&mut doc, "same", &FieldValue::Check(false)).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "same").0, [false, false]);
|
||||
assert!(matches!(set_value(&mut doc, "pair", &FieldValue::Text("C".into())), Err(FormError::Invalid(_))));
|
||||
// A script that sets the value to B ticks B.
|
||||
let to_b = FieldChange { name: "pair".into(), value: Some(vec!["B".into()]), ..FieldChange::default() };
|
||||
set_value(&mut doc, "pair", &FieldValue::Text("A".into())).unwrap();
|
||||
apply_script_changes(&mut doc, &[to_b], &mut NoScripts).unwrap();
|
||||
assert_eq!(on_widgets(&doc, "pair"), (vec![false, true], vec!["B".to_string()]), "a script's B");
|
||||
}
|
||||
|
||||
/// A one-page form with list box `dup` (single select unless `ff` says otherwise) whose first two
|
||||
/// options share the export value `1`, plus `extra` entries (`/V`, `/I`) on the field.
|
||||
fn duplicate_exports(ff: u32, extra: &str) -> Document {
|
||||
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 [6 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Ff {ff} /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] {extra} /Rect [50 700 200 746] /P 3 0 R >>"
|
||||
),
|
||||
];
|
||||
document(&objs)
|
||||
}
|
||||
|
||||
/// The bottom edges of the highlighted rows in a list box appearance, top row first.
|
||||
fn highlighted_rows(appearance: &str) -> Vec<String> {
|
||||
let lines: Vec<&str> = appearance.lines().collect();
|
||||
lines.windows(2).filter(|w| w[0] == "0.6 0.75 0.86 rg").map(|w| w[1].split(' ').nth(1).unwrap_or_default().to_string()).collect()
|
||||
}
|
||||
|
||||
/// The rows the display copy (`/NeedAppearances`) highlights in `dup`.
|
||||
fn shown_rows(doc: &Document) -> Vec<String> {
|
||||
let copy = with_field_appearances(doc).expect("the form leaves its appearances to the viewer");
|
||||
highlighted_rows(&ap(©, &field(&fields(©), "dup").widgets[0]))
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 234: `/I` "shall be used when two or more elements in the Opt array have
|
||||
/// different names but the same export value". `/V (1)` with `/I [1]` selects One-B alone, not
|
||||
/// every option exporting `1`.
|
||||
#[test]
|
||||
fn a_list_box_with_duplicate_export_values_selects_the_option_i_names() {
|
||||
let doc = duplicate_exports(0, "/V (1) /I [1]");
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
assert_eq!(dup.selected, [1]);
|
||||
assert_eq!(dup.display_value(), "One-B");
|
||||
let one_b = shown_rows(&doc);
|
||||
assert_eq!(one_b.len(), 1, "one highlighted row");
|
||||
// The same field with /I [0] highlights the row above it.
|
||||
let one_a = shown_rows(&duplicate_exports(0, "/V (1) /I [0]"));
|
||||
assert_eq!(one_a.len(), 1);
|
||||
assert_ne!(one_a, one_b, "One-A and One-B are different rows");
|
||||
let row = |s: &[String]| s.first().and_then(|y| y.parse::<f64>().ok()).unwrap();
|
||||
assert!(row(&one_b) < row(&one_a), "One-B is drawn below One-A");
|
||||
}
|
||||
|
||||
/// Without a usable `/I`, `/V` decides (Table 234: "If the items identified by this entry differ
|
||||
/// from those in the V entry …, the V entry shall be used"), and an export value two options
|
||||
/// share selects the first of them. A malformed `/I` never panics.
|
||||
#[test]
|
||||
fn an_unusable_i_falls_back_to_the_first_option_with_the_value() {
|
||||
for (extra, multi, want) in [
|
||||
("/V (1)", 0, vec![0]), // no /I: the first option exporting 1
|
||||
("/V (1) /I [5]", 0, vec![0]), // out of range
|
||||
("/V (1) /I [-1]", 0, vec![0]), // negative
|
||||
("/V (1) /I [(1)]", 0, vec![0]), // not an integer
|
||||
("/V (1) /I [1.5]", 0, vec![0]), // not a whole number
|
||||
("/V (1) /I 1", 0, vec![0]), // not an array
|
||||
("/V (1) /I [2]", 0, vec![0]), // names Two, which /V doesn't
|
||||
("/V (1) /I []", 0, vec![0]), // names nothing
|
||||
("/V [(1) (2)] /I [2 1]", 1 << 21, vec![0, 2]), // not ascending
|
||||
("/V [(1) (2)] /I [1 1 2]", 1 << 21, vec![0, 2]), // repeated
|
||||
("/V [(1) (2)] /I [1 2]", 1 << 21, vec![1, 2]), // usable: One-B and Two
|
||||
("/V [(1) (1)] /I [0 1]", 1 << 21, vec![0, 1]), // usable: both options exporting 1
|
||||
("/V [(1) (1)] /I [1]", 1 << 21, vec![0]), // names one item where /V names two
|
||||
("/V [] /I [1]", 0, vec![]), // an empty value selects nothing
|
||||
("/V (9)", 0, vec![]), // no option exports 9
|
||||
] {
|
||||
let doc = duplicate_exports(multi, extra);
|
||||
assert_eq!(field(&fields(&doc), "dup").selected, want, "{extra}");
|
||||
assert_eq!(shown_rows(&doc).len(), want.len(), "{extra}");
|
||||
}
|
||||
// Pure: positions past the options or unlike the values are ignored.
|
||||
let options = [("1".to_string(), "One-A".to_string()), ("1".to_string(), "One-B".to_string())];
|
||||
assert_eq!(selected_options(&options, &["1".into()], Some(&[1])), [1]);
|
||||
assert_eq!(selected_options(&options, &["1".into()], Some(&[7])), [0]);
|
||||
assert_eq!(selected_options(&options, &[], Some(&[])), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
/// Picking an option by position writes its export value to `/V` and its position to `/I`, so a
|
||||
/// pick of One-A or One-B survives a save and reopen; picking by display text does the same.
|
||||
#[test]
|
||||
fn picking_one_of_two_options_with_the_same_export_value_round_trips() {
|
||||
for (value, want) in [
|
||||
(FieldValue::ChoiceIndices(vec![0]), 0),
|
||||
(FieldValue::ChoiceIndices(vec![1]), 1),
|
||||
(FieldValue::Text("One-B".into()), 1),
|
||||
(FieldValue::Text("One-A".into()), 0),
|
||||
(FieldValue::Choice(vec!["1".into()]), 0),
|
||||
] {
|
||||
let mut doc = duplicate_exports(0, "/V (1) /I [1]");
|
||||
set_value(&mut doc, "dup", &value).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
let d = doc.get(dup.obj).as_dict().cloned().unwrap();
|
||||
assert_eq!(d.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("1"), "{value:?}: /V is one string");
|
||||
let i: Vec<i64> = d.get(b"I").and_then(|i| i.as_array()).unwrap().iter().filter_map(Object::as_int).collect();
|
||||
assert_eq!(i, [want as i64], "{value:?}");
|
||||
assert_eq!(dup.selected, [want], "{value:?}");
|
||||
assert_eq!(highlighted_rows(&ap(&doc, &dup.widgets[0])).len(), 1, "{value:?}: its saved look highlights one row");
|
||||
}
|
||||
// The saved look highlights the row picked, not the first with its value.
|
||||
let saved = |pick: usize| {
|
||||
let mut doc = duplicate_exports(0, "");
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![pick])).unwrap();
|
||||
highlighted_rows(&ap(&doc, &field(&fields(&doc), "dup").widgets[0]))
|
||||
};
|
||||
assert_ne!(saved(0), saved(1));
|
||||
// Positions are checked: out of range, or several in a single-select list.
|
||||
let mut doc = duplicate_exports(0, "");
|
||||
assert!(matches!(set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![3])), Err(FormError::Invalid(_))));
|
||||
assert!(matches!(set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![usize::MAX])), Err(FormError::Invalid(_))));
|
||||
assert!(matches!(set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![0, 1])), Err(FormError::Invalid(_))));
|
||||
// A multi-select list takes both options that share the value, in ascending /I.
|
||||
let mut doc = duplicate_exports(1 << 21, "");
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![1, 0])).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
assert_eq!(dup.value, ["1", "1"]);
|
||||
assert_eq!(dup.selected, [0, 1]);
|
||||
assert_eq!(dup.picked_in_order(), [0, 1]);
|
||||
// A check box can't take positions.
|
||||
let mut doc = fixture();
|
||||
assert!(matches!(set_value(&mut doc, "agree", &FieldValue::ChoiceIndices(vec![0])), Err(FormError::Invalid(_))));
|
||||
}
|
||||
|
||||
/// A file can hold a list box with very many options and values. Matching values to options
|
||||
/// takes one lookup per value, not a scan of the options (or of the selection) for each, so
|
||||
/// reading and showing such a field stays fast. Two options share each export value, and every
|
||||
/// result still names the first option exporting a value, or the next one selected.
|
||||
#[test]
|
||||
fn many_options_and_values_match_in_linear_time() {
|
||||
const N: usize = 100_000;
|
||||
let options: Vec<(String, String)> = (0..2 * N).map(|i| (format!("e{}", i / 2), format!("d{i}"))).collect();
|
||||
let values: Vec<String> = (0..N).rev().map(|k| format!("e{k}")).collect();
|
||||
let started = std::time::Instant::now();
|
||||
let selected = selected_options(&options, &values, None);
|
||||
assert_eq!(selected, (0..N).map(|k| 2 * k).collect::<Vec<_>>(), "the first option exporting each value");
|
||||
let took = started.elapsed();
|
||||
assert!(took < std::time::Duration::from_secs(2), "selected_options took {took:?}");
|
||||
|
||||
let mut list = field(&fields(&fixture()), "toppings").clone();
|
||||
list.options = options;
|
||||
list.value = values;
|
||||
list.selected = (0..2 * N).collect();
|
||||
let started = std::time::Instant::now();
|
||||
let order = list.picked_in_order();
|
||||
let shown = list.display_value();
|
||||
let took = started.elapsed();
|
||||
assert!(took < std::time::Duration::from_secs(2), "picked_in_order and display_value took {took:?}");
|
||||
// The values name e{N-1} first: its first option, then down to e0; the second option of
|
||||
// each value is selected without a value naming it, so it follows in ascending order.
|
||||
assert_eq!(order.first(), Some(&(2 * (N - 1))));
|
||||
assert_eq!(order.get(N - 1), Some(&0));
|
||||
assert_eq!(order.get(N..), Some(&(0..N).map(|k| 2 * k + 1).collect::<Vec<_>>()[..]));
|
||||
assert!(shown.starts_with(&format!("d{}, d{}", 2 * (N - 1), 2 * (N - 2))), "{}", shown.get(..40).unwrap_or(&shown));
|
||||
}
|
||||
|
||||
/// A one-page form with list box `pair` (single select unless `ff` says otherwise) of three
|
||||
/// countries, plus `extra` entries (`/V`, `/DV`, `/I`) on the field.
|
||||
fn countries(ff: u32, extra: &str) -> Document {
|
||||
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 [6 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (pair) /Ff {ff} /Opt [[(TW) (Taiwan)] [(JP) (Japan)] [(US) (United States)]] {extra} /Rect [50 700 200 746] /P 3 0 R >>"
|
||||
),
|
||||
];
|
||||
document(&objs)
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 233, MultiSelect: "if clear, at most one item shall be selected". A list box
|
||||
/// without it given `/V [(TW) (JP)]` holds and shows Taiwan alone, and opening it changes nothing
|
||||
/// in the file.
|
||||
#[test]
|
||||
fn a_single_select_list_given_several_values_shows_the_first() {
|
||||
for (extra, multi, value, want) in [
|
||||
("/V [(TW) (JP)]", 0, vec!["TW"], vec![0]),
|
||||
("/V [(JP) (TW)]", 0, vec!["JP"], vec![1]),
|
||||
("/V [(TW) (JP)] /I [0 1]", 0, vec!["TW"], vec![0]), // /I names more than the one value
|
||||
("/V [(XX) (JP)]", 0, vec!["XX"], vec![]), // the first value is no option
|
||||
("/V []", 0, vec![], vec![]),
|
||||
("/V [(TW) (JP)]", 1 << 21, vec!["TW", "JP"], vec![0, 1]), // multi-select keeps both
|
||||
] {
|
||||
let doc = countries(multi, extra);
|
||||
let pair = field(&fields(&doc), "pair").clone();
|
||||
assert_eq!(pair.value, value, "{extra}");
|
||||
assert_eq!(pair.selected, want, "{extra}");
|
||||
let copy = with_field_appearances(&doc).expect("left to the viewer");
|
||||
assert_eq!(highlighted_rows(&ap(©, &field(&fields(©), "pair").widgets[0])).len(), want.len(), "{extra}");
|
||||
// Reading and drawing the display copy leaves the field's own /V as it was.
|
||||
let v = doc.get(pair.obj).as_dict().and_then(|d| d.get(b"V").cloned()).unwrap();
|
||||
assert!(matches!(v, Object::Array(_)), "{extra}: {v:?}");
|
||||
}
|
||||
// Two options selected by /I alone in a single-select list: the first.
|
||||
let doc = duplicate_exports(0, "/V (1) /I [0 1]");
|
||||
assert_eq!(field(&fields(&doc), "dup").selected, [0]);
|
||||
}
|
||||
|
||||
/// Picking a row in such a list writes one string to `/V` and that option's position to `/I`,
|
||||
/// and Clear form goes back to the first value of an array `/DV` instead of refusing it.
|
||||
#[test]
|
||||
fn picking_in_a_single_select_list_given_several_values_writes_one() {
|
||||
for (pick, export, index) in [(FieldValue::ChoiceIndices(vec![2]), "US", 2), (FieldValue::Choice(vec!["JP".into()]), "JP", 1)] {
|
||||
let mut doc = countries(0, "/V [(TW) (JP)] /I [0 1]");
|
||||
set_value(&mut doc, "pair", &pick).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let pair = field(&fields(&doc), "pair").clone();
|
||||
let d = doc.get(pair.obj).as_dict().cloned().unwrap();
|
||||
assert_eq!(d.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some(export), "{pick:?}: /V is one string");
|
||||
let i: Vec<i64> = d.get(b"I").and_then(|i| i.as_array()).unwrap().iter().filter_map(Object::as_int).collect();
|
||||
assert_eq!(i, [index], "{pick:?}");
|
||||
assert_eq!((pair.value, pair.selected), (vec![export.to_string()], vec![index as usize]));
|
||||
}
|
||||
let mut doc = countries(0, "/V (US) /DV [(JP) (TW)]");
|
||||
assert_eq!(reset(&mut doc, None).unwrap(), 1);
|
||||
let pair = field(&fields(&doc), "pair").clone();
|
||||
assert_eq!((pair.value, pair.selected), (vec!["JP".to_string()], vec![1]));
|
||||
}
|
||||
|
||||
/// A position picked twice is written once in both `/V` and `/I`, so they still match item for
|
||||
/// item and the option picked (the second of two sharing an export value) comes back on reopen.
|
||||
#[test]
|
||||
fn a_position_picked_twice_is_written_once_in_v_and_i() {
|
||||
let mut doc = duplicate_exports(1 << 21, "");
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![1, 1])).unwrap();
|
||||
let dup = field(&fields(&doc), "dup").clone();
|
||||
let d = doc.get(dup.obj).as_dict().cloned().unwrap();
|
||||
let v: Vec<String> = match d.get(b"V") {
|
||||
Some(Object::Array(a)) => a.iter().filter_map(|o| o.as_string().map(|s| s.to_text())).collect(),
|
||||
Some(o) => o.as_string().map(|s| vec![s.to_text()]).unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let i: Vec<i64> = d.get(b"I").and_then(|i| i.as_array()).map(|a| a.iter().filter_map(Object::as_int).collect()).unwrap_or_default();
|
||||
assert_eq!((v, i), (vec!["1".to_string()], vec![1]), "one entry each");
|
||||
assert_eq!(dup.selected, [1], "One-B, not One-A");
|
||||
}
|
||||
|
||||
/// A same-name twin listing the options sharing an export value in another order is given the
|
||||
/// option picked, not the one at the same position: `/I` is mapped to the twin's own options.
|
||||
#[test]
|
||||
fn a_twin_with_options_in_another_order_gets_the_option_picked() {
|
||||
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 [6 0 R 7 0 R] >>".into(),
|
||||
"<< /Fields [6 0 R 7 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Ff 0 /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] /Rect [50 700 200 746] /P 3 0 R >>"
|
||||
.into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Ff 0 /Opt [[(1) (One-B)] [(1) (One-A)] [(2) (Two)]] /Rect [50 600 200 646] /P 3 0 R >>"
|
||||
.into(),
|
||||
];
|
||||
let mut doc = document(&objs);
|
||||
set_value(&mut doc, "dup", &FieldValue::ChoiceIndices(vec![1])).unwrap();
|
||||
let all = fields(&doc);
|
||||
let twin = all.iter().find(|f| f.obj == pdfcraft_cos::ObjRef::new(7, 0)).unwrap();
|
||||
let i: Vec<i64> = doc
|
||||
.get(twin.obj)
|
||||
.as_dict()
|
||||
.and_then(|d| d.get(b"I").and_then(|i| i.as_array().cloned()))
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(Object::as_int)
|
||||
.collect();
|
||||
assert_eq!(i, [0], "One-B is first in the twin's options");
|
||||
assert_eq!(twin.selected, [0]);
|
||||
}
|
||||
|
||||
/// A `/MK /BC` or `/BG` written `[1 0 0 null]` is CMYK with the null as 0, as annotation `/C`
|
||||
/// colours are read (PDFBOX-2699), not RGB from the three numbers left; three numbers stay RGB.
|
||||
#[test]
|
||||
|
||||
+132
-46
@@ -1,5 +1,5 @@
|
||||
use super::appearances::{declares_pdfa, need_appearances};
|
||||
use super::read::{acroform, field_flags, fields, listing_fields_named, page_refs};
|
||||
use super::read::{acroform, field_flags, fields, listed_indices, listing_fields_named, page_refs, selected_options};
|
||||
use super::{
|
||||
Dict, Document, Field, FieldEvent, FieldKind, FieldValue, FormError, NoScripts, ObjRef, Object, PdfString, Scripts, Widget, af, appearance,
|
||||
author, calc_order, flags, invalid, name_obj, scripting,
|
||||
@@ -117,7 +117,7 @@ fn fill(doc: &mut Document, all: &[Field], named: &[usize], name: &str, value: &
|
||||
if !twins.is_empty() {
|
||||
let taken = fields(doc).into_iter().find(|x| x.obj == f.obj).map(|x| x.value).unwrap_or_default();
|
||||
for t in twins {
|
||||
share_value(doc, f.obj, t, &taken, scripts)?;
|
||||
share_value(doc, (f.obj, &f.options), t, &taken, scripts)?;
|
||||
}
|
||||
}
|
||||
// A field whose `/Kids` lists radio fields that don't name it as their `/Parent` has their
|
||||
@@ -133,9 +133,15 @@ fn fill(doc: &mut Document, all: &[Field], named: &[usize], name: &str, value: &
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Give `twin` the value `source` holds: its `/V` (and a choice's `/I`), drawn in the twin's own
|
||||
/// widgets.
|
||||
fn share_value(doc: &mut Document, source: ObjRef, twin: &Field, value: &[String], scripts: &mut dyn Scripts) -> Result<(), FormError> {
|
||||
/// Give `twin` the value `source` (a field and its options) holds: its `/V`, and a choice's `/I`
|
||||
/// mapped to the twin's own options, drawn in the twin's own widgets.
|
||||
fn share_value(
|
||||
doc: &mut Document,
|
||||
(source, source_options): (ObjRef, &[(String, String)]),
|
||||
twin: &Field,
|
||||
value: &[String],
|
||||
scripts: &mut dyn Scripts,
|
||||
) -> Result<(), FormError> {
|
||||
match twin.kind {
|
||||
FieldKind::CheckBox => {
|
||||
let state = twin.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into());
|
||||
@@ -153,18 +159,37 @@ fn share_value(doc: &mut Document, source: ObjRef, twin: &Field, value: &[String
|
||||
}
|
||||
FieldKind::Text | FieldKind::Combo | FieldKind::List => {
|
||||
let src = doc.get(source).as_dict().cloned().unwrap_or_default();
|
||||
// `/I` holds positions in the source's options: each goes to the twin's first unused option
|
||||
// with the same export value and text, its options perhaps in another order. One with no
|
||||
// match leaves the twin no `/I` (its `/V` picks), never part of one.
|
||||
let positions = match twin.kind {
|
||||
FieldKind::Combo | FieldKind::List => {
|
||||
listed_indices(doc, &src, source_options.len()).and_then(|picked| twin_positions(&picked, source_options, &twin.options))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
doc.update_dict(twin.obj, |d| {
|
||||
for key in [&b"V"[..], b"I"] {
|
||||
match src.get(key) {
|
||||
Some(v) => d.set(key.to_vec(), v.clone()),
|
||||
None => {
|
||||
d.remove(key);
|
||||
}
|
||||
match src.get(b"V") {
|
||||
Some(v) => d.set(b"V".to_vec(), v.clone()),
|
||||
None => {
|
||||
d.remove(b"V");
|
||||
}
|
||||
}
|
||||
match &positions {
|
||||
Some(p) => d.set(b"I".to_vec(), Object::Array(p.iter().map(|&i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect())),
|
||||
None => {
|
||||
d.remove(b"I");
|
||||
}
|
||||
}
|
||||
d.remove(b"RV");
|
||||
})?;
|
||||
redraw(doc, twin, value, scripts)
|
||||
// Drawn with the options that `/I` selects, not only the export values.
|
||||
let mut shown = twin.clone();
|
||||
shown.value = value.to_vec();
|
||||
if matches!(twin.kind, FieldKind::Combo | FieldKind::List) {
|
||||
shown.selected = selected_options(&twin.options, value, positions.as_deref());
|
||||
}
|
||||
redraw(doc, &shown, value, scripts)
|
||||
}
|
||||
FieldKind::PushButton | FieldKind::Signature => Ok(()),
|
||||
}
|
||||
@@ -303,24 +328,33 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
set_states(doc, f, Some(&state), Some(*i))
|
||||
}
|
||||
(FieldKind::CheckBox, v) => {
|
||||
let state = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into());
|
||||
let on = match v {
|
||||
FieldValue::Check(on) => *on,
|
||||
// The on-state name or a yes/no word also work (agents, FDF-style data).
|
||||
// The kids of one check box field can have different on states, and the field's
|
||||
// value is the on state of the kid that is on (ISO 32000-2 §12.7.5.2.3, Table 230).
|
||||
// "Checked" keeps the state that is on, else takes the first kid's.
|
||||
let first = f.widgets.iter().find_map(|w| w.on_state.clone()).unwrap_or_else(|| "Yes".into());
|
||||
let checked = || (0..f.widgets.len()).find(|&i| f.widget_on(i)).and_then(|i| f.widgets.get(i)?.on_state.clone()).unwrap_or(first.clone());
|
||||
let state = match v {
|
||||
FieldValue::Check(on) => on.then(checked),
|
||||
// An on-state name (or `/Opt` export value) turns on the kids that have it; a
|
||||
// yes/no word also works (agents, FDF-style data).
|
||||
FieldValue::Text(t) | FieldValue::Radio(Some(t)) => {
|
||||
let t = t.trim();
|
||||
if t == state || f.state_for(t).is_some() || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) {
|
||||
true
|
||||
if let Some(s) = f.state_for(t) {
|
||||
Some(s.to_owned())
|
||||
} else if t == first || ["yes", "true", "on", "1", "x", "checked"].contains(&t.to_lowercase().as_str()) {
|
||||
Some(checked())
|
||||
} else if t.is_empty() || ["no", "false", "off", "0", "unchecked"].contains(&t.to_lowercase().as_str()) {
|
||||
false
|
||||
None
|
||||
} else {
|
||||
return invalid(format!("{:?} is a check box: use true or false", f.name));
|
||||
}
|
||||
}
|
||||
FieldValue::Radio(None) => false,
|
||||
FieldValue::Choice(_) | FieldValue::Widget(_) => return invalid(format!("{:?} is a check box: use true or false", f.name)),
|
||||
FieldValue::Radio(None) => None,
|
||||
FieldValue::Choice(_) | FieldValue::ChoiceIndices(_) | FieldValue::Widget(_) => {
|
||||
return invalid(format!("{:?} is a check box: use true or false", f.name));
|
||||
}
|
||||
};
|
||||
set_states(doc, f, on.then_some(state.as_str()), None)
|
||||
set_states(doc, f, state.as_deref(), None)
|
||||
}
|
||||
(FieldKind::Radio, v) => {
|
||||
let choice = match v {
|
||||
@@ -343,37 +377,67 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
}
|
||||
set_states(doc, f, choice.as_deref(), None)
|
||||
}
|
||||
(FieldKind::Combo | FieldKind::List, FieldValue::Choice(_) | FieldValue::Text(_)) => {
|
||||
let vals: Vec<String> = match value {
|
||||
FieldValue::Choice(v) => v.clone(),
|
||||
FieldValue::Text(t) if t.is_empty() => Vec::new(),
|
||||
FieldValue::Text(t) => vec![t.clone()],
|
||||
other => return invalid(format!("{:?} can't take {other:?}", f.name)),
|
||||
(FieldKind::Combo | FieldKind::List, FieldValue::Choice(_) | FieldValue::Text(_) | FieldValue::ChoiceIndices(_)) => {
|
||||
let count = match value {
|
||||
FieldValue::Choice(v) => v.len(),
|
||||
FieldValue::ChoiceIndices(v) => v.len(),
|
||||
_ => 1,
|
||||
};
|
||||
if vals.len() > 1 && !(f.kind == FieldKind::List && f.has(flags::MULTI_SELECT)) {
|
||||
if count > 1 && !(f.kind == FieldKind::List && f.has(flags::MULTI_SELECT)) {
|
||||
return invalid(format!("{:?} takes a single value", f.name));
|
||||
}
|
||||
// Accept export values or display texts; free text only in editable combo boxes.
|
||||
// Each value as its export value and, when it is one of the options, that option's
|
||||
// position: two options can share an export value, and the position (`/I`) says
|
||||
// which one is picked (ISO 32000-2 Table 234).
|
||||
let mut exports = Vec::new();
|
||||
for v in &vals {
|
||||
match option_named(f, v).and_then(|i| f.options.get(i)) {
|
||||
Some((e, _)) => exports.push(e.clone()),
|
||||
None if f.kind == FieldKind::Combo && f.has(flags::EDIT) => exports.push(v.clone()),
|
||||
None if f.options.is_empty() => exports.push(v.clone()),
|
||||
None => {
|
||||
let opts: Vec<&str> = f.options.iter().map(|(_, d)| d.as_str()).collect();
|
||||
return invalid(format!("{:?} has no option {v:?} (options: {})", f.name, opts.join(", ")));
|
||||
let mut picked: Vec<usize> = Vec::new();
|
||||
// Each option once in both `/V` and `/I`: a reader that finds them differ (a repeat in one)
|
||||
// goes by the export values alone and may pick another option sharing one.
|
||||
let mut seen = vec![false; f.options.len()];
|
||||
match value {
|
||||
FieldValue::ChoiceIndices(positions) => {
|
||||
for &i in positions {
|
||||
let Some((e, _)) = f.options.get(i) else {
|
||||
return invalid(format!("{:?} has no option {} (it has {})", f.name, i.saturating_add(1), f.options.len()));
|
||||
};
|
||||
if first_pick(&mut seen, i) {
|
||||
exports.push(e.clone());
|
||||
picked.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let vals: Vec<String> = match value {
|
||||
FieldValue::Choice(v) => v.clone(),
|
||||
FieldValue::Text(t) if t.is_empty() => Vec::new(),
|
||||
FieldValue::Text(t) => vec![t.clone()],
|
||||
other => return invalid(format!("{:?} can't take {other:?}", f.name)),
|
||||
};
|
||||
// Accept export values or display texts; free text only in editable combo boxes.
|
||||
for v in &vals {
|
||||
match option_named(f, v) {
|
||||
Some(i) => {
|
||||
if first_pick(&mut seen, i) {
|
||||
exports.push(f.options.get(i).map(|(e, _)| e.clone()).unwrap_or_else(|| v.clone()));
|
||||
picked.push(i);
|
||||
}
|
||||
}
|
||||
None if f.kind == FieldKind::Combo && f.has(flags::EDIT) => exports.push(v.clone()),
|
||||
None if f.options.is_empty() => exports.push(v.clone()),
|
||||
None => {
|
||||
let opts: Vec<&str> = f.options.iter().map(|(_, d)| d.as_str()).collect();
|
||||
return invalid(format!("{:?} has no option {v:?} (options: {})", f.name, opts.join(", ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut indices: Vec<Object> =
|
||||
exports.iter().filter_map(|e| f.options.iter().position(|(x, _)| x == e)).map(|i| Object::Int(i as i64)).collect();
|
||||
// /I lists option indices in ascending order; /V keeps the caller's value order.
|
||||
// Every entry above is an integer, so this sorts by its numeric option index.
|
||||
indices.sort_unstable_by_key(Object::as_int);
|
||||
// /I lists option indices in ascending order, each once; /V keeps the caller's order.
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
let indices: Vec<Object> = picked.iter().map(|&i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect();
|
||||
// A list box scrolls (`/TI`) so the picked options are among the rows it draws, as
|
||||
// in other viewers: a pick below the last visible row would otherwise not show (#1524).
|
||||
let picked: Vec<usize> = indices.iter().filter_map(|i| i.as_int()).filter_map(|i| usize::try_from(i).ok()).collect();
|
||||
let top = list_scroll(f, &picked, f.options.len());
|
||||
// An empty value of its own keeps a parent field's /V from showing through.
|
||||
let shadow = exports.is_empty() && crate::author::ancestor_sets(doc, f.obj, b"V");
|
||||
@@ -398,7 +462,10 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr
|
||||
}
|
||||
})?;
|
||||
scroll_widgets(doc, f, &picked, f.options.len())?;
|
||||
redraw(doc, f, &exports, scripts)
|
||||
let mut shown = f.clone();
|
||||
shown.value = exports.clone();
|
||||
shown.selected = picked;
|
||||
redraw(doc, &shown, &exports, scripts)
|
||||
}
|
||||
(FieldKind::PushButton, _) => invalid(format!("{:?} is a button; it has no value", f.name)),
|
||||
(FieldKind::Signature, _) => invalid(format!("{:?} is a signature field; sign it with Fill & Sign or a digital ID", f.name)),
|
||||
@@ -774,7 +841,7 @@ pub fn reset(doc: &mut Document, names: Option<&[String]>) -> Result<usize, Form
|
||||
}
|
||||
let v = match f.kind {
|
||||
FieldKind::Text => FieldValue::Text(f.default.first().cloned().unwrap_or_default()),
|
||||
FieldKind::CheckBox => FieldValue::Check(!f.default.is_empty()),
|
||||
FieldKind::CheckBox => f.check_box_value(f.default.first().map(String::as_str)),
|
||||
FieldKind::Radio => FieldValue::Radio(f.default.first().cloned()),
|
||||
FieldKind::Combo | FieldKind::List => FieldValue::Choice(f.default.clone()),
|
||||
FieldKind::PushButton | FieldKind::Signature => continue,
|
||||
@@ -788,3 +855,22 @@ pub fn reset(doc: &mut Document, names: Option<&[String]>) -> Result<usize, Form
|
||||
recalculate(doc)?;
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Marks option `i` picked; false when it already was, or there is no such option.
|
||||
fn first_pick(seen: &mut [bool], i: usize) -> bool {
|
||||
match seen.get_mut(i) {
|
||||
Some(taken) if !*taken => {
|
||||
*taken = true;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The twin's positions for the source's picked positions `picked`, as
|
||||
/// [`crate::option_positions_in`] maps them, in ascending order, as `/I` lists them.
|
||||
fn twin_positions(picked: &[usize], source: &[(String, String)], twin: &[(String, String)]) -> Option<Vec<usize>> {
|
||||
let mut out = crate::option_positions_in(picked, source, twin)?;
|
||||
out.sort_unstable();
|
||||
Some(out)
|
||||
}
|
||||
@@ -1009,3 +1009,15 @@ pub fn clear_marks(doc: &mut Document, pages: Option<&[usize]>) -> Result<usize,
|
||||
}
|
||||
Ok(targets.len())
|
||||
}
|
||||
|
||||
/// The name to save a document under after [`apply`]: `_Redacted` before the extension, as
|
||||
/// Acrobat appends it ("contract.pdf" gives "contract_Redacted.pdf"). The `.pdf` extension is
|
||||
/// matched in any letter case. A name that already ends in `_Redacted` keeps it once.
|
||||
pub fn redacted_file_name(name: &str) -> String {
|
||||
let cut = name.len().saturating_sub(4);
|
||||
let stem = match (name.get(..cut), name.get(cut..)) {
|
||||
(Some(stem), Some(ext)) if ext.eq_ignore_ascii_case(".pdf") => stem,
|
||||
_ => name,
|
||||
};
|
||||
if stem.ends_with("_Redacted") { format!("{stem}.pdf") } else { format!("{stem}_Redacted.pdf") }
|
||||
}
|
||||
@@ -2319,6 +2319,17 @@ fn clearing_marks_leaves_the_annotation_list_as_it_was() {
|
||||
assert_eq!((doc.get(page), doc.get(list)), before, "the page points at its array, which lists the link alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_copies_are_named_with_redacted_before_the_extension() {
|
||||
assert_eq!(redacted_file_name("contract.pdf"), "contract_Redacted.pdf");
|
||||
assert_eq!(redacted_file_name("SCAN.PDF"), "SCAN_Redacted.pdf");
|
||||
assert_eq!(redacted_file_name("Report.Pdf"), "Report_Redacted.pdf");
|
||||
// A document without the extension (opened from bytes) gets it.
|
||||
assert_eq!(redacted_file_name("Untitled"), "Untitled_Redacted.pdf");
|
||||
// Redacting a redacted copy again does not add a second suffix.
|
||||
assert_eq!(redacted_file_name("contract_Redacted.pdf"), "contract_Redacted.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_content_fails_closed() {
|
||||
let mut doc = one_page(b"", "", vec![]);
|
||||
|
||||
@@ -25,6 +25,9 @@ log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
# Reads rendered pixel words as bytes; already in the tree through hayro.
|
||||
bytemuck = { version = "1" }
|
||||
# Resolves relative URI actions against the catalog's /URI /Base, by the rules the browser uses;
|
||||
# already in the tree (pdfcraft-engine checks document links with it).
|
||||
url = "2.5"
|
||||
# Tells combining marks (bidi class NSM: general categories Mn and Me) in extracted text; the
|
||||
# version pdfcraft-fonts already uses.
|
||||
unicode-bidi = "0.3"
|
||||
|
||||
@@ -72,6 +72,9 @@ pub struct DocInfo {
|
||||
pub annotations: Vec<Annotation>,
|
||||
pub fields: Vec<Field>,
|
||||
pub links: Vec<Link>,
|
||||
/// The catalog's `/URI /Base` (ISO 32000-2 Table 211), the base for relative URI actions, when
|
||||
/// it is a string of at most [`crate::MAX_URI_BASE_BYTES`].
|
||||
pub uri_base: Option<String>,
|
||||
pub layers: Vec<Layer>,
|
||||
/// Radio-button layer groups (`/OCProperties /D /RBGroups`): turning one layer of a group on
|
||||
/// turns the others off.
|
||||
|
||||
@@ -17,11 +17,13 @@ const MAX_REMOTE_DESTINATION_NAME_BYTES: usize = 1024;
|
||||
/// are not listed: real comments stay far below, many small ones sharing one long string do not.
|
||||
pub(super) const MAX_ANNOTATION_BYTES: usize = 64 << 20;
|
||||
|
||||
/// Web-address text the bookmark and link listings, and name, description and embedded-file key
|
||||
/// text the attachment listing, keep together. Many bookmarks, links or attachments can share one
|
||||
/// long string, which each would otherwise copy. Past it, a bookmark or link to a web address lists
|
||||
/// as a URI action without its address, an attachment under its generic name without a
|
||||
/// description, and an embedded file whose key does not fit is not listed.
|
||||
/// Web-address text and `/QuadPoints` geometry the bookmark and link listings, and name,
|
||||
/// description and embedded-file key text the attachment listing, keep together. Many bookmarks,
|
||||
/// links or attachments can share one long string or array, which each would otherwise copy. Past
|
||||
/// it, a bookmark or link to a web address lists as a URI action without its address (or a link
|
||||
/// keeps a relative address unresolved against the document's base), a link is active over its
|
||||
/// whole `/Rect`, an attachment is listed under its generic name without a description, and an
|
||||
/// embedded file whose key does not fit is not listed.
|
||||
pub(super) const MAX_LINK_ATTACHMENT_TEXT_BYTES: usize = 16 << 20;
|
||||
|
||||
/// A colour array as RGB, read as pdfcraft-annot's appearance builder reads it (`appearance::color`
|
||||
@@ -87,6 +89,9 @@ impl<'a> Inspector<'a> {
|
||||
|
||||
/// `text_budget` is what is left of [`MAX_LINK_ATTACHMENT_TEXT_BYTES`].
|
||||
pub(super) fn annotations(&self, info: &mut DocInfo, text_budget: &mut usize) {
|
||||
// Indirect `/QuadPoints` arrays whose quadrilaterals did not fit what was left of the budget:
|
||||
// the budget only shrinks, so they are not read again (review on #4474).
|
||||
let mut unfit_quads: HashSet<ObjectId> = HashSet::new();
|
||||
let mut pages: Vec<(ObjectId, usize)> = self.page_index.iter().map(|(&id, &page)| (id, page)).collect();
|
||||
pages.sort_unstable_by_key(|&(_, page)| page);
|
||||
// An annotation, or a whole `/Annots` array, that several entries or pages list is on the
|
||||
@@ -138,7 +143,7 @@ impl<'a> Inspector<'a> {
|
||||
info.attachments.push(self.attachment(fs, AttachmentSource::Annotation { page, index }, text_budget, fallback));
|
||||
}
|
||||
if subtype == "Link" {
|
||||
if let Some(link) = self.link(page, index, d, text_budget) {
|
||||
if let Some(link) = self.link(page, index, d, info.uri_base.as_deref(), text_budget, &mut unfit_quads) {
|
||||
if matches!(&link.target, LinkTarget::Other(s) if s == "JavaScript") {
|
||||
info.has_javascript = true;
|
||||
}
|
||||
@@ -238,16 +243,64 @@ impl<'a> Inspector<'a> {
|
||||
|
||||
/// The link annotation `d`, at position `index` of page `page`'s `/Annots`: where its `/Dest`
|
||||
/// goes, else what its action `/A` does ([`Self::action_target`]). `None` when it has no
|
||||
/// rectangle, or a destination or action that leads nowhere.
|
||||
fn link(&self, page: usize, index: usize, d: &Dictionary, text_budget: &mut usize) -> Option<Link> {
|
||||
/// rectangle, or a destination or action that leads nowhere. `base` is the catalog's
|
||||
/// `/URI /Base`, which a relative URI action is resolved against. `unfit_quads` holds the
|
||||
/// indirect `/QuadPoints` arrays already found too large for the budget.
|
||||
fn link(
|
||||
&self,
|
||||
page: usize,
|
||||
index: usize,
|
||||
d: &Dictionary,
|
||||
base: Option<&str>,
|
||||
text_budget: &mut usize,
|
||||
unfit_quads: &mut HashSet<ObjectId>,
|
||||
) -> Option<Link> {
|
||||
let rect = rect4(self.resolve(d.get(b"Rect").ok()?));
|
||||
let target = if let Ok(dest) = d.get(b"Dest") {
|
||||
let (page, view) = self.dest(dest, 0)?;
|
||||
LinkTarget::Page(page, view)
|
||||
} else {
|
||||
self.action_target(d.get(b"A").ok().and_then(|a| self.dict(a))?, text_budget)?
|
||||
match self.action_target(d.get(b"A").ok().and_then(|a| self.dict(a))?, text_budget)? {
|
||||
LinkTarget::Uri(uri) => match crate::resolve_uri(base, &uri) {
|
||||
// The raw address is spent already. What the base adds is spent too, or the
|
||||
// link keeps the raw address.
|
||||
Some(resolved) if resolved.len().saturating_sub(uri.len()) <= *text_budget => {
|
||||
*text_budget = text_budget.saturating_sub(resolved.len().saturating_sub(uri.len()));
|
||||
LinkTarget::Uri(resolved)
|
||||
}
|
||||
_ => LinkTarget::Uri(uri),
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
};
|
||||
Some(Link { page, index, rect, target })
|
||||
// Not read at all once no quadrilateral would fit what is left of the budget, or when this
|
||||
// shared array already did not fit: many links can share one long array, and reading it
|
||||
// again for each would cost its length every time (review on #4474).
|
||||
let shared = d.get(b"QuadPoints").ok().and_then(|o| o.as_reference().ok());
|
||||
let readable = *text_budget >= std::mem::size_of::<[f32; 8]>() && shared.is_none_or(|id| !unfit_quads.contains(&id));
|
||||
let quads = match d.get(b"QuadPoints").map(|o| self.resolve(o)) {
|
||||
// Read no further than one value past the cap: a longer array isn't used.
|
||||
Ok(Object::Array(q)) if readable && q.len() <= crate::MAX_LINK_QUADS.saturating_mul(8) => {
|
||||
#[cfg(test)]
|
||||
QUAD_ARRAYS_READ.with(|n| n.set(n.get() + 1));
|
||||
let values: Vec<Option<f32>> = q.iter().map(|o| self.resolve(o).as_float().ok()).collect();
|
||||
let quads = crate::link_quads(&values, rect);
|
||||
// Many links can share one long array, which each would otherwise copy. Past the
|
||||
// budget a link is active over its whole `/Rect`.
|
||||
let bytes = std::mem::size_of_val(quads.as_slice());
|
||||
if bytes <= *text_budget {
|
||||
*text_budget = text_budget.saturating_sub(bytes);
|
||||
quads
|
||||
} else {
|
||||
if let Some(id) = shared {
|
||||
unfit_quads.insert(id);
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Some(Link { page, index, rect, quads, target })
|
||||
}
|
||||
|
||||
/// What an action does when a link or a bookmark runs it. Only a go-to's `/D` is a place in
|
||||
@@ -643,3 +696,9 @@ fn rect4(o: &Object) -> [f32; 4] {
|
||||
_ => [0.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// `/QuadPoints` arrays whose values were read.
|
||||
pub(super) static QUAD_ARRAYS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
@@ -222,6 +222,10 @@ impl<'a> Inspector<'a> {
|
||||
Ok(notes) => info.warnings.extend(notes.into_iter().map(|note| format!("Page labels: {note}."))),
|
||||
Err(reason) => info.warnings.push(format!("Page labels were skipped: {reason}; using physical page numbers.")),
|
||||
}
|
||||
info.uri_base = catalog.get(b"URI").ok().and_then(|o| self.dict(o)).and_then(|d| match d.get(b"Base").map(|o| self.resolve(o)) {
|
||||
Ok(Object::String(bytes, _)) if bytes.len() <= crate::MAX_URI_BASE_BYTES => std::str::from_utf8(bytes).ok().map(str::to_owned),
|
||||
_ => None,
|
||||
});
|
||||
let mut text_budget = MAX_LINK_ATTACHMENT_TEXT_BYTES;
|
||||
if let Some(first) = catalog.get(b"Outlines").ok().and_then(|o| self.dict(o)).and_then(|d| d.get(b"First").ok()) {
|
||||
(info.outline, info.outline_more) = self.outline_window(first, &mut text_budget);
|
||||
|
||||
@@ -196,13 +196,39 @@ pub struct Link {
|
||||
/// Zero-based position in the page's raw `/Annots` array.
|
||||
pub index: usize,
|
||||
pub rect: [f32; 4],
|
||||
/// Where the link is active when that isn't the whole of `rect`: its `/QuadPoints`, 8 numbers
|
||||
/// each in user space (ISO 32000-2 Table 176). Empty when the link is active over `rect`
|
||||
/// ([`crate::link_quads`]).
|
||||
pub quads: Vec<[f32; 8]>,
|
||||
pub target: LinkTarget,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
/// Whether the user-space point `(x, y)` activates the link: inside one of its quadrilaterals,
|
||||
/// or inside its rectangle when it has none.
|
||||
pub fn contains(&self, x: f32, y: f32) -> bool {
|
||||
let [x0, y0, x1, y1] = self.rect;
|
||||
if self.quads.is_empty() {
|
||||
return x >= x0 && x <= x1 && y >= y0 && y <= y1;
|
||||
}
|
||||
// Every kept quadrilateral lies within `/Rect` give or take the slack `link_quads`
|
||||
// accepts, so a point outside that is in none of them: skip the scan (up to
|
||||
// `MAX_LINK_QUADS` per link, run per link on every pointer move).
|
||||
let s = crate::link_area::RECT_SLACK;
|
||||
if !(x >= x0 - s && x <= x1 + s && y >= y0 - s && y <= y1 + s) {
|
||||
return false;
|
||||
}
|
||||
self.quads.iter().any(|q| crate::quad_contains(q, x, y))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum LinkTarget {
|
||||
/// A destination in this document: the 0-based page and where on it the view goes.
|
||||
Page(usize, DestView),
|
||||
/// A URI action's address, resolved against the catalog's `/URI /Base` when it is a relative
|
||||
/// reference ([`crate::resolve_uri`]); not yet checked, as the opener must
|
||||
/// (`pdfcraft_engine::links::document_url`).
|
||||
Uri(String),
|
||||
/// A set-layer-visibility action (`SetOCGState`, ISO 32000-2 §12.6.4.13): each change in
|
||||
/// order, naming the layer by its optional content group. With `preserve_rb`, a layer turned
|
||||
|
||||
@@ -1141,6 +1141,152 @@ fn a_named_attachment_leaves_its_contents_unspent() {
|
||||
assert!(matches!(&info.links[0].target, LinkTarget::Uri(u) if *u == uri));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_hit_test_rejects_points_outside_the_rect_before_scanning_quads() {
|
||||
// A quadrilateral reaching past `/Rect` (hand-built: `link_quads` keeps none beyond the
|
||||
// slack) shows whether the bounds gate runs before the quadrilateral scan.
|
||||
let link = Link {
|
||||
page: 0,
|
||||
index: 0,
|
||||
rect: [0.0, 0.0, 10.0, 10.0],
|
||||
quads: vec![[0.0, 0.0, 50.0, 0.0, 50.0, 10.0, 0.0, 10.0]],
|
||||
target: LinkTarget::Other("URI".into()),
|
||||
};
|
||||
assert!(link.contains(5.0, 5.0), "inside the rect and the quadrilateral");
|
||||
assert!(link.contains(10.005, 5.0), "within the slack `link_quads` accepts");
|
||||
assert!(!link.contains(30.0, 5.0), "outside the rect: no quadrilateral is scanned");
|
||||
assert!(!link.contains(f32::NAN, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_whose_quads_have_no_area_is_active_over_its_rect() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let link = |values: &[f32]| Link {
|
||||
page: 0,
|
||||
index: 0,
|
||||
rect,
|
||||
quads: crate::link_quads(&values.iter().map(|v| Some(*v)).collect::<Vec<_>>(), rect),
|
||||
target: LinkTarget::Other("URI".into()),
|
||||
};
|
||||
let flat = [10.0, 20.0, 60.0, 20.0, 60.0, 20.0, 10.0, 20.0];
|
||||
assert!(link(&flat).contains(100.0, 25.0), "no usable quad: the whole /Rect");
|
||||
let good = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
let mixed: Vec<f32> = flat.iter().chain(good.iter()).copied().collect();
|
||||
assert!(link(&mixed).contains(30.0, 25.0), "inside the usable quad");
|
||||
assert!(!link(&mixed).contains(100.0, 25.0), "the usable quad still gates the /Rect");
|
||||
}
|
||||
|
||||
fn links_of(catalog_extra: &str, annots: &str) -> DocInfo {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R {catalog_extra} >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [{annots}] >> endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF"
|
||||
);
|
||||
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
|
||||
let page = PageInfo { width: 300.0, height: 300.0, crop: [0.0, 0.0, 300.0, 300.0], rotation: 0, label: String::new() };
|
||||
let mut info = DocInfo { pages: vec![page], ..Default::default() };
|
||||
Inspector::new(&doc).fill(&mut info);
|
||||
info
|
||||
}
|
||||
|
||||
fn uris(info: &DocInfo) -> Vec<String> {
|
||||
info.links.iter().map(|l| if let LinkTarget::Uri(u) = &l.target { u.clone() } else { format!("{:?}", l.target) }).collect()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.6.4.8, Table 211: a relative URI action is resolved against the catalog's
|
||||
/// `/URI /Base`; absolute addresses, and a base that isn't a web address, change nothing.
|
||||
#[test]
|
||||
fn relative_uri_actions_resolve_against_the_catalog_base() {
|
||||
let annots = "<< /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (page.html) >> >> \
|
||||
<< /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (javascript:alert(1)) >> >> \
|
||||
<< /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (https://example.org/abs) >> >>";
|
||||
let info = links_of("/URI << /Base (https://example.com/base/) >>", annots);
|
||||
assert_eq!(info.uri_base.as_deref(), Some("https://example.com/base/"));
|
||||
assert_eq!(uris(&info), ["https://example.com/base/page.html", "javascript:alert(1)", "https://example.org/abs"]);
|
||||
// An indirect URI dictionary is followed too.
|
||||
let pdf_indirect = links_of("/URI 4 0 R >> endobj\n4 0 obj << /Base (https://example.com/b/) >> endobj\n5 0 obj <<", annots);
|
||||
assert_eq!(uris(&pdf_indirect).first().map(String::as_str), Some("https://example.com/b/page.html"));
|
||||
// Without a base, or with one that isn't a web address, the address stays as written.
|
||||
assert_eq!(uris(&links_of("", annots)).first().map(String::as_str), Some("page.html"));
|
||||
for base in ["/URI << /Base (file:///C:/docs/) >>", "/URI << /Base /NotAString >>", "/URI 7", "/URI << /Base (javascript:x//) >>"] {
|
||||
assert_eq!(uris(&links_of(base, annots)).first().map(String::as_str), Some("page.html"), "{base}");
|
||||
}
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.5.6.5, Table 176: a link is active in its `/QuadPoints`, or over its
|
||||
/// `/Rect` when they are missing, malformed or reach outside it.
|
||||
#[test]
|
||||
fn links_are_active_in_their_quad_points() {
|
||||
let link = |quads: &str| format!("<< /Subtype /Link /Rect [10 10 200 30] {quads} /A << /S /URI /URI (https://example.org/) >> >>");
|
||||
let info = links_of("", &link("/QuadPoints [10 10 60 10 60 30 10 30]"));
|
||||
let l = &info.links[0];
|
||||
assert_eq!(l.quads, vec![[10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0]]);
|
||||
assert!(l.contains(30.0, 20.0), "the first word");
|
||||
assert!(!l.contains(150.0, 20.0), "inside /Rect but outside the quad");
|
||||
for fallback in [
|
||||
"",
|
||||
"/QuadPoints [10 10 60 10 60 30 10]",
|
||||
"/QuadPoints [10 10 60 10 60 30 10 (x)]",
|
||||
"/QuadPoints [10 10 260 10 260 30 10 30]",
|
||||
"/QuadPoints 5",
|
||||
] {
|
||||
let info = links_of("", &link(fallback));
|
||||
let l = &info.links[0];
|
||||
assert!(l.quads.is_empty(), "{fallback}");
|
||||
assert!(l.contains(150.0, 20.0) && !l.contains(250.0, 20.0), "{fallback}: active over /Rect");
|
||||
}
|
||||
let many = "10 10 60 10 60 30 10 30 ".repeat(crate::MAX_LINK_QUADS + 1);
|
||||
assert!(links_of("", &link(&format!("/QuadPoints [{many}]"))).links[0].quads.is_empty(), "too many quads");
|
||||
}
|
||||
|
||||
/// Links sharing one long `/QuadPoints` array, or a relative address resolved against a long
|
||||
/// `/URI /Base`, keep their copies only within `MAX_LINK_ATTACHMENT_TEXT_BYTES`, and every
|
||||
/// link is still listed.
|
||||
#[test]
|
||||
fn links_sharing_quad_points_or_a_long_base_keep_them_within_a_budget() {
|
||||
let page = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() };
|
||||
let fill = |catalog_extra: &str, links: &str, object5: &str| {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R {catalog_extra} >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{links}] >> endobj\n\
|
||||
5 0 obj {object5} endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF"
|
||||
);
|
||||
let doc = Document::load_mem(pdf.as_bytes()).expect("loads");
|
||||
let mut info = DocInfo { pages: vec![page.clone()], ..Default::default() };
|
||||
Inspector::new(&doc).fill(&mut info);
|
||||
info
|
||||
};
|
||||
|
||||
let count = MAX_LINK_ATTACHMENT_TEXT_BYTES / (crate::MAX_LINK_QUADS * std::mem::size_of::<[f32; 8]>()) + 20;
|
||||
let quads = format!("[{}]", "10 10 60 10 60 30 10 30 ".repeat(crate::MAX_LINK_QUADS));
|
||||
let links = "<< /Subtype /Link /Rect [0 0 100 100] /QuadPoints 5 0 R /A << /S /URI /URI (https://example.org/) >> >> ".repeat(count);
|
||||
super::annotations::QUAD_ARRAYS_READ.with(|n| n.set(0));
|
||||
let info = fill("", &links, &quads);
|
||||
assert_eq!(info.links.len(), count);
|
||||
let kept: usize = info.links.iter().map(|l| std::mem::size_of_val(l.quads.as_slice())).sum();
|
||||
assert!(kept > 0 && kept <= MAX_LINK_ATTACHMENT_TEXT_BYTES, "{kept} quad bytes kept");
|
||||
assert!(info.links.iter().any(|l| l.quads.is_empty()), "past the budget a link is active over its /Rect");
|
||||
// Review on #4474: the shared array is read once for each link it fits, and once more to find
|
||||
// that it no longer does; not again for every link after that.
|
||||
let fitted = info.links.iter().filter(|l| !l.quads.is_empty()).count();
|
||||
let read = super::annotations::QUAD_ARRAYS_READ.with(std::cell::Cell::get);
|
||||
assert_eq!(read, fitted + 1, "{read} reads for {fitted} links within the budget, of {count}");
|
||||
|
||||
let base = format!("https://example.com/{}/", "b".repeat(crate::MAX_URI_BASE_BYTES - 32));
|
||||
let count = MAX_LINK_ATTACHMENT_TEXT_BYTES / base.len() + 20;
|
||||
let links = "<< /Subtype /Link /Rect [0 0 1 1] /A 5 0 R >> ".repeat(count);
|
||||
let info = fill(&format!("/URI << /Base ({base}) >>"), &links, "<< /S /URI /URI (p.html) >>");
|
||||
assert_eq!(info.links.len(), count);
|
||||
let addresses = uris(&info);
|
||||
let kept: usize = addresses.iter().map(String::len).sum();
|
||||
assert!(kept <= MAX_LINK_ATTACHMENT_TEXT_BYTES, "{kept} address bytes kept");
|
||||
assert_eq!(addresses.first(), Some(&format!("{base}p.html")));
|
||||
assert!(addresses.iter().any(|u| u == "p.html"), "past the budget a link keeps its raw address");
|
||||
}
|
||||
|
||||
/// Embedded files whose name-tree keys share one long string keep it, as key and as name, only
|
||||
/// within `MAX_LINK_ATTACHMENT_TEXT_BYTES`.
|
||||
#[test]
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod inspect;
|
||||
mod link_area;
|
||||
mod pixels;
|
||||
mod raster;
|
||||
mod reading;
|
||||
@@ -22,6 +23,7 @@ pub use inspect::{
|
||||
OutlineItem, PageInfo, PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, attachment_data, check_pages, inspect,
|
||||
link_replies, pretty_date, thread_tops,
|
||||
};
|
||||
pub use link_area::{MAX_LINK_QUADS, MAX_URI_BASE_BYTES, link_quads, quad_contains, resolve_uri};
|
||||
pub use pixels::Pixels;
|
||||
pub use raster::{
|
||||
MAX_PIXELS, MAX_SIDE, PRINT_TAG, PageRenderer, RenderConfig, RenderPool, RenderRequest, RenderStats, RenderWarning, RenderedPage, RequestKind,
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Where a link annotation is active, and where its URI action goes.
|
||||
//!
|
||||
//! - ISO 32000-2 §12.5.6.5, Table 176: a link's `/QuadPoints` are "the region in which the link
|
||||
//! should be activated"; when they are absent, not understood, or any coordinate lies outside
|
||||
//! `/Rect`, the activation region is `/Rect`.
|
||||
//! - ISO 32000-2 §12.6.4.8, Table 211: the catalog's `/URI /Base` is "the base URI that shall be
|
||||
//! used in resolving relative URI references" in URI actions.
|
||||
|
||||
/// The most quadrilaterals a link's `/QuadPoints` may give before they are not used (the link is
|
||||
/// then active over its `/Rect`, as for an array that isn't understood).
|
||||
pub const MAX_LINK_QUADS: usize = 1024;
|
||||
|
||||
/// The longest `/URI /Base` that is used. A longer base would only produce an address the link
|
||||
/// check refuses as too long, so it is ignored.
|
||||
pub const MAX_URI_BASE_BYTES: usize = 8192;
|
||||
|
||||
/// How far (in points) a quadrilateral's corner may lie outside `/Rect` and still count as inside:
|
||||
/// rounding in the writer, not a different region.
|
||||
pub(crate) const RECT_SLACK: f32 = 0.01;
|
||||
|
||||
/// A link's quadrilaterals from its `/QuadPoints` values (`None` for an entry that isn't a
|
||||
/// number), or an empty list when the link is active over its whole `/Rect`: no values, a count
|
||||
/// that isn't a multiple of 8, more than [`MAX_LINK_QUADS`], a value that isn't a finite number,
|
||||
/// a corner outside `rect` (normalized, `[x0, y0, x1, y1]`), or no quadrilateral that encloses
|
||||
/// an area.
|
||||
///
|
||||
/// A quadrilateral no thicker than [`RECT_SLACK`] (its corners on one line, give or take
|
||||
/// rounding) is left out: it adds nothing to the region the others make, and kept alone it would
|
||||
/// leave the link active nowhere. When every quadrilateral is like that, the array is not one
|
||||
/// that can be used and the link is active over `/Rect`.
|
||||
pub fn link_quads(values: &[Option<f32>], rect: [f32; 4]) -> Vec<[f32; 8]> {
|
||||
if values.is_empty() || !values.len().is_multiple_of(8) || values.len() / 8 > MAX_LINK_QUADS {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut numbers = Vec::with_capacity(values.len());
|
||||
for v in values {
|
||||
match v {
|
||||
Some(n) if n.is_finite() => numbers.push(*n),
|
||||
_ => return Vec::new(),
|
||||
}
|
||||
}
|
||||
let [x0, y0, x1, y1] = rect;
|
||||
let inside = numbers
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.all(|[x, y]| *x >= x0 - RECT_SLACK && *x <= x1 + RECT_SLACK && *y >= y0 - RECT_SLACK && *y <= y1 + RECT_SLACK);
|
||||
if !inside {
|
||||
return Vec::new();
|
||||
}
|
||||
numbers.as_chunks::<8>().0.iter().filter(|q| encloses_area(q)).copied().collect()
|
||||
}
|
||||
|
||||
/// Whether the quadrilateral `q` (`x1 y1 … x4 y4`, finite) is thicker than [`RECT_SLACK`]: one of
|
||||
/// the four triangles its corners make (whose union [`quad_contains`] tests) is more than that
|
||||
/// high over its longest side. Worked in `f64`, where products of finite `f32` values neither
|
||||
/// overflow nor become NaN.
|
||||
fn encloses_area(q: &[f32; 8]) -> bool {
|
||||
let p = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]].map(|[x, y]| [f64::from(x), f64::from(y)]);
|
||||
let len = |u: [f64; 2], v: [f64; 2]| (v[0] - u[0]).hypot(v[1] - u[1]);
|
||||
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]].iter().any(|&[a, b, c]| match (p.get(a), p.get(b), p.get(c)) {
|
||||
(Some(&a), Some(&b), Some(&c)) => {
|
||||
// Twice the triangle's area is its longest side times its height over that side.
|
||||
let twice_area = ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).abs();
|
||||
let longest = len(a, b).max(len(b, c)).max(len(c, a));
|
||||
twice_area > f64::from(RECT_SLACK) * longest
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the point `(x, y)` lies in the quadrilateral `q` (`x1 y1 … x4 y4`), edges included.
|
||||
/// Writers disagree on the corners' order (the specification says counterclockwise, text-markup
|
||||
/// writers often go top-left, top-right, bottom-left, bottom-right), so the quadrilateral is taken
|
||||
/// as the area its four corners enclose: the union of the four triangles they make.
|
||||
pub fn quad_contains(q: &[f32; 8], x: f32, y: f32) -> bool {
|
||||
if !(x.is_finite() && y.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let p = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]];
|
||||
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]].iter().any(|&[a, b, c]| match (p.get(a), p.get(b), p.get(c)) {
|
||||
(Some(a), Some(b), Some(c)) => triangle_contains(*a, *b, *c, [x, y]),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Worked in `f64`, like [`encloses_area`]: in `f32` the cross products of far-apart finite
|
||||
/// corners overflow to infinity and their differences to NaN, which no sign test rejects.
|
||||
fn triangle_contains(a: [f32; 2], b: [f32; 2], c: [f32; 2], p: [f32; 2]) -> bool {
|
||||
let [a, b, c, p] = [a, b, c, p].map(|[x, y]| [f64::from(x), f64::from(y)]);
|
||||
let cross = |o: [f64; 2], u: [f64; 2], v: [f64; 2]| (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]);
|
||||
// A triangle with no area holds no point (it would otherwise hold its whole line).
|
||||
if cross(a, b, c) == 0.0 {
|
||||
return false;
|
||||
}
|
||||
let (d1, d2, d3) = (cross(a, b, p), cross(b, c, p), cross(c, a, p));
|
||||
let negative = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
|
||||
let positive = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
|
||||
!(negative && positive)
|
||||
}
|
||||
|
||||
/// Whether `s` begins with an RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"`),
|
||||
/// so it is an absolute URI rather than a relative reference.
|
||||
fn has_scheme(s: &str) -> bool {
|
||||
s.split_once(':').is_some_and(|(scheme, _)| {
|
||||
scheme.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
|
||||
})
|
||||
}
|
||||
|
||||
/// The address a URI action goes to when the document's catalog gives `base` (`/URI /Base`):
|
||||
/// a relative reference (`page.html`, `../a/`, `?q=1`, `//host/x`) resolved against it by
|
||||
/// RFC 3986 §5 (the WHATWG URL rules, which the browser applies too). `None` when the address is
|
||||
/// used as written: it already has a scheme (`https:`, `mailto:`, `javascript:`…), there is no
|
||||
/// usable base, or the result wouldn't be a web address.
|
||||
///
|
||||
/// Only a web (`http`, `https`) base is used, and the result must keep the base's scheme, so a
|
||||
/// base never turns a relative link into a `file:`, `javascript:` or other address. An address
|
||||
/// with control characters or whitespace other than a plain space is left as written, since the
|
||||
/// URL rules would drop them and read what is left (`java\nscript:`) differently. Either way the
|
||||
/// address still goes through the same check and confirmation as any other link.
|
||||
pub fn resolve_uri(base: Option<&str>, raw: &str) -> Option<String> {
|
||||
let reference = raw.trim();
|
||||
let base = base?.trim();
|
||||
if reference.is_empty() || base.len() > MAX_URI_BASE_BYTES || has_scheme(reference) {
|
||||
return None;
|
||||
}
|
||||
let hidden = |s: &str| s.chars().any(|c| c.is_control() || (c.is_whitespace() && c != ' '));
|
||||
// The base must name its host as written (`https://host/…`): the URL rules would also accept
|
||||
// `https:///host/` or `https:host/`, which no link check reads as a web address.
|
||||
let names_host = base.split_once("://").is_some_and(|(_, rest)| !rest.starts_with(['/', '\\']));
|
||||
if hidden(reference) || hidden(base) || !names_host {
|
||||
return None;
|
||||
}
|
||||
let base = url::Url::parse(base).ok()?;
|
||||
if !matches!(base.scheme(), "http" | "https") || base.host().is_none() {
|
||||
return None;
|
||||
}
|
||||
let resolved = base.join(reference).ok()?;
|
||||
(resolved.scheme() == base.scheme() && resolved.host().is_some()).then(|| resolved.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const BASE: &str = "https://example.com/base/";
|
||||
|
||||
#[test]
|
||||
fn relative_references_resolve_against_the_base() {
|
||||
let r = |raw: &str| resolve_uri(Some(BASE), raw);
|
||||
assert_eq!(r("page.html").as_deref(), Some("https://example.com/base/page.html"));
|
||||
assert_eq!(r(" page.html ").as_deref(), Some("https://example.com/base/page.html"), "trimmed like any link");
|
||||
assert_eq!(r("../up.html").as_deref(), Some("https://example.com/up.html"));
|
||||
assert_eq!(r("/root.html").as_deref(), Some("https://example.com/root.html"));
|
||||
assert_eq!(r("?q=1").as_deref(), Some("https://example.com/base/?q=1"));
|
||||
assert_eq!(r("#part").as_deref(), Some("https://example.com/base/#part"));
|
||||
assert_eq!(r("a/b:c").as_deref(), Some("https://example.com/base/a/b:c"), "a colon after a slash is no scheme");
|
||||
// A network-path reference names its own host; the confirmation shows that host.
|
||||
assert_eq!(r("//other.example/x").as_deref(), Some("https://other.example/x"));
|
||||
assert_eq!(resolve_uri(Some("http://example.com/dir/file.pdf"), "next.pdf").as_deref(), Some("http://example.com/dir/next.pdf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_addresses_and_missing_bases_are_used_as_written() {
|
||||
for raw in ["https://example.org/x", "HTTP://example.org", "mailto:a@example.org", "javascript:alert(1)", "file:///etc/passwd", "C:\\x.pdf"] {
|
||||
assert_eq!(resolve_uri(Some(BASE), raw), None, "{raw}");
|
||||
}
|
||||
assert_eq!(resolve_uri(None, "page.html"), None);
|
||||
assert_eq!(resolve_uri(Some(BASE), ""), None);
|
||||
assert_eq!(resolve_uri(Some(BASE), " "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_base_that_is_not_a_web_address_is_not_used() {
|
||||
for base in [
|
||||
"file:///C:/docs/",
|
||||
"javascript:alert(1)//",
|
||||
"data:text/html,x/",
|
||||
"mailto:a@example.org",
|
||||
"smb://server/share/",
|
||||
"relative/base/",
|
||||
"",
|
||||
"https://",
|
||||
"https:///nohost/",
|
||||
"https:nohost/",
|
||||
"https:\\\\nohost/",
|
||||
"https://exa\nmple.com/",
|
||||
] {
|
||||
assert_eq!(resolve_uri(Some(base), "page.html"), None, "{base:?}");
|
||||
}
|
||||
let long = format!("https://example.com/{}/", "a".repeat(MAX_URI_BASE_BYTES));
|
||||
assert_eq!(resolve_uri(Some(&long), "page.html"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_characters_never_make_a_scheme() {
|
||||
// The URL rules drop tabs and newlines, which would read these as `javascript:`.
|
||||
for raw in ["java\nscript:alert(1)", "java\tscript:alert(1)", "\u{0}javascript:alert(1)", "page\u{2028}.html"] {
|
||||
assert_eq!(resolve_uri(Some(BASE), raw), None, "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quads_inside_the_rect_are_used() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let q = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0].map(Some);
|
||||
assert_eq!(link_quads(&q, rect), vec![[10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0]]);
|
||||
let two: Vec<Option<f32>> = q.iter().chain(q.iter()).copied().collect();
|
||||
assert_eq!(link_quads(&two, rect).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quads_that_are_not_understood_fall_back_to_the_rect() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let good = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
assert!(link_quads(&[], rect).is_empty());
|
||||
assert!(link_quads(&good[..7].iter().copied().map(Some).collect::<Vec<_>>(), rect).is_empty(), "not a multiple of 8");
|
||||
let mut odd: Vec<Option<f32>> = good.map(Some).to_vec();
|
||||
odd.push(Some(1.0));
|
||||
assert!(link_quads(&odd, rect).is_empty());
|
||||
let mut not_number = good.map(Some);
|
||||
not_number[3] = None;
|
||||
assert!(link_quads(¬_number, rect).is_empty());
|
||||
let mut nan = good.map(Some);
|
||||
nan[0] = Some(f32::NAN);
|
||||
assert!(link_quads(&nan, rect).is_empty());
|
||||
// A /Rect too large for f32 would hold an infinite corner.
|
||||
let mut infinite = good.map(Some);
|
||||
infinite[2] = Some(f32::INFINITY);
|
||||
assert!(link_quads(&infinite, [f32::NEG_INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY]).is_empty());
|
||||
let mut outside = good.map(Some);
|
||||
outside[2] = Some(250.0);
|
||||
assert!(link_quads(&outside, rect).is_empty(), "a corner outside /Rect");
|
||||
let mut below = good.map(Some);
|
||||
below[1] = Some(9.0);
|
||||
assert!(link_quads(&below, rect).is_empty(), "a corner below /Rect");
|
||||
let too_many: Vec<Option<f32>> = std::iter::repeat_n(good.map(Some), MAX_LINK_QUADS + 1).flatten().collect();
|
||||
assert!(link_quads(&too_many, rect).is_empty());
|
||||
let most: Vec<Option<f32>> = std::iter::repeat_n(good.map(Some), MAX_LINK_QUADS).flatten().collect();
|
||||
assert_eq!(link_quads(&most, rect).len(), MAX_LINK_QUADS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quads_with_no_area_are_left_out() {
|
||||
let rect = [10.0, 10.0, 200.0, 30.0];
|
||||
let good = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
// Corners on one line, all at one point, and a sliver thinner than the slack.
|
||||
let line = [10.0, 20.0, 60.0, 20.0, 60.0, 20.0, 10.0, 20.0];
|
||||
let point = [30.0, 20.0, 30.0, 20.0, 30.0, 20.0, 30.0, 20.0];
|
||||
let sliver = [10.0, 20.0, 60.0, 20.0, 60.0, 20.005, 10.0, 20.005];
|
||||
for flat in [line, point, sliver] {
|
||||
assert!(link_quads(&flat.map(Some), rect).is_empty(), "{flat:?} alone: active over /Rect");
|
||||
let mixed: Vec<Option<f32>> = flat.iter().chain(good.iter()).map(|v| Some(*v)).collect();
|
||||
assert_eq!(link_quads(&mixed, rect), vec![good], "{flat:?} beside a usable quad");
|
||||
}
|
||||
// Thicker than the slack is a region, however thin.
|
||||
let thin = [10.0, 20.0, 60.0, 20.0, 60.0, 20.05, 10.0, 20.05];
|
||||
assert_eq!(link_quads(&thin.map(Some), rect), vec![thin]);
|
||||
// A triangle (two corners shared) still encloses an area.
|
||||
let triangle = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 60.0, 30.0];
|
||||
assert_eq!(link_quads(&triangle.map(Some), rect), vec![triangle]);
|
||||
// The largest finite values neither overflow nor turn to NaN.
|
||||
let all = [f32::MIN, f32::MIN, f32::MAX, f32::MAX];
|
||||
let huge = [f32::MIN, f32::MIN, f32::MAX, f32::MIN, f32::MAX, f32::MAX, f32::MIN, f32::MAX];
|
||||
assert_eq!(link_quads(&huge.map(Some), all), vec![huge]);
|
||||
let huge_line = [f32::MIN, f32::MIN, f32::MAX, f32::MAX, f32::MAX, f32::MAX, f32::MIN, f32::MIN];
|
||||
assert!(link_quads(&huge_line.map(Some), all).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quad_holds_its_area_in_any_corner_order() {
|
||||
// Counterclockwise from the bottom left, as the specification writes them.
|
||||
let ccw = [10.0, 10.0, 60.0, 10.0, 60.0, 30.0, 10.0, 30.0];
|
||||
// Top-left, top-right, bottom-left, bottom-right, as text-markup writers often do.
|
||||
let z = [10.0, 30.0, 60.0, 30.0, 10.0, 10.0, 60.0, 10.0];
|
||||
for q in [ccw, z] {
|
||||
assert!(quad_contains(&q, 30.0, 20.0));
|
||||
assert!(quad_contains(&q, 10.0, 10.0), "corners count");
|
||||
assert!(quad_contains(&q, 60.0, 20.0), "edges count");
|
||||
assert!(!quad_contains(&q, 100.0, 20.0), "right of the quad");
|
||||
assert!(!quad_contains(&q, 30.0, 31.0), "above the quad");
|
||||
assert!(!quad_contains(&q, 9.0, 20.0), "left of the quad");
|
||||
assert!(!quad_contains(&q, 30.0, 9.0), "below the quad");
|
||||
}
|
||||
// A tilted quad: the corner of its bounding box is outside it.
|
||||
let diamond = [50.0, 0.0, 100.0, 50.0, 50.0, 100.0, 0.0, 50.0];
|
||||
assert!(quad_contains(&diamond, 50.0, 50.0));
|
||||
assert!(!quad_contains(&diamond, 5.0, 5.0));
|
||||
// A quad with no area holds nothing.
|
||||
let flat = [0.0, 0.0, 10.0, 0.0, 20.0, 0.0, 30.0, 0.0];
|
||||
assert!(!quad_contains(&flat, 5.0, 0.0));
|
||||
assert!(!quad_contains(&ccw, f32::NAN, 20.0), "a point that isn't a number is nowhere");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quad_with_extreme_corners_holds_only_its_area() {
|
||||
// In f32 the cross products overflow (inf, and inf - inf = NaN), which passed every sign
|
||||
// test and put (1.5e20, 1.5e20), outside the triangle, inside it.
|
||||
let q = [0.0, 0.0, 2e20, 0.0, 0.0, 2e20, 0.0, 0.0];
|
||||
assert_eq!(link_quads(&q.map(Some), [0.0, 0.0, 3e20, 3e20]), vec![q], "kept by the area check");
|
||||
assert!(!quad_contains(&q, 1.5e20, 1.5e20), "beyond the long edge");
|
||||
assert!(!quad_contains(&q, 3e20, 1.0), "right of the triangle");
|
||||
assert!(quad_contains(&q, 0.5e20, 0.5e20));
|
||||
assert!(quad_contains(&q, 1.0, 1.0));
|
||||
let max = [0.0, 0.0, f32::MAX, 0.0, 0.0, f32::MAX, 0.0, 0.0];
|
||||
assert!(!quad_contains(&max, f32::MAX, f32::MAX));
|
||||
assert!(quad_contains(&max, 1.0, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,8 @@ impl PageText {
|
||||
/// Case-insensitive search. Returns glyph ranges of every match (words may span line breaks,
|
||||
/// which count as a single space, or as nothing where the line runs on between two Chinese or
|
||||
/// Japanese characters or ends in a soft hyphen: there a query with a space across the break
|
||||
/// doesn't match, and one without does).
|
||||
/// doesn't match, and one without does; a ligature matches its letters, and a word divided by a
|
||||
/// hyphen at a line end matches whole as well as with the hyphen).
|
||||
pub fn find(&self, needle: &str) -> Vec<std::ops::Range<usize>> {
|
||||
self.find_opts(needle, false, false)
|
||||
}
|
||||
|
||||
@@ -1,33 +1,133 @@
|
||||
//! Literal search in normalized page text, retaining the original glyph owners.
|
||||
//!
|
||||
//! Words and lines are separated by one space, except where a line of Chinese or Japanese runs on
|
||||
//! to the next: a break between two such characters is no word break, so it reads as nothing and
|
||||
//! "検知機構" is found when the line ends after "検知".
|
||||
//! The page text is read as characters, each owned by the glyph it came from. Words and lines are
|
||||
//! separated by one space, except where a line of Chinese or Japanese runs on to the next: a break
|
||||
//! between two such characters is no word break, so it reads as nothing and "検知機構" is found
|
||||
//! when the line ends after "検知". A Latin compatibility ligature (U+FB00–U+FB06) reads as its
|
||||
//! letters in the page and in the query, so "office" finds "o\u{FB03}ce". A word divided by a
|
||||
//! hyphen at the end of a line is also found whole: where a line ends in a hyphen between two
|
||||
//! letters, the text is searched a second time without the hyphen and the line break ("example"
|
||||
//! finds "exam-" + "ple") and a third time with the hyphen but without the break ("exam-ple"). A
|
||||
//! hit in any reading counts; where hits from different readings overlap, the one that starts
|
||||
//! first is kept (the longer on a tie). A soft hyphen needs no second reading: it draws nothing,
|
||||
//! and a line that ends in one always runs on.
|
||||
use super::device::ligature_letters;
|
||||
use super::{PageText, fold_case};
|
||||
use std::ops::Range;
|
||||
|
||||
/// How a line ending in a hyphen between two letters is read.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Hyphen {
|
||||
/// As written: the hyphen, then a line break (a space).
|
||||
Written,
|
||||
/// One word: neither the hyphen nor the break.
|
||||
Joined,
|
||||
/// A hyphenated compound: the hyphen, but no break.
|
||||
Kept,
|
||||
}
|
||||
|
||||
/// A visible hyphen that can divide a word at a line end: HYPHEN-MINUS and HYPHEN. A SOFT HYPHEN
|
||||
/// (ISO 32000-2 §14.8.2.3) is invisible instead: find skips it, and a line that ends in one runs on.
|
||||
fn is_hyphen(c: char) -> bool {
|
||||
matches!(c, '-' | '\u{2010}')
|
||||
}
|
||||
|
||||
/// Whether a line break separates glyph `i` from the glyph before it.
|
||||
fn breaks_before(page: &PageText, i: usize) -> bool {
|
||||
i.checked_sub(1).and_then(|previous| page.line_of.get(previous)).zip(page.line_of.get(i)).is_some_and(|(a, b)| a != b)
|
||||
}
|
||||
|
||||
pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: bool, limit: usize) -> Vec<Range<usize>> {
|
||||
if limit == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let fold = |s: &str| if sensitive { s.to_owned() } else { fold_case(s) };
|
||||
let fold = |s: &str| if sensitive { ligature_letters(s.to_owned()) } else { fold_case(&ligature_letters(s.to_owned())) };
|
||||
let query: String = fold(query).chars().filter(|&c| !is_invisible(c)).collect();
|
||||
let needle: Vec<char> = query.split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();
|
||||
if needle.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let texts: Vec<String> = page.glyphs.iter().map(|g| fold(&g.text)).collect();
|
||||
let divided: Vec<bool> = (0..texts.len()).map(|i| divides(page, &texts, i)).collect();
|
||||
let readings: &[Hyphen] = if divided.contains(&true) { &[Hyphen::Written, Hyphen::Joined, Hyphen::Kept] } else { &[Hyphen::Written] };
|
||||
// KMP reuses a matched prefix instead of comparing a long query again at every position.
|
||||
// The table is bounded by the page's already materialized character count.
|
||||
let mut prefix = vec![0; needle.len()];
|
||||
let mut matched = 0;
|
||||
for (i, &c) in needle.iter().enumerate().skip(1) {
|
||||
matched = advance(&needle, &prefix, matched, c);
|
||||
if let Some(slot) = prefix.get_mut(i) {
|
||||
*slot = matched;
|
||||
}
|
||||
}
|
||||
let mut hits: Vec<(Range<usize>, usize)> = Vec::new();
|
||||
for (r, &reading) in readings.iter().enumerate() {
|
||||
let (chars, zero_width_space) = characters(page, &texts, ÷d, reading);
|
||||
let found = search(&chars, &zero_width_space, &needle, &prefix, whole_words, limit);
|
||||
hits.extend(found.into_iter().map(|hit| (hit, r)));
|
||||
}
|
||||
if readings.len() == 1 {
|
||||
return hits.into_iter().map(|(hit, _)| hit).collect();
|
||||
}
|
||||
// Each reading's hits are in order and apart in its characters, though two can share a glyph
|
||||
// ("f" twice in an "ffi" glyph); they are all kept. Across readings, the earliest start wins
|
||||
// (the longer on a tie): a hit is left out where it overlaps one kept from another reading.
|
||||
// The sort is stable, so the earlier reading wins an exact tie.
|
||||
hits.sort_by(|a, b| a.0.start.cmp(&b.0.start).then(b.0.end.cmp(&a.0.end)));
|
||||
// The furthest end of the hits kept from each reading. Hits come in order of start, so one
|
||||
// overlaps an earlier kept hit exactly when it starts before that hit's end.
|
||||
let mut ends = [0usize; 3];
|
||||
let mut kept: Vec<Range<usize>> = Vec::new();
|
||||
for (hit, r) in hits {
|
||||
if ends.iter().enumerate().all(|(other, &end)| other == r || hit.start >= end) {
|
||||
if let Some(end) = ends.get_mut(r) {
|
||||
*end = (*end).max(hit.end);
|
||||
}
|
||||
kept.push(hit);
|
||||
if kept.len() == limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// Whether glyph `i` ends its line with a hyphen that follows a letter of its word, and the next
|
||||
/// line starts with a letter. `texts` are the glyphs' folded texts; the invisible characters find
|
||||
/// skips are passed over on both sides.
|
||||
fn divides(page: &PageText, texts: &[String], i: usize) -> bool {
|
||||
let Some(text) = texts.get(i) else { return false };
|
||||
let mut back = text.chars().rev().filter(|&c| !is_invisible(c));
|
||||
if !back.next().is_some_and(is_hyphen) {
|
||||
return false;
|
||||
}
|
||||
let before = match back.next() {
|
||||
Some(c) => Some(c),
|
||||
// A hyphen glyph of its own: the letter is the end of the glyph before, on its line with no word gap.
|
||||
None if !page.space_before.get(i).copied().unwrap_or(false) && !breaks_before(page, i) => {
|
||||
i.checked_sub(1).and_then(|p| texts.get(p)).and_then(|t| t.chars().rev().find(|&c| !is_invisible(c)))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let Some(next) = i.checked_add(1) else { return false };
|
||||
before.is_some_and(char::is_alphabetic)
|
||||
&& breaks_before(page, next)
|
||||
&& texts.get(next).and_then(|t| t.chars().find(|&c| !is_invisible(c))).is_some_and(char::is_alphabetic)
|
||||
}
|
||||
|
||||
/// The page's characters in one `reading`, each with the glyph it came from, and whether a
|
||||
/// skipped ZERO WIDTH SPACE came right before each one: it draws nothing, but it is a word
|
||||
/// boundary (UAX #29 breaks on both sides of it), which Thai and Khmer write between words with
|
||||
/// no visible gap, so whole-word search still sees two words there.
|
||||
fn characters(page: &PageText, texts: &[String], divided: &[bool], reading: Hyphen) -> (Vec<(char, usize)>, Vec<bool>) {
|
||||
let mut chars: Vec<(char, usize)> = Vec::new();
|
||||
// Whether a skipped ZERO WIDTH SPACE came right before each character: it draws nothing, but
|
||||
// it is a word boundary (UAX #29 breaks on both sides of it), which Thai and Khmer write between words
|
||||
// with no visible gap, so whole-word search still sees two words there.
|
||||
let mut zero_width_space: Vec<bool> = Vec::new();
|
||||
let mut pending_zero_width_space = false;
|
||||
// The last character pushed other than a variation selector, kept as characters are pushed so
|
||||
// a long run of selectors costs no rescan.
|
||||
let mut last_base: Option<char> = None;
|
||||
for (i, glyph) in page.glyphs.iter().enumerate() {
|
||||
let text = fold(&glyph.text);
|
||||
let line_break = i.checked_sub(1).and_then(|previous| page.line_of.get(previous)).zip(page.line_of.get(i)).is_some_and(|(a, b)| a != b);
|
||||
for (i, text) in texts.iter().enumerate() {
|
||||
let line_break = breaks_before(page, i);
|
||||
// A soft hyphen marks where a word may be divided at a line end (ISO 32000-2 §14.8.2.3), so
|
||||
// a line that ends in one runs on to the next with no word break between them.
|
||||
// Other invisible characters after the soft hyphen don't hide it.
|
||||
@@ -36,18 +136,29 @@ pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: b
|
||||
// sides of the break are the visible ones: invisible characters are skipped below, and a
|
||||
// variation selector after the last one only picks its glyph.
|
||||
let joined = line_break && last_base.is_some_and(unspaced) && first_visible(page, i).is_some_and(unspaced) && wraps(page, i);
|
||||
let gap = page.space_before.get(i).copied().unwrap_or(false) || (line_break && !(joined || soft_break));
|
||||
// And, in the readings that join it, a line that ends in a visible hyphen between letters.
|
||||
let after_divide = reading != Hyphen::Written && i.checked_sub(1).and_then(|p| divided.get(p)).copied().unwrap_or(false);
|
||||
let gap = page.space_before.get(i).copied().unwrap_or(false) || (line_break && !(joined || soft_break || after_divide));
|
||||
if i > 0 && gap && chars.last().is_some_and(|c| c.0 != ' ') {
|
||||
chars.push((' ', i));
|
||||
last_base = Some(' ');
|
||||
zero_width_space.push(false);
|
||||
pending_zero_width_space = false;
|
||||
}
|
||||
for c in text.chars() {
|
||||
// The divided glyph's hyphen is its last visible character, left out of the joined reading.
|
||||
let dropped = if reading == Hyphen::Joined && divided.get(i).copied().unwrap_or(false) {
|
||||
text.char_indices().rev().find(|&(_, c)| !is_invisible(c)).map(|(at, _)| at)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (at, c) in text.char_indices() {
|
||||
if is_invisible(c) {
|
||||
pending_zero_width_space |= c == '\u{200B}';
|
||||
continue;
|
||||
}
|
||||
if Some(at) == dropped {
|
||||
continue;
|
||||
}
|
||||
let c = if c.is_whitespace() { ' ' } else { c };
|
||||
if c != ' ' || chars.last().is_none_or(|last| last.0 != ' ') {
|
||||
chars.push((c, i));
|
||||
@@ -59,35 +170,38 @@ pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: b
|
||||
}
|
||||
}
|
||||
}
|
||||
(chars, zero_width_space)
|
||||
}
|
||||
|
||||
/// Non-overlapping hits of `needle` (with its KMP `prefix` table) in `chars`, as glyph ranges.
|
||||
/// `zero_width_space` says which characters come right after a skipped zero width space.
|
||||
fn search(
|
||||
chars: &[(char, usize)],
|
||||
zero_width_space: &[bool],
|
||||
needle: &[char],
|
||||
prefix: &[usize],
|
||||
whole_words: bool,
|
||||
limit: usize,
|
||||
) -> Vec<Range<usize>> {
|
||||
if needle.len() > chars.len() {
|
||||
return Vec::new();
|
||||
}
|
||||
// KMP reuses a matched prefix instead of comparing a long query again at every position.
|
||||
// The table is bounded by the page's already materialized character count.
|
||||
let mut prefix = vec![0; needle.len()];
|
||||
let mut matched = 0;
|
||||
for (i, &c) in needle.iter().enumerate().skip(1) {
|
||||
matched = advance(&needle, &prefix, matched, c);
|
||||
if let Some(slot) = prefix.get_mut(i) {
|
||||
*slot = matched;
|
||||
}
|
||||
}
|
||||
matched = 0;
|
||||
// A neighbour bounds a word only in a script that puts spaces between words. Han, kana, Thai
|
||||
// and the like run their words together, so a character of theirs next to the match is no
|
||||
// reason to reject it: Acrobat finds 台北 inside 台北市 with Whole words only on. Digits still
|
||||
// bound, in any script: ๑ is not a whole word inside the number ๑๒.
|
||||
let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|c| c.0.is_alphanumeric() && (c.0.is_numeric() || !unspaced_script(c.0)));
|
||||
// A skipped zero width space before the first character or after the last is a boundary.
|
||||
let after_break = |i: usize| zero_width_space.get(i).copied().unwrap_or(false);
|
||||
let mut hits = Vec::new();
|
||||
for (i, &(c, owner)) in chars.iter().enumerate() {
|
||||
matched = advance(&needle, &prefix, matched, c);
|
||||
matched = advance(needle, prefix, matched, c);
|
||||
if matched != needle.len() {
|
||||
continue;
|
||||
}
|
||||
let end = i.saturating_add(1);
|
||||
let start = end.saturating_sub(needle.len());
|
||||
// A skipped zero width space before the first character or after the last is a boundary.
|
||||
let after_break = |i: usize| zero_width_space.get(i).copied().unwrap_or(false);
|
||||
let bounded = !whole_words || ((after_break(start) || !word(start.checked_sub(1))) && (after_break(end) || !word(Some(end))));
|
||||
if bounded {
|
||||
if let Some((_, first)) = chars.get(start)
|
||||
|
||||
@@ -88,68 +88,172 @@ const UNSPACED_BLOCK_SAMPLES: &[(char, bool, &str)] = &[
|
||||
('\u{323AF}', true, "CJK Unified Ideographs Extension H (31350..323AF), last"),
|
||||
];
|
||||
|
||||
// The original straightforward search is an independent oracle for valid page metadata.
|
||||
// The original straightforward search is an independent oracle for valid page metadata, extended
|
||||
// with ligature letters and the three readings of a line-end hyphen between letters: as written,
|
||||
// joined (no hyphen, no break) and kept (hyphen, no break).
|
||||
fn reference(page: &PageText, query: &str, sensitive: bool, whole: bool, limit: usize) -> Vec<Range<usize>> {
|
||||
let fold = |s: &str| if sensitive { s.to_owned() } else { fold_case(s) };
|
||||
let letters = |s: &str| {
|
||||
s.replace('\u{FB00}', "ff")
|
||||
.replace('\u{FB01}', "fi")
|
||||
.replace('\u{FB02}', "fl")
|
||||
.replace('\u{FB03}', "ffi")
|
||||
.replace('\u{FB04}', "ffl")
|
||||
.replace(['\u{FB05}', '\u{FB06}'], "st")
|
||||
};
|
||||
let fold = |s: &str| if sensitive { letters(s) } else { fold_case(&letters(s)) };
|
||||
// Soft hyphens and zero width characters draw nothing and are skipped on both sides.
|
||||
let visible =
|
||||
|s: String| s.chars().filter(|c| !matches!(c, '\u{AD}' | '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}')).collect::<String>();
|
||||
let invisible = |c: char| matches!(c, '\u{AD}' | '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}');
|
||||
let visible = |s: String| s.chars().filter(|&c| !invisible(c)).collect::<String>();
|
||||
let needle: Vec<char> = visible(fold(query)).split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();
|
||||
if needle.is_empty() || limit == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// Each character, its glyph, and whether a skipped zero width space came right before it.
|
||||
let mut chars: Vec<(char, usize, bool)> = Vec::new();
|
||||
let mut after_zwsp = false;
|
||||
for (i, glyph) in page.glyphs.iter().enumerate() {
|
||||
// A line that ends in a soft hyphen, past any empty or other invisible glyphs and
|
||||
// characters after it on that line, runs on to the next.
|
||||
let ends_in_soft_hyphen = |end: usize| {
|
||||
(0..=end)
|
||||
.rev()
|
||||
.take_while(|&k| page.line_of[k] == page.line_of[end])
|
||||
.flat_map(|k| page.glyphs[k].text.chars().rev())
|
||||
.find(|&c| c == '\u{AD}' || !visible(c.to_string()).is_empty())
|
||||
== Some('\u{AD}')
|
||||
};
|
||||
let line_break = i > 0 && page.line_of[i] != page.line_of[i - 1] && !ends_in_soft_hyphen(i - 1);
|
||||
if i > 0 && (page.space_before[i] || line_break) && chars.last().is_some_and(|&(c, ..)| c != ' ') {
|
||||
chars.push((' ', i, false));
|
||||
after_zwsp = false;
|
||||
}
|
||||
for c in fold(&glyph.text).chars() {
|
||||
after_zwsp |= c == '\u{200B}';
|
||||
if visible(c.to_string()).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let c = if c.is_whitespace() { ' ' } else { c };
|
||||
if c != ' ' || chars.last().is_none_or(|&(last, ..)| last != ' ') {
|
||||
chars.push((c, i, after_zwsp && c != ' '));
|
||||
let texts: Vec<String> = page.glyphs.iter().map(|g| fold(&g.text)).collect();
|
||||
let n = texts.len();
|
||||
let new_line = |i: usize| i > 0 && page.line_of[i] != page.line_of[i - 1];
|
||||
// A line that ends in a soft hyphen, past any empty or other invisible glyphs and characters
|
||||
// after it on that line, runs on to the next.
|
||||
let ends_in_soft_hyphen = |end: usize| {
|
||||
(0..=end)
|
||||
.rev()
|
||||
.take_while(|&k| page.line_of[k] == page.line_of[end])
|
||||
.flat_map(|k| page.glyphs[k].text.chars().rev())
|
||||
.find(|&c| c == '\u{AD}' || !invisible(c))
|
||||
== Some('\u{AD}')
|
||||
};
|
||||
// A visible hyphen between letters at a line end.
|
||||
let hyphen = |c: char| matches!(c, '-' | '\u{2010}');
|
||||
let divided: Vec<bool> = (0..n)
|
||||
.map(|i| {
|
||||
let chars: Vec<char> = visible(texts[i].clone()).chars().collect();
|
||||
let Some(&last) = chars.last() else { return false };
|
||||
let before = if chars.len() >= 2 {
|
||||
Some(chars[chars.len() - 2])
|
||||
} else if i > 0 && !page.space_before[i] && !new_line(i) {
|
||||
visible(texts[i - 1].clone()).chars().last()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
hyphen(last)
|
||||
&& before.is_some_and(char::is_alphabetic)
|
||||
&& i + 1 < n
|
||||
&& new_line(i + 1)
|
||||
&& visible(texts[i + 1].clone()).chars().next().is_some_and(char::is_alphabetic)
|
||||
})
|
||||
.collect();
|
||||
let mut all = Vec::new();
|
||||
let readings = if divided.contains(&true) { 3 } else { 1 };
|
||||
for reading in 0..readings {
|
||||
// Each character, its glyph, and whether a skipped zero width space came right before it.
|
||||
let mut chars: Vec<(char, usize, bool)> = Vec::new();
|
||||
let mut after_zwsp = false;
|
||||
for i in 0..n {
|
||||
let joined = reading > 0 && i > 0 && divided[i - 1];
|
||||
let line_break = new_line(i) && !ends_in_soft_hyphen(i - 1) && !joined;
|
||||
if i > 0 && (page.space_before[i] || line_break) && chars.last().is_some_and(|&(c, ..)| c != ' ') {
|
||||
chars.push((' ', i, false));
|
||||
after_zwsp = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A neighbour bounds a word only in a script written with spaces between words, or when it
|
||||
// is a digit.
|
||||
let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|&(c, ..)| c.is_alphanumeric() && (c.is_numeric() || !unspaced(c)));
|
||||
// A word ends at a skipped zero width space as it does at a space.
|
||||
let edge = |i: usize| chars.get(i).is_some_and(|&(.., zwsp)| zwsp);
|
||||
let mut hits = Vec::new();
|
||||
let mut start = 0;
|
||||
while start + needle.len() <= chars.len() {
|
||||
let end = start + needle.len();
|
||||
let bounded = (edge(start) || !word(start.checked_sub(1))) && (edge(end) || !word(Some(end)));
|
||||
if (!whole || bounded) && chars[start..end].iter().map(|&(c, ..)| c).eq(needle.iter().copied()) {
|
||||
hits.push(chars[start].1..chars[end - 1].1 + 1);
|
||||
if hits.len() == limit {
|
||||
break;
|
||||
let mut glyph: Vec<char> = texts[i].chars().collect();
|
||||
if reading == 1 && divided[i] {
|
||||
// The hyphen: the last visible character.
|
||||
if let Some(at) = glyph.iter().rposition(|&c| !invisible(c)) {
|
||||
glyph.remove(at);
|
||||
}
|
||||
}
|
||||
start = end;
|
||||
} else {
|
||||
start += 1;
|
||||
for c in glyph {
|
||||
after_zwsp |= c == '\u{200B}';
|
||||
if invisible(c) {
|
||||
continue;
|
||||
}
|
||||
let c = if c.is_whitespace() { ' ' } else { c };
|
||||
if c != ' ' || chars.last().is_none_or(|&(last, ..)| last != ' ') {
|
||||
chars.push((c, i, after_zwsp && c != ' '));
|
||||
after_zwsp = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A neighbour bounds a word only in a script written with spaces between words, or when it
|
||||
// is a digit.
|
||||
let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|&(c, ..)| c.is_alphanumeric() && (c.is_numeric() || !unspaced(c)));
|
||||
// A word ends at a skipped zero width space as it does at a space.
|
||||
let edge = |i: usize| chars.get(i).is_some_and(|&(.., zwsp)| zwsp);
|
||||
let mut hits = Vec::new();
|
||||
let mut start = 0;
|
||||
while start + needle.len() <= chars.len() {
|
||||
let end = start + needle.len();
|
||||
let bounded = (edge(start) || !word(start.checked_sub(1))) && (edge(end) || !word(Some(end)));
|
||||
if (!whole || bounded) && chars[start..end].iter().map(|&(c, ..)| c).eq(needle.iter().copied()) {
|
||||
hits.push(chars[start].1..chars[end - 1].1 + 1);
|
||||
if hits.len() == limit {
|
||||
break;
|
||||
}
|
||||
start = end;
|
||||
} else {
|
||||
start += 1;
|
||||
}
|
||||
}
|
||||
all.push(hits);
|
||||
}
|
||||
if readings == 1 {
|
||||
return all.remove(0);
|
||||
}
|
||||
// A hit is left out where it overlaps one kept from another reading; one reading's hits are
|
||||
// all kept, though two can share a glyph.
|
||||
let mut hits: Vec<(Range<usize>, usize)> = all.into_iter().enumerate().flat_map(|(r, hits)| hits.into_iter().map(move |h| (h, r))).collect();
|
||||
hits.sort_by_key(|(h, _)| (h.start, std::cmp::Reverse(h.end)));
|
||||
let mut out: Vec<(Range<usize>, usize)> = Vec::new();
|
||||
for (h, r) in hits {
|
||||
let overlaps = out.iter().any(|(k, kr)| *kr != r && h.start < k.end && k.start < h.end);
|
||||
if !overlaps && out.len() < limit {
|
||||
out.push((h, r));
|
||||
}
|
||||
}
|
||||
hits
|
||||
out.into_iter().map(|(h, _)| h).collect()
|
||||
}
|
||||
|
||||
/// One glyph per entry of `text`, each on the line given in `lines`.
|
||||
fn lined(text: &[&str], lines: &[u32]) -> PageText {
|
||||
let mut p = page(text);
|
||||
p.line_of = lines.to_vec();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ligature_matches_its_letters() {
|
||||
let text = page(&["o", "\u{FB03}", "c", "e", " ", "o", "f", "\u{FB01}", "c", "e"]);
|
||||
assert_eq!(text.find("office"), vec![0..4, 5..10]);
|
||||
assert_eq!(text.find("OFFICE"), vec![0..4, 5..10]);
|
||||
assert_eq!(text.find_opts("office", true, true), vec![0..4, 5..10], "case-sensitive and whole words too");
|
||||
assert_eq!(text.find("o\u{FB03}ce"), vec![0..4, 5..10], "a ligature in the query reads as its letters too");
|
||||
assert_eq!(text.find("fi"), vec![1..2, 7..8], "a match inside a ligature takes its glyph");
|
||||
assert!(text.find("o\u{FB13}").is_empty(), "no other compatibility folding");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_divided_by_a_line_end_hyphen_matches_whole_and_as_written() {
|
||||
// "exam-" ends line 0, "ple" starts line 1; the hyphen is its own glyph.
|
||||
let text = lined(&["e", "x", "a", "m", "-", "p", "l", "e"], &[0, 0, 0, 0, 0, 1, 1, 1]);
|
||||
assert_eq!(text.find("example"), vec![0..8], "both parts, and the hyphen between them");
|
||||
assert_eq!(text.find_opts("example", false, true), vec![0..8], "a whole word");
|
||||
assert_eq!(text.find("exam-ple"), vec![0..8], "a query with the hyphen");
|
||||
assert_eq!(text.find("exam- ple"), vec![0..8], "and with the line break as a space");
|
||||
assert_eq!(text.find("exam"), vec![0..4]);
|
||||
// The hyphen in the glyph of the last letter, a soft hyphen and U+2010.
|
||||
for hyphen in ["m-", "m\u{AD}", "m\u{2010}"] {
|
||||
let text = lined(&["e", "x", "a", hyphen, "p", "l", "e"], &[0, 0, 0, 0, 1, 1, 1]);
|
||||
assert_eq!(text.find("example"), vec![0..7], "{hyphen:?}");
|
||||
}
|
||||
// Not divided: a hyphen inside a line, a dash after a word gap, a hyphen between digits.
|
||||
assert!(page(&["e", "x", "a", "m", "-", "p", "l", "e"]).find("example").is_empty(), "inside a line");
|
||||
let mut spaced = lined(&["e", "x", "a", "m", "-", "p", "l", "e"], &[0, 0, 0, 0, 0, 1, 1, 1]);
|
||||
spaced.space_before[4] = true;
|
||||
assert!(spaced.find("example").is_empty(), "a dash after a word gap");
|
||||
assert!(spaced.find("exam ple").is_empty(), "a dash after a word gap is never dropped");
|
||||
assert!(lined(&["1", "0", "-", "2", "0"], &[0, 0, 0, 1, 1]).find("1020").is_empty(), "between digits");
|
||||
assert!(lined(&["a", "-", "2", "0"], &[0, 0, 1, 1]).find("a20").is_empty(), "before a number");
|
||||
assert!(lined(&["1", "0", "-", "a", "b"], &[0, 0, 0, 1, 1]).find("10ab").is_empty(), "after a number");
|
||||
assert!(lined(&["a", "-"], &[0, 0]).find("a-").len() == 1, "at the end of the page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -171,6 +275,10 @@ fn whole_word_rejection_keeps_overlapping_candidates() {
|
||||
// Accepted matches still do not overlap, even within one multi-character glyph.
|
||||
assert_eq!(page(&["aaaaa"]).find("aaa"), vec![0..1]);
|
||||
assert_eq!(page(&["aaaaa"]).find("aa"), vec![0..1, 0..1]);
|
||||
// So does a page with a word divided at a line end, which is searched in three readings.
|
||||
let divided = lined(&["\u{FB03}", " ", "exam", "-", "ple"], &[0, 0, 0, 0, 1]);
|
||||
assert_eq!(divided.find("f"), vec![0..1, 0..1]);
|
||||
assert_eq!(divided.find("example"), vec![2..5]);
|
||||
}
|
||||
|
||||
/// A letter from a block in `UNSPACED_BLOCK_SAMPLES` next to a whole-word match leaves it standing
|
||||
@@ -191,6 +299,8 @@ fn whole_words_follow_the_unicode_blocks_of_unspaced_scripts() {
|
||||
#[test]
|
||||
fn search_matches_reference_for_unicode_gaps_limits_and_word_boundaries() {
|
||||
let alphabet = ["a", "b", " ", "-", "İ", "ı", "ς", "Σ", "\t", "\n", "ffi", "", "界", "ก", "한", "e\u{301}", "العربية", "\u{AD}", "a\u{200B}"];
|
||||
// Ligatures, digits and HYPHEN exercise the readings of a line-end hyphen.
|
||||
let alphabet: Vec<&str> = alphabet.into_iter().chain(["\u{FB01}", "1", "\u{2010}"]).collect();
|
||||
let mut seed = 1234567u64;
|
||||
let mut next = || {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
|
||||
@@ -42,6 +42,7 @@ mod xform;
|
||||
mod zoom;
|
||||
pub(super) mod zoom_snap;
|
||||
|
||||
pub(crate) use area::SignTab;
|
||||
pub(crate) use area::signature_badges;
|
||||
use area::{drawing_edge_pointer, glide_interrupted, page_scroll, presentation_click, run_button, set_layers, zoom_anchor};
|
||||
#[cfg(test)]
|
||||
@@ -714,6 +715,24 @@ pub struct DocView {
|
||||
/// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style.
|
||||
pub redact_drag: crate::redact_ui::AreaDrag,
|
||||
pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>,
|
||||
/// How many Apply redactions steps are in effect in this view. While it is above 0, Save
|
||||
/// proposes the name with `_Redacted` ([`pdfcraft_engine::redacted_file_name`]), and while it is
|
||||
/// above `redactions_downloaded`, Save asks where.
|
||||
/// Undo of an Apply redactions step takes one off and Redo adds it back. Reload and a desktop
|
||||
/// save set it to 0, and Revert sets it to `redactions_downloaded`; after a desktop save the document has the name it was saved
|
||||
/// under. A web download keeps it, so later downloads carry the `_Redacted` name.
|
||||
pub redactions_applied: usize,
|
||||
/// How many Apply redactions steps saved into the document's file are undone in this view.
|
||||
/// While it is above 0, Save asks where, so the restored content is not written over the
|
||||
/// redacted file. Redo takes one off. Revert, Reload and a desktop save set it to 0.
|
||||
pub redactions_undone_after_save: usize,
|
||||
/// Set when Apply redactions runs while saved Apply redactions steps are undone: Redo can no
|
||||
/// longer bring those steps back, so Save asks where until a desktop save or Revert clears it.
|
||||
pub saved_redactions_cut_off: bool,
|
||||
/// `redactions_applied` at the last web download, which Revert restores. While
|
||||
/// `redactions_applied` is below it, a delivered step is undone and Save asks where. A desktop
|
||||
/// save leaves it at 0.
|
||||
pub redactions_downloaded: usize,
|
||||
/// A crop rectangle being dragged (Crop tool).
|
||||
pub crop_drag: crate::crop::CropDrag,
|
||||
/// Enhance ▸ Camera image: the quadrilateral being placed.
|
||||
@@ -1129,6 +1148,10 @@ impl DocView {
|
||||
links: Default::default(),
|
||||
redact_drag: None,
|
||||
pending_redaction: None,
|
||||
redactions_applied: 0,
|
||||
redactions_undone_after_save: 0,
|
||||
saved_redactions_cut_off: false,
|
||||
redactions_downloaded: 0,
|
||||
crop_drag: None,
|
||||
camera: None,
|
||||
camera_done: None,
|
||||
@@ -1716,6 +1739,7 @@ fn draw_page(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, i
|
||||
area_tool: false,
|
||||
hover: None,
|
||||
released_over: false,
|
||||
sign_tabs: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
page_tool_input(ui, view, frame, &slot)
|
||||
@@ -3025,7 +3049,8 @@ fn fits_height(r: Rect, view_height: f32, pixels_per_point: f32) -> bool {
|
||||
}
|
||||
|
||||
/// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a
|
||||
/// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.
|
||||
/// scroll area with this frame's zoom, scrolling, tool input, overlays (form fields, comments,
|
||||
/// signature badges and sign tabs) and render requests.
|
||||
pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let can_paste_key = egui::Id::unique("can-paste-image");
|
||||
@@ -3699,5 +3724,7 @@ enum FieldMenu {
|
||||
Duplicate(String),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sign_tab_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{LayerOp, PdfCraftApp, Pos2, Rect};
|
||||
use super::{Color32, HashSet, LayerOp, PdfCraftApp, Pos2, Rect, Tokens, Vec2, icons, pos2, theme, vec2};
|
||||
|
||||
/// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text.
|
||||
pub(crate) struct SignatureBadge {
|
||||
@@ -27,6 +27,121 @@ pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], pa
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The empty signature fields on one page that get a sign tab, as their names and widget
|
||||
/// rectangles (user space). Each is unsigned and visible, on this page, with a rectangle that
|
||||
/// passes the same screen-space guard as [`signature_badges`]. A click must also be able to sign
|
||||
/// it, as in `forms_ui::page_input`: the document allows filling (`can_fill`), and the form field
|
||||
/// of that name is a signature field that isn't read-only, with a shown widget at that place
|
||||
/// that isn't read-only on its own.
|
||||
pub(crate) fn sign_tabs<'a>(
|
||||
signatures: &'a [pdfcraft_engine::SignatureInfo],
|
||||
form: &[pdfcraft_engine::FormField],
|
||||
page: usize,
|
||||
can_fill: bool,
|
||||
) -> Vec<(&'a str, [f64; 4])> {
|
||||
let mut empty = signatures
|
||||
.iter()
|
||||
.filter(|s| can_fill && !s.signed && s.visible && s.page == Some(page))
|
||||
.filter_map(|s| s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|r| (s.field.as_str(), r)))
|
||||
.peekable();
|
||||
if empty.peek().is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
// The widgets a click signs, by field name and exact rectangle, from one pass over the form:
|
||||
// a file with thousands of fields costs no more per frame than the field hit test does.
|
||||
let signable: HashSet<(&str, [u64; 4])> = form
|
||||
.iter()
|
||||
.filter(|f| f.kind == pdfcraft_engine::FormFieldKind::Signature && !f.read_only())
|
||||
.flat_map(|f| {
|
||||
f.widgets.iter().filter(|w| w.page == Some(page) && !w.hidden && !w.read_only).map(move |w| (f.name.as_str(), w.rect.map(f64::to_bits)))
|
||||
})
|
||||
.collect();
|
||||
empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).collect()
|
||||
}
|
||||
|
||||
/// The largest sign tab's height, in points. Every other size is a share of the tab's height,
|
||||
/// taken from this one: a 3 pt inset, a 12 pt icon, 5 pt padding, an 11 pt label and 4 pt corners.
|
||||
pub(super) const SIGN_TAB_MAX: f32 = 18.0;
|
||||
/// The smallest sign tab's height, in points: a field too small for this chip gets no tab.
|
||||
const SIGN_TAB_MIN: f32 = 10.0;
|
||||
/// The share of its field's height on screen that a sign tab takes, between the two sizes.
|
||||
const SIGN_TAB_SHARE: f32 = 0.4;
|
||||
/// The smallest sign tab that carries the label; below it the tab is the icon alone.
|
||||
const SIGN_TAB_LABEL_MIN: f32 = 14.0;
|
||||
/// The label's font size on the largest sign tab; it shrinks with the tab.
|
||||
const SIGN_TAB_FONT: f32 = 11.0;
|
||||
|
||||
/// Where one sign tab is drawn on screen: its chip, the icon's square and, when the label fits,
|
||||
/// the point where the label starts (its left edge, on the chip's center line), with the
|
||||
/// label's font size and the chip's corner radius at this tab's size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct SignTab {
|
||||
pub rect: Rect,
|
||||
pub icon: Rect,
|
||||
pub label: Option<Pos2>,
|
||||
pub font: f32,
|
||||
pub radius: f32,
|
||||
}
|
||||
|
||||
/// Lays out a sign tab inside the top-left corner of `field` (the widget on screen), for a label
|
||||
/// `label_width` points wide at [`SIGN_TAB_FONT`], its size on the largest tab. The tab is
|
||||
/// [`SIGN_TAB_SHARE`] of the field's height, from [`SIGN_TAB_MIN`] to [`SIGN_TAB_MAX`], and its
|
||||
/// inset, icon, padding, label and corners scale with it. It carries the label from
|
||||
/// [`SIGN_TAB_LABEL_MIN`] up when the whole tab fits in half the field's width, and is a square
|
||||
/// icon chip otherwise. It is left out when even that chip doesn't fit, or the field isn't finite.
|
||||
pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option<SignTab> {
|
||||
if !field.is_finite() {
|
||||
return None;
|
||||
}
|
||||
// Finite, so the clamp has a number to work on (and its bounds are constants in order).
|
||||
let h = (field.height() * SIGN_TAB_SHARE).clamp(SIGN_TAB_MIN, SIGN_TAB_MAX);
|
||||
let scale = h / SIGN_TAB_MAX;
|
||||
let (inset, icon_side, pad) = (3.0 * scale, 12.0 * scale, 5.0 * scale);
|
||||
if field.height() < h + 2.0 * inset || h > field.width() / 2.0 {
|
||||
return None;
|
||||
}
|
||||
let full = pad + icon_side + pad + label_width * scale + pad;
|
||||
let with_label = h >= SIGN_TAB_LABEL_MIN && label_width.is_finite() && label_width > 0.0 && full <= field.width() / 2.0;
|
||||
let width = if with_label { full } else { h };
|
||||
let rect = Rect::from_min_size(field.min + Vec2::splat(inset), vec2(width, h));
|
||||
let icon_x = if with_label { rect.left() + pad } else { rect.center().x - icon_side / 2.0 };
|
||||
let icon = Rect::from_min_size(pos2(icon_x, rect.center().y - icon_side / 2.0), Vec2::splat(icon_side));
|
||||
let label = with_label.then(|| pos2(icon.right() + pad, rect.center().y));
|
||||
Some(SignTab { rect, icon, label, font: SIGN_TAB_FONT * scale, radius: 4.0 * scale })
|
||||
}
|
||||
|
||||
/// The sign tab's label, "Sign", laid out at `size` points.
|
||||
fn sign_tab_label(ui: &egui::Ui, size: f32) -> std::sync::Arc<egui::Galley> {
|
||||
ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE))
|
||||
}
|
||||
|
||||
/// The sign tab of an empty signature field whose widget is at `field` on screen, on the page at
|
||||
/// `page`, laid out for its label measured at its largest size: where it is painted and where a
|
||||
/// click on it signs.
|
||||
pub(super) fn sign_tab_at(ui: &egui::Ui, field: Rect, page: Rect) -> Option<SignTab> {
|
||||
sign_tab_on_page(field, page, sign_tab_label(ui, SIGN_TAB_FONT).size().x)
|
||||
}
|
||||
|
||||
/// [`sign_tab_layout`] in the part of `field` that is on `page`: form fields take clicks on the
|
||||
/// page only, so a widget that straddles the page's edge gets its tab where a click reaches it,
|
||||
/// or none when that part has no room for one.
|
||||
pub(crate) fn sign_tab_on_page(field: Rect, page: Rect, label_width: f32) -> Option<SignTab> {
|
||||
sign_tab_layout(field.intersect(page), label_width)
|
||||
}
|
||||
|
||||
/// Paints a sign tab laid out by [`sign_tab_at`]: an accent chip with the signature icon and
|
||||
/// "Sign" in white, as the app's primary buttons are. The label is drawn at the tab's size; text
|
||||
/// scales with its size, and the padding takes up any rounding. Screen-only chrome, like the
|
||||
/// validation badges.
|
||||
pub(super) fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, tab: &SignTab, t: &Tokens) {
|
||||
painter.rect_filled(tab.rect, egui::epaint::CornerRadiusF32::same(tab.radius), t.accent);
|
||||
icons::paint(ui, tab.icon, "signature", tab.icon.width(), Color32::WHITE);
|
||||
if let Some(at) = tab.label {
|
||||
let galley = sign_tab_label(ui, tab.font);
|
||||
painter.galley(at - vec2(0.0, galley.size().y / 2.0), galley, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the viewer's scroll identity tied to the document instead of its parent UI. Without
|
||||
// `fades` (Show Page Edge Shadows off) the viewport-edge gradients are off for this area only.
|
||||
pub(super) fn page_scroll<R>(
|
||||
|
||||
@@ -363,6 +363,9 @@ fn zoom_shortcuts(view: &mut DocView, pressed: &impl Fn(egui::KeyboardShortcut)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document view's keyboard shortcuts: find, rotation, zoom (or the page grid's size),
|
||||
/// history, Escape, and the paging and scrolling keys. An open form field keeps the paging
|
||||
/// and scrolling keys for itself.
|
||||
pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) {
|
||||
use egui::{Key, KeyboardShortcut, Modifiers};
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) {
|
||||
@@ -407,8 +410,13 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s
|
||||
view.view_history(true);
|
||||
}
|
||||
let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k));
|
||||
// An open form field (a drop-down's or a list box's items) takes the arrows, Page Up / Page
|
||||
// Down, Home, End and Escape. A focused check box or radio button uses none of them, so the
|
||||
// page keys still work there.
|
||||
let field_open = view.forms.focus.is_some() && form_box.is_none();
|
||||
// An open menu takes Escape first and closes; the selection stays for the next one (#3535).
|
||||
if key(Key::Escape) && !egui::Popup::is_any_open(ctx) {
|
||||
// So does an open field, whose list closes.
|
||||
if key(Key::Escape) && !egui::Popup::is_any_open(ctx) && !field_open {
|
||||
if view.camera.is_some() || view.camera_done.is_some() {
|
||||
view.pending_action = Some(ViewAction::CancelCamera);
|
||||
} else if view.selection.is_some() || view.all_text {
|
||||
@@ -418,6 +426,10 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s
|
||||
view.find = None;
|
||||
}
|
||||
}
|
||||
// The open field's keys leave the page under it where it is.
|
||||
if field_open {
|
||||
return;
|
||||
}
|
||||
// Home and End, and the keys listed with them for Go to first / last page: Shift+Ctrl
|
||||
// (Shift+⌘ on macOS) with ↑ / ↓ or Page Up / Page Down (#6434).
|
||||
let shift_cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Stroke};
|
||||
use pdfcraft_render::{DocInfo, LinkTarget, PageText};
|
||||
|
||||
use super::area::{SignTab, paint_sign_tab, sign_tab_at, sign_tabs};
|
||||
use super::{
|
||||
DocView, MARK_ICON_SHARE, PageEnv, PageFrame, PageSlot, PageXform, Selection, Span, cached_edit_images, click_unit, mark_anchor,
|
||||
signature_badges, verdict_mark_rect,
|
||||
@@ -30,6 +31,8 @@ pub(super) struct PageInput {
|
||||
/// The press's click came up over what the press began on: a link's or a field's click counts
|
||||
/// only then, as a button's does.
|
||||
pub(super) released_over: bool,
|
||||
/// The sign tabs on empty fields a click would sign, painted over the page.
|
||||
pub(super) sign_tabs: Vec<SignTab>,
|
||||
}
|
||||
|
||||
/// Common geometry and pointer state for a tool acting on one page.
|
||||
@@ -83,6 +86,10 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut
|
||||
};
|
||||
// While a table is being set up, nothing else is drawn or moved.
|
||||
let prepare_allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();
|
||||
// An empty field a click would sign carries a small tab saying so, shown only while
|
||||
// a click on the field signs it (the Select tool, not while preparing a form). The tab
|
||||
// is drawn over every field, so a click on it signs its field (`forms_ui::hit`).
|
||||
let tabs = page_sign_tabs(ui, doc, form, info, slot, can_fill, tool == QuickTool::Select && !preparing);
|
||||
let hits = PageHits {
|
||||
page: i,
|
||||
xf: &xf,
|
||||
@@ -102,6 +109,7 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut
|
||||
images: &images,
|
||||
clip: ui.clip_rect(),
|
||||
text_links,
|
||||
tabs: &tabs,
|
||||
};
|
||||
if let Some(o) = ptr.pressed() {
|
||||
// A press with Shift or ⌘ in Edit text is the objects', whatever lies under it
|
||||
@@ -254,7 +262,39 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut
|
||||
let on_comment = comments::page_input(ui, resp, &pcx, press, taken, view);
|
||||
let consumed = taken || on_comment;
|
||||
let hover = pointer.and_then(|p| claim_under(&hits, view, p, frame.env.unobstructed));
|
||||
PageInput { press, text_drag: !view.router.keeps_drag(), consumed, area_tool, hover, released_over }
|
||||
PageInput {
|
||||
press,
|
||||
text_drag: !view.router.keeps_drag(),
|
||||
consumed,
|
||||
area_tool,
|
||||
hover,
|
||||
released_over,
|
||||
sign_tabs: tabs.into_iter().map(|(_, tab)| tab).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sign tabs on the slot's page, on empty fields a click would sign, each with the field it
|
||||
/// signs; none unless `shown`.
|
||||
fn page_sign_tabs<'a>(
|
||||
ui: &egui::Ui,
|
||||
doc: &'a pdfcraft_engine::Document,
|
||||
form: &[pdfcraft_engine::FormField],
|
||||
info: &DocInfo,
|
||||
slot: &PageSlot,
|
||||
can_fill: bool,
|
||||
shown: bool,
|
||||
) -> Vec<(&'a str, SignTab)> {
|
||||
let PageSlot { i, xf, .. } = slot;
|
||||
let i = *i;
|
||||
if !shown {
|
||||
return Vec::new();
|
||||
}
|
||||
sign_tabs(&doc.signatures, form, i, can_fill)
|
||||
.into_iter()
|
||||
.filter_map(|(name, [x0, y0, x1, y1])| {
|
||||
sign_tab_at(ui, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]), xf.rect).map(|tab| (name, tab))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What lies under the pointer at `p`, after the tools act: its top, what a press there would take,
|
||||
@@ -457,6 +497,9 @@ struct PageHits<'a> {
|
||||
clip: Rect,
|
||||
/// Addresses written as plain page text open like links (#4207).
|
||||
text_links: bool,
|
||||
/// The sign tabs on empty signature fields, with the field each one signs: drawn over every
|
||||
/// field, so the pointer on one is on its own field.
|
||||
tabs: &'a [(&'a str, SignTab)],
|
||||
}
|
||||
|
||||
impl PageHits<'_> {
|
||||
@@ -539,6 +582,7 @@ impl PageHits<'_> {
|
||||
images,
|
||||
clip,
|
||||
text_links,
|
||||
tabs,
|
||||
} = *self;
|
||||
// A press with Shift or ⌘ is the objects' (`object_ui::modified_hit`), off crop mode's page.
|
||||
if let Some(objects) = objects {
|
||||
@@ -561,7 +605,7 @@ impl PageHits<'_> {
|
||||
let fields = if preparing {
|
||||
crate::prepare::hit(xf, info, page, form, field_tool, prepare_allowed, &view.prepare, p)
|
||||
} else if tool == QuickTool::Select {
|
||||
crate::forms_ui::hit(xf, info, page, form, can_fill, p)
|
||||
crate::forms_ui::hit(xf, info, page, form, tabs, can_fill, p)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -844,6 +888,7 @@ pub(super) fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut P
|
||||
prefs,
|
||||
preparing,
|
||||
redact_mark,
|
||||
t,
|
||||
table_preview,
|
||||
tool,
|
||||
unobstructed,
|
||||
@@ -969,6 +1014,11 @@ pub(super) fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut P
|
||||
view.flash = None;
|
||||
}
|
||||
}
|
||||
// The sign tabs (above). Like the validation badges, they never enter the file,
|
||||
// exports or printing.
|
||||
for tab in &input.sign_tabs {
|
||||
paint_sign_tab(ui, painter, tab, t);
|
||||
}
|
||||
// Validation badges are viewer chrome over the widget. A recognised named-layer appearance may
|
||||
// show the verdict in the display copy too; saves retain its original streams. Badges never
|
||||
// enter document streams, exports or either print path. Their tips show where the comments'
|
||||
|
||||
@@ -241,7 +241,7 @@ const RAW_READS: [&str; 21] = [
|
||||
|
||||
/// Functions in the page modules that are not page input and read egui's pointer state
|
||||
/// themselves: (file, function, why).
|
||||
const NOT_PAGE_INPUT: [(&str, &str, &str); 10] = [
|
||||
const NOT_PAGE_INPUT: [(&str, &str, &str); 12] = [
|
||||
("canvas/area.rs", "zoom_anchor", "a pinch zooms the whole view, and is read before the pages' widget exists"),
|
||||
("canvas/area.rs", "drawing_edge_pointer", "scrolls the view at its edges, read before the pages' widget exists"),
|
||||
("canvas/area.rs", "glide_interrupted", "a press anywhere stops the touchpad's glide"),
|
||||
@@ -249,6 +249,8 @@ const NOT_PAGE_INPUT: [(&str, &str, &str); 10] = [
|
||||
("canvas/bars.rs", "page_size_hint", "the page size hint sits in the view's corner, not on a page"),
|
||||
("canvas/organize.rs", "organize_grid", "Organize Pages shows thumbnails, not pages"),
|
||||
("tools/forms_ui.rs", "overlay", "the field editor is an Area of its own over the page"),
|
||||
("tools/forms_ui.rs", "choice_list", "a drop-down's open list is an Area of its own over the page"),
|
||||
("tools/forms_ui.rs", "scroll_bar", "the scroll bar of a drop-down's open list, in its Area over the page"),
|
||||
("tools/content_ui.rs", "editor", "the added-text editor is an Area of its own over the page"),
|
||||
("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page"),
|
||||
("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"),
|
||||
|
||||
@@ -76,9 +76,14 @@ impl DocView {
|
||||
/// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its
|
||||
/// text layer is loaded (used by UI tests and automation to aim pointer input).
|
||||
pub fn glyph_screen_pos(&self, page: usize, glyph: usize) -> Option<Pos2> {
|
||||
self.glyph_screen_rect(page, glyph).map(|r| r.center())
|
||||
}
|
||||
|
||||
/// The screen rectangle of glyph `glyph` on `page`, when the page is on screen.
|
||||
pub fn glyph_screen_rect(&self, page: usize, glyph: usize) -> Option<Rect> {
|
||||
let (_, xf) = self.screen_xforms.iter().find(|(p, _)| *p == page)?;
|
||||
let g = self.texts.get(&page)?.glyphs.get(glyph)?;
|
||||
Some(xf.view_rect(g.rect).center())
|
||||
Some(xf.view_rect(g.rect))
|
||||
}
|
||||
|
||||
/// Selected text, if any (⌘C).
|
||||
@@ -172,6 +177,9 @@ enum SelectionAction {
|
||||
Copy,
|
||||
}
|
||||
|
||||
/// The selection bar's width before it has been laid out once (English labels).
|
||||
const SELECTION_BAR_GUESS: f32 = 520.0;
|
||||
|
||||
/// Actions on an existing text selection, next to the selected words.
|
||||
pub(super) fn selection_actions(
|
||||
ui: &mut egui::Ui,
|
||||
@@ -203,32 +211,33 @@ pub(super) fn selection_actions(
|
||||
if !viewport.intersects(rect) {
|
||||
return false;
|
||||
}
|
||||
let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - 520.0).max(viewport.left() + 8.0));
|
||||
let id = egui::Id::unique(("text-selection-actions", view.view_key()));
|
||||
// The bar stays inside the pages' area, by the width it had last frame (its labels make it
|
||||
// wider in some languages), so it never covers a side panel; a first guess before it has one.
|
||||
let width = egui::AreaState::load(ui.ctx(), id).and_then(|a| a.size).map_or(SELECTION_BAR_GUESS, |s| s.x);
|
||||
let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - width - 8.0).max(viewport.left() + 8.0));
|
||||
let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };
|
||||
let mut chosen = None;
|
||||
egui::Area::new(egui::Id::unique(("text-selection-actions", view.view_key()))).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(
|
||||
ui.ctx(),
|
||||
|ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (label, action) in [
|
||||
(tl!("Add comment"), SelectionAction::Note),
|
||||
(tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
|
||||
(tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
|
||||
(tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
|
||||
(tl!("Replace text"), SelectionAction::Replace),
|
||||
] {
|
||||
if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
|
||||
chosen = Some(action);
|
||||
}
|
||||
egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (label, action) in [
|
||||
(tl!("Add comment"), SelectionAction::Note),
|
||||
(tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
|
||||
(tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
|
||||
(tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
|
||||
(tl!("Replace text"), SelectionAction::Replace),
|
||||
] {
|
||||
if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() {
|
||||
chosen = Some(action);
|
||||
}
|
||||
if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
|
||||
chosen = Some(SelectionAction::Copy);
|
||||
}
|
||||
});
|
||||
}
|
||||
if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
|
||||
chosen = Some(SelectionAction::Copy);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
let Some(action) = chosen else { return false };
|
||||
if let SelectionAction::Copy = action {
|
||||
// Copying closes the bar but keeps the words selected, for ⌘C or a second action.
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! Unit tests for the sign tabs on empty signature fields (`area.rs`).
|
||||
|
||||
use super::area::{SIGN_TAB_MAX, sign_tab_layout, sign_tab_on_page, sign_tabs};
|
||||
use super::*;
|
||||
use pdfcraft_engine::{FormField, FormFieldKind, FormWidget, SignatureInfo};
|
||||
|
||||
/// The widget rectangle the unit tests use (user space).
|
||||
const RECT: [f64; 4] = [20.0, 110.0, 140.0, 180.0];
|
||||
|
||||
/// An unsigned, visible signature listing for field `name` with its widget on `page` at
|
||||
/// `rect`. Each test changes the one thing it is about.
|
||||
fn listing(name: &str, page: usize, rect: [f64; 4]) -> SignatureInfo {
|
||||
SignatureInfo {
|
||||
field: name.into(),
|
||||
signed: false,
|
||||
page: Some(page),
|
||||
rect: Some(rect),
|
||||
visible: true,
|
||||
signer: None,
|
||||
certificate: None,
|
||||
chain: Vec::new(),
|
||||
date: None,
|
||||
signing_time: None,
|
||||
reason: None,
|
||||
location: None,
|
||||
contact: None,
|
||||
sub_filter: None,
|
||||
doc_timestamp: false,
|
||||
certify: None,
|
||||
revision: 1,
|
||||
signed_len: 0,
|
||||
digest: None,
|
||||
algorithm: None,
|
||||
timestamp: false,
|
||||
timestamp_time: None,
|
||||
status: pdfcraft_engine::SignatureStatus::Unknown,
|
||||
modification: pdfcraft_engine::sign::Modification::None,
|
||||
details: Vec::new(),
|
||||
verdict_shown: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The signature form field `name` with one shown widget on `page` at `rect`.
|
||||
fn field(name: &str, page: usize, rect: [f64; 4]) -> FormField {
|
||||
FormField {
|
||||
name: name.into(),
|
||||
obj: pdfcraft_cos::ObjRef::new(4, 0),
|
||||
kind: FormFieldKind::Signature,
|
||||
value: Vec::new(),
|
||||
default: Vec::new(),
|
||||
flags: 0,
|
||||
max_len: None,
|
||||
options: Vec::new(),
|
||||
selected: Vec::new(),
|
||||
single_value_is_array: false,
|
||||
da: String::new(),
|
||||
quadding: 0,
|
||||
tooltip: None,
|
||||
widgets: vec![FormWidget {
|
||||
obj: pdfcraft_cos::ObjRef::new(4, 0),
|
||||
page: Some(page),
|
||||
rect,
|
||||
on_state: None,
|
||||
state: None,
|
||||
tab: 0,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
read_only: false,
|
||||
rotation: 0,
|
||||
caption: None,
|
||||
list: None,
|
||||
round: false,
|
||||
}],
|
||||
actions: Default::default(),
|
||||
button: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The cases (by name) whose single listing and form still got a tab on page 0.
|
||||
fn tabbed<'a>(cases: &[(&'a str, SignatureInfo, Vec<FormField>, bool)]) -> Vec<&'a str> {
|
||||
cases.iter().filter(|(_, s, form, can_fill)| !sign_tabs(std::slice::from_ref(s), form, 0, *can_fill).is_empty()).map(|c| c.0).collect()
|
||||
}
|
||||
|
||||
/// An empty, visible signature field that a click signs gets one tab, at its widget, on its
|
||||
/// own page only.
|
||||
#[test]
|
||||
fn sign_tabs_mark_an_empty_field_that_a_click_signs() {
|
||||
let approver = [listing("Approver", 0, RECT)];
|
||||
assert_eq!(sign_tabs(&approver, &[field("Approver", 0, RECT)], 0, true), vec![("Approver", RECT)]);
|
||||
let later = [listing("Witness", 1, RECT)];
|
||||
assert_eq!(sign_tabs(&later, &[field("Witness", 1, RECT)], 1, true), vec![("Witness", RECT)]);
|
||||
assert!(sign_tabs(&later, &[field("Witness", 1, RECT)], 0, true).is_empty(), "not on the page before");
|
||||
}
|
||||
|
||||
/// Signed, invisible, other-page and unplaced fields get no tab. Each case is checked on its
|
||||
/// own, so a failure names every case that wrongly got one.
|
||||
#[test]
|
||||
fn sign_tabs_skip_signed_invisible_other_page_and_unplaced_fields() {
|
||||
let form = || vec![field("Approver", 0, RECT)];
|
||||
let cases = [
|
||||
("signed", SignatureInfo { signed: true, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
("invisible", SignatureInfo { visible: false, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
("on another page", listing("Approver", 1, RECT), vec![field("Approver", 1, RECT)], true),
|
||||
("on no page", SignatureInfo { page: None, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
("without a rectangle", SignatureInfo { rect: None, ..listing("Approver", 0, RECT) }, form(), true),
|
||||
];
|
||||
assert_eq!(tabbed(&cases), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
/// NaN, infinite and gigantic rectangles never reach the painter, even when the form's
|
||||
/// widget carries the same numbers.
|
||||
#[test]
|
||||
fn sign_tabs_skip_rectangles_that_cannot_reach_the_screen() {
|
||||
let hostile = |name: &'static str, rect: [f64; 4]| (name, listing("Approver", 0, rect), vec![field("Approver", 0, rect)], true);
|
||||
let cases = [
|
||||
hostile("NaN", [f64::NAN, 110.0, 140.0, 180.0]),
|
||||
hostile("infinite", [20.0, f64::INFINITY, 140.0, 180.0]),
|
||||
hostile("minus infinite", [20.0, 110.0, f64::NEG_INFINITY, 180.0]),
|
||||
hostile("huge", [20.0, 110.0, 1e300, 180.0]),
|
||||
];
|
||||
assert_eq!(tabbed(&cases), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
/// Fields a click would not sign get no tab: a read-only field, a document that refuses
|
||||
/// filling, a listing with no form field of its name, a field of another kind of that name,
|
||||
/// and a widget that is hidden, read-only on its own or elsewhere.
|
||||
#[test]
|
||||
fn sign_tabs_skip_fields_that_a_click_cannot_sign() {
|
||||
let empty = || listing("Approver", 0, RECT);
|
||||
let with = |change: fn(&mut FormField)| {
|
||||
let mut f = field("Approver", 0, RECT);
|
||||
change(&mut f);
|
||||
vec![f]
|
||||
};
|
||||
let cases = [
|
||||
("read-only", empty(), with(|f| f.flags = pdfcraft_engine::field_flags::READ_ONLY), true),
|
||||
("filling refused", empty(), with(|_| {}), false),
|
||||
("no form field", empty(), Vec::new(), true),
|
||||
("another kind", empty(), with(|f| f.kind = FormFieldKind::Text), true),
|
||||
("hidden widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.hidden = true)), true),
|
||||
("read-only widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.read_only = true)), true),
|
||||
("widget elsewhere", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.rect = [160.0, 110.0, 280.0, 180.0])), true),
|
||||
];
|
||||
assert_eq!(tabbed(&cases), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
/// Whether two layout sizes match, to a hundredth of a point.
|
||||
fn near(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < 0.01
|
||||
}
|
||||
|
||||
/// What a field `width` by `height` points on screen shows, for a label 30 pt wide on the
|
||||
/// largest tab: "label" (the full tab), "icon" (the square chip) or "none".
|
||||
fn shows(width: f32, height: f32) -> &'static str {
|
||||
match sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(width, height)), 30.0) {
|
||||
Some(tab) if tab.label.is_some() => "label",
|
||||
Some(_) => "icon",
|
||||
None => "none",
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab is 0.4 of the field's height on screen, at most 18 pt: a tall, wide field gets the
|
||||
/// 18 pt tab with its label 3 pt inside the corner, and a 29 pt field (a 22 pt box at fit
|
||||
/// width) an 11.6 pt icon chip, too small for the label, with the inset and icon scaled to it.
|
||||
#[test]
|
||||
fn sign_tab_layout_scales_the_chip_with_the_field_height() {
|
||||
let large = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 60.0));
|
||||
let tab = sign_tab_layout(large, 30.0).expect("fits");
|
||||
assert!(near(tab.rect.height(), 18.0) && tab.rect.min == large.min + vec2(3.0, 3.0), "{tab:?}");
|
||||
assert!(near(tab.icon.width(), 12.0) && tab.rect.contains_rect(tab.icon), "{tab:?}");
|
||||
let at = tab.label.expect("the label fits");
|
||||
assert!(at.x >= tab.icon.right() && at.x + 30.0 <= tab.rect.right() && at.y == tab.rect.center().y, "{tab:?}");
|
||||
|
||||
let short = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 29.0));
|
||||
let tab = sign_tab_layout(short, 30.0).expect("fits");
|
||||
assert!(near(tab.rect.height(), 11.6) && near(tab.rect.width(), 11.6) && tab.label.is_none(), "{tab:?}");
|
||||
let inset = tab.rect.min - short.min;
|
||||
assert!(near(inset.x, 11.6 / 6.0) && near(inset.y, 11.6 / 6.0) && short.contains_rect(tab.rect), "{tab:?}");
|
||||
assert!(near(tab.icon.width(), 11.6 * 2.0 / 3.0) && tab.rect.contains_rect(tab.icon), "{tab:?}");
|
||||
}
|
||||
|
||||
/// A 19 pt field (a 14 pt box at fit width) still gets the smallest chip, 10 pt with the icon
|
||||
/// alone. A 12 pt field is too short for even that, and a rectangle that isn't finite gets
|
||||
/// nothing. A label that can't be measured is left out instead of drawn at a NaN position.
|
||||
#[test]
|
||||
fn sign_tab_layout_keeps_a_small_icon_on_short_fields_and_none_below() {
|
||||
let field = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 19.0));
|
||||
let tab = sign_tab_layout(field, 30.0).expect("the smallest chip fits");
|
||||
assert!(near(tab.rect.height(), 10.0) && near(tab.rect.width(), 10.0) && tab.label.is_none(), "{tab:?}");
|
||||
assert!(field.contains_rect(tab.rect) && tab.rect.contains_rect(tab.icon), "{tab:?}");
|
||||
let cases = [
|
||||
("12 pt tall", Rect::from_min_size(Pos2::ZERO, vec2(400.0, 12.0))),
|
||||
("infinite", Rect::from_min_max(Pos2::ZERO, pos2(f32::INFINITY, 40.0))),
|
||||
("NaN", Rect::from_min_max(pos2(f32::NAN, 0.0), pos2(400.0, 40.0))),
|
||||
];
|
||||
let laid_out: Vec<&str> = cases.iter().filter(|(_, r)| sign_tab_layout(*r, 30.0).is_some()).map(|c| c.0).collect();
|
||||
assert_eq!(laid_out, Vec::<&str>::new());
|
||||
let roomy = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0));
|
||||
assert_eq!(sign_tab_layout(roomy, f32::NAN).map(|t| t.label), Some(None));
|
||||
}
|
||||
|
||||
/// The label's font and the chip's corners shrink with the tab: 11 pt and 4 pt on the largest
|
||||
/// tab, 8.8 pt and 3.2 pt on the 14.4 pt tab of a 36 pt field.
|
||||
#[test]
|
||||
fn sign_tab_layout_scales_the_label_font_and_corners_with_the_chip() {
|
||||
let large = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0)), 30.0).expect("fits");
|
||||
assert!(near(large.font, 11.0) && near(large.radius, 4.0), "{large:?}");
|
||||
let small = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 36.0)), 30.0).expect("fits");
|
||||
assert!(near(small.font, 8.8) && near(small.radius, 3.2) && small.label.is_some(), "{small:?}");
|
||||
}
|
||||
|
||||
/// As a 36 pt field (a 14.4 pt tab, its label 24 pt wide at that size) narrows, the tab keeps
|
||||
/// its label while the whole tab fits in half the width (91.2 pt), then shows the icon alone
|
||||
/// while the chip does (28.8 pt), then nothing.
|
||||
#[test]
|
||||
fn sign_tab_layout_drops_the_label_then_the_tab_as_the_field_narrows() {
|
||||
let widths = [400.0, 92.0, 90.0, 29.0, 28.0];
|
||||
assert_eq!(widths.map(|w| shows(w, 36.0)), ["label", "label", "icon", "icon", "none"]);
|
||||
let tab = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(92.0, 36.0)), 30.0).expect("fits");
|
||||
assert!(near(tab.rect.height(), 14.4) && tab.rect.width() <= 46.0, "{tab:?}");
|
||||
}
|
||||
|
||||
/// A field that straddles the page's edge gets its tab in the part on the page, where clicks
|
||||
/// reach it, or none when that part has no room for one.
|
||||
#[test]
|
||||
fn a_sign_tab_stays_on_the_page() {
|
||||
let page = Rect::from_min_size(pos2(100.0, 50.0), vec2(600.0, 800.0));
|
||||
let straddling = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 90.0));
|
||||
let tab = sign_tab_on_page(straddling, page, 30.0).expect("the part on the page has room");
|
||||
assert!(page.contains_rect(tab.rect), "{tab:?} on {page:?}");
|
||||
assert_eq!(tab.rect.height(), SIGN_TAB_MAX, "sized to the 60 px on the page");
|
||||
let sliver = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 36.0));
|
||||
assert_eq!(sign_tab_on_page(sliver, page, 30.0), None, "6 px on the page");
|
||||
let off = Rect::from_min_size(pos2(60.0, 900.0), vec2(300.0, 90.0));
|
||||
assert_eq!(sign_tab_on_page(off, page, 30.0), None, "wholly off the page");
|
||||
}
|
||||
|
||||
/// Where two sign tabs overlap, a click takes the one painted last, which is on top.
|
||||
#[test]
|
||||
fn the_sign_tab_painted_last_takes_the_click() {
|
||||
let tab = |x: f32| sign_tab_layout(Rect::from_min_size(pos2(x, 0.0), vec2(300.0, 60.0)), 30.0).expect("fits");
|
||||
let tabs = [("Approver", tab(0.0)), ("Witness", tab(10.0))];
|
||||
let both = tabs[1].1.rect.left_center() + vec2(2.0, 0.0);
|
||||
assert!(tabs[0].1.rect.contains(both), "the tabs overlap there");
|
||||
assert_eq!(crate::forms_ui::tab_under(&tabs, both), Some("Witness"));
|
||||
assert_eq!(crate::forms_ui::tab_under(&tabs, tabs[0].1.rect.left_center() + vec2(2.0, 0.0)), Some("Approver"));
|
||||
assert_eq!(crate::forms_ui::tab_under(&tabs, pos2(-5.0, -5.0)), None);
|
||||
}
|
||||
|
||||
/// One page with three signature fields: Approver is empty, Witness is signed (a signature
|
||||
/// dictionary as its value is enough to list it as signed) and Locked is empty but read-only.
|
||||
const SIGN_FIELDS: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R 6 0 R] >> endobj
|
||||
4 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Approver) /Rect [20 110 140 180] /P 3 0 R /F 4 >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Witness) /V << /Type /Sig >> /Rect [160 110 280 180] /P 3 0 R /F 4 >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Locked) /Ff 1 /Rect [20 20 140 90] /P 3 0 R /F 4 >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// Every shape painted in the last frame, with nested lists flattened.
|
||||
fn painted(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec<egui::Shape> {
|
||||
let mut stack: Vec<egui::Shape> = h.output().shapes.iter().map(|c| c.shape.clone()).collect();
|
||||
let mut out = Vec::new();
|
||||
while let Some(shape) = stack.pop() {
|
||||
match shape {
|
||||
egui::Shape::Vec(inner) => stack.extend(inner),
|
||||
shape => out.push(shape),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where the named field's first widget is on screen.
|
||||
fn field_on_screen(h: &egui_kittest::Harness<'static, PdfCraftApp>, name: &str) -> Rect {
|
||||
let app = h.state();
|
||||
let view = &app.views[0];
|
||||
let doc = app.session.get(view.id).expect("open");
|
||||
let f = doc.form.iter().find(|f| f.name == name).expect("field");
|
||||
crate::forms_ui::field_screen_rect(view, &doc.info, f, 0).expect("on screen")
|
||||
}
|
||||
|
||||
/// One page where the text field Name, first in the form's order, covers the top-left corner
|
||||
/// of the empty signature field Approver, where its sign tab is drawn.
|
||||
const SIGN_UNDER_TEXT: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R] >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R] >> endobj
|
||||
4 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (Name) /Rect [10 120 130 190] /P 3 0 R /F 4 >> endobj
|
||||
5 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Approver) /Rect [20 110 140 180] /P 3 0 R /F 4 >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF";
|
||||
|
||||
/// The real shell with `bytes` open, the side panes closed, after the first frames.
|
||||
fn shell(bytes: &'static [u8]) -> egui_kittest::Harness<'static, PdfCraftApp> {
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("sign-fields.pdf", None, bytes.to_vec()).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("panel", "none").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(6);
|
||||
h
|
||||
}
|
||||
|
||||
/// The accent chips painted in the last frame: the sign tabs.
|
||||
fn chips(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec<Rect> {
|
||||
let accent = Tokens::get(&h.ctx).accent;
|
||||
painted(h)
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Rect(r) if r.fill == accent => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Clicks at `at` and lets the shell answer.
|
||||
fn click_at(h: &mut egui_kittest::Harness<'static, PdfCraftApp>, at: Pos2) {
|
||||
h.drag_at(at);
|
||||
h.run_steps(1);
|
||||
h.drop_at(at);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// In the real shell, an empty signature field shows its accent tab with "Sign" in its
|
||||
/// top-left corner, and the signed and read-only fields show none. The tab is part of the
|
||||
/// field: hovering it shows the pointing hand, and clicking it starts signing that field.
|
||||
#[test]
|
||||
fn empty_signature_fields_show_a_sign_tab_that_signs_them() {
|
||||
let mut h = shell(SIGN_FIELDS);
|
||||
let (shapes, chips) = (painted(&h), chips(&h));
|
||||
let (approver, witness, locked) = (field_on_screen(&h, "Approver"), field_on_screen(&h, "Witness"), field_on_screen(&h, "Locked"));
|
||||
let tab = chips.iter().copied().find(|c| approver.contains_rect(*c)).unwrap_or_else(|| panic!("no tab in {approver:?}: {chips:?}"));
|
||||
assert!(tab.min.x - approver.min.x < 8.0 && tab.min.y - approver.min.y < 8.0, "in the top-left corner: {tab:?} in {approver:?}");
|
||||
let label = shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == "Sign" && tab.contains(t.pos)));
|
||||
assert!(label, "the tab says Sign");
|
||||
assert!(!chips.iter().any(|c| witness.intersects(*c)), "a signed field has no tab: {chips:?}");
|
||||
assert!(!chips.iter().any(|c| locked.intersects(*c)), "a read-only field has no tab: {chips:?}");
|
||||
|
||||
h.hover_at(tab.center());
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand);
|
||||
click_at(&mut h, tab.center());
|
||||
assert_eq!(h.state().dialog, Some(crate::Dialog::Sign));
|
||||
assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver"));
|
||||
}
|
||||
|
||||
/// A sign tab is drawn over every field, so a click on it signs its field even where a field
|
||||
/// earlier in the form's order overlaps it, which would otherwise take the click. Beside the
|
||||
/// tab, the overlapping field still takes clicks as before.
|
||||
#[test]
|
||||
fn a_sign_tab_signs_its_field_where_an_earlier_field_overlaps_it() {
|
||||
let mut h = shell(SIGN_UNDER_TEXT);
|
||||
let (name, approver) = (field_on_screen(&h, "Name"), field_on_screen(&h, "Approver"));
|
||||
let tab = chips(&h).into_iter().find(|c| approver.contains_rect(*c)).expect("Approver has a tab");
|
||||
assert!(name.contains_rect(tab), "the text field covers the tab: {tab:?} in {name:?}");
|
||||
|
||||
h.hover_at(tab.center());
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand);
|
||||
click_at(&mut h, tab.center());
|
||||
assert_eq!(h.state().dialog, Some(crate::Dialog::Sign));
|
||||
assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver"));
|
||||
assert!(h.state().views[0].forms.focus.is_none(), "the text field didn't open");
|
||||
|
||||
let beside = pos2(tab.right() + 6.0, tab.center().y);
|
||||
assert!(name.contains(beside) && approver.contains(beside), "beside the tab, both fields are under the pointer");
|
||||
h.state_mut().dialog = None;
|
||||
h.state_mut().sign_draft = None;
|
||||
h.run_steps(1);
|
||||
click_at(&mut h, beside);
|
||||
assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.name.as_str()), Some("Name"), "the earlier field takes the click");
|
||||
}
|
||||
@@ -128,6 +128,19 @@ impl PageXform {
|
||||
Rect::from_two_pos(self.norm_to_screen(a.0, a.1), self.norm_to_screen(b.0, b.1))
|
||||
}
|
||||
|
||||
/// Whether the screen point `p` activates link `l` on `page`: inside one of its
|
||||
/// `/QuadPoints` quadrilaterals, or its rectangle when it has none (ISO 32000-2 Table 176).
|
||||
pub fn link_contains(&self, info: &DocInfo, page: usize, l: &pdfcraft_render::Link, p: Pos2) -> bool {
|
||||
if l.quads.is_empty() {
|
||||
return self.user_rect(info, page, l.rect).contains(p);
|
||||
}
|
||||
// The inverse of `user_rect`: screen → the displayed page's fraction → user space.
|
||||
let Some(pg) = info.pages.get(page) else { return false };
|
||||
let (u, v) = self.screen_to_norm(p);
|
||||
let [x, y] = pg.view_to_user(u * pg.width, v * pg.height);
|
||||
l.contains(x, y)
|
||||
}
|
||||
|
||||
pub fn user_rect_f64(&self, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect {
|
||||
self.user_rect(info, page, r.map(|v| v as f32))
|
||||
}
|
||||
|
||||
@@ -1885,6 +1885,15 @@ fn finish_redactions_and_fields(app: &mut PdfCraftApp, req: &mut Pending) {
|
||||
Some(Dialog::RedactApply) => {
|
||||
let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks());
|
||||
if app.apply_edit(Edit::ApplyRedactions { pages: None }) {
|
||||
if let Some(view) = app.active.and_then(|i| app.views.get_mut(i)) {
|
||||
let delivered_undone = view.redactions_applied < view.redactions_downloaded;
|
||||
view.redactions_applied = view.redactions_applied.saturating_add(1);
|
||||
// A new step clears the redo history, so the undone saved steps can't come back.
|
||||
if view.redactions_undone_after_save > 0 || delivered_undone {
|
||||
view.redactions_undone_after_save = 0;
|
||||
view.saved_redactions_cut_off = true;
|
||||
}
|
||||
}
|
||||
if let Some((_, id)) = app.active_ids() {
|
||||
app.renew_recovery(id);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use save::{SaveTarget, write_atomically};
|
||||
#[cfg(test)]
|
||||
pub(crate) use save::{is_mail_temp_copy, save_dialog_folder};
|
||||
#[cfg(test)]
|
||||
use save::{write_atomically_syncing, write_atomically_with};
|
||||
use save::{unredacted_file_name, write_atomically_syncing, write_atomically_with};
|
||||
|
||||
/// Text typed into a new text box that isn't added to the page yet.
|
||||
fn new_text_typed(v: &crate::DocView) -> bool {
|
||||
@@ -380,6 +380,17 @@ impl PdfCraftApp {
|
||||
view.comments.selected = None;
|
||||
view.comments.history_stepped();
|
||||
}
|
||||
if label == (Edit::ApplyRedactions { pages: None }).label() {
|
||||
let view = &mut self.views[i];
|
||||
let (applied, undone) = (view.redactions_applied, view.redactions_undone_after_save);
|
||||
// Undo past the last save counts as undone; Redo first takes those back.
|
||||
match (undo, applied, undone) {
|
||||
(true, 0, _) => view.redactions_undone_after_save = undone.saturating_add(1),
|
||||
(true, _, _) => view.redactions_applied = applied.saturating_sub(1),
|
||||
(false, _, 0) => view.redactions_applied = applied.saturating_add(1),
|
||||
(false, _, _) => view.redactions_undone_after_save = undone.saturating_sub(1),
|
||||
}
|
||||
}
|
||||
let label = crate::i18n::edit_label(&label);
|
||||
if undo {
|
||||
self.notify_fmt("Undid {label}", &[("label", &label)]);
|
||||
@@ -1201,9 +1212,11 @@ mod revert_draft_tests {
|
||||
use crate::forms_ui::Focus;
|
||||
use pdfcraft_engine::FieldValue;
|
||||
|
||||
/// An open editor on the first widget of the field "name", holding `text` as typed.
|
||||
fn focus(text: &str) -> Focus {
|
||||
Focus {
|
||||
name: "name".into(),
|
||||
obj: None,
|
||||
widget: 0,
|
||||
text: text.into(),
|
||||
picked: Vec::new(),
|
||||
@@ -1213,6 +1226,7 @@ mod revert_draft_tests {
|
||||
calendar: None,
|
||||
calendar_rect: None,
|
||||
calendar_text: None,
|
||||
list: Default::default(),
|
||||
had_focus: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,11 @@ impl PdfCraftApp {
|
||||
view.forms.committed = None;
|
||||
view.forms.unbaked.clear();
|
||||
view.pending_edit = None;
|
||||
// The redactions applied since the last save are discarded too. Those in the
|
||||
// last web download stay, so later downloads keep the `_Redacted` name.
|
||||
view.redactions_applied = view.redactions_downloaded;
|
||||
view.redactions_undone_after_save = 0;
|
||||
view.saved_redactions_cut_off = false;
|
||||
}
|
||||
self.notify_tr("Reverted to the last saved version");
|
||||
}
|
||||
|
||||
@@ -50,6 +50,21 @@ impl PdfCraftApp {
|
||||
let Some(id) = self.views.get(index).map(|v| v.id) else { return false };
|
||||
let Some(doc) = self.session.get(id) else { return false };
|
||||
let (name, path) = (doc.name.clone(), doc.path.clone());
|
||||
// After Apply redactions, Save asks where and proposes the name with `_Redacted`.
|
||||
// In the web build a delivered step stays counted, so only the steps applied since the
|
||||
// last delivery make Save ask where.
|
||||
let redacted = self.views.get(index).is_some_and(|v| v.redactions_applied > 0);
|
||||
let not_delivered = self.views.get(index).is_some_and(|v| v.redactions_applied > v.redactions_downloaded);
|
||||
let name = if redacted { pdfcraft_engine::redacted_file_name(&name) } else { name };
|
||||
// Undo past a saved Apply redactions brings back content that the file on disk has
|
||||
// redacted: ask where instead of writing it over that file. In the web build a delivered
|
||||
// step stays counted in `redactions_applied`, so fewer steps than were delivered means one
|
||||
// was undone.
|
||||
let unredacted = self.views.get(index).is_some_and(restores_saved_redactions);
|
||||
// The restored content is not a redacted copy: propose the name without `_Redacted`, so
|
||||
// the dialog's default is not the redacted file.
|
||||
let name = if unredacted && !redacted { unredacted_file_name(&name) } else { name };
|
||||
let target = if not_delivered || unredacted { SaveTarget::As } else { target };
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let doc_path = path.clone();
|
||||
@@ -66,6 +81,14 @@ impl PdfCraftApp {
|
||||
let dialog = in_document_folder(dialog, doc_path.as_deref());
|
||||
// The bytes are taken once the user has chosen, so edits made meanwhile are saved too.
|
||||
self.ask_one(crate::pickers::Ask::Save(dialog), None, move |app, dest| {
|
||||
// An Apply redactions or an Undo of one while the dialog was open makes the
|
||||
// name it proposed wrong: ask again with the name for the current content.
|
||||
let asked = (redacted, unredacted);
|
||||
let changed = |v: &crate::DocView| v.id == id && (v.redactions_applied > 0, restores_saved_redactions(v)) != asked;
|
||||
if let Some(index) = app.views.iter().position(changed) {
|
||||
app.save_then(index, SaveTarget::As, after);
|
||||
return;
|
||||
}
|
||||
app.save_doc_to_then(id, &dest.to_string_lossy(), target, Box::new(after));
|
||||
});
|
||||
return false;
|
||||
@@ -100,6 +123,9 @@ impl PdfCraftApp {
|
||||
&& let Some(view) = self.views.get_mut(index)
|
||||
{
|
||||
view.document_changed(&doc.info);
|
||||
// `redactions_applied` stays set: the document keeps its name here, so
|
||||
// later downloads are named after the redacted copy too.
|
||||
view.redactions_downloaded = view.redactions_applied;
|
||||
}
|
||||
// The host reports where the file went (and any failure) itself.
|
||||
if !to_host {
|
||||
@@ -206,6 +232,9 @@ impl PdfCraftApp {
|
||||
// Saving over a version that changed on disk keeps this one: nothing to ask.
|
||||
for view in self.views.iter_mut().filter(|v| v.id == id) {
|
||||
view.disk_changed = false;
|
||||
view.redactions_applied = 0;
|
||||
view.redactions_undone_after_save = 0;
|
||||
view.saved_redactions_cut_off = false;
|
||||
}
|
||||
self.notify_fmt("Saved {name}", &[("name", &short_name(dest))]);
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -244,6 +273,27 @@ pub(crate) fn is_mail_temp_copy(path: &str) -> bool {
|
||||
|| p.contains("/library/containers/com.apple.mail/data/library/mail downloads/")
|
||||
}
|
||||
|
||||
/// Whether `view` holds content that a saved or delivered Apply redactions removed: a saved step
|
||||
/// is undone, cannot be redone, or (in the web build) fewer steps are in effect than were
|
||||
/// delivered.
|
||||
fn restores_saved_redactions(view: &crate::DocView) -> bool {
|
||||
view.redactions_undone_after_save > 0 || view.saved_redactions_cut_off || view.redactions_applied < view.redactions_downloaded
|
||||
}
|
||||
|
||||
/// `name` without the `_Redacted` that [`pdfcraft_engine::redacted_file_name`] adds before the
|
||||
/// extension ("contract_Redacted.pdf" gives "contract.pdf"). Any other name is returned as it is.
|
||||
pub(crate) fn unredacted_file_name(name: &str) -> String {
|
||||
let cut = name.len().saturating_sub(4);
|
||||
let (stem, ext) = match (name.get(..cut), name.get(cut..)) {
|
||||
(Some(stem), Some(ext)) if ext.eq_ignore_ascii_case(".pdf") => (stem, ext),
|
||||
_ => (name, ""),
|
||||
};
|
||||
match stem.strip_suffix("_Redacted") {
|
||||
Some(base) if !base.is_empty() => format!("{base}{ext}"),
|
||||
_ => name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a Save As style dialog should open in for a document stored at `path`: the
|
||||
/// document's own folder, as Acrobat and Foxit do, instead of whichever folder the system picks.
|
||||
/// `None` (keep the system's choice) for a new document, a path with no parent, or an email
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
use super::{SaveTarget, is_mail_temp_copy, save_dialog_folder, write_atomically, write_atomically_syncing, write_atomically_with};
|
||||
use super::{
|
||||
SaveTarget, is_mail_temp_copy, save_dialog_folder, unredacted_file_name, write_atomically, write_atomically_syncing, write_atomically_with,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn restored_content_is_not_proposed_under_the_redacted_name() {
|
||||
assert_eq!(unredacted_file_name("contract_Redacted.pdf"), "contract.pdf");
|
||||
assert_eq!(unredacted_file_name("SCAN_Redacted.PDF"), "SCAN.PDF");
|
||||
assert_eq!(unredacted_file_name("Untitled_Redacted"), "Untitled");
|
||||
assert_eq!(unredacted_file_name("contract.pdf"), "contract.pdf");
|
||||
assert_eq!(unredacted_file_name("_Redacted.pdf"), "_Redacted.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_dialogs_open_in_the_documents_folder() {
|
||||
|
||||
@@ -10,13 +10,13 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Stroke, vec2};
|
||||
use pdfcraft_cos::ObjRef;
|
||||
use pdfcraft_engine::{Edit, FieldValue, FormField, FormFieldKind, FormWidget, field_flags, form_appearance};
|
||||
use pdfcraft_render::DocInfo;
|
||||
|
||||
use crate::canvas::{DocView, PageToolContext, PageXform};
|
||||
use crate::canvas::{DocView, PageToolContext, PageXform, SignTab};
|
||||
use crate::page_cursor::Layer;
|
||||
use crate::page_router::{Hit, Owner, PagePress};
|
||||
use crate::theme::Tokens;
|
||||
|
||||
const FOCUS_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);
|
||||
/// Background of the in-place text field editor, the same in every theme.
|
||||
@@ -26,6 +26,10 @@ const FIELD_FILL: Color32 = Color32::from_rgb(0xFF, 0xFF, 0xF4);
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Focus {
|
||||
pub name: String,
|
||||
/// The focused field's object. Same-name twins are one field (ISO 32000-2 §12.7.3.1) but come
|
||||
/// as separate fields here, each with its own widgets and option order, and this says which
|
||||
/// one has the focus. `None` goes by the name: the first field with it.
|
||||
pub obj: Option<ObjRef>,
|
||||
/// Which of the field's widgets (a field can appear on several pages).
|
||||
pub widget: usize,
|
||||
/// Text being typed (text fields).
|
||||
@@ -44,11 +48,30 @@ pub struct Focus {
|
||||
/// The text the calendar last saw, so it moves to a typed date once, when the typing becomes
|
||||
/// a whole date, and otherwise keeps the month its arrows turned to.
|
||||
pub calendar_text: Option<String>,
|
||||
/// Drop-downs: where the open list is scrolled to and which item is current.
|
||||
pub list: ChoiceList,
|
||||
/// Whether the text box had the keyboard at the end of the editor's last frame
|
||||
/// ([`crate::edit_text_ui::lost_focus_once`]).
|
||||
pub(crate) had_focus: bool,
|
||||
}
|
||||
|
||||
/// A drop-down's open list: the first item shown, the item the keys or the pointer are on, and
|
||||
/// where on the scroll bar's thumb a drag took hold.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct ChoiceList {
|
||||
pub first: usize,
|
||||
pub current: Option<usize>,
|
||||
pub grab: Option<f32>,
|
||||
/// Wheel movement not yet a whole row.
|
||||
pub wheel: f32,
|
||||
/// Where the pointer was last frame: only a pointer that moves makes the item under it
|
||||
/// current, so a resting one keeps no claim on the highlight when the keys scroll the list
|
||||
/// beneath it.
|
||||
pub pointer_at: Option<egui::Pos2>,
|
||||
/// Set on the first frame, from the field's value.
|
||||
pub placed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FormView {
|
||||
pub focus: Option<Focus>,
|
||||
@@ -73,6 +96,10 @@ pub struct FormView {
|
||||
/// The widget holding egui's keyboard focus for the focused check box or radio button, and
|
||||
/// whether it takes the arrows (radio buttons). The page keys still work around it.
|
||||
pub(crate) keys: Option<(egui::Id, bool)>,
|
||||
/// The list box row clicked last, without Shift: (its field name, the row). A Shift-click picks
|
||||
/// the rows from it to the one clicked; the field's value can't say which row came last when
|
||||
/// rows share an export value, and `/I` lists them in ascending order.
|
||||
pub(crate) list_anchor: Option<(String, usize)>,
|
||||
}
|
||||
|
||||
/// A form message for the app to show, with document data kept separate so the visible
|
||||
@@ -145,9 +172,40 @@ pub(crate) fn draft_text(f: &FormField) -> String {
|
||||
value
|
||||
}
|
||||
|
||||
impl Focus {
|
||||
/// Whether this is the focus of widget `widget` of `f` (of that twin, for same-name fields).
|
||||
fn is_on(&self, f: &FormField, widget: usize) -> bool {
|
||||
self.name == f.name && self.widget == widget && self.obj.is_none_or(|o| o == f.obj)
|
||||
}
|
||||
}
|
||||
|
||||
/// The field `focus` is on: the twin with its field object, or else the first field with its name.
|
||||
pub(crate) fn focused_field<'a>(focus: &Focus, form: &'a [FormField]) -> Option<&'a FormField> {
|
||||
focus.obj.and_then(|o| form.iter().find(|f| f.obj == o && f.name == focus.name)).or_else(|| form.iter().find(|f| f.name == focus.name))
|
||||
}
|
||||
|
||||
/// The edit picking the options at `picked` (positions in `f`'s options) in the list box `f`.
|
||||
/// The edit names the field, and positions are read in the first field of that name: a same-name
|
||||
/// twin listing its options in another order gives its picks as positions there. One option
|
||||
/// missing there goes by export value.
|
||||
fn list_pick_edit(form: &[FormField], f: &FormField, picked: Vec<usize>) -> Edit {
|
||||
let first = form.iter().find(|x| x.name == f.name).filter(|x| x.obj != f.obj);
|
||||
let value = match first {
|
||||
None => FieldValue::ChoiceIndices(picked),
|
||||
Some(first) => match f.positions_in(first, &picked) {
|
||||
Some(there) => FieldValue::ChoiceIndices(there),
|
||||
None => FieldValue::Choice(picked.iter().filter_map(|&i| f.options.get(i)).map(|(e, _)| e.clone()).collect()),
|
||||
},
|
||||
};
|
||||
Edit::SetFieldValue { name: f.name.clone(), value }
|
||||
}
|
||||
|
||||
/// Editor state for opening widget `widget` of `f`: it starts from the field's value, asks
|
||||
/// for keyboard focus, and gives a drop-down a fresh list that places itself from that value.
|
||||
fn open_focus(f: &FormField, widget: usize) -> Focus {
|
||||
Focus {
|
||||
name: f.name.clone(),
|
||||
obj: Some(f.obj),
|
||||
widget,
|
||||
text: draft_text(f),
|
||||
picked: f.value.clone(),
|
||||
@@ -157,6 +215,7 @@ fn open_focus(f: &FormField, widget: usize) -> Focus {
|
||||
calendar: None,
|
||||
calendar_rect: None,
|
||||
calendar_text: None,
|
||||
list: ChoiceList::default(),
|
||||
had_focus: false,
|
||||
}
|
||||
}
|
||||
@@ -173,8 +232,16 @@ fn select_edit(f: &FormField, wi: usize) -> Option<Edit> {
|
||||
|
||||
/// What clicking widget `wi` of a check box or radio button does.
|
||||
fn toggle_edit(f: &FormField, wi: usize) -> Option<Edit> {
|
||||
let w = f.widgets.get(wi)?;
|
||||
let value = match f.kind {
|
||||
FormFieldKind::CheckBox => FieldValue::Check(f.value.is_empty()),
|
||||
// A check box's kids can have different on states (ISO 32000-2 §12.7.5.2.3, Table 230):
|
||||
// clicking one that is off turns on its state (it, and any kid sharing that state, on;
|
||||
// the others off); clicking one that is on turns the field off.
|
||||
FormFieldKind::CheckBox => match &w.on_state {
|
||||
Some(s) if !f.widget_on(wi) => FieldValue::Text(s.clone()),
|
||||
Some(_) => FieldValue::Check(false),
|
||||
None => FieldValue::Check(f.value.is_empty()),
|
||||
},
|
||||
// Clicking the selected button again turns it off unless the group forbids it
|
||||
// (NoToggleToOff, Table 229).
|
||||
FormFieldKind::Radio if f.widget_on(wi) => {
|
||||
@@ -189,6 +256,17 @@ fn toggle_edit(f: &FormField, wi: usize) -> Option<Edit> {
|
||||
Some(Edit::SetFieldValue { name: f.name.clone(), value })
|
||||
}
|
||||
|
||||
/// The first shown widget of `f` on `page` under the pointer at `p`, with its index.
|
||||
fn widget_at<'a>(xf: &PageXform, info: &DocInfo, page: usize, f: &'a FormField, p: egui::Pos2) -> Option<(usize, &'a FormWidget)> {
|
||||
f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && !w.hidden && widget_rect(xf, info, page, w.rect).contains(p))
|
||||
}
|
||||
|
||||
/// The field whose sign tab is under `p`, of `tabs` in the order they are painted: where tabs
|
||||
/// overlap, the one painted last is on top.
|
||||
pub(crate) fn tab_under<'a>(tabs: &[(&'a str, SignTab)], p: egui::Pos2) -> Option<&'a str> {
|
||||
tabs.iter().rev().find(|(_, tab)| tab.rect.contains(p)).map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
/// Whether `w`, a widget of `f`, takes a press: fillable, a push button with an action, or an
|
||||
/// empty signature field (signed by clicking it, Use a certificate). A radio button of a group can
|
||||
/// be read-only on its own.
|
||||
@@ -198,19 +276,22 @@ fn usable(f: &FormField, w: &FormWidget, allowed: bool) -> bool {
|
||||
}
|
||||
|
||||
/// The form widget under `p` on `page`: the one hit test of the fields, for the cursor and the
|
||||
/// press. Over the page's text too: a check box drawn with a glyph, or set on printed text, is a
|
||||
/// button, not text to select.
|
||||
pub(crate) fn hit(xf: &PageXform, info: &DocInfo, page: usize, form: &[FormField], allowed: bool, p: Pos2) -> Option<Hit> {
|
||||
/// press. It is the first widget under the pointer in the form's order, except on a sign tab
|
||||
/// (`tabs`, with the signature field each one signs), which is drawn over every field and so is
|
||||
/// on its own field. Over the page's text too: a check box drawn with a glyph, or set on printed
|
||||
/// text, is a button, not text to select.
|
||||
pub(crate) fn hit(xf: &PageXform, info: &DocInfo, page: usize, form: &[FormField], tabs: &[(&str, SignTab)], allowed: bool, p: Pos2) -> Option<Hit> {
|
||||
if !xf.rect.contains(p) {
|
||||
return None;
|
||||
}
|
||||
let (field, f, widget, w) = form.iter().enumerate().find_map(|(fi, f)| {
|
||||
f.widgets
|
||||
.iter()
|
||||
let under = |only: Option<&str>| {
|
||||
form.iter()
|
||||
.enumerate()
|
||||
.find(|(_, w)| w.page == Some(page) && !w.hidden && widget_rect(xf, info, page, w.rect).contains(p))
|
||||
.map(|(wi, w)| (fi, f, wi, w))
|
||||
})?;
|
||||
.filter(|(_, f)| only.is_none_or(|name| f.name == name && f.kind == FormFieldKind::Signature))
|
||||
.find_map(|(fi, f)| widget_at(xf, info, page, f, p).map(|(wi, w)| (fi, f, wi, w)))
|
||||
};
|
||||
// A tab lies inside its field's widget, so that widget is under the pointer too.
|
||||
let (field, f, widget, w) = tab_under(tabs, p).and_then(|name| under(Some(name))).or_else(|| under(None))?;
|
||||
let icon = match (usable(f, w, allowed), f.kind) {
|
||||
(false, _) => egui::CursorIcon::NotAllowed,
|
||||
(true, FormFieldKind::Text) => egui::CursorIcon::Text,
|
||||
@@ -250,7 +331,7 @@ pub(crate) fn page_input(
|
||||
if f.kind == FormFieldKind::Text
|
||||
&& usable
|
||||
&& let Some(at) = ptr.pressed()
|
||||
&& view.forms.focus.as_ref().is_none_or(|x| x.name != f.name || x.widget != wi)
|
||||
&& view.forms.focus.as_ref().is_none_or(|x| !x.is_on(f, wi))
|
||||
{
|
||||
commit(view, form);
|
||||
view.forms.focus = Some(Focus { press: Some(at), ..open_focus(f, wi) });
|
||||
@@ -275,7 +356,7 @@ pub(crate) fn page_input(
|
||||
FormFieldKind::CheckBox | FormFieldKind::Radio => {
|
||||
// The box takes the focus, as in Acrobat, so Tab goes on from it (#2223). The overlay
|
||||
// toggles it, after the edit for any text this commits.
|
||||
if view.forms.focus.as_ref().is_none_or(|x| x.name != f.name || x.widget != wi) {
|
||||
if view.forms.focus.as_ref().is_none_or(|x| !x.is_on(f, wi)) {
|
||||
commit(view, form);
|
||||
view.forms.focus = Some(open_focus(f, wi));
|
||||
}
|
||||
@@ -287,12 +368,12 @@ pub(crate) fn page_input(
|
||||
FormFieldKind::Text if ptr.pressed().is_none() => {
|
||||
// An editor opened by the press cannot be hit until a frame has laid it out: the
|
||||
// release lands on the page and would take its focus away.
|
||||
if let Some(x) = view.forms.focus.as_mut().filter(|x| x.name == f.name && x.widget == wi) {
|
||||
if let Some(x) = view.forms.focus.as_mut().filter(|x| x.is_on(f, wi)) {
|
||||
x.request_focus = true;
|
||||
}
|
||||
}
|
||||
FormFieldKind::Text | FormFieldKind::Combo => {
|
||||
if view.forms.focus.as_ref().is_none_or(|x| x.name != f.name || x.widget != wi) {
|
||||
if view.forms.focus.as_ref().is_none_or(|x| !x.is_on(f, wi)) {
|
||||
commit(view, form);
|
||||
view.forms.focus = Some(open_focus(f, wi));
|
||||
}
|
||||
@@ -306,31 +387,39 @@ pub(crate) fn page_input(
|
||||
let zoom = (r.height() as f64) / height_pt;
|
||||
let y_pt = (p.y - r.min.y) as f64 / zoom;
|
||||
let rows = w.list.unwrap_or(form_appearance::ListRows { top: 0, inset: 2.0, row: 12.0 * 1.15, size: 12.0 });
|
||||
let picked_indices: Vec<usize> = f.value.iter().filter_map(|v| f.options.iter().position(|(e, _)| e == v)).collect();
|
||||
let top = form_appearance::ListRows::top_showing(rows.top, &picked_indices, rows.visible(height_pt), f.options.len());
|
||||
let top = form_appearance::ListRows::top_showing(rows.top, &f.selected, rows.visible(height_pt), f.options.len());
|
||||
if let Some(opt_idx) = rows.option_at(top, y_pt).filter(|&i| i < f.options.len()) {
|
||||
let export = &f.options[opt_idx].0;
|
||||
let ctrl = ui.input(|i| i.modifiers.command || i.modifiers.ctrl);
|
||||
let shift = ui.input(|i| i.modifiers.shift);
|
||||
let multi = f.has(field_flags::MULTI_SELECT);
|
||||
let new_value = if multi && ctrl {
|
||||
let mut picked = f.value.clone();
|
||||
if let Some(pos) = picked.iter().position(|x| x == export) {
|
||||
// Options by position: two options can share an export value (ISO 32000-2
|
||||
// Table 234, `/I`), and the click picks the row, not the first option with its value.
|
||||
let in_order = f.picked_in_order();
|
||||
let picked: Vec<usize> = if multi && ctrl {
|
||||
let mut picked = in_order.clone();
|
||||
if let Some(pos) = picked.iter().position(|&x| x == opt_idx) {
|
||||
picked.remove(pos);
|
||||
} else {
|
||||
picked.push(export.clone());
|
||||
picked.push(opt_idx);
|
||||
}
|
||||
FieldValue::Choice(picked)
|
||||
} else if multi && shift && !f.value.is_empty() {
|
||||
let anchor = f.value.last().and_then(|last| f.options.iter().position(|(e, _)| e == last)).unwrap_or(opt_idx);
|
||||
picked
|
||||
} else if multi
|
||||
&& shift
|
||||
&& let Some(anchor) =
|
||||
view.forms.list_anchor.as_ref().filter(|(name, _)| *name == f.name).map(|(_, row)| *row).or_else(|| in_order.last().copied())
|
||||
{
|
||||
let (min, max) = (anchor.min(opt_idx), anchor.max(opt_idx));
|
||||
let picked = f.options[min..=max].iter().map(|(e, _)| e.clone()).collect();
|
||||
FieldValue::Choice(picked)
|
||||
(min..=max).collect()
|
||||
} else {
|
||||
FieldValue::Choice(vec![export.clone()])
|
||||
vec![opt_idx]
|
||||
};
|
||||
if new_value != FieldValue::Choice(f.value.clone()) {
|
||||
view.pending_edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: new_value });
|
||||
if !(multi && shift) {
|
||||
view.forms.list_anchor = Some((f.name.clone(), opt_idx));
|
||||
}
|
||||
// A single-select list holding an array is written as one value even when its shown
|
||||
// row is clicked again.
|
||||
if picked != in_order || f.single_value_is_array {
|
||||
view.pending_edit = Some(list_pick_edit(form, f, picked));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -340,7 +429,7 @@ pub(crate) fn page_input(
|
||||
|
||||
/// The edit the focused field's draft makes, if it differs from the field's value.
|
||||
pub(crate) fn draft_edit(focus: &Focus, form: &[FormField]) -> Option<Edit> {
|
||||
let f = form.iter().find(|f| f.name == focus.name)?;
|
||||
let f = focused_field(focus, form)?;
|
||||
let value = match f.kind {
|
||||
FormFieldKind::Text if f.value.first().map(String::as_str).unwrap_or("") != focus.text => FieldValue::Text(focus.text.clone()),
|
||||
// Typed into an editable combo box: a shown text picks its option, anything else is the
|
||||
@@ -555,7 +644,7 @@ pub(crate) fn paint_page(
|
||||
for (fi, f) in form.iter().enumerate() {
|
||||
for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page) && !w.hidden) {
|
||||
let r = widget_rect(xf, info, page, w.rect);
|
||||
let focused = view.forms.focus.as_ref().is_some_and(|x| x.name == f.name && x.widget == wi);
|
||||
let focused = view.forms.focus.as_ref().is_some_and(|x| x.is_on(f, wi));
|
||||
if focused {
|
||||
painter.rect_stroke(r.expand(1.0), CornerRadius::same(2), Stroke::new(2.0, FOCUS_BLUE), egui::StrokeKind::Outside);
|
||||
}
|
||||
@@ -564,10 +653,27 @@ pub(crate) fn paint_page(
|
||||
} else if fillable(f) && hovered == Some((fi, wi)) {
|
||||
painter.rect_stroke(r, CornerRadius::same(1), Stroke::new(1.0, FOCUS_BLUE.gamma_multiply(0.8)), egui::StrokeKind::Outside);
|
||||
}
|
||||
if f.kind == FormFieldKind::Combo && fillable(f) {
|
||||
paint_drop_down_arrow(painter, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A drop-down's arrow at the right of its box, which says the field opens a list (its page
|
||||
/// appearance shows only the value). Drawn on screen only, not into the file.
|
||||
fn paint_drop_down_arrow(painter: &egui::Painter, r: Rect) {
|
||||
let width = (r.height() * 0.45).clamp(5.0, 12.0);
|
||||
let inset = (r.height() * 0.25).clamp(2.0, 6.0);
|
||||
// Too narrow a box keeps its value visible instead.
|
||||
if r.width() < width * 3.0 {
|
||||
return;
|
||||
}
|
||||
let (x, y, half) = (r.max.x - inset - width / 2.0, r.center().y, width / 2.0);
|
||||
let points = vec![egui::pos2(x - half, y - half / 2.0), egui::pos2(x + half, y - half / 2.0), egui::pos2(x, y + half / 2.0)];
|
||||
painter.add(egui::Shape::convex_polygon(points, Color32::BLACK, Stroke::NONE));
|
||||
}
|
||||
|
||||
/// The size, in points, a text field shows `text` at on screen: its `/DA` size, or for auto size
|
||||
/// (`0 Tf`) the page appearance's fit, measured in the font the screen draws with so the text
|
||||
/// stays inside the box (the interface font runs wider than the page's Helvetica).
|
||||
@@ -650,19 +756,19 @@ fn paint_unbaked_widget(painter: &egui::Painter, xf: &PageXform, f: &FormField,
|
||||
let zoom = (xf.rect.width() / unrotated_w.max(1.0)) as f64;
|
||||
let rows = w.list.unwrap_or(form_appearance::ListRows { top: 0, inset: 2.0, row: 12.0 * 1.15, size: 12.0 });
|
||||
let height_pt = if matches!(w.rotation, 90 | 270) { (w.rect[2] - w.rect[0]).max(1.0) } else { (w.rect[3] - w.rect[1]).max(1.0) };
|
||||
let picked_indices: Vec<usize> = f.value.iter().filter_map(|v| f.options.iter().position(|(e, _)| e == v)).collect();
|
||||
let top = form_appearance::ListRows::top_showing(rows.top, &picked_indices, rows.visible(height_pt), f.options.len());
|
||||
let top = form_appearance::ListRows::top_showing(rows.top, &f.selected, rows.visible(height_pt), f.options.len());
|
||||
let font_size = (rows.size * zoom).clamp(6.0, 64.0) as f32;
|
||||
let row_h = (rows.row * zoom) as f32;
|
||||
let inset = (rows.inset * zoom) as f32;
|
||||
let p = painter.with_clip_rect(r);
|
||||
let mut y = r.min.y + inset;
|
||||
for (export, display) in f.options.iter().skip(top) {
|
||||
for (i, (_, display)) in f.options.iter().enumerate().skip(top) {
|
||||
if y + row_h > r.max.y {
|
||||
break;
|
||||
}
|
||||
let row_rect = Rect::from_min_size(egui::pos2(r.min.x + 1.0, y), egui::vec2(r.width() - 2.0, row_h));
|
||||
if f.value.contains(export) {
|
||||
// By position: options can share an export value.
|
||||
if f.selected.contains(&i) {
|
||||
p.rect_filled(row_rect, CornerRadius::ZERO, Color32::from_rgb(0x99, 0xC0, 0xDC));
|
||||
}
|
||||
p.text(
|
||||
@@ -678,7 +784,7 @@ fn paint_unbaked_widget(painter: &egui::Painter, xf: &PageXform, f: &FormField,
|
||||
FormFieldKind::CheckBox => {
|
||||
painter.rect_filled(r, CornerRadius::same(1), Color32::from_rgb(0xFF, 0xFF, 0xF4));
|
||||
painter.rect_stroke(r, CornerRadius::same(1), Stroke::new(1.0, Color32::from_gray(180)), egui::StrokeKind::Inside);
|
||||
let checked = f.value.first().is_some_and(|v| v != "Off" && !v.is_empty());
|
||||
let checked = if w.on_state.is_some() { f.widget_on(wi) } else { f.value.first().is_some_and(|v| v != "Off" && !v.is_empty()) };
|
||||
if checked {
|
||||
let sz = (r.height() * 0.75).clamp(8.0, 32.0);
|
||||
painter.text(r.center(), egui::Align2::CENTER_CENTER, "✔", egui::FontId::proportional(sz), Color32::BLACK);
|
||||
@@ -770,7 +876,7 @@ fn tab_to_next_field(
|
||||
// The next field that can be filled in, check boxes and radio buttons included (#2223), in
|
||||
// the document's tab order (each page's /Tabs: rows, columns or structure), wrapping.
|
||||
let order = tab_order(form, info);
|
||||
let exact = order.iter().position(|(fi, wi)| form.get(*fi).is_some_and(|x| x.name == f.name && *wi == widget));
|
||||
let exact = order.iter().position(|(fi, wi)| form.get(*fi).is_some_and(|x| x.obj == f.obj && *wi == widget));
|
||||
let same_field = order.iter().position(|(fi, _)| form.get(*fi).is_some_and(|x| x.name == f.name));
|
||||
let next_after_removed = if exact.is_none() && same_field.is_none() {
|
||||
form.iter().position(|field| field.name == f.name).and_then(|fi| {
|
||||
@@ -849,7 +955,7 @@ pub(crate) fn overlay(
|
||||
let toggle = std::mem::take(&mut view.forms.toggle);
|
||||
view.forms.keys = None;
|
||||
let focus = view.forms.focus.clone()?;
|
||||
let Some(f) = form.iter().find(|f| f.name == focus.name) else {
|
||||
let Some(f) = focused_field(&focus, form) else {
|
||||
view.forms.focus = None;
|
||||
return None;
|
||||
};
|
||||
@@ -870,7 +976,6 @@ pub(crate) fn overlay(
|
||||
// winit reports Windows pen input as touch), which clears `hover_pos`.
|
||||
let clicked_outside = || ctx.input(|i| i.pointer.any_click() && !i.pointer.interact_pos().is_some_and(|p| rect.contains(p)));
|
||||
let zoom = xf.zoom();
|
||||
let t = Tokens::get(ctx);
|
||||
let mut edit = None;
|
||||
let mut close = false;
|
||||
let mut next: Option<bool> = None; // Tab / Shift+Tab
|
||||
@@ -957,28 +1062,21 @@ pub(crate) fn overlay(
|
||||
}
|
||||
FormFieldKind::Combo => {
|
||||
// An editable combo box has a text box over the field as well as its list (ISO
|
||||
// 32000-2 Table 233, Edit).
|
||||
// 32000-2 Table 233, Edit); the keys are the text box's then, and the list takes
|
||||
// the pointer.
|
||||
if editable_combo(f) {
|
||||
combo_editor(ctx, view, ComboEditor { form, field: f, widget: w, rect, zoom, index: focus.widget });
|
||||
}
|
||||
let resp = egui::Area::new(egui::Id::unique(("form-choices", view.view_key())))
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(rect.left_bottom() + vec2(0.0, 2.0))
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(rect.width().max(160.0));
|
||||
ui.label(egui::RichText::new(&f.name).small().color(t.text_faint));
|
||||
egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
|
||||
for (export, display) in &f.options {
|
||||
let on = f.value.first() == Some(export);
|
||||
if ui.selectable_label(on, display).clicked() {
|
||||
edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: FieldValue::Choice(vec![export.clone()]) });
|
||||
close = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
let mut st = view.forms.focus.as_ref().map(|x| x.list).unwrap_or_default();
|
||||
let list = DropDownList { view: view.view_key(), field: f, widget: w, rect, zoom, keys: !editable_combo(f) };
|
||||
let (chosen, resp) = choice_list(ctx, list, &mut st);
|
||||
if let Some(fx) = view.forms.focus.as_mut() {
|
||||
fx.list = st;
|
||||
}
|
||||
if let Some((export, _)) = chosen.and_then(|i| f.options.get(i)) {
|
||||
edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: FieldValue::Choice(vec![export.clone()]) });
|
||||
close = true;
|
||||
}
|
||||
let clicked_away = !resp.response.contains_pointer() && clicked_outside();
|
||||
let (tab, shift) = ctx.input(|i| (i.key_pressed(egui::Key::Tab), i.modifiers.shift));
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
@@ -1006,11 +1104,12 @@ pub(crate) fn overlay(
|
||||
} else if tab {
|
||||
next = Some(!shift);
|
||||
} else if (up || down) && !f.options.is_empty() {
|
||||
let current_idx = f.value.last().and_then(|v| f.options.iter().position(|(e, _)| e == v)).unwrap_or(0);
|
||||
let next_idx = if up { current_idx.saturating_sub(1) } else { (current_idx + 1).min(f.options.len().saturating_sub(1)) };
|
||||
let current_idx = f.picked_in_order().last().copied().unwrap_or(0);
|
||||
let next_idx = if up { current_idx.saturating_sub(1) } else { current_idx.saturating_add(1).min(f.options.len().saturating_sub(1)) };
|
||||
if next_idx != current_idx && next_idx < f.options.len() {
|
||||
let export = f.options[next_idx].0.clone();
|
||||
edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: FieldValue::Choice(vec![export]) });
|
||||
// By position, so the arrows step through options that share an export value,
|
||||
// in the focused twin's own order.
|
||||
edit = Some(list_pick_edit(form, f, vec![next_idx]));
|
||||
}
|
||||
}
|
||||
if clicked_outside() {
|
||||
@@ -1077,6 +1176,202 @@ pub(crate) fn overlay(
|
||||
edit.or_else(|| view.pending_edit.take())
|
||||
}
|
||||
|
||||
/// Where a drop-down's open list ([`choice_list`]) goes and what it lists.
|
||||
struct DropDownList<'a> {
|
||||
/// The document view's pane key, which the list's own ids are made from.
|
||||
view: u64,
|
||||
field: &'a FormField,
|
||||
widget: &'a FormWidget,
|
||||
/// The field's rectangle on screen; the list opens under it.
|
||||
rect: Rect,
|
||||
zoom: f32,
|
||||
/// Whether the list takes the arrow keys and Enter: not for an editable combo box, whose
|
||||
/// text box has them.
|
||||
keys: bool,
|
||||
}
|
||||
|
||||
/// Items a drop-down's list shows before it scrolls.
|
||||
const LIST_ROWS: usize = 9;
|
||||
|
||||
/// A drop-down's open list, under the field and drawn like it, as other viewers draw theirs: as
|
||||
/// wide as the box, its items in the field's text size and alignment, black on white with a blue
|
||||
/// highlight that follows the pointer and the arrow keys, and a scroll bar with step buttons when
|
||||
/// there are more than nine items. Returns the item chosen (a click, or Enter on the current one)
|
||||
/// and the list's response. With `keys` off (an editable combo box, whose text box has the keys)
|
||||
/// only the pointer moves through and picks from it.
|
||||
fn choice_list(ctx: &egui::Context, list: DropDownList<'_>, st: &mut ChoiceList) -> (Option<usize>, egui::InnerResponse<()>) {
|
||||
let DropDownList { view, field: f, widget: w, rect, zoom, keys } = list;
|
||||
let n = f.options.len();
|
||||
let shown = n.min(LIST_ROWS);
|
||||
let max_first = n.saturating_sub(shown);
|
||||
// Auto-sized text is fitted to what the field shows (its chosen item's shown name), so the
|
||||
// list's items come out at the size the field's value is drawn at.
|
||||
let value_text = f.value.first().map_or("", |v| f.options.iter().find(|(e, _)| e == v).map_or(v.as_str(), |(_, d)| d.as_str()));
|
||||
let size = (field_text_size(&ctx.layer_painter(egui::LayerId::background()), f, w, value_text) * zoom).clamp(6.0, 48.0);
|
||||
let row = (size * 1.45).round().max(8.0);
|
||||
let bar = if n > shown { (row * 0.7).round().clamp(12.0, 22.0) } else { 0.0 };
|
||||
let width = rect.width().max(24.0 + bar);
|
||||
if !st.placed {
|
||||
st.current = f.value.first().and_then(|v| f.options.iter().position(|(e, _)| e == v));
|
||||
st.first = st.current.map_or(0, |c| c.min(max_first));
|
||||
st.placed = true;
|
||||
}
|
||||
// Consumed, so the keys move through the list rather than the page.
|
||||
let key = |k| keys && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, k));
|
||||
let moved = if n == 0 {
|
||||
None
|
||||
} else if key(egui::Key::ArrowUp) {
|
||||
Some(st.current.map_or(0, |c| c.saturating_sub(1)))
|
||||
} else if key(egui::Key::ArrowDown) {
|
||||
Some(st.current.map_or(0, |c| (c + 1).min(n - 1)))
|
||||
} else if key(egui::Key::PageUp) {
|
||||
Some(st.current.map_or(0, |c| c.saturating_sub(shown)))
|
||||
} else if key(egui::Key::PageDown) {
|
||||
Some(st.current.map_or(0, |c| (c + shown).min(n - 1)))
|
||||
} else if key(egui::Key::Home) {
|
||||
Some(0)
|
||||
} else if key(egui::Key::End) {
|
||||
Some(n - 1)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(m) = moved {
|
||||
st.current = Some(m);
|
||||
st.first = if m < st.first {
|
||||
m
|
||||
} else if m >= st.first + shown {
|
||||
m + 1 - shown
|
||||
} else {
|
||||
st.first
|
||||
};
|
||||
}
|
||||
let mut chosen = key(egui::Key::Enter).then_some(st.current).flatten();
|
||||
let align = match f.quadding {
|
||||
1 => egui::Align::Center,
|
||||
2 => egui::Align::Max,
|
||||
_ => egui::Align::Min,
|
||||
};
|
||||
let resp =
|
||||
egui::Area::new(egui::Id::unique(("form-choices", view))).order(egui::Order::Foreground).fixed_pos(rect.left_bottom()).show(ctx, |ui| {
|
||||
let (outer, area) = ui.allocate_exact_size(vec2(width, shown as f32 * row + 2.0), egui::Sense::hover());
|
||||
let p = ui.painter();
|
||||
// The list is drawn as the form's own, a white list in the field's font with a blue
|
||||
// highlight, in light and dark themes alike, so its colors are fixed, not the app's tokens.
|
||||
p.rect_filled(outer, CornerRadius::ZERO, Color32::WHITE);
|
||||
// The wheel scrolls the list, a row at a time, and not the page under it.
|
||||
if area.contains_pointer() && n > shown {
|
||||
st.wheel += ctx.input(|i| i.smooth_scroll_delta.y);
|
||||
ctx.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);
|
||||
let steps = (st.wheel / row).trunc();
|
||||
if steps != 0.0 {
|
||||
st.wheel -= steps * row;
|
||||
st.first = (st.first as f32 - steps).clamp(0.0, max_first as f32) as usize;
|
||||
}
|
||||
}
|
||||
let pointer = ctx.input(|i| i.pointer.hover_pos());
|
||||
let pointer_moved = pointer != st.pointer_at;
|
||||
let font = egui::FontId::proportional(size);
|
||||
for k in 0..shown {
|
||||
let i = st.first + k;
|
||||
let Some((_, display)) = f.options.get(i) else { break };
|
||||
let r = Rect::from_min_size(outer.min + vec2(1.0, 1.0 + k as f32 * row), vec2(width - 2.0 - bar, row));
|
||||
let item = ui.interact(r, ui.scope_id().with(("choice", i)), egui::Sense::click());
|
||||
item.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, st.current == Some(i), display));
|
||||
if item.hovered() && pointer_moved {
|
||||
st.current = Some(i);
|
||||
}
|
||||
if item.clicked() {
|
||||
chosen = Some(i);
|
||||
}
|
||||
let on = st.current == Some(i);
|
||||
if on {
|
||||
p.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0x1F, 0x65, 0xD6));
|
||||
}
|
||||
let galley = p.layout_no_wrap(display.clone(), font.clone(), if on { Color32::WHITE } else { Color32::BLACK });
|
||||
let inner = r.shrink2(vec2(3.0, 0.0));
|
||||
let x = match align {
|
||||
egui::Align::Center => inner.center().x - galley.size().x / 2.0,
|
||||
egui::Align::Max => inner.max.x - galley.size().x,
|
||||
egui::Align::Min => inner.min.x,
|
||||
};
|
||||
p.with_clip_rect(r).galley(egui::pos2(x, r.center().y - galley.size().y / 2.0), galley, Color32::BLACK);
|
||||
}
|
||||
st.pointer_at = pointer;
|
||||
if bar > 0.0 {
|
||||
scroll_bar(ui, Rect::from_min_max(egui::pos2(outer.max.x - 1.0 - bar, outer.min.y + 1.0), outer.max - vec2(1.0, 1.0)), shown, n, st);
|
||||
}
|
||||
p.rect_stroke(outer, CornerRadius::ZERO, Stroke::new(1.0, Color32::BLACK), egui::StrokeKind::Inside);
|
||||
});
|
||||
(chosen, resp)
|
||||
}
|
||||
|
||||
/// A list's classic scroll bar: step buttons at each end, a thumb sized to the share of the
|
||||
/// items shown that can be dragged, and a track that pages when clicked.
|
||||
fn scroll_bar(ui: &egui::Ui, track: Rect, shown: usize, n: usize, st: &mut ChoiceList) {
|
||||
let max_first = n.saturating_sub(shown);
|
||||
if max_first == 0 {
|
||||
return;
|
||||
}
|
||||
let side = track.width();
|
||||
let up = Rect::from_min_size(track.min, vec2(side, side));
|
||||
let down = Rect::from_min_max(egui::pos2(track.min.x, track.max.y - side), track.max);
|
||||
let trough = Rect::from_min_max(egui::pos2(track.min.x, up.max.y), egui::pos2(track.max.x, down.min.y));
|
||||
let thumb_len = (trough.height() * shown as f32 / n as f32).max(side * 0.75).min(trough.height());
|
||||
let travel = (trough.height() - thumb_len).max(1.0);
|
||||
let thumb_at = |first: usize| trough.min.y + travel * first as f32 / max_first as f32;
|
||||
let id = ui.scope_id().with("choice-bar");
|
||||
let p = ui.painter();
|
||||
p.rect_filled(track, CornerRadius::ZERO, Color32::from_gray(240));
|
||||
for (r, step, pointing_up) in [(up, -1i64, true), (down, 1, false)] {
|
||||
let b = ui.interact(r, id.with(pointing_up), egui::Sense::click());
|
||||
if b.clicked() {
|
||||
st.first = (st.first as i64 + step).clamp(0, max_first as i64) as usize;
|
||||
}
|
||||
p.rect_filled(r.shrink(1.0), CornerRadius::ZERO, if b.hovered() { Color32::from_gray(205) } else { Color32::from_gray(222) });
|
||||
p.rect_stroke(r.shrink(1.0), CornerRadius::ZERO, Stroke::new(1.0, Color32::from_gray(150)), egui::StrokeKind::Inside);
|
||||
let (c, h) = (r.center(), (side * 0.18).max(2.0));
|
||||
let tip = if pointing_up { -h } else { h };
|
||||
let points = vec![egui::pos2(c.x - h * 1.4, c.y - tip / 2.0), egui::pos2(c.x + h * 1.4, c.y - tip / 2.0), egui::pos2(c.x, c.y + tip / 2.0)];
|
||||
p.add(egui::Shape::convex_polygon(points, Color32::from_gray(40), Stroke::NONE));
|
||||
}
|
||||
let thumb = Rect::from_min_size(egui::pos2(trough.min.x, thumb_at(st.first)), vec2(side, thumb_len));
|
||||
let t = ui.interact(thumb, id.with("thumb"), egui::Sense::drag());
|
||||
let pointer = ui.input(|i| i.pointer.interact_pos());
|
||||
// The primary button only: a right-button drag moves nothing (AGENTS.md "Page presses").
|
||||
if t.drag_started_by(egui::PointerButton::Primary) {
|
||||
st.grab = pointer.map(|q| q.y - thumb.min.y);
|
||||
}
|
||||
if t.dragged()
|
||||
&& let (Some(q), Some(grab)) = (pointer, st.grab)
|
||||
{
|
||||
let share = ((q.y - grab - trough.min.y) / travel).clamp(0.0, 1.0);
|
||||
st.first = (share * max_first as f32).round() as usize;
|
||||
}
|
||||
if t.drag_stopped() {
|
||||
st.grab = None;
|
||||
}
|
||||
let page = ui.interact(trough, id.with("trough"), egui::Sense::click());
|
||||
if page.clicked()
|
||||
&& let Some(q) = pointer
|
||||
&& !thumb.contains(q)
|
||||
{
|
||||
st.first = if q.y < thumb.min.y { st.first.saturating_sub(shown) } else { (st.first + shown).min(max_first) };
|
||||
}
|
||||
let thumb = Rect::from_min_size(egui::pos2(trough.min.x, thumb_at(st.first)), vec2(side, thumb_len)).shrink2(vec2(1.0, 0.5));
|
||||
p.rect_filled(thumb, CornerRadius::ZERO, if t.dragged() || t.hovered() { Color32::from_gray(176) } else { Color32::from_gray(196) });
|
||||
p.rect_stroke(thumb, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_gray(140)), egui::StrokeKind::Inside);
|
||||
// Grip lines across the middle of the thumb.
|
||||
if thumb.height() > side {
|
||||
for k in -1..=1 {
|
||||
let y = thumb.center().y + k as f32 * 3.0;
|
||||
p.line_segment(
|
||||
[egui::pos2(thumb.min.x + side * 0.3, y), egui::pos2(thumb.max.x - side * 0.3, y)],
|
||||
Stroke::new(1.0, Color32::from_gray(120)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a field's widget is on screen (tests and automation).
|
||||
pub fn field_screen_rect(view: &DocView, info: &DocInfo, f: &FormField, widget: usize) -> Option<Rect> {
|
||||
let w = f.widgets.get(widget)?;
|
||||
|
||||
@@ -117,7 +117,7 @@ pub(crate) fn hit(xf: &PageXform, info: &DocInfo, page: usize, links: &[LinkItem
|
||||
let index = links.iter().rfind(|l| l.page == page && screen_rect(xf, info, page, l.rect).expand(LINK_TOOL_MARGIN).contains(p))?.index;
|
||||
(index, info.links.iter().find(|l| l.page == page && l.index == index))
|
||||
} else {
|
||||
let link = info.links.iter().rfind(|l| l.page == page && xf.user_rect(info, page, l.rect).contains(p))?;
|
||||
let link = info.links.iter().rfind(|l| l.page == page && xf.link_contains(info, page, l, p))?;
|
||||
(link.index, Some(link))
|
||||
};
|
||||
let tip = link.map(|l| target_label(info, &l.target));
|
||||
|
||||
@@ -3556,6 +3556,28 @@ fn an_upright_comment_on_a_turned_page_is_drawn_where_it_goes_before_release() {
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// The selection bar stays inside the pages' area: its place was worked out for a 520 pt bar,
|
||||
/// so longer labels (German here) pushed it over the side panel next to a selection on the right.
|
||||
#[test]
|
||||
fn the_selection_bar_stays_inside_the_pages_area() {
|
||||
let mut h = harness(|app| app.set_option("language", "de").unwrap());
|
||||
// Narrower than the harness, as with a side panel open.
|
||||
h.set_size(egui::vec2(1100.0, 900.0));
|
||||
h.run_steps(4);
|
||||
// The rightmost glyph of "The quick brown fox": the bar opens at its left.
|
||||
let last = (0..64).filter_map(|i| h.state().views[0].glyph_screen_pos(0, i).map(|p| (i, p.x))).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap().0;
|
||||
h.state_mut().views[0].select_text(0, last, last);
|
||||
h.run_steps(4);
|
||||
let viewport = h.state().views[0].viewport_rect();
|
||||
// The bar's whole area, frame included, not only its first and last buttons.
|
||||
let id = egui::Id::unique(("text-selection-actions", h.state().views[0].view_key()));
|
||||
let bar = h.ctx.memory(|m| m.area_rect(id)).expect("the selection bar is shown");
|
||||
// The bar opens at the selection's left edge: past the area's right edge, without the clamp.
|
||||
let anchor = h.state().views[0].glyph_screen_rect(0, last).unwrap().left();
|
||||
assert!(anchor + bar.width() > viewport.right(), "selection at {anchor}, bar {} wide, area {viewport:?}", bar.width());
|
||||
assert!(viewport.contains_rect(bar), "bar {bar:?} inside {viewport:?}");
|
||||
}
|
||||
|
||||
/// `n` pages with one comment each, "Card 1" to "Card n".
|
||||
fn one_comment_per_page(n: usize) -> Vec<u8> {
|
||||
let mut objs = vec!["<< /Type /Catalog /Pages 2 0 R >>".to_string()];
|
||||
|
||||
@@ -1038,3 +1038,61 @@ fn a_drag_from_an_address_in_the_page_text_selects_it() {
|
||||
assert!(selected.as_deref().is_some_and(|t| t.starts_with("tp")), "the drag selects the address's text: {selected:?}");
|
||||
assert_eq!(h.state().pending_link, None, "a drag opens nothing");
|
||||
}
|
||||
|
||||
/// One 300×400 page with two links (ISO 32000-2 §12.5.6.5, §12.6.4.8): at y 300..350 a relative
|
||||
/// address the catalog's `/URI /Base` resolves, and at y 200..250 a link whose `/Rect` spans the
|
||||
/// page but whose `/QuadPoints` cover only x 50..120.
|
||||
fn base_and_quads_fixture() -> Vec<u8> {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /URI << /Base (https://example.org/base/) >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [50 300 250 350] /Border [0 0 0] /A << /S /URI /URI (page.html) >> >>",
|
||||
"<< /Type /Annot /Subtype /Link /Rect [50 200 250 250] /QuadPoints [50 200 120 200 120 250 50 250] /Border [0 0 0] /A << /S /URI /URI (https://example.org/first-word) >> >>",
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let x = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offs {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A relative link opens at the address the document's base gives it, through the usual
|
||||
/// confirmation; a link is active only in its `/QuadPoints`, not over the rest of its `/Rect`.
|
||||
#[test]
|
||||
fn relative_links_use_the_base_and_quad_points_limit_where_a_link_is_active() {
|
||||
let _gpu = gpu();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("base.pdf", None, base_and_quads_fixture()).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("panel", "none").unwrap();
|
||||
app.set_option("zoom", "150").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(8);
|
||||
click_link(&mut h);
|
||||
assert_eq!(h.state().pending_link, pending("https://example.org/base/page.html", LinkOrigin::Link));
|
||||
h.get_by_label("Cancel").click();
|
||||
h.run_steps(4);
|
||||
let point = |h: &Harness<'static, PdfCraftApp>, x: f32, y: f32| {
|
||||
let r = h.state().views[0].page_screen_rect(0).expect("page 1 on screen");
|
||||
egui::pos2(r.min.x + r.width() * (x / 300.0), r.min.y + r.height() * (1.0 - y / 400.0))
|
||||
};
|
||||
// Inside /Rect, outside the quadrilateral: nothing.
|
||||
let away = point(&h, 200.0, 225.0);
|
||||
click_at(&mut h, away);
|
||||
assert_eq!(h.state().pending_link, None, "the rest of /Rect is not the link");
|
||||
let on = point(&h, 80.0, 225.0);
|
||||
click_at(&mut h, on);
|
||||
assert_eq!(h.state().pending_link, pending("https://example.org/first-word", LinkOrigin::Link));
|
||||
}
|
||||
@@ -1422,6 +1422,145 @@ fn list_box_clicks_select_directly_and_ctrl_click_toggles_multi() {
|
||||
assert_eq!(value(&h, "ListMulti"), ["Tue", "Thu"], "Ctrl-clicking Thu toggled it on, keeping Tue");
|
||||
}
|
||||
|
||||
/// The selected option positions of `name` (`/I`, or `/V` without a usable one).
|
||||
fn selected(h: &Harness<'static, PdfCraftApp>, name: &str) -> Vec<usize> {
|
||||
let s = h.state();
|
||||
s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == name).unwrap().selected.clone()
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 234: `/I` tells apart options that share an export value. A list box whose
|
||||
/// One-A and One-B both export `1` shows the one `/I` names, and a click picks the row clicked:
|
||||
/// `/V (1)` with `/I` naming it, so the pick survives a save and reopen.
|
||||
#[test]
|
||||
fn a_list_box_click_picks_one_of_two_options_with_the_same_export_value() {
|
||||
let bytes = pdf_from_objects(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] /V (1) /I [1] /Rect [50 250 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
]);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("dup.pdf", None, bytes).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("zoom", "100").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
assert_eq!(selected(&h, "dup"), [1], "One-B is selected, not One-A too");
|
||||
|
||||
let r = {
|
||||
let s = h.state();
|
||||
let doc = s.session.get(s.views[0].id).unwrap();
|
||||
let f = doc.form.iter().find(|f| f.name == "dup").unwrap();
|
||||
pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen")
|
||||
};
|
||||
let zoom = r.height() / 70.0;
|
||||
// Row 0 (One-A), then row 1 (One-B): each click changes the selection though /V stays (1).
|
||||
click_at(&mut h, egui::pos2(r.center().x, r.min.y + 8.0 * zoom));
|
||||
assert_eq!(value(&h, "dup"), ["1"]);
|
||||
assert_eq!(selected(&h, "dup"), [0], "clicking One-A picks One-A");
|
||||
click_at(&mut h, egui::pos2(r.center().x, r.min.y + 19.0 * zoom));
|
||||
assert_eq!(selected(&h, "dup"), [1], "clicking One-B picks One-B again");
|
||||
click_at(&mut h, egui::pos2(r.center().x, r.min.y + 8.0 * zoom));
|
||||
assert_eq!(selected(&h, "dup"), [0]);
|
||||
|
||||
let dir = scratch("duplicate-exports");
|
||||
let out = dir.join("saved.pdf");
|
||||
h.state_mut().save_override = Some(out.to_string_lossy().into_owned());
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S);
|
||||
wait_for_file(&mut h, &out);
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.open_bytes("saved.pdf", None, std::fs::read(&out).unwrap()).unwrap();
|
||||
let reopened = app.session.get(app.views[0].id).unwrap().form.iter().find(|f| f.name == "dup").unwrap().clone();
|
||||
assert_eq!(reopened.value, ["1"], "/V is the one export value");
|
||||
assert_eq!(reopened.selected, [0], "/I keeps One-A through the save");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Same-name list boxes are one field (ISO 32000-2 §12.7.3.1), and a twin can list the options
|
||||
/// sharing an export value in another order: clicking One-B in the second gives both One-B, not
|
||||
/// the option at the same position in the first.
|
||||
#[test]
|
||||
fn a_click_in_a_twin_list_box_with_options_in_another_order_picks_the_row_clicked() {
|
||||
let bytes = pdf_from_objects(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 6 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 6 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Opt [[(1) (One-A)] [(1) (One-B)] [(2) (Two)]] /Rect [50 250 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (dup) /Opt [[(1) (One-B)] [(1) (One-A)] [(2) (Two)]] /Rect [50 100 200 170] /P 3 0 R /F 4 >>",
|
||||
]);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("twins.pdf", None, bytes).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("zoom", "100").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
let twins = |h: &Harness<'static, PdfCraftApp>| -> Vec<Vec<usize>> {
|
||||
let s = h.state();
|
||||
s.session.get(s.views[0].id).unwrap().form.iter().filter(|f| f.name == "dup").map(|f| f.selected.clone()).collect()
|
||||
};
|
||||
let r = {
|
||||
let s = h.state();
|
||||
let doc = s.session.get(s.views[0].id).unwrap();
|
||||
let f = doc.form.iter().filter(|f| f.name == "dup").nth(1).unwrap();
|
||||
pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen")
|
||||
};
|
||||
let zoom = r.height() / 70.0;
|
||||
// Row 0 of the second list box: One-B.
|
||||
click_at(&mut h, egui::pos2(r.center().x, r.min.y + 8.0 * zoom));
|
||||
assert_eq!(value(&h, "dup"), ["1"]);
|
||||
assert_eq!(twins(&h), [vec![1], vec![0]], "One-B in both: second in the first, first in the twin");
|
||||
// The arrows step through the focused twin's own rows: ↓ from One-B there is One-A, which is
|
||||
// first in the first field, not Two (the row after One-B in the first field).
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
h.run_steps(3);
|
||||
assert_eq!(twins(&h), [vec![0], vec![1]], "One-A in both after ↓ in the twin");
|
||||
h.key_press(egui::Key::ArrowUp);
|
||||
h.run_steps(3);
|
||||
assert_eq!(twins(&h), [vec![1], vec![0]], "back to One-B after ↑ in the twin");
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 233: a list box without MultiSelect selects "at most one item". Given
|
||||
/// `/V [(TW) (JP)]` it shows Taiwan alone, and a click writes the one option clicked.
|
||||
#[test]
|
||||
fn a_single_select_list_box_given_two_values_shows_and_takes_one() {
|
||||
let bytes = pdf_from_objects(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (pair) /Opt [[(TW) (Taiwan)] [(JP) (Japan)] [(US) (United States)]] /V [(TW) (JP)] /Rect [50 250 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
]);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("pair.pdf", None, bytes).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("zoom", "100").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
assert_eq!((value(&h, "pair"), selected(&h, "pair")), (vec!["TW".to_string()], vec![0]), "Taiwan alone");
|
||||
|
||||
let r = {
|
||||
let s = h.state();
|
||||
let doc = s.session.get(s.views[0].id).unwrap();
|
||||
let f = doc.form.iter().find(|f| f.name == "pair").unwrap();
|
||||
pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen")
|
||||
};
|
||||
let zoom = r.height() / 70.0;
|
||||
// Row 1 (Japan), which /V also named: clicking it makes it the one value.
|
||||
click_at(&mut h, egui::pos2(r.center().x, r.min.y + 19.0 * zoom));
|
||||
assert_eq!((value(&h, "pair"), selected(&h, "pair")), (vec!["JP".to_string()], vec![1]));
|
||||
}
|
||||
|
||||
/// Auto-size (`0 Tf`, inherited from the AcroForm) single-line and multiline fields, and a fixed 10 pt one.
|
||||
fn auto_size_form() -> Vec<u8> {
|
||||
pdf_from_objects(&[
|
||||
@@ -1829,3 +1968,474 @@ fn a_read_only_radio_button_is_focused_but_not_selected() {
|
||||
click_field(&mut h, "size", 1);
|
||||
assert_eq!((value(&h, "size"), toast(&h)), (vec!["S".to_string()], Some("size is read-only".to_string())), "nor does a click");
|
||||
}
|
||||
|
||||
/// Check box fields of two kids each: `pair` with the on states A and B, `same` with Yes twice.
|
||||
fn check_box_kids() -> Harness<'static, PdfCraftApp> {
|
||||
let kid = |parent: u32, y: u32, x: u32, state: &str| {
|
||||
format!(
|
||||
"<< /Type /Annot /Subtype /Widget /Parent {parent} 0 R /AS /Off /Rect [{x} {y} {} {}] /P 3 0 R /F 4 /AP << /N << /{state} 5 0 R /Off 5 0 R >> >> >>",
|
||||
x + 16,
|
||||
y + 16
|
||||
)
|
||||
};
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R 9 0 R] /DA (/Helv 0 Tf 0 g) >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 10 0 R 11 0 R] >>".into(),
|
||||
"<< >>".into(),
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 16 16] /Length 0 >>\nstream\n\nendstream".into(),
|
||||
"<< /FT /Btn /T (pair) /V /Off /Kids [7 0 R 8 0 R] >>".into(),
|
||||
kid(6, 350, 20, "A"),
|
||||
kid(6, 350, 60, "B"),
|
||||
"<< /FT /Btn /T (same) /V /Off /Kids [10 0 R 11 0 R] >>".into(),
|
||||
kid(9, 300, 20, "Yes"),
|
||||
kid(9, 300, 60, "Yes"),
|
||||
];
|
||||
let objs: Vec<&str> = objs.iter().map(String::as_str).collect();
|
||||
let bytes = pdf_from_objects(&objs);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("kids.pdf", None, bytes).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("zoom", "150").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(6);
|
||||
h
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §12.7.5.2.3: a check box field's value is the on state of the kid that is on, and
|
||||
/// its kids can have different on states (Table 230). Clicking B after A ticks B and clears A;
|
||||
/// clicking B again clears the field; kids sharing an on state tick together (EXAMPLE 2).
|
||||
#[test]
|
||||
fn clicking_check_box_kids_with_different_on_states() {
|
||||
let mut h = check_box_kids();
|
||||
click_field(&mut h, "pair", 0);
|
||||
assert_eq!((on_widgets(&h, "pair"), value(&h, "pair")), (vec![true, false], vec!["A".to_string()]));
|
||||
click_field(&mut h, "pair", 1);
|
||||
assert_eq!((on_widgets(&h, "pair"), value(&h, "pair")), (vec![false, true], vec!["B".to_string()]), "B ticks and A clears");
|
||||
click_field(&mut h, "pair", 1);
|
||||
assert_eq!((on_widgets(&h, "pair"), value(&h, "pair")), (vec![false, false], vec![]), "clicking B again clears the field");
|
||||
click_field(&mut h, "pair", 1);
|
||||
click_field(&mut h, "pair", 0);
|
||||
assert_eq!((on_widgets(&h, "pair"), value(&h, "pair")), (vec![true, false], vec!["A".to_string()]), "the tick moves back to A");
|
||||
click_field(&mut h, "same", 0);
|
||||
assert_eq!(on_widgets(&h, "same"), [true, true], "kids sharing Yes tick together");
|
||||
click_field(&mut h, "same", 1);
|
||||
assert_eq!(on_widgets(&h, "same"), [false, false], "and untick together");
|
||||
// Space on the focused kid toggles that kid too.
|
||||
click_field(&mut h, "pair", 1);
|
||||
assert_eq!(value(&h, "pair"), ["B"]);
|
||||
h.key_press(egui::Key::Space);
|
||||
h.run_steps(3);
|
||||
assert!(value(&h, "pair").is_empty(), "Space clears the ticked kid");
|
||||
}
|
||||
|
||||
/// Click at `p` with `modifiers` held.
|
||||
fn click_with(h: &mut Harness<'static, PdfCraftApp>, p: egui::Pos2, modifiers: egui::Modifiers) {
|
||||
h.event(egui::Event::ModifiersChanged(modifiers));
|
||||
h.hover_at(p);
|
||||
h.run_steps(1);
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers });
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// A list box opened at 100% zoom on its own page, and its rectangle on screen.
|
||||
fn list_box(objects: &[&str], name: &str) -> (Harness<'static, PdfCraftApp>, egui::Rect) {
|
||||
let bytes = pdf_from_objects(objects);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("list.pdf", None, bytes).unwrap();
|
||||
app.set_option("left", "closed").unwrap();
|
||||
app.set_option("zoom", "100").unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
let r = {
|
||||
let s = h.state();
|
||||
let doc = s.session.get(s.views[0].id).unwrap();
|
||||
let f = doc.form.iter().find(|f| f.name == name).unwrap();
|
||||
pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen")
|
||||
};
|
||||
(h, r)
|
||||
}
|
||||
|
||||
/// A Shift-click picks the rows from the one clicked last: after Ctrl-clicking row 3 and then
|
||||
/// row 1, Shift on row 4 picks rows 1 to 4, not 3 to 4. The rows share one export value, so the
|
||||
/// value can't say which came last, and `/I` lists them in ascending order.
|
||||
#[test]
|
||||
fn a_shift_click_in_a_list_box_extends_from_the_row_clicked_last() {
|
||||
let (mut h, r) = list_box(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (days) /Ff 2097152 /Opt [[(x) (Mon)] [(x) (Tue)] [(x) (Wed)] [(x) (Thu)] [(x) (Fri)] [(x) (Sat)]] /Rect [50 220 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
],
|
||||
"days",
|
||||
);
|
||||
let zoom = r.height() / 100.0;
|
||||
let row = |k: f32| egui::pos2(r.center().x, r.min.y + (8.0 + 11.5 * k) * zoom);
|
||||
click_with(&mut h, row(3.0), egui::Modifiers::COMMAND);
|
||||
click_with(&mut h, row(1.0), egui::Modifiers::COMMAND);
|
||||
assert_eq!(selected(&h, "days"), [1, 3]);
|
||||
click_with(&mut h, row(4.0), egui::Modifiers::SHIFT);
|
||||
assert_eq!(selected(&h, "days"), [1, 2, 3, 4], "from row 1, the one clicked last");
|
||||
}
|
||||
|
||||
/// A single-select list box holding an array `/V` is written as one value when its shown row is
|
||||
/// clicked again, not left as an array because the row was already selected.
|
||||
#[test]
|
||||
fn clicking_the_shown_row_of_a_single_select_list_holding_an_array_writes_one_value() {
|
||||
let (mut h, r) = list_box(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 400] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Ch /T (pair) /Opt [[(TW) (Taiwan)] [(JP) (Japan)] [(US) (United States)]] /V [(TW) (JP)] /Rect [50 250 200 320] /P 3 0 R /F 4 >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
],
|
||||
"pair",
|
||||
);
|
||||
let field = |h: &Harness<'static, PdfCraftApp>| {
|
||||
let s = h.state();
|
||||
s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == "pair").unwrap().clone()
|
||||
};
|
||||
assert!(field(&h).single_value_is_array, "loaded from an array");
|
||||
let zoom = r.height() / 70.0;
|
||||
click_at(&mut h, egui::pos2(r.center().x, r.min.y + 8.0 * zoom));
|
||||
let f = field(&h);
|
||||
assert_eq!((f.value, f.selected, f.single_value_is_array), (vec!["TW".to_string()], vec![0], false), "Taiwan, now one value");
|
||||
}
|
||||
|
||||
/// Where the first widget of field `name` is on screen in the first view.
|
||||
fn field_rect(h: &Harness<'static, PdfCraftApp>, name: &str) -> egui::Rect {
|
||||
let s = h.state();
|
||||
let doc = s.session.get(s.views[0].id).unwrap();
|
||||
let f = doc.form.iter().find(|f| f.name == name).unwrap();
|
||||
pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen")
|
||||
}
|
||||
|
||||
/// Filled triangles painted inside `within`, at any depth of the frame's shapes.
|
||||
fn triangles_in(h: &Harness<'static, PdfCraftApp>, within: egui::Rect) -> Vec<Vec<egui::Pos2>> {
|
||||
/// Collects the filled three-point paths of `shape` that lie inside `within`, descending into
|
||||
/// nested shape lists.
|
||||
fn walk(shape: &egui::Shape, within: egui::Rect, out: &mut Vec<Vec<egui::Pos2>>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, within, out)),
|
||||
egui::Shape::Path(p) if p.points.len() == 3 && p.fill != egui::Color32::TRANSPARENT && p.points.iter().all(|q| within.contains(*q)) => {
|
||||
out.push(p.points.clone())
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for c in &h.output().shapes {
|
||||
walk(&c.shape, within, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A drop-down draws one filled arrow at the right of its box, and a text field draws none.
|
||||
#[test]
|
||||
fn a_drop_down_shows_its_arrow_and_text_fields_do_not() {
|
||||
let mut h = harness();
|
||||
h.run_steps(2);
|
||||
let country = field_rect(&h, "country");
|
||||
let arrows = triangles_in(&h, country);
|
||||
assert_eq!(arrows.len(), 1, "one arrow in the drop-down: {arrows:?}");
|
||||
let tip = arrows[0].iter().fold(egui::Pos2::ZERO, |a, p| egui::pos2(a.x.max(p.x), a.y.max(p.y)));
|
||||
assert!(tip.x > country.center().x, "at the right of the box");
|
||||
assert!(triangles_in(&h, field_rect(&h, "city")).is_empty(), "a text field has none");
|
||||
}
|
||||
|
||||
/// A drop-down's list opens on the field's left edge and no wider than the field, without
|
||||
/// showing the field's name, and clicking an item chooses it.
|
||||
#[test]
|
||||
fn a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name() {
|
||||
let mut h = harness();
|
||||
click_field(&mut h, "country", 0);
|
||||
let country = field_rect(&h, "country");
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "country").is_none(), "the field's name isn't shown");
|
||||
let item = egui_kittest::kittest::Queryable::get_by_label(&h, "France").rect();
|
||||
assert!((item.left() - country.left()).abs() <= 2.0 && item.right() <= country.right() + 1.0, "{item:?} in {country:?}");
|
||||
egui_kittest::kittest::Queryable::get_by_label(&h, "France").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(value(&h, "country"), ["fr"]);
|
||||
}
|
||||
|
||||
/// A drop-down with 30 options keeps its scroll bar in its own room, so the items stop short
|
||||
/// of the field's right edge.
|
||||
#[test]
|
||||
fn a_long_drop_down_list_keeps_its_scroll_bar_beside_the_items() {
|
||||
let mut h = harness();
|
||||
let options: Vec<String> = (0..30).map(|i| format!("{i:02}00")).collect();
|
||||
assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps {
|
||||
name: "country".into(),
|
||||
props: Box::new(pdfcraft_engine::FieldProps { options: Some(options), ..Default::default() }),
|
||||
}));
|
||||
h.run_steps(3);
|
||||
click_field(&mut h, "country", 0);
|
||||
let country = field_rect(&h, "country");
|
||||
let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect();
|
||||
// A scroll bar that stays shown takes its own room, so people see there is more below.
|
||||
assert!(first.right() <= country.right() - 6.0, "{first:?} leaves room for the bar in {country:?}");
|
||||
}
|
||||
|
||||
/// Where `text` is drawn in the last frame, if anywhere.
|
||||
fn text_rect(h: &Harness<'static, PdfCraftApp>, text: &str) -> Option<egui::Rect> {
|
||||
/// The rectangle of the text shape in `shape` that reads exactly `text`, searching nested
|
||||
/// shape lists.
|
||||
fn walk(shape: &egui::Shape, text: &str) -> Option<egui::Rect> {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| walk(s, text)),
|
||||
egui::Shape::Text(t) if t.galley.text() == text => Some(egui::Rect::from_min_size(t.pos, t.galley.size())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
h.output().shapes.iter().find_map(|c| walk(&c.shape, text))
|
||||
}
|
||||
|
||||
/// Gives the "country" drop-down 30 options, "0000" to "2900", more than its list shows at once.
|
||||
fn long_country(h: &mut Harness<'static, PdfCraftApp>) {
|
||||
let options: Vec<String> = (0..30).map(|i| format!("{i:02}00")).collect();
|
||||
assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps {
|
||||
name: "country".into(),
|
||||
props: Box::new(pdfcraft_engine::FieldProps { options: Some(options), ..Default::default() }),
|
||||
}));
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// A centered drop-down (quadding 1) centers the items of its open list too.
|
||||
#[test]
|
||||
fn a_drop_downs_list_aligns_its_items_as_the_field_does() {
|
||||
let mut h = harness();
|
||||
assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps {
|
||||
name: "country".into(),
|
||||
props: Box::new(pdfcraft_engine::FieldProps { quadding: Some(1), ..Default::default() }),
|
||||
}));
|
||||
h.run_steps(3);
|
||||
click_field(&mut h, "country", 0);
|
||||
let country = field_rect(&h, "country");
|
||||
let france = text_rect(&h, "France").expect("drawn");
|
||||
assert!((france.center().x - country.center().x).abs() <= 2.0, "centered as the field is: {france:?} in {country:?}");
|
||||
}
|
||||
|
||||
/// The arrow keys move through an open drop-down's list without changing the value, Enter
|
||||
/// chooses the current item and closes the list, and a reopened list starts from the value.
|
||||
#[test]
|
||||
fn the_arrow_keys_move_through_a_drop_downs_list_and_enter_chooses() {
|
||||
let mut h = harness();
|
||||
click_field(&mut h, "country", 0);
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
h.run_steps(1);
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
h.run_steps(1);
|
||||
assert!(value(&h, "country").is_empty(), "the arrows only move through the list");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, "country"), ["fr"]);
|
||||
assert!(h.state().views[0].forms.focus.is_none(), "Enter closes the list");
|
||||
// Reopened, the list starts from the field's value.
|
||||
click_field(&mut h, "country", 0);
|
||||
h.key_press(egui::Key::ArrowUp);
|
||||
h.run_steps(1);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, "country"), ["ca"]);
|
||||
}
|
||||
|
||||
/// Pressing the scroll bar's down button moves a long drop-down list on one row, and End goes
|
||||
/// to the last item, which Enter then chooses.
|
||||
#[test]
|
||||
fn a_long_drop_down_list_scrolls_by_its_arrow_button_and_to_its_end() {
|
||||
let mut h = harness();
|
||||
long_country(&mut h);
|
||||
click_field(&mut h, "country", 0);
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0900").is_none(), "nine rows show");
|
||||
let country = field_rect(&h, "country");
|
||||
let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect();
|
||||
// The bar's down button, at the bottom of the bar beside the ninth row.
|
||||
let bar = country.right() - first.right();
|
||||
let down = egui::pos2(country.right() - bar / 2.0, first.top() + first.height() * 9.0 - bar / 2.0);
|
||||
h.hover_at(down);
|
||||
h.run_steps(1);
|
||||
h.drag_at(down);
|
||||
h.run_steps(1);
|
||||
h.drop_at(down);
|
||||
h.run_steps(2);
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0900").is_some(), "one row on");
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none());
|
||||
h.key_press(egui::Key::End);
|
||||
h.run_steps(2);
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "2900").is_some(), "End goes to the last item");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, "country"), ["2900"]);
|
||||
}
|
||||
|
||||
/// The mouse wheel over an open long drop-down scrolls its list and leaves the page where it was.
|
||||
#[test]
|
||||
fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() {
|
||||
let mut h = harness();
|
||||
long_country(&mut h);
|
||||
click_field(&mut h, "country", 0);
|
||||
let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect();
|
||||
let page = h.state().views[0].page_screen_rect(0);
|
||||
h.hover_at(first.center() + egui::vec2(0.0, first.height() * 4.0));
|
||||
h.run_steps(1);
|
||||
for _ in 0..3 {
|
||||
h.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
});
|
||||
h.run_steps(2);
|
||||
}
|
||||
h.run_steps(6);
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "the list scrolled down");
|
||||
assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was");
|
||||
}
|
||||
|
||||
/// Escape in an open drop-down closes its list and nothing else: the find bar, which Escape
|
||||
/// closes when no field is open, stays open.
|
||||
#[test]
|
||||
fn escape_closes_an_open_drop_downs_list_and_leaves_the_page_alone() {
|
||||
let mut h = harness();
|
||||
long_country(&mut h);
|
||||
h.state_mut().views[0].open_find();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().views[0].find.is_some());
|
||||
click_field(&mut h, "country", 0);
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_some(), "the list is open");
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "Escape closed the list");
|
||||
assert!(h.state().views[0].forms.focus.is_none(), "and the field");
|
||||
assert!(h.state().views[0].find.is_some(), "the find bar stays open");
|
||||
}
|
||||
|
||||
/// An auto-sized drop-down's list draws its items at the size the field shows its value at, so a
|
||||
/// long chosen item fits the list as it fits the field instead of growing past it.
|
||||
#[test]
|
||||
fn an_auto_sized_drop_downs_list_shows_its_items_at_the_fields_text_size() {
|
||||
let mut h = harness();
|
||||
let long = "The Commonwealth of the Northern Mariana Islands";
|
||||
assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps {
|
||||
name: "country".into(),
|
||||
props: Box::new(pdfcraft_engine::FieldProps { options: Some(vec!["Canada".into(), long.into()]), ..Default::default() }),
|
||||
}));
|
||||
assert!(
|
||||
h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldValue {
|
||||
name: "country".into(),
|
||||
value: pdfcraft_engine::FieldValue::Choice(vec![long.into()])
|
||||
})
|
||||
);
|
||||
h.run_steps(3);
|
||||
click_field(&mut h, "country", 0);
|
||||
let field = field_rect(&h, "country");
|
||||
let item = text_rect(&h, long).expect("the long item in the open list");
|
||||
assert!(item.width() <= field.width(), "the item fits as the field's value does: {} wide in a {} field", item.width(), field.width());
|
||||
}
|
||||
|
||||
/// In single-page view, where the wheel turns pages, the wheel over an open drop-down's list
|
||||
/// scrolls the list and leaves the page as it is; over the page itself it still turns it.
|
||||
#[test]
|
||||
fn in_single_page_view_the_wheel_over_an_open_list_scrolls_the_list_not_the_page() {
|
||||
let mut h = harness();
|
||||
long_country(&mut h);
|
||||
assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::InsertBlankPage { at: 1, width: 300.0, height: 400.0 }));
|
||||
h.state_mut().set_option("continuous", "off").unwrap();
|
||||
h.key_press(egui::Key::Home);
|
||||
for _ in 0..60 {
|
||||
h.run_steps(2);
|
||||
if !h.state().render_pending() && h.state().views[0].page_screen_rect(0).is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let wheel = |h: &mut Harness<'static, PdfCraftApp>, at: egui::Pos2| {
|
||||
h.hover_at(at);
|
||||
h.run_steps(1);
|
||||
for _ in 0..3 {
|
||||
h.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
});
|
||||
h.run_steps(2);
|
||||
}
|
||||
h.run_steps(6);
|
||||
};
|
||||
// The control: over the page, the wheel turns it.
|
||||
let page = h.state().views[0].page_screen_rect(0).expect("page 1 on screen");
|
||||
wheel(&mut h, page.center());
|
||||
assert_eq!(h.state().views[0].current, 1, "over the page, the wheel turns it");
|
||||
h.key_press(egui::Key::Home);
|
||||
h.run_steps(6);
|
||||
assert_eq!(h.state().views[0].current, 0);
|
||||
// Over the open list, it scrolls the list instead.
|
||||
click_field(&mut h, "country", 0);
|
||||
let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect();
|
||||
wheel(&mut h, first.center() + egui::vec2(0.0, first.height() * 4.0));
|
||||
assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "the list scrolled down");
|
||||
assert_eq!(h.state().views[0].current, 0, "the page didn't turn");
|
||||
}
|
||||
|
||||
/// With a page taller than the window and the pointer resting on an open drop-down's list,
|
||||
/// Home and the down arrow move through the list and leave the page where it was.
|
||||
#[test]
|
||||
fn an_open_drop_down_keeps_the_arrow_keys_and_home_from_moving_the_page() {
|
||||
let mut h = harness();
|
||||
long_country(&mut h);
|
||||
// A page taller than the window, so the keys would scroll it.
|
||||
h.state_mut().set_option("zoom", "300").unwrap();
|
||||
for _ in 0..30 {
|
||||
h.run_steps(2);
|
||||
if !h.state().render_pending() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
click_field(&mut h, "country", 0);
|
||||
// The pointer rests on the list, as it does after reaching for it.
|
||||
let row = egui_kittest::kittest::Queryable::get_by_label(&h, "0300").rect();
|
||||
h.hover_at(row.center());
|
||||
h.run_steps(2);
|
||||
let page = h.state().views[0].page_screen_rect(0);
|
||||
h.key_press(egui::Key::Home);
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, "country"), ["0100"], "one item down from the first");
|
||||
}
|
||||
|
||||
/// When End scrolls a drop-down's list under a resting pointer, Enter chooses the item End
|
||||
/// went to, not the one that came under the pointer.
|
||||
#[test]
|
||||
fn a_pointer_resting_on_a_list_the_keys_scroll_keeps_the_highlight_on_the_keys() {
|
||||
let mut h = harness();
|
||||
long_country(&mut h);
|
||||
click_field(&mut h, "country", 0);
|
||||
let row = egui_kittest::kittest::Queryable::get_by_label(&h, "0300").rect();
|
||||
h.hover_at(row.center());
|
||||
h.run_steps(2);
|
||||
// End scrolls the list, so another item comes under the resting pointer.
|
||||
h.key_press(egui::Key::End);
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, "country"), ["2900"], "the item End went to, not the one under the pointer");
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use egui::Pos2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use pdfcraft_ui_egui::{Dialog, PdfCraftApp};
|
||||
use pdfcraft_ui_egui::{Dialog, PdfCraftApp, SaveTarget};
|
||||
|
||||
fn harness() -> Harness<'static, PdfCraftApp> {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
|
||||
@@ -74,6 +74,417 @@ fn marking_applying_and_clearing() {
|
||||
assert!(doc.form.is_empty(), "the whole page was redacted, fields included");
|
||||
}
|
||||
|
||||
/// After Apply redactions, Save asks where instead of writing over the opened file, as Acrobat
|
||||
/// shows Save As with `_Redacted` appended to the name. Once that copy is written, Save writes
|
||||
/// it in place again.
|
||||
#[test]
|
||||
fn saving_after_applying_redactions_asks_where() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-save-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
let source = include_bytes!("../data/form.pdf").to_vec();
|
||||
std::fs::write(&original, &source).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(marks(&h), 1);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(marks(&h), 0);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 1);
|
||||
let copy = dir.join("contract_Redacted.pdf");
|
||||
h.state_mut().pick_override = Some(vec![copy.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace), "Save asks where first");
|
||||
h.run_steps(3);
|
||||
assert_eq!(std::fs::read(&original).unwrap(), source, "the opened file is left as it was");
|
||||
assert!(copy.exists(), "the redacted copy is written where the user chose");
|
||||
let s = h.state();
|
||||
assert_eq!(s.session.get(s.views[0].id).unwrap().name, "contract_Redacted.pdf");
|
||||
assert_eq!(s.views[0].redactions_applied, 0);
|
||||
h.state_mut().pick_override = None;
|
||||
assert!(h.state_mut().save_active(SaveTarget::InPlace), "the next Save writes the copy in place");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Undo past an Apply redactions that is already saved in the `_Redacted` copy makes Save ask
|
||||
/// where, so the restored content is not written over the copy. Redo makes Save write in place.
|
||||
#[test]
|
||||
fn undoing_saved_redactions_does_not_save_over_the_redacted_copy() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-saved-undo-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
let copy = dir.join("contract_Redacted.pdf");
|
||||
h.state_mut().pick_override = Some(vec![copy.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace));
|
||||
h.run_steps(3);
|
||||
h.state_mut().pick_override = None;
|
||||
assert!(copy.exists());
|
||||
// Undo and Redo leave the saved redactions in effect: Save writes the copy in place.
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
h.state_mut().execute("edit.redo");
|
||||
h.run_steps(3);
|
||||
assert_eq!((h.state().views[0].redactions_applied, h.state().views[0].redactions_undone_after_save), (0, 0));
|
||||
assert!(h.state_mut().save_active(SaveTarget::InPlace), "with the redactions back, Save writes the copy in place");
|
||||
let saved = std::fs::read(©).unwrap();
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_undone_after_save, 1);
|
||||
let elsewhere = dir.join("contract_restored.pdf");
|
||||
h.state_mut().pick_override = Some(vec![elsewhere.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace), "Save asks where instead of writing over the copy");
|
||||
h.run_steps(3);
|
||||
h.state_mut().pick_override = None;
|
||||
assert_eq!(std::fs::read(©).unwrap(), saved, "the redacted copy is left as it was");
|
||||
assert!(elsewhere.exists(), "the restored version is written where the user chose");
|
||||
assert_eq!(h.state().views[0].redactions_undone_after_save, 0);
|
||||
// The restored version is now the saved one: Redo applies the redactions to it again.
|
||||
h.state_mut().execute("edit.redo");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A new Apply redactions after Undo past a saved one clears Redo, so Undo and Redo of the new
|
||||
/// step do not bring Save in place back over the `_Redacted` copy.
|
||||
#[test]
|
||||
fn redoing_a_new_apply_after_undoing_saved_redactions_still_asks_where() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-branch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
let copy = dir.join("contract_Redacted.pdf");
|
||||
h.state_mut().pick_override = Some(vec![copy.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace));
|
||||
h.run_steps(3);
|
||||
h.state_mut().pick_override = None;
|
||||
let saved = std::fs::read(©).unwrap();
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
// Apply the marks again as a new step, then Undo and Redo it.
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
let view = &h.state().views[0];
|
||||
assert_eq!((view.redactions_applied, view.redactions_undone_after_save, view.saved_redactions_cut_off), (0, 0, true));
|
||||
h.state_mut().execute("edit.redo");
|
||||
h.run_steps(3);
|
||||
let elsewhere = dir.join("contract_again.pdf");
|
||||
h.state_mut().pick_override = Some(vec![elsewhere.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace), "Save asks where instead of writing over the copy");
|
||||
h.run_steps(3);
|
||||
h.state_mut().pick_override = None;
|
||||
assert_eq!(std::fs::read(©).unwrap(), saved, "the redacted copy is left as it was");
|
||||
assert!(!h.state().views[0].saved_redactions_cut_off);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// In the web build a delivered save keeps `redactions_applied` and records it in
|
||||
/// `redactions_downloaded`. Undo past a delivered Apply redactions, or a new Apply after it, makes
|
||||
/// Save ask where, so a host does not write the restored content over the redacted copy.
|
||||
#[test]
|
||||
fn undoing_delivered_redactions_asks_where() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-delivered-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
// The state a web save leaves: the step is delivered and stays counted.
|
||||
h.state_mut().views[0].redactions_downloaded = 1;
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
let elsewhere = dir.join("contract_restored.pdf");
|
||||
h.state_mut().pick_override = Some(vec![elsewhere.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace), "Save asks where after Undo past a delivered step");
|
||||
h.run_steps(3);
|
||||
h.state_mut().pick_override = None;
|
||||
assert!(elsewhere.exists());
|
||||
// A new Apply after Undo past a delivered step cannot be redone back to the delivered one.
|
||||
h.state_mut().views[0].redactions_downloaded = 1;
|
||||
h.state_mut().views[0].redactions_applied = 0;
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().views[0].saved_redactions_cut_off);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Once every Apply redactions step is delivered, Save writes in place again even though the web
|
||||
/// build keeps the steps counted for the `_Redacted` name.
|
||||
#[test]
|
||||
fn delivered_redactions_save_in_place() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-delivered-save-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
// The state a web save leaves: the step is delivered and stays counted.
|
||||
h.state_mut().views[0].redactions_downloaded = 1;
|
||||
assert!(h.state_mut().save_active(SaveTarget::InPlace), "Save writes in place after the step is delivered");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Undo past a saved Apply redactions while the Save dialog is open makes Save ask again, so the
|
||||
/// restored content is not written to the redacted copy the dialog proposed.
|
||||
#[test]
|
||||
fn undoing_saved_redactions_while_the_save_dialog_is_open_asks_again() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-dialog-undo-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
let apply = |h: &mut Harness<'static, PdfCraftApp>| {
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
};
|
||||
apply(&mut h);
|
||||
let copy = dir.join("contract_Redacted.pdf");
|
||||
h.state_mut().pick_override = Some(vec![copy.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace));
|
||||
h.run_steps(3);
|
||||
let saved = std::fs::read(©).unwrap();
|
||||
// A second Apply redactions makes Save ask where. Before the answer, Undo takes back the
|
||||
// second Apply, its marks and the saved Apply.
|
||||
apply(&mut h);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace));
|
||||
for _ in 0..3 {
|
||||
h.state_mut().execute("edit.undo");
|
||||
}
|
||||
assert_eq!(h.state().views[0].redactions_undone_after_save, 1);
|
||||
let elsewhere = dir.join("contract_restored.pdf");
|
||||
h.state_mut().pick_override = Some(vec![elsewhere.to_string_lossy().into_owned()]);
|
||||
h.run_steps(4);
|
||||
h.state_mut().pick_override = None;
|
||||
assert_eq!(std::fs::read(©).unwrap(), saved, "the redacted copy is left as it was");
|
||||
assert!(elsewhere.exists(), "Save asked again and wrote where the user chose");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Undo of Apply redactions while the Save dialog that proposed the `_Redacted` name is open
|
||||
/// makes Save ask again, so the unredacted content is not saved under that name.
|
||||
#[test]
|
||||
fn undoing_apply_redactions_while_the_save_dialog_is_open_asks_again() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-dialog-unapply-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
let copy = dir.join("contract_Redacted.pdf");
|
||||
h.state_mut().pick_override = Some(vec![copy.to_string_lossy().into_owned()]);
|
||||
assert!(!h.state_mut().save_active(SaveTarget::InPlace));
|
||||
h.state_mut().execute("edit.undo");
|
||||
assert_eq!(h.state().views[0].redactions_applied, 0);
|
||||
let elsewhere = dir.join("contract_copy.pdf");
|
||||
h.state_mut().pick_override = Some(vec![elsewhere.to_string_lossy().into_owned()]);
|
||||
h.run_steps(4);
|
||||
h.state_mut().pick_override = None;
|
||||
assert!(!copy.exists(), "the unredacted content is not saved under the _Redacted name");
|
||||
assert!(elsewhere.exists(), "Save asked again and wrote where the user chose");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Undo of Apply redactions brings back Save in place; Redo makes Save ask where again.
|
||||
#[test]
|
||||
fn undoing_apply_redactions_saves_in_place_again() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-undo-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
for _ in 0..2 {
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
assert_eq!(h.state().views[0].redactions_applied, 2);
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 1, "the first Apply redactions is still in effect");
|
||||
// Undoing the second mark leaves the first Apply redactions in effect.
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 1);
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 0);
|
||||
h.state_mut().execute("edit.redo");
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 1);
|
||||
h.state_mut().execute("edit.undo");
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().save_active(SaveTarget::InPlace), "with the redactions undone, Save writes in place");
|
||||
let s = h.state();
|
||||
assert_eq!(s.session.get(s.views[0].id).unwrap().name, "contract.pdf");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// File ▸ Revert discards the applied redactions, so Save writes the opened file in place again.
|
||||
#[test]
|
||||
fn reverting_after_apply_redactions_saves_in_place_again() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redacted-revert-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let original = dir.join("contract.pdf");
|
||||
std::fs::write(&original, include_bytes!("../data/form.pdf")).unwrap();
|
||||
let path = original.to_string_lossy().into_owned();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_path(&path);
|
||||
app
|
||||
});
|
||||
crate::support::settle(&mut h);
|
||||
h.state_mut().execute("redact.pages");
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state_mut().execute("redact.apply"));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Apply").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 1);
|
||||
assert!(h.state_mut().execute("file.revert"));
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog, Some(Dialog::Revert));
|
||||
h.get_all_by_label("Revert").last().expect("the button").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views[0].redactions_applied, 0);
|
||||
assert!(h.state_mut().save_active(SaveTarget::InPlace), "after Revert, Save writes in place");
|
||||
let s = h.state();
|
||||
assert_eq!(s.session.get(s.views[0].id).unwrap().name, "contract.pdf");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redaction_codes_become_the_overlay_text() {
|
||||
let mut h = harness();
|
||||
|
||||
@@ -2269,6 +2269,48 @@ fn an_fdf_comment_popup_without_a_rect_is_dropped() {
|
||||
assert_eq!(popups, 0);
|
||||
}
|
||||
|
||||
/// A check box field whose two kids have the on states `A` and `B`.
|
||||
fn check_box_kids() -> 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 [6 0 R 7 0 R] >>",
|
||||
"<< /Fields [5 0 R] >>",
|
||||
"<< /FT /Btn /T (pair) /V /Off /Kids [6 0 R 7 0 R] >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [50 700 64 714] /P 3 0 R /AP << /N << /A 8 0 R /Off 8 0 R >> >> >>",
|
||||
"<< /Type /Annot /Subtype /Widget /Parent 5 0 R /AS /Off /Rect [80 700 94 714] /P 3 0 R /AP << /N << /B 8 0 R /Off 8 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()
|
||||
}
|
||||
|
||||
/// Imported data that names a check box kid's on state ticks that kid (ISO 32000-2 §12.7.5.2.3:
|
||||
/// the field's value is the on state of the kid that is on), not the first kid.
|
||||
#[test]
|
||||
fn imported_values_tick_the_check_box_kid_they_name() {
|
||||
let mut src = check_box_kids();
|
||||
set_value(&mut src, "pair", &pdfcraft_forms::FieldValue::Text("B".into())).unwrap();
|
||||
let xfdf = export_xfdf(&src, false, true, "form.pdf");
|
||||
let mut dst = check_box_kids();
|
||||
import(&mut dst, xfdf.as_bytes()).unwrap();
|
||||
let all = fields(&dst);
|
||||
let pair = all.iter().find(|f| f.name == "pair").unwrap();
|
||||
assert_eq!(pair.value, ["B"], "{xfdf}");
|
||||
assert_eq!((pair.widget_on(0), pair.widget_on(1)), (false, true));
|
||||
}
|
||||
|
||||
/// Copy: the chosen comments travel with their replies and nothing else.
|
||||
#[test]
|
||||
fn exporting_selected_comments_takes_them_and_their_replies() {
|
||||
|
||||
@@ -837,7 +837,7 @@ pub(crate) fn apply_values(doc: &mut Document, values: &[(String, Vec<String>)],
|
||||
let first = vals.first().cloned().unwrap_or_default();
|
||||
let v = match f.kind {
|
||||
FieldKind::Text => FieldValue::Text(first),
|
||||
FieldKind::CheckBox => FieldValue::Check(!first.is_empty() && first != "Off"),
|
||||
FieldKind::CheckBox => f.check_box_value(Some(first.as_str())),
|
||||
FieldKind::Radio => FieldValue::Radio((!first.is_empty() && first != "Off").then_some(first)),
|
||||
// XML, CSV and text hold a multi-select list's values in one cell, joined by ", "
|
||||
// (as export_data writes them); split it unless the whole cell is one option.
|
||||
|
||||
@@ -1202,8 +1202,8 @@ milestone = "M3"
|
||||
status = "shipped"
|
||||
commands = []
|
||||
tools = ["link_open"]
|
||||
evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_escape_or_dismissal_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link"]
|
||||
notes = "GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. Named remote destinations open at default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); URL/network file systems, GoToE, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge."
|
||||
evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_escape_or_dismissal_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link", "crates/render/src/inspect/tests.rs::relative_uri_actions_resolve_against_the_catalog_base", "crates/render/src/inspect/tests.rs::links_are_active_in_their_quad_points", "crates/automation/tests/it/automation.rs::links_resolve_relative_addresses_and_report_their_quad_points"]
|
||||
notes = "A relative URI action resolves against the catalog's /URI /Base (ISO 32000-2 Table 211) when that base is an http(s) address, then goes through the usual check and confirmation; without a base, a relative address is still refused (resolving against the document's own location is not done). A link with valid /QuadPoints is active only inside them, otherwise over /Rect (Table 176); link_list reports resolved_url and active_areas. IsMap is not supported. GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. Named remote destinations open at default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); URL/network file systems, GoToE, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge."
|
||||
|
||||
[[feature]]
|
||||
id = "view.annotation-hover"
|
||||
@@ -1418,8 +1418,8 @@ milestone = "M3"
|
||||
status = "shipped"
|
||||
commands = ["edit.find"]
|
||||
tools = ["text_find"]
|
||||
evidence = ["crates/ui-egui/tests/it/ui.rs::find_counts_matches_across_pages", "crates/ui-egui/tests/it/ui.rs::find_reports_no_matches", "crates/automation/tests/it/automation.rs::open_inspect_render_and_find", "crates/render/src/text/tests.rs::identity_v_columns_are_searchable_in_reading_order", "crates/render/src/text/tests.rs::toc_leaders_do_not_hide_word_gaps", "crates/render/src/text/tests.rs::short_tracked_ellipses_remain_searchable", "crates/render/tests/it/search.rs::find_skips_soft_hyphens_and_zero_width_characters", "crates/render/tests/it/search.rs::find_joins_a_word_divided_at_a_line_end_soft_hyphen", "crates/render/tests/it/search.rs::a_zero_width_space_is_a_word_boundary_for_whole_words", "crates/render/tests/it/search.rs::a_chinese_or_japanese_word_divided_by_a_line_end_is_found_on_both_lines", "crates/render/tests/it/search.rs::a_line_break_stays_a_space_beside_latin_or_hangul_and_between_side_by_side_text", "crates/render/tests/it/search.rs::a_word_divided_between_vertical_columns_is_found_in_both", "crates/render/tests/it/search.rs::each_unspaced_range_joins_and_spaced_scripts_do_not", "crates/render/tests/it/search.rs::a_soft_hyphen_and_a_chinese_or_japanese_line_end_combine", "crates/render/src/text/tests.rs::thai_marks_drawn_one_glyph_at_a_time_keep_their_place_and_words"]
|
||||
notes = "Horizontal and WMode 1 vertical text are grouped independently, including a horizontal heading above right-to-left vertical columns. Dotted TOC leaders preserve word spaces for phrase search (#3086), while short tracked ellipses remain intact and searchable; sparse lines and condensed OCR gaps below the existing height-based threshold remain limitations. Combining marks (Mn/Me) of left-to-right scripts drawn right after their letter stay with it in content order, and Thai or Indic word gaps without a space glyph are found as spaces (#6517). Complex interleaved flows still use a geometric reading-order heuristic. Soft hyphens, zero width spaces and joiners, word joiners and U+FEFF inside a word are skipped, in the page and in the query; a skipped zero width space still ends a word for Whole words only. A line break reads as no word break when the line ends in a soft hyphen, or when it runs on between two Chinese or Japanese characters (East Asian Wide, Fullwidth or Halfwidth, not Hangul and not fullwidth Latin letters or digits), so a divided word is found, in horizontal lines and in vertical columns that continue to the left; the break stays a space beside Latin or Korean text and between text set side by side on one line or in staggered cells."
|
||||
evidence = ["crates/ui-egui/tests/it/ui.rs::find_counts_matches_across_pages", "crates/ui-egui/tests/it/ui.rs::find_reports_no_matches", "crates/automation/tests/it/automation.rs::open_inspect_render_and_find", "crates/render/src/text/tests.rs::identity_v_columns_are_searchable_in_reading_order", "crates/render/src/text/tests.rs::toc_leaders_do_not_hide_word_gaps", "crates/render/src/text/tests.rs::short_tracked_ellipses_remain_searchable", "crates/render/tests/it/search.rs::find_skips_soft_hyphens_and_zero_width_characters", "crates/render/tests/it/search.rs::find_joins_a_word_divided_at_a_line_end_soft_hyphen", "crates/render/tests/it/search.rs::a_zero_width_space_is_a_word_boundary_for_whole_words", "crates/render/tests/it/search.rs::a_chinese_or_japanese_word_divided_by_a_line_end_is_found_on_both_lines", "crates/render/tests/it/search.rs::a_line_break_stays_a_space_beside_latin_or_hangul_and_between_side_by_side_text", "crates/render/tests/it/search.rs::a_word_divided_between_vertical_columns_is_found_in_both", "crates/render/tests/it/search.rs::each_unspaced_range_joins_and_spaced_scripts_do_not", "crates/render/tests/it/search.rs::a_soft_hyphen_and_a_chinese_or_japanese_line_end_combine", "crates/render/src/text/tests.rs::thai_marks_drawn_one_glyph_at_a_time_keep_their_place_and_words", "crates/render/tests/it/search.rs::a_ligature_matches_its_letters", "crates/render/tests/it/search.rs::a_word_divided_by_a_line_end_hyphen_matches_whole_and_as_written", "crates/automation/tests/it/find_text.rs::text_find_matches_ligatures_and_words_divided_at_a_line_end"]
|
||||
notes = "Horizontal and WMode 1 vertical text are grouped independently, including a horizontal heading above right-to-left vertical columns. Dotted TOC leaders preserve word spaces for phrase search (#3086), while short tracked ellipses remain intact and searchable; sparse lines and condensed OCR gaps below the existing height-based threshold remain limitations. Combining marks (Mn/Me) of left-to-right scripts drawn right after their letter stay with it in content order, and Thai or Indic word gaps without a space glyph are found as spaces (#6517). Complex interleaved flows still use a geometric reading-order heuristic. Soft hyphens, zero width spaces and joiners, word joiners and U+FEFF inside a word are skipped, in the page and in the query; a skipped zero width space still ends a word for Whole words only. A line break reads as no word break when the line ends in a soft hyphen, or when it runs on between two Chinese or Japanese characters (East Asian Wide, Fullwidth or Halfwidth, not Hangul and not fullwidth Latin letters or digits), so a divided word is found, in horizontal lines and in vertical columns that continue to the left; the break stays a space beside Latin or Korean text and between text set side by side on one line or in staggered cells. A Latin ligature (U+FB00–FB06) matches its letters, and a word divided by a hyphen (U+002D or U+2010) between letters at a line end matches whole, highlighted on both lines, as well as with the hyphen. Missing: accent-insensitive matching (an unaccented query finding accented text; an open pull request adds it)."
|
||||
|
||||
[[feature]]
|
||||
id = "view.find-next-previous"
|
||||
@@ -4650,8 +4650,8 @@ milestone = "M6"
|
||||
status = "shipped"
|
||||
commands = ["form.fields"]
|
||||
tools = ["form_fill"]
|
||||
evidence = ["crates/ui-egui/tests/it/forms.rs::check_boxes_radios_and_choices", "crates/forms/src/tests.rs::check_boxes_and_radios_switch_states", "crates/ui-egui/tests/it/forms.rs::tab_and_space_fill_in_a_check_box_between_text_fields", "crates/ui-egui/tests/it/forms.rs::clicking_a_check_box_while_typing_keeps_the_text_and_focuses_the_box", "crates/ui-egui/tests/it/forms.rs::radio_buttons_take_tab_space_and_arrows", "crates/forms/src/tests.rs::a_round_xfa_check_button_draws_a_round_background_and_border", "crates/xfa/src/tests.rs::round_check_buttons_are_marked_for_a_round_appearance", "crates/engine/src/tests.rs::round_xfa_check_buttons_open_drawn_round", "crates/forms/src/tests.rs::radio_buttons_sharing_an_on_state_are_exclusive_unless_in_unison", "crates/ui-egui/tests/it/forms.rs::clicking_a_radio_button_that_shares_its_on_state", "crates/ui-egui/tests/it/forms.rs::a_read_only_radio_button_is_focused_but_not_selected", "crates/automation/tests/it/automation.rs::form_fill_picks_one_of_radio_buttons_sharing_an_on_state"]
|
||||
notes = "NoToggleToOff honoured; widgets without appearances get our own, drawn round for an XFA check button with shape=\"round\" (its background and border a circle inside the widget, as another viewer draws them on a synthetic form). Tab and Shift+Tab stop on check boxes and on each radio button, Space toggles the focused one, and the arrows move within a radio group (#2223); a click focuses the box too. Radio buttons sharing an on state follow RadiosInUnison (ISO 32000-2 Table 229): with it they turn on together, without it only the clicked one does (its /AS; /V names the shared state), which survives a save; form_fill takes {\"widget\": n} for the same and form_fields lists on_widgets. Without NoToggleToOff a second click deselects the button. Not yet: telling such buttons apart in exported form data (FDF/XFDF carry /V only)"
|
||||
evidence = ["crates/ui-egui/tests/it/forms.rs::check_boxes_radios_and_choices", "crates/forms/src/tests.rs::check_boxes_and_radios_switch_states", "crates/ui-egui/tests/it/forms.rs::tab_and_space_fill_in_a_check_box_between_text_fields", "crates/ui-egui/tests/it/forms.rs::clicking_a_check_box_while_typing_keeps_the_text_and_focuses_the_box", "crates/ui-egui/tests/it/forms.rs::radio_buttons_take_tab_space_and_arrows", "crates/forms/src/tests.rs::a_round_xfa_check_button_draws_a_round_background_and_border", "crates/xfa/src/tests.rs::round_check_buttons_are_marked_for_a_round_appearance", "crates/engine/src/tests.rs::round_xfa_check_buttons_open_drawn_round", "crates/forms/src/tests.rs::radio_buttons_sharing_an_on_state_are_exclusive_unless_in_unison", "crates/ui-egui/tests/it/forms.rs::clicking_a_radio_button_that_shares_its_on_state", "crates/ui-egui/tests/it/forms.rs::a_read_only_radio_button_is_focused_but_not_selected", "crates/automation/tests/it/automation.rs::form_fill_picks_one_of_radio_buttons_sharing_an_on_state", "crates/forms/src/tests.rs::check_box_kids_with_different_on_states_tick_one_at_a_time", "crates/ui-egui/tests/it/forms.rs::clicking_check_box_kids_with_different_on_states", "crates/automation/tests/it/automation.rs::form_fill_ticks_one_kid_of_a_check_box_by_its_on_state", "crates/xfdf/src/tests.rs::imported_values_tick_the_check_box_kid_they_name"]
|
||||
notes = "NoToggleToOff honoured; widgets without appearances get our own, drawn round for an XFA check button with shape=\"round\" (its background and border a circle inside the widget, as another viewer draws them on a synthetic form). Tab and Shift+Tab stop on check boxes and on each radio button, Space toggles the focused one, and the arrows move within a radio group (#2223); a click focuses the box too. Radio buttons sharing an on state follow RadiosInUnison (ISO 32000-2 Table 229): with it they turn on together, without it only the clicked one does (its /AS; /V names the shared state), which survives a save; form_fill takes {\"widget\": n} for the same and form_fields lists on_widgets. Without NoToggleToOff a second click deselects the button. A check box whose kids have different on states (ISO 32000-2 §12.7.5.2.3, Table 230) ticks the kid clicked and clears the others, and a second click clears the field; kids sharing an on state tick together. Named values, a reset to /DV, script changes and imported form data tick the kid whose on state they name; form_fill takes the name and form_fields lists the options and the checked one. Not yet: telling such buttons apart in exported form data (FDF/XFDF carry /V only); two same-name field dictionaries (rather than kids) whose on states differ share only the first one's state"
|
||||
|
||||
[[feature]]
|
||||
id = "form.fill-choice"
|
||||
@@ -4661,9 +4661,9 @@ tier = "P0"
|
||||
milestone = "M6"
|
||||
status = "shipped"
|
||||
commands = ["form.fields"]
|
||||
tools = ["form_fill"]
|
||||
evidence = ["crates/ui-egui/tests/it/forms.rs::check_boxes_radios_and_choices", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text", "crates/ui-egui/tests/it/forms.rs::an_editable_combo_box_takes_a_typed_value", "crates/ui-egui/tests/it/forms.rs::a_combo_box_without_edit_takes_no_typing", "crates/automation/tests/it/automation.rs::form_fill_takes_free_text_only_in_an_editable_combo_box"]
|
||||
notes = "combo and list boxes, multi-select lists; an editable combo box (Edit flag) has a text box over the field as well as its list, and takes typed text on the page and through form_fill; a combo box without Edit takes only its options. No type-ahead or spell check in the typed box"
|
||||
tools = ["form_fill", "form_fields"]
|
||||
evidence = ["crates/ui-egui/tests/it/forms.rs::check_boxes_radios_and_choices", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text", "crates/ui-egui/tests/it/forms.rs::an_editable_combo_box_takes_a_typed_value", "crates/ui-egui/tests/it/forms.rs::a_combo_box_without_edit_takes_no_typing", "crates/automation/tests/it/automation.rs::form_fill_takes_free_text_only_in_an_editable_combo_box", "crates/forms/src/tests.rs::a_list_box_with_duplicate_export_values_selects_the_option_i_names", "crates/forms/src/tests.rs::an_unusable_i_falls_back_to_the_first_option_with_the_value", "crates/forms/src/tests.rs::picking_one_of_two_options_with_the_same_export_value_round_trips", "crates/ui-egui/tests/it/forms.rs::a_list_box_click_picks_one_of_two_options_with_the_same_export_value", "crates/automation/tests/it/list_selection.rs::form_fields_reports_which_of_two_options_with_one_export_value_is_selected", "crates/forms/src/tests.rs::a_single_select_list_given_several_values_shows_the_first", "crates/forms/src/tests.rs::picking_in_a_single_select_list_given_several_values_writes_one", "crates/ui-egui/tests/it/forms.rs::a_single_select_list_box_given_two_values_shows_and_takes_one", "crates/automation/tests/it/list_selection.rs::form_fields_reports_one_value_for_a_single_select_list_given_two", "crates/ui-egui/tests/it/forms.rs::a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name", "crates/ui-egui/tests/it/forms.rs::the_arrow_keys_move_through_a_drop_downs_list_and_enter_chooses"]
|
||||
notes = "combo and list boxes, multi-select lists; an editable combo box (Edit flag) has a text box over the field as well as its list, and takes typed text on the page and through form_fill; a combo box without Edit takes only its options. a list box whose options share an export value shows and picks the one /I names (ISO 32000-2 Table 234): /I is used when it is integers, ascending, in range and names the same export values as /V, otherwise /V decides and each value selects the first option exporting it; a click or arrow key picks the row by position and writes its export value to /V and its position to /I, and form_fields reports selected (1-based positions); a list box without MultiSelect given an array /V or /DV holds, shows and resets to the first value only (Table 233), leaving the file as it is until the field is filled, when /V becomes one string and /I its position. A combo box shows its arrow on screen and opens its list under the field, as wide as the box, in its text size and alignment, black on white with a highlight that follows the pointer; more than nine items get a scroll bar with step buttons, the wheel scrolls it, and the arrow keys, Page Up/Down, Home and End move through it, Enter choosing (in an editable combo box the keys are its text box's, and the list takes the pointer). The list is drawn in the interface font, not the field's (no serif interface font ships yet). No type-ahead or spell check in the typed box; a combo box whose options share an export value still shows the first of them"
|
||||
|
||||
[[feature]]
|
||||
id = "form.push-buttons"
|
||||
@@ -6000,11 +6000,11 @@ title = "Add a suffix to redacted file names"
|
||||
area = "G"
|
||||
tier = "P3"
|
||||
milestone = "M8"
|
||||
status = "planned"
|
||||
commands = []
|
||||
tools = []
|
||||
evidence = []
|
||||
notes = ""
|
||||
status = "shipped"
|
||||
commands = ["redact.apply", "file.save"]
|
||||
tools = ["redact_apply"]
|
||||
evidence = ["crates/ui-egui/tests/it/redact.rs::saving_after_applying_redactions_asks_where", "crates/automation/tests/it/automation.rs::applying_redactions_proposes_the_name_with_redacted", "crates/redact/src/tests.rs::redacted_copies_are_named_with_redacted_before_the_extension"]
|
||||
notes = "After Apply redactions, Save asks where and proposes the name with _Redacted before the extension (contract.pdf gives contract_Redacted.pdf; a name already ending in _Redacted keeps one); the web build downloads under that name. redact_apply returns the same name in save_as, for doc_save's path; doc_save without a path still writes in place. The suffix is fixed: there is no preference to change it or to use a prefix."
|
||||
|
||||
[[feature]]
|
||||
id = "protect.redact-ai-suggestions"
|
||||
@@ -6223,8 +6223,8 @@ milestone = "M9"
|
||||
status = "shipped"
|
||||
commands = ["sign.digital"]
|
||||
tools = ["sign_document"]
|
||||
evidence = ["crates/sign/tests/it/pdf.rs::signing_an_existing_field_and_counter_signing", "crates/ui-egui/tests/it/signing.rs::clicking_an_empty_signature_field_signs_it"]
|
||||
notes = ""
|
||||
evidence = ["crates/sign/tests/it/pdf.rs::signing_an_existing_field_and_counter_signing", "crates/ui-egui/tests/it/signing.rs::clicking_an_empty_signature_field_signs_it", "crates/ui-egui/src/canvas/sign_tab_tests.rs::empty_signature_fields_show_a_sign_tab_that_signs_them", "crates/ui-egui/src/canvas/sign_tab_tests.rs::sign_tabs_skip_fields_that_a_click_cannot_sign"]
|
||||
notes = "Clicking an empty signature field signs it (Use a certificate for that field). With the Select tool, each empty field a click would sign (filling allowed, the field not read-only, its widget shown) carries a small accent tab in its top-left corner, sized to the field (0.4 of its height on screen, from 10 to 18 pt): the signature icon and Sign from 14 pt up, the icon alone below that or when the label would take more than half the field's width, and no tab on a field too small for the 10 pt chip. The tab is screen-only chrome, never written into the file, exports or printing, and is hidden while preparing a form. Headless, the fields it marks are the ones sign_list reports unsigned and visible on a page, with their rect, that form_fields doesn't report read-only. Missing: the tab is painted only, with no accessibility node or keyboard focus of its own"
|
||||
|
||||
[[feature]]
|
||||
id = "sign.invisible-signature"
|
||||
|
||||
Reference in new issue
Block a user