SPB Git

Repository Public BSD-3-Clause

TracksModel.swift 10.0 KB 266 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/TracksModel.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 Foundation89import Observation90import ORIXGeoCore91import ORIXGeoExchange92import ORIXLocation93import ORIXMapRenderer94import ORIXMapStyle95import ORIXTracks9697/// Track recording (only when the user starts it), the saved tracks and the track shown on the map.98@Observable99final class TracksModel {100    private(set) var summaries: [TrackSummary] = []101    private(set) var recorder: TrackRecorder?102    /// Statistics of the recording in progress, refreshed as fixes arrive.103    private(set) var liveStatistics: TrackStatistics?104    /// The saved track currently drawn on the map.105    private(set) var displayed: Track?106    private(set) var isAvailable = false107    /// A recording interrupted by the application stopping, waiting for the user's decision.108    private(set) var interrupted: Track?109110    @ObservationIgnored private var store: TrackStore?111    @ObservationIgnored private let location: LocationService112    @ObservationIgnored private weak var map: MapController?113    @ObservationIgnored private var consumer: UUID?114    @ObservationIgnored private var unsaved = 0115116    init(directory: URL, location: LocationService, map: MapController) {117        self.location = location118        self.map = map119        store = try? TrackStore(directory: directory)120        isAvailable = store != nil121    }122123    func reload() async {124        guard let store else { return }125        summaries = await store.summaries()126        if recorder == nil { interrupted = await store.activeRecording() }127    }128129    var isRecording: Bool { recorder?.state == .recording }130    var isPaused: Bool { recorder?.state == .paused }131132    // MARK: Recording133134    func startRecording(name: String) {135        guard recorder == nil else { return }136        var r = TrackRecorder(name: name)137        r.start()138        recorder = r139        attach()140    }141142    /// Continues the recording that was in progress when the application stopped.143    func resumeInterrupted() {144        guard let track = interrupted else { return }145        var r = TrackRecorder(resuming: track)146        r.start()147        recorder = r148        interrupted = nil149        attach()150    }151152    func discardInterrupted() {153        interrupted = nil154        Task { await store?.discardActive() }155    }156157    /// Saves the interrupted recording as it is.158    func saveInterrupted() async {159        guard let track = interrupted else { return }160        _ = try? await store?.finishActive(track)161        interrupted = nil162        await reload()163    }164165    private func attach() {166        location.start(.recording)167        consumer = location.addConsumer { [weak self] fix in self?.ingest(fix) }168        redrawLive()169    }170171    private func ingest(_ fix: LocationFix) {172        guard var r = recorder else { return }173        let added = r.add(coordinate: fix.coordinate, time: fix.timestamp, accuracy: fix.horizontalAccuracy, altitude: fix.altitude, speed: fix.speed)174        recorder = r175        guard added else { return }176        liveStatistics = r.track.statistics177        redrawLive()178        unsaved += 1179        if unsaved >= 10 {180            unsaved = 0181            let snapshot = r.track182            Task { try? await store?.saveActive(snapshot) }183        }184    }185186    func pauseRecording() {187        recorder?.pause()188        if let t = recorder?.track { Task { try? await store?.saveActive(t) } }189    }190191    func resumeRecording() { recorder?.start() }192193    /// Stops and saves. Returns the saved track's summary, nil when fewer than two points were recorded.194    @discardableResult195    func stopRecording() async -> TrackSummary? {196        guard var r = recorder else { return nil }197        r.stop()198        if let consumer { location.removeConsumer(consumer) }199        consumer = nil200        location.end(.recording)201        recorder = nil202        liveStatistics = nil203        let saved = try? await store?.finishActive(r.track)204        map?.setOverlay(OverlayID.track, features: [])205        await reload()206        return saved ?? nil207    }208209    private func redrawLive() {210        guard let r = recorder else { return }211        map?.setOverlay(OverlayID.track, features: r.track.segments.filter { $0.count > 1 }.map { OverlayFeature(.line($0.map(\.coordinate))) })212    }213214    // MARK: Saved tracks215216    func track(_ id: UUID) async -> Track? { try? await store?.track(id) }217218    /// Draws a saved track on the map and frames it.219    func show(_ track: Track) {220        guard recorder == nil else { return }221        displayed = track222        map?.setOverlay(OverlayID.track, features: track.segments.filter { $0.count > 1 }.map { OverlayFeature(.line($0.map(\.coordinate))) })223        if let b = track.bounds { map?.fit(b) }224    }225226    func hideDisplayed() {227        displayed = nil228        if recorder == nil { map?.setOverlay(OverlayID.track, features: []) }229    }230231    /// Draws the travelled part of a track during a replay.232    func showReplay(lines: [[Coordinate]]) {233        map?.setOverlay(OverlayID.track, features: lines.filter { $0.count > 1 }.map { OverlayFeature(.line($0)) })234    }235236    func delete(_ id: UUID) async {237        await store?.delete(id)238        if displayed?.id == id { hideDisplayed() }239        await reload()240    }241242    func rename(_ id: UUID, name: String, note: String) async {243        try? await store?.rename(id, to: name, note: note)244        await reload()245    }246247    func exportFile(_ id: UUID, format: ExchangeFormat) async -> URL? {248        guard let t = await track(id) else { return nil }249        let name = t.name.components(separatedBy: CharacterSet(charactersIn: "/\\:?%*|\"<>")).joined()250        return LibraryModel.temporaryFile(named: "\(name.isEmpty ? "track" : name).\(format.fileExtension)", data: ExchangeCodec.encode(t.exchangeDocument(), format: format))251    }252253    /// Imports the tracks of a GPX, GeoJSON or KML file. Returns the number imported, or nil when the file is unusable.254    func importFile(_ url: URL) async -> Int? {255        guard let store else { return nil }256        let scoped = url.startAccessingSecurityScopedResource()257        defer { if scoped { url.stopAccessingSecurityScopedResource() } }258        let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0259        guard size <= ExchangeLimits.maxBytes, let data = try? Data(contentsOf: url), let (doc, _) = try? ExchangeCodec.decode(data, fileExtension: url.pathExtension) else { return nil }260        let tracks = Track.tracks(from: doc, fallbackName: url.deletingPathExtension().lastPathComponent)261        for t in tracks { _ = try? await store.save(t) }262        await reload()263        return tracks.count264    }265}266
Files main
Menu

Theme