mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-26 04:58:07 +00:00
pdf-workflows-w11: net change of 2 commits
- pdf-workflows-w11: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot) - pdf-workflows-w11: review fixes (review-1)
This commit is contained in:
@@ -1,46 +1,23 @@
|
||||
//! Create a PDF (blank, from images, from text) and Reduce File Size (execution plan M10.2,
|
||||
//! M11.1). Opening an image or a text file converts it to a new, unsaved PDF, as Acrobat does.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::file_filter::AddFilterAnyCase as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::host::{PickRequest, Picked, WriteIntent};
|
||||
use craft::platform::clipboard::TEXT;
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::dialog::{DialogResult, dialog_id};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
|
||||
use crate::PdfCraftApp;
|
||||
use crate::widgets;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ResolutionChoice {
|
||||
#[default]
|
||||
Image,
|
||||
Default72,
|
||||
Custom,
|
||||
}
|
||||
/// The dialog key of the image import: the id its result is taken by.
|
||||
const IMAGES_DIALOG: &str = "create.images";
|
||||
|
||||
/// The images staged for the resolution dialog; no document exists until the dialog confirms.
|
||||
pub struct ImageImport {
|
||||
pub images: Vec<(String, Vec<u8>)>,
|
||||
pub choice: ResolutionChoice,
|
||||
pub dpi: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn image_import_body(ui: &mut egui::Ui, app: &mut PdfCraftApp) -> (bool, bool) {
|
||||
ui.heading(tl!("Create PDF from images"));
|
||||
let Some(draft) = app.image_import.as_mut() else { return (false, true) };
|
||||
ui.label(crate::i18n::fmt(tl!("Selected image files: {count}"), &[("count", &draft.images.len().to_string())]));
|
||||
ui.add_space(8.0);
|
||||
widgets::radio_value(ui, &mut draft.choice, ResolutionChoice::Image, tl!("Use image resolution"));
|
||||
ui.label(tl!("Use each image's embedded DPI; use 72 DPI when it is absent."));
|
||||
widgets::radio_value(ui, &mut draft.choice, ResolutionChoice::Default72, tl!("Use 72 DPI (one point per pixel)"));
|
||||
widgets::radio_value(ui, &mut draft.choice, ResolutionChoice::Custom, tl!("Use custom DPI"));
|
||||
ui.add_enabled(draft.choice == ResolutionChoice::Custom, egui::DragValue::new(&mut draft.dpi).range(1.0..=1200.0).suffix(" DPI"));
|
||||
ui.label(tl!("DPI sets the printed page size without resampling the image."));
|
||||
ui.add_space(12.0);
|
||||
let mut go = false;
|
||||
let mut cancel = false;
|
||||
ui.horizontal(|ui| {
|
||||
go = crate::widgets::pill_button(ui, tl!("Create"), true).clicked();
|
||||
cancel = crate::widgets::pill_button(ui, tl!("Cancel"), false).clicked();
|
||||
});
|
||||
(go, cancel)
|
||||
}
|
||||
|
||||
/// What Create ▸ Clipboard found on the clipboard.
|
||||
@@ -55,32 +32,9 @@ pub enum Clip {
|
||||
Text(String),
|
||||
}
|
||||
|
||||
/// An image on the system clipboard, or else its text.
|
||||
pub(crate) const MAX_IMAGE_SIDE: usize = 16384;
|
||||
pub(crate) const MAX_IMAGE_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_clipboard() -> Option<Clip> {
|
||||
crate::os_clipboard::with(|cb| {
|
||||
if let Ok(img) = cb.get_image() {
|
||||
let expected_len = img.width.checked_mul(img.height).and_then(|px| px.checked_mul(4));
|
||||
if img.width > 0
|
||||
&& img.height > 0
|
||||
&& img.width <= MAX_IMAGE_SIDE
|
||||
&& img.height <= MAX_IMAGE_SIDE
|
||||
&& expected_len == Some(img.bytes.len())
|
||||
&& img.bytes.len() <= MAX_IMAGE_BYTES
|
||||
{
|
||||
return Ok(Some(Clip::Image { width: img.width, height: img.height, rgba: img.bytes.into_owned() }));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(cb.get_text().ok().filter(|t| !t.trim().is_empty()).map(Clip::Text))
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn png_from_rgba(width: usize, height: usize, rgba: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let (w, h) = (u32::try_from(width).map_err(|e| e.to_string())?, u32::try_from(height).map_err(|e| e.to_string())?);
|
||||
let expected = width.checked_mul(height).and_then(|p| p.checked_mul(4));
|
||||
@@ -95,6 +49,49 @@ fn stem(name: &str) -> &str {
|
||||
name.rsplit_once('.').map_or(name, |(s, _)| s)
|
||||
}
|
||||
|
||||
/// The resolution dialog over `count` staged images. The values are the host's; `build` makes the dialog over them
|
||||
/// each pass.
|
||||
fn image_import_dialog(ctx: &egui::Context, count: usize) -> HostedParamDialog {
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("resolution", FieldValue::Text("image".into()));
|
||||
fields.set("dpi", FieldValue::Int(300));
|
||||
HostedParamDialog::new(ctx, IMAGES_DIALOG, fields, move |fields| {
|
||||
let options = vec![
|
||||
("image".to_string(), tl!("Use image resolution").into()),
|
||||
("72".to_string(), tl!("Use 72 DPI (one point per pixel)").into()),
|
||||
("custom".to_string(), tl!("Use custom DPI").into()),
|
||||
];
|
||||
let params = vec![
|
||||
Param::read_only_text(
|
||||
"count",
|
||||
tl!("Images"),
|
||||
crate::i18n::fmt(tl!("Selected image files: {count}"), &[("count", &count.to_string())]),
|
||||
),
|
||||
Param::new("resolution", tl!("Resolution"), ParamKind::radio(options, Some("image".to_string()))),
|
||||
Param::read_only_text("embedded", tl!("Image resolution"), tl!("Use each image's embedded DPI; use 72 DPI when it is absent.")),
|
||||
Param::new("dpi", tl!("DPI"), ParamKind::int(Some(1), Some(1200), 300)).enabled_when("resolution", FieldValue::Text("custom".into())),
|
||||
];
|
||||
ParamDialog::new(IMAGES_DIALOG, tl!("Create PDF from Images"), params)
|
||||
.values(Bind::bound(fields))
|
||||
.ok_label(tl!("Create"))
|
||||
.footer_note(tl!("DPI sets the printed page size without resampling the image."))
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes the image dialog's answer once it has finished: OK creates the document at the chosen resolution, Cancel
|
||||
/// creates nothing. Either way the staged images are released.
|
||||
pub(crate) fn pass(app: &mut PdfCraftApp) {
|
||||
let Some(result) = app.dialogs.take_by_id::<HostedParamDialog>(dialog_id(IMAGES_DIALOG)) else { return };
|
||||
let Some(draft) = app.image_import.take() else { return };
|
||||
let DialogResult::Ok(answer) = result else { return };
|
||||
let resolution = match answer.fields.text("resolution") {
|
||||
Some("72") => pdfcraft_engine::ImageResolution::Dpi(72.0),
|
||||
Some("custom") => pdfcraft_engine::ImageResolution::Dpi(answer.fields.int("dpi").unwrap_or(300) as f64),
|
||||
_ => pdfcraft_engine::ImageResolution::Embedded,
|
||||
};
|
||||
app.create_from_images_with_resolution(draft.images, resolution);
|
||||
}
|
||||
|
||||
impl PdfCraftApp {
|
||||
/// Convert a non-PDF file (image, text, Office document) into a new tab. Returns `None` when
|
||||
/// `bytes` is not something Create understands (the caller then tries to open it as a PDF).
|
||||
@@ -112,17 +109,18 @@ impl PdfCraftApp {
|
||||
/// Open `created`, the PDF converted from the file `name`, as a new, unsaved tab named after
|
||||
/// it (`Report.docx` → `Report.pdf`).
|
||||
pub(crate) fn open_converted_pdf(&mut self, name: &str, created: Result<Arc<Vec<u8>>, String>) -> Result<(), String> {
|
||||
self.open_created_bytes(&format!("{}.pdf", stem(name)), created)
|
||||
created.and_then(|bytes| self.open_new_document(&format!("{}.pdf", stem(name)), bytes))
|
||||
}
|
||||
|
||||
fn open_created_bytes(&mut self, name: &str, created: Result<Arc<Vec<u8>>, String>) -> Result<(), String> {
|
||||
let bytes = created?;
|
||||
/// Open `bytes`, a PDF the app just made, as a new, unsaved tab called `name`.
|
||||
pub(crate) fn open_new_document(&mut self, name: &str, bytes: Arc<Vec<u8>>) -> Result<(), String> {
|
||||
let id = self.session.open_new(name, bytes).map_err(|e| e.to_string())?;
|
||||
// The reading-colours preference is app-wide: the newly created document starts with it.
|
||||
self.session.set_reading_colors(id, self.reading_colors);
|
||||
let info = &self.session.get(id).ok_or("the new document could not be opened")?.info;
|
||||
let mut view = crate::DocView::new(id, info, self.view_defaults);
|
||||
if self.full_screen {
|
||||
let info = &self.session.get(id).ok_or_else(|| tl!("the new document could not be opened").to_string())?.info;
|
||||
let mut view = crate::DocView::new(id, info, self.view_defaults, self.highlight_fields);
|
||||
// PLAN: assumed `full_screen() -> bool` (pdf-shell-w8)
|
||||
if self.full_screen() {
|
||||
view.enter_presentation();
|
||||
}
|
||||
self.views.push(view);
|
||||
@@ -130,14 +128,23 @@ impl PdfCraftApp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The system clipboard's text when it has any, else its image: Create ▸ Clipboard takes what the user copied last,
|
||||
/// and a cached image never hides newer text.
|
||||
fn read_clipboard(&mut self) -> Option<Clip> {
|
||||
if let Ok(Some(flavor)) = self.clipboard.read(&[TEXT])
|
||||
&& let Ok(text) = String::from_utf8(flavor.data)
|
||||
&& !text.trim().is_empty()
|
||||
{
|
||||
return Some(Clip::Text(text));
|
||||
}
|
||||
let image = self.clipboard.read_image().ok().flatten()?;
|
||||
Some(Clip::Image { width: image.width as usize, height: image.height as usize, rgba: image.rgba })
|
||||
}
|
||||
|
||||
/// Create ▸ Clipboard: a new document from the image (one page, its size) or the text on
|
||||
/// the clipboard, as Acrobat does.
|
||||
pub(crate) fn create_from_clipboard(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let clip = read_clipboard();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let clip: Option<Clip> = None;
|
||||
match clip {
|
||||
match self.read_clipboard() {
|
||||
Some(c) => {
|
||||
if let Err(e) = self.create_from_clip(c) {
|
||||
self.notify_fmt("Couldn't create a PDF: {e}", &[("e", &e.to_string())]);
|
||||
@@ -156,41 +163,46 @@ impl PdfCraftApp {
|
||||
}
|
||||
Clip::Text(t) => self.session.create_from_text("Clipboard", &t),
|
||||
};
|
||||
self.open_created_bytes("Clipboard.pdf", created.map_err(|e| e.to_string()))
|
||||
created.map_err(|e| e.to_string()).and_then(|bytes| self.open_new_document("Clipboard.pdf", bytes))
|
||||
}
|
||||
|
||||
/// Create ▸ Blank page: a new untitled document on the system region's paper (#5644).
|
||||
pub(crate) fn create_blank(&mut self) {
|
||||
let (w, h) = self.blank_paper.points();
|
||||
let created = self.session.create_blank(w, h, 1).map_err(|e| e.to_string());
|
||||
if let Err(e) = self.open_created_bytes("Untitled.pdf", created) {
|
||||
if let Err(e) = created.and_then(|bytes| self.open_new_document("Untitled.pdf", bytes)) {
|
||||
self.notify_fmt("Couldn't create a PDF: {e}", &[("e", &e.to_string())]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Create ▸ Images: several images, one page each, in one new document.
|
||||
pub(crate) fn create_from_images_dialog(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let dialog = rfd::AsyncFileDialog::new()
|
||||
.add_filter_any_case(tl!("Images"), &["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx"])
|
||||
.set_title(tl!("Choose images"));
|
||||
self.ask(crate::pickers::Ask::Files(dialog), None, |app, files| {
|
||||
let mut images = Vec::new();
|
||||
for f in files {
|
||||
match std::fs::read(&f) {
|
||||
Ok(b) => images.push((f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), b)),
|
||||
Err(e) => {
|
||||
app.notify_fmt("Couldn't read {name}: {e}", &[("name", &f.display().to_string()), ("e", &e.to_string())]);
|
||||
return;
|
||||
// PLAN: the `create.images` command in `commands.rs:259` (pdf-hub-w3) must pass the `egui::Context` its execution receives (L-208)
|
||||
pub(crate) fn create_from_images_dialog(&mut self, ctx: &egui::Context) {
|
||||
let request = PickRequest::open_many("create.images")
|
||||
.title(tl!("Choose images"))
|
||||
.filter(tl!("Images"), &["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx"]);
|
||||
let ctx = ctx.clone();
|
||||
self.pick_file(request, None, move |app, picked| {
|
||||
let images = match picked {
|
||||
// The browser hands over the bytes with the names.
|
||||
Picked::Contents(files) => files,
|
||||
Picked::Paths(paths) => {
|
||||
let mut images = Vec::new();
|
||||
for f in paths {
|
||||
match app.host.files().read(&f) {
|
||||
Ok(b) => images.push((f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), b)),
|
||||
Err(e) => {
|
||||
app.notify_fmt("Couldn't read {name}: {e}", &[("name", &f.display().to_string()), ("e", &e.to_string())]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
images
|
||||
}
|
||||
app.begin_image_import(images);
|
||||
});
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
self.notify_tr("On the web, open or drop an image to convert it");
|
||||
Picked::Cancelled | Picked::Unavailable(_) => return,
|
||||
};
|
||||
app.begin_image_import(&ctx, images);
|
||||
});
|
||||
}
|
||||
|
||||
/// One new document from images (tests and automation call this directly).
|
||||
@@ -199,8 +211,9 @@ impl PdfCraftApp {
|
||||
}
|
||||
|
||||
/// Stage selected images for the DPI chooser; no document is created until confirmed.
|
||||
// PLAN: `apps/pdfcraft/src/main.rs:536` must pass its `egui::Context` (the owner of that caller)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn begin_image_import_paths(&mut self, paths: &[String]) -> Result<(), String> {
|
||||
pub fn begin_image_import_paths(&mut self, ctx: &egui::Context, paths: &[String]) -> Result<(), String> {
|
||||
let images = paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
@@ -210,27 +223,18 @@ impl PdfCraftApp {
|
||||
Ok((name, bytes))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
self.begin_image_import(images);
|
||||
self.begin_image_import(ctx, images);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage selected images for the DPI chooser; no document is created until confirmed.
|
||||
pub fn begin_image_import(&mut self, images: Vec<(String, Vec<u8>)>) {
|
||||
pub fn begin_image_import(&mut self, ctx: &egui::Context, images: Vec<(String, Vec<u8>)>) {
|
||||
if images.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.image_import = Some(ImageImport { images, choice: ResolutionChoice::Image, dpi: 300.0 });
|
||||
self.dialog = Some(crate::Dialog::CreateImages);
|
||||
}
|
||||
|
||||
pub(crate) fn finish_image_import(&mut self) {
|
||||
let Some(draft) = self.image_import.take() else { return };
|
||||
let resolution = match draft.choice {
|
||||
ResolutionChoice::Image => pdfcraft_engine::ImageResolution::Embedded,
|
||||
ResolutionChoice::Default72 => pdfcraft_engine::ImageResolution::Dpi(72.0),
|
||||
ResolutionChoice::Custom => pdfcraft_engine::ImageResolution::Dpi(draft.dpi),
|
||||
};
|
||||
self.create_from_images_with_resolution(draft.images, resolution);
|
||||
let dialog = image_import_dialog(ctx, images.len());
|
||||
self.image_import = Some(ImageImport { images });
|
||||
crate::dialogs::host::open(self, dialog);
|
||||
}
|
||||
|
||||
/// Create directly at the requested resolution (also used by UI tests).
|
||||
@@ -241,7 +245,7 @@ impl PdfCraftApp {
|
||||
let name =
|
||||
if let Some((name, _)) = images.first().filter(|_| images.len() == 1) { format!("{}.pdf", stem(name)) } else { "Images.pdf".to_string() };
|
||||
let created = self.session.create_from_images_with_resolution(&images, resolution).map_err(|e| e.to_string());
|
||||
if let Err(e) = self.open_created_bytes(&name, created) {
|
||||
if let Err(e) = created.and_then(|bytes| self.open_new_document(&name, bytes)) {
|
||||
self.notify_fmt("Couldn't create a PDF: {e}", &[("e", &e.to_string())]);
|
||||
}
|
||||
}
|
||||
@@ -252,33 +256,32 @@ impl PdfCraftApp {
|
||||
pub(crate) fn reduce_file_size(&mut self) {
|
||||
use crate::optimize_ui::OptimizeKind::Reduce;
|
||||
let settings = pdfcraft_engine::optimize::Settings::default();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
self.start_optimize(Reduce, &settings, &[]);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// What can't run says so now, not after asking where to save.
|
||||
if !self.commit_form_typing() {
|
||||
return;
|
||||
}
|
||||
let Some((_, id)) = self.active_ids() else { return };
|
||||
if self.optimize_run.is_some() {
|
||||
self.notify_tr("Optimization is already running");
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.session.optimize_job(id, &settings, &[]) {
|
||||
return self.save_optimized(id, Reduce, Err(e), None);
|
||||
}
|
||||
if let Some(path) = self.save_override.clone() {
|
||||
return self.run_optimize(id, Reduce, &settings, &[], Some(path));
|
||||
}
|
||||
let Some(doc) = self.session.get(id) else { return };
|
||||
let dialog = rfd::AsyncFileDialog::new().add_filter_any_case("PDF", &["pdf"]).set_file_name(optimized_name(&doc.name, Reduce));
|
||||
let dialog = crate::editing::in_document_folder(dialog, doc.path.as_deref());
|
||||
// With the target, a document closed, switched from or edited meanwhile isn't compressed.
|
||||
self.ask_one(crate::pickers::Ask::Save(dialog), Some(id), move |app, path| {
|
||||
app.run_optimize(id, Reduce, &settings, &[], Some(path.to_string_lossy().into_owned()));
|
||||
});
|
||||
// What can't run says so now, not after asking where to save.
|
||||
if !self.commit_form_typing() {
|
||||
return;
|
||||
}
|
||||
let Some((_, id)) = self.active_ids() else { return };
|
||||
if self.optimize_run.is_some() {
|
||||
self.notify_tr("Optimization is already running");
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.session.optimize_job(id, &settings, &[]) {
|
||||
return self.save_optimized(id, Reduce, Err(e), None);
|
||||
}
|
||||
let Some(doc) = self.session.get(id) else { return };
|
||||
let name = optimized_name(&doc.name, Reduce);
|
||||
let folder = doc.path.as_deref().and_then(|p| Path::new(p).parent()).map(Path::to_path_buf);
|
||||
let mut request = PickRequest::save("reduce").file_name(name).filter("PDF", &["pdf"]);
|
||||
if let Some(folder) = folder {
|
||||
request = request.default_directory(folder);
|
||||
}
|
||||
// With the target, a document closed, switched from or edited meanwhile isn't compressed.
|
||||
let target = self.pick_target(Some(id));
|
||||
self.pick_file(request, target, move |app, picked| {
|
||||
if let Some(path) = picked.paths().into_iter().next() {
|
||||
app.run_optimize(id, Reduce, &settings, &[], Some(path.to_string_lossy().into_owned()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Save an optimized copy (Reduce File Size, Optimize PDF) to `destination`, or where the user
|
||||
@@ -293,8 +296,7 @@ impl PdfCraftApp {
|
||||
) {
|
||||
let Some(doc) = self.session.get(id) else { return };
|
||||
let (before, name) = (doc.bytes.len(), optimized_name(&doc.name, kind));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let folder = doc.path.clone();
|
||||
let folder = doc.path.as_deref().and_then(|p| Path::new(p).parent()).map(Path::to_path_buf);
|
||||
let (bytes, detail) = match result {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
@@ -326,53 +328,41 @@ impl PdfCraftApp {
|
||||
);
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let chose_first = destination.is_some() && self.save_override.is_none();
|
||||
match destination.or_else(|| self.save_override.clone()) {
|
||||
Some(path) => match crate::editing::write_atomically(&path, &bytes) {
|
||||
Ok(()) => saved(self, path),
|
||||
Err(e) => {
|
||||
self.notify_fmt("Couldn't write {path}: {e}", &[("path", &path), ("e", &e.to_string())]);
|
||||
// The copy can have taken minutes: a place that has gone bad since doesn't lose it.
|
||||
if chose_first {
|
||||
self.ask_where_to_save_optimized(name, folder, bytes, saved);
|
||||
}
|
||||
}
|
||||
},
|
||||
None => self.ask_where_to_save_optimized(name, folder, bytes, saved),
|
||||
}
|
||||
match destination {
|
||||
Some(path) => self.write_optimized(path, name, folder, bytes, saved),
|
||||
None => self.ask_where_to_save_optimized(name, folder, bytes, saved),
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = destination;
|
||||
match crate::editing::download(&name, &bytes) {
|
||||
Ok(()) => saved(self, name),
|
||||
Err(e) => self.notify_fmt("Couldn't download {name}: {e}", &[("name", &name), ("e", &e.to_string())]),
|
||||
}
|
||||
|
||||
/// Write an optimized copy to `path`. The copy can have taken minutes: a place that has gone bad since doesn't
|
||||
/// lose it, so a failed write asks again.
|
||||
fn write_optimized(
|
||||
&mut self,
|
||||
path: String,
|
||||
name: String,
|
||||
folder: Option<PathBuf>,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
saved: impl FnOnce(&mut Self, String) + 'static,
|
||||
) {
|
||||
match self.host.files().write(Path::new(&path), &bytes, WriteIntent::SaveAs) {
|
||||
Ok(_) => saved(self, path),
|
||||
Err(e) => {
|
||||
self.notify_fmt("Couldn't write {path}: {e}", &[("path", &path), ("e", &e.to_string())]);
|
||||
self.ask_where_to_save_optimized(name, folder, bytes, saved);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask where an optimized copy goes and write it there, asking again until it is written or
|
||||
/// the question is cancelled.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ask_where_to_save_optimized(
|
||||
&mut self,
|
||||
name: String,
|
||||
folder: Option<String>,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
saved: impl FnOnce(&mut Self, String) + Send + 'static,
|
||||
) {
|
||||
let dialog = rfd::AsyncFileDialog::new().add_filter_any_case("PDF", &["pdf"]).set_file_name(&name);
|
||||
let dialog = crate::editing::in_document_folder(dialog, folder.as_deref());
|
||||
self.ask_one(crate::pickers::Ask::Save(dialog), None, move |app, p| {
|
||||
let path = p.to_string_lossy().into_owned();
|
||||
match crate::editing::write_atomically(&path, &bytes) {
|
||||
Ok(()) => saved(app, path),
|
||||
Err(e) => {
|
||||
app.notify_fmt("Couldn't write {path}: {e}", &[("path", &path), ("e", &e.to_string())]);
|
||||
app.ask_where_to_save_optimized(name, folder, bytes, saved);
|
||||
}
|
||||
fn ask_where_to_save_optimized(&mut self, name: String, folder: Option<PathBuf>, bytes: Arc<Vec<u8>>, saved: impl FnOnce(&mut Self, String) + 'static) {
|
||||
let mut request = PickRequest::save("reduce").file_name(name.clone()).filter("PDF", &["pdf"]);
|
||||
if let Some(folder) = &folder {
|
||||
request = request.default_directory(folder.clone());
|
||||
}
|
||||
self.pick_file(request, None, move |app, picked| {
|
||||
if let Some(path) = picked.paths().into_iter().next() {
|
||||
app.write_optimized(path.to_string_lossy().into_owned(), name, folder, bytes, saved);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -382,3 +372,190 @@ impl PdfCraftApp {
|
||||
fn optimized_name(document: &str, kind: crate::optimize_ui::OptimizeKind) -> String {
|
||||
format!("{} ({}).pdf", stem(document), kind.suffix())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft::host::{AppInfo, FileError, Files, Host, ManualJobs, PickId, PickRequest, Picked, ScriptedFiles, WriteIntent};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
use crate::PdfCraftApp;
|
||||
|
||||
/// A one-page document showing `text`, with an unencoded content stream long enough that
|
||||
/// Reduce File Size makes a smaller copy (it saves none otherwise).
|
||||
fn text_pdf(text: &str) -> Vec<u8> {
|
||||
let content = format!("BT /F1 12 Tf 20 250 Td ({text}) Tj ET\n{}", "q Q\n".repeat(500));
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_string(),
|
||||
format!("<< /Length {} >>\nstream\n{content}endstream", content.len()),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".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
|
||||
}
|
||||
|
||||
/// An app on `files` and `jobs` with `notes.pdf` open, in a harness.
|
||||
fn reducing(files: Arc<dyn Files>, jobs: Arc<ManualJobs>, source: Vec<u8>) -> Harness<'static, PdfCraftApp> {
|
||||
let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).jobs(jobs).build());
|
||||
// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (L-207, pdf-hub-w1)
|
||||
let services = crate::AppServices::new(craft::host::Wake::none(), None, None, None, None, None);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::with_host(host, services);
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.session = std::mem::take(&mut app.session).with_clock(|| 1_700_000_000);
|
||||
app.open_bytes("notes.pdf", None, source).unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(2);
|
||||
h
|
||||
}
|
||||
|
||||
fn reopened_text(bytes: Vec<u8>) -> String {
|
||||
let mut again = pdfcraft_engine::Session::new();
|
||||
let id = again.open("notes (reduced).pdf", None, Arc::new(bytes), None).unwrap();
|
||||
pdfcraft_engine::export::Exporter::new(again.get(id).unwrap()).text(0).unwrap()
|
||||
}
|
||||
|
||||
/// Files whose first `fails` writes are refused, as a place that has gone bad.
|
||||
struct FailingWrites {
|
||||
inner: Arc<ScriptedFiles>,
|
||||
fails: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl Files for FailingWrites {
|
||||
fn pick(&self, request: PickRequest) -> PickId {
|
||||
self.inner.pick(request)
|
||||
}
|
||||
fn take_answer(&self, id: PickId) -> Option<Picked> {
|
||||
self.inner.take_answer(id)
|
||||
}
|
||||
fn forget(&self, id: PickId) {
|
||||
self.inner.forget(id);
|
||||
}
|
||||
fn pick_pending(&self) -> bool {
|
||||
self.inner.pick_pending()
|
||||
}
|
||||
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
|
||||
self.inner.read(path)
|
||||
}
|
||||
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
|
||||
let mut fails = self.fails.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if *fails > 0 {
|
||||
*fails -= 1;
|
||||
return Err(FileError::PermissionDenied(path.to_path_buf()));
|
||||
}
|
||||
drop(fails);
|
||||
self.inner.write(path, bytes, intent)
|
||||
}
|
||||
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
|
||||
self.inner.last_folder(purpose)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduce_file_size_asks_where_to_save_before_it_compresses() {
|
||||
let out = PathBuf::from("/reduced/notes (reduced).pdf");
|
||||
let files = Arc::new(ScriptedFiles::held());
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = reducing(files.clone(), jobs.clone(), text_pdf("Minutes of the harbour board"));
|
||||
h.state_mut().reduce_file_size();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().optimize_run.is_none() && jobs.waiting() == 0, "nothing runs until the answer is in");
|
||||
assert_eq!(files.open(), 1, "the question is out");
|
||||
assert!(files.file(&out).is_none(), "no copy is written before the answer");
|
||||
files.answer(Picked::Paths(vec![out.clone()]));
|
||||
h.run_steps(2);
|
||||
jobs.run_all();
|
||||
h.run_steps(3);
|
||||
assert_eq!(files.requests().len(), 1, "no second question");
|
||||
let written = files.file(&out).expect("the copy is written where the user chose");
|
||||
let text = reopened_text(written);
|
||||
assert!(text.contains("Minutes of the harbour board"), "the copy reopens with its text: {text:?}");
|
||||
}
|
||||
|
||||
/// The answer is for the document it was asked about.
|
||||
#[test]
|
||||
fn switching_documents_while_reduce_file_size_asks_compresses_nothing() {
|
||||
let out = PathBuf::from("/reduced/notes (reduced).pdf");
|
||||
let files = Arc::new(ScriptedFiles::held());
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = reducing(files.clone(), jobs.clone(), text_pdf("Minutes of the harbour board"));
|
||||
h.state_mut().reduce_file_size();
|
||||
h.run_steps(2);
|
||||
h.state_mut().open_bytes("other.pdf", None, text_pdf("Another document")).unwrap();
|
||||
files.answer(Picked::Paths(vec![out.clone()]));
|
||||
h.run_steps(3);
|
||||
jobs.run_all();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().optimize_run.is_none() && files.file(&out).is_none(), "nothing runs, and nothing is written");
|
||||
}
|
||||
|
||||
/// Minutes of work aren't lost because the place chosen first has gone bad.
|
||||
#[test]
|
||||
fn a_reduced_copy_asks_until_it_can_be_written() {
|
||||
let good = PathBuf::from("/good/notes (reduced).pdf");
|
||||
let inner = Arc::new(ScriptedFiles::answering([
|
||||
Picked::Paths(vec![PathBuf::from("/gone1/notes (reduced).pdf")]),
|
||||
Picked::Paths(vec![PathBuf::from("/gone2/notes (reduced).pdf")]),
|
||||
Picked::Paths(vec![good.clone()]),
|
||||
]));
|
||||
let files = Arc::new(FailingWrites { inner: inner.clone(), fails: Mutex::new(2) });
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = reducing(files, jobs.clone(), text_pdf("Minutes of the harbour board"));
|
||||
h.state_mut().reduce_file_size();
|
||||
h.run_steps(2);
|
||||
jobs.run_all();
|
||||
h.run_steps(8);
|
||||
assert_eq!(inner.requests().len(), 3, "each unwritable place raises a new question");
|
||||
assert!(inner.file(&good).is_some(), "the copy lands at the third place");
|
||||
}
|
||||
|
||||
/// A chosen existing file stays as it was when no copy is made.
|
||||
#[test]
|
||||
fn a_reduced_copy_that_isnt_smaller_leaves_the_chosen_file_alone() {
|
||||
let out = PathBuf::from("/out/notes (reduced).pdf");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out.clone()])]).with_file(out.clone(), b"keep this file".to_vec()));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = reducing(files.clone(), jobs.clone(), text_pdf("Minutes"));
|
||||
// A copy of a plain text file is no smaller.
|
||||
h.state_mut().open_bytes("plain.txt", None, "lorem ipsum ".repeat(500).into_bytes()).unwrap();
|
||||
h.run_steps(2);
|
||||
h.state_mut().reduce_file_size();
|
||||
h.run_steps(2);
|
||||
jobs.run_all();
|
||||
h.run_steps(3);
|
||||
assert_eq!(files.file(&out).unwrap(), b"keep this file");
|
||||
h.get_by_label_contains("No copy was saved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduce_file_size_doesnt_ask_while_a_run_is_going() {
|
||||
let out = PathBuf::from("/out/notes (reduced).pdf");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out])]));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = reducing(files.clone(), jobs.clone(), text_pdf("Minutes of the harbour board"));
|
||||
h.state_mut().reduce_file_size();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().optimize_run.is_some(), "the first run is waiting for its job");
|
||||
h.state_mut().reduce_file_size();
|
||||
h.run_steps(2);
|
||||
assert_eq!(files.requests().len(), 1, "no second question");
|
||||
h.get_by_label_contains("Optimization is already running");
|
||||
}
|
||||
}
|
||||
|
||||
+114
-147
@@ -1,5 +1,10 @@
|
||||
//! Create a PDF and Reduce File Size in the real shell.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles};
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
use pdfcraft_ui_egui::PdfCraftApp;
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
@@ -7,13 +12,31 @@ fn png() -> Vec<u8> {
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A harness whose app asks `files` for its picks and runs its background work when the test steps `jobs`.
|
||||
fn scripted(
|
||||
files: Arc<ScriptedFiles>,
|
||||
jobs: Arc<ManualJobs>,
|
||||
size: egui::Vec2,
|
||||
setup: impl FnOnce(&mut PdfCraftApp) + 'static,
|
||||
) -> Harness<'static, PdfCraftApp> {
|
||||
let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).jobs(jobs).build());
|
||||
// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (L-207, pdf-hub-w1)
|
||||
let services = pdfcraft_ui_egui::AppServices::new(craft::host::Wake::none(), None, None, None, None, None);
|
||||
Harness::builder().with_size(size).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::with_host(host, services);
|
||||
app.set_option("language", "en").unwrap();
|
||||
setup(&mut app);
|
||||
app
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_import_dialog_chooses_dpi_and_cancels() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| {
|
||||
use egui::{Key, Modifiers};
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.begin_image_import(vec![("scan.png".into(), png())]);
|
||||
app.begin_image_import(&cc.egui_ctx, vec![("scan.png".into(), png())]);
|
||||
app
|
||||
});
|
||||
h.run_steps(3);
|
||||
@@ -28,16 +51,22 @@ fn image_import_dialog_chooses_dpi_and_cancels() {
|
||||
assert!(h.state().image_import.is_none());
|
||||
let page = &h.state().session.docs()[0].info.pages[0];
|
||||
assert_eq!((page.width, page.height), (8.0, 4.0));
|
||||
h.state_mut().begin_image_import(vec![("scan.png".into(), png())]);
|
||||
h.state_mut().image_import.as_mut().unwrap().dpi = 144.0;
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().begin_image_import(&ctx, vec![("scan.png".into(), png())]);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Use custom DPI").click();
|
||||
h.run_steps(1);
|
||||
h.run_steps(2);
|
||||
let field = h.get_by_label("DPI");
|
||||
field.focus();
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
|
||||
h.get_by_label("DPI").type_text("144");
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Create").click();
|
||||
h.run_steps(3);
|
||||
let page = &h.state().session.docs()[1].info.pages[0];
|
||||
assert_eq!((page.width, page.height), (4.0, 2.0));
|
||||
h.state_mut().begin_image_import(vec![("scan.png".into(), png())]);
|
||||
h.state_mut().begin_image_import(&ctx, vec![("scan.png".into(), png())]);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Cancel").click();
|
||||
h.run_steps(2);
|
||||
@@ -63,65 +92,34 @@ fn opening_images_and_text_converts_them_to_new_pdfs() {
|
||||
assert!(app.open_bytes("junk.png", None, b"\x89PNG\r\n\x1a\nnot really".to_vec()).is_err());
|
||||
}
|
||||
|
||||
struct ReduceDir(std::path::PathBuf);
|
||||
impl ReduceDir {
|
||||
fn new() -> Self {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
for _ in 0..128 {
|
||||
let path = std::env::temp_dir().join(format!("pdfcraft-reduce-test-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("creating Reduce test directory: {error}"),
|
||||
}
|
||||
}
|
||||
panic!("no unused Reduce test directory after 128 attempts");
|
||||
}
|
||||
}
|
||||
impl Drop for ReduceDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open `name` and run Reduce File Size on it, saving to `out` without a dialog.
|
||||
fn reduce(name: &'static str, bytes: Vec<u8>, out: &std::path::Path) -> egui_kittest::Harness<'static, PdfCraftApp> {
|
||||
let out2 = out.to_path_buf();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
/// Open `name` and run Reduce File Size on it, saving to a place the script answers with.
|
||||
fn reduce(name: &'static str, bytes: Vec<u8>) -> (Harness<'static, PdfCraftApp>, Arc<ScriptedFiles>, PathBuf) {
|
||||
let out = PathBuf::from("/reduced/reduced.pdf");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out.clone()])]));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = scripted(files.clone(), jobs.clone(), egui::vec2(1200.0, 800.0), move |app| {
|
||||
// Keep metadata identical: changing ModDate can make a compact PDF one byte smaller.
|
||||
app.session = std::mem::take(&mut app.session).with_clock(|| 1_700_000_000);
|
||||
app.open_bytes(name, None, bytes).unwrap();
|
||||
app.save_override = Some(out2.to_string_lossy().into_owned());
|
||||
app
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert!(h.state_mut().execute("optimize.reduce"));
|
||||
// It runs on a worker thread like the PDF Optimizer, with the progress card meanwhile.
|
||||
let start = std::time::Instant::now();
|
||||
while h.state().optimize_run.is_some() && start.elapsed() < std::time::Duration::from_secs(30) {
|
||||
h.run_steps(1);
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert!(h.state().optimize_run.is_none() && h.state().progress_notice.is_none(), "the run finished");
|
||||
h
|
||||
jobs.run_all();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().optimize_run.is_none(), "the run finished");
|
||||
(h, files, out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reduce_file_size_writes_a_compact_copy() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
// A photo-like picture, stored losslessly: Reduce recompresses it as JPEG.
|
||||
let (w, h) = (600u32, 400u32);
|
||||
let px: Vec<u8> = (0..w * h).flat_map(|i| [(i % w * 255 / w) as u8 ^ (i & 7) as u8, (i / w * 255 / h) as u8, 128]).collect();
|
||||
let img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgb, px).unwrap();
|
||||
let photo = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
let dir = ReduceDir::new();
|
||||
let out = dir.0.join("reduced.pdf");
|
||||
let h = reduce("photo.png", photo, &out);
|
||||
let bytes = std::fs::read(&out).unwrap();
|
||||
let (h, files, out) = reduce("photo.png", photo);
|
||||
let bytes = files.file(&out).expect("the copy is written");
|
||||
assert!(bytes.starts_with(b"%PDF-"));
|
||||
assert!(bytes.len() < h.state().session.docs()[0].bytes.len(), "the copy is smaller");
|
||||
assert!(h.state().session.docs()[0].dirty, "the open document is unchanged");
|
||||
@@ -130,12 +128,9 @@ fn reduce_file_size_writes_a_compact_copy() {
|
||||
|
||||
#[test]
|
||||
fn reduce_file_size_saves_nothing_when_the_file_is_already_small() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let dir = ReduceDir::new();
|
||||
let out = dir.0.join("reduced.pdf");
|
||||
// A new text PDF is already compact: a copy would be no smaller (#490).
|
||||
let h = reduce("notes.txt", "lorem ipsum ".repeat(500).into_bytes(), &out);
|
||||
assert!(!out.exists(), "no copy was written");
|
||||
let (h, files, out) = reduce("notes.txt", "lorem ipsum ".repeat(500).into_bytes());
|
||||
assert!(files.file(&out).is_none(), "no copy was written");
|
||||
h.get_by_label_contains("This file is already as small as it can be made");
|
||||
}
|
||||
|
||||
@@ -157,18 +152,11 @@ fn clipboard_images_and_text_become_new_pdfs() {
|
||||
|
||||
#[test]
|
||||
fn the_pdf_optimizer_dialog_saves_an_optimized_copy() {
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-optimizer-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let out = dir.join("optimized.pdf");
|
||||
let out2 = out.clone();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
let out = PathBuf::from("/optimized/optimized.pdf");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out.clone()])]));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = scripted(files.clone(), jobs.clone(), egui::vec2(1200.0, 800.0), |app| {
|
||||
app.open_bytes("notes.txt", None, "lorem ipsum ".repeat(500).into_bytes()).unwrap();
|
||||
app.save_override = Some(out2.to_string_lossy().into_owned());
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
assert!(h.state_mut().execute("optimize.advanced"));
|
||||
@@ -176,11 +164,9 @@ fn the_pdf_optimizer_dialog_saves_an_optimized_copy() {
|
||||
h.get_by_label("PDF Optimizer");
|
||||
h.get_by_label("Color Images");
|
||||
h.get_by_label("Monochrome Images");
|
||||
assert_eq!(h.state().optimize_draft.settings.mono, pdfcraft_engine::optimize::MonoSettings::REDUCE);
|
||||
// Monochrome Images ▸ Downsample to can be turned off.
|
||||
h.get_by_label("Downsample to").click();
|
||||
h.run_steps(2);
|
||||
assert!(!h.state().optimize_draft.settings.mono.downsample);
|
||||
h.get_by_label("Discard Objects").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Discard document tags").click();
|
||||
@@ -188,30 +174,17 @@ fn the_pdf_optimizer_dialog_saves_an_optimized_copy() {
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Discard document information and metadata").click();
|
||||
h.run_steps(1);
|
||||
{
|
||||
let d = &h.state().optimize_draft;
|
||||
assert!(d.settings.discard_tags && d.discard == vec![pdfcraft_engine::Hidden::Metadata]);
|
||||
}
|
||||
h.get_by_label("OK").click();
|
||||
// The click is handled next frame. The optimization then runs on a worker thread and the
|
||||
// copy is saved when it is done.
|
||||
h.run_steps(1);
|
||||
let start = std::time::Instant::now();
|
||||
while (h.state().optimize_run.is_some() || !out.exists()) && start.elapsed() < std::time::Duration::from_secs(30) {
|
||||
h.run_steps(1);
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert!(h.state().progress_notice.is_none(), "the progress card is gone");
|
||||
assert!(std::fs::read(&out).unwrap().starts_with(b"%PDF-"));
|
||||
assert_eq!(h.state().dialog, None);
|
||||
h.run_steps(3);
|
||||
jobs.run_all();
|
||||
h.run_steps(4);
|
||||
assert!(files.file(&out).expect("the copy is saved").starts_with(b"%PDF-"));
|
||||
assert!(h.state().optimize_run.is_none(), "the run is over");
|
||||
assert!(h.query_by_label("PDF Optimizer").is_none(), "the dialog closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pdf_optimizer_dialog_picks_a_preset() {
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use pdfcraft_engine::optimize::Preset;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
@@ -221,31 +194,32 @@ fn the_pdf_optimizer_dialog_picks_a_preset() {
|
||||
h.run_steps(4);
|
||||
assert!(h.state_mut().execute("optimize.advanced"));
|
||||
h.run_steps(2);
|
||||
assert_eq!(Preset::of(&h.state().optimize_draft.settings), Some(Preset::Standard));
|
||||
h.get_by_label("Merge image fragments");
|
||||
h.get_by_value("Standard");
|
||||
assert_eq!(h.get_by_label("Merge image fragments").toggled(), Some(true));
|
||||
h.get_by_value("Standard").click();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Mobile").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().optimize_draft.settings, Preset::Mobile.settings(), "Mobile chosen");
|
||||
h.get_by_value("Mobile");
|
||||
assert_eq!(h.get_by_label("Merge image fragments").toggled(), Some(false), "Mobile turns it off");
|
||||
// Changing an option makes the settings custom.
|
||||
h.get_by_label("Merge image fragments").click();
|
||||
h.run_steps(2);
|
||||
assert!(!h.state().optimize_draft.settings.merge_fragments);
|
||||
h.get_by_value("Custom");
|
||||
|
||||
// Pick a target PDF version and toggle structure compression on Clean Up.
|
||||
// Object streams need PDF 1.5 or later.
|
||||
h.get_by_label("Clean Up").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_value("Retain existing").click();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("PDF 1.4").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.get_by_label("Compress document structure (object streams)").accesskit_node().is_disabled());
|
||||
h.get_by_value("PDF 1.4").click();
|
||||
h.run_steps(4);
|
||||
h.get_by_label("PDF 2.0").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().optimize_draft.settings.compatibility, pdfcraft_engine::optimize::Compatibility::Pdf2_0);
|
||||
h.get_by_label("Clean Up").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().optimize_draft.settings.object_streams);
|
||||
h.get_by_label("Compress document structure (object streams)").click();
|
||||
h.run_steps(2);
|
||||
assert!(!h.state().optimize_draft.settings.object_streams);
|
||||
assert!(!h.get_by_label("Compress document structure (object streams)").accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
fn mixed_files(app: &PdfCraftApp) -> Vec<(String, Vec<u8>)> {
|
||||
@@ -261,60 +235,50 @@ fn mixed_files(app: &PdfCraftApp) -> Vec<(String, Vec<u8>)> {
|
||||
#[test]
|
||||
fn separate_batch_creates_one_pdf_per_source_without_replacing_existing_files() {
|
||||
use pdfcraft_ui_egui::FilePurpose;
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-separate-batch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("notes.pdf"), b"keep this file").unwrap();
|
||||
let dir = PathBuf::from("/batch");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![dir.clone()])]).with_file(dir.join("notes.pdf"), b"keep this file".to_vec()));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = scripted(files.clone(), jobs, egui::vec2(1000.0, 720.0), |_| {});
|
||||
h.run_steps(2);
|
||||
let mut sources = mixed_files(h.state());
|
||||
sources.push(("notes.txt".into(), b"another text file".to_vec()));
|
||||
h.state_mut().use_files(FilePurpose::CreateMultipleSeparate, sources);
|
||||
h.run_steps(3);
|
||||
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.export_dir_override = Some(dir.to_string_lossy().into_owned());
|
||||
let mut files = mixed_files(&app);
|
||||
files.push(("notes.txt".into(), b"another text file".to_vec()));
|
||||
app.use_files(FilePurpose::CreateMultipleSeparate, files);
|
||||
|
||||
assert_eq!(std::fs::read(dir.join("notes.pdf")).unwrap(), b"keep this file");
|
||||
assert_eq!(files.file(&dir.join("notes.pdf")).unwrap(), b"keep this file");
|
||||
for name in ["notes (2).pdf", "notes (3).pdf", "photo.pdf"] {
|
||||
assert!(std::fs::read(dir.join(name)).unwrap().starts_with(b"%PDF-"), "{name}");
|
||||
assert!(files.file(&dir.join(name)).unwrap_or_default().starts_with(b"%PDF-"), "{name}");
|
||||
}
|
||||
assert!(!dir.join("a (2).pdf").exists(), "an already-PDF input is skipped");
|
||||
assert!(!dir.join("report.pdf").exists(), "an invalid Office file is skipped");
|
||||
assert!(app.views.is_empty(), "batch conversion must not open PDF tabs");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
assert!(files.file(&dir.join("a (2).pdf")).is_none(), "an already-PDF input is skipped");
|
||||
assert!(files.file(&dir.join("report.pdf")).is_none(), "an invalid Office file is skipped");
|
||||
assert!(h.state().views.is_empty(), "batch conversion must not open PDF tabs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_batch_command_picks_files_and_writes_to_the_chosen_folder() {
|
||||
use egui_kittest::Harness;
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-separate-command-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = dir.join("letter.txt");
|
||||
std::fs::write(&source, b"A separate PDF").unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1000.0, 720.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.pick_override = Some(vec![source.to_string_lossy().into_owned()]);
|
||||
app.export_dir_override = Some(dir.to_string_lossy().into_owned());
|
||||
app
|
||||
});
|
||||
let source = PathBuf::from("/in/letter.txt");
|
||||
let dir = PathBuf::from("/out");
|
||||
let files = Arc::new(
|
||||
ScriptedFiles::answering([Picked::Paths(vec![source.clone()]), Picked::Paths(vec![dir.clone()])]).with_file(source, b"A separate PDF".to_vec()),
|
||||
);
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = scripted(files.clone(), jobs.clone(), egui::vec2(1000.0, 720.0), |_| {});
|
||||
assert!(h.state_mut().execute("create.multiple_separate"));
|
||||
h.run_steps(2);
|
||||
assert!(std::fs::read(dir.join("letter.pdf")).unwrap().starts_with(b"%PDF-"));
|
||||
h.run_steps(4);
|
||||
jobs.run_all();
|
||||
h.run_steps(3);
|
||||
assert!(files.file(&dir.join("letter.pdf")).unwrap_or_default().starts_with(b"%PDF-"));
|
||||
assert!(h.state().views.is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_files_open_as_one_document_in_the_page_grid() {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let path = std::env::temp_dir().join(format!("pdfcraft-create-multiple-{}.pdf", std::process::id()));
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1000.0, 720.0)).build_eframe(|_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
let files = mixed_files(&app);
|
||||
app.use_files(pdfcraft_ui_egui::FilePurpose::CreateMultiple, files);
|
||||
app
|
||||
let path = PathBuf::from("/saved/combined.pdf");
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![path.clone()])]));
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = scripted(files.clone(), jobs, egui::vec2(1000.0, 720.0), |app| {
|
||||
let sources = mixed_files(app);
|
||||
app.use_files(pdfcraft_ui_egui::FilePurpose::CreateMultiple, sources);
|
||||
});
|
||||
h.run_steps(4);
|
||||
{
|
||||
@@ -339,22 +303,25 @@ fn multiple_files_open_as_one_document_in_the_page_grid() {
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Delete pages (Delete)").click();
|
||||
h.run_steps(3);
|
||||
h.state_mut().save_override = Some(path.to_string_lossy().into_owned());
|
||||
h.get_by_label("Save pages").click();
|
||||
h.run_steps(4);
|
||||
let app = h.state();
|
||||
let doc = app.session.get(app.views[0].id).unwrap();
|
||||
assert!(!doc.dirty && doc.info.pages.len() == 2);
|
||||
assert!(std::fs::read(&path).unwrap().starts_with(b"%PDF-"));
|
||||
assert!(files.file(&path).unwrap_or_default().starts_with(b"%PDF-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_files_that_cannot_be_converted_open_nothing() {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.use_files(pdfcraft_ui_egui::FilePurpose::CreateMultiple, vec![("report.docx".into(), b"PK\x03\x04".to_vec())]);
|
||||
assert!(app.views.is_empty());
|
||||
assert!(app.toast.is_some());
|
||||
let files = Arc::new(ScriptedFiles::new());
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let mut h = scripted(files, jobs, egui::vec2(1000.0, 720.0), |_| {});
|
||||
h.run_steps(2);
|
||||
h.state_mut().use_files(pdfcraft_ui_egui::FilePurpose::CreateMultiple, vec![("report.docx".into(), b"PK\x03\x04".to_vec())]);
|
||||
h.run_steps(3);
|
||||
assert!(h.state().views.is_empty());
|
||||
// PLAN: assumed `support::shown_notice(&Harness<PdfCraftApp>) -> Option<String>` (pdf-chrome-w9)
|
||||
assert!(crate::support::shown_notice(&h).is_some(), "the user is told");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user