commit e51e48f971d9eda90bab412b30bd939c7b852be6
parent da995711c4e61d9ca66ce01f8fe00591c8e57a59
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 11:11:55 -0500
Merged dives: follow save-git for the duration and the sensor mappings
Checked against the Subsurface sources (save-git.cpp, load-git.cpp,
dive.cpp, divecomputer.cpp, event.cpp); the functions relied on are
cited in Merge.swift.
- The duration of the "Dive" file is the first computer's
(create_dive_buffer), not the longest.
- A computer with tanksensormapping lines keeps its sensor numbers and
has the mapping renumbered; without any, sensor N is cylinder N and
the samples are renumbered, old "sensor=N" and bare "bar" included.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYJwSV8KMFfnh7K4gJq
Diffstat:
3 files changed, 64 insertions(+), 9 deletions(-)
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Merge.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Merge.swift
@@ -16,6 +16,28 @@ public struct DiveRef: Codable, Sendable, Equatable, Hashable {
/// 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.
+///
+/// What is written here was checked against the Subsurface sources (`core/save-git.cpp`, `core/load-git.cpp`,
+/// `core/dive.cpp`, `core/divecomputer.cpp`, `core/event.cpp`, master of 2026-11-14):
+/// - File names: `save_one_dive` numbers the computers from 1 when there are several and passes 0 for a single
+/// one; `save_one_divecomputer` formats `"Divecomputer%c%03u"` with the dash only for a non-zero index, hence
+/// `Divecomputer`, or `Divecomputer-001`, `Divecomputer-002`… `walk_tree_file` reads them in the order of the git
+/// tree (the "Dive" file sorts before them) and `create_new_dc` appends each one: the first file is `dcs[0]`.
+/// - Start of a computer: `save_dc` calls `show_date` (`date %04u-%02u-%02u`, `time %02u:%02u:%02u`) when
+/// `dc.when != dive.when`, after `model`, `lastmanualtime`, `deviceid`, `diveid` and before `duration`;
+/// `create_new_dc` starts from the dive's time and `parse_dc_date` / `parse_dc_time` override it.
+/// - Duration: `create_dive_buffer` writes the `duration` of the "Dive" file from `dcs[0].duration`, and `save_dc`
+/// gives a computer its own `duration` line when it differs from that. On load both are recomputed anyway:
+/// `fixup_dc_duration` from the samples (surface segments left out) and `fixup_duration` as the longest of the
+/// computers. Depths and temperatures live in the computer files and are likewise recomputed (`fixup_dive`).
+/// - Cylinders: a gas change says `cylinder=N`, the zero-based index of the cylinder in the "Dive" file
+/// (`save_one_event`, `parse_event_keyvalue`); `flags` holds the same index plus one as an older extension
+/// (`event::event`). A pressure `…bar:N` names a sensor (`save_sample`, `parse_sample_unit`); sensor N is
+/// cylinder N unless the computer has `tanksensormapping "sensor" "cylinder"` lines (`save_tank_sensor_mappings`,
+/// `get_tank_sensor_mappings_for_storage`, where sensor -1 only says "no mapping").
+/// - Subsurface's own merge (`dive::create_merged_dive`) joins profiles on one timeline for the same device at
+/// another time (`interleave_dive_computers`) and keeps different computers side by side
+/// (`join_dive_computers`); `LogEditor.merged` does the same.
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.
@@ -215,9 +237,17 @@ struct ComputerFile {
hasOwnStart = true
}
- /// The cylinders of a dive are numbered in its "Dive" file; a computer moved to another dive follows the new numbers.
+ /// The cylinders of a dive are numbered in its "Dive" file; a computer moved to another dive follows the new
+ /// numbers: in its gas changes, and for its pressure sensors either in its `tanksensormapping` lines or, without
+ /// any (sensor N is then cylinder N), in the samples themselves.
mutating func remapCylinders(_ map: [Int: Int]) {
guard map.contains(where: { $0.key != $0.value }) else { return }
+ let mapped = header.contains { $0.keyword == "tanksensormapping" }
+ header = header.map { line in
+ guard line.keyword == "tanksensormapping", let strings = LogFormat.lines(line.bytes).first?.strings, strings.count == 2,
+ let sensor = Int(strings[0]), sensor >= 0, let old = Int(strings[1]), let new = map[old] else { return line }
+ return Line(keyword: line.keyword, bytes: Array("tanksensormapping \"\(sensor)\" \"\(new)\"\n".utf8))
+ }
events = events.map { line in
let text = Self.text(line)
let isGasChange = text.contains("name=\"gaschange")
@@ -231,8 +261,11 @@ struct ComputerFile {
}
samples = samples.map { line in
let text = Self.text(line)
- guard text.contains("bar:") else { return line }
+ guard !mapped, text.contains("bar") || text.contains("sensor=") else { return line }
let tokens = text.split(separator: " ", omittingEmptySubsequences: false).map { token -> String in
+ // Old files: "sensor=N" sets the sensor of the pressures that follow, and a bare "bar" is sensor 0.
+ if token.hasPrefix("sensor="), let old = Int(token.dropFirst(7)), let new = map[old] { return "sensor=\(new)" }
+ if token.hasSuffix("bar"), !token.contains("="), !text.contains("sensor="), let new = map[0], new != 0 { return "\(token):\(new)" }
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)"
}
@@ -409,7 +442,7 @@ extension LogEditor {
/// 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.
+ /// duration of the dive is the one of its first computer, as Subsurface writes it.
static func merged(_ target: DiveParts, with others: [DiveParts]) -> (diveFile: [UInt8], computers: [[UInt8]]) {
var file = target.diveFile
var computers = [ComputerFile]()
@@ -443,7 +476,7 @@ extension LogEditor {
(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) }
+ if let primary = ordered.first, primary.duration > 0 { file = setting(duration: primary.duration, inDiveFile: file) }
return (file, ordered.map(\.bytes))
}
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/MergeTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/MergeTests.swift
@@ -161,6 +161,26 @@ final class MergeTests: XCTestCase {
0:20 6.0m 12.0°C 50.0bar:2 ndl=5:00
""")
+
+ // A computer that maps its sensors to cylinders keeps its sensor numbers: the mapping follows the cylinders.
+ let mapped = """
+ model "Y"
+ tanksensormapping "0" "1"
+ tanksensormapping "3" "0"
+ tanksensormapping "-1" "0"
+ 0:10 5.0m 200.0bar:0 po2=1.2bar
+ 0:20 6.0m 50.0bar:3
+
+ """
+ computer = ComputerFile(Array(mapped.utf8), diveWhen: 1000, diveDuration: 0)
+ computer.remapCylinders(filled.cylinders)
+ XCTAssertEqual(String(decoding: computer.bytes, as: UTF8.self), mapped
+ .replacingOccurrences(of: "\"0\" \"1\"", with: "\"0\" \"2\"").replacingOccurrences(of: "\"3\" \"0\"", with: "\"3\" \"1\""))
+ // Old files: a pressure without a sensor is sensor 0, and "sensor=N" names it.
+ let old = "model \"Z\"\n 0:10 5.0m 200.0bar po2=1.2bar\n 0:20 6.0m sensor=1 50.0bar\n"
+ computer = ComputerFile(Array(old.utf8), diveWhen: 1000, diveDuration: 0)
+ computer.remapCylinders(filled.cylinders)
+ XCTAssertEqual(String(decoding: computer.bytes, as: UTF8.self), "model \"Z\"\n 0:10 5.0m 200.0bar:1 po2=1.2bar\n 0:20 6.0m sensor=2 50.0bar\n")
}
// MARK: Automatic merge at import
@@ -327,15 +347,17 @@ final class MergeTests: XCTestCase {
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)
+ // The dive has everything it needs already: its file is the desktop's, byte for byte, unknown line included,
+ // except for the duration, which Subsurface writes from the first computer.
+ XCTAssertEqual(String(decoding: try remote.git(["show", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Dive-41"]), as: UTF8.self),
+ desktop.replacingOccurrences(of: "duration 45:30 min", with: "duration 44:00 min"))
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(dive.durationSeconds, 44 * 60)
XCTAssertEqual(log.site(of: dive)?.name, "Carrière Morrison")
XCTAssertEqual(log.sites.count, 1)
@@ -392,7 +414,7 @@ final class MergeTests: XCTestCase {
XCTAssertEqual(dive.tags, ["lac"])
XCTAssertEqual(dive.cylinders.map(\.description), ["AL80"])
XCTAssertEqual(dive.cylinders.first?.startBar, 200)
- XCTAssertEqual(dive.durationSeconds, 2400)
+ XCTAssertEqual(dive.durationSeconds, 38 * 60) // the first computer's
XCTAssertEqual(dive.maxDepth, 18)
// The merge goes through the change queue: it survives a restart and is replayed on the server's state.
diff --git a/README.md b/README.md
@@ -33,7 +33,7 @@ The app is available in English and French.
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
+ then the other dive computers, then Open Mérou (`DiveMerge.rank`), and the duration shown is the first computer's. 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