diff --git a/Documentation/Plan.md b/Documentation/Plan.md index 3da5b60..75ca96a 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -284,53 +284,49 @@ image: ## 8. Web views -`LinuxWebKit` implements `WebContent` (AppRuntime's `WebKit.md`) with WPE -WebKit, and the player draws `WebView` nodes. It follows Perry's -(`Sources/PerryUIKit/WPE.swift` there): - -- **No WebKit at build time.** The host opens libwpe, WPEBackend-fdo, - libwayland-server, `libWPEWebKit-2.0.so.1`, GLib and GObject when a page - is first made, locally, so their symbols stand in for no others. Without - them a page loads nothing, and fails each load saying so. Debian 13 - packages WPE 2.48 (`libwpewebkit-2.0-1`, `libwpebackend-fdo-1.0-1`); - Ubuntu 26.04 doesn't, so the development image and CI moved to Debian 13. -- **Frames in shared memory.** WPEBackend-fdo runs in its SHM mode - (`wpe_fdo_initialize_shm`), and each page's exportable view backend hands - over every frame the web process draws as a `wl_shm` buffer: premultiplied - BGRA, turned into RGBA for Cacao's `Image(pixels:)`. WebKit draws on the - CPU; there's no GL. -- **GLib's context** runs on the main loop every 8 ms while there are pages: - their signals, script results and frames all come through it. -- **The contract** maps onto `WebKitWebView`: - - `load-changed`, `load-failed` and `load-failed-with-tls-errors` give - loading, finishing and failing; - - `notify::` on `uri`, `title` and `estimated-load-progress`, and the - history after each commit, give the rest; - - `uri` changes as soon as a load is asked for, and before a history - navigation is decided, so it's reported only once the navigation - commits or follows a redirect, as the contract wants; - - cancelled and replaced navigations aren't failures. -- **Errors** come as GErrors and map to `WebError.Code`: WebKit's network - and policy errors, GIO's (a timeout is `timedOut`, the rest `network`), - the resolver's, and TLS (`security`). -- **`decide-policy`** asks `shouldNavigate` for each navigation and new - window, except the guest's own `load`, `loadHTML` and `loadResource`. A - new window loads in the same page. WPE doesn't say which frame a - navigation is in, so `isMainFrame` is always true. -- **Without `network`**: - - a remote `load`, or a navigation to a remote URL, fails with - `notPermitted` before it starts; - - every other request goes through a proxy on a `.invalid` host (RFC - 2606), which never resolves, so remote subresources don't load. -- **`loadResource`** loads a `file://` URL in the bundle's `resources/`, - refusing paths that leave it. -- **The view** (`Sources/LinuxUI/HostWebView.swift`): - - It gives the page its size in points and the display's scale, and - makes it visible while it's on screen. The page stays loaded when the - view goes. - - A drag is the primary button, and hovering moves the pointer. - - A click focuses the page. Keys go to it as XKB keysyms, which WPE turns - into text. +`LinuxWebKit` implements `WebContent` (AppRuntime's `WebKit.md`) over +PureSwift/WebKit, whose `WPEWebKit` drives WPE WebKit, and the player shows +`WebView` nodes with its `CacaoWebKit`. PureSwift/WebKit's own plan +(`Documentation/Plan.md` there) has the engine's details; here is what the +host adds: + +- **No WebKit at build time.** `WPEWebKit` opens libwpe, WPEBackend-fdo, + libwayland-server, `libWPEWebKit-2.0.so.1`, GLib, GObject, GIO and + libsoup when a page is first made, locally, so their symbols stand in for + no others. Without them a page loads nothing, and fails each load saying + so. Debian 13 packages WPE 2.48 (`libwpewebkit-2.0-1`, + `libwpebackend-fdo-1.0-1`); Ubuntu 26.04 doesn't, so the development + image and CI moved to Debian 13. +- **The contract's page** (`LinuxWebContent`) makes a `WPEWebContent`, + whose delegate already has the contract's methods and numbers, and + passes what it hears to the guest's delegate. It refuses a load of what + isn't a URL, or of a remote URL without `network`, before anything + starts, with WPE or without; and it loads `loadResource`'s `file://` URL + from the bundle's `resources/`, refusing paths that leave it. The rest + is `WPEWebContent`'s: + - loading, finishing and failing from `load-changed`, `load-failed` and + `load-failed-with-tls-errors`, and the URL only once a navigation + commits; cancelled and replaced navigations aren't failures; + - GErrors mapped to `WebError.Code`; + - `decide-policy` asking `shouldNavigate` about each navigation and new + window but the guest's own loads, a new window loading in the same + page, and `isMainFrame` always true, as WPE doesn't say; + - without `network`, every other request going through a proxy on a + `.invalid` host (RFC 2606), which never resolves. +- **GLib's context** runs on the main loop: `WPEEngine.pump()` there when + the engine says its pages have work (`WPEEngine.onReady`), so nothing + polls. A guest's call sets off a pump on the loop's next turn, so the + guest doesn't hear from a page while it's calling it. +- **Frames** come from WPEBackend-fdo's SHM mode as premultiplied BGRA, and + go to the page's Cacao `ExternalSurface` as they are: no conversion, one + copy. WebKit draws on the CPU; there's no GL. +- **The view** (`Sources/LinuxUI/HostWebView.swift`) is CacaoWebKit's + `WebView(content:)` over the page its node names: + - it attaches the page at its size in points and the display's scale + while it's on screen, and the page stays loaded when it goes; + - Cacao's input goes to the page: the pointer with its buttons, hover, + the wheel and smooth scrolling, a finger's tap as a click and its drag + as a scroll, keys, typed text with the keyboard's layout, and focus. - **The sandbox.** WebKit starts its web and network processes under bubblewrap, which can't make namespaces in a container, so the development image and CI set `WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1` @@ -338,12 +334,10 @@ WebKit, and the player draws `WebView` nodes. It follows Perry's own sandbox (AppRuntime's §7.8) it's still the open question `WebKit.md` names. - **Not yet**: - - The wheel: Cacao sends it only to its scroll views. Pages scroll with - the arrow keys, Page Up and Page Down, and Space. - `alert`, `confirm` and `prompt`: WebKit's defaults apply, which show nothing. - Permission requests: WebKit denies them by default. - - Touches, and buttons other than the primary. + - More than one finger: a pinch doesn't zoom. - Reading files beside a bundled page only: WebKit's file-URL rules apply. diff --git a/Package.swift b/Package.swift index eecab78..acd7588 100644 --- a/Package.swift +++ b/Package.swift @@ -12,7 +12,8 @@ import PackageDescription /// The environment: /// /// - `APPRUNTIME_PATH`: a local AppRuntime checkout instead of GitHub; -/// `CACAO_PATH` likewise for PureSwift/Cacao. +/// `CACAO_PATH` likewise for PureSwift/Cacao, and `WEBKIT_PATH` for +/// PureSwift/WebKit. let environment = ProcessInfo.processInfo.environment let appRuntime: Package.Dependency = { @@ -31,6 +32,15 @@ let cacao: Package.Dependency = { return .package(url: "https://github.com/PureSwift/Cacao.git", branch: "develop") }() +/// PureSwift/WebKit: WPE WebKit's pages, and the `WebView` that shows them +/// in Cacao. `WEBKIT_PATH` points at a local checkout. +let webKit: Package.Dependency = { + if let path = environment["WEBKIT_PATH"] { + return .package(name: "WebKit", path: path) + } + return .package(url: "https://github.com/PureSwift/WebKit.git", branch: "master") +}() + /// The player is DarwinAppRuntime's SwiftUI renderer: on Linux its /// `import SwiftUI` and `import Combine` are Cacao's modules of those names. #if os(Linux) @@ -38,6 +48,7 @@ let swiftUI: [Target.Dependency] = [ .product(name: "SwiftUI", package: "Cacao"), .product(name: "Combine", package: "Cacao"), .product(name: "Cacao", package: "Cacao"), + .product(name: "CacaoWebKit", package: "WebKit"), ] #else let swiftUI: [Target.Dependency] = [] @@ -79,6 +90,7 @@ let package = Package( dependencies: [ appRuntime, cacao, + webKit, // D-Bus, in Swift without libdbus, which Bluetooth talks to BlueZ // over, and Location to GeoClue; it has no releases. .package(url: "https://github.com/PureSwift/DBus.git", revision: "d34567d64bb553a35e5b263f344c6963a5170ca3"), @@ -137,10 +149,12 @@ let package = Package( // MARK: - Web views - // WPE WebKit, loaded at run time: the host links no WebKit. + // WPE WebKit through PureSwift/WebKit, which loads it at run time: + // the host links no WebKit. .target( name: "LinuxWebKit", - dependencies: ["LinuxHost", runtime("DynamicWebKit"), runtime("DynamicRuntime"), runtime("RuntimeABI")], + dependencies: ["LinuxHost", runtime("DynamicWebKit"), runtime("DynamicRuntime"), runtime("RuntimeABI"), + .product(name: "WPEWebKit", package: "WebKit")], swiftSettings: host ), @@ -277,7 +291,8 @@ let package = Package( swiftSettings: host), .testTarget( name: "LinuxUITests", - dependencies: ["LinuxUI", runtime("DynamicUI"), runtime("DynamicRuntime"), .product(name: "Cacao", package: "Cacao")] + swiftUI, + dependencies: ["LinuxUI", "LinuxWebKit", runtime("DynamicUI"), runtime("DynamicRuntime"), runtime("DynamicWebKit"), + .product(name: "Cacao", package: "Cacao")] + swiftUI, swiftSettings: host ), .testTarget(name: "LinuxBluetoothTests", dependencies: ["LinuxBluetooth"], swiftSettings: host), @@ -302,7 +317,8 @@ let package = Package( .testTarget(name: "LinuxMediaTests", dependencies: ["LinuxMedia", runtime("DynamicMedia"), runtime("RuntimeMedia"), runtime("RuntimeHost")], swiftSettings: host), .testTarget(name: "LinuxMotionTests", dependencies: ["LinuxMotion", runtime("DynamicMotion")], swiftSettings: host), - .testTarget(name: "LinuxWebKitTests", dependencies: ["LinuxWebKit", runtime("DynamicWebKit")], swiftSettings: host), + .testTarget(name: "LinuxWebKitTests", dependencies: ["LinuxWebKit", runtime("DynamicWebKit"), .product(name: "WPEWebKit", package: "WebKit")], + swiftSettings: host), .testTarget(name: "LinuxPackagerTests", dependencies: ["LinuxPackager", "LinuxHostApp", runtime("RuntimeNetworking")]), ] ) diff --git a/README.md b/README.md index bf64be6..392676e 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ added to its database between launches: | `LinuxUI` | The SwiftUI player: DarwinAppRuntime's `DarwinUI`, copied by `Scripts/sync-darwinui.sh`, over Cacao's `SwiftUI` | | `LinuxBluetooth` | `BluetoothCentral`, `BluetoothPeripheral`, `BluetoothService`, `BluetoothCharacteristic`, `BluetoothDescriptor` and `BluetoothAdvertisement` over BlueZ, through `LinuxDBus` | | `LinuxGraphics` | `Surface`: GLES 2.0 drawn in EGL pbuffers, loaded at run time, and read back into the player's `GLSurface` view ([plan](Documentation/Plan.md) §7) | -| `LinuxWebKit` | `WebContent`: WPE WebKit pages, loaded at run time, drawn into shared memory and shown by the player's `WebView` view ([plan](Documentation/Plan.md) §8) | +| `LinuxWebKit` | `WebContent`: WPE WebKit pages through [PureSwift/WebKit](https://github.com/PureSwift/WebKit), loaded at run time and shown by the player's `WebView` view, CacaoWebKit's ([plan](Documentation/Plan.md) §8) | | `LinuxCoreModel` | `LinuxModelStore`: the app's CoreModel stores in SQLite, through AppRuntime's `HostModelStore` and CoreModel-SQLite ([plan](Documentation/Plan.md) §9) | | `LinuxDevice` | `Device`: the machine, its battery, power mode and heat, from `/etc`, DMI, the device tree and sysfs, and its orientation and proximity from iio-sensor-proxy ([plan](Documentation/Plan.md) §10) | | `LinuxDBus` | `Bus`: the system and session buses for the modules that talk to system services, over PureSwift/DBus, with calls, properties and signals delivered on the main loop ([plan](Documentation/Plan.md) §11.1) | @@ -101,9 +101,9 @@ with this checkout at `/src`: Scripts/docker.sh swift test --scratch-path .build/linux ``` -AppRuntime and Cacao (its `develop` branch) come from GitHub. -`APPRUNTIME_PATH` and `CACAO_PATH` point at local checkouts instead, and -`Scripts/docker.sh` mounts them. +AppRuntime, Cacao (its `develop` branch) and PureSwift/WebKit come from +GitHub. `APPRUNTIME_PATH`, `CACAO_PATH` and `WEBKIT_PATH` point at local +checkouts instead, and `Scripts/docker.sh` mounts them. `Scripts/sync-darwinui.sh` updates the player from a DarwinAppRuntime checkout beside this one. diff --git a/Scripts/docker.sh b/Scripts/docker.sh index 8d79f85..1f80754 100755 --- a/Scripts/docker.sh +++ b/Scripts/docker.sh @@ -1,8 +1,8 @@ #!/bin/sh # Runs a command in the Linux development image (Dockerfile), with this # checkout at /src and, if APPRUNTIME_PATH is set, that AppRuntime checkout at -# /AppRuntime; likewise CACAO_PATH at /Cacao. Builds go to .build/linux, apart -# from a Mac's .build. +# /AppRuntime; likewise CACAO_PATH at /Cacao, and WEBKIT_PATH, PureSwift/WebKit, +# at /WebKit. Builds go to .build/linux, apart from a Mac's .build. # # Scripts/docker.sh swift test --scratch-path .build/linux # APPRUNTIME_PATH=~/Developer/AppRuntime Scripts/docker.sh swift build --scratch-path .build/linux @@ -26,6 +26,9 @@ fi if [ -n "$CACAO_PATH" ]; then set -- "$@" -v "$CACAO_PATH:/Cacao" -e CACAO_PATH=/Cacao fi +if [ -n "$WEBKIT_PATH" ]; then + set -- "$@" -v "$WEBKIT_PATH:/WebKit" -e WEBKIT_PATH=/WebKit +fi exec docker run --rm \ -v "$root:/src" -w /src \ -v linuxappruntime-swiftpm:/root/.cache \ diff --git a/Sources/LinuxUI/HostWebView.swift b/Sources/LinuxUI/HostWebView.swift index bc1355a..dc5055b 100644 --- a/Sources/LinuxUI/HostWebView.swift +++ b/Sources/LinuxUI/HostWebView.swift @@ -1,180 +1,28 @@ -// `WebView` nodes: a `LinuxWebContent`'s frames, with the view's pointer and -// key input going to its page (`WebKit.md`). Scripts/sync-darwinui.sh keeps -// this file. +// `WebView` nodes: a `LinuxWebContent`'s page, shown by PureSwift/WebKit's +// `WebView(content:)`, with the view's input going to it (`WebKit.md`). +// Scripts/sync-darwinui.sh keeps this file. #if os(Linux) -import DynamicUI -import Foundation +import CacaoWebKit import LinuxHost import LinuxWebKit import SwiftUI -/// A page's frames, at the size the view is offered. +/// A page, at the size the view is offered. The page stays loaded when the +/// view goes. struct HostWebView: View { let identifier: Int32 - @StateObject private var model = HostWebViewModel() - - @FocusState private var focused: Bool - - @Environment(\.displayScale) private var displayScale - var body: some View { - GeometryReader { proxy in - frame - .frame(width: proxy.size.width, height: proxy.size.height) - .contentShape(Rectangle()) - .gesture( - DragGesture(minimumDistance: 0) - .onChanged { value in - focused = true - model.drag(to: value.location) - } - .onEnded { value in - model.endDrag(at: value.location) - } - ) - .onContinuousHover { phase in - if case let .active(location) = phase { - model.hover(at: location) - } - } - .focusable() - .focused($focused) - .onKeyPress(phases: .all) { press in - model.key(press) - } - .onChange(of: focused) { focused in - model.page?.focus(focused) - } - .onAppear { - model.attach(identifier, size: proxy.size, scale: displayScale) - } - .onChange(of: proxy.size) { size in - model.resize(size, scale: displayScale) - } - .onDisappear { - model.detach() - } - } - } - - @ViewBuilder - private var frame: some View { - if let frame = model.frame { - Image(pixels: frame.data, width: frame.width, height: frame.height, bytesPerRow: frame.width * 4, - scale: CGFloat(frame.scale)) - .resizable() + if let content = LinuxWebContent.page(identifier: identifier)?.content { + CacaoWebKit.WebView(content: content) } else { Color.white - } - } -} - -/// The view's page and its latest frame. -final class HostWebViewModel: ObservableObject { - - @Published private(set) var frame: WebFrame? - - private(set) var page: LinuxWebContent? - - private var isDragging = false - - func attach(_ identifier: Int32, size: CGSize, scale: CGFloat) { - guard page == nil else { return } - guard let page = LinuxWebContent.page(identifier: identifier) else { - HostLog.warning("web: no page \(identifier) for a WebView") - return - } - self.page = page - page.display = { [weak self] frame in - self?.frame = frame - } - page.attach(width: UInt32(max(0, size.width.rounded())), height: UInt32(max(0, size.height.rounded())), scale: Float(scale)) - } - - func resize(_ size: CGSize, scale: CGFloat) { - page?.resize(width: UInt32(max(0, size.width.rounded())), height: UInt32(max(0, size.height.rounded())), scale: Float(scale)) - } - - func detach() { - page?.detach() - page?.display = nil - page = nil - isDragging = false - } - - // MARK: Pointer - - func drag(to location: CGPoint) { - guard let page else { return } - page.pointerMoved(x: Float(location.x), y: Float(location.y)) - if !isDragging { - isDragging = true - page.pointerButton(x: Float(location.x), y: Float(location.y), pressed: true) - } - } - - func endDrag(at location: CGPoint) { - guard isDragging, let page else { return } - isDragging = false - page.pointerMoved(x: Float(location.x), y: Float(location.y)) - page.pointerButton(x: Float(location.x), y: Float(location.y), pressed: false) - } - - func hover(at location: CGPoint) { - guard !isDragging else { return } - page?.pointerMoved(x: Float(location.x), y: Float(location.y)) - } - - // MARK: Keys - - func key(_ press: KeyPress) -> KeyPress.Result { - guard let page, let keysym = Keysyms.keysym(for: press.key.character) else { - return .ignored - } - let modifiers = press.modifiers - page.key(keysym: keysym, pressed: press.phase != .up, control: modifiers.contains(.control), - shift: modifiers.contains(.shift), alt: modifiers.contains(.option), meta: modifiers.contains(.command)) - return .handled - } -} - -/// XKB keysyms, which libwpe's key events carry, for the keys Cacao -/// reports as characters. -enum Keysyms { - - static func keysym(for character: Character) -> UInt32? { - switch character { - case KeyEquivalent.return.character, "\n": return 0xFF0D - case KeyEquivalent.escape.character: return 0xFF1B - case KeyEquivalent.delete.character, "\u{7F}": return 0xFF08 // Backspace - case KeyEquivalent.deleteForward.character: return 0xFFFF - case KeyEquivalent.tab.character: return 0xFF09 - case KeyEquivalent.home.character: return 0xFF50 - case KeyEquivalent.leftArrow.character: return 0xFF51 - case KeyEquivalent.upArrow.character: return 0xFF52 - case KeyEquivalent.rightArrow.character: return 0xFF53 - case KeyEquivalent.downArrow.character: return 0xFF54 - case KeyEquivalent.pageUp.character: return 0xFF55 - case KeyEquivalent.pageDown.character: return 0xFF56 - case KeyEquivalent.end.character: return 0xFF57 - default: break - } - guard character.unicodeScalars.count == 1, let scalar = character.unicodeScalars.first else { - return nil - } - let value = scalar.value - switch value { - case 0x20...0x7E, 0xA0...0xFF: - // Latin-1's keysyms are its code points. - return value - case 0x100...0x10FFFF where !(0xE000...0xF8FF).contains(value): - // Other characters are Unicode keysyms; the private-use area - // is where Cacao's function keys are. - return 0x0100_0000 | value - default: - return nil + .onAppear { + if LinuxWebContent.page(identifier: identifier) == nil { + HostLog.warning("web: no page \(identifier) for a WebView") + } + } } } } diff --git a/Sources/LinuxWebKit/LinuxWebContent.swift b/Sources/LinuxWebKit/LinuxWebContent.swift index 10f3104..4180017 100644 --- a/Sources/LinuxWebKit/LinuxWebContent.swift +++ b/Sources/LinuxWebKit/LinuxWebContent.swift @@ -1,127 +1,42 @@ import DynamicWebKit import Foundation import LinuxHost +import WPEWebKit -/// A frame of a page: 8-bit RGBA, premultiplied, rows top to bottom, in -/// pixels, and the pixels per point it was drawn at. -public struct WebFrame: Sendable { - - public var data: Data - - public var width: Int - - public var height: Int - - public var scale: Float -} - -/// The `WebContent` contract (`WebKit.md`) over a WPE `WebKitWebView`. +/// The `WebContent` contract (`WebKit.md`) over PureSwift/WebKit's +/// `WPEWebContent`, a WPE WebKit page. /// /// The page loads whether or not it's shown. The player's `WebView` view -/// attaches it with its size in points, gets its frames through `display`, -/// and forwards its input. Main thread only. +/// shows `content` with CacaoWebKit's `WebView(content:)`, which attaches it +/// while it's on screen and forwards its input. Main thread only. public final class LinuxWebContent: WebContent { - public typealias Pointer = UnsafeMutableRawPointer - public let delegate: any WebContentDelegate - private let id: Int32 - - private let wpe: WPE? - - private var exportable: Pointer? - - private var backend: Pointer? - - private var view: Pointer? - - /// The exportable's client data: this page, until it goes. - private let slot: UnsafeMutablePointer - - private var handlers: [UInt] = [] + /// The engine's page; nil where WPE WebKit isn't installed or can't make + /// one. + public let content: WPEWebContent? - // MARK: What the delegate was last told - - private var reportedURL: String? - - private var reportedTitle = "" - - private var reportedHistory = (canGoBack: false, canGoForward: false) - - private var isLoading = false - - /// A navigation started and hasn't committed: WebKit's `uri` is what - /// was asked for, not where the page is yet. - private var isProvisional = false - - /// The navigation in progress failed, so it doesn't finish. - private var failed = false - - /// The guest asked for the next navigation itself (`load`, `loadHTML`, - /// `loadResource`, or a new window it agreed to), so it isn't asked - /// about it. - private var expectsOwnNavigation = false - - // MARK: The view - - /// Called with each frame while the page is attached, for the view to - /// show. - public var display: ((WebFrame) -> Void)? - - /// The view's size in points and its scale, while attached. - public private(set) var size: (width: UInt32, height: UInt32, scale: Float)? - - public var isAttached: Bool { size != nil } + private let id: Int32 - private var buttonsHeld: UInt32 = 0 + /// What the engine's page reports to, passed on to `delegate`. + private let relay: Relay private init(delegate: any WebContentDelegate, id: Int32) { self.delegate = delegate self.id = id - self.wpe = WPE.shared - slot = .allocate(capacity: 1) - slot.initialize(to: nil) - guard let wpe else { return } - LinuxWebKit.applyNetworkPolicy() - // WebKit destroys the exportable when it's done with the backend. - guard let exportable = wpe.exportableCreate(Self.client, slot, 800, 600), - let backend = wpe.exportableGetViewBackend(exportable), - let webBackend = wpe.webViewBackendNew(backend, unsafeBitCast(Self.onBackendDestroyed, to: Pointer.self), exportable), - let view = wpe.webViewNew(webBackend) else { - HostLog.warning("web: can't make a WPE web view") - return - } - self.exportable = exportable - self.backend = backend - self.view = view - slot.pointee = Unmanaged.passUnretained(self).toOpaque() - wpe.viewBackendAddActivityState(backend, WPE.inWindow) - let data = Unmanaged.passUnretained(self).toOpaque() - func connect(_ signal: String, _ callback: UnsafeRawPointer) { - handlers.append(wpe.signalConnectData(view, signal, callback, data, nil, 0)) - } - connect("load-changed", unsafeBitCast(Self.onLoadChanged, to: UnsafeRawPointer.self)) - connect("load-failed", unsafeBitCast(Self.onLoadFailed, to: UnsafeRawPointer.self)) - connect("load-failed-with-tls-errors", unsafeBitCast(Self.onTLSErrors, to: UnsafeRawPointer.self)) - connect("decide-policy", unsafeBitCast(Self.onDecidePolicy, to: UnsafeRawPointer.self)) - for property in ["title", "uri", "estimated-load-progress"] { - connect("notify::\(property)", unsafeBitCast(Self.onNotify, to: UnsafeRawPointer.self)) + LinuxWebKit.prepare() + relay = Relay() + content = WPEWebContent(delegate: relay) + relay.page = self + if content != nil { + // The engine watches what the new page waits for from here on. + LinuxWebKit.pump() } } deinit { - if let wpe, let view { - for handler in handlers { - wpe.signalHandlerDisconnect(view, handler) - } - wpe.objectUnref(view) - } - // The slot stays, empty, for a frame still on its way. - slot.pointee = nil - let id = self.id Self.pages[id] = nil - LinuxWebKit.pagesChanged() } // MARK: WebContent @@ -130,7 +45,6 @@ public final class LinuxWebContent: WebContent { let page = LinuxWebContent(delegate: delegate, id: nextID) nextID &+= 1 pages[page.id] = Weak(page) - LinuxWebKit.pagesChanged() return page } @@ -138,86 +52,68 @@ public final class LinuxWebContent: WebContent { id } + /// A URL that isn't one, or a remote one without the network, is + /// refused before anything starts, with WPE WebKit or without. public func load(_ url: String) { guard let scheme = Self.scheme(of: url) else { - delegate.didFailNavigation(self, error: WebError.Code.badURL.rawValue, message: "\(url) isn't a URL") - return + return delegate.didFailNavigation(self, error: WebError.Code.badURL.rawValue, message: "\(url) isn't a URL") } if Self.remoteSchemes.contains(scheme), !LinuxWebKit.hasNetwork { - delegate.didFailNavigation(self, error: WebError.Code.notPermitted.rawValue, message: Self.noNetwork) - return + return delegate.didFailNavigation(self, error: WebError.Code.notPermitted.rawValue, message: Self.noNetwork) } - guard let view, let wpe else { + guard let content else { return unavailable() } LinuxWebKit.applyNetworkPolicy() - startOwnNavigation() - wpe.webViewLoadURI(view, url) + content.load(url) + LinuxWebKit.pump() } public func loadHTML(_ html: String, baseURL: String?) { - guard let view, let wpe else { + guard let content else { return unavailable() } - startOwnNavigation() - if let baseURL { - wpe.webViewLoadHTML(view, html, baseURL) - } else { - wpe.webViewLoadHTML(view, html, nil) - } + content.loadHTML(html, baseURL: baseURL) + LinuxWebKit.pump() } public func loadResource(_ path: String) { - guard let view, let wpe else { + guard let content else { return unavailable() } guard let file = Self.resourceFile(path) else { - delegate.didFailNavigation(self, error: WebError.Code.badURL.rawValue, message: "no resource \(path) in the app's bundle") - return + return delegate.didFailNavigation(self, error: WebError.Code.badURL.rawValue, message: "no resource \(path) in the app's bundle") } - startOwnNavigation() - wpe.webViewLoadURI(view, URL(fileURLWithPath: file).absoluteString) + content.load(URL(fileURLWithPath: file).absoluteString) + LinuxWebKit.pump() } public func reload() { - guard let wpe, let view else { return } - isProvisional = true - wpe.webViewReload(view) + content?.reload() + LinuxWebKit.pump() } public func stopLoading() { - guard let wpe, let view else { return } - wpe.webViewStopLoading(view) + content?.stopLoading() + LinuxWebKit.pump() } - /// WebKit moves its `uri` to the history item before asking about the - /// navigation, so it's provisional from here. public func goBack() { - guard let wpe, let view, wpe.webViewCanGoBack(view) != 0 else { return } - isProvisional = true - wpe.webViewGoBack(view) + content?.goBack() + LinuxWebKit.pump() } public func goForward() { - guard let wpe, let view, wpe.webViewCanGoForward(view) != 0 else { return } - isProvisional = true - wpe.webViewGoForward(view) + content?.goForward() + LinuxWebKit.pump() } public func evaluateJavaScript(_ script: String, request: Int32) { - guard let wpe, let view else { - delegate.didEvaluateJavaScript(self, request: request, result: nil, error: Self.notInstalled) - return + guard let content else { + return delegate.didEvaluateJavaScript(self, request: request, result: nil, error: Self.notInstalled) } - let box = Unmanaged.passRetained(Evaluation(page: self, request: request)).toOpaque() - wpe.webViewEvaluateJavaScript(view, script, -1, nil, nil, nil, unsafeBitCast(Self.onEvaluated, to: Pointer.self), box) - } - - /// The guest's own load: it isn't asked about, and WebKit's `uri`, - /// which changes at once, isn't where the page is until it commits. - private func startOwnNavigation() { - expectsOwnNavigation = true - isProvisional = true + content.evaluateJavaScript(script, request: request) + LinuxWebKit.pump() } private func unavailable() { @@ -244,10 +140,6 @@ public final class LinuxWebContent: WebContent { pages[identifier]?.page } - static var count: Int { - pages.values.filter { $0.page != nil }.count - } - // MARK: URLs /// Schemes that reach the network. @@ -278,386 +170,53 @@ public final class LinuxWebContent: WebContent { } return file } +} - // MARK: Reporting - - /// Where the page is: not while a navigation is provisional, nor an - /// empty URI WebKit has after a failed first load. - private func reportURL() { - guard let wpe, let view, !isProvisional else { return } - let uri = wpe.webViewGetURI(view).map { String(cString: $0) } - let url = uri?.isEmpty == false ? uri : nil - guard url != reportedURL else { return } - reportedURL = url - delegate.didChangeURL(self, url: url) - reportHistory() - } - - private func reportTitle() { - guard let wpe, let view else { return } - let title = wpe.webViewGetTitle(view).map { String(cString: $0) } ?? "" - guard title != reportedTitle else { return } - reportedTitle = title - delegate.didChangeTitle(self, title: title) - } - - private func reportProgress() { - guard let wpe, let view, isLoading else { return } - delegate.didChangeLoading(self, isLoading: true, progress: wpe.webViewGetEstimatedLoadProgress(view)) - } - - private func reportHistory() { - guard let wpe, let view else { return } - let history = (canGoBack: wpe.webViewCanGoBack(view) != 0, canGoForward: wpe.webViewCanGoForward(view) != 0) - guard history != reportedHistory else { return } - reportedHistory = history - delegate.didChangeHistory(self, canGoBack: history.canGoBack, canGoForward: history.canGoForward) - } - - fileprivate func loadChanged(_ event: Int32) { - switch event { - case WPE.loadStarted: - failed = false - isLoading = true - isProvisional = true - reportProgress() - case WPE.loadRedirected: - // The redirect is followed: the page is going there. - isProvisional = false - reportURL() - isProvisional = true - case WPE.loadCommitted: - isProvisional = false - reportURL() - reportHistory() - case WPE.loadFinished: - isLoading = false - isProvisional = false - reportURL() - reportHistory() - delegate.didChangeLoading(self, isLoading: false, progress: 1) - if !failed { - delegate.didFinishNavigation(self) - } - failed = false - default: - break - } - } - - fileprivate func loadFailed(_ error: GError) { - HostLog.debug("web: page \(id) failed: \(error.domain) \(error.code) \(error.message)") - guard let code = Self.errorCode(error) else { - // Stopped, or replaced by another navigation: not a failure. - return - } - fail(code, error.message) - } - - fileprivate func fail(_ code: WebError.Code, _ message: String) { - failed = true - delegate.didFailNavigation(self, error: code.rawValue, message: message) - } - - /// `WebError.Code` for a load's GError; nil when it isn't a failure. - static func errorCode(_ error: GError) -> WebError.Code? { - switch error.domain { - case "WebKitNetworkError": - switch error.code { - case 302: return nil // cancelled - case 300: return .network // transport - case 301, 303: return .badURL // unknown protocol, no such file - default: return .unknown - } - case "WebKitPolicyError": - switch error.code { - case 102: return nil // interrupted by a policy change - case 101: return .badURL // can't show the URI - default: return .unknown - } - case "g-resolver-error-quark", "soup-session-error-quark": - return .network - case "g-io-error-quark": - return error.code == 24 ? .timedOut : .network - case "g-tls-error-quark": - return .security - default: - return .unknown - } - } - - /// Asks the delegate about a navigation the page or the user started, - /// and answers WebKit. - fileprivate func decide(_ decision: Pointer, type: Int32) -> Bool { - guard let wpe, type == WPE.navigationAction || type == WPE.newWindowAction, - let action = wpe.navigationPolicyDecisionGetNavigationAction(decision) else { - return false - } - let url = wpe.navigationActionGetRequest(action).flatMap(wpe.uriRequestGetURI).map { String(cString: $0) } ?? "" - let kind = Self.navigationKind(wpe.navigationActionGetNavigationType(action)) - if type == WPE.navigationAction, expectsOwnNavigation { - expectsOwnNavigation = false - wpe.policyDecisionUse(decision) - return true - } - if let scheme = Self.scheme(of: url), Self.remoteSchemes.contains(scheme), !LinuxWebKit.hasNetwork { - wpe.policyDecisionIgnore(decision) - delegate.didFailNavigation(self, error: WebError.Code.notPermitted.rawValue, message: Self.noNetwork) - return true - } - let allowed = delegate.shouldNavigate(self, url: url, kind: kind.rawValue, isMainFrame: true) - if type == WPE.newWindowAction { - // New windows load in this page. - wpe.policyDecisionIgnore(decision) - if allowed, let view { - startOwnNavigation() - wpe.webViewLoadURI(view, url) - } - } else if allowed { - isProvisional = true - wpe.policyDecisionUse(decision) - } else { - wpe.policyDecisionIgnore(decision) - } - return true - } - - /// `WebKitNavigationType` as `WebNavigationKind`. - static func navigationKind(_ type: Int32) -> WebNavigationKind { - switch type { - case 0: .linkActivated - case 1, 4: .formSubmitted // submitted, resubmitted - case 2: .backForward - case 3: .reload - default: .other - } - } - - // MARK: The view - - /// Puts the page on screen at a size in points: it's visible, draws at - /// that size, and sends its frames to `display`. - public func attach(width: UInt32, height: UInt32, scale: Float) { - guard let wpe, let backend else { return } - size = (max(width, 1), max(height, 1), scale) - wpe.viewBackendDispatchSetDeviceScaleFactor(backend, scale) - wpe.viewBackendDispatchSetSize(backend, max(width, 1), max(height, 1)) - wpe.viewBackendAddActivityState(backend, WPE.visible) - } - - public func resize(width: UInt32, height: UInt32, scale: Float) { - guard let wpe, let backend, let size else { return } - let width = max(width, 1), height = max(height, 1) - if scale != size.scale { - wpe.viewBackendDispatchSetDeviceScaleFactor(backend, scale) - } - if width != size.width || height != size.height { - wpe.viewBackendDispatchSetSize(backend, width, height) - } - self.size = (width, height, scale) - } - - /// The view is gone: the page stays loaded, hidden and unfocused. - public func detach() { - guard let wpe, let backend, isAttached else { return } - focus(false) - buttonsHeld = 0 - wpe.viewBackendRemoveActivityState(backend, WPE.visible) - size = nil - } - - fileprivate func receive(_ buffer: Pointer) { - guard let wpe, let exportable else { return } - defer { - wpe.exportableReleaseShmBuffer(exportable, buffer) - wpe.exportableFrameComplete(exportable) - } - guard let size, let display, let shm = wpe.shmExportedBufferGetShmBuffer(buffer) else { return } - wpe.shmBufferBeginAccess(shm) - defer { wpe.shmBufferEndAccess(shm) } - let width = Int(wpe.shmBufferGetWidth(shm)), height = Int(wpe.shmBufferGetHeight(shm)) - let stride = Int(wpe.shmBufferGetStride(shm)) - guard width > 0, height > 0, stride >= width * 4, let pixels = wpe.shmBufferGetData(shm) else { return } - let data = Self.rgba(fromBGRA: UnsafeRawPointer(pixels), width: width, height: height, stride: stride) - display(WebFrame(data: data, width: width, height: height, scale: size.scale)) - } - - /// Wayland's ARGB8888, premultiplied, blue first in memory, as RGBA. - static func rgba(fromBGRA pixels: UnsafeRawPointer, width: Int, height: Int, stride: Int) -> Data { - var data = Data(count: width * height * 4) - data.withUnsafeMutableBytes { (output: UnsafeMutableRawBufferPointer) in - let output = output.bindMemory(to: UInt8.self) - let input = pixels.assumingMemoryBound(to: UInt8.self) - for row in 0.. UInt32 { - UInt32(truncatingIfNeeded: MainLoop.now() / 1_000_000) - } - - // MARK: Callbacks from C +/// The engine page's delegate: passes what it hears to the guest's, with +/// the contract's page in place of the engine's. Its numbers are already +/// the contract's (`WebNavigationKind`, `WebError.Code`). It doesn't keep +/// the page alive: the page owns the engine's page, which owns this. +private final class Relay: WPEWebContentDelegate { - /// `wpe_view_backend_exportable_fdo_client`: frames in shared memory. - nonisolated(unsafe) private static let client: UnsafeRawPointer = { - let client = UnsafeMutablePointer.allocate(capacity: 5) - client.initialize(repeating: nil, count: 5) - client[2] = unsafeBitCast(LinuxWebContent.onShmBuffer, to: UnsafeRawPointer.self) - return UnsafeRawPointer(client) - }() + weak var page: LinuxWebContent? - private static func page(_ data: Pointer?) -> LinuxWebContent? { - data.map { Unmanaged.fromOpaque($0).takeUnretainedValue() } + func shouldNavigate(_ content: WPEWebContent, url: String, kind: Int32, isMainFrame: Bool) -> Bool { + guard let page else { return false } + return page.delegate.shouldNavigate(page, url: url, kind: kind, isMainFrame: isMainFrame) } - private static let onShmBuffer: @convention(c) (Pointer?, Pointer?) -> Void = { data, buffer in - guard let buffer else { return } - guard let pointer = data?.assumingMemoryBound(to: Pointer?.self).pointee else { - return - } - page(pointer)?.receive(buffer) + func didChangeURL(_ content: WPEWebContent, url: String?) { + guard let page else { return } + page.delegate.didChangeURL(page, url: url) } - private static let onBackendDestroyed: @convention(c) (Pointer?) -> Void = { exportable in - if let exportable { - WPE.shared?.exportableDestroy(exportable) - } + func didChangeTitle(_ content: WPEWebContent, title: String) { + guard let page else { return } + page.delegate.didChangeTitle(page, title: title) } - private static let onLoadChanged: @convention(c) (Pointer?, Int32, Pointer?) -> Void = { _, event, data in - page(data)?.loadChanged(event) + func didChangeLoading(_ content: WPEWebContent, isLoading: Bool, progress: Double) { + guard let page else { return } + page.delegate.didChangeLoading(page, isLoading: isLoading, progress: progress) } - /// load-failed: the view, the load event, the URI and the GError; - /// true, as handled. - private static let onLoadFailed: @convention(c) (Pointer?, Int32, UnsafePointer?, Pointer?, Pointer?) -> Int32 = { - _, _, _, error, data in - guard let page = page(data), let wpe = page.wpe else { return 1 } - page.loadFailed(error.map(wpe.error) ?? GError(domain: "", code: 0, message: "")) - return 1 + func didChangeHistory(_ content: WPEWebContent, canGoBack: Bool, canGoForward: Bool) { + guard let page else { return } + page.delegate.didChangeHistory(page, canGoBack: canGoBack, canGoForward: canGoForward) } - /// load-failed-with-tls-errors: the view, the URI, the certificate and - /// its errors; true, as handled, so load-failed doesn't follow. - private static let onTLSErrors: @convention(c) (Pointer?, UnsafePointer?, Pointer?, UInt32, Pointer?) -> Int32 = { - _, uri, _, _, data in - let url = uri.map { String(cString: $0) } ?? "" - page(data)?.fail(.security, "the certificate for \(url) isn't trusted") - return 1 + func didFinishNavigation(_ content: WPEWebContent) { + guard let page else { return } + page.delegate.didFinishNavigation(page) } - private static let onDecidePolicy: @convention(c) (Pointer?, Pointer?, Int32, Pointer?) -> Int32 = { _, decision, type, data in - guard let page = page(data), let decision else { return 0 } - return page.decide(decision, type: type) ? 1 : 0 + func didFailNavigation(_ content: WPEWebContent, error: Int32, message: String) { + guard let page else { return } + page.delegate.didFailNavigation(page, error: error, message: message) } - private static let onNotify: @convention(c) (Pointer?, Pointer?, Pointer?) -> Void = { _, spec, data in - guard let page = page(data), let spec, let name = page.wpe?.paramSpecGetName(spec) else { return } - switch String(cString: name) { - case "title": page.reportTitle() - case "uri": page.reportURL() - case "estimated-load-progress": page.reportProgress() - default: break - } - } - - private final class Evaluation { - let page: LinuxWebContent - let request: Int32 - init(page: LinuxWebContent, request: Int32) { - self.page = page - self.request = request - } - } - - /// A script's value as JSON (nil for undefined and what JSON can't - /// hold), or the exception's message. - private static let onEvaluated: @convention(c) (Pointer?, Pointer?, Pointer?) -> Void = { source, result, data in - guard let data else { return } - let evaluation = Unmanaged.fromOpaque(data).takeRetainedValue() - let page = evaluation.page - guard let wpe = page.wpe else { return } - var error: Pointer? - guard let source, let result, let value = wpe.webViewEvaluateJavaScriptFinish(source, result, &error) else { - let message = error.map(wpe.error)?.message ?? "the script failed" - if let error { - wpe.errorFree(error) - } - page.delegate.didEvaluateJavaScript(page, request: evaluation.request, result: nil, error: message) - return - } - defer { wpe.objectUnref(value) } - var json: String? - if wpe.valueIsUndefined(value) == 0, let text = wpe.valueToJSON(value, 0) { - json = String(cString: text) - wpe.free(text) - } - page.delegate.didEvaluateJavaScript(page, request: evaluation.request, result: json, error: nil) + func didEvaluateJavaScript(_ content: WPEWebContent, request: Int32, result: String?, error: String?) { + guard let page else { return } + page.delegate.didEvaluateJavaScript(page, request: request, result: result, error: error) } } diff --git a/Sources/LinuxWebKit/LinuxWebKit.swift b/Sources/LinuxWebKit/LinuxWebKit.swift index c6c8847..938aea8 100644 --- a/Sources/LinuxWebKit/LinuxWebKit.swift +++ b/Sources/LinuxWebKit/LinuxWebKit.swift @@ -2,9 +2,11 @@ import DynamicRuntime import DynamicWebKit import LinuxHost import RuntimeABI +import WPEWebKit /// The web view contracts (`WebKit.md`, `Plan.md` §8): pages in WPE WebKit, -/// shown by the player's `WebView` view. Main loop only. +/// through PureSwift/WebKit, shown by the player's `WebView` view. Main +/// loop only. public enum LinuxWebKit: HostModule { public static var contracts: [ContractDescriptor] { @@ -19,16 +21,14 @@ public enum LinuxWebKit: HostModule { /// Whether WPE WebKit loads. Without it a page loads nothing, and says /// so. public static var isAvailable: Bool { - WPE.shared != nil + WPEEngine.isAvailable } // MARK: The network /// In place of the app's capabilities, for tests: whether pages may /// reach the network. - nonisolated(unsafe) public static var networkOverride: Bool? = nil { - didSet { appliedNetwork = nil } - } + nonisolated(unsafe) public static var networkOverride: Bool? = nil /// Whether pages may reach the network: the app declares `network`. /// Without it, remote loads are refused, and the rest go through a @@ -37,49 +37,37 @@ public enum LinuxWebKit: HostModule { networkOverride ?? HostPermissions.declared.contains(.network) } - nonisolated(unsafe) private static var appliedNetwork: Bool? - - /// Sets WebKit's proxy to match `hasNetwork`, once per change. + /// Gives the engine the app's network, which it applies once per + /// change. static func applyNetworkPolicy() { - guard let wpe = WPE.shared else { return } - let allowed: Bool = hasNetwork - guard appliedNetwork != allowed else { return } - appliedNetwork = allowed - if allowed { - if let session = wpe.networkSessionGetDefault() { - wpe.networkSessionSetProxySettings(session, 0, nil) // the system's proxy - } - } else { - wpe.blockNetwork() - } + WPEEngine.isNetworkAllowed = hasNetwork } - // MARK: GLib's main context + // MARK: The engine's loop - /// How often the main loop runs GLib's context while there are pages. - static let interval: Int64 = 8_000_000 + nonisolated(unsafe) private static var isPrepared = false - nonisolated(unsafe) private static var timer: MainLoop.TimerToken? - - /// Runs GLib's context on the main loop while any page is alive. - static func pagesChanged() { - if LinuxWebContent.count == 0 { - if let timer { - MainLoop.shared.cancel(timer) - self.timer = nil - } - } else if timer == nil { - schedule() - } + /// Before the first page: the engine logs to the host's log, and its + /// loop runs on the main loop, which it wakes when its pages have work. + static func prepare() { + applyNetworkPolicy() + guard !isPrepared else { return } + isPrepared = true + WPEEngine.logger = { HostLog.warning("web: \($0)") } + WPEEngine.onReady = { MainLoop.shared.post { WPEEngine.pump() } } } - private static func schedule() { - timer = MainLoop.shared.schedule(after: interval) { - timer = nil - WPE.shared?.dispatch() - if LinuxWebContent.count > 0 { - schedule() - } + /// Runs the engine's loop on the main loop's next turn, after the guest's + /// call that set it off has returned, so the guest doesn't hear from + /// its pages while it's calling them. + static func pump() { + guard !isPumpPosted else { return } + isPumpPosted = true + MainLoop.shared.post { + isPumpPosted = false + WPEEngine.pump() } } + + nonisolated(unsafe) private static var isPumpPosted = false } diff --git a/Sources/LinuxWebKit/WPE.swift b/Sources/LinuxWebKit/WPE.swift deleted file mode 100644 index 64b180d..0000000 --- a/Sources/LinuxWebKit/WPE.swift +++ /dev/null @@ -1,294 +0,0 @@ -#if canImport(Glibc) -import Glibc -#elseif canImport(Darwin) -import Darwin -#endif -import LinuxHost - -/// WPE WebKit, WebKit's port for embedding, opened at run time -/// (`Plan.md` §8), as Perry does. -/// -/// Each page is a `WebKitWebView` over a view backend from WPEBackend-fdo -/// in its shared-memory mode, which hands every frame the web process draws -/// to the host as a `wl_shm` buffer: no GL. Pages run in WPE's web and -/// network processes, and their signals and replies come through GLib's -/// main context, which the main loop runs while there are pages. Without -/// WPE installed, `WebContent` is unavailable. -final class WPE { - - typealias Pointer = UnsafeMutableRawPointer - - // MARK: libwpe and WPEBackend-fdo - - let viewBackendAddActivityState: @convention(c) (Pointer, UInt32) -> Void - let viewBackendRemoveActivityState: @convention(c) (Pointer, UInt32) -> Void - let viewBackendDispatchSetSize: @convention(c) (Pointer, UInt32, UInt32) -> Void - let viewBackendDispatchSetDeviceScaleFactor: @convention(c) (Pointer, Float) -> Void - let viewBackendDispatchPointerEvent: @convention(c) (Pointer, UnsafeMutableRawPointer) -> Void - let viewBackendDispatchAxisEvent: @convention(c) (Pointer, UnsafeMutableRawPointer) -> Void - let viewBackendDispatchKeyboardEvent: @convention(c) (Pointer, UnsafeMutableRawPointer) -> Void - let exportableCreate: @convention(c) (UnsafeRawPointer, Pointer?, UInt32, UInt32) -> Pointer? - let exportableDestroy: @convention(c) (Pointer) -> Void - let exportableGetViewBackend: @convention(c) (Pointer) -> Pointer? - let exportableFrameComplete: @convention(c) (Pointer) -> Void - let exportableReleaseShmBuffer: @convention(c) (Pointer, Pointer) -> Void - let shmExportedBufferGetShmBuffer: @convention(c) (Pointer) -> Pointer? - - // MARK: libwayland-server's shared-memory buffers - - let shmBufferGetData: @convention(c) (Pointer) -> Pointer? - let shmBufferGetWidth: @convention(c) (Pointer) -> Int32 - let shmBufferGetHeight: @convention(c) (Pointer) -> Int32 - let shmBufferGetStride: @convention(c) (Pointer) -> Int32 - let shmBufferBeginAccess: @convention(c) (Pointer) -> Void - let shmBufferEndAccess: @convention(c) (Pointer) -> Void - - // MARK: WPE WebKit - - let webViewBackendNew: @convention(c) (Pointer, Pointer?, Pointer?) -> Pointer? - let webViewNew: @convention(c) (Pointer) -> Pointer? - let webViewLoadHTML: @convention(c) (Pointer, UnsafePointer, UnsafePointer?) -> Void - let webViewLoadURI: @convention(c) (Pointer, UnsafePointer) -> Void - let webViewGetTitle: @convention(c) (Pointer) -> UnsafePointer? - let webViewGetURI: @convention(c) (Pointer) -> UnsafePointer? - let webViewIsLoading: @convention(c) (Pointer) -> Int32 - let webViewGetEstimatedLoadProgress: @convention(c) (Pointer) -> Double - let webViewCanGoBack: @convention(c) (Pointer) -> Int32 - let webViewCanGoForward: @convention(c) (Pointer) -> Int32 - let webViewGoBack: @convention(c) (Pointer) -> Void - let webViewGoForward: @convention(c) (Pointer) -> Void - let webViewReload: @convention(c) (Pointer) -> Void - let webViewStopLoading: @convention(c) (Pointer) -> Void - let webViewGetSettings: @convention(c) (Pointer) -> Pointer? - let settingsSetAllowFileAccessFromFileURLs: @convention(c) (Pointer, Int32) -> Void - let webViewEvaluateJavaScript: @convention(c) (Pointer, UnsafePointer, Int, UnsafePointer?, - UnsafePointer?, Pointer?, Pointer?, Pointer?) -> Void - let webViewEvaluateJavaScriptFinish: @convention(c) (Pointer, Pointer, UnsafeMutablePointer) -> Pointer? - let valueIsUndefined: @convention(c) (Pointer) -> Int32 - let valueToJSON: @convention(c) (Pointer, UInt32) -> UnsafeMutablePointer? - let navigationPolicyDecisionGetNavigationAction: @convention(c) (Pointer) -> Pointer? - let navigationActionGetRequest: @convention(c) (Pointer) -> Pointer? - let navigationActionGetNavigationType: @convention(c) (Pointer) -> Int32 - let uriRequestGetURI: @convention(c) (Pointer) -> UnsafePointer? - let policyDecisionUse: @convention(c) (Pointer) -> Void - let policyDecisionIgnore: @convention(c) (Pointer) -> Void - let networkSessionGetDefault: @convention(c) () -> Pointer? - let networkSessionSetProxySettings: @convention(c) (Pointer, Int32, Pointer?) -> Void - let networkProxySettingsNew: @convention(c) (UnsafePointer?, UnsafePointer?>?) -> Pointer? - let networkProxySettingsFree: @convention(c) (Pointer) -> Void - - // MARK: GLib and GObject - - let mainContextIteration: @convention(c) (Pointer?, Int32) -> Int32 - let signalConnectData: @convention(c) (Pointer, UnsafePointer, UnsafeRawPointer, Pointer?, Pointer?, Int32) -> UInt - let signalHandlerDisconnect: @convention(c) (Pointer, UInt) -> Void - let objectUnref: @convention(c) (Pointer) -> Void - let free: @convention(c) (Pointer?) -> Void - let errorFree: @convention(c) (Pointer) -> Void - let quarkToString: @convention(c) (UInt32) -> UnsafePointer? - let paramSpecGetName: @convention(c) (Pointer) -> UnsafePointer? - - // MARK: Constants - - // WebKitLoadEvent. - static let loadStarted: Int32 = 0, loadRedirected: Int32 = 1, loadCommitted: Int32 = 2, loadFinished: Int32 = 3 - // WebKitPolicyDecisionType. - static let navigationAction: Int32 = 0, newWindowAction: Int32 = 1 - /// wpe_view_activity_state. - static let visible: UInt32 = 1, focused: UInt32 = 2, inWindow: UInt32 = 4 - /// WEBKIT_NETWORK_PROXY_MODE_CUSTOM. - static let proxyModeCustom: Int32 = 2 - - /// WPE, initialized; nil when it isn't installed. - static let shared: WPE? = WPE() - - private init?() { - let names = ["libwpe-1.0.so.1", "libWPEBackend-fdo-1.0.so.1", "libwayland-server.so.0", "libWPEWebKit-2.0.so.1", - "libglib-2.0.so.0", "libgobject-2.0.so.0"] - // Local, so WPE's libraries never stand in for others of the same - // names in the process. - let libraries = names.map { dlopen($0, RTLD_NOW | RTLD_LOCAL) } - guard let wpe = libraries[0], let fdo = libraries[1], let wayland = libraries[2], let webkit = libraries[3], - let glib = libraries[4], let gobject = libraries[5] else { - HostLog.debug("web: WPE WebKit isn't installed") - return nil - } - var missing: [String] = [] - func bind(_ library: Pointer, _ name: String, _: T.Type) -> T { - guard let symbol = dlsym(library, name) else { - missing.append(name) - return unsafeBitCast(WPE.missingFunction, to: T.self) - } - return unsafeBitCast(symbol, to: T.self) - } - let loaderInit = bind(wpe, "wpe_loader_init", (@convention(c) (UnsafePointer) -> Int32).self) - let initializeShm = bind(fdo, "wpe_fdo_initialize_shm", (@convention(c) () -> Int32).self) - viewBackendAddActivityState = bind(wpe, "wpe_view_backend_add_activity_state", (@convention(c) (Pointer, UInt32) -> Void).self) - viewBackendRemoveActivityState = bind(wpe, "wpe_view_backend_remove_activity_state", (@convention(c) (Pointer, UInt32) -> Void).self) - viewBackendDispatchSetSize = bind(wpe, "wpe_view_backend_dispatch_set_size", (@convention(c) (Pointer, UInt32, UInt32) -> Void).self) - viewBackendDispatchSetDeviceScaleFactor = bind(wpe, "wpe_view_backend_dispatch_set_device_scale_factor", - (@convention(c) (Pointer, Float) -> Void).self) - viewBackendDispatchPointerEvent = bind(wpe, "wpe_view_backend_dispatch_pointer_event", - (@convention(c) (Pointer, UnsafeMutableRawPointer) -> Void).self) - viewBackendDispatchAxisEvent = bind(wpe, "wpe_view_backend_dispatch_axis_event", - (@convention(c) (Pointer, UnsafeMutableRawPointer) -> Void).self) - viewBackendDispatchKeyboardEvent = bind(wpe, "wpe_view_backend_dispatch_keyboard_event", - (@convention(c) (Pointer, UnsafeMutableRawPointer) -> Void).self) - exportableCreate = bind(fdo, "wpe_view_backend_exportable_fdo_create", - (@convention(c) (UnsafeRawPointer, Pointer?, UInt32, UInt32) -> Pointer?).self) - exportableDestroy = bind(fdo, "wpe_view_backend_exportable_fdo_destroy", (@convention(c) (Pointer) -> Void).self) - exportableGetViewBackend = bind(fdo, "wpe_view_backend_exportable_fdo_get_view_backend", (@convention(c) (Pointer) -> Pointer?).self) - exportableFrameComplete = bind(fdo, "wpe_view_backend_exportable_fdo_dispatch_frame_complete", (@convention(c) (Pointer) -> Void).self) - exportableReleaseShmBuffer = bind(fdo, "wpe_view_backend_exportable_fdo_dispatch_release_shm_exported_buffer", - (@convention(c) (Pointer, Pointer) -> Void).self) - shmExportedBufferGetShmBuffer = bind(fdo, "wpe_fdo_shm_exported_buffer_get_shm_buffer", (@convention(c) (Pointer) -> Pointer?).self) - shmBufferGetData = bind(wayland, "wl_shm_buffer_get_data", (@convention(c) (Pointer) -> Pointer?).self) - shmBufferGetWidth = bind(wayland, "wl_shm_buffer_get_width", (@convention(c) (Pointer) -> Int32).self) - shmBufferGetHeight = bind(wayland, "wl_shm_buffer_get_height", (@convention(c) (Pointer) -> Int32).self) - shmBufferGetStride = bind(wayland, "wl_shm_buffer_get_stride", (@convention(c) (Pointer) -> Int32).self) - shmBufferBeginAccess = bind(wayland, "wl_shm_buffer_begin_access", (@convention(c) (Pointer) -> Void).self) - shmBufferEndAccess = bind(wayland, "wl_shm_buffer_end_access", (@convention(c) (Pointer) -> Void).self) - webViewBackendNew = bind(webkit, "webkit_web_view_backend_new", (@convention(c) (Pointer, Pointer?, Pointer?) -> Pointer?).self) - webViewNew = bind(webkit, "webkit_web_view_new", (@convention(c) (Pointer) -> Pointer?).self) - webViewLoadHTML = bind(webkit, "webkit_web_view_load_html", - (@convention(c) (Pointer, UnsafePointer, UnsafePointer?) -> Void).self) - webViewLoadURI = bind(webkit, "webkit_web_view_load_uri", (@convention(c) (Pointer, UnsafePointer) -> Void).self) - webViewGetTitle = bind(webkit, "webkit_web_view_get_title", (@convention(c) (Pointer) -> UnsafePointer?).self) - webViewGetURI = bind(webkit, "webkit_web_view_get_uri", (@convention(c) (Pointer) -> UnsafePointer?).self) - webViewIsLoading = bind(webkit, "webkit_web_view_is_loading", (@convention(c) (Pointer) -> Int32).self) - webViewGetEstimatedLoadProgress = bind(webkit, "webkit_web_view_get_estimated_load_progress", (@convention(c) (Pointer) -> Double).self) - webViewCanGoBack = bind(webkit, "webkit_web_view_can_go_back", (@convention(c) (Pointer) -> Int32).self) - webViewCanGoForward = bind(webkit, "webkit_web_view_can_go_forward", (@convention(c) (Pointer) -> Int32).self) - webViewGoBack = bind(webkit, "webkit_web_view_go_back", (@convention(c) (Pointer) -> Void).self) - webViewGoForward = bind(webkit, "webkit_web_view_go_forward", (@convention(c) (Pointer) -> Void).self) - webViewReload = bind(webkit, "webkit_web_view_reload", (@convention(c) (Pointer) -> Void).self) - webViewStopLoading = bind(webkit, "webkit_web_view_stop_loading", (@convention(c) (Pointer) -> Void).self) - webViewGetSettings = bind(webkit, "webkit_web_view_get_settings", (@convention(c) (Pointer) -> Pointer?).self) - settingsSetAllowFileAccessFromFileURLs = bind(webkit, "webkit_settings_set_allow_file_access_from_file_urls", - (@convention(c) (Pointer, Int32) -> Void).self) - webViewEvaluateJavaScript = bind(webkit, "webkit_web_view_evaluate_javascript", - (@convention(c) (Pointer, UnsafePointer, Int, UnsafePointer?, - UnsafePointer?, Pointer?, Pointer?, Pointer?) -> Void).self) - webViewEvaluateJavaScriptFinish = bind(webkit, "webkit_web_view_evaluate_javascript_finish", - (@convention(c) (Pointer, Pointer, UnsafeMutablePointer) -> Pointer?).self) - valueIsUndefined = bind(webkit, "jsc_value_is_undefined", (@convention(c) (Pointer) -> Int32).self) - valueToJSON = bind(webkit, "jsc_value_to_json", (@convention(c) (Pointer, UInt32) -> UnsafeMutablePointer?).self) - navigationPolicyDecisionGetNavigationAction = bind(webkit, "webkit_navigation_policy_decision_get_navigation_action", - (@convention(c) (Pointer) -> Pointer?).self) - navigationActionGetRequest = bind(webkit, "webkit_navigation_action_get_request", (@convention(c) (Pointer) -> Pointer?).self) - navigationActionGetNavigationType = bind(webkit, "webkit_navigation_action_get_navigation_type", - (@convention(c) (Pointer) -> Int32).self) - uriRequestGetURI = bind(webkit, "webkit_uri_request_get_uri", (@convention(c) (Pointer) -> UnsafePointer?).self) - policyDecisionUse = bind(webkit, "webkit_policy_decision_use", (@convention(c) (Pointer) -> Void).self) - policyDecisionIgnore = bind(webkit, "webkit_policy_decision_ignore", (@convention(c) (Pointer) -> Void).self) - networkSessionGetDefault = bind(webkit, "webkit_network_session_get_default", (@convention(c) () -> Pointer?).self) - networkSessionSetProxySettings = bind(webkit, "webkit_network_session_set_proxy_settings", - (@convention(c) (Pointer, Int32, Pointer?) -> Void).self) - networkProxySettingsNew = bind(webkit, "webkit_network_proxy_settings_new", - (@convention(c) (UnsafePointer?, UnsafePointer?>?) -> Pointer?).self) - networkProxySettingsFree = bind(webkit, "webkit_network_proxy_settings_free", (@convention(c) (Pointer) -> Void).self) - mainContextIteration = bind(glib, "g_main_context_iteration", (@convention(c) (Pointer?, Int32) -> Int32).self) - signalConnectData = bind(gobject, "g_signal_connect_data", - (@convention(c) (Pointer, UnsafePointer, UnsafeRawPointer, Pointer?, Pointer?, Int32) -> UInt).self) - signalHandlerDisconnect = bind(gobject, "g_signal_handler_disconnect", (@convention(c) (Pointer, UInt) -> Void).self) - objectUnref = bind(gobject, "g_object_unref", (@convention(c) (Pointer) -> Void).self) - free = bind(glib, "g_free", (@convention(c) (Pointer?) -> Void).self) - errorFree = bind(glib, "g_error_free", (@convention(c) (Pointer) -> Void).self) - quarkToString = bind(glib, "g_quark_to_string", (@convention(c) (UInt32) -> UnsafePointer?).self) - paramSpecGetName = bind(gobject, "g_param_spec_get_name", (@convention(c) (Pointer) -> UnsafePointer?).self) - guard missing.isEmpty else { - HostLog.warning("web: WPE WebKit is incomplete (no \(missing.joined(separator: ", ")))") - return nil - } - guard loaderInit("libWPEBackend-fdo-1.0.so.1") != 0, initializeShm() != 0 else { - HostLog.warning("web: WPEBackend-fdo didn't initialize") - return nil - } - } - - private static let missingFunction: @convention(c) () -> Void = {} - - /// Runs what GLib's main context has ready: WPE's signals, replies and - /// frames. - func dispatch() { - var budget = 1000 - while budget > 0, mainContextIteration(nil, 0) != 0 { - budget -= 1 - } - } - - /// A GError's domain, code and message. - func error(_ error: Pointer) -> GError { - let domain = quarkToString(error.load(as: UInt32.self)).map { String(cString: $0) } ?? "" - let code = error.load(fromByteOffset: 4, as: Int32.self) - let message = error.load(fromByteOffset: 8, as: UnsafePointer?.self).map { String(cString: $0) } ?? "" - return GError(domain: domain, code: code, message: message) - } - - /// Sends every page's remote loads to a proxy that refuses them: the - /// app has no `network` capability (`WebKit.md`, "Without network"). - func blockNetwork() { - guard let session = networkSessionGetDefault(), - let settings = networkProxySettingsNew(WPE.refusingProxy, nil) else { return } - networkSessionSetProxySettings(session, WPE.proxyModeCustom, settings) - networkProxySettingsFree(settings) - } - - /// A proxy on a host that never resolves (`.invalid`, RFC 2606), so - /// nothing can answer for it. - static let refusingProxy = "http://no-network.invalid:8080" -} - -/// A GError's fields. -struct GError: Equatable { - var domain: String - var code: Int32 - var message: String -} - -// MARK: - libwpe's input events - -/// `struct wpe_input_pointer_event`. The event structs are laid out as -/// libwpe's, and passed to it by address. -struct PointerEvent { - /// `wpe_input_pointer_event_type`: 1 motion, 2 button. - var type: UInt32 - var time: UInt32 - var x: Int32 - var y: Int32 - var button: UInt32 - var state: UInt32 - var modifiers: UInt32 -} - -/// `struct wpe_input_axis_event`. -struct AxisEvent { - /// `wpe_input_axis_event_type`: 1 motion. - var type: UInt32 - var time: UInt32 - var x: Int32 - var y: Int32 - /// 0 vertical, 1 horizontal. - var axis: UInt32 - var value: Int32 - var modifiers: UInt32 -} - -/// `struct wpe_input_keyboard_event`. -struct KeyboardEvent { - var time: UInt32 - /// An XKB keysym. - var keyCode: UInt32 - var hardwareKeyCode: UInt32 - var pressed: Bool - var modifiers: UInt32 -} - -/// `wpe_input_modifier`. -enum WPEModifier { - static let control: UInt32 = 1 << 0 - static let shift: UInt32 = 1 << 1 - static let alt: UInt32 = 1 << 2 - static let meta: UInt32 = 1 << 3 - static let button1: UInt32 = 1 << 20 -} diff --git a/Tests/LinuxUITests/RenderingTests.swift b/Tests/LinuxUITests/RenderingTests.swift index da4204b..fb86b7b 100644 --- a/Tests/LinuxUITests/RenderingTests.swift +++ b/Tests/LinuxUITests/RenderingTests.swift @@ -3,6 +3,10 @@ import DynamicUI @testable import Cacao import Testing @testable import LinuxUI +#if os(Linux) +import DynamicWebKit +import LinuxWebKit +#endif /// Hosts `RendererView` in a Cacao view graph and lays it out, for every /// node type and modifier kind. Adapted from DarwinAppRuntime's @@ -229,6 +233,39 @@ struct RenderingTests { } } + #if os(Linux) + /// A page's delegate that hears nothing it needs. + final class QuietPage: WebContentDelegate { + func shouldNavigate(_ content: WebContent, url: String, kind: Int32, isMainFrame: Bool) -> Bool { true } + func didChangeURL(_ content: WebContent, url: String?) { } + func didChangeTitle(_ content: WebContent, title: String) { } + func didChangeLoading(_ content: WebContent, isLoading: Bool, progress: Double) { } + func didChangeHistory(_ content: WebContent, canGoBack: Bool, canGoForward: Bool) { } + func didFinishNavigation(_ content: WebContent) { } + func didFailNavigation(_ content: WebContent, error: Int32, message: String) { } + func didEvaluateJavaScript(_ content: WebContent, request: Int32, result: String?, error: String?) { } + } + + /// A `WebView` node shows the page it names, attached while it's + /// there, and the page stays when it goes. + @Test(.enabled(if: LinuxWebKit.isAvailable, "WPE WebKit isn't installed")) + func aWebViewNodeShowsItsPage() throws { + let page = LinuxWebContent.make(QuietPage()) + let content = try #require(page.content) + let (renderer, _) = makeRenderer() + let view = Self.host(renderer) + renderer.apply(RenderNode("WebView", id: 1, props: ["page": .int(Int(page.identifier()))], + modifiers: [ModifierNode("frame", ["width": 200.0, "height": 100.0])])) + Self.layOut(view) + #expect(content.isAttached) + #expect(content.size?.width == 200 && content.size?.height == 100) + renderer.apply(RenderNode("Text", id: 2, props: ["text": "Gone"])) + Self.layOut(view) + #expect(!content.isAttached) + #expect(LinuxWebContent.page(identifier: page.identifier()) === page) + } + #endif + @Test func emptyRendererShowsNothing() { let (renderer, _) = makeRenderer() let view = Self.host(renderer) diff --git a/Tests/LinuxWebKitTests/WebContentTests.swift b/Tests/LinuxWebKitTests/WebContentTests.swift index 1e248af..7e830b6 100644 --- a/Tests/LinuxWebKitTests/WebContentTests.swift +++ b/Tests/LinuxWebKitTests/WebContentTests.swift @@ -2,6 +2,7 @@ import DynamicWebKit import Foundation import LinuxHost import Testing +import WPEWebKit @testable import LinuxWebKit /// Records what a page tells its delegate, and answers `shouldNavigate`. @@ -101,7 +102,7 @@ func wait(_ seconds: Double = 20, until condition: () -> Bool) -> Bool { if Date() > deadline { return false } - WPE.shared?.dispatch() + WPEEngine.dispatch() usleep(5_000) } return true @@ -111,7 +112,7 @@ func wait(_ seconds: Double = 20, until condition: () -> Bool) -> Bool { @Suite(.serialized) struct WebContentTests { static var hasWPE: Bool { - (try? WebThread.shared.run { WPE.shared != nil }) ?? false + (try? WebThread.shared.run { WPEEngine.isAvailable }) ?? false } // MARK: Without WPE @@ -126,32 +127,8 @@ func wait(_ seconds: Double = 20, until condition: () -> Bool) -> Bool { #expect(LinuxWebContent.scheme(of: "/path:with/colon") == nil) } - @Test func errors() { - #expect(LinuxWebContent.errorCode(GError(domain: "WebKitNetworkError", code: 302, message: "")) == nil) - #expect(LinuxWebContent.errorCode(GError(domain: "WebKitPolicyError", code: 102, message: "")) == nil) - #expect(LinuxWebContent.errorCode(GError(domain: "WebKitNetworkError", code: 300, message: "")) == .network) - #expect(LinuxWebContent.errorCode(GError(domain: "WebKitNetworkError", code: 303, message: "")) == .badURL) - #expect(LinuxWebContent.errorCode(GError(domain: "g-resolver-error-quark", code: 1, message: "")) == .network) - #expect(LinuxWebContent.errorCode(GError(domain: "g-io-error-quark", code: 24, message: "")) == .timedOut) - #expect(LinuxWebContent.errorCode(GError(domain: "g-io-error-quark", code: 39, message: "")) == .network) - #expect(LinuxWebContent.errorCode(GError(domain: "g-tls-error-quark", code: 3, message: "")) == .security) - #expect(LinuxWebContent.errorCode(GError(domain: "other", code: 1, message: "")) == .unknown) - } - @Test func navigationKinds() { - #expect(LinuxWebContent.navigationKind(0) == .linkActivated) - #expect(LinuxWebContent.navigationKind(1) == .formSubmitted) - #expect(LinuxWebContent.navigationKind(4) == .formSubmitted) - #expect(LinuxWebContent.navigationKind(2) == .backForward) - #expect(LinuxWebContent.navigationKind(3) == .reload) - #expect(LinuxWebContent.navigationKind(5) == .other) - } - @Test func pixelsTurnRGBA() { - let bgra: [UInt8] = [10, 20, 30, 255, 1, 2, 3, 4, 99, 99, 99, 99] - let data = bgra.withUnsafeBytes { LinuxWebContent.rgba(fromBGRA: $0.baseAddress!, width: 2, height: 1, stride: 12) } - #expect(Array(data) == [30, 20, 10, 255, 3, 2, 1, 4]) - } @Test func resourcesStayInTheBundle() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent("web-resources-\(UUID())") @@ -304,60 +281,30 @@ func wait(_ seconds: Double = 20, until condition: () -> Bool) -> Bool { } } - @Test(.enabled(if: WebContentTests.hasWPE)) func drawsFramesAndTakesInput() throws { + @Test(.enabled(if: WebContentTests.hasWPE)) func aWebViewFindsThePageItsNodeNames() throws { try WebThread.shared.run { let delegate = RecordingDelegate() - let page = LinuxWebContent.make(delegate) - var frame: WebFrame? - page.display = { frame = $0 } - page.attach(width: 160, height: 120, scale: 1) - page.loadHTML(""" - Start - - - - """, baseURL: nil) - // The background, below the button, once drawn: #22aa66. - let offset = (100 * 160 + 140) * 4 + var page: LinuxWebContent? = LinuxWebContent.make(delegate) + let id = try #require(page?.identifier()) + #expect(LinuxWebContent.page(identifier: id) === page) + #expect(LinuxWebContent.page(identifier: id + 1000) == nil) + let content = try #require(page?.content) + // As the view attaches it: frames come at its size. + content.attach(width: 160, height: 120, scale: 1) + page?.loadHTML("", baseURL: nil) + #expect(wait { delegate.finished && content.surface.pixelSize == CGSize(width: 160, height: 120) }) + // Premultiplied BGRA, rows top to bottom: #22aa66 below and right. func green() -> Bool { - guard let frame, frame.data.count == 160 * 120 * 4 else { return false } - return Array(frame.data[offset...size == 28) - #expect(MemoryLayout.size == 28) - #expect(MemoryLayout.stride == 20) - #expect(MemoryLayout.offset(of: \.pressed) == 12) - #expect(MemoryLayout.offset(of: \.modifiers) == 16) -}