// .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, sequence_to_staff, staff_to_scheme_string}; /// 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::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 morpheme = notes_to_markup(¬es); // Convert sequence to staff line positions let staff = sequence_to_staff(sequence); // Convert staff to Scheme list string let rungs = staff_to_scheme_string(&staff); // Substitute both values into template let ly_content = template::substitute_template(&morpheme, &rungs)?; // 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, RenderError> { generate_ly_files_with_offset(sequences, temp_dir, 0, sequences.len()) } /// Generates .ly files for multiple sequences with custom offset and total count. /// /// This function is used internally for batch processing to maintain proper /// global indexing across batches. The offset parameter allows each batch to /// start numbering from its global position, while total_count ensures /// consistent padding width across all batches. /// /// # Arguments /// - `sequences`: The sequences to generate files for (batch) /// - `temp_dir`: The directory to write files to /// - `offset`: Starting index in the global sequence list /// - `total_count`: Total number of sequences across all batches /// /// # Returns /// A vector of paths to the generated .ly files /// /// # Examples /// ```no_run /// use morphology::{Sequence, Value}; /// use morphology_img::file_gen::{generate_ly_files_with_offset, create_temp_dir}; /// /// // Second batch of a 12-sequence job /// let sequences = vec![ /// Sequence::new(vec![Value::new(5, 0)]), /// Sequence::new(vec![Value::new(6, 0)]), /// ]; /// /// let temp_dir = create_temp_dir().unwrap(); /// // offset=5, total_count=12 ensures filenames are sequence-05.ly, sequence-06.ly /// let paths = generate_ly_files_with_offset(&sequences, temp_dir.path(), 5, 12).unwrap(); /// ``` pub fn generate_ly_files_with_offset( sequences: &[Sequence], temp_dir: &Path, offset: usize, total_count: usize, ) -> Result, RenderError> { let mut paths = Vec::with_capacity(sequences.len()); for (index, sequence) in sequences.iter().enumerate() { let global_index = offset + index; let filename = generate_filename(global_index, total_count); let output_path = temp_dir.join(&filename); generate_ly_file(sequence, &output_path)?; paths.push(output_path); } Ok(paths) }