Sources/OrgCore/Compute/PlotSettings.swift

design-themes-widgets
orgstar/Sources/OrgCore/Compute/PlotSettings.swift history · blame · raw

131 lines · 6393 bytes

  1import Foundation
  2
  3/// The gnuplot `set` commands a plot drawn without gnuplot follows, and the options it leaves out.
  4extension TablePlot {
  5    public struct Settings: Sendable, Equatable {
  6        public enum Key: Sendable, Equatable {
  7            case off
  8            /// `top`/`bottom` and `left`/`right`, either left to the chart.
  9            case at(vertical: String?, horizontal: String?)
 10        }
 11
 12        public struct Range: Sendable, Equatable {
 13            public var low: Double?
 14            public var high: Double?
 15
 16            public init(low: Double?, high: Double?) {
 17                self.low = low
 18                self.high = high
 19            }
 20        }
 21
 22        public var title: String?
 23        public var xlabel: String?
 24        public var ylabel: String?
 25        public var xrange: Range?
 26        public var yrange: Range?
 27        public var logX = false
 28        public var logY = false
 29        public var grid = false
 30        public var key: Key?
 31        public var xtics: Double?
 32        public var ytics: Double?
 33        /// The options not followed, as written in `#+PLOT`: `set:"…"`, `line:"…"`, `script:"…"`.
 34        public var unfollowed: [String] = []
 35    }
 36
 37    /// The `set` commands each kind of chart can follow.
 38    static func followed(_ plot: Plot) -> Set<String> {
 39        switch plot.options.type {
 40        case "2d":
 41            let numericX = plot.options.ind <= 0 || !(plot.timeInd || plot.textInd || plot.options.with == "histograms")
 42            return numericX ? ["title", "xlabel", "ylabel", "xrange", "yrange", "logscale", "grid", "key", "xtics", "ytics"]
 43                : ["title", "xlabel", "ylabel", "yrange", "logscale y", "grid", "key", "ytics"]
 44        // The heat map's legend is its colour scale, which gnuplot's `set key` leaves alone.
 45        case "grid": return ["title", "xlabel", "ylabel"]
 46        case "3d" where plot.options["map"]?.truthy == true: return ["title", "xlabel", "ylabel"]
 47        // The radar script sets its own key, after these.
 48        default: return ["title"]
 49        }
 50    }
 51
 52    /// The script's `title:`, `line:` and `set:` in the order gnuplot reads them, so a later
 53    /// one wins.
 54    public static func settings(_ plot: Plot) -> Settings {
 55        var s = Settings()
 56        let o = plot.options
 57        var follows = followed(plot)
 58        func read() -> (lines: [String], sets: [String]) {
 59            s = Settings()
 60            s.title = o.title
 61            var lines: [String] = [], sets: [String] = []
 62            for line in o.lines {
 63                if !(line.hasPrefix("set ") && apply(String(line.dropFirst(4)), to: &s, follows: follows)) { lines.append("line:\"\(line)\"") }
 64            }
 65            for set in o.sets where !apply(set, to: &s, follows: follows) { sets.append("set:\"\(set)\"") }
 66            return (lines, sets)
 67        }
 68        var (lines, sets) = read()
 69        // On a log axis gnuplot steps by a factor, not an increment.
 70        if s.logX || s.logY {
 71            if s.logX { follows.remove("xtics") }
 72            if s.logY { follows.remove("ytics") }
 73            (lines, sets) = read()
 74        }
 75        // Each comes twice, as Org reads the options twice; list them once, as written.
 76        for u in lines.reversed() + sets.reversed() where !s.unfollowed.contains(u) { s.unfollowed.append(u) }
 77        if let script = o["script"] { s.unfollowed.append("script:\"\(script)\"") }
 78        return s
 79    }
 80
 81    static func apply(_ command: String, to s: inout Settings, follows: Set<String>) -> Bool {
 82        let words = command.split(separator: " ", maxSplits: 1).map(String.init)
 83        guard let name = words.first else { return false }
 84        let rest = words.count > 1 ? words[1].trimmingCharacters(in: .whitespaces) : ""
 85        func quoted() -> String? {
 86            guard let m = rest.firstMatch(of: /^(["'])(.*)\1$/) else { return nil }
 87            return String(m.2)
 88        }
 89        func range() -> Settings.Range? {
 90            guard let m = rest.firstMatch(of: /^\[\s*([^:\]]*?)\s*:\s*([^:\]]*?)\s*\]$/) else { return nil }
 91            func bound(_ t: Substring) -> Double?? { t.isEmpty || t == "*" ? .some(nil) : Double(t).map { .some($0) } }
 92            guard let low = bound(m.1), let high = bound(m.2) else { return nil }
 93            // gnuplot reverses the axis for these, which the charts here don't.
 94            if let low, let high, low > high { return nil }
 95            return Settings.Range(low: low, high: high)
 96        }
 97        func step() -> Double? { Double(rest).flatMap { $0 > 0 ? $0 : nil } }
 98        switch name {
 99        case "title", "xlabel", "ylabel":
100            guard follows.contains(name), let text = quoted() else { return false }
101            if name == "title" { s.title = text } else if name == "xlabel" { s.xlabel = text } else { s.ylabel = text }
102        case "xrange", "yrange":
103            guard follows.contains(name), let r = range() else { return false }
104            if name == "xrange" { s.xrange = r } else { s.yrange = r }
105        case "logscale":
106            let axes = rest.isEmpty ? "xy" : rest
107            guard ["x", "y", "xy", "yx"].contains(axes), follows.contains("logscale") || (axes == "y" && follows.contains("logscale y")) else { return false }
108            if axes.contains("x") { s.logX = true }
109            if axes.contains("y") { s.logY = true }
110        case "grid":
111            guard follows.contains(name), rest.isEmpty else { return false }
112            s.grid = true
113        case "key":
114            let words = rest.split(separator: " ").map(String.init)
115            guard follows.contains(name), words.allSatisfy(["off", "top", "bottom", "left", "right"].contains) else { return false }
116            if words == ["off"] {
117                s.key = .off
118            } else {
119                let vertical = words.filter { $0 == "top" || $0 == "bottom" }, horizontal = words.filter { $0 == "left" || $0 == "right" }
120                guard !words.contains("off"), vertical.count <= 1, horizontal.count <= 1 else { return false }
121                s.key = .at(vertical: vertical.first, horizontal: horizontal.first)
122            }
123        case "xtics", "ytics":
124            guard follows.contains(name), let step = step() else { return false }
125            if name == "xtics" { s.xtics = step } else { s.ytics = step }
126        default:
127            return false
128        }
129        return true
130    }
131}