plox 0.3.7

Turn messy logs into clean graphs. Plot fields or regex matches over time, mark events, count occurrences — all from your terminal.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! This module handles the creation of gnuplot scripts and graph images.
//!
//! It generates scripts for gnuplot to produce visual representations based on
//! resolved configurations and parsed data. Additionally, it manages the execution
//! of gnuplot and the saving of resulting graph images.

use crate::{
	graph_config::{
		AxisScale, Color, DashStyle, GraphFullContext, MarkerType, OutputFilePaths, PlotStyle,
		YAxis,
	},
	logging::APPV,
	resolved_graph_config::{ResolvedGraphConfig, ResolvedLine},
};
use std::{
	fs::File,
	io::{self, Write},
	path::{Path, PathBuf},
	process::{Command, ExitStatus},
};
use tracing::{debug, info, warn};

const LOG_TARGET: &str = "gnuplot";

#[derive(Debug, thiserror::Error)]
pub enum Error {
	#[error("I/O error: {0}")]
	IoError(#[from] io::Error),
	#[error("CSV data files not resolved properly (internal bug) for line: {0:#?}")]
	CvsFilesResolutionError(Box<ResolvedLine>),
	#[error("Looks like '{0}' command is not available: {1}")]
	GnuplotCommandNotAvailable(String, io::Error),
	#[error("gnuplot execution error: '{0}' / {1}")]
	GnuplotExecution(String, io::Error),
	#[error("gnuplot non-zero exit code: '{0}', stdout:'{1}', stderr:'{2}")]
	GnuplotNonZeroExitCode(ExitStatus, String, String),
	#[error("Error while creating gnuplot script '{0}': {1}")]
	ScriptCreationError(PathBuf, io::Error),
	#[error("Incorrect input files (this is bug).")]
	IncorrectOutputFiles,
	#[error("Parsing log error: {0} (this is bug?)")]
	ParsingLogError(#[from] crate::process_log::Error),
}

impl MarkerType {
	/// Returns the gnuplot marker specification, e.g., `pt 7`.
	pub fn to_gnuplot(&self) -> &'static str {
		match self {
			MarkerType::Dot => "pt 7",
			MarkerType::Plus => "pt 1",
			MarkerType::Cross => "pt 3",
			MarkerType::Circle => "pt 6",
			MarkerType::Triangle => "pt 8",
			MarkerType::TriangleFilled => "pt 9",
			MarkerType::Square => "pt 4",
			MarkerType::SquareFilled => "pt 5",
			MarkerType::Diamond => "pt 12",
			MarkerType::DiamondFilled => "pt 13",
			MarkerType::X => "pt 2",
		}
	}
}

impl Color {
	/// Returns the gnuplot color specification, e.g. `lc rgb "red"`.
	pub fn to_gnuplot(&self) -> &'static str {
		match self {
			Color::Red => "lc rgb \"red\"",
			Color::Blue => "lc rgb \"blue\"",
			Color::Green => "lc rgb \"green\"",
			Color::Orange => "lc rgb \"orange\"",
			Color::Purple => "lc rgb \"purple\"",
			Color::Cyan => "lc rgb \"cyan\"",
			Color::Magenta => "lc rgb \"magenta\"",
			Color::Goldenrod => "lc rgb \"goldenrod\"",
			Color::Brown => "lc rgb \"brown\"",
			Color::Olive => "lc rgb \"olive\"",
			Color::Navy => "lc rgb \"navy\"",
			Color::DarkGreen => "lc rgb \"dark-green\"",
			Color::DarkOrange => "lc rgb \"dark-orange\"",
			Color::Violet => "lc rgb \"violet\"",
			Color::Coral => "lc rgb \"coral\"",
			Color::Salmon => "lc rgb \"salmon\"",
			Color::SteelBlue => "lc rgb \"steelblue\"",
			Color::DarkMagenta => "lc rgb \"dark-magenta\"",
			Color::DarkCyan => "lc rgb \"dark-cyan\"",
			Color::DarkYellow => "lc rgb \"dark-yellow\"",
			Color::DarkTurquoise => "lc rgb \"dark-turquoise\"",
			Color::Yellow => "lc rgb \"yellow\"",
			Color::Black => "lc rgb \"black\"",
		}
	}
}

