open-remora

Open Remora, a free secondary dive computer for Apple Watch Ultra
git clone https://git.schurger.org/open-remora.git
Log | Files | Refs | README | LICENSE

RootView.swift (10710B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import SwiftUI
      3 import RemoraDeco
      4 import RemoraUI
      5 
      6 struct RootView: View {
      7     @Environment(LogStore.self) private var store
      8     @Environment(DiveSession.self) private var session
      9     @State private var path: [DiveLog] = []
     10     @AppStorage("showDemo") private var showDemo = true
     11     @AppStorage(Setup.key) private var setupDone = 0
     12 
     13     /// Screenshots skip the introduction (`-acceptTerms`); `-setup` shows it.
     14     private var needsSetup: Bool {
     15         if CommandLine.arguments.contains("-setup") { return setupDone < Setup.version }
     16         return setupDone < Setup.version && !CommandLine.arguments.contains("-acceptTerms")
     17     }
     18 
     19     /// The dive and "Ready" screens replace the home screen instead of covering it: a cover gets a close
     20     /// button from the system, which the locked touch screen makes useless and which must not end anything.
     21     var body: some View {
     22         Group {
     23             if needsSetup {
     24                 SetupView()
     25             } else if session.isDiving {
     26                 NavigationStack { DiveView() }
     27             } else if session.isReady {
     28                 NavigationStack { ReadyView() }
     29             } else {
     30                 home
     31             }
     32         }
     33         .onChange(of: session.finishedDive) { _, dive in
     34             guard let dive else { return }
     35             path = [dive]
     36             session.finishedDive = nil
     37         }
     38         .task(id: needsSetup) {
     39             // The permissions are asked by the introduction; afterwards this only starts the sensor.
     40             guard !needsSetup else { return }
     41             session.listen()
     42             if !CommandLine.arguments.contains("-demo") { await session.workout.requestAuthorization() }
     43         }
     44         .task {
     45             if CommandLine.arguments.contains(where: { $0 == "-showDive" || $0 == "-showProfile" }), let dive = store.dives.first { path = [dive] }
     46             if CommandLine.arguments.contains("-simulate") {
     47                 session.startSimulation(CommandLine.arguments.contains("-deep") ? .deep : .reef,
     48                                         speed: CommandLine.arguments.contains("-slow") ? 8 : 30)
     49             }
     50             if CommandLine.arguments.contains("-ready") { session.getReady() }
     51         }
     52     }
     53 
     54     private var dives: [DiveLog] { showDemo ? store.dives : store.dives.filter { $0.source != .simulation } }
     55 
     56     private var home: some View {
     57         NavigationStack(path: $path) {
     58             List {
     59                 if session.sensorAvailable {
     60                     Section {
     61                         Button { session.getReady() } label: {
     62                             Label("Ready to dive", systemImage: "figure.open.water.swim")
     63                                 .font(.headline)
     64                         }
     65                         .listItemTint(.cyan)
     66                     } footer: {
     67                         Text("Takes the GPS position, starts the dive session and locks the screen (long press on the crown to unlock). Without it, the dive still starts on submersion.")
     68                     }
     69                 }
     70 
     71                 Section("Logbook") {
     72                     if dives.isEmpty {
     73                         Text("No dives").foregroundStyle(.secondary)
     74                     }
     75                     ForEach(dives) { dive in
     76                         NavigationLink(value: dive) { DiveRow(dive: dive) }
     77                     }
     78                     .onDelete { offsets in
     79                         let dives = dives
     80                         for i in offsets { store.remove(dives[i]) }
     81                     }
     82                 }
     83 
     84                 Section {
     85                     if session.sensorAvailable {
     86                         Label("Get in the water: the dive starts by itself", systemImage: "water.waves")
     87                             .font(.footnote)
     88                     } else {
     89                         Label("No depth sensor on this watch", systemImage: "exclamationmark.triangle")
     90                             .font(.footnote)
     91                             .foregroundStyle(.orange)
     92                     }
     93                     Text("\(store.settings.gas.description) · \(store.settings.gradientFactors.description)")
     94                         .font(.footnote)
     95                         .foregroundStyle(.secondary)
     96                 }
     97 
     98                 Section {
     99                     NavigationLink { CompassScreen() } label: { Label("Compass", systemImage: "location.north.line") }
    100                     NavigationLink { SettingsView() } label: { Label("Settings", systemImage: "gearshape") }
    101                     NavigationLink { OptionsView() } label: { Label("Options", systemImage: "slider.horizontal.3") }
    102                     if showDemo {
    103                         Button { session.startSimulation() } label: {
    104                             Label("Demo dive", systemImage: "play.circle")
    105                         }
    106                     }
    107                 } footer: {
    108                     Text("Secondary computer, not certified. To be used with a primary dive computer.")
    109                 }
    110             }
    111             .navigationTitle("Open Rémora")
    112             .navigationDestination(for: DiveLog.self) { dive in
    113                 if CommandLine.arguments.contains("-showProfile") { ProfileView(dive: dive) }
    114                 else { DiveDetailView(dive: dive) }
    115             }
    116         }
    117     }
    118 }
    119 
    120 /// One logbook row: the essentials at a glance.
    121 struct DiveRow: View {
    122     let dive: DiveLog
    123 
    124     var body: some View {
    125         HStack(alignment: .firstTextBaseline) {
    126             VStack(alignment: .leading, spacing: 2) {
    127                 Text("\(Format.depth(dive.maxDepth)) m · \(Format.minutes(dive.duration))")
    128                     .font(.headline)
    129                 Text("No. \(dive.number) · \(Format.day(dive.start))")
    130                     .font(.caption2)
    131                     .foregroundStyle(.secondary)
    132             }
    133             Spacer()
    134             if !dive.violations.isEmpty {
    135                 Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.red)
    136             } else if dive.hadDecompression {
    137                 Text("STOPS").font(.system(size: 9, weight: .bold)).foregroundStyle(.orange)
    138             }
    139         }
    140     }
    141 }
    142 
    143 /// Waiting for submersion: the session is running, the entry position is being taken, the screen recalls the
    144 /// gas, the conservatism and the battery. The Action button starts the dive without waiting for the water.
    145 struct ReadyView: View {
    146     @Environment(LogStore.self) private var store
    147     @Environment(DiveSession.self) private var session
    148 
    149     var body: some View {
    150         let locked = session.screenLocked
    151         VStack(spacing: 4) {
    152             Label("Ready", systemImage: "water.waves").font(.title3.bold()).foregroundStyle(.cyan)
    153             Text("Starts on submersion or with the Action button").font(.caption2)
    154                 .foregroundStyle(.secondary).multilineTextAlignment(.center)
    155                 .lineLimit(2).minimumScaleFactor(0.7).fixedSize(horizontal: false, vertical: true)
    156             PositionLine(position: session.position)
    157             if locked {
    158                 Label("Screen locked: long press on the crown", systemImage: "lock.fill")
    159                     .font(.caption2).foregroundStyle(.cyan).multilineTextAlignment(.center)
    160             }
    161             Text("\(store.settings.gas.description) · \(store.settings.gradientFactors.description)")
    162                 .font(.footnote)
    163             let mod = store.settings.maximumOperatingDepth()
    164             Text(mod > 40 ? "max 40 m (watch limit)" : "max \(Format.depth(mod)) m for this gas")
    165                 .font(.caption2).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.7)
    166             if let level = session.batteryLevel {
    167                 Label(Format.percent(Int((level * 100).rounded())), systemImage: level < 0.3 ? "battery.25" : "battery.100")
    168                     .font(.footnote)
    169                     .foregroundStyle(level < 0.3 ? .red : .secondary)
    170                 if level < 0.3 { Text("Low battery").font(.caption2.bold()).foregroundStyle(.red) }
    171             }
    172         }
    173         .toolbar {
    174             // Useless while the touch screen is locked: it comes back once unlocked (long press on the crown).
    175             if !locked {
    176                 ToolbarItem(placement: .cancellationAction) {
    177                     Button("Cancel") { session.cancelReady() }
    178                 }
    179             }
    180         }
    181     }
    182 }
    183 
    184 /// Entry position on the "Ready" screen: searching, taken (with its uncertainty), or not allowed.
    185 private struct PositionLine: View {
    186     let position: EntryPosition
    187 
    188     var body: some View {
    189         Group {
    190             if let fix = position.fix {
    191                 Label("Position taken (±\(Int(fix.horizontalAccuracy.rounded())) m)", systemImage: "location.fill")
    192                     .foregroundStyle(.green)
    193             } else {
    194                 switch position.state {
    195                 case .denied:
    196                     Label("No position: location not allowed", systemImage: "location.slash").foregroundStyle(.orange)
    197                 case .unavailable:
    198                     Label("No position", systemImage: "location.slash").foregroundStyle(.orange)
    199                 default:
    200                     Label("Looking for the GPS position…", systemImage: "location").foregroundStyle(.secondary)
    201                 }
    202             }
    203         }
    204         .font(.caption2)
    205         .multilineTextAlignment(.center)
    206     }
    207 }
    208 
    209 /// Result of the last trial: Action button received by the app, Apple's dive session.
    210 struct DiagnosticsRows: View {
    211     @Environment(DiveSession.self) private var session
    212 
    213     var body: some View {
    214         let d = session.diagnostics
    215         VStack(alignment: .leading, spacing: 2) {
    216             // Plural forms are in the String Catalog.
    217             Text("Action button: \(d.presses) presses received")
    218             if let depth = d.deepestPress {
    219                 Text("deepest at \(Format.depth(depth)) m").foregroundStyle(.secondary)
    220             }
    221             Text("Next action: \(d.donation)").foregroundStyle(.secondary)
    222             Text("Workout: \(d.workout)").foregroundStyle(.secondary)
    223             Text("Dive session: \(d.runtime)").foregroundStyle(.secondary)
    224             Text(d.lockSeen ? "Screen lock: seen" : "Screen lock: not seen").foregroundStyle(.secondary)
    225             if let start = d.startedAt {
    226                 Text(start.formatted(date: .abbreviated, time: .shortened)).foregroundStyle(.secondary)
    227             }
    228             Text(verbatim: "Open Rémora \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?") (\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?"))")
    229                 .foregroundStyle(.secondary)
    230         }
    231         .font(.caption2)
    232     }
    233 }