Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : App/Screens/ThemeEditorView.swift10// Description : Theme editor for a custom theme: backdrop gradient, effect11// and motion, a local background photo, colours per key12// family, per row and per key, metrics, haptics, a live13// keyboard preview with a contrast readout, JSON export and14// deletion.15// Module : App16// Repository : https://git.spboucher.ai/sp-keyboard17// Created : 2026-12-0118// Last Modified : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import PhotosUI94import KeyboardCore95import ThemeEngine9697struct ThemeEditorView: View {98 let themeID: String99 @Environment(AppModel.self) private var model100 @Environment(\.dismiss) private var dismiss101 @State private var draft: Theme?102 @State private var document = PreviewDocument(text: "Bonjour ")103 @State private var photoItem: PhotosPickerItem?104 @State private var photoMessage: String?105 @State private var isExporting = false106 @State private var exportData = Data()107 @State private var confirmDelete = false108 @State private var keyToTint = "a"109110 static let tintableKeys: [(id: String, name: String)] =111 "abcdefghijklmnopqrstuvwxyz".map { (String($0), String($0).uppercased()) }112 + [("é", "É"), ("ñ", "Ñ"), ("'", "Apostrophe"), (".", "Point"), ("space", "Espace"), ("return", "Retour"), ("shift", "Majuscule"),113 ("backspace", "Effacer"), ("page.numbers", "123"), ("globe", "Globe"), ("language", "Langue")]114115 var body: some View {116 Group {117 if let draft {118 editor(Binding(get: { self.draft ?? draft }, set: { self.draft = $0 }))119 } else {120 ContentUnavailableView("Thème introuvable", systemImage: "paintpalette",121 description: Text("Ce thème a été supprimé."))122 }123 }124 .navigationTitle(draft?.name ?? "Thème")125 .navigationBarTitleDisplayMode(.inline)126 .onAppear { if draft == nil { draft = model.library.custom.first { $0.id == themeID } } }127 .onChange(of: draft) { _, value in128 if let value { model.updateTheme(value) }129 }130 }131132 private func editor(_ theme: Binding<Theme>) -> some View {133 Form {134 Section("Nom") {135 TextField("Nom du thème", text: theme.name)136 .accessibilityIdentifier("editor.name")137 Button(model.library.active.id == themeID ? "Thème actif" : "Activer ce thème") {138 model.activateTheme(id: themeID)139 }140 .disabled(model.library.active.id == themeID)141 .accessibilityIdentifier("editor.activate")142 }143144 Section {145 contrastRow(theme.wrappedValue)146 } header: {147 Text("Lisibilité")148 } footer: {149 Text("Le clavier corrige de lui-même une étiquette illisible ; ce chiffre est le contraste de vos couleurs telles que choisies.")150 }151152 Section("Fond") {153 colorList("Couleur", colors: theme.background.colors, minimum: 1)154 LabeledSlider(title: "Angle du dégradé", value: theme.background.angle, range: 0...360, step: 5) { "\(Int($0))°" }155 Picker("Effet", selection: theme.effect) {156 ForEach(BackdropEffect.allCases, id: \.self) { Text(Self.name($0)).tag($0) }157 }158 Picker("Animation", selection: theme.motion) {159 Text("Aucune").tag(MotionLevel.off)160 Text("Discrète").tag(MotionLevel.subtle)161 Text("Complète").tag(MotionLevel.full)162 }163 }164165 if theme.wrappedValue.effect != .none {166 Section("Couleurs de l'effet") {167 colorList("Teinte", colors: theme.effectColors, minimum: 0)168 }169 }170171 Section {172 PhotosPicker(selection: $photoItem, matching: .images, photoLibrary: .shared()) {173 Label(theme.wrappedValue.backgroundImage == nil ? "Choisir une photo de fond" : "Changer la photo de fond", systemImage: "photo")174 }175 .accessibilityIdentifier("editor.photo")176 if theme.wrappedValue.backgroundImage != nil {177 LabeledSlider(title: "Voile sur la photo", value: theme.imageDim, range: 0...0.85) { "\(Int($0 * 100)) %" }178 Button("Retirer la photo", role: .destructive) {179 draft = model.removeBackground(from: theme.wrappedValue)180 }181 }182 if let photoMessage {183 Text(photoMessage).font(.footnote).foregroundStyle(.secondary)184 }185 } header: {186 Text("Photo")187 } footer: {188 Text("La photo est réduite sur l'appareil (\(ThemeLibrary.maxBackgroundPixels) px, \(ThemeLibrary.maxBackgroundBytes / 1024) Ko au plus), rangée dans le conteneur partagé avec le clavier et jamais envoyée sur le réseau. Elle n'est pas incluse dans un export.")189 }190 .onChange(of: photoItem) { _, item in191 guard let item else { return }192 Task { await loadPhoto(item) }193 }194195 keySection("Touches de lettres", style: theme.letterKey)196 keySection("Touches de fonction", style: theme.functionKey)197 keySection("Touche d'action (retour)", style: theme.accentKey)198199 Section("Autres couleurs") {200 ColorPicker("Touche enfoncée", selection: theme.pressedTint.asColor)201 ColorPicker("Texte des suggestions", selection: theme.suggestionText.asColor, supportsOpacity: false)202 }203204 Section {205 Toggle("Teinter chaque rangée", isOn: Binding(206 get: { !theme.wrappedValue.rowTints.isEmpty },207 set: { enabled in208 theme.wrappedValue.rowTints = enabled ? Array(repeating: theme.wrappedValue.letterKey.border.opacity(1), count: 4) : []209 }))210 ForEach(theme.wrappedValue.rowTints.indices, id: \.self) { index in211 ColorPicker("Rangée \(index + 1)", selection: theme.rowTints[index].asColor, supportsOpacity: false)212 }213 } header: {214 Text("Couleurs par rangée")215 } footer: {216 Text("Teinte de la bordure et du halo des lettres, de haut en bas.")217 }218219 Section {220 Picker("Touche", selection: $keyToTint) {221 ForEach(Self.tintableKeys, id: \.id) { Text($0.name).tag($0.id) }222 }223 Button("Ajouter une couleur pour cette touche") {224 theme.wrappedValue.keyTints[keyToTint] = theme.wrappedValue.accentKey.glow.opacity(1)225 }226 .disabled(theme.wrappedValue.keyTints[keyToTint] != nil || theme.wrappedValue.keyTints.count >= Theme.maxKeyTints)227 ForEach(theme.wrappedValue.keyTints.keys.sorted(), id: \.self) { key in228 HStack {229 ColorPicker(Self.tintableKeys.first { $0.id == key }?.name ?? key, selection: Binding(230 get: { (theme.wrappedValue.keyTints[key] ?? .white).color },231 set: { theme.wrappedValue.keyTints[key] = RGBA($0) }), supportsOpacity: false)232 Button(role: .destructive) {233 theme.wrappedValue.keyTints[key] = nil234 } label: {235 Image(systemName: "minus.circle.fill")236 }237 .buttonStyle(.borderless)238 .accessibilityLabel("Retirer la couleur de la touche \(key)")239 }240 }241 } header: {242 Text("Couleurs par touche")243 }244245 Section("Forme et espacement") {246 LabeledSlider(title: "Arrondi", value: theme.metrics.cornerRadius, range: ThemeMetrics.cornerRadiusRange, step: 1) { "\(Int($0)) pt" }247 LabeledSlider(title: "Hauteur", value: theme.metrics.heightScale, range: ThemeMetrics.heightScaleRange, step: 0.05) { "\(Int(($0 * 100).rounded())) %" }248 LabeledSlider(title: "Espacement", value: theme.metrics.spacing, range: ThemeMetrics.spacingRange, step: 1) { "\(Int($0)) pt" }249 LabeledSlider(title: "Bordure", value: theme.metrics.borderWidth, range: ThemeMetrics.borderWidthRange, step: 0.1) { String(format: "%.1f pt", $0) }250 }251252 Section("Lumière") {253 LabeledSlider(title: "Opacité des touches", value: theme.metrics.keyOpacity, range: ThemeMetrics.keyOpacityRange) { "\(Int($0 * 100)) %" }254 LabeledSlider(title: "Intensité des halos", value: theme.metrics.glowIntensity, range: 0...1) { "\(Int($0 * 100)) %" }255 LabeledSlider(title: "Renfort de contraste", value: theme.metrics.contrastBoost, range: 0...1) { "\(Int($0 * 100)) %" }256 Toggle("Thème sombre", isOn: theme.isDark)257 }258259 Section("Retour tactile du thème") {260 Picker("Retour tactile", selection: theme.haptic) {261 Text("Aucun").tag(HapticLevel.off)262 Text("Léger").tag(HapticLevel.light)263 Text("Marqué").tag(HapticLevel.medium)264 }265 .pickerStyle(.segmented)266 }267268 Section {269 Button {270 if let data = try? model.exportTheme(theme.wrappedValue) {271 exportData = data272 isExporting = true273 }274 } label: {275 Label("Exporter en JSON", systemImage: "square.and.arrow.up")276 }277 .accessibilityIdentifier("editor.export")278 Button(role: .destructive) {279 confirmDelete = true280 } label: {281 Label("Supprimer ce thème", systemImage: "trash")282 }283 .accessibilityIdentifier("editor.delete")284 }285 }286 .safeAreaInset(edge: .bottom, spacing: 0) {287 PreviewDock(theme: theme.wrappedValue, settings: model.settings, dictionary: model.dictionary, aiSettings: model.ai, document: document)288 }289 .fileExporter(isPresented: $isExporting, document: JSONFile(data: exportData), contentType: .json,290 defaultFilename: Self.fileName(theme.wrappedValue.name)) { _ in }291 .confirmationDialog("Supprimer ce thème?", isPresented: $confirmDelete, titleVisibility: .visible) {292 Button("Supprimer", role: .destructive) {293 draft = nil294 model.deleteTheme(id: themeID)295 dismiss()296 }297 } message: {298 Text("Sa photo de fond est aussi effacée de l'appareil.")299 }300 }301302 private func contrastRow(_ theme: Theme) -> some View {303 let ratio = theme.normalized().minimumContrast304 return HStack {305 Image(systemName: ratio >= 4.5 ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")306 .foregroundStyle(ratio >= 4.5 ? .green : .orange)307 .accessibilityHidden(true)308 VStack(alignment: .leading, spacing: 2) {309 Text("Contraste minimal \(ratio.formatted(.number.precision(.fractionLength(1)).locale(Locale(identifier: "fr_CA")))) : 1").font(.subheadline.weight(.semibold))310 Text(ratio >= 4.5 ? "Lettres lisibles (4,5 : 1 ou plus)." : "Sous 4,5 : 1 : le clavier ajustera la couleur des lettres.")311 .font(.footnote)312 .foregroundStyle(.secondary)313 }314 }315 .accessibilityElement(children: .combine)316 .accessibilityIdentifier("editor.contrast")317 }318319 @ViewBuilder320 private func colorList(_ label: String, colors: Binding<[RGBA]>, minimum: Int) -> some View {321 ForEach(colors.wrappedValue.indices, id: \.self) { index in322 HStack {323 ColorPicker("\(label) \(index + 1)", selection: colors[index].asColor, supportsOpacity: false)324 if colors.wrappedValue.count > minimum {325 Button(role: .destructive) {326 colors.wrappedValue.remove(at: index)327 } label: {328 Image(systemName: "minus.circle.fill")329 }330 .buttonStyle(.borderless)331 .accessibilityLabel("Retirer \(label.lowercased()) \(index + 1)")332 }333 }334 }335 if colors.wrappedValue.count < Theme.maxGradientColors {336 Button("Ajouter une couleur") {337 colors.wrappedValue.append(colors.wrappedValue.last ?? RGBA("#8B5CF6"))338 }339 }340 }341342 private func keySection(_ title: String, style: Binding<KeyStyle>) -> some View {343 Section(title) {344 ColorPicker("Fond (haut)", selection: Binding(345 get: { (style.wrappedValue.fill.colors.first ?? .black).color },346 set: { color in347 var colors = style.wrappedValue.fill.colors348 if colors.isEmpty { colors = [RGBA(color)] } else { colors[0] = RGBA(color) }349 style.wrappedValue.fill.colors = colors350 }))351 ColorPicker("Fond (bas)", selection: Binding(352 get: { (style.wrappedValue.fill.colors.last ?? .black).color },353 set: { color in354 var colors = style.wrappedValue.fill.colors355 if colors.count < 2 { colors = [colors.first ?? RGBA(color), RGBA(color)] } else { colors[colors.count - 1] = RGBA(color) }356 style.wrappedValue.fill.colors = colors357 }))358 ColorPicker("Lettres", selection: style.text.asColor, supportsOpacity: false)359 ColorPicker("Bordure", selection: style.border.asColor)360 ColorPicker("Halo", selection: style.glow.asColor)361 }362 }363364 private func loadPhoto(_ item: PhotosPickerItem) async {365 photoMessage = nil366 defer { photoItem = nil }367 guard let data = try? await item.loadTransferable(type: Data.self), let current = draft else {368 photoMessage = "Photo illisible."369 return370 }371 do {372 draft = try model.setBackground(imageData: data, for: current)373 photoMessage = "Photo réduite et enregistrée sur l'appareil."374 } catch {375 switch error {376 case .containerUnavailable: photoMessage = "Conteneur partagé inaccessible : la photo ne peut pas être transmise au clavier."377 case .unreadableImage: photoMessage = "Ce fichier n'est pas une image lisible."378 case .tooLarge: photoMessage = "Photo encore trop lourde après réduction."379 case .writeFailed: photoMessage = "Écriture impossible."380 }381 }382 }383384 static func fileName(_ name: String) -> String {385 let cleaned = name.lowercased().map { $0.isLetter || $0.isNumber ? $0 : "-" }386 return "sp-keyboard-theme-" + String(cleaned).trimmingCharacters(in: CharacterSet(charactersIn: "-"))387 }388389 static func name(_ effect: BackdropEffect) -> String {390 switch effect {391 case .none: "Aucun"392 case .aurora: "Aurore"393 case .neon: "Néon"394 case .plasma: "Plasma"395 case .waves: "Vagues"396 case .stars: "Étoiles"397 case .iridescence: "Iridescence"398 case .glass: "Verre"399 case .energy: "Énergie"400 case .crystal: "Cristal"401 case .luxe: "Luxe"402 case .heat: "Chaleur"403 }404 }405}406