SPB Git

Repository Public

ContentView.swift 22.5 KB 487 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : sdk/ios/Example/App/ContentView.swift10// Module           : sdk11// Repository       : https://git.spboucher.ai/ka-maps-engine12// Created          : 2026-12-0113// Last Modified    : 2026-12-0114//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          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import KAMaps88import SwiftUI8990struct ContentView: View {91    @Bindable var model: DemoModel92    @State private var showOffline = false93    @State private var showSearch = false94    @Environment(\.colorScheme) private var scheme9596    var body: some View {97        ZStack {98            map.ignoresSafeArea()99            VStack(spacing: 8) {100                topBar101                Spacer(minLength: 0)102                if model.isDrawing || !model.drawLine.isEmpty { drawBar }103                if let s = model.selectedLabel { selectionCard(s) }104                toolbar105            }106            .padding(.horizontal, 12)107            .padding(.bottom, 6)108        }109        .sheet(isPresented: $showOffline) { OfflineView(model: model).presentationDetents([.medium, .large]) }110        .sheet(isPresented: $showSearch) { SearchView(model: model).presentationDetents([.medium]) }111    }112113    private var map: some View {114        var m = KAMap(camera: $model.camera, theme: model.followsInterfaceStyle ? nil : model.theme, brand: model.brand, mode: $model.mode, layers: model.layers, selection: $model.selection, controller: model.map) {115            // Bulle animée au-dessus de la pastille sélectionnée : une vraie vue SwiftUI, posée par le moteur.116            if model.showsSelectionCallout, let c = model.selectedCoordinate, let label = model.selectedLabel {117                KAAnnotation(id: "selection", coordinate: c, anchor: .bottom, offset: CGSize(width: 0, height: -30), priority: 100, accessibilityLabel: "Sélection : \(label)") {118                    SelectionCallout(text: label)119                }120            }121            for a in model.demoAnnotations {122                KAAnnotation(id: a.id, coordinate: a.coordinate, anchor: .bottom, priority: a.priority, collision: model.annotationsCollide ? .hideWhenOverlapped : .none, isHiddenBehindBuildings: model.annotationsHideBehindBuildings, accessibilityLabel: a.title) {123                    DemoPin(title: a.title, strong: a.priority == 4)124                }125            }126        }127            .mapUserLocation(model.userLocation)128            .mapInteraction(model.interaction)129            .mapNetworkPolicy(model.networkEnabled ? .default : .offlineOnly)130            // Le bandeau d'outils du bas masque la carte : l'attribution et les cadrages s'en écartent.131            .mapContentInsets(KAEdgeInsets(top: 52, bottom: model.selectedLabel == nil ? 64 : 140))132        if model.followsInterfaceStyle {133            m = m.mapTheme(forInterfaceStyle: { $0 == .dark ? .midnight : .signature })134        }135        return m136    }137138    private var topBar: some View {139        HStack(spacing: 8) {140            Button {141                showSearch = true142            } label: {143                Label("Adresse, rue, lieu", systemImage: "magnifyingglass")144                    .font(.subheadline)145                    .frame(maxWidth: .infinity, alignment: .leading)146                    .padding(.horizontal, 12)147                    .padding(.vertical, 9)148            }149            .buttonStyle(.plain)150            .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))151            .accessibilityIdentifier("search")152            VStack(alignment: .trailing, spacing: 1) {153                Text(String(format: "z %.1f  %.0f°  cap %.0f°", model.camera.zoom, model.camera.pitch, model.camera.bearing))154                if let p = model.perf {155                    Text(String(format: "%.0f i/s  %d tuiles", p.fps, p.tiles))156                }157            }158            .font(.caption2.monospacedDigit())159            .padding(.horizontal, 8)160            .padding(.vertical, 5)161            .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 8, style: .continuous))162            .accessibilityElement(children: .combine)163            .accessibilityIdentifier("hud")164            // État pour les essais d'interface.165            Text(model.status)166                .font(.system(size: 6))167                .frame(width: 8, height: 8)168                .opacity(0.02)169                .accessibilityIdentifier("status")170        }171    }172173    private func selectionCard(_ s: String) -> some View {174        HStack {175            VStack(alignment: .leading, spacing: 2) {176                Text(s).font(.headline)177                Text("Donnée fictive de démonstration").font(.caption).foregroundStyle(.secondary)178            }179            Spacer()180            Button("Fermer", systemImage: "xmark.circle.fill") {181                model.map.clearSelection()182                model.selectedLabel = nil183            }184            .labelStyle(.iconOnly)185            .font(.title3)186            .foregroundStyle(.secondary)187        }188        .padding(12)189        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12, style: .continuous))190        .accessibilityIdentifier("selectionCard")191    }192193    private var drawBar: some View {194        HStack {195            Text(model.drawLine.isEmpty ? "Touchez la carte pour poser des sommets" : model.drawLine).font(.footnote)196            Spacer()197            if model.isDrawing {198                Button("Annuler le dernier") { model.map.drawUndo() }199                Button("Terminer") { model.map.finishDraw() }.bold()200            } else {201                Button("Effacer") { model.drawLine = "" }202            }203        }204        .font(.footnote)205        .padding(10)206        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))207    }208209    private var toolbar: some View {210        ScrollView(.horizontal, showsIndicators: false) {211            HStack(spacing: 8) {212                Menu {213                    ForEach(DemoPlace.allCases) { p in Button(p.title) { model.go(p) } }214                } label: { chip("Lieu", "mappin.and.ellipse") }215                .accessibilityIdentifier("menu.place")216217                Menu {218                    Picker("Marque", selection: $model.brand) {219                        Text("Aucune").tag(KABrand?.none)220                        ForEach(KABrand.allCases, id: \.self) { b in Text(b.rawValue).tag(KABrand?.some(b)) }221                    }222                } label: { chip(model.brand?.rawValue ?? "Marque", "paintpalette") }223                .accessibilityIdentifier("menu.brand")224225                Menu {226                    Picker("Thème", selection: $model.theme) {227                        ForEach(model.themes, id: \.self) { t in Text(t.rawValue).tag(t) }228                    }229                    Toggle("Suivre clair / sombre", isOn: $model.followsInterfaceStyle)230                } label: { chip(model.theme.rawValue, "circle.lefthalf.filled") }231                .accessibilityIdentifier("menu.theme")232233                Button {234                    model.mode = model.mode == .flat ? .volumes : .flat235                } label: { chip(model.mode == .flat ? "3D" : "2D", "cube") }236                .accessibilityIdentifier("toggle.mode")237238                Menu {239                    ForEach(KALayerKind.allCases, id: \.self) { k in240                        Toggle(k.rawValue, isOn: Binding(get: { model.enabledLayers.contains(k) }, set: { on in241                            if on { model.enabledLayers.insert(k) } else { model.enabledLayers.remove(k) }242                        }))243                    }244                } label: { chip("Couches", "square.3.layers.3d") }245                .accessibilityIdentifier("menu.layers")246247                Menu {248                    Button("Survol (flyTo) vers Québec") { model.go(.quebec) }249                    Button("Cadrer les pastilles") {250                        if let b = KABounds(containing: DemoData.layer(.markers, around: model.place.coordinate, brand: model.brand).markers.map(\.coordinate)) {251                            model.map.fitBounds(b, duration: 0.8)252                        }253                    }254                    Button("Orbite") { model.map.orbit(center: model.place.coordinate, zoom: 16.2, pitch: 58, turns: 1, duration: 18) }255                    Button("Visite de trois lieux") {256                        model.map.tour(DemoPlace.allCases.map { KATourStop(camera: KACameraUpdate(center: $0.coordinate, zoom: 15.5, bearing: 20, pitch: 50), hold: 1.5) })257                    }258                    Button("Révélation Lou-Ka (porte)") {259                        _ = try? model.map.reveal(target: model.place.coordinate)260                    }261                    Button("Mettre un bâtiment en évidence") { model.map.highlightBuilding(at: model.map.camera.center, pulse: true) }262                    Button("Arrêter") { model.map.stop() }263                } label: { chip("Caméra", "video") }264                .accessibilityIdentifier("menu.camera")265266                Menu {267                    Button("Dessiner un polygone") {268                        model.isDrawing = true269                        model.drawLine = ""270                        model.map.startDraw(.polygon)271                    }272                    Button("Mesurer une distance") {273                        model.isDrawing = true274                        model.drawLine = ""275                        model.map.startDraw(.line)276                    }277                    Button("Ma position (simulée)") {278                        model.userLocation = model.userLocation == nil ? KAUserLocation(coordinate: model.map.camera.center, horizontalAccuracy: 35, heading: 40) : nil279                    }280                    Picker("Gestes", selection: $model.interaction) {281                        Text("Tous").tag(KAInteraction.all)282                        Text("Deux doigts (page défilante)").tag(KAInteraction.twoFingers)283                        Text("Déplacer et zoomer").tag(KAInteraction.panAndZoom)284                        Text("Aucun").tag(KAInteraction.none)285                    }286                    Button("Adresse au centre") { Task { await model.reverseAtCenter() } }287                } label: { chip("Outils", "ruler") }288                .accessibilityIdentifier("menu.tools")289290                Button {291                    model.refreshOffline()292                    showOffline = true293                } label: { chip(model.networkEnabled ? "Hors ligne" : "Sans réseau", model.networkEnabled ? "arrow.down.circle" : "wifi.slash") }294                .accessibilityIdentifier("open.offline")295            }296            .padding(.vertical, 2)297        }298        .overlay(alignment: .topLeading) {299            if !model.reverseLine.isEmpty {300                Text(model.reverseLine).font(.caption2).padding(4).background(.regularMaterial, in: Capsule()).offset(y: -24)301            }302        }303    }304305    private func chip(_ title: String, _ image: String) -> some View {306        Label(title, systemImage: image)307            .font(.subheadline.weight(.medium))308            .padding(.horizontal, 12)309            .padding(.vertical, 9)310            .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))311            .foregroundStyle(.primary)312    }313}314315struct SearchView: View {316    @Bindable var model: DemoModel317    @Environment(\.dismiss) private var dismiss318319    var body: some View {320        NavigationStack {321            List(model.searchResults) { r in322                Button {323                    model.map.flyTo(KACameraUpdate(center: r.coordinate, zoom: r.type == "address" ? 17 : 14.5))324                    model.map.highlightBuilding(at: r.coordinate, pulse: true)325                    dismiss()326                } label: {327                    VStack(alignment: .leading) {328                        Text(r.label)329                        Text(r.isApproximate ? "\(r.type) — position approchée" : r.type).font(.caption).foregroundStyle(.secondary)330                    }331                }332            }333            .searchable(text: $model.searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Adresse, rue, lieu")334            .onSubmit(of: .search) { Task { await model.search() } }335            .task(id: model.searchText) {336                try? await Task.sleep(for: .milliseconds(280))337                if !Task.isCancelled, model.searchText.count >= 3 { await model.search() }338            }339            .navigationTitle("Recherche")340            .navigationBarTitleDisplayMode(.inline)341        }342    }343}344345struct OfflineView: View {346    @Bindable var model: DemoModel347    @State private var index: KAOfflinePackIndex?348    @State private var installed: [KAInstalledPack] = []349    @State private var downloads: [String: KAPackDownload] = [:]350    @State private var message = ""351352    var body: some View {353        NavigationStack {354            List {355                Section("Réseau") {356                    Toggle("Réseau des tuiles", isOn: $model.networkEnabled)357                    Text(model.usageLine).font(.caption).foregroundStyle(.secondary)358                }359                Section("Régions (pyramide de tuiles)") {360                    Button("Télécharger la vue courante (z ≤ 14)") {361                        do {362                            let b = try model.map.visibleBounds()363                            let z = Int(model.map.camera.zoom.rounded(.down))364                            try model.map.downloadRegion(id: "vue-\(Int(Date().timeIntervalSince1970))", name: "\(model.place.title) z\(z)", bounds: b, minZoom: max(z - 3, 0), maxZoom: 14)365                            message = ""366                        } catch { message = "\(error)" }367                        model.refreshOffline()368                    }369                    ForEach(model.regions) { r in370                        VStack(alignment: .leading, spacing: 3) {371                            Text(r.name).font(.subheadline.weight(.medium))372                            ProgressView(value: r.progress)373                            Text("\(r.tilesDone)/\(r.tilesTotal) tuiles — \(ByteCountFormatter().string(fromByteCount: Int64(r.bytes))) — \(r.state.rawValue)\(r.completedAt.map { " — \($0.formatted(date: .abbreviated, time: .shortened))" } ?? "")\(r.dataVersion.map { " — données \($0)" } ?? "")")374                                .font(.caption)375                                .foregroundStyle(.secondary)376                        }377                        .swipeActions {378                            Button("Supprimer", role: .destructive) {379                                _ = try? model.map.removeRegion(r.id)380                                model.refreshOffline()381                            }382                        }383                    }384                }385                Section("Archives PMTiles") {386                    if let index {387                        if index.packs.isEmpty { Text("Aucune archive publiée (données \(index.dataVersion)).").font(.footnote).foregroundStyle(.secondary) }388                        ForEach(index.packs) { p in389                            HStack {390                                VStack(alignment: .leading) {391                                    Text(p.title)392                                    Text("\(ByteCountFormatter().string(fromByteCount: p.bytes)) — données \(p.dataVersion)").font(.caption).foregroundStyle(.secondary)393                                    if let d = downloads[p.id], d.state == .downloading || d.state == .waiting { ProgressView(value: d.progress) }394                                }395                                Spacer()396                                if installed.contains(where: { $0.id == p.id }) {397                                    Image(systemName: "checkmark.circle.fill").foregroundStyle(.green)398                                } else {399                                    Button("Télécharger") { KAOfflineManager.shared.download(p) }400                                }401                            }402                        }403                    }404                    ForEach(installed) { p in405                        VStack(alignment: .leading) {406                            Text("Installée : \(p.title)")407                            Text("\(ByteCountFormatter().string(fromByteCount: p.bytes)) — données \(p.dataVersion) — \(p.installedAt.formatted(date: .abbreviated, time: .shortened))\(index.map { p.isOutdated(comparedTo: $0) ? " — à mettre à jour" : "" } ?? "")")408                                .font(.caption)409                                .foregroundStyle(.secondary)410                        }411                        .swipeActions {412                            Button("Supprimer", role: .destructive) {413                                KAOfflineManager.shared.removePack(p.id)414                                installed = KAOfflineManager.shared.installedPacks()415                            }416                        }417                    }418                }419                if !message.isEmpty { Section { Text(message).foregroundStyle(.red).font(.footnote) } }420            }421            .navigationTitle("Hors ligne")422            .navigationBarTitleDisplayMode(.inline)423            .task {424                installed = KAOfflineManager.shared.installedPacks()425                do { index = try await KAOfflineManager.shared.fetchPackIndex() } catch { message = "\(error)" }426                for await d in KAOfflineManager.shared.downloadUpdates {427                    downloads[d.id] = d428                    if d.state == .finished { installed = KAOfflineManager.shared.installedPacks() }429                }430            }431        }432    }433}434435/// Bulle de sélection : s'ouvre avec un ressort, comme la porte de Lou-Ka au-dessus de la pastille choisie.436struct SelectionCallout: View {437    let text: String438    @State private var open = false439440    var body: some View {441        VStack(spacing: 0) {442            HStack(spacing: 6) {443                Image(systemName: "door.left.hand.open")444                    .rotation3DEffect(.degrees(open ? 0 : 70), axis: (x: 0, y: 1, z: 0), anchor: .leading)445                Text(text).font(.footnote.weight(.semibold))446            }447            .padding(.horizontal, 10)448            .padding(.vertical, 7)449            .background(Color(.label), in: RoundedRectangle(cornerRadius: 9, style: .continuous))450            .foregroundStyle(Color(.systemBackground))451            Triangle().fill(Color(.label)).frame(width: 12, height: 6)452        }453        .scaleEffect(open ? 1 : 0.6, anchor: .bottom)454        .opacity(open ? 1 : 0)455        .onAppear { withAnimation(.spring(response: 0.42, dampingFraction: 0.68)) { open = true } }456    }457}458459struct Triangle: Shape {460    func path(in r: CGRect) -> Path {461        var p = Path()462        p.move(to: CGPoint(x: r.minX, y: r.minY))463        p.addLine(to: CGPoint(x: r.maxX, y: r.minY))464        p.addLine(to: CGPoint(x: r.midX, y: r.maxY))465        p.closeSubpath()466        return p467    }468}469470struct DemoPin: View {471    let title: String472    let strong: Bool473474    var body: some View {475        VStack(spacing: 0) {476            Text(title)477                .font(.caption2.weight(.semibold))478                .padding(.horizontal, 7)479                .padding(.vertical, 4)480                .background(strong ? Color(red: 0.71, green: 0.27, blue: 0.17) : Color(.systemBackground), in: Capsule())481                .foregroundStyle(strong ? Color.white : Color(.label))482                .overlay(Capsule().strokeBorder(Color(.label).opacity(0.25), lineWidth: 0.5))483            Triangle().fill(strong ? Color(red: 0.71, green: 0.27, blue: 0.17) : Color(.systemBackground)).frame(width: 8, height: 4)484        }485    }486}487
Files main
Menu

Theme