Repository Public
1import SwiftUI23// MARK: - Downloads45struct DownloadsButton: View {6 @Bindable var state: BrowserWindowState7 let environment: AppEnvironment8 @State private var pulse = false9 @Environment(\.accessibilityReduceMotion) private var reduceMotion1011 var body: some View {12 let downloads = environment.downloads13 IconButton(symbol: "arrow.down.circle", label: CommandID.showDownloads.title, isActive: state.downloadsVisible || downloads.activeCount > 0) {14 state.downloadsVisible.toggle()15 }16 .overlay {17 if downloads.activeCount > 0 {18 Circle().trim(from: 0, to: max(downloads.overallFraction, 0.03)).stroke(Theme.accent, style: StrokeStyle(lineWidth: 2, lineCap: .round))19 .rotationEffect(.degrees(-90)).frame(width: 22, height: 22).allowsHitTesting(false)20 }21 }22 .scaleEffect(pulse ? 1.25 : 1)23 .onChange(of: downloads.startCounter) {24 guard !reduceMotion else { return }25 withAnimation(.spring(duration: 0.25)) { pulse = true }26 withAnimation(.spring(duration: 0.3).delay(0.25)) { pulse = false }27 }28 .popover(isPresented: $state.downloadsVisible, arrowEdge: .bottom) { DownloadsList(downloads: downloads, showPrivate: state.isPrivate) }29 .accessibilityValue(downloads.activeCount > 0 ? L("%d in progress", downloads.activeCount) : "")30 }31}3233struct DownloadsList: View {34 let downloads: DownloadManager35 let showPrivate: Bool3637 var body: some View {38 // Downloads started in a private window are only listed in private windows.39 let items = downloads.items.filter { showPrivate || !$0.isPrivate }40 VStack(spacing: 0) {41 HStack {42 Text(L("Downloads")).font(.headline)43 Spacer()44 Button(L("Clear")) { downloads.clearInactive() }.controlSize(.small).disabled(items.allSatisfy { $0.isActive || $0.state == .paused })45 }46 .padding(12)47 Divider()48 if items.isEmpty {49 StateView(symbol: "arrow.down.circle", title: L("No downloads"), message: L("Files you download appear here."), compact: true).frame(height: 150)50 } else {51 ScrollView {52 VStack(spacing: 2) { ForEach(items) { DownloadRow(item: $0, downloads: downloads) } }.padding(8)53 }54 .frame(maxHeight: 360)55 }56 }57 .frame(width: 380)58 }59}6061struct DownloadRow: View {62 let item: DownloadItem63 let downloads: DownloadManager6465 var body: some View {66 HStack(spacing: 10) {67 Image(systemName: icon).font(.title3).foregroundStyle(tint).frame(width: 26)68 VStack(alignment: .leading, spacing: 3) {69 Text(item.filename).font(.system(size: 12.5, weight: .medium)).lineLimit(1).truncationMode(.middle)70 if item.state == .inProgress {71 ProgressView(value: min(max(item.fraction, 0), 1)).controlSize(.small)72 .accessibilityLabel(L("Download progress")).accessibilityValue("\(Int(item.fraction * 100)) %")73 }74 Text(status).font(.system(size: 10.5)).foregroundStyle(.secondary).lineLimit(1)75 }76 Spacer(minLength: 0)77 switch item.state {78 case .inProgress:79 IconButton(symbol: "pause.fill", label: L("Pause"), size: 24) { downloads.pause(item) }80 IconButton(symbol: "xmark", label: L("Cancel"), size: 24) { downloads.cancel(item) }81 case .paused:82 IconButton(symbol: "play.fill", label: L("Resume"), size: 24) { Task { await downloads.resume(item) } }.disabled(!item.canResume)83 IconButton(symbol: "xmark", label: L("Cancel"), size: 24) { downloads.cancel(item) }84 case .finished:85 IconButton(symbol: "magnifyingglass", label: L("Show in Finder"), size: 24) { downloads.reveal(item) }.disabled(!item.fileExists)86 default:87 IconButton(symbol: "trash", label: L("Remove from List"), size: 24) { downloads.remove(item) }88 }89 }90 .padding(8)91 .background(RoundedRectangle(cornerRadius: Theme.radiusS).fill(Theme.hover.opacity(0.5)))92 .contentShape(Rectangle())93 .onTapGesture(count: 2) { downloads.open(item) }94 .contextMenu {95 Button(L("Open")) { downloads.open(item) }.disabled(item.state != .finished || !item.fileExists)96 Button(L("Show in Finder")) { downloads.reveal(item) }.disabled(!item.fileExists)97 Button(L("Remove from List")) { downloads.remove(item) }98 }99 .accessibilityElement(children: .contain)100 }101102 private var icon: String {103 switch item.state {104 case .finished: return item.risk == .executable ? "exclamationmark.shield" : "doc.fill"105 case .failed: return "exclamationmark.triangle"106 case .cancelled: return "xmark.circle"107 case .paused: return "pause.circle"108 case .inProgress: return "arrow.down.doc"109 }110 }111112 private var tint: Color {113 switch item.state {114 case .failed: return .orange115 case .finished: return item.risk == .executable ? .orange : Theme.accent116 default: return .secondary117 }118 }119120 private var status: String {121 let source = item.sourceHost.isEmpty ? "" : " · " + item.sourceHost122 switch item.state {123 case .inProgress:124 let total = item.bytesExpected > 0 ? L("%@ of %@", formattedBytes(item.bytesReceived), formattedBytes(item.bytesExpected)) : formattedBytes(item.bytesReceived)125 return total + source126 case .paused: return (item.resumeData == nil ? L("Pausing…") : L("Paused")) + source127 case .finished:128 if !item.fileExists { return L("File moved or deleted") + source }129 return (item.risk == .executable ? L("Can run code — open with care") : L("Completed")) + source130 case .cancelled: return L("Cancelled") + source131 case .failed(let reason): return reason132 }133 }134}135136// MARK: - Sheets137138struct SheetContent: View {139 let state: BrowserWindowState140 let environment: AppEnvironment141142 var body: some View {143 switch state.sheet {144 case .bookmarkEditor: BookmarkEditor(state: state)145 case .clearHistory: ClearHistorySheet(state: state, environment: environment)146 case .saveSession: SaveSessionSheet(state: state, environment: environment)147 case .userAgent: UserAgentSheet(state: state, environment: environment)148 case .none: EmptyView()149 }150 }151}152153struct BookmarkEditor: View {154 let state: BrowserWindowState155 @State private var title = ""156 @State private var url = ""157 @State private var tags = ""158 @State private var folderID = ""159 @State private var existing: Bookmark?160161 var body: some View {162 let folders = state.profile.bookmarks.folders()163 VStack(alignment: .leading, spacing: 14) {164 Text(existing == nil ? L("Add Bookmark") : L("Edit Bookmark")).font(.title3.weight(.semibold))165 Form {166 TextField(L("Title"), text: $title)167 TextField(L("Address"), text: $url)168 TextField(L("Tags"), text: $tags, prompt: Text(L("comma-separated, e.g. work, reading")))169 Picker(L("Folder"), selection: $folderID) {170 Text(L("Top level")).tag("")171 ForEach(folders) { Text($0.title).tag($0.id) }172 }173 }174 .formStyle(.columns)175 HStack {176 if let existing {177 Button(L("Delete"), role: .destructive) { state.profile.bookmarks.delete(id: existing.id); finish() }178 }179 Spacer()180 Button(L("Cancel")) { finish() }.keyboardShortcut(.cancelAction)181 Button(L("Save")) { save() }.keyboardShortcut(.defaultAction).disabled(URL(string: url)?.scheme == nil)182 }183 }184 .padding(20).frame(width: 440)185 .onAppear(perform: load)186 }187188 private func load() {189 let store = state.profile.bookmarks190 let target = state.editingBookmark ?? state.selectedTab?.url.flatMap { store.bookmarks(forURL: $0.absoluteString).first }191 existing = target192 if let target {193 title = target.title; url = target.url ?? ""; tags = target.tags.joined(separator: ", "); folderID = target.parentID ?? ""194 } else if let tab = state.selectedTab {195 title = tab.displayTitle; url = tab.url?.absoluteString ?? ""196 }197 }198199 private func save() {200 let store = state.profile.bookmarks201 let tagList = tags.split(separator: ",").map(String.init)202 let parent = folderID.isEmpty ? nil : folderID203 if var bookmark = existing {204 bookmark.title = title; bookmark.url = url; bookmark.tags = tagList205 store.update(bookmark)206 if bookmark.parentID != parent { store.move(id: bookmark.id, toParent: parent) }207 } else {208 store.add(title: title.isEmpty ? url : title, url: url, parentID: parent, tags: tagList)209 }210 finish()211 }212213 private func finish() {214 state.editingBookmark = nil215 state.bookmarksRevision += 1216 state.sheet = .none217 }218}219220struct ClearHistorySheet: View {221 let state: BrowserWindowState222 let environment: AppEnvironment223 @State private var range = 0224 @State private var alsoSiteData = false225226 var body: some View {227 VStack(alignment: .leading, spacing: 14) {228 Label(L("Clear History"), systemImage: "clock.arrow.circlepath").font(.title3.weight(.semibold))229 Picker(L("Remove"), selection: $range) {230 Text(L("the last hour")).tag(0)231 Text(L("today")).tag(1)232 Text(L("the last 7 days")).tag(2)233 Text(L("all history")).tag(3)234 }235 Toggle(L("Also remove cookies, cache and site data of this profile"), isOn: $alsoSiteData)236 Text(alsoSiteData237 ? L("You will be signed out of websites in the “%@” profile. This cannot be undone.", state.profile.profile.name)238 : L("Only the list of visited pages is removed. This cannot be undone."))239 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)240 HStack {241 Spacer()242 Button(L("Cancel")) { state.sheet = .none }.keyboardShortcut(.cancelAction)243 Button(L("Clear"), role: .destructive) { clear() }244 }245 }246 .padding(20).frame(width: 440)247 }248249 private func clear() {250 let since: Date?251 switch range {252 case 0: since = Date().addingTimeInterval(-3600)253 case 1: since = Calendar.current.startOfDay(for: Date())254 case 2: since = Date().addingTimeInterval(-7 * 86400)255 default: since = nil256 }257 let removed = state.profile.history.clear(since: since)258 state.historyRevision += 1259 let profile = state.profile260 if alsoSiteData {261 Task {262 if let since { await profile.dataStore.removeData(ofTypes: WKWebsiteDataStoreTypes.all, modifiedSince: since) } else { await profile.clearAllSiteData() }263 }264 }265 state.toast = L("%d history entries removed.", removed)266 state.sheet = .none267 }268}269270import WebKit271enum WKWebsiteDataStoreTypes { @MainActor static var all: Set<String> { WKWebsiteDataStore.allWebsiteDataTypes() } }272273struct SaveSessionSheet: View {274 let state: BrowserWindowState275 let environment: AppEnvironment276 @State private var name = ""277278 var body: some View {279 let snapshot = environment.sessionSnapshot()280 VStack(alignment: .leading, spacing: 14) {281 Label(L("Save Session"), systemImage: "tray.and.arrow.down").font(.title3.weight(.semibold))282 Text(L("%d windows and %d tabs will be saved. Private windows are never included.", snapshot.windows.count, snapshot.tabCount))283 .font(.callout).foregroundStyle(.secondary)284 TextField(L("Session name"), text: $name).textFieldStyle(.roundedBorder).onSubmit(save)285 HStack {286 Spacer()287 Button(L("Cancel")) { state.sheet = .none }.keyboardShortcut(.cancelAction)288 Button(L("Save"), action: save).keyboardShortcut(.defaultAction)289 }290 }291 .padding(20).frame(width: 420)292 .onAppear { name = L("Session of %@", Date().formatted(date: .abbreviated, time: .shortened)) }293 }294295 private func save() {296 do {297 try environment.sessionStore.saveNamed(name, snapshot: environment.sessionSnapshot())298 state.toast = L("Session saved.")299 } catch { state.toast = L("The session could not be saved.") }300 state.sheet = .none301 }302}303304struct UserAgentSheet: View {305 let state: BrowserWindowState306 let environment: AppEnvironment307 @State private var agent = ""308309 static let presets: [(String, String)] = [310 ("Safari (macOS)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15"),311 ("Chrome (macOS)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"),312 ("Firefox (macOS)", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:132.0) Gecko/20100101 Firefox/132.0"),313 ("Safari (iPhone)", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"),314 ]315316 var body: some View {317 VStack(alignment: .leading, spacing: 14) {318 Label(L("User Agent"), systemImage: "person.text.rectangle").font(.title3.weight(.semibold))319 Label(L("Changing the user agent only changes how SP Browser introduces itself. Pages are still rendered by WebKit, so sites that receive another browser's name may send code that does not work here, or lock features."), systemImage: "exclamationmark.triangle")320 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)321 TextField(L("Leave empty to use the default"), text: $agent, axis: .vertical).lineLimit(3, reservesSpace: true).textFieldStyle(.roundedBorder)322 HStack {323 Menu(L("Presets")) {324 Button(L("Default (SP Browser)")) { agent = "" }325 ForEach(Self.presets, id: \.0) { preset in Button(preset.0) { agent = preset.1 } }326 }327 .fixedSize()328 Spacer()329 Button(L("Cancel")) { state.sheet = .none }.keyboardShortcut(.cancelAction)330 Button(L("Apply and Reload")) {331 environment.settings.customUserAgent = agent.trimmingCharacters(in: .whitespacesAndNewlines)332 state.sheet = .none333 state.selectedTab?.reload()334 }335 .keyboardShortcut(.defaultAction)336 }337 }338 .padding(20).frame(width: 520)339 .onAppear { agent = environment.settings.customUserAgent }340 }341}342