impl PlotStyle {
	/// Returns the gnuplot style snippet, e.g. `"with linespoints"`
	pub fn to_gnuplot(&self) -> &'static str {
		match self {
			PlotStyle::Lines => "with lines",
			PlotStyle::Steps => "with steps",
			PlotStyle::Points => "with points",
			PlotStyle::LinesPoints => "with linespoints",
		}
	}
}
impl DashStyle {
	/// Returns the gnuplot dash (line type) snippet, e.g. `"lt 2"`
	pub fn to_gnuplot(&self) -> &'static str {
		match self {
			DashStyle::Solid => "dt 1",
			DashStyle::Dashed => "dt 2",
			DashStyle::Dotted => "dt 3",
			DashStyle::DashDot => "dt 4",
			DashStyle::LongDash => "dt 5",
		}
	}
}

use strum::IntoEnumIterator;

#[derive(Debug, Clone, Copy)]
struct Style {
	color: Color,
	dash: DashStyle,
	marker: MarkerType,
}

impl Style {
	pub fn line_style(&self, i: usize) -> String {
		format!(
			"set linetype {} {} {} {} lw 2.0 ps 4.0",
			i,
			self.color.to_gnuplot(),
			self.dash.to_gnuplot(),
			self.marker.to_gnuplot()
		)
	}
}

fn build_default_styles() -> Vec<Style> {
	let mut styles = Vec::new();
	for dash in DashStyle::iter() {
		for (color, marker) in Color::iter().zip(MarkerType::iter().cycle()) {
			styles.push(Style { color, dash, marker });
		}
	}
	styles
}

