Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

DRM services open in WebKit, where Apple's FairPlay plays them

Victor606ab3724dc8
diff --git a/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift b/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift
new file mode 100644
index 0000000..e531e4e
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift
@@ -0,0 +1,97 @@
+import Foundation
+
+/// Which engine draws a page.
+public enum PageEngine: String, Equatable, Sendable {
+ /// Chromium (CEF): every page, unless a rule below says otherwise.
+ case chromium
+ /// The Mac's own WebKit (WKWebView), for sites whose DRM licence servers turn Cra's
+ /// Chromium away.
+ case webKit
+}
+
+/// Sites that play protected media (DRM) only in WebKit.
+///
+/// Chromium's Widevine CDM works in Cra, but the licence servers of these services also want
+/// Widevine's Verified Media Path: `.sig` files for Cra's binaries, signed with a certificate
+/// Google licenses through paid partners (docs/protected-media.md). Without it Spotify skips
+/// track after track and Disney+ shows error 83 (GitHub #66). WebKit uses Apple's FairPlay,
+/// which macOS gives any app: no certificate, no signing, no fee. So these sites open in a
+/// WKWebView tab, which Safari's user agent makes look like Safari to them.
+///
+/// The rules, as a value so they can be tested without a page:
+/// - A page Cra opens (a tab restored or created, a URL typed, a pinned tab reset) gets
+/// `engine(for:)`: WebKit for a listed site, Chromium for anything else.
+/// - A navigation a Chromium page starts itself (a link, a redirect, history) to a listed site
+/// moves to WebKit before the request goes out (`handoff`), so a sign-in callback's one-time
+/// code is spent in the engine that keeps the session. A POST stays: its body can't move.
+/// - A WebKit page stays in WebKit wherever it navigates by itself: sign-in goes through
+/// other sites (accounts.google.com, appleid.apple.com) and has to come back to the same
+/// cookies. Cra's own navigations (the URL bar) pick the engine again.
+public struct ProtectedMediaSites: Equatable, Sendable {
+ /// The web players of services that need Verified Media Path in Chromium on a Mac and play
+ /// in Safari. A host matches itself and its subdomains. Players only, not whole domains:
+ /// other sites send their "Sign in with Spotify/Tidal/Deezer" through accounts.spotify.com,
+ /// login.tidal.com and connect.deezer.com, and those must finish in the engine they started in.
+ public static let defaultHosts: [String] = [
+ "open.spotify.com",
+ "netflix.com",
+ "disneyplus.com",
+ // Max signs in on its own hosts and sends play.max.com on to www.hbomax.com; no other site
+ // signs in with Max, so the whole domains.
+ "max.com", "hbomax.com",
+ "primevideo.com",
+ "hulu.com",
+ "paramountplus.com",
+ "peacocktv.com",
+ "tv.apple.com", "music.apple.com",
+ "listen.tidal.com",
+ "www.deezer.com",
+ ]
+
+ /// Off: every page is Chromium's, as before.
+ public var isEnabled: Bool
+ /// Lower-cased hosts without a leading dot.
+ public private(set) var hosts: [String]
+
+ /// `extraHosts` add to the list (tests, a user's own entries); `removedHosts` take sites
+ /// off it.
+ public init(isEnabled: Bool = true, extraHosts: [String] = [], removedHosts: [String] = []) {
+ self.isEnabled = isEnabled
+ let removed = Set(removedHosts.compactMap(Self.normalizedHost))
+ var seen = Set<String>()
+ hosts = (Self.defaultHosts + extraHosts).compactMap(Self.normalizedHost)
+ .filter { !removed.contains($0) && seen.insert($0).inserted }
+ }
+
+ /// The engine a page Cra opens at `url` gets.
+ public func engine(for url: String) -> PageEngine {
+ guard isEnabled, let host = Self.webHost(of: url) else { return .chromium }
+ return hosts.contains { host == $0 || host.hasSuffix("." + $0) } ? .webKit : .chromium
+ }
+
+ /// A navigation a page started itself: the engine it has to move to, or nil to stay.
+ /// `method` is the request's HTTP method.
+ public func handoff(from current: PageEngine, to url: String, method: String) -> PageEngine? {
+ guard current == .chromium, method.uppercased() == "GET", engine(for: url) == .webKit else { return nil }
+ return .webKit
+ }
+
+ /// The host of an http(s) URL, lower-cased; nil for any other scheme (about:, chrome:,
+ /// file:, data:, view-source:), which only Chromium shows.
+ static func webHost(of url: String) -> String? {
+ guard let c = URLComponents(string: url.trimmingCharacters(in: .whitespaces)),
+ let scheme = c.scheme?.lowercased(), scheme == "https" || scheme == "http",
+ let host = c.host?.lowercased(), !host.isEmpty else { return nil }
+ return host.hasSuffix(".") ? String(host.dropLast()) : host
+ }
+
+ /// "Open.Spotify.com", " spotify.com ", ".spotify.com" → "spotify.com"; a URL gives its host.
+ static func normalizedHost(_ entry: String) -> String? {
+ var s = entry.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+ if s.contains("://"), let host = webHost(of: s) { s = host }
+ while s.hasPrefix(".") { s.removeFirst() }
+ while s.hasSuffix(".") { s.removeLast() }
+ guard !s.isEmpty, !s.contains("/"), !s.contains(" ") else { return nil }
+ return s
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ProtectedMediaTests.swift b/Packages/CraCore/Tests/CraCoreTests/ProtectedMediaTests.swift
new file mode 100644
index 0000000..e9299ed
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/ProtectedMediaTests.swift
@@ -0,0 +1,90 @@
+import CraCore
+import Foundation
+import Testing
+
+/// Which engine a page gets: WebKit (FairPlay) for the DRM services, Chromium for the rest.
+struct ProtectedMediaTests {
+ let sites = ProtectedMediaSites()
+
+ @Test(arguments: [
+ "https://open.spotify.com/",
+ "https://open.spotify.com/track/1?si=x",
+ "https://www.netflix.com/browse",
+ "https://NETFLIX.com/title/1",
+ "https://www.disneyplus.com/",
+ "https://play.max.com/",
+ "https://www.hbomax.com/",
+ "https://auth.max.com/login",
+ "https://www.primevideo.com/",
+ "https://tv.apple.com/",
+ "https://music.apple.com/us/browse",
+ "https://listen.tidal.com/",
+ "http://www.hulu.com/",
+ "https://www.netflix.com./browse",
+ ])
+ func servicesOpenInWebKit(url: String) {
+ #expect(sites.engine(for: url) == .webKit)
+ }
+
+ @Test(arguments: [
+ "https://www.google.com/search?q=spotify.com",
+ "https://example.com/?u=https://open.spotify.com/",
+ "https://notspotify.com/",
+ "https://spotify.com.evil.example/",
+ "https://www.apple.com/",
+ "https://support.apple.com/",
+ "https://appleid.apple.com/auth/authorize",
+ "https://accounts.spotify.com/authorize?client_id=x",
+ "https://www.spotify.com/us/premium/",
+ "https://login.tidal.com/authorize",
+ "https://connect.deezer.com/oauth/auth.php",
+ "https://www.youtube.com/watch?v=x",
+ "about:blank",
+ "chrome://settings",
+ "view-source:https://open.spotify.com/",
+ "file:///Users/x/spotify.com.html",
+ "data:text/html,netflix.com",
+ "",
+ "netflix.com",
+ ])
+ func everythingElseStaysInChromium(url: String) {
+ #expect(sites.engine(for: url) == .chromium)
+ }
+
+ @Test func offMeansChromiumEverywhere() {
+ let off = ProtectedMediaSites(isEnabled: false)
+ #expect(off.engine(for: "https://open.spotify.com/") == .chromium)
+ #expect(off.handoff(from: .chromium, to: "https://open.spotify.com/", method: "GET") == nil)
+ }
+
+ @Test func listCanGrowAndShrink() {
+ let custom = ProtectedMediaSites(extraHosts: [" 127.0.0.1 ", "https://Stream.Example.org/path", ".crunchyroll.com."],
+ removedHosts: ["NETFLIX.com"])
+ #expect(custom.engine(for: "http://127.0.0.1:8123/page.html") == .webKit)
+ #expect(custom.engine(for: "https://stream.example.org/") == .webKit)
+ #expect(custom.engine(for: "https://example.org/") == .chromium)
+ #expect(custom.engine(for: "https://www.crunchyroll.com/") == .webKit)
+ #expect(custom.engine(for: "https://www.netflix.com/") == .chromium)
+ #expect(custom.engine(for: "https://open.spotify.com/") == .webKit)
+ #expect(custom.engine(for: "https://open.spotify.com.") == .webKit)
+ }
+
+ @Test func entriesAreCleanedAndDeduplicated() {
+ let custom = ProtectedMediaSites(extraHosts: ["open.spotify.com", "OPEN.SPOTIFY.COM", "", " ", "a b", "x.com/path"])
+ #expect(custom.hosts.filter { $0 == "open.spotify.com" }.count == 1)
+ #expect(custom.hosts.count == ProtectedMediaSites.defaultHosts.count)
+ }
+
+ /// A Chromium page's own navigation to a service moves before the request goes out; a POST
+ /// can't move its body, and a WebKit page never leaves by itself (sign-in round trips).
+ @Test func handoffRules() {
+ #expect(sites.handoff(from: .chromium, to: "https://www.netflix.com/browse", method: "GET") == .webKit)
+ #expect(sites.handoff(from: .chromium, to: "https://www.netflix.com/browse", method: "get") == .webKit)
+ #expect(sites.handoff(from: .chromium, to: "https://open.spotify.com/callback", method: "POST") == nil)
+ // Another site's "Sign in with Spotify" finishes where it started.
+ #expect(sites.handoff(from: .chromium, to: "https://accounts.spotify.com/authorize?client_id=x", method: "GET") == nil)
+ #expect(sites.handoff(from: .chromium, to: "https://www.google.com/", method: "GET") == nil)
+ #expect(sites.handoff(from: .webKit, to: "https://accounts.google.com/o/oauth2", method: "GET") == nil)
+ #expect(sites.handoff(from: .webKit, to: "https://open.spotify.com/", method: "GET") == nil)
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index c67d0c8..b67d1d6 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -444,7 +444,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
mainWindows.removeAll { $0 === c }
c.tearDown()
store.removeWindow(c.windowID)
- if c.isIncognito, !mainWindows.contains(where: \.isIncognito) { CraCEFRuntime.endIncognitoSession() }
+ if c.isIncognito, !mainWindows.contains(where: \.isIncognito) {
+ CraCEFRuntime.endIncognitoSession()
+ WebKitStores.endIncognitoSession()
+ }
// AppKit makes the next window key on its own; until then actions go to the frontmost.
if let front = NSApp.orderedWindows.compactMap({ w in mainWindows.first { $0.window === w } }).first {
store.activeWindowID = front.windowID
@@ -692,6 +695,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if let v = dict["banner"] { SoftwareUpdater.shared.debugUpdated(v == "none" ? nil : v); return }
if let v = dict["bannerReady"] { SoftwareUpdater.shared.debugReady(v == "none" ? nil : v); return }
if dict["switcher"] != nil { main.debugTabSwitcher(); return }
+ // The sidebar player without the pointer: play/pause/next/previous/pip on the newest
+ // card ("state" only logs), then its cards: "Cra nowPlaying[<label>] <host> playing=… prev=… next=… video=… pip=…".
+ if let op = dict["nowPlaying"], let np = main.browsers.nowPlaying {
+ let label = dict["label"].map { "[\($0)]" } ?? ""
+ let actions: [String: NowPlaying.Action] = ["toggle": .togglePlayback, "next": .next, "previous": .previous,
+ "pip": .pictureInPicture, "dismiss": .dismiss]
+ if let action = actions[op], let id = np.entries.last?.id { main.browsers.performNowPlaying(id, action) }
+ for e in np.entries {
+ let host = CraLog.host(main.browsers.runtime(for: e.id)?.browser.currentURL ?? "")
+ NSLog("Cra nowPlaying%@ %@ playing=%d prev=%d next=%d video=%d pip=%d", label, host, e.playing ? 1 : 0, e.hasPrevious ? 1 : 0,
+ e.hasNext ? 1 : 0, e.hasVideo ? 1 : 0, np.pictureInPicture.contains(e.id) ? 1 : 0)
+ }
+ if np.entries.isEmpty { NSLog("Cra nowPlaying%@ none", label) }
+ return
+ }
if dict["themeEditor"] != nil { main.showSpaceStyleEditor(space: store.focusedSpace); return }
if dict["jumpPill"] != nil { SpaceListView.jumpToSelected(for: main.sidebarUI, space: store.focusedSpaceID); return }
if let f = dict["folderPreview"] {
diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swift
index 071ffff..a59b9ce 100644
--- a/Sources/Cra/App/main.swift
+++ b/Sources/Cra/App/main.swift
@@ -32,6 +32,8 @@ MainActor.assumeIsolated {
let profile = AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true)
if CredentialImport.hasPending { CredentialImport.applyPending(root: AppPaths.chromiumCache) }
CredentialImport.repairImportedCookies(profileDir: profile)
+ // WebKit's data for a deleted profile goes with its Chromium folder (PageEngines).
+ ProfileCleanup.removed = { name in MainActor.assumeIsolated { WebKitStores.removeProfile(folderName: name) } }
ProfileCleanup.run()
}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 704195d..6710d89 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -135,9 +135,10 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
log(tabID, "opens a page for \(site(tab.url, tabID))")
if sleptTabs.remove(tabID) != nil { Perf.begin(.tabWake, tabID.uuidString) }
+ // Chromium, or WebKit for a DRM service (ProtectedMediaSites).
let browser = Perf.time(.pageCreate) {
- CraBrowser(frame: container.bounds, url: tab.url, delegate: self, incognito: store.isIncognito(item: tabID),
- profilePath: store.profilePath(item: tabID))
+ PageEngines.makeBrowser(frame: container.bounds, url: tab.url, delegate: self, incognito: store.isIncognito(item: tabID),
+ profilePath: store.profilePath(item: tabID))
}
return register(browser: browser, tabID: tabID)
}
@@ -155,10 +156,10 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
return rt
}
- /// Popup host: a browser shell CEF will fill with window.open content.
- func makePopupHost(for tabID: UUID) -> CraBrowser {
- let browser = CraBrowser(frame: container.bounds, url: nil, delegate: self, incognito: store.isIncognito(item: tabID),
- profilePath: store.profilePath(item: tabID))
+ /// Popup host: a browser shell its opener's engine will fill with window.open content.
+ func makePopupHost(for tabID: UUID, opener: CraBrowser) -> CraBrowser {
+ let browser = PageEngines.makeBrowser(frame: container.bounds, url: nil, delegate: self, incognito: store.isIncognito(item: tabID),
+ profilePath: store.profilePath(item: tabID), opener: opener)
register(browser: browser, tabID: tabID)
return browser
}
@@ -738,7 +739,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
if active { np.pictureInPicture.insert(id) } else { np.pictureInPicture.remove(id) }
}
log(id, active ? "enters Picture in Picture" : "leaves Picture in Picture")
- if active {
+ // WebKit's video goes to the system's own Picture in Picture window, with its own controls.
+ if browser is WebKitBrowser {
+ } else if active {
// The floating window's hover controls act on this tab.
PictureInPictureChrome.shared.actions = PictureInPictureActions(
backToTab: { [weak self] in self?.bringToFront(id) },
@@ -1023,11 +1026,37 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
let sourceSpace = tabID(of: browser).flatMap { store.spaceID(ofItem: $0) }
let tab = store.createTab(url: url, in: sourceSpace, select: !background, window: windowID)
if background { store.markUnread(tab.id, true) }
- let host = makePopupHost(for: tab.id)
+ let host = makePopupHost(for: tab.id, opener: browser)
if !background { show(tab.id, focus: true) }
return host
}
+ /// A page about to navigate where the other engine has to show it (ProtectedMediaSites): the
+ /// navigation stops here and the tab's page opens again in that engine, at that address.
+ func browser(_ browser: CraBrowser, handsOffNavigationToURL url: String, method: String) -> Bool {
+ guard let id = tabID(of: browser), let engine = PageEngines.handoffTarget(from: browser, to: url, method: method) else { return false }
+ log(id, "moves to \(engine == .webKit ? "WebKit" : "Chromium") for \(site(url, id, browser))")
+ // Not from inside Chromium's navigation callback: the page closes a turn later.
+ DispatchQueue.main.async { [weak self, weak browser] in
+ guard let self, let browser else { return }
+ self.reopen(id, at: url, replacing: browser)
+ }
+ return true
+ }
+
+ /// The tab's page closes and opens again at `url`, in the engine the address gets, on screen
+ /// where it was (its split pane, the focus).
+ private func reopen(_ id: UUID, at url: String, replacing old: CraBrowser) {
+ guard runtimes[id]?.browser === old, store.item(id)?.isTab == true else { return }
+ let visible = visibleTabIDs
+ let focused = visibleTabID
+ let hadFocus = old.containerView.window?.firstResponder.map { r in (r as? NSView)?.isDescendant(of: old.containerView) ?? false } ?? false
+ store.updateTab(id, url: url)
+ unload(id)
+ ensureRuntime(for: id)
+ if visible.contains(id) { show(visible, focused: focused, focus: hadFocus || focused == id) }
+ }
+
func browser(_ browser: CraBrowser, opensPeekForURL url: String, shiftClick: Bool, newTab: Bool) -> Bool {
guard let id = tabID(of: browser), !browser.isIncognito else { return false }
return delegate?.browserManagerOpensPeek(url: url, fromTab: id, pageURL: browser.currentURL, shiftClick: shiftClick, newTab: newTab) ?? false
diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swift
index 1eeac75..12cfdd8 100644
--- a/Sources/Cra/Services/Persistence.swift
+++ b/Sources/Cra/Services/Persistence.swift
@@ -9,12 +9,16 @@ enum ProfileCleanup {
file.saveNow(Array(Set(file.load(or: { [] }) + [directoryName])))
}
+ /// Told each folder name removed (WebKit's data for that profile goes too).
+ nonisolated(unsafe) static var removed: ((String) -> Void)?
+
/// Call before Chromium initializes.
static func run() {
let names = file.load(or: { [] })
guard !names.isEmpty else { return }
for name in names where name.hasPrefix("Profile ") {
try? FileManager.default.removeItem(at: AppPaths.chromiumCache.appendingPathComponent(name, isDirectory: true))
+ removed?(name)
}
file.saveNow([])
}
diff --git a/Sources/Cra/Services/WebKit/PageEngines.swift b/Sources/Cra/Services/WebKit/PageEngines.swift
new file mode 100644
index 0000000..be9e0d8
--- /dev/null
+++ b/Sources/Cra/Services/WebKit/PageEngines.swift
@@ -0,0 +1,49 @@
+import AppKit
+import CraCEF
+
+/// Which engine draws a page, and the factory every page browser comes from
+/// (ProtectedMediaSites has the rules; docs/protected-media.md the why).
+@MainActor
+enum PageEngines {
+ /// Read once per launch. `defaults write dk.kildahl.cra webKitProtectedMedia -bool NO` turns
+ /// it off (every page Chromium's again); `webKitProtectedMediaHosts` and
+ /// `webKitProtectedMediaRemovedHosts` (string arrays) change the list. A test instance sets
+ /// CRA_WEBKIT_DRM=0|1 and CRA_WEBKIT_HOSTS=<host,host> (the scenarios' 127.0.0.1).
+ static let sites: ProtectedMediaSites = {
+ let env = ProcessInfo.processInfo.environment
+ let defaults = UserDefaults.standard
+ let enabled = env["CRA_WEBKIT_DRM"].map { $0 != "0" } ?? (defaults.object(forKey: "webKitProtectedMedia") as? Bool ?? true)
+ let extra = (env["CRA_WEBKIT_HOSTS"] ?? "").split(separator: ",").map(String.init)
+ + (defaults.stringArray(forKey: "webKitProtectedMediaHosts") ?? [])
+ let removed = defaults.stringArray(forKey: "webKitProtectedMediaRemovedHosts") ?? []
+ return ProtectedMediaSites(isEnabled: enabled, extraHosts: extra, removedHosts: removed)
+ }()
+
+ static func engine(of browser: CraBrowser) -> PageEngine { browser is WebKitBrowser ? .webKit : .chromium }
+
+ /// A page browser for `url` in the engine the rules pick. A popup host (`url` nil) takes its
+ /// opener's engine: WebKit can only hand a popup to a web view it made, CEF to a CraBrowser.
+ static func makeBrowser(frame: NSRect, url: String?, delegate: CraBrowserDelegate?, incognito: Bool,
+ profilePath: String?, opener: CraBrowser? = nil) -> CraBrowser {
+ let engine = url.map { sites.engine(for: $0) } ?? opener.map(engine(of:)) ?? .chromium
+ switch engine {
+ case .webKit:
+ return WebKitBrowser(frame: frame, url: url, delegate: delegate, incognito: incognito, profilePath: profilePath)
+ case .chromium:
+ return CraBrowser(frame: frame, url: url, delegate: delegate, incognito: incognito, profilePath: profilePath)
+ }
+ }
+
+ /// Whether a navigation `browser` is about to make has to happen in the other engine.
+ /// Chromium asks for every main-frame request (CraCEF's OnBeforeBrowse); WebKit only for
+ /// addresses Cra loads (-loadURL:), never for the page's own navigations.
+ static func handoffTarget(from browser: CraBrowser, to url: String, method: String) -> PageEngine? {
+ let current = engine(of: browser)
+ switch current {
+ case .chromium: return sites.handoff(from: current, to: url, method: method)
+ case .webKit:
+ let wanted = sites.engine(for: url)
+ return wanted == current ? nil : wanted
+ }
+ }
+}
diff --git a/Sources/Cra/Services/WebKit/WebKitBrowser.swift b/Sources/Cra/Services/WebKit/WebKitBrowser.swift
new file mode 100644
index 0000000..9361bba
--- /dev/null
+++ b/Sources/Cra/Services/WebKit/WebKitBrowser.swift
@@ -0,0 +1,1108 @@
+import AppKit
+import CraCEF
+import WebKit
+
+/// A page drawn by the Mac's WebKit instead of Chromium, for the sites in ProtectedMediaSites:
+/// WebKit plays their DRM with Apple's FairPlay, which needs no certificate (Chromium's Widevine
+/// needs a paid Verified Media Path one for these services).
+///
+/// It is a CraBrowser, so BrowserManager, split view, Little Windows, Peek, tab sleeping, the
+/// tab switcher, the sidebar player and Picture in Picture drive it exactly like a Chromium page:
+/// it hosts like Alloy (its view in `containerView`, no `hostWindow`), sends the same delegate
+/// callbacks, and answers the few DevTools Protocol methods Cra calls (`sendDevToolsMethod`) from
+/// WebKit's own API. What WebKit can't do answers an error, and each caller already has a path
+/// for that (a page Chromium can't discard closes instead, for one).
+///
+/// Not here: Chrome extensions (WebKit pages have none), Chromium's site settings, content
+/// blocking and HTTPS-Only (Chromium's network stack), Chrome's DevTools (WebKit's Web Inspector
+/// opens instead). Cookies are WebKit's own, per profile (WebKitStores): a service is signed into
+/// once more the first time it opens here.
+final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate {
+ private let container: NSView
+ private(set) var webView: CraWebView?
+ private let incognitoPage: Bool
+ private let profile: String?
+ /// The address before the web view has one (a page not created yet, a failed load).
+ private var pendingURL: String
+ private var failedURL: String?
+ private var created = false
+ private var closed = false
+ private var pageClosedItself = false
+ private var committed = false
+ private var lastStatus = 0
+ private var lastLoadingState: [Bool] = []
+ private var observations: [NSKeyValueObservation] = []
+ private var observesPlayingAudio = false
+ private var playing = false
+ private var audible = false
+ private var audibleOff: DispatchWorkItem?
+ private var capturing = false
+ private var inPictureInPicture = false
+ private var pictureInPicturePlaying = false
+ private var hoverURL = ""
+ private var findQuery = ""
+ private var findCount = 0
+ private var findIndex = 0
+ private var messages: ScriptMessageProxy?
+ /// Downloads in flight, with their info for the sidebar.
+ private var downloads: [ObjectIdentifier: (download: WKDownload, info: CraDownloadInfo, progress: NSKeyValueObservation?)] = [:]
+ private static var nextDownloadID: UInt32 = 0x7000_0000
+
+ /// Cra's isolated world: PageScript's own script, plus what WebKit doesn't report natively.
+ static let world = WKContentWorld.world(name: PageScript.world)
+
+ override init(frame: NSRect, url: String?, delegate: CraBrowserDelegate?, incognito: Bool, profilePath: String?) {
+ container = NSView(frame: frame)
+ incognitoPage = incognito
+ profile = incognito ? nil : profilePath
+ pendingURL = url ?? ""
+ super.init()
+ self.delegate = delegate
+ container.wantsLayer = true
+ container.autoresizesSubviews = true
+ container.layer?.backgroundColor = CraBrowser.pageCanvasColor.cgColor
+ // nil: a popup host, filled by adoptPopup(configuration:) when WebKit opens the popup.
+ if let url { MainActor.assumeIsolated { makeWebView(configuration: nil); load(url) } }
+ }
+
+ override convenience init(frame: NSRect, url: String?, delegate: CraBrowserDelegate?) {
+ self.init(frame: frame, url: url, delegate: delegate, incognito: false, profilePath: nil)
+ }
+
+ override convenience init(frame: NSRect, url: String?, delegate: CraBrowserDelegate?, incognito: Bool) {
+ self.init(frame: frame, url: url, delegate: delegate, incognito: incognito, profilePath: nil)
+ }
+
+ // MARK: Web view
+
+ @MainActor
+ private func makeWebView(configuration given: WKWebViewConfiguration?) {
+ let configuration = given ?? WKWebViewConfiguration()
+ if given == nil {
+ configuration.websiteDataStore = WebKitStores.store(profilePath: profile, incognito: incognitoPage)
+ }
+ // A popup's configuration is its opener's copy: it gets its own scripts and handler.
+ let content = WKUserContentController()
+ content.addUserScript(WKUserScript(source: PageScript.mainWorld, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .page))
+ content.addUserScript(WKUserScript(source: PageScript.isolatedWorld + Self.isolatedAddOn, injectionTime: .atDocumentStart,
+ forMainFrameOnly: false, in: Self.world))
+ let proxy = ScriptMessageProxy(owner: self)
+ content.add(proxy, contentWorld: Self.world, name: "cra")
+ messages = proxy
+ configuration.userContentController = content
+ configuration.preferences.isElementFullscreenEnabled = true
+ // Off for apps other than Safari: video.requestPictureInPicture() answered NotSupportedError,
+ // so the sidebar player's button and auto Picture in Picture did nothing.
+ if configuration.preferences.responds(to: NSSelectorFromString("_setAllowsPictureInPictureMediaPlayback:")) {
+ configuration.preferences.setValue(true, forKey: "allowsPictureInPictureMediaPlayback")
+ }
+ configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
+ configuration.applicationNameForUserAgent = Self.safariProduct
+
+ let web = CraWebView(frame: container.bounds, configuration: configuration)
+ web.owner = self
+ web.autoresizingMask = [.width, .height]
+ web.navigationDelegate = self
+ web.uiDelegate = self
+ web.allowsBackForwardNavigationGestures = true
+ web.allowsMagnification = true
+ web.isInspectable = true
+ container.addSubview(web)
+ webView = web
+ created = true
+ observe(web)
+ }
+
+ /// The popup WebKit opens for window.open in an opener page: it must be a web view made with
+ /// WebKit's configuration, so the popup keeps window.opener (sign-in windows post back).
+ @MainActor
+ func adoptPopup(configuration: WKWebViewConfiguration) -> WKWebView? {
+ guard webView == nil, !closed else { return nil }
+ makeWebView(configuration: configuration)
+ return webView
+ }
+
+ /// Safari's own product token, so the services see Safari and pick FairPlay (Spotify, Netflix
+ /// and Disney+ refuse browsers they don't know). Safari's version is the Mac's.
+ static let safariProduct: String = {
+ let paths = ["/Applications/Safari.app", "/System/Volumes/Preboot/Cryptexes/App/System/Applications/Safari.app"]
+ let version = paths.lazy.compactMap { Bundle(path: $0)?.infoDictionary?["CFBundleShortVersionString"] as? String }.first
+ let os = ProcessInfo.processInfo.operatingSystemVersion
+ let fallback = os.majorVersion >= 26 ? "\(os.majorVersion).0" : "18.0"
+ let parts = (version ?? fallback).split(separator: ".")
+ return "Version/\(parts.prefix(2).joined(separator: ".")) Safari/605.1.15"
+ }()
+
+ @MainActor
+ private func observe(_ web: WKWebView) {
+ observations = [
+ web.observe(\.title, options: [.new]) { [weak self] web, _ in
+ MainActor.assumeIsolated {
+ // A page starting to load has no title yet; Chromium says nothing until it has one.
+ guard let self, !self.closed, let title = web.title, !title.isEmpty else { return }
+ self.delegate?.browser(self, didChangeTitle: title)
+ }
+ },
+ web.observe(\.url, options: [.new]) { [weak self] web, _ in
+ MainActor.assumeIsolated {
+ guard let self, !self.closed, let url = web.url?.absoluteString else { return }
+ self.delegate?.browser(self, didChangeURL: url)
+ }
+ },
+ web.observe(\.isLoading, options: [.new]) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.reportLoading() }
+ },
+ web.observe(\.canGoBack, options: [.new]) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.reportLoading() }
+ },
+ web.observe(\.canGoForward, options: [.new]) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.reportLoading() }
+ },
+ web.observe(\.estimatedProgress, options: [.new]) { [weak self] web, _ in
+ MainActor.assumeIsolated {
+ guard let self, !self.closed, web.isLoading else { return }
+ self.delegate?.browser(self, didChangeProgress: web.estimatedProgress)
+ }
+ },
+ web.observe(\.themeColor, options: [.new]) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.reportThemeColor() }
+ },
+ web.observe(\.cameraCaptureState, options: [.new]) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.reportCapture() }
+ },
+ web.observe(\.microphoneCaptureState, options: [.new]) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.reportCapture() }
+ },
+ ]
+ // WebKit's own "playing audio" (Safari's tab speaker), when this macOS has it; the
+ // isolated world's media events stand in otherwise.
+ if web.responds(to: NSSelectorFromString("_isPlayingAudio")) {
+ web.addObserver(self, forKeyPath: "_isPlayingAudio", options: [.new], context: nil)
+ observesPlayingAudio = true
+ }
+ }
+
+ override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?,
+ context: UnsafeMutableRawPointer?) {
+ guard keyPath == "_isPlayingAudio", let web = object as? WKWebView else {
+ return super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
+ }
+ MainActor.assumeIsolated { setPlaying((web.value(forKey: "_isPlayingAudio") as? Bool) ?? false) }
+ }
+
+ // MARK: State
+
+ override var containerView: NSView { container }
+ override var hostWindow: NSWindow? { nil }
+ override var currentURL: String {
+ MainActor.assumeIsolated { failedURL ?? webView?.url?.absoluteString ?? pendingURL }
+ }
+ override var currentTitle: String { MainActor.assumeIsolated { webView?.title ?? "" } }
+ override var isLoading: Bool { MainActor.assumeIsolated { webView?.isLoading ?? false } }
+ override var hasCommittedLoad: Bool { committed }
+ override var canGoBack: Bool { MainActor.assumeIsolated { webView?.canGoBack ?? false } }
+ override var canGoForward: Bool { MainActor.assumeIsolated { webView?.canGoForward ?? false } }
+ override var isCreated: Bool { created && !closed }
+ override var isClosed: Bool { closed }
+ override var closedByPage: Bool { pageClosedItself }
+ override var hasDevTools: Bool { false }
+ override var isIncognito: Bool { incognitoPage }
+ override var profilePath: String? { profile }
+ override var isInPictureInPicture: Bool { inPictureInPicture }
+ override var isPictureInPicturePlaying: Bool { pictureInPicturePlaying }
+ override var isCapturingMedia: Bool { capturing }
+ override var isAudible: Bool { audible }
+
+ /// Once per change of the three, as CEF's OnLoadingStateChange (each of them is observed).
+ @MainActor
+ private func reportLoading() {
+ guard let web = webView, !closed else { return }
+ let now = [web.isLoading, web.canGoBack, web.canGoForward]
+ guard now != lastLoadingState else { return }
+ lastLoadingState = now
+ delegate?.browser(self, didChangeLoading: web.isLoading, canGoBack: web.canGoBack, canGoForward: web.canGoForward)
+ }
+
+ @MainActor
+ private func reportCapture() {
+ guard let web = webView, !closed else { return }
+ let now = web.cameraCaptureState == .active || web.microphoneCaptureState == .active
+ guard now != capturing else { return }
+ capturing = now
+ delegate?.browser?(self, didChangeMediaCapture: now)
+ }
+
+ /// Chrome's audible state: on as sound starts, off 2 s after it stops.
+ @MainActor
+ private func setPlaying(_ now: Bool) {
+ playing = now
+ audibleOff?.cancel()
+ audibleOff = nil
+ if now {
+ guard !audible else { return }
+ audible = true
+ delegate?.browser?(self, didChangeAudible: true)
+ } else if audible {
+ let work = DispatchWorkItem { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self, !self.playing, self.audible, !self.closed else { return }
+ self.audible = false
+ self.delegate?.browser?(self, didChangeAudible: false)
+ }
+ }
+ audibleOff = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: work)
+ }
+ }
+
+ @MainActor
+ private func reportThemeColor() {
+ guard let web = webView, !closed else { return }
+ if let color = web.themeColor, let hex = Self.hex(color) {
+ delegate?.browser(self, didReportThemeColor: hex)
+ }
+ }
+
+ // MARK: Navigation
+
+ override func loadURL(_ url: String) {
+ MainActor.assumeIsolated {
+ guard !closed else { return }
+ // Cra's own navigation (the URL bar, a pinned tab's home) to a page the other engine
+ // shows: the tab's page moves there.
+ if delegate?.browser?(self, handsOffNavigationToURL: url, method: "GET") == true { return }
+ load(url)
+ }
+ }
+
+ @MainActor
+ private func load(_ url: String) {
+ guard let web = webView else { pendingURL = url; return }
+ failedURL = nil
+ pendingURL = url
+ guard let u = URL(string: url) ?? URL(string: url.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) ?? "") else { return }
+ web.load(URLRequest(url: u))
+ }
+
+ override func goBack() { MainActor.assumeIsolated { _ = webView?.goBack() } }
+ override func goForward() { MainActor.assumeIsolated { _ = webView?.goForward() } }
+ override func reload() {
+ MainActor.assumeIsolated {
+ if let failedURL { load(failedURL) } else { _ = webView?.reload() }
+ }
+ }
+ override func reloadIgnoringCache() {
+ MainActor.assumeIsolated {
+ if let failedURL { load(failedURL) } else { _ = webView?.reloadFromOrigin() }
+ }
+ }
+ override func stopLoading() { MainActor.assumeIsolated { webView?.stopLoading() } }
+
+ func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, preferences: WKWebpagePreferences,
+ decisionHandler: @escaping @MainActor (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
+ if action.shouldPerformDownload { return decisionHandler(.download, preferences) }
+ guard let url = action.request.url else { return decisionHandler(.allow, preferences) }
+ let scheme = url.scheme?.lowercased() ?? ""
+ // mailto:, zoommtg:, itms-apps: go to their app, only from a click.
+ if !["http", "https", "about", "blob", "data", "file"].contains(scheme) {
+ if action.navigationType == .linkActivated { NSWorkspace.shared.open(url) }
+ return decisionHandler(.cancel, preferences)
+ }
+ guard action.navigationType == .linkActivated else { return decisionHandler(.allow, preferences) }
+ let s = url.absoluteString
+ let mods = action.modifierFlags
+ // ⌘-click and middle-click: a new tab, in the background unless ⇧ is down too (Chrome).
+ if mods.contains(.command) || action.buttonNumber == 2 {
+ delegate?.browser(self, requestsNewTabWithURL: s, inBackground: !mods.contains(.shift))
+ return decisionHandler(.cancel, preferences)
+ }
+ guard action.targetFrame?.isMainFrame ?? true else { return decisionHandler(.allow, preferences) }
+ // Arc's Peek, and Shift-click (Chrome's new window).
+ if delegate?.browser?(self, opensPeekForURL: s, shiftClick: mods.contains(.shift), newTab: false) == true {
+ return decisionHandler(.cancel, preferences)
+ }
+ if mods.contains(.shift) {
+ delegate?.browser(self, requestsNewTabWithURL: s, inBackground: false)
+ return decisionHandler(.cancel, preferences)
+ }
+ decisionHandler(.allow, preferences)
+ }
+
+ func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse,
+ decisionHandler: @escaping @MainActor (WKNavigationResponsePolicy) -> Void) {
+ let http = response.response as? HTTPURLResponse
+ if response.isForMainFrame { lastStatus = http?.statusCode ?? 0 }
+ let attachment = (http?.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment")
+ decisionHandler(attachment || !response.canShowMIMEType ? .download : .allow)
+ }
+
+ func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
+ failedURL = nil
+ setCommitted(false)
+ }
+
+ func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
+ setCommitted(true)
+ }
+
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
+ guard !closed else { return }
+ let url = webView.url?.absoluteString ?? pendingURL
+ delegate?.browser(self, didFinishLoadingURL: url, title: webView.title ?? "", statusCode: lastStatus)
+ reportThemeColor()
+ probeBackgroundColor()
+ loadFavicon()
+ }
+
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
+ failed(webView, error)
+ }
+
+ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
+ failed(webView, error)
+ }
+
+ @MainActor
+ private func failed(_ webView: WKWebView, _ error: Error) {
+ let e = error as NSError
+ // Cancelled by a new navigation, a download or Peek: not a failure.
+ if e.domain == NSURLErrorDomain && e.code == NSURLErrorCancelled { return }
+ if e.domain == "WebKitErrorDomain" && (e.code == 102 || e.code == 204) { return }
+ let url = (e.userInfo[NSURLErrorFailingURLStringErrorKey] as? String) ?? webView.url?.absoluteString ?? pendingURL
+ delegate?.browser?(self, didFailLoadingURL: url, errorCode: Self.netError(e))
+ guard !closed, e.domain == NSURLErrorDomain, let failing = URL(string: url) else { return }
+ // Chrome's error page shows the address that failed; Reload tries it again (reload()).
+ failedURL = url
+ webView.loadSimulatedRequest(URLRequest(url: failing), responseHTML: Self.errorPage(host: failing.host ?? url, message: e.localizedDescription))
+ }
+
+ @MainActor
+ private func setCommitted(_ now: Bool) {
+ guard committed != now else { return }
+ committed = now
+ delegate?.browser?(self, didChangeCommittedLoad: now)
+ }
+
+ func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
+ CraLog.note("WebKit page process ended: \(incognitoPage ? "(incognito)" : CraLog.host(currentURL)), reloading")
+ webView.reload()
+ }
+
+ // MARK: Windows and popups
+
+ func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction,
+ windowFeatures: WKWindowFeatures) -> WKWebView? {
+ let url = action.request.url?.absoluteString ?? ""
+ // A target=_blank link: a new tab without an opener, like Chrome's noopener default.
+ if action.navigationType == .linkActivated {
+ let mods = action.modifierFlags
+ if mods.contains(.command) || action.buttonNumber == 2 {
+ delegate?.browser(self, requestsNewTabWithURL: url, inBackground: !mods.contains(.shift))
+ } else if delegate?.browser?(self, opensPeekForURL: url, shiftClick: mods.contains(.shift), newTab: true) != true {
+ delegate?.browser(self, requestsNewTabWithURL: url, inBackground: false)
+ }
+ return nil
+ }
+ // window.open: a popup that keeps its opener (sign-in windows).
+ guard let host = delegate?.browser(self, popupHostForURL: url, inBackground: false) as? WebKitBrowser else { return nil }
+ return host.adoptPopup(configuration: configuration)
+ }
+
+ /// window.close(): the tab goes, like Chrome.
+ func webViewDidClose(_ webView: WKWebView) {
+ pageClosedItself = true
+ close()
+ }
+
+ // MARK: Dialogs and permissions
+
+ func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
+ completionHandler: @escaping @MainActor () -> Void) {
+ runAlert(message, frame: frame, buttons: ["OK"]) { _ in completionHandler() }
+ }
+
+ func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
+ completionHandler: @escaping @MainActor (Bool) -> Void) {
+ runAlert(message, frame: frame, buttons: ["OK", "Cancel"]) { completionHandler($0 == .alertFirstButtonReturn) }
+ }
+
+ func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?,
+ initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping @MainActor (String?) -> Void) {
+ let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 24))
+ field.stringValue = defaultText ?? ""
+ runAlert(prompt, frame: frame, buttons: ["OK", "Cancel"], accessory: field) {
+ completionHandler($0 == .alertFirstButtonReturn ? field.stringValue : nil)
+ }
+ }
+
+ @MainActor
+ private func runAlert(_ message: String, frame: WKFrameInfo, buttons: [String], accessory: NSView? = nil,
+ done: @escaping (NSApplication.ModalResponse) -> Void) {
+ let alert = NSAlert()
+ alert.messageText = frame.securityOrigin.host.isEmpty ? "This page says" : "\(frame.securityOrigin.host) says"
+ alert.informativeText = message
+ for b in buttons { alert.addButton(withTitle: b) }
+ alert.accessoryView = accessory
+ guard let window = container.window else { return done(.alertSecondButtonReturn) }
+ alert.beginSheetModal(for: window, completionHandler: done)
+ }
+
+ func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo,
+ completionHandler: @escaping @MainActor ([URL]?) -> Void) {
+ let panel = NSOpenPanel()
+ panel.allowsMultipleSelection = parameters.allowsMultipleSelection
+ panel.canChooseDirectories = parameters.allowsDirectories
+ guard let window = container.window else { return completionHandler(nil) }
+ panel.beginSheetModal(for: window) { completionHandler($0 == .OK ? panel.urls : nil) }
+ }
+
+ /// Camera and microphone ask through Cra's prompt, as Chromium's pages do (kinds 1 and 2).
+ func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo,
+ type: WKMediaCaptureType, decisionHandler: @escaping @MainActor (WKPermissionDecision) -> Void) {
+ let kinds: UInt
+ switch type {
+ case .camera: kinds = 1
+ case .microphone: kinds = 2
+ case .cameraAndMicrophone: kinds = 3
+ @unknown default: kinds = 16
+ }
+ let port = origin.port == 0 ? "" : ":\(origin.port)"
+ guard let delegate else { return decisionHandler(.deny) }
+ delegate.browser(self, requestsPermissionForOrigin: "\(origin.protocol)://\(origin.host)\(port)", kinds: kinds) { allowed in
+ DispatchQueue.main.async { decisionHandler(allowed ? .grant : .deny) }
+ }
+ }
+
+ // MARK: Focus, zoom, find, sound
+
+ override func setFocused(_ focused: Bool) {
+ MainActor.assumeIsolated {
+ guard focused, let web = webView, let window = web.window else { return }
+ if window.firstResponder !== web { window.makeFirstResponder(web) }
+ }
+ }
+
+ /// Chromium's zoom level is log base 1.2 of the factor (0 = 100 %, 1 = 120 %).
+ override func zoomLevel() -> Double {
+ MainActor.assumeIsolated { log(Double(webView?.pageZoom ?? 1)) / log(1.2) }
+ }
+
+ override func setZoomLevel(_ level: Double) {
+ MainActor.assumeIsolated { webView?.pageZoom = CGFloat(pow(1.2, level)) }
+ }
+
+ override func findText(_ text: String, forward: Bool, matchCase: Bool, findNext: Bool) {
+ MainActor.assumeIsolated {
+ guard let web = webView, !text.isEmpty else { return }
+ let config = WKFindConfiguration()
+ config.backwards = !forward
+ config.caseSensitive = matchCase
+ config.wraps = true
+ let fresh = !findNext || text != findQuery
+ findQuery = text
+ web.find(text, configuration: config) { [weak self] result in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ guard result.matchFound else {
+ self.findCount = 0
+ self.findIndex = 0
+ self.delegate?.browser?(self, didFindMatches: 0, activeMatch: 0)
+ return
+ }
+ let step = { [weak self] (count: Int) in
+ guard let self else { return }
+ self.findCount = max(count, 1)
+ if fresh { self.findIndex = forward ? 1 : self.findCount } else {
+ self.findIndex = forward ? self.findIndex % self.findCount + 1 : (self.findIndex + self.findCount - 2) % self.findCount + 1
+ }
+ self.delegate?.browser?(self, didFindMatches: self.findCount, activeMatch: self.findIndex)
+ }
+ if !fresh, self.findCount > 0 { return step(self.findCount) }
+ // WebKit's find doesn't count: the page's text does, the way find sees it.
+ web.callAsyncJavaScript(Self.countMatches, arguments: ["q": text, "cs": matchCase], in: nil, in: Self.world) { r in
+ MainActor.assumeIsolated { step((try? r.get()) as? Int ?? 1) }
+ }
+ }
+ }
+ }
+ }
+
+ private static let countMatches = """
+ const t = document.body ? document.body.innerText : '';
+ const a = cs ? t : t.toLowerCase(), b = cs ? q : q.toLowerCase();
+ let n = 0, i = 0;
+ while (b && (i = a.indexOf(b, i)) !== -1) { n++; i += b.length; }
+ return n;
+ """
+
+ override func stopFinding(_ clearSelection: Bool) {
+ MainActor.assumeIsolated {
+ findQuery = ""
+ findCount = 0
+ findIndex = 0
+ if clearSelection { webView?.evaluateJavaScript("getSelection().removeAllRanges()", in: nil, in: Self.world) { _ in } }
+ }
+ }
+
+ /// WebKit's page mute (Safari's tab mute), else every media element.
+ override func setAudioMuted(_ muted: Bool) {
+ MainActor.assumeIsolated {
+ guard let web = webView else { return }
+ let sel = NSSelectorFromString("_setPageMuted:")
+ if let m = class_getInstanceMethod(type(of: web), sel) {
+ typealias Fn = @convention(c) (AnyObject, Selector, UInt) -> Void
+ unsafeBitCast(method_getImplementation(m), to: Fn.self)(web, sel, muted ? 1 : 0)
+ } else {
+ web.evaluateJavaScript("document.querySelectorAll('video,audio').forEach(m => m.muted = \(muted))", in: nil, in: Self.world) { _ in }
+ }
+ }
+ }
+
+ override func exitFullscreen() {
+ MainActor.assumeIsolated { webView?.closeAllMediaPresentations {} }
+ }
+
+ // MARK: Picture in Picture (WebKit's own, the system's floating window)
+
+ override func requestPictureInPicture(automatic: Bool) {
+ // BrowserManager asked the page first; WebKit has no other way in.
+ }
+
+ override func exitPictureInPicture() {
+ runPictureInPicture("if (document.pictureInPictureElement) document.exitPictureInPicture();")
+ }
+
+ override func closePictureInPicture() {
+ runPictureInPicture("const v = document.pictureInPictureElement; if (v) { v.pause(); document.exitPictureInPicture(); }")
+ }
+
+ override func togglePictureInPicturePlayback() {
+ runPictureInPicture("const v = document.pictureInPictureElement; if (v) { v.paused ? v.play() : v.pause(); }")
+ }
+
+ override func skipPictureInPicture(by seconds: Double) {
+ runPictureInPicture("const v = document.pictureInPictureElement; if (v) v.currentTime = Math.max(0, v.currentTime + \(seconds));")
+ }
+
+ private func runPictureInPicture(_ js: String) {
+ MainActor.assumeIsolated { webView?.evaluateJavaScript(js, in: nil, in: Self.world) { _ in } }
+ }
+
+ // MARK: Messages from the isolated world
+
+ @MainActor
+ fileprivate func receive(_ body: Any) {
+ guard !closed, let m = body as? [String: Any], let kind = m["t"] as? String else { return }
+ switch kind {
+ case "media":
+ if !observesPlayingAudio { setPlaying(m["playing"] as? Bool ?? false) }
+ case "pip":
+ let on = m["on"] as? Bool ?? false
+ guard on != inPictureInPicture else { return }
+ inPictureInPicture = on
+ pictureInPicturePlaying = on && (m["playing"] as? Bool ?? true)
+ delegate?.browser?(self, didChangePictureInPicture: on)
+ case "pipPlaying":
+ let on = m["on"] as? Bool ?? false
+ guard inPictureInPicture, on != pictureInPicturePlaying else { return }
+ pictureInPicturePlaying = on
+ delegate?.browser?(self, didChangePictureInPicturePlayback: on)
+ case "hover":
+ let url = m["url"] as? String ?? ""
+ guard url != hoverURL else { return }
+ hoverURL = url
+ delegate?.browser(self, didChangeStatusMessage: url)
+ case "colors":
+ if let bg = m["bg"] as? String { delegate?.browser?(self, didReportBackgroundColor: bg) }
+ default: break
+ }
+ }
+
+ /// Added to PageScript's isolated world here: what Chromium reports natively.
+ static let isolatedAddOn = """
+
+ (() => {
+ if (window.__craWebKit) return;
+ window.__craWebKit = true;
+ const post = m => { try { webkit.messageHandlers.cra.postMessage(m); } catch {} };
+ const media = () => [...document.querySelectorAll('video,audio')];
+ let was = false;
+ const report = () => {
+ const now = media().some(m => !m.paused && !m.ended && !m.muted && m.volume > 0);
+ if (now !== was) { was = now; post({ t: 'media', playing: now }); }
+ };
+ for (const ev of ['play', 'playing', 'pause', 'ended', 'volumechange', 'emptied']) addEventListener(ev, e => {
+ report();
+ const v = document.pictureInPictureElement;
+ if (v && e.target === v && (ev === 'play' || ev === 'pause')) post({ t: 'pipPlaying', on: ev === 'play' });
+ }, true);
+ addEventListener('enterpictureinpicture', e => post({ t: 'pip', on: true, playing: !e.target.paused }), true);
+ addEventListener('leavepictureinpicture', () => post({ t: 'pip', on: false }), true);
+ if (window.top === window) {
+ let last = '';
+ addEventListener('mouseover', e => {
+ const a = e.target instanceof Element ? e.target.closest('a[href]') : null;
+ const url = a ? a.href : '';
+ if (url !== last) { last = url; post({ t: 'hover', url }); }
+ }, true);
+ document.addEventListener('mouseleave', () => { if (last) { last = ''; post({ t: 'hover', url: '' }); } });
+ }
+ })();
+ """
+
+ /// The page's own background (root, then body), else its color scheme's canvas, as Chromium reports it.
+ override func probeBackgroundColor() {
+ MainActor.assumeIsolated {
+ webView?.evaluateJavaScript(Self.backgroundProbe, in: nil, in: Self.world) { [weak self] r in
+ MainActor.assumeIsolated {
+ guard let self, !self.closed, let hex = (try? r.get()) as? String, !hex.isEmpty else { return }
+ self.delegate?.browser?(self, didReportBackgroundColor: hex)
+ if self.webView?.themeColor == nil { self.delegate?.browser(self, didReportThemeColor: hex) }
+ }
+ }
+ }
+ }
+
+ private static let backgroundProbe = """
+ (() => {
+ const hex = el => {
+ if (!el) return '';
+ const m = getComputedStyle(el).backgroundColor.match(/rgba?\\(\\s*([\\d.]+)[ ,]+([\\d.]+)[ ,]+([\\d.]+)(?:[ ,/]+([\\d.]+))?/);
+ if (!m || (m[4] !== undefined && +m[4] === 0)) return '';
+ return '#' + [m[1], m[2], m[3]].map(x => Math.round(+x).toString(16).padStart(2, '0')).join('');
+ };
+ const dark = getComputedStyle(document.documentElement).colorScheme.includes('dark') && matchMedia('(prefers-color-scheme: dark)').matches;
+ return hex(document.documentElement) || hex(document.body) || (dark ? '#121212' : '#ffffff');
+ })()
+ """
+
+ // MARK: Favicon
+
+ /// The page's own icon (the largest it declares, else /favicon.ico), fetched without cookies.
+ @MainActor
+ private func loadFavicon() {
+ let js = """
+ (() => {
+ const links = [...document.querySelectorAll('link[rel~="icon"], link[rel="apple-touch-icon"], link[rel="shortcut icon"]')];
+ const size = l => Math.max(0, ...(l.getAttribute('sizes') || '').split(/\\s+/).map(s => parseInt(s, 10) || 0));
+ links.sort((a, b) => size(b) - size(a));
+ const svgless = links.filter(l => !/\\.svg(\\?|$)/i.test(l.href));
+ return (svgless[0] || links[0])?.href || new URL('/favicon.ico', location.href).href;
+ })()
+ """
+ webView?.evaluateJavaScript(js, in: nil, in: Self.world) { [weak self] r in
+ guard let s = (try? r.get()) as? String, let url = URL(string: s), ["http", "https", "data"].contains(url.scheme ?? "") else { return }
+ Self.iconSession.dataTask(with: url) { data, _, _ in
+ guard let data, let image = NSImage(data: data), image.size.width > 0 else { return }
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ guard let self, !self.closed else { return }
+ self.delegate?.browser(self, didLoadFavicon: image, forURL: s)
+ }
+ }
+ }.resume()
+ }
+ }
+
+ private static let iconSession: URLSession = {
+ let c = URLSessionConfiguration.ephemeral
+ c.httpCookieStorage = nil
+ c.httpShouldSetCookies = false
+ c.timeoutIntervalForRequest = 15
+ return URLSession(configuration: c)
+ }()
+
+ // MARK: Scripts and the DevTools Protocol methods Cra uses
+
+ override func executeJavaScript(_ script: String) {
+ MainActor.assumeIsolated { webView?.evaluateJavaScript(script) { _, _ in } }
+ }
+
+ override func executeJavaScript(_ script: String, inDevTools: Bool) {
+ if !inDevTools { executeJavaScript(script) }
+ }
+
+ override func evaluate(inIsolatedWorld world: String, params: String, completion: @escaping (String?, String?) -> Void) {
+ MainActor.assumeIsolated { evaluate(params, in: WKContentWorld.world(name: world), completion: completion) }
+ }
+
+ override func sendDevToolsMethod(_ method: String, params: String, completion: @escaping (String?, String?) -> Void) {
+ MainActor.assumeIsolated {
+ guard let web = webView, !closed else { return reply(completion, nil, "\(method): the page is closed") }
+ switch method {
+ case "Runtime.evaluate":
+ evaluate(params, in: .page, completion: completion)
+ case "Page.captureScreenshot":
+ captureScreenshot(web, params: Self.object(params), completion: completion)
+ case "Page.getLayoutMetrics":
+ let js = """
+ (() => { const e = document.documentElement, v = window.visualViewport;
+ return JSON.stringify({ cssContentSize: { x: 0, y: 0, width: e.scrollWidth, height: e.scrollHeight },
+ cssVisualViewport: { pageX: scrollX, pageY: scrollY, clientWidth: v ? v.width : innerWidth,
+ clientHeight: v ? v.height : innerHeight, scale: v ? v.scale : 1 } }); })()
+ """
+ web.evaluateJavaScript(js, in: nil, in: Self.world) { [weak self] r in
+ self?.reply(completion, (try? r.get()) as? String, "Page.getLayoutMetrics failed")
+ }
+ case "Storage.clearDataForOrigin":
+ clearCookies(origin: Self.object(params)["origin"] as? String ?? "", completion: completion)
+ case "Network.clearBrowserCache":
+ let types: Set<String> = [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeFetchCache]
+ web.configuration.websiteDataStore.removeData(ofTypes: types, modifiedSince: .distantPast) { [weak self] in
+ self?.reply(completion, "{}", nil)
+ }
+ case "Cra.setFreezingVote", "Cra.load":
+ // WebKit decides when a hidden page sleeps; tab sleeping closes the page instead.
+ reply(completion, "{}", nil)
+ default:
+ // Cra.discard, Cra.getFreezingState, Target.*: Chromium only. Each caller has a path for this.
+ reply(completion, nil, "\(method) is not available in a WebKit page")
+ }
+ }
+ }
+
+ /// Completions come on the main queue, a turn later, as CraCEF's do.
+ @MainActor
+ private func reply(_ completion: @escaping (String?, String?) -> Void, _ result: String?, _ error: String?) {
+ DispatchQueue.main.async { result != nil ? completion(result, nil) : completion(nil, error ?? "failed") }
+ }
+
+ /// Runtime.evaluate's params (`expression`, `awaitPromise`, `returnByValue`), answered as
+ /// Chromium does: {"result":{"type":…,"value":…}} or {"exceptionDetails":{…}}. Scripts run as a
+ /// user gesture (WebKit's evaluateJavaScript always does), so play() and requestPictureInPicture work.
+ @MainActor
+ private func evaluate(_ params: String, in world: WKContentWorld, completion: @escaping (String?, String?) -> Void) {
+ guard let web = webView, !closed else { return reply(completion, nil, "the page is closed") }
+ let p = Self.object(params)
+ guard let expression = p["expression"] as? String else { return reply(completion, nil, "no expression") }
+ let done: (Result<Any, Error>) -> Void = { [weak self] r in
+ MainActor.assumeIsolated { self?.reply(completion, Self.evaluationResult(r), nil) }
+ }
+ if p["awaitPromise"] as? Bool == true {
+ web.callAsyncJavaScript("return await (\n\(expression)\n);", arguments: [:], in: nil, in: world, completionHandler: done)
+ } else {
+ web.evaluateJavaScript(expression, in: nil, in: world, completionHandler: done)
+ }
+ }
+
+ static func evaluationResult(_ r: Result<Any, Error>) -> String {
+ let out: [String: Any]
+ switch r {
+ case .success(let value):
+ switch value {
+ case is NSNull: out = ["result": ["type": "object", "subtype": "null", "value": NSNull()]]
+ case let n as NSNumber where CFGetTypeID(n) == CFBooleanGetTypeID(): out = ["result": ["type": "boolean", "value": n.boolValue]]
+ case let n as NSNumber: out = ["result": ["type": "number", "value": n]]
+ case let s as String: out = ["result": ["type": "string", "value": s]]
+ default: out = ["result": ["type": "object", "value": JSONSerialization.isValidJSONObject(value) ? value : NSNull()]]
+ }
+ case .failure(let error):
+ let e = error as NSError
+ // "JavaScript execution returned a result of an unsupported type": undefined, a promise, a node.
+ if e.domain == WKErrorDomain && e.code == WKError.javaScriptResultTypeIsUnsupported.rawValue {
+ out = ["result": ["type": "undefined"]]
+ } else {
+ let text = e.userInfo["WKJavaScriptExceptionMessage"] as? String ?? e.localizedDescription
+ out = ["exceptionDetails": ["text": text, "exception": ["type": "object", "description": text]]]
+ }
+ }
+ return String(decoding: (try? JSONSerialization.data(withJSONObject: out, options: [.fragmentsAllowed])) ?? Data("{}".utf8), as: UTF8.self)
+ }
+
+ /// The viewport (or `clip`, in CSS pixels), as {"data": base64}. `captureBeyondViewport`
+ /// (Capture's full page) renders the whole document through WebKit's PDF path.
+ @MainActor
+ private func captureScreenshot(_ web: WKWebView, params: [String: Any], completion: @escaping (String?, String?) -> Void) {
+ let png = (params["format"] as? String ?? "png") == "png"
+ let quality = Double(params["quality"] as? Int ?? 80) / 100
+ let clip = params["clip"] as? [String: Any]
+ let encode: (CGImage?) -> Void = { [weak self] image in
+ guard let image else { return MainActor.assumeIsolated { self?.reply(completion, nil, "no image") } }
+ let rep = NSBitmapImageRep(cgImage: image)
+ let data = png ? rep.representation(using: .png, properties: [:])
+ : rep.representation(using: .jpeg, properties: [.compressionFactor: quality])
+ let json = data.map { #"{"data":""# + $0.base64EncodedString() + #""}"# }
+ MainActor.assumeIsolated { self?.reply(completion, json, "encoding failed") }
+ }
+ if params["captureBeyondViewport"] as? Bool == true, let clip {
+ let rect = NSRect(x: clip["x"] as? Double ?? 0, y: clip["y"] as? Double ?? 0,
+ width: clip["width"] as? Double ?? Double(web.bounds.width), height: clip["height"] as? Double ?? Double(web.bounds.height))
+ let config = WKPDFConfiguration()
+ config.rect = rect
+ web.createPDF(configuration: config) { r in encode((try? r.get()).flatMap(Self.render(pdf:))) }
+ return
+ }
+ let config = WKSnapshotConfiguration()
+ if let clip {
+ config.rect = NSRect(x: clip["x"] as? Double ?? 0, y: clip["y"] as? Double ?? 0,
+ width: clip["width"] as? Double ?? 0, height: clip["height"] as? Double ?? 0)
+ }
+ config.afterScreenUpdates = false
+ web.takeSnapshot(with: config) { image, _ in
+ encode(image?.cgImage(forProposedRect: nil, context: nil, hints: nil))
+ }
+ }
+
+ /// The first page of a PDF at 2× (Capture's full page).
+ static func render(pdf data: Data) -> CGImage? {
+ guard let provider = CGDataProvider(data: data as CFData), let doc = CGPDFDocument(provider), let page = doc.page(at: 1) else { return nil }
+ let box = page.getBoxRect(.mediaBox)
+ let scale: CGFloat = min(2, 16384 / max(box.height, 1))
+ let w = Int(box.width * scale), h = Int(box.height * scale)
+ guard w > 0, h > 0, let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }
+ ctx.setFillColor(.white)
+ ctx.fill(CGRect(x: 0, y: 0, width: w, height: h))
+ ctx.scaleBy(x: scale, y: scale)
+ ctx.drawPDFPage(page)
+ return ctx.makeImage()
+ }
+
+ /// Arc's "Clear Cookies and Refresh" for this site (its registrable domain's records).
+ @MainActor
+ private func clearCookies(origin: String, completion: @escaping (String?, String?) -> Void) {
+ guard let store = webView?.configuration.websiteDataStore, let host = URL(string: origin)?.host?.lowercased() else {
+ return reply(completion, nil, "no origin")
+ }
+ let types: Set<String> = [WKWebsiteDataTypeCookies]
+ store.fetchDataRecords(ofTypes: types) { [weak self] records in
+ let mine = records.filter { r in
+ let d = r.displayName.lowercased()
+ return host == d || host.hasSuffix("." + d)
+ }
+ store.removeData(ofTypes: types, for: mine) { MainActor.assumeIsolated { self?.reply(completion, "{}", nil) } }
+ }
+ }
+
+ static func object(_ json: String) -> [String: Any] {
+ (try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any]) ?? [:]
+ }
+
+ // MARK: DevTools, printing, source, connection
+
+ /// WebKit's Web Inspector, in its own window (Chrome's DevTools dock is Chromium's).
+ override func showDevTools() { MainActor.assumeIsolated { inspector(perform: "show") } }
+ override func closeDevTools() { MainActor.assumeIsolated { inspector(perform: "close") } }
+ override func applyDevToolsAction() { devToolsAction = nil }
+
+ @MainActor
+ private func inspector(perform name: String) {
+ guard let web = webView, web.responds(to: NSSelectorFromString("_inspector")),
+ let inspector = web.value(forKey: "_inspector") as? NSObject, inspector.responds(to: NSSelectorFromString(name)) else { return }
+ inspector.perform(NSSelectorFromString(name))
+ }
+
+ override func print() {
+ MainActor.assumeIsolated {
+ guard let web = webView, let window = web.window else { return }
+ let op = web.printOperation(with: NSPrintInfo.shared)
+ op.view?.frame = web.bounds
+ op.runModal(for: window, delegate: nil, didRun: nil, contextInfo: nil)
+ }
+ }
+
+ /// Chromium's view-source: page, in a new tab.
+ override func viewSource() {
+ MainActor.assumeIsolated {
+ let url = currentURL
+ guard url.hasPrefix("http") else { return }
+ delegate?.browser(self, requestsNewTabWithURL: "view-source:" + url, inBackground: false)
+ }
+ }
+
+ override func sslStatus() -> CraSSLStatus? {
+ MainActor.assumeIsolated {
+ guard let web = webView, web.url != nil else { return nil }
+ let s = CraSSLStatus()
+ guard web.url?.scheme == "https", let trust = web.serverTrust else { return s }
+ s.secureConnection = true
+ s.certificates = (SecTrustCopyCertificateChain(trust) as? [SecCertificate] ?? []).map { SecCertificateCopyData($0) as Data }
+ // net::SSLStatus::DISPLAYED_INSECURE_CONTENT: something on the page came over http.
+ s.contentStatus = web.hasOnlySecureContent ? 0 : 1
+ return s
+ }
+ }
+
+ override func notifyMoveOrResizeStarted() {}
+
+ // MARK: Close
+
+ override func close() {
+ MainActor.assumeIsolated {
+ guard !closed else { return }
+ closed = true
+ audibleOff?.cancel()
+ for (_, d) in downloads { d.progress?.invalidate() }
+ if let web = webView {
+ observations.forEach { $0.invalidate() }
+ observations = []
+ if observesPlayingAudio { web.removeObserver(self, forKeyPath: "_isPlayingAudio") }
+ observesPlayingAudio = false
+ web.closeAllMediaPresentations {}
+ web.pauseAllMediaPlayback()
+ web.stopLoading()
+ web.navigationDelegate = nil
+ web.uiDelegate = nil
+ web.configuration.userContentController.removeAllScriptMessageHandlers()
+ web.configuration.userContentController.removeAllUserScripts()
+ web.owner = nil
+ web.removeFromSuperview()
+ }
+ webView = nil
+ // Like CEF, -browserDidClose: comes once the page is gone, a turn later.
+ DispatchQueue.main.async { [self] in delegate?.browserDidClose(self) }
+ }
+ }
+
+ // MARK: Downloads
+
+ 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,
+ completionHandler: @escaping @MainActor (URL?) -> Void) {
+ let folder = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
+ let name = suggestedFilename.isEmpty ? "download" : suggestedFilename.replacingOccurrences(of: "/", with: "-")
+ var dest = folder.appendingPathComponent(name)
+ let base = dest.deletingPathExtension().lastPathComponent, ext = dest.pathExtension
+ var n = 1
+ while FileManager.default.fileExists(atPath: dest.path) {
+ dest = folder.appendingPathComponent(ext.isEmpty ? "\(base) (\(n))" : "\(base) (\(n)).\(ext)")
+ n += 1
+ }
+ Self.nextDownloadID &+= 1
+ let info = CraDownloadInfo()
+ info.identifier = Self.nextDownloadID
+ info.url = response.url?.absoluteString ?? ""
+ info.fullPath = dest.path
+ info.suggestedName = dest.lastPathComponent
+ info.totalBytes = response.expectedContentLength
+ info.state = .inProgress
+ let key = ObjectIdentifier(download)
+ let progress = download.progress.observe(\.fractionCompleted) { [weak self] p, _ in
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ guard let self, let d = self.downloads[key] else { return }
+ d.info.receivedBytes = p.completedUnitCount
+ if p.totalUnitCount > 0 { d.info.totalBytes = p.totalUnitCount }
+ d.info.percent = d.info.totalBytes > 0 ? Int(d.info.receivedBytes * 100 / d.info.totalBytes) : -1
+ self.delegate?.browser(self, didUpdateDownload: d.info)
+ }
+ }
+ }
+ downloads[key] = (download, info, progress)
+ delegate?.browser(self, didUpdateDownload: info)
+ completionHandler(dest)
+ }
+
+ func downloadDidFinish(_ download: WKDownload) {
+ finish(download, .complete)
+ }
+
+ func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
+ let e = error as NSError
+ finish(download, e.domain == NSURLErrorDomain && e.code == NSURLErrorCancelled ? .cancelled : .interrupted)
+ }
+
+ @MainActor
+ private func finish(_ download: WKDownload, _ state: CraDownloadState) {
+ guard let d = downloads.removeValue(forKey: ObjectIdentifier(download)) else { return }
+ d.progress?.invalidate()
+ d.info.state = state
+ if state == .complete {
+ d.info.receivedBytes = max(d.info.receivedBytes, d.info.totalBytes)
+ d.info.percent = 100
+ }
+ delegate?.browser(self, didUpdateDownload: d.info)
+ }
+
+ // MARK: Helpers
+
+ static func hex(_ color: NSColor) -> String? {
+ guard let c = color.usingColorSpace(.sRGB), c.alphaComponent > 0 else { return nil }
+ return String(format: "#%02x%02x%02x", Int((c.redComponent * 255).rounded()), Int((c.greenComponent * 255).rounded()),
+ Int((c.blueComponent * 255).rounded()))
+ }
+
+ /// Chromium's net error for a URL loading error, for the log and ExtensionPageRetry.
+ static func netError(_ e: NSError) -> Int {
+ guard e.domain == NSURLErrorDomain else { return -2 }
+ switch e.code {
+ case NSURLErrorNotConnectedToInternet: return -106
+ case NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed: return -105
+ case NSURLErrorTimedOut: return -7
+ case NSURLErrorCannotConnectToHost: return -102
+ case NSURLErrorNetworkConnectionLost: return -101
+ case NSURLErrorSecureConnectionFailed: return -107
+ case NSURLErrorServerCertificateUntrusted, NSURLErrorServerCertificateHasBadDate,
+ NSURLErrorServerCertificateHasUnknownRoot, NSURLErrorServerCertificateNotYetValid: return -202
+ default: return -2
+ }
+ }
+
+ static func errorPage(host: String, message: String) -> String {
+ func esc(_ s: String) -> String {
+ s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;").replacingOccurrences(of: ">", with: "&gt;")
+ }
+ return """
+ <!doctype html><meta charset="utf-8"><meta name="color-scheme" content="light dark"><title>\(esc(host))</title>
+ <style>body{font:15px -apple-system,system-ui,sans-serif;margin:0;display:grid;place-items:center;height:100vh;color:CanvasText;background:Canvas}
+ div{max-width:520px;padding:24px}h1{font-size:20px;font-weight:600;margin:0 0 8px}p{opacity:.7;margin:0}</style>
+ <div><h1>This page couldn’t load</h1><p>\(esc(host)): \(esc(message))</p></div>
+ """
+ }
+}
+
+/// WKUserContentController holds its handlers strongly; the browser is held weakly here.
+private final class ScriptMessageProxy: NSObject, WKScriptMessageHandler {
+ weak var owner: WebKitBrowser?
+ init(owner: WebKitBrowser) { self.owner = owner }
+ func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
+ MainActor.assumeIsolated { owner?.receive(message.body) }
+ }
+}
+
+/// The page view: tells its browser about focus and keys the way CEF's view does.
+final class CraWebView: WKWebView {
+ weak var owner: WebKitBrowser?
+ /// The ⌘-key WebKit is offering the page; WebKit sends it again if the page leaves it alone.
+ private weak var offered: NSEvent?
+
+ override func becomeFirstResponder() -> Bool {
+ let ok = super.becomeFirstResponder()
+ if ok, let owner { owner.delegate?.browserDidReceiveFocus(owner) }
+ return ok
+ }
+
+ /// Chrome's order: Cra's reserved shortcuts before the page sees the key, the page next,
+ /// then the menu bar and Cra's other shortcuts for keys the page left alone.
+ override func performKeyEquivalent(with event: NSEvent) -> Bool {
+ // AppKit offers a key equivalent to every view in the window: only the focused page takes it,
+ // not one in a hidden tab or the other split pane.
+ guard let owner, event.type == .keyDown, window?.firstResponder === self, !isHiddenOrHasHiddenAncestor else {
+ return super.performKeyEquivalent(with: event)
+ }
+ if let offered, offered === event {
+ self.offered = nil
+ if NSApp.mainMenu?.performKeyEquivalent(with: event) == true { return true }
+ return owner.delegate?.browser(owner, handleUnhandledKeyEvent: event) ?? false
+ }
+ if owner.delegate?.browser(owner, handleKeyEvent: event) == true { return true }
+ offered = event
+ return super.performKeyEquivalent(with: event)
+ }
+
+ /// "Open Link in New Window" opens a tab in Cra.
+ override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
+ super.willOpenMenu(menu, with: event)
+ for item in menu.items {
+ switch item.identifier?.rawValue {
+ case "WKMenuItemIdentifierOpenLinkInNewWindow": item.title = "Open Link in New Tab"
+ case "WKMenuItemIdentifierOpenImageInNewWindow": item.title = "Open Image in New Tab"
+ case "WKMenuItemIdentifierOpenMediaInNewWindow": item.title = "Open Video in New Tab"
+ case "WKMenuItemIdentifierOpenFrameInNewWindow": item.title = "Open Frame in New Tab"
+ default: break
+ }
+ }
+ }
+}
diff --git a/Sources/Cra/Services/WebKit/WebKitStores.swift b/Sources/Cra/Services/WebKit/WebKitStores.swift
new file mode 100644
index 0000000..adac2fc
--- /dev/null
+++ b/Sources/Cra/Services/WebKit/WebKitStores.swift
@@ -0,0 +1,55 @@
+import CryptoKit
+import Foundation
+import WebKit
+
+/// WebKit's cookies, storage and cache, one persistent store per Cra profile (like Chromium's
+/// profile folders) and one throwaway store per incognito session. Stores live under
+/// ~/Library/WebKit/<bundle id>/WebsiteDataStore/<uuid>; the uuid is derived from the data
+/// folder and the profile, so a test instance (CRA_DATA_DIR) never shares the daily one's.
+@MainActor
+enum WebKitStores {
+ private static var persistent: [String: WKWebsiteDataStore] = [:]
+ private static var incognito: WKWebsiteDataStore?
+
+ static func store(profilePath: String?, incognito isIncognito: Bool) -> WKWebsiteDataStore {
+ if isIncognito {
+ if let s = incognito { return s }
+ let s = WKWebsiteDataStore.nonPersistent()
+ incognito = s
+ return s
+ }
+ let key = profileKey(profilePath)
+ if let s = persistent[key] { return s }
+ let s = WKWebsiteDataStore(forIdentifier: identifier(forProfileKey: key))
+ persistent[key] = s
+ return s
+ }
+
+ /// The last incognito window closed (CraCEFRuntime.endIncognitoSession): the next incognito
+ /// page starts with nothing.
+ static func endIncognitoSession() { incognito = nil }
+
+ /// A Cra profile was deleted with its Chromium folder (`name` "Profile <id>"): its WebKit data goes too.
+ static func removeProfile(folderName name: String) {
+ let key = profileKey(AppPaths.chromiumCache.appendingPathComponent(name, isDirectory: true).path)
+ persistent[key] = nil
+ WKWebsiteDataStore.remove(forIdentifier: identifier(forProfileKey: key)) { error in
+ if let error { NSLog("Cra: removing WebKit data of %@ failed: %@", name, error.localizedDescription) }
+ }
+ }
+
+ /// "Default", or the profile's folder name ("Profile <id>").
+ static func profileKey(_ profilePath: String?) -> String {
+ guard let p = profilePath, !p.isEmpty else { return "Default" }
+ return URL(fileURLWithPath: p).lastPathComponent
+ }
+
+ /// A stable UUID (version 8, name-based) for the data folder plus the profile.
+ static func identifier(forProfileKey key: String) -> UUID {
+ let digest = SHA256.hash(data: Data("cra-webkit|\(AppPaths.supportDir.standardizedFileURL.path)|\(key)".utf8))
+ var b = Array(digest.prefix(16))
+ b[6] = (b[6] & 0x0F) | 0x80
+ b[8] = (b[8] & 0x3F) | 0x80
+ return UUID(uuid: (b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]))
+ }
+}
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
index 2356928..267f5b8 100644
--- a/Sources/Cra/UI/Windows/LittleWindowController.swift
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -265,8 +265,9 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
let sid = state.targetSpaceID
state.profileID = app.store.isIncognito(space: sid) ? nil : app.store.profile(app.store.space(sid)?.profileID)?.id
}
- let b = CraBrowser(frame: shell.page.bounds, url: url.map { $0.isEmpty ? "about:blank" : $0 }, delegate: self,
- incognito: false, profilePath: app.store.profilePath(profile: state.profileID))
+ // Chromium, or WebKit for a DRM service; a popup host takes its opener's engine.
+ let b = PageEngines.makeBrowser(frame: shell.page.bounds, url: url.map { $0.isEmpty ? "about:blank" : $0 }, delegate: self,
+ incognito: false, profilePath: app.store.profilePath(profile: state.profileID), opener: opener)
attach(b)
state.url = (url == "about:blank" ? "" : url) ?? ""
}
@@ -825,18 +826,37 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
/// A page can't move between profiles: a new browser in the other one loads its address.
private func reload(inProfile id: UUID?) {
- guard let old = browser else { return }
- let url = hasPage ? currentURL : "about:blank"
+ guard browser != nil else { return }
state.profileID = id
+ replacePage(at: hasPage ? currentURL : "about:blank")
+ }
+
+ /// A new page at `url` in place of this window's, in the engine the address gets (a profile
+ /// change, or a navigation the other engine has to show).
+ private func replacePage(at url: String) {
+ guard let old = browser else { return }
old.delegate = nil
if let w = old.hostWindow, w.parent === window { window?.removeChildWindow(w); w.orderOut(nil) }
old.containerView.removeFromSuperview()
- let b = CraBrowser(frame: shell.page.bounds, url: url, delegate: self, incognito: false, profilePath: store.profilePath(profile: id))
+ let b = PageEngines.makeBrowser(frame: shell.page.bounds, url: url, delegate: self, incognito: false,
+ profilePath: store.profilePath(profile: state.profileID))
attach(b)
old.close()
if window?.isKeyWindow == true { focusPage() }
}
+ /// A navigation the other engine has to show (ProtectedMediaSites): this window's page opens
+ /// again there, a turn later (not from inside Chromium's navigation callback).
+ func browser(_ browser: CraBrowser, handsOffNavigationToURL url: String, method: String) -> Bool {
+ guard browser === self.browser, PageEngines.handoffTarget(from: browser, to: url, method: method) != nil else { return false }
+ DispatchQueue.main.async { [weak self, weak browser] in
+ guard let self, let browser, browser === self.browser else { return }
+ self.state.url = url
+ self.replacePage(at: url)
+ }
+ return true
+ }
+
/// Archive the page to the Library (Arc keeps closed Little Arcs there too).
func archivePage() {
// A Peek is a look at a link, not a page to keep.
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index 47398bd..9f89cd4 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -1496,6 +1496,11 @@ public:
CraBrowser* o = owner_;
if (!o || !frame->IsMain()) return false;
if (OpensPeek(o, request, user_gesture, is_redirect)) return true;
+ // A page Cra shows in another engine (ProtectedMediaSites, WebKit for DRM services):
+ // cancelled before the request goes out, so a sign-in's one-time code isn't spent here.
+ if ([o.delegate respondsToSelector:@selector(browser:handsOffNavigationToURL:method:)]
+ && [o.delegate browser:o handsOffNavigationToURL:NSStringFromCef(request->GetURL())
+ method:NSStringFromCef(request->GetMethod())]) return true;
// A new page, also one started while the last is still loading: the loading bar waits
// for its answer again.
if (!is_redirect) SetCommittedLoad(o, NO);
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index de98045..bce1110 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -111,6 +111,11 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// opens as a target=_blank tab) or Shift-clicked (YES, instead of a new window). Return
/// YES to show it in a Peek; the page then stays where it is.
- (BOOL)browser:(CraBrowser *)browser opensPeekForURL:(NSString *)url shiftClick:(BOOL)shiftClick newTab:(BOOL)newTab;
+/// A main-frame navigation (a link, a redirect, history, an address Cra loaded) before its request
+/// goes out; `method` is its HTTP method. Return YES to cancel it here because Cra shows `url` in
+/// another engine (ProtectedMediaSites: WebKit for DRM services). Called on the main thread from
+/// inside Chromium: don't close the browser before returning.
+- (BOOL)browser:(CraBrowser *)browser handsOffNavigationToURL:(NSString *)url method:(NSString *)method;
/// The DevTools frontend shows `panel` ("elements", "console", "network", …): on load, and
/// on every switch, from Cra or the frontend's own tab bar.
- (void)browser:(CraBrowser *)browser devToolsShowsPanel:(NSString *)panel;
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index 553ea80..32c4c52 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -102,6 +102,7 @@ enum BrowserManagerLifecycleTests {
extensionPageRetryCase()
await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }
await pageProbeCase()
+ await pageEngineCase()
print("Browser manager lifecycle: \(checks) checks passed")
}
@@ -135,6 +136,66 @@ enum BrowserManagerLifecycleTests {
manager.closeAll()
}
+ /// DRM services open in WebKit (ProtectedMediaSites); a popup keeps its opener's engine; a
+ /// navigation the other engine has to show reopens the tab's page there, in its place on screen.
+ @MainActor
+ private static func pageEngineCase() async {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let observer = Observer()
+ manager.delegate = observer
+ let player = store.createTab(url: "https://open.spotify.com/").id
+ let site = store.createTab(url: "https://example.test/a").id
+ let other = store.createTab(url: "https://example.test/b").id
+ manager.show([site, other], focused: other, focus: false)
+ expect(manager.ensureRuntime(for: player)?.browser is WebKitBrowser, "a DRM service's tab opens in WebKit")
+ let chromium = manager.runtime(for: site)!.browser
+ expect(!(chromium is WebKitBrowser), "any other site opens in Chromium")
+
+ // window.open keeps its opener's engine: WebKit can only fill a web view it made.
+ let fromWebKit = manager.browser(manager.runtime(for: player)!.browser, popupHostForURL: "https://example.test/signin", inBackground: true)
+ expect(fromWebKit is WebKitBrowser, "a WebKit page's popup host is a WebKit page, whatever its address")
+ let fromChromium = manager.browser(chromium, popupHostForURL: "https://open.spotify.com/", inBackground: true)
+ expect(fromChromium.map { !($0 is WebKitBrowser) } == true, "a Chromium page's popup host is Chromium's, whatever its address")
+
+ // A POST, or a site Chromium shows: the navigation goes on in Chromium.
+ expect(!manager.browser(chromium, handsOffNavigationToURL: "https://www.netflix.com/login", method: "POST"),
+ "a POST to a service stays: its body can't move")
+ expect(!manager.browser(chromium, handsOffNavigationToURL: "https://example.test/c", method: "GET"), "a Chromium site stays in Chromium")
+ await drainMainQueue()
+ expect(manager.runtime(for: site)?.browser === chromium, "nothing moved")
+
+ // A link in the left pane to Netflix: the pane's page reopens in WebKit, same split, same focus.
+ expect(manager.browser(chromium, handsOffNavigationToURL: "https://www.netflix.com/browse", method: "GET"),
+ "Chromium's navigation to a service stops before its request goes out")
+ expect(manager.runtime(for: site)?.browser === chromium, "the page moves a turn later, not inside Chromium's callback")
+ await drainMainQueue()
+ let moved = manager.runtime(for: site)?.browser
+ expect(moved is WebKitBrowser && moved?.currentURL == "https://www.netflix.com/browse", "the pane's page opens in WebKit at the address")
+ expect(chromium.closeRequested && store.item(site)?.tab?.url == "https://www.netflix.com/browse", "the Chromium page closes; the tab has the new address")
+ expect(manager.visibleTabIDs == [site, other] && manager.visibleTabID == other, "the split keeps its panes, order and focus")
+ chromium.finishClose()
+
+ // Cra's own navigation in a WebKit page (the URL bar) to another site goes back to Chromium.
+ expect(manager.browser(moved!, handsOffNavigationToURL: "https://example.test/typed", method: "GET"),
+ "a typed address WebKit doesn't show moves to Chromium")
+ expect(!manager.browser(moved!, handsOffNavigationToURL: "https://www.netflix.com/title/1", method: "GET"),
+ "a typed address of a service stays in WebKit")
+ await drainMainQueue()
+ expect(!(manager.runtime(for: site)?.browser is WebKitBrowser) && manager.visibleTabIDs == [site, other], "back in Chromium, in its pane")
+
+ // A tab out of sight gets its page in the other engine at once, so its title and favicon fill in.
+ let hidden = manager.ensureRuntime(for: store.createTab(url: "https://t.example.test/x").id)!
+ expect(manager.browser(hidden.browser, handsOffNavigationToURL: "https://www.disneyplus.com/", method: "GET"), "a background redirect moves too")
+ await drainMainQueue()
+ expect(manager.runtime(for: hidden.tabID)?.browser is WebKitBrowser && !manager.visibleTabIDs.contains(hidden.tabID),
+ "a hidden tab is reopened in WebKit and stays hidden")
+
+ // A late request from a page that already moved changes nothing.
+ expect(!manager.browser(chromium, handsOffNavigationToURL: "https://www.netflix.com/", method: "GET"), "a retired page can't move its tab again")
+ manager.closeAll()
+ }
+
@MainActor
private static func embeddedPageHandoffCase() {
_ = NSApplication.shared
diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swift
index 1bf135f..4e9e76a 100644
--- a/Tests/BrowserManagerSupport/AppServices.swift
+++ b/Tests/BrowserManagerSupport/AppServices.swift
@@ -89,3 +89,6 @@ final class PictureInPictureChrome {
func videoEntered() {}
func videoLeft() {}
}
+/// The WebKit page (Sources/Cra/Services/WebKit/WebKitBrowser.swift): here only its type, which
+/// is what PageEngines and BrowserManager decide on.
+final class WebKitBrowser: CraBrowser {}
diff --git a/Tests/BrowserManagerSupport/CraCEF.swift b/Tests/BrowserManagerSupport/CraCEF.swift
index 230754c..5d627a4 100644
--- a/Tests/BrowserManagerSupport/CraCEF.swift
+++ b/Tests/BrowserManagerSupport/CraCEF.swift
@@ -11,8 +11,9 @@ public protocol CraBrowserDelegate: AnyObject {
public final class CraDownloadInfo {}
+/// `open`: the app subclasses it (WebKitBrowser, faked in AppServices.swift).
@MainActor
-public final class CraBrowser {
+open class CraBrowser {
public weak var delegate: CraBrowserDelegate?
public let containerView: NSView
public var hostWindow: NSWindow?
diff --git a/Tests/Fixtures/Pages/clip.mp4 b/Tests/Fixtures/Pages/clip.mp4
new file mode 100644
index 0000000..8af8645
Binary files /dev/null and b/Tests/Fixtures/Pages/clip.mp4 differ
diff --git a/Tests/Fixtures/Pages/media.html b/Tests/Fixtures/Pages/media.html
new file mode 100644
index 0000000..407e48e
--- /dev/null
+++ b/Tests/Fixtures/Pages/media.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Media fixture</title>
+<style>body { margin: 0; background: #111; color: #eee; font: 14px system-ui; } video { width: 640px; height: 360px; display: block; }</style>
+<!-- A looping H.264/AAC clip (clip.mp4: ffmpeg testsrc2 with a silent AAC track, 4 s; WebKit counts a playing, unmuted track as sound, and a scenario stays quiet) with media
+ session handlers, for the sidebar player, Picture in Picture and tab sleep. Paused until a
+ scenario plays it with a user gesture. The title says what the page last heard. -->
+<video id="v" src="clip.mp4" loop playsinline></video>
+<p id="state">ready</p>
+<script>
+ const v = document.getElementById('v');
+ const say = s => { document.getElementById('state').textContent = s; document.title = 'Media ' + s; };
+ for (const a of ['previoustrack', 'nexttrack']) navigator.mediaSession.setActionHandler(a, () => say(a));
+ for (const e of ['play', 'pause', 'enterpictureinpicture', 'leavepictureinpicture']) v.addEventListener(e, () => say(e));
+</script>
diff --git a/Tests/Scenarios/webkit-drm-tabs.scenario b/Tests/Scenarios/webkit-drm-tabs.scenario
new file mode 100644
index 0000000..b5a77e9
--- /dev/null
+++ b/Tests/Scenarios/webkit-drm-tabs.scenario
@@ -0,0 +1,102 @@
+# DRM services open in WebKit, where Apple's FairPlay plays them (ProtectedMediaSites,
+# docs/protected-media.md). ${WEBKIT} is the fixture server as localhost, which this run lists as
+# such a service, so the journey needs no network and no account. A Chromium page answers
+# 'userAgentData' in navigator with true, a WebKit page with false.
+# Covers: the engine a tab gets, the page's world kept apart from Cra's, the DevTools methods Cra
+# calls, FairPlay, moving between engines both ways, split view with one page of each, the sidebar
+# player and its media session buttons, a Little Window, tab sleep and waking, closing the page.
+# No & in a script: it ends the cra:// query. The clip is silent and paused before its tab is left: nothing plays aloud or pops out in
+# Picture in Picture while it runs behind your windows.
+budget rss=900 stalls50=40
+pace 0.5
+
+# A Chromium tab, then a service: WebKit, Safari's user agent, the page's world without Cra's.
+cra://open?url=${PAGE}?n=chromium
+expect-log loaded 127\.0\.0\.1 \(HTTP 200\)
+cra://open?url=${WEBKIT}/page.html?n=webkit
+expect-log opens a page for localhost
+expect-log loaded localhost \(HTTP 200\)
+cra://debug?cdp=Runtime.evaluate&params={"expression":"[document.title,'userAgentData' in navigator,navigator.userAgent.includes('Safari/605.1.15'),typeof window.__cra].join()"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Fixture webkit,false,true,undefined"
+# Cra's isolated world: PageScript's long-task counter answers there (the page probe uses it too).
+expect-log page localhost: .*painted
+cra://debug?cdp=Runtime.evaluate&params={"expression":"navigator.requestMediaKeySystemAccess('com.apple.fps',[{initDataTypes:['skd'],videoCapabilities:[{contentType:'application/vnd.apple.mpegurl'}]}]).then(()=>'fairplay:yes',e=>'fairplay:'+e.name)","awaitPromise":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"fairplay:yes"
+cra://debug?cdp=Page.captureScreenshot&params={"format":"jpeg","quality":80}
+expect-log Cra cdp Page.captureScreenshot → \{"data":"/9j/
+cra://debug?cdp=Page.getLayoutMetrics
+expect-log Cra cdp Page.getLayoutMetrics → .*cssContentSize
+cra://debug?cdp=Cra.discard
+expect-log Cra cdp Cra.discard → error: Cra.discard is not available in a WebKit page
+
+# A Chromium page's own navigation to the service moves to WebKit before its request goes out.
+cra://open?url=${PAGE}?n=link
+expect-log loaded 127\.0\.0\.1
+cra://debug?pageJS=location.href='${WEBKIT}/page.html?n=moved'
+expect-log moves to WebKit for localhost
+wait 2
+cra://debug?cdp=Runtime.evaluate&params={"expression":"[document.title,'userAgentData' in navigator].join()"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Fixture moved,false"
+# An address typed for that tab goes back to Chromium.
+cra://navigate?url=${PAGE}?n=typed
+expect-log moves to Chromium for 127\.0\.0\.1
+wait 2
+cra://debug?cdp=Runtime.evaluate&params={"expression":"[document.title,'userAgentData' in navigator].join()"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Fixture typed,true"
+
+# Split view: the Chromium page on the left, a WebKit player in the new pane.
+cra://action/addSplitView
+wait 1
+cra://navigate?url=${WEBKIT}/media.html
+expect-log shown: localhost
+wait 2
+cra://debug?cdp=Runtime.evaluate&params={"expression":"document.querySelector('video').play().then(()=>'playing:'+('userAgentData' in navigator))","awaitPromise":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"playing:false"
+# The WebKit page fills its pane (half the window), not the whole card.
+cra://debug?cdp=Runtime.evaluate&params={"expression":"['pane',innerWidth>300?innerWidth<800:false,document.querySelector('video').videoWidth,document.querySelector('video').webkitSupportsPresentationMode('picture-in-picture')].join()"}
+# Picture in Picture is on (WebKit has it off for apps other than Safari until asked).
+expect-log Cra cdp Runtime.evaluate .*"value":"pane,true,320,true"
+wait 2
+# The sidebar player has it, with the page's own previous/next handlers.
+cra://debug?nowPlaying=state&label=split
+expect-log Cra nowPlaying\[split\] localhost playing=1 prev=1 next=1 video=1 pip=0
+cra://debug?nowPlaying=next
+wait 1
+cra://debug?cdp=Runtime.evaluate&params={"expression":"document.title"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Media nexttrack"
+cra://debug?nowPlaying=toggle
+wait 1
+cra://debug?nowPlaying=state&label=paused
+expect-log Cra nowPlaying\[paused\] localhost playing=0
+# Playing on out of sight (Spotify while you browse other tabs): the card stays playing. No
+# Picture in Picture for this video, so leaving its tab pops nothing out over your screen.
+cra://debug?cdp=Runtime.evaluate&params={"expression":"(v=>(v.disablePictureInPicture=true,v.play().then(()=>'again')))(document.querySelector('video'))","awaitPromise":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"again"
+cra://open?url=${PAGE}?n=away
+wait 5
+cra://debug?nowPlaying=state&label=away
+expect-log Cra nowPlaying\[away\] localhost playing=1 prev=1 next=1 video=1 pip=0
+cra://debug?nowPlaying=toggle&label=stopped
+expect-log Cra nowPlaying\[stopped\] localhost
+cra://debug?checkStore=1
+
+# A Little Window for a service is WebKit too.
+cra://open?url=${WEBKIT}/page.html?n=little&little=1
+wait 3
+cra://debug?cdp=Runtime.evaluate&target=little&params={"expression":"[document.title,'userAgentData' in navigator].join()"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Fixture little,false"
+
+# Tab sleep: the hidden WebKit page closes (WebKit has no in-place discard) and opens again when shown.
+cra://open?url=${WEBKIT}/page.html?n=sleeper
+expect-log loaded localhost
+cra://open?url=${PAGE}?n=front
+wait 2
+cra://debug?sleepTabs=1
+expect-log tab sleep unloads localhost
+cra://action/nextTab
+wait 3
+cra://debug?cdp=Runtime.evaluate&params={"expression":"[document.title,'userAgentData' in navigator].join()"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Fixture sleeper,false"
+cra://action/closeTab
+wait 2
+reject-log WebKit page process ended
diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.sh
index 4b737d5..e41fb11 100755
--- a/Tests/test-browser-manager.sh
+++ b/Tests/test-browser-manager.sh
@@ -11,7 +11,7 @@ xcrun swiftc -swift-version 5 -emit-module -emit-library -module-name CraCEF \
xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} -I "$TEST_DIR" -L "$TEST_DIR" -lCraCEF \
-Xlinker -rpath -Xlinker "$TEST_DIR" \
"$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Sources/Cra/Services/Scheduler.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/PageProbe.swift Sources/Cra/Services/Persistence.swift \
- Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift Packages/CraCore/Sources/CraCore/PermissionPrompt.swift Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \
+ Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift Packages/CraCore/Sources/CraCore/PermissionPrompt.swift Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift Packages/CraCore/Sources/CraCore/ProtectedMedia.swift Sources/Cra/Services/WebKit/PageEngines.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \
Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests"
"$TEST_DIR/lifecycle-tests"
[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/lifecycle-tests" "$CRA_TEST_KEEP/"
diff --git a/docs/development.md b/docs/development.md
index a5ce160..0a6bd4a 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -33,6 +33,8 @@ issue when a newer stable CEF is out; `scripts/update-cef.sh` moves the pin.
view, windows, settings, onboarding)
- `Sources/CraCEF` — Objective-C++ bridge between Swift and CEF
- `Sources/CraHelper` — Chromium subprocess executable
+- `Sources/Cra/Services/WebKit` — the WebKit page that DRM services open in
+ ([protected-media.md](protected-media.md))
- `Packages/CraCore` — models and decisions with no AppKit or Chromium (the sidebar model,
settings and the other data-folder files, Air Traffic Control, live folder data, key chords,
space themes, Arc theme import, the favorites grid), visible in every `Sources/Cra` file.
@@ -114,7 +116,9 @@ sidebar link, `pageJS=<js>` runs script in the focused page, `installExtension=<
memory-pressure sweep at that level, if Settings ▸ Tabs has it on), `stall=<ms>` (blocks the main
thread), `perfReport=<path>` (the recorder's perf.json now), `systemAppearance=light|dark|system`
(the appearance Auto space themes follow, without changing the Mac's), `themeEditor=1` (Edit
-Theme Color… for the focused space), `relaunch=1` and `quit=1`.
+Theme Color… for the focused space), `relaunch=1`, `quit=1`, and `nowPlaying=state|toggle|next|previous|pip|dismiss` (the sidebar player's
+newest card, then a `Cra nowPlaying[<label>] <host> playing=… prev=… next=… video=… pip=…` line per card
+on stdout; `&label=` tells checks apart).
## Running a test instance
diff --git a/docs/protected-media.md b/docs/protected-media.md
new file mode 100644
index 0000000..b311a4d
--- /dev/null
+++ b/docs/protected-media.md
@@ -0,0 +1,117 @@
+# Protected media (DRM)
+
+Spotify, Netflix, Disney+ and the other big services open in a WebKit page inside Cra, not a
+Chromium one. WebKit plays their DRM with Apple's FairPlay, which macOS gives every app for free.
+Everything else stays in Chromium.
+
+## Why
+
+Chromium's Widevine CDM works in Cra: the component updater installs it, and sites whose licence
+policy doesn't ask for more play (Shaka's Widevine demo does). The big services ask for more:
+**Verified Media Path** (VMP), a signature over the browser's own binaries (`.sig` files next to
+the framework and helpers) made with a certificate that Google licenses through paid partners.
+Without it:
+
+- Spotify's licence server answers 403/500 and the web player skips track after track.
+- Disney+ shows error 83 (GitHub #66).
+- Netflix and Max refuse to play, or play in low quality.
+
+Getting VMP costs about €10,000 up front (castLabs: a code audit of Cra's Chromium build, then a
+signing service at about a third of that per year), plus a Widevine licence agreement and a
+company. Re-signing every release and CEF build would also tie the release pipeline to a
+third party.
+
+FairPlay needs none of that. The content provider pays for its FairPlay licence; the browser
+only hosts Apple's CDM, which every WKWebView gets. A plain, ad-hoc-signed test app with no
+entitlements played EZDRM's public FairPlay stream end to end (certificate, licence request,
+licence, keys usable, 720p playing). That is the whole requirement.
+
+## How it works
+
+`ProtectedMediaSites` (CraCore) holds the rules, with tests:
+
+- **Which pages:** the services' web players. Each host matches itself and its subdomains:
+ `open.spotify.com`, `netflix.com`, `disneyplus.com`, `max.com`, `hbomax.com`,
+ `primevideo.com`, `hulu.com`, `paramountplus.com`, `peacocktv.com`, `tv.apple.com`,
+ `music.apple.com`, `listen.tidal.com` and `www.deezer.com`. They are players, not whole domains, except where nothing else signs in through the service (Max sends `play.max.com` on to `www.hbomax.com` and signs in on its own hosts):
+ other sites send their "Sign in with Spotify/Tidal/Deezer" through `accounts.spotify.com`,
+ `login.tidal.com` and `connect.deezer.com`, and those must finish in the engine they started in.
+- **A page Cra opens** (a tab restored or created, a link opened in a new tab, a Little Window, an
+ address typed, a pinned tab reset) gets WebKit for a listed site and Chromium for anything else.
+- **A Chromium page's own navigation** (a link, a redirect, history) to a listed site is stopped
+ before its request goes out. Then the tab's page opens again in WebKit at that address, in the
+ same split pane and with the same focus. Stopping it that early means a sign-in callback's
+ one-time code is spent where the session will live. A POST stays in Chromium, because its body
+ can't move.
+- **A WebKit page stays in WebKit** wherever it navigates by itself, because sign-in goes through
+ other sites (accounts.google.com, appleid.apple.com) and has to come back to the same cookies.
+ Only Cra's own navigation (the URL bar) picks the engine again.
+- **A popup** (`window.open`) keeps its opener's engine, so `window.opener` still works for
+ sign-in windows.
+
+`WebKitBrowser` (`Sources/Cra/Services/WebKit/`) is a `CraBrowser` subclass backed by a
+`WKWebView`. It hosts the way Alloy pages do: its view sits in `containerView`, which split view
+places in the pane, and it has no `hostWindow`. It sends the same delegate callbacks as CraCEF.
+It also answers the DevTools Protocol methods Cra calls from WebKit's own API:
+
+| Cra calls | WebKit page |
+|---|---|
+| `Runtime.evaluate`, isolated world | `evaluateJavaScript` / `callAsyncJavaScript` in the page world or in the `cra` content world, answered in the protocol's JSON. Both run as a user gesture. |
+| `Page.captureScreenshot` | `takeSnapshot` (tab switcher, Capture); the full page goes through `createPDF` |
+| `Page.getLayoutMetrics` | the document's scroll size and the visual viewport |
+| `Storage.clearDataForOrigin`, `Network.clearBrowserCache` | the profile's `WKWebsiteDataStore` |
+| `Cra.setFreezingVote`, `Cra.load` | accepted; WebKit throttles hidden pages itself |
+| `Cra.discard`, `Cra.getFreezingState`, `Target.*` | an error. Tab sleeping then closes the page, and it loads again when shown; extension actions don't apply. |
+
+PageScript's two scripts run in WebKit as user scripts, in the page world and in a `cra`
+content world. With them come Cra's typed-text and long-task tracking, the sidebar player's
+media session buttons and its volume. A small addition in the `cra` world reports what Chromium
+tells CraCEF natively: media playing, Picture in Picture and link hovers (the status bubble).
+WebKit's `_isPlayingAudio` drives the speaker when this macOS has it.
+
+Cookies and storage live in WebKit, one persistent `WKWebsiteDataStore` per Cra profile and one
+throwaway store per incognito session (`WebKitStores`). The store's identifier comes from the
+data folder plus the profile, so a test instance (`CRA_DATA_DIR`) never shares the daily one's.
+Deleting a profile deletes its WebKit store at the next launch, together with its Chromium
+folder. The user agent is Safari's (`Version/<Safari's version> Safari/605.1.15`), because the
+services pick their DRM by browser.
+
+## What a WebKit page doesn't have
+
+- **Chrome extensions**, including password managers' autofill: those services are signed into
+ once, by hand or from the password manager's own app.
+- **Chromium's logins and cookies**: the first visit to a service signs in again.
+- **Chromium's site settings, content blocking and HTTPS-Only**: camera and microphone ask
+ through Cra's prompt on every visit.
+- **Chrome's DevTools**: Develop ▸ Developer Tools opens WebKit's Web Inspector in its own window.
+- **Arc's Picture in Picture window**: the video goes to the system's own Picture in Picture
+ window, with its controls. Auto Picture in Picture, the sidebar player's button and coming
+ back to the tab work as for Chromium pages.
+- **Chromium's fullscreen handling**: WebKit takes a fullscreen video to its own fullscreen
+ window, as in Safari.
+- **In-place tab sleep**: a sleeping WebKit page closes and loads its address again when shown.
+ Its back/forward list goes with it.
+
+## Settings
+
+ defaults write dk.kildahl.cra webKitProtectedMedia -bool NO # every page Chromium's again
+ defaults write dk.kildahl.cra webKitProtectedMediaHosts -array crunchyroll.com
+ defaults write dk.kildahl.cra webKitProtectedMediaRemovedHosts -array netflix.com
+
+They are read at launch. A test instance takes `CRA_WEBKIT_DRM=0|1` and
+`CRA_WEBKIT_HOSTS=<host,host>` (the scenarios list `localhost`).
+
+## Testing
+
+- `swift test --package-path Packages/CraCore --filter ProtectedMedia`: the rules.
+- `Tests/test-browser-manager.sh` (`pageEngineCase`): the real `BrowserManager` and
+ `PageEngines` choosing engines, popups keeping their opener's engine, and handoffs in both
+ directions keeping the split, its order and its focus.
+- `scripts/scenario.sh webkit-drm-tabs`: the running app. The fixture server is reached as
+ `localhost`, which the run lists, so it needs no network and no account. The scenario covers
+ FairPlay being offered and every emulated protocol method. It also covers both handoffs, split
+ view with one engine per pane, the sidebar player and its media-session buttons, playback
+ while the tab is out of sight, a Little Window, tab sleep, waking and closing.
+- By hand (L5), with real accounts: Spotify plays track after track, Netflix and Disney+ play,
+ Picture in Picture opens and returns, fullscreen enters and leaves, ⌘-shortcuts reach Cra, Peek
+ works, and sign-in through Google or Apple comes back signed in.
diff --git a/scripts/scenario.sh b/scripts/scenario.sh
index fb57c4e..4f5a200 100755
--- a/scripts/scenario.sh
+++ b/scripts/scenario.sh
@@ -30,7 +30,8 @@
# requires screen
# port <n> serve ${PAGE} on a fixed port (snapshots show the address)
# ${FIXTURES}, ${PAGE} (Tests/Fixtures/Pages/page.html from a local server, so it has a host
-# for developer mode and tab sleep), ${EXTENSION_ID} (Tests/Fixtures/Extension) and
+# for developer mode and tab sleep), ${WEBKIT} (that server as http://localhost:<port>, a host the
+# run treats as a DRM service, so its pages open in WebKit), ${EXTENSION_ID} (Tests/Fixtures/Extension) and
# ${SIDE_PANEL_EXTENSION_ID} (Tests/Fixtures/SidePanelExtension) expand.
set -uo pipefail
cd "$(dirname "$0")/.."
@@ -83,8 +84,11 @@ python3 -I -u -m http.server --bind 127.0.0.1 --directory "$FIXTURES/Pages" "${F
SERVER=$!
for _ in $(seq 1 50); do PORT=$(sed -n 's/.*port \([0-9]*\).*/\1/p' "$OUT/server.log" | head -1); [ -n "$PORT" ] && break; sleep 0.1; done
PAGE="http://127.0.0.1:${PORT:?http server did not start}/page.html"
+# The same server under another host, which the run lists as a DRM service (CRA_WEBKIT_HOSTS):
+# its pages open in WebKit, the way Spotify and Netflix do (ProtectedMediaSites).
+WEBKIT="http://localhost:${PORT}"
-CRA_DATA_DIR="$DATA" CRA_COMMAND_FILE="$CMD" CRA_HITCH_LOG="$HITCH" CRA_TEST_BACKGROUND=1 \
+CRA_DATA_DIR="$DATA" CRA_COMMAND_FILE="$CMD" CRA_HITCH_LOG="$HITCH" CRA_TEST_BACKGROUND=1 CRA_WEBKIT_HOSTS=localhost \
CRA_ARC_DIR="$FIXTURES/Arc" CRA_FLAGS="${CRA_FLAGS:-}" \
"$APP/Contents/MacOS/Cra" >"$OUT/stdout.log" 2>&1 &
PID=$!
@@ -122,7 +126,7 @@ sleep 2
PACE=0.2
RSS_BUDGET=1500 MAXSTALL=1500 STALLS50=10 LAUNCHSTALL=1000 PERFCPU=0.1
BASELINE=""
-expand() { local s="$1"; s="${s//\$\{FIXTURES\}/$FIXTURES}"; s="${s//\$\{PAGE\}/$PAGE}"; s="${s//\$\{EXTENSION_ID\}/$EXTENSION_ID}"; s="${s//\$\{SIDE_PANEL_EXTENSION_ID\}/$SIDE_PANEL_EXTENSION_ID}"; printf '%s' "$s"; }
+expand() { local s="$1"; s="${s//\$\{FIXTURES\}/$FIXTURES}"; s="${s//\$\{PAGE\}/$PAGE}"; s="${s//\$\{WEBKIT\}/$WEBKIT}"; s="${s//\$\{EXTENSION_ID\}/$EXTENSION_ID}"; s="${s//\$\{SIDE_PANEL_EXTENSION_ID\}/$SIDE_PANEL_EXTENSION_ID}"; printf '%s' "$s"; }
echo "$NAME (pid $PID, logs in ${OUT#$ROOT/})"
while IFS= read -r raw || [ -n "$raw" ]; do