SPB Git

Repository Public License

WebViewPool.swift 4.5 KB 107 lines swift

1import Diagnostics2import Foundation3import NavigatorCore45/// Lifecycle helper for the Blink module: keeps the number of live web views under a limit by suspending the6/// least recently used tabs, and resumes a tab when it is shown again.7///8/// The pool only references engines weakly and never suspends a tab that is audible, capturing, in fullscreen,9/// loading or explicitly protected.10@MainActor11public final class WebViewPool {12    private final class Entry {13        weak var engine: WebEngine?14        init(_ engine: WebEngine) { self.engine = engine }15    }1617    private var entries: [TabID: Entry] = [:]18    private var memoryPressureSource: (any DispatchSourceMemoryPressure)?1920    /// Maximum number of tabs holding a web view once `enforceLimit` has run.21    public var maximumLiveWebViews: Int2223    public init(maximumLiveWebViews: Int = 12) {24        self.maximumLiveWebViews = max(1, maximumLiveWebViews)25    }2627    public func track(_ engine: WebEngine) { entries[engine.id] = Entry(engine) }28    public func untrack(_ id: TabID) { entries[id] = nil }2930    public var trackedEngines: [WebEngine] {31        entries = entries.filter { $0.value.engine != nil }32        return entries.values.compactMap(\.engine)33    }3435    public var liveCount: Int { trackedEngines.filter { $0.webView != nil }.count }3637    /// The tab is being shown: recreate its web view if it was released, and mark it most recently used.38    public func activate(_ engine: WebEngine) {39        if entries[engine.id] == nil { track(engine) }40        engine.resume()41        engine.lastActiveAt = .now42    }4344    /// Suspends least-recently-used tabs until at most `maximumLiveWebViews` are live. Returns the suspended ids.45    @discardableResult46    public func enforceLimit(protecting protected: Set<TabID> = []) async -> [TabID] {47        await suspend(downTo: maximumLiveWebViews, protecting: protected)48    }4950    /// Suspends every tab that can be, except the protected ones (memory warning, app going to the background).51    @discardableResult52    public func suspendAll(protecting protected: Set<TabID> = []) async -> [TabID] {53        await suspend(downTo: 0, protecting: protected)54    }5556    /// Suspends tabs that have not been active for `interval`.57    @discardableResult58    public func suspendIdle(olderThan interval: TimeInterval, protecting protected: Set<TabID> = []) async -> [TabID] {59        let cutoff = Date().addingTimeInterval(-interval)60        var suspended: [TabID] = []61        for engine in trackedEngines where engine.isSuspendable && !protected.contains(engine.id) && engine.lastActiveAt < cutoff {62            if await engine.suspend() != nil { suspended.append(engine.id) }63        }64        return suspended65    }6667    private func suspend(downTo limit: Int, protecting protected: Set<TabID>) async -> [TabID] {68        var live = trackedEngines.filter { $0.webView != nil }69        guard live.count > limit else { return [] }70        let candidates = live.filter { $0.isSuspendable && !protected.contains($0.id) }71            .sorted { $0.lastActiveAt < $1.lastActiveAt }72        var suspended: [TabID] = []73        for engine in candidates {74            guard live.count > limit else { break }75            // State may have changed while the previous tab was being captured.76            guard engine.isSuspendable else { continue }77            if await engine.suspend() != nil {78                suspended.append(engine.id)79                live.removeAll { $0 === engine }80            }81        }82        if !suspended.isEmpty { Log.performance.info("Suspended \(suspended.count, privacy: .public) tab(s)") }83        return suspended84    }8586    /// Suspends background tabs when the system reports memory pressure. `protected` is asked at that moment for87    /// the tabs that must stay (visible tabs, pinned tabs the user wants live).88    public func startObservingMemoryPressure(protecting protected: @escaping @MainActor () -> Set<TabID>) {89        stopObservingMemoryPressure()90        let source = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: .main)91        source.setEventHandler { [weak self] in92            MainActor.assumeIsolated {93                guard let self else { return }94                let keep = protected()95                Task { await self.suspendAll(protecting: keep) }96            }97        }98        source.resume()99        memoryPressureSource = source100    }101102    public func stopObservingMemoryPressure() {103        memoryPressureSource?.cancel()104        memoryPressureSource = nil105    }106}107
Files main
Menu

Theme