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 da995711c4e61d9ca66ce01f8fe00591c8e57a59
parent 363b4f08a7af3d1e0151791172d3b6ba5f32affc
Author: Jean Schurger <jean@schurger.org>
Date:   Sat, 14 Nov 2026 11:09:05 -0500

Merge dives recorded by several dive computers; import Open Mérou dives

A dive that comes in while the logbook already has a dive at that time
(overlapping [start, end] ranges, not the same start time) joins it as
one more dive computer, the way Subsurface stores it (Divecomputer-001,
Divecomputer-002...), in either arrival order. The dive keeps its date,
number, site and notes; the incoming one fills what it lacks. The same
dive from the same computer is still not imported twice.

- DiveMerge: the rules (overlap, same computer, order of the computers:
  Open Rémora, other dive computers, Open Mérou, manual profile).
- LogEditor.merged: one implementation, on the text of the files, used
  by the import, by the new mergeDives change (manual merge) and by
  divelog-cli merge; the same computer on successive immersions is
  joined on one timeline (replaces ImportedDive.merged).
- A computer that did not start with its dive carries date/time lines;
  the loader reads them (DiveComputer.when).
- App: "Merge dives…" in the + menu (selection, then confirmation), the
  first computer is shown by default, the import sheet says which dives
  will be merged, and Open Mérou's shared folder (OpenMerou/Dives) is
  read like Open Rémora's.
- The Open Rémora contract is docs/SHARING.md (was docs/PARTAGE.md).

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

Diffstat:
MApp/DiveLogApp.swift | 6+++---
MApp/Localizable.xcstrings | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
MApp/Model/AppModel.swift | 130++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
MApp/Views/DiveDetailView.swift | 4++--
MApp/Views/DiveListView.swift | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
MApp/Views/ImportView.swift | 11+++++++++--
MPackages/DiveKit/Sources/SubsurfaceLog/Changes.swift | 24+++++++++++++-----------
MPackages/DiveKit/Sources/SubsurfaceLog/Import.swift | 45+--------------------------------------------
MPackages/DiveKit/Sources/SubsurfaceLog/Loader.swift | 20++++++++++++++++----
APackages/DiveKit/Sources/SubsurfaceLog/Merge.swift | 535+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MPackages/DiveKit/Sources/SubsurfaceLog/Model.swift | 20++++++++++++++++++++
MPackages/DiveKit/Sources/SubsurfaceLog/RemoraImport.swift | 28++++++++++++++++++++++------
MPackages/DiveKit/Sources/SubsurfaceLog/Repository.swift | 41++++++++++++++++++++++++++++++++++-------
MPackages/DiveKit/Sources/divelog-cli/main.swift | 28++++++++++++++++++----------
MPackages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift | 34++++++++++------------------------
APackages/DiveKit/Tests/SubsurfaceLogTests/MergeTests.swift | 520+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MREADME.md | 22+++++++++++++++++-----
17 files changed, 1452 insertions(+), 181 deletions(-)

