subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

commit 63204ede9da9be73bfbb07511055dee1da7303d7
parent 3cfd0cb10b0fe0140ff6623dc5f6ce4c6210f870
Author: Jean Schurger <jean@schurger.org>
Date:   Sun, 15 Nov 2026 22:09:20 -0500

UDDF import and export; planner screens for what was ported

- UDDF 3.2: reading (profile, gases and switches, stops, site, buddies,
  notes; universal times brought back to local time) and writing (whole
  logbook or one dive). The importer recognises .uddf files; Settings and the
  dive page export through the Files app.
- Planner: recreational model, date of the plan and the earlier dives of the
  logbook (within 48 hours), another setpoint for a closed-circuit ascent,
  EN 13319 water, time shown at the surface, stops in feet with imperial
  units.
- French strings, README, version 0.10.

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

Diffstat:
MApp/Localizable.xcstrings | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
MApp/Model/AppModel.swift | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
MApp/Views/DiveDetailView.swift | 4++++
MApp/Views/ImportView.swift | 56+++++++++++++++++++++++++++++++++++++++++++++++++++++++-
MApp/Views/SettingsView.swift | 6++++++
MApp/Views/TechPlanView.swift | 83++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
MPackages/DiveKit/Sources/SubsurfaceLog/Import.swift | 5+++++
MPackages/DiveKit/Sources/SubsurfaceLog/Repository.swift | 9+++++++++
APackages/DiveKit/Sources/SubsurfaceLog/UDDF.swift | 356+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MPackages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MREADME.md | 8++++++--
Mfastlane/Fastfile | 4++--
Mproject.yml | 2+-
13 files changed, 814 insertions(+), 20 deletions(-)

diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings @@ -41,6 +41,16 @@ } } }, + "%@ before": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ avant" + } + } + } + }, "%@ for %@ min on %@": { "localizations": { "fr": { @@ -691,6 +701,16 @@ } } }, + "Another setpoint for the ascent": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autre point de consigne pour la remontée" + } + } + } + }, "Answer": { "localizations": { "fr": { @@ -941,6 +961,26 @@ } } }, + "Bottom time extended by %@ min: the longest this dive can be without stops, with the gas there is.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Temps de fond prolongé de %@ min : le plus long que cette plongée peut durer sans palier, avec le gaz disponible." + } + } + } + }, + "Bottom time extended by %lld min: the longest this dive can be without stops, with the gas there is.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Temps de fond prolongé de %lld min : le plus long que cette plongée peut durer sans palier, avec le gaz disponible." + } + } + } + }, "Breaks during oxygen stops": { "localizations": { "fr": { @@ -1411,6 +1451,16 @@ } } }, + "Count my earlier dives": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Compter mes plongées précédentes" + } + } + } + }, "Country": { "localizations": { "fr": { @@ -1501,6 +1551,16 @@ } } }, + "Date": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Date" + } + } + } + }, "Date issued": { "localizations": { "fr": { @@ -2201,12 +2261,32 @@ } } }, - "File format not recognized. Supported formats: Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).": { + "Export as UDDF…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Exporter en UDDF…" + } + } + } + }, + "Export failed": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Échec de l'export" + } + } + } + }, + "File format not recognized. Supported formats: UDDF (.uddf), Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).": { "localizations": { "fr": { "stringUnit": { "state": "translated", - "value": "Format de fichier non reconnu. Formats acceptés : export Shearwater Cloud (.zip ou dive_data.db) et base de Dive Shearwater (watermelon.db)." + "value": "Format de fichier non reconnu. Formats acceptés : UDDF (.uddf), export Shearwater Cloud (.zip ou dive_data.db) et base de Dive Shearwater (watermelon.db)." } } } @@ -2281,6 +2361,16 @@ } } }, + "From": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "À partir de" + } + } + } + }, "Front": { "localizations": { "fr": { @@ -3101,6 +3191,16 @@ } } }, + "No dive of the logbook in the 48 hours before.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune plongée du carnet dans les 48 heures précédentes." + } + } + } + }, "No dives": { "localizations": { "fr": { @@ -3261,6 +3361,16 @@ } } }, + "No-stop diving: the bottom time is extended as far as a direct ascent stays allowed and the gas lasts, reserve kept.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plongée sans palier : le temps de fond est prolongé tant qu'une remontée directe reste permise et que le gaz suffit, réserve gardée." + } + } + } + }, "No-stop time": { "localizations": { "fr": { @@ -3711,6 +3821,16 @@ } } }, + "Recreational": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Loisir" + } + } + } + }, "Refresher dive, sea fans everywhere.": { "localizations": { "fr": { @@ -4711,6 +4831,16 @@ } } }, + "The dives of the logbook that ended less than 48 hours before this date leave gas in the tissues: the plan starts from there.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les plongées du carnet terminées moins de 48 heures avant cette date laissent du gaz dans les tissus : le plan part de là." + } + } + } + }, "The download failed.": { "localizations": { "fr": { @@ -4881,6 +5011,16 @@ } } }, + "This dive needs decompression stops: it is beyond the no-stop limit of the recreational mode.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette plongée demande des paliers : elle dépasse la limite sans palier du mode loisir." + } + } + } + }, "This email is not valid.": { "localizations": { "fr": { @@ -4911,6 +5051,16 @@ } } }, + "Time shown at the surface": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Temps affiché en surface" + } + } + } + }, "Time spent": { "localizations": { "fr": { diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only import Foundation +import DivePlanner import GitLite import Observation import Photos @@ -339,7 +340,7 @@ final class AppModel { if let importError = error as? ImportError { switch importError { case .unknownFormat: - return String(localized: "File format not recognized. Supported formats: Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).") + return String(localized: "File format not recognized. Supported formats: UDDF (.uddf), Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).") case .unreadable(let why): return String(localized: "Couldn't read the file: \(why)") case .empty: return String(localized: "No dives in this file.") } @@ -624,6 +625,63 @@ final class AppModel { } } + /// A dive of the logbook that still counts for a plan: how long before the plan it ended, and its profile. + struct EarlierDive: Identifiable { + let id: String + let title: String + /// Seconds between the end of the dive and the start of the plan. + let interval: Int + let prior: PriorDive + } + + /// The dives of the logbook that ended less than 48 hours before `date`, oldest first, with their profiles. + func earlierDives(before date: Date) async -> [EarlierDive] { + let start = DiveDate.naive(from: date) + let candidates = logbook.dives.filter { $0.when < start && $0.when + $0.durationSeconds > start - 48 * 3600 }.sorted { $0.when < $1.when } + var found = [EarlierDive]() + for (index, dive) in candidates.enumerated() { + func gas(_ mix: GasMix) -> BreathingGas { BreathingGas(o2: mix.o2Fraction, he: mix.heFraction) } + let first = dive.cylinders.first.map { gas($0.gas) } ?? .air + let computer = await profile(of: dive).first + var samples = [PriorDive.Sample]() + if let computer, computer.samples.count > 1 { + let changes = computer.events.filter(\.isGasChange).sorted { $0.time < $1.time } + for sample in computer.samples { + var breathed = first + if let change = changes.last(where: { $0.time <= sample.time }) { + if let mix = change.gas { + breathed = gas(mix) + } else if let cylinder = change.cylinder, dive.cylinders.indices.contains(cylinder) { + breathed = gas(dive.cylinders[cylinder].gas) + } + } + samples.append(PriorDive.Sample(time: Double(sample.time), depth: sample.depth, gas: breathed)) + } + } else { + // No profile: a square dive at the maximum depth. + let duration = Double(max(dive.durationSeconds, 120)) + samples = [PriorDive.Sample(time: 0, depth: 0, gas: first), PriorDive.Sample(time: 60, depth: dive.maxDepth, gas: first), + PriorDive.Sample(time: duration - 60, depth: dive.maxDepth, gas: first), PriorDive.Sample(time: duration, depth: 0, gas: first)] + } + let end = dive.when + max(dive.durationSeconds, Int(samples.last?.time ?? 0)) + let next = index + 1 < candidates.count ? candidates[index + 1].when : start + let number = dive.number > 0 ? String(localized: "Dive \(dive.number)") : String(localized: "Dive") + found.append(EarlierDive(id: dive.id, title: "\(number) · \(siteName(of: dive))", interval: max(0, start - end), + prior: PriorDive(samples: samples, surfaceInterval: Double(max(0, next - end))))) + } + return found + } + + /// The logbook, or some of its dives, as a UDDF document. + func uddf(dives: [Dive]? = nil) async throws -> String { + guard let repository else { return "" } + do { + return try await repository.uddf(dives: dives, generator: Brand.name, version: Brand.shortVersion) + } catch { + throw AppError.message(Self.describe(error)) + } + } + func profile(of dive: Dive) async -> [DiveComputer] { guard let repository else { return [] } return (try? await repository.profile(of: dive)) ?? [] diff --git a/App/Views/DiveDetailView.swift b/App/Views/DiveDetailView.swift @@ -13,6 +13,7 @@ struct DiveDetailView: View { @State private var computerIndex = 0 @State private var editing = LaunchOptions.flag("-edit") @State private var confirmingDelete = false + @State private var exporting = false @State private var error: String? @State private var photoAccess = PhotoAccess() @State private var photos: [DivePhoto] = [] @@ -199,6 +200,7 @@ struct DiveDetailView: View { dismiss() } .disabled(model.logbook.dives.count < 2) + Button("Export as UDDF…", systemImage: "square.and.arrow.up") { exporting = true } Button("Delete dive", systemImage: "trash", role: .destructive) { confirmingDelete = true } } label: { Label("More actions", systemImage: "ellipsis.circle") @@ -206,6 +208,8 @@ struct DiveDetailView: View { } } .sheet(isPresented: $editing) { DiveEditView(dive: dive) } + .modifier(UDDFExport(isPresented: $exporting, dives: model.dive(id: diveID).map { [$0] } ?? [], + fileName: model.dive(id: diveID).map { "dive-\($0.number)" } ?? "dive")) .confirmationDialog("Delete this dive from the logbook?", isPresented: $confirmingDelete, titleVisibility: .visible) { Button("Delete", role: .destructive) { Task { diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift @@ -15,7 +15,7 @@ struct FileImport: ViewModifier { func body(content: Content) -> some View { content - .fileImporter(isPresented: $isPresented, allowedContentTypes: [.zip, .database, .data], allowsMultipleSelection: false) { result in + .fileImporter(isPresented: $isPresented, allowedContentTypes: [.zip, .database, .xml, .data], allowsMultipleSelection: false) { result in switch result { case .success(let urls): if let url = urls.first { open(url) } @@ -286,3 +286,57 @@ struct CreateAccountView: View { } } } + +/// A UDDF document on its way to the Files app. +struct UDDFFile: FileDocument { + static let type = UTType(filenameExtension: "uddf", conformingTo: .xml) ?? .xml + static var readableContentTypes: [UTType] { [type] } + var text: String + + init(text: String) { self.text = text } + + init(configuration: ReadConfiguration) throws { + text = String(decoding: configuration.file.regularFileContents ?? Data(), as: UTF8.self) + } + + func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { + FileWrapper(regularFileWithContents: Data(text.utf8)) + } +} + +/// Writes the logbook, or the given dives, as a UDDF file that other dive log programs read. +struct UDDFExport: ViewModifier { + @Environment(AppModel.self) private var model + @Binding var isPresented: Bool + /// nil: the whole logbook. + var dives: [Dive]? + var fileName = "logbook" + @State private var document: UDDFFile? + @State private var error: String? + + func body(content: Content) -> some View { + content + .onChange(of: isPresented) { + guard isPresented else { return } + Task { + do { + document = UDDFFile(text: try await model.uddf(dives: dives)) + } catch { + self.error = AppModel.describe(error) + isPresented = false + } + } + } + .fileExporter(isPresented: Binding(get: { document != nil }, set: { if !$0 { document = nil; isPresented = false } }), + document: document, contentType: UDDFFile.type, defaultFilename: fileName) { result in + if case .failure(let failure) = result { error = failure.localizedDescription } + document = nil + isPresented = false + } + .alert("Export failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { + Button("OK", role: .cancel) {} + } message: { + Text(error ?? "") + } + } +} diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift @@ -6,6 +6,7 @@ struct SettingsView: View { @State private var confirmingSignOut = false @State private var importing = false @State private var downloading = false + @State private var exporting = false @State private var connecting = LaunchOptions.flag("-connectCloud") @State private var showingCards = LaunchOptions.flag("-cards") @Environment(CardStore.self) private var cards @@ -88,6 +89,10 @@ struct SettingsView: View { Button { importing = true } label: { Label("Import a file…", systemImage: "square.and.arrow.down") } + Button { exporting = true } label: { + Label("Export as UDDF…", systemImage: "square.and.arrow.up") + } + .disabled(model.logbook.dives.isEmpty) ForEach(model.logbook.warnings, id: \.self) { warning in Label(warning, systemImage: "exclamationmark.triangle") .font(.footnote) @@ -132,6 +137,7 @@ struct SettingsView: View { .navigationTitle("Settings") .navigationDestination(isPresented: $showingCards) { CardsView() } .modifier(FileImport(isPresented: $importing)) + .modifier(UDDFExport(isPresented: $exporting)) .modifier(DiveComputerImport(isPresented: $downloading)) .sheet(isPresented: $connecting) { ConnectCloudView() } .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?") diff --git a/App/Views/TechPlanView.swift b/App/Views/TechPlanView.swift @@ -11,6 +11,9 @@ struct TechPlanView: View { @State private var result = PlanResult() @State private var confirmingReset = false @State private var variations: PlanVariations? + @AppStorage("planDate") private var planDate = Date().timeIntervalSince1970 + @AppStorage("planCountEarlierDives") private var countEarlierDives = false + @State private var earlier: [AppModel.EarlierDive] = [] @AppStorage("planShowVariations") private var showVariations = false @State private var saving = LaunchOptions.flag("-savePlan") @@ -44,6 +47,16 @@ struct TechPlanView: View { if plan.mode != .openCircuit { Toggle("Ascent on open-circuit bailout", isOn: $plan.bailout) } + if plan.mode == .closedCircuit, !plan.bailout { + Toggle("Another setpoint for the ascent", isOn: Binding(get: { plan.ascentSetpoint != nil }, + set: { plan.ascentSetpoint = $0 ? 1.4 : nil })) + if plan.ascentSetpoint != nil { + NumberRow(title: "Setpoint", value: Binding(get: { plan.ascentSetpoint ?? 1.4 }, set: { plan.ascentSetpoint = $0 }), + unit: "bar", digits: 2, range: 0.4...1.6, step: 0.1) + NumberRow(title: "From", value: units.depthBinding($plan.ascentSetpointDepth), unit: units.depthUnit, + range: 0...units.depthValue(100), step: units.imperial ? 10 : 3) + } + } } footer: { if plan.mode == .closedCircuit { Text(plan.bailout @@ -55,6 +68,28 @@ struct TechPlanView: View { } Section { + DatePicker("Date", selection: Binding(get: { Date(timeIntervalSince1970: planDate) }, set: { planDate = $0.timeIntervalSince1970 })) + Toggle("Count my earlier dives", isOn: $countEarlierDives) + if countEarlierDives { + if earlier.isEmpty { + Text("No dive of the logbook in the 48 hours before.").foregroundStyle(.secondary).font(.callout) + } + ForEach(earlier) { dive in + HStack { + Text(dive.title) + Spacer() + Text(String(localized: "\(Units.duration(dive.interval)) before")).foregroundStyle(.secondary) + } + .font(.callout) + } + } + } footer: { + if countEarlierDives { + Text("The dives of the logbook that ended less than 48 hours before this date leave gas in the tissues: the plan starts from there.") + } + } + + Section { ForEach($plan.levels) { $level in VStack(spacing: 8) { NumberRow(title: "Depth", value: units.depthBinding($level.depth), unit: units.depthUnit, digits: units.imperial ? 0 : 1, @@ -141,10 +176,13 @@ struct TechPlanView: View { .confirmationDialog("Start a new plan?", isPresented: $confirmingReset, titleVisibility: .visible) { Button("Start over", role: .destructive) { plan = Self.starter } } - .task(id: plan) { + .task(id: PlanInputs(plan: plan, date: planDate, earlier: countEarlierDives, imperial: model.units.imperial, dives: model.logbook.dives.count)) { if let data = try? JSONEncoder().encode(plan) { UserDefaults.standard.set(data, forKey: Self.storageKey) } - let current = plan - let computed = await Task.detached(priority: .userInitiated) { DivePlanner.plan(current) }.value + var current = plan + current.settings.stopsInFeet = model.units.imperial + earlier = countEarlierDives ? await model.earlierDives(before: Date(timeIntervalSince1970: planDate)) : [] + let prior = earlier.map(\.prior) + let computed = await Task.detached(priority: .userInitiated) { DivePlanner.plan(current, after: prior) }.value guard !Task.isCancelled else { return } result = computed variations = nil @@ -158,7 +196,7 @@ struct TechPlanView: View { let current = plan variations = await Task.detached(priority: .utility) { DivePlanner.variations(of: current) }.value } - .sheet(isPresented: $saving) { SavePlanView(plan: plan, result: result) } + .sheet(isPresented: $saving) { SavePlanView(plan: plan, result: result, date: Date(timeIntervalSince1970: planDate)) } } // MARK: Results @@ -176,6 +214,11 @@ struct TechPlanView: View { } } .listRowInsets(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)) + if result.bottomExtensionMinutes > 0 { + Label(String(localized: "Bottom time extended by \(Int(result.bottomExtensionMinutes.rounded())) min: the longest this dive can be without stops, with the gas there is."), + systemImage: "clock.arrow.2.circlepath") + .font(.callout) + } if showVariations, let variations { Label(String(localized: "One metre deeper: \(signed(variations.perMeter)) of run time. One minute longer: \(signed(variations.perMinute)) of ascent."), systemImage: "plusminus") @@ -305,7 +348,7 @@ struct TechPlanView: View { private func isSevere(_ warning: PlanWarning) -> Bool { switch warning { - case .oxygenTooHigh, .oxygenTooLow, .notEnoughGas, .endless, .unknownCylinder: return true + case .oxygenTooHigh, .oxygenTooLow, .notEnoughGas, .endless, .unknownCylinder, .exceedsNoStopLimit: return true case .narcosis, .density, .underMinimumGas, .underReserve, .cnsHigh: return false } } @@ -329,6 +372,8 @@ struct TechPlanView: View { return String(localized: "\(name(cylinder)): \(units.pressure(left)) left at the end, under the reserve of \(units.pressure(reserve)).") case .cnsHigh(let percent): return String(localized: "Oxygen clock at \(fixed(percent, 0)) %.") + case .exceedsNoStopLimit: + return String(localized: "This dive needs decompression stops: it is beyond the no-stop limit of the recreational mode.") case .unknownCylinder: return String(localized: "A level uses a cylinder that is no longer in the list.") case .endless: @@ -337,6 +382,15 @@ struct TechPlanView: View { } } +/// Everything the plan depends on: any change computes it again. +private struct PlanInputs: Equatable { + let plan: DivePlan + let date: Double + let earlier: Bool + let imperial: Bool + let dives: Int +} + /// The planned profile, with the gas switches. private struct PlanChart: View { let result: PlanResult @@ -466,6 +520,7 @@ private struct PlanSettingsEditor: View { Picker("Model", selection: $settings.model) { Text("Bühlmann").tag(DecoModel.buhlmann) Text(verbatim: "VPM-B").tag(DecoModel.vpmb) + Text("Recreational").tag(DecoModel.recreational) } .pickerStyle(.segmented) if settings.model == .vpmb { @@ -473,8 +528,12 @@ private struct PlanSettingsEditor: View { } } header: { Text("Decompression model") + } footer: { + if settings.model == .recreational { + Text("No-stop diving: the bottom time is extended as far as a direct ascent stays allowed and the gas lasts, reserve kept.") + } } - if settings.model == .buhlmann { + if settings.model != .vpmb { Section { Menu { ForEach(Conservatism.allCases) { level in @@ -508,6 +567,7 @@ private struct PlanSettingsEditor: View { NumberRow(title: "Gas switch", value: $settings.gasSwitchSeconds, unit: "s", range: 0...300, step: 30) Toggle("Switch gas only at required stops", isOn: $settings.switchOnlyAtRequiredStops) Toggle("Breaks during oxygen stops", isOn: $settings.oxygenBreaks) + NumberRow(title: "Time shown at the surface", value: $settings.surfaceSegmentMinutes, unit: "min", range: 0...60, step: 1) } Section("Consumption at the surface") { NumberRow(title: "At the bottom", value: $settings.sacBottom, unit: "L/min", digits: 1, range: 5...60, step: 1) @@ -525,10 +585,11 @@ private struct PlanSettingsEditor: View { NumberRow(title: "Decompression", value: $settings.ppO2Deco, unit: "bar", digits: 1, range: 1...1.6, step: 0.1) } Section("Water") { - Picker("Water", selection: Binding(get: { settings.environment.waterDensity < 1.015 }, - set: { settings.environment.waterDensity = $0 ? 1.0 : 1.03 })) { - Text("Sea").tag(false) - Text("Fresh").tag(true) + Picker("Water", selection: Binding(get: { (settings.environment.waterDensity * 100).rounded() / 100 }, + set: { settings.environment.waterDensity = $0 })) { + Text("Sea").tag(1.03) + Text(verbatim: "EN 13319").tag(1.02) + Text("Fresh").tag(1.0) } .pickerStyle(.segmented) NumberRow(title: "Altitude", value: altitude(units), unit: units.depthUnit, range: 0...units.depthValue(5000), step: units.imperial ? 500 : 100) @@ -563,7 +624,7 @@ struct SavePlanView: View { @Environment(\.dismiss) private var dismiss let plan: DivePlan let result: PlanResult - @State private var date = Calendar.current.date(bySetting: .minute, value: 0, of: Date().addingTimeInterval(3600)) ?? Date() + @State var date: Date @State private var working = false @State private var error: String? diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift @@ -83,6 +83,11 @@ public enum ImportError: Error, Equatable, CustomStringConvertible { public enum DiveImporter { /// Detects the format of a file and extracts its dives, from the most recent to the oldest. public static func dives(from data: [UInt8]) throws -> [ImportedDive] { + if UDDF.isUDDF(data) { + let dives = try UDDF.dives(from: data) + guard !dives.isEmpty else { throw ImportError.empty } + return dives.sorted { $0.when > $1.when } + } var database = data if ZipArchive.isZip(data) { do { diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift @@ -282,6 +282,15 @@ public actor LogRepository { return files } + /// The logbook (or some of its dives) as a UDDF document, profiles included. + public func uddf(dives only: [Dive]? = nil, generator: String, version: String) throws -> String { + let log = try logbook() + let exported = try (only ?? log.dives).map { dive in + UDDF.ExportedDive(dive: dive, computers: try LogLoader.loadProfile(of: dive, store: store), site: log.site(of: dive)) + } + return UDDF.document(exported, generator: generator, version: version) + } + /// Sends a whole logbook to the server as the new state of the branch, on top of whatever is there (which /// stays in the history), and makes it the local logbook. For a logbook kept without an account, the day its /// owner connects one. diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/UDDF.swift b/Packages/DiveKit/Sources/SubsurfaceLog/UDDF.swift @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: GPL-2.0-only +import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif + +/// UDDF (Universal Dive Data Format, version 3.2): the neutral exchange format that most dive log software reads +/// and writes. SI units throughout: metres, seconds, kelvins, pascals, cubic metres. +/// Reference: https://www.streit.cc/extern/uddf_v321/en/index.html +public enum UDDF { + public static func isUDDF(_ data: [UInt8]) -> Bool { + let head = String(decoding: data.prefix(4096), as: UTF8.self) + return head.contains("<uddf") + } + + // MARK: Import + + /// The dives of a UDDF document, as the importer handles them. + public static func dives(from data: [UInt8], timeZone: TimeZone = .current) throws -> [ImportedDive] { + let reader = Reader(timeZone: timeZone) + let parser = XMLParser(data: Data(data)) + parser.delegate = reader + guard parser.parse() else { + throw ImportError.unreadable(parser.parserError?.localizedDescription ?? "XML") + } + return reader.finished() + } + + private final class Reader: NSObject, XMLParserDelegate { + struct Mix { var o2 = 0.21, he = 0.0 } + struct Site { var name = "", latitude: Double?, longitude: Double? } + struct Pending { + var dive = ImportedDive(when: 0, durationSeconds: 0) + var links = [String]() + var hasDate = false + var notes = [String]() + var number: Int? + } + + let timeZone: TimeZone + private var path = [String]() + private var text = "" + private var generator = "" + private var mixes = [String: Mix]() + private var sites = [String: Site]() + private var buddies = [String: String]() + private var currentID = "" + private var mix = Mix() + private var site = Site() + private var firstName = "", lastName = "" + private var pending: Pending? + private var sample: ImportedDive.Sample? + private var sampleSwitch: String? + private var gas = Mix() + private var done = [Pending]() + + init(timeZone: TimeZone) { self.timeZone = timeZone } + + private func inside(_ name: String) -> Bool { path.contains(name) } + private var number: Double? { Double(text.trimmingCharacters(in: .whitespacesAndNewlines)) } + private var trimmed: String { text.trimmingCharacters(in: .whitespacesAndNewlines) } + + func parser(_ parser: XMLParser, didStartElement element: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String]) { + path.append(element) + text = "" + switch element { + case "mix": + currentID = attributes["id"] ?? "" + mix = Mix() + case "site": + currentID = attributes["id"] ?? "" + site = Site() + case "buddy", "owner": + currentID = attributes["id"] ?? "" + firstName = "" + lastName = "" + case "dive": + pending = Pending() + gas = Mix() + case "link": + if inside("informationbeforedive") || inside("informationafterdive") || path.dropLast().last == "dive" { + if let ref = attributes["ref"] { pending?.links.append(ref) } + } else if inside("tankdata"), pending?.dive.samples.isEmpty == true, let ref = attributes["ref"], let found = mixes[ref] { + // The first cylinder's gas is the one breathed until a switch says otherwise. + if !(pending?.links.contains("mix:") ?? false) { + gas = found + pending?.links.append("mix:") + } + } + case "waypoint": + sample = ImportedDive.Sample(time: 0, depth: 0) + sampleSwitch = nil + case "switchmix": + sampleSwitch = attributes["ref"] + case "decostop": + if attributes["kind"] != "safety" { + sample?.stopDepth = Double(attributes["decodepth"] ?? "") ?? 0 + sample?.decoTime = Int(Double(attributes["duration"] ?? "") ?? 0) + } + default: + break + } + } + + func parser(_ parser: XMLParser, foundCharacters string: String) { text += string } + + func parser(_ parser: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName: String?) { + defer { + path.removeLast() + text = "" + } + let parent = path.dropLast().last ?? "" + switch element { + case "name": + if parent == "generator" { generator = trimmed } else if parent == "site" { site.name = trimmed } + case "o2": if parent == "mix", let value = number { mix.o2 = value } + case "he": if parent == "mix", let value = number { mix.he = value } + case "mix": mixes[currentID] = mix + case "latitude": if inside("site") { site.latitude = number } + case "longitude": if inside("site") { site.longitude = number } + case "location": if inside("site"), site.name.isEmpty { site.name = trimmed } + case "site": sites[currentID] = site + case "firstname": firstName = trimmed + case "lastname": lastName = trimmed + case "buddy": + buddies[currentID] = [firstName, lastName].filter { !$0.isEmpty }.joined(separator: " ") + + case "datetime": + if inside("informationbeforedive"), let when = timestamp(trimmed) { + pending?.dive.when = when + pending?.hasDate = true + } + case "divenumber": pending?.number = number.map { Int($0) } + case "atmosphericpressure": + if let value = number, value > 50_000 { pending?.dive.surfacePressureBar = (value / 100).rounded() / 1000 } + case "density": + if inside("informationbeforedive") || inside("informationafterdive"), let value = number, value > 900, value < 1100 { + pending?.dive.salinity = Int(value.rounded()) + } + + case "divetime": if let value = number { sample?.time = Int(value.rounded()) } + case "depth": if parent == "waypoint", let value = number { sample?.depth = (value * 100).rounded() / 100 } + case "temperature": if parent == "waypoint", let value = number { sample?.temperature = ((value - 273.15) * 10).rounded() / 10 } + case "tankpressure": + if parent == "waypoint", let value = number { + let bar = (value / 10_000).rounded() / 10 + if sample?.pressure1 == nil { sample?.pressure1 = bar } else { sample?.pressure2 = bar } + } + case "cns": if parent == "waypoint", let value = number { sample?.cns = Int((value * (value <= 3 ? 100 : 1)).rounded()) } + case "nodecotime": if parent == "waypoint", let value = number, sample?.stopDepth == 0 { sample?.decoTime = Int(value) } + case "waypoint": + if let ref = sampleSwitch, let found = mixes[ref] { gas = found } + if var finished = sample { + finished.o2 = Int((gas.o2 * 100).rounded()) + finished.he = Int((gas.he * 100).rounded()) + pending?.dive.samples.append(finished) + } + sample = nil + + case "diveduration": if inside("informationafterdive"), let value = number { pending?.dive.durationSeconds = Int(value.rounded()) } + case "para", "text": if inside("notes"), inside("dive"), !trimmed.isEmpty { pending?.notes.append(trimmed) } + case "notes": + // Notes written without paragraphs. + if inside("dive"), pending?.notes.isEmpty == true, !trimmed.isEmpty { pending?.notes.append(trimmed) } + case "dive": + if let finished = pending { done.append(finished) } + pending = nil + default: + break + } + } + + /// "2026-06-21T15:00:00", local time; with a "Z" it is a universal time, brought back to the local one. + private func timestamp(_ text: String) -> Int? { + let numbers = text.prefix(19).split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) } + guard numbers.count >= 3 else { return nil } + guard let naive = NaiveTime.timestamp(year: numbers[0], month: numbers[1], day: numbers[2], + hour: numbers.count > 3 ? numbers[3] : 0, minute: numbers.count > 4 ? numbers[4] : 0, + second: numbers.count > 5 ? numbers[5] : 0) else { return nil } + guard text.hasSuffix("Z") else { return naive } + return naive + timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: TimeInterval(naive))) + } + + func finished() -> [ImportedDive] { + done.compactMap { entry -> ImportedDive? in + var dive = entry.dive + guard entry.hasDate, !dive.samples.isEmpty || dive.durationSeconds > 0 else { return nil } + dive.samples.sort { $0.time < $1.time } + if dive.durationSeconds <= 0 { dive.durationSeconds = dive.samples.last?.time ?? 0 } + dive.model = generator.isEmpty ? "UDDF" : generator + dive.sourceID = "uddf-\(dive.when)" + for link in entry.links { + if let site = sites[link] { + dive.site = site.name + dive.latitude = site.latitude + dive.longitude = site.longitude + } else if let buddy = buddies[link], !buddy.isEmpty { + dive.buddy = dive.buddy.isEmpty ? buddy : dive.buddy + ", " + buddy + } + } + dive.notes = entry.notes.joined(separator: "\n") + return dive + } + } + } + + // MARK: Export + + /// One dive to write: the dive, its profile, and the name and position of its site. + public struct ExportedDive { + public var dive: Dive + public var computers: [DiveComputer] + public var site: DiveSite? + + public init(dive: Dive, computers: [DiveComputer], site: DiveSite?) { + self.dive = dive + self.computers = computers + self.site = site + } + } + + /// A UDDF 3.2 document holding the dives, with their sites, buddies, gases, cylinders and profiles. + public static func document(_ dives: [ExportedDive], generator: String, version: String) -> String { + func escape(_ text: String) -> String { + text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;") + .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;") + } + func fixed(_ value: Double, _ digits: Int = 2) -> String { String(format: "%.\(digits)f", locale: Locale(identifier: "en_US_POSIX"), value) } + func kelvin(_ celsius: Double) -> String { fixed(celsius + 273.15) } + + // What the dives refer to: gases, sites, buddies. + var mixes = [GasMix]() + func mixID(_ mix: GasMix) -> String { + let normal = mix.isAir ? GasMix.air : mix + if let index = mixes.firstIndex(of: normal) { return "mix\(index + 1)" } + mixes.append(normal) + return "mix\(mixes.count)" + } + var siteIDs = [UInt32: String]() + var siteList = [DiveSite]() + var buddyIDs = [String: String]() + var buddyList = [String]() + var body = "" + for (index, entry) in dives.sorted(by: { $0.dive.when < $1.dive.when }).enumerated() { + let dive = entry.dive + let computer = entry.computers.first + body += " <dive id=\"dive\(index + 1)\">\n <informationbeforedive>\n" + if let site = entry.site, !site.name.isEmpty { + if siteIDs[site.uuid] == nil { + siteList.append(site) + siteIDs[site.uuid] = "site\(siteList.count)" + } + body += " <link ref=\"\(siteIDs[site.uuid]!)\"/>\n" + } + let people = (dive.buddy.split(separator: ",") + dive.divemaster.split(separator: ",")) + .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + for person in people { + if buddyIDs[person] == nil { + buddyList.append(person) + buddyIDs[person] = "buddy\(buddyList.count)" + } + body += " <link ref=\"\(buddyIDs[person]!)\"/>\n" + } + if dive.number > 0 { body += " <divenumber>\(dive.number)</divenumber>\n" } + let c = NaiveTime.components(dive.when) + body += String(format: " <datetime>%04d-%02d-%02dT%02d:%02d:%02d</datetime>\n", + c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0) + if let surface = computer?.surfacePressureBar, surface > 0 { + body += " <atmosphericpressure>\(fixed(surface * 100_000, 0))</atmosphericpressure>\n" + } + body += " </informationbeforedive>\n" + + for (cylinderIndex, cylinder) in dive.cylinders.enumerated() { + body += " <tankdata id=\"dive\(index + 1)tank\(cylinderIndex + 1)\">\n <link ref=\"\(mixID(cylinder.gas))\"/>\n" + if let liters = cylinder.volumeLiters, liters > 0 { body += " <tankvolume>\(fixed(liters / 1000, 5))</tankvolume>\n" } + if let start = cylinder.startBar { body += " <tankpressurebegin>\(fixed(start * 100_000, 0))</tankpressurebegin>\n" } + if let end = cylinder.endBar { body += " <tankpressureend>\(fixed(end * 100_000, 0))</tankpressureend>\n" } + body += " </tankdata>\n" + } + + body += " <samples>\n" + let changes = (computer?.events ?? []).filter(\.isGasChange) + var switched = Set<Int>() + let firstMix = dive.cylinders.first?.gas ?? .air + for (sampleIndex, sample) in (computer?.samples ?? []).enumerated() { + body += " <waypoint><depth>\(fixed(sample.depth))</depth><divetime>\(sample.time)</divetime>" + if let temperature = sample.temperature { body += "<temperature>\(kelvin(temperature))</temperature>" } + for pressure in sample.pressures where dive.cylinders.indices.contains(pressure.sensor) || dive.cylinders.isEmpty { + let ref = dive.cylinders.isEmpty ? "" : " ref=\"dive\(index + 1)tank\(pressure.sensor + 1)\"" + body += "<tankpressure\(ref)>\(fixed(pressure.bar * 100_000, 0))</tankpressure>" + } + if sampleIndex == 0 { body += "<switchmix ref=\"\(mixID(firstMix))\"/>" } + for (changeIndex, change) in changes.enumerated() where change.time <= sample.time && !switched.contains(changeIndex) && change.time > 0 { + switched.insert(changeIndex) + if let mix = change.gas ?? change.cylinder.flatMap({ dive.cylinders.indices.contains($0) ? dive.cylinders[$0].gas : nil }) { + body += "<switchmix ref=\"\(mixID(mix))\"/>" + } + } + if sample.inDeco, let depth = sample.stopDepth, depth > 0 { + body += "<decostop kind=\"mandatory\" decodepth=\"\(fixed(depth, 1))\" duration=\"\(sample.stopTime ?? 0)\"/>" + } else if let ndl = sample.ndl { + body += "<nodecotime>\(ndl)</nodecotime>" + } + if let cns = sample.cns { body += "<cns>\(fixed(Double(cns) / 100, 2))</cns>" } + body += "</waypoint>\n" + } + body += " </samples>\n <informationafterdive>\n" + if let lowest = dive.waterTemperatureOverride ?? computer?.waterTemperature { body += " <lowesttemperature>\(kelvin(lowest))</lowesttemperature>\n" } + body += " <greatestdepth>\(fixed(dive.maxDepth))</greatestdepth>\n" + if let mean = dive.meanDepth { body += " <averagedepth>\(fixed(mean))</averagedepth>\n" } + body += " <diveduration>\(dive.durationSeconds)</diveduration>\n" + if !dive.notes.isEmpty { + body += " <notes>\n" + for paragraph in dive.notes.split(separator: "\n", omittingEmptySubsequences: true) { + body += " <para>\(escape(String(paragraph)))</para>\n" + } + body += " </notes>\n" + } + if dive.rating > 0 { body += " <rating><ratingvalue>\(dive.rating * 2)</ratingvalue></rating>\n" } + body += " </informationafterdive>\n </dive>\n" + } + + var out = """ + <?xml version="1.0" encoding="UTF-8"?> + <uddf xmlns="http://www.streit.cc/uddf/3.2/" version="3.2.3"> + <generator> + <name>\(escape(generator))</name> + <type>logbook</type> + <version>\(escape(version))</version> + </generator> + + """ + out += " <diver>\n <owner id=\"owner\"><personal><firstname></firstname><lastname></lastname></personal></owner>\n" + for person in buddyList { + let parts = person.split(separator: " ", maxSplits: 1).map(String.init) + out += " <buddy id=\"\(buddyIDs[person]!)\"><personal><firstname>\(escape(parts[0]))</firstname>" + + "<lastname>\(escape(parts.count > 1 ? parts[1] : ""))</lastname></personal></buddy>\n" + } + out += " </diver>\n <divesite>\n" + for site in siteList { + out += " <site id=\"\(siteIDs[site.uuid]!)\"><name>\(escape(site.name))</name>" + if let latitude = site.latitude, let longitude = site.longitude { + out += "<geography><latitude>\(fixed(latitude, 6))</latitude><longitude>\(fixed(longitude, 6))</longitude></geography>" + } + out += "</site>\n" + } + out += " </divesite>\n <gasdefinitions>\n" + for (index, mix) in mixes.enumerated() { + let o2 = mix.o2Fraction, he = mix.heFraction + let name = he > 0 ? "Tx\(Int((o2 * 100).rounded()))/\(Int((he * 100).rounded()))" : (mix.isAir ? "Air" : "EAN\(Int((o2 * 100).rounded()))") + out += " <mix id=\"mix\(index + 1)\"><name>\(name)</name><o2>\(fixed(o2, 3))</o2><n2>\(fixed(max(0, 1 - o2 - he), 3))</n2><he>\(fixed(he, 3))</he></mix>\n" + } + out += " </gasdefinitions>\n <profiledata>\n <repetitiongroup id=\"rg1\">\n" + body + " </repetitiongroup>\n </profiledata>\n</uddf>\n" + return out + } +} diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift @@ -285,6 +285,93 @@ final class ImportTests: XCTestCase { try remote.git(["fsck", "--strict"]) } + /// UDDF: a document written by another program is read, and the logbook written as UDDF reads back the same. + func testUDDF() async throws { + let document = """ + <?xml version="1.0" encoding="UTF-8"?> + <uddf xmlns="http://www.streit.cc/uddf/3.2/" version="3.2.1"> + <generator><name>Other Logbook</name><version>1.0</version></generator> + <diver> + <owner id="me"><personal><firstname>Sam</firstname><lastname>Diver</lastname></personal></owner> + <buddy id="b1"><personal><firstname>Alex</firstname><lastname>Martin</lastname></personal></buddy> + </diver> + <divesite><site id="s1"><name>North Quarry</name><geography><latitude>45.5</latitude><longitude>-73.6</longitude></geography></site></divesite> + <gasdefinitions> + <mix id="air"><name>Air</name><o2>0.21</o2><n2>0.79</n2><he>0</he></mix> + <mix id="ean50"><name>EAN50</name><o2>0.5</o2><n2>0.5</n2><he>0</he></mix> + </gasdefinitions> + <profiledata><repetitiongroup id="rg1"> + <dive id="d1"> + <informationbeforedive><link ref="s1"/><link ref="b1"/><divenumber>7</divenumber><datetime>2026-07-18T10:30:00</datetime> + <atmosphericpressure>101300</atmosphericpressure></informationbeforedive> + <tankdata><link ref="air"/><tankvolume>0.012</tankvolume><tankpressurebegin>20000000</tankpressurebegin></tankdata> + <samples> + <waypoint><depth>0.0</depth><divetime>0</divetime><switchmix ref="air"/></waypoint> + <waypoint><depth>20.4</depth><divetime>120</divetime><temperature>285.15</temperature><tankpressure>19000000</tankpressure></waypoint> + <waypoint><depth>6.0</depth><divetime>1800</divetime><switchmix ref="ean50"/><decostop kind="mandatory" decodepth="6" duration="120"/></waypoint> + <waypoint><depth>0.0</depth><divetime>2400</divetime></waypoint> + </samples> + <informationafterdive><greatestdepth>20.4</greatestdepth><diveduration>2400</diveduration> + <notes><para>Clear water &amp; a pike.</para><para>Second line.</para></notes></informationafterdive> + </dive> + <dive id="d2"><informationbeforedive><datetime>2026-07-19T14:00:00Z</datetime></informationbeforedive> + <samples><waypoint><depth>5</depth><divetime>60</divetime></waypoint><waypoint><depth>0</depth><divetime>600</divetime></waypoint></samples> + <informationafterdive><diveduration>600</diveduration></informationafterdive></dive> + </repetitiongroup></profiledata> + </uddf> + """ + XCTAssertTrue(UDDF.isUDDF(Array(document.utf8))) + let dives = try UDDF.dives(from: Array(document.utf8), timeZone: TimeZone(secondsFromGMT: -4 * 3600)!) + XCTAssertEqual(dives.count, 2) + let first = dives[0] + XCTAssertEqual(first.when, NaiveTime.timestamp(year: 2026, month: 7, day: 18, hour: 10, minute: 30)) + XCTAssertEqual(first.durationSeconds, 2400) + XCTAssertEqual(first.site, "North Quarry") + XCTAssertEqual(first.latitude, 45.5) + XCTAssertEqual(first.buddy, "Alex Martin") + XCTAssertEqual(first.notes, "Clear water & a pike.\nSecond line.") + XCTAssertEqual(first.model, "Other Logbook") + XCTAssertEqual(first.surfacePressureBar, 1.013) + XCTAssertEqual(first.samples.map(\.depth), [0, 20.4, 6, 0]) + XCTAssertEqual(first.samples[1].temperature, 12) + XCTAssertEqual(first.samples[1].pressure1, 190) + XCTAssertEqual(first.samples.map(\.o2), [21, 21, 50, 50]) + XCTAssertEqual(first.samples[2].stopDepth, 6) + // A universal time ("Z") is brought back to the local time of the reader: 14:00 UTC is 10:00 at UTC-4. + XCTAssertEqual(dives[1].when, NaiveTime.timestamp(year: 2026, month: 7, day: 19, hour: 10, minute: 0)) + XCTAssertEqual(try DiveImporter.dives(from: Array(document.utf8)).count, 2) + + // The fixture logbook, written as UDDF, reads back with the same dives. + let (remote, _) = try Fixture.makeRemote() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: Fixture.branch, + authorName: "DiveLog", authorEmail: Fixture.branch) + _ = try await repo.sync(transport: transport) + let log = try await repo.logbook() + let written = try await repo.uddf(generator: "DiveLog", version: "1.0") + XCTAssertTrue(written.contains("<uddf ")) + let back = try UDDF.dives(from: Array(written.utf8)) + XCTAssertEqual(back.map(\.when).sorted(), log.dives.map(\.when).sorted()) + for dive in log.dives { + let read = try XCTUnwrap(back.first { $0.when == dive.when }) + XCTAssertEqual(read.durationSeconds, dive.durationSeconds) + XCTAssertEqual(read.site, log.site(of: dive)?.name ?? "") + XCTAssertEqual(read.notes, dive.notes.split(separator: "\n", omittingEmptySubsequences: true).joined(separator: "\n")) + let profile = try await repo.profile(of: dive).first + XCTAssertEqual(read.samples.count, profile?.samples.count ?? 0) + if let deepest = profile?.samples.map(\.depth).max() { XCTAssertEqual(read.maxDepth, deepest, accuracy: 0.01) } + } + // And it is well-formed for the system's own XML tool. + let file = try LocalGit.temporaryDirectory("uddf").appendingPathComponent("logbook.uddf") + try written.write(to: file, atomically: true, encoding: .utf8) + let lint = Process() + lint.executableURL = URL(fileURLWithPath: "/usr/bin/xmllint") + lint.arguments = ["--noout", file.path] + try lint.run() + lint.waitUntilExit() + XCTAssertEqual(lint.terminationStatus, 0) + } + /// Dive dropped by Open Rémora (JSON of RemoraDeco's `DiveLog`, sorted keys, ISO 8601 dates). func testOpenRemoraDive() throws { let json = """ diff --git a/README.md b/README.md @@ -16,6 +16,9 @@ The app is available in English and French. - Offline editing: site, buddy, guide, suit, tags, rating, visibility, notes; adding a dive by hand, creating a site, deleting a dive. Changes are sent at the next sync. - Map and list of dive sites, statistics, metric or imperial units. +- UDDF 3.2 import and export (`SubsurfaceLog/UDDF.swift`): the exchange format most dive log programs read and + write. Import: date, profile (depth, temperature, cylinder pressure, gas switches, stops), site and position, + buddies, notes. Export: the whole logbook or one dive, with sites, buddies, gases, cylinders and profiles. - Import of a Shearwater Cloud export (`.zip` or `dive_data.db`) or of the Dive Shearwater app database (`watermelon.db`, found in `~/Library/Containers/com.shearwater.dive/Data/Documents` when the iOS app runs on a Mac): full profiles, gases, deco stops, pressure, sites created as needed, duplicates skipped. @@ -82,8 +85,9 @@ Not there yet: Subsurface XML import, dive planner. ascent steps): Bühlmann ZHL-16C with gradient factors, VPM-B, open circuit, closed and semi-closed rebreathers, bailout, oxygen breaks. `SubsurfaceVectorsTests` runs the plans of Subsurface's `tests/testplan.cpp` (one Bühlmann, seven VPM-B, one closed circuit with bailout) and expects its known run - times to the second. Not ported: its recreational mode (the app has its own no-stop screen), setpoint - changes during a closed-circuit ascent, and repetitive dives. + times to the second, in metres and in feet. Also ported, without a reference figure in Subsurface's tests: + its recreational mode, the tissues left by earlier dives (`init_decompression`), setpoint switches on the + loop, semi-closed circuits, oxygen breaks. - `Packages/DiveKit/Sources/CLibDiveComputer`: libdivecomputer, vendored unchanged (see its `README.md` for the exact revision), built as a package target. - `Packages/DiveKit/Sources/DiveComputerKit`: Swift on top of it. `Catalog` lists the models and matches one from diff --git a/fastlane/Fastfile b/fastlane/Fastfile @@ -76,9 +76,9 @@ platform :ios do end texts = { "fr-CA" => ["Votre carnet de plongée sur iPhone : profils, modification hors ligne, ordinateur de plongée en Bluetooth, synchronisation facultative avec le nuage Subsurface, sauvegarde iCloud. Application indépendante de l'équipe de Subsurface.", - "0.9 : Planification complétée d'après le planificateur de Subsurface, et validée contre ses propres plans de test (mêmes durées à la seconde). Nouveau : modèle VPM-B avec conservatisme ; recycleur fermé (point de consigne) et semi-fermé, avec remontée de secours en circuit ouvert ; vitesses de remontée par zone, altitude, changement de gaz seulement aux paliers requis, pauses pendant les paliers à l'oxygène, réserve par bouteille, variations du plan ; enregistrement du plan comme plongée du carnet ; onglet Gaz : tableau par pression d'oxygène, profondeur narcotique réglable. Aide à la planification seulement."], + "0.10 : Nouveau : (1) Import et export UDDF, le format d'échange des carnets de plongée : Réglages, Importer un fichier (.uddf) ou Exporter en UDDF ; une plongée seule s'exporte depuis son menu. (2) Planification, ce qui manquait par rapport à Subsurface : mode loisir (temps de fond prolongé jusqu'à la limite sans palier ou jusqu'au gaz), plongées précédentes du carnet prises en compte (date du plan), autre point de consigne pour la remontée en circuit fermé, eau EN 13319, temps en surface, paliers tous les 10 pieds en unités impériales."], "en-CA" => ["Your dive log on iPhone: profiles, offline editing, dive computer over Bluetooth, optional sync with Subsurface cloud storage, iCloud backup. Independent from the Subsurface team.", - "0.9: Planning completed after the Subsurface planner and validated against its own test plans (same run times to the second). New: VPM-B model with conservatism; closed circuit (setpoint) and semi-closed rebreathers, with open-circuit bailout; ascent rates by zone, altitude, gas switches only at required stops, breaks during oxygen stops, reserve per cylinder, plan variations; saving the plan as a dive of the logbook; Gas tab: table by oxygen pressure, adjustable narcotic depth. A planning aid only."], + "0.10: New: (1) UDDF import and export, the exchange format of dive logs: Settings, Import a file (.uddf) or Export as UDDF; a single dive exports from its menu. (2) Planning, what was missing compared with Subsurface: recreational mode (bottom time extended to the no-stop limit or to the gas), earlier dives of the logbook taken into account (date of the plan), another setpoint for a closed-circuit ascent, EN 13319 water, time at the surface, stops every 10 ft in imperial units."], } _, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations") texts.each do |locale, (description, _)| diff --git a/project.yml b/project.yml @@ -13,7 +13,7 @@ settings: base: DEVELOPMENT_TEAM: CM5RQKJH56 CODE_SIGN_STYLE: Automatic - MARKETING_VERSION: "0.9" + MARKETING_VERSION: "0.10" CURRENT_PROJECT_VERSION: "1" SWIFT_VERSION: "5.0" targets: