subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

ProfileChart.swift (12823B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Charts
      3 import SubsurfaceLog
      4 import SwiftUI
      5 
      6 /// Profile data prepared for display (the user's units, downsampled samples).
      7 struct ProfileData {
      8     struct Point: Identifiable {
      9         let id: Int
     10         let minute: Double
     11         let value: Double
     12     }
     13 
     14     struct Series: Identifiable {
     15         let id: String
     16         var points: [Point]
     17     }
     18 
     19     struct Marker: Identifiable {
     20         let id: Int
     21         let minute: Double
     22         let depth: Double
     23         let label: String?
     24         let name: String
     25         let seconds: Int
     26     }
     27 
     28     var depth: [Point] = []
     29     var ceiling: [Point] = []
     30     var temperature: [Point] = []
     31     var pressure: [Series] = []
     32     var markers: [Marker] = []
     33     var maxMinute = 1.0
     34     var samples: [Sample] = []
     35     /// Last known pressure of each sensor at each sample, for the readout under the cursor.
     36     var pressureAt: [[Int: Double]] = []
     37 
     38     init(computer: DiveComputer, units: Units) {
     39         samples = computer.samples
     40         guard let last = samples.last else { return }
     41         maxMinute = max(Double(last.time) / 60, 1)
     42 
     43         // At most ~700 points: keep the deepest of each bucket so the peaks are not shaved off.
     44         let bucket = max(1, samples.count / 700)
     45         var index = 0
     46         while index < samples.count {
     47             let slice = samples[index..<min(index + bucket, samples.count)]
     48             if let deepest = slice.max(by: { $0.depth < $1.depth }) {
     49                 depth.append(Point(id: depth.count, minute: Double(deepest.time) / 60, value: units.depthValue(deepest.depth)))
     50             }
     51             index += bucket
     52         }
     53 
     54         var lastTemp: Double?
     55         var known = [Int: Double]()
     56         var bySensor = [Int: [Point]]()
     57         var inCeiling = false
     58         for (i, sample) in samples.enumerated() {
     59             let minute = Double(sample.time) / 60
     60             if let t = sample.temperature, t != lastTemp || i == samples.count - 1 {
     61                 temperature.append(Point(id: temperature.count, minute: minute, value: units.temperatureValue(t)))
     62                 lastTemp = t
     63             }
     64             for p in sample.pressures {
     65                 known[p.sensor] = p.bar
     66                 bySensor[p.sensor, default: []].append(Point(id: bySensor[p.sensor]?.count ?? 0, minute: minute, value: units.pressureValue(p.bar)))
     67             }
     68             pressureAt.append(known)
     69             let stop = sample.inDeco ? (sample.stopDepth ?? 0) : 0
     70             if stop > 0 || inCeiling {
     71                 ceiling.append(Point(id: ceiling.count, minute: minute, value: units.depthValue(stop)))
     72                 inCeiling = stop > 0
     73             }
     74         }
     75         pressure = bySensor.keys.sorted().map { Series(id: "Cylinder \($0 + 1)", points: bySensor[$0] ?? []) }
     76 
     77         for (i, event) in computer.events.enumerated() {
     78             let minute = Double(event.time) / 60
     79             let depthThere = sample(at: minute).map { units.depthValue($0.depth) } ?? 0
     80             var label: String?
     81             if event.isGasChange, event.time > 30 { label = event.gas?.label ?? String(localized: "Gas") }
     82             if event.isGasChange, event.time <= 30 { continue }
     83             markers.append(Marker(id: i, minute: minute, depth: depthThere, label: label, name: event.name, seconds: event.time))
     84         }
     85     }
     86 
     87     func sampleIndex(at minute: Double) -> Int? {
     88         guard !samples.isEmpty else { return nil }
     89         let target = Int(minute * 60)
     90         var low = 0, high = samples.count - 1
     91         while low < high {
     92             let mid = (low + high) / 2
     93             if samples[mid].time < target { low = mid + 1 } else { high = mid }
     94         }
     95         if low > 0, abs(samples[low - 1].time - target) < abs(samples[low].time - target) { return low - 1 }
     96         return low
     97     }
     98 
     99     func sample(at minute: Double) -> Sample? { sampleIndex(at: minute).map { samples[$0] } }
    100 }
    101 
    102 struct ProfileChart: View {
    103     let data: ProfileData
    104     let units: Units
    105     /// Times (seconds since entering the water) at which a photo was taken.
    106     var photoOffsets: [Int] = []
    107     @State private var selection: Double?
    108 
    109     private let axisWidth: CGFloat = 34
    110 
    111     var body: some View {
    112         VStack(alignment: .leading, spacing: 10) {
    113             readout
    114             depthChart
    115                 .frame(height: 220)
    116             if data.temperature.count > 1 {
    117                 smallChart(title: String(localized: "Temperature"), unit: units.temperatureUnit, series: [.init(id: "Temperature", points: data.temperature)], color: .orange)
    118             }
    119             if data.pressure.contains(where: { $0.points.count > 1 }) {
    120                 smallChart(title: String(localized: "Cylinder pressure"), unit: units.pressureUnit, series: data.pressure, color: .green)
    121             }
    122         }
    123     }
    124 
    125     /// Values under the finger; with no selection, a discreet hint.
    126     @ViewBuilder private var readout: some View {
    127         if let minute = selection, let index = data.sampleIndex(at: minute) {
    128             let sample = data.samples[index]
    129             ScrollView(.horizontal, showsIndicators: false) {
    130                 HStack(spacing: 14) {
    131                     value(String(localized: "Time"), Units.clock(sample.time))
    132                     value(String(localized: "Depth"), units.depth(sample.depth))
    133                     if let t = sample.temperature { value(String(localized: "Water"), units.temperature(t)) }
    134                     ForEach(data.pressureAt[index].keys.sorted(), id: \.self) { sensor in
    135                         value(data.pressureAt[index].count > 1 ? String(localized: "Cyl. \(sensor + 1)") : String(localized: "Pressure"),
    136                               units.pressure(data.pressureAt[index][sensor] ?? 0))
    137                     }
    138                     if sample.inDeco, let stop = sample.stopDepth, stop > 0 {
    139                         value(String(localized: "Stop"), units.depth(stop), color: .red)
    140                         if let tts = sample.tts { value(String(localized: "Surface in"), Units.duration(tts)) }
    141                     } else if let ndl = sample.ndl {
    142                         value(String(localized: "No stop"), ndl >= 99 * 60 ? String(localized: "99+ min") : Units.duration(ndl))
    143                     }
    144                     if let cns = sample.cns, cns > 0 { value(String(localized: "CNS"), String(localized: "\(cns)%")) }
    145                 }
    146             }
    147             .frame(height: 36)
    148         } else {
    149             Text("Drag your finger across the profile to read the values.")
    150                 .font(.caption)
    151                 .foregroundStyle(.secondary)
    152                 .frame(height: 36, alignment: .leading)
    153         }
    154     }
    155 
    156     private func value(_ title: String, _ text: String, color: Color = .primary) -> some View {
    157         VStack(alignment: .leading, spacing: 1) {
    158             Text(title).font(.caption2).foregroundStyle(.secondary)
    159             Text(text).font(.callout.monospacedDigit().weight(.semibold)).foregroundStyle(color)
    160         }
    161     }
    162 
    163     private var depthChart: some View {
    164         Chart {
    165             ForEach(data.depth) { point in
    166                 AreaMark(x: .value("Time", point.minute), y: .value("Depth", point.value),
    167                          series: .value("Series", "Depth"), stacking: .unstacked)
    168                     .foregroundStyle(LinearGradient(colors: [Color.accentColor.opacity(0.12), Color.accentColor.opacity(0.5)],
    169                                                     startPoint: .top, endPoint: .bottom))
    170                     .interpolationMethod(.monotone)
    171                 LineMark(x: .value("Time", point.minute), y: .value("Depth", point.value),
    172                          series: .value("Series", "Depth"))
    173                     .foregroundStyle(Color.accentColor)
    174                     .lineStyle(StrokeStyle(lineWidth: 2))
    175                     .interpolationMethod(.monotone)
    176             }
    177             ForEach(data.ceiling) { point in
    178                 AreaMark(x: .value("Time", point.minute), yStart: .value("Surface", 0.0), yEnd: .value("Ceiling", point.value),
    179                          series: .value("Series", "Ceiling"))
    180                     .foregroundStyle(Color.red.opacity(0.3))
    181                     .interpolationMethod(.stepEnd)
    182             }
    183             ForEach(data.markers) { marker in
    184                 PointMark(x: .value("Time", marker.minute), y: .value("Depth", marker.depth))
    185                     .symbol(marker.label == nil ? .triangle : .diamond)
    186                     .symbolSize(60)
    187                     .foregroundStyle(marker.label == nil ? Color.orange : Color.purple)
    188                     .annotation(position: .bottom, spacing: 2) {
    189                         if let label = marker.label {
    190                             Text(label).font(.caption2.weight(.semibold)).foregroundStyle(.purple)
    191                         }
    192                     }
    193             }
    194             ForEach(Array(photoOffsets.enumerated()), id: \.offset) { _, seconds in
    195                 let minute = Double(seconds) / 60
    196                 PointMark(x: .value("Time", minute), y: .value("Depth", data.sample(at: minute).map { units.depthValue($0.depth) } ?? 0))
    197                     .symbol(.circle)
    198                     .symbolSize(photoOffsets.count > 25 ? 22 : 46)
    199                     .foregroundStyle(Color.pink)
    200                     .annotation(position: .top, spacing: 1) {
    201                         if photoOffsets.count <= 25 {
    202                             Image(systemName: "camera.fill").font(.system(size: 8)).foregroundStyle(.pink)
    203                         }
    204                     }
    205             }
    206             if let selection {
    207                 RuleMark(x: .value("Time", selection))
    208                     .foregroundStyle(Color.secondary.opacity(0.6))
    209                     .lineStyle(StrokeStyle(lineWidth: 1))
    210                 if let sample = data.sample(at: selection) {
    211                     PointMark(x: .value("Time", Double(sample.time) / 60), y: .value("Depth", units.depthValue(sample.depth)))
    212                         .symbolSize(80)
    213                         .foregroundStyle(Color.accentColor)
    214                 }
    215             }
    216         }
    217         .chartXScale(domain: 0...data.maxMinute)
    218         .chartYScale(domain: .automatic(includesZero: true, reversed: true))
    219         .chartXSelection(value: $selection)
    220         .chartLegend(.hidden)
    221         .chartXAxis {
    222             AxisMarks(values: .automatic(desiredCount: 6)) { value in
    223                 AxisGridLine()
    224                 AxisValueLabel {
    225                     if let minute = value.as(Double.self) { Text("\(Int(minute)) min") }
    226                 }
    227             }
    228         }
    229         .chartYAxis {
    230             AxisMarks(position: .leading, values: .automatic(desiredCount: 5)) { value in
    231                 AxisGridLine()
    232                 AxisValueLabel {
    233                     if let depth = value.as(Double.self) {
    234                         Text("\(Int(depth)) \(units.depthUnit)").frame(width: axisWidth, alignment: .trailing)
    235                     }
    236                 }
    237             }
    238         }
    239         .accessibilityLabel("Dive profile")
    240     }
    241 
    242     private func smallChart(title: String, unit: String, series: [ProfileData.Series], color: Color) -> some View {
    243         VStack(alignment: .leading, spacing: 2) {
    244             Text(title).font(.caption).foregroundStyle(.secondary)
    245             Chart {
    246                 ForEach(series) { serie in
    247                     ForEach(serie.points) { point in
    248                         LineMark(x: .value("Time", point.minute), y: .value(title, point.value), series: .value("Series", serie.id))
    249                             .foregroundStyle(color)
    250                             .lineStyle(StrokeStyle(lineWidth: 1.5))
    251                     }
    252                 }
    253                 if let selection {
    254                     RuleMark(x: .value("Time", selection))
    255                         .foregroundStyle(Color.secondary.opacity(0.6))
    256                         .lineStyle(StrokeStyle(lineWidth: 1))
    257                 }
    258             }
    259             .chartXScale(domain: 0...data.maxMinute)
    260             .chartYScale(domain: .automatic(includesZero: false))
    261             .chartXSelection(value: $selection)
    262             .chartLegend(.hidden)
    263             .chartXAxis {
    264                 AxisMarks(values: .automatic(desiredCount: 6)) { _ in AxisGridLine() }
    265             }
    266             .chartYAxis {
    267                 AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { value in
    268                     AxisGridLine()
    269                     AxisValueLabel {
    270                         if let number = value.as(Double.self) {
    271                             Text("\(Int(number))").frame(width: axisWidth, alignment: .trailing)
    272                         }
    273                     }
    274                 }
    275             }
    276             .frame(height: 70)
    277             .accessibilityLabel(Text(verbatim: "\(title) (\(unit))"))
    278         }
    279     }
    280 }