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

TechPlanView.swift (43472B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Charts
      3 import DivePlanner
      4 import SubsurfaceLog
      5 import SwiftUI
      6 
      7 /// The decompression planner: levels and cylinders in, stops, gas and warnings out.
      8 struct TechPlanView: View {
      9     @Environment(AppModel.self) private var model
     10     @State private var plan = TechPlanView.stored()
     11     @State private var result = PlanResult()
     12     @State private var confirmingReset = false
     13     @State private var variations: PlanVariations?
     14     @AppStorage("planDate") private var planDate = Date().timeIntervalSince1970
     15     @AppStorage("planCountEarlierDives") private var countEarlierDives = false
     16     @State private var earlier: [AppModel.EarlierDive] = []
     17     @AppStorage("planShowVariations") private var showVariations = false
     18     @State private var saving = LaunchOptions.flag("-savePlan")
     19     @State private var library = PlanLibrary()
     20     @AppStorage("planCurrentID") private var currentID = ""
     21     @State private var naming = false
     22     @State private var choosingSave = false
     23     @State private var newName = ""
     24     @State private var shared: SharedFile?
     25 
     26     private static let storageKey = "divePlan2"
     27 
     28     /// The plan the planner starts with: one level on one cylinder, one decompression gas.
     29     static var starter: DivePlan {
     30         DivePlan(levels: [PlanLevel(depth: 45, minutes: 25)],
     31                  cylinders: [PlanCylinder(gas: BreathingGas(o2Percent: 21, hePercent: 35), volumeLiters: 24, startBar: 220),
     32                              PlanCylinder(gas: BreathingGas(o2Percent: 50), volumeLiters: 11.1, startBar: 200, isDeco: true)])
     33     }
     34 
     35     private static func stored() -> DivePlan {
     36         guard !LaunchOptions.flag("-starterPlan"), let data = UserDefaults.standard.data(forKey: storageKey),
     37               let plan = try? JSONDecoder().decode(DivePlan.self, from: data), !plan.cylinders.isEmpty else { return starter }
     38         return plan
     39     }
     40 
     41     var body: some View {
     42         let units = model.units
     43         ScrollViewReader { proxy in
     44         Form {
     45             Section {
     46                 NavigationLink {
     47                     SavedPlansView(library: library, currentID: currentID) { saved in
     48                         plan = saved.plan
     49                         planDate = saved.date
     50                         currentID = saved.id.uuidString
     51                     }
     52                 } label: {
     53                     HStack {
     54                         Label("Saved plans", systemImage: "tray.full")
     55                         Spacer()
     56                         Text("\(library.plans.count)").foregroundStyle(.secondary)
     57                     }
     58                 }
     59                 HStack {
     60                     VStack(alignment: .leading, spacing: 2) {
     61                         Text(current?.name ?? String(localized: "Plan not saved"))
     62                         if let current, current.plan != plan || current.date != planDate {
     63                             Text("Changed since it was saved").font(.caption).foregroundStyle(.orange)
     64                         }
     65                     }
     66                     Spacer()
     67                     Button("Save") {
     68                         if current != nil { choosingSave = true } else { askName() }
     69                     }
     70                     .buttonStyle(.bordered)
     71                     .disabled(current.map { $0.plan == plan && $0.date == planDate } ?? false)
     72                 }
     73             }
     74 
     75             Section {
     76                 Picker("Circuit", selection: $plan.mode) {
     77                     Text("Open circuit").tag(BreathingMode.openCircuit)
     78                     Text("Closed circuit (CCR)").tag(BreathingMode.closedCircuit)
     79                     Text("Semi-closed (pSCR)").tag(BreathingMode.semiClosed)
     80                 }
     81                 if plan.mode == .closedCircuit {
     82                     NumberRow(title: "Setpoint", value: $plan.setpoint, unit: "bar", digits: 2, range: 0.4...1.6, step: 0.1)
     83                 }
     84                 if plan.mode != .openCircuit {
     85                     Toggle("Ascent on open-circuit bailout", isOn: $plan.bailout)
     86                 }
     87                 if plan.mode == .closedCircuit, !plan.bailout {
     88                     Toggle("Another setpoint for the ascent", isOn: Binding(get: { plan.ascentSetpoint != nil },
     89                                                                            set: { plan.ascentSetpoint = $0 ? 1.4 : nil }))
     90                     if plan.ascentSetpoint != nil {
     91                         NumberRow(title: "Setpoint", value: Binding(get: { plan.ascentSetpoint ?? 1.4 }, set: { plan.ascentSetpoint = $0 }),
     92                                   unit: "bar", digits: 2, range: 0.4...1.6, step: 0.1)
     93                         NumberRow(title: "From", value: units.depthBinding($plan.ascentSetpointDepth), unit: units.depthUnit,
     94                                   range: 0...units.depthValue(100), step: units.imperial ? 10 : 3)
     95                     }
     96                 }
     97             } footer: {
     98                 if plan.mode == .closedCircuit {
     99                     Text(plan.bailout
    100                          ? "The dive is on the loop to the end of the bottom time, then on the bailout gases: mark them as decompression gases."
    101                          : "The whole dive is on the loop, on the diluent of the last level: the other cylinders are not used.")
    102                 } else if plan.mode == .semiClosed {
    103                     Text("The oxygen in the loop is lower than in the cylinder, by what the diver uses up; decompression gases are breathed through the loop as well.")
    104                 }
    105             }
    106 
    107             Section {
    108                 DatePicker("Date", selection: Binding(get: { Date(timeIntervalSince1970: planDate) }, set: { planDate = $0.timeIntervalSince1970 }))
    109                 Toggle("Count my earlier dives", isOn: $countEarlierDives)
    110                 if countEarlierDives {
    111                     if earlier.isEmpty {
    112                         Text("No dive of the logbook in the 48 hours before.").foregroundStyle(.secondary).font(.callout)
    113                     }
    114                     ForEach(earlier) { dive in
    115                         HStack {
    116                             Text(dive.title)
    117                             Spacer()
    118                             Text(String(localized: "\(Units.duration(dive.interval)) before")).foregroundStyle(.secondary)
    119                         }
    120                         .font(.callout)
    121                     }
    122                 }
    123             } footer: {
    124                 if countEarlierDives {
    125                     Text("The dives of the logbook that ended less than 48 hours before this date leave gas in the tissues: the plan starts from there.")
    126                 }
    127             }
    128 
    129             Section {
    130                 ForEach($plan.levels) { $level in
    131                     VStack(spacing: 8) {
    132                         NumberRow(title: "Depth", value: units.depthBinding($level.depth), unit: units.depthUnit, digits: units.imperial ? 0 : 1,
    133                                   range: 0...units.depthValue(200), step: units.depthStep)
    134                         NumberRow(title: "Time", value: $level.minutes, unit: "min", range: 0...600, step: 1)
    135                         Picker("Cylinder", selection: $level.cylinder) {
    136                             ForEach(Array(plan.cylinders.enumerated()), id: \.offset) { index, cylinder in
    137                                 Text(verbatim: cylinder.gas.name).tag(index)
    138                             }
    139                         }
    140                     }
    141                 }
    142                 .onDelete { plan.levels.remove(atOffsets: $0) }
    143                 .deleteDisabled(plan.levels.count < 2)
    144                 Button {
    145                     let last = plan.levels.last
    146                     plan.levels.append(PlanLevel(depth: max(6, (last?.depth ?? 30) - 15), minutes: 10, cylinder: last?.cylinder ?? 0))
    147                 } label: {
    148                     Label("Add a level", systemImage: "plus.circle")
    149                 }
    150             } header: {
    151                 Text("Dive")
    152             } footer: {
    153                 Text("Each time counts from leaving the previous depth: the way down, or up, is part of it.")
    154             }
    155 
    156             Section {
    157                 ForEach($plan.cylinders) { $cylinder in
    158                     NavigationLink {
    159                         PlanCylinderEditor(cylinder: $cylinder, settings: plan.settings)
    160                     } label: {
    161                         cylinderLabel(cylinder, units)
    162                     }
    163                 }
    164                 .onDelete(perform: removeCylinders)
    165                 .deleteDisabled(plan.cylinders.count < 2)
    166                 Button {
    167                     plan.cylinders.append(PlanCylinder(gas: .oxygen, volumeLiters: 5.7, startBar: 200, isDeco: true))
    168                 } label: {
    169                     Label("Add a cylinder", systemImage: "plus.circle")
    170                 }
    171             } header: {
    172                 Text("Cylinders")
    173             }
    174 
    175             Section {
    176                 NavigationLink {
    177                     PlanSettingsEditor(settings: $plan.settings)
    178                 } label: {
    179                     HStack {
    180                         Text("Settings")
    181                         Spacer()
    182                         Text(verbatim: plan.settings.model == .vpmb
    183                              ? "VPM-B +\(plan.settings.vpmbConservatism)"
    184                              : "GF \(Int((plan.settings.gfLow * 100).rounded()))/\(Int((plan.settings.gfHigh * 100).rounded()))")
    185                             .foregroundStyle(.secondary)
    186                     }
    187                 }
    188             }
    189 
    190             summary(units)
    191             if result.points.count > 1 {
    192                 Section("Profile") {
    193                     PlanChart(result: result, plan: plan, units: units)
    194                         .frame(height: 200)
    195                         .listRowInsets(EdgeInsets(top: 12, leading: 8, bottom: 8, trailing: 12))
    196                 }
    197             }
    198             stops(units)
    199             gasSection(units)
    200 
    201             Section {
    202                 Toggle("Show how the plan varies", isOn: $showVariations)
    203                 Button { share() } label: { Label("Print or share…", systemImage: "printer") }
    204                     .disabled(result.points.count < 2)
    205                 Button { saving = true } label: { Label("Save in the logbook…", systemImage: "square.and.arrow.down") }
    206                     .disabled(result.points.count < 2 || model.isDemo)
    207                 Button("Start a new plan", role: .destructive) { confirmingReset = true }
    208             } footer: {
    209                 VStack(alignment: .leading, spacing: 6) {
    210                     Text("Computed the way Subsurface's planner does (Bühlmann ZHL-16C with gradient factors, or VPM-B): its own test plans give the same run times here.")
    211                     PlanningDisclaimer()
    212                 }
    213             }
    214         }
    215         .onChange(of: result.runtime) {
    216             // Screenshot option: bring the results into view.
    217             guard LaunchOptions.flag("-planScroll") else { return }
    218             DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { proxy.scrollTo("stops", anchor: .center) }
    219         }
    220         }
    221         .confirmationDialog("Start a new plan?", isPresented: $confirmingReset, titleVisibility: .visible) {
    222             Button("Start over", role: .destructive) {
    223                 plan = Self.starter
    224                 currentID = ""
    225             }
    226         } message: {
    227             Text("The saved plans are not touched.")
    228         }
    229         .confirmationDialog(current?.name ?? "", isPresented: $choosingSave, titleVisibility: .visible) {
    230             Button("Update this plan") {
    231                 if var saved = current {
    232                     saved.plan = plan
    233                     saved.date = planDate
    234                     library.save(saved)
    235                 }
    236             }
    237             Button("Save as a new plan…") { askName() }
    238             Button("Cancel", role: .cancel) {}
    239         }
    240         .alert("Name of the plan", isPresented: $naming) {
    241             TextField("Name", text: $newName)
    242             Button("Save") {
    243                 let name = newName.trimmingCharacters(in: .whitespaces)
    244                 let saved = SavedPlan(name: name.isEmpty ? plan.suggestedName(units: model.units) : name, plan: plan, date: planDate)
    245                 library.save(saved)
    246                 currentID = saved.id.uuidString
    247             }
    248             Button("Cancel", role: .cancel) {}
    249         }
    250         .sheet(item: $shared) { ActivityView(items: [$0.url]) }
    251         .task(id: PlanInputs(plan: plan, date: planDate, earlier: countEarlierDives, imperial: model.units.imperial, dives: model.logbook.dives.count)) {
    252             if let data = try? JSONEncoder().encode(plan) { UserDefaults.standard.set(data, forKey: Self.storageKey) }
    253             var current = plan
    254             current.settings.stopsInFeet = model.units.imperial
    255             earlier = countEarlierDives ? await model.earlierDives(before: Date(timeIntervalSince1970: planDate)) : []
    256             let prior = earlier.map(\.prior)
    257             let computed = await Task.detached(priority: .userInitiated) { DivePlanner.plan(current, after: prior) }.value
    258             guard !Task.isCancelled else { return }
    259             result = computed
    260             // Test option: write the printable sheet to a file, to look at it without the share sheet.
    261             if let path = LaunchOptions.value("-planPDF") { _ = sheet.pdf(named: "plan", at: URL(fileURLWithPath: path)) }
    262             // Test option: save the plan under a name, as the Save button and its name prompt would.
    263             if let name = LaunchOptions.value("-savePlanAs"), library.plans.allSatisfy({ $0.name != name }) {
    264                 let saved = SavedPlan(name: name, plan: plan, date: planDate)
    265                 library.save(saved)
    266                 currentID = saved.id.uuidString
    267             }
    268             variations = nil
    269             if showVariations {
    270                 let around = await Task.detached(priority: .utility) { DivePlanner.variations(of: current) }.value
    271                 if !Task.isCancelled { variations = around }
    272             }
    273         }
    274         .task(id: showVariations) {
    275             guard showVariations, variations == nil else { return }
    276             let current = plan
    277             variations = await Task.detached(priority: .utility) { DivePlanner.variations(of: current) }.value
    278         }
    279         .sheet(isPresented: $saving) { SavePlanView(plan: plan, result: result, date: Date(timeIntervalSince1970: planDate)) }
    280     }
    281 
    282     // MARK: Results
    283 
    284     @ViewBuilder private func summary(_ units: Units) -> some View {
    285         Section {
    286             Grid(horizontalSpacing: 8, verticalSpacing: 8) {
    287                 GridRow {
    288                     Figure(title: "Run time", value: Units.duration(Int(result.runtime.rounded())), icon: "timer")
    289                     Figure(title: "Ascent and stops", value: Units.duration(Int(result.ascentTime.rounded())), icon: "arrow.up.to.line")
    290                 }
    291                 GridRow {
    292                     Figure(title: "Oxygen clock (CNS)", value: fixed(result.cns * 100, 0) + " %%", icon: "o.circle")
    293                     Figure(title: "Oxygen units (OTU)", value: fixed(result.otu, 0), icon: "lungs")
    294                 }
    295             }
    296             .listRowInsets(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12))
    297             if result.bottomExtensionMinutes > 0 {
    298                 Label(String(localized: "Bottom time extended by \(Int(result.bottomExtensionMinutes.rounded())) min: the longest this dive can be without stops, with the gas there is."),
    299                       systemImage: "clock.arrow.2.circlepath")
    300                     .font(.callout)
    301             }
    302             if showVariations, let variations {
    303                 Label(String(localized: "One metre deeper: \(signed(variations.perMeter)) of run time. One minute longer: \(signed(variations.perMinute)) of ascent."),
    304                       systemImage: "plusminus")
    305                     .font(.callout)
    306                     .foregroundStyle(.secondary)
    307             }
    308             ForEach(Array(result.warnings.enumerated()), id: \.offset) { _, warning in
    309                 Label(describe(warning, units), systemImage: "exclamationmark.triangle.fill")
    310                     .font(.callout)
    311                     .foregroundStyle(isSevere(warning) ? Color.red : Color.orange)
    312             }
    313         } header: {
    314             Text("Plan")
    315         }
    316     }
    317 
    318     @ViewBuilder private func stops(_ units: Units) -> some View {
    319         Section {
    320             if result.stops.isEmpty {
    321                 Text("No stop: a direct ascent at \(units.depth(plan.settings.ascentRateStops)) per minute.")
    322                     .foregroundStyle(.secondary)
    323             }
    324             ForEach(Array(result.stops.enumerated()), id: \.offset) { _, stop in
    325                 // Two lines, so that nothing has to break whatever the text size: depth and time, then the details.
    326                 VStack(alignment: .leading, spacing: 3) {
    327                     HStack(alignment: .firstTextBaseline) {
    328                         Text(units.depth(stop.depth))
    329                             .font(.body.monospacedDigit().weight(.medium))
    330                         Spacer(minLength: 8)
    331                         Text(String(localized: "\(Int((stop.seconds / 60).rounded())) min"))
    332                             .font(.body.monospacedDigit().weight(.medium))
    333                     }
    334                     .lineLimit(1)
    335                     HStack(alignment: .firstTextBaseline, spacing: 6) {
    336                         Text(verbatim: plan.cylinders.indices.contains(stop.cylinder) ? plan.cylinders[stop.cylinder].gas.name : "")
    337                             .foregroundStyle(.green)
    338                         if stop.kind != .deco {
    339                             Text(stop.kind == .safety ? String(localized: "Safety stop") : String(localized: "Gas switch"))
    340                                 .foregroundStyle(.secondary)
    341                         }
    342                         Spacer(minLength: 8)
    343                         Text(String(localized: "at \(Int((stop.endTime / 60).rounded())) min"))
    344                             .monospacedDigit()
    345                             .foregroundStyle(.secondary)
    346                     }
    347                     .font(.caption)
    348                     .lineLimit(1)
    349                     .minimumScaleFactor(0.8)
    350                 }
    351             }
    352         } header: {
    353             Text("Stops").id("stops")
    354         } footer: {
    355             if !result.stops.isEmpty { Text("On the right: the run time when each stop ends.") }
    356         }
    357     }
    358 
    359     @ViewBuilder private func gasSection(_ units: Units) -> some View {
    360         Section {
    361             ForEach(Array(plan.cylinders.enumerated()), id: \.offset) { index, cylinder in
    362                 let used = result.gasUsed.indices.contains(index) ? result.gasUsed[index] : 0
    363                 HStack {
    364                     Text(verbatim: cylinder.gas.name).frame(width: 84, alignment: .leading)
    365                     VStack(alignment: .leading, spacing: 2) {
    366                         Text(fixed(used, 0) + " L").monospacedDigit()
    367                         if let start = cylinder.startBar, let left = cylinder.pressure(afterUsing: used) {
    368                             Text(String(localized: "\(units.pressure(max(0, start - left))) used, \(units.pressure(max(0, left))) left"))
    369                                 .font(.caption)
    370                                 .foregroundStyle(left < plan.settings.reserveBar ? (left < 0 ? Color.red : Color.orange) : Color.secondary)
    371                         }
    372                     }
    373                     Spacer()
    374                 }
    375             }
    376             if let minimum = result.minimumGasLiters, plan.cylinders.indices.contains(result.bottomCylinder) {
    377                 let cylinder = plan.cylinders[result.bottomCylinder]
    378                 HStack {
    379                     Text("Minimum gas")
    380                     Spacer()
    381                     Text(cylinder.volumeLiters.map { units.pressure(RealGas.pressure(cylinder.gas, liters: minimum, volumeLiters: max($0, 0.1))) } ?? fixed(minimum, 0) + " L")
    382                         .monospacedDigit()
    383                         .foregroundStyle(.secondary)
    384                 }
    385             }
    386         } header: {
    387             Text("Gas")
    388         } footer: {
    389             Text("Minimum gas: what must be left in \(plan.cylinders.indices.contains(result.bottomCylinder) ? plan.cylinders[result.bottomCylinder].gas.name : "") when leaving the bottom, for \(Int(plan.settings.problemMinutes)) minutes on a problem and the ascent to the first gas switch, at \(fixed(plan.settings.minimumGasFactor, 0)) times the consumption.")
    390         }
    391     }
    392 
    393     private func cylinderLabel(_ cylinder: PlanCylinder, _ units: Units) -> some View {
    394         HStack {
    395             Text(verbatim: cylinder.gas.name).font(.body.weight(.medium))
    396             Spacer()
    397             VStack(alignment: .trailing, spacing: 2) {
    398                 if let volume = cylinder.volumeLiters, let start = cylinder.startBar {
    399                     Text(verbatim: "\(units.volume(volume)) · \(units.pressure(start))").font(.callout)
    400                 }
    401                 Text(cylinder.isDeco
    402                      ? (plan.mode != .openCircuit && plan.bailout
    403                         ? String(localized: "Bailout, from \(units.depth(DivePlanner.switchDepth(of: cylinder, settings: plan.settings)))")
    404                         : String(localized: "Decompression, from \(units.depth(DivePlanner.switchDepth(of: cylinder, settings: plan.settings)))"))
    405                      : (plan.mode == .closedCircuit ? String(localized: "Diluent") : String(localized: "Bottom gas")))
    406                     .font(.caption)
    407                     .foregroundStyle(.secondary)
    408             }
    409         }
    410     }
    411 
    412     private func removeCylinders(at offsets: IndexSet) {
    413         for index in offsets.sorted(by: >) where plan.cylinders.count > 1 {
    414             plan.cylinders.remove(at: index)
    415             for level in plan.levels.indices {
    416                 if plan.levels[level].cylinder == index {
    417                     plan.levels[level].cylinder = 0
    418                 } else if plan.levels[level].cylinder > index {
    419                     plan.levels[level].cylinder -= 1
    420                 }
    421             }
    422         }
    423     }
    424 
    425     private var current: SavedPlan? { library.plan(id: currentID) }
    426 
    427     private func askName() {
    428         newName = plan.suggestedName(units: model.units)
    429         naming = true
    430     }
    431 
    432     private var sheet: PlanSheet {
    433         PlanSheet(name: current?.name ?? plan.suggestedName(units: model.units), date: Date(timeIntervalSince1970: planDate),
    434                   plan: plan, result: result, units: model.units)
    435     }
    436 
    437     private func share() {
    438         if let url = sheet.pdf(named: current?.name ?? String(localized: "Dive plan")) { shared = SharedFile(url: url) }
    439     }
    440 
    441     /// "+2 min 30 s", "−40 s".
    442     private func signed(_ seconds: Double) -> String {
    443         let whole = Int(seconds.rounded())
    444         let sign = whole < 0 ? "−" : "+"
    445         let minutes = abs(whole) / 60, rest = abs(whole) % 60
    446         if minutes == 0 { return "\(sign)\(rest) s" }
    447         return rest == 0 ? "\(sign)\(minutes) min" : "\(sign)\(minutes) min \(rest) s"
    448     }
    449 
    450     private func isSevere(_ warning: PlanWarning) -> Bool {
    451         switch warning {
    452         case .oxygenTooHigh, .oxygenTooLow, .notEnoughGas, .endless, .unknownCylinder, .exceedsNoStopLimit: return true
    453         case .narcosis, .density, .underMinimumGas, .underReserve, .cnsHigh: return false
    454         }
    455     }
    456 
    457     private func describe(_ warning: PlanWarning, _ units: Units) -> String {
    458         func name(_ index: Int) -> String { plan.cylinders.indices.contains(index) ? plan.cylinders[index].gas.name : "?" }
    459         switch warning {
    460         case .oxygenTooHigh(let cylinder, let depth, let ppO2):
    461             return String(localized: "\(name(cylinder)) at \(units.depth(depth)): oxygen at \(fixed(ppO2, 2)) bar, above the limit.")
    462         case .oxygenTooLow(let cylinder, let depth, let ppO2):
    463             return String(localized: "\(name(cylinder)) at \(units.depth(depth)): only \(fixed(ppO2, 2)) bar of oxygen, not breathable there.")
    464         case .narcosis(let cylinder, let depth, let end):
    465             return String(localized: "\(name(cylinder)) at \(units.depth(depth)): as narcotic as air at \(units.depth(end)).")
    466         case .density(let cylinder, let depth, let density):
    467             return String(localized: "\(name(cylinder)) at \(units.depth(depth)): gas density \(fixed(density, 1)) g/L.")
    468         case .notEnoughGas(let cylinder, let needed, let available):
    469             return String(localized: "Not enough \(name(cylinder)): \(fixed(needed, 0)) L needed, \(fixed(available, 0)) L in the cylinder.")
    470         case .underMinimumGas(let cylinder, let left, let minimum):
    471             return String(localized: "\(name(cylinder)): \(units.pressure(left)) left when leaving the bottom, under the minimum gas of \(units.pressure(minimum)).")
    472         case .underReserve(let cylinder, let left, let reserve):
    473             return String(localized: "\(name(cylinder)): \(units.pressure(left)) left at the end, under the reserve of \(units.pressure(reserve)).")
    474         case .cnsHigh(let percent):
    475             return String(localized: "Oxygen clock at \(fixed(percent, 0)) %.")
    476         case .exceedsNoStopLimit:
    477             return String(localized: "This dive needs decompression stops: it is beyond the no-stop limit of the recreational mode.")
    478         case .unknownCylinder:
    479             return String(localized: "A level uses a cylinder that is no longer in the list.")
    480         case .endless:
    481             return String(localized: "The decompression does not end with these gases.")
    482         }
    483     }
    484 }
    485 
    486 /// Everything the plan depends on: any change computes it again.
    487 private struct PlanInputs: Equatable {
    488     let plan: DivePlan
    489     let date: Double
    490     let earlier: Bool
    491     let imperial: Bool
    492     let dives: Int
    493 }
    494 
    495 /// The planned profile, with the gas switches.
    496 struct PlanChart: View {
    497     let result: PlanResult
    498     let plan: DivePlan
    499     let units: Units
    500 
    501     var body: some View {
    502         let switches = result.points.enumerated().compactMap { index, point -> PlanPoint? in
    503             index > 0 && result.points[index - 1].cylinder != point.cylinder ? point : nil
    504         }
    505         // One point per instant: the plan has several at the same time (a gas switch, the end of a stop), and area
    506         // marks sharing an x are stacked on top of each other, which drew a fill twice as deep as the dive.
    507         let outline = result.points.reduce(into: [PlanPoint]()) { kept, point in
    508             if let last = kept.last, last.time == point.time { kept[kept.count - 1] = point } else { kept.append(point) }
    509         }
    510         Chart {
    511             ForEach(Array(outline.enumerated()), id: \.offset) { _, point in
    512                 AreaMark(x: .value("Time", point.time / 60), yStart: .value("Surface", 0), yEnd: .value("Depth", -units.depthValue(point.depth)))
    513                     .foregroundStyle(Color.accentColor.opacity(0.18))
    514                 LineMark(x: .value("Time", point.time / 60), y: .value("Depth", -units.depthValue(point.depth)))
    515                     .foregroundStyle(Color.accentColor)
    516                     .lineStyle(StrokeStyle(lineWidth: 2))
    517             }
    518             ForEach(Array(switches.enumerated()), id: \.offset) { _, point in
    519                 PointMark(x: .value("Time", point.time / 60), y: .value("Depth", -units.depthValue(point.depth)))
    520                     .foregroundStyle(.green)
    521                     .annotation(position: .top, spacing: 2) {
    522                         Text(verbatim: plan.cylinders.indices.contains(point.cylinder) ? plan.cylinders[point.cylinder].gas.name : "")
    523                             .font(.caption2)
    524                             .foregroundStyle(.green)
    525                     }
    526             }
    527         }
    528         .chartYAxis {
    529             AxisMarks(position: .leading) { value in
    530                 AxisGridLine()
    531                 AxisValueLabel {
    532                     if let depth = value.as(Double.self) { Text(verbatim: "\(Int(-depth)) \(units.depthUnit)") }
    533                 }
    534             }
    535         }
    536         .chartXAxis {
    537             AxisMarks { value in
    538                 AxisGridLine()
    539                 AxisValueLabel {
    540                     if let minute = value.as(Double.self) { Text(verbatim: "\(Int(minute))′") }
    541                 }
    542             }
    543         }
    544     }
    545 }
    546 
    547 /// One cylinder of the plan.
    548 private struct PlanCylinderEditor: View {
    549     @Environment(AppModel.self) private var model
    550     @Binding var cylinder: PlanCylinder
    551     let settings: PlanSettings
    552 
    553     var body: some View {
    554         let units = model.units
    555         let automatic = cylinder.gas.switchDepth(ppO2: settings.ppO2Deco, in: settings.environment)
    556         Form {
    557             Section {
    558                 NumberRow(title: "Oxygen", value: percent(\.o2), unit: "%", range: 5...100, step: 1)
    559                 NumberRow(title: "Helium", value: percent(\.he), unit: "%", range: 0...95, step: 1)
    560             } header: {
    561                 Text(verbatim: cylinder.gas.name)
    562             } footer: {
    563                 Text("Deepest: \(units.depth(cylinder.gas.maximumOperatingDepth(ppO2: settings.ppO2Bottom, in: settings.environment))) at \(fixed(settings.ppO2Bottom, 1)) bar, \(units.depth(cylinder.gas.maximumOperatingDepth(ppO2: settings.ppO2Deco, in: settings.environment))) at \(fixed(settings.ppO2Deco, 1)) bar.")
    564             }
    565             Section("Cylinder") {
    566                 Menu {
    567                     ForEach(CylinderPreset.all) { preset in
    568                         Button(preset.name) {
    569                             cylinder.volumeLiters = preset.liters
    570                             if cylinder.startBar == nil { cylinder.startBar = 200 }
    571                         }
    572                     }
    573                 } label: {
    574                     Label("Common cylinders", systemImage: "list.bullet")
    575                 }
    576                 NumberRow(title: "Volume", value: optional(\.volumeLiters), unit: "L", digits: 1, range: 0...60)
    577                 NumberRow(title: "Pressure", value: units.pressureBinding(optional(\.startBar)), unit: units.pressureUnit, range: 0...units.pressureValue(350))
    578             }
    579             Section {
    580                 Toggle("Decompression gas", isOn: $cylinder.isDeco)
    581                 if cylinder.isDeco {
    582                     Toggle("Switch depth by hand", isOn: Binding(get: { cylinder.switchDepth != nil },
    583                                                                    set: { cylinder.switchDepth = $0 ? automatic : nil }))
    584                     if cylinder.switchDepth != nil {
    585                         NumberRow(title: "Switch at", value: units.depthBinding(optional(\.switchDepth)), unit: units.depthUnit,
    586                                   range: 0...units.depthValue(150), step: units.imperial ? 10 : 3)
    587                     } else {
    588                         LabeledContent("Switch at", value: units.depth(automatic))
    589                     }
    590                 }
    591             } footer: {
    592                 Text("A decompression gas is taken on the way up, from its switch depth. Without a depth set by hand, that is where its oxygen reaches \(fixed(settings.ppO2Deco, 1)) bar.")
    593             }
    594         }
    595         .navigationTitle(cylinder.gas.name)
    596         .navigationBarTitleDisplayMode(.inline)
    597     }
    598 
    599     private func percent(_ path: WritableKeyPath<BreathingGas, Double>) -> Binding<Double> {
    600         Binding {
    601             (cylinder.gas[keyPath: path] * 100).rounded()
    602         } set: { new in
    603             var o2 = cylinder.gas.o2, he = cylinder.gas.he
    604             if path == \BreathingGas.o2 { o2 = new / 100 } else { he = new / 100 }
    605             cylinder.gas = BreathingGas(o2: o2, he: he)
    606         }
    607     }
    608 
    609     private func optional(_ path: WritableKeyPath<PlanCylinder, Double?>) -> Binding<Double> {
    610         Binding {
    611             cylinder[keyPath: path] ?? 0
    612         } set: {
    613             cylinder[keyPath: path] = $0 > 0 ? $0 : nil
    614         }
    615     }
    616 }
    617 
    618 private struct PlanSettingsEditor: View {
    619     @Environment(AppModel.self) private var model
    620     @Binding var settings: PlanSettings
    621 
    622     var body: some View {
    623         let units = model.units
    624         Form {
    625             Section {
    626                 Picker("Model", selection: $settings.model) {
    627                     Text("Bühlmann").tag(DecoModel.buhlmann)
    628                     Text(verbatim: "VPM-B").tag(DecoModel.vpmb)
    629                     Text("Recreational").tag(DecoModel.recreational)
    630                 }
    631                 .pickerStyle(.segmented)
    632                 if settings.model == .vpmb {
    633                     Stepper("Conservatism: +\(settings.vpmbConservatism)", value: $settings.vpmbConservatism, in: 0...4)
    634                 }
    635             } header: {
    636                 Text("Decompression model")
    637             } footer: {
    638                 if settings.model == .recreational {
    639                     Text("No-stop diving: the bottom time is extended as far as a direct ascent stays allowed and the gas lasts, reserve kept.")
    640                 }
    641             }
    642             if settings.model != .vpmb {
    643             Section {
    644                 Menu {
    645                     ForEach(Conservatism.allCases) { level in
    646                         Button(level.label) {
    647                             settings.gfLow = level.gradientFactors.low
    648                             settings.gfHigh = level.gradientFactors.high
    649                         }
    650                     }
    651                 } label: {
    652                     Label("Usual settings", systemImage: "list.bullet")
    653                 }
    654                 NumberRow(title: "GF low", value: fraction(\.gfLow), unit: "%", range: 10...100, step: 5)
    655                 NumberRow(title: "GF high", value: fraction(\.gfHigh), unit: "%", range: 10...100, step: 5)
    656             } header: {
    657                 Text("Gradient factors")
    658             } footer: {
    659                 Text("Lower figures are more conservative. The low factor sets how deep the first stop is, the high one how much is left on surfacing.")
    660             }
    661             }
    662             Section("Speeds") {
    663                 NumberRow(title: "Descent", value: units.depthBinding($settings.descentRate), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(40), step: units.depthStep)
    664                 NumberRow(title: "Ascent, deepest quarter", value: units.depthBinding($settings.ascentRate75), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
    665                 NumberRow(title: "Ascent, to half the depth", value: units.depthBinding($settings.ascentRate50), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
    666                 NumberRow(title: "Ascent, up to \(units.depth(6))", value: units.depthBinding($settings.ascentRateStops), unit: "\(units.depthUnit)/min", range: 1...units.depthValue(18), step: units.depthStep)
    667                 NumberRow(title: "Ascent above \(units.depth(6))", value: units.depthBinding($settings.ascentRateLast6m), unit: "\(units.depthUnit)/min",
    668                           range: 1...units.depthValue(18), step: units.depthStep)
    669             }
    670             Section("Stops") {
    671                 Toggle("Last stop at \(units.depth(6))", isOn: $settings.lastStopAt6m)
    672                 Toggle("Safety stop when no stop is needed", isOn: $settings.safetyStop)
    673                 NumberRow(title: "Gas switch", value: $settings.gasSwitchSeconds, unit: "s", range: 0...300, step: 30)
    674                 Toggle("Switch gas only at required stops", isOn: $settings.switchOnlyAtRequiredStops)
    675                 Toggle("Breaks during oxygen stops", isOn: $settings.oxygenBreaks)
    676                 NumberRow(title: "Time shown at the surface", value: $settings.surfaceSegmentMinutes, unit: "min", range: 0...60, step: 1)
    677             }
    678             Section("Consumption at the surface") {
    679                 NumberRow(title: "At the bottom", value: $settings.sacBottom, unit: "L/min", digits: 1, range: 5...60, step: 1)
    680                 NumberRow(title: "Ascent and stops", value: $settings.sacDeco, unit: "L/min", digits: 1, range: 5...60, step: 1)
    681             }
    682             Section {
    683                 NumberRow(title: "Problem at the bottom", value: $settings.problemMinutes, unit: "min", range: 0...10, step: 1)
    684                 NumberRow(title: "Consumption factor", value: $settings.minimumGasFactor, unit: "×", digits: 1, range: 1...6, step: 0.5)
    685                 NumberRow(title: "Reserve in each cylinder", value: units.pressureBinding($settings.reserveBar), unit: units.pressureUnit, range: 0...units.pressureValue(150))
    686             } header: {
    687                 Text("Minimum gas")
    688             }
    689             Section("Oxygen limits") {
    690                 NumberRow(title: "At the bottom", value: $settings.ppO2Bottom, unit: "bar", digits: 1, range: 1...1.6, step: 0.1)
    691                 NumberRow(title: "Decompression", value: $settings.ppO2Deco, unit: "bar", digits: 1, range: 1...1.6, step: 0.1)
    692             }
    693             Section("Water") {
    694                 Picker("Water", selection: Binding(get: { (settings.environment.waterDensity * 100).rounded() / 100 },
    695                                                    set: { settings.environment.waterDensity = $0 })) {
    696                     Text("Sea").tag(1.03)
    697                     Text(verbatim: "EN 13319").tag(1.02)
    698                     Text("Fresh").tag(1.0)
    699                 }
    700                 .pickerStyle(.segmented)
    701                 NumberRow(title: "Altitude", value: altitude(units), unit: units.depthUnit, range: 0...units.depthValue(5000), step: units.imperial ? 500 : 100)
    702                 NumberRow(title: "Pressure at the surface", value: $settings.environment.surfacePressure, unit: "bar", digits: 3, range: 0.5...1.1)
    703             }
    704         }
    705         .navigationTitle("Settings")
    706         .navigationBarTitleDisplayMode(.inline)
    707     }
    708 
    709     private func altitude(_ units: Units) -> Binding<Double> {
    710         Binding {
    711             units.depthValue(max(0, settings.environment.altitude)).rounded()
    712         } set: {
    713             settings.environment.altitude = units.metersFromDisplay($0)
    714         }
    715     }
    716 
    717     private func fraction(_ path: WritableKeyPath<PlanSettings, Double>) -> Binding<Double> {
    718         Binding {
    719             (settings[keyPath: path] * 100).rounded()
    720         } set: {
    721             settings[keyPath: path] = $0 / 100
    722         }
    723     }
    724 }
    725 
    726 /// Saves the plan as a dive of the logbook, the way Subsurface does: a dive whose computer is "planned dive",
    727 /// with the planned profile and the plan written in its notes.
    728 struct SavePlanView: View {
    729     @Environment(AppModel.self) private var model
    730     @Environment(\.dismiss) private var dismiss
    731     let plan: DivePlan
    732     let result: PlanResult
    733     @State var date: Date
    734     @State private var working = false
    735     @State private var error: String?
    736 
    737     var body: some View {
    738         NavigationStack {
    739             Form {
    740                 Section {
    741                     DatePicker("Start", selection: $date)
    742                 } footer: {
    743                     Text("The plan becomes a dive of the logbook, marked as planned, with its profile and the plan in its notes. It is sent to the Subsurface cloud like any other dive.")
    744                 }
    745                 Section("Notes") {
    746                     Text(PlanText.notes(plan: plan, result: result, units: model.units))
    747                         .font(.footnote.monospaced())
    748                 }
    749                 if let error {
    750                     Section { Text(error).foregroundStyle(.red) }
    751                 }
    752             }
    753             .navigationTitle("Save the plan")
    754             .navigationBarTitleDisplayMode(.inline)
    755             .toolbar {
    756                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
    757                 ToolbarItem(placement: .confirmationAction) {
    758                     Button("Save", action: save).disabled(working)
    759                 }
    760             }
    761         }
    762     }
    763 
    764     private func save() {
    765         working = true
    766         var dive = ImportedDive(when: DiveDate.naive(from: date), durationSeconds: Int(result.runtime.rounded()))
    767         dive.model = "planned dive"
    768         dive.sourceID = "plan-\(dive.when)"
    769         dive.notes = PlanText.notes(plan: plan, result: result, units: model.units)
    770         dive.surfacePressureBar = plan.settings.environment.surfacePressure
    771         dive.salinity = Int((plan.settings.environment.waterDensity * 1000).rounded())
    772         dive.samples = result.points.map { point in
    773             var sample = ImportedDive.Sample(time: Int(point.time.rounded()), depth: (point.depth * 100).rounded() / 100)
    774             if plan.cylinders.indices.contains(point.cylinder) {
    775                 sample.o2 = plan.cylinders[point.cylinder].gas.o2Percent
    776                 sample.he = plan.cylinders[point.cylinder].gas.hePercent
    777             }
    778             return sample
    779         }
    780         Task {
    781             do {
    782                 if try await model.importDives([dive]) == 0 {
    783                     throw AppError.message(String(localized: "The logbook already has a planned dive at that time."))
    784                 }
    785                 dismiss()
    786             } catch {
    787                 self.error = AppModel.describe(error)
    788                 working = false
    789             }
    790         }
    791     }
    792 }
    793 
    794 /// The plan as text, for the notes of the saved dive.
    795 enum PlanText {
    796     static func notes(plan: DivePlan, result: PlanResult, units: Units) -> String {
    797         func name(_ index: Int) -> String { plan.cylinders.indices.contains(index) ? plan.cylinders[index].gas.name : "?" }
    798         let settings = plan.settings
    799         var lines = [String]()
    800         let model = settings.model == .vpmb
    801             ? "VPM-B +\(settings.vpmbConservatism)"
    802             : "Bühlmann ZHL-16C GF \(Int((settings.gfLow * 100).rounded()))/\(Int((settings.gfHigh * 100).rounded()))"
    803         lines.append(String(localized: "Dive plan made with \(Brand.name) \(Brand.shortVersion) (\(model))"))
    804         switch plan.mode {
    805         case .openCircuit: break
    806         case .closedCircuit: lines.append(String(localized: "Closed circuit, setpoint \(fixed(plan.setpoint, 2)) bar") + (plan.bailout ? String(localized: ", open-circuit bailout") : ""))
    807         case .semiClosed: lines.append(String(localized: "Semi-closed circuit") + (plan.bailout ? String(localized: ", open-circuit bailout") : ""))
    808         }
    809         lines.append("")
    810         for level in plan.levels {
    811             lines.append(String(localized: "\(units.depth(level.depth)) for \(Int(level.minutes.rounded())) min on \(name(level.cylinder))"))
    812         }
    813         lines.append("")
    814         for stop in result.stops {
    815             let minutes = Int((stop.seconds / 60).rounded()), end = Int((stop.endTime / 60).rounded())
    816             lines.append(String(localized: "Stop at \(units.depth(stop.depth)): \(minutes) min on \(name(stop.cylinder)), until \(end) min"))
    817         }
    818         lines.append(String(localized: "Run time: \(Int((result.runtime / 60).rounded())) min"))
    819         lines.append("")
    820         for (index, cylinder) in plan.cylinders.enumerated() where result.gasUsed.indices.contains(index) && result.gasUsed[index] > 0 {
    821             var line = "\(cylinder.gas.name): \(fixed(result.gasUsed[index], 0)) L"
    822             if let start = cylinder.startBar, let left = cylinder.pressure(afterUsing: result.gasUsed[index]) {
    823                 line += " (\(units.pressure(start)) → \(units.pressure(max(0, left))))"
    824             }
    825             lines.append(line)
    826         }
    827         lines.append(String(localized: "CNS \(fixed(result.cns * 100, 0)) %, OTU \(fixed(result.otu, 0))"))
    828         return lines.joined(separator: "\n")
    829     }
    830 }