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/Layers/ThemeEditor.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 ORIXDesignSystem89import ORIXMapStyle90import SwiftUI91import UniformTypeIdentifiers9293extension UTType {94 static let orixTheme = UTType(exportedAs: "ai.spboucher.orix.maps.theme", conformingTo: .json)95}9697/// Map Studio: the list of themes, with duplicate, import, export and delete.98struct ThemeListScreen: View {99 @Environment(AppModel.self) private var app100 @State private var importing = false101 @State private var error: String?102 @State private var shared: URL?103104 var body: some View {105 List {106 Section("Built-in themes") {107 ForEach(BuiltInThemes.all) { theme in row(theme) }108 }109 Section {110 if app.themes.customThemes.isEmpty {111 Text("Duplicate a built-in theme to make your own: colours, road widths, label density and the kinds of places shown.")112 .font(.footnote).foregroundStyle(.secondary)113 }114 ForEach(app.themes.customThemes) { theme in115 NavigationLink { ThemeEditorScreen(theme: theme) } label: { rowLabel(theme) }116 .swipeActions {117 Button("Delete", role: .destructive) {118 if app.settings.themeID == theme.id { app.selectTheme(BuiltInThemes.dayID) }119 app.themes.delete(id: theme.id)120 }121 }122 .accessibilityIdentifier("studio.custom.\(theme.name)")123 }124 } header: { Text("My themes") }125 UserLayersSection()126 Section {127 Button { importing = true } label: { Label("Import a theme file", systemImage: "square.and.arrow.down") }128 .accessibilityIdentifier("studio.import")129 }130 }131 .navigationTitle("Map Studio")132 .navigationBarTitleDisplayMode(.inline)133 .fileImporter(isPresented: $importing, allowedContentTypes: [.orixTheme, .json]) { result in importTheme(result) }134 .alert("Import failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { Button("OK") {} } message: { Text(error ?? "") }135 #if DEBUG136 .task {137 // -ORIXImportTheme valid|invalid: the file a user would pick, handed to the same import code.138 guard let kind = app.options.importThemeFixture, !Self.fixtureImported else { return }139 Self.fixtureImported = true140 var theme = BuiltInThemes.terrain141 theme.name = "Imported test theme"142 let data = kind == "valid" ? (try? ThemeDocument(theme: theme).exported()) ?? Data() : Data("{\"format\": \"something-else\", \"version\": 1}".utf8)143 let file = FileManager.default.temporaryDirectory.appending(path: "orix-import-fixture.orixtheme")144 try? data.write(to: file, options: .atomic)145 importTheme(.success(file))146 }147 #endif148 }149150 #if DEBUG151 private static var fixtureImported = false152 #endif153154 /// Imports the picked file and selects the new theme, or explains why the file was refused.155 private func importTheme(_ result: Result<URL, any Error>) {156 do {157 let theme = try app.themes.importTheme(from: try result.get())158 app.selectTheme(theme.id)159 } catch let e as ThemeDocument.ImportError {160 switch e {161 case .tooLarge: error = String(localized: "This file is too large to be a theme.")162 case .notAThemeFile: error = String(localized: "This file is not an ORIX Maps theme.")163 case .unsupportedVersion: error = String(localized: "This theme was made with a newer version of ORIX Maps.")164 }165 } catch { self.error = String(localized: "The file could not be read.") }166 }167168 private func rowLabel(_ theme: MapTheme) -> some View {169 HStack(spacing: ORIX.Spacing.m) {170 ThemeSwatch(theme: theme).frame(width: 64, height: 44)171 Text(theme.displayName)172 Spacer()173 if theme.id == app.settings.themeID { Image(systemName: "checkmark").foregroundStyle(ORIX.Palette.accent).accessibilityLabel("Selected") }174 }175 }176177 private func row(_ theme: MapTheme) -> some View {178 HStack {179 Button { app.selectTheme(theme.id) } label: { rowLabel(theme) }.buttonStyle(.plain)180 Button {181 if let copy = try? app.themes.duplicate(theme, name: String(localized: "\(theme.displayName) copy")) { app.selectTheme(copy.id) }182 } label: { Image(systemName: "plus.square.on.square").frame(width: ORIX.minimumTarget, height: ORIX.minimumTarget) }183 .buttonStyle(.borderless)184 .accessibilityLabel(Text("Duplicate \(theme.displayName)"))185 .accessibilityIdentifier("studio.duplicate.\(theme.id)")186 }187 }188}189190/// Editor of one user theme. Every change is drawn on the map immediately and saved.191struct ThemeEditorScreen: View {192 @Environment(AppModel.self) private var app193 @Environment(\.dismiss) private var dismiss194 @State var theme: MapTheme195 @State private var exportURL: URL?196197 var body: some View {198 Form {199 Section {200 TextField("Name", text: $theme.name)201 Toggle("Dark theme", isOn: $theme.isDark)202 }203 Section("Roads and labels") {204 slider("Road width", value: $theme.roadWidthScale, range: 0.5...2)205 Toggle("Road outlines", isOn: $theme.roadCasings)206 slider("Label density", value: $theme.labelDensity, range: 0...1)207 slider("Label size", value: $theme.labelSizeScale, range: 0.8...1.6)208 }209 Section("Content") {210 Toggle("Buildings", isOn: $theme.showBuildings)211 Toggle("3D buildings when tilted", isOn: $theme.extrudeBuildings).disabled(!theme.showBuildings)212 Toggle("Land use colours", isOn: $theme.showLandUse)213 Toggle("Places of interest", isOn: $theme.showPointsOfInterest)214 Toggle("Emphasize railways and stations", isOn: $theme.emphasizeTransit)215 Toggle("Emphasize trails and nature", isOn: $theme.emphasizeOutdoors)216 }217 if theme.showPointsOfInterest {218 Section("Kinds of places shown") {219 ForEach(POIGroup.all) { g in220 Toggle(isOn: Binding(get: { !theme.hiddenPOIGroups.contains(g.id) }, set: { on in221 if on { theme.hiddenPOIGroups.remove(g.id) } else { theme.hiddenPOIGroups.insert(g.id) }222 })) { Label(g.localizedName, systemImage: g.symbol) }223 }224 }225 }226 ForEach(ColorRole.groups, id: \.id) { group in227 Section(ColorRole.groupName(group.id)) {228 ForEach(group.roles, id: \.self) { role in229 ColorPicker(role.localizedName, selection: Binding(get: { Color(theme[role]) }, set: { theme[role] = HexColor($0) ?? theme[role] }), supportsOpacity: false)230 }231 }232 }233 Section {234 if let exportURL { ShareLink(item: exportURL) { Label("Share the theme file", systemImage: "square.and.arrow.up") } }235 if theme.isDark {236 Button("Restore the colours of Midnight") { theme.colors = BuiltInThemes.midnight.colors }237 } else {238 Button("Restore the colours of ORIX Day") { theme.colors = BuiltInThemes.day.colors }239 }240 Button("Delete this theme", role: .destructive) {241 app.selectTheme(BuiltInThemes.dayID)242 app.themes.delete(id: theme.id)243 dismiss()244 }245 }246 }247 .navigationTitle(theme.name)248 .navigationBarTitleDisplayMode(.inline)249 .onAppear { app.selectTheme(theme.id); exportURL = try? app.themes.exportFile(for: theme) }250 .onChange(of: theme) { _, new in251 guard let saved = try? app.themes.save(new) else { return }252 app.selectTheme(saved.id)253 exportURL = try? app.themes.exportFile(for: saved)254 }255 }256257 private func slider(_ title: LocalizedStringKey, value: Binding<Double>, range: ClosedRange<Double>) -> some View {258 VStack(alignment: .leading, spacing: 2) {259 Text(title).font(.subheadline)260 Slider(value: value, in: range) { Text(title) }261 }262 }263}264265extension HexColor {266 /// Converts an sRGB SwiftUI colour picked by the user.267 init?(_ color: Color) {268 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0269 guard UIColor(color).getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }270 func byte(_ v: CGFloat) -> UInt8 { UInt8((min(1, max(0, v)) * 255).rounded()) }271 self.init(red: byte(r), green: byte(g), blue: byte(b))272 }273}274275extension POIGroup {276 var localizedName: String {277 switch id {278 case "food": String(localized: "Food and drink")279 case "shopping": String(localized: "Shops")280 case "lodging": String(localized: "Lodging")281 case "health": String(localized: "Health")282 case "education": String(localized: "Education")283 case "transit": String(localized: "Transit")284 case "motoring": String(localized: "Fuel, charging and parking")285 case "nature": String(localized: "Parks and nature")286 case "culture": String(localized: "Culture and sights")287 case "sport": String(localized: "Sport")288 default: String(localized: "Services")289 }290 }291}292293extension ColorRole {294 static func groupName(_ id: String) -> String {295 switch id {296 case "land": String(localized: "Land")297 case "water": String(localized: "Water")298 case "areas": String(localized: "Areas")299 case "buildings": String(localized: "Buildings")300 case "roads": String(localized: "Roads and lines")301 case "labels": String(localized: "Labels")302 default: String(localized: "Routes and markers")303 }304 }305306 var localizedName: String {307 switch self {308 case .land: String(localized: "Land")309 case .water: String(localized: "Water")310 case .waterway: String(localized: "Rivers and streams")311 case .park: String(localized: "Parks")312 case .wood: String(localized: "Forest")313 case .grass: String(localized: "Grass")314 case .farmland: String(localized: "Farmland")315 case .sand: String(localized: "Sand and rock")316 case .glacier: String(localized: "Ice")317 case .wetland: String(localized: "Wetland")318 case .residential: String(localized: "Built-up areas")319 case .industrial: String(localized: "Industrial areas")320 case .education: String(localized: "Schools and campuses")321 case .medical: String(localized: "Hospitals")322 case .pedestrian: String(localized: "Pedestrian areas")323 case .aerodrome: String(localized: "Airports")324 case .cemetery: String(localized: "Cemeteries")325 case .building: String(localized: "Buildings")326 case .buildingOutline: String(localized: "Building outlines")327 case .highway: String(localized: "Motorways")328 case .highwayCasing: String(localized: "Motorway outlines")329 case .majorRoad: String(localized: "Main roads")330 case .majorRoadCasing: String(localized: "Main road outlines")331 case .minorRoad: String(localized: "Streets")332 case .minorRoadCasing: String(localized: "Street outlines")333 case .path: String(localized: "Paths and trails")334 case .rail: String(localized: "Railways")335 case .tunnelTint: String(localized: "Tunnel tint")336 case .boundary: String(localized: "Borders")337 case .placeLabel: String(localized: "Place names")338 case .roadLabel: String(localized: "Road names")339 case .waterLabel: String(localized: "Water names")340 case .poiLabel: String(localized: "Place of interest names")341 case .labelHalo: String(localized: "Text outline")342 case .route: String(localized: "Route")343 case .routeCasing: String(localized: "Route outline")344 case .routeAlternative: String(localized: "Alternative routes")345 case .track: String(localized: "Recorded tracks")346 case .accent: String(localized: "Markers and position")347 }348 }349}350