SPB Git

Repository Public BSD-3-Clause

TracksScreen.swift 18.8 KB 365 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Tracks/TracksScreen.swift10// Module           : Tracks11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Charts89import ORIXDesignSystem90import ORIXGeoCore91import ORIXGeoExchange92import ORIXTracks93import SwiftUI9495struct TracksScreen: View {96    @Environment(AppModel.self) private var app97    @State private var importing = false98    @State private var message: String?99100    private var tracks: TracksModel { app.tracks }101102    var body: some View {103        List {104            if let interrupted = tracks.interrupted {105                Section("Unfinished recording") {106                    Text(verbatim: "\(interrupted.name) — \(app.settings.formatter.distance(interrupted.statistics.distance))")107                    Button("Continue recording") { tracks.resumeInterrupted(); app.route = .trackRecording; app.modal = nil }108                    Button("Save as it is") { Task { await tracks.saveInterrupted() } }109                    Button("Discard", role: .destructive) { tracks.discardInterrupted() }110                }111            }112            Section {113                if tracks.recorder != nil {114                    Button { app.route = .trackRecording; app.modal = nil } label: { Label("Recording in progress", systemImage: "record.circle.fill").foregroundStyle(ORIX.Palette.danger) }115                } else {116                    Button {117                        tracks.startRecording(name: String(localized: "Track of \(Date().formatted(date: .abbreviated, time: .shortened))"))118                        app.route = .trackRecording119                        app.modal = nil120                    } label: { Label("Record a track", systemImage: "record.circle") }121                        .accessibilityIdentifier("tracks.record")122                }123                Button { importing = true } label: { Label("Import GPX, GeoJSON or KML", systemImage: "square.and.arrow.down") }124            } footer: { Text("Recording uses your position only while it runs, including with the screen locked, and stops when you stop it. Tracks stay on this device.") }125            Section("Saved tracks") {126                if tracks.summaries.isEmpty { Text("No track yet.").foregroundStyle(.secondary) }127                ForEach(tracks.summaries) { s in128                    NavigationLink { TrackDetailScreen(summary: s) } label: {129                        VStack(alignment: .leading, spacing: 2) {130                            Text(s.name)131                            Text(verbatim: [app.settings.formatter.distance(s.statistics.distance), s.statistics.duration.map { app.settings.formatter.duration($0) }, s.createdAt.formatted(date: .abbreviated, time: .omitted)].compactMap { $0 }.joined(separator: " · "))132                                .font(.footnote).foregroundStyle(.secondary)133                        }134                    }135                    .swipeActions { Button("Delete", role: .destructive) { Task { await tracks.delete(s.id) } } }136                    .accessibilityIdentifier("tracks.row")137                }138            }139        }140        .navigationTitle("Tracks")141        .navigationBarTitleDisplayMode(.inline)142        .task { await tracks.reload() }143        .fileImporter(isPresented: $importing, allowedContentTypes: [.json, .xml, .data]) { result in144            guard let url = try? result.get() else { return }145            Task {146                if let n = await tracks.importFile(url), n > 0 { message = String(localized: "\(n) tracks imported.") }147                else { message = String(localized: "No track found in this file. Use GPX, GeoJSON or KML.") }148            }149        }150        .alert("Tracks", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { Button("OK") {} } message: { Text(message ?? "") }151    }152}153154/// Statistics, profile, replay and export of one track.155struct TrackDetailScreen: View {156    @Environment(AppModel.self) private var app157    @Environment(\.dismiss) private var dismiss158    let summary: TrackSummary159    @State private var track: Track?160    @State private var name = ""161    @State private var note = ""162    @State private var exported: URL?163164    var body: some View {165        let f = app.settings.formatter166        let st = track?.statistics ?? summary.statistics167        List {168            Section {169                TextField("Name", text: $name)170                TextField("Note", text: $note, axis: .vertical).lineLimit(1...5)171            }172            Section("Statistics") {173                LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: ORIX.Spacing.m) {174                    StatView("Distance", value: f.distance(st.distance))175                    StatView("Duration", value: st.duration.map { f.duration($0) } ?? "—")176                    StatView("Moving time", value: st.movingDuration.map { f.duration($0) } ?? "—")177                    StatView("Average speed", value: st.averageMovingSpeed.map { f.speed(metersPerSecond: $0) } ?? "—")178                    StatView("Top speed", value: st.maxSpeed.map { f.speed(metersPerSecond: $0) } ?? "—")179                    StatView("Climb", value: st.ascent.map { f.altitude($0) } ?? "—")180                    StatView("Descent", value: st.descent.map { f.altitude($0) } ?? "—")181                    StatView("Highest point", value: st.maxAltitude.map { f.altitude($0) } ?? "—")182                }183                if st.duration == nil { NoticeView("This track has no timestamps: time and speed are unknown.") }184                if st.ascent != nil { NoticeView("Altitudes come from the device's GPS as recorded; climb ignores changes under 3 m.") }185            }186            if let track {187                let profile = TrackProfile(track: track)188                // The charts follow the units setting, like every other figure of the screen.189                let metric = app.settings.units == .metric190                let distanceUnit = metric ? "km" : "mi", altitudeUnit = metric ? "m" : "ft", speedUnit = metric ? "km/h" : "mph"191                let perDistance = metric ? 1000 : 1609.344, altitudeFactor = metric ? 1 : 3.280_84, speedFactor = metric ? 3.6 : 2.236_936192                if profile.points.contains(where: { $0.altitude != nil }) {193                    Section("Altitude") {194                        Chart(Array(profile.points.enumerated()), id: \.offset) { _, p in195                            if let a = p.altitude { AreaMark(x: .value("Distance", p.distance / perDistance), y: .value("Altitude", a * altitudeFactor)).foregroundStyle(ORIX.Palette.accent.opacity(0.25))196                                LineMark(x: .value("Distance", p.distance / perDistance), y: .value("Altitude", a * altitudeFactor)).foregroundStyle(ORIX.Palette.accent) }197                        }198                        .chartXAxisLabel(distanceUnit).chartYAxisLabel(altitudeUnit).frame(height: 160)199                        .accessibilityLabel("Altitude along the track")200                    }201                }202                if profile.points.contains(where: { $0.speed != nil }) {203                    Section("Speed") {204                        Chart(Array(profile.points.enumerated()), id: \.offset) { _, p in205                            if let v = p.speed { LineMark(x: .value("Distance", p.distance / perDistance), y: .value("Speed", v * speedFactor)).foregroundStyle(ORIX.Palette.route) }206                        }207                        .chartXAxisLabel(distanceUnit).chartYAxisLabel(speedUnit).frame(height: 140)208                        .accessibilityLabel("Speed along the track")209                    }210                }211                Section {212                    Button { app.tracks.show(track); app.modal = nil } label: { Label("Show on the map", systemImage: "map") }213                    if TripReplay(track: track) != nil {214                        Button { app.tracks.show(track); app.replay = ReplayState(track: track); app.route = .trackRecording; app.modal = nil } label: { Label("Replay the trip", systemImage: "play.circle") }215                            .accessibilityIdentifier("track.replay")216                    }217                    Menu {218                        ForEach(ExchangeFormat.allCases, id: \.self) { fmt in219                            Button(fmt.rawValue.uppercased()) { Task { exported = await app.tracks.exportFile(track.id, format: fmt) } }220                        }221                    } label: { Label("Export", systemImage: "square.and.arrow.up").frame(maxWidth: .infinity, alignment: .leading).contentShape(.rect) }222                    .accessibilityIdentifier("track.export")223                    if let exported { ShareLink(item: exported) { Label("Share \(exported.lastPathComponent)", systemImage: "paperplane") } }224                    Button("Delete track", role: .destructive) { Task { await app.tracks.delete(summary.id); dismiss() } }225                }226            }227        }228        .navigationTitle(summary.name)229        .navigationBarTitleDisplayMode(.inline)230        .task {231            track = await app.tracks.track(summary.id)232            name = track?.name ?? summary.name233            note = track?.note ?? ""234        }235        .onDisappear {236            if let track, name != track.name || note != track.note { Task { await app.tracks.rename(summary.id, name: name, note: note) } }237        }238    }239}240241/// State of a trip replay shown in the panel.242struct ReplayState: Equatable {243    var track: Track244    var offset: TimeInterval = 0245    var isPlaying = false246    var rate: Double = 20247}248249/// The panel shown while recording a track or replaying one.250struct TrackPanel: View {251    @Environment(AppModel.self) private var app252    @State private var confirmStop = false253254    var body: some View {255        if app.replay != nil { ReplayPanel() } else { recording }256    }257258    private var recording: some View {259        let f = app.settings.formatter260        let st = app.tracks.liveStatistics261        return VStack(alignment: .leading, spacing: ORIX.Spacing.l) {262            PanelHeader(title: app.tracks.recorder?.track.name ?? String(localized: "Track"), subtitle: app.tracks.isPaused ? String(localized: "Paused") : String(localized: "Recording")) { app.route = .home }263            HStack {264                StatView("Distance", value: f.distance(st?.distance ?? 0))265                StatView("Time", value: st?.duration.map { f.duration($0) } ?? "—")266                StatView("Speed", value: app.location.lastFix?.speed.map { f.speed(metersPerSecond: $0) } ?? "—")267            }268            HStack {269                StatView("Climb", value: st?.ascent.map { f.altitude($0) } ?? "—")270                StatView("Altitude", value: app.location.lastFix?.altitude.map { f.altitude($0) } ?? "—")271                StatView("Accuracy", value: app.location.lastFix.map { "±" + f.distance($0.horizontalAccuracy) } ?? "—")272            }273            if app.location.authorization == .denied || app.location.authorization == .restricted {274                NoticeView("Position access is off: nothing can be recorded. Turn it on in Settings.", kind: .error)275            } else if app.location.lastFix == nil {276                NoticeView("Waiting for a position. Recording starts with the first precise fix.")277            }278            AdaptiveStack {279                if app.tracks.isPaused {280                    Button("Resume") { app.tracks.resumeRecording() }.buttonStyle(SecondaryButtonStyle())281                } else {282                    Button("Pause") { app.tracks.pauseRecording() }.buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("track.pause")283                }284                Button("Stop and save") { confirmStop = true }.buttonStyle(PrimaryButtonStyle(tint: AppColor.dangerFill)).accessibilityIdentifier("track.stop")285                    .confirmationDialog("Stop recording?", isPresented: $confirmStop, titleVisibility: .visible) {286                        Button("Stop and save") {287                            Task {288                                let saved = await app.tracks.stopRecording()289                                app.route = .home290                                app.showToast(saved == nil ? String(localized: "Nothing recorded: the track had fewer than two points.") : String(localized: "Track saved"))291                            }292                        }293                        .accessibilityIdentifier("track.stop.confirm")294                    }295            }296            Spacer(minLength: 0)297        }298        .padding(ORIX.Spacing.l)299        .accessibilityElement(children: .contain)300        .accessibilityIdentifier("track.panel")301    }302}303304/// Trip replay controls: the recorded positions are played back in time; nothing between recorded segments is invented.305struct ReplayPanel: View {306    @Environment(AppModel.self) private var app307    @State private var timer: Timer?308309    var body: some View {310        let f = app.settings.formatter311        VStack(alignment: .leading, spacing: ORIX.Spacing.l) {312            if let state = app.replay, let replay = TripReplay(track: state.track) {313                let frame = replay.frame(at: state.offset)314                PanelHeader(title: state.track.name, subtitle: frame.time.formatted(date: .abbreviated, time: .standard)) { stop() }315                HStack {316                    StatView("Distance", value: f.distance(frame.distance))317                    StatView("Speed", value: frame.speed.map { f.speed(metersPerSecond: $0) } ?? "—")318                    StatView("Altitude", value: frame.altitude.map { f.altitude($0) } ?? "—")319                }320                if !frame.isRecorded { NoticeView("Nothing was recorded during this interval (pause or lost signal).") }321                Slider(value: Binding(get: { state.offset }, set: { app.replay?.offset = $0; draw() }), in: 0...max(1, replay.duration)) { Text("Position in the trip") }322                HStack(spacing: ORIX.Spacing.s) {323                    Button(state.isPlaying ? "Pause" : "Play") { app.replay?.isPlaying.toggle() }.buttonStyle(PrimaryButtonStyle(tint: AppColor.primaryFill)).accessibilityIdentifier("replay.play")324                    Picker("Speed", selection: Binding(get: { state.rate }, set: { app.replay?.rate = $0 })) {325                        ForEach([1.0, 5, 20, 60, 200], id: \.self) { Text(verbatim: "×\(Int($0))").tag($0) }326                    }327                    .pickerStyle(.menu)328                }329            }330            Spacer(minLength: 0)331        }332        .padding(ORIX.Spacing.l)333        .onAppear {334            draw()335            timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in336                Task { @MainActor in337                    guard var s = app.replay, s.isPlaying, let replay = TripReplay(track: s.track) else { return }338                    s.offset = min(replay.duration, s.offset + 0.1 * s.rate)339                    if s.offset >= replay.duration { s.isPlaying = false }340                    app.replay = s341                    draw()342                }343            }344        }345        .onDisappear { timer?.invalidate(); timer = nil }346        .accessibilityElement(children: .contain)347        .accessibilityIdentifier("replay.panel")348    }349350    private func draw() {351        guard let state = app.replay, let replay = TripReplay(track: state.track) else { return }352        let frame = replay.frame(at: state.offset)353        app.tracks.showReplay(lines: replay.traveledPath(at: state.offset))354        app.showReplayMarker(at: frame.coordinate, bearing: frame.bearing)355    }356357    private func stop() {358        timer?.invalidate()359        app.replay = nil360        app.showReplayMarker(at: nil, bearing: nil)361        app.tracks.hideDisplayed()362        app.route = .home363    }364}365
Files main
Menu

Theme