1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
|
// .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, sequence_to_ledgers, vector_to_scheme};
/// 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 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 = vector_to_scheme(&staff);
// Convert sequence to ledger line positions
let ledger_positions = sequence_to_ledgers(sequence);
// Convert ledgers to Scheme list string
let ledgers = vector_to_scheme(&ledger_positions);
// Substitute all values into template
let ly_content = template::substitute_template(&morpheme, &rungs, &ledgers)?;
// 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> {
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<Vec<PathBuf>, 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)
}
|