commit 110a12f44e4b996a86e0d319f8387060742501d8
parent 0c476a0a0fec1426ef7eae6432c7415ef8de28b2
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 13:42:43 -0500
Edit the cylinders and the weights of a dive
New setEquipment change: the cylinder and weightsystem lines of the Dive file
are rewritten, the cylinders left untouched keep their line byte for byte.
The edit screen lists cylinders (name, volume, working pressure, gas,
pressures, common presets) and weights, in the units on screen.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
6 files changed, 420 insertions(+), 2 deletions(-)
diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings
@@ -421,6 +421,16 @@
}
}
},
+ "Add a cylinder": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ajouter une bouteille"
+ }
+ }
+ }
+ },
"Add a dive with the + button, or pull to sync.": {
"localizations": {
"fr": {
@@ -431,6 +441,16 @@
}
}
},
+ "Add weights": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ajouter du lest"
+ }
+ }
+ }
+ },
"Air": {
"localizations": {
"fr": {
@@ -531,6 +551,16 @@
}
}
},
+ "Belt, pockets…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ceinture, poches…"
+ }
+ }
+ }
+ },
"Bluetooth is off": {
"localizations": {
"fr": {
@@ -651,6 +681,16 @@
}
}
},
+ "Common cylinders": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bouteilles courantes"
+ }
+ }
+ }
+ },
"Computer": {
"localizations": {
"fr": {
@@ -841,6 +881,16 @@
}
}
},
+ "Cylinders": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bouteilles"
+ }
+ }
+ }
+ },
"Deco model": {
"localizations": {
"fr": {
@@ -1031,6 +1081,16 @@
}
}
},
+ "Dive %@: equipment edited": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %@ : équipement modifié"
+ }
+ }
+ }
+ },
"Dive %lld": {
"localizations": {
"fr": {
@@ -1281,6 +1341,16 @@
}
}
},
+ "End": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Fin"
+ }
+ }
+ }
+ },
"Enter your email and password.": {
"localizations": {
"fr": {
@@ -1431,6 +1501,16 @@
}
}
},
+ "Helium": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hélium"
+ }
+ }
+ }
+ },
"Hunting octopuses and tarpon in the beams of our lights.": {
"localizations": {
"fr": {
@@ -1791,6 +1871,16 @@
}
}
},
+ "Name (AL80, steel 100…)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nom (AL80, acier 100…)"
+ }
+ }
+ }
+ },
"Nearby": {
"localizations": {
"fr": {
@@ -2141,6 +2231,16 @@
}
}
},
+ "Oxygen": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Oxygène"
+ }
+ }
+ }
+ },
"Password": {
"localizations": {
"fr": {
@@ -2951,6 +3051,16 @@
}
}
},
+ "Total: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Total : %@"
+ }
+ }
+ }
+ },
"Trilaminate drysuit": {
"localizations": {
"fr": {
@@ -3151,6 +3261,16 @@
}
}
},
+ "Volume": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Volume"
+ }
+ }
+ }
+ },
"Waiting to upload": {
"localizations": {
"fr": {
@@ -3261,6 +3381,16 @@
}
}
},
+ "Working pressure": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pression de service"
+ }
+ }
+ }
+ },
"Year": {
"localizations": {
"fr": {
diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift
@@ -254,6 +254,9 @@ final class AppModel {
let dive = String(number)
let renumbered = String(newNumber)
return String(localized: "Dive \(dive) renumbered to \(renumbered)")
+ case .setEquipment(_, let number, _, _, _):
+ let dive = String(number)
+ return String(localized: "Dive \(dive): equipment edited")
case .mergeDives(_, let number, let others):
let dive = String(number)
let merged = others.map { String($0.number) }.joined(separator: ", ")
diff --git a/App/Model/Units.swift b/App/Model/Units.swift
@@ -19,6 +19,10 @@ struct Units: Equatable {
func temperatureValue(_ celsius: Double) -> Double { imperial ? celsius * 9 / 5 + 32 : celsius }
func celsiusFromDisplay(_ value: Double) -> Double { imperial ? (value - 32) * 5 / 9 : value }
func pressureValue(_ bar: Double) -> Double { imperial ? bar * 14.5038 : bar }
+ func barFromDisplay(_ value: Double) -> Double { imperial ? value / 14.5038 : value }
+ var weightUnit: String { imperial ? "lb" : "kg" }
+ func weightValue(_ kilograms: Double) -> Double { imperial ? kilograms * 2.20462 : kilograms }
+ func kilogramsFromDisplay(_ value: Double) -> Double { imperial ? value / 2.20462 : value }
func depth(_ meters: Double) -> String { "\(number(depthValue(meters), imperial ? 0 : 1)) \(depthUnit)" }
func temperature(_ celsius: Double) -> String { "\(number(temperatureValue(celsius), 0)) \(temperatureUnit)" }
diff --git a/App/Views/DiveEditView.swift b/App/Views/DiveEditView.swift
@@ -16,6 +16,8 @@ struct DiveEditView: View {
@State private var rating = 0
@State private var visibility = 0
@State private var notes = ""
+ @State private var cylinders: [Cylinder] = []
+ @State private var weights: [WeightSystem] = []
@State private var loaded = false
@State private var saving = false
@State private var error: String?
@@ -41,6 +43,40 @@ struct DiveEditView: View {
TextField("Tags, separated by commas", text: $tags)
.textInputAutocapitalization(.never)
}
+ Section {
+ ForEach(cylinders.indices, id: \.self) { index in
+ NavigationLink {
+ CylinderEditor(cylinder: $cylinders[index])
+ } label: {
+ CylinderLabel(cylinder: cylinders[index])
+ }
+ // Only the last one can go: the profile refers to the cylinders by their position.
+ .deleteDisabled(index != cylinders.count - 1)
+ }
+ .onDelete { cylinders.remove(atOffsets: $0) }
+ Button { cylinders.append(Cylinder()) } label: { Label("Add a cylinder", systemImage: "plus.circle") }
+ } header: {
+ Text("Cylinders")
+ }
+ Section {
+ ForEach(weights.indices, id: \.self) { index in
+ HStack {
+ TextField("Belt, pockets…", text: $weights[index].description)
+ TextField("0", value: weightBinding(index), format: .number.precision(.fractionLength(0...1)))
+ .keyboardType(.decimalPad)
+ .multilineTextAlignment(.trailing)
+ .frame(width: 70)
+ Text(model.units.weightUnit).foregroundStyle(.secondary)
+ }
+ }
+ .onDelete { weights.remove(atOffsets: $0) }
+ Button { weights.append(WeightSystem()) } label: { Label("Add weights", systemImage: "plus.circle") }
+ } header: {
+ Text("Weights")
+ } footer: {
+ let total = weights.reduce(0) { $0 + $1.kilograms }
+ if weights.count > 1, total > 0 { Text("Total: \(model.units.weight(total))") }
+ }
Section("Notes") {
TextEditor(text: $notes)
.frame(minHeight: 140)
@@ -54,7 +90,7 @@ struct DiveEditView: View {
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
- Button("Save", action: save).disabled(saving || changes.isEmpty)
+ Button("Save", action: save).disabled(saving || (changes.isEmpty && !equipmentChanged))
}
}
.onAppear {
@@ -68,6 +104,8 @@ struct DiveEditView: View {
rating = dive.rating
visibility = dive.visibility
notes = dive.notes
+ cylinders = dive.cylinders
+ weights = dive.weights
}
}
}
@@ -90,11 +128,47 @@ struct DiveEditView: View {
return fields
}
+ /// Weight of one line, in the units on screen.
+ private func weightBinding(_ index: Int) -> Binding<Double?> {
+ Binding {
+ let kilograms = weights[index].kilograms
+ return kilograms > 0 ? (model.units.weightValue(kilograms) * 10).rounded() / 10 : nil
+ } set: {
+ weights[index].kilograms = $0.map { model.units.kilogramsFromDisplay($0) } ?? 0
+ }
+ }
+
+ /// Lines left empty are not kept.
+ private var cleanCylinders: [Cylinder] {
+ var kept = cylinders
+ while let last = kept.last, kept.count > dive.cylinders.count, last == Cylinder() { kept.removeLast() }
+ return kept
+ }
+
+ private var cleanWeights: [WeightSystem] {
+ weights.filter { $0.kilograms > 0 }.map { weight in
+ var clean = weight
+ clean.description = weight.description.trimmingCharacters(in: .whitespacesAndNewlines)
+ return clean
+ }
+ }
+
+ private var equipmentChanged: Bool { cleanCylinders != dive.cylinders || cleanWeights != dive.weights }
+
private func save() {
saving = true
Task {
do {
- try await model.apply(.editDive(when: dive.when, number: dive.number, fields: changes))
+ if !changes.isEmpty {
+ try await model.apply(.editDive(when: dive.when, number: dive.number, fields: changes))
+ }
+ if equipmentChanged {
+ let new = cleanCylinders
+ let unchanged = new.indices.filter { $0 < dive.cylinders.count && new[$0] == dive.cylinders[$0] }
+ try await model.apply(.setEquipment(when: dive.when, number: dive.number,
+ cylinders: new != dive.cylinders ? new : nil, unchangedCylinders: Array(unchanged),
+ weights: cleanWeights != dive.weights ? cleanWeights : nil))
+ }
dismiss()
} catch {
self.error = AppModel.describe(error)
@@ -104,6 +178,104 @@ struct DiveEditView: View {
}
}
+/// One cylinder in the list: its name, its gas, its pressures.
+struct CylinderLabel: View {
+ @Environment(AppModel.self) private var model
+ let cylinder: Cylinder
+
+ var body: some View {
+ HStack {
+ Text(cylinder.description.isEmpty ? String(localized: "Cylinder") : cylinder.description)
+ Spacer()
+ VStack(alignment: .trailing, spacing: 2) {
+ Text(cylinder.gas.label)
+ .foregroundStyle(cylinder.gas.isAir ? Color.secondary : Color.green)
+ if let start = cylinder.startBar, let end = cylinder.endBar {
+ Text(verbatim: "\(model.units.pressure(start)) → \(model.units.pressure(end))")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+}
+
+/// Edits one cylinder. The logbook is metric: pressures are converted to and from the units on screen.
+struct CylinderEditor: View {
+ @Environment(AppModel.self) private var model
+ @Binding var cylinder: Cylinder
+
+ private static let presets: [(name: String, liters: Double, bar: Double)] = [
+ ("AL80", 11.1, 207), ("AL63", 9.0, 207), ("AL40", 5.7, 207), ("HP100", 12.9, 237), ("HP130", 16.8, 237),
+ ("10 L 232 bar", 10, 232), ("12 L 232 bar", 12, 232), ("15 L 232 bar", 15, 232),
+ ]
+
+ var body: some View {
+ Form {
+ Section {
+ TextField("Name (AL80, steel 100…)", text: $cylinder.description)
+ Menu {
+ ForEach(Self.presets, id: \.name) { preset in
+ Button(preset.name) {
+ cylinder.description = preset.name
+ cylinder.volumeLiters = preset.liters
+ cylinder.workPressureBar = preset.bar
+ }
+ }
+ } label: {
+ Label("Common cylinders", systemImage: "list.bullet")
+ }
+ field("Volume", $cylinder.volumeLiters, unit: "L", digits: 1)
+ field("Working pressure", pressure(\.workPressureBar), unit: model.units.pressureUnit, digits: 0)
+ }
+ Section("Gas") {
+ field("Oxygen", percent(\.o2Permille, empty: 0), unit: "%", digits: 0, prompt: "21")
+ field("Helium", percent(\.hePermille, empty: 0), unit: "%", digits: 0)
+ }
+ Section("Pressure") {
+ field("Start", pressure(\.startBar), unit: model.units.pressureUnit, digits: 0)
+ field("End", pressure(\.endBar), unit: model.units.pressureUnit, digits: 0)
+ }
+ }
+ .navigationTitle(cylinder.description.isEmpty ? String(localized: "Cylinder") : cylinder.description)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private func field(_ title: LocalizedStringKey, _ value: Binding<Double?>, unit: String, digits: Int, prompt: String = "") -> some View {
+ HStack {
+ Text(title)
+ Spacer()
+ TextField(prompt, value: value, format: .number.precision(.fractionLength(0...digits)))
+ .keyboardType(.decimalPad)
+ .multilineTextAlignment(.trailing)
+ .frame(width: 90)
+ Text(unit).foregroundStyle(.secondary).frame(minWidth: 28, alignment: .leading)
+ }
+ }
+
+ private func pressure(_ path: WritableKeyPath<Cylinder, Double?>) -> Binding<Double?> {
+ Binding {
+ cylinder[keyPath: path].map { model.units.pressureValue($0).rounded() }
+ } set: {
+ cylinder[keyPath: path] = $0.flatMap { $0 > 0 ? model.units.barFromDisplay($0) : nil }
+ }
+ }
+
+ /// A gas fraction, in percent on screen and per mille in the logbook (0 % of oxygen stands for air).
+ private func percent(_ path: WritableKeyPath<GasMix, Int>, empty: Int) -> Binding<Double?> {
+ Binding {
+ let permille = cylinder.gas[keyPath: path]
+ return permille > 0 ? Double(permille) / 10 : nil
+ } set: {
+ cylinder.gas[keyPath: path] = $0.map { Int(($0 * 10).rounded()).clamped(to: 0...1000) } ?? empty
+ }
+ }
+}
+
+private extension Int {
+ func clamped(to range: ClosedRange<Int>) -> Int { Swift.min(Swift.max(self, range.lowerBound), range.upperBound) }
+}
+
/// Picks an existing site, or creates a site from its name.
struct SitePicker: View {
@Environment(AppModel.self) private var model
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift
@@ -59,6 +59,9 @@ public enum LogChange: Codable, Sendable, Equatable {
case removeSite(uuid: UInt32)
/// Changes the number of a dive (the number is carried by the file name, "Dive-N").
case renumberDive(when: Int, number: Int, newNumber: Int)
+ /// Replaces the cylinders and the weights of a dive (nil: left alone). The cylinders whose index is in
+ /// `unchangedCylinders` keep their line byte for byte, with whatever this app does not know about them.
+ case setEquipment(when: Int, number: Int, cylinders: [Cylinder]?, unchangedCylinders: [Int], weights: [WeightSystem]?)
public var summary: String {
switch self {
@@ -71,6 +74,7 @@ public enum LogChange: Codable, Sendable, Equatable {
case .locateSite: return "site position"
case .removeSite: return "site removed"
case .renumberDive(_, let number, let newNumber): return "dive \(number) renumbered \(newNumber)"
+ case .setEquipment(_, let number, _, _, _): return "dive \(number): equipment"
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: ", "))"
@@ -155,6 +159,54 @@ public enum LogEditor {
return lines.flatMap(\.bytes)
}
+ /// A "cylinder" line as Subsurface writes it (`save_cylinder_info` in save-git.cpp).
+ static func line(_ cylinder: Cylinder) -> String {
+ var text = "cylinder"
+ if let volume = cylinder.volumeLiters, volume > 0 { text += " vol=\(LogFormat.milli(volume))l" }
+ if let pressure = cylinder.workPressureBar, pressure > 0 { text += " workpressure=\(LogFormat.milli(pressure))bar" }
+ if !cylinder.description.isEmpty { text += " description=\(LogFormat.quote(cylinder.description))" }
+ if !cylinder.gas.isAir || cylinder.gas.hePermille > 0 {
+ if cylinder.gas.o2Permille > 0 { text += " o2=\(LogFormat.milli(cylinder.gas.o2Permille * 100))%" }
+ if cylinder.gas.hePermille > 0 { text += " he=\(LogFormat.milli(cylinder.gas.hePermille * 100))%" }
+ }
+ if let start = cylinder.startBar, start > 0 { text += " start=\(LogFormat.milli(start))bar" }
+ if let end = cylinder.endBar, end > 0 { text += " end=\(LogFormat.milli(end))bar" }
+ if let use = cylinder.use, !use.isEmpty { text += " use=\(LogFormat.quote(use))" }
+ return text + "\n"
+ }
+
+ static func line(_ weight: WeightSystem) -> String {
+ "weightsystem weight=\(LogFormat.milli(weight.kilograms))kg description=\(LogFormat.quote(weight.description))\n"
+ }
+
+ /// Replaces the "cylinder" and "weightsystem" lines of a "Dive" file; every other line keeps its bytes.
+ static func patch(diveFile data: [UInt8], cylinders: [Cylinder]?, unchangedCylinders: [Int], weights: [WeightSystem]?) -> [UInt8] {
+ var lines: [(keyword: String, bytes: [UInt8])] = LogFormat.lines(data).map {
+ (String($0.keyword), Array(data[$0.range]))
+ }
+ if var last = lines.last, last.bytes.last != 0x0a {
+ last.bytes.append(0x0a)
+ lines[lines.count - 1] = last
+ }
+ func rank(_ keyword: String) -> Int { order.firstIndex(of: keyword) ?? order.count }
+ func replace(_ keyword: String, with replacement: [[UInt8]]) {
+ let position = lines.firstIndex { $0.keyword == keyword } ?? lines.firstIndex { rank($0.keyword) > rank(keyword) } ?? lines.count
+ let before = lines[..<position].filter { $0.keyword != keyword }.count
+ lines.removeAll { $0.keyword == keyword }
+ lines.insert(contentsOf: replacement.map { (keyword, $0) }, at: before)
+ }
+ if let cylinders {
+ let existing = lines.filter { $0.keyword == "cylinder" }.map(\.bytes)
+ replace("cylinder", with: cylinders.enumerated().map { index, cylinder in
+ unchangedCylinders.contains(index) && index < existing.count ? existing[index] : Array(line(cylinder).utf8)
+ })
+ }
+ if let weights {
+ replace("weightsystem", with: weights.filter { $0.kilograms > 0 }.map { Array(line($0).utf8) })
+ }
+ return lines.flatMap(\.bytes)
+ }
+
// MARK: Trees
/// Replaces (or removes, if `entry` is nil) the entry at the end of `path` and returns the new root tree.
@@ -327,6 +379,14 @@ public enum LogEditor {
else { throw ChangeError.diveNotFound(Int(uuid)) }
result = try replacing(root: current, path: ["01-Divesites", file.name], with: nil, store: store)
+ case .setEquipment(let when, let number, let cylinders, let unchanged, let weights):
+ guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store),
+ let file = try store.tree(directory.tree).first(where: { !$0.isTree && LogWalker.diveNumber(fileName: $0.name) != nil })
+ else { throw ChangeError.diveNotFound(when) }
+ let patched = patch(diveFile: try store.blob(file.id), cylinders: cylinders, unchangedCylinders: unchanged, weights: weights)
+ let blob = try store.put(GitObject(type: .blob, data: patched))
+ result = try replacing(root: current, path: directory.path + [file.name], with: .blob(file.name, blob), store: store)
+
case .renumberDive(let when, let number, let newNumber):
guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store),
let file = try store.tree(directory.tree).first(where: { !$0.isTree && LogWalker.diveNumber(fileName: $0.name) != nil })
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift
@@ -157,6 +157,55 @@ final class SubsurfaceLogTests: XCTestCase {
"duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n")
}
+ /// Editing the equipment rewrites the lines that changed and nothing else.
+ func testEquipmentPatch() {
+ let file = """
+ duration 45:00 min
+ buddy "Sam"
+ cylinder vol=11.1l workpressure=207.0bar description="AL80" o2=32.0% start=200.0bar end=60.0bar depth=33.998m
+ cylinder vol=5.7l description="AL40" o2=50.0% use="not used"
+ weightsystem weight=6.0kg description="ceinture"
+ watertemp 12.0°C
+
+ """
+ var first = Cylinder()
+ first.description = "ignored: this line is kept as it is"
+ var second = Cylinder()
+ second.description = "AL40"
+ second.volumeLiters = 5.7
+ second.gas = GasMix(o2Permille: 800)
+ second.startBar = 190
+ second.endBar = 150
+ var third = Cylinder()
+ third.description = "D12"
+ third.gas = GasMix(o2Permille: 180, hePermille: 450)
+ var belt = WeightSystem()
+ belt.kilograms = 4.5
+ belt.description = "belt"
+ var pockets = WeightSystem()
+ pockets.kilograms = 2
+ pockets.description = "pockets"
+ let patched = String(decoding: LogEditor.patch(diveFile: Array(file.utf8), cylinders: [first, second, third],
+ unchangedCylinders: [0], weights: [belt, pockets]), as: UTF8.self)
+ XCTAssertEqual(patched, """
+ duration 45:00 min
+ buddy "Sam"
+ cylinder vol=11.1l workpressure=207.0bar description="AL80" o2=32.0% start=200.0bar end=60.0bar depth=33.998m
+ cylinder vol=5.7l description="AL40" o2=80.0% start=190.0bar end=150.0bar
+ cylinder description="D12" o2=18.0% he=45.0%
+ weightsystem weight=4.5kg description="belt"
+ weightsystem weight=2.0kg description="pockets"
+ watertemp 12.0°C
+
+ """)
+ // No equipment at all yet: the lines land at their place in the file.
+ let bare = "duration 30:00 min\nnotes \"x\"\nwatertemp 9.0°C\n"
+ XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: Array(bare.utf8), cylinders: [third], unchangedCylinders: [], weights: [belt]), as: UTF8.self),
+ "duration 30:00 min\nnotes \"x\"\ncylinder description=\"D12\" o2=18.0% he=45.0%\nweightsystem weight=4.5kg description=\"belt\"\nwatertemp 9.0°C\n")
+ // Weights removed, cylinders left alone.
+ XCTAssertFalse(String(decoding: LogEditor.patch(diveFile: Array(file.utf8), cylinders: nil, unchangedCylinders: [], weights: []), as: UTF8.self).contains("weightsystem"))
+ }
+
func testSyncEditsAndPush() async throws {
let (remote, _) = try Fixture.makeRemote()
let transport = LocalProcessTransport(repository: remote.directory)