SPB Git

Repository Public

SettingsView.swift 14.0 KB 197 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Settings/SettingsView.swift3// Description: Settings window: general (Finder location, start at login, menu bar), synchronisation (pause, bandwidth, parallel transfers), notifications, account and security (devices, biometric lock, sign out).4import ServiceManagement5import SPDriveCore6import SPDriveNext7import SwiftUI89struct SettingsView: View {10    @AppStorage("settingsTab") private var tab = "general"11    var body: some View {12        TabView(selection: $tab) {13            GeneralSettings().tabItem { Label("Général", systemImage: "gearshape") }.tag("general")14            SyncSettings().tabItem { Label("Synchronisation", systemImage: "arrow.triangle.2.circlepath") }.tag("sync")15            NotificationSettings().tabItem { Label("Notifications", systemImage: "bell") }.tag("notifications")16            AccountSettings().tabItem { Label("Compte", systemImage: "person.crop.circle") }.tag("account")17        }18        .frame(width: 600, height: 580)19    }20}2122private struct GeneralSettings: View {23    @Environment(AppModel.self) private var model24    @State private var launchAtLogin = SMAppService.mainApp.status == .enabled25    @State private var loginError: String?26    var body: some View {27        @Bindable var s = model.settings28        Form {29            Section("Finder") {30                Toggle("Afficher SP Drive dans le Finder", isOn: Binding(get: { s.finderIntegration }, set: { s.finderIntegration = $0; Task { await model.applyFinderIntegration() } }))31                if model.finderRegistered, !model.finderEnabled {32                    Label("L’emplacement attend votre accord dans Réglages Système › Général › Ouverture et extensions › Fournisseurs de fichiers.", systemImage: "exclamationmark.circle").font(.callout).foregroundStyle(.orange)33                    Button("Ouvrir les Réglages Système") { DriveDomain.shared.openSystemSettings() }34                }35                Text(model.finderReady ? "SP Drive est un emplacement du Finder : ouvrez, modifiez et enregistrez vos fichiers depuis vos applications, les changements sont synchronisés." : "Sans l’emplacement du Finder, les fichiers se consultent et se téléchargent depuis l’application ; la disponibilité hors ligne n’est pas gérée.")36                    .font(.caption).foregroundStyle(.secondary)37                if model.finderReady { Button("Ouvrir SP Drive dans le Finder") { Task { await DriveDomain.shared.openInFinder() } } }38            }39            Section("Démarrage") {40                Toggle("Ouvrir SP Drive à l’ouverture de session", isOn: Binding(get: { launchAtLogin }, set: { on in41                    do { if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }; loginError = nil } catch { loginError = error.localizedDescription }42                    launchAtLogin = SMAppService.mainApp.status == .enabled43                }))44                if let loginError { Text(loginError).font(.caption).foregroundStyle(.orange) }45                Toggle("Afficher l’icône dans la barre de menus", isOn: $s.showMenuBarIcon)46                Text("Avec l’icône de la barre de menus, SP Drive continue de synchroniser quand sa fenêtre est fermée.").font(.caption).foregroundStyle(.secondary)47            }48            Section("Bureau et recherche") {49                Toggle("Zone de dépôt flottante sur le bureau", isOn: Binding(get: { s.dropZone }, set: { s.dropZone = $0; DropZoneController.shared.update(model: model) }))50                if s.dropZone {51                    Picker("Destination", selection: Binding(get: { s.dropZoneFolderID ?? "" }, set: { s.dropZoneFolderID = $0.isEmpty ? nil : $0 })) {52                        Text("Mon Drive").tag("")53                        ForEach((model.rootID.map { model.children(of: $0) } ?? []).filter(\.isFolder)) { f in Text(f.name).tag(f.id) }54                    }55                }56                Text("Une petite tuile reste au-dessus des fenêtres : glissez-y des fichiers depuis n’importe quelle application. Elle se déplace à la souris et ne prend jamais le focus.").font(.caption).foregroundStyle(.secondary)57                Toggle("Retrouver mes éléments dans Spotlight (noms seulement)", isOn: Binding(get: { s.spotlightIndex }, set: { on in58                    s.spotlightIndex = on59                    Task { if on { await SpotlightIndexer.shared.sync(model: model) } else { await SpotlightIndexer.shared.removeAll() } }60                }))61                Text("Seuls le nom, le type, les dates et l’emplacement sont indexés sur ce Mac — jamais le contenu des fichiers. L’index est effacé si vous décochez cette case ou vous déconnectez. Inutile si l’emplacement du Finder est actif : macOS indexe déjà ses fichiers.").font(.caption).foregroundStyle(.secondary)62            }63            Section("À propos") {64                LabeledContent("Version", value: "\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? ""))")65                LabeledContent("Serveur", value: AppEnvironment.serverURL.host ?? "")66                Text("Les fichiers sont chiffrés en transit (TLS) et au repos sur le serveur. Ce n’est pas un chiffrement de bout en bout : le serveur MacLustr détient les clés.").font(.caption).foregroundStyle(.secondary)67            }68        }.formStyle(.grouped)69    }70}7172private struct SyncSettings: View {73    @Environment(AppModel.self) private var model74    var body: some View {75        @Bindable var s = model.settings76        Form {77            Section("État") {78                LabeledContent("Synchronisation") { HStack { SyncStatusIcon(status: model.status); Text(SyncStatusText.title(model.status)) } }79                LabeledContent("Détail", value: SyncStatusText.detail(model.status))80                Toggle("Mettre la synchronisation en pause", isOn: Binding(get: { s.syncPaused }, set: { on in Task { await model.setPaused(on) } }))81                Button("Synchroniser maintenant") { Task { await model.syncNow() } }.disabled(s.syncPaused)82            }83            Section("Bande passante") {84                Picker("Envoi", selection: Binding(get: { s.uploadLimitKB }, set: { s.uploadLimitKB = $0; Task { await model.applyTransferSettings() } })) { limits }85                Picker("Réception", selection: Binding(get: { s.downloadLimitKB }, set: { s.downloadLimitKB = $0; Task { await model.applyTransferSettings() } })) { limits }86            }87            Section("Énergie") {88                Toggle("Ménager la batterie", isOn: Binding(get: { s.respectPower }, set: { s.respectPower = $0; Task { await model.applyTransferSettings() } }))89                Text("En mode Économie d’énergie, ou sous 10 % de batterie, seuls les transferts que vous demandez passent, un à la fois ; le reste attend. Sous 20 %, deux transferts au plus.").font(.caption).foregroundStyle(.secondary)90                if model.power.lowPowerMode || model.power.onBattery {91                    LabeledContent("Maintenant", value: model.power.lowPowerMode ? "Mode Économie d’énergie" : "Sur batterie\(model.power.level.map { " · \(Int($0 * 100)) %" } ?? "")")92                }93            }94            Section("Transferts simultanés") {95                Picker("Nombre", selection: Binding(get: { s.parallelTransfers }, set: { s.parallelTransfers = $0; Task { await model.applyTransferSettings() } })) {96                    Text("Automatique (selon le débit mesuré)").tag(0)97                    ForEach([1, 2, 3, 4, 6, 8], id: \.self) { Text("\($0)").tag($0) }98                }99                Text("En automatique, SP Drive ajoute des transferts (jusqu’à 6) tant que le débit total augmente, en retire quand les échecs se répètent, et se limite sur un partage de connexion ou en mode Données réduites.").font(.caption).foregroundStyle(.secondary)100                LabeledContent("En ce moment", value: "\(model.policy.concurrency) simultané\(model.policy.concurrency > 1 ? "s" : "") · \(SyncStatusText.channel(model.status).lowercased())")101            }102        }.formStyle(.grouped)103    }104    @ViewBuilder private var limits: some View {105        Text("Sans limite").tag(0)106        ForEach([256, 512, 1024, 2048, 5120, 10240, 51200], id: \.self) { kb in Text(kb < 1024 ? "\(kb) Ko/s" : "\(kb / 1024) Mo/s").tag(kb) }107    }108}109110private struct NotificationSettings: View {111    @Environment(AppModel.self) private var model112    var body: some View {113        @Bindable var s = model.settings114        Form {115            Section {116                Toggle("Transferts terminés (une notification par lot)", isOn: $s.notifyTransfers)117                Toggle("Conflits à régler", isOn: $s.notifyConflicts)118                Toggle("Nouveaux dépôts reçus", isOn: $s.notifyDeposits)119            } footer: { Text("Les erreurs de synchronisation persistantes et le manque d’espace sont toujours signalés. Le style et le son se règlent dans Réglages Système › Notifications.") }120        }.formStyle(.grouped)121    }122}123124private struct AccountSettings: View {125    @Environment(AppModel.self) private var model126    @State private var sessions: [DeviceSession] = []127    @State private var confirmSignOut = false128    @State private var error: String?129    var body: some View {130        @Bindable var s = model.settings131        Form {132            Section("Compte") {133                LabeledContent("Nom", value: model.account?.displayName ?? "—")134                LabeledContent("Courriel", value: model.account?.email ?? "—")135                LabeledContent("Ce Mac", value: AppEnvironment.deviceName)136            }137            Section("Sécurité") {138                Toggle("Verrouiller l’application avec Touch ID", isOn: $s.biometricLock)139                Text("Le jeton de session de ce Mac est gardé dans le trousseau. Le verrou demande Touch ID (ou le mot de passe du Mac) à l’ouverture et après une absence.").font(.caption).foregroundStyle(.secondary)140            }141            if model.meta.api >= 2 { AIConsentSection(model: model); DevicesSection(model: model) } else {142            Section("Appareils connectés") {143                if sessions.isEmpty { Text(error ?? "Chargement…").foregroundStyle(.secondary) }144                ForEach(sessions) { d in145                    HStack {146                        Image(systemName: d.kind == "device" ? "laptopcomputer" : "globe").foregroundStyle(.secondary)147                        VStack(alignment: .leading) {148                            Text((d.deviceName?.isEmpty == false ? d.deviceName! : (d.kind == "device" ? "Application" : "Navigateur")) + (d.current ? " — cet appareil" : "")).lineLimit(1)149                            Text("\(d.ip) · vu \(Fmt.relative(d.lastSeenAt))").font(.caption).foregroundStyle(.secondary)150                        }151                        Spacer()152                        if !d.current { Button("Révoquer") { Task { try? await model.api?.revokeSession(d.id); await load() } }.controlSize(.small) }153                    }154                }155            } }156            Section {157                Button("Se déconnecter de ce Mac…", role: .destructive) { confirmSignOut = true }158            }159        }160        .formStyle(.grouped)161        .task { await load() }162        .confirmationDialog("Se déconnecter de SP Drive ?", isPresented: $confirmSignOut) {163            Button("Se déconnecter", role: .destructive) { Task { await model.signOut() } }164            Button("Annuler", role: .cancel) {}165        } message: {166            Text(model.unsyncedCount > 0 ? "Attention : \(model.unsyncedCount) modification(s) de ce Mac ne sont pas encore envoyées au serveur. Les opérations en attente de l’application seront perdues ; les fichiers modifiés dans le Finder et non envoyés seront conservés dans un dossier à part." : "La session de ce Mac sera révoquée et l’emplacement SP Drive retiré du Finder. Vos fichiers restent sur SP Drive.")167        }168    }169    private func load() async {170        do { sessions = try await model.api?.sessions() ?? []; error = nil } catch { self.error = DriveError.wrap(error).errorDescription }171    }172}173174/// The account's own consent to external AI providers. Off by default; the local provider needs none.175struct AIConsentSection: View {176    let model: AppModel177    @State private var providers: AIProviders?178    @State private var error: String?179    var body: some View {180        Section("SP Drive AI") {181            if let p = providers {182                let local = p.providers.filter { $0.local && $0.configured }, external = p.providers.filter { !$0.local && $0.configured }183                LabeledContent("Modèle local", value: local.isEmpty ? "aucun configuré sur ce serveur" : local.flatMap { $0.models.map(\.label) }.joined(separator: ", "))184                Toggle("Autoriser les fournisseurs externes pour mon compte", isOn: Binding(get: { p.external?.account ?? false }, set: { on in Task { await set(on) } }))185                    .accessibilityIdentifier("ai-external-toggle")186                Text(p.external?.server == true187                     ? (external.isEmpty ? "Le serveur autorise les fournisseurs externes, mais aucun n’est configuré." : "Fournisseurs externes configurés : \(external.map(\.label).joined(separator: ", ")). Activé, des passages de vos documents leur sont envoyés à chaque question que vous posez avec l’un de leurs modèles.")188                     : "L’administrateur de ce serveur n’a pas activé les fournisseurs externes : ce réglage est sans effet tant que c’est le cas. Avec le modèle local, rien ne quitte l’infrastructure MacLustr.")189                    .font(.caption).foregroundStyle(.secondary)190            } else { Text(error ?? "Chargement…").foregroundStyle(.secondary) }191        }192        .task { await load() }193    }194    private func load() async { do { providers = try await model.next?.aiProviders(); error = nil } catch { self.error = NextText.error(error) } }195    private func set(_ on: Bool) async { do { try await model.next?.setExternalAI(on) } catch { self.error = NextText.error(error) }; await load() }196}197
Files main
Menu

Theme