Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Documentation/Plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
115 changes: 113 additions & 2 deletions Sources/LinuxWebKit/LinuxWebContent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,21 +24,52 @@ 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
LinuxWebKit.prepare()
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()
}
}

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
Expand All @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down
100 changes: 99 additions & 1 deletion Tests/LinuxWebKitTests/WebContentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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? {
Expand Down Expand Up @@ -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("""
<script>
const ask = (n) => window.webkit.messageHandlers.ask.postMessage(n)
.then(v => JSON.stringify(v), e => 'rejected ' + e.message);
Promise.all([ask(5), ask(0)]).then(r => { document.title = r.join(' | '); });
</script>
""", 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("<script>document.title = String(window.webkit.messageHandlers.ask === undefined)</script>", 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("<title>App</title><script>fetch('test-linux-app:/data', { method: 'POST', body: 'hi' }).then(r => r.text().then(t => { document.title = r.status + ' ' + r.headers.get('x-answer') + ' ' + t; }))</script>".utf8))
case "test-linux-app:/data":
#expect(method == "POST")
#expect(body == Array("hi".utf8))
content.finishURLSchemeTask(task, status: 201, contentType: "text/plain",
headers: ["X-Answer", "yes", "Access-Control-Allow-Origin", "*", "Access-Control-Expose-Headers", "X-Answer"],
body: Array("stored".utf8))
default:
content.failURLSchemeTask(task, error: WebError.Code.notPermitted.rawValue, message: "not for you")
}
}
let page = LinuxWebContent.make(delegate, dataStore: 0, options: 0, schemes: ["Test-Linux-App", "https"])
page.load("test-linux-app:/index.html")
#expect(wait { delegate.title == "201 yes stored" }, "\(delegate.events)")
#expect(delegate.events.contains("url test-linux-app:/index.html"))
#expect(delegate.events.contains("task 1 GET test-linux-app:/index.html"))
#expect(delegate.events.contains("task 2 POST test-linux-app:/data"))

delegate.events.removeAll()
page.load("test-linux-app:/forbidden")
#expect(wait { delegate.events.contains { $0.hasPrefix("fail") } }, "\(delegate.events)")
#expect(delegate.events.contains("fail \(WebError.Code.notPermitted.rawValue)"))
// A task answered already, or never asked, is let be.
page.finishURLSchemeTask(1, status: 200, contentType: nil, headers: [], body: [])
page.failURLSchemeTask(99, error: 0, message: "")
withExtendedLifetime(page) { }
}
}
}
Loading