From e2e7ddb625dfc0e9c371bddbc9f9dad26ba46f03 Mon Sep 17 00:00:00 2001 From: Andrei Gherghescu <8067229+andrei-ng@users.noreply.github.com> Date: Wed, 13 Aug 2025 10:31:59 +0300 Subject: [PATCH] expose an async API for plotly_static Signed-off-by: Andrei Gherghescu <8067229+andrei-ng@users.noreply.github.com> --- CHANGELOG.md | 12 + README.md | 8 +- .../src/fundamentals/static_image_export.md | 44 +- .../src/main.rs | 13 +- examples/static_export/Cargo.toml | 6 +- examples/static_export/README.md | 27 +- examples/static_export/src/bin/async.rs | 78 ++ .../src/{main.rs => bin/sync.rs} | 32 +- plotly/Cargo.toml | 16 +- plotly/src/export.rs | 339 +++++++++ plotly/src/layout/rangebreaks.rs | 2 +- plotly/src/layout/scene.rs | 2 +- plotly/src/lib.rs | 13 +- plotly/src/plot.rs | 164 ++--- plotly_static/Cargo.toml | 2 +- plotly_static/README.md | 19 +- plotly_static/src/lib.rs | 685 ++++++++++++------ plotly_static/src/template.rs | 1 - plotly_static/src/webdriver.rs | 4 +- 19 files changed, 1093 insertions(+), 374 deletions(-) create mode 100644 examples/static_export/src/bin/async.rs rename examples/static_export/src/{main.rs => bin/sync.rs} (84%) create mode 100644 plotly/src/export.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 85f3faad..a88c9c1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +https://github.com/plotly/plotly.rs/pull/350 + +## [0.13.6] - 2025-xx-xx + +### Fixed + +- [[#348](https://github.com/plotly/plotly.rs/pull/348)] Fix Pie chart color setting + +### Changed + +- [[#350](https://github.com/plotly/plotly.rs/pull/350)] Add `plotly_static` `async` API + ## [0.13.5] - 2025-07-31 ### Fixed diff --git a/README.md b/README.md index 461356c1..6d796956 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,13 @@ let base64_data = plot.to_base64(ImageFormat::PNG, 800, 600, 1.0)?; let svg_string = plot.to_svg(800, 600, 1.0)?; ``` -**Note:** This feature requires a WebDriver-compatible browser (Chrome or Firefox) as well as a Webdriver (chromedriver/geckodriver) to be available on the system. For advanced usage, see the [`plotly_static` crate documentation](https://docs.rs/plotly_static/). +**Note:** This feature requires a WebDriver-compatible browser (Chrome or Firefox) as well as a Webdriver (chromedriver/geckodriver) to be available on the system. + +The above example uses the legacy API that is backwards compatible with the Kaleido API. However, for more efficient workflows a `StaticExporter` object can be built and reused between calls to `write_image`. + +More specificallt, enabling any of the `plotly` features `static_export_chromedriver`, `static_export_geckodriver`, or `static_export_default` gives access to both the synchronous `StaticExporter` and the asynchronous `AsyncStaticExporter` (available via `plotly::plotly_static`). For exporter reuse and up-to-date sync/async usage patterns, please see the dedicated example in `examples/static_export`, which demonstrates both synchronous and asynchronous exporters and how to reuse a single exporter instance across multiple exports. + + For further details see [`plotly_static` crate documentation](https://docs.rs/plotly_static/). ## Exporting Static Images with Kaleido (legacy) diff --git a/docs/book/src/fundamentals/static_image_export.md b/docs/book/src/fundamentals/static_image_export.md index 81dab8d0..2c4f6265 100644 --- a/docs/book/src/fundamentals/static_image_export.md +++ b/docs/book/src/fundamentals/static_image_export.md @@ -34,11 +34,13 @@ plotly = { version = "0.13", features = ["static_export_chromedriver", "static_e plotly = { version = "0.13", features = ["static_export_default"] } ``` +> Enabling any of the static export features in `plotly` (`static_export_chromedriver`, `static_export_geckodriver`, or `static_export_default`) enables both APIs from `plotly_static`: the sync `StaticExporter` and the async `AsyncStaticExporter` (reachable as `plotly::plotly_static::AsyncStaticExporter`). Prefer the async API inside async code. + ## Prerequisites 1. **WebDriver Installation**: You need either chromedriver or geckodriver installed - - Chrome: Download from https://chromedriver.chromium.org/ - - Firefox: Download from https://github.com/mozilla/geckodriver/releases + - Chrome: Download from [https://chromedriver.chromium.org/](https://chromedriver.chromium.org/) + - Firefox: Download from [https://github.com/mozilla/geckodriver/releases](https://github.com/mozilla/geckodriver/releases) - Or use the `static_export_wd_download` feature for automatic download 2. **Browser Installation**: You need Chrome/Chromium or Firefox installed @@ -74,6 +76,7 @@ For better performance when exporting multiple plots, reuse a single `StaticExpo ```rust use plotly::{Plot, Scatter}; use plotly::plotly_static::{StaticExporterBuilder, ImageFormat}; +use plotly::prelude::*; let mut plot1 = Plot::new(); plot1.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); @@ -87,10 +90,13 @@ let mut exporter = StaticExporterBuilder::default() .expect("Failed to create StaticExporter"); // Export multiple plots using the same exporter -plot1.write_image_with_exporter(&mut exporter, "plot1", ImageFormat::PNG, 800, 600, 1.0) +exporter.write_image(&plot1, "plot1", ImageFormat::PNG, 800, 600, 1.0) .expect("Failed to export plot1"); -plot2.write_image_with_exporter(&mut exporter, "plot2", ImageFormat::JPEG, 800, 600, 1.0) +exporter.write_image(&plot2, "plot2", ImageFormat::JPEG, 800, 600, 1.0) .expect("Failed to export plot2"); + +// Always close the exporter to ensure proper release of WebDriver resources +exporter.close(); ``` ## Supported Formats @@ -114,6 +120,7 @@ For web applications or APIs, you can export to strings: ```rust use plotly::{Plot, Scatter}; use plotly::plotly_static::{StaticExporterBuilder, ImageFormat}; +use plotly::prelude::*; let mut plot = Plot::new(); plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); @@ -123,14 +130,19 @@ let mut exporter = StaticExporterBuilder::default() .expect("Failed to create StaticExporter"); // Get base64 data (useful for embedding in HTML) -let base64_data = plot.to_base64_with_exporter(&mut exporter, ImageFormat::PNG, 400, 300, 1.0) +let base64_data = exporter.to_base64(&plot, ImageFormat::PNG, 400, 300, 1.0) .expect("Failed to export plot"); // Get SVG data (vector format, scalable) -let svg_data = plot.to_svg_with_exporter(&mut exporter, 400, 300, 1.0) +let svg_data = exporter.to_svg(&plot, 400, 300, 1.0) .expect("Failed to export plot"); + +// Always close the exporter to ensure proper release of WebDriver resources +exporter.close(); ``` +Always call `close()` on the exporter to ensure proper release of WebDriver resources. Due to the nature of WebDriver implementation, close has to be called as resources cannot be automatically dropped or released. + ## Advanced Configuration ### Custom WebDriver Configuration @@ -150,6 +162,10 @@ let mut exporter = StaticExporterBuilder::default() ]) .build() .expect("Failed to create StaticExporter"); + +// Always close the exporter to ensure proper release of WebDriver resources +exporter.close(); + ``` ### Parallel Usage @@ -172,8 +188,19 @@ let mut exporter = StaticExporterBuilder::default() .webdriver_port(get_unique_port()) .build() .expect("Failed to build StaticExporter"); + +// Always close the exporter to ensure proper release of WebDriver resources +exporter.close(); ``` +### Async support + +`plotly_static` package offers an `async` API which is exposed in `plotly` via the `write_image_async`, `to_base64_async` and `to_svg_async` functions. However, the user must pass an `AsyncStaticExporter` asynchronous exporter instead of a synchronous one by building it via `StaticExportBuilder`'s `build_async` method. + +> Note: Both sync and async exporters are available whenever a `static_export_*` feature is enabled in `plotly`. + +For more details check the [`plotly_static` API Documentation](https://docs.rs/plotly_static/) + ## Logging Support Enable logging for debugging and monitoring: @@ -190,6 +217,9 @@ env_logger::init(); let mut exporter = StaticExporterBuilder::default() .build() .expect("Failed to create StaticExporter"); + +// Always close the exporter to ensure proper release of WebDriver resources +exporter.close(); ``` ## Performance Considerations @@ -200,7 +230,7 @@ let mut exporter = StaticExporterBuilder::default() ## Complete Example -See the [static export example](../../../examples/static_export/) for a complete working example that demonstrates: +See the [static export example](https://github.com/plotly/plotly.rs/tree/main/examples/static_export) for a complete working example that demonstrates: - Multiple export formats - Exporter reuse diff --git a/examples/customization/consistent_static_format_export/src/main.rs b/examples/customization/consistent_static_format_export/src/main.rs index 813d5571..1e8a923a 100644 --- a/examples/customization/consistent_static_format_export/src/main.rs +++ b/examples/customization/consistent_static_format_export/src/main.rs @@ -3,6 +3,7 @@ use plotly::color::{NamedColor, Rgb}; use plotly::common::{Anchor, Font, Line, Marker, MarkerSymbol, Mode, Title}; use plotly::layout::{Axis, ItemSizing, Legend, Margin, Shape, ShapeLine, ShapeType}; use plotly::plotly_static::{ImageFormat, StaticExporterBuilder}; +use plotly::prelude::*; use plotly::{Layout, Plot, Scatter}; fn line_and_scatter_plot( @@ -149,19 +150,25 @@ fn line_and_scatter_plot( .unwrap(); info!("Exporting to PNG format..."); - plot.write_image_with_exporter(&mut exporter, file_name, ImageFormat::PNG, 1280, 960, 1.0) + exporter + .write_image(&plot, file_name, ImageFormat::PNG, 1280, 960, 1.0) .unwrap(); info!("Exporting to SVG format..."); - plot.write_image_with_exporter(&mut exporter, file_name, ImageFormat::SVG, 1280, 960, 1.0) + exporter + .write_image(&plot, file_name, ImageFormat::SVG, 1280, 960, 1.0) .unwrap(); info!("Exporting to PDF format..."); - plot.write_image_with_exporter(&mut exporter, file_name, ImageFormat::PDF, 1280, 960, 1.0) + exporter + .write_image(&plot, file_name, ImageFormat::PDF, 1280, 960, 1.0) .unwrap(); info!("Export complete. Check the output files:"); info!(" - {file_name}.pdf"); info!(" - {file_name}.svg"); info!(" - {file_name}.png"); + + // Always close the exporter to ensure proper release of WebDriver resources + exporter.close(); } fn read_from_file(file_path: &str) -> Vec> { diff --git a/examples/static_export/Cargo.toml b/examples/static_export/Cargo.toml index 71c75304..a6de5cde 100644 --- a/examples/static_export/Cargo.toml +++ b/examples/static_export/Cargo.toml @@ -5,8 +5,10 @@ authors = ["Andrei Gherghescu andrei-ng@protonmail.com"] edition = "2021" description = "Example demonstrating static image export using plotly_static with WebDriver" readme = "README.md" +default-run = "sync" [dependencies] plotly = { path = "../../plotly", features = ["static_export_default"] } -env_logger = "0.10" -log = "0.4" +env_logger = "0.11" +log = "0.4" +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } diff --git a/examples/static_export/README.md b/examples/static_export/README.md index 5c5149b3..c5f03936 100644 --- a/examples/static_export/README.md +++ b/examples/static_export/README.md @@ -6,13 +6,13 @@ The `plotly_static` provides a interface for converting Plotly plots into variou In this example it is shown how to use the `StaticExporter` with the old style Kaleido API and also with the new style API. Using the former API is fine for one time static exports, but that API will crate an instance of the `StaticExporter` for each `write_image` call. The new style API is recommended for performance as the same instance of the `StaticExporter` can be reused across multiple exports. -See also the `Static Image Export` section in the book for a more detailed description. +When any of the `plotly` static export features are enabled (`static_export_chromedriver`, `static_export_geckodriver`, or `static_export_default`), both `StaticExporter` (sync) and `AsyncStaticExporter` (async) are available via `plotly::plotly_static`. This example includes separate `sync` and `async` bins demonstrating both. Refer to the [`plotly_static` API Documentation](https://docs.rs/plotly_static/) a more detailed description. ## Overview - ## Features +- **Async/Sync API** - **Multiple Export Formats**: PNG, JPEG, SVG, PDF - **Exporter Reuse (new API)**: Efficient reuse of a single `StaticExporter` instance - **String Export**: Base64 and SVG string output for web applications @@ -45,17 +45,32 @@ plotly = { version = "0.13", features = ["static_export_geckodriver"] } plotly = { version = "0.13", features = ["static_export_chromedriver"] } ``` -## Running the Example +## Running the Example(s) + +To run the `sync` API example + +```bash +# Basic run +cargo run --bin sync + +# With debug logging +RUST_LOG=debug cargo run --bin sync + +# With custom WebDriver path +WEBDRIVER_PATH=/path/to/chromedriver cargo run --bin sync +``` + +To run the `async` API example ```bash # Basic run -cargo run +cargo run --bin async # With debug logging -RUST_LOG=debug cargo run +RUST_LOG=debug cargo run --bin async # With custom WebDriver path -WEBDRIVER_PATH=/path/to/chromedriver cargo run +WEBDRIVER_PATH=/path/to/chromedriver cargo run --bin async ``` ## Output diff --git a/examples/static_export/src/bin/async.rs b/examples/static_export/src/bin/async.rs new file mode 100644 index 00000000..8ba78394 --- /dev/null +++ b/examples/static_export/src/bin/async.rs @@ -0,0 +1,78 @@ +use log::info; +use plotly::plotly_static::{ImageFormat, StaticExporterBuilder}; +use plotly::prelude::*; +use plotly::{Plot, Scatter}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + + // Create some plots + let mut plot1 = Plot::new(); + plot1.add_trace(Scatter::new(vec![1, 2, 3, 4], vec![10, 15, 13, 17]).name("trace1")); + + let mut plot2 = Plot::new(); + plot2.add_trace(Scatter::new(vec![2, 3, 4, 5], vec![16, 5, 11, 9]).name("trace2")); + + std::fs::create_dir_all("./output").unwrap(); + + info!("Creating AsyncStaticExporter with default configuration..."); + let mut exporter = StaticExporterBuilder::default() + .webdriver_port(5111) + .build_async() + .expect("Failed to create AsyncStaticExporter"); + + info!("Exporting multiple plots using a single AsyncStaticExporter..."); + exporter + .write_image( + &plot1, + "./output/plot1_async_api", + ImageFormat::PNG, + 800, + 600, + 1.0, + ) + .await?; + exporter + .write_image( + &plot1, + "./output/plot1_async_api", + ImageFormat::JPEG, + 800, + 600, + 1.0, + ) + .await?; + exporter + .write_image( + &plot2, + "./output/plot2_async_api", + ImageFormat::SVG, + 800, + 600, + 1.0, + ) + .await?; + exporter + .write_image( + &plot2, + "./output/plot2_async_api", + ImageFormat::PDF, + 800, + 600, + 1.0, + ) + .await?; + + info!("Exporting to base64 and SVG strings with async API..."); + let _base64_data = exporter + .to_base64(&plot1, ImageFormat::PNG, 400, 300, 1.0) + .await?; + let _svg_data = exporter.to_svg(&plot1, 400, 300, 1.0).await?; + + // Always close the exporter to ensure proper release of WebDriver resources + exporter.close().await; + + info!("Async exports completed successfully!"); + Ok(()) +} diff --git a/examples/static_export/src/main.rs b/examples/static_export/src/bin/sync.rs similarity index 84% rename from examples/static_export/src/main.rs rename to examples/static_export/src/bin/sync.rs index 391ed41c..8cb93a98 100644 --- a/examples/static_export/src/main.rs +++ b/examples/static_export/src/bin/sync.rs @@ -1,5 +1,6 @@ use log::info; use plotly::plotly_static::{ImageFormat, StaticExporterBuilder}; +use plotly::prelude::*; use plotly::{Plot, Scatter}; fn main() -> Result<(), Box> { @@ -28,36 +29,39 @@ fn main() -> Result<(), Box> { 1.0, )?; plot3.write_image("./output/plot3_legacy_api", ImageFormat::SVG, 800, 600, 1.0)?; - plot1.write_image("./output/plot3_legacy_api", ImageFormat::PDF, 800, 600, 1.0)?; + + plot1.write_image("./output/plot1_legacy_api", ImageFormat::PDF, 800, 600, 1.0)?; // Create a single StaticExporter to reuse across all plots // This is more efficient than creating a new exporter for each plot which // happens implicitly in the calls above using the old API info!("Creating StaticExporter with default configuration..."); let mut exporter = StaticExporterBuilder::default() + .webdriver_port(5112) .build() .expect("Failed to create StaticExporter"); info!("Exporting multiple plots using a single StaticExporter..."); - // Export all plots using the same exporter - plot1.write_image_with_exporter( - &mut exporter, + // Export all plots using the same exporter (new unified naming via extension + // trait) + exporter.write_image( + &plot1, "./output/plot1_new_api", ImageFormat::PNG, 800, 600, 1.0, )?; - plot2.write_image_with_exporter( - &mut exporter, + exporter.write_image( + &plot2, "./output/plot2_new_api", ImageFormat::JPEG, 800, 600, 1.0, )?; - plot3.write_image_with_exporter( - &mut exporter, + exporter.write_image( + &plot3, "./output/plot3_new_api", ImageFormat::SVG, 800, @@ -65,8 +69,8 @@ fn main() -> Result<(), Box> { 1.0, )?; - plot1.write_image_with_exporter( - &mut exporter, + exporter.write_image( + &plot1, "./output/plot1_new_api", ImageFormat::PDF, 800, @@ -77,11 +81,10 @@ fn main() -> Result<(), Box> { // Demonstrate string-based export info!("Exporting to base64 and SVG strings..."); // Get base64 data (useful for embedding in HTML or APIs) - let base64_data = - plot1.to_base64_with_exporter(&mut exporter, ImageFormat::PNG, 400, 300, 1.0)?; + let base64_data = exporter.to_base64(&plot1, ImageFormat::PNG, 400, 300, 1.0)?; info!("Base64 data length: {}", base64_data.len()); - let svg_data = plot1.to_svg_with_exporter(&mut exporter, 400, 300, 1.0)?; + let svg_data = exporter.to_svg(&plot1, 400, 300, 1.0)?; info!("SVG data starts with: {}", &svg_data[..50]); info!("All exports completed successfully!"); @@ -108,5 +111,8 @@ fn main() -> Result<(), Box> { .expect("Failed to create custom StaticExporter"); */ + // Always close the exporter to ensure proper release of WebDriver resources + exporter.close(); + Ok(()) } diff --git a/plotly/Cargo.toml b/plotly/Cargo.toml index a744ceea..24340dcc 100644 --- a/plotly/Cargo.toml +++ b/plotly/Cargo.toml @@ -17,13 +17,22 @@ keywords = ["plot", "chart", "plotly"] exclude = ["target/*"] [features] -static_export_chromedriver = ["plotly_static", "plotly_static/chromedriver"] -static_export_geckodriver = ["plotly_static", "plotly_static/geckodriver"] +static_export_chromedriver = [ + "plotly_static", + "plotly_static/chromedriver", + "async-trait", +] +static_export_geckodriver = [ + "plotly_static", + "plotly_static/geckodriver", + "async-trait", +] static_export_wd_download = ["plotly_static/webdriver_download"] static_export_default = [ "plotly_static", "plotly_static/chromedriver", "plotly_static/webdriver_download", + "async-trait", ] plotly_ndarray = ["ndarray"] @@ -52,7 +61,7 @@ dyn-clone = "1" erased-serde = "0.4" image = { version = "0.25", optional = true } plotly_derive = { version = "0.13", path = "../plotly_derive" } -plotly_static = { version = "0.0", path = "../plotly_static", optional = true } +plotly_static = { version = "0.1", path = "../plotly_static", optional = true } plotly_kaleido = { version = "0.13", path = "../plotly_kaleido", optional = true } ndarray = { version = "0.16", optional = true } once_cell = "1" @@ -64,6 +73,7 @@ rand = { version = "0.9", default-features = false, features = [ "small_rng", "alloc", ] } +async-trait = { version = "0.1", optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen-futures = { version = "0.4" } diff --git a/plotly/src/export.rs b/plotly/src/export.rs new file mode 100644 index 00000000..c91ea41f --- /dev/null +++ b/plotly/src/export.rs @@ -0,0 +1,339 @@ +#[cfg(feature = "plotly_static")] +pub mod sync { + use std::path::Path; + + use crate::{plot::Plot, ImageFormat}; + + /// Extension methods for exporting plots using a synchronous exporter. + pub trait ExporterSyncExt { + /// Convert the `Plot` to a static image of the given image format and + /// save at the given location using a provided StaticExporter. + /// + /// This method allows you to reuse a StaticExporter instance across + /// multiple plots, which is more efficient than creating a new one for + /// each operation. + /// + /// This method requires the usage of the `plotly_static` crate using + /// one of the available feature flags. For advanced usage (parallelism, exporter reuse, custom config), see the [plotly_static documentation](https://docs.rs/plotly_static/). + /// + /// # Arguments + /// + /// * `exporter` - A mutable reference to a StaticExporter instance + /// * `filename` - The destination path for the output file + /// * `format` - The desired output image format + /// * `width` - The width of the output image in pixels + /// * `height` - The height of the output image in pixels + /// * `scale` - The scale factor for the image (1.0 = normal size) + /// + /// # Examples + /// + /// ```no_run + /// use plotly::{Plot, Scatter}; + /// use plotly::export::sync::ExporterSyncExt as _; + /// use plotly::plotly_static::{StaticExporterBuilder, ImageFormat}; + /// + /// let mut plot = Plot::new(); + /// plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); + /// + /// let mut exporter = StaticExporterBuilder::default() + /// .build() + /// .expect("Failed to create StaticExporter"); + /// + /// // Export multiple plots using the same exporter + /// exporter.write_image(&plot, "plot1", ImageFormat::PNG, 800, 600, 1.0) + /// .expect("Failed to export plot"); + /// + /// exporter.close(); + /// ``` + fn write_image>( + &mut self, + plot: &Plot, + filename: P, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result<(), Box>; + + /// Convert the `Plot` to a static image and return the image as a + /// `base64` string. Supported formats are [ImageFormat::JPEG], + /// [ImageFormat::PNG] and [ImageFormat::WEBP]. + /// + /// This method allows you to reuse the same StaticExporter instance + /// across multiple plots, which is more efficient than creating + /// a new one for each operation. + /// + /// For advanced usage (parallelism, exporter reuse, custom config), see the [plotly_static documentation](https://docs.rs/plotly_static/). + /// + /// # Arguments + /// + /// * `format` - The desired output image format + /// * `width` - The width of the output image in pixels + /// * `height` - The height of the output image in pixels + /// * `scale` - The scale factor for the image (1.0 = normal size) + /// + /// # Examples + /// + /// ```no_run + /// use plotly::{Plot, Scatter}; + /// use plotly::export::sync::ExporterSyncExt as _; + /// use plotly::plotly_static::{StaticExporterBuilder, ImageFormat}; + /// + /// let mut plot = Plot::new(); + /// plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); + /// + /// let mut exporter = StaticExporterBuilder::default() + /// .build() + /// .expect("Failed to create StaticExporter"); + /// + /// let base64_data = exporter.to_base64(&plot, ImageFormat::PNG, 800, 600, 1.0) + /// .expect("Failed to export plot"); + /// + /// exporter.close(); + /// ``` + fn to_base64( + &mut self, + plot: &Plot, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result>; + + /// Convert the `Plot` to SVG and return it as a String. + /// + /// This method allows you to reuse the same StaticExporter instance + /// across multiple plots, which is more efficient than creating + /// a new one for each operation. + /// + /// For advanced usage (parallelism, exporter reuse, custom config), see the [plotly_static documentation](https://docs.rs/plotly_static/). + /// + /// # Arguments + /// + /// * `width` - The width of the output image in pixels + /// * `height` - The height of the output image in pixels + /// * `scale` - The scale factor for the image (1.0 = normal size) + /// + /// # Examples + /// + /// ```no_run + /// use plotly::{Plot, Scatter}; + /// use plotly::export::sync::ExporterSyncExt as _; + /// use plotly::plotly_static::{StaticExporterBuilder, ImageFormat}; + /// + /// let mut plot = Plot::new(); + /// plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); + /// + /// let mut exporter = StaticExporterBuilder::default() + /// .build() + /// .expect("Failed to create StaticExporter"); + /// + /// let svg_data = exporter.to_svg(&plot, 800, 600, 1.0) + /// .expect("Failed to export plot"); + /// + /// exporter.close(); + /// ``` + fn to_svg( + &mut self, + plot: &Plot, + width: usize, + height: usize, + scale: f64, + ) -> Result>; + } + + impl ExporterSyncExt for plotly_static::StaticExporter { + fn write_image>( + &mut self, + plot: &Plot, + filename: P, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result<(), Box> { + self.write_fig( + filename.as_ref(), + &serde_json::to_value(plot)?, + format, + width, + height, + scale, + ) + } + + fn to_base64( + &mut self, + plot: &Plot, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result> { + match format { + ImageFormat::JPEG | ImageFormat::PNG | ImageFormat::WEBP => self.write_to_string( + &serde_json::to_value(plot)?, + format, + width, + height, + scale, + ), + _ => Err(format!( + "Cannot generate base64 string for ImageFormat:{format}. Allowed formats are JPEG, PNG, WEBP" + ) + .into()), + } + } + + fn to_svg( + &mut self, + plot: &Plot, + width: usize, + height: usize, + scale: f64, + ) -> Result> { + self.write_to_string( + &serde_json::to_value(plot)?, + ImageFormat::SVG, + width, + height, + scale, + ) + } + } +} + +#[cfg(feature = "plotly_static")] +pub mod r#async { + use std::path::Path; + + use async_trait::async_trait; + + use crate::{plot::Plot, ImageFormat}; + + /// Extension methods for exporting plots using an asynchronous exporter. + #[async_trait(?Send)] + pub trait ExporterAsyncExt { + /// Convert the `Plot` to a static image of the given format and save at + /// the given location using the asynchronous exporter. + /// + /// The exporter must have been built with the `build_async` method of + /// the StaticExporterBuilder. + /// + /// Functionally signature equivalent to the sync version in + /// [`crate::export::sync::ExporterSyncExt::write_image`], but meant for + /// async contexts. + /// + /// For more details see the [plotly_static documentation](https://docs.rs/plotly_static/). + async fn write_image>( + &mut self, + plot: &Plot, + filename: P, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result<(), Box>; + + /// Convert the `Plot` to a static image and return the image as a + /// `base64` string using the asynchronous exporter. + /// + /// The exporter must have been built with the `build_async` method of + /// the StaticExporterBuilder. + /// + /// Functionally signature equivalent to the sync version in + /// [`crate::export::sync::ExporterSyncExt::to_base64`], but meant for + /// async contexts. + /// + /// For more details see the [plotly_static documentation](https://docs.rs/plotly_static/). + async fn to_base64( + &mut self, + plot: &Plot, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result>; + + /// Convert the `Plot` to SVG and return it as a String using the + /// asynchronous exporter. + /// + /// Functionally signature equivalent to the sync version in + /// [`crate::export::sync::ExporterSyncExt::to_svg`], but meant for + /// async contexts. + /// + /// For more details see the [plotly_static documentation](https://docs.rs/plotly_static/). + async fn to_svg( + &mut self, + plot: &Plot, + width: usize, + height: usize, + scale: f64, + ) -> Result>; + } + + #[async_trait(?Send)] + impl ExporterAsyncExt for plotly_static::AsyncStaticExporter { + async fn write_image>( + &mut self, + plot: &Plot, + filename: P, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result<(), Box> { + self.write_fig( + filename.as_ref(), + &serde_json::to_value(plot)?, + format, + width, + height, + scale, + ) + .await + } + + async fn to_base64( + &mut self, + plot: &Plot, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result> { + match format { + ImageFormat::JPEG | ImageFormat::PNG | ImageFormat::WEBP => self + .write_to_string( + &serde_json::to_value(plot)?, + format, + width, + height, + scale, + ) + .await, + _ => Err(format!( + "Cannot generate base64 string for ImageFormat:{format}. Allowed formats are JPEG, PNG, WEBP" + ) + .into()), + } + } + + async fn to_svg( + &mut self, + plot: &Plot, + width: usize, + height: usize, + scale: f64, + ) -> Result> { + self.write_to_string( + &serde_json::to_value(plot)?, + ImageFormat::SVG, + width, + height, + scale, + ) + .await + } + } +} diff --git a/plotly/src/layout/rangebreaks.rs b/plotly/src/layout/rangebreaks.rs index 16470b31..43dcb57c 100644 --- a/plotly/src/layout/rangebreaks.rs +++ b/plotly/src/layout/rangebreaks.rs @@ -4,7 +4,7 @@ use serde::Serialize; use crate::private::NumOrString; /// Struct representing a rangebreak for Plotly axes. -/// See: https://plotly.com/python/reference/layout/xaxis/#layout-xaxis-rangebreaks +/// See: #[derive(Debug, Clone, Serialize, PartialEq, FieldSetter)] pub struct RangeBreak { /// Sets the lower and upper bounds for this range break, e.g. ["sat", diff --git a/plotly/src/layout/scene.rs b/plotly/src/layout/scene.rs index cd721e39..01cf5084 100644 --- a/plotly/src/layout/scene.rs +++ b/plotly/src/layout/scene.rs @@ -357,7 +357,7 @@ impl Rotation { pub struct Projection { #[serde(rename = "type")] projection_type: Option, - /// Sets the rotation of the map projection. See https://plotly.com/python/reference/layout/geo/#layout-geo-projection-rotation + // Sets the rotation of the map projection. See https://plotly.com/python/reference/layout/geo/#layout-geo-projection-rotation #[serde(rename = "rotation")] rotation: Option, } diff --git a/plotly/src/lib.rs b/plotly/src/lib.rs index a06f04d5..7caab75d 100644 --- a/plotly/src/lib.rs +++ b/plotly/src/lib.rs @@ -6,7 +6,7 @@ //! //! The `kaleido` and `kaleido_download` features are deprecated since version //! 0.13.0 and will be removed in version 0.14.0. Please migrate to the -//! `plotly_static` and `plotly_static_download` features instead. +//! `plotly_static` and `static_export_*` features instead. #![recursion_limit = "256"] // lets us use a large serde_json::json! macro for testing crate::layout::Axis extern crate askama; extern crate rand; @@ -49,6 +49,7 @@ pub mod callbacks; pub mod common; pub mod configuration; +pub mod export; pub mod layout; pub mod plot; pub mod traces; @@ -76,6 +77,16 @@ pub use plotly_kaleido::ImageFormat; #[cfg(feature = "plotly_static")] pub use plotly_static::{self, ImageFormat}; +// Public prelude for ergonomic imports in examples and user code +pub mod prelude { + #[cfg(feature = "plotly_static")] + pub use crate::export::r#async::ExporterAsyncExt; + #[cfg(feature = "plotly_static")] + pub use crate::export::sync::ExporterSyncExt; + #[cfg(feature = "plotly_static")] + pub use crate::plotly_static::ImageFormat; +} + // Not public API. #[doc(hidden)] mod private; diff --git a/plotly/src/plot.rs b/plotly/src/plot.rs index 130b75ea..26835bc1 100644 --- a/plotly/src/plot.rs +++ b/plotly/src/plot.rs @@ -518,8 +518,9 @@ impl Plot { /// **Note:** This method creates a new `StaticExporter` (and thus a new /// WebDriver instance) for each call, which is not performant for /// repeated operations. For better performance and resource management, - /// consider using `write_image_with_exporter` to reuse a single - /// `StaticExporter` instance across multiple operations. + /// consider using the [`ExporterSyncExt`] or [`ExporterAsyncExt`] extension + /// methods to reuse a single `StaticExporter` instance across multiple + /// operations. #[cfg(feature = "plotly_static")] pub fn write_image>( &self, @@ -529,10 +530,13 @@ impl Plot { height: usize, scale: f64, ) -> Result<(), Box> { + use crate::prelude::*; let mut exporter = plotly_static::StaticExporterBuilder::default() .build() .map_err(|e| format!("Failed to create StaticExporter: {e}"))?; - self.write_image_with_exporter(&mut exporter, filename, format, width, height, scale) + let result = exporter.write_image(self, filename, format, width, height, scale); + exporter.close(); + result } /// Convert the `Plot` to a static image and return the image as a `base64` @@ -545,10 +549,11 @@ impl Plot { /// /// /// **Note:** This method creates a new `StaticExporter` (and thus a new - /// WebDriver instance) for each call, which is not performant for - /// repeated operations. For better performance and resource management, - /// consider using `to_base64_with_exporter` to reuse a single - /// `StaticExporter` instance across multiple operations. + /// WebDriver instance) for each call, which is not performant for repeated + /// operations. For better performance and resource management, consider + /// using the [`ExporterSyncExt`] or [`ExporterAsyncExt`] extension methods + /// to reuse a single `StaticExporter` instance across multiple + /// operations. #[cfg(feature = "plotly_static")] pub fn to_base64( &self, @@ -557,10 +562,13 @@ impl Plot { height: usize, scale: f64, ) -> Result> { + use crate::prelude::*; let mut exporter = plotly_static::StaticExporterBuilder::default() .build() .map_err(|e| format!("Failed to create StaticExporter: {e}"))?; - self.to_base64_with_exporter(&mut exporter, format, width, height, scale) + let result = exporter.to_base64(self, format, width, height, scale); + exporter.close(); + result } /// Convert the `Plot` to SVG and return it as a String using plotly_static. @@ -571,8 +579,9 @@ impl Plot { /// **Note:** This method creates a new `StaticExporter` (and thus a new /// WebDriver instance) for each call, which is not performant for /// repeated operations. For better performance and resource management, - /// consider using `to_svg_with_exporter` to reuse a single - /// `StaticExporter` instance across multiple operations. + /// consider using the [`ExporterSyncExt`] or [`ExporterAsyncExt`] extension + /// methods to reuse a single `StaticExporter` instance across multiple + /// operations. #[cfg(feature = "plotly_static")] pub fn to_svg( &self, @@ -580,48 +589,19 @@ impl Plot { height: usize, scale: f64, ) -> Result> { + use crate::prelude::*; let mut exporter = plotly_static::StaticExporterBuilder::default() .build() .map_err(|e| format!("Failed to create StaticExporter: {e}"))?; - self.to_svg_with_exporter(&mut exporter, width, height, scale) + let result = exporter.to_svg(self, width, height, scale); + exporter.close(); + result } - /// Convert the `Plot` to a static image of the given image format and save - /// at the given location using a provided StaticExporter. - /// - /// This method allows you to reuse a StaticExporter instance across - /// multiple plots, which is more efficient than creating a new one for - /// each operation. - /// - /// This method requires the usage of the `plotly_static` crate using one of - /// the available feature flags. For advanced usage (parallelism, exporter reuse, custom config), see the [plotly_static documentation](https://docs.rs/plotly_static/). - /// - /// # Arguments - /// - /// * `exporter` - A mutable reference to a StaticExporter instance - /// * `filename` - The destination path for the output file - /// * `format` - The desired output image format - /// * `width` - The width of the output image in pixels - /// * `height` - The height of the output image in pixels - /// * `scale` - The scale factor for the image (1.0 = normal size) - /// - /// # Examples - /// - /// ```no_run - /// use plotly::{Plot, Scatter}; - /// use plotly_static::{StaticExporterBuilder, ImageFormat}; - /// - /// let mut plot = Plot::new(); - /// plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); - /// - /// let mut exporter = StaticExporterBuilder::default() - /// .build() - /// .expect("Failed to create StaticExporter"); - /// - /// // Export multiple plots using the same exporter - /// plot.write_image_with_exporter(&mut exporter, "plot1", ImageFormat::PNG, 800, 600, 1.0) - /// .expect("Failed to export plot"); - /// ``` + /// Deprecated: use [crate::export::sync::ExporterSyncExt::write_image]. + #[deprecated( + note = "Use exporter.write_image(&plot, ...) from plotly::export::sync::ExporterSyncExt" + )] #[cfg(feature = "plotly_static")] pub fn write_image_with_exporter>( &self, @@ -642,41 +622,10 @@ impl Plot { ) } - /// Convert the `Plot` to a static image and return the image as a `base64` - /// String using a provided StaticExporter. Supported formats are - /// [ImageFormat::JPEG], [ImageFormat::PNG] and [ImageFormat::WEBP]. - /// - /// This method allows you to reuse a StaticExporter instance across - /// multiple plots, which is more efficient than creating a new one for - /// each operation. - /// - /// This method requires the usage of the `plotly_static` crate using one of - /// the available feature flags. For advanced usage (parallelism, exporter reuse, custom config), see the [plotly_static documentation](https://docs.rs/plotly_static/). - /// - /// # Arguments - /// - /// * `exporter` - A mutable reference to a StaticExporter instance - /// * `format` - The desired output image format - /// * `width` - The width of the output image in pixels - /// * `height` - The height of the output image in pixels - /// * `scale` - The scale factor for the image (1.0 = normal size) - /// - /// # Examples - /// - /// ```no_run - /// use plotly::{Plot, Scatter}; - /// use plotly_static::{StaticExporterBuilder, ImageFormat}; - /// - /// let mut plot = Plot::new(); - /// plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); - /// - /// let mut exporter = StaticExporterBuilder::default() - /// .build() - /// .expect("Failed to create StaticExporter"); - /// - /// let base64_data = plot.to_base64_with_exporter(&mut exporter, ImageFormat::PNG, 800, 600, 1.0) - /// .expect("Failed to export plot"); - /// ``` + /// Deprecated: use [crate::export::sync::ExporterSyncExt::to_base64]. + #[deprecated( + note = "Use exporter.to_base64(&plot, ...) from plotly::export::sync::ExporterSyncExt" + )] #[cfg(feature = "plotly_static")] pub fn to_base64_with_exporter( &self, @@ -702,39 +651,10 @@ impl Plot { } } - /// Convert the `Plot` to SVG and return it as a String using a provided - /// StaticExporter. - /// - /// This method allows you to reuse a StaticExporter instance across - /// multiple plots, which is more efficient than creating a new one for - /// each operation. - /// - /// This method requires the usage of the `plotly_static` crate using one of - /// the available feature flags. For advanced usage (parallelism, exporter reuse, custom config), see the [plotly_static documentation](https://docs.rs/plotly_static/). - /// - /// # Arguments - /// - /// * `exporter` - A mutable reference to a StaticExporter instance - /// * `width` - The width of the output image in pixels - /// * `height` - The height of the output image in pixels - /// * `scale` - The scale factor for the image (1.0 = normal size) - /// - /// # Examples - /// - /// ```no_run - /// use plotly::{Plot, Scatter}; - /// use plotly_static::StaticExporterBuilder; - /// - /// let mut plot = Plot::new(); - /// plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); - /// - /// let mut exporter = StaticExporterBuilder::default() - /// .build() - /// .expect("Failed to create StaticExporter"); - /// - /// let svg_data = plot.to_svg_with_exporter(&mut exporter, 800, 600, 1.0) - /// .expect("Failed to export plot"); - /// ``` + /// Deprecated: use [crate::export::sync::ExporterSyncExt::to_svg]. + #[deprecated( + note = "Use exporter.to_svg(&plot, ...) from plotly::export::sync::ExporterSyncExt" + )] #[cfg(feature = "plotly_static")] pub fn to_svg_with_exporter( &self, @@ -900,7 +820,6 @@ impl PartialEq for Plot { #[cfg(test)] mod tests { use std::path::PathBuf; - use std::sync::atomic::{AtomicU32, Ordering}; #[cfg(feature = "kaleido")] use plotly_kaleido::ImageFormat; @@ -1065,12 +984,11 @@ mod tests { assert!(std::fs::remove_file(&dst).is_ok()); } - #[cfg(feature = "plotly_static")] // Helper to generate unique ports for parallel tests - static PORT_COUNTER: AtomicU32 = AtomicU32::new(4444); - #[cfg(feature = "plotly_static")] fn get_unique_port() -> u32 { + use std::sync::atomic::{AtomicU32, Ordering}; + static PORT_COUNTER: AtomicU32 = AtomicU32::new(5144); PORT_COUNTER.fetch_add(1, Ordering::SeqCst) } @@ -1091,6 +1009,7 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(&dst).is_ok()); + exporter.close(); } #[test] @@ -1110,6 +1029,7 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(&dst).is_ok()); + exporter.close(); } #[test] @@ -1129,6 +1049,7 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(&dst).is_ok()); + exporter.close(); } #[test] @@ -1156,6 +1077,7 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(&dst).is_ok()); + exporter.close(); } #[test] @@ -1175,6 +1097,7 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(&dst).is_ok()); + exporter.close(); } #[test] @@ -1200,6 +1123,7 @@ mod tests { // Limit the comparison to the first characters; // As image contents seem to be slightly inconsistent across platforms assert_eq!(expected_decoded[..2], result_decoded[..2]); + exporter.close(); } #[test] @@ -1221,6 +1145,7 @@ mod tests { // seem to contain uniquely generated IDs const LEN: usize = 10; assert_eq!(expected[..LEN], image_svg[..LEN]); + exporter.close(); } #[test] @@ -1261,5 +1186,6 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(&dst).is_ok()); + exporter.close(); } } diff --git a/plotly_static/Cargo.toml b/plotly_static/Cargo.toml index 6b43502f..0da576b1 100644 --- a/plotly_static/Cargo.toml +++ b/plotly_static/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotly_static" -version = "0.0.4" +version = "0.1.0" description = "Export Plotly graphs to static images using WebDriver" authors = ["Andrei Gherghescu andrei-ng@protonmail.com"] license = "MIT" diff --git a/plotly_static/README.md b/plotly_static/README.md index 27eaa6e9..7f70c286 100644 --- a/plotly_static/README.md +++ b/plotly_static/README.md @@ -8,6 +8,7 @@ Export Plotly plots to static images using WebDriver and headless browsers. ## Features +- **Async/Sync API Support**: Support for both async and sync contexts - **Multiple Formats**: PNG, JPEG, WEBP, SVG, PDF - **Browser Support**: Chrome/Chromium (chromedriver) and Firefox (geckodriver) - **Efficient**: Reuse `StaticExporter` instances for multiple exports @@ -56,7 +57,7 @@ Add to your `Cargo.toml`: ```toml [dependencies] -plotly_static = { version = "0.0.4", features = ["chromedriver", "webdriver_download"] } +plotly_static = { version = "0.1", features = ["chromedriver", "webdriver_download"] } serde_json = "1.0" ``` @@ -72,6 +73,22 @@ serde_json = "1.0" 2. **WebDriver**: Manually installed or automatically downloaded and installed with the `webdriver_download` feature 3. **Internet Connectivity**: Required for WebDriver download when using the auto-download and install feature +## Async Support + +The library supports async operations. To use the async API you need to call `build_async` instead of `build` on the `StaticExporterBuilder` . This will + return an `AsyncStaticExporter` instance where the `write_fig` and `write_to_string` methods are async. + + ```rust + use plotly_static::StaticExporterBuilder; + + let exporter = StaticExporterBuilder::default() + .build_async() + .expect("Failed to build AsyncStaticExporter"); + ``` + + Never use the `sync` API in `async` contexts. The `sync` API wraps the `async` API and uses a `tokio::runtime::Runtime` instance internally. Using the `sync` API in an async context will cause runtime errors such as e.g., "Cannot drop a runtime in a context where blocking is not allowed. This happens when a runtime is dropped from within an + asynchronous context." or similar ones. + ## Advanced Usage ### Static Exporter Reuse diff --git a/plotly_static/src/lib.rs b/plotly_static/src/lib.rs index f11c9432..b2235896 100644 --- a/plotly_static/src/lib.rs +++ b/plotly_static/src/lib.rs @@ -9,6 +9,7 @@ //! //! ## Features //! +//! - **Async/Sync API Support**: Support for both async and sync contexts //! - **Multiple Formats**: Support for PNG, JPEG, WEBP, SVG, and PDF export //! - **Headless Rendering**: Uses headless browsers for rendering //! - **WebDriver Support**: Supports both Chrome (chromedriver) and Firefox @@ -74,14 +75,38 @@ //! //! ```toml //! [dependencies] -//! plotly_static = { version = "0.0.4", features = ["chromedriver", "webdriver_download"] } +//! plotly_static = { version = "0.1", features = ["chromedriver", "webdriver_download"] } //! ``` //! +//! ## Async Support +//! +//! The library supports async operations. To use the async API you need to call +//! `build_async` instead of `build` on the `StaticExporterBuilder` . This will +//! return an `AsyncStaticExporter` instance where the `write_fig` and +//! `write_to_string` methods are async. +//! +//! ```no_run +//! use plotly_static::StaticExporterBuilder; +//! +//! let exporter = StaticExporterBuilder::default() +//! .build_async() +//! .expect("Failed to build AsyncStaticExporter"); +//! ``` +//! +//! Never use the `sync` API in async contexts. The `sync` API wraps the `async` +//! API and uses a `tokio::runtime::Runtime` instance internally. Using the +//! `sync` API in an async context will cause runtime errors such as e.g., +//! "Cannot drop a runtime in a context where blocking is not allowed. This +//! happens when a runtime is dropped from within an asynchronous context." or +//! similar ones. +//! //! ## Advanced Usage //! //! ### Custom Configuration //! //! ```no_run +//! // This example requires a running WebDriver (chromedriver/geckodriver) and a browser. +//! // It cannot be run as a doc test. //! use plotly_static::StaticExporterBuilder; //! //! let exporter = StaticExporterBuilder::default() @@ -191,11 +216,13 @@ //! - **Process Spawning**: Automatically spawns WebDriver if not already //! running //! - **Connection Reuse**: Reuses existing WebDriver sessions when possible -//! - **Cleanup**: Automatically terminates WebDriver processes when -//! `StaticExporter` is dropped //! - **External Sessions**: Can connect to externally managed WebDriver //! sessions //! +//! Due to the underlying WebDriver implementation, the library cannot +//! automatically close WebDriver processes when `StaticExporter` is dropped. +//! You must call `close` manually to ensure proper cleanup. +//! //! ### WebDriver Configuration //! //! Set the `WEBDRIVER_PATH` environment variable to specify a custom WebDriver @@ -231,8 +258,6 @@ //! - **Parallel Usage**: Use unique ports for parallel operations //! - **WebDriver Reuse**: The library automatically reuses WebDriver sessions //! when possible -//! - **Resource Cleanup**: WebDriver processes are automatically cleaned up on -//! drop //! //! ## Comparison with Kaleido //! @@ -581,10 +606,12 @@ impl StaticExporterBuilder { self } - /// Builds a `StaticExporter` instance with the current configuration. + /// Builds a synchronous `StaticExporter` instance with the current + /// configuration. /// - /// This method creates a new `StaticExporter` instance with all the - /// configured settings. The method manages WebDriver: + /// The synchronous API is blocking and should not be used in async + /// contexts. Use `build_async` instead and the associated + /// `AsyncStaticExporter` instance. /// /// - If `spawn_webdriver` is enabled, it first tries to connect to an /// existing WebDriver session on the specified port, and only spawns a @@ -599,7 +626,7 @@ impl StaticExporterBuilder { /// /// # Examples /// - /// ```rust + /// ```rust,no_run /// use plotly_static::StaticExporterBuilder; /// /// let exporter = StaticExporterBuilder::default() @@ -608,8 +635,6 @@ impl StaticExporterBuilder { /// .expect("Failed to build StaticExporter"); /// ``` pub fn build(&self) -> Result { - let wd = self.create_webdriver()?; - let runtime = std::sync::Arc::new( tokio::runtime::Builder::new_multi_thread() .enable_all() @@ -617,33 +642,74 @@ impl StaticExporterBuilder { .expect("Failed to create Tokio runtime"), ); - Ok(StaticExporter { + let inner = Self::build_async(self)?; + + Ok(StaticExporter { runtime, inner }) + } + + /// Create a new WebDriver instance based on the spawn_webdriver flag + fn create_webdriver(&self) -> Result { + let port = self.webdriver_port; + let in_async = tokio::runtime::Handle::try_current().is_ok(); + + let run_create_fn = |spawn: bool| -> Result { + let work = move || { + if spawn { + WebDriver::connect_or_spawn(port) + } else { + WebDriver::new(port) + } + }; + if in_async { + std::thread::spawn(work) + .join() + .map_err(|_| anyhow!("failed to join webdriver thread"))? + } else { + work() + } + }; + + run_create_fn(self.spawn_webdriver) + } + + /// Build an async exporter for use within async contexts. + /// + /// This method creates an `AsyncStaticExporter` instance with the current + /// configuration. The async API is non-blocking and can be used in async + /// contexts. + /// + /// # Examples + /// + /// ```rust,no_run + /// use plotly_static::StaticExporterBuilder; + /// + /// let exporter = StaticExporterBuilder::default() + /// .build_async() + /// .expect("Failed to build AsyncStaticExporter"); + /// ``` + pub fn build_async(&self) -> Result { + let wd = self.create_webdriver()?; + Ok(AsyncStaticExporter { webdriver_port: self.webdriver_port, webdriver_url: self.webdriver_url.clone(), webdriver: wd, offline_mode: self.offline_mode, pdf_export_timeout: self.pdf_export_timeout, webdriver_browser_caps: self.webdriver_browser_caps.clone(), - runtime, webdriver_client: None, }) } - - /// Create a new WebDriver instance based on the spawn_webdriver flag - fn create_webdriver(&self) -> Result { - match self.spawn_webdriver { - // Try to connect to existing WebDriver or spawn new if not available - true => WebDriver::connect_or_spawn(self.webdriver_port), - // Create the WebDriver instance without spawning - false => WebDriver::new(self.webdriver_port), - } - } } -/// Main struct for exporting Plotly plots to static images. +/// Synchronous exporter for exporting Plotly plots to static images. /// -/// This struct provides methods to convert Plotly JSON plots into various +/// This object provides methods to convert Plotly JSON plots into various /// static image formats using a headless browser via WebDriver. +/// The synchronous API is blocking and should not be used in async contexts. +/// Use `build_async` instead and the associated `AsyncStaticExporter` object. +/// +/// Always call `close` when you are done with the exporter to ensure proper +/// cleanup of the WebDriver process. /// /// # Examples /// @@ -678,6 +744,9 @@ impl StaticExporterBuilder { /// 600, /// 1.0 /// ).expect("Failed to export plot"); +/// +/// // Close the exporter +/// exporter.close(); /// ``` /// /// # Features @@ -688,58 +757,11 @@ impl StaticExporterBuilder { /// - Offline mode support /// - Automatic WebDriver management pub struct StaticExporter { - /// WebDriver server port (default: 4444) - webdriver_port: u32, - - /// WebDriver server base URL (default: "http://localhost") - webdriver_url: String, - - /// WebDriver process manager for spawning and cleanup - webdriver: WebDriver, - - /// Use bundled JS libraries instead of CDN - offline_mode: bool, - - /// PDF export timeout in milliseconds - pdf_export_timeout: u32, - - /// Browser command-line flags (e.g., "--headless", "--no-sandbox") - webdriver_browser_caps: Vec, - /// Tokio runtime for async operations runtime: std::sync::Arc, - /// Cached WebDriver client for session reuse - webdriver_client: Option, -} - -impl Drop for StaticExporter { - /// Automatically cleans up WebDriver resources when the `StaticExporter` - /// instance is dropped. - /// - /// This ensures that the WebDriver process is properly terminated and - /// resources are released, even if the instance goes out of scope - /// unexpectedly. - /// - /// - Only terminates WebDriver processes that were spawned by this instance - /// - Leaves externally managed WebDriver sessions running - /// - Logs errors but doesn't panic if cleanup fails - fn drop(&mut self) { - // Close the WebDriver client if it exists - if let Some(client) = self.webdriver_client.take() { - let runtime = self.runtime.clone(); - runtime.block_on(async { - if let Err(e) = client.close().await { - error!("Failed to close WebDriver client: {e}"); - } - }); - } - - // Stop the WebDriver process - if let Err(e) = self.webdriver.stop() { - error!("Failed to stop WebDriver: {e}"); - } - } + /// Async inner exporter + inner: AsyncStaticExporter, } impl StaticExporter { @@ -749,13 +771,17 @@ impl StaticExporter { /// browser and saves the result as an image file in the specified /// format. /// - /// Returns `Ok(())` on success, or an error if the export fails. + /// Returns `Ok()` on success, or an error if the export fails. + /// + /// The file extension is automatically added based on the format /// /// # Examples /// /// ```no_run + /// /// // This example requires a running WebDriver (chromedriver/geckodriver) and a browser. /// // It cannot be run as a doc test. + /// /// use plotly_static::{StaticExporterBuilder, ImageFormat}; /// use serde_json::json; /// use std::path::Path; @@ -767,6 +793,7 @@ impl StaticExporter { /// /// let mut exporter = StaticExporterBuilder::default().build().unwrap(); /// + /// // Creates "my_plot.png" with 1200x800 pixels at 2x scale /// exporter.write_fig( /// Path::new("my_plot"), /// &plot, @@ -775,14 +802,10 @@ impl StaticExporter { /// 800, /// 2.0 /// ).expect("Failed to export plot"); - /// // Creates "my_plot.png" with 1200x800 pixels at 2x scale - /// ``` - /// - /// # Notes /// - /// - The file extension is automatically added based on the format - /// - SVG format outputs plain text, others output binary data - /// - PDF format uses browser JavaScript for generation + /// // Close the exporter + /// exporter.close(); + /// ``` pub fn write_fig( &mut self, dst: &Path, @@ -792,42 +815,34 @@ impl StaticExporter { height: usize, scale: f64, ) -> Result<(), Box> { - let mut dst = PathBuf::from(dst); - dst.set_extension(format.to_string()); - - let plot_data = PlotData { - format: format.clone(), - width, - height, - scale, - data: plot, - }; - - let image_data = self.export(plot_data)?; - let data = match format { - ImageFormat::SVG => image_data.as_bytes(), - _ => &general_purpose::STANDARD.decode(image_data)?, - }; - let mut file = File::create(dst.as_path())?; - file.write_all(data)?; - file.flush()?; - - Ok(()) + if tokio::runtime::Handle::try_current().is_ok() { + return Err(anyhow!( + "StaticExporter sync methods cannot be used inside an async context. \ + Use StaticExporterBuilder::build_async() and the associated AsyncStaticExporter::write_fig(...)." + ) + .into()); + } + let rt = self.runtime.clone(); + rt.block_on( + self.inner + .write_fig(dst, plot, format, width, height, scale), + ) } /// Exports a Plotly plot to a string representation. /// - /// This method renders the provided Plotly JSON plot and returns the result - /// as a string. The format of the string depends on the image format: - /// - SVG: Returns plain SVG text - /// - PNG/JPEG/WEBP/PDF: Returns base64-encoded data + /// Renders the provided Plotly JSON plot and returns the result as a + /// string. or an error if the export fails. + /// + /// The format of the string depends on the image format. For + /// ImageFormat::SVG the function will generate plain SVG text, for + /// other formats it will return base64-encoded data. /// - /// Returns the image data as a string on success, or an error if the export - /// fails. /// /// # Examples /// /// ```no_run + /// /// // This example requires a running WebDriver (chromedriver/geckodriver) and a browser. /// // It cannot be run as a doc test. /// use plotly_static::{StaticExporterBuilder, ImageFormat}; @@ -848,17 +863,117 @@ impl StaticExporter { /// 1.0 /// ).expect("Failed to export plot"); /// + /// // Close the exporter + /// exporter.close(); + /// /// // svg_data contains the SVG markup as a string /// assert!(svg_data.starts_with(" Result> { + if tokio::runtime::Handle::try_current().is_ok() { + return Err(anyhow!( + "StaticExporter sync methods cannot be used inside an async context. \ + Use StaticExporterBuilder::build_async() and the associated AsyncStaticExporter::write_to_string(...)." + ) + .into()); + } + let rt = self.runtime.clone(); + rt.block_on( + self.inner + .write_to_string(plot, format, width, height, scale), + ) + } + + /// Get diagnostic information about the underlying WebDriver process. /// - /// # Notes + /// This method provides detailed information about the WebDriver process + /// for debugging purposes, including process status, port information, + /// and connection details. + pub fn get_webdriver_diagnostics(&self) -> String { + self.inner.get_webdriver_diagnostics() + } + + /// Explicitly close the WebDriver session and stop the driver. /// - /// - SVG format returns plain text that can be embedded in HTML - /// - Other formats return base64-encoded data that can be used in data URLs - /// - This method is useful when you need the image data as a string rather - /// than a file - pub fn write_to_string( + /// Always call close to ensure proper cleanup. + pub fn close(&mut self) { + let runtime = self.runtime.clone(); + runtime.block_on(self.inner.close()); + } +} + +/// Async StaticExporter for async contexts. Keeps the same API as the sync +/// StaticExporter for compatibility. +pub struct AsyncStaticExporter { + /// WebDriver server port (default: 4444) + webdriver_port: u32, + + /// WebDriver server base URL (default: "http://localhost") + webdriver_url: String, + + /// WebDriver process manager for spawning and cleanup + webdriver: WebDriver, + + /// Use bundled JS libraries instead of CDN + offline_mode: bool, + + /// PDF export timeout in milliseconds + pdf_export_timeout: u32, + + /// Browser command-line flags (e.g., "--headless", "--no-sandbox") + webdriver_browser_caps: Vec, + + /// Cached WebDriver client for session reuse + webdriver_client: Option, +} + +impl AsyncStaticExporter { + /// Exports a Plotly plot to a static image file + /// + /// Same as [`StaticExporter::write_fig`] but async. + pub async fn write_fig( + &mut self, + dst: &Path, + plot: &serde_json::Value, + format: ImageFormat, + width: usize, + height: usize, + scale: f64, + ) -> Result<(), Box> { + let mut dst = PathBuf::from(dst); + dst.set_extension(format.to_string()); + + let plot_data = PlotData { + format: format.clone(), + width, + height, + scale, + data: plot, + }; + + let image_data = self.static_export(&plot_data).await?; + let data = match format { + ImageFormat::SVG => image_data.as_bytes().to_vec(), + _ => general_purpose::STANDARD.decode(image_data)?, + }; + let mut file = File::create(dst.as_path())?; + file.write_all(&data)?; + file.flush()?; + + Ok(()) + } + + /// Exports a Plotly plot to a string representation. + /// + /// Same as [`StaticExporter::write_to_string`] but async. + pub async fn write_to_string( &mut self, plot: &serde_json::Value, format: ImageFormat, @@ -873,29 +988,47 @@ impl StaticExporter { scale, data: plot, }; - let image_data = self.export(plot_data)?; + let image_data = self.static_export(&plot_data).await?; Ok(image_data) } - /// Convert the Plotly graph to a static image using Kaleido and return the - /// result as a String - pub(crate) fn export(&mut self, plot: PlotData) -> Result { - let data = self.static_export(&plot)?; - Ok(data) + /// Close the WebDriver session and stop the driver if it was spawned. + /// + /// Always call close to ensure proper cleanup. + pub async fn close(&mut self) { + if let Some(client) = self.webdriver_client.take() { + if let Err(e) = client.close().await { + error!("Failed to close WebDriver client: {e}"); + } + } + if let Err(e) = self.webdriver.stop() { + error!("Failed to stop WebDriver: {e}"); + } + } + + /// Get diagnostic information about the underlying WebDriver process. + pub fn get_webdriver_diagnostics(&self) -> String { + self.webdriver.get_diagnostics() } - fn static_export(&mut self, plot: &PlotData<'_>) -> Result { + /// Export the Plotly plot image to a string representation calling the + /// Plotly.toImage function. + async fn static_export(&mut self, plot: &PlotData<'_>) -> Result { let html_content = template::get_html_body(self.offline_mode); - let runtime = self.runtime.clone(); - runtime - .block_on(self.extract(&html_content, plot)) + self.extract(&html_content, plot) + .await .with_context(|| "Failed to extract static image from browser session") } + /// Extract a static image from a browser session. async fn extract(&mut self, html_content: &str, plot: &PlotData<'_>) -> Result { let caps = self.build_webdriver_caps()?; - debug!("Use WebDriver and headless browser to export static plot"); - let webdriver_url = format!("{}:{}", self.webdriver_url, self.webdriver_port,); + debug!( + "Use WebDriver and headless browser to export static plot (offline_mode={}, port={})", + self.offline_mode, self.webdriver_port + ); + let webdriver_url = format!("{}:{}", self.webdriver_url, self.webdriver_port); + debug!("Connecting to WebDriver at {webdriver_url}"); // Reuse existing client or create new one let client = if let Some(ref client) = self.webdriver_client { @@ -926,6 +1059,19 @@ impl StaticExporter { // Open the HTML client.goto(&url).await?; + #[cfg(target_os = "windows")] + Self::wait_for_document_ready(&client, std::time::Duration::from_secs(10)).await?; + + // Wait for Plotly container element + #[cfg(target_os = "windows")] + Self::wait_for_plotly_container(&client, std::time::Duration::from_secs(10)).await?; + + // In online mode, ensure Plotly is loaded + if !self.offline_mode { + #[cfg(target_os = "windows")] + Self::wait_for_plotly_loaded(&client, std::time::Duration::from_secs(15)).await?; + } + let (js_script, args) = match plot.format { ImageFormat::PDF => { // Always use SVG for PDF export @@ -954,9 +1100,6 @@ impl StaticExporter { let data = client.execute_async(&js_script, args).await?; - // Don't close the client - keep it for reuse - // client.close().await?; - let result = data.as_str().ok_or(anyhow!( "Failed to execute Plotly.toImage in browser session" ))?; @@ -966,22 +1109,133 @@ impl StaticExporter { } match plot.format { - ImageFormat::SVG => Self::extract_plain(result, &plot.format), + ImageFormat::SVG => common::extract_plain(result, &plot.format), ImageFormat::PNG | ImageFormat::JPEG | ImageFormat::WEBP | ImageFormat::PDF => { - Self::extract_encoded(result, &plot.format) + common::extract_encoded(result, &plot.format) } #[allow(deprecated)] ImageFormat::EPS => { error!("EPS format is deprecated. Use SVG or PDF instead."); - Self::extract_encoded(result, &plot.format) + common::extract_encoded(result, &plot.format) + } + } + } + + fn build_webdriver_caps(&self) -> Result { + // Define browser capabilities (copied to avoid reordering existing code) + let mut caps = JsonMap::new(); + let mut browser_opts = JsonMap::new(); + let browser_args = self.webdriver_browser_caps.clone(); + + browser_opts.insert("args".to_string(), serde_json::json!(browser_args)); + + // Add Chrome binary capability if BROWSER_PATH is set + #[cfg(feature = "chromedriver")] + if let Ok(chrome_path) = std::env::var("BROWSER_PATH") { + browser_opts.insert("binary".to_string(), serde_json::json!(chrome_path)); + debug!("Added Chrome binary capability: {chrome_path}"); + } + // Add Firefox binary capability if BROWSER_PATH is set + #[cfg(feature = "geckodriver")] + if let Ok(firefox_path) = std::env::var("BROWSER_PATH") { + browser_opts.insert("binary".to_string(), serde_json::json!(firefox_path)); + debug!("Added Firefox binary capability: {firefox_path}"); + } + + // Add Firefox-specific preferences for CI environments + #[cfg(feature = "geckodriver")] + { + let prefs = common::get_firefox_ci_preferences(); + browser_opts.insert("prefs".to_string(), serde_json::json!(prefs)); + debug!("Added Firefox preferences for CI compatibility"); + } + + caps.insert( + "browserName".to_string(), + serde_json::json!(get_browser_name()), + ); + caps.insert( + get_options_key().to_string(), + serde_json::json!(browser_opts), + ); + + debug!("WebDriver capabilities: {caps:?}"); + + Ok(caps) + } + + #[cfg(target_os = "windows")] + async fn wait_for_document_ready(client: &Client, timeout: std::time::Duration) -> Result<()> { + let start = std::time::Instant::now(); + loop { + let state = client + .execute("return document.readyState;", vec![]) + .await + .unwrap_or(serde_json::Value::Null); + if state.as_str().map(|s| s == "complete").unwrap_or(false) { + return Ok(()); + } + if start.elapsed() > timeout { + return Err(anyhow!( + "Timeout waiting for document.readyState === 'complete'" + )); + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + } + + #[cfg(target_os = "windows")] + async fn wait_for_plotly_container( + client: &Client, + timeout: std::time::Duration, + ) -> Result<()> { + let start = std::time::Instant::now(); + loop { + let has_el = client + .execute( + "return !!document.getElementById('plotly-html-element');", + vec![], + ) + .await + .unwrap_or(serde_json::Value::Bool(false)); + if has_el.as_bool().unwrap_or(false) { + return Ok(()); + } + } + if start.elapsed() > timeout { + return Err(anyhow!( + "Timeout waiting for #plotly-html-element to appear in DOM" + )); + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + + #[cfg(target_os = "windows")] + async fn wait_for_plotly_loaded(client: &Client, timeout: std::time::Duration) -> Result<()> { + let start = std::time::Instant::now(); + loop { + let has_plotly = client + .execute("return !!window.Plotly;", vec![]) + .await + .unwrap_or(serde_json::Value::Bool(false)); + if has_plotly.as_bool().unwrap_or(false) { + return Ok(()); + } + if start.elapsed() > timeout { + return Err(anyhow!("Timeout waiting for Plotly library to load")); } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; } } +} + +mod common { + use super::*; - fn extract_plain(payload: &str, format: &ImageFormat) -> Result { + pub(crate) fn extract_plain(payload: &str, format: &ImageFormat) -> Result { match payload.split_once(",") { Some((type_info, data)) => { - Self::extract_type_info(type_info, format); + extract_type_info(type_info, format); let decoded = urlencoding::decode(data)?; Ok(decoded.to_string()) } @@ -989,18 +1243,18 @@ impl StaticExporter { } } - fn extract_encoded(payload: &str, format: &ImageFormat) -> Result { + pub(crate) fn extract_encoded(payload: &str, format: &ImageFormat) -> Result { match payload.split_once(";") { Some((type_info, encoded_data)) => { - Self::extract_type_info(type_info, format); - Self::extract_encoded_data(encoded_data) + extract_type_info(type_info, format); + extract_encoded_data(encoded_data) .ok_or(anyhow!("No valid image data found in 'src' attribute")) } None => Err(anyhow!("'src' attribute has invalid base64 data")), } } - fn extract_type_info(type_info: &str, format: &ImageFormat) { + pub(crate) fn extract_type_info(type_info: &str, format: &ImageFormat) { let val = type_info.split_once("/").map(|d| d.1.to_string()); match val { Some(ext) => { @@ -1012,7 +1266,7 @@ impl StaticExporter { } } - fn extract_encoded_data(data: &str) -> Option { + pub(crate) fn extract_encoded_data(data: &str) -> Option { data.split_once(",").map(|d| d.1.to_string()) } @@ -1021,7 +1275,7 @@ impl StaticExporter { /// These preferences force software rendering and enable WebGL in headless /// mode to work around graphics/WebGL issues in CI environments. #[cfg(feature = "geckodriver")] - fn get_firefox_ci_preferences() -> serde_json::Map { + pub(crate) fn get_firefox_ci_preferences() -> serde_json::Map { let mut prefs = serde_json::Map::new(); // Force software rendering and enable WebGL in headless mode @@ -1068,58 +1322,6 @@ impl StaticExporter { prefs } - - fn build_webdriver_caps(&self) -> Result { - // Define browser capabilities - let mut caps = JsonMap::new(); - let mut browser_opts = JsonMap::new(); - let browser_args = self.webdriver_browser_caps.clone(); - - browser_opts.insert("args".to_string(), serde_json::json!(browser_args)); - - // Add Chrome binary capability if BROWSER_PATH is set - #[cfg(feature = "chromedriver")] - if let Ok(chrome_path) = std::env::var("BROWSER_PATH") { - browser_opts.insert("binary".to_string(), serde_json::json!(chrome_path)); - debug!("Added Chrome binary capability: {chrome_path}"); - } - // Add Firefox binary capability if BROWSER_PATH is set - #[cfg(feature = "geckodriver")] - if let Ok(firefox_path) = std::env::var("BROWSER_PATH") { - browser_opts.insert("binary".to_string(), serde_json::json!(firefox_path)); - debug!("Added Firefox binary capability: {firefox_path}"); - } - - // Add Firefox-specific preferences for CI environments - #[cfg(feature = "geckodriver")] - { - let prefs = Self::get_firefox_ci_preferences(); - browser_opts.insert("prefs".to_string(), serde_json::json!(prefs)); - debug!("Added Firefox preferences for CI compatibility"); - } - - caps.insert( - "browserName".to_string(), - serde_json::json!(get_browser_name()), - ); - caps.insert( - get_options_key().to_string(), - serde_json::json!(browser_opts), - ); - - debug!("WebDriver capabilities: {caps:?}"); - - Ok(caps) - } - - /// Get diagnostic information about the underlying WebDriver process. - /// - /// This method provides detailed information about the WebDriver process - /// for debugging purposes, including process status, port information, - /// and connection details. - pub fn get_webdriver_diagnostics(&self) -> String { - self.webdriver.get_diagnostics() - } } #[cfg(test)] @@ -1134,12 +1336,29 @@ mod tests { } // Helper to generate unique ports for parallel tests - static PORT_COUNTER: AtomicU32 = AtomicU32::new(4444); - + #[cfg(not(feature = "debug"))] fn get_unique_port() -> u32 { + static PORT_COUNTER: AtomicU32 = AtomicU32::new(4844); PORT_COUNTER.fetch_add(1, Ordering::SeqCst) } + // In CI which may run on slow machines, we run a different strategy to generate + // the unique port. + #[cfg(feature = "debug")] + fn get_unique_port() -> u32 { + static PORT_COUNTER: AtomicU32 = AtomicU32::new(4844); + + // Sometimes the webdriver process is not stopped immediately + // and we get port conflicts. We try to give some time for other + // webdriver processes to stop so that we don't get port conflicts. + loop { + let p = PORT_COUNTER.fetch_add(1, Ordering::SeqCst); + if !webdriver::WebDriver::is_webdriver_running(p) { + return p; + } + } + } + fn create_test_plot() -> serde_json::Value { serde_json::to_value(serde_json::json!( { @@ -1208,13 +1427,13 @@ mod tests { init(); let test_plot = create_test_plot(); - let mut export = StaticExporterBuilder::default() + let mut exporter = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(get_unique_port()) .build() .unwrap(); let dst = PathBuf::from("static_example.png"); - export + exporter .write_fig(dst.as_path(), &test_plot, ImageFormat::PNG, 1200, 900, 4.5) .unwrap(); assert!(dst.exists()); @@ -1223,19 +1442,21 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close(); } #[test] fn save_jpeg() { init(); let test_plot = create_test_plot(); - let mut export = StaticExporterBuilder::default() + let mut exporter = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(get_unique_port()) .build() .unwrap(); let dst = PathBuf::from("static_example.jpeg"); - export + exporter .write_fig(dst.as_path(), &test_plot, ImageFormat::JPEG, 1200, 900, 4.5) .unwrap(); assert!(dst.exists()); @@ -1244,19 +1465,21 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close(); } #[test] fn save_svg() { init(); let test_plot = create_test_plot(); - let mut export = StaticExporterBuilder::default() + let mut exporter = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(get_unique_port()) .build() .unwrap(); let dst = PathBuf::from("static_example.svg"); - export + exporter .write_fig(dst.as_path(), &test_plot, ImageFormat::SVG, 1200, 900, 4.5) .unwrap(); assert!(dst.exists()); @@ -1265,19 +1488,21 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close(); } #[test] fn save_webp() { init(); let test_plot = create_test_plot(); - let mut export = StaticExporterBuilder::default() + let mut exporter = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(get_unique_port()) .build() .unwrap(); let dst = PathBuf::from("static_example.webp"); - export + exporter .write_fig(dst.as_path(), &test_plot, ImageFormat::WEBP, 1200, 900, 4.5) .unwrap(); assert!(dst.exists()); @@ -1286,6 +1511,35 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close(); + } + + #[tokio::test] + async fn save_png_async() { + init(); + let test_plot = create_test_plot(); + + let mut exporter = StaticExporterBuilder::default() + .spawn_webdriver(true) + .webdriver_port(5444) + .build_async() + .unwrap(); + + let dst = PathBuf::from("static_example_async.png"); + exporter + .write_fig(dst.as_path(), &test_plot, ImageFormat::PNG, 1200, 900, 4.5) + .await + .unwrap(); + + assert!(dst.exists()); + let metadata = std::fs::metadata(&dst).expect("Could not retrieve file metadata"); + let file_size = metadata.len(); + assert!(file_size > 0,); + #[cfg(not(feature = "debug"))] + assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close().await; } #[test] @@ -1317,20 +1571,22 @@ mod tests { assert!(file_size > 600000,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close(); } #[test] fn save_jpeg_sequentially() { init(); let test_plot = create_test_plot(); - let mut export = StaticExporterBuilder::default() + let mut exporter = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(get_unique_port()) .build() .unwrap(); let dst = PathBuf::from("static_example.jpeg"); - export + exporter .write_fig(dst.as_path(), &test_plot, ImageFormat::JPEG, 1200, 900, 4.5) .unwrap(); assert!(dst.exists()); @@ -1341,7 +1597,7 @@ mod tests { assert!(std::fs::remove_file(dst.as_path()).is_ok()); let dst = PathBuf::from("example2.jpeg"); - export + exporter .write_fig(dst.as_path(), &test_plot, ImageFormat::JPEG, 1200, 900, 4.5) .unwrap(); assert!(dst.exists()); @@ -1350,6 +1606,8 @@ mod tests { assert!(file_size > 0,); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst.as_path()).is_ok()); + + exporter.close(); } #[test] @@ -1364,7 +1622,7 @@ mod tests { let test_port = get_unique_port(); // Create first exporter - this should spawn a new WebDriver - let mut export1 = StaticExporterBuilder::default() + let mut exporter1 = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(test_port) .build() @@ -1372,16 +1630,17 @@ mod tests { // Export first image let dst1 = PathBuf::from("process_reuse_1.png"); - export1 + exporter1 .write_fig(dst1.as_path(), &test_plot, ImageFormat::PNG, 800, 600, 1.0) .unwrap(); assert!(dst1.exists()); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst1.as_path()).is_ok()); + exporter1.close(); // Create second exporter on the same port - this should connect to existing // WebDriver process (but create a new session) - let mut export2 = StaticExporterBuilder::default() + let mut exporter2 = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(test_port) .build() @@ -1389,16 +1648,17 @@ mod tests { // Export second image using a new session on the same WebDriver process let dst2 = PathBuf::from("process_reuse_2.png"); - export2 + exporter2 .write_fig(dst2.as_path(), &test_plot, ImageFormat::PNG, 800, 600, 1.0) .unwrap(); assert!(dst2.exists()); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst2.as_path()).is_ok()); + exporter2.close(); // Create third exporter on the same port - should also connect to existing // WebDriver process - let mut export3 = StaticExporterBuilder::default() + let mut exporter3 = StaticExporterBuilder::default() .spawn_webdriver(true) .webdriver_port(test_port) .build() @@ -1406,12 +1666,13 @@ mod tests { // Export third image using another new session on the same WebDriver process let dst3 = PathBuf::from("process_reuse_3.png"); - export3 + exporter3 .write_fig(dst3.as_path(), &test_plot, ImageFormat::PNG, 800, 600, 1.0) .unwrap(); assert!(dst3.exists()); #[cfg(not(feature = "debug"))] assert!(std::fs::remove_file(dst3.as_path()).is_ok()); + exporter3.close(); } } diff --git a/plotly_static/src/template.rs b/plotly_static/src/template.rs index b8e04a60..c83c24f9 100644 --- a/plotly_static/src/template.rs +++ b/plotly_static/src/template.rs @@ -233,7 +233,6 @@ pub(crate) fn html_body(js_source: &str) -> String { } /// Save the html file to a temporary file -#[allow(unused)] pub(crate) fn to_file(data: &str) -> Result { use std::env; // Set up the temp file with a unique filename. diff --git a/plotly_static/src/webdriver.rs b/plotly_static/src/webdriver.rs index 095c6e0e..fa6f2e1c 100644 --- a/plotly_static/src/webdriver.rs +++ b/plotly_static/src/webdriver.rs @@ -32,7 +32,7 @@ const WEBDRIVER_BIN: &str = "chromedriver"; /// Default WebDriver port pub(crate) const WEBDRIVER_PORT: u32 = 4444; /// Default WebDriver URL -pub(crate) const WEBDRIVER_URL: &str = "http://localhost"; +pub(crate) const WEBDRIVER_URL: &str = "http://127.0.0.1"; #[cfg(all(feature = "chromedriver", not(target_os = "windows")))] pub(crate) fn chrome_default_caps() -> Vec<&'static str> { @@ -608,7 +608,7 @@ impl WebDriver { /// Check if a WebDriver is already running on the specified port. /// - /// This method performs a WebDriver standard-compliant check by: + /// This method performs a WebDriver check by: /// 1. Making an HTTP GET request to `/status` endpoint /// 2. Checking for HTTP 200 response /// 3. Verifying the response contains "ready" indicating the service is