diff --git a/App/DiveLogApp.swift b/App/DiveLogApp.swift @@ -12,12 +12,12 @@ struct DiveLogApp: App { .environment(model) .task { await model.start() - await model.importFromOpenRemora() + await model.importSharedDives() } // Open Rémora opens "subrascasse://open-remora" after dropping a dive. - .onOpenURL { _ in Task { await model.importFromOpenRemora() } } + .onOpenURL { _ in Task { await model.importSharedDives() } } .onChange(of: scenePhase) { - if scenePhase == .active { Task { await model.importFromOpenRemora() } } + if scenePhase == .active { Task { await model.importSharedDives() } } } } } diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings @@ -61,6 +61,16 @@ } } }, + "%@ · will be merged with dive %@": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%1$@ · sera fusionnée avec la plongée %2$@" + } + } + } + }, "%@, %lld underwater (marked with a wave)": { "localizations": { "fr": { @@ -91,12 +101,22 @@ } } }, - "%lld Open Rémora dives added to the logbook.": { + "%lld %@ dives added to the logbook.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%1$lld plongées %2$@ ajoutées au carnet." + } + } + } + }, + "%lld %@ dives merged with dives already in the logbook.": { "localizations": { "fr": { "stringUnit": { "state": "translated", - "value": "%lld plongées d'Open Rémora ajoutées au carnet." + "value": "%1$lld plongées %2$@ fusionnées avec des plongées déjà au carnet." } } } @@ -201,12 +221,22 @@ } } }, - "1 Open Rémora dive added to the logbook.": { + "1 %@ dive added to the logbook.": { "localizations": { "fr": { "stringUnit": { "state": "translated", - "value": "1 plongée d'Open Rémora ajoutée au carnet." + "value": "1 plongée %@ ajoutée au carnet." + } + } + } + }, + "1 %@ dive merged with a dive already in the logbook.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "1 plongée %@ fusionnée avec une plongée déjà au carnet." } } } @@ -681,12 +711,12 @@ } } }, - "Couldn't read the Open Rémora dive (%@): %@": { + "Couldn't read the %@ dive (%@): %@": { "localizations": { "fr": { "stringUnit": { "state": "translated", - "value": "Plongée d'Open Rémora illisible (%1$@) : %2$@" + "value": "Plongée %1$@ illisible (%2$@) : %3$@" } } } @@ -981,6 +1011,16 @@ } } }, + "Dive %@ merged with %@": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plongée %1$@ fusionnée avec %2$@" + } + } + } + }, "Dive %@ renumbered to %@": { "localizations": { "fr": { @@ -1641,6 +1681,36 @@ } } }, + "Merge": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fusionner" + } + } + } + }, + "Merge %lld dives into one?": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fusionner %lld plongées en une seule ?" + } + } + } + }, + "Merge dives…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fusionner des plongées…" + } + } + } + }, "Metric (m, °C, bar)": { "localizations": { "fr": { @@ -2771,6 +2841,16 @@ } } }, + "The earliest dive keeps its date, number, site and notes; the others fill in what it lacks and add their dive computers. The merge will be sent to the Subsurface cloud at the next sync.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "La plongée la plus ancienne garde sa date, son numéro, son site et ses notes ; les autres complètent ce qui lui manque et ajoutent leurs ordinateurs de plongée. La fusion sera envoyée au nuage Subsurface à la prochaine synchronisation." + } + } + } + }, "The location can be added later in Subsurface.": { "localizations": { "fr": { @@ -2781,12 +2861,12 @@ } } }, - "The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. Dives already in the logbook (same start time) are skipped.": { + "The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. A dive that overlaps one already in the logbook joins it as one more dive computer; a dive the logbook already has from this computer is skipped.": { "localizations": { "fr": { "stringUnit": { "state": "translated", - "value": "Les plongées choisies sont ajoutées au carnet avec leur profil complet, puis envoyées au nuage Subsurface. Celles que le carnet contient déjà (même heure de début) sont laissées de côté." + "value": "Les plongées choisies sont ajoutées au carnet avec leur profil complet, puis envoyées au nuage Subsurface. Une plongée qui en chevauche une déjà au carnet s'y joint comme ordinateur de plongée supplémentaire ; une plongée que le carnet a déjà de cet ordinateur est ignorée." } } } diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift @@ -254,6 +254,10 @@ final class AppModel { let dive = String(number) let renumbered = String(newNumber) return String(localized: "Dive \(dive) renumbered to \(renumbered)") + case .mergeDives(_, let number, let others): + let dive = String(number) + let merged = others.map { String($0.number) }.joined(separator: ", ") + return String(localized: "Dive \(dive) merged with \(merged)") } } @@ -274,11 +278,22 @@ final class AppModel { struct ImportCandidate: Identifiable { let dive: ImportedDive + /// The logbook already has this dive from this computer. let alreadyInLog: Bool + /// Number of the dive of the logbook that this one overlaps and will join as one more dive computer. + let mergesInto: Int? var id: String { dive.id } } - /// Reads an export file and tells, for each dive, whether the logbook already has it (same start time within 2 minutes). + private func candidate(_ dive: ImportedDive) -> ImportCandidate { + switch DiveMerge.disposition(of: dive, among: logbook.dives) { + case .new: return ImportCandidate(dive: dive, alreadyInLog: false, mergesInto: nil) + case .duplicate: return ImportCandidate(dive: dive, alreadyInLog: true, mergesInto: nil) + case .merge(let existing): return ImportCandidate(dive: dive, alreadyInLog: false, mergesInto: existing.number) + } + } + + /// Reads an export file and tells, for each dive, what the logbook already has at that time (see `DiveMerge`). func importCandidates(from url: URL) throws -> [ImportCandidate] { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } @@ -289,10 +304,7 @@ final class AppModel { throw AppError.message(String(localized: "Couldn't read this file.")) } do { - let known = logbook.dives.map(\.when) - return try DiveImporter.dives(from: Array(data)).map { dive in - ImportCandidate(dive: dive, alreadyInLog: known.contains { abs($0 - dive.when) < 120 }) - } + return try DiveImporter.dives(from: Array(data)).map(candidate) } catch let error as ImportError { throw AppError.message(Self.describe(error)) } @@ -300,19 +312,17 @@ final class AppModel { /// Same, for dives that are already decoded (downloaded from a dive computer), most recent first. func importCandidates(for dives: [ImportedDive]) -> [ImportCandidate] { - let known = logbook.dives.map(\.when) - return dives.sorted { $0.when > $1.when }.map { dive in - ImportCandidate(dive: dive, alreadyInLog: known.contains { abs($0 - dive.when) < 120 }) - } + dives.sorted { $0.when > $1.when }.map(candidate) } - /// Adds the dives to the logbook, oldest first, creating any missing sites. - /// Returns the number of dives added. + /// Adds the dives to the logbook, oldest first, creating any missing sites. A dive that overlaps one of the + /// logbook joins it as one more dive computer. Returns the number of dives added or merged. func importDives(_ dives: [ImportedDive]) async throws -> Int { guard let repository else { return 0 } let added: Int do { - added = try await repository.importDives(dives) + let summary = try await repository.importDives(dives) + added = summary.added + summary.merged try await reload() } catch { try? await reload() @@ -323,28 +333,42 @@ final class AppModel { return added } - // MARK: Dives from Open Rémora + /// Merges dives of the logbook into one (see `LogRepository.mergeDives`). + func mergeDives(ids: Set<String>) async throws { + guard let repository else { return } + do { + logbook = try await repository.mergeDives(logbook.dives.filter { ids.contains($0.id) }) + pending = await repository.pending + } catch { + throw AppError.message(Self.describe(error)) + } + scheduleSync() + } + + // MARK: Dives from Open Rémora and Open Mérou - /// Folder where the Open Rémora iPhone app drops the dives from the watch (shared app group). - private var remoraFolder: URL? { - if let path = LaunchOptions.value("-remoraFolder") { return URL(fileURLWithPath: path) } + /// Folder where a companion app drops its dives (shared app group); `-remoraFolder` and `-merouFolder` point + /// elsewhere, for tests in the simulator. + private func sharedFolder(of source: SharedDiveSource) -> URL? { + if let path = LaunchOptions.value(Self.folderOption(of: source)) { return URL(fileURLWithPath: path) } return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: RemoraImport.appGroup)? - .appendingPathComponent(RemoraImport.folder, isDirectory: true) + .appendingPathComponent(source.folder, isDirectory: true) + } + + private static func folderOption(of source: SharedDiveSource) -> String { + source == .openMerou ? "-merouFolder" : "-remoraFolder" } - @ObservationIgnored private var importingFromRemora = false - - /// Adds the pending dives to the logbook, then removes their files from the shared folder. Nothing happens while - /// no logbook is open (or in the demo logbook, except for screenshots): the dives then stay pending on the - /// Open Rémora side. - func importFromOpenRemora() async { - guard phase == .ready, let repository, !importingFromRemora, let folder = remoraFolder else { return } - guard !isDemo || LaunchOptions.value("-remoraFolder") != nil else { return } - let files = RemoraImport.pendingFiles(in: folder) - guard !files.isEmpty else { return } - importingFromRemora = true - defer { importingFromRemora = false } - // The alarms of the watch are written into the dive notes, in the user's language. + @ObservationIgnored private var importingSharedDives = false + + /// Adds the dives waiting in the shared folders to the logbook, then removes their files. A dive that overlaps + /// one of the logbook joins it as one more dive computer. Nothing happens while no logbook is open (or in the + /// demo logbook, except for screenshots): the dives then stay pending on the side of the app that dropped them. + func importSharedDives() async { + guard phase == .ready, let repository, !importingSharedDives else { return } + importingSharedDives = true + defer { importingSharedDives = false } + // The alarms of the dive are written into the dive notes, in the user's language. let alarmLabels = [ "ascentFast": String(localized: "fast ascent"), "ascentTooFast": String(localized: "ascent too fast"), @@ -354,26 +378,38 @@ final class AppModel { "missedSafetyStop": String(localized: "missed safety stop"), ] let alarmsPrefix = String(localized: "Alarms: ") - var added = 0 - for file in files { - do { - let dive = try RemoraImport.dive(fromJSON: try Data(contentsOf: file), timeZone: .current, - alarmLabels: alarmLabels, alarmsPrefix: alarmsPrefix, - marksPrefix: String(localized: "Marks: ")) - added += try await repository.importDives([dive]) - RemoraImport.consume(file) // imported, or already in the logbook: it is no longer pending - } catch { - let name = file.lastPathComponent - let reason = Self.describe(error) - notices.append(String(localized: "Couldn't read the Open Rémora dive (\(name)): \(reason)")) + var changed = false + for source in SharedDiveSource.all { + guard !isDemo || LaunchOptions.value(Self.folderOption(of: source)) != nil, let folder = sharedFolder(of: source) else { continue } + let app = source.name + var total = ImportSummary() + for file in RemoraImport.pendingFiles(in: folder) { + do { + let dive = try RemoraImport.dive(fromJSON: try Data(contentsOf: file), timeZone: .current, defaultModel: source.name, + alarmLabels: alarmLabels, alarmsPrefix: alarmsPrefix, + marksPrefix: String(localized: "Marks: ")) + let summary = try await repository.importDives([dive]) + total.added += summary.added + total.merged += summary.merged + RemoraImport.consume(file) // imported, merged, or already in the logbook: it is no longer pending + } catch { + let name = file.lastPathComponent + let reason = Self.describe(error) + notices.append(String(localized: "Couldn't read the \(app) dive (\(name)): \(reason)")) + } + } + if total.added > 0 { + notices.append(total.added == 1 ? String(localized: "1 \(app) dive added to the logbook.") + : String(localized: "\(total.added) \(app) dives added to the logbook.")) } + if total.merged > 0 { + notices.append(total.merged == 1 ? String(localized: "1 \(app) dive merged with a dive already in the logbook.") + : String(localized: "\(total.merged) \(app) dives merged with dives already in the logbook.")) + } + changed = changed || total.added + total.merged > 0 } try? await reload() - if added > 0 { - notices.append(added == 1 ? String(localized: "1 Open Rémora dive added to the logbook.") - : String(localized: "\(added) Open Rémora dives added to the logbook.")) - scheduleSync() - } + if changed { scheduleSync() } } // MARK: Dives and sites that have photos diff --git a/App/Views/DiveDetailView.swift b/App/Views/DiveDetailView.swift @@ -222,8 +222,8 @@ struct DiveDetailView: View { .task(id: dive.computerBlobs.map(\.hex)) { let loaded = await model.profile(of: dive) computers = loaded - // By default, the computer with the most detailed profile. - computerIndex = loaded.indices.max(by: { loaded[$0].samples.count < loaded[$1].samples.count }) ?? 0 + // By default, the first computer: the primary one of a merged dive (or the first that has a profile). + computerIndex = loaded.firstIndex { $0.samples.count > 1 } ?? 0 loadedFor = dive.computerBlobs.map(\.hex) await loadPhotos(dive) } diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift @@ -10,11 +10,16 @@ struct DiveListView: View { @State private var downloading = false @State private var path: [String] = [] @State private var appliedLaunchOptions = false + // Merging: the list turns into a selection, then the selected dives become one. + @State private var selecting = false + @State private var selection = Set<String>() + @State private var confirmingMerge = false + @State private var error: String? var body: some View { NavigationStack(path: $path) { let sections = model.sections(matching: search) - List { + List(selection: $selection) { SyncBanner() ForEach(sections) { section in Section { @@ -45,7 +50,12 @@ struct DiveListView: View { ContentUnavailableView.search(text: search) } } - .navigationTitle("Dives") + .environment(\.editMode, .constant(selecting ? .active : .inactive)) + .navigationTitle(selecting + ? (selection.count == 1 ? String(localized: "1 dive selected") : String(localized: "\(selection.count) dives selected")) + : String(localized: "Dives")) + .navigationBarTitleDisplayMode(selecting ? .inline : .automatic) + .toolbar(selecting ? .hidden : .automatic, for: .tabBar) .navigationDestination(for: String.self) { DiveDetailView(diveID: $0) } .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Site, buddy, tag, notes") .refreshable { await model.sync() } @@ -54,15 +64,47 @@ struct DiveListView: View { if model.syncState == .syncing { ProgressView() } } ToolbarItem(placement: .topBarTrailing) { - Menu { - Button { adding = true } label: { Label("New dive", systemImage: "square.and.pencil") } - Button { downloading = true } label: { Label("Download from a dive computer…", systemImage: "gauge.with.dots.needle.bottom.50percent") } - Button { importing = true } label: { Label("Import a file…", systemImage: "square.and.arrow.down") } - } label: { - Label("Add", systemImage: "plus") + if selecting { + Button("Done") { stopSelecting() } + } else { + Menu { + Button { adding = true } label: { Label("New dive", systemImage: "square.and.pencil") } + Button { downloading = true } label: { Label("Download from a dive computer…", systemImage: "gauge.with.dots.needle.bottom.50percent") } + Button { importing = true } label: { Label("Import a file…", systemImage: "square.and.arrow.down") } + Divider() + Button { selecting = true } label: { Label("Merge dives…", systemImage: "arrow.triangle.merge") } + .disabled(model.logbook.dives.count < 2) + } label: { + Label("Add", systemImage: "plus") + } + } + } + if selecting { + ToolbarItem(placement: .bottomBar) { + Button("Merge") { confirmingMerge = true } + .disabled(selection.count < 2) } } } + .confirmationDialog(String(localized: "Merge \(selection.count) dives into one?"), isPresented: $confirmingMerge, titleVisibility: .visible) { + Button("Merge") { + Task { + do { + try await model.mergeDives(ids: selection) + stopSelecting() + } catch { + self.error = AppModel.describe(error) + } + } + } + } message: { + Text("The earliest dive keeps its date, number, site and notes; the others fill in what it lacks and add their dive computers. The merge will be sent to the Subsurface cloud at the next sync.") + } + .alert("Action failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { + Button("OK", role: .cancel) {} + } message: { + Text(error ?? "") + } .sheet(isPresented: $adding) { NewDiveView() } .task(id: model.logbook.dives.count) { await model.refreshPhotoPresence() } .modifier(FileImport(isPresented: $importing)) @@ -82,10 +124,21 @@ struct DiveListView: View { path = [dive.id] } if LaunchOptions.flag("-newDive") { adding = true } + // Screenshot option: the selection that precedes a merge, "-selectDives 12,13". + if let numbers = LaunchOptions.value("-selectDives")?.split(separator: ",").compactMap({ Int($0) }) { + selecting = true + selection = Set(model.logbook.dives.filter { numbers.contains($0.number) }.map(\.id)) + if LaunchOptions.flag("-merge") { confirmingMerge = true } + } } } } + private func stopSelecting() { + selecting = false + selection = [] + } + private func countLabel(_ count: Int) -> String { count == 1 ? String(localized: "1 dive") : String(localized: "\(count) dives") } diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift @@ -92,7 +92,7 @@ struct ImportSheet: View { Text(batch.name) } footer: { VStack(alignment: .leading, spacing: 8) { - Text("The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. Dives already in the logbook (same start time) are skipped.") + Text("The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. A dive that overlaps one already in the logbook joins it as one more dive computer; a dive the logbook already has from this computer is skipped.") if batch.fromComputer { // The logbook numbers the dives itself; the computer's own counter is not used. Text("Dives are numbered by the logbook, not by the computer. After this import, the next dive will be no. \(model.logbook.nextNumber + selected.count): set the computer's counter to it if you want both to match.") @@ -142,7 +142,7 @@ struct ImportSheet: View { Text(dive.site.isEmpty ? String(localized: "Unknown site") : dive.site) .font(.body.weight(.medium)) .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.primary) - Text(candidate.alreadyInLog ? String(localized: "\(date) · already in the logbook") : date) + Text(subtitle(candidate, date: date)) .font(.caption) .foregroundStyle(.secondary) } @@ -160,6 +160,13 @@ struct ImportSheet: View { .contentShape(Rectangle()) } + private func subtitle(_ candidate: AppModel.ImportCandidate, date: String) -> String { + if candidate.alreadyInLog { return String(localized: "\(date) · already in the logbook") } + // Dive numbers are identifiers: formatted as plain text so they never get a thousands separator. + if let number = candidate.mergesInto.map({ String($0) }) { return String(localized: "\(date) · will be merged with dive \(number)") } + return date + } + private func run() { let dives = batch.candidates.filter { selected.contains($0.id) }.map(\.dive) guard !dives.isEmpty else { return } diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift @@ -44,8 +44,13 @@ public enum LogChange: Codable, Sendable, Equatable { case addDive(NewDive) case deleteDive(when: Int, number: Int) case addSite(uuid: UInt32, name: String, latitude: Double?, longitude: Double?) - /// Dive coming from an external file, with its full profile. + /// Dive coming from an external file or from a dive computer, with its full profile. When the logbook already + /// has a dive at that time (overlapping time ranges), the dive joins it as one more dive computer and `number` + /// is not used; the very same dive from the very same computer is refused (`diveAlreadyExists`). case importDive(ImportedDive, number: Int, siteUUID: UInt32?) + /// Merges `others` into the dive `when`/`number`, which keeps its date, number and everything it has; see + /// `LogEditor.merged`. Dives that are gone by the time the change is replayed are left out. + case mergeDives(when: Int, number: Int, others: [DiveRef]) /// Changes nothing except adding the settings file if it is missing. case ensureSettings /// Sets or replaces the position of an existing site; the rest of its record is kept. @@ -67,6 +72,8 @@ public enum LogChange: Codable, Sendable, Equatable { case .removeSite: return "site removed" case .renumberDive(_, let number, let newNumber): return "dive \(number) renumbered \(newNumber)" case .importDive(let dive, let number, _): return "dive \(number) imported (\(dive.model))" + case .mergeDives(_, let number, let others): + return "dive \(number) merged with \(others.map { String($0.number) }.joined(separator: ", "))" } } } @@ -78,7 +85,7 @@ public enum ChangeError: Error, Equatable, CustomStringConvertible { public var description: String { switch self { case .diveNotFound: return "the dive no longer exists in the logbook" - case .diveAlreadyExists: return "a dive already exists at this date and time" + case .diveAlreadyExists: return "this dive is already in the logbook" } } } @@ -333,15 +340,10 @@ public enum LogEditor { } case .importDive(let dive, let number, let siteUUID): - if try LogWalker.find(when: dive.when, number: nil, root: current, store: store) != nil { - throw ChangeError.diveAlreadyExists(dive.when) - } - let diveBlob = try store.putBlob(diveFile(dive, siteUUID: siteUUID)) - let computerBlob = try store.putBlob(computerFile(dive)) - let name = number > 0 ? "Dive-\(number)" : "Dive" - let tree = try store.putTree([.blob(name, diveBlob), .blob("Divecomputer", computerBlob)]) - let path = divePath(when: dive.when) - result = try replacing(root: current, path: path, with: .tree(path.last!, tree), store: store) + result = try importing(dive, number: number, siteUUID: siteUUID, root: current, store: store) + + case .mergeDives(let when, let number, let others): + result = try merging(others, into: DiveRef(when: when, number: number), root: current, store: store) case .deleteDive(let when, let number): guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store) else { diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift @@ -49,50 +49,7 @@ public struct ImportedDive: Codable, Sendable, Equatable, Identifiable { public var maxDepth: Double { samples.map(\.depth).max() ?? 0 } public var minTemperature: Double? { samples.compactMap(\.temperature).min() } - /// Joins several closely spaced immersions into a single dive, like Subsurface's merge: the profiles - /// follow one another on the same timeline, separated by their surface interval. The duration is the time spent - /// underwater; site, buddy and notes come from the first immersion that has them. - public static func merged(_ dives: [ImportedDive]) -> ImportedDive? { - let ordered = dives.sorted { $0.when < $1.when } - guard var result = ordered.first else { return nil } - guard ordered.count > 1 else { return result } - result.durationSeconds = ordered.reduce(0) { $0 + $1.durationSeconds } - result.sourceID = ordered.map(\.sourceID).joined(separator: "+") - result.site = ordered.map(\.site).first { !$0.isEmpty } ?? "" - result.latitude = ordered.compactMap(\.latitude).first - result.longitude = ordered.compactMap(\.longitude).first - result.buddy = ordered.map(\.buddy).first { !$0.isEmpty } ?? "" - result.notes = ordered.map(\.notes).filter { !$0.isEmpty }.joined(separator: "\n") - var samples = [Sample]() - for dive in ordered { - let offset = dive.when - result.when - if let last = samples.last, let first = dive.samples.first { - // Back to the surface after the previous immersion, then at the surface until the next one starts. - var up = last - up.time = last.time + 10 - up.depth = 0 - up.pressure1 = nil - up.pressure2 = nil - up.stopDepth = 0 - var down = up - down.time = max(up.time + 10, offset) - down.o2 = first.o2 - down.he = first.he - if up.time < offset + first.time { samples.append(up) } - if down.time < offset + first.time { samples.append(down) } - } - for sample in dive.samples { - var shifted = sample - shifted.time += offset - if let last = samples.last, shifted.time <= last.time { continue } - samples.append(shifted) - } - } - result.samples = samples - return result - } - - /// Mean depth underwater (the surface intervals of a merged dive do not count). + /// Mean depth underwater. public var meanDepth: Double { let wet = samples.filter { $0.depth > 0 } return wet.isEmpty ? 0 : wet.reduce(0) { $0 + $1.depth } / Double(wet.count) diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Loader.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Loader.swift @@ -175,7 +175,8 @@ public enum LogLoader { return site } - private static func loadDive(_ directory: DiveDirectory, store: ObjectStore, log: inout Logbook) throws -> Dive { + /// `withSamples` also reads the profiles, which gives each computer its real duration. + static func loadDive(_ directory: DiveDirectory, store: ObjectStore, log: inout Logbook, withSamples: Bool = false) throws -> Dive { var dive = Dive(when: directory.when) dive.path = directory.path dive.tripID = directory.tripID @@ -184,7 +185,7 @@ public enum LogLoader { for entry in try store.tree(directory.tree) where !entry.isTree { if entry.name.hasPrefix("Divecomputer") { dive.computerBlobs.append(entry.id) - dive.computers.append(parseComputer(try store.blob(entry.id), withSamples: false)) + dive.computers.append(parseComputer(try store.blob(entry.id), withSamples: withSamples, diveWhen: directory.when)) } else if let number = LogWalker.diveNumber(fileName: entry.name) { dive.number = number dive.diveFile = entry.name @@ -269,9 +270,12 @@ public enum LogLoader { } } - static func parseComputer(_ data: [UInt8], withSamples: Bool) -> DiveComputer { + /// `diveWhen` is the start of the dive: a computer that started at another time says so with its own + /// `date` and `time` lines (several computers on one dive), and `when` is then filled in. + static func parseComputer(_ data: [UInt8], withSamples: Bool, diveWhen: Int? = nil) -> DiveComputer { var dc = DiveComputer() var previous: Sample? + var date: [Int]?, time: [Int]? for line in LogFormat.lines(data, skipSamples: !withSamples) { guard let first = line.text.utf8.first else { continue } if first == 0x20 || (first >= 0x30 && first <= 0x39) { @@ -285,6 +289,8 @@ public enum LogLoader { case "model": dc.model = line.strings.first ?? "" case "deviceid": dc.deviceID = String(arg) case "diveid": dc.diveID = String(arg) + case "date": date = arg.split(separator: "-").compactMap { Int($0) } + case "time": time = arg.split(separator: ":").compactMap { Int($0) } case "duration": dc.durationSeconds = LogFormat.duration(arg) case "dctype": dc.diveMode = String(arg) case "maxdepth": dc.maxDepth = LogFormat.number(arg) @@ -304,6 +310,12 @@ public enum LogLoader { if dc.maxDepth == nil { dc.maxDepth = dc.samples.map(\.depth).max() } if dc.durationSeconds == nil { dc.durationSeconds = last.time } } + if date?.count == 3 || time?.count == 3, let diveWhen { + let base = NaiveTime.components(diveWhen) + let d = date?.count == 3 ? date! : [base.year!, base.month!, base.day!] + let t = time?.count == 3 ? time! : [base.hour!, base.minute!, base.second!] + dc.when = NaiveTime.timestamp(year: d[0], month: d[1], day: d[2], hour: t[0], minute: t[1], second: t[2]) + } return dc } @@ -381,6 +393,6 @@ public enum LogLoader { /// Loads the full profiles of the computers of a dive. public static func loadProfile(of dive: Dive, store: ObjectStore) throws -> [DiveComputer] { - try dive.computerBlobs.map { parseComputer(try store.blob($0), withSamples: true) } + try dive.computerBlobs.map { parseComputer(try store.blob($0), withSamples: true, diveWhen: dive.when) } } } diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Merge.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Merge.swift @@ -0,0 +1,535 @@ +// SPDX-License-Identifier: GPL-2.0-only +import Foundation +import GitLite + +/// A dive of the logbook, the way changes point at it. +public struct DiveRef: Codable, Sendable, Equatable, Hashable { + public var when: Int + public var number: Int + + public init(when: Int, number: Int) { + self.when = when + self.number = number + } +} + +/// Rules for dives recorded by several dive computers. A merged dive is ONE dive with several dive computers, as +/// Subsurface stores it (`Divecomputer-001`, `Divecomputer-002`…): the first one is the primary computer, whose +/// profile and values are shown by default. +public enum DiveMerge { + /// Place of a dive computer in a merged dive, lowest first: Open Rémora (the primary computer), then any other + /// dive computer (a Petrel…), then Open Mérou, then the made-up profile of a dive entered by hand. + public static func rank(model: String) -> Int { + let name = model.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) + if name.hasPrefix("open remora") { return 0 } + if name.hasPrefix("open merou") { return 2 } + if name == "manually added dive" { return 3 } + return 1 + } + + /// Same model, and serial numbers that do not contradict each other (a missing one matches anything; the same + /// number is written in hexadecimal by some sources and in decimal by others). + public static func sameComputer(model: String, serial: String, as otherModel: String, serial otherSerial: String) -> Bool { + func fold(_ text: String) -> String { + text.trimmingCharacters(in: .whitespaces).folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) + } + guard fold(model) == fold(otherModel) else { return false } + let a = String(fold(serial).drop { $0 == "0" }), b = String(fold(otherSerial).drop { $0 == "0" }) + if a.isEmpty || b.isEmpty || a == b { return true } + if let hex = Int(a, radix: 16), hex == Int(b) { return true } + if let hex = Int(b, radix: 16), hex == Int(a) { return true } + return false + } + + /// Seconds shared by two time ranges; nil when they do not meet (ranges that just touch share 0 seconds). + public static func overlap(_ a: ClosedRange<Int>, _ b: ClosedRange<Int>) -> Int? { + let shared = min(a.upperBound, b.upperBound) - max(a.lowerBound, b.lowerBound) + return shared >= 0 ? shared : nil + } + + public enum Disposition: Equatable, Sendable { + /// No dive of the logbook at that time: the dive is added. + case new + /// The logbook already has this dive from this very computer: nothing to do. + case duplicate(Dive) + /// The logbook has a dive at that time, recorded by something else: the incoming dive joins it as one more + /// dive computer. + case merge(Dive) + } + + /// What importing `incoming` does to a logbook holding `dives`. + /// + /// The rule is the overlap of the [start, end] ranges, not the start time: each device notices the submersion + /// at its own moment. Among several overlapping dives, the one sharing the most time wins. A computer already + /// on an overlapping dive (same model and serial, its own recording overlapping too) makes it a re-import. + public static func disposition(of incoming: ImportedDive, among dives: [Dive]) -> Disposition { + let range = incoming.when...(incoming.when + max(incoming.durationSeconds, incoming.samples.last?.time ?? 0, 0)) + var best: (dive: Dive, shared: Int)? + for dive in dives { + guard let shared = overlap(range, dive.timeRange) else { continue } + for computer in dive.computers + where sameComputer(model: computer.model, serial: computer.serial, as: incoming.model, serial: incoming.serial) + && overlap(range, computer.timeRange(in: dive)) != nil { + return .duplicate(dive) + } + if let current = best, (current.shared, -abs(current.dive.when - incoming.when)) >= (shared, -abs(dive.when - incoming.when)) { continue } + best = (dive, shared) + } + return best.map { .merge($0.dive) } ?? .new + } +} + +/// A "Divecomputer" file handled as text: merging moves computers between dives without decoding them, so the +/// lines this app does not know about survive, and a file that needs no change keeps its bytes (and its git blob). +struct ComputerFile { + struct Line { + var keyword: String + var bytes: [UInt8] + } + + /// The file as it was read, until something changes it. + private var original: [UInt8]? + private(set) var header: [Line] = [] + private(set) var events: [[UInt8]] = [] + private(set) var samples: [[UInt8]] = [] + private(set) var model = "" + private(set) var serial = "" + /// Start of the recording, naive local time. + private(set) var start: Int + /// Dive time: the `duration` line, else the time of the last sample, else the duration of the dive it came with. + private(set) var duration: Int + private var hasOwnStart = false + + init(_ data: [UInt8], diveWhen: Int, diveDuration: Int) { + original = data + start = diveWhen + var date: [Int]?, time: [Int]?, explicit: Int? + for line in LogFormat.lines(data) { + var bytes = Array(data[line.range]) + if bytes.last != 0x0a { bytes.append(0x0a) } + guard let first = bytes.first else { continue } + if first == 0x20 || (first >= 0x30 && first <= 0x39) { + samples.append(bytes) + continue + } + let keyword = String(line.keyword) + if keyword == "event" { + events.append(bytes) + continue + } + header.append(Line(keyword: keyword, bytes: bytes)) + switch keyword { + case "model": model = line.strings.first ?? "" + case "keyvalue": if line.strings.count == 2, line.strings[0] == "Serial" { serial = line.strings[1] } + case "date": date = line.argument.split(separator: "-").compactMap { Int($0) } + case "time": time = line.argument.split(separator: ":").compactMap { Int($0) } + case "duration": explicit = LogFormat.duration(line.argument) + default: break + } + } + if date?.count == 3 || time?.count == 3 { + let base = NaiveTime.components(diveWhen) + let d = date?.count == 3 ? date! : [base.year!, base.month!, base.day!] + let t = time?.count == 3 ? time! : [base.hour!, base.minute!, base.second!] + if let own = NaiveTime.timestamp(year: d[0], month: d[1], day: d[2], hour: t[0], minute: t[1], second: t[2]) { + start = own + hasOwnStart = true + } + } + duration = diveDuration + duration = explicit ?? lastSampleTime ?? diveDuration + } + + var bytes: [UInt8] { + original ?? (header.flatMap(\.bytes) + events.flatMap { $0 } + samples.flatMap { $0 }) + } + + var lastSampleTime: Int? { samples.last.map(Self.sampleTime) } + /// End of the recording (a profile joined from several immersions lasts longer than its dive time). + var end: Int { start + max(duration, lastSampleTime ?? 0) } + + // MARK: Lines + + private static func text(_ bytes: [UInt8]) -> String { + var text = String(decoding: bytes, as: UTF8.self) + if text.hasSuffix("\n") { text.removeLast() } + return text + } + + /// " 1:30 12.0m …": the time, in seconds. + static func sampleTime(_ line: [UInt8]) -> Int { + let trimmed = text(line).drop { $0 == " " } + return LogFormat.duration(trimmed.prefix { $0 != " " }) + } + + private static func sample(_ line: [UInt8], shiftedBy offset: Int) -> [UInt8] { + let trimmed = text(line).drop { $0 == " " } + let token = trimmed.prefix { $0 != " " } + let time = LogFormat.duration(token) + offset + return Array("\(String(format: "%3d:%02d", time / 60, time % 60))\(trimmed.dropFirst(token.count))\n".utf8) + } + + /// "event 12:10 type=3 …" + private static func event(_ line: [UInt8], shiftedBy offset: Int) -> [UInt8] { + let rest = text(line).dropFirst("event".count).drop { $0 == " " } + let token = rest.prefix { $0 != " " } + return Array("event \(LogFormat.minutes(LogFormat.duration(token) + offset))\(rest.dropFirst(token.count))\n".utf8) + } + + /// Last value written for a key of the samples (they only say what changes). + private func lastSampleValue(_ key: String) -> Substring? { + let prefix = key + "=" + for line in samples.reversed() { + for token in Self.text(line).split(separator: " ") where token.hasPrefix(prefix) { + return token.dropFirst(prefix.count) + } + } + return nil + } + + private func headerNumber(_ keyword: String) -> Double? { + header.first { $0.keyword == keyword }.map { LogFormat.number(Self.text($0.bytes).dropFirst(keyword.count)) } + } + + private mutating func setHeader(_ keyword: String, _ line: String, before: Set<String> = []) { + let bytes = Array((line + "\n").utf8) + if let index = header.firstIndex(where: { $0.keyword == keyword }) { + header[index].bytes = bytes + } else { + // Subsurface writes: model, lastmanualtime, deviceid, diveid, date, time, duration, then the rest. + let index = before.isEmpty ? header.count : (header.firstIndex { !before.contains($0.keyword) } ?? header.count) + header.insert(Line(keyword: keyword, bytes: bytes), at: index) + } + original = nil + } + + // MARK: Changes + + /// A computer that did not start with the dive it now belongs to says when it did (`date` and `time` lines). + mutating func anchor(toDiveAt diveWhen: Int) { + guard start != diveWhen, !hasOwnStart else { return } + let c = NaiveTime.components(start) + let identity: Set<String> = ["model", "lastmanualtime", "deviceid", "diveid"] + setHeader("date", String(format: "date %04d-%02d-%02d", c.year!, c.month!, c.day!), before: identity) + setHeader("time", String(format: "time %02d:%02d:%02d", c.hour!, c.minute!, c.second!), before: identity.union(["date"])) + hasOwnStart = true + } + + /// The cylinders of a dive are numbered in its "Dive" file; a computer moved to another dive follows the new numbers. + mutating func remapCylinders(_ map: [Int: Int]) { + guard map.contains(where: { $0.key != $0.value }) else { return } + events = events.map { line in + let text = Self.text(line) + let isGasChange = text.contains("name=\"gaschange") + let tokens = text.split(separator: " ", omittingEmptySubsequences: false).map { token -> String in + if token.hasPrefix("cylinder="), let old = Int(token.dropFirst(9)), let new = map[old] { return "cylinder=\(new)" } + // Older files carry the cylinder in the flags of a gas change, counted from 1. + if isGasChange, token.hasPrefix("flags="), let old = Int(token.dropFirst(6)), old > 0, let new = map[old - 1] { return "flags=\(new + 1)" } + return String(token) + } + return Array((tokens.joined(separator: " ") + "\n").utf8) + } + samples = samples.map { line in + let text = Self.text(line) + guard text.contains("bar:") else { return line } + let tokens = text.split(separator: " ", omittingEmptySubsequences: false).map { token -> String in + guard let marker = token.range(of: "bar:"), let old = Int(token[marker.upperBound...]), let new = map[old] else { return String(token) } + return "\(token[..<marker.upperBound])\(new)" + } + return Array((tokens.joined(separator: " ") + "\n").utf8) + } + original = nil + } + + /// Joins a later immersion recorded by the same computer: the profiles follow one another on the same timeline, + /// separated by their surface interval, like Subsurface's merge. The dive time is the time spent underwater. + mutating func append(_ next: ComputerFile) { + let offset = next.start - start + var last = lastSampleTime + if let surfaced = last, let first = next.samples.first.map(Self.sampleTime) { + // Back to the surface after this immersion, then at the surface until the next one starts. Samples only + // say what changes: what the deco state was is cleared, so that it does not leak into the next immersion. + var resets = "" + if let tts = lastSampleValue("tts"), LogFormat.duration(tts) != 0 { resets += " tts=0:00" } + if let deco = lastSampleValue("in_deco"), LogFormat.integer(deco) != 0 { resets += " in_deco=0" } + if let time = lastSampleValue("stoptime"), LogFormat.duration(time) != 0 { resets += " stoptime=0:00" } + if let depth = lastSampleValue("stopdepth"), LogFormat.number(depth) != 0 { resets += " stopdepth=0.0m" } + let up = surfaced + 10 + let down = max(up + 10, offset) + for (time, extra) in [(up, resets), (down, "")] where time < offset + first { + samples.append(Array((String(format: "%3d:%02d", time / 60, time % 60) + " 0.0m" + extra + "\n").utf8)) + last = time + } + } + for line in next.samples { + let time = Self.sampleTime(line) + offset + if let last, time <= last { continue } + samples.append(Self.sample(line, shiftedBy: offset)) + last = time + } + events += next.events.map { Self.event($0, shiftedBy: offset) } + + if let a = headerNumber("maxdepth"), let b = next.headerNumber("maxdepth") { + setHeader("maxdepth", "maxdepth \(LogFormat.milli(max(a, b)))m") + } + if let a = headerNumber("meandepth"), let b = next.headerNumber("meandepth"), duration + next.duration > 0 { + let mean = (a * Double(duration) + b * Double(next.duration)) / Double(duration + next.duration) + setHeader("meandepth", "meandepth \(LogFormat.milli(mean))m") + } + if let a = headerNumber("watertemp"), let b = next.headerNumber("watertemp") { + setHeader("watertemp", "watertemp \(LogFormat.milli(min(a, b)))°C") + } + for line in next.header where line.keyword == "keyvalue" && !header.contains(where: { $0.bytes == line.bytes }) { + header.append(line) + } + duration += next.duration + setHeader("duration", "duration \(LogFormat.minutes(duration)) min", before: ["model", "lastmanualtime", "deviceid", "diveid", "date", "time"]) + original = nil + } +} + +/// What makes a dive in the git tree, as text. +struct DiveParts { + var when: Int + var diveFile: [UInt8] + var computers: [ComputerFile] +} + +extension LogEditor { + private struct FileLine { + var keyword: String + var line: LogLine + var bytes: [UInt8] + + init?(_ bytes: [UInt8]) { + guard let line = LogFormat.lines(bytes).first else { return nil } + self.keyword = String(line.keyword) + self.line = line + self.bytes = bytes.last == 0x0a ? bytes : bytes + [0x0a] + } + + var text: String? { line.strings.first } + var pairs: [(key: String, value: String)] { LogFormat.keyValues(line.argument, strings: line.strings) } + var gas: GasMix { + var gas = GasMix() + for (key, value) in pairs { + if key == "o2" { gas.o2Permille = Int((LogFormat.number(value) * 10).rounded()) } + if key == "he" { gas.hePermille = Int((LogFormat.number(value) * 10).rounded()) } + } + return gas + } + } + + private static func fileLines(_ data: [UInt8]) -> [FileLine] { + LogFormat.lines(data).compactMap { FileLine(Array(data[$0.range])) } + } + + /// Fills the gaps of a "Dive" file from the one of a dive merged into it. Nothing of the target changes; the + /// source brings what the target lacks: a field that is missing or empty, its notes (appended), its tags and + /// buddies (added to the lists), its cylinders (matched by gas mix, else added) and any line the target has no + /// equivalent of. Returns the file and where each cylinder of the source ended up. + static func fill(diveFile target: [UInt8], from source: [UInt8]) -> (file: [UInt8], cylinders: [Int: Int]) { + var lines = fileLines(target) + func rank(_ keyword: String) -> Int { order.firstIndex(of: keyword) ?? order.count } + func insert(_ line: FileLine) { + lines.insert(line, at: lines.firstIndex { rank($0.keyword) > rank(line.keyword) } ?? lines.count) + } + func set(_ keyword: String, _ text: String?) { + guard let text, let line = FileLine(Array(text.utf8)) else { return } + if let index = lines.firstIndex(where: { $0.keyword == keyword }) { lines[index] = line } else { insert(line) } + } + func names(_ text: String) -> [String] { + text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + } + func union(_ a: [String], _ b: [String]) -> [String] { + a + b.filter { new in !a.contains { $0.compare(new, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame } } + } + let hadWeights = lines.contains { $0.keyword == "weightsystem" } + let hadSite = lines.contains { ["divesiteid", "location", "gps"].contains($0.keyword) } + var cylinders = [Int: Int]() + var taken = Set<Int>() + var sourceCylinder = 0 + + for line in fileLines(source) { + let existing = lines.first { $0.keyword == line.keyword } + switch line.keyword { + case "duration": + break + case "cylinder": + let slots = lines.indices.filter { lines[$0].keyword == "cylinder" } + let gas = line.gas + if let slot = slots.indices.first(where: { !taken.contains($0) && (lines[slots[$0]].gas == gas || (lines[slots[$0]].gas.isAir && gas.isAir)) }) { + // Same gas: the same cylinder. The richer description wins when it only adds to the other. + let known = Set(lines[slots[slot]].pairs.map(\.key)), offered = Set(line.pairs.map(\.key)) + if known.isStrictSubset(of: offered) { lines[slots[slot]] = line } + cylinders[sourceCylinder] = slot + taken.insert(slot) + } else { + insert(line) + cylinders[sourceCylinder] = slots.count + taken.insert(slots.count) + } + sourceCylinder += 1 + case "weightsystem": + if !hadWeights { insert(line) } + case "notes": + let mine = existing?.text ?? "", theirs = line.text ?? "" + if mine.isEmpty { set("notes", LogEditor.line(.notes, theirs)) } + else if !theirs.isEmpty, !mine.contains(theirs) { set("notes", LogEditor.line(.notes, mine + "\n" + theirs)) } + case "tags": + set("tags", LogEditor.line(.tags, union(existing?.line.strings ?? [], line.line.strings).joined(separator: ","))) + case "buddy", "divemaster": + let all = union(names(existing?.text ?? ""), names(line.text ?? "")) + if !all.isEmpty { set(line.keyword, "\(line.keyword) \(LogFormat.quote(all.joined(separator: ", ")))\n") } + case "divesiteid", "location", "gps": + // One site per dive, whatever the way it is written. + if !hadSite { insert(line) } + default: + if let existing { + if existing.line.strings == [""], let index = lines.firstIndex(where: { $0.keyword == line.keyword }) { lines[index] = line } + } else { + insert(line) + } + } + } + return (lines.flatMap(\.bytes), cylinders) + } + + static func duration(ofDiveFile data: [UInt8]) -> Int { + LogFormat.lines(data).first { $0.keyword == "duration" }.map { LogFormat.duration($0.argument) } ?? 0 + } + + static func setting(duration seconds: Int, inDiveFile data: [UInt8]) -> [UInt8] { + var lines = fileLines(data) + guard let line = FileLine(Array("duration \(LogFormat.minutes(seconds)) min\n".utf8)) else { return data } + if let index = lines.firstIndex(where: { $0.keyword == "duration" }) { lines[index] = line } else { lines.insert(line, at: 0) } + return lines.flatMap(\.bytes) + } + + /// Merges dives into `target`, which keeps its date, number, site, notes and everything else it has; the others + /// fill its gaps (see `fill`). Every dive computer is kept: the same computer on successive immersions becomes + /// one profile on one timeline, different computers stay side by side, ordered by `DiveMerge.rank`. The + /// duration of the dive is the longest of its computers', as Subsurface computes it. + static func merged(_ target: DiveParts, with others: [DiveParts]) -> (diveFile: [UInt8], computers: [[UInt8]]) { + var file = target.diveFile + var computers = [ComputerFile]() + func add(_ computer: ComputerFile) { + for index in computers.indices + where DiveMerge.sameComputer(model: computers[index].model, serial: computers[index].serial, as: computer.model, serial: computer.serial) { + if computers[index].end < computer.start { + computers[index].append(computer) + return + } + if computer.end < computers[index].start { + var earlier = computer + earlier.append(computers[index]) + computers[index] = earlier + return + } + } + computers.append(computer) + } + target.computers.forEach(add) + for other in others.sorted(by: { $0.when < $1.when }) { + let filled = fill(diveFile: file, from: other.diveFile) + file = filled.file + for var computer in other.computers { + computer.remapCylinders(filled.cylinders) + add(computer) + } + } + // The existing order is kept among computers of the same rank. + var ordered = computers.enumerated().sorted { + (DiveMerge.rank(model: $0.element.model), $0.offset) < (DiveMerge.rank(model: $1.element.model), $1.offset) + }.map(\.element) + for index in ordered.indices { ordered[index].anchor(toDiveAt: target.when) } + if let longest = ordered.map(\.duration).max(), longest > 0 { file = setting(duration: longest, inDiveFile: file) } + return (file, ordered.map(\.bytes)) + } + + // MARK: In the tree + + private static func isComputer(_ entry: TreeEntry) -> Bool { !entry.isTree && entry.name.hasPrefix("Divecomputer") } + private static func isDiveFile(_ entry: TreeEntry) -> Bool { !entry.isTree && LogWalker.diveNumber(fileName: entry.name) != nil } + + static func parts(of directory: DiveDirectory, store: ObjectStore) throws -> DiveParts { + let entries = try store.tree(directory.tree) + let file = try entries.first(where: isDiveFile).map { try store.blob($0.id) } ?? [] + let duration = duration(ofDiveFile: file) + let computers = try entries.filter(isComputer).map { + ComputerFile(try store.blob($0.id), diveWhen: directory.when, diveDuration: duration) + } + return DiveParts(when: directory.when, diveFile: file, computers: computers) + } + + /// Rewrites the directory of `target` as the merge of it and `others`: its "Dive" file keeps its name (hence + /// its number), the computers are renumbered `Divecomputer-001…` (a single one is plain `Divecomputer`), and + /// whatever else the directories hold (pictures) is kept. + static func merging(_ others: [DiveParts], extra: [TreeEntry] = [], into target: DiveDirectory, root: ObjectID, store: ObjectStore) throws -> ObjectID? { + let entries = try store.tree(target.tree) + let result = merged(try parts(of: target, store: store), with: others) + let fileName = entries.first(where: isDiveFile)?.name ?? "Dive" + var kept = entries.filter { !isComputer($0) && $0.name != fileName } + kept += extra.filter { new in !isComputer(new) && !isDiveFile(new) && !kept.contains { $0.name == new.name } } + kept.append(.blob(fileName, try store.put(GitObject(type: .blob, data: result.diveFile)))) + for (index, bytes) in result.computers.enumerated() { + let name = result.computers.count == 1 ? "Divecomputer" : String(format: "Divecomputer-%03d", index + 1) + kept.append(.blob(name, try store.put(GitObject(type: .blob, data: bytes)))) + } + return try replacing(root: root, path: target.path, with: .tree(target.path.last!, try store.putTree(kept)), store: store) + } + + /// What importing a dive does to the logbook at `root` (see `DiveMerge.disposition`), with the directory of the + /// dive it meets. Only the dives around that time are read, profiles included, to know when each computer stopped. + static func disposition(of dive: ImportedDive, root: ObjectID, store: ObjectStore) throws -> (DiveMerge.Disposition, DiveDirectory?) { + let end = dive.when + max(dive.durationSeconds, dive.samples.last?.time ?? 0) + let near = try LogWalker.diveDirectories(root: root, store: store).filter { $0.when <= end && $0.when >= dive.when - 2 * 86_400 } + var scratch = Logbook() + let dives = near.compactMap { try? LogLoader.loadDive($0, store: store, log: &scratch, withSamples: true) } + let disposition = DiveMerge.disposition(of: dive, among: dives) + switch disposition { + case .new: return (disposition, nil) + case .duplicate(let found), .merge(let found): return (disposition, near.first { $0.path == found.path }) + } + } + + /// `.importDive`: a new directory, or one more computer on the dive already there at that time. + static func importing(_ dive: ImportedDive, number: Int, siteUUID: UInt32?, root: ObjectID, store: ObjectStore) throws -> ObjectID? { + let diveText = diveFile(dive, siteUUID: siteUUID) + let computerText = computerFile(dive) + switch try disposition(of: dive, root: root, store: store) { + case (.duplicate, _): + throw ChangeError.diveAlreadyExists(dive.when) + case (.merge, let directory?): + let computer = ComputerFile(Array(computerText.utf8), diveWhen: dive.when, diveDuration: dive.durationSeconds) + let incoming = DiveParts(when: dive.when, diveFile: Array(diveText.utf8), computers: [computer]) + return try merging([incoming], into: directory, root: root, store: store) + default: + let name = number > 0 ? "Dive-\(number)" : "Dive" + let tree = try store.putTree([.blob(name, try store.putBlob(diveText)), .blob("Divecomputer", try store.putBlob(computerText))]) + let path = divePath(when: dive.when) + return try replacing(root: root, path: path, with: .tree(path.last!, tree), store: store) + } + } + + /// `.mergeDives`: the other dives join the target and their directories go away. Dives that are no longer + /// there are left out; with none of them left there is nothing to merge. + static func merging(_ others: [DiveRef], into target: DiveRef, root: ObjectID, store: ObjectStore) throws -> ObjectID? { + guard let directory = try LogWalker.find(when: target.when, number: target.number, root: root, store: store) else { + throw ChangeError.diveNotFound(target.when) + } + var sources = [DiveDirectory]() + for other in others { + guard let found = try LogWalker.find(when: other.when, number: other.number, root: root, store: store), + found.path != directory.path, !sources.contains(where: { $0.path == found.path }) else { continue } + sources.append(found) + } + guard !sources.isEmpty else { throw ChangeError.diveNotFound(others.first?.when ?? target.when) } + let extra = try sources.flatMap { try store.tree($0.tree) } + var result = try merging(try sources.map { try parts(of: $0, store: store) }, extra: extra, into: directory, root: root, store: store) + for source in sources { + result = try replacing(root: result, path: source.path, with: nil, store: store) + } + return result + } +} diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Model.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Model.swift @@ -81,6 +81,9 @@ public struct DiveEvent: Sendable, Equatable { public struct DiveComputer: Sendable, Equatable { public var model = "" + /// Start of this computer's profile (naive local time) when it differs from the dive's: several computers on + /// one dive do not notice the submersion at the same moment. + public var when: Int? public var deviceID: String? public var diveID: String? public var durationSeconds: Int? @@ -97,6 +100,13 @@ public struct DiveComputer: Sendable, Equatable { public init() {} public var isManual: Bool { model == "manually added dive" } + public var serial: String { extra.first { $0.key == "Serial" }?.value ?? "" } + + /// From the start to the end of this computer's recording, on a dive that starts at `dive.when`. + public func timeRange(in dive: Dive) -> ClosedRange<Int> { + let start = when ?? dive.when + return start...(start + max(durationSeconds ?? dive.durationSeconds, samples.last?.time ?? 0, 0)) + } } public struct KeyValue: Sendable, Equatable { @@ -170,6 +180,16 @@ public struct Dive: Sendable, Equatable, Identifiable { public var computerModel: String? { computers.first(where: { !$0.model.isEmpty && !$0.isManual })?.model } public var isManual: Bool { computers.allSatisfy { $0.isManual } } + /// From the earliest start to the latest end of what the dive and its computers recorded. + public var timeRange: ClosedRange<Int> { + var range = when...(when + max(durationSeconds, 0)) + for computer in computers { + let own = computer.timeRange(in: self) + range = min(range.lowerBound, own.lowerBound)...max(range.upperBound, own.upperBound) + } + return range + } + /// Surface air consumption, in litres per minute (ideal gas, cylinders with volume and pressures filled in). public var sac: Double? { guard durationSeconds > 0, let mean = meanDepth, mean > 0 else { return nil } diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/RemoraImport.swift b/Packages/DiveKit/Sources/SubsurfaceLog/RemoraImport.swift @@ -1,12 +1,27 @@ // SPDX-License-Identifier: GPL-2.0-only import Foundation -/// Dives dropped by Open Rémora (a dive computer for Apple Watch) into the shared folder of the app group. -/// Contract: `docs/PARTAGE.md` in the open-remora repository. The JSON (`DiveLog` from RemoraDeco) is read without +/// An app that drops its dives into the app group shared with this one: a folder holding, for each dive, +/// `<uuid>.json` (the `DiveLog` of RemoraDeco) and `<uuid>.uddf`. +public struct SharedDiveSource: Sendable, Equatable { + /// Name of the app; also the dive computer model of a dive that does not give one. + public let name: String + /// Folder inside the app group container. + public let folder: String + + /// Open Rémora, a dive computer for Apple Watch. + public static let openRemora = SharedDiveSource(name: "Open Rémora", folder: "OpenRemora/Plongees") + /// Open Mérou, the app of an iPhone underwater housing. + public static let openMerou = SharedDiveSource(name: "Open Mérou", folder: "OpenMerou/Dives") + public static let all = [openRemora, openMerou] +} + +/// Dives dropped by Open Rémora and Open Mérou into the shared folders of the app group. +/// Contract: `docs/SHARING.md` in the open-remora repository. The JSON (`DiveLog` from RemoraDeco) is read without /// depending on that package: only the fields useful to the logbook are decoded, the others are ignored. public enum RemoraImport { public static let appGroup = "group.org.schurger.dive" - public static let folder = "OpenRemora/Plongees" + public static let folder = SharedDiveSource.openRemora.folder struct Log: Decodable { struct Gas: Decodable { let o2: Double } @@ -51,7 +66,8 @@ public enum RemoraImport { /// The alarms are appended to the notes as `alarmsPrefix` followed by "m:ss label" entries; `alarmLabels` maps /// each warning identifier to its label (an identifier missing from the dictionary is written as is). /// The points marked by the diver follow, as `marksPrefix` and "m:ss depth heading" entries. - public static func dive(fromJSON data: Data, timeZone: TimeZone = .current, + /// `defaultModel` names the dive computer of a dive whose JSON has no `computerModel`. + public static func dive(fromJSON data: Data, timeZone: TimeZone = .current, defaultModel: String = SharedDiveSource.openRemora.name, alarmLabels: [String: String] = RemoraImport.defaultAlarmLabels, alarmsPrefix: String = "Alarms: ", marksPrefix: String = "Marks: ") throws -> ImportedDive { @@ -63,7 +79,7 @@ public enum RemoraImport { let when = Int(log.start.timeIntervalSince1970.rounded()) + timeZone.secondsFromGMT(for: log.start) var dive = ImportedDive(when: when, durationSeconds: Int(last.time.rounded())) - dive.model = log.computerModel ?? "Open Rémora" + dive.model = log.computerModel ?? defaultModel dive.sourceID = log.id.uuidString dive.site = log.site ?? "" dive.latitude = log.latitude @@ -120,7 +136,7 @@ public enum RemoraImport { .sorted { $0.lastPathComponent < $1.lastPathComponent } } - /// Removes both files of a dive (JSON and UDDF): Open Rémora counts the remaining JSON files as "pending". + /// Removes both files of a dive (JSON and UDDF): the app that dropped them counts the remaining JSON files as "pending". public static func consume(_ json: URL) { try? FileManager.default.removeItem(at: json) try? FileManager.default.removeItem(at: json.deletingPathExtension().appendingPathExtension("uddf")) diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift @@ -78,6 +78,13 @@ public enum CloudAccount { } } +/// What an import did: dives added as new dives, and dives merged into a dive that was already there. +public struct ImportSummary: Sendable, Equatable { + public var added = 0 + public var merged = 0 + public init() {} +} + public struct SyncReport: Sendable, Equatable { public var downloaded = false public var sent: [String] = [] @@ -182,15 +189,25 @@ public actor LogRepository { } /// Queues the imported dives, from the oldest to the most recent: sites created as needed (matched by - /// name), numbers continuing the logbook's, dives already present left aside. Returns the number added. + /// name), numbers continuing the logbook's. A dive that overlaps one of the logbook joins it as one more dive + /// computer (see `DiveMerge.disposition`); the same dive from the same computer is left aside. @discardableResult - public func importDives(_ dives: [ImportedDive]) throws -> Int { - var added = 0 + public func importDives(_ dives: [ImportedDive]) throws -> ImportSummary { + var summary = ImportSummary() var log = try logbook() for dive in dives.sorted(by: { $0.when < $1.when }) { + var existing: Dive? + if let root = try workingTree() { + switch try LogEditor.disposition(of: dive, root: root, store: store).0 { + case .duplicate: continue + case .merge(let found): existing = found + case .new: break + } + } var siteUUID: UInt32? let name = dive.site.trimmingCharacters(in: .whitespacesAndNewlines) - if !name.isEmpty { + // A dive that already has its site keeps it. + if !name.isEmpty, existing?.siteUUID == nil { if let existing = log.sites.values.first(where: { $0.name.compare(name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) { siteUUID = existing.uuid // The site exists without a position and the file provides one: set it. @@ -205,13 +222,23 @@ public actor LogRepository { } } do { - log = try enqueue(.importDive(dive, number: log.nextNumber, siteUUID: siteUUID)) - added += 1 + log = try enqueue(.importDive(dive, number: existing?.number ?? log.nextNumber, siteUUID: siteUUID)) + if existing == nil { summary.added += 1 } else { summary.merged += 1 } } catch ChangeError.diveAlreadyExists { continue } } - return added + return summary + } + + /// Queues the merge of dives of the logbook into one: the earliest keeps its date, number, site and notes, the + /// others fill its gaps and bring their dive computers (see `LogEditor.merged`). + @discardableResult + public func mergeDives(_ dives: [Dive]) throws -> Logbook { + let ordered = dives.sorted { ($0.when, $0.number) < ($1.when, $1.number) } + guard let target = ordered.first, ordered.count > 1 else { return try logbook() } + let others = ordered.dropFirst().map { DiveRef(when: $0.when, number: $0.number) } + return try enqueue(.mergeDives(when: target.when, number: target.number, others: others)) } public func discardPending() throws { diff --git a/Packages/DiveKit/Sources/divelog-cli/main.swift b/Packages/DiveKit/Sources/divelog-cli/main.swift @@ -88,8 +88,8 @@ do { let dives = all.filter { $0.durationSeconds >= 120 } print("file: \(all.count) logs, of which \(all.count - dives.count) short dips ignored") try await repository.enqueue(.ensureSettings) - let added = try await repository.importDives(dives) - print("added to the logbook: \(added) (already there: \(dives.count - added))") + let summary = try await repository.importDives(dives) + print("added to the logbook: \(summary.added), merged into a dive already there: \(summary.merged) (already there: \(dives.count - summary.added - summary.merged))") let report = try await repository.sync(transport: transport) print("pushed: \(report.sent.count) changes, commit \(report.head?.hex ?? "-")") for dropped in report.dropped { print(" dropped: \(dropped)") } @@ -139,22 +139,30 @@ do { describe(try await repository.logbook()) case "merge": // merge <file> <from> <to> <number>: merges into one dive the immersions of the file that started between - // two times (seconds, naive time), removes from the logbook those already there and imports the merged dive. + // two times (seconds, naive time). Those the logbook does not have yet are imported first, then the dives + // are merged the way the app does it (LogRepository.mergeDives) and the result takes the number given. let rest = Array(arguments.dropFirst()) guard rest.count == 4, let from = Int(rest[1]), let to = Int(rest[2]), let number = Int(rest[3]) else { fail("usage: merge <file> <from> <to> <number>") } let parts = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: rest[0])))).filter { $0.when >= from && $0.when <= to } - guard parts.count > 1, let merged = ImportedDive.merged(parts) else { fail("at least two immersions are needed in this interval") } + guard parts.count > 1 else { fail("at least two immersions are needed in this interval") } + try await repository.importDives(parts) let before = try await repository.logbook() - var siteUUID: UInt32? + var dives = [Dive]() for part in parts { - if let existing = before.dive(when: part.when) { - siteUUID = siteUUID ?? existing.siteUUID - try await repository.enqueue(.deleteDive(when: existing.when, number: existing.number)) + switch DiveMerge.disposition(of: part, among: before.dives) { + case .duplicate(let dive), .merge(let dive): if !dives.contains(where: { $0.id == dive.id }) { dives.append(dive) } + case .new: break } } - try await repository.enqueue(.importDive(merged, number: number, siteUUID: siteUUID)) + guard let target = dives.min(by: { ($0.when, $0.number) < ($1.when, $1.number) }) else { fail("these immersions did not reach the logbook") } + // A single dive: importing was enough (the immersions joined a dive that was already there). + if dives.count > 1 { try await repository.mergeDives(dives) } + if target.number != number { + try await repository.enqueue(.renumberDive(when: target.when, number: target.number, newNumber: number)) + } let report = try await repository.sync(transport: transport) - print("\(parts.count) immersions merged: \(merged.durationSeconds / 60) min underwater, \(merged.maxDepth) m, \(merged.samples.count) samples; pushed \(report.sent.count) changes, commit \(report.head?.hex ?? "-")") + let merged = try await repository.logbook().dive(when: target.when, number: number) + print("\(dives.count) dives merged: \((merged?.durationSeconds ?? 0) / 60) min underwater, \(merged?.maxDepth ?? 0) m; pushed \(report.sent.count) changes, commit \(report.head?.hex ?? "-")") describe(try await repository.logbook()) case "locate": // locate "Site name" latitude longitude diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift @@ -247,30 +247,6 @@ final class ImportTests: XCTestCase { } } - func testMergeImmersions() throws { - var first = ImportedDive(when: 1000, durationSeconds: 30) - first.sourceID = "a" - first.samples = [10, 20, 30].map { ImportedDive.Sample(time: $0, depth: Double($0) / 2) } - first.samples[2].pressure1 = 150 - var second = ImportedDive(when: 1300, durationSeconds: 20) - second.sourceID = "b" - second.buddy = "Sam" - second.notes = "second" - second.samples = [10, 20].map { ImportedDive.Sample(time: $0, depth: 8) } - let merged = try XCTUnwrap(ImportedDive.merged([second, first])) - XCTAssertEqual(merged.when, 1000) - XCTAssertEqual(merged.durationSeconds, 50) // time underwater, without the interval - XCTAssertEqual(merged.samples.map(\.time), [10, 20, 30, 40, 300, 310, 320]) - XCTAssertEqual(merged.samples.map(\.depth), [5, 10, 15, 0, 0, 8, 8]) - XCTAssertNil(merged.samples[3].pressure1) // no made-up pressure at the surface - XCTAssertEqual(merged.maxDepth, 15) - XCTAssertEqual(merged.meanDepth, (5 + 10 + 15 + 8 + 8) / 5.0) - XCTAssertEqual(merged.buddy, "Sam") - XCTAssertEqual(merged.notes, "second") - XCTAssertEqual(merged.sourceID, "a+b") - XCTAssertEqual(ImportedDive.merged([first]), first) - } - /// Dive dropped by Open Rémora (JSON of RemoraDeco's `DiveLog`, sorted keys, ISO 8601 dates). func testOpenRemoraDive() throws { let json = """ @@ -317,6 +293,16 @@ final class ImportTests: XCTestCase { XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(marked.utf8), timeZone: montreal, marksPrefix: "Repères : ").notes, "Première sortie\nAlarms: 10:00 fast ascent, 21:00 ceiling violated\nRepères : 10:05 18.2 m 237°, 15:00 25.0 m") + // Open Mérou drops the same JSON in its own folder of the same app group, with its own model name. + XCTAssertEqual(SharedDiveSource.all.map(\.folder), ["OpenRemora/Plongees", "OpenMerou/Dives"]) + XCTAssertEqual(RemoraImport.folder, "OpenRemora/Plongees") + let merouJSON = json.replacingOccurrences(of: "\"computerModel\":\"Open Rémora\"", with: "\"computerModel\":\"Open Mérou\"") + XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(merouJSON.utf8), timeZone: montreal).model, "Open Mérou") + let unnamed = json.replacingOccurrences(of: "\"computerModel\":\"Open Rémora\",", with: "") + XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(unnamed.utf8), timeZone: montreal, defaultModel: SharedDiveSource.openMerou.name).model, "Open Mérou") + XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(unnamed.utf8), timeZone: montreal).model, "Open Rémora") + XCTAssertThrowsError(try RemoraImport.dive(fromJSON: Data(merouJSON.replacingOccurrences(of: "\"source\":\"remora\"", with: "\"source\":\"simulation\"").utf8))) + // A demo dive must never enter the logbook. XCTAssertThrowsError(try RemoraImport.dive(fromJSON: Data(json.replacingOccurrences(of: "\"source\":\"remora\"", with: "\"source\":\"simulation\"").utf8))) diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/MergeTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/MergeTests.swift @@ -0,0 +1,520 @@ +// SPDX-License-Identifier: GPL-2.0-only +import XCTest +import GitLite +import GitTestSupport +@testable import SubsurfaceLog + +/// One dive recorded by several dive computers: the automatic merge at import, the manual merge, and what ends up +/// in the Subsurface git format. Everything runs against a local git repository. +final class MergeTests: XCTestCase { + private func repository(_ name: String = "local") throws -> LogRepository { + try LogRepository(directory: try LocalGit.temporaryDirectory(name), branch: Fixture.branch, + authorName: "DiveLog", authorEmail: Fixture.branch) + } + + /// A square profile with one sample per minute. + private func recorded(_ model: String, when: Int, minutes: Int, depth: Double, serial: String = "", o2: Int = 21) -> ImportedDive { + var dive = ImportedDive(when: when, durationSeconds: minutes * 60) + dive.model = model + dive.serial = serial + dive.samples = (0...minutes).map { minute in + var sample = ImportedDive.Sample(time: minute * 60, depth: minute == 0 || minute == minutes ? 0 : depth) + sample.temperature = 12 + sample.o2 = o2 + return sample + } + return dive + } + + private func logged(_ model: String, when: Int, minutes: Int, serial: String = "", startsAt own: Int? = nil) -> Dive { + var computer = DiveComputer() + computer.model = model + computer.when = own + if !serial.isEmpty { computer.extra = [KeyValue(key: "Serial", value: serial)] } + var dive = Dive(when: when) + dive.durationSeconds = minutes * 60 + dive.computers = [computer] + return dive + } + + // MARK: Rules + + func testComputerOrder() { + XCTAssertEqual(["Open Mérou", "manually added dive", "Shearwater Petrel 3", "Open Rémora", "Suunto D5"] + .sorted { DiveMerge.rank(model: $0) < DiveMerge.rank(model: $1) }.first, "Open Rémora") + XCTAssertEqual(DiveMerge.rank(model: "Open Rémora"), 0) + XCTAssertEqual(DiveMerge.rank(model: "open remora"), 0) // accents and case do not matter + XCTAssertEqual(DiveMerge.rank(model: "Shearwater Petrel 3"), 1) + XCTAssertEqual(DiveMerge.rank(model: "Suunto D5"), 1) + XCTAssertEqual(DiveMerge.rank(model: ""), 1) + XCTAssertEqual(DiveMerge.rank(model: "Open Mérou"), 2) + XCTAssertEqual(DiveMerge.rank(model: "manually added dive"), 3) + + // In a merged dive: Open Rémora first whatever the arrival order, the others keep theirs within a rank. + let parts = ["Open Mérou", "manually added dive", "Suunto D5", "Open Rémora", "Shearwater Petrel 3"].enumerated().map { index, model in + DiveParts(when: 1000 + index, diveFile: Array("duration 10:00 min\n".utf8), + computers: [ComputerFile(Array("model \"\(model)\"\n 0:00 0.0m\n 10:00 0.0m\n".utf8), diveWhen: 1000 + index, diveDuration: 600)]) + } + let merged = LogEditor.merged(parts[0], with: Array(parts.dropFirst())) + XCTAssertEqual(merged.computers.map { LogLoader.parseComputer($0, withSamples: false).model }, + ["Open Rémora", "Suunto D5", "Shearwater Petrel 3", "Open Mérou", "manually added dive"]) + } + + func testOverlapRule() { + XCTAssertEqual(DiveMerge.overlap(0...100, 40...300), 60) + XCTAssertEqual(DiveMerge.overlap(40...300, 0...100), 60) + XCTAssertEqual(DiveMerge.overlap(0...100, 100...200), 0) // touching ranges meet + XCTAssertNil(DiveMerge.overlap(0...100, 101...200)) + + let start = Fixture.when(2026, 7, 4, 10, 30, 0) + let watch = recorded("Open Rémora", when: start, minutes: 40, depth: 18) + // The other device noticed the submersion three minutes later: far more than "the same start time". + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [logged("Shearwater Petrel 3", when: start + 180, minutes: 36)]), + .merge(logged("Shearwater Petrel 3", when: start + 180, minutes: 36))) + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [logged("Shearwater Petrel 3", when: start - 1200, minutes: 21)]), + .merge(logged("Shearwater Petrel 3", when: start - 1200, minutes: 21))) + // The next dive of the day, and the previous one, are other dives. + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [logged("Shearwater Petrel 3", when: start + 41 * 60, minutes: 30), + logged("Shearwater Petrel 3", when: start - 3600, minutes: 59)]), .new) + XCTAssertEqual(DiveMerge.disposition(of: watch, among: []), .new) + // The same computer over the same time: a re-import, even when the start moved by a few seconds. + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [logged("Open Rémora", when: start + 4, minutes: 40)]), + .duplicate(logged("Open Rémora", when: start + 4, minutes: 40))) + // Same model, another serial number: somebody else's computer. + var mine = recorded("Shearwater Petrel 3", when: start, minutes: 40, depth: 18, serial: "ABCD1234") + XCTAssertEqual(DiveMerge.disposition(of: mine, among: [logged("Shearwater Petrel 3", when: start, minutes: 40, serial: "0000FFFF")]), + .merge(logged("Shearwater Petrel 3", when: start, minutes: 40, serial: "0000FFFF"))) + XCTAssertEqual(DiveMerge.disposition(of: mine, among: [logged("Shearwater Petrel 3", when: start, minutes: 40, serial: "abcd1234")]), + .duplicate(logged("Shearwater Petrel 3", when: start, minutes: 40, serial: "abcd1234"))) + mine.serial = "65535" // the same number, decimal on one side and hexadecimal on the other + XCTAssertEqual(DiveMerge.disposition(of: mine, among: [logged("Shearwater Petrel 3", when: start, minutes: 40, serial: "0000FFFF")]), + .duplicate(logged("Shearwater Petrel 3", when: start, minutes: 40, serial: "0000FFFF"))) + // Two dives overlap (a clock that is a few minutes off): the one sharing the most time wins. + let before = logged("Shearwater Petrel 3", when: start - 50 * 60, minutes: 52) + let same = logged("Shearwater Petrel 3", when: start + 120, minutes: 40) + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [before, same]), .merge(same)) + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [same, before]), .merge(same)) + // A computer of a merged dive that started earlier than the dive itself counts with its own time. + let late = logged("Shearwater Petrel 3", when: start + 45 * 60, minutes: 5, startsAt: start + 30 * 60) + XCTAssertEqual(late.timeRange, (start + 30 * 60)...(start + 50 * 60)) + XCTAssertEqual(DiveMerge.disposition(of: watch, among: [late]), .merge(late)) + } + + func testFillDiveFileAndRenumberCylinders() { + let target = Array("duration 40:00 min\ntags \"lac\"\nbuddy \"Sam\"\nsuit \"\"\nnotes \"Alarms: none\"\ncylinder\nfuturekeyword 1\n".utf8) + let source = Array(""" + duration 39:00 min + rating 4 + tags "nuit", "Lac" + divesiteid 7f3a1b2c + buddy "Max, sam" + suit "7 mm" + notes "Belle visi" + cylinder o2=32.0% start=200.0bar + cylinder o2=50.0% + cylinder + weightsystem weight=6.0kg description="belt" + futurekeyword 2 + + """.utf8) + let filled = LogEditor.fill(diveFile: target, from: source) + XCTAssertEqual(String(decoding: filled.file, as: UTF8.self), """ + duration 40:00 min + rating 4 + tags "lac", "nuit" + divesiteid 7f3a1b2c + buddy "Sam, Max" + suit "7 mm" + notes "Alarms: none + \tBelle visi" + cylinder + cylinder o2=32.0% start=200.0bar + cylinder o2=50.0% + weightsystem weight=6.0kg description="belt" + futurekeyword 1 + + """) + XCTAssertEqual(filled.cylinders, [0: 1, 1: 2, 2: 0]) + // Filling twice from the same dive changes nothing more. + XCTAssertEqual(LogEditor.fill(diveFile: filled.file, from: source).file, filled.file) + + let text = """ + model "X" + event 0:00 type=25 flags=1 name="gaschange" cylinder=0 o2=32.0% + event 5:00 type=25 flags=2 name="gaschange" cylinder=1 o2=50.0% + event 6:00 type=3 flags=1 name="ascent" + 0:10 5.0m 200.0bar:0 + 0:20 6.0m 12.0°C 50.0bar:1 ndl=5:00 + + """ + var computer = ComputerFile(Array(text.utf8), diveWhen: 1000, diveDuration: 0) + XCTAssertEqual(computer.duration, 20) + computer.remapCylinders([0: 0, 1: 1]) + XCTAssertEqual(String(decoding: computer.bytes, as: UTF8.self), text) + computer.remapCylinders(filled.cylinders) + XCTAssertEqual(String(decoding: computer.bytes, as: UTF8.self), """ + model "X" + event 0:00 type=25 flags=2 name="gaschange" cylinder=1 o2=32.0% + event 5:00 type=25 flags=3 name="gaschange" cylinder=2 o2=50.0% + event 6:00 type=3 flags=1 name="ascent" + 0:10 5.0m 200.0bar:1 + 0:20 6.0m 12.0°C 50.0bar:2 ndl=5:00 + + """) + } + + // MARK: Automatic merge at import + + /// The watch first, then the Petrel; and the Petrel first, then the watch. Either way: one dive, two dive + /// computers, Open Rémora first, and the same thing read back from the server by another device. + func testImportMergesOverlappingDivesInEitherOrder() async throws { + let (remote, _) = try Fixture.makeRemote() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try repository() + _ = try await repo.sync(transport: transport) + + // Arrival order 1: Open Rémora, then the Petrel that started 45 seconds later. + let first = Fixture.when(2026, 7, 4, 10, 30, 0) + var watch = recorded("Open Rémora", when: first, minutes: 40, depth: 18.2, o2: 32) + watch.site = "Niagara II" + watch.latitude = 45.2503 + watch.longitude = -81.6017 + watch.notes = "Alarms: 10:00 fast ascent" + var petrel = recorded("Shearwater Petrel 3", when: first + 45, minutes: 39, depth: 18.6, serial: "ABCD1234", o2: 32) + petrel.site = "Tobermory" + petrel.buddy = "Sam" + petrel.notes = "Belle visi" + for index in petrel.samples.indices { petrel.samples[index].pressure1 = 200 - Double(index) * 3 } + + var summary = try await repo.importDives([watch]) + XCTAssertEqual(summary, { var s = ImportSummary(); s.added = 1; return s }()) + summary = try await repo.importDives([petrel]) + XCTAssertEqual(summary, { var s = ImportSummary(); s.merged = 1; return s }()) + + var log = try await repo.logbook() + XCTAssertEqual(log.dives.count, 4) + var dive = try XCTUnwrap(log.dive(when: first)) + XCTAssertEqual(dive.number, 44) + XCTAssertEqual(dive.computers.map(\.model), ["Open Rémora", "Shearwater Petrel 3"]) + XCTAssertEqual(dive.computers.map(\.when), [nil, first + 45]) + XCTAssertEqual(dive.computerModel, "Open Rémora") + XCTAssertEqual(log.site(of: dive)?.name, "Niagara II") // the dive keeps its site + XCTAssertEqual(log.sites.values.map(\.name).sorted(), ["Carrière Morrison", "Niagara II"]) // and no orphan site is made + XCTAssertEqual(dive.buddy, "Sam") // gap filled + XCTAssertEqual(dive.notes, "Alarms: 10:00 fast ascent\nBelle visi") // nothing lost + XCTAssertEqual(dive.cylinders.count, 1) // the same EAN32 cylinder, now with its pressures + XCTAssertEqual(dive.cylinders.first?.gas.label, "EAN32") + XCTAssertEqual(dive.cylinders.first?.startBar, 200) + XCTAssertEqual(dive.durationSeconds, 40 * 60) + XCTAssertEqual(dive.maxDepth, 18.6) + XCTAssertEqual(dive.meanDepth, dive.computers.first?.meanDepth) + + // The very same dives again, even with a start a few seconds off: nothing happens. + var again = petrel + again.when += 5 + let pendingBefore = await repo.pending.count + summary = try await repo.importDives([watch, petrel, again]) + XCTAssertEqual(summary, ImportSummary()) + let pendingAfter = await repo.pending.count + XCTAssertEqual(pendingAfter, pendingBefore) + do { + try await repo.enqueue(.importDive(watch, number: 99, siteUUID: nil)) + XCTFail("should have failed") + } catch let error as ChangeError { + XCTAssertEqual(error, .diveAlreadyExists(watch.when)) + } + + var report = try await repo.sync(transport: transport) + XCTAssertEqual(report.dropped, []) + try remote.git(["fsck", "--strict"]) + XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2026/07/04-Sat-10=30=00"]), + "Dive-44\nDivecomputer-001\nDivecomputer-002") + XCTAssertTrue(try remote.text(["show", "\(Fixture.branch):2026/07/04-Sat-10=30=00/Divecomputer-001"]).hasPrefix("model \"Open Rémora\"\nmaxdepth 18.2m\n")) + XCTAssertTrue(try remote.text(["show", "\(Fixture.branch):2026/07/04-Sat-10=30=00/Divecomputer-002"]) + .hasPrefix("model \"Shearwater Petrel 3\"\ndate 2026-07-04\ntime 10:30:45\nmaxdepth 18.6m\n")) + let diveFile = try remote.text(["show", "\(Fixture.branch):2026/07/04-Sat-10=30=00/Dive-44"]) + XCTAssertTrue(diveFile.hasPrefix("duration 40:00 min\ndivesiteid "), diveFile) + XCTAssertTrue(diveFile.hasSuffix("buddy \"Sam\"\nnotes \"Alarms: 10:00 fast ascent\n\tBelle visi\"\ncylinder o2=32.0% start=200.0bar end=83.0bar"), diveFile) + + // Arrival order 2: the Petrel is already on the server; the watch, which started 30 seconds earlier, comes after. + let second = Fixture.when(2026, 7, 5, 14, 0, 0) + petrel.when = second + petrel.notes = "" + watch.when = second - 30 + watch.durationSeconds = 41 * 60 + watch.samples.append(ImportedDive.Sample(time: 41 * 60, depth: 0)) + summary = try await repo.importDives([petrel]) + XCTAssertEqual(summary.added, 1) + report = try await repo.sync(transport: transport) + let petrelBlob = try remote.text(["rev-parse", "\(Fixture.branch):2026/07/05-Sun-14=00=00/Divecomputer"]) + summary = try await repo.importDives([watch]) + XCTAssertEqual(summary.merged, 1) + report = try await repo.sync(transport: transport) + XCTAssertEqual(report.sent.count, 1) + XCTAssertEqual(report.dropped, []) + try remote.git(["fsck", "--strict"]) + XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2026/07/05-Sun-14=00=00"]), + "Dive-45\nDivecomputer-001\nDivecomputer-002") + XCTAssertTrue(try remote.text(["show", "\(Fixture.branch):2026/07/05-Sun-14=00=00/Divecomputer-001"]) + .hasPrefix("model \"Open Rémora\"\ndate 2026-07-05\ntime 13:59:30\nmaxdepth 18.2m\n")) + // The Petrel's file did not change: it is the same git object under its new name. + XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):2026/07/05-Sun-14=00=00/Divecomputer-002"]), petrelBlob) + summary = try await repo.importDives([watch, petrel]) + XCTAssertEqual(summary, ImportSummary()) + + // Round trip through the Subsurface git format: another device, from scratch. + let other = try repository("other") + _ = try await other.sync(transport: transport) + log = try await other.logbook() + XCTAssertEqual(log.dives.map(\.number), [45, 44, 43, 42, 41]) + XCTAssertEqual(log.warnings, []) + dive = try XCTUnwrap(log.dive(when: first)) + var computers = try await other.profile(of: dive) + XCTAssertEqual(computers.map(\.model), ["Open Rémora", "Shearwater Petrel 3"]) + XCTAssertEqual(computers.map(\.samples.count), [41, 40]) + XCTAssertEqual(computers.map { $0.samples.map(\.depth).max() }, [18.2, 18.6]) + XCTAssertEqual(computers[1].samples.first?.pressures, [SensorPressure(sensor: 0, bar: 200)]) + XCTAssertEqual(computers[1].extra.first, KeyValue(key: "Serial", value: "ABCD1234")) + XCTAssertEqual(computers.map(\.when), [nil, first + 45]) + + dive = try XCTUnwrap(log.dive(when: second)) // the dive keeps the date it had + XCTAssertEqual(dive.number, 45) + XCTAssertEqual(log.site(of: dive)?.name, "Tobermory") + XCTAssertEqual(dive.buddy, "Sam") + XCTAssertEqual(dive.notes, "Alarms: 10:00 fast ascent") + XCTAssertEqual(dive.durationSeconds, 41 * 60) + XCTAssertEqual(dive.timeRange, (second - 30)...(second + 41 * 60)) // from the earliest start to the latest end + computers = try await other.profile(of: dive) + XCTAssertEqual(computers.map(\.model), ["Open Rémora", "Shearwater Petrel 3"]) + XCTAssertEqual(computers.map(\.samples.count), [42, 40]) + XCTAssertEqual(computers.map(\.when), [second - 30, nil]) + // And that other device does not take them for new dives either. + summary = try await other.importDives([watch, petrel]) + XCTAssertEqual(summary, ImportSummary()) + } + + /// The merge waits in the change queue while the desktop edits the same dive: it is replayed on top. + func testMergeAtImportReplaysOverRemoteChanges() async throws { + let (remote, work) = try Fixture.makeRemote() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try repository() + _ = try await repo.sync(transport: transport) + let when41 = Fixture.when(2024, 7, 13, 10, 15, 30) + let petrelBlob = try remote.text(["rev-parse", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Divecomputer"]) + + var watch = recorded("Open Rémora", when: when41 + 20, minutes: 44, depth: 30.1, o2: 32) + watch.site = "Ailleurs" + let summary = try await repo.importDives([watch]) + XCTAssertEqual(summary.merged, 1) + var log = try await repo.logbook() + XCTAssertEqual(log.dives.count, 3) + XCTAssertEqual(log.dive(when: when41)?.computers.map(\.model), ["Open Rémora", "Shearwater Petrel 3"]) + + // The queue survives a restart of the app. + let reopened = try LogRepository(directory: repo.directory, branch: Fixture.branch, authorName: "DiveLog", authorEmail: Fixture.branch) + let pending = await reopened.pending + XCTAssertEqual(pending.map(\.summary), ["dive 41 imported (Open Rémora)"]) + + let desktop = Fixture.dive41.replacingOccurrences(of: "buddy \"Sam, Max\"", with: "buddy \"Bureau\"") + try work.write("2024/07/13-Sat-10=15=30/Dive-41", desktop) + try work.commitAll("desktop changes") + try work.git(["push", "-q", "origin", "main:refs/heads/\(Fixture.branch)"]) + + let report = try await reopened.sync(transport: transport) + XCTAssertTrue(report.downloaded) + XCTAssertEqual(report.sent.count, 1) + XCTAssertEqual(report.dropped, []) + try remote.git(["fsck", "--strict"]) + XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2024/07/13-Sat-10=15=30"]), + "Dive-41\nDivecomputer-001\nDivecomputer-002") + // The dive has everything it needs already: its file is the desktop's, byte for byte, unknown line included. + XCTAssertEqual(String(decoding: try remote.git(["show", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Dive-41"]), as: UTF8.self), desktop) + XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Divecomputer-002"]), petrelBlob) + XCTAssertTrue(try remote.text(["show", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Divecomputer-001"]) + .hasPrefix("model \"Open Rémora\"\ndate 2024-07-13\ntime 10:15:50\n")) + log = try await reopened.logbook() + let dive = try XCTUnwrap(log.dive(when: when41)) + XCTAssertEqual(dive.buddy, "Bureau") + XCTAssertEqual(dive.durationSeconds, 45 * 60 + 30) + XCTAssertEqual(log.site(of: dive)?.name, "Carrière Morrison") + XCTAssertEqual(log.sites.count, 1) + + // The dive was deleted on the server while a merge into it was waiting: the import makes its own dive. + let when42 = Fixture.when(2024, 8, 2, 9, 0, 0) + _ = try await reopened.importDives([recorded("Open Rémora", when: when42 + 60, minutes: 48, depth: 18)]) + try work.git(["pull", "-q", "origin", Fixture.branch]) + try work.git(["rm", "-rq", "2024/08/02-Bonaire~1a2b3c4/02-Fri-09=00=00"]) + try work.commitAll("dive deleted") + try work.git(["push", "-q", "origin", "main:refs/heads/\(Fixture.branch)"]) + let later = try await reopened.sync(transport: transport) + XCTAssertEqual(later.dropped, []) + log = try await reopened.logbook() + XCTAssertEqual(log.dive(when: when42 + 60)?.computers.map(\.model), ["Open Rémora"]) + XCTAssertNil(log.dives.first { $0.when == when42 }) + } + + // MARK: Manual merge + + /// Two dives the automatic rule cannot bring together (a dive entered by hand at a guessed time, and the same + /// dive recorded two hours "later" by a device whose clock was off): the user merges them. + func testManualMergeOfTwoDives() async throws { + let (remote, work) = try Fixture.makeRemote() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try repository() + _ = try await repo.sync(transport: transport) + + let when = Fixture.when(2025, 3, 1, 10, 0, 0) + var paper = NewDive(when: when, number: 44, durationSeconds: 2400, maxDepth: 18) + paper.buddy = "Sam" + paper.tags = ["lac"] + paper.notes = "Carnet papier" + paper.tank = "AL80" + paper.startBar = 200 + paper.endBar = 60 + try await repo.enqueue(.addDive(paper)) + var housing = recorded("Open Mérou", when: when + 7200, minutes: 38, depth: 17.5) + housing.site = "Lac Memphrémagog" + housing.notes = "Vidéo" + let summary = try await repo.importDives([housing]) + XCTAssertEqual(summary.added, 1) // no overlap: two dives + var log = try await repo.logbook() + XCTAssertEqual(log.dives.map(\.number), [45, 44, 43, 42, 41]) + + // Whatever the order of the selection, the earliest dive is the one that stays. + log = try await repo.mergeDives([log.dives[0], log.dives[1]]) + XCTAssertEqual(log.dives.map(\.number), [44, 43, 42, 41]) + var dive = try XCTUnwrap(log.dive(when: when)) + XCTAssertEqual(dive.computers.map(\.model), ["Open Mérou", "manually added dive"]) + XCTAssertEqual(dive.computers.map(\.when), [when + 7200, nil]) + XCTAssertEqual(log.site(of: dive)?.name, "Lac Memphrémagog") + XCTAssertEqual(dive.notes, "Carnet papier\nVidéo") + XCTAssertEqual(dive.buddy, "Sam") + XCTAssertEqual(dive.tags, ["lac"]) + XCTAssertEqual(dive.cylinders.map(\.description), ["AL80"]) + XCTAssertEqual(dive.cylinders.first?.startBar, 200) + XCTAssertEqual(dive.durationSeconds, 2400) + XCTAssertEqual(dive.maxDepth, 18) + + // The merge goes through the change queue: it survives a restart and is replayed on the server's state. + let reopened = try LogRepository(directory: repo.directory, branch: Fixture.branch, authorName: "DiveLog", authorEmail: Fixture.branch) + let pending = await reopened.pending + XCTAssertEqual(pending.map(\.summary), ["dive 44 added", "site added: Lac Memphrémagog", "dive 45 imported (Open Mérou)", "dive 44 merged with 45"]) + var report = try await reopened.sync(transport: transport) + XCTAssertEqual(report.sent.count, 4) + XCTAssertEqual(report.dropped, []) + try remote.git(["fsck", "--strict"]) + XCTAssertEqual(try remote.text(["ls-tree", "-r", "--name-only", "\(Fixture.branch):2025/03"]), + "01-Sat-10=00=00/Dive-44\n01-Sat-10=00=00/Divecomputer-001\n01-Sat-10=00=00/Divecomputer-002") + XCTAssertTrue(try remote.text(["show", "\(Fixture.branch):2025/03/01-Sat-10=00=00/Divecomputer-001"]) + .hasPrefix("model \"Open Mérou\"\ndate 2025-03-01\ntime 12:00:00\n")) + + let other = try repository("other") + _ = try await other.sync(transport: transport) + log = try await other.logbook() + dive = try XCTUnwrap(log.dive(when: when)) + let computers = try await other.profile(of: dive) + XCTAssertEqual(computers.map(\.model), ["Open Mérou", "manually added dive"]) + XCTAssertEqual(computers.map(\.samples.count), [39, 4]) + XCTAssertEqual(dive.notes, "Carnet papier\nVidéo") + + // A merge whose other dives are gone from the server is dropped, and says so; a merge of one dive is nothing. + let when42 = Fixture.when(2024, 8, 2, 9, 0, 0) + let dive42 = try XCTUnwrap(log.dive(when: when42)) + _ = try await reopened.mergeDives([dive]) + var waiting = await reopened.pending.count + XCTAssertEqual(waiting, 0) + _ = try await reopened.mergeDives([dive, dive42]) + waiting = await reopened.pending.count + XCTAssertEqual(waiting, 1) + try work.git(["pull", "-q", "origin", Fixture.branch]) + try work.git(["rm", "-rq", "2024/08/02-Bonaire~1a2b3c4/02-Fri-09=00=00"]) + try work.commitAll("dive deleted") + try work.git(["push", "-q", "origin", "main:refs/heads/\(Fixture.branch)"]) + report = try await reopened.sync(transport: transport) + XCTAssertEqual(report.sent, []) + XCTAssertEqual(report.dropped.count, 1) + log = try await reopened.logbook() + XCTAssertEqual(log.dives.map(\.number), [44, 43, 41]) + } + + /// The same computer on successive immersions: one profile on one timeline, with the surface interval, and the + /// time spent underwater as the duration (what `divelog-cli merge` does with the immersions of a file). + func testManualMergeJoinsImmersionsOfTheSameComputer() async throws { + let (remote, _) = try Fixture.makeRemote() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try repository() + _ = try await repo.sync(transport: transport) + + let when = Fixture.when(2025, 3, 1, 10, 0, 0) + var first = ImportedDive(when: when, durationSeconds: 30) + first.model = "Shearwater Petrel 3" + first.samples = [10, 20, 30].map { ImportedDive.Sample(time: $0, depth: Double($0) / 2) } + first.samples[2].pressure1 = 150 + first.samples[2].stopDepth = 3 + first.samples[2].decoTime = 120 + var second = ImportedDive(when: when + 300, durationSeconds: 20) + second.model = "Shearwater Petrel 3" + second.buddy = "Sam" + second.notes = "second" + second.samples = [10, 20].map { ImportedDive.Sample(time: $0, depth: 8) } + var watch = ImportedDive(when: when + 5, durationSeconds: 330) + watch.model = "Open Rémora" + watch.samples = [0, 100, 330].map { ImportedDive.Sample(time: $0, depth: $0 == 100 ? 14 : 0) } + + // Two immersions: two dives, as the computer logged them. + var summary = try await repo.importDives([second, first]) + XCTAssertEqual(summary.added, 2) + var log = try await repo.logbook() + log = try await repo.mergeDives(Array(log.dives.prefix(2))) + XCTAssertEqual(log.dives.map(\.number), [44, 43, 42, 41]) + var dive = try XCTUnwrap(log.dive(when: when)) + XCTAssertEqual(dive.durationSeconds, 50) // time underwater, without the interval + XCTAssertEqual(dive.buddy, "Sam") + XCTAssertEqual(dive.notes, "second") + XCTAssertEqual(dive.maxDepth, 15) + var computers = try await repo.profile(of: dive) + XCTAssertEqual(computers.count, 1) + XCTAssertEqual(computers[0].samples.map(\.time), [10, 20, 30, 40, 300, 310, 320]) + XCTAssertEqual(computers[0].samples.map(\.depth), [5, 10, 15, 0, 0, 8, 8]) + XCTAssertEqual(computers[0].samples.map(\.inDeco), [false, false, true, false, false, false, false]) + XCTAssertEqual(computers[0].samples.map { $0.pressures.count }, [0, 0, 1, 0, 0, 0, 0]) // no made-up pressure at the surface + XCTAssertEqual(computers[0].durationSeconds, 50) + XCTAssertEqual(computers[0].events.filter(\.isGasChange).map(\.time), [0, 300]) + XCTAssertEqual(dive.timeRange, when...(when + 50)) // headers only; with the profile, the recording ends later + XCTAssertEqual(computers[0].timeRange(in: dive), when...(when + 320)) + + // The same immersions again: already there. The watch saw one long dive: it joins the merged one, first. + summary = try await repo.importDives([first, second]) + XCTAssertEqual(summary, ImportSummary()) + summary = try await repo.importDives([watch]) + XCTAssertEqual(summary.merged, 1) + + // The other way round: the watch's dive is there, and the computer's immersions arrive one by one. + let later = when + 86_400 + watch.when = later + 5 + first.when = later + second.when = later + 300 + summary = try await repo.importDives([watch]) + XCTAssertEqual(summary.added, 1) + summary = try await repo.importDives([first, second]) + XCTAssertEqual(summary.merged, 2) + + let report = try await repo.sync(transport: transport) + XCTAssertEqual(report.dropped, []) + try remote.git(["fsck", "--strict"]) + let other = try repository("other") + _ = try await other.sync(transport: transport) + log = try await other.logbook() + XCTAssertEqual(log.dives.map(\.number), [45, 44, 43, 42, 41]) + for start in [when, later] { + dive = try XCTUnwrap(log.dives.first { abs($0.when - start) <= 5 }) + computers = try await other.profile(of: dive) + XCTAssertEqual(computers.map(\.model), ["Open Rémora", "Shearwater Petrel 3"]) + XCTAssertEqual(computers[1].samples.map(\.time), [10, 20, 30, 40, 300, 310, 320]) + XCTAssertEqual(computers[1].samples.map(\.depth), [5, 10, 15, 0, 0, 8, 8]) + XCTAssertEqual(dive.durationSeconds, 330) + } + summary = try await other.importDives([first, second, watch]) + XCTAssertEqual(summary, ImportSummary()) + } +} diff --git a/README.md b/README.md @@ -23,10 +23,19 @@ The app is available in English and French. libdivecomputer recognises by name, downloads the dives (only the new ones after the first time) and previews them like a file import. Checked so far with Shearwater logs only (Petrel 3); Heinrichs-Weikamp computers need a flow-control step that is not written yet. -- Dives from Open Rémora (a dive computer for Apple Watch): at launch, when coming back to the foreground and when - `subrascasse://open-remora` is opened, the app reads `OpenRemora/Plongees/*.json` in the - `group.org.schurger.dive` app group, adds the dives to the logbook and removes the files (the contract is - `docs/PARTAGE.md` in the open-remora repository). Nothing is read until a logbook is open. +- Dives from Open Rémora (a dive computer for Apple Watch) and Open Mérou (an iPhone underwater housing): at + launch, when coming back to the foreground and when `subrascasse://open-remora` is opened, the app reads + `OpenRemora/Plongees/*.json` and `OpenMerou/Dives/*.json` in the `group.org.schurger.dive` app group, adds the + dives to the logbook and removes the files (the contract is `docs/SHARING.md` in the open-remora repository). + Nothing is read until a logbook is open. +- One dive, several dive computers: a dive that comes in (from a file, a dive computer, Open Rémora or Open + Mérou) while the logbook already has a dive at that time joins it as one more dive computer, the way Subsurface + stores it (`Divecomputer-001`, `Divecomputer-002`…). "At that time" means that the two [start, end] ranges + overlap: each device notices the submersion at its own moment. The dive keeps its date, number, site and notes, + and the incoming one fills what it lacks. Open Rémora is the primary computer (the first one, shown by default), + then the other dive computers, then Open Mérou (`DiveMerge.rank`). The same dive from the same computer is not + imported twice. "Merge dives…" in the + menu does the same for dives picked by hand (clocks that disagree, + successive immersions: the same computer's profiles are then joined on one timeline). - Photos: a dive page shows the photos and videos of the photo library taken during the dive (from 20 minutes before to 30 minutes after), placed on the profile at their time, hence at their depth; a site page shows those of all its dives. Logbook times are local to the site: the time zone comes from the site's position (Apple @@ -46,6 +55,8 @@ Not there yet: Subsurface XML import, dive planner. kept byte-identical. - `Repository` handles sync: an offline change queue, replayed on top of the server state. - Importers for the Shearwater and Open Rémora formats. + - `Merge` holds the rules for dives recorded by several computers and merges them as text, so that the files + of the other computers stay byte-identical. - `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 @@ -78,7 +89,8 @@ Not there yet: Subsurface XML import, dive planner. `make test-kit FILTER=TestName` runs a single test. Launch options: `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`, `-newDive`, -`-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`, `-diveComputer` +`-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`, `-merouFolder path`, +`-selectDives 12,13` (the selection that precedes a merge; with `-merge`, its confirmation), `-diveComputer` (opens the download sheet; with `-fakeComputers` it lists made-up computers, the simulator having no Bluetooth). ### Validating on a real logbook