/// Write a gnuplot script to the given output path based on the graph configuration.
///
/// # Arguments
/// * `config` - The full graph configuration (panels and lines).
/// * `output_script_path` - The path where the .gnu file will be written.
/// * `output_image_path` - The path to the output PNG file.
pub fn write_gnuplot_script(
	config: &ResolvedGraphConfig,
	context: &GraphFullContext,
	output_script_path: &PathBuf,
	output_image_path: &Path,
) -> Result<(), Error> {
	let mut file = File::create(output_script_path)
		.map_err(|e| Error::ScriptCreationError(output_script_path.clone(), e))?;
	let num_non_empty_panels = config.panels.iter().filter(|p| !p.is_empty()).count();
	let plot_margin = 0.005;
	let plot_height = 1.0 / num_non_empty_panels as f64 - plot_margin;

	let has_multiple_input_files = context.input().len() > 1;

	//write to gnuplot script wrapper
	macro_rules! gpwr {
	    ($dst:expr, $($arg:tt)*) => ({
	        writeln!($dst, $($arg)*).map_err(|e| Error::ScriptCreationError(output_script_path.clone(),e))
	    });
	}

	gpwr!(file, "set terminal pngcairo enhanced font 'arial,10' fontscale 3.0 size 7560, 5500")?;
	gpwr!(file, "set output '{}'", output_image_path.display())?;

	{
		let styles = build_default_styles().into_iter().take(20);
		for (i, style) in styles.enumerate() {
			gpwr!(file, "{}", style.line_style(i + 1))?;
		}
	}

	gpwr!(file, "set datafile separator ','")?;
	gpwr!(file, "set xdata time")?;
	gpwr!(file, "set timefmt '%Y-%m-%dT%H:%M:%S'")?;
	gpwr!(file, "set format x '%H:%M:%S'")?;
	gpwr!(file, "set mxtics 10")?;
	gpwr!(file, "set grid xtics mxtics")?;
	gpwr!(file, "set grid ytics mytics")?;
	gpwr!(file, "set ytics nomirror")?;
	gpwr!(file, "set key noenhanced")?;
	gpwr!(file, "set multiplot")?;
	gpwr!(file, "set lmargin at screen 0.035")?;
	gpwr!(file, "set rmargin at screen 0.975")?;

	gpwr!(file, "combine_datetime(date_col,time_col) = strcol(date_col) . 'T' . strcol(time_col)")?;

	let mut i = 0;
	for panel in config.panels.iter().rev() {
		debug!(target:LOG_TARGET,"drawing: {:#?}",panel);
		if panel.is_empty() {
			continue;
		}

		let y_position = plot_height * i as f64;
		i += 1;
		gpwr!(file, "set origin 0.0,{}", y_position)?;
		gpwr!(file, "set size 1.0,{}", plot_height)?;
		gpwr!(file, "unset label")?;
		{
			let mut x = -0.03;
			for (i, title_line) in panel.title().into_iter().enumerate() {
				let font = if i == 0 { "arial bold,10" } else { "arial,8" };
				gpwr!(
					file,
					"set label '{title_line}' at graph {x},0.5 rotate by 90 center font\"{font}\" noenhanced",
				)?;
				x += 0.005;
			}
		}

		match panel.params.yaxis_scale {
			Some(AxisScale::Linear) | None => gpwr!(file, "unset logscale y")?,
			Some(AxisScale::Log) => gpwr!(file, "set logscale y 10")?,
		}

		if panel.lines.iter().any(|line| matches!(line.line.params.yaxis, Some(YAxis::Y2))) {
			gpwr!(file, "set y2tics nomirror")?;
			gpwr!(file, "set my2tics 10")?;
		};

		if let Some((start, end)) = panel.time_range {
			let format = "%Y-%m-%dT%H:%M:%S"; // must match `set timefmt`
			gpwr!(file, "set xrange [\"{}\":\"{}\"]", start.format(format), end.format(format))?;
		}

		let mut non_empty_lines = vec![];
		for (j, line) in panel.lines.iter().enumerate() {
			let has_data_points = if let Some((start, end)) = panel.time_range {
				let has_data_points = line.has_data_points_in_time_range(start, end)?;
				if !has_data_points {
					warn!(target:APPV,
						input_file = ?line.source_file_name().display(),
						guard = ?line.guard(),
						regex = line.regex_pattern(),
						"No data points in given range.");
				}
				has_data_points
			} else {
				!line.is_empty()
			};
			if has_data_points {
				let csv_data_path = line
					.shared_csv_filename()
					.ok_or(Error::CvsFilesResolutionError(Box::new(line.clone())))?;
				gpwr!(file, "csv_data_file_{j:04} = '{}'", csv_data_path.display())?;
				non_empty_lines.push((j, line));
			}
		}

		if !non_empty_lines.is_empty() {
			gpwr!(file, "plot \\")?;
		} else if let Some((start, end)) = panel.time_range {
			warn!(target:APPV,
				title = ?panel.title(),
				?start,
				?end,
				"No data points in given range for panel.");
		} else {
			warn!(target:APPV,
				title = ?panel.title(),
				"No data points for panel.");
		};
		for (idx, (line_index, line)) in non_empty_lines.iter().enumerate() {
			let mut style_parts: Vec<String> = Vec::new();

			style_parts.push(line.line.params.style.to_gnuplot().into());
			if let Some(dash_style) = &line.line.params.dash_style {
				style_parts.push(dash_style.to_gnuplot().into());
			}

			if let Some(line_width) = &line.line.params.line_width {
				style_parts.push(format!("lw {}", line_width));
			}

			if let Some(color) = &line.line.params.line_color {
				style_parts.push(color.to_gnuplot().into());
			}

			if matches!(line.line.params.style, PlotStyle::LinesPoints | PlotStyle::Points) {
				if let Some(marker) = &line.line.params.marker_type {
					style_parts.push(marker.to_gnuplot().into());
				}
				style_parts.push(format!("ps {}", line.line.params.marker_size));

				if let Some(mcol) = &line.line.params.marker_color {
					style_parts.push(mcol.to_gnuplot().into());
				}
			}

			let axis = match line.line.params.yaxis.as_ref().unwrap_or(&YAxis::Y) {
				YAxis::Y2 => "axes x1y2",
				YAxis::Y => "axes x1y1",
			};
			style_parts.push(axis.into());

			let style = if style_parts.is_empty() {
				"with lines axes x1y1".to_string()
			} else {
				style_parts.join(" ")
			};

			write!(
				file,
				"   csv_data_file_{line_index:04} using (combine_datetime('date','time')):'{}' {} title '{}'",
				line.csv_data_column_for_plot(),
				style,
				line.title(has_multiple_input_files),
			)?;

			if idx != non_empty_lines.len() - 1 {
				gpwr!(file, ", \\")?;
			} else {
				gpwr!(file, "")?;
			}
		}
		gpwr!(file, "unset y2tics")?;
		gpwr!(file, "unset my2tics")?;
	}

	gpwr!(file, "unset multiplot")?;
	Ok(())
}

