diff --git a/README.md b/README.md index a2911b0..90c3474 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ After setup completes, click Enhance again. When the selected Enhancer checkout For web PDFs, the viewer sends the already-loaded document to the host in acknowledged chunks. Enhancement does not make another HTTP download, so it can use PDFs that the browser loaded from sites that reject standalone requests. Local PDFs are read directly from disk. Both enhancement modes use `--force-ocr --ai-review` to re-read every page and review recognized text against page images with the local AI models, including when the PDF already contains text. This rasterizes pages in the enhanced copy and takes longer than preserving existing text. The source remains unchanged. The tagger builds heading structure and section bookmarks from the reviewed text. Cached results from the previous pipeline are regenerated on the next enhancement. -Enhanced web copies are saved under `~/Library/Application Support/PDF Magic/Enhanced` on macOS or `~/.local/share/pdf-magic/enhanced` on Linux. This lets browser-launched helpers finish tagging without needing to replace files in the protected Downloads folder. Enhanced local copies are saved beside their source PDF. +Enhanced local copies are saved beside their source PDF. If the native helper cannot read the local path during preparation, the viewer retries using the loaded PDF bytes. If the enhanced copy is available in a different folder, **Save enhanced copy** opens the browser's Save As dialog so you can choose the original folder. The viewer opens the copy from the location you select. Copies staged for Save As and enhanced web copies are stored under `~/Library/Application Support/PDF Magic/Enhanced` on macOS or `~/.local/share/pdf-magic/enhanced` on Linux. Enhancement requests are deduplicated by the PDF's SHA-256 content hash, including requests from separate tabs and different URLs or filenames. Duplicate requests share the running job's progress and result. Completed results are reused only while their output hash still matches; submitting an unchanged enhanced PDF also reuses that result. Changed or missing outputs are regenerated, and failed or interrupted jobs can be retried. Job records are stored in `.jobs` under the enhanced web-copy directory. Jobs already started by an older native host continue independently. diff --git a/manifest.json b/manifest.json index ca9c59e..e61ecbe 100644 --- a/manifest.json +++ b/manifest.json @@ -7,6 +7,7 @@ "tabs", "webRequest", "clipboardWrite", + "downloads", "storage", "nativeMessaging" ], diff --git a/native/pdfmagic-enhancer-host.py b/native/pdfmagic-enhancer-host.py index 94dbf2e..cad9401 100644 --- a/native/pdfmagic-enhancer-host.py +++ b/native/pdfmagic-enhancer-host.py @@ -480,18 +480,27 @@ def enhance_pdf( with tempfile.TemporaryDirectory(prefix="pdf-magic-enhancer-") as temp_name: temporary_directory = Path(temp_name) - input_path, is_local = ( - (uploaded_path, False) if uploaded_path is not None - else input_from_url(source_url, temporary_directory) - ) - # Browser-launched helpers can create Downloads files yet be denied - # permission to replace them during tagging. Keep web copies in app data. + input_path = uploaded_path + if input_path is None: + input_path, _ = input_from_url(source_url, temporary_directory) + # Keep web copies and copies awaiting a browser Save As in app data. web_output_directory = ( Path.home() / "Library/Application Support/PDF Magic/Enhanced" if sys.platform == "darwin" else Path.home() / ".local/share/pdf-magic/enhanced" ) - output_directory = input_path.parent if is_local else web_output_directory + output_directory = web_output_directory + source = urlparse(source_url) + if source.scheme == "file": + source_directory = Path(unquote(source.path)).parent + try: + # Tagging creates and replaces files in the destination directory. + with tempfile.NamedTemporaryFile(prefix=".pdfmagic-", dir=source_directory): + pass + except (PermissionError, FileNotFoundError): + pass + else: + output_directory = source_directory options = enhancement_options(enhancement_mode) def create(report): output_path = unique_output(output_directory, safe_stem(source_url)) diff --git a/src/viewer.html b/src/viewer.html index 6630797..e2bbf93 100644 --- a/src/viewer.html +++ b/src/viewer.html @@ -221,6 +221,13 @@ + +
Loading PDF…
diff --git a/src/viewer/enhance-pdf.js b/src/viewer/enhance-pdf.js index 5a63455..c70c32b 100644 --- a/src/viewer/enhance-pdf.js +++ b/src/viewer/enhance-pdf.js @@ -28,10 +28,14 @@ const errorNotice = document.querySelector("#enhance-error-notice"); const errorMessage = document.querySelector("#enhance-error-message"); const copyErrorButton = document.querySelector("#enhance-copy-error"); const dismissErrorButton = document.querySelector("#enhance-dismiss-error"); +const saveNotice = document.querySelector("#enhance-save-notice"); +const saveMessage = document.querySelector("#enhance-save-message"); +const saveCopyButton = document.querySelector("#enhance-save-copy"); const defaultTitle = enhanceButton.title; let titleResetTimer; let toastTimer; let lastEnhancementStage = "preparing"; +let pendingSave; function isMissingNativeHost(message) { return /native.*(?:host|messag)|host.*(?:not found|not configured)|enhancer script not found|enhancer-host[.]json|native.*exited/i.test(message); @@ -107,6 +111,21 @@ function updateEnhancementProgress(stage, completed, total) { } async function enhanceLoadedPdf(sourceUrl, referenceUrl) { + if (new URL(sourceUrl).protocol === "file:") { + try { + return await requestEnhancement(sourceUrl, referenceUrl, true); + } catch (error) { + // macOS can let the browser open a file while denying its native helper + // access to the same path. Retry with the bytes already in the viewer. + if (lastEnhancementStage !== "preparing" || !/^\[Errno (?:1|13)\] /.test(error.message)) { + throw error; + } + } + } + return await requestEnhancement(sourceUrl, referenceUrl, false); +} + +async function requestEnhancement(sourceUrl, referenceUrl, useLocalPath) { const port = chrome.runtime.connectNative(NATIVE_HOST); let pending; let disconnected = false; @@ -143,12 +162,12 @@ async function enhanceLoadedPdf(sourceUrl, referenceUrl) { }); } try { - const session = await pdfDocumentSessionReady; - const pdfDocument = session?.document; const enhancementMode = "light"; - if (new URL(sourceUrl).protocol === "file:") { + if (useLocalPath) { return await request({ action: "enhance-pdf", sourceUrl, referenceUrl, enhancementMode, progress: true }); } + const session = await pdfDocumentSessionReady; + const pdfDocument = session?.document; if (!pdfDocument) throw new Error("PDF has not finished loading"); const data = await pdfDocument.getData(); updateEnhancementProgress("upload", 0, data.length); @@ -241,7 +260,62 @@ async function replaceCurrentTab(outputUrl) { window.location.replace(destination.href); } +function waitForSavedCopy(id) { + return new Promise((resolve, reject) => { + async function check() { + try { + const [item] = await chrome.downloads.search({ id }); + if (!item || item.state === "interrupted") { + if (item?.error === "USER_CANCELED") resolve(null); + else reject(new Error(item?.error || "The browser could not save the file")); + } else if (item.state === "complete") { + resolve(item.filename); + } else { + return; + } + } catch (error) { + reject(error); + } + chrome.downloads.onChanged.removeListener(onChanged); + } + function onChanged(change) { + if (change.id === id && change.state) void check(); + } + chrome.downloads.onChanged.addListener(onChanged); + void check(); + }); +} + +saveCopyButton.addEventListener("click", async () => { + if (!pendingSave || saveCopyButton.disabled) return; + const { outputUrl, prompt } = pendingSave; + saveCopyButton.disabled = true; + saveMessage.textContent = prompt; + try { + const filename = decodeURIComponent(new URL(outputUrl).pathname.split("/").pop()); + const id = await chrome.downloads.download({ url: outputUrl, filename, saveAs: true }); + const savedPath = await waitForSavedCopy(id); + if (!savedPath) return; + const savedUrl = `file://${savedPath.split("/").map(encodeURIComponent).join("/")}`; + pendingSave = undefined; + saveNotice.hidden = true; + await replaceCurrentTab(savedUrl); + } catch (error) { + if (pendingSave) { + saveMessage.textContent = `${error.message}. ${prompt}`; + } else { + showToast("Enhanced copy saved. Open it from the browser’s downloads."); + } + } finally { + saveCopyButton.disabled = false; + } +}); + async function enhanceCurrentPdf() { + if (pendingSave) { + saveCopyButton.focus(); + return; + } errorNotice.hidden = true; for (const button of enhanceButtons) button.disabled = true; setEnhanceTitle("Enhancing PDF…"); @@ -258,12 +332,26 @@ async function enhanceCurrentPdf() { throw new Error("PDF source URL unavailable"); } - const response = await enhanceLoadedPdf(source.originalUrl.href, referenceUrl); + const original = source.originalUrl; + const response = await enhanceLoadedPdf(original.href, referenceUrl); if (!response?.ok || !response.outputUrl) { throw new Error(response?.error || "PDF enhancer did not return a local copy"); } + if (original.protocol === "file:") { + const sourceDirectory = new URL(".", original); + const outputDirectory = new URL(".", response.outputUrl); + if (decodeURIComponent(sourceDirectory.href) !== decodeURIComponent(outputDirectory.href)) { + const folder = decodeURIComponent(sourceDirectory.pathname); + const prompt = `Choose the original PDF’s folder (${folder}) to save the enhanced copy beside it.`; + pendingSave = { outputUrl: response.outputUrl, prompt }; + saveMessage.textContent = prompt; + saveNotice.hidden = false; + return; + } + } + showToast("Enhanced PDF ready"); updateEnhancementProgress("complete", 1, 1); await replaceCurrentTab(response.outputUrl); diff --git a/src/viewer/viewer.css b/src/viewer/viewer.css index c738859..2bb193b 100644 --- a/src/viewer/viewer.css +++ b/src/viewer/viewer.css @@ -1114,7 +1114,8 @@ input { } /* Keep native-host and OCR errors available after the progress bar closes. */ -.enhance-error-notice { +.enhance-error-notice, +.enhance-save-notice { position: fixed; left: 50%; bottom: 24px; @@ -1124,14 +1125,15 @@ input { max-height: min(45vh, 300px); overflow-y: auto; padding: 12px 14px; - border: 1px solid #c43f3f; + border: 1px solid var(--border); border-radius: 8px; background: var(--toast-bg); color: var(--text); box-shadow: 0 8px 28px rgb(0 0 0 / 20%); } -.enhance-error-notice[hidden] { display: none; } -.enhance-error-notice p { +.enhance-error-notice { border-color: #c43f3f; } +.enhance-error-notice[hidden], .enhance-save-notice[hidden] { display: none; } +.enhance-error-notice p, .enhance-save-notice p { margin: 8px 0 12px; white-space: pre-wrap; overflow-wrap: anywhere; diff --git a/tests/enhance-failure.test.mjs b/tests/enhance-failure.test.mjs index 441caa7..29a8c8e 100644 --- a/tests/enhance-failure.test.mjs +++ b/tests/enhance-failure.test.mjs @@ -18,6 +18,7 @@ function fixture(responseForAction) { "enhance-progress", "enhance-progress-bar", "enhance-progress-label", "enhance-progress-percentage", "enhance-error-notice", "enhance-error-message", "enhance-copy-error", "enhance-dismiss-error", + "enhance-save-notice", "enhance-save-message", "enhance-save-copy", ]; for (const id of identifiers) { elements.set(`#${id}`, { diff --git a/tests/enhance-pdf.test.mjs b/tests/enhance-pdf.test.mjs index af2ef01..52c1e94 100644 --- a/tests/enhance-pdf.test.mjs +++ b/tests/enhance-pdf.test.mjs @@ -24,6 +24,13 @@ async function enhancerFixture(sendNativeMessage, pageNumber = "1", data = new U style: { setProperty() {} }, }); } + for (const id of ["enhance-save-notice", "enhance-save-message", "enhance-save-copy"]) { + elements.set(`#${id}`, { + hidden: true, + focus() {}, + addEventListener(type, handler) { if (type === "click") clickHandlers.set(id, handler); }, + }); + } elements.get("#page-number").value = pageNumber; const destinations = []; const messages = []; @@ -45,12 +52,15 @@ async function enhancerFixture(sendNativeMessage, pageNumber = "1", data = new U Promise.resolve().then(async () => { try { if (["enhance-pdf", "enhance-pdf-finish"].includes(message.action)) { - messageListener({ type: "progress", stage: "review", completed: 2, total: 4 }); - progressSnapshots.push({ label: elements.get("#enhance-progress-label").textContent, - value: elements.get("#enhance-progress-bar").value, - percentage: elements.get("#enhance-progress-percentage").textContent, - hidden: elements.get("#enhance-progress").hidden }); - messageListener(await sendNativeMessage()); + const response = await sendNativeMessage(message); + if (response.ok) { + messageListener({ type: "progress", stage: "review", completed: 2, total: 4 }); + progressSnapshots.push({ label: elements.get("#enhance-progress-label").textContent, + value: elements.get("#enhance-progress-bar").value, + percentage: elements.get("#enhance-progress-percentage").textContent, + hidden: elements.get("#enhance-progress").hidden }); + } + messageListener(response); } else { messageListener({ ok: true }); } @@ -90,6 +100,7 @@ async function enhancerFixture(sendNativeMessage, pageNumber = "1", data = new U chrome: { storage: { local: { get: async () => ({}), set: async () => {} } }, runtime, + downloads: setupOptions.downloads, tabs: { getCurrent: async () => ({ id: 42 }), update: async (_, destination) => destinations.push(destination.url) }, }, }); @@ -216,10 +227,51 @@ test("progress events update the bar without consuming the final response", asyn }); test("local PDFs use a persistent native connection for progress", async () => { - const { messages, progressSnapshots } = await enhancerFixture(async () => ({ ok: true, outputUrl: "file:///tmp/enhanced.pdf" }), "1", undefined, "file:///tmp/source.pdf"); + const { messages, progressSnapshots, destinations } = await enhancerFixture(async () => ({ ok: true, outputUrl: "file:///tmp/enhanced.pdf" }), "1", undefined, "file:///tmp/source.pdf"); assert.equal(messages.length, 1); assert.equal(messages[0].action, "enhance-pdf"); assert.equal(messages[0].progress, true); assert.equal(messages[0].enhancementMode, "light"); assert.equal(progressSnapshots[0].value, 50); + assert.deepEqual(destinations, ["chrome-extension://viewer/src/viewer.html?url=file%3A%2F%2F%2Ftmp%2Fenhanced.pdf"]); +}); + +test("a denied local path retries with the loaded PDF and opens the copy saved beside it", async () => { + const sourceUrl = "file:///Users/example/Desktop/local%20source.pdf"; + const data = new Uint8Array([37, 80, 68, 70, 45]); + const downloads = []; + const listeners = new Set(); + const { messages, elements, clickHandlers, destinations } = await enhancerFixture(async ({ action }) => { + if (action === "enhance-pdf") { + return { ok: false, error: "[Errno 1] Operation not permitted: '/Users/example/Desktop/local source.pdf'" }; + } + return { ok: true, outputUrl: "file:///tmp/enhanced.pdf" }; + }, "2", data, sourceUrl, {}, { + downloads: { + download: async (options) => downloads.push({ ...options }), + search: async ({ id }) => id === 1 + ? [{ state: "interrupted", error: "USER_CANCELED" }] + : [{ state: "complete", filename: "/Users/example/Desktop/enhanced #1.pdf" }], + onChanged: { addListener: (listener) => listeners.add(listener), removeListener: (listener) => listeners.delete(listener) }, + }, + }); + + assert.deepEqual(messages.map(({ action }) => action), [ + "enhance-pdf", "enhance-pdf-start", "enhance-pdf-chunk", "enhance-pdf-finish", + ]); + assert.equal(messages[1].sourceUrl, sourceUrl); + assert.equal(messages[1].referenceUrl, messages[0].referenceUrl); + assert.equal(messages[1].byteLength, data.length); + assert.deepEqual(Buffer.from(messages[2].data, "base64"), Buffer.from(data)); + assert.match(elements.get("#enhance-save-message").textContent, /\/Users\/example\/Desktop\//); + assert.equal(elements.get("#enhance-save-notice").hidden, false); + assert.deepEqual(destinations, []); + await clickHandlers.get("enhance-save-copy")(); + assert.deepEqual(destinations, []); + assert.equal(elements.get("#enhance-save-notice").hidden, false); + await clickHandlers.get("enhance-save-copy")(); + assert.deepEqual(downloads[1], { url: "file:///tmp/enhanced.pdf", filename: "enhanced.pdf", saveAs: true }); + assert.deepEqual(destinations, ["chrome-extension://viewer/src/viewer.html?url=file%3A%2F%2F%2FUsers%2Fexample%2FDesktop%2Fenhanced%2520%25231.pdf#page=2"]); + assert.equal(elements.get("#enhance-save-notice").hidden, true); + assert.equal(listeners.size, 0); }); diff --git a/tests/native-enhancer.test.py b/tests/native-enhancer.test.py index 3667f33..1c0f0a8 100644 --- a/tests/native-enhancer.test.py +++ b/tests/native-enhancer.test.py @@ -316,6 +316,34 @@ def test_web_copy_finishes_in_application_data(self): self.assertEqual(result, directory / "Library/Application Support/PDF Magic/Enhanced/source-enhanced-ocr.pdf") self.assertEqual(result.read_bytes(), source.read_bytes()) + def test_uploaded_local_copy_prefers_source_folder_and_stages_when_denied(self): + for denied in (False, True): + with self.subTest(denied=denied), tempfile.TemporaryDirectory() as folder: + directory = Path(folder).resolve() + source_folder = directory / "Desktop" + source_folder.mkdir() + source = source_folder / "scan.pdf" + uploaded = directory / "uploaded.pdf" + uploaded.write_bytes(b"%PDF-1.7\nloaded data") + (directory / "ocr-scanned-pdf.sh").write_text('cp "$1" "$2"\n') + named_temporary_file = tempfile.NamedTemporaryFile + + def create_temporary_file(*args, **kwargs): + if denied and kwargs.get("dir") == source_folder: + raise PermissionError("Desktop access denied") + return named_temporary_file(*args, **kwargs) + + with patch.object(host, "load_config", return_value={"enhancer_dir": folder}), \ + patch.object(host.Path, "home", return_value=directory), \ + patch.object(host.sys, "platform", "darwin"), \ + patch.object(host, "stamp_source_url"), \ + patch.object(host.tempfile, "NamedTemporaryFile", side_effect=create_temporary_file): + result = host.enhance_pdf(source.as_uri(), source.as_uri(), uploaded_path=uploaded) + + expected_folder = directory / "Library/Application Support/PDF Magic/Enhanced" if denied else source_folder + self.assertEqual(result, expected_folder / "scan-enhanced-ocr.pdf") + self.assertEqual(result.read_bytes(), uploaded.read_bytes()) + def test_metadata_and_qpdf_logs_use_stderr(self): with patch.object(host, "pikepdf_python", return_value=["python3"]), \ patch.object(host.shutil, "which", return_value="qpdf"), \