summaryrefslogtreecommitdiff
path: root/morphology-img
diff options
context:
space:
mode:
authorjacksonfu14 <jackson@fashionunited.com>2025-11-17 08:41:32 +0100
committerJackson Moore <jacksonmoore@tuta.io>2025-11-17 08:41:32 +0100
commitfc43589d3a5206a9b555dc868a1db0c92af53802 (patch)
tree4e23cb92a912584a46450e5675654b0057f00f11 /morphology-img
parenta20f9a327c4d9e5ac8f42db4e2e9fb29770c3d37 (diff)
feature: ly processing progress callbacks
Diffstat (limited to 'morphology-img')
-rw-r--r--morphology-img/src/lib.rs58
-rw-r--r--morphology-img/src/render.rs15
-rw-r--r--morphology-img/tests/integration.rs175
-rw-r--r--morphology-img/tests/render.rs7
4 files changed, 250 insertions, 5 deletions
diff --git a/morphology-img/src/lib.rs b/morphology-img/src/lib.rs
index 3ba78f2..8e82f91 100644
--- a/morphology-img/src/lib.rs
+++ b/morphology-img/src/lib.rs
@@ -34,6 +34,25 @@ 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.
///
@@ -53,7 +72,7 @@ use std::path::PathBuf;
/// .keep_temp_files(true)
/// .lilypond_binary("/usr/local/bin/lilypond");
/// ```
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct RenderConfig {
/// Directory where SVG files should be created
pub output_dir: PathBuf,
@@ -63,6 +82,20 @@ pub struct RenderConfig {
/// Path to the LilyPond binary (default: "lilypond")
pub lilypond_binary: PathBuf,
+
+ /// Optional callback for progress reporting during batch rendering
+ pub progress_callback: Option<ProgressCallback>,
+}
+
+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>"))
+ .finish()
+ }
}
impl Default for RenderConfig {
@@ -71,6 +104,7 @@ impl Default for RenderConfig {
output_dir: PathBuf::from("output"),
keep_temp_files: false,
lilypond_binary: PathBuf::from("lilypond"),
+ progress_callback: None,
}
}
}
@@ -136,6 +170,27 @@ impl RenderConfig {
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
+ }
}
/// Renders multiple sequences to SVG files.
@@ -217,6 +272,7 @@ pub fn render_sequences(
&ly_files,
&config.output_dir,
&config.lilypond_binary,
+ config.progress_callback.as_ref(),
)?;
// Handle temp directory cleanup
diff --git a/morphology-img/src/render.rs b/morphology-img/src/render.rs
index 189dd61..ca61df4 100644
--- a/morphology-img/src/render.rs
+++ b/morphology-img/src/render.rs
@@ -138,6 +138,7 @@ pub fn render_ly_to_svg(
/// - `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
@@ -157,7 +158,7 @@ pub fn render_ly_to_svg(
/// 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();
+/// let svg_paths = render_ly_files_to_svg(&ly_files, output_dir, lilypond, None).unwrap();
/// println!("Generated {} SVG files", svg_paths.len());
/// ```
///
@@ -165,16 +166,24 @@ pub fn render_ly_to_svg(
/// - 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 mut svg_paths = Vec::with_capacity(ly_files.len());
+ let total_count = ly_files.len();
+ let mut svg_paths = Vec::with_capacity(total_count);
- for ly_file in ly_files {
+ 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)
diff --git a/morphology-img/tests/integration.rs b/morphology-img/tests/integration.rs
index e6db544..227e5d1 100644
--- a/morphology-img/tests/integration.rs
+++ b/morphology-img/tests/integration.rs
@@ -1,7 +1,8 @@
-use morphology_img::{render_sequences, RenderConfig};
+use morphology_img::{render_sequences, RenderConfig, ProgressCallback};
use morphology::{Sequence, Value};
use tempfile::TempDir;
use std::fs;
+use std::sync::{Arc, Mutex};
/// Test the complete pipeline with basic configuration
#[test]
@@ -363,3 +364,175 @@ fn test_render_sequences_realistic_workflow() {
assert_eq!(svg_paths[0].file_name().unwrap().to_str().unwrap(), "sequence-0.svg");
assert_eq!(svg_paths[3].file_name().unwrap().to_str().unwrap(), "sequence-3.svg");
}
+
+// Tests for progress callback
+
+/// Test that progress callback is called correctly
+#[test]
+#[ignore]
+fn test_progress_callback_basic() {
+ let sequences = vec![
+ Sequence::new(vec![Value::origin()]),
+ Sequence::new(vec![Value::new(1, 0)]),
+ Sequence::new(vec![Value::new(2, 0)]),
+ ];
+
+ let progress_calls = Arc::new(Mutex::new(Vec::new()));
+ let progress_calls_clone = progress_calls.clone();
+
+ let callback: ProgressCallback = Arc::new(move |current, total| {
+ progress_calls_clone.lock().unwrap().push((current, total));
+ });
+
+ let output_dir = TempDir::new().unwrap();
+ let config = RenderConfig::new(output_dir.path())
+ .progress_callback(callback);
+
+ let svg_paths = render_sequences(&sequences, &config).unwrap();
+
+ // Verify all SVGs were created
+ assert_eq!(svg_paths.len(), 3);
+
+ // Verify progress callback was called correctly
+ let calls = progress_calls.lock().unwrap();
+ assert_eq!(calls.len(), 3, "callback should be called once per sequence");
+
+ // Verify calls have correct values
+ assert_eq!(calls[0], (1, 3), "first call should be (1, 3)");
+ assert_eq!(calls[1], (2, 3), "second call should be (2, 3)");
+ assert_eq!(calls[2], (3, 3), "third call should be (3, 3)");
+}
+
+/// Test progress callback with single sequence
+#[test]
+#[ignore]
+fn test_progress_callback_single() {
+ let sequences = vec![Sequence::new(vec![Value::origin()])];
+
+ let progress_calls = Arc::new(Mutex::new(Vec::new()));
+ let progress_calls_clone = progress_calls.clone();
+
+ let callback: ProgressCallback = Arc::new(move |current, total| {
+ progress_calls_clone.lock().unwrap().push((current, total));
+ });
+
+ let output_dir = TempDir::new().unwrap();
+ let config = RenderConfig::new(output_dir.path())
+ .progress_callback(callback);
+
+ let _svg_paths = render_sequences(&sequences, &config).unwrap();
+
+ let calls = progress_calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0], (1, 1));
+}
+
+/// Test progress callback with many sequences
+#[test]
+#[ignore]
+fn test_progress_callback_many() {
+ let sequences: Vec<Sequence> = (0..10)
+ .map(|i| Sequence::new(vec![Value::new(i, 0)]))
+ .collect();
+
+ let progress_calls = Arc::new(Mutex::new(Vec::new()));
+ let progress_calls_clone = progress_calls.clone();
+
+ let callback: ProgressCallback = Arc::new(move |current, total| {
+ progress_calls_clone.lock().unwrap().push((current, total));
+ });
+
+ let output_dir = TempDir::new().unwrap();
+ let config = RenderConfig::new(output_dir.path())
+ .progress_callback(callback);
+
+ let svg_paths = render_sequences(&sequences, &config).unwrap();
+
+ assert_eq!(svg_paths.len(), 10);
+
+ let calls = progress_calls.lock().unwrap();
+ assert_eq!(calls.len(), 10);
+
+ // Verify each call has correct values
+ for (i, &(current, total)) in calls.iter().enumerate() {
+ assert_eq!(current, i + 1);
+ assert_eq!(total, 10);
+ }
+}
+
+/// Test that rendering works without progress callback
+#[test]
+#[ignore]
+fn test_no_progress_callback() {
+ let sequences = vec![
+ Sequence::new(vec![Value::origin()]),
+ Sequence::new(vec![Value::new(1, 0)]),
+ ];
+
+ let output_dir = TempDir::new().unwrap();
+ let config = RenderConfig::new(output_dir.path());
+ // No progress callback set
+
+ let svg_paths = render_sequences(&sequences, &config).unwrap();
+
+ // Should work normally without callback
+ assert_eq!(svg_paths.len(), 2);
+ for svg_path in &svg_paths {
+ assert!(svg_path.exists());
+ }
+}
+
+/// Test progress callback with empty sequence list
+#[test]
+#[ignore]
+fn test_progress_callback_empty() {
+ let sequences: Vec<Sequence> = vec![];
+
+ let progress_calls = Arc::new(Mutex::new(Vec::new()));
+ let progress_calls_clone = progress_calls.clone();
+
+ let callback: ProgressCallback = Arc::new(move |current, total| {
+ progress_calls_clone.lock().unwrap().push((current, total));
+ });
+
+ let output_dir = TempDir::new().unwrap();
+ let config = RenderConfig::new(output_dir.path())
+ .progress_callback(callback);
+
+ let svg_paths = render_sequences(&sequences, &config).unwrap();
+
+ assert_eq!(svg_paths.len(), 0);
+
+ // Callback should not be called for empty list
+ let calls = progress_calls.lock().unwrap();
+ assert_eq!(calls.len(), 0, "callback should not be called for empty input");
+}
+
+/// Test that progress callback can track actual progress
+#[test]
+#[ignore]
+fn test_progress_callback_tracking() {
+ let sequences: Vec<Sequence> = (0..5)
+ .map(|i| Sequence::new(vec![Value::new(i, 0)]))
+ .collect();
+
+ let last_progress = Arc::new(Mutex::new((0, 0)));
+ let last_progress_clone = last_progress.clone();
+
+ let callback: ProgressCallback = Arc::new(move |current, total| {
+ let mut progress = last_progress_clone.lock().unwrap();
+ *progress = (current, total);
+ });
+
+ let output_dir = TempDir::new().unwrap();
+ let config = RenderConfig::new(output_dir.path())
+ .progress_callback(callback);
+
+ let svg_paths = render_sequences(&sequences, &config).unwrap();
+
+ assert_eq!(svg_paths.len(), 5);
+
+ // Last progress should be 5/5
+ let final_progress = last_progress.lock().unwrap();
+ assert_eq!(*final_progress, (5, 5), "final progress should be 5/5");
+}
diff --git a/morphology-img/tests/render.rs b/morphology-img/tests/render.rs
index dc2c54a..b6538ab 100644
--- a/morphology-img/tests/render.rs
+++ b/morphology-img/tests/render.rs
@@ -314,6 +314,7 @@ fn test_render_multiple_svgs_batch() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
).unwrap();
// Verify all SVGs were created
@@ -348,6 +349,7 @@ fn test_batch_render_preserves_order() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
).unwrap();
// Verify filenames are in order
@@ -372,6 +374,7 @@ fn test_batch_render_empty_list() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
).unwrap();
assert_eq!(svg_paths.len(), 0, "should return empty vector for empty input");
@@ -396,6 +399,7 @@ fn test_batch_render_single_file() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
).unwrap();
assert_eq!(svg_paths.len(), 1);
@@ -428,6 +432,7 @@ fn test_batch_render_stops_on_error() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
);
// Should fail due to invalid file
@@ -460,6 +465,7 @@ fn test_batch_render_many_files() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
).unwrap();
// Verify all 10 SVGs were created
@@ -517,6 +523,7 @@ fn test_complete_pipeline_batch_rendering() {
&ly_files,
output_dir.path(),
Path::new("lilypond"),
+ None,
).unwrap();
// Verify complete pipeline