fn path_to_display(path: &Path) -> &Path {
	let Ok(cwd) = std::env::current_dir() else {
		return path;
	};
	path.strip_prefix(&cwd).unwrap_or(path)
}

/// Write gnuplot script and immediately execute it with `gnuplot`.
pub fn run_gnuplot(config: &ResolvedGraphConfig, context: &GraphFullContext) -> Result<(), Error> {
	let OutputFilePaths::Gnuplot((image_path, script_path)) = context.get_graph_output_path()
	else {
		return Err(Error::IncorrectOutputFiles);
	};

	write_gnuplot_script(config, context, &script_path, &image_path)?;
	let script_path = if context.output_graph_ctx.display_absolute_paths {
		script_path
	} else {
		path_to_display(&script_path).to_path_buf()
	};
	info!(target:APPV,"Script saved: {}", script_path.display());

	if std::env::var("PLOX_SKIP_GNUPLOT").is_ok() {
		info!(target:APPV, "PLOX_SKIP_GNUPLOT is set, skipping gnuplot execution and image generation.");
		return Ok(());
	}

	const GNUPLOT_CMD: &str = "gnuplot";

	Command::new(GNUPLOT_CMD)
		.output()
		.map_err(|e| Error::GnuplotCommandNotAvailable(GNUPLOT_CMD.into(), e))?;

	let output = Command::new(GNUPLOT_CMD).arg(&script_path).output()?;

	if !output.status.success() {
		return Err(Error::GnuplotNonZeroExitCode(
			output.status,
			String::from_utf8_lossy(&output.stdout).to_string(),
			String::from_utf8_lossy(&output.stderr).to_string(),
		));
	}

	let image_path = if context.output_graph_ctx.display_absolute_paths {
		image_path
	} else {
		path_to_display(&image_path).to_path_buf()
	};
	info!(target:APPV,"Image  saved: {}", image_path.display());

	if !output.stdout.is_empty() {
		debug!(target:APPV,"--- gnuplot stdout ---");
		debug!(target:APPV,"\n{}", String::from_utf8_lossy(&output.stdout));
	}

	if !output.stderr.is_empty() {
		debug!(target:APPV,"--- gnuplot stderr ---");
		debug!(target:APPV,"\n{}", String::from_utf8_lossy(&output.stderr));
	}

	let do_not_open =
		context.output_graph_ctx.do_not_display || std::env::var("PLOX_DO_NOT_DISPLAY").is_ok();

	if !do_not_open {
		let cmd = if let Ok(viewer_cmd_path) = std::env::var("PLOX_IMAGE_VIEWER") {
			Some(Command::new(viewer_cmd_path))
		} else {
			#[cfg(target_os = "linux")]
			{
				Some(Command::new("xdg-open"))
			}
			#[cfg(not(target_os = "linux"))]
			{
				None
			}
		};

		if let Some(mut cmd) = cmd {
			cmd.arg(image_path);
			if let Err(e) = cmd.status() {
				warn!(target:APPV,"Displaying image with command: '{cmd:?}' failed {e}.");
			}
		};
	} else {
		debug!(target:APPV,"Displaying image disabled.");
	}
	Ok(())
}