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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
|
// 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
/// - `progress_callback`: Optional callback for progress reporting
///
/// # 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, None).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
/// - Progress callback is called after each file is rendered (if provided)
pub fn render_ly_files_to_svg(
ly_files: &[PathBuf],
output_dir: &Path,
lilypond_binary: &Path,
progress_callback: Option<&crate::ProgressCallback>,
) -> Result<Vec<PathBuf>, RenderError> {
let total_count = ly_files.len();
let mut svg_paths = Vec::with_capacity(total_count);
for (index, ly_file) in ly_files.iter().enumerate() {
let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?;
svg_paths.push(svg_path);
// Call progress callback if provided
if let Some(callback) = progress_callback {
callback(index + 1, total_count);
}
}
Ok(svg_paths)
}
/// Renders multiple .ly files to SVGs using LilyPond in parallel.
///
/// This function processes multiple LilyPond source files concurrently using rayon,
/// converting each to an SVG image in the specified output directory. This can
/// significantly improve performance for large batches on multi-core systems.
///
/// # 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
/// - `progress_callback`: Optional callback for progress reporting
///
/// # 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.
///
/// # Performance Notes
/// - Files are processed in parallel using rayon
/// - Progress callbacks may be invoked out of order (but still track correct indices)
/// - Best for batches of 10+ files on multi-core systems
/// - May be slower than sequential for very small batches due to overhead
///
/// # Examples
/// ```no_run
/// use morphology_img::render::render_ly_files_to_svg_parallel;
/// 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_parallel(&ly_files, output_dir, lilypond, None).unwrap();
/// println!("Generated {} SVG files", svg_paths.len());
/// ```
pub fn render_ly_files_to_svg_parallel(
ly_files: &[PathBuf],
output_dir: &Path,
lilypond_binary: &Path,
progress_callback: Option<&crate::ProgressCallback>,
) -> Result<Vec<PathBuf>, RenderError> {
use rayon::prelude::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
let total_count = ly_files.len();
// Use atomic counter for progress tracking
let completed = Arc::new(AtomicUsize::new(0));
// Process files in parallel
let results: Vec<Result<PathBuf, RenderError>> = ly_files
.par_iter()
.map(|ly_file| {
let svg_path = render_ly_to_svg(ly_file, output_dir, lilypond_binary)?;
// Update progress if callback is provided
if let Some(callback) = progress_callback {
let current = completed.fetch_add(1, Ordering::SeqCst) + 1;
callback(current, total_count);
}
Ok(svg_path)
})
.collect();
// Collect results, returning early on first error
results.into_iter().collect()
}
|