//! Converts meta-affine sequences to SVG visualizations via LilyPond markup. //! //! This library provides a public API for converting structures from the //! morphology crate into SVG images. All LilyPond-specific implementation //! details are kept internal. //! //! # Public API //! //! The primary function is [`sequence_to_markup`] which converts a //! meta-affine `Sequence` directly to a LilyPond markup string. //! //! # Architecture //! //! - **Input**: Only types from the morphology crate (`Sequence`, `Value`) //! - **Output**: File paths or markup strings //! - **Hidden**: All LilyPond-specific types and implementation details pub mod error; #[doc(hidden)] pub mod note; #[doc(hidden)] pub mod template; #[doc(hidden)] pub mod file_gen; #[doc(hidden)] pub mod render; // Public API - only export what external clients should use pub use error::RenderError; pub use note::sequence_to_markup; use std::path::PathBuf; use std::sync::Arc; /// Type alias for progress callback function. /// /// The callback receives: /// - `current`: The number of sequences processed so far (1-indexed) /// - `total`: The total number of sequences to process /// /// # Examples /// /// ```no_run /// use morphology_img::ProgressCallback; /// use std::sync::Arc; /// /// let callback: ProgressCallback = Arc::new(|current, total| { /// println!("Progress: {}/{}", current, total); /// }); /// ``` pub type ProgressCallback = Arc; /// Configuration for rendering sequences to SVGs. /// /// This struct uses the builder pattern to configure how sequences are rendered /// to SVG files using LilyPond. /// /// # Examples /// /// ``` /// use morphology_img::RenderConfig; /// /// // Basic configuration with default settings /// let config = RenderConfig::new("output"); /// /// // Advanced configuration with custom settings /// let config = RenderConfig::new("output") /// .keep_temp_files(true) /// .lilypond_binary("/usr/local/bin/lilypond"); /// ``` #[derive(Clone)] pub struct RenderConfig { /// Directory where SVG files should be created pub output_dir: PathBuf, /// Whether to keep temporary .ly files for debugging pub keep_temp_files: bool, /// Path to the LilyPond binary (default: "lilypond") pub lilypond_binary: PathBuf, /// Optional callback for progress reporting during batch rendering pub progress_callback: Option, } impl std::fmt::Debug for RenderConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("RenderConfig") .field("output_dir", &self.output_dir) .field("keep_temp_files", &self.keep_temp_files) .field("lilypond_binary", &self.lilypond_binary) .field("progress_callback", &self.progress_callback.as_ref().map(|_| "")) .finish() } } impl Default for RenderConfig { fn default() -> Self { Self { output_dir: PathBuf::from("output"), keep_temp_files: false, lilypond_binary: PathBuf::from("lilypond"), progress_callback: None, } } } impl RenderConfig { /// Creates a new RenderConfig with the specified output directory. /// /// All other settings use their default values: /// - `keep_temp_files`: false /// - `lilypond_binary`: "lilypond" /// /// # Examples /// /// ``` /// use morphology_img::RenderConfig; /// /// let config = RenderConfig::new("my-output"); /// assert_eq!(config.output_dir.to_str().unwrap(), "my-output"); /// ``` pub fn new(output_dir: impl Into) -> Self { Self { output_dir: output_dir.into(), ..Default::default() } } /// Sets whether to keep temporary .ly files for debugging. /// /// By default, temporary files are automatically cleaned up. Setting this /// to `true` will preserve them for inspection. /// /// # Examples /// /// ``` /// use morphology_img::RenderConfig; /// /// let config = RenderConfig::new("output") /// .keep_temp_files(true); /// /// assert!(config.keep_temp_files); /// ``` pub fn keep_temp_files(mut self, keep: bool) -> Self { self.keep_temp_files = keep; self } /// Sets the path to the LilyPond binary. /// /// By default, this is "lilypond", which will be found in the system PATH. /// Use this method to specify a custom path to the LilyPond executable. /// /// # Examples /// /// ``` /// use morphology_img::RenderConfig; /// /// let config = RenderConfig::new("output") /// .lilypond_binary("/usr/local/bin/lilypond"); /// /// assert_eq!(config.lilypond_binary.to_str().unwrap(), "/usr/local/bin/lilypond"); /// ``` pub fn lilypond_binary(mut self, path: impl Into) -> Self { self.lilypond_binary = path.into(); self } /// Sets a progress callback for batch rendering. /// /// The callback will be called after each sequence is rendered, allowing /// you to track progress for large batches. /// /// # Examples /// /// ``` /// use morphology_img::RenderConfig; /// use std::sync::Arc; /// /// let config = RenderConfig::new("output") /// .progress_callback(Arc::new(|current, total| { /// println!("Rendered {}/{} sequences", current, total); /// })); /// ``` pub fn progress_callback(mut self, callback: ProgressCallback) -> Self { self.progress_callback = Some(callback); self } } /// Renders multiple sequences to SVG files. /// /// This is the main public API for converting meta-affine sequences into /// SVG visualizations using LilyPond. The function handles the complete pipeline: /// 1. Creates temporary directory for .ly files /// 2. Writes LilyPond support files (.ily) /// 3. Generates .ly files from sequences /// 4. Invokes LilyPond to render SVGs /// 5. Cleans up temporary files (unless configured to keep them) /// /// # Arguments /// - `sequences`: The meta-affine sequences to render /// - `config`: Configuration for output directory, LilyPond binary, etc. /// /// # Returns /// Vector of paths to generated SVG files, in the same order as input sequences /// /// # Errors /// - `RenderError::FileIO` if directories cannot be created or files cannot be written /// - `RenderError::LilyPondNotFound` if LilyPond is not available /// - `RenderError::LilyPondExecution` if LilyPond fails to render any sequence /// - `RenderError::Template` if template processing fails /// /// # Examples /// /// ```no_run /// use morphology::{Sequence, Value}; /// use morphology_img::{render_sequences, RenderConfig}; /// /// // Create some sequences /// let sequences = vec![ /// Sequence::new(vec![Value::origin()]), /// Sequence::new(vec![Value::new(1, 0)]), /// ]; /// /// // Configure rendering /// let config = RenderConfig::new("output"); /// /// // Render to SVGs /// let svg_paths = render_sequences(&sequences, &config).unwrap(); /// println!("Generated {} SVG files", svg_paths.len()); /// ``` /// /// # Advanced Configuration /// /// ```no_run /// use morphology::{Sequence, Value}; /// use morphology_img::{render_sequences, RenderConfig}; /// /// let sequences = vec![Sequence::new(vec![Value::origin()])]; /// /// // Keep temporary .ly files for debugging /// let config = RenderConfig::new("output") /// .keep_temp_files(true) /// .lilypond_binary("/usr/local/bin/lilypond"); /// /// let svg_paths = render_sequences(&sequences, &config).unwrap(); /// ``` pub fn render_sequences( sequences: &[morphology::Sequence], config: &RenderConfig, ) -> Result, RenderError> { // Check if LilyPond is available before doing any work render::check_lilypond_available()?; // Create temporary directory for .ly files let temp_dir = file_gen::create_temp_dir()?; // Write support files (.ily) to temp directory file_gen::write_support_files(temp_dir.path())?; // Generate .ly files from sequences let ly_files = file_gen::generate_ly_files(sequences, temp_dir.path())?; // Render .ly files to SVGs let svg_paths = render::render_ly_files_to_svg( &ly_files, &config.output_dir, &config.lilypond_binary, config.progress_callback.as_ref(), )?; // Handle temp directory cleanup if config.keep_temp_files { // Persist the temp directory by keeping it let temp_path = temp_dir.keep(); eprintln!("Temporary files kept at: {}", temp_path.display()); } // Otherwise, temp_dir will be automatically dropped and cleaned up Ok(svg_paths) }