SPB Git

Repository Public

BrowserWindowState+Commands.swift 15.8 KB 316 lines swift

1import AppKit2import UniformTypeIdentifiers3import WebKit45/// The single dispatch point for every browser action. Menus, shortcuts, the command palette6/// and App Intents all end up here, so behaviour is identical whichever way a command is invoked.7extension BrowserWindowState {8    func isEnabled(_ command: CommandID) -> Bool {9        let tab = selectedTab10        let hasPage = tab?.url != nil11        // A native search page is not a web document: nothing to print, read, bookmark or inspect.12        let hasWebPage = hasPage && tab?.isSearchPage != true13        switch command {14        case .goBack: return tab?.canGoBack ?? false15        case .goForward: return tab?.canGoForward ?? false16        case .stopLoading: return tab?.isLoading ?? false17        case .reload, .hardReload, .duplicateTab:18            return hasPage19        case .savePageAsPDF, .capturePage, .printPage, .sharePage, .findInPage, .findNext, .findPrevious,20             .zoomIn, .zoomOut, .zoomReset, .toggleReader, .addBookmark, .pageInfo, .viewSource, .pageMetadata, .showNotes:21            return hasWebPage22        case .addToReadingList, .toggleFavorite:23            return hasWebPage && !isPrivate && (tab?.url).map(HistoryStore.isRecordable) == true24        case .showReadingList, .showOtherDevices: return !isPrivate25        case .syncNow: return environment.services.account.isSignedIn && environment.settings.syncEnabled26        case .toggleBlockerForSite, .clearSiteData: return tab?.url?.host != nil27        case .reopenClosedTab: return !recentlyClosed.isEmpty28        case .closeOtherTabs, .nextTab, .previousTab: return visibleTabs.count > 129        case .moveTabToNewWindow: return tabs.count > 1 && !isPrivate30        case .swapSplit: return splitTabID != nil31        case .nextWorkspace, .previousWorkspace: return workspaces.count > 132        case .saveSession, .showSessions: return !isPrivate33        case .toggleIntelligence: return environment.settings.aiEnabled34        case .addToCanvas: return hasPage35        case .showPortal: return !isPrivate36        case .peekLink: return tab?.hovered != nil37        default: return true38        }39    }4041    func perform(_ command: CommandID) {42        guard isEnabled(command) else { return }43        let tab = selectedTab44        switch command {45        case .newTab:46            newTab(url: environment.homepageURL(), select: true)47            focusAddressBar()48        case .newWindow: environment.openWindow(profile: profile.profile)49        case .newPrivateWindow: environment.openWindow(profile: profile.profile, isPrivate: true)50        case .openFile: openFile()51        case .openLocation: focusAddressBar()52        case .closeTab: if let tab { close(tab) }53        case .closeWindow: window?.performClose(nil)54        case .closeOtherTabs: if let tab { closeOthers(keeping: tab) }55        case .reopenClosedTab: reopenClosedTab()56        case .duplicateTab: if let tab { duplicate(tab) }57        case .pinTab: if let tab { togglePin(tab) }58        case .moveTabToNewWindow: if let tab { moveToNewWindow(tab) }59        case .savePageAsPDF: savePageAsPDF()60        case .capturePage: capturePage()61        case .printPage: printPage()62        case .sharePage: sharePage()63        case .findInPage: findVisible = true64        case .findNext: findVisible = true; findRequest(backwards: false)65        case .findPrevious: findVisible = true; findRequest(backwards: true)66        case .reload: if let model = tab?.searchPage, tab?.isSearchPage == true { model.reload(ignoringCache: true) } else { tab?.reload() }67        case .hardReload: if let model = tab?.searchPage, tab?.isSearchPage == true { model.reload(ignoringCache: true) } else { tab?.reload(ignoringCache: true) }68        case .stopLoading: tab?.stopLoading()69        case .goBack: tab?.goBack()70        case .goForward: tab?.goForward()71        case .goHome:72            if let home = environment.homepageURL() ?? AddressResolver.resolve(environment.settings.homepage, engine: environment.settings.activeSearchEngine())?.url {73                tab?.load(home)74            } else {75                tab?.showStartPage()76            }77        case .zoomIn: tab?.setZoom((tab?.zoom ?? 1) + 0.1)78        case .zoomOut: tab?.setZoom((tab?.zoom ?? 1) - 0.1)79        case .zoomReset: tab?.setZoom(1)80        case .toggleSidebar:81            sidebarVisible.toggle()82            environment.settings.sidebarVisible = sidebarVisible83        case .toggleTabLayout:84            environment.settings.tabLayout = environment.settings.tabLayout == .horizontal ? .vertical : .horizontal85            if environment.settings.tabLayout == .vertical { sidebarVisible = true; sidebarPanel = .tabs }86        case .toggleFocusMode: AuraMotion.perform(.expressive) { focusMode.toggle() }87        case .toggleReader:88            Task { if await tab?.toggleReader() == false { toast = L("Reader view is not available for this page.") } }89        case .toggleFullScreen: window?.toggleFullScreen(nil)90        case .commandPalette: palettePrefill = ""; orbitVisible = false; AuraMotion.perform(.expressive) { paletteVisible.toggle() }91        case .searchTabs: palettePrefill = "@"; orbitVisible = false; AuraMotion.perform(.expressive) { paletteVisible = true }92        case .nextTab: selectAdjacentTab(offset: 1)93        case .previousTab: selectAdjacentTab(offset: -1)94        case .toggleSplitView: toggleSplit()95        case .swapSplit: swapSplit()96        case .suspendTab:97            let before = tabs.filter { $0.webView != nil }.count98            suspendInactiveTabs(olderThan: 0)99            toast = L("%d background tabs suspended.", before - tabs.filter { $0.webView != nil }.count)100        case .newTabGroup: if let tab { createGroup(name: "", with: tab) }101        case .nextWorkspace: cycleWorkspace(offset: 1)102        case .previousWorkspace: cycleWorkspace(offset: -1)103        case .addBookmark: sheet = .bookmarkEditor104        case .showBookmarks: showSidebar(.bookmarks)105        case .showHistory: showSidebar(.history)106        case .showNotes: showSidebar(.notes)107        case .showSessions: showSidebar(.sessions)108        case .showDownloads: downloadsVisible.toggle()109        case .importBookmarks: importBookmarks()110        case .exportBookmarks: exportBookmarks()111        case .clearHistory: sheet = .clearHistory112        case .saveSession: sheet = .saveSession113        case .pageInfo: rightPanel = rightPanel == .pageInfo ? .none : .pageInfo114        case .viewSource, .pageMetadata: rightPanel = rightPanel == .developer ? .none : .developer115        case .toggleIntelligence: rightPanel = rightPanel == .intelligence ? .none : .intelligence116        case .toggleBlockerForSite: toggleBlockerForCurrentSite()117        case .clearSiteData: clearCurrentSiteData()118        case .openSettings: (NSApp.delegate as? AppDelegate)?.showSettings()119        case .showAccount: (NSApp.delegate as? AppDelegate)?.showSettings(section: .account)120        case .syncNow: Task { await environment.services.sync.syncNow() }121        case .showReadingList: showSidebar(.readingList)122        case .showOtherDevices: showSidebar(.devices)123        case .addToReadingList:124            if let tab, let url = tab.url { addToReadingList(title: tab.displayTitle, url: url.absoluteString) }125        case .toggleFavorite:126            if let tab, let url = tab.url?.absoluteString {127                let library = environment.services.library128                if library.isFavorite(url) { library.removeFavorite(url: url); toast = L("Removed from Favorites") }129                else { library.addFavorite(title: tab.displayTitle, url: url); toast = L("Added to Favorites") }130                environment.services.localChange()131            }132        case .changeUserAgent: sheet = .userAgent133        case .commandOrbit: toggleOrbit()134        case .showConstellation: toggleAura(.constellation)135        case .showFlow: toggleAura(.flow)136        case .showCanvas: toggleAura(.canvas)137        case .addToCanvas: addCurrentPageToCanvas()138        case .showPortal: toggleAura(.portal)139        case .peekLink: if let link = tab?.hovered { showPeek(link) }140        }141    }142143    private func showSidebar(_ panel: SidebarPanel) {144        if sidebarVisible && sidebarPanel == panel && !focusMode {145            sidebarVisible = false146        } else {147            focusMode = false148            sidebarVisible = true149            sidebarPanel = panel150        }151    }152153    // MARK: Find154155    func findRequest(backwards: Bool) {156        guard let tab = selectedTab, !findQuery.isEmpty else { return }157        let query = findQuery158        Task { findFound = await tab.find(query, backwards: backwards) }159    }160161    // MARK: Files and export162163    private func openFile() {164        guard let window else { return }165        let panel = NSOpenPanel()166        panel.allowedContentTypes = [.html, .pdf, .image, .plainText, .webArchive, .xml, .json]167        panel.allowsMultipleSelection = true168        panel.beginSheetModal(for: window) { [weak self] response in169            guard response == .OK else { return }170            for (index, url) in panel.urls.enumerated() {171                if index == 0, self?.selectedTab?.isBlank == true { self?.selectedTab?.load(url) } else { self?.newTab(url: url, select: true) }172            }173        }174    }175176    private func savePanel(suggested: String, type: UTType, completion: @escaping @MainActor (URL) -> Void) {177        guard let window else { return }178        let panel = NSSavePanel()179        panel.allowedContentTypes = [type]180        panel.nameFieldStringValue = DownloadSafety.sanitize(filename: suggested)181        panel.canCreateDirectories = true182        panel.beginSheetModal(for: window) { response in183            if response == .OK, let url = panel.url { completion(url) }184        }185    }186187    private func savePageAsPDF() {188        guard let tab = selectedTab, let webView = tab.webView else { return }189        savePanel(suggested: tab.displayTitle + ".pdf", type: .pdf) { [weak self] url in190            Task {191                do {192                    try await webView.pdf(configuration: WKPDFConfiguration()).write(to: url, options: .atomic)193                    self?.toast = L("PDF saved.")194                } catch { self?.toast = L("The PDF could not be saved.") }195            }196        }197    }198199    /// Captures the visible part of the page. Nothing is captured without this explicit command and a save location chosen by the user.200    private func capturePage() {201        guard let tab = selectedTab, let webView = tab.webView else { return }202        savePanel(suggested: tab.displayTitle + ".png", type: .png) { [weak self] url in203            webView.takeSnapshot(with: nil) { image, _ in204                Task { @MainActor in205                    guard let tiff = image?.tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiff),206                          let png = bitmap.representation(using: .png, properties: [:]), (try? png.write(to: url, options: .atomic)) != nil else {207                        self?.toast = L("The capture could not be saved.")208                        return209                    }210                    self?.toast = L("Capture saved.")211                }212            }213        }214    }215216    private func printPage() {217        guard let webView = selectedTab?.webView, let window else { return }218        let info = NSPrintInfo.shared.copy() as? NSPrintInfo ?? NSPrintInfo.shared219        info.horizontalPagination = .fit220        info.isVerticallyCentered = false221        let operation = webView.printOperation(with: info)222        operation.view?.frame = webView.bounds223        operation.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil)224    }225226    private func sharePage() {227        guard let url = selectedTab?.url, let view = window?.contentView else { return }228        let picker = NSSharingServicePicker(items: [url])229        picker.show(relativeTo: NSRect(x: view.bounds.maxX - 120, y: view.bounds.maxY - 44, width: 1, height: 1), of: view, preferredEdge: .minY)230    }231232    private func moveToNewWindow(_ tab: BrowserTab) {233        guard !isPrivate, let detached = detach(tab), let controller = environment.openWindow(profile: profile.profile) else { return }234        let blank = controller.state.tabs235        controller.state.adopt(detached)236        blank.forEach(controller.state.close)237    }238239    // MARK: Bookmarks import / export240241    private func importBookmarks() {242        guard let window else { return }243        let panel = NSOpenPanel()244        panel.allowedContentTypes = [.html]245        panel.message = L("Choose a bookmarks file exported from another browser (HTML).")246        panel.beginSheetModal(for: window) { [weak self] response in247            guard response == .OK, let url = panel.url, let self else { return }248            guard let data = try? Data(contentsOf: url), data.count < 50_000_000,249                  let html = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {250                self.toast = L("The file could not be read.")251                return252            }253            let nodes = NetscapeBookmarkCodec.parse(html)254            guard !nodes.isEmpty else { self.toast = L("No bookmarks were found in this file."); return }255            let folder = self.profile.bookmarks.addFolder(L("Imported %@", Date().formatted(date: .abbreviated, time: .omitted)))256            let count = self.profile.bookmarks.importNodes(nodes, under: folder?.id)257            self.bookmarksRevision += 1258            self.toast = L("%d bookmarks imported.", count)259            self.showSidebar(.bookmarks)260        }261    }262263    private func exportBookmarks() {264        let html = NetscapeBookmarkCodec.export(profile.bookmarks.tree())265        savePanel(suggested: "SP Browser Bookmarks.html", type: .html) { [weak self] url in266            let ok = (try? Data(html.utf8).write(to: url, options: .atomic)) != nil267            self?.toast = ok ? L("Bookmarks exported.") : L("The bookmarks could not be exported.")268        }269    }270271    // MARK: Privacy272273    private func toggleBlockerForCurrentSite() {274        guard let host = selectedTab?.url?.host else { return }275        let key = URLInspector.registrableDomain(of: host)276        var hosts = environment.settings.blockerDisabledHosts277        if environment.settings.isBlockerDisabled(forHost: host) {278            hosts.removeAll { $0 == key || host.hasSuffix("." + $0) || $0 == host.lowercased() }279            toast = L("Content blocker turned on for %@.", key)280        } else {281            hosts.append(key)282            toast = L("Content blocker turned off for %@.", key)283        }284        environment.settings.blockerDisabledHosts = hosts.sorted()285        let tab = selectedTab286        Task {287            await environment.blocker.refresh(settings: environment.settings, lists: environment.blockLists)288            tab?.reload()289        }290    }291292    private func clearCurrentSiteData() {293        guard let tab = selectedTab, let host = tab.url?.host, let window else { return }294        let site = URLInspector.registrableDomain(of: host)295        let alert = NSAlert()296        alert.alertStyle = .warning297        alert.messageText = L("Clear all data for %@?", site)298        alert.informativeText = L("Cookies, cache, local storage and history entries for this site will be removed. You will be signed out of it. This cannot be undone.")299        alert.addButton(withTitle: L("Clear Data"))300        alert.addButton(withTitle: L("Cancel"))301        alert.buttons.first?.hasDestructiveAction = true302        alert.beginSheetModal(for: window) { [weak self] response in303            guard response == .alertFirstButtonReturn, let self else { return }304            Task {305                let removed = await self.profile.clearSiteData(host: host)306                let visits = self.profile.history.delete(host: site)307                self.profile.flow.update { $0.forget(host: site) }308                self.profile.permissions.reset(host: host)309                self.historyRevision += 1310                self.toast = L("Removed %d data records and %d history entries for %@.", removed, visits, site)311                tab.reload()312            }313        }314    }315}316
Files main
Menu

Theme