Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Apps/ORIXMaps/Sources/Map/StyleCoordinator.swift10// Module : Map11// 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 ORIXGeoCore90import ORIXMapRenderer91import ORIXMapStyle9293/// Rebuilds the style document whenever the theme, the label language or the set of installed regions changes.94final class StyleCoordinator {95 private let controller: MapController96 private let cacheDirectory: URL97 private var lastKey: String?9899 init(controller: MapController, cacheDirectory: URL) {100 self.controller = controller101 self.cacheDirectory = cacheDirectory102 try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)103 }104105 static let baseMapURL = Bundle.main.bundleURL.appending(path: "BaseMap/world-base.pmtiles")106 static let worldLabelsURL = Bundle.main.bundleURL.appending(path: "BaseMap/world-labels.geojson")107 static let baseMapMaxZoom = 6108109 func apply(theme: MapTheme, language: String, regions: [MapRegion]) {110 let visible = Self.drawnRegions(regions)111 var sources = [StyleSource(id: "base", url: "pmtiles://" + Self.baseMapURL.absoluteString, role: .base, minZoom: 0, maxZoom: Self.baseMapMaxZoom,112 attribution: "© OpenStreetMap contributors, Natural Earth")]113 for r in visible {114 sources.append(StyleSource(id: "r-" + r.id, url: "pmtiles://" + r.mapURL.absoluteString, role: .region, minZoom: r.minZoom, maxZoom: r.maxZoom, bounds: r.bounds))115 }116 let labels = worldLabels(excluding: visible.map(\.bounds))117 let options = StyleOptions(glyphsURL: Bundle.main.bundleURL.absoluteString + "Glyphs/{fontstack}/{range}.pbf", language: language,118 regionDetailMinZoom: Self.baseMapMaxZoom + 1, worldLabelsURL: labels?.absoluteString)119 guard let data = try? StyleBuilder.styleData(theme: theme, sources: sources, options: options) else { return }120 controller.setStyle(data)121 }122123 /// The installed regions that are drawn: a region wholly inside another one that is at least as recent and as124 /// detailed is left out (see `RegionRenderPlanner`). The order of `regions` is kept.125 static func drawnRegions(_ regions: [MapRegion]) -> [MapRegion] {126 let drawn = Set(RegionRenderPlanner.regionsToDraw(regions.map {127 RegionRenderPlanner.Candidate(id: $0.id, bounds: $0.bounds, dataVersion: $0.dataVersion, maxZoom: $0.maxZoom)128 }))129 return regions.filter { drawn.contains($0.id) }130 }131132 /// The bundled world labels with `inRegion: true` on every city covered by a drawn region (whose own labels take over133 /// at higher zooms). Written once per distinct set of regions.134 func worldLabels(excluding boxes: [BoundingBox]) -> URL? {135 guard !boxes.isEmpty else { return Self.worldLabelsURL }136 let key = boxes.map { "\($0.minLat),\($0.minLon),\($0.maxLat),\($0.maxLon)" }.sorted().joined(separator: ";")137 let name = "world-labels-\(UInt64(truncatingIfNeeded: key.hashValue.magnitude) % 1_000_000_007)-\(key.count).geojson"138 let out = cacheDirectory.appending(path: name)139 if lastKey == key, FileManager.default.fileExists(atPath: out.path) { return out }140 guard let data = try? Data(contentsOf: Self.worldLabelsURL),141 var root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],142 var features = root["features"] as? [[String: Any]] else { return Self.worldLabelsURL }143 for i in features.indices {144 guard let g = features[i]["geometry"] as? [String: Any], let c = g["coordinates"] as? [Double], c.count == 2,145 var p = features[i]["properties"] as? [String: Any], p["kind"] as? String == "locality" else { continue }146 let point = Coordinate(latitude: c[1], longitude: c[0])147 if boxes.contains(where: { $0.contains(point) }) { p["inRegion"] = true; features[i]["properties"] = p }148 }149 root["features"] = features150 guard let encoded = try? JSONSerialization.data(withJSONObject: root) else { return Self.worldLabelsURL }151 // Remove files written for earlier region sets.152 for f in (try? FileManager.default.contentsOfDirectory(at: cacheDirectory, includingPropertiesForKeys: nil)) ?? [] where f.lastPathComponent.hasPrefix("world-labels-") {153 try? FileManager.default.removeItem(at: f)154 }155 do { try encoded.write(to: out, options: .atomic) } catch { return Self.worldLabelsURL }156 lastKey = key157 return out158 }159}160