// SWITCHING, LIKE TABS (owner, 25 Nov 2026; sites/DECISIONS.md "Kept as left", CONTRACT "Switching"): leaving a page // for the list or another site never closes it. The most recent sites stay alive, exactly as left (scroll, typed // words, a video's place), up to a budget measured from this phone's memory; the core's `sites.live` decides which // are let go, so both phones let go the same ones, and only under real pressure. A page the system took back comes // back silently by its saved `interactionState` (kept sealed in the book by `sites.state`), under a still picture of // it held in memory only. Load again and Close this page are separate, deliberate actions. // // Each site's page lives in WebKit's store named by its id (walled off: spike 0, `spike/RESULTS-ios.md`); a quick // visit or a search lives in a store never written to disk. Everything a page asks (an alert, a question, a link out // of the web, a file it gives) is put to Sites' own sheets, headed by the page's address. #if os(iOS) import CottonKit import Network import os import SwiftUI import UIKit import WebKit /// What a page asks of Sites, for the screen to draw in its own sheet. enum SitesAsking: Identifiable { /// An alert, a confirm or a prompt: the page's own words under Sites' head. case panel(kind: String, text: String, defaultText: String?, answer: (Bool, String?) -> Void) /// A link out of the web (a call, a map, a store, a mail): asked first. case exit(URL) /// A file the page gave, held in memory until saved or shared. case file(URL, from: String) /// A result tapped on the search page: the chooser, since a result never opens in a signed-in site by itself. case choose(URL) var id: String { switch self { case .panel(let kind, let text, _, _): "panel-\(kind)-\(text.hashValue)" case .exit(let url): "exit-\(url.absoluteString)" case .file(let url, _): "file-\(url.path)" case .choose(let url): "choose-\(url.absoluteString)" } } } /// One live page: a site's (signed in as it) or a quick visit's. @MainActor @Observable final class SitesPage: NSObject, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate { /// The site's id, or the quick visit's throwaway store name. let id: String private(set) var row: SitesRow? /// A quick visit's or a search's words (strip, dashed name, Close). let quick: SitesOpened.Quick? let web: WKWebView var url: URL? var title: String? var canBack = false var canForward = false var loading = false var progress = 0.0 /// The page did not open: Sites draws its own page, with the address it was going to. var failed: URL? /// One line after a link from another app landed here. var arrived: SitesOpened.Arrived? /// A picture of the page as it was left, shown while a page the system took back loads again. var picture: UIImage? /// What the page is asking now. var asking: SitesAsking? /// A search's throwaway place: the engine's host, whose own links stay; a result elsewhere goes to the chooser. var engineHost: String? /// Page text size, 0.5 to 2. var zoom: CGFloat = 1 { didSet { web.pageZoom = zoom } } /// Told where the page settled and its title, for the list's second line (a site that stays signed in). var report: ((URL, String?) -> Void)? private var reporting: Task? /// The page on screen is a form's answer: its address alone cannot bring it back, so it is not kept. private var posted = false private var watching: [NSKeyValueObservation] = [] private var downloads: [ObjectIdentifier: URL] = [:] /// Whether the tracker list is on this page's web view now. private(set) var blocking = false init(id: String, row: SitesRow?, quick: SitesOpened.Quick?, url: URL?, state: Data?, quickTrackers: Bool = true) { self.id = id self.row = row self.quick = quick let config = WKWebViewConfiguration() if let row, let uuid = UUID(uuidString: row.storeUUID) { config.websiteDataStore = WKWebsiteDataStore(forIdentifier: uuid) } else { config.websiteDataStore = .nonPersistent() } config.preferences.javaScriptCanOpenWindowsAutomatically = true config.allowsInlineMediaPlayback = true config.mediaTypesRequiringUserActionForPlayback = .all config.defaultWebpagePreferences.preferredContentMode = .mobile // Trackers: blocked by WebKit while the site's switch is on (a quick visit: as the core opened it, on by default). let blocking = row?.trackers ?? quickTrackers if blocking, let list = SitesTrackers.list { config.userContentController.add(list) } self.blocking = blocking && SitesTrackers.list != nil web = WKWebView(frame: .zero, configuration: config) web.allowsBackForwardNavigationGestures = true web.isInspectable = SitesPage.inspectable web.scrollView.contentInsetAdjustmentBehavior = .automatic self.url = url super.init() web.navigationDelegate = self web.uiDelegate = self watching = [ web.observe(\.url) { [weak self] web, _ in MainActor.assumeIsolated { self?.moved(to: web.url) } }, web.observe(\.title) { [weak self] web, _ in MainActor.assumeIsolated { self?.title = web.title.flatMap { $0.isEmpty ? nil : $0 } } }, web.observe(\.canGoBack) { [weak self] web, _ in MainActor.assumeIsolated { self?.canBack = web.canGoBack } }, web.observe(\.canGoForward) { [weak self] web, _ in MainActor.assumeIsolated { self?.canForward = web.canGoForward } }, web.observe(\.isLoading) { [weak self] web, _ in MainActor.assumeIsolated { self?.loading = web.isLoading } }, web.observe(\.estimatedProgress) { [weak self] web, _ in MainActor.assumeIsolated { self?.progress = web.estimatedProgress } }, ] if let state { // Back where it was: history, the page and its scroll (spike 0, check 3). web.interactionState = state } else if let url { web.load(URLRequest(url: url)) } } #if COTTON_DEV static let inspectable = true #else static let inspectable = false #endif /// The row changed (renamed, a new home, pinned): the page keeps going. func update(_ row: SitesRow) { self.row = row block(row.trackers) } /// The site's Trackers switch changed: the list is added or taken off this live page, which loads again so the /// switch holds for what is on screen. func block(_ on: Bool) { let wanted = on && SitesTrackers.list != nil guard wanted != blocking, let list = SitesTrackers.list else { return } if wanted { web.configuration.userContentController.add(list) } else { web.configuration.userContentController.remove(list) } blocking = wanted if web.url != nil { web.reload() } } var isQuick: Bool { row == nil } func go(_ url: URL) { failed = nil web.load(URLRequest(url: url)) } /// Load again: a reload, or the address a page that did not open was going to. func again() { if let failing = failed { failed = nil; web.load(URLRequest(url: failing)); return } web.reload() } /// The page as WebKit keeps it now, to bring it back after the system lets it go. var state: Data? { web.interactionState as? Data } /// A still picture of the page, taken as it is left. func takePicture() async { guard web.window != nil, web.bounds.width > 0 else { return } let config = WKSnapshotConfiguration() config.afterScreenUpdates = false picture = try? await web.takeSnapshot(configuration: config) } // MARK: Loading func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { failed = nil } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { picture = nil } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { picture = nil settled() } @objc(webView:didFailProvisionalNavigation:withError:) func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { fail(error) } @objc(webView:didFailNavigation:withError:) func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { fail(error) } /// A load stopped on purpose (a new one began, a link handed elsewhere, a file) is not a failure. private func fail(_ error: Error) { let error = error as NSError if error.domain == NSURLErrorDomain, error.code == NSURLErrorCancelled { return } if error.domain == "WebKitErrorDomain", [102, 204].contains(error.code) { return } picture = nil failed = (error.userInfo[NSURLErrorFailingURLErrorKey] as? URL) ?? url ?? row.flatMap { URL(string: $0.open) } } /// Whether the phone is offline now (a failure says "You're offline" and tries again by itself). static var offline: Bool { !SitesReach.shared.online } private func moved(to now: URL?) { guard let now else { return } url = now } /// The page settled: where it is and its title go to the book a moment later (a site that stays signed in, /// never a form's answer), so it reopens there and the list says which page. private func settled() { guard let report, !posted, let now = web.url, ["http", "https"].contains(now.scheme?.lowercased() ?? "") else { return } reporting?.cancel() reporting = Task { @MainActor [weak self] in try? await Task.sleep(for: .milliseconds(600)) guard let self, !Task.isCancelled else { return } report(now, self.title) } } func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { posted = false } /// The system ended the page's web process: it loads again where it was, saying nothing. func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { SitesLive.shared.webEnded() if webView.backForwardList.currentItem != nil { webView.reload() } else if let url { webView.load(URLRequest(url: url)) } } /// A page asking for a new window (a sign-in's pop-up, a link with a target) opens in this same page: no piles. func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if action.targetFrame == nil, let url = action.request.url { if let engine = engineHost, let host = url.host(), !host.hasSuffix(engine), !engine.hasSuffix(host) { asking = .choose(url) } else { webView.load(action.request) } } return nil } /// The web's own pages load here; anything else is asked first, through the core (`sites.exit`). func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, preferences: WKWebpagePreferences) async -> (WKNavigationActionPolicy, WKWebpagePreferences) { if action.targetFrame?.isMainFrame ?? true { posted = action.request.httpMethod?.uppercased() == "POST" } if action.shouldPerformDownload { return (.download, preferences) } guard let url = action.request.url, let scheme = url.scheme?.lowercased() else { return (.allow, preferences) } if let engine = engineHost, ["http", "https"].contains(scheme), action.navigationType == .linkActivated || action.targetFrame == nil, let host = url.host(), !host.hasSuffix(engine), !engine.hasSuffix(host) { asking = .choose(url) return (.cancel, preferences) } if ["http", "https", "about", "blob", "data"].contains(scheme) { return (.allow, preferences) } if action.targetFrame?.isMainFrame == false, action.navigationType == .other { return (.cancel, preferences) } asking = .exit(url) return (.cancel, preferences) } /// What the page cannot show itself (a file to keep) is fetched into Sites' own viewer. func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse) async -> WKNavigationResponsePolicy { if let http = response.response as? HTTPURLResponse, (http.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment") { return .download } return response.canShowMIMEType ? .allow : .download } func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = self } func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = self } func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String) async -> URL? { let folder = FileManager.default.temporaryDirectory.appendingPathComponent("sites-files-\(UUID().uuidString)", isDirectory: true) try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) let file = folder.appendingPathComponent(suggestedFilename.isEmpty ? "file" : suggestedFilename) downloads[ObjectIdentifier(download)] = file return file } func downloadDidFinish(_ download: WKDownload) { guard let file = downloads.removeValue(forKey: ObjectIdentifier(download)) else { return } asking = .file(file, from: download.originalRequest?.url?.host() ?? url?.host() ?? "") } func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) { downloads.removeValue(forKey: ObjectIdentifier(download)) } // MARK: A page's own words, in Sites' sheet func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async { await withCheckedContinuation { done in asking = .panel(kind: "alert", text: message, defaultText: nil) { _, _ in done.resume() } } } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async -> Bool { await withCheckedContinuation { done in asking = .panel(kind: "confirm", text: message, defaultText: nil) { yes, _ in done.resume(returning: yes) } } } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo) async -> String? { await withCheckedContinuation { done in asking = .panel(kind: "prompt", text: prompt, defaultText: defaultText) { yes, text in done.resume(returning: yes ? (text ?? "") : nil) } } } // MARK: Find on this page /// How many times `words` stand in the page's text, counted in Sites' own script world (the page never sees it). func count(_ words: String) async -> Int { guard !words.isEmpty else { return 0 } let script = "const t=(document.body&&document.body.innerText||'').toLowerCase();const w=q.toLowerCase();let n=0,i=0;while((i=t.indexOf(w,i))!==-1){n++;i+=w.length}return n;" let n = try? await web.callAsyncJavaScript(script, arguments: ["q": words], contentWorld: SitesPage.world) return (n as? Int) ?? (n as? NSNumber)?.intValue ?? 0 } /// The next or the previous match, chosen in the page. func find(_ words: String, back: Bool) async -> Bool { guard !words.isEmpty else { return false } let config = WKFindConfiguration() config.backwards = back config.caseSensitive = false config.wraps = true return (try? await web.find(words, configuration: config))?.matchFound ?? false } static let world = WKContentWorld.world(name: "cotton-sites") } /// Whether the phone is online, so a failed page says whose fault it likely is, and tries again by itself offline. @MainActor @Observable final class SitesReach { static let shared = SitesReach() private(set) var online = true private let monitor = NWPathMonitorBox() private init() { monitor.start { [weak self] online in Task { @MainActor in self?.online = online } } } } /// The path monitor, held apart so the class above stays on the main actor. final class NWPathMonitorBox: @unchecked Sendable { private let monitor = NWPathMonitor() func start(_ changed: @escaping @Sendable (Bool) -> Void) { monitor.pathUpdateHandler = { path in changed(path.status == .satisfied) } monitor.start(queue: DispatchQueue(label: "cotton.sites.reach")) } } /// The live pages, most recent first: as many as this phone's memory comfortably allows (`budget`), the least /// recently used let go first, and only under real pressure (a memory warning, the system ending a web process). @MainActor final class SitesLive { static let shared = SitesLive() private(set) var pages: [String: SitesPage] = [:] /// Pictures of pages let go, held in memory only, shown while they load again. private var pictures: [String: UIImage] = [:] /// How many pages stay alive, from this phone's memory (raised from Comms' four); halved for a while after a warning. private(set) var budget: Int = SitesLive.measured private var warned: NSObjectProtocol? private var figures = SitesFigures(limit: UInt32(SitesLive.measured)) private var said: SitesFigures? var core: (any CottonCalling)? /// The budget for this phone: about one live page per 512 MB of memory past the first 1.5 GB, at least 4, at most 12. static var measured: Int { let gb = Double(ProcessInfo.processInfo.physicalMemory) / 1_073_741_824 return min(12, max(4, Int((gb - 1.5) * 2))) } private init() { warned = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main) { _ in MainActor.assumeIsolated { SitesLive.shared.warning() } } } /// Whether a site has a live page now (the list's dot). func isAlive(_ id: String) -> Bool { pages[id] != nil } /// A site's live page, if the phone still keeps it. func page(_ id: String) -> SitesPage? { pages[id] } /// The page for an opening: the live one, else a new one (back by its saved state when the book kept one). func page(for row: SitesRow?, opened: SitesOpened, link: URL?) -> SitesPage { if let row, let live = pages[row.id] { live.update(row) if let link { live.go(link) } if let arrived = opened.arrived { live.arrived = arrived } return live } let id = row?.id ?? opened.store let state = link == nil ? opened.state.flatMap { Data(base64Encoded: $0) } : nil let page = SitesPage(id: id, row: row, quick: opened.quick, url: URL(string: opened.url), state: state, quickTrackers: opened.trackers ?? true) page.arrived = opened.arrived if state != nil { page.picture = pictures[id] } pictures[id] = nil if let row { page.zoom = zooms[row.id] ?? 1 } pages[id] = page tell() return page } /// Page text size, kept per site while Sites runs. private var zooms: [String: CGFloat] = [:] func keepZoom(_ page: SitesPage) { if let row = page.row { zooms[row.id] = page.zoom } } /// Switched to `id`: the core says which pages stay alive, and the rest are let go. func switched(to id: String?, book: SitesCalls, showing: String?) async { guard let answer = try? await book.live(id, budget: budget) else { return } for gone in answer.letGo where gone != showing { letGo(gone) } } /// A page let go: its picture kept in memory, its state already in the book. func letGo(_ id: String) { guard let page = pages.removeValue(forKey: id) else { return } if let picture = page.picture { pictures[id] = picture } page.report = nil page.web.stopLoading() figures.letGo += 1 tell() } /// Close this page, Sign out, Remove, a site that forgets closed, a quick visit closed: the page ends now. func end(_ id: String) { guard let page = pages.removeValue(forKey: id) else { return } pictures[id] = nil page.report = nil page.web.stopLoading() tell() } /// Every quick visit ends (Sites left the screen with none open, or Sites is quit). func endQuick(except showing: String?) { for (id, page) in pages where page.isQuick && id != showing { end(id) } } /// A memory warning: the budget halves, and every page past it not on screen is let go. private func warning() { figures.warnings += 1 budget = max(2, budget / 2) Task { @MainActor in if let core { await switched(to: nil, book: SitesCalls(core: core), showing: SitesLive.shared.showing) } // The budget comes back after a quiet minute. try? await Task.sleep(for: .seconds(60)) budget = SitesLive.measured } tell() } /// The page on screen now (never let go). var showing: String? func webEnded() { figures.webEnded += 1 tell() } /// The figures on the device's row (`diagnostics.say {sites}`): counts and megabytes, never a name or an address. private func tell() { figures.limit = UInt32(budget) figures.alive = UInt32(pages.count) figures.mostAlive = max(figures.mostAlive, figures.alive) if let footprint = SitesFigures.footprintMB() { figures.peakFootprintMb = max(figures.peakFootprintMb ?? 0, footprint) } if let headroom = SitesFigures.headroomMB() { figures.leastHeadroomMb = min(figures.leastHeadroomMb ?? .max, headroom) } guard figures != said, let core else { return } said = figures struct Body: Encodable { let sites: SitesFigures } let body = Body(sites: figures) Task { _ = try? await core.callJSON("diagnostics.say", body) } } } /// A live page in the screen. The view is the page's own, so switching away and back keeps it exactly as it was. struct SitesWebView: UIViewRepresentable { let page: SitesPage func makeUIView(context: Context) -> UIView { let box = UIView() box.backgroundColor = .clear return box } func updateUIView(_ box: UIView, context: Context) { guard page.web.superview !== box else { return } box.subviews.forEach { $0.removeFromSuperview() } page.web.frame = box.bounds page.web.autoresizingMask = [.flexibleWidth, .flexibleHeight] box.addSubview(page.web) } } #endif