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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
|
//! 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<dyn Fn(usize, usize) + Send + Sync>;
/// 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<ProgressCallback>,
/// Maximum number of sequences to process in a single batch
///
/// If set, large batches will be split into smaller chunks to avoid
/// filesystem issues. If None, all sequences are processed in one batch.
pub max_batch_size: Option<usize>,
/// Whether to use parallel processing for rendering SVGs
///
/// When enabled, multiple LilyPond processes will run concurrently using rayon.
/// This can significantly improve performance for large batches on multi-core systems.
/// Default: false (conservative default to avoid overwhelming the system).
pub parallel: bool,
}
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(|_| "<callback>"))
.field("max_batch_size", &self.max_batch_size)
.field("parallel", &self.parallel)
.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,
max_batch_size: None,
parallel: false,
}
}
}
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
}
/// 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
}
/// Sets the maximum batch size for processing sequences.
///
/// When set, large batches of sequences will be split into smaller chunks
/// to avoid overwhelming the filesystem or LilyPond. Each chunk is processed
/// independently with its own temporary directory.
///
/// # Examples
///
/// ```
/// use morphology_img::RenderConfig;
///
/// let config = RenderConfig::new("output")
/// .max_batch_size(50);
///
/// assert_eq!(config.max_batch_size, Some(50));
/// ```
pub fn max_batch_size(mut self, size: usize) -> Self {
self.max_batch_size = Some(size);
self
}
/// Enables or disables parallel processing for SVG rendering.
///
/// When enabled, LilyPond will be invoked in parallel using rayon,
/// which can significantly improve performance for large batches on
/// multi-core systems. The default is false (sequential processing).
///
/// # Performance Considerations
///
/// Parallel processing is most beneficial when:
/// - Rendering many sequences (typically 10+)
/// - Running on a multi-core system
/// - LilyPond execution is the bottleneck (not file I/O)
///
/// For small batches (< 10 sequences), sequential processing may be faster
/// due to the overhead of spawning parallel tasks.
///
/// # Examples
///
/// ```
/// use morphology_img::RenderConfig;
///
/// let config = RenderConfig::new("output")
/// .parallel(true);
///
/// assert!(config.parallel);
/// ```
pub fn parallel(mut self, parallel: bool) -> Self {
self.parallel = parallel;
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> {
// Handle empty input
if sequences.is_empty() {
return Ok(Vec::new());
}
// Check if LilyPond is available before doing any work
render::check_lilypond_available()?;
// Determine batch size
let batch_size = config.max_batch_size.unwrap_or(sequences.len());
let mut all_svg_paths = Vec::with_capacity(sequences.len());
let total_count = sequences.len();
// Process sequences in chunks with global indexing
let mut global_offset = 0;
for chunk in sequences.chunks(batch_size) {
let svg_paths = render_sequences_batch(chunk, config, global_offset, total_count)?;
all_svg_paths.extend(svg_paths);
global_offset += chunk.len();
}
Ok(all_svg_paths)
}
/// Helper function to render a single batch of sequences.
///
/// This function handles the complete rendering pipeline for a batch:
/// creating temp directory, writing support files, generating .ly files,
/// and rendering to SVGs.
///
/// # Arguments
/// - `sequences`: The batch of sequences to render
/// - `config`: Configuration for rendering
/// - `global_offset`: The starting index for this batch in the overall sequence list
/// - `total_count`: The total number of sequences across all batches
fn render_sequences_batch(
sequences: &[morphology::Sequence],
config: &RenderConfig,
global_offset: usize,
total_count: usize,
) -> Result<Vec<PathBuf>, RenderError> {
// 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 with proper global indexing
let ly_files = file_gen::generate_ly_files_with_offset(
sequences,
temp_dir.path(),
global_offset,
total_count,
)?;
// Render .ly files to SVGs (parallel or sequential based on config)
let svg_paths = if config.parallel {
render::render_ly_files_to_svg_parallel(
&ly_files,
&config.output_dir,
&config.lilypond_binary,
config.progress_callback.as_ref(),
)?
} else {
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)
}
|