SPB Git

Repository Public BSD-3-Clause

UserLayers.swift 9.7 KB 215 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Layers/UserLayers.swift10// Module           : Layers11// 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 ORIXGeoExchange93import ORIXMapRenderer94import ORIXMapStyle95import SwiftUI9697/// Layers the user adds to the map from GeoJSON, GPX or KML files (Map Studio). Files are copied into the app's98/// storage, validated on import, and drawn above the base map.99@Observable100final class UserLayersModel {101    struct Layer: Identifiable, Equatable, Codable {102        var id: UUID103        var name: String104        var format: String105        var isVisible: Bool106        var featureCount: Int107    }108109    private(set) var layers: [Layer] = []110    @ObservationIgnored private let directory: URL111    @ObservationIgnored private weak var map: MapController?112    @ObservationIgnored private var cache: [UUID: ExchangeDocument] = [:]113114    init(directory: URL, map: MapController) {115        self.directory = directory116        self.map = map117        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)118        if let data = try? Data(contentsOf: index), let saved = try? JSONDecoder().decode([Layer].self, from: data) { layers = saved }119        redraw()120    }121122    private var index: URL { directory.appending(path: "layers.json") }123    private func file(_ l: Layer) -> URL { directory.appending(path: "\(l.id.uuidString).\(l.format)") }124    private func persist() { try? JSONEncoder().encode(layers).write(to: index, options: .atomic) }125126    private func document(_ l: Layer) -> ExchangeDocument? {127        if let d = cache[l.id] { return d }128        guard let format = ExchangeFormat(rawValue: l.format), let data = try? Data(contentsOf: file(l)), let d = try? ExchangeCodec.decode(data, format: format) else { return nil }129        cache[l.id] = d130        return d131    }132133    /// Imports a file as a new layer. Returns a message for the user when it cannot be used.134    func importFile(_ url: URL) -> String? {135        let scoped = url.startAccessingSecurityScopedResource()136        defer { if scoped { url.stopAccessingSecurityScopedResource() } }137        let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0138        guard size <= ExchangeLimits.maxBytes, let data = try? Data(contentsOf: url) else { return String(localized: "The file is too large or could not be read.") }139        guard let (doc, format) = try? ExchangeCodec.decode(data, fileExtension: url.pathExtension) else { return String(localized: "The file could not be read: it is damaged or not a GPX, GeoJSON or KML file.") }140        let layer = Layer(id: UUID(), name: String(url.deletingPathExtension().lastPathComponent.prefix(80)), format: format.rawValue, isVisible: true,141                          featureCount: doc.waypoints.count + doc.tracks.count + doc.areas.count)142        // Store a normalized copy: only what was understood and validated is kept.143        guard (try? ExchangeCodec.encode(doc, format: format).write(to: file(layer), options: .atomic)) != nil else { return String(localized: "The layer could not be saved on this device.") }144        cache[layer.id] = doc145        layers.append(layer)146        persist()147        redraw()148        if let b = doc.bounds { map?.fit(b) }149        return nil150    }151152    func setVisible(_ id: UUID, _ visible: Bool) {153        guard let i = layers.firstIndex(where: { $0.id == id }) else { return }154        layers[i].isVisible = visible155        persist(); redraw()156    }157158    func delete(_ id: UUID) {159        guard let i = layers.firstIndex(where: { $0.id == id }) else { return }160        try? FileManager.default.removeItem(at: file(layers[i]))161        cache[id] = nil162        layers.remove(at: i)163        persist(); redraw()164    }165166    func show(_ id: UUID) {167        if let l = layers.first(where: { $0.id == id }), let b = document(l)?.bounds { map?.fit(b) }168    }169170    private func redraw() {171        var features: [OverlayFeature] = []172        for l in layers where l.isVisible {173            guard let d = document(l) else { continue }174            features += d.waypoints.map { OverlayFeature(.point($0.coordinate), properties: ["title": .string($0.name ?? l.name)]) }175            features += d.tracks.flatMap { $0.segments.filter { $0.count > 1 }.map { OverlayFeature(.line($0.map(\.coordinate))) } }176            features += d.areas.map { OverlayFeature(.polygon($0.rings)) }177            features += d.areas.flatMap { $0.rings.map { OverlayFeature(.line($0.first == $0.last ? $0 : $0 + $0.prefix(1))) } }178        }179        map?.setOverlay(OverlayID.geoJSONLayer, features: features)180    }181}182183/// Map Studio section listing the user's layers.184struct UserLayersSection: View {185    @Environment(AppModel.self) private var app186    @State private var importing = false187    @State private var message: String?188189    var body: some View {190        Section {191            ForEach(app.userLayers.layers) { l in192                HStack {193                    Toggle(isOn: Binding(get: { l.isVisible }, set: { app.userLayers.setVisible(l.id, $0) })) {194                        VStack(alignment: .leading) {195                            Text(l.name)196                            Text(verbatim: "\(String(localized: "\(l.featureCount) features")) · \(l.format.uppercased())").font(.footnote).foregroundStyle(.secondary)197                        }198                    }199                }200                .swipeActions {201                    Button("Delete", role: .destructive) { app.userLayers.delete(l.id) }202                    Button("Show") { app.userLayers.show(l.id); app.modal = nil }203                }204            }205            Button { importing = true } label: { Label("Add a GeoJSON, GPX or KML layer", systemImage: "square.3.layers.3d.down.right") }206                .accessibilityIdentifier("studio.addlayer")207        } header: { Text("My layers") } footer: { Text("Layers are drawn above the map with the theme's marker colour. Swipe a layer to show or delete it.") }208        .fileImporter(isPresented: $importing, allowedContentTypes: [.json, .xml, .data]) { result in209            guard let url = try? result.get() else { return }210            message = app.userLayers.importFile(url)211        }212        .alert("Layer", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { Button("OK") {} } message: { Text(message ?? "") }213    }214}215
Files main
Menu

Theme