commit fd8cb13b71f22b10cf9e316cf5379f47b116c18b
parent 9aa575655228ef1c352ee27109bb9dd52dd2181f
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 23:45:41 -0500
Show photo-library photos on dive and site pages, placed on the profile at the time they were taken
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
7 files changed, 395 insertions(+), 1 deletion(-)
diff --git a/App/Model/DivePhotos.swift b/App/Model/DivePhotos.swift
@@ -0,0 +1,95 @@
+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.
+struct DivePhoto: Identifiable {
+ let asset: PHAsset
+ /// Secondes depuis la mise à l'eau quand la photo a été prise pendant la plongée ; nil sinon.
+ let offset: Int?
+ var id: String { asset.localIdentifier }
+}
+
+/// Accès à la photothèque : l'app ne fait que lire, et seulement après accord.
+@MainActor
+@Observable
+final class PhotoAccess {
+ var status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
+
+ var granted: Bool { status == .authorized || status == .limited }
+
+ func request() async {
+ status = await PHPhotoLibrary.requestAuthorization(for: .readWrite)
+ }
+}
+
+/// 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.
+enum SiteTimeZone {
+ private static func key(_ site: DiveSite) -> String {
+ String(format: "tz-%.2f,%.2f", site.latitude ?? 0, site.longitude ?? 0)
+ }
+
+ static func cached(for site: DiveSite?) -> TimeZone? {
+ guard let site, site.hasLocation, let name = UserDefaults.standard.string(forKey: key(site)) else { return nil }
+ return TimeZone(identifier: name)
+ }
+
+ /// Sans position, ou si la recherche échoue : le fuseau de l'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 }
+ let placemarks = try? await CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude))
+ if let zone = placemarks?.first?.timeZone {
+ 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.
+ 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") }
+
+ /// Instant absolu d'une heure « naïve » du carnet, dans le fuseau du lieu.
+ 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.
+ static func window(for dive: Dive, elapsed: Int, zone: TimeZone) -> DateInterval {
+ if timeIsGuessed(dive) {
+ let dayStart = dive.when - dive.when % 86_400
+ return DateInterval(start: absolute(dayStart, in: zone), duration: 86_400)
+ }
+ let start = absolute(dive.when, in: zone)
+ return DateInterval(start: start.addingTimeInterval(-20 * 60), duration: TimeInterval(elapsed + 50 * 60))
+ }
+
+ /// Photos et vidéos de la fenêtre, dans l'ordre de prise de vue.
+ 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()
+ options.predicate = NSPredicate(format: "creationDate >= %@ AND creationDate <= %@", window.start as NSDate, window.end as NSDate)
+ options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
+ options.fetchLimit = limit
+ let start = absolute(dive.when, in: zone)
+ var out = [DivePhoto]()
+ PHAsset.fetchAssets(with: options).enumerateObjects { asset, _, _ in
+ var offset: Int?
+ if !timeIsGuessed(dive), let taken = asset.creationDate {
+ let seconds = Int(taken.timeIntervalSince(start))
+ if seconds >= 0, seconds <= elapsed { offset = seconds }
+ }
+ out.append(DivePhoto(asset: asset, offset: offset))
+ }
+ return out
+ }
+}
diff --git a/App/Views/DiveDetailView.swift b/App/Views/DiveDetailView.swift
@@ -13,6 +13,10 @@ struct DiveDetailView: View {
@State private var editing = LaunchOptions.flag("-edit")
@State private var confirmingDelete = false
@State private var error: String?
+ @State private var photoAccess = PhotoAccess()
+ @State private var photos: [DivePhoto] = []
+ @State private var photosLoading = false
+ @State private var photoZone = TimeZone.current
var body: some View {
if let dive = model.dive(id: diveID) {
@@ -64,7 +68,8 @@ struct DiveDetailView: View {
}
}
if computers.indices.contains(computerIndex), computers[computerIndex].samples.count > 1 {
- ProfileChart(data: ProfileData(computer: computers[computerIndex], units: units), units: units)
+ ProfileChart(data: ProfileData(computer: computers[computerIndex], units: units), units: units,
+ photoOffsets: photos.compactMap(\.offset))
.padding(.vertical, 4)
} else if loadedFor == dive.computerBlobs.map(\.hex) {
Text("Pas de profil enregistré pour cette plongée.")
@@ -74,6 +79,16 @@ 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.",
+ onGranted: { Task { await loadPhotos(dive) } },
+ caption: { photoCaption($0) })
+ .id("photos")
+ }
+
if !dive.buddy.isEmpty || !dive.divemaster.isEmpty {
Section("Équipe") {
if !dive.buddy.isEmpty { LabeledContent("Binôme", value: dive.buddy) }
@@ -206,6 +221,35 @@ struct DiveDetailView: View {
// Par défaut, l'ordinateur qui a le profil le plus détaillé.
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).
+ private func elapsed(_ dive: Dive) -> Int {
+ max(dive.durationSeconds, computers.compactMap { $0.samples.last?.time }.max() ?? 0)
+ }
+
+ private func loadPhotos(_ dive: Dive) async {
+ guard photoAccess.granted else { return }
+ photosLoading = photos.isEmpty
+ let zone = await SiteTimeZone.zone(for: model.logbook.site(of: dive))
+ photoZone = zone
+ photos = DivePhotoFinder.photos(for: dive, elapsed: elapsed(dive), zone: zone)
+ photosLoading = false
+ }
+
+ /// « 10 h 36 · 12,4 m » pour une photo prise sous l'eau, l'heure seule sinon.
+ private func photoCaption(_ photo: DivePhoto) -> String {
+ var parts = [String]()
+ if let taken = photo.asset.creationDate {
+ parts.append(taken.formatted(Date.FormatStyle(timeZone: photoZone).hour().minute()))
+ }
+ 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")
}
+ return parts.joined(separator: " · ")
}
}
diff --git a/App/Views/PhotoViews.swift b/App/Views/PhotoViews.swift
@@ -0,0 +1,205 @@
+import AVKit
+import Photos
+import SubsurfaceLog
+import SwiftUI
+
+/// Vignette carrée d'une photo ou d'une vidéo de la photothèque.
+struct PhotoThumbnail: View {
+ let asset: PHAsset
+ var side: CGFloat = 96
+ @State private var image: UIImage?
+
+ var body: some View {
+ ZStack(alignment: .bottomTrailing) {
+ Group {
+ if let image {
+ Image(uiImage: image).resizable().scaledToFill()
+ } else {
+ Color(.tertiarySystemGroupedBackground)
+ }
+ }
+ .frame(width: side, height: side)
+ .clipped()
+ if asset.mediaType == .video {
+ Label(Units.clock(Int(asset.duration.rounded())), systemImage: "video.fill")
+ .font(.caption2.weight(.semibold))
+ .labelStyle(.titleAndIcon)
+ .padding(.horizontal, 5)
+ .padding(.vertical, 2)
+ .background(.black.opacity(0.55), in: Capsule())
+ .foregroundStyle(.white)
+ .padding(4)
+ }
+ }
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .task(id: asset.localIdentifier) {
+ let options = PHImageRequestOptions()
+ options.deliveryMode = .opportunistic
+ options.isNetworkAccessAllowed = true
+ let scale = UIScreen.main.scale
+ PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: side * scale, height: side * scale),
+ contentMode: .aspectFill, options: options) { result, _ in
+ if let result { image = result }
+ }
+ }
+ }
+}
+
+/// Une photo en grand, ou une vidéo qu'on peut lire.
+private struct FullPhoto: View {
+ let asset: PHAsset
+ @State private var image: UIImage?
+ @State private var player: AVPlayer?
+
+ var body: some View {
+ ZStack {
+ if let player {
+ VideoPlayer(player: player)
+ } else if let image {
+ Image(uiImage: image).resizable().scaledToFit()
+ } else {
+ ProgressView().tint(.white)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .task(id: asset.localIdentifier) {
+ let options = PHImageRequestOptions()
+ options.deliveryMode = .highQualityFormat
+ options.isNetworkAccessAllowed = true
+ PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 2400, height: 2400), contentMode: .aspectFit,
+ options: options) { result, _ in
+ if let result { image = result }
+ }
+ if asset.mediaType == .video {
+ let video = PHVideoRequestOptions()
+ video.isNetworkAccessAllowed = true
+ PHImageManager.default().requestPlayerItem(forVideo: asset, options: video) { item, _ in
+ guard let item else { return }
+ DispatchQueue.main.async { player = AVPlayer(playerItem: item) }
+ }
+ }
+ }
+ .onDisappear { player?.pause() }
+ }
+}
+
+/// Défilement plein écran des photos d'une plongée ; la légende donne l'heure, et la profondeur quand on la connaît.
+struct PhotoViewer: View {
+ @Environment(\.dismiss) private var dismiss
+ let photos: [DivePhoto]
+ @State var index: Int
+ let caption: (DivePhoto) -> String
+
+ var body: some View {
+ NavigationStack {
+ TabView(selection: $index) {
+ ForEach(Array(photos.enumerated()), id: \.offset) { position, photo in
+ FullPhoto(asset: photo.asset).tag(position)
+ }
+ }
+ .tabViewStyle(.page(indexDisplayMode: .never))
+ .background(Color.black)
+ .ignoresSafeArea(edges: .bottom)
+ .safeAreaInset(edge: .bottom) {
+ if photos.indices.contains(index) {
+ Text(caption(photos[index]))
+ .font(.footnote.monospacedDigit())
+ .foregroundStyle(.white)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(.black.opacity(0.5), in: Capsule())
+ .padding(.bottom, 12)
+ }
+ }
+ .navigationTitle("\(index + 1) sur \(photos.count)")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(.black, for: .navigationBar)
+ .toolbarColorScheme(.dark, for: .navigationBar)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } }
+ }
+ }
+ }
+}
+
+/// Contenu d'une section « Photos » : demande d'accès, état vide, ou bande de vignettes.
+struct PhotoStrip: View {
+ let access: PhotoAccess
+ let photos: [DivePhoto]
+ let loading: Bool
+ let emptyText: String
+ let onGranted: () -> Void
+ let caption: (DivePhoto) -> String
+ @State private var viewing: ViewedPhoto?
+
+ private struct ViewedPhoto: Identifiable {
+ let id: Int
+ }
+
+ var body: some 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é.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ Button {
+ Task {
+ await access.request()
+ if access.granted { onGranted() }
+ }
+ } label: {
+ Label("Autoriser l'accès aux photos", 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.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ if let url = URL(string: UIApplication.openSettingsURLString) {
+ Link("Ouvrir les réglages", destination: url)
+ }
+ }
+ default:
+ if loading {
+ ProgressView().frame(maxWidth: .infinity, minHeight: 96)
+ } else if photos.isEmpty {
+ Text(emptyText).font(.footnote).foregroundStyle(.secondary)
+ } else {
+ VStack(alignment: .leading, spacing: 6) {
+ ScrollView(.horizontal, showsIndicators: false) {
+ LazyHStack(spacing: 6) {
+ ForEach(Array(photos.enumerated()), id: \.element.id) { position, photo in
+ PhotoThumbnail(asset: photo.asset)
+ .overlay(alignment: .topLeading) {
+ if photo.offset != nil {
+ Image(systemName: "water.waves")
+ .font(.caption2.weight(.bold))
+ .padding(4)
+ .background(Color.accentColor, in: Circle())
+ .foregroundStyle(.white)
+ .padding(4)
+ .accessibilityLabel("Prise pendant la plongée")
+ }
+ }
+ .onTapGesture { viewing = ViewedPhoto(id: position) }
+ .accessibilityAddTraits(.isButton)
+ }
+ }
+ }
+ Text(summary).font(.caption).foregroundStyle(.secondary)
+ }
+ .fullScreenCover(item: $viewing) { viewed in
+ PhotoViewer(photos: photos, index: viewed.id, caption: caption)
+ }
+ }
+ }
+ }
+
+ 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
+ }
+}
diff --git a/App/Views/ProfileChart.swift b/App/Views/ProfileChart.swift
@@ -101,6 +101,8 @@ struct ProfileData {
struct ProfileChart: View {
let data: ProfileData
let units: Units
+ /// Instants (secondes depuis la mise à l'eau) où une photo a été prise.
+ var photoOffsets: [Int] = []
@State private var selection: Double?
private let axisWidth: CGFloat = 34
@@ -187,6 +189,18 @@ 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))
+ .symbol(.circle)
+ .symbolSize(photoOffsets.count > 25 ? 22 : 46)
+ .foregroundStyle(Color.pink)
+ .annotation(position: .top, spacing: 1) {
+ if photoOffsets.count <= 25 {
+ Image(systemName: "camera.fill").font(.system(size: 8)).foregroundStyle(.pink)
+ }
+ }
+ }
if let selection {
RuleMark(x: .value("Temps", selection))
.foregroundStyle(Color.secondary.opacity(0.6))
diff --git a/App/Views/SitesView.swift b/App/Views/SitesView.swift
@@ -123,6 +123,10 @@ struct SitesView: View {
struct SiteDetailView: View {
@Environment(AppModel.self) private var model
let uuid: UInt32
+ @State private var photoAccess = PhotoAccess()
+ @State private var photos: [DivePhoto] = []
+ @State private var photosLoading = false
+ @State private var photoZone = TimeZone.current
var body: some View {
let site = model.logbook.sites[uuid]
@@ -161,6 +165,14 @@ struct SiteDetailView: View {
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("Photos") {
+ PhotoStrip(access: photoAccess, photos: photos, loading: photosLoading,
+ emptyText: "Aucune photo de vos plongées ici dans la photothèque de cet iPhone.",
+ onGranted: { Task { await loadPhotos(dives) } },
+ caption: { photo in
+ photo.asset.creationDate?.formatted(Date.FormatStyle(date: .abbreviated, time: .shortened, timeZone: photoZone)) ?? ""
+ })
+ }
Section("Plongées") {
ForEach(dives) { dive in
NavigationLink(value: dive.id) {
@@ -182,5 +194,24 @@ struct SiteDetailView: View {
}
.navigationTitle(site?.name ?? "Lieu")
.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).
+ private func loadPhotos(_ dives: [Dive]) async {
+ guard photoAccess.granted else { return }
+ photosLoading = photos.isEmpty
+ let zone = await SiteTimeZone.zone(for: model.logbook.sites[uuid])
+ photoZone = zone
+ var found = [DivePhoto]()
+ var seen = Set<String>()
+ for dive in dives.prefix(40) {
+ for photo in DivePhotoFinder.photos(for: dive, elapsed: dive.durationSeconds, zone: zone, limit: 60) where seen.insert(photo.id).inserted {
+ found.append(photo)
+ }
+ if found.count >= 300 { break }
+ }
+ photos = found
+ photosLoading = false
}
}
diff --git a/README.md b/README.md
@@ -20,6 +20,10 @@ sans lien avec l'équipe de Subsurface.
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`).
diff --git a/project.yml b/project.yml
@@ -46,6 +46,7 @@ targets:
ITSAppUsesNonExemptEncryption: false
UILaunchScreen: {}
UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight]
+ NSPhotoLibraryUsageDescription: Sub Rascasse montre, sur la fiche d'une plongée, les photos et vidéos que vous avez prises pendant cette plongée. Elles restent sur l'iPhone.
# Open Rémora ouvre « subrascasse://open-remora » après avoir déposé une plongée.
CFBundleURLTypes:
- CFBundleURLName: org.schurger.subrascasse