pdf-workflows-w8: net change of 2 commits

- pdf-workflows-w8: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot)
- pdf-workflows-w8: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:28 -05:00
parent aa4675d367
commit e700a0019e
2 changed files with 186 additions and 285 deletions
+171 -212
View File
@@ -2,12 +2,29 @@
//! (replaced blue, inserted green, deleted red), shades them on the newer document's pages, and
//! offers a report or the differences as comments.
use egui::{Align, Color32, Layout};
use craft::behavior::{IconId, Selection, keyed};
use craft::pages::ui::{Lead, PageRangeField, SyncedViews, SyncedViewsState};
use craft::pages::{format_pages, parse_pages};
use craft::theme::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::{Checkbox, Segmented};
use craft::ui::contract::{Bind, Entry, Pad, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{DialogResult, dialog_id};
use craft::ui::display::Text;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{HueTarget, List, ListRow};
use craft::ui::notices::Notice;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
use craft::ui::primitives::IconSpec;
use craft::ui::style::DataColor;
use egui::Color32;
use pdfcraft_engine::DocId;
use pdfcraft_engine::compare::{Comparison, Kind};
use crate::theme::{self, Tokens};
use crate::{PdfCraftApp, RightPanel, widgets};
use crate::{PdfCraftApp, RightPanel};
/// The key the Compare Files dialog files its answer under.
const DIALOG_KEY: &str = "compare";
/// The last comparison.
pub struct CompareState {
@@ -22,10 +39,8 @@ pub struct CompareState {
/// Side by side: the old file on the left, the new on the right, scrolled and zoomed
/// together.
pub side_by_side: bool,
/// Which half leads the other (the one the pointer was over last): 0 old, 1 new.
pub leader: usize,
/// Each half's scroll offset last frame, to tell which one moved.
pub prev_scroll: [egui::Vec2; 2],
/// The pair's divider and which half leads; the new file leads at first.
pub views: SyncedViewsState,
/// Show: whether the text changes are in the list and the shading, and whether the visual
/// differences (counted, never listed) are shaded (Acrobat's Filter).
pub show_text: bool,
@@ -50,140 +65,137 @@ pub fn colour(kind: Kind) -> Color32 {
Color32::from_rgb((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8)
}
/// The Compare Files dialog: pick the older document. Returns (compare, cancel).
pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (bool, bool) {
ui.label(egui::RichText::new(tl!("Compare Files")).font(theme::semibold(18.0)));
ui.add_space(8.0);
let Some((active_i, new)) = app.active_ids() else { return (false, true) };
let others: Vec<(DocId, String)> =
app.views.iter().filter(|v| v.id != new).filter_map(|v| app.session.get(v.id).map(|d| (d.id, d.name.clone()))).collect();
if app.compare_old.is_none_or(|o| !others.iter().any(|(id, _)| *id == o)) {
app.compare_old = others.first().map(|(id, _)| *id);
}
let new_name = app.session.get(new).map(|d| d.name.clone()).unwrap_or_default();
let page_count = app.views.get(active_i).map_or(0, |v| v.page_count());
egui::Grid::new("compare-files").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| {
ui.label(tl!("Old file:"));
let shown =
others.iter().find(|(id, _)| Some(*id) == app.compare_old).map_or(tl!("Open the older version first").to_string(), |(_, n)| n.clone());
craft_ui::ComboBox::from_id_salt("compare-old").selected_text(shown).width(320.0).show_ui(ui, |ui| {
for (id, n) in &others {
ui.selectable_value(&mut app.compare_old, Some(*id), n);
}
});
ui.end_row();
ui.label(tl!("New file:"));
ui.label(egui::RichText::new(new_name).strong());
ui.end_row();
ui.label(tl!("Pages:"));
let field = ui.add(egui::TextEdit::singleline(&mut app.compare_pages).desired_width(320.0).hint_text(format!("1-{page_count}")));
field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), tl!("Pages")));
ui.end_row();
});
let pages_error = crate::page_selection_ui::parse(&app.compare_pages, page_count).err();
if let Some(e) = &pages_error {
ui.label(e.said(&|s| crate::i18n::t(s).to_string()));
}
ui.add_space(4.0);
ui.label(egui::RichText::new(tl!("Text is compared word by word; the differences are shown on the new file.")).small().color(t.text_muted));
ui.add_space(10.0);
let (mut go, mut cancel) = (false, false);
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let ready = app.compare_old.is_some() && pages_error.is_none();
if ui.add_enabled_ui(ready, |ui| widgets::pill_button(ui, tl!("Compare"), true)).inner.clicked() {
go = true;
}
if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {
cancel = true;
}
})
});
(go, cancel)
/// The key a document is offered under in the dialog's choice.
fn option_key(id: DocId) -> String {
id.0.to_string()
}
/// The Compare panel.
pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, state: &Option<CompareState>, id: DocId) -> Option<PanelAction> {
/// Opens the Compare Files dialog: the older version among the other open documents, the active file
/// as the new one, and the pages to compare.
pub(crate) fn open_compare_dialog(app: &mut PdfCraftApp, ctx: &egui::Context) {
let Some((active_i, new)) = app.active_ids() else { return };
let others: Vec<(String, String)> =
app.views.iter().filter(|v| v.id != new).filter_map(|v| app.session.get(v.id).map(|d| (option_key(d.id), d.name.clone()))).collect();
let old = app.compare_old.map(option_key).filter(|key| others.iter().any(|(k, _)| k == key)).or_else(|| others.first().map(|(k, _)| k.clone()));
let new_name = app.session.get(new).map(|d| d.name.clone()).unwrap_or_default();
let count = app.views.get(active_i).map_or(0, |v| v.page_count());
let fields = DialogFields::from_pairs([("old", old.unwrap_or_default()), ("pages", app.compare_pages.clone())]);
let build = move |fields: &mut DialogFields| {
let chosen = fields.text("old").filter(|o| !o.is_empty()).map(str::to_owned);
let pages_ok = parse_pages(fields.text("pages").unwrap_or_default(), count).is_ok();
let options = others.iter().map(|(key, name)| (key.clone(), name.clone().into())).collect();
let pages = Param::custom("pages", tl!("Pages").to_string(), move |ui, fields, _| {
let shown = parse_pages(fields.text("pages").unwrap_or_default(), count).unwrap_or_default();
let out = PageRangeField::new(tl!("Pages").to_string(), &shown, count, 0).show(ui);
if let Some(picked) = out.picked {
fields.set("pages", format_pages(&picked));
}
out.response
})
.opens_with(String::new());
let params = vec![
Param::new("old", tl!("Old file:").to_string(), ParamKind::choice(options, chosen.clone())),
Param::read_only_text("new", tl!("New file:").to_string(), new_name.clone()),
pages,
];
let reason = if chosen.is_none() { tl!("Open the older version first") } else { tl!("Enter valid page numbers") };
ParamDialog::new(DIALOG_KEY, tl!("Compare Files").to_string(), params)
.ok_label(tl!("Compare").to_string())
.ok_enabled(chosen.is_some() && pages_ok)
.ok_reason(reason.to_string())
.footer_note(tl!("Text is compared word by word; the differences are shown on the new file.").to_string())
};
crate::dialogs::host::open(app, HostedParamDialog::new(ctx, DIALOG_KEY, fields, build));
}
/// Once per frame: when the Compare Files dialog answered OK, runs the comparison it asked for.
pub(crate) fn pass(app: &mut PdfCraftApp) {
let Some(DialogResult::Ok(result)) = app.dialogs.take_by_id::<HostedParamDialog>(dialog_id(DIALOG_KEY)) else { return };
let chosen = result.fields.text("old").unwrap_or_default();
let Some(old) = app.views.iter().map(|v| v.id).find(|id| option_key(*id) == chosen) else { return };
app.compare_old = Some(old);
app.compare_pages = result.fields.text("pages").unwrap_or_default().to_owned();
app.run_compare();
}
/// The text a change shows in the list.
fn change_text(ch: &pdfcraft_engine::compare::Change) -> String {
match ch.kind {
Kind::Replaced => format!("\"{}\" → \"{}\"", ch.old.text, ch.new.text),
Kind::Inserted => format!("+ \"{}\"", ch.new.text),
Kind::Deleted => format!("− \"{}\"", ch.old.text),
}
}
/// The kind's name, written out so the catalogue extraction sees each word.
fn kind_label(kind: Kind) -> String {
match kind {
Kind::Replaced => tl!("Replaced").to_string(),
Kind::Inserted => tl!("Inserted").to_string(),
Kind::Deleted => tl!("Deleted").to_string(),
}
}
/// A count of one kind of difference after its coloured badge.
fn count_row(ui: &mut egui::Ui, colour: Color32, n: usize, kind: &str) {
let text = crate::i18n::fmt(tl!("{n} {kind}"), &[("n", &n.to_string()), ("kind", kind)]);
ListRow::new(text).icon(IconSpec::svg(IconId::new("square"))).hue(DataColor::new(colour), HueTarget::Icon).show(ui);
}
/// The Compare panel, a dock body.
pub(crate) fn panel(ui: &mut egui::Ui, state: &Option<CompareState>, id: DocId) -> Option<PanelAction> {
let Some(s) = state.as_ref().filter(|s| s.new == id) else {
ui.label(egui::RichText::new(tl!("Compare this file with an older version: Compare files… in All tools.")).color(t.text_muted));
Notice::new(Tone::Info, tl!("Compare this file with an older version: Compare files… in All tools.").to_string()).show(ui);
return None;
};
let mut action = None;
let c = &s.result;
if c.identical() {
ui.label(tl!("No differences in the text."));
}
ui.horizontal_wrapped(|ui| {
Stack::new().pad(Pad::Control).show(ui, |ui, _| {
if c.identical() {
Notice::new(Tone::Info, tl!("No differences in the text.").to_string()).show(ui);
}
for k in [Kind::Replaced, Kind::Inserted, Kind::Deleted] {
let (dot, _) = ui.allocate_exact_size(egui::vec2(10.0, 10.0), egui::Sense::hover());
ui.painter().rect_filled(dot, egui::CornerRadius::same(2), colour(k));
ui.label(crate::i18n::fmt(tl!("{n} {kind}"), &[("n", &c.count(k).to_string()), ("kind", tl!(k.label()))]));
count_row(ui, colour(k), c.count(k), &kind_label(k));
}
let (dot, _) = ui.allocate_exact_size(egui::vec2(10.0, 10.0), egui::Sense::hover());
ui.painter().rect_filled(dot, egui::CornerRadius::same(2), VISUAL);
ui.label(crate::i18n::fmt(tl!("{n} {kind}"), &[("n", &s.visual.len().to_string()), ("kind", tl!("Visual"))]));
});
ui.horizontal(|ui| {
ui.label(tl!("Show:"));
let (mut text, mut visual) = (s.show_text, s.show_visual);
let text_changed = ui.add(widgets::checkbox(&mut text, tl!("Text"))).changed();
if ui.add(widgets::checkbox(&mut visual, tl!("Visual"))).changed() || text_changed {
action = Some(PanelAction::Show { text, visual });
}
});
ui.add_space(6.0);
// Side by side, or the new file alone.
ui.horizontal(|ui| {
if widgets::pill_button(ui, tl!("Side by side"), s.side_by_side).clicked() {
action = Some(PanelAction::SideBySide(true));
}
if widgets::pill_button(ui, tl!("New file only"), !s.side_by_side).clicked() {
action = Some(PanelAction::SideBySide(false));
}
});
ui.add_space(4.0);
ui.horizontal(|ui| {
if ui.button(tl!("Mark as comments")).clicked() {
action = Some(PanelAction::Mark);
}
if ui.button(tl!("Report…")).clicked() {
action = Some(PanelAction::Report);
}
if ui.button(tl!("Clear")).clicked() {
action = Some(PanelAction::Clear);
}
});
ui.separator();
for (i, ch) in c.changes.iter().enumerate().filter(|_| s.show_text).take(2000) {
let text = match ch.kind {
Kind::Replaced => format!("\"{}\" → \"{}\"", ch.old.text, ch.new.text),
Kind::Inserted => format!("+ \"{}\"", ch.new.text),
Kind::Deleted => format!("− \"{}\"", ch.old.text),
};
let selected = s.selected == Some(i);
let r = ui.push_id(i, |ui| {
ui.horizontal(|ui| {
let (bar, _) = ui.allocate_exact_size(egui::vec2(4.0, 34.0), egui::Sense::hover());
ui.painter().rect_filled(bar, egui::CornerRadius::same(2), colour(ch.kind));
ui.vertical(|ui| {
ui.label(
egui::RichText::new(crate::i18n::fmt(
tl!("{kind} · page {p}"),
&[("kind", tl!(ch.kind.label())), ("p", &(ch.new.page + 1).to_string())],
))
.small()
.color(t.text_muted),
);
ui.selectable_label(selected, text)
})
.inner
})
.inner
count_row(ui, VISUAL, s.visual.len(), tl!("Visual"));
Row::new().show(ui, |ui, _| {
Text::new(tl!("Show:").to_string()).show(ui);
let (mut text, mut visual) = (s.show_text, s.show_visual);
Checkbox::new(Bind::bound(&mut text)).label(tl!("Text").to_string()).show(ui);
Checkbox::new(Bind::bound(&mut visual)).label(tl!("Visual").to_string()).show(ui);
if (text, visual) != (s.show_text, s.show_visual) {
action = Some(PanelAction::Show { text, visual });
}
});
if r.inner.clicked() {
action = Some(PanelAction::Select(i));
let entries = [Entry::new(true, tl!("Side by side").to_string()), Entry::new(false, tl!("New file only").to_string())];
let mut side = s.side_by_side;
Segmented::new(tl!("Layout").to_string(), Bind::bound(&mut side), &entries).show(ui);
if side != s.side_by_side {
action = Some(PanelAction::SideBySide(side));
}
}
Row::new().show(ui, |ui, _| {
if Button::new(tl!("Mark as comments").to_string()).show(ui).clicked() {
action = Some(PanelAction::Mark);
}
if Button::new(tl!("Report…").to_string()).show(ui).clicked() {
action = Some(PanelAction::Report);
}
if Button::new(tl!("Clear").to_string()).show(ui).clicked() {
action = Some(PanelAction::Clear);
}
});
let order: Vec<usize> = (0..c.changes.len()).filter(|_| s.show_text).take(2000).collect();
let mut selection = Selection::new(s.selected.into_iter().collect(), s.selected, s.selected);
let rows = keyed(&order, |i| *i);
List::new(tl!("Differences").to_string()).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items(ui, &rows, &mut |key, item| {
let Some(ch) = c.changes.get(*key) else { return ListRow::new(String::new()) };
let detail = crate::i18n::fmt(tl!("{kind} · page {p}"), &[("kind", kind_label(ch.kind).as_str()), ("p", &(ch.new.page + 1).to_string())]);
ListRow::new(change_text(ch)).detail(detail).hue(DataColor::new(colour(ch.kind)), HueTarget::Icon).icon(IconSpec::svg(IconId::new("square"))).state(item.row.clone())
});
if let Some(picked) = selection.items.first().copied().filter(|p| Some(*p) != s.selected) {
action = Some(PanelAction::Select(picked));
}
});
action
}
@@ -194,7 +206,7 @@ impl PdfCraftApp {
let partner = side_by_side(self, index).and_then(|(old, _)| self.views.get(old).map(|v| v.id));
for view in &mut self.views {
if view.id == id || partner == Some(view.id) {
view.set_page_gaps(show);
view.view.page_gaps = show;
}
}
}
@@ -204,9 +216,9 @@ impl PdfCraftApp {
let Some((i, new)) = self.active_ids() else { return };
let Some(old) = self.compare_old else { return };
let count = self.views.get(i).map_or(0, |v| v.page_count());
let pages = match crate::page_selection_ui::parse(&self.compare_pages, count) {
let pages = match parse_pages(&self.compare_pages, count) {
Ok(pages) => pages,
Err(e) => return self.notify_error(e.said(&|s| crate::i18n::t(s).to_string())),
Err(e) => return self.notify_error(e.to_string()),
};
match self.session.compare_pages(old, new, &pages) {
Ok(result) => {
@@ -225,8 +237,7 @@ impl PdfCraftApp {
visual,
selected: None,
side_by_side,
leader: 1,
prev_scroll: [egui::Vec2::ZERO; 2],
views: Default::default(),
show_text: true,
show_visual: true,
});
@@ -266,7 +277,6 @@ impl PdfCraftApp {
}
PanelAction::SideBySide(on) => {
s.side_by_side = on;
s.leader = 1;
}
PanelAction::Show { text, visual } => {
s.show_text = text;
@@ -360,85 +370,34 @@ pub(crate) fn side_by_side(app: &PdfCraftApp, index: usize) -> Option<(usize, us
}
/// Side by side: the old file on the left, the new on the right, each a page view of its own
/// with its shading, scrolled and zoomed together. The half the pointer is over leads; the
/// other follows its zoom, layout and scroll offset.
/// with its shading. The pair keeps them scrolled and zoomed together, the half last pressed leading.
pub(crate) fn compare_area(app: &mut PdfCraftApp, old: usize, new: usize, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let rect = ui.available_rect_before_wrap();
let gap = 1.0;
let half_w = ((rect.width() - gap) / 2.0).max(1.0);
let caption_h = 22.0;
let left = egui::Rect::from_min_size(rect.min, egui::vec2(half_w, rect.height()));
let right = egui::Rect::from_min_size(egui::pos2(rect.min.x + half_w + gap, rect.min.y), egui::vec2(half_w, rect.height()));
// Who leads: the half under the pointer (remembered), the new file at first.
if let Some(p) = ui.input(|i| i.pointer.hover_pos())
&& let Some(c) = app.compare.as_mut()
{
if left.contains(p) {
c.leader = 0;
} else if right.contains(p) {
c.leader = 1;
let (Some(old_view), Some(new_view)) = (app.views.get(old), app.views.get(new)) else { return };
let ids = [old_view.id, new_view.id];
let mut states = (old_view.view.clone(), new_view.view.clone());
let names = ids.map(|id| app.session.get(id).map(|d| d.name.clone()).unwrap_or_default());
let Some(mut pair) = app.compare.as_mut().map(|c| std::mem::take(&mut c.views)) else { return };
let left = crate::i18n::fmt(tl!("Old file: {name}"), &[("name", &names[0])]);
let right = crate::i18n::fmt(tl!("New file: {name}"), &[("name", &names[1])]);
SyncedViews::new(tl!("Comparison").to_string(), &mut pair).captions(left, right).halves(ui, (&mut states.0, &mut states.1), |ui, rect, state, half| {
let index = if half == Lead::Left { old } else { new };
// The app draws through its own view state: the pair's state for this half stands in for it during the draw.
if let Some(v) = app.views.get_mut(index) {
std::mem::swap(&mut v.view, state);
}
let output = crate::canvas::document_area_at(app, index, rect, ui);
if let Some(v) = app.views.get_mut(index) {
std::mem::swap(&mut v.view, state);
}
output
});
// A half can close its own tab while it draws (#3915): each is found again by id.
for (id, state) in ids.into_iter().zip([states.0, states.1]) {
if let Some(v) = app.views.iter_mut().find(|v| v.id == id) {
v.view = state;
}
}
let leader = app.compare.as_ref().map_or(1, |c| c.leader);
let (lead, follow) = if leader == 0 { (old, new) } else { (new, old) };
// The follower takes the leader's zoom and layout before either is drawn.
let (zoom, fit, layout, continuous, page_gaps, rotation) = {
let v = &app.views[lead];
(v.zoom, v.fit, v.layout, v.continuous, v.show_page_gaps, v.rotation)
};
{
let v = &mut app.views[follow];
if v.zoom != zoom
|| v.fit != fit
|| v.layout != layout
|| v.continuous != continuous
|| v.show_page_gaps != page_gaps
|| v.rotation != rotation
{
v.zoom = zoom;
v.fit = fit;
v.layout = layout;
v.continuous = continuous;
v.show_page_gaps = page_gaps;
v.rotation = rotation;
}
}
let names = [old, new].map(|i| app.session.get(app.views[i].id).map(|d| d.name.clone()).unwrap_or_default());
// Drawing a half can close its own tab (its snapshot bar's Close, #3915), which shifts or
// removes the indexes below. Each half is found again by id, and the frame stops when one is gone.
let ids = [app.views[old].id, app.views[new].id];
let find = |app: &PdfCraftApp, id| app.views.iter().position(|v| v.id == id);
ui.painter().vline(rect.min.x + half_w, rect.y_range(), egui::Stroke::new(gap, t.border));
for (k, r) in [left, right].into_iter().enumerate() {
// Both halves must still be open: once either has closed, the pair is over.
let (Some(old_index), Some(new_index)) = (find(app, ids[0]), find(app, ids[1])) else { return };
let index = if k == 0 { old_index } else { new_index };
let caption = egui::Rect::from_min_size(r.min, egui::vec2(r.width(), caption_h));
ui.painter().rect_filled(caption, 0.0, t.panel);
let label = crate::i18n::fmt(if k == 0 { tl!("Old file: {name}") } else { tl!("New file: {name}") }, &[("name", &names[k])]);
ui.painter().text(
egui::pos2(caption.min.x + 10.0, caption.center().y),
egui::Align2::LEFT_CENTER,
label,
egui::FontId::proportional(12.0),
t.text_muted,
);
let body = egui::Rect::from_min_max(egui::pos2(r.min.x, r.min.y + caption_h), r.max);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).id_salt(("compare-half", k)));
child.set_clip_rect(body);
crate::canvas::document_area(app, index, &mut child);
}
// After both drew: the leader's scroll, when it moved, is the follower's next offset.
let (Some(old), Some(new)) = (find(app, ids[0]), find(app, ids[1])) else { return };
let follow = if leader == 0 { new } else { old };
let offsets = [app.views[old].last_scroll, app.views[new].last_scroll];
if let Some(c) = app.compare.as_mut() {
let lead_k = if leader == 0 { 0 } else { 1 };
if (offsets[lead_k] - c.prev_scroll[lead_k]).length() > 0.5 && (offsets[1 - lead_k] - offsets[lead_k]).length() > 0.5 {
app.views[follow].sync_scroll = Some(offsets[lead_k]);
ui.ctx().request_repaint();
}
c.prev_scroll = offsets;
c.views = pair;
}
}
+15 -73
View File
@@ -39,10 +39,10 @@ fn compare_two_versions() {
let old_i = h.state().views.iter().position(|v| v.id == h.state().compare.as_ref().unwrap().old).unwrap();
assert_eq!(h.state().views[old_i].compare_marks.len(), 2, "replaced words shaded on the old file too");
assert!(h.state().views[old_i].flash.is_some(), "the old half jumped to the change");
h.state_mut().views[i].zoom = 1.5;
h.state_mut().views[i].fit = pdfcraft_ui_egui::canvas::Fit::None;
h.state_mut().views[i].view.zoom = 1.5;
h.state_mut().views[i].view.fit = craft::pages::Fit::None;
h.run_steps(3);
assert_eq!((h.state().views[old_i].zoom, h.state().views[old_i].fit), (1.5, pdfcraft_ui_egui::canvas::Fit::None), "the old half follows");
assert_eq!((h.state().views[old_i].view.zoom, h.state().views[old_i].view.fit), (1.5, craft::pages::Fit::None), "the old half follows");
h.get_by_label("New file only").click();
h.run_steps(2);
assert!(!h.state().compare.as_ref().unwrap().side_by_side);
@@ -160,68 +160,6 @@ fn compare_filters_hide_text_or_visual_changes() {
assert_eq!(kinds(&h, old_i), (text_old, 0));
}
/// The Compare Files dialog's Pages field rejects an out-of-range page: the
/// comparison does not run and the dialog stays open with the typed range kept.
#[test]
fn compare_dialog_pages_field_rejects_out_of_range() {
let s = Session::new();
let v1 = s.create_from_text("t", "Delivery within five days. Returns accepted.").unwrap().to_vec();
let v2 = s.create_from_text("t", "Delivery within three days. Returns accepted for a week.").unwrap().to_vec();
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("v1.pdf", None, v1.clone()).unwrap();
app.open_bytes("v2.pdf", None, v2.clone()).unwrap();
app
});
h.run_steps(4);
assert!(h.state_mut().execute("doc.compare"));
h.run_steps(2);
h.get_by_label("Compare Files");
let pages = h.query_by_role_and_label(egui::accesskit::Role::TextInput, "Pages");
assert!(pages.is_some(), "the dialog has a Pages text input");
assert!(h.query_by_label("Pages:").is_some(), "the dialog has a Pages field");
let Some(pages) = pages else { return };
pages.focus();
pages.type_text("99");
h.run_steps(2);
assert_eq!(
h.query_by_role_and_label(egui::accesskit::Role::TextInput, "Pages").and_then(|n| n.value()),
Some("99".to_string()),
"the typed range is kept"
);
h.get_by_label("Compare").click();
h.run_steps(3);
assert!(h.query_by_label("Compare Files").is_some(), "the dialog stays open for an out-of-range page");
assert!(h.state().compare.is_none(), "the comparison did not run");
assert_ne!(h.state().right, Some(RightPanel::Compare));
}
/// Writes a screenshot of the Compare panel when PDFCRAFT_SHOT is set (for review).
#[test]
fn compare_panel_screenshot() {
let Ok(out) = std::env::var("PDFCRAFT_SHOT") else { return };
let _gpu = crate::gpu();
let s = Session::new();
let v1 = s.create_from_text("t", "Delivery within five days. Returns accepted.").unwrap().to_vec();
let v2 = s.create_from_text("t", "Delivery within three days. Returns accepted for a week.").unwrap().to_vec();
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("v1.pdf", None, v1.clone()).unwrap();
app.open_bytes("v2.pdf", None, v2.clone()).unwrap();
app
});
h.run_steps(4);
h.state_mut().compare_old = h.state().views.first().map(|v| v.id);
h.state_mut().run_compare();
for _ in 0..20 {
h.run_steps(2);
std::thread::sleep(std::time::Duration::from_millis(50));
}
h.render().unwrap().save(out).unwrap();
}
#[test]
fn pdfa_dialog_verifies_and_converts() {
let doc = Session::new().create_from_text("t", "Keep forever").unwrap().to_vec();
@@ -242,8 +180,8 @@ fn pdfa_dialog_verifies_and_converts() {
h.get_by_label("Save as PDF/A").click();
h.run_steps(3);
h.get_by_label("Declared conformance: PDF/A-2b");
let issues = h.state().pdfa.issues.clone().unwrap();
assert!(issues.iter().all(|i| !i.fixable), "{issues:?}");
// The issues are the dialog's findings: the one left over is shown as not fixable here.
assert!(!h.query_all_by_label_contains("not fixable here").collect::<Vec<_>>().is_empty(), "the remaining finding says it is not fixable");
let id = h.state().active_ids().unwrap().1;
assert_eq!(h.state().session.get(id).unwrap().can_undo(), Some("Save as PDF/A-2b"));
h.get_by_label("Remove PDF/A identification").click();
@@ -303,16 +241,20 @@ fn pdfa_dialog_shows_a_declared_pdfua() {
#[test]
fn export_to_word_html_and_rtf() {
let doc = Session::new().create_from_text("t", "Exported words").unwrap().to_vec();
let dir = std::env::temp_dir().join(format!("pdfcraft-office-ui-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut app = PdfCraftApp::new();
app.set_option("language", "en").unwrap();
app.open_bytes("e.pdf", None, doc).unwrap();
for ext in ["docx", "pptx", "html", "rtf"] {
let out = dir.join(format!("e.{ext}"));
app.save_override = Some(out.to_string_lossy().into_owned());
// Each save is answered with the suggested name in the suggested folder.
let files = std::sync::Arc::new(craft::host::ScriptedFiles::new().saving_suggested());
app.set_files(files.clone()); // PLAN: assumed `PdfCraftApp::set_files(Arc<dyn Files>)` (pdf-shell-w16)
assert!(app.execute(&format!("export.{ext}")));
assert!(std::fs::metadata(&out).unwrap().len() > 40, "{ext}");
let request = files.requests().pop().expect("the export asked where to save");
let path = request.directory.or(request.default_directory).unwrap_or_default().join(request.file_name.expect("a suggested name"));
let bytes = files.file(&path).unwrap_or_else(|| panic!("{ext} was written"));
assert!(bytes.len() > 40, "{ext}");
if ext == "html" {
assert!(String::from_utf8_lossy(&bytes).contains("Exported words"));
}
}
assert!(std::fs::read_to_string(dir.join("e.html")).unwrap().contains("Exported words"));
}