// LilyPond CLI invocation for SVG generation use std::process::Command; use std::path::{Path, PathBuf}; use std::fs; use crate::error::RenderError; /// Checks if LilyPond is available on the system. /// /// This function attempts to run `lilypond --version` to detect if LilyPond /// is installed and accessible in the system PATH. /// /// # Returns /// - `Ok(version_string)` if LilyPond is found and responds successfully /// - `Err(RenderError::LilyPondNotFound)` if LilyPond is not found or fails to execute /// /// # Examples /// ```no_run /// use morphology_img::render::check_lilypond_available; /// /// match check_lilypond_available() { /// Ok(version) => println!("LilyPond is available: {}", version), /// Err(e) => eprintln!("LilyPond not found: {}", e), /// } /// ``` /// /// # Installation Instructions /// If LilyPond is not found, install it from: /// - **macOS**: `brew install lilypond` /// - **Ubuntu/Debian**: `sudo apt-get install lilypond` /// - **Windows**: Download from pub fn check_lilypond_available() -> Result { let output = Command::new("lilypond") .arg("--version") .output(); match output { Ok(output) => { if output.status.success() { let version = String::from_utf8_lossy(&output.stdout); Ok(version.lines().next().unwrap_or("Unknown version").to_string()) } else { Err(RenderError::LilyPondNotFound( "LilyPond command failed".to_string() )) } } Err(e) => { Err(RenderError::LilyPondNotFound( format!("LilyPond not found in PATH: {}. Please install LilyPond from https://lilypond.org", e) )) } } } /// Renders multiple .ly files to SVGs by calling LilyPond once with all files. /// /// This function invokes LilyPond with all .ly files as arguments in a single command, /// which is significantly more efficient than calling LilyPond separately for each file. /// It eliminates process startup overhead and allows the OS to handle scheduling optimally. /// /// # Arguments /// - `ly_files`: Paths to the .ly files to render /// - `output_dir`: Directory where SVGs should be created /// - `lilypond_binary`: Path to the LilyPond binary (typically "lilypond") /// /// # Returns /// Vector of paths to generated SVG files, in the same order as input /// /// # Errors /// - `RenderError::FileIO` if the output directory cannot be created /// - `RenderError::LilyPondExecution` if LilyPond fails to execute or produce output /// - `RenderError::Template` if any .ly filename is invalid /// /// # Examples /// ```no_run /// use morphology_img::render::render_all_ly_files_batch; /// use std::path::{Path, PathBuf}; /// /// let ly_files = vec![ /// PathBuf::from("/tmp/sequence-0.ly"), /// PathBuf::from("/tmp/sequence-1.ly"), /// ]; /// let output_dir = Path::new("output"); /// let lilypond = Path::new("lilypond"); /// /// let svg_paths = render_all_ly_files_batch(&ly_files, output_dir, lilypond).unwrap(); /// println!("Generated {} SVG files", svg_paths.len()); /// ``` /// /// # Performance Notes /// - All files are processed in a single LilyPond invocation /// - Much faster than sequential individual file processing /// - Optimal for batches of any size pub fn render_all_ly_files_batch( ly_files: &[PathBuf], output_dir: &Path, lilypond_binary: &Path, ) -> Result, RenderError> { // Handle empty input if ly_files.is_empty() { return Ok(Vec::new()); } // Ensure output directory exists fs::create_dir_all(output_dir)?; // Get the directory containing the .ly files (should all be in same temp dir) let ly_dir = ly_files[0] .parent() .ok_or_else(|| RenderError::Template("Invalid .ly file path".to_string()))?; // Build command: lilypond --svg file1.ly file2.ly file3.ly ... // WITHOUT -o flag, so SVGs are created next to .ly files with correct names let output = Command::new(lilypond_binary) .arg("--svg") .args(ly_files) .current_dir(ly_dir) // Run in the temp directory .output()?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); return Err(RenderError::LilyPondExecution(stderr.to_string())); } // Copy SVG files from temp directory to output directory let mut svg_paths = Vec::with_capacity(ly_files.len()); for ly_file in ly_files.iter() { let svg_filename = ly_file .file_stem() .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))? .to_string_lossy() .to_string() + ".svg"; // SVG was created next to the .ly file in temp directory let temp_svg_path = ly_dir.join(&svg_filename); // Verify the SVG was created if !temp_svg_path.exists() { return Err(RenderError::LilyPondExecution( format!("Expected SVG not created: {}", temp_svg_path.display()) )); } // Copy to output directory (can't use rename - may be different filesystem) let final_svg_path = output_dir.join(&svg_filename); fs::copy(&temp_svg_path, &final_svg_path)?; svg_paths.push(final_svg_path); } Ok(svg_paths) }