Changes.swift (23414B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import GitLite 4 5 /// Fields of a dive that can be edited from the app. 6 public enum DiveField: String, Codable, Sendable, CaseIterable { 7 case rating, visibility, tags, site, divemaster, buddy, suit, notes 8 } 9 10 public struct NewDive: Codable, Sendable, Equatable { 11 public var when: Int 12 public var number: Int 13 public var durationSeconds: Int 14 public var maxDepth: Double 15 public var siteUUID: UInt32? 16 public var buddy = "" 17 public var divemaster = "" 18 public var suit = "" 19 public var notes = "" 20 public var rating = 0 21 public var visibility = 0 22 public var waterTemperature: Double? 23 public var tags: [String] = [] 24 /// Cylinder and weights, for dives copied from a paper logbook. 25 public var tank: String? 26 public var o2Percent: Int? 27 public var startBar: Double? 28 public var endBar: Double? 29 public var weightKg: Double? 30 31 public init(when: Int, number: Int, durationSeconds: Int, maxDepth: Double) { 32 self.when = when 33 self.number = number 34 self.durationSeconds = durationSeconds 35 self.maxDepth = maxDepth 36 } 37 } 38 39 /// A change waiting to be sent. It can be replayed on any state of the logbook: that is what makes it possible to 40 /// work offline and then apply on top of whatever another device has pushed in the meantime. 41 public enum LogChange: Codable, Sendable, Equatable { 42 /// Text values: integers for the ratings out of 5, hexadecimal UUID for the site, comma-separated tags. 43 case editDive(when: Int, number: Int, fields: [String: String]) 44 case addDive(NewDive) 45 case deleteDive(when: Int, number: Int) 46 case addSite(uuid: UInt32, name: String, latitude: Double?, longitude: Double?) 47 /// Dive coming from an external file or from a dive computer, with its full profile. When the logbook already 48 /// has a dive at that time (overlapping time ranges), the dive joins it as one more dive computer and `number` 49 /// is not used; the very same dive from the very same computer is refused (`diveAlreadyExists`). 50 case importDive(ImportedDive, number: Int, siteUUID: UInt32?) 51 /// Merges `others` into the dive `when`/`number`, which keeps its date, number and everything it has; see 52 /// `LogEditor.merged`. Dives that are gone by the time the change is replayed are left out. 53 case mergeDives(when: Int, number: Int, others: [DiveRef]) 54 /// Changes nothing except adding the settings file if it is missing. 55 case ensureSettings 56 /// Sets or replaces the position of an existing site; the rest of its record is kept. 57 case locateSite(uuid: UInt32, latitude: Double, longitude: Double) 58 /// Removes a site record (the dives that were there must have been attached elsewhere beforehand). 59 case removeSite(uuid: UInt32) 60 /// Changes the number of a dive (the number is carried by the file name, "Dive-N"). 61 case renumberDive(when: Int, number: Int, newNumber: Int) 62 /// Replaces the cylinders and the weights of a dive (nil: left alone). The cylinders whose index is in 63 /// `unchangedCylinders` keep their line byte for byte, with whatever this app does not know about them. 64 case setEquipment(when: Int, number: Int, cylinders: [Cylinder]?, unchangedCylinders: [Int], weights: [WeightSystem]?) 65 66 public var summary: String { 67 switch self { 68 case .editDive(_, let number, let fields): 69 return "dive \(number) edited (\(fields.keys.sorted().joined(separator: ", ")))" 70 case .addDive(let dive): return "dive \(dive.number) added" 71 case .deleteDive(_, let number): return "dive \(number) deleted" 72 case .addSite(_, let name, _, _): return "site added: \(name)" 73 case .ensureSettings: return "logbook settings" 74 case .locateSite: return "site position" 75 case .removeSite: return "site removed" 76 case .renumberDive(_, let number, let newNumber): return "dive \(number) renumbered \(newNumber)" 77 case .setEquipment(_, let number, _, _, _): return "dive \(number): equipment" 78 case .importDive(let dive, let number, _): return "dive \(number) imported (\(dive.model))" 79 case .mergeDives(_, let number, let others): 80 return "dive \(number) merged with \(others.map { String($0.number) }.joined(separator: ", "))" 81 } 82 } 83 } 84 85 public enum ChangeError: Error, Equatable, CustomStringConvertible { 86 case diveNotFound(Int) 87 case diveAlreadyExists(Int) 88 89 public var description: String { 90 switch self { 91 case .diveNotFound: return "the dive no longer exists in the logbook" 92 case .diveAlreadyExists: return "this dive is already in the logbook" 93 } 94 } 95 } 96 97 public enum LogEditor { 98 /// Order of the lines of the "Dive" file, as Subsurface writes it. 99 static let order = ["duration", "rating", "visibility", "wavesize", "current", "surge", "chill", "watersalinity", 100 "airpressure", "notrip", "invalid", "tags", "divesiteid", "divemaster", "buddy", "suit", "notes", 101 "cylinder", "weightsystem", "airtemp", "watertemp"] 102 103 static func keyword(_ field: DiveField) -> String { 104 field == .site ? "divesiteid" : field.rawValue 105 } 106 107 /// Line to write for a field, or nil if the value is empty (the line then disappears, as in Subsurface). 108 static func line(_ field: DiveField, _ value: String) -> String? { 109 switch field { 110 case .rating, .visibility: 111 let n = Int(value) ?? 0 112 return n > 0 ? "\(field.rawValue) \(n)\n" : nil 113 case .tags: 114 let tags = value.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } 115 return tags.isEmpty ? nil : "tags " + tags.map(LogFormat.quote).joined(separator: ", ") + "\n" 116 case .site: 117 guard let uuid = UInt32(value, radix: 16), uuid != 0 else { return nil } 118 return "divesiteid " + String(format: "%08x", uuid) + "\n" 119 case .divemaster, .buddy, .suit, .notes: 120 return value.isEmpty ? nil : "\(field.rawValue) \(LogFormat.quote(value))\n" 121 } 122 } 123 124 /// Rewrites only the lines of the edited fields; everything else in the file is kept byte for byte, 125 /// including the lines this app does not know about. 126 static func patch(diveFile data: [UInt8], fields: [DiveField: String]) -> [UInt8] { 127 var lines: [(keyword: String, bytes: [UInt8])] = LogFormat.lines(data).map { 128 (String($0.keyword), Array(data[$0.range])) 129 } 130 if var last = lines.last, last.bytes.last != 0x0a { 131 last.bytes.append(0x0a) 132 lines[lines.count - 1] = last 133 } 134 func rank(_ keyword: String) -> Int { order.firstIndex(of: keyword) ?? order.count } 135 for field in DiveField.allCases { 136 guard let value = fields[field] else { continue } 137 let key = keyword(field) 138 var replacement = line(field, value).map { Array($0.utf8) } 139 let existing = lines.firstIndex(where: { $0.keyword == key }) 140 // Subsurface keeps the line of a text that was emptied (`buddy ""`): we do the same when it already exists. 141 if replacement == nil, existing != nil, [.divemaster, .buddy, .suit, .notes].contains(field) { 142 replacement = Array("\(key) \"\"\n".utf8) 143 } 144 if let index = existing { 145 if let replacement { 146 lines[index].bytes = replacement 147 } else { 148 lines.remove(at: index) 149 } 150 // Old logbooks: the location written in plain text gives way to the site record. 151 } else if let replacement { 152 let position = lines.firstIndex(where: { rank($0.keyword) > rank(key) }) ?? lines.count 153 lines.insert((key, replacement), at: position) 154 } 155 if field == .site { 156 lines.removeAll { $0.keyword == "location" || $0.keyword == "gps" } 157 } 158 } 159 return lines.flatMap(\.bytes) 160 } 161 162 /// A "cylinder" line as Subsurface writes it (`save_cylinder_info` in save-git.cpp). 163 static func line(_ cylinder: Cylinder) -> String { 164 var text = "cylinder" 165 if let volume = cylinder.volumeLiters, volume > 0 { text += " vol=\(LogFormat.milli(volume))l" } 166 if let pressure = cylinder.workPressureBar, pressure > 0 { text += " workpressure=\(LogFormat.milli(pressure))bar" } 167 if !cylinder.description.isEmpty { text += " description=\(LogFormat.quote(cylinder.description))" } 168 if !cylinder.gas.isAir || cylinder.gas.hePermille > 0 { 169 if cylinder.gas.o2Permille > 0 { text += " o2=\(LogFormat.milli(cylinder.gas.o2Permille * 100))%" } 170 if cylinder.gas.hePermille > 0 { text += " he=\(LogFormat.milli(cylinder.gas.hePermille * 100))%" } 171 } 172 if let start = cylinder.startBar, start > 0 { text += " start=\(LogFormat.milli(start))bar" } 173 if let end = cylinder.endBar, end > 0 { text += " end=\(LogFormat.milli(end))bar" } 174 if let use = cylinder.use, !use.isEmpty { text += " use=\(LogFormat.quote(use))" } 175 return text + "\n" 176 } 177 178 static func line(_ weight: WeightSystem) -> String { 179 "weightsystem weight=\(LogFormat.milli(weight.kilograms))kg description=\(LogFormat.quote(weight.description))\n" 180 } 181 182 /// Replaces the "cylinder" and "weightsystem" lines of a "Dive" file; every other line keeps its bytes. 183 static func patch(diveFile data: [UInt8], cylinders: [Cylinder]?, unchangedCylinders: [Int], weights: [WeightSystem]?) -> [UInt8] { 184 var lines: [(keyword: String, bytes: [UInt8])] = LogFormat.lines(data).map { 185 (String($0.keyword), Array(data[$0.range])) 186 } 187 if var last = lines.last, last.bytes.last != 0x0a { 188 last.bytes.append(0x0a) 189 lines[lines.count - 1] = last 190 } 191 func rank(_ keyword: String) -> Int { order.firstIndex(of: keyword) ?? order.count } 192 func replace(_ keyword: String, with replacement: [[UInt8]]) { 193 let position = lines.firstIndex { $0.keyword == keyword } ?? lines.firstIndex { rank($0.keyword) > rank(keyword) } ?? lines.count 194 let before = lines[..<position].filter { $0.keyword != keyword }.count 195 lines.removeAll { $0.keyword == keyword } 196 lines.insert(contentsOf: replacement.map { (keyword, $0) }, at: before) 197 } 198 if let cylinders { 199 let existing = lines.filter { $0.keyword == "cylinder" }.map(\.bytes) 200 replace("cylinder", with: cylinders.enumerated().map { index, cylinder in 201 unchangedCylinders.contains(index) && index < existing.count ? existing[index] : Array(line(cylinder).utf8) 202 }) 203 } 204 if let weights { 205 replace("weightsystem", with: weights.filter { $0.kilograms > 0 }.map { Array(line($0).utf8) }) 206 } 207 return lines.flatMap(\.bytes) 208 } 209 210 // MARK: Trees 211 212 /// Replaces (or removes, if `entry` is nil) the entry at the end of `path` and returns the new root tree. 213 /// Missing intermediate directories are created; a directory left empty is removed from its parent. 214 static func replacing(root: ObjectID?, path: [String], with entry: TreeEntry?, store: ObjectStore) throws -> ObjectID? { 215 guard let name = path.first else { return entry?.id } 216 var entries = try root.map { try store.tree($0) } ?? [] 217 let index = entries.firstIndex { $0.name == name } 218 if path.count == 1 { 219 if let index { entries.remove(at: index) } 220 if let entry { entries.append(TreeEntry(mode: entry.mode, name: name, id: entry.id)) } 221 } else { 222 let existing = index.map { entries[$0] } 223 let child = try replacing(root: existing?.isTree == true ? existing?.id : nil, path: Array(path.dropFirst()), with: entry, store: store) 224 if let index { entries.remove(at: index) } 225 if let child { entries.append(.tree(name, child)) } 226 } 227 if entries.isEmpty { return nil } 228 return try store.putTree(entries) 229 } 230 231 /// Builds a complete tree from "path → content" files. 232 public static func buildTree(files: [String: String], store: ObjectStore) throws -> ObjectID { 233 var blobs = [TreeEntry]() 234 var folders = [String: [String: String]]() 235 for (path, content) in files { 236 let parts = path.split(separator: "/", maxSplits: 1).map(String.init) 237 if parts.count == 1 { 238 blobs.append(.blob(parts[0], try store.putBlob(content))) 239 } else { 240 folders[parts[0], default: [:]][parts[1]] = content 241 } 242 } 243 for (name, inner) in folders { 244 blobs.append(.tree(name, try buildTree(files: inner, store: store))) 245 } 246 return try store.putTree(blobs) 247 } 248 249 /// Path and name of the directory of a dive added by the app. 250 public static func diveDirectory(when: Int) -> String { divePath(when: when).joined(separator: "/") } 251 252 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 253 254 static func divePath(when: Int) -> [String] { 255 let c = NaiveTime.components(when) 256 let name = String(format: "%02d-%@-%02d=%02d=%02d", c.day!, weekdays[(c.weekday! - 1) % 7], c.hour!, c.minute!, c.second!) 257 return [String(format: "%04d", c.year!), String(format: "%02d", c.month!), name] 258 } 259 260 static func diveFile(_ dive: NewDive) -> String { 261 var text = "" 262 if dive.durationSeconds > 0 { text += "duration \(LogFormat.minutes(dive.durationSeconds)) min\n" } 263 var fields = [DiveField: String]() 264 fields[.rating] = String(dive.rating) 265 fields[.visibility] = String(dive.visibility) 266 fields[.tags] = dive.tags.joined(separator: ",") 267 fields[.site] = dive.siteUUID.map { String($0, radix: 16) } ?? "" 268 fields[.divemaster] = dive.divemaster 269 fields[.buddy] = dive.buddy 270 fields[.suit] = dive.suit 271 fields[.notes] = dive.notes 272 for field in DiveField.allCases { 273 if let line = line(field, fields[field] ?? "") { text += line } 274 } 275 if dive.tank != nil || dive.o2Percent != nil || dive.startBar != nil { 276 text += "cylinder" 277 if let tank = dive.tank, !tank.isEmpty { text += " description=\(LogFormat.quote(tank))" } 278 if let o2 = dive.o2Percent, o2 != 21 { text += " o2=\(LogFormat.milli(o2 * 1000))%" } 279 if let start = dive.startBar { text += " start=\(LogFormat.milli(start))bar" } 280 if let end = dive.endBar { text += " end=\(LogFormat.milli(end))bar" } 281 text += "\n" 282 } 283 if let weight = dive.weightKg, weight > 0 { text += "weightsystem weight=\(LogFormat.milli(weight))kg description=\"lest\"\n" } 284 if let temp = dive.waterTemperature { text += "watertemp \(LogFormat.milli(temp))°C\n" } 285 return text 286 } 287 288 /// "Manually added dive" computer: trapezoid profile, as Subsurface does. 289 static func computerFile(_ dive: NewDive) -> String { 290 let duration = max(dive.durationSeconds, 60) 291 let depth = max(dive.maxDepth, 0) 292 // Descent at 18 m/min, ascent at 9 m/min, each capped at a third of the dive. 293 let descent = min(Int((depth / 18 * 60).rounded()), duration / 3) 294 let ascent = min(Int((depth / 9 * 60).rounded()), duration / 3) 295 let bottom = duration - descent - ascent 296 let mean = duration > 0 ? depth * (Double(bottom) + Double(descent + ascent) / 2) / Double(duration) : 0 297 var text = "model \"manually added dive\"\n" 298 if depth > 0 { 299 text += "maxdepth \(LogFormat.milli(depth))m\n" 300 text += "meandepth \(LogFormat.milli(mean))m\n" 301 } 302 func sample(_ seconds: Int, _ meters: Double) -> String { 303 String(format: "%3d:%02d", seconds / 60, seconds % 60) + " \(LogFormat.milli(meters))m\n" 304 } 305 text += sample(0, 0) 306 if descent > 0 { text += sample(descent, depth) } 307 if bottom > 0 { text += sample(descent + bottom, depth) } 308 text += sample(duration, 0) 309 return text 310 } 311 312 static func siteFile(name: String, latitude: Double?, longitude: Double?) -> String { 313 var text = "name \(LogFormat.quote(name))\n" 314 if let latitude, let longitude { 315 text += "gps " + String(format: "%.6f %.6f", latitude, longitude) + "\n" 316 } 317 return text 318 } 319 320 /// Applies a change to the root tree (nil = empty logbook) and returns the new tree. 321 public static func apply(_ change: LogChange, root: ObjectID?, store: ObjectStore) throws -> ObjectID { 322 // A logbook always has its settings file; a brand-new account (empty repository) does not have one yet. 323 var entries = try root.map { try store.tree($0) } ?? [] 324 if !entries.contains(where: { $0.name == "00-Subsurface" }) { 325 entries.append(.blob("00-Subsurface", try store.putBlob("version 3\n"))) 326 } 327 let current = try store.putTree(entries) 328 let result: ObjectID? 329 switch change { 330 case .editDive(let when, let number, let fields): 331 guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store), 332 let file = try store.tree(directory.tree).first(where: { !$0.isTree && LogWalker.diveNumber(fileName: $0.name) != nil }) 333 else { throw ChangeError.diveNotFound(when) } 334 var typed = [DiveField: String]() 335 for (key, value) in fields { 336 if let field = DiveField(rawValue: key) { typed[field] = value } 337 } 338 let patched = patch(diveFile: try store.blob(file.id), fields: typed) 339 let blob = try store.put(GitObject(type: .blob, data: patched)) 340 result = try replacing(root: current, path: directory.path + [file.name], with: .blob(file.name, blob), store: store) 341 342 case .addDive(let dive): 343 if try LogWalker.find(when: dive.when, number: nil, root: current, store: store) != nil { 344 throw ChangeError.diveAlreadyExists(dive.when) 345 } 346 let diveBlob = try store.putBlob(diveFile(dive)) 347 let computerBlob = try store.putBlob(computerFile(dive)) 348 let name = dive.number > 0 ? "Dive-\(dive.number)" : "Dive" 349 let tree = try store.putTree([.blob(name, diveBlob), .blob("Divecomputer", computerBlob)]) 350 let path = divePath(when: dive.when) 351 result = try replacing(root: current, path: path, with: .tree(path.last!, tree), store: store) 352 353 case .ensureSettings: 354 result = current 355 356 case .locateSite(let uuid, let latitude, let longitude): 357 let fileName = "Site-" + String(format: "%08x", uuid) 358 guard let folder = try store.tree(current).first(where: { $0.isTree && $0.name == "01-Divesites" }), 359 let file = try store.tree(folder.id).first(where: { !$0.isTree && LogWalker.nonUnique($0.name) == fileName }) 360 else { throw ChangeError.diveNotFound(Int(uuid)) } 361 let data = try store.blob(file.id) 362 var lines = LogFormat.lines(data).map { (keyword: String($0.keyword), bytes: Array(data[$0.range])) } 363 if var last = lines.last, last.bytes.last != 0x0a { last.bytes.append(0x0a); lines[lines.count - 1] = last } 364 let gps = Array(("gps " + String(format: "%.6f %.6f", latitude, longitude) + "\n").utf8) 365 if let index = lines.firstIndex(where: { $0.keyword == "gps" }) { 366 lines[index].bytes = gps 367 } else { 368 // Subsurface order: name, description, notes, gps, geo. 369 let position = lines.firstIndex(where: { $0.keyword == "geo" }) ?? lines.count 370 lines.insert((keyword: "gps", bytes: gps), at: position) 371 } 372 let blob = try store.put(GitObject(type: .blob, data: lines.flatMap(\.bytes))) 373 result = try replacing(root: current, path: ["01-Divesites", file.name], with: .blob(file.name, blob), store: store) 374 375 case .removeSite(let uuid): 376 let fileName = "Site-" + String(format: "%08x", uuid) 377 guard let folder = try store.tree(current).first(where: { $0.isTree && $0.name == "01-Divesites" }), 378 let file = try store.tree(folder.id).first(where: { !$0.isTree && LogWalker.nonUnique($0.name) == fileName }) 379 else { throw ChangeError.diveNotFound(Int(uuid)) } 380 result = try replacing(root: current, path: ["01-Divesites", file.name], with: nil, store: store) 381 382 case .setEquipment(let when, let number, let cylinders, let unchanged, let weights): 383 guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store), 384 let file = try store.tree(directory.tree).first(where: { !$0.isTree && LogWalker.diveNumber(fileName: $0.name) != nil }) 385 else { throw ChangeError.diveNotFound(when) } 386 let patched = patch(diveFile: try store.blob(file.id), cylinders: cylinders, unchangedCylinders: unchanged, weights: weights) 387 let blob = try store.put(GitObject(type: .blob, data: patched)) 388 result = try replacing(root: current, path: directory.path + [file.name], with: .blob(file.name, blob), store: store) 389 390 case .renumberDive(let when, let number, let newNumber): 391 guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store), 392 let file = try store.tree(directory.tree).first(where: { !$0.isTree && LogWalker.diveNumber(fileName: $0.name) != nil }) 393 else { throw ChangeError.diveNotFound(when) } 394 let name = newNumber > 0 ? "Dive-\(newNumber)" : "Dive" 395 if name == file.name { 396 result = current 397 } else { 398 let without = try replacing(root: current, path: directory.path + [file.name], with: nil, store: store) 399 result = try replacing(root: without, path: directory.path + [name], with: .blob(name, file.id), store: store) 400 } 401 402 case .importDive(let dive, let number, let siteUUID): 403 result = try importing(dive, number: number, siteUUID: siteUUID, root: current, store: store) 404 405 case .mergeDives(let when, let number, let others): 406 result = try merging(others, into: DiveRef(when: when, number: number), root: current, store: store) 407 408 case .deleteDive(let when, let number): 409 guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store) else { 410 throw ChangeError.diveNotFound(when) 411 } 412 result = try replacing(root: current, path: directory.path, with: nil, store: store) 413 414 case .addSite(let uuid, let name, let latitude, let longitude): 415 let fileName = "Site-" + String(format: "%08x", uuid) 416 let blob = try store.putBlob(siteFile(name: name, latitude: latitude, longitude: longitude)) 417 result = try replacing(root: current, path: ["01-Divesites", fileName], with: .blob(fileName, blob), store: store) 418 } 419 return try result ?? store.putTree([]) 420 } 421 }