Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src-tauri/src/compress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,20 @@ pub async fn compress_files(

match run_gs(&app, args).await {
Ok(()) => {
std::fs::rename(&tmp_path, &output_path).map_err(|e| e.to_string())?;
if let Err(e) = std::fs::rename(&tmp_path, &output_path) {
let _ = std::fs::remove_file(&tmp_path);
let _ = app.emit(
"compress:progress",
ProgressEvent {
file: job.path.clone(),
status: "error".into(),
saved_bytes: None,
compressed_size: None,
error_msg: Some(e.to_string()),
},
);
continue;
}

let compressed_size = std::fs::metadata(&output_path)
.map(|m| m.len() as i64)
Expand Down
6 changes: 0 additions & 6 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,6 @@ pub fn check_path_writable(path: String) -> bool {
}
}

#[tauri::command]
fn check_path_writable_cmd(path: String) -> bool {
check_path_writable(path)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
use crate::compress::compress_files;
Expand Down Expand Up @@ -89,7 +84,6 @@ pub fn run() {
reveal_in_finder,
get_file_meta,
validate_pdf,
check_path_writable_cmd,
set_menu_item_enabled,
check_for_update,
])
Expand Down
45 changes: 45 additions & 0 deletions src-tauri/src/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,5 +175,50 @@ mod tests {
assert!(ids.contains("clear-queue"));
assert!(ids.contains("compress"));
assert!(ids.contains("reset-selected"));
assert!(ids.contains("check-for-update"));
}

#[test]
fn menu_ids_sync_with_build_menu() {
// Note: build_menu requires AppHandle and cannot be called in unit tests.
// Instead we maintain a parallel list here that must be kept in sync with
// the map.insert calls in build_menu.
// Hardcoded list of IDs that are inserted in build_menu's HashMap
let build_menu_ids: &[&str] = &[
"add-files",
"reveal-in-finder",
"clear-queue",
"compress",
"reset-selected",
"check-for-update",
];

// Assert length matches
assert_eq!(
MENU_IDS.len(),
build_menu_ids.len(),
"MENU_IDS and build_menu HashMap have different lengths"
);

// Assert all MENU_IDS appear in build_menu_ids
let build_menu_set: std::collections::HashSet<&str> =
build_menu_ids.iter().copied().collect();
for id in MENU_IDS {
assert!(
build_menu_set.contains(id),
"ID '{}' in MENU_IDS is not inserted in build_menu",
id
);
}

// Assert all build_menu_ids appear in MENU_IDS
let menu_ids_set: std::collections::HashSet<&str> = MENU_IDS.iter().copied().collect();
for id in build_menu_ids {
assert!(
menu_ids_set.contains(id),
"ID '{}' inserted in build_menu is not in MENU_IDS",
id
);
}
}
}
14 changes: 6 additions & 8 deletions src-tauri/src/updater.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
fn strip_v(tag: &str) -> &str {
tag.strip_prefix('v').unwrap_or(tag)
}

pub fn parse_version(tag: &str) -> Option<(u64, u64, u64)> {
let s = tag.strip_prefix('v').unwrap_or(tag);
let s = strip_v(tag);
let parts: Vec<&str> = s.split('.').collect();
if parts.len() != 3 {
return None;
Expand Down Expand Up @@ -40,13 +44,7 @@ pub async fn check_for_update() -> Option<String> {
.ok()?;

if is_newer(&release.tag_name, env!("CARGO_PKG_VERSION")) {
Some(
release
.tag_name
.strip_prefix('v')
.unwrap_or(&release.tag_name)
.to_string(),
)
Some(strip_v(&release.tag_name).to_string())
} else {
None
}
Expand Down
3 changes: 2 additions & 1 deletion src/lib/components/ActionBar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { selectedFileId } from "$lib/stores/selectionStore";
import { settings } from "$lib/stores/settingsStore";
import { toast } from "$lib/stores/toastStore";
import { basename } from "$lib/fileActions";
import { buildNotificationBody } from "$lib/notification";

const doneCount = derived(queue, ($q) => $q.filter((e) => e.status === "done").length);
Expand Down Expand Up @@ -59,7 +60,7 @@
compressDone++;
} else if (payload.status === "error") {
queue.updateStatus(payload.file, "error", { errorMsg: payload.error_msg });
const name = payload.file.split("/").pop() ?? payload.file;
const name = basename(payload.file);
toast.show(`${name}: ${payload.error_msg ?? "Compression failed"}`);
compressDone++;
} else {
Expand Down
19 changes: 5 additions & 14 deletions src/lib/components/DetailPanel.svelte
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
<script lang="ts">
import { derived } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { queue, type Preset } from "$lib/stores/queueStore";
import { selectedFileId } from "$lib/stores/selectionStore";
import { settings } from "$lib/stores/settingsStore";
import { formatBytes } from "$lib/notification";
import { revealInFinder } from "$lib/fileActions";

const selectedFile = derived([queue, selectedFileId], ([$q, $id]) => $q.find((e) => e.id === $id) ?? null);

$: hasFiles = $queue.length > 0;

function formatSize(bytes: number): string {
if (bytes >= 1_000_000) return `${(bytes / 1_000_000).toFixed(1)} MB`;
if (bytes >= 1_000) return `${(bytes / 1_000).toFixed(0)} KB`;
return `${bytes} B`;
}

function savingsPct(original: number, compressed: number): string {
return `−${Math.round(((original - compressed) / original) * 100)}%`;
}

function revealInFinder(path: string) {
invoke("reveal_in_finder", { path });
}

function resetToCompress() {
if (!$selectedFile) return;
queue.resetFile($selectedFile.id);
Expand Down Expand Up @@ -85,13 +76,13 @@
{/if}

<div class="sizes">
<div class="size-row"><span class="label">Original</span><span>{formatSize($selectedFile.size)}</span></div>
<div class="size-row"><span class="label">Original</span><span>{formatBytes($selectedFile.size)}</span></div>
{#if $selectedFile.status === "done" && $selectedFile.compressedSize !== undefined}
<div class="result-block">
<div class="savings-pct">{savingsPct($selectedFile.size, $selectedFile.compressedSize)}</div>
<div class="size-story">
{formatSize($selectedFile.size)} → {formatSize($selectedFile.compressedSize)}
· saved {formatSize($selectedFile.size - $selectedFile.compressedSize)}
{formatBytes($selectedFile.size)} → {formatBytes($selectedFile.compressedSize)}
· saved {formatBytes($selectedFile.size - $selectedFile.compressedSize)}
</div>
<div class="result-actions">
<button class="finder-btn" on:click={() => revealInFinder($selectedFile!.path)}>Show in Finder</button>
Expand Down
10 changes: 9 additions & 1 deletion src/lib/fileActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { queue } from "$lib/stores/queueStore";

export function basename(path: string): string {
return path.split("/").pop() ?? path;
}

export async function addPath(path: string): Promise<void> {
const name = path.split("/").pop() ?? path;
const name = basename(path);
try {
const isPdf = await invoke<boolean>("validate_pdf", { path });
if (!isPdf) {
Expand All @@ -24,3 +28,7 @@ export async function addFiles(): Promise<void> {
const list = Array.isArray(paths) ? paths : [paths];
for (const path of list) await addPath(path);
}

export function revealInFinder(path: string): void {
invoke("reveal_in_finder", { path }).catch(() => {});
}
4 changes: 2 additions & 2 deletions src/lib/notification.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function formatSavedBytes(bytes: number): string {
export function formatBytes(bytes: number): string {
if (bytes >= 1_000_000) return `${(bytes / 1_000_000).toFixed(1)} MB`;
if (bytes >= 1_000) return `${Math.round(bytes / 1_000)} KB`;
return `${bytes} B`;
Expand All @@ -11,7 +11,7 @@ export function buildNotificationBody(
): string {
if (errorCount === 0) {
const noun = doneCount === 1 ? "PDF" : "PDFs";
return `${doneCount} ${noun} compressed — saved ${formatSavedBytes(savedBytes)} total`;
return `${doneCount} ${noun} compressed — saved ${formatBytes(savedBytes)} total`;
}
const total = doneCount + errorCount;
return `${doneCount} of ${total} PDFs compressed — ${errorCount} failed`;
Expand Down
38 changes: 18 additions & 20 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import { settings } from "$lib/stores/settingsStore";
import { queue, pendingCount } from "$lib/stores/queueStore";
import { selectedFileId } from "$lib/stores/selectionStore";
import { addFiles } from "$lib/fileActions";
import { addFiles, revealInFinder } from "$lib/fileActions";
import { handleShortcut, type ShortcutState } from "$lib/shortcuts";
import { openUrl } from "@tauri-apps/plugin-opener";
import { toast } from "$lib/stores/toastStore";
Expand All @@ -22,7 +22,7 @@

function revealSelected() {
if (selectedFile?.status === "done") {
invoke("reveal_in_finder", { path: selectedFile.path });
revealInFinder(selectedFile.path);
}
}

Expand Down Expand Up @@ -87,6 +87,20 @@
invoke("set_menu_item_enabled", { id, enabled }).catch(() => {});
}

// ── update check helper ───────────────────────────────────────────────────

async function checkAndShowUpdateToast(showUpToDate = false) {
const version: string | null = await invoke("check_for_update");
if (version) {
toast.showPersistent(`v${version} is available`, {
label: "Download",
handler: () => openUrl("https://github.com/JBolanle/PDFCompressor/releases/latest"),
});
} else if (showUpToDate) {
toast.show("You're on the latest version");
}
}

$: syncMenu("reveal-in-finder", selectedFile?.status === "done");
$: syncMenu("clear-queue", $queue.length > 0);
$: syncMenu("compress", $pendingCount > 0 && !isCompressing);
Expand All @@ -100,31 +114,15 @@
settings.load();
window.addEventListener("keydown", onKeyDown);

const version: string | null = await invoke("check_for_update");
if (version) {
toast.showPersistent(`v${version} is available`, {
label: "Download",
handler: () => openUrl("https://github.com/JBolanle/PDFCompressor/releases/latest"),
});
}
await checkAndShowUpdateToast();

unlisteners = await Promise.all([
listen("menu:add-files", () => addFiles()),
listen("menu:compress", () => triggerCompress()),
listen("menu:reveal-in-finder", () => revealSelected()),
listen("menu:clear-queue", () => clearAll()),
listen("menu:reset-selected", () => resetSelected()),
listen("menu:check-for-update", async () => {
const v: string | null = await invoke("check_for_update");
if (v) {
toast.showPersistent(`v${v} is available`, {
label: "Download",
handler: () => openUrl("https://github.com/JBolanle/PDFCompressor/releases/latest"),
});
} else {
toast.show("You're on the latest version");
}
}),
listen("menu:check-for-update", () => checkAndShowUpdateToast(true)),
]);
});

Expand Down
12 changes: 6 additions & 6 deletions src/test/notification.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { describe, it, expect } from "vitest";
import { buildNotificationBody, formatSavedBytes } from "$lib/notification";
import { buildNotificationBody, formatBytes } from "$lib/notification";

describe("formatSavedBytes", () => {
describe("formatBytes", () => {
it("formats bytes under 1 KB", () => {
expect(formatSavedBytes(500)).toBe("500 B");
expect(formatBytes(500)).toBe("500 B");
});

it("formats KB (rounds to nearest KB)", () => {
expect(formatSavedBytes(840_000)).toBe("840 KB");
expect(formatBytes(840_000)).toBe("840 KB");
});

it("formats MB to one decimal place", () => {
expect(formatSavedBytes(2_400_000)).toBe("2.4 MB");
expect(formatBytes(2_400_000)).toBe("2.4 MB");
});

it("formats exactly 1 MB", () => {
expect(formatSavedBytes(1_000_000)).toBe("1.0 MB");
expect(formatBytes(1_000_000)).toBe("1.0 MB");
});
});

Expand Down