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 c4493d1ee11aeddcb034a999e9f40f98f624b448
parent bca2060a3d80d012c795c510e9e8e535691f8128
Author: Jean Schurger <jean@schurger.org>
Date:   Sun, 15 Nov 2026 22:50:53 -0500

Saved plans, printable plan sheet, planned dives kept out of the statistics

- Plans are saved by name in a library of their own (in the settings, hence
  in the iCloud backup): open, update, save as new, duplicate, rename, delete.
- Print or share: a PDF sheet (run time table, gases, minimum gas, profile),
  rendered from a SwiftUI view, handed to the share sheet.
- A plan saved in the logbook (computer 'planned dive') carries a Plan tag
  and counts neither in the statistics nor as an earlier dive for a plan.
- French strings, README, version 0.11.

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

Diffstat:
MApp/Localizable.xcstrings | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Model/AppModel.swift | 2+-
MApp/Views/DiveListView.swift | 8++++++++
AApp/Views/SavedPlans.swift | 342+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Views/StatsView.swift | 2+-
MApp/Views/TechPlanView.swift | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
MPackages/DiveKit/Sources/SubsurfaceLog/Model.swift | 2++
MREADME.md | 4+++-
Mfastlane/Fastfile | 4++--
Mproject.yml | 2+-
10 files changed, 681 insertions(+), 8 deletions(-)

diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage": "en", "strings": { + "%@ (copy)": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ (copie)" + } + } + } + }, "%@ at %@: as narcotic as air at %@.": { "localizations": { "fr": { @@ -91,6 +101,16 @@ } } }, + "%@ left": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ restants" + } + } + } + }, "%@ min": { "localizations": { "fr": { @@ -691,6 +711,16 @@ } } }, + "Altitude %@": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Altitude %@" + } + } + } + }, "Anemones, nudibranchs and crabs under the pilings.": { "localizations": { "fr": { @@ -1141,6 +1171,16 @@ } } }, + "Changed since it was saved": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Modifié depuis l'enregistrement" + } + } + } + }, "Changes stay on this iPhone and disappear when you leave the demo.": { "localizations": { "fr": { @@ -1901,6 +1941,16 @@ } } }, + "Dive plan": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plan de plongée" + } + } + } + }, "Dive plan made with %@ %@ (%@)": { "localizations": { "fr": { @@ -2111,6 +2161,16 @@ } } }, + "Duplicate": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Dupliquer" + } + } + } + }, "Duration": { "localizations": { "fr": { @@ -2281,6 +2341,16 @@ } } }, + "Extension": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Prolongation" + } + } + } + }, "File format not recognized. Supported formats: UDDF (.uddf), Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).": { "localizations": { "fr": { @@ -2821,6 +2891,16 @@ } } }, + "Made with %@ %@. A planning aid, not a dive computer: check this plan against another tool and dive within your training.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fait avec %@ %@. Une aide à la planification, pas un ordinateur de plongée : vérifiez ce plan avec un autre outil et plongez dans les limites de votre formation." + } + } + } + }, "Manually entered dive": { "localizations": { "fr": { @@ -2951,6 +3031,16 @@ } } }, + "Minimum gas when leaving the bottom: %@ of %@": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Gaz minimum en quittant le fond : %@ de %@" + } + } + } + }, "Minimum gas: what must be left in %@ when leaving the bottom, for %@ minutes on a problem and the ascent to the first gas switch, at %@ times the consumption.": { "localizations": { "fr": { @@ -3031,6 +3121,16 @@ } } }, + "Name": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Nom" + } + } + } + }, "Name (AL80, steel 100…)": { "localizations": { "fr": { @@ -3041,6 +3141,16 @@ } } }, + "Name of the plan": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Nom du plan" + } + } + } + }, "Narcotic depth not to pass": { "localizations": { "fr": { @@ -3291,6 +3401,16 @@ } } }, + "No saved plan": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucun plan enregistré" + } + } + } + }, "No site": { "localizations": { "fr": { @@ -3731,6 +3851,16 @@ } } }, + "Plan not saved": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plan non enregistré" + } + } + } + }, "Planning": { "localizations": { "fr": { @@ -3781,6 +3911,16 @@ } } }, + "Print or share…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Imprimer ou partager…" + } + } + } + }, "Problem at the bottom": { "localizations": { "fr": { @@ -3851,6 +3991,16 @@ } } }, + "Rename": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Renommer" + } + } + } + }, "Reserve": { "localizations": { "fr": { @@ -3901,6 +4051,16 @@ } } }, + "Run time table": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Table des temps" + } + } + } + }, "Run time: %@ min": { "localizations": { "fr": { @@ -3961,6 +4121,16 @@ } } }, + "Save as a new plan…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Enregistrer comme nouveau plan…" + } + } + } + }, "Save in the logbook…": { "localizations": { "fr": { @@ -3981,6 +4151,26 @@ } } }, + "Save the plan you are working on to find it here, with its name.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Enregistrez le plan en cours pour le retrouver ici, avec son nom." + } + } + } + }, + "Saved plans": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plans enregistrés" + } + } + } + }, "Sea": { "localizations": { "fr": { @@ -4001,6 +4191,16 @@ } } }, + "Sea water": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Eau de mer" + } + } + } + }, "Seal Cove": { "localizations": { "fr": { @@ -4961,6 +5161,16 @@ } } }, + "The saved plans are not touched.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les plans enregistrés ne sont pas touchés." + } + } + } + }, "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": { @@ -5281,6 +5491,16 @@ } } }, + "Update this plan": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Mettre à jour ce plan" + } + } + } + }, "Use": { "localizations": { "fr": { @@ -5651,6 +5871,16 @@ } } }, + "from %@": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "à partir de %@" + } + } + } + }, "high ppO2": { "localizations": { "fr": { diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift @@ -637,7 +637,7 @@ final class AppModel { /// The dives of the logbook that ended less than 48 hours before `date`, oldest first, with their profiles. func earlierDives(before date: Date) async -> [EarlierDive] { let start = DiveDate.naive(from: date) - let candidates = logbook.dives.filter { $0.when < start && $0.when + $0.durationSeconds > start - 48 * 3600 }.sorted { $0.when < $1.when } + let candidates = logbook.dives.filter { !$0.isPlanned && $0.when < start && $0.when + $0.durationSeconds > start - 48 * 3600 }.sorted { $0.when < $1.when } var found = [EarlierDive]() for (index, dive) in candidates.enumerated() { func gas(_ mix: GasMix) -> BreathingGas { BreathingGas(o2: mix.o2Fraction, he: mix.heFraction) } diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift @@ -247,6 +247,14 @@ struct DiveRow: View { Text(verbatim: "\(DiveDate.short(dive)) · \(DiveDate.time(dive))") .lineLimit(1) .fixedSize() + if dive.isPlanned { + Text("Plan") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(Color.accentColor.opacity(0.15), in: Capsule()) + .foregroundStyle(Color.accentColor) + } if !compact, dive.rating > 0 { Text(String(repeating: "★", count: dive.rating)) .foregroundStyle(.yellow) diff --git a/App/Views/SavedPlans.swift b/App/Views/SavedPlans.swift @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: GPL-2.0-only +import DivePlanner +import Observation +import SwiftUI +import UIKit + +/// A plan kept for later: its name, the plan, and the date it is meant for. +struct SavedPlan: Codable, Identifiable, Equatable { + var id = UUID() + var name: String + var plan: DivePlan + /// Seconds since 1970 of the planned start. + var date: Double + var modified = Date() +} + +/// The saved plans. They live in the app's settings, so they go to the iCloud backup with them. +@MainActor +@Observable +final class PlanLibrary { + private(set) var plans: [SavedPlan] = [] + private static let key = "savedPlans" + + init() { + guard let data = UserDefaults.standard.data(forKey: Self.key) else { return } + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + plans = (try? decoder.decode([SavedPlan].self, from: data)) ?? [] + } + + private func persist() { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + if let data = try? encoder.encode(plans) { UserDefaults.standard.set(data, forKey: Self.key) } + } + + func plan(id: String) -> SavedPlan? { plans.first { $0.id.uuidString == id } } + + /// Adds the plan, or replaces the one with the same identifier. + func save(_ plan: SavedPlan) { + var saved = plan + saved.modified = Date() + if let index = plans.firstIndex(where: { $0.id == saved.id }) { plans[index] = saved } else { plans.append(saved) } + persist() + } + + func delete(_ plan: SavedPlan) { + plans.removeAll { $0.id == plan.id } + persist() + } + + @discardableResult + func duplicate(_ plan: SavedPlan) -> SavedPlan { + var copy = plan + copy.id = UUID() + copy.name = String(localized: "\(plan.name) (copy)") + save(copy) + return copy + } + + func rename(_ plan: SavedPlan, to name: String) { + guard var changed = plans.first(where: { $0.id == plan.id }) else { return } + changed.name = name + save(changed) + } +} + +extension DivePlan { + /// A name made of what tells plans apart: deepest level, its time, the gases. + func suggestedName(units: Units) -> String { + guard let deepest = levels.max(by: { $0.depth < $1.depth }) else { return String(localized: "Plan") } + let gases = cylinders.map(\.gas.name).joined(separator: ", ") + return "\(units.depth(deepest.depth)) · \(Int(levels.reduce(0) { $0 + $1.minutes }.rounded())) min · \(gases)" + } +} + +/// The list of saved plans: open one, duplicate it, rename it, delete it. +struct SavedPlansView: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + let library: PlanLibrary + let currentID: String + let onOpen: (SavedPlan) -> Void + @State private var renaming: SavedPlan? + @State private var newName = "" + + var body: some View { + List { + if library.plans.isEmpty { + ContentUnavailableView("No saved plan", systemImage: "tray", + description: Text("Save the plan you are working on to find it here, with its name.")) + } + ForEach(library.plans.sorted { $0.modified > $1.modified }) { saved in + Button { + onOpen(saved) + dismiss() + } label: { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(saved.name).font(.body.weight(.medium)).foregroundStyle(Color.primary) + Text(saved.plan.suggestedName(units: model.units)) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 8) + if saved.id.uuidString == currentID { + Image(systemName: "checkmark").foregroundStyle(Color.accentColor) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .swipeActions { + Button("Delete", role: .destructive) { library.delete(saved) } + Button("Duplicate") { library.duplicate(saved) } + Button("Rename") { + newName = saved.name + renaming = saved + } + .tint(.orange) + } + } + } + .listStyle(.insetGrouped) + .navigationTitle("Saved plans") + .navigationBarTitleDisplayMode(.inline) + .alert("Name of the plan", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) { + TextField("Name", text: $newName) + Button("Rename") { + if let renaming, !newName.trimmingCharacters(in: .whitespaces).isEmpty { library.rename(renaming, to: newName.trimmingCharacters(in: .whitespaces)) } + renaming = nil + } + Button("Cancel", role: .cancel) { renaming = nil } + } + } +} + +// MARK: Printing + +/// The plan on paper: what goes on the slate first (run time table, gases), then the rest. Always black on white. +struct PlanSheet: View { + let name: String + let date: Date + let plan: DivePlan + let result: PlanResult + let units: Units + + private func gasName(_ index: Int) -> String { plan.cylinders.indices.contains(index) ? plan.cylinders[index].gas.name : "?" } + private func minutes(_ seconds: Double) -> String { String(Int((seconds / 60).rounded())) } + + private var modelLine: String { + let settings = plan.settings + var parts = [String]() + switch settings.model { + case .buhlmann: parts.append("Bühlmann ZHL-16C GF \(Int((settings.gfLow * 100).rounded()))/\(Int((settings.gfHigh * 100).rounded()))") + case .vpmb: parts.append("VPM-B +\(settings.vpmbConservatism)") + case .recreational: parts.append(String(localized: "Recreational") + " GF \(Int((settings.gfLow * 100).rounded()))/\(Int((settings.gfHigh * 100).rounded()))") + } + switch plan.mode { + case .openCircuit: parts.append(String(localized: "Open circuit")) + case .closedCircuit: parts.append(String(localized: "Closed circuit, setpoint \(fixed(plan.setpoint, 2)) bar") + (plan.bailout ? String(localized: ", open-circuit bailout") : "")) + case .semiClosed: parts.append(String(localized: "Semi-closed circuit") + (plan.bailout ? String(localized: ", open-circuit bailout") : "")) + } + parts.append(settings.environment.waterDensity < 1.015 ? String(localized: "Fresh water") : String(localized: "Sea water")) + if settings.environment.altitude > 50 { parts.append(String(localized: "Altitude \(units.depth(settings.environment.altitude))")) } + return parts.joined(separator: " · ") + } + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 3) { + Text(name).font(.system(size: 20, weight: .bold)) + Text(date.formatted(date: .long, time: .shortened)).font(.system(size: 11)).foregroundStyle(.gray) + Text(modelLine).font(.system(size: 11)).foregroundStyle(.gray) + } + + HStack(spacing: 18) { + figure(String(localized: "Run time"), "\(minutes(result.runtime)) min") + figure(String(localized: "Maximum depth"), units.depth(result.maxDepth)) + figure(String(localized: "Ascent and stops"), "\(minutes(result.ascentTime)) min") + figure("CNS", fixed(result.cns * 100, 0) + " %") + figure("OTU", fixed(result.otu, 0)) + } + + section(String(localized: "Run time table")) + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 5) { + GridRow { + Text("Depth") + Text("Time").gridColumnAlignment(.trailing) + Text("Run time").gridColumnAlignment(.trailing) + Text("Gas") + Text(verbatim: "") + } + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.gray) + ForEach(Array(rows.enumerated()), id: \.offset) { _, row in + GridRow { + Text(row.depth).fontWeight(.semibold) + Text(row.time) + Text(row.runtime).fontWeight(.semibold) + Text(row.gas) + Text(row.note).foregroundStyle(.gray) + } + .font(.system(size: 13).monospacedDigit()) + } + } + + section(String(localized: "Gas")) + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 5) { + ForEach(Array(plan.cylinders.enumerated()), id: \.offset) { index, cylinder in + let used = result.gasUsed.indices.contains(index) ? result.gasUsed[index] : 0 + GridRow { + Text(cylinder.gas.name).fontWeight(.semibold) + Text(cylinder.isDeco + ? String(localized: "from \(units.depth(DivePlanner.switchDepth(of: cylinder, settings: plan.settings)))") + : (plan.mode == .closedCircuit ? String(localized: "Diluent") : String(localized: "Bottom gas"))) + Text([cylinder.volumeLiters.map { units.volume($0) }, cylinder.startBar.map { units.pressure($0) }].compactMap { $0 }.joined(separator: " · ")) + Text(fixed(used, 0) + " L").gridColumnAlignment(.trailing) + Text(cylinder.pressure(afterUsing: used).map { String(localized: "\(units.pressure(max(0, $0))) left") } ?? "") + } + .font(.system(size: 12).monospacedDigit()) + } + } + if let minimum = result.minimumGasLiters, plan.cylinders.indices.contains(result.bottomCylinder) { + let cylinder = plan.cylinders[result.bottomCylinder] + let amount = cylinder.volumeLiters.map { units.pressure(RealGas.pressure(cylinder.gas, liters: minimum, volumeLiters: max($0, 0.1))) } ?? fixed(minimum, 0) + " L" + Text("Minimum gas when leaving the bottom: \(amount) of \(cylinder.gas.name)") + .font(.system(size: 12, weight: .semibold)) + } + + if result.points.count > 1 { + section(String(localized: "Profile")) + PlanChart(result: result, plan: plan, units: units) + .frame(height: 170) + } + + Text("Made with \(Brand.name) \(Brand.shortVersion). A planning aid, not a dive computer: check this plan against another tool and dive within your training.") + .font(.system(size: 9)) + .foregroundStyle(.gray) + .padding(.top, 4) + } + .padding(0) + .frame(width: Self.width, alignment: .leading) + .foregroundStyle(.black) + .background(Color.white) + .environment(\.colorScheme, .light) + .dynamicTypeSize(.medium) + } + + static let width: CGFloat = 540 + + private struct Row { + var depth: String, time: String, runtime: String, gas: String, note: String + } + + /// The dive from top to bottom: each level, then each stop, then the surface. + private var rows: [Row] { + var out = [Row]() + var clock = 0.0 + for level in plan.levels { + clock += level.minutes * 60 + out.append(Row(depth: units.depth(level.depth), time: "\(Int(level.minutes.rounded())) min", runtime: minutes(clock), + gas: gasName(level.cylinder), note: "")) + } + if result.bottomExtensionMinutes > 0, let last = plan.levels.last { + clock += result.bottomExtensionMinutes * 60 + out.append(Row(depth: units.depth(last.depth), time: "+\(Int(result.bottomExtensionMinutes.rounded())) min", runtime: minutes(clock), + gas: gasName(last.cylinder), note: String(localized: "Extension"))) + } + for stop in result.stops.sorted(by: { $0.endTime < $1.endTime }) { + let note: String + switch stop.kind { + case .deco: note = "" + case .gasSwitch: note = String(localized: "Gas switch") + case .safety: note = String(localized: "Safety stop") + } + out.append(Row(depth: units.depth(stop.depth), time: "\(minutes(stop.seconds)) min", runtime: minutes(stop.endTime), + gas: gasName(stop.cylinder), note: note)) + } + out.append(Row(depth: String(localized: "Surface"), time: "", runtime: minutes(result.runtime), gas: "", note: "")) + return out + } + + private func figure(_ title: String, _ value: String) -> some View { + VStack(alignment: .leading, spacing: 1) { + Text(title).font(.system(size: 9)).foregroundStyle(.gray) + Text(value).font(.system(size: 15, weight: .semibold).monospacedDigit()) + } + } + + private func section(_ title: String) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(title.uppercased()).font(.system(size: 10, weight: .semibold)).foregroundStyle(.gray) + Rectangle().fill(Color.gray.opacity(0.4)).frame(height: 0.5) + } + } + + /// The sheet as a PDF file (US Letter pages), ready for the share sheet and for printing. + @MainActor + func pdf(named fileName: String, at destination: URL? = nil) -> URL? { + let safe = fileName.map { $0.isLetter || $0.isNumber || $0 == " " || $0 == "-" ? $0 : "-" } + let url = destination ?? FileManager.default.temporaryDirectory.appendingPathComponent(String(safe).prefix(60) + ".pdf") + let renderer = ImageRenderer(content: self) + var written = false + renderer.render { size, draw in + let page = CGSize(width: 612, height: 792), margin: CGFloat = 36 + let usable = page.height - 2 * margin + var box = CGRect(origin: .zero, size: page) + guard let context = CGContext(url as CFURL, mediaBox: &box, nil) else { return } + let pages = max(1, Int((size.height / usable).rounded(.up))) + for index in 0..<pages { + context.beginPDFPage(nil) + context.saveGState() + // The page shows a slice of the sheet: the origin of a PDF page is at its bottom left. + context.clip(to: CGRect(x: margin, y: margin, width: page.width - 2 * margin, height: usable)) + context.translateBy(x: margin, y: page.height - margin - size.height + CGFloat(index) * usable) + draw(context) + context.restoreGState() + context.endPDFPage() + } + context.closePDF() + written = true + } + return written ? url : nil + } +} + +/// The system share sheet (Print, Files, Messages…). +struct ActivityView: UIViewControllerRepresentable { + let items: [Any] + + func makeUIViewController(context: Context) -> UIActivityViewController { + UIActivityViewController(activityItems: items, applicationActivities: nil) + } + + func updateUIViewController(_ controller: UIActivityViewController, context: Context) {} +} + +struct SharedFile: Identifiable { + let url: URL + var id: String { url.path } +} diff --git a/App/Views/StatsView.swift b/App/Views/StatsView.swift @@ -72,7 +72,7 @@ struct StatsView: View { var body: some View { NavigationStack { - let dives = model.logbook.dives.filter { !$0.invalid } + let dives = model.logbook.dives.filter { !$0.invalid && !$0.isPlanned } let units = model.units ScrollViewReader { proxy in List { diff --git a/App/Views/TechPlanView.swift b/App/Views/TechPlanView.swift @@ -16,6 +16,12 @@ struct TechPlanView: View { @State private var earlier: [AppModel.EarlierDive] = [] @AppStorage("planShowVariations") private var showVariations = false @State private var saving = LaunchOptions.flag("-savePlan") + @State private var library = PlanLibrary() + @AppStorage("planCurrentID") private var currentID = "" + @State private var naming = false + @State private var choosingSave = false + @State private var newName = "" + @State private var shared: SharedFile? private static let storageKey = "divePlan2" @@ -37,6 +43,36 @@ struct TechPlanView: View { ScrollViewReader { proxy in Form { Section { + NavigationLink { + SavedPlansView(library: library, currentID: currentID) { saved in + plan = saved.plan + planDate = saved.date + currentID = saved.id.uuidString + } + } label: { + HStack { + Label("Saved plans", systemImage: "tray.full") + Spacer() + Text("\(library.plans.count)").foregroundStyle(.secondary) + } + } + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(current?.name ?? String(localized: "Plan not saved")) + if let current, current.plan != plan || current.date != planDate { + Text("Changed since it was saved").font(.caption).foregroundStyle(.orange) + } + } + Spacer() + Button("Save") { + if current != nil { choosingSave = true } else { askName() } + } + .buttonStyle(.bordered) + .disabled(current.map { $0.plan == plan && $0.date == planDate } ?? false) + } + } + + Section { Picker("Circuit", selection: $plan.mode) { Text("Open circuit").tag(BreathingMode.openCircuit) Text("Closed circuit (CCR)").tag(BreathingMode.closedCircuit) @@ -164,6 +200,8 @@ struct TechPlanView: View { Section { Toggle("Show how the plan varies", isOn: $showVariations) + Button { share() } label: { Label("Print or share…", systemImage: "printer") } + .disabled(result.points.count < 2) Button { saving = true } label: { Label("Save in the logbook…", systemImage: "square.and.arrow.down") } .disabled(result.points.count < 2 || model.isDemo) Button("Start a new plan", role: .destructive) { confirmingReset = true } @@ -181,8 +219,35 @@ struct TechPlanView: View { } } .confirmationDialog("Start a new plan?", isPresented: $confirmingReset, titleVisibility: .visible) { - Button("Start over", role: .destructive) { plan = Self.starter } + Button("Start over", role: .destructive) { + plan = Self.starter + currentID = "" + } + } message: { + Text("The saved plans are not touched.") + } + .confirmationDialog(current?.name ?? "", isPresented: $choosingSave, titleVisibility: .visible) { + Button("Update this plan") { + if var saved = current { + saved.plan = plan + saved.date = planDate + library.save(saved) + } + } + Button("Save as a new plan…") { askName() } + Button("Cancel", role: .cancel) {} } + .alert("Name of the plan", isPresented: $naming) { + TextField("Name", text: $newName) + Button("Save") { + let name = newName.trimmingCharacters(in: .whitespaces) + let saved = SavedPlan(name: name.isEmpty ? plan.suggestedName(units: model.units) : name, plan: plan, date: planDate) + library.save(saved) + currentID = saved.id.uuidString + } + Button("Cancel", role: .cancel) {} + } + .sheet(item: $shared) { ActivityView(items: [$0.url]) } .task(id: PlanInputs(plan: plan, date: planDate, earlier: countEarlierDives, imperial: model.units.imperial, dives: model.logbook.dives.count)) { if let data = try? JSONEncoder().encode(plan) { UserDefaults.standard.set(data, forKey: Self.storageKey) } var current = plan @@ -192,6 +257,14 @@ struct TechPlanView: View { let computed = await Task.detached(priority: .userInitiated) { DivePlanner.plan(current, after: prior) }.value guard !Task.isCancelled else { return } result = computed + // Test option: write the printable sheet to a file, to look at it without the share sheet. + if let path = LaunchOptions.value("-planPDF") { _ = sheet.pdf(named: "plan", at: URL(fileURLWithPath: path)) } + // Test option: save the plan under a name, as the Save button and its name prompt would. + if let name = LaunchOptions.value("-savePlanAs"), library.plans.allSatisfy({ $0.name != name }) { + let saved = SavedPlan(name: name, plan: plan, date: planDate) + library.save(saved) + currentID = saved.id.uuidString + } variations = nil if showVariations { let around = await Task.detached(priority: .utility) { DivePlanner.variations(of: current) }.value @@ -349,6 +422,22 @@ struct TechPlanView: View { } } + private var current: SavedPlan? { library.plan(id: currentID) } + + private func askName() { + newName = plan.suggestedName(units: model.units) + naming = true + } + + private var sheet: PlanSheet { + PlanSheet(name: current?.name ?? plan.suggestedName(units: model.units), date: Date(timeIntervalSince1970: planDate), + plan: plan, result: result, units: model.units) + } + + private func share() { + if let url = sheet.pdf(named: current?.name ?? String(localized: "Dive plan")) { shared = SharedFile(url: url) } + } + /// "+2 min 30 s", "−40 s". private func signed(_ seconds: Double) -> String { let whole = Int(seconds.rounded()) @@ -404,7 +493,7 @@ private struct PlanInputs: Equatable { } /// The planned profile, with the gas switches. -private struct PlanChart: View { +struct PlanChart: View { let result: PlanResult let plan: DivePlan let units: Units diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Model.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Model.swift @@ -179,6 +179,8 @@ public struct Dive: Sendable, Equatable, Identifiable { public var totalWeight: Double { weights.reduce(0) { $0 + $1.kilograms } } public var computerModel: String? { computers.first(where: { !$0.model.isEmpty && !$0.isManual })?.model } public var isManual: Bool { computers.allSatisfy { $0.isManual } } + /// A plan saved in the logbook (Subsurface's "planned dive" computer), not a dive that was made. + public var isPlanned: Bool { !computers.isEmpty && computers.allSatisfy { $0.model == "planned dive" } } /// From the earliest start to the latest end of what the dive and its computers recorded. public var timeRange: ClosedRange<Int> { diff --git a/README.md b/README.md @@ -60,7 +60,9 @@ The app is available in English and French. - no-stop: how long at a depth on a gas with a cylinder (no-stop time, gas time, table of no-stop times); - decompression: levels, cylinders with nitrox, trimix and decompression gases, Bühlmann with gradient factors or VPM-B, open circuit or rebreather (CCR, pSCR, bailout), stops, run time, gas per cylinder, - minimum gas, CNS and OTU, warnings, profile, plan variations, and saving the plan as a logbook dive; + minimum gas, CNS and OTU, warnings, profile, plan variations; plans are saved by name in a library of + their own (kept in the settings, hence in the iCloud backup), printed or shared as a PDF sheet, and can + also be saved as a logbook dive, which then carries a "Plan" tag and stays out of the statistics; - gas: maximum operating depth, equivalent narcotic and air depths, density, best mix, consumption. - Creation of a Subsurface cloud account (email, password, code received by email). - Demo logbook (a button on the sign-in screen, or the `-demo` launch option). diff --git a/fastlane/Fastfile b/fastlane/Fastfile @@ -76,9 +76,9 @@ platform :ios do end texts = { "fr-CA" => ["Votre carnet de plongée sur iPhone : profils, modification hors ligne, ordinateur de plongée en Bluetooth, synchronisation facultative avec le nuage Subsurface, sauvegarde iCloud. Application indépendante de l'équipe de Subsurface.", - "0.10 : Nouveau : (1) Import et export UDDF, le format d'échange des carnets de plongée : Réglages, Importer un fichier (.uddf) ou Exporter en UDDF ; une plongée seule s'exporte depuis son menu. (2) Planification, ce qui manquait par rapport à Subsurface : mode loisir (temps de fond prolongé jusqu'à la limite sans palier ou jusqu'au gaz), plongées précédentes du carnet prises en compte (date du plan), autre point de consigne pour la remontée en circuit fermé, eau EN 13319, temps en surface, paliers tous les 10 pieds en unités impériales."], + "0.11 : Nouveau dans Planification, Décompression : (1) Plans enregistrés : donner un nom à un plan, le rouvrir, le dupliquer, le renommer ; ils partent dans la sauvegarde iCloud. (2) Imprimer ou partager : une page PDF avec la table des temps, les gaz, le gaz minimum et le profil, par la feuille de partage (AirPrint, Fichiers...). (3) Les plans enregistrés dans le carnet portent une étiquette Plan et ne comptent plus dans les statistiques ni dans les plongées précédentes. Corrigé : le remplissage du profil du plan."], "en-CA" => ["Your dive log on iPhone: profiles, offline editing, dive computer over Bluetooth, optional sync with Subsurface cloud storage, iCloud backup. Independent from the Subsurface team.", - "0.10: New: (1) UDDF import and export, the exchange format of dive logs: Settings, Import a file (.uddf) or Export as UDDF; a single dive exports from its menu. (2) Planning, what was missing compared with Subsurface: recreational mode (bottom time extended to the no-stop limit or to the gas), earlier dives of the logbook taken into account (date of the plan), another setpoint for a closed-circuit ascent, EN 13319 water, time at the surface, stops every 10 ft in imperial units."], + "0.11: New in Planning, Decompression: (1) Saved plans: name a plan, reopen it, duplicate it, rename it; they go to the iCloud backup. (2) Print or share: a PDF page with the run time table, the gases, the minimum gas and the profile, through the share sheet (AirPrint, Files...). (3) Plans saved in the logbook carry a Plan tag and no longer count in the statistics or as earlier dives. Fixed: the fill of the plan profile."], } _, 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.10" + MARKETING_VERSION: "0.11" CURRENT_PROJECT_VERSION: "1" SWIFT_VERSION: "5.0" targets: