// On-device document conversion (standalone mode): the same converters the // server uses, found on this machine. LibreOffice for office formats, pandoc // (plus a PDF engine) for markup. Nothing is bundled; binaries are probed from // the usual install locations and a clear error names what to install. use serde::Serialize; const OFFICE_EXTENSIONS: &[&str] = &[ "doc", "docx", "odt", "rtf", "ppt", "pptx", "odp", "xls", "xlsx", "ods", "csv", ]; const PDF_ENGINES: &[&str] = &[ "typst", "tectonic", "weasyprint", "wkhtmltopdf", "xelatex", "lualatex", "pdflatex", ]; // GUI-launched macOS apps get a minimal PATH; probe the usual homes too. fn find_binary(names: &[&str]) -> Option { let dirs = [ "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/Applications/LibreOffice.app/Contents/MacOS", ]; for name in names { if let Ok(path) = which_in_path(name) { return Some(path); } for dir in dirs { let candidate = std::path::Path::new(dir).join(name); if candidate.is_file() { return Some(candidate); } } } None } fn which_in_path(name: &str) -> Result { let path = std::env::var("PATH").map_err(|_| ())?; for dir in std::env::split_paths(&path) { let candidate = dir.join(name); if candidate.is_file() { return Ok(candidate); } } Err(()) } fn run_command(mut cmd: std::process::Command) -> Result<(), String> { let output = cmd.output().map_err(|e| e.to_string())?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); return Err(stderr.chars().take(400).collect()); } Ok(()) } // A user-configured path (Settings > Document conversion) wins when it points at // a real file; otherwise the usual install locations are probed. fn resolve_override(path: &Option) -> Option { path.as_deref() .map(str::trim) .filter(|s| !s.is_empty()) .map(std::path::PathBuf::from) .filter(|p| p.is_file()) } fn resolve_soffice(over: &Option) -> Option { resolve_override(over).or_else(|| find_binary(&["soffice"])) } fn resolve_pandoc(over: &Option) -> Option { resolve_override(over).or_else(|| find_binary(&["pandoc"])) } fn resolve_pdf_engine(over: &Option) -> Option { resolve_override(over).or_else(|| PDF_ENGINES.iter().find_map(|name| find_binary(&[name]))) } #[derive(Clone, Serialize)] pub(crate) struct ConverterStatus { soffice: Option, pandoc: Option, pdf_engine: Option, } #[tauri::command] pub(crate) fn converter_status( soffice_path: Option, pandoc_path: Option, pdf_engine_path: Option, ) -> ConverterStatus { ConverterStatus { soffice: resolve_soffice(&soffice_path).map(|p| p.display().to_string()), pandoc: resolve_pandoc(&pandoc_path).map(|p| p.display().to_string()), pdf_engine: resolve_pdf_engine(&pdf_engine_path).map(|p| p.display().to_string()), } } fn convert_file( input: &std::path::Path, ext: &str, soffice: Option, pandoc: Option, pdf_engine: Option, ) -> Result { let out_dir = input.parent().unwrap().to_path_buf(); if OFFICE_EXTENSIONS.contains(&ext) { let soffice = soffice.ok_or( "LibreOffice was not found on this device; install it or set its path in Settings > Document conversion (or connect a server)", )?; // A throwaway user profile per run: concurrent soffice instances fight // over the default profile lock otherwise. let profile = out_dir.join("soffice-profile"); let mut cmd = std::process::Command::new(soffice); cmd.arg("--headless") .arg("--norestore") .arg(format!("-env:UserInstallation=file://{}", profile.display())) .arg("--convert-to") .arg("pdf") .arg("--outdir") .arg(&out_dir) .arg(input); run_command(cmd)?; } else { let pandoc = pandoc.ok_or( "pandoc was not found on this device; install it or set its path in Settings > Document conversion (or connect a server)", )?; let engine = pdf_engine.ok_or( "pandoc needs a PDF engine (e.g. typst); install one or set its path in Settings > Document conversion (or connect a server)", )?; let mut cmd = std::process::Command::new(pandoc); cmd.arg(input) .arg("-o") .arg(out_dir.join("input.pdf")) .arg(format!("--pdf-engine={}", engine.display())); run_command(cmd)?; } let produced = out_dir.join("input.pdf"); if !produced.is_file() { return Err("the converter did not produce a PDF (unsupported or corrupt file?)".into()); } Ok(produced) } // Conversion shells out to LibreOffice or pandoc, which takes seconds. An // async command runs off the main thread, so the window keeps painting while it // works. #[tauri::command] pub(crate) async fn convert_to_pdf( filename: String, bytes_b64: String, soffice_path: Option, pandoc_path: Option, pdf_engine_path: Option, ) -> Result { tauri::async_runtime::spawn_blocking(move || { convert_to_pdf_blocking(filename, bytes_b64, soffice_path, pandoc_path, pdf_engine_path) }) .await .map_err(|e| e.to_string())? } fn convert_to_pdf_blocking( filename: String, bytes_b64: String, soffice_path: Option, pandoc_path: Option, pdf_engine_path: Option, ) -> Result { use base64::Engine as _; let engine = base64::engine::general_purpose::STANDARD; let bytes = engine.decode(bytes_b64).map_err(|e| e.to_string())?; let ext = std::path::Path::new(&filename) .extension() .and_then(|e| e.to_str()) .unwrap_or("") .to_ascii_lowercase(); if ext.is_empty() { return Err("the file has no extension to convert from".into()); } // Per call, not per process: two concurrent conversions sharing one // directory would delete each other's input and race over the output name. static CALL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let seq = CALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("synapse-convert-{}-{seq}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let input = dir.join(format!("input.{ext}")); std::fs::write(&input, &bytes).map_err(|e| e.to_string())?; let result = convert_file( &input, &ext, resolve_soffice(&soffice_path), resolve_pandoc(&pandoc_path), resolve_pdf_engine(&pdf_engine_path), ) .and_then(|pdf| std::fs::read(pdf).map_err(|e| e.to_string())) .map(|pdf_bytes| engine.encode(pdf_bytes)); let _ = std::fs::remove_dir_all(&dir); result } #[cfg(test)] mod tests { use super::*; // Real conversion through the installed LibreOffice; skipped when the machine // does not have it (CI without office tools). #[test] fn converts_a_docx_like_text_file_to_pdf() { if find_binary(&["soffice"]).is_none() { eprintln!("soffice not installed, skipping"); return; } let dir = std::env::temp_dir().join(format!("synapse-convert-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let input = dir.join("input.txt"); std::fs::write(&input, "Suites et limites: definitions.").unwrap(); // The ext argument picks the branch; soffice converts by file content and // opens plain text fine. let produced = convert_file(&input, "doc", resolve_soffice(&None), None, None) .expect("soffice failed to convert"); let bytes = std::fs::read(produced).unwrap(); assert_eq!(&bytes[0..5], b"%PDF-"); let _ = std::fs::remove_dir_all(&dir); } }