M14: "Combine files in PdfCraft" on File Explorer's PDF menu (#585) (#2503)

This commit is contained in:
mtlcl410 authored and GitHub committed 2026-11-09 18:10:56 +08:00
1 parent 239491cbfe
commit c028b51b3d
15 files changed
+290 -55

No files matched your search

+3 -2
View File
@@ -476,7 +476,8 @@ logs and crash recovery in a `PdfCraftData` folder next to `pdfcraft.exe`, so no
The MSI installs for your account only by default, without administrator privileges. Choose
"Everyone on this computer" on its first page, or pass `ALLUSERS=1` from an elevated terminal, to install
for all users. It adds "Edit with PdfCraft"
to the right-click menu of PDF files and "Create PDF with PdfCraft…" to the right-click menu of
and "Combine files in PdfCraft" (select several PDFs: they land in the Combine files tab of the
running PdfCraft) to the right-click menu of PDF files and "Create PDF with PdfCraft…" to the right-click menu of
images (.png .jpg .jpeg .tif .tiff .gif .bmp .jp2 .j2k .jpx) in File Explorer (on Windows 11, under
"Show more options"), without changing which app opens them by default. For unattended deployment
without a desktop shortcut (add `ALLUSERS=1`, from an elevated terminal, for an all-users install):
@@ -488,7 +489,7 @@ msiexec /i "pdfcraft-<ver>-windows-x64.msi" /qn /norestart INSTALLDESKTOPSHORTCU
| Property | `=0` leaves out |
|---|---|
| `INSTALLDESKTOPSHORTCUT` | the desktop shortcut |
| `INSTALLPDFCONTEXTMENU` | "Edit with PdfCraft" on PDF files |
| `INSTALLPDFCONTEXTMENU` | "Edit with PdfCraft" and "Combine files in PdfCraft" on PDF files |
| `INSTALLIMAGECONTEXTMENU` | "Create PDF with PdfCraft…" on images |
All three are on for a first install. An upgrade keeps what the installed version has: a shortcut
+1
View File
@@ -452,6 +452,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-14 (M12, reading colours, #2059):** Pending page backgrounds use the document's reading colour immediately, preventing white flashes while scrolling to uncached pages. A headless canvas regression covers three pending pages in every preset and a custom background. Estimates unchanged.
- **2026-10-15 (community, M6, #2608):** In Prepare a form the selected field moves with the arrow keys: a point per press, ten with Shift, as the object nudge and dragging it do. Each press is one undo step ("Change field properties"), and the keys no longer turn the page while a field is selected. Estimates unchanged.
- **2026-10-15 (M3, closable community card):** The ArtCraft community card on Home has a close button that hides it for the rest of the run; it returns on the next launch, and its links stay in the top bar's Discord button and the Help menu. A UI regression covers closing and the fresh-launch default. Estimates unchanged.
- **2026-10-15 (M14, Combine files from File Explorer, #585):** The Windows MSI adds "Combine files in PdfCraft" to PDF files' right-click menu (with the Edit verb, same switch); each selected file starts `pdfcraft --combine`, and the single-instance hand-off (`"combine": true`, `OsEvent::Combine`) collects them into the running PdfCraft's Combine files tab. Tests: the request round trip and hand-off in `single_instance.rs`, the OS event in `tests/ui.rs`, the verb rows in `test-msi.ps1`. Estimates unchanged.
- **2026-10-15 (M14, MSI install folder, #1139):** The Windows installer's welcome dialog has an "Install to" row with a native folder browser, starting on the folder chosen for the per-user or per-machine scope (the recorded one on an update). `test-msi.ps1` checks the dialog wiring: both Install buttons set the folder before the dialog closes, and Browse's OK and Cancel. Estimates unchanged.
- **2026-10-13 (community, M3, #1569 review):** Pixel-only Wayland wheel, wheel-tilt and continuous input use standalone moved events, so Ctrl zoom does not remain latched after the modifier is released (#991); vendored winit patch (13), with a policy test. Estimates unchanged.
- **2026-10-18 (M1, PR #1143 repair policy):** A live in-file reference resolves when its generation matches the xref row or a same-number header at that indexed offset. Neither-match and free slots remain null, including when old object bytes remain. Opening records bounded xref/header disagreements without parsing object bodies or expanding compact xref rows. Synthetic controls cover read order, clones, overlays, dictionary edits, full classic/packed saves and an independent reader of incremental output. **Correction to the 2026-10-15 note below:** its async-opening-test sentence was not evidenced by this COS change; no fresh async-opening or GUI validation is claimed. The full-reference stream-length recursion key is defensive hardening, not an independently isolated regression fix. Estimates unchanged.
+12 -4
View File
@@ -12,6 +12,8 @@
//! --cover on|off --default-layout single|continuous|two-up|two-page --default-continuous on|off --default-zoom fit-width|fit-page|<percent> --always-default-view on|off
//! --page-gaps on|off --default-page-gaps on|off --recent-files 0..50
//! --combine-view grid|list --combine-zoom 60..200`
//! `--combine files…` adds the files to the Combine files tab (File Explorer's "Combine files in
//! PdfCraft", #585), of the PdfCraft already running when there is one.
//!
//! `--new-window` opens a window of its own. Without it, on Windows, a launch that only names files
//! hands them to the PdfCraft already running, where they open as tabs (`single_instance`).
@@ -69,6 +71,7 @@ Options:
--two-paged open command-line PDFs in noncontinuous two-page view
--new-window open a window of its own instead of passing the files to a running PdfCraft
--create-images [images…] put the images in one PDF and ask for the page DPI
--combine files… add the files to the Combine files tab, of a running PdfCraft if there is one
--control <file> enable the UI control channel (pdfcraft-cli ui --control <file> …)
--page N, --zoom 150, --layout continuous, --theme dark, …
view settings applied once the files are open
@@ -231,7 +234,7 @@ fn main() -> eframe::Result {
}
startup.files = rejoin_split_paths(startup.files, |p| std::path::Path::new(p).is_file());
let may_hand_off = startup.may_hand_off();
let startup::Arguments { files, options, control_file, create_images, two_paged, .. } = startup;
let startup::Arguments { files, options, control_file, create_images, combine, two_paged, .. } = startup;
let integrated = cfg!(target_os = "macos");
// GNOME on Wayland leaves the window frame to the app (src/decorations.rs).
let window_controls = if cfg!(any(target_os = "macos", target_os = "windows")) { None } else { decorations::app_drawn() };
@@ -255,13 +258,13 @@ fn main() -> eframe::Result {
// Absolute for this instance too: links relative to a document resolve against its folder,
// never the working directory.
let files = single_instance::absolute(&files);
let instance = match single_instance::claim(&files, may_hand_off) {
let instance = match single_instance::claim(&files, may_hand_off, combine) {
single_instance::Claim::HandedOff => return Ok(()),
single_instance::Claim::Primary(server) => Some(server),
single_instance::Claim::Alone => None,
};
let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref());
let launch = Launch { files, options, control_file, create_images, integrated, window_controls, two_paged };
let launch = Launch { files, options, control_file, create_images, combine, integrated, window_controls, two_paged };
// Finder, Open With and the Dock deliver files as Apple events, not arguments; catch the one
// that launched us as well as later ones. Lives until the event loop returns.
#[cfg(target_os = "macos")]
@@ -368,6 +371,8 @@ struct Launch {
options: Vec<(String, String)>,
control_file: Option<String>,
create_images: bool,
/// `--combine`: the files go to the Combine files tab.
combine: bool,
integrated: bool,
/// The window buttons the app draws, when the desktop leaves the frame to it.
window_controls: Option<pdfcraft_ui_egui::window_controls::Layout>,
@@ -392,7 +397,7 @@ fn app_creator<'a>(
instance: Option<&'a single_instance::Server>,
#[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents,
) -> eframe::AppCreator<'a> {
let Launch { files, options, control_file, create_images, integrated, window_controls, two_paged } = launch;
let Launch { files, options, control_file, create_images, combine, integrated, window_controls, two_paged } = launch;
Box::new(move |cc| {
started.set(true);
let mut app = PdfCraftApp::new();
@@ -466,6 +471,9 @@ fn app_creator<'a>(
if let Err(e) = app.begin_image_import_paths(&files) {
app.notify(e);
}
} else if combine {
app.reopen_last_files(&[]);
app.combine_paths(&files);
} else {
// With the preference on, last session's files come back first; files named on
// the command line open after them, in front (#442).
+96 -35
View File
@@ -14,7 +14,9 @@
//! intercept a launch or open files in this user's window. Inside a Flatpak, `$XDG_RUNTIME_DIR` is
//! the app's own and is shared by every run of it, so the handoff works there too. The exchange is
//! one line each way, a JSON request naming absolute paths and `ok`, and the running app opens the
//! paths exactly as File ▸ Open would.
//! paths exactly as File ▸ Open would. A `--combine` launch (File Explorer's "Combine files in
//! PdfCraft", #585, one launch per selected file) hands them over the same way with
//! `"combine": true`, and the running app adds them to its Combine files tab instead.
//!
//! Every failure falls back to the old behaviour: a launch that can't hand its files over within
//! a few seconds opens its own window. `--new-window`, any other option, or no files at all also
@@ -58,7 +60,10 @@ pub enum Claim {
/// Files that later launches handed over, and how to wake the UI for them.
#[derive(Default)]
struct Inbox {
paths: Vec<String>,
/// The requests in the order they arrived: [`OsEvent::Open`] or, for `--combine`,
/// [`OsEvent::Combine`]. One queue, so the UI handles an Open that came after a Combine after
/// it, and that Open comes to the front instead of opening behind the Combine files tab.
events: Vec<OsEvent>,
wake: Option<Box<dyn Fn() + Send>>,
}
@@ -74,11 +79,20 @@ impl Server {
Self { inbox: Arc::default() }
}
/// Queue files from another launch and wake the UI.
/// Queue files from another launch (to open, or to combine) and wake the UI.
#[cfg_attr(not(any(windows, all(unix, not(target_os = "macos")))), allow(dead_code))]
fn deliver(&self, paths: Vec<String>) {
fn deliver(&self, paths: Vec<String>, combine: bool) {
if paths.is_empty() {
return;
}
let mut inbox = self.inbox.lock().unwrap_or_else(PoisonError::into_inner);
inbox.paths.extend(paths);
// A run of requests of one kind (File Explorer starts one launch per selected file) stays
// one event; a request of the other kind starts a new one after it.
match (inbox.events.last_mut(), combine) {
(Some(OsEvent::Combine(queued)), true) | (Some(OsEvent::Open(queued)), false) => queued.extend(paths),
(_, true) => inbox.events.push(OsEvent::Combine(paths)),
(_, false) => inbox.events.push(OsEvent::Open(paths)),
}
if let Some(wake) = &inbox.wake {
wake();
}
@@ -95,8 +109,8 @@ impl Server {
let inbox = Arc::clone(&self.inbox);
let ctx = ctx.clone();
Box::new(move || {
let paths = std::mem::take(&mut inbox.lock().unwrap_or_else(PoisonError::into_inner).paths);
if paths.is_empty() {
let events = std::mem::take(&mut inbox.lock().unwrap_or_else(PoisonError::into_inner).events);
if events.is_empty() {
return Vec::new();
}
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
@@ -104,27 +118,37 @@ impl Server {
if native_wayland {
ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(egui::UserAttentionType::Informational));
}
vec![OsEvent::Open(paths)]
events
})
}
}
/// The request a launch sends: `{"open":[…]}` and a newline.
/// The request a launch sends: `{"open":[…]}` (with `"combine":true` for `--combine`) and a
/// newline.
#[cfg_attr(not(any(windows, all(unix, not(target_os = "macos")))), allow(dead_code))]
pub fn request(paths: &[String]) -> String {
let mut line = serde_json::json!({ "open": paths }).to_string();
pub fn request(paths: &[String], combine: bool) -> String {
let mut value = serde_json::json!({ "open": paths });
if combine {
value["combine"] = serde_json::Value::Bool(true);
}
let mut line = value.to_string();
line.push('\n');
line
}
/// The paths a request names, or `None` when it isn't a request: anything but one JSON object
/// whose `open` is a non-empty list of non-empty strings.
/// The paths a request names and whether they are for Combine files, or `None` when it isn't a
/// request: anything but one JSON object whose `open` is a non-empty list of non-empty strings
/// (`combine`, when there, must be a boolean).
#[cfg_attr(not(any(windows, all(unix, not(target_os = "macos")))), allow(dead_code))]
pub fn parse_request(line: &str) -> Option<Vec<String>> {
pub fn parse_request(line: &str) -> Option<(Vec<String>, bool)> {
let value: serde_json::Value = serde_json::from_str(line.trim_end()).ok()?;
let open = value.get("open")?.as_array()?;
let paths = open.iter().map(|p| p.as_str().filter(|s| !s.is_empty()).map(str::to_string)).collect::<Option<Vec<String>>>()?;
(!paths.is_empty()).then_some(paths)
let combine = match value.get("combine") {
None => false,
Some(c) => c.as_bool()?,
};
(!paths.is_empty()).then_some((paths, combine))
}
/// File arguments made absolute against this launch's working folder, which the running app
@@ -134,18 +158,19 @@ pub fn absolute(paths: &[String]) -> Vec<String> {
}
/// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false
/// when the launch asked for anything besides opening files, so it gets its own window.
pub fn claim(files: &[String], may_hand_off: bool) -> Claim {
/// when the launch asked for anything besides opening (or, with `combine`, combining) files, so
/// it gets its own window.
pub fn claim(files: &[String], may_hand_off: bool, combine: bool) -> Claim {
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
{
match socket_path() {
Some(path) => claim_at(&path, files, may_hand_off),
Some(path) => claim_at(&path, files, may_hand_off, combine),
None => Claim::Alone,
}
}
#[cfg(not(any(windows, all(unix, not(target_os = "macos")))))]
{
let _ = (files, may_hand_off);
let _ = (files, may_hand_off, combine);
Claim::Alone
}
}
@@ -239,7 +264,7 @@ fn election(socket: &std::path::Path) -> Option<std::fs::File> {
/// [`claim`] with the socket at `path`.
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
fn claim_at(path: &std::path::Path, files: &[String], may_hand_off: bool) -> Claim {
fn claim_at(path: &std::path::Path, files: &[String], may_hand_off: bool, combine: bool) -> Claim {
// Released when this function returns: by then this launch listens, or has handed over.
let _election = election(path);
// Two launches can start together: the one that loses the race to bind hands over to the
@@ -250,7 +275,7 @@ fn claim_at(path: &std::path::Path, files: &[String], may_hand_off: bool) -> Cla
if !may_hand_off {
return Claim::Alone;
}
return match hand_off(&stream, files) {
return match hand_off(&stream, files, combine) {
Ok(()) => Claim::HandedOff,
Err(e) => {
log::warn!("couldn't hand the files to the running PdfCraft ({e}); opening a new window");
@@ -296,12 +321,12 @@ fn claim_at(path: &std::path::Path, files: &[String], may_hand_off: bool) -> Cla
/// Send `files` over `stream` and wait for the running app's `ok`.
#[cfg(any(windows, all(unix, not(target_os = "macos"))))]
fn hand_off(stream: &UnixStream, files: &[String]) -> std::io::Result<()> {
fn hand_off(stream: &UnixStream, files: &[String], combine: bool) -> std::io::Result<()> {
use std::io::{BufRead, Read, Write};
stream.set_read_timeout(Some(TIMEOUT))?;
stream.set_write_timeout(Some(TIMEOUT))?;
let mut writer = stream;
writer.write_all(request(files).as_bytes())?;
writer.write_all(request(files, combine).as_bytes())?;
let mut reply = String::new();
std::io::BufReader::new(stream.take(16)).read_line(&mut reply)?;
if reply == "ok\n" { Ok(()) } else { Err(std::io::Error::other("the running PdfCraft didn't confirm")) }
@@ -343,8 +368,8 @@ fn receive(stream: &UnixStream, server: &Server) -> std::io::Result<()> {
if line.is_empty() {
return Ok(());
}
let paths = parse_request(&line).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "not an open request"))?;
server.deliver(paths);
let (paths, combine) = parse_request(&line).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "not an open request"))?;
server.deliver(paths, combine);
let mut writer = stream;
writer.write_all(b"ok\n")
}
@@ -356,16 +381,31 @@ mod tests {
#[test]
fn a_request_names_the_paths_and_round_trips() {
let paths = vec![r"C:\Users\me\Documents\Quote.pdf".to_string(), r"D:\Scans\Plan „A“ 1.pdf".to_string()];
let line = request(&paths);
let line = request(&paths, false);
assert!(line.ends_with('\n') && !line.trim_end().contains('\n'), "one line");
assert_eq!(parse_request(&line), Some(paths));
assert_eq!(parse_request(&line), Some((paths.clone(), false)));
assert!(!line.contains("combine"), "an open request says nothing about combining");
let line = request(&paths, true);
assert_eq!(parse_request(&line), Some((paths, true)), "a --combine launch's request");
}
#[test]
fn anything_but_a_list_of_paths_is_refused() {
for line in ["", "ok\n", "{}", r#"{"open":[]}"#, r#"{"open":[""]}"#, r#"{"open":["a.pdf",3]}"#, r#"{"open":"a.pdf"}"#, "[\"a.pdf\"]"] {
for line in [
"",
"ok\n",
"{}",
r#"{"open":[]}"#,
r#"{"open":[""]}"#,
r#"{"open":["a.pdf",3]}"#,
r#"{"open":"a.pdf"}"#,
"[\"a.pdf\"]",
r#"{"open":["a.pdf"],"combine":"yes"}"#,
r#"{"open":["a.pdf"],"combine":1}"#,
] {
assert_eq!(parse_request(line), None, "{line:?}");
}
assert_eq!(parse_request(r#"{"open":["a.pdf"],"combine":false}"#), Some((vec!["a.pdf".to_string()], false)));
}
#[test]
@@ -398,13 +438,31 @@ mod tests {
fn delivered_files_reach_the_ui_once_wake_it_and_bring_the_window_forward() {
let server = Server::new();
// Before the window exists: queued, nothing to wake yet.
server.deliver(vec!["a.pdf".into()]);
server.deliver(vec!["a.pdf".into()], false);
let ctx = egui::Context::default();
let mut poll = server.connect(&ctx, false);
server.deliver(vec!["b.pdf".into()]);
server.deliver(vec!["b.pdf".into()], false);
let events = poll();
assert!(matches!(events.as_slice(), [OsEvent::Open(p)] if p == &["a.pdf", "b.pdf"]));
assert!(poll().is_empty(), "each file is delivered once");
// Files to combine (one launch each, from File Explorer) arrive as one Combine event,
// apart from files to open.
server.deliver(vec!["c.pdf".into()], true);
server.deliver(vec!["e.pdf".into()], true);
let events = poll();
assert!(matches!(events.as_slice(), [OsEvent::Combine(c)] if c == &["c.pdf", "e.pdf"]), "{events:?}");
// #2503 review: requests reach the UI in the order they arrived, so an Open after a
// Combine is handled after it and comes to the front instead of opening behind the
// Combine files tab.
server.deliver(vec!["f.pdf".into()], true);
server.deliver(vec!["g.pdf".into()], false);
server.deliver(vec!["h.pdf".into()], true);
let events = poll();
assert!(
matches!(events.as_slice(), [OsEvent::Combine(f), OsEvent::Open(g), OsEvent::Combine(h)] if f == &["f.pdf"] && g == &["g.pdf"] && h == &["h.pdf"]),
"{events:?}"
);
assert!(poll().is_empty());
}
#[test]
@@ -442,12 +500,15 @@ mod tests {
#[test]
fn a_second_launch_hands_its_files_to_the_first() {
let path = socket("hand-off");
let Claim::Primary(first) = claim_at(&path, &[], true) else { panic!("the first launch listens") };
let Claim::Primary(first) = claim_at(&path, &[], true, false) else { panic!("the first launch listens") };
let mut poll = first.connect(&egui::Context::default(), false);
assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true), Claim::HandedOff));
assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true, false), Claim::HandedOff));
assert!(matches!(poll().as_slice(), [OsEvent::Open(p)] if p == &["C:\\a.pdf"]));
// A --combine launch hands its file over for the Combine files tab (#585).
assert!(matches!(claim_at(&path, &["C:\\c.pdf".into()], true, true), Claim::HandedOff));
assert!(matches!(poll().as_slice(), [OsEvent::Combine(p)] if p == &["C:\\c.pdf"]));
// A launch with options keeps its own window and doesn't take over the socket.
assert!(matches!(claim_at(&path, &["C:\\b.pdf".into()], false), Claim::Alone));
assert!(matches!(claim_at(&path, &["C:\\b.pdf".into()], false, false), Claim::Alone));
assert!(poll().is_empty());
}
@@ -462,7 +523,7 @@ mod tests {
let (path, barrier) = (path.clone(), Arc::clone(&barrier));
std::thread::spawn(move || {
barrier.wait();
claim_at(&path, &[format!("C:\\{i}.pdf")], true)
claim_at(&path, &[format!("C:\\{i}.pdf")], true, false)
})
})
.collect();
@@ -483,6 +544,6 @@ mod tests {
}));
// `symlink_metadata`, not `exists`, which follows the socket's reparse point and can fail.
assert!(std::fs::symlink_metadata(&path).is_ok(), "the socket file stays behind");
assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true), Claim::Primary(_)));
assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true, false), Claim::Primary(_)));
}
}
+5
View File
@@ -7,6 +7,8 @@ pub(super) struct Arguments {
pub options: Vec<(String, String)>,
pub control_file: Option<String>,
pub create_images: bool,
/// `--combine`: the files go to the Combine files tab.
pub combine: bool,
pub new_window: bool,
pub two_paged: bool,
pub version: bool,
@@ -33,6 +35,9 @@ impl Arguments {
}
"--control" => parsed.control_file = args.next(),
"--create-images" => parsed.create_images = true,
// File Explorer's "Combine files in PdfCraft" (#585): the files go to the Combine
// files tab, of the running PdfCraft when there is one.
"--combine" => parsed.combine = true,
"--new-window" => parsed.new_window = true,
"--two-paged" => parsed.two_paged = true,
flag if flag.starts_with("--two-paged=") => {
+9 -1
View File
@@ -609,8 +609,16 @@ impl PdfCraftApp {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
// Combine from File Explorer's PDF menu, also handed to the running app: the dialog
// it opens has to be seen, so the window comes to the front as for Open.
#[cfg(not(target_arch = "wasm32"))]
OsEvent::Combine(paths) => {
self.combine_paths(&paths);
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
#[cfg(target_arch = "wasm32")]
OsEvent::Open(_) => {}
OsEvent::Open(_) | OsEvent::Combine(_) => {}
// Like closing the window: `guard_quit` asks about unsaved changes.
OsEvent::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
}
+3
View File
@@ -11,6 +11,9 @@ pub type FailedInbox = std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>;
pub enum OsEvent {
/// Open these files.
Open(Vec<String>),
/// Add these files to Combine files and show it (`pdfcraft --combine`, File Explorer's
/// "Combine files in PdfCraft", #585).
Combine(Vec<String>),
/// Quit (the Dock's Quit, logging out), asking about unsaved changes first.
Quit,
}
@@ -401,6 +401,33 @@ impl PdfCraftApp {
let _ = recursive;
}
/// Add the files at `paths` to the Combine files list and show it: `pdfcraft --combine` and
/// File Explorer's "Combine files in PdfCraft" (#585), where each selected file arrives as a
/// launch of its own and the running PdfCraft collects them here. Nothing to add shows the
/// tab all the same.
#[cfg(not(target_arch = "wasm32"))]
pub fn combine_paths(&mut self, paths: &[String]) {
// A file still opening from before (another launch's Open), or waiting for its password,
// opens in the background, so finishing doesn't hide the tab shown here; a later Open
// still comes to the front. An open that something waits on keeps its focus: a chosen
// tool, a link's destination or a recovery runs on the document once it is in front.
for pending in &mut self.pending_opens {
if pending.then.is_none() && pending.after_open.is_none() && pending.recovered.is_none() {
pending.activate = false;
}
}
if let Some(prompt) = self.password_prompt.as_mut()
&& prompt.then.is_none()
&& prompt.after_open.is_none()
&& prompt.recovered.is_none()
{
prompt.activate = false;
}
self.open_combine_tab();
let paths: Vec<std::path::PathBuf> = paths.iter().map(std::path::PathBuf::from).collect();
self.use_paths(crate::files::FilePurpose::Combine, &paths);
}
/// Add the PDFs, images and text files in `dir` to the Combine files list, as one undo step.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn add_folder_to_combine(&mut self, dir: &std::path::Path, recursive: bool) {
@@ -210,3 +210,26 @@ fn removing_pages_drops_emptied_parts_and_joins_what_meets() {
// A page that isn't there: nothing changes, and it says so.
assert_eq!(removed_pages(&two, &BTreeSet::from([(1, 9)]), &mut new_id), None);
}
/// #2503 review: a PDF waiting for its password when Combine arrives opens behind the Combine
/// files tab once unlocked, like one still opening; a prompt that a chosen tool waits on keeps
/// its focus, since the tool runs on the document in front.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_password_answered_after_combine_opens_behind_the_combine_tab() {
let mut app = PdfCraftApp::new();
app.open_bytes("locked.pdf", None, locked()).unwrap();
assert!(app.password_prompt.is_some() && app.views.is_empty());
app.combine_paths(&[]);
assert!(app.combine_showing());
app.submit_password(Some("pw".into()));
assert!(app.password_prompt.is_none());
assert_eq!(app.views.len(), 1, "the document is open");
assert!(app.combine_showing(), "and the Combine files tab still shows");
let mut app = PdfCraftApp::new();
app.open_bytes("locked.pdf", None, locked()).unwrap();
app.password_prompt.as_mut().unwrap().then = Some("export.text");
app.combine_paths(&[]);
assert!(app.password_prompt.as_ref().unwrap().activate, "a tool's open keeps its focus");
}
+71
View File
@@ -1278,6 +1278,77 @@ fn files_and_quit_from_the_operating_system() {
assert!(closing);
}
/// #585: File Explorer's "Combine files in PdfCraft" starts one launch per selected file, and the
/// running PdfCraft collects them (an `OsEvent::Combine` each) into its Combine files tab.
#[test]
fn files_to_combine_from_the_operating_system() {
use pdfcraft_ui_egui::OsEvent;
let dir = std::env::temp_dir().join(format!("pdfcraft-os-combine-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<String> = ["one.pdf", "two.pdf"]
.iter()
.map(|n| {
let p = dir.join(n);
std::fs::write(&p, FIXTURE).unwrap();
p.to_string_lossy().into_owned()
})
.collect();
let queue = std::rc::Rc::new(std::cell::RefCell::new(vec![OsEvent::Combine(vec![paths[0].clone()])]));
let q = queue.clone();
let mut h = harness(move |app| app.os_events = Some(Box::new(move || q.borrow_mut().drain(..).collect())));
assert!(h.state().combine_showing(), "the Combine files tab shows");
assert!(h.state().views.is_empty(), "nothing opens as a document");
queue.borrow_mut().push(OsEvent::Combine(vec![paths[1].clone()]));
h.run_steps(3);
let _ = std::fs::remove_dir_all(&dir);
let names: Vec<_> = h.state().combine_draft.iter().map(|f| f.name.clone()).collect();
assert_eq!(names, ["one.pdf", "two.pdf"], "each launch's file joins the list, in order");
assert!(h.state().combine_showing() && h.state().views.is_empty());
}
/// #2503 review: a PDF still opening when Combine arrives opens behind the Combine files tab
/// instead of hiding it; an Open that comes after Combine still shows its document.
#[test]
fn an_open_finishing_after_combine_keeps_the_combine_tab() {
use pdfcraft_ui_egui::OsEvent;
let dir = std::env::temp_dir().join(format!("pdfcraft-os-combine-pending-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<String> = ["opening.pdf", "combined.pdf", "later.pdf"]
.iter()
.map(|n| {
let p = dir.join(n);
std::fs::write(&p, FIXTURE).unwrap();
p.to_string_lossy().into_owned()
})
.collect();
let queue = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let q = queue.clone();
let mut h = harness(move |app| app.os_events = Some(Box::new(move || q.borrow_mut().drain(..).collect())));
h.run_steps(2);
// Both in one frame: the open goes to the worker and is still pending when Combine shows.
queue.borrow_mut().extend([OsEvent::Open(vec![paths[0].clone()]), OsEvent::Combine(vec![paths[1].clone()])]);
for _ in 0..200 {
h.run_steps(1);
if !h.state().views.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert_eq!(h.state().views.len(), 1, "the earlier open finished");
assert!(h.state().combine_showing(), "and the Combine files tab still shows");
queue.borrow_mut().push(OsEvent::Open(vec![paths[2].clone()]));
for _ in 0..200 {
h.run_steps(1);
if h.state().views.len() == 2 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(h.state().views.len(), 2);
assert!(!h.state().combine_showing() && h.state().active == Some(1), "a later Open shows its document");
}
#[test]
fn default_workspace_mode_persists_and_tolerates_invalid_settings() {
use pdfcraft_ui_egui::Mode;
+12 -8
View File
@@ -130,13 +130,14 @@ neither the MSI nor the portable zip needs the Visual C++ redistributable.
dialogs. Full UI confirms success with Finish; failures and cancellations have distinct messages.
The welcome dialog has an "Install to" row (a `PathEdit`, and Browse… into `BrowseFolder`, a
native folder browser: drive list, folder list, Up, New folder, typed path; #1139), a "Create a
desktop shortcut" checkbox and an "Edit with PdfCraft" right-click menu checkbox, both ticked by
default. Install sets the folder (`SetTargetPath`) before the dialog closes. `INSTALLFOLDER` is
secure, so the choice reaches the elevated install, and `INSTALLFOLDER=<path>` works on the
command line. The row starts on the folder `install-policy.wxi` chose for the scope picked on the
first page (the recorded folder on an update), and an update installs into the recorded folder
unless the command line gives one (`INSTALLATION.md`). `/qn` and `/qb` stay unattended and create
both unless `INSTALLDESKTOPSHORTCUT=0` or `INSTALLPDFCONTEXTMENU=0` is passed;
desktop shortcut" checkbox and an "Add Edit and Combine files to the right-click menu of PDF
files" checkbox, both ticked by default. Install sets the folder (`SetTargetPath`) before the
dialog closes. `INSTALLFOLDER` is secure, so the choice reaches the elevated install, and
`INSTALLFOLDER=<path>` works on the command line. The row starts on the folder
`install-policy.wxi` chose for the scope picked on the first page (the recorded folder on an
update), and an update installs into the recorded folder unless the command line gives one
(`INSTALLATION.md`). `/qn` and `/qb` stay unattended and create both unless
`INSTALLDESKTOPSHORTCUT=0` or `INSTALLPDFCONTEXTMENU=0` is passed;
`INSTALLIMAGECONTEXTMENU=0` (no checkbox) leaves out the image menu. An update (the launcher runs
`msiexec /passive` with no properties) keeps the desktop shortcut only if `PdfCraft.lnk` is still
on the all-users desktop, so deleting it once keeps it away (#1058), and keeps each menu only if
@@ -150,7 +151,10 @@ neither the MSI nor the portable zip needs the Visual C++ redistributable.
limit for a `Document` verb) start one `pdfcraft.exe "<file>"` each, and the single-instance
hand-off opens them as tabs. On Windows 11 it is under "Show more options"; a first-level entry
needs an `IExplorerCommand` handler and package identity (a sparse MSIX package), which the MSI
doesn't have.
doesn't have. "Combine files in PdfCraft" (#585) is a second verb in the same component,
`PdfCraft.Combine`, running `pdfcraft --combine "<file>"` once per selected file; the
single-instance hand-off sends them with `"combine": true`, and the running app adds them to
its Combine files tab (`OsEvent::Combine`). Both verbs come and go with `INSTALLPDFCONTEXTMENU`.
- The image right-click entry (#190) is the same kind of verb, `PdfCraft.CreatePdf`, for ten image
types, in its own component (`PdfcraftImageContextMenu`) since it became optional. Its rows moved
out of `PdfcraftApp`; that's safe because `MajorUpgrade` removes the old version before installing
+1 -1
View File
@@ -19,7 +19,7 @@
<Publish Event="SpawnDialog" Value="BrowseFolder" />
</Control>
<Control Id="DesktopShortcut" Type="CheckBox" X="20" Y="126" Width="330" Height="17" Property="INSTALLDESKTOPSHORTCUT" CheckBoxValue="1" Text="Create a &amp;desktop shortcut" />
<Control Id="PdfContextMenu" Type="CheckBox" X="20" Y="144" Width="330" Height="17" Property="INSTALLPDFCONTEXTMENU" CheckBoxValue="1" Text="Add &quot;&amp;Edit with PdfCraft&quot; to the right-click menu of PDF files" />
<Control Id="PdfContextMenu" Type="CheckBox" X="20" Y="144" Width="330" Height="17" Property="INSTALLPDFCONTEXTMENU" CheckBoxValue="1" Text="Add &amp;Edit and Combine files to the right-click menu of PDF files" />
<Control Id="Install" Type="PushButton" X="195" Y="175" Width="75" Height="23" Default="yes" DefaultCondition="ALLUSERS = 1" ElevationShield="yes" HideCondition="ALLUSERS &lt;&gt; 1" ShowCondition="ALLUSERS = 1" Text="&amp;Install">
<Publish Event="SetTargetPath" Value="INSTALLFOLDER" Order="1" />
<Publish Event="EndDialog" Value="Return" Order="2" />
+7
View File
@@ -159,6 +159,13 @@
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Edit" Name="Icon" Value="&quot;[#PdfcraftExe]&quot;,0" Type="string" />
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Edit" Name="MultiSelectModel" Value="Document" Type="string" />
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Edit\command" Value="&quot;[#PdfcraftExe]&quot; &quot;%1&quot;" Type="string" />
<!-- "Combine files in PdfCraft" (#585), on the same switch: each selected file starts one
launch of pdfcraft.exe with the combine option, and the running PdfCraft collects them into its Combine
files tab (single_instance). -->
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Combine" Value="Combine files in PdfCraft" Type="string" />
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Combine" Name="Icon" Value="&quot;[#PdfcraftExe]&quot;,0" Type="string" />
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Combine" Name="MultiSelectModel" Value="Document" Type="string" />
<RegistryValue Root="HKMU" Key="Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Combine\command" Value="&quot;[#PdfcraftExe]&quot; --combine &quot;%1&quot;" Type="string" />
</Component>
<!-- Image context menu (#190): "Create PDF with PdfCraft…" opens the DPI chooser, without
+18 -2
View File
@@ -245,10 +245,26 @@ if (($secure[0] -split ';') -notcontains 'INSTALLPDFCONTEXTMENU') { throw "INSTA
$pdfCheckbox = Read-Row 'SELECT `Type`, `Property`, `Text` FROM `Control` WHERE `Dialog_` = ''InstallWelcome'' AND `Control` = ''PdfContextMenu''' 3
Assert-Equal $pdfCheckbox[0] 'CheckBox' 'Welcome PDF context-menu control'
Assert-Equal $pdfCheckbox[1] 'INSTALLPDFCONTEXTMENU' 'Welcome PDF context-menu property'
if ($pdfCheckbox[2] -notmatch 'Edit with PdfCraft') { throw "Welcome PDF context-menu label: '$($pdfCheckbox[2])'" }
if ($pdfCheckbox[2] -notmatch '&Edit' -or $pdfCheckbox[2] -notmatch 'Combine files') { throw "Welcome PDF context-menu label: '$($pdfCheckbox[2])'" }
$pdfChecked = Read-Row 'SELECT `Value` FROM `CheckBox` WHERE `Property` = ''INSTALLPDFCONTEXTMENU''' 1
Assert-Equal $pdfChecked[0] '1' 'Welcome PDF context-menu value'
Assert-NoRow 'SELECT `Registry` FROM `Registry` WHERE `Key` = ''Software\Classes\.pdf'' AND `Name` IS NULL' '.pdf default app'
# "Combine files in PdfCraft" (#585): in the PDF menu's component, so the one switch covers both
# verbs. Each selected file starts `pdfcraft --combine "<file>"` (Document), and the running
# PdfCraft collects them into its Combine files tab.
$combineKey = 'Software\Classes\SystemFileAssociations\.pdf\shell\PdfCraft.Combine'
$combineMenu = Read-Row ('SELECT `Value`, `Component_`, `Root` FROM `Registry` WHERE `Key` = ''' + $combineKey + ''' AND `Name` IS NULL') 3
Assert-Equal $combineMenu[0] 'Combine files in PdfCraft' 'Combine verb label'
Assert-Equal $combineMenu[1] 'PdfcraftPdfContextMenu' 'Combine verb component'
Assert-Equal $combineMenu[2] '-1' 'Combine verb context-sensitive root'
foreach ($value in @(@('Icon', '"[#PdfcraftExe]",0'), @('MultiSelectModel', 'Document'))) {
$row = Read-Row ('SELECT `Value`, `Component_` FROM `Registry` WHERE `Key` = ''' + $combineKey + ''' AND `Name` = ''' + $value[0] + '''') 2
Assert-Equal $row[0] $value[1] "Combine verb $($value[0])"
Assert-Equal $row[1] 'PdfcraftPdfContextMenu' "Combine verb $($value[0]) component"
}
$combineCommand = Read-Row ('SELECT `Value`, `Component_` FROM `Registry` WHERE `Key` = ''' + $combineKey + '\command''') 2
Assert-Equal $combineCommand[0] '"[#PdfcraftExe]" --combine "%1"' 'Combine verb command'
Assert-Equal $combineCommand[1] 'PdfcraftPdfContextMenu' 'Combine verb command component'
# Install folder (#1139): the welcome dialog's "Install to" row (a PathEdit, and Browse… into a
# native folder browser) changes the folder install-policy.wxi chose for the scope. Its secure
@@ -308,4 +324,4 @@ $rm = Read-Row 'SELECT `Dialog` FROM `Dialog` WHERE `Dialog` = ''MsiRMFilesInUse
Assert-Equal $rm[0] 'MsiRMFilesInUse' 'Files-in-use dialog'
[void] [Runtime.InteropServices.Marshal]::FinalReleaseComObject($Database)
[void] [Runtime.InteropServices.Marshal]::FinalReleaseComObject($Installer)
Write-Output 'ok MSI: dual-scope guards, publisher, persistent progress text, Start Menu shortcut, optional desktop shortcut and PDF and image context menus (on for a first install, kept on update only while present; checkboxes for the first two), install folder (welcome row and browse dialog), icon/key path, full-UI success/cancel/error and Finish controls, files-in-use dialog, OCR models'
Write-Output 'ok MSI: dual-scope guards, publisher, persistent progress text, Start Menu shortcut, optional desktop shortcut and PDF (Edit, Combine files) and image context menus (on for a first install, kept on update only while present; checkboxes for the first two), install folder (welcome row and browse dialog), icon/key path, full-UI success/cancel/error and Finish controls, files-in-use dialog, OCR models'
+2 -2
View File
@@ -3034,8 +3034,8 @@ milestone = "M4"
status = "shipped"
commands = ["page.combine"]
tools = ["doc_combine"]
evidence = ["crates/organize/src/tests.rs::combine_concatenates_with_a_bookmark_per_file", "crates/ui-egui/tests/it/editing.rs::combining_files_opens_a_new_unsaved_tab", "crates/ui-egui/tests/it/editing.rs::combine_files_opens_in_its_own_tab", "crates/ui-egui/tests/it/editing.rs::combine_lists_size_and_warns_before_combining", "crates/ui-egui/tests/it/editing.rs::a_password_protected_file_is_unlocked_with_its_password_and_combined", "crates/ui-egui/tests/it/editing.rs::a_folder_adds_its_pdfs_images_and_text_in_order_and_optionally_its_subfolders", "crates/ui-egui/tests/it/editing.rs::images_and_text_files_join_the_combine_list_as_pdfs", "crates/ui-egui/tests/it/editing.rs::files_that_cannot_be_read_are_listed_and_left_out_once_the_user_agrees", "crates/ui-egui/tests/it/ui.rs::pdfs_dropped_on_the_combine_tab_join_its_list", "crates/ui-egui/tests/it/ui.rs::files_dropped_on_the_combine_tab_join_the_end_of_its_list_in_the_order_dropped", "crates/ui-egui/tests/it/ui.rs::a_file_combine_does_not_take_is_left_out_of_a_drop_and_named", "crates/ui-egui/tests/it/ui.rs::a_pdf_dropped_on_a_document_opens_while_the_combine_tab_waits_behind_it", "crates/automation/tests/it/automation.rs::combine_extract_and_split", "crates/automation/tests/it/automation.rs::combine_opens_protected_files_with_their_passwords", "crates/automation/tests/it/automation.rs::combine_takes_images_and_text_files", "crates/engine/src/tests.rs::files_for_combine_are_made_into_pdfs_and_pdfs_pass_through", "crates/organize/src/tests.rs::combine_keeps_pdfx_when_every_source_agrees", "crates/organize/src/tests.rs::combine_claims_no_pdfx_when_the_sources_disagree"]
notes = "Combine files is its own tab: a table of the files (name, pages, size, modified, warnings) with column sorting, resizing and moving; files, folders (with subfolders) and open documents can be added, or dropped on the tab (desktop and web): a drop joins the end of the list in the order dropped, as one undo step, not at the place under the pointer; files of a kind Combine does not take are left out and named. Dropped elsewhere, files open as before. Dropping adds no engine behaviour, so it has no tool of its own (doc_combine takes the files). Images (PNG, JPEG, TIFF, GIF, BMP, JPEG 2000) and .txt files become PDFs as they are added (#569; also in doc_combine). A file that can't be read stays in the list with why, and Combine asks before leaving it out; Office documents, HTML and other formats are not converted yet. Problems show before Combine (password, security settings that withhold page assembly, bad page ranges, duplicates); protected files are unlocked with their open or permissions password (also doc_combine passwords). The result is never encrypted, and is not yet offered for protection in the same step. A PDF/X result (output intent, GTS_PDFXVersion, Trapped, XMP pdfxid) only when every source declares the same version and output intent (#263). When they differ the result claims none, and nothing reports that yet; Acrobat behaviour not observed."
evidence = ["crates/organize/src/tests.rs::combine_concatenates_with_a_bookmark_per_file", "crates/ui-egui/tests/it/editing.rs::combining_files_opens_a_new_unsaved_tab", "crates/ui-egui/tests/it/ui.rs::files_to_combine_from_the_operating_system", "apps/pdfcraft/src/single_instance.rs::a_second_launch_hands_its_files_to_the_first", "crates/ui-egui/tests/it/editing.rs::combine_files_opens_in_its_own_tab", "crates/ui-egui/tests/it/editing.rs::combine_lists_size_and_warns_before_combining", "crates/ui-egui/tests/it/editing.rs::a_password_protected_file_is_unlocked_with_its_password_and_combined", "crates/ui-egui/tests/it/editing.rs::a_folder_adds_its_pdfs_images_and_text_in_order_and_optionally_its_subfolders", "crates/ui-egui/tests/it/editing.rs::images_and_text_files_join_the_combine_list_as_pdfs", "crates/ui-egui/tests/it/editing.rs::files_that_cannot_be_read_are_listed_and_left_out_once_the_user_agrees", "crates/ui-egui/tests/it/ui.rs::pdfs_dropped_on_the_combine_tab_join_its_list", "crates/ui-egui/tests/it/ui.rs::files_dropped_on_the_combine_tab_join_the_end_of_its_list_in_the_order_dropped", "crates/ui-egui/tests/it/ui.rs::a_file_combine_does_not_take_is_left_out_of_a_drop_and_named", "crates/ui-egui/tests/it/ui.rs::a_pdf_dropped_on_a_document_opens_while_the_combine_tab_waits_behind_it", "crates/automation/tests/it/automation.rs::combine_extract_and_split", "crates/automation/tests/it/automation.rs::combine_opens_protected_files_with_their_passwords", "crates/automation/tests/it/automation.rs::combine_takes_images_and_text_files", "crates/engine/src/tests.rs::files_for_combine_are_made_into_pdfs_and_pdfs_pass_through", "crates/organize/src/tests.rs::combine_keeps_pdfx_when_every_source_agrees", "crates/organize/src/tests.rs::combine_claims_no_pdfx_when_the_sources_disagree"]
notes = "Combine files is its own tab: a table of the files (name, pages, size, modified, warnings) with column sorting, resizing and moving; files, folders (with subfolders) and open documents can be added, or dropped on the tab (desktop and web): a drop joins the end of the list in the order dropped, as one undo step, not at the place under the pointer; files of a kind Combine does not take are left out and named. Dropped elsewhere, files open as before. File Explorer's \"Combine files in PdfCraft\" and `pdfcraft --combine files…` add files from outside, to the running PdfCraft's tab (#585). Dropping adds no engine behaviour, so it has no tool of its own (doc_combine takes the files). Images (PNG, JPEG, TIFF, GIF, BMP, JPEG 2000) and .txt files become PDFs as they are added (#569; also in doc_combine). A file that can't be read stays in the list with why, and Combine asks before leaving it out; Office documents, HTML and other formats are not converted yet. Problems show before Combine (password, security settings that withhold page assembly, bad page ranges, duplicates); protected files are unlocked with their open or permissions password (also doc_combine passwords). The result is never encrypted, and is not yet offered for protection in the same step. A PDF/X result (output intent, GTS_PDFXVersion, Trapped, XMP pdfxid) only when every source declares the same version and output intent (#263). When they differ the result claims none, and nothing reports that yet; Acrobat behaviour not observed."
[[feature]]
id = "organize.combine-bookmarks"