Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238// 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<std::path::PathBuf> { 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<std::path::PathBuf, ()> { 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<String>) -> Option<std::path::PathBuf> { 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<String>) -> Option<std::path::PathBuf> { resolve_override(over).or_else(|| find_binary(&["soffice"]))}
fn resolve_pandoc(over: &Option<String>) -> Option<std::path::PathBuf> { resolve_override(over).or_else(|| find_binary(&["pandoc"]))}
fn resolve_pdf_engine(over: &Option<String>) -> Option<std::path::PathBuf> { resolve_override(over).or_else(|| PDF_ENGINES.iter().find_map(|name| find_binary(&[name])))}
#[derive(Clone, Serialize)]pub(crate) struct ConverterStatus { soffice: Option<String>, pandoc: Option<String>, pdf_engine: Option<String>,}
#[tauri::command]pub(crate) fn converter_status( soffice_path: Option<String>, pandoc_path: Option<String>, pdf_engine_path: Option<String>,) -> 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<std::path::PathBuf>, pandoc: Option<std::path::PathBuf>, pdf_engine: Option<std::path::PathBuf>,) -> Result<std::path::PathBuf, String> { 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<String>, pandoc_path: Option<String>, pdf_engine_path: Option<String>,) -> Result<String, String> { 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<String>, pandoc_path: Option<String>, pdf_engine_path: Option<String>,) -> Result<String, String> { 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); }}