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

SavedPlans.swift (15632B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import DivePlanner
      3 import Observation
      4 import SwiftUI
      5 import UIKit
      6 
      7 /// A plan kept for later: its name, the plan, and the date it is meant for.
      8 struct SavedPlan: Codable, Identifiable, Equatable {
      9     var id = UUID()
     10     var name: String
     11     var plan: DivePlan
     12     /// Seconds since 1970 of the planned start.
     13     var date: Double
     14     var modified = Date()
     15 }
     16 
     17 /// The saved plans. They live in the app's settings, so they go to the iCloud backup with them.
     18 @MainActor
     19 @Observable
     20 final class PlanLibrary {
     21     private(set) var plans: [SavedPlan] = []
     22     private static let key = "savedPlans"
     23 
     24     init() {
     25         guard let data = UserDefaults.standard.data(forKey: Self.key) else { return }
     26         let decoder = JSONDecoder()
     27         decoder.dateDecodingStrategy = .iso8601
     28         plans = (try? decoder.decode([SavedPlan].self, from: data)) ?? []
     29     }
     30 
     31     private func persist() {
     32         let encoder = JSONEncoder()
     33         encoder.dateEncodingStrategy = .iso8601
     34         if let data = try? encoder.encode(plans) { UserDefaults.standard.set(data, forKey: Self.key) }
     35     }
     36 
     37     func plan(id: String) -> SavedPlan? { plans.first { $0.id.uuidString == id } }
     38 
     39     /// Adds the plan, or replaces the one with the same identifier.
     40     func save(_ plan: SavedPlan) {
     41         var saved = plan
     42         saved.modified = Date()
     43         if let index = plans.firstIndex(where: { $0.id == saved.id }) { plans[index] = saved } else { plans.append(saved) }
     44         persist()
     45     }
     46 
     47     func delete(_ plan: SavedPlan) {
     48         plans.removeAll { $0.id == plan.id }
     49         persist()
     50     }
     51 
     52     @discardableResult
     53     func duplicate(_ plan: SavedPlan) -> SavedPlan {
     54         var copy = plan
     55         copy.id = UUID()
     56         copy.name = String(localized: "\(plan.name) (copy)")
     57         save(copy)
     58         return copy
     59     }
     60 
     61     func rename(_ plan: SavedPlan, to name: String) {
     62         guard var changed = plans.first(where: { $0.id == plan.id }) else { return }
     63         changed.name = name
     64         save(changed)
     65     }
     66 }
     67 
     68 extension DivePlan {
     69     /// A name made of what tells plans apart: deepest level, its time, the gases.
     70     func suggestedName(units: Units) -> String {
     71         guard let deepest = levels.max(by: { $0.depth < $1.depth }) else { return String(localized: "Plan") }
     72         let gases = cylinders.map(\.gas.name).joined(separator: ", ")
     73         return "\(units.depth(deepest.depth)) · \(Int(levels.reduce(0) { $0 + $1.minutes }.rounded())) min · \(gases)"
     74     }
     75 }
     76 
     77 /// The list of saved plans: open one, duplicate it, rename it, delete it.
     78 struct SavedPlansView: View {
     79     @Environment(AppModel.self) private var model
     80     @Environment(\.dismiss) private var dismiss
     81     let library: PlanLibrary
     82     let currentID: String
     83     let onOpen: (SavedPlan) -> Void
     84     @State private var renaming: SavedPlan?
     85     @State private var newName = ""
     86 
     87     var body: some View {
     88         List {
     89             if library.plans.isEmpty {
     90                 ContentUnavailableView("No saved plan", systemImage: "tray",
     91                                        description: Text("Save the plan you are working on to find it here, with its name."))
     92             }
     93             ForEach(library.plans.sorted { $0.modified > $1.modified }) { saved in
     94                 Button {
     95                     onOpen(saved)
     96                     dismiss()
     97                 } label: {
     98                     HStack {
     99                         VStack(alignment: .leading, spacing: 3) {
    100                             Text(saved.name).font(.body.weight(.medium)).foregroundStyle(Color.primary)
    101                             Text(saved.plan.suggestedName(units: model.units))
    102                                 .font(.caption)
    103                                 .foregroundStyle(.secondary)
    104                         }
    105                         Spacer(minLength: 8)
    106                         if saved.id.uuidString == currentID {
    107                             Image(systemName: "checkmark").foregroundStyle(Color.accentColor)
    108                         }
    109                     }
    110                     .contentShape(Rectangle())
    111                 }
    112                 .buttonStyle(.plain)
    113                 .swipeActions {
    114                     Button("Delete", role: .destructive) { library.delete(saved) }
    115                     Button("Duplicate") { library.duplicate(saved) }
    116                     Button("Rename") {
    117                         newName = saved.name
    118                         renaming = saved
    119                     }
    120                     .tint(.orange)
    121                 }
    122             }
    123         }
    124         .listStyle(.insetGrouped)
    125         .navigationTitle("Saved plans")
    126         .navigationBarTitleDisplayMode(.inline)
    127         .alert("Name of the plan", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {
    128             TextField("Name", text: $newName)
    129             Button("Rename") {
    130                 if let renaming, !newName.trimmingCharacters(in: .whitespaces).isEmpty { library.rename(renaming, to: newName.trimmingCharacters(in: .whitespaces)) }
    131                 renaming = nil
    132             }
    133             Button("Cancel", role: .cancel) { renaming = nil }
    134         }
    135     }
    136 }
    137 
    138 // MARK: Printing
    139 
    140 /// The plan on paper: what goes on the slate first (run time table, gases), then the rest. Always black on white.
    141 struct PlanSheet: View {
    142     let name: String
    143     let date: Date
    144     let plan: DivePlan
    145     let result: PlanResult
    146     let units: Units
    147 
    148     private func gasName(_ index: Int) -> String { plan.cylinders.indices.contains(index) ? plan.cylinders[index].gas.name : "?" }
    149     private func minutes(_ seconds: Double) -> String { String(Int((seconds / 60).rounded())) }
    150 
    151     private var modelLine: String {
    152         let settings = plan.settings
    153         var parts = [String]()
    154         switch settings.model {
    155         case .buhlmann: parts.append("Bühlmann ZHL-16C GF \(Int((settings.gfLow * 100).rounded()))/\(Int((settings.gfHigh * 100).rounded()))")
    156         case .vpmb: parts.append("VPM-B +\(settings.vpmbConservatism)")
    157         case .recreational: parts.append(String(localized: "Recreational") + " GF \(Int((settings.gfLow * 100).rounded()))/\(Int((settings.gfHigh * 100).rounded()))")
    158         }
    159         switch plan.mode {
    160         case .openCircuit: parts.append(String(localized: "Open circuit"))
    161         case .closedCircuit: parts.append(String(localized: "Closed circuit, setpoint \(fixed(plan.setpoint, 2)) bar") + (plan.bailout ? String(localized: ", open-circuit bailout") : ""))
    162         case .semiClosed: parts.append(String(localized: "Semi-closed circuit") + (plan.bailout ? String(localized: ", open-circuit bailout") : ""))
    163         }
    164         parts.append(settings.environment.waterDensity < 1.015 ? String(localized: "Fresh water") : String(localized: "Sea water"))
    165         if settings.environment.altitude > 50 { parts.append(String(localized: "Altitude \(units.depth(settings.environment.altitude))")) }
    166         return parts.joined(separator: " · ")
    167     }
    168 
    169     var body: some View {
    170         VStack(alignment: .leading, spacing: 14) {
    171             VStack(alignment: .leading, spacing: 3) {
    172                 Text(name).font(.system(size: 20, weight: .bold))
    173                 Text(date.formatted(date: .long, time: .shortened)).font(.system(size: 11)).foregroundStyle(.gray)
    174                 Text(modelLine).font(.system(size: 11)).foregroundStyle(.gray)
    175             }
    176 
    177             HStack(spacing: 18) {
    178                 figure(String(localized: "Run time"), "\(minutes(result.runtime)) min")
    179                 figure(String(localized: "Maximum depth"), units.depth(result.maxDepth))
    180                 figure(String(localized: "Ascent and stops"), "\(minutes(result.ascentTime)) min")
    181                 figure("CNS", fixed(result.cns * 100, 0) + " %")
    182                 figure("OTU", fixed(result.otu, 0))
    183             }
    184 
    185             section(String(localized: "Run time table"))
    186             Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 5) {
    187                 GridRow {
    188                     Text("Depth")
    189                     Text("Time").gridColumnAlignment(.trailing)
    190                     Text("Run time").gridColumnAlignment(.trailing)
    191                     Text("Gas")
    192                     Text(verbatim: "")
    193                 }
    194                 .font(.system(size: 10, weight: .semibold))
    195                 .foregroundStyle(.gray)
    196                 ForEach(Array(rows.enumerated()), id: \.offset) { _, row in
    197                     GridRow {
    198                         Text(row.depth).fontWeight(.semibold)
    199                         Text(row.time)
    200                         Text(row.runtime).fontWeight(.semibold)
    201                         Text(row.gas)
    202                         Text(row.note).foregroundStyle(.gray)
    203                     }
    204                     .font(.system(size: 13).monospacedDigit())
    205                 }
    206             }
    207 
    208             section(String(localized: "Gas"))
    209             Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 5) {
    210                 ForEach(Array(plan.cylinders.enumerated()), id: \.offset) { index, cylinder in
    211                     let used = result.gasUsed.indices.contains(index) ? result.gasUsed[index] : 0
    212                     GridRow {
    213                         Text(cylinder.gas.name).fontWeight(.semibold)
    214                         Text(cylinder.isDeco
    215                              ? String(localized: "from \(units.depth(DivePlanner.switchDepth(of: cylinder, settings: plan.settings)))")
    216                              : (plan.mode == .closedCircuit ? String(localized: "Diluent") : String(localized: "Bottom gas")))
    217                         Text([cylinder.volumeLiters.map { units.volume($0) }, cylinder.startBar.map { units.pressure($0) }].compactMap { $0 }.joined(separator: " · "))
    218                         Text(fixed(used, 0) + " L").gridColumnAlignment(.trailing)
    219                         Text(cylinder.pressure(afterUsing: used).map { String(localized: "\(units.pressure(max(0, $0))) left") } ?? "")
    220                     }
    221                     .font(.system(size: 12).monospacedDigit())
    222                 }
    223             }
    224             if let minimum = result.minimumGasLiters, plan.cylinders.indices.contains(result.bottomCylinder) {
    225                 let cylinder = plan.cylinders[result.bottomCylinder]
    226                 let amount = cylinder.volumeLiters.map { units.pressure(RealGas.pressure(cylinder.gas, liters: minimum, volumeLiters: max($0, 0.1))) } ?? fixed(minimum, 0) + " L"
    227                 Text("Minimum gas when leaving the bottom: \(amount) of \(cylinder.gas.name)")
    228                     .font(.system(size: 12, weight: .semibold))
    229             }
    230 
    231             if result.points.count > 1 {
    232                 section(String(localized: "Profile"))
    233                 PlanChart(result: result, plan: plan, units: units)
    234                     .frame(height: 170)
    235             }
    236 
    237             Text("Made with \(Brand.name) \(Brand.shortVersion). A planning aid, not a dive computer: check this plan against another tool and dive within your training.")
    238                 .font(.system(size: 9))
    239                 .foregroundStyle(.gray)
    240                 .padding(.top, 4)
    241         }
    242         .padding(0)
    243         .frame(width: Self.width, alignment: .leading)
    244         .foregroundStyle(.black)
    245         .background(Color.white)
    246         .environment(\.colorScheme, .light)
    247         .dynamicTypeSize(.medium)
    248     }
    249 
    250     static let width: CGFloat = 540
    251 
    252     private struct Row {
    253         var depth: String, time: String, runtime: String, gas: String, note: String
    254     }
    255 
    256     /// The dive from top to bottom: each level, then each stop, then the surface.
    257     private var rows: [Row] {
    258         var out = [Row]()
    259         var clock = 0.0
    260         for level in plan.levels {
    261             clock += level.minutes * 60
    262             out.append(Row(depth: units.depth(level.depth), time: "\(Int(level.minutes.rounded())) min", runtime: minutes(clock),
    263                            gas: gasName(level.cylinder), note: ""))
    264         }
    265         if result.bottomExtensionMinutes > 0, let last = plan.levels.last {
    266             clock += result.bottomExtensionMinutes * 60
    267             out.append(Row(depth: units.depth(last.depth), time: "+\(Int(result.bottomExtensionMinutes.rounded())) min", runtime: minutes(clock),
    268                            gas: gasName(last.cylinder), note: String(localized: "Extension")))
    269         }
    270         for stop in result.stops.sorted(by: { $0.endTime < $1.endTime }) {
    271             let note: String
    272             switch stop.kind {
    273             case .deco: note = ""
    274             case .gasSwitch: note = String(localized: "Gas switch")
    275             case .safety: note = String(localized: "Safety stop")
    276             }
    277             out.append(Row(depth: units.depth(stop.depth), time: "\(minutes(stop.seconds)) min", runtime: minutes(stop.endTime),
    278                            gas: gasName(stop.cylinder), note: note))
    279         }
    280         out.append(Row(depth: String(localized: "Surface"), time: "", runtime: minutes(result.runtime), gas: "", note: ""))
    281         return out
    282     }
    283 
    284     private func figure(_ title: String, _ value: String) -> some View {
    285         VStack(alignment: .leading, spacing: 1) {
    286             Text(title).font(.system(size: 9)).foregroundStyle(.gray)
    287             Text(value).font(.system(size: 15, weight: .semibold).monospacedDigit())
    288         }
    289     }
    290 
    291     private func section(_ title: String) -> some View {
    292         VStack(alignment: .leading, spacing: 4) {
    293             Text(title.uppercased()).font(.system(size: 10, weight: .semibold)).foregroundStyle(.gray)
    294             Rectangle().fill(Color.gray.opacity(0.4)).frame(height: 0.5)
    295         }
    296     }
    297 
    298     /// The sheet as a PDF file (US Letter pages), ready for the share sheet and for printing.
    299     @MainActor
    300     func pdf(named fileName: String, at destination: URL? = nil) -> URL? {
    301         let safe = fileName.map { $0.isLetter || $0.isNumber || $0 == " " || $0 == "-" ? $0 : "-" }
    302         let url = destination ?? FileManager.default.temporaryDirectory.appendingPathComponent(String(safe).prefix(60) + ".pdf")
    303         let renderer = ImageRenderer(content: self)
    304         var written = false
    305         renderer.render { size, draw in
    306             let page = CGSize(width: 612, height: 792), margin: CGFloat = 36
    307             let usable = page.height - 2 * margin
    308             var box = CGRect(origin: .zero, size: page)
    309             guard let context = CGContext(url as CFURL, mediaBox: &box, nil) else { return }
    310             let pages = max(1, Int((size.height / usable).rounded(.up)))
    311             for index in 0..<pages {
    312                 context.beginPDFPage(nil)
    313                 context.saveGState()
    314                 // The page shows a slice of the sheet: the origin of a PDF page is at its bottom left.
    315                 context.clip(to: CGRect(x: margin, y: margin, width: page.width - 2 * margin, height: usable))
    316                 context.translateBy(x: margin, y: page.height - margin - size.height + CGFloat(index) * usable)
    317                 draw(context)
    318                 context.restoreGState()
    319                 context.endPDFPage()
    320             }
    321             context.closePDF()
    322             written = true
    323         }
    324         return written ? url : nil
    325     }
    326 }
    327 
    328 /// The system share sheet (Print, Files, Messages…).
    329 struct ActivityView: UIViewControllerRepresentable {
    330     let items: [Any]
    331 
    332     func makeUIViewController(context: Context) -> UIActivityViewController {
    333         UIActivityViewController(activityItems: items, applicationActivities: nil)
    334     }
    335 
    336     func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}
    337 }
    338 
    339 struct SharedFile: Identifiable {
    340     let url: URL
    341     var id: String { url.path }
    342 }