commit 26a4045f7bc5356043916b192fd5c07f0e961b9f
parent 8255e01cbf30bf2c0e48f03d878c0a2192f1179c
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 15:45:08 -0500
iPhone app 0.1: Subsurface cloud sign-in, dive list, dive page with profile, offline editing, sites, statistics, demo
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
28 files changed, 2381 insertions(+), 8 deletions(-)
diff --git a/App/Assets.xcassets/AccentColor.colorset/Contents.json b/App/Assets.xcassets/AccentColor.colorset/Contents.json
@@ -0,0 +1,8 @@
+{
+ "colors" : [
+ { "idiom" : "universal", "color" : { "color-space" : "srgb", "components" : { "red" : "0.000", "green" : "0.478", "blue" : "0.655", "alpha" : "1.000" } } },
+ { "idiom" : "universal", "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ],
+ "color" : { "color-space" : "srgb", "components" : { "red" : "0.290", "green" : "0.760", "blue" : "0.890", "alpha" : "1.000" } } }
+ ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/App/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,4 @@
+{
+ "images" : [ { "filename" : "icon-1024.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" } ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/App/Assets.xcassets/AppIcon.appiconset/icon-1024.png b/App/Assets.xcassets/AppIcon.appiconset/icon-1024.png
Binary files differ.
diff --git a/App/Assets.xcassets/Contents.json b/App/Assets.xcassets/Contents.json
@@ -0,0 +1 @@
+{ "info" : { "author" : "xcode", "version" : 1 } }
diff --git a/App/Assets.xcassets/Logo.imageset/Contents.json b/App/Assets.xcassets/Logo.imageset/Contents.json
@@ -0,0 +1,4 @@
+{
+ "images" : [ { "filename" : "logo.png", "idiom" : "universal", "scale" : "2x" } ],
+ "info" : { "author" : "xcode", "version" : 1 }
+}
diff --git a/App/Assets.xcassets/Logo.imageset/logo.png b/App/Assets.xcassets/Logo.imageset/logo.png
Binary files differ.
diff --git a/App/Brand.swift b/App/Brand.swift
@@ -0,0 +1,12 @@
+import Foundation
+
+/// Nom et adresses de l'app, réunis ici pour qu'un changement de nom ne touche que ce fichier et project.yml.
+enum Brand {
+ static let name = "Subrascasse"
+ static var version: String {
+ let info = Bundle.main.infoDictionary
+ return "\(info?["CFBundleShortVersionString"] as? String ?? "0") (\(info?["CFBundleVersion"] as? String ?? "0"))"
+ }
+ static var shortVersion: String { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0" }
+ static let keychainService = "org.schurger.subrascasse.cloud"
+}
diff --git a/App/DiveLogApp.swift b/App/DiveLogApp.swift
@@ -0,0 +1,14 @@
+import SwiftUI
+
+@main
+struct DiveLogApp: App {
+ @State private var model = AppModel()
+
+ var body: some Scene {
+ WindowGroup {
+ RootView()
+ .environment(model)
+ .task { await model.start() }
+ }
+ }
+}
diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift
@@ -0,0 +1,259 @@
+import Foundation
+import GitLite
+import Observation
+import SubsurfaceLog
+
+struct DiveSection: Identifiable {
+ let id: String
+ let title: String
+ let subtitle: String
+ var dives: [Dive]
+}
+
+@MainActor
+@Observable
+final class AppModel {
+ enum Phase { case launching, signedOut, ready }
+ enum SyncState: Equatable { case idle, syncing, failed(String) }
+
+ var phase = Phase.launching
+ var logbook = Logbook()
+ var syncState = SyncState.idle
+ var lastSync: Date?
+ var pending: [LogChange] = []
+ var email = ""
+ var isDemo = false
+ var notices: [String] = []
+ var units = Units(imperial: UserDefaults.standard.object(forKey: "imperial") as? Bool ?? (Locale.current.measurementSystem == .us))
+
+ @ObservationIgnored private var repository: LogRepository?
+ @ObservationIgnored private var password = ""
+ @ObservationIgnored private var syncTask: Task<Void, Never>?
+
+ // MARK: Démarrage et compte
+
+ func start() async {
+ guard phase == .launching else { return }
+ if ProcessInfo.processInfo.arguments.contains("-demo") {
+ await startDemo()
+ return
+ }
+ let saved = UserDefaults.standard.string(forKey: "email") ?? ""
+ guard !saved.isEmpty, let secret = Keychain.password(account: saved) else {
+ phase = .signedOut
+ return
+ }
+ email = saved
+ password = secret
+ do {
+ try await open(account: saved)
+ phase = .ready
+ scheduleSync()
+ } catch {
+ phase = .signedOut
+ }
+ }
+
+ private static func storage(for account: String) throws -> URL {
+ let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
+ let safe = String(account.map { $0.isLetter || $0.isNumber ? $0 : "_" })
+ return base.appendingPathComponent("logbooks").appendingPathComponent(safe)
+ }
+
+ private func open(account: String) async throws {
+ let repo = try LogRepository(directory: try Self.storage(for: account), branch: account,
+ authorName: Brand.name, authorEmail: account)
+ repository = repo
+ try await reload()
+ }
+
+ private func reload() async throws {
+ guard let repository else { return }
+ logbook = try await repository.logbook()
+ pending = await repository.pending
+ lastSync = await repository.lastSync
+ }
+
+ /// Vérifie les identifiants auprès du nuage, puis télécharge le carnet.
+ func signIn(email rawEmail: String, password rawPassword: String) async throws {
+ let account = SubsurfaceCloud.sanitize(email: rawEmail)
+ guard account.contains("@"), !rawPassword.isEmpty else { throw AppError.message("Entrez votre courriel et votre mot de passe.") }
+ let transport = SubsurfaceCloud.transport(email: account, password: rawPassword)
+ do {
+ _ = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
+ } catch {
+ throw AppError.message(Self.describe(error))
+ }
+ Keychain.save(password: rawPassword, account: account)
+ UserDefaults.standard.set(account, forKey: "email")
+ email = account
+ password = rawPassword
+ isDemo = false
+ try await open(account: account)
+ phase = .ready
+ await sync()
+ }
+
+ func signOut() async {
+ syncTask?.cancel()
+ if let repository { try? await repository.erase() }
+ if !isDemo {
+ Keychain.delete(account: email)
+ UserDefaults.standard.removeObject(forKey: "email")
+ }
+ repository = nil
+ logbook = Logbook()
+ pending = []
+ notices = []
+ lastSync = nil
+ email = ""
+ password = ""
+ isDemo = false
+ syncState = .idle
+ phase = .signedOut
+ }
+
+ func startDemo() async {
+ do {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("demo-logbook")
+ try? FileManager.default.removeItem(at: directory)
+ let repo = try LogRepository(directory: directory, branch: "demo", authorName: Brand.name, authorEmail: "demo@example.com")
+ try await repo.importTree(files: DemoData.files())
+ repository = repo
+ isDemo = true
+ email = "demo@example.com"
+ try await reload()
+ phase = .ready
+ if LaunchOptions.flag("-demoChanges") { await demoChanges() }
+ } catch {
+ phase = .signedOut
+ }
+ }
+
+ /// Essai de bout en bout du circuit de modification (option de lancement `-demoChanges`).
+ private func demoChanges() async {
+ guard let latest = logbook.dives.first else { return }
+ do {
+ try await apply(.editDive(when: latest.when, number: latest.number, fields: ["buddy": "Modifié par l'essai", "rating": "1"]))
+ let uuid = newSiteUUID()
+ try await apply(.addSite(uuid: uuid, name: "Lieu ajouté par l'essai", latitude: nil, longitude: nil))
+ var dive = NewDive(when: latest.when + 86_400, number: logbook.nextNumber, durationSeconds: 1500, maxDepth: 9.5)
+ dive.siteUUID = uuid
+ try await apply(.addDive(dive))
+ } catch {
+ notices.append("Essai en échec : \(Self.describe(error))")
+ }
+ }
+
+ // MARK: Synchronisation
+
+ func scheduleSync() {
+ syncTask?.cancel()
+ syncTask = Task { await sync() }
+ }
+
+ func sync() async {
+ guard let repository, syncState != .syncing else { return }
+ if isDemo {
+ try? await repository.commitPendingLocally()
+ try? await reload()
+ return
+ }
+ syncState = .syncing
+ do {
+ let report = try await repository.sync(transport: SubsurfaceCloud.transport(email: email, password: password),
+ appVersion: Brand.shortVersion)
+ notices.append(contentsOf: report.dropped.map { "Modification abandonnée : \($0)" })
+ try await reload()
+ syncState = .idle
+ } catch {
+ try? await reload()
+ syncState = .failed(Self.describe(error))
+ }
+ }
+
+ static func describe(_ error: Error) -> String {
+ if let git = error as? GitError {
+ switch git {
+ case .unauthorized: return "Courriel ou mot de passe refusé par le nuage Subsurface."
+ case .notFound: return "Aucun carnet trouvé pour ce compte."
+ case .network(let what): return "Connexion impossible : \(what)"
+ case .http(let code): return "Le nuage Subsurface a répondu par une erreur (\(code))."
+ case .pushRejected(let why): return "Le nuage a refusé l'envoi : \(why)"
+ default: return "Synchronisation impossible (\(git))."
+ }
+ }
+ if let app = error as? AppError { return app.description }
+ if let change = error as? ChangeError { return change.description.capitalizedFirst + "." }
+ return error.localizedDescription
+ }
+
+ // MARK: Modifications
+
+ func apply(_ change: LogChange) async throws {
+ guard let repository else { return }
+ do {
+ logbook = try await repository.enqueue(change)
+ pending = await repository.pending
+ } catch {
+ throw AppError.message(Self.describe(error))
+ }
+ scheduleSync()
+ }
+
+ func profile(of dive: Dive) async -> [DiveComputer] {
+ guard let repository else { return [] }
+ return (try? await repository.profile(of: dive)) ?? []
+ }
+
+ func setImperial(_ value: Bool) {
+ units.imperial = value
+ UserDefaults.standard.set(value, forKey: "imperial")
+ }
+
+ func newSiteUUID() -> UInt32 {
+ var uuid = UInt32.random(in: 1...UInt32.max)
+ while logbook.sites[uuid] != nil { uuid = UInt32.random(in: 1...UInt32.max) }
+ return uuid
+ }
+
+ // MARK: Vues dérivées
+
+ func dive(id: String) -> Dive? { logbook.dives.first { $0.id == id } }
+
+ func siteName(of dive: Dive) -> String {
+ let name = logbook.site(of: dive)?.name ?? ""
+ return name.isEmpty ? "Lieu inconnu" : name
+ }
+
+ /// Plongées regroupées par voyage, sinon par mois, de la plus récente à la plus ancienne.
+ func sections(matching search: String) -> [DiveSection] {
+ let needle = search.trimmingCharacters(in: .whitespaces).lowercased()
+ let dives = needle.isEmpty ? logbook.dives : logbook.dives.filter { dive in
+ let site = logbook.site(of: dive)
+ let haystack = [site?.name ?? "", site?.country ?? "", dive.buddy, dive.divemaster, dive.notes, dive.suit,
+ dive.tags.joined(separator: " "), logbook.trip(of: dive)?.location ?? "", String(dive.number)]
+ return haystack.contains { $0.lowercased().contains(needle) }
+ }
+ var sections = [DiveSection]()
+ for dive in dives {
+ let key = dive.tripID ?? DiveDate.monthKey(dive.when)
+ if sections.last?.id == key {
+ sections[sections.count - 1].dives.append(dive)
+ } else if let trip = logbook.trip(of: dive) {
+ sections.append(DiveSection(id: key, title: trip.location.isEmpty ? "Voyage" : trip.location,
+ subtitle: DiveDate.monthTitle(dive.when), dives: [dive]))
+ } else {
+ sections.append(DiveSection(id: key, title: DiveDate.monthTitle(dive.when), subtitle: "", dives: [dive]))
+ }
+ }
+ return sections
+ }
+}
+
+enum AppError: Error, CustomStringConvertible {
+ case message(String)
+ var description: String {
+ switch self { case .message(let text): return text }
+ }
+}
diff --git a/App/Model/DemoData.swift b/App/Model/DemoData.swift
@@ -0,0 +1,182 @@
+import Foundation
+import SubsurfaceLog
+
+/// Carnet de démonstration, écrit dans le vrai format de Subsurface : il sert aux essais sans compte,
+/// aux captures d'écran et aux réviseurs des magasins d'applications. Lieux et personnes fictifs.
+enum DemoData {
+ private struct Site {
+ let uuid: String, name: String, description: String, latitude: Double, longitude: Double, country: String
+ }
+
+ private struct Plan {
+ let number: Int
+ let date: (Int, Int, Int, Int, Int)
+ let site: String
+ let depth: Double
+ let minutes: Int
+ let surfaceTemp: Double, bottomTemp: Double
+ let o2: Int
+ let buddy: String
+ let rating: Int, visibility: Int
+ let tags: [String]
+ let notes: String
+ let trip: String?
+ let cold: Bool
+ }
+
+ private static let sites = [
+ Site(uuid: "c0000001", name: "Récif des Gorgones", description: "Récif frangeant, entrée du bord", latitude: 12.1600, longitude: -68.2900, country: "Bonaire"),
+ Site(uuid: "c0000002", name: "Épave du Cormoran", description: "Petit cargo posé droit sur le sable", latitude: 12.2150, longitude: -68.3450, country: "Bonaire"),
+ Site(uuid: "c0000003", name: "Tombant aux Tortues", description: "Tombant en pente douce jusqu'à 35 m", latitude: 12.0950, longitude: -68.2850, country: "Bonaire"),
+ Site(uuid: "c0000004", name: "Carrière du Nord", description: "Carrière inondée, plateformes à 6 m et 12 m", latitude: 45.6500, longitude: -75.9200, country: "Canada"),
+ Site(uuid: "c0000005", name: "Anse aux Phoques", description: "Fond de roche et laminaires", latitude: 48.8300, longitude: -64.2000, country: "Canada"),
+ Site(uuid: "c0000006", name: "Quai des Brumes", description: "Plongée sous le quai, beaucoup de vie fixée", latitude: 48.4200, longitude: -64.3300, country: "Canada"),
+ ]
+
+ private static let plans: [Plan] = [
+ Plan(number: 1, date: (2025, 6, 14, 10, 5), site: "c0000004", depth: 12.4, minutes: 38, surfaceTemp: 19, bottomTemp: 11, o2: 21, buddy: "Camille", rating: 3, visibility: 2, tags: ["formation"], notes: "Révision des exercices sur la plateforme de 6 m.", trip: nil, cold: true),
+ Plan(number: 2, date: (2025, 7, 5, 9, 40), site: "c0000004", depth: 18.2, minutes: 42, surfaceTemp: 22, bottomTemp: 8, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [], notes: "Thermocline marquée à 9 m.", trip: nil, cold: true),
+ Plan(number: 3, date: (2025, 8, 16, 8, 30), site: "c0000005", depth: 16.8, minutes: 47, surfaceTemp: 12, bottomTemp: 6, o2: 21, buddy: "Sam", rating: 5, visibility: 4, tags: ["phoques"], notes: "Trois phoques curieux pendant toute la plongée.\nEau très claire pour la saison.", trip: "Gaspesie", cold: true),
+ Plan(number: 4, date: (2025, 8, 16, 13, 15), site: "c0000006", depth: 9.6, minutes: 55, surfaceTemp: 12, bottomTemp: 8, o2: 21, buddy: "Sam", rating: 4, visibility: 3, tags: ["macro"], notes: "Anémones, nudibranches et crabes sous les piliers.", trip: "Gaspesie", cold: true),
+ Plan(number: 5, date: (2025, 8, 17, 9, 0), site: "c0000005", depth: 22.3, minutes: 41, surfaceTemp: 11, bottomTemp: 5, o2: 32, buddy: "Sam, Alex", rating: 4, visibility: 4, tags: ["nitrox"], notes: "Forêt de laminaires, loup de mer dans une faille.", trip: "Gaspesie", cold: true),
+ Plan(number: 6, date: (2025, 8, 18, 20, 45), site: "c0000006", depth: 8.2, minutes: 48, surfaceTemp: 12, bottomTemp: 9, o2: 21, buddy: "Alex", rating: 5, visibility: 3, tags: ["nuit", "macro"], notes: "Plongée de nuit : bioluminescence au palier.", trip: "Gaspesie", cold: true),
+ Plan(number: 7, date: (2025, 10, 4, 11, 20), site: "c0000004", depth: 24.6, minutes: 36, surfaceTemp: 14, bottomTemp: 6, o2: 21, buddy: "Camille", rating: 2, visibility: 1, tags: [], notes: "Visibilité réduite après la pluie.", trip: nil, cold: true),
+ Plan(number: 8, date: (2026, 5, 23, 10, 0), site: "c0000004", depth: 15.1, minutes: 44, surfaceTemp: 13, bottomTemp: 7, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: ["réglages"], notes: "Première plongée de la saison, lestage à revoir.", trip: nil, cold: true),
+ Plan(number: 9, date: (2026, 6, 20, 9, 10), site: "c0000001", depth: 18.9, minutes: 58, surfaceTemp: 28, bottomTemp: 27, o2: 32, buddy: "Sam", rating: 4, visibility: 5, tags: ["récif"], notes: "Plongée de réadaptation, gorgones en éventail partout.", trip: "Bonaire", cold: false),
+ Plan(number: 10, date: (2026, 6, 20, 14, 30), site: "c0000003", depth: 27.4, minutes: 52, surfaceTemp: 28, bottomTemp: 26, o2: 32, buddy: "Sam", rating: 5, visibility: 5, tags: ["tortues", "récif"], notes: "Deux tortues vertes et un banc de carangues.", trip: "Bonaire", cold: false),
+ Plan(number: 11, date: (2026, 6, 21, 8, 45), site: "c0000002", depth: 30.2, minutes: 46, surfaceTemp: 28, bottomTemp: 26, o2: 32, buddy: "Sam, Alex", rating: 5, visibility: 4, tags: ["épave", "nitrox"], notes: "Tour de l'épave par la proue.\nMurène verte dans la cale avant.", trip: "Bonaire", cold: false),
+ Plan(number: 12, date: (2026, 6, 21, 15, 0), site: "c0000001", depth: 14.3, minutes: 64, surfaceTemp: 29, bottomTemp: 28, o2: 32, buddy: "Alex", rating: 4, visibility: 5, tags: ["photo"], notes: "Longue plongée photo dans 10 m d'eau.", trip: "Bonaire", cold: false),
+ Plan(number: 13, date: (2026, 6, 22, 9, 30), site: "c0000003", depth: 34.8, minutes: 43, surfaceTemp: 28, bottomTemp: 25, o2: 28, buddy: "Sam", rating: 4, visibility: 5, tags: ["profonde"], notes: "Descente le long du tombant jusqu'aux éponges tonneaux.", trip: "Bonaire", cold: false),
+ Plan(number: 14, date: (2026, 6, 23, 19, 50), site: "c0000001", depth: 12.0, minutes: 61, surfaceTemp: 28, bottomTemp: 28, o2: 32, buddy: "Sam, Alex", rating: 5, visibility: 4, tags: ["nuit"], notes: "Poulpes en chasse et tarpons dans le faisceau des lampes.", trip: "Bonaire", cold: false),
+ Plan(number: 15, date: (2026, 7, 18, 10, 30), site: "c0000004", depth: 20.4, minutes: 40, surfaceTemp: 23, bottomTemp: 9, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [], notes: "Essai du nouveau détendeur.", trip: nil, cold: true),
+ Plan(number: 16, date: (2026, 9, 12, 9, 15), site: "c0000004", depth: 28.7, minutes: 39, surfaceTemp: 20, bottomTemp: 6, o2: 21, buddy: "Camille, Sam", rating: 4, visibility: 4, tags: ["profonde"], notes: "Visite du vieux camion au fond de la carrière.", trip: nil, cold: true),
+ ]
+
+ private static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
+
+ static func files() -> [String: String] {
+ var files = [String: String]()
+ files["00-Subsurface"] = "version 3\nautogroup\nunits METRIC\n"
+ for site in sites {
+ files["01-Divesites/Site-\(site.uuid)"] = """
+ name "\(site.name)"
+ description "\(site.description)"
+ gps \(String(format: "%.6f %.6f", site.latitude, site.longitude))
+ geo cat 2 origin 0 "\(site.country)"
+
+ """
+ }
+ let tripFolders = ["Gaspesie": "2025/08/16-Gaspesie", "Bonaire": "2026/06/20-Bonaire"]
+ files["2025/08/16-Gaspesie/00-Trip"] = "date 2025-08-16\ntime 08:30:00\nlocation \"Gaspésie\"\nnotes \"Fin de semaine prolongée en eau froide\"\n"
+ files["2026/06/20-Bonaire/00-Trip"] = "date 2026-06-20\ntime 09:10:00\nlocation \"Bonaire\"\nnotes \"Une semaine de plongées du bord\"\n"
+
+ for plan in plans {
+ let (y, mo, d, h, mi) = plan.date
+ guard let when = NaiveTime.timestamp(year: y, month: mo, day: d, hour: h, minute: mi) else { continue }
+ let weekday = weekdays[((NaiveTime.components(when).weekday ?? 1) - 1) % 7]
+ let name = String(format: "%02d-%@-%02d=%02d=00", d, weekday, h, mi)
+ let folder = plan.trip.flatMap { tripFolders[$0] } ?? String(format: "%04d/%02d", y, mo)
+ let base = "\(folder)/\(name)"
+ let start = plan.cold ? 205.0 : 200.0
+ let used = Double(plan.minutes) * (plan.depth / 20 + 1) * (plan.cold ? 1.5 : 1.25)
+ let end = max(40, (start - used).rounded())
+ files["\(base)/Dive-\(plan.number)"] = diveFile(plan, start: start, end: end)
+ files["\(base)/Divecomputer"] = computerFile(plan, start: start, end: end)
+ }
+ return files
+ }
+
+ private static func quoted(_ text: String) -> String {
+ "\"" + text.replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\n\t") + "\""
+ }
+
+ private static func diveFile(_ plan: Plan, start: Double, end: Double) -> String {
+ var text = "duration \(plan.minutes):00 min\n"
+ text += "rating \(plan.rating)\nvisibility \(plan.visibility)\n"
+ if !plan.tags.isEmpty { text += "tags " + plan.tags.map(quoted).joined(separator: ", ") + "\n" }
+ text += "divesiteid \(plan.site)\n"
+ text += "buddy \(quoted(plan.buddy))\n"
+ text += "suit \(quoted(plan.cold ? "Étanche trilaminé" : "Combinaison courte 3 mm"))\n"
+ text += "notes \(quoted(plan.notes))\n"
+ let gas = plan.o2 == 21 ? "" : " o2=\(plan.o2).0%"
+ if plan.cold {
+ text += "cylinder vol=12.0l workpressure=232.0bar description=\"12 L acier\"\(gas) start=\(Int(start)).0bar end=\(Int(end)).0bar\n"
+ text += "weightsystem weight=10.0kg description=\"ceinture\"\n"
+ } else {
+ text += "cylinder vol=11.1l workpressure=207.0bar description=\"AL80\"\(gas) start=\(Int(start)).0bar end=\(Int(end)).0bar\n"
+ text += "weightsystem weight=4.0kg description=\"poches\"\n"
+ }
+ return text
+ }
+
+ /// Profondeur à l'instant `t` : descente, fond en deux niveaux qui ondule, remontée et palier de sécurité à 5 m.
+ private static func depth(_ plan: Plan, at t: Int) -> Double {
+ let total = plan.minutes * 60
+ let maxDepth = plan.depth
+ let descent = Int(maxDepth / 18 * 60)
+ let stop = maxDepth > 9 ? 180 : 0
+ let finalAscent = Int(5.0 / 9 * 60) + 10
+ let ascent = Int(max(maxDepth * 0.55 - 5, 0) / 9 * 60)
+ let bottomEnd = total - finalAscent - stop - ascent
+ let wobble = sin(Double(t) / 47 + Double(plan.number)) * 0.5 + sin(Double(t) / 13) * 0.2
+ if t <= 0 || t >= total { return 0 }
+ if t < descent { return maxDepth * Double(t) / Double(descent) }
+ if t < bottomEnd {
+ // Du fond vers un second niveau à 55 % de la profondeur, en pente douce.
+ let progress = Double(t - descent) / Double(max(bottomEnd - descent, 1))
+ let eased = progress < 0.35 ? 0 : (progress - 0.35) / 0.65
+ let level = maxDepth * (1 - 0.45 * eased)
+ return max(1, min(maxDepth, level + wobble))
+ }
+ let second = max(maxDepth * 0.55, min(maxDepth, 5))
+ if t < bottomEnd + ascent {
+ return second - (second - 5) * Double(t - bottomEnd) / Double(max(ascent, 1))
+ }
+ if t < bottomEnd + ascent + stop { return min(second, 5) + wobble * 0.3 }
+ let left = total - t
+ return max(0, min(second, 5) * Double(left) / Double(finalAscent))
+ }
+
+ private static func milli(_ value: Double) -> String {
+ let rounded = (value * 10).rounded() / 10
+ return String(format: "%.1f", rounded)
+ }
+
+ private static func computerFile(_ plan: Plan, start: Double, end: Double) -> String {
+ let total = plan.minutes * 60
+ var samples = ""
+ var deepest = 0.0, sum = 0.0, count = 0.0
+ var lastTemp = "", lastNDL = -1
+ var loading = 0.0
+ for t in stride(from: 0, through: total, by: 10) {
+ let d = depth(plan, at: t)
+ deepest = max(deepest, d)
+ sum += d; count += 1
+ var line = String(format: "%3d:%02d", t / 60, t % 60) + " \(milli(d))m"
+ let fraction = plan.depth > 0 ? min(d / plan.depth, 1) : 0
+ let temp = milli((plan.surfaceTemp + (plan.bottomTemp - plan.surfaceTemp) * pow(fraction, 0.6)).rounded())
+ if temp != lastTemp { line += " \(temp)°C"; lastTemp = temp }
+ if t % 30 == 0 {
+ let pressure = start - (start - end) * Double(t) / Double(total)
+ line += " \(milli(pressure))bar:0"
+ }
+ // Charge en azote très simplifiée, juste pour donner une marge sans palier plausible.
+ loading += max(d - 6, 0) * 10 / 60
+ let limit = d < 8 ? 99 : max(2, Int(1400 / pow(d, 1.25) - loading / 14))
+ let ndl = min(limit, 99)
+ if ndl != lastNDL { line += " ndl=\(ndl):00"; lastNDL = ndl }
+ samples += line + "\n"
+ }
+ var text = "model \"Ordinateur de démonstration\"\n"
+ text += "maxdepth \(milli(deepest))m\n"
+ text += "meandepth \(milli(sum / max(count, 1)))m\n"
+ text += "airtemp \(milli(plan.surfaceTemp + 3))°C\n"
+ text += "watertemp \(milli(plan.bottomTemp))°C\n"
+ text += "surfacepressure 1.013bar\n"
+ text += "salinity \(plan.site == "c0000004" ? 1000 : 1025)g/l\n"
+ text += "keyvalue \"Modèle de décompression\" \"GF 30/70\"\n"
+ let gas = plan.o2 == 21 ? " o2=21.0%" : " o2=\(plan.o2).0%"
+ text += "event 0:00 type=25 flags=1 name=\"gaschange\" cylinder=0\(gas)\n"
+ return text + samples
+ }
+}
diff --git a/App/Model/Keychain.swift b/App/Model/Keychain.swift
@@ -0,0 +1,32 @@
+import Foundation
+import Security
+
+/// Mot de passe du nuage, gardé dans le trousseau de l'appareil.
+enum Keychain {
+ private static func query(_ account: String) -> [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: Brand.keychainService,
+ kSecAttrAccount as String: account]
+ }
+
+ static func save(password: String, account: String) {
+ SecItemDelete(query(account) as CFDictionary)
+ var item = query(account)
+ item[kSecValueData as String] = Data(password.utf8)
+ item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
+ SecItemAdd(item as CFDictionary, nil)
+ }
+
+ static func password(account: String) -> String? {
+ var item = query(account)
+ item[kSecReturnData as String] = true
+ item[kSecMatchLimit as String] = kSecMatchLimitOne
+ var result: AnyObject?
+ guard SecItemCopyMatching(item as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
+ return String(decoding: data, as: UTF8.self)
+ }
+
+ static func delete(account: String) {
+ SecItemDelete(query(account) as CFDictionary)
+ }
+}
diff --git a/App/Model/Units.swift b/App/Model/Units.swift
@@ -0,0 +1,89 @@
+import Foundation
+import SubsurfaceLog
+
+/// Affichage des grandeurs : le carnet est toujours en métrique, la conversion ne se fait qu'à l'écran.
+struct Units: Equatable {
+ var imperial = false
+
+ private func number(_ value: Double, _ digits: Int) -> String {
+ value.formatted(.number.precision(.fractionLength(digits)))
+ }
+
+ var depthUnit: String { imperial ? "ft" : "m" }
+ var temperatureUnit: String { imperial ? "°F" : "°C" }
+ var pressureUnit: String { imperial ? "psi" : "bar" }
+
+ func depthValue(_ meters: Double) -> Double { imperial ? meters * 3.28084 : meters }
+ func metersFromDisplay(_ value: Double) -> Double { imperial ? value / 3.28084 : value }
+ func temperatureValue(_ celsius: Double) -> Double { imperial ? celsius * 9 / 5 + 32 : celsius }
+ func celsiusFromDisplay(_ value: Double) -> Double { imperial ? (value - 32) * 5 / 9 : value }
+ func pressureValue(_ bar: Double) -> Double { imperial ? bar * 14.5038 : bar }
+
+ func depth(_ meters: Double) -> String { "\(number(depthValue(meters), imperial ? 0 : 1)) \(depthUnit)" }
+ func temperature(_ celsius: Double) -> String { "\(number(temperatureValue(celsius), 0)) \(temperatureUnit)" }
+ func pressure(_ bar: Double) -> String { "\(number(pressureValue(bar), 0)) \(pressureUnit)" }
+ func weight(_ kilograms: Double) -> String {
+ imperial ? "\(number(kilograms * 2.20462, 0)) lb" : "\(number(kilograms, 1)) kg"
+ }
+ func volume(_ liters: Double) -> String { "\(number(liters, 1)) L" }
+ func sac(_ litersPerMinute: Double) -> String {
+ imperial ? "\(number(litersPerMinute * 0.0353147, 2)) pi³/min" : "\(number(litersPerMinute, 1)) L/min"
+ }
+
+ /// « 45 min », « 1 h 05 »
+ static func duration(_ seconds: Int) -> String {
+ let minutes = Int((Double(seconds) / 60).rounded())
+ if minutes < 60 { return "\(minutes) min" }
+ return "\(minutes / 60) h " + String(format: "%02d", minutes % 60)
+ }
+
+ /// « 12:34 » pour le curseur du profil.
+ static func clock(_ seconds: Int) -> String { "\(seconds / 60):" + String(format: "%02d", seconds % 60) }
+
+ static func totalTime(_ seconds: Int) -> String {
+ let hours = seconds / 3600
+ let minutes = (seconds % 3600) / 60
+ return hours > 0 ? "\(hours) h " + String(format: "%02d", minutes) : "\(minutes) min"
+ }
+}
+
+/// Les heures du carnet sont locales et « naïves » : on les affiche telles quelles, sans fuseau.
+enum DiveDate {
+ private static let utc = TimeZone(identifier: "UTC")!
+
+ static func full(_ dive: Dive) -> String {
+ dive.date.formatted(Date.FormatStyle(date: .complete, time: .shortened, timeZone: utc))
+ }
+
+ static func day(_ dive: Dive) -> String {
+ dive.date.formatted(Date.FormatStyle(timeZone: utc).day().month(.abbreviated).year())
+ }
+
+ static func short(_ dive: Dive) -> String {
+ dive.date.formatted(Date.FormatStyle(timeZone: utc).weekday(.abbreviated).day().month(.abbreviated))
+ }
+
+ static func time(_ dive: Dive) -> String {
+ dive.date.formatted(Date.FormatStyle(timeZone: utc).hour().minute())
+ }
+
+ static func monthTitle(_ when: Int) -> String {
+ Date(timeIntervalSince1970: TimeInterval(when)).formatted(Date.FormatStyle(timeZone: utc).month(.wide).year()).capitalizedFirst
+ }
+
+ static func year(_ when: Int) -> Int { NaiveTime.components(when).year ?? 0 }
+ static func monthKey(_ when: Int) -> String {
+ let c = NaiveTime.components(when)
+ return String(format: "%04d-%02d", c.year ?? 0, c.month ?? 0)
+ }
+
+ /// Date choisie dans un sélecteur (fuseau de l'appareil) → heure naïve du carnet, secondes à zéro.
+ static func naive(from date: Date) -> Int {
+ let local = Int(date.timeIntervalSince1970) + TimeZone.current.secondsFromGMT(for: date)
+ return local - local % 60
+ }
+}
+
+extension String {
+ var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() }
+}
diff --git a/App/Views/Components.swift b/App/Views/Components.swift
@@ -0,0 +1,79 @@
+import SwiftUI
+
+struct Stars: View {
+ let value: Int
+ var body: some View {
+ HStack(spacing: 1) {
+ ForEach(1...5, id: \.self) { index in
+ Image(systemName: index <= value ? "star.fill" : "star")
+ .foregroundStyle(index <= value ? Color.yellow : Color.secondary.opacity(0.4))
+ }
+ }
+ .font(.caption)
+ .accessibilityLabel("\(value) sur 5")
+ }
+}
+
+/// Note sur 5 ; toucher l'étoile déjà choisie remet à zéro.
+struct StarPicker: View {
+ let title: String
+ @Binding var value: Int
+
+ var body: some View {
+ HStack {
+ Text(title)
+ Spacer()
+ HStack(spacing: 6) {
+ ForEach(1...5, id: \.self) { index in
+ Image(systemName: index <= value ? "star.fill" : "star")
+ .font(.title3)
+ .foregroundStyle(index <= value ? Color.yellow : Color.secondary.opacity(0.5))
+ .onTapGesture { value = value == index ? 0 : index }
+ .accessibilityLabel("\(index) sur 5")
+ .accessibilityAddTraits(.isButton)
+ }
+ }
+ }
+ }
+}
+
+struct Figure: View {
+ let title: String
+ let value: String
+ var icon: String?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 4) {
+ if let icon { Image(systemName: icon).font(.caption2) }
+ Text(title).font(.caption2)
+ }
+ .foregroundStyle(.secondary)
+ Text(value)
+ .font(.headline.monospacedDigit())
+ .lineLimit(1)
+ .minimumScaleFactor(0.7)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(10)
+ .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ }
+}
+
+struct TagChips: View {
+ let tags: [String]
+ var body: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ ForEach(tags, id: \.self) { tag in
+ Text(tag)
+ .font(.caption.weight(.medium))
+ .padding(.horizontal, 10)
+ .padding(.vertical, 4)
+ .background(Color.accentColor.opacity(0.15), in: Capsule())
+ .foregroundStyle(Color.accentColor)
+ }
+ }
+ }
+ }
+}
diff --git a/App/Views/DiveDetailView.swift b/App/Views/DiveDetailView.swift
@@ -0,0 +1,211 @@
+import MapKit
+import SubsurfaceLog
+import SwiftUI
+
+struct DiveDetailView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ let diveID: String
+
+ @State private var computers: [DiveComputer] = []
+ @State private var loadedFor: [String] = []
+ @State private var computerIndex = 0
+ @State private var editing = LaunchOptions.flag("-edit")
+ @State private var confirmingDelete = false
+ @State private var error: String?
+
+ var body: some View {
+ if let dive = model.dive(id: diveID) {
+ content(dive)
+ } else {
+ ContentUnavailableView("Plongée introuvable", systemImage: "questionmark.circle",
+ description: Text("Elle a été supprimée ou renumérotée depuis un autre appareil."))
+ }
+ }
+
+ private func content(_ dive: Dive) -> some View {
+ let site = model.logbook.site(of: dive)
+ let units = model.units
+ return ScrollViewReader { proxy in
+ List {
+ Section {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(model.siteName(of: dive))
+ .font(.title2.bold())
+ Text(DiveDate.full(dive).capitalizedFirst)
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ HStack(spacing: 10) {
+ if let trip = model.logbook.trip(of: dive), !trip.location.isEmpty {
+ Label(trip.location, systemImage: "suitcase")
+ }
+ if dive.rating > 0 { Stars(value: dive.rating) }
+ }
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 3), spacing: 8) {
+ Figure(title: "Prof. max", value: units.depth(dive.maxDepth), icon: "arrow.down.to.line")
+ Figure(title: "Durée", value: Units.duration(dive.durationSeconds), icon: "clock")
+ if let t = dive.waterTemperature { Figure(title: "Eau", value: units.temperature(t), icon: "thermometer.medium") }
+ if let mean = dive.meanDepth { Figure(title: "Prof. moy.", value: units.depth(mean), icon: "arrow.up.and.down") }
+ if let sac = dive.sac { Figure(title: "Conso.", value: units.sac(sac), icon: "lungs") }
+ if let t = dive.airTemperature { Figure(title: "Air", value: units.temperature(t), icon: "sun.max") }
+ }
+ .listRowSeparator(.hidden)
+ }
+
+ Section("Profil") {
+ if computers.count > 1 {
+ Picker("Ordinateur", selection: $computerIndex) {
+ ForEach(computers.indices, id: \.self) { index in
+ Text(computers[index].model.isEmpty ? "Ordinateur \(index + 1)" : computers[index].model).tag(index)
+ }
+ }
+ }
+ if computers.indices.contains(computerIndex), computers[computerIndex].samples.count > 1 {
+ ProfileChart(data: ProfileData(computer: computers[computerIndex], units: units), units: units)
+ .padding(.vertical, 4)
+ } else if loadedFor == dive.computerBlobs.map(\.hex) {
+ Text("Pas de profil enregistré pour cette plongée.")
+ .foregroundStyle(.secondary)
+ } else {
+ ProgressView().frame(maxWidth: .infinity, minHeight: 220)
+ }
+ }
+
+ if !dive.buddy.isEmpty || !dive.divemaster.isEmpty {
+ Section("Équipe") {
+ if !dive.buddy.isEmpty { LabeledContent("Binôme", value: dive.buddy) }
+ if !dive.divemaster.isEmpty { LabeledContent("Guide", value: dive.divemaster) }
+ }
+ }
+
+ if !dive.cylinders.isEmpty || !dive.weights.isEmpty || !dive.suit.isEmpty {
+ Section("Équipement") {
+ ForEach(Array(dive.cylinders.enumerated()), id: \.offset) { _, cylinder in
+ VStack(alignment: .leading, spacing: 2) {
+ HStack {
+ Text(cylinder.description.isEmpty ? "Bouteille" : cylinder.description)
+ Spacer()
+ Text(cylinder.gas.label)
+ .font(.callout.weight(.semibold))
+ .foregroundStyle(cylinder.gas.isAir ? Color.secondary : Color.green)
+ }
+ if let start = cylinder.startBar, let end = cylinder.endBar, start > end {
+ Text("\(units.pressure(start)) → \(units.pressure(end))")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ } else if let use = cylinder.use, use == "not used" {
+ Text("Non utilisée").font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ }
+ if dive.totalWeight > 0 { LabeledContent("Lest", value: units.weight(dive.totalWeight)) }
+ if !dive.suit.isEmpty { LabeledContent("Combinaison", value: dive.suit) }
+ }
+ }
+
+ if dive.visibility > 0 || dive.current > 0 || dive.waveSize > 0 || !dive.tags.isEmpty {
+ Section("Conditions") {
+ if dive.visibility > 0 { LabeledContent("Visibilité") { Stars(value: dive.visibility) } }
+ if dive.current > 0 { LabeledContent("Courant") { Stars(value: dive.current) } }
+ if dive.waveSize > 0 { LabeledContent("Vagues") { Stars(value: dive.waveSize) } }
+ if !dive.tags.isEmpty { TagChips(tags: dive.tags) }
+ }
+ }
+
+ if !dive.notes.isEmpty {
+ Section("Notes") {
+ EmptyView().id("notes")
+ Text(dive.notes).textSelection(.enabled)
+ }
+ }
+
+ if let site, let latitude = site.latitude, let longitude = site.longitude {
+ Section("Lieu") {
+ let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
+ Map(initialPosition: .region(MKCoordinateRegion(center: coordinate, latitudinalMeters: 6000, longitudinalMeters: 6000))) {
+ Marker(site.name, systemImage: "water.waves", coordinate: coordinate).tint(Color.accentColor)
+ }
+ .frame(height: 170)
+ .listRowInsets(EdgeInsets())
+ .allowsHitTesting(false)
+ if !site.description.isEmpty { Text(site.description).font(.callout) }
+ if !site.notes.isEmpty { Text(site.notes).font(.callout).foregroundStyle(.secondary) }
+ }
+ }
+
+ if computers.indices.contains(computerIndex) {
+ let computer = computers[computerIndex]
+ Section("Ordinateur") {
+ EmptyView().id("bottom")
+ LabeledContent("Modèle", value: computer.isManual ? "Plongée saisie à la main" : (computer.model.isEmpty ? "Inconnu" : computer.model))
+ if computer.diveMode != "OC" { LabeledContent("Mode", value: computer.diveMode) }
+ if !computer.events.isEmpty {
+ DisclosureGroup("Événements (\(computer.events.count))") {
+ ForEach(Array(computer.events.enumerated()), id: \.offset) { _, event in
+ LabeledContent(Units.clock(event.time), value: event.isGasChange ? "Gaz : \(event.gas?.label ?? "changement")" : event.name)
+ .font(.callout)
+ }
+ }
+ }
+ if !computer.extra.isEmpty {
+ DisclosureGroup("Détails (\(computer.extra.count))") {
+ ForEach(Array(computer.extra.enumerated()), id: \.offset) { _, pair in
+ LabeledContent(pair.key, value: pair.value).font(.callout)
+ }
+ }
+ }
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .onChange(of: loadedFor) {
+ // Option de capture d'écran : montrer le bas de la fiche.
+ if let target = LaunchOptions.value("-scroll") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { proxy.scrollTo(target, anchor: .bottom) }
+ }
+ }
+ }
+ .navigationTitle(dive.number > 0 ? "Plongée \(dive.number)" : "Plongée")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItemGroup(placement: .topBarTrailing) {
+ Button("Modifier") { editing = true }
+ Menu {
+ Button("Supprimer la plongée", systemImage: "trash", role: .destructive) { confirmingDelete = true }
+ } label: {
+ Label("Autres actions", systemImage: "ellipsis.circle")
+ }
+ }
+ }
+ .sheet(isPresented: $editing) { DiveEditView(dive: dive) }
+ .confirmationDialog("Supprimer cette plongée du carnet ?", isPresented: $confirmingDelete, titleVisibility: .visible) {
+ Button("Supprimer", role: .destructive) {
+ Task {
+ do {
+ try await model.apply(.deleteDive(when: dive.when, number: dive.number))
+ dismiss()
+ } catch {
+ self.error = AppModel.describe(error)
+ }
+ }
+ }
+ } message: {
+ Text("La suppression sera envoyée au nuage Subsurface à la prochaine synchronisation.")
+ }
+ .alert("Action impossible", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(error ?? "")
+ }
+ .task(id: dive.computerBlobs.map(\.hex)) {
+ let loaded = await model.profile(of: dive)
+ computers = loaded
+ // Par défaut, l'ordinateur qui a le profil le plus détaillé.
+ computerIndex = loaded.indices.max(by: { loaded[$0].samples.count < loaded[$1].samples.count }) ?? 0
+ loadedFor = dive.computerBlobs.map(\.hex)
+ }
+ }
+}
diff --git a/App/Views/DiveEditView.swift b/App/Views/DiveEditView.swift
@@ -0,0 +1,276 @@
+import SubsurfaceLog
+import SwiftUI
+
+/// Modification des champs « carnet » d'une plongée. Seuls les champs réellement changés sont envoyés.
+struct DiveEditView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ let dive: Dive
+
+ @State private var siteUUID: UInt32?
+ @State private var buddy = ""
+ @State private var divemaster = ""
+ @State private var suit = ""
+ @State private var tags = ""
+ @State private var rating = 0
+ @State private var visibility = 0
+ @State private var notes = ""
+ @State private var loaded = false
+ @State private var saving = false
+ @State private var error: String?
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ Section {
+ NavigationLink {
+ SitePicker(selection: $siteUUID)
+ } label: {
+ LabeledContent("Lieu", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? "Aucun")
+ }
+ }
+ Section("Équipe") {
+ TextField("Binôme", text: $buddy)
+ TextField("Guide", text: $divemaster)
+ }
+ Section("Conditions") {
+ StarPicker(title: "Évaluation", value: $rating)
+ StarPicker(title: "Visibilité", value: $visibility)
+ TextField("Combinaison", text: $suit)
+ TextField("Étiquettes, séparées par des virgules", text: $tags)
+ .textInputAutocapitalization(.never)
+ }
+ Section("Notes") {
+ TextEditor(text: $notes)
+ .frame(minHeight: 140)
+ }
+ if let error {
+ Section { Text(error).foregroundStyle(.red) }
+ }
+ }
+ .navigationTitle(dive.number > 0 ? "Plongée \(dive.number)" : "Plongée")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Enregistrer", action: save).disabled(saving || changes.isEmpty)
+ }
+ }
+ .onAppear {
+ guard !loaded else { return }
+ loaded = true
+ siteUUID = dive.siteUUID
+ buddy = dive.buddy
+ divemaster = dive.divemaster
+ suit = dive.suit
+ tags = dive.tags.joined(separator: ", ")
+ rating = dive.rating
+ visibility = dive.visibility
+ notes = dive.notes
+ }
+ }
+ }
+
+ private var cleanTags: [String] {
+ tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ }
+
+ private var changes: [String: String] {
+ var fields = [String: String]()
+ func trimmed(_ text: String) -> String { text.trimmingCharacters(in: .whitespacesAndNewlines) }
+ if siteUUID != dive.siteUUID { fields[DiveField.site.rawValue] = siteUUID.map { String($0, radix: 16) } ?? "" }
+ if trimmed(buddy) != dive.buddy { fields[DiveField.buddy.rawValue] = trimmed(buddy) }
+ if trimmed(divemaster) != dive.divemaster { fields[DiveField.divemaster.rawValue] = trimmed(divemaster) }
+ if trimmed(suit) != dive.suit { fields[DiveField.suit.rawValue] = trimmed(suit) }
+ if cleanTags != dive.tags { fields[DiveField.tags.rawValue] = cleanTags.joined(separator: ",") }
+ if rating != dive.rating { fields[DiveField.rating.rawValue] = String(rating) }
+ if visibility != dive.visibility { fields[DiveField.visibility.rawValue] = String(visibility) }
+ if trimmed(notes) != dive.notes { fields[DiveField.notes.rawValue] = trimmed(notes) }
+ return fields
+ }
+
+ private func save() {
+ saving = true
+ Task {
+ do {
+ try await model.apply(.editDive(when: dive.when, number: dive.number, fields: changes))
+ dismiss()
+ } catch {
+ self.error = AppModel.describe(error)
+ saving = false
+ }
+ }
+ }
+}
+
+/// Choix d'un lieu existant, ou création d'un lieu par son nom.
+struct SitePicker: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @Binding var selection: UInt32?
+ @State private var search = ""
+ @State private var creating = false
+ @State private var newName = ""
+ @State private var error: String?
+
+ var body: some View {
+ let sites = model.logbook.sites.values
+ .filter { !$0.name.isEmpty && (search.isEmpty || $0.name.localizedCaseInsensitiveContains(search)) }
+ .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
+ List {
+ Section {
+ Button { creating = true } label: { Label("Nouveau lieu…", systemImage: "plus.circle") }
+ Button { selection = nil; dismiss() } label: {
+ HStack {
+ Text("Aucun lieu").foregroundStyle(Color.primary)
+ Spacer()
+ if selection == nil { Image(systemName: "checkmark") }
+ }
+ }
+ }
+ Section {
+ ForEach(sites) { site in
+ Button { selection = site.uuid; dismiss() } label: {
+ HStack {
+ VStack(alignment: .leading) {
+ Text(site.name).foregroundStyle(Color.primary)
+ if let country = site.country { Text(country).font(.caption).foregroundStyle(.secondary) }
+ }
+ Spacer()
+ if selection == site.uuid { Image(systemName: "checkmark") }
+ }
+ }
+ }
+ }
+ }
+ .navigationTitle("Lieu")
+ .searchable(text: $search, prompt: "Chercher un lieu")
+ .alert("Nouveau lieu", isPresented: $creating) {
+ TextField("Nom du lieu", text: $newName)
+ Button("Annuler", role: .cancel) { newName = "" }
+ Button("Créer") { create() }
+ } message: {
+ Text("La position pourra être ajoutée plus tard dans Subsurface.")
+ }
+ .alert("Action impossible", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(error ?? "")
+ }
+ }
+
+ private func create() {
+ let name = newName.trimmingCharacters(in: .whitespacesAndNewlines)
+ newName = ""
+ guard !name.isEmpty else { return }
+ if let existing = model.logbook.sites.values.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) {
+ selection = existing.uuid
+ dismiss()
+ return
+ }
+ let uuid = model.newSiteUUID()
+ Task {
+ do {
+ try await model.apply(.addSite(uuid: uuid, name: name, latitude: nil, longitude: nil))
+ selection = uuid
+ dismiss()
+ } catch {
+ self.error = AppModel.describe(error)
+ }
+ }
+ }
+}
+
+/// Saisie d'une plongée sans ordinateur.
+struct NewDiveView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var date = Date()
+ @State private var minutes = 40
+ @State private var depthText = ""
+ @State private var temperatureText = ""
+ @State private var siteUUID: UInt32?
+ @State private var buddy = ""
+ @State private var notes = ""
+ @State private var rating = 0
+ @State private var saving = false
+ @State private var error: String?
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ Section {
+ DatePicker("Début", selection: $date, in: ...Date.now)
+ Stepper(value: $minutes, in: 1...600) {
+ LabeledContent("Durée", value: "\(minutes) min")
+ }
+ LabeledContent("Profondeur max (\(model.units.depthUnit))") {
+ TextField("0", text: $depthText)
+ .keyboardType(.decimalPad)
+ .multilineTextAlignment(.trailing)
+ }
+ LabeledContent("Eau (\(model.units.temperatureUnit))") {
+ TextField("–", text: $temperatureText)
+ .keyboardType(.numbersAndPunctuation)
+ .multilineTextAlignment(.trailing)
+ }
+ }
+ Section {
+ NavigationLink {
+ SitePicker(selection: $siteUUID)
+ } label: {
+ LabeledContent("Lieu", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? "Aucun")
+ }
+ TextField("Binôme", text: $buddy)
+ StarPicker(title: "Évaluation", value: $rating)
+ }
+ Section("Notes") {
+ TextEditor(text: $notes).frame(minHeight: 100)
+ }
+ if let error {
+ Section { Text(error).foregroundStyle(.red) }
+ }
+ }
+ .navigationTitle("Nouvelle plongée")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Ajouter", action: save).disabled(saving || depth == nil)
+ }
+ }
+ }
+ }
+
+ private func parse(_ text: String) -> Double? {
+ Double(text.replacingOccurrences(of: ",", with: ".").trimmingCharacters(in: .whitespaces))
+ }
+
+ private var depth: Double? {
+ guard let value = parse(depthText), value > 0 else { return nil }
+ let meters = model.units.metersFromDisplay(value)
+ return meters <= 350 ? meters : nil
+ }
+
+ private func save() {
+ guard let depth else { return }
+ saving = true
+ var dive = NewDive(when: DiveDate.naive(from: date), number: model.logbook.nextNumber, durationSeconds: minutes * 60,
+ maxDepth: (depth * 10).rounded() / 10)
+ dive.siteUUID = siteUUID
+ dive.buddy = buddy.trimmingCharacters(in: .whitespacesAndNewlines)
+ dive.notes = notes.trimmingCharacters(in: .whitespacesAndNewlines)
+ dive.rating = rating
+ if let t = parse(temperatureText) { dive.waterTemperature = (model.units.celsiusFromDisplay(t) * 10).rounded() / 10 }
+ Task {
+ do {
+ try await model.apply(.addDive(dive))
+ dismiss()
+ } catch {
+ self.error = AppModel.describe(error)
+ saving = false
+ }
+ }
+ }
+}
diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift
@@ -0,0 +1,148 @@
+import SubsurfaceLog
+import SwiftUI
+
+struct DiveListView: View {
+ @Environment(AppModel.self) private var model
+ @State private var search = ""
+ @State private var adding = false
+ @State private var path: [String] = []
+ @State private var appliedLaunchOptions = false
+
+ var body: some View {
+ NavigationStack(path: $path) {
+ let sections = model.sections(matching: search)
+ List {
+ SyncBanner()
+ ForEach(sections) { section in
+ Section {
+ ForEach(section.dives) { dive in
+ NavigationLink(value: dive.id) { DiveRow(dive: dive) }
+ }
+ } header: {
+ HStack {
+ Text(section.title)
+ Spacer()
+ Text(section.subtitle.isEmpty ? countLabel(section.dives.count) : "\(section.subtitle) · \(countLabel(section.dives.count))")
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .overlay {
+ if model.logbook.dives.isEmpty {
+ ContentUnavailableView {
+ Label("Carnet vide", systemImage: "water.waves")
+ } description: {
+ Text(model.syncState == .syncing ? "Téléchargement du carnet…" : "Ajoutez une plongée avec le bouton +, ou tirez pour synchroniser.")
+ }
+ } else if sections.isEmpty {
+ ContentUnavailableView.search(text: search)
+ }
+ }
+ .navigationTitle("Plongées")
+ .navigationDestination(for: String.self) { DiveDetailView(diveID: $0) }
+ .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Lieu, binôme, étiquette, notes")
+ .refreshable { await model.sync() }
+ .toolbar {
+ ToolbarItem(placement: .topBarLeading) {
+ if model.syncState == .syncing { ProgressView() }
+ }
+ ToolbarItem(placement: .topBarTrailing) {
+ Button { adding = true } label: { Label("Ajouter une plongée", systemImage: "plus") }
+ }
+ }
+ .sheet(isPresented: $adding) { NewDiveView() }
+ .onAppear {
+ guard !appliedLaunchOptions else { return }
+ appliedLaunchOptions = true
+ if let number = LaunchOptions.value("-showDive").flatMap({ Int($0) }),
+ let dive = model.logbook.dives.first(where: { $0.number == number }) {
+ path = [dive.id]
+ }
+ if LaunchOptions.flag("-newDive") { adding = true }
+ }
+ }
+ }
+
+ private func countLabel(_ count: Int) -> String {
+ count == 1 ? "1 plongée" : "\(count) plongées"
+ }
+}
+
+/// État de la synchronisation, en tête de liste quand il y a quelque chose à dire.
+struct SyncBanner: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ if model.isDemo {
+ Section {
+ Label("Carnet de démonstration : rien n'est envoyé.", systemImage: "sparkles")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+ } else if case .failed(let message) = model.syncState {
+ Section {
+ Label(message, systemImage: "exclamationmark.icloud")
+ .font(.footnote)
+ .foregroundStyle(.red)
+ if !model.pending.isEmpty { pendingLabel }
+ }
+ } else if !model.pending.isEmpty {
+ Section { pendingLabel }
+ }
+ ForEach(model.notices, id: \.self) { notice in
+ Section {
+ Label(notice, systemImage: "info.circle")
+ .font(.footnote)
+ .foregroundStyle(.orange)
+ }
+ }
+ }
+
+ private var pendingLabel: some View {
+ Label(model.pending.count == 1 ? "1 modification à envoyer" : "\(model.pending.count) modifications à envoyer",
+ systemImage: "arrow.up.circle")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ }
+}
+
+struct DiveRow: View {
+ @Environment(AppModel.self) private var model
+ let dive: Dive
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 12) {
+ Text(dive.number > 0 ? "\(dive.number)" : "–")
+ .font(.footnote.monospacedDigit().weight(.semibold))
+ .foregroundStyle(.white)
+ .frame(minWidth: 34, minHeight: 34)
+ .background(Color.accentColor.gradient, in: RoundedRectangle(cornerRadius: 9, style: .continuous))
+ VStack(alignment: .leading, spacing: 3) {
+ Text(model.siteName(of: dive))
+ .font(.body.weight(.medium))
+ .lineLimit(1)
+ HStack(spacing: 6) {
+ Text("\(DiveDate.short(dive)) · \(DiveDate.time(dive))")
+ if dive.rating > 0 {
+ Text(String(repeating: "★", count: dive.rating))
+ .foregroundStyle(.yellow)
+ }
+ }
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ Spacer(minLength: 8)
+ VStack(alignment: .trailing, spacing: 3) {
+ Text(model.units.depth(dive.maxDepth))
+ .font(.callout.monospacedDigit().weight(.semibold))
+ Text(Units.duration(dive.durationSeconds))
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(.vertical, 2)
+ .opacity(dive.invalid ? 0.5 : 1)
+ }
+}
diff --git a/App/Views/LoginView.swift b/App/Views/LoginView.swift
@@ -0,0 +1,101 @@
+import SwiftUI
+
+struct LoginView: View {
+ @Environment(AppModel.self) private var model
+ @State private var email = ""
+ @State private var password = ""
+ @State private var busy = false
+ @State private var error: String?
+ @FocusState private var focus: Field?
+
+ private enum Field { case email, password }
+
+ var body: some View {
+ NavigationStack {
+ ScrollView {
+ VStack(spacing: 20) {
+ Image("Logo")
+ .resizable()
+ .frame(width: 120, height: 120)
+ .clipShape(RoundedRectangle(cornerRadius: 27, style: .continuous))
+ .shadow(radius: 8, y: 4)
+ .padding(.top, 32)
+ Text(Brand.name)
+ .font(.largeTitle.bold())
+ Text("Votre carnet de plongée Subsurface, sur iPhone.")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+
+ VStack(spacing: 12) {
+ TextField("Courriel du compte Subsurface", text: $email)
+ .textContentType(.username)
+ .keyboardType(.emailAddress)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .focused($focus, equals: .email)
+ .submitLabel(.next)
+ .onSubmit { focus = .password }
+ Divider()
+ SecureField("Mot de passe", text: $password)
+ .textContentType(.password)
+ .focused($focus, equals: .password)
+ .submitLabel(.go)
+ .onSubmit { signIn() }
+ }
+ .padding()
+ .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14))
+
+ if let error {
+ Label(error, systemImage: "exclamationmark.triangle.fill")
+ .font(.footnote)
+ .foregroundStyle(.red)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ Button(action: signIn) {
+ HStack {
+ if busy { ProgressView().tint(.white) }
+ Text(busy ? "Connexion…" : "Se connecter")
+ .fontWeight(.semibold)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 6)
+ }
+ .buttonStyle(.borderedProminent)
+ .disabled(busy || email.isEmpty || password.isEmpty)
+
+ Button("Essayer avec un carnet de démonstration") {
+ Task { await model.startDemo() }
+ }
+ .font(.subheadline)
+ .disabled(busy)
+
+ Text("Le compte est celui du nuage Subsurface (cloud.subsurface-divelog.org), créé depuis Subsurface. Vos identifiants ne sont envoyés qu'à ce service et le mot de passe reste dans le trousseau de l'iPhone.\n\n\(Brand.name) est une application indépendante, sans lien avec l'équipe de Subsurface.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .padding(.top, 8)
+ }
+ .padding(.horizontal, 24)
+ }
+ .background(Color(.systemGroupedBackground))
+ .scrollDismissesKeyboard(.interactively)
+ }
+ }
+
+ private func signIn() {
+ guard !busy, !email.isEmpty, !password.isEmpty else { return }
+ busy = true
+ error = nil
+ focus = nil
+ Task {
+ do {
+ try await model.signIn(email: email, password: password)
+ } catch {
+ self.error = AppModel.describe(error)
+ }
+ busy = false
+ }
+ }
+}
diff --git a/App/Views/ProfileChart.swift b/App/Views/ProfileChart.swift
@@ -0,0 +1,264 @@
+import Charts
+import SubsurfaceLog
+import SwiftUI
+
+/// Données du profil préparées pour l'affichage (unités de l'usager, échantillons allégés).
+struct ProfileData {
+ struct Point: Identifiable {
+ let id: Int
+ let minute: Double
+ let value: Double
+ }
+
+ struct Series: Identifiable {
+ let id: String
+ var points: [Point]
+ }
+
+ struct Marker: Identifiable {
+ let id: Int
+ let minute: Double
+ let depth: Double
+ let label: String?
+ let name: String
+ let seconds: Int
+ }
+
+ var depth: [Point] = []
+ var ceiling: [Point] = []
+ var temperature: [Point] = []
+ var pressure: [Series] = []
+ var markers: [Marker] = []
+ var maxMinute = 1.0
+ var samples: [Sample] = []
+ /// Dernière pression connue de chaque capteur à chaque échantillon, pour la lecture au curseur.
+ var pressureAt: [[Int: Double]] = []
+
+ init(computer: DiveComputer, units: Units) {
+ samples = computer.samples
+ guard let last = samples.last else { return }
+ maxMinute = max(Double(last.time) / 60, 1)
+
+ // Au plus ~700 points : on garde le plus profond de chaque tranche pour ne pas raboter les pointes.
+ let bucket = max(1, samples.count / 700)
+ var index = 0
+ while index < samples.count {
+ let slice = samples[index..<min(index + bucket, samples.count)]
+ if let deepest = slice.max(by: { $0.depth < $1.depth }) {
+ depth.append(Point(id: depth.count, minute: Double(deepest.time) / 60, value: units.depthValue(deepest.depth)))
+ }
+ index += bucket
+ }
+
+ var lastTemp: Double?
+ var known = [Int: Double]()
+ var bySensor = [Int: [Point]]()
+ var inCeiling = false
+ for (i, sample) in samples.enumerated() {
+ let minute = Double(sample.time) / 60
+ if let t = sample.temperature, t != lastTemp || i == samples.count - 1 {
+ temperature.append(Point(id: temperature.count, minute: minute, value: units.temperatureValue(t)))
+ lastTemp = t
+ }
+ for p in sample.pressures {
+ known[p.sensor] = p.bar
+ bySensor[p.sensor, default: []].append(Point(id: bySensor[p.sensor]?.count ?? 0, minute: minute, value: units.pressureValue(p.bar)))
+ }
+ pressureAt.append(known)
+ let stop = sample.inDeco ? (sample.stopDepth ?? 0) : 0
+ if stop > 0 || inCeiling {
+ ceiling.append(Point(id: ceiling.count, minute: minute, value: units.depthValue(stop)))
+ inCeiling = stop > 0
+ }
+ }
+ pressure = bySensor.keys.sorted().map { Series(id: "Bouteille \($0 + 1)", points: bySensor[$0] ?? []) }
+
+ for (i, event) in computer.events.enumerated() {
+ let minute = Double(event.time) / 60
+ let depthThere = sample(at: minute).map { units.depthValue($0.depth) } ?? 0
+ var label: String?
+ if event.isGasChange, event.time > 30 { label = event.gas?.label ?? "Gaz" }
+ if event.isGasChange, event.time <= 30 { continue }
+ markers.append(Marker(id: i, minute: minute, depth: depthThere, label: label, name: event.name, seconds: event.time))
+ }
+ }
+
+ func sampleIndex(at minute: Double) -> Int? {
+ guard !samples.isEmpty else { return nil }
+ let target = Int(minute * 60)
+ var low = 0, high = samples.count - 1
+ while low < high {
+ let mid = (low + high) / 2
+ if samples[mid].time < target { low = mid + 1 } else { high = mid }
+ }
+ if low > 0, abs(samples[low - 1].time - target) < abs(samples[low].time - target) { return low - 1 }
+ return low
+ }
+
+ func sample(at minute: Double) -> Sample? { sampleIndex(at: minute).map { samples[$0] } }
+}
+
+struct ProfileChart: View {
+ let data: ProfileData
+ let units: Units
+ @State private var selection: Double?
+
+ private let axisWidth: CGFloat = 34
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ readout
+ depthChart
+ .frame(height: 220)
+ if data.temperature.count > 1 {
+ smallChart(title: "Température", unit: units.temperatureUnit, series: [.init(id: "Température", points: data.temperature)], color: .orange)
+ }
+ if data.pressure.contains(where: { $0.points.count > 1 }) {
+ smallChart(title: "Pression des bouteilles", unit: units.pressureUnit, series: data.pressure, color: .green)
+ }
+ }
+ }
+
+ /// Valeurs sous le doigt ; sans sélection, une invitation discrète.
+ @ViewBuilder private var readout: some View {
+ if let minute = selection, let index = data.sampleIndex(at: minute) {
+ let sample = data.samples[index]
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 14) {
+ value("Temps", Units.clock(sample.time))
+ value("Profondeur", units.depth(sample.depth))
+ if let t = sample.temperature { value("Eau", units.temperature(t)) }
+ ForEach(data.pressureAt[index].keys.sorted(), id: \.self) { sensor in
+ value(data.pressureAt[index].count > 1 ? "Bout. \(sensor + 1)" : "Pression", units.pressure(data.pressureAt[index][sensor] ?? 0))
+ }
+ if sample.inDeco, let stop = sample.stopDepth, stop > 0 {
+ value("Palier", units.depth(stop), color: .red)
+ if let tts = sample.tts { value("Surface dans", Units.duration(tts)) }
+ } else if let ndl = sample.ndl {
+ value("Sans palier", ndl >= 99 * 60 ? "99+ min" : Units.duration(ndl))
+ }
+ if let cns = sample.cns, cns > 0 { value("CNS", "\(cns) %") }
+ }
+ }
+ .frame(height: 36)
+ } else {
+ Text("Glissez le doigt sur le profil pour lire les valeurs.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .frame(height: 36, alignment: .leading)
+ }
+ }
+
+ private func value(_ title: String, _ text: String, color: Color = .primary) -> some View {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(title).font(.caption2).foregroundStyle(.secondary)
+ Text(text).font(.callout.monospacedDigit().weight(.semibold)).foregroundStyle(color)
+ }
+ }
+
+ private var depthChart: some View {
+ Chart {
+ ForEach(data.depth) { point in
+ AreaMark(x: .value("Temps", point.minute), y: .value("Profondeur", point.value),
+ series: .value("Série", "Profondeur"), stacking: .unstacked)
+ .foregroundStyle(LinearGradient(colors: [Color.accentColor.opacity(0.12), Color.accentColor.opacity(0.5)],
+ startPoint: .top, endPoint: .bottom))
+ .interpolationMethod(.monotone)
+ LineMark(x: .value("Temps", point.minute), y: .value("Profondeur", point.value),
+ series: .value("Série", "Profondeur"))
+ .foregroundStyle(Color.accentColor)
+ .lineStyle(StrokeStyle(lineWidth: 2))
+ .interpolationMethod(.monotone)
+ }
+ ForEach(data.ceiling) { point in
+ AreaMark(x: .value("Temps", point.minute), yStart: .value("Surface", 0.0), yEnd: .value("Plafond", point.value),
+ series: .value("Série", "Plafond"))
+ .foregroundStyle(Color.red.opacity(0.3))
+ .interpolationMethod(.stepEnd)
+ }
+ ForEach(data.markers) { marker in
+ PointMark(x: .value("Temps", marker.minute), y: .value("Profondeur", marker.depth))
+ .symbol(marker.label == nil ? .triangle : .diamond)
+ .symbolSize(60)
+ .foregroundStyle(marker.label == nil ? Color.orange : Color.purple)
+ .annotation(position: .bottom, spacing: 2) {
+ if let label = marker.label {
+ Text(label).font(.caption2.weight(.semibold)).foregroundStyle(.purple)
+ }
+ }
+ }
+ if let selection {
+ RuleMark(x: .value("Temps", selection))
+ .foregroundStyle(Color.secondary.opacity(0.6))
+ .lineStyle(StrokeStyle(lineWidth: 1))
+ if let sample = data.sample(at: selection) {
+ PointMark(x: .value("Temps", Double(sample.time) / 60), y: .value("Profondeur", units.depthValue(sample.depth)))
+ .symbolSize(80)
+ .foregroundStyle(Color.accentColor)
+ }
+ }
+ }
+ .chartXScale(domain: 0...data.maxMinute)
+ .chartYScale(domain: .automatic(includesZero: true, reversed: true))
+ .chartXSelection(value: $selection)
+ .chartLegend(.hidden)
+ .chartXAxis {
+ AxisMarks(values: .automatic(desiredCount: 6)) { value in
+ AxisGridLine()
+ AxisValueLabel {
+ if let minute = value.as(Double.self) { Text("\(Int(minute)) min") }
+ }
+ }
+ }
+ .chartYAxis {
+ AxisMarks(position: .leading, values: .automatic(desiredCount: 5)) { value in
+ AxisGridLine()
+ AxisValueLabel {
+ if let depth = value.as(Double.self) {
+ Text("\(Int(depth)) \(units.depthUnit)").frame(width: axisWidth, alignment: .trailing)
+ }
+ }
+ }
+ }
+ .accessibilityLabel("Profil de la plongée")
+ }
+
+ private func smallChart(title: String, unit: String, series: [ProfileData.Series], color: Color) -> some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title).font(.caption).foregroundStyle(.secondary)
+ Chart {
+ ForEach(series) { serie in
+ ForEach(serie.points) { point in
+ LineMark(x: .value("Temps", point.minute), y: .value(title, point.value), series: .value("Série", serie.id))
+ .foregroundStyle(color)
+ .lineStyle(StrokeStyle(lineWidth: 1.5))
+ }
+ }
+ if let selection {
+ RuleMark(x: .value("Temps", selection))
+ .foregroundStyle(Color.secondary.opacity(0.6))
+ .lineStyle(StrokeStyle(lineWidth: 1))
+ }
+ }
+ .chartXScale(domain: 0...data.maxMinute)
+ .chartYScale(domain: .automatic(includesZero: false))
+ .chartXSelection(value: $selection)
+ .chartLegend(.hidden)
+ .chartXAxis {
+ AxisMarks(values: .automatic(desiredCount: 6)) { _ in AxisGridLine() }
+ }
+ .chartYAxis {
+ AxisMarks(position: .leading, values: .automatic(desiredCount: 3)) { value in
+ AxisGridLine()
+ AxisValueLabel {
+ if let number = value.as(Double.self) {
+ Text("\(Int(number))").frame(width: axisWidth, alignment: .trailing)
+ }
+ }
+ }
+ }
+ .frame(height: 70)
+ .accessibilityLabel("\(title) (\(unit))")
+ }
+ }
+}
diff --git a/App/Views/RootView.swift b/App/Views/RootView.swift
@@ -0,0 +1,41 @@
+import SwiftUI
+
+struct RootView: View {
+ @Environment(AppModel.self) private var model
+ @State private var tab = LaunchOptions.value("-tab") ?? "dives"
+
+ var body: some View {
+ switch model.phase {
+ case .launching:
+ ProgressView()
+ case .signedOut:
+ LoginView()
+ case .ready:
+ TabView(selection: $tab) {
+ DiveListView()
+ .tabItem { Label("Plongées", systemImage: "water.waves") }
+ .tag("dives")
+ SitesView()
+ .tabItem { Label("Lieux", systemImage: "map") }
+ .tag("sites")
+ StatsView()
+ .tabItem { Label("Statistiques", systemImage: "chart.bar") }
+ .tag("stats")
+ SettingsView()
+ .tabItem { Label("Réglages", systemImage: "gearshape") }
+ .tag("settings")
+ }
+ }
+ }
+}
+
+/// Options de lancement pour les captures d'écran : `-demo`, `-tab sites|stats|settings`, `-showDive 11`, `-edit`.
+enum LaunchOptions {
+ static func value(_ name: String) -> String? {
+ let arguments = ProcessInfo.processInfo.arguments
+ guard let index = arguments.firstIndex(of: name), index + 1 < arguments.count else { return nil }
+ return arguments[index + 1]
+ }
+
+ static func flag(_ name: String) -> Bool { ProcessInfo.processInfo.arguments.contains(name) }
+}
diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift
@@ -0,0 +1,94 @@
+import SwiftUI
+
+struct SettingsView: View {
+ @Environment(AppModel.self) private var model
+ @State private var confirmingSignOut = false
+
+ var body: some View {
+ NavigationStack {
+ List {
+ Section("Compte") {
+ if model.isDemo {
+ Label("Carnet de démonstration", systemImage: "sparkles")
+ Text("Les modifications restent sur cet iPhone et disparaissent en quittant la démonstration.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ } else {
+ LabeledContent("Nuage Subsurface", value: model.email)
+ LabeledContent("Dernière synchronisation") {
+ switch model.syncState {
+ case .syncing: ProgressView()
+ default: Text(model.lastSync.map { $0.formatted(.relative(presentation: .named)) } ?? "Jamais")
+ }
+ }
+ if case .failed(let message) = model.syncState {
+ Label(message, systemImage: "exclamationmark.triangle.fill")
+ .font(.footnote)
+ .foregroundStyle(.red)
+ }
+ Button {
+ Task { await model.sync() }
+ } label: {
+ Label("Synchroniser maintenant", systemImage: "arrow.triangle.2.circlepath")
+ }
+ .disabled(model.syncState == .syncing)
+ }
+ }
+
+ if !model.pending.isEmpty {
+ Section("En attente d'envoi") {
+ ForEach(Array(model.pending.enumerated()), id: \.offset) { _, change in
+ Text(change.summary.capitalizedFirst).font(.callout)
+ }
+ }
+ }
+
+ Section("Affichage") {
+ Picker("Unités", selection: Binding(get: { model.units.imperial }, set: { model.setImperial($0) })) {
+ Text("Métriques (m, °C, bar)").tag(false)
+ Text("Impériales (ft, °F, psi)").tag(true)
+ }
+ }
+
+ Section("Carnet") {
+ LabeledContent("Plongées", value: "\(model.logbook.dives.count)")
+ LabeledContent("Lieux", value: "\(model.logbook.sites.count)")
+ LabeledContent("Voyages", value: "\(model.logbook.trips.count)")
+ ForEach(model.logbook.warnings, id: \.self) { warning in
+ Label(warning, systemImage: "exclamationmark.triangle")
+ .font(.footnote)
+ .foregroundStyle(.orange)
+ }
+ }
+
+ Section {
+ LabeledContent("Version", value: Brand.version)
+ Text("\(Brand.name) lit et modifie le carnet que Subsurface garde dans son nuage, dans le même format. C'est une application indépendante, sans lien avec l'équipe de Subsurface. Elle ne remplace ni un ordinateur de plongée ni une formation.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ } header: {
+ Text("À propos")
+ }
+
+ Section {
+ Button(model.isDemo ? "Quitter la démonstration" : "Se déconnecter", role: .destructive) {
+ confirmingSignOut = true
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .navigationTitle("Réglages")
+ .confirmationDialog(model.isDemo ? "Quitter la démonstration ?" : "Se déconnecter ?", isPresented: $confirmingSignOut, titleVisibility: .visible) {
+ Button(model.isDemo ? "Quitter" : "Se déconnecter", role: .destructive) {
+ Task { await model.signOut() }
+ }
+ } message: {
+ if !model.isDemo, !model.pending.isEmpty {
+ Text("Attention : \(model.pending.count) modification(s) pas encore envoyée(s) seront perdues. La copie du carnet sur cet iPhone sera effacée.")
+ } else if !model.isDemo {
+ Text("La copie du carnet sur cet iPhone sera effacée. Rien n'est supprimé dans le nuage.")
+ }
+ }
+ }
+ }
+}
diff --git a/App/Views/SitesView.swift b/App/Views/SitesView.swift
@@ -0,0 +1,186 @@
+import MapKit
+import SubsurfaceLog
+import SwiftUI
+
+struct SitesView: View {
+ @Environment(AppModel.self) private var model
+ @State private var mode = 0
+ @State private var selection: UInt32?
+ @State private var search = ""
+
+ private struct Entry: Identifiable {
+ let site: DiveSite
+ let count: Int
+ var id: UInt32 { site.uuid }
+ }
+
+ private var entries: [Entry] {
+ var counts = [UInt32: Int]()
+ for dive in model.logbook.dives {
+ if let uuid = dive.siteUUID { counts[uuid, default: 0] += 1 }
+ }
+ return model.logbook.sites.values
+ .filter { !$0.name.isEmpty || $0.hasLocation }
+ .map { Entry(site: $0, count: counts[$0.uuid] ?? 0) }
+ .sorted { $0.site.name.localizedCaseInsensitiveCompare($1.site.name) == .orderedAscending }
+ }
+
+ var body: some View {
+ NavigationStack {
+ let all = entries
+ Group {
+ if mode == 0 {
+ map(all.filter { $0.site.hasLocation })
+ } else {
+ list(all)
+ }
+ }
+ .navigationTitle("Lieux")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .principal) {
+ Picker("Affichage", selection: $mode) {
+ Text("Carte").tag(0)
+ Text("Liste").tag(1)
+ }
+ .pickerStyle(.segmented)
+ .frame(width: 180)
+ }
+ }
+ .navigationDestination(for: UInt32.self) { SiteDetailView(uuid: $0) }
+ .navigationDestination(for: String.self) { DiveDetailView(diveID: $0) }
+ }
+ }
+
+ private func map(_ located: [Entry]) -> some View {
+ Map(selection: $selection) {
+ ForEach(located) { entry in
+ Marker(entry.site.name, systemImage: "water.waves",
+ coordinate: CLLocationCoordinate2D(latitude: entry.site.latitude ?? 0, longitude: entry.site.longitude ?? 0))
+ .tint(Color.accentColor)
+ .tag(entry.site.uuid)
+ }
+ }
+ .mapStyle(.hybrid(elevation: .flat))
+ .overlay {
+ if located.isEmpty {
+ ContentUnavailableView("Aucun lieu avec position", systemImage: "mappin.slash",
+ description: Text("Les lieux de plongée situés dans Subsurface apparaîtront ici."))
+ .background(.regularMaterial)
+ }
+ }
+ .safeAreaInset(edge: .bottom) {
+ if let selection, let entry = located.first(where: { $0.site.uuid == selection }) {
+ NavigationLink(value: entry.site.uuid) {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(entry.site.name).font(.headline).foregroundStyle(Color.primary)
+ Text(countLabel(entry.count)).font(.caption).foregroundStyle(.secondary)
+ }
+ Spacer()
+ Image(systemName: "chevron.right").foregroundStyle(.secondary)
+ }
+ .padding()
+ .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .padding(.horizontal)
+ .padding(.bottom, 8)
+ }
+ }
+ }
+ }
+
+ private func list(_ all: [Entry]) -> some View {
+ let shown = search.isEmpty ? all : all.filter {
+ $0.site.name.localizedCaseInsensitiveContains(search) || ($0.site.country ?? "").localizedCaseInsensitiveContains(search)
+ }
+ return List(shown) { entry in
+ NavigationLink(value: entry.site.uuid) {
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(entry.site.name.isEmpty ? "Lieu sans nom" : entry.site.name)
+ if let country = entry.site.country {
+ Text(country).font(.caption).foregroundStyle(.secondary)
+ }
+ }
+ Spacer()
+ Text("\(entry.count)")
+ .font(.callout.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ .searchable(text: $search, prompt: "Chercher un lieu")
+ .overlay {
+ if all.isEmpty { ContentUnavailableView("Aucun lieu", systemImage: "map") }
+ }
+ }
+
+ private func countLabel(_ count: Int) -> String {
+ count == 0 ? "Aucune plongée" : (count == 1 ? "1 plongée" : "\(count) plongées")
+ }
+}
+
+struct SiteDetailView: View {
+ @Environment(AppModel.self) private var model
+ let uuid: UInt32
+
+ var body: some View {
+ let site = model.logbook.sites[uuid]
+ let dives = model.logbook.dives.filter { $0.siteUUID == uuid }
+ List {
+ if let site, let latitude = site.latitude, let longitude = site.longitude {
+ Section {
+ let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
+ Map(initialPosition: .region(MKCoordinateRegion(center: coordinate, latitudinalMeters: 8000, longitudinalMeters: 8000))) {
+ Marker(site.name, systemImage: "water.waves", coordinate: coordinate).tint(Color.accentColor)
+ }
+ .mapStyle(.hybrid(elevation: .flat))
+ .frame(height: 220)
+ .listRowInsets(EdgeInsets())
+ LabeledContent("Position", value: String(format: "%.5f, %.5f", latitude, longitude))
+ .textSelection(.enabled)
+ Button {
+ let item = MKMapItem(placemark: MKPlacemark(coordinate: coordinate))
+ item.name = site.name
+ item.openInMaps()
+ } label: {
+ Label("Ouvrir dans Plans", systemImage: "arrow.triangle.turn.up.right.diamond")
+ }
+ }
+ }
+ if let site, !site.description.isEmpty || !site.notes.isEmpty || site.country != nil {
+ Section("À propos") {
+ if let country = site.country { LabeledContent("Pays", value: country) }
+ if !site.description.isEmpty { Text(site.description) }
+ if !site.notes.isEmpty { Text(site.notes).foregroundStyle(.secondary) }
+ }
+ }
+ if !dives.isEmpty {
+ Section("Résumé") {
+ LabeledContent("Plongées", value: "\(dives.count)")
+ LabeledContent("Plus profonde", value: model.units.depth(dives.map(\.maxDepth).max() ?? 0))
+ LabeledContent("Temps passé", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }))
+ }
+ Section("Plongées") {
+ ForEach(dives) { dive in
+ NavigationLink(value: dive.id) {
+ HStack {
+ Text(dive.number > 0 ? "\(dive.number)" : "–")
+ .font(.footnote.monospacedDigit().weight(.semibold))
+ .frame(minWidth: 30, alignment: .leading)
+ .foregroundStyle(Color.accentColor)
+ Text(DiveDate.day(dive))
+ Spacer()
+ Text("\(model.units.depth(dive.maxDepth)) · \(Units.duration(dive.durationSeconds))")
+ .font(.callout.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+ }
+ }
+ .navigationTitle(site?.name ?? "Lieu")
+ .navigationBarTitleDisplayMode(.inline)
+ }
+}
diff --git a/App/Views/StatsView.swift b/App/Views/StatsView.swift
@@ -0,0 +1,124 @@
+import Charts
+import SubsurfaceLog
+import SwiftUI
+
+struct StatsView: View {
+ @Environment(AppModel.self) private var model
+
+ private struct Bucket: Identifiable {
+ let id: String
+ let count: Int
+ }
+
+ var body: some View {
+ NavigationStack {
+ let dives = model.logbook.dives.filter { !$0.invalid }
+ let units = model.units
+ List {
+ if dives.isEmpty {
+ ContentUnavailableView("Pas encore de statistiques", systemImage: "chart.bar",
+ description: Text("Elles apparaîtront avec vos premières plongées."))
+ } else {
+ Section {
+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 2), spacing: 8) {
+ Figure(title: "Plongées", value: "\(dives.count)", icon: "number")
+ Figure(title: "Temps sous l'eau", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }), icon: "clock")
+ Figure(title: "Plus profonde", value: units.depth(dives.map(\.maxDepth).max() ?? 0), icon: "arrow.down.to.line")
+ Figure(title: "Plus longue", value: Units.duration(dives.map(\.durationSeconds).max() ?? 0), icon: "hourglass")
+ Figure(title: "Profondeur moyenne", value: units.depth(dives.map(\.maxDepth).reduce(0, +) / Double(dives.count)), icon: "arrow.up.and.down")
+ Figure(title: "Durée moyenne", value: Units.duration(dives.reduce(0) { $0 + $1.durationSeconds } / dives.count), icon: "timer")
+ if let cold = dives.compactMap(\.waterTemperature).min(), let warm = dives.compactMap(\.waterTemperature).max() {
+ Figure(title: "Eau la plus froide", value: units.temperature(cold), icon: "snowflake")
+ Figure(title: "Eau la plus chaude", value: units.temperature(warm), icon: "sun.max")
+ }
+ let sacs = dives.compactMap(\.sac)
+ if !sacs.isEmpty {
+ Figure(title: "Conso. moyenne", value: units.sac(sacs.reduce(0, +) / Double(sacs.count)), icon: "lungs")
+ }
+ Figure(title: "Lieux visités", value: "\(Set(dives.compactMap(\.siteUUID)).count)", icon: "mappin.and.ellipse")
+ }
+ .listRowSeparator(.hidden)
+ }
+
+ Section("Plongées par année") {
+ let years = Dictionary(grouping: dives, by: { DiveDate.year($0.when) })
+ .map { Bucket(id: String($0.key), count: $0.value.count) }
+ .sorted { $0.id < $1.id }
+ Chart(years) { bucket in
+ BarMark(x: .value("Année", bucket.id), y: .value("Plongées", bucket.count))
+ .foregroundStyle(Color.accentColor.gradient)
+ .annotation(position: .top) {
+ Text("\(bucket.count)").font(.caption2).foregroundStyle(.secondary)
+ }
+ }
+ .frame(height: 170)
+ .padding(.vertical, 6)
+ }
+
+ Section("Profondeur maximale") {
+ let step = units.imperial ? 30.0 : 10.0
+ let grouped = Dictionary(grouping: dives, by: { Int(units.depthValue($0.maxDepth) / step) })
+ let buckets = (0...(grouped.keys.max() ?? 0)).map { index in
+ Bucket(id: "\(Int(Double(index) * step))–\(Int(Double(index + 1) * step))", count: grouped[index]?.count ?? 0)
+ }
+ Chart(buckets) { bucket in
+ BarMark(x: .value("Plongées", bucket.count), y: .value("Profondeur (\(units.depthUnit))", bucket.id))
+ .foregroundStyle(Color.accentColor.gradient)
+ .annotation(position: .trailing) {
+ if bucket.count > 0 { Text("\(bucket.count)").font(.caption2).foregroundStyle(.secondary) }
+ }
+ }
+ .frame(height: CGFloat(max(buckets.count, 2)) * 30)
+ .padding(.vertical, 6)
+ }
+
+ Section("Gaz") {
+ let gases = Dictionary(grouping: dives.filter { !$0.cylinders.isEmpty }, by: { gasFamily($0) })
+ ForEach(gases.keys.sorted(), id: \.self) { family in
+ LabeledContent(family, value: "\(gases[family]?.count ?? 0)")
+ }
+ }
+
+ Section("Lieux les plus plongés") {
+ let bySite = Dictionary(grouping: dives.filter { $0.siteUUID != nil }, by: { $0.siteUUID! })
+ .map { (name: model.logbook.sites[$0.key]?.name ?? "", count: $0.value.count) }
+ .filter { !$0.name.isEmpty }
+ .sorted { ($0.count, $1.name) > ($1.count, $0.name) }
+ .prefix(8)
+ ForEach(Array(bySite), id: \.name) { entry in
+ LabeledContent(entry.name, value: "\(entry.count)")
+ }
+ }
+
+ let buddies = topBuddies(dives)
+ if !buddies.isEmpty {
+ Section("Binômes") {
+ ForEach(buddies, id: \.name) { entry in
+ LabeledContent(entry.name, value: "\(entry.count)")
+ }
+ }
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .navigationTitle("Statistiques")
+ }
+ }
+
+ private func gasFamily(_ dive: Dive) -> String {
+ let used = dive.cylinders.filter { $0.use != "not used" }
+ if used.contains(where: { $0.gas.hePermille > 0 }) { return "Trimix" }
+ if used.contains(where: { !$0.gas.isAir }) { return "Nitrox" }
+ return "Air"
+ }
+
+ private func topBuddies(_ dives: [Dive]) -> [(name: String, count: Int)] {
+ var counts = [String: Int]()
+ for dive in dives {
+ for name in dive.buddy.split(separator: ",").map({ $0.trimmingCharacters(in: .whitespaces) }) where !name.isEmpty {
+ counts[name, default: 0] += 1
+ }
+ }
+ return counts.map { (name: $0.key, count: $0.value) }.sorted { ($0.count, $1.name) > ($1.count, $0.name) }.prefix(8).map { $0 }
+ }
+}
diff --git a/Makefile b/Makefile
@@ -1,7 +1,7 @@
# Le code vit ici (hotrats) ; Swift et Xcode tournent sur chunga.
CHUNGA ?= chunga
-REMOTE ?= src/perso/open-surfclam
-DEST ?= platform=iOS Simulator,name=iPhone 17 Pro
+REMOTE ?= src/perso/divelog
+DEST ?= platform=iOS Simulator,name=DiveLog test iPhone
.PHONY: sync test-kit project build test
@@ -16,7 +16,20 @@ project: sync
ssh $(CHUNGA) 'cd $(REMOTE) && xcodegen -q'
build: project
- ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenSurfclam -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO build'
+ ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme DiveLog -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO build'
test: project
- ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenSurfclam -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO test'
+ ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme DiveLog -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO test'
+
+# Lance l'app dans le simulateur avec le carnet de démonstration et prend une capture.
+# ARGS = options de lancement (voir LaunchOptions), SHOT = nom de la capture, WAIT = délai avant la capture.
+SIM ?= DiveLog test iPhone
+ARGS ?=
+DEMO ?= -demo
+SHOT ?= shot
+WAIT ?= 4
+APP_ID = org.schurger.subrascasse
+.PHONY: shot
+shot:
+ @ssh $(CHUNGA) 'cd $(REMOTE) && xcrun simctl bootstatus "$(SIM)" -b >/dev/null && xcrun simctl install "$(SIM)" build/Build/Products/Debug-iphonesimulator/DiveLog.app && (xcrun simctl terminate "$(SIM)" $(APP_ID) 2>/dev/null; true) && xcrun simctl launch "$(SIM)" $(APP_ID) $(DEMO) -AppleLanguages "(fr)" -AppleLocale fr_CA $(ARGS) >/dev/null && sleep $(WAIT) && mkdir -p build/shots && xcrun simctl io "$(SIM)" screenshot build/shots/$(SHOT).png 2>/dev/null && sips -Z 1100 build/shots/$(SHOT).png --out build/shots/$(SHOT)-small.png >/dev/null'
+ @mkdir -p build/shots && scp -q $(CHUNGA):$(REMOTE)/build/shots/$(SHOT)-small.png build/shots/$(SHOT).png
diff --git a/Packages/DiveKit/Sources/GitLite/Client.swift b/Packages/DiveKit/Sources/GitLite/Client.swift
@@ -52,7 +52,7 @@ public struct HTTPTransport: GitTransport {
public let userAgent: String
public let session: URLSession
- public init(baseURL: URL, username: String, password: String, userAgent: String = "git/2.0 (open-surfclam)", session: URLSession? = nil) {
+ public init(baseURL: URL, username: String, password: String, userAgent: String = "git/2.0 (divelog)", session: URLSession? = nil) {
self.baseURL = baseURL
self.username = username
self.password = password
@@ -123,7 +123,7 @@ public struct RemoteRefs: Sendable {
public struct GitClient: Sendable {
public let transport: GitTransport
public let store: ObjectStore
- public var agent = "open-surfclam/0.1"
+ public var agent = "divelog/0.1"
public init(transport: GitTransport, store: ObjectStore) {
self.transport = transport
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift
@@ -6,7 +6,7 @@ import GitTestSupport
final class SubsurfaceLogTests: XCTestCase {
private func repository(_ name: String = "local") throws -> LogRepository {
try LogRepository(directory: try LocalGit.temporaryDirectory(name), branch: Fixture.branch,
- authorName: "Open Surfclam", authorEmail: Fixture.branch)
+ authorName: "DiveLog", authorEmail: Fixture.branch)
}
// MARK: Format
@@ -180,7 +180,7 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertEqual(try remote.text(["log", "--format=%s", Fixture.branch]), "carnet de test")
// Une autre instance rouvre la même copie locale : la file d'attente a survécu.
- let reopened = try LogRepository(directory: repo.directory, branch: Fixture.branch, authorName: "Open Surfclam", authorEmail: Fixture.branch)
+ let reopened = try LogRepository(directory: repo.directory, branch: Fixture.branch, authorName: "DiveLog", authorEmail: Fixture.branch)
let pendingCount = await reopened.pending.count
XCTAssertEqual(pendingCount, 4)
@@ -343,6 +343,18 @@ final class SubsurfaceLogTests: XCTestCase {
print("\(log.dives.count) plongées, \(log.sites.count) lieux, \(log.trips.count) voyages, \(samples) échantillons")
}
+ /// Une seule requête au vrai nuage, avec un compte qui n'existe pas (CLOUD_TEST=1) : il doit refuser proprement.
+ func testCloudRejectsUnknownAccount() async throws {
+ guard ProcessInfo.processInfo.environment["CLOUD_TEST"] == "1" else { throw XCTSkip("CLOUD_TEST non défini") }
+ let transport = SubsurfaceCloud.transport(email: "nobody@example.com", password: "invalide")
+ do {
+ _ = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
+ XCTFail("le nuage aurait dû refuser")
+ } catch let error as GitError {
+ XCTAssertEqual(error, .unauthorized)
+ }
+ }
+
func testCloudAddresses() {
XCTAssertEqual(SubsurfaceCloud.sanitize(email: " Jean.Test+plongee@Example.com\n"), "jean.test+plongee@example.com")
XCTAssertEqual(SubsurfaceCloud.repositoryURL(email: "Jean@Example.com").absoluteString,
diff --git a/README.md b/README.md
@@ -0,0 +1,45 @@
+# Subrascasse
+
+App iPhone pour le carnet de plongée de [Subsurface](https://subsurface-divelog.org) : elle lit et modifie le carnet
+gardé dans le nuage Subsurface, dans le même format, sans passer par l'app officielle. Application indépendante,
+sans lien avec l'équipe de Subsurface.
+
+## Ce qui marche (0.1)
+
+- Connexion au nuage Subsurface (courriel + mot de passe, gardé dans le trousseau), carnet copié sur l'iPhone.
+- Liste par voyage ou par mois, recherche, fiche de plongée avec profil (profondeur, température, pression,
+ paliers, événements, lecture au doigt), plusieurs ordinateurs par plongée.
+- Modification hors ligne : lieu, binôme, guide, combinaison, étiquettes, évaluation, visibilité, notes ;
+ ajout d'une plongée à la main, création d'un lieu, suppression. Envoi à la synchronisation suivante.
+- Carte et liste des lieux, statistiques, unités métriques ou impériales.
+- Carnet de démonstration (bouton sur l'écran de connexion, ou option de lancement `-demo`).
+
+Pas encore : téléchargement depuis un ordinateur de plongée, création de compte, photos, planificateur, anglais.
+
+## Organisation
+
+- `Packages/DiveKit/Sources/GitLite` : client git en Swift pur (objets, paquets, protocole « smart HTTP »,
+ récupération superficielle et incrémentale, envoi). Aucune dépendance binaire.
+- `Packages/DiveKit/Sources/SubsurfaceLog` : format de stockage git de Subsurface (`Loader`), modifications
+ (`Changes` : seules les lignes touchées d'un fichier sont réécrites, le reste est conservé à l'octet près),
+ synchronisation (`Repository` : les modifications en attente se rejouent sur l'état du serveur).
+- `App` : interface SwiftUI. Le nom affiché et l'identifiant ne vivent que dans `project.yml` et `App/Brand.swift`.
+
+Le format a été écrit d'après les sources de Subsurface (`core/save-git.cpp`, `core/load-git.cpp`, GPL-2.0),
+https://github.com/subsurface/subsurface, et validé sur deux carnets publics :
+https://github.com/Egbertdepauw/anchorline (vrais exports) et https://github.com/Ventrilok/divelens.
+
+## Travailler dessus
+
+Le code vit sur hotrats, Swift et Xcode tournent sur chunga.
+
+ make test-kit # tests du paquet (contre le vrai git en ligne de commande)
+ make build # app pour le simulateur
+ make shot SHOT=liste # capture avec le carnet de démonstration (build/shots/)
+ make shot SHOT=fiche ARGS="-showDive 11"
+
+Options de lancement : `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`,
+`-newDive`, `-demoChanges`.
+
+Valider sur un vrai carnet : `SUBSURFACE_TREE=/chemin/arbre swift test --filter testExternalTree` (dossier
+disposé comme l'arbre git : `00-Subsurface`, `01-Divesites/`, `aaaa/mm/…`).
diff --git a/project.yml b/project.yml
@@ -0,0 +1,53 @@
+# Projet Xcode généré par XcodeGen (`xcodegen` sur chunga) : modifier ce fichier, pas le .xcodeproj.
+# Le nom affiché « Subrascasse » n'apparaît qu'ici (nom affiché, identifiant) et dans App/Brand.swift.
+name: DiveLog
+options:
+ bundleIdPrefix: org.schurger
+ developmentLanguage: fr
+ deploymentTarget:
+ iOS: "17.0"
+packages:
+ DiveKit:
+ path: Packages/DiveKit
+settings:
+ base:
+ DEVELOPMENT_TEAM: CM5RQKJH56
+ CODE_SIGN_STYLE: Automatic
+ MARKETING_VERSION: "0.1"
+ CURRENT_PROJECT_VERSION: "1"
+ SWIFT_VERSION: "5.0"
+targets:
+ DiveLog:
+ type: application
+ platform: iOS
+ sources:
+ - path: App
+ dependencies:
+ - package: DiveKit
+ product: GitLite
+ - package: DiveKit
+ product: SubsurfaceLog
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: org.schurger.subrascasse
+ PRODUCT_NAME: DiveLog
+ TARGETED_DEVICE_FAMILY: "1"
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME: AccentColor
+ SUPPORTS_MACCATALYST: NO
+ SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD: NO
+ info:
+ path: App/Info.plist
+ properties:
+ CFBundleDisplayName: Subrascasse
+ CFBundleShortVersionString: $(MARKETING_VERSION)
+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
+ CFBundleLocalizations: [fr, en]
+ ITSAppUsesNonExemptEncryption: false
+ UILaunchScreen: {}
+ UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight]
+schemes:
+ DiveLog:
+ build:
+ targets:
+ DiveLog: all
diff --git a/tools/make-icon.swift b/tools/make-icon.swift
@@ -0,0 +1,121 @@
+// Génère l'icône 1024×1024 (sans transparence) : swift tools/make-icon.swift chemin.png
+// Une rascasse juste sous la surface.
+import CoreGraphics
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+
+let size = 1024.0
+let out = CommandLine.arguments[1]
+let ctx = CGContext(data: nil, width: Int(size), height: Int(size), bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
+
+func rgb(_ r: Double, _ g: Double, _ b: Double, _ a: Double = 1) -> CGColor {
+ CGColor(red: r / 255, green: g / 255, blue: b / 255, alpha: a)
+}
+let space = CGColorSpaceCreateDeviceRGB()
+
+// Eau : du bleu profond (bas) au turquoise (haut).
+let water = CGGradient(colorsSpace: space, colors: [rgb(6, 40, 92), rgb(8, 104, 150), rgb(64, 190, 205)] as CFArray, locations: [0, 0.6, 1])!
+ctx.drawLinearGradient(water, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size), options: [])
+
+// Surface : une vague claire en haut.
+ctx.setFillColor(rgb(214, 244, 250))
+ctx.move(to: CGPoint(x: 0, y: size))
+ctx.addLine(to: CGPoint(x: 0, y: 850))
+ctx.addCurve(to: CGPoint(x: 512, y: 850), control1: CGPoint(x: 170, y: 910), control2: CGPoint(x: 340, y: 790))
+ctx.addCurve(to: CGPoint(x: 1024, y: 850), control1: CGPoint(x: 684, y: 910), control2: CGPoint(x: 854, y: 790))
+ctx.addLine(to: CGPoint(x: 1024, y: size))
+ctx.fillPath()
+
+// Sable au fond.
+ctx.setFillColor(rgb(232, 204, 150))
+ctx.move(to: CGPoint(x: 0, y: 0))
+ctx.addLine(to: CGPoint(x: 0, y: 170))
+ctx.addCurve(to: CGPoint(x: 1024, y: 150), control1: CGPoint(x: 340, y: 240), control2: CGPoint(x: 700, y: 110))
+ctx.addLine(to: CGPoint(x: 1024, y: 0))
+ctx.fillPath()
+
+// Rascasse : corps trapu rouge orangé, grosse tête, dorsale épineuse, air bougon mais sympathique.
+let red = rgb(226, 78, 52), deep = rgb(150, 40, 36), light = rgb(255, 170, 110), belly = rgb(255, 214, 170)
+// Queue.
+ctx.setFillColor(red)
+ctx.move(to: CGPoint(x: 300, y: 450))
+ctx.addCurve(to: CGPoint(x: 120, y: 610), control1: CGPoint(x: 230, y: 500), control2: CGPoint(x: 150, y: 560))
+ctx.addCurve(to: CGPoint(x: 130, y: 300), control1: CGPoint(x: 190, y: 500), control2: CGPoint(x: 190, y: 410))
+ctx.addCurve(to: CGPoint(x: 300, y: 450), control1: CGPoint(x: 170, y: 350), control2: CGPoint(x: 240, y: 410))
+ctx.fillPath()
+// Dorsale épineuse : une rangée de piquants reliés par une membrane.
+let spines: [(Double, Double)] = [(330, 640), (390, 760), (450, 650), (520, 790), (585, 660), (650, 770), (705, 640), (760, 700)]
+ctx.setFillColor(light)
+ctx.move(to: CGPoint(x: 300, y: 560))
+for (x, y) in spines { ctx.addLine(to: CGPoint(x: x, y: y)) }
+ctx.addLine(to: CGPoint(x: 800, y: 560))
+ctx.fillPath()
+ctx.setStrokeColor(deep)
+ctx.setLineWidth(12)
+ctx.setLineCap(.round)
+for (x, y) in spines where y > 690 {
+ ctx.move(to: CGPoint(x: x, y: y)); ctx.addLine(to: CGPoint(x: x - 10, y: 580)); ctx.strokePath()
+}
+// Corps.
+ctx.saveGState()
+let bodyRect = CGRect(x: 240, y: 280, width: 640, height: 400)
+ctx.addEllipse(in: bodyRect)
+ctx.clip()
+let scales = CGGradient(colorsSpace: space, colors: [belly, light, red, deep] as CFArray, locations: [0, 0.25, 0.6, 1])!
+ctx.drawLinearGradient(scales, start: CGPoint(x: 0, y: 280), end: CGPoint(x: 0, y: 700), options: [])
+// Marbrures.
+ctx.setFillColor(rgb(150, 40, 36, 0.45))
+for (x, y, r) in [(380.0, 560.0, 34.0), (470, 610, 26), (460, 500, 30), (560, 570, 28), (350, 470, 22), (620, 620, 20), (540, 470, 18)] {
+ ctx.fillEllipse(in: CGRect(x: x - r, y: y - r * 0.8, width: 2 * r, height: 1.6 * r))
+}
+ctx.restoreGState()
+ctx.setStrokeColor(deep)
+ctx.setLineWidth(14)
+ctx.strokeEllipse(in: bodyRect)
+// Pectorale en éventail.
+ctx.setFillColor(light)
+ctx.move(to: CGPoint(x: 560, y: 430))
+ctx.addCurve(to: CGPoint(x: 430, y: 300), control1: CGPoint(x: 500, y: 410), control2: CGPoint(x: 440, y: 360))
+ctx.addCurve(to: CGPoint(x: 600, y: 330), control1: CGPoint(x: 480, y: 270), control2: CGPoint(x: 560, y: 280))
+ctx.closePath()
+ctx.fillPath()
+ctx.setStrokeColor(deep)
+ctx.setLineWidth(10)
+for (x, y) in [(450.0, 310.0), (500, 300), (550, 310)] {
+ ctx.move(to: CGPoint(x: 560, y: 420)); ctx.addLine(to: CGPoint(x: x, y: y)); ctx.strokePath()
+}
+// Gros œil, sourcil épineux, joue rose.
+ctx.setFillColor(rgb(255, 255, 255))
+ctx.fillEllipse(in: CGRect(x: 690, y: 500, width: 120, height: 130))
+ctx.setFillColor(rgb(30, 30, 50))
+ctx.fillEllipse(in: CGRect(x: 730, y: 522, width: 66, height: 78))
+ctx.setFillColor(rgb(255, 255, 255))
+ctx.fillEllipse(in: CGRect(x: 764, y: 566, width: 24, height: 24))
+ctx.setStrokeColor(deep)
+ctx.setLineWidth(16)
+ctx.move(to: CGPoint(x: 680, y: 640)); ctx.addLine(to: CGPoint(x: 820, y: 622)); ctx.strokePath()
+ctx.setFillColor(rgb(255, 150, 160, 0.7))
+ctx.fillEllipse(in: CGRect(x: 690, y: 420, width: 70, height: 40))
+// Grande bouche, un rien boudeuse.
+ctx.setStrokeColor(deep)
+ctx.setLineWidth(16)
+ctx.move(to: CGPoint(x: 800, y: 420))
+ctx.addQuadCurve(to: CGPoint(x: 878, y: 440), control: CGPoint(x: 840, y: 450))
+ctx.strokePath()
+
+// Bulles qui montent vers la surface.
+ctx.setStrokeColor(rgb(255, 255, 255, 0.85))
+ctx.setLineWidth(8)
+for (x, y, r) in [(900.0, 560.0, 26.0), (930, 670, 18), (905, 760, 12), (200, 700, 20), (160, 780, 13)] {
+ ctx.setFillColor(rgb(255, 255, 255, 0.18))
+ ctx.fillEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
+ ctx.strokeEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
+}
+
+let image = ctx.makeImage()!
+let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: out) as CFURL, UTType.png.identifier as CFString, 1, nil)!
+CGImageDestinationAddImage(dest, image, nil)
+CGImageDestinationFinalize(dest)