Sources/OrgPrograms/Gnuplot.swift
49 lines · 2957 bytes
1#if os(macOS)
2import Foundation
3import OrgApp
4import OrgCore
5
6extension PlotOutput {
7 /// gnuplot on the `PATH` Babel uses, when installed.
8 public static var gnuplot: URL? {
9 let path = BabelRunner.environment["PATH"] ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
10 return path.split(separator: ":").map { URL(fileURLWithPath: String($0)).appendingPathComponent("gnuplot") }
11 .first { FileManager.default.isExecutableFile(atPath: $0.path) }
12 }
13
14 /// `org-plot/gnuplot` through gnuplot: the data file and script org-plot writes, run with
15 /// the output at `file:`, or a PNG for showing when there's none. Returns the image.
16 public static func runGnuplot(_ plot: TablePlot.Plot, directory: URL?, gnuplot: URL) async throws -> URL {
17 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
18 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
19 let dataFile = folder.appendingPathComponent("data.tsv")
20 var plot = plot
21 let output = file(plot, directory: directory) ?? folder.appendingPathComponent("plot.png")
22 if plot.options.file == nil { plot.options.values["file"] = .string(output.path) }
23 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), [])
24 try data.write(to: dataFile, atomically: true, encoding: .utf8)
25 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels)
26 if let custom = plot.options["script"]?.description {
27 let path = OrgPaths.expandingTilde(custom)
28 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
29 guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") }
30 script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true)
31 + "\n" + text.replacingOccurrences(of: "$datafile", with: dataFile.path)
32 }
33 let scriptFile = folder.appendingPathComponent("plot.gp")
34 try script.write(to: scriptFile, atomically: true, encoding: .utf8)
35 let process = Process()
36 process.executableURL = gnuplot
37 process.arguments = [scriptFile.path]
38 process.currentDirectoryURL = directory
39 let errors = Pipe()
40 process.standardError = errors
41 try process.run()
42 while process.isRunning { try await Task.sleep(for: .milliseconds(50)) }
43 guard process.terminationStatus == 0 else {
44 throw Failure(description: "gnuplot: " + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
45 }
46 return output
47 }
48}
49#endif