diff --git a/Documentation/Plan.md b/Documentation/Plan.md index 75ca96a..833a9e5 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -320,6 +320,15 @@ host adds: - **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. +- **Scripts and schemes an app talks to its pages with** (`features()` + says `userScripts`, `scriptMessages`, `messageReplies` and `urlSchemes`) + are `WPEWebContent`'s: user scripts in its `WebKitUserContentManager`, + message handlers with and without replies, and schemes registered once + per process, from `make(_:dataStore:options:schemes:)`; one WebKit + loads itself, such as `https`, is left to it and logged. Replies and + requests are numbered for the guest. WPE doesn't say when a page stops + wanting a request, so `stopURLSchemeTask` isn't sent. Releasing the page + rejects the replies it owes and fails its requests. - **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 diff --git a/Sources/LinuxWebKit/LinuxWebContent.swift b/Sources/LinuxWebKit/LinuxWebContent.swift index 4180017..980a8f2 100644 --- a/Sources/LinuxWebKit/LinuxWebContent.swift +++ b/Sources/LinuxWebKit/LinuxWebContent.swift @@ -8,7 +8,9 @@ import WPEWebKit /// /// The page loads whether or not it's shown. The player's `WebView` view /// shows `content` with CacaoWebKit's `WebView(content:)`, which attaches it -/// while it's on screen and forwards its input. Main thread only. +/// while it's on screen and forwards its input. It runs the app's user +/// scripts, passes on its script messages and their replies, and its URL +/// schemes' requests. Main thread only. public final class LinuxWebContent: WebContent { public let delegate: any WebContentDelegate @@ -22,6 +24,16 @@ public final class LinuxWebContent: WebContent { /// What the engine's page reports to, passed on to `delegate`. private let relay: Relay + /// Replies the page awaits, by the number the guest has for each. + private var replies: [Int32: WPEScriptMessageReply] = [:] + + private var nextReply: Int32 = 1 + + /// Requests in the app's schemes not yet answered, likewise. + private var tasks: [Int32: WPEURLSchemeTask] = [:] + + private var nextTask: Int32 = 1 + private init(delegate: any WebContentDelegate, id: Int32) { self.delegate = delegate self.id = id @@ -29,7 +41,22 @@ public final class LinuxWebContent: WebContent { relay = Relay() content = WPEWebContent(delegate: relay) relay.page = self - if content != nil { + if let content { + content.onScriptMessage = { [weak self] name, body in + self?.received(name, body, reply: nil) + } + content.onScriptMessageWithReply = { [weak self] name, body, reply in + guard let self else { + return reply.returnError("the page went away") + } + self.received(name, body, reply: reply) + } + content.onURLSchemeRequest = { [weak self] task in + guard let self else { + return task.fail(.cancelled, message: "the page went away") + } + self.start(task) + } // The engine watches what the new page waits for from here on. LinuxWebKit.pump() } @@ -37,6 +64,12 @@ public final class LinuxWebContent: WebContent { deinit { Self.pages[id] = nil + for reply in replies.values { + reply.returnError("the page went away") + } + for task in tasks.values { + task.fail(.cancelled, message: "the page went away") + } } // MARK: WebContent @@ -48,6 +81,25 @@ public final class LinuxWebContent: WebContent { return page } + /// What this host does beyond loading a page: what an app talks to its + /// pages with. None of a browser's or a mail reader's features yet. + public static func features() -> Int32 { + guard LinuxWebKit.isAvailable else { return 0 } + return WebFeatures([.userScripts, .scriptMessages, .messageReplies, .urlSchemes]).rawValue + } + + /// The default store and no options, as `features()` offers no others, + /// answering `schemes`. A scheme WebKit loads itself is left to it. + public static func make(_ delegate: any WebContentDelegate, dataStore: Int32, options: Int32, schemes: [String]) -> LinuxWebContent { + let page = make(delegate) + if let content = page.content { + for scheme in schemes where !content.registerURLScheme(scheme) { + HostLog.warning("web: \(scheme) can't be an app's scheme") + } + } + return page + } + public func identifier() -> Int32 { id } @@ -116,6 +168,65 @@ public final class LinuxWebContent: WebContent { LinuxWebKit.pump() } + // MARK: Scripts and schemes + + public func addUserScript(_ source: String, atDocumentStart: Bool, mainFrameOnly: Bool) { + content?.addUserScript(source, atDocumentStart: atDocumentStart, mainFrameOnly: mainFrameOnly) + } + + public func removeAllUserScripts() { + content?.removeAllUserScripts() + } + + public func addMessageHandler(_ name: String, replies: Bool) { + content?.addScriptMessageHandler(name, replies: replies) + } + + public func removeMessageHandler(_ name: String) { + content?.removeScriptMessageHandler(name) + } + + public func replyToMessage(_ reply: Int32, result: String?, error: String?) { + guard let pending = replies.removeValue(forKey: reply) else { return } + if let error { + pending.returnError(error) + } else { + pending.returnValue(json: result) + } + LinuxWebKit.pump() + } + + public func finishURLSchemeTask(_ task: Int32, status: Int32, contentType: String?, headers: [String], body: [UInt8]) { + guard let pending = tasks.removeValue(forKey: task) else { return } + let pairs = stride(from: 0, to: headers.count - 1, by: 2).map { (name: headers[$0], value: headers[$0 + 1]) } + pending.finish(status: Int(status), contentType: contentType, headers: pairs, body: body) + LinuxWebKit.pump() + } + + public func failURLSchemeTask(_ task: Int32, error: Int32, message: String) { + guard let pending = tasks.removeValue(forKey: task) else { return } + pending.fail(WPEWebContent.ErrorCode(rawValue: error) ?? .unknown, message: message) + LinuxWebKit.pump() + } + + private func received(_ name: String, _ body: String?, reply: WPEScriptMessageReply?) { + var number: Int32 = 0 + if let reply { + number = nextReply + nextReply = nextReply == .max ? 1 : nextReply + 1 + replies[number] = reply + } + delegate.didReceiveMessage(self, name: name, body: body, reply: number) + } + + private func start(_ task: WPEURLSchemeTask) { + let number = nextTask + nextTask = nextTask == .max ? 1 : nextTask + 1 + tasks[number] = task + delegate.startURLSchemeTask(self, task: number, url: task.url, method: task.method, + headers: task.headers.flatMap { [$0.name, $0.value] }, body: task.body) + } + private func unavailable() { delegate.didFailNavigation(self, error: WebError.Code.unknown.rawValue, message: Self.notInstalled) } diff --git a/Tests/LinuxWebKitTests/WebContentTests.swift b/Tests/LinuxWebKitTests/WebContentTests.swift index 7e830b6..548f099 100644 --- a/Tests/LinuxWebKitTests/WebContentTests.swift +++ b/Tests/LinuxWebKitTests/WebContentTests.swift @@ -47,6 +47,22 @@ final class RecordingDelegate: WebContentDelegate { scripts[request] = (result, error) } + /// Answers each message that waits for a reply, by its number. + var onMessage: ((_ content: WebContent, _ name: String, _ body: String?, _ reply: Int32) -> Void)? + + /// Answers each request in the app's schemes. + var onTask: ((_ content: WebContent, _ task: Int32, _ url: String, _ method: String, _ headers: [String], _ body: [UInt8]?) -> Void)? + + func didReceiveMessage(_ content: WebContent, name: String, body: String?, reply: Int32) { + events.append("message \(name) \(body ?? "undefined")\(reply == 0 ? "" : " reply")") + onMessage?(content, name, body, reply) + } + + func startURLSchemeTask(_ content: WebContent, task: Int32, url: String, method: String, headers: [String], body: [UInt8]?) { + events.append("task \(task) \(method) \(url)") + onTask?(content, task, url, method, headers, body) + } + var finished: Bool { events.contains("finish") } var title: String? { @@ -306,5 +322,87 @@ func wait(_ seconds: Double = 20, until condition: () -> Bool) -> Bool { #expect(LinuxWebContent.page(identifier: id) == nil) } } -} + // MARK: Scripts and schemes + + @Test(.enabled(if: WebContentTests.hasWPE)) func saysWhatItDoes() throws { + let features = WebFeatures(rawValue: try WebThread.shared.run { LinuxWebContent.features() }) + #expect(features == [.userScripts, .scriptMessages, .messageReplies, .urlSchemes]) + } + + @Test(.enabled(if: WebContentTests.hasWPE)) func runsUserScriptsAndPassesOnMessages() throws { + try WebThread.shared.run { + let delegate = RecordingDelegate() + delegate.onMessage = { content, name, body, reply in + guard reply != 0 else { return } + if body == "0" { + content.replyToMessage(reply, result: nil, error: "no zeros") + } else { + content.replyToMessage(reply, result: #"{"echo":\#(body ?? "null")}"#, error: nil) + } + } + let page = LinuxWebContent.make(delegate, dataStore: 0, options: 0, schemes: []) + page.addUserScript("window.webkit.messageHandlers.note.postMessage({ early: true })", atDocumentStart: true, mainFrameOnly: true) + page.addMessageHandler("note", replies: false) + page.addMessageHandler("ask", replies: true) + page.loadHTML(""" + + """, baseURL: "https://example.invalid/") + #expect(wait { delegate.title == #"{"echo":5} | rejected no zeros"# }, "\(delegate.events)") + #expect(delegate.events.contains(#"message note {"early":true}"#), "the user script ran before the page's own") + #expect(delegate.events.contains("message ask 5 reply")) + + // Answering again, or a number never given, does nothing. + page.replyToMessage(1, result: "1", error: nil) + page.replyToMessage(99, result: "1", error: nil) + + page.removeMessageHandler("ask") + page.removeAllUserScripts() + delegate.events.removeAll() + page.loadHTML("", baseURL: nil) + #expect(wait { delegate.finished && delegate.title == "true" }) + #expect(!delegate.events.contains { $0.hasPrefix("message") }, "no user script, no handler") + withExtendedLifetime(page) { } + } + } + + @Test(.enabled(if: WebContentTests.hasWPE)) func servesAPageFromAnAppScheme() throws { + try WebThread.shared.run { + let delegate = RecordingDelegate() + delegate.onTask = { content, task, url, method, headers, body in + switch url { + case "test-linux-app:/index.html": + content.finishURLSchemeTask(task, status: 200, contentType: "text/html", headers: [], + body: Array("