SPB Git

Repository Public

SettingsView.swift 22.0 KB 407 lines swift

1import AIAssistant2import DesignSystem3import SettingsModel4import SwiftUI5import TerminalCore67struct SettingsView: View {8    @Bindable var model: AppModel910    var body: some View {11        TabView {12            GeneralSettings(model: model).tabItem { Label("General", systemImage: "gearshape") }13            AppearanceSettings(model: model).tabItem { Label("Appearance", systemImage: "paintpalette") }14            ShellSettings(model: model).tabItem { Label("Shell", systemImage: "terminal") }15            SafetySettings(model: model).tabItem { Label("Safety & Privacy", systemImage: "lock.shield") }16            ShortcutSettings(model: model).tabItem { Label("Shortcuts", systemImage: "keyboard") }17            IntelligenceSettings(model: model).tabItem { Label("Intelligence", systemImage: "sparkles") }18        }19        .frame(width: 640, height: 520)20    }21}2223private struct GeneralSettings: View {24    @Bindable var model: AppModel25    @State private var notificationNote = ""2627    var body: some View {28        Form {29            Section("Windows") {30                Picker("New windows open on", selection: $model.settings.newWindowScreen) {31                    Text("The display of the active window").tag(NewWindowScreen.active)32                    Text("The main display").tag(NewWindowScreen.main)33                    Text("The display under the pointer").tag(NewWindowScreen.pointer)34                }35                Toggle("Restore windows, tabs and panes at launch", isOn: $model.settings.restoreWorkspaceOnLaunch)36                Text("Layout, titles and directories are restored; processes are always started fresh. For sessions that survive a restart, use tmux or zellij (Command Palette).")37                    .font(.caption).foregroundStyle(.secondary)38                Toggle("Show sidebar in new windows", isOn: $model.settings.showSidebar)39                Toggle("Show status bar", isOn: $model.settings.showStatusBar)40                Toggle("Show pane headers", isOn: $model.settings.showPaneHeaders)41            }42            Section("Quick Terminal") {43                Toggle("Enable the global shortcut", isOn: $model.settings.quickTerminalEnabled)44                LabeledContent("Shortcut") {45                    ChordField(chord: Binding(get: { model.settings.quickTerminalShortcut }, set: { model.settings.quickTerminalShortcut = $0 }))46                }47                Slider(value: $model.settings.quickTerminalHeightFraction, in: 0.2...1) { Text("Height") }48                Text("The shortcut works from any application. It uses the system hot-key service and needs no Accessibility permission.")49                    .font(.caption).foregroundStyle(.secondary)50            }51            Section("Notifications") {52                Toggle("Notify when a long command finishes or an SSH session ends", isOn: Binding(53                    get: { model.settings.notifyOnLongCommand },54                    set: { enabled in55                        model.settings.notifyOnLongCommand = enabled56                        guard enabled else { return }57                        Task {58                            let granted = await Notifier.shared.requestAuthorization()59                            notificationNote = granted ? "" : "macOS did not grant permission; enable SP Term in System Settings › Notifications."60                        }61                    }))62                Stepper("Long means at least \(model.settings.longCommandSeconds) s", value: $model.settings.longCommandSeconds, in: 5...3600, step: 5)63                Text("Only while SP Term is in the background. Notifications contain the program name and duration, never terminal output.")64                    .font(.caption).foregroundStyle(.secondary)65                if !notificationNote.isEmpty { Text(notificationNote).font(.caption).foregroundStyle(.orange) }66            }67        }68        .formStyle(.grouped)69    }70}7172private struct AppearanceSettings: View {73    @Bindable var model: AppModel74    @State private var fonts: [String] = ["SF Mono"]7576    var body: some View {77        Form {78            Section("Theme") {79                Picker("Appearance", selection: $model.settings.appearance) {80                    Text("Follow system").tag(AppearanceMode.system)81                    Text("Dark").tag(AppearanceMode.dark)82                    Text("Light").tag(AppearanceMode.light)83                }84                Picker("Dark theme", selection: $model.settings.darkThemeID) {85                    ForEach(ThemeCatalog.all.filter(\.isDark)) { Text($0.name).tag($0.id) }86                }87                Picker("Light theme", selection: $model.settings.lightThemeID) {88                    ForEach(ThemeCatalog.all.filter { !$0.isDark }) { Text($0.name).tag($0.id) }89                }90                Text("When “Increase contrast” is on in System Settings › Accessibility, the high-contrast theme is used automatically.")91                    .font(.caption).foregroundStyle(.secondary)92                HStack {93                    Text("Accent")94                    Spacer()95                    ForEach(["#4C8DFF", "#5CC8FF", "#8B6CFF", "#2FBF71", "#F2994A", "#F0707A"], id: \.self) { hex in96                        let color = SPColor(hex: hex)!97                        Circle().fill(Color(color)).frame(width: 18, height: 18)98                            .overlay(Circle().strokeBorder(Color.primary, lineWidth: model.settings.accentOverride == color ? 2 : 0))99                            .onTapGesture { model.settings.accentOverride = color }100                            .accessibilityLabel("Accent \(hex)")101                    }102                    Button("Theme default") { model.settings.accentOverride = nil }.controlSize(.small)103                }104            }105            Section("Chrome") {106                Picker("Surface", selection: $model.settings.chromeMaterial) {107                    Text("Translucent material").tag(ChromeMaterial.translucent)108                    Text("Solid").tag(ChromeMaterial.solid)109                }110                Toggle("Liquid Glass for floating surfaces", isOn: $model.settings.useLiquidGlass)111                    .disabled(!AppModel.systemHasLiquidGlass)112                if !AppModel.systemHasLiquidGlass {113                    Text("Liquid Glass needs macOS 26 or later; this Mac uses standard materials.").font(.caption).foregroundStyle(.secondary)114                }115                Picker("Title bar", selection: $model.settings.density) {116                    Text("Compact").tag(ChromeDensity.compact)117                    Text("Expanded").tag(ChromeDensity.expanded)118                }119                Toggle("Dynamic accent: one colour per SSH host", isOn: $model.settings.dynamicAccent)120                Toggle("Ambient accent light", isOn: $model.settings.ambientGradient)121                Text("Translucency applies to the chrome only. The terminal text surface stays opaque unless you lower the window opacity below.")122                    .font(.caption).foregroundStyle(.secondary)123            }124            Section("Motion") {125                Picker("Animations", selection: $model.settings.motion) {126                    Text("Follow system (Reduce Motion)").tag(MotionPreference.system)127                    Text("Always reduced").tag(MotionPreference.reduced)128                }129                Toggle("Signal when a command ends", isOn: $model.settings.completionFeedback)130                Text("Terminal output is never animated. With reduced motion, movement is replaced by short fades.")131                    .font(.caption).foregroundStyle(.secondary)132            }133            Section("Toolbar") {134                ForEach(AppAction.toolbarCandidates) { action in135                    Toggle(isOn: Binding(get: { model.settings.toolbarItems.contains(action.rawValue) },136                                         set: { model.setToolbar(action, shown: $0) })) {137                        Label(action.title.replacingOccurrences(of: "…", with: ""), systemImage: action.symbol)138                    }139                }140                Button("Reset Toolbar") { model.settings.toolbarItems = AppSettings.defaultToolbarItems }.controlSize(.small)141            }142            Section("Text") {143                Picker("Font", selection: $model.settings.fontName) {144                    ForEach(fonts, id: \.self) { Text($0).tag($0) }145                }146                HStack {147                    Slider(value: $model.settings.fontSize, in: Metrics.minimumFontSize...Metrics.maximumFontSize, step: 1) { Text("Size") }148                    Text("\(Int(model.settings.fontSize)) pt").monospacedDigit().frame(width: 44)149                }150                Text("Ligatures follow the font: choose a font with programming ligatures to get them. Line spacing is fixed by the rendering engine.")151                    .font(.caption).foregroundStyle(.secondary)152                Picker("Cursor", selection: $model.settings.cursorShape) {153                    Text("Block").tag(CursorShape.block)154                    Text("Underline").tag(CursorShape.underline)155                    Text("Bar").tag(CursorShape.bar)156                }157                Toggle("Blinking cursor", isOn: $model.settings.cursorBlink)158            }159            Section("Window") {160                HStack {161                    Slider(value: $model.settings.backgroundOpacity, in: 0.3...1) { Text("Opacity") }162                    Text("\(Int(model.settings.backgroundOpacity * 100))%").monospacedDigit().frame(width: 44)163                }164                Toggle("Blur what is behind translucent windows", isOn: $model.settings.backgroundBlur)165                Toggle("Use the Metal renderer (experimental)", isOn: $model.settings.useMetalRenderer)166                Text("The default CoreGraphics renderer is the measured, supported path. See BENCHMARKS.md before enabling Metal.")167                    .font(.caption).foregroundStyle(.secondary)168            }169        }170        .formStyle(.grouped)171        .task { fonts = TerminalSession.monospacedFontFamilies() }172    }173}174175private struct ShellSettings: View {176    @Bindable var model: AppModel177    @State private var shells: [ShellInfo] = []178179    var body: some View {180        Form {181            Section("Shell") {182                Picker("Shell for new sessions", selection: Binding(get: { model.settings.shellPath ?? "" }, set: { model.settings.shellPath = $0.isEmpty ? nil : $0 })) {183                    Text("Account default (\(ShellCatalog.defaultShell()))").tag("")184                    ForEach(shells) { Text("\($0.name) — \($0.path)").tag($0.path) }185                }186                Toggle("Start as a login shell", isOn: $model.settings.loginShell)187                TextField("Start in directory (empty = home)", text: Binding(get: { model.settings.startupDirectory ?? "" },188                                                                             set: { model.settings.startupDirectory = $0.isEmpty ? nil : $0 }))189                Toggle("New tabs and splits start in the current directory", isOn: $model.settings.newPaneInheritsDirectory)190                TextField("Command to run in new local shells (optional)", text: $model.settings.startupCommand)191            }192            Section("Terminal") {193                Stepper("Scrollback: \(model.settings.scrollbackLines) lines", value: $model.settings.scrollbackLines, in: 0...1_000_000, step: 5000)194                Toggle("Option key acts as Meta", isOn: $model.settings.optionAsMeta)195                Toggle("Let programs use the mouse", isOn: $model.settings.mouseReporting)196                Picker("Bell", selection: $model.settings.bell) {197                    Text("Off").tag(BellMode.off)198                    Text("Sound").tag(BellMode.sound)199                    Text("Visual").tag(BellMode.visual)200                    Text("Both").tag(BellMode.both)201                }202            }203        }204        .formStyle(.grouped)205        .task { shells = ShellCatalog.installedShells() }206    }207}208209private struct SafetySettings: View {210    @Bindable var model: AppModel211212    var body: some View {213        Form {214            Section("Paste") {215                Picker("Ask before pasting", selection: $model.settings.pasteConfirmation) {216                    Text("Never").tag(PasteConfirmation.never)217                    Text("Several lines").tag(PasteConfirmation.multiline)218                    Text("Always").tag(PasteConfirmation.always)219                }220                Text("Text containing terminal control sequences always asks, whatever this setting.").font(.caption).foregroundStyle(.secondary)221            }222            Section("Clipboard access by programs (OSC 52)") {223                Picker("Programs may write the clipboard", selection: $model.settings.clipboardWrite) {224                    Text("Never").tag(ClipboardAccess.deny)225                    Text("Ask each time").tag(ClipboardAccess.ask)226                    Text("Always").tag(ClipboardAccess.allow)227                }228                Picker("Programs may read the clipboard", selection: Binding(229                    get: { model.settings.clipboardRead == .allow },230                    set: { model.settings.clipboardRead = $0 ? .allow : .deny })) {231                    Text("Never").tag(false)232                    Text("Always").tag(true)233                }234                Text("Reading lets any program in a session, including on remote hosts, see what you copied. Keep it off unless you need it.")235                    .font(.caption).foregroundStyle(.secondary)236            }237            Section("Closing") {238                Toggle("Confirm before closing a session that is running something", isOn: $model.settings.confirmCloseRunning)239                Toggle("Confirm before quitting with running sessions", isOn: $model.settings.confirmQuitRunning)240            }241            Section("Privacy") {242                Toggle("Private mode", isOn: $model.settings.privateMode)243                Text("While on: the window layout is not saved, the command history is not written and no notification is posted. The saved layout is deleted when private mode is turned on.")244                    .font(.caption).foregroundStyle(.secondary)245                Toggle("Keep a history of commands run from snippets and the assistant", isOn: $model.settings.recordHistory)246                Text("Off by default. Terminal output and what you type at the prompt are never recorded. Secrets are masked before writing. File: \(Formatters.abbreviate(path: model.stores.locations.history.path))")247                    .font(.caption).foregroundStyle(.secondary)248                Button("Delete Saved Layout and History") {249                    model.stores.lastSession.delete()250                    model.stores.history.clear()251                }252            }253        }254        .formStyle(.grouped)255    }256}257258/// Editable text form of a shortcut ("cmd+shift+p").259struct ChordField: View {260    @Binding var chord: KeyChord261    @State private var text = ""262    @State private var invalid = false263264    var body: some View {265        HStack(spacing: 6) {266            TextField("cmd+shift+p", text: $text)267                .textFieldStyle(.roundedBorder).frame(width: 150)268                .onSubmit { commit() }269            Text(chord.symbolic).font(.system(size: 12, design: .rounded)).foregroundStyle(.secondary)270            if invalid { Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange).help("Not a valid shortcut") }271        }272        .onAppear { text = chord.description }273    }274275    private func commit() {276        if let parsed = KeyChord(text) { chord = parsed; invalid = false; text = parsed.description } else { invalid = true }277    }278}279280private struct ShortcutSettings: View {281    @Bindable var model: AppModel282    @State private var drafts: [String: String] = [:]283    @State private var message = ""284285    var body: some View {286        VStack(alignment: .leading, spacing: 6) {287            Text("Type a shortcut such as cmd+shift+p or ctrl+opt+left, then press Return. Changes apply immediately to the menus.")288                .font(.caption).foregroundStyle(.secondary)289            if !message.isEmpty { Text(message).font(.caption).foregroundStyle(.orange) }290            List {291                ForEach(AppAction.Category.allCases, id: \.self) { category in292                    Section(category.rawValue) {293                        ForEach(AppAction.allCases.filter { $0.category == category }) { action in294                            HStack {295                                Text(action.title)296                                Spacer()297                                Text(action.chord(in: model.settings)?.symbolic ?? "—").font(.system(size: 12, design: .rounded)).foregroundStyle(.secondary).frame(width: 70, alignment: .trailing)298                                TextField("none", text: Binding(get: { drafts[action.rawValue] ?? action.chord(in: model.settings)?.description ?? "" },299                                                                 set: { drafts[action.rawValue] = $0 }))300                                    .textFieldStyle(.roundedBorder).frame(width: 150)301                                    .onSubmit { apply(action) }302                                Button("Reset") {303                                    model.settings.keyBindings[action.rawValue] = nil304                                    drafts[action.rawValue] = nil305                                }306                                .controlSize(.small).disabled(model.settings.keyBindings[action.rawValue] == nil)307                            }308                        }309                    }310                }311            }312        }313        .padding(12)314    }315316    private func apply(_ action: AppAction) {317        let text = (drafts[action.rawValue] ?? "").trimmingCharacters(in: .whitespaces)318        guard let chord = KeyChord(text) else {319            message = "“\(text)” is not a valid shortcut."320            return321        }322        if let conflict = AppAction.allCases.first(where: { $0 != action && $0.chord(in: model.settings) == chord }) {323            message = "\(chord.symbolic) is already used by “\(conflict.title)”."324            return325        }326        message = ""327        model.settings.keyBindings[action.rawValue] = chord328        drafts[action.rawValue] = nil329    }330}331332private struct IntelligenceSettings: View {333    @Bindable var model: AppModel334    @State private var keyDrafts: [String: String] = [:]335    @State private var note = ""336337    var body: some View {338        Form {339            Section {340                Toggle("Enable SP Intelligence", isOn: $model.settings.assistantEnabled)341                Toggle("Local only: refuse any destination that is not this Mac", isOn: $model.settings.assistantLocalOnly)342                Text("Requests are only made when you press Send under a preview of the exact payload. Secrets are masked in that payload. API keys are stored in the macOS Keychain, never in files or logs.")343                    .font(.caption).foregroundStyle(.secondary)344            }345            ForEach($model.providers) { $provider in346                Section(provider.label.isEmpty ? provider.kind.displayName : provider.label) {347                    TextField("Label", text: $provider.label)348                    TextField("Base URL", text: Binding(get: { provider.baseURL.absoluteString },349                                                        set: { if let url = URL(string: $0), url.scheme != nil { provider.baseURL = url } }))350                    TextField("Model", text: $provider.model)351                    if !provider.kind.suggestedModels.isEmpty {352                        Picker("Suggested models", selection: $provider.model) {353                            ForEach(provider.kind.suggestedModels, id: \.self) { Text($0).tag($0) }354                            if !provider.kind.suggestedModels.contains(provider.model) { Text(provider.model.isEmpty ? "—" : provider.model).tag(provider.model) }355                        }356                    }357                    HStack {358                        SecureField(provider.kind.requiresAPIKey ? "API key" : "API key (optional for local servers)", text: Binding(359                            get: { keyDrafts[provider.id] ?? "" }, set: { keyDrafts[provider.id] = $0 }))360                        Button("Save Key") { saveKey(provider.id) }.disabled((keyDrafts[provider.id] ?? "").isEmpty)361                    }362                    HStack {363                        let stored = (try? model.environment.secrets.hasSecret(for: provider.id)) ?? false364                        Label(stored ? "A key is stored in the Keychain" : "No key stored", systemImage: stored ? "key.fill" : "key")365                            .font(.caption).foregroundStyle(stored ? .green : .secondary)366                        Spacer()367                        Button("Use This Provider") { model.settings.assistantActiveProviderID = provider.id }368                            .disabled(model.activeProvider?.id == provider.id)369                        Button("Remove", role: .destructive) {370                            try? model.environment.secrets.deleteSecret(for: provider.id)371                            model.providers.removeAll { $0.id == provider.id }372                            model.saveProviders()373                        }374                    }375                }376            }377            Section {378                HStack {379                    Button("Add Anthropic") { add(.anthropic) }380                    Button("Add OpenAI") { add(.openAI) }381                    Button("Add Local / OpenAI-compatible") { add(.openAICompatible) }382                }383                if !note.isEmpty { Text(note).font(.caption).foregroundStyle(.orange) }384            }385        }386        .formStyle(.grouped)387        .onChange(of: model.providers) { _, _ in model.saveProviders() }388    }389390    private func add(_ kind: AIProviderKind) {391        let provider = AIProviderConfig(kind: kind)392        model.providers.append(provider)393        if model.settings.assistantActiveProviderID == nil { model.settings.assistantActiveProviderID = provider.id }394    }395396    private func saveKey(_ id: String) {397        guard let draft = keyDrafts[id], !draft.isEmpty else { return }398        do {399            try model.environment.secrets.setSecret(SecretValue(draft), for: id)400            note = ""401        } catch {402            note = "The Keychain refused to store the key."403        }404        keyDrafts[id] = nil405    }406}407
Files main
Menu

Theme