SPB Git

Repository Public

SettingsView.swift 37.9 KB 633 lines swift

1import SwiftUI23enum SettingsSection: String, CaseIterable, Identifiable {4    case general, account, appearance, search, privacy, blocker, profiles, shortcuts, intelligence, scripts, advanced5    var id: String { rawValue }67    var title: String {8        switch self {9        case .general: return L("General")10        case .account: return L("Account & Sync")11        case .appearance: return L("Appearance")12        case .search: return L("Search Engine")13        case .privacy: return L("Privacy & Security")14        case .blocker: return L("Content Blocker")15        case .profiles: return L("Profiles")16        case .shortcuts: return L("Keyboard")17        case .intelligence: return L("Intelligence")18        case .scripts: return L("User Scripts")19        case .advanced: return L("Advanced")20        }21    }2223    var symbol: String {24        switch self {25        case .general: return "gearshape"26        case .account: return "person.crop.circle"27        case .appearance: return "paintbrush"28        case .search: return "magnifyingglass"29        case .privacy: return "hand.raised"30        case .blocker: return "shield.lefthalf.filled"31        case .profiles: return "person.2"32        case .shortcuts: return "keyboard"33        case .intelligence: return "sparkles"34        case .scripts: return "curlybraces"35        case .advanced: return "wrench.and.screwdriver"36        }37    }38}3940struct SettingsView: View {41    @Bindable var environment: AppEnvironment42    private var section: SettingsSection { environment.settingsSection }4344    var body: some View {45        NavigationSplitView {46            List(SettingsSection.allCases, selection: Binding(get: { environment.settingsSection }, set: { environment.settingsSection = $0 ?? .general })) { item in47                Label(item.title, systemImage: item.symbol).tag(item)48            }49            .navigationSplitViewColumnWidth(240)50        } detail: {51            Group {52                switch section {53                case .general: GeneralSettings(environment: environment)54                case .account: AccountView(services: environment.services, syncEnabled: $environment.settings.syncEnabled)55                case .appearance: AppearanceSettings(environment: environment)56                case .search: SearchSettings(environment: environment)57                case .privacy: PrivacySettings(environment: environment)58                case .blocker: BlockerSettings(environment: environment)59                case .profiles: ProfileSettings(environment: environment)60                case .shortcuts: ShortcutSettings(environment: environment)61                case .intelligence: IntelligenceSettings(environment: environment)62                case .scripts: ScriptSettings(environment: environment)63                case .advanced: AdvancedSettings(environment: environment)64                }65            }66            .navigationTitle(section.title)67        }68    }69}7071private struct Note: View {72    let text: String73    init(_ text: String) { self.text = text }74    var body: some View { Text(text).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }75}7677struct GeneralSettings: View {78    @Bindable var environment: AppEnvironment79    var body: some View {80        Form {81            Section(L("Startup")) {82                Toggle(L("Restore windows and tabs from the last session"), isOn: $environment.settings.restoreSessionOnLaunch)83                Picker(L("New tabs open with"), selection: $environment.settings.newTabContent) {84                    Text(L("Start page")).tag(NewTabContent.startPage)85                    Text(L("Homepage")).tag(NewTabContent.homepage)86                }87                TextField(L("Homepage"), text: $environment.settings.homepage, prompt: Text("https://example.com"))88            }89            Section(L("Tabs")) {90                Picker(L("Unload background tabs after"), selection: $environment.settings.suspendTabsAfterMinutes) {91                    Text(L("Never")).tag(0)92                    Text(L("10 minutes")).tag(10)93                    Text(L("30 minutes")).tag(30)94                    Text(L("1 hour")).tag(60)95                    Text(L("4 hours")).tag(240)96                }97                Note(L("Unloaded tabs keep their place, title and back/forward list, and reload when you return to them. Pinned tabs are never unloaded."))98                Toggle(L("Ask before closing a window with several tabs"), isOn: $environment.settings.confirmBeforeClosingManyTabs)99            }100            Section(L("Downloads")) {101                Toggle(L("Ask where to save each file"), isOn: $environment.settings.askWhereToSaveDownloads)102                Note(L("Otherwise files go to your Downloads folder under a safe, unique name."))103            }104        }105        .formStyle(.grouped)106    }107}108109struct AppearanceSettings: View {110    @Bindable var environment: AppEnvironment111    var body: some View {112        Form {113            Section(L("Theme")) {114                Picker(L("Appearance"), selection: $environment.settings.appearance) {115                    Text(L("Match system")).tag(AppearanceMode.system)116                    Text(L("Light")).tag(AppearanceMode.light)117                    Text(L("Dark")).tag(AppearanceMode.dark)118                }119                .pickerStyle(.segmented)120            }121            Section(L("Layout")) {122                Picker(L("Tabs"), selection: $environment.settings.tabLayout) {123                    Text(L("Horizontal, under the toolbar")).tag(TabLayout.horizontal)124                    Text(L("Vertical, in the sidebar")).tag(TabLayout.vertical)125                }126                Toggle(L("Show the sidebar in new windows"), isOn: $environment.settings.sidebarVisible)127                Toggle(L("Always show the full address"), isOn: $environment.settings.showFullURL)128                Note(L("When off, the address bar emphasises the site's real domain, which makes look-alike addresses easier to notice."))129            }130            Section(L("Ambient theme")) {131                HStack(spacing: 14) {132                    ForEach(AmbientTheme.allCases) { theme in133                        Button { environment.settings.startPage.ambient = theme } label: { AmbientThemeSwatch(theme: theme, isSelected: environment.settings.startPage.ambient == theme) }134                            .buttonStyle(AuraPressStyle(scale: 0.95)).help(theme.summary)135                    }136                }137                Toggle(L("Animate the background"), isOn: $environment.settings.ambientMotionEnabled)138                Note(L("Motion always stops with Reduce Motion, in Low Power Mode and when the window is in the background."))139            }140            Section(L("Reading and focus")) {141                Toggle(L("Focus Trail: show reading progress"), isOn: $environment.settings.focusTrailEnabled)142                Toggle(L("Hide browser notices in Focus Mode"), isOn: $environment.settings.focusHidesDistractions)143                Note(L("Focus Mode never changes a page: it only hides SP Browser's own bars, badges and confirmations. Errors are still shown."))144            }145            Section(L("Links and path")) {146                Toggle(L("Peek at a link when the pointer rests on it"), isOn: $environment.settings.peekOnHover)147                Note(L("Holding ⌥ over a link, or ⌥⌘P, always shows the preview. A preview is fetched without cookies and without running the page's scripts; the site still sees one request from your address."))148                Toggle(L("Record my path (Flow)"), isOn: $environment.settings.flowEnabled)149                Note(L("Flow remembers which page led to which, on this Mac only. It is never recorded to disk in private windows and is cleared with the history."))150            }151            Section(L("Start page")) {152                Toggle(L("Greeting"), isOn: $environment.settings.startPage.showGreeting)153                Toggle(L("Workspaces"), isOn: $environment.settings.startPage.showWorkspaces)154                Toggle(L("Recent sessions"), isOn: $environment.settings.startPage.showRecentSessions)155                Toggle(L("Search field"), isOn: $environment.settings.startPage.showSearch)156                Toggle(L("Favorites"), isOn: $environment.settings.startPage.showSyncedFavorites)157                Toggle(L("Workspace favorites"), isOn: $environment.settings.startPage.showFavorites)158                Toggle(L("Frequently visited"), isOn: $environment.settings.startPage.showTopSites)159                Toggle(L("Recently visited"), isOn: $environment.settings.startPage.showRecentlyVisited)160                Toggle(L("Recent searches"), isOn: $environment.settings.startPage.showRecentSearches)161                Toggle(L("Continue from another device"), isOn: $environment.settings.startPage.showOtherDevices)162                Toggle(L("Bookmarks"), isOn: $environment.settings.startPage.showBookmarks)163                Toggle(L("Reading list"), isOn: $environment.settings.startPage.showReadingList)164                Toggle(L("Recently closed tabs"), isOn: $environment.settings.startPage.showRecentlyClosed)165                Toggle(L("Privacy dashboard"), isOn: $environment.settings.startPage.showPrivacyDashboard)166                Toggle(L("Privacy note"), isOn: $environment.settings.startPage.showPrivacyNote)167            }168        }169        .formStyle(.grouped)170    }171}172173struct SearchSettings: View {174    @Bindable var environment: AppEnvironment175    @State private var draft = SearchEngine(id: "", name: "", template: "", shortcut: "")176177    var body: some View {178        Form {179            Section(L("Default search engine")) {180                Picker(L("Search with"), selection: $environment.settings.searchEngineID) {181                    ForEach(environment.settings.allSearchEngines()) { Text($0.name).tag($0.id) }182                }183                Toggle(L("Suggest pages from history"), isOn: $environment.settings.suggestFromHistory)184                Toggle(L("Suggest bookmarks"), isOn: $environment.settings.suggestFromBookmarks)185                Note(L("Suggestions come only from this Mac. What you type is not sent to the search engine until you press Return."))186            }187            if environment.settings.activeSearchEngine().isNative { SPSearchPreferencesSection(services: environment.services) }188            Section(L("Search shortcuts")) {189                ForEach(environment.settings.allSearchEngines()) { engine in190                    HStack {191                        Text(engine.shortcut).font(.system(.callout, design: .monospaced)).frame(width: 44, alignment: .leading)192                        Text(engine.name)193                        Spacer()194                        if environment.settings.customSearchEngines.contains(where: { $0.id == engine.id }) {195                            Button(L("Remove")) {196                                environment.settings.customSearchEngines.removeAll { $0.id == engine.id }197                                if environment.settings.searchEngineID == engine.id { environment.settings.searchEngineID = SearchEngine.fallback.id }198                            }199                            .controlSize(.small)200                        }201                    }202                }203                Note(L("Type the shortcut, a space, then your query — for example “w Montréal” searches Wikipedia."))204            }205            Section(L("Add a search engine")) {206                TextField(L("Name"), text: $draft.name)207                TextField(L("Address with %s for the query"), text: $draft.template, prompt: Text("https://example.com/search?q=%s"))208                TextField(L("Shortcut"), text: $draft.shortcut)209                Button(L("Add")) {210                    var engine = draft211                    engine.id = "custom-" + UUID().uuidString212                    engine.shortcut = engine.shortcut.lowercased().trimmingCharacters(in: .whitespaces)213                    environment.settings.customSearchEngines.append(engine)214                    draft = SearchEngine(id: "", name: "", template: "", shortcut: "")215                }216                .disabled(!draft.isValid || draft.shortcut.trimmingCharacters(in: .whitespaces).isEmpty217                          || environment.settings.allSearchEngines().contains { $0.shortcut == draft.shortcut.lowercased() })218            }219        }220        .formStyle(.grouped)221    }222}223224struct PrivacySettings: View {225    @Bindable var environment: AppEnvironment226    @State private var confirmReset = false227228    var body: some View {229        Form {230            Section(L("Protection")) {231                Toggle(L("Upgrade known sites to HTTPS"), isOn: $environment.settings.upgradeToHTTPS)232                Toggle(L("Block pop-up windows not opened by a click"), isOn: $environment.settings.blockPopups)233                Toggle(L("Warn before following links with misleading addresses"), isOn: $environment.settings.warnOnDeceptiveURLs)234                Note(L("These checks reduce risk; they cannot detect every fraudulent site. WebKit's own fraudulent-site warning also stays on. The HTTPS setting applies to tabs opened afterwards."))235            }236            Section(L("What SP Browser never does")) {237                Label(L("No telemetry, analytics or crash reports are sent."), systemImage: "checkmark.shield")238                Label(L("No account, no sync: your data stays on this Mac."), systemImage: "checkmark.shield")239                Label(L("No script is injected into pages unless you add one yourself."), systemImage: "checkmark.shield")240                Label(L("TLS certificate errors cannot be bypassed."), systemImage: "checkmark.shield")241            }242            Section(L("Site permissions")) {243                let sites = environment.defaultContext.permissions.allSites.count244                LabeledContent(L("Sites with saved choices"), value: "\(sites)")245                Button(L("Reset All Site Permissions…"), role: .destructive) { confirmReset = true }.disabled(sites == 0)246                Note(L("Camera and microphone are asked per site. Location, web notifications and clipboard reads cannot be controlled per site with WebKit's public API on macOS; SP Browser does not pretend otherwise."))247            }248        }249        .formStyle(.grouped)250        .confirmationDialog(L("Reset all site permissions?"), isPresented: $confirmReset) {251            Button(L("Reset"), role: .destructive) { environment.defaultContext.permissions.resetAll() }252        } message: { Text(L("Every site will ask again for camera and microphone, and zoom levels return to 100 %.")) }253    }254}255256struct BlockerSettings: View {257    @Bindable var environment: AppEnvironment258    @State private var customURL = ""259    @State private var updating: UUID?260    @State private var message: String?261262    var body: some View {263        Form {264            Section {265                Toggle(L("Block trackers and ads"), isOn: $environment.settings.contentBlockerEnabled)266                Toggle(L("Tracking and analytics servers"), isOn: $environment.settings.blockTrackers).disabled(!environment.settings.contentBlockerEnabled)267                Toggle(L("Advertising servers"), isOn: $environment.settings.blockAds).disabled(!environment.settings.contentBlockerEnabled)268                LabeledContent(L("Active rules"), value: environment.blocker.isCompiling ? L("Compiling…") : "\(environment.blocker.ruleCount)")269                if let error = environment.blocker.lastError { Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) }270                Note(L("Rules are compiled into WebKit, which blocks matching third-party requests itself. SP Browser does not read your traffic to do this and cannot count what was blocked. Blocking can occasionally break a page: turn it off for that site from the shield button."))271            }272            Section(L("Sites where blocking is off")) {273                if environment.settings.blockerDisabledHosts.isEmpty { Note(L("None.")) }274                ForEach(environment.settings.blockerDisabledHosts, id: \.self) { host in275                    HStack { Text(host); Spacer(); Button(L("Remove")) { environment.settings.blockerDisabledHosts.removeAll { $0 == host } }.controlSize(.small) }276                }277            }278            Section(L("Additional lists")) {279                Note(L("Lists are downloaded only when you press Update, over HTTPS, without cookies. Only plain “block this domain” entries are used; other rule types are ignored."))280                ForEach(environment.blockLists.sources) { source in281                    HStack {282                        Toggle(isOn: Binding(get: { source.enabled }, set: { value in mutate(source) { $0.enabled = value } })) {283                            VStack(alignment: .leading) {284                                Text(source.name)285                                Text(source.lastUpdated.map { L("%d domains · updated %@", source.domainCount, $0.formatted(date: .abbreviated, time: .shortened)) } ?? L("Never downloaded"))286                                    .font(.caption).foregroundStyle(.secondary)287                            }288                        }289                        Spacer()290                        if updating == source.id { ProgressView().controlSize(.small) }291                        Button(L("Update")) { update(source) }.controlSize(.small).disabled(updating != nil)292                        Button(L("Remove")) {293                            environment.blockLists.domainsBySource[source.id.uuidString] = nil294                            environment.blockLists.sources.removeAll { $0.id == source.id }295                        }296                        .controlSize(.small)297                    }298                }299                ForEach(BlockListSource.suggested.filter { suggestion in !environment.blockLists.sources.contains { $0.url == suggestion.url } }) { suggestion in300                    HStack { Text(suggestion.name).foregroundStyle(.secondary); Spacer(); Button(L("Add")) { environment.blockLists.sources.append(suggestion) }.controlSize(.small) }301                }302                HStack {303                    TextField(L("List address (https)"), text: $customURL, prompt: Text("https://…"))304                    Button(L("Add")) {305                        environment.blockLists.sources.append(BlockListSource(name: URL(string: customURL)?.host ?? customURL, url: customURL))306                        customURL = ""307                    }308                    .disabled(!BlockListSource(name: "", url: customURL).isFetchable)309                }310                if let message { Note(message) }311            }312        }313        .formStyle(.grouped)314    }315316    private func mutate(_ source: BlockListSource, _ change: (inout BlockListSource) -> Void) {317        guard let index = environment.blockLists.sources.firstIndex(where: { $0.id == source.id }) else { return }318        change(&environment.blockLists.sources[index])319    }320321    private func update(_ source: BlockListSource) {322        updating = source.id323        message = nil324        Task {325            defer { updating = nil }326            do {327                let domains = try await environment.blocker.fetchDomains(from: source)328                var lists = environment.blockLists329                lists.domainsBySource[source.id.uuidString] = domains330                if let index = lists.sources.firstIndex(where: { $0.id == source.id }) {331                    lists.sources[index].lastUpdated = Date()332                    lists.sources[index].domainCount = domains.count333                }334                environment.blockLists = lists335                message = L("%d domains loaded from “%@”.", domains.count, source.name)336            } catch {337                message = L("“%@” could not be updated: %@", source.name, error.localizedDescription)338            }339        }340    }341}342343struct ProfileSettings: View {344    @Bindable var environment: AppEnvironment345    @State private var newName = ""346    @State private var deleting: Profile?347348    var body: some View {349        Form {350            Section {351                Note(L("Each profile has its own cookies, logins, cache, history, bookmarks, permissions and workspaces. Website data is kept in a separate WebKit store per profile, so a site signed in under one profile is signed out in the others."))352            }353            Section(L("Profiles")) {354                ForEach(environment.profiles) { profile in355                    HStack {356                        Image(systemName: profile.symbol).foregroundStyle(Theme.color(profile.colorIndex))357                        TextField(L("Name"), text: Binding(get: { profile.name }, set: { value in var copy = profile; copy.name = value; environment.updateProfile(copy) }))358                            .labelsHidden()359                        Picker(L("Color"), selection: Binding(get: { profile.colorIndex }, set: { value in var copy = profile; copy.colorIndex = value; environment.updateProfile(copy) })) {360                            ForEach(0..<Theme.palette.count, id: \.self) { Text(L("Color %d", $0 + 1)).tag($0) }361                        }362                        .labelsHidden().fixedSize()363                        Button(L("Open Window")) { environment.openWindow(profile: profile) }.controlSize(.small)364                        Button(L("Delete…"), role: .destructive) { deleting = profile }.controlSize(.small).disabled(profile.id == environment.profileStore.defaultID)365                    }366                }367            }368            Section(L("New profile")) {369                HStack {370                    TextField(L("Name"), text: $newName, prompt: Text(L("Work, School…")))371                    Button(L("Create")) { environment.createProfile(name: newName, colorIndex: environment.profiles.count); newName = "" }372                        .disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty)373                }374            }375        }376        .formStyle(.grouped)377        .confirmationDialog(L("Delete the profile “%@”?", deleting?.name ?? ""), isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {378            Button(L("Delete Profile and Its Data"), role: .destructive) {379                if let profile = deleting { Task { await environment.deleteProfile(profile) } }380                deleting = nil381            }382        } message: { Text(L("Its windows will close. Its history, bookmarks, notes, cookies and website data will be permanently removed.")) }383    }384}385386struct ShortcutSettings: View {387    @Bindable var environment: AppEnvironment388    @State private var recording: CommandID?389    @State private var monitor: Any?390391    var body: some View {392        let overrides = environment.settings.shortcutOverrides393        let conflicts = CommandID.conflicts(overrides: overrides)394        Form {395            Section {396                Note(L("Click a shortcut, then press the new key combination. It must include ⌘ or ⌃. Press Escape to cancel. Changes apply immediately to the menus."))397                if !conflicts.isEmpty {398                    Label(L("Some commands share the same shortcut; only the first one in the menus will respond."), systemImage: "exclamationmark.triangle").foregroundStyle(.orange)399                }400                Button(L("Restore Default Shortcuts")) { environment.settings.shortcutOverrides = [:] }.disabled(overrides.isEmpty)401            }402            ForEach(CommandCategory.allCases, id: \.self) { category in403                let commands = CommandID.allCases.filter { $0.category == category }404                if !commands.isEmpty {405                    Section(category.title) {406                        ForEach(commands, id: \.self) { command in407                            let combo = command.shortcut(overrides: overrides)408                            HStack {409                                Text(command.title)410                                Spacer()411                                if let combo, (conflicts[combo]?.count ?? 0) > 1 {412                                    Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange).help(L("Shared with another command"))413                                }414                                Button(recording == command ? L("Press keys…") : (combo?.display ?? L("None"))) { toggleRecording(command) }415                                    .font(.system(.body, design: .rounded)).frame(minWidth: 90)416                                    .accessibilityLabel(L("Shortcut for %@: %@", command.title, combo?.display ?? L("None")))417                                if overrides[command.rawValue] != nil {418                                    Button { environment.settings.shortcutOverrides[command.rawValue] = nil } label: { Image(systemName: "arrow.uturn.backward") }419                                        .buttonStyle(.borderless).help(L("Restore default"))420                                } else if combo != nil {421                                    Button { environment.settings.shortcutOverrides[command.rawValue] = KeyCombo("", command: false) } label: { Image(systemName: "xmark.circle") }422                                        .buttonStyle(.borderless).help(L("Remove shortcut"))423                                }424                            }425                        }426                    }427                }428            }429        }430        .formStyle(.grouped)431        .onDisappear(perform: stopRecording)432    }433434    private func toggleRecording(_ command: CommandID) {435        if recording == command { stopRecording(); return }436        stopRecording()437        recording = command438        monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in439            if event.keyCode == 53 { Task { @MainActor in stopRecording() }; return nil }440            guard let combo = Self.combo(from: event), combo.isUsable else { NSSound.beep(); return nil }441            Task { @MainActor in442                environment.settings.shortcutOverrides[command.rawValue] = combo == command.defaultShortcut ? nil : combo443                stopRecording()444            }445            return nil446        }447    }448449    private func stopRecording() {450        if let monitor { NSEvent.removeMonitor(monitor) }451        monitor = nil452        recording = nil453    }454455    static func combo(from event: NSEvent) -> KeyCombo? {456        let named: [UInt16: String] = [123: "left", 124: "right", 125: "down", 126: "up", 36: "return", 48: "tab", 51: "delete", 49: "space"]457        let flags = event.modifierFlags458        let key = named[event.keyCode] ?? event.charactersIgnoringModifiers?.lowercased() ?? ""459        guard key.count == 1 || named.values.contains(key) else { return nil }460        return KeyCombo(key, command: flags.contains(.command), shift: flags.contains(.shift), option: flags.contains(.option), control: flags.contains(.control))461    }462}463464struct IntelligenceSettings: View {465    @Bindable var environment: AppEnvironment466    @State private var keyDrafts: [String: String] = [:]467    @State private var testResults: [String: String] = [:]468    @State private var keyRevision = 0469470    var body: some View {471        Form {472            Section {473                Toggle(L("Enable SP Intelligence"), isOn: $environment.settings.aiEnabled)474                Note(L("Optional. It is off by default and uses a model you choose: a local endpoint on this Mac, or a service for which you provide your own API key. Page content is sent only when you start an action and confirm the preview. The assistant can read a page; it cannot click, buy, send or publish anything."))475            }476            Section(L("Behaviour")) {477                Toggle(L("Prefer a local endpoint when one is running"), isOn: $environment.settings.aiPreferLocal)478                Picker(L("Active provider"), selection: $environment.settings.aiActiveProviderID) {479                    Text(L("First available")).tag(String?.none)480                    ForEach(environment.settings.aiProviders) { Text($0.name).tag(String?.some($0.id)) }481                }482                Picker(L("Maximum page text per request"), selection: $environment.settings.aiMaxPageCharacters) {483                    Text(L("8,000 characters")).tag(8_000)484                    Text(L("24,000 characters")).tag(24_000)485                    Text(L("60,000 characters")).tag(60_000)486                    Text(L("200,000 characters")).tag(200_000)487                }488                Toggle(L("Keep a local history of answers"), isOn: $environment.settings.aiKeepHistory)489                LabeledContent(L("Stored answers"), value: "\(environment.aiHistory.entries.count)")490                Button(L("Erase History"), role: .destructive) { environment.aiHistory.clear(); keyRevision += 1 }491                Note(L("The history keeps the task, the answer and the site name — never the page text. It is not recorded in private windows."))492            }493            ForEach($environment.settings.aiProviders) { $provider in494                Section(provider.name.isEmpty ? L("Provider") : provider.name) {495                    TextField(L("Name"), text: $provider.name)496                    Picker(L("Protocol"), selection: $provider.kind) { ForEach(AIProviderKind.allCases, id: \.self) { Text($0.title).tag($0) } }497                    TextField(L("Endpoint address"), text: $provider.baseURL)498                    TextField(L("Model"), text: $provider.model)499                    Toggle(L("Requires an API key"), isOn: $provider.requiresKey)500                    if provider.requiresKey {501                        let _ = keyRevision502                        let stored = environment.secrets.secret(for: provider.id) != nil503                        HStack {504                            SecureField(stored ? L("Key stored in Keychain — type to replace") : L("API key"), text: Binding(get: { keyDrafts[provider.id] ?? "" }, set: { keyDrafts[provider.id] = $0 }))505                            Button(L("Save Key")) {506                                environment.secrets.setSecret(keyDrafts[provider.id], for: provider.id)507                                keyDrafts[provider.id] = ""508                                keyRevision += 1509                            }510                            .disabled((keyDrafts[provider.id] ?? "").isEmpty)511                            if stored { Button(L("Delete Key"), role: .destructive) { environment.secrets.setSecret(nil, for: provider.id); keyRevision += 1 } }512                        }513                        Note(L("The key is stored in your macOS Keychain. It is never written to settings, logs or addresses, and is not shown again."))514                    }515                    if let problem = provider.validationError { Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) }516                    else { Label(provider.isLocal ? L("Local endpoint: page content stays on this Mac.") : L("Remote endpoint: page content you confirm is sent to %@.", provider.endpointURL?.host ?? ""),517                                 systemImage: provider.isLocal ? "desktopcomputer" : "network").foregroundStyle(.secondary) }518                    HStack {519                        Button(L("Test Connection")) {520                            let config = provider521                            testResults[config.id] = L("Testing…")522                            Task {523                                testResults[config.id] = await AIService.isReachable(config, secrets: environment.secrets) ? L("The endpoint answered.") : L("No answer from the endpoint.")524                            }525                        }526                        if let result = testResults[provider.id] { Text(result).font(.callout).foregroundStyle(.secondary) }527                        Spacer()528                        Button(L("Remove Provider"), role: .destructive) {529                            let id = provider.id530                            environment.secrets.setSecret(nil, for: id)531                            environment.settings.aiProviders.removeAll { $0.id == id }532                            if environment.settings.aiActiveProviderID == id { environment.settings.aiActiveProviderID = nil }533                        }534                    }535                }536            }537            Section(L("Add a provider")) {538                HStack {539                    Button(L("Local model (Ollama, LM Studio…)")) { environment.settings.aiProviders.append(.localTemplate()) }540                    Button("Anthropic") {541                        environment.settings.aiProviders.append(AIProviderConfig(name: "Anthropic", kind: .anthropic, baseURL: AIProviderKind.anthropic.defaultBaseURL, model: AIProviderKind.anthropic.defaultModel))542                    }543                    Button(L("OpenAI-compatible")) {544                        environment.settings.aiProviders.append(AIProviderConfig(name: L("OpenAI-compatible"), kind: .openAICompatible, baseURL: AIProviderKind.openAICompatible.defaultBaseURL, model: ""))545                    }546                }547            }548        }549        .formStyle(.grouped)550    }551}552553struct ScriptSettings: View {554    @Bindable var environment: AppEnvironment555    @State private var selection: UUID?556557    var body: some View {558        Form {559            Section {560                Toggle(L("Allow user scripts"), isOn: $environment.settings.userScriptsEnabled)561                Label(L("A user script can read and change everything on the pages it runs on, including what you type there. Only add scripts you wrote or fully understand."), systemImage: "exclamationmark.triangle")562                    .foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)563                Note(L("Scripts are off by default, run only on the sites listed for each one (there is no “all sites” option), in an isolated JavaScript world, and never in private windows. Changes apply to pages loaded afterwards."))564            }565            Section(L("Scripts")) {566                ForEach($environment.userScripts) { $script in567                    DisclosureGroup(isExpanded: Binding(get: { selection == script.id }, set: { selection = $0 ? script.id : nil })) {568                        TextField(L("Name"), text: $script.name)569                        TextField(L("Sites"), text: Binding(get: { script.hosts.joined(separator: ", ") },570                                                              set: { script.hosts = $0.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces).lowercased() }.filter { !$0.isEmpty } }),571                                  prompt: Text("example.com, *.docs.example.org"))572                        let invalid = script.hosts.filter { !HostPattern.isValid($0) }573                        if !invalid.isEmpty { Label(L("Not valid site names: %@", invalid.joined(separator: ", ")), systemImage: "exclamationmark.triangle").foregroundStyle(.orange) }574                        Picker(L("Run"), selection: $script.runAt) {575                            Text(L("When the page has loaded")).tag(UserScript.RunAt.documentEnd)576                            Text(L("Before the page starts loading")).tag(UserScript.RunAt.documentStart)577                        }578                        Toggle(L("Main page only (not embedded frames)"), isOn: $script.mainFrameOnly)579                        TextEditor(text: $script.source).font(.system(size: 12, design: .monospaced)).frame(minHeight: 140)580                            .overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(Theme.hairline)).accessibilityLabel(L("JavaScript source"))581                        Button(L("Delete Script"), role: .destructive) { let id = script.id; environment.userScripts.removeAll { $0.id == id } }582                    } label: {583                        Toggle(isOn: $script.enabled) {584                            VStack(alignment: .leading) {585                                Text(script.name.isEmpty ? L("Untitled script") : script.name)586                                Text(script.hosts.isEmpty ? L("No site: this script never runs") : script.hosts.joined(separator: ", ")).font(.caption).foregroundStyle(.secondary)587                            }588                        }589                    }590                }591                Button(L("New Script")) {592                    let script = UserScript(name: L("New script"), source: "// document.body.style.outline = '2px solid #2F6BFF';\n", hosts: [])593                    environment.userScripts.append(script)594                    selection = script.id595                }596            }597        }598        .formStyle(.grouped)599    }600}601602struct AdvancedSettings: View {603    @Bindable var environment: AppEnvironment604605    var body: some View {606        Form {607            Section(L("Diagnostics")) {608                Toggle(L("Write a local diagnostics log"), isOn: $environment.settings.diagnosticsEnabled)609                Note(L("Off by default. When on, technical events (failed loads, blocked navigations) are appended to a file on this Mac. Addresses are reduced to the site name; page content, cookies and keys are never logged. Nothing is uploaded."))610                HStack {611                    Button(L("Show Log in Finder")) { NSWorkspace.shared.activateFileViewerSelecting([environment.root.appendingPathComponent("diagnostics.log")]) }612                    Button(L("Delete Log"), role: .destructive) { try? FileManager.default.removeItem(at: environment.root.appendingPathComponent("diagnostics.log")) }613                }614                .disabled(!FileManager.default.fileExists(atPath: environment.root.appendingPathComponent("diagnostics.log").path))615            }616            Section(L("User agent")) {617                TextField(L("Custom user agent"), text: $environment.settings.customUserAgent, prompt: Text(L("Leave empty to use the default")))618                Note(L("Only changes the name sent to sites. Pages are still rendered by WebKit; some sites may then serve code that does not work."))619            }620            Section(L("Storage")) {621                LabeledContent(L("Data folder")) {622                    Button(environment.root.path) { NSWorkspace.shared.activateFileViewerSelecting([environment.root]) }.buttonStyle(.link).lineLimit(1).truncationMode(.head)623                }624            }625            Section(L("About the engine")) {626                Note(L("SP Browser renders pages with WebKit, the system engine also used by Safari. Site compatibility is therefore WebKit's. Extensions from Chrome, Firefox or Safari are not supported. Web Inspector is available in development builds only."))627                LabeledContent(L("Version"), value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")628            }629        }630        .formStyle(.grouped)631    }632}633
Files main
Menu

Theme