Sources/OrgPrograms/Gnuplot.swift

51 lines · 3212 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        let setupFile = folder.appendingPathComponent("setup.gp")
26        if plot.options.type == "radar", plot.options["script"] == nil { try TablePlot.radarSetup(plot).write(to: setupFile, atomically: true, encoding: .utf8) }
27        var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, setupFile: setupFile.path)
28        if let custom = plot.options["script"]?.description {
29            let path = OrgPaths.expandingTilde(custom)
30            let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
31            guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") }
32            script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true)
33                + "\n" + text.replacingOccurrences(of: "$datafile", with: dataFile.path)
34        }
35        let scriptFile = folder.appendingPathComponent("plot.gp")
36        try script.write(to: scriptFile, atomically: true, encoding: .utf8)
37        let process = Process()
38        process.executableURL = gnuplot
39        process.arguments = [scriptFile.path]
40        process.currentDirectoryURL = directory
41        let errors = Pipe()
42        process.standardError = errors
43        try process.run()
44        while process.isRunning { try await Task.sleep(for: .milliseconds(50)) }
45        guard process.terminationStatus == 0 else {
46            throw Failure(description: "gnuplot: " + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
47        }
48        return output
49    }
50}
51#endif