Repository Public
1import AppKit2import UniformTypeIdentifiers3import WebKit45enum SidebarPanel: String, CaseIterable, Identifiable {6 case tabs, bookmarks, history, readingList, devices, notes, sessions7 var id: String { rawValue }89 var title: String {10 switch self {11 case .tabs: return L("Tabs")12 case .bookmarks: return L("Bookmarks")13 case .history: return L("History")14 case .readingList: return L("Reading List")15 case .devices: return L("Other Devices")16 case .notes: return L("Notes")17 case .sessions: return L("Sessions")18 }19 }2021 var symbol: String {22 switch self {23 case .tabs: return "square.on.square"24 case .bookmarks: return "bookmark"25 case .history: return "clock"26 case .readingList: return "eyeglasses"27 case .devices: return "laptopcomputer.and.iphone"28 case .notes: return "note.text"29 case .sessions: return "tray.full"30 }31 }32}3334enum RightPanel: Equatable { case none, intelligence, pageInfo, developer }35enum OverlaySheet: Equatable { case none, bookmarkEditor, clearHistory, saveSession, userAgent }3637/// All the state of one browser window: its tabs, layout and transient UI. Views observe it; commands mutate it.38@MainActor39@Observable40final class BrowserWindowState: TabHost {41 @ObservationIgnored let environment: AppEnvironment42 @ObservationIgnored let profile: ProfileContext43 @ObservationIgnored weak var window: NSWindow?4445 private(set) var tabs: [BrowserTab] = []46 private(set) var selectedTabID: UUID?47 private(set) var splitTabID: UUID?48 private(set) var groups: [TabGroup] = []49 private(set) var workspaces: [Workspace] = []50 private(set) var activeWorkspaceID: UUID51 private(set) var recentlyClosed: [TabSnapshot] = []5253 var sidebarVisible: Bool54 var sidebarPanel: SidebarPanel = .tabs55 var rightPanel: RightPanel = .none56 var focusMode = false57 var paletteVisible = false58 var palettePrefill = ""59 var findVisible = false60 var downloadsVisible = false61 var sheet: OverlaySheet = .none62 var isFullScreen = false63 /// Incremented to ask the address bar to take keyboard focus.64 private(set) var addressFocusRequest = 065 var toast: String?66 /// The bookmark being edited in the editor sheet; nil means "bookmark the current page".67 var editingBookmark: Bookmark?68 var findQuery = ""69 var findFound: Bool?70 /// Bumped when bookmarks or history change outside the views that display them, so those views reload.71 var bookmarksRevision = 072 var historyRevision = 07374 // AURA (3.0)75 /// The full-window AURA surface on screen, if any.76 var auraOverlay: AuraOverlay = .none77 var orbitVisible = false78 /// Where Orbit opens, in window coordinates (top-left origin); nil = centre of the page.79 var orbitAnchor: CGPoint?80 /// The link preview on screen and the link it belongs to.81 var peek: PeekModel?82 var peekLink: HoveredLink?83 /// A tab that just opened from a link: the page area plays the morph from this unit point.84 var morph: TabMorph?85 var flowRevision = 086 @ObservationIgnored var canvasController: CanvasController?8788 var isPrivate: Bool { profile.isPrivate }89 var hostWindow: NSWindow? { window }9091 init(environment: AppEnvironment, profile: ProfileContext) {92 self.environment = environment93 self.profile = profile94 sidebarVisible = environment.settings.sidebarVisible95 let stored = profile.workspaces.value96 let initial = stored.isEmpty ? Workspace.defaults() : stored97 activeWorkspaceID = initial[0].id98 workspaces = initial99 }100101 // MARK: Derived102103 var selectedTab: BrowserTab? { tabs.first { $0.id == selectedTabID } }104 var splitTab: BrowserTab? { tabs.first { $0.id == splitTabID } }105 var activeWorkspace: Workspace? { workspaces.first { $0.id == activeWorkspaceID } }106 /// Tabs of the active workspace, pinned first.107 var visibleTabs: [BrowserTab] {108 let mine = tabs.filter { $0.workspaceID == activeWorkspaceID }109 return mine.filter(\.isPinned) + mine.filter { !$0.isPinned }110 }111 func tab(id: UUID?) -> BrowserTab? { tabs.first { $0.id == id } }112 func group(id: UUID?) -> TabGroup? { groups.first { $0.id == id } }113114 // MARK: Tabs115116 @discardableResult117 func newTab(url: URL? = nil, select: Bool = true, after: BrowserTab? = nil, adopting configuration: WKWebViewConfiguration? = nil) -> BrowserTab {118 let tab = BrowserTab(profile: profile, environment: environment)119 tab.host = self120 tab.workspaceID = after?.workspaceID ?? activeWorkspaceID121 tab.groupID = after?.groupID122 tab.openerID = after?.id123 if let after, let point = after.recentPressPoint(for: url) { tab.morphOrigin = point }124 if let after, let index = tabs.firstIndex(where: { $0.id == after.id }) {125 tabs.insert(tab, at: index + 1)126 } else {127 tabs.append(tab)128 }129 if configuration != nil {130 tab.ensureWebView(adopting: configuration)131 } else if let url {132 if select { tab.load(url) } else { tab.load(url) }133 }134 if select { self.select(tab) } else { tab.lastActive = Date() }135 if select, let origin = tab.morphOrigin { morph = TabMorph(tabID: tab.id, origin: origin) }136 stateChanged()137 return tab138 }139140 func select(_ tab: BrowserTab) {141 guard tabs.contains(where: { $0.id == tab.id }) else { return }142 if let previous = selectedTab, previous.id != tab.id { previous.captureThumbnail(); previous.lastActive = Date() }143 if tab.workspaceID != activeWorkspaceID, let workspace = tab.workspaceID { activeWorkspaceID = workspace }144 if splitTabID == tab.id { splitTabID = nil }145 selectedTabID = tab.id146 tab.lastActive = Date()147 if tab.url != nil { tab.ensureWebView() }148 findVisible = false149 stateChanged()150 }151152 func close(_ tab: BrowserTab) {153 guard let index = tabs.firstIndex(where: { $0.id == tab.id }) else { return }154 if tab.url != nil {155 recentlyClosed.insert(tab.snapshot(), at: 0)156 if recentlyClosed.count > 25 { recentlyClosed.removeLast() }157 }158 let wasSelected = selectedTabID == tab.id159 let workspace = tab.workspaceID160 if splitTabID == tab.id { splitTabID = nil }161 tab.tearDownWebView()162 tab.host = nil163 tabs.remove(at: index)164 let closedID = tab.id165 profile.flow.update { $0.tabClosed(closedID) }166 if peek != nil { dismissPeek() }167168 if tabs.isEmpty {169 window?.performClose(nil)170 return171 }172 if wasSelected {173 let siblings = visibleTabs.filter { $0.workspaceID == workspace }174 if let next = siblings.first(where: { candidate in tabs.firstIndex { $0.id == candidate.id }.map { $0 >= index } ?? false }) ?? siblings.last {175 select(next)176 } else {177 newTab(select: true)178 }179 }180 stateChanged()181 }182183 func closeOthers(keeping tab: BrowserTab) {184 visibleTabs.filter { $0.id != tab.id && !$0.isPinned }.forEach(close)185 select(tab)186 }187188 func reopenClosedTab() {189 guard !recentlyClosed.isEmpty else { return }190 reopen(recentlyClosed.removeFirst())191 }192193 func reopen(_ snapshot: TabSnapshot) {194 recentlyClosed.removeAll { $0.id == snapshot.id }195 var copy = snapshot196 copy.id = UUID()197 copy.workspaceID = workspaces.contains { $0.id == snapshot.workspaceID } ? snapshot.workspaceID : activeWorkspaceID198 if !groups.contains(where: { $0.id == copy.groupID }) { copy.groupID = nil }199 let tab = BrowserTab(snapshot: copy, profile: profile, environment: environment)200 tab.host = self201 tabs.append(tab)202 select(tab)203 }204205 func duplicate(_ tab: BrowserTab) {206 newTab(url: tab.url, select: true, after: tab)207 }208209 func togglePin(_ tab: BrowserTab) {210 tab.isPinned.toggle()211 if tab.isPinned { tab.groupID = nil }212 stateChanged()213 }214215 /// Moves `tabID` so that it sits just before `targetID` (or at the end when `targetID` is nil).216 func moveTab(_ tabID: UUID, before targetID: UUID?) {217 guard tabID != targetID, let from = tabs.firstIndex(where: { $0.id == tabID }) else { return }218 let tab = tabs.remove(at: from)219 if let targetID, let target = tabs.first(where: { $0.id == targetID }), let to = tabs.firstIndex(where: { $0.id == targetID }) {220 tab.isPinned = target.isPinned221 tab.groupID = target.groupID222 tab.workspaceID = target.workspaceID223 tabs.insert(tab, at: to)224 } else {225 tabs.append(tab)226 }227 stateChanged()228 }229230 func selectAdjacentTab(offset: Int) {231 let list = visibleTabs232 guard list.count > 1, let current = list.firstIndex(where: { $0.id == selectedTabID }) else { return }233 select(list[(current + offset + list.count) % list.count])234 }235236 func selectTab(atVisibleIndex index: Int) {237 let list = visibleTabs238 guard !list.isEmpty else { return }239 select(index >= 8 ? list[list.count - 1] : list[min(index, list.count - 1)])240 }241242 /// Detaches `tab` and returns it so another window can adopt it with its live page.243 func detach(_ tab: BrowserTab) -> BrowserTab? {244 guard let index = tabs.firstIndex(where: { $0.id == tab.id }), tabs.count > 1 else { return nil }245 if splitTabID == tab.id { splitTabID = nil }246 tabs.remove(at: index)247 tab.host = nil248 if selectedTabID == tab.id, let next = visibleTabs.first ?? tabs.first { select(next) }249 stateChanged()250 return tab251 }252253 func adopt(_ tab: BrowserTab) {254 tab.host = self255 tab.workspaceID = activeWorkspaceID256 tab.groupID = nil257 tabs.append(tab)258 select(tab)259 }260261 func suspendInactiveTabs(olderThan interval: TimeInterval) {262 let cutoff = Date().addingTimeInterval(-interval)263 for tab in tabs where tab.id != selectedTabID && tab.id != splitTabID && !tab.isPinned && tab.webView != nil && tab.lastActive < cutoff {264 tab.suspend()265 }266 }267268 // MARK: Groups269270 @discardableResult271 func createGroup(name: String, with tab: BrowserTab?) -> TabGroup {272 let group = TabGroup(name: name.isEmpty ? L("Group %d", groups.count + 1) : name, colorIndex: groups.count % 6)273 groups.append(group)274 if let tab { tab.groupID = group.id; tab.isPinned = false }275 stateChanged()276 return group277 }278279 func setGroup(_ groupID: UUID?, for tab: BrowserTab) {280 tab.groupID = groupID281 if groupID != nil { tab.isPinned = false }282 pruneGroups()283 stateChanged()284 }285286 func updateGroup(_ group: TabGroup) {287 guard let index = groups.firstIndex(where: { $0.id == group.id }) else { return }288 groups[index] = group289 stateChanged()290 }291292 func removeGroup(_ group: TabGroup, closingTabs: Bool) {293 let members = tabs.filter { $0.groupID == group.id }294 if closingTabs { members.forEach(close) } else { members.forEach { $0.groupID = nil } }295 groups.removeAll { $0.id == group.id }296 stateChanged()297 }298299 private func pruneGroups() {300 groups.removeAll { group in !tabs.contains { $0.groupID == group.id } }301 }302303 // MARK: Workspaces304305 func switchWorkspace(to id: UUID) {306 guard id != activeWorkspaceID, workspaces.contains(where: { $0.id == id }) else { return }307 selectedTab?.captureThumbnail()308 activeWorkspaceID = id309 splitTabID = nil310 if let first = visibleTabs.max(by: { $0.lastActive < $1.lastActive }) { select(first) } else { newTab(select: true) }311 }312313 func cycleWorkspace(offset: Int) {314 guard workspaces.count > 1, let index = workspaces.firstIndex(where: { $0.id == activeWorkspaceID }) else { return }315 switchWorkspace(to: workspaces[(index + offset + workspaces.count) % workspaces.count].id)316 }317318 func saveWorkspaces(_ updated: [Workspace]) {319 guard !updated.isEmpty else { return }320 let removed = Set(workspaces.map(\.id)).subtracting(updated.map(\.id))321 workspaces = updated322 profile.workspaces.value = updated323 if !removed.isEmpty {324 // Tabs of a deleted workspace move to the first remaining one rather than being closed.325 tabs.filter { $0.workspaceID.map(removed.contains) ?? true }.forEach { $0.workspaceID = updated[0].id }326 if removed.contains(activeWorkspaceID) { activeWorkspaceID = updated[0].id }327 }328 environment.controllers.map(\.state).filter { $0 !== self && $0.profile === profile }.forEach { $0.reloadWorkspaces() }329 stateChanged()330 }331332 func reloadWorkspaces() {333 let stored = profile.workspaces.value334 guard !stored.isEmpty else { return }335 workspaces = stored336 if !stored.contains(where: { $0.id == activeWorkspaceID }) { activeWorkspaceID = stored[0].id }337 tabs.filter { tab in !stored.contains { $0.id == tab.workspaceID } }.forEach { $0.workspaceID = stored[0].id }338 }339340 func addWorkspace(name: String) {341 var list = workspaces342 list.append(Workspace(name: name.isEmpty ? L("New Workspace") : name, colorIndex: list.count % 6))343 saveWorkspaces(list)344 if let last = list.last { switchWorkspace(to: last.id) }345 }346347 func toggleFavorite(for tab: BrowserTab) {348 guard let url = tab.url?.absoluteString, var workspace = activeWorkspace else { return }349 if let index = workspace.favorites.firstIndex(where: { $0.url == url }) {350 workspace.favorites.remove(at: index)351 } else {352 workspace.favorites.append(WorkspaceFavorite(title: tab.displayTitle, url: url))353 }354 saveWorkspaces(workspaces.map { $0.id == workspace.id ? workspace : $0 })355 }356357 // MARK: Split view358359 func toggleSplit() {360 if splitTabID != nil { splitTabID = nil; stateChanged(); return }361 guard let current = selectedTab else { return }362 let candidates = visibleTabs.filter { $0.id != current.id }363 let other = candidates.max(by: { $0.lastActive < $1.lastActive }) ?? newTab(select: false)364 openInSplit(other)365 }366367 func openInSplit(_ tab: BrowserTab) {368 guard tab.id != selectedTabID else { return }369 splitTabID = tab.id370 if tab.url != nil { tab.ensureWebView() }371 stateChanged()372 }373374 func swapSplit() {375 guard let split = splitTab, let primary = selectedTab else { return }376 splitTabID = primary.id377 selectedTabID = split.id378 stateChanged()379 }380381 // MARK: Navigation382383 /// What the results views of `tab` can ask the window to do.384 func searchActions(for tab: BrowserTab) -> SearchActions {385 SearchActions(386 open: { [weak self, weak tab] url, disposition in387 guard let self, let tab else { return }388 switch disposition {389 case .current: tab.load(url)390 case .newTab: self.newTab(url: url, select: true, after: tab)391 case .backgroundTab: self.newTab(url: url, select: false, after: tab)392 }393 },394 search: { [weak tab] text, kind in tab?.search(text, kind: kind) },395 share: { [weak self] url in self?.share(url) },396 saveImage: { [weak self] image in self?.saveImage(image) },397 addToReadingList: isPrivate ? nil : { [weak self] title, url in self?.addToReadingList(title: title, url: url.absoluteString) })398 }399400 func addToReadingList(title: String, url: String) {401 environment.services.library.addToReadingList(title: title, url: url)402 environment.services.localChange()403 toast = L("Added to Reading List")404 }405406 func share(_ url: URL) {407 guard let view = window?.contentView else { return }408 NSSharingServicePicker(items: [url]).show(relativeTo: NSRect(x: view.bounds.midX - 1, y: view.bounds.maxY - 60, width: 2, height: 2), of: view, preferredEdge: .minY)409 }410411 /// Saves a search-result image where the user chooses.412 func saveImage(_ image: ImageResult) {413 guard let url = URL(string: image.imageURL), let window else { return }414 let panel = NSSavePanel()415 panel.nameFieldStringValue = DownloadSafety.sanitize(filename: url.lastPathComponent.isEmpty ? "image" : url.lastPathComponent)416 panel.beginSheetModal(for: window) { [weak self] response in417 guard response == .OK, let destination = panel.url else { return }418 Task { @MainActor in419 do {420 let data = try await RemoteImageLoader.shared.data(from: url)421 try data.write(to: destination, options: .atomic)422 self?.toast = L("Image saved")423 } catch {424 self?.toast = L("The image could not be saved")425 }426 }427 }428 }429430 func navigate(_ text: String, in tab: BrowserTab? = nil, newTab openInNewTab: Bool = false) {431 let settings = environment.settings432 guard let resolved = AddressResolver.resolve(text, engine: settings.activeSearchEngine(), engines: settings.allSearchEngines()) else { return }433 if openInNewTab { newTab(url: resolved.url, select: true); return }434 guard let target = tab ?? selectedTab else { newTab(url: resolved.url, select: true); return }435 target.load(resolved.url)436 stateChanged()437 }438439 func open(_ url: URL, inNewTab: Bool = false) {440 if inNewTab || selectedTab == nil { newTab(url: url, select: true) } else { selectedTab?.load(url) }441 }442443 func focusAddressBar() {444 if focusMode { focusMode = false }445 addressFocusRequest += 1446 }447448 // MARK: TabHost449450 func tab(_ tab: BrowserTab, openTabFor url: URL?, configuration: WKWebViewConfiguration?, inBackground: Bool) -> BrowserTab? {451 newTab(url: configuration == nil ? url : nil, select: !inBackground, after: tab, adopting: configuration)452 }453454 func tabRequestsClose(_ tab: BrowserTab) { close(tab) }455456 func tabStateDidChange(_ tab: BrowserTab) { environment.scheduleSessionSave() }457458 private func stateChanged() {459 updateWindowTitle()460 environment.scheduleSessionSave()461 }462463 func updateWindowTitle() {464 let page = selectedTab?.displayTitle ?? "SP Browser"465 let title = isPrivate ? L("%@ — Private", page) : page466 if window?.title != title { window?.title = title }467 }468469 // MARK: Session470471 func snapshot(frame: String?) -> WindowSnapshot {472 WindowSnapshot(tabs: tabs.map { $0.snapshot() }, selectedTabID: selectedTabID, groups: groups, profileID: profile.profile.id,473 activeWorkspaceID: activeWorkspaceID, frame: frame, sidebarVisible: sidebarVisible)474 }475476 func restore(_ snapshot: WindowSnapshot) {477 groups = snapshot.groups478 sidebarVisible = snapshot.sidebarVisible479 tabs = snapshot.tabs.map { saved in480 var copy = saved481 if !workspaces.contains(where: { $0.id == copy.workspaceID }) { copy.workspaceID = workspaces[0].id }482 if !groups.contains(where: { $0.id == copy.groupID }) { copy.groupID = nil }483 let tab = BrowserTab(snapshot: copy, profile: profile, environment: environment)484 tab.host = self485 return tab486 }487 pruneGroups()488 if let workspace = snapshot.activeWorkspaceID, workspaces.contains(where: { $0.id == workspace }) { activeWorkspaceID = workspace }489 // Only the selected tab is loaded now; the others load when first shown.490 if let selected = tab(id: snapshot.selectedTabID) ?? visibleTabs.first ?? tabs.first { select(selected) }491 }492493 func teardown() {494 tabs.forEach { $0.tearDownWebView(); $0.host = nil }495 tabs = []496 }497}498