#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Set up Rust formatting (#8897)
James Brunton9245830e32d9
diff --git a/.github/workflows/rust-lint.yml b/.github/workflows/rust-lint.ymlindex 64b1be5e63..fec7d3d35a 100644--- a/.github/workflows/rust-lint.yml+++ b/.github/workflows/rust-lint.yml@@ -2,12 +2,11 @@ name: Rust Lint# Reusable workflow called from build.yml when desktop / Rust sources change.#-# The task behind it is `desktop:lint`, so swapping Clippy for another linter-# does not rename the job. Clippy only analyses the `cfg` branches for the host-# it runs on, and the Tauri crate carries Linux-, macOS- and Windows-only-# modules. The matrix therefore runs on all three so every platform branch is-# linted where it actually compiles, including the Windows-only thumbnail-# handler crate.+# Formatting is platform-independent, so rustfmt runs once on Linux. Clippy+# only analyses the `cfg` branches for the host it runs on, and the Tauri crate+# carries Linux-, macOS- and Windows-only modules. The matrix therefore runs on+# all three so every platform branch is linted where it actually compiles,+# including the Windows-only thumbnail handler crate.on:workflow_call:@@ -47,7 +46,7 @@ jobs:uses: dtolnay/rust-toolchain@4be9e76fd7c4901c61fb841f559994984270fce7 # stablewith:toolchain: stable- components: clippy+ components: clippy, rustfmt# Registry + compiled dependencies; a cold Clippy run rebuilds the whole# Tauri graph, which is what dominates this job.@@ -67,5 +66,9 @@ jobs:with:version: 3.54.0+ - name: Check Rust formatting+ if: runner.os == 'Linux'+ run: task desktop:format:check+- name: Run desktop lintrun: task desktop:lintdiff --git a/.taskfiles/desktop.yml b/.taskfiles/desktop.ymlindex 8e40c63bf0..1ad475efeb 100644--- a/.taskfiles/desktop.yml+++ b/.taskfiles/desktop.yml@@ -128,12 +128,20 @@ tasks:- cargo clippy --all-targets -- -D warningsformat:- desc: "Auto-fix Rust formatting (not implemented yet)"- cmds: []+ desc: "Auto-fix Rust formatting"+ dir: src-tauri+ cmds:+ - cargo fmt+ - cargo fmt --manifest-path provisioner/Cargo.toml+ - cargo fmt --manifest-path thumbnail-handler/Cargo.tomlformat:check:- desc: "Check Rust formatting (not implemented yet)"- cmds: []+ desc: "Check Rust formatting"+ dir: src-tauri+ cmds:+ - cargo fmt -- --check+ - cargo fmt --manifest-path provisioner/Cargo.toml -- --check+ - cargo fmt --manifest-path thumbnail-handler/Cargo.toml -- --checkcheck:desc: "Full desktop quality gate"diff --git a/Taskfile.yml b/Taskfile.ymlindex 407872bdde..8f7d159514 100644--- a/Taskfile.yml+++ b/Taskfile.yml@@ -292,6 +292,7 @@ tasks:- task: backend:fix- task: frontend:fix- task: engine:fix+ - task: desktop:formatformat:desc: "Auto-fix formatting across all components"@@ -299,6 +300,7 @@ tasks:- task: backend:format- task: frontend:format- task: engine:format+ - task: desktop:formatformat:check:desc: "Check formatting across all components"@@ -306,6 +308,7 @@ tasks:- task: backend:format:check- task: frontend:format:check- task: engine:format:check+ - task: desktop:format:check# ============================================================# Code generationdiff --git a/frontend/src-tauri/src/commands/auth.rs b/frontend/src-tauri/src/commands/auth.rsindex 48eaa03f12..94378cee3d 100644--- a/frontend/src-tauri/src/commands/auth.rs+++ b/frontend/src-tauri/src/commands/auth.rs@@ -1,13 +1,13 @@-use keyring::{Entry};+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};+use keyring::Entry;+use rand::distr::Alphanumeric;+use rand::RngExt;use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};use std::sync::{Arc, Mutex};use tauri::{AppHandle, Runtime};use tauri_plugin_store::StoreExt;use tiny_http::{Response, Server};-use sha2::{Sha256, Digest};-use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};-use rand::RngExt;-use rand::distr::Alphanumeric;const STORE_FILE: &str = "connection.json";const USER_INFO_KEY: &str = "user_info";@@ -31,12 +31,15 @@ fn get_keyring_entry() -> Result<Entry, String> {if std::env::var("STIRLING_PDF_TEST_FORCE_AUTH_KEYRING_FAIL").is_ok() {return Err("Forced keyring failure for tests".to_string());}- log::debug!("Creating keyring entry with service='{}' username='{}'", KEYRING_SERVICE, KEYRING_TOKEN_KEY);- let entry = Entry::new(KEYRING_SERVICE, KEYRING_TOKEN_KEY)- .map_err(|e| {- log::error!("Failed to create keyring entry: {}", e);- format!("Failed to access keyring: {}", e)- })?;+ log::debug!(+ "Creating keyring entry with service='{}' username='{}'",+ KEYRING_SERVICE,+ KEYRING_TOKEN_KEY+ );+ let entry = Entry::new(KEYRING_SERVICE, KEYRING_TOKEN_KEY).map_err(|e| {+ log::error!("Failed to create keyring entry: {}", e);+ format!("Failed to access keyring: {}", e)+ })?;log::debug!("Keyring entry created successfully");Ok(entry)}@@ -97,16 +100,24 @@ pub async fn save_auth_token(app_handle: AppHandle, token: String) -> Result<(),return Ok(());}_ => {- log::info!("Keyring did not persist auth token - using Tauri Store fallback");+ log::info!(+ "Keyring did not persist auth token - using Tauri Store fallback"+ );}}}Err(e) => {- log::info!("Keyring set failed for auth token: {} - using Tauri Store fallback", e);+ log::info!(+ "Keyring set failed for auth token: {} - using Tauri Store fallback",+ e+ );}},Err(e) => {- log::info!("Keyring entry unavailable for auth token: {} - using Tauri Store fallback", e);+ log::info!(+ "Keyring entry unavailable for auth token: {} - using Tauri Store fallback",+ e+ );}}@@ -117,8 +128,7 @@ pub async fn save_auth_token(app_handle: AppHandle, token: String) -> Result<(),store.set(AUTH_TOKEN_STORE_KEY,- serde_json::to_value(trimmed)- .map_err(|e| format!("Failed to serialize token: {}", e))?,+ serde_json::to_value(trimmed).map_err(|e| format!("Failed to serialize token: {}", e))?,);store@@ -140,11 +150,17 @@ pub async fn get_auth_token(app_handle: AppHandle) -> Result<Option<String>, Strlog::debug!("No auth token in keyring, trying Tauri Store");}Err(e) => {- log::warn!("Keyring error reading auth token: {} - trying Tauri Store", e);+ log::warn!(+ "Keyring error reading auth token: {} - trying Tauri Store",+ e+ );}},Err(e) => {- log::warn!("Keyring entry unavailable for auth token: {} - trying Tauri Store", e);+ log::warn!(+ "Keyring entry unavailable for auth token: {} - trying Tauri Store",+ e+ );}}@@ -195,7 +211,10 @@ pub async fn clear_auth_token(app_handle: AppHandle) -> Result<(), String> {}#[tauri::command]-pub async fn save_refresh_token<R: Runtime>(app_handle: AppHandle<R>, token: String) -> Result<(), String> {+pub async fn save_refresh_token<R: Runtime>(+ app_handle: AppHandle<R>,+ token: String,+) -> Result<(), String> {log::info!("Saving refresh token - trying keyring first");match try_save_refresh_token_to_keyring(&token) {@@ -214,7 +233,10 @@ pub async fn save_refresh_token<R: Runtime>(app_handle: AppHandle<R>, token: Strlog::info!("Keyring did not persist refresh token - using Tauri Store fallback");}Err(e) => {- log::info!("Keyring error for refresh token: {} - using Tauri Store fallback", e);+ log::info!(+ "Keyring error for refresh token: {} - using Tauri Store fallback",+ e+ );}}@@ -225,8 +247,7 @@ pub async fn save_refresh_token<R: Runtime>(app_handle: AppHandle<R>, token: Strstore.set(REFRESH_TOKEN_STORE_KEY,- serde_json::to_value(&token)- .map_err(|e| format!("Failed to serialize token: {}", e))?,+ serde_json::to_value(&token).map_err(|e| format!("Failed to serialize token: {}", e))?,);store@@ -238,7 +259,9 @@ pub async fn save_refresh_token<R: Runtime>(app_handle: AppHandle<R>, token: Str}#[tauri::command]-pub async fn get_refresh_token<R: Runtime>(app_handle: AppHandle<R>) -> Result<Option<String>, String> {+pub async fn get_refresh_token<R: Runtime>(+ app_handle: AppHandle<R>,+) -> Result<Option<String>, String> {// Try keyring first (production / unrestricted environments). Any failure -// including entry creation - falls through to the Tauri Store fallback below.match get_refresh_token_keyring_entry() {@@ -251,11 +274,17 @@ pub async fn get_refresh_token<R: Runtime>(app_handle: AppHandle<R>) -> Result<Olog::debug!("No refresh token in keyring, trying Tauri Store");}Err(e) => {- log::warn!("Keyring error reading refresh token: {} - trying Tauri Store", e);+ log::warn!(+ "Keyring error reading refresh token: {} - trying Tauri Store",+ e+ );}},Err(e) => {- log::warn!("Keyring entry unavailable for refresh token: {} - trying Tauri Store", e);+ log::warn!(+ "Keyring entry unavailable for refresh token: {} - trying Tauri Store",+ e+ );}}@@ -441,7 +470,10 @@ pub async fn login(if is_supabase {// Supabase authentication flow- let login_url = format!("{}/auth/v1/token?grant_type=password", server_url.trim_end_matches('/'));+ let login_url = format!(+ "{}/auth/v1/token?grant_type=password",+ server_url.trim_end_matches('/')+ );let request_body = serde_json::json!({"email": username,@@ -484,7 +516,11 @@ pub async fn login(.text().await.unwrap_or_else(|_| "Unknown error".to_string());- log::error!("Supabase login failed with status {}: {}", status, error_text);+ log::error!(+ "Supabase login failed with status {}: {}",+ status,+ error_text+ );return Err(if status.as_u16() == 400 || status.as_u16() == 401 {"Invalid username or password".to_string()@@ -502,7 +538,9 @@ pub async fn login(.map_err(|e| format!("Failed to parse Supabase response: {}", e))?;let email = login_response.user.email.clone();- let username = login_response.user.user_metadata+ let username = login_response+ .user+ .user_metadata.as_ref().and_then(|m| m.full_name.clone()).or_else(|| email.clone())@@ -579,7 +617,11 @@ pub async fn login(.text().await.unwrap_or_else(|_| "Unknown error".to_string());- log::error!("Spring Boot login failed with status {}: {}", status, error_text);+ log::error!(+ "Spring Boot login failed with status {}: {}",+ status,+ error_text+ );if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {let error_code = error_json@@ -649,13 +691,20 @@ pub async fn start_oauth_login(success_html: String,error_html: String,) -> Result<OAuthCallbackResult, String> {- log::info!("Starting OAuth login for provider: {} with auth server: {}", provider, auth_server_url);+ log::info!(+ "Starting OAuth login for provider: {} with auth server: {}",+ provider,+ auth_server_url+ );// Generate PKCE code_verifier and code_challengelet code_verifier = generate_code_verifier();let code_challenge = generate_code_challenge(&code_verifier);- log::debug!("PKCE code_verifier generated: {} chars", code_verifier.len());+ log::debug!(+ "PKCE code_verifier generated: {} chars",+ code_verifier.len()+ );log::debug!("PKCE code_challenge: {}", code_challenge);// Use port 0 to let OS assign an available port (avoids port reuse issues)@@ -667,7 +716,9 @@ pub async fn start_oauth_login(tiny_http::ListenAddr::IP(addr) => addr.port(),#[cfg(unix)]tiny_http::ListenAddr::Unix(_) => {- return Err("OAuth callback server bound to Unix socket instead of TCP port".to_string())+ return Err(+ "OAuth callback server bound to Unix socket instead of TCP port".to_string(),+ )}};@@ -704,7 +755,8 @@ pub async fn start_oauth_login(log::info!("Waiting for OAuth callback...");// Wait for callback (with timeout)- for _ in 0..120 { // 2 minute timeout+ for _ in 0..120 {+ // 2 minute timeoutif let Ok(Some(request)) = server.recv_timeout(std::time::Duration::from_secs(1)) {let url_str = format!("http://127.0.0.1{}", request.url());log::debug!("Received OAuth callback: {}", url_str);@@ -726,8 +778,16 @@ pub async fn start_oauth_login(};let response = Response::from_string(html_response)- .with_header(tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]).unwrap())- .with_header(tiny_http::Header::from_bytes(&b"Connection"[..], &b"close"[..]).unwrap());+ .with_header(+ tiny_http::Header::from_bytes(+ &b"Content-Type"[..],+ &b"text/html; charset=utf-8"[..],+ )+ .unwrap(),+ )+ .with_header(+ tiny_http::Header::from_bytes(&b"Connection"[..], &b"close"[..]).unwrap(),+ );let _ = request.respond(response);@@ -740,18 +800,29 @@ pub async fn start_oauth_login(});// Wait for server thread to complete- server_handle.join()+ server_handle+ .join().map_err(|_| "OAuth callback server thread panicked".to_string())?;// Get result- let callback_data = result.lock().unwrap().take()+ let callback_data = result+ .lock()+ .unwrap()+ .take().ok_or_else(|| "OAuth callback timeout - no response received".to_string())?;// Handle the callback data - exchange authorization code for tokensmatch callback_data? {OAuthCallbackData::Code { code, redirect_uri } => {log::info!("OAuth completed with authorization code flow, exchanging code...");- exchange_code_for_token(&auth_server_url, &code, &redirect_uri, &code_verifier, &supabase_key).await+ exchange_code_for_token(+ &auth_server_url,+ &code,+ &redirect_uri,+ &code_verifier,+ &supabase_key,+ )+ .await}}}@@ -789,7 +860,10 @@ async fn exchange_code_for_token(format!("Failed to create HTTP client: {}", e)})?;// grant_type goes in query string, not body!- let token_url = format!("{}/auth/v1/token?grant_type=pkce", auth_server_url.trim_end_matches('/'));+ let token_url = format!(+ "{}/auth/v1/token?grant_type=pkce",+ auth_server_url.trim_end_matches('/')+ );// Body should be JSON with auth_code and code_verifierlet body = serde_json::json!({@@ -833,7 +907,11 @@ async fn exchange_code_for_token(.text().await.unwrap_or_else(|_| "Unknown error".to_string());- log::error!("Token exchange failed with status {}: {}", status, error_text);+ log::error!(+ "Token exchange failed with status {}: {}",+ status,+ error_text+ );return Err(format!("Token exchange failed: {}", error_text));}@@ -856,9 +934,7 @@ async fn exchange_code_for_token(.and_then(|v| v.as_str()).map(|s| s.to_string());- let expires_in = token_response- .get("expires_in")- .and_then(|v| v.as_i64());+ let expires_in = token_response.get("expires_in").and_then(|v| v.as_i64());Ok(OAuthCallbackResult {access_token,@@ -869,8 +945,8 @@ async fn exchange_code_for_token(fn parse_oauth_callback(url_str: &str) -> Result<OAuthCallbackData, String> {// Parse URL to extract authorization code or error- let parsed_url = url::Url::parse(url_str)- .map_err(|e| format!("Failed to parse callback URL: {}", e))?;+ let parsed_url =+ url::Url::parse(url_str).map_err(|e| format!("Failed to parse callback URL: {}", e))?;// Check for OAuth error first (error responses take precedence)let mut error = None;@@ -889,7 +965,10 @@ fn parse_oauth_callback(url_str: &str) -> Result<OAuthCallbackData, String> {// If OAuth provider returned an error, fail immediatelyif let Some(error_code) = error {let error_msg = if let Some(description) = error_description {- format!("OAuth authentication failed: {} - {}", error_code, description)+ format!(+ "OAuth authentication failed: {} - {}",+ error_code, description+ )} else {format!("OAuth authentication failed: {}", error_code)};@@ -903,14 +982,16 @@ fn parse_oauth_callback(url_str: &str) -> Result<OAuthCallbackData, String> {// Reconstruct the redirect_uri (without query params) for token exchangelet redirect_uri = if let Some(port) = parsed_url.port() {- format!("{}://{}:{}{}",+ format!(+ "{}://{}:{}{}",parsed_url.scheme(),parsed_url.host_str().unwrap_or("127.0.0.1"),port,parsed_url.path())} else {- format!("{}://{}{}",+ format!(+ "{}://{}{}",parsed_url.scheme(),parsed_url.host_str().unwrap_or("127.0.0.1"),parsed_url.path()diff --git a/frontend/src-tauri/src/commands/backend.rs b/frontend/src-tauri/src/commands/backend.rsindex d0d015b7e4..be563e755f 100644--- a/frontend/src-tauri/src/commands/backend.rs+++ b/frontend/src-tauri/src/commands/backend.rs@@ -1,11 +1,11 @@-use tauri_plugin_shell::ShellExt;-use tauri::Manager;+use crate::state::connection_state::{AppConnectionState, ConnectionMode};+use crate::utils::{add_log, app_data_dir};+use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Mutex;-use std::path::{Path, PathBuf};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};-use crate::utils::{add_log, app_data_dir};-use crate::state::connection_state::{AppConnectionState, ConnectionMode};+use tauri::Manager;+use tauri_plugin_shell::ShellExt;/// Removes shutdown markers left by previous sessions. The current path cannot/// exist yet, so it is never a sweep target.@@ -46,8 +46,9 @@ fn extract_port_from_running_log(log_line: &str) -> Option<u16> {// Look for pattern: "running on port: PORT"if let Some(start) = log_line.find("running on port: ") {let after_prefix = &log_line[start + 17..]; // Skip "running on port: "- // Take digits until whitespace or end of line- let port_str: String = after_prefix.chars()+ // Take digits until whitespace or end of line+ let port_str: String = after_prefix+ .chars().take_while(|c| c.is_ascii_digit()).collect();return port_str.parse::<u16>().ok();@@ -103,7 +104,10 @@ fn find_stirling_jar(resource_dir: &Path) -> Result<PathBuf, String> {let libs_dir = resource_dir.join("libs");let mut jar_files: Vec<_> = std::fs::read_dir(&libs_dir).map_err(|e| {- let error_msg = format!("Failed to read libs directory: {}. Make sure the JAR is copied to libs/", e);+ let error_msg = format!(+ "Failed to read libs directory: {}. Make sure the JAR is copied to libs/",+ e+ );add_log(error_msg.clone());error_msg})?@@ -111,8 +115,12 @@ fn find_stirling_jar(resource_dir: &Path) -> Result<PathBuf, String> {.filter(|entry| {let path = entry.path();// Match any .jar file containing "stirling-pdf" (case-insensitive)- path.extension().and_then(|s| s.to_str()).map(|ext| ext.eq_ignore_ascii_case("jar")).unwrap_or(false)- && path.file_name()+ path.extension()+ .and_then(|s| s.to_str())+ .map(|ext| ext.eq_ignore_ascii_case("jar"))+ .unwrap_or(false)+ && path+ .file_name().and_then(|f| f.to_str()).map(|name| name.to_ascii_lowercase().contains("stirling-pdf")).unwrap_or(false)@@ -134,7 +142,10 @@ fn find_stirling_jar(resource_dir: &Path) -> Result<PathBuf, String> {});let jar_path = jar_files[0].path();- add_log(format!("π Selected JAR: {:?}", jar_path.file_name().unwrap()));+ add_log(format!(+ "π Selected JAR: {:?}",+ jar_path.file_name().unwrap()+ ));Ok(jar_path)}@@ -279,7 +290,11 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {}// Create, configure and run the Java command to run Stirling-PDF JAR-fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &PathBuf) -> Result<(), String> {+fn run_stirling_pdf_jar(+ app: &tauri::AppHandle,+ java_path: &PathBuf,+ jar_path: &PathBuf,+) -> Result<(), String> {// Get platform-specific application data directory for Tauri modelet app_data_dir = app_data_dir();@@ -297,12 +312,17 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &// Migrate legacy workspace content into the app data root before launch.if legacy_work_dir.exists() {- add_log(format!("π¦ Migrating legacy workspace from {}", legacy_work_dir.display()));+ add_log(format!(+ "π¦ Migrating legacy workspace from {}",+ legacy_work_dir.display()+ ));if let Err(err) = migrate_legacy_workspace(&legacy_work_dir, &app_data_dir) {add_log(format!("β οΈ Failed to migrate legacy workspace: {}", err));} else {match std::fs::remove_dir_all(&legacy_work_dir) {- Ok(_) => add_log("β Removed legacy workspace directory after migration".to_string()),+ Ok(_) => {+ add_log("β Removed legacy workspace directory after migration".to_string())+ }Err(err) => add_log(format!("β οΈ Failed to remove legacy workspace: {}", err)),}}@@ -322,12 +342,12 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &"-DSTIRLING_PDF_TAURI_MODE=true",&log_path_option,"-Dlogging.file.name=stirling-pdf.log",- "-Dserver.port=0", // Let OS assign an available port+ "-Dserver.port=0", // Let OS assign an available port// No reverse proxy in front of the local sidecar, so don't trust forwarded headers.// Stops a LAN caller spoofing X-Forwarded-For to defeat the desktop-only signing gate."-Dserver.forward-headers-strategy=none",- "-Dsecurity.enableLogin=false", // Disable login for desktop mode- "-Dsecurity.csrfDisabled=true", // Disable CSRF for desktop mode+ "-Dsecurity.enableLogin=false", // Disable login for desktop mode+ "-Dsecurity.csrfDisabled=true", // Disable CSRF for desktop mode];// Enable the login agreement on local desktop installs when it has been provisioned.@@ -393,22 +413,23 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &.shell().command(java_path.to_str().unwrap()).args(java_options)- .current_dir(&work_dir) // Set working directory to writable location+ .current_dir(&work_dir) // Set working directory to writable location.env("TAURI_PARENT_PID", std::process::id().to_string()).env("STIRLING_PDF_CONFIG_DIR", config_dir.to_str().unwrap()).env("STIRLING_PDF_LOG_DIR", log_dir.to_str().unwrap()).env("STIRLING_PDF_WORK_DIR", work_dir.to_str().unwrap())- .env("STIRLING_PDF_SHUTDOWN_FILE", shutdown_file.to_str().unwrap());+ .env(+ "STIRLING_PDF_SHUTDOWN_FILE",+ shutdown_file.to_str().unwrap(),+ );add_log("βοΈ Starting backend with bundled JRE...".to_string());- let (rx, child) = sidecar_command- .spawn()- .map_err(|e| {- let error_msg = format!("β Failed to spawn sidecar: {}", e);- add_log(error_msg.clone());- error_msg- })?;+ let (rx, child) = sidecar_command.spawn().map_err(|e| {+ let error_msg = format!("β Failed to spawn sidecar: {}", e);+ add_log(error_msg.clone());+ error_msg+ })?;BACKEND_EXITED.store(false, Ordering::Release);{@@ -425,7 +446,9 @@ fn run_stirling_pdf_jar(app: &tauri::AppHandle, java_path: &PathBuf, jar_path: &}// Monitor backend output in a separate task-fn monitor_backend_output(mut rx: tauri::async_runtime::Receiver<tauri_plugin_shell::process::CommandEvent>) {+fn monitor_backend_output(+ mut rx: tauri::async_runtime::Receiver<tauri_plugin_shell::process::CommandEvent>,+) {tokio::spawn(async move {let mut _startup_detected = false;let mut error_count = 0;@@ -462,14 +485,20 @@ fn monitor_backend_output(mut rx: tauri::async_runtime::Receiver<tauri_plugin_shadd_log(format!("π₯ Backend Error: {}", output_str));// Look for error indicators- if output_str.contains("ERROR") || output_str.contains("Exception") || output_str.contains("FATAL") {+ if output_str.contains("ERROR")+ || output_str.contains("Exception")+ || output_str.contains("FATAL")+ {error_count += 1;add_log(format!("β οΈ Backend error #{}: {}", error_count, output_str));}// Look for specific common issuesif output_str.contains("Address already in use") {- add_log("π¨ CRITICAL: Port 8080 is already in use by another process!".to_string());+ add_log(+ "π¨ CRITICAL: Port 8080 is already in use by another process!"+ .to_string(),+ );}if output_str.contains("java.lang.ClassNotFoundException") {add_log("π¨ CRITICAL: Missing Java dependencies!".to_string());@@ -482,7 +511,10 @@ fn monitor_backend_output(mut rx: tauri::async_runtime::Receiver<tauri_plugin_shadd_log(format!("β Backend process error: {}", error));}tauri_plugin_shell::process::CommandEvent::Terminated(payload) => {- add_log(format!("π Backend terminated with code: {:?}", payload.code));+ add_log(format!(+ "π Backend terminated with code: {:?}",+ payload.code+ ));if let Some(code) = payload.code {match code {0 => println!("β Process terminated normally"),@@ -506,7 +538,10 @@ fn monitor_backend_output(mut rx: tauri::async_runtime::Receiver<tauri_plugin_sh}if error_count > 0 {- println!("β οΈ Backend process ended with {} errors detected", error_count);+ println!(+ "β οΈ Backend process ended with {} errors detected",+ error_count+ );}});}@@ -517,7 +552,9 @@ pub async fn start_backend(app: tauri::AppHandle,connection_state: tauri::State<'_, AppConnectionState>,) -> Result<String, String> {- add_log("π start_backend() called - Attempting to start backend with bundled JRE...".to_string());+ add_log(+ "π start_backend() called - Attempting to start backend with bundled JRE...".to_string(),+ );// Check connection modelet mode = {@@ -557,8 +594,7 @@ pub async fn start_backend(add_log(format!("π Resource directory: {:?}", resource_dir));// Find the bundled JRE- let java_executable =- find_bundled_jre(&resource_dir).inspect_err(|_| reset_starting_flag())?;+ let java_executable = find_bundled_jre(&resource_dir).inspect_err(|_| reset_starting_flag())?;// Find the Stirling-PDF JARlet jar_path = find_stirling_jar(&resource_dir).inspect_err(|_| reset_starting_flag())?;@@ -569,7 +605,10 @@ pub async fn start_backend(add_log(format!("π¦ Found JAR file: {:?}", jar_path));add_log(format!("π¦ Normalized JAR path: {:?}", normalized_jar_path));- add_log(format!("π¦ Normalized Java path: {:?}", normalized_java_path));+ add_log(format!(+ "π¦ Normalized Java path: {:?}",+ normalized_java_path+ ));// Create and start the Java commandrun_stirling_pdf_jar(&app, &normalized_java_path, &normalized_jar_path)@@ -594,7 +633,10 @@ pub fn cleanup_backend() {let child = BACKEND_PROCESS.lock().unwrap().take();let Some(child) = child else { return };let pid = child.pid();- add_log(format!("App shutting down, stopping backend (PID: {})", pid));+ add_log(format!(+ "App shutting down, stopping backend (PID: {})",+ pid+ ));if let Some(path) = BACKEND_SHUTDOWN_FILE.lock().unwrap().clone() {if let Err(e) = std::fs::write(&path, b"stop") {@@ -610,7 +652,10 @@ pub fn cleanup_backend() {if BACKEND_EXITED.load(Ordering::Acquire) {add_log(format!("Backend (PID: {}) stopped gracefully", pid));} else {- add_log(format!("Backend (PID: {}) did not stop in time, killing", pid));+ add_log(format!(+ "Backend (PID: {}) did not stop in time, killing",+ pid+ ));let _ = child.kill();}}diff --git a/frontend/src-tauri/src/commands/default_app.rs b/frontend/src-tauri/src/commands/default_app.rsindex 1ca4e0c004..e9ff0baf9a 100644--- a/frontend/src-tauri/src/commands/default_app.rs+++ b/frontend/src-tauri/src/commands/default_app.rs@@ -55,8 +55,8 @@ fn check_default_windows() -> Result<bool, String> {COINIT_APARTMENTTHREADED,};use windows::Win32::UI::Shell::{- IApplicationAssociationRegistration, ApplicationAssociationRegistration,- ASSOCIATIONTYPE, ASSOCIATIONLEVEL,+ ApplicationAssociationRegistration, IApplicationAssociationRegistration, ASSOCIATIONLEVEL,+ ASSOCIATIONTYPE,};unsafe {@@ -69,22 +69,27 @@ fn check_default_windows() -> Result<bool, String> {let result = (|| -> Result<bool, String> {// Create the IApplicationAssociationRegistration instance- let reg: IApplicationAssociationRegistration =- CoCreateInstance(&ApplicationAssociationRegistration, None, CLSCTX_INPROC_SERVER)- .map_err(|e| format!("Failed to create COM instance: {}", e))?;+ let reg: IApplicationAssociationRegistration = CoCreateInstance(+ &ApplicationAssociationRegistration,+ None,+ CLSCTX_INPROC_SERVER,+ )+ .map_err(|e| format!("Failed to create COM instance: {}", e))?;// Query the current default handler for .pdf extensionlet extension = HSTRING::from(".pdf");- let default_app = reg.QueryCurrentDefault(- &extension,- ASSOCIATIONTYPE(0), // AT_FILEEXTENSION- ASSOCIATIONLEVEL(1), // AL_EFFECTIVE - gets the effective default (user or machine level)- )- .map_err(|e| format!("Failed to query current default: {}", e))?;+ let default_app = reg+ .QueryCurrentDefault(+ &extension,+ ASSOCIATIONTYPE(0), // AT_FILEEXTENSION+ ASSOCIATIONLEVEL(1), // AL_EFFECTIVE - gets the effective default (user or machine level)+ )+ .map_err(|e| format!("Failed to query current default: {}", e))?;// Convert PWSTR to String- let default_str = default_app.to_string()+ let default_str = default_app+ .to_string().map_err(|e| format!("Failed to convert default app string: {}", e))?;add_log(format!("Windows PDF handler ProgID: {}", default_str));@@ -148,7 +153,8 @@ fn check_default_macos() -> Result<bool, String> {unsafe {// Query the default handler for "com.adobe.pdf" (PDF UTI - standard macOS identifier)let pdf_uti = CFString::new("com.adobe.pdf");- let handler_ref = LSCopyDefaultRoleHandlerForContentType(pdf_uti.as_concrete_TypeRef(), K_LS_ROLES_ALL);+ let handler_ref =+ LSCopyDefaultRoleHandlerForContentType(pdf_uti.as_concrete_TypeRef(), K_LS_ROLES_ALL);if handler_ref.is_null() {add_log("No default PDF handler found".to_string());@@ -214,8 +220,7 @@ fn set_default_macos() -> Result<String, String> {/// Installed desktop entry names vary by packaging (template vs binary name).#[cfg(target_os = "linux")]-const LINUX_DESKTOP_CANDIDATES: &[&str] =- &["Stirling-PDF.desktop", "stirling-pdf.desktop"];+const LINUX_DESKTOP_CANDIDATES: &[&str] = &["Stirling-PDF.desktop", "stirling-pdf.desktop"];#[cfg(target_os = "linux")]fn is_stirling_desktop_handler(handler: &str) -> bool {diff --git a/frontend/src-tauri/src/commands/mod.rs b/frontend/src-tauri/src/commands/mod.rsindex ad985f716e..48bb1dc0d6 100644--- a/frontend/src-tauri/src/commands/mod.rs+++ b/frontend/src-tauri/src/commands/mod.rs@@ -1,9 +1,9 @@+pub mod auth;pub mod backend;-pub mod files;-pub mod file_drop;pub mod connection;-pub mod auth;pub mod default_app;+pub mod file_drop;+pub mod files;pub mod local_proxy;pub mod platform;pub mod print;@@ -11,42 +11,19 @@ pub mod updater;pub mod watcher;pub mod window;-pub use backend::{cleanup_backend, get_backend_port, start_backend};-pub use files::{- add_opened_file, clear_opened_files, file_disk_state, get_opened_files, pop_opened_files,-};-pub use watcher::{release_window_watches, unwatch_disk_paths, watch_disk_paths};-pub use window::{- build_main_window,- forward_files_to_window,- open_files_in_new_window,- open_in_new_window,- pop_window_file_ids,- target_window_label,- MAIN_WINDOW_LABEL,+pub use auth::{+ clear_auth_token, clear_refresh_token, clear_user_info, get_auth_token, get_refresh_token,+ get_user_info, login, save_auth_token, save_refresh_token, save_user_info, start_oauth_login,};+pub use backend::{cleanup_backend, get_backend_port, start_backend};pub use connection::{- get_connection_config,- get_update_mode,- is_first_launch,- reset_setup_completion,- set_connection_mode,- set_update_mode,-};-pub use auth::{- clear_auth_token,- clear_refresh_token,- clear_user_info,- get_auth_token,- get_refresh_token,- get_user_info,- login,- save_auth_token,- save_refresh_token,- save_user_info,- start_oauth_login,+ get_connection_config, get_update_mode, is_first_launch, reset_setup_completion,+ set_connection_mode, set_update_mode,};pub use default_app::{is_default_pdf_handler, set_as_default_pdf_handler};+pub use files::{+ add_opened_file, clear_opened_files, file_disk_state, get_opened_files, pop_opened_files,+};pub use local_proxy::proxy_local_pdf_request;pub use platform::get_desktop_os;pub use print::print_pdf_file_native;@@ -54,3 +31,8 @@ pub use updater::{can_install_updates, check_for_update, download_and_install_update, get_app_version,restart_app,};+pub use watcher::{release_window_watches, unwatch_disk_paths, watch_disk_paths};+pub use window::{+ build_main_window, forward_files_to_window, open_files_in_new_window, open_in_new_window,+ pop_window_file_ids, target_window_label, MAIN_WINDOW_LABEL,+};diff --git a/frontend/src-tauri/src/commands/print.rs b/frontend/src-tauri/src/commands/print.rsindex dad46c645c..26ae48c50b 100644--- a/frontend/src-tauri/src/commands/print.rs+++ b/frontend/src-tauri/src/commands/print.rs@@ -11,7 +11,11 @@ mod macos {use tauri::AppHandle;#[tauri::command]- pub fn print_pdf_file_native(app: AppHandle, file_path: String, title: Option<String>) -> Result<(), String> {+ pub fn print_pdf_file_native(+ app: AppHandle,+ file_path: String,+ title: Option<String>,+ ) -> Result<(), String> {if !Path::new(&file_path).exists() {return Err(format!("Print file does not exist: {}", file_path));}@@ -29,13 +33,12 @@ mod macos {let print_info = NSPrintInfo::sharedPrintInfo();let print_operation = unsafe {- document- .printOperationForPrintInfo_scalingMode_autoRotate(- Some(&print_info),- PDFPrintScalingMode::PageScaleDownToFit,- true,- mtm,- )+ document.printOperationForPrintInfo_scalingMode_autoRotate(+ Some(&print_info),+ PDFPrintScalingMode::PageScaleDownToFit,+ true,+ mtm,+ )}.ok_or_else(|| "PDFKit did not create a print operation".to_string())?;@@ -50,11 +53,10 @@ mod macos {});let _ = sender.send(result);- }).map_err(|error| error.to_string())?;+ })+ .map_err(|error| error.to_string())?;- receiver- .recv()- .map_err(|error| error.to_string())?+ receiver.recv().map_err(|error| error.to_string())?}}diff --git a/frontend/src-tauri/src/commands/updater.rs b/frontend/src-tauri/src/commands/updater.rsindex 9afa9a18f4..ba45e1146e 100644--- a/frontend/src-tauri/src/commands/updater.rs+++ b/frontend/src-tauri/src/commands/updater.rs@@ -1,5 +1,5 @@-use std::sync::{Arc, Mutex};use serde::{Deserialize, Serialize};+use std::sync::{Arc, Mutex};use tauri::{AppHandle, Emitter};use tauri_plugin_updater::UpdaterExt;@@ -52,14 +52,20 @@ pub async fn check_for_update(app: AppHandle) -> Result<Option<UpdateInfo>, Strilet updater = match app.updater() {Ok(u) => u,Err(e) => {- add_log(format!("β οΈ Updater not available (plugin not configured?): {}", e));+ add_log(format!(+ "β οΈ Updater not available (plugin not configured?): {}",+ e+ ));return Ok(None);}};match updater.check().await {Ok(Some(update)) => {- add_log(format!("β Update available: {} β {}", current_version, update.version));+ add_log(format!(+ "β Update available: {} β {}",+ current_version, update.version+ ));Ok(Some(UpdateInfo {version: update.version.clone(),current_version,diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rsindex 7479c389df..8a48fe4c4e 100644--- a/frontend/src-tauri/src/lib.rs+++ b/frontend/src-tauri/src/lib.rs@@ -2,106 +2,70 @@ use tauri::{AppHandle, Emitter, Manager, RunEvent, WindowEvent};use tauri_plugin_dialog::{DialogExt, MessageDialogKind};use tauri_plugin_window_state::StateFlags;-mod utils;pub mod commands;-mod state;mod directory_drop;+mod state;+mod utils;+use commands::connection::apply_provisioning_if_present;use commands::{- add_opened_file,- cleanup_backend,- clear_auth_token,- clear_opened_files,- clear_refresh_token,- clear_user_info,- file_disk_state,- forward_files_to_window,- is_default_pdf_handler,- get_auth_token,- get_backend_port,- get_connection_config,- get_opened_files,- open_files_in_new_window,- open_in_new_window,- pop_opened_files,- pop_window_file_ids,- release_window_watches,- unwatch_disk_paths,- watch_disk_paths,- get_refresh_token,- get_user_info,- is_first_launch,- login,- proxy_local_pdf_request,- reset_setup_completion,- save_auth_token,- save_refresh_token,- save_user_info,- set_connection_mode,- set_as_default_pdf_handler,- get_desktop_os,- get_update_mode,- print_pdf_file_native,- set_update_mode,- start_backend,- start_oauth_login,- can_install_updates,- check_for_update,- download_and_install_update,- get_app_version,- restart_app,- target_window_label,- build_main_window,- MAIN_WINDOW_LABEL,+ add_opened_file, build_main_window, can_install_updates, check_for_update, cleanup_backend,+ clear_auth_token, clear_opened_files, clear_refresh_token, clear_user_info,+ download_and_install_update, file_disk_state, forward_files_to_window, get_app_version,+ get_auth_token, get_backend_port, get_connection_config, get_desktop_os, get_opened_files,+ get_refresh_token, get_update_mode, get_user_info, is_default_pdf_handler, is_first_launch,+ login, open_files_in_new_window, open_in_new_window, pop_opened_files, pop_window_file_ids,+ print_pdf_file_native, proxy_local_pdf_request, release_window_watches, reset_setup_completion,+ restart_app, save_auth_token, save_refresh_token, save_user_info, set_as_default_pdf_handler,+ set_connection_mode, set_update_mode, start_backend, start_oauth_login, target_window_label,+ unwatch_disk_paths, watch_disk_paths, MAIN_WINDOW_LABEL,};-use commands::connection::apply_provisioning_if_present;use state::connection_state::AppConnectionState;-use utils::{add_log, get_tauri_logs};use tauri_plugin_deep_link::DeepLinkExt;+use utils::{add_log, get_tauri_logs};fn dispatch_deep_link(app: &AppHandle, url: &str) {- add_log(format!("π Dispatching deep link: {}", url));- let _ = app.emit("deep-link", url.to_string());+ add_log(format!("π Dispatching deep link: {}", url));+ let _ = app.emit("deep-link", url.to_string());- if let Some(window) = app.get_webview_window("main") {- let _ = window.set_focus();- let _ = window.unminimize();- }+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ let _ = window.unminimize();+ }}// Extract existing file paths from CLI args (skips the executable name).fn parse_launch_files(args: &[String]) -> Vec<String> {- args- .iter()- .skip(1)- .filter(|arg| std::path::Path::new(arg).exists())- .cloned()- .collect()+ args.iter()+ .skip(1)+ .filter(|arg| std::path::Path::new(arg).exists())+ .cloned()+ .collect()}// URLs the webview is allowed to show: the bundled app and dev server only.// Anything else (file://, https://...) must never replace the app UI.fn is_app_url(url: &tauri::Url) -> bool {- match url.scheme() {- "tauri" | "about" | "blob" | "data" => true,- "http" | "https" => matches!(- url.host_str(),- Some("tauri.localhost") | Some("localhost") | Some("127.0.0.1")- ),- _ => false,- }+ match url.scheme() {+ "tauri" | "about" | "blob" | "data" => true,+ "http" | "https" => matches!(+ url.host_str(),+ Some("tauri.localhost") | Some("localhost") | Some("127.0.0.1")+ ),+ _ => false,+ }}#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {- // WebKitGTK's DMA-BUF renderer crashes the web process on NVIDIA and some- // Wayland stacks (blank window, app dying on tool switch). Opt out unless overridden.- #[cfg(target_os = "linux")]- if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() {- std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");- }+ // WebKitGTK's DMA-BUF renderer crashes the web process on NVIDIA and some+ // Wayland stacks (blank window, app dying on tool switch). Opt out unless overridden.+ #[cfg(target_os = "linux")]+ if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() {+ std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");+ }- tauri::Builder::default()+ tauri::Builder::default().plugin(// Dropping a file outside a dropzone makes WebKit navigate the webview to// that file, killing the app UI and its close handler (window becomes@@ -357,36 +321,36 @@ pub fn run() {#[cfg(test)]mod tests {- use super::is_app_url;+ use super::is_app_url;- fn allows(raw: &str) -> bool {- is_app_url(&tauri::Url::parse(raw).expect("valid url"))- }+ fn allows(raw: &str) -> bool {+ is_app_url(&tauri::Url::parse(raw).expect("valid url"))+ }- #[test]- fn allows_bundled_app_and_dev_server() {- assert!(allows("tauri://localhost/index.html"));- assert!(allows("http://tauri.localhost/"));- assert!(allows("http://localhost:5173/"));- assert!(allows("http://127.0.0.1:8080/api"));- assert!(allows("about:blank"));- assert!(allows("blob:http://localhost:5173/abc"));- assert!(allows("data:text/html,hi"));- }+ #[test]+ fn allows_bundled_app_and_dev_server() {+ assert!(allows("tauri://localhost/index.html"));+ assert!(allows("http://tauri.localhost/"));+ assert!(allows("http://localhost:5173/"));+ assert!(allows("http://127.0.0.1:8080/api"));+ assert!(allows("about:blank"));+ assert!(allows("blob:http://localhost:5173/abc"));+ assert!(allows("data:text/html,hi"));+ }- #[test]- fn blocks_dropped_files() {- // The #6872 lockup: webview navigating to a dropped PDF.- assert!(!allows("file:///C:/Users/me/report.pdf"));- assert!(!allows("file:///home/me/report.pdf"));- }+ #[test]+ fn blocks_dropped_files() {+ // The #6872 lockup: webview navigating to a dropped PDF.+ assert!(!allows("file:///C:/Users/me/report.pdf"));+ assert!(!allows("file:///home/me/report.pdf"));+ }- #[test]- fn blocks_remote_origins() {- assert!(!allows("https://example.com/"));- assert!(!allows("http://evil.test/"));- // Look-alike hosts must not slip past the allowlist.- assert!(!allows("https://localhost.evil.test/"));- assert!(!allows("https://nottauri.localhost.evil.test/"));- }+ #[test]+ fn blocks_remote_origins() {+ assert!(!allows("https://example.com/"));+ assert!(!allows("http://evil.test/"));+ // Look-alike hosts must not slip past the allowlist.+ assert!(!allows("https://localhost.evil.test/"));+ assert!(!allows("https://nottauri.localhost.evil.test/"));+ }}diff --git a/frontend/src-tauri/src/main.rs b/frontend/src-tauri/src/main.rsindex ad5fe83991..69c3a72ec5 100644--- a/frontend/src-tauri/src/main.rs+++ b/frontend/src-tauri/src/main.rs@@ -2,5 +2,5 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]fn main() {- app_lib::run();+ app_lib::run();}diff --git a/frontend/src-tauri/src/utils/logging.rs b/frontend/src-tauri/src/utils/logging.rsindex bda1913ad1..dbc510ef4e 100644--- a/frontend/src-tauri/src/utils/logging.rs+++ b/frontend/src-tauri/src/utils/logging.rs@@ -1,8 +1,8 @@-use std::sync::Mutex;use std::collections::VecDeque;use std::fs::OpenOptions;use std::io::Write;use std::path::PathBuf;+use std::sync::Mutex;// Store backend logs globallystatic BACKEND_LOGS: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());@@ -12,15 +12,22 @@ fn get_log_directory() -> PathBuf {if cfg!(target_os = "macos") {// macOS: ~/Library/Logs/Stirling-PDFlet home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());- PathBuf::from(home).join("Library").join("Logs").join("Stirling-PDF")+ PathBuf::from(home)+ .join("Library")+ .join("Logs")+ .join("Stirling-PDF")} else if cfg!(target_os = "windows") {// Windows: %APPDATA%\Stirling-PDF\logs- let appdata = std::env::var("APPDATA").unwrap_or_else(|_| std::env::temp_dir().to_string_lossy().to_string());+ let appdata = std::env::var("APPDATA")+ .unwrap_or_else(|_| std::env::temp_dir().to_string_lossy().to_string());PathBuf::from(appdata).join("Stirling-PDF").join("logs")} else {// Linux: ~/.config/Stirling-PDF/logslet home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());- PathBuf::from(home).join(".config").join("Stirling-PDF").join("logs")+ PathBuf::from(home)+ .join(".config")+ .join("Stirling-PDF")+ .join("logs")}}@@ -30,9 +37,9 @@ pub fn add_log(message: String) {.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();-+let log_entry = format!("{}: {}", timestamp, message);-+// Add to memory logs{let mut logs = BACKEND_LOGS.lock().unwrap();@@ -42,10 +49,10 @@ pub fn add_log(message: String) {logs.pop_front();}}-+// Write to filewrite_to_log_file(&log_entry);-+// Remove trailing newline if presentlet clean_message = message.trim_end_matches('\n').to_string();println!("{}", clean_message); // Also print to console@@ -58,14 +65,10 @@ fn write_to_log_file(log_entry: &str) {eprintln!("Failed to create log directory: {}", e);return;}-+let log_file = log_dir.join("tauri-backend.log");-- match OpenOptions::new()- .create(true)- .append(true)- .open(&log_file)- {++ match OpenOptions::new().create(true).append(true).open(&log_file) {Ok(mut file) => {if let Err(e) = writeln!(file, "{}", log_entry) {eprintln!("Failed to write to log file: {}", e);@@ -87,4 +90,4 @@ pub fn get_logs() -> Vec<String> {#[tauri::command]pub async fn get_tauri_logs() -> Result<Vec<String>, String> {Ok(get_logs())-}\ No newline at end of file+}diff --git a/frontend/src-tauri/src/utils/paths.rs b/frontend/src-tauri/src/utils/paths.rsindex e0e5b1547a..e05d58e528 100644--- a/frontend/src-tauri/src/utils/paths.rs+++ b/frontend/src-tauri/src/utils/paths.rs@@ -22,7 +22,11 @@ pub fn system_provisioning_dir() -> Option<PathBuf> {let program_data = std::env::var("PROGRAMDATA").ok()?;Some(PathBuf::from(program_data).join("Stirling-PDF"))} else if cfg!(target_os = "macos") {- Some(PathBuf::from("/Library").join("Application Support").join("Stirling-PDF"))+ Some(+ PathBuf::from("/Library")+ .join("Application Support")+ .join("Stirling-PDF"),+ )} else if cfg!(target_os = "linux") {Some(PathBuf::from("/etc").join("stirling-pdf"))} else {diff --git a/frontend/src-tauri/thumbnail-handler/src/lib.rs b/frontend/src-tauri/thumbnail-handler/src/lib.rsindex 1649321bd2..34a53c8c7f 100644--- a/frontend/src-tauri/thumbnail-handler/src/lib.rs+++ b/frontend/src-tauri/thumbnail-handler/src/lib.rs@@ -23,16 +23,16 @@ use windows::Win32::System::Com::{CoCreateInstance, IClassFactory, IClassFactory_Impl, IStream, CLSCTX_INPROC_SERVER,STATFLAG_DEFAULT, STREAM_SEEK_SET,};-use windows::Win32::UI::Shell::{- IThumbnailProvider, IThumbnailProvider_Impl, SHCreateMemStream, WTS_ALPHATYPE,-};use windows::Win32::UI::Shell::PropertiesSystem::{IInitializeWithStream, IInitializeWithStream_Impl,};+use windows::Win32::UI::Shell::{+ IThumbnailProvider, IThumbnailProvider_Impl, SHCreateMemStream, WTS_ALPHATYPE,+};// WinRT imports for PDF renderinguse windows::Data::Pdf::PdfDocument;-use windows::Storage::Streams::{DataWriter, InMemoryRandomAccessStream, IRandomAccessStream};+use windows::Storage::Streams::{DataWriter, IRandomAccessStream, InMemoryRandomAccessStream};// CLSID for this thumbnail handler -- must match WiX registry entriesconst CLSID_STIRLING_THUMBNAIL: GUID = GUID::from_u128(0x2d2fbe3a_9a88_4308_a52e_7ef63ca7cf48);@@ -67,11 +67,7 @@ impl Drop for ThumbnailProvider {}impl IInitializeWithStream_Impl for ThumbnailProvider_Impl {- fn Initialize(- &self,- pstream: Option<&IStream>,- _grfmode: u32,- ) -> windows::core::Result<()> {+ fn Initialize(&self, pstream: Option<&IStream>, _grfmode: u32) -> windows::core::Result<()> {let result = catch_unwind(std::panic::AssertUnwindSafe(|| {*self.stream.borrow_mut() = pstream.cloned();}));