feat(ui): add Bates numbering to a list of files from the app

Bates numbering > Add to files... (edit.bates_files) numbers a list of
files as one run: each file starts one after the last number of the file
before, with the single-file token's prefix, suffix, digits, start and box.
It writes numbered copies beside each original or in a picked folder and
never changes the originals. Nothing is written when a copy would land on
another copy (names compared without case) or on an existing file, or when
a file can't be read, opened (password, signed) or numbered.

The engine gains BatesFormat (check, spans with checked arithmetic, label,
settings) and Session::add_bates. doc_bates_multi is not moved onto it
here; that move is its own change.

Parity edit.bates-multi-file stays partial: the dialog refuses password
and signed files and runs on the frame thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
KenM76andClaude Opus 5.5 committed 2026-11-28 04:27:06 -05:00
1 parent 81a475e55f
commit a63cdcfede
11 files changed
+566 -4

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
//! Bates numbering across several files as one run: each file's first number follows the last
//! number of the file before it. The app's Bates numbering ▸ Add to files… numbers with these
//! rules, which are the `doc_bates_multi` tool's.
use crate::{DocId, Edit, EditError, HeaderFooter, Session};
/// The most files one run numbers.
pub const BATES_MAX_FILES: usize = 1000;
/// The most characters in a prefix or a suffix.
pub const BATES_AFFIX_CHARS: usize = 128;
/// The most digits a number is padded to.
pub const BATES_MAX_DIGITS: u8 = 12;
/// The most bytes of files one run reads.
pub const BATES_MAX_BYTES: u64 = 512 * 1024 * 1024;
/// How a run's numbers read and where they are drawn.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BatesFormat {
/// The first file's first number, at least 1.
pub start: u64,
/// Numbers shorter than this are padded with zeros (1 to [`BATES_MAX_DIGITS`]).
pub digits: u8,
pub prefix: String,
pub suffix: String,
/// The header and footer box the number goes in: 0 to 2 are the header's left, centre and
/// right, 3 to 5 the footer's.
pub position: usize,
}
/// The numbers one file gets, both ends included.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BatesSpan {
pub first: u64,
pub last: u64,
}
/// Why a run can't be numbered. File indexes count from 0.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum BatesError {
#[error("the start number must be at least 1")]
Start,
#[error("the number of digits must be from 1 to 12")]
Digits,
#[error("a prefix or suffix must be at most 128 characters and can't contain # or >>")]
Affix,
#[error("the number must go in one of the six header and footer boxes")]
Position,
#[error("there are no files to number, or more than 1000")]
Count,
#[error("file {0} has no pages to number")]
NoPages(usize),
#[error("the Bates numbers of file {0} run past the largest number")]
Overflow(usize),
}
impl BatesFormat {
/// Refuses a format the Bates token can't carry.
pub fn check(&self) -> Result<(), BatesError> {
if self.start == 0 {
return Err(BatesError::Start);
}
if !(1..=BATES_MAX_DIGITS).contains(&self.digits) {
return Err(BatesError::Digits);
}
let bad = |s: &str| s.chars().count() > BATES_AFFIX_CHARS || s.contains('#') || s.contains(">>");
if bad(&self.prefix) || bad(&self.suffix) {
return Err(BatesError::Affix);
}
if self.position > 5 {
return Err(BatesError::Position);
}
Ok(())
}
/// The span of each file, in order, for files of `pages` pages each.
pub fn spans(&self, pages: &[usize]) -> Result<Vec<BatesSpan>, BatesError> {
self.check()?;
if pages.is_empty() || pages.len() > BATES_MAX_FILES {
return Err(BatesError::Count);
}
let mut spans = Vec::with_capacity(pages.len());
let mut next = Some(self.start);
for (index, &count) in pages.iter().enumerate() {
let first = next.ok_or(BatesError::Overflow(index))?;
let offset = count.checked_sub(1).ok_or(BatesError::NoPages(index))?;
let last = u64::try_from(offset).ok().and_then(|o| first.checked_add(o)).ok_or(BatesError::Overflow(index))?;
spans.push(BatesSpan { first, last });
// The last file may end on the largest number; only a file after it overflows.
next = last.checked_add(1);
}
Ok(spans)
}
/// Number `number` as the page shows it.
pub fn label(&self, number: u64) -> String {
let width = usize::from(self.digits);
format!("{}{number:0width$}{}", self.prefix, self.suffix)
}
/// Header and footer settings that number a file from `first`.
pub fn settings(&self, first: u64) -> HeaderFooter {
let mut settings = HeaderFooter::default();
if let Some(text) = settings.text.get_mut(self.position) {
*text = format!("<<Bates Number#{}#{first}#{}#{}>>", self.digits, self.prefix, self.suffix);
}
settings
}
}
impl Session {
/// Numbers every page of document `id` from `first`, as one header and footer edit.
pub fn add_bates(&mut self, id: DocId, format: &BatesFormat, first: u64) -> Result<(), EditError> {
let count = self.get(id).ok_or(EditError::NoDocument)?.info.pages.len();
self.apply(id, Edit::AddHeaderFooter { pages: (0..count).collect(), settings: format.settings(first), replace: false })
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{BatesError, BatesFormat};
fn format(start: u64) -> BatesFormat {
BatesFormat { start, digits: 6, prefix: "CASE-".into(), suffix: String::new(), position: 5 }
}
#[test]
fn each_file_starts_after_the_last_page_of_the_file_before() {
let spans = format(17).spans(&[2, 3, 1]).unwrap();
assert_eq!(spans[0].first, 17);
for pair in spans.windows(2) {
assert_eq!(pair[1].first, pair[0].last + 1);
}
for (span, pages) in spans.iter().zip([2u64, 3, 1]) {
assert_eq!(span.last - span.first + 1, pages);
}
}
#[test]
fn only_a_file_after_the_largest_number_overflows() {
assert!(format(u64::MAX).spans(&[1]).is_ok());
assert_eq!(format(u64::MAX).spans(&[1, 1]), Err(BatesError::Overflow(1)));
assert_eq!(format(u64::MAX - 1).spans(&[3]), Err(BatesError::Overflow(0)));
assert_eq!(format(1).spans(&[2, 0]), Err(BatesError::NoPages(1)));
}
#[test]
fn a_format_the_token_cannot_carry_is_refused() {
for bad in [
BatesFormat { prefix: "A#B".into(), ..format(1) },
BatesFormat { suffix: "A>>".into(), ..format(1) },
BatesFormat { prefix: "é".repeat(129), ..format(1) },
] {
assert_eq!(bad.check(), Err(BatesError::Affix));
}
assert!(BatesFormat { prefix: "é".repeat(128), ..format(1) }.check().is_ok());
assert_eq!(BatesFormat { digits: 13, ..format(1) }.check(), Err(BatesError::Digits));
assert_eq!(format(0).check(), Err(BatesError::Start));
}
}
+1 -1
View File
@@ -145,7 +145,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
menu_item("Header and footer", "heading", &["edit.header_footer", "edit.header_footer.update", "edit.header_footer.remove"]),
menu_item("Watermark", "stamp", &["edit.watermark", "edit.watermark.update", "edit.watermark.remove"]),
item("Link", "link", "edit.link", Ready),
item("Bates numbering", "hash", "edit.bates", Ready),
menu_item("Bates numbering", "hash", &["edit.bates", "edit.bates_files"]),
menu_item("Background", "palette", &["edit.background", "edit.background.update", "edit.background.remove"]),
item("Attach file", "paperclip", "edit.attach", Ready),
],
+1
View File
@@ -350,6 +350,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("edit.links_from_urls", "Create links from URLs", None, None, Modification, "link"),
c("edit.remove_links", "Remove all links", None, None, Modification, "trash-2"),
c("edit.bates", "Add Bates numbering…", None, None, Modification, "hash"),
c("edit.bates_files", "Add Bates numbering to files…", None, None, Nothing, "files"),
c("edit.image", "Add image…", None, None, Modification, "image-plus"),
c("redact.mark", "Redact text and images", None, None, Modification, "rectangle"),
c("redact.pages", "Redact pages…", None, None, Modification, "file-x"),
+2
View File
@@ -14,6 +14,8 @@
pub mod actions;
pub mod autotag;
mod bates_files;
pub use bates_files::{BATES_AFFIX_CHARS, BATES_MAX_BYTES, BATES_MAX_DIGITS, BATES_MAX_FILES, BatesError, BatesFormat, BatesSpan};
mod bookmarks;
pub mod build_info;
pub mod camera;
+1
View File
@@ -760,6 +760,7 @@ impl PdfCraftApp {
self.marks_draft.focused_box = 5;
self.open_marks(ctx, pdfcraft_engine::MarkKind::HeaderFooter, false);
}
"edit.bates_files" => self.open_bates_files(ctx),
"prepress.marks" => self.open_printer_marks(ctx),
"edit.header_footer.remove" | "edit.watermark.remove" | "edit.background.remove" | "prepress.marks.remove" => {
use pdfcraft_engine::MarkKind as K;
+1
View File
@@ -5,6 +5,7 @@ use crate::PdfCraftApp;
mod about;
pub(crate) mod attachment_description;
pub(super) mod bates_files_ui;
pub mod bookmark_styles_ui;
pub(super) mod comment_props;
pub(super) mod convert_colours_ui;
@@ -0,0 +1,284 @@
//! Bates numbering ▸ Add to files…: numbers several files as one run, in list order, each file
//! starting after the last number of the one before. It writes numbered copies and never changes
//! the originals. Nothing is written unless every file can be numbered, and no copy replaces a
//! file. The numbering rules are the engine's ([`pdfcraft_engine::BatesFormat`]).
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use craft::host::{PickRequest, WriteIntent};
use craft::theme::variant::Tone;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::dialog::dialog_id;
use craft::ui::display::{Shade, Text};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
use pdfcraft_engine::{BATES_MAX_BYTES, BATES_MAX_FILES, BatesError, BatesFormat, EditError, Session};
use pdfcraft_render::OpenError;
use crate::PdfCraftApp;
/// The dialog's key.
const KEY: &str = "edit.bates_files";
/// The header and footer boxes, in [`BatesFormat::position`] order.
const POSITIONS: [&str; 6] = ["Top left", "Top center", "Top right", "Bottom left", "Bottom center", "Bottom right"];
/// Characters a copy name's ending can't hold on any desktop system.
const NOT_IN_NAMES: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
/// What the dialog's fields ask for.
struct Request {
files: Vec<PathBuf>,
format: BatesFormat,
ending: String,
/// Whether the copies go in a folder picked after OK, instead of beside each original.
to_folder: bool,
}
impl Request {
fn read(fields: &DialogFields) -> Self {
let files = fields
.list("files")
.map(|items| items.iter().filter_map(|item| if let FieldValue::Text(path) = item { Some(PathBuf::from(path)) } else { None }).collect())
.unwrap_or_default();
let int = |key, default| fields.int(key).unwrap_or(default);
let format = BatesFormat {
start: u64::try_from(int("start", 1)).unwrap_or(0),
digits: u8::try_from(int("digits", 6)).unwrap_or(0),
prefix: fields.text("prefix").unwrap_or_default().to_owned(),
suffix: fields.text("suffix").unwrap_or_default().to_owned(),
position: fields.text("position").and_then(|p| p.parse().ok()).unwrap_or(5),
};
let ending = fields.text("ending").unwrap_or_default().to_owned();
Request { files, format, ending, to_folder: fields.text("place") == Some("folder") }
}
/// Why OK can't run yet, if it can't.
fn refusal(&self) -> Option<String> {
if self.files.is_empty() {
return Some(tl!("Add the files to number.").to_owned());
}
if self.files.len() > BATES_MAX_FILES {
return Some(too_many());
}
if let Err(error) = self.format.check() {
return Some(format_problem(&error));
}
if self.ending.contains(NOT_IN_NAMES) || self.ending.chars().any(char::is_control) {
return Some(tl!("The name ending can't contain / \\ : * ? \" < > |").to_owned());
}
if self.ending.is_empty() && !self.to_folder {
return Some(tl!("Copies beside the originals need a name ending, so they don't replace them.").to_owned());
}
None
}
}
fn too_many() -> String {
crate::i18n::fmt(tl!("A run numbers at most {n} files."), &[("n", &BATES_MAX_FILES.to_string())])
}
/// What is wrong with a format, in the UI language.
fn format_problem(error: &BatesError) -> String {
match error {
BatesError::Start => tl!("The start number must be at least 1.").to_owned(),
BatesError::Digits => tl!("The number of digits must be from 1 to 12.").to_owned(),
BatesError::Affix => tl!("The prefix and suffix can have at most 128 characters, and no # or >>.").to_owned(),
BatesError::Position => tl!("Choose where the number goes.").to_owned(),
BatesError::Count => too_many(),
BatesError::NoPages(_) | BatesError::Overflow(_) => error.to_string(),
}
}
/// The dialog over the values: OK waits for files and a format the Bates number can carry, and the
/// first number is shown as the page will.
fn dialog(fields: &mut DialogFields, open: Vec<PathBuf>) -> ParamDialog<'_> {
let request = Request::read(fields);
let refusal = request.refusal();
let first = request.format.check().ok().map(|()| request.format.label(request.format.start));
let positions = POSITIONS.iter().enumerate().map(|(i, name)| (i.to_string(), tl!(name).into())).collect();
let places = vec![("beside".to_owned(), tl!("Beside each original").into()), ("folder".to_owned(), tl!("In a folder I choose").into())];
let params = vec![
Param::files("files", tl!("Files, numbered in this order")).open_files(open),
Param::new("prefix", tl!("Prefix"), ParamKind::text("")),
Param::new("start", tl!("Start number"), ParamKind::int(Some(1), None, 1)),
Param::new("digits", tl!("Digits"), ParamKind::int(Some(1), Some(i64::from(pdfcraft_engine::BATES_MAX_DIGITS)), 6)),
Param::new("suffix", tl!("Suffix"), ParamKind::text("")),
Param::new("position", tl!("Position"), ParamKind::choice(positions, Some("5".into()))),
Param::new("ending", tl!("Copy name ending"), ParamKind::text("_Bates")),
Param::new("place", tl!("Save copies"), ParamKind::choice(places, Some("beside".into()))),
];
let shown = refusal.clone();
let mut dialog = ParamDialog::new(KEY, tl!("Add Bates Numbering to Files"), params)
.values(Bind::bound(fields))
.ok_label(tl!("Number").into())
.ok_enabled(refusal.is_none())
.below(move |ui, _| {
if let Some(line) = &shown {
Text::new(line.clone()).tone(Tone::Bad).show(ui);
} else if let Some(first) = &first {
Text::new(crate::i18n::fmt(tl!("The first page is numbered {label}."), &[("label", first)])).shade(Shade::Muted).show(ui);
}
Text::new(tl!("Numbered copies are written; the original files are not changed.")).show(ui);
});
if let Some(reason) = refusal {
dialog = dialog.ok_reason(reason.into());
}
dialog
}
/// A file numbered and ready to write.
struct Numbered {
target: PathBuf,
bytes: Arc<Vec<u8>>,
}
fn name_of(path: &Path) -> String {
path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned())
}
/// Where each copy goes: `<stem><ending>.pdf` beside its original, or in `folder`.
fn targets(files: &[PathBuf], ending: &str, folder: Option<&Path>) -> Vec<PathBuf> {
files
.iter()
.map(|source| {
let stem = source.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let dir = folder.map_or_else(|| source.parent().map(Path::to_path_buf).unwrap_or_default(), Path::to_path_buf);
dir.join(format!("{stem}{ending}.pdf"))
})
.collect()
}
/// A path as compared for "the same file": letter case is ignored, as on Windows and macOS.
fn same_key(path: &Path) -> String {
path.to_string_lossy().to_lowercase()
}
impl PdfCraftApp {
/// Bates numbering ▸ Add to files…: the dialog, offering the open documents' files.
pub(crate) fn open_bates_files(&mut self, ctx: &egui::Context) {
let open: Vec<PathBuf> = self.session.docs().iter().filter_map(|d| d.path.as_ref().map(PathBuf::from)).collect();
let dialog = HostedParamDialog::new(ctx, KEY, DialogFields::new(), move |fields| dialog(fields, open.clone()));
crate::dialogs::host::open(self, dialog);
}
/// Takes the dialog's answer: Number writes the copies, after asking for the folder when they
/// go in one.
pub(crate) fn bates_files_pass(&mut self, _ctx: &egui::Context) {
let Some(answer) = self.dialogs.take_by_id::<HostedParamDialog>(dialog_id(KEY)) else { return };
let Some(result) = answer.ok() else { return };
let request = Request::read(&result.fields);
if let Some(reason) = request.refusal() {
self.notify(reason);
return;
}
if request.to_folder {
let pick = PickRequest::folder("edit.bates_files").title(tl!("Choose a folder for the numbered copies"));
self.pick_file(pick, None, move |app, _, picked| {
if let Some(dir) = picked.first_path() {
app.number_files(&request, Some(&dir));
}
});
} else {
self.number_files(&request, None);
}
}
/// Numbers `request`'s files and writes the copies, or writes nothing and says why.
fn number_files(&mut self, request: &Request, folder: Option<&Path>) {
let targets = targets(&request.files, &request.ending, folder);
let numbered = self.refuse_targets(&request.files, &targets).and_then(|()| self.number_all(request, targets));
let (numbered, first, last) = match numbered {
Ok(done) => done,
Err(reason) => {
self.notify(crate::i18n::fmt(tl!("Nothing was numbered: {reason}"), &[("reason", &reason)]));
return;
}
};
for (done, file) in numbered.iter().enumerate() {
if let Err(e) = self.host.files().write(&file.target, &file.bytes, WriteIntent::SaveAs) {
let (n, total) = (done.to_string(), numbered.len().to_string());
let args = [("n", n.as_str()), ("total", total.as_str()), ("name", &name_of(&file.target)), ("e", &e.to_string())];
self.notify_fmt("Wrote {n} of {total} numbered copies; couldn't write {name}: {e}", &args);
return;
}
}
let n = numbered.len().to_string();
let next = last.checked_add(1).map_or_else(|| tl!("none").to_owned(), |next| next.to_string());
let (first, last) = (request.format.label(first), request.format.label(last));
let args = [("n", n.as_str()), ("first", &first), ("last", &last), ("next", &next)];
// The next number is what a following run starts from, so the series can go on.
self.notify_fmt("Numbered {n} files from {first} to {last}. The next start number is {next}.", &args);
}
/// Refuses a copy that would land on an original, on another copy, or on a file that exists.
fn refuse_targets(&self, files: &[PathBuf], targets: &[PathBuf]) -> Result<(), String> {
let sources: HashSet<String> = files.iter().map(|p| same_key(p)).collect();
let mut taken = HashSet::new();
for target in targets {
let name = name_of(target);
if sources.contains(&same_key(target)) {
return Err(crate::i18n::fmt(tl!("the copy {name} would replace an original"), &[("name", &name)]));
}
if !taken.insert(same_key(target)) {
return Err(crate::i18n::fmt(tl!("two copies would be named {name}"), &[("name", &name)]));
}
if self.host.files().exists(target) {
return Err(crate::i18n::fmt(tl!("{name} already exists"), &[("name", &name)]));
}
}
Ok(())
}
/// Reads and numbers every file in a session of its own, so no tab opens. Gives the copies and
/// the run's first and last numbers.
fn number_all(&self, request: &Request, targets: Vec<PathBuf>) -> Result<(Vec<Numbered>, u64, u64), String> {
let mut session = Session::new();
let mut ids = Vec::with_capacity(request.files.len());
let mut read = 0u64;
for source in &request.files {
ids.push(self.open_source(&mut session, source, &mut read)?);
}
let pages: Vec<usize> = ids.iter().map(|&id| session.get(id).map_or(0, |d| d.info.pages.len())).collect();
let name = |index: usize| request.files.get(index).map(|p| name_of(p)).unwrap_or_default();
let spans = request.format.spans(&pages).map_err(|error| match error {
BatesError::NoPages(i) => crate::i18n::fmt(tl!("{name} has no pages"), &[("name", &name(i))]),
BatesError::Overflow(i) => crate::i18n::fmt(tl!("the numbers run out at {name}"), &[("name", &name(i))]),
other => other.to_string(),
})?;
let mut numbered = Vec::with_capacity(ids.len());
for (index, ((&id, span), target)) in ids.iter().zip(&spans).zip(targets).enumerate() {
let failed = |e: EditError| crate::i18n::fmt(tl!("couldn't number {name}: {e}"), &[("name", &name(index)), ("e", &e.to_string())]);
session.add_bates(id, &request.format, span.first).map_err(failed)?;
let bytes = session.save_full_bytes(id).map_err(failed)?;
session.check_save(id, &bytes).map_err(failed)?;
numbered.push(Numbered { target, bytes });
}
let first = spans.first().map_or(request.format.start, |s| s.first);
let last = spans.last().map_or(first, |s| s.last);
Ok((numbered, first, last))
}
/// Opens `source` in `session`, refusing a file that can't be read, needs a password or is
/// signed (numbering would break its signature).
fn open_source(&self, session: &mut Session, source: &Path, read: &mut u64) -> Result<pdfcraft_engine::DocId, String> {
let name = name_of(source);
let bytes = self
.host
.files()
.read(source)
.map_err(|e| crate::i18n::fmt(tl!("couldn't read {name}: {e}"), &[("name", &name), ("e", &e.to_string())]))?;
// The sources, their documents and the copies are all held until the copies are written.
*read = u64::try_from(bytes.len()).ok().and_then(|n| read.checked_add(n)).filter(|total| *total <= BATES_MAX_BYTES).ok_or_else(|| {
let mb = (BATES_MAX_BYTES / (1024 * 1024)).to_string();
crate::i18n::fmt(tl!("the files come to more than {n} MB at {name}"), &[("n", &mb), ("name", &name)])
})?;
let id = session.open(name.clone(), None, Arc::new(bytes), None).map_err(|e| match e {
OpenError::NeedsPassword | OpenError::WrongPassword => crate::i18n::fmt(tl!("{name} is password-protected"), &[("name", &name)]),
other => crate::i18n::fmt(tl!("couldn't open {name}: {e}"), &[("name", &name), ("e", &other.to_string())]),
})?;
if session.get(id).is_some_and(pdfcraft_engine::Document::is_signed) {
return Err(crate::i18n::fmt(tl!("{name} is signed, and numbering it would break the signature"), &[("name", &name)]));
}
Ok(id)
}
}
+1
View File
@@ -61,6 +61,7 @@ fn results(app: &mut PdfCraftApp, ctx: &egui::Context) {
app.about_pass(ctx);
app.pin_tools_pass(ctx);
app.marks_pass(ctx);
app.bates_files_pass(ctx);
app.printer_marks_pass(ctx);
app.convert_colours_pass(ctx);
app.fix_hairlines_pass(ctx);
+106
View File
@@ -0,0 +1,106 @@
//! Bates numbering ▸ Add to files…: one run over several files, written as numbered copies.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::support::AppHarness as _;
use craft::host::{Picked, ScriptedFiles};
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind};
use pdfcraft_ui_egui::PdfCraftApp;
fn harness(files: Arc<ScriptedFiles>) -> Harness<'static, PdfCraftApp> {
let host = crate::support::host_with_files(files);
Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(move |cc| {
crate::support::install_runtime(&cc.egui_ctx);
let mut app = crate::support::test_app(host);
app.set_option(&egui::Context::default(), "language", "en").unwrap();
app
})
}
/// The Bates number on each page of `pdf`: the run of digits in the page's text after "CASE-".
fn numbers(pdf: Vec<u8>) -> Vec<u64> {
let mut r = PageRenderer::new(Arc::new(pdf), Default::default());
(0..r.page_count())
.map(|p| {
let out = r.render(RenderRequest { page: p, kind: RequestKind::Text, scale: 1.0, ..Default::default() });
let text = out.text.map(|t| t.plain_text()).unwrap_or_default();
let at = text.find("CASE-").expect("a Bates number on every page") + "CASE-".len();
text[at..].chars().take_while(char::is_ascii_digit).collect::<String>().parse().unwrap()
})
.collect()
}
/// Opens the dialog, fills its list with `sources` through Browse, types the prefix and presses Number.
fn number(h: &mut Harness<'static, PdfCraftApp>) {
assert!(h.execute("edit.bates_files"));
h.run_steps(3);
let dialog = h.get_by_role_and_label(Role::Dialog, "Add Bates Numbering to Files");
dialog.get_by_label("Browse…").click();
h.run_steps(3);
h.get_by_role_and_label(Role::TextInput, "Prefix").type_text("CASE-");
h.run_steps(2);
h.get_by_label("Number").click();
h.run_steps(4);
}
fn paths() -> (PathBuf, PathBuf) {
(Path::new("case").join("b.pdf"), Path::new("case").join("a.pdf"))
}
#[test]
fn each_copy_continues_the_numbers_of_the_one_before_and_the_originals_stay() {
let (b, a) = paths();
let (b_bytes, a_bytes) = (crate::support::fixtures::pdf_pages(2), crate::support::fixtures::pdf_pages(3));
let files =
Arc::new(ScriptedFiles::answering([Picked::Paths(vec![b.clone(), a.clone()])]).with_file(&b, b_bytes.clone()).with_file(&a, a_bytes.clone()));
let mut h = harness(files.clone());
number(&mut h);
let first = numbers(files.file(&Path::new("case").join("b_Bates.pdf")).expect("the first file's copy"));
let second = numbers(files.file(&Path::new("case").join("a_Bates.pdf")).expect("the second file's copy"));
assert_eq!(first.len(), 2);
assert_eq!(second.len(), 3);
for pages in [&first, &second] {
assert!(pages.windows(2).all(|w| w[1] == w[0] + 1), "pages count up by one: {pages:?}");
}
assert_eq!(second[0], first[1] + 1, "the list's second file starts after the first one's last page");
assert_eq!(files.file(&b), Some(b_bytes), "the original is not changed");
assert_eq!(files.file(&a), Some(a_bytes), "the original is not changed");
}
#[test]
fn a_copy_that_exists_already_means_nothing_is_written() {
let (b, a) = paths();
let taken = Path::new("case").join("a_Bates.pdf");
let files = Arc::new(
ScriptedFiles::answering([Picked::Paths(vec![b.clone(), a.clone()])])
.with_file(&b, crate::support::fixtures::pdf_pages(2))
.with_file(&a, crate::support::fixtures::pdf_pages(1))
.with_file(&taken, b"keep".to_vec()),
);
let mut h = harness(files.clone());
number(&mut h);
assert!(files.written().is_empty(), "no copy is written when one can't be: {:?}", files.written());
assert_eq!(files.file(&taken).as_deref(), Some(&b"keep"[..]), "the file there is kept");
let notice = crate::support::shown_notice(&h).unwrap_or_default();
assert!(notice.contains("a_Bates.pdf"), "the notice names the copy in the way: {notice}");
}
#[test]
fn two_copies_that_would_share_a_name_mean_nothing_is_written() {
// On a case-insensitive disk the two copies are one file, so the second would replace the first.
let (lower, upper) = (Path::new("case").join("a.pdf"), Path::new("case").join("A.pdf"));
let files = Arc::new(
ScriptedFiles::answering([Picked::Paths(vec![lower.clone(), upper.clone()])])
.with_file(&lower, crate::support::fixtures::pdf_pages(1))
.with_file(&upper, crate::support::fixtures::pdf_pages(1)),
);
let mut h = harness(files.clone());
number(&mut h);
assert!(files.written().is_empty(), "neither copy is written: {:?}", files.written());
let notice = crate::support::shown_notice(&h).unwrap_or_default();
assert!(notice.contains("_Bates.pdf"), "the notice names the shared copy name: {notice}");
}
+1
View File
@@ -22,6 +22,7 @@ mod actions;
mod animate;
mod attach_picker_target;
mod attachment_row;
mod bates_files;
mod bookmark_position;
mod bookmarks;
mod bulk_fields;
+8 -3
View File
@@ -2614,10 +2614,15 @@ area = "C"
tier = "P1"
milestone = "M7"
status = "partial"
commands = []
commands = ["edit.bates_files"]
tools = ["doc_bates_multi"]
evidence = ["crates/automation/tests/it/automation.rs::bates_numbers_continue_across_files_and_report_preflight_and_permission_failures"]
notes = "The headless batch tool allocates inclusive intervals in input order and reports per-file failures; it refuses existing output paths. Missing: a GUI batch dialog (Acrobat sets this up from Header & Footer ▸ Add Bates numbering with a file list), so it is reachable only through `doc_bates_multi`."
evidence = [
"crates/automation/tests/it/automation.rs::bates_numbers_continue_across_files_and_report_preflight_and_permission_failures",
"crates/ui-egui/tests/it/bates_files.rs::each_copy_continues_the_numbers_of_the_one_before_and_the_originals_stay",
"crates/ui-egui/tests/it/bates_files.rs::a_copy_that_exists_already_means_nothing_is_written",
"crates/ui-egui/tests/it/bates_files.rs::two_copies_that_would_share_a_name_mean_nothing_is_written",
]
notes = "Bates numbering ▸ Add to files… numbers a list of files as one run, in list order, each file starting after the last number of the one before, with the prefix, suffix, digits, start and box of the single-file token. It writes numbered copies (`<name>_Bates.pdf` beside each original, or in a chosen folder) and never changes the originals. Before writing anything it refuses a copy that would land on another copy (names compared without letter case) or on any file that exists, an original included, and a file that can't be read or numbered. A write that fails partway leaves the copies already written and says how many. `doc_bates_multi` numbers the same way headless, with explicit output paths and a password per file. Missing: the dialog can't number password-protected or signed files (it says so and writes nothing), and it numbers on the frame thread, so a long list holds the window until it is done."
[[feature]]
id = "edit.bates-remove"