1use std::fmt::Write as _;
4use std::sync::Arc;
5
6use egui::{Color32, Pos2};
7
8use egui::{Context, Rect, Vec2};
9
10use super::axis::Transform;
11use super::scene::{self, Dash, Measure, Prim, Scene};
12use super::{Plot, PlotState, overlay};
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum ExportPreset {
18 #[default]
20 Screen,
21 HalfPage,
23 Letter,
25 Journal,
27}
28
29impl ExportPreset {
30 pub const fn size(self) -> [f32; 2] {
32 match self {
33 Self::Screen => [960.0, 540.0],
34 Self::HalfPage => [468.0, 360.0],
35 Self::Letter => [612.0, 792.0],
36 Self::Journal => [504.0, 360.0],
37 }
38 }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct ExportOptions {
44 pub width: f32,
46 pub height: f32,
48 pub scale: f32,
50 pub transparent: bool,
53}
54
55impl ExportOptions {
56 pub fn for_preset(preset: ExportPreset) -> Self {
58 let [width, height] = preset.size();
59 Self {
60 width,
61 height,
62 ..Self::default()
63 }
64 }
65}
66
67impl Default for ExportOptions {
68 fn default() -> Self {
69 Self {
70 width: 960.0,
71 height: 540.0,
72 scale: 2.0,
73 transparent: false,
74 }
75 }
76}
77
78const FONT_FAMILY: &str = "Ubuntu, 'Ubuntu Light', 'Segoe UI', 'Helvetica Neue', Arial, sans-serif";
81
82fn color(color: Color32) -> (String, f32) {
83 let [r, g, b, a] = color.to_srgba_unmultiplied();
84 (format!("#{r:02x}{g:02x}{b:02x}"), f32::from(a) / 255.0)
85}
86
87fn paint_attr(name: &str, value: Color32) -> String {
88 let (hex, alpha) = color(value);
89 if alpha <= 0.0 {
90 return format!(" {name}=\"none\"");
91 }
92 if alpha >= 0.999 {
93 format!(" {name}=\"{hex}\"")
94 } else {
95 format!(" {name}=\"{hex}\" {name}-opacity=\"{alpha:.3}\"")
96 }
97}
98
99fn escape(text: &str) -> String {
100 text.replace('&', "&")
101 .replace('<', "<")
102 .replace('>', ">")
103 .replace('"', """)
104}
105
106fn points(points: &[Pos2]) -> String {
107 let mut out = String::with_capacity(points.len() * 14);
108 for (index, point) in points.iter().enumerate() {
109 if index > 0 {
110 out.push(' ');
111 }
112 let _ = write!(out, "{:.2},{:.2}", point.x, point.y);
113 }
114 out
115}
116
117fn prim(out: &mut String, prim: &Prim) {
118 match prim {
119 Prim::Line {
120 points: line,
121 width,
122 color,
123 dash,
124 } => {
125 let dash = match dash {
126 Dash::Solid => String::new(),
127 Dash::Dashed(dash, gap) => format!(" stroke-dasharray=\"{dash:.2} {gap:.2}\""),
128 Dash::Dotted(spacing) => {
129 format!(" stroke-dasharray=\"0 {spacing:.2}\" stroke-linecap=\"round\"")
130 }
131 Dash::Marching { dash, gap, offset } => {
132 format!(" stroke-dasharray=\"{dash:.2} {gap:.2}\" stroke-dashoffset=\"{offset:.2}\"")
133 }
134 };
135 let _ = writeln!(
136 out,
137 "<polyline points=\"{}\" fill=\"none\"{} stroke-width=\"{width:.2}\" stroke-linejoin=\"round\"{dash}/>",
138 points(line),
139 paint_attr("stroke", *color),
140 );
141 }
142 Prim::Area {
143 points: line,
144 base_y,
145 color,
146 } => {
147 if let (Some(first), Some(last)) = (line.first(), line.last()) {
148 let mut polygon = line.clone();
149 polygon.push(Pos2::new(last.x, *base_y));
150 polygon.push(Pos2::new(first.x, *base_y));
151 let _ = writeln!(
152 out,
153 "<polygon points=\"{}\"{}/>",
154 points(&polygon),
155 paint_attr("fill", *color)
156 );
157 }
158 }
159 Prim::Polygon { points: shape, color } => {
160 let _ = writeln!(
161 out,
162 "<polygon points=\"{}\"{}/>",
163 points(shape),
164 paint_attr("fill", *color)
165 );
166 }
167 Prim::Quad { points: shape, color } => {
168 let _ = writeln!(
169 out,
170 "<polygon points=\"{}\"{}/>",
171 points(shape),
172 paint_attr("fill", *color)
173 );
174 }
175 Prim::Fan {
176 center,
177 points: shape,
178 color,
179 } => {
180 let mut polygon = Vec::with_capacity(shape.len() + 1);
181 polygon.push(*center);
182 polygon.extend_from_slice(shape);
183 let _ = writeln!(
184 out,
185 "<polygon points=\"{}\"{}/>",
186 points(&polygon),
187 paint_attr("fill", *color)
188 );
189 }
190 Prim::Rect {
191 rect,
192 radius,
193 fill,
194 stroke,
195 } => {
196 let inset = stroke.map_or(0.0, |(width, _)| width * 0.5);
198 let rect = rect.shrink(inset);
199 let stroke = stroke.map_or_else(String::new, |(width, color)| {
200 format!("{} stroke-width=\"{width:.2}\"", paint_attr("stroke", color))
201 });
202 let _ = writeln!(
203 out,
204 "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" rx=\"{radius:.2}\"{}{stroke}/>",
205 rect.left(),
206 rect.top(),
207 rect.width().max(0.0),
208 rect.height().max(0.0),
209 paint_attr("fill", *fill),
210 );
211 }
212 Prim::Circle {
213 center,
214 radius,
215 fill,
216 stroke,
217 } => {
218 let stroke = stroke.map_or_else(String::new, |(width, color)| {
219 format!("{} stroke-width=\"{width:.2}\"", paint_attr("stroke", color))
220 });
221 let _ = writeln!(
222 out,
223 "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{radius:.2}\"{}{stroke}/>",
224 center.x,
225 center.y,
226 paint_attr("fill", *fill),
227 );
228 }
229 Prim::Text {
230 pos,
231 text,
232 size,
233 color,
234 baseline,
235 angle,
236 } => {
237 let transform = if *angle == 0.0 {
238 String::new()
239 } else {
240 format!(
241 " transform=\"rotate({:.3} {:.2} {:.2})\"",
242 angle.to_degrees(),
243 pos.x,
244 pos.y
245 )
246 };
247 let _ = writeln!(
248 out,
249 "<text xml:space=\"preserve\" x=\"{:.2}\" y=\"{:.2}\" font-size=\"{size:.2}\"{}{transform}>{}</text>",
250 pos.x,
251 pos.y + baseline,
252 paint_attr("fill", *color),
253 escape(text),
254 );
255 }
256 }
257}
258
259pub(super) fn svg(scene: &Scene, canvas: Option<Color32>) -> String {
261 let (width, height) = (scene.size.x, scene.size.y);
262 let mut out = String::with_capacity(64 * 1024);
263 let _ = writeln!(
264 out,
265 "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width:.0}\" height=\"{height:.0}\" \
266 viewBox=\"0 0 {width:.2} {height:.2}\" font-family=\"{FONT_FAMILY}\" font-weight=\"300\">"
267 );
268 let frame = scene.frame;
269 let _ = writeln!(
270 out,
271 "<defs><clipPath id=\"plot-frame\"><rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\"/></clipPath></defs>",
272 frame.left(),
273 frame.top(),
274 frame.width(),
275 frame.height()
276 );
277 if let Some(canvas) = canvas {
278 let _ = writeln!(
279 out,
280 "<rect width=\"100%\" height=\"100%\"{}/>",
281 paint_attr("fill", canvas)
282 );
283 }
284 for primitive in &scene.under {
285 prim(&mut out, primitive);
286 }
287 out.push_str("<g clip-path=\"url(#plot-frame)\">\n");
288 for primitive in &scene.data {
289 prim(&mut out, primitive);
290 }
291 out.push_str("</g>\n");
292 for primitive in &scene.over {
293 prim(&mut out, primitive);
294 }
295 out.push_str("</svg>\n");
296 out
297}
298
299const MAX_PIXELS: u64 = 100_000_000;
301
302pub(super) fn png(svg: &str, scale: f32) -> Result<Vec<u8>, String> {
305 let mut options = usvg::Options::default();
306 {
307 let database = Arc::make_mut(&mut options.fontdb);
308 for data in egui::FontDefinitions::default().font_data.values() {
309 database.load_font_data((*data.font).as_ref().to_vec());
310 }
311 }
312 options.font_family = "Ubuntu".to_owned();
313 let tree = usvg::Tree::from_str(svg, &options).map_err(|error| format!("invalid SVG: {error}"))?;
314 let size = tree.size();
315 let scale = scale.clamp(0.25, 8.0);
316 let width = (size.width() * scale).round().max(1.0) as u32;
317 let height = (size.height() * scale).round().max(1.0) as u32;
318 if u64::from(width) * u64::from(height) > MAX_PIXELS {
320 return Err("the image is too large".to_owned());
321 }
322 let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height).ok_or("the image is too large")?;
323 resvg::render(
324 &tree,
325 resvg::tiny_skia::Transform::from_scale(scale, scale),
326 &mut pixmap.as_mut(),
327 );
328 pixmap
329 .encode_png()
330 .map_err(|error| format!("PNG encoding failed: {error}"))
331}
332
333impl Plot<'_> {
334 fn export_scene(
336 &self,
337 ctx: &Context,
338 state: &PlotState,
339 options: &ExportOptions,
340 ) -> (scene::Scene, Option<Color32>) {
341 let measure = Measure {
342 ctx: ctx.clone(),
343 pixels_per_point: 1.0,
344 };
345 let rect = Rect::from_min_size(
346 Pos2::ZERO,
347 Vec2::new(options.width.max(120.0), options.height.max(120.0)),
348 );
349 let view = state.view.unwrap_or_else(|| self.auto_bounds(state));
350 let y2 = self.second_axis(state);
351 let mode = self.chart_mode();
352 let layout = overlay::layout(&measure, &self.config, rect, view, y2, mode);
353 let transform = Transform {
354 frame: layout.frame,
355 view,
356 x_scale: self.config.x.scale,
357 y_scale: self.config.y.scale,
358 y2,
359 };
360 let visuals = ctx.style_of(ctx.theme()).visuals.clone();
361 let mut colors = overlay::Colors::resolve(&self.config, &visuals);
362 let canvas = if options.transparent {
363 colors.canvas.take()
364 } else {
365 Some(colors.canvas.take().unwrap_or(visuals.panel_fill))
366 };
367 let theme = crisol_ui_kit::theme::current(ctx);
368 let mut scene = overlay::build_scene(
369 &measure, self, &layout, &transform, state, &colors, &theme, true, mode, 0.0, false, false,
370 );
371 super::annotations::paint(&mut scene.data, &transform, &state.annotations, &theme);
372 (scene, canvas)
373 }
374
375 pub fn to_svg(&self, ctx: &Context, state: &PlotState, options: &ExportOptions) -> String {
378 let (scene, canvas) = self.export_scene(ctx, state, options);
379 svg(&scene, canvas)
380 }
381
382 pub fn to_pdf(&self, ctx: &Context, state: &PlotState, options: &ExportOptions) -> Vec<u8> {
384 let (scene, _) = self.export_scene(ctx, state, options);
385 super::pdf::write(&scene, options)
386 }
387
388 pub fn to_png(&self, ctx: &Context, state: &PlotState, options: &ExportOptions) -> Result<Vec<u8>, String> {
394 png(&self.to_svg(ctx, state, options), options.scale)
395 }
396}