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

commit b0e09cb601315106f3cf0acbda281fbf55ec2d23
parent 110a12f44e4b996a86e0d319f8387060742501d8
Author: Jean Schurger <jean@schurger.org>
Date:   Sat, 14 Nov 2026 13:45:36 -0500

Certification cards, backed up in iCloud Drive

Settings > Certification cards: agency, certification, number, date issued and
a photo of each side (camera or photo library), shown full screen. The cards
are kept on the iPhone and copied to the app's iCloud Drive folder whenever
they change; both copies are merged at launch and when the app comes back
(most recent change wins, deletions are remembered), so a new iPhone gets
them back.

iCloud Documents entitlement and container, camera usage description (en, fr),
French strings, README, version 0.5.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc

Diffstat:
MApp/DiveLogApp.swift | 8+++++++-
MApp/InfoPlist.xcstrings | 7+++++++
MApp/Localizable.xcstrings | 220+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AApp/Model/Cards.swift | 334+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AApp/Views/CardsView.swift | 322+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Views/SettingsView.swift | 17+++++++++++++++++
MREADME.md | 9++++++++-
Mfastlane/Fastfile | 4++--
Mproject.yml | 13++++++++++++-
9 files changed, 929 insertions(+), 5 deletions(-)

diff --git a/App/DiveLogApp.swift b/App/DiveLogApp.swift @@ -4,20 +4,26 @@ import SwiftUI @main struct DiveLogApp: App { @State private var model = AppModel() + @State private var cards = LaunchOptions.flag("-demoCards") ? CardStore.demo() : CardStore() @Environment(\.scenePhase) private var scenePhase var body: some Scene { WindowGroup { RootView() .environment(model) + .environment(cards) .task { + cards.sync() await model.start() await model.importSharedDives() } // Open Rémora opens "subrascasse://open-remora" after dropping a dive. .onOpenURL { _ in Task { await model.importSharedDives() } } .onChange(of: scenePhase) { - if scenePhase == .active { Task { await model.importSharedDives() } } + if scenePhase == .active { + cards.sync() + Task { await model.importSharedDives() } + } } } } diff --git a/App/InfoPlist.xcstrings b/App/InfoPlist.xcstrings @@ -8,6 +8,13 @@ "fr" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse utilise Bluetooth pour télécharger les plongées gardées dans votre ordinateur de plongée." } } } }, + "NSCameraUsageDescription" : { + "extractionState" : "manual", + "localizations" : { + "en" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse uses the camera to photograph your certification cards." } }, + "fr" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse utilise l'appareil photo pour photographier vos cartes de certification." } } + } + }, "NSPhotoLibraryUsageDescription" : { "extractionState" : "manual", "localizations" : { diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings @@ -421,6 +421,16 @@ } } }, + "Add a card": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ajouter une carte" + } + } + } + }, "Add a cylinder": { "localizations": { "fr": { @@ -451,6 +461,26 @@ } } }, + "Add your certification cards, with a photo of each side, to have them with you.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ajoutez vos cartes de certification, avec une photo de chaque face, pour les avoir sur vous." + } + } + } + }, + "Agency": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Agence" + } + } + } + }, "Air": { "localizations": { "fr": { @@ -551,6 +581,26 @@ } } }, + "Back": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Verso" + } + } + } + }, + "Backed up automatically in iCloud Drive (%@). They come back on a new iPhone signed in to the same account.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Sauvegardées automatiquement dans iCloud Drive (%@). Elles reviennent sur un nouvel iPhone connecté au même compte." + } + } + } + }, "Belt, pockets…": { "localizations": { "fr": { @@ -621,6 +671,26 @@ } } }, + "Card": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Carte" + } + } + } + }, + "Card number": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Numéro de carte" + } + } + } + }, "Ceiling": { "localizations": { "fr": { @@ -631,6 +701,36 @@ } } }, + "Certification": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Certification" + } + } + } + }, + "Certification (Advanced Open Water…)": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Certification (Advanced Open Water…)" + } + } + } + }, + "Certification cards": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cartes de certification" + } + } + } + }, "Change dropped: %@": { "localizations": { "fr": { @@ -651,6 +751,26 @@ } } }, + "Checking the iCloud backup…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Vérification de la sauvegarde iCloud…" + } + } + } + }, + "Choose a photo": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Choisir une photo" + } + } + } + }, "Close": { "localizations": { "fr": { @@ -891,6 +1011,16 @@ } } }, + "Date issued": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Date d'émission" + } + } + } + }, "Deco model": { "localizations": { "fr": { @@ -1151,6 +1281,16 @@ } } }, + "Diver": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plongeur" + } + } + } + }, "Dives": { "localizations": { "fr": { @@ -1441,6 +1581,16 @@ } } }, + "Front": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Recto" + } + } + } + }, "Gas": { "localizations": { "fr": { @@ -1561,6 +1711,16 @@ } } }, + "Instructor, dive centre…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Instructeur, centre de plongée…" + } + } + } + }, "It was deleted or renumbered from another device.": { "localizations": { "fr": { @@ -1911,6 +2071,16 @@ } } }, + "New card": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Nouvelle carte" + } + } + } + }, "New dive": { "localizations": { "fr": { @@ -1971,6 +2141,16 @@ } } }, + "No cards yet": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune carte" + } + } + } + }, "No dives": { "localizations": { "fr": { @@ -2351,6 +2531,16 @@ } } }, + "Remove the photo": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Retirer la photo" + } + } + } + }, "Rocky bottom and kelp": { "localizations": { "fr": { @@ -2781,6 +2971,16 @@ } } }, + "Take a photo": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Prendre une photo" + } + } + } + }, "Taken during the dive": { "localizations": { "fr": { @@ -2871,6 +3071,16 @@ } } }, + "The cards are only on this iPhone: sign in to iCloud and turn iCloud Drive on to have them backed up automatically.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les cartes ne sont que sur cet iPhone : connectez-vous à iCloud et activez iCloud Drive pour qu'elles soient sauvegardées automatiquement." + } + } + } + }, "The cloud rejected the upload: %@": { "localizations": { "fr": { @@ -2961,6 +3171,16 @@ } } }, + "The iCloud backup failed: %@": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "La sauvegarde iCloud a échoué : %@" + } + } + } + }, "The location can be added later in Subsurface.": { "localizations": { "fr": { diff --git a/App/Model/Cards.swift b/App/Model/Cards.swift @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: GPL-2.0-only +import Foundation +import Observation +import UIKit + +/// A certification card: who issued it, what for, its number, and a photo of each side. +struct CertificationCard: Codable, Identifiable, Equatable { + var id = UUID() + var agency = "" + var title = "" + var number = "" + /// Day the certification was issued, "yyyy-MM-dd"; empty when unknown. + var issued = "" + var notes = "" + var hasFront = false + var hasBack = false + /// Last change, for merging the copy on this iPhone with the one in iCloud: the most recent one wins. + var modified = Date() + /// A deleted card stays in the file, so that the deletion reaches the other copy too. + var deleted = false + + enum Side: String, CaseIterable { case front, back } + + func has(_ side: Side) -> Bool { side == .front ? hasFront : hasBack } + func fileName(_ side: Side) -> String { "\(id.uuidString)-\(side.rawValue).jpg" } + + var issuedDate: Date? { + get { Self.dayFormat.date(from: issued) } + set { issued = newValue.map { Self.dayFormat.string(from: $0) } ?? "" } + } + + private static let dayFormat: DateFormatter = { + let format = DateFormatter() + format.calendar = Calendar(identifier: .gregorian) + format.locale = Locale(identifier: "en_US_POSIX") + format.timeZone = TimeZone(identifier: "UTC") + format.dateFormat = "yyyy-MM-dd" + return format + }() +} + +/// The cards live on the iPhone (Application Support/Cards: `cards.json` and one JPEG per side) and are copied +/// to the app's iCloud Drive folder whenever they change. At launch and when the app comes back, both copies are +/// merged, so a new iPhone gets the cards back and a card edited elsewhere arrives here. +@MainActor +@Observable +final class CardStore { + enum Backup: Equatable { + case unknown + /// No iCloud account, or iCloud Drive turned off for the app. + case unavailable + case working + case done(Date) + case failed(String) + } + + private(set) var all: [CertificationCard] = [] + private(set) var backup = Backup.unknown + /// Bumped when a photo changes, so that the views showing it read it again. + private(set) var photoVersion = 0 + + var cards: [CertificationCard] { + all.filter { !$0.deleted }.sorted { + ($0.issued, $0.agency, $0.title) < ($1.issued, $1.agency, $1.title) + } + } + + @ObservationIgnored private let local: URL + @ObservationIgnored private var syncing = false + @ObservationIgnored private var syncAgain = false + + nonisolated static let containerIdentifier = "iCloud.org.schurger.subrascasse" + private nonisolated static let indexName = "cards.json" + + init(directory: URL? = nil) { + let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + local = directory ?? base.appendingPathComponent("Cards", isDirectory: true) + try? FileManager.default.createDirectory(at: local, withIntermediateDirectories: true) + all = Self.read(local.appendingPathComponent(Self.indexName)) + } + + /// Made-up cards in a scratch folder, for screenshots ("-demoCards"); nothing goes to iCloud. + static func demo() -> CardStore { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("demo-cards-\(UUID().uuidString)", isDirectory: true) + let store = CardStore(directory: directory) + let samples: [(String, String, String, String, UIColor)] = [ + ("Open Water Diver", "Example Diving Agency", "OW-104 552", "2018-03-10", .systemTeal), + ("Advanced Open Water Diver", "Example Diving Agency", "AOW-221 907", "2019-07-21", .systemIndigo), + ("Nitrox", "Example Diving Agency", "NX-330 118", "2020-02-08", .systemGreen), + ] + for (title, agency, number, issued, color) in samples { + var card = CertificationCard() + card.title = title + card.agency = agency + card.number = number + card.issued = issued + for side in CertificationCard.Side.allCases { + let size = CGSize(width: 860, height: 540) + let image = UIGraphicsImageRenderer(size: size).image { context in + (side == .front ? color : UIColor.secondarySystemBackground).setFill() + context.fill(CGRect(origin: .zero, size: size)) + let ink = side == .front ? UIColor.white : UIColor.label + (side == .front ? title : "Sample diver\n" + number).draw( + in: CGRect(x: 48, y: 48, width: 760, height: 300), + withAttributes: [.font: UIFont.systemFont(ofSize: 54, weight: .bold), .foregroundColor: ink]) + agency.draw(at: CGPoint(x: 48, y: 440), withAttributes: [.font: UIFont.systemFont(ofSize: 34), .foregroundColor: ink]) + } + store.setPhoto(image, of: card, side: side) + } + card.hasFront = true + card.hasBack = true + store.save(card) + } + return store + } + + // MARK: Editing + + func card(id: UUID) -> CertificationCard? { all.first { $0.id == id && !$0.deleted } } + + /// Adds the card, or replaces the one with the same identifier. + func save(_ card: CertificationCard) { + var card = card + card.modified = Date() + if let index = all.firstIndex(where: { $0.id == card.id }) { all[index] = card } else { all.append(card) } + persist() + } + + func delete(_ card: CertificationCard) { + guard let index = all.firstIndex(where: { $0.id == card.id }) else { return } + all[index].deleted = true + all[index].hasFront = false + all[index].hasBack = false + all[index].modified = Date() + for side in CertificationCard.Side.allCases { + try? FileManager.default.removeItem(at: local.appendingPathComponent(card.fileName(side))) + } + persist() + } + + /// Stores the photo of one side (scaled down, JPEG); nil removes it. The card itself is saved by the caller. + func setPhoto(_ image: UIImage?, of card: CertificationCard, side: CertificationCard.Side) { + let url = local.appendingPathComponent(card.fileName(side)) + if let image, let data = Self.scaled(image, longestSide: 2000).jpegData(compressionQuality: 0.8) { + try? data.write(to: url, options: .atomic) + } else { + try? FileManager.default.removeItem(at: url) + } + photoVersion += 1 + } + + func photo(of card: CertificationCard, side: CertificationCard.Side) -> UIImage? { + guard card.has(side) else { return nil } + return UIImage(contentsOfFile: local.appendingPathComponent(card.fileName(side)).path) + } + + private func persist() { + Self.write(all, to: local.appendingPathComponent(Self.indexName)) + sync() + } + + private static func scaled(_ image: UIImage, longestSide: CGFloat) -> UIImage { + let longest = max(image.size.width, image.size.height) + guard longest > longestSide else { return image } + let ratio = longestSide / longest + let size = CGSize(width: (image.size.width * ratio).rounded(), height: (image.size.height * ratio).rounded()) + let format = UIGraphicsImageRendererFormat.default() + format.scale = 1 + return UIGraphicsImageRenderer(size: size, format: format).image { _ in image.draw(in: CGRect(origin: .zero, size: size)) } + } + + // MARK: Files + + nonisolated private static func read(_ url: URL) -> [CertificationCard] { + guard let data = try? Data(contentsOf: url) else { return [] } + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return (try? decoder.decode([CertificationCard].self, from: data)) ?? [] + } + + nonisolated private static func write(_ cards: [CertificationCard], to url: URL) { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + guard let data = try? encoder.encode(cards) else { return } + try? data.write(to: url, options: .atomic) + } + + // MARK: iCloud + + /// Merges this iPhone's cards with the copy in iCloud Drive, both ways. Safe to call at any time. + func sync() { + guard !LaunchOptions.flag("-demoCards") else { + backup = .unavailable + return + } + if syncing { + syncAgain = true + return + } + syncing = true + if backup == .unknown || backup == .unavailable { backup = .working } + let local = local + Task.detached(priority: .utility) { + let outcome = Self.merge(local: local) + await MainActor.run { + self.syncing = false + switch outcome { + case .unavailable: self.backup = .unavailable + case .failed(let message): self.backup = .failed(message) + case .merged(let cards, let photosChanged): + if cards != self.all { + // Changes made here while the merge ran are kept: the next pass sends them. + let merged = Self.newest(self.all, cards) + self.all = merged + Self.write(merged, to: local.appendingPathComponent(Self.indexName)) + } + if photosChanged { self.photoVersion += 1 } + self.backup = .done(Date()) + } + if self.syncAgain { + self.syncAgain = false + self.sync() + } + } + } + } + + private enum Outcome { + case unavailable + case failed(String) + case merged([CertificationCard], photosChanged: Bool) + } + + /// For each card, the most recently modified of the two copies. + nonisolated private static func newest(_ a: [CertificationCard], _ b: [CertificationCard]) -> [CertificationCard] { + var byID = [UUID: CertificationCard]() + for card in a + b { + if let other = byID[card.id], other.modified >= card.modified { continue } + byID[card.id] = card + } + return byID.values.sorted { $0.id.uuidString < $1.id.uuidString } + } + + nonisolated private static func merge(local: URL) -> Outcome { + let files = FileManager.default + // Asking for the container can take a while the first time: never on the main thread. + guard files.ubiquityIdentityToken != nil, + let container = files.url(forUbiquityContainerIdentifier: containerIdentifier) else { return .unavailable } + let remote = container.appendingPathComponent("Documents/Cards", isDirectory: true) + do { + try files.createDirectory(at: remote, withIntermediateDirectories: true) + } catch { + return .failed(error.localizedDescription) + } + // On a new iPhone the files are in iCloud but not downloaded yet: ask for them and give them a moment. + let remoteIndex = remote.appendingPathComponent(indexName) + download(remoteIndex) + let mine = read(local.appendingPathComponent(indexName)) + let theirs = coordinatedRead(remoteIndex).map { data -> [CertificationCard] in + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return (try? decoder.decode([CertificationCard].self, from: data)) ?? [] + } ?? [] + let merged = newest(mine, theirs) + var photosChanged = false + + for card in merged { + let fromRemote = theirs.first { $0.id == card.id } == card && mine.first { $0.id == card.id } != card + for side in CertificationCard.Side.allCases { + let here = local.appendingPathComponent(card.fileName(side)) + let there = remote.appendingPathComponent(card.fileName(side)) + if !card.has(side) { + if files.fileExists(atPath: here.path) { + try? files.removeItem(at: here) + photosChanged = true + } + coordinatedRemove(there) + } else if fromRemote || !files.fileExists(atPath: here.path) { + // The copy in iCloud is the newer one (or the only one): bring its photo here. + download(there) + if let data = coordinatedRead(there) { + try? data.write(to: here, options: .atomic) + photosChanged = true + } + } else if let data = try? Data(contentsOf: here), coordinatedRead(there) != data { + coordinatedWrite(data, to: there) + } + } + } + if merged != theirs { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + if let data = try? encoder.encode(merged) { coordinatedWrite(data, to: remoteIndex) } + } + return .merged(merged, photosChanged: photosChanged) + } + + /// Asks iCloud for a file that is not on the device yet, and waits a little for it. + nonisolated private static func download(_ url: URL) { + let files = FileManager.default + let placeholder = url.deletingLastPathComponent().appendingPathComponent("." + url.lastPathComponent + ".icloud") + guard files.fileExists(atPath: placeholder.path) || isNotDownloaded(url) else { return } + try? files.startDownloadingUbiquitousItem(at: url) + for _ in 0..<40 { + if files.fileExists(atPath: url.path), !isNotDownloaded(url) { return } + Thread.sleep(forTimeInterval: 0.25) + } + } + + nonisolated private static func isNotDownloaded(_ url: URL) -> Bool { + guard let status = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]).ubiquitousItemDownloadingStatus else { return false } + return status == .notDownloaded + } + + nonisolated private static func coordinatedRead(_ url: URL) -> Data? { + var data: Data? + var error: NSError? + NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &error) { data = try? Data(contentsOf: $0) } + return data + } + + nonisolated private static func coordinatedWrite(_ data: Data, to url: URL) { + var error: NSError? + NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &error) { try? data.write(to: $0, options: .atomic) } + } + + nonisolated private static func coordinatedRemove(_ url: URL) { + guard FileManager.default.fileExists(atPath: url.path) else { return } + var error: NSError? + NSFileCoordinator().coordinate(writingItemAt: url, options: .forDeleting, error: &error) { try? FileManager.default.removeItem(at: $0) } + } +} diff --git a/App/Views/CardsView.swift b/App/Views/CardsView.swift @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: GPL-2.0-only +import PhotosUI +import SwiftUI +import UIKit + +/// The certification cards: one row per card, a tap shows it full size (to hand the iPhone over at a dive shop). +struct CardsView: View { + @Environment(CardStore.self) private var store + @State private var editing: CertificationCard? + @State private var shown: CertificationCard? + + var body: some View { + List { + if store.cards.isEmpty { + ContentUnavailableView("No cards yet", systemImage: "person.text.rectangle", + description: Text("Add your certification cards, with a photo of each side, to have them with you.")) + } + ForEach(store.cards) { card in + Button { shown = card } label: { CardRow(card: card) } + .buttonStyle(.plain) + .swipeActions { + Button("Delete", role: .destructive) { store.delete(card) } + Button("Edit") { editing = card } + } + } + Section { + Button { editing = CertificationCard() } label: { Label("Add a card", systemImage: "plus.circle") } + } footer: { + BackupFootnote() + } + } + .listStyle(.insetGrouped) + .navigationTitle("Certification cards") + .navigationBarTitleDisplayMode(.inline) + .sheet(item: $editing) { CardEditView(card: $0) } + .fullScreenCover(item: $shown) { card in + CardFullScreen(cardID: card.id) { editing = $0 } + } + .onAppear { + store.sync() + if LaunchOptions.flag("-showCard"), let first = store.cards.last { shown = first } + if LaunchOptions.flag("-editCard"), let first = store.cards.last { editing = first } + } + } +} + +/// Where the cards are kept, in one line. +struct BackupFootnote: View { + @Environment(CardStore.self) private var store + + var body: some View { + switch store.backup { + case .unknown, .working: + Text("Checking the iCloud backup…") + case .unavailable: + Text("The cards are only on this iPhone: sign in to iCloud and turn iCloud Drive on to have them backed up automatically.") + case .done(let date): + Text("Backed up automatically in iCloud Drive (\(date.formatted(date: .abbreviated, time: .shortened))). They come back on a new iPhone signed in to the same account.") + case .failed(let message): + Text("The iCloud backup failed: \(message)") + } + } +} + +struct CardRow: View { + @Environment(CardStore.self) private var store + let card: CertificationCard + + var body: some View { + HStack(spacing: 12) { + let _ = store.photoVersion + Group { + if let image = store.photo(of: card, side: .front) ?? store.photo(of: card, side: .back) { + Image(uiImage: image).resizable().scaledToFill() + } else { + ZStack { + Color.accentColor.opacity(0.15) + Image(systemName: "person.text.rectangle").foregroundStyle(Color.accentColor) + } + } + } + .frame(width: 72, height: 46) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + VStack(alignment: .leading, spacing: 3) { + Text(card.title.isEmpty ? String(localized: "Certification") : card.title) + .font(.body.weight(.medium)) + Text([card.agency, card.number].filter { !$0.isEmpty }.joined(separator: " · ")) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 8) + if let date = card.issuedDate { + Text(date.formatted(Date.FormatStyle(timeZone: TimeZone(identifier: "UTC")!).year())) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + .padding(.vertical, 2) + .contentShape(Rectangle()) + } +} + +/// The card on the whole screen, front then back, on a dark background. +struct CardFullScreen: View { + @Environment(CardStore.self) private var store + @Environment(\.dismiss) private var dismiss + let cardID: UUID + let onEdit: (CertificationCard) -> Void + + var body: some View { + NavigationStack { + ScrollView { + if let card = store.card(id: cardID) { + VStack(spacing: 16) { + let _ = store.photoVersion + ForEach(CertificationCard.Side.allCases, id: \.self) { side in + if let image = store.photo(of: card, side: side) { + Image(uiImage: image) + .resizable() + .scaledToFit() + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + } + VStack(spacing: 6) { + Text(card.title).font(.title3.weight(.semibold)) + Text(card.agency).foregroundStyle(.secondary) + if !card.number.isEmpty { + Text(card.number) + .font(.title2.monospaced().weight(.medium)) + .textSelection(.enabled) + } + if let date = card.issuedDate { + Text(date.formatted(Date.FormatStyle(timeZone: TimeZone(identifier: "UTC")!).day().month(.wide).year())) + .font(.callout) + .foregroundStyle(.secondary) + } + if !card.notes.isEmpty { Text(card.notes).font(.callout).multilineTextAlignment(.center) } + } + .frame(maxWidth: .infinity) + .padding() + } + .padding() + } + } + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Edit") { + guard let card = store.card(id: cardID) else { return } + dismiss() + // The edit sheet belongs to the list, which can only show it once this cover is gone. + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { onEdit(card) } + } + } + } + } + } +} + +struct CardEditView: View { + @Environment(CardStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State var card: CertificationCard + @State private var hasDate = false + @State private var date = Date() + @State private var loaded = false + /// Photos picked in this sheet, written when the card is saved (nil inside: photo removed). + @State private var picked: [CertificationCard.Side: UIImage?] = [:] + + private static let agencies = ["PADI", "SSI", "NAUI", "CMAS", "FQAS", "ACUC", "SDI", "TDI", "GUE", "IANTD", "RAID", "BSAC", "DAN"] + + private var isNew: Bool { store.card(id: card.id) == nil } + + var body: some View { + NavigationStack { + Form { + Section { + HStack { + TextField("Agency", text: $card.agency) + .textInputAutocapitalization(.characters) + .autocorrectionDisabled() + Menu { + ForEach(Self.agencies, id: \.self) { name in Button(name) { card.agency = name } } + } label: { + Image(systemName: "chevron.up.chevron.down").foregroundStyle(.secondary) + } + } + TextField("Certification (Advanced Open Water…)", text: $card.title) + TextField("Card number", text: $card.number) + .autocorrectionDisabled() + .textInputAutocapitalization(.characters) + Toggle("Date issued", isOn: $hasDate.animation()) + if hasDate { + DatePicker("Date issued", selection: $date, in: ...Date(), displayedComponents: .date) + .labelsHidden() + .environment(\.timeZone, TimeZone(identifier: "UTC")!) + } + } + Section("Front") { photoRow(.front) } + Section("Back") { photoRow(.back) } + Section("Notes") { + TextField("Instructor, dive centre…", text: $card.notes, axis: .vertical) + .lineLimit(1...4) + } + } + .navigationTitle(isNew ? String(localized: "New card") : String(localized: "Card")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save", action: save) + .disabled(card.agency.isEmpty && card.title.isEmpty && card.number.isEmpty && picked.isEmpty) + } + } + .onAppear { + guard !loaded else { return } + loaded = true + if let issued = card.issuedDate { + hasDate = true + date = issued + } + } + } + } + + private func image(_ side: CertificationCard.Side) -> UIImage? { + if let change = picked[side] { return change } + return store.photo(of: card, side: side) + } + + @ViewBuilder private func photoRow(_ side: CertificationCard.Side) -> some View { + if let image = image(side) { + Image(uiImage: image) + .resizable() + .scaledToFit() + .frame(maxHeight: 190) + .frame(maxWidth: .infinity) + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + PhotoSourceButtons(hasPhoto: image(side) != nil) { picked[side] = .some($0) } + } + + private func save() { + var saved = card + saved.agency = saved.agency.trimmingCharacters(in: .whitespacesAndNewlines) + saved.title = saved.title.trimmingCharacters(in: .whitespacesAndNewlines) + saved.number = saved.number.trimmingCharacters(in: .whitespacesAndNewlines) + saved.issuedDate = hasDate ? date : nil + for (side, image) in picked { + store.setPhoto(image, of: saved, side: side) + if side == .front { saved.hasFront = image != nil } else { saved.hasBack = image != nil } + } + store.save(saved) + dismiss() + } +} + +/// "Take a photo", "Choose a photo" and, when there is one, "Remove". +private struct PhotoSourceButtons: View { + let hasPhoto: Bool + /// The new photo, or nil to remove the current one. + let onChange: (UIImage?) -> Void + @State private var item: PhotosPickerItem? + @State private var usingCamera = false + + var body: some View { + HStack(spacing: 18) { + if UIImagePickerController.isSourceTypeAvailable(.camera) { + Button { usingCamera = true } label: { Label("Take a photo", systemImage: "camera") } + } + PhotosPicker(selection: $item, matching: .images) { Label("Choose a photo", systemImage: "photo") } + if hasPhoto { + Spacer(minLength: 0) + Button(role: .destructive) { onChange(nil) } label: { Image(systemName: "trash") } + .accessibilityLabel("Remove the photo") + } + } + // Several buttons in one row of a form: each must answer for itself. + .buttonStyle(.borderless) + .font(.callout) + .onChange(of: item) { + guard let item else { return } + Task { + if let data = try? await item.loadTransferable(type: Data.self), let image = UIImage(data: data) { onChange(image) } + self.item = nil + } + } + .fullScreenCover(isPresented: $usingCamera) { + CameraPicker { image in + usingCamera = false + if let image { onChange(image) } + } + .ignoresSafeArea() + } + } +} + +private struct CameraPicker: UIViewControllerRepresentable { + let onDone: (UIImage?) -> Void + + func makeUIViewController(context: Context) -> UIImagePickerController { + let picker = UIImagePickerController() + picker.sourceType = .camera + picker.delegate = context.coordinator + return picker + } + + func updateUIViewController(_ controller: UIImagePickerController, context: Context) {} + + func makeCoordinator() -> Coordinator { Coordinator(onDone: onDone) } + + final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { + let onDone: (UIImage?) -> Void + init(onDone: @escaping (UIImage?) -> Void) { self.onDone = onDone } + + func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { + onDone(info[.originalImage] as? UIImage) + } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { onDone(nil) } + } +} diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift @@ -6,6 +6,8 @@ struct SettingsView: View { @State private var confirmingSignOut = false @State private var importing = false @State private var downloading = false + @State private var showingCards = LaunchOptions.flag("-cards") + @Environment(CardStore.self) private var cards private var about: String { 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.") @@ -75,6 +77,20 @@ struct SettingsView: View { } Section { + Button { showingCards = true } label: { + HStack { + Label("Certification cards", systemImage: "person.text.rectangle") + Spacer() + Text("\(cards.cards.count)").foregroundStyle(.secondary) + Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(.tertiary) + } + } + .foregroundStyle(.primary) + } header: { + Text("Diver") + } + + Section { LabeledContent("Version", value: Brand.version) Text(about) .font(.footnote) @@ -94,6 +110,7 @@ struct SettingsView: View { } .listStyle(.insetGrouped) .navigationTitle("Settings") + .navigationDestination(isPresented: $showingCards) { CardsView() } .modifier(FileImport(isPresented: $importing)) .modifier(DiveComputerImport(isPresented: $downloading)) .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?") : String(localized: "Sign out?"), diff --git a/README.md b/README.md @@ -40,6 +40,13 @@ The app is available in English and French. before to 30 minutes after), placed on the profile at their time, hence at their depth; a site page shows those of all its dives. Logbook times are local to the site: the time zone comes from the site's position (Apple reverse geocoding, then remembered). Read-only; nothing is sent anywhere. +- Editing a dive: site, buddy, guide, suit, tags, rating, visibility, notes, and its equipment: cylinders (name, + volume, working pressure, gas, start and end pressures) and weights. +- Merging dives: from the list (+, Merge dives) or from a dive page; the numbering closes up. +- Certification cards (Settings, Certification cards): agency, certification, number, date, a photo of each + side, shown full screen. They are not part of the Subsurface logbook: they are kept on the iPhone and copied + automatically to the app's iCloud Drive folder (`iCloud.org.schurger.subrascasse`, `Documents/Cards`), merged + both ways at launch, so they come back on a new iPhone. - Creation of a Subsurface cloud account (email, password, code received by email). - Demo logbook (a button on the sign-in screen, or the `-demo` launch option). @@ -90,7 +97,7 @@ Not there yet: Subsurface XML import, dive planner. Launch options: `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`, `-newDive`, `-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`, `-merouFolder path`, -`-selectDives 12,13` (the selection that precedes a merge; with `-merge`, its confirmation), `-diveComputer` +`-selectDives 12,13` (the selection that precedes a merge; with `-merge`, its confirmation), `-cards`, `-demoCards`, `-showCard`, `-editCard`, `-selectDives 12,13`, `-mergeNow`, `-diveComputer` (opens the download sheet; with `-fakeComputers` it lists made-up computers, the simulator having no Bluetooth). ### Validating on a real logbook diff --git a/fastlane/Fastfile b/fastlane/Fastfile @@ -61,9 +61,9 @@ platform :ios do end texts = { "fr-CA" => ["Votre carnet de plongée Subsurface sur iPhone : lecture, profils, modification hors ligne, synchronisation avec le nuage Subsurface. Application indépendante de l'équipe de Subsurface.", - "0.4 : Nouveau : fusionner des plongées (Plongées, +, Fusionner des plongées) : les immersions choisies deviennent une seule plongée et la numérotation se referme. Une plongée déjà fusionnée n'est plus reproposée par l'ordinateur. Rappel 0.3 : téléchargement Bluetooth depuis un ordinateur de plongée (vérifié sur un Shearwater Petrel 3) ; après un téléchargement, l'app indique le prochain numéro du carnet."], + "0.5 : Nouveau : (1) Modifier une plongée permet de saisir les bouteilles et le lest. (2) Réglages, Cartes de certification : agence, numéro, photo recto et verso, affichage plein écran ; sauvegarde automatique dans iCloud Drive. (3) Fusion de plongées depuis la liste (+) ou depuis la fiche (menu ...). À vérifier : après avoir ajouté une carte, le pied de la liste doit indiquer la sauvegarde iCloud, et le dossier Sub Rascasse doit apparaître dans Fichiers, iCloud Drive."], "en-CA" => ["Your Subsurface dive log on iPhone: browse, profiles, offline editing, sync with Subsurface cloud storage. Independent from the Subsurface team.", - "0.4: New: merge dives (Dives, +, Merge dives): the selected immersions become one dive and the numbering closes up. Immersions already merged are no longer offered again by the computer. From 0.3: Bluetooth download from a dive computer (checked on a Shearwater Petrel 3); after a download the app tells the next logbook number."], + "0.5: New: (1) Editing a dive now covers cylinders and weights. (2) Settings, Certification cards: agency, number, photo of each side, full screen display; automatic backup in iCloud Drive. (3) Merging dives from the list (+) or from a dive page (... menu). To check: after adding a card, the footer of the list should mention the iCloud backup, and a Sub Rascasse folder should appear in Files, iCloud Drive."], } _, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations") texts.each do |locale, (description, _)| diff --git a/project.yml b/project.yml @@ -13,7 +13,7 @@ settings: base: DEVELOPMENT_TEAM: CM5RQKJH56 CODE_SIGN_STYLE: Automatic - MARKETING_VERSION: "0.4" + MARKETING_VERSION: "0.5" CURRENT_PROJECT_VERSION: "1" SWIFT_VERSION: "5.0" targets: @@ -50,6 +50,13 @@ targets: UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight] # French translation in App/InfoPlist.xcstrings. NSPhotoLibraryUsageDescription: "Sub Rascasse flags the dives you have photos or videos of and shows them on the dive page. They stay on your iPhone; nothing is sent." + NSCameraUsageDescription: "Sub Rascasse uses the camera to photograph your certification cards." + # The cards folder shows up in the Files app, under iCloud Drive. + NSUbiquitousContainers: + iCloud.org.schurger.subrascasse: + NSUbiquitousContainerIsDocumentScopePublic: true + NSUbiquitousContainerName: Sub Rascasse + NSUbiquitousContainerSupportedFolderLevels: Any NSBluetoothAlwaysUsageDescription: "Sub Rascasse uses Bluetooth to download the dives stored in your dive computer." # Open Remora opens "subrascasse://open-remora" after dropping a dive. CFBundleURLTypes: @@ -60,6 +67,10 @@ targets: properties: # Folder shared with Open Remora (dives from the watch, to be imported). com.apple.security.application-groups: [group.org.schurger.dive] + # iCloud Drive folder where the certification cards are backed up. + com.apple.developer.icloud-container-identifiers: [iCloud.org.schurger.subrascasse] + com.apple.developer.ubiquity-container-identifiers: [iCloud.org.schurger.subrascasse] + com.apple.developer.icloud-services: [CloudDocuments] schemes: DiveLog: build: