commit af44ed33db0c88e07b8f8b30dec422eb15996c58
parent c9fe763c24c950d8021c0f6cae73dfa03263c93a
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 09:14:50 -0500
English code, comments and docs; English source language with French localization; GPL-2.0 license
All comments, library messages, CLI output and the README are now in
English. The app uses English as its source language and keeps French
as a translation (App/Localizable.xcstrings, App/InfoPlist.xcstrings).
Every Swift file carries an SPDX identifier and LICENSE holds the GPL
version 2 text.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
48 files changed, 4496 insertions(+), 877 deletions(-)
diff --git a/App/Brand.swift b/App/Brand.swift
@@ -1,6 +1,7 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
-/// Nom et adresses de l'app, réunis ici pour qu'un changement de nom ne touche que ce fichier et project.yml.
+/// App name and identifiers, gathered here so that renaming the app only touches this file and project.yml.
enum Brand {
static let name = "Sub Rascasse"
static var version: String {
diff --git a/App/DiveLogApp.swift b/App/DiveLogApp.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SwiftUI
@main
@@ -13,7 +14,7 @@ struct DiveLogApp: App {
await model.start()
await model.importFromOpenRemora()
}
- // Open Rémora ouvre « subrascasse://open-remora » après avoir déposé une plongée.
+ // Open Rémora opens "subrascasse://open-remora" after dropping a dive.
.onOpenURL { _ in Task { await model.importFromOpenRemora() } }
.onChange(of: scenePhase) {
if scenePhase == .active { Task { await model.importFromOpenRemora() } }
diff --git a/App/InfoPlist.xcstrings b/App/InfoPlist.xcstrings
@@ -0,0 +1,13 @@
+{
+ "sourceLanguage" : "en",
+ "strings" : {
+ "NSPhotoLibraryUsageDescription" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse flags the dives you have photos or videos of and shows them on the dive page. They stay on your iPhone; nothing is sent." } },
+ "fr" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse signale les plongées dont vous avez des photos ou des vidéos et les montre sur leur fiche. Elles restent sur l'iPhone, rien n'est envoyé." } }
+ }
+ }
+ },
+ "version" : "1.0"
+}
diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings
@@ -0,0 +1,3036 @@
+{
+ "sourceLanguage": "en",
+ "strings": {
+ "%@ into the dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "à %@ de plongée"
+ }
+ }
+ }
+ },
+ "%@ min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ min"
+ }
+ }
+ }
+ },
+ "%@ reads and edits the logbook that Subsurface keeps in its cloud, in the same format. It is an independent app, not affiliated with the Subsurface team. It replaces neither a dive computer nor proper training.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ lit et modifie le carnet que Subsurface garde dans son nuage, dans le même format. C'est une application indépendante, sans lien avec l'équipe de Subsurface. Elle ne remplace ni un ordinateur de plongée ni une formation."
+ }
+ }
+ }
+ },
+ "%@ · already in the logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@ · déjà dans le carnet"
+ }
+ }
+ }
+ },
+ "%@, %lld underwater (marked with a wave)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%@, dont %lld sous l'eau (marquées d'une vague)"
+ }
+ }
+ }
+ },
+ "%lld": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld"
+ }
+ }
+ }
+ },
+ "%lld %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld %@"
+ }
+ }
+ }
+ },
+ "%lld Open Rémora dives added to the logbook.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld plongées d'Open Rémora ajoutées au carnet."
+ }
+ }
+ }
+ },
+ "%lld changes to upload": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld modifications à envoyer"
+ }
+ }
+ }
+ },
+ "%lld dives": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld plongées"
+ }
+ }
+ }
+ },
+ "%lld dives selected": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld plongées choisies"
+ }
+ }
+ }
+ },
+ "%lld min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld min"
+ }
+ }
+ }
+ },
+ "%lld of %lld": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld sur %lld"
+ }
+ }
+ }
+ },
+ "%lld of 5": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld sur 5"
+ }
+ }
+ }
+ },
+ "%lld photos and videos": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld photos et vidéos"
+ }
+ }
+ }
+ },
+ "%lld%%": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%lld %%"
+ }
+ }
+ }
+ },
+ "%lld–%lld %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "%1$lld à %2$lld %3$@"
+ }
+ }
+ }
+ },
+ "0": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "0"
+ }
+ }
+ }
+ },
+ "1 Open Rémora dive added to the logbook.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "1 plongée d'Open Rémora ajoutée au carnet."
+ }
+ }
+ }
+ },
+ "1 change to upload": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "1 modification à envoyer"
+ }
+ }
+ }
+ },
+ "1 dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "1 plongée"
+ }
+ }
+ }
+ },
+ "1 dive selected": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "1 plongée choisie"
+ }
+ }
+ }
+ },
+ "1 photo or video": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "1 photo ou vidéo"
+ }
+ }
+ }
+ },
+ "12 L steel": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "12 L acier"
+ }
+ }
+ }
+ },
+ "15–30 min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "15 à 30 min"
+ }
+ }
+ }
+ },
+ "3 mm shorty": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Combinaison courte 3 mm"
+ }
+ }
+ }
+ },
+ "30–45 min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "30 à 45 min"
+ }
+ }
+ }
+ },
+ "45–60 min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "45 à 60 min"
+ }
+ }
+ }
+ },
+ "60–75 min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "60 à 75 min"
+ }
+ }
+ }
+ },
+ "75 min or more": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "75 min et plus"
+ }
+ }
+ }
+ },
+ "99+ min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "99+ min"
+ }
+ }
+ }
+ },
+ "A dive already exists at this date and time.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Une plongée existe déjà à cette date et heure."
+ }
+ }
+ }
+ },
+ "A week of shore diving": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Une semaine de plongées du bord"
+ }
+ }
+ }
+ },
+ "About": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "À propos"
+ }
+ }
+ }
+ },
+ "Account": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Compte"
+ }
+ }
+ }
+ },
+ "Action failed": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Action impossible"
+ }
+ }
+ }
+ },
+ "Add": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ajouter"
+ }
+ }
+ }
+ },
+ "Add a dive with the + button, or pull to sync.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ajoutez une plongée avec le bouton +, ou tirez pour synchroniser."
+ }
+ }
+ }
+ },
+ "Air": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Air"
+ }
+ }
+ }
+ },
+ "Alarms: ": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Alarmes : "
+ }
+ }
+ }
+ },
+ "Allow photo access": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Autoriser l'accès aux photos"
+ }
+ }
+ }
+ },
+ "Anemones, nudibranchs and crabs under the pilings.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Anémones, nudibranches et crabes sous les piliers."
+ }
+ }
+ }
+ },
+ "Around the wreck, starting at the bow.\nGreen moray in the forward hold.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Tour de l'épave par la proue.\nMurène verte dans la cale avant."
+ }
+ }
+ }
+ },
+ "Average SAC": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conso. moyenne"
+ }
+ }
+ }
+ },
+ "Average depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur moyenne"
+ }
+ }
+ }
+ },
+ "Average duration": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Durée moyenne"
+ }
+ }
+ }
+ },
+ "Avg depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prof. moy."
+ }
+ }
+ }
+ },
+ "Buddies": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Binômes"
+ }
+ }
+ }
+ },
+ "Buddy": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Binôme"
+ }
+ }
+ }
+ },
+ "CNS": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "CNS"
+ }
+ }
+ }
+ },
+ "Cancel": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Annuler"
+ }
+ }
+ }
+ },
+ "Ceiling": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plafond"
+ }
+ }
+ }
+ },
+ "Change dropped: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modification abandonnée : %@"
+ }
+ }
+ }
+ },
+ "Changes stay on this iPhone and disappear when you leave the demo.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Les modifications restent sur cet iPhone et disparaissent en quittant la démonstration."
+ }
+ }
+ }
+ },
+ "Close": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Fermer"
+ }
+ }
+ }
+ },
+ "Code received by email": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Code reçu par courriel"
+ }
+ }
+ }
+ },
+ "Coldest water": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Eau la plus froide"
+ }
+ }
+ }
+ },
+ "Computer": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur"
+ }
+ }
+ }
+ },
+ "Computer %lld": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur %lld"
+ }
+ }
+ }
+ },
+ "Conditions": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conditions"
+ }
+ }
+ }
+ },
+ "Cormorant Wreck": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Épave du Cormoran"
+ }
+ }
+ }
+ },
+ "Couldn't connect: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connexion impossible : %@"
+ }
+ }
+ }
+ },
+ "Couldn't read the Open Rémora dive (%@): %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée d'Open Rémora illisible (%1$@) : %2$@"
+ }
+ }
+ }
+ },
+ "Couldn't read the file: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Fichier illisible : %@"
+ }
+ }
+ }
+ },
+ "Couldn't read this file.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossible de lire ce fichier."
+ }
+ }
+ }
+ },
+ "Couldn't sync (%@).": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Synchronisation impossible (%@)."
+ }
+ }
+ }
+ },
+ "Country": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pays"
+ }
+ }
+ }
+ },
+ "Create": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Créer"
+ }
+ }
+ }
+ },
+ "Create account": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Créer le compte"
+ }
+ }
+ }
+ },
+ "Create an account": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Créer un compte"
+ }
+ }
+ }
+ },
+ "Current": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Courant"
+ }
+ }
+ }
+ },
+ "Cyl. %lld": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bout. %lld"
+ }
+ }
+ }
+ },
+ "Cylinder": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Bouteille"
+ }
+ }
+ }
+ },
+ "Cylinder pressure": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pression des bouteilles"
+ }
+ }
+ }
+ },
+ "Deco model": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modèle de décompression"
+ }
+ }
+ }
+ },
+ "Deepest": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plus profonde"
+ }
+ }
+ }
+ },
+ "Delete": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Supprimer"
+ }
+ }
+ }
+ },
+ "Delete dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Supprimer la plongée"
+ }
+ }
+ }
+ },
+ "Delete this dive from the logbook?": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Supprimer cette plongée du carnet ?"
+ }
+ }
+ }
+ },
+ "Demo computer": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ordinateur de démonstration"
+ }
+ }
+ }
+ },
+ "Demo logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carnet de démonstration"
+ }
+ }
+ }
+ },
+ "Demo logbook: nothing is uploaded.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carnet de démonstration : rien n'est envoyé."
+ }
+ }
+ }
+ },
+ "Depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur"
+ }
+ }
+ }
+ },
+ "Deselect all": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Tout décocher"
+ }
+ }
+ }
+ },
+ "Details (%lld)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Détails (%lld)"
+ }
+ }
+ }
+ },
+ "Display": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Affichage"
+ }
+ }
+ }
+ },
+ "Dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée"
+ }
+ }
+ }
+ },
+ "Dive %@ added": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %@ ajoutée"
+ }
+ }
+ }
+ },
+ "Dive %@ deleted": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %@ supprimée"
+ }
+ }
+ }
+ },
+ "Dive %@ edited (%@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %1$@ modifiée (%2$@)"
+ }
+ }
+ }
+ },
+ "Dive %@ imported (%@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %1$@ importée (%2$@)"
+ }
+ }
+ }
+ },
+ "Dive %@ renumbered to %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %1$@ renumérotée %2$@"
+ }
+ }
+ }
+ },
+ "Dive %lld": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée %lld"
+ }
+ }
+ }
+ },
+ "Dive not found": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée introuvable"
+ }
+ }
+ }
+ },
+ "Dive profile": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profil de la plongée"
+ }
+ }
+ }
+ },
+ "Dive sites located in Subsurface will appear here.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Les lieux de plongée situés dans Subsurface apparaîtront ici."
+ }
+ }
+ }
+ },
+ "Dive under the wharf, lots of sessile life": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée sous le quai, beaucoup de vie fixée"
+ }
+ }
+ }
+ },
+ "Dives": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongées"
+ }
+ }
+ }
+ },
+ "Dives per month": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongées par mois"
+ }
+ }
+ }
+ },
+ "Dives per year": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongées par année"
+ }
+ }
+ }
+ },
+ "Down the wall to the barrel sponges.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Descente le long du tombant jusqu'aux éponges tonneaux."
+ }
+ }
+ }
+ },
+ "Downloading the logbook…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Téléchargement du carnet…"
+ }
+ }
+ }
+ },
+ "Drag your finger across the profile to read the values.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Glissez le doigt sur le profil pour lire les valeurs."
+ }
+ }
+ }
+ },
+ "Duration": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Durée"
+ }
+ }
+ }
+ },
+ "Edit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modifier"
+ }
+ }
+ }
+ },
+ "Edited by the test": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modifié par l'essai"
+ }
+ }
+ }
+ },
+ "Email": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Courriel"
+ }
+ }
+ }
+ },
+ "Empty logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carnet vide"
+ }
+ }
+ }
+ },
+ "Enter your email and password.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Entrez votre courriel et votre mot de passe."
+ }
+ }
+ }
+ },
+ "Equipment": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Équipement"
+ }
+ }
+ }
+ },
+ "Events (%lld)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Événements (%lld)"
+ }
+ }
+ }
+ },
+ "File format not recognized. Supported formats: Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Format de fichier non reconnu. Formats acceptés : export Shearwater Cloud (.zip ou dive_data.db) et base de Dive Shearwater (watermelon.db)."
+ }
+ }
+ }
+ },
+ "First dive of the season, weighting needs adjusting.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Première plongée de la saison, lestage à revoir."
+ }
+ }
+ }
+ },
+ "Flooded quarry, platforms at 6 m and 12 m": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carrière inondée, plateformes à 6 m et 12 m"
+ }
+ }
+ }
+ },
+ "Forgot password?": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mot de passe oublié ?"
+ }
+ }
+ }
+ },
+ "Fringing reef, shore entry": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Récif frangeant, entrée du bord"
+ }
+ }
+ }
+ },
+ "Gas": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Gaz"
+ }
+ }
+ }
+ },
+ "Gas: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Gaz : %@"
+ }
+ }
+ }
+ },
+ "Gaspé Peninsula": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Gaspésie"
+ }
+ }
+ }
+ },
+ "Gently sloping wall down to 35 m": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Tombant en pente douce jusqu'à 35 m"
+ }
+ }
+ }
+ },
+ "Guide": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Guide"
+ }
+ }
+ }
+ },
+ "Has photos": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avec photos"
+ }
+ }
+ }
+ },
+ "Hunting octopuses and tarpon in the beams of our lights.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Poulpes en chasse et tarpons dans le faisceau des lampes."
+ }
+ }
+ }
+ },
+ "Imperial (ft, °F, psi)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impériales (ft, °F, psi)"
+ }
+ }
+ }
+ },
+ "Import": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Importer"
+ }
+ }
+ }
+ },
+ "Import a file…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Importer un fichier…"
+ }
+ }
+ }
+ },
+ "Import failed": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Import impossible"
+ }
+ }
+ }
+ },
+ "It was deleted or renumbered from another device.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Elle a été supprimée ou renumérotée depuis un autre appareil."
+ }
+ }
+ }
+ },
+ "Kelp forest, a wolffish in a crevice.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Forêt de laminaires, loup de mer dans une faille."
+ }
+ }
+ }
+ },
+ "Last sync": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Dernière synchronisation"
+ }
+ }
+ }
+ },
+ "Leave": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Quitter"
+ }
+ }
+ }
+ },
+ "Leave the demo": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Quitter la démonstration"
+ }
+ }
+ }
+ },
+ "Leave the demo?": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Quitter la démonstration ?"
+ }
+ }
+ }
+ },
+ "List": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Liste"
+ }
+ }
+ }
+ },
+ "Logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carnet"
+ }
+ }
+ }
+ },
+ "Logbook settings": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Réglages du carnet"
+ }
+ }
+ }
+ },
+ "Long photo dive in 10 m of water.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Longue plongée photo dans 10 m d'eau."
+ }
+ }
+ }
+ },
+ "Long weekend in cold water": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Fin de semaine prolongée en eau froide"
+ }
+ }
+ }
+ },
+ "Longest": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plus longue"
+ }
+ }
+ }
+ },
+ "Manually entered dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée saisie à la main"
+ }
+ }
+ }
+ },
+ "Map": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carte"
+ }
+ }
+ }
+ },
+ "Max depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prof. max"
+ }
+ }
+ }
+ },
+ "Max depth (%@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur max (%@)"
+ }
+ }
+ }
+ },
+ "Maximum depth": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profondeur maximale"
+ }
+ }
+ }
+ },
+ "Metric (m, °C, bar)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Métriques (m, °C, bar)"
+ }
+ }
+ }
+ },
+ "Misty Wharf": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Quai des Brumes"
+ }
+ }
+ }
+ },
+ "Mode": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mode"
+ }
+ }
+ }
+ },
+ "Model": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Modèle"
+ }
+ }
+ }
+ },
+ "Month": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mois"
+ }
+ }
+ }
+ },
+ "More actions": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Autres actions"
+ }
+ }
+ }
+ },
+ "Most dived sites": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieux les plus plongés"
+ }
+ }
+ }
+ },
+ "Never": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Jamais"
+ }
+ }
+ }
+ },
+ "New account": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nouveau compte"
+ }
+ }
+ }
+ },
+ "New dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nouvelle plongée"
+ }
+ }
+ }
+ },
+ "New site": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nouveau lieu"
+ }
+ }
+ }
+ },
+ "New site…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nouveau lieu…"
+ }
+ }
+ }
+ },
+ "Night dive: bioluminescence at the safety stop.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée de nuit : bioluminescence au palier."
+ }
+ }
+ }
+ },
+ "No dives": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucune plongée"
+ }
+ }
+ }
+ },
+ "No dives in this file.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucune plongée dans ce fichier."
+ }
+ }
+ }
+ },
+ "No logbook found for this account.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucun carnet trouvé pour ce compte."
+ }
+ }
+ }
+ },
+ "No photos around this dive in this iPhone's photo library.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucune photo autour de cette plongée dans la photothèque de cet iPhone."
+ }
+ }
+ }
+ },
+ "No photos from that day in this iPhone's photo library.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucune photo ce jour-là dans la photothèque de cet iPhone."
+ }
+ }
+ }
+ },
+ "No photos of your dives here in this iPhone's photo library.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucune photo de vos plongées ici dans la photothèque de cet iPhone."
+ }
+ }
+ }
+ },
+ "No profile recorded for this dive.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pas de profil enregistré pour cette plongée."
+ }
+ }
+ }
+ },
+ "No site": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucun lieu"
+ }
+ }
+ }
+ },
+ "No sites": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucun lieu"
+ }
+ }
+ }
+ },
+ "No sites with a location": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucun lieu avec position"
+ }
+ }
+ }
+ },
+ "No statistics yet": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pas encore de statistiques"
+ }
+ }
+ }
+ },
+ "No stop": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sans palier"
+ }
+ }
+ }
+ },
+ "None": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Aucun"
+ }
+ }
+ }
+ },
+ "North Quarry": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carrière du Nord"
+ }
+ }
+ }
+ },
+ "Not used": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Non utilisée"
+ }
+ }
+ }
+ },
+ "Notes": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Notes"
+ }
+ }
+ }
+ },
+ "Number of dives per depth range": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nombre de plongées par tranche de profondeur"
+ }
+ }
+ }
+ },
+ "Number of dives per duration range": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nombre de plongées par tranche de durée"
+ }
+ }
+ }
+ },
+ "Number of dives per month of the year": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nombre de plongées par mois de l'année"
+ }
+ }
+ }
+ },
+ "Number of dives per year": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nombre de plongées par année"
+ }
+ }
+ }
+ },
+ "OK": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "OK"
+ }
+ }
+ }
+ },
+ "Open Settings": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ouvrir les réglages"
+ }
+ }
+ }
+ },
+ "Open in Maps": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ouvrir dans Plans"
+ }
+ }
+ }
+ },
+ "Password": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mot de passe"
+ }
+ }
+ }
+ },
+ "Password, again": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mot de passe, encore"
+ }
+ }
+ }
+ },
+ "Photo access is denied. You can turn it back on in Settings → Privacy → Photos.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "L'accès aux photos est refusé. Il se rétablit dans Réglages → Confidentialité → Photos."
+ }
+ }
+ }
+ },
+ "Photos": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Photos"
+ }
+ }
+ }
+ },
+ "Poor visibility after the rain.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Visibilité réduite après la pluie."
+ }
+ }
+ }
+ },
+ "Position": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Position"
+ }
+ }
+ }
+ },
+ "Pressure": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pression"
+ }
+ }
+ }
+ },
+ "Profile": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Profil"
+ }
+ }
+ }
+ },
+ "Rating": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Évaluation"
+ }
+ }
+ }
+ },
+ "Refresher dive, sea fans everywhere.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Plongée de réadaptation, gorgones en éventail partout."
+ }
+ }
+ }
+ },
+ "Rocky bottom and kelp": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Fond de roche et laminaires"
+ }
+ }
+ }
+ },
+ "SAC": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Conso."
+ }
+ }
+ }
+ },
+ "Save": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Enregistrer"
+ }
+ }
+ }
+ },
+ "Sea Fan Reef": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Récif des Gorgones"
+ }
+ }
+ }
+ },
+ "Seal Cove": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Anse aux Phoques"
+ }
+ }
+ }
+ },
+ "Search for a site": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Chercher un lieu"
+ }
+ }
+ }
+ },
+ "Search sites": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Chercher un lieu"
+ }
+ }
+ }
+ },
+ "Select all": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Tout cocher"
+ }
+ }
+ }
+ },
+ "Series": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Série"
+ }
+ }
+ }
+ },
+ "Settings": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Réglages"
+ }
+ }
+ }
+ },
+ "Sharp thermocline at 9 m.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Thermocline marquée à 9 m."
+ }
+ }
+ }
+ },
+ "Sign in": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Se connecter"
+ }
+ }
+ }
+ },
+ "Sign out": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Se déconnecter"
+ }
+ }
+ }
+ },
+ "Sign out?": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Se déconnecter ?"
+ }
+ }
+ }
+ },
+ "Signing in…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connexion…"
+ }
+ }
+ }
+ },
+ "Site": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu"
+ }
+ }
+ }
+ },
+ "Site added by the test": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu ajouté par l'essai"
+ }
+ }
+ }
+ },
+ "Site added: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu ajouté : %@"
+ }
+ }
+ }
+ },
+ "Site name": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nom du lieu"
+ }
+ }
+ }
+ },
+ "Site position": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Position d'un lieu"
+ }
+ }
+ }
+ },
+ "Site removed": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu retiré"
+ }
+ }
+ }
+ },
+ "Site, buddy, tag, notes": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu, binôme, étiquette, notes"
+ }
+ }
+ }
+ },
+ "Sites": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieux"
+ }
+ }
+ }
+ },
+ "Sites visited": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieux visités"
+ }
+ }
+ }
+ },
+ "Skills review on the 6 m platform.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Révision des exercices sur la plateforme de 6 m."
+ }
+ }
+ }
+ },
+ "Small freighter sitting upright on the sand": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Petit cargo posé droit sur le sable"
+ }
+ }
+ }
+ },
+ "Start": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Début"
+ }
+ }
+ }
+ },
+ "Statistics": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Statistiques"
+ }
+ }
+ }
+ },
+ "Stop": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Palier"
+ }
+ }
+ }
+ },
+ "Sub Rascasse can show the photos and videos taken during the dive here. They stay on your iPhone: nothing is uploaded.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sub Rascasse peut montrer ici les photos et vidéos prises pendant la plongée. Elles restent sur l'iPhone : rien n'est envoyé."
+ }
+ }
+ }
+ },
+ "Subsurface account email": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Courriel du compte Subsurface"
+ }
+ }
+ }
+ },
+ "Subsurface cloud": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Nuage Subsurface"
+ }
+ }
+ }
+ },
+ "Subsurface cloud denies access to this logbook (response 403).": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage Subsurface interdit l'accès à ce carnet (réponse 403)."
+ }
+ }
+ }
+ },
+ "Subsurface cloud passwords can only contain unaccented letters, digits and the characters @ . + _ -": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage Subsurface n'accepte dans le mot de passe que des lettres sans accent, des chiffres et les signes @ . + _ -"
+ }
+ }
+ }
+ },
+ "Subsurface cloud rejected this email and password (response 401). Check them, or create an account if you don't have one yet.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage Subsurface a refusé ce courriel et ce mot de passe (réponse 401). Vérifiez-les, ou créez un compte s'il n'existe pas encore."
+ }
+ }
+ }
+ },
+ "Subsurface cloud responded with an error (%lld).": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage Subsurface a répondu par une erreur (%lld)."
+ }
+ }
+ }
+ },
+ "Suit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Combinaison"
+ }
+ }
+ }
+ },
+ "Summary": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Résumé"
+ }
+ }
+ }
+ },
+ "Surface": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Surface"
+ }
+ }
+ }
+ },
+ "Surface in": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Surface dans"
+ }
+ }
+ }
+ },
+ "Sync now": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Synchroniser maintenant"
+ }
+ }
+ }
+ },
+ "Tags, separated by commas": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Étiquettes, séparées par des virgules"
+ }
+ }
+ }
+ },
+ "Taken during the dive": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prise pendant la plongée"
+ }
+ }
+ }
+ },
+ "Team": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Équipe"
+ }
+ }
+ }
+ },
+ "Temperature": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Température"
+ }
+ }
+ }
+ },
+ "Test failed: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Essai en échec : %@"
+ }
+ }
+ }
+ },
+ "That code is incorrect.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ce code n'est pas le bon."
+ }
+ }
+ }
+ },
+ "The Subsurface cloud just sent a code to %@. It may take a few minutes to arrive; check your junk folder too.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage Subsurface vient d'envoyer un code à %@. Il peut mettre quelques minutes à arriver ; regardez aussi dans les indésirables."
+ }
+ }
+ }
+ },
+ "The Subsurface cloud refused: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage Subsurface a refusé : %@"
+ }
+ }
+ }
+ },
+ "The account is created in the Subsurface cloud (cloud.subsurface-divelog.org), the free service of the Subsurface project. It also works in Subsurface on a computer. Password: unaccented letters, digits and @ . + _ - only.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le compte est créé dans le nuage Subsurface (cloud.subsurface-divelog.org), le service gratuit du projet Subsurface. Il servira aussi dans Subsurface sur ordinateur. Mot de passe : lettres sans accent, chiffres et @ . + _ - seulement."
+ }
+ }
+ }
+ },
+ "The account is your Subsurface cloud account (cloud.subsurface-divelog.org), the same one you use in Subsurface. Your credentials are sent only to that service, and the password stays in the iPhone keychain.\n\n%@ is an independent app, not affiliated with the Subsurface team.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le compte est celui du nuage Subsurface (cloud.subsurface-divelog.org), le même que dans Subsurface. Vos identifiants ne sont envoyés qu'à ce service et le mot de passe reste dans le trousseau de l'iPhone.\n\n%@ est une application indépendante, sans lien avec l'équipe de Subsurface."
+ }
+ }
+ }
+ },
+ "The cloud rejected the upload: %@": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le nuage a refusé l'envoi : %@"
+ }
+ }
+ }
+ },
+ "The copy of the logbook on this iPhone will be erased. Nothing is deleted in the cloud.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La copie du carnet sur cet iPhone sera effacée. Rien n'est supprimé dans le nuage."
+ }
+ }
+ }
+ },
+ "The deletion will be sent to the Subsurface cloud at the next sync.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La suppression sera envoyée au nuage Subsurface à la prochaine synchronisation."
+ }
+ }
+ }
+ },
+ "The dive no longer exists in the logbook.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La plongée n'existe plus dans le carnet."
+ }
+ }
+ }
+ },
+ "The location can be added later in Subsurface.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La position pourra être ajoutée plus tard dans Subsurface."
+ }
+ }
+ }
+ },
+ "The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. Dives already in the logbook (same start time) are skipped.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Les plongées choisies sont ajoutées au carnet avec leur profil complet, puis envoyées au nuage Subsurface. Celles que le carnet contient déjà (même heure de début) sont laissées de côté."
+ }
+ }
+ }
+ },
+ "They'll appear with your first dives.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Elles apparaîtront avec vos premières plongées."
+ }
+ }
+ }
+ },
+ "This email is not valid.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ce courriel n'est pas valide."
+ }
+ }
+ }
+ },
+ "Three curious seals for the whole dive.\nVery clear water for the season.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Trois phoques curieux pendant toute la plongée.\nEau très claire pour la saison."
+ }
+ }
+ }
+ },
+ "Time": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Temps"
+ }
+ }
+ }
+ },
+ "Time spent": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Temps passé"
+ }
+ }
+ }
+ },
+ "Time underwater": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Temps sous l'eau"
+ }
+ }
+ }
+ },
+ "Trilaminate drysuit": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Étanche trilaminé"
+ }
+ }
+ }
+ },
+ "Trip": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Voyage"
+ }
+ }
+ }
+ },
+ "Trips": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Voyages"
+ }
+ }
+ }
+ },
+ "Try a demo logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Essayer avec un carnet de démonstration"
+ }
+ }
+ }
+ },
+ "Trying out the new regulator.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Essai du nouveau détendeur."
+ }
+ }
+ }
+ },
+ "Turtle Wall": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Tombant aux Tortues"
+ }
+ }
+ }
+ },
+ "Two green turtles and a school of jacks.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Deux tortues vertes et un banc de carangues."
+ }
+ }
+ }
+ },
+ "Under 15 min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "moins de 15 min"
+ }
+ }
+ }
+ },
+ "Units": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Unités"
+ }
+ }
+ }
+ },
+ "Unknown": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Inconnu"
+ }
+ }
+ }
+ },
+ "Unknown site": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu inconnu"
+ }
+ }
+ }
+ },
+ "Unnamed site": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lieu sans nom"
+ }
+ }
+ }
+ },
+ "Verification": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Vérification"
+ }
+ }
+ }
+ },
+ "Verify code": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Valider le code"
+ }
+ }
+ }
+ },
+ "Version": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Version"
+ }
+ }
+ }
+ },
+ "View": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Affichage"
+ }
+ }
+ }
+ },
+ "Visibility": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Visibilité"
+ }
+ }
+ }
+ },
+ "Visit to the old truck at the bottom of the quarry.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Visite du vieux camion au fond de la carrière."
+ }
+ }
+ }
+ },
+ "Waiting to upload": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "En attente d'envoi"
+ }
+ }
+ }
+ },
+ "Warmest water": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Eau la plus chaude"
+ }
+ }
+ }
+ },
+ "Warning: %@ change(s) not yet uploaded will be lost. The copy of the logbook on this iPhone will be erased.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Attention : %@ modification(s) pas encore envoyée(s) seront perdues. La copie du carnet sur cet iPhone sera effacée."
+ }
+ }
+ }
+ },
+ "Warning: %lld change(s) not yet uploaded will be lost. The copy of the logbook on this iPhone will be erased.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Attention : %lld modification(s) pas encore envoyée(s) seront perdues. La copie du carnet sur cet iPhone sera effacée."
+ }
+ }
+ }
+ },
+ "Water": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Eau"
+ }
+ }
+ }
+ },
+ "Water (%@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Eau (%@)"
+ }
+ }
+ }
+ },
+ "Waves": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Vagues"
+ }
+ }
+ }
+ },
+ "Weights": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Lest"
+ }
+ }
+ }
+ },
+ "With photos": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avec photos"
+ }
+ }
+ }
+ },
+ "With photos and videos": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avec photos et vidéos"
+ }
+ }
+ }
+ },
+ "With videos": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Avec vidéos"
+ }
+ }
+ }
+ },
+ "Year": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Année"
+ }
+ }
+ }
+ },
+ "Your Subsurface dive log, on iPhone.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Votre carnet de plongée Subsurface, sur iPhone."
+ }
+ }
+ }
+ },
+ "ascent too fast": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "remontée trop rapide"
+ }
+ }
+ }
+ },
+ "belt": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ceinture"
+ }
+ }
+ }
+ },
+ "ceiling violated": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "plafond franchi"
+ }
+ }
+ }
+ },
+ "change": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "changement"
+ }
+ }
+ }
+ },
+ "critical ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ppO2 critique"
+ }
+ }
+ }
+ },
+ "cu ft/min": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "pi³/min"
+ }
+ }
+ }
+ },
+ "deep": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "profonde"
+ }
+ }
+ }
+ },
+ "fast ascent": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "remontée rapide"
+ }
+ }
+ }
+ },
+ "high ppO2": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ppO2 élevée"
+ }
+ }
+ }
+ },
+ "missed safety stop": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "palier de sécurité sauté"
+ }
+ }
+ }
+ },
+ "night": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "nuit"
+ }
+ }
+ }
+ },
+ "pockets": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "poches"
+ }
+ }
+ }
+ },
+ "reef": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "récif"
+ }
+ }
+ }
+ },
+ "seals": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "phoques"
+ }
+ }
+ }
+ },
+ "training": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "formation"
+ }
+ }
+ }
+ },
+ "tuning": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "réglages"
+ }
+ }
+ }
+ },
+ "turtles": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "tortues"
+ }
+ }
+ }
+ },
+ "wreck": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "épave"
+ }
+ }
+ }
+ },
+ "–": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "–"
+ }
+ }
+ }
+ }
+ },
+ "version": "1.0"
+}
+\ No newline at end of file
diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
import Observation
@@ -31,7 +32,7 @@ final class AppModel {
@ObservationIgnored private var password = ""
@ObservationIgnored private var syncTask: Task<Void, Never>?
- // MARK: Démarrage et compte
+ // MARK: Startup and account
func start() async {
guard phase == .launching else { return }
@@ -40,7 +41,7 @@ final class AppModel {
return
}
#if DEBUG
- // Essais dans le simulateur sur un vrai carnet : identifiants passés par l'environnement, jamais en version publiée.
+ // Simulator testing against a real logbook: credentials come from the environment, never in a release build.
let environment = ProcessInfo.processInfo.environment
if let devEmail = environment["DEV_CLOUD_EMAIL"], let devPassword = environment["DEV_CLOUD_PASSWORD"] {
do {
@@ -87,10 +88,12 @@ final class AppModel {
lastSync = await repository.lastSync
}
- /// Vérifie les identifiants auprès du nuage, puis télécharge le carnet.
+ /// Checks the credentials with the cloud, then downloads the logbook.
func signIn(email rawEmail: String, password rawPassword: String) async throws {
let account = SubsurfaceCloud.sanitize(email: rawEmail)
- guard account.contains("@"), !rawPassword.isEmpty else { throw AppError.message("Entrez votre courriel et votre mot de passe.") }
+ guard account.contains("@"), !rawPassword.isEmpty else {
+ throw AppError.message(String(localized: "Enter your email and password."))
+ }
let transport = SubsurfaceCloud.transport(email: account, password: rawPassword)
do {
_ = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
@@ -143,22 +146,24 @@ final class AppModel {
}
}
- /// Essai de bout en bout du circuit de modification (option de lancement `-demoChanges`).
+ /// End-to-end test of the editing pipeline (launch option `-demoChanges`).
private func demoChanges() async {
guard let latest = logbook.dives.first else { return }
do {
- try await apply(.editDive(when: latest.when, number: latest.number, fields: ["buddy": "Modifié par l'essai", "rating": "1"]))
+ try await apply(.editDive(when: latest.when, number: latest.number,
+ fields: ["buddy": String(localized: "Edited by the test"), "rating": "1"]))
let uuid = newSiteUUID()
- try await apply(.addSite(uuid: uuid, name: "Lieu ajouté par l'essai", latitude: nil, longitude: nil))
+ try await apply(.addSite(uuid: uuid, name: String(localized: "Site added by the test"), latitude: nil, longitude: nil))
var dive = NewDive(when: latest.when + 86_400, number: logbook.nextNumber, durationSeconds: 1500, maxDepth: 9.5)
dive.siteUUID = uuid
try await apply(.addDive(dive))
} catch {
- notices.append("Essai en échec : \(Self.describe(error))")
+ let reason = Self.describe(error)
+ notices.append(String(localized: "Test failed: \(reason)"))
}
}
- // MARK: Synchronisation
+ // MARK: Sync
func scheduleSync() {
syncTask?.cancel()
@@ -176,7 +181,7 @@ final class AppModel {
do {
let report = try await repository.sync(transport: SubsurfaceCloud.transport(email: email, password: password),
appVersion: Brand.shortVersion)
- notices.append(contentsOf: report.dropped.map { "Modification abandonnée : \($0)" })
+ notices.append(contentsOf: report.dropped.map { (dropped: String) in String(localized: "Change dropped: \(dropped)") })
try await reload()
syncState = .idle
} catch {
@@ -188,21 +193,71 @@ final class AppModel {
static func describe(_ error: Error) -> String {
if let git = error as? GitError {
switch git {
- case .unauthorized: return "Le nuage Subsurface a refusé ce courriel et ce mot de passe (réponse 401). Vérifiez-les, ou créez un compte s'il n'existe pas encore."
- case .http(403): return "Le nuage Subsurface interdit l'accès à ce carnet (réponse 403)."
- case .notFound: return "Aucun carnet trouvé pour ce compte."
- case .network(let what): return "Connexion impossible : \(what)"
- case .http(let code): return "Le nuage Subsurface a répondu par une erreur (\(code))."
- case .pushRejected(let why): return "Le nuage a refusé l'envoi : \(why)"
- default: return "Synchronisation impossible (\(git))."
+ case .unauthorized:
+ return String(localized: "Subsurface cloud rejected this email and password (response 401). Check them, or create an account if you don't have one yet.")
+ case .http(403): return String(localized: "Subsurface cloud denies access to this logbook (response 403).")
+ case .notFound: return String(localized: "No logbook found for this account.")
+ case .network(let what): return String(localized: "Couldn't connect: \(what)")
+ case .http(let code): return String(localized: "Subsurface cloud responded with an error (\(code)).")
+ case .pushRejected(let why): return String(localized: "The cloud rejected the upload: \(why)")
+ default:
+ // Unexpected cases: the library's developer description is the only detail available.
+ let detail = String(describing: git)
+ return String(localized: "Couldn't sync (\(detail)).")
}
}
if let app = error as? AppError { return app.description }
- if let change = error as? ChangeError { return change.description.capitalizedFirst + "." }
+ if let change = error as? ChangeError {
+ switch change {
+ case .diveNotFound: return String(localized: "The dive no longer exists in the logbook.")
+ case .diveAlreadyExists: return String(localized: "A dive already exists at this date and time.")
+ }
+ }
+ if let importError = error as? ImportError {
+ switch importError {
+ case .unknownFormat:
+ return String(localized: "File format not recognized. Supported formats: Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).")
+ case .unreadable(let why): return String(localized: "Couldn't read the file: \(why)")
+ case .empty: return String(localized: "No dives in this file.")
+ }
+ }
return error.localizedDescription
}
- // MARK: Modifications
+ /// One-line description of a pending change, for the list of changes waiting to be uploaded.
+ static func summary(_ change: LogChange) -> String {
+ switch change {
+ case .editDive(_, let number, let fields):
+ // Dive numbers are identifiers: formatted as plain text so they never get a thousands separator.
+ let dive = String(number)
+ let names = fields.keys.sorted().joined(separator: ", ")
+ return String(localized: "Dive \(dive) edited (\(names))")
+ case .addDive(let newDive):
+ let dive = String(newDive.number)
+ return String(localized: "Dive \(dive) added")
+ case .deleteDive(_, let number):
+ let dive = String(number)
+ return String(localized: "Dive \(dive) deleted")
+ case .addSite(_, let name, _, _):
+ return String(localized: "Site added: \(name)")
+ case .importDive(let imported, let number, _):
+ let dive = String(number)
+ let model = imported.model
+ return String(localized: "Dive \(dive) imported (\(model))")
+ case .ensureSettings:
+ return String(localized: "Logbook settings")
+ case .locateSite:
+ return String(localized: "Site position")
+ case .removeSite:
+ return String(localized: "Site removed")
+ case .renumberDive(_, let number, let newNumber):
+ let dive = String(number)
+ let renumbered = String(newNumber)
+ return String(localized: "Dive \(dive) renumbered to \(renumbered)")
+ }
+ }
+
+ // MARK: Changes
func apply(_ change: LogChange) async throws {
guard let repository else { return }
@@ -215,7 +270,7 @@ final class AppModel {
scheduleSync()
}
- // MARK: Import de fichiers
+ // MARK: File import
struct ImportCandidate: Identifiable {
let dive: ImportedDive
@@ -223,7 +278,7 @@ final class AppModel {
var id: String { dive.id }
}
- /// Lit un fichier d'export et dit, pour chaque plongée, si le carnet l'a déjà (même heure de début à 2 minutes près).
+ /// Reads an export file and tells, for each dive, whether the logbook already has it (same start time within 2 minutes).
func importCandidates(from url: URL) throws -> [ImportCandidate] {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
@@ -231,7 +286,7 @@ final class AppModel {
do {
data = try Data(contentsOf: url)
} catch {
- throw AppError.message("Impossible de lire ce fichier.")
+ throw AppError.message(String(localized: "Couldn't read this file."))
}
do {
let known = logbook.dives.map(\.when)
@@ -239,12 +294,12 @@ final class AppModel {
ImportCandidate(dive: dive, alreadyInLog: known.contains { abs($0 - dive.when) < 120 })
}
} catch let error as ImportError {
- throw AppError.message(error.description)
+ throw AppError.message(Self.describe(error))
}
}
- /// Ajoute les plongées au carnet, de la plus ancienne à la plus récente, en créant les lieux qui manquent.
- /// Rend le nombre de plongées ajoutées.
+ /// Adds the dives to the logbook, oldest first, creating any missing sites.
+ /// Returns the number of dives added.
func importDives(_ dives: [ImportedDive]) async throws -> Int {
guard let repository else { return 0 }
let added: Int
@@ -260,9 +315,9 @@ final class AppModel {
return added
}
- // MARK: Plongées d'Open Rémora
+ // MARK: Dives from Open Rémora
- /// Dossier où l'app iPhone d'Open Rémora dépose les plongées de la montre (groupe d'apps partagé).
+ /// Folder where the Open Rémora iPhone app drops the dives from the watch (shared app group).
private var remoraFolder: URL? {
if let path = LaunchOptions.value("-remoraFolder") { return URL(fileURLWithPath: path) }
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: RemoraImport.appGroup)?
@@ -271,9 +326,9 @@ final class AppModel {
@ObservationIgnored private var importingFromRemora = false
- /// Ajoute au carnet les plongées en attente, puis retire leurs fichiers du dossier partagé. Rien ne se passe tant
- /// qu'aucun carnet n'est ouvert (ou dans le carnet de démonstration, sauf pour les captures d'écran) : les
- /// plongées restent alors en attente du côté d'Open Rémora.
+ /// Adds the pending dives to the logbook, then removes their files from the shared folder. Nothing happens while
+ /// no logbook is open (or in the demo logbook, except for screenshots): the dives then stay pending on the
+ /// Open Rémora side.
func importFromOpenRemora() async {
guard phase == .ready, let repository, !importingFromRemora, let folder = remoraFolder else { return }
guard !isDemo || LaunchOptions.value("-remoraFolder") != nil else { return }
@@ -281,37 +336,51 @@ final class AppModel {
guard !files.isEmpty else { return }
importingFromRemora = true
defer { importingFromRemora = false }
+ // The alarms of the watch are written into the dive notes, in the user's language.
+ let alarmLabels = [
+ "ascentFast": String(localized: "fast ascent"),
+ "ascentTooFast": String(localized: "ascent too fast"),
+ "ceilingViolated": String(localized: "ceiling violated"),
+ "ppO2High": String(localized: "high ppO2"),
+ "ppO2Critical": String(localized: "critical ppO2"),
+ "missedSafetyStop": String(localized: "missed safety stop"),
+ ]
+ let alarmsPrefix = String(localized: "Alarms: ")
var added = 0
for file in files {
do {
- let dive = try RemoraImport.dive(fromJSON: try Data(contentsOf: file))
+ let dive = try RemoraImport.dive(fromJSON: try Data(contentsOf: file), timeZone: .current,
+ alarmLabels: alarmLabels, alarmsPrefix: alarmsPrefix)
added += try await repository.importDives([dive])
- RemoraImport.consume(file) // importée, ou déjà dans le carnet : elle n'est plus en attente
+ RemoraImport.consume(file) // imported, or already in the logbook: it is no longer pending
} catch {
- notices.append("Plongée d'Open Rémora illisible (\(file.lastPathComponent)) : \(Self.describe(error))")
+ let name = file.lastPathComponent
+ let reason = Self.describe(error)
+ notices.append(String(localized: "Couldn't read the Open Rémora dive (\(name)): \(reason)"))
}
}
try? await reload()
if added > 0 {
- notices.append(added == 1 ? "1 plongée d'Open Rémora ajoutée au carnet." : "\(added) plongées d'Open Rémora ajoutées au carnet.")
+ notices.append(added == 1 ? String(localized: "1 Open Rémora dive added to the logbook.")
+ : String(localized: "\(added) Open Rémora dives added to the logbook."))
scheduleSync()
}
}
- // MARK: Plongées et lieux qui ont des photos
+ // MARK: Dives and sites that have photos
- /// Ce que la photothèque contient pour chaque plongée (vide tant que l'accès n'est pas accordé).
+ /// What the photo library holds for each dive (empty until access is granted).
var photoPresence: [String: DivePhotoFinder.Presence] = [:]
- /// Lieux dont au moins une plongée a des photos ou des vidéos.
+ /// Sites where at least one dive has photos or videos.
var sitesWithPhotos: Set<UInt32> = []
@ObservationIgnored private var scanningPhotos = false
- /// Cherche, plongée par plongée, s'il existe des photos ou des vidéos prises à ce moment-là. Sans l'autorisation
- /// d'accès à la photothèque, rien ne se passe. Le fuseau de chaque lieu est demandé une fois à Apple, sans se presser.
+ /// Looks, dive by dive, for photos or videos taken at that time. Without permission to access the photo
+ /// library, nothing happens. The time zone of each site is requested from Apple once, without hurrying.
func refreshPhotoPresence() async {
var status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
- // Première fois : on pose la question dès que le carnet est affiché, pour que la liste et la carte puissent
- // signaler les plongées qui ont des photos. iOS ne la repose jamais ; un refus se change dans les Réglages.
+ // First time: ask as soon as the logbook is shown, so the list and the map can flag the dives that have
+ // photos. iOS never asks again; a refusal can be changed in Settings.
if status == .notDetermined, phase == .ready, !LaunchOptions.flag("-noPhotoPrompt") {
status = await PHPhotoLibrary.requestAuthorization(for: .readWrite)
}
@@ -320,7 +389,7 @@ final class AppModel {
defer { scanningPhotos = false }
let log = logbook
- // Premier passage, tout de suite, avec les fuseaux connus ou estimés.
+ // First pass, right away, with the known or estimated time zones.
func scan() async -> [String: DivePhotoFinder.Presence] {
await Task.detached(priority: .utility) {
var found = [String: DivePhotoFinder.Presence]()
@@ -340,7 +409,7 @@ final class AppModel {
}
publish(await scan())
- // Puis on retrouve les vrais fuseaux qui manquent, un lieu à la fois, et on affine.
+ // Then look up the real time zones that are missing, one site at a time, and refine.
let used = Set(log.dives.compactMap(\.siteUUID))
let missing = used.compactMap { log.sites[$0] }.filter { $0.hasLocation && SiteTimeZone.cached(for: $0) == nil }
guard !missing.isEmpty else { return }
@@ -351,15 +420,17 @@ final class AppModel {
publish(await scan())
}
- // MARK: Création de compte
+ // MARK: Account creation
private var cloudUserAgent: String { "SubRascasse:\(Brand.shortVersion):iOS" }
- /// Demande la création du compte ; le nuage envoie alors un code par courriel.
+ /// Requests the account creation; the cloud then sends a code by email.
func createAccount(email: String, password: String) async throws -> CloudAccount.Status {
- guard CloudAccount.isValid(email: SubsurfaceCloud.sanitize(email: email)) else { throw AppError.message("Ce courriel n'est pas valide.") }
+ guard CloudAccount.isValid(email: SubsurfaceCloud.sanitize(email: email)) else {
+ throw AppError.message(String(localized: "This email is not valid."))
+ }
guard CloudAccount.isValid(password: password) else {
- throw AppError.message("Le nuage Subsurface n'accepte dans le mot de passe que des lettres sans accent, des chiffres et les signes @ . + _ -")
+ throw AppError.message(String(localized: "Subsurface cloud passwords can only contain unaccented letters, digits and the characters @ . + _ -"))
}
do {
return try await CloudAccount.submit(email: email, password: password, userAgent: cloudUserAgent)
@@ -368,7 +439,7 @@ final class AppModel {
}
}
- /// Valide le code reçu par courriel.
+ /// Validates the code received by email.
func verifyAccount(email: String, password: String, pin: String) async throws -> CloudAccount.Status {
do {
return try await CloudAccount.submit(email: email, password: password, pin: pin.trimmingCharacters(in: .whitespaces), userAgent: cloudUserAgent)
@@ -393,16 +464,16 @@ final class AppModel {
return uuid
}
- // MARK: Vues dérivées
+ // MARK: Derived views
func dive(id: String) -> Dive? { logbook.dives.first { $0.id == id } }
func siteName(of dive: Dive) -> String {
let name = logbook.site(of: dive)?.name ?? ""
- return name.isEmpty ? "Lieu inconnu" : name
+ return name.isEmpty ? String(localized: "Unknown site") : name
}
- /// Plongées regroupées par voyage, sinon par mois, de la plus récente à la plus ancienne.
+ /// Dives grouped by trip, otherwise by month, most recent first.
func sections(matching search: String) -> [DiveSection] {
let needle = search.trimmingCharacters(in: .whitespaces).lowercased()
let dives = needle.isEmpty ? logbook.dives : logbook.dives.filter { dive in
@@ -417,7 +488,7 @@ final class AppModel {
if sections.last?.id == key {
sections[sections.count - 1].dives.append(dive)
} else if let trip = logbook.trip(of: dive) {
- sections.append(DiveSection(id: key, title: trip.location.isEmpty ? "Voyage" : trip.location,
+ sections.append(DiveSection(id: key, title: trip.location.isEmpty ? String(localized: "Trip") : trip.location,
subtitle: DiveDate.monthTitle(dive.when), dives: [dive]))
} else {
sections.append(DiveSection(id: key, title: DiveDate.monthTitle(dive.when), subtitle: "", dives: [dive]))
@@ -427,6 +498,7 @@ final class AppModel {
}
}
+/// An error whose message is already localized and ready to show to the user.
enum AppError: Error, CustomStringConvertible {
case message(String)
var description: String {
diff --git a/App/Model/DemoData.swift b/App/Model/DemoData.swift
@@ -1,8 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import SubsurfaceLog
-/// Carnet de démonstration, écrit dans le vrai format de Subsurface : il sert aux essais sans compte,
-/// aux captures d'écran et aux réviseurs des magasins d'applications. Lieux et personnes fictifs.
+/// Demo logbook, written in the real Subsurface format: it is used for trying the app without an account,
+/// for screenshots and by app store reviewers. Sites and people are fictional.
+///
+/// Everything the user reads (site names, notes, tags, equipment) is localized; Subsurface keywords, file names
+/// and folder names in the git paths are not.
enum DemoData {
private struct Site {
let uuid: String, name: String, description: String, latitude: Double, longitude: Double, country: String
@@ -25,31 +29,31 @@ enum DemoData {
}
private static let sites = [
- Site(uuid: "c0000001", name: "Récif des Gorgones", description: "Récif frangeant, entrée du bord", latitude: 12.1600, longitude: -68.2900, country: "Bonaire"),
- Site(uuid: "c0000002", name: "Épave du Cormoran", description: "Petit cargo posé droit sur le sable", latitude: 12.2150, longitude: -68.3450, country: "Bonaire"),
- Site(uuid: "c0000003", name: "Tombant aux Tortues", description: "Tombant en pente douce jusqu'à 35 m", latitude: 12.0950, longitude: -68.2850, country: "Bonaire"),
- Site(uuid: "c0000004", name: "Carrière du Nord", description: "Carrière inondée, plateformes à 6 m et 12 m", latitude: 45.6500, longitude: -75.9200, country: "Canada"),
- Site(uuid: "c0000005", name: "Anse aux Phoques", description: "Fond de roche et laminaires", latitude: 48.8300, longitude: -64.2000, country: "Canada"),
- Site(uuid: "c0000006", name: "Quai des Brumes", description: "Plongée sous le quai, beaucoup de vie fixée", latitude: 48.4200, longitude: -64.3300, country: "Canada"),
+ Site(uuid: "c0000001", name: String(localized: "Sea Fan Reef"), description: String(localized: "Fringing reef, shore entry"), latitude: 12.1600, longitude: -68.2900, country: "Bonaire"),
+ Site(uuid: "c0000002", name: String(localized: "Cormorant Wreck"), description: String(localized: "Small freighter sitting upright on the sand"), latitude: 12.2150, longitude: -68.3450, country: "Bonaire"),
+ Site(uuid: "c0000003", name: String(localized: "Turtle Wall"), description: String(localized: "Gently sloping wall down to 35 m"), latitude: 12.0950, longitude: -68.2850, country: "Bonaire"),
+ Site(uuid: "c0000004", name: String(localized: "North Quarry"), description: String(localized: "Flooded quarry, platforms at 6 m and 12 m"), latitude: 45.6500, longitude: -75.9200, country: "Canada"),
+ Site(uuid: "c0000005", name: String(localized: "Seal Cove"), description: String(localized: "Rocky bottom and kelp"), latitude: 48.8300, longitude: -64.2000, country: "Canada"),
+ Site(uuid: "c0000006", name: String(localized: "Misty Wharf"), description: String(localized: "Dive under the wharf, lots of sessile life"), latitude: 48.4200, longitude: -64.3300, country: "Canada"),
]
private static let plans: [Plan] = [
- Plan(number: 1, date: (2025, 6, 14, 10, 5), site: "c0000004", depth: 12.4, minutes: 38, surfaceTemp: 19, bottomTemp: 11, o2: 21, buddy: "Camille", rating: 3, visibility: 2, tags: ["formation"], notes: "Révision des exercices sur la plateforme de 6 m.", trip: nil, cold: true),
- Plan(number: 2, date: (2025, 7, 5, 9, 40), site: "c0000004", depth: 18.2, minutes: 42, surfaceTemp: 22, bottomTemp: 8, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [], notes: "Thermocline marquée à 9 m.", trip: nil, cold: true),
- Plan(number: 3, date: (2025, 8, 16, 8, 30), site: "c0000005", depth: 16.8, minutes: 47, surfaceTemp: 12, bottomTemp: 6, o2: 21, buddy: "Sam", rating: 5, visibility: 4, tags: ["phoques"], notes: "Trois phoques curieux pendant toute la plongée.\nEau très claire pour la saison.", trip: "Gaspesie", cold: true),
- Plan(number: 4, date: (2025, 8, 16, 13, 15), site: "c0000006", depth: 9.6, minutes: 55, surfaceTemp: 12, bottomTemp: 8, o2: 21, buddy: "Sam", rating: 4, visibility: 3, tags: ["macro"], notes: "Anémones, nudibranches et crabes sous les piliers.", trip: "Gaspesie", cold: true),
- Plan(number: 5, date: (2025, 8, 17, 9, 0), site: "c0000005", depth: 22.3, minutes: 41, surfaceTemp: 11, bottomTemp: 5, o2: 32, buddy: "Sam, Alex", rating: 4, visibility: 4, tags: ["nitrox"], notes: "Forêt de laminaires, loup de mer dans une faille.", trip: "Gaspesie", cold: true),
- Plan(number: 6, date: (2025, 8, 18, 20, 45), site: "c0000006", depth: 8.2, minutes: 48, surfaceTemp: 12, bottomTemp: 9, o2: 21, buddy: "Alex", rating: 5, visibility: 3, tags: ["nuit", "macro"], notes: "Plongée de nuit : bioluminescence au palier.", trip: "Gaspesie", cold: true),
- Plan(number: 7, date: (2025, 10, 4, 11, 20), site: "c0000004", depth: 24.6, minutes: 36, surfaceTemp: 14, bottomTemp: 6, o2: 21, buddy: "Camille", rating: 2, visibility: 1, tags: [], notes: "Visibilité réduite après la pluie.", trip: nil, cold: true),
- Plan(number: 8, date: (2026, 5, 23, 10, 0), site: "c0000004", depth: 15.1, minutes: 44, surfaceTemp: 13, bottomTemp: 7, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: ["réglages"], notes: "Première plongée de la saison, lestage à revoir.", trip: nil, cold: true),
- Plan(number: 9, date: (2026, 6, 20, 9, 10), site: "c0000001", depth: 18.9, minutes: 58, surfaceTemp: 28, bottomTemp: 27, o2: 32, buddy: "Sam", rating: 4, visibility: 5, tags: ["récif"], notes: "Plongée de réadaptation, gorgones en éventail partout.", trip: "Bonaire", cold: false),
- Plan(number: 10, date: (2026, 6, 20, 14, 30), site: "c0000003", depth: 27.4, minutes: 52, surfaceTemp: 28, bottomTemp: 26, o2: 32, buddy: "Sam", rating: 5, visibility: 5, tags: ["tortues", "récif"], notes: "Deux tortues vertes et un banc de carangues.", trip: "Bonaire", cold: false),
- Plan(number: 11, date: (2026, 6, 21, 8, 45), site: "c0000002", depth: 30.2, minutes: 46, surfaceTemp: 28, bottomTemp: 26, o2: 32, buddy: "Sam, Alex", rating: 5, visibility: 4, tags: ["épave", "nitrox"], notes: "Tour de l'épave par la proue.\nMurène verte dans la cale avant.", trip: "Bonaire", cold: false),
- Plan(number: 12, date: (2026, 6, 21, 15, 0), site: "c0000001", depth: 14.3, minutes: 64, surfaceTemp: 29, bottomTemp: 28, o2: 32, buddy: "Alex", rating: 4, visibility: 5, tags: ["photo"], notes: "Longue plongée photo dans 10 m d'eau.", trip: "Bonaire", cold: false),
- Plan(number: 13, date: (2026, 6, 22, 9, 30), site: "c0000003", depth: 34.8, minutes: 43, surfaceTemp: 28, bottomTemp: 25, o2: 28, buddy: "Sam", rating: 4, visibility: 5, tags: ["profonde"], notes: "Descente le long du tombant jusqu'aux éponges tonneaux.", trip: "Bonaire", cold: false),
- Plan(number: 14, date: (2026, 6, 23, 19, 50), site: "c0000001", depth: 12.0, minutes: 61, surfaceTemp: 28, bottomTemp: 28, o2: 32, buddy: "Sam, Alex", rating: 5, visibility: 4, tags: ["nuit"], notes: "Poulpes en chasse et tarpons dans le faisceau des lampes.", trip: "Bonaire", cold: false),
- Plan(number: 15, date: (2026, 7, 18, 10, 30), site: "c0000004", depth: 20.4, minutes: 40, surfaceTemp: 23, bottomTemp: 9, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [], notes: "Essai du nouveau détendeur.", trip: nil, cold: true),
- Plan(number: 16, date: (2026, 9, 12, 9, 15), site: "c0000004", depth: 28.7, minutes: 39, surfaceTemp: 20, bottomTemp: 6, o2: 21, buddy: "Camille, Sam", rating: 4, visibility: 4, tags: ["profonde"], notes: "Visite du vieux camion au fond de la carrière.", trip: nil, cold: true),
+ Plan(number: 1, date: (2025, 6, 14, 10, 5), site: "c0000004", depth: 12.4, minutes: 38, surfaceTemp: 19, bottomTemp: 11, o2: 21, buddy: "Camille", rating: 3, visibility: 2, tags: [String(localized: "training")], notes: String(localized: "Skills review on the 6 m platform."), trip: nil, cold: true),
+ Plan(number: 2, date: (2025, 7, 5, 9, 40), site: "c0000004", depth: 18.2, minutes: 42, surfaceTemp: 22, bottomTemp: 8, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [], notes: String(localized: "Sharp thermocline at 9 m."), trip: nil, cold: true),
+ Plan(number: 3, date: (2025, 8, 16, 8, 30), site: "c0000005", depth: 16.8, minutes: 47, surfaceTemp: 12, bottomTemp: 6, o2: 21, buddy: "Sam", rating: 5, visibility: 4, tags: [String(localized: "seals")], notes: String(localized: "Three curious seals for the whole dive.\nVery clear water for the season."), trip: "Gaspesie", cold: true),
+ Plan(number: 4, date: (2025, 8, 16, 13, 15), site: "c0000006", depth: 9.6, minutes: 55, surfaceTemp: 12, bottomTemp: 8, o2: 21, buddy: "Sam", rating: 4, visibility: 3, tags: ["macro"], notes: String(localized: "Anemones, nudibranchs and crabs under the pilings."), trip: "Gaspesie", cold: true),
+ Plan(number: 5, date: (2025, 8, 17, 9, 0), site: "c0000005", depth: 22.3, minutes: 41, surfaceTemp: 11, bottomTemp: 5, o2: 32, buddy: "Sam, Alex", rating: 4, visibility: 4, tags: ["nitrox"], notes: String(localized: "Kelp forest, a wolffish in a crevice."), trip: "Gaspesie", cold: true),
+ Plan(number: 6, date: (2025, 8, 18, 20, 45), site: "c0000006", depth: 8.2, minutes: 48, surfaceTemp: 12, bottomTemp: 9, o2: 21, buddy: "Alex", rating: 5, visibility: 3, tags: [String(localized: "night"), "macro"], notes: String(localized: "Night dive: bioluminescence at the safety stop."), trip: "Gaspesie", cold: true),
+ Plan(number: 7, date: (2025, 10, 4, 11, 20), site: "c0000004", depth: 24.6, minutes: 36, surfaceTemp: 14, bottomTemp: 6, o2: 21, buddy: "Camille", rating: 2, visibility: 1, tags: [], notes: String(localized: "Poor visibility after the rain."), trip: nil, cold: true),
+ Plan(number: 8, date: (2026, 5, 23, 10, 0), site: "c0000004", depth: 15.1, minutes: 44, surfaceTemp: 13, bottomTemp: 7, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [String(localized: "tuning")], notes: String(localized: "First dive of the season, weighting needs adjusting."), trip: nil, cold: true),
+ Plan(number: 9, date: (2026, 6, 20, 9, 10), site: "c0000001", depth: 18.9, minutes: 58, surfaceTemp: 28, bottomTemp: 27, o2: 32, buddy: "Sam", rating: 4, visibility: 5, tags: [String(localized: "reef")], notes: String(localized: "Refresher dive, sea fans everywhere."), trip: "Bonaire", cold: false),
+ Plan(number: 10, date: (2026, 6, 20, 14, 30), site: "c0000003", depth: 27.4, minutes: 52, surfaceTemp: 28, bottomTemp: 26, o2: 32, buddy: "Sam", rating: 5, visibility: 5, tags: [String(localized: "turtles"), String(localized: "reef")], notes: String(localized: "Two green turtles and a school of jacks."), trip: "Bonaire", cold: false),
+ Plan(number: 11, date: (2026, 6, 21, 8, 45), site: "c0000002", depth: 30.2, minutes: 46, surfaceTemp: 28, bottomTemp: 26, o2: 32, buddy: "Sam, Alex", rating: 5, visibility: 4, tags: [String(localized: "wreck"), "nitrox"], notes: String(localized: "Around the wreck, starting at the bow.\nGreen moray in the forward hold."), trip: "Bonaire", cold: false),
+ Plan(number: 12, date: (2026, 6, 21, 15, 0), site: "c0000001", depth: 14.3, minutes: 64, surfaceTemp: 29, bottomTemp: 28, o2: 32, buddy: "Alex", rating: 4, visibility: 5, tags: ["photo"], notes: String(localized: "Long photo dive in 10 m of water."), trip: "Bonaire", cold: false),
+ Plan(number: 13, date: (2026, 6, 22, 9, 30), site: "c0000003", depth: 34.8, minutes: 43, surfaceTemp: 28, bottomTemp: 25, o2: 28, buddy: "Sam", rating: 4, visibility: 5, tags: [String(localized: "deep")], notes: String(localized: "Down the wall to the barrel sponges."), trip: "Bonaire", cold: false),
+ Plan(number: 14, date: (2026, 6, 23, 19, 50), site: "c0000001", depth: 12.0, minutes: 61, surfaceTemp: 28, bottomTemp: 28, o2: 32, buddy: "Sam, Alex", rating: 5, visibility: 4, tags: [String(localized: "night")], notes: String(localized: "Hunting octopuses and tarpon in the beams of our lights."), trip: "Bonaire", cold: false),
+ Plan(number: 15, date: (2026, 7, 18, 10, 30), site: "c0000004", depth: 20.4, minutes: 40, surfaceTemp: 23, bottomTemp: 9, o2: 21, buddy: "Camille", rating: 3, visibility: 3, tags: [], notes: String(localized: "Trying out the new regulator."), trip: nil, cold: true),
+ Plan(number: 16, date: (2026, 9, 12, 9, 15), site: "c0000004", depth: 28.7, minutes: 39, surfaceTemp: 20, bottomTemp: 6, o2: 21, buddy: "Camille, Sam", rating: 4, visibility: 4, tags: [String(localized: "deep")], notes: String(localized: "Visit to the old truck at the bottom of the quarry."), trip: nil, cold: true),
]
private static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
@@ -67,8 +71,12 @@ enum DemoData {
"""
}
let tripFolders = ["Gaspesie": "2025/08/16-Gaspesie", "Bonaire": "2026/06/20-Bonaire"]
- files["2025/08/16-Gaspesie/00-Trip"] = "date 2025-08-16\ntime 08:30:00\nlocation \"Gaspésie\"\nnotes \"Fin de semaine prolongée en eau froide\"\n"
- files["2026/06/20-Bonaire/00-Trip"] = "date 2026-06-20\ntime 09:10:00\nlocation \"Bonaire\"\nnotes \"Une semaine de plongées du bord\"\n"
+ // Folder names in the git paths stay ASCII and are the same in every language; only the trip text is localized.
+ let gaspeLocation = String(localized: "Gaspé Peninsula")
+ let gaspeNotes = String(localized: "Long weekend in cold water")
+ let bonaireNotes = String(localized: "A week of shore diving")
+ files["2025/08/16-Gaspesie/00-Trip"] = "date 2025-08-16\ntime 08:30:00\nlocation \(quoted(gaspeLocation))\nnotes \(quoted(gaspeNotes))\n"
+ files["2026/06/20-Bonaire/00-Trip"] = "date 2026-06-20\ntime 09:10:00\nlocation \"Bonaire\"\nnotes \(quoted(bonaireNotes))\n"
for plan in plans {
let (y, mo, d, h, mi) = plan.date
@@ -96,20 +104,24 @@ enum DemoData {
if !plan.tags.isEmpty { text += "tags " + plan.tags.map(quoted).joined(separator: ", ") + "\n" }
text += "divesiteid \(plan.site)\n"
text += "buddy \(quoted(plan.buddy))\n"
- text += "suit \(quoted(plan.cold ? "Étanche trilaminé" : "Combinaison courte 3 mm"))\n"
+ let suit = plan.cold ? String(localized: "Trilaminate drysuit") : String(localized: "3 mm shorty")
+ text += "suit \(quoted(suit))\n"
text += "notes \(quoted(plan.notes))\n"
let gas = plan.o2 == 21 ? "" : " o2=\(plan.o2).0%"
if plan.cold {
- text += "cylinder vol=12.0l workpressure=232.0bar description=\"12 L acier\"\(gas) start=\(Int(start)).0bar end=\(Int(end)).0bar\n"
- text += "weightsystem weight=10.0kg description=\"ceinture\"\n"
+ let cylinder = String(localized: "12 L steel")
+ let weights = String(localized: "belt")
+ text += "cylinder vol=12.0l workpressure=232.0bar description=\(quoted(cylinder))\(gas) start=\(Int(start)).0bar end=\(Int(end)).0bar\n"
+ text += "weightsystem weight=10.0kg description=\(quoted(weights))\n"
} else {
+ let weights = String(localized: "pockets")
text += "cylinder vol=11.1l workpressure=207.0bar description=\"AL80\"\(gas) start=\(Int(start)).0bar end=\(Int(end)).0bar\n"
- text += "weightsystem weight=4.0kg description=\"poches\"\n"
+ text += "weightsystem weight=4.0kg description=\(quoted(weights))\n"
}
return text
}
- /// Profondeur à l'instant `t` : descente, fond en deux niveaux qui ondule, remontée et palier de sécurité à 5 m.
+ /// Depth at time `t`: descent, a two-level bottom that undulates, ascent and safety stop at 5 m.
private static func depth(_ plan: Plan, at t: Int) -> Double {
let total = plan.minutes * 60
let maxDepth = plan.depth
@@ -122,7 +134,7 @@ enum DemoData {
if t <= 0 || t >= total { return 0 }
if t < descent { return maxDepth * Double(t) / Double(descent) }
if t < bottomEnd {
- // Du fond vers un second niveau à 55 % de la profondeur, en pente douce.
+ // From the bottom to a second level at 55% of the depth, on a gentle slope.
let progress = Double(t - descent) / Double(max(bottomEnd - descent, 1))
let eased = progress < 0.35 ? 0 : (progress - 0.35) / 0.65
let level = maxDepth * (1 - 0.45 * eased)
@@ -160,21 +172,23 @@ enum DemoData {
let pressure = start - (start - end) * Double(t) / Double(total)
line += " \(milli(pressure))bar:0"
}
- // Charge en azote très simplifiée, juste pour donner une marge sans palier plausible.
+ // Very simplified nitrogen loading, just enough to give a plausible no-decompression limit.
loading += max(d - 6, 0) * 10 / 60
let limit = d < 8 ? 99 : max(2, Int(1400 / pow(d, 1.25) - loading / 14))
let ndl = min(limit, 99)
if ndl != lastNDL { line += " ndl=\(ndl):00"; lastNDL = ndl }
samples += line + "\n"
}
- var text = "model \"Ordinateur de démonstration\"\n"
+ let model = String(localized: "Demo computer")
+ let decoModelKey = String(localized: "Deco model")
+ var text = "model \(quoted(model))\n"
text += "maxdepth \(milli(deepest))m\n"
text += "meandepth \(milli(sum / max(count, 1)))m\n"
text += "airtemp \(milli(plan.surfaceTemp + 3))°C\n"
text += "watertemp \(milli(plan.bottomTemp))°C\n"
text += "surfacepressure 1.013bar\n"
text += "salinity \(plan.site == "c0000004" ? 1000 : 1025)g/l\n"
- text += "keyvalue \"Modèle de décompression\" \"GF 30/70\"\n"
+ text += "keyvalue \(quoted(decoModelKey)) \"GF 30/70\"\n"
let gas = plan.o2 == 21 ? " o2=21.0%" : " o2=\(plan.o2).0%"
text += "event 0:00 type=25 flags=1 name=\"gaschange\" cylinder=0\(gas)\n"
return text + samples
diff --git a/App/Model/DivePhotos.swift b/App/Model/DivePhotos.swift
@@ -1,18 +1,19 @@
+// SPDX-License-Identifier: GPL-2.0-only
import CoreLocation
import Foundation
import Observation
import Photos
import SubsurfaceLog
-/// Une photo ou une vidéo de la photothèque rattachée à une plongée par son heure de prise de vue.
+/// A photo or video from the photo library, linked to a dive by the time it was taken.
struct DivePhoto: Identifiable {
let asset: PHAsset
- /// Secondes depuis la mise à l'eau quand la photo a été prise pendant la plongée ; nil sinon.
+ /// Seconds since the start of the dive when the photo was taken during the dive; nil otherwise.
let offset: Int?
var id: String { asset.localIdentifier }
}
-/// Accès à la photothèque : l'app ne fait que lire, et seulement après accord.
+/// Photo library access: the app only reads, and only once permission is granted.
@MainActor
@Observable
final class PhotoAccess {
@@ -25,9 +26,9 @@ final class PhotoAccess {
}
}
-/// Fuseau horaire d'un lieu de plongée. Le carnet garde l'heure locale du lieu, les photos un instant absolu :
-/// pour les rapprocher, il faut savoir dans quel fuseau était la plongée. On le demande une fois à Apple
-/// (géocodage inverse de la position du lieu), puis on le garde.
+/// Time zone of a dive site. The logbook keeps the local time of the site, photos an absolute instant: to match
+/// them, we need to know which time zone the dive was in. It is requested from Apple once (reverse geocoding of
+/// the site position), then cached.
enum SiteTimeZone {
private static func key(_ site: DiveSite) -> String {
String(format: "tz-%.2f,%.2f", site.latitude ?? 0, site.longitude ?? 0)
@@ -38,13 +39,13 @@ enum SiteTimeZone {
return TimeZone(identifier: name)
}
- /// Fuseau estimé sans réseau : celui de la longitude (heure d'hiver), exact à une heure près.
+ /// Time zone estimated offline: the one of the longitude (standard time), accurate to within an hour.
static func estimated(for site: DiveSite?) -> TimeZone {
guard let longitude = site?.longitude else { return .current }
return TimeZone(secondsFromGMT: Int((longitude / 15).rounded()) * 3600) ?? .current
}
- /// Sans position, ou si la recherche échoue : le fuseau de l'iPhone.
+ /// Without a position, or if the lookup fails: the time zone of the iPhone.
static func zone(for site: DiveSite?) async -> TimeZone {
guard let site, let latitude = site.latitude, let longitude = site.longitude else { return .current }
if let known = cached(for: site) { return known }
@@ -53,23 +54,28 @@ enum SiteTimeZone {
UserDefaults.standard.set(zone.identifier, forKey: key(site))
return zone
}
- // En mer, loin de tout : le fuseau « nautique » de la longitude vaut mieux que celui de l'iPhone.
+ // At sea, far from everything: the "nautical" time zone of the longitude beats the one of the iPhone.
return TimeZone(secondsFromGMT: Int((longitude / 15).rounded()) * 3600) ?? .current
}
}
enum DivePhotoFinder {
- /// Vrai quand l'heure de la plongée n'était pas écrite sur le carnet papier : elle est alors supposée.
- static func timeIsGuessed(_ dive: Dive) -> Bool { dive.notes.contains("Heure non écrite sur la fiche") }
+ /// True when the time of the dive was not written in the paper logbook: it is then a guess.
+ ///
+ /// The marker is DATA, not interface text: it was written into the notes of existing logbooks in French, so
+ /// the French literal must stay as is. The English marker is accepted as well.
+ static func timeIsGuessed(_ dive: Dive) -> Bool {
+ dive.notes.contains("Heure non écrite sur la fiche") || dive.notes.contains("Time not written on the log page")
+ }
- /// Instant absolu d'une heure « naïve » du carnet, dans le fuseau du lieu.
+ /// Absolute instant of a "naive" logbook time, in the time zone of the site.
static func absolute(_ when: Int, in zone: TimeZone) -> Date {
let naive = Date(timeIntervalSince1970: TimeInterval(when))
return naive.addingTimeInterval(-TimeInterval(zone.secondsFromGMT(for: naive)))
}
- /// Fenêtre où chercher les photos : la plongée avec une marge (20 min avant, 30 min après), ou la journée
- /// entière du lieu quand l'heure n'est pas connue.
+ /// Window in which to look for photos: the dive with a margin (20 min before, 30 min after), or the whole
+ /// day at the site when the time is not known.
static func window(for dive: Dive, elapsed: Int, zone: TimeZone) -> DateInterval {
if timeIsGuessed(dive) {
let dayStart = dive.when - dive.when % 86_400
@@ -79,15 +85,15 @@ enum DivePhotoFinder {
return DateInterval(start: start.addingTimeInterval(-20 * 60), duration: TimeInterval(elapsed + 50 * 60))
}
- /// Ce que la photothèque contient pour une plongée.
+ /// What the photo library holds for a dive.
struct Presence: Equatable {
var photos = false
var videos = false
var any: Bool { photos || videos }
}
- /// Y a-t-il des photos, des vidéos, dans la fenêtre de la plongée ? `slack` élargit la fenêtre quand le fuseau
- /// du lieu n'est qu'estimé (à une heure près, à cause de l'heure d'été).
+ /// Are there photos or videos in the window of the dive? `slack` widens the window when the time zone of
+ /// the site is only estimated (within an hour, because of daylight saving time).
static func presence(for dive: Dive, zone: TimeZone, slack: TimeInterval = 0) -> Presence {
let window = window(for: dive, elapsed: dive.durationSeconds, zone: zone)
func exists(_ type: PHAssetMediaType) -> Bool {
@@ -100,7 +106,7 @@ enum DivePhotoFinder {
return Presence(photos: exists(.image), videos: exists(.video))
}
- /// Photos et vidéos de la fenêtre, dans l'ordre de prise de vue.
+ /// Photos and videos in the window, in the order they were taken.
static func photos(for dive: Dive, elapsed: Int, zone: TimeZone, limit: Int = 300) -> [DivePhoto] {
let window = window(for: dive, elapsed: elapsed, zone: zone)
let options = PHFetchOptions()
diff --git a/App/Model/Keychain.swift b/App/Model/Keychain.swift
@@ -1,7 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import Security
-/// Mot de passe du nuage, gardé dans le trousseau de l'appareil.
+/// Cloud password, kept in the device keychain.
enum Keychain {
private static func query(_ account: String) -> [String: Any] {
[kSecClass as String: kSecClassGenericPassword,
diff --git a/App/Model/Units.swift b/App/Model/Units.swift
@@ -1,7 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import SubsurfaceLog
-/// Affichage des grandeurs : le carnet est toujours en métrique, la conversion ne se fait qu'à l'écran.
+/// Display of quantities: the logbook is always metric, conversion only happens on screen.
struct Units: Equatable {
var imperial = false
@@ -27,17 +28,17 @@ struct Units: Equatable {
}
func volume(_ liters: Double) -> String { "\(number(liters, 1)) L" }
func sac(_ litersPerMinute: Double) -> String {
- imperial ? "\(number(litersPerMinute * 0.0353147, 2)) pi³/min" : "\(number(litersPerMinute, 1)) L/min"
+ imperial ? "\(number(litersPerMinute * 0.0353147, 2)) \(String(localized: "cu ft/min"))" : "\(number(litersPerMinute, 1)) L/min"
}
- /// « 45 min », « 1 h 05 »
+ /// "45 min", "1 h 05"
static func duration(_ seconds: Int) -> String {
let minutes = Int((Double(seconds) / 60).rounded())
if minutes < 60 { return "\(minutes) min" }
return "\(minutes / 60) h " + String(format: "%02d", minutes % 60)
}
- /// « 12:34 » pour le curseur du profil.
+ /// "12:34" for the profile cursor.
static func clock(_ seconds: Int) -> String { "\(seconds / 60):" + String(format: "%02d", seconds % 60) }
static func totalTime(_ seconds: Int) -> String {
@@ -47,7 +48,7 @@ struct Units: Equatable {
}
}
-/// Les heures du carnet sont locales et « naïves » : on les affiche telles quelles, sans fuseau.
+/// Logbook times are local and "naive": they are shown as they are, without a time zone.
enum DiveDate {
private static let utc = TimeZone(identifier: "UTC")!
@@ -77,7 +78,7 @@ enum DiveDate {
return String(format: "%04d-%02d", c.year ?? 0, c.month ?? 0)
}
- /// Date choisie dans un sélecteur (fuseau de l'appareil) → heure naïve du carnet, secondes à zéro.
+ /// Date chosen in a picker (device time zone) → naive logbook time, seconds set to zero.
static func naive(from date: Date) -> Int {
let local = Int(date.timeIntervalSince1970) + TimeZone.current.secondsFromGMT(for: date)
return local - local % 60
diff --git a/App/Views/Components.swift b/App/Views/Components.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SwiftUI
struct Stars: View {
@@ -10,13 +11,13 @@ struct Stars: View {
}
}
.font(.caption)
- .accessibilityLabel("\(value) sur 5")
+ .accessibilityLabel("\(value) of 5")
}
}
-/// Note sur 5 ; toucher l'étoile déjà choisie remet à zéro.
+/// Rating out of 5; tapping the star already selected resets it to zero.
struct StarPicker: View {
- let title: String
+ let title: LocalizedStringKey
@Binding var value: Int
var body: some View {
@@ -29,7 +30,7 @@ struct StarPicker: View {
.font(.title3)
.foregroundStyle(index <= value ? Color.yellow : Color.secondary.opacity(0.5))
.onTapGesture { value = value == index ? 0 : index }
- .accessibilityLabel("\(index) sur 5")
+ .accessibilityLabel("\(index) of 5")
.accessibilityAddTraits(.isButton)
}
}
@@ -38,7 +39,7 @@ struct StarPicker: View {
}
struct Figure: View {
- let title: String
+ let title: LocalizedStringKey
let value: String
var icon: String?
diff --git a/App/Views/DiveDetailView.swift b/App/Views/DiveDetailView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import MapKit
import SubsurfaceLog
import SwiftUI
@@ -22,8 +23,8 @@ struct DiveDetailView: View {
if let dive = model.dive(id: diveID) {
content(dive)
} else {
- ContentUnavailableView("Plongée introuvable", systemImage: "questionmark.circle",
- description: Text("Elle a été supprimée ou renumérotée depuis un autre appareil."))
+ ContentUnavailableView("Dive not found", systemImage: "questionmark.circle",
+ description: Text("It was deleted or renumbered from another device."))
}
}
@@ -49,21 +50,21 @@ struct DiveDetailView: View {
.foregroundStyle(.secondary)
}
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 3), spacing: 8) {
- Figure(title: "Prof. max", value: units.depth(dive.maxDepth), icon: "arrow.down.to.line")
- Figure(title: "Durée", value: Units.duration(dive.durationSeconds), icon: "clock")
- if let t = dive.waterTemperature { Figure(title: "Eau", value: units.temperature(t), icon: "thermometer.medium") }
- if let mean = dive.meanDepth { Figure(title: "Prof. moy.", value: units.depth(mean), icon: "arrow.up.and.down") }
- if let sac = dive.sac { Figure(title: "Conso.", value: units.sac(sac), icon: "lungs") }
+ Figure(title: "Max depth", value: units.depth(dive.maxDepth), icon: "arrow.down.to.line")
+ Figure(title: "Duration", value: Units.duration(dive.durationSeconds), icon: "clock")
+ if let t = dive.waterTemperature { Figure(title: "Water", value: units.temperature(t), icon: "thermometer.medium") }
+ if let mean = dive.meanDepth { Figure(title: "Avg depth", value: units.depth(mean), icon: "arrow.up.and.down") }
+ if let sac = dive.sac { Figure(title: "SAC", value: units.sac(sac), icon: "lungs") }
if let t = dive.airTemperature { Figure(title: "Air", value: units.temperature(t), icon: "sun.max") }
}
.listRowSeparator(.hidden)
}
- Section("Profil") {
+ Section("Profile") {
if computers.count > 1 {
- Picker("Ordinateur", selection: $computerIndex) {
+ Picker("Computer", selection: $computerIndex) {
ForEach(computers.indices, id: \.self) { index in
- Text(computers[index].model.isEmpty ? "Ordinateur \(index + 1)" : computers[index].model).tag(index)
+ Text(computers[index].model.isEmpty ? String(localized: "Computer \(index + 1)") : computers[index].model).tag(index)
}
}
}
@@ -72,7 +73,7 @@ struct DiveDetailView: View {
photoOffsets: photos.compactMap(\.offset))
.padding(.vertical, 4)
} else if loadedFor == dive.computerBlobs.map(\.hex) {
- Text("Pas de profil enregistré pour cette plongée.")
+ Text("No profile recorded for this dive.")
.foregroundStyle(.secondary)
} else {
ProgressView().frame(maxWidth: .infinity, minHeight: 220)
@@ -82,50 +83,50 @@ struct DiveDetailView: View {
Section("Photos") {
PhotoStrip(access: photoAccess, photos: photos, loading: photosLoading,
emptyText: DivePhotoFinder.timeIsGuessed(dive)
- ? "Aucune photo ce jour-là dans la photothèque de cet iPhone."
- : "Aucune photo autour de cette plongée dans la photothèque de cet iPhone.",
+ ? String(localized: "No photos from that day in this iPhone's photo library.")
+ : String(localized: "No photos around this dive in this iPhone's photo library."),
onGranted: { Task { await loadPhotos(dive); await model.refreshPhotoPresence() } },
caption: { photoCaption($0) })
.id("photos")
}
if !dive.buddy.isEmpty || !dive.divemaster.isEmpty {
- Section("Équipe") {
- if !dive.buddy.isEmpty { LabeledContent("Binôme", value: dive.buddy) }
+ Section("Team") {
+ if !dive.buddy.isEmpty { LabeledContent("Buddy", value: dive.buddy) }
if !dive.divemaster.isEmpty { LabeledContent("Guide", value: dive.divemaster) }
}
}
if !dive.cylinders.isEmpty || !dive.weights.isEmpty || !dive.suit.isEmpty {
- Section("Équipement") {
+ Section("Equipment") {
ForEach(Array(dive.cylinders.enumerated()), id: \.offset) { _, cylinder in
VStack(alignment: .leading, spacing: 2) {
HStack {
- Text(cylinder.description.isEmpty ? "Bouteille" : cylinder.description)
+ Text(cylinder.description.isEmpty ? String(localized: "Cylinder") : cylinder.description)
Spacer()
Text(cylinder.gas.label)
.font(.callout.weight(.semibold))
.foregroundStyle(cylinder.gas.isAir ? Color.secondary : Color.green)
}
if let start = cylinder.startBar, let end = cylinder.endBar, start > end {
- Text("\(units.pressure(start)) → \(units.pressure(end))")
+ Text(verbatim: "\(units.pressure(start)) → \(units.pressure(end))")
.font(.caption)
.foregroundStyle(.secondary)
} else if let use = cylinder.use, use == "not used" {
- Text("Non utilisée").font(.caption).foregroundStyle(.secondary)
+ Text("Not used").font(.caption).foregroundStyle(.secondary)
}
}
}
- if dive.totalWeight > 0 { LabeledContent("Lest", value: units.weight(dive.totalWeight)) }
- if !dive.suit.isEmpty { LabeledContent("Combinaison", value: dive.suit) }
+ if dive.totalWeight > 0 { LabeledContent("Weights", value: units.weight(dive.totalWeight)) }
+ if !dive.suit.isEmpty { LabeledContent("Suit", value: dive.suit) }
}
}
if dive.visibility > 0 || dive.current > 0 || dive.waveSize > 0 || !dive.tags.isEmpty {
Section("Conditions") {
- if dive.visibility > 0 { LabeledContent("Visibilité") { Stars(value: dive.visibility) } }
- if dive.current > 0 { LabeledContent("Courant") { Stars(value: dive.current) } }
- if dive.waveSize > 0 { LabeledContent("Vagues") { Stars(value: dive.waveSize) } }
+ if dive.visibility > 0 { LabeledContent("Visibility") { Stars(value: dive.visibility) } }
+ if dive.current > 0 { LabeledContent("Current") { Stars(value: dive.current) } }
+ if dive.waveSize > 0 { LabeledContent("Waves") { Stars(value: dive.waveSize) } }
if !dive.tags.isEmpty { TagChips(tags: dive.tags) }
}
}
@@ -138,7 +139,7 @@ struct DiveDetailView: View {
}
if let site, let latitude = site.latitude, let longitude = site.longitude {
- Section("Lieu") {
+ Section("Site") {
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
Map(initialPosition: .region(MKCoordinateRegion(center: coordinate, latitudinalMeters: 6000, longitudinalMeters: 6000))) {
Marker(site.name, systemImage: "water.waves", coordinate: coordinate).tint(Color.accentColor)
@@ -153,20 +154,23 @@ struct DiveDetailView: View {
if computers.indices.contains(computerIndex) {
let computer = computers[computerIndex]
- Section("Ordinateur") {
+ Section("Computer") {
EmptyView().id("bottom")
- LabeledContent("Modèle", value: computer.isManual ? "Plongée saisie à la main" : (computer.model.isEmpty ? "Inconnu" : computer.model))
+ LabeledContent("Model", value: computer.isManual
+ ? String(localized: "Manually entered dive")
+ : (computer.model.isEmpty ? String(localized: "Unknown") : computer.model))
if computer.diveMode != "OC" { LabeledContent("Mode", value: computer.diveMode) }
if !computer.events.isEmpty {
- DisclosureGroup("Événements (\(computer.events.count))") {
+ DisclosureGroup("Events (\(computer.events.count))") {
ForEach(Array(computer.events.enumerated()), id: \.offset) { _, event in
- LabeledContent(Units.clock(event.time), value: event.isGasChange ? "Gaz : \(event.gas?.label ?? "changement")" : event.name)
+ let gas: String = event.gas?.label ?? String(localized: "change")
+ LabeledContent(Units.clock(event.time), value: event.isGasChange ? String(localized: "Gas: \(gas)") : event.name)
.font(.callout)
}
}
}
if !computer.extra.isEmpty {
- DisclosureGroup("Détails (\(computer.extra.count))") {
+ DisclosureGroup("Details (\(computer.extra.count))") {
ForEach(Array(computer.extra.enumerated()), id: \.offset) { _, pair in
LabeledContent(pair.key, value: pair.value).font(.callout)
}
@@ -177,27 +181,27 @@ struct DiveDetailView: View {
}
.listStyle(.insetGrouped)
.onChange(of: loadedFor) {
- // Option de capture d'écran : montrer le bas de la fiche.
+ // Screenshot option: show the bottom of the dive sheet.
if let target = LaunchOptions.value("-scroll") {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { proxy.scrollTo(target, anchor: .bottom) }
}
}
}
- .navigationTitle(dive.number > 0 ? "Plongée \(dive.number)" : "Plongée")
+ .navigationTitle(dive.number > 0 ? String(localized: "Dive \(dive.number)") : String(localized: "Dive"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .topBarTrailing) {
- Button("Modifier") { editing = true }
+ Button("Edit") { editing = true }
Menu {
- Button("Supprimer la plongée", systemImage: "trash", role: .destructive) { confirmingDelete = true }
+ Button("Delete dive", systemImage: "trash", role: .destructive) { confirmingDelete = true }
} label: {
- Label("Autres actions", systemImage: "ellipsis.circle")
+ Label("More actions", systemImage: "ellipsis.circle")
}
}
}
.sheet(isPresented: $editing) { DiveEditView(dive: dive) }
- .confirmationDialog("Supprimer cette plongée du carnet ?", isPresented: $confirmingDelete, titleVisibility: .visible) {
- Button("Supprimer", role: .destructive) {
+ .confirmationDialog("Delete this dive from the logbook?", isPresented: $confirmingDelete, titleVisibility: .visible) {
+ Button("Delete", role: .destructive) {
Task {
do {
try await model.apply(.deleteDive(when: dive.when, number: dive.number))
@@ -208,9 +212,9 @@ struct DiveDetailView: View {
}
}
} message: {
- Text("La suppression sera envoyée au nuage Subsurface à la prochaine synchronisation.")
+ Text("The deletion will be sent to the Subsurface cloud at the next sync.")
}
- .alert("Action impossible", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
+ .alert("Action failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
Button("OK", role: .cancel) {}
} message: {
Text(error ?? "")
@@ -218,14 +222,14 @@ struct DiveDetailView: View {
.task(id: dive.computerBlobs.map(\.hex)) {
let loaded = await model.profile(of: dive)
computers = loaded
- // Par défaut, l'ordinateur qui a le profil le plus détaillé.
+ // By default, the computer with the most detailed profile.
computerIndex = loaded.indices.max(by: { loaded[$0].samples.count < loaded[$1].samples.count }) ?? 0
loadedFor = dive.computerBlobs.map(\.hex)
await loadPhotos(dive)
}
}
- /// Durée écoulée entre la mise à l'eau et la sortie (plus longue que le temps sous l'eau pour une plongée réunie).
+ /// Time elapsed between entering and leaving the water (longer than the time underwater for a merged dive).
private func elapsed(_ dive: Dive) -> Int {
max(dive.durationSeconds, computers.compactMap { $0.samples.last?.time }.max() ?? 0)
}
@@ -239,7 +243,7 @@ struct DiveDetailView: View {
photosLoading = false
}
- /// « 10 h 36 · 12,4 m » pour une photo prise sous l'eau, l'heure seule sinon.
+ /// "10:36 · 12.4 m" for a photo taken underwater, the time alone otherwise.
private func photoCaption(_ photo: DivePhoto) -> String {
var parts = [String]()
if let taken = photo.asset.creationDate {
@@ -248,7 +252,8 @@ struct DiveDetailView: View {
if let offset = photo.offset, computers.indices.contains(computerIndex),
let sample = ProfileData(computer: computers[computerIndex], units: model.units).sample(at: Double(offset) / 60) {
parts.append(model.units.depth(sample.depth))
- parts.append("à \(Units.clock(offset)) de plongée")
+ let clock: String = Units.clock(offset)
+ parts.append(String(localized: "\(clock) into the dive"))
}
return parts.joined(separator: " · ")
}
diff --git a/App/Views/DiveEditView.swift b/App/Views/DiveEditView.swift
@@ -1,7 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SubsurfaceLog
import SwiftUI
-/// Modification des champs « carnet » d'une plongée. Seuls les champs réellement changés sont envoyés.
+/// Edits the "logbook" fields of a dive. Only the fields that actually changed are sent.
struct DiveEditView: View {
@Environment(AppModel.self) private var model
@Environment(\.dismiss) private var dismiss
@@ -26,18 +27,18 @@ struct DiveEditView: View {
NavigationLink {
SitePicker(selection: $siteUUID)
} label: {
- LabeledContent("Lieu", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? "Aucun")
+ LabeledContent("Site", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? String(localized: "None"))
}
}
- Section("Équipe") {
- TextField("Binôme", text: $buddy)
+ Section("Team") {
+ TextField("Buddy", text: $buddy)
TextField("Guide", text: $divemaster)
}
Section("Conditions") {
- StarPicker(title: "Évaluation", value: $rating)
- StarPicker(title: "Visibilité", value: $visibility)
- TextField("Combinaison", text: $suit)
- TextField("Étiquettes, séparées par des virgules", text: $tags)
+ StarPicker(title: "Rating", value: $rating)
+ StarPicker(title: "Visibility", value: $visibility)
+ TextField("Suit", text: $suit)
+ TextField("Tags, separated by commas", text: $tags)
.textInputAutocapitalization(.never)
}
Section("Notes") {
@@ -48,12 +49,12 @@ struct DiveEditView: View {
Section { Text(error).foregroundStyle(.red) }
}
}
- .navigationTitle(dive.number > 0 ? "Plongée \(dive.number)" : "Plongée")
+ .navigationTitle(dive.number > 0 ? String(localized: "Dive \(dive.number)") : String(localized: "Dive"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
- Button("Enregistrer", action: save).disabled(saving || changes.isEmpty)
+ Button("Save", action: save).disabled(saving || changes.isEmpty)
}
}
.onAppear {
@@ -103,7 +104,7 @@ struct DiveEditView: View {
}
}
-/// Choix d'un lieu existant, ou création d'un lieu par son nom.
+/// Picks an existing site, or creates a site from its name.
struct SitePicker: View {
@Environment(AppModel.self) private var model
@Environment(\.dismiss) private var dismiss
@@ -119,10 +120,10 @@ struct SitePicker: View {
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
List {
Section {
- Button { creating = true } label: { Label("Nouveau lieu…", systemImage: "plus.circle") }
+ Button { creating = true } label: { Label("New site…", systemImage: "plus.circle") }
Button { selection = nil; dismiss() } label: {
HStack {
- Text("Aucun lieu").foregroundStyle(Color.primary)
+ Text("No site").foregroundStyle(Color.primary)
Spacer()
if selection == nil { Image(systemName: "checkmark") }
}
@@ -143,16 +144,16 @@ struct SitePicker: View {
}
}
}
- .navigationTitle("Lieu")
- .searchable(text: $search, prompt: "Chercher un lieu")
- .alert("Nouveau lieu", isPresented: $creating) {
- TextField("Nom du lieu", text: $newName)
- Button("Annuler", role: .cancel) { newName = "" }
- Button("Créer") { create() }
+ .navigationTitle("Site")
+ .searchable(text: $search, prompt: "Search for a site")
+ .alert("New site", isPresented: $creating) {
+ TextField("Site name", text: $newName)
+ Button("Cancel", role: .cancel) { newName = "" }
+ Button("Create") { create() }
} message: {
- Text("La position pourra être ajoutée plus tard dans Subsurface.")
+ Text("The location can be added later in Subsurface.")
}
- .alert("Action impossible", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
+ .alert("Action failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
Button("OK", role: .cancel) {}
} message: {
Text(error ?? "")
@@ -181,7 +182,7 @@ struct SitePicker: View {
}
}
-/// Saisie d'une plongée sans ordinateur.
+/// Manual entry of a dive made without a computer.
struct NewDiveView: View {
@Environment(AppModel.self) private var model
@Environment(\.dismiss) private var dismiss
@@ -201,16 +202,16 @@ struct NewDiveView: View {
NavigationStack {
Form {
Section {
- DatePicker("Début", selection: $date, in: ...Date.now)
+ DatePicker("Start", selection: $date, in: ...Date.now)
Stepper(value: $minutes, in: 1...600) {
- LabeledContent("Durée", value: "\(minutes) min")
+ LabeledContent("Duration", value: String(localized: "\(minutes) min"))
}
- LabeledContent("Profondeur max (\(model.units.depthUnit))") {
+ LabeledContent("Max depth (\(model.units.depthUnit))") {
TextField("0", text: $depthText)
.keyboardType(.decimalPad)
.multilineTextAlignment(.trailing)
}
- LabeledContent("Eau (\(model.units.temperatureUnit))") {
+ LabeledContent("Water (\(model.units.temperatureUnit))") {
TextField("–", text: $temperatureText)
.keyboardType(.numbersAndPunctuation)
.multilineTextAlignment(.trailing)
@@ -220,10 +221,10 @@ struct NewDiveView: View {
NavigationLink {
SitePicker(selection: $siteUUID)
} label: {
- LabeledContent("Lieu", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? "Aucun")
+ LabeledContent("Site", value: siteUUID.flatMap { model.logbook.sites[$0]?.name } ?? String(localized: "None"))
}
- TextField("Binôme", text: $buddy)
- StarPicker(title: "Évaluation", value: $rating)
+ TextField("Buddy", text: $buddy)
+ StarPicker(title: "Rating", value: $rating)
}
Section("Notes") {
TextEditor(text: $notes).frame(minHeight: 100)
@@ -232,12 +233,12 @@ struct NewDiveView: View {
Section { Text(error).foregroundStyle(.red) }
}
}
- .navigationTitle("Nouvelle plongée")
+ .navigationTitle("New dive")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
- Button("Ajouter", action: save).disabled(saving || depth == nil)
+ Button("Add", action: save).disabled(saving || depth == nil)
}
}
}
diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SubsurfaceLog
import SwiftUI
@@ -33,17 +34,19 @@ struct DiveListView: View {
.overlay {
if model.logbook.dives.isEmpty {
ContentUnavailableView {
- Label("Carnet vide", systemImage: "water.waves")
+ Label("Empty logbook", systemImage: "water.waves")
} description: {
- Text(model.syncState == .syncing ? "Téléchargement du carnet…" : "Ajoutez une plongée avec le bouton +, ou tirez pour synchroniser.")
+ Text(model.syncState == .syncing
+ ? String(localized: "Downloading the logbook…")
+ : String(localized: "Add a dive with the + button, or pull to sync."))
}
} else if sections.isEmpty {
ContentUnavailableView.search(text: search)
}
}
- .navigationTitle("Plongées")
+ .navigationTitle("Dives")
.navigationDestination(for: String.self) { DiveDetailView(diveID: $0) }
- .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Lieu, binôme, étiquette, notes")
+ .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Site, buddy, tag, notes")
.refreshable { await model.sync() }
.toolbar {
ToolbarItem(placement: .topBarLeading) {
@@ -51,10 +54,10 @@ struct DiveListView: View {
}
ToolbarItem(placement: .topBarTrailing) {
Menu {
- Button { adding = true } label: { Label("Nouvelle plongée", systemImage: "square.and.pencil") }
- Button { importing = true } label: { Label("Importer un fichier…", systemImage: "square.and.arrow.down") }
+ Button { adding = true } label: { Label("New dive", systemImage: "square.and.pencil") }
+ Button { importing = true } label: { Label("Import a file…", systemImage: "square.and.arrow.down") }
} label: {
- Label("Ajouter", systemImage: "plus")
+ Label("Add", systemImage: "plus")
}
}
}
@@ -62,7 +65,7 @@ struct DiveListView: View {
.task(id: model.logbook.dives.count) { await model.refreshPhotoPresence() }
.modifier(FileImport(isPresented: $importing))
.onChange(of: model.logbook.dives.count) {
- // Option de capture : ouvrir une plongée qui vient d'être importée.
+ // Screenshot option: open a dive that has just been imported.
if path.isEmpty, let number = LaunchOptions.value("-showDive").flatMap({ Int($0) }),
let dive = model.logbook.dives.first(where: { $0.number == number }) {
path = [dive.id]
@@ -81,18 +84,18 @@ struct DiveListView: View {
}
private func countLabel(_ count: Int) -> String {
- count == 1 ? "1 plongée" : "\(count) plongées"
+ count == 1 ? String(localized: "1 dive") : String(localized: "\(count) dives")
}
}
-/// État de la synchronisation, en tête de liste quand il y a quelque chose à dire.
+/// Sync status, shown at the top of the list when there is something to say.
struct SyncBanner: View {
@Environment(AppModel.self) private var model
var body: some View {
if model.isDemo {
Section {
- Label("Carnet de démonstration : rien n'est envoyé.", systemImage: "sparkles")
+ Label("Demo logbook: nothing is uploaded.", systemImage: "sparkles")
.font(.footnote)
.foregroundStyle(.secondary)
}
@@ -116,7 +119,7 @@ struct SyncBanner: View {
}
private var pendingLabel: some View {
- Label(model.pending.count == 1 ? "1 modification à envoyer" : "\(model.pending.count) modifications à envoyer",
+ Label(model.pending.count == 1 ? String(localized: "1 change to upload") : String(localized: "\(model.pending.count) changes to upload"),
systemImage: "arrow.up.circle")
.font(.footnote)
.foregroundStyle(.secondary)
@@ -146,11 +149,15 @@ struct DiveRow: View {
}
.font(.caption2)
.foregroundStyle(.pink)
- .accessibilityLabel(presence.photos && presence.videos ? "Avec photos et vidéos" : (presence.videos ? "Avec vidéos" : "Avec photos"))
+ .accessibilityLabel(presence.photos && presence.videos
+ ? String(localized: "With photos and videos")
+ : (presence.videos ? String(localized: "With videos") : String(localized: "With photos")))
}
}
HStack(spacing: 6) {
- Text("\(DiveDate.short(dive)) · \(DiveDate.time(dive))")
+ Text(verbatim: "\(DiveDate.short(dive)) · \(DiveDate.time(dive))")
+ .lineLimit(1)
+ .fixedSize()
if dive.rating > 0 {
Text(String(repeating: "★", count: dive.rating))
.foregroundStyle(.yellow)
diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift
@@ -1,15 +1,16 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SubsurfaceLog
import SwiftUI
import UniformTypeIdentifiers
-/// Choix d'un fichier à importer, puis aperçu des plongées trouvées avant de les ajouter au carnet.
+/// Picks a file to import, then previews the dives found before adding them to the logbook.
struct FileImport: ViewModifier {
@Environment(AppModel.self) private var model
@Binding var isPresented: Bool
@State private var batch: ImportBatch?
@State private var error: String?
- /// L'option de lancement `-importFile chemin` (captures d'écran) n'ouvre l'aperçu qu'une fois.
+ /// The `-importFile path` launch option (screenshots) opens the preview only once.
@MainActor private static var launchOptionUsed = false
func body(content: Content) -> some View {
@@ -23,7 +24,7 @@ struct FileImport: ViewModifier {
}
}
.sheet(item: $batch) { ImportSheet(batch: $0) }
- .alert("Import impossible", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
+ .alert("Import failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
Button("OK", role: .cancel) {}
} message: {
Text(error ?? "")
@@ -79,23 +80,23 @@ struct ImportSheet: View {
} header: {
Text(batch.name)
} footer: {
- Text("Les plongées choisies sont ajoutées au carnet avec leur profil complet, puis envoyées au nuage Subsurface. Celles que le carnet contient déjà (même heure de début) sont laissées de côté.")
+ Text("The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. Dives already in the logbook (same start time) are skipped.")
}
if let error {
Section { Text(error).foregroundStyle(.red) }
}
}
- .navigationTitle(selected.count == 1 ? "1 plongée choisie" : "\(selected.count) plongées choisies")
+ .navigationTitle(selected.count == 1 ? String(localized: "1 dive selected") : String(localized: "\(selected.count) dives selected"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
- Button("Importer", action: run)
+ Button("Import", action: run)
.disabled(selected.isEmpty || working)
}
ToolbarItem(placement: .bottomBar) {
if !fresh.isEmpty {
- Button(selected.count == fresh.count ? "Tout décocher" : "Tout cocher") {
+ Button(selected.count == fresh.count ? String(localized: "Deselect all") : String(localized: "Select all")) {
selected = selected.count == fresh.count ? [] : Set(fresh.map(\.id))
}
.disabled(working)
@@ -105,7 +106,7 @@ struct ImportSheet: View {
.onAppear {
guard !loaded else { return }
loaded = true
- // Les trempettes de moins de deux minutes (ordinateur mouillé en surface) ne sont pas cochées d'office.
+ // Dips shorter than two minutes (computer got wet at the surface) are not selected by default.
selected = Set(fresh.filter { $0.dive.durationSeconds >= 120 }.map(\.id))
if LaunchOptions.flag("-importAll") { run() }
}
@@ -121,10 +122,10 @@ struct ImportSheet: View {
.font(.title3)
.foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.accentColor)
VStack(alignment: .leading, spacing: 3) {
- Text(dive.site.isEmpty ? "Lieu inconnu" : dive.site)
+ Text(dive.site.isEmpty ? String(localized: "Unknown site") : dive.site)
.font(.body.weight(.medium))
.foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.primary)
- Text(candidate.alreadyInLog ? "\(date) · déjà dans le carnet" : date)
+ Text(candidate.alreadyInLog ? String(localized: "\(date) · already in the logbook") : date)
.font(.caption)
.foregroundStyle(.secondary)
}
@@ -158,11 +159,11 @@ struct ImportSheet: View {
}
}
-/// Création d'un compte du nuage Subsurface : courriel et mot de passe, puis code reçu par courriel.
+/// Creates a Subsurface cloud account: email and password, then the code received by email.
struct CreateAccountView: View {
@Environment(AppModel.self) private var model
@Environment(\.dismiss) private var dismiss
- /// Appelé quand le compte est prêt, pour enchaîner sur la connexion.
+ /// Called once the account is ready, to carry on with signing in.
let onReady: (String, String) -> Void
@State private var email = ""
@@ -177,32 +178,32 @@ struct CreateAccountView: View {
NavigationStack {
Form {
Section {
- TextField("Courriel", text: $email)
+ TextField("Email", text: $email)
.textContentType(.username)
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.disabled(waitingForPIN)
- SecureField("Mot de passe", text: $password)
+ SecureField("Password", text: $password)
.textContentType(.newPassword)
.disabled(waitingForPIN)
if !waitingForPIN {
- SecureField("Mot de passe, encore", text: $confirmation)
+ SecureField("Password, again", text: $confirmation)
.textContentType(.newPassword)
}
} footer: {
- Text("Le compte est créé dans le nuage Subsurface (cloud.subsurface-divelog.org), le service gratuit du projet Subsurface. Il servira aussi dans Subsurface sur ordinateur. Mot de passe : lettres sans accent, chiffres et @ . + _ - seulement.")
+ Text("The account is created in the Subsurface cloud (cloud.subsurface-divelog.org), the free service of the Subsurface project. It also works in Subsurface on a computer. Password: unaccented letters, digits and @ . + _ - only.")
}
if waitingForPIN {
Section {
- TextField("Code reçu par courriel", text: $pin)
+ TextField("Code received by email", text: $pin)
.keyboardType(.numbersAndPunctuation)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
} header: {
- Text("Vérification")
+ Text("Verification")
} footer: {
- Text("Le nuage Subsurface vient d'envoyer un code à \(email). Il peut mettre quelques minutes à arriver ; regardez aussi dans les indésirables.")
+ Text("The Subsurface cloud just sent a code to \(email). It may take a few minutes to arrive; check your junk folder too.")
}
}
if let error {
@@ -212,16 +213,16 @@ struct CreateAccountView: View {
Button(action: submit) {
HStack {
if busy { ProgressView() }
- Text(waitingForPIN ? "Valider le code" : "Créer le compte")
+ Text(waitingForPIN ? String(localized: "Verify code") : String(localized: "Create account"))
}
}
.disabled(busy || !ready)
}
}
- .navigationTitle("Nouveau compte")
+ .navigationTitle("New account")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
}
}
}
@@ -247,9 +248,9 @@ struct CreateAccountView: View {
waitingForPIN = true
case .invalidPIN:
waitingForPIN = true
- error = "Ce code n'est pas le bon."
+ error = String(localized: "That code is incorrect.")
case .rejected(let message):
- error = "Le nuage Subsurface a refusé : \(message)"
+ error = String(localized: "The Subsurface cloud refused: \(message)")
}
} catch {
self.error = AppModel.describe(error)
diff --git a/App/Views/LoginView.swift b/App/Views/LoginView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SwiftUI
struct LoginView: View {
@@ -11,6 +12,10 @@ struct LoginView: View {
private enum Field { case email, password }
+ private var disclaimer: String {
+ String(localized: "The account is your Subsurface cloud account (cloud.subsurface-divelog.org), the same one you use in Subsurface. Your credentials are sent only to that service, and the password stays in the iPhone keychain.\n\n\(Brand.name) is an independent app, not affiliated with the Subsurface team.")
+ }
+
var body: some View {
NavigationStack {
ScrollView {
@@ -23,13 +28,13 @@ struct LoginView: View {
.padding(.top, 32)
Text(Brand.name)
.font(.largeTitle.bold())
- Text("Votre carnet de plongée Subsurface, sur iPhone.")
+ Text("Your Subsurface dive log, on iPhone.")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
VStack(spacing: 12) {
- TextField("Courriel du compte Subsurface", text: $email)
+ TextField("Subsurface account email", text: $email)
.textContentType(.username)
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
@@ -38,7 +43,7 @@ struct LoginView: View {
.submitLabel(.next)
.onSubmit { focus = .password }
Divider()
- SecureField("Mot de passe", text: $password)
+ SecureField("Password", text: $password)
.textContentType(.password)
.focused($focus, equals: .password)
.submitLabel(.go)
@@ -57,7 +62,7 @@ struct LoginView: View {
Button(action: signIn) {
HStack {
if busy { ProgressView().tint(.white) }
- Text(busy ? "Connexion…" : "Se connecter")
+ Text(busy ? String(localized: "Signing in…") : String(localized: "Sign in"))
.fontWeight(.semibold)
}
.frame(maxWidth: .infinity)
@@ -67,19 +72,19 @@ struct LoginView: View {
.disabled(busy || email.isEmpty || password.isEmpty)
HStack(spacing: 24) {
- Button("Créer un compte") { creating = true }
+ Button("Create an account") { creating = true }
.disabled(busy)
- Link("Mot de passe oublié ?", destination: URL(string: "https://cloud.subsurface-divelog.org/passwordreset")!)
+ Link("Forgot password?", destination: URL(string: "https://cloud.subsurface-divelog.org/passwordreset")!)
}
.font(.subheadline)
- Button("Essayer avec un carnet de démonstration") {
+ Button("Try a demo logbook") {
Task { await model.startDemo() }
}
.font(.subheadline)
.disabled(busy)
- Text("Le compte est celui du nuage Subsurface (cloud.subsurface-divelog.org), le même que dans Subsurface. Vos identifiants ne sont envoyés qu'à ce service et le mot de passe reste dans le trousseau de l'iPhone.\n\n\(Brand.name) est une application indépendante, sans lien avec l'équipe de Subsurface.")
+ Text(disclaimer)
.font(.footnote)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
diff --git a/App/Views/PhotoViews.swift b/App/Views/PhotoViews.swift
@@ -1,9 +1,10 @@
+// SPDX-License-Identifier: GPL-2.0-only
import AVKit
import Photos
import SubsurfaceLog
import SwiftUI
-/// Vignette carrée d'une photo ou d'une vidéo de la photothèque.
+/// Square thumbnail of a photo or video from the photo library.
struct PhotoThumbnail: View {
let asset: PHAsset
var side: CGFloat = 96
@@ -45,7 +46,7 @@ struct PhotoThumbnail: View {
}
}
-/// Une photo en grand, ou une vidéo qu'on peut lire.
+/// A full-size photo, or a playable video.
private struct FullPhoto: View {
let asset: PHAsset
@State private var image: UIImage?
@@ -83,7 +84,7 @@ private struct FullPhoto: View {
}
}
-/// Défilement plein écran des photos d'une plongée ; la légende donne l'heure, et la profondeur quand on la connaît.
+/// Full-screen pager over a dive's photos; the caption gives the time, and the depth when it is known.
struct PhotoViewer: View {
@Environment(\.dismiss) private var dismiss
let photos: [DivePhoto]
@@ -111,18 +112,18 @@ struct PhotoViewer: View {
.padding(.bottom, 12)
}
}
- .navigationTitle("\(index + 1) sur \(photos.count)")
+ .navigationTitle("\(index + 1) of \(photos.count)")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.black, for: .navigationBar)
.toolbarColorScheme(.dark, for: .navigationBar)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }
+ ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } }
}
}
}
}
-/// Contenu d'une section « Photos » : demande d'accès, état vide, ou bande de vignettes.
+/// Content of a "Photos" section: access request, empty state, or a strip of thumbnails.
struct PhotoStrip: View {
let access: PhotoAccess
let photos: [DivePhoto]
@@ -140,7 +141,7 @@ struct PhotoStrip: View {
switch access.status {
case .notDetermined:
VStack(alignment: .leading, spacing: 8) {
- Text("Sub Rascasse peut montrer ici les photos et vidéos prises pendant la plongée. Elles restent sur l'iPhone : rien n'est envoyé.")
+ Text("Sub Rascasse can show the photos and videos taken during the dive here. They stay on your iPhone: nothing is uploaded.")
.font(.footnote)
.foregroundStyle(.secondary)
Button {
@@ -149,16 +150,16 @@ struct PhotoStrip: View {
if access.granted { onGranted() }
}
} label: {
- Label("Autoriser l'accès aux photos", systemImage: "photo.on.rectangle")
+ Label("Allow photo access", systemImage: "photo.on.rectangle")
}
}
case .denied, .restricted:
VStack(alignment: .leading, spacing: 8) {
- Text("L'accès aux photos est refusé. Il se rétablit dans Réglages → Confidentialité → Photos.")
+ Text("Photo access is denied. You can turn it back on in Settings → Privacy → Photos.")
.font(.footnote)
.foregroundStyle(.secondary)
if let url = URL(string: UIApplication.openSettingsURLString) {
- Link("Ouvrir les réglages", destination: url)
+ Link("Open Settings", destination: url)
}
}
default:
@@ -180,7 +181,7 @@ struct PhotoStrip: View {
.background(Color.accentColor, in: Circle())
.foregroundStyle(.white)
.padding(4)
- .accessibilityLabel("Prise pendant la plongée")
+ .accessibilityLabel("Taken during the dive")
}
}
.onTapGesture { viewing = ViewedPhoto(id: position) }
@@ -199,7 +200,7 @@ struct PhotoStrip: View {
private var summary: String {
let during = photos.filter { $0.offset != nil }.count
- let total = photos.count == 1 ? "1 photo ou vidéo" : "\(photos.count) photos et vidéos"
- return during > 0 ? "\(total), dont \(during) sous l'eau (marquées d'une vague)" : total
+ let total = photos.count == 1 ? String(localized: "1 photo or video") : String(localized: "\(photos.count) photos and videos")
+ return during > 0 ? String(localized: "\(total), \(during) underwater (marked with a wave)") : total
}
}
diff --git a/App/Views/ProfileChart.swift b/App/Views/ProfileChart.swift
@@ -1,8 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Charts
import SubsurfaceLog
import SwiftUI
-/// Données du profil préparées pour l'affichage (unités de l'usager, échantillons allégés).
+/// Profile data prepared for display (the user's units, downsampled samples).
struct ProfileData {
struct Point: Identifiable {
let id: Int
@@ -31,7 +32,7 @@ struct ProfileData {
var markers: [Marker] = []
var maxMinute = 1.0
var samples: [Sample] = []
- /// Dernière pression connue de chaque capteur à chaque échantillon, pour la lecture au curseur.
+ /// Last known pressure of each sensor at each sample, for the readout under the cursor.
var pressureAt: [[Int: Double]] = []
init(computer: DiveComputer, units: Units) {
@@ -39,7 +40,7 @@ struct ProfileData {
guard let last = samples.last else { return }
maxMinute = max(Double(last.time) / 60, 1)
- // Au plus ~700 points : on garde le plus profond de chaque tranche pour ne pas raboter les pointes.
+ // At most ~700 points: keep the deepest of each bucket so the peaks are not shaved off.
let bucket = max(1, samples.count / 700)
var index = 0
while index < samples.count {
@@ -71,13 +72,13 @@ struct ProfileData {
inCeiling = stop > 0
}
}
- pressure = bySensor.keys.sorted().map { Series(id: "Bouteille \($0 + 1)", points: bySensor[$0] ?? []) }
+ pressure = bySensor.keys.sorted().map { Series(id: "Cylinder \($0 + 1)", points: bySensor[$0] ?? []) }
for (i, event) in computer.events.enumerated() {
let minute = Double(event.time) / 60
let depthThere = sample(at: minute).map { units.depthValue($0.depth) } ?? 0
var label: String?
- if event.isGasChange, event.time > 30 { label = event.gas?.label ?? "Gaz" }
+ if event.isGasChange, event.time > 30 { label = event.gas?.label ?? String(localized: "Gas") }
if event.isGasChange, event.time <= 30 { continue }
markers.append(Marker(id: i, minute: minute, depth: depthThere, label: label, name: event.name, seconds: event.time))
}
@@ -101,7 +102,7 @@ struct ProfileData {
struct ProfileChart: View {
let data: ProfileData
let units: Units
- /// Instants (secondes depuis la mise à l'eau) où une photo a été prise.
+ /// Times (seconds since entering the water) at which a photo was taken.
var photoOffsets: [Int] = []
@State private var selection: Double?
@@ -113,38 +114,39 @@ struct ProfileChart: View {
depthChart
.frame(height: 220)
if data.temperature.count > 1 {
- smallChart(title: "Température", unit: units.temperatureUnit, series: [.init(id: "Température", points: data.temperature)], color: .orange)
+ smallChart(title: String(localized: "Temperature"), unit: units.temperatureUnit, series: [.init(id: "Temperature", points: data.temperature)], color: .orange)
}
if data.pressure.contains(where: { $0.points.count > 1 }) {
- smallChart(title: "Pression des bouteilles", unit: units.pressureUnit, series: data.pressure, color: .green)
+ smallChart(title: String(localized: "Cylinder pressure"), unit: units.pressureUnit, series: data.pressure, color: .green)
}
}
}
- /// Valeurs sous le doigt ; sans sélection, une invitation discrète.
+ /// Values under the finger; with no selection, a discreet hint.
@ViewBuilder private var readout: some View {
if let minute = selection, let index = data.sampleIndex(at: minute) {
let sample = data.samples[index]
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 14) {
- value("Temps", Units.clock(sample.time))
- value("Profondeur", units.depth(sample.depth))
- if let t = sample.temperature { value("Eau", units.temperature(t)) }
+ value(String(localized: "Time"), Units.clock(sample.time))
+ value(String(localized: "Depth"), units.depth(sample.depth))
+ if let t = sample.temperature { value(String(localized: "Water"), units.temperature(t)) }
ForEach(data.pressureAt[index].keys.sorted(), id: \.self) { sensor in
- value(data.pressureAt[index].count > 1 ? "Bout. \(sensor + 1)" : "Pression", units.pressure(data.pressureAt[index][sensor] ?? 0))
+ value(data.pressureAt[index].count > 1 ? String(localized: "Cyl. \(sensor + 1)") : String(localized: "Pressure"),
+ units.pressure(data.pressureAt[index][sensor] ?? 0))
}
if sample.inDeco, let stop = sample.stopDepth, stop > 0 {
- value("Palier", units.depth(stop), color: .red)
- if let tts = sample.tts { value("Surface dans", Units.duration(tts)) }
+ value(String(localized: "Stop"), units.depth(stop), color: .red)
+ if let tts = sample.tts { value(String(localized: "Surface in"), Units.duration(tts)) }
} else if let ndl = sample.ndl {
- value("Sans palier", ndl >= 99 * 60 ? "99+ min" : Units.duration(ndl))
+ value(String(localized: "No stop"), ndl >= 99 * 60 ? String(localized: "99+ min") : Units.duration(ndl))
}
- if let cns = sample.cns, cns > 0 { value("CNS", "\(cns) %") }
+ if let cns = sample.cns, cns > 0 { value(String(localized: "CNS"), String(localized: "\(cns)%")) }
}
}
.frame(height: 36)
} else {
- Text("Glissez le doigt sur le profil pour lire les valeurs.")
+ Text("Drag your finger across the profile to read the values.")
.font(.caption)
.foregroundStyle(.secondary)
.frame(height: 36, alignment: .leading)
@@ -161,25 +163,25 @@ struct ProfileChart: View {
private var depthChart: some View {
Chart {
ForEach(data.depth) { point in
- AreaMark(x: .value("Temps", point.minute), y: .value("Profondeur", point.value),
- series: .value("Série", "Profondeur"), stacking: .unstacked)
+ AreaMark(x: .value("Time", point.minute), y: .value("Depth", point.value),
+ series: .value("Series", "Depth"), stacking: .unstacked)
.foregroundStyle(LinearGradient(colors: [Color.accentColor.opacity(0.12), Color.accentColor.opacity(0.5)],
startPoint: .top, endPoint: .bottom))
.interpolationMethod(.monotone)
- LineMark(x: .value("Temps", point.minute), y: .value("Profondeur", point.value),
- series: .value("Série", "Profondeur"))
+ LineMark(x: .value("Time", point.minute), y: .value("Depth", point.value),
+ series: .value("Series", "Depth"))
.foregroundStyle(Color.accentColor)
.lineStyle(StrokeStyle(lineWidth: 2))
.interpolationMethod(.monotone)
}
ForEach(data.ceiling) { point in
- AreaMark(x: .value("Temps", point.minute), yStart: .value("Surface", 0.0), yEnd: .value("Plafond", point.value),
- series: .value("Série", "Plafond"))
+ AreaMark(x: .value("Time", point.minute), yStart: .value("Surface", 0.0), yEnd: .value("Ceiling", point.value),
+ series: .value("Series", "Ceiling"))
.foregroundStyle(Color.red.opacity(0.3))
.interpolationMethod(.stepEnd)
}
ForEach(data.markers) { marker in
- PointMark(x: .value("Temps", marker.minute), y: .value("Profondeur", marker.depth))
+ PointMark(x: .value("Time", marker.minute), y: .value("Depth", marker.depth))
.symbol(marker.label == nil ? .triangle : .diamond)
.symbolSize(60)
.foregroundStyle(marker.label == nil ? Color.orange : Color.purple)
@@ -191,7 +193,7 @@ struct ProfileChart: View {
}
ForEach(Array(photoOffsets.enumerated()), id: \.offset) { _, seconds in
let minute = Double(seconds) / 60
- PointMark(x: .value("Temps", minute), y: .value("Profondeur", data.sample(at: minute).map { units.depthValue($0.depth) } ?? 0))
+ PointMark(x: .value("Time", minute), y: .value("Depth", data.sample(at: minute).map { units.depthValue($0.depth) } ?? 0))
.symbol(.circle)
.symbolSize(photoOffsets.count > 25 ? 22 : 46)
.foregroundStyle(Color.pink)
@@ -202,11 +204,11 @@ struct ProfileChart: View {
}
}
if let selection {
- RuleMark(x: .value("Temps", selection))
+ RuleMark(x: .value("Time", selection))
.foregroundStyle(Color.secondary.opacity(0.6))
.lineStyle(StrokeStyle(lineWidth: 1))
if let sample = data.sample(at: selection) {
- PointMark(x: .value("Temps", Double(sample.time) / 60), y: .value("Profondeur", units.depthValue(sample.depth)))
+ PointMark(x: .value("Time", Double(sample.time) / 60), y: .value("Depth", units.depthValue(sample.depth)))
.symbolSize(80)
.foregroundStyle(Color.accentColor)
}
@@ -234,7 +236,7 @@ struct ProfileChart: View {
}
}
}
- .accessibilityLabel("Profil de la plongée")
+ .accessibilityLabel("Dive profile")
}
private func smallChart(title: String, unit: String, series: [ProfileData.Series], color: Color) -> some View {
@@ -243,13 +245,13 @@ struct ProfileChart: View {
Chart {
ForEach(series) { serie in
ForEach(serie.points) { point in
- LineMark(x: .value("Temps", point.minute), y: .value(title, point.value), series: .value("Série", serie.id))
+ LineMark(x: .value("Time", point.minute), y: .value(title, point.value), series: .value("Series", serie.id))
.foregroundStyle(color)
.lineStyle(StrokeStyle(lineWidth: 1.5))
}
}
if let selection {
- RuleMark(x: .value("Temps", selection))
+ RuleMark(x: .value("Time", selection))
.foregroundStyle(Color.secondary.opacity(0.6))
.lineStyle(StrokeStyle(lineWidth: 1))
}
@@ -272,7 +274,7 @@ struct ProfileChart: View {
}
}
.frame(height: 70)
- .accessibilityLabel("\(title) (\(unit))")
+ .accessibilityLabel(Text(verbatim: "\(title) (\(unit))"))
}
}
}
diff --git a/App/Views/RootView.swift b/App/Views/RootView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SwiftUI
struct RootView: View {
@@ -13,23 +14,23 @@ struct RootView: View {
case .ready:
TabView(selection: $tab) {
DiveListView()
- .tabItem { Label("Plongées", systemImage: "water.waves") }
+ .tabItem { Label("Dives", systemImage: "water.waves") }
.tag("dives")
SitesView()
- .tabItem { Label("Lieux", systemImage: "map") }
+ .tabItem { Label("Sites", systemImage: "map") }
.tag("sites")
StatsView()
- .tabItem { Label("Statistiques", systemImage: "chart.bar") }
+ .tabItem { Label("Statistics", systemImage: "chart.bar") }
.tag("stats")
SettingsView()
- .tabItem { Label("Réglages", systemImage: "gearshape") }
+ .tabItem { Label("Settings", systemImage: "gearshape") }
.tag("settings")
}
}
}
}
-/// Options de lancement pour les captures d'écran : `-demo`, `-tab sites|stats|settings`, `-showDive 11`, `-edit`.
+/// Launch options for screenshots: `-demo`, `-tab sites|stats|settings`, `-showDive 11`, `-edit`.
enum LaunchOptions {
static func value(_ name: String) -> String? {
let arguments = ProcessInfo.processInfo.arguments
diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import SwiftUI
struct SettingsView: View {
@@ -5,21 +6,25 @@ struct SettingsView: View {
@State private var confirmingSignOut = false
@State private var importing = false
+ private var about: String {
+ String(localized: "\(Brand.name) reads and edits the logbook that Subsurface keeps in its cloud, in the same format. It is an independent app, not affiliated with the Subsurface team. It replaces neither a dive computer nor proper training.")
+ }
+
var body: some View {
NavigationStack {
List {
- Section("Compte") {
+ Section("Account") {
if model.isDemo {
- Label("Carnet de démonstration", systemImage: "sparkles")
- Text("Les modifications restent sur cet iPhone et disparaissent en quittant la démonstration.")
+ Label("Demo logbook", systemImage: "sparkles")
+ Text("Changes stay on this iPhone and disappear when you leave the demo.")
.font(.footnote)
.foregroundStyle(.secondary)
} else {
- LabeledContent("Nuage Subsurface", value: model.email)
- LabeledContent("Dernière synchronisation") {
+ LabeledContent("Subsurface cloud", value: model.email)
+ LabeledContent("Last sync") {
switch model.syncState {
case .syncing: ProgressView()
- default: Text(model.lastSync.map { $0.formatted(.relative(presentation: .named)) } ?? "Jamais")
+ default: Text(model.lastSync.map { $0.formatted(.relative(presentation: .named)) } ?? String(localized: "Never"))
}
}
if case .failed(let message) = model.syncState {
@@ -30,33 +35,33 @@ struct SettingsView: View {
Button {
Task { await model.sync() }
} label: {
- Label("Synchroniser maintenant", systemImage: "arrow.triangle.2.circlepath")
+ Label("Sync now", systemImage: "arrow.triangle.2.circlepath")
}
.disabled(model.syncState == .syncing)
}
}
if !model.pending.isEmpty {
- Section("En attente d'envoi") {
+ Section("Waiting to upload") {
ForEach(Array(model.pending.enumerated()), id: \.offset) { _, change in
- Text(change.summary.capitalizedFirst).font(.callout)
+ Text(AppModel.summary(change)).font(.callout)
}
}
}
- Section("Affichage") {
- Picker("Unités", selection: Binding(get: { model.units.imperial }, set: { model.setImperial($0) })) {
- Text("Métriques (m, °C, bar)").tag(false)
- Text("Impériales (ft, °F, psi)").tag(true)
+ Section("Display") {
+ Picker("Units", selection: Binding(get: { model.units.imperial }, set: { model.setImperial($0) })) {
+ Text("Metric (m, °C, bar)").tag(false)
+ Text("Imperial (ft, °F, psi)").tag(true)
}
}
- Section("Carnet") {
- LabeledContent("Plongées", value: "\(model.logbook.dives.count)")
- LabeledContent("Lieux", value: "\(model.logbook.sites.count)")
- LabeledContent("Voyages", value: "\(model.logbook.trips.count)")
+ Section("Logbook") {
+ LabeledContent("Dives", value: "\(model.logbook.dives.count)")
+ LabeledContent("Sites", value: "\(model.logbook.sites.count)")
+ LabeledContent("Trips", value: "\(model.logbook.trips.count)")
Button { importing = true } label: {
- Label("Importer un fichier…", systemImage: "square.and.arrow.down")
+ Label("Import a file…", systemImage: "square.and.arrow.down")
}
ForEach(model.logbook.warnings, id: \.self) { warning in
Label(warning, systemImage: "exclamationmark.triangle")
@@ -67,31 +72,32 @@ struct SettingsView: View {
Section {
LabeledContent("Version", value: Brand.version)
- Text("\(Brand.name) lit et modifie le carnet que Subsurface garde dans son nuage, dans le même format. C'est une application indépendante, sans lien avec l'équipe de Subsurface. Elle ne remplace ni un ordinateur de plongée ni une formation.")
+ Text(about)
.font(.footnote)
.foregroundStyle(.secondary)
} header: {
- Text("À propos")
+ Text("About")
}
Section {
- Button(model.isDemo ? "Quitter la démonstration" : "Se déconnecter", role: .destructive) {
+ Button(model.isDemo ? String(localized: "Leave the demo") : String(localized: "Sign out"), role: .destructive) {
confirmingSignOut = true
}
}
}
.listStyle(.insetGrouped)
- .navigationTitle("Réglages")
+ .navigationTitle("Settings")
.modifier(FileImport(isPresented: $importing))
- .confirmationDialog(model.isDemo ? "Quitter la démonstration ?" : "Se déconnecter ?", isPresented: $confirmingSignOut, titleVisibility: .visible) {
- Button(model.isDemo ? "Quitter" : "Se déconnecter", role: .destructive) {
+ .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?") : String(localized: "Sign out?"),
+ isPresented: $confirmingSignOut, titleVisibility: .visible) {
+ Button(model.isDemo ? String(localized: "Leave") : String(localized: "Sign out"), role: .destructive) {
Task { await model.signOut() }
}
} message: {
if !model.isDemo, !model.pending.isEmpty {
- Text("Attention : \(model.pending.count) modification(s) pas encore envoyée(s) seront perdues. La copie du carnet sur cet iPhone sera effacée.")
+ Text("Warning: \(model.pending.count) change(s) not yet uploaded will be lost. The copy of the logbook on this iPhone will be erased.")
} else if !model.isDemo {
- Text("La copie du carnet sur cet iPhone sera effacée. Rien n'est supprimé dans le nuage.")
+ Text("The copy of the logbook on this iPhone will be erased. Nothing is deleted in the cloud.")
}
}
}
diff --git a/App/Views/SitesView.swift b/App/Views/SitesView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import MapKit
import SubsurfaceLog
import SwiftUI
@@ -41,13 +42,13 @@ struct SitesView: View {
list(all)
}
}
- .navigationTitle("Lieux")
+ .navigationTitle("Sites")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .principal) {
- Picker("Affichage", selection: $mode) {
- Text("Carte").tag(0)
- Text("Liste").tag(1)
+ Picker("View", selection: $mode) {
+ Text("Map").tag(0)
+ Text("List").tag(1)
}
.pickerStyle(.segmented)
.frame(width: 180)
@@ -61,10 +62,10 @@ struct SitesView: View {
private func map(_ located: [Entry]) -> some View {
Map(selection: $selection) {
- // L'identité de l'épingle change avec la présence de photos : sans cela, la carte garde l'ancienne.
+ // The identity of the pin changes with the presence of photos: otherwise the map keeps the old one.
ForEach(located.map { Pin(entry: $0, hasPhotos: model.sitesWithPhotos.contains($0.site.uuid)) }) { pin in
let entry = pin.entry
- // Un appareil photo rose quand la photothèque a des photos d'une plongée faite ici.
+ // A pink camera when the photo library has photos of a dive made here.
let hasPhotos = pin.hasPhotos
Marker(entry.site.name, systemImage: hasPhotos ? "camera.fill" : "water.waves",
coordinate: CLLocationCoordinate2D(latitude: entry.site.latitude ?? 0, longitude: entry.site.longitude ?? 0))
@@ -75,8 +76,8 @@ struct SitesView: View {
.mapStyle(.hybrid(elevation: .flat))
.overlay {
if located.isEmpty {
- ContentUnavailableView("Aucun lieu avec position", systemImage: "mappin.slash",
- description: Text("Les lieux de plongée situés dans Subsurface apparaîtront ici."))
+ ContentUnavailableView("No sites with a location", systemImage: "mappin.slash",
+ description: Text("Dive sites located in Subsurface will appear here."))
.background(.regularMaterial)
}
}
@@ -108,7 +109,7 @@ struct SitesView: View {
NavigationLink(value: entry.site.uuid) {
HStack {
VStack(alignment: .leading, spacing: 2) {
- Text(entry.site.name.isEmpty ? "Lieu sans nom" : entry.site.name)
+ Text(entry.site.name.isEmpty ? String(localized: "Unnamed site") : entry.site.name)
if let country = entry.site.country {
Text(country).font(.caption).foregroundStyle(.secondary)
}
@@ -118,7 +119,7 @@ struct SitesView: View {
Image(systemName: "camera.fill")
.font(.caption)
.foregroundStyle(.pink)
- .accessibilityLabel("Avec photos")
+ .accessibilityLabel("Has photos")
}
Text("\(entry.count)")
.font(.callout.monospacedDigit())
@@ -126,14 +127,14 @@ struct SitesView: View {
}
}
}
- .searchable(text: $search, prompt: "Chercher un lieu")
+ .searchable(text: $search, prompt: "Search sites")
.overlay {
- if all.isEmpty { ContentUnavailableView("Aucun lieu", systemImage: "map") }
+ if all.isEmpty { ContentUnavailableView("No sites", systemImage: "map") }
}
}
private func countLabel(_ count: Int) -> String {
- count == 0 ? "Aucune plongée" : (count == 1 ? "1 plongée" : "\(count) plongées")
+ count == 0 ? String(localized: "No dives") : (count == 1 ? String(localized: "1 dive") : String(localized: "\(count) dives"))
}
}
@@ -165,32 +166,32 @@ struct SiteDetailView: View {
item.name = site.name
item.openInMaps()
} label: {
- Label("Ouvrir dans Plans", systemImage: "arrow.triangle.turn.up.right.diamond")
+ Label("Open in Maps", systemImage: "arrow.triangle.turn.up.right.diamond")
}
}
}
if let site, !site.description.isEmpty || !site.notes.isEmpty || site.country != nil {
- Section("À propos") {
- if let country = site.country { LabeledContent("Pays", value: country) }
+ Section("About") {
+ if let country = site.country { LabeledContent("Country", value: country) }
if !site.description.isEmpty { Text(site.description) }
if !site.notes.isEmpty { Text(site.notes).foregroundStyle(.secondary) }
}
}
if !dives.isEmpty {
- Section("Résumé") {
- LabeledContent("Plongées", value: "\(dives.count)")
- LabeledContent("Plus profonde", value: model.units.depth(dives.map(\.maxDepth).max() ?? 0))
- LabeledContent("Temps passé", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }))
+ Section("Summary") {
+ LabeledContent("Dives", value: "\(dives.count)")
+ LabeledContent("Deepest", value: model.units.depth(dives.map(\.maxDepth).max() ?? 0))
+ LabeledContent("Time spent", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }))
}
Section("Photos") {
PhotoStrip(access: photoAccess, photos: photos, loading: photosLoading,
- emptyText: "Aucune photo de vos plongées ici dans la photothèque de cet iPhone.",
+ emptyText: String(localized: "No photos of your dives here in this iPhone's photo library."),
onGranted: { Task { await loadPhotos(dives); await model.refreshPhotoPresence() } },
caption: { photo in
photo.asset.creationDate?.formatted(Date.FormatStyle(date: .abbreviated, time: .shortened, timeZone: photoZone)) ?? ""
})
}
- Section("Plongées") {
+ Section("Dives") {
ForEach(dives) { dive in
NavigationLink(value: dive.id) {
HStack {
@@ -209,12 +210,12 @@ struct SiteDetailView: View {
}
}
}
- .navigationTitle(site?.name ?? "Lieu")
+ .navigationTitle(site?.name ?? String(localized: "Site"))
.navigationBarTitleDisplayMode(.inline)
.task(id: dives.map(\.id)) { await loadPhotos(dives) }
}
- /// Photos de toutes les plongées faites ici, les plus récentes d'abord (au plus 40 plongées, 300 photos).
+ /// Photos of all the dives made here, most recent first (at most 40 dives, 300 photos).
private func loadPhotos(_ dives: [Dive]) async {
guard photoAccess.granted else { return }
photosLoading = photos.isEmpty
diff --git a/App/Views/StatsView.swift b/App/Views/StatsView.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Charts
import SubsurfaceLog
import SwiftUI
@@ -12,11 +13,11 @@ struct StatsView: View {
var name: String { label ?? id }
}
- /// Colonnes : une par catégorie, le nombre écrit au-dessus, sans axe vertical (les nombres suffisent).
+ /// Columns: one per category, the count written above, no vertical axis (the numbers are enough).
private func columns(_ buckets: [Bucket], label: String) -> some View {
let top = Double(max(buckets.map(\.count).max() ?? 1, 1))
return Chart(buckets) { bucket in
- BarMark(x: .value(label, bucket.id), y: .value("Plongées", bucket.count), width: .ratio(0.72))
+ BarMark(x: .value(label, bucket.id), y: .value("Dives", bucket.count), width: .ratio(0.72))
.foregroundStyle(Color.accentColor.gradient)
.cornerRadius(4)
.annotation(position: .top, spacing: 3) {
@@ -27,7 +28,7 @@ struct StatsView: View {
}
.chartYScale(domain: 0...(top * 1.12))
.chartYAxis(.hidden)
- // Les étiquettes d'un graphique n'ont pas la place de grossir avec le texte de l'iPhone.
+ // Chart labels have no room to grow with the iPhone text size.
.dynamicTypeSize(...DynamicTypeSize.large)
.chartXAxis {
AxisMarks { value in
@@ -40,8 +41,8 @@ struct StatsView: View {
}
}
- /// Barres horizontales : le nom de la tranche à gauche, le nombre au bout de la barre. Dessinées à la main plutôt
- /// qu'avec un graphique : l'étiquette et sa barre restent sur la même ligne quelle que soit la taille du texte.
+ /// Horizontal bars: the name of the range on the left, the count at the end of the bar. Drawn by hand rather
+ /// than with a chart: the label and its bar stay on the same line whatever the text size.
private func rows(_ buckets: [Bucket], label: String) -> some View {
let top = CGFloat(max(buckets.map(\.count).max() ?? 1, 1))
return Grid(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 12) {
@@ -76,78 +77,83 @@ struct StatsView: View {
ScrollViewReader { proxy in
List {
if dives.isEmpty {
- ContentUnavailableView("Pas encore de statistiques", systemImage: "chart.bar",
- description: Text("Elles apparaîtront avec vos premières plongées."))
+ ContentUnavailableView("No statistics yet", systemImage: "chart.bar",
+ description: Text("They'll appear with your first dives."))
} else {
Section {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 2), spacing: 8) {
- Figure(title: "Plongées", value: "\(dives.count)", icon: "number")
- Figure(title: "Temps sous l'eau", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }), icon: "clock")
- Figure(title: "Plus profonde", value: units.depth(dives.map(\.maxDepth).max() ?? 0), icon: "arrow.down.to.line")
- Figure(title: "Plus longue", value: Units.duration(dives.map(\.durationSeconds).max() ?? 0), icon: "hourglass")
- Figure(title: "Profondeur moyenne", value: units.depth(dives.map(\.maxDepth).reduce(0, +) / Double(dives.count)), icon: "arrow.up.and.down")
- Figure(title: "Durée moyenne", value: Units.duration(dives.reduce(0) { $0 + $1.durationSeconds } / dives.count), icon: "timer")
+ Figure(title: "Dives", value: "\(dives.count)", icon: "number")
+ Figure(title: "Time underwater", value: Units.totalTime(dives.reduce(0) { $0 + $1.durationSeconds }), icon: "clock")
+ Figure(title: "Deepest", value: units.depth(dives.map(\.maxDepth).max() ?? 0), icon: "arrow.down.to.line")
+ Figure(title: "Longest", value: Units.duration(dives.map(\.durationSeconds).max() ?? 0), icon: "hourglass")
+ Figure(title: "Average depth", value: units.depth(dives.map(\.maxDepth).reduce(0, +) / Double(dives.count)), icon: "arrow.up.and.down")
+ Figure(title: "Average duration", value: Units.duration(dives.reduce(0) { $0 + $1.durationSeconds } / dives.count), icon: "timer")
if let cold = dives.compactMap(\.waterTemperature).min(), let warm = dives.compactMap(\.waterTemperature).max() {
- Figure(title: "Eau la plus froide", value: units.temperature(cold), icon: "snowflake")
- Figure(title: "Eau la plus chaude", value: units.temperature(warm), icon: "sun.max")
+ Figure(title: "Coldest water", value: units.temperature(cold), icon: "snowflake")
+ Figure(title: "Warmest water", value: units.temperature(warm), icon: "sun.max")
}
let sacs = dives.compactMap(\.sac)
if !sacs.isEmpty {
- Figure(title: "Conso. moyenne", value: units.sac(sacs.reduce(0, +) / Double(sacs.count)), icon: "lungs")
+ Figure(title: "Average SAC", value: units.sac(sacs.reduce(0, +) / Double(sacs.count)), icon: "lungs")
}
- Figure(title: "Lieux visités", value: "\(Set(dives.compactMap(\.siteUUID)).count)", icon: "mappin.and.ellipse")
+ Figure(title: "Sites visited", value: "\(Set(dives.compactMap(\.siteUUID)).count)", icon: "mappin.and.ellipse")
}
.listRowSeparator(.hidden)
}
- Section("Plongées par année") {
+ Section("Dives per year") {
EmptyView().id("years")
- // Toutes les années de la première à la dernière, y compris celles sans plongée.
+ // Every year from the first to the last, including those without a dive.
let counts = Dictionary(grouping: dives, by: { DiveDate.year($0.when) }).mapValues(\.count)
let span = (counts.keys.min() ?? 0)...(counts.keys.max() ?? 0)
- // Au-delà de six années, « ’18 » plutôt que « 2018 » : sinon les étiquettes se chevauchent.
+ // Beyond six years, "’18" rather than "2018": otherwise the labels overlap.
let years = span.map { Bucket(id: String($0), count: counts[$0] ?? 0, label: span.count > 6 ? "’" + String(format: "%02d", $0 % 100) : nil) }
- columns(years, label: "Année")
+ columns(years, label: String(localized: "Year"))
.frame(height: 190)
.padding(.vertical, 6)
- .accessibilityLabel("Nombre de plongées par année")
+ .accessibilityLabel("Number of dives per year")
}
- Section("Plongées par mois") {
+ Section("Dives per month") {
EmptyView().id("months")
let counts = Dictionary(grouping: dives, by: { NaiveTime.components($0.when).month ?? 0 }).mapValues(\.count)
+ // Month initials, identical in English and French.
let initials = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]
- // L'identifiant porte le rang du mois : plusieurs mois ont la même initiale.
+ // The identifier carries the rank of the month: several months share the same initial.
let months = (1...12).map { Bucket(id: "\($0)", count: counts[$0] ?? 0, label: initials[$0 - 1]) }
- columns(months, label: "Mois")
+ columns(months, label: String(localized: "Month"))
.frame(height: 170)
.padding(.vertical, 6)
- .accessibilityLabel("Nombre de plongées par mois de l'année")
+ .accessibilityLabel("Number of dives per month of the year")
}
- Section("Profondeur maximale") {
+ Section("Maximum depth") {
EmptyView().id("depth")
let step = units.imperial ? 30.0 : 10.0
let grouped = Dictionary(grouping: dives, by: { Int(units.depthValue($0.maxDepth) / step) })
+ let unit = units.depthUnit
let buckets = (0...(grouped.keys.max() ?? 0)).map { index in
- Bucket(id: "\(Int(Double(index) * step)) à \(Int(Double(index + 1) * step)) \(units.depthUnit)", count: grouped[index]?.count ?? 0)
+ let from = Int(Double(index) * step)
+ let to = Int(Double(index + 1) * step)
+ return Bucket(id: String(localized: "\(from)–\(to) \(unit)"), count: grouped[index]?.count ?? 0)
}
- rows(buckets, label: "Profondeur")
+ rows(buckets, label: String(localized: "Depth"))
.padding(.vertical, 6)
- .accessibilityLabel("Nombre de plongées par tranche de profondeur")
+ .accessibilityLabel("Number of dives per depth range")
}
- Section("Durée") {
+ Section("Duration") {
EmptyView().id("duration")
let grouped = Dictionary(grouping: dives, by: { min($0.durationSeconds / 60 / 15, 5) })
- let names = ["moins de 15 min", "15 à 30 min", "30 à 45 min", "45 à 60 min", "60 à 75 min", "75 min et plus"]
+ let names = [String(localized: "Under 15 min"), String(localized: "15–30 min"), String(localized: "30–45 min"),
+ String(localized: "45–60 min"), String(localized: "60–75 min"), String(localized: "75 min or more")]
let buckets = (0...(grouped.keys.max() ?? 0)).map { Bucket(id: names[$0], count: grouped[$0]?.count ?? 0) }
- rows(buckets, label: "Durée")
+ rows(buckets, label: String(localized: "Duration"))
.padding(.vertical, 6)
- .accessibilityLabel("Nombre de plongées par tranche de durée")
+ .accessibilityLabel("Number of dives per duration range")
}
- Section("Gaz") {
+ Section("Gas") {
EmptyView().id("gas")
let gases = Dictionary(grouping: dives.filter { !$0.cylinders.isEmpty }, by: { gasFamily($0) })
ForEach(gases.keys.sorted(), id: \.self) { family in
@@ -155,7 +161,7 @@ struct StatsView: View {
}
}
- Section("Lieux les plus plongés") {
+ Section("Most dived sites") {
let bySite = Dictionary(grouping: dives.filter { $0.siteUUID != nil }, by: { $0.siteUUID! })
.map { (name: model.logbook.sites[$0.key]?.name ?? "", count: $0.value.count) }
.filter { !$0.name.isEmpty }
@@ -168,7 +174,7 @@ struct StatsView: View {
let buddies = topBuddies(dives)
if !buddies.isEmpty {
- Section("Binômes") {
+ Section("Buddies") {
ForEach(buddies, id: \.name) { entry in
LabeledContent(entry.name, value: "\(entry.count)")
}
@@ -178,16 +184,17 @@ struct StatsView: View {
}
.listStyle(.insetGrouped)
.onAppear {
- // Option de capture d'écran : montrer une section plus bas.
+ // Screenshot option: show a section further down.
if let target = LaunchOptions.value("-statsScroll") {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { proxy.scrollTo(target, anchor: .top) }
}
}
}
- .navigationTitle("Statistiques")
+ .navigationTitle("Statistics")
}
}
+ /// Gas family names are the same in English and French.
private func gasFamily(_ dive: Dive) -> String {
let used = dive.cylinders.filter { $0.use != "not used" }
if used.contains(where: { $0.gas.hePermille > 0 }) { return "Trimix" }
diff --git a/LICENSE b/LICENSE
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/Makefile b/Makefile
@@ -1,4 +1,4 @@
-# Le code vit ici (hotrats) ; Swift et Xcode tournent sur chunga.
+# The sources live on this host; Swift and Xcode run on a Mac reachable over SSH (CHUNGA), in the REMOTE directory.
CHUNGA ?= chunga
REMOTE ?= src/perso/divelog
DEST ?= platform=iOS Simulator,name=DiveLog test iPhone
@@ -8,7 +8,7 @@ DEST ?= platform=iOS Simulator,name=DiveLog test iPhone
sync:
rsync -a --delete --exclude .git --exclude .claude --exclude '*.xcodeproj' --exclude build --exclude .build ./ $(CHUNGA):$(REMOTE)/
-# Paquet Swift seul (git + format Subsurface), sans interface. FILTER=NomDuTest pour un seul test.
+# The Swift package alone (git + Subsurface format), without the interface. FILTER=TestName runs a single test.
test-kit: sync
ssh $(CHUNGA) 'cd $(REMOTE)/Packages/DiveKit && swift test $(if $(FILTER),--filter $(FILTER)) 2>&1'
@@ -21,23 +21,25 @@ build: project
test: project
ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme DiveLog -destination "$(DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO test'
-# Lance l'app dans le simulateur avec le carnet de démonstration et prend une capture.
-# ARGS = options de lancement (voir LaunchOptions), SHOT = nom de la capture, WAIT = délai avant la capture.
+# Launches the app in the simulator with the demo logbook and takes a screenshot.
+# ARGS = launch options (see LaunchOptions), SHOT = screenshot name, WAIT = delay before the screenshot.
SIM ?= DiveLog test iPhone
ARGS ?=
DEMO ?= -demo
-# Variables d'environnement passées à l'app (SIMCTL_CHILD_NOM=valeur), par exemple pour un vrai carnet.
+# Language of the app for screenshots: en or fr.
+APPLANG ?= en
+# Environment variables passed to the app (SIMCTL_CHILD_NAME=value), for instance to open a real logbook.
SIMENV ?=
SHOT ?= shot
WAIT ?= 4
APP_ID = org.schurger.subrascasse
.PHONY: shot
shot:
- @ssh $(CHUNGA) 'cd $(REMOTE) && xcrun simctl bootstatus "$(SIM)" -b >/dev/null && xcrun simctl install "$(SIM)" build/Build/Products/Debug-iphonesimulator/DiveLog.app && (xcrun simctl terminate "$(SIM)" $(APP_ID) 2>/dev/null; true) && $(SIMENV) xcrun simctl launch "$(SIM)" $(APP_ID) $(DEMO) -AppleLanguages "(fr)" -AppleLocale fr_CA $(ARGS) >/dev/null && sleep $(WAIT) && mkdir -p build/shots && xcrun simctl io "$(SIM)" screenshot build/shots/$(SHOT).png 2>/dev/null && sips -Z 1100 build/shots/$(SHOT).png --out build/shots/$(SHOT)-small.png >/dev/null'
+ @ssh $(CHUNGA) 'cd $(REMOTE) && xcrun simctl bootstatus "$(SIM)" -b >/dev/null && xcrun simctl install "$(SIM)" build/Build/Products/Debug-iphonesimulator/DiveLog.app && (xcrun simctl terminate "$(SIM)" $(APP_ID) 2>/dev/null; true) && $(SIMENV) xcrun simctl launch "$(SIM)" $(APP_ID) $(DEMO) -AppleLanguages "($(APPLANG))" -AppleLocale $(APPLANG)_CA $(ARGS) >/dev/null && sleep $(WAIT) && mkdir -p build/shots && xcrun simctl io "$(SIM)" screenshot build/shots/$(SHOT).png 2>/dev/null && sips -Z 1100 build/shots/$(SHOT).png --out build/shots/$(SHOT)-small.png >/dev/null'
@mkdir -p build/shots && scp -q $(CHUNGA):$(REMOTE)/build/shots/$(SHOT)-small.png build/shots/$(SHOT).png
-# Archive signée pour TestFlight (signature automatique, clé API perso de chunga). BUILD=n fixe le numéro ;
-# chaque build a son dossier build/tf-<numéro>.
+# Signed archive for TestFlight (automatic signing, App Store Connect API key from the Mac's environment).
+# BUILD=n sets the build number; each build gets its own build/tf-<number> folder.
BUILD ?= $(shell date +%Y%m%d%H%M)
OUT = build/tf-$(BUILD)
AUTH = -allowProvisioningUpdates -authenticationKeyPath $$PERSO_ASC_KEY_PATH -authenticationKeyID $$PERSO_ASC_KEY_ID -authenticationKeyIssuerID $$PERSO_ASC_ISSUER_ID
@@ -46,10 +48,10 @@ AUTH = -allowProvisioningUpdates -authenticationKeyPath $$PERSO_ASC_KEY_PATH -au
archive: project
ssh $(CHUNGA) 'source ~/.zshrc_build && security unlock-keychain -p "$$(cat ~/.keyring_secret)" ~/Library/Keychains/login.keychain-db && cd $(REMOTE) && xcodebuild -quiet -scheme DiveLog -configuration Release -destination "generic/platform=iOS" -archivePath $(OUT)/DiveLog.xcarchive CURRENT_PROJECT_VERSION=$(BUILD) $(AUTH) archive && PATH=/usr/bin:$$PATH xcodebuild -quiet -exportArchive -archivePath $(OUT)/DiveLog.xcarchive -exportOptionsPlist tools/ExportOptions.plist -exportPath $(OUT)/ipa $(AUTH) && ls -la $(OUT)/ipa'
-# Envoi sur TestFlight de l'IPA archivée, avec le même BUILD (altool cherche la clé dans API_PRIVATE_KEYS_DIR).
+# Uploads the archived IPA to TestFlight, with the same BUILD (altool looks for the key in API_PRIVATE_KEYS_DIR).
upload:
ssh $(CHUNGA) 'source ~/.zshrc_build && cd $(REMOTE) && API_PRIVATE_KEYS_DIR=$$(dirname $$PERSO_ASC_KEY_PATH) xcrun altool --upload-app -f $(OUT)/ipa/DiveLog.ipa -t ios --apiKey $$PERSO_ASC_KEY_ID --apiIssuer $$PERSO_ASC_ISSUER_ID'
-# Groupe « Interne », textes TestFlight et notes de la dernière build.
+# "Interne" tester group, TestFlight texts and notes of the latest build.
beta-setup: sync
ssh $(CHUNGA) 'source ~/.zshrc_build && cd $(REMOTE) && fastlane ios beta_setup'
diff --git a/Packages/DiveKit/Package.swift b/Packages/DiveKit/Package.swift
@@ -1,4 +1,5 @@
// swift-tools-version: 5.9
+// SPDX-License-Identifier: GPL-2.0-only
import PackageDescription
let package = Package(
@@ -9,13 +10,13 @@ let package = Package(
.library(name: "SubsurfaceLog", targets: ["SubsurfaceLog"]),
],
targets: [
- // Client git minimal en Swift pur : objets, paquets, protocole « smart HTTP ».
+ // Minimal git client in pure Swift: objects, packfiles, smart HTTP protocol.
.target(name: "GitLite", linkerSettings: [.linkedLibrary("z")]),
- // Format de carnet de Subsurface (stockage git) : lecture, modification, synchronisation.
+ // Subsurface logbook format (git storage): reading, editing, sync.
.target(name: "SubsurfaceLog", dependencies: ["GitLite"]),
- // Outils de test : pilote le vrai git en ligne de commande (macOS seulement).
+ // Test support: drives the real command-line git (macOS only).
.target(name: "GitTestSupport", dependencies: ["GitLite"]),
- // Outil en ligne de commande (macOS) : importer un fichier dans un carnet du nuage, lister un carnet.
+ // Command-line tool (macOS): import a file into a cloud logbook, list a logbook.
.executableTarget(name: "divelog-cli", dependencies: ["SubsurfaceLog", "GitLite"]),
.testTarget(name: "GitLiteTests", dependencies: ["GitLite", "GitTestSupport"]),
.testTarget(name: "SubsurfaceLogTests", dependencies: ["SubsurfaceLog", "GitLite", "GitTestSupport"]),
diff --git a/Packages/DiveKit/Sources/GitLite/Client.swift b/Packages/DiveKit/Sources/GitLite/Client.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
// MARK: - pkt-line
@@ -11,20 +12,20 @@ enum PktLine {
static func encode(_ text: String) -> [UInt8] { encode(Array(text.utf8)) }
- /// Découpe un flux en paquets ; `nil` = paquet de vidage (0000).
+ /// Splits a stream into packets; `nil` = flush packet (0000).
static func decode(_ data: [UInt8]) throws -> [[UInt8]?] {
var out = [[UInt8]?]()
var pos = 0
while pos + 4 <= data.count {
guard let length = Int(String(decoding: data[pos..<(pos + 4)], as: UTF8.self), radix: 16) else {
- throw GitError.malformed("pkt-line : longueur")
+ throw GitError.malformed("pkt-line: length")
}
if length < 4 {
out.append(nil)
pos += 4
continue
}
- guard pos + length <= data.count else { throw GitError.malformed("pkt-line tronqué") }
+ guard pos + length <= data.count else { throw GitError.malformed("truncated pkt-line") }
out.append(Array(data[(pos + 4)..<(pos + length)]))
pos += length
}
@@ -39,7 +40,7 @@ public enum GitService: String, Sendable {
case receivePack = "git-receive-pack"
}
-/// Transport sans état, calqué sur le protocole « smart HTTP » de git.
+/// Stateless transport, modelled on git's "smart HTTP" protocol.
public protocol GitTransport: Sendable {
func advertisement(_ service: GitService) async throws -> [UInt8]
func rpc(_ service: GitService, body: [UInt8]) async throws -> [UInt8]
@@ -86,7 +87,7 @@ public struct HTTPTransport: GitTransport {
} catch {
throw GitError.network(error.localizedDescription)
}
- guard let http = response as? HTTPURLResponse else { throw GitError.network("réponse inattendue") }
+ guard let http = response as? HTTPURLResponse else { throw GitError.network("unexpected response") }
switch http.statusCode {
case 200: return Array(data)
case 401: throw GitError.unauthorized
@@ -156,8 +157,8 @@ public struct GitClient: Sendable {
return result
}
- /// Récupère `want` et ce qui en dépend. `have` = commits déjà connus, `shallow` = commits locaux sans parents,
- /// `depth` = profondeur d'historique demandée. Rend les commits que le serveur a laissés sans parents.
+ /// Fetches `want` and everything it depends on. `have` = commits already known, `shallow` = local commits without
+ /// parents, `depth` = requested history depth. Returns the commits the server left without parents.
@discardableResult
public func fetch(want: ObjectID, have: [ObjectID] = [], shallow: [ObjectID] = [], depth: Int? = nil,
capabilities: Set<String>) async throws -> [ObjectID] {
@@ -201,7 +202,7 @@ public struct GitClient: Sendable {
}
}
} else {
- // Sans bande latérale : quelques paquets texte, puis le paquet d'objets brut.
+ // Without side-band: a few text packets, then the raw packfile.
var pos = 0
while pos + 4 <= response.count, !(response[pos] == 0x50 && response[pos + 1] == 0x41) {
guard let length = Int(String(decoding: response[pos..<(pos + 4)], as: UTF8.self), radix: 16) else { break }
@@ -215,7 +216,7 @@ public struct GitClient: Sendable {
pack = Array(response[min(pos, response.count)...])
}
- guard !pack.isEmpty else { throw GitError.malformed("réponse sans paquet d'objets") }
+ guard !pack.isEmpty else { throw GitError.malformed("response without a packfile") }
let store = self.store
let objects = try Pack.parse(pack, external: { store.get($0) })
for object in objects { _ = try store.put(object) }
@@ -223,7 +224,7 @@ public struct GitClient: Sendable {
return newShallow
}
- /// Envoie des objets et déplace une référence de `old` (nil = création) vers `new`.
+ /// Sends objects and moves a reference from `old` (nil = creation) to `new`.
public func push(ref: String, old: ObjectID?, new: ObjectID, objects: [GitObject]) async throws {
var body = PktLine.encode(Array("\((old ?? .zero).hex) \(new.hex) \(ref)".utf8) + [0] + Array("report-status agent=\(agent)\n".utf8))
body += PktLine.flush
@@ -233,7 +234,7 @@ public struct GitClient: Sendable {
var refOK = false
for packet in try PktLine.decode(response) {
guard var payload = packet else { continue }
- // Certains serveurs enveloppent le rapport dans la bande 1.
+ // Some servers wrap the report in side-band channel 1.
if payload.first == 1 {
let inner = (try? PktLine.decode(Array(payload.dropFirst()))) ?? []
for case let line? in inner { try check(line, ref: ref, unpackOK: &unpackOK, refOK: &refOK) }
@@ -243,7 +244,7 @@ public struct GitClient: Sendable {
if payload.first == 3 { payload.removeFirst(); throw GitError.remote(String(decoding: payload, as: UTF8.self)) }
try check(payload, ref: ref, unpackOK: &unpackOK, refOK: &refOK)
}
- guard unpackOK, refOK else { throw GitError.pushRejected("réponse incomplète du serveur") }
+ guard unpackOK, refOK else { throw GitError.pushRejected("incomplete response from the server") }
}
private func check(_ line: [UInt8], ref: String, unpackOK: inout Bool, refOK: inout Bool) throws {
diff --git a/Packages/DiveKit/Sources/GitLite/Compression.swift b/Packages/DiveKit/Sources/GitLite/Compression.swift
@@ -1,19 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import zlib
-/// Décompression pour les fichiers importés : gzip, et archives zip (entrées stockées ou « deflate »).
+/// Decompression for imported files: gzip, and zip archives (stored or "deflate" entries).
public enum Inflate {
public enum Format: Int32 {
- case gzip = 31 // 16 + 15 : en-tête gzip
- case raw = -15 // flux « deflate » nu, comme dans un zip
- case auto = 47 // 32 + 15 : gzip ou zlib, reconnu à l'en-tête
+ case gzip = 31 // 16 + 15: gzip header
+ case raw = -15 // raw "deflate" stream, as in a zip
+ case auto = 47 // 32 + 15: gzip or zlib, detected from the header
}
public static func decompress(_ input: [UInt8], format: Format, limit: Int = 256 << 20) throws -> [UInt8] {
guard !input.isEmpty else { return [] }
var stream = z_stream()
guard inflateInit2_(&stream, format.rawValue, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else {
- throw GitError.malformed("zlib : initialisation")
+ throw GitError.malformed("zlib: initialization")
}
defer { inflateEnd(&stream) }
var output = [UInt8]()
@@ -29,16 +30,16 @@ public enum Inflate {
status = inflate(&stream, Z_NO_FLUSH)
return outPtr.count - Int(stream.avail_out)
}
- guard status == Z_OK || status == Z_STREAM_END else { throw GitError.malformed("données compressées invalides (\(status))") }
+ guard status == Z_OK || status == Z_STREAM_END else { throw GitError.malformed("invalid compressed data (\(status))") }
output.append(contentsOf: chunk[0..<produced])
- guard output.count <= limit else { throw GitError.malformed("fichier trop volumineux") }
- if produced == 0, stream.avail_in == 0, status != Z_STREAM_END { throw GitError.malformed("données compressées tronquées") }
+ guard output.count <= limit else { throw GitError.malformed("file too large") }
+ if produced == 0, stream.avail_in == 0, status != Z_STREAM_END { throw GitError.malformed("truncated compressed data") }
}
}
return output
}
- /// Compresse au format gzip (sert aux tests).
+ /// Compresses to the gzip format (used by the tests).
public static func gzip(_ input: [UInt8]) -> [UInt8] {
var stream = z_stream()
guard deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION,
@@ -62,7 +63,7 @@ public enum Inflate {
}
}
-/// Lecture minimale d'une archive zip (sans zip64 ni chiffrement).
+/// Minimal reader for a zip archive (no zip64, no encryption).
public struct ZipArchive {
public struct Entry {
public let name: String
@@ -82,21 +83,21 @@ public struct ZipArchive {
self.data = data
func u16(_ i: Int) -> Int { Int(data[i]) | Int(data[i + 1]) << 8 }
func u32(_ i: Int) -> Int { u16(i) | u16(i + 2) << 16 }
- // Fin du répertoire central : on la cherche depuis la fin (un commentaire peut la suivre).
+ // End of central directory: searched from the end (a comment may follow it).
var end = data.count - 22
var found = -1
while end >= 0, end >= data.count - 22 - 65_535 {
if data[end] == 0x50, data[end + 1] == 0x4b, data[end + 2] == 0x05, data[end + 3] == 0x06 { found = end; break }
end -= 1
}
- guard found >= 0 else { throw GitError.malformed("archive zip illisible") }
+ guard found >= 0 else { throw GitError.malformed("unreadable zip archive") }
let count = u16(found + 10)
var pos = u32(found + 16)
var list = [Entry]()
for _ in 0..<count {
- guard pos + 46 <= data.count, u32(pos) == 0x0201_4b50 else { throw GitError.malformed("archive zip : répertoire") }
+ guard pos + 46 <= data.count, u32(pos) == 0x0201_4b50 else { throw GitError.malformed("zip archive: central directory") }
let nameLength = u16(pos + 28), extraLength = u16(pos + 30), commentLength = u16(pos + 32)
- guard pos + 46 + nameLength <= data.count else { throw GitError.malformed("archive zip : nom") }
+ guard pos + 46 + nameLength <= data.count else { throw GitError.malformed("zip archive: name") }
let name = String(decoding: data[(pos + 46)..<(pos + 46 + nameLength)], as: UTF8.self)
list.append(Entry(name: name, method: u16(pos + 10), compressedSize: u32(pos + 20), localOffset: u32(pos + 42)))
pos += 46 + nameLength + extraLength + commentLength
@@ -108,15 +109,15 @@ public struct ZipArchive {
func u16(_ i: Int) -> Int { Int(data[i]) | Int(data[i + 1]) << 8 }
let pos = entry.localOffset
guard pos + 30 <= data.count, data[pos] == 0x50, data[pos + 1] == 0x4b, data[pos + 2] == 0x03, data[pos + 3] == 0x04 else {
- throw GitError.malformed("archive zip : entrée")
+ throw GitError.malformed("zip archive: entry")
}
let start = pos + 30 + u16(pos + 26) + u16(pos + 28)
- guard start + entry.compressedSize <= data.count else { throw GitError.malformed("archive zip tronquée") }
+ guard start + entry.compressedSize <= data.count else { throw GitError.malformed("truncated zip archive") }
let raw = Array(data[start..<(start + entry.compressedSize)])
switch entry.method {
case 0: return raw
case 8: return try Inflate.decompress(raw, format: .raw)
- default: throw GitError.malformed("archive zip : compression non prise en charge")
+ default: throw GitError.malformed("zip archive: unsupported compression")
}
}
diff --git a/Packages/DiveKit/Sources/GitLite/Objects.swift b/Packages/DiveKit/Sources/GitLite/Objects.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import CryptoKit
import Foundation
@@ -13,19 +14,19 @@ public enum GitError: Error, Equatable, CustomStringConvertible {
public var description: String {
switch self {
- case .malformed(let what): return "données git invalides : \(what)"
- case .missingObject(let id): return "objet git manquant : \(id)"
- case .unauthorized: return "identifiants refusés"
- case .notFound: return "dépôt introuvable"
- case .http(let code): return "erreur HTTP \(code)"
- case .network(let what): return "réseau : \(what)"
- case .remote(let what): return "serveur : \(what)"
- case .pushRejected(let why): return "envoi refusé : \(why)"
+ case .malformed(let what): return "invalid git data: \(what)"
+ case .missingObject(let id): return "missing git object: \(id)"
+ case .unauthorized: return "credentials rejected"
+ case .notFound: return "repository not found"
+ case .http(let code): return "HTTP error \(code)"
+ case .network(let what): return "network: \(what)"
+ case .remote(let what): return "server: \(what)"
+ case .pushRejected(let why): return "push rejected: \(why)"
}
}
}
-/// Identifiant d'objet git (SHA-1, 20 octets).
+/// Git object identifier (SHA-1, 20 bytes).
public struct ObjectID: Hashable, Sendable, CustomStringConvertible, Codable {
public let bytes: [UInt8]
@@ -74,7 +75,7 @@ public struct ObjectID: Hashable, Sendable, CustomStringConvertible, Codable {
public init(from decoder: Decoder) throws {
let text = try decoder.singleValueContainer().decode(String.self)
guard let id = ObjectID(hex: text) else {
- throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "identifiant git invalide"))
+ throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "invalid git identifier"))
}
self = id
}
@@ -119,7 +120,7 @@ func sha1(_ bytes: [UInt8]) -> [UInt8] {
Array(Insecure.SHA1.hash(data: bytes))
}
-// MARK: - Arbres
+// MARK: - Trees
public struct TreeEntry: Sendable, Equatable {
public var mode: String
@@ -143,9 +144,9 @@ public enum Tree {
var entries = [TreeEntry]()
var i = 0
while i < data.count {
- guard let space = data[i...].firstIndex(of: 0x20) else { throw GitError.malformed("arbre : mode") }
- guard let nul = data[space...].firstIndex(of: 0) else { throw GitError.malformed("arbre : nom") }
- guard nul + 21 <= data.count else { throw GitError.malformed("arbre : identifiant") }
+ guard let space = data[i...].firstIndex(of: 0x20) else { throw GitError.malformed("tree: mode") }
+ guard let nul = data[space...].firstIndex(of: 0) else { throw GitError.malformed("tree: name") }
+ guard nul + 21 <= data.count else { throw GitError.malformed("tree: identifier") }
let mode = String(decoding: data[i..<space], as: UTF8.self)
let name = String(decoding: data[(space + 1)..<nul], as: UTF8.self)
let id = ObjectID(bytes: Array(data[(nul + 1)..<(nul + 21)]))!
@@ -155,7 +156,7 @@ public enum Tree {
return entries
}
- /// Sérialise un arbre dans l'ordre exigé par git (les dossiers se comparent comme « nom/ »).
+ /// Serializes a tree in the order git requires (directories compare as "name/").
public static func serialize(_ entries: [TreeEntry]) -> [UInt8] {
func key(_ e: TreeEntry) -> [UInt8] { Array(e.name.utf8) + (e.isTree ? [0x2f] : []) }
let sorted = entries.sorted { key($0).lexicographicallyPrecedes(key($1)) }
@@ -207,7 +208,7 @@ public struct Commit: Sendable, Equatable {
committer = String(line.dropFirst(10))
}
}
- guard let tree else { throw GitError.malformed("commit sans arbre") }
+ guard let tree else { throw GitError.malformed("commit without a tree") }
return Commit(tree: tree, parents: parents, author: author, committer: committer, message: message)
}
@@ -218,7 +219,7 @@ public struct Commit: Sendable, Equatable {
return Array(text.utf8)
}
- /// « Nom <courriel> secondes +0000 »
+ /// "Name <email> seconds +0000"
public static func signature(name: String, email: String, date: Date = Date()) -> String {
"\(name) <\(email)> \(Int(date.timeIntervalSince1970)) +0000"
}
diff --git a/Packages/DiveKit/Sources/GitLite/Pack.swift b/Packages/DiveKit/Sources/GitLite/Pack.swift
@@ -1,17 +1,18 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import zlib
enum Zlib {
- /// Décompresse un flux zlib qui commence à `offset` ; rend les données et le nombre d'octets lus.
+ /// Inflates a zlib stream that starts at `offset`; returns the data and the number of bytes consumed.
static func inflate(_ input: [UInt8], from offset: Int, expectedSize: Int) throws -> (data: [UInt8], consumed: Int) {
var stream = z_stream()
guard inflateInit_(&stream, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else {
- throw GitError.malformed("zlib : initialisation")
+ throw GitError.malformed("zlib: initialization")
}
defer { inflateEnd(&stream) }
var output = [UInt8](repeating: 0, count: max(expectedSize, 1))
let available = input.count - offset
- guard available > 0 else { throw GitError.malformed("zlib : flux vide") }
+ guard available > 0 else { throw GitError.malformed("zlib: empty stream") }
var status: Int32 = Z_OK
var produced = 0
try input.withUnsafeBufferPointer { inPtr in
@@ -23,11 +24,11 @@ enum Zlib {
status = zlib.inflate(&stream, Z_FINISH)
produced = outPtr.count - Int(stream.avail_out)
if status != Z_STREAM_END {
- throw GitError.malformed("zlib : flux invalide (\(status))")
+ throw GitError.malformed("zlib: invalid stream (\(status))")
}
}
}
- guard produced == expectedSize else { throw GitError.malformed("zlib : taille inattendue") }
+ guard produced == expectedSize else { throw GitError.malformed("zlib: unexpected size") }
let consumed = min(available, Int(UInt32.max)) - Int(stream.avail_in)
if output.count != expectedSize { output.removeLast(output.count - expectedSize) }
return (output, consumed)
@@ -37,37 +38,37 @@ enum Zlib {
var bound = compressBound(UInt(input.count))
var output = [UInt8](repeating: 0, count: Int(bound))
let status = input.withUnsafeBufferPointer { inPtr -> Int32 in
- // compress2 exige un pointeur non nul même pour une entrée vide.
+ // compress2 requires a non-null pointer even for an empty input.
var dummy: UInt8 = 0
return withUnsafePointer(to: &dummy) { dummyPtr in
compress2(&output, &bound, inPtr.baseAddress ?? dummyPtr, UInt(input.count), Z_DEFAULT_COMPRESSION)
}
}
- precondition(status == Z_OK, "zlib : compression impossible")
+ precondition(status == Z_OK, "zlib: compression failed")
output.removeLast(output.count - Int(bound))
return output
}
}
-/// Lecture et écriture des paquets d'objets (« packfiles », version 2).
+/// Reading and writing packfiles (version 2).
public enum Pack {
private struct Entry {
- var type: UInt8 // 1…4 objet, 6 ofs-delta, 7 ref-delta
- var data: [UInt8] // contenu, ou instructions de delta
+ var type: UInt8 // 1…4 object, 6 ofs-delta, 7 ref-delta
+ var data: [UInt8] // content, or delta instructions
var baseOffset: Int = 0
var baseID: ObjectID?
}
- /// Décode un paquet ; `external` fournit les bases absentes du paquet (paquets « minces »).
+ /// Decodes a pack; `external` provides the bases missing from the pack ("thin" packs).
public static func parse(_ pack: [UInt8], external: (ObjectID) -> GitObject? = { _ in nil }) throws -> [GitObject] {
guard pack.count >= 32, pack[0] == 0x50, pack[1] == 0x41, pack[2] == 0x43, pack[3] == 0x4b else {
- throw GitError.malformed("paquet : en-tête")
+ throw GitError.malformed("pack: header")
}
let version = be32(pack, 4)
- guard version == 2 || version == 3 else { throw GitError.malformed("paquet : version \(version)") }
+ guard version == 2 || version == 3 else { throw GitError.malformed("pack: version \(version)") }
let count = Int(be32(pack, 8))
guard sha1(Array(pack[0..<(pack.count - 20)])) == Array(pack[(pack.count - 20)...]) else {
- throw GitError.malformed("paquet : somme de contrôle")
+ throw GitError.malformed("pack: checksum")
}
var entries = [Int: Entry]()
@@ -76,14 +77,14 @@ public enum Pack {
var pos = 12
let end = pack.count - 20
for _ in 0..<count {
- guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ guard pos < end else { throw GitError.malformed("truncated pack") }
let start = pos
var byte = pack[pos]; pos += 1
let type = (byte >> 4) & 7
var size = Int(byte & 15)
var shift = 4
while byte & 0x80 != 0 {
- guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ guard pos < end else { throw GitError.malformed("truncated pack") }
byte = pack[pos]; pos += 1
size |= Int(byte & 0x7f) << shift
shift += 7
@@ -93,21 +94,21 @@ public enum Pack {
case 1, 2, 3, 4:
break
case 6:
- guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ guard pos < end else { throw GitError.malformed("truncated pack") }
byte = pack[pos]; pos += 1
var offset = Int(byte & 0x7f)
while byte & 0x80 != 0 {
- guard pos < end else { throw GitError.malformed("paquet tronqué") }
+ guard pos < end else { throw GitError.malformed("truncated pack") }
byte = pack[pos]; pos += 1
offset = ((offset + 1) << 7) | Int(byte & 0x7f)
}
entry.baseOffset = start - offset
case 7:
- guard pos + 20 <= end else { throw GitError.malformed("paquet tronqué") }
+ guard pos + 20 <= end else { throw GitError.malformed("truncated pack") }
entry.baseID = ObjectID(bytes: Array(pack[pos..<(pos + 20)]))
pos += 20
default:
- throw GitError.malformed("paquet : type \(type)")
+ throw GitError.malformed("pack: type \(type)")
}
let (data, consumed) = try Zlib.inflate(pack, from: pos, expectedSize: size)
entry.data = data
@@ -119,7 +120,7 @@ public enum Pack {
var resolved = [Int: GitObject]()
var byID = [ObjectID: GitObject]()
- // Objets entiers d'abord : ils servent de base aux deltas par identifiant.
+ // Whole objects first: they are the bases of the deltas that refer to them by identifier.
for offset in order {
let e = entries[offset]!
if let type = ObjectType(rawValue: e.type) {
@@ -131,12 +132,12 @@ public enum Pack {
func resolve(_ offset: Int, depth: Int) throws -> GitObject {
if let done = resolved[offset] { return done }
- guard depth < 4096, let e = entries[offset] else { throw GitError.malformed("paquet : chaîne de deltas") }
+ guard depth < 4096, let e = entries[offset] else { throw GitError.malformed("pack: delta chain") }
let base: GitObject
if e.type == 6 {
base = try resolve(e.baseOffset, depth: depth + 1)
} else {
- guard let id = e.baseID else { throw GitError.malformed("paquet : delta sans base") }
+ guard let id = e.baseID else { throw GitError.malformed("pack: delta without a base") }
if let found = byID[id] {
base = found
} else if let found = external(id) {
@@ -151,7 +152,7 @@ public enum Pack {
return object
}
- // Les deltas par identifiant peuvent pointer vers un delta pas encore résolu : plusieurs passes.
+ // Ref-deltas may point to a delta that is not resolved yet: several passes.
var pending = order.filter { resolved[$0] == nil }
while !pending.isEmpty {
var next = [Int]()
@@ -168,7 +169,7 @@ public enum Pack {
}
}
}
- if next.count == pending.count { throw firstError ?? GitError.malformed("paquet : deltas") }
+ if next.count == pending.count { throw firstError ?? GitError.malformed("pack: deltas") }
pending = next
}
return order.compactMap { resolved[$0] }
@@ -179,7 +180,7 @@ public enum Pack {
func varint() throws -> Int {
var value = 0, shift = 0
while true {
- guard pos < delta.count else { throw GitError.malformed("delta tronqué") }
+ guard pos < delta.count else { throw GitError.malformed("truncated delta") }
let b = delta[pos]; pos += 1
value |= Int(b & 0x7f) << shift
shift += 7
@@ -187,7 +188,7 @@ public enum Pack {
}
}
let baseSize = try varint()
- guard baseSize == base.count else { throw GitError.malformed("delta : taille de la base") }
+ guard baseSize == base.count else { throw GitError.malformed("delta: base size") }
let resultSize = try varint()
var out = [UInt8]()
out.reserveCapacity(resultSize)
@@ -196,30 +197,30 @@ public enum Pack {
if op & 0x80 != 0 {
var offset = 0, size = 0
for i in 0..<4 where op & (1 << UInt8(i)) != 0 {
- guard pos < delta.count else { throw GitError.malformed("delta tronqué") }
+ guard pos < delta.count else { throw GitError.malformed("truncated delta") }
offset |= Int(delta[pos]) << (8 * i); pos += 1
}
for i in 0..<3 where op & (0x10 << UInt8(i)) != 0 {
- guard pos < delta.count else { throw GitError.malformed("delta tronqué") }
+ guard pos < delta.count else { throw GitError.malformed("truncated delta") }
size |= Int(delta[pos]) << (8 * i); pos += 1
}
if size == 0 { size = 0x10000 }
- guard offset + size <= base.count else { throw GitError.malformed("delta : copie hors limites") }
+ guard offset + size <= base.count else { throw GitError.malformed("delta: copy out of bounds") }
out.append(contentsOf: base[offset..<(offset + size)])
} else if op != 0 {
let size = Int(op)
- guard pos + size <= delta.count else { throw GitError.malformed("delta tronqué") }
+ guard pos + size <= delta.count else { throw GitError.malformed("truncated delta") }
out.append(contentsOf: delta[pos..<(pos + size)])
pos += size
} else {
- throw GitError.malformed("delta : instruction nulle")
+ throw GitError.malformed("delta: zero instruction")
}
}
- guard out.count == resultSize else { throw GitError.malformed("delta : taille du résultat") }
+ guard out.count == resultSize else { throw GitError.malformed("delta: result size") }
return out
}
- /// Écrit un paquet d'objets entiers (sans delta).
+ /// Writes a pack of whole objects (no deltas).
public static func write(_ objects: [GitObject]) -> [UInt8] {
var out: [UInt8] = [0x50, 0x41, 0x43, 0x4b, 0, 0, 0, 2]
let n = UInt32(objects.count)
diff --git a/Packages/DiveKit/Sources/GitLite/Store.swift b/Packages/DiveKit/Sources/GitLite/Store.swift
@@ -1,6 +1,7 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
-/// Magasin d'objets git. Les implémentations sont sûres entre fils d'exécution.
+/// Git object store. Implementations are thread-safe.
public protocol ObjectStore: AnyObject, Sendable {
func get(_ id: ObjectID) -> GitObject?
func put(_ object: GitObject) throws -> ObjectID
@@ -15,19 +16,19 @@ public extension ObjectStore {
func tree(_ id: ObjectID) throws -> [TreeEntry] {
let object = try require(id)
- guard object.type == .tree else { throw GitError.malformed("\(id.hex) n'est pas un arbre") }
+ guard object.type == .tree else { throw GitError.malformed("\(id.hex) is not a tree") }
return try Tree.parse(object.data)
}
func commit(_ id: ObjectID) throws -> Commit {
let object = try require(id)
- guard object.type == .commit else { throw GitError.malformed("\(id.hex) n'est pas un commit") }
+ guard object.type == .commit else { throw GitError.malformed("\(id.hex) is not a commit") }
return try Commit.parse(object.data)
}
func blob(_ id: ObjectID) throws -> [UInt8] {
let object = try require(id)
- guard object.type == .blob else { throw GitError.malformed("\(id.hex) n'est pas un fichier") }
+ guard object.type == .blob else { throw GitError.malformed("\(id.hex) is not a blob") }
return object.data
}
@@ -71,7 +72,7 @@ public final class MemoryObjectStore: ObjectStore, @unchecked Sendable {
}
}
-/// Magasin sur disque : un fichier par objet (`ab/cdef…`), premier octet = type, le reste = contenu.
+/// On-disk store: one file per object (`ab/cdef…`), first byte = type, the rest = content.
public final class FileObjectStore: ObjectStore, @unchecked Sendable {
public let directory: URL
private var cache = [ObjectID: GitObject]()
diff --git a/Packages/DiveKit/Sources/GitTestSupport/GitHTTPServer.swift b/Packages/DiveKit/Sources/GitTestSupport/GitHTTPServer.swift
@@ -1,8 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0-only
#if os(macOS)
import Foundation
-/// Vrai serveur git « smart HTTP » local, avec authentification Basic : un petit serveur Python qui passe les
-/// requêtes à `git http-backend`, comme le fait Apache sur le nuage Subsurface.
+/// A real local git "smart HTTP" server, with Basic authentication: a small Python server that hands the
+/// requests to `git http-backend`, as Apache does on the Subsurface cloud.
public final class GitHTTPServer {
public let port: Int
private let process: Process
@@ -53,7 +54,7 @@ print(server.server_address[1], flush=True)
server.serve_forever()
"""#
- /// `root` contient les dépôts nus servis sous `/git/…` (root/git/<nom>).
+ /// `root` holds the bare repositories served under `/git/…` (root/git/<name>).
public init(root: URL, user: String, password: String) throws {
let scriptURL = root.appendingPathComponent("server.py")
try Data(Self.script.utf8).write(to: scriptURL)
@@ -68,7 +69,7 @@ server.serve_forever()
while let byte = try output.fileHandleForReading.read(upToCount: 1)?.first, byte != 0x0a { line.append(byte) }
guard let port = Int(String(decoding: line, as: UTF8.self)) else {
process.terminate()
- throw NSError(domain: "GitHTTPServer", code: 1, userInfo: [NSLocalizedDescriptionKey: "le serveur de test n'a pas démarré"])
+ throw NSError(domain: "GitHTTPServer", code: 1, userInfo: [NSLocalizedDescriptionKey: "the test server did not start"])
}
self.port = port
}
diff --git a/Packages/DiveKit/Sources/GitTestSupport/LocalGit.swift b/Packages/DiveKit/Sources/GitTestSupport/LocalGit.swift
@@ -1,8 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0-only
#if os(macOS)
import Foundation
import GitLite
-/// Dépôt git local piloté par la commande `git`, pour confronter GitLite au vrai git.
+/// Local git repository driven by the `git` command, to check GitLite against the real git.
public struct LocalGit: Sendable {
public let directory: URL
@@ -70,13 +71,13 @@ public struct LocalGit: Sendable {
process.waitUntilExit()
while !errorReader.isFinished { usleep(1000) }
guard process.terminationStatus == 0 else {
- throw GitError.remote("git \(arguments.joined(separator: " ")) : \(String(decoding: errorData, as: UTF8.self))")
+ throw GitError.remote("git \(arguments.joined(separator: " ")): \(String(decoding: errorData, as: UTF8.self))")
}
return Array(output)
}
}
-/// Transport qui parle au vrai `git upload-pack` / `git receive-pack` en mode sans état, comme le ferait un serveur HTTP.
+/// Transport that talks to the real `git upload-pack` / `git receive-pack` in stateless mode, as an HTTP server would.
public struct LocalProcessTransport: GitTransport {
public let repository: URL
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift
@@ -1,7 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
-/// Champs d'une plongée modifiables depuis l'app.
+/// Fields of a dive that can be edited from the app.
public enum DiveField: String, Codable, Sendable, CaseIterable {
case rating, visibility, tags, site, divemaster, buddy, suit, notes
}
@@ -20,7 +21,7 @@ public struct NewDive: Codable, Sendable, Equatable {
public var visibility = 0
public var waterTemperature: Double?
public var tags: [String] = []
- /// Bouteille et lest, pour les plongées reprises d'un carnet papier.
+ /// Cylinder and weights, for dives copied from a paper logbook.
public var tank: String?
public var o2Percent: Int?
public var startBar: Double?
@@ -35,37 +36,37 @@ public struct NewDive: Codable, Sendable, Equatable {
}
}
-/// Modification en attente d'envoi. Elle se rejoue sur n'importe quel état du carnet : c'est ce qui permet de
-/// travailler hors ligne puis de s'appliquer par-dessus ce qu'un autre appareil a envoyé entre-temps.
+/// A change waiting to be sent. It can be replayed on any state of the logbook: that is what makes it possible to
+/// work offline and then apply on top of whatever another device has pushed in the meantime.
public enum LogChange: Codable, Sendable, Equatable {
- /// Valeurs texte : entiers pour les notes sur 5, UUID hexadécimal pour le lieu, étiquettes séparées par des virgules.
+ /// Text values: integers for the ratings out of 5, hexadecimal UUID for the site, comma-separated tags.
case editDive(when: Int, number: Int, fields: [String: String])
case addDive(NewDive)
case deleteDive(when: Int, number: Int)
case addSite(uuid: UInt32, name: String, latitude: Double?, longitude: Double?)
- /// Plongée venue d'un fichier externe, avec son profil complet.
+ /// Dive coming from an external file, with its full profile.
case importDive(ImportedDive, number: Int, siteUUID: UInt32?)
- /// Ne change rien d'autre que d'ajouter le fichier de réglages s'il manque.
+ /// Changes nothing except adding the settings file if it is missing.
case ensureSettings
- /// Pose ou remplace la position d'un lieu existant ; le reste de sa fiche est conservé.
+ /// Sets or replaces the position of an existing site; the rest of its record is kept.
case locateSite(uuid: UInt32, latitude: Double, longitude: Double)
- /// Retire la fiche d'un lieu (les plongées qui y étaient doivent avoir été rattachées ailleurs avant).
+ /// Removes a site record (the dives that were there must have been attached elsewhere beforehand).
case removeSite(uuid: UInt32)
- /// Change le numéro d'une plongée (le numéro est porté par le nom du fichier « Dive-N »).
+ /// Changes the number of a dive (the number is carried by the file name, "Dive-N").
case renumberDive(when: Int, number: Int, newNumber: Int)
public var summary: String {
switch self {
case .editDive(_, let number, let fields):
- return "plongée \(number) modifiée (\(fields.keys.sorted().joined(separator: ", ")))"
- case .addDive(let dive): return "plongée \(dive.number) ajoutée"
- case .deleteDive(_, let number): return "plongée \(number) supprimée"
- case .addSite(_, let name, _, _): return "lieu ajouté : \(name)"
- case .ensureSettings: return "réglages du carnet"
- case .locateSite: return "position d'un lieu"
- case .removeSite: return "lieu retiré"
- case .renumberDive(_, let number, let newNumber): return "plongée \(number) renumérotée \(newNumber)"
- case .importDive(let dive, let number, _): return "plongée \(number) importée (\(dive.model))"
+ return "dive \(number) edited (\(fields.keys.sorted().joined(separator: ", ")))"
+ case .addDive(let dive): return "dive \(dive.number) added"
+ case .deleteDive(_, let number): return "dive \(number) deleted"
+ case .addSite(_, let name, _, _): return "site added: \(name)"
+ case .ensureSettings: return "logbook settings"
+ case .locateSite: return "site position"
+ case .removeSite: return "site removed"
+ case .renumberDive(_, let number, let newNumber): return "dive \(number) renumbered \(newNumber)"
+ case .importDive(let dive, let number, _): return "dive \(number) imported (\(dive.model))"
}
}
}
@@ -76,14 +77,14 @@ public enum ChangeError: Error, Equatable, CustomStringConvertible {
public var description: String {
switch self {
- case .diveNotFound: return "la plongée n'existe plus dans le carnet"
- case .diveAlreadyExists: return "une plongée existe déjà à cette date et heure"
+ case .diveNotFound: return "the dive no longer exists in the logbook"
+ case .diveAlreadyExists: return "a dive already exists at this date and time"
}
}
}
public enum LogEditor {
- /// Ordre des lignes du fichier « Dive » tel que Subsurface l'écrit.
+ /// Order of the lines of the "Dive" file, as Subsurface writes it.
static let order = ["duration", "rating", "visibility", "wavesize", "current", "surge", "chill", "watersalinity",
"airpressure", "notrip", "invalid", "tags", "divesiteid", "divemaster", "buddy", "suit", "notes",
"cylinder", "weightsystem", "airtemp", "watertemp"]
@@ -92,7 +93,7 @@ public enum LogEditor {
field == .site ? "divesiteid" : field.rawValue
}
- /// Ligne à écrire pour un champ, ou nil si la valeur est vide (la ligne disparaît alors, comme dans Subsurface).
+ /// Line to write for a field, or nil if the value is empty (the line then disappears, as in Subsurface).
static func line(_ field: DiveField, _ value: String) -> String? {
switch field {
case .rating, .visibility:
@@ -109,8 +110,8 @@ public enum LogEditor {
}
}
- /// Réécrit seulement les lignes des champs modifiés ; tout le reste du fichier est conservé octet pour octet,
- /// y compris les lignes que cette app ne connaît pas.
+ /// Rewrites only the lines of the edited fields; everything else in the file is kept byte for byte,
+ /// including the lines this app does not know about.
static func patch(diveFile data: [UInt8], fields: [DiveField: String]) -> [UInt8] {
var lines: [(keyword: String, bytes: [UInt8])] = LogFormat.lines(data).map {
(String($0.keyword), Array(data[$0.range]))
@@ -125,7 +126,7 @@ public enum LogEditor {
let key = keyword(field)
var replacement = line(field, value).map { Array($0.utf8) }
let existing = lines.firstIndex(where: { $0.keyword == key })
- // Subsurface garde la ligne d'un texte vidé (« buddy "" ») : on fait pareil quand elle existe déjà.
+ // Subsurface keeps the line of a text that was emptied (`buddy ""`): we do the same when it already exists.
if replacement == nil, existing != nil, [.divemaster, .buddy, .suit, .notes].contains(field) {
replacement = Array("\(key) \"\"\n".utf8)
}
@@ -135,7 +136,7 @@ public enum LogEditor {
} else {
lines.remove(at: index)
}
- // Anciens carnets : le lieu écrit en clair laisse la place à la fiche de site.
+ // Old logbooks: the location written in plain text gives way to the site record.
} else if let replacement {
let position = lines.firstIndex(where: { rank($0.keyword) > rank(key) }) ?? lines.count
lines.insert((key, replacement), at: position)
@@ -147,10 +148,10 @@ public enum LogEditor {
return lines.flatMap(\.bytes)
}
- // MARK: Arbres
+ // MARK: Trees
- /// Remplace (ou retire, si `entry` est nil) l'entrée au bout de `path` et rend le nouvel arbre racine.
- /// Les dossiers intermédiaires absents sont créés ; un dossier vidé est retiré de son parent.
+ /// Replaces (or removes, if `entry` is nil) the entry at the end of `path` and returns the new root tree.
+ /// Missing intermediate directories are created; a directory left empty is removed from its parent.
static func replacing(root: ObjectID?, path: [String], with entry: TreeEntry?, store: ObjectStore) throws -> ObjectID? {
guard let name = path.first else { return entry?.id }
var entries = try root.map { try store.tree($0) } ?? []
@@ -168,7 +169,7 @@ public enum LogEditor {
return try store.putTree(entries)
}
- /// Construit un arbre complet à partir de fichiers « chemin → contenu ».
+ /// Builds a complete tree from "path → content" files.
public static func buildTree(files: [String: String], store: ObjectStore) throws -> ObjectID {
var blobs = [TreeEntry]()
var folders = [String: [String: String]]()
@@ -186,7 +187,7 @@ public enum LogEditor {
return try store.putTree(blobs)
}
- /// Chemin et nom du dossier d'une plongée ajoutée par l'app.
+ /// Path and name of the directory of a dive added by the app.
public static func diveDirectory(when: Int) -> String { divePath(when: when).joined(separator: "/") }
static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
@@ -225,11 +226,11 @@ public enum LogEditor {
return text
}
- /// Ordinateur « plongée ajoutée à la main » : profil en trapèze, comme le fait Subsurface.
+ /// "Manually added dive" computer: trapezoid profile, as Subsurface does.
static func computerFile(_ dive: NewDive) -> String {
let duration = max(dive.durationSeconds, 60)
let depth = max(dive.maxDepth, 0)
- // Descente à 18 m/min, remontée à 9 m/min, bornées à un tiers de la plongée chacune.
+ // Descent at 18 m/min, ascent at 9 m/min, each capped at a third of the dive.
let descent = min(Int((depth / 18 * 60).rounded()), duration / 3)
let ascent = min(Int((depth / 9 * 60).rounded()), duration / 3)
let bottom = duration - descent - ascent
@@ -257,9 +258,9 @@ public enum LogEditor {
return text
}
- /// Applique une modification à l'arbre racine (nil = carnet vide) et rend le nouvel arbre.
+ /// Applies a change to the root tree (nil = empty logbook) and returns the new tree.
public static func apply(_ change: LogChange, root: ObjectID?, store: ObjectStore) throws -> ObjectID {
- // Un carnet a toujours son fichier de réglages ; un compte neuf (dépôt vide) n'en a pas encore.
+ // A logbook always has its settings file; a brand-new account (empty repository) does not have one yet.
var entries = try root.map { try store.tree($0) } ?? []
if !entries.contains(where: { $0.name == "00-Subsurface" }) {
entries.append(.blob("00-Subsurface", try store.putBlob("version 3\n")))
@@ -305,7 +306,7 @@ public enum LogEditor {
if let index = lines.firstIndex(where: { $0.keyword == "gps" }) {
lines[index].bytes = gps
} else {
- // Ordre de Subsurface : name, description, notes, gps, geo.
+ // Subsurface order: name, description, notes, gps, geo.
let position = lines.firstIndex(where: { $0.keyword == "geo" }) ?? lines.count
lines.insert((keyword: "gps", bytes: gps), at: position)
}
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Format.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Format.swift
@@ -1,11 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
-/// Une ligne logique d'un fichier du carnet : le texte hors chaînes (chaque chaîne y est réduite à son guillemet
-/// ouvrant), les chaînes décodées, et la position de la ligne dans le fichier d'origine.
+/// A logical line of a logbook file: the text outside strings (each string is reduced to its opening
+/// quote there), the decoded strings, and the position of the line in the original file.
struct LogLine {
var text: String
var strings: [String]
- var range: Range<Int> // octets, saut de ligne final compris
+ var range: Range<Int> // bytes, trailing newline included
var keyword: Substring { text.prefix { $0 != " " } }
var argument: Substring {
@@ -15,8 +16,8 @@ struct LogLine {
}
enum LogFormat {
- /// Découpe un fichier en lignes logiques, comme le lecteur de Subsurface : une chaîne entre guillemets peut
- /// s'étendre sur plusieurs lignes physiques (suite marquée par une tabulation).
+ /// Splits a file into logical lines, like the Subsurface reader: a quoted string may
+ /// span several physical lines (continuation marked by a tab).
static func lines(_ data: [UInt8], skipSamples: Bool = false) -> [LogLine] {
var out = [LogLine]()
var pos = 0
@@ -24,12 +25,12 @@ enum LogFormat {
while pos < end {
let start = pos
let first = data[pos]
- // Ligne vide ou commençant par une tabulation : reste d'un conflit de fusion, ignorée.
+ // Empty line or line starting with a tab: leftover of a merge conflict, ignored.
if first == 0x0a || first == 0x09 {
while pos < end { pos += 1; if data[pos - 1] == 0x0a { break } }
continue
}
- // Échantillons du profil : la masse des données, sans chaînes ; on peut les sauter d'un bloc.
+ // Profile samples: the bulk of the data, without strings; they can be skipped in one go.
if skipSamples, first == 0x20 || (first >= 0x30 && first <= 0x39) {
while pos < end { pos += 1; if data[pos - 1] == 0x0a { break } }
continue
@@ -64,7 +65,7 @@ enum LogFormat {
return out
}
- /// Met une chaîne entre guillemets comme Subsurface l'écrit.
+ /// Quotes a string the way Subsurface writes it.
static func quote(_ value: String) -> String {
var out = "\""
let bytes = Array(value.utf8)
@@ -93,7 +94,7 @@ enum LogFormat {
return out + "\""
}
- /// Nombre en tête de texte, à la manière de strtod (le reste, unité comprise, est ignoré).
+ /// Number at the start of a text, strtod-style (the rest, unit included, is ignored).
static func number<S: StringProtocol>(_ text: S) -> Double {
var digits = ""
var seenDot = false
@@ -110,7 +111,7 @@ enum LogFormat {
static func integer<S: StringProtocol>(_ text: S) -> Int { Int(number(text)) }
- /// « m:ss » en secondes.
+ /// "m:ss" in seconds.
static func duration<S: StringProtocol>(_ text: S) -> Int {
let parts = text.split(separator: ":", maxSplits: 1)
let m = parts.first.map { integer($0) } ?? 0
@@ -118,7 +119,7 @@ enum LogFormat {
return m * 60 + s
}
- /// Millièmes écrits comme Subsurface : au moins une décimale, zéros de fin retirés (« 12.5 », « 3.0 »).
+ /// Thousandths written like Subsurface: at least one decimal, trailing zeros removed ("12.5", "3.0").
static func milli(_ value: Int) -> String {
let sign = value < 0 ? "-" : ""
let v = abs(value)
@@ -132,14 +133,14 @@ enum LogFormat {
static func minutes(_ seconds: Int) -> String { "\(seconds / 60):" + String(format: "%02d", seconds % 60) }
- /// Empreinte stable d'un texte (FNV-1a, 32 bits).
+ /// Stable hash of a text (FNV-1a, 32 bits).
static func stableHash(_ text: String) -> UInt32 {
var hash: UInt32 = 2_166_136_261
for byte in text.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 }
return hash
}
- /// Découpe « clé=valeur clé2="chaîne" mot » ; les chaînes viennent de la liste décodée de la ligne.
+ /// Splits `key=value key2="string" word`; the strings come from the decoded list of the line.
static func keyValues<S: StringProtocol>(_ text: S, strings: [String]) -> [(key: String, value: String)] {
var out = [(String, String)]()
var next = 0
@@ -153,7 +154,7 @@ enum LogFormat {
}
out.append((key, value))
} else if token.hasPrefix("\"") {
- // Chaîne isolée (liste d'étiquettes, par exemple) : consommée, sans clé.
+ // Standalone string (a list of tags, for example): consumed, without a key.
out.append(("", next < strings.count ? strings[next] : ""))
next += 1
} else {
@@ -164,7 +165,7 @@ enum LogFormat {
}
}
-/// Calendrier des heures « naïves » de Subsurface : tout se calcule en UTC.
+/// Calendar for Subsurface's "naive" times: everything is computed in UTC.
public enum NaiveTime {
public static let calendar: Calendar = {
var c = Calendar(identifier: .gregorian)
@@ -181,7 +182,7 @@ public enum NaiveTime {
calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekday], from: Date(timeIntervalSince1970: TimeInterval(when)))
}
- /// Heure locale actuelle exprimée en heure naïve.
+ /// Current local time expressed as a naive time.
public static func now(in zone: TimeZone = .current) -> Int {
let date = Date()
return Int(date.timeIntervalSince1970) + zone.secondsFromGMT(for: date)
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift
@@ -1,18 +1,19 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
import SQLite3
-/// Plongée lue dans un fichier externe, avec son profil complet, prête à entrer dans le carnet.
+/// Dive read from an external file, with its full profile, ready to enter the logbook.
public struct ImportedDive: Codable, Sendable, Equatable, Identifiable {
public struct Sample: Codable, Sendable, Equatable {
- public var time: Int // secondes
- public var depth: Double // mètres
+ public var time: Int // seconds
+ public var depth: Double // metres
public var temperature: Double? // °C
- public var pressure1: Double? // bar, émetteur 1
- public var pressure2: Double? // bar, émetteur 2
- public var stopDepth = 0.0 // mètres ; 0 = pas de palier
- public var decoTime = 0 // secondes : durée du palier, ou marge sans palier
- public var tts = 0 // secondes
+ public var pressure1: Double? // bar, transmitter 1
+ public var pressure2: Double? // bar, transmitter 2
+ public var stopDepth = 0.0 // metres; 0 = no stop
+ public var decoTime = 0 // seconds: stop duration, or no-decompression limit
+ public var tts = 0 // seconds
public var cns = 0 // %
public var o2 = 21 // %
public var he = 0 // %
@@ -29,7 +30,7 @@ public struct ImportedDive: Codable, Sendable, Equatable, Identifiable {
public var serial = ""
public var sourceID = ""
public var site = ""
- /// Position du lieu quand le fichier la donne.
+ /// Position of the site when the file provides it.
public var latitude: Double?
public var longitude: Double?
public var buddy = ""
@@ -48,9 +49,9 @@ public struct ImportedDive: Codable, Sendable, Equatable, Identifiable {
public var maxDepth: Double { samples.map(\.depth).max() ?? 0 }
public var minTemperature: Double? { samples.compactMap(\.temperature).min() }
- /// Réunit plusieurs immersions rapprochées en une seule plongée, comme la fusion de Subsurface : les profils
- /// se suivent sur une même ligne de temps, séparés par leur intervalle en surface. La durée est le temps passé
- /// sous l'eau ; lieu, binôme et notes viennent de la première immersion qui en a.
+ /// Joins several closely spaced immersions into a single dive, like Subsurface's merge: the profiles
+ /// follow one another on the same timeline, separated by their surface interval. The duration is the time spent
+ /// underwater; site, buddy and notes come from the first immersion that has them.
public static func merged(_ dives: [ImportedDive]) -> ImportedDive? {
let ordered = dives.sorted { $0.when < $1.when }
guard var result = ordered.first else { return nil }
@@ -66,7 +67,7 @@ public struct ImportedDive: Codable, Sendable, Equatable, Identifiable {
for dive in ordered {
let offset = dive.when - result.when
if let last = samples.last, let first = dive.samples.first {
- // Retour en surface après l'immersion précédente, puis surface jusqu'au départ de la suivante.
+ // Back to the surface after the previous immersion, then at the surface until the next one starts.
var up = last
up.time = last.time + 10
up.depth = 0
@@ -91,13 +92,13 @@ public struct ImportedDive: Codable, Sendable, Equatable, Identifiable {
return result
}
- /// Profondeur moyenne sous l'eau (les passages en surface d'une plongée fusionnée ne comptent pas).
+ /// Mean depth underwater (the surface intervals of a merged dive do not count).
public var meanDepth: Double {
let wet = samples.filter { $0.depth > 0 }
return wet.isEmpty ? 0 : wet.reduce(0) { $0 + $1.depth } / Double(wet.count)
}
- /// Mélanges respirés, dans l'ordre où ils apparaissent.
+ /// Gas mixes breathed, in the order they appear.
public var gases: [GasMix] {
var list = [GasMix]()
for sample in samples where sample.o2 > 0 || sample.he > 0 {
@@ -115,15 +116,15 @@ public enum ImportError: Error, Equatable, CustomStringConvertible {
public var description: String {
switch self {
- case .unknownFormat: return "Format de fichier non reconnu. Formats acceptés : export Shearwater Cloud (.zip ou dive_data.db) et base de Dive Shearwater (watermelon.db)."
- case .unreadable(let why): return "Fichier illisible : \(why)"
- case .empty: return "Aucune plongée dans ce fichier."
+ case .unknownFormat: return "Unrecognized file format. Supported formats: Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db)."
+ case .unreadable(let why): return "Unreadable file: \(why)"
+ case .empty: return "No dive in this file."
}
}
}
public enum DiveImporter {
- /// Reconnaît le format d'un fichier et en tire les plongées, de la plus récente à la plus ancienne.
+ /// Detects the format of a file and extracts its dives, from the most recent to the oldest.
public static func dives(from data: [UInt8]) throws -> [ImportedDive] {
var database = data
if ZipArchive.isZip(data) {
@@ -142,12 +143,12 @@ public enum DiveImporter {
}
}
-/// Export de Shearwater Cloud : base SQLite `dive_data.db`, journaux au format PNF (enregistrements de 32 octets,
-/// compressés en gzip). Disposition des champs d'après libdivecomputer (`shearwater_predator_parser.c`).
+/// Shearwater Cloud export: SQLite database `dive_data.db`, logs in the PNF format (32-byte records,
+/// gzip-compressed). Field layout taken from libdivecomputer (`shearwater_predator_parser.c`).
enum ShearwaterCloud {
- /// Lit l'une des deux bases de Shearwater : l'export de Shearwater Cloud (`log_data` + `dive_details`, journaux
- /// en blob) ou la base de l'app Dive Shearwater (`dive_log_data` + `dive_details` + `geo_site` + `dive_buddy`,
- /// journaux en base64). Les journaux sont les mêmes dans les deux.
+ /// Reads either of the two Shearwater databases: the Shearwater Cloud export (`log_data` + `dive_details`, logs
+ /// as blobs) or the database of the Dive Shearwater app (`dive_log_data` + `dive_details` + `geo_site` +
+ /// `dive_buddy`, logs in base64). The logs are the same in both.
static func dives(database: [UInt8]) throws -> [ImportedDive] {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString).db")
try Data(database).write(to: url)
@@ -156,11 +157,11 @@ enum ShearwaterCloud {
var handle: OpaquePointer?
guard sqlite3_open_v2(url.path, &handle, SQLITE_OPEN_READONLY, nil) == SQLITE_OK, let db = handle else {
sqlite3_close(handle)
- throw ImportError.unreadable("base de données")
+ throw ImportError.unreadable("database")
}
defer { sqlite3_close(db) }
- // Colonnes rendues, dans l'ordre : identifiant, modèle, journal, format, date, durée, lieu, binômes, notes, série.
+ // Columns returned, in order: identifier, model, log, format, date, duration, site, buddies, notes, serial.
let cloud = """
select l.log_id, l.file_name, l.data_bytes_1, l.format, d.DiveDate, d.DiveLengthTime,
coalesce(nullif(d.Site, ''), d.Location), d.Buddy, d.Notes, d.SerialNumber
@@ -215,7 +216,7 @@ enum ShearwaterCloud {
let identifier = text(0)
let when: Int?
if fromApp {
- // L'identifiant se termine par l'heure de début (locale, à la seconde) ; la fiche l'arrondit à la minute.
+ // The identifier ends with the start time (local, to the second); the details record rounds it to the minute.
when = timestamp(fromIdentifier: identifier) ?? Int(text(4))
} else {
when = timestamp(text(4)) ?? timestamp(fromFileName: text(1))
@@ -246,7 +247,7 @@ enum ShearwaterCloud {
return out
}
- /// Identifiant de journal Shearwater : 9 chiffres fixes puis l'heure de début en secondes.
+ /// Shearwater log identifier: 9 fixed digits, then the start time in seconds.
static func timestamp(fromIdentifier identifier: String) -> Int? {
guard identifier.count == 19, identifier.allSatisfy(\.isNumber), let value = Int(identifier.suffix(10)),
value > 946_684_800, value < 4_102_444_800 else { return nil }
@@ -260,7 +261,7 @@ enum ShearwaterCloud {
second: numbers.count > 5 ? numbers[5] : 0)
}
- /// « Petrel 3[B72CDA1C]#9 2025-9-6 11-27-54.swlogzp »
+ /// "Petrel 3[B72CDA1C]#9 2025-9-6 11-27-54.swlogzp"
static func timestamp(fromFileName name: String) -> Int? {
guard let hash = name.firstIndex(of: "#"), let space = name[hash...].firstIndex(of: " ") else { return nil }
return timestamp(String(name[space...]))
@@ -314,7 +315,7 @@ enum ShearwaterCloud {
sample.he = Int(record[start + 9])
sample.decoTime = Int(record[start + 10]) * 60
sample.cns = Int(record[start + 23])
- // Pression des émetteurs : 12 bits de poids faible, en unités de 2 psi ; ≥ 0xFFF0 = pas de mesure.
+ // Transmitter pressure: low-order 12 bits, in units of 2 psi; ≥ 0xFFF0 = no reading.
func pressure(_ offset: Int) -> Double? {
let raw = be16(record, offset)
guard raw < 0xFFF0, raw & 0x0FFF != 0 else { return nil }
@@ -328,7 +329,7 @@ enum ShearwaterCloud {
}
extension LogEditor {
- /// Fichier « Dive » d'une plongée importée.
+ /// "Dive" file of an imported dive.
static func diveFile(_ dive: ImportedDive, siteUUID: UInt32?) -> String {
var text = "duration \(LogFormat.minutes(dive.durationSeconds)) min\n"
if let siteUUID, let line = line(.site, String(siteUUID, radix: 16)) { text += line }
@@ -349,7 +350,7 @@ extension LogEditor {
return text
}
- /// Fichier « Divecomputer » d'une plongée importée ; les valeurs ne sont écrites que lorsqu'elles changent.
+ /// "Divecomputer" file of an imported dive; values are only written when they change.
static func computerFile(_ dive: ImportedDive) -> String {
var text = "model \(LogFormat.quote(dive.model))\n"
text += "maxdepth \(LogFormat.milli(dive.maxDepth))m\n"
@@ -360,7 +361,7 @@ extension LogEditor {
if !dive.serial.isEmpty { text += "keyvalue \"Serial\" \(LogFormat.quote(dive.serial))\n" }
if let model = dive.decoModel { text += "keyvalue \"Deco model\" \(LogFormat.quote(model))\n" }
- // Changements de gaz.
+ // Gas changes.
let gases = dive.gases
var current: GasMix?
var first = true
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Loader.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Loader.swift
@@ -1,7 +1,8 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
-/// Dossier de plongée repéré dans l'arbre du dépôt.
+/// Dive directory found in the repository tree.
struct DiveDirectory {
var path: [String]
var tree: ObjectID
@@ -9,12 +10,12 @@ struct DiveDirectory {
var tripID: String?
}
-/// Parcours de l'arbre git d'un carnet Subsurface :
-/// `aaaa/mm/[jj-Voyage~hex/][[aaaa-]mm-]jj-Jour-hh=mm=ss[~hex]/{Dive-N, Divecomputer…}`.
+/// Walks the git tree of a Subsurface logbook:
+/// `yyyy/mm/[dd-Trip~hex/][[yyyy-]mm-]dd-Day-hh=mm=ss[~hex]/{Dive-N, Divecomputer…}`.
enum LogWalker {
static func nonUnique(_ name: String) -> Substring { name.prefix { $0 != "~" } }
- /// Date et heure d'un dossier de plongée, ou nil si le nom n'en est pas un.
+ /// Date and time of a dive directory, or nil if the name is not one.
static func diveTime(name: String, year: Int?, month: Int?) -> Int? {
let base = Array(nonUnique(name).utf8)
guard base.count >= 15 else { return nil }
@@ -25,11 +26,11 @@ enum LogWalker {
let time = String(decoding: base[timeStart...], as: UTF8.self)
let hms = time.split(whereSeparator: { $0 == ":" || $0 == "=" }).compactMap { Int($0) }
guard hms.count == 3, (0..<24).contains(hms[0]), (0..<60).contains(hms[1]), (0...60).contains(hms[2]) else { return nil }
- // Avant l'heure : [[aaaa-]mm-]jj-Jour
+ // Before the time: [[yyyy-]mm-]dd-Day
let head = String(decoding: base[..<(timeStart - 1)], as: UTF8.self)
var fields = head.split(separator: "-").map(String.init)
guard fields.count >= 2 else { return nil }
- fields.removeLast() // jour de la semaine
+ fields.removeLast() // day of the week
guard let day = Int(fields.removeLast()) else { return nil }
var y = year, m = month
if let last = fields.popLast(), let value = Int(last) { m = value }
@@ -68,7 +69,7 @@ enum LogWalker {
return out
}
- /// Dossier de la plongée `when` (et numéro `number` s'il y a des homonymes).
+ /// Directory of the dive at `when` (and with number `number` if several share that time).
static func find(when: Int, number: Int?, root: ObjectID, store: ObjectStore) throws -> DiveDirectory? {
let matches = try diveDirectories(root: root, store: store).filter { $0.when == when }
if matches.count > 1, let number {
@@ -80,7 +81,7 @@ enum LogWalker {
return matches.first
}
- /// Numéro porté par « Dive-12 » ou « Dive-12~abcdef0 » ; nil si ce n'est pas le fichier de plongée.
+ /// Number carried by "Dive-12" or "Dive-12~abcdef0"; nil if this is not the dive file.
static func diveNumber(fileName: String) -> Int? {
guard fileName.hasPrefix("Dive"), !fileName.hasPrefix("Divecomputer") else { return nil }
let suffix = nonUnique(fileName).dropFirst(4)
@@ -91,7 +92,7 @@ enum LogWalker {
}
public enum LogLoader {
- /// Lit tout le carnet à partir de l'arbre racine. Les profils (échantillons) ne sont pas chargés : voir `loadProfile`.
+ /// Reads the whole logbook from the root tree. Profiles (samples) are not loaded: see `loadProfile`.
public static func load(root: ObjectID, store: ObjectStore) throws -> Logbook {
var log = Logbook()
let rootEntries = try store.tree(root)
@@ -106,7 +107,7 @@ public enum LogLoader {
}
}
if log.settings.version > 3 {
- log.warnings.append("Carnet enregistré dans un format plus récent (version \(log.settings.version)).")
+ log.warnings.append("Logbook saved in a newer format (version \(log.settings.version)).")
}
}
@@ -125,7 +126,7 @@ public enum LogLoader {
}
log.dives.append(try loadDive(directory, store: store, log: &log))
} catch {
- log.warnings.append("Plongée illisible (\(directory.path.joined(separator: "/"))) : \(error)")
+ log.warnings.append("Unreadable dive (\(directory.path.joined(separator: "/"))): \(error)")
}
}
log.dives.sort { ($0.when, $0.number) > ($1.when, $1.number) }
@@ -165,7 +166,7 @@ public enum LogLoader {
site.longitude = LogFormat.number(parts[1])
}
case "geo":
- // « geo cat 2 origin 0 "Canada" » : la catégorie 2 est le pays.
+ // `geo cat 2 origin 0 "Canada"`: category 2 is the country.
let parts = line.argument.split(separator: " ")
if parts.count >= 2, parts[0] == "cat", parts[1] == "2" { site.country = line.strings.first }
default: break
@@ -191,7 +192,7 @@ public enum LogLoader {
parseDive(try store.blob(entry.id), into: &dive, location: &legacyLocation, gps: &legacyGPS)
}
}
- // Anciens carnets : lieu et position écrits dans la plongée, sans fiche de site.
+ // Old logbooks: location and position written in the dive, without a site record.
if dive.siteUUID == nil, legacyLocation != nil || legacyGPS != nil {
let name = legacyLocation ?? ""
if let existing = log.sites.values.first(where: { !name.isEmpty && $0.name == name }) {
@@ -332,7 +333,7 @@ public enum LogLoader {
return event
}
- /// Un échantillon reprend les valeurs du précédent (sauf la pression des bouteilles, qui s'interpole).
+ /// A sample carries over the values of the previous one (except cylinder pressure, which is interpolated).
static func parseSample(_ text: String, previous: Sample?) -> Sample {
var sample = previous ?? Sample()
sample.pressures = []
@@ -378,7 +379,7 @@ public enum LogLoader {
return sample
}
- /// Charge les profils complets des ordinateurs d'une plongée.
+ /// Loads the full profiles of the computers of a dive.
public static func loadProfile(of dive: Dive, store: ObjectStore) throws -> [DiveComputer] {
try dive.computerBlobs.map { parseComputer(try store.blob($0), withSamples: true) }
}
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Model.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Model.swift
@@ -1,8 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
public struct GasMix: Sendable, Equatable, Codable, Hashable {
- /// Pour mille ; 0 = air pour l'oxygène.
+ /// Per mille; 0 = air for oxygen.
public var o2Permille: Int
public var hePermille: Int
@@ -16,7 +17,7 @@ public struct GasMix: Sendable, Equatable, Codable, Hashable {
public var o2Fraction: Double { o2Permille == 0 ? 0.209 : Double(o2Permille) / 1000 }
public var heFraction: Double { Double(hePermille) / 1000 }
- /// « Air », « EAN32 », « 18/45 », « Oxygène »
+ /// "Air", "EAN32", "18/45", "O₂"
public var label: String {
if isAir { return "Air" }
let o2 = Int((Double(o2Permille) / 10).rounded())
@@ -45,11 +46,11 @@ public struct WeightSystem: Sendable, Equatable, Codable {
}
public struct Sample: Sendable, Equatable {
- public var time = 0 // secondes
- public var depth = 0.0 // mètres
- public var temperature: Double? // °C, reporté d'un échantillon à l'autre
- public var pressures: [SensorPressure] = [] // seulement quand l'ordinateur en donne une
- public var ndl: Int? // secondes
+ public var time = 0 // seconds
+ public var depth = 0.0 // metres
+ public var temperature: Double? // °C, carried over from one sample to the next
+ public var pressures: [SensorPressure] = [] // only when the computer reports one
+ public var ndl: Int? // seconds
public var tts: Int?
public var inDeco = false
public var stopDepth: Double?
@@ -118,17 +119,17 @@ public struct DiveSite: Sendable, Equatable, Identifiable {
}
public struct Trip: Sendable, Equatable, Identifiable {
- public var id: String // chemin du dossier dans le dépôt
+ public var id: String // path of the directory in the repository
public var location = ""
public var notes = ""
public init(id: String) { self.id = id }
}
-/// Une plongée. Les heures de Subsurface sont des heures locales « naïves », stockées comme si elles étaient UTC.
+/// A dive. Subsurface times are "naive" local times, stored as if they were UTC.
public struct Dive: Sendable, Equatable, Identifiable {
- public var when: Int // secondes depuis 1970, heure locale naïve
+ public var when: Int // seconds since 1970, naive local time
public var number = 0
- public var path: [String] = [] // dossiers jusqu'à celui de la plongée
+ public var path: [String] = [] // directories down to the dive's own
public var diveFile = "Dive"
public var diveBlob: ObjectID?
public var computerBlobs: [ObjectID] = []
@@ -153,7 +154,7 @@ public struct Dive: Sendable, Equatable, Identifiable {
public var airTemperatureOverride: Double?
public var waterTemperatureOverride: Double?
- /// En-têtes des ordinateurs (sans échantillons tant que `loadProfile` n'a pas été appelé).
+ /// Headers of the dive computers (without samples until `loadProfile` has been called).
public var computers: [DiveComputer] = []
public init(when: Int) { self.when = when }
@@ -169,7 +170,7 @@ public struct Dive: Sendable, Equatable, Identifiable {
public var computerModel: String? { computers.first(where: { !$0.model.isEmpty && !$0.isManual })?.model }
public var isManual: Bool { computers.allSatisfy { $0.isManual } }
- /// Consommation en surface, en litres par minute (gaz parfait, première bouteille renseignée).
+ /// Surface air consumption, in litres per minute (ideal gas, cylinders with volume and pressures filled in).
public var sac: Double? {
guard durationSeconds > 0, let mean = meanDepth, mean > 0 else { return nil }
var liters = 0.0
@@ -190,7 +191,7 @@ public struct LogSettings: Sendable, Equatable {
}
public struct Logbook: Sendable, Equatable {
- public var dives: [Dive] = [] // de la plus récente à la plus ancienne
+ public var dives: [Dive] = [] // from the most recent to the oldest
public var sites: [UInt32: DiveSite] = [:]
public var trips: [String: Trip] = [:]
public var settings = LogSettings()
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/RemoraImport.swift b/Packages/DiveKit/Sources/SubsurfaceLog/RemoraImport.swift
@@ -1,8 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
-/// Plongées déposées par Open Rémora (ordinateur de plongée pour Apple Watch) dans le dossier partagé du groupe
-/// d'apps. Contrat : `docs/PARTAGE.md` du dépôt open-remora. On lit le JSON (`DiveLog` de RemoraDeco) sans dépendre
-/// de ce paquet : seuls les champs utiles au carnet sont décodés, les autres sont ignorés.
+/// Dives dropped by Open Rémora (a dive computer for Apple Watch) into the shared folder of the app group.
+/// Contract: `docs/PARTAGE.md` in the open-remora repository. The JSON (`DiveLog` from RemoraDeco) is read without
+/// depending on that package: only the fields useful to the logbook are decoded, the others are ignored.
public enum RemoraImport {
public static let appGroup = "group.org.schurger.dive"
public static let folder = "OpenRemora/Plongees"
@@ -36,16 +37,23 @@ public enum RemoraImport {
let longitude: Double?
}
- static let warnings = ["ascentFast": "remontée rapide", "ascentTooFast": "remontée trop rapide", "ceilingViolated": "plafond franchi",
- "ppO2High": "ppO2 élevée", "ppO2Critical": "ppO2 critique", "missedSafetyStop": "palier de sécurité sauté"]
+ /// Default (English) labels of the Open Rémora alarms, keyed by the warning identifier found in the JSON.
+ /// The labels end up in the dive notes, so an app passes its own localized dictionary to `dive(fromJSON:)`.
+ public static let defaultAlarmLabels = ["ascentFast": "fast ascent", "ascentTooFast": "ascent too fast",
+ "ceilingViolated": "ceiling violated", "ppO2High": "high ppO2",
+ "ppO2Critical": "critical ppO2", "missedSafetyStop": "missed safety stop"]
- /// Décode une plongée. L'heure d'Open Rémora est un instant absolu ; le carnet Subsurface garde l'heure locale
- /// « naïve », d'où le fuseau à appliquer (celui de l'appareil au moment de la plongée, par défaut).
- public static func dive(fromJSON data: Data, timeZone: TimeZone = .current) throws -> ImportedDive {
+ /// Decodes a dive. Open Rémora's time is an absolute instant; the Subsurface logbook keeps the "naive" local
+ /// time, hence the time zone to apply (by default, the device's at the time of the dive).
+ /// The alarms are appended to the notes as `alarmsPrefix` followed by "m:ss label" entries; `alarmLabels` maps
+ /// each warning identifier to its label (an identifier missing from the dictionary is written as is).
+ public static func dive(fromJSON data: Data, timeZone: TimeZone = .current,
+ alarmLabels: [String: String] = RemoraImport.defaultAlarmLabels,
+ alarmsPrefix: String = "Alarms: ") throws -> ImportedDive {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let log = try decoder.decode(Log.self, from: data)
- guard log.source != "simulation" else { throw ImportError.unreadable("plongée de démonstration") }
+ guard log.source != "simulation" else { throw ImportError.unreadable("demo dive") }
guard let last = log.samples.last else { throw ImportError.empty }
let when = Int(log.start.timeIntervalSince1970.rounded()) + timeZone.secondsFromGMT(for: log.start)
@@ -74,7 +82,7 @@ public enum RemoraImport {
out.stopDepth = stop
out.decoTime = (sample.stopMinutes ?? 0) * 60
} else {
- // nil = marge sans palier illimitée : 99 minutes, comme l'affichent les ordinateurs.
+ // nil = unlimited no-decompression limit: 99 minutes, as dive computers display it.
out.decoTime = Int(min(sample.noDecompressionLimit ?? 99, 99).rounded()) * 60
}
if let previous = dive.samples.last, out.time <= previous.time { continue }
@@ -85,21 +93,21 @@ public enum RemoraImport {
if let text = log.notes, !text.isEmpty { notes.append(text) }
let alarms = (log.events ?? []).map { event -> String in
let seconds = Int(event.time.rounded())
- return "\(seconds / 60):" + String(format: "%02d", seconds % 60) + " \(warnings[event.warning] ?? event.warning)"
+ return "\(seconds / 60):" + String(format: "%02d", seconds % 60) + " \(alarmLabels[event.warning] ?? event.warning)"
}
- if !alarms.isEmpty { notes.append("Alarmes : " + alarms.joined(separator: ", ")) }
+ if !alarms.isEmpty { notes.append(alarmsPrefix + alarms.joined(separator: ", ")) }
dive.notes = notes.joined(separator: "\n")
return dive
}
- /// Fichiers JSON en attente dans le dossier partagé.
+ /// JSON files waiting in the shared folder.
public static func pendingFiles(in directory: URL) -> [URL] {
((try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [])
.filter { $0.pathExtension.lowercased() == "json" }
.sorted { $0.lastPathComponent < $1.lastPathComponent }
}
- /// Retire les deux fichiers d'une plongée (JSON et UDDF) : Open Rémora compte les JSON restants comme « en attente ».
+ /// Removes both files of a dive (JSON and UDDF): Open Rémora counts the remaining JSON files as "pending".
public static func consume(_ json: URL) {
try? FileManager.default.removeItem(at: json)
try? FileManager.default.removeItem(at: json.deletingPathExtension().appendingPathExtension("uddf"))
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift
@@ -1,18 +1,19 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
-/// Adresses du nuage Subsurface (stockage git en HTTPS, authentification Basic courriel + mot de passe).
+/// Addresses of the Subsurface cloud (git storage over HTTPS, Basic authentication with email + password).
public enum SubsurfaceCloud {
public static let defaultHost = "cloud.subsurface-divelog.org"
- /// Même nettoyage que Subsurface : minuscules, puis lettres, chiffres et « @ . _ + - » seulement.
+ /// Same sanitizing as Subsurface: lowercase, then letters, digits and "@ . _ + -" only.
public static func sanitize(email: String) -> String {
String(email.lowercased().unicodeScalars.filter {
($0.isASCII && ($0.properties.isAlphabetic || $0.properties.numericType != nil)) || "@._+-".unicodeScalars.contains($0)
}.map(Character.init))
}
- /// Dépôt de l'usager : `https://hôte/git/<courriel>`, branche `<courriel>`.
+ /// The user's repository: `https://host/git/<email>`, branch `<email>`.
public static func repositoryURL(email: String, host: String = defaultHost) -> URL {
URL(string: "https://\(host)/git/")!.appendingPathComponent(sanitize(email: email))
}
@@ -23,21 +24,21 @@ public enum SubsurfaceCloud {
}
}
-/// Compte du nuage Subsurface : création et vérification par le code reçu par courriel.
-/// Même échange que Subsurface (`core/cloudstorage.cpp`) : un texte « courriel mot-de-passe [code] » envoyé en POST.
+/// Subsurface cloud account: creation, and verification with the code received by email.
+/// Same exchange as Subsurface (`core/cloudstorage.cpp`): a text "email password [code]" sent by POST.
public enum CloudAccount {
public enum Status: Equatable, Sendable {
- case verified // compte prêt
- case needsPIN // un code a été envoyé par courriel
+ case verified // account ready
+ case needsPIN // a code was sent by email
case invalidPIN
- case rejected(String) // message du serveur
+ case rejected(String) // message from the server
}
public static func isValid(email: String) -> Bool {
email.count <= 254 && email.range(of: "^[a-zA-Z0-9.+_-]{1,64}@[a-zA-Z0-9.+_-]+\\.[a-zA-Z0-9+_-]{2,}$", options: .regularExpression) != nil
}
- /// Le nuage n'accepte que lettres, chiffres et « @ . + _ - » dans le mot de passe.
+ /// The cloud only accepts letters, digits and "@ . + _ -" in the password.
public static func isValid(password: String) -> Bool {
password.range(of: "^[a-zA-Z0-9@.+_-]+$", options: .regularExpression) != nil
}
@@ -48,7 +49,7 @@ public enum CloudAccount {
case "[VERIFIED]", "[OK]": return .verified
case "[VERIFY]": return .needsPIN
case "Invalid PIN": return .invalidPIN
- default: return .rejected(text.isEmpty ? "réponse vide" : String(text.prefix(200)))
+ default: return .rejected(text.isEmpty ? "empty reply" : String(text.prefix(200)))
}
}
@@ -64,7 +65,7 @@ public enum CloudAccount {
return request
}
- /// Sans `pin` : crée le compte (ou confirme qu'il existe). Avec `pin` : valide le code reçu par courriel.
+ /// Without `pin`: creates the account (or confirms that it exists). With `pin`: validates the code received by email.
public static func submit(email: String, password: String, pin: String? = nil, userAgent: String,
session: URLSession = .shared) async throws -> Status {
let data: Data
@@ -85,7 +86,7 @@ public struct SyncReport: Sendable, Equatable {
public init() {}
}
-/// Magasin qui note ce qu'on y écrit, pour savoir quels objets envoyer au serveur.
+/// Store that records what is written to it, to know which objects to send to the server.
final class RecordingStore: ObjectStore, @unchecked Sendable {
let base: ObjectStore
private var recorded = [ObjectID: GitObject]()
@@ -108,7 +109,7 @@ final class RecordingStore: ObjectStore, @unchecked Sendable {
}
}
-/// Copie locale du carnet : objets git sur disque, dernier état connu du serveur et modifications en attente.
+/// Local copy of the logbook: git objects on disk, last known state of the server, and pending changes.
public actor LogRepository {
struct State: Codable {
var head: ObjectID?
@@ -152,7 +153,7 @@ public actor LogRepository {
try state.head.map { try store.commit($0).tree }
}
- /// Arbre de travail : dernier état du serveur + modifications en attente (celles qui ne s'appliquent plus sont sautées).
+ /// Working tree: last state of the server + pending changes (those that no longer apply are skipped).
private func workingTree() throws -> ObjectID? {
var root = try headTree()
for change in state.pending {
@@ -161,7 +162,7 @@ public actor LogRepository {
return root
}
- /// Carnet tel que l'usager doit le voir, modifications locales comprises.
+ /// The logbook as the user should see it, local changes included.
public func logbook() throws -> Logbook {
guard let root = try workingTree() else { return Logbook() }
return try LogLoader.load(root: root, store: store)
@@ -171,7 +172,7 @@ public actor LogRepository {
try LogLoader.loadProfile(of: dive, store: store)
}
- /// Ajoute une modification à la file ; échoue si elle ne s'applique pas au carnet actuel.
+ /// Adds a change to the queue; fails if it does not apply to the current logbook.
@discardableResult
public func enqueue(_ change: LogChange) throws -> Logbook {
let root = try LogEditor.apply(change, root: try workingTree(), store: store)
@@ -180,8 +181,8 @@ public actor LogRepository {
return try LogLoader.load(root: root, store: store)
}
- /// Met en file les plongées importées, de la plus ancienne à la plus récente : lieux créés au besoin (retrouvés par
- /// leur nom), numéros à la suite du carnet, plongées déjà présentes laissées de côté. Rend le nombre ajouté.
+ /// Queues the imported dives, from the oldest to the most recent: sites created as needed (matched by
+ /// name), numbers continuing the logbook's, dives already present left aside. Returns the number added.
@discardableResult
public func importDives(_ dives: [ImportedDive]) throws -> Int {
var added = 0
@@ -192,7 +193,7 @@ public actor LogRepository {
if !name.isEmpty {
if let existing = log.sites.values.first(where: { $0.name.compare(name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) {
siteUUID = existing.uuid
- // Le lieu existe sans position et le fichier en donne une : on la pose.
+ // The site exists without a position and the file provides one: set it.
if !existing.hasLocation, let latitude = dive.latitude, let longitude = dive.longitude {
log = try enqueue(.locateSite(uuid: existing.uuid, latitude: latitude, longitude: longitude))
}
@@ -218,40 +219,40 @@ public actor LogRepository {
try save()
}
- /// Remplace le carnet local par un arbre construit sur place (mode démonstration, sans serveur).
+ /// Replaces the local logbook with a tree built locally (demo mode, without a server).
public func importTree(files: [String: String]) throws {
let root = try LogEditor.buildTree(files: files, store: store)
let who = Commit.signature(name: authorName, email: authorEmail)
- let commit = Commit(tree: root, parents: [], author: who, committer: who, message: "Carnet de démonstration\n")
+ let commit = Commit(tree: root, parents: [], author: who, committer: who, message: "Demo logbook\n")
state = State(head: try store.put(GitObject(type: .commit, data: commit.serialize())))
try save()
}
- /// Intègre les modifications en attente au carnet local sans rien envoyer (mode démonstration).
+ /// Commits the pending changes to the local logbook without sending anything (demo mode).
public func commitPendingLocally() throws {
guard !state.pending.isEmpty, let root = try workingTree() else { return }
let who = Commit.signature(name: authorName, email: authorEmail)
- let commit = Commit(tree: root, parents: state.head.map { [$0] } ?? [], author: who, committer: who, message: "Modifications locales\n")
+ let commit = Commit(tree: root, parents: state.head.map { [$0] } ?? [], author: who, committer: who, message: "Local changes\n")
state.head = try store.put(GitObject(type: .commit, data: commit.serialize()))
state.pending = []
try save()
}
- /// Efface la copie locale (déconnexion).
+ /// Erases the local copy (sign-out).
public func erase() throws {
state = State()
try? FileManager.default.removeItem(at: directory)
try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true)
}
- /// Récupère l'état du serveur, rejoue dessus les modifications en attente et les envoie.
+ /// Fetches the state of the server, replays the pending changes on top of it and sends them.
public func sync(transport: GitTransport, appVersion: String = "0.1") async throws -> SyncReport {
- var lastError: Error = GitError.pushRejected("trop de tentatives")
+ var lastError: Error = GitError.pushRejected("too many attempts")
for _ in 0..<3 {
do {
return try await syncOnce(transport: transport, appVersion: appVersion)
} catch let error as GitError {
- // Un autre appareil a envoyé entre notre lecture et notre envoi : on recommence.
+ // Another device pushed between our fetch and our push: start over.
guard case .pushRejected = error else { throw error }
lastError = error
}
@@ -270,7 +271,7 @@ public actor LogRepository {
try await download(remoteHead, client: client, capabilities: remote.capabilities, fresh: false)
report.downloaded = true
}
- // S'assure que tout l'arbre est là ; sinon copie fraîche.
+ // Makes sure the whole tree is there; otherwise, fresh copy.
do {
_ = try LogLoader.load(root: try store.commit(remoteHead).tree, store: store)
} catch let error as GitError {
@@ -279,15 +280,15 @@ public actor LogRepository {
report.downloaded = true
}
} else {
- // Compte sans carnet sur le serveur.
+ // Account without a logbook on the server.
state.head = nil
state.shallow = []
}
return try await finish(report: report, client: client, remoteHead: remoteHead, appVersion: appVersion)
}
- /// Télécharge l'état `remoteHead` (sans historique). D'abord en incrémental à partir de ce qu'on a déjà,
- /// puis, si le serveur refuse ou si la copie locale est incomplète, en entier.
+ /// Downloads the state `remoteHead` (without history). First incrementally from what we already have,
+ /// then, if the server refuses or the local copy is incomplete, in full.
private func download(_ remoteHead: ObjectID, client: GitClient, capabilities: Set<String>, fresh: Bool) async throws {
let known = fresh ? nil : state.head.flatMap { store.contains($0) ? $0 : nil }
var done = false
@@ -322,7 +323,7 @@ public actor LogRepository {
root = try LogEditor.apply(change, root: root, store: recorder)
applied.append(change)
} catch let error as ChangeError {
- report.dropped.append("\(change.summary) : \(error)")
+ report.dropped.append("\(change.summary): \(error)")
}
}
if let root, root != base, !applied.isEmpty {
diff --git a/Packages/DiveKit/Sources/divelog-cli/main.swift b/Packages/DiveKit/Sources/divelog-cli/main.swift
@@ -1,11 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
import SubsurfaceLog
-// Outil de vérification, hors de l'app : même code que sur l'iPhone, contre le vrai nuage Subsurface.
+// Verification tool, outside the app: the same code as on the iPhone, against the real Subsurface cloud.
// CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli list
// CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli import export.zip
-// Le mot de passe ne se passe que par l'environnement, jamais en argument.
+// The password is only ever passed through the environment, never as an argument.
func fail(_ message: String) -> Never {
FileHandle.standardError.write(Data((message + "\n").utf8))
@@ -14,25 +15,35 @@ func fail(_ message: String) -> Never {
let arguments = CommandLine.arguments.dropFirst()
let environment = ProcessInfo.processInfo.environment
-// « inspect » ne touche à aucun réseau : il montre ce qu'un fichier contient.
+// "inspect" never touches the network: it shows what a file contains.
if arguments.first == "inspect", let path = arguments.dropFirst().first {
do {
let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
- print("\(dives.count) plongées dans le fichier")
+ print("\(dives.count) dives in the file")
for dive in dives {
let c = NaiveTime.components(dive.when)
let date = String(format: "%04d-%02d-%02d %02d:%02d:%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
let pressures = dive.samples.compactMap(\.pressure1)
- print(" \(date) \(String(format: "%5.1f", dive.maxDepth)) m \(String(format: "%3d", dive.durationSeconds / 60)) min \(dive.model) \(dive.gases.map(\.label).joined(separator: "+")) \(dive.decoModel ?? "") \(Int(pressures.first ?? 0))→\(Int(pressures.last ?? 0)) bar éch=\(dive.samples.count) lieu=\(dive.site.isEmpty ? "-" : dive.site) binôme=\(dive.buddy.isEmpty ? "-" : dive.buddy) notes=\(dive.notes.count)")
+ print(" \(date) \(String(format: "%5.1f", dive.maxDepth)) m \(String(format: "%3d", dive.durationSeconds / 60)) min \(dive.model) \(dive.gases.map(\.label).joined(separator: "+")) \(dive.decoModel ?? "") \(Int(pressures.first ?? 0))→\(Int(pressures.last ?? 0)) bar samples=\(dive.samples.count) site=\(dive.site.isEmpty ? "-" : dive.site) buddy=\(dive.buddy.isEmpty ? "-" : dive.buddy) notes=\(dive.notes.count)")
}
exit(0)
} catch {
- fail("échec : \(error)")
+ fail("failed: \(error)")
}
}
guard let command = arguments.first, let email = environment["CLOUD_EMAIL"], let password = environment["CLOUD_PASSWORD"] else {
- fail("usage : CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli list | import <fichier>")
+ fail("""
+ usage: CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli <command>
+ list dives of the cloud logbook
+ table whole logbook as a markdown table
+ sites dive sites as a markdown table
+ import <file> import a file into the logbook and push
+ 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
+ usage: divelog-cli inspect <file> show what a file contains (no network)
+ """)
}
let account = SubsurfaceCloud.sanitize(email: email)
@@ -41,13 +52,13 @@ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("d
defer { try? FileManager.default.removeItem(at: directory) }
func describe(_ log: Logbook) {
- print("\(log.dives.count) plongées, \(log.sites.count) lieux, \(log.trips.count) voyages")
+ print("\(log.dives.count) dives, \(log.sites.count) sites, \(log.trips.count) trips")
for dive in log.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 site = log.site(of: dive)?.name ?? "-"
let depth = String(format: "%.1f", dive.maxDepth)
- print(" #\(dive.number) \(date) \(depth) m \(dive.durationSeconds / 60) min \(site) [\(dive.computerModel ?? "saisie")]")
+ print(" #\(dive.number) \(date) \(depth) m \(dive.durationSeconds / 60) min \(site) [\(dive.computerModel ?? "manual")]")
}
for warning in log.warnings { print(" ! \(warning)") }
}
@@ -59,35 +70,39 @@ do {
case "list":
describe(try await repository.logbook())
case "import":
- guard let path = arguments.dropFirst().first else { fail("fichier à importer manquant") }
+ guard let path = arguments.dropFirst().first else { fail("missing file to import") }
let all = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
- // Comme dans l'app : les trempettes de moins de deux minutes sont laissées de côté.
+ // As in the app: dips shorter than two minutes are left out.
let dives = all.filter { $0.durationSeconds >= 120 }
- print("fichier : \(all.count) journaux, dont \(all.count - dives.count) trempettes ignorées")
+ print("file: \(all.count) logs, of which \(all.count - dives.count) short dips ignored")
try await repository.enqueue(.ensureSettings)
let added = try await repository.importDives(dives)
- print("ajoutées au carnet : \(added) (déjà présentes : \(dives.count - added))")
+ print("added to the logbook: \(added) (already there: \(dives.count - added))")
let report = try await repository.sync(transport: transport)
- print("envoyé : \(report.sent.count) modifications, commit \(report.head?.hex ?? "-")")
- for dropped in report.dropped { print(" abandonné : \(dropped)") }
- // Relecture par une copie neuve, pour voir ce que le serveur a réellement gardé.
- let check = try LogRepository(directory: directory.appendingPathComponent("relecture"), branch: account, authorName: "Sub Rascasse", authorEmail: account)
+ print("pushed: \(report.sent.count) changes, commit \(report.head?.hex ?? "-")")
+ for dropped in report.dropped { print(" dropped: \(dropped)") }
+ // Read back through a fresh clone, to see what the server really kept.
+ let check = try LogRepository(directory: directory.appendingPathComponent("readback"), branch: account, authorName: "Sub Rascasse", authorEmail: account)
_ = try await check.sync(transport: transport)
describe(try await check.logbook())
case "table":
- // Tout le carnet en tableau markdown, de la plus ancienne à la plus récente.
+ // The whole logbook as a markdown table, from the oldest dive to the most recent.
+ // Two markers written in French in the notes of existing logbooks are data and are matched as is:
+ // "Heure non écrite sur la fiche" (the time was not written on the paper sheet, so it is a guess) and
+ // "Carnet papier N, page P (écrit n° X)" (provenance: paper logbook N, page P, written dive number X).
let log = try await repository.logbook()
func cell(_ text: String) -> String { text.replacingOccurrences(of: "|", with: "/").replacingOccurrences(of: "\n", with: " ") }
- print("| N° | Date | Heure | Lieu | Prof. | Durée | Eau | Binôme | Guide | Source |")
+ print("| No. | Date | Time | Site | Depth | Duration | Water | Buddy | Guide | Source |")
print("|---|---|---|---|---|---|---|---|---|---|")
for dive in log.dives.reversed() {
let c = NaiveTime.components(dive.when)
let date = String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
let time = String(format: "%02d:%02d", c.hour ?? 0, c.minute ?? 0)
let guessed = dive.notes.contains("Heure non écrite")
- var source = dive.computerModel ?? "saisie"
+ var source = dive.computerModel ?? "manual"
if let range = dive.notes.range(of: "Carnet papier [0-9]+, page [0-9]+( \\(écrit n° [0-9]+\\))?", options: .regularExpression) {
- source = String(dive.notes[range]).replacingOccurrences(of: "Carnet papier ", with: "carnet ").replacingOccurrences(of: ", page ", with: " p. ")
+ source = String(dive.notes[range]).replacingOccurrences(of: "Carnet papier ", with: "paper log ").replacingOccurrences(of: ", page ", with: " p. ")
+ .replacingOccurrences(of: "(écrit n° ", with: "(written no. ")
}
let temp = dive.waterTemperature.map { String(format: "%.0f °C", $0) } ?? ""
print("| \(dive.number) | \(date) | \(time)\(guessed ? " ?" : "") | \(cell(log.site(of: dive)?.name ?? "")) | \(String(format: "%.1f", dive.maxDepth)) m | \(dive.durationSeconds / 60) min | \(temp) | \(cell(dive.buddy)) | \(cell(dive.divemaster)) | \(cell(source)) |")
@@ -96,27 +111,27 @@ do {
let log = try await repository.logbook()
var counts = [UInt32: Int]()
for dive in log.dives { if let uuid = dive.siteUUID { counts[uuid, default: 0] += 1 } }
- print("| Lieu | Plongées | Latitude | Longitude |")
+ print("| Site | Dives | Latitude | Longitude |")
print("|---|---|---|---|")
for site in log.sites.values.sorted(by: { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }) {
print("| \(site.name) | \(counts[site.uuid] ?? 0) | \(site.latitude.map { String(format: "%.5f", $0) } ?? "") | \(site.longitude.map { String(format: "%.5f", $0) } ?? "") |")
}
case "apply":
- // Applique une liste de modifications (tableau JSON de LogChange) et l'envoie.
- guard let path = arguments.dropFirst().first else { fail("fichier de modifications manquant") }
+ // Applies a list of changes (JSON array of LogChange) and pushes it.
+ guard let path = arguments.dropFirst().first else { fail("missing changes file") }
let changes = try JSONDecoder().decode([LogChange].self, from: try Data(contentsOf: URL(fileURLWithPath: path)))
for change in changes { try await repository.enqueue(change) }
let report = try await repository.sync(transport: transport)
- print("envoyé : \(report.sent.count) modifications sur \(changes.count), commit \(report.head?.hex ?? "-")")
- for dropped in report.dropped { print(" abandonné : \(dropped)") }
+ print("pushed: \(report.sent.count) changes out of \(changes.count), commit \(report.head?.hex ?? "-")")
+ for dropped in report.dropped { print(" dropped: \(dropped)") }
describe(try await repository.logbook())
case "merge":
- // merge <fichier> <début> <fin> <numéro> : réunit en une plongée les immersions du fichier commencées entre
- // deux heures (secondes, heure naïve), retire du carnet celles qui y sont déjà et importe la plongée réunie.
+ // merge <file> <from> <to> <number>: merges into one dive the immersions of the file that started between
+ // two times (seconds, naive time), removes from the logbook those already there and imports the merged dive.
let rest = Array(arguments.dropFirst())
- guard rest.count == 4, let from = Int(rest[1]), let to = Int(rest[2]), let number = Int(rest[3]) else { fail("usage : merge <fichier> <début> <fin> <numéro>") }
+ guard rest.count == 4, let from = Int(rest[1]), let to = Int(rest[2]), let number = Int(rest[3]) else { fail("usage: merge <file> <from> <to> <number>") }
let parts = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: rest[0])))).filter { $0.when >= from && $0.when <= to }
- guard parts.count > 1, let merged = ImportedDive.merged(parts) else { fail("il faut au moins deux immersions dans cet intervalle") }
+ guard parts.count > 1, let merged = ImportedDive.merged(parts) else { fail("at least two immersions are needed in this interval") }
let before = try await repository.logbook()
var siteUUID: UInt32?
for part in parts {
@@ -127,22 +142,22 @@ do {
}
try await repository.enqueue(.importDive(merged, number: number, siteUUID: siteUUID))
let report = try await repository.sync(transport: transport)
- print("\(parts.count) immersions réunies : \(merged.durationSeconds / 60) min sous l'eau, \(merged.maxDepth) m, \(merged.samples.count) échantillons ; envoyé \(report.sent.count) modifications, commit \(report.head?.hex ?? "-")")
+ print("\(parts.count) immersions merged: \(merged.durationSeconds / 60) min underwater, \(merged.maxDepth) m, \(merged.samples.count) samples; pushed \(report.sent.count) changes, commit \(report.head?.hex ?? "-")")
describe(try await repository.logbook())
case "locate":
- // locate "Nom du lieu" latitude longitude
+ // locate "Site name" latitude longitude
let rest = Array(arguments.dropFirst())
- guard rest.count == 3, let latitude = Double(rest[1]), let longitude = Double(rest[2]) else { fail("usage : locate <lieu> <latitude> <longitude>") }
+ guard rest.count == 3, let latitude = Double(rest[1]), let longitude = Double(rest[2]) else { fail("usage: locate <site> <latitude> <longitude>") }
let log = try await repository.logbook()
guard let site = log.sites.values.first(where: { $0.name.compare(rest[0], options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) else {
- fail("lieu introuvable : \(rest[0])")
+ fail("site not found: \(rest[0])")
}
try await repository.enqueue(.locateSite(uuid: site.uuid, latitude: latitude, longitude: longitude))
let report = try await repository.sync(transport: transport)
- print("\(site.name) : position envoyée (\(report.sent.count) modification), commit \(report.head?.hex ?? "-")")
+ print("\(site.name): position pushed (\(report.sent.count) change), commit \(report.head?.hex ?? "-")")
default:
- fail("commande inconnue : \(command)")
+ fail("unknown command: \(command)")
}
} catch {
- fail("échec : \(error)")
+ fail("failed: \(error)")
}
diff --git a/Packages/DiveKit/Tests/GitLiteTests/GitLiteTests.swift b/Packages/DiveKit/Tests/GitLiteTests/GitLiteTests.swift
@@ -1,10 +1,11 @@
+// SPDX-License-Identifier: GPL-2.0-only
import XCTest
@testable import GitLite
import GitTestSupport
final class GitLiteTests: XCTestCase {
func testObjectIDs() throws {
- // « git hash-object » d'un fichier vide et de "hello\n"
+ // `git hash-object` of an empty file and of "hello\n"
XCTAssertEqual(GitObject(type: .blob, data: []).id.hex, "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391")
XCTAssertEqual(GitObject(type: .blob, data: Array("hello\n".utf8)).id.hex, "ce013625030ba8dba906f756967f9e9ca394464a")
XCTAssertEqual(ObjectID(hex: "ce013625030ba8dba906f756967f9e9ca394464a")?.hex, "ce013625030ba8dba906f756967f9e9ca394464a")
@@ -34,20 +35,20 @@ final class GitLiteTests: XCTestCase {
try repo.write("a-b", "3")
try repo.write("a0", "4")
try repo.write("Z", "5")
- try repo.commitAll("ordre")
+ try repo.commitAll("order")
let raw = try repo.git(["cat-file", "tree", "HEAD^{tree}"])
let entries = try Tree.parse(raw)
XCTAssertEqual(entries.map(\.name), ["Z", "a-b", "a.txt", "a", "a0"])
XCTAssertEqual(Tree.serialize(entries.shuffled()), raw)
}
- /// Dépôt avec historique et deltas, relu en entier par notre client.
+ /// Repository with history and deltas, read back in full by our client.
func testFetchMatchesRealGit() async throws {
let repo = try LocalGit.create()
- var body = (0..<400).map { "ligne \($0) du profil de plongée\n" }.joined()
+ var body = (0..<400).map { "line \($0) of the dive profile\n" }.joined()
for i in 0..<12 {
- body += "ajout \(i)\n"
- try repo.write("2024/05/plongee-\(i % 3)/Divecomputer", body)
+ body += "addition \(i)\n"
+ try repo.write("2024/05/dive-\(i % 3)/Divecomputer", body)
try repo.write("00-Subsurface", "version 3\nrev \(i)\n")
try repo.commitAll("commit \(i)")
}
@@ -60,12 +61,12 @@ final class GitLiteTests: XCTestCase {
XCTAssertEqual(remote.branch("main"), head)
try await client.fetch(want: head, capabilities: remote.capabilities)
- // Tous les objets du dépôt sont là et identiques.
+ // Every object of the repository is there and identical.
let listing = try repo.text(["rev-list", "--objects", "--all"])
var checked = 0
for line in listing.split(separator: "\n") {
let id = ObjectID(hex: line.prefix(40))!
- let object = try XCTUnwrap(store.get(id), "objet absent : \(line)")
+ let object = try XCTUnwrap(store.get(id), "missing object: \(line)")
let type = try repo.text(["cat-file", "-t", id.hex])
XCTAssertEqual(object.type.name, type)
XCTAssertEqual(object.data, try repo.git(["cat-file", type, id.hex]))
@@ -79,24 +80,24 @@ final class GitLiteTests: XCTestCase {
func testShallowThenIncrementalFetch() async throws {
let repo = try LocalGit.create()
- try repo.write("a", "un\n")
- try repo.commitAll("un")
- try repo.write("b", "deux\n")
- let second = try repo.commitAll("deux")
+ try repo.write("a", "one\n")
+ try repo.commitAll("one")
+ try repo.write("b", "two\n")
+ let second = try repo.commitAll("two")
let store = MemoryObjectStore()
let client = GitClient(transport: LocalProcessTransport(repository: repo.directory), store: store)
var remote = try await client.refs()
let shallow = try await client.fetch(want: second, depth: 1, capabilities: remote.capabilities)
XCTAssertEqual(shallow, [second])
- XCTAssertEqual(store.count, 4) // 1 commit, 1 arbre, 2 fichiers : pas d'historique
+ XCTAssertEqual(store.count, 4) // 1 commit, 1 tree, 2 blobs: no history
- try repo.write("c", "trois\n")
- let third = try repo.commitAll("trois")
+ try repo.write("c", "three\n")
+ let third = try repo.commitAll("three")
remote = try await client.refs()
let again = try await client.fetch(want: third, have: [second], shallow: shallow, depth: 1, capabilities: remote.capabilities)
XCTAssertEqual(again, [third])
- XCTAssertEqual(store.count, 7) // + 1 commit, 1 arbre, 1 fichier seulement
+ XCTAssertEqual(store.count, 7) // + 1 commit, 1 tree, 1 blob only
XCTAssertEqual(try store.tree(try store.commit(third).tree).map(\.name), ["a", "b", "c"])
}
@@ -108,7 +109,7 @@ final class GitLiteTests: XCTestCase {
let blob = GitObject(type: .blob, data: Array("version 3\n".utf8))
let tree = GitObject(type: .tree, data: Tree.serialize([.blob("00-Subsurface", blob.id)]))
let who = Commit.signature(name: "Test", email: "test@example.com", date: Date(timeIntervalSince1970: 1_700_000_000))
- let first = GitObject(type: .commit, data: Commit(tree: tree.id, parents: [], author: who, committer: who, message: "premier\n").serialize())
+ let first = GitObject(type: .commit, data: Commit(tree: tree.id, parents: [], author: who, committer: who, message: "first\n").serialize())
try await client.push(ref: "refs/heads/jean@example.com", old: nil, new: first.id, objects: [blob, tree, first])
XCTAssertEqual(try repo.text(["rev-parse", "refs/heads/jean@example.com"]), first.id.hex)
XCTAssertEqual(try repo.text(["show", "jean@example.com:00-Subsurface"]), "version 3")
@@ -119,14 +120,14 @@ final class GitLiteTests: XCTestCase {
let tree2 = GitObject(type: .tree, data: Tree.serialize([.blob("00-Subsurface", blob.id), .tree("2024", sub.id)]))
let second = GitObject(type: .commit, data: Commit(tree: tree2.id, parents: [first.id], author: who, committer: who, message: "second\n").serialize())
try await client.push(ref: "refs/heads/jean@example.com", old: first.id, new: second.id, objects: [blob2, sub, tree2, second])
- XCTAssertEqual(try repo.text(["log", "--format=%s", "jean@example.com"]), "second\npremier")
+ XCTAssertEqual(try repo.text(["log", "--format=%s", "jean@example.com"]), "second\nfirst")
try repo.git(["fsck", "--strict"])
- // Une mise à jour à partir d'un état périmé est refusée.
- let third = GitObject(type: .commit, data: Commit(tree: tree.id, parents: [first.id], author: who, committer: who, message: "périmé\n").serialize())
+ // An update from a stale state is rejected.
+ let third = GitObject(type: .commit, data: Commit(tree: tree.id, parents: [first.id], author: who, committer: who, message: "stale\n").serialize())
do {
try await client.push(ref: "refs/heads/jean@example.com", old: first.id, new: third.id, objects: [third])
- XCTFail("l'envoi aurait dû être refusé")
+ XCTFail("the push should have been rejected")
} catch let error as GitError {
guard case .pushRejected = error else { return XCTFail("\(error)") }
}
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/Fixture.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/Fixture.swift
@@ -1,8 +1,10 @@
+// SPDX-License-Identifier: GPL-2.0-only
import Foundation
import GitLite
import GitTestSupport
-/// Petit carnet au format git de Subsurface, écrit avec le vrai git.
+/// Small logbook in Subsurface's git format, written with the real git.
+/// The sample data (site names, notes, tags) is deliberately in French: it exercises accented text.
enum Fixture {
static let branch = "jean@example.com"
@@ -84,7 +86,7 @@ enum Fixture {
"model \"\(model)\"\nmaxdepth \(depth)m\nmeandepth 9.0m\nwatertemp 27.0°C\n 0:00 0.0m\n 25:00 \(depth)m\n 50:00 0.0m\n"
}
- /// Dépôt « serveur » nu, avec la branche de l'usager, et le dépôt de travail qui l'a rempli.
+ /// Bare "server" repository, with the user's branch, and the working repository that filled it.
static func makeRemote() throws -> (remote: LocalGit, work: LocalGit) {
let work = try LocalGit.create(name: "work")
try work.write("00-Subsurface", settings)
@@ -94,7 +96,7 @@ enum Fixture {
try work.write("2024/08/02-Bonaire~1a2b3c4/00-Trip", trip)
try work.write("2024/08/02-Bonaire~1a2b3c4/02-Fri-09=00=00/Dive-42", simpleDive(buddy: "Sam"))
try work.write("2024/08/02-Bonaire~1a2b3c4/02-Fri-09=00=00/Divecomputer", simpleComputer(model: "Shearwater Petrel 3", depth: "18.0"))
- // Plongée du voyage tombée le mois suivant : le mois est repris dans le nom du dossier.
+ // Dive of the trip that fell in the following month: the month is repeated in the directory name.
try work.write("2024/08/02-Bonaire~1a2b3c4/09-01-Sun-08=30=00~abcdef1/Dive-43", simpleDive(buddy: "Max"))
try work.write("2024/08/02-Bonaire~1a2b3c4/09-01-Sun-08=30=00~abcdef1/Divecomputer-001", simpleComputer(model: "Shearwater Petrel 3", depth: "21.5"))
try work.write("2024/08/02-Bonaire~1a2b3c4/09-01-Sun-08=30=00~abcdef1/Divecomputer-002", simpleComputer(model: "Suunto D5", depth: "21.9"))
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/HTTPTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/HTTPTests.swift
@@ -1,9 +1,10 @@
+// SPDX-License-Identifier: GPL-2.0-only
import XCTest
import GitLite
import GitTestSupport
@testable import SubsurfaceLog
-/// Le chemin réel de l'app : URLSession → HTTP avec authentification Basic → `git http-backend`.
+/// The app's real path: URLSession → HTTP with Basic authentication → `git http-backend`.
final class HTTPTests: XCTestCase {
func testSyncOverAuthenticatedHTTP() async throws {
let email = Fixture.branch
@@ -21,15 +22,15 @@ final class HTTPTests: XCTestCase {
let base = URL(string: "http://127.0.0.1:\(server.port)/git/")!.appendingPathComponent(email)
let transport = HTTPTransport(baseURL: base, username: email, password: password)
- // Mauvais mot de passe : refus net.
+ // Wrong password: rejected outright.
do {
- _ = try await GitClient(transport: HTTPTransport(baseURL: base, username: email, password: "faux"), store: MemoryObjectStore()).refs()
- XCTFail("aurait dû être refusé")
+ _ = try await GitClient(transport: HTTPTransport(baseURL: base, username: email, password: "wrong"), store: MemoryObjectStore()).refs()
+ XCTFail("should have been rejected")
} catch let error as GitError {
XCTAssertEqual(error, .unauthorized)
}
- // Bon mot de passe : la liste des branches, puis tout le carnet.
+ // Right password: the list of branches, then the whole logbook.
let refs = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
XCTAssertNotNil(refs.branch(email))
let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: email, authorName: "DiveLog", authorEmail: email)
@@ -38,24 +39,24 @@ final class HTTPTests: XCTestCase {
var log = try await repo.logbook()
XCTAssertEqual(log.dives.map(\.number), [43, 42, 41])
- // Une modification part et se retrouve dans le dépôt du serveur.
- try await repo.enqueue(.editDive(when: Fixture.when(2024, 7, 13, 10, 15, 30), number: 41, fields: ["buddy": "Par HTTP"]))
+ // A change is sent and ends up in the server's repository.
+ try await repo.enqueue(.editDive(when: Fixture.when(2024, 7, 13, 10, 15, 30), number: 41, fields: ["buddy": "Over HTTP"]))
let second = try await repo.sync(transport: transport)
XCTAssertEqual(second.sent.count, 1)
try bare.git(["fsck", "--strict"])
- XCTAssertTrue(try bare.text(["show", "\(email):2024/07/13-Sat-10=15=30/Dive-41"]).contains("buddy \"Par HTTP\""))
+ XCTAssertTrue(try bare.text(["show", "\(email):2024/07/13-Sat-10=15=30/Dive-41"]).contains("buddy \"Over HTTP\""))
- // Un second appareil récupère la modification.
+ // A second device picks up the change.
let other = try LogRepository(directory: try LocalGit.temporaryDirectory("other"), branch: email, authorName: "DiveLog", authorEmail: email)
_ = try await other.sync(transport: transport)
log = try await other.logbook()
- XCTAssertEqual(log.dives.last?.buddy, "Par HTTP")
+ XCTAssertEqual(log.dives.last?.buddy, "Over HTTP")
}
- /// Vrai nuage, en lecture seule : CLOUD_EMAIL et CLOUD_PASSWORD dans l'environnement. N'envoie rien.
+ /// Real cloud, read-only: CLOUD_EMAIL and CLOUD_PASSWORD in the environment. Sends nothing.
func testRealCloudReadOnly() async throws {
let env = ProcessInfo.processInfo.environment
- guard let email = env["CLOUD_EMAIL"], let password = env["CLOUD_PASSWORD"] else { throw XCTSkip("CLOUD_EMAIL non défini") }
+ guard let email = env["CLOUD_EMAIL"], let password = env["CLOUD_PASSWORD"] else { throw XCTSkip("CLOUD_EMAIL not set") }
let transport = SubsurfaceCloud.transport(email: email, password: password)
print("CLOUD url=\(transport.baseURL.absoluteString)")
let refs = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
@@ -65,9 +66,9 @@ final class HTTPTests: XCTestCase {
let report = try await repo.sync(transport: transport)
XCTAssertEqual(report.sent, [])
let log = try await repo.logbook()
- print("CLOUD plongées=\(log.dives.count) lieux=\(log.sites.count) voyages=\(log.trips.count) avertissements=\(log.warnings)")
+ print("CLOUD dives=\(log.dives.count) sites=\(log.sites.count) trips=\(log.trips.count) warnings=\(log.warnings)")
var samples = 0
for dive in log.dives { samples += (try await repo.profile(of: dive)).reduce(0) { $0 + $1.samples.count } }
- print("CLOUD échantillons=\(samples) numéros=\(log.dives.first?.number ?? 0)…\(log.dives.last?.number ?? 0) modèles=\(Set(log.dives.compactMap(\.computerModel)).sorted())")
+ print("CLOUD samples=\(samples) numbers=\(log.dives.first?.number ?? 0)…\(log.dives.last?.number ?? 0) models=\(Set(log.dives.compactMap(\.computerModel)).sorted())")
}
}
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import XCTest
import GitLite
import GitTestSupport
@@ -5,7 +6,7 @@ import SQLite3
@testable import SubsurfaceLog
final class ImportTests: XCTestCase {
- /// Enregistrement PNF de 32 octets.
+ /// 32-byte PNF record.
private func record(_ type: UInt8, _ fill: (inout [UInt8]) -> Void) -> [UInt8] {
var bytes = [UInt8](repeating: 0, count: 32)
bytes[0] = type
@@ -18,7 +19,7 @@ final class ImportTests: XCTestCase {
bytes[offset + 1] = UInt8(value & 255)
}
- /// Journal fictif : 6 échantillons toutes les 10 s, un changement de gaz, un palier.
+ /// Made-up log: 6 samples every 10 s, one gas change, one stop.
private func syntheticLog(imperial: Bool = false) -> [UInt8] {
var log = [UInt8]()
log += record(0x10) { $0[4] = 45; $0[5] = 95; $0[8] = imperial ? 1 : 0 }
@@ -47,7 +48,7 @@ final class ImportTests: XCTestCase {
return log
}
- /// Base au schéma de l'export Shearwater Cloud, réduite aux colonnes lues.
+ /// Database with the schema of the Shearwater Cloud export, reduced to the columns that are read.
private func makeDatabase(log: [UInt8]) throws -> [UInt8] {
let url = try LocalGit.temporaryDirectory("sw").appendingPathComponent("dive_data.db")
var db: OpaquePointer?
@@ -72,7 +73,7 @@ final class ImportTests: XCTestCase {
}
func testGzipAndZip() throws {
- let payload = Array("bonjour ".utf8) + [UInt8](repeating: 7, count: 100_000)
+ let payload = Array("hello ".utf8) + [UInt8](repeating: 7, count: 100_000)
XCTAssertEqual(try Inflate.decompress(Inflate.gzip(payload), format: .gzip), payload)
let directory = try LocalGit.temporaryDirectory("zip")
@@ -107,8 +108,8 @@ final class ImportTests: XCTestCase {
XCTAssertEqual(dive.samples.map(\.depth), [5.2, 15, 30.5, 30, 6, 1])
XCTAssertEqual(dive.samples.map(\.temperature), [20, 18, 12, 12, 14, 19])
XCTAssertEqual(dive.samples[0].pressure1, 199.9) // 1450 × 2 psi
- XCTAssertNil(dive.samples[2].pressure1) // pas de mesure
- XCTAssertNil(dive.samples[5].pressure1) // émetteur muet
+ XCTAssertNil(dive.samples[2].pressure1) // no reading
+ XCTAssertNil(dive.samples[5].pressure1) // silent transmitter
XCTAssertNil(dive.samples[0].pressure2)
XCTAssertEqual(dive.samples[3].stopDepth, 3)
XCTAssertEqual(dive.samples[3].decoTime, 120)
@@ -116,17 +117,17 @@ final class ImportTests: XCTestCase {
XCTAssertEqual(dive.gases.map(\.label), ["EAN32", "EAN50"])
XCTAssertEqual(dive.maxDepth, 30.5)
- // Unités impériales : pieds et °F convertis.
+ // Imperial units: feet and °F converted.
let imperial = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog(imperial: true)))[0]
XCTAssertEqual(imperial.samples[2].depth, 30.5 * 0.3048, accuracy: 0.001)
XCTAssertEqual(try XCTUnwrap(imperial.samples[0].temperature), (20.0 - 32) * 5 / 9, accuracy: 0.001)
- XCTAssertThrowsError(try DiveImporter.dives(from: Array("pas une base".utf8))) {
+ XCTAssertThrowsError(try DiveImporter.dives(from: Array("not a database".utf8))) {
XCTAssertEqual($0 as? ImportError, .unknownFormat)
}
}
- /// Base de l'app Dive Shearwater (WatermelonDB) : journaux en base64, lieux et binômes dans des tables à part.
+ /// Database of the Dive Shearwater app (WatermelonDB): logs in base64, sites and buddies in separate tables.
func testDiveShearwaterAppDatabase() throws {
let url = try LocalGit.temporaryDirectory("dsw").appendingPathComponent("watermelon.db")
var db: OpaquePointer?
@@ -151,7 +152,7 @@ final class ImportTests: XCTestCase {
let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: url)))
XCTAssertEqual(dives.count, 2)
let dive = try XCTUnwrap(dives.last)
- XCTAssertEqual(dive.when, Fixture.when(2025, 9, 6, 11, 27, 54)) // l'heure exacte vient de l'identifiant
+ XCTAssertEqual(dive.when, Fixture.when(2025, 9, 6, 11, 27, 54)) // the exact time comes from the identifier
XCTAssertEqual(dive.durationSeconds, 55)
XCTAssertEqual(dive.model, "Shearwater Petrel 3")
XCTAssertEqual(dive.serial, "ABCD1234")
@@ -161,13 +162,13 @@ final class ImportTests: XCTestCase {
XCTAssertEqual(dive.buddy, "Sam, Alex")
XCTAssertEqual(dive.notes, "Free flow")
XCTAssertEqual(dive.samples.map(\.depth), [5.2, 15, 30.5, 30, 6, 1])
- // Journal sans fiche : importé quand même, daté par son identifiant.
+ // Log without a details record: imported anyway, dated from its identifier.
XCTAssertEqual(dives[0].when, 1_757_160_635)
XCTAssertEqual(dives[0].site, "")
XCTAssertEqual(dives[0].durationSeconds, 60)
}
- /// La plongée importée entre dans le carnet, part au serveur et se relit à l'identique.
+ /// The imported dive enters the logbook, goes to the server and reads back identically.
func testImportedDiveRoundTrip() async throws {
let (remote, _) = try Fixture.makeRemote()
let transport = LocalProcessTransport(repository: remote.directory)
@@ -178,10 +179,10 @@ final class ImportTests: XCTestCase {
var log = try await repo.enqueue(.importDive(imported, number: 44, siteUUID: 0x7f3a1b2c))
XCTAssertEqual(log.dives.count, 4)
- // Deux fois la même plongée : refusée.
+ // The same dive twice: rejected.
do {
try await repo.enqueue(.importDive(imported, number: 45, siteUUID: nil))
- XCTFail("aurait dû échouer")
+ XCTFail("should have failed")
} catch let error as ChangeError {
XCTAssertEqual(error, .diveAlreadyExists(imported.when))
}
@@ -230,15 +231,15 @@ final class ImportTests: XCTestCase {
XCTAssertEqual(computer.extra.first, KeyValue(key: "Serial", value: "ABCD1234"))
}
- /// Vrai export Shearwater Cloud (SHEARWATER_EXPORT = chemin du .zip ou de dive_data.db), hors dépôt.
+ /// Real Shearwater Cloud export (SHEARWATER_EXPORT = path of the .zip or of dive_data.db), kept outside the repository.
func testRealShearwaterExport() throws {
- guard let path = ProcessInfo.processInfo.environment["SHEARWATER_EXPORT"] else { throw XCTSkip("SHEARWATER_EXPORT non défini") }
+ guard let path = ProcessInfo.processInfo.environment["SHEARWATER_EXPORT"] else { throw XCTSkip("SHEARWATER_EXPORT not set") }
let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
XCTAssertGreaterThan(dives.count, 0)
for dive in dives {
let c = NaiveTime.components(dive.when)
let pressures = dive.samples.compactMap(\.pressure1)
- print("IMPORT \(c.year!)-\(c.month!)-\(c.day!) \(c.hour!):\(c.minute!) \(dive.model) durée=\(dive.durationSeconds) max=\(dive.maxDepth) moy=\(String(format: "%.2f", dive.meanDepth)) tmin=\(dive.minTemperature ?? -99) gaz=\(dive.gases.map(\.label)) \(dive.decoModel ?? "") surf=\(dive.surfacePressureBar ?? 0) sal=\(dive.salinity ?? 0) éch=\(dive.samples.count) pas=\(dive.samples.first?.time ?? 0) bar=\(pressures.first ?? 0)→\(pressures.last ?? 0) paliers=\(Set(dive.samples.map(\.stopDepth)).sorted()) lieu=\(dive.site.count) binôme=\(dive.buddy.isEmpty ? 0 : 1)")
+ print("IMPORT \(c.year!)-\(c.month!)-\(c.day!) \(c.hour!):\(c.minute!) \(dive.model) duration=\(dive.durationSeconds) max=\(dive.maxDepth) mean=\(String(format: "%.2f", dive.meanDepth)) tmin=\(dive.minTemperature ?? -99) gases=\(dive.gases.map(\.label)) \(dive.decoModel ?? "") surf=\(dive.surfacePressureBar ?? 0) sal=\(dive.salinity ?? 0) samples=\(dive.samples.count) step=\(dive.samples.first?.time ?? 0) bar=\(pressures.first ?? 0)→\(pressures.last ?? 0) stops=\(Set(dive.samples.map(\.stopDepth)).sorted()) site=\(dive.site.count) buddy=\(dive.buddy.isEmpty ? 0 : 1)")
XCTAssertGreaterThan(dive.maxDepth, 3)
XCTAssertLessThan(dive.maxDepth, 80)
XCTAssertGreaterThan(dive.samples.count, 50)
@@ -254,23 +255,23 @@ final class ImportTests: XCTestCase {
var second = ImportedDive(when: 1300, durationSeconds: 20)
second.sourceID = "b"
second.buddy = "Sam"
- second.notes = "seconde"
+ second.notes = "second"
second.samples = [10, 20].map { ImportedDive.Sample(time: $0, depth: 8) }
let merged = try XCTUnwrap(ImportedDive.merged([second, first]))
XCTAssertEqual(merged.when, 1000)
- XCTAssertEqual(merged.durationSeconds, 50) // temps sous l'eau, sans l'intervalle
+ XCTAssertEqual(merged.durationSeconds, 50) // time underwater, without the interval
XCTAssertEqual(merged.samples.map(\.time), [10, 20, 30, 40, 300, 310, 320])
XCTAssertEqual(merged.samples.map(\.depth), [5, 10, 15, 0, 0, 8, 8])
- XCTAssertNil(merged.samples[3].pressure1) // pas de pression inventée en surface
+ XCTAssertNil(merged.samples[3].pressure1) // no made-up pressure at the surface
XCTAssertEqual(merged.maxDepth, 15)
XCTAssertEqual(merged.meanDepth, (5 + 10 + 15 + 8 + 8) / 5.0)
XCTAssertEqual(merged.buddy, "Sam")
- XCTAssertEqual(merged.notes, "seconde")
+ XCTAssertEqual(merged.notes, "second")
XCTAssertEqual(merged.sourceID, "a+b")
XCTAssertEqual(ImportedDive.merged([first]), first)
}
- /// Plongée déposée par Open Rémora (JSON du `DiveLog` de RemoraDeco, clés triées, dates ISO 8601).
+ /// Dive dropped by Open Rémora (JSON of RemoraDeco's `DiveLog`, sorted keys, ISO 8601 dates).
func testOpenRemoraDive() throws {
let json = """
{"computerModel":"Open Rémora","events":[{"time":600,"warning":"ascentFast"},{"time":1260,"warning":"ceilingViolated"}],
@@ -285,7 +286,7 @@ final class ImportTests: XCTestCase {
"""
let montreal = try XCTUnwrap(TimeZone(identifier: "America/Toronto"))
let dive = try RemoraImport.dive(fromJSON: Data(json.utf8), timeZone: montreal)
- XCTAssertEqual(dive.when, Fixture.when(2026, 7, 4, 10, 30, 0)) // 14 h 30 UTC = 10 h 30 à Montréal en été
+ XCTAssertEqual(dive.when, Fixture.when(2026, 7, 4, 10, 30, 0)) // 14:30 UTC = 10:30 in Montreal in summer
XCTAssertEqual(dive.durationSeconds, 1560)
XCTAssertEqual(dive.model, "Open Rémora")
XCTAssertEqual(dive.sourceID, "6F1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D")
@@ -300,14 +301,22 @@ final class ImportTests: XCTestCase {
XCTAssertEqual(dive.samples.map(\.temperature), [18.2, 12, 8, 14, nil])
XCTAssertEqual(dive.samples.map(\.decoTime), [99 * 60, 45 * 60, 4 * 60, 99 * 60, 99 * 60])
XCTAssertEqual(dive.samples.map(\.stopDepth), [0, 0, 3, 0, 0])
- XCTAssertEqual(dive.notes, "Première sortie\nAlarmes : 10:00 remontée rapide, 21:00 plafond franchi")
+ // Default alarm labels are English.
+ XCTAssertEqual(dive.notes, "Première sortie\nAlarms: 10:00 fast ascent, 21:00 ceiling violated")
XCTAssertTrue(LogEditor.computerFile(dive).contains("in_deco=1 stoptime=4:00 stopdepth=3.0m"))
- // Une plongée de démonstration ne doit jamais entrer dans le carnet.
+ // The app passes its own localized labels and prefix; a warning missing from the dictionary is written as is.
+ let localized = try RemoraImport.dive(fromJSON: Data(json.utf8), timeZone: montreal,
+ alarmLabels: ["ascentFast": "remontée rapide"], alarmsPrefix: "Alarmes : ")
+ XCTAssertEqual(localized.notes, "Première sortie\nAlarmes : 10:00 remontée rapide, 21:00 ceilingViolated")
+ XCTAssertEqual(RemoraImport.defaultAlarmLabels.keys.sorted(),
+ ["ascentFast", "ascentTooFast", "ceilingViolated", "missedSafetyStop", "ppO2Critical", "ppO2High"])
+
+ // A demo dive must never enter the logbook.
XCTAssertThrowsError(try RemoraImport.dive(fromJSON: Data(json.replacingOccurrences(of: "\"source\":\"remora\"", with: "\"source\":\"simulation\"").utf8)))
- // Dossier partagé : seuls les JSON sont en attente ; consommer retire aussi le UDDF.
- let folder = try LocalGit.temporaryDirectory("partage")
+ // Shared folder: only the JSON files are pending; consuming also removes the UDDF.
+ let folder = try LocalGit.temporaryDirectory("shared")
try Data(json.utf8).write(to: folder.appendingPathComponent("a.json"))
try Data("<uddf/>".utf8).write(to: folder.appendingPathComponent("a.uddf"))
let pending = RemoraImport.pendingFiles(in: folder)
@@ -326,7 +335,7 @@ final class ImportTests: XCTestCase {
XCTAssertFalse(CloudAccount.isValid(email: "jean@example"))
XCTAssertFalse(CloudAccount.isValid(email: "jean example@example.com"))
XCTAssertTrue(CloudAccount.isValid(password: "Abc123@.+_-"))
- XCTAssertFalse(CloudAccount.isValid(password: "mot de passe"))
+ XCTAssertFalse(CloudAccount.isValid(password: "pass word"))
XCTAssertFalse(CloudAccount.isValid(password: "été2026!"))
XCTAssertFalse(CloudAccount.isValid(password: ""))
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0-only
import XCTest
import GitLite
import GitTestSupport
@@ -12,7 +13,7 @@ final class SubsurfaceLogTests: XCTestCase {
// MARK: Format
func testQuoteRoundTrip() {
- for value in ["simple", "avec \"guillemets\" et \\ barre", "ligne 1\nligne 2", "a\n\nb\n\n\nc", "fin\n", "accents éàü 🐚"] {
+ for value in ["simple", "with \"quotes\" and a \\ backslash", "line 1\nline 2", "a\n\nb\n\n\nc", "end\n", "accents éàü 🐚"] {
let line = Array(("notes " + LogFormat.quote(value) + "\n").utf8)
let parsed = LogFormat.lines(line)
XCTAssertEqual(parsed.count, 1, value)
@@ -46,7 +47,7 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertNil(LogWalker.diveNumber(fileName: "Divecomputer-001"))
}
- // MARK: Lecture
+ // MARK: Reading
func testLoadLogbook() async throws {
let (remote, _) = try Fixture.makeRemote()
@@ -107,16 +108,16 @@ final class SubsurfaceLogTests: XCTestCase {
_ = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory))
let log = try await repo.logbook()
let dive = try XCTUnwrap(log.dive(when: Fixture.when(2024, 7, 13, 10, 15, 30)))
- XCTAssertEqual(dive.computers.first?.samples.count, 0) // résumé seulement
+ XCTAssertEqual(dive.computers.first?.samples.count, 0) // summary only
let computers = try await repo.profile(of: dive)
let dc = try XCTUnwrap(computers.first)
XCTAssertEqual(dc.samples.count, 6)
XCTAssertEqual(dc.samples.map(\.time), [0, 10, 60, 1200, 1800, 2730])
XCTAssertEqual(dc.samples.map(\.depth), [0, 3.2, 12, 30.5, 15, 0])
- XCTAssertEqual(dc.samples[1].temperature, 26) // reportée
+ XCTAssertEqual(dc.samples[1].temperature, 26) // carried over
XCTAssertEqual(dc.samples[2].temperature, 25)
XCTAssertEqual(dc.samples[0].pressures, [SensorPressure(sensor: 0, bar: 200)])
- XCTAssertEqual(dc.samples[1].pressures, []) // pas reportée : s'interpole
+ XCTAssertEqual(dc.samples[1].pressures, []) // not carried over: interpolated
XCTAssertEqual(dc.samples[2].ndl, 2700)
XCTAssertEqual(dc.samples[2].cns, 1)
XCTAssertTrue(dc.samples[3].inDeco)
@@ -133,7 +134,7 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertEqual(dc.salinity, 1025)
}
- // MARK: Modification
+ // MARK: Editing
func testPatchKeepsEverythingElse() {
let original = Array(Fixture.dive41.utf8)
@@ -143,11 +144,11 @@ final class SubsurfaceLogTests: XCTestCase {
.replacingOccurrences(of: "buddy \"Sam, Max\"", with: "buddy \"Léa\"")
XCTAssertEqual(String(decoding: patched, as: UTF8.self), expected)
- // Rien à changer : identique à l'octet près.
+ // Nothing to change: identical byte for byte.
XCTAssertEqual(LogEditor.patch(diveFile: original, fields: [:]), original)
XCTAssertEqual(LogEditor.patch(diveFile: original, fields: [.buddy: "Sam, Max", .notes: "Belle plongée.\nTortue \"verte\" au palier.\n\nFin."]), original)
- // Champ vidé : la ligne disparaît. Champ absent : inséré à sa place canonique.
+ // Emptied field: the line disappears (an existing text line is kept as `""`). Missing field: inserted at its canonical place.
let minimal = Array("duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n".utf8)
let edited = LogEditor.patch(diveFile: minimal, fields: [.buddy: "", .notes: "ok", .rating: "3", .site: "7f3a1b2c", .tags: "nuit, épave"])
XCTAssertEqual(String(decoding: edited, as: UTF8.self),
@@ -164,7 +165,7 @@ final class SubsurfaceLogTests: XCTestCase {
let when41 = Fixture.when(2024, 7, 13, 10, 15, 30)
let when43 = Fixture.when(2024, 9, 1, 8, 30, 0)
- // Modifications hors ligne : visibles tout de suite, pas encore envoyées.
+ // Offline changes: visible right away, not sent yet.
var log = try await repo.enqueue(.editDive(when: when41, number: 41, fields: ["buddy": "Léa", "notes": "Nouvelles notes\nsur deux lignes"]))
XCTAssertEqual(log.dive(when: when41)?.buddy, "Léa")
log = try await repo.enqueue(.editDive(when: when43, number: 43, fields: ["rating": "5"]))
@@ -179,7 +180,7 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertEqual(log.dives[0].number, 44)
XCTAssertEqual(try remote.text(["log", "--format=%s", Fixture.branch]), "carnet de test")
- // Une autre instance rouvre la même copie locale : la file d'attente a survécu.
+ // Another instance reopens the same local copy: the queue survived.
let reopened = try LogRepository(directory: repo.directory, branch: Fixture.branch, authorName: "DiveLog", authorEmail: Fixture.branch)
let pendingCount = await reopened.pending.count
XCTAssertEqual(pendingCount, 4)
@@ -190,7 +191,7 @@ final class SubsurfaceLogTests: XCTestCase {
let stillPending = await reopened.pending.count
XCTAssertEqual(stillPending, 0)
- // Le vrai git voit un dépôt sain, avec un commit de plus et les bons fichiers.
+ // The real git sees a healthy repository, with one more commit and the right files.
try remote.git(["fsck", "--strict"])
XCTAssertEqual(try remote.text(["rev-list", "--count", Fixture.branch]), "2")
XCTAssertEqual(try remote.text(["rev-parse", Fixture.branch]), report.head?.hex)
@@ -206,13 +207,13 @@ final class SubsurfaceLogTests: XCTestCase {
"model \"manually added dive\"\nmaxdepth 18.0m\nmeandepth 17.325m\n 0:00 0.0m\n 1:00 18.0m\n 38:00 18.0m\n 40:00 0.0m")
XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):01-Divesites/Site-1234abcd"]),
"name \"Épave du \\\"Lord\\\"\"\ngps 12.100000 -68.250000")
- // Les fichiers non touchés sont les mêmes objets qu'avant.
+ // The untouched files are the same objects as before.
XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Divecomputer"]),
try remote.text(["rev-parse", "\(Fixture.branch)~1:2024/07/13-Sat-10=15=30/Divecomputer"]))
XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):00-Subsurface"]),
try remote.text(["rev-parse", "\(Fixture.branch)~1:00-Subsurface"]))
- // Un second appareil part de zéro et voit tout.
+ // A second device starts from scratch and sees everything.
let other = try repository("other")
_ = try await other.sync(transport: transport)
let seen = try await other.logbook()
@@ -222,13 +223,13 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertEqual(seen.site(of: seen.dives[0])?.name, "Épave du \"Lord\"")
XCTAssertEqual(seen.dive(when: when41)?.notes, "Nouvelles notes\nsur deux lignes")
- // Rien de neuf : la synchro suivante ne télécharge ni n'envoie rien.
+ // Nothing new: the next sync neither downloads nor sends anything.
let idle = try await reopened.sync(transport: transport)
XCTAssertFalse(idle.downloaded)
XCTAssertEqual(idle.sent, [])
}
- /// Un autre appareil (Subsurface de bureau) a envoyé entre-temps : nos modifications se rejouent par-dessus.
+ /// Another device (desktop Subsurface) pushed in the meantime: our changes are replayed on top.
func testPendingEditsReplayOverRemoteChanges() async throws {
let (remote, work) = try Fixture.makeRemote()
let transport = LocalProcessTransport(repository: remote.directory)
@@ -241,11 +242,11 @@ final class SubsurfaceLogTests: XCTestCase {
try await repo.enqueue(.editDive(when: when42, number: 42, fields: ["notes": "sera perdue"]))
try await repo.enqueue(.deleteDive(when: Fixture.when(2024, 9, 1, 8, 30, 0), number: 43))
- // Pendant ce temps, le bureau renumérote la 41 en 141, change son binôme et supprime la 42.
+ // Meanwhile, the desktop renumbers dive 41 to 141, changes its buddy and deletes dive 42.
try work.git(["mv", "2024/07/13-Sat-10=15=30/Dive-41", "2024/07/13-Sat-10=15=30/Dive-141"])
try work.write("2024/07/13-Sat-10=15=30/Dive-141", Fixture.dive41.replacingOccurrences(of: "buddy \"Sam, Max\"", with: "buddy \"Bureau\""))
try work.git(["rm", "-rq", "2024/08/02-Bonaire~1a2b3c4/02-Fri-09=00=00"])
- try work.commitAll("modifs du bureau")
+ try work.commitAll("desktop changes")
try work.git(["push", "-q", "origin", "main:refs/heads/\(Fixture.branch)"])
let report = try await repo.sync(transport: transport)
@@ -257,9 +258,9 @@ final class SubsurfaceLogTests: XCTestCase {
let log = try await repo.logbook()
XCTAssertEqual(log.dives.map(\.number), [141])
- XCTAssertEqual(log.dives[0].buddy, "Bureau") // le changement du bureau
- XCTAssertEqual(log.dives[0].suit, "étanche") // et le nôtre
- // Le voyage vidé de ses plongées garde sa fiche, comme dans Subsurface.
+ XCTAssertEqual(log.dives[0].buddy, "Bureau") // the desktop's change
+ XCTAssertEqual(log.dives[0].suit, "étanche") // and ours
+ // The trip emptied of its dives keeps its record, as in Subsurface.
XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2024/08/02-Bonaire~1a2b3c4"]), "00-Trip")
}
@@ -269,14 +270,14 @@ final class SubsurfaceLogTests: XCTestCase {
_ = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory))
do {
try await repo.enqueue(.editDive(when: 12345, number: 1, fields: ["buddy": "x"]))
- XCTFail("aurait dû échouer")
+ XCTFail("should have failed")
} catch let error as ChangeError {
XCTAssertEqual(error, .diveNotFound(12345))
}
let duplicate = NewDive(when: Fixture.when(2024, 7, 13, 10, 15, 30), number: 99, durationSeconds: 600, maxDepth: 5)
do {
try await repo.enqueue(.addDive(duplicate))
- XCTFail("aurait dû échouer")
+ XCTFail("should have failed")
} catch let error as ChangeError {
XCTAssertEqual(error, .diveAlreadyExists(duplicate.when))
}
@@ -284,7 +285,7 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertEqual(pending, 0)
}
- /// Compte neuf : aucune branche sur le serveur ; la première plongée la crée.
+ /// Brand-new account: no branch on the server; the first dive creates it.
func testEmptyAccount() async throws {
let remote = try LocalGit.create(bare: true, name: "empty")
let transport = LocalProcessTransport(repository: remote.directory)
@@ -303,10 +304,10 @@ final class SubsurfaceLogTests: XCTestCase {
"00-Subsurface\n2025/01/02-Thu-03=04=05/Dive-1\n2025/01/02-Thu-03=04=05/Divecomputer")
}
- /// Validation sur un vrai carnet : SUBSURFACE_TREE = dossier disposé comme l'arbre git (00-Subsurface, 01-Divesites, aaaa/…).
+ /// Validation against a real logbook: SUBSURFACE_TREE = directory laid out like the git tree (00-Subsurface, 01-Divesites, yyyy/…).
func testExternalTree() async throws {
guard let path = ProcessInfo.processInfo.environment["SUBSURFACE_TREE"] else {
- throw XCTSkip("SUBSURFACE_TREE non défini")
+ throw XCTSkip("SUBSURFACE_TREE not set")
}
let work = try LocalGit.create(name: "external")
_ = try LocalGit.run(["-c", "core.quotepath=off", "init", "-q"], in: work.directory)
@@ -315,7 +316,7 @@ final class SubsurfaceLogTests: XCTestCase {
process.arguments = ["-R", path + "/.", work.directory.path]
try process.run()
process.waitUntilExit()
- try work.commitAll("carnet externe")
+ try work.commitAll("external logbook")
let remote = try LocalGit.create(bare: true, name: "remote")
try work.git(["push", "-q", remote.directory.path, "main:refs/heads/\(Fixture.branch)"])
let repo = try repository()
@@ -328,8 +329,8 @@ final class SubsurfaceLogTests: XCTestCase {
let computers = try await repo.profile(of: dive)
samples += computers.reduce(0) { $0 + $1.samples.count }
let site = log.site(of: dive)?.name ?? "-"
- print("#\(dive.number) \(dive.date) \(dive.durationSeconds / 60) min \(dive.maxDepth) m \(dive.waterTemperature.map { "\($0) °C" } ?? "-") [\(site)] \(dive.computers.map(\.model)) bouteilles=\(dive.cylinders.map { $0.gas.label }) binôme=\(dive.buddy) éch=\(computers.map(\.samples.count)) évén=\(computers.map(\.events.count))")
- // Réécrire une plongée avec ses propres valeurs ne doit pas changer un octet.
+ print("#\(dive.number) \(dive.date) \(dive.durationSeconds / 60) min \(dive.maxDepth) m \(dive.waterTemperature.map { "\($0) °C" } ?? "-") [\(site)] \(dive.computers.map(\.model)) cylinders=\(dive.cylinders.map { $0.gas.label }) buddy=\(dive.buddy) samples=\(computers.map(\.samples.count)) events=\(computers.map(\.events.count))")
+ // Rewriting a dive with its own values must not change a single byte.
let original = try repo.store.blob(try XCTUnwrap(dive.diveBlob))
var same: [DiveField: String] = [.buddy: dive.buddy, .divemaster: dive.divemaster, .suit: dive.suit, .notes: dive.notes,
.rating: String(dive.rating), .visibility: String(dive.visibility),
@@ -338,26 +339,26 @@ final class SubsurfaceLogTests: XCTestCase {
same[.site] = String(uuid, radix: 16)
}
XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: original, fields: same), as: UTF8.self),
- String(decoding: original, as: UTF8.self), "plongée \(dive.number)")
+ String(decoding: original, as: UTF8.self), "dive \(dive.number)")
}
- print("\(log.dives.count) plongées, \(log.sites.count) lieux, \(log.trips.count) voyages, \(samples) échantillons")
+ print("\(log.dives.count) dives, \(log.sites.count) sites, \(log.trips.count) trips, \(samples) samples")
}
- /// Une seule requête au vrai nuage, avec un compte qui n'existe pas (CLOUD_TEST=1) : il doit refuser proprement.
+ /// A single request to the real cloud, with an account that does not exist (CLOUD_TEST=1): it must refuse cleanly.
func testCloudRejectsUnknownAccount() async throws {
- guard ProcessInfo.processInfo.environment["CLOUD_TEST"] == "1" else { throw XCTSkip("CLOUD_TEST non défini") }
- let transport = SubsurfaceCloud.transport(email: "nobody@example.com", password: "invalide")
+ guard ProcessInfo.processInfo.environment["CLOUD_TEST"] == "1" else { throw XCTSkip("CLOUD_TEST not set") }
+ let transport = SubsurfaceCloud.transport(email: "nobody@example.com", password: "invalid")
do {
_ = try await GitClient(transport: transport, store: MemoryObjectStore()).refs()
- XCTFail("le nuage aurait dû refuser")
+ XCTFail("the cloud should have refused")
} catch let error as GitError {
XCTAssertEqual(error, .unauthorized)
}
}
- /// Compte créé par Subsurface mais jamais rempli : un commit dont l'arbre est vide. Le fichier de réglages est ajouté.
+ /// Account created by Subsurface but never filled: a commit whose tree is empty. The settings file gets added.
func testEmptyTreeAccountGetsSettingsFile() async throws {
- let remote = try LocalGit.create(bare: true, name: "vide")
+ let remote = try LocalGit.create(bare: true, name: "empty")
let work = try LocalGit.create(name: "work")
try work.commitAll("Initial commit to create empty repo.")
try work.git(["push", "-q", remote.directory.path, "main:refs/heads/\(Fixture.branch)"])
@@ -370,7 +371,7 @@ final class SubsurfaceLogTests: XCTestCase {
XCTAssertEqual(try remote.text(["ls-tree", "-r", "--name-only", Fixture.branch]),
"00-Subsurface\n2025/01/02-Thu-03=04=05/Dive-1\n2025/01/02-Thu-03=04=05/Divecomputer")
XCTAssertEqual(try remote.text(["rev-list", "--count", Fixture.branch]), "2")
- // Rien à faire quand le fichier existe déjà : aucun commit de plus.
+ // Nothing to do when the file already exists: no additional commit.
try await repo.enqueue(.ensureSettings)
let idle = try await repo.sync(transport: transport)
XCTAssertEqual(idle.sent, [])
@@ -394,7 +395,7 @@ final class SubsurfaceLogTests: XCTestCase {
paper.notes = "Tunnels"
let log = try await repo.enqueue(.addDive(paper))
XCTAssertEqual(log.dives.map(\.number), [43, 42, 188, 101])
- XCTAssertEqual(log.dives[2].buddy, "Sam, Max") // le contenu de la plongée renumérotée n'a pas bougé
+ XCTAssertEqual(log.dives[2].buddy, "Sam, Max") // the content of the renumbered dive has not changed
_ = try await repo.sync(transport: transport)
try remote.git(["fsck", "--strict"])
XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2024/07/13-Sat-10=15=30"]), "Dive-188\nDivecomputer")
@@ -419,7 +420,7 @@ final class SubsurfaceLogTests: XCTestCase {
try await repo.enqueue(.locateSite(uuid: 0xabc, latitude: 45.26166, longitude: -81.66015))
let log = try await repo.enqueue(.locateSite(uuid: 0x7f3a1b2c, latitude: 45.5, longitude: -75.5))
XCTAssertEqual(log.sites[0xabc]?.latitude, 45.26166)
- // Un lieu qui ne sert plus se retire ; les autres restent.
+ // A site that is no longer used can be removed; the others stay.
try await repo.enqueue(.addSite(uuid: 0xdef, name: "En trop", latitude: nil, longitude: nil))
let trimmed = try await repo.enqueue(.removeSite(uuid: 0xdef))
XCTAssertNil(trimmed.sites[0xdef])
diff --git a/README.md b/README.md
@@ -1,58 +1,96 @@
# Sub Rascasse
-App iPhone pour le carnet de plongée de [Subsurface](https://subsurface-divelog.org) : elle lit et modifie le carnet
-gardé dans le nuage Subsurface, dans le même format, sans passer par l'app officielle. Application indépendante,
-sans lien avec l'équipe de Subsurface.
-
-## Ce qui marche (0.1)
-
-- Connexion au nuage Subsurface (courriel + mot de passe, gardé dans le trousseau), carnet copié sur l'iPhone.
-- Liste par voyage ou par mois, recherche, fiche de plongée avec profil (profondeur, température, pression,
- paliers, événements, lecture au doigt), plusieurs ordinateurs par plongée.
-- Modification hors ligne : lieu, binôme, guide, combinaison, étiquettes, évaluation, visibilité, notes ;
- ajout d'une plongée à la main, création d'un lieu, suppression. Envoi à la synchronisation suivante.
-- Carte et liste des lieux, statistiques, unités métriques ou impériales.
-- Import d'un export Shearwater Cloud (`.zip` ou `dive_data.db`) ou de la base de l'app Dive Shearwater
- (`watermelon.db`, dans `~/Library/Containers/com.shearwater.dive/Data/Documents` quand l'app iOS tourne sur un Mac) : profils complets, gaz, paliers, pression,
- lieux créés au besoin, doublons écartés. Décodage PNF d'après libdivecomputer (`shearwater_predator_parser.c`),
- https://github.com/libdivecomputer/libdivecomputer.
-- Plongées d'Open Rémora (ordinateur de plongée pour Apple Watch) : au lancement, au retour au premier plan et à
- l'ouverture de `subrascasse://open-remora`, l'app lit `OpenRemora/Plongees/*.json` dans le groupe d'apps
- `group.org.schurger.dive`, ajoute les plongées au carnet et retire les fichiers (contrat : `docs/PARTAGE.md`
- du dépôt open-remora). Rien n'est lu tant qu'aucun carnet n'est ouvert.
-- Photos : la fiche d'une plongée montre les photos et vidéos de la photothèque prises pendant la plongée (20 min
- avant, 30 min après), placées sur le profil à leur heure, donc à leur profondeur ; la fiche d'un lieu montre celles
- de toutes ses plongées. L'heure du carnet est locale au lieu : le fuseau vient de la position du lieu (géocodage
- inverse d'Apple, gardé ensuite). Lecture seule, rien n'est envoyé.
-- Création d'un compte du nuage Subsurface (courriel, mot de passe, code reçu par courriel).
-- Carnet de démonstration (bouton sur l'écran de connexion, ou option de lancement `-demo`).
-
-Pas encore : téléchargement depuis un ordinateur de plongée, import XML de Subsurface, photos, planificateur, anglais.
-
-## Organisation
-
-- `Packages/DiveKit/Sources/GitLite` : client git en Swift pur (objets, paquets, protocole « smart HTTP »,
- récupération superficielle et incrémentale, envoi). Aucune dépendance binaire.
-- `Packages/DiveKit/Sources/SubsurfaceLog` : format de stockage git de Subsurface (`Loader`), modifications
- (`Changes` : seules les lignes touchées d'un fichier sont réécrites, le reste est conservé à l'octet près),
- synchronisation (`Repository` : les modifications en attente se rejouent sur l'état du serveur).
-- `App` : interface SwiftUI. Le nom affiché et l'identifiant ne vivent que dans `project.yml` et `App/Brand.swift`.
-
-Le format a été écrit d'après les sources de Subsurface (`core/save-git.cpp`, `core/load-git.cpp`, GPL-2.0),
-https://github.com/subsurface/subsurface, et validé sur deux carnets publics :
-https://github.com/Egbertdepauw/anchorline (vrais exports) et https://github.com/Ventrilok/divelens.
-
-## Travailler dessus
-
-Le code vit sur hotrats, Swift et Xcode tournent sur chunga.
-
- make test-kit # tests du paquet (contre le vrai git en ligne de commande)
- make build # app pour le simulateur
- make shot SHOT=liste # capture avec le carnet de démonstration (build/shots/)
- make shot SHOT=fiche ARGS="-showDive 11"
-
-Options de lancement : `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`,
-`-newDive`, `-demoChanges`, `-importFile chemin`, `-importAll`, `-createAccount`, `-remoraFolder chemin`.
-
-Valider sur un vrai carnet : `SUBSURFACE_TREE=/chemin/arbre swift test --filter testExternalTree` (dossier
-disposé comme l'arbre git : `00-Subsurface`, `01-Divesites/`, `aaaa/mm/…`).
+An iPhone app for [Subsurface](https://subsurface-divelog.org) dive logs: it reads and edits the logbook kept in
+Subsurface cloud storage, in the same format, without going through the official app.
+
+Sub Rascasse is an independent application. It is not affiliated with, or endorsed by, the Subsurface team.
+
+The app is available in English and French.
+
+## Features
+
+- Sign in to Subsurface cloud storage (email and password, kept in the keychain); the logbook is copied to the
+ iPhone.
+- Dive list by trip or by month, search, and a dive page with its profile (depth, temperature, pressure, deco
+ stops, events, scrubbing with a finger), with several dive computers per dive.
+- Offline editing: site, buddy, guide, suit, tags, rating, visibility, notes; adding a dive by hand, creating a
+ site, deleting a dive. Changes are sent at the next sync.
+- Map and list of dive sites, statistics, metric or imperial units.
+- Import of a Shearwater Cloud export (`.zip` or `dive_data.db`) or of the Dive Shearwater app database
+ (`watermelon.db`, found in `~/Library/Containers/com.shearwater.dive/Data/Documents` when the iOS app runs on a
+ Mac): full profiles, gases, deco stops, pressure, sites created as needed, duplicates skipped.
+- Dives from Open Rémora (a dive computer for Apple Watch): at launch, when coming back to the foreground and when
+ `subrascasse://open-remora` is opened, the app reads `OpenRemora/Plongees/*.json` in the
+ `group.org.schurger.dive` app group, adds the dives to the logbook and removes the files (the contract is
+ `docs/PARTAGE.md` in the open-remora repository). Nothing is read until a logbook is open.
+- Photos: a dive page shows the photos and videos of the photo library taken during the dive (from 20 minutes
+ before to 30 minutes after), placed on the profile at their time, hence at their depth; a site page shows those
+ of all its dives. Logbook times are local to the site: the time zone comes from the site's position (Apple
+ reverse geocoding, then remembered). Read-only; nothing is sent anywhere.
+- 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).
+
+Not there yet: downloading from a dive computer, Subsurface XML import, dive planner.
+
+## Architecture
+
+- `Packages/DiveKit/Sources/GitLite`: a git client in pure Swift (objects, packfiles, the smart HTTP protocol,
+ shallow and incremental fetch, push). No binary dependency.
+- `Packages/DiveKit/Sources/SubsurfaceLog`: the Subsurface git storage format.
+ - `Loader` reads the format.
+ - `Changes` applies line-level edits: only the lines touched in a file are rewritten, the rest of the file is
+ kept byte-identical.
+ - `Repository` handles sync: an offline change queue, replayed on top of the server state.
+ - Importers for the Shearwater and Open Rémora formats.
+- `Packages/DiveKit/Sources/divelog-cli`: a macOS command-line tool running the same code as the app (list a cloud
+ logbook, inspect or import a file).
+- `App`: the SwiftUI interface. The display name and the bundle identifier live only in `project.yml` and
+ `App/Brand.swift`.
+
+## Acknowledgements and sources
+
+- The storage format was written from the Subsurface sources (`core/save-git.cpp`, `core/load-git.cpp`,
+ GPL-2.0): https://github.com/subsurface/subsurface
+- The Shearwater PNF format is decoded after libdivecomputer (`shearwater_predator_parser.c`):
+ https://github.com/libdivecomputer/libdivecomputer
+- The format reader was validated on two public sample logbooks: https://github.com/Egbertdepauw/anchorline (real
+ exports) and https://github.com/Ventrilok/divelens
+
+## Building and testing
+
+ make test-kit # package tests (checked against the real command-line git)
+ make build # app for the simulator
+ make shot SHOT=list # screenshot with the demo logbook (build/shots/)
+ make shot SHOT=dive ARGS="-showDive 11"
+
+`make test-kit FILTER=TestName` runs a single test.
+
+Launch options: `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`, `-newDive`,
+`-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`.
+
+### Validating on a real logbook
+
+These tests are skipped unless their environment variables are set (run them from `Packages/DiveKit`):
+
+- `SUBSURFACE_TREE=/path/to/tree swift test --filter testExternalTree`: a folder laid out like the git tree
+ (`00-Subsurface`, `01-Divesites/`, `yyyy/mm/…`).
+- `SHEARWATER_EXPORT=/path/to/export swift test --filter testRealShearwaterExport`: a Shearwater Cloud export
+ (the `.zip` or `dive_data.db`).
+- `CLOUD_EMAIL=… CLOUD_PASSWORD=… swift test --filter testRealCloudReadOnly`: a real Subsurface cloud account,
+ read-only; nothing is pushed.
+
+### Development setup
+
+The Makefile assumes the author's setup: the sources are edited on a Linux host and synced with `rsync` to a Mac
+reachable over SSH as `chunga`, which runs Swift and Xcode. Set `CHUNGA` (the SSH host) and `REMOTE` (the
+directory on the Mac) to adapt it:
+
+ make build CHUNGA=my-mac REMOTE=src/subrascasse
+
+Or work directly on a Mac: run `xcodegen` at the root of the repository and open the generated Xcode project
+(`project.yml` is the source of truth; the `.xcodeproj` is not versioned), and run `swift test` in
+`Packages/DiveKit`.
+
+## License
+
+GPL-2.0-only. See [LICENSE](LICENSE).
diff --git a/fastlane/Fastfile b/fastlane/Fastfile
@@ -2,7 +2,7 @@ require "tmpdir"
default_platform(:ios)
-# Compte développeur perso (équipe CM5RQKJH56), clé App Store Connect lue dans ~/.zshrc_build de chunga.
+# Developer account (team CM5RQKJH56); the App Store Connect key comes from the environment (~/.zshrc_build on the build Mac).
APP_ID = "org.schurger.subrascasse"
def api_key
@@ -33,28 +33,31 @@ platform :ios do
[res.code.to_i, (JSON.parse(res.body) rescue {})]
end
- desc "Groupe de testeurs internes, textes TestFlight et notes de la dernière build"
+ desc "Internal tester group, TestFlight texts and notes of the latest build"
lane :beta_setup do
api_key
app = Spaceship::ConnectAPI::App.find(APP_ID)
_, groups = asc(:get, "/v1/apps/#{app.id}/betaGroups")
group = groups["data"].find { |g| g["attributes"]["name"] == "Interne" }
unless group
- # POST brut : spaceship envoie publicLinkLimitEnabled, refusé pour un groupe interne.
+ # Raw POST: spaceship sends publicLinkLimitEnabled, which is refused for an internal group.
c, r = asc(:post, "/v1/betaGroups", { data: { type: "betaGroups",
attributes: { name: "Interne", isInternalGroup: true, hasAccessToAllBuilds: true },
relationships: { app: { data: { type: "apps", id: app.id } } } } })
- UI.message("GROUPE Interne -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
+ UI.message("GROUP Interne -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
group = r["data"]
end
- email = ENV["PERSO_APPLE_ID"] || "jean@schurger.org"
+ # The internal tester comes from the build machine's environment, never from the repository.
+ email = ENV["PERSO_APPLE_ID"] or UI.user_error!("PERSO_APPLE_ID is not set")
+ first_name = ENV["PERSO_FIRST_NAME"] || "Internal"
+ last_name = ENV["PERSO_LAST_NAME"] || "Tester"
_, testers = asc(:get, "/v1/betaTesters?filter[email]=#{email}&filter[apps]=#{app.id}")
if testers["data"].empty?
- c, r = asc(:post, "/v1/betaTesters", { data: { type: "betaTesters", attributes: { email: email, firstName: "Jean", lastName: "Schurger" },
+ c, r = asc(:post, "/v1/betaTesters", { data: { type: "betaTesters", attributes: { email: email, firstName: first_name, lastName: last_name },
relationships: { betaGroups: { data: [{ type: "betaGroups", id: group["id"] }] } } } })
- UI.message("TESTEUR #{email} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
+ UI.message("TESTER #{email} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
else
- UI.message("TESTEUR #{email} déjà présent")
+ UI.message("TESTER #{email} already there")
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.",
@@ -76,7 +79,7 @@ platform :ios do
end
_, builds = asc(:get, "/v1/builds?filter[app]=#{app.id}&sort=-uploadedDate&limit=1")
build = builds["data"].first
- UI.user_error!("Aucune build encore visible") unless build
+ UI.user_error!("No build visible yet") unless build
UI.message("BUILD #{build["attributes"]["version"]} #{build["attributes"]["processingState"]}")
_, blocs = asc(:get, "/v1/builds/#{build["id"]}/betaBuildLocalizations")
texts.each do |locale, (_, what)|
@@ -87,7 +90,7 @@ platform :ios do
asc(:post, "/v1/betaBuildLocalizations", { data: { type: "betaBuildLocalizations", attributes: { locale: locale, whatsNew: what },
relationships: { build: { data: { type: "builds", id: build["id"] } } } } })
end
- UI.message("A TESTER #{locale} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
+ UI.message("WHAT TO TEST #{locale} -> #{c} #{(r["errors"] || []).map { |e| e["detail"] }.join(" ; ")}")
end
end
end
diff --git a/project.yml b/project.yml
@@ -1,9 +1,9 @@
-# Projet Xcode généré par XcodeGen (`xcodegen` sur chunga) : modifier ce fichier, pas le .xcodeproj.
-# Le nom affiché « Sub Rascasse » n'apparaît qu'ici (nom affiché, identifiant) et dans App/Brand.swift.
+# Xcode project generated by XcodeGen (`xcodegen`): edit this file, not the .xcodeproj.
+# The display name "Sub Rascasse" appears only here (display name, identifier) and in App/Brand.swift.
name: DiveLog
options:
bundleIdPrefix: org.schurger
- developmentLanguage: fr
+ developmentLanguage: en
deploymentTarget:
iOS: "17.0"
packages:
@@ -42,19 +42,20 @@ targets:
CFBundleDisplayName: Sub Rascasse
CFBundleShortVersionString: $(MARKETING_VERSION)
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
- CFBundleLocalizations: [fr, en]
+ CFBundleLocalizations: [en, fr]
ITSAppUsesNonExemptEncryption: false
UILaunchScreen: {}
UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight]
- NSPhotoLibraryUsageDescription: Sub Rascasse signale les plongées dont vous avez des photos ou des vidéos et les montre sur leur fiche. Elles restent sur l'iPhone, rien n'est envoyé.
- # Open Rémora ouvre « subrascasse://open-remora » après avoir déposé une plongée.
+ # French translation in App/InfoPlist.xcstrings.
+ NSPhotoLibraryUsageDescription: "Sub Rascasse flags the dives you have photos or videos of and shows them on the dive page. They stay on your iPhone; nothing is sent."
+ # Open Remora opens "subrascasse://open-remora" after dropping a dive.
CFBundleURLTypes:
- CFBundleURLName: org.schurger.subrascasse
CFBundleURLSchemes: [subrascasse]
entitlements:
path: App/DiveLog.entitlements
properties:
- # Dossier partagé avec Open Rémora (plongées de la montre à importer).
+ # Folder shared with Open Remora (dives from the watch, to be imported).
com.apple.security.application-groups: [group.org.schurger.dive]
schemes:
DiveLog:
diff --git a/tools/make-icon.swift b/tools/make-icon.swift
@@ -1,5 +1,6 @@
-// Génère l'icône 1024×1024 (sans transparence) : swift tools/make-icon.swift chemin.png
-// Une rascasse juste sous la surface.
+// SPDX-License-Identifier: GPL-2.0-only
+// Generates the 1024×1024 icon (no transparency): swift tools/make-icon.swift path.png
+// A scorpionfish ("rascasse" in French) just below the surface.
import CoreGraphics
import Foundation
import ImageIO
@@ -16,11 +17,11 @@ func rgb(_ r: Double, _ g: Double, _ b: Double, _ a: Double = 1) -> CGColor {
}
let space = CGColorSpaceCreateDeviceRGB()
-// Eau : du bleu profond (bas) au turquoise (haut).
+// Water: from deep blue (bottom) to turquoise (top).
let water = CGGradient(colorsSpace: space, colors: [rgb(6, 40, 92), rgb(8, 104, 150), rgb(64, 190, 205)] as CFArray, locations: [0, 0.6, 1])!
ctx.drawLinearGradient(water, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size), options: [])
-// Surface : une vague claire en haut.
+// Surface: a light wave at the top.
ctx.setFillColor(rgb(214, 244, 250))
ctx.move(to: CGPoint(x: 0, y: size))
ctx.addLine(to: CGPoint(x: 0, y: 850))
@@ -29,7 +30,7 @@ ctx.addCurve(to: CGPoint(x: 1024, y: 850), control1: CGPoint(x: 684, y: 910), co
ctx.addLine(to: CGPoint(x: 1024, y: size))
ctx.fillPath()
-// Sable au fond.
+// Sand at the bottom.
ctx.setFillColor(rgb(232, 204, 150))
ctx.move(to: CGPoint(x: 0, y: 0))
ctx.addLine(to: CGPoint(x: 0, y: 170))
@@ -37,16 +38,16 @@ ctx.addCurve(to: CGPoint(x: 1024, y: 150), control1: CGPoint(x: 340, y: 240), co
ctx.addLine(to: CGPoint(x: 1024, y: 0))
ctx.fillPath()
-// Rascasse : corps trapu rouge orangé, grosse tête, dorsale épineuse, air bougon mais sympathique.
+// Scorpionfish: stocky orange-red body, big head, spiny dorsal fin, grumpy but likeable.
let red = rgb(226, 78, 52), deep = rgb(150, 40, 36), light = rgb(255, 170, 110), belly = rgb(255, 214, 170)
-// Queue.
+// Tail.
ctx.setFillColor(red)
ctx.move(to: CGPoint(x: 300, y: 450))
ctx.addCurve(to: CGPoint(x: 120, y: 610), control1: CGPoint(x: 230, y: 500), control2: CGPoint(x: 150, y: 560))
ctx.addCurve(to: CGPoint(x: 130, y: 300), control1: CGPoint(x: 190, y: 500), control2: CGPoint(x: 190, y: 410))
ctx.addCurve(to: CGPoint(x: 300, y: 450), control1: CGPoint(x: 170, y: 350), control2: CGPoint(x: 240, y: 410))
ctx.fillPath()
-// Dorsale épineuse : une rangée de piquants reliés par une membrane.
+// Spiny dorsal fin: a row of spines joined by a membrane.
let spines: [(Double, Double)] = [(330, 640), (390, 760), (450, 650), (520, 790), (585, 660), (650, 770), (705, 640), (760, 700)]
ctx.setFillColor(light)
ctx.move(to: CGPoint(x: 300, y: 560))
@@ -59,14 +60,14 @@ ctx.setLineCap(.round)
for (x, y) in spines where y > 690 {
ctx.move(to: CGPoint(x: x, y: y)); ctx.addLine(to: CGPoint(x: x - 10, y: 580)); ctx.strokePath()
}
-// Corps.
+// Body.
ctx.saveGState()
let bodyRect = CGRect(x: 240, y: 280, width: 640, height: 400)
ctx.addEllipse(in: bodyRect)
ctx.clip()
let scales = CGGradient(colorsSpace: space, colors: [belly, light, red, deep] as CFArray, locations: [0, 0.25, 0.6, 1])!
ctx.drawLinearGradient(scales, start: CGPoint(x: 0, y: 280), end: CGPoint(x: 0, y: 700), options: [])
-// Marbrures.
+// Mottling.
ctx.setFillColor(rgb(150, 40, 36, 0.45))
for (x, y, r) in [(380.0, 560.0, 34.0), (470, 610, 26), (460, 500, 30), (560, 570, 28), (350, 470, 22), (620, 620, 20), (540, 470, 18)] {
ctx.fillEllipse(in: CGRect(x: x - r, y: y - r * 0.8, width: 2 * r, height: 1.6 * r))
@@ -75,7 +76,7 @@ ctx.restoreGState()
ctx.setStrokeColor(deep)
ctx.setLineWidth(14)
ctx.strokeEllipse(in: bodyRect)
-// Pectorale en éventail.
+// Fan-shaped pectoral fin.
ctx.setFillColor(light)
ctx.move(to: CGPoint(x: 560, y: 430))
ctx.addCurve(to: CGPoint(x: 430, y: 300), control1: CGPoint(x: 500, y: 410), control2: CGPoint(x: 440, y: 360))
@@ -87,7 +88,7 @@ ctx.setLineWidth(10)
for (x, y) in [(450.0, 310.0), (500, 300), (550, 310)] {
ctx.move(to: CGPoint(x: 560, y: 420)); ctx.addLine(to: CGPoint(x: x, y: y)); ctx.strokePath()
}
-// Gros œil, sourcil épineux, joue rose.
+// Big eye, spiny eyebrow, pink cheek.
ctx.setFillColor(rgb(255, 255, 255))
ctx.fillEllipse(in: CGRect(x: 690, y: 500, width: 120, height: 130))
ctx.setFillColor(rgb(30, 30, 50))
@@ -99,14 +100,14 @@ ctx.setLineWidth(16)
ctx.move(to: CGPoint(x: 680, y: 640)); ctx.addLine(to: CGPoint(x: 820, y: 622)); ctx.strokePath()
ctx.setFillColor(rgb(255, 150, 160, 0.7))
ctx.fillEllipse(in: CGRect(x: 690, y: 420, width: 70, height: 40))
-// Grande bouche, un rien boudeuse.
+// Wide mouth, slightly sulky.
ctx.setStrokeColor(deep)
ctx.setLineWidth(16)
ctx.move(to: CGPoint(x: 800, y: 420))
ctx.addQuadCurve(to: CGPoint(x: 878, y: 440), control: CGPoint(x: 840, y: 450))
ctx.strokePath()
-// Bulles qui montent vers la surface.
+// Bubbles rising to the surface.
ctx.setStrokeColor(rgb(255, 255, 255, 0.85))
ctx.setLineWidth(8)
for (x, y, r) in [(900.0, 560.0, 26.0), (930, 670, 18), (905, 760, 12), (200, 700, 20), (160, 780, 13)] {