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

SettingsView.swift (12980B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import SwiftUI
      3 
      4 struct SettingsView: View {
      5     @Environment(AppModel.self) private var model
      6     @State private var confirmingSignOut = false
      7     @State private var importing = false
      8     @State private var downloading = false
      9     @State private var exporting = false
     10     @State private var connecting = LaunchOptions.flag("-connectCloud")
     11     @State private var showingCards = LaunchOptions.flag("-cards")
     12     @Environment(CardStore.self) private var cards
     13 
     14     private var about: String {
     15         String(localized: "\(Brand.name) reads and edits the logbook that Subsurface keeps in its cloud, in the same format. It is an independent app, not affiliated with the Subsurface team. It replaces neither a dive computer nor proper training.")
     16     }
     17 
     18     var body: some View {
     19         NavigationStack {
     20             List {
     21                 Section("Account") {
     22                     if model.isDemo {
     23                         Label("Demo logbook", systemImage: "sparkles")
     24                         Text("Changes stay on this iPhone and disappear when you leave the demo.")
     25                             .font(.footnote)
     26                             .foregroundStyle(.secondary)
     27                     } else if model.isLocal {
     28                         Label("Logbook on this iPhone", systemImage: "iphone")
     29                         Text("No Subsurface cloud account: the logbook is kept on this iPhone. Connect an account to use it in Subsurface too, on a computer for instance.")
     30                             .font(.footnote)
     31                             .foregroundStyle(.secondary)
     32                         Button { connecting = true } label: {
     33                             Label("Connect to Subsurface cloud…", systemImage: "cloud")
     34                         }
     35                     } else {
     36                         LabeledContent("Subsurface cloud", value: model.email)
     37                         LabeledContent("Last sync") {
     38                             switch model.syncState {
     39                             case .syncing: ProgressView()
     40                             default: Text(model.lastSync.map { $0.formatted(.relative(presentation: .named)) } ?? String(localized: "Never"))
     41                             }
     42                         }
     43                         if case .failed(let message) = model.syncState {
     44                             Label(message, systemImage: "exclamationmark.triangle.fill")
     45                                 .font(.footnote)
     46                                 .foregroundStyle(.red)
     47                         }
     48                         Button {
     49                             Task { await model.sync() }
     50                         } label: {
     51                             Label("Sync now", systemImage: "arrow.triangle.2.circlepath")
     52                         }
     53                         .disabled(model.syncState == .syncing)
     54                     }
     55                 }
     56 
     57                 if !model.isDemo {
     58                     Section {
     59                         LabeledContent("Logbook and settings") { BackupStatus(state: model.backup.state) }
     60                     } header: {
     61                         Text("iCloud backup")
     62                     } footer: {
     63                         Text("A copy of the logbook and of the settings goes to the Sub Rascasse folder of your iCloud Drive after each change, with one archive per day for the last week. Your photos are not copied.")
     64                     }
     65                 }
     66 
     67                 if !model.pending.isEmpty {
     68                     Section("Waiting to upload") {
     69                         ForEach(Array(model.pending.enumerated()), id: \.offset) { _, change in
     70                             Text(AppModel.summary(change)).font(.callout)
     71                         }
     72                     }
     73                 }
     74 
     75                 Section("Display") {
     76                     Picker("Units", selection: Binding(get: { model.units.imperial }, set: { model.setImperial($0) })) {
     77                         Text("Metric (m, °C, bar)").tag(false)
     78                         Text("Imperial (ft, °F, psi)").tag(true)
     79                     }
     80                 }
     81 
     82                 Section("Logbook") {
     83                     LabeledContent("Dives", value: "\(model.logbook.dives.count)")
     84                     LabeledContent("Sites", value: "\(model.logbook.sites.count)")
     85                     LabeledContent("Trips", value: "\(model.logbook.trips.count)")
     86                     Button { downloading = true } label: {
     87                         Label("Download from a dive computer…", systemImage: "gauge.with.dots.needle.bottom.50percent")
     88                     }
     89                     Button { importing = true } label: {
     90                         Label("Import a file…", systemImage: "square.and.arrow.down")
     91                     }
     92                     Button { exporting = true } label: {
     93                         Label("Export as UDDF…", systemImage: "square.and.arrow.up")
     94                     }
     95                     .disabled(model.logbook.dives.isEmpty)
     96                     ForEach(model.logbook.warnings, id: \.self) { warning in
     97                         Label(warning, systemImage: "exclamationmark.triangle")
     98                             .font(.footnote)
     99                             .foregroundStyle(.orange)
    100                     }
    101                 }
    102 
    103                 Section {
    104                     Button { showingCards = true } label: {
    105                         HStack {
    106                             Label("Certification cards", systemImage: "person.text.rectangle")
    107                             Spacer()
    108                             Text("\(cards.cards.count)").foregroundStyle(.secondary)
    109                             Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(.tertiary)
    110                         }
    111                     }
    112                     .foregroundStyle(.primary)
    113                 } header: {
    114                     Text("Diver")
    115                 }
    116 
    117                 Section {
    118                     LabeledContent("Version", value: Brand.version)
    119                     Text(about)
    120                         .font(.footnote)
    121                         .foregroundStyle(.secondary)
    122                     Text("Free software under the GPL 2.0 licence. Dive computers are read with libdivecomputer (LGPL 2.1). Source code: git.schurger.org/subrascasse")
    123                         .font(.footnote)
    124                         .foregroundStyle(.secondary)
    125                 } header: {
    126                     Text("About")
    127                 }
    128 
    129                 Section {
    130                     Button(model.isDemo ? String(localized: "Leave the demo")
    131                            : (model.isLocal ? String(localized: "Erase the logbook from this iPhone") : String(localized: "Sign out")), role: .destructive) {
    132                         confirmingSignOut = true
    133                     }
    134                 }
    135             }
    136             .listStyle(.insetGrouped)
    137             .navigationTitle("Settings")
    138             .navigationDestination(isPresented: $showingCards) { CardsView() }
    139             .modifier(FileImport(isPresented: $importing))
    140             .modifier(UDDFExport(isPresented: $exporting))
    141             .modifier(DiveComputerImport(isPresented: $downloading))
    142             .sheet(isPresented: $connecting) { ConnectCloudView() }
    143             .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?")
    144                                 : (model.isLocal ? String(localized: "Erase the logbook?") : String(localized: "Sign out?")),
    145                                 isPresented: $confirmingSignOut, titleVisibility: .visible) {
    146                 if model.isDemo {
    147                     Button("Leave", role: .destructive) { Task { await model.signOut() } }
    148                 } else if model.isLocal {
    149                     Button("Erase", role: .destructive) { Task { await model.signOut() } }
    150                 } else {
    151                     Button("Sign out and keep the logbook on this iPhone") { Task { await model.signOut(keepLogbook: true) } }
    152                     Button("Sign out and erase the copy", role: .destructive) { Task { await model.signOut() } }
    153                 }
    154             } message: {
    155                 if model.isLocal {
    156                     Text("The logbook is removed from this iPhone. The last copy saved in iCloud Drive, if any, stays there.")
    157                 } else if !model.isDemo, !model.pending.isEmpty {
    158                     Text("Warning: \(model.pending.count) change(s) not yet uploaded will be lost if you erase the copy. Nothing is deleted in the cloud.")
    159                 } else if !model.isDemo {
    160                     Text("Keeping the logbook lets you go on without the Subsurface cloud. Nothing is deleted in the cloud either way.")
    161                 }
    162             }
    163         }
    164     }
    165 }
    166 
    167 /// State of an iCloud backup, in a few words.
    168 struct BackupStatus: View {
    169     let state: LogbookBackup.State
    170 
    171     var body: some View {
    172         switch state {
    173         case .unknown: Text("Not yet").foregroundStyle(.secondary)
    174         case .working: ProgressView()
    175         case .notBuiltIn: Text("Not in this version").foregroundStyle(.secondary)
    176         case .unavailable: Text("iCloud Drive is off").foregroundStyle(.orange)
    177         case .done(let date): Text(date.formatted(.relative(presentation: .named)))
    178         case .failed(let message): Text(message).foregroundStyle(.red)
    179         }
    180     }
    181 }
    182 
    183 /// Connects a logbook kept on this iPhone to a Subsurface cloud account.
    184 struct ConnectCloudView: View {
    185     @Environment(AppModel.self) private var model
    186     @Environment(\.dismiss) private var dismiss
    187     @State private var email = ""
    188     @State private var password = ""
    189     @State private var busy = false
    190     @State private var creating = false
    191     @State private var error: String?
    192     @State private var conflict: AppModel.CloudNotEmpty?
    193 
    194     var body: some View {
    195         NavigationStack {
    196             Form {
    197                 Section {
    198                     TextField("Subsurface account email", text: $email)
    199                         .textContentType(.username)
    200                         .keyboardType(.emailAddress)
    201                         .textInputAutocapitalization(.never)
    202                         .autocorrectionDisabled()
    203                     SecureField("Password", text: $password)
    204                         .textContentType(.password)
    205                 } footer: {
    206                     Text("The logbook of this iPhone is sent to the account, then kept in sync with it. If the account already has dives, you choose which logbook stays.")
    207                 }
    208                 Section {
    209                     Button("Create an account") { creating = true }
    210                     Link("Forgot password?", destination: URL(string: "https://cloud.subsurface-divelog.org/passwordreset")!)
    211                 }
    212                 if let error {
    213                     Section { Text(error).foregroundStyle(.red) }
    214                 }
    215             }
    216             .navigationTitle("Subsurface cloud")
    217             .navigationBarTitleDisplayMode(.inline)
    218             .toolbar {
    219                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
    220                 ToolbarItem(placement: .confirmationAction) {
    221                     if busy { ProgressView() } else {
    222                         Button("Connect") { connect(keepLocal: nil) }.disabled(email.isEmpty || password.isEmpty)
    223                     }
    224                 }
    225             }
    226             .sheet(isPresented: $creating) {
    227                 CreateAccountView { newEmail, newPassword in
    228                     email = newEmail
    229                     password = newPassword
    230                     connect(keepLocal: nil)
    231                 }
    232             }
    233             .confirmationDialog("This account already has a logbook", isPresented: Binding(get: { conflict != nil }, set: { if !$0 { conflict = nil } }),
    234                                 titleVisibility: .visible) {
    235                 Button("Send this iPhone's logbook to the account") { connect(keepLocal: true) }
    236                 Button("Use the account's logbook") { connect(keepLocal: false) }
    237                 Button("Cancel", role: .cancel) {}
    238             } message: {
    239                 if let conflict {
    240                     Text("The account holds \(conflict.cloudDives) dives, this iPhone \(conflict.localDives). The two are not mixed: the one you do not keep stays recoverable, in the history of the account or in the iCloud backups of the last week.")
    241                 }
    242             }
    243         }
    244         .interactiveDismissDisabled(busy)
    245     }
    246 
    247     private func connect(keepLocal: Bool?) {
    248         guard !busy else { return }
    249         busy = true
    250         error = nil
    251         Task {
    252             do {
    253                 try await model.connectCloud(email: email, password: password, keepLocal: keepLocal)
    254                 dismiss()
    255             } catch let found as AppModel.CloudNotEmpty {
    256                 conflict = found
    257             } catch {
    258                 self.error = AppModel.describe(error)
    259             }
    260             busy = false
    261         }
    262     }
    263 }