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 0c476a0a0fec1426ef7eae6432c7415ef8de28b2
parent e51e48f971d9eda90bab412b30bd939c7b852be6
Author: Jean Schurger <jean@schurger.org>
Date:   Sat, 14 Nov 2026 13:37:49 -0500

Merging from the dive page, numbering closed after a merge, import preview reads profiles

- The import preview asks the repository what each dive would do, with the
  profiles read: immersions already merged into one dive are recognised up to
  the end of the last one (they were offered again after a download).
- Merging by hand renumbers the following dives so that no number is left.
- Dive page: Merge with other dives... opens the list selection with the dive
  picked. The list rows no longer collapse (selection mode squeezed them).
- divelog-cli check <file>: what an import would do, without changing anything.
- Version 0.4, TestFlight notes, README (Petrel 3 checked on a real computer).

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

Diffstat:
MApp/Localizable.xcstrings | 14++++++++++++--
MApp/Model/AppModel.swift | 17+++++++++++------
MApp/Views/DiveComputerView.swift | 7+++++--
MApp/Views/DiveDetailView.swift | 6++++++
MApp/Views/DiveListView.swift | 35++++++++++++++++++++++++++++++-----
MApp/Views/ImportView.swift | 10++++++----
MPackages/DiveKit/Sources/SubsurfaceLog/Repository.swift | 22++++++++++++++++++++--
MPackages/DiveKit/Sources/divelog-cli/main.swift | 17+++++++++++++++++
MPackages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift | 38++++++++++++++++++++++++++++++++++++++
MREADME.md | 2+-
Mfastlane/Fastfile | 4++--
Mproject.yml | 2+-
12 files changed, 149 insertions(+), 25 deletions(-)

diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings @@ -1711,6 +1711,16 @@ } } }, + "Merge with other dives…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fusionner avec d'autres plongées…" + } + } + } + }, "Metric (m, °C, bar)": { "localizations": { "fr": { @@ -2841,12 +2851,12 @@ } } }, - "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.": { + "The earliest dive keeps its date, number, site and notes; the others fill in what it lacks and add their dive computers. The dives numbered after them move down so that no number is left empty. 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." + "value": "La plongée la plus ancienne garde sa date, son numéro, son lieu et ses notes ; les autres complètent ce qui lui manque et ajoutent leurs ordinateurs de plongée. Les plongées numérotées après elles descendent d'autant, pour ne laisser aucun numéro vide. La fusion sera envoyée au nuage Subsurface à la prochaine synchronisation." } } } diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift @@ -274,6 +274,9 @@ final class AppModel { scheduleSync() } + /// Identifier of a dive whose page asked for a merge: the dive list starts its selection with it. + var mergeRequest: String? + // MARK: File import struct ImportCandidate: Identifiable { @@ -285,8 +288,8 @@ final class AppModel { var id: String { dive.id } } - private func candidate(_ dive: ImportedDive) -> ImportCandidate { - switch DiveMerge.disposition(of: dive, among: logbook.dives) { + private func candidate(_ dive: ImportedDive, _ known: DiveMerge.Disposition? = nil) -> ImportCandidate { + switch known ?? 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) @@ -294,7 +297,7 @@ final class AppModel { } /// 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] { + func importCandidates(from url: URL) async throws -> [ImportCandidate] { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let data: Data @@ -304,15 +307,17 @@ final class AppModel { throw AppError.message(String(localized: "Couldn't read this file.")) } do { - return try DiveImporter.dives(from: Array(data)).map(candidate) + return await importCandidates(for: try DiveImporter.dives(from: Array(data)), sorted: false) } catch let error as ImportError { throw AppError.message(Self.describe(error)) } } /// Same, for dives that are already decoded (downloaded from a dive computer), most recent first. - func importCandidates(for dives: [ImportedDive]) -> [ImportCandidate] { - dives.sorted { $0.when > $1.when }.map(candidate) + func importCandidates(for dives: [ImportedDive], sorted: Bool = true) async -> [ImportCandidate] { + // The repository reads the profiles, which the dive list does not hold: it knows where each dive really ends. + let known = (try? await repository?.dispositions(of: dives)) ?? [:] + return (sorted ? dives.sorted { $0.when > $1.when } : dives).map { candidate($0, known[$0.id]) } } /// Adds the dives to the logbook, oldest first, creating any missing sites. A dive that overlaps one of the diff --git a/App/Views/DiveComputerView.swift b/App/Views/DiveComputerView.swift @@ -34,8 +34,11 @@ struct DiveComputerImport: ViewModifier { }) { DiveComputerSheet(session: session) { name, dives in let session = session - downloaded = ImportBatch(name: name, candidates: model.importCandidates(for: dives), fromComputer: true) { session.rememberDownload() } - isPresented = false + Task { + let candidates = await model.importCandidates(for: dives) + downloaded = ImportBatch(name: name, candidates: candidates, fromComputer: true) { session.rememberDownload() } + isPresented = false + } } } .sheet(item: $batch) { ImportSheet(batch: $0) } diff --git a/App/Views/DiveDetailView.swift b/App/Views/DiveDetailView.swift @@ -193,6 +193,12 @@ struct DiveDetailView: View { ToolbarItemGroup(placement: .topBarTrailing) { Button("Edit") { editing = true } Menu { + Button("Merge with other dives…", systemImage: "arrow.triangle.merge") { + // The list takes over: it opens in selection mode with this dive already picked. + model.mergeRequest = diveID + dismiss() + } + .disabled(model.logbook.dives.count < 2) Button("Delete dive", systemImage: "trash", role: .destructive) { confirmingDelete = true } } label: { Label("More actions", systemImage: "ellipsis.circle") diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift @@ -24,7 +24,12 @@ struct DiveListView: View { ForEach(sections) { section in Section { ForEach(section.dives) { dive in - NavigationLink(value: dive.id) { DiveRow(dive: dive) } + if selecting { + // Selection mode: no link, and only what tells the dives apart. + DiveRow(dive: dive, compact: true) + } else { + NavigationLink(value: dive.id) { DiveRow(dive: dive) } + } } } header: { HStack { @@ -98,13 +103,20 @@ struct DiveListView: View { } } } 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.") + Text("The earliest dive keeps its date, number, site and notes; the others fill in what it lacks and add their dive computers. The dives numbered after them move down so that no number is left empty. 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 ?? "") } + .onChange(of: model.mergeRequest) { + guard let id = model.mergeRequest else { return } + model.mergeRequest = nil + path = [] + selection = [id] + selecting = true + } .sheet(isPresented: $adding) { NewDiveView() } .task(id: model.logbook.dives.count) { await model.refreshPhotoPresence() } .modifier(FileImport(isPresented: $importing)) @@ -129,6 +141,13 @@ struct DiveListView: View { selecting = true selection = Set(model.logbook.dives.filter { numbers.contains($0.number) }.map(\.id)) if LaunchOptions.flag("-merge") { confirmingMerge = true } + // "-mergeNow" goes through with it (the simulator cannot be tapped from a script). + if LaunchOptions.flag("-mergeNow") { + Task { + try? await model.mergeDives(ids: selection) + stopSelecting() + } + } } } } @@ -185,6 +204,8 @@ struct SyncBanner: View { struct DiveRow: View { @Environment(AppModel.self) private var model let dive: Dive + /// Leaves out the photo badge and the rating (the list in selection mode has less room). + var compact = false var body: some View { HStack(alignment: .center, spacing: 12) { @@ -198,7 +219,7 @@ struct DiveRow: View { Text(model.siteName(of: dive)) .font(.body.weight(.medium)) .lineLimit(1) - if let presence = model.photoPresence[dive.id] { + if !compact, let presence = model.photoPresence[dive.id] { HStack(spacing: 3) { if presence.photos { Image(systemName: "camera.fill") } if presence.videos { Image(systemName: "video.fill") } @@ -214,15 +235,18 @@ struct DiveRow: View { Text(verbatim: "\(DiveDate.short(dive)) · \(DiveDate.time(dive))") .lineLimit(1) .fixedSize() - if dive.rating > 0 { + if !compact, dive.rating > 0 { Text(String(repeating: "★", count: dive.rating)) .foregroundStyle(.yellow) + .lineLimit(1) + .fixedSize() } } .font(.caption) .foregroundStyle(.secondary) } - Spacer(minLength: 8) + // The text column takes whatever the figures on the right leave. + .frame(maxWidth: .infinity, alignment: .leading) VStack(alignment: .trailing, spacing: 3) { Text(model.units.depth(dive.maxDepth)) .font(.callout.monospacedDigit().weight(.semibold)) @@ -230,6 +254,7 @@ struct DiveRow: View { .font(.caption.monospacedDigit()) .foregroundStyle(.secondary) } + .fixedSize() } .padding(.vertical, 2) .opacity(dive.invalid ? 0.5 : 1) diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift @@ -37,10 +37,12 @@ struct FileImport: ViewModifier { } private func open(_ url: URL) { - do { - batch = ImportBatch(name: url.lastPathComponent, candidates: try model.importCandidates(from: url)) - } catch { - self.error = AppModel.describe(error) + Task { + do { + batch = ImportBatch(name: url.lastPathComponent, candidates: try await model.importCandidates(from: url)) + } catch { + self.error = AppModel.describe(error) + } } } } diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift @@ -188,6 +188,16 @@ public actor LogRepository { return try LogLoader.load(root: root, store: store) } + /// What importing each dive would do (see `DiveMerge.disposition`), by dive identifier. Unlike a look at the + /// dive list, this reads the profiles around each dive, so a dive made of several immersions is known up to + /// the end of its last one, not only for the time spent underwater. + public func dispositions(of dives: [ImportedDive]) throws -> [String: DiveMerge.Disposition] { + guard let root = try workingTree() else { return [:] } + var found = [String: DiveMerge.Disposition]() + for dive in dives { found[dive.id] = try LogEditor.disposition(of: dive, root: root, store: store).0 } + return found + } + /// Queues the imported dives, from the oldest to the most recent: sites created as needed (matched by /// 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. @@ -232,13 +242,21 @@ public actor LogRepository { } /// 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`). + /// others fill its gaps and bring their dive computers (see `LogEditor.merged`). The numbers of the dives that + /// disappear are not left empty: the dives numbered after them move down. @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)) + var log = try enqueue(.mergeDives(when: target.when, number: target.number, others: others)) + let freed = Set(others.map(\.number).filter { $0 > 0 && $0 != target.number }).subtracting(log.dives.map(\.number)) + guard let lowest = freed.min() else { return log } + for dive in log.dives.sorted(by: { $0.number < $1.number }) where dive.number > lowest { + let shift = freed.filter { $0 < dive.number }.count + log = try enqueue(.renumberDive(when: dive.when, number: dive.number, newNumber: dive.number - shift)) + } + return log } public func discardPending() throws { diff --git a/Packages/DiveKit/Sources/divelog-cli/main.swift b/Packages/DiveKit/Sources/divelog-cli/main.swift @@ -42,6 +42,7 @@ guard let command = arguments.first, let email = environment["CLOUD_EMAIL"], let apply <changes.json> apply a JSON array of changes and push locate <site> <latitude> <longitude> set the position of a site merge <file> <from> <to> <number> merge several immersions of a file into one dive + check <file> what importing a file would do, without changing anything renumber-plan JSON list of the dives whose number differs from their rank in time usage: divelog-cli inspect <file> show what a file contains (no network) """) @@ -70,6 +71,22 @@ do { switch command { case "list": describe(try await repository.logbook()) + case "check": + // check <file>: what importing each dive of the file would do to the cloud logbook; nothing is changed. + guard let path = arguments.dropFirst().first else { fail("missing file to check") } + let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path)))) + let found = try await repository.dispositions(of: dives) + for dive in dives { + let c = NaiveTime.components(dive.when) + let date = String(format: "%04d-%02d-%02d %02d:%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0) + let what: String + switch found[dive.id] { + case .duplicate(let existing): what = "already in the logbook (dive \(existing.number))" + case .merge(let existing): what = "would join dive \(existing.number) as one more computer" + case .new, nil: what = "new" + } + print(" \(date) \(dive.durationSeconds / 60) min \(what)") + } case "renumber-plan": // Dives in chronological order should be numbered 1, 2, 3…: lists those that are not, with their notes, // so that a list of changes can be prepared and reviewed before `apply`. diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift @@ -247,6 +247,44 @@ final class ImportTests: XCTestCase { } } + /// Merging dives by hand leaves no hole in the numbering, and what was merged is not offered again. + func testManualMergeClosesTheNumbering() async throws { + let (remote, _) = try Fixture.makeRemote() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: Fixture.branch, + authorName: "DiveLog", authorEmail: Fixture.branch) + _ = try await repo.sync(transport: transport) + func immersion(_ id: String, at when: Int) -> ImportedDive { + var dive = ImportedDive(when: when, durationSeconds: 600) + dive.sourceID = id + dive.model = "Shearwater Petrel 3" + dive.serial = "1a2b3c4d" + dive.samples = stride(from: 60, through: 600, by: 60).map { ImportedDive.Sample(time: $0, depth: 9) } + return dive + } + let start = 1_781_619_660 + let parts = [immersion("a", at: start), immersion("b", at: start + 1500), immersion("c", at: start + 3000)] + let later = immersion("d", at: start + 9000) + _ = try await repo.importDives(parts + [later]) + var log = try await repo.logbook() + let first = try XCTUnwrap(log.dives.first { $0.when == start }).number + XCTAssertEqual(log.dives.first { $0.when == start + 9000 }?.number, first + 3) + + log = try await repo.mergeDives(log.dives.filter { $0.when >= start && $0.when <= start + 3000 }) + XCTAssertEqual(log.dives.first { $0.when == start }?.number, first) + XCTAssertEqual(log.dives.first { $0.when == start + 9000 }?.number, first + 1) + XCTAssertEqual(Set(log.dives.map(\.number)).count, log.dives.count) + + // The three immersions are still known, each one inside the merged dive. + let found = try await repo.dispositions(of: parts) + for part in parts { + guard case .duplicate(let existing)? = found[part.id] else { return XCTFail("\(part.id) should be known") } + XCTAssertEqual(existing.number, first) + } + _ = try await repo.sync(transport: transport) + try remote.git(["fsck", "--strict"]) + } + /// Dive dropped by Open Rémora (JSON of RemoraDeco's `DiveLog`, sorted keys, ISO 8601 dates). func testOpenRemoraDive() throws { let json = """ diff --git a/README.md b/README.md @@ -21,7 +21,7 @@ The app is available in English and French. Mac): full profiles, gases, deco stops, pressure, sites created as needed, duplicates skipped. - Download from a dive computer over Bluetooth LE, with libdivecomputer: the app lists the computers nearby that 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 + them like a file import. Checked on a real Shearwater Petrel 3 (2026-11-14); Heinrichs-Weikamp computers need a flow-control step that is not written yet. - 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 diff --git a/fastlane/Fastfile b/fastlane/Fastfile @@ -61,9 +61,9 @@ platform :ios do end texts = { "fr-CA" => ["Votre carnet de plongée Subsurface sur iPhone : lecture, profils, modification hors ligne, synchronisation avec le nuage Subsurface. Application indépendante de l'équipe de Subsurface.", - "0.3 : Nouveau : télécharger les plongées d'un ordinateur de plongée par Bluetooth (Plongées → + → « Télécharger depuis un ordinateur de plongée »). Mettre l'ordinateur en mode Bluetooth, toucher son nom, puis choisir les plongées à importer. En cas d'échec, « Partager le journal technique » m'aide à corriger. Vérifié pour l'instant avec des journaux Shearwater seulement."], + "0.4 : Nouveau : fusionner des plongées (Plongées, +, Fusionner des plongées) : les immersions choisies deviennent une seule plongée et la numérotation se referme. Une plongée déjà fusionnée n'est plus reproposée par l'ordinateur. Rappel 0.3 : téléchargement Bluetooth depuis un ordinateur de plongée (vérifié sur un Shearwater Petrel 3) ; après un téléchargement, l'app indique le prochain numéro du carnet."], "en-CA" => ["Your Subsurface dive log on iPhone: browse, profiles, offline editing, sync with Subsurface cloud storage. Independent from the Subsurface team.", - "0.3: New: download dives from a dive computer over Bluetooth (Dives, then +, then Download from a dive computer). Put the computer in Bluetooth mode, tap its name, then pick the dives to import. If it fails, the Share the technical log button helps me fix it. Only checked with Shearwater logs so far."], + "0.4: New: merge dives (Dives, +, Merge dives): the selected immersions become one dive and the numbering closes up. Immersions already merged are no longer offered again by the computer. From 0.3: Bluetooth download from a dive computer (checked on a Shearwater Petrel 3); after a download the app tells the next logbook number."], } _, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations") texts.each do |locale, (description, _)| diff --git a/project.yml b/project.yml @@ -13,7 +13,7 @@ settings: base: DEVELOPMENT_TEAM: CM5RQKJH56 CODE_SIGN_STYLE: Automatic - MARKETING_VERSION: "0.3" + MARKETING_VERSION: "0.4" CURRENT_PROJECT_VERSION: "1" SWIFT_VERSION: "5.0" targets: