SPB Git

Repository Public

BrowserWindowController.swift 5.5 KB 108 lines swift

1import AppKit2import SwiftUI34/// Hosts one browser window. The chrome is drawn by SwiftUI under a transparent title bar;5/// the traffic lights are re-centred on the custom toolbar row.6@MainActor7final class BrowserWindowController: NSWindowController, NSWindowDelegate {8    let state: BrowserWindowState9    static let toolbarHeight: CGFloat = 461011    init(state: BrowserWindowState, frameDescriptor: String?) {12        self.state = state13        let window = BrowserWindow(contentRect: NSRect(x: 0, y: 0, width: 1320, height: 860),14                                   styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],15                                   backing: .buffered, defer: false)16        window.titlebarAppearsTransparent = true17        window.titleVisibility = .hidden18        window.isMovableByWindowBackground = false19        window.tabbingMode = .disallowed20        window.minSize = NSSize(width: 620, height: 420)21        window.isReleasedWhenClosed = false22        window.collectionBehavior.insert(.fullScreenPrimary)23        if state.isPrivate { window.appearance = NSAppearance(named: .darkAqua) }24        super.init(window: window)25        window.delegate = self26        state.window = window27        let host = NSHostingView(rootView: BrowserRootView(state: state, environment: state.environment))28        host.sizingOptions = []29        window.contentView = host30        if let frameDescriptor, !frameDescriptor.isEmpty {31            window.setFrame(from: frameDescriptor)32        } else {33            window.center()34            if let last = state.environment.controllers.last?.window {35                window.setFrameOrigin(NSPoint(x: last.frame.minX + 28, y: last.frame.minY - 28))36            }37        }38        // A restored frame may refer to a display that is no longer connected.39        if !NSScreen.screens.contains(where: { $0.visibleFrame.intersects(window.frame) }) { window.center() }40        state.updateWindowTitle()41        layoutTrafficLights()42    }4344    @available(*, unavailable)45    required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }4647    /// Centres the close/minimise/zoom buttons vertically in the custom toolbar row.48    func layoutTrafficLights() {49        guard let window, !window.styleMask.contains(.fullScreen) else { return }50        let buttons = [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton].compactMap(window.standardWindowButton)51        guard let container = buttons.first?.superview else { return }52        for (index, button) in buttons.enumerated() {53            let y = container.bounds.height - (Self.toolbarHeight + button.frame.height) / 254            let origin = NSPoint(x: 16 + CGFloat(index) * 20, y: max(y, 0))55            if button.frame.origin != origin { button.setFrameOrigin(origin) }56        }57    }5859    /// AppKit re-centres the buttons in the standard title bar whenever it lays the title bar out again60    /// (title change, activation…), so their position is re-applied on every window update. It is a no-op when unchanged.61    func windowDidUpdate(_ notification: Notification) { layoutTrafficLights() }62    func windowDidResize(_ notification: Notification) { layoutTrafficLights() }63    func windowDidBecomeKey(_ notification: Notification) { layoutTrafficLights() }64    func windowDidEndLiveResize(_ notification: Notification) { state.environment.scheduleSessionSave() }65    func windowDidMove(_ notification: Notification) { state.environment.scheduleSessionSave() }66    func windowWillEnterFullScreen(_ notification: Notification) { state.isFullScreen = true }67    func windowDidExitFullScreen(_ notification: Notification) { state.isFullScreen = false; layoutTrafficLights() }6869    func windowShouldClose(_ sender: NSWindow) -> Bool {70        let count = state.tabs.filter { $0.url != nil }.count71        guard count > 3, state.environment.settings.confirmBeforeClosingManyTabs, !state.environment.isTerminating else { return true }72        let alert = NSAlert()73        alert.messageText = L("Close this window and its %d tabs?", count)74        alert.informativeText = state.isPrivate75            ? L("Private tabs cannot be reopened once the window is closed.")76            : L("You can bring them back with History › Reopen Closed Tab only while SP Browser stays open.")77        alert.addButton(withTitle: L("Close Window"))78        alert.addButton(withTitle: L("Cancel"))79        return alert.runModal() == .alertFirstButtonReturn80    }8182    func windowWillClose(_ notification: Notification) {83        let environment = state.environment84        if environment.isTerminating {85            state.teardown()86            return87        }88        // Remove the window from the list first so the saved session no longer contains it.89        environment.windowDidClose(self)90        state.teardown()91        window?.contentView = nil92    }93}9495/// A window whose keyboard handling gives the browser's own shortcuts priority over page content96/// for the few keys WebKit would otherwise swallow.97final class BrowserWindow: NSWindow {98    override func performKeyEquivalent(with event: NSEvent) -> Bool {99        // Let the main menu see ⌘-shortcuts before the web view does, so ⌘L, ⌘T, ⌘W always work.100        if event.modifierFlags.contains(.command), NSApp.mainMenu?.performKeyEquivalent(with: event) == true { return true }101        return super.performKeyEquivalent(with: event)102    }103104    override func cancelOperation(_ sender: Any?) {105        // Escape leaves full screen only through the standard control, never by accident while typing.106    }107}108
Files main
Menu

Theme