SPB Git

Repository Public BSD-3-Clause

AppModel.swift 24.7 KB 528 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/App/AppModel.swift10// Module           : App11// 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 ORIXDesignSystem91import ORIXGeoCore92import ORIXLocation93import ORIXMapPackage94import ORIXMapRenderer95import ORIXMapStyle96import SwiftUI9798/// A place shown in the place card: a search result, a map feature, a saved place or a bare coordinate.99struct PlaceSelection: Identifiable, Equatable {100    enum Origin: Equatable { case droppedPin, mapFeature, search, saved(String), coordinates }101    var id = UUID()102    var title: String103    var subtitle: String?104    var coordinate: Coordinate105    var origin: Origin106    /// Category identifier (search taxonomy) or tile kind, when known.107    var category: String?108    /// Extra facts taken from the data (phone, website, opening hours text…), shown as they are.109    var details: [String: String] = [:]110}111112/// How the map follows the position.113enum TrackingMode: Equatable { case none, follow, followWithHeading }114115/// What the panel (bottom sheet on iPhone, side panel on iPad) shows.116enum PanelRoute: Equatable {117    case home118    case place(PlaceSelection)119    case directions120    case navigation121    case measure122    case trackRecording123}124125/// Full-screen or sheet destinations opened from the menu.126enum ModalRoute: String, Identifiable {127    case layers, downloads, collections, tracks, settings, compass, studio, explorer, about, planner128    var id: String { rawValue }129}130131/// Composition root: owns the stores and services and the interface state shared by the screens.132@Observable133final class AppModel {134    let options: LaunchOptions135    let settings: AppSettings136    let map: MapController137    let themes: ThemeStore138    let location: LocationService139    let regionsModel: RegionsModel140    let library: LibraryModel141    let tracks: TracksModel142    let search: SearchModel143    let directions: DirectionsModel144    let userLayers: UserLayersModel145    /// A trip replay in progress, shown in the panel.146    var replay: ReplayState?147    @ObservationIgnored let style: StyleCoordinator148    @ObservationIgnored let directories: AppDirectories149150    var route: PanelRoute = .home151    var modal: ModalRoute?152    var tracking: TrackingMode = .none153    /// Interface colour scheme currently in effect (reported by the root view).154    var isDarkInterface = false { didSet { if oldValue != isDarkInterface { refreshStyle() } } }155    private(set) var regions: [MapRegion] = []156    /// A short message shown above the panel (errors, confirmations), cleared automatically.157    var toast: String?158159    init(options: LaunchOptions = LaunchOptions()) {160        self.options = options161        let dirs = AppDirectories(temporary: options.isUITest)162        if options.reset { dirs.eraseEverything() }163        directories = dirs164        let defaults: UserDefaults165        if options.isUITest {166            let suite = "ai.spboucher.orix.maps.uitest"167            if options.reset { UserDefaults().removePersistentDomain(forName: suite) }168            defaults = UserDefaults(suiteName: suite) ?? .standard169        } else {170            if options.reset, let id = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: id) }171            defaults = .standard172        }173        let settings = AppSettings(defaults: defaults)174        if options.skipOnboarding { settings.hasCompletedOnboarding = true }175        if let id = options.themeID { settings.themeID = id; settings.nightThemeAutomatic = false }176        self.settings = settings177        map = MapController(camera: options.camera ?? settings.lastCamera ?? .world)178        themes = ThemeStore(directory: dirs.themes)179        style = StyleCoordinator(controller: map, cacheDirectory: dirs.caches)180        location = LocationService(provider: CoreLocationProvider())181        regionsModel = RegionsModel(root: dirs.regions, caches: dirs.caches, catalogURL: options.catalogURL)182        library = LibraryModel(databaseURL: dirs.database.appending(path: "places.sqlite"), map: map, settings: settings)183        search = SearchModel(map: map)184        directions = DirectionsModel(map: map, location: location, settings: settings)185        userLayers = UserLayersModel(directory: dirs.root.appending(path: "Layers", directoryHint: .isDirectory), map: map)186        tracks = TracksModel(directory: dirs.root.appending(path: "Tracks", directoryHint: .isDirectory), location: location, map: map)187        map.onEvent = { [weak self] event in self?.handle(event) }188        refreshStyle()189        regionObservers.append { [search, directions] regions in search.setRegions(regions); directions.setRegions(regions) }190        directionsHandler = { [weak self] place in191            guard let self else { return }192            self.map.setOverlay(OverlayID.selection, features: [])193            self.route = .directions194            if self.location.usage == nil, self.location.authorization.isAuthorized || self.location.authorization == .notDetermined { self.location.start(.browsing) }195            self.directions.plan(to: place)196        }197        enrichSelection = { [search, settings] place in198            let language = settings.interfaceLanguageCode199            var out = place200            if place.origin == .mapFeature, let hit = await search.lookup(name: place.title, near: place.coordinate) {201                let s = hit.selection(language: language)202                out.subtitle = s.subtitle; out.category = s.category203                return out204            }205            guard let r = await search.reverse(place.coordinate), let nearest = r.nearest else { return nil }206            let line = [nearest.result.name, nearest.result.secondaryLine].filter { !$0.isEmpty }.joined(separator: ", ")207            if place.origin == .mapFeature { out.subtitle = line } else {208                // A dropped pin keeps its coordinates as the title; the address is the nearest known one, with its distance.209                out.subtitle = nearest.distance < 25 ? line : String(localized: "Near \(line)")210            }211            return out212        }213        eraseHistoryHooks.append { [library] in Task { await library.eraseHistory() } }214        Task { [library, tracks] in await library.reload(); await tracks.reload() }215        regionsModel.onRegionsChanged = { [weak self] installed in self?.installedRegionsDidChange(installed) }216        Task { [regionsModel, options] in217            await regionsModel.start()218            #if DEBUG219            if let id = options.autoDownload, regionsModel.installedRegion(id) == nil {220                await regionsModel.refreshCatalog(force: true)221                if let region = regionsModel.catalog?.document.region(id) { regionsModel.download(region) }222            }223            #endif224        }225        #if DEBUG226        if options.routeTo != nil || options.searchText != nil { Task { [weak self] in await self?.runDebugScenario() } }227        #endif228        #if DEBUG229        if let name = options.screen {230            // Opens a screen right after launch (tests and screenshots). The panel must be on screen before a sheet can open above it.231            Task { [weak self] in232                try? await Task.sleep(for: .milliseconds(900))233                if name == "measure" { self?.route = .measure } else if let modal = ModalRoute(rawValue: name) { self?.modal = modal }234            }235        }236        #endif237        #if DEBUG238        if let path = options.devRegionPath {239            // A raw tile archive drawn without installation, for development and renderer checks only.240            let world = BoundingBox(minLat: -85, minLon: -180, maxLat: 85, maxLon: 180)241            setRegions([MapRegion(id: "dev", nameEN: "Development region", nameFR: "Région de développement", bounds: world, dataVersion: "0", dataDate: nil,242                                  minZoom: 0, maxZoom: 15, mapURL: URL(fileURLWithPath: path), searchURL: nil, routingURL: nil, installedBytes: 0, attributions: [])])243        }244        #endif245    }246247    // MARK: Style248249    /// Theme actually drawn: the chosen one, or Midnight when the interface is dark and the automatic night theme is on.250    var effectiveTheme: MapTheme {251        let chosen = themes.theme(id: settings.themeID) ?? BuiltInThemes.day252        if settings.nightThemeAutomatic, isDarkInterface, !chosen.isDark, themes.isBuiltIn(chosen.id) { return BuiltInThemes.midnight }253        return chosen254    }255256    func refreshStyle() {257        style.apply(theme: effectiveTheme, language: settings.labelLanguageCode, regions: regions)258        map.setFrameRate(settings.highFrameRate ? .maximum : .standard)259    }260261    func selectTheme(_ id: String) {262        settings.themeID = id263        refreshStyle()264    }265266    /// Hooks called when the set of installed regions changes (search and routing open or close their files).267    @ObservationIgnored var regionObservers: [([MapRegion]) -> Void] = []268269    private func installedRegionsDidChange(_ installed: [InstalledRegion]) {270        let first = regions.isEmpty271        setRegions(installed.compactMap(\.mapRegion))272        // The first region ever installed: show it.273        if first, settings.lastCamera == nil || map.camera.zoom < 3, let r = regions.first { map.fit(r.bounds, duration: 0) }274    }275276    func setRegions(_ new: [MapRegion]) {277        guard new != regions else { return }278        regions = new279        refreshStyle()280        for observer in regionObservers { observer(new) }281    }282283    // MARK: Map events284285    private func handle(_ event: MapEvent) {286        switch event {287        case .cameraChanged(let camera, let reason, let finished):288            if reason == .gesture, tracking != .none { tracking = .none }289            if reason == .gesture, directions.isNavigating { directions.followsPosition = false }290            if finished { settings.lastCamera = camera }291        case .tap(let coordinate, let feature):292            mapTapped(coordinate, feature: feature)293        case .longPress(let coordinate):294            dropPin(at: coordinate)295        case .styleLoaded, .styleFailed:296            break297        }298    }299300    /// Hooks filled by features that take over taps (measuring).301    @ObservationIgnored var tapInterceptor: ((Coordinate) -> Bool)?302303    private func mapTapped(_ coordinate: Coordinate, feature: MapFeature?) {304        if let tapInterceptor, tapInterceptor(coordinate) { return }305        if let feature, feature.layer == .pin, let id = feature.attributes["id"].flatMap(UUID.init(uuidString:)), let p = library.places.first(where: { $0.id == id }) {306            select(PlaceSelection(title: p.name, subtitle: p.address, coordinate: p.coordinate, origin: .saved(p.id.uuidString), category: p.category), moveCamera: false)307            return308        }309        if let feature, feature.layer == .searchResult, let id = feature.attributes["id"], let r = search.results.first(where: { $0.id == id }) {310            select(r.selection(language: settings.interfaceLanguageCode), moveCamera: false)311            return312        }313        guard let feature else {314            if case .place(let p) = route, p.origin == .droppedPin || p.origin == .mapFeature { clearSelection() }315            return316        }317        let title = feature.name ?? CoordinateText.format(feature.coordinate, style: settings.coordinateStyle)318        select(PlaceSelection(title: title, subtitle: nil, coordinate: feature.coordinate, origin: .mapFeature, category: feature.kind, details: [:]), moveCamera: false)319    }320321    func dropPin(at coordinate: Coordinate) {322        guard coordinate.isValid else { return }323        select(PlaceSelection(title: CoordinateText.format(coordinate, style: settings.coordinateStyle), subtitle: nil, coordinate: coordinate, origin: .droppedPin), moveCamera: false)324    }325326    /// Hook that lets the search layer complete a selection with the nearest address (reverse geocoding), when a region covers it.327    @ObservationIgnored var enrichSelection: ((PlaceSelection) async -> PlaceSelection?)?328329    /// The system's Reduce Motion setting, reported by the root view: camera moves started by the application are330    /// then immediate.331    @ObservationIgnored var reduceMotion = false332333    func select(_ place: PlaceSelection, moveCamera: Bool) {334        route = .place(place)335        map.setOverlay(OverlayID.selection, features: [OverlayFeature(.point(place.coordinate))])336        if moveCamera {337            var camera = map.camera338            camera.center = place.coordinate339            camera.zoom = max(camera.zoom, 15)340            map.setCamera(camera, duration: ORIX.Motion.cameraDuration(reduceMotion: reduceMotion))341        }342        if let enrichSelection, place.origin == .droppedPin || place.origin == .mapFeature || place.origin == .coordinates {343            Task { [weak self] in344                guard let enriched = await enrichSelection(place), let self, case .place(let current) = self.route, current.id == place.id else { return }345                self.route = .place(enriched)346            }347        }348    }349350    /// Opens the route planner towards a place. Filled in by the directions feature.351    @ObservationIgnored var directionsHandler: ((PlaceSelection) -> Void)?352353    func startDirections(to place: PlaceSelection) {354        if let directionsHandler { directionsHandler(place) } else { showToast(String(localized: "Directions need a downloaded region.")) }355    }356357    func clearSelection() {358        map.setOverlay(OverlayID.selection, features: [])359        if case .place = route { route = .home }360    }361362    // MARK: Position363364    /// The location button: first tap centres on the position, second tap follows the heading, third releases.365    func cycleTracking(reduceMotion: Bool) {366        guard location.authorization.isAuthorized else {367            if location.authorization == .denied || location.authorization == .restricted {368                // Nothing can follow a position the app is not allowed to read: say so instead of looking active.369                tracking = .none370                showToast(String(localized: "Position access is off. Turn it on in Settings to see your position."))371                return372            }373            location.start(.browsing)374            tracking = .follow375            return376        }377        if location.usage == nil { location.start(.browsing) }378        switch tracking {379        case .none: tracking = .follow380        case .follow: tracking = .followWithHeading; location.retainHeading(); headingRetained = true381        case .followWithHeading: tracking = .none382        }383        if tracking != .followWithHeading, headingRetained { location.releaseHeading(); headingRetained = false }384        applyTracking(animated: !reduceMotion)385    }386387    @ObservationIgnored private var headingRetained = false388389    /// Called when the position permission changes: a refusal (in the system prompt or in Settings) releases the390    /// follow mode, which would otherwise stay highlighted with no position behind it.391    func authorizationDidChange() {392        let authorization = location.authorization393        guard authorization == .denied || authorization == .restricted else { return }394        if headingRetained { location.releaseHeading(); headingRetained = false }395        if tracking != .none {396            tracking = .none397            showToast(String(localized: "Position access is off. Turn it on in Settings to see your position."))398        }399        positionDidChange()400    }401402    /// Called when a new fix or heading arrives: redraws the position and moves the camera when following.403    func positionDidChange() {404        guard let fix = location.lastFix else {405            map.setOverlay(OverlayID.location, features: [])406            map.setOverlay(OverlayID.locationAccuracy, features: [])407            return408        }409        var properties: [String: OverlayValue] = ["stale": .bool(!location.isFixFresh)]410        if let h = location.heading?.best ?? fix.course { properties["heading"] = .number(h) }411        map.setOverlay(OverlayID.location, features: [OverlayFeature(.point(fix.coordinate), properties: properties)])412        map.setOverlay(OverlayID.locationAccuracy, features: fix.horizontalAccuracy > 12 ? [OverlayFeature.circle(center: fix.coordinate, radius: fix.horizontalAccuracy)] : [])413        applyTracking(animated: !reduceMotion)414    }415416    private func applyTracking(animated: Bool) {417        guard tracking != .none, !directions.isNavigating, let fix = location.lastFix else { return }418        var camera = map.camera419        camera.center = fix.coordinate420        if camera.zoom < 13 { camera.zoom = 15.5 }421        if tracking == .followWithHeading, let h = location.heading?.best ?? fix.course { camera.bearing = h } else if tracking == .follow { camera.bearing = map.camera.bearing }422        map.setCamera(camera, duration: animated ? 0.35 : 0)423    }424425    func resetNorth(reduceMotion: Bool) {426        var camera = map.camera427        camera.bearing = 0428        camera.pitch = 0429        if tracking == .followWithHeading { tracking = .follow }430        map.setCamera(camera, duration: ORIX.Motion.cameraDuration(reduceMotion: reduceMotion, 0.3))431    }432433    func toggle3D(reduceMotion: Bool) {434        var camera = map.camera435        camera.pitch = camera.pitch > 5 ? 0 : 55436        if camera.pitch > 0, camera.zoom < 15 { camera.zoom = 15.5 }437        map.setCamera(camera, duration: ORIX.Motion.cameraDuration(reduceMotion: reduceMotion, 0.5))438    }439440    /// Erases what the history setting covers: recent searches and places (kept by the history store) and the last viewpoint.441    @ObservationIgnored var eraseHistoryHooks: [() -> Void] = []442443    func eraseHistory() {444        settings.lastCamera = nil445        for hook in eraseHistoryHooks { hook() }446        showToast(String(localized: "History erased"))447    }448449    #if DEBUG450    /// Development and test scenarios driven by launch arguments (see `LaunchOptions`).451    private func runDebugScenario() async {452        // Up to a minute: with -ORIXAutoDownload the region is first downloaded and installed.453        for _ in 0..<600 where !(directions.hasRouting && search.hasIndex) { try? await Task.sleep(for: .milliseconds(100)) }454        if let text = options.searchText {455            search.update(text: text, full: true)456        }457        guard let to = options.routeTo else { return }458        if let m = options.travelMode { directions.mode = m == "walk" ? .pedestrian : (m == "bike" ? .bicycle : .car) }459        route = .directions460        directions.points = [options.routeFrom.map { RoutePoint(title: CoordinateText.format($0), coordinate: $0) } ?? .myPosition, RoutePoint(title: CoordinateText.format(to), coordinate: to)]461        directions.compute()462        guard options.simulateDrive else { return }463        for _ in 0..<100 where directions.route == nil { try? await Task.sleep(for: .milliseconds(100)) }464        startNavigation(simulated: true)465    }466    #endif467468    func startNavigation(simulated: Bool) {469        tracking = .none470        directions.startNavigation(simulated: simulated)471        if directions.isNavigating { route = .navigation }472    }473474    func endNavigation() {475        directions.stopNavigation()476        directions.clear()477        route = .home478    }479480    /// Marker of the replayed position (drawn with the selection pin so that it never looks like the live position).481    func showReplayMarker(at coordinate: Coordinate?, bearing: Double?) {482        map.setOverlay(OverlayID.selection, features: coordinate.map { [OverlayFeature(.point($0))] } ?? [])483    }484485    func showToast(_ message: String) {486        toast = message487        Task { [weak self] in488            try? await Task.sleep(for: .seconds(3.5))489            if self?.toast == message { self?.toast = nil }490        }491    }492}493494/// Where the application keeps its files. Everything lives in the app container; nothing is in iCloud.495struct AppDirectories {496    let root: URL497    let caches: URL498499    init(temporary: Bool) {500        let fm = FileManager.default501        if temporary {502            root = fm.temporaryDirectory.appending(path: "orix-maps-uitest", directoryHint: .isDirectory)503            caches = root.appending(path: "Caches", directoryHint: .isDirectory)504        } else {505            root = (try? fm.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true))?.appending(path: "ORIXMaps", directoryHint: .isDirectory)506                ?? fm.temporaryDirectory.appending(path: "ORIXMaps", directoryHint: .isDirectory)507            caches = (try? fm.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true))?.appending(path: "ORIXMaps", directoryHint: .isDirectory)508                ?? fm.temporaryDirectory.appending(path: "ORIXMapsCaches", directoryHint: .isDirectory)509        }510        for d in [root, caches] { try? fm.createDirectory(at: d, withIntermediateDirectories: true) }511        // Downloaded maps can be fetched again: keep them out of device backups.512        var values = URLResourceValues(); values.isExcludedFromBackup = true513        var regions = self.regions514        try? fm.createDirectory(at: regions, withIntermediateDirectories: true)515        try? regions.setResourceValues(values)516    }517518    var themes: URL { root.appending(path: "Themes", directoryHint: .isDirectory) }519    var regions: URL { root.appending(path: "Regions", directoryHint: .isDirectory) }520    var database: URL { root.appending(path: "Library", directoryHint: .isDirectory) }521522    func eraseEverything() {523        try? FileManager.default.removeItem(at: root)524        try? FileManager.default.removeItem(at: caches)525        for d in [root, caches] { try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }526    }527}528
Files main
Menu

Theme