pdf-workflows-w9: net change of 2 commits

- pdf-workflows-w9: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot)
- pdf-workflows-w9: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:28 -05:00
parent e700a0019e
commit 34c0d01559
3 changed files with 724 additions and 460 deletions
+144 -83
View File
@@ -3,13 +3,20 @@
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use craft::behavior::{DisplayOrder, ItemSource, Selection, SelectionChange};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, CollectionEvent, Outcome as _, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::display::{Shade, Text};
use craft::ui::form::{Field, FieldGroup};
use craft::ui::list::{List, ListRow};
use craft::ui::notices::Notice;
use craft::ui::text::TextField;
use egui::Ui;
use pdfcraft_cos::ObjRef;
use pdfcraft_engine::a11y::{TagContentItem, TagInfo, TagPlacement, TagProperty};
use pdfcraft_engine::{DocId, Edit};
use crate::{icons, theme::Tokens, widgets};
#[derive(Clone, Debug, Default)]
pub(crate) struct State {
doc: Option<DocId>,
@@ -119,10 +126,76 @@ impl State {
}
}
/// The tags in display order, as the list shows them.
struct TagRows<'a> {
rows: &'a [&'a TagInfo],
parents: &'a HashSet<ObjRef>,
collapsed: &'a BTreeSet<ObjRef>,
/// A search lists matches with their ancestors and ignores collapsed groups, so no row is a group then.
searching: bool,
selected: Option<ObjRef>,
/// An unsaved draft keeps every other row from being selected.
dirty: bool,
}
impl TagRows<'_> {
fn is_group(&self, tag: &TagInfo) -> bool {
self.parents.contains(&tag.object) && !self.searching
}
}
impl DisplayOrder<ObjRef> for TagRows<'_> {
fn len(&self) -> usize {
self.rows.len()
}
fn key(&self, at: usize) -> ObjRef {
// The list never asks past `len()`; object 0 is a key no tag has.
self.rows.get(at).map_or_else(|| ObjRef::new(0, 0), |tag| tag.object)
}
fn depth(&self, at: usize) -> usize {
self.rows.get(at).map_or(0, |tag| tag.depth)
}
fn has_children(&self, at: usize) -> bool {
self.rows.get(at).is_some_and(|tag| self.is_group(tag))
}
fn open(&self, at: usize) -> bool {
self.rows.get(at).is_some_and(|tag| self.is_group(tag) && !self.collapsed.contains(&tag.object))
}
fn enabled(&self, at: usize) -> bool {
self.rows.get(at).is_some_and(|tag| !self.dirty || self.selected == Some(tag.object))
}
}
impl ItemSource<ObjRef> for TagRows<'_> {}
/// A list of `count` rows keyed by position.
struct Positions(usize);
impl DisplayOrder<usize> for Positions {
fn len(&self) -> usize {
self.0
}
fn key(&self, at: usize) -> usize {
at
}
}
impl ItemSource<usize> for Positions {}
/// The label of a marked-content row.
fn content_label(item: &TagContentItem) -> String {
let page_label = item.page.map(|p| crate::i18n::fmt(tl!("Go to page {p}"), &[("p", &(p + 1).to_string())]));
match (&page_label, item.text.trim()) {
(Some(page), text) if !text.is_empty() => format!("MCID {} · {page} · {text}", item.mcid),
(Some(page), _) => format!("MCID {} · {page}", item.mcid),
(_, text) if !text.is_empty() => format!("MCID {} · {text}", item.mcid),
_ => format!("MCID {}", item.mcid),
}
}
/// The chosen page and an edit to apply after the panel releases its document borrow.
pub(crate) fn panel(
ui: &mut Ui,
t: &Tokens,
doc: DocId,
tags: &[TagInfo],
content: &[TagContentItem],
@@ -137,106 +210,103 @@ pub(crate) fn panel(
state.collapsed.clear();
}
if tags.is_empty() {
ui.label(tl!("This document has no editable structure tags."));
Notice::new(Tone::Neutral, tl!("This document has no editable structure tags.")).show(ui);
return (None, None);
}
if state.selected.is_none_or(|r| !tags.iter().any(|t| t.object == r)) {
state.selected = Some(tags[0].object);
state.draft = Draft::from_tag(&tags[0]);
}
let search_label = ui.label(tl!("Find a tag"));
ui.add(egui::TextEdit::singleline(&mut state.query).hint_text(tl!("Find a tag"))).labelled_by(search_label.id);
ui.add_space(4.0);
TextField::new(tl!("Find a tag"), Bind::bound(&mut state.query)).show(ui);
let query = state.query.to_lowercase();
let matching = visible_tags(tags, &query, &state.collapsed);
let parents: HashSet<ObjRef> = tags.iter().filter_map(|tag| tag.parent).collect();
let dirty = state.selected.and_then(|r| tags.iter().find(|t| t.object == r)).is_some_and(|tag| state.draft.edit(tag).is_some());
ui.label(egui::RichText::new(crate::i18n::fmt(tl!("{n} tags"), &[("n", &matching.len().to_string())])).small().color(t.text_muted));
Text::new(crate::i18n::fmt(tl!("{n} tags"), &[("n", &matching.len().to_string())])).shade(Shade::Muted).show(ui);
let mut page = None;
egui::ScrollArea::vertical().max_height(100.0).show_rows(ui, 26.0, matching.len(), |ui, range| {
for tag in &matching[range] {
let source = TagRows { rows: &matching, parents: &parents, collapsed: &state.collapsed, searching: !query.is_empty(), selected: state.selected, dirty };
let mut picked = match state.selected {
Some(object) => Selection::single(object),
None => Selection::new(Vec::new(), None, None),
};
let out = List::<ObjRef>::new(tl!("Tags"))
.tree(true)
.natural_height(true)
.select(SelectMode::Single)
.selection(Bind::bound(&mut picked))
.show_items(ui, &source, &mut |key, _| {
let Some(tag) = matching.iter().find(|tag| tag.object == *key) else { return ListRow::new("") };
let title = tag.title.as_deref().filter(|s| !s.is_empty()).unwrap_or(&tag.kind);
let label = format!("{title} · {}", tag.object.num);
ui.horizontal(|ui| {
ui.add_space((tag.depth.min(8) as f32) * 12.0);
if parents.contains(&tag.object) && query.is_empty() {
let closed = state.collapsed.contains(&tag.object);
if icons::button(
ui,
if closed { "chevron-right" } else { "chevron-down" },
18.0,
false,
if closed { tl!("Expand tag") } else { tl!("Collapse tag") },
)
.clicked()
{
if closed {
state.collapsed.remove(&tag.object);
} else {
state.collapsed.insert(tag.object);
}
}
let row = ListRow::new(format!("{title} · {}", tag.object.num)).depth(tag.depth);
if source.is_group(tag) { row.group(!source.collapsed.contains(&tag.object)) } else { row }
});
for event in &out.events {
match event {
CollectionEvent::Open(change) => {
if change.open {
state.collapsed.remove(&change.key);
} else {
ui.add_space(18.0);
state.collapsed.insert(change.key);
}
if ui
.add_enabled(!dirty || state.selected == Some(tag.object), egui::Button::selectable(state.selected == Some(tag.object), label))
.clicked()
{
}
CollectionEvent::Selection(SelectionChange::Set(keys)) => {
if let Some(tag) = keys.last().and_then(|key| tags.iter().find(|tag| tag.object == *key)) {
state.selected = Some(tag.object);
state.draft = Draft::from_tag(tag);
page = tag.page;
}
});
}
_ => {}
}
});
ui.separator();
}
let Some(tag) = state.selected.and_then(|r| tags.iter().find(|t| t.object == r)) else { return (page, None) };
ui.label(egui::RichText::new(format!("{} {} R", tag.object.num, tag.object.generation)).small().color(t.text_faint));
Text::new(format!("{} {} R", tag.object.num, tag.object.generation)).shade(Shade::Muted).show(ui);
if let Some(p) = tag.page
&& ui.button(crate::i18n::fmt(tl!("Go to page {p}"), &[("p", &(p + 1).to_string())])).clicked()
&& Button::new(crate::i18n::fmt(tl!("Go to page {p}"), &[("p", &(p + 1).to_string())])).show(ui).response().clicked()
{
page = Some(p);
}
ui.add_enabled_ui(can_edit, |ui| {
field(ui, tl!("Tag type"), &mut state.draft.kind, false);
field(ui, tl!("Title"), &mut state.draft.title, false);
field(ui, tl!("Actual text"), &mut state.draft.actual_text, true);
field(ui, tl!("Alternate text"), &mut state.draft.alt, true);
field(ui, tl!("Language"), &mut state.draft.language, false);
let draft = &mut state.draft;
FieldGroup::new(tl!("Tag properties")).show(ui, |ui, _| {
Field::new(tl!("Tag type")).show(ui, |ui, _| {
TextField::new(tl!("Tag type"), Bind::bound(&mut draft.kind)).enabled(can_edit).show(ui);
});
Field::new(tl!("Title")).show(ui, |ui, _| {
TextField::new(tl!("Title"), Bind::bound(&mut draft.title)).enabled(can_edit).show(ui);
});
Field::new(tl!("Actual text")).show(ui, |ui, _| {
TextField::new(tl!("Actual text"), Bind::bound(&mut draft.actual_text)).lines(2).enabled(can_edit).show(ui);
});
Field::new(tl!("Alternate text")).show(ui, |ui, _| {
TextField::new(tl!("Alternate text"), Bind::bound(&mut draft.alt)).lines(2).enabled(can_edit).show(ui);
});
Field::new(tl!("Language")).show(ui, |ui, _| {
TextField::new(tl!("Language"), Bind::bound(&mut draft.language)).enabled(can_edit).show(ui);
});
});
let edit = state.draft.edit(tag);
let mut save = false;
let siblings: Vec<&TagInfo> = tag.parent.map(|parent| tags.iter().filter(|other| other.parent == Some(parent)).collect()).unwrap_or_default();
let position = siblings.iter().position(|sibling| sibling.object == tag.object);
let before = position.and_then(|position| position.checked_sub(1)).map(|position| siblings[position]);
let before = position.and_then(|position| position.checked_sub(1)).and_then(|position| siblings.get(position).copied());
let after = position.and_then(|position| siblings.get(position + 1)).copied();
ui.horizontal(|ui| {
save = ui.add_enabled(can_edit && !state.draft.kind.is_empty() && edit.is_some(), egui::Button::new(tl!("Save tag properties"))).clicked();
if ui.add_enabled(dirty, egui::Button::new(tl!("Revert changes"))).clicked() {
state.draft = Draft::from_tag(tag);
}
});
let (mut earlier, mut later, mut artifact) = (false, false, false);
ui.horizontal(|ui| {
earlier = ui.add_enabled(can_edit && !dirty && before.is_some(), egui::Button::new(tl!("Move tag earlier"))).clicked();
later = ui.add_enabled(can_edit && !dirty && after.is_some(), egui::Button::new(tl!("Move tag later"))).clicked();
artifact = ui
.add_enabled(can_edit && !dirty, egui::Button::new(tl!("Mark as artifact")))
.on_hover_text(tl!("Remove this leaf tag from reading order and mark its direct content as an artifact"))
.clicked();
});
ui.separator();
for item in content {
let page_label = item.page.map(|p| crate::i18n::fmt(tl!("Go to page {p}"), &[("p", &(p + 1).to_string())]));
let label = match (&page_label, item.text.trim()) {
(Some(page), text) if !text.is_empty() => format!("MCID {} · {page} · {text}", item.mcid),
(Some(page), _) => format!("MCID {} · {page}", item.mcid),
(_, text) if !text.is_empty() => format!("MCID {} · {text}", item.mcid),
_ => format!("MCID {}", item.mcid),
};
if ui.button(label).clicked() {
page = item.page;
let save = Button::new(tl!("Save tag properties")).enabled(can_edit && !state.draft.kind.is_empty() && edit.is_some()).show(ui).response().clicked();
if Button::new(tl!("Revert changes")).enabled(dirty).show(ui).response().clicked() {
state.draft = Draft::from_tag(tag);
}
let earlier = Button::new(tl!("Move tag earlier")).enabled(can_edit && !dirty && before.is_some()).show(ui).response().clicked();
let later = Button::new(tl!("Move tag later")).enabled(can_edit && !dirty && after.is_some()).show(ui).response().clicked();
let artifact = Button::new(tl!("Mark as artifact")).enabled(can_edit && !dirty).show(ui).response().clicked();
let mut chosen = Selection::new(Vec::new(), None, None);
let marked = List::<usize>::new(tl!("Marked content"))
.natural_height(true)
.select(SelectMode::Single)
.selection(Bind::bound(&mut chosen))
.show_items(ui, &Positions(content.len()), &mut |key, _| ListRow::new(content.get(*key).map(content_label).unwrap_or_default()));
for event in &marked.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(item) = keys.last().and_then(|key| content.get(*key))
{
page = item.page.or(page);
}
}
(
@@ -282,12 +352,3 @@ fn visible_tags<'a>(tags: &'a [TagInfo], query: &str, collapsed: &BTreeSet<ObjRe
}
tags.iter().filter(|tag| show.contains(&tag.object)).collect()
}
fn field(ui: &mut Ui, label: &str, value: &mut String, multiline: bool) {
let l = ui.label(label);
if multiline {
ui.add(widgets::block(value).desired_rows(2).desired_width(f32::INFINITY)).labelled_by(l.id);
} else {
ui.add(egui::TextEdit::singleline(value).desired_width(f32::INFINITY)).labelled_by(l.id);
}
}
File diff suppressed because it is too large Load Diff
+32 -16
View File
@@ -1,11 +1,14 @@
//! Prepare for accessibility ▸ Check for accessibility in the real shell (egui_kittest): the
//! options dialog, the results panel, Fix, Skip Rule and the report.
use std::sync::Arc;
use craft::host::ScriptedFiles;
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use pdfcraft_engine::a11y::{Rule, Status};
use pdfcraft_ui_egui::{Dialog, PdfCraftApp, RightPanel};
use pdfcraft_ui_egui::{PdfCraftApp, RightPanel};
const FIXTURE: &[u8] = b"%PDF-1.7
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
@@ -60,15 +63,14 @@ fn automatic_text_tagging_opens_reviewable_tags() {
#[test]
fn checking_fixing_skipping_and_reporting() {
let dir = std::env::temp_dir().join(format!("pdfcraft-a11y-ui-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let d = dir.clone();
let files = Arc::new(ScriptedFiles::new().saving_suggested());
let scripted = files.clone();
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_bytes("notes.pdf", None, FIXTURE.to_vec()).unwrap();
app.export_dir_override = Some(d.to_string_lossy().into_owned());
// PLAN: assumed `PdfCraftApp::set_files(Arc<dyn Files>)` (pdf-workflows-w13, A-6)
app.set_files(scripted);
app
});
h.run_steps(4);
@@ -79,7 +81,7 @@ fn checking_fixing_skipping_and_reporting() {
h.get_by_label("Document title is showing in title bar");
h.get_by_label("Start Checking").click();
h.run_steps(3);
assert_eq!(h.state().dialog, None);
assert!(h.state().dialogs.is_empty());
assert_eq!(h.state().right, Some(RightPanel::Accessibility));
h.get_by_label("Document (3 issues)");
h.get_by_label("Title - Failed");
@@ -90,10 +92,11 @@ fn checking_fixing_skipping_and_reporting() {
h.run_steps(3);
assert_eq!(status(&h, Rule::Title), Status::Passed);
assert_eq!(h.state().a11y.previous.as_ref().unwrap().1.result(Rule::Title).unwrap().status, Status::Failed);
assert!(matches!(h.state().dialog, Some(Dialog::Properties(_))));
assert!(!h.state().dialogs.is_empty(), "Document Properties opens to edit the title");
assert_eq!(h.state().window_title, "notes • — PdfCraft");
h.state_mut().dialog = None;
h.get_by_label("Cancel").click();
h.run_steps(2);
assert!(h.state().dialogs.is_empty());
h.get_by_label("Compare");
h.get_by_label_contains("Title: Failed (2) → Passed (0)");
// Skip a rule; it stays skipped when checking again.
@@ -110,12 +113,18 @@ fn checking_fixing_skipping_and_reporting() {
h.run_steps(2);
h.get_by_label_contains("Screen readers choose their voice");
h.get_by_label("Primary language - Failed").click();
h.key_press(egui::Key::ArrowRight);
h.run_steps(2);
h.get_by_label("No document language is set");
// The report.
h.get_by_label("Report").click();
h.run_steps(2);
let html = std::fs::read_to_string(dir.join("notes Accessibility Report.html")).unwrap();
let requests = files.requests();
assert_eq!(requests.len(), 1, "the report asks where to be saved once");
assert_eq!(requests[0].file_name.as_deref(), Some("notes Accessibility Report.html"));
// PLAN: assumed the scripted save lands at the suggested directory and name (pdf-workflows-w13, A-6)
let saved = requests[0].directory.clone().unwrap_or_default().join("notes Accessibility Report.html");
let html = String::from_utf8(files.file(&saved).expect("the report was written")).unwrap();
assert!(html.contains("Accessibility Report") && html.contains("Skipped"));
}
@@ -142,7 +151,7 @@ fn a_rule_skipped_in_one_document_is_not_skipped_in_another() {
};
assert!(h.state_mut().execute("a11y.check"));
h.run_steps(3);
assert_eq!(h.state().dialog, None);
assert!(h.state().dialogs.is_empty(), "no options dialog while it is turned off");
right_click(&mut h, "Tagged PDF - Failed");
h.get_by_label("Skip Rule").click();
h.run_steps(2);
@@ -152,7 +161,7 @@ fn a_rule_skipped_in_one_document_is_not_skipped_in_another() {
h.run_steps(2);
assert!(h.state_mut().execute("a11y.check"));
h.run_steps(3);
assert_eq!(h.state().dialog, None);
assert!(h.state().dialogs.is_empty());
assert_eq!(tagged(&h), (Status::Failed, 2), "b.pdf's own result");
// Starting again from the options dialog forgets b.pdf's skips, not a.pdf's.
right_click(&mut h, "Tagged PDF - Failed");
@@ -162,6 +171,7 @@ fn a_rule_skipped_in_one_document_is_not_skipped_in_another() {
h.state_mut().a11y_options.show_dialog = true;
assert!(h.state_mut().execute("a11y.check"));
h.run_steps(2);
assert!(!h.state().dialogs.is_empty(), "the options dialog opens");
h.get_by_label("Start Checking").click();
h.run_steps(3);
assert_eq!(tagged(&h), (Status::Failed, 2));
@@ -270,7 +280,9 @@ fn checker_shows_a_figure_finding_on_its_page() {
h.run_steps(4);
h.state_mut().run_accessibility_check();
h.run_steps(3);
// The rule opens as a user opens a tree row: select it, then Right.
h.get_by_label("Figures alternate text - Failed").click();
h.key_press(egui::Key::ArrowRight);
h.run_steps(2);
h.get_by_label_contains("Figure element on page 1: no alternate text").click();
h.run_steps(1);
@@ -291,12 +303,14 @@ fn setting_alternate_text_figure_by_figure() {
h.run_steps(2);
h.get_by_label("Set Alternate Text");
h.get_by_label("Figure 1 of 2 on page 1");
h.state_mut().alt_draft.texts[0] = "A grey square".into();
let field = h.get_by_role_and_label(Role::TextInput, "Alternate text");
field.focus();
field.type_text("A grey square");
h.run_steps(2);
h.get_by_label("Next figure").click();
h.run_steps(2);
h.get_by_label("Figure 2 of 2 on page 1");
h.get_by_label("Decorative figure").click();
h.get_by_label_contains("decorative").click();
h.run_steps(1);
h.get_by_label("Save & Close").click();
h.run_steps(3);
@@ -320,10 +334,12 @@ fn tags_panel_edits_a_tag_property_and_undoes_it() {
assert!(h.state_mut().execute("a11y.tags"));
h.run_steps(2);
assert_eq!(h.state().right, Some(RightPanel::Tags));
h.get_by_label("Collapse tag").click();
// The list's own disclosure: Left closes the selected group, Right opens it.
h.get_by_label("Document · 6").click();
h.key_press(egui::Key::ArrowLeft);
h.run_steps(2);
assert!(h.query_by_label("Figure · 7").is_none());
h.get_by_label("Expand tag").click();
h.key_press(egui::Key::ArrowRight);
h.run_steps(2);
h.get_by_label("Figure · 7").click();
h.run_steps(2);