SPB Git

Repository Public License

WebEngine+Commands.swift 29.3 KB 646 lines swift

1import Diagnostics2import Foundation3import NavigatorCore4import WebKit56#if canImport(AppKit)7import AppKit8public typealias PlatformImage = NSImage9#elseif canImport(UIKit)10import UIKit11public typealias PlatformImage = UIImage12#endif1314// MARK: - Loading1516extension WebEngine {17    /// Loads `url` on behalf of the user (omnibox, bookmark, history). The scheme allow-list applies: a refused18    /// URL is recorded in `blockedNavigations` and the reason is returned (`nil` means the load started). Resumes a suspended tab first.19    @discardableResult20    public func load(_ url: URL, transition: NavigationEntry.Transition = .typed) -> WebEngineError? {21        var navigationSettings = settings.navigation22        navigationSettings.httpAllowedHosts.formUnion(profile.httpAllowedHosts)23        switch NavigationPolicy.decideAppLoad(url, settings: navigationSettings) {24        case .block(let reason):25            noteBlocked(url, reason: reason, isMainFrame: true)26            return .navigationBlocked(reason)27        case .external:28            // The omnibox does not launch applications; only a page link may ask, and the user confirms.29            noteBlocked(url, reason: .externalAppUnavailable, isMainFrame: true)30            return .navigationBlocked(.externalAppUnavailable)31        case .upgradeToHTTPS(let upgraded):32            httpsUpgradeAttempt = (original: url, upgraded: upgraded)33            startLoad(upgraded, transition: transition)34            return nil35        case .allow, .download:36            startLoad(url, transition: transition)37            return nil38        }39    }4041    /// Classifies omnibox text and loads the address or the search. `javascript:`, `data:` and friends typed in42    /// the omnibox are refused, never executed.43    @discardableResult44    public func load(input: String, searchEngine: SearchEngine = .default,45                     classifier: OmniboxClassifier? = nil) -> WebEngineError? {46        let classifier = classifier ?? OmniboxClassifier(allowsFileURLs: settings.navigation.allowsFileURLs)47        switch classifier.classify(input) {48        case .empty:49            return nil50        case .url(let url):51            return load(url, transition: .typed)52        case .search(let query):53            return loadSearch(query, engine: searchEngine)54        case .blocked(let scheme):55            let reason: NavigationBlockReason = NavigationPolicy.scriptSchemes.contains(scheme) ? .scriptScheme56                : scheme == "file" ? .localFileFromWeb : .opaqueTopLevelDocument57            if let url = URL(string: "\(scheme):") { noteBlocked(url, reason: reason, isMainFrame: true) }58            return .navigationBlocked(reason)59        }60    }6162    @discardableResult63    public func loadSearch(_ query: String, engine: SearchEngine = .default) -> WebEngineError? {64        guard engine.isValid, let url = engine.searchURL(for: query) else { return .navigationBlocked(.malformed) }65        return load(url, transition: .typed)66    }6768    /// Loads an internal `orix://` page. Only the app can do this; web content cannot.69    @discardableResult70    public func loadInternal(_ url: URL) -> WebEngineError? {71        guard InternalPage.isInternal(url) else { return .navigationBlocked(.malformed) }72        startLoad(url, transition: .other)73        return nil74    }7576    func startLoad(_ url: URL, transition: NavigationEntry.Transition) {77        if webView == nil { activateWebView(restoringState: false) }78        guard let view = webView else { return }79        pendingAppURL = url80        pendingTransition = transition81        lastActiveAt = .now82        assign(\.url, url)83        assign(\.loadError, nil)84        assign(\.certificateError, nil)85        if httpsUpgradeAttempt.map({ !NavigationPolicy.sameDocumentTarget($0.upgraded, url) }) ?? true {86            httpsUpgradeAttempt = nil87            assign(\.httpsUpgradeFailure, nil)88        }89        if url.isFileURL {90            // Read access is limited to the file itself: the user chose that file, not its folder.91            view.loadFileURL(url, allowingReadAccessTo: url)92        } else {93            view.load(URLRequest(url: url))94        }95    }9697    /// Reloads the page. After a web content process crash this is what brings the tab back.98    public func reload() {99        guard let view = webView else { resume(); return }100        retryOrReload(view) { view.reload() }101    }102103    /// Reloads, revalidating every resource with the server.104    public func reloadFromOrigin() {105        guard let view = webView else { resume(); return }106        retryOrReload(view) { view.reloadFromOrigin() }107    }108109    private func retryOrReload(_ view: WKWebView, _ reload: () -> Void) {110        // A page that never committed (network error, certificate error, failed upgrade) has nothing to reload:111        // retry the address the user asked for.112        if let failed = httpsUpgradeFailure?.originalURL ?? certificateError?.failingURL ?? loadError?.url {113            load(failed, transition: .reload)114        } else if view.url == nil, let url {115            load(url, transition: .reload)116        } else {117            pendingAppURL = view.url118            pendingTransition = .reload119            assign(\.processState, .running)120            reload()121        }122    }123124    public func stop() { webView?.stopLoading() }125126    public func goBack() {127        guard let view = webView, view.canGoBack else { return }128        pendingTransition = .backForward129        view.goBack()130    }131132    public func goForward() {133        guard let view = webView, view.canGoForward else { return }134        pendingTransition = .backForward135        view.goForward()136    }137138    /// Entries around the current page, for the long-press back/forward menu.139    public func backForwardList() -> BackForwardSnapshot {140        guard let list = webView?.backForwardList else { return BackForwardSnapshot(back: [], current: nil, forward: []) }141        func entry(_ item: WKBackForwardListItem, _ offset: Int) -> BackForwardEntry {142            BackForwardEntry(offset: offset, url: item.url, title: item.title ?? "", initialURL: item.initialURL)143        }144        let back = list.backList145        return BackForwardSnapshot(146            back: back.enumerated().map { entry($1, $0 - back.count) },147            current: list.currentItem.map { entry($0, 0) },148            forward: list.forwardList.enumerated().map { entry($1, $0 + 1) })149    }150151    /// Jumps to an entry of `backForwardList()` by its offset.152    public func go(toOffset offset: Int) {153        guard offset != 0, let view = webView, let item = view.backForwardList.item(at: offset) else { return }154        pendingTransition = .backForward155        view.go(to: item)156    }157158    // MARK: HTTPS-only and certificate interstitials159160    /// The user accepts to open the page over plain http after a failed upgrade. Remembered for this host until161    /// the profile session ends.162    public func proceedWithInsecureHTTP() {163        guard let failure = httpsUpgradeFailure, let host = failure.originalURL.host()?.lowercased() else { return }164        profile.httpAllowedHosts.insert(host)165        assign(\.httpsUpgradeFailure, nil)166        load(failure.originalURL, transition: .typed)167    }168169    /// The user explicitly accepts the invalid certificate of `certificateError` for this session, and the page170    /// is loaded again. Never called automatically; the exception is visible in171    /// `ProfileContext.certificateExceptions` and flagged on `serverTrust.usesUserException`.172    public func proceedIgnoringCertificateError() {173        guard let failure = certificateError, profile.grantCertificateException(for: failure) != nil else { return }174        assign(\.certificateError, nil)175        if let url = failure.failingURL { startLoad(url, transition: .typed) }176    }177178    /// Leaves the interstitial the tab is showing (invalid certificate, failed HTTPS-only upgrade, load error,179    /// blocked address) without loading anything: the page that was committed before is shown again as it is,180    /// or, when the tab never committed a page, the engine goes back to the empty state (`url == nil`, the181    /// new-tab page). Returns `false` when there was nothing to dismiss.182    @discardableResult183    public func dismissInterstitial() -> Bool {184        let hasBlockedPage = committedURL == nil && blockedNavigations.contains(where: \.isMainFrame)185        guard certificateError != nil || httpsUpgradeFailure != nil || loadError != nil || hasBlockedPage else { return false }186        // A retry still in flight must not bring the interstitial back after the user left it.187        if isLoading { webView?.stopLoading() }188        pendingAppURL = nil189        provisionalMainURL = nil190        pendingCertificateError = nil191        httpsUpgradeAttempt = nil192        pendingTransition = .link193        assign(\.certificateError, nil)194        assign(\.httpsUpgradeFailure, nil)195        assign(\.loadError, nil)196        if hasBlockedPage { blockedNavigations.removeAll(where: \.isMainFrame) }197        if let committed = committedURL {198            assign(\.url, committed)199            assign(\.title, webView?.title ?? title)200            refreshServerTrust()201        } else {202            assign(\.url, nil)203            assign(\.title, "")204            assign(\.faviconURL, nil)205            assign(\.serverTrust, nil)206        }207        assign(\.estimatedProgress, 0)208        return true209    }210211    // MARK: Live settings212213    /// Replaces the navigation policy of a live engine (HTTPS-only mode, loopback exemption, file access). It214    /// applies to the next navigation decision; the page being shown is not reloaded.215    public func updateNavigationSettings(_ navigation: NavigationPolicySettings) {216        guard settings.navigation != navigation else { return }217        settings.navigation = navigation218    }219220    /// Changes one or several navigation settings in place.221    public func updateNavigationSettings(_ change: (inout NavigationPolicySettings) -> Void) {222        var navigation = settings.navigation223        change(&navigation)224        updateNavigationSettings(navigation)225    }226227    // MARK: Downloads228229    /// Downloads `url` instead of displaying it (context menu "Download Linked File").230    public func startDownload(_ url: URL) async {231        await startDownload(url, id: DownloadID())232    }233234    /// Downloads `url` under a given identifier: the sink sees `id` in `downloadWillBegin` and in every event, so235    /// a download restarted from the beginning keeps its identity in the download list. A dormant or suspended236    /// tab gets its web view back first. Returns `false` when the address cannot be downloaded.237    @discardableResult238    public func startDownload(_ url: URL, id: DownloadID, originURL: URL? = nil) async -> Bool {239        guard let scheme = url.scheme?.lowercased(), ["http", "https", "blob", "data"].contains(scheme) else { return false }240        if webView == nil { activateWebView(restoringState: false) }241        guard let view = webView else { return false }242        let download = await view.startDownload(using: URLRequest(url: url))243        profile.downloads.adopt(download, originURL: originURL ?? committedURL, id: id)244        return true245    }246247    /// Resumes a download from WebKit resume data. `destination` is the partially written file the data refers248    /// to; `id` keeps the identity of the original download for the sink.249    public func resumeDownload(resumeData: Data, id: DownloadID, destination: URL) async {250        if webView == nil { activateWebView(restoringState: false) }251        guard let view = webView else { return }252        let download = await view.resumeDownload(fromResumeData: resumeData)253        profile.downloads.adopt(download, originURL: committedURL, id: id, knownDestination: destination)254    }255}256257// MARK: - Find, zoom, modes258259extension WebEngine {260    /// Finds the next (or previous) occurrence and selects it. WebKit reports only whether a match was found;261    /// the count is computed separately from the document text.262    @discardableResult263    public func find(_ query: String, backwards: Bool = false, options: FindOptions = FindOptions()) async throws(WebEngineError) -> FindOutcome {264        guard let view = webView else { throw .noWebView }265        guard !query.isEmpty else {266            await clearFind()267            return FindOutcome(query: "", matchFound: false, matchCount: 0)268        }269        let configuration = WKFindConfiguration()270        configuration.backwards = backwards271        configuration.caseSensitive = options.caseSensitive272        configuration.wraps = options.wraps273        let found: Bool274        do { found = try await view.find(query, configuration: configuration).matchFound } catch {275            throw .scriptFailed((error as NSError).localizedDescription)276        }277        var count: Int?278        if lastFind?.query == query, let previous = lastFind?.matchCount {279            count = previous280        } else {281            let script = """282            var text = document.body ? document.body.innerText : "";283            if (!caseSensitive) { text = text.toLocaleLowerCase(); needle = needle.toLocaleLowerCase(); }284            if (!needle) return 0;285            var count = 0, at = 0;286            while (count < limit) { at = text.indexOf(needle, at); if (at < 0) break; count++; at += needle.length; }287            return count;288            """289            count = (try? await evaluate(script, arguments: ["needle": .string(query), "caseSensitive": .bool(options.caseSensitive),290                                                             "limit": .number(Double(FindOutcome.countLimit))], in: .bridge))?.intValue291        }292        let outcome = FindOutcome(query: query, matchFound: found, matchCount: count)293        lastFind = outcome294        return outcome295    }296297    public func findNext() async throws(WebEngineError) -> FindOutcome? {298        guard let query = lastFind?.query, !query.isEmpty else { return nil }299        return try await find(query, backwards: false)300    }301302    public func findPrevious() async throws(WebEngineError) -> FindOutcome? {303        guard let query = lastFind?.query, !query.isEmpty else { return nil }304        return try await find(query, backwards: true)305    }306307    /// Ends a find session: forgets the query and removes the selection WebKit placed on the last match.308    public func clearFind() async {309        lastFind = nil310        _ = try? await evaluate("var s = window.getSelection(); if (s) s.removeAllRanges(); return true;", in: .bridge)311    }312313    #if os(iOS)314    /// Presents the system find panel (keyboard-attached find bar).315    public func presentSystemFindPanel() {316        guard let view = webView else { return }317        view.isFindInteractionEnabled = true318        view.findInteraction?.presentFindNavigator(showingReplace: false)319    }320    #endif321322    public static let zoomSteps: [Double] = [0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5]323324    /// Whole-page zoom (layout reflows), 0.25…5.325    public func setPageZoom(_ zoom: Double) {326        let value = Self.clampZoom(zoom)327        pageZoom = value328        webView?.pageZoom = value329    }330331    public func zoomIn() { setPageZoom(Self.zoomSteps.first { $0 > pageZoom + 0.001 } ?? 5) }332    public func zoomOut() { setPageZoom(Self.zoomSteps.last { $0 < pageZoom - 0.001 } ?? 0.25) }333    public func resetZoom() { setPageZoom(1) }334335    /// Text-only sizing exists where WebKit honours `-webkit-text-size-adjust`: iOS and iPadOS. macOS has no336    /// public text-only zoom; use `setPageZoom` there.337    public static var supportsTextOnlyZoom: Bool {338        #if os(iOS)339        true340        #else341        false342        #endif343    }344345    /// iOS: scales text without scaling layout (50…300 %). Throws on macOS.346    public func setTextSizePercent(_ percent: Int) throws(WebEngineError) {347        guard Self.supportsTextOnlyZoom else {348            throw .unsupportedOnThisPlatform("Text-only zoom is not available in WKWebView on macOS")349        }350        let value = min(300, max(50, percent))351        textSizePercent = value352        if value == 100 {353            removeStylesheet(id: "orix.text-size")354        } else {355            try installStylesheet(id: "orix.text-size",356                                  css: "html { -webkit-text-size-adjust: \(value)% !important; }", hosts: ["*"])357        }358    }359360    /// Desktop or mobile site. Takes effect on the next navigation; `reload` applies it now.361    public func setContentMode(_ mode: UserAgentMode, reload shouldReload: Bool = true) {362        contentMode = mode363        applyUserAgent()364        if shouldReload, webView?.url != nil { reloadFromOrigin() }365    }366367    /// The content mode is carried by `WKWebpagePreferences.preferredContentMode` on each navigation. The user368    /// agent only needs an override where WebKit has no such mode: "mobile" on macOS.369    func applyUserAgent() {370        guard let view = webView else { return }371        #if os(macOS)372        switch contentMode {373        case .mobile: view.customUserAgent = settings.mobileUserAgent374        case .desktop: view.customUserAgent = settings.desktopUserAgent375        case .automatic: view.customUserAgent = nil376        }377        #else378        view.customUserAgent = contentMode == .desktop ? settings.desktopUserAgent : nil379        #endif380    }381382    /// Shows or hides this page in Safari's Web Inspector (Develop menu).383    public func setInspectable(_ inspectable: Bool) {384        isInspectable = inspectable385        webView?.isInspectable = inspectable386    }387388    /// Turns the profile's content rule lists off or on for this tab ("shields down"). Applies to the next load.389    public func setContentBlockingEnabled(_ enabled: Bool) {390        guard enabled != isContentBlockingEnabled else { return }391        isContentBlockingEnabled = enabled392        guard let controller = webView?.configuration.userContentController else { return }393        controller.removeAllContentRuleLists()394        if enabled { for list in profile.attachedRuleLists { controller.add(list) } }395    }396}397398// MARK: - Media399400extension WebEngine {401    /// Mutes or unmutes the tab. Implemented on the page's media elements (WKWebView has no public page mute);402    /// Web Audio output is not covered — see WEBKIT_LIMITATIONS.md.403    public func setMuted(_ muted: Bool) {404        guard muted != isMuted else { return }405        isMuted = muted406        if muted { scriptRegistry?.install(Self.mutePreamble) } else { scriptRegistry?.remove(id: Self.mutePreamble.id) }407        pushMuteState(to: nil)408        for frame in mediaFrameInfos.values where !frame.isMainFrame { pushMuteState(to: frame) }409    }410411    public func pauseAllMedia() async { await webView?.pauseAllMediaPlayback() }412413    /// Closes Picture in Picture and element fullscreen.414    public func closeAllMediaPresentations() async { await webView?.closeAllMediaPresentations() }415416    /// Mutes (keeps the stream) or stops the page's camera capture.417    public func setCameraCapture(_ status: MediaCaptureStatus) async {418        await webView?.setCameraCaptureState(status == .active ? .active : status == .muted ? .muted : .none)419    }420421    public func setMicrophoneCapture(_ status: MediaCaptureStatus) async {422        await webView?.setMicrophoneCaptureState(status == .active ? .active : status == .muted ? .muted : .none)423    }424}425426// MARK: - Export: print, PDF, web archive, snapshot427428extension WebEngine {429    #if os(macOS)430    /// A print operation for the page. The caller runs it (`runModal(for:…)`) on its window.431    public func makePrintOperation(printInfo: NSPrintInfo = .shared) throws(WebEngineError) -> NSPrintOperation {432        guard let view = webView else { throw .noWebView }433        let operation = view.printOperation(with: printInfo)434        operation.jobTitle = title.isEmpty ? (url?.host() ?? "") : title435        // WebKit creates the print view with an empty frame; running the operation like that prints nothing.436        operation.view?.frame = view.bounds437        return operation438    }439440    /// Shows the print sheet on `window` (or the web view's window).441    public func print(in window: NSWindow? = nil) throws(WebEngineError) {442        let operation = try makePrintOperation()443        guard let target = window ?? webView?.window else { throw .exportFailed("The page is not in a window") }444        operation.runModal(for: target, delegate: nil, didRun: nil, contextInfo: nil)445    }446    #elseif os(iOS)447    /// Presents the system print controller for the page. Returns whether the job was submitted.448    @discardableResult449    public func presentPrintController() async throws(WebEngineError) -> Bool {450        guard let view = webView else { throw .noWebView }451        guard UIPrintInteractionController.isPrintingAvailable else { throw .exportFailed("Printing is not available") }452        let controller = UIPrintInteractionController.shared453        let info = UIPrintInfo(dictionary: nil)454        info.jobName = title.isEmpty ? (url?.host() ?? "") : title455        info.outputType = .general456        controller.printInfo = info457        controller.printFormatter = view.viewPrintFormatter()458        return await withCheckedContinuation { continuation in459            controller.present(animated: true) { _, completed, _ in continuation.resume(returning: completed) }460        }461    }462    #endif463464    /// The page as PDF. `rect` in web view coordinates; `nil` captures the whole document.465    public func pdfData(rect: CGRect? = nil) async throws(WebEngineError) -> Data {466        guard let view = webView else { throw .noWebView }467        let configuration = WKPDFConfiguration()468        configuration.rect = rect469        do { return try await view.pdf(configuration: configuration) } catch {470            throw .exportFailed((error as NSError).localizedDescription)471        }472    }473474    /// A `.webarchive` of the page with the sub-resources WebKit has loaded.475    public func webArchiveData() async throws(WebEngineError) -> Data {476        guard let view = webView else { throw .noWebView }477        let result: Result<Data, any Error> = await withCheckedContinuation { continuation in478            view.createWebArchiveData { continuation.resume(returning: $0) }479        }480        switch result {481        case .success(let data): return data482        case .failure(let error): throw .exportFailed((error as NSError).localizedDescription)483        }484    }485486    /// A snapshot of the visible page, `maxWidth` points wide (thumbnails for tab grids and suspended tabs).487    public func snapshotImage(maxWidth: CGFloat = 480) async throws(WebEngineError) -> PlatformImage {488        guard let view = webView else { throw .noWebView }489        let configuration = WKSnapshotConfiguration()490        let width = min(maxWidth, max(1, view.bounds.width))491        configuration.snapshotWidth = NSNumber(value: Double(width))492        // Waiting for a screen update never completes for a web view that is not on screen.493        configuration.afterScreenUpdates = false494        do { return try await view.takeSnapshot(configuration: configuration) } catch {495            throw .snapshotFailed((error as NSError).localizedDescription)496        }497    }498499    public func snapshotPNG(maxWidth: CGFloat = 480) async throws(WebEngineError) -> Data {500        let image = try await snapshotImage(maxWidth: maxWidth)501        #if canImport(AppKit)502        guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil),503              let data = NSBitmapImageRep(cgImage: cgImage).representation(using: .png, properties: [:]) else {504            throw .snapshotFailed("PNG encoding failed")505        }506        return data507        #else508        guard let data = image.pngData() else { throw .snapshotFailed("PNG encoding failed") }509        return data510        #endif511    }512}513514// MARK: - Session state, suspension515516extension WebEngine {517    /// WebKit's opaque interaction state (back/forward list, scroll positions, form state it keeps), for session518    /// restore. `nil` when there is no web view or WebKit produced something that is not plain data.519    public func sessionStateData() -> Data? {520        guard let view = webView else { return suspendedPage?.interactionState ?? dormantSessionState }521        return view.interactionState as? Data522    }523524    /// Restores a state produced by `sessionStateData()`; WebKit reloads the current entry.525    @discardableResult526    public func restoreSessionState(_ data: Data) -> Bool {527        if webView == nil { activateWebView(restoringState: false) }528        guard let view = webView else { return false }529        isRestoringSession = true530        pendingTransition = .restore531        view.interactionState = data532        // WebKit ignores data it does not recognise and leaves the list empty.533        if view.backForwardList.currentItem == nil && view.url == nil {534            isRestoringSession = false535            return false536        }537        return true538    }539540    /// The tab as it should be persisted (fields this layer knows about).541    public func updating(_ tab: Tab) -> Tab {542        var tab = tab543        tab.url = url544        tab.title = title545        tab.faviconURL = faviconURL546        tab.isMuted = isMuted547        tab.zoom = pageZoom548        tab.userAgentMode = contentMode549        tab.lifecycle = lifecycle550        tab.sessionState = sessionStateData()551        return tab552    }553554    /// False while releasing the web view would be noticed by the user or lose work in flight.555    public var isSuspendable: Bool {556        guard webView != nil, lifecycle == .live else { return false }557        return !isPlayingAudio && mediaActivity.playingElements == 0 && cameraCapture == .none && microphoneCapture == .none558            && fullscreenState == .notInFullscreen && !isLoading && !isPickingElement559    }560561    /// Captures the interaction state and a thumbnail, then releases the web view (and with it the web content562    /// process share of this tab). The engine keeps its title, address and icon. Returns what was saved.563    @discardableResult564    public func suspend(thumbnailWidth: CGFloat? = 480) async -> SuspendedPage? {565        guard webView != nil else { return suspendedPage }566        var thumbnail: Data?567        if let thumbnailWidth, !processState.isTerminated { thumbnail = try? await snapshotPNG(maxWidth: thumbnailWidth) }568        guard let view = webView else { return suspendedPage }569        let page = SuspendedPage(url: view.url ?? url, title: title, interactionState: view.interactionState as? Data,570                                 thumbnailPNG: thumbnail, pageZoom: pageZoom, contentMode: contentMode, isMuted: isMuted,571                                 suspendedAt: .now)572        destroyWebView()573        suspendedPage = page574        lifecycle = .suspended575        return page576    }577578    /// Recreates the web view of a suspended or dormant tab and restores its page.579    public func resume() {580        guard webView == nil, !isClosed else { return }581        activateWebView(restoringState: true)582    }583584    func activateWebView(restoringState: Bool) {585        guard webView == nil, !isClosed else { return }586        let state = suspendedPage?.interactionState ?? dormantSessionState587        let address = suspendedPage?.url ?? url588        createWebView(adopting: nil)589        lifecycle = .live590        suspendedPage = nil591        dormantSessionState = nil592        processState = .running593        lastActiveAt = .now594        guard restoringState else { return }595        if let state, restoreSessionState(state) { return }596        if let address { load(address, transition: .restore) }597    }598}599600// MARK: - Context menu actions601602extension WebEngine {603    /// Executes a standard context-menu action. Returns `false` for actions only the UI can perform604    /// (`shareLink`, `searchSelection`) or when the element lacks what the action needs.605    @discardableResult606    public func perform(_ action: ContextMenuAction, on element: ContextMenuElement) -> Bool {607        func newTab(_ url: URL?, _ disposition: NewTabRequest.Disposition) -> Bool {608            guard let url, let delegate = navigationDelegate else { return false }609            delegate.webEngine(self, requestsNewTab: NewTabRequest(url: url, disposition: disposition, openerTabID: id,610                                                                   isUserGesture: true))611            return true612        }613        func download(_ url: URL?) -> Bool {614            guard let url else { return false }615            Task { await self.startDownload(url) }616            return true617        }618        switch action {619        case .openLink:620            guard let url = element.linkURL else { return false }621            return load(url, transition: .link) == nil622        case .openLinkInNewTab: return newTab(element.linkURL, .foreground)623        case .openLinkInBackgroundTab: return newTab(element.linkURL, .background)624        case .openLinkInSplit: return newTab(element.linkURL, .split)625        case .openImageInNewTab: return newTab(element.imageURL, .foreground)626        case .copyLink: return Self.copyToPasteboard(element.linkURL?.absoluteString)627        case .copyImageAddress: return Self.copyToPasteboard(element.imageURL?.absoluteString)628        case .copySelection: return Self.copyToPasteboard(element.selectionText.isEmpty ? nil : element.selectionText)629        case .downloadLink: return download(element.linkURL)630        case .downloadImage: return download(element.imageURL)631        case .shareLink, .searchSelection: return false632        }633    }634635    private static func copyToPasteboard(_ text: String?) -> Bool {636        guard let text else { return false }637        #if canImport(AppKit)638        NSPasteboard.general.clearContents()639        return NSPasteboard.general.setString(text, forType: .string)640        #else641        UIPasteboard.general.string = text642        return true643        #endif644    }645}646
Files main
Menu

Theme