diff options
Diffstat (limited to 'morphology-img/src')
| -rw-r--r-- | morphology-img/src/file_gen.rs | 179 | ||||
| -rw-r--r-- | morphology-img/src/lib.rs | 197 | ||||
| -rw-r--r-- | morphology-img/src/render.rs | 180 | ||||
| -rw-r--r-- | morphology-img/src/template.rs | 52 |
4 files changed, 608 insertions, 0 deletions
diff --git a/morphology-img/src/file_gen.rs b/morphology-img/src/file_gen.rs index c429719..edeeeeb 100644 --- a/morphology-img/src/file_gen.rs +++ b/morphology-img/src/file_gen.rs @@ -1 +1,180 @@ // .ly file generation and temp directory management + +use std::path::{Path, PathBuf}; +use std::fs; +use tempfile::TempDir; +use morphology::Sequence; +use crate::error::RenderError; +use crate::template; +use crate::note::{sequence_to_notes, notes_to_markup}; + +/// Generates a filename for a sequence with proper zero-padding. +/// +/// The padding width is determined by the total number of sequences, +/// ensuring that all filenames sort correctly in lexicographic order. +/// +/// # Arguments +/// - `index`: The sequence index (0-based) +/// - `total_count`: Total number of sequences (used to determine padding) +/// +/// # Examples +/// ``` +/// use morphology_img::file_gen::generate_filename; +/// +/// assert_eq!(generate_filename(0, 10).to_str().unwrap(), "sequence-00.ly"); +/// assert_eq!(generate_filename(5, 10).to_str().unwrap(), "sequence-05.ly"); +/// assert_eq!(generate_filename(42, 1000).to_str().unwrap(), "sequence-0042.ly"); +/// ``` +pub fn generate_filename(index: usize, total_count: usize) -> PathBuf { + let width = total_count.to_string().len(); + PathBuf::from(format!("sequence-{:0width$}.ly", index, width = width)) +} + +/// Creates a temporary directory for .ly files. +/// +/// The directory will be automatically cleaned up when the TempDir is dropped, +/// unless explicitly persisted using `TempDir::into_path()`. +/// +/// # Returns +/// A TempDir handle that manages cleanup +/// +/// # Errors +/// Returns `RenderError::FileIO` if the temporary directory cannot be created +pub fn create_temp_dir() -> Result<TempDir, RenderError> { + TempDir::new().map_err(RenderError::from) +} + +/// Writes the .ily support files to the specified directory. +/// +/// This function writes the three LilyPond include files that are referenced +/// by the main template: +/// - `format.ily`: Format definitions +/// - `entry.ily`: Entry block definitions +/// - `elements.ily`: Element definitions +/// +/// # Arguments +/// - `dir`: The directory to write files to +/// +/// # Returns +/// Ok(()) on success +/// +/// # Errors +/// Returns `RenderError::FileIO` if any file cannot be written +pub fn write_support_files(dir: &Path) -> Result<(), RenderError> { + let files = [ + ("format.ily", template::get_format_ily()), + ("entry.ily", template::get_entry_ily()), + ("elements.ily", template::get_elements_ily()), + ]; + + for (filename, content) in files { + let path = dir.join(filename); + fs::write(&path, content)?; + } + + Ok(()) +} + +/// Generates a .ly file for a single sequence. +/// +/// This function performs the complete transformation pipeline: +/// 1. Convert sequence to notes +/// 2. Convert notes to markup string +/// 3. Substitute markup into template +/// 4. Write the complete .ly file to the specified path +/// +/// # Arguments +/// - `sequence`: The meta-affine sequence to render +/// - `output_path`: Path where the .ly file should be written +/// +/// # Returns +/// Ok(()) on success +/// +/// # Errors +/// - `RenderError::Template` if template substitution fails +/// - `RenderError::FileIO` if file cannot be written +/// +/// # Examples +/// ```no_run +/// use morphology::{Sequence, Value}; +/// use morphology_img::file_gen::{generate_ly_file, create_temp_dir}; +/// use std::path::Path; +/// +/// let seq = Sequence::new(vec![Value::origin()]); +/// let temp_dir = create_temp_dir().unwrap(); +/// let output_path = temp_dir.path().join("test.ly"); +/// +/// generate_ly_file(&seq, &output_path).unwrap(); +/// assert!(output_path.exists()); +/// ``` +pub fn generate_ly_file( + sequence: &Sequence, + output_path: &Path, +) -> Result<(), RenderError> { + // Convert sequence to notes + let notes = sequence_to_notes(sequence); + + // Convert notes to markup string + let markup = notes_to_markup(¬es); + + // Substitute into template + let ly_content = template::substitute_template(&markup)?; + + // Write to file (UTF-8) + fs::write(output_path, ly_content)?; + + Ok(()) +} + +/// Generates .ly files for multiple sequences in a specified directory. +/// +/// This function generates numbered .ly files for each sequence in the input, +/// with filenames automatically padded based on the total count. +/// +/// # Arguments +/// - `sequences`: The sequences to generate files for +/// - `temp_dir`: The directory to write files to +/// +/// # Returns +/// A vector of paths to the generated .ly files, in the same order as input +/// +/// # Errors +/// - `RenderError::Template` if template substitution fails +/// - `RenderError::FileIO` if any file cannot be written +/// +/// # Examples +/// ```no_run +/// use morphology::{Sequence, Value}; +/// use morphology_img::file_gen::{generate_ly_files, create_temp_dir}; +/// +/// let sequences = vec![ +/// Sequence::new(vec![Value::origin()]), +/// Sequence::new(vec![Value::new(1, 0)]), +/// ]; +/// +/// let temp_dir = create_temp_dir().unwrap(); +/// let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap(); +/// +/// assert_eq!(paths.len(), 2); +/// for path in paths { +/// assert!(path.exists()); +/// } +/// ``` +pub fn generate_ly_files( + sequences: &[Sequence], + temp_dir: &Path, +) -> Result<Vec<PathBuf>, RenderError> { + let total_count = sequences.len(); + let mut paths = Vec::with_capacity(total_count); + + for (index, sequence) in sequences.iter().enumerate() { + let filename = generate_filename(index, total_count); + let output_path = temp_dir.join(&filename); + + generate_ly_file(sequence, &output_path)?; + + paths.push(output_path); + } + + Ok(paths) +} diff --git a/morphology-img/src/lib.rs b/morphology-img/src/lib.rs index b94bb5c..3ba78f2 100644 --- a/morphology-img/src/lib.rs +++ b/morphology-img/src/lib.rs @@ -32,3 +32,200 @@ 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; + +/// 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(Debug, 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, +} + +impl Default for RenderConfig { + fn default() -> Self { + Self { + output_dir: PathBuf::from("output"), + keep_temp_files: false, + lilypond_binary: PathBuf::from("lilypond"), + } + } +} + +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<PathBuf>) -> 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<PathBuf>) -> Self { + self.lilypond_binary = path.into(); + 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<Vec<PathBuf>, 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, + )?; + + // 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) +} diff --git a/morphology-img/src/render.rs b/morphology-img/src/render.rs index cd5b293..189dd61 100644 --- a/morphology-img/src/render.rs +++ b/morphology-img/src/render.rs @@ -1 +1,181 @@ // 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 <https://lilypond.org/download.html> +pub fn check_lilypond_available() -> Result<String, RenderError> { + 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 a single .ly file to SVG using LilyPond. +/// +/// This function invokes the LilyPond CLI to convert a LilyPond source file +/// into an SVG image. The SVG file will be created in the specified output directory. +/// +/// # Arguments +/// - `ly_file`: Path to the .ly file to render +/// - `output_dir`: Directory where the SVG should be created +/// - `lilypond_binary`: Path to the LilyPond binary (typically "lilypond") +/// +/// # Returns +/// Path to the generated SVG file +/// +/// # Errors +/// - `RenderError::FileIO` if the output directory cannot be created +/// - `RenderError::LilyPondExecution` if LilyPond fails to execute or produce output +/// - `RenderError::Template` if the .ly filename is invalid +/// +/// # Examples +/// ```no_run +/// use morphology_img::render::render_ly_to_svg; +/// use std::path::Path; +/// +/// let ly_file = Path::new("/tmp/sequence-0.ly"); +/// let output_dir = Path::new("output"); +/// let lilypond = Path::new("lilypond"); +/// +/// let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond).unwrap(); +/// println!("Generated SVG: {}", svg_path.display()); +/// ``` +/// +/// # Notes +/// - LilyPond creates `filename.svg` from `filename.ly` in the output directory +/// - The function verifies that the expected SVG file was actually created +/// - LilyPond must be installed and the binary must be accessible +pub fn render_ly_to_svg( + ly_file: &Path, + output_dir: &Path, + lilypond_binary: &Path, +) -> Result<PathBuf, RenderError> { + // Ensure output directory exists + fs::create_dir_all(output_dir)?; + + // Build the command: lilypond --svg -o output_dir ly_file + let output = Command::new(lilypond_binary) + .arg("--svg") + .arg("-o") + .arg(output_dir) + .arg(ly_file) + .output()?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(RenderError::LilyPondExecution(stderr.to_string())); + } + + // Determine the output SVG path + // LilyPond creates filename.svg from filename.ly + let svg_filename = ly_file + .file_stem() + .ok_or_else(|| RenderError::Template("Invalid .ly filename".to_string()))? + .to_string_lossy() + .to_string() + ".svg"; + + let svg_path = output_dir.join(svg_filename); + + // Verify the SVG was created + if !svg_path.exists() { + return Err(RenderError::LilyPondExecution( + format!("Expected SVG not created: {}", svg_path.display()) + )); + } + + Ok(svg_path) +} + +/// Renders multiple .ly files to SVGs using LilyPond. +/// +/// This function processes multiple LilyPond source files sequentially, +/// converting each to an SVG image in the specified output directory. +/// +/// # 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 +/// +/// # Returns +/// Vector of paths to generated SVG files, in the same order as input +/// +/// # Errors +/// Returns an error if any file fails to render. Processing stops at the first error. +/// +/// # Examples +/// ```no_run +/// use morphology_img::render::render_ly_files_to_svg; +/// 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_ly_files_to_svg(&ly_files, output_dir, lilypond).unwrap(); +/// println!("Generated {} SVG files", svg_paths.len()); +/// ``` +/// +/// # Notes +/// - Files are processed sequentially (not in parallel) +/// - All SVGs are created in the same output directory +/// - If any file fails, an error is returned immediately +pub fn render_ly_files_to_svg( + ly_files: &[PathBuf], + output_dir: &Path, + lilypond_binary: &Path, +) -> Result<Vec<PathBuf>, RenderError> { + let mut svg_paths = Vec::with_capacity(ly_files.len()); + + for ly_file in ly_files { + let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?; + svg_paths.push(svg_path); + } + + Ok(svg_paths) +} diff --git a/morphology-img/src/template.rs b/morphology-img/src/template.rs index afa091b..15a47d5 100644 --- a/morphology-img/src/template.rs +++ b/morphology-img/src/template.rs @@ -1 +1,53 @@ // Template handling and substitution + +use crate::error::RenderError; + +/// Template files embedded at compile time +const TEMPLATE_LY: &str = include_str!("../static/template.ly"); +const FORMAT_ILY: &str = include_str!("../static/format.ily"); +const ENTRY_ILY: &str = include_str!("../static/entry.ily"); +const ELEMENTS_ILY: &str = include_str!("../static/elements.ily"); + +const PLACEHOLDER: &str = "%%%"; + +/// Returns the template .ly content +pub fn get_template() -> &'static str { + TEMPLATE_LY +} + +/// Returns the format.ily content +pub fn get_format_ily() -> &'static str { + FORMAT_ILY +} + +/// Returns the entry.ily content +pub fn get_entry_ily() -> &'static str { + ENTRY_ILY +} + +/// Returns the elements.ily content +pub fn get_elements_ily() -> &'static str { + ELEMENTS_ILY +} + +/// Substitutes the placeholder in the template with the provided markup. +/// +/// # Arguments +/// - `markup`: The LilyPond markup to substitute into the template +/// +/// # Returns +/// The complete .ly file content with substitution applied +/// +/// # Errors +/// Returns `RenderError::Template` if the placeholder is not found +pub fn substitute_template(markup: &str) -> Result<String, RenderError> { + let template = get_template(); + + if !template.contains(PLACEHOLDER) { + return Err(RenderError::Template( + "Template does not contain placeholder '%%%'".to_string() + )); + } + + Ok(template.replace(PLACEHOLDER, markup)) +} |