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

DiveComputerView.swift (10096B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import DiveComputerKit
      3 import SubsurfaceLog
      4 import SwiftUI
      5 import UIKit
      6 
      7 /// A downloaded dive, as the session hands it over.
      8 struct ImportedDiveBox: Identifiable {
      9     let dive: ImportedDive
     10     var id: String { dive.id }
     11 }
     12 
     13 /// Keeps the screen on while a download runs (it stops if the iPhone locks).
     14 enum UIApplicationIdleTimer {
     15     @MainActor static func disable(_ disabled: Bool) { UIApplication.shared.isIdleTimerDisabled = disabled }
     16 }
     17 
     18 /// Downloads dives from a dive computer over Bluetooth, then previews them like a file import.
     19 struct DiveComputerImport: ViewModifier {
     20     @Environment(AppModel.self) private var model
     21     @Binding var isPresented: Bool
     22     @State private var session = DiveComputerSession()
     23     @State private var downloaded: ImportBatch?
     24     @State private var batch: ImportBatch?
     25 
     26     @MainActor private static var launchOptionUsed = false
     27 
     28     func body(content: Content) -> some View {
     29         content
     30             .sheet(isPresented: $isPresented, onDismiss: {
     31                 session.stop()
     32                 batch = downloaded
     33                 downloaded = nil
     34             }) {
     35                 DiveComputerSheet(session: session) { name, dives in
     36                     let session = session
     37                     Task {
     38                         let candidates = await model.importCandidates(for: dives)
     39                         downloaded = ImportBatch(name: name, candidates: candidates, fromComputer: true) { session.rememberDownload() }
     40                         isPresented = false
     41                     }
     42                 }
     43             }
     44             .sheet(item: $batch) { ImportSheet(batch: $0) }
     45             .onAppear {
     46                 guard !Self.launchOptionUsed, LaunchOptions.flag("-diveComputer") else { return }
     47                 Self.launchOptionUsed = true
     48                 isPresented = true
     49             }
     50     }
     51 }
     52 
     53 struct DiveComputerSheet: View {
     54     @Environment(\.dismiss) private var dismiss
     55     @Environment(AppModel.self) private var model
     56     let session: DiveComputerSession
     57     /// Called with the name of the computer and its dives, to move on to the import preview.
     58     let onDives: (String, [ImportedDive]) -> Void
     59 
     60     var body: some View {
     61         NavigationStack {
     62             Group {
     63                 switch session.phase {
     64                 case .scanning: scanning
     65                 case .connecting(let computer): progress(computer, fraction: nil)
     66                 case .downloading(let computer, let fraction): progress(computer, fraction: fraction)
     67                 case .finished(let computer): finished(computer)
     68                 case .failed(let computer, let message): failed(computer, message)
     69                 }
     70             }
     71             .navigationTitle("Dive computer")
     72             .navigationBarTitleDisplayMode(.inline)
     73             .toolbar {
     74                 ToolbarItem(placement: .cancellationAction) {
     75                     Button("Close") {
     76                         session.stop()
     77                         dismiss()
     78                     }
     79                 }
     80             }
     81         }
     82         .interactiveDismissDisabled(isBusy)
     83         .onAppear { session.start() }
     84     }
     85 
     86     private var nextNumber: Int { model.logbook.nextNumber }
     87 
     88     private var isBusy: Bool {
     89         switch session.phase {
     90         case .connecting, .downloading: return true
     91         default: return false
     92         }
     93     }
     94 
     95     // MARK: Looking for computers
     96 
     97     @ViewBuilder private var scanning: some View {
     98         switch session.bluetooth {
     99         case .off:
    100             ContentUnavailableView("Bluetooth is off", systemImage: "antenna.radiowaves.left.and.right.slash",
    101                                    description: Text("Turn Bluetooth on in Control Center to reach your dive computer."))
    102         case .denied:
    103             ContentUnavailableView {
    104                 Label("Bluetooth not allowed", systemImage: "hand.raised")
    105             } description: {
    106                 Text("Allow \(Brand.name) to use Bluetooth in Settings to reach your dive computer.")
    107             } actions: {
    108                 Button("Open Settings") {
    109                     if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
    110                 }
    111             }
    112         case .unavailable:
    113             ContentUnavailableView("No Bluetooth on this device", systemImage: "antenna.radiowaves.left.and.right.slash")
    114         case .starting, .ready:
    115             List {
    116                 Section {
    117                     ForEach(session.computers) { computer in
    118                         Button {
    119                             session.download(from: computer)
    120                         } label: {
    121                             HStack(spacing: 12) {
    122                                 Image(systemName: "gauge.with.dots.needle.bottom.50percent")
    123                                     .font(.title3)
    124                                     .foregroundStyle(Color.accentColor)
    125                                     .frame(width: 30)
    126                                 VStack(alignment: .leading, spacing: 3) {
    127                                     Text(computer.name).font(.body.weight(.medium)).foregroundStyle(Color.primary)
    128                                     Text(session.hasEarlierDownload(computer)
    129                                          ? String(localized: "\(computer.model.name) · new dives only")
    130                                          : computer.model.name)
    131                                         .font(.caption)
    132                                         .foregroundStyle(.secondary)
    133                                 }
    134                                 Spacer(minLength: 8)
    135                                 Image(systemName: "arrow.down.circle").foregroundStyle(.secondary)
    136                             }
    137                             .padding(.vertical, 2)
    138                             .contentShape(Rectangle())
    139                         }
    140                         .buttonStyle(.plain)
    141                         .contextMenu {
    142                             Button { session.download(from: computer, everything: true) } label: {
    143                                 Label("Download all dives", systemImage: "arrow.down.circle.dotted")
    144                             }
    145                         }
    146                     }
    147                     HStack(spacing: 10) {
    148                         ProgressView()
    149                         Text("Looking for dive computers…").foregroundStyle(.secondary)
    150                     }
    151                 } header: {
    152                     Text("Nearby")
    153                 } footer: {
    154                     Text("Put the computer in Bluetooth mode (on a Shearwater: Menu, then Bluetooth), keep it close to the iPhone, then tap its name. The dives are read with libdivecomputer; support has only been checked on a few models so far.")
    155                 }
    156             }
    157             .listStyle(.insetGrouped)
    158         }
    159     }
    160 
    161     // MARK: Download
    162 
    163     private func progress(_ computer: DiveComputerSession.Computer, fraction: Double?) -> some View {
    164         VStack(spacing: 18) {
    165             Spacer()
    166             Image(systemName: "gauge.with.dots.needle.bottom.50percent")
    167                 .font(.system(size: 52))
    168                 .foregroundStyle(Color.accentColor)
    169             Text(computer.name).font(.title3.weight(.semibold))
    170             if let fraction {
    171                 ProgressView(value: fraction)
    172                     .frame(maxWidth: 260)
    173                 Text("Downloading… \(Int((fraction * 100).rounded())) %")
    174                     .font(.callout.monospacedDigit())
    175                     .foregroundStyle(.secondary)
    176             } else {
    177                 ProgressView()
    178                 Text("Connecting…").font(.callout).foregroundStyle(.secondary)
    179             }
    180             Text("Keep the computer close to the iPhone and leave this screen open.")
    181                 .font(.footnote)
    182                 .foregroundStyle(.secondary)
    183                 .multilineTextAlignment(.center)
    184                 .padding(.horizontal, 32)
    185             Spacer()
    186             Button("Cancel", role: .cancel) { session.cancel() }
    187                 .padding(.bottom, 24)
    188         }
    189         .frame(maxWidth: .infinity)
    190     }
    191 
    192     private func finished(_ computer: DiveComputerSession.Computer) -> some View {
    193         ContentUnavailableView {
    194             Label(session.dives.isEmpty ? String(localized: "No new dives") : String(localized: "Download complete"),
    195                   systemImage: session.dives.isEmpty ? "checkmark.circle" : "arrow.down.circle")
    196         } description: {
    197             if session.dives.isEmpty {
    198                 Text(session.onlyNewer
    199                      ? String(localized: "Nothing new on \(computer.name) since the last download.")
    200                      : String(localized: "\(computer.name) has no dives in memory."))
    201                 Text("Next dive in the logbook: no. \(nextNumber).")
    202             }
    203         } actions: {
    204             if session.dives.isEmpty {
    205                 if session.onlyNewer {
    206                     Button("Download all dives") { session.download(from: computer, everything: true) }
    207                 }
    208                 Button("Done") { dismiss() }
    209             } else {
    210                 ProgressView()
    211             }
    212         }
    213         .onAppear {
    214             guard !session.dives.isEmpty else { return }
    215             onDives(computer.name, session.dives.map(\.dive))
    216         }
    217     }
    218 
    219     private func failed(_ computer: DiveComputerSession.Computer, _ message: String) -> some View {
    220         ContentUnavailableView {
    221             Label("Download failed", systemImage: "exclamationmark.triangle")
    222         } description: {
    223             Text(message)
    224         } actions: {
    225             Button("Try again") { session.download(from: computer) }
    226                 .buttonStyle(.borderedProminent)
    227             Button("Other computer") { session.reset() }
    228             if !session.troubleshooting.isEmpty {
    229                 ShareLink(item: session.troubleshooting) {
    230                     Label("Share the technical log", systemImage: "square.and.arrow.up")
    231                 }
    232                 .font(.footnote)
    233             }
    234         }
    235     }
    236 }