SPB Git

Repository Public License

WebEngine.swift 26.0 KB 512 lines swift

1import Diagnostics2import Foundation3import NavigatorCore4import Observation5import WebKit67/// One tab's web page: owns (at most) one `WKWebView`, mirrors its state into observable properties and exposes8/// every command the browser needs. Named `WebEngine` because WebKit itself ships a `WebPage` type since OS 26.9///10/// The web view can be released and recreated (`suspend()` / `resume()`); the engine and its observable state11/// outlive it. Call `close()` when the tab is closed.12@MainActor13@Observable14public final class WebEngine: Identifiable {15    // MARK: Identity1617    public nonisolated let id: TabID18    public let profile: ProfileContext19    /// The tab that opened this one through `window.open` / `target=_blank`.20    public let openerID: TabID?21    public internal(set) var settings: WebEngineSettings2223    /// The live web view, or `nil` while the tab is dormant or suspended. Host it with `WebEngineView`.24    public internal(set) var webView: NavigatorWebView?2526    // MARK: Observable page state2728    public internal(set) var url: URL?29    public internal(set) var title: String = ""30    public internal(set) var estimatedProgress: Double = 031    public internal(set) var isLoading = false32    public internal(set) var canGoBack = false33    public internal(set) var canGoForward = false34    public internal(set) var hasOnlySecureContent = false35    /// Certificate chain of the committed page (https only).36    public internal(set) var serverTrust: ServerTrustSummary?37    /// Best icon declared by the page, or `/favicon.ico` of the origin until the page reports its own.38    public internal(set) var faviconURL: URL?39    public internal(set) var metadata: PageMetadata?40    /// `theme-color` as parsed by WebKit.41    public internal(set) var themeColor: RGBAColor?42    public internal(set) var underPageBackgroundColor: RGBAColor?43    /// A media element of the page is playing with sound (derived by script, see WEBKIT_LIMITATIONS.md).44    public internal(set) var isPlayingAudio = false45    public internal(set) var mediaActivity = MediaActivity()46    public internal(set) var isMuted = false47    public internal(set) var cameraCapture: MediaCaptureStatus = .none48    public internal(set) var microphoneCapture: MediaCaptureStatus = .none49    public internal(set) var fullscreenState: WebFullscreenState = .notInFullscreen50    public internal(set) var processState: WebProcessState = .running51    public internal(set) var lifecycle: TabLifecycle52    public internal(set) var suspendedPage: SuspendedPage?5354    // MARK: Observable errors and interstitials (the UI renders native pages from these)5556    public internal(set) var loadError: PageLoadError?57    public internal(set) var certificateError: CertificateError?58    public internal(set) var httpsUpgradeFailure: HTTPSUpgradeFailure?59    /// Most recent first, at most 20.60    public internal(set) var blockedNavigations: [BlockedNavigation] = []61    /// Windows the current page tried to open without a user gesture. Cleared on navigation.62    public internal(set) var blockedPopups: [BlockedPopup] = []63    /// Sub-resource requests cancelled because of an invalid certificate on the current page.64    public internal(set) var insecureSubresourceBlockCount = 065    /// JavaScript dialogs auto-dismissed on the current page after the user chose to suppress them.66    public internal(set) var suppressedDialogCount = 067    public internal(set) var areDialogsSuppressed = false6869    // MARK: Observable view state7071    public internal(set) var pageZoom: Double = 172    /// iOS only: `-webkit-text-size-adjust` percentage applied to pages (100 = unchanged).73    public internal(set) var textSizePercent: Int = 10074    public internal(set) var contentMode: UserAgentMode75    public internal(set) var scroll = ScrollMetrics()76    public internal(set) var scrollDirection: ScrollDirection = .none77    public internal(set) var selection: TextSelection?78    public internal(set) var contextElement: ContextMenuElement?79    public internal(set) var isPickingElement = false80    public internal(set) var lastPickedElement: PickedElement?81    /// Dev module: captured errors and (when mirroring is on) console output of the current page, oldest first.82    public internal(set) var consoleEntries: [ConsoleEntry] = []83    public internal(set) var lastFind: FindOutcome?84    public internal(set) var isInspectable: Bool85    public internal(set) var isContentBlockingEnabled = true86    public internal(set) var lastActiveAt: Date = .now87    /// Address of the document committed in the main frame (`nil` before the first commit). Unlike `url`, it88    /// never shows an address that is still loading or that failed.89    public internal(set) var committedURL: URL?90    /// Number of main-frame documents committed by this engine. Observing it tells a reload of the same address91    /// apart from no navigation at all.92    public internal(set) var commitCount = 09394    // MARK: Delegates9596    @ObservationIgnored public weak var navigationDelegate: (any WebEngineNavigationDelegate)?97    @ObservationIgnored public weak var uiDelegate: (any WebEngineUIDelegate)?98    @ObservationIgnored public weak var contextMenuDelegate: (any WebEngineContextMenuDelegate)?99100    // MARK: Internal bookkeeping (not observable)101102    @ObservationIgnored var adapter: WebEngineAdapter!103    @ObservationIgnored var scriptRegistry: UserScriptRegistry?104    @ObservationIgnored var observations: [NSKeyValueObservation] = []105    /// Descriptors installed by features; re-installed when the web view is recreated.106    @ObservationIgnored var featureScripts: [UserScriptDescriptor] = []107    @ObservationIgnored var pendingAppURL: URL?108    /// Target of the main-frame navigation in flight (updated on every redirect).109    @ObservationIgnored var provisionalMainURL: URL?110    @ObservationIgnored var pendingTransition: NavigationEntry.Transition = .link111    @ObservationIgnored var isRestoringSession = false112    @ObservationIgnored var dormantSessionState: Data?113    @ObservationIgnored var httpsUpgradeAttempt: (original: URL, upgraded: URL)?114    @ObservationIgnored var pendingCertificateError: CertificateError?115    @ObservationIgnored var dialogSequence = 0116    @ObservationIgnored var lastUserActivation: Date?117    @ObservationIgnored var popupVerdicts: [WebOrigin: PermissionDecision.Verdict] = [:]118    @ObservationIgnored var mediaFrames: [String: MediaActivity] = [:]119    @ObservationIgnored var mediaFrameInfos: [String: WKFrameInfo] = [:]120    @ObservationIgnored var contextElementDate: Date?121    @ObservationIgnored var isExternalRequestPending = false122    @ObservationIgnored var lastRecordedVisitURL: URL?123    @ObservationIgnored var usesNativeScrollObservation = false124    @ObservationIgnored var terminationCount = 0125    /// Messages refused by the bridge validator since the engine was created.126    @ObservationIgnored public internal(set) var rejectedBridgeMessageCount = 0127    @ObservationIgnored var isClosed = false128129    // MARK: Init130131    /// A live tab with an empty web view.132    public convenience init(profile: ProfileContext, id: TabID = TabID(), settings: WebEngineSettings = WebEngineSettings()) {133        self.init(profile: profile, id: id, settings: settings, openerID: nil, lifecycle: .live)134        createWebView(adopting: nil)135    }136137    /// A tab restored from storage. No web view is created until `resume()`: the tab shows its saved title and138    /// address, and costs no web process.139    public convenience init(profile: ProfileContext, restoring tab: Tab, settings: WebEngineSettings = WebEngineSettings()) {140        var settings = settings141        settings.contentMode = tab.userAgentMode142        self.init(profile: profile, id: tab.id, settings: settings, openerID: tab.parentID, lifecycle: .dormant)143        url = tab.url144        title = tab.title145        faviconURL = tab.faviconURL146        pageZoom = Self.clampZoom(tab.zoom)147        isMuted = tab.isMuted148        dormantSessionState = tab.sessionState149    }150151    /// A child opened by a page; `configuration` is the one WebKit supplied and must be used as is.152    convenience init(profile: ProfileContext, settings: WebEngineSettings, opener: TabID,153                     adopting configuration: WKWebViewConfiguration) {154        self.init(profile: profile, id: TabID(), settings: settings, openerID: opener, lifecycle: .live)155        createWebView(adopting: configuration)156    }157158    private init(profile: ProfileContext, id: TabID, settings: WebEngineSettings, openerID: TabID?, lifecycle: TabLifecycle) {159        self.id = id160        self.profile = profile161        self.settings = settings162        self.openerID = openerID163        self.lifecycle = lifecycle164        self.contentMode = settings.contentMode165        self.isInspectable = settings.isInspectable166        self.adapter = WebEngineAdapter(engine: self)167        profile.register(self)168    }169170    /// Releases the web view and detaches from the profile. The engine must not be used afterwards.171    public func close() {172        guard !isClosed else { return }173        isClosed = true174        destroyWebView()175        profile.unregister(self)176    }177178    // MARK: Web view lifecycle179180    func createWebView(adopting adopted: WKWebViewConfiguration?) {181        precondition(webView == nil, "The engine already has a web view")182        let configuration: WKWebViewConfiguration183        if let adopted {184            // WebKit hands the opener's configuration: same data store and process relationship (required for185            // `window.opener`). It also shares the opener's user content controller, which would route this186            // page's bridge messages to the opener — so the child gets its own.187            configuration = adopted188            profile.apply(settings, to: configuration)189            configuration.userContentController = profile.makeUserContentController()190            if configuration.urlSchemeHandler(forURLScheme: InternalPage.scheme) == nil {191                configuration.setURLSchemeHandler(profile.internalSchemeHandler, forURLScheme: InternalPage.scheme)192            }193        } else {194            configuration = profile.makeConfiguration(settings: settings)195        }196197        let controller = configuration.userContentController198        if !isContentBlockingEnabled { controller.removeAllContentRuleLists() }199        for world in [ScriptWorld.bridge, .lens, .dev] {200            controller.add(adapter, contentWorld: world.contentWorld, name: WebRuntimeConstants.bridgeHandlerName)201        }202        let registry = UserScriptRegistry(controller: controller)203        scriptRegistry = registry204        installBuiltInScripts(in: registry)205        for descriptor in featureScripts { registry.install(descriptor) }206        if settings.mirrorsConsole { installConsoleMirror(in: registry, controller: controller) }207208        let view = NavigatorWebView(frame: CGRect(origin: .zero, size: settings.offscreenSize), configuration: configuration)209        view.engine = self210        view.navigationDelegate = adapter211        view.uiDelegate = adapter212        view.allowsBackForwardNavigationGestures = settings.allowsBackForwardGestures213        view.allowsLinkPreview = settings.allowsLinkPreview214        view.isInspectable = isInspectable215        #if os(macOS)216        view.allowsMagnification = settings.allowsMagnification217        #endif218        view.pageZoom = pageZoom219        webView = view220        applyUserAgent()221        observe(view)222    }223224    func destroyWebView() {225        observations.forEach { $0.invalidate() }226        observations.removeAll()227        guard let view = webView else { return }228        view.stopLoading()229        view.navigationDelegate = nil230        view.uiDelegate = nil231        view.engine = nil232        view.configuration.userContentController.removeAllScriptMessageHandlers()233        view.removeFromSuperview()234        scriptRegistry = nil235        webView = nil236        mediaFrames.removeAll()237        mediaFrameInfos.removeAll()238        isLoading = false239        estimatedProgress = 0240        isPlayingAudio = false241        mediaActivity = MediaActivity()242        cameraCapture = .none243        microphoneCapture = .none244    }245246    private func installBuiltInScripts(in registry: UserScriptRegistry) {247        if isMuted { registry.install(Self.mutePreamble) }248        registry.install(UserScriptDescriptor(id: "orix.builtin.activation", source: BundledScript.activation.source,249                                              world: .bridge, injectionTime: .documentStart, mainFrameOnly: false))250        registry.install(UserScriptDescriptor(id: "orix.builtin.media", source: BundledScript.mediaState.source,251                                              world: .bridge, injectionTime: .documentStart, mainFrameOnly: false))252        registry.install(UserScriptDescriptor(id: "orix.builtin.context", source: BundledScript.contextElement.source,253                                              world: .bridge, injectionTime: .documentStart, mainFrameOnly: false))254        registry.install(UserScriptDescriptor(id: "orix.builtin.metadata", source: BundledScript.pageMetadata.source,255                                              world: .bridge, injectionTime: .documentEnd, mainFrameOnly: true))256        registry.install(UserScriptDescriptor(id: "orix.builtin.scroll", source: BundledScript.scrollReporter.source,257                                              world: .bridge, injectionTime: .documentEnd, mainFrameOnly: true))258        registry.install(UserScriptDescriptor(id: "orix.builtin.dev-errors", source: BundledScript.devErrors.source,259                                              world: .dev, injectionTime: .documentStart, mainFrameOnly: true))260        if settings.reportsSelection {261            registry.install(UserScriptDescriptor(id: "orix.builtin.lens", source: BundledScript.lens.source,262                                                  world: .lens, injectionTime: .documentEnd, mainFrameOnly: true))263        }264    }265266    static let mutePreamble = UserScriptDescriptor(id: "orix.builtin.mute", source: "window.__orixInitialMute = true;",267                                                   world: .bridge, injectionTime: .documentStart, mainFrameOnly: false)268    static let consoleMirrorID = "orix.builtin.dev-console"269270    func installConsoleMirror(in registry: UserScriptRegistry, controller: WKUserContentController) {271        guard !registry.isInstalled(Self.consoleMirrorID) else { return }272        controller.add(adapter, contentWorld: .page, name: WebRuntimeConstants.consoleHandlerName)273        registry.install(UserScriptDescriptor(pageWorldID: Self.consoleMirrorID, source: BundledScript.devConsole.source,274                                              injectionTime: .documentStart, mainFrameOnly: true))275    }276277    // MARK: KVO → observable state278279    private func observe(_ view: NavigatorWebView) {280        // WKWebView posts KVO on the main thread; `assumeIsolated` states that fact instead of hopping, which281        // would reorder updates relative to delegate callbacks.282        func watch<Value>(_ keyPath: KeyPath<NavigatorWebView, Value>, _ apply: @escaping @MainActor (WebEngine, NavigatorWebView) -> Void) {283            observations.append(view.observe(keyPath, options: [.initial, .new]) { [weak self] view, _ in284                MainActor.assumeIsolated {285                    guard let self, self.webView === view else { return }286                    apply(self, view)287                }288            })289        }290        watch(\.title) { engine, view in291            let title = view.title ?? ""292            // WebKit clears the title while a new page is loading; the previous one stays until a real one arrives.293            guard !title.isEmpty || !view.isLoading else { return }294            engine.assign(\.title, title)295            engine.noteTitleChanged()296        }297        watch(\.url) { engine, view in298            // After a failed or suspended load WebKit reports nil; the last address stays visible.299            if let url = view.url { engine.assign(\.url, url) }300            engine.noteURLChanged()301        }302        watch(\.estimatedProgress) { engine, view in engine.assign(\.estimatedProgress, view.estimatedProgress) }303        watch(\.isLoading) { engine, view in engine.assign(\.isLoading, view.isLoading) }304        watch(\.canGoBack) { engine, view in engine.assign(\.canGoBack, view.canGoBack) }305        watch(\.canGoForward) { engine, view in engine.assign(\.canGoForward, view.canGoForward) }306        watch(\.hasOnlySecureContent) { engine, view in engine.assign(\.hasOnlySecureContent, view.hasOnlySecureContent) }307        watch(\.serverTrust) { engine, _ in engine.refreshServerTrust() }308        watch(\.themeColor) { engine, view in engine.assign(\.themeColor, RGBAColor(view.themeColor)) }309        watch(\.underPageBackgroundColor) { engine, view in310            engine.assign(\.underPageBackgroundColor, RGBAColor(view.underPageBackgroundColor))311        }312        watch(\.cameraCaptureState) { engine, view in engine.assign(\.cameraCapture, MediaCaptureStatus(view.cameraCaptureState)) }313        watch(\.microphoneCaptureState) { engine, view in314            engine.assign(\.microphoneCapture, MediaCaptureStatus(view.microphoneCaptureState))315        }316        watch(\.fullscreenState) { engine, view in317            let state: WebFullscreenState = switch view.fullscreenState {318            case .enteringFullscreen: .entering319            case .inFullscreen: .inFullscreen320            case .exitingFullscreen: .exiting321            default: .notInFullscreen322            }323            engine.assign(\.fullscreenState, state)324        }325    }326327    /// Writes only real changes, so observers are not invalidated by KVO echoes.328    func assign<Value: Equatable>(_ keyPath: ReferenceWritableKeyPath<WebEngine, Value>, _ value: Value) {329        if self[keyPath: keyPath] != value { self[keyPath: keyPath] = value }330    }331332    func refreshServerTrust() {333        guard let view = webView, let trust = view.serverTrust, let current = view.url,334              current.scheme?.lowercased() == "https", let host = current.host() else {335            assign(\.serverTrust, nil)336            return337        }338        let port = current.port ?? 443339        assign(\.serverTrust, ServerTrustSummary(trust: trust, host: host,340                                                 usesUserException: profile.hasCertificateException(host: host, port: port)))341    }342343    private func noteTitleChanged() {344        guard !profile.isGhost, !title.isEmpty, let url = committedURL, Self.isRecordable(url),345              let history = profile.services.history else { return }346        let title = title, profileID = profile.profile.id347        Task { await history.updateTitle(title, for: url, profileID: profileID) }348    }349350    /// Same-document navigations (`history.pushState`, fragment changes) produce no delegate callback: the URL351    /// change is the only signal.352    private func noteURLChanged() {353        guard let view = webView, let current = view.url, !view.isLoading, let committed = committedURL,354              current != committed, WebOrigin(url: current) == WebOrigin(url: committed) else { return }355        committedURL = current356        recordVisit(current, transition: .link)357    }358359    static func isRecordable(_ url: URL) -> Bool {360        let scheme = url.scheme?.lowercased()361        return scheme == "http" || scheme == "https" || scheme == "file"362    }363364    func recordVisit(_ url: URL, transition: NavigationEntry.Transition) {365        guard !profile.isGhost, Self.isRecordable(url), let history = profile.services.history else { return }366        // A reload of the same address is not a new visit.367        if transition == .reload, lastRecordedVisitURL == url { return }368        lastRecordedVisitURL = url369        let visit = PageVisit(profileID: profile.profile.id, tabID: id, url: url, title: "", transition: transition)370        Task { await history.recordVisit(visit) }371    }372373    static func defaultFavicon(for url: URL?) -> URL? {374        guard let url, let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",375              var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }376        components.path = "/favicon.ico"377        components.query = nil378        components.fragment = nil379        components.user = nil380        components.password = nil381        return components.url382    }383384    // MARK: Bridge messages385386    func receive(_ message: WKScriptMessage) {387        guard let view = webView else { return }388        let frame = message.frameInfo389        let envelope = BridgeEnvelope(handlerName: message.name, worldName: message.world.name,390                                      isFromOwnWebView: message.webView === view, isMainFrame: frame.isMainFrame,391                                      frameOrigin: WebOrigin(frame.securityOrigin),392                                      pageOrigin: committedURL.flatMap(WebOrigin.init(url:)), pageURL: committedURL,393                                      body: ScriptValue(any: message.body))394        let validated: BridgeMessage395        do { validated = try BridgeValidator.validate(envelope) } catch {396            // A stale report from the page that was just replaced is expected, not hostile.397            if error != .staleDocument {398                rejectedBridgeMessageCount += 1399                Log.web.notice("Bridge message rejected: \(String(describing: error), privacy: .public)")400            }401            return402        }403        apply(validated, frame: frame)404    }405406    private func apply(_ message: BridgeMessage, frame: WKFrameInfo) {407        switch message {408        case .activation:409            lastUserActivation = .now410        case .metadata(let value):411            assign(\.metadata, value)412            assign(\.faviconURL, value.bestIcon()?.url ?? Self.defaultFavicon(for: value.url))413        case .scroll(let value):414            guard !usesNativeScrollObservation else { return }415            updateScroll(value)416        case .media(let frameID, let activity, let scriptMuted):417            mediaFrames[frameID] = activity418            mediaFrameInfos[frameID] = frame419            if mediaFrames.count > 256 { mediaFrames = mediaFrames.filter { $0.value.totalElements > 0 } }420            var total = MediaActivity()421            for value in mediaFrames.values {422                total.totalElements += value.totalElements423                total.playingElements += value.playingElements424                total.audibleElements += value.audibleElements425                total.isPictureInPictureActive = total.isPictureInPictureActive || value.isPictureInPictureActive426            }427            assign(\.mediaActivity, total)428            assign(\.isPlayingAudio, total.audibleElements > 0)429            // A frame that loaded before the mute preamble existed, or after an unmute: bring it in line.430            if scriptMuted != isMuted { pushMuteState(to: frame) }431        case .context(let value):432            contextElement = value433            contextElementDate = .now434        case .selection(let value):435            assign(\.selection, value.isCollapsed ? nil : value)436        case .elementPicked(let value):437            isPickingElement = false438            lastPickedElement = value439        case .console(let entry):440            consoleEntries.append(entry)441            if consoleEntries.count > 500 { consoleEntries.removeFirst(consoleEntries.count - 500) }442        }443    }444445    func updateScroll(_ value: ScrollMetrics) {446        let delta = value.y - scroll.y447        if abs(delta) >= 1 { assign(\.scrollDirection, delta > 0 ? .down : .up) }448        assign(\.scroll, value)449    }450451    func pushMuteState(to frame: WKFrameInfo?) {452        guard let view = webView else { return }453        let script = "window.__orixMedia ? window.__orixMedia.setMuted(\(isMuted ? "true" : "false")) : null"454        view.evaluateJavaScript(script, in: frame, in: ScriptWorld.bridge.contentWorld, completionHandler: nil)455    }456457    /// Per-page state reset when a new document commits in the main frame.458    func resetPageState(for url: URL?) {459        assign(\.metadata, nil)460        assign(\.faviconURL, Self.defaultFavicon(for: url))461        mediaFrames.removeAll()462        mediaFrameInfos.removeAll()463        assign(\.mediaActivity, MediaActivity())464        assign(\.isPlayingAudio, false)465        assign(\.scroll, ScrollMetrics())466        assign(\.scrollDirection, .none)467        assign(\.selection, nil)468        contextElement = nil469        dialogSequence = 0470        assign(\.areDialogsSuppressed, false)471        assign(\.suppressedDialogCount, 0)472        assign(\.insecureSubresourceBlockCount, 0)473        if !blockedPopups.isEmpty { blockedPopups.removeAll() }474        if !consoleEntries.isEmpty { consoleEntries.removeAll() }475        assign(\.lastFind, nil)476        isPickingElement = false477    }478479    func noteBlocked(_ url: URL, reason: NavigationBlockReason, isMainFrame: Bool) {480        blockedNavigations.insert(BlockedNavigation(url: url, reason: reason, isMainFrame: isMainFrame), at: 0)481        if blockedNavigations.count > 20 { blockedNavigations.removeLast(blockedNavigations.count - 20) }482        Log.web.notice("Navigation blocked: \(reason.rawValue, privacy: .public)")483    }484485    var hasRecentUserActivation: Bool {486        guard let last = lastUserActivation else { return false }487        return Date().timeIntervalSince(last) <= settings.popupActivationWindow488    }489490    /// Fetches the stored popup verdict of an origin so that `createWebView` — which is synchronous — can use it.491    func refreshPopupVerdict(for url: URL?) {492        guard let origin = url.flatMap(WebOrigin.init(url:)), let permissions = profile.services.permissions else { return }493        let profileID = profile.profile.id494        Task { [weak self] in495            let verdict = await permissions.verdict(for: .popups, origin: origin, profileID: profileID)496            self?.popupVerdicts[origin] = verdict497        }498    }499500    static func clampZoom(_ value: Double) -> Double { min(5, max(0.25, value.isFinite ? value : 1)) }501}502503extension WebOrigin {504    /// From WebKit's origin triple. Opaque origins (empty host: `file:`, `data:`, `about:blank`) give `nil`.505    @MainActor init?(_ origin: WKSecurityOrigin) {506        let scheme = origin.protocol.lowercased()507        guard !origin.host.isEmpty, !scheme.isEmpty else { return nil }508        let defaultPort = scheme == "https" ? 443 : scheme == "http" ? 80 : 0509        self.init(scheme: scheme, host: origin.host, port: origin.port == 0 || origin.port == defaultPort ? nil : origin.port)510    }511}512
Files main
Menu

Theme