Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : sdk/ios/Example/App/Scenarios2.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 CoreLocation88import Foundation89import KAMaps90import UIKit9192/// Scénarios de la version 0.2 : vues d'annotation, options tardives du moteur, deux cartes sur un stock,93/// perte du périphérique GPU, clavier / trackpad / molette, grandes tailles de texte, reprises hors ligne.94extension ScenarioRunner {95 static var round2: [String] { ["annotations", "options", "twomaps", "deviceloss", "keyboard", "dyntype", "reconnect", "stale"] }9697 private func arg(_ name: String) -> String? {98 let a = ProcessInfo.processInfo.arguments99 guard let i = a.firstIndex(of: name), i + 1 < a.count else { return nil }100 return a[i + 1]101 }102103 private var view: KAMapView {104 get throws {105 guard let v = map.mapView else { throw ScenarioFailure("vue absente") }106 return v107 }108 }109110 /// Écart maximal (points) entre le cadre de chaque vue d'annotation vivante et la projection du moteur.111 private func annotationError() throws -> (max: CGFloat, checked: Int) {112 let v = try view113 var worst: CGFloat = 0114 var n = 0115 for a in v.viewAnnotations {116 guard let av = v.view(forAnnotation: a.id), let p = map.project(a.coordinate) else { continue }117 let s = av.bounds.size118 let expected = CGPoint(x: p.x - s.width * a.anchor.x + a.offset.width + s.width / 2, y: p.y - s.height * a.anchor.y + a.offset.height + s.height / 2)119 worst = max(worst, hypot(av.center.x - expected.x, av.center.y - expected.y))120 n += 1121 }122 return (worst, n)123 }124125 // MARK: Vues d'annotation126127 func annotations() async throws {128 try await reset(.montreal, zoom: 15.2, layers: [.markers])129 let v = try view130 model.annotationSpread = 0.006131 model.annotationsCollide = false132 model.annotationsHideBehindBuildings = false133 model.annotationCount = 50134 await sleep(0.8)135 var st = v.annotationStats136 fact("live", .number(Double(st.live)))137 fact("created", .number(Double(st.created)))138 try check(st.total == 50 && st.live > 20 && st.live <= 50, "50 annotations attendues, \(st.live) vivantes sur \(st.total)")139 try check((v.layer as? CAMetalLayer)?.presentsWithTransaction == true, "avec des annotations, l'image Metal doit être présentée dans la transaction")140 var e = try annotationError()141 try check(e.checked > 20 && e.max < 0.51, "au repos, écart vue ↔ moteur de \(e.max) point(s) sur \(e.checked) vues")142 await checkpoint("annotations-50")143144 // Pendant un glissement avec élan : à chaque image, les vues sont à la position de la caméra dessinée.145 var worst: CGFloat = 0146 var samples = 0147 let token = map.addEventHandler { [weak self] ev in148 guard let self, case .move = ev, let r = try? self.annotationError() else { return }149 worst = max(worst, r.max)150 samples += 1151 }152 v.resetAnnotationTimings()153 let f0 = map.frameCount154 let t0 = CACurrentMediaTime()155 for k in 0..<6 {156 let m = mark157 // Élan : même commande que la levée du doigt (points par seconde).158 try map.command("fling", ["vx": .number(k % 2 == 0 ? 1500 : -1500), "vy": .number(k % 3 == 0 ? 900 : -700)])159 try await wait("moveend", since: m, timeout: 8) { if case .moveEnd = $0 { return true } else { return false } }160 }161 let dt = CACurrentMediaTime() - t0162 map.removeEventHandler(token)163 st = v.annotationStats164 fact("fling.frames", .number(Double(map.frameCount - f0)))165 fact("fling.fps", .number((Double(map.frameCount - f0) / dt * 10).rounded() / 10))166 fact("fling.samples", .number(Double(samples)))167 fact("fling.maxErrorPoints", .number((Double(worst) * 1000).rounded() / 1000))168 fact("fling.updateAvgUs", .number(st.averageUpdateMicroseconds.rounded()))169 fact("fling.updateMaxUs", .number(st.maxUpdateMicroseconds.rounded()))170 fact("fling.updates", .number(Double(st.updates)))171 fact("fling.cpuMs", .number((((try? map.perf().cpuMs) ?? 0) * 100).rounded() / 100))172 try check(samples > 60, "trop peu d'images pendant les élans : \(samples)")173 try check(worst < 0.51, "pendant l'élan, une vue s'écarte de \(worst) point(s) de la caméra dessinée")174 try check(st.updates >= Int(map.frameCount - f0) - 2, "une passe d'annotations par image dessinée attendue : \(st.updates) passes pour \(map.frameCount - f0) images")175 try check(st.averageUpdateMicroseconds < 1500, "passe d'annotations trop lente : \(st.averageUpdateMicroseconds) µs en moyenne")176177 // Recyclage : ce qui est sorti de l'écran a été rendu au réservoir et resservi.178 fact("recycled", .number(Double(st.recycled)))179 fact("createdAfterFling", .number(Double(st.created)))180 try check(st.recycled > 0, "aucune vue recyclée après six élans")181 try check(st.created <= 80, "trop de vues créées (\(st.created)) : le recyclage ne sert pas")182183 // Plafond : 80 annotations à l'écran, 50 vivantes au plus, les plus prioritaires d'abord.184 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 15.2)) }185 model.annotationSpread = 0.003186 model.annotationCount = 80187 await sleep(0.6)188 st = v.annotationStats189 fact("cap.live", .number(Double(st.live)))190 fact("cap.over", .number(Double(st.overCap)))191 try check(st.live == 50 && st.overCap == 30, "plafond : 50 vivantes et 30 écartées attendues, \(st.live) et \(st.overCap)")192 let kept = v.viewAnnotations.filter { v.view(forAnnotation: $0.id) != nil }193 let dropped = v.viewAnnotations.filter { v.view(forAnnotation: $0.id) == nil }194 try check((kept.map(\.priority).min() ?? 0) >= (dropped.map(\.priority).max() ?? 0) - 0 || kept.filter { $0.priority == 4 }.count == v.viewAnnotations.filter { $0.priority == 4 }.count, "le plafond doit garder les annotations les plus prioritaires")195196 // Collisions : parmi celles qui y participent, aucune paire visible ne se chevauche.197 model.annotationsCollide = true198 await sleep(0.6)199 st = v.annotationStats200 fact("collision.hidden", .number(Double(st.hiddenByCollision)))201 try check(st.hiddenByCollision > 0, "80 annotations sur 400 m devraient se chevaucher")202 let visible = v.viewAnnotations.compactMap { a in v.view(forAnnotation: a.id).flatMap { $0.alpha > 0.5 ? (a, $0.frame) : nil } }203 for i in visible.indices {204 for j in visible.indices where j > i {205 try check(!visible[i].1.intersects(visible[j].1), "\(visible[i].0.id) et \(visible[j].0.id) se chevauchent malgré les collisions")206 }207 }208 await checkpoint("annotations-collision")209210 // Occultation par les volumes : en 3D, des vues passent derrière des tours ; à plat, aucune.211 model.annotationsCollide = false212 model.annotationSpread = 0.008213 model.annotationCount = 50214 model.annotationsHideBehindBuildings = true215 await sleep(0.4)216 try check(v.annotationStats.hiddenByBuildings == 0, "à plat, aucune annotation ne doit être masquée par un bâtiment")217 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 16.2)) }218 try await settle { model.mode = .volumes }219 try await settle { map.easeTo(KACameraUpdate(bearing: 40, pitch: 62), duration: 0.4) }220 await sleep(0.4)221 st = v.annotationStats222 fact("occlusion.hidden3d", .number(Double(st.hiddenByBuildings)))223 fact("occlusion.live3d", .number(Double(st.live)))224 try check(st.hiddenByBuildings > 0 && st.hiddenByBuildings < st.live, "en 3D au centre-ville, une partie des \(st.live) vues devrait être derrière une tour : \(st.hiddenByBuildings)")225 await checkpoint("annotations-occlusion-3d")226 model.annotationsHideBehindBuildings = false227 try await settle { model.mode = .flat }228229 // Accessibilité : les vues d'annotation sont dans l'ordre de lecture, avec leur libellé.230 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 15.2)) }231 await sleep(0.3)232 let els = v.accessibilityElements ?? []233 let ann = els.compactMap { $0 as? UIView }.filter { $0.accessibilityIdentifier?.hasPrefix("KAMapAnnotation-") == true }234 fact("a11y.annotationElements", .number(Double(ann.count)))235 try check(ann.count >= 10 && ann.allSatisfy { $0.accessibilityLabel?.hasPrefix("Vue ") == true }, "les vues d'annotation doivent être exposées avec leur libellé : \(ann.count)")236 let ys = els.dropFirst().compactMap { e -> CGFloat? in (e as? UIView).flatMap { $0.accessibilityIdentifier?.hasPrefix("KAMapAnnotation-") == true ? $0.center.y : nil } }237 try check(zip(ys, ys.dropFirst()).allSatisfy { $0 <= $1 + 24 }, "l'ordre de lecture doit aller de haut en bas")238239 // Bulle de sélection : une vue SwiftUI animée suit la pastille choisie, y compris absorbée puis ressortie.240 model.annotationCount = 0241 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 16)) }242 let markers = DemoData.layer(.markers, around: DemoPlace.montreal.coordinate, brand: model.brand).markers243 guard let target = markers.first(where: { m in map.renderedMarker(layer: "markers", id: m.id).map { $0.feature.kind == .marker && v.bounds.insetBy(dx: 40, dy: 160).contains($0.point) } ?? false }),244 let p = map.renderedMarker(layer: "markers", id: target.id)?.point else { throw ScenarioFailure("aucune pastille à sélectionner") }245 v.simulateTap(at: p)246 await sleep(0.9)247 guard let callout = v.view(forAnnotation: "selection") else { throw ScenarioFailure("la bulle de sélection n'est pas apparue") }248 try check(callout.bounds.width > 40 && callout.alpha > 0.9, "bulle de sélection invisible : \(callout.frame)")249 e = try annotationError()250 try check(e.max < 0.51, "la bulle n'est pas sur sa pastille : \(e.max) point(s)")251 await checkpoint("annotations-callout")252 model.annotationCount = 0253 map.clearSelection()254 model.selectedLabel = nil255 await sleep(0.3)256 try check(v.view(forAnnotation: "selection") == nil && v.viewAnnotations.isEmpty, "les annotations retirées doivent disparaître")257 try check((v.layer as? CAMetalLayer)?.presentsWithTransaction == false, "sans annotation, retour à la présentation directe")258 }259260 // MARK: Options tardives du moteur261262 func options() async throws {263 try await reset(.montreal, zoom: 11.5)264 let c = DemoPlace.montreal.coordinate265 let pts = DemoData.markers(around: c, count: 200, brand: .louka)266 // keepSelected + gabarit d'étiquette de grappe.267 try await settle { map.addLayer(.markers(id: "opt", pts, cluster: KAClusterOptions(aggregate: .median, label: .value, keepSelected: true, labelTemplate: "{value} · {count}"))) }268 var drawn = try map.renderedMarkers(layer: "opt")269 let clusters = drawn.filter { $0.feature.kind == .cluster }270 fact("clusters", .number(Double(clusters.count)))271 try check(clusters.count >= 3, "grappes attendues à z11,5")272 // Un marqueur absorbé par une grappe : sélectionné, il doit ressortir en pastille individuelle.273 let drawnIDs = Set(drawn.filter { $0.feature.kind == .marker }.compactMap { $0.feature.id })274 let vb = try view.bounds275 var absorbedOpt: KAMarker?276 for m in pts where !drawnIDs.contains(m.id) {277 if let p = map.project(m.coordinate), vb.contains(p) {278 absorbedOpt = m279 break280 }281 }282 guard let absorbed = absorbedOpt else { throw ScenarioFailure("aucun marqueur absorbé") }283 try await settle { map.select(layer: "opt", id: absorbed.id) }284 drawn = try map.renderedMarkers(layer: "opt")285 try check(drawn.contains { $0.feature.kind == .marker && $0.feature.id == absorbed.id }, "keepSelected : le marqueur sélectionné \(absorbed.id) devrait être dessiné seul")286 await checkpoint("options-keepselected")287 try await settle { map.clearSelection() }288 drawn = try map.renderedMarkers(layer: "opt")289 try check(!drawn.contains { $0.feature.kind == .marker && $0.feature.id == absorbed.id }, "désélectionné, le marqueur retourne dans sa grappe")290 map.removeLayer("opt")291292 // Polygones au-dessus des bâtiments avec étiquette, surface en cases pleines, rayon par point.293 try await settle { map.jumpTo(KACamera(center: c, zoom: 15.4)) }294 let ring = DemoData.zone(around: c, radius: 0.004)295 var closed = ring.map { KAJSON.array([.number($0.longitude), .number($0.latitude)]) }296 closed.append(closed[0])297 let zone: KAJSON = ["type": "FeatureCollection", "features": [["type": "Feature", "properties": ["id": "z1", "value": 0.7, "nom": "Zone d'essai"], "geometry": ["type": "Polygon", "coordinates": [.array(closed)]]]]]298 var grid = DemoData.surface(around: CLLocationCoordinate2D(latitude: c.latitude - 0.006, longitude: c.longitude), half: 0.003, n: 8)299 grid.values = grid.values.enumerated().map { $0.offset % 3 == 0 ? nil : $0.element }300 var radii: [KAPoint] = []301 for i in 0..<40 {302 let lat: Double = c.latitude + 0.004 + Double(i / 8) * 0.0006303 let lon: Double = c.longitude - 0.004 + Double(i % 8) * 0.001304 let r: Double = 3 + Double(i % 8) * 1.5305 radii.append(KAPoint(id: "r\(i)", coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lon), value: Double(i) / 40, radius: r))306 }307 let m = mark308 try await settle {309 map.addLayer(.polygons(id: "zone", geoJSON: zone, fillColor: "#1f4e79", fillOpacity: 0.35, strokeColor: "#1f4e79", strokeWidth: 2, aboveBuildings: true, labelProperty: "nom"))310 map.addLayer(.surface(id: "cases", grid, scale: DemoData.valueScale, fillOpacity: 0.7, interpolate: false, aboveBuildings: true))311 map.addLayer(.points(id: "rayons", radii, scale: DemoData.valueScale, strokeColor: "#ffffff", strokeWidth: 1))312 }313 let errs = model.log[m...].compactMap { e -> String? in if case .error(let s) = e.event { return s } else { return nil } }314 try check(errs.isEmpty, "options refusées par le moteur : \(errs)")315 let v = try view316 let hit = try map.queryRendered(at: map.project(c) ?? .zero, layers: ["zone"])317 try check(hit.first?.id == "z1", "la zone doit être interrogeable par son id : \(hit.first?.raw.encoded() ?? "rien")")318 await checkpoint("options-above-interpolate-radius")319 for id in ["zone", "cases", "rayons"] { map.removeLayer(id) }320321 // Bornes de zoom.322 map.setZoomRange(min: 10, max: 16)323 try await settle { map.jumpTo(KACameraUpdate(zoom: 19)) }324 fact("zoomRange.at19", .number(map.camera.zoom))325 try check(abs(map.camera.zoom - 16) < 0.01, "zoom borné à 16 attendu : \(map.camera.zoom)")326 try await settle { map.jumpTo(KACameraUpdate(zoom: 4)) }327 try check(abs(map.camera.zoom - 10) < 0.01, "zoom borné à 10 attendu : \(map.camera.zoom)")328 map.setZoomRange()329 try await settle { map.jumpTo(KACamera(center: c, zoom: 14)) }330331 // Marge permanente : le centre demandé arrive au centre de la zone libre, pour tout mouvement.332 let insets = KAEdgeInsets(top: 100, leading: 0, bottom: 320, trailing: 0)333 map.setPadding(insets)334 let target = CLLocationCoordinate2D(latitude: 45.5088, longitude: -73.5617)335 try await settle { map.jumpTo(KACameraUpdate(center: target)) }336 guard let tp = map.project(target) else { throw ScenarioFailure("projection impossible") }337 let free = CGPoint(x: v.bounds.midX, y: (100 + v.bounds.height - 320) / 2)338 fact("padding.point", [.number(tp.x.rounded()), .number(tp.y.rounded())])339 try check(hypot(tp.x - free.x, tp.y - free.y) < 2, "marge permanente : cible en \(tp), centre libre \(free)")340 map.setPadding(nil)341 try await settle { map.jumpTo(KACameraUpdate(center: target)) }342 guard let tp2 = map.project(target) else { throw ScenarioFailure("projection impossible") }343 try check(hypot(tp2.x - v.bounds.midX, tp2.y - v.bounds.midY) < 2, "marge retirée : la cible revient au centre de la vue")344 // Variante : les marges de contenu de la vue font foi.345 v.cameraPaddingFollowsContentInsets = true346 try await settle { map.jumpTo(KACameraUpdate(center: c)) }347 guard let cp = map.project(c) else { throw ScenarioFailure("projection impossible") }348 let safe = v.safeAreaInsets349 let usableMidY = (safe.top + v.contentInsets.top + v.bounds.height - safe.bottom - v.contentInsets.bottom) / 2350 try check(abs(cp.y - usableMidY) < 2, "marges de contenu suivies : centre en y \(cp.y), attendu \(usableMidY)")351 v.cameraPaddingFollowsContentInsets = false352353 // Formes de marqueur par genre, par-dessus le thème.354 try await settle { map.jumpTo(KACamera(center: c, zoom: 15.6)) }355 var shaped = DemoData.markers(around: c, count: 60, brand: .louka, spread: 0.01, seed: 3)356 for i in shaped.indices { shaped[i].kind = i % 2 == 0 ? "vente" : "inscription" }357 map.setMarkerShapes(["vente": .dot, "inscription": .diamondRing])358 let m2 = mark359 try await settle { map.addLayer(.markers(id: "formes", shaped, cluster: nil)) }360 let doc = KAJSON.parse(try map.themeDocument())361 try check(doc?["markers"]?["pill"]?["kinds"]?["vente"]?["shape"]?.stringValue == "dot" && doc?["markers"]?["pill"]?["kinds"]?["inscription"]?["shape"]?.stringValue == "diamond-ring", "les formes doivent être dans le document de style effectif")362 try check(model.log[m2...].allSatisfy { if case .error = $0.event { return false } else { return true } }, "erreur du moteur en posant les formes")363 await checkpoint("options-shapes")364 // Elles survivent à un changement de thème.365 try await settle { map.setTheme(.midnight) }366 try check(KAJSON.parse(try map.themeDocument())?["markers"]?["pill"]?["kinds"]?["vente"]?["shape"]?.stringValue == "dot", "les formes doivent survivre au changement de thème")367 map.setMarkerShapes([:])368 try await settle { map.setTheme(.signature) }369 map.removeLayer("formes")370 map.retryFailedTiles()371 await sleep(0.2)372 }373374 // MARK: Deux cartes, un stock375376 func twoMaps() async throws {377 try await reset(.montreal, zoom: 13)378 let v = try view379 for r in try map.offlineRegions() { try map.removeRegion(r.id) }380 // Carte de fiche, posée par-dessus la carte de liste : même dossier de stock, donc même `TileStore`.381 let detail = KAMapView(frame: CGRect(x: 16, y: 150, width: v.bounds.width - 32, height: 260), options: KAMapOptions(brand: .immoka, theme: .midnight, camera: KACamera(center: DemoPlace.quebec.coordinate, zoom: 14.5, pitch: 50)))382 detail.layer.cornerRadius = 14383 detail.layer.borderWidth = 1384 detail.layer.borderColor = UIColor.white.withAlphaComponent(0.6).cgColor385 detail.interaction = .twoFingers386 v.superview?.addSubview(detail)387 defer { detail.removeFromSuperview() }388 var idle = false389 let token = detail.controller.addEventHandler { if case .idle = $0 { idle = true } }390 let end = Date().addingTimeInterval(30)391 while !idle, Date() < end { await sleep(0.05) }392 detail.controller.removeEventHandler(token)393 try check(idle, "la seconde carte n'atteint pas le repos : \(detail.creationError?.message ?? "pas d'erreur de création")")394 let (p1, p2) = (try map.perf(), try detail.controller.perf())395 fact("list.tiles", .number(Double(p1.tiles)))396 fact("detail.tiles", .number(Double(p2.tiles)))397 try check(p1.tiles > 0 && p2.tiles > 0 && detail.controller.frameCount > 0, "les deux cartes doivent dessiner (\(p1.tiles) et \(p2.tiles) tuiles)")398 try check(detail.controller.theme == .midnight && map.theme == model.theme, "chaque carte garde son thème")399 await checkpoint("twomaps")400401 // Le stock est partagé : une région téléchargée par la carte de liste est vue par la carte de fiche.402 let c = CLLocationCoordinate2D(latitude: 45.4042, longitude: -71.8929)403 let m = mark404 let region = try map.downloadRegion(id: "partage", name: "Stock partagé", bounds: KABounds(west: c.longitude - 0.02, south: c.latitude - 0.012, east: c.longitude + 0.02, north: c.latitude + 0.012), minZoom: 11, maxZoom: 14)405 try await wait("offline:done", since: m, timeout: 90) { if case .offlineDone = $0 { return true } else { return false } }406 let (u1, u2) = (try map.tileStoreUsage(), try detail.controller.tileStoreUsage())407 fact("pinned.list", .number(Double(u1.pinnedBytes)))408 fact("pinned.detail", .number(Double(u2.pinnedBytes)))409 fact("region.tiles", .number(Double(region.tilesTotal)))410 try check(u1.pinnedBytes > 0 && u1.pinnedBytes == u2.pinnedBytes && u1.bytes == u2.bytes && u1.tiles == u2.tiles, "les deux cartes doivent voir le même stock : \(u1) / \(u2)")411 // La carte de fiche, réseau coupé, dessine la région téléchargée par l'autre.412 detail.networkPolicy = .offlineOnly413 let net0 = detail.controller.networkStats.completed414 idle = false415 let t2 = detail.controller.addEventHandler { if case .idle = $0 { idle = true } }416 detail.controller.jumpTo(KACamera(center: c, zoom: 13.8))417 let end2 = Date().addingTimeInterval(30)418 while !idle, Date() < end2 { await sleep(0.05) }419 detail.controller.removeEventHandler(t2)420 let p3 = try detail.controller.perf()421 fact("detail.offlineTriangles", .number(Double(p3.triangles)))422 try check(idle && p3.tiles > 0 && p3.triangles > 500 && detail.controller.networkStats.completed == net0, "la carte de fiche doit dessiner la région de l'autre carte sans réseau (\(p3.tiles) tuiles, \(p3.triangles) triangles)")423 await checkpoint("twomaps-shared-region")424 try check(try map.removeRegion("partage"), "suppression refusée")425 try check(try detail.controller.tileStoreUsage().pinnedBytes == 0, "la suppression doit être vue par l'autre carte")426 try check(detail.controller.gpuErrorCount == 0, "erreurs GPU sur la seconde carte")427 }428429 // MARK: Perte du périphérique GPU430431 func deviceLoss() async throws {432 try await reset(.montreal, zoom: 14.5, layers: [.markers, .polygons])433 try await settle { model.mode = .volumes }434 model.userLocation = KAUserLocation(coordinate: DemoPlace.montreal.coordinate, horizontalAccuracy: 30)435 await sleep(0.3)436 let v = try view437 let before = map.camera438 let layersBefore = (try map.command("listLayers").arrayValue ?? []).count439 let m = mark440 v.simulateDeviceLoss()441 try await wait("renderer:restarted", since: m, timeout: 15) { if case .rendererRestarted = $0 { return true } else { return false } }442 try await waitIdle(since: m, timeout: 40)443 let after = map.camera444 let layersAfter = (try map.command("listLayers").arrayValue ?? []).count445 let perf = try map.perf()446 fact("layersBefore", .number(Double(layersBefore)))447 fact("layersAfter", .number(Double(layersAfter)))448 fact("tilesAfter", .number(Double(perf.tiles)))449 fact("pitchAfter", .number(after.pitch))450 try check(v.creationError == nil, "la carte ne s'est pas recréée : \(v.creationError?.message ?? "")")451 try check(layersAfter == layersBefore && layersBefore == 2, "couches rejouées : \(layersAfter) sur \(layersBefore)")452 try check(abs(after.center.latitude - before.center.latitude) < 1e-6 && abs(after.zoom - before.zoom) < 0.01 && after.pitch > 40, "caméra non restaurée : \(after)")453 try check(try map.command("getMode").stringValue == "3d", "mode 3D non restauré")454 try check(perf.tiles > 0 && perf.triangles > 500, "la carte recréée ne dessine pas")455 try check(map.gpuErrorCount == 0, "le nouveau moteur a des erreurs GPU")456 try check(!(try map.renderedMarkers(layer: "markers")).isEmpty, "les pastilles ne sont pas revenues")457 await checkpoint("deviceloss-restored")458 model.userLocation = nil459 try await settle { model.mode = .flat }460 }461462 // MARK: Clavier, trackpad, molette463464 func keyboard() async throws {465 try await reset(.montreal, zoom: 14)466 let v = try view467 try check(v.canBecomeFirstResponder && (v.keyCommands?.count ?? 0) >= 11, "commandes clavier absentes")468 func press(_ input: String, shift: Bool = false) async throws -> KACamera {469 try await settle { v.performKeyboardNavigation(input: input, shift: shift) }470 return map.camera471 }472 let c0 = map.camera473 let up = try await press(UIKeyCommand.inputUpArrow)474 try check(up.center.latitude > c0.center.latitude + 1e-4 && abs(up.center.longitude - c0.center.longitude) < 1e-5, "flèche haut : la carte doit aller au nord")475 let right = try await press(UIKeyCommand.inputRightArrow)476 try check(right.center.longitude > up.center.longitude + 1e-4, "flèche droite : la carte doit aller à l'est")477 let plus = try await press("=")478 try check(abs(plus.zoom - (right.zoom + 1)) < 0.01, "+ : un niveau de zoom")479 let minus = try await press("-")480 try check(abs(minus.zoom - right.zoom) < 0.01, "− : un niveau de zoom en moins")481 let rot = try await press(UIKeyCommand.inputRightArrow, shift: true)482 try check(abs(rot.bearing - 15) < 0.1, "Maj + droite : rotation de 15°, obtenu \(rot.bearing)")483 let tilt = try await press(UIKeyCommand.inputUpArrow, shift: true)484 try check(abs(tilt.pitch - 10) < 0.1, "Maj + haut : inclinaison de 10°, obtenu \(tilt.pitch)")485 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 14)) }486487 // Trackpad : défilement = déplacement ; molette : zoom autour du pointeur.488 let p = CGPoint(x: v.bounds.width * 0.3, y: v.bounds.height * 0.4)489 guard let under = map.unproject(p) else { throw ScenarioFailure("unproject impossible") }490 try await settle {491 v.simulateScroll(dx: -80, dy: 0)492 try map.command("fling")493 }494 try check(map.camera.center.longitude > DemoPlace.montreal.coordinate.longitude + 1e-4, "défilement vers la gauche : la carte doit montrer l'est")495 try await settle { map.jumpTo(KACamera(center: DemoPlace.montreal.coordinate, zoom: 14)) }496 try await settle {497 v.simulateWheel(deltaY: 240, at: p)498 try map.command("fling")499 }500 try check(abs(map.camera.zoom - 16) < 0.01, "molette : deux niveaux de zoom attendus, zoom \(map.camera.zoom)")501 guard let still = map.project(under) else { throw ScenarioFailure("projection impossible") }502 try check(hypot(still.x - p.x, still.y - p.y) < 1.5, "le point sous le pointeur doit rester fixe pendant le zoom à la molette : \(still) pour \(p)")503 // Gestes coupés : le clavier et la molette le sont aussi.504 model.interaction = .none505 await sleep(0.2)506 let z = map.camera.zoom507 v.performKeyboardNavigation(input: "=")508 v.simulateWheel(deltaY: 240, at: p)509 await sleep(0.5)510 try check(abs(map.camera.zoom - z) < 0.001 && v.keyCommands == nil, "interaction .none : ni clavier ni molette")511 model.interaction = .all512 await sleep(0.2)513 }514515 // MARK: Grandes tailles de texte516517 func dynamicType() async throws {518 try await reset(.montreal)519 let v = try view520 guard let window = v.window, let att = (v.accessibilityElements ?? []).compactMap({ $0 as? UIControl }).first else { throw ScenarioFailure("attribution absente") }521 let normal = att.frame522 var sizes: [KAJSON] = []523 for cat in [UIContentSizeCategory.extraExtraExtraLarge, .accessibilityLarge, .accessibilityExtraExtraExtraLarge] {524 window.traitOverrides.preferredContentSizeCategory = cat525 v.setNeedsLayout()526 v.layoutIfNeeded()527 await sleep(0.4)528 let f = att.frame529 sizes.append(["category": .string(cat.rawValue), "width": .number(f.width.rounded()), "height": .number(f.height.rounded())])530 let insets = v.safeAreaInsets531 let allowed = v.bounds.inset(by: UIEdgeInsets(top: insets.top, left: insets.left, bottom: insets.bottom, right: insets.right))532 try check(allowed.insetBy(dx: -1, dy: -1).contains(f), "attribution hors de la zone sûre en \(cat.rawValue) : \(f)")533 try check(f.height >= normal.height, "le texte doit grandir avec la taille système")534 try check(f.height <= v.bounds.height * 0.16, "l'attribution ne doit pas manger la carte : \(f.height) points en \(cat.rawValue)")535 try check(att.point(inside: CGPoint(x: f.width / 2, y: f.height / 2 - 20), with: nil) || f.height >= 44, "cible tactile de 44 points")536 if cat == .accessibilityExtraExtraExtraLarge {537 try check(att.showsLargeContentViewer && att.largeContentTitle?.contains("OpenStreetMap") == true, "visionneuse de grand contenu attendue au-delà de la borne")538 await checkpoint("dyntype-ax5")539 }540 }541 fact("attribution.normal", [.number(normal.width.rounded()), .number(normal.height.rounded())])542 fact("attribution.sizes", .array(sizes))543 window.traitOverrides.remove(UITraitPreferredContentSizeCategory.self)544 v.setNeedsLayout()545 await sleep(0.3)546 }547548 // MARK: Reprise au retour du réseau549550 /// Archive : la première tentative est coupée par le serveur d'essai (`-flakyURL`), le réseau « tombe »551 /// puis « revient » (`overrideConnectivity`) : le téléchargement repart seul. Région : téléchargée552 /// réseau coupé (erreurs), elle se complète au retour.553 func reconnect() async throws {554 let mgr = KAOfflineManager.shared555 try await reset(.montreal, zoom: 12)556 defer { mgr.overrideConnectivity(nil) }557 if let s = arg("-slowURL"), let url = URL(string: s) {558 mgr.removePack("coupure")559 mgr.overrideConnectivity(KAConnectivity(isOnline: true))560 let updates = mgr.downloadUpdates561 mgr.download(KAOfflinePack(id: "coupure", title: "Coupure (essai)", url: url, bytes: 0, bounds: nil, minZoom: 0, maxZoom: 14, tiles: 0, dataVersion: "essai"))562 // Laisser arriver une partie du fichier, puis interrompre le transfert comme le ferait une563 // coupure : la tâche se termine avec ses données de reprise.564 var received: Int64 = 0565 let progress = Task { () -> Int64 in566 for await d in updates where d.id == "coupure" {567 if d.bytesReceived > 150_000 { return d.bytesReceived }568 }569 return 0570 }571 let g0 = Task { try? await Task.sleep(for: .seconds(30)); progress.cancel() }572 received = await progress.value573 g0.cancel()574 try check(received > 150_000, "le transfert lent n'a pas démarré (\(received) octets)")575 mgr.overrideConnectivity(KAConnectivity(isOnline: false))576 let updates1 = mgr.downloadUpdates577 mgr.pauseDownload("coupure")578 let paused = Task { () -> KAPackDownload? in579 for await d in updates1 where d.id == "coupure" {580 if d.state == .waiting || d.state == .finished { return d }581 if case .failed = d.state { return d }582 }583 return nil584 }585 let g1 = Task { try? await Task.sleep(for: .seconds(15)); paused.cancel() }586 let p1 = await paused.value587 g1.cancel()588 fact("pack.receivedBeforeCut", .number(Double(received)))589 try check(p1?.state == .waiting, "après la coupure l'archive doit attendre avec ses données de reprise : \(String(describing: p1?.state))")590 try check(mgr.installedPacks().first { $0.id == "coupure" } == nil, "archive installée malgré la coupure")591 await sleep(1.0)592 try check(mgr.currentDownloads().first { $0.id == "coupure" }?.state == .waiting, "hors ligne, rien ne doit repartir")593 // Le réseau revient : reprise automatique, par une demande de plage d'octets.594 let updates2 = mgr.downloadUpdates595 let t0 = Date()596 mgr.overrideConnectivity(KAConnectivity(isOnline: true))597 let second = Task { () -> KAPackDownload.State? in598 for await d in updates2 where d.id == "coupure" {599 switch d.state {600 case .failed, .finished: return d.state601 default: continue602 }603 }604 return nil605 }606 let guard2 = Task { try? await Task.sleep(for: .seconds(60)); second.cancel() }607 let s2 = await second.value608 guard2.cancel()609 fact("pack.resumeSeconds", .number((Date().timeIntervalSince(t0) * 10).rounded() / 10))610 try check(s2 == .finished, "au retour du réseau l'archive devait repartir seule : \(String(describing: s2))")611 let inst = mgr.installedPacks().first { $0.id == "coupure" }612 fact("pack.bytes", .number(Double(inst?.bytes ?? 0)))613 try check((inst?.bytes ?? 0) > 1_000_000, "archive incomplète après la reprise : \(inst?.bytes ?? 0) octets")614 mgr.removePack("coupure")615 } else {616 fact("pack.skipped", "-slowURL absent")617 }618619 // Région : réseau coupé pendant le téléchargement → erreurs ; retour du réseau → complète.620 for r in try map.offlineRegions() { try map.removeRegion(r.id) }621 let c = CLLocationCoordinate2D(latitude: 46.3432, longitude: -72.5432) // Trois-Rivières622 let b = KABounds(west: c.longitude - 0.03, south: c.latitude - 0.02, east: c.longitude + 0.03, north: c.latitude + 0.02)623 model.networkEnabled = false624 await sleep(0.3)625 mgr.overrideConnectivity(KAConnectivity(isOnline: false))626 var m = mark627 try map.downloadRegion(id: "reprise", name: "Reprise (essai)", bounds: b, minZoom: 10, maxZoom: 14)628 let e1 = try await wait("offline:done", since: m, timeout: 60) { if case .offlineDone = $0 { return true } else { return false } }629 guard case .offlineDone(let r1) = e1 else { throw ScenarioFailure("offline:done attendu") }630 fact("region.errorsOffline", .number(Double(r1.errors)))631 fact("region.doneOffline", .number(Double(r1.tilesDone)))632 try check(r1.state == .error && r1.errors > 0 && r1.tilesDone < r1.tilesTotal, "réseau coupé, la région devait finir en erreur : \(r1.state.rawValue), \(r1.tilesDone)/\(r1.tilesTotal)")633 model.networkEnabled = true634 await sleep(0.3)635 m = mark636 mgr.overrideConnectivity(KAConnectivity(isOnline: true))637 let e2 = try await wait("offline:done après le retour", since: m, timeout: 90) { if case .offlineDone = $0 { return true } else { return false } }638 guard case .offlineDone(let r2) = e2 else { throw ScenarioFailure("offline:done attendu") }639 fact("region.doneAfter", .number(Double(r2.tilesDone)))640 fact("region.total", .number(Double(r2.tilesTotal)))641 try check(r2.state == .complete && r2.tilesDone == r2.tilesTotal, "au retour du réseau la région devait se compléter seule : \(r2.state.rawValue), \(r2.tilesDone)/\(r2.tilesTotal)")642 try map.removeRegion("reprise")643 }644645 /// Archive périmée : politique manuelle (rien ne bouge), Wi-Fi seulement hors Wi-Fi (rien ne part),646 /// puis automatique en Wi-Fi : retéléchargée, remplacée, remontée dans la carte sans coupure.647 func stale() async throws {648 guard let s = arg("-packURL"), let url = URL(string: s) else {649 fact("skipped", "-packURL absent")650 return651 }652 let mgr = KAOfflineManager.shared653 try await reset(.montreal, zoom: 12)654 defer {655 mgr.overrideConnectivity(nil)656 mgr.refreshPolicy = .manual657 }658 mgr.removePack("essai")659 // Installation d'une « ancienne » version : la même archive, étiquetée d'une version passée.660 mgr.overrideConnectivity(KAConnectivity(isOnline: true))661 let (tmp, _) = try await URLSession.shared.download(from: url)662 let old = try mgr.installPack(from: tmp, id: "essai", title: "Val-d'Or (essai)", dataVersion: "20260101")663 await sleep(0.5)664 try check(try map.tileStoreUsage().archives.contains("essai"), "ancienne archive non montée")665 let index = KAOfflinePackIndex(dataVersion: "20261130", packs: [KAOfflinePack(id: "essai", title: "Val-d'Or (essai)", url: url, bytes: old.bytes, bounds: nil, minZoom: 0, maxZoom: 14, tiles: 59, dataVersion: "20261130")])666 try check(old.isOutdated(comparedTo: index) && mgr.stalePacks(comparedTo: index).map(\.id) == ["essai"], "l'archive devait être reconnue périmée")667 // Wi-Fi seulement, en cellulaire : rien ne part.668 mgr.overrideConnectivity(KAConnectivity(isOnline: true, isExpensive: true, isWiFi: false))669 try check(mgr.refreshStalePacks(comparedTo: index, wifiOnly: true).isEmpty, "Wi-Fi seulement : rien ne doit partir en cellulaire")670 // En Wi-Fi : la mise à jour part, l'ancienne archive reste montée jusqu'au remplacement.671 mgr.overrideConnectivity(KAConnectivity(isOnline: true, isExpensive: false, isWiFi: true))672 let updates = mgr.downloadUpdates673 let started = mgr.refreshStalePacks(comparedTo: index, wifiOnly: true)674 try check(started == ["essai"], "la mise à jour devait partir : \(started)")675 try check(try map.tileStoreUsage().archives.contains("essai"), "l'ancienne archive doit rester montée pendant la mise à jour")676 let done = Task { () -> KAPackDownload.State? in677 for await d in updates where d.id == "essai" {678 switch d.state {679 case .failed, .finished: return d.state680 default: continue681 }682 }683 return nil684 }685 let g = Task { try? await Task.sleep(for: .seconds(60)); done.cancel() }686 let st = await done.value687 g.cancel()688 try check(st == .finished, "mise à jour de l'archive : \(String(describing: st))")689 guard let fresh = mgr.installedPacks().first(where: { $0.id == "essai" }) else { throw ScenarioFailure("archive disparue après la mise à jour") }690 fact("old.dataVersion", .string(old.dataVersion))691 fact("new.dataVersion", .string(fresh.dataVersion))692 fact("new.installedAfterOld", .bool(fresh.installedAt > old.installedAt))693 try check(fresh.dataVersion == "20261130" && fresh.installedAt > old.installedAt && !fresh.isOutdated(comparedTo: index), "fraîcheur non mise à jour : \(fresh)")694 await sleep(0.6)695 // La carte a remonté la nouvelle archive et la dessine réseau coupé.696 try check(try map.tileStoreUsage().archives.contains("essai"), "la nouvelle archive doit être montée")697 model.networkEnabled = false698 await sleep(0.2)699 try await settle(timeout: 40) { map.jumpTo(KACamera(center: CLLocationCoordinate2D(latitude: 48.0975, longitude: -77.7828), zoom: 13.4)) }700 let perf = try map.perf()701 try check(perf.tiles > 0 && perf.triangles > 300, "la nouvelle archive ne se dessine pas (\(perf.tiles) tuiles)")702 model.networkEnabled = true703 mgr.removePack("essai")704 }705706 // MARK: Index du stock : arrêt brutal sans écriture (piloté par Scripts/test-store-index.sh)707708 /// Reproduit le défaut de l'index persistant : la région que le scénario `offline` téléchargera au709 /// lancement suivant est téléchargée, puis supprimée, et le processus attend d'être tué (`kill -9`) sans710 /// passer par l'arrière-plan — donc sans écriture de l'instantané de l'index.711 func indexKill() async throws {712 let stageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("idx-stage.txt")713 var stages = ""714 let t0 = Date()715 func stage(_ n: String) {716 stages += String(format: "%.1f %@\n", Date().timeIntervalSince(t0), n)717 try? stages.write(to: stageURL, atomically: true, encoding: .utf8)718 }719 stage("début")720 try await reset(.montreal, zoom: 12)721 stage("reset")722 for r in try map.offlineRegions() { try map.removeRegion(r.id) }723 let c = CLLocationCoordinate2D(latitude: 45.4042, longitude: -71.8929)724 let b = KABounds(west: c.longitude - 0.035, south: c.latitude - 0.022, east: c.longitude + 0.035, north: c.latitude + 0.022)725 let m = mark726 // Les tuiles peuvent déjà être dans le stock ambiant : la région est alors complète d'emblée, sans événement.727 let started = try map.downloadRegion(id: "essai-sherbrooke", name: "Sherbrooke (essai)", bounds: b, minZoom: 9, maxZoom: 14)728 stage("download \(started.state.rawValue) \(started.tilesDone)/\(started.tilesTotal)")729 if started.state != .complete {730 let done = try await wait("offline:done", since: m, timeout: 60) { if case .offlineDone = $0 { return true } else { return false } }731 guard case .offlineDone(let r) = done, r.state == .complete else { throw ScenarioFailure("région incomplète avant l'arrêt") }732 }733 stage("done")734 try check(try map.removeRegion("essai-sherbrooke"), "suppression refusée")735 stage("removed")736 // Quelques tuiles ambiantes de plus : écritures et évictions en cours au moment de l'arrêt.737 map.setAmbientCacheCap(bytes: 1 << 20)738 map.jumpTo(KACamera(center: DemoPlace.quebec.coordinate, zoom: 13))739 await sleep(0.4)740 try? "ready".write(to: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("idx-ready.txt"), atomically: true, encoding: .utf8)741 await sleep(120)742 throw ScenarioFailure("le processus devait être tué par l'hôte")743 }744745 // MARK: Transfert d'arrière-plan (piloté par Scripts/test-background-transfer.sh)746747 /// Lance le téléchargement d'une archive lente (`-slowURL`) et attend : l'hôte suspend ou tue le processus.748 func bgStart() async throws {749 guard let s = arg("-slowURL"), let url = URL(string: s) else { throw ScenarioFailure("-slowURL requis") }750 let mgr = KAOfflineManager.shared751 mgr.removePack("lent")752 mgr.overrideConnectivity(KAConnectivity(isOnline: true))753 mgr.download(KAOfflinePack(id: "lent", title: "Lent (essai)", url: url, bytes: 0, bounds: nil, minZoom: 0, maxZoom: 14, tiles: 0, dataVersion: "essai"))754 try? "started".write(to: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("bg-started.txt"), atomically: true, encoding: .utf8)755 // Reste en vie jusqu'à l'installation (cas « suspendu puis repris ») ; tué avant dans le cas « tué ».756 let end = Date().addingTimeInterval(120)757 while Date() < end, mgr.installedPacks().first(where: { $0.id == "lent" }) == nil { await sleep(0.1) }758 let inst = mgr.installedPacks().first { $0.id == "lent" }759 fact("installedBytes", .number(Double(inst?.bytes ?? 0)))760 fact("finishedAt", .number(Date().timeIntervalSince1970))761 try check(inst != nil, "archive non installée")762 }763764 /// Après relance : le transfert d'avant l'arrêt se termine (tâche retrouvée vivante, ou reprise).765 func bgFinish() async throws {766 let mgr = KAOfflineManager.shared767 let t0 = Date()768 let end = Date().addingTimeInterval(120)769 while Date() < end, mgr.installedPacks().first(where: { $0.id == "lent" }) == nil { await sleep(0.1) }770 let inst = mgr.installedPacks().first { $0.id == "lent" }771 fact("installedBytes", .number(Double(inst?.bytes ?? 0)))772 fact("secondsAfterRelaunch", .number((Date().timeIntervalSince(t0) * 10).rounded() / 10))773 fact("reattachedTransfers", .number(Double(mgr.reattachedTransfers)))774 fact("backgroundSessionEvents", .number(Double(mgr.backgroundSessionEvents)))775 fact("finishedAt", .number(Date().timeIntervalSince1970))776 try check(inst != nil, "archive non installée après la relance")777 await sleep(0.5)778 try check(try map.tileStoreUsage().archives.contains("lent"), "archive non montée après la relance")779 mgr.removePack("lent")780 